text
stringlengths
20
812k
id
stringlengths
40
40
metadata
dict
from __future__ import unicode_literals from abc import ABCMeta, abstractmethod from django.conf import settings from pydoc import locate _ACTIVE_BACKEND = None def get_backend(): """ Gets the active backend for this casepro instance """ global _ACTIVE_BACKEND if not _ACTIVE_BACKEND: _ACTIVE_BACKEND = locate(settings.SITE_BACKEND)() return _ACTIVE_BACKEND class BaseBackend(object): __metaclass__ = ABCMeta @abstractmethod def pull_contacts(self, org, modified_after, modified_before, progress_callback=None): """ Pulls contacts modified in the given time window :param org: the org :param datetime modified_after: pull contacts modified after this :param datetime modified_before: pull contacts modified before this :param progress_callback: callable that will be called from time to time with number of contacts pulled :return: tuple of the number of contacts created, updated, deleted and ignored """ pass @abstractmethod def pull_fields(self, org): """ Pulls all contact fields :param org: the org :return: tuple of the number of fields created, updated, deleted and ignored """ pass @abstractmethod def pull_groups(self, org): """ Pulls all contact groups :param org: the org :return: tuple of the number of groups created, updated, deleted and ignored """ pass @abstractmethod def pull_labels(self, org): """ Pulls all message labels :param org: the org :return: tuple of the number of labels created, updated, deleted and ignored """ pass @abstractmethod def pull_messages(self, org, modified_after, modified_before, as_handled=False, progress_callback=None): """ Pulls messages modified in the given time window :param org: the org :param datetime modified_after: pull messages modified after this :param datetime modified_before: pull messages modified before this :param bool as_handled: whether messages should be saved as already handled :param progress_callback: callable that will be called from time to time with number of messages pulled :return: tuple of the number of messages created, updated, deleted and ignored """ pass @abstractmethod def create_label(self, org, name): """ Creates a label (or returns an existing label) with the given name :param org: the org :param name: the name, e.g. "Spam" :return: the backend label UUID """ pass @abstractmethod def create_outgoing(self, org, text, contacts, urns): """ Creates an outgoing broadcast message :param org: the org :param text: the message text :param contacts: the contact recipients :param urns: the raw URN recipients :return: tuple of the broadcast id and it's timestamp """ pass @abstractmethod def add_to_group(self, org, contact, group): """ Adds the given contact to a group :param org: the org :param contact: the contact :param group: the group """ pass @abstractmethod def remove_from_group(self, org, contact, group): """ Removes the given contact from a group :param org: the org :param contact: the contact :param group: the group """ pass @abstractmethod def stop_runs(self, org, contact): """ Stops any ongoing flow runs for the given contact :param org: the org :param contact: the contact """ pass @abstractmethod def label_messages(self, org, messages, label): """ Adds a label to the given messages :param org: the org :param messages: the messages :param label: the label """ pass @abstractmethod def unlabel_messages(self, org, messages, label): """ Removes a label from the given messages :param org: the org :param messages: the messages :param label: the label """ pass @abstractmethod def archive_messages(self, org, messages): """ Archives the given messages :param org: the org :param messages: the messages """ pass @abstractmethod def archive_contact_messages(self, org, contact): """ Archives all messages for the given contact :param org: the org :param contact: the contact """ pass @abstractmethod def restore_messages(self, org, messages): """ Restores (un-archives) the given messages :param org: the org :param messages: the messages """ pass @abstractmethod def flag_messages(self, org, messages): """ Flags the given messages :param org: the org :param messages: the messages """ pass @abstractmethod def unflag_messages(self, org, messages): """ Un-flags the given messages :param org: the org :param messages: the messages """ pass @abstractmethod def fetch_contact_messages(self, org, contact, created_after, created_before): """ Fetches a contact's incoming and outgoing messages to display on a case timeline :param org: the org :param contact: the contact :param created_after: include messages created after this time :param created_before: include messages created before this time :return: the messages as JSON objects in reverse chronological order """ pass
a0b9828a83c576dca6732cbbceabbbf4a553a1f3
{ "blob_id": "a0b9828a83c576dca6732cbbceabbbf4a553a1f3", "branch_name": "refs/heads/master", "committer_date": "2016-03-10T10:55:40", "content_id": "0f2cca360a02ab3d6b116befd77a5be1b81f7a42", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "d05fa3feec04c19dad98479a136629039e3bc321", "extension": "py", "filename": "__init__.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5917, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/casepro/backend/__init__.py", "provenance": "stack-edu-0064.json.gz:614011", "repo_name": "digideskio/casepro", "revision_date": "2016-03-10T10:55:40", "revision_id": "54ad1fb58300c86ae07344b2094681106d34b146", "snapshot_id": "dc3f028ad8a6f49c01cff2dc56bf7c2ce92166c9", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/digideskio/casepro/54ad1fb58300c86ae07344b2094681106d34b146/casepro/backend/__init__.py", "visit_date": "2020-05-29T11:02:58.368483", "added": "2024-11-18T21:33:36.916313+00:00", "created": "2016-03-10T10:55:40", "int_score": 2, "score": 2.375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0082.json.gz" }
package com.inspur.viz.user.controller; import java.util.Map; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.session.Session; import org.apache.shiro.subject.Subject; import org.loushang.framework.base.RestResult; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class LoginController { @PostMapping("/login") public RestResult<String> doLogin(@RequestBody Map<String, String> userMap) { String username = userMap.get("username"); String pwd = userMap.get("password"); Subject subject = SecurityUtils.getSubject(); Session session = subject.getSession(); String sessionId = session.getId().toString(); System.out.println("sessionId: " + sessionId); UsernamePasswordToken token = new UsernamePasswordToken(username, pwd); return new RestResult<String>(); } }
4f5ea9b8c7ed0c194cace84d2441ec3caf3c6255
{ "blob_id": "4f5ea9b8c7ed0c194cace84d2441ec3caf3c6255", "branch_name": "refs/heads/master", "committer_date": "2018-09-19T06:00:59", "content_id": "c4104e99f0ce053282d73dcbbce920c718bbebac", "detected_licenses": [ "Apache-2.0" ], "directory_id": "216996cdb08bb1bb98fe0a9d9e586ce85200c112", "extension": "java", "filename": "LoginController.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1039, "license": "Apache-2.0", "license_type": "permissive", "path": "/backend/src/main/java/com/inspur/viz/user/controller/LoginController.java", "provenance": "stack-edu-0020.json.gz:863073", "repo_name": "VivienZhai/vue-demo", "revision_date": "2018-09-19T06:00:59", "revision_id": "c5e5613ef172f82a6412d028c6e9b998d5a1a261", "snapshot_id": "2c9a02b0edfeae213ef2f254ca4125bbe2c72b3e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/VivienZhai/vue-demo/c5e5613ef172f82a6412d028c6e9b998d5a1a261/backend/src/main/java/com/inspur/viz/user/controller/LoginController.java", "visit_date": "2020-03-29T01:40:11.806200", "added": "2024-11-19T03:10:58.131262+00:00", "created": "2018-09-19T06:00:59", "int_score": 2, "score": 2.109375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0038.json.gz" }
var assert = require('assert'); var exec = require('child_process').exec; exports.rand = function () { var to = setTimeout(function () { assert.fail('never executed'); }, 5000); var cmd = 'node -e \'console.log(require(' + JSON.stringify(__dirname + '/../') + ').rand(1000).toString())\'' ; exec(cmd, function (err1, r1) { exec(cmd, function (err2, r2) { clearTimeout(to); assert.ok(!err1); assert.ok(!err2); assert.ok( r1.match(/^\d+\n/), JSON.stringify(r1) + ' is not an integer' ); assert.ok( r2.match(/^\d+\n/), JSON.stringify(r2) + ' is not an integer' ); var n1 = parseInt(r1.split('\n')[0], 10); var n2 = parseInt(r2.split('\n')[0], 10); assert.ok(n1 >= 0, 'n1 >= 0'); assert.ok(n2 >= 0, 'n2 >= 0'); assert.ok(n1 < 1000, 'n1 < 1000'); assert.ok(n2 < 1000, 'n2 < 1000'); assert.ok(n1 != n2, 'n1 != n2'); }) }); }
f8fe6fe41ba5f8e1e0efa360097499843cb51ebf
{ "blob_id": "f8fe6fe41ba5f8e1e0efa360097499843cb51ebf", "branch_name": "refs/heads/master", "committer_date": "2012-03-21T22:34:28", "content_id": "bf780f5c43880b64e537880c9a3fcb50e4ce0c00", "detected_licenses": [ "MIT" ], "directory_id": "d956cbdea533123f2afedbba709ceddb293d5623", "extension": "js", "filename": "seed.js", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 2252860, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1186, "license": "MIT", "license_type": "permissive", "path": "/node_modules/bigint/test/seed.js", "provenance": "stack-edu-0043.json.gz:27237", "repo_name": "ifwe/node-kafka", "revision_date": "2012-03-21T22:34:28", "revision_id": "3f28579010685ea6fbbb42e8d151134fea93a827", "snapshot_id": "c9767f50f47355010fb6c3af4558586730a232bb", "src_encoding": "UTF-8", "star_events_count": 10, "url": "https://raw.githubusercontent.com/ifwe/node-kafka/3f28579010685ea6fbbb42e8d151134fea93a827/node_modules/bigint/test/seed.js", "visit_date": "2021-01-18T09:32:38.932533", "added": "2024-11-19T00:49:28.335109+00:00", "created": "2012-03-21T22:34:28", "int_score": 3, "score": 2.6875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0061.json.gz" }
var React = require('react'); var BulletPoint = require('./BulletPoint.react'); var HomeImage = require('./HomeImage.react'); var OnThisDay = React.createClass({ // propTypes: { // wikiData: React.PropTypes.string // }, getDate: function () { var d = new Date(); var month = new Array(); month[0] = 'January'; month[1] = 'February'; month[2] = 'March'; month[3] = 'April'; month[4] = 'May'; month[5] = 'June'; month[6] = 'July'; month[7] = 'August'; month[8] = 'September'; month[9] = 'October'; month[10] = 'November'; month[11] = 'December'; var n = month[d.getMonth()]; var day = d.getDate(); return n + ' ' + day; }, render: function () { var text = this.props.text; var links = this.props.link; var picture = this.props.picture; return ( <div> <h4>On This Day</h4> <div className="homeSectionContent"> <HomeImage picture={picture}/> {this.getDate()} <ul> {text.map(function(point, i) { return (//<li key={'point' + i}>{point}</li> <div key={'point' + i}> <BulletPoint blurb={point} link={links[i]} /> </div> ) })} </ul> </div> </div> ); } }); module.exports = OnThisDay;
a98e23fe59c0ae67f785103478c4ac04eeebf00a
{ "blob_id": "a98e23fe59c0ae67f785103478c4ac04eeebf00a", "branch_name": "refs/heads/master", "committer_date": "2015-11-12T20:07:12", "content_id": "e1f9c07b7e8dceb10772235b51d9c667eba7ec80", "detected_licenses": [ "MIT" ], "directory_id": "eae9f159bac47e3710ccfd336638c63b8c4235b2", "extension": "js", "filename": "OnThisDay.react.js", "fork_events_count": 5, "gha_created_at": "2015-10-15T18:07:33", "gha_event_created_at": "2015-11-12T20:07:13", "gha_language": "JavaScript", "gha_license_id": null, "github_id": 44336081, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1406, "license": "MIT", "license_type": "permissive", "path": "/client/app/components/home/OnThisDay.react.js", "provenance": "stack-edu-0039.json.gz:640837", "repo_name": "MischievousBoys/WikiPoetry", "revision_date": "2015-11-12T20:07:12", "revision_id": "224beb22c95e454f800c5785ac06b4262e196512", "snapshot_id": "28b6138df842ba01997d79125a521574a178e800", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/MischievousBoys/WikiPoetry/224beb22c95e454f800c5785ac06b4262e196512/client/app/components/home/OnThisDay.react.js", "visit_date": "2016-08-12T16:53:46.309540", "added": "2024-11-19T01:11:07.520987+00:00", "created": "2015-11-12T20:07:12", "int_score": 2, "score": 2.328125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0057.json.gz" }
#include<iostream> using namespace std; int main() { int limit, no1 = 0, no2 = 1; cout<<"Enter the number of terms :- "; cin>>limit; cout<<"Fibonacci series upto "<<limit<<" elements is :- "<<endl; if(limit == 0) return 0; else { cout<<no1<<"\t"; for(int i = 0; i < limit - 1; i++) { no2 = no1 + no2; no1 = no2 - no1; cout<<no1<<"\t"; } } return 0; }
26a408ee7eb9d1ec693bfdd4c4d208759b305048
{ "blob_id": "26a408ee7eb9d1ec693bfdd4c4d208759b305048", "branch_name": "refs/heads/master", "committer_date": "2021-03-31T11:08:59", "content_id": "b087d52193e1eb2f78c1d271a0d072f712b2d3d2", "detected_licenses": [ "Apache-2.0" ], "directory_id": "0272b58d843a01bee4b61a71eaaba6b8444b7929", "extension": "cpp", "filename": "fibo.cpp", "fork_events_count": 0, "gha_created_at": "2020-10-09T17:45:45", "gha_event_created_at": "2021-03-31T11:09:00", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 302713943, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 474, "license": "Apache-2.0", "license_type": "permissive", "path": "/Mathematics/fibo.cpp", "provenance": "stack-edu-0009.json.gz:10689", "repo_name": "mebsahle/data-structure-and-algorithms", "revision_date": "2021-03-31T11:08:59", "revision_id": "ac0abb69232b195ba90a4d001670757aa887d959", "snapshot_id": "4c63c6b02c1517b145c8e327ac8cbee66774ec7f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mebsahle/data-structure-and-algorithms/ac0abb69232b195ba90a4d001670757aa887d959/Mathematics/fibo.cpp", "visit_date": "2023-03-26T02:04:23.401722", "added": "2024-11-18T21:42:16.982834+00:00", "created": "2021-03-31T11:08:59", "int_score": 3, "score": 3.015625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0027.json.gz" }
// A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value. // Given the root to a binary tree, count the number of unival subtrees. // For example, the following tree has 5 unival subtrees: // 0 // / \ // 1 0 // / \ // 1 0 // / \ // 1 1 // Example // const unique_ptr<Node> node_tree ( // new Node(0, // new Node(1), // new Node(0, // new Node(1, // new Node(1), // new Node(1)), // new Node(0)))); // // auto result = problem_eight(node_tree.get(), node_tree->value); #include <memory> using namespace std; struct Node { const int value; const Node* const child_left, *child_right; Node(const int value, const Node* const child_left = nullptr, const Node* const child_right = nullptr) :value(value), child_left(child_left), child_right(child_right) {} constexpr bool is_leaf() const { return this->child_left == nullptr && this->child_right == nullptr; } constexpr bool is_value_equal(const Node* const node) const { return !node || node->value == this->value; } ~Node() { delete this->child_left; delete this->child_right; } }; int problem_eight(const Node* const node, int value) { if (node == nullptr) return 0; if (node->is_leaf()) return 1; const auto leaf_count = problem_eight(node->child_left, node->value) + problem_eight(node->child_right, node->value); return node->is_value_equal(node->child_left) && node->is_value_equal(node->child_right) ? leaf_count + 1 : leaf_count; }
b208ff16928577d637836cf0926d776ade3f5270
{ "blob_id": "b208ff16928577d637836cf0926d776ade3f5270", "branch_name": "refs/heads/master", "committer_date": "2020-03-17T19:09:12", "content_id": "9ff7aa0458945f5707396618636335da4231b38d", "detected_licenses": [ "Apache-2.0" ], "directory_id": "d890454e18e12b119d6611f03fb52aaccbbdc076", "extension": "cpp", "filename": "problem_8.cpp", "fork_events_count": 0, "gha_created_at": "2020-03-02T19:27:27", "gha_event_created_at": "2020-03-17T19:09:13", "gha_language": "C++", "gha_license_id": "Apache-2.0", "github_id": 244456679, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1574, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/problem_8.cpp", "provenance": "stack-edu-0006.json.gz:282978", "repo_name": "MihailsKuzmins/daily-coding-problem", "revision_date": "2020-03-17T19:09:12", "revision_id": "ca8b7589b6ce2eb6dec846829c82a12c1272a5ec", "snapshot_id": "d182bc62f3eb0db80d098fa04ea3189df66fd6ec", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/MihailsKuzmins/daily-coding-problem/ca8b7589b6ce2eb6dec846829c82a12c1272a5ec/src/problem_8.cpp", "visit_date": "2021-02-11T04:59:03.927701", "added": "2024-11-18T23:26:06.925334+00:00", "created": "2020-03-17T19:09:12", "int_score": 3, "score": 3.3125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0024.json.gz" }
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Validator; use App\Http\Requests; use App\Historia; use App\HistoriaClinica; use App\Movimiento; use App\Seguimiento; use App\Convenio; use App\Cita; use App\Departamento; use App\Provincia; use App\Distrito; use App\Person; use App\Plan; use App\Detallehistoriacie; use App\Examenhistoriaclinica; use App\Rolpersona; use App\Librerias\Libreria; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\DB; use Elibyy\TCPDF\Facades\TCPDF; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Session; ini_set('memory_limit', '512M'); //Raise to 512 MB ini_set('max_execution_time', '60000'); //Raise to 512 MB class HistoriaController extends Controller { protected $folderview = 'app.historia'; protected $tituloAdmin = 'Historia'; protected $tituloRegistrar = 'Registrar historia'; protected $tituloModificar = 'Modificar historia'; protected $tituloEliminar = 'Eliminar historia'; protected $rutas = array('create' => 'historia.create', 'edit' => 'historia.edit', 'delete' => 'historia.eliminar', 'search' => 'historia.buscar', 'buscaProv' => 'historia.buscaProv', 'buscaDist' => 'historia.buscaDist', 'index' => 'historia.index', 'fallecido' => 'historia.fallecido', ); public function __construct() { $this->middleware('auth'); } public function buscar(Request $request) { $sucursal_id = Session::get('sucursal_id'); $pagina = $request->input('page'); $filas = $request->input('filas'); $entidad = 'Historia'; $nombre = Libreria::getParam($request->input('nombre'),''); $dni = Libreria::getParam($request->input('dni')); $numero = Libreria::getParam($request->input('numero')); $numero2 = Libreria::getParam($request->input('numero2')); $tipopaciente = Libreria::getParam($request->input('tipopaciente')); $resultado = Historia::join('person', 'person.id', '=', 'historia.person_id') ->leftjoin('convenio', 'convenio.id', '=', 'historia.convenio_id') //->where('historia.sucursal_id', '=', $sucursal_id) ->where(DB::raw('concat(apellidopaterno,\' \',apellidomaterno,\' \',nombres)'), 'LIKE', '%'.strtoupper($nombre).'%') ->where('person.dni', 'LIKE', '%'.strtoupper($dni).'%'); if($tipopaciente!=""){ $resultado = $resultado->where('historia.tipopaciente', 'LIKE', ''.strtoupper($tipopaciente).''); } if($numero!=""){ $resultado = $resultado->where('historia.numero', 'LIKE', '%'.strtoupper($numero).'%'); } if($numero2!=""){ $resultado = $resultado->where('historia.numero2', 'LIKE', '%'.strtoupper($numero2).'%'); } $resultado = $resultado->select('historia.*')->orderBy('historia.numero', 'ASC'); $vistamedico = $request->input('vistamedico'); if($vistamedico != "SI"){ $resultado = $resultado->limit(100); } $lista = $resultado->get(); $cabecera = array(); $cabecera[] = array('valor' => '#', 'numero' => '1'); $cabecera[] = array('valor' => 'Nro Historia', 'numero' => '1'); $cabecera[] = array('valor' => 'Nro Historia2', 'numero' => '1'); $cabecera[] = array('valor' => 'Paciente', 'numero' => '1'); $cabecera[] = array('valor' => 'DNI', 'numero' => '1'); $cabecera[] = array('valor' => 'Tipo Paciente', 'numero' => '1'); $cabecera[] = array('valor' => 'Telefono', 'numero' => '1'); //$cabecera[] = array('valor' => 'Fecha Nacimiento', 'numero' => '1'); $cabecera[] = array('valor' => 'Direccion', 'numero' => '1'); if($vistamedico != "SI"){ $cabecera[] = array('valor' => 'Operaciones', 'numero' => '7'); }else{ $cabecera[] = array('valor' => 'Ver Citas', 'numero' => '1'); } $titulo_modificar = $this->tituloModificar; $titulo_eliminar = $this->tituloEliminar; $ruta = $this->rutas; $user = Auth::user(); if (count($lista) > 0) { $clsLibreria = new Libreria(); $paramPaginacion = $clsLibreria->generarPaginacion($lista, $pagina, $filas, $entidad); $paginacion = $paramPaginacion['cadenapaginacion']; $inicio = $paramPaginacion['inicio']; $fin = $paramPaginacion['fin']; $paginaactual = $paramPaginacion['nuevapagina']; $lista = $resultado->paginate($filas); $request->replace(array('page' => $paginaactual)); return view($this->folderview.'.list')->with(compact('lista', 'paginacion', 'inicio', 'vistamedico' ,'fin', 'entidad', 'cabecera', 'titulo_modificar', 'titulo_eliminar', 'ruta', 'user')); } return view($this->folderview.'.list')->with(compact('lista', 'entidad')); } public function index() { $entidad = 'Historia'; $title = $this->tituloAdmin; $titulo_registrar = $this->tituloRegistrar; $ruta = $this->rutas; $cboTipoPaciente = array("" => "Todos","Particular" => "Particular", "Convenio" => "Convenio", "Hospital" => "Hospital"); return view($this->folderview.'.admin')->with(compact('entidad', 'title', 'titulo_registrar', 'ruta', 'cboTipoPaciente')); } public function create(Request $request) { $listar = Libreria::getParam($request->input('listar'), 'NO'); $modo = $request->input('modo',''); $entidad = 'Historia'; $historia = null; $cboConvenio = array(); $cboDepa = array('---- Elija uno ----'); $convenios = Convenio::where(DB::raw('1'),'=','1')->orderBy('nombre','ASC')->get(); foreach ($convenios as $key => $value) { $cboConvenio = $cboConvenio + array($value->id => $value->nombre); } $departamentos = Departamento::orderBy('nombre','ASC')->get(); foreach ($departamentos as $key => $value) { $cboDepa = $cboDepa + array($value->id => $value->nombre); } $cboEstadoCivil = array("SOLTERO(A)"=>"SOLTERO(A)","CASADO(A)"=>"CASADO(A)","VIUDO(A)"=>"VIUDO(A)","DIVORCIADO(A)"=>"DIVORCIADO(A)","CONVIVIENTE"=>"CONVIVIENTE"); $cboSexo = array("M"=>"M","F"=>"F"); $cboCategoria = array("Normal"=>"Normal","Religioso"=>"Religioso","Doctor"=>"Doctor","Familiar Trabajador"=>"Familiar Trabajador","Aldeas Infantiles"=>"Aldeas Infantiles"); $formData = array('historia.store'); $cboTipoPaciente = array("Particular" => "Particular", "Convenio" => "Convenio", "Hospital" => "Hospital"); $cboModo = array("F" => "Fisico", "V" => "Registro Virtual"); $sucursal_id = Session::get('sucursal_id'); $num = Historia::NumeroSigue($sucursal_id); $user = Auth::user(); $formData = array('route' => $formData, 'class' => 'form-horizontal', 'id' => 'formMantenimiento'.$entidad, 'autocomplete' => 'off'); $boton = 'Registrar'; return view($this->folderview.'.mant')->with(compact('historia', 'formData', 'entidad', 'boton', 'listar', 'cboTipoPaciente', 'cboConvenio', 'cboEstadoCivil', 'modo', 'cboSexo', 'cboDepa', 'cboModo', 'num', 'user', 'cboCategoria')); } public function buscaProv($departamento) { $provincias = Provincia::where('departamento_id','=',$departamento)->orderBy('nombre','ASC')->get(); $cboProv = '<option value="0">---- Elija uno ----</option>'; foreach ($provincias as $key => $value) { $cboProv = $cboProv.'<option value="'.$value->id.'">'.$value->nombre.'</option>'; } echo $cboProv; } public function buscaDist($provincia) { $distritos = Distrito::where('provincia_id','=',$provincia)->orderBy('nombre','ASC')->get(); $cboDist = '<option value="0">---- Elija uno ----</option>'; foreach ($distritos as $key => $value) { $cboDist = $cboDist.'<option value="'.$value->id.'">'.$value->nombre.'</option>'; } echo $cboDist; } public function store(Request $request) { $listar = Libreria::getParam($request->input('listar'), 'NO'); $modo = $request->input('modo',''); $reglas = array( 'nombres' => 'required', 'apellidopaterno' => 'required', 'apellidomaterno' => 'required', 'telefono' => 'required', ); $mensajes = array( 'apellidopaterno.required' => 'Debe ingresar un apellido paterno', 'apellidomaterno.required' => 'Debe ingresar un apellido materno', 'nombres.required' => 'Debe ingresar un nombre', ); $validacion = Validator::make($request->all(), $reglas, $mensajes); if ($validacion->fails()) { return $validacion->messages()->toJson(); } $dni = $request->input('dni'); $mdlPerson = new Person(); $resultado = Person::where('dni','LIKE',$dni); $value = $resultado->first(); $sucursal_id = Session::get('sucursal_id'); if(count($value)>0 && strlen(trim($dni))>0){ $objHistoria = new Historia(); //$list2 = Historia::where('person_id','=',$value->id)->where('historia.sucursal_id','=',$sucursal_id)->first(); $list2 = Historia::where('person_id','=',$value->id)->first(); if(count($list2)>0){//SI TIENE HISTORIA return $dat[0]=array("respuesta"=>"Ya tiene historia"); }else{//NO TIENE HISTORIA PERO SI ESTA REGISTRADO LA PERSONA COMO PROVEEDOR O PERSONAL $idpersona=$value->id; } }else{ $idpersona=0; } $dat=array(); $user = Auth::user(); $error = DB::transaction(function() use($request,$idpersona,$user,&$dat){ $sucursal_id = Session::get('sucursal_id'); $Historia = new Historia(); if($idpersona==0){ $person = new Person(); $person->dni=$request->input('dni'); $person->apellidopaterno=trim(strtoupper($request->input('apellidopaterno'))); $person->apellidomaterno=trim(strtoupper($request->input('apellidomaterno'))); $person->nombres=trim(strtoupper($request->input('nombres'))); $person->telefono=$request->input('telefono'); $person->direccion=trim($request->input('direccion')); $person->telefono2=$request->input('telefono2'); $person->sexo=$request->input('sexo'); $person->email=$request->input('email'); if($request->input('fechanacimiento')!=""){ $person->fechanacimiento=$request->input('fechanacimiento'); } $person->save(); $idpersona=$person->id; }else{ $person = Person::find($idpersona); } $Historia->person_id = $idpersona; $Historia->tipopaciente=$request->input('tipopaciente'); $Historia->fecha=date("Y-m-d"); $Historia->enviadopor=$request->input('enviadopor'); $Historia->familiar=$request->input('familiar'); $Historia->modo=$request->input('modo'); $Historia->estadocivil=$request->input('estadocivil'); $Historia->ocupacion=$request->input('ocupacion'); $Historia->departamento=$request->input('departamento'); $Historia->provincia=$request->input('provincia'); $Historia->distrito=$request->input('distrito'); $Historia->categoria=$request->input('categoria'); $Historia->detallecategoria=$request->input('detallecategoria'); $Historia->usuario_id=$user->person_id; if($request->input('tipopaciente')=="Convenio"){ $Historia->convenio_id=$request->input('convenio'); $Historia->empresa=$request->input('empresa'); $Historia->carnet=$request->input('carnet'); $Historia->plan_susalud=$request->input('plan_susalud'); $Historia->poliza=$request->input('poliza'); $Historia->soat=$request->input('soat'); $Historia->titular=$request->input('titular'); } $Historia->numero = Historia::NumeroSigue($sucursal_id); //$Historia->sucursal_id = $sucursal_id; $Historia->save(); $RolPersona = new RolPersona(); $RolPersona->rol_id = 3; $RolPersona->person_id = $idpersona; $RolPersona->save(); $dat[0]=array("respuesta"=>"OK","id"=>$Historia->id,"paciente"=>$person->apellidopaterno.' '.$person->apellidomaterno.' '.$person->nombres,"historia"=>$Historia->numero,"person_id"=>$Historia->person_id,"tipopaciente"=>$Historia->tipopaciente); }); if($modo=="popup"){ return is_null($error) ? json_encode($dat) : $error; }else{ return is_null($error) ? json_encode($dat) : $error; } } public function show($id) { // } public function edit($id, Request $request) { $existe = Libreria::verificarExistencia($id, 'Historia'); if ($existe !== true) { return $existe; } $listar = Libreria::getParam($request->input('listar'), 'NO'); $modo = $request->input('modo',''); $historia = Historia::join('person','person.id','=','historia.person_id')->where('historia.id','=',$id)->select('historia.*')->select('person.*','historia.*')->first(); $entidad = 'Historia'; $cboConvenio = array(); $convenios = Convenio::where(DB::raw('1'),'=','1')->orderBy('nombre','ASC')->get(); foreach ($convenios as $key => $value) { $cboConvenio = $cboConvenio + array($value->id => $value->nombre); } $cboEstadoCivil = array("SOLTERO(A)"=>"SOLTERO(A)","CASADO(A)"=>"CASADO(A)","VIUDO(A)"=>"VIUDO(A)","DIVORCIADO(A)"=>"DIVORCIADO(A)","CONVIVIENTE"=>"CONVIVIENTE"); $cboCategoria = array("Normal"=>"Normal","Religioso"=>"Religioso","Doctor"=>"Doctor","Familiar Trabajador"=>"Familiar Trabajador","Aldeas Infantiles"=>"Aldeas Infantiles"); $cboSexo = array("M"=>"M","F"=>"F"); $cboModo = array("F" => "Fisico", "V" => "Registro Virtual"); $cboTipoPaciente = array("Particular" => "Particular", "Convenio" => "Convenio", "Hospital" => "Hospital"); $user = Auth::user(); $formData = array('historia.update', $id); $formData = array('route' => $formData, 'method' => 'PUT', 'class' => 'form-horizontal', 'id' => 'formMantenimiento'.$entidad, 'autocomplete' => 'off'); $boton = 'Modificar'; $cboDepa = array(); $departamentos = Departamento::orderBy('nombre','ASC')->get(); foreach ($departamentos as $key => $value) { $cboDepa = $cboDepa + array($value->id => $value->nombre); } return view($this->folderview.'.mant')->with(compact('historia', 'formData', 'entidad', 'boton', 'listar', 'cboConvenio', 'cboTipoPaciente', 'cboEstadoCivil', 'modo', 'cboSexo', 'cboDepa', 'cboModo', 'user', 'cboCategoria')); } public function update(Request $request, $id) { $sucursal_id = Session::get('sucursal_id'); $existe = Libreria::verificarExistencia($id, 'Historia'); if ($existe !== true) { return $existe; } $reglas = array( 'nombres' => 'required', 'apellidopaterno' => 'required', 'apellidomaterno' => 'required', 'telefono' => 'required', ); $mensajes = array( 'apellidopaterno.required' => 'Debe ingresar un apellido paterno', 'apellidomaterno.required' => 'Debe ingresar un apellido materno', 'nombres.required' => 'Debe ingresar un nombre', ); $validacion = Validator::make($request->all(), $reglas, $mensajes); if ($validacion->fails()) { return $validacion->messages()->toJson(); } $dni = $request->input('dni'); $mdlPerson = new Person(); $resultado = Person::where('dni','LIKE',$dni); $value = $resultado->first(); if(count($value)>0 && strlen(trim($dni))>0){ $objHistoria = new Historia(); $list2 = Historia::where('person_id','=',$value->id)->where('historia.sucursal_id', $sucursal_id)->where('id','<>',$id)->first(); if(count($list2)>0){//SI TIENE HISTORIA return "Ya tiene otra historia"; }else{//NO TIENE HISTORIA PERO SI ESTA REGISTRADO LA PERSONA COMO PROVEEDOR O PERSONAL $idpersona=$value->id; } }else{ $idpersona=0; } $error = DB::transaction(function() use($request, $id, $idpersona){ $sucursal_id = Session::get('sucursal_id'); $Historia = Historia::find($id); if($Historia->modo=="V" && $request->input('modo')=="F"){ $Historia->fechamodo=date("Y-m-d"); } if($idpersona==0){ $person = new Person(); $person->dni=$request->input('dni'); $person->apellidopaterno=trim(strtoupper($request->input('apellidopaterno'))); $person->apellidomaterno=trim(strtoupper($request->input('apellidomaterno'))); $person->nombres=trim(strtoupper($request->input('nombres'))); $person->telefono=$request->input('telefono'); $person->direccion=trim($request->input('direccion')); $person->nombres=$request->input('nombres'); $person->telefono2=$request->input('telefono2'); $person->sexo=$request->input('sexo'); $person->email=$request->input('email'); if($request->input('fechanacimiento')!=""){ $person->fechanacimiento=$request->input('fechanacimiento'); } $person->save(); $idpersona=$person->id; $list = Movimiento::where('persona_id','=',$Historia->person_id)->where('tipomovimiento_id','=',1)->get(); foreach ($list as $key => $value) { $value->persona_id=$idpersona; $value->save(); } }else{ $person = Person::find($idpersona); $person->dni=$request->input('dni'); $person->apellidopaterno=trim($request->input('apellidopaterno')); $person->apellidomaterno=trim($request->input('apellidomaterno')); $person->nombres=trim($request->input('nombres')); $person->telefono=$request->input('telefono'); $person->direccion=trim($request->input('direccion')); $person->telefono2=$request->input('telefono2'); $person->sexo=$request->input('sexo'); $person->email=$request->input('email'); if($request->input('fechanacimiento')!=""){ $person->fechanacimiento=$request->input('fechanacimiento'); } $person->save(); $idpersona=$person->id; } $Historia->person_id = $idpersona; $Historia->numero = $request->input('numero'); $Historia->tipopaciente=$request->input('tipopaciente'); //$Historia->fecha=date("Y-m-d"); $Historia->enviadopor=$request->input('enviadopor'); $Historia->familiar=$request->input('familiar'); $Historia->estadocivil=$request->input('estadocivil'); $Historia->modo=$request->input('modo'); $Historia->departamento=$request->input('departamento'); $Historia->provincia=$request->input('provincia'); $Historia->distrito=$request->input('distrito'); $Historia->categoria=$request->input('categoria'); $Historia->detallecategoria=$request->input('detallecategoria'); if($request->input('tipopaciente')=="Convenio"){ $Historia->convenio_id=$request->input('convenio'); $Historia->empresa=$request->input('empresa'); $Historia->carnet=$request->input('carnet'); $Historia->plan_susalud=$request->input('plan_susalud'); $Historia->poliza=$request->input('poliza'); $Historia->soat=$request->input('soat'); $Historia->titular=$request->input('titular'); } //$Historia->sucursal_id = $sucursal_id; $Historia->save(); }); $dat=array(); $dat[0]=array("respuesta"=>"OK"); return is_null($error) ? json_encode($dat) : $error; } public function destroy($id) { $existe = Libreria::verificarExistencia($id, 'Historia'); if ($existe !== true) { return $existe; } $error = DB::transaction(function() use($id){ $Historia = Historia::find($id); $Historia->delete(); }); return is_null($error) ? "OK" : $error; } public function eliminar($id, $listarLuego) { $existe = Libreria::verificarExistencia($id, 'Historia'); if ($existe !== true) { return $existe; } $listar = "NO"; if (!is_null(Libreria::obtenerParametro($listarLuego))) { $listar = $listarLuego; } $modelo = Historia::find($id); $entidad = 'Historia'; $formData = array('route' => array('historia.destroy', $id), 'method' => 'DELETE', 'class' => 'form-horizontal', 'id' => 'formMantenimiento'.$entidad, 'autocomplete' => 'off'); $boton = 'Eliminar'; return view('app.confirmarEliminar')->with(compact('modelo', 'formData', 'entidad', 'boton', 'listar')); } public function validarDNI(Request $request) { $dni = $request->input("dni"); $entidad = 'Person'; $mdlPerson = new Person(); $resultado = Person::where('dni','LIKE',$dni); $value = $resultado->first(); $sucursal_id = Session::get('sucursal_id'); if(count($value)>0){ $objHistoria = new Historia(); //$list2 = Historia::where('person_id','=',$value->id)->where('historia.sucursal_id','=',$sucursal_id)->first(); $list2 = Historia::where('person_id','=',$value->id)->first(); if(count($list2)>0){//SI TIENE HISTORIA $data[] = array( 'apellidopaterno' => $value->apellidopaterno, 'apellidomaterno' => $value->apellidomaterno, 'nombres' => $value->nombres, 'telefono' => $value->telefono, 'direccion' => $value->direccion, 'id' => $value->id, 'msg' => 'N', ); }else{//NO TIENE HISTORIA PERO SI ESTA REGISTRADO LA PERSONA COMO PROVEEDOR O PERSONAL $data[] = array( 'apellidopaterno' => $value->apellidopaterno, 'apellidomaterno' => $value->apellidomaterno, 'nombres' => $value->nombres, 'telefono' => $value->telefono, 'direccion' => $value->direccion, 'id' => $value->id, 'msg' => 'S', 'modo'=> 'Registrado', ); } }else{ $data[] = array('msg'=>'S','modo'=>'Nada'); } return json_encode($data); } public function personautocompletar($searching) { $entidad = 'Historia'; $sucursal_id = Session::get('sucursal_id'); $resultado = Historia::join('person', 'person.id', '=', 'historia.person_id') ->leftjoin('convenio', 'convenio.id', '=', 'historia.convenio_id') ->where(DB::raw('concat(person.dni,\' \',apellidopaterno,\' \',apellidomaterno,\' \',nombres)'), 'LIKE', '%'.strtoupper($searching).'%') //->where('historia.sucursal_id', '=', $sucursal_id) ->select('historia.*','convenio.nombre as convenio2','convenio.plan_id'); $list = $resultado->get(); $data = array(); foreach ($list as $key => $value) { if($value->plan_id){ $pl = Plan::find($value->plan_id); $plan=$pl->nombre; $coa=$pl->coaseguro; $deducible=$pl->deducible; $ruc=$pl->ruc; $direccion=$pl->direccion; $razonsocial=$pl->razonsocial; $tipo=$pl->tipo; }else{ $pl = Plan::find(6); $plan=$pl->nombre; $coa=$pl->coaseguro; $deducible=$pl->deducible; $ruc=$pl->ruc; $direccion=$pl->direccion; $razonsocial=$pl->razonsocial; $tipo=$pl->tipo; } $data[] = array( 'label' => $value->persona->dni.' '.$value->persona->apellidopaterno.' '.$value->persona->apellidomaterno.' '.$value->persona->nombres, 'id' => $value->id, 'value' => $value->persona->dni.' '.$value->persona->apellidopaterno.' '.$value->persona->apellidomaterno.' '.$value->persona->nombres, 'value2' => $value->persona->apellidopaterno.' '.$value->persona->apellidomaterno.' '.$value->persona->nombres, 'numero'=> $value->numero, 'person_id' => $value->persona->id, 'dni' => $value->persona->dni, 'tipopaciente' => $value->tipopaciente, 'telefono' => $value->persona->telefono, 'fallecido' => $value->fallecido, 'placa' => $value->poliza, 'convenio' => $value->convenio2, 'plan_id' => $pl->id, 'plan' => $plan, 'coa' => $coa, 'deducible' => $deducible, 'ruc' => $ruc, 'direccion' => $direccion, 'razonsocial' => $razonsocial, 'tipo' => $tipo, 'direccion2' => $value->persona->direccion, 'edad' => ($value->persona->fechanacimiento==""?'0':$value->persona->fechanacimiento), 'fecha' => date('Y-m-d'), ); } return json_encode($data); } public function historiaautocompletar($searching) { $entidad = 'Historia'; $sucursal_id = Session::get('sucursal_id'); $resultado = Historia::join('person', 'person.id', '=', 'historia.person_id') ->leftjoin('convenio', 'convenio.id', '=', 'historia.convenio_id') ->where('historia.numero', 'LIKE', '%'.strtoupper($searching).'%') ->whereNull('person.deleted_at') //->where('historia.sucursal_id', '=', $sucursal_id) ->select('historia.*','convenio.nombre as convenio2','convenio.plan_id'); $list = $resultado->get(); $data = array(); foreach ($list as $key => $value) { if($value->plan_id){ $pl = Plan::find($value->plan_id); $plan=$pl->nombre; $coa=$pl->coaseguro; $deducible=$pl->deducible; $ruc=$pl->ruc; $direccion=$pl->direccion; $razonsocial=$pl->razonsocial; $tipo=$pl->tipo; }else{ $plan=''; $coa=0; $deducible=0; $ruc=''; $direccion=''; $razonsocial=''; $tipo=''; } $data[] = array( 'label' => $value->persona->dni.' '.$value->persona->apellidopaterno.' '.$value->persona->apellidomaterno.' '.$value->persona->nombres, 'id' => $value->id, 'value' => $value->persona->dni.' '.$value->persona->apellidopaterno.' '.$value->persona->apellidomaterno.' '.$value->persona->nombres, 'value2' => $value->persona->apellidopaterno.' '.$value->persona->apellidomaterno.' '.$value->persona->nombres, 'numero'=> $value->numero, 'person_id' => $value->persona->id, 'dni' => $value->persona->dni, 'tipopaciente' => $value->tipopaciente, 'telefono' => $value->persona->telefono, 'fallecido' => $value->fallecido, 'placa' => $value->poliza, 'convenio' => $value->convenio2, 'plan_id' => $value->plan_id, 'plan' => $plan, 'coa' => $coa, 'deducible' => $deducible, 'ruc' => $ruc, 'direccion' => $direccion, 'razonsocial' => $razonsocial, 'tipo' => $tipo, 'direccion2' => $value->persona->direccion, 'edad' => ($value->persona->fechanacimiento==""?'0':$value->persona->fechanacimiento), 'fecha' => date('Y-m-d'), ); } return json_encode($data); } public function pdfSeguimiento(Request $request){ $resultado = Seguimiento::where('historia_id','=',$request->id)->orderBy('fechaenvio', 'ASC'); $lista = $resultado->get(); if (count($lista) > 0) { $historia = Historia::find($request->id); $pdf = new TCPDF(); $pdf::SetTitle('Seguimiento de Historia'); $pdf::AddPage(); $pdf::SetFont('helvetica','B',12); $pdf::Cell(0,10,utf8_decode("SEGUIMIENTO DE HISTORIA ".$historia->numero),0,0,'C'); $pdf::Ln(); $pdf::SetFont('helvetica','B',10); $pdf::Cell(20,9,utf8_decode("PACIENTE: "),0,0,'C'); $pdf::SetFont('helvetica','',10); $pdf::Cell(0,9,utf8_decode($historia->persona->apellidopaterno." ".$historia->persona->apellidomaterno." ".$historia->persona->nombres),0,0,'L'); $pdf::Ln(); $pdf::SetFont('helvetica','B',9); $pdf::Cell(20,6,utf8_decode("TIPO"),1,0,'C'); $pdf::Cell(30,6,utf8_decode("FECHA"),1,0,'C'); $pdf::Cell(40,6,utf8_decode("AREA"),1,0,'C'); $pdf::Cell(40,6,utf8_decode("USUARIO"),1,0,'C'); $pdf::Cell(60,6,utf8_decode("COMENTARIO"),1,0,'C'); $pdf::Ln(); foreach ($lista as $key => $value){ $pdf::SetFont('helvetica','',8); $pdf::Cell(20,5,utf8_decode("ENVIADO"),1,0,'C'); $pdf::Cell(30,5,utf8_decode($value->fechaenvio),1,0,'L'); $pdf::Cell(40,5,utf8_decode($value->areaenvio->nombre),1,0,'C'); $pdf::Cell(40,5,utf8_decode($value->personaenvio->apellidopaterno." ".$value->personaenvio->apellidomaterno." ".$value->personaenvio->nombres),1,0,'C'); $pdf::Cell(60,5,utf8_decode($value->comentario),1,0,'C'); $pdf::Ln(); if($value->fecharecepcion!=""){ if($value->situacion=="A"){ $pdf::Cell(20,5,utf8_decode("RECIBIDO"),1,0,'C'); }else{ $pdf::Cell(20,5,utf8_decode("RECHAZADO"),1,0,'C'); } $pdf::Cell(30,5,utf8_decode($value->fecharecepcion),1,0,'L'); $pdf::Cell(40,5,utf8_decode($value->areadestino->nombre),1,0,'C'); $pdf::Cell(40,5,utf8_decode($value->personarecepcion->apellidopaterno." ".$value->personarecepcion->apellidomaterno." ".$value->personarecepcion->nombres),1,0,'C'); $pdf::Cell(60,5,"",1,0,'C'); $pdf::Ln(); } } $pdf::Output('ListaCita.pdf'); } } public function pdfHistoria(Request $request){ $historia = Historia::find($request->id); if ($historia->departamento != 0) { $departamento = Departamento::find($historia->departamento); $provincia = Provincia::find($historia->provincia); $distrito = Distrito::find($historia->distrito); } else { $departamento = (object) array('nombre'=>'-'); $provincia = (object) array('nombre'=>'-'); $distrito = (object) array('nombre'=>'-'); } $pdf = new TCPDF(); $pdf::SetTitle('Historia'); $pdf::AddPage(); $pdf::Image("http://localhost:81/clinica/dist/img/logo2-ojos.jpg", 20, 7, 50, 15); $pdf::SetFont('helvetica','B',15); $pdf::Cell(60,10,"",0,0,'C'); $pdf::Cell(75,10,"",0,0,'C'); $pdf::SetFont('helvetica','B',18); $pdf::Cell(40,10,utf8_decode($historia->numero),1,0,'C'); $pdf::Ln(); $pdf::SetFont('helvetica','B',15); $pdf::Cell(60,10,strtoupper(""),0,0,'C'); $pdf::Cell(70,10,"",0,0,'C'); $pdf::Ln(); $pdf::Cell(60,6,"",0,0,'C'); $pdf::SetFont('helvetica','',14); $pdf::Cell(70,4,"----------------------------------------------------------",0,0,'C'); $pdf::Ln(); $pdf::SetFont('helvetica','B',14); $pdf::Cell(48,10,"",0,0,'C'); $pdf::Cell(95,10,utf8_decode("HISTORIA CLINICA"),'B',0,'C'); $pdf::Ln(); $pdf::Ln(); $pdf::Cell(40,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',9); $pdf::Cell(20,8,utf8_decode("FECHA: "),0,0,'L'); $pdf::SetFont('helvetica','',9); $pdf::Cell(20,8,date("d/m/Y",strtotime($historia->fecha)),0,0,'C'); $pdf::Cell(10,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',9); $pdf::Cell(20,8,utf8_decode("HORA: "),0,0,'C'); $pdf::SetFont('helvetica','',9); $pdf::Cell(20,8,date("H:i:s",strtotime($historia->created_at)),0,0,'C'); $pdf::Ln(); $pdf::Cell(40,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',9); $pdf::Cell(20,8,utf8_decode("PACIENTE: "),0,0,'L'); $pdf::SetFont('helvetica','',9); $pdf::Cell(60,8,($historia->persona->apellidopaterno." ".$historia->persona->apellidomaterno." ".$historia->persona->nombres),0,0,'L'); $pdf::Ln(); $pdf::Cell(40,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',9); $pdf::Cell(28,8,utf8_decode("TIPO PACIENTE: "),0,0,'L'); $pdf::SetFont('helvetica','',9); $pdf::Cell(20,8,strtoupper($historia->tipopaciente),0,0,'L'); $pdf::Ln(); $pdf::Cell(40,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',9); $pdf::Cell(20,8,utf8_decode("DNI: "),0,0,'L'); $pdf::SetFont('helvetica','',9); $pdf::Cell(20,8,utf8_decode($historia->persona->dni),0,0,'L'); $pdf::Cell(10,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',9); $pdf::Cell(20,8,utf8_decode("SEXO: "),0,0,'C'); $pdf::SetFont('helvetica','',9); $pdf::Cell(20,8,utf8_decode($historia->persona->sexo),0,0,'L'); $pdf::Ln(); $pdf::Cell(40,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',9); $pdf::Cell(20,8,utf8_decode("FECHA NAC:"),0,0,'L'); $pdf::SetFont('helvetica','',9); $pdf::Cell(20,8,date("d/m/Y",strtotime($historia->persona->fechanacimiento)),0,0,'L'); $pdf::Cell(10,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',9); $pdf::Cell(20,8,utf8_decode("EDAD: "),0,0,'C'); $pdf::SetFont('helvetica','',9); if($historia->persona->fechanacimiento!=''){ $pdf::Cell(20,8,date("Y-m-d") - date("Y-m-d",strtotime($historia->persona->fechanacimiento)),0,0,'L'); }else{ $pdf::Cell(20,8,'-',0,0,'L'); } $pdf::Ln(); $pdf::Cell(40,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',9); $pdf::Cell(20,8,utf8_decode("DOMICILIO:"),0,0,'L'); $pdf::SetFont('helvetica','',9); $pdf::Cell(20,8,utf8_encode($historia->persona->direccion),0,0,'L'); $pdf::Ln(); $pdf::Cell(40,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',9); $pdf::Cell(29,8,utf8_decode("DEPARTAMENTO:"),0,0,'L'); $pdf::SetFont('helvetica','',9); $pdf::Cell(20,8,utf8_decode($departamento->nombre),0,0,'L'); $pdf::Cell(5,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',9); $pdf::Cell(20,8,utf8_decode("PROVINCIA:"),0,0,'L'); $pdf::SetFont('helvetica','',9); if(!is_null($provincia)){ $pdf::Cell(20,8,utf8_decode($provincia->nombre),0,0,'L'); }else{ $pdf::Cell(20,8,utf8_decode(""),0,0,'L'); } $pdf::Cell(5,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',9); $pdf::Cell(16,8,utf8_decode("DISTRITO:"),0,0,'L'); $pdf::SetFont('helvetica','',9); if(!is_null($distrito)){ $pdf::Cell(20,8,utf8_decode($distrito->nombre),0,0,'L'); }else{ $pdf::Cell(20,8,utf8_decode(""),0,0,'L'); } $pdf::Ln(); $pdf::Cell(40,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',9); $pdf::Cell(20,8,utf8_decode("CATEGORIA: "),0,0,'L'); $pdf::SetFont('helvetica','',9); $pdf::Cell(25,8,utf8_decode($historia->categoria),0,0,'L'); $pdf::Cell(8,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',9); $pdf::Cell(20,8,utf8_decode("DETALLE: "),0,0,'C'); $pdf::SetFont('helvetica','',9); $pdf::Cell(20,8,utf8_decode($historia->detallecategoria),0,0,'L'); $pdf::Ln(); $pdf::Cell(40,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',9); $pdf::Cell(20,8,utf8_decode("TELEFONO: "),0,0,'L'); $pdf::SetFont('helvetica','',9); $pdf::Cell(20,8,utf8_decode($historia->persona->telefono .' - '.$historia->persona->telefono2),0,0,'L'); $pdf::Ln(); $pdf::Cell(40,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',9); $pdf::Cell(28,8,utf8_decode("ESTADO CIVIL: "),0,0,'L'); $pdf::SetFont('helvetica','',9); $pdf::Cell(20,8,utf8_decode($historia->estadocivil),0,0,'L'); $pdf::Ln(); $pdf::Cell(40,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',9); $pdf::Cell(20,8,utf8_decode("FAM. RESP: "),0,0,'L'); $pdf::SetFont('helvetica','',9); $pdf::Cell(20,8,utf8_decode($historia->familiar),0,0,'L'); $pdf::Ln(); $pdf::Cell(40,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',9); $pdf::Cell(20,8,utf8_decode("ENV. POR: "),0,0,'L'); $pdf::SetFont('helvetica','',9); $pdf::Cell(20,8,utf8_decode($historia->enviadopor),0,0,'L'); $pdf::Ln(); $pdf::Cell(40,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',9); $pdf::Cell(65,8,utf8_decode("OTROS DATOS DE LA HISTORIA:"),'B',0,'L'); $pdf::Ln(); $pdf::Cell(40,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',8); $pdf::Cell(20,8,utf8_decode("SOAT "),0,0,'L'); $pdf::SetFont('helvetica','',8); $pdf::Cell(20,8,utf8_decode($historia->soat),0,0,'L'); $pdf::Ln(); $pdf::Cell(40,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',8); $pdf::Cell(20,8,utf8_decode("TITULAR: "),0,0,'L'); $pdf::SetFont('helvetica','',8); $pdf::Cell(20,8,utf8_decode($historia->titular),0,0,'L'); $pdf::Ln(); if($historia->tipopaciente=='Convenio'){ $pdf::Cell(40,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',8); $pdf::Cell(20,8,utf8_decode("EMPRESA: "),0,0,'L'); $pdf::SetFont('helvetica','',8); if ($historia->convenio_id == NULL) { $pdf::Cell(20,8,utf8_decode($historia->empresa),0,0,'L'); } else { $pdf::Cell(20,8,utf8_decode($historia->convenio->nombre),0,0,'L'); //.' - '.$historia->empresa } $pdf::Ln(); }else{ $pdf::Cell(40,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',8); $pdf::Cell(20,8,utf8_decode("EMPRESA: "),0,0,'L'); $pdf::SetFont('helvetica','',8); $pdf::Cell(20,8,utf8_decode($historia->empresa),0,0,'L'); $pdf::Ln(); } $pdf::Cell(40,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',8); $pdf::Cell(20,8,utf8_decode("POLIZA: "),0,0,'L'); $pdf::SetFont('helvetica','',8); $pdf::Cell(20,8,utf8_decode($historia->poliza),0,0,'L'); $pdf::Ln(); $pdf::Cell(40,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',8); $pdf::Cell(20,8,utf8_decode("CARNET: "),0,0,'L'); $pdf::SetFont('helvetica','',8); $pdf::Cell(20,8,utf8_decode($historia->carnet),0,0,'L'); $pdf::Ln(); $pdf::Ln(); $pdf::SetFont('helvetica','',8); $pdf::Cell(40,8,"",0,0,'C'); $pdf::Cell(50,8,"IDENTIDAD MEDICINA - HISTORIAS CLINICA",0,0,'C'); $pdf::Cell(40,8,"",0,0,'C'); $pdf::Cell(15,8,"USUARIO:",0,0,'C'); $pdf::SetFont('helvetica','',8); if($historia->usuario_id>0){ $pdf::Cell(50,8,$historia->usuario->nombres,0,0,'L'); }else{ $pdf::Cell(50,8,"",0,0,'C'); } $pdf::Output('Historia.pdf'); } public function guardarfallecido(Request $request) { $error = DB::transaction(function() use($request){ $Historia = Historia::find($request->input('historia_id')); $Historia->fechafallecido = $request->input('fecha'); $Historia->fallecido='S'; $Historia->save(); }); return is_null($error) ? "OK" : $error; } public function fallecido($id, $listarLuego) { $existe = Libreria::verificarExistencia($id, 'Historia'); if ($existe !== true) { return $existe; } $listar = "NO"; if (!is_null(Libreria::obtenerParametro($listarLuego))) { $listar = $listarLuego; } $modelo = Historia::find($id); $entidad = 'Historia'; $paciente = $modelo->persona->apellidopaterno." ".$modelo->persona->apellidomaterno." ".$modelo->persona->nombres; $numero = $modelo->numero; $formData = array('route' => array('historia.guardarfallecido', $id), 'method' => 'Acept', 'class' => 'form-horizontal', 'id' => 'formMantenimiento'.$entidad, 'autocomplete' => 'off'); $boton = 'Fallecido'; return view($this->folderview.'.fallecido')->with(compact('modelo', 'formData', 'entidad', 'boton', 'listar', 'numero', 'paciente')); } public function pdfHistoria2(Request $request){ $citas = HistoriaClinica::where('historia_id', $request->input('id'))->get(); $historia = Historia::find($request->id); $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false); $pdf::SetTitle('Historial de Citas'); // remove default header/footer $pdf::setPrintHeader(false); $pdf::setPrintFooter(false); // set default monospaced font $pdf::SetDefaultMonospacedFont(PDF_FONT_MONOSPACED); // set margins $pdf::SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT); // set auto page breaks $pdf::SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM); // set image scale factor $pdf::setImageScale(PDF_IMAGE_SCALE_RATIO); $pdf::AddPage(); $pdf::Image("http://localhost:81/clinica/dist/img/logo2-ojos.jpg", 20, 26, 50, 15); $pdf::SetFont('helvetica','B',15); $pdf::Cell(60,10,"",0,0,'C'); $pdf::Cell(75,10,"",0,0,'C'); $pdf::SetFont('helvetica','B',10); $pdf::Cell(40,10,utf8_decode('Historia '.$historia->numero),1,0,'C'); $pdf::Ln(); $pdf::SetFont('helvetica','B',15); $pdf::Cell(60,10,strtoupper(""),0,0,'C'); $pdf::Cell(70,10,"",0,0,'C'); $pdf::Cell(60,6,"",0,0,'C'); $o = 0; foreach ($citas as $cita) { //Solo los antecedentes anteriores del paciente :v if($o == 0) { $pdf::Ln(4); $pdf::SetFont('helvetica','B',14); $pdf::Cell(48,10,"",0,0,'C'); $pdf::Cell(95,10,'ANTECEDENTES ANTERIORES','B',0,'C'); $pdf::Ln(4); $pdf::Ln(4); $pdf::Ln(4); $pdf::Ln(4); $pdf::Cell(8,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',9); $pdf::Cell(35,8,utf8_decode("PACIENTE: "),0,0,'L'); $pdf::SetFont('helvetica','',9); $pdf::Multicell(120,8,($historia->persona->apellidopaterno." ".$historia->persona->apellidomaterno." ".$historia->persona->nombres),0,'L'); $pdf::Ln(2); $pdf::Ln(3); $pdf::Ln(3); $pdf::SetFont('helvetica','',9); $pdf::Cell(8,8,"",0,0,'C'); $pdf::Multicell(165,8,($historia->antecedentes2),0,'L'); $pdf::Ln(2); $pdf::Ln(3); $pdf::Ln(3); } // $pdf::Ln(4); $pdf::SetFont('helvetica','B',14); $pdf::Cell(48,10,"",0,0,'C'); $pdf::Cell(95,10,'Cita N° ' . $cita->numero . ' / ' . date('d-m-Y',strtotime($cita->fecha_atencion)),'B',0,'C'); $pdf::Ln(4); $pdf::Ln(4); $pdf::Ln(4); $pdf::Ln(4); $pdf::Cell(8,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',9); $pdf::Cell(35,8,utf8_decode("PACIENTE: "),0,0,'L'); $pdf::SetFont('helvetica','',9); $pdf::Multicell(120,8,($historia->persona->apellidopaterno." ".$historia->persona->apellidomaterno." ".$historia->persona->nombres),0,'L'); $pdf::Ln(2); $pdf::Ln(3); $pdf::Ln(3); $pdf::Cell(8,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',9); $pdf::Cell(35,8,utf8_decode("CIE 10: "),0,0,'L'); $pdf::SetFont('helvetica','',9); $cadenacies = ''; if($cita->cie_id != 0 || $cita->cie_id != '') { $cadenacies .= $cita->cie->codigo . ' ' . $cita->cie->descripcion . '<br>'; } $cies = Detallehistoriacie::where('historiaclinica_id', $cita->id)->whereNull('deleted_at')->get(); if(count($cies) != 0){ foreach ($cies as $value) { $cadenacies .= $value->cie->codigo . ' ' . $value->cie->descripcion .'<br>'; } } $cies2 = explode('<BR>', strtoupper($cadenacies)); if($cies2[0] == ''){ $cies2[] = '-'; } $i = 0; foreach($cies2 as $c) { if($c != '') { if($i != 0) { $pdf::Cell(8,8,"",0,0,'C'); $pdf::Cell(35,8,"",0,0,'L'); } $pdf::Multicell(120,8,$c==''?'-':$c,0,'L'); $pdf::Ln(3); $i++; } } $pdf::Ln(3); $pdf::Ln(3); $pdf::Cell(8,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',9); $pdf::Cell(35,8,utf8_decode("MOTIVO: "),0,0,'L'); $pdf::SetFont('helvetica','',9); $mot = explode('<BR>', strtoupper($cita->motivo)); if($mot[0] == ''){ $mot[] = '-'; } $i = 0; foreach($mot as $m) { if($m != '') { if($i != 0) { $pdf::Cell(8,8,"",0,0,'C'); $pdf::Cell(35,8,"",0,0,'L'); } $pdf::Multicell(120,8,$m==''?'-':$m,0,'L'); $pdf::Ln(3); $i++; } } $pdf::Ln(3); $pdf::Ln(3); $pdf::Cell(8,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',9); $pdf::Cell(35,8,"DIAGNÓSTICO: ",0,0,'L'); $pdf::SetFont('helvetica','',9); $diag = explode('<BR>', strtoupper($cita->diagnostico)); if($diag[0] == ''){ $diag[] = '-'; } $i = 0; foreach($diag as $d) { if($d != '') { if($i != 0) { $pdf::Cell(8,8,"",0,0,'C'); $pdf::Cell(35,8,"",0,0,'L'); } $pdf::Multicell(120,8,$d,0,'L'); $pdf::Ln(3); $i++; } } $pdf::Ln(3); $pdf::Ln(3); $pdf::Cell(8,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',9); $pdf::Cell(35,8,"TRATAMIENTO: ",0,0,'L'); $pdf::SetFont('helvetica','',9); $trat = explode('<BR>', strtoupper($cita->tratamiento)); if($trat[0] == ''){ $trat[] = '-'; } $i = 0; foreach($trat as $t) { if($t != '') { if($i != 0) { $pdf::Cell(8,8,"",0,0,'C'); $pdf::Cell(35,8,"",0,0,'L'); } $pdf::Multicell(120,8,$t,0,'L'); $pdf::Ln(3); $i++; } } $pdf::Ln(3); $pdf::Ln(3); $pdf::Cell(8,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',9); $pdf::Cell(35,8,"EXÁMENES: ",0,0,'L'); $pdf::SetFont('helvetica','',9); $cadenaexamenes = ''; $examenes = Examenhistoriaclinica::where('historiaclinica_id', $cita->id)->whereNull('deleted_at')->get(); if(count($examenes) != 0){ foreach ($examenes as $value) { $cadenaexamenes .= $value->servicio->nombre .'<br>'; } } $examenes2 = explode('<BR>', strtoupper($cadenaexamenes)); if($examenes2[0] == ''){ $examenes2[] = '-'; } $i = 0; foreach($examenes2 as $e) { if($e != '') { if($i != 0) { $pdf::Cell(8,8,"",0,0,'C'); $pdf::Cell(35,8,"",0,0,'L'); } $pdf::Multicell(120,8,$e,0,'L'); $pdf::Ln(3); $i++; } } $pdf::Ln(3); $pdf::Ln(3); $pdf::Cell(8,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',9); $pdf::Cell(35,8,"EXPLOR. FÍSICA: ",0,0,'L'); $pdf::SetFont('helvetica','',9); $exf = explode('<BR>', strtoupper($cita->exploracion_fisica)); if($exf[0] == ''){ $exf[] = '-'; } $i = 0; foreach($exf as $ef) { if($ef != '') { if($i != 0) { $pdf::Cell(8,8,"",0,0,'C'); $pdf::Cell(35,8,"",0,0,'L'); } $pdf::Multicell(120,8,$ef,0,'L'); $pdf::Ln(3); $i++; } } $pdf::Ln(3); $pdf::Ln(3); $pdf::Cell(8,8,"",0,0,'C'); $pdf::SetFont('helvetica','B',9); $pdf::Cell(35,8,"COMENTARIO: ",0,0,'L'); $pdf::SetFont('helvetica','',9); $pdf::Multicell(120,8,$cita->comentario== null ?'-':$cita->comentario,0,'L'); $o++; } $pdf::Output('HistorialCitas.pdf'); } public function unirHistorias(Request $request) { /*$historias = Person::select('h1.id as i1', 'h2.id as i2', 'h1.numero as n1', 'h1.sucursal_id as s1', 'h2.numero as n2', 'h2.sucursal_id as s2', 'h1.person_id as p1', 'h2.person_id as p2', 'person.id') ->leftjoin('historia as h1', 'h1.person_id', '=', 'person.id') ->leftjoin('historia as h2', 'h2.person_id', '=', 'person.id') ->where('h1.sucursal_id', '=', 1) ->where('h2.sucursal_id', '=', 2) ->whereRaw('h1.person_id = h2.person_id') ->orderBy('h1.numero') ->orderBy('h2.numero') ->get();*/ /*select `h1`.`numero` as `n1`, `h1`.`sucursal_id` as `s1`, `h2`.`numero` as `n2`, `h2`.`sucursal_id` as `s2`, `h1`.`person_id` as `p1`, `h2`.`person_id` as `p2`, `person`.`id` from `person` inner join `historia` as `h1` on `h1`.`person_id` = `person`.`id` inner join `historia` as `h2` on `h2`.`person_id` = `person`.`id` where `person`.`deleted_at` is null and `h1`.`person_id` = h2.person_id and h1.sucursal_id = 1 and h2.sucursal_id = 2 order by `h1`.`numero` asc, `h2`.`numero` asc*/ /*$mensaje = ''; foreach ($historias as $value) { //Eliminar la Historia con sucursal_id = 1, rescatar su numero de historia //Pasar ese id a id_alternativo y buscar historiasclinicas, actualizar la referencia con el nuevo id } echo $mensaje;*/ $personas = Person::select('id')->get(); foreach ($personas as $value) { $historia1 = Historia::where('person_id', '=', $value->id)->where('sucursal_id', '=', 1)->first(); $historia2 = Historia::where('person_id', '=', $value->id)->where('sucursal_id', '=', 2)->first(); //Solo si hay dos historias (ojos y esp) if($historia1 !== NULL && $historia2 !== NULL) { //busco las historiasclinicas que tienen id de historia de ojos $historiasclinicas = HistoriaClinica::where('historia_id', '=', $historia1->id)->get(); if(count($historiasclinicas) > 0) { foreach ($historiasclinicas as $hc) { //Actualizo la historia_id a la de la sucursal 2 (esp) $hc->historia_id = $historia2->id; $hc->save(); } } //busco las citas que tienen id de historia de ojos $citas = Cita::where('historia_id', '=', $historia1->id)->get(); if(count($citas) > 0) { foreach ($citas as $cita) { //Actualizo la historia_id a la de la sucursal 2 (esp) $cita->historia_id = $historia2->id; $cita->save(); } } //Elimino sucursal en Historia2 //$historia2->sucursal_id=null; //$historia2->save(); //Elimino historia con sucursal 1 $historia1->delete(); } } //Reestructurar números de historia $historias = Historia::select('historia.id')->orderBy(DB::raw('CONCAT(apellidopaterno, " ", apellidomaterno, " ", nombres)'), 'ASC') ->join('person as p', 'p.id', '=', 'historia.person_id') ->get(); $i = 1; foreach ($historias as $history) { $historia = Historia::find($history->id); $numero2 = $historia->numero; $numero1 = str_pad($i,8,'0',STR_PAD_LEFT); if($historia->sucursal_id == 1) { $historia->numero2 = NULL; } else { $historia->numero2 = $numero2; } $historia->sucursal_id = NULL; $historia->numero = $numero1; $historia->save(); echo $historia->sucursal_id; $i++; } } //Eliminar Historias Clinicas con número = 0 public function unirHistorias2(Request $request) { $historiasclinicas = HistoriaClinica::where('numero', '=', '0')->get(); foreach ($historiasclinicas as $hc) { $hc->delete(); } echo count($historiasclinicas) . ' HISTORIAS CLÍNICAS ELIMINADAS'; } }
be3125e5d0842c4c993a533dfb7b280a2e9da643
{ "blob_id": "be3125e5d0842c4c993a533dfb7b280a2e9da643", "branch_name": "refs/heads/master", "committer_date": "2019-09-23T05:03:24", "content_id": "18912b729d29b03c13400e84de7cd7ef14bbe29a", "detected_licenses": [ "MIT" ], "directory_id": "f3805d01572f5d4301ee18e812225a5843aa9ca0", "extension": "php", "filename": "HistoriaController.php", "fork_events_count": 2, "gha_created_at": "2018-11-13T16:45:12", "gha_event_created_at": "2019-12-02T20:03:24", "gha_language": "PHP", "gha_license_id": null, "github_id": 157413497, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 58661, "license": "MIT", "license_type": "permissive", "path": "/app/Http/Controllers/HistoriaController.php", "provenance": "stack-edu-0052.json.gz:187692", "repo_name": "alexander03/sisclinica", "revision_date": "2019-09-23T05:03:24", "revision_id": "a325643878e3a069654610bd5e179963f5b05796", "snapshot_id": "a4f4b18e5e81b57f8ff5ba322a8d372ba2e42869", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/alexander03/sisclinica/a325643878e3a069654610bd5e179963f5b05796/app/Http/Controllers/HistoriaController.php", "visit_date": "2020-04-06T11:21:09.358565", "added": "2024-11-19T01:34:27.153200+00:00", "created": "2019-09-23T05:03:24", "int_score": 2, "score": 2.078125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0070.json.gz" }
###Blog Topics - Quick look at Angular Grids - Best directives to help build your Angular application - Best 3rd party libraries that can help build your Angular application - Restangular, Lodash, Moment, etc - No jQuery - How to be a successful web developer - Make sure you have a passion for it. - Develop on your own, find applications to write - Learn, learn, learn - Always admit that you have more to learn - Be organized - Be a team player - Customer focus - Seek to help the client uncover their true needs. Sometimes they do not need an automated solution, sometimes something manual will do just fine. Often times they are so close to the situation they cannot step back and see the full picture. We are all like that including myself. As analytical people, developers can often ask the right questions because we need to know all the details in order to build a system (computers are not that smart). Ask the why questions before the how and what questions. - Under promise and over deliver. Seek to impress with words and sales-speak, but instead impress with attitude, honesty, actions and invaluable service. You are after a long term relationship after all and that is built on trust and serving others. You cannot promise something until you understand all the details, and you will never understand all the details until you are complete.
1deac7395664685a00b9f651beb593669c88b5fc
{ "blob_id": "1deac7395664685a00b9f651beb593669c88b5fc", "branch_name": "refs/heads/master", "committer_date": "2015-07-27T17:05:49", "content_id": "a80cd1e854d47e78530b86d7745a9260bc8f6312", "detected_licenses": [ "MIT" ], "directory_id": "777c8ec32301129667f70981dc7aebb224c5336b", "extension": "md", "filename": "blog-topics.md", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 24469834, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1383, "license": "MIT", "license_type": "permissive", "path": "/_drafts/blog-topics.md", "provenance": "stack-edu-markdown-0014.json.gz:304207", "repo_name": "bengwall/bengwall.github.io", "revision_date": "2015-07-27T17:05:49", "revision_id": "20faeb0abfd5391c660a946fcf053814f3fd7043", "snapshot_id": "e9d53ce3c6e408586dd36bc3efe667d2a7b3214a", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/bengwall/bengwall.github.io/20faeb0abfd5391c660a946fcf053814f3fd7043/_drafts/blog-topics.md", "visit_date": "2016-09-06T11:44:48.585722", "added": "2024-11-18T22:02:41.984693+00:00", "created": "2015-07-27T17:05:49", "int_score": 2, "score": 2.125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0014.json.gz" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Exam2 { class Program { static void Main(string[] args) { string sentance = ""; int count = 0; //int[] pNum; //List<string> pName; //for dynamic names //pName = new List<string>(); //pNum = Enumerable.Range(1, 100).ToArray(); while (sentance != "Worm Ipsum") { //foreach (int num in pNum) //pName.Add(Console.ReadLine()); //use dynamic variables Console.ReadLine(); return; } Console.WriteLine("This is a random eeeeeeee."); Console.WriteLine("This is another random eeeeeeee."); Console.WriteLine("You have dddddddddd aaaa."); Console.WriteLine(""); } } }
a7724a3694409d77501c9bc37a696f6488742722
{ "blob_id": "a7724a3694409d77501c9bc37a696f6488742722", "branch_name": "refs/heads/master", "committer_date": "2017-05-13T05:48:23", "content_id": "5ff9adbbdd22c03741d7de3c6c0bc02cbdff57e9", "detected_licenses": [ "MIT" ], "directory_id": "7f5a8ab4e866e0b00d4c2129e15aa47147d0cc37", "extension": "cs", "filename": "Program.cs", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 79628120, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 989, "license": "MIT", "license_type": "permissive", "path": "/DataTypes/Methods/Exam2/Exam2/Program.cs", "provenance": "stack-edu-0013.json.gz:231628", "repo_name": "Nahalius/testo", "revision_date": "2017-05-13T05:48:23", "revision_id": "692962e0b4b782c1ad0fcb432ef6646307686fba", "snapshot_id": "1c162eb3d414b8c23812fdc840be28ca211e7582", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Nahalius/testo/692962e0b4b782c1ad0fcb432ef6646307686fba/DataTypes/Methods/Exam2/Exam2/Program.cs", "visit_date": "2021-01-11T18:47:49.760638", "added": "2024-11-18T21:35:50.795178+00:00", "created": "2017-05-13T05:48:23", "int_score": 3, "score": 3.234375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0031.json.gz" }
package academy.dd.artemis.date; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; public class DateTimeCalculator { private final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); private final Calendar calendar = Calendar.getInstance(); private Day day; private String calculatedDate; public DateTimeCalculator(Day day) throws Exception { this.day = day; calculateFromGivenDay(); } public DateTimeCalculator(String date) throws ParseException { this.calculatedDate = dateFormat.format(dateFormat.parse(date)); } public String getDate() { return this.calculatedDate; } private void calculateFromGivenDay() throws Exception { switch(day) { case TODAY: this.calculatedDate = dateFormat.format(calendar.getTime()); break; case YESTERDAY: calendar.add(Calendar.DATE, -1); this.calculatedDate = dateFormat.format(calendar.getTime()); break; default: throw new Exception("Cannot calculate the date, must be one of TODAY or YESTERDAY"); } } }
0c2199121fdd90e6148bd97e585b69473e038372
{ "blob_id": "0c2199121fdd90e6148bd97e585b69473e038372", "branch_name": "refs/heads/master", "committer_date": "2019-09-17T08:40:39", "content_id": "3c1325bb7820f8c7566fda3498927697efb27348", "detected_licenses": [ "Apache-2.0" ], "directory_id": "96b03905076503c473675be4b6ee3850f603f512", "extension": "java", "filename": "DateTimeCalculator.java", "fork_events_count": 0, "gha_created_at": "2018-01-21T14:04:01", "gha_event_created_at": "2022-11-16T12:38:05", "gha_language": "Java", "gha_license_id": "Apache-2.0", "github_id": 118340063, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1259, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/main/java/academy/dd/artemis/date/DateTimeCalculator.java", "provenance": "stack-edu-0023.json.gz:326007", "repo_name": "digital-delivery-academy/artemis-test-uilities", "revision_date": "2019-09-17T08:40:39", "revision_id": "ffff8a6ebe66e1836f0c85eed74f571f3d9fb775", "snapshot_id": "2edc553a74908db596caa3df52fe9ce763892a16", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/digital-delivery-academy/artemis-test-uilities/ffff8a6ebe66e1836f0c85eed74f571f3d9fb775/src/main/java/academy/dd/artemis/date/DateTimeCalculator.java", "visit_date": "2022-11-26T20:57:16.403164", "added": "2024-11-19T00:26:44.701899+00:00", "created": "2019-09-17T08:40:39", "int_score": 3, "score": 3.4375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0041.json.gz" }
package ub.edu.view; import ub.edu.controller.IController; import javax.swing.*; import java.awt.*; //import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowEvent; import java.time.LocalDate; import java.time.format.DateTimeFormatter; /** * Finestra amb la barra de reproducció d'un episodi. Aquesta classe hereta de JDialog */ class FormReproduccio extends JDialog { private JPanel jPanel; private JProgressBar progressBar; private JButton tancaButton; private Timer timer; private final int duracioVisualitzacio; private int duracioVisualitzada; private final String serie; private final int numTemporada; private final int episodi; private final String currentClient; private final String currentUser; private final IController controller; private final Frame owner; /** * Constructor de la classe * @param idSerie identificador de la sèrie de l'episodi a reproduir * @param numTemporada número de temporada de l'episodi a reproduir * @param episodi títol de l'episodi a reproduir * @param duracioEpisodi duració de l'episodi a reproduir */ protected FormReproduccio(Frame owner, IController controller, String idSerie, int numTemporada, int episodi, int duracioEpisodi, String currentClient, String currentUser) { this.owner = owner; this.controller = controller; this.currentClient = currentClient; this.currentUser = currentUser; this.duracioVisualitzacio = duracioEpisodi; this.duracioVisualitzada = controller.getDuracioVisualitzada(currentClient, currentUser, idSerie, numTemporada, episodi, duracioEpisodi); this.serie = idSerie; this.numTemporada = numTemporada; this.episodi = episodi; initComponents(); setResizable(false); setTitle("Reproducció"); setDefaultCloseOperation(HIDE_ON_CLOSE); } /** * Mètode que inicialitza tots els components de la GUI de FormReproduccio i s'afegeixen els listeners dels events per quan es fa l'acció sobre els diferents components de Java. */ private void initComponents() { add(jPanel); setModal(true); setMinimumSize(new Dimension(300,300)); addWindowListener(new java.awt.event.WindowAdapter() { public void windowOpened(WindowEvent evt) { formWindowOpened(evt); } public void windowClosing(WindowEvent evt) { formWindowClosing(evt, serie, numTemporada, episodi); } }); progressBar.setMinimum(0); progressBar.setMaximum(100); progressBar.setStringPainted(true); tancaButton.addActionListener(e -> onPause(serie, numTemporada, episodi)); } private void onPause(String serie, int numTemporada, int episodi) { timer.stop(); int tempsVisualitzacio = (progressBar.getValue()*duracioVisualitzacio)/100; String estat = "Visualització parada"; JOptionPane.showMessageDialog(jPanel, estat); } /** * Mètode que serveix per començar a reproduir l'episodi una vegada s'ha obert la finestra de reproducció * @param evt event que detecta quan s'obra la finestra */ private void formWindowOpened(WindowEvent evt) { if(duracioVisualitzada == duracioVisualitzacio) duracioVisualitzada = 0; progressBar.setValue((duracioVisualitzada*100)/duracioVisualitzacio); int delay = (duracioVisualitzacio*1000)/100; ActionListener actionListener = e -> { if (progressBar.getValue() < 100) progressBar.setValue(progressBar.getValue() + 1); else { formWindowClosing(evt, serie, numTemporada, episodi); } }; if (timer==null) this.timer = new Timer(delay, actionListener); timer.start(); } /** * Mètode que es crida quan es tanca la finestra de reproducció * @param evt event del mètode * @param serie identificador de la sèrie de l'episodi a reproduir * @param numTemporada número de temporada de l'episodi a reproduir * @param idEpisodi títol de l'episodi a reproduir */ private void formWindowClosing(WindowEvent evt, String serie, int numTemporada, int idEpisodi) { timer.stop(); int tempsVisualitzacio = ((progressBar.getValue()*duracioVisualitzacio)/100); int segundosRestantes = duracioVisualitzacio - tempsVisualitzacio; DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd.MM.yyyy"); LocalDate localDate = LocalDate.now(); String info = controller.visualitzarEpisodi(1, currentClient, currentUser, serie, numTemporada, idEpisodi, dtf.format(localDate), segundosRestantes); JOptionPane.showMessageDialog(jPanel, info); dispose(); } }
00e072c664ee16ca5fb746873b4bf61b2248ab53
{ "blob_id": "00e072c664ee16ca5fb746873b4bf61b2248ab53", "branch_name": "refs/heads/main", "committer_date": "2021-01-10T17:13:10", "content_id": "2ae651ecfe36da16084f0429a4435dee3b2ae6bb", "detected_licenses": [ "Apache-2.0" ], "directory_id": "1d945d9f06d6c05ad69ac62d8df61ad8daec69c5", "extension": "java", "filename": "FormReproduccio.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 370673770, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4899, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/ub/edu/view/FormReproduccio.java", "provenance": "stack-edu-0025.json.gz:809601", "repo_name": "lisa31419/Disseny_de_SW_2020", "revision_date": "2021-01-10T17:13:10", "revision_id": "b67cc23405c7f52fb0e9b856d84fa0f45807800e", "snapshot_id": "c11dfe7d1e5c0838d465d42548acd25d46e5ea78", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/lisa31419/Disseny_de_SW_2020/b67cc23405c7f52fb0e9b856d84fa0f45807800e/src/ub/edu/view/FormReproduccio.java", "visit_date": "2023-04-20T13:14:22.883223", "added": "2024-11-18T22:07:39.518182+00:00", "created": "2021-01-10T17:13:10", "int_score": 3, "score": 2.6875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0043.json.gz" }
# SoftwarerepositoryFileServer An external software repository which serves as the source of the file to be imported into the image catalog. If the source is the user's local machine, the file is copied/imported into Intersight's local repository. If not, only a pointer to the file in the external repository is created in the image catalog. For more information, please refer to the softwarerepositoryUploader and softwarerepositoryFile object descriptions where this type is used. ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
86edb6f052cfa95bf5bd8b24d027c282404b6793
{ "blob_id": "86edb6f052cfa95bf5bd8b24d027c282404b6793", "branch_name": "refs/heads/master", "committer_date": "2021-10-25T16:15:50", "content_id": "3aa7cea619f1c81bc8d57f90620c2d5f5dcf7270", "detected_licenses": [ "Apache-2.0" ], "directory_id": "e56214188faae8ebfb36a463e34fc8324935b3c2", "extension": "md", "filename": "SoftwarerepositoryFileServer.md", "fork_events_count": 18, "gha_created_at": "2017-12-26T17:14:03", "gha_event_created_at": "2020-03-02T16:19:49", "gha_language": "Python", "gha_license_id": "Apache-2.0", "github_id": 115440875, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 760, "license": "Apache-2.0", "license_type": "permissive", "path": "/docs/SoftwarerepositoryFileServer.md", "provenance": "stack-edu-markdown-0002.json.gz:267799", "repo_name": "CiscoUcs/intersight-python", "revision_date": "2021-10-25T16:15:50", "revision_id": "a92fccb1c8df4332ba1f05a0e784efbb4f2efdc4", "snapshot_id": "866d6c63e0cb8c33440771efd93541d679bb1ecc", "src_encoding": "UTF-8", "star_events_count": 25, "url": "https://raw.githubusercontent.com/CiscoUcs/intersight-python/a92fccb1c8df4332ba1f05a0e784efbb4f2efdc4/docs/SoftwarerepositoryFileServer.md", "visit_date": "2021-11-07T12:54:41.888973", "added": "2024-11-18T21:51:07.449974+00:00", "created": "2021-10-25T16:15:50", "int_score": 3, "score": 3, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0002.json.gz" }
<?php namespace Spyl\Bundle\BakaBundle\Behat; use Behat\Behat\Context\Context; use Behat\Behat\Hook\Scope\BeforeScenarioScope; use Behat\MinkExtension\Context\RawMinkContext; use Behat\Symfony2Extension\Context\KernelAwareContext; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\DataFixtures\Purger\ORMPurger; use Doctrine\Common\DataFixtures\Executor\ORMExecutor; use Doctrine\Common\Persistence\ObjectManager; use Doctrine\Common\DataFixtures\Loader; use Doctrine\Common\DataFixtures\DependentFixtureInterface; use Faker\Factory as FakerFactory; use Faker\Generator; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpKernel\KernelInterface; use Symfony\Component\Security\Core\SecurityContextInterface; use Symfony\Component\Security\Core\User\UserInterface; abstract class DefaultContext extends RawMinkContext implements Context, KernelAwareContext { /** * Faker. * * @var Generator */ protected $faker; /** * @var KernelInterface */ protected $kernel; public function __construct() { $this->faker = FakerFactory::create(); } /** * {@inheritdoc} */ public function setKernel(KernelInterface $kernel) { $this->kernel = $kernel; } public function purgeDatabase() { $purger = new ORMPurger($this->getService('doctrine.orm.entity_manager')); $purger->purge(); } /** * Get entity manager. * * @return ObjectManager */ protected function getEntityManager() { return $this->getService('doctrine')->getManager(); } /** * Returns Container instance. * * @return ContainerInterface */ protected function getContainer() { return $this->kernel->getContainer(); } /** * Get service by id. * * @param string $id * * @return object */ protected function getService($id) { return $this->getContainer()->get($id); } /** * Get parameter by id. * * @param string $id * * @return object */ protected function getParameter($id) { return $this->getContainer()->getParameter($id); } /** * Get current user instance. * * @return null|UserInterface * * @throws \Exception */ protected function getUser() { $token = $this->getSecurityContext()->getToken(); if (null === $token) { throw new \Exception('No token found in security context.'); } return $token->getUser(); } /** * Get security context. * * @return SecurityContextInterface */ protected function getSecurityContext() { return $this->getContainer()->get('security.context'); } /** * Generate url. * * @param string $route * @param array $parameters * @param Boolean $absolute * * @return string */ protected function generateUrl($route, array $parameters = array(), $absolute = false) { return $this->locatePath($this->getService('router')->generate($route, $parameters, $absolute)); } /** * Load a data fixture class * * @param \Doctrine\Common\DataFixtures\Loader $loader Data fixtures loader * @param string $className Class name of fixture */ public function loadFixtureClass(Loader $loader, $className) { $fixture = new $className(); if ($loader->hasFixture($fixture)) { unset($fixture); return; } $loader->addFixture(new $className); if ($fixture instanceof DependentFixtureInterface) { foreach ($fixture->getDependencies() as $dependency) { $this->loadFixtureClass($loader, $dependency); } } } /** * Load a data fixture class * * @param \Doctrine\Common\DataFixtures\Loader $loader Data fixtures loader * @param array $classNames Array of class names of fixtures */ public function loadFixtureClasses(Loader $loader, array $classNames) { foreach ($classNames as $className) { $this->loadFixtureClass($loader, $className); } } /** * Execute the fixtures * * @param \Doctrine\Common\DataFixtures\Loader $loader Data fixtures loader */ public function purgeAndExecuteFixtures(Loader $loader) { $executor = new ORMExecutor($this->getService('doctrine.orm.entity_manager'), new ORMPurger()); $executor->execute($loader->getFixtures()); } }
ae5ef3387bf4129bda454206f78cb9e29355baa1
{ "blob_id": "ae5ef3387bf4129bda454206f78cb9e29355baa1", "branch_name": "refs/heads/master", "committer_date": "2014-09-24T18:48:34", "content_id": "bb22f4d2fcfc31ebdee0613e931e4da923be68d5", "detected_licenses": [ "Apache-2.0", "MIT" ], "directory_id": "2dcee84e3e4f18f38d44b6060b82ccc2ba292ff7", "extension": "php", "filename": "DefaultContext.php", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 22809407, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4923, "license": "Apache-2.0,MIT", "license_type": "permissive", "path": "/src/Spyl/Bundle/BakaBundle/Behat/DefaultContext.php", "provenance": "stack-edu-0053.json.gz:745240", "repo_name": "spyl94/baka", "revision_date": "2014-09-24T18:48:34", "revision_id": "64245050ee4e4ee3731aa9207a874177cc5ca58b", "snapshot_id": "12875cce068bf8d9259cfe71ae99e3d7e6f80526", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/spyl94/baka/64245050ee4e4ee3731aa9207a874177cc5ca58b/src/Spyl/Bundle/BakaBundle/Behat/DefaultContext.php", "visit_date": "2021-01-10T21:48:50.607680", "added": "2024-11-19T02:19:49.940056+00:00", "created": "2014-09-24T18:48:34", "int_score": 2, "score": 2.296875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0071.json.gz" }
"""This script configures GigabitEthernet2 interfaces on network devices. Copyright (c) 2018 Cisco and/or its affiliates. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from ncclient import manager import xmltodict def check_ip(device): """This function checks the IP configuration of GigabitEthernet2 """ # MISSION TODO 1: Provide the proper type of NETCONF object needed # Create an XML filter for targeted NETCONF queries netconf_filter = """ <MISSION> <interfaces xmlns="http://openconfig.net/yang/interfaces"> <interface> <name>GigabitEthernet2</name> </interface> </interfaces> </MISSION>""" # END MISSION SECTION # print("Opening NETCONF Connection to {}".format(device["conn"]["host"])) # Open a connection to the network device using ncclient with manager.connect( host=device["conn"]["host"], port=device["conn"]["netconf_port"], username=device["conn"]["username"], password=device["conn"]["password"], hostkey_verify=False, ) as m: # MISSION TODO 2: Provide the appropriate Manager Method Name # print("Sending a <get-config> operation to the device.\n") # Make a NETCONF <get-config> query using the filter netconf_reply = m.MISSION(source="running", filter=netconf_filter) # END MISSION SECTION # Uncomment the below lines to print the raw XML body # print("Here is the raw XML data returned from the device.\n") # print(xml.dom.minidom.parseString(netconf_reply.xml).toprettyxml()) # print("") # Parse the returned XML to an Ordered Dictionary netconf_data = xmltodict.parse(netconf_reply.xml)["rpc-reply"]["data"] # Get the Interface Details interface = netconf_data["interfaces"]["interface"] print("Device: {}".format(device["conn"]["host"])) print(" Interface: {}".format(interface["config"]["name"])) try: ipv4 = interface["subinterfaces"]["subinterface"]["ipv4"]["addresses"][ "address" ] print( " IPv4: {}/{}".format( ipv4["ip"], ipv4["config"]["prefix-length"] ) ) return ( device["conn"]["host"], ipv4["ip"], ipv4["config"]["prefix-length"] ) except KeyError: print(" IPv4: not configured.") print("\n") def set_ip(device): """This function configures the IP of GigabitEthernet2 """ # MISSION TODO 3: What XML attribute is used to indicate the capability? # Create an XML configuration template for openconfig-interfaces netconf_interface_template = """ <config> <interfaces MISSION="http://openconfig.net/yang/interfaces"> <interface> <name>{name}</name> <config> <type xmlns:ianaift="urn:ietf:params:xml:ns:yang:iana-if-type"> ianaift:ethernetCsmacd </type> <name>{name}</name> <enabled>{status}</enabled> </config> <subinterfaces> <subinterface> <index>0</index> <ipv4 xmlns="http://openconfig.net/yang/interfaces/ip"> <addresses> <address> <ip>{ip_address}</ip> <config> <ip>{ip_address}</ip> <prefix-length>{prefix}</prefix-length> </config> </address> </addresses> </ipv4> <ipv6 xmlns="http://openconfig.net/yang/interfaces/ip"> <config> <enabled>false</enabled> </config> </ipv6> </subinterface> </subinterfaces> </interface> </interfaces> </config>""" # END MISSION SECTION # Create NETCONF Payload for device # MISSION TODO 4: What String method is used to fill in a template? netconf_data = netconf_interface_template.MISSION( name="GigabitEthernet2", status="true", ip_address=device["ip"], prefix=device["prefix"], ) # END MISSION SECTION # Uncomment the below lines to view the config payload # print("The configuration payload to be sent over NETCONF.\n") # print(netconf_data) # Open a connection to the network device using ncclient with manager.connect( host=device["conn"]["host"], port=device["conn"]["netconf_port"], username=device["conn"]["username"], password=device["conn"]["password"], hostkey_verify=False, ) as m: # print("Sending a <edit-config> operation to the device.\n") # Make a NETCONF <get-config> query using the filter netconf_reply = m.edit_config(netconf_data, target="running") if netconf_reply.ok: print( "Device {} updated successfully".format(device["conn"]["host"]) ) print("") return netconf_reply def clear_ip(device): """This function will clear the IP address on GigabitEthernet2 """ # MISSION TODO 5: What edit operation type is needed to clear details? # Create an XML configuration template for openconfig-interfaces netconf_interface_template = """ <config> <interfaces xmlns="http://openconfig.net/yang/interfaces"> <interface> <name>{name}</name> <subinterfaces> <subinterface> <index>0</index> <ipv4 xmlns="http://openconfig.net/yang/interfaces/ip" operation="MISSION" /> </ipv4> </subinterface> </subinterfaces> </interface> </interfaces> </config>""" # END MISSION SECTION # Create NETCONF Payload for device netconf_data = netconf_interface_template.format(name="GigabitEthernet2") # Uncomment the below lines to view the config payload # print("The configuration payload to be sent over NETCONF.\n") # print(netconf_data) # MISSION TODO 6: What Manager method is used to start a session? # Open a connection to the network device using ncclient with manager.MISSION( host=device["conn"]["host"], port=device["conn"]["netconf_port"], username=device["conn"]["username"], password=device["conn"]["password"], hostkey_verify=False, ) as m: # END MISSION SECTION # print("Sending a <edit-config> operation to the device.\n") # Make a NETCONF <get-config> query using the filter netconf_reply = m.edit_config(netconf_data, target="running") if netconf_reply.ok: print( "Device {} updated successfully".format(device["conn"]["host"]) ) print("") return netconf_reply
e97656e494e2a68238bdbab92f3705c914841cce
{ "blob_id": "e97656e494e2a68238bdbab92f3705c914841cce", "branch_name": "refs/heads/master", "committer_date": "2019-10-22T13:50:04", "content_id": "44a24b5261d4524509aaf71c95152af4c42fe0f0", "detected_licenses": [ "MIT" ], "directory_id": "9a1e1c523a4e7f186b02511f3e159e202be37549", "extension": "py", "filename": "netconf_functions.py", "fork_events_count": 0, "gha_created_at": "2019-10-22T13:52:08", "gha_event_created_at": "2021-09-23T23:26:45", "gha_language": "HTML", "gha_license_id": "MIT", "github_id": 216825970, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8251, "license": "MIT", "license_type": "permissive", "path": "/intro-mdp/mission01/netconf_functions.py", "provenance": "stack-edu-0055.json.gz:33879", "repo_name": "anguschuks/Python-Exercises-CISCO", "revision_date": "2019-10-22T13:50:04", "revision_id": "3426ac68a271f07d24b920c956e02e20e429da5d", "snapshot_id": "8a54cf9a74ad57f531085c638737a0a0f205f3ba", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/anguschuks/Python-Exercises-CISCO/3426ac68a271f07d24b920c956e02e20e429da5d/intro-mdp/mission01/netconf_functions.py", "visit_date": "2021-10-07T22:53:59.449385", "added": "2024-11-19T00:33:39.015530+00:00", "created": "2019-10-22T13:50:04", "int_score": 2, "score": 2.375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0073.json.gz" }
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class RollingHash{ private: static const int MODULO = 667013; const int SIZE; const int BASE; vector<int> values; vector<int> hashValues; int maxPow; void fixMaxPow(){ maxPow = 1; for(int i = 1; i <= SIZE - 1; ++i){ maxPow = (maxPow * BASE) % MODULO; } } public: RollingHash(const int& SIZE, const int& BASE): SIZE(SIZE), BASE(BASE){ fixMaxPow(); } RollingHash(const vector<int>& VALUES, const int& BASE): SIZE(VALUES.size()), BASE(BASE){ fixMaxPow(); for(const int& VAL: VALUES){ pushBack(VAL); } } void pushBack(const int& VAL){ values.push_back(VAL); int hashVal = (hashValues.empty() ? 0 : hashValues.back()); if(values.size() >= SIZE){ hashVal = (((hashVal - maxPow * values[(int)values.size() - SIZE]) % MODULO) + MODULO) % MODULO; } hashVal = (BASE * (hashVal + VAL)) % MODULO; hashValues.push_back(hashVal); } void popBack(){ values.pop_back(); hashValues.pop_back(); } int getHash(){ if(hashValues.size() >= SIZE){ return hashValues.back(); } return -1; } }; class Solution { private: bool matches(const vector<int>& VALUES, const vector<int>& TARGET_VALUES){ for(int i = (int)VALUES.size() - 1, j = (int)TARGET_VALUES.size() - 1; j >= 0; --i, --j){ if(VALUES[i] != TARGET_VALUES[j]){ return false; } } return true; } void dfs(TreeNode* node, vector<int>& values, const vector<int>& TARGET_VALUES, RollingHash& hashObj, const int& TARGET_HASH, bool& contains){ if(node == NULL || contains){ return; } values.push_back(node->val); hashObj.pushBack(node->val); if(hashObj.getHash() == TARGET_HASH){ contains = matches(values, TARGET_VALUES); } dfs(node->left, values, TARGET_VALUES, hashObj, TARGET_HASH, contains); dfs(node->right, values, TARGET_VALUES, hashObj, TARGET_HASH, contains); values.pop_back(); hashObj.popBack(); } public: bool isSubPath(ListNode* head, TreeNode* root) { vector<int> targetValues; for(ListNode* node = head; node != NULL; node = node->next){ targetValues.push_back(node->val); } const int SIZE = targetValues.size(); const int BASE = 101; const int TARGET_HASH = RollingHash(targetValues, BASE).getHash(); vector<int> values; RollingHash hashObj(SIZE, BASE); bool contains = false; dfs(root, values, targetValues, hashObj, TARGET_HASH, contains); return contains; } };
4789eb99de8fc9ce8a99503cfb01a8a2f0e8253e
{ "blob_id": "4789eb99de8fc9ce8a99503cfb01a8a2f0e8253e", "branch_name": "refs/heads/master", "committer_date": "2023-08-14T21:21:51", "content_id": "5f97f1f5aec80ad9f7897b81c9f8916fd0826450", "detected_licenses": [ "MIT" ], "directory_id": "a21d7710b1d193ae7ee12205c2af2c47db09905e", "extension": "cpp", "filename": "#1367_LinkedListInBinaryTree_sol2_rolling_hash_O(T)_time_O(H)_extra_space_40ms_33MB.cpp", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 243604510, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3631, "license": "MIT", "license_type": "permissive", "path": "/LeetCode/Problems/Algorithms/#1367_LinkedListInBinaryTree_sol2_rolling_hash_O(T)_time_O(H)_extra_space_40ms_33MB.cpp", "provenance": "stack-edu-0004.json.gz:29323", "repo_name": "Tudor67/Competitive-Programming", "revision_date": "2023-08-14T21:21:51", "revision_id": "827cabc45951ac33f63d1d6e69e57897207ea666", "snapshot_id": "0db89e0f8376cac7c058185b84fdf11dcb99dae8", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/Tudor67/Competitive-Programming/827cabc45951ac33f63d1d6e69e57897207ea666/LeetCode/Problems/Algorithms/#1367_LinkedListInBinaryTree_sol2_rolling_hash_O(T)_time_O(H)_extra_space_40ms_33MB.cpp", "visit_date": "2023-08-19T05:22:10.451067", "added": "2024-11-18T23:15:43.432578+00:00", "created": "2023-08-14T21:21:51", "int_score": 3, "score": 3, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0022.json.gz" }
var WechatMore = WechatMore || {}; WechatMore.bgMp3 = function () { //背景音乐 var btn = $('#js_musicBtn'), oMedia = $('#bgMusic')[0]; btn.on(WechatMore.events.start, function (e) { if (oMedia.paused) { oMedia.play(); } else { oMedia.pause(); } e.preventDefault(); }); oMedia.load(); oMedia.play(); if (oMedia.paused) { $('#wrapper').one(WechatMore.events.start, function (e) { oMedia.play(); e.preventDefault(); }); }; $(oMedia).on('play', function () { btn.addClass('musicPlay'); }); $(oMedia).on('pause', function () { btn.removeClass('musicPlay'); }); } $(document).ready(function(){ var i = 0; if( WechatMore.step >0 ) { i = $("[data-step='"+WechatMore.step+"']").prevAll().length; } swiper = new Swiper('.swiper-container', { direction: 'vertical', initialSlide : i, speed:800, followFinger : false, touchRatio : 0.1, resistanceRatio : 0, onSlideChangeEnd: function(swiper){ console.log('onSlideChangeEnd:'+swiper.activeIndex ); WechatMore.step = parseInt( swiper.slides.eq(swiper.activeIndex).data('step')); //切换结束时,告诉我现在是第几个slide if( WechatMore.step == 6) // 积攒页面 { //如果openid对应的客户存在 if( WechatMore.game_player_by_openid>0 ) { $('#j-apply-btn').hide(); }else{ //显示我也要参加活动 $('#j-apply-btn').show(); } } if( WechatMore.step == 5) //气球页面 { $('.qiqiu-wrap').addClass('up'); }else{ $('.qiqiu-wrap').removeClass('up'); } //根据当前页面,重新生成分享链接 fixShareLink(); } }); WechatMore.swiper = swiper; $('.next-slide-btn').on( WechatMore.events.start, function(e){ e.stopPropagation(); swiper.slideNext(); }); //选择店铺 $('.select-store-btn').on( WechatMore.events.start, function(){ $(this).parent('.store').addClass('selected').siblings().removeClass('selected'); var store_id = $(this).data('id'); $('#game_player_store_id').val(store_id ); swiper.slideNext(); }); //注册 $('#j-submit-player-btn').on( WechatMore.events.start, function(){ if (! $("#j-game-player-form").valid()) { return; } $.ajax( { url: WechatMore.routes.game_players_path , type:'POST', dataType: 'json', data: $("#j-game-player-form").serialize(), success: function(data){ //设置投票对象ID WechatMore.game_player_id = data.game_player.id; WechatMore.game_player_by_openid = WechatMore.game_player_id; //我要报名改为已注册 $('#j-startup-btn').html('已报名'); //隐藏提交按钮 $('#j-submit-player-btn').hide(); //升起气球 //var qiqiu = $('#j_qiqiu').addClass('qiqiu0'); $('.qiqiu-wrap').addClass('up'); $('#j_qiqiu .realname').html(data.game_player.realname); var t=setTimeout("handleQiqiu();",5000) swiper.slideNext(); //新注册用户隐藏积攒信息 $('#j-game-player').hide(); fixShareLink(); } }); }); //解锁,积攒 $('#j-unlock-btn').on( WechatMore.events.start, function(){ //在积攒页面 //点赞对象为分享链接的玩家,如果不是分享链接,则是为自己点赞, $('#vote_game_player_id').val(WechatMore.game_player_id ); $.ajax( { url: WechatMore.routes.votes_path , type:'POST', dataType: 'json', data: $("#j-vote-form").serialize(), success: function(data){ //显示当前积攒数, "某某某已经解锁了120个" $('#j-game-player .votes_count').html( data.vote.game_player.realname+'已经解锁了'+data.vote.game_player.votes_count+'个'); if( WechatMore.game_player_by_openid ==0 ) { //显示我也要参加活动 $('#j-apply-btn').show(); } $('#j-game-player').show(); WechatMore.game_player_votes_count = data.vote.game_player.votes_count; showPlayerForSharePage( ); } }); }); // 上传图片 $('#file_left').on('change',function(){ WechatMore.fn.previewImage(this,0); }); $('#file_right').on('change',function(){ WechatMore.fn.previewImage(this,1); }); //生成图片 $('#j-make-photo-btn').on( WechatMore.events.start, function(){ if (! $("#j-wedding-photo-form").valid()) { return; } drawWeddingPhoto(); swiper.slideNext(); }); $(".dpicker").dpicker({ title: "请选择您的出生日期", cols: [ { textAlign: 'center', values: (function () { var arr = []; for (var i=1950; i<=2010; i++) arr.push(i.toString()); return arr; })() //如果你希望显示文案和实际值不同,可以在这里加一个displayValues: [.....] }, { textAlign: 'center', values:(function () { var minutes = []; for (var i=1; i<=12; i++) minutes.push(i.toString()); return minutes; })() }, { textAlign: 'center', values: (function () { var minutes = []; for (var i=1; i<=31; i++) minutes.push(i.toString()); return minutes; })() } ] }); //绑定滑屏事件 var time = new Date(); touch.on('.swiper-container', 'swipeup swipedown', function(ev){ console.log("you have done", ev.type); var now = new Date(); if( now - time >500 ) // 忽略连续滑屏事件 300 { if( ev.type=='swipeup') { if( !WechatMore.swiper.isEnd) { //如果是 2,3,4注册页面,只能点击按钮翻页,无法滑动 if( WechatMore.step == 2 || WechatMore.step == 3|| WechatMore.step == 4 ) { if( WechatMore.game_player_by_openid >0 ) { WechatMore.swiper.slideNext(); }else { if( WechatMore.step == 3)//当进入step4,再返回时,应允许向下滑动 { if( parseInt( $('#game_player_store_id').val()) > 0) { WechatMore.swiper.slideNext(); } } } }else if( WechatMore.step == 10)//生成结婚证页面 { var wedding_image = $("#j-wedding-image"); if( wedding_image.attr('src') && wedding_image.attr('src').length>0 ) {//如果用户已经生成过结婚照,允许翻页 WechatMore.swiper.slideNext(); } }else{ WechatMore.swiper.slideNext(); } } if( WechatMore.step == 8) { oMedia = $('#bgMusic')[0]; if( oMedia) { oMedia.pause(); } } }else{ if( !WechatMore.swiper.isBeginning) { //如果注册以后,向上滑动,跳过注册页面 if( WechatMore.game_player_by_openid >0 ) { WechatMore.swiper.slidePrev(); }else { //没有注册 if( WechatMore.step == 6 )//积攒页面 { }else { WechatMore.swiper.slidePrev(); } } } } } time = now; }); //点击小车 $('#j-car-btn').on( WechatMore.events.start, function(e){ $('#j-car-tips').fadeIn(); e.preventDefault(); }); $('#j-car-tips').on( WechatMore.events.start, function(e){ $('#j-car-tips').fadeOut(); }); // 当用户分享页面给他人时, // 显示分享用户对应信息,如年龄对应的商品系列 showPlayerForSharePage( ); // 根据用户积攒数显示解锁进度条 }); function handleQiqiu() { //用户可能已经滑屏到其他页面了 if( WechatMore.step == 4) { WechatMore.swiper.slideNext(); } } function drawWeddingPhoto(){ var images= { image1: $("#j-photo-1")[0], image2: $("#j-photo-2")[0], bg: $("#j-wedding-bg")[0] }; var c= document.createElement('canvas'),//document.getElementById('j-wedding-canvas'); ctx=c.getContext('2d'); //结婚照图片 700*495 var photo_image_size = [1440,988]; var male_image_size = [105,140]; var male_image_positon=[1140,435]; var male_name_position=[845,485]; var male_gender_position=[1025, 485]; var male_birth_position=[905,545]; var photo_ratio = photo_image_size[1]/photo_image_size[0]; var female_image_positon=[1140,610]; var female_name_position=[845,660]; var female_gender_position=[1025, 660]; var female_birth_position=[905,720]; var release_at_position=[470,400]; var width = photo_image_size[0]; //$('#j-image-wrap').width(); var height = width* photo_ratio; var scale = width/photo_image_size[0]; c.width=width; c.height=height; //ctx.rect(0,0,c.width,c.height); ctx.fillStyle='black';//画布填充颜色 ctx.font="34px/40px '微软雅黑'"; //ctx.fill(); ctx.drawImage(images.bg,0,0,width,height); ctx.drawImage(images.image1,scale*male_image_positon[0],scale*male_image_positon[1],scale*male_image_size[0],scale*male_image_size[1]); ctx.drawImage(images.image2,scale*female_image_positon[0],scale*female_image_positon[1],scale*male_image_size[0],scale*male_image_size[1]); //画名字,出生日期,性别, 发证日期 ctx.fillText($('#male_realname').val(), scale*male_name_position[0], scale*male_name_position[1]); ctx.fillText($('#female_realname').val(), scale*female_name_position[0], scale*female_name_position[1]); ctx.fillText("男", scale*male_gender_position[0], scale*male_gender_position[1]); ctx.fillText("女", scale*female_gender_position[0], scale*female_gender_position[1]); ctx.fillText($('#male_birth').val(), scale*male_birth_position[0], scale*male_birth_position[1]); ctx.fillText($('#female_birth').val(), scale*female_birth_position[0], scale*female_birth_position[1]); var today = new Date(); var stoday = today.toLocaleDateString(); //today.getFullYear()+'年' + today.get + today.getDate() //ctx.fillText(stoday, scale*release_at_position[0], scale*release_at_position[1]); var imageData = c.toDataURL('image/png'); $('#base64_image').val( imageData); $('#j-wedding-image').attr( 'src', imageData); //如果是结婚照页面,需要先上传图片,以便获取结婚照图片路径 //$.ajax( { url: WechatMore.routes.photographs_path , type:'POST', dataType: 'json', // data: $("#j-photograph-form").serialize(), // success: function(data){ // //console.log(data); // WechatMore.shareData.weddingPageUrl = WechatMore.routes.shared_game_round_url+ '?photo_id='+ data.photograph.id+'&step='+WechatMore.step; // //WechatMore.shareData.weddingImgUrl = data.photograph.image_url; // } //}); //创建用户,分享后可以查看 $.ajax( { url: WechatMore.routes.game_players_path , type:'POST', dataType: 'json', data: $("#j-wedding-photo-form").serialize(), success: function(data){ //设置投票对象ID console.log(data); WechatMore.game_player_id = data.game_player.id; WechatMore.game_player_by_openid = WechatMore.game_player_id; WechatMore.game_player_age = data.game_player.age; //根据年龄显示推荐商品 fixShareLink(); showPlayerForSharePage( ); } }); } function showPlayerForSharePage( ) { //根据年龄显示相应推荐商品 var age = WechatMore.game_player_age; var selected = '1'; if( age<=25 ){ selected = '1'; }else if ( age>25 && age<=30 ){ selected = '2'; }else if ( age>30 && age<=35 ){ selected = '3'; }else{ selected = '4'; } $('.image-style').removeClass('selected'); $('.image-style.style'+selected).addClass('selected'); //根据积攒数显示解锁进度条 var votes_count = WechatMore.game_player_votes_count; if( votes_count >0 ) { $('.j-prize').each(function(){ var $this = $(this); var score = $this.data('score'); var percent = votes_count/parseInt(score); if(percent>=1){ $this.addClass('unlock'); percent =1; } $this.find('.progress').css('width', percent*100+'%'); }); } }
b427183c5c8fe96cb4cd6786e2bffd72e97643e9
{ "blob_id": "b427183c5c8fe96cb4cd6786e2bffd72e97643e9", "branch_name": "refs/heads/master", "committer_date": "2021-04-12T07:28:08", "content_id": "36fc3092a19a8b9e4820a063db0e5800a5acdd08", "detected_licenses": [ "MIT" ], "directory_id": "f9a53ce80499eb065eb127bde5605cc3987dfc57", "extension": "js", "filename": "game.js", "fork_events_count": 0, "gha_created_at": "2018-03-31T02:07:06", "gha_event_created_at": "2023-01-19T11:18:54", "gha_language": "HTML", "gha_license_id": "MIT", "github_id": 127490416, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 12607, "license": "MIT", "license_type": "permissive", "path": "/app/assets/javascripts/game/yhzy_ido/game.js", "provenance": "stack-edu-0046.json.gz:14262", "repo_name": "RuanShan/jpos_rapi", "revision_date": "2021-04-12T07:28:08", "revision_id": "260e3ae1e9061c4414cb2cf5f2931e3820e021f9", "snapshot_id": "fc5a723df69ae099e87de2790713be052cb35819", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/RuanShan/jpos_rapi/260e3ae1e9061c4414cb2cf5f2931e3820e021f9/app/assets/javascripts/game/yhzy_ido/game.js", "visit_date": "2023-01-20T11:05:33.281351", "added": "2024-11-18T22:42:19.197292+00:00", "created": "2021-04-12T07:28:08", "int_score": 2, "score": 2, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0064.json.gz" }
use super::layout::Layout; use super::lexer; use crate::wayland::{ river_layout_v3::river_layout_manager_v3::RiverLayoutManagerV3, river_layout_v3::river_layout_v3::Event, }; use wayland_client::protocol::wl_output::WlOutput; use wayland_client::Main; pub struct Globals { pub namespace: String, pub layout_manager: Option<Main<RiverLayoutManagerV3>>, } // Parameters necessary to generate a layout #[derive(Copy, Clone)] pub struct Parameters { pub amount: u32, pub index: u32, pub ratio: f64, } #[derive(Copy, Clone)] pub enum Order { Ascend, Descend, } // The state of an Output pub struct Output { pub output: Main<WlOutput>, // This is the index of the focused Tag pub focused: usize, // Defines if a layout should regenerated or not pub reload: bool, // Defines if a the layout area should reajusted to the output dimension or not pub resize: bool, // Order the tags are sorted pub order: Order, // Dimensions of the layout area pub dimension: Area, pub view_padding: i32, pub outer_padding: i32, pub smart_padding: bool, // The configuration of all Tags pub tags: [Option<Tag>; 32], } // The configuration of a Tag pub struct Tag { pub name: String, pub layout: Layout, pub parameters: Parameters, } #[derive(Copy, Clone, Debug)] pub struct Area { pub x: u32, pub y: u32, pub w: u32, pub h: u32, } impl Globals { pub fn new(namespace: String) -> Globals { { Globals { namespace, layout_manager: None, } } } } impl Output { pub fn new(output: Main<WlOutput>) -> Output { { Output { output, dimension: Area { x: 0, y: 0, w: 0, h: 0, }, focused: 0, reload: true, resize: false, view_padding: 0, outer_padding: 0, smart_padding: false, order: Order::Ascend, tags: Default::default(), } } } pub fn layout_filter( mut self, layout_manager: Option<&Main<RiverLayoutManagerV3>>, namespace: String, ) { // A generic default configuration used when a Tag isn't defined let mut default: Tag = { Tag { name: "kile".to_owned(), parameters: { Parameters { index: 0, amount: 1, ratio: 0.6, } }, layout: Layout::Full, } }; let layout = layout_manager .expect("Compositor doesn't implement river_layout_v3") .get_layout(&self.output, namespace.clone()); let mut view_padding = 0; // A vector holding the geometry of all the views from the most recent layout demand let mut views: Vec<Area> = Vec::new(); layout.quick_assign(move |layout, event, _| match event { Event::LayoutDemand { view_count, usable_width, usable_height, serial, tags, } => { let layout_name = if self.reload { if !self.resize { self.dimension = { Area { x: 0, y: 0, w: usable_width, h: usable_height, } }; if !self.smart_padding || view_count > 1 { self.dimension.apply_padding(self.outer_padding); } } self.focused = tag(tags, &self.order) as usize; match self.tags[self.focused].as_ref() { Some(tag) => { view_padding = self.view_padding; tag.update(&mut views, view_count, self.dimension); tag.name.as_str() } None => { default.update(&mut views, view_count, self.dimension); default.name.as_str() } } } else { "reload" }; self.reload = true; for area in &mut views { if !self.smart_padding || view_count > 1 { area.apply_padding(view_padding); } layout.push_view_dimensions( area.x as i32, area.y as i32, area.w, area.h, serial, ) } layout.commit(layout_name.to_owned(), serial); } Event::NamespaceInUse => { println!("Namespace already in use."); layout.destroy(); } // All String events are delegated to the lexer Event::UserCommand { command } => { if let Some((command, value)) = command.split_once(' ') { match command { "padding" => { if let Ok(value) = value.parse::<i32>() { self.outer_padding = value; view_padding = value - view_padding; self.view_padding = value; } } "mod_padding" => { if let Ok(delta) = value.parse::<i32>() { self.outer_padding += delta; if (self.view_padding as i32) + delta >= 0 { self.view_padding += delta; view_padding = delta; } } } "outer_padding" => { if let Ok(value) = value.parse::<i32>() { self.outer_padding = value; } } "view_padding" => { if let Ok(value) = value.parse::<i32>() { view_padding = value - view_padding; self.view_padding = value; if !views.is_empty() { self.reload = false; } } } "mod_outer_padding" => { if let Ok(delta) = value.parse::<i32>() { self.outer_padding += delta; } } "mod_view_padding" => { if let Ok(delta) = value.parse::<i32>() { if (self.view_padding as i32) + delta >= 0 { self.view_padding += delta; view_padding = delta; if !views.is_empty() { self.reload = false; } } } } "main_ratio" => { if let Some(tag) = self.tags[self.focused].as_mut() { if let Ok(value) = value.parse::<f64>() { tag.parameters.ratio = value.clamp(0.0, 1.0); } } } "mod_main_ratio" => { if let Some(tag) = self.tags[self.focused].as_mut() { if let Ok(delta) = value.parse::<f64>() { if delta <= tag.parameters.ratio { tag.parameters.ratio += delta; } } } } "default_main_ratio" => { if let Ok(value) = value.parse::<f64>() { default.parameters.ratio = value.clamp(0.0, 1.0); } } "mod_default__main_ratio" => { if let Ok(delta) = value.parse::<f64>() { if delta <= default.parameters.ratio { default.parameters.ratio += delta; } } } "main_amount" => { if let Some(tag) = self.tags[self.focused].as_mut() { if let Ok(value) = value.parse::<u32>() { tag.parameters.amount = value } } } "mod_main_amount" => { if let Some(tag) = self.tags[self.focused].as_mut() { if let Ok(delta) = value.parse::<i32>() { if (tag.parameters.amount as i32) + delta >= 0 { tag.parameters.amount = ((tag.parameters.amount as i32) + delta) as u32 } } } } "default_main_amount" => { if let Ok(value) = value.parse::<u32>() { default.parameters.amount = value; } } "mod_default_main_amount" => { if let Ok(delta) = value.parse::<i32>() { if (default.parameters.amount as i32) + delta >= 0 { default.parameters.amount = ((default.parameters.amount as i32) + delta) as u32 } } } "main_index" => { if let Some(tag) = self.tags[self.focused].as_mut() { if let Ok(value) = value.parse::<u32>() { tag.parameters.index = value; } } } "mod_main_index" => { if let Some(tag) = self.tags[self.focused].as_mut() { if let Ok(delta) = value.parse::<i32>() { if (tag.parameters.index as i32) + delta >= 0 { tag.parameters.index = ((tag.parameters.index as i32) + delta) as u32 } } } } "default_main_index" => { if let Ok(value) = value.parse::<u32>() { default.parameters.index = value; } } "mod_default_main_index" => { if let Ok(delta) = value.parse::<i32>() { if (default.parameters.index as i32) + delta >= 0 { default.parameters.index = ((default.parameters.index as i32) + delta) as u32 } } } "xoffset" => { if let Ok(delta) = value.parse::<i32>() { if delta < 0 { self.dimension.x = 0; } else { self.dimension.x = delta.abs() as u32; } self.dimension.w -= delta.abs() as u32; self.resize = true; } } "yoffset" => { if let Ok(delta) = value.parse::<i32>() { if delta < 0 { self.dimension.y = 0; } else { self.dimension.y = delta.abs() as u32; } self.dimension.h -= delta.abs() as u32; self.resize = true; } } "dimension" => { let mut fields = value.split_whitespace(); self.dimension = { self.resize = true; Area { x: fields .next() .unwrap_or_default() .parse::<u32>() .unwrap_or(self.dimension.x), y: fields .next() .unwrap_or_default() .parse::<u32>() .unwrap_or(self.dimension.y), w: fields .next() .unwrap_or_default() .parse::<u32>() .unwrap_or(self.dimension.w), h: fields .next() .unwrap_or_default() .parse::<u32>() .unwrap_or(self.dimension.h), } } } "resize" => { if let Ok(ans) = value.parse::<bool>() { self.resize = ans; } } "smart_padding" => { if let Ok(ans) = value.parse::<bool>() { self.smart_padding = ans; } } "order" => match value { "ascend" => self.order = Order::Ascend, "descend" => self.order = Order::Descend, _ => {} }, "default" => { let (name, layout) = if let Some(data) = value.split_once('\n') { data } else if let Some(data) = lexer::split_ounce(value, ' ') { data } else { ("kile", value) }; default.name = name.to_owned(); default.layout = lexer::parse(layout); } "clear" => match value { "all" => self.tags = Default::default(), "default" => default.layout = Layout::Full, "focused" => self.tags[self.focused] = None, _ => match value.parse::<usize>() { Ok(int) => { if int > 0 && int < 33 { self.tags[int - 1] = None } } Err(_) => {} }, }, _ => lexer::main(&mut self, command, value), } } } }); } } impl Tag { fn update(&self, views: &mut Vec<Area>, view_amount: u32, area: Area) { views.clear(); area.generate(views, &self.layout, &self.parameters, view_amount, true); } } fn tag(tagmask: u32, order: &Order) -> u32 { let mut int = 0; let mut current: u32; while { current = 1 << int; current < tagmask } { if current != tagmask && (tagmask / current) % 2 != 0 { if let Order::Descend = order { int = tag(tagmask - current, order); } break; } int += 1; } int }
6801540499707c71e70bd45a3ac8c9aac57d865b
{ "blob_id": "6801540499707c71e70bd45a3ac8c9aac57d865b", "branch_name": "refs/heads/main", "committer_date": "2021-09-20T13:44:37", "content_id": "8095a0336721965c161f2aa4060b4a2737fa6279", "detected_licenses": [ "MIT" ], "directory_id": "ba142d29a0b78ae50aa249ecbde878a44428a532", "extension": "rs", "filename": "client.rs", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 17785, "license": "MIT", "license_type": "permissive", "path": "/src/client.rs", "provenance": "stack-edu-0068.json.gz:16954", "repo_name": "hasturi/kile", "revision_date": "2021-09-20T13:44:37", "revision_id": "5fd84dfd4ce71cda45f395656d7b85711df4c250", "snapshot_id": "902a71f3a0622368ab692281e12babbce36b200f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/hasturi/kile/5fd84dfd4ce71cda45f395656d7b85711df4c250/src/client.rs", "visit_date": "2023-08-18T08:02:23.261578", "added": "2024-11-18T22:43:33.376778+00:00", "created": "2021-09-20T13:44:37", "int_score": 2, "score": 2.3125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0086.json.gz" }
package com.thinkhodl.bedshema.backend; import com.thinkhodl.bedshema.R; import java.util.ArrayList; public class PrayerLists { private static ArrayList<Prayer> mShemaPrayer; private static ArrayList<Prayer> mBirkathHasharar; private static ArrayList<Prayer> mTphilathBH; private static ArrayList<Prayer> mTphilathHaerech; private static ArrayList<Prayer> mBirathHalevanah; public static ArrayList<Prayer> getmShemaPrayer() { mShemaPrayer = new ArrayList<>(); mShemaPrayer.add(new Prayer(R.string.bed_shema_first_benediction, Prayer.TYPE_MAIN_PRAYER)); mShemaPrayer.add(new Prayer(R.string.bed_shema_shema_intro, Prayer.TYPE_SUBTITLE)); mShemaPrayer.add(new Prayer(R.string.bed_shema_shema, Prayer.TYPE_TITLE)); mShemaPrayer.add(new Prayer(R.string.bed_shema_shema_baruch_shem_kevod, Prayer.TYPE_SUBTITLE)); mShemaPrayer.add(new Prayer(R.string.bed_shema_shema_firstparagraph)); mShemaPrayer.add(new Prayer(R.string.bed_shema_tehilim_01)); mShemaPrayer.add(new Prayer(R.string.bed_shema_tehilim_02)); mShemaPrayer.add(new Prayer(R.string.bed_shema_tehilim_03)); mShemaPrayer.add(new Prayer(R.string.bed_shema_tehilim_04)); mShemaPrayer.add(new Prayer(R.string.bed_shema_tehilim_05)); mShemaPrayer.add(new Prayer(R.string.bed_shema_tehilim_06)); mShemaPrayer.add(new Prayer(R.string.bed_shema_tehilim_07)); mShemaPrayer.add(new Prayer(R.string.bed_shema_three_times, Prayer.TYPE_CAPTION)); mShemaPrayer.add(new Prayer(R.string.bed_shema_tehilim_08)); mShemaPrayer.add(new Prayer(R.string.bed_shema_tehilim_09)); mShemaPrayer.add(new Prayer(R.string.bed_shema_tehilim_10)); mShemaPrayer.add(new Prayer(R.string.bed_shema_tehilim_11)); mShemaPrayer.add(new Prayer(R.string.bed_shema_tehilim_12)); mShemaPrayer.add(new Prayer(R.string.bed_shema_tehilim_13)); return mShemaPrayer; } public static ArrayList<Prayer> getmBirkathHasharar() { // Preparatory Prayers mBirkathHasharar = new ArrayList<>(); mBirkathHasharar.add(new Prayer(R.string.preparatory_prayers_ma_tovu)); mBirkathHasharar.add(new Prayer(R.string.preparatory_prayers_adon_olam)); mBirkathHasharar.add(new Prayer(R.string.preparatory_prayers_netliath)); mBirkathHasharar.add(new Prayer(R.string.preparatory_prayers_asher_yosar)); mBirkathHasharar.add(new Prayer(R.string.preparatory_prayers_elokhai_neshama)); mBirkathHasharar.add(new Prayer(R.string.preparatory_prayers_birkoth_hashachar)); mBirkathHasharar.add(new Prayer(R.string.preparatory_prayers_yehy_rason_1)); mBirkathHasharar.add(new Prayer(R.string.preparatory_prayers_yehy_rason_2)); mBirkathHasharar.add(new Prayer(R.string.preparatory_prayers_yehy_rason_3)); mBirkathHasharar.add(new Prayer(R.string.preparatory_prayers_yehy_rason_4)); mBirkathHasharar.add(new Prayer(R.string.preparatory_prayers_yehy_rason_5)); mBirkathHasharar.add(new Prayer(R.string.preparatory_prayers_yehy_rason_6)); mBirkathHasharar.add(new Prayer(R.string.preparatory_prayers_yehy_rason_7, Prayer.TYPE_TITLE)); mBirkathHasharar.add(new Prayer(R.string.preparatory_prayers_yehy_rason_8)); mBirkathHasharar.add(new Prayer(R.string.preparatory_prayers_yehy_rason_9)); mBirkathHasharar.add(new Prayer(R.string.preparatory_prayers_birkath_hatorah)); mBirkathHasharar.add(new Prayer(R.string.preparatory_prayers_parashath_hatamid)); mBirkathHasharar.add(new Prayer(R.string.preparatory_prayers_parashath_haketoreth_1)); mBirkathHasharar.add(new Prayer(R.string.preparatory_prayers_parashath_haketoreth_2)); mBirkathHasharar.add(new Prayer(R.string.preparatory_prayers_parashath_haketoreth_3)); mBirkathHasharar.add(new Prayer(R.string.preparatory_prayers_korbanoth_rosh_hodesh_title, Prayer.TYPE_CAPTION)); mBirkathHasharar.add(new Prayer(R.string.preparatory_prayers_korbanoth_rosh_hodesh)); mBirkathHasharar.add(new Prayer(R.string.preparatory_prayers_dinei_zvachim_1)); mBirkathHasharar.add(new Prayer(R.string.preparatory_prayers_dinei_zvachim_2)); mBirkathHasharar.add(new Prayer(R.string.preparatory_prayers_dinei_zvachim_3)); mBirkathHasharar.add(new Prayer(R.string.preparatory_prayers_dinei_zvachim_4)); mBirkathHasharar.add(new Prayer(R.string.preparatory_prayers_dinei_zvachim_5)); mBirkathHasharar.add(new Prayer(R.string.preparatory_prayers_dinei_zvachim_6)); mBirkathHasharar.add(new Prayer(R.string.preparatory_prayers_dinei_zvachim_7)); mBirkathHasharar.add(new Prayer(R.string.preparatory_prayers_dinei_zvachim_8)); mBirkathHasharar.add(new Prayer(R.string.preparatory_prayers_divrei_ribbi_yshmael)); mBirkathHasharar.add(new Prayer(R.string.preparatory_prayers_last_yehyeh_chason)); return mBirkathHasharar; } public static ArrayList<Prayer> getmTphilathBH() { // Tphilath BH mTphilathBH = new ArrayList<>(); mTphilathBH.add(new Prayer(R.string.tphilath_bh_before_english_intro, Prayer.TYPE_CAPTION)); mTphilathBH.add(new Prayer(R.string.tphilath_bh_before)); mTphilathBH.add(new Prayer(R.string.tphilath_bh_after_english_intro, Prayer.TYPE_CAPTION)); mTphilathBH.add(new Prayer(R.string.tphilath_bh_after)); return mTphilathBH; } public static ArrayList<Prayer> getmTphilathHaerech() { // Tphilath Haderech mTphilathHaerech = new ArrayList<>(); mTphilathHaerech.add(new Prayer(R.string.travel_prayer)); return mTphilathHaerech; } public static ArrayList<Prayer> getmBirkathHalevanah() { // Birkath Halevanah mBirathHalevanah = new ArrayList<>(); mBirathHalevanah.add(new Prayer(R.string.birkath_halevanah_beroche)); mBirathHalevanah.add(new Prayer(R.string.bed_shema_three_times, Prayer.TYPE_CAPTION)); mBirathHalevanah.add(new Prayer(R.string.birkath_halevanah_yotser)); mBirathHalevanah.add(new Prayer(R.string.bed_shema_three_times, Prayer.TYPE_CAPTION)); mBirathHalevanah.add(new Prayer(R.string.birkath_halevanah_roked)); mBirathHalevanah.add(new Prayer(R.string.bed_shema_three_times, Prayer.TYPE_CAPTION)); mBirathHalevanah.add(new Prayer(R.string.birkath_halevanah_tipol)); mBirathHalevanah.add(new Prayer(R.string.birkath_halevanah_david)); mBirathHalevanah.add(new Prayer(R.string.bed_shema_three_times, Prayer.TYPE_CAPTION)); mBirathHalevanah.add(new Prayer(R.string.birkath_halevanah_shalom)); mBirathHalevanah.add(new Prayer(R.string.bed_shema_three_times, Prayer.TYPE_CAPTION)); mBirathHalevanah.add(new Prayer(R.string.birkath_halevanah_siman_tov)); return mBirathHalevanah; } }
94481b359c776b88ba46c5b21772310f1ba36c1c
{ "blob_id": "94481b359c776b88ba46c5b21772310f1ba36c1c", "branch_name": "refs/heads/master", "committer_date": "2019-02-07T10:33:43", "content_id": "332bc22c873b22bd384ecf97fee4f8b13da8d407", "detected_licenses": [ "MIT" ], "directory_id": "7042b2e0aeea8297e8e4adf0187bd556b9d66f0c", "extension": "java", "filename": "PrayerLists.java", "fork_events_count": 0, "gha_created_at": "2018-10-08T19:36:46", "gha_event_created_at": "2018-11-22T12:51:39", "gha_language": "Java", "gha_license_id": null, "github_id": 152135830, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 7077, "license": "MIT", "license_type": "permissive", "path": "/app/src/main/java/com/thinkhodl/bedshema/backend/PrayerLists.java", "provenance": "stack-edu-0019.json.gz:828247", "repo_name": "ephammer/BedShema", "revision_date": "2019-02-07T10:33:43", "revision_id": "4837bb36bc68d75c891daa98cdc233f452cb37fa", "snapshot_id": "dd2b893b64efa8aaa82ff4dffc7a3a28615fb7af", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ephammer/BedShema/4837bb36bc68d75c891daa98cdc233f452cb37fa/app/src/main/java/com/thinkhodl/bedshema/backend/PrayerLists.java", "visit_date": "2020-03-31T10:28:11.441031", "added": "2024-11-18T21:17:48.930101+00:00", "created": "2019-02-07T10:33:43", "int_score": 2, "score": 2.125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0037.json.gz" }
<?php require $GLOBALS['APP_DIR'] . '/code/community/Sendit/Bliskapaczka/Model/Observer.php'; use PHPUnit\Framework\TestCase; class ObserverTest extends TestCase { protected function setUp() { $this->receiverFirstName = 'Zenek'; $this->receiverLastName = 'Bliskopaczki'; $this->receiverPhoneNumber = '504 445 665'; $this->receiverEmail = '[email protected]'; $this->operatorName = 'INPOST'; $this->destinationCode = 'KRA010'; $this->orderMock = $this->getMockBuilder(Mage_Sales_Model_Order::class) ->disableOriginalConstructor() ->disableOriginalClone() ->disableArgumentCloning() ->disallowMockingUnknownTypes() ->setMethods( array( 'getShippingMethod', 'getShippingAddress' ) ) ->getMock(); $this->observerMock = $this->getMockBuilder(Varien_Event_Observer::class) ->disableOriginalConstructor() ->disableOriginalClone() ->disableArgumentCloning() ->disallowMockingUnknownTypes() ->setMethods(array('getEvent')) ->getMock(); $this->addressMock = $this->getMockBuilder(Mage_Sales_Model_Order_Address::class) ->disableOriginalConstructor() ->disableOriginalClone() ->disableArgumentCloning() ->disallowMockingUnknownTypes() ->setMethods( array( 'getFirstname', 'getLastname', 'getTelephone', 'getEmail', 'getPosOperator', 'getPosCode' ) ) ->getMock(); $this->addressMock->method('getFirstname')->will($this->returnValue($this->receiverFirstName)); $this->addressMock->method('getLastname')->will($this->returnValue($this->receiverLastName)); $this->addressMock->method('getTelephone')->will($this->returnValue($this->receiverPhoneNumber)); $this->addressMock->method('getEmail')->will($this->returnValue($this->receiverEmail)); $this->addressMock->method('getPosOperator')->will($this->returnValue($this->operatorName)); $this->addressMock->method('getPosCode')->will($this->returnValue($this->destinationCode)); } public function testCreateOrderViaApi() { spl_autoload_register(array(Sendit_Bliskapaczka_Model_Observer::class, 'load'), true, true); $event = new Varien_Event(array('order' => $this->orderMock)); $shippingMethod = new Varien_Object( array('method' => 'bliskapaczka_sendit_bliskapaczka', 'carrier_code', 'sendit') ); $this->observerMock->expects($this->once())->method('getEvent')->will($this->returnValue($event)); $this ->orderMock ->expects($this->any()) ->method('getShippingMethod') ->will($this->returnValue($shippingMethod)); $this ->orderMock ->expects($this->any()) ->method('getShippingAddress') ->will($this->returnValue($this->addressMock)); $observer = new Sendit_Bliskapaczka_Model_Observer(); $observer->createOrderViaApi($this->observerMock); } public function testValidateAdminConfiguration() { // spl_autoload_register(array(Sendit_Bliskapaczka_Model_Observer::class, 'load'), true, true); // $observer = new Sendit_Bliskapaczka_Model_Observer(); // $observer->validateAdminConfiguration(); } }
0b03e46e4df838ab0de1f6d80adc0eeffed2f569
{ "blob_id": "0b03e46e4df838ab0de1f6d80adc0eeffed2f569", "branch_name": "refs/heads/master", "committer_date": "2021-02-23T12:33:37", "content_id": "0f85571c1dfa69abf243d932a0725a5cb2468cd9", "detected_licenses": [ "MIT" ], "directory_id": "88956bf683de1f25699ecc603117913ec679547f", "extension": "php", "filename": "ObserverTest.php", "fork_events_count": 3, "gha_created_at": "2017-06-19T13:21:20", "gha_event_created_at": "2021-02-23T12:33:38", "gha_language": "PHP", "gha_license_id": "MIT", "github_id": 94778963, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 4446, "license": "MIT", "license_type": "permissive", "path": "/dev/tests/integration/app/community/Sendit/Bliskapaczka/Model/ObserverTest.php", "provenance": "stack-edu-0048.json.gz:100304", "repo_name": "bliskapaczkapl/magento", "revision_date": "2021-02-23T12:33:37", "revision_id": "a90ceb419b9745c317957abd7ab5235b768beda3", "snapshot_id": "9d80651cde9710bcad2b3fbf0784e3b32f791317", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/bliskapaczkapl/magento/a90ceb419b9745c317957abd7ab5235b768beda3/dev/tests/integration/app/community/Sendit/Bliskapaczka/Model/ObserverTest.php", "visit_date": "2021-05-23T06:04:53.082787", "added": "2024-11-18T23:32:08.577310+00:00", "created": "2021-02-23T12:33:37", "int_score": 2, "score": 2.296875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0066.json.gz" }
use std::collections::VecDeque; use std::io::{self, Read}; use crate::disk::block::BlockDeviceRef; use crate::disk::block::Location; use crate::disk::block::BLOCK_SIZE; use crate::disk::chain::{ChainIterator, ChainReader}; use crate::disk::directory::{self, DirectoryEntry}; use crate::disk::DiskError; use crate::disk::geos::GEOSDirectoryEntry; /// A block can store 254 bytes of data -- the 256 full block size, minus 2 /// bytes for the next track and sector pointer. const BLOCK_DATA_SIZE: usize = BLOCK_SIZE - 2; enum GEOSReaderState { DirectoryEntry, InfoBlock, VLIRIndexBlock, Records, Finished, } /// A GEOSReader serializes a complex GEOS file into a flat byte stream in a /// manner compatible with the GEOS Convert utility. This preserves directory /// entry metadata, info blocks, and VLIR records. pub struct GEOSReader { blocks: BlockDeviceRef, state: GEOSReaderState, buffer: Vec<u8>, is_vlir: bool, info_location: Location, start_location: Location, chains: VecDeque<ChainReader>, } impl GEOSReader { /// Create a new GEOSReader for serializing the GEOS file at the provided /// directory entry. pub fn new(blocks: BlockDeviceRef, entry: &DirectoryEntry) -> io::Result<GEOSReader> { const CVT_SIGNATURE_OFFSET: usize = 0x20; const CVT_SIGNATURE_PRG: &[u8] = b"PRG"; const CVT_SIGNATURE_SEQ: &[u8] = b"SEQ"; const CVT_SIGNATURE_SUFFIX: &[u8] = b" formatted GEOS file V1.0"; // Construct the initial 254-byte data block which contains a copy of the // original directory entry and any extra implementation-specific data // such as the signature string. let mut buffer = [0; BLOCK_SIZE].to_vec(); // Load the directory entry bytes entry.to_bytes(&mut buffer[0..directory::ENTRY_SIZE]); // Write the signature string. I don't think this is required, but both the // GEOS Convert2.5 program and Vice's c1541 seem to add this. if entry.is_vlir()? { buffer[CVT_SIGNATURE_OFFSET..CVT_SIGNATURE_OFFSET + 3] .copy_from_slice(CVT_SIGNATURE_PRG); } else { buffer[CVT_SIGNATURE_OFFSET..CVT_SIGNATURE_OFFSET + 3] .copy_from_slice(CVT_SIGNATURE_SEQ); } buffer[CVT_SIGNATURE_OFFSET + 3..CVT_SIGNATURE_OFFSET + 3 + CVT_SIGNATURE_SUFFIX.len()] .copy_from_slice(CVT_SIGNATURE_SUFFIX); // Remove the would-be NTS (next track and sector) link. buffer.drain(0..2); assert!(buffer.len() == BLOCK_DATA_SIZE); Ok(GEOSReader { blocks, state: GEOSReaderState::DirectoryEntry, buffer, is_vlir: entry.is_vlir()?, info_location: entry .info_location()? .ok_or_else(|| DiskError::GEOSInfoNotFound.to_io_error())?, start_location: entry.first_sector, chains: VecDeque::new(), }) } /// Process the VLIR index block by converting (track, sector) pairs into /// (block count, bytes used in the final block) pairs. Along the way, /// accumulate the ChainReaders that will be needed to read the VLIR /// records in the Records state. fn process_vlir_index_block(&mut self) -> io::Result<()> { let blocks = self.blocks.borrow(); let mut index_block = blocks.sector(self.start_location)?[2..].to_vec(); /// Scan the chain and return the number of blocks used, and the number /// of bytes used in the final block. fn scan_chain(blocks: BlockDeviceRef, start: Location) -> io::Result<(u8, u8)> { let (count, last) = ChainIterator::new(blocks, start).fold(Ok((0, 0)), |acc, b| { acc.and_then(|(count, _last)| { // Note we subtract one from the data length to convert to CBM's "offset of last // used byte within the full block containing a two block track and sector // prefix". b.map(|b| (count + 1, b.data.len() - 1)) }) })?; if count > ::std::u8::MAX as usize { return Err(DiskError::RecordTooLarge.into()); } assert!(last <= ::std::u8::MAX as usize); Ok((count as u8, last as u8)) } // For every pair of bytes in the index block, generate an optional chain // reader, the block count, and the number of bytes used in the final // block. let (chains, conversions): (Vec<Option<ChainReader>>, Vec<(u8, u8)>) = index_block .chunks_mut(2) .take_while(|chunk| chunk[0] != 0x00 || chunk[1] != 0x00) .map(|chunk| { if chunk[0] == 0x00 && chunk[1] == 0xFF { // Empty record Ok((None, (0x00, 0xFF))) } else { let record_start = Location::from_bytes(chunk); let (count, last) = scan_chain(self.blocks.clone(), record_start)?; let reader = ChainReader::new(self.blocks.clone(), record_start); Ok((Some(reader), (count, last))) } }) .collect::<io::Result<Vec<_>>>()? .into_iter() .unzip(); // Render the new VLIR block where (track, sector) pairs have been converted // into (block count, final bytes) pairs. let mut block = conversions .iter() .fold(Vec::with_capacity(BLOCK_DATA_SIZE), |mut v, conversion| { v.push(conversion.0); v.push(conversion.1); v }); // Pad remainder of block with zeros. block.resize(BLOCK_DATA_SIZE, 0); // The converted index block will be fed to the reader in VLIRIndexBlock state. self.buffer = block; // Save the chain readers for later processing in the Records state. self.chains = chains.into_iter().flatten().collect(); Ok(()) } /// Transition to the next state, loading the buffer with the bytes to be /// read in the new state. fn next_state(&mut self) -> io::Result<()> { match self.state { GEOSReaderState::DirectoryEntry => { // Transition to reading the GEOS info block. self.state = GEOSReaderState::InfoBlock; let blocks = self.blocks.borrow(); let info_block = blocks.sector(self.info_location)?; self.buffer = info_block[2..].to_vec(); } GEOSReaderState::InfoBlock => { if self.is_vlir { // Transition to reading the VLIR index block. self.state = GEOSReaderState::VLIRIndexBlock; // Convert the VLIR index block and initialize chain readers. self.process_vlir_index_block()?; } else { // If this is a sequential file, start reading the single record. self.state = GEOSReaderState::Records; self.chains .push_back(ChainReader::new(self.blocks.clone(), self.start_location)); } } GEOSReaderState::VLIRIndexBlock => { self.state = GEOSReaderState::Records; self.next_state()?; } GEOSReaderState::Records => { match self.chains.pop_front() { Some(mut chain) => { chain.read_to_end(&mut self.buffer)?; // Pad to a multiple of BLOCK_DATA_SIZE unless this is the last record. if !self.chains.is_empty() { let remainder = self.buffer.len() % BLOCK_DATA_SIZE; if remainder > 0 { let padded_size = self.buffer.len() + BLOCK_DATA_SIZE - remainder; self.buffer.resize(padded_size, 0); } } } None => self.state = GEOSReaderState::Finished, } } GEOSReaderState::Finished => {} }; Ok(()) } } impl Read for GEOSReader { fn read(&mut self, mut buf: &mut [u8]) -> io::Result<usize> { if let GEOSReaderState::Finished = self.state { return Ok(0); } let mut bytes_written: usize = 0; loop { let bytes = buf.len().min(self.buffer.len()); // Write bytes let _ = &mut buf[..bytes].copy_from_slice(&self.buffer[..bytes]); bytes_written += bytes; if bytes == buf.len() { // Output buffer filled -- nothing more to do for now. break; } // Reduce the output buffer to the unwritten portion. let buf_ref = &mut buf; let value: &mut [u8] = std::mem::take(buf_ref); *buf_ref = &mut value[bytes..]; // Reduce the input buffer self.buffer.drain(0..bytes); // Input buffer drained -- transition to next step if self.buffer.is_empty() { // State transition self.next_state()?; if let GEOSReaderState::Finished = self.state { break; } } } Ok(bytes_written) } }
4b652afb3e744decb1a38c601b6ad9ce90c4d2d7
{ "blob_id": "4b652afb3e744decb1a38c601b6ad9ce90c4d2d7", "branch_name": "refs/heads/master", "committer_date": "2022-12-24T15:45:47", "content_id": "dfa2a1ca11f0556c1b1b247592d18dd3aa78d436", "detected_licenses": [ "Apache-2.0", "MIT" ], "directory_id": "71e5688ba6778931a86b46012f813449bfd89edc", "extension": "rs", "filename": "reader.rs", "fork_events_count": 4, "gha_created_at": "2018-06-26T23:27:09", "gha_event_created_at": "2023-01-04T18:25:51", "gha_language": "Rust", "gha_license_id": "Apache-2.0", "github_id": 138804434, "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 9611, "license": "Apache-2.0,MIT", "license_type": "permissive", "path": "/src/disk/geos/reader.rs", "provenance": "stack-edu-0067.json.gz:733918", "repo_name": "simmons/cbm", "revision_date": "2022-12-24T15:45:47", "revision_id": "103793b6d0137a088a320a9d0232168fb2964e29", "snapshot_id": "2101cfbeb3c0d5cfb1b431e62c96e079dcef38d1", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/simmons/cbm/103793b6d0137a088a320a9d0232168fb2964e29/src/disk/geos/reader.rs", "visit_date": "2023-01-09T17:31:57.155859", "added": "2024-11-18T23:20:01.001998+00:00", "created": "2022-12-24T15:45:47", "int_score": 2, "score": 2.453125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0085.json.gz" }
namespace BLEMotionInstaller { partial class Form1 { /// <summary> /// 必要なデザイナー変数です。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 使用中のリソースをすべてクリーンアップします。 /// </summary> /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows フォーム デザイナーで生成されたコード /// <summary> /// デザイナー サポートに必要なメソッドです。このメソッドの内容を /// コード エディターで変更しないでください。 /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); this.cmbBoxMode = new System.Windows.Forms.ComboBox(); this.statusStrip1 = new System.Windows.Forms.StatusStrip(); this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel(); this.toolStripStatusLabelPadding = new System.Windows.Forms.ToolStripStatusLabel(); this.toolStripStatusLabel2 = new System.Windows.Forms.ToolStripStatusLabel(); this.labelSendCmdCnt = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.button3 = new System.Windows.Forms.Button(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.button2 = new System.Windows.Forms.Button(); this.textBox1 = new System.Windows.Forms.TextBox(); this.button1 = new System.Windows.Forms.Button(); this.listBox1 = new System.Windows.Forms.ListBox(); this.label4 = new System.Windows.Forms.Label(); this.statusStrip1.SuspendLayout(); this.SuspendLayout(); // // cmbBoxMode // this.cmbBoxMode.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbBoxMode.FormattingEnabled = true; this.cmbBoxMode.Items.AddRange(new object[] { "BLE", "USB"}); this.cmbBoxMode.Location = new System.Drawing.Point(116, 75); this.cmbBoxMode.Name = "cmbBoxMode"; this.cmbBoxMode.Size = new System.Drawing.Size(71, 20); this.cmbBoxMode.TabIndex = 20; this.cmbBoxMode.SelectedIndexChanged += new System.EventHandler(this.cmbBoxMode_SelectedIndexChanged); // // statusStrip1 // this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripStatusLabel1, this.toolStripStatusLabelPadding, this.toolStripStatusLabel2}); this.statusStrip1.Location = new System.Drawing.Point(0, 390); this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.Size = new System.Drawing.Size(688, 22); this.statusStrip1.TabIndex = 19; this.statusStrip1.Text = "statusStrip1"; // // toolStripStatusLabel1 // this.toolStripStatusLabel1.Name = "toolStripStatusLabel1"; this.toolStripStatusLabel1.Size = new System.Drawing.Size(0, 17); // // toolStripStatusLabelPadding // this.toolStripStatusLabelPadding.Name = "toolStripStatusLabelPadding"; this.toolStripStatusLabelPadding.Size = new System.Drawing.Size(396, 17); this.toolStripStatusLabelPadding.Spring = true; // // toolStripStatusLabel2 // this.toolStripStatusLabel2.Name = "toolStripStatusLabel2"; this.toolStripStatusLabel2.Size = new System.Drawing.Size(277, 17); this.toolStripStatusLabel2.Text = "Sum of the PLEN that have sent command : 0"; // // labelSendCmdCnt // this.labelSendCmdCnt.AutoSize = true; this.labelSendCmdCnt.Location = new System.Drawing.Point(222, 11); this.labelSendCmdCnt.Name = "labelSendCmdCnt"; this.labelSendCmdCnt.Size = new System.Drawing.Size(11, 12); this.labelSendCmdCnt.TabIndex = 18; this.labelSendCmdCnt.Text = "0"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(12, 11); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(210, 12); this.label3.TabIndex = 17; this.label3.Text = "Sum of the motions that will have sent :"; // // button3 // this.button3.Location = new System.Drawing.Point(89, 34); this.button3.Name = "button3"; this.button3.Size = new System.Drawing.Size(110, 26); this.button3.TabIndex = 16; this.button3.Text = "Load Motion(s)"; this.button3.UseVisualStyleBackColor = true; this.button3.Click += new System.EventHandler(this.button3_Click); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(18, 108); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(78, 12); this.label2.TabIndex = 15; this.label2.Text = "COM Port List"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(181, 108); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(20, 12); this.label1.TabIndex = 14; this.label1.Text = "log"; // // button2 // this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.button2.Enabled = false; this.button2.Location = new System.Drawing.Point(489, 34); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(110, 26); this.button2.TabIndex = 13; this.button2.Text = "Abort All Process"; this.button2.UseVisualStyleBackColor = true; this.button2.Click += new System.EventHandler(this.button2_Click); // // textBox1 // this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBox1.Location = new System.Drawing.Point(173, 124); this.textBox1.Multiline = true; this.textBox1.Name = "textBox1"; this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.textBox1.Size = new System.Drawing.Size(498, 262); this.textBox1.TabIndex = 12; // // button1 // this.button1.Anchor = System.Windows.Forms.AnchorStyles.Top; this.button1.Location = new System.Drawing.Point(289, 34); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(110, 26); this.button1.TabIndex = 11; this.button1.Text = "Install Motion(s)"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // listBox1 // this.listBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.listBox1.FormattingEnabled = true; this.listBox1.ItemHeight = 12; this.listBox1.Location = new System.Drawing.Point(18, 124); this.listBox1.Name = "listBox1"; this.listBox1.SelectionMode = System.Windows.Forms.SelectionMode.MultiSimple; this.listBox1.Size = new System.Drawing.Size(128, 256); this.listBox1.TabIndex = 10; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(18, 79); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(95, 12); this.label4.TabIndex = 21; this.label4.Text = "Transfer methods"; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(688, 412); this.Controls.Add(this.label4); this.Controls.Add(this.cmbBoxMode); this.Controls.Add(this.statusStrip1); this.Controls.Add(this.labelSendCmdCnt); this.Controls.Add(this.label3); this.Controls.Add(this.button3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.button2); this.Controls.Add(this.textBox1); this.Controls.Add(this.button1); this.Controls.Add(this.listBox1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "Form1"; this.Text = "PLEN - Motion Installer"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing); this.Load += new System.EventHandler(this.Form1_Load); this.statusStrip1.ResumeLayout(false); this.statusStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.StatusStrip statusStrip1; private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1; private System.Windows.Forms.Label labelSendCmdCnt; private System.Windows.Forms.Label label3; private System.Windows.Forms.Button button3; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button button2; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Button button1; private System.Windows.Forms.ListBox listBox1; private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabelPadding; private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel2; private System.Windows.Forms.ComboBox cmbBoxMode; private System.Windows.Forms.Label label4; } }
512e2119c08f317fa764035333faf5358ef4398c
{ "blob_id": "512e2119c08f317fa764035333faf5358ef4398c", "branch_name": "refs/heads/master", "committer_date": "2017-01-16T02:49:25", "content_id": "7019fa624b38148d02ee31b9fcd48c64b181ef63", "detected_licenses": [ "MIT" ], "directory_id": "bac7ab9eb4ee8a88bd8874cca1fe1712754e445f", "extension": "cs", "filename": "Form1.Designer.cs", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 56200574, "is_generated": true, "is_vendor": false, "language": "C#", "length_bytes": 11566, "license": "MIT", "license_type": "permissive", "path": "/src/Form1.Designer.cs", "provenance": "stack-edu-0014.json.gz:381387", "repo_name": "plen-admin/plen-MotionInstaller_Win", "revision_date": "2017-01-16T02:49:25", "revision_id": "4411defd37492da56df5c34b43890d77023cd17b", "snapshot_id": "a4e704b3f255672e0f8ea4b21d731cdca192c83c", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/plen-admin/plen-MotionInstaller_Win/4411defd37492da56df5c34b43890d77023cd17b/src/Form1.Designer.cs", "visit_date": "2021-06-09T20:11:21.406559", "added": "2024-11-19T00:33:55.073930+00:00", "created": "2017-01-16T02:49:25", "int_score": 2, "score": 2.015625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0032.json.gz" }
[![CircleCI](https://circleci.com/gh/muramurasan/okuribito_rails.svg?style=svg)](https://circleci.com/gh/muramurasan/okuribito_rails) [![Code Climate](https://codeclimate.com/github/muramurasan/okuribito_rails.png)](https://codeclimate.com/github/muramurasan/okuribito_rails) [![Test Coverage](https://codeclimate.com/github/muramurasan/okuribito_rails/badges/coverage.svg)](https://codeclimate.com/github/muramurasan/okuribito_rails/coverage) # OkuribitoRails https://rubygems.org/gems/okuribito_rails ![Sample](https://raw.githubusercontent.com/muramurasan/okuribito_rails/master/doc/method_call_situations.png) OkuribitoRails is an engine for Rails that aims to manage method call status. OkuribitoRails monitors method calls with YAML. You can identify methods that have not been called from anywhere! # Features Here's a comprehensive list of the features currently in OkuribitoRails: * Monitoring method call * During application execution, monitor specified method calls * After detecting the method call, register the call history in the DB * You can enable or disable monitoring of method calls (depending on RAILS_ENV) * Web UI * Viewing monitored methods * Viewing call history of monitored methods * You can hide or show WebUI (depending on RAILS_ENV) # Getting started Please read [Getting Started](https://github.com/muramurasan/okuribito_rails/wiki/Getting-Started). # More information The following link have useful information on using OkuribitoRails. https://github.com/muramurasan/okuribito_rails/wiki # Caution! Sorry, OkuribitoRails does not support helper method monitoring. # License The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
ebf11e19337e8c19cbd50a94f95a5ef0008dd39e
{ "blob_id": "ebf11e19337e8c19cbd50a94f95a5ef0008dd39e", "branch_name": "refs/heads/master", "committer_date": "2020-12-25T08:57:30", "content_id": "02e7700c78383f29ff0f43ce2cbcc7a3b301e088", "detected_licenses": [ "MIT" ], "directory_id": "89e07a2e29a5bf1e02b969226fff968c176fa872", "extension": "md", "filename": "README.md", "fork_events_count": 0, "gha_created_at": "2020-12-25T08:51:13", "gha_event_created_at": "2020-12-25T08:57:31", "gha_language": null, "gha_license_id": "MIT", "github_id": 324325413, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1751, "license": "MIT", "license_type": "permissive", "path": "/README.md", "provenance": "stack-edu-markdown-0009.json.gz:218818", "repo_name": "strviola/okuribito_rails", "revision_date": "2020-12-25T08:57:30", "revision_id": "e409dce59cc04249b4d32c9e513449b4901c9428", "snapshot_id": "a77b41d8932a136e508779b1f38d97e295c9659d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/strviola/okuribito_rails/e409dce59cc04249b4d32c9e513449b4901c9428/README.md", "visit_date": "2023-02-04T02:43:07.533987", "added": "2024-11-18T22:43:15.426685+00:00", "created": "2020-12-25T08:57:30", "int_score": 3, "score": 3.375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0009.json.gz" }
#py_calendar.py import calendar #create a TextCalendar instance cal = calendar.TextCalendar() print("We just produced a {}.\n".format(type(cal))) print("Let's check out the calendar for April, 2016\n") calendar.prmonth(2016,4) print() #what day of the week was I born? birthday_year=1957 birthday_month=5 birthday_day=10 birthday_day_of_week=calendar.weekday(birthday_year, birthday_month, birthday_day) birthday_dict={0:'Mon', 1:'Tue', 2:'Wed', 3:'Thur', 4:'Fri', 5:'Sat', 6:'Sun'} print("I was born on a {}".format(birthday_dict[birthday_day_of_week]))
57c42faa61bb7a08b75099a6494d4406d1253d3a
{ "blob_id": "57c42faa61bb7a08b75099a6494d4406d1253d3a", "branch_name": "refs/heads/main", "committer_date": "2021-04-23T19:15:56", "content_id": "6d965215ad9658078eb56731f83dad1992fac7aa", "detected_licenses": [ "MIT" ], "directory_id": "234458aada8348533041bfb39a5807a49e2eabd6", "extension": "py", "filename": "py_calendar.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 351913353, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 638, "license": "MIT", "license_type": "permissive", "path": "/dkr-py310/docker-student-portal-310/course_files/begin_advanced/py_calendar.py", "provenance": "stack-edu-0058.json.gz:192146", "repo_name": "pbarton666/virtual_classroom", "revision_date": "2021-04-23T19:15:56", "revision_id": "a9d0dc2eb16ebc4d2fd451c3a3e6f96e37c87675", "snapshot_id": "89fa5fdfa957f853847e8e4de19983180b19ef23", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/pbarton666/virtual_classroom/a9d0dc2eb16ebc4d2fd451c3a3e6f96e37c87675/dkr-py310/docker-student-portal-310/course_files/begin_advanced/py_calendar.py", "visit_date": "2023-04-15T21:16:05.863254", "added": "2024-11-18T21:10:56.507237+00:00", "created": "2021-04-23T19:15:56", "int_score": 4, "score": 4.15625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0076.json.gz" }
/* * Copyright (c) 2020 SAP SE or an SAP affiliate company. All rights reserved. * * This is a generated file powered by the SAP Cloud SDK for JavaScript. */ import { Testentity_1RequestBuilder } from './Testentity_1RequestBuilder'; import { Moment } from 'moment'; import { BigNumber } from 'bignumber.js'; import { TestComplexType, TestComplexTypeField } from './TestComplexType'; import { AllFields, AnyField, BigNumberField, BooleanField, CustomFieldV2, DateField, EntityBuilderType, EntityV2, Field, Link, NumberField, OneToOneLink, StringField, Time, TimeField } from '../../../../../src'; /** * This class represents the entity "A_Testentity" of service "API_TEST_SRV". */ export class Testentity_1 extends EntityV2 implements Testentity_1Type { /** * Technical entity name for Testentity_1. */ static _entityName = 'A_Testentity'; /** * Default url path for the according service. */ static _defaultServicePath = '/sap/opu/odata/sap/API_TEST_SRV'; /** * Key Property Guid. */ keyPropertyGuid!: string; /** * Key Property String. */ keyPropertyString!: string; /** * String Property. * Maximum length: 10. * @nullable */ stringProperty?: string; /** * Boolean Property. * @nullable */ booleanProperty?: boolean; /** * Guid Property. * @nullable */ guidProperty?: string; /** * Int 16 Property. * @nullable */ int16Property?: number; /** * Int 32 Property. * @nullable */ int32Property?: number; /** * Int 64 Property. * @nullable */ int64Property?: BigNumber; /** * Decimal Property. * @nullable */ decimalProperty?: BigNumber; /** * Single Property. * @nullable */ singleProperty?: number; /** * Double Property. * @nullable */ doubleProperty?: number; /** * Float Property. * @nullable */ floatProperty?: number; /** * Time Property. * @nullable */ timeProperty?: Time; /** * Date Time Property. * @nullable */ dateTimeProperty?: Moment; /** * Date Time Off Set Property. * @nullable */ dateTimeOffSetProperty?: Moment; /** * Byte Property. * @nullable */ byteProperty?: number; /** * S Byte Property. * @nullable */ sByteProperty?: number; /** * Something The Sdk Does Not Support. * @nullable */ somethingTheSdkDoesNotSupport?: any; /** * Complex Type Property. * @nullable */ complexTypeProperty?: TestComplexType; /** * One-to-many navigation property to the [[TestEntityMultiLink]] entity. */ toMultiLink!: TestEntityMultiLink[]; /** * One-to-many navigation property to the [[TestEntityOtherMultiLink]] entity. */ toOtherMultiLink!: TestEntityOtherMultiLink[]; /** * One-to-one navigation property to the [[TestEntitySingleLink]] entity. */ toSingleLink!: TestEntitySingleLink; /** * Returns an entity builder to construct instances of `Testentity_1`. * @returns A builder that constructs instances of entity type `Testentity_1`. */ static builder(): EntityBuilderType<Testentity_1, Testentity_1Type> { return EntityV2.entityBuilder(Testentity_1); } /** * Returns a request builder to construct requests for operations on the `Testentity_1` entity type. * @returns A `Testentity_1` request builder. */ static requestBuilder(): Testentity_1RequestBuilder { return new Testentity_1RequestBuilder(); } /** * Returns a selectable object that allows the selection of custom field in a get request for the entity `Testentity_1`. * @param fieldName Name of the custom field to select * @returns A builder that constructs instances of entity type `Testentity_1`. */ static customField(fieldName: string): CustomFieldV2<Testentity_1> { return EntityV2.customFieldSelector(fieldName, Testentity_1); } /** * Overwrites the default toJSON method so that all instance variables as well as all custom fields of the entity are returned. * @returns An object containing all instance variables + custom fields. */ toJSON(): { [key: string]: any } { return { ...this, ...this._customFields }; } } import { TestEntityMultiLink, TestEntityMultiLinkType } from './TestEntityMultiLink'; import { TestEntityOtherMultiLink, TestEntityOtherMultiLinkType } from './TestEntityOtherMultiLink'; import { TestEntitySingleLink, TestEntitySingleLinkType } from './TestEntitySingleLink'; export interface Testentity_1Type { keyPropertyGuid: string; keyPropertyString: string; stringProperty?: string | null; booleanProperty?: boolean | null; guidProperty?: string | null; int16Property?: number | null; int32Property?: number | null; int64Property?: BigNumber | null; decimalProperty?: BigNumber | null; singleProperty?: number | null; doubleProperty?: number | null; floatProperty?: number | null; timeProperty?: Time | null; dateTimeProperty?: Moment | null; dateTimeOffSetProperty?: Moment | null; byteProperty?: number | null; sByteProperty?: number | null; somethingTheSdkDoesNotSupport?: any | null; complexTypeProperty?: TestComplexType | null; toMultiLink: TestEntityMultiLinkType[]; toOtherMultiLink: TestEntityOtherMultiLinkType[]; toSingleLink: TestEntitySingleLinkType; } export namespace Testentity_1 { /** * Static representation of the [[keyPropertyGuid]] property for query construction. * Use to reference this property in query operations such as 'select' in the fluent request API. */ export const KEY_PROPERTY_GUID: StringField<Testentity_1> = new StringField('KeyPropertyGuid', Testentity_1, 'Edm.Guid'); /** * Static representation of the [[keyPropertyString]] property for query construction. * Use to reference this property in query operations such as 'select' in the fluent request API. */ export const KEY_PROPERTY_STRING: StringField<Testentity_1> = new StringField('KeyPropertyString', Testentity_1, 'Edm.String'); /** * Static representation of the [[stringProperty]] property for query construction. * Use to reference this property in query operations such as 'select' in the fluent request API. */ export const STRING_PROPERTY: StringField<Testentity_1> = new StringField('StringProperty', Testentity_1, 'Edm.String'); /** * Static representation of the [[booleanProperty]] property for query construction. * Use to reference this property in query operations such as 'select' in the fluent request API. */ export const BOOLEAN_PROPERTY: BooleanField<Testentity_1> = new BooleanField('BooleanProperty', Testentity_1, 'Edm.Boolean'); /** * Static representation of the [[guidProperty]] property for query construction. * Use to reference this property in query operations such as 'select' in the fluent request API. */ export const GUID_PROPERTY: StringField<Testentity_1> = new StringField('GuidProperty', Testentity_1, 'Edm.Guid'); /** * Static representation of the [[int16Property]] property for query construction. * Use to reference this property in query operations such as 'select' in the fluent request API. */ export const INT_16_PROPERTY: NumberField<Testentity_1> = new NumberField('Int16Property', Testentity_1, 'Edm.Int16'); /** * Static representation of the [[int32Property]] property for query construction. * Use to reference this property in query operations such as 'select' in the fluent request API. */ export const INT_32_PROPERTY: NumberField<Testentity_1> = new NumberField('Int32Property', Testentity_1, 'Edm.Int32'); /** * Static representation of the [[int64Property]] property for query construction. * Use to reference this property in query operations such as 'select' in the fluent request API. */ export const INT_64_PROPERTY: BigNumberField<Testentity_1> = new BigNumberField('Int64Property', Testentity_1, 'Edm.Int64'); /** * Static representation of the [[decimalProperty]] property for query construction. * Use to reference this property in query operations such as 'select' in the fluent request API. */ export const DECIMAL_PROPERTY: BigNumberField<Testentity_1> = new BigNumberField('DecimalProperty', Testentity_1, 'Edm.Decimal'); /** * Static representation of the [[singleProperty]] property for query construction. * Use to reference this property in query operations such as 'select' in the fluent request API. */ export const SINGLE_PROPERTY: NumberField<Testentity_1> = new NumberField('SingleProperty', Testentity_1, 'Edm.Single'); /** * Static representation of the [[doubleProperty]] property for query construction. * Use to reference this property in query operations such as 'select' in the fluent request API. */ export const DOUBLE_PROPERTY: NumberField<Testentity_1> = new NumberField('DoubleProperty', Testentity_1, 'Edm.Double'); /** * Static representation of the [[floatProperty]] property for query construction. * Use to reference this property in query operations such as 'select' in the fluent request API. */ export const FLOAT_PROPERTY: NumberField<Testentity_1> = new NumberField('FloatProperty', Testentity_1, 'Edm.Float'); /** * Static representation of the [[timeProperty]] property for query construction. * Use to reference this property in query operations such as 'select' in the fluent request API. */ export const TIME_PROPERTY: TimeField<Testentity_1> = new TimeField('TimeProperty', Testentity_1, 'Edm.Time'); /** * Static representation of the [[dateTimeProperty]] property for query construction. * Use to reference this property in query operations such as 'select' in the fluent request API. */ export const DATE_TIME_PROPERTY: DateField<Testentity_1> = new DateField('DateTimeProperty', Testentity_1, 'Edm.DateTime'); /** * Static representation of the [[dateTimeOffSetProperty]] property for query construction. * Use to reference this property in query operations such as 'select' in the fluent request API. */ export const DATE_TIME_OFF_SET_PROPERTY: DateField<Testentity_1> = new DateField('DateTimeOffSetProperty', Testentity_1, 'Edm.DateTimeOffset'); /** * Static representation of the [[byteProperty]] property for query construction. * Use to reference this property in query operations such as 'select' in the fluent request API. */ export const BYTE_PROPERTY: NumberField<Testentity_1> = new NumberField('ByteProperty', Testentity_1, 'Edm.Byte'); /** * Static representation of the [[sByteProperty]] property for query construction. * Use to reference this property in query operations such as 'select' in the fluent request API. */ export const S_BYTE_PROPERTY: NumberField<Testentity_1> = new NumberField('SByteProperty', Testentity_1, 'Edm.SByte'); /** * Static representation of the [[somethingTheSdkDoesNotSupport]] property for query construction. * Use to reference this property in query operations such as 'select' in the fluent request API. */ export const SOMETHING_THE_SDK_DOES_NOT_SUPPORT: AnyField<Testentity_1> = new AnyField('SomethingTheSDKDoesNotSupport', Testentity_1, 'Edm.Any'); /** * Static representation of the [[complexTypeProperty]] property for query construction. * Use to reference this property in query operations such as 'select' in the fluent request API. */ export const COMPLEX_TYPE_PROPERTY: TestComplexTypeField<Testentity_1> = new TestComplexTypeField('ComplexTypeProperty', Testentity_1); /** * Static representation of the one-to-many navigation property [[toMultiLink]] for query construction. * Use to reference this property in query operations such as 'select' in the fluent request API. */ export const TO_MULTI_LINK: Link<Testentity_1, TestEntityMultiLink> = new Link('to_MultiLink', Testentity_1, TestEntityMultiLink); /** * Static representation of the one-to-many navigation property [[toOtherMultiLink]] for query construction. * Use to reference this property in query operations such as 'select' in the fluent request API. */ export const TO_OTHER_MULTI_LINK: Link<Testentity_1, TestEntityOtherMultiLink> = new Link('to_OtherMultiLink', Testentity_1, TestEntityOtherMultiLink); /** * Static representation of the one-to-one navigation property [[toSingleLink]] for query construction. * Use to reference this property in query operations such as 'select' in the fluent request API. */ export const TO_SINGLE_LINK: OneToOneLink<Testentity_1, TestEntitySingleLink> = new OneToOneLink('to_SingleLink', Testentity_1, TestEntitySingleLink); /** * All fields of the Testentity_1 entity. */ export const _allFields: Array<StringField<Testentity_1> | BooleanField<Testentity_1> | NumberField<Testentity_1> | BigNumberField<Testentity_1> | TimeField<Testentity_1> | DateField<Testentity_1> | AnyField<Testentity_1> | TestComplexTypeField<Testentity_1> | Link<Testentity_1, TestEntityMultiLink> | Link<Testentity_1, TestEntityOtherMultiLink> | OneToOneLink<Testentity_1, TestEntitySingleLink>> = [ Testentity_1.KEY_PROPERTY_GUID, Testentity_1.KEY_PROPERTY_STRING, Testentity_1.STRING_PROPERTY, Testentity_1.BOOLEAN_PROPERTY, Testentity_1.GUID_PROPERTY, Testentity_1.INT_16_PROPERTY, Testentity_1.INT_32_PROPERTY, Testentity_1.INT_64_PROPERTY, Testentity_1.DECIMAL_PROPERTY, Testentity_1.SINGLE_PROPERTY, Testentity_1.DOUBLE_PROPERTY, Testentity_1.FLOAT_PROPERTY, Testentity_1.TIME_PROPERTY, Testentity_1.DATE_TIME_PROPERTY, Testentity_1.DATE_TIME_OFF_SET_PROPERTY, Testentity_1.BYTE_PROPERTY, Testentity_1.S_BYTE_PROPERTY, Testentity_1.SOMETHING_THE_SDK_DOES_NOT_SUPPORT, Testentity_1.COMPLEX_TYPE_PROPERTY, Testentity_1.TO_MULTI_LINK, Testentity_1.TO_OTHER_MULTI_LINK, Testentity_1.TO_SINGLE_LINK ]; /** * All fields selector. */ export const ALL_FIELDS: AllFields<Testentity_1> = new AllFields('*', Testentity_1); /** * All key fields of the Testentity_1 entity. */ export const _keyFields: Array<Field<Testentity_1>> = [Testentity_1.KEY_PROPERTY_GUID, Testentity_1.KEY_PROPERTY_STRING]; /** * Mapping of all key field names to the respective static field property Testentity_1. */ export const _keys: { [keys: string]: Field<Testentity_1> } = Testentity_1._keyFields.reduce((acc: { [keys: string]: Field<Testentity_1> }, field: Field<Testentity_1>) => { acc[field._fieldName] = field; return acc; }, {}); }
91e8445a3b45d0da38f14f90237352d699508773
{ "blob_id": "91e8445a3b45d0da38f14f90237352d699508773", "branch_name": "refs/heads/main", "committer_date": "2021-02-12T06:39:44", "content_id": "65ea06c645fa69723a9afb3a7881323d1206978d", "detected_licenses": [ "Apache-2.0" ], "directory_id": "66aa5bb77275ad640ebe807e85884bab6580d092", "extension": "ts", "filename": "Testentity_1.ts", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 14517, "license": "Apache-2.0", "license_type": "permissive", "path": "/packages/core/test/test-util/test-services/v2/test-service/Testentity_1.ts", "provenance": "stack-edu-0073.json.gz:236043", "repo_name": "blaart/cloud-sdk-js", "revision_date": "2021-02-12T06:39:44", "revision_id": "fec0bf271288dcdab9fda28e786a7ff0a9fa061b", "snapshot_id": "57febaab14fca1873eacc7893a2923ad4b31da21", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/blaart/cloud-sdk-js/fec0bf271288dcdab9fda28e786a7ff0a9fa061b/packages/core/test/test-util/test-services/v2/test-service/Testentity_1.ts", "visit_date": "2023-03-03T16:33:50.824713", "added": "2024-11-18T20:57:14.019365+00:00", "created": "2021-02-12T06:39:44", "int_score": 2, "score": 2.046875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0091.json.gz" }
Removes and returns the first element of the list stored at `key`. @return @bulk-string-reply: the value of the first element, or `nil` when `key` does not exist. @examples ```cli RPUSH mylist "one" RPUSH mylist "two" RPUSH mylist "three" LPOP mylist LRANGE mylist 0 -1 ```
8cb076676576890a3d40e0323a4d318587b2eef1
{ "blob_id": "8cb076676576890a3d40e0323a4d318587b2eef1", "branch_name": "refs/heads/master", "committer_date": "2020-02-20T08:39:01", "content_id": "b6860a651e57c8300d3f106429619e37c942b78f", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "f0b1a73a8f8f11a5e063677429ccdfccdfa9687d", "extension": "md", "filename": "lpop.md", "fork_events_count": 0, "gha_created_at": "2020-02-20T08:42:27", "gha_event_created_at": "2020-02-20T08:42:27", "gha_language": null, "gha_license_id": "BSD-3-Clause", "github_id": 241833967, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 278, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/iredis/data/commands/lpop.md", "provenance": "stack-edu-markdown-0017.json.gz:110968", "repo_name": "lyqscmy/iredis", "revision_date": "2020-02-20T08:39:01", "revision_id": "6565ad33b74bc1408b7554f319f6ae2f13a33b50", "snapshot_id": "7f60d1ee4ce5ff50f1a1278784b93ccc5ea639cd", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/lyqscmy/iredis/6565ad33b74bc1408b7554f319f6ae2f13a33b50/iredis/data/commands/lpop.md", "visit_date": "2021-01-07T22:08:23.031885", "added": "2024-11-18T22:33:22.032245+00:00", "created": "2020-02-20T08:39:01", "int_score": 3, "score": 2.53125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0017.json.gz" }
// Author: btjanaka (Bryon Tjanaka) // Problem: (LeetCode) 52 // Title: N-Queens II // Link: https://leetcode.com/problems/n-queens-ii/ // Idea: This implementation uses an "engine" that keeps track of an internal // state. The step() function is repeatedly called to advance the state and find // all solutions. // Difficulty: medium // Tags: complete-search class NQueensEngine { constructor(n) { this.n = undefined; this.queens = undefined; this.curQueen = undefined; this.justBacktracked = undefined; this.reset(n); } // Resets the board with n new queens. reset = n => { this.n = n; this.queens = []; for (let i = 0; i < n; ++i) this.queens.push(0); this.curQueen = 0; this.justBacktracked = false; }; // Returns true if a solution was found. step = () => { // Check if current position conflicts, but only if we did not just // backtrack (there is no need to check for conflicts if we just // backtracked). let conflict = false; if (!this.justBacktracked) { for (let i = 0; i < this.curQueen; ++i) { let sameRow = this.queens[i] == this.queens[this.curQueen]; let sameDiag1 = this.queens[i] - this.queens[this.curQueen] == i - this.curQueen; let sameDiag2 = this.queens[i] - this.queens[this.curQueen] == this.curQueen - i; if (sameRow || sameDiag1 || sameDiag2) { conflict = true; break; } } } if (!conflict && !this.justBacktracked) { // If no conflict, advance the queen. ++this.curQueen; // If curQueen is now at the end, a solution was found. Furthermore, we // should decrement curQueen to continue the search. if (this.curQueen == this.n) { --this.curQueen; this.justBacktracked = true; return true; } return false; } else { // Otherwise, advance in the current column. ++this.queens[this.curQueen]; this.justBacktracked = false; // Reset this column and move curQueen back if done checking. if (this.queens[this.curQueen] == this.n) { this.queens[this.curQueen] = 0; --this.curQueen; this.justBacktracked = true; } return false; } }; // Returns true if done searching. This happens when curQueen is set to -1 // because the step function is unable to move the queen in column 0 anymore. done = () => { return this.curQueen == -1; }; } /** * @param {number} n * @return {number} */ let totalNQueens = function (n) { let engine = new NQueensEngine(n); let tot = 0; while (!engine.done()) { if (engine.step()) { ++tot; } } return tot; };
8e819fda5b4b8a991f7ae64b09a5803099b1f3fa
{ "blob_id": "8e819fda5b4b8a991f7ae64b09a5803099b1f3fa", "branch_name": "refs/heads/master", "committer_date": "2021-02-09T11:29:35", "content_id": "782998d34bd44bcf4463b996af4543baa3dc94c1", "detected_licenses": [ "MIT" ], "directory_id": "a4016e3a099af344cbb07eff1a9268b621305a10", "extension": "js", "filename": "52.js", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 169714578, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2714, "license": "MIT", "license_type": "permissive", "path": "/leetcode/52.js", "provenance": "stack-edu-0044.json.gz:361641", "repo_name": "btjanaka/algorithm-problems", "revision_date": "2021-02-09T11:29:35", "revision_id": "e3df47c18451802b8521ebe61ca71ee348e5ced7", "snapshot_id": "4d92ae091676a90f5a8cb5a0b6b8c65e34946aee", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/btjanaka/algorithm-problems/e3df47c18451802b8521ebe61ca71ee348e5ced7/leetcode/52.js", "visit_date": "2021-06-17T22:10:01.324863", "added": "2024-11-18T22:29:03.332573+00:00", "created": "2021-02-09T11:29:35", "int_score": 3, "score": 3.40625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0062.json.gz" }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Jill { public partial class Preview : Form { string full_path = null; public Preview(string path) { InitializeComponent(); full_path = path; } private void Preview_Load(object sender, EventArgs e) { render.Image = Image.FromFile(full_path); render.SizeMode = PictureBoxSizeMode.StretchImage; } } }
de8646b479635b314917a84faf38e618ce8239dd
{ "blob_id": "de8646b479635b314917a84faf38e618ce8239dd", "branch_name": "refs/heads/main", "committer_date": "2021-04-22T10:34:16", "content_id": "685dcdde4823f6e66f2e3ca6b8fd7f264562a9a6", "detected_licenses": [ "MIT" ], "directory_id": "a0906f16864779bf605b2eb047c77fef37c90cea", "extension": "cs", "filename": "Preview.cs", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 359194859, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 673, "license": "MIT", "license_type": "permissive", "path": "/src/Jill/Preview.cs", "provenance": "stack-edu-0013.json.gz:110293", "repo_name": "Neotoxic-off/Jill", "revision_date": "2021-04-22T10:34:16", "revision_id": "d66abea4665fd8e2766a55712088ab4bba717749", "snapshot_id": "f1eefe247a94cd5e1200a76c3de3660d68640270", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/Neotoxic-off/Jill/d66abea4665fd8e2766a55712088ab4bba717749/src/Jill/Preview.cs", "visit_date": "2023-06-27T07:20:42.507082", "added": "2024-11-18T23:18:11.380532+00:00", "created": "2021-04-22T10:34:16", "int_score": 2, "score": 2.46875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0031.json.gz" }
/* global describe, it */ import * as blockLike from '../src/lib' const assert = require('assert') describe('Sprite UI', () => { const stage = new blockLike.Stage() const sprite = new blockLike.Sprite() const otherSprite = new blockLike.Sprite() stage.addSprite(sprite) stage.addSprite(otherSprite) describe('think()', () => { it('it should create a think bubble', () => { sprite.think('I think therefore I am') assert(typeof sprite.textui === 'object') assert(sprite.textui.constructor.name === 'TextUiElement') }) it('should contain a DOM element', () => { sprite.think('I think therefore I am') assert(typeof sprite.textui.el === 'object') assert(sprite.textui.el.constructor.name === 'HTMLDivElement') }) it('should be styled like a think bubble', () => { sprite.think('I think therefore I am') assert(sprite.textui.el.className.indexOf('think') !== -1) }) it('should contain the text specified', () => { sprite.think('I think therefore I am') assert(sprite.textui.el.innerHTML.indexOf('I think therefore I am') !== -1) }) it('it should disappear when text is set to empty string', () => { sprite.think('') assert(sprite.textui === null) assert(document.getElementsByClassName('block-script-say').length === 0) }) it('it should disappear when text is ommited', () => { sprite.think() assert(sprite.textui === null) assert(document.getElementsByClassName('block-script-say').length === 0) }) it('it should replace old text with new text', () => { sprite.think('A') assert(sprite.textui.el.innerHTML.indexOf('A') !== -1) sprite.think('B') assert(sprite.textui.el.innerHTML.indexOf('A') === -1) assert(sprite.textui.el.innerHTML.indexOf('B') !== -1) }) it('it should accept \' in text', () => { sprite.think('That\'s it!') assert(sprite.textui.el.innerHTML.indexOf('\'') !== -1) }) it('it should accept " in text', () => { sprite.think('I say: "yay!"') assert(sprite.textui.el.innerHTML.indexOf('"') !== -1) }) it('it should accept number as input text', () => { sprite.think(10) assert(sprite.textui.el.innerHTML.indexOf('10') !== -1) }) it('it should accept 0 number as input text', () => { sprite.think(0) assert(sprite.textui.el.innerHTML.indexOf('0') !== -1) }) }) describe('say()', () => { it('it should create a speech bubble', () => { sprite.say('Hello World') assert(typeof sprite.textui === 'object') assert(sprite.textui.constructor.name === 'TextUiElement') }) it('should contain a DOM element', () => { sprite.say('Hello World') assert(typeof sprite.textui.el === 'object') assert(sprite.textui.el.constructor.name === 'HTMLDivElement') }) it('should be styled like a say bubble', () => { sprite.say('Hello World') assert(sprite.textui.el.className.indexOf('say') !== -1) }) it('should contain the text specified', () => { sprite.say('Hello World') assert(sprite.textui.el.innerHTML.indexOf('Hello World') !== -1) }) it('it should disappear when text is set to empty string', () => { sprite.say('') assert(sprite.textui === null) assert(document.getElementsByClassName('block-script-say').length === 0) }) it('it should disappear when text is ommited', () => { sprite.say() assert(sprite.textui === null) assert(document.getElementsByClassName('block-script-say').length === 0) }) it('it should replace old text with new text', () => { sprite.say('A') assert(sprite.textui.el.innerHTML.indexOf('A') !== -1) sprite.say('B') assert(sprite.textui.el.innerHTML.indexOf('A') === -1) assert(sprite.textui.el.innerHTML.indexOf('B') !== -1) }) it('it should accept \' in text', () => { sprite.say('That\'s it!') assert(sprite.textui.el.innerHTML.indexOf('\'') !== -1) }) it('it should accept " in text', () => { sprite.say('I say: "yay!"') assert(sprite.textui.el.innerHTML.indexOf('"') !== -1) }) it('it should accept number as input text', () => { sprite.say(10) assert(sprite.textui.el.innerHTML.indexOf('10') !== -1) }) it('it should accept 0 number as input text', () => { sprite.say(0) assert(sprite.textui.el.innerHTML.indexOf('0') !== -1) }) }) describe('ask()', () => { it('it should create a speech bubble', () => { sprite.ask('You OK?') assert(typeof sprite.textui === 'object') assert(sprite.textui.constructor.name === 'TextUiElement') }) it('should contain a DOM element', () => { sprite.ask('You OK?') assert(typeof sprite.textui.el === 'object') assert(sprite.textui.el.constructor.name === 'HTMLDivElement') }) it('should be styled like an ask bubble', () => { sprite.ask('You OK?') assert(sprite.textui.el.className.indexOf('ask') !== -1) }) it('should contain the text specified', () => { sprite.ask('You OK?') assert(sprite.textui.el.innerHTML.indexOf('You OK?') !== -1) }) it('it should disappear when text is set to empty string', () => { sprite.ask('') assert(sprite.textui === null) assert(document.getElementsByClassName('block-script-say').length === 0) }) it('it should disappear when text is ommited', () => { sprite.ask() assert(sprite.textui === null) assert(document.getElementsByClassName('block-script-say').length === 0) }) it('it should replace old text with new text', () => { sprite.ask('A') assert(sprite.textui.el.innerHTML.indexOf('A') !== -1) sprite.ask('B') assert(sprite.textui.el.innerHTML.indexOf('A') === -1) assert(sprite.textui.el.innerHTML.indexOf('B') !== -1) }) it('it should accept \' in text', () => { sprite.ask('What\'s your name?') assert(sprite.textui.el.innerHTML.indexOf('\'') !== -1) }) it('it should accept " in text', () => { sprite.ask('Do you agree on: "yay!"') assert(sprite.textui.el.innerHTML.indexOf('"') !== -1) }) it('it should accept number as input text', () => { sprite.ask(10) assert(sprite.textui.el.innerHTML.indexOf('10') !== -1) }) it('it should accept 0 number as input text', () => { sprite.ask(0) assert(sprite.textui.el.innerHTML.indexOf('0') !== -1) }) // TODO: add the tests for user input capture }) })
a4e345d6378e68e33d80f0399f6f188339914de1
{ "blob_id": "a4e345d6378e68e33d80f0399f6f188339914de1", "branch_name": "refs/heads/master", "committer_date": "2022-12-06T06:28:50", "content_id": "5a6178b0d0888c5b55b66855d5671d24b65c421c", "detected_licenses": [ "MIT" ], "directory_id": "c460833460f00cf110fbfd7a61cb351e11ab3715", "extension": "js", "filename": "sprite_ui.test.js", "fork_events_count": 19, "gha_created_at": "2018-02-14T18:30:45", "gha_event_created_at": "2023-03-15T08:48:10", "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 121546056, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 6612, "license": "MIT", "license_type": "permissive", "path": "/test/sprite_ui.test.js", "provenance": "stack-edu-0033.json.gz:36166", "repo_name": "ronilan/BlockLike", "revision_date": "2022-12-06T06:28:50", "revision_id": "fb0760141808af75360b45d8e44dd4909dc3144c", "snapshot_id": "8a390eae64c77ce35e2fb8c81af8dba077159e03", "src_encoding": "UTF-8", "star_events_count": 261, "url": "https://raw.githubusercontent.com/ronilan/BlockLike/fb0760141808af75360b45d8e44dd4909dc3144c/test/sprite_ui.test.js", "visit_date": "2023-04-10T01:58:27.709122", "added": "2024-11-19T01:13:05.883197+00:00", "created": "2022-12-06T06:28:50", "int_score": 3, "score": 2.734375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0051.json.gz" }
// Daniel Shiffman // http://codingtra.in // http://patreon.com/codingtrain // Code for this video: https://youtu.be/9Xy-LMAfglE var cities = []; var totalCities = 10; var order = []; var totalPermutations; var count = 0; var recordDistance; var bestEver; function setup() { createCanvas(400, 600); for (var i = 0; i < totalCities; i++) { var v = createVector(random(width), random(height / 2)); cities[i] = v; order[i] = i; } var d = calcDistance(cities, order); recordDistance = d; bestEver = order.slice(); totalPermutations = factorial(totalCities); console.log(totalPermutations); } function draw() { background(0); //frameRate(5); fill(255); for (var i = 0; i < cities.length; i++) { ellipse(cities[i].x, cities[i].y, 8, 8); } stroke(255, 0, 255); strokeWeight(4); noFill(); beginShape(); for (var i = 0; i < order.length; i++) { var n = bestEver[i]; vertex(cities[n].x, cities[n].y); } endShape(); translate(0, height / 2); stroke(255); strokeWeight(1); noFill(); beginShape(); for (var i = 0; i < order.length; i++) { var n = order[i]; vertex(cities[n].x, cities[n].y); } endShape(); var d = calcDistance(cities, order); if (d < recordDistance) { recordDistance = d; bestEver = order.slice(); } textSize(32); // var s = ''; // for (var i = 0; i < order.length; i++) { // s += order[i]; // } fill(255); var percent = 100 * (count / totalPermutations); text(nf(percent, 0, 2) + '% completed', 20, height / 2 - 50); nextOrder(); } function swap(a, i, j) { var temp = a[i]; a[i] = a[j]; a[j] = temp; } function calcDistance(points, order) { var sum = 0; for (var i = 0; i < order.length - 1; i++) { var cityAIndex = order[i]; var cityA = points[cityAIndex]; var cityBIndex = order[i + 1]; var cityB = points[cityBIndex]; var d = dist(cityA.x, cityA.y, cityB.x, cityB.y); sum += d; } return sum; } // This is my lexical order algorithm function nextOrder() { count++; // STEP 1 of the algorithm // https://www.quora.com/How-would-you-explain-an-algorithm-that-generates-permutations-using-lexicographic-ordering var largestI = -1; for (var i = 0; i < order.length - 1; i++) { if (order[i] < order[i + 1]) { largestI = i; } } if (largestI == -1) { noLoop(); console.log('finished'); } // STEP 2 var largestJ = -1; for (var j = 0; j < order.length; j++) { if (order[largestI] < order[j]) { largestJ = j; } } // STEP 3 swap(order, largestI, largestJ); // STEP 4: reverse from largestI + 1 to the end var endArray = order.splice(largestI + 1); endArray.reverse(); order = order.concat(endArray); } function factorial(n) { if (n == 1) { return 1; } else { return n * factorial(n - 1); } }
af5bb2915a1bca79561177ed864dbb7b2624ad1f
{ "blob_id": "af5bb2915a1bca79561177ed864dbb7b2624ad1f", "branch_name": "refs/heads/master", "committer_date": "2020-01-22T13:57:30", "content_id": "6df4229c83cab621d00c69b567771b6a9652338e", "detected_licenses": [ "MIT" ], "directory_id": "80bb1560eb338b6fa657700876775816bdb9a56d", "extension": "js", "filename": "sketch.js", "fork_events_count": 1, "gha_created_at": "2020-02-08T12:24:22", "gha_event_created_at": "2020-02-08T12:24:22", "gha_language": null, "gha_license_id": "MIT", "github_id": 239128393, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2855, "license": "MIT", "license_type": "permissive", "path": "/CodingChallenges/CC_035.3_TSP_Lexical/P5/sketch.js", "provenance": "stack-edu-0038.json.gz:373338", "repo_name": "shiffman/website-1", "revision_date": "2020-01-22T13:57:30", "revision_id": "27dbfe766d20e7867d0dec56e5f5c5838e3d504e", "snapshot_id": "5aab6ea6bc6f1811a77697c1936a637d5d76e5ef", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/shiffman/website-1/27dbfe766d20e7867d0dec56e5f5c5838e3d504e/CodingChallenges/CC_035.3_TSP_Lexical/P5/sketch.js", "visit_date": "2021-01-01T01:48:29.438921", "added": "2024-11-19T01:21:26.688809+00:00", "created": "2020-01-22T13:57:30", "int_score": 3, "score": 3.15625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0056.json.gz" }
<?php namespace App; use Illuminate\Database\Eloquent\Model; class TtDetPedido extends Model { // protected $table = "TT_DET_PEDIDO"; protected $fillable = [ 'det_pedido', 'cantidad', 'precio', 'observaciones', 'id_pedido', 'id_producto', 'id_estado', 'id_usuario_crea', 'id_usuario_modifica' ]; protected $hidden = [ 'updated_at', 'id_usuario_crea', 'id_usuario_modifica' ]; }
ca0cfd3fc5679fec60694babf481120e60aac34a
{ "blob_id": "ca0cfd3fc5679fec60694babf481120e60aac34a", "branch_name": "refs/heads/master", "committer_date": "2021-06-12T22:55:06", "content_id": "6bb33ca308b629e66f5d6affc59ea6772eb1053e", "detected_licenses": [ "MIT" ], "directory_id": "4a26a67709b9933340728eb4f0073cf99ffe4b7f", "extension": "php", "filename": "TtDetPedido.php", "fork_events_count": 0, "gha_created_at": "2019-09-06T06:27:46", "gha_event_created_at": "2022-03-26T00:34:40", "gha_language": "PHP", "gha_license_id": null, "github_id": 206727752, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 501, "license": "MIT", "license_type": "permissive", "path": "/app/TtDetPedido.php", "provenance": "stack-edu-0051.json.gz:444166", "repo_name": "Miguelito777/pedidos_back", "revision_date": "2021-06-12T22:55:06", "revision_id": "4759aea3ced3837b5e2ef0220e11a8e1cb7777e6", "snapshot_id": "f552f4f0f1925639c4d8f8087e26fb9385f1e538", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Miguelito777/pedidos_back/4759aea3ced3837b5e2ef0220e11a8e1cb7777e6/app/TtDetPedido.php", "visit_date": "2022-05-09T06:11:31.992412", "added": "2024-11-18T20:02:30.890637+00:00", "created": "2021-06-12T22:55:06", "int_score": 2, "score": 2.09375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0069.json.gz" }
#include "ofApp.h" class ClassA{ public: ClassA(){ std::cout << "ClassA is being created" << std::endl; } ~ClassA(){ std::cout << "ClassA is being deleted" << std::endl; } }; class ClassB{ public: ClassB(){ std::cout << "ClassB is being created" << std::endl; } ~ClassB(){ std::cout << "ClassB is being deleted" << std::endl; } }; class ClassC{ public: ClassC(){ std::cout << "ClassC is being created" << std::endl; } ~ClassC(){ std::cout << "ClassC is being deleted" << std::endl; } }; class ClassD{ public: ClassD(){ std::cout << "ClassD is being created" << std::endl; } ~ClassD(){ std::cout << "ClassD is being deleted" << std::endl; } }; //-------------------------------------------------------------- void ofApp::setup(){ cout << "-----Begin-----" << endl; ofxTinySingleton<ClassA>::get_instance(); //"ClassA is being created" ofxTinySingleton<ClassA>::get_instance(); ofxTinySingleton<ClassA>::get_instance(); ofxTinySingleton<ClassB>::get_instance(); //"ClassA is being created" ofxTinySingleton<ClassA>::get_instance(); ofxTinySingleton<ClassA>::get_instance(); ofxTinySingleton<ClassA>::get_instance(); ofxTinySingleton<ClassC>::get_instance(); //"ClassA is being created" ofxTinySingleton<ClassB>::get_instance(); ofxTinySingleton<ClassA>::get_instance(); ofxTinySingleton<ClassB>::get_instance(); ofxTinySingleton<ClassA>::get_instance(); ofxTinySingleton<ClassD>::get_instance(); //"ClassD is being created" ofxTinySingleton<ClassC>::get_instance(); ofxTinySingleton<ClassB>::get_instance(); ofxTinySingleton<ClassA>::get_instance(); ofxTinySingleton<ClassB>::get_instance(); ofxTinySingleton<ClassA>::get_instance(); cout << "-----End-----" << endl; cout << "The order of the destructions should be ClassD,ClassC,ClassB,ClassA\n" << endl; } //-------------------------------------------------------------- void ofApp::update(){ } //-------------------------------------------------------------- void ofApp::draw(){ ofDrawBitmapString("Exit the app and check the console", 300, 400); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
40d4aec0947761bdcd284cb391b85643c93a7df0
{ "blob_id": "40d4aec0947761bdcd284cb391b85643c93a7df0", "branch_name": "refs/heads/master", "committer_date": "2016-11-02T12:24:43", "content_id": "8250f1f3d238cd937f78d7534a1f15409ca59cbf", "detected_licenses": [ "MIT" ], "directory_id": "8677118a515cf407fae933cb07c4f2c67f3e7ca7", "extension": "cpp", "filename": "ofApp.cpp", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 55589472, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3469, "license": "MIT", "license_type": "permissive", "path": "/ofxTinySingletonExample/src/ofApp.cpp", "provenance": "stack-edu-0003.json.gz:70292", "repo_name": "daitomanabe/ofxTinySingleton", "revision_date": "2016-11-02T12:24:43", "revision_id": "63c601255fc44dbf8853f93c6d341c564fc54c84", "snapshot_id": "99432f4a06a60f185508ac2b27402637aa8b2c65", "src_encoding": "UTF-8", "star_events_count": 11, "url": "https://raw.githubusercontent.com/daitomanabe/ofxTinySingleton/63c601255fc44dbf8853f93c6d341c564fc54c84/ofxTinySingletonExample/src/ofApp.cpp", "visit_date": "2021-01-10T12:42:41.151488", "added": "2024-11-19T02:23:53.927240+00:00", "created": "2016-11-02T12:24:43", "int_score": 2, "score": 2.46875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0021.json.gz" }
#include <json5pp.hpp> #include <ostream> void exec(std::ostream& out) { auto value = json5pp::array({}); auto& array = value.as_array(); array.resize(3); array[1] = 123ll; out << value; }
78fd0d7b19b5aea29b95536f48f981fd23963ddf
{ "blob_id": "78fd0d7b19b5aea29b95536f48f981fd23963ddf", "branch_name": "refs/heads/master", "committer_date": "2021-04-28T07:34:14", "content_id": "ad78bcd0d5522cad817b184ae0351e48d7f79059", "detected_licenses": [ "MIT" ], "directory_id": "e23db5fac498175b54a1c3fb8d52de840d0e661b", "extension": "cpp", "filename": "exec_array_nullptr_element.cpp", "fork_events_count": 1, "gha_created_at": "2020-12-18T08:59:51", "gha_event_created_at": "2021-04-28T07:34:15", "gha_language": "C++", "gha_license_id": "MIT", "github_id": 322542054, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 200, "license": "MIT", "license_type": "permissive", "path": "/test/input/exec_array_nullptr_element.cpp", "provenance": "stack-edu-0003.json.gz:153593", "repo_name": "thpatch/json5pp", "revision_date": "2021-04-28T07:34:14", "revision_id": "c2bba387375001156add475414b1ffffc743b570", "snapshot_id": "c65e7f914a45934fc1f750faf1d574167ba4102e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/thpatch/json5pp/c2bba387375001156add475414b1ffffc743b570/test/input/exec_array_nullptr_element.cpp", "visit_date": "2023-04-11T17:10:15.371042", "added": "2024-11-18T21:53:18.686727+00:00", "created": "2021-04-28T07:34:14", "int_score": 2, "score": 2.15625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0021.json.gz" }
package core.commands.whoknows; import core.Chuu; import core.commands.utils.CommandCategory; import core.commands.utils.CommandUtil; import core.exceptions.LastFmException; import core.parsers.ArtistAlbumParser; import core.parsers.Parser; import core.parsers.params.ArtistAlbumParameters; import dao.ChuuService; import dao.entities.*; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import java.util.*; import java.util.stream.Collectors; public class WhoKnowsAlbumCommand extends WhoKnowsBaseCommand<ArtistAlbumParameters> { public WhoKnowsAlbumCommand(ChuuService dao) { super(dao); } @Override protected CommandCategory initCategory() { return CommandCategory.SERVER_STATS; } @Override public Parser<ArtistAlbumParameters> initParser() { return new ArtistAlbumParser(db, lastFM); } @Override public String getDescription() { return ("How many times the guild has heard an album!"); } @Override public List<String> getAliases() { return Arrays.asList("uwkalbum", "uwka", "uwhoknowsalbum"); } @Override public String getName() { return "Updated Who Knows Album"; } @Override WhoKnowsMode getWhoknowsMode(ArtistAlbumParameters params) { return getEffectiveMode(params.getLastFMData().getWhoKnowsMode(), params); } @Override WrapperReturnNowPlaying generateWrapper(ArtistAlbumParameters ap, WhoKnowsMode whoKnowsMode) throws LastFmException { ScrobbledArtist validable = new ScrobbledArtist(ap.getArtist(), 0, ""); CommandUtil.validate(db, validable, lastFM, discogsApi, spotify, true, !ap.isNoredirect()); ap.setScrobbledArtist(validable); MessageReceivedEvent e = ap.getE(); ScrobbledArtist artist = ap.getScrobbledArtist(); long id = e.getGuild().getIdLong(); // Gets list of users registered in guild List<UsersWrapper> userList = db.getAll(id); if (userList.isEmpty()) { sendMessageQueue(e, "There are no users registered on this server"); return null; } // Gets play number for each registered artist AlbumUserPlays urlContainter = new AlbumUserPlays("", ""); Set<Long> usersThatKnow = db.whoKnows(artist.getArtistId(), id, 25).getReturnNowPlayings().stream() .map(ReturnNowPlaying::getDiscordId) .collect(Collectors.toSet()); usersThatKnow.add(ap.getLastFMData().getDiscordId()); usersThatKnow.add(e.getAuthor().getIdLong()); userList = userList.stream() .filter(x -> usersThatKnow.contains(x.getDiscordID()) || x.getDiscordID() == ap.getLastFMData().getDiscordId() || x.getDiscordID() == e.getAuthor().getIdLong()) .collect(Collectors.toList()); if (userList.isEmpty()) { Chuu.getLogger().error("Something went real wrong"); sendMessageQueue(e, String.format(" No one knows %s - %s", CommandUtil.cleanMarkdownCharacter(ap.getArtist()), CommandUtil.cleanMarkdownCharacter(ap.getAlbum()))); return null; } Map<UsersWrapper, Integer> userMapPlays = fillPlayCounter(userList, artist.getArtist(), ap.getAlbum(), urlContainter); String correctedAlbum = urlContainter.getAlbum() == null || urlContainter.getAlbum().isEmpty() ? ap.getAlbum() : urlContainter.getAlbum(); String correctedArtist = urlContainter.getArtist() == null || urlContainter.getArtist().isEmpty() ? artist.getArtist() : urlContainter.getArtist(); // Manipulate data in order to pass it to the image Maker List<Map.Entry<UsersWrapper, Integer>> userCounts = new ArrayList<>(userMapPlays.entrySet()); userCounts.sort(Map.Entry.comparingByValue(Comparator.reverseOrder())); WhoKnowsMode effectiveMode = WhoKnowsCommand.getEffectiveMode(ap.getLastFMData().getWhoKnowsMode(), ap); List<ReturnNowPlaying> list2 = userCounts.stream().sequential().limit(effectiveMode.equals(WhoKnowsMode.IMAGE) ? 10 : Integer.MAX_VALUE).map(t -> { long id2 = t.getKey().getDiscordID(); ReturnNowPlaying np = new ReturnNowPlayingAlbum(id2, t.getKey().getLastFMName(), correctedArtist, t.getValue(), correctedAlbum); np.setDiscordName(CommandUtil.getUserInfoNotStripped(e, id2).getUsername()); return np; }).filter(x -> x.getPlayNumber() > 0).collect(Collectors.toList()); if (list2.isEmpty()) { sendMessageQueue(e, String.format(" No one knows %s - %s", CommandUtil.cleanMarkdownCharacter(correctedArtist), CommandUtil.cleanMarkdownCharacter(correctedAlbum))); return null; } doExtraThings(list2, id, artist.getArtistId(), correctedAlbum); return new WrapperReturnNowPlaying(list2, userCounts.size(), urlContainter.getAlbumUrl(), correctedArtist + " - " + correctedAlbum); } void doExtraThings(List<ReturnNowPlaying> list2, long id, long artistId, String album) { ReturnNowPlaying crownUser = list2.get(0); db.insertAlbumCrown(artistId, album, crownUser.getDiscordId(), id, crownUser.getPlayNumber()); } Map<UsersWrapper, Integer> fillPlayCounter(List<UsersWrapper> userList, String artist, String album, AlbumUserPlays fillWithUrl) throws LastFmException { Map<UsersWrapper, Integer> userMapPlays = new HashMap<>(); UsersWrapper usersWrapper = userList.get(0); AlbumUserPlays temp = lastFM.getPlaysAlbumArtist(LastFMData.ofUserWrapper(usersWrapper), artist, album); fillWithUrl.setAlbumUrl(temp.getAlbumUrl()); fillWithUrl.setAlbum(temp.getAlbum()); fillWithUrl.setArtist(temp.getArtist()); userMapPlays.put(usersWrapper, temp.getPlays()); userList.stream().skip(1).forEach(u -> { try { AlbumUserPlays albumUserPlays = lastFM.getPlaysAlbumArtist(LastFMData.ofUserWrapper(u), artist, album); userMapPlays.put(u, albumUserPlays.getPlays()); } catch (LastFmException ex) { Chuu.getLogger().warn(ex.getMessage(), ex); } }); return userMapPlays; } @Override public String getTitle(ArtistAlbumParameters params, String baseTitle) { return "Who knows " + CommandUtil.cleanMarkdownCharacter(params.getArtist() + " - " + params.getAlbum()) + " in " + baseTitle + "?"; } }
fe5f79846479f2ecaf24dc738cf367c4bd66defc
{ "blob_id": "fe5f79846479f2ecaf24dc738cf367c4bd66defc", "branch_name": "refs/heads/master", "committer_date": "2021-02-23T20:44:53", "content_id": "e8c6f53dce35c7f023c7a86d98f1a377c811ffa2", "detected_licenses": [ "MIT" ], "directory_id": "0a01147067aadcb1286f1522282674c235ac428c", "extension": "java", "filename": "WhoKnowsAlbumCommand.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 6584, "license": "MIT", "license_type": "permissive", "path": "/src/main/java/core/commands/whoknows/WhoKnowsAlbumCommand.java", "provenance": "stack-edu-0023.json.gz:351552", "repo_name": "Textacy/Chuu", "revision_date": "2021-02-23T20:44:53", "revision_id": "f1a52149b40d898c0ace59eec3dffb0d0e772b6f", "snapshot_id": "831603dd026f67814e7054a75477f10cfe853565", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Textacy/Chuu/f1a52149b40d898c0ace59eec3dffb0d0e772b6f/src/main/java/core/commands/whoknows/WhoKnowsAlbumCommand.java", "visit_date": "2023-03-11T16:50:47.425692", "added": "2024-11-18T21:13:28.933911+00:00", "created": "2021-02-23T20:44:53", "int_score": 2, "score": 2.296875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0041.json.gz" }
<?php class_exists('ICertificateType') or require(dirname(__FILE__).'/ICertificateType.php'); class DataVerifier { ///**校验证件类型正确性*/ public static function isValidCertificate($sCertificateType, $sCertificateNo) { if (strpos(ICertificateType::CERTIFICATETYPE, "|".$sCertificateType."|") === false) { return false; } if ($sCertificateNo == null) return false; $len = strlen($sCertificateNo); if (!(ICertificateType::I === $sCertificateType)) return true; if ($len != 15 && $len != 18) return false; return true; } /** * 检验银行卡号是否合法 * @param iBankCardNo * @return */ public static function isValidBankCardNo($iBankCardNo) { if (!self::isValidString($iBankCardNo, ILength::CARDNO_LEN)) return false; $numeric = "1234567890"; for ($i = 0; $i < strlen($iBankCardNo); $i++) { $character = substr($iBankCardNo,$i, 1); if (strpos($numeric, $character) === false) { return false; } } return true; } /**校验字符串是否不为空且有效*/ public static function isValidString($sValue, $len) { if ($sValue == null) return false; if (strlen($sValue) > $len) return false; return true; } /// <summary> 检查传入的字符串时否符合URL的格式。 /// </summary> /// <param name="aString">需要检查的字符串。 /// </param> /// <returns> 检查结果,true:正确 false:不正确 /// /// </returns> public static function isValidURL($aString) { if ((strlen($aString) < 0) || (strlen($aString)> ILength :: RESULT_NOTIFY_URL_LEN)) return false; if ((strpos($aString, 'http://') === false) && (strpos($aString, 'https://') === false)) return false; return true; } /** * 检验传入的字符串是否合法 * @param * @return */ public static function isValid($str) { $numeric = '1234567890'; if (strlen($str) <= 0) return false; for ($i = 0; $i < strlen($str); $i++) { $character = $str[$i]; if (strpos($numeric, $character) === false) { return false; } } /**/ return true; } /// <summary> 检查传入的字符串时否符合YYYY/MM/DD的日期格式。 /// </summary> /// <param name="aString">需要检查的字符串。 /// </param> /// <returns> 检查结果,true:正确 false:不正确 /// /// </returns> public static function isValidDate($aString) { if (strlen($aString) !== 10) return false; if (($aString[4] !== '/') || ($aString[7] !== '/')) return false; $tYYYY = substr($aString, 0, 4); $tMM = substr($aString, 5, 2); $tDD = substr($aString, 8, 2); if (($tMM < 1) || ($tMM > 12)) return false; if (($tDD < 1) || ($tDD > 31)) return false; return true; } /// <summary> 检查传入的字符串时否符合HH:MM:SS的时间格式。 /// </summary> /// <param name="aString">需要检查的字符串。 /// </param> /// <returns> 检查结果,true:正确 false:不正确 /// /// </returns> public static function isValidTime($aString) { if (strlen($aString) !== 8) return false; if (($aString[2] !== ':') || ($aString[5] !== ':')) return false; $tHH = substr($aString, 0, 2); $tMM = substr($aString, 3, 2); $tSS = substr($aString, 6, 2); if (($tHH < 0) || ($tHH > 23)) return false; if (($tMM < 0) || ($tMM > 59)) return false; if (($tSS < 0) || ($tSS > 59)) return false; return true; } /// <summary> 检查传入的金额是否符合要。 /// </summary> /// <param name="aAmount">金额。 /// </param> /// <param name="aExp">小数点后位数,如果小于零时,将不对传入的金额作检查并回传false。 /// </param> /// <returns> 检查结果,true:正确 false:不正确 /// /// </returns> public static function isValidAmount($tAmountStr, $aExp) { if ($tAmountStr <= 0) return false; if (!is_numeric($tAmountStr)) return false; if ($aExp >= 0) { $tIndex = strpos($tAmountStr, ".", 0); if ($tIndex === false) return true; else if ($tIndex >= strlen($tAmountStr) - $aExp - 1) return true; } } } ?>
a4a535fef15638b65157aac62d77c9c556c7569a
{ "blob_id": "a4a535fef15638b65157aac62d77c9c556c7569a", "branch_name": "refs/heads/master", "committer_date": "2017-05-02T02:35:06", "content_id": "9a807b16741cf99960c1cf7888aaaf3ac6cfa22e", "detected_licenses": [ "MIT" ], "directory_id": "3d17697cf0590e638d2f402b00cdfb0e95f41b24", "extension": "php", "filename": "DataVerifier.php", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 78500298, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 5120, "license": "MIT", "license_type": "permissive", "path": "/public/ebusclient/core/DataVerifier.php", "provenance": "stack-edu-0048.json.gz:185797", "repo_name": "wssflylshily/yougangwang", "revision_date": "2017-05-02T02:35:06", "revision_id": "6a54a5c08223cb93e6d8768c625dbf312b3f1f82", "snapshot_id": "f54a7b4400da437915cf3e3cc2108e25b25069b3", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/wssflylshily/yougangwang/6a54a5c08223cb93e6d8768c625dbf312b3f1f82/public/ebusclient/core/DataVerifier.php", "visit_date": "2021-01-12T02:19:37.770939", "added": "2024-11-19T03:21:31.102506+00:00", "created": "2017-05-02T02:35:06", "int_score": 3, "score": 3.046875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0066.json.gz" }
# Roman Numeral Calculator A calculator for doing arithmetic on Roman Numerals without converting back and forth to decimal representations.
4dcc6f8c58f84cc7e92774eb42f06896b7daf012
{ "blob_id": "4dcc6f8c58f84cc7e92774eb42f06896b7daf012", "branch_name": "refs/heads/master", "committer_date": "2016-03-27T15:15:28", "content_id": "c2bc21b3788a1e2bb06b7f2275b881566adc1d3d", "detected_licenses": [ "Apache-2.0" ], "directory_id": "28624ab5e496dffdc0dcffcd95e6c27398a9db5b", "extension": "md", "filename": "README.md", "fork_events_count": 0, "gha_created_at": "2016-02-22T23:54:53", "gha_event_created_at": "2016-03-27T15:15:28", "gha_language": "Ruby", "gha_license_id": null, "github_id": 52315229, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 141, "license": "Apache-2.0", "license_type": "permissive", "path": "/README.md", "provenance": "stack-edu-markdown-0010.json.gz:217281", "repo_name": "splaroche/roman-numeral-calculator", "revision_date": "2016-03-27T15:15:28", "revision_id": "f46d82b04f64c6a2b50d052dedf633b1eb1ecd9b", "snapshot_id": "515012b7fa328d7bf87584efe6c4a0e4fb1857a0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/splaroche/roman-numeral-calculator/f46d82b04f64c6a2b50d052dedf633b1eb1ecd9b/README.md", "visit_date": "2021-01-10T03:40:12.967618", "added": "2024-11-18T23:26:28.764681+00:00", "created": "2016-03-27T15:15:28", "int_score": 2, "score": 2.109375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0010.json.gz" }
/* * This file is generated by Entity Class Compiler, (c) CroTeam 1997-98 */ #ifndef _FogMarker_INCLUDED #define _FogMarker_INCLUDED 1 #include <EntitiesMP/Marker.h> extern DECL_DLL CEntityPropertyEnumType FogAttenuationType_enum; enum FogAttenuationType { FA_LINEAR = 0, FA_EXP = 1, FA_EXP2 = 2, }; DECL_DLL inline void ClearToDefault(FogAttenuationType &e) { e = (FogAttenuationType)0; } ; extern DECL_DLL CEntityPropertyEnumType FogGraduationType2_enum; enum FogGraduationType2 { FG_CONSTANT = 0, FG_LINEAR = 1, FG_EXP = 2, }; DECL_DLL inline void ClearToDefault(FogGraduationType2 &e) { e = (FogGraduationType2)0; } ; extern "C" DECL_DLL CDLLEntityClass CFogMarker_DLLClass; class CFogMarker : public CMarker { public: virtual BOOL IsImportant(void) const { return TRUE; }; DECL_DLL virtual void SetDefaultProperties(void); FLOAT m_fDepth; FLOAT m_fAbove; FLOAT m_fBelow; FLOAT m_fFar; enum FogAttenuationType m_faType; FLOAT m_fDensity; enum FogGraduationType2 m_fgType; FLOAT m_fGraduation; BOOL m_bDensityDirect; FLOAT m_fDensityPercentage; FLOAT m_fDensityDistance; BOOL m_bGraduationDirect; FLOAT m_fGraduationPercentage; FLOAT m_fGraduationDistance; INDEX m_iSizeL; INDEX m_iSizeH; COLOR m_colColor; #line 57 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" const CTString & GetFogName(void); #line 62 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" void GetFog(class CFogParameters & fpFog); #define STATE_CFogMarker_Main 1 BOOL #line 83 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" Main(const CEntityEvent &__eeInput); }; #endif // _FogMarker_INCLUDED
22b80cbd103d06f46e9146a1331f1979e8392ef1
{ "blob_id": "22b80cbd103d06f46e9146a1331f1979e8392ef1", "branch_name": "refs/heads/master", "committer_date": "2021-07-31T21:51:49", "content_id": "0b11be801e960baaf9e1743828d6eb590e439a48", "detected_licenses": [ "Apache-2.0" ], "directory_id": "4aa3ff56e35d2d4cdeba40f45795f62f276859b3", "extension": "h", "filename": "FogMarker.h", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1703, "license": "Apache-2.0", "license_type": "permissive", "path": "/EntitiesMP/FogMarker.h", "provenance": "stack-edu-0006.json.gz:409029", "repo_name": "SixShoot/lastchaos-source-client", "revision_date": "2021-07-31T21:51:49", "revision_id": "3d88594dba7347b1bb45378136605e31f73a8555", "snapshot_id": "fde6a750afc4d7c5df3e9e0c542b056573c1b42d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/SixShoot/lastchaos-source-client/3d88594dba7347b1bb45378136605e31f73a8555/EntitiesMP/FogMarker.h", "visit_date": "2023-06-28T17:20:35.951648", "added": "2024-11-18T21:49:37.473238+00:00", "created": "2021-07-31T21:51:49", "int_score": 2, "score": 2.03125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0024.json.gz" }
import React, { useCallback, useEffect, useMemo, useRef, useState, } from 'react'; import { scrollToIndex } from '##/components/SelectComponentsCanary/useSelect/helpers'; import { useClickOutside } from '##/hooks/useClickOutside'; import { useFlag } from '##/hooks/useFlag'; import { KeyHandler, useKeys } from '##/hooks/useKeys'; import { useRefs } from '##/hooks/useRefs'; import { getGroups } from '##/utils/getGroups'; type IndexForHighlight = number | ((oldIndex: number) => number); type GetItemGroupKey<ITEM> = (item: ITEM) => string | number | undefined; type GetGroupKey<GROUP> = (item: GROUP) => string | number | undefined; type OnChangeProp<ITEM> = (props: { value: ITEM | null; e: React.SyntheticEvent; }) => void; type UseAutoCompleteProps<ITEM, GROUP> = { getItemGroupKey?: GetItemGroupKey<ITEM> | undefined; getGroupKey?: GetGroupKey<GROUP>; groups?: GROUP[]; items: ITEM[]; dropdownRef: React.MutableRefObject<HTMLDivElement | null>; controlRef: React.MutableRefObject<HTMLDivElement | null>; disabled?: boolean; getItemLabel: (item: ITEM) => string; getItemKey: (item: ITEM) => string | number; searchFunction?: (item: ITEM, searchValue: string) => boolean; onFocus?: React.FocusEventHandler<HTMLInputElement>; onBlur?: React.FocusEventHandler<HTMLInputElement>; searchValue?: string; onChange: OnChangeProp<ITEM>; isLoading?: boolean; dropdownOpen?: boolean; onDropdownOpen?: (isOpen: boolean) => void; ignoreOutsideClicksRefs?: ReadonlyArray<React.RefObject<HTMLElement>>; }; type OptionProps<ITEM> = { index: number; item: ITEM; keyPrefix: number; }; type GetOptionPropsResult = { onClick: (e: React.SyntheticEvent) => void; onMouseEnter: (e: React.SyntheticEvent) => void; active: boolean; hovered: boolean; key: string | number; }; export function useAutoComplete<ITEM, GROUP>( params: UseAutoCompleteProps<ITEM, GROUP>, ) { const { items, dropdownRef, controlRef, disabled = false, getItemLabel, getItemKey, searchFunction, getItemGroupKey, groups, getGroupKey, onFocus, onBlur, searchValue, isLoading, dropdownOpen, onDropdownOpen, ignoreOutsideClicksRefs, } = params; const inputRef = useRef<HTMLInputElement>(null); const [isOpen, setIsOpen] = useFlag(); const [highlightedIndex, setHighlightedIndex] = useState<number>(0); const searchFunctionDefault = (item: ITEM, searchValue: string) => { if (!searchValue) { return false; } return ( getItemLabel(item) .toLocaleLowerCase() .indexOf(searchValue.toLocaleLowerCase()) !== -1 ); }; const filteredOptions = useMemo( () => items.filter((item) => searchFunction ? searchFunction(item, searchValue || '') : searchFunctionDefault(item, searchValue || ''), ), [searchValue, items], ); const visibleItems = useMemo(() => { const resultGroups = getGroups( filteredOptions, groups?.length ? getItemGroupKey : undefined, groups, getGroupKey, undefined, ); return resultGroups; }, [filteredOptions, groups, getItemGroupKey, getGroupKey]); const hasItems = useMemo(() => { return !!visibleItems.find((group) => group.items.length > 0); }, [visibleItems]); const highlightIndex = useCallback( (indexForHighlight: IndexForHighlight) => { setHighlightedIndex( Math.min( Math.max( 0, typeof indexForHighlight === 'function' ? indexForHighlight(highlightedIndex) : indexForHighlight, ), filteredOptions.length - 1, ), ); }, [filteredOptions, highlightedIndex], ); const onChange = (e: React.SyntheticEvent, item: ITEM) => { if (!disabled) { params.onChange({ value: item, e }); } }; // Prop Getters const ArrowUp: KeyHandler = (_, e): void => { if (!disabled) { e.preventDefault(); setIsOpen.on(); highlightIndex((old) => old - 1); } }; const ArrowDown: KeyHandler = (_, e): void => { if (!disabled) { e.preventDefault(); setIsOpen.on(); highlightIndex((old) => old + 1); } }; const Enter: KeyHandler = (_, e): void => { if (isOpen) { if (searchValue || filteredOptions[highlightedIndex]) { e.preventDefault(); } const getItem = (index: number) => { let couter = 0; for (const group of visibleItems) { if (group.items.length + couter > index) { return group.items[index - couter]; } couter += group.items.length; } return undefined; }; const item = getItem(highlightedIndex); if (item) { onChange(e, item); } } else { setIsOpen.on(); } }; const Escape: KeyHandler = (): void => { setIsOpen.off(); }; const Tab: KeyHandler = (_, e): void => { setIsOpen.off(); if (isOpen && hasItems) { e.preventDefault(); } }; const getKeyProps = useKeys({ ArrowUp, ArrowDown, PageUp: ArrowUp, PageDown: ArrowDown, Home: ArrowUp, End: ArrowDown, Enter, Escape, Tab, }); const getOptionProps = ({ index, item, }: OptionProps<ITEM>): GetOptionPropsResult => { const key = getItemKey(item); return { onClick: (e: React.SyntheticEvent) => { onChange(e, item); }, onMouseEnter: () => { highlightIndex(index); }, active: false, hovered: index === highlightedIndex, key, }; }; const optionsRefs = useRefs<HTMLDivElement>(filteredOptions.length, [isOpen]); const handleInputFocus = (e: React.FocusEvent<HTMLInputElement>): void => { if (!disabled) { setIsOpen.toggle(); if (typeof onFocus === 'function') { onFocus(e); } } }; const handleInputBlur = (e: React.FocusEvent<HTMLInputElement>): void => { if (isOpen) { inputRef.current?.focus(); return; } if (typeof onBlur === 'function') { onBlur(e); } }; useClickOutside({ isActive: isOpen, ignoreClicksInsideRefs: [ dropdownRef, controlRef, ...(ignoreOutsideClicksRefs || []), ], handler: setIsOpen.off, }); useEffect(() => { if (disabled) { setIsOpen.off(); inputRef.current?.blur(); } }, [disabled]); useEffect(() => { if (filteredOptions.length > 0) { scrollToIndex(highlightedIndex, dropdownRef, optionsRefs, () => highlightIndex(0), ); } setIsOpen.on(); }, [highlightedIndex]); useEffect(() => { onDropdownOpen?.(isOpen); }, [isOpen]); useEffect(() => { setIsOpen.set(dropdownOpen || false); }, [dropdownOpen]); useEffect(() => { if (searchValue) { setIsOpen.on(); } }, [searchValue]); return { isOpen: Boolean(isOpen && (isLoading ? true : hasItems)), visibleItems, getOptionProps, handleInputFocus, handleInputBlur, inputRef, getKeyProps, hasItems, optionsRefs, }; }
285145532f760abd50165f95fccb49028b44ae30
{ "blob_id": "285145532f760abd50165f95fccb49028b44ae30", "branch_name": "refs/heads/dev", "committer_date": "2023-08-30T16:26:44", "content_id": "ab6e53c9866719dd6d03390d624d50ba3cface86", "detected_licenses": [ "MIT" ], "directory_id": "252f4cfea6e7e1baab2f0baee7884e79793a74f6", "extension": "ts", "filename": "useAutoComplete.ts", "fork_events_count": 41, "gha_created_at": "2019-08-28T07:02:37", "gha_event_created_at": "2023-09-14T08:43:22", "gha_language": "TypeScript", "gha_license_id": "MIT", "github_id": 204869037, "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 7163, "license": "MIT", "license_type": "permissive", "path": "/src/components/AutoCompleteCanary/useAutoComplete.ts", "provenance": "stack-edu-0074.json.gz:63753", "repo_name": "consta-design-system/uikit", "revision_date": "2023-08-30T16:26:44", "revision_id": "d1fda90d786622598630da8666c63d9bdd4ada10", "snapshot_id": "01ed2c8d9fe8c8f1f21e9f44b47a903f89af5c83", "src_encoding": "UTF-8", "star_events_count": 66, "url": "https://raw.githubusercontent.com/consta-design-system/uikit/d1fda90d786622598630da8666c63d9bdd4ada10/src/components/AutoCompleteCanary/useAutoComplete.ts", "visit_date": "2023-08-30T21:42:12.385304", "added": "2024-11-19T02:36:04.373102+00:00", "created": "2023-08-30T16:26:44", "int_score": 2, "score": 2.421875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0092.json.gz" }
from matplotlib_venn import venn3, venn3_circles from matplotlib import pyplot as plt def complement(subs=1, size=15, fill_color='skyblue', bg_color='white', font_color='#000', font_size=20, title_a='Complement A', title_b="Complement A'", set_a="A", set_b="A'", text_size=15): """ Complement Venn diagram parameters ---------- subs: 1 shows the both diagram.(default) 2 shows A filled diagram. 3 shows A' filled diagram. size: Set the figure size. The default value is 15. fill_color: Set the tfilling color. The default value is 'skyblue'. bg_color: Set the background color. The default value is 'white'. font_size: Set the title font size. The default value is 20. title_a: Set the title value for the left diagram. The default value is 'Complement A'. title_b: Set the title value for the left diagram. The default value is "Complement A'". set_a: Set the set name for the left diagram. The default value is 'A'. set_b: Set the set name for the left diagram. The default value is 'B'. text_size: Set the text size. The default value is 15. example ------- complement() complement(subs=2, size=5, fill_color='#3eacb5', bg_color='#c1d9db', font_color='#d40f19', font_size=25, title_a='Complement P', set_a='P', set_b="P'") """ if subs == 1: figure, (ax1, ax2) = plt.subplots(1, 2, figsize=(size, size)) elif subs == 2: figure, ax1 = plt.subplots(1, 1, figsize=(size, size)) else: figure, ax2 = plt.subplots(1, 1, figsize=(size, size)) if subs == 1 or subs == 2: # A filled v1 = venn3(subsets=(1, 1, 0, 1, 0, 0, 0), set_labels=('', '', ''), ax=ax1) c1 = venn3_circles(subsets=(1, 1, 0, 1, 0, 0, 0), ax=ax1) c1[0].set_lw(0) c1[2].set_lw(0) for area in ['001', '100']: v1.get_patch_by_id(area).set_color(bg_color) txt = v1.get_label_by_id(area) if txt: txt.set_text('') v1.get_patch_by_id('010').set_color(fill_color) v1.get_patch_by_id('010').set_alpha(1) v1.get_label_by_id('010').set_text(set_a) v1.get_label_by_id('010').set_fontsize(font_size) v1.get_label_by_id('010').set_color(font_color) v1.get_label_by_id('001').set_text(set_b) v1.get_label_by_id('001').set_fontsize(font_size) v1.get_label_by_id('001').set_color(font_color) ax1.set_axis_on() ax1.set_facecolor(bg_color) ax1.text(-1, 0.2, r'U', fontsize=font_size) ax1.set_title(title_a, fontsize=font_size) if subs == 1 or subs == 3: # A' filled v2 = venn3(subsets=(1, 1, 0, 1, 0, 0, 0), set_labels=('', '', ''), ax=ax2) c2 = venn3_circles(subsets=(1, 1, 0, 1, 0, 0, 0), ax=ax2) c2[0].set_lw(0) c2[2].set_lw(0) for area in ['001', '100']: v2.get_patch_by_id(area).set_color(fill_color) txt = v2.get_label_by_id(area) if txt: txt.set_text('') v2.get_patch_by_id('010').set_color(bg_color) v2.get_patch_by_id('010').set_alpha(1) v2.get_label_by_id('010').set_text(set_a) v2.get_label_by_id('010').set_fontsize(font_size) v2.get_label_by_id('010').set_color(font_color) v2.get_label_by_id('001').set_text(set_b) v2.get_label_by_id('001').set_fontsize(font_size) v2.get_label_by_id('001').set_color(font_color) ax2.set_axis_on() ax2.set_facecolor(fill_color) ax2.text(-1, 0.2, r'U', fontsize=font_size) ax2.set_title(title_b, fontsize=font_size) plt.rc('font', size=text_size) plt.show()
b1af76b212eca679b71c4dadc1e5da1983a796c1
{ "blob_id": "b1af76b212eca679b71c4dadc1e5da1983a796c1", "branch_name": "refs/heads/master", "committer_date": "2020-12-21T23:42:52", "content_id": "5ff4ad99c851690495dd11a5cb40dfbe5c2e1e1c", "detected_licenses": [ "MIT" ], "directory_id": "55aead826f8a1722f7e01cb2fceef50ecea5d82a", "extension": "py", "filename": "complement.py", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 285935998, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3789, "license": "MIT", "license_type": "permissive", "path": "/vennfig/complement.py", "provenance": "stack-edu-0063.json.gz:375380", "repo_name": "shinokada/vennfig", "revision_date": "2020-12-21T23:42:52", "revision_id": "41de83be4ee0740c3fc8a795e345b6b88dac6b63", "snapshot_id": "69c7dc54c91433fb0f2413a3133cbc752c6d8e20", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/shinokada/vennfig/41de83be4ee0740c3fc8a795e345b6b88dac6b63/vennfig/complement.py", "visit_date": "2023-02-02T00:26:25.216695", "added": "2024-11-18T22:26:09.143183+00:00", "created": "2020-12-21T23:42:52", "int_score": 3, "score": 3.21875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0081.json.gz" }
from scipy.interpolate import RegularGridInterpolator as rgi from numpy.lib.stride_tricks import as_strided import numpy as np def init_multigrid(proj, geo, alpha,alg): # WARNING: This takes a lot of memory! if alg=='SART': from tigre.Algorithms.SART import SART as italg if alg=='SIRT': from tigre.Algorithms.SIRT import SIRT as italg finalsize = geo.nVoxel maxval= max(proj.ravel()) minval = min(proj.ravel()) # Start with 16 (raise this for larger images) geo.nVoxel = np.array([16, 16, 16]) geo.dVoxel = geo.sVoxel / geo.nVoxel if (geo.nVoxel > finalsize).all(): return np.zeros(finalsize, dtype=np.float32) niter = 100 initres = np.zeros(geo.nVoxel, dtype=np.float32) while (geo.nVoxel != finalsize).all(): geo.dVoxel = geo.sVoxel / geo.nVoxel initres = italg(proj, geo, alpha, niter, init=initres,verbose=False) # get new dims(should be a way to do this more efficiently). geo.nVoxel = geo.nVoxel * 2 geo.nVoxel[geo.nVoxel > finalsize] = finalsize[geo.nVoxel > finalsize] geo.dVoxel = geo.sVoxel / geo.nVoxel (x,y,z)=( np.linspace(minval, maxval, geo.nVoxel[0]/2,dtype=np.float32), np.linspace(minval, maxval, geo.nVoxel[1]/2,dtype=np.float32), np.linspace(minval, maxval, geo.nVoxel[2]/2,dtype=np.float32) ) # evaluate the function sart at the points xv,yv,zv xv,yv,zv=[tile_array(tile_array(x,2), geo.nVoxel[0]**2), tile_array(tile_array(y,2), geo.nVoxel[0]**2), tile_array(tile_array(x,2), geo.nVoxel[0]**2)] initres = rgi((x, y, z), initres)(np.column_stack((xv,yv,zv))) initres = initres.reshape(geo.nVoxel) return initres def tile_array(mat, b1): r, = mat.shape rs, = mat.strides x = as_strided(mat, (r, b1), (rs, 0)) return x.reshape(r*b1)
f8d65cc5360b949c2815105833a12ebb36cf4590
{ "blob_id": "f8d65cc5360b949c2815105833a12ebb36cf4590", "branch_name": "refs/heads/master", "committer_date": "2019-04-29T18:15:10", "content_id": "16775d0e18e75238fdb69c73e2ae63cabf563b56", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "fb1006f30af6d30ecf15b7f5bcc3729640392c21", "extension": "py", "filename": "init_multigrid.py", "fork_events_count": 1, "gha_created_at": "2018-10-10T21:48:52", "gha_event_created_at": "2019-04-26T03:29:20", "gha_language": "MATLAB", "gha_license_id": "BSD-3-Clause", "github_id": 152494214, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1962, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/Python/python_build/tigre/Utilities/init_multigrid.py", "provenance": "stack-edu-0066.json.gz:71318", "repo_name": "nlaluzerne/TIGRE", "revision_date": "2019-04-29T18:15:10", "revision_id": "65c209a7757f7ea7f71c3aca3b585a39dfd1d0c6", "snapshot_id": "6d7e8c81f45a6e51df37768b58337e1aa95e493b", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/nlaluzerne/TIGRE/65c209a7757f7ea7f71c3aca3b585a39dfd1d0c6/Python/python_build/tigre/Utilities/init_multigrid.py", "visit_date": "2020-03-31T19:21:32.832706", "added": "2024-11-18T20:49:15.132274+00:00", "created": "2019-04-29T18:15:10", "int_score": 3, "score": 2.515625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0084.json.gz" }
<?php namespace App\Http\Controllers; use App\user_bin; use App\user; use Illuminate\Http\Request; class UserBinController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $user_bins = User_bin::all(); $users=User::all(); foreach($user_bins as $user_bin) { foreach($users as $user) { if($user_bin->user_id==$user->id) { $user_bin->user_id=$user->name; } } } return view('userbins',['user_bins'=>$user_bins,]); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * Display the specified resource. * * @param \App\user_bin $user_bin * @return \Illuminate\Http\Response */ public function show(user_bin $user_bin) { // } /** * Show the form for editing the specified resource. * * @param \App\user_bin $user_bin * @return \Illuminate\Http\Response */ public function edit(user_bin $user_bin) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\user_bin $user_bin * @return \Illuminate\Http\Response */ public function update(Request $request, user_bin $user_bin) { // } /** * Remove the specified resource from storage. * * @param \App\user_bin $user_bin * @return \Illuminate\Http\Response */ public function destroy(user_bin $user_bin) { // } }
e480acb5760f88f5d01f9fe5f27f64b6abf47d78
{ "blob_id": "e480acb5760f88f5d01f9fe5f27f64b6abf47d78", "branch_name": "refs/heads/master", "committer_date": "2020-09-07T17:46:47", "content_id": "4bd4e03e7910a5673b2f992f4f11b922b2590482", "detected_licenses": [ "MIT" ], "directory_id": "543c1b1d453799fa8d7f1535e83196db51719e77", "extension": "php", "filename": "UserBinController.php", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 292541126, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2042, "license": "MIT", "license_type": "permissive", "path": "/app/Http/Controllers/UserBinController.php", "provenance": "stack-edu-0054.json.gz:99187", "repo_name": "haider1041/thursday", "revision_date": "2020-09-07T17:46:47", "revision_id": "18cc8888de75d02c8bfbb4c32047776a0ff71b83", "snapshot_id": "2d1e46f1a37ae6e069c01b17bd4b51b2a05ab9fc", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/haider1041/thursday/18cc8888de75d02c8bfbb4c32047776a0ff71b83/app/Http/Controllers/UserBinController.php", "visit_date": "2022-12-25T18:43:35.879227", "added": "2024-11-18T23:23:24.421380+00:00", "created": "2020-09-07T17:46:47", "int_score": 2, "score": 2.4375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0072.json.gz" }
// Copyright 2013 The StudyGolang Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // http://studygolang.com // Author:polaris [email protected] package controller import ( "fmt" "html/template" "net/http" "strings" "config" "filter" "github.com/dchest/captcha" "github.com/gorilla/sessions" "github.com/studygolang/mux" "logger" "service" "util" ) // 用户注册 // uri: /account/register{json:(|.json)} func RegisterHandler(rw http.ResponseWriter, req *http.Request) { if _, ok := filter.CurrentUser(req); ok { util.Redirect(rw, req, "/") return } vars := mux.Vars(req) username := req.PostFormValue("username") // 请求注册页面 if username == "" || req.Method != "POST" || vars["json"] == "" { filter.SetData(req, map[string]interface{}{"captchaId": captcha.NewLen(4)}) req.Form.Set(filter.CONTENT_TPL_KEY, "/template/register.html") return } // 校验验证码 if !captcha.VerifyString(req.PostFormValue("captchaid"), req.PostFormValue("captchaSolution")) { fmt.Fprint(rw, `{"ok": 0, "error":"验证码错误"}`) return } // 入库 errMsg, err := service.CreateUser(req.PostForm) if err != nil { // bugfix:http://studygolang.com/topics/255 if errMsg == "" { errMsg = err.Error() } fmt.Fprint(rw, `{"ok": 0, "error":"`, errMsg, `"}`) return } // 注册成功,自动为其登录 setCookie(rw, req, req.PostFormValue("username")) // 发送欢迎邮件 go sendWelcomeMail([]string{req.PostFormValue("email")}) fmt.Fprint(rw, `{"ok": 1, "msg":"注册成功"}`) } func sendWelcomeMail(email []string) { content := `Welcome to Study Golang.<br><br> 欢迎您,成功注册成为 Golang中文社区 | Go语言学习园地 会员<br><br> Golang中文社区是一个Go语言技术社区,完全用Go语言开发。我们为gopher们提供一个好的学习交流场所。加入到社区中来,参与分享,学习,不断提高吧。前往 <a href="http://studygolang.com">Golang中文社区 | Go语言学习园地</a><br> <div style="text-align:right;">&copy;2012-2014 studygolang.com Golang中文社区 | Go语言学习园地</div>` service.SendMail("Golang中文社区 | Go语言学习园地 注册成功通知", content, email) } // 登录 // uri : /account/login{json:(|.json)} func LoginHandler(rw http.ResponseWriter, req *http.Request) { username := req.PostFormValue("username") if username == "" || req.Method != "POST" { filter.SetData(req, map[string]interface{}{"error": "非法请求"}) req.Form.Set(filter.CONTENT_TPL_KEY, "/template/login.html") return } vars := mux.Vars(req) suffix := vars["json"] // 处理用户登录 passwd := req.PostFormValue("passwd") userLogin, err := service.Login(username, passwd) if err != nil { if suffix != "" { logger.Errorln("login error:", err) fmt.Fprint(rw, `{"ok":0,"error":"`+err.Error()+`"}`) return } req.Form.Set(filter.CONTENT_TPL_KEY, "/template/login.html") filter.SetData(req, map[string]interface{}{"username": username, "error": err.Error()}) return } logger.Debugf("remember_me is %q\n", req.FormValue("remember_me")) // 登录成功,种cookie setCookie(rw, req, userLogin.Username) if suffix != "" { fmt.Fprint(rw, `{"ok":1,"msg":"success"}`) return } // 支持跳转到源页面 uri := "/" values := filter.NewFlash(rw, req).Flashes("uri") if values != nil { uri = values[0].(string) } logger.Debugln("uri===", uri) util.Redirect(rw, req, uri) } // 用户编辑个人信息 func AccountEditHandler(rw http.ResponseWriter, req *http.Request) { vars := mux.Vars(req) curUser, _ := filter.CurrentUser(req) if req.Method != "POST" || vars["json"] == "" { // 获取用户信息 user := service.FindUserByUsername(curUser["username"].(string)) // 设置模板数据 filter.SetData(req, map[string]interface{}{"user": user, "default_avatars": service.DefaultAvatars}) req.Form.Set(filter.CONTENT_TPL_KEY, "/template/user/edit.html") return } req.PostForm.Set("username", curUser["username"].(string)) if req.PostFormValue("open") != "1" { req.PostForm.Set("open", "0") } // 更新个人信息 errMsg, err := service.UpdateUser(req.PostForm) if err != nil { fmt.Fprint(rw, `{"ok": 0, "error":"`, errMsg, `"}`) return } fmt.Fprint(rw, `{"ok": 1, "msg":"个人资料更新成功!"}`) } // 更换头像 // uri: /account/change_avatar.json func ChangeAvatarHandler(rw http.ResponseWriter, req *http.Request) { curUser, _ := filter.CurrentUser(req) avatar, ok := req.PostForm["avatar"] if !ok { fmt.Fprint(rw, `{"ok": 0, "error":"非法请求!"}`) return } err := service.ChangeAvatar(curUser["uid"].(int), avatar[0]) if err != nil { fmt.Fprint(rw, `{"ok": 0, "error":"更换头像失败"}`) return } fmt.Fprint(rw, `{"ok": 1, "msg":"更换头像成功!"}`) } // 修改密码 // uri: /account/changepwd.json func ChangePwdHandler(rw http.ResponseWriter, req *http.Request) { curUser, _ := filter.CurrentUser(req) username := curUser["username"].(string) curPasswd := req.PostFormValue("cur_passwd") _, err := service.Login(username, curPasswd) if err != nil { // 原密码错误 fmt.Fprint(rw, `{"ok": 0, "error": "原密码填写错误!"}`) return } // 更新密码 errMsg, err := service.UpdatePasswd(username, req.PostFormValue("passwd")) if err != nil { fmt.Fprint(rw, `{"ok": 0, "error":"`, errMsg, `"}`) return } fmt.Fprint(rw, `{"ok": 1, "msg":"密码修改成功!"}`) } // 保存uuid和email的对应关系(TODO:重启如何处理,有效期问题) var resetPwdMap = map[string]string{} // 忘记密码 // uri: /account/forgetpwd func ForgetPasswdHandler(rw http.ResponseWriter, req *http.Request) { if _, ok := filter.CurrentUser(req); ok { util.Redirect(rw, req, "/") return } req.Form.Set(filter.CONTENT_TPL_KEY, "/template/user/forget_pwd.html") data := map[string]interface{}{"activeUsers": "active"} email := req.FormValue("email") if email == "" || req.Method != "POST" { filter.SetData(req, data) return } // 校验email是否存在 if service.EmailExists(email) { var uuid string for { uuid = util.GenUUID() if _, ok := resetPwdMap[uuid]; !ok { resetPwdMap[uuid] = email break } logger.Infoln("GenUUID 冲突....") } var emailUrl string if strings.HasSuffix(email, "@gmail.com") { emailUrl = "http://mail.google.com" } else { pos := strings.LastIndex(email, "@") emailUrl = "http://mail." + email[pos+1:] } data["success"] = template.HTML(`一封包含了重设密码链接的邮件已经发送到您的注册邮箱,按照邮件中的提示,即可重设您的密码。<a href="` + emailUrl + `" target="_blank">立即前往邮箱</a>`) go sendResetpwdMail(email, uuid) } else { data["error"] = "该邮箱没有在本社区注册过!" } filter.SetData(req, data) } // 重置密码 // uri: /account/resetpwd func ResetPasswdHandler(rw http.ResponseWriter, req *http.Request) { if _, ok := filter.CurrentUser(req); ok { util.Redirect(rw, req, "/") return } uuid := req.FormValue("code") if uuid == "" { util.Redirect(rw, req, "/account/login") return } req.Form.Set(filter.CONTENT_TPL_KEY, "/template/user/reset_pwd.html") data := map[string]interface{}{"activeUsers": "active"} passwd := req.FormValue("passwd") email, ok := resetPwdMap[uuid] if !ok { // 是提交重置密码 if passwd != "" && req.Method == "POST" { data["error"] = template.HTML(`非法请求!<p>将在<span id="jumpTo">3</span>秒后跳转到<a href="/" id="jump_url">首页</a></p>`) } else { data["error"] = template.HTML(`链接无效或过期,请重新操作。<a href="/account/forgetpwd">忘记密码?</a>`) } filter.SetData(req, data) return } data["valid"] = true data["code"] = uuid // 提交修改密码 if passwd != "" && req.Method == "POST" { // 简单校验 if len(passwd) < 6 || len(passwd) > 32 { data["error"] = "密码长度必须在6到32个字符之间" } else if passwd != req.FormValue("pass2") { data["error"] = "两次密码输入不一致" } else { // 更新密码 _, err := service.UpdatePasswd(email, passwd) if err != nil { data["error"] = "对不起,服务器错误,请重试!" } else { data["success"] = template.HTML(`密码重置成功,<p>将在<span id="jumpTo">3</span>秒后跳转到<a href="/account/login" id="jump_url">登录</a>页面</p>`) } } } filter.SetData(req, data) } // 发重置密码邮件 func sendResetpwdMail(email, uuid string) { content := `您好,` + email + `,<br/><br/> &nbsp;&nbsp;&nbsp;&nbsp;我们的系统收到一个请求,说您希望通过电子邮件重新设置您在 <a href="http://` + config.Config["domain"] + `">Golang中文社区</a> 的密码。您可以点击下面的链接重设密码:<br/><br/> &nbsp;&nbsp;&nbsp;&nbsp;http://` + config.Config["domain"] + `/account/resetpwd?code=` + uuid + ` <br/><br/> 如果这个请求不是由您发起的,那没问题,您不用担心,您可以安全地忽略这封邮件。<br/><br/> 如果您有任何疑问,可以回复这封邮件向我们提问。谢谢!<br/><br/> <div style="text-align:right;">&copy;2013 studygolang.com Golang中文社区 | Go语言学习园地</div>` service.SendMail("【Golang中文社区】重设密码 ", content, []string{email}) } func setCookie(rw http.ResponseWriter, req *http.Request, username string) { session, _ := filter.Store.Get(req, "user") if req.FormValue("remember_me") != "1" { // 浏览器关闭,cookie删除,否则保存30天 session.Options = &sessions.Options{ Path: "/", } } session.Values["username"] = username session.Save(req, rw) } // 注销 // uri : /account/logout func LogoutHandler(rw http.ResponseWriter, req *http.Request) { // 删除cookie信息 session, _ := filter.Store.Get(req, "user") session.Options = &sessions.Options{Path: "/", MaxAge: -1} session.Save(req, rw) // 重定向得到登录页(TODO:重定向到什么页面比较好?) util.Redirect(rw, req, "/account/login") }
1cc5e2b8335ba9e11ddcac6bbe0aa8c321153140
{ "blob_id": "1cc5e2b8335ba9e11ddcac6bbe0aa8c321153140", "branch_name": "refs/heads/master", "committer_date": "2014-11-21T14:38:48", "content_id": "e9853e1af58277daef7bd25fc7a68b83d3b7dff5", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "ba06240ab3213b748e4776c69559992cc409db22", "extension": "go", "filename": "account.go", "fork_events_count": 0, "gha_created_at": "2015-01-18T15:41:14", "gha_event_created_at": "2015-01-18T15:41:14", "gha_language": null, "gha_license_id": null, "github_id": 29430682, "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 10149, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/websites/code/studygolang/src/controller/account.go", "provenance": "stack-edu-0015.json.gz:561379", "repo_name": "mengqingshare/studygolang", "revision_date": "2014-11-21T14:38:48", "revision_id": "a30f200df21b1c593dfa88776249f97a970f50ac", "snapshot_id": "97d1b7aab60da8f8eea6e94af7939599800211a5", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/mengqingshare/studygolang/a30f200df21b1c593dfa88776249f97a970f50ac/websites/code/studygolang/src/controller/account.go", "visit_date": "2020-12-11T05:32:03.427611", "added": "2024-11-18T21:32:56.077255+00:00", "created": "2014-11-21T14:38:48", "int_score": 2, "score": 2.40625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0033.json.gz" }
import React, { Component } from 'react'; import { classNames } from '../../utils'; import Field from './components/Field'; import Link from './components/Link'; import Error from './components/Error'; import * as styles from './FormCard.scss'; class FormCard extends Component { static Field = Field; static Link = Link; static Error = Error; render() { const { children, header, blend = false, align = 'center', } = this.props; const headerMarkup = header && ( <h2 className={styles.header}>{header}</h2> ); const formCardClassName = classNames( styles.FormCard, styles[`${align}Text`], !blend && styles.card, ); const formElements = React.Children.toArray(children); const linkMarkup = []; for (let i = 0; i < formElements.length; i++) { if ( formElements[i].type && formElements[i].type.displayName === 'Link' ) { linkMarkup.push(formElements.splice(i, 1)); } } console.log(linkMarkup); return ( <div className={formCardClassName}> {headerMarkup} <form className={styles.form}>{formElements}</form> {linkMarkup} </div> ); } } export default FormCard;
c6779eaaa5302eea95ec334963136892503b45b9
{ "blob_id": "c6779eaaa5302eea95ec334963136892503b45b9", "branch_name": "refs/heads/master", "committer_date": "2018-10-24T22:12:20", "content_id": "240b808af17f85556a9305de766d362e18ba289a", "detected_licenses": [ "MIT" ], "directory_id": "010c199e61776a7942b3c1e71c70ec165d5871e5", "extension": "jsx", "filename": "FormCard.jsx", "fork_events_count": 0, "gha_created_at": "2018-05-26T03:58:05", "gha_event_created_at": "2018-10-24T22:12:21", "gha_language": "JavaScript", "gha_license_id": null, "github_id": 134927526, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1249, "license": "MIT", "license_type": "permissive", "path": "/client/shared/FormCard/FormCard.jsx", "provenance": "stack-edu-0032.json.gz:607877", "repo_name": "AndrewMusgrave/book-traders", "revision_date": "2018-10-24T22:12:20", "revision_id": "554aaea4f27a460eb5e534c853bac7288e520b32", "snapshot_id": "377d037ff1171fff46261be3d63bb35178777926", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/AndrewMusgrave/book-traders/554aaea4f27a460eb5e534c853bac7288e520b32/client/shared/FormCard/FormCard.jsx", "visit_date": "2020-03-18T15:45:05.940055", "added": "2024-11-19T02:19:56.613043+00:00", "created": "2018-10-24T22:12:20", "int_score": 2, "score": 2.34375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0050.json.gz" }
<?php namespace Tests\Unit; use App\DataProvider\Eloquent\Slip; use App\DataProvider\Eloquent\SlipRepository; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; class DataProvider_Eloquent_SlipRepositoryTest extends DataProvider_SlipRepositoryInterfaceTest { use RefreshDatabase; protected $slip; public function setUp(): void { parent::setUp(); $this->slip = new SlipRepository(); } public function tearDown(): void { Artisan::call('migrate:refresh'); parent::tearDown(); } /** * @test */ public function create_OneRecordIsCreated() { $bookId = (string) Str::uuid(); $outline = 'outline2'; $date = '2019-07-02'; $memo = 'memo2'; $isDraft = false; DB::statement('SET FOREIGN_KEY_CHECKS=0;'); $slipId = $this->slip->create($bookId, $outline, $date, $memo, null, $isDraft); DB::statement('SET FOREIGN_KEY_CHECKS=1;'); $this->assertDatabaseHas('bk2_0_slips', [ 'slip_id' => $slipId, 'book_id' => $bookId, 'slip_outline' => $outline, 'slip_memo' => $memo, 'date' => $date, 'is_draft' => $isDraft, ]); } /** * @test */ public function delete_OneRecordIsSoftDeleted() { $bookId = (string) Str::uuid(); $outline = 'outline4'; $memo = 'memo4'; $date = '2019-09-03'; $isDraft = false; DB::statement('SET FOREIGN_KEY_CHECKS=0;'); $slipId = factory(Slip::class)->create([ 'book_id' => $bookId, 'slip_outline' => $outline, 'slip_memo' => $memo, 'date' => $date, 'is_draft' => $isDraft, ])->slip_id; DB::statement('SET FOREIGN_KEY_CHECKS=1;'); $this->slip->delete($slipId); $this->assertSoftDeleted('bk2_0_slips', [ 'slip_id' => $slipId, 'book_id' => $bookId, 'slip_outline' => $outline, 'slip_memo' => $memo, 'date' => $date, 'is_draft' => $isDraft, ]); } /** * @test */ public function findAllDraftByBookId_ReturnSlips() { $bookId = (string) Str::uuid(); $outline = 'outline5'; $memo = 'memo5'; $date = '2019-10-03'; DB::statement('SET FOREIGN_KEY_CHECKS=0;'); $slipId = factory(Slip::class)->create([ 'book_id' => $bookId, 'slip_outline' => $outline, 'slip_memo' => $memo, 'date' => $date, 'is_draft' => true, ])->slip_id; DB::statement('SET FOREIGN_KEY_CHECKS=1;'); $slips_expected = [ ['slip_id' => $slipId, 'date' => $date, 'slip_outline' => $outline, 'slip_memo' => $memo], ]; $slips_actual = $this->slip->findAllDraftByBookId($bookId); $this->assertSame($slips_expected, $slips_actual); } /** * @test */ public function findById_ReturnSlip() { $bookId = (string) Str::uuid(); $outline = 'outline120'; $memo = 'memo120'; $date = '2019-01-22'; DB::statement('SET FOREIGN_KEY_CHECKS=0;'); $slipId = factory(Slip::class)->create([ 'book_id' => $bookId, 'slip_outline' => $outline, 'slip_memo' => $memo, 'date' => $date, 'is_draft' => false, ])->slip_id; DB::statement('SET FOREIGN_KEY_CHECKS=1;'); $slip_expected = ['book_id' => $bookId, 'slip_id' => $slipId, 'date' => $date, 'slip_outline' => $outline, 'slip_memo' => $memo]; $slip_actual = $this->slip->findById($slipId); $this->assertSame($slip_expected, $slip_actual); } /** * @test */ public function update_OneRecordIsUpdated() { $bookId = (string) Str::uuid(); $outline = 'outline6'; $memo = 'memo6'; $date = '2019-11-03'; $isDraft = false; $outline_updated = 'outline6_updated'; $memo_updated = 'memo6_updated'; $date_updated = '2019-12-03'; DB::statement('SET FOREIGN_KEY_CHECKS=0;'); $slipId = factory(Slip::class)->create([ 'book_id' => $bookId, 'slip_outline' => $outline, 'slip_memo' => $memo, 'date' => $date, 'is_draft' => $isDraft, ])->slip_id; DB::statement('SET FOREIGN_KEY_CHECKS=1;'); $this->slip->update($slipId, [ 'outline' => $outline_updated, 'memo' => $memo_updated, 'date' => $date_updated, ]); $this->assertDatabaseHas('bk2_0_slips', [ 'slip_id' => $slipId, 'book_id' => $bookId, 'slip_outline' => $outline_updated, 'slip_memo' => $memo_updated, 'date' => $date_updated, 'is_draft' => $isDraft, ]); } /** * @test */ public function updateIsDraft_IsDraftIsUpdated() { $bookId = (string) Str::uuid(); $outline = 'outline3'; $date = '2019-07-03'; $memo = 'memo3'; $isDraft = false; $isDraft_updated = true; DB::statement('SET FOREIGN_KEY_CHECKS=0;'); $slipId = factory(Slip::class)->create([ 'book_id' => $bookId, 'slip_outline' => $outline, 'slip_memo' => $memo, 'date' => $date, 'is_draft' => $isDraft, ])->slip_id; DB::statement('SET FOREIGN_KEY_CHECKS=1;'); $this->slip->updateIsDraft($slipId, $isDraft_updated); $this->assertDatabaseHas('bk2_0_slips', [ 'slip_id' => $slipId, 'book_id' => $bookId, 'slip_outline' => $outline, 'slip_memo' => $memo, 'date' => $date, 'is_draft' => $isDraft_updated, ]); } }
83d1a3d6d77a37a5066ba3c97122b83f701a61a4
{ "blob_id": "83d1a3d6d77a37a5066ba3c97122b83f701a61a4", "branch_name": "refs/heads/master", "committer_date": "2021-07-23T00:47:42", "content_id": "8b6d0869debe58d2a49b0fc52e8648c7e15e0339", "detected_licenses": [ "MIT" ], "directory_id": "e2991cf79a69c55b335425fd5b47eac1549283b6", "extension": "php", "filename": "DataProvider_Eloquent_SlipRepositoryTest.php", "fork_events_count": 1, "gha_created_at": "2019-11-19T10:38:07", "gha_event_created_at": "2023-04-19T20:12:54", "gha_language": "PHP", "gha_license_id": null, "github_id": 222671619, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 6309, "license": "MIT", "license_type": "permissive", "path": "/book-keeping/tests/Unit/DataProvider_Eloquent_SlipRepositoryTest.php", "provenance": "stack-edu-0051.json.gz:930184", "repo_name": "book-keeping/laraBookKeeping", "revision_date": "2021-07-23T00:47:42", "revision_id": "30939ed155d278ff45de94052b548460e1de0156", "snapshot_id": "6a23ed46a71eeac6042dc28146773fde31cbd365", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/book-keeping/laraBookKeeping/30939ed155d278ff45de94052b548460e1de0156/book-keeping/tests/Unit/DataProvider_Eloquent_SlipRepositoryTest.php", "visit_date": "2023-04-29T21:48:09.919759", "added": "2024-11-19T00:26:57.104419+00:00", "created": "2021-07-23T00:47:42", "int_score": 2, "score": 2.296875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0069.json.gz" }
package slimeknights.tconstruct.world.worldgen.trees.feature; import com.mojang.serialization.Codec; import net.minecraft.core.BlockPos; import net.minecraft.util.Mth; import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; import net.minecraft.world.level.levelgen.feature.HugeFungusConfiguration; import net.minecraft.world.level.levelgen.feature.HugeFungusFeature; import slimeknights.tconstruct.world.worldgen.trees.config.SlimeFungusConfig; import java.util.Random; public class SlimeFungusFeature extends HugeFungusFeature { public SlimeFungusFeature(Codec<HugeFungusConfiguration> codec) { super(codec); } @Override public boolean place(FeaturePlaceContext<HugeFungusConfiguration> context) { if (!(context.config() instanceof SlimeFungusConfig config)) { return super.place(context); } // must be on the right ground WorldGenLevel level = context.level(); BlockPos pos = context.origin(); if (!level.getBlockState(pos.below()).is(config.getGroundTag())) { return false; } // ensure not too tall Random random = context.random(); int height = Mth.nextInt(random, 4, 13); if (random.nextInt(12) == 0) { height *= 2; } if (!config.planted && pos.getY() + height + 1 >= context.chunkGenerator().getGenDepth()) { return false; } // actual generation boolean flag = !config.planted && random.nextFloat() < 0.06F; level.setBlock(pos, Blocks.AIR.defaultBlockState(), 4); this.placeStem(level, random, config, pos, height, flag); this.placeHat(level, random, config, pos, height, flag); return true; } }
d87ab0b4b094cb2fb277ff72cf3b271b9c62fc54
{ "blob_id": "d87ab0b4b094cb2fb277ff72cf3b271b9c62fc54", "branch_name": "refs/heads/1.18.2", "committer_date": "2023-08-09T07:07:40", "content_id": "12c75f0b7947d797f1cc7d180dea962c56674529", "detected_licenses": [ "MIT" ], "directory_id": "a1f94955c480d73d042fe939cf229774ac1c0646", "extension": "java", "filename": "SlimeFungusFeature.java", "fork_events_count": 911, "gha_created_at": "2013-01-22T20:46:32", "gha_event_created_at": "2023-08-22T15:57:33", "gha_language": "Java", "gha_license_id": "MIT", "github_id": 7760890, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1735, "license": "MIT", "license_type": "permissive", "path": "/src/main/java/slimeknights/tconstruct/world/worldgen/trees/feature/SlimeFungusFeature.java", "provenance": "stack-edu-0021.json.gz:373134", "repo_name": "SlimeKnights/TinkersConstruct", "revision_date": "2023-08-09T07:07:40", "revision_id": "09626c7f3f379ebe68e37312395af07b8c16e475", "snapshot_id": "6d581a9a52df175b1a9bb7cee17c1822ccfc00b4", "src_encoding": "UTF-8", "star_events_count": 1126, "url": "https://raw.githubusercontent.com/SlimeKnights/TinkersConstruct/09626c7f3f379ebe68e37312395af07b8c16e475/src/main/java/slimeknights/tconstruct/world/worldgen/trees/feature/SlimeFungusFeature.java", "visit_date": "2023-08-26T08:59:01.749216", "added": "2024-11-18T23:24:29.788646+00:00", "created": "2023-08-09T07:07:40", "int_score": 2, "score": 2.21875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0039.json.gz" }
package com.pengyifan.leetcode; import static org.junit.Assert.*; import org.junit.Test; import com.pengyifan.leetcode.commons.ListNode; public class PartitionListTest { PartitionList s = new PartitionList(); @Test public void testPartition() { ListNode head = ListNode.createList(new int[] { 2, 1 }); head = s.partition(head, 2); assertEquals(1, head.val); head = head.next; assertEquals(2, head.val); head = head.next; assertNull(head); } }
158affc6242a6095294a4f414f9caa6c4cd9967d
{ "blob_id": "158affc6242a6095294a4f414f9caa6c4cd9967d", "branch_name": "refs/heads/master", "committer_date": "2019-11-24T01:53:35", "content_id": "329cc69eee655b222cb312ff45779068d8dccade", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "123ca08e533c85355880efd7b070758b18e7f84e", "extension": "java", "filename": "PartitionListTest.java", "fork_events_count": 0, "gha_created_at": "2018-01-10T20:36:41", "gha_event_created_at": "2019-11-24T02:40:55", "gha_language": "Java", "gha_license_id": "BSD-3-Clause", "github_id": 117008032, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 485, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/src/test/java/com/pengyifan/leetcode/PartitionListTest.java", "provenance": "stack-edu-0024.json.gz:409461", "repo_name": "aav789/pengyifan-leetcode", "revision_date": "2019-11-24T01:53:35", "revision_id": "aa0b1062c3e22ce50f6a97edb906338d86e4e9ae", "snapshot_id": "d9e33c019fbb15ee532768de30ecccf83b32d81b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/aav789/pengyifan-leetcode/aa0b1062c3e22ce50f6a97edb906338d86e4e9ae/src/test/java/com/pengyifan/leetcode/PartitionListTest.java", "visit_date": "2022-03-07T02:29:44.944557", "added": "2024-11-19T01:36:11.270691+00:00", "created": "2019-11-24T01:53:35", "int_score": 2, "score": 2.4375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0042.json.gz" }
import React from "react" import { Link, graphql, useStaticQuery } from "gatsby" import headerStyles from "./header.module.scss" const Header = () => { const data = useStaticQuery(graphql` query { site { siteMetadata { title } } } `) const pages = [ { id: 1, name: "Home", route: "/" }, { id: 2, name: "Blog", route: "/blog" }, { id: 3, name: "About", route: "/about" }, { id: 4, name: "Contact", route: "/contact" }, ] return ( <header className={headerStyles.header}> <h1> <Link to="/" className={headerStyles.title}> { data.site.siteMetadata.title } </Link> </h1> <nav> <ul className={headerStyles.navList}> {pages.map(page => ( <li key={page.id}> <Link className={headerStyles.navItem} activeClassName={headerStyles.activeNavItem} to={page.route} > {page.name} </Link> </li> ))} </ul> </nav> </header> ) } export default Header
16999e7865f198c955ea8b1e145f5a2075f36141
{ "blob_id": "16999e7865f198c955ea8b1e145f5a2075f36141", "branch_name": "refs/heads/master", "committer_date": "2019-04-19T21:56:34", "content_id": "11a524f70b080a54b78e51d61a570d8b1fd1b08a", "detected_licenses": [ "MIT" ], "directory_id": "3319acd7154b2ee6e3291f42f39df0856e3897b1", "extension": "js", "filename": "Header.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 182159552, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1135, "license": "MIT", "license_type": "permissive", "path": "/src/components/Header.js", "provenance": "stack-edu-0033.json.gz:685214", "repo_name": "githubMizz/gatsby-blog", "revision_date": "2019-04-19T21:56:34", "revision_id": "6a1d25a58bca1cc1df1faaa764845495ed7944e8", "snapshot_id": "28351aec8a67b816fc9521e0a53dd974fb04551d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/githubMizz/gatsby-blog/6a1d25a58bca1cc1df1faaa764845495ed7944e8/src/components/Header.js", "visit_date": "2020-05-15T08:25:58.538376", "added": "2024-11-19T01:54:49.372342+00:00", "created": "2019-04-19T21:56:34", "int_score": 2, "score": 2.3125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0051.json.gz" }
<?php namespace App\Http\Controllers; use App\Clock; use Illuminate\Http\Request; class ClockController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $clock = Clock::all(); return view('clock.list', compact('clock')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('clock.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $validatedData = $request->validate([ 'name'=>'bail|required', 'price'=>'bail|required', 'vendor'=>'required' ]); $clock = new Clock(); $clock->name = $request->input('name'); $clock->price = $request->input('price'); $clock->vendor= $request->input('vendor'); $clock->save(); return redirect()->route('clocks.index'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $clock = Clock::findOrFail($id); return view('clock.edit',compact('clock')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $clock = Clock::findOrFail($id); $clock->name = $request->input('name'); $clock->price = $request->input('price'); $clock->vendor= $request->input('vendor'); $clock->save(); return redirect()->route('clocks.index'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $clock = Clock::findOrFail($id); $clock->delete(); return redirect()->route('clocks.index'); } public function search(Request $request){ $keyword = $request->input('keyword'); if (!$keyword){ return redirect()->route('clocks.index'); } $clock = Clock::where('name','LIKE','%'.$keyword.'%')->paginate(2); return view('clock.list',compact('clock')); } }
d39b47491105d750363850bab752641fbd12f023
{ "blob_id": "d39b47491105d750363850bab752641fbd12f023", "branch_name": "refs/heads/master", "committer_date": "2019-10-03T03:57:39", "content_id": "415aba57cdbac8192d67ad8eaa8a3dfd539d80db", "detected_licenses": [ "MIT" ], "directory_id": "a0ac648eb46086838fb4d8dd546c1c2c7d67d5de", "extension": "php", "filename": "ClockController.php", "fork_events_count": 0, "gha_created_at": "2019-10-03T03:57:25", "gha_event_created_at": "2023-01-04T12:00:26", "gha_language": "PHP", "gha_license_id": null, "github_id": 212493459, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2787, "license": "MIT", "license_type": "permissive", "path": "/app/Http/Controllers/ClockController.php", "provenance": "stack-edu-0050.json.gz:573903", "repo_name": "namtiennguyen97/repeat-all-things", "revision_date": "2019-10-03T03:57:39", "revision_id": "b69fa67d99f4598a0a77b4e64a794b0dcbba4315", "snapshot_id": "c24380cc932ee4579ab1f5a02a091c940fa31838", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/namtiennguyen97/repeat-all-things/b69fa67d99f4598a0a77b4e64a794b0dcbba4315/app/Http/Controllers/ClockController.php", "visit_date": "2023-01-24T19:52:58.822939", "added": "2024-11-18T21:01:26.928924+00:00", "created": "2019-10-03T03:57:39", "int_score": 3, "score": 2.609375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0068.json.gz" }
'use strict'; var bitcore = require('bitcore'); var $ = bitcore.util.preconditions; var _ = bitcore.deps._; var BufferUtil = bitcore.util.buffer; var NULL = '0000000000000000000000000000000000000000000000000000000000000000'; function BlockChain() { this.tip = NULL; this.work = {}; this.work[NULL] = 0; this.height = {}; this.height[NULL] = -1; this.hashByHeight = { '-1': NULL }; this.next = {}; this.prev = {}; } BlockChain.NULL = NULL; BlockChain.fromObject = function(obj) { var blockchain = new BlockChain(); blockchain.tip = obj.tip; blockchain.work = obj.work; blockchain.hashByHeight = obj.hashByHeight; blockchain.height = obj.height; blockchain.next = obj.next; blockchain.prev = obj.prev; return blockchain; }; var getWork = function(bits) { var bytes = ((bits >>> 24) & 0xff) >>> 0; return ((bits & 0xffffff) << (8 * (bytes - 3))) >>> 0; }; BlockChain.prototype.addData = function(header) { $.checkArgument(header instanceof bitcore.Block.BlockHeader, 'Argument is not a BlockHeader instance'); var prevHash = BufferUtil.reverse(header.prevHash).toString('hex'); var hash = header.hash; this.work[hash] = this.work[prevHash] + getWork(header.bits); this.prev[hash] = prevHash; }; BlockChain.prototype._appendNewBlock = function(hash) { var toUnconfirm = []; var toConfirm = []; var self = this; var pointer = hash; while (_.isUndefined(this.height[pointer])) { toConfirm.push(pointer); pointer = this.prev[pointer]; } var commonAncestor = pointer; pointer = this.tip; while (pointer !== commonAncestor) { toUnconfirm.push(pointer); pointer = this.prev[pointer]; } toConfirm.reverse(); toUnconfirm.map(function(hash) { self.unconfirm(hash); }); toConfirm.map(function(hash) { self.confirm(hash); }); return { unconfirmed: toUnconfirm, confirmed: toConfirm }; }; BlockChain.prototype.proposeNewHeader = function(header) { $.checkArgument(header instanceof bitcore.Block.BlockHeader, 'Argument is not a BlockHeader instance'); var prevHash = BufferUtil.reverse(header.prevHash).toString('hex'); var hash = header.hash; $.checkState(this.hasData(prevHash), 'No previous data to estimate work'); this.addData(header); var work = this.work[hash]; var tipWork = this.work[this.tip]; $.checkState(!_.isUndefined(work), 'No work found for ' + hash); $.checkState(!_.isUndefined(tipWork), 'No work found for tip ' + this.tip); if (work > tipWork) { return this._appendNewBlock(hash); } return { unconfirmed: [], confirmed: [] }; }; BlockChain.prototype.proposeNewBlock = function(block) { $.checkArgument(block instanceof bitcore.Block, 'Argument is not a Block instance'); return this.proposeNewHeader(block.header); }; BlockChain.prototype.confirm = function(hash) { var prevHash = this.prev[hash]; $.checkState(prevHash === this.tip, 'Attempting to confirm a non-contiguous block.'); this.tip = hash; var height = this.height[prevHash] + 1; this.next[prevHash] = hash; this.hashByHeight[height] = hash; this.height[hash] = height; }; BlockChain.prototype.unconfirm = function(hash) { var prevHash = this.prev[hash]; $.checkState(hash === this.tip, 'Attempting to unconfirm a non-tip block'); this.tip = prevHash; var height = this.height[hash]; delete this.next[prevHash]; delete this.hashByHeight[height]; delete this.height[hash]; }; BlockChain.prototype.hasData = function(hash) { return !_.isUndefined(this.work[hash]); }; BlockChain.prototype.prune = function() { var self = this; _.each(this.prev, function(key) { if (!self.height[key]) { delete self.prev[key]; delete self.work[key]; } }); }; BlockChain.prototype.toObject = function() { return { tip: this.tip, work: this.work, next: this.next, hashByHeight: this.hashByHeight, height: this.height, prev: this.prev }; }; BlockChain.prototype.toJSON = function() { return JSON.stringify(this.toObject()); }; BlockChain.prototype.getBlockLocator = function() { $.checkState(this.tip); $.checkState(!_.isUndefined(this.height[this.tip])); var result = []; var currentHeight = this.getCurrentHeight(); var exponentialBackOff = 1; for (var i = 0; i < 10; i++) { if (currentHeight >= 0) { result.push(this.hashByHeight[currentHeight--]); } } while (currentHeight > 0) { result.push(this.hashByHeight[currentHeight]); currentHeight -= exponentialBackOff; exponentialBackOff *= 2; } return result; }; BlockChain.prototype.getCurrentHeight = function() { return this.height[this.tip]; }; module.exports = BlockChain;
d8ca3e5aa5cedf67144c3f05b20755a020ead39f
{ "blob_id": "d8ca3e5aa5cedf67144c3f05b20755a020ead39f", "branch_name": "refs/heads/master", "committer_date": "2015-07-06T19:58:22", "content_id": "2ba21d43c4eeb849b916f0ff22acd1e1150f6362", "detected_licenses": [ "MIT" ], "directory_id": "422433333f719481ea8a77a97149980cd1a2b9c7", "extension": "js", "filename": "blockchain.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4692, "license": "MIT", "license_type": "permissive", "path": "/lib/blockchain.js", "provenance": "stack-edu-0034.json.gz:696552", "repo_name": "PalmerEk/bitcore-node", "revision_date": "2015-07-06T19:58:22", "revision_id": "c45bd0c4ee87d9e145d6675f3b211fc386c0ea7c", "snapshot_id": "7eb791f414d120dcce026fdd76eccb8f5d03034d", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/PalmerEk/bitcore-node/c45bd0c4ee87d9e145d6675f3b211fc386c0ea7c/lib/blockchain.js", "visit_date": "2020-12-11T07:27:01.727471", "added": "2024-11-19T03:06:44.207109+00:00", "created": "2015-07-06T19:58:22", "int_score": 3, "score": 2.578125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0052.json.gz" }
import React, { Component } from 'react' import { Link } from 'react-router-dom' import M from 'materialize-css' import InputMask from 'react-input-mask' import Conecta from '../constants/Conecta' import { Redirect } from 'react-router' export default class Editar extends Component { state = { id: 0, nome: '', fabricacao: '', perecivel: false, validade: '', preco: '', erroNome: false, erroFabricacao: false, erroPerecivel: false, erroValidade: false, erroPreco: false, redirect: false } async componentDidMount() { const { match: { params } } = this.props; const produto = await Conecta.get(`/produtos/${params.id}`) let preco = "" + produto.data.preco let partesPreco = preco.split(".") produto.data.preco = (partesPreco[0] + "," + (partesPreco[1] === undefined ? '00' : partesPreco[1])).toString() this.setState(produto.data) } handleChange = e => { this.setState({ [e.target.name]: e.target.value }) } handleChange = e => { const isCheckbox = e.target.type === "checkbox"; this.setState({ [e.target.name]: isCheckbox ? e.target.checked : e.target.value }) } validacoes = () => { let erroNome = ''; let erroFabricacao = ''; let erroValidade = ''; let erroPreco = ''; if (!this.state.nome) { erroNome = 'O nome não pode ser vazio!' } if (!this.state.fabricacao) { erroFabricacao = 'A data de fabricação não pode ser vazia!' } if (this.state.perecivel) { if (!this.state.validade) { erroValidade = 'A data de validade não pode ser vazia!' } let partesDataFabricacao = this.state.fabricacao.split("/"); let dataFabricacao = new Date(partesDataFabricacao[2], partesDataFabricacao[1] - 1, partesDataFabricacao[0]); let partesDataValidade = this.state.validade.split("/"); let dataValidade = new Date(partesDataValidade[2], partesDataValidade[1] - 1, partesDataValidade[0]) if (dataFabricacao > dataValidade) { erroValidade = 'A data de validade não pode ser menor que a de fabricação!' } } if (!this.state.preco) { erroPreco = 'O preço não pode ser vazio!' } else if (this.state.preco.search('^[0-9]+(,[0-9]{1,2})?$')) { erroPreco = 'O preço dever ser em reais, ex.: 22,50' } if (erroNome || erroFabricacao || erroPreco || erroValidade) { this.setState({ erroNome, erroFabricacao, erroValidade, erroPreco }) return false } return true } handleSubmit = async (e) => { e.preventDefault() const alterado = { nome: this.state.nome, fabricacao: this.state.fabricacao, perecivel: this.state.perecivel, validade: this.state.validade, preco: this.state.preco } //EXECUTA O UPDATE NO ARQUIVO db.json REFERENTE AO PRODUTO A SER ATUALIZADO if (this.validacoes()) { try { alterado.validade = alterado.validade === '' ? '—' : alterado.validade alterado.validade = alterado.perecivel === false ? '—' : alterado.validade let partesPreco = alterado.preco.split(","); alterado.preco = parseFloat(partesPreco[0] + "." + partesPreco[1]) const produto = await Conecta.put(`/produtos/${this.state.id}`, alterado) this.setState({ redirect: true }) M.toast({ html: `Produto de id ${produto.data.id} alterado com sucesso!` }) } catch (erro) { alert('Ops! Algo deu errado: ' + erro) } } } render() { if (this.state.redirect) { return <Redirect to="/produtos" /> } else { return ( <div className="row spacing"> <div className="col s12"> <div className="card-panel"> <h5 className="grey-text"><strong>EDITAR PRODUTO</strong></h5> <form className="panel-produto" onSubmit={this.handleSubmit}> <div className="row"> <div className="input-field col s12"> <input id="nome" name="nome" type="text" className={this.state.erroNome ? "error-input" : ''} onChange={this.handleChange} value={this.state.nome} /> <label htmlFor="nome" className={this.state.erroNome ? "red-text" : this.state.nome !== "" ? "active" : ""}>Nome do produto</label> <span className="helper-text red-text">{this.state.erroNome}</span> </div> <div className="input-field col s12"> <InputMask id="fabricacao" name="fabricacao" type="text" className={this.state.erroFabricacao ? "error-input" : ''} onChange={this.handleChange} value={this.state.fabricacao} mask="99/99/9999"></InputMask> <label htmlFor="fabricacao" className={this.state.erroFabricacao ? "red-text" : this.state.fabricacao !== "" ? "active" : ""}>Data de fabricação</label> <span className="helper-text red-text">{this.state.erroFabricacao}</span> </div> <div className="input-field col s12"> <InputMask id="preco" name="preco" type="text" className={this.state.erroPreco ? "error-input" : ''} onChange={this.handleChange} value={this.state.preco}></InputMask> <label htmlFor="preco" className={this.state.erroPreco ? "red-text" : this.state.preco !== "" ? "active" : ""}>Preço do produto</label> <span className="helper-text red-text">{this.state.erroPreco}</span> </div> {this.state.perecivel ? <div className="input-field col s12"> <InputMask id="validade" name="validade" type="text" className={this.state.erroValidade ? "error-input" : ''} onChange={this.handleChange} value={this.state.validade} mask="99/99/9999"></InputMask> <label htmlFor="validade" className={this.state.erroValidade ? "red-text" : this.state.validade !== "" ? "active" : ""}>Data de validade</label> <span className="helper-text red-text">{this.state.erroValidade}</span> </div> : ''} <div className="input-field col s12"> <label> <input name="perecivel" type="checkbox" className="filled-in" onChange={this.handleChange} value={this.state.perecivel} checked={this.state.perecivel} /> <span>Perecível</span> </label> <br /> </div> <div className="input-field col s12"> <button type="submit" className="btn waves-effect waves-light col s12">EDITAR</button> </div> </div> </form> </div> </div> <div className="col s12 right-align"> <Link to="/produtos" className="btn waves-effect waves-light">VOLTAR</Link> </div> </div> ) } } }
fc544ec5ea021613a84a2f009a485d5b8f9948e6
{ "blob_id": "fc544ec5ea021613a84a2f009a485d5b8f9948e6", "branch_name": "refs/heads/master", "committer_date": "2020-02-07T13:39:58", "content_id": "209fac53df2d8c4e6654b8adbc5cc9ace36507c3", "detected_licenses": [ "MIT" ], "directory_id": "68da7eed86f81eed132b19968db3d9ba6ad7ad48", "extension": "js", "filename": "Editar.js", "fork_events_count": 0, "gha_created_at": "2020-02-03T16:46:53", "gha_event_created_at": "2023-01-05T06:23:35", "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 238013640, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 7874, "license": "MIT", "license_type": "permissive", "path": "/src/components/Editar.js", "provenance": "stack-edu-0036.json.gz:764693", "repo_name": "rafatheonly/teste-hox", "revision_date": "2020-02-07T13:39:58", "revision_id": "1e4523c049f7ec207fbd535c355a47f4b3d9219c", "snapshot_id": "08e64f8cc4e7bd5a0df6ab2f749736fde0450a1f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/rafatheonly/teste-hox/1e4523c049f7ec207fbd535c355a47f4b3d9219c/src/components/Editar.js", "visit_date": "2023-01-11T19:53:41.796421", "added": "2024-11-19T01:39:00.188613+00:00", "created": "2020-02-07T13:39:58", "int_score": 3, "score": 2.546875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0054.json.gz" }
# from augmentations.sed_default_augment import get_transforms from augmentations.sed_background_augment import get_transforms from config_params.example_config import Parameters from dataloaders.sed_dataset import SedDataset from torch.utils.data import DataLoader from ignite.utils import convert_tensor from models.sed_models import PANNsDense121Att import ignite.distributed as idist from loss.sed_scaled_pos_neg_focal_loss import SedScaledPosNegFocalLoss def test_dataloader(): hparams = Parameters() transforms = get_transforms(bckgrd_aug_dir=hparams.bckgrd_aug_dir, secondary_bckgrd_aug_dir=hparams.secondary_bckgrd_aug_dir) train_ds = SedDataset(**hparams.train_ds_params, transform=transforms['train']) sampler = train_ds.sampler(train_ds, train_ds.get_label) kwargs = {"batch_size": hparams.train_bs, "num_workers": hparams.train_num_workers, "shuffle": False, "drop_last":True, "sampler": sampler, "worker_init_fn": train_ds.additional_loader_params['worker_init_fn'], 'pin_memory': True} train_loader = DataLoader(train_ds, **kwargs) dataloader_iter = iter(train_loader) for i in train_ds: print(i.keys()) break batch = next(dataloader_iter) # prepare_batch method of SedEngine device = idist.device() x = convert_tensor(batch["waveforms"], device=device, non_blocking=True) bs, c, s = x.shape y_target = {} all_labels = convert_tensor(batch["all_labels"], device=device, non_blocking=True) y_target["all_labels"] = all_labels primary_labels = convert_tensor(batch["primary_labels"], device=device, non_blocking=True) secondary_labels = convert_tensor(batch["secondary_labels"], device=device, non_blocking=True) y_target["secondary_labels"] = secondary_labels mixup_lambda = None x, y = ((x, mixup_lambda), {"all_labels": all_labels, "primary_labels": primary_labels, "secondary_labels": secondary_labels}) # create model model = PANNsDense121Att(**hparams.model_config).to("cuda") model.train() y_pred = model(x) criterion = SedScaledPosNegFocalLoss(**hparams.criterion_params) print(y) test_dataloader()
a2b0b0d7d62fb6c1bb177eafafdc8ab9db6dc509
{ "blob_id": "a2b0b0d7d62fb6c1bb177eafafdc8ab9db6dc509", "branch_name": "refs/heads/main", "committer_date": "2021-04-18T01:27:05", "content_id": "811ca82ce74fc89392f21059d63492476e37d432", "detected_licenses": [ "MIT" ], "directory_id": "3f4652e5bb6a05d749223f93f62ed935c15f9b92", "extension": "py", "filename": "test_dataloader_in_sed_dataset.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 354039136, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2162, "license": "MIT", "license_type": "permissive", "path": "/kaggle_birdsong_recognition/src/test/test_dataloader_in_sed_dataset.py", "provenance": "stack-edu-0064.json.gz:88344", "repo_name": "wmmxk/cornell_birdcall", "revision_date": "2021-04-18T01:27:05", "revision_id": "d395aab619e011d3e967056ad8f02f95e7f2c18e", "snapshot_id": "834b735ec735d04f26c27997cc195749499f4cc7", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/wmmxk/cornell_birdcall/d395aab619e011d3e967056ad8f02f95e7f2c18e/kaggle_birdsong_recognition/src/test/test_dataloader_in_sed_dataset.py", "visit_date": "2023-04-03T12:20:38.383091", "added": "2024-11-18T21:33:30.368162+00:00", "created": "2021-04-18T01:27:05", "int_score": 2, "score": 2.125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0082.json.gz" }
<?php namespace App\Http\Controllers\Admin; use Carbon\Carbon; use App\Models\Section; use App\Models\Category; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Auth; class DashboardController extends Controller { public function dashboard() { $user_id = Auth::user()->id; $elements = DB::table('elements')->where([ ['user_id', '=', $user_id], ['parent_id', '=', 0], ])->get(); return view('admin.dashboard', ['elements' => $elements]); } public function create_note(Request $request){ if($request->ajax()){ if (Auth::user()){ $element_name = $request->element_name; $parent_id = $request->parent_id; $parent_complex_id = $request->parent_complex_id; $user_id = Auth::user()->id; $date = Carbon::now(); if($parent_id == null && $parent_complex_id == null){ $parent_id = 0; $id_note = DB::table('elements')->insertGetId( array('element_name' => $element_name, 'parent_id' => $parent_id, 'complex_id' => $parent_id, 'user_id' => $user_id, 'created_at' => $date, 'updated_at' => $date) ); $result = DB::update('update elements set complex_id = ? where id = ?', [ $id_note, $id_note ]); } else if($parent_id != null){ $id_note = DB::table('elements')->insertGetId( array('element_name' => $element_name, 'parent_id' => $parent_id, 'complex_id' => $parent_complex_id, 'user_id' => $user_id, 'created_at' => $date, 'updated_at' => $date) ); $complex_id = $parent_complex_id . '-' . $id_note; $result = DB::update('update elements set complex_id = ? where id = ?', [ $complex_id, $id_note ]); } return $result; } } } public function element_data(Request $request){ if($request->ajax()){ if (Auth::user()){ $user_id = Auth::user()->id; $elements = DB::table('elements')->where([ ['parent_id', '=', $request->parent_id], ['user_id', '=', $user_id], ])->get(); return $elements; } } } public function remove_element(Request $request){ if($request->ajax()){ if (Auth::user()){ $element_id = $request->element_id; $user_id = Auth::user()->id; $attributes = DB::table('attributes')->where([ ['element_id', '=', $request->element_id], ['user_id', '=', $user_id], ])->get(); $arr = []; foreach($attributes as $attr){ DB::table('attributes_value')->where('attribute_id', $attr->id)->where('user_id', $user_id)->delete(); } DB::table('attributes')->where('element_id', $element_id)->where('user_id', $user_id)->delete(); $result = DB::table('elements')->where('id', $element_id)->where('user_id', $user_id)->delete(); return $result; } } } public function get_remove_elements(Request $request){ if($request->ajax()){ if (Auth::user()){ $element_id = $request->element_id; $user_id = Auth::user()->id; $elements = DB::table('elements')->where([ ['parent_id', '=', $request->element_id], ['user_id', '=', $user_id], ])->get(); return $elements; } } } public function show_elements(Request $request){ if($request->ajax()){ if (Auth::user()){ $element_id = $request->element_id; return $element_id; } } } public function edit_element(Request $request){ if($request->ajax()){ if (Auth::user()){ $user_id = Auth::user()->id; $date = Carbon::now(); $element_id = $request->element_id; $name = $request->element_name; $result = DB::update('update elements set element_name = ? where id = ?', [ $name, $element_id ]); } } return $result; } public function create_attr(Request $request){ if($request->ajax()){ if (Auth::user()){ $user_id = Auth::user()->id; $date = Carbon::now(); $element_id = $request->attrubute_id; $attribute_bool = $request->attribute_bool; $attribute_file = $request->attribute_file; $attribute_ip = $request->attribute_ip; $attribute_name = $request->attribute_name; $attribute_text = $request->attribute_text; $attribute_varchar = $request->attribute_varchar; $description = $request->description; $double_2 = $request->double_2; $double_15 = $request->double_15; $number_attribute = $request->number_attribute; $time_first = $request->time_first; $time_second = $request->time_second; $attribute_json = null; if($attribute_name != null){ $id_note = DB::table('attributes')->insertGetId( array('user_id' => $user_id, 'element_id' => $element_id, 'attribute_name' => $attribute_name, 'attribute_description' => $description, 'created_at' => $date, 'updated_at' => $date) ); if($time_first != null || $time_second != null || $number_attribute != null || $double_2 != null || $double_15 != null || $attribute_text != null || $attribute_varchar != null || $attribute_file != null || $attribute_ip != null || $attribute_bool != null){ $result = DB::table('attributes_value')->insertGetId( array('user_id' => $user_id, 'attribute_id' => $id_note, 'attribute_time_first' => $time_first, 'attribute_time_second' => $time_second, 'attribute_int' => $number_attribute, 'attribute_float' => $double_2, 'attribute_double' => $double_15, 'attribute_text' => $attribute_text, 'attribute_varchar' => $attribute_varchar, 'attribute_img' => $attribute_file, 'attribute_bool' => $attribute_bool, 'attribute_IP' => $attribute_ip, 'attribute_json' => $attribute_json, 'created_at' => $date, 'updated_at' => $date) ); } else { $result = null; } } else { $result = null; } return $result; } } } public function get_attr(Request $request){ if($request->ajax()){ if (Auth::user()){ $element_id = $request->element_id; $user_id = Auth::user()->id; $attributes = DB::table('attributes')->where([ ['element_id', '=', $element_id], ['user_id', '=', $user_id], ])->get(); $attributes_values = null; for($i = 0; $i < count($attributes); $i++){ $attributes_values[$i] = DB::table('attributes_value')->where([ ['attribute_id', '=', $attributes[$i]->id], ['user_id', '=', $user_id], ])->get(); $count_attr = DB::table('attributes_value')->where([ ['attribute_id', '=', $attributes[$i]->id], ['user_id', '=', $user_id], ])->count(); $attributes_values[$i]['element_id'] = $element_id; $attributes_values[$i]['count_attr'] = $count_attr; $attributes_values[$i]['attribute_id'] = $attributes[$i]->id; $attributes_values[$i]['attribute_name'] = $attributes[$i]->attribute_name; $attributes_values[$i]['attribute_description'] = $attributes[$i]->attribute_description; } return $attributes_values; } } } public function edit_attr(Request $request){ if($request->ajax()){ if (Auth::user()){ $attrubute_id = $request->attrubute_id; $attrubute_name = $request->attrubute_name; $attribute_description = $request->attribute_description; $result = DB::table('attributes')->where('id', $attrubute_id )->update(['attribute_name' => $attrubute_name, 'attribute_description' => $attribute_description]); return $result; } } } public function get_complex_id(Request $request){ if($request->ajax()){ if (Auth::user()){ $user_id = Auth::user()->id; $element = DB::table('elements')->where([ ['id', '=', $request->element_id], ['user_id', '=', $user_id], ])->get(); $elements = explode('-', $element[0]->complex_id); return $elements; } } } public function edit_value_attr(Request $request){ if($request->ajax()){ if (Auth::user()){ $user_id = Auth::user()->id; $date = Carbon::now(); $id = $request->id; $attrubute_id = $request->attrubute_id; $attribute_bool = $request->attribute_bool; $attribute_file = $request->attribute_file; $attribute_ip = $request->attribute_ip; $attribute_text = $request->attribute_text; $attribute_varchar = $request->attribute_varchar; $double_2 = $request->double_2; $double_15 = $request->double_15; $number_attribute = $request->number_attribute; $time_first = $request->time_first; $time_second = $request->time_second; $attribute_json = null; //$result = DB::table('attributes_value')->where(['attribute_id' => $attrubute_id, 'user_id' => $user_id, 'id' => $id])->update(['attribute_bool' => $attribute_bool, 'attribute_img' => $attribute_file, 'attribute_ip' => $attribute_ip, 'attribute_text' => $attribute_text, 'attribute_varchar' => $attribute_varchar, 'attribute_float' => $double_2, 'attribute_double' => $double_15, 'attribute_int' => $number_attribute, 'attribute_time_first' => $time_first, 'attribute_time_second' => $time_second, 'attribute_json' => $attribute_json, 'updated_at' => $date]); $result = DB::table('attributes_value')->where(['id' => $id , 'user_id' => $user_id, 'attribute_id' => $attrubute_id])->update(['attribute_bool' => $attribute_bool, 'attribute_img' => $attribute_file, 'attribute_ip' => $attribute_ip, 'attribute_text' => $attribute_text, 'attribute_varchar' => $attribute_varchar, 'attribute_float' => $double_2, 'attribute_double' => $double_15, 'attribute_int' => $number_attribute, 'attribute_time_first' => $time_first, 'attribute_time_second' => $time_second, 'attribute_json' => $attribute_json, 'updated_at' => $date]); return $result; } } } public function remove_attr(Request $request){ if($request->ajax()){ if (Auth::user()){ $user_id = Auth::user()->id; $attr_id = $request->attr_id; if($request->attr_type == 'main'){ $result = DB::table('attributes_value')->where('attribute_id', $attr_id)->where('user_id', $user_id)->delete(); $result = DB::table('attributes')->where('id', $attr_id)->where('user_id', $user_id)->delete(); } else if($request->attr_type == 'value'){ $result = DB::table('attributes_value')->where('id', $attr_id)->where('user_id', $user_id)->delete(); } } return $result; } } public function create_attr_value(Request $request){ if($request->ajax()){ if (Auth::user()){ $user_id = Auth::user()->id; $date = Carbon::now(); $attribute_id = $request->attrubute_id; $attribute_bool = $request->attribute_bool; $attribute_file = $request->attribute_file; $attribute_ip = $request->attribute_ip; $attribute_text = $request->attribute_text; $attribute_varchar = $request->attribute_varchar; $double_2 = $request->double_2; $double_15 = $request->double_15; $number_attribute = $request->number_attribute; $time_first = $request->time_first; $time_second = $request->time_second; $attribute_json = null; if($time_first != null || $time_second != null || $number_attribute != null || $double_2 != null || $double_15 != null || $attribute_text != null || $attribute_varchar != null || $attribute_file != null || $attribute_ip != null || $attribute_bool != null){ $result = DB::table('attributes_value')->insertGetId( array('user_id' => $user_id, 'attribute_id' => $attribute_id, 'attribute_time_first' => $time_first, 'attribute_time_second' => $time_second, 'attribute_int' => $number_attribute, 'attribute_float' => $double_2, 'attribute_double' => $double_15, 'attribute_text' => $attribute_text, 'attribute_varchar' => $attribute_varchar, 'attribute_img' => $attribute_file, 'attribute_bool' => $attribute_bool, 'attribute_IP' => $attribute_ip, 'attribute_json' => $attribute_json, 'created_at' => $date, 'updated_at' => $date) ); } else { $result = null; } return $result; } } } public function search_element(Request $request){ if($request->ajax()){ if (Auth::user()){ $user_id = Auth::user()->id; $elements = DB::table('elements')->where([ ['element_name', 'LIKE', '%' . $request->value_text .'%' ], ['user_id', '=', $user_id], ])->get(); return $elements; } } } public function search_attributes_int(Request $request){ if($request->ajax()){ if (Auth::user()){ $user_id = Auth::user()->id; $attributes_int = DB::table('attributes_value')->where([ ['attribute_int', '!=', null ], ['user_id', '=', $user_id], ])->get(); return $attributes_int; } } } public function search_attributes_float(Request $request){ if($request->ajax()){ if (Auth::user()){ $user_id = Auth::user()->id; $attributes_float = DB::table('attributes_value')->where([ ['attribute_float', '!=', null ], ['user_id', '=', $user_id], ])->get(); return $attributes_float; } } } public function search_attributes_double(Request $request){ if($request->ajax()){ if (Auth::user()){ $user_id = Auth::user()->id; $attributes_double = DB::table('attributes_value')->where([ ['attribute_double', '!=', null ], ['user_id', '=', $user_id], ])->get(); $count = 0; foreach($attributes_double as $attr){ $array[$count] = $attr->attribute_id; $count += 1; } $array = array_unique($array, SORT_REGULAR); $count = 0; foreach($array as $arr){ $attributes[$count] = DB::table('attributes_value')->where([ ['attribute_id', '=', $arr ], ['user_id', '=', $user_id], ])->get(); $count += 1; } return $attributes; } } } public function get_all_attr(Request $request){ if($request->ajax()){ if (Auth::user()){ $user_id = Auth::user()->id; $attributes = DB::table('attributes')->where([ ['user_id', '=', $user_id], ])->get(); foreach($attributes as $item){ $element = DB::table('elements')->where([ ['id', '=', $item->element_id], ])->get(); $item->element_name = $element[0]->element_name; } return $attributes; } } } public function get_attr_val(Request $request){ if($request->ajax()){ if (Auth::user()){ $user_id = Auth::user()->id; $attributes = DB::table('attributes_value')->where([ ['attribute_id', '=', $request->attribute_id], ['user_id', '=', $user_id], ])->get(); $attributes_values = null; for($i = 0; $i < count($attributes); $i++){ $attributes_values[$i] = $attributes[$i]; $attributes_values['length'] = $i + 1; } return $attributes_values; } } } // public function get_elements(Request $request){ // if($request->ajax()){ // if (Auth::user()){ // $user_id = Auth::user()->id; // $elements = DB::table('elements')->where([ // ['user_id', '=', $user_id], // ])->get(); // return $elements; // } // } // } // public function move_element(Request $request){ // if($request->ajax()){ // if (Auth::user()){ // $user_id = Auth::user()->id; // $result = DB::update('update elements set complex_id = ? where id = ? and where', [ $complex_id, $id_note ]); // $element_id = $request->element_id; // $parent_id = $request->parent_id; // $complex_id = $request->complex_id; // $elements = DB::table('elements')->where([ // ['id', '=', $element_id], // ['user_id', '=', $user_id], // ])->update(); // return $result; // } // } // } }
8caedc640081c2ae8f90fb8b531f9a6f84dd056f
{ "blob_id": "8caedc640081c2ae8f90fb8b531f9a6f84dd056f", "branch_name": "refs/heads/main", "committer_date": "2021-08-07T08:49:07", "content_id": "859712abfc22fcc2e9901f69246caab5251055c6", "detected_licenses": [ "MIT" ], "directory_id": "4ce13857f142bb679116cf1b41c3309ac7ecd03d", "extension": "php", "filename": "DashboardController.php", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 357709899, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 19189, "license": "MIT", "license_type": "permissive", "path": "/app/Http/Controllers/Admin/DashboardController.php", "provenance": "stack-edu-0052.json.gz:490995", "repo_name": "artcomplay/note", "revision_date": "2021-08-07T08:49:07", "revision_id": "d4025893e176f8eecf25b000ef6b5c0144a32974", "snapshot_id": "f0b35e44a6fbc6404893d963a63c3fc12b567a4f", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/artcomplay/note/d4025893e176f8eecf25b000ef6b5c0144a32974/app/Http/Controllers/Admin/DashboardController.php", "visit_date": "2023-07-09T06:43:39.102469", "added": "2024-11-19T01:44:53.967564+00:00", "created": "2021-08-07T08:49:07", "int_score": 2, "score": 2.203125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0070.json.gz" }
package cn.zealon.readingcloud.book.common.config; import com.github.pagehelper.PageHelper; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.apache.ibatis.plugin.Interceptor; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import javax.sql.DataSource; import java.util.Properties; /** * MyBatis配置 * @author: zealon * @since: 2020/4/2 */ @Configuration @MapperScan(basePackages = "cn.zealon.readingcloud.book.dao", sqlSessionTemplateRef="bookCenterSqlSessionTemplate") public class MybatisConfig { private final static String MAPPER_LOCATIONS = "classpath*:mappers/*.xml"; /** 工厂配置 */ @Bean public SqlSessionFactory sqlSessionFactoryBean(@Qualifier("bookCenterDataSource") DataSource dataSource) throws Exception { // 设置数据源 SqlSessionFactoryBean factory = new SqlSessionFactoryBean(); factory.setDataSource(dataSource); // 添加XML映射 ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); factory.setMapperLocations(resolver.getResources(MAPPER_LOCATIONS)); //添加插件 factory.setPlugins(new Interceptor[]{ this.getPageHelper() }); return factory.getObject(); } /** 会话模板 */ @Bean(name = "bookCenterSqlSessionTemplate") public SqlSessionTemplate setSqlSessionTemplate(SqlSessionFactory sqlSessionFactory) { return new SqlSessionTemplate(sqlSessionFactory); } /** 分页插件 */ private PageHelper getPageHelper(){ //配置分页插件,详情请查阅官方文档 PageHelper pageHelper = new PageHelper(); Properties properties = new Properties(); //分页尺寸为0时查询所有纪录不再执行分页 properties.setProperty("pageSizeZero", "true"); //页码<=0 查询第一页,页码>=总页数查询最后一页 properties.setProperty("reasonable", "true"); //支持通过 Mapper 接口参数来传递分页参数 properties.setProperty("supportMethodsArguments", "true"); properties.setProperty("params", "count=countSql"); //切换数据源,自动解析不同数据库的分页 properties.setProperty("autoRuntimeDialect", "true"); pageHelper.setProperties(properties); return pageHelper; } }
b11a3743606a92d00dbfd34163e15e15b83dace8
{ "blob_id": "b11a3743606a92d00dbfd34163e15e15b83dace8", "branch_name": "refs/heads/master", "committer_date": "2020-06-09T01:16:34", "content_id": "e752cf74e9a33b54ed701ec289e346e7b76bca27", "detected_licenses": [ "MIT" ], "directory_id": "e2615849f498d49c6b386b884f66abe604db945e", "extension": "java", "filename": "MybatisConfig.java", "fork_events_count": 0, "gha_created_at": "2020-06-20T10:40:09", "gha_event_created_at": "2020-06-20T10:40:09", "gha_language": null, "gha_license_id": "MIT", "github_id": 273688188, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2761, "license": "MIT", "license_type": "permissive", "path": "/reading-cloud-book/src/main/java/cn/zealon/readingcloud/book/common/config/MybatisConfig.java", "provenance": "stack-edu-0031.json.gz:294903", "repo_name": "zyhao11/light-reading-cloud", "revision_date": "2020-06-09T01:16:34", "revision_id": "b3e3da89dcf493d21b2084b464e5eb81545fc320", "snapshot_id": "4ceee09951f8f3778ed4bce6ef372b3941b64933", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/zyhao11/light-reading-cloud/b3e3da89dcf493d21b2084b464e5eb81545fc320/reading-cloud-book/src/main/java/cn/zealon/readingcloud/book/common/config/MybatisConfig.java", "visit_date": "2022-10-24T09:27:08.569395", "added": "2024-11-18T23:13:42.455161+00:00", "created": "2020-06-09T01:16:34", "int_score": 2, "score": 2.265625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0049.json.gz" }
# Mesh Utilities This repository contains scripts for generating neuropil meshes for NeuroNLP and FlyBrainLab. # Installation Instructions On a Python 3.6 environment, run ``` pip install pyvista ``` to install pyvista. # Examples The file mesh_generator/stl_2_ffbo_mesh.py can be run as follows to convert a mesh from the .stl format to .json: ``` python stl_2_ffbo_mesh.py -i _temp_mesh.stl -o out.json ``` To generate a mesh from point cloud input, check out mesh_generator/example.py as a starting point: ``` python example.py ``` You may want to open the generated mesh _temp_mesh.stl in an application like MeshLab for further improvements before conversion to .json.
fdf69a13426e5f3a45f51da18d842ec5656b7c61
{ "blob_id": "fdf69a13426e5f3a45f51da18d842ec5656b7c61", "branch_name": "refs/heads/master", "committer_date": "2020-08-28T00:18:28", "content_id": "c6fe947e8e7bcfe1f7c0334679d4db55d31cbfed", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "184b4422782aaf313515927b101d36d492c9c4f6", "extension": "md", "filename": "README.md", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 290908248, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 679, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/README.md", "provenance": "stack-edu-markdown-0003.json.gz:165042", "repo_name": "fruitflybrain/mesh_utilities", "revision_date": "2020-08-28T00:18:28", "revision_id": "004bc897d3e16ae61e416780e3461a0f05d5c6af", "snapshot_id": "b67255ceffbcd21848560aa515a0ffca3aff73de", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/fruitflybrain/mesh_utilities/004bc897d3e16ae61e416780e3461a0f05d5c6af/README.md", "visit_date": "2022-12-08T21:43:54.363532", "added": "2024-11-18T21:36:16.090307+00:00", "created": "2020-08-28T00:18:28", "int_score": 3, "score": 3.03125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0003.json.gz" }
import { Card } from '../../../interfaces' import Set from '../Team Rocket' const card: Card = { name: { en: "Dark Vileplume", fr: "Rafflesia obscur" }, illustrator: "Kagemaru Himeno", rarity: "Rare", category: "Pokemon", set: Set, dexId: [ 45, ], hp: 60, types: [ "Grass", ], evolveFrom: { en: "Gloom", }, stage: "Stage2", abilities: [ { type: "Pokemon Power", name: { en: "Hay Fever", fr: "Rhume des foins" }, effect: { en: "No Trainer cards can be played. This power stops working while Dark Vileplume is Asleep, Confused, or Paralyzed.", fr: "Aucune carte Dresseur ne peut être jouée. Ce pouvoir cesse de fonctionner lorsque Rafflesia obscur est Endormi, Confus ou Paralysé." }, }, ], attacks: [ { cost: [ "Grass", "Grass", "Grass", ], name: { en: "Petal Whirlwind", fr: "Tourbillon de pétales" }, effect: { en: "Flip 3 coins. This attack does 30 damage times the number of heads. If you get 2 or more heads, Dark Vileplume is now Confused (after dealing damage).", fr: "Lancez 3 pièces. Cette attaque inflige 30 dégâts multipliés par le nombre de faces. Si vous obtenez 2 faces ou plus, Rafflesia obscur est maintenant Confus (après application des dégâts)." }, damage: "30×", }, ], weaknesses: [ { type: "Fire", value: "×2" }, ], description: { fr: "Les autres Pokémon restent à l'écart des endroits où vivent les Rafflesia, peut être en raison du fort parfum de leur pollen." } } export default card
1bac807019512a1a35e67f6623a991fccac96f3e
{ "blob_id": "1bac807019512a1a35e67f6623a991fccac96f3e", "branch_name": "refs/heads/master", "committer_date": "2023-03-21T14:18:18", "content_id": "cda11839f448ecdd9ee998b60846450d4ac50d7d", "detected_licenses": [ "MIT" ], "directory_id": "009ab400387b7170d8fa786ce93b17fc25417cd6", "extension": "ts", "filename": "30.ts", "fork_events_count": 15, "gha_created_at": "2020-02-19T15:09:23", "gha_event_created_at": "2023-03-04T00:00:49", "gha_language": "TypeScript", "gha_license_id": "MIT", "github_id": 241652591, "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1570, "license": "MIT", "license_type": "permissive", "path": "/data/Base/Team Rocket/30.ts", "provenance": "stack-edu-0075.json.gz:514881", "repo_name": "tcgdex/cards-database", "revision_date": "2023-03-21T14:18:18", "revision_id": "e0e3a1a4fd892f0d124e147f2e6bd3ab33174e47", "snapshot_id": "6d7263f8e2004faa385d14f7c559429a2ebd7472", "src_encoding": "UTF-8", "star_events_count": 55, "url": "https://raw.githubusercontent.com/tcgdex/cards-database/e0e3a1a4fd892f0d124e147f2e6bd3ab33174e47/data/Base/Team Rocket/30.ts", "visit_date": "2023-04-05T05:56:20.168452", "added": "2024-11-18T22:59:17.768947+00:00", "created": "2023-03-21T14:18:18", "int_score": 3, "score": 2.59375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0093.json.gz" }
# Dolph PHP Framework ![Dolph PHP Framework](dolph-php-logo.png) Dolph PHP is an advanced PHP framework designed to elevate the language and empower developers with modern tools and capabilities. It aims to save PHP by bringing cutting-edge features, performance optimizations, and a streamlined development experience to the ecosystem. ## Key Features - **Asynchronous Programming**: Harness the power of asynchronous programming techniques for non-blocking I/O and efficient handling of concurrent requests. - **Event Loop**: Benefit from an integrated event loop mechanism to manage events, I/O operations, and concurrency efficiently. - **WebSockets and Real-Time Communication**: Seamlessly integrate WebSocket support for building real-time and interactive features in your applications. - **Performance Optimization**: Optimize code execution, leverage caching mechanisms, and utilize PHP extensions for enhanced performance and speed. - **Robust Ecosystem and Tooling**: Enjoy a thriving ecosystem with well-documented APIs, a collection of useful libraries, and developer tooling to boost productivity. - **Scalability and Deployment**: Scale your applications effortlessly with guidelines for horizontal scaling, load balancing, and easy deployment using Docker or cloud platforms. ## Additional Features - **Routing and Middleware**: Powerful routing system for URL handling and flexible middleware support for request/response processing. - **Database Integration**: Seamless integration with popular databases through an ORM or a database abstraction layer. - **Authentication and Authorization**: Built-in authentication and authorization mechanisms for secure access control. - **Caching Strategies**: Support for various caching strategies like in-memory caching and Redis for optimal application performance. - **Template Engine**: Use a powerful template engine for dynamic content generation and separation of concerns. - **Logging and Error Handling**: Robust logging functionality for effective debugging and error handling. - **Testing Framework**: Built-in testing framework for unit tests, integration tests, and automated testing. - **Comprehensive Documentation**: Extensive documentation with tutorials, examples, and guides to help you get started and make the most out of the framework. ## Getting Started To get started with Dolph PHP, follow the installation guide and explore the documentation available at [Dolph PHP Documentation](https://dolph-php.com/docs). ## Contributing We welcome contributions from the community! If you'd like to contribute to Dolph PHP, please read our [Contribution Guidelines](https://dolph-php.com/contributing) for instructions. ## License Dolph PHP is released under the [MIT License](https://opensource.org/licenses/MIT). Feel free to use, modify, and distribute the framework. ## Contact If you have any questions, suggestions, or feedback, please reach out to our team at [[email protected]](mailto:[email protected]). Let's save PHP together with Dolph PHP!
a49de97c3604048596503856ca6a413874f23e26
{ "blob_id": "a49de97c3604048596503856ca6a413874f23e26", "branch_name": "refs/heads/main", "committer_date": "2023-07-16T18:18:35", "content_id": "4a06403863d9384c578276ddc4c6823dcde2ac23", "detected_licenses": [ "MIT" ], "directory_id": "026f4fd436540b10a23661343f3a2812586986b5", "extension": "md", "filename": "README.md", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 666978761, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3045, "license": "MIT", "license_type": "permissive", "path": "/README.md", "provenance": "stack-edu-markdown-0004.json.gz:25050", "repo_name": "Questgig/dolph-php", "revision_date": "2023-07-16T18:18:35", "revision_id": "bde62bfe83a5a564b6355839a1f8f53c84aaab09", "snapshot_id": "69e61ae4febe0c2a02db36dae4d70f837b709653", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/Questgig/dolph-php/bde62bfe83a5a564b6355839a1f8f53c84aaab09/README.md", "visit_date": "2023-08-11T02:00:59.939926", "added": "2024-11-18T22:52:28.014290+00:00", "created": "2023-07-16T18:18:35", "int_score": 3, "score": 3.390625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0004.json.gz" }
import { gradients } from "@/utils/gradients" import { motion } from "framer-motion" import styles from "./GradientLockup.module.css" const rotation = { "-1": "-rotate-1", "-2": "-rotate-1 sm:-rotate-2", 1: "rotate-1", 2: "rotate-1 sm:rotate-2", } export function GradientLockup({ header, left, right, color, rotate, pin = "left", gradientProps = {}, }) { return ( <div className={`grid ${styles.root}`}> <div className={`col-start-2 col-end-3 lg:col-start-1 lg:col-end-5 ${ left && right ? "row-start-2 row-end-4" : "row-start-2 row-end-5" } lg:row-end-5 lg:py-10 xl:py-16 flex ${ pin === "left" ? "-ml-8 pr-4 sm:ml-0 sm:pr-0" : "-mr-8 pl-4 sm:mr-0 sm:pl-0" }`} > <div className="bg-gray-100 w-full flex-none rounded-3xl" /> <motion.div className={`w-full flex-none -ml-full rounded-3xl transform shadow-lg bg-gradient-to-br ${gradients[color][0]} ${rotation[rotate]}`} {...gradientProps} /> </div> {header && ( <div className="relative col-start-1 col-end-4 px-4 sm:px-6 md:px-8 lg:px-0 lg:col-start-2 lg:col-end-4 xl:col-end-3 row-start-1 row-end-2 xl:row-end-3 pb-8 lg:pb-11 xl:pb-0"> {header} </div> )} {left && right ? ( <> <div className={`relative col-start-2 col-end-3 lg:col-end-3 row-start-2 row-end-3 lg:row-start-3 lg:row-end-4 self-center ${ pin === "left" ? "pr-8" : "pl-8" } sm:px-6 md:px-8 pt-6 md:pt-8 lg:px-0 lg:pt-0`} > {left} </div> <div className="relative w-full lg:w-auto col-start-1 col-end-4 md:px-8 lg:px-0 lg:col-start-3 lg:col-end-4 row-start-3 row-end-4 lg:row-start-2 lg:row-end-5 self-center pb-8 lg:pb-0"> {right} </div> </> ) : ( <div className="relative w-full col-start-1 lg:col-start-2 col-end-4 row-start-2 row-end-5 py-8 md:px-8 lg:p-0"> {left || right} </div> )} </div> ) }
ec086b56e22c77948ab03362830b694c03c1ca75
{ "blob_id": "ec086b56e22c77948ab03362830b694c03c1ca75", "branch_name": "refs/heads/main", "committer_date": "2021-02-27T13:31:18", "content_id": "7130d11348e2d7b4c1f9ebf71458d9f9fe4c0026", "detected_licenses": [ "MIT" ], "directory_id": "ad1133deb8b255db4ee6b92c85e6136855306eab", "extension": "js", "filename": "GradientLockup.js", "fork_events_count": 0, "gha_created_at": "2021-03-01T04:38:36", "gha_event_created_at": "2021-03-01T04:38:36", "gha_language": null, "gha_license_id": "MIT", "github_id": 343291531, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2066, "license": "MIT", "license_type": "permissive", "path": "/app/components/GradientLockup.js", "provenance": "stack-edu-0039.json.gz:127135", "repo_name": "sbappan/blitzjs.com", "revision_date": "2021-02-27T13:31:18", "revision_id": "9f9ccc79b0228702f7d19db6c6b0d3ad5b88ee7e", "snapshot_id": "d0d1f5d9ab46a768e9cc93e770f0b7964a73fd48", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/sbappan/blitzjs.com/9f9ccc79b0228702f7d19db6c6b0d3ad5b88ee7e/app/components/GradientLockup.js", "visit_date": "2023-03-22T00:17:29.503014", "added": "2024-11-19T01:03:51.755325+00:00", "created": "2021-02-27T13:31:18", "int_score": 2, "score": 2.1875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0057.json.gz" }
// Copyright Contributors to the Open Cluster Management project package automation import ( "context" "fmt" "time" policiesv1 "github.com/open-cluster-management/governance-policy-propagator/pkg/apis/policy/v1" policyv1beta1 "github.com/open-cluster-management/governance-policy-propagator/pkg/apis/policy/v1beta1" "github.com/open-cluster-management/governance-policy-propagator/pkg/controller/common" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/dynamic" "k8s.io/client-go/tools/record" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/controller" logf "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/manager" "sigs.k8s.io/controller-runtime/pkg/reconcile" "sigs.k8s.io/controller-runtime/pkg/source" ) const controllerName string = "policy-automation" var log = logf.Log.WithName(controllerName) // Add creates a new Policy Controller and adds it to the Manager. The Manager will set fields on the Controller // and Start it when the Manager is Started. func Add(mgr manager.Manager) error { return add(mgr, newReconciler(mgr)) } // newReconciler returns a new reconcile.Reconciler func newReconciler(mgr manager.Manager) reconcile.Reconciler { dyamicClient, err := dynamic.NewForConfig(mgr.GetConfig()) if err != nil { panic(err) } return &ReconcilePolicy{client: mgr.GetClient(), scheme: mgr.GetScheme(), dyamicClient: dyamicClient, recorder: mgr.GetEventRecorderFor(controllerName)} } // add adds a new Controller to mgr with r as the reconcile.Reconciler func add(mgr manager.Manager, r reconcile.Reconciler) error { // Create a new controller c, err := controller.New(controllerName, mgr, controller.Options{Reconciler: r}) if err != nil { return err } // Watch for changes to primary resource Policy err = c.Watch(&source.Kind{Type: &policiesv1.Policy{}}, &common.EnqueueRequestsFromMapFunc{ToRequests: &policyMapper{mgr.GetClient()}}, policyPredicateFuncs) if err != nil { return err } // Watch for changes to resource PolicyAutomation err = c.Watch(&source.Kind{Type: &policyv1beta1.PolicyAutomation{}}, &common.EnqueueRequestsFromMapFunc{ToRequests: &policyAutomationMapper{mgr.GetClient()}}, configMapPredicateFuncs) if err != nil { return err } return nil } // blank assignment to verify that ReconcilePolicy implements reconcile.Reconciler var _ reconcile.Reconciler = &ReconcilePolicy{} // ReconcilePolicy reconciles a Policy object type ReconcilePolicy struct { // This client, initialized using mgr.Client() above, is a split client // that reads objects from the cache and writes to the apiserver client client.Client dyamicClient dynamic.Interface scheme *runtime.Scheme recorder record.EventRecorder counter int } // Reconcile reads that state of the cluster for a Policy object and makes changes based on the state read // and what is in the Policy.Spec // Note: // The Controller will requeue the Request to be processed again if the returned error is non-nil or // Result.Requeue is true, otherwise upon completion it will remove the work from the queue. func (r *ReconcilePolicy) Reconcile(request reconcile.Request) (reconcile.Result, error) { reqLogger := log.WithValues("Request.Namespace", request.Namespace, "Request.Name", request.Name) // Fetch the ConfigMap instance policyAutomation := &policyv1beta1.PolicyAutomation{} err := r.client.Get(context.TODO(), request.NamespacedName, policyAutomation) if err != nil { if errors.IsNotFound(err) { reqLogger.Info("Automation was deleted, doing nothing...") return reconcile.Result{}, nil } // Error reading the object - requeue the request. return reconcile.Result{}, err } reqLogger = log.WithValues("Request.Namespace", request.Namespace, "Request.Name", request.Name, "policyRef", policyAutomation.Spec.PolicyRef) reqLogger.Info("Handling automation...") if policyAutomation.Annotations["policy.open-cluster-management.io/rerun"] == "true" { reqLogger.Info("Triggering manual run...") err = common.CreateAnsibleJob(policyAutomation, r.dyamicClient, "manual", nil) if err != nil { reqLogger.Error(err, "Failed to create ansible job...") return reconcile.Result{}, err } // manual run suceeded, remove annotation delete(policyAutomation.Annotations, "policy.open-cluster-management.io/rerun") err = r.client.Update(context.TODO(), policyAutomation, &client.UpdateOptions{}) if err != nil { reqLogger.Error(err, "Failed to remove annotation `policy.open-cluster-management.io/rerun`...") return reconcile.Result{}, err } reqLogger.Info("Manual run complete...") return reconcile.Result{}, nil } else if policyAutomation.Spec.Mode == "disabled" { reqLogger.Info("Automation is disabled, doing nothing...") return reconcile.Result{}, nil } else { policy := &policiesv1.Policy{} err := r.client.Get(context.TODO(), types.NamespacedName{ Name: policyAutomation.Spec.PolicyRef, Namespace: policyAutomation.GetNamespace(), }, policy) if err != nil { if errors.IsNotFound(err) { //policy is gone, need to delete automation reqLogger.Info("Policy specified in policyRef field not found, may have been deleted, doing nothing...") return reconcile.Result{}, nil } // Error reading the object - requeue the request. reqLogger.Error(err, "Failed to retrieve policy specified in policyRef field...") return reconcile.Result{}, err } if policy.Spec.Disabled { reqLogger.Info("Policy is disabled, doing nothing...") return reconcile.Result{}, nil } if policyAutomation.Spec.Mode == "scan" { reqLogger.Info("Triggering scan mode...") requeueAfter, err := time.ParseDuration(policyAutomation.Spec.RescanAfter) if err != nil { return reconcile.Result{RequeueAfter: requeueAfter}, err } targetList := common.FindNonCompliantClustersForPolicy(policy) if len(targetList) > 0 { reqLogger.Info("Creating ansible job with targetList", "targetList", targetList) err = common.CreateAnsibleJob(policyAutomation, r.dyamicClient, "scan", targetList) if err != nil { return reconcile.Result{RequeueAfter: requeueAfter}, err } } else { reqLogger.Info("No cluster is in noncompliant status, doing nothing...") } // no violations found, doing nothing r.counter++ reqLogger.Info("RequeueAfter.", "RequeueAfter", requeueAfter.String(), "counter", fmt.Sprintf("%d", r.counter)) return reconcile.Result{RequeueAfter: requeueAfter}, nil } else if policyAutomation.Spec.Mode == "once" { reqLogger.Info("Triggering once mode...") targetList := common.FindNonCompliantClustersForPolicy(policy) if len(targetList) > 0 { reqLogger.Info("Creating ansible job with targetList", "targetList", targetList) err = common.CreateAnsibleJob(policyAutomation, r.dyamicClient, "once", targetList) if err != nil { reqLogger.Error(err, "Failed to create ansible job...") return reconcile.Result{}, err } policyAutomation.Spec.Mode = "disabled" err = r.client.Update(context.TODO(), policyAutomation, &client.UpdateOptions{}) if err != nil { reqLogger.Error(err, "Failed to update mode to disabled...") return reconcile.Result{}, err } } else { reqLogger.Info("No cluster is in noncompliant status, doing nothing...") } } } return reconcile.Result{}, nil }
6f19daf6e5a309d7d64e52bb8731a4743bc6b89b
{ "blob_id": "6f19daf6e5a309d7d64e52bb8731a4743bc6b89b", "branch_name": "refs/heads/main", "committer_date": "2021-09-02T13:45:38", "content_id": "34feb336159a710e10daf1dad3dd5dc4f4246fae", "detected_licenses": [ "Apache-2.0" ], "directory_id": "529881c60205e88bfa74f98732fca23407500608", "extension": "go", "filename": "policy_automation_controller.go", "fork_events_count": 0, "gha_created_at": "2021-09-01T05:55:23", "gha_event_created_at": "2021-09-01T05:55:23", "gha_language": null, "gha_license_id": "Apache-2.0", "github_id": 401947845, "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 7480, "license": "Apache-2.0", "license_type": "permissive", "path": "/pkg/controller/automation/policy_automation_controller.go", "provenance": "stack-edu-0017.json.gz:624304", "repo_name": "levinwang88/governance-policy-propagator", "revision_date": "2021-09-01T19:27:12", "revision_id": "0c916f0de0b755aeccb34b417548f3f657719753", "snapshot_id": "ec3ba98941bca4877778df2cf7e8f8caa5072c7c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/levinwang88/governance-policy-propagator/0c916f0de0b755aeccb34b417548f3f657719753/pkg/controller/automation/policy_automation_controller.go", "visit_date": "2023-07-26T20:27:45.297124", "added": "2024-11-18T21:20:17.444367+00:00", "created": "2021-09-01T19:27:12", "int_score": 2, "score": 2.28125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0035.json.gz" }
package com.osh.rvs.mapper.inline; import org.apache.ibatis.annotations.Param; import com.osh.rvs.bean.inline.GlueMixingProcessPaceEntity; /** * * @Title: GlueMixingProcessPaceMapper.java * @Package com.osh.rvs.mapper.inline * @Description: 胶水调制作业分段时间 * @author liuxb * @date 2017-12-18 上午11:11:36 */ public interface GlueMixingProcessPaceMapper { /** * 新建胶水调制作业分段时间 * * @param entity */ public void insert(GlueMixingProcessPaceEntity entity); /** * 根据胶水调制作业ID获取胶水调制作业时间最大分段 * @param glue_mixing_process_id * @return */ public int getMaxPaceByGlueMixingProcessId(@Param("glue_mixing_process_id") String glue_mixing_process_id); /** * 更新新建胶水调制作业分段时间 * @param entity */ public void update(GlueMixingProcessPaceEntity entity); /** * 根据胶水调制作业ID获取胶水调制作业时间未完成信息 * @param glue_mixing_process_id * @return */ public GlueMixingProcessPaceEntity getUnFinishById(@Param("glue_mixing_process_id") String glue_mixing_process_id); }
57960f86cfddebf56229e93f02d46e4043ff3625
{ "blob_id": "57960f86cfddebf56229e93f02d46e4043ff3625", "branch_name": "refs/heads/master", "committer_date": "2023-05-09T07:35:00", "content_id": "2e02f6c7ecc598c8bbdc5dc2b311102eb6287bbd", "detected_licenses": [ "Apache-2.0" ], "directory_id": "889334ad3c51a8625d5d42c43644d7b56cfb73f4", "extension": "java", "filename": "GlueMixingProcessPaceMapper.java", "fork_events_count": 2, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 157845028, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1141, "license": "Apache-2.0", "license_type": "permissive", "path": "/rvs2.0/src/com/osh/rvs/mapper/inline/GlueMixingProcessPaceMapper.java", "provenance": "stack-edu-0028.json.gz:270070", "repo_name": "fangke-ray/RVS-OGZ", "revision_date": "2023-05-09T07:35:00", "revision_id": "7f251143806252566561053bf351e8f1cf666357", "snapshot_id": "80ffc3092cbbadb0e9c9b07f2186c049e37308b6", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/fangke-ray/RVS-OGZ/7f251143806252566561053bf351e8f1cf666357/rvs2.0/src/com/osh/rvs/mapper/inline/GlueMixingProcessPaceMapper.java", "visit_date": "2023-05-25T07:08:39.226063", "added": "2024-11-18T21:36:49.545711+00:00", "created": "2023-05-09T07:35:00", "int_score": 2, "score": 2.125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0046.json.gz" }
package org.folio.edge.core.utils; import java.security.SecureRandom; import java.util.Base64; import java.util.Random; import org.folio.edge.core.model.ClientInfo; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.Option; import io.vertx.core.json.JsonObject; public class ApiKeyUtils { public static final String ALPHANUMERIC = "0123456789abcdefghijklmnopqrstuvwxyABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static final Random RANDOM = new SecureRandom(); public static final int DEFAULT_SALT_LEN = 10; @Option(name = "-p", usage = "parse an API Key", forbids = "-g") private String keyToParse; @Option(name = "-g", usage = "generate an API Key", forbids = "-p", depends = { "-t", "-u" }) private boolean generate; @Option(name = "-s", aliases = "--salt-len", usage = "the number of salt characters", depends = "-g") private int saltLen = DEFAULT_SALT_LEN; @Option(name = "-t", aliases = "--tenant-id", usage = "the tenant's ID", depends = "-g") private String tenantId; @Option(name = "-u", aliases = "--username", usage = "the tenant's institutional user's username", depends = "-g") private String username; public static String generateSalt(int length) { StringBuilder buf = new StringBuilder(length); for (int i = 0; i < length; i++) { buf.append(ALPHANUMERIC.charAt(RANDOM.nextInt(ALPHANUMERIC.length()))); } return buf.toString(); } public static String generateApiKey(String salt, String tenantId, String username) { if (salt == null || salt.isEmpty()) { throw new IllegalArgumentException("ClientID/Salt cannot be null"); } if (tenantId == null || tenantId.isEmpty()) { throw new IllegalArgumentException("TenantID cannot be null"); } if (username == null || username.isEmpty()) { throw new IllegalArgumentException("Username cannot be null"); } ClientInfo ci = new ClientInfo(salt, tenantId, username); return Base64.getUrlEncoder().encodeToString(JsonObject.mapFrom(ci).encode().getBytes()); } public static String generateApiKey(int saltLen, String tenantId, String username) { return generateApiKey(generateSalt(saltLen), tenantId, username); } public static ClientInfo parseApiKey(String apiKey) throws MalformedApiKeyException { ClientInfo ret = null; try { String decoded = new String(Base64.getUrlDecoder().decode(apiKey.getBytes())); JsonObject json = new JsonObject(decoded); ret = json.mapTo(ClientInfo.class); } catch (Exception e) { throw new MalformedApiKeyException("Failed to parse", e); } if (ret.salt == null || ret.salt.isEmpty()) { throw new MalformedApiKeyException("Null/Empty Salt"); } if (ret.tenantId == null || ret.tenantId.isEmpty()) { throw new MalformedApiKeyException("Null/Empty Tenant"); } if (ret.username == null || ret.username.isEmpty()) { throw new MalformedApiKeyException("Null/Empty Username"); } return ret; } public static void main(String[] args) { ApiKeyUtils utils = new ApiKeyUtils(); System.exit(utils.runMain(args)); } @SuppressWarnings({ "squid:S106", "squid:S1148" }) public int runMain(String[] args) { CmdLineParser parser = new CmdLineParser(this); try { // parse the arguments. parser.parseArgument(args); if (generate) { System.out.println(generateApiKey(saltLen, tenantId, username)); return 0; } else if (keyToParse != null && !keyToParse.isEmpty()) { ClientInfo info = parseApiKey(keyToParse); System.out.println("Salt: " + info.salt); System.out.println("Tenant ID: " + info.tenantId); System.out.println("Username: " + info.username); return 0; } else { throw new CmdLineException(parser, "Either -g or -p need to be specified", new Exception()); } } catch (CmdLineException e) { // if there's a problem in the command line, // you'll get this exception. this will report // an error message. System.err.println(e.getMessage()); System.err.println("Usage: ApiKeyUtils [options]"); // print the list of available options parser.printUsage(System.err); System.err.println(); return 2; } catch (MalformedApiKeyException e) { System.err.println("Failed to parse API Key!"); e.printStackTrace(); return 3; } } public static class MalformedApiKeyException extends Exception { private static final long serialVersionUID = 7852873967223950947L; public static final String MSG = "Malformed API Key"; public MalformedApiKeyException(String msg, Throwable t) { super(MSG + ": " + msg, t); } public MalformedApiKeyException(String msg) { super(MSG + ": " + msg); } } }
3f166c0c539e649c47b516b848101d2775be5365
{ "blob_id": "3f166c0c539e649c47b516b848101d2775be5365", "branch_name": "refs/heads/master", "committer_date": "2023-07-10T13:54:06", "content_id": "212351264649009ed574c319c6c189b7d42b7191", "detected_licenses": [ "Apache-2.0" ], "directory_id": "e08bd3a3545024f70cec72425382c256cbf83d47", "extension": "java", "filename": "ApiKeyUtils.java", "fork_events_count": 4, "gha_created_at": "2018-05-23T20:20:08", "gha_event_created_at": "2023-07-10T13:54:08", "gha_language": "Java", "gha_license_id": "Apache-2.0", "github_id": 134621285, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 5007, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/main/java/org/folio/edge/core/utils/ApiKeyUtils.java", "provenance": "stack-edu-0019.json.gz:289584", "repo_name": "folio-org/edge-common", "revision_date": "2023-07-10T13:54:06", "revision_id": "0a9f9775bc54b4756f5d75a991de150af63bea05", "snapshot_id": "c3ed2e101ade089330dc23ab85dbe1aa7729e989", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/folio-org/edge-common/0a9f9775bc54b4756f5d75a991de150af63bea05/src/main/java/org/folio/edge/core/utils/ApiKeyUtils.java", "visit_date": "2023-07-26T09:35:12.300624", "added": "2024-11-18T21:35:52.406933+00:00", "created": "2023-07-10T13:54:06", "int_score": 3, "score": 2.65625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0037.json.gz" }
/** * @api {delete} /users/{id} User delete * @apiVersion 0.3.0 * @apiName users delete * @apiGroup Users * @apiSampleRequest off * * @apiDescription Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sed ipsum dolor. Suspendisse et libero ex. Aenean congue nec dui hendrerit posuere. Morbi laoreet orci diam, molestie rutrum sapien dapibus vel. * * * @apiSuccess {String} status Sample Text. * @apiSuccess {String} message Sample Message. * @apiSuccessExample {json} Success-Response: *HTTP/1.1 200 OK *{ * "status": "success" * "message": "User Successfully Updated" *} * @apiError {String} error Error Message. * @apiErrorExample Response (404): * HTTP/1.1 404 Bad Request * { * "error": "Sample Message" * } * */
8e69f2eb7f5043203e6236bb488abbaa927d9f0d
{ "blob_id": "8e69f2eb7f5043203e6236bb488abbaa927d9f0d", "branch_name": "refs/heads/master", "committer_date": "2017-11-03T02:26:03", "content_id": "861c6bbe02d2fe3c4f5fc9e360bc82fef74bcc41", "detected_licenses": [ "MIT" ], "directory_id": "996d486819a3d98ed829a2057a409a1b4f89045c", "extension": "js", "filename": "users-delete.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 89977118, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 787, "license": "MIT", "license_type": "permissive", "path": "/example/users/users-delete.js", "provenance": "stack-edu-0040.json.gz:644057", "repo_name": "ivjose/yondu-api-documentation", "revision_date": "2017-11-03T02:26:03", "revision_id": "ad8b82de8d10292198f5064232f250f77951c5f1", "snapshot_id": "eaa2a415ed5a61aec2f1cdfdccfded731c01c9d0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ivjose/yondu-api-documentation/ad8b82de8d10292198f5064232f250f77951c5f1/example/users/users-delete.js", "visit_date": "2021-01-20T07:12:55.079012", "added": "2024-11-18T23:47:30.735589+00:00", "created": "2017-11-03T02:26:03", "int_score": 2, "score": 2.046875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0058.json.gz" }
import xml.etree.ElementTree as ET import cv2 from PIL import Image import os import glob from tqdm import tqdm import numpy as np import shutil os.environ['OPENCV_IO_ENABLE_JASPER']= 'TRUE' def purificate(xpath, ipath, save_img, save_xml): assert os.path.exists(xpath) assert os.path.exists(ipath) os.makedirs(save_xml, exist_ok = True) os.makedirs(save_img, exist_ok = True) count0=0 for xmlfile in tqdm(glob.glob(xpath+"/*.xml")): #xmlの読み込み tree = ET.parse(xmlfile) root = tree.getroot() filename = root.find("filename").text element_objs = root.findall("object") cellcount=0 #細胞が存在するか確認 for element_obj in element_objs: class_name = element_obj.find('name').text if class_name=='silent' or class_name=='low' or class_name=='high': cellcount+=1 #保存 if not cellcount==0: name = os.path.basename(xmlfile) if not os.path.exists(save_xml+"/"+name): shutil.copy(xmlfile,save_xml+"/"+name) if not os.path.exists(save_img+"/"+filename): shutil.copy(ipath + "/" + filename, save_img+"/"+filename) else: count0+=1 print("細胞数0の画像とXMLの組は{}個ありました。".format(count0)) def rotate1(xpath, ipath, save_img, save_xml): assert os.path.exists(xpath) assert os.path.exists(ipath) os.makedirs(save_xml, exist_ok = True) os.makedirs(save_img, exist_ok = True) for xmlfile in tqdm(glob.glob(xpath+"/*.xml")): #xmlの読み込み tree = ET.parse(xmlfile) root = tree.getroot() filename = root.find("filename").text folder = root.find("folder").text size_elements = root.findall("size") obj_elements = root.findall("object") #imgの読み込み image = cv2.imread(ipath+filename) #imgの保存 #90 new_name = filename.replace(".jp2","") + '-' + 'rotate_90' + '.jp2' new_path = os.path.join(save_img, new_name) img_transpose = np.transpose(image, (1,0,2)) img_90 = cv2.flip(img_transpose, 1) if not os.path.isfile(new_path): cv2.imwrite(new_path,img_90) #180 new_name_180 = filename.replace(".jp2","") + '-' + 'rotate_180' + '.jp2' new_path_180 = os.path.join(save_img, new_name_180) img_180 = cv2.flip(image, -1) if not os.path.isfile(new_path_180): cv2.imwrite(new_path_180,img_180) #270 new_name_270 = filename.replace(".jp2","") + '-' + 'rotate_270' + '.jp2' new_path_270 = os.path.join(save_img, new_name_270) img_transpose_270 = np.transpose(image, (1,0,2)) img_270 = cv2.flip(img_transpose_270, 0) if not os.path.isfile(new_path_270): cv2.imwrite(new_path_270, img_270) pwd_lines=[] for obj in obj_elements: class_name = obj.find('name').text obj_bbox = obj.find('bndbox') x1 = int(obj_bbox.find("xmin").text) y1 = int(obj_bbox.find("ymin").text) x2 = int(obj_bbox.find("xmax").text) y2 = int(obj_bbox.find("ymax").text) # for angle 90 h,w = image.shape[:2] angle_x1 = h - y2 angle_y1 = x1 angle_x2 = h -y1 angle_y2 = x2 lines = [new_name, ',', str(angle_x1), ',', str(angle_y1), ',', str(angle_x2), ',', str(angle_y2), ',', class_name, '\n'] pwd_lines.append(lines) #for angle 180 ang_x1 = w - x2 ang_y1 = h - y2 ang_x2 = w - x1 ang_y2 = h - y1 lines_180 = [new_name_180, ',', str(ang_x1), ',', str(ang_y1), ',', str(ang_x2), ',', str(ang_y2), ',', class_name, '\n'] pwd_lines.append(lines_180) #for angle 270 an_x1 = y1 an_y1 = w - x2 an_x2 = y2 an_y2 = w - x1 lines_270 = [new_name_270, ',', str(an_x1), ',', str(an_y1), ',', str(an_x2), ',', str(an_y2), ',', class_name, '\n'] pwd_lines.append(lines_270) # for pwd_line in pwd_lines: xml_name = pwd_line[0].replace(".jp2",".xml") if not os.path.isfile(save_xml+"/"+xml_name): #Elementの完成 root = ET.Element('annotations') ET.SubElement(root, 'filename').text = pwd_line[5] ET.SubElement(root, 'folder').text = "images" size = ET.SubElement(root, 'size') w,h,d = image.shape[:3] ET.SubElement(size,"width").text = str(w) ET.SubElement(size,"height").text = str(h) ET.SubElement(size,"depth").text = str(d) for pwd_lines in pwd_lines: obj = ET.SubElement(root, 'object') ET.SubElement(obj, "name").text = pwd_line[5] ET.SubElement(obj, "pose").text = "Unspecified" ET.SubElement(obj, "truncated").text = str(0) ET.SubElement(obj, "difficult").text = str(0) ET.SubElement(obj,"xmin").text = str(pwd_line[1]) ET.SubElement(obj,"ymin").text = str(pwd_line[2]) ET.SubElement(obj,"xmax").text = str(pwd_line[3]) ET.SubElement(obj,"ymax").text = str(pwd_line[4]) #xml tree = ET.ElementTree(root) tree.write(save_xml+"/"+xml_name) def rotate2(xpath, ipath, save_img, save_xml): assert os.path.exists(xpath) assert os.path.exists(ipath) os.makedirs(save_xml, exist_ok = True) os.makedirs(save_img, exist_ok = True) for xmlfile in tqdm(glob.glob(xpath+"/*.xml")): #xmlの読み込み tree = ET.parse(xmlfile) root = tree.getroot() filename = root.find("filename").text folder = root.find("folder").text size_elements = root.findall("size") obj_elements = root.findall("object") #imgの読み込み image = cv2.imread(ipath+filename) pwd_lines=[] #imageの保存 new_name = filename.replace(".jp2","") + '_rotate_45' + '.jp2' new_path = os.path.join(save_img, new_name) h,w,d = image.shape #45 mat = cv2.getRotationMatrix2D((w / 2, h / 2), 45, 1) img_45 = cv2.warpAffine(image, mat, (w, h)) if not os.path.isfile(new_path): cv2.imwrite(new_path,img_45) #135 mat = cv2.getRotationMatrix2D((w / 2, h / 2), 135, 1) img_135 = cv2.warpAffine(image, mat, (w, h)) new_name = filename.replace(".jp2","") + '_rotate_135' + '.jp2' new_path = os.path.join(save_img, new_name) if not os.path.isfile(new_path): cv2.imwrite(new_path,img_135) #225 mat = cv2.getRotationMatrix2D((w / 2, h / 2), 225, 1) img_225 = cv2.warpAffine(image, mat, (w, h)) new_name = filename.replace(".jp2","") + '_rotate_225' + '.jp2' new_path = os.path.join(save_img, new_name) if not os.path.isfile(new_path): cv2.imwrite(new_path,img_225) #315 mat = cv2.getRotationMatrix2D((w / 2, h / 2), 315, 1) img_315 = cv2.warpAffine(image, mat, (w, h)) new_name = filename.replace(".jp2","") + '_rotate_315' + '.jp2' new_path = os.path.join(save_img, new_name) if not os.path.isfile(new_path): cv2.imwrite(new_path,img_315) #15 mat = cv2.getRotationMatrix2D((w / 2, h / 2), 15, 1) img_15 = cv2.warpAffine(image, mat, (w, h)) new_name = filename.replace(".jp2","") + '_rotate_15' + '.jp2' new_path = os.path.join(save_img, new_name) if not os.path.isfile(new_path): cv2.imwrite(new_path,img_15) #105 mat = cv2.getRotationMatrix2D((w / 2, h / 2), 105, 1) img_105 = cv2.warpAffine(image, mat, (w, h)) new_name = filename.replace(".jp2","") + '_rotate_105' + '.jp2' new_path = os.path.join(save_img, new_name) if not os.path.isfile(new_path): cv2.imwrite(new_path,img_105) #195 mat = cv2.getRotationMatrix2D((w / 2, h / 2), 195, 1) img_195 = cv2.warpAffine(image, mat, (w, h)) new_name = filename.replace(".jp2","") + '_rotate_195' + '.jp2' new_path = os.path.join(save_img, new_name) if not os.path.isfile(new_path): cv2.imwrite(new_path,img_195) #285 mat = cv2.getRotationMatrix2D((w / 2, h / 2), 285, 1) img_285 = cv2.warpAffine(image, mat, (w, h)) new_name = filename.replace(".jp2","") + '_rotate_285' + '.jp2' new_path = os.path.join(save_img, new_name) if not os.path.isfile(new_path): cv2.imwrite(new_path,img_285) for obj in obj_elements: class_name = obj.find('name').text obj_bbox = obj.find('bndbox') x1 = obj_bbox.find("xmin").text y1 = obj_bbox.find("ymin").text x2 = obj_bbox.find("xmax").text y2 = obj_bbox.find("ymax").text # for angle 45 h,w,d = image.shape mat = cv2.getRotationMatrix2D((w / 2, h / 2), 45, 1) img_45 = cv2.warpAffine(image, mat, (w, h)) theta = -45 sin = math.sin(math.radians(theta)) cos = math.cos(math.radians(theta)) x1_45 = (x1 - w/2)*cos - (y1 - h/2)*sin + w/2 y1_45 = (x1 - w/2)*sin + (y1 - h/2)*cos + h/2 x2_45 = (x2 - w/2)*cos - (y2 - h/2)*sin + w/2 y2_45 = (x2 - w/2)*sin + (y2 - h/2)*cos + h/2 x3_45 = (x2 - w/2)*cos - (y1 - h/2)*sin + w/2 y3_45 = (x2 - w/2)*sin + (y1 - h/2)*cos + h/2 x4_45 = (x1 - w/2)*cos - (y2 - h/2)*sin + w/2 y4_45 = (x1 - w/2)*sin + (y2 - h/2)*cos + h/2 r45_x1 = np.round(min([x1_45, x2_45, x3_45, x4_45])).astype(np.uint16) r45_y1 = np.round(min([y1_45, y2_45, y3_45, y4_45])).astype(np.uint16) r45_x2 = np.round(max([x1_45, x2_45, x3_45, x4_45])).astype(np.uint16) r45_y2 = np.round(max([y1_45, y2_45, y3_45, y4_45])).astype(np.uint16) lines = [new_name, ',', str(r45_x1), ',', str(r45_y1), ',', str(r45_x2), ',', str(r45_y2), ',', class_name, '\n'] pwd_lines.append(lines) # for angle 135 theta = -135 sin = math.sin(math.radians(theta)) cos = math.cos(math.radians(theta)) x1_135 = (x1 - w/2)*cos - (y1 - h/2)*sin + w/2 y1_135 = (x1 - w/2)*sin + (y1 - h/2)*cos + h/2 x2_135 = (x2 - w/2)*cos - (y2 - h/2)*sin + w/2 y2_135 = (x2 - w/2)*sin + (y2 - h/2)*cos + h/2 x3_135 = (x2 - w/2)*cos - (y1 - h/2)*sin + w/2 y3_135 = (x2 - w/2)*sin + (y1 - h/2)*cos + h/2 x4_135 = (x1 - w/2)*cos - (y2 - h/2)*sin + w/2 y4_135 = (x1 - w/2)*sin + (y2 - h/2)*cos + h/2 r135_x1 = np.round(min([x1_135, x2_135, x3_135, x4_135])).astype(np.uint16) r135_y1 = np.round(min([y1_135, y2_135, y3_135, y4_135])).astype(np.uint16) r135_x2 = np.round(max([x1_135, x2_135, x3_135, x4_135])).astype(np.uint16) r135_y2 = np.round(max([y1_135, y2_135, y3_135, y4_135])).astype(np.uint16) lines = [new_name, ',', str(r135_x1), ',', str(r135_y1), ',', str(r135_x2), ',', str(r135_y2), ',', class_name, '\n'] pwd_lines.append(lines) # for angle 225 theta = -225 sin = math.sin(math.radians(theta)) cos = math.cos(math.radians(theta)) x1_225 = (x1 - w/2)*cos - (y1 - h/2)*sin + w/2 y1_225 = (x1 - w/2)*sin + (y1 - h/2)*cos + h/2 x2_225 = (x2 - w/2)*cos - (y2 - h/2)*sin + w/2 y2_225 = (x2 - w/2)*sin + (y2 - h/2)*cos + h/2 x3_225 = (x2 - w/2)*cos - (y1 - h/2)*sin + w/2 y3_225 = (x2 - w/2)*sin + (y1 - h/2)*cos + h/2 x4_225 = (x1 - w/2)*cos - (y2 - h/2)*sin + w/2 y4_225 = (x1 - w/2)*sin + (y2 - h/2)*cos + h/2 r225_x1 = np.round(min([x1_225, x2_225, x3_225, x4_225])).astype(np.uint16) r225_y1 = np.round(min([y1_225, y2_225, y3_225, y4_225])).astype(np.uint16) r225_x2 = np.round(max([x1_225, x2_225, x3_225, x4_225])).astype(np.uint16) r225_y2 = np.round(max([y1_225, y2_225, y3_225, y4_225])).astype(np.uint16) lines = [new_name, ',', str(r225_x1), ',', str(r225_y1), ',', str(r225_x2), ',', str(r225_y2), ',', class_name, '\n'] pwd_lines.append(lines) # for angle 315 theta = -315 sin = math.sin(math.radians(theta)) cos = math.cos(math.radians(theta)) x1_315 = (x1 - w/2)*cos - (y1 - h/2)*sin + w/2 y1_315 = (x1 - w/2)*sin + (y1 - h/2)*cos + h/2 x2_315 = (x2 - w/2)*cos - (y2 - h/2)*sin + w/2 y2_315 = (x2 - w/2)*sin + (y2 - h/2)*cos + h/2 x3_315 = (x2 - w/2)*cos - (y1 - h/2)*sin + w/2 y3_315 = (x2 - w/2)*sin + (y1 - h/2)*cos + h/2 x4_315 = (x1 - w/2)*cos - (y2 - h/2)*sin + w/2 y4_315 = (x1 - w/2)*sin + (y2 - h/2)*cos + h/2 r315_x1 = np.round(min([x1_315, x2_315, x3_315, x4_315])).astype(np.uint16) r315_y1 = np.round(min([y1_315, y2_315, y3_315, y4_315])).astype(np.uint16) r315_x2 = np.round(max([x1_315, x2_315, x3_315, x4_315])).astype(np.uint16) r315_y2 = np.round(max([y1_315, y2_315, y3_315, y4_315])).astype(np.uint16) lines = [new_name, ',', str(r315_x1), ',', str(r315_y1), ',', str(r315_x2), ',', str(r315_y2), ',', class_name, '\n'] pwd_lines.append(lines) # for angle 15 theta = -15 sin = math.sin(math.radians(theta)) cos = math.cos(math.radians(theta)) x1_15 = (x1 - w/2)*cos - (y1 - h/2)*sin + w/2 y1_15 = (x1 - w/2)*sin + (y1 - h/2)*cos + h/2 x2_15 = (x2 - w/2)*cos - (y2 - h/2)*sin + w/2 y2_15 = (x2 - w/2)*sin + (y2 - h/2)*cos + h/2 x3_15 = (x2 - w/2)*cos - (y1 - h/2)*sin + w/2 y3_15 = (x2 - w/2)*sin + (y1 - h/2)*cos + h/2 x4_15 = (x1 - w/2)*cos - (y2 - h/2)*sin + w/2 y4_15 = (x1 - w/2)*sin + (y2 - h/2)*cos + h/2 r15_x1 = np.round(min([x1_15, x2_15, x3_15, x4_15])).astype(np.uint16) r15_y1 = np.round(min([y1_15, y2_15, y3_15, y4_15])).astype(np.uint16) r15_x2 = np.round(max([x1_15, x2_15, x3_15, x4_15])).astype(np.uint16) r15_y2 = np.round(max([y1_15, y2_15, y3_15, y4_15])).astype(np.uint16) lines = [new_name, ',', str(r15_x1), ',', str(r15_y1), ',', str(r15_x2), ',', str(r15_y2), ',', class_name, '\n'] pwd_lines.append(lines) # for angle 105 theta = -105 sin = math.sin(math.radians(theta)) cos = math.cos(math.radians(theta)) x1_105 = (x1 - w/2)*cos - (y1 - h/2)*sin + w/2 y1_105 = (x1 - w/2)*sin + (y1 - h/2)*cos + h/2 x2_105 = (x2 - w/2)*cos - (y2 - h/2)*sin + w/2 y2_105 = (x2 - w/2)*sin + (y2 - h/2)*cos + h/2 x3_105 = (x2 - w/2)*cos - (y1 - h/2)*sin + w/2 y3_105 = (x2 - w/2)*sin + (y1 - h/2)*cos + h/2 x4_105 = (x1 - w/2)*cos - (y2 - h/2)*sin + w/2 y4_105 = (x1 - w/2)*sin + (y2 - h/2)*cos + h/2 r105_x1 = np.round(min([x1_105, x2_105, x3_105, x4_105])).astype(np.uint16) r105_y1 = np.round(min([y1_105, y2_105, y3_105, y4_105])).astype(np.uint16) r105_x2 = np.round(max([x1_105, x2_105, x3_105, x4_105])).astype(np.uint16) r105_y2 = np.round(max([y1_105, y2_105, y3_105, y4_105])).astype(np.uint16) lines = [new_name, ',', str(r105_x1), ',', str(r105_y1), ',', str(r105_x2), ',', str(r105_y2), ',', class_name, '\n'] pwd_lines.append(lines) # for angle 195 theta = -195 sin = math.sin(math.radians(theta)) cos = math.cos(math.radians(theta)) x1_195 = (x1 - w/2)*cos - (y1 - h/2)*sin + w/2 y1_195 = (x1 - w/2)*sin + (y1 - h/2)*cos + h/2 x2_195 = (x2 - w/2)*cos - (y2 - h/2)*sin + w/2 y2_195 = (x2 - w/2)*sin + (y2 - h/2)*cos + h/2 x3_195 = (x2 - w/2)*cos - (y1 - h/2)*sin + w/2 y3_195 = (x2 - w/2)*sin + (y1 - h/2)*cos + h/2 x4_195 = (x1 - w/2)*cos - (y2 - h/2)*sin + w/2 y4_195 = (x1 - w/2)*sin + (y2 - h/2)*cos + h/2 r195_x1 = np.round(min([x1_195, x2_195, x3_195, x4_195])).astype(np.uint16) r195_y1 = np.round(min([y1_195, y2_195, y3_195, y4_195])).astype(np.uint16) r195_x2 = np.round(max([x1_195, x2_195, x3_195, x4_195])).astype(np.uint16) r195_y2 = np.round(max([y1_195, y2_195, y3_195, y4_195])).astype(np.uint16) lines = [new_name, ',', str(r195_x1), ',', str(r195_y1), ',', str(r195_x2), ',', str(r195_y2), ',', class_name, '\n'] pwd_lines.append(lines) # for angle 285 theta = -285 sin = math.sin(math.radians(theta)) cos = math.cos(math.radians(theta)) x1_285 = (x1 - w/2)*cos - (y1 - h/2)*sin + w/2 y1_285 = (x1 - w/2)*sin + (y1 - h/2)*cos + h/2 x2_285 = (x2 - w/2)*cos - (y2 - h/2)*sin + w/2 y2_285 = (x2 - w/2)*sin + (y2 - h/2)*cos + h/2 x3_285 = (x2 - w/2)*cos - (y1 - h/2)*sin + w/2 y3_285 = (x2 - w/2)*sin + (y1 - h/2)*cos + h/2 x4_285 = (x1 - w/2)*cos - (y2 - h/2)*sin + w/2 y4_285 = (x1 - w/2)*sin + (y2 - h/2)*cos + h/2 r285_x1 = np.round(min([x1_285, x2_285, x3_285, x4_285])).astype(np.uint16) r285_y1 = np.round(min([y1_285, y2_285, y3_285, y4_285])).astype(np.uint16) r285_x2 = np.round(max([x1_285, x2_285, x3_285, x4_285])).astype(np.uint16) r285_y2 = np.round(max([y1_285, y2_285, y3_285, y4_285])).astype(np.uint16) lines = [new_name, ',', str(r285_x1), ',', str(r285_y1), ',', str(r285_x2), ',', str(r285_y2), ',', class_name, '\n'] pwd_lines.append(lines) for pwd_line in pwd_lines: xml_name = pwd_line[0].replace(".jp2",".xml") if not os.path.isfile(save_xml+"/"+xml_name): #Elementの完成 root = ET.Element('annotations') ET.SubElement(root, 'filename').text = pwd_line[5] ET.SubElement(root, 'folder').text = "images" size = ET.SubElement(root, 'size') w,h,d = image.shape[:3] ET.SubElement(size,"width").text = str(w) ET.SubElement(size,"height").text = str(h) ET.SubElement(size,"depth").text = str(d) for pwd_line in pwd_lines: obj = ET.SubElement(root, 'object') ET.SubElement(obj, "name").text = pwd_line[5] ET.SubElement(obj, "pose").text = "Unspecified" ET.SubElement(obj, "truncated").text = str(0) ET.SubElement(obj, "difficult").text = str(0) ET.SubElement(obj,"xmin").text = str(pwd_line[1]) ET.SubElement(obj,"ymin").text = str(pwd_line[2]) ET.SubElement(obj,"xmax").text = str(pwd_line[3]) ET.SubElement(obj,"ymax").text = str(pwd_line[4]) #xml tree = ET.ElementTree(root) tree.write(save_xml+"/"+xml_name) def confirm (xml_path, data_path): xml_files1=glob.glob(xml_path+"/*.xml") print('xmlfileの数は : '+str(len(xml_files1))) image_files1=glob.glob(data_path+"/*.jp2") print('image_fileの数は :'+str(len(image_files1))) silent=0 low=0 high=0 count=0 count1=0 count2=0 assert len(xml_files1) <= len(image_files1) for xml_file in xml_files1: et = ET.parse(xml_file) #xml fileを一つの木として認識 element = et.getroot() #getroot()で枝を認識 element_objs = element.findall('object') element_filename = element.find('filename').text base_filename = os.path.join(data_path, element_filename) if os.path.exists(base_filename)==False: #print('この画像ファイルは存在しません : '+str(element_filename)) count2+=1 continue #element_objが1つのbox、element_objsが1枚の画像に含まれるbox cellcount=0 for element_obj in element_objs: class_name = element_obj.find('name').text if class_name=='silent': silent+=1 cellcount+=1 if class_name=='low': low+=1 cellcount+=1 if class_name=='high': high+=1 cellcount+=1 if cellcount==0: count1+=1 else: count+=1 print() print('xmlがあり、細胞が存在する画像の枚数は :'+str(count)) print('xmlがあり、細胞が存在しない画像の枚数は :'+str(count1)) print('xmlがあり、対応する画像が存在しないものは :'+str(count2)) print('silentの細胞数は :'+str(silent)) print('lowの細胞数は : '+str(low)) print('highの細胞数は : '+str(high)) def set_copy(xpath, ipath, save_xml, save_img): assert os.path.exists(xpath) assert os.path.exists(ipath) os.makedirs(save_xml, exist_ok = True) os.makedirs(save_img, exist_ok = True) for file in tqdm(glob.glob(xpath+"/*.xml")): name = os.path.basename(file) if not os.path.exists(save_xml+name): shutil.copy(file, save_xml+name) for file in tqdm(glob.glob(ipath+"/*.jp2")): name = os.path.basename(file) if not os.path.exists(save_img+name): shutil.copy(file, save_img+name) def flip(xpath, ipath, save_xml, save_img): assert os.path.exists(xpath) assert os.path.exists(ipath) os.makedirs(save_xml, exist_ok = True) os.makedirs(save_img, exist_ok = True) for xmlfile in tqdm(glob.glob(xpath+"/*.xml")): #xmlの読み込み tree = ET.parse(xmlfile) root = tree.getroot() filename = root.find("filename").text folder = root.find("folder").text size_elements = root.findall("size") obj_elements = root.findall("object") image = cv2.imread(ipath+filename) f_points = [0, 1] save_objs = [] for obj in obj_elements: class_name = obj.find('name').text obj_bbox = obj.find('bndbox') xmin = int(obj_bbox.find("xmin").text) ymin = int(obj_bbox.find("ymin").text) xmax = int(obj_bbox.find("xmax").text) ymax = int(obj_bbox.find("ymax").text) for f in f_points: f_img = cv2.flip(image, f) w,h,d = image.shape[:3] if f == 1: f_x1 = w-xmax f_y1 = ymin f_x2 = w-xmin f_y2 = ymax f_str = 'f1' elif f == 0: f_x1 = xmin f_y1 = h - ymax f_x2 = xmax f_y2 = h-ymin f_str = 'f0' save_objs.append([class_name,f_x1, f_y1, f_x2, f_y2]) new_name = filename.replace(".jp2","") + '-' + f_str + '.jp2' save_path = save_img + "/" + new_name # jp2の保存 if not os.path.isfile(save_path): cv2.imwrite(save_path, f_img) # xml の保存 xml_name = new_name.replace('.jp2','.xml') if not os.path.isfile(save_xml+"/"+xml_name): #Elementの完成 root = ET.Element('annotations') ET.SubElement(root, 'filename').text = new_name ET.SubElement(root, 'folder').text = "images" size = ET.SubElement(root, 'size') ET.SubElement(size,"width").text = str(w) ET.SubElement(size,"height").text = str(h) ET.SubElement(size,"depth").text = str(d) for save_obj in save_objs: obj = ET.SubElement(root, 'object') ET.SubElement(obj, "name").text = save_obj[0] ET.SubElement(obj, "pose").text = "Unspecified" ET.SubElement(obj, "truncated").text = str(0) ET.SubElement(obj, "difficult").text = str(0) ET.SubElement(obj,"xmin").text = str(save_obj[1]) ET.SubElement(obj,"ymin").text = str(save_obj[2]) ET.SubElement(obj,"xmax").text = str(save_obj[3]) ET.SubElement(obj,"ymax").text = str(save_obj[4]) #保存 tree = ET.ElementTree(root) tree.write(save_xml+"/"+xml_name) #https://qiita.com/koshian2/items/78de8ccd09dd2998ddfc #データの色分布を加味した色の加減ができ、Data Augmentationとしてよく用いられるカラーチャンネルシフトよりも自然な画像が出来上がる def pca_color_augmentation(xpath, ipath, save_img, save_xml): assert os.path.exists(xpath) assert os.path.exists(ipath) os.makedirs(save_xml, exist_ok = True) os.makedirs(save_img, exist_ok = True) for xmlfile in tqdm(glob.glob(xpath+"/*.xml")): #xmlの読み込み tree = ET.parse(xmlfile) root = tree.getroot() filename = root.find("filename").text folder = root.find("folder").text size_elements = root.findall("size") obj_elements = root.findall("object") save_objs = [] for obj in obj_elements: class_name = obj.find('name').text obj_bbox = obj.find('bndbox') xmin = obj_bbox.find("xmin").text ymin = obj_bbox.find("ymin").text xmax = obj_bbox.find("xmax").text ymax = obj_bbox.find("ymax").text save_objs.append([class_name,xmin, ymin, xmax, ymax]) #imgの読み込み image = cv2.imread(ipath+filename) #color_augmentation (image) assert image.ndim == 3 and image.shape[2] == 3 assert image.dtype == np.uint8 img = image.reshape(-1, 3).astype(np.float32) sf = np.sqrt(3.0/np.sum(np.var(img, axis=0))) img = (img - np.mean(img, axis=0))*sf cov = np.cov(img, rowvar=False) # calculate the covariance matrix value, p = np.linalg.eig(cov) # calculation of eigen vector and eigen value rand = np.random.randn(3)*0.08 delta = np.dot(p, rand*value) delta = (delta*255.0).astype(np.int32)[np.newaxis, np.newaxis, :] img_out = np.clip(image+delta, 0, 255).astype(np.uint8) #imageの保存 colorname = filename.replace(".jp2",'-color0' +'.jp2') if not os.path.exists(save_img+"/"+colorname): cv2.imwrite(save_img+"/"+colorname, img_out) xml_name = colorname.replace(".jp2",".xml") if not os.path.isfile(save_xml+"/"+xml_name): #Elementの完成 root = ET.Element('annotations') ET.SubElement(root, 'filename').text = colorname ET.SubElement(root, 'folder').text = "images" size = ET.SubElement(root, 'size') w,h,d = image.shape[:3] ET.SubElement(size,"width").text = str(w) ET.SubElement(size,"height").text = str(h) ET.SubElement(size,"depth").text = str(d) for save_obj in save_objs: obj = ET.SubElement(root, 'object') ET.SubElement(obj, "name").text = save_obj[0] ET.SubElement(obj, "pose").text = "Unspecified" ET.SubElement(obj, "truncated").text = str(0) ET.SubElement(obj, "difficult").text = str(0) ET.SubElement(obj,"xmin").text = str(save_obj[1]) ET.SubElement(obj,"ymin").text = str(save_obj[2]) ET.SubElement(obj,"xmax").text = str(save_obj[3]) ET.SubElement(obj,"ymax").text = str(save_obj[4]) #xml tree = ET.ElementTree(root) tree.write(save_xml+"/"+xml_name)
7828205b6b59fd05954d31bfac3220686f366f26
{ "blob_id": "7828205b6b59fd05954d31bfac3220686f366f26", "branch_name": "refs/heads/main", "committer_date": "2020-10-31T07:10:53", "content_id": "b72f54b4d36cc376ccef2d557055f7b782bd2226", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "4c5fe60b548164099942335b380a198e340605a4", "extension": "py", "filename": "augment.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 308814247, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 28694, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/augment.py", "provenance": "stack-edu-0057.json.gz:106669", "repo_name": "komez/augment_pack", "revision_date": "2020-10-31T07:10:53", "revision_id": "50384d7465e3a12cd73be90867e46e80ee045968", "snapshot_id": "98f58924baf813180ea92bf6897338ab16830710", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/komez/augment_pack/50384d7465e3a12cd73be90867e46e80ee045968/augment.py", "visit_date": "2023-01-02T22:58:21.232110", "added": "2024-11-19T03:00:11.433906+00:00", "created": "2020-10-31T07:10:53", "int_score": 2, "score": 2.46875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0075.json.gz" }
import * as core from '@actions/core'; import * as tc from '@actions/tool-cache'; import { mkdirP } from '@actions/io'; import { compiler } from './compiler'; async function run() { try { if (process.arch != "x64") throw new Error("Only x64 arch is supported by all platforms"); const input = core.getInput('compiler'); const descr = await compiler(input); console.log(`Enabling ${input}`); let cached = tc.find('dc', input); if (cached) { console.log("Using cache"); } else { console.log(`Downloading ${descr.url}`); const archive = await tc.downloadTool(descr.url); const dc_path = await extract(archive); cached = await tc.cacheDir(dc_path, 'dc', input); } core.addPath(cached + descr.binpath); core.exportVariable("DC", descr.name); console.log("Done"); } catch (error) { core.setFailed(error.message); } } async function extract(archive: string) { switch (process.platform) { case "win32": return await tc.extract7z(archive); case "linux": case "darwin": return await tc.extractTar(archive, undefined, 'x'); default: throw new Error("unsupported platform: " + process.platform); } } run();
9abaa490207060b3317b16a92ab5bfbbd39f2799
{ "blob_id": "9abaa490207060b3317b16a92ab5bfbbd39f2799", "branch_name": "refs/heads/master", "committer_date": "2019-09-17T15:54:44", "content_id": "26f6e981815e2e078e8d8960d7cf3fcefc40636e", "detected_licenses": [ "MIT" ], "directory_id": "c23ef8bf0b3f84d55a2c5b0db929f6161b56b700", "extension": "ts", "filename": "main.ts", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 208139354, "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1368, "license": "MIT", "license_type": "permissive", "path": "/src/main.ts", "provenance": "stack-edu-0075.json.gz:750813", "repo_name": "kinke/setup-dlang", "revision_date": "2019-09-17T15:54:44", "revision_id": "782a868db47c559c4fcc4c2d594bd0bc1cd1ac40", "snapshot_id": "cad1c08c382fa8f1bfbc08735dd4a43f042f699e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/kinke/setup-dlang/782a868db47c559c4fcc4c2d594bd0bc1cd1ac40/src/main.ts", "visit_date": "2020-07-25T02:46:57.288177", "added": "2024-11-19T00:58:51.222070+00:00", "created": "2019-09-17T15:54:44", "int_score": 2, "score": 2.484375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0093.json.gz" }
const superagent = require('superagent'); const jwt_decode =require('jwt-decode') const validation = require('../../lib/validation-methods') const auth_0 = require('../../lib/authprofile-methods') const query = require('./profile-queries') const profileValidate = require('./profile-validation') const profile = {}; profile.fetchProfile = (req, res) => { let token = validation.checkForToken(req.headers.authorization) auth_0.getAuthProfile(token) .then(user=>{ validation.validateUid(user) .then(user=>{ query.fetchProfileQuery(res, user) }) .catch(err=>console.log(err)) }) .catch(err=>console.log('error extracting user from auth 0',err)) } profile.updateProfile = (req,res) => { let token = validation.checkForToken(req.headers.authorization) let profileInfo = profileValidate.userProfileValidate(req.body) auth_0.decodeToken(token) .then(user=>{ validation.validateUid(user) .then(user=>{ query.updateProfileQuery(res, user, profileInfo) }) .catch(err=>{ console.log(err) res(500).send(err) }) }) .catch(err=>{ console.log(err) res(500).send(err) }) } profile.delete module.exports = profile;
ad4805607344307057af96a58cbe6d4e469704a0
{ "blob_id": "ad4805607344307057af96a58cbe6d4e469704a0", "branch_name": "refs/heads/master", "committer_date": "2018-11-14T04:44:38", "content_id": "0481a5ae485ea9ac9786717e17f3505a84ed0a8e", "detected_licenses": [ "MIT" ], "directory_id": "26cafe7e9a7e2bb265ef3f964a266102467d9937", "extension": "js", "filename": "profile-methods.js", "fork_events_count": 0, "gha_created_at": "2018-06-28T02:05:47", "gha_event_created_at": "2018-11-14T04:09:04", "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 138954100, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1376, "license": "MIT", "license_type": "permissive", "path": "/routes-api/profile/profile-methods.js", "provenance": "stack-edu-0042.json.gz:778609", "repo_name": "axelmichael11/poller-backend", "revision_date": "2018-11-14T04:44:38", "revision_id": "93a53efe592b2ebbc0f62e27066a1bc0bfaddfe0", "snapshot_id": "487edba030c26646dbf7887f99e22b7b2d8af58b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/axelmichael11/poller-backend/93a53efe592b2ebbc0f62e27066a1bc0bfaddfe0/routes-api/profile/profile-methods.js", "visit_date": "2020-03-21T19:31:17.887812", "added": "2024-11-19T01:27:47.498738+00:00", "created": "2018-11-14T04:44:38", "int_score": 2, "score": 2.046875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0060.json.gz" }
package cronjob import ( "fmt" "os" "github.com/kyma-incubator/compass/components/director/pkg/kubernetes" "github.com/kyma-incubator/compass/components/director/pkg/log" "context" "time" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/tools/leaderelection" "k8s.io/client-go/tools/leaderelection/resourcelock" ) const hostnameEnvVar = "HOSTNAME" // ElectionConfig configuration for k8s leader election with lease type ElectionConfig struct { LeaseLockName string `envconfig:"APP_ELECTION_LEASE_LOCK_NAME"` LeaseLockNamespace string `envconfig:"APP_ELECTION_LEASE_LOCK_NAMESPACE"` LeaseDuration time.Duration `envconfig:"optional,default=60s,APP_ELECTION_LEASE_DURATION"` RenewDeadline time.Duration `envconfig:"optional,default=15s,APP_ELECTION_RENEW_DEADLINE"` RetryPeriod time.Duration `envconfig:"optional,default=5s,APP_ELECTION_RETRY_PERIOD"` ElectionEnabled bool `envconfig:"optional,default=true,APP_ELECTION_ENABLED"` ClientConfig kubernetes.Config } // CronJob represents a job that executes Fn on every SchedulePeriod. type CronJob struct { Name string Fn func(ctx context.Context) SchedulePeriod time.Duration } type cronJobRunner struct { CronJob CronJob stop context.CancelFunc } func (r *cronJobRunner) Start(ctx context.Context) { newCtx, stop := context.WithCancel(ctx) r.stop = stop defer r.Stop() for { start := time.Now() log.C(ctx).Infof("Starting CronJob %s execution", r.CronJob.Name) r.CronJob.Fn(newCtx) if newCtx.Err() != nil { log.C(ctx).Infof("CronJob %s stopped due to context done", r.CronJob.Name) return } jobTime := time.Since(start) log.C(ctx).Infof("CronJob %s executed for %s", r.CronJob.Name, jobTime.String()) if jobTime < r.CronJob.SchedulePeriod { waitPeriod := r.CronJob.SchedulePeriod - jobTime log.C(ctx).Infof("Scheduling CronJob %s to run after %s", r.CronJob.Name, waitPeriod.String()) select { case <-newCtx.Done(): log.C(ctx).Infof("Context of CronJob %s is done. Exiting CronJob loop...", r.CronJob.Name) return case <-time.After(waitPeriod): log.C(ctx).Infof("Waited %s to run next iteration of CronJob %s", waitPeriod.String(), r.CronJob.Name) } } } } func (r *cronJobRunner) Stop() { if r.stop != nil { r.stop() } } func runLeaderLeaseLoop(ctx context.Context, electionConfig ElectionConfig, job CronJob) error { k8sConfig := electionConfig.ClientConfig client, err := kubernetes.NewKubernetesClientSet( ctx, k8sConfig.PollInterval, k8sConfig.PollTimeout, k8sConfig.Timeout) if err != nil { return err } electionID := os.Getenv(hostnameEnvVar) if electionID == "" { return fmt.Errorf("not running in k8s pod. Env variable %s not set", hostnameEnvVar) } runner := cronJobRunner{ CronJob: job, } lock := &resourcelock.LeaseLock{ LeaseMeta: metav1.ObjectMeta{ Name: electionConfig.LeaseLockName, Namespace: electionConfig.LeaseLockNamespace, }, Client: client.CoordinationV1(), LockConfig: resourcelock.ResourceLockConfig{ Identity: electionID, }, } leaderElectionConfig := leaderelection.LeaderElectionConfig{ Lock: lock, ReleaseOnCancel: true, LeaseDuration: electionConfig.LeaseDuration, RenewDeadline: electionConfig.RenewDeadline, RetryPeriod: electionConfig.RetryPeriod, Callbacks: leaderelection.LeaderCallbacks{ OnStartedLeading: func(ctx context.Context) { log.C(ctx).Infof("Starting CronJob executor on %s", electionID) runner.Start(ctx) log.C(ctx).Infof("CronJob executor on %s exited", electionID) }, OnStoppedLeading: func() { log.C(ctx).Errorf("Instance %s is no longer leader. Stopping CronJob executor", electionID) runner.Stop() }, OnNewLeader: func(identity string) { log.C(ctx).Debugf("Instance %s elected as leader", identity) }, }, } leaderElection, err := leaderelection.NewLeaderElector(leaderElectionConfig) if err != nil { return err } leaderElection.Run(ctx) return nil } func runCronJobWithElection(ctx context.Context, cfg ElectionConfig, job CronJob) error { for { if err := runLeaderLeaseLoop(ctx, cfg, job); err != nil { return err } select { case <-ctx.Done(): log.C(ctx).Info("Leader lease loop context is done, exiting leader lease loop...") return nil default: log.C(ctx).Error("Leader lease loop ended, re-running...") } } } // RunCronJob runs a CronJob and blocks. // If cfg.LeaseEnabled is true then only one pod (if application is scaled) will run the cron job. // This is done using leader election from k8s with leases. // Returns error in case of bad configuration or bad connection to k8s cluster func RunCronJob(ctx context.Context, cfg ElectionConfig, job CronJob) error { if cfg.ElectionEnabled { return runCronJobWithElection(ctx, cfg, job) } runner := cronJobRunner{ CronJob: job, } runner.Start(ctx) return nil }
0b8cb5e9d5f6dfcd6f89091339e54e06e407f7fc
{ "blob_id": "0b8cb5e9d5f6dfcd6f89091339e54e06e407f7fc", "branch_name": "refs/heads/main", "committer_date": "2023-08-31T14:14:54", "content_id": "99eac22346afd89e54b938becbf2ed42d3f6422e", "detected_licenses": [ "Apache-2.0" ], "directory_id": "87117c688490e19624673ab2825a629cbf39c8cd", "extension": "go", "filename": "cronjob.go", "fork_events_count": 109, "gha_created_at": "2019-05-14T09:28:13", "gha_event_created_at": "2023-09-14T15:47:31", "gha_language": "Go", "gha_license_id": "Apache-2.0", "github_id": 186589820, "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 4979, "license": "Apache-2.0", "license_type": "permissive", "path": "/components/director/pkg/cronjob/cronjob.go", "provenance": "stack-edu-0018.json.gz:380784", "repo_name": "kyma-incubator/compass", "revision_date": "2023-08-31T14:14:54", "revision_id": "cd659afd6f3ad07fa048aa9b027a668b3666c26b", "snapshot_id": "474b346b20ea5d6ad48a6f42a06c51adb5ef505f", "src_encoding": "UTF-8", "star_events_count": 54, "url": "https://raw.githubusercontent.com/kyma-incubator/compass/cd659afd6f3ad07fa048aa9b027a668b3666c26b/components/director/pkg/cronjob/cronjob.go", "visit_date": "2023-09-01T03:15:59.554086", "added": "2024-11-19T02:10:05.149267+00:00", "created": "2023-08-31T14:14:54", "int_score": 2, "score": 2.484375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0036.json.gz" }
package array_and_matrix; import java.util.HashMap; import java.util.Map; /** * @Author: Wenhang Chen * @Description:给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现了三次。找出那个只出现了一次的元素。 说明: * <p> * 你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗? * <p> * 示例 1: * <p> * 输入: [2,2,3,2] * 输出: 3 * 示例 2: * <p> * 输入: [0,1,0,1,0,1,99] * 输出: 99 * @Date: Created in 19:37 6/19/2020 * @Modified by: */ public class OnceNumberII { public int singleNumber(int[] nums) { if (nums == null || nums.length < 1) return 0; Map<Integer, Integer> map = new HashMap<>(); for (int num : nums) { map.put(num, map.getOrDefault(num, 0) + 1); } for (Map.Entry<Integer, Integer> entry : map.entrySet()) { if (entry.getValue() == 1) return entry.getKey(); } return 0; } }
972a7cd207d195ab17a9f30f9e81d1c85f1060a1
{ "blob_id": "972a7cd207d195ab17a9f30f9e81d1c85f1060a1", "branch_name": "refs/heads/master", "committer_date": "2021-09-26T12:20:25", "content_id": "f87c08534798bc86d08d89ccb171e2d591d296c0", "detected_licenses": [ "MIT" ], "directory_id": "faeac99b8391b181784168a8cfea764e4cb62f83", "extension": "java", "filename": "OnceNumberII.java", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 217215897, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1060, "license": "MIT", "license_type": "permissive", "path": "/src/array_and_matrix/OnceNumberII.java", "provenance": "stack-edu-0025.json.gz:752924", "repo_name": "chenwenhang/AlgorithmPractice", "revision_date": "2021-09-26T12:20:25", "revision_id": "e35b18094d4bf25d4e4065d5bc9a611009aff233", "snapshot_id": "123f9987c7b1621e4bb38d10f583e01c5c92220d", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/chenwenhang/AlgorithmPractice/e35b18094d4bf25d4e4065d5bc9a611009aff233/src/array_and_matrix/OnceNumberII.java", "visit_date": "2021-10-03T02:22:36.397972", "added": "2024-11-19T00:26:37.266989+00:00", "created": "2021-09-26T12:20:25", "int_score": 4, "score": 3.828125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0043.json.gz" }
/* * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package javafx.scene.shape; import com.sun.javafx.geom.Arc2D; import com.sun.javafx.geom.Path2D; import com.sun.javafx.geom.PathIterator; import com.sun.javafx.geom.transform.BaseTransform; import com.sun.javafx.sg.prism.NGPath; import javafx.beans.property.BooleanProperty; import javafx.beans.property.BooleanPropertyBase; import javafx.beans.property.DoubleProperty; import javafx.beans.property.DoublePropertyBase; // PENDING_DOC_REVIEW /** * A path element that forms an arc from the previous coordinates * to the specified x and y coordinates using the specified radius. * * <p>For more information on path elements see the {@link Path} and * {@link PathElement} classes. * * <p>Example: * <PRE> import javafx.scene.shape.*; Path path = new Path(); MoveTo moveTo = new MoveTo(); moveTo.setX(0.0); moveTo.setY(0.0); ArcTo arcTo = new ArcTo(); arcTo.setX(50.0); arcTo.setY(50.0); arcTo.setRadiusX(50.0); arcTo.setRadiusY(50.0); path.getElements().add(moveTo); path.getElements().add(arcTo); </PRE> * * <p> * Following image demonstrates {@code radiusX}, {@code radiusY} and * {@code xAxisRotation} parameters: * {@code radiusX} is the horizontal radius of the full ellipse of which this arc is * a partial section, {@code radiusY} is its vertical radius. * {@code xAxisRotation} defines the rotation of the ellipse in degrees. * </p> * <p> * <img src="doc-files/arcto.png"/> * </p> * <p> * In most cases, there are four options of how to draw an arc from * starting point to given end coordinates. They can be distinguished by * {@code largeArcFlag} and {@code sweepFlag} parameters. * {@code largeArcFlag == true} means that the arc greater than 180 degrees will * be drawn. {@code sweepFlag == true} means that the arc will be drawn * in the positive angle direction - i.e. the angle in the * ellipse formula will increase from {@code [fromX, fromY]} to {@code [x,y]}. * Following images demonstrate this behavior: * </p> * <p> * <img src="doc-files/arcto-flags.png"/> * </p> * @since JavaFX 2.0 */ public class ArcTo extends PathElement { /** * Creates an empty instance of ArcTo. */ public ArcTo() { } /** * Creates a new instance of ArcTo. * @param radiusX horizontal radius of the arc * @param radiusY vertical radius of the arc * @param xAxisRotation the x-axis rotation in degrees * @param x horizontal position of the arc end point * @param y vertical position of the arc end point * @param largeArcFlag large arg flag: determines which arc to use (large/small) * @param sweepFlag sweep flag: determines which arc to use (direction) */ public ArcTo(double radiusX, double radiusY, double xAxisRotation, double x, double y, boolean largeArcFlag, boolean sweepFlag) { setRadiusX(radiusX); setRadiusY(radiusY); setXAxisRotation(xAxisRotation); setX(x); setY(y); setLargeArcFlag(largeArcFlag); setSweepFlag(sweepFlag); } /** * The horizontal radius to use for the arc. * * @defaultValue 0.0 */ private DoubleProperty radiusX = new DoublePropertyBase() { @Override public void invalidated() { u(); } @Override public Object getBean() { return ArcTo.this; } @Override public String getName() { return "radiusX"; } }; public final void setRadiusX(double value) { radiusX.set(value); } public final double getRadiusX() { return radiusX.get(); } public final DoubleProperty radiusXProperty() { return radiusX; } /** * The vertical radius to use for the arc. * * @defaultValue 0.0 */ private DoubleProperty radiusY = new DoublePropertyBase() { @Override public void invalidated() { u(); } @Override public Object getBean() { return ArcTo.this; } @Override public String getName() { return "radiusY"; } }; public final void setRadiusY(double value) { radiusY.set(value); } public final double getRadiusY() { return radiusY.get(); } public final DoubleProperty radiusYProperty() { return radiusY; } /** * The x-axis rotation in degrees. * * @defaultValue 0.0 */ private DoubleProperty xAxisRotation; /** * Sets the x-axis rotation in degrees. * @param value the x-axis rotation in degrees. */ public final void setXAxisRotation(double value) { if (xAxisRotation != null || value != 0.0) { XAxisRotationProperty().set(value); } } /** * Gets the x-axis rotation in degrees. * @return the x-axis rotation in degrees. */ public final double getXAxisRotation() { return xAxisRotation == null ? 0.0 : xAxisRotation.get(); } /** * The x-axis rotation in degrees. * @return The XAxisRotation property */ public final DoubleProperty XAxisRotationProperty() { if (xAxisRotation == null) { xAxisRotation = new DoublePropertyBase() { @Override public void invalidated() { u(); } @Override public Object getBean() { return ArcTo.this; } @Override public String getName() { return "XAxisRotation"; } }; } return xAxisRotation; } /** * The large arc flag. * * @defaultValue false */ private BooleanProperty largeArcFlag; public final void setLargeArcFlag(boolean value) { if (largeArcFlag != null || value != false) { largeArcFlagProperty().set(value); } } public final boolean isLargeArcFlag() { return largeArcFlag == null ? false : largeArcFlag.get(); } public final BooleanProperty largeArcFlagProperty() { if (largeArcFlag == null) { largeArcFlag = new BooleanPropertyBase() { @Override public void invalidated() { u(); } @Override public Object getBean() { return ArcTo.this; } @Override public String getName() { return "largeArcFlag"; } }; } return largeArcFlag; } /** * The sweep flag * * @defaultValue false */ private BooleanProperty sweepFlag; public final void setSweepFlag(boolean value) { if (sweepFlag != null || value != false) { sweepFlagProperty().set(value); } } public final boolean isSweepFlag() { return sweepFlag == null ? false : sweepFlag.get(); } public final BooleanProperty sweepFlagProperty() { if (sweepFlag == null) { sweepFlag = new BooleanPropertyBase() { @Override public void invalidated() { u(); } @Override public Object getBean() { return ArcTo.this; } @Override public String getName() { return "sweepFlag"; } }; } return sweepFlag; } /** * The x coordinate to arc to. * * @defaultValue 0.0 */ private DoubleProperty x; public final void setX(double value) { if (x != null || value != 0.0) { xProperty().set(value); } } public final double getX() { return x == null ? 0.0 : x.get(); } public final DoubleProperty xProperty() { if (x == null) { x = new DoublePropertyBase() { @Override public void invalidated() { u(); } @Override public Object getBean() { return ArcTo.this; } @Override public String getName() { return "x"; } }; } return x; } /** * The y coordinate to arc to. * * @defaultValue 0.0 */ private DoubleProperty y; public final void setY(double value) { if (y != null || value != 0.0) { yProperty().set(value); } } public final double getY() { return y == null ? 0.0 : y.get(); } public final DoubleProperty yProperty() { if (y == null) { y = new DoublePropertyBase() { @Override public void invalidated() { u(); } @Override public Object getBean() { return ArcTo.this; } @Override public String getName() { return "y"; } }; } return y; } @Override void addTo(NGPath pgPath) { addArcTo(pgPath, null, pgPath.getCurrentX(), pgPath.getCurrentY()); } /** * @treatAsPrivate implementation detail * @deprecated This is an internal API that is not intended for use and will be removed in the next version */ @Deprecated @Override public void impl_addTo(Path2D path) { addArcTo(null, path, path.getCurrentX(), path.getCurrentY()); } // This function is nearly identical to the one written for the // original port of the F3 graphics/UI library: // javafx.ui.canvas.ArcTo#addTo private void addArcTo(NGPath pgPath, Path2D path, final double x0, final double y0) { double localX = getX(); double localY = getY(); boolean localSweepFlag = isSweepFlag(); boolean localLargeArcFlag = isLargeArcFlag(); // Determine target "to" position final double xto = (isAbsolute()) ? localX : localX + x0; final double yto = (isAbsolute()) ? localY : localY + y0; // Compute the half distance between the current and the final point final double dx2 = (x0 - xto) / 2.0; final double dy2 = (y0 - yto) / 2.0; // Convert angle from degrees to radians final double xAxisRotationR = Math.toRadians(getXAxisRotation()); final double cosAngle = Math.cos(xAxisRotationR); final double sinAngle = Math.sin(xAxisRotationR); // // Step 1 : Compute (x1, y1) // final double x1 = ( cosAngle * dx2 + sinAngle * dy2); final double y1 = (-sinAngle * dx2 + cosAngle * dy2); // Ensure radii are large enough double rx = Math.abs(getRadiusX()); double ry = Math.abs(getRadiusY()); double Prx = rx * rx; double Pry = ry * ry; final double Px1 = x1 * x1; final double Py1 = y1 * y1; // check that radii are large enough final double radiiCheck = Px1/Prx + Py1/Pry; if (radiiCheck > 1.0) { rx = Math.sqrt(radiiCheck) * rx; ry = Math.sqrt(radiiCheck) * ry; if (rx == rx && ry == ry) {/* not NANs */} else { if (pgPath == null) { path.lineTo((float) xto, (float) yto); } else { pgPath.addLineTo((float) xto, (float) yto); } return; } Prx = rx * rx; Pry = ry * ry; } // // Step 2 : Compute (cx1, cy1) // double sign = ((localLargeArcFlag == localSweepFlag) ? -1.0 : 1.0); double sq = ((Prx*Pry)-(Prx*Py1)-(Pry*Px1)) / ((Prx*Py1)+(Pry*Px1)); sq = (sq < 0.0) ? 0.0 : sq; final double coef = (sign * Math.sqrt(sq)); final double cx1 = coef * ((rx * y1) / ry); final double cy1 = coef * -((ry * x1) / rx); // // Step 3 : Compute (cx, cy) from (cx1, cy1) // final double sx2 = (x0 + xto) / 2.0; final double sy2 = (y0 + yto) / 2.0; final double cx = sx2 + (cosAngle * cx1 - sinAngle * cy1); final double cy = sy2 + (sinAngle * cx1 + cosAngle * cy1); // // Step 4 : Compute the angleStart (angle1) and the angleExtent (dangle) // final double ux = (x1 - cx1) / rx; final double uy = (y1 - cy1) / ry; final double vx = (-x1 - cx1) / rx; final double vy = (-y1 - cy1) / ry; // Compute the angle start double n = Math.sqrt((ux * ux) + (uy * uy)); double p = ux; // (1 * ux) + (0 * uy) sign = ((uy < 0.0) ? -1.0 : 1.0); double angleStart = Math.toDegrees(sign * Math.acos(p / n)); // Compute the angle extent n = Math.sqrt((ux * ux + uy * uy) * (vx * vx + vy * vy)); p = ux * vx + uy * vy; sign = ((ux * vy - uy * vx < 0.0) ? -1.0 : 1.0); double angleExtent = Math.toDegrees(sign * Math.acos(p / n)); if (!localSweepFlag && (angleExtent > 0)) { angleExtent -= 360.0; } else if (localSweepFlag && (angleExtent < 0)) { angleExtent += 360.0; } angleExtent = angleExtent % 360; angleStart = angleStart % 360; // // We can now build the resulting Arc2D // final float arcX = (float) (cx - rx); final float arcY = (float) (cy - ry); final float arcW = (float) (rx * 2.0); final float arcH = (float) (ry * 2.0); final float arcStart = (float) -angleStart; final float arcExtent = (float) -angleExtent; if (pgPath == null) { final Arc2D arc = new Arc2D(arcX, arcY, arcW, arcH, arcStart, arcExtent, Arc2D.OPEN); BaseTransform xform = (xAxisRotationR == 0) ? null : BaseTransform.getRotateInstance(xAxisRotationR, cx, cy); PathIterator pi = arc.getPathIterator(xform); // RT-8926, append(true) converts the initial moveTo into a // lineTo which can generate huge miter joins if the segment // is small enough. So, we manually skip it here instead. pi.next(); path.append(pi, true); } else { pgPath.addArcTo(arcX, arcY, arcW, arcH, arcStart, arcExtent, (float) xAxisRotationR); } } /** * Returns a string representation of this {@code ArcTo} object. * @return a string representation of this {@code ArcTo} object. */ @Override public String toString() { final StringBuilder sb = new StringBuilder("ArcTo["); sb.append("x=").append(getX()); sb.append(", y=").append(getY()); sb.append(", radiusX=").append(getRadiusX()); sb.append(", radiusY=").append(getRadiusY()); sb.append(", xAxisRotation=").append(getXAxisRotation()); if (isLargeArcFlag()) { sb.append(", lartArcFlag"); } if (isSweepFlag()) { sb.append(", sweepFlag"); } return sb.append("]").toString(); } }
cd1817f6bd267d42df2bbf8417668c170dc4fb20
{ "blob_id": "cd1817f6bd267d42df2bbf8417668c170dc4fb20", "branch_name": "refs/heads/main", "committer_date": "2021-04-05T13:40:48", "content_id": "bb2b97bceda4c5f747d9c7fc459440659fabe21a", "detected_licenses": [ "Apache-2.0" ], "directory_id": "6103cb13beb5c3564376849332c0f65013fb1e4a", "extension": "java", "filename": "ArcTo.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 334418487, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 15730, "license": "Apache-2.0", "license_type": "permissive", "path": "/javafx-src/javafx/scene/shape/ArcTo.java", "provenance": "stack-edu-0023.json.gz:541874", "repo_name": "songningbo/jdk8source", "revision_date": "2021-04-05T13:40:48", "revision_id": "7458e994df5fc9519004e60d280b728b6736a978", "snapshot_id": "26e1c3b66ce589f0d1bbe4e50a39de0adf106b68", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/songningbo/jdk8source/7458e994df5fc9519004e60d280b728b6736a978/javafx-src/javafx/scene/shape/ArcTo.java", "visit_date": "2023-03-30T01:12:21.275633", "added": "2024-11-18T21:16:58.826962+00:00", "created": "2021-04-05T13:40:48", "int_score": 3, "score": 2.671875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0041.json.gz" }
using System; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Serialization; namespace Requester.Serialization { public static class DefaultJsonSerializerSettings { public static IContractResolver DefaultContractResolver = new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy(false, false, false) }; public static Func<JsonSerializerSettings, JsonSerializerSettings> Applier { private get; set; } = settings => { settings.NullValueHandling = NullValueHandling.Ignore; settings.DateFormatHandling = DateFormatHandling.IsoDateFormat; settings.DateTimeZoneHandling = DateTimeZoneHandling.Utc; settings.MissingMemberHandling = MissingMemberHandling.Ignore; settings.TypeNameHandling = TypeNameHandling.None; settings.ContractResolver = DefaultContractResolver; settings.Converters.Add(new StringEnumConverter()); return settings; }; public static JsonSerializerSettings Create() => ApplyTo(new JsonSerializerSettings()); public static JsonSerializerSettings ApplyTo(JsonSerializerSettings settings) => Applier(settings); } }
5b9653eaae37a38c309642f7a9620c51fb4e3cdb
{ "blob_id": "5b9653eaae37a38c309642f7a9620c51fb4e3cdb", "branch_name": "refs/heads/master", "committer_date": "2017-07-14T17:41:17", "content_id": "9c8fb3b17514791ca09587f1fe6fb8ed81f8a9a7", "detected_licenses": [ "MIT" ], "directory_id": "970ea19f543f20ae35ee32550e705e4082a79947", "extension": "cs", "filename": "DefaultJsonSerializerSettings.cs", "fork_events_count": 8, "gha_created_at": "2015-04-29T21:24:42", "gha_event_created_at": "2017-07-05T18:25:50", "gha_language": "C#", "gha_license_id": null, "github_id": 34819153, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1315, "license": "MIT", "license_type": "permissive", "path": "/src/projects/Requester/Serialization/DefaultJsonSerializerSettings.cs", "provenance": "stack-edu-0013.json.gz:512751", "repo_name": "danielwertheim/requester", "revision_date": "2017-07-14T17:41:17", "revision_id": "942eec129d705f03eb4aae67d5c135cf596a6c1f", "snapshot_id": "4fe373fb3feb61dd7115f484a910184a05435723", "src_encoding": "UTF-8", "star_events_count": 38, "url": "https://raw.githubusercontent.com/danielwertheim/requester/942eec129d705f03eb4aae67d5c135cf596a6c1f/src/projects/Requester/Serialization/DefaultJsonSerializerSettings.cs", "visit_date": "2020-06-01T15:40:37.160523", "added": "2024-11-19T00:50:25.936781+00:00", "created": "2017-07-14T17:41:17", "int_score": 3, "score": 2.609375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0031.json.gz" }
from collections import deque from functools import reduce from itertools import product from os.path import exists, dirname, join from os import remove, stat from stat import S_ISFIFO from subprocess import PIPE, STDOUT, run from tempfile import mkstemp import logging from .mode import Mode from ..asp import unlite, fact, atom, AnswerSet from ..common import Action, Orientation, Location, paint from ..simulator import World from ..util import dlv logger = logging.getLogger('asp-agent') plain = { # Required to return the desired action to the game. 'do': (Action,), # The next three are needed to implement the autopilot. 'autopilot': (), 'goal': (Location,), 'safe': (Location,), # For diagnosing de facto inconsistencies. 'bad': (int,), # This one is needed for painting. 'size': (int,), } interesting = { # For debugging, you may add other predicates here. # Note that painters are added below. 'mode': (Mode,), } painted = ( { 'now': Orientation, 'h': int, }, { 'frontier': 'F', 'safe': 'S', 'pit': 'P', 'next': 'N', 'goal': 'G', 'wumpus': 'W', } ) extract = dict(plain) extract.update(interesting) extract.update(dict([ (predicate, (Location,target)) for predicate, target in painted[0].items() ])) extract.update(dict([ (predicate, (Location,)) for predicate in painted[1].keys() ])) class ASPAgent(): def __init__(self): self.dlv = dlv() self.actions = [] self.shot = None self.grabbed = None self.world = {} self.position = Location(1, 1) self.orientation = Orientation.RIGHT self.killed = False self.bumped = None self.previousAction = None self.size = 2 self.paint = exists('agent') and S_ISFIFO(stat('agent').st_mode) _, self.prog = mkstemp() unlite(join(dirname(__file__), 'agent.md'), self.prog) # To look at the ASP-Core compliant version, uncomment this. #unlite(join(dirname(__file__), 'agent.md'), 'agent.asp') def process(self, percept): if percept.scream: self.killed = True if percept.bump: self.bumped = self.position.getAdjacent(self.orientation, self.size + 1) elif self.previousAction == Action.GOFORWARD: self.position = self.position.getAdjacent(self.orientation, self.size) elif self.previousAction in {Action.TURNLEFT, Action.TURNRIGHT}: self.orientation = self.orientation.turn(self.previousAction) elif self.previousAction == Action.SHOOT: self.shot = (self.position, self.orientation) elif self.previousAction == Action.GRAB: self.grabbed = self.position if self.actions != []: self.previousAction = self.actions.pop(0) return self.previousAction self.world[self.position] = (percept.stench, percept.breeze, percept.glitter) result = self.solve() self.size = result.singleton('size') if self.paint: paint( self.size, [(result.tofun(pred),) for pred, _ in painted[0].items()] + [(result.tobfun(pred), symbol) for pred, symbol in painted[1].items()], 'agent', result.pretty(interesting.keys()) ) if self.bad(result): return None if not result.proposition('autopilot'): self.previousAction = result.singleton('do') return self.previousAction goal = result.singleton('goal') self.actions = self.bfs(result['safe'], goal) mode = result.singleton('mode') if mode == Mode.ESCAPE and goal == Location(1, 1) and len(self.actions) > 0: self.actions.append(Action.CLIMB) self.previousAction = self.actions.pop(0) return self.previousAction def facts(self): # now/3 and killed/0 are certain. result = [ fact(True, 'now', [*self.position, int(self.orientation)]), fact(self.killed, 'killed'), ] if self.bumped != None: result.append(fact(True, 'bumped', self.bumped)) if self.shot != None: result.append(fact(True, 'shot', [*self.shot[0], int(self.shot[1])])) if self.grabbed != None: result.append(fact(True, 'grabbed', self.grabbed)) for k, v in self.world.items(): result += [ fact(v[i], name, k) for i, name in enumerate(['stench', 'breeze', 'glitter']) ] + [ fact(True, 'explored', k) ] return result def solve(self): result = run( [ self.dlv, '-n=1', '-silent', '-filter=' + ','.join(extract.keys()), self.prog, '--' ], stderr=STDOUT, stdout=PIPE, input='\n'.join(self.facts()), encoding='utf-8' ).stdout if len(result) == 0: logger.debug('ASP program did not return any answer sets! Inconsistency?') return None if result.startswith('Best model: {'): start, end = result.find('{'), result.find('}') result = result[start:end+1] if result[0] != '{': logger.error('ASP Errors:\n \033[31m' + result.replace('\n', '\n ') + '\033[0m') return None return AnswerSet.parse(result.strip().split('\n')[0], extract) def bad(self, result): bads = result.true('bad') if len(bads) == 0: return False for (x,) in bads: prefix = '%{} '.format(x) found = False with open(self.prog) as f: for ln in f: if ln.startswith(prefix): found = True logger.debug('\033[31mCONSISTENCY ' + str(x) + ': ' + ln[len(prefix):].strip() + '\033[0m') if not found: logger.debug('No comment describing bad({}). Add a line starting with \'%{} \' followed by a description.'.format(x, x)) return True def bfs(self, safe, target): source = (self.position, self.orientation) visited = {source: None} queue = deque([source]) while queue: node = queue.popleft() if node[0] == target: path = [] while node is not None: v = visited[node] if v == None: break act, node = v path.append(act) return path[::-1] (l, o) = node neighbours = [(a, (l, o.turn(a))) for a in {Action.TURNLEFT, Action.TURNRIGHT}] adj = l.getAdjacent(o, self.size) if adj != None and (safe.get((adj,), False) or adj == target): neighbours.append((Action.GOFORWARD, (adj, o))) for act, neighbour in neighbours: if neighbour not in visited: visited[neighbour] = (act, node) queue.append(neighbour) return None def getStats(self): return '{:2}\t{:2}'.format(self.size, len(self.world))
31c7c3359dad72c31d4bdeb6034edb387a9dee13
{ "blob_id": "31c7c3359dad72c31d4bdeb6034edb387a9dee13", "branch_name": "refs/heads/master", "committer_date": "2018-06-05T16:27:08", "content_id": "a814fcc52eb3d15a7df41753c5a4ddd5c2b282e5", "detected_licenses": [ "MIT" ], "directory_id": "5fa15b27e3e35a460d8305b566889c6c84689b95", "extension": "py", "filename": "asp.py", "fork_events_count": 1, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 123415348, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7488, "license": "MIT", "license_type": "permissive", "path": "/Projects/hakuna_matata/src/hakuna_matata/agent/asp.py", "provenance": "stack-edu-0060.json.gz:620491", "repo_name": "lorenzleutgeb/ils", "revision_date": "2018-06-05T16:26:25", "revision_id": "2714bf5f13ba1b5a0db72e9d0394db777f52eeec", "snapshot_id": "718da0464e1d7dc23cc30321512f96a62a4046ac", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/lorenzleutgeb/ils/2714bf5f13ba1b5a0db72e9d0394db777f52eeec/Projects/hakuna_matata/src/hakuna_matata/agent/asp.py", "visit_date": "2021-03-27T10:27:23.914373", "added": "2024-11-19T01:02:20.509016+00:00", "created": "2018-06-05T16:26:25", "int_score": 2, "score": 2.234375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0078.json.gz" }
//! Intermediate representation for C/C++ functions and methods. use super::comp::MethodKind; use super::context::{BindgenContext, TypeId}; use super::dot::DotAttributes; use super::item::Item; use super::traversal::{EdgeKind, Trace, Tracer}; use super::ty::TypeKind; use crate::callbacks::{ItemInfo, ItemKind}; use crate::clang::{self, Attribute}; use crate::parse::{ClangSubItemParser, ParseError, ParseResult}; use clang_sys::{self, CXCallingConv}; use quote::TokenStreamExt; use std::io; use std::str::FromStr; const RUST_DERIVE_FUNPTR_LIMIT: usize = 12; /// What kind of a function are we looking at? #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub(crate) enum FunctionKind { /// A plain, free function. Function, /// A method of some kind. Method(MethodKind), } impl FunctionKind { /// Given a clang cursor, return the kind of function it represents, or /// `None` otherwise. pub(crate) fn from_cursor(cursor: &clang::Cursor) -> Option<FunctionKind> { // FIXME(emilio): Deduplicate logic with `ir::comp`. Some(match cursor.kind() { clang_sys::CXCursor_FunctionDecl => FunctionKind::Function, clang_sys::CXCursor_Constructor => { FunctionKind::Method(MethodKind::Constructor) } clang_sys::CXCursor_Destructor => { FunctionKind::Method(if cursor.method_is_virtual() { MethodKind::VirtualDestructor { pure_virtual: cursor.method_is_pure_virtual(), } } else { MethodKind::Destructor }) } clang_sys::CXCursor_CXXMethod => { if cursor.method_is_virtual() { FunctionKind::Method(MethodKind::Virtual { pure_virtual: cursor.method_is_pure_virtual(), }) } else if cursor.method_is_static() { FunctionKind::Method(MethodKind::Static) } else { FunctionKind::Method(MethodKind::Normal) } } _ => return None, }) } } /// The style of linkage #[derive(Debug, Clone, Copy)] pub(crate) enum Linkage { /// Externally visible and can be linked against External, /// Not exposed externally. 'static inline' functions will have this kind of linkage Internal, } /// A function declaration, with a signature, arguments, and argument names. /// /// The argument names vector must be the same length as the ones in the /// signature. #[derive(Debug)] pub(crate) struct Function { /// The name of this function. name: String, /// The mangled name, that is, the symbol. mangled_name: Option<String>, /// The link name. If specified, overwrite mangled_name. link_name: Option<String>, /// The ID pointing to the current function signature. signature: TypeId, /// The kind of function this is. kind: FunctionKind, /// The linkage of the function. linkage: Linkage, } impl Function { /// Construct a new function. pub(crate) fn new( name: String, mangled_name: Option<String>, link_name: Option<String>, signature: TypeId, kind: FunctionKind, linkage: Linkage, ) -> Self { Function { name, mangled_name, link_name, signature, kind, linkage, } } /// Get this function's name. pub(crate) fn name(&self) -> &str { &self.name } /// Get this function's name. pub(crate) fn mangled_name(&self) -> Option<&str> { self.mangled_name.as_deref() } /// Get this function's link name. pub fn link_name(&self) -> Option<&str> { self.link_name.as_deref() } /// Get this function's signature type. pub(crate) fn signature(&self) -> TypeId { self.signature } /// Get this function's kind. pub(crate) fn kind(&self) -> FunctionKind { self.kind } /// Get this function's linkage. pub(crate) fn linkage(&self) -> Linkage { self.linkage } } impl DotAttributes for Function { fn dot_attributes<W>( &self, _ctx: &BindgenContext, out: &mut W, ) -> io::Result<()> where W: io::Write, { if let Some(ref mangled) = self.mangled_name { let mangled: String = mangled.chars().flat_map(|c| c.escape_default()).collect(); writeln!( out, "<tr><td>mangled name</td><td>{}</td></tr>", mangled )?; } Ok(()) } } /// A valid rust ABI. #[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)] pub enum Abi { /// The default C ABI. C, /// The "stdcall" ABI. Stdcall, /// The "efiapi" ABI. EfiApi, /// The "fastcall" ABI. Fastcall, /// The "thiscall" ABI. ThisCall, /// The "vectorcall" ABI. Vectorcall, /// The "aapcs" ABI. Aapcs, /// The "win64" ABI. Win64, /// The "C-unwind" ABI. CUnwind, /// The "system" ABI. System, } impl FromStr for Abi { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "C" => Ok(Self::C), "stdcall" => Ok(Self::Stdcall), "efiapi" => Ok(Self::EfiApi), "fastcall" => Ok(Self::Fastcall), "thiscall" => Ok(Self::ThisCall), "vectorcall" => Ok(Self::Vectorcall), "aapcs" => Ok(Self::Aapcs), "win64" => Ok(Self::Win64), "C-unwind" => Ok(Self::CUnwind), "system" => Ok(Self::System), _ => Err(format!("Invalid or unknown ABI {:?}", s)), } } } impl std::fmt::Display for Abi { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let s = match *self { Self::C => "C", Self::Stdcall => "stdcall", Self::EfiApi => "efiapi", Self::Fastcall => "fastcall", Self::ThisCall => "thiscall", Self::Vectorcall => "vectorcall", Self::Aapcs => "aapcs", Self::Win64 => "win64", Self::CUnwind => "C-unwind", Abi::System => "system", }; s.fmt(f) } } impl quote::ToTokens for Abi { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { let abi = self.to_string(); tokens.append_all(quote! { #abi }); } } /// An ABI extracted from a clang cursor. #[derive(Debug, Copy, Clone)] pub(crate) enum ClangAbi { /// An ABI known by Rust. Known(Abi), /// An unknown or invalid ABI. Unknown(CXCallingConv), } impl ClangAbi { /// Returns whether this Abi is known or not. fn is_unknown(&self) -> bool { matches!(*self, ClangAbi::Unknown(..)) } } impl quote::ToTokens for ClangAbi { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { match *self { Self::Known(abi) => abi.to_tokens(tokens), Self::Unknown(cc) => panic!( "Cannot turn unknown calling convention to tokens: {:?}", cc ), } } } /// A function signature. #[derive(Debug)] pub(crate) struct FunctionSig { /// The name of this function signature. name: String, /// The return type of the function. return_type: TypeId, /// The type of the arguments, optionally with the name of the argument when /// declared. argument_types: Vec<(Option<String>, TypeId)>, /// Whether this function is variadic. is_variadic: bool, is_divergent: bool, /// Whether this function's return value must be used. must_use: bool, /// The ABI of this function. abi: ClangAbi, } fn get_abi(cc: CXCallingConv) -> ClangAbi { use clang_sys::*; match cc { CXCallingConv_Default => ClangAbi::Known(Abi::C), CXCallingConv_C => ClangAbi::Known(Abi::C), CXCallingConv_X86StdCall => ClangAbi::Known(Abi::Stdcall), CXCallingConv_X86FastCall => ClangAbi::Known(Abi::Fastcall), CXCallingConv_X86ThisCall => ClangAbi::Known(Abi::ThisCall), CXCallingConv_X86VectorCall => ClangAbi::Known(Abi::Vectorcall), CXCallingConv_AAPCS => ClangAbi::Known(Abi::Aapcs), CXCallingConv_X86_64Win64 => ClangAbi::Known(Abi::Win64), other => ClangAbi::Unknown(other), } } /// Get the mangled name for the cursor's referent. pub(crate) fn cursor_mangling( ctx: &BindgenContext, cursor: &clang::Cursor, ) -> Option<String> { if !ctx.options().enable_mangling { return None; } // We early return here because libclang may crash in some case // if we pass in a variable inside a partial specialized template. // See rust-lang/rust-bindgen#67, and rust-lang/rust-bindgen#462. if cursor.is_in_non_fully_specialized_template() { return None; } let is_destructor = cursor.kind() == clang_sys::CXCursor_Destructor; if let Ok(mut manglings) = cursor.cxx_manglings() { while let Some(m) = manglings.pop() { // Only generate the destructor group 1, see below. if is_destructor && !m.ends_with("D1Ev") { continue; } return Some(m); } } let mut mangling = cursor.mangling(); if mangling.is_empty() { return None; } if is_destructor { // With old (3.8-) libclang versions, and the Itanium ABI, clang returns // the "destructor group 0" symbol, which means that it'll try to free // memory, which definitely isn't what we want. // // Explicitly force the destructor group 1 symbol. // // See http://refspecs.linuxbase.org/cxxabi-1.83.html#mangling-special // for the reference, and http://stackoverflow.com/a/6614369/1091587 for // a more friendly explanation. // // We don't need to do this for constructors since clang seems to always // have returned the C1 constructor. // // FIXME(emilio): Can a legit symbol in other ABIs end with this string? // I don't think so, but if it can this would become a linker error // anyway, not an invalid free at runtime. // // TODO(emilio, #611): Use cpp_demangle if this becomes nastier with // time. if mangling.ends_with("D0Ev") { let new_len = mangling.len() - 4; mangling.truncate(new_len); mangling.push_str("D1Ev"); } } Some(mangling) } fn args_from_ty_and_cursor( ty: &clang::Type, cursor: &clang::Cursor, ctx: &mut BindgenContext, ) -> Vec<(Option<String>, TypeId)> { let cursor_args = cursor.args().unwrap_or_default().into_iter(); let type_args = ty.args().unwrap_or_default().into_iter(); // Argument types can be found in either the cursor or the type, but argument names may only be // found on the cursor. We often have access to both a type and a cursor for each argument, but // in some cases we may only have one. // // Prefer using the type as the source of truth for the argument's type, but fall back to // inspecting the cursor (this happens for Objective C interfaces). // // Prefer using the cursor for the argument's type, but fall back to using the parent's cursor // (this happens for function pointer return types). cursor_args .map(Some) .chain(std::iter::repeat(None)) .zip(type_args.map(Some).chain(std::iter::repeat(None))) .take_while(|(cur, ty)| cur.is_some() || ty.is_some()) .map(|(arg_cur, arg_ty)| { let name = arg_cur.map(|a| a.spelling()).and_then(|name| { if name.is_empty() { None } else { Some(name) } }); let cursor = arg_cur.unwrap_or(*cursor); let ty = arg_ty.unwrap_or_else(|| cursor.cur_type()); (name, Item::from_ty_or_ref(ty, cursor, None, ctx)) }) .collect() } impl FunctionSig { /// Get the function name. pub(crate) fn name(&self) -> &str { &self.name } /// Construct a new function signature from the given Clang type. pub(crate) fn from_ty( ty: &clang::Type, cursor: &clang::Cursor, ctx: &mut BindgenContext, ) -> Result<Self, ParseError> { use clang_sys::*; debug!("FunctionSig::from_ty {:?} {:?}", ty, cursor); // Skip function templates let kind = cursor.kind(); if kind == CXCursor_FunctionTemplate { return Err(ParseError::Continue); } let spelling = cursor.spelling(); // Don't parse operatorxx functions in C++ let is_operator = |spelling: &str| { spelling.starts_with("operator") && !clang::is_valid_identifier(spelling) }; if is_operator(&spelling) { return Err(ParseError::Continue); } // Constructors of non-type template parameter classes for some reason // include the template parameter in their name. Just skip them, since // we don't handle well non-type template parameters anyway. if (kind == CXCursor_Constructor || kind == CXCursor_Destructor) && spelling.contains('<') { return Err(ParseError::Continue); } let cursor = if cursor.is_valid() { *cursor } else { ty.declaration() }; let mut args = match kind { CXCursor_FunctionDecl | CXCursor_Constructor | CXCursor_CXXMethod | CXCursor_ObjCInstanceMethodDecl | CXCursor_ObjCClassMethodDecl => { args_from_ty_and_cursor(ty, &cursor, ctx) } _ => { // For non-CXCursor_FunctionDecl, visiting the cursor's children // is the only reliable way to get parameter names. let mut args = vec![]; cursor.visit(|c| { if c.kind() == CXCursor_ParmDecl { let ty = Item::from_ty_or_ref(c.cur_type(), c, None, ctx); let name = c.spelling(); let name = if name.is_empty() { None } else { Some(name) }; args.push((name, ty)); } CXChildVisit_Continue }); if args.is_empty() { // FIXME(emilio): Sometimes libclang doesn't expose the // right AST for functions tagged as stdcall and such... // // https://bugs.llvm.org/show_bug.cgi?id=45919 args_from_ty_and_cursor(ty, &cursor, ctx) } else { args } } }; let (must_use, mut is_divergent) = if ctx.options().enable_function_attribute_detection { let [must_use, no_return, no_return_cpp] = cursor.has_attrs(&[ Attribute::MUST_USE, Attribute::NO_RETURN, Attribute::NO_RETURN_CPP, ]); (must_use, no_return || no_return_cpp) } else { Default::default() }; // This looks easy to break but the clang parser keeps the type spelling clean even if // other attributes are added. is_divergent = is_divergent || ty.spelling().contains("__attribute__((noreturn))"); let is_method = kind == CXCursor_CXXMethod; let is_constructor = kind == CXCursor_Constructor; let is_destructor = kind == CXCursor_Destructor; if (is_constructor || is_destructor || is_method) && cursor.lexical_parent() != cursor.semantic_parent() { // Only parse constructors once. return Err(ParseError::Continue); } if is_method || is_constructor || is_destructor { let is_const = is_method && cursor.method_is_const(); let is_virtual = is_method && cursor.method_is_virtual(); let is_static = is_method && cursor.method_is_static(); if !is_static && !is_virtual { let parent = cursor.semantic_parent(); let class = Item::parse(parent, None, ctx) .expect("Expected to parse the class"); // The `class` most likely is not finished parsing yet, so use // the unchecked variant. let class = class.as_type_id_unchecked(); let class = if is_const { let const_class_id = ctx.next_item_id(); ctx.build_const_wrapper( const_class_id, class, None, &parent.cur_type(), ) } else { class }; let ptr = Item::builtin_type(TypeKind::Pointer(class), false, ctx); args.insert(0, (Some("this".into()), ptr)); } else if is_virtual { let void = Item::builtin_type(TypeKind::Void, false, ctx); let ptr = Item::builtin_type(TypeKind::Pointer(void), false, ctx); args.insert(0, (Some("this".into()), ptr)); } } let ty_ret_type = if kind == CXCursor_ObjCInstanceMethodDecl || kind == CXCursor_ObjCClassMethodDecl { ty.ret_type() .or_else(|| cursor.ret_type()) .ok_or(ParseError::Continue)? } else { ty.ret_type().ok_or(ParseError::Continue)? }; let ret = if is_constructor && ctx.is_target_wasm32() { // Constructors in Clang wasm32 target return a pointer to the object // being constructed. let void = Item::builtin_type(TypeKind::Void, false, ctx); Item::builtin_type(TypeKind::Pointer(void), false, ctx) } else { Item::from_ty_or_ref(ty_ret_type, cursor, None, ctx) }; // Clang plays with us at "find the calling convention", see #549 and // co. This seems to be a better fix than that commit. let mut call_conv = ty.call_conv(); if let Some(ty) = cursor.cur_type().canonical_type().pointee_type() { let cursor_call_conv = ty.call_conv(); if cursor_call_conv != CXCallingConv_Invalid { call_conv = cursor_call_conv; } } let abi = get_abi(call_conv); if abi.is_unknown() { warn!("Unknown calling convention: {:?}", call_conv); } Ok(Self { name: spelling, return_type: ret, argument_types: args, is_variadic: ty.is_variadic(), is_divergent, must_use, abi, }) } /// Get this function signature's return type. pub(crate) fn return_type(&self) -> TypeId { self.return_type } /// Get this function signature's argument (name, type) pairs. pub(crate) fn argument_types(&self) -> &[(Option<String>, TypeId)] { &self.argument_types } /// Get this function signature's ABI. pub(crate) fn abi( &self, ctx: &BindgenContext, name: Option<&str>, ) -> crate::codegen::error::Result<ClangAbi> { // FIXME (pvdrz): Try to do this check lazily instead. Maybe store the ABI inside `ctx` // instead?. let abi = if let Some(name) = name { if let Some((abi, _)) = ctx .options() .abi_overrides .iter() .find(|(_, regex_set)| regex_set.matches(name)) { ClangAbi::Known(*abi) } else { self.abi } } else if let Some((abi, _)) = ctx .options() .abi_overrides .iter() .find(|(_, regex_set)| regex_set.matches(&self.name)) { ClangAbi::Known(*abi) } else { self.abi }; match abi { ClangAbi::Known(Abi::ThisCall) if !ctx.options().rust_features().thiscall_abi => { Err(crate::codegen::error::Error::UnsupportedAbi("thiscall")) } ClangAbi::Known(Abi::Vectorcall) if !ctx.options().rust_features().vectorcall_abi => { Err(crate::codegen::error::Error::UnsupportedAbi("vectorcall")) } ClangAbi::Known(Abi::CUnwind) if !ctx.options().rust_features().c_unwind_abi => { Err(crate::codegen::error::Error::UnsupportedAbi("C-unwind")) } ClangAbi::Known(Abi::EfiApi) if !ctx.options().rust_features().abi_efiapi => { Err(crate::codegen::error::Error::UnsupportedAbi("efiapi")) } ClangAbi::Known(Abi::Win64) if self.is_variadic() => { Err(crate::codegen::error::Error::UnsupportedAbi("Win64")) } abi => Ok(abi), } } /// Is this function signature variadic? pub(crate) fn is_variadic(&self) -> bool { // Clang reports some functions as variadic when they *might* be // variadic. We do the argument check because rust doesn't codegen well // variadic functions without an initial argument. self.is_variadic && !self.argument_types.is_empty() } /// Must this function's return value be used? pub(crate) fn must_use(&self) -> bool { self.must_use } /// Are function pointers with this signature able to derive Rust traits? /// Rust only supports deriving traits for function pointers with a limited /// number of parameters and a couple ABIs. /// /// For more details, see: /// /// * <https://github.com/rust-lang/rust-bindgen/issues/547>, /// * <https://github.com/rust-lang/rust/issues/38848>, /// * and <https://github.com/rust-lang/rust/issues/40158> pub(crate) fn function_pointers_can_derive(&self) -> bool { if self.argument_types.len() > RUST_DERIVE_FUNPTR_LIMIT { return false; } matches!(self.abi, ClangAbi::Known(Abi::C) | ClangAbi::Unknown(..)) } /// Whether this function has attributes marking it as divergent. pub(crate) fn is_divergent(&self) -> bool { self.is_divergent } } impl ClangSubItemParser for Function { fn parse( cursor: clang::Cursor, context: &mut BindgenContext, ) -> Result<ParseResult<Self>, ParseError> { use clang_sys::*; let kind = match FunctionKind::from_cursor(&cursor) { None => return Err(ParseError::Continue), Some(k) => k, }; debug!("Function::parse({:?}, {:?})", cursor, cursor.cur_type()); let visibility = cursor.visibility(); if visibility != CXVisibility_Default { return Err(ParseError::Continue); } if cursor.access_specifier() == CX_CXXPrivate { return Err(ParseError::Continue); } let linkage = cursor.linkage(); let linkage = match linkage { CXLinkage_External | CXLinkage_UniqueExternal => Linkage::External, CXLinkage_Internal => Linkage::Internal, _ => return Err(ParseError::Continue), }; if cursor.is_inlined_function() || cursor .definition() .map_or(false, |x| x.is_inlined_function()) { if !context.options().generate_inline_functions && !context.options().wrap_static_fns { return Err(ParseError::Continue); } if cursor.is_deleted_function() { return Err(ParseError::Continue); } // We cannot handle `inline` functions that are not `static`. if context.options().wrap_static_fns && cursor.is_inlined_function() && matches!(linkage, Linkage::External) { return Err(ParseError::Continue); } } // Grab the signature using Item::from_ty. let sig = Item::from_ty(&cursor.cur_type(), cursor, None, context)?; let mut name = cursor.spelling(); assert!(!name.is_empty(), "Empty function name?"); if cursor.kind() == CXCursor_Destructor { // Remove the leading `~`. The alternative to this is special-casing // code-generation for destructor functions, which seems less than // ideal. if name.starts_with('~') { name.remove(0); } // Add a suffix to avoid colliding with constructors. This would be // technically fine (since we handle duplicated functions/methods), // but seems easy enough to handle it here. name.push_str("_destructor"); } if let Some(nm) = context.options().last_callback(|callbacks| { callbacks.generated_name_override(ItemInfo { name: name.as_str(), kind: ItemKind::Function, }) }) { name = nm; } assert!(!name.is_empty(), "Empty function name."); let mangled_name = cursor_mangling(context, &cursor); let link_name = context.options().last_callback(|callbacks| { callbacks.generated_link_name_override(ItemInfo { name: name.as_str(), kind: ItemKind::Function, }) }); let function = Self::new( name.clone(), mangled_name, link_name, sig, kind, linkage, ); Ok(ParseResult::New(function, Some(cursor))) } } impl Trace for FunctionSig { type Extra = (); fn trace<T>(&self, _: &BindgenContext, tracer: &mut T, _: &()) where T: Tracer, { tracer.visit_kind(self.return_type().into(), EdgeKind::FunctionReturn); for &(_, ty) in self.argument_types() { tracer.visit_kind(ty.into(), EdgeKind::FunctionParameter); } } }
eaf32330e21fee095bbec00a8806de9c85ec49b4
{ "blob_id": "eaf32330e21fee095bbec00a8806de9c85ec49b4", "branch_name": "refs/heads/main", "committer_date": "2023-08-15T18:01:02", "content_id": "5bfb70eff1d2f856abb68ca7549d95458e32b8eb", "detected_licenses": [ "BSD-3-Clause" ], "directory_id": "96df46515663aee49a753171fb3b07d74c8ef72f", "extension": "rs", "filename": "function.rs", "fork_events_count": 391, "gha_created_at": "2016-06-22T15:05:51", "gha_event_created_at": "2023-09-12T20:32:46", "gha_language": "Rust", "gha_license_id": "BSD-3-Clause", "github_id": 61728459, "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 26835, "license": "BSD-3-Clause", "license_type": "permissive", "path": "/bindgen/ir/function.rs", "provenance": "stack-edu-0068.json.gz:203609", "repo_name": "rust-lang/rust-bindgen", "revision_date": "2023-08-15T18:01:02", "revision_id": "820ca42982fe77d5504f7a0534a3de6db6a1d703", "snapshot_id": "05273ad4d385ce0b5a2315859f8c7c453c150db6", "src_encoding": "UTF-8", "star_events_count": 2874, "url": "https://raw.githubusercontent.com/rust-lang/rust-bindgen/820ca42982fe77d5504f7a0534a3de6db6a1d703/bindgen/ir/function.rs", "visit_date": "2023-08-30T19:59:33.017994", "added": "2024-11-18T22:48:33.156797+00:00", "created": "2023-08-15T18:01:02", "int_score": 2, "score": 2.421875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0086.json.gz" }
import { Controller, DefaultWorker, Worker, textResult, viewResult, Singleton, HTTP_METHOD, Route, redirectResult, Guards } from "fortjs"; import { StudentService } from "../services/student_service"; import { StudentValidatorGuard } from "../guards/student_validator_guard"; export class StudentController extends Controller { constructor(@Singleton(StudentService) service) { super(); this.service = service; } @DefaultWorker() async getStudents() { const students = this.service.getAllStudents(); return viewResult("student/index.html", { students: students }); } @Worker(HTTP_METHOD.Get) @Route("/edit/{id}") async editStudent() { const studentId = Number(this.param.id); const student = this.service.getStudentById(studentId); if (student) { this.logger.log('student', student); return viewResult("student/edit.html", { student: student }); } else { return textResult("Invalid studentId") } } @Worker(HTTP_METHOD.Get) @Route("/add") async getStudentForm() { return viewResult("student/add.html"); } @Worker(HTTP_METHOD.Post) @Route("/add") @Guards(StudentValidatorGuard) async addStudent() { const student = this.data.student; this.service.addStudent(student); return redirectResult("/student"); } @Worker(HTTP_METHOD.Post) @Route("/update") @Guards(StudentValidatorGuard) async updateStudent() { const student = this.data.student; const isUpdated = this.service.updateStudent(student); if (isUpdated) { return redirectResult("/student"); } else { return textResult("Unable to update Student"); } } @Worker(HTTP_METHOD.Get) @Route("/delete/{id}") async deleteStudent() { const studentId = Number(this.param.id); const student = this.service.getStudentById(studentId); if (student) { this.logger.log('student', student); this.service.deleteStudentById(studentId); return redirectResult("/student"); } else { return textResult("Invalid studentId") } } }
81966b8c98bdb33019db235dfcb77a21ebaed5ac
{ "blob_id": "81966b8c98bdb33019db235dfcb77a21ebaed5ac", "branch_name": "refs/heads/master", "committer_date": "2023-06-26T05:37:12", "content_id": "a2f1e040ab1aadefe112d67cf864fd97b803cf0d", "detected_licenses": [ "MIT" ], "directory_id": "be9c1574e7c1f99c659aa0e7f4ffde21ab9f6e6e", "extension": "js", "filename": "student_controller.js", "fork_events_count": 1, "gha_created_at": "2019-12-08T01:52:51", "gha_event_created_at": "2020-08-01T08:57:08", "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 226600556, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2341, "license": "MIT", "license_type": "permissive", "path": "/crud/javascript/controllers/student_controller.js", "provenance": "stack-edu-0032.json.gz:262809", "repo_name": "ujjwalguptaofficial/fortjs-examples", "revision_date": "2023-06-26T05:37:12", "revision_id": "6fc6e9150057d407e6e475fa17891eeb9942642b", "snapshot_id": "537f4949b26bc02eecaa4cdd23ff70d898d632cd", "src_encoding": "UTF-8", "star_events_count": 2, "url": "https://raw.githubusercontent.com/ujjwalguptaofficial/fortjs-examples/6fc6e9150057d407e6e475fa17891eeb9942642b/crud/javascript/controllers/student_controller.js", "visit_date": "2023-07-07T13:25:59.847267", "added": "2024-11-18T20:49:27.317375+00:00", "created": "2023-06-26T05:37:12", "int_score": 2, "score": 2.4375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0050.json.gz" }
var LineChart = function(name, features, attributes, processed_data, div) { this.lineChart = null; this.name = name || null; this.features = features || null; this.attributes = attributes || null; this.processed_data = processed_data || null; this.getLineChart = function(){ return this.lineChart; }; this.setLineChart = function(lineChart){ this.lineChart = lineChart; }; this.cleanChartDataNullIndex(); this.initChart(div); }; Array.prototype.clean = function(deleteValue) { for (var i = 0; i < this.length; i++) { if (this[i] == deleteValue) { this.splice(i, 1); i--; } } return this; }; LineChart.prototype.cleanChartDataNullIndex = function(){ this.processed_data.clean(undefined); console.log(this.processed_data); }; LineChart.prototype.initChart = function(div){ var data = new google.visualization.DataTable(); data.addColumn('string', 'Id'); data.addColumn('number', this.attributes); data.addColumn('number', 'Média'); data.addColumn({'type': 'string', 'role': 'tooltip'}); data.addRows(this.processed_data); var options = { 'title': this.name, 'width':350, 'height':250, legend: { position: 'bottom', maxLines: 1 }, hAxis: { minValue: 0 }, vAxis: {title: this.attributes}, series: { 1: { legend: 'none' // tooltip: {isHtml: true}, } } }; var chart = new google.visualization.LineChart(div); chart.draw(data, options); };
2e04fd83ea46293cc9ae87b1d0ca923c5f230ae3
{ "blob_id": "2e04fd83ea46293cc9ae87b1d0ca923c5f230ae3", "branch_name": "refs/heads/master", "committer_date": "2019-05-28T01:07:47", "content_id": "26cba7f828071c3ffd64a53b07ebe17c4d0e0123", "detected_licenses": [ "MIT" ], "directory_id": "965e4d29599a6ded00b92f989bb395d0d1e52b3b", "extension": "js", "filename": "lineChart.js", "fork_events_count": 0, "gha_created_at": "2015-09-24T16:45:37", "gha_event_created_at": "2022-12-03T09:36:13", "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 43079847, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1637, "license": "MIT", "license_type": "permissive", "path": "/assets/js/model/lineChart.js", "provenance": "stack-edu-0041.json.gz:609662", "repo_name": "renanpupin/geovis", "revision_date": "2019-05-28T01:07:47", "revision_id": "9c8543ea250dcdf0eccb49f15c15e9d0e3b0babe", "snapshot_id": "1b2a9269c629a5823c5c0b9907bf26a9ee6739c4", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/renanpupin/geovis/9c8543ea250dcdf0eccb49f15c15e9d0e3b0babe/assets/js/model/lineChart.js", "visit_date": "2022-12-15T18:21:00.388849", "added": "2024-11-19T03:42:05.275157+00:00", "created": "2019-05-28T01:07:47", "int_score": 3, "score": 2.78125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0059.json.gz" }
#!/usr/bin/python3 # -*- coding: utf-8 -*- import funcoes as fun import nltk from nltk.corpus import stopwords from nltk.probability import FreqDist from nltk.tokenize import word_tokenize from nltk.tokenize.treebank import TreebankWordDetokenizer pos = {} texto = "Era uma vez um lugarzinho. era uma vez uma quitanda." texto = fun.converter(texto) palavras = word_tokenize(texto.lower()) fdist1 = FreqDist(palavras) qtd_palavras_texto = len(palavras) print (fdist1.hapaxes()) numerodehapaxes = len((fdist1.hapaxes())) print ("numero de hapaxes:" , numerodehapaxes) print ("Quantidade de palavras do texto", qtd_palavras_texto) print (palavras) hapax_legomana = numerodehapaxes / qtd_palavras_texto print ("razao hapax:", round(hapax_legomana,2))
91ae9c956c136d65cf31822cea8099288ed63d38
{ "blob_id": "91ae9c956c136d65cf31822cea8099288ed63d38", "branch_name": "refs/heads/master", "committer_date": "2019-12-16T02:05:57", "content_id": "fe014db535d9ec79349998b8346800ad9197053e", "detected_licenses": [ "MIT" ], "directory_id": "aeb1bfdb9e1b9d61638a5013e1ef8f7dc7ffc484", "extension": "py", "filename": "testehapaxnltk.py", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 223386386, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 752, "license": "MIT", "license_type": "permissive", "path": "/python/testehapaxnltk.py", "provenance": "stack-edu-0058.json.gz:479134", "repo_name": "raquelmachado4993/omundodanarrativagit", "revision_date": "2019-12-16T02:05:57", "revision_id": "eb8cebcc74514ba8449fab5f9dc5e9a93a826850", "snapshot_id": "b1b251950e7a85e97f5dfb4c8b2d36537c71a4b5", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/raquelmachado4993/omundodanarrativagit/eb8cebcc74514ba8449fab5f9dc5e9a93a826850/python/testehapaxnltk.py", "visit_date": "2020-09-15T08:00:04.638645", "added": "2024-11-18T19:44:13.341206+00:00", "created": "2019-12-16T02:05:57", "int_score": 3, "score": 2.984375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0076.json.gz" }
#!/usr/bin/python3 import argparse import os parser = argparse.ArgumentParser(description='A username and wordlist generator for Quebec specific users.') group = parser.add_mutually_exclusive_group(required=True) group.add_argument('-u', '--username', action='store_true', help='Generate a user list') group.add_argument('-w', '--wordlist', action='store_true', help='Generate a password list') group2 = parser.add_mutually_exclusive_group(required=True) group2.add_argument('-m', '--male', action='store_true', help='Include only male first names') group2.add_argument('-f', '--female', action='store_true', help='Include only female first names') group2.add_argument('-b', '--both', action='store_true', help='Include both male and female first names') group3 = parser.add_mutually_exclusive_group(required=False) group3.add_argument('-d', '--domain', action='store_true', help='Generate a username list as emails') parser.add_argument('-o', '--output', help='Output file name (do not include extensions or path)', required=True) args = parser.parse_args() email = "" if args.male: first_male = open("./source/william.txt", "r") fname = first_male.read() if args.female: first_female = open("./source/olivia.txt", "r") fname = first_female.read() if args.both: first_male = open("./source/william.txt", "r") first_female = open("./source/olivia.txt", "r") fname = first_male.read() + first_female.read() if args.wordlist: year_doc = open("./source/years.txt", "r") years = year_doc.read() last_name = open("./source/tremblay.txt", "r") lname = last_name.read() print("") a = open("banner.txt","r") print(a.read()) a.close() print("Version: 1.0 - June 2, 2021") print("Author: @r3dshell") print("") if args.domain: print("") email = input("[*] Enter the domain name (example.com)\n") print("") if args.username: print("") format = input("[*] Select the format for the username generation (first,last,first.last,first_last,flast,lastf,firstl,lfirst,firstlast,lastfirst): \n") print("") if format == 'first': user = '{}'.format(fname) file = open("tmp.txt", "w") if email: for lines in user.splitlines(): file.write(lines.lower() + "@" + email + '\n') else: file.write(user.lower()) if format == 'last': user = '{}'.format(lname) file = open("tmp.txt", "w") if email: for lines in user.splitlines(): file.write(lines.lower() + "@" + email + '\n') else: file.write(user.lower()) if format == 'first.last': file = open("tmp.txt", "w") if email: for lines in fname.splitlines(): for lines2 in lname.splitlines(): file.write(lines.lower() + "." + lines2.lower() + "@" + email + '\n') else: for lines in fname.splitlines(): for lines2 in lname.splitlines(): file.write(lines.lower() + "." + lines2.lower() + '\n') if format == 'first_last': file = open("tmp.txt", "w") if email: for lines in fname.splitlines(): for lines2 in lname.splitlines(): file.write(lines.lower() + "_" + lines2.lower() + "@" + email + '\n') else: for lines in fname.splitlines(): for lines2 in lname.splitlines(): file.write(lines.lower() + "_" + lines2.lower() + '\n') if format == 'flast': file = open("tmp.txt", "w") if email: for lines in fname.splitlines(): for lines2 in lname.splitlines(): file.write(lines[0].lower()+lines2.lower()+"@"+email+'\n') else: for lines in fname.splitlines(): for lines2 in lname.splitlines(): file.write(lines[0].lower()+lines2.lower()+'\n') if format == 'lastf': file = open("tmp.txt", "w") if email: for lines in fname.splitlines(): for lines2 in lname.splitlines(): file.write(lines2.lower() + lines[0].lower() + "@" + email + '\n') else: for lines in fname.splitlines(): for lines2 in lname.splitlines(): file.write(lines2.lower()+lines[0].lower()+'\n') if format == 'firstl': file = open("tmp.txt", "w") if email: for lines in fname.splitlines(): for lines2 in lname.splitlines(): file.write(lines.lower()+lines2[0].lower()+'\n') else: for lines in fname.splitlines(): for lines2 in lname.splitlines(): file.write(lines.lower() + lines2[0].lower() + '\n') if format == 'lfirst': file = open("tmp.txt", "w") if email: for lines in fname.splitlines(): for lines2 in lname.splitlines(): file.write(lines2[0].lower()+lines.lower()+'\n') else: for lines in fname.splitlines(): for lines2 in lname.splitlines(): file.write(lines2[0].lower() + lines.lower() + '\n') if format == 'firstlast': file = open("tmp.txt", "w") if email: for lines in fname.splitlines(): for lines2 in lname.splitlines(): file.write(lines.lower() + lines2.lower() + '\n') else: for lines in fname.splitlines(): for lines2 in lname.splitlines(): file.write(lines.lower() + lines2.lower() + '\n') if format == 'lastfirst': file = open("tmp.txt", "w") if email: for lines in fname.splitlines(): for lines2 in lname.splitlines(): file.write(lines2.lower() + lines.lower() + '\n') else: for lines in fname.splitlines(): for lines2 in lname.splitlines(): file.write(lines2.lower() + lines.lower() + '\n') if args.wordlist: print("") format = input("[*] Select the format for the password list generation (first+year, last+year, First+year, Last+year): \n") if format == 'first+year': file = open("tmp.txt", "w") for lines in fname.splitlines(): for lines2 in years.splitlines(): file.write(lines.lower() + lines2 + '\n') if format == 'last+year': file = open("tmp.txt", "w") for lines in lname.splitlines(): for lines2 in years.splitlines(): file.write(lines.lower() + lines2 + '\n') if format == 'First+year': file = open("tmp.txt", "w") for lines in fname.splitlines(): for lines2 in years.splitlines(): file.write(lines.lower().capitalize() + lines2 + '\n') if format == 'Last+year': file = open("tmp.txt", "w") for lines in lname.splitlines(): for lines2 in years.splitlines(): file.write(lines.lower().capitalize() + lines2 + '\n') # Duplicate removal content = open("tmp.txt",'r').readlines() content_set = set(content) cleandata = open('./'+args.output+'.txt','w') for line in content_set: cleandata.write(line) os.remove("tmp.txt")
a8041b12594fa08077122c83ca8134594b326456
{ "blob_id": "a8041b12594fa08077122c83ca8134594b326456", "branch_name": "refs/heads/main", "committer_date": "2021-06-03T02:02:30", "content_id": "54ddc740b59bf87b9edf0ff922a87939e97d0c7a", "detected_licenses": [ "MIT" ], "directory_id": "c6358479c35f394ffbf81d6a36de79faaeaa30e3", "extension": "py", "filename": "main.py", "fork_events_count": 0, "gha_created_at": "2021-06-03T05:54:50", "gha_event_created_at": "2021-06-03T05:54:50", "gha_language": null, "gha_license_id": "MIT", "github_id": 373396535, "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7346, "license": "MIT", "license_type": "permissive", "path": "/main.py", "provenance": "stack-edu-0059.json.gz:231188", "repo_name": "d33ds/QC_Username_Generator", "revision_date": "2021-06-03T02:02:30", "revision_id": "773146fd724c3196834c6eb57a5e3f697c31e914", "snapshot_id": "4892d33349861bf5640f6b1fca6a8efc7c1ff6cf", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/d33ds/QC_Username_Generator/773146fd724c3196834c6eb57a5e3f697c31e914/main.py", "visit_date": "2023-05-25T09:12:29.032851", "added": "2024-11-19T03:22:33.635397+00:00", "created": "2021-06-03T02:02:30", "int_score": 3, "score": 2.765625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0077.json.gz" }
package com.yaet.blog.controller; import com.yaet.blog.utils.RedisCacheUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @RestController @RequestMapping("") public class HomeController { private static final Logger LOGGER = LoggerFactory.getLogger(HomeController.class); @Autowired private RedisCacheUtil redisCacheUtil; @RequestMapping("/") public ModelAndView toHome(ModelAndView modelAndView) { List<Object> articles = new ArrayList<>(); for (int i = 0; i < 5; i++) { Map<String, String> article = new HashMap<>(); article.put("content", "wode booke"); articles.add(article); } if (!redisCacheUtil.hasKey("content")) { redisCacheUtil.set("content", articles); LOGGER.info(redisCacheUtil.get("content").toString()); } modelAndView.addObject("articles", articles); modelAndView.setViewName("home"); return modelAndView; } }
194ef5b5677a2aaa9a2187d8ae2d4712240259d2
{ "blob_id": "194ef5b5677a2aaa9a2187d8ae2d4712240259d2", "branch_name": "refs/heads/master", "committer_date": "2018-06-25T14:52:23", "content_id": "5a229ad338ad2fb6e4b9b1aabc01fb000e4c26dd", "detected_licenses": [ "Apache-2.0" ], "directory_id": "5203084e2daebd1b3456fa85c5313d05003f3e21", "extension": "java", "filename": "HomeController.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 135103685, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1335, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/main/java/com/yaet/blog/controller/HomeController.java", "provenance": "stack-edu-0030.json.gz:24339", "repo_name": "yaets/yaet", "revision_date": "2018-06-25T14:52:23", "revision_id": "6297ca2d93a743843e3d6c06bb8f63470782ac87", "snapshot_id": "e68c77cbfd2c7279e8a48c8d7525c2d4f85a3256", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/yaets/yaet/6297ca2d93a743843e3d6c06bb8f63470782ac87/src/main/java/com/yaet/blog/controller/HomeController.java", "visit_date": "2020-03-18T18:36:11.326268", "added": "2024-11-18T22:58:30.333156+00:00", "created": "2018-06-25T14:52:23", "int_score": 2, "score": 2.390625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0048.json.gz" }
// src/views/partials/container.js import React from 'react'; import PropTypes from 'prop-types'; const Container = ({ children, xs, sm, md, lg, xl, className }) => ( <div className={className ? className + " container" : "container"}> <style> {` ${xs ? `.container { max-width: ${xs}px; margin-left: auto; margin-right: auto; padding-left: 10px; padding-right: 10px; }` : ""}; @media (min-width: 576px) { .container { max-width: ${sm || (xs != Container.defaultProps.xs && xs) || 560}px; padding-left: 0px; padding-right: 0px; } } @media (min-width: 768px) { .container { max-width: ${md || sm || (xs != Container.defaultProps.xs && xs) || 750}px; padding-left: 0px; padding-right: 0px; } } @media (min-width: 992px) { .container { max-width: ${lg || md || sm || (xs != Container.defaultProps.xs && xs) || 920}px; padding-left: 0px; padding-right: 0px; } } @media (min-width: 1200px) { .container { max-width: ${xl || lg || md || sm || (xs != Container.defaultProps.xs && xs) || 980}px; padding-left: 0px; padding-right: 0px; } } `} </style> {children} </div> ) Container.propTypes = { className: PropTypes.string, children: PropTypes.any, xs: PropTypes.number, // max width on XS sm: PropTypes.number, // ... md: PropTypes.number, lg: PropTypes.number, xl: PropTypes.number } Container.defaultProps = { xs: 560 } export default Container
4fb80d9e6b679679398dd476f1911b948e98917a
{ "blob_id": "4fb80d9e6b679679398dd476f1911b948e98917a", "branch_name": "refs/heads/master", "committer_date": "2023-01-30T08:10:03", "content_id": "acf2f73424423d23a9f9bff30e810213a0f6f70b", "detected_licenses": [ "MIT" ], "directory_id": "80aafed4905b55837ec9dcb77a6de4ac8b5b24af", "extension": "js", "filename": "container.js", "fork_events_count": 9, "gha_created_at": "2018-10-04T03:35:09", "gha_event_created_at": "2022-06-09T17:24:17", "gha_language": "HTML", "gha_license_id": "MIT", "github_id": 151514220, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2138, "license": "MIT", "license_type": "permissive", "path": "/SECTION4-BUILDING-DYNAMIC-FRONTENDS/Video 4.3 - Building an Ethereum application with React/example_build/tic-tac-toe/src/views/partials/container.js", "provenance": "stack-edu-0041.json.gz:360146", "repo_name": "PacktPublishing/Creating-Smart-Contracts-with-Ethereum", "revision_date": "2023-01-30T08:10:03", "revision_id": "b20c1f4e176d259ffadc7d33c52d083fd7d10b4a", "snapshot_id": "aa3199d39a4c575612ea548dfe40a1a6c508d074", "src_encoding": "UTF-8", "star_events_count": 6, "url": "https://raw.githubusercontent.com/PacktPublishing/Creating-Smart-Contracts-with-Ethereum/b20c1f4e176d259ffadc7d33c52d083fd7d10b4a/SECTION4-BUILDING-DYNAMIC-FRONTENDS/Video 4.3 - Building an Ethereum application with React/example_build/tic-tac-toe/src/views/partials/container.js", "visit_date": "2023-02-02T02:41:47.061138", "added": "2024-11-18T21:22:19.723676+00:00", "created": "2023-01-30T08:10:03", "int_score": 2, "score": 2.28125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0059.json.gz" }
let num = [5 ,7 ,8 ,6] num.push(1) num[4] = 10 console.log(`Nosso vetor é o ${num}`) console.log(`O vetor tem ${num.length}`) console.log(`O primeiro valor do vetor é ${num[0]}`) console.log(`Nosso vetor decrescene é ${num.sort()}`) // OREDENA E SÓ DEPOIS CONCATENA let pos = num.indexOf(8) if (pos == -1) { // QUANDO NÃO HÁ O NÚMERO NA SEQUENCIA = -1 console.log('Valor não enontrao.') } else { console.log(`O valor 8 está na posição ${pos}`) }
fe29d7a9703d9148e667f8c00141df4fb6d62df8
{ "blob_id": "fe29d7a9703d9148e667f8c00141df4fb6d62df8", "branch_name": "refs/heads/main", "committer_date": "2021-06-19T14:40:58", "content_id": "a5c773e3601c7de3f5452001885e1e580c3900ad", "detected_licenses": [ "MIT" ], "directory_id": "c568dfa9d93ab643e9379ebd94d4959b86d8271c", "extension": "js", "filename": "ambiente.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 373988288, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 474, "license": "MIT", "license_type": "permissive", "path": "/aula15/ambiente.js", "provenance": "stack-edu-0039.json.gz:245680", "repo_name": "Santos1000/Curso-JS", "revision_date": "2021-06-19T14:40:58", "revision_id": "6f7e9f476068a5dd593732cb8175092cc3b90959", "snapshot_id": "2f4bfd97b68fea23fdf8515e64465684936a8c80", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Santos1000/Curso-JS/6f7e9f476068a5dd593732cb8175092cc3b90959/aula15/ambiente.js", "visit_date": "2023-06-04T14:16:41.591932", "added": "2024-11-19T01:42:53.870895+00:00", "created": "2021-06-19T14:40:58", "int_score": 4, "score": 3.546875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0057.json.gz" }
//! `GET /_matrix/federation/*/event_auth/{roomId}/{eventId}` //! //! Get the complete auth chain for a given event. pub mod v1 { //! `/v1/` ([spec]) //! //! [spec]: https://spec.matrix.org/latest/server-server-api/#get_matrixfederationv1event_authroomideventid use ruma_common::{ api::{request, response, Metadata}, metadata, OwnedEventId, OwnedRoomId, }; use serde_json::value::RawValue as RawJsonValue; const METADATA: Metadata = metadata! { method: GET, rate_limited: false, authentication: ServerSignatures, history: { 1.0 => "/_matrix/federation/v1/event_auth/:room_id/:event_id", } }; /// Request type for the `get_event_authorization` endpoint. #[request] pub struct Request { /// The room ID to get the auth chain for. #[ruma_api(path)] pub room_id: OwnedRoomId, /// The event ID to get the auth chain for. #[ruma_api(path)] pub event_id: OwnedEventId, } /// Response type for the `get_event_authorization` endpoint. #[response] pub struct Response { /// The full set of authorization events that make up the state of the room, /// and their authorization events, recursively. pub auth_chain: Vec<Box<RawJsonValue>>, } impl Request { /// Creates a new `Request` with the given room id and event id. pub fn new(room_id: OwnedRoomId, event_id: OwnedEventId) -> Self { Self { room_id, event_id } } } impl Response { /// Creates a new `Response` with the given auth chain. pub fn new(auth_chain: Vec<Box<RawJsonValue>>) -> Self { Self { auth_chain } } } }
bab8a74fbe0eef59098e536e69ffc27b4fd48b01
{ "blob_id": "bab8a74fbe0eef59098e536e69ffc27b4fd48b01", "branch_name": "refs/heads/main", "committer_date": "2023-08-29T09:19:48", "content_id": "699e2934cbba178c17911114e4753075f8b4fe72", "detected_licenses": [ "MIT" ], "directory_id": "88a885ea656334265dda526b5b5d74089f755c6a", "extension": "rs", "filename": "get_event_authorization.rs", "fork_events_count": 60, "gha_created_at": "2015-11-29T10:59:46", "gha_event_created_at": "2020-04-09T14:53:54", "gha_language": "Rust", "gha_license_id": "MIT", "github_id": 47059992, "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 1761, "license": "MIT", "license_type": "permissive", "path": "/crates/ruma-federation-api/src/authorization/get_event_authorization.rs", "provenance": "stack-edu-0067.json.gz:785173", "repo_name": "ruma/ruma", "revision_date": "2023-08-25T11:23:58", "revision_id": "e4a46437c97cf670aaa9977365caf11300d9ff6e", "snapshot_id": "b457d45663ac0f692305444a9c9f503512d71747", "src_encoding": "UTF-8", "star_events_count": 1199, "url": "https://raw.githubusercontent.com/ruma/ruma/e4a46437c97cf670aaa9977365caf11300d9ff6e/crates/ruma-federation-api/src/authorization/get_event_authorization.rs", "visit_date": "2023-09-03T14:19:12.854588", "added": "2024-11-19T00:33:52.829550+00:00", "created": "2023-08-25T11:23:58", "int_score": 3, "score": 2.5625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0085.json.gz" }
# sshpiper 🖇 ![Go](https://github.com/tg123/sshpiper/workflows/Go/badge.svg) [![Go Report Card](https://goreportcard.com/badge/github.com/tg123/sshpiper)](https://goreportcard.com/report/github.com/tg123/sshpiper) [![Docker Image](https://img.shields.io/docker/pulls/farmer1992/sshpiperd.svg)](https://hub.docker.com/r/farmer1992/sshpiperd) `sshpiper` is the reverse proxy for sshd. all protocols, including ssh, scp, port forwarding, running on top of ssh are supported. *Note:* this is `v1` version, checkout legacy `v0` [here](https://github.com/tg123/sshpiper/tree/v0) ### Overview and Terminology * `downstream`: the client side, typically an ssh client. * `upstream`: the server side, typically an ssh server. * `plugin`: handles the routing from `downstream` to `upstream`. The `plugin` is also responsible for mapping authentication methods to the upstream server. For example, the downstream may use password authentication, but the upstream server may receive public key authentication mapped by `sshpiper`. * `additional challenge`: some `plugins` will not only perform routing but also add additional challenges to SSH authentication for the `upstream` server. Here illustrates the example of `addional challenge` before the `fixed` plugin. ``` sudo ./out/sshpiperd --log-level=trace ./out/simplemath -- ./out/fixed --target <IP_ADDRESS>:5522 ``` ## Plugins ### icons * 🔀: routing plugin * 🔒: addtional challenge plugin Plugin list * [workingdir](plugin/workingdir/) 🔀: `/home`-like directory to managed upstreams routing by sshpiped. * [workingdirbykey](plugin/workingdirbykey/) 🔀: same as `workingdir` but uses public key to route. * [yaml](plugin/yaml/) 🔀: config routing with a single yaml file. * [docker](plugin/docker/) 🔀: pipe into docker containers. * [kubernetes](plugin/kubernetes/) 🔀: manage pipes via Kubernetes CRD. * [totp](plugin/totp/) 🔒: TOTP 2FA plugin. compatible with all [RFC6238](https://datatracker.ietf.org/doc/html/rfc6238) authenticator, for example: `google authenticator`, `azure authenticator`. * [azdevicecode](plugin/azdevicecode/) 🔒: ask user to enter [azure device code](https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-device-code) before login * [fixed](plugin/fixed/) 🔀: fixed targetting the dummy sshd server * [simplemath](plugin/simplemath/) 🔒: ask for very simple math question before login, demo purpose * [githubapp](https://github.com/tg123/sshpiper-gh) 🔀: login ssh with your github account * [restful](https://github.com/11notes/docker-sshpiper) by [@11notes](https://github.com/11notes) 🔀🔒: The rest plugin for sshpiperd is a simple plugin that allows you to use a restful backend for authentication and challenge. * [failtoban](plugin/failtoban/) 🔒: ban ip after failed login attempts ## Screening recording `sshpiperd` support recording the screen in `typescript` format (not the lang). The format is compatible with [scriptreplay(1)](https://linux.die.net/man/1/scriptreplay) To use it, start sshpiperd with `--typescript-log-dir loggingdir` Example: ``` ssh<EMAIL_ADDRESS>-p 2222 ... do some commands exit $ cd loggingdir/user_name $ ls *.timing *.typescript <PHONE_NUMBER>.timing<PHONE_NUMBER>.typescript $ scriptreplay -t<PHONE_NUMBER>.timing<PHONE_NUMBER>.typescript # will replay the ssh session ``` ## Public key authentication when using sshpiper (Private key remapping) During SSH publickey auth, [RFC 4252 Section 7](http://tools.ietf.org/html/rfc4252#section-7), ssh client sign `session_id` and some other data using private key into a signature `sig`. This is for server to verify that the connection is from the client not `the man in the middle`. However, sshpiper actually holds two ssh connection, and it is doing what `the man in the middle` does. the two ssh connections' `session_id` will never be the same, because they are hash of the shared secret. [RFC 4253 Section 7.2](http://tools.ietf.org/html/rfc4253#section-7). To support publickey auth, `sshpiper` routing plugin must provide a new private key for the `upstream` to sign the `session_id`. This new private key is called `mapping key`. How this work ``` +------------+ +------------------------+ | | | | | client | | sshpiper | | PK_X +--------> | | | | | v | | | | Check Permission | +------------+ | | | | | | | | | +----------------+ | v | | | | sign agian | | server | | using PK_Y +--------------> check PK_Y | | | | | | | | | +------------------------+ +----------------+ ``` ## Migrating from `v0` ### What's the major change in `v1` * low level sshpiper api is fully redesigned to support more routing protocols. * plugins system totally redesigned to be more flexible and extensible. * plugins are now sperated from main process and no longer a single big binary, this allow user to write their own plugins without touching `sshpiperd` code. * `grpc` is first class now, the plugins are built on top of it For plugins already in `v1`, you need change params to new params. However, not all plugins are migrated to `v1` yet, they are being migrated gradually. you can still use the old plugins in [`v0` branch](https://github.com/tg123/sshpiper/tree/v0) ## Contributing see [CONTRIBUTING.md](CONTRIBUTING.md) ## License MIT
0263135a2eaa3992596588f62cf2f1487c00d0f1
{ "blob_id": "0263135a2eaa3992596588f62cf2f1487c00d0f1", "branch_name": "refs/heads/master", "committer_date": "2023-08-30T17:44:37", "content_id": "38079dc4e3126641504ccde68e5331a7d76fa1ce", "detected_licenses": [ "MIT" ], "directory_id": "92a53c91f5f9e8c84181e84d78daa564d6c1d679", "extension": "md", "filename": "README.md", "fork_events_count": 136, "gha_created_at": "2014-12-04T18:00:12", "gha_event_created_at": "2023-09-12T21:40:32", "gha_language": "Go", "gha_license_id": "MIT", "github_id": 27552826, "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7864, "license": "MIT", "license_type": "permissive", "path": "/README.md", "provenance": "stack-edu-markdown-0016.json.gz:219472", "repo_name": "tg123/sshpiper", "revision_date": "2023-08-30T17:44:37", "revision_id": "2256c137c890c042f5e86a4eae937ccd8a2f23cb", "snapshot_id": "3b7128d6f547fbaf7f5914094f02fdb26de49941", "src_encoding": "UTF-8", "star_events_count": 820, "url": "https://raw.githubusercontent.com/tg123/sshpiper/2256c137c890c042f5e86a4eae937ccd8a2f23cb/README.md", "visit_date": "2023-08-31T18:16:21.665222", "added": "2024-11-18T23:31:40.408030+00:00", "created": "2023-08-30T17:44:37", "int_score": 4, "score": 3.671875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0016.json.gz" }
using System.Collections; using System.Collections.Generic; using UnityEngine; using IzanagiLibrary; public class ActivateTester : MonoBehaviour { [SerializeField] private GameObject _targetObject; [SerializeField] private ShaderPropertyChanger _changer; [SerializeField] private float _startValue = 0.0f; [SerializeField] private float _goalValue = 2.0f; [SerializeField] private float _duration = 2.0f; [SerializeField] private bool _activeOnAwake = false; private bool _isActivated = false; private void Awake() { _targetObject.SetActive(_activeOnAwake); _isActivated = _activeOnAwake; } private void Update() { // デバッグ用 if (Input.GetKeyDown(KeyCode.A)) { ActivateTest(); } else if (Input.GetKeyDown(KeyCode.D)) { DeactivateTest(); } } [ContextMenu("ActivateTest")] public void ActivateTest() { if (_isActivated) { return; } _targetObject.SetActive(true); _changer.OnFinish = () => { _isActivated = true; }; _changer.ChangeProperty(_startValue, _goalValue, _duration); } [ContextMenu("DeactivateTest")] public void DeactivateTest() { if (!_isActivated) { return; } _changer.OnFinish = () => { _targetObject.SetActive(false); _isActivated = false; }; _changer.ChangeProperty(_goalValue, _startValue, _duration); } }
2c21ca8a73f9d787764f3999d4243842cebf0131
{ "blob_id": "2c21ca8a73f9d787764f3999d4243842cebf0131", "branch_name": "refs/heads/master", "committer_date": "2018-02-09T09:56:39", "content_id": "bd1cb87f6feece0bd5a2af17f32e55fe930381b2", "detected_licenses": [ "MIT" ], "directory_id": "0ddc072ddd2741dcc9c84619261c88a24330336b", "extension": "cs", "filename": "ActivateTester.cs", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 119479853, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1627, "license": "MIT", "license_type": "permissive", "path": "/Assets/Sample/Destruction/Scripts/ActivateTester.cs", "provenance": "stack-edu-0014.json.gz:462267", "repo_name": "GoSato/IzanagiLibrary", "revision_date": "2018-02-09T09:56:39", "revision_id": "80d25fa30842fdf39204e9813e30fee6f9806c98", "snapshot_id": "bcb6a199cb2953a6cb9d1b112f728e65eb3276ef", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/GoSato/IzanagiLibrary/80d25fa30842fdf39204e9813e30fee6f9806c98/Assets/Sample/Destruction/Scripts/ActivateTester.cs", "visit_date": "2021-05-05T00:19:18.398430", "added": "2024-11-18T23:21:02.729653+00:00", "created": "2018-02-09T09:56:39", "int_score": 2, "score": 2.046875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0032.json.gz" }
<?php use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\DB; use App\Http\Controllers\MainController; use App\Http\Controllers\SearchController; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('home'); }); Route::get('/information', function () { return view('information'); }); Route::get('category/{guid}', function ($guid) { return view('category_page')->with(['guid' => $guid]); }); Route::get('product/{guid}', function ($guid) { return view('product_page')->with(['guid' => $guid]); }); Route::get('search', [SearchController::class, 'search'])->name('web.search'); Route::get('/account', function () { return view('login'); }); Route::post('/auth/save', [MainController::class, 'save'])->name('auth.save'); Route::post('/auth/check', [MainController::class, 'check'])->name('auth.check'); Route::get('/auth/logout', [MainController::class, 'logout'])->name('auth.logout'); Route::post('/admin/gestione_categorie/crea_categoria/save', [MainController::class, 'create_category'])->name('admin.create_category'); Route::post('/admin/gestione_categorie/aggiungi_prodotto/save', [MainController::class, 'add_product'])->name('admin.add_product'); Route::post('/admin/modifica_prodotto', [MainController::class, 'modify_product'])->name('admin.modify_product'); //Route::get('/profile/dashboard', [MainController::class, 'dashboard']); Route::group(['middleware' => ['AuthCheck']], function () { Route::get('/auth/login', [MainController::class, 'login'])->name('auth.login'); Route::get('/auth/register', [MainController::class, 'register'])->name('auth.register'); Route::get('/profile/dashboard', [MainController::class, 'dashboard']); Route::get('/profile/personal_data', [MainController::class, 'personal_data']); Route::get('/profile/change_password', [MainController::class, 'change_password']); Route::get('/profile/address', [MainController::class, 'address']); Route::get('/admin/dashboard', [MainController::class, 'admin']); Route::get('/admin/gestione_categorie', [MainController::class, 'gestione_categorie']); Route::get('/admin/gestione_categorie/crea_categoria', [MainController::class, 'crea_categoria']); Route::get('/admin/gestione_categorie/aggiungi_prodotto/{guid}', function ($guid) { return view('admin.gestione_categorie.aggiungi_prodotto')->with(['guid' => $guid]); }); Route::get('/admin/gestione_categorie/{guid}', function ($guid) { return view('admin.gestione_categorie.gestione_prodotti')->with(['guid' => $guid]); }); Route::get('/admin/modifica_prodotto/{guid}', function ($guid) { return view('admin.gestione_categorie.modifica_prodotto')->with(['guid' => $guid]); }); }); Route::get('/example', function () { return 'Hello World!!!'; }); Route::get('/user', function () { return view('user', ['name' => 'Jhon']); }); Route::get('/select', function () { $superior_categories = DB::select('select * from superior_categories where store_id = 1'); foreach ($superior_categories as $superior_category) { echo $superior_category->name . '<br>' . '<img src="' . $superior_category->img . '">'; } });
9295fe4bad9ac37137584895af8fd62fb341c49b
{ "blob_id": "9295fe4bad9ac37137584895af8fd62fb341c49b", "branch_name": "refs/heads/master", "committer_date": "2021-10-12T11:12:42", "content_id": "137df666c54ba466dd634e9d5b1e44d3e2a9705a", "detected_licenses": [ "MIT" ], "directory_id": "a7a4c8ea0d68950a255506fbf1f80abf872ab11c", "extension": "php", "filename": "web.php", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 399472890, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 3585, "license": "MIT", "license_type": "permissive", "path": "/Main_files/routes/web.php", "provenance": "stack-edu-0050.json.gz:441118", "repo_name": "laraxot/theme_leo_adm", "revision_date": "2021-10-12T11:12:42", "revision_id": "17a57ec149d7f9125ae3b2785f65fd0d648b2d23", "snapshot_id": "28cf6015c5a49eaf06d52df9636bf5dcb5970562", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/laraxot/theme_leo_adm/17a57ec149d7f9125ae3b2785f65fd0d648b2d23/Main_files/routes/web.php", "visit_date": "2023-08-22T12:53:11.509876", "added": "2024-11-19T01:34:26.250657+00:00", "created": "2021-10-12T11:12:42", "int_score": 2, "score": 2.15625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0068.json.gz" }
package fr.insee.arc.web.util; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class Session { @Autowired private HttpSession httpSession; public Object get(String attributeName) { return httpSession.getAttribute(attributeName); } public void put(String attributeName, Object attributeValue) { if (httpSession!=null) { httpSession.setAttribute(attributeName, attributeValue); } } public void remove(String attributeName) { httpSession.removeAttribute(attributeName); } public HttpSession getHttpSession() { return httpSession; } public void setHttpSession(HttpSession httpSession) { this.httpSession = httpSession; } }
86e685a78857b3bfa7f2939d51454eea400b3698
{ "blob_id": "86e685a78857b3bfa7f2939d51454eea400b3698", "branch_name": "refs/heads/master", "committer_date": "2023-08-22T07:15:27", "content_id": "5ad4d314635bb923d780e39f5b48b56ba6e10af3", "detected_licenses": [ "MIT" ], "directory_id": "ea8df3c7306a15dcfe74e7faaa1c1b782a76ea83", "extension": "java", "filename": "Session.java", "fork_events_count": 8, "gha_created_at": "2019-05-21T13:12:52", "gha_event_created_at": "2023-04-25T14:45:36", "gha_language": "Java", "gha_license_id": "MIT", "github_id": 187840296, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 783, "license": "MIT", "license_type": "permissive", "path": "/arc-web/src/main/java/fr/insee/arc/web/util/Session.java", "provenance": "stack-edu-0021.json.gz:614144", "repo_name": "InseeFr/ARC", "revision_date": "2023-08-22T07:15:27", "revision_id": "7bfff28d86a6b4e728d1dc0e3872ac15ab8b87aa", "snapshot_id": "0d1569bca2d1b0e26f57a2f7d2847b90b6fe04f6", "src_encoding": "UTF-8", "star_events_count": 13, "url": "https://raw.githubusercontent.com/InseeFr/ARC/7bfff28d86a6b4e728d1dc0e3872ac15ab8b87aa/arc-web/src/main/java/fr/insee/arc/web/util/Session.java", "visit_date": "2023-09-01T00:32:19.872539", "added": "2024-11-18T22:25:38.859337+00:00", "created": "2023-08-22T07:15:27", "int_score": 2, "score": 2.21875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0039.json.gz" }
# # ============LICENSE_START======================================================= # org.onap.aai # ================================================================================ # Copyright © 2017 AT&T Intellectual Property. All rights reserved. # ================================================================================ # 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. # ============LICENSE_END========================================================= # # ECOMP is a trademark and service mark of AT&T Intellectual Property. # # set system related env # and make script compatible both with ubuntu and alpine base images # jre-alpine image has $JAVA_HOME set and added to $PATH # ubuntu image requires to set $JAVA_HOME and add java to $PATH manually if [ -z $JAVA_HOME ] && [ $(grep -i "ID=ubuntu" /etc/os-release | wc -w) -eq 1 ] ; then export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-`dpkg --print-architecture | awk -F- '{ print $NF }'` export PATH=$PATH:${JAVA_HOME}/jre/bin:${JAVA_HOME}/bin fi # set app related env export PROJECT_HOME=/opt/app/aai-traversal export AAIENV=dev export PROJECT_OWNER=aaiadmin export PROJECT_GROUP=aaiadmin export PROJECT_UNIXHOMEROOT=/opt/aaihome export idns_api_url= export idnscred= export idnstenant= umask 0022
4e5b75e5b41c17932b56d952aa92e9d82d1eead8
{ "blob_id": "4e5b75e5b41c17932b56d952aa92e9d82d1eead8", "branch_name": "refs/heads/master", "committer_date": "2023-07-11T14:10:20", "content_id": "8cda4f0eb56f4b1581581ed15b10f23f94d97fc1", "detected_licenses": [ "Apache-2.0" ], "directory_id": "7397916c3499b3ff2c4a6a21a463596e85d2604b", "extension": "sh", "filename": "aai.sh", "fork_events_count": 4, "gha_created_at": "2017-12-21T22:37:34", "gha_event_created_at": "2021-06-29T18:11:52", "gha_language": "Java", "gha_license_id": "NOASSERTION", "github_id": 115053260, "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1768, "license": "Apache-2.0", "license_type": "permissive", "path": "/aai-traversal/src/main/docker/aai.sh", "provenance": "stack-edu-0070.json.gz:195981", "repo_name": "onap/aai-traversal", "revision_date": "2023-07-11T14:10:11", "revision_id": "818806ec5b3810da0599aa0a7538583cdcc0bfca", "snapshot_id": "76eb6f26a4439e64f322e86a76a8a79aea7a929e", "src_encoding": "UTF-8", "star_events_count": 3, "url": "https://raw.githubusercontent.com/onap/aai-traversal/818806ec5b3810da0599aa0a7538583cdcc0bfca/aai-traversal/src/main/docker/aai.sh", "visit_date": "2023-09-01T13:10:47.131922", "added": "2024-11-18T21:33:34.751593+00:00", "created": "2023-07-11T14:10:11", "int_score": 2, "score": 2.453125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0088.json.gz" }
/** * Namespace: yootil.sound * Allows us to play a sound (uses HTML 5 Audio) * * Set access on the audio files, specifically Access-Control-Allow-Origin. * See http://www.w3.org/TR/cors/#access-control-allow-origin-response-hea * for more information about Access-Control. */ yootil.sound = (function(){ return { audio_obj: null, play: function(sound){ if(!this.audio_obj){ this.create_audio_obj(); } if(sound){ this.audio_obj.attr("src", sound); this.audio_obj.get(0).play(); } }, create_audio_obj: function(){ this.audio_obj = $("<audio id='yootil_sound_player' style='display: none'></audio>"); this.audio_obj.appendTo($("body")); } }; })();
86dc72ae24d9adb597de419952d04f44bc2b038e
{ "blob_id": "86dc72ae24d9adb597de419952d04f44bc2b038e", "branch_name": "refs/heads/master", "committer_date": "2014-06-24T22:48:47", "content_id": "32e10fb95c2fc5f0ada281407dd76b35a278f340", "detected_licenses": [ "MIT" ], "directory_id": "52f1d30f9a912bf4ed5cc62e872ae3e57e046374", "extension": "js", "filename": "sound.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 698, "license": "MIT", "license_type": "permissive", "path": "/src/sound.js", "provenance": "stack-edu-0039.json.gz:86208", "repo_name": "protex/ProBoards-Yootil", "revision_date": "2014-06-24T22:48:47", "revision_id": "ef32bfc97820c457b9426d561b47109edeff81fc", "snapshot_id": "4ff2633bf31acbbc4f01bd1a3d20c8c9e316ff2e", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/protex/ProBoards-Yootil/ef32bfc97820c457b9426d561b47109edeff81fc/src/sound.js", "visit_date": "2021-01-16T19:21:03.643619", "added": "2024-11-19T01:42:51.135158+00:00", "created": "2014-06-24T22:48:47", "int_score": 3, "score": 2.609375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0057.json.gz" }
import React, {Component} from 'react'; import { Link } from 'react-router-dom' import Loader from '../components/Loader'; export default class Home extends Component { state = { masjids: [], loading: true }; componentDidMount() { this._fetchMasjids(); } _fetchMasjids = async () => { this.setState({ loading: true }); const response = await axios.get('/masjids'); this.setState({ masjids: response.data, loading: false }); }; render() { if (this.state.loading) { return <Loader/>; } return ( <div> <h1>Masjids</h1> <hr/> { this.state.masjids.map(masjid => <div key={masjid.id}> <p> <Link to={`/masjid/${masjid.id}`}><b style={{ fontSize: 20 }}>{masjid.name}</b></Link> {/*&nbsp;*/} {/*<a*/} {/*onClick={ () => this._deleteMasjid(masjid.id) }*/} {/*title={'delete'}*/} {/*className={'btn text-danger'}>(x)</a>*/} </p> </div> ) } </div> ); } }
1fb5a0acefba0658d3c06794344bdec31711a389
{ "blob_id": "1fb5a0acefba0658d3c06794344bdec31711a389", "branch_name": "refs/heads/master", "committer_date": "2019-01-01T03:46:24", "content_id": "1018a2fc85c70e6b95cf85b606259d67e548f68f", "detected_licenses": [ "MIT" ], "directory_id": "f2c13f70ca85f5b3ee661e4c4f1f9402ab682199", "extension": "js", "filename": "Home.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 152206099, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1128, "license": "MIT", "license_type": "permissive", "path": "/resources/assets/js/views/Home.js", "provenance": "stack-edu-0037.json.gz:186360", "repo_name": "gamingumar/jamat-timings", "revision_date": "2019-01-01T03:46:24", "revision_id": "a4b5ff08026222b598a70c0775fcd2c894b00cac", "snapshot_id": "2705d3fb3b62170c9aede5db59367bfc46f4c7ba", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/gamingumar/jamat-timings/a4b5ff08026222b598a70c0775fcd2c894b00cac/resources/assets/js/views/Home.js", "visit_date": "2020-03-31T12:10:46.365791", "added": "2024-11-18T21:38:04.511293+00:00", "created": "2019-01-01T03:46:24", "int_score": 2, "score": 2.4375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0055.json.gz" }
using System; using System.Text; using System.Linq; namespace SumBigNumbers { public class Program { public static void Main() { string numberOne = Console.ReadLine(); string numberTwo = Console.ReadLine(); StringBuilder result = new StringBuilder(); int savedDigit = 0; int multiply = 0; if (int.Parse(numberTwo) == 0) { Console.WriteLine("0"); } else { for (int i = numberOne.Length - 1; i >= 0; i--) { int digitOne = int.Parse(Convert.ToString(numberOne[i])); int digitTwo = int.Parse(Convert.ToString(numberTwo)); multiply = digitOne * digitTwo; multiply += savedDigit; if ((digitOne * digitTwo) + savedDigit > 9) { result.Append(multiply % 10); } else { result.Append(multiply); } savedDigit = multiply / 10; if (i == 0 && savedDigit > 0) { result.Append(savedDigit); } } Console.WriteLine(new string(result.ToString().TrimEnd('0').ToCharArray().Reverse().ToArray())); } } } }
f4b2976f39e22d6789ff7e4d3a91abfcef4d08b3
{ "blob_id": "f4b2976f39e22d6789ff7e4d3a91abfcef4d08b3", "branch_name": "refs/heads/master", "committer_date": "2018-03-05T14:32:30", "content_id": "874908e899b73a13275e3622567cd83a357dba4c", "detected_licenses": [ "MIT" ], "directory_id": "081f06aaa500552dabfeb83f532438afbe366cd2", "extension": "cs", "filename": "Program.cs", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 123911408, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1487, "license": "MIT", "license_type": "permissive", "path": "/Programming Fundamentals/Program Fundamentals - Strings and Text Processing - Exercises/MultiplyBigNumber/MultiplyBigNumber/Program.cs", "provenance": "stack-edu-0012.json.gz:94193", "repo_name": "valkin88/Technologies-Fundamentals", "revision_date": "2018-03-05T14:32:30", "revision_id": "b29f67a24639091851f5374c6ec3967a1ba6c8d6", "snapshot_id": "bc88c40984f5ba2cadcf215ad267bb01faf77557", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/valkin88/Technologies-Fundamentals/b29f67a24639091851f5374c6ec3967a1ba6c8d6/Programming Fundamentals/Program Fundamentals - Strings and Text Processing - Exercises/MultiplyBigNumber/MultiplyBigNumber/Program.cs", "visit_date": "2021-04-26T22:59:57.856818", "added": "2024-11-18T22:13:18.331588+00:00", "created": "2018-03-05T14:32:30", "int_score": 4, "score": 3.734375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0030.json.gz" }
import * as React from 'react'; import * as ReactDOM from 'react-dom'; class Fourth extends React.Component { constructor(props) { super(props); console.log('constructor: fourth'); } componentWillMount() { console.log('component will mount: fourth'); } componentDidMount() { console.log('component did mount: fourth'); } componentWillUnmount() { console.log('component will unmount: fourth'); } render() { console.log('render: fourth'); return <div> <div>Fourth</div> </div>; } } class Third extends React.PureComponent { constructor(props) { super(props); console.log('constructor: third'); } componentWillMount() { console.log('component will mount: third'); } componentDidMount() { console.log('component did mount: third'); } // shouldComponentUpdate(nextProps, nextState) { // console.log('component should update: third'); // return false; // } render() { console.log('render: third'); return <div> <div>Third. nums: {JSON.stringify(this.props.nums)}</div> </div>; } } class Second extends React.Component { constructor(props) { super(props); console.log('constructor: second'); this.state = { message: '', }; } componentWillMount() { console.log('component will mount: second'); } componentDidMount() { console.log('component did mount: second'); } componentWillReceiveProps(nextProps) { console.log('component will receive props: second'); console.log(nextProps); console.log('calling set state second'); this.setState({ message: 'new counter prop: ' + nextProps.counter, }, () => { console.log('set start second completed'); }); } shouldComponentUpdate() { console.log('component should update: second'); return true; } componentWillUpdate() { console.log('component will update: second'); } render() { console.log('render: second'); return <div> <div>Second, counter: {this.props.counter}</div> <Third nums={this.props.nums} /> </div>; } componentDidUpdate() { console.log('component did update: second'); } } class First extends React.Component { constructor(props) { super(props); console.log('constructor: first'); this.state = { counter: 1, nums: [ 1 ], }; } componentWillMount() { console.log('component will mount: first'); } componentDidMount() { console.log('component did mount: first'); } render() { console.log('render: first'); return <div> <div>First</div> <button type="button" onClick={() => { console.log('calling set state first a'); const originalState = this.state; this.setState({ nums: (this.state.nums.push(this.state.counter), this.state.nums), counter: this.state.counter + 1 }, () => { console.log('set start first a completed'); console.log(originalState === this.state); }); console.log('calling set state first b'); this.setState((lastState) => { console.log('running set state first b'); return { nums: (lastState.nums.push(this.state.counter), lastState.nums), counter: lastState.counter + 1 }; }, () => { console.log('set start first b completed'); }); }}>Increment</button> <Second {...this.state} /> {(this.state.counter < 3) ? <Fourth /> : null} </div>; } } ReactDOM.render( <First />, document.querySelector('main') );
fcdd904314c47a32f5947833bd27587cdd1afc57
{ "blob_id": "fcdd904314c47a32f5947833bd27587cdd1afc57", "branch_name": "refs/heads/master", "committer_date": "2017-11-03T20:58:44", "content_id": "b14a1dcdefc0f2a1964f355718ff44bf1afaaeff", "detected_licenses": [ "MIT" ], "directory_id": "a484013aa2a31c432a1527014cf51e8610270b86", "extension": "js", "filename": "app-set-state.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 105399963, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3708, "license": "MIT", "license_type": "permissive", "path": "/client/js/app-set-state.js", "provenance": "stack-edu-0032.json.gz:489373", "repo_name": "training4developers/react_mobx_10062017", "revision_date": "2017-11-03T20:58:44", "revision_id": "1c22955e4a18dca2936f61c0d310125738e4a449", "snapshot_id": "ae6194c62d4d1c4722fe6d925ce7d86f0bd3da7c", "src_encoding": "UTF-8", "star_events_count": 1, "url": "https://raw.githubusercontent.com/training4developers/react_mobx_10062017/1c22955e4a18dca2936f61c0d310125738e4a449/client/js/app-set-state.js", "visit_date": "2021-07-24T23:36:00.994040", "added": "2024-11-19T01:05:09.928768+00:00", "created": "2017-11-03T20:58:44", "int_score": 3, "score": 2.921875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0050.json.gz" }
/* @flow */ import React from 'react' import PasswordForm from 'components/PasswordForm' import styles from './styles' import contentStyles from 'styles/content.css' type Props = { email: string, name: string, logOutAction: Function, onSubmit: Function } const PasswordReset = ({ email, name, onSubmit }: Props) => { if (!email) return null const displayName = name || email return ( <section className={styles.profile}> <header className={styles.greeting}> <h1 className={contentStyles.header}>Welcome, {displayName}</h1> <h3 className={contentStyles.subheader}>Please provide us with a new password</h3> </header> <section className={styles.myAccount}> <div className={styles.container}> <PasswordForm onSubmit={onSubmit} /> </div> </section> </section> ) } export default PasswordReset
b75a9dee3f9281bacfb189ccee0ff03a494458ed
{ "blob_id": "b75a9dee3f9281bacfb189ccee0ff03a494458ed", "branch_name": "refs/heads/master", "committer_date": "2017-10-09T16:30:17", "content_id": "bdf3cf3ca2bcc1a0751fdd77a908183fd6d08f5e", "detected_licenses": [ "MIT" ], "directory_id": "1464d32598bffc4ca07c4b1f1ee939da1f884f8c", "extension": "js", "filename": "component.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 106305443, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 889, "license": "MIT", "license_type": "permissive", "path": "/universal/components/PasswordResetForm/component.js", "provenance": "stack-edu-0032.json.gz:555516", "repo_name": "riverKanies/CodeRiver", "revision_date": "2017-10-09T16:30:17", "revision_id": "79fdd92371a7f6a2e5133d4e4d827874a39c1b71", "snapshot_id": "90e8716e20a2409ea5cd963c2e86e1a084cbb24c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/riverKanies/CodeRiver/79fdd92371a7f6a2e5133d4e4d827874a39c1b71/universal/components/PasswordResetForm/component.js", "visit_date": "2021-07-11T03:36:25.245758", "added": "2024-11-18T23:38:00.719769+00:00", "created": "2017-10-09T16:30:17", "int_score": 2, "score": 2.25, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0050.json.gz" }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web.Http; using System.Web.ModelBinding; using System.Web.OData; using System.Web.OData.Query; using System.Web.OData.Routing; using _2016ODataInEF.Models; namespace _2016ODataInEF.Controllers { /* The WebApiConfig class may require additional changes to add a route for this controller. Merge these statements into the Register method of the WebApiConfig class as applicable. Note that OData URLs are case sensitive. using System.Web.OData.Builder; using System.Web.OData.Extensions; using _2016ODataInEF.Models; ODataConventionModelBuilder builder = new ODataConventionModelBuilder(); builder.EntitySet<Currency>("Currencies"); builder.EntitySet<CountryRegionCurrency>("CountryRegionCurrencies"); builder.EntitySet<CurrencyRate>("CurrencyRates"); config.MapODataServiceRoute("odata", "odata", builder.GetEdmModel()); */ public class CurrenciesController : ODataController { private Model1 db = new Model1(); // GET: odata/Currencies [EnableQuery] public IQueryable<Currency> GetCurrencies() { return db.Currencies; } // GET: odata/Currencies(5) [EnableQuery] public SingleResult<Currency> GetCurrency([FromODataUri] string key) { return SingleResult.Create(db.Currencies.Where(currency => currency.CurrencyCode == key)); } // PUT: odata/Currencies(5) public async Task<IHttpActionResult> Put([FromODataUri] string key, Delta<Currency> patch) { Validate(patch.GetEntity()); if (!ModelState.IsValid) { return BadRequest(ModelState); } Currency currency = await db.Currencies.FindAsync(key); if (currency == null) { return NotFound(); } patch.Put(currency); try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CurrencyExists(key)) { return NotFound(); } else { throw; } } return Updated(currency); } // POST: odata/Currencies public async Task<IHttpActionResult> Post(Currency currency) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.Currencies.Add(currency); try { await db.SaveChangesAsync(); } catch (DbUpdateException) { if (CurrencyExists(currency.CurrencyCode)) { return Conflict(); } else { throw; } } return Created(currency); } // PATCH: odata/Currencies(5) [AcceptVerbs("PATCH", "MERGE")] public async Task<IHttpActionResult> Patch([FromODataUri] string key, Delta<Currency> patch) { Validate(patch.GetEntity()); if (!ModelState.IsValid) { return BadRequest(ModelState); } Currency currency = await db.Currencies.FindAsync(key); if (currency == null) { return NotFound(); } patch.Patch(currency); try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CurrencyExists(key)) { return NotFound(); } else { throw; } } return Updated(currency); } // DELETE: odata/Currencies(5) public async Task<IHttpActionResult> Delete([FromODataUri] string key) { Currency currency = await db.Currencies.FindAsync(key); if (currency == null) { return NotFound(); } db.Currencies.Remove(currency); await db.SaveChangesAsync(); return StatusCode(HttpStatusCode.NoContent); } // GET: odata/Currencies(5)/CountryRegionCurrencies [EnableQuery] public IQueryable<CountryRegionCurrency> GetCountryRegionCurrencies([FromODataUri] string key) { return db.Currencies.Where(m => m.CurrencyCode == key).SelectMany(m => m.CountryRegionCurrencies); } // GET: odata/Currencies(5)/CurrencyRates [EnableQuery] public IQueryable<CurrencyRate> GetCurrencyRates([FromODataUri] string key) { return db.Currencies.Where(m => m.CurrencyCode == key).SelectMany(m => m.CurrencyRates); } // GET: odata/Currencies(5)/CurrencyRates1 [EnableQuery] public IQueryable<CurrencyRate> GetCurrencyRates1([FromODataUri] string key) { return db.Currencies.Where(m => m.CurrencyCode == key).SelectMany(m => m.CurrencyRates1); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } private bool CurrencyExists(string key) { return db.Currencies.Count(e => e.CurrencyCode == key) > 0; } } }
3550f5e4e1a545ce3aa2df0d7d6ee3380abad4c6
{ "blob_id": "3550f5e4e1a545ce3aa2df0d7d6ee3380abad4c6", "branch_name": "refs/heads/master", "committer_date": "2016-05-26T09:41:59", "content_id": "98ea19c00f9f33a27b55d888910d76540806460b", "detected_licenses": [ "MIT" ], "directory_id": "47eea607f69a8fd50f414c479d6ae451c4e355ba", "extension": "cs", "filename": "CurrenciesController.cs", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 58820280, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 5878, "license": "MIT", "license_type": "permissive", "path": "/05OData/2016ODataInEF/2016ODataInEF/Controllers/CurrenciesController.cs", "provenance": "stack-edu-0009.json.gz:680311", "repo_name": "tkopacz/2016SQLDay", "revision_date": "2016-05-26T09:41:59", "revision_id": "b93985bd1780bf33b1857c017732f6c951c8b6ac", "snapshot_id": "e184479d6e3a7b4f54cf077b072045a0437c4729", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/tkopacz/2016SQLDay/b93985bd1780bf33b1857c017732f6c951c8b6ac/05OData/2016ODataInEF/2016ODataInEF/Controllers/CurrenciesController.cs", "visit_date": "2016-09-13T21:16:09.858097", "added": "2024-11-18T23:50:45.558210+00:00", "created": "2016-05-26T09:41:59", "int_score": 2, "score": 2.28125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0027.json.gz" }
using ContactManager.Models; using System; using System.IO; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; namespace ContactManager.Formatters { public class ContactPngFormatter : BufferedMediaTypeFormatter { public ContactPngFormatter() { this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("image/png")); } public override void WriteToStream(Type type, object value, Stream stream, HttpContent content) { var contact = value as Contact; if (contact != null) { var imageId = contact.ContactId % 8; if (imageId == 0) { imageId++; } var path = string.Format(@"Images\Image{0}.png", imageId); path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path); using (var fileStream = new FileStream(path, FileMode.Open)) { byte[] bytes = new byte[fileStream.Length]; fileStream.Read(bytes, 0, (int)fileStream.Length); stream.Write(bytes, 0, (int)fileStream.Length); } } } public override bool CanReadType(Type type) { return false; } public override bool CanWriteType(Type type) { return typeof(Contact).Equals(type); } } }
bcb501da5515a408ebafa6c182604d1d3ae570d8
{ "blob_id": "bcb501da5515a408ebafa6c182604d1d3ae570d8", "branch_name": "refs/heads/master", "committer_date": "2020-10-29T18:43:37", "content_id": "b08c7e0fe5dd7720d5e0a10be5135dc95b5a5dcc", "detected_licenses": [ "MIT" ], "directory_id": "4699d5949b789bcbc8d98cac051d41b78f883b39", "extension": "cs", "filename": "ContactPngFormatter.cs", "fork_events_count": 6, "gha_created_at": "2012-07-27T13:20:52", "gha_event_created_at": "2023-06-22T01:55:47", "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 5204749, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1488, "license": "MIT", "license_type": "permissive", "path": "/ASP.NET MVC Web API/ContactManager/ContactManager/Formatters/ContactPngFormatter.cs", "provenance": "stack-edu-0012.json.gz:632600", "repo_name": "rfinochi/confsamples", "revision_date": "2020-10-29T18:43:37", "revision_id": "24e71d24ab3aa26ba974636fb79e1ce51cae52c2", "snapshot_id": "a953c33b746768ab605cdc457bf3ef6fb3bec2a9", "src_encoding": "UTF-8", "star_events_count": 4, "url": "https://raw.githubusercontent.com/rfinochi/confsamples/24e71d24ab3aa26ba974636fb79e1ce51cae52c2/ASP.NET MVC Web API/ContactManager/ContactManager/Formatters/ContactPngFormatter.cs", "visit_date": "2023-07-06T03:25:35.570106", "added": "2024-11-18T22:00:28.240445+00:00", "created": "2020-10-29T18:43:37", "int_score": 3, "score": 2.96875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0030.json.gz" }
import React, { Component } from 'react'; import { LocaleProvider } from 'antd'; import zh_CN from 'antd/lib/locale-provider/zh_CN'; const getDisplayName = WrappedComponent => WrappedComponent.displayName || WrappedComponent.name || 'Component'; // decorator export default (opts = {}) => WrappedComponent => { return class extends Component { constructor() { super(); this.displayName = `CreateLanguage${getDisplayName(WrappedComponent)}`; } render() { opts = { locale: zh_CN, ...opts }; return ( <LocaleProvider {...opts}> <WrappedComponent {...this.props} ref="WrappedComponent" /> </LocaleProvider> ); } }; };
451a1f255c994113c8d1370913a3aad1ad3793ab
{ "blob_id": "451a1f255c994113c8d1370913a3aad1ad3793ab", "branch_name": "refs/heads/master", "committer_date": "2018-12-23T08:23:35", "content_id": "22e70b6ae2385d5c3d7a899d6c17111799655800", "detected_licenses": [ "MIT" ], "directory_id": "1279bc5c80f99af42ba4feacd02e40957c8e6736", "extension": "js", "filename": "index.js", "fork_events_count": 7, "gha_created_at": "2017-12-12T06:17:23", "gha_event_created_at": "2018-03-14T09:07:18", "gha_language": "JavaScript", "gha_license_id": "MIT", "github_id": 113951294, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 653, "license": "MIT", "license_type": "permissive", "path": "/src/web/create-language/index.js", "provenance": "stack-edu-0033.json.gz:665150", "repo_name": "wya-team/wya-rc", "revision_date": "2018-12-23T08:23:35", "revision_id": "d150bd6fc16f8e5794b5bc7ca685558e71d808bf", "snapshot_id": "8a4580a1bbd65b7d7e11838ef2b99c1dc84bd7b4", "src_encoding": "UTF-8", "star_events_count": 15, "url": "https://raw.githubusercontent.com/wya-team/wya-rc/d150bd6fc16f8e5794b5bc7ca685558e71d808bf/src/web/create-language/index.js", "visit_date": "2021-05-06T07:19:45.643269", "added": "2024-11-19T01:15:58.393639+00:00", "created": "2018-12-23T08:23:35", "int_score": 2, "score": 2.203125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0051.json.gz" }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class SwordStand : BaseInteraction { public GameObject Sword; public BaseWeapon TargetWeapon; public UnityEvent<BaseWeapon> OnPickedUp; public override void Interact() { if (!Sword.activeSelf) { return; } Sword.SetActive(false); OnPickedUp.Invoke(TargetWeapon); } }
08f613bcbf8bb6fbcd5deebba01b4269ae667d53
{ "blob_id": "08f613bcbf8bb6fbcd5deebba01b4269ae667d53", "branch_name": "refs/heads/main", "committer_date": "2021-09-02T23:24:34", "content_id": "d4f44d6a8fbadf5c71b94cec3aa2802e5592b2de", "detected_licenses": [ "MIT" ], "directory_id": "3d032b050c29c7521a6a5f22bc700ea8f00606ae", "extension": "cs", "filename": "SwordStand.cs", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 399917483, "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 459, "license": "MIT", "license_type": "permissive", "path": "/Assets/Scripts/Interactions/SwordStand.cs", "provenance": "stack-edu-0010.json.gz:693794", "repo_name": "GameJamForoya/AudioWorkshop2021", "revision_date": "2021-09-02T23:24:34", "revision_id": "633d846faf25a8d261cb2f341599a9b4403642b6", "snapshot_id": "232c5c153db518eca3a47a140c388ac3f0478a06", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/GameJamForoya/AudioWorkshop2021/633d846faf25a8d261cb2f341599a9b4403642b6/Assets/Scripts/Interactions/SwordStand.cs", "visit_date": "2023-07-14T09:56:54.174263", "added": "2024-11-19T00:51:35.904087+00:00", "created": "2021-09-02T23:24:34", "int_score": 2, "score": 2.28125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0028.json.gz" }
package com.izymes; public class BuildResultElement implements ConditionElement { final boolean result; public BuildResultElement() { this(false); } public BuildResultElement(boolean result) { this.result = result; } @Override public int accept(ConditionVisitor visitor) { return visitor.visit(this); } }
8631a77fdc37b0ed1b7b6b08b30ebd79a02a3cf3
{ "blob_id": "8631a77fdc37b0ed1b7b6b08b30ebd79a02a3cf3", "branch_name": "refs/heads/master", "committer_date": "2015-05-04T00:43:36", "content_id": "4f29590baa3aa960e2adf0180fb16df1dc1ebef0", "detected_licenses": [ "Apache-2.0" ], "directory_id": "966ac52a0bf37eae39d62a5481dfc38f9c2afef2", "extension": "java", "filename": "BuildResultElement.java", "fork_events_count": 0, "gha_created_at": "2015-02-18T00:20:07", "gha_event_created_at": "2015-05-04T00:43:37", "gha_language": "Java", "gha_license_id": null, "github_id": 30945126, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 366, "license": "Apache-2.0", "license_type": "permissive", "path": "/src/main/java/com/izymes/BuildResultElement.java", "provenance": "stack-edu-0023.json.gz:441955", "repo_name": "ukuhnhardt/visitor-pattern", "revision_date": "2015-05-04T00:43:36", "revision_id": "ef2f293e32b84ec6002aacc0c702874d90e74425", "snapshot_id": "1e73944084716693f20ed5c9afff2e4422b7c60b", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/ukuhnhardt/visitor-pattern/ef2f293e32b84ec6002aacc0c702874d90e74425/src/main/java/com/izymes/BuildResultElement.java", "visit_date": "2021-01-23T17:19:37.583485", "added": "2024-11-18T22:52:24.136014+00:00", "created": "2015-05-04T00:43:36", "int_score": 2, "score": 2.5, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0041.json.gz" }
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { environment } from '@environments/environment'; import { User } from '@app/_models'; import { BaseService } from './base.service'; import { UserModel } from '../_models/users-model-data'; import { BehaviorSubject, Observable } from 'rxjs'; import { BlockUI, NgBlockUI } from 'ng-block-ui'; import { map } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class UserService extends BaseService { @BlockUI() blockUI: NgBlockUI; private ProfileSubject: BehaviorSubject<any>; public Profile: Observable<any>; constructor(private http: HttpClient) { super(); this.setController('Users'); this.ProfileSubject = new BehaviorSubject<any>(JSON.parse(localStorage.getItem('Profile'))); this.Profile = this.ProfileSubject.asObservable(); } public get ProfileValue(): any { return this.ProfileSubject.value; } getAll() { return this.http.get<User[]>(`${environment.apiUrl}/users`); } AddUser(User: any) { return this.http.post<any>(`${this.endPoint('Add')}`, User) .pipe(map(User => { return User; })); } public getUsers = () => this.http.get<UserModel[]>(this.endPoint()); public getProfile = () => this.http.get(this.endPoint('Profile')); setProfile() { /*if(!localStorage.getItem('Profile')){ this.BloackUIStart('Loading Profile'); this.getProfile().subscribe(res => { localStorage.setItem('Profile', JSON.stringify(res)); this.ProfileSubject.next(res); this.BloackUIStop(); }); }*/ } setNull(){ this.ProfileSubject.next(null); } getStates() { return this.ProfileValue; } BloackUIStart(message?: string) { this.blockUI.start(message); } BloackUIStop(time:number = 0) { setTimeout(() => { this.blockUI.stop(); }, time); } }
bfac0bd092b4334a173716fd90d89c1720f06f22
{ "blob_id": "bfac0bd092b4334a173716fd90d89c1720f06f22", "branch_name": "refs/heads/master", "committer_date": "2021-07-13T23:25:46", "content_id": "d77ffbc09a87407f8b0d613f9b231e70344808cf", "detected_licenses": [ "MIT" ], "directory_id": "30f1b9e0f6c03ccd0acf1a234079005a8e3a924e", "extension": "ts", "filename": "user.service.ts", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 385733855, "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1952, "license": "MIT", "license_type": "permissive", "path": "/Avian.Web/ClientApp/src/app/_services/user.service.ts", "provenance": "stack-edu-0074.json.gz:129152", "repo_name": "JoseVenancioQH/Avian_", "revision_date": "2021-07-13T23:25:46", "revision_id": "ec2621150819dcbff9080d503ec45fb14720f2ef", "snapshot_id": "b6c9e0be25ec67554a90bfe50341b829a03c4e53", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/JoseVenancioQH/Avian_/ec2621150819dcbff9080d503ec45fb14720f2ef/Avian.Web/ClientApp/src/app/_services/user.service.ts", "visit_date": "2023-06-13T00:31:29.429254", "added": "2024-11-19T02:11:11.796914+00:00", "created": "2021-07-13T23:25:46", "int_score": 2, "score": 2.09375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0092.json.gz" }
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Locale; import java.util.Scanner; public class CalendarAndDays { public static void main(String[] args) throws ParseException { // создаётся объект класса SimpleDateFormat, задающий формат вывода даты в виде дни дополненные нулями, // месяцы, дополненные нулями и год из 4 цифр. SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd.MM.yyyy"); System.out.println("Введите дату рождения в формате dd.MM.yyyy: "); // создаётся экземпляр класса Calendar с использованием текущего часового пояса и локализации. Calendar dr = Calendar.getInstance(); // устанавливается время по формату из введенной строки // (не знал, что так можно писать (new Scanner(System.in).nextLine()))) dr.setTime(simpleDateFormat.parse(new Scanner(System.in).nextLine())); //видимо создается второй объект для сравнения с первым и ему задается тоже самое. // Не понятно только почему локализация здесь есть, а там нет. Calendar now = Calendar.getInstance(); simpleDateFormat = new SimpleDateFormat("dd.MM.yyyy - EEEE", new Locale("ru")); //в цикле выводится то, что требуется for (int i = 0; dr.before(now); i++) { //simpleDateFormat.format(dr.getTime())); в жизни бы не додумался и до сих пор не уяснил логику // Я понимаю, что здесь написано, но повторить не смогу. Поскольку в голове каша от этого синтаксиса // данного класса. System.out.println("Возраст: " + i + " Дата: " + simpleDateFormat.format(dr.getTime())); //добавляет или вычитает указанное количество времени // к данному календарному полю (в данном случае ГОД) видимо потому что нельзя написать переменная++. // Мне в основном было не понятно как здесь применить цикл, чтобы условие продолжения цикла // изменялось и в конце концов закончилось. Поэтому смысл применения метода before я не мог понять. // Теперь ясно. dr.add(Calendar.YEAR, 1); } } }
90fc1819dff3a6559719e6ccf8045a3f54091b25
{ "blob_id": "90fc1819dff3a6559719e6ccf8045a3f54091b25", "branch_name": "refs/heads/main", "committer_date": "2021-03-24T06:38:54", "content_id": "fa0cef7f7d00fb4989f40126b20686cb28ea12c6", "detected_licenses": [ "Unlicense" ], "directory_id": "b534b89582ad738e1aff3c98763dee0d3ca6c574", "extension": "java", "filename": "CalendarAndDays.java", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 314155545, "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3050, "license": "Unlicense", "license_type": "permissive", "path": "/04_NumbersStringsAndDates/CalendarAndDates/src/CalendarAndDays.java", "provenance": "stack-edu-0020.json.gz:304222", "repo_name": "AlexOblizin/Repo.Homework", "revision_date": "2021-03-24T06:38:54", "revision_id": "b5bc745084ae68d2d466b9f576747c507bc30d84", "snapshot_id": "5500a6b5fadc44b357f73308f00b7b0869420695", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/AlexOblizin/Repo.Homework/b5bc745084ae68d2d466b9f576747c507bc30d84/04_NumbersStringsAndDates/CalendarAndDates/src/CalendarAndDays.java", "visit_date": "2023-03-26T04:08:14.498299", "added": "2024-11-18T23:17:13.413381+00:00", "created": "2021-03-24T06:38:54", "int_score": 3, "score": 2.96875, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0038.json.gz" }
import endpoints from '../objects/endpoints' import config from '../config/default.js' const merge = require('deepmerge') /** * User Vuex component */ export default { state: { user: { }, users: [], lastLoad: { users: { time: null, interval: 5 } } }, mutations: { /** * Metodo adaptado p/ setar a resposta da API * @param {object} state * @param {object} data */ SET_AUTH_USER(state, data) { state.user = { created_at: data.created_at, email: data.email, id: data.id, name: data.name, updated_at: data.updated_at, oauth: data.oauth } window.axios.defaults.headers.common['Authorization'] = 'Bearer ' + data.oauth.access_token }, /** * * @param {*} state * @param {*} permissions */ SET_USER_PERMISSIONS(state, permissions) { state.user.permissions = permissions }, /** * Seta o @var state.users * * @param {object} state * @param {object} users */ SET_USERS(state, users) { state.users = users } }, actions: { /** * Executa o login e define os valores do @var state.user * @param {object} commit Objecto passado pela action * @param {object} user Objeto user {email: '[email protected]', password: 'userdogname'} */ login ({ commit }, user) { let oauth = config.oauth_client let endpoint = 'api.oauth.token' return axios.post(endpoints.get({endpoint}), merge(oauth, user)) .then(res => { if(res.status === 200) { commit('SET_AUTH_USER', res.data) let endpoint = 'api.permissions.list' axios.get(endpoints.get({endpoint})).then(res => { if(res.status === 200) { commit('SET_USER_PERMISSIONS', res.data) } }) } return res }) .catch(err => { return err.response }) }, /** * Verifica se o login ainda está ativo * * @param {*} param0 */ verify({commit}) { let endpoint = 'api.oauth.ping' return axios.get(endpoints.get({endpoint})) .catch(err => { commit('CLEAR_STATE') throw err.response }) }, /** * Carrega uma lista de usuarios * @param {object} param0 * @param {boolean} force */ loadUsers({commit, getters}, force) { if(getters.hasLoaded('address', force)) { return } let endpoint = 'api.users.index' return axios.get(endpoints.get({endpoint})) .then(res => { commit('SET_USERS', res.data) commit('SET_LAST_LOAD', 'users') return res.data }) .catch(err => { throw err.response }) }, /** * Cria um novo usuário * * @param {void} param0 * @param {object} user */ createUser({}, user) { let endpoint = 'api.users.create' return axios.post(endpoints.get({endpoint}), user) .then(res => { return res }) .catch(err => { throw err.response }) }, /** * Altera a senha do usuário * * @param {void} param0 * @param {object} passwords */ changeUserPassword({}, passwords) { let endpoint = 'api.users.change_password' return axios.put(endpoints.get({endpoint}), passwords) .then(res => { return res }) .catch(err => { throw err.response }) }, /** * Atualiza um usuário * @param {void} param0 * @param {object} user */ updateUser({}, user) { let endpoint = 'api.users.update' let params = {id: user.id} return axios.put(endpoints.get({endpoint, params}), user) .then(res => { return res }) .catch(err => { throw err.response }) }, /** * Envia um email de confimação ao novo usuário * @param {void} param0 * @param {number} userID */ sendCreatedEmail({}, userID) { let endpoint = 'api.user.send_created_email' let params = {id: userID} return axios.get(endpoints.get({endpoint, params})) .then(res => { return res }) .catch(err => { throw err.response }) }, /** * Deleta um usuário * @param {void} param0 * @param {number} id */ deleteUser({}, id) { let endpoint = 'api.users.delete' let params = {id: id} return axios.delete(endpoints.get({endpoint, params})) .then(res => { return res }) .catch(err => { throw err.response }) } }, getters: { user: store => store.user, userByID: store => { return id => store.users.filter(the => the.id == id)[0] } } }
87aad87dd7953b0396905df5c510c05058df4c18
{ "blob_id": "87aad87dd7953b0396905df5c510c05058df4c18", "branch_name": "refs/heads/main", "committer_date": "2021-06-08T17:04:22", "content_id": "7d6f371b31532fe34344bdd981d728882fa61e1b", "detected_licenses": [ "MIT" ], "directory_id": "c985644f61a91818811af5fb86ef48beabfcce28", "extension": "js", "filename": "users.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 6117, "license": "MIT", "license_type": "permissive", "path": "/resources/assets/js/store/users.js", "provenance": "stack-edu-0042.json.gz:295412", "repo_name": "gzorzo/norde", "revision_date": "2021-06-08T17:04:22", "revision_id": "21ba99f35d7c01d8914f98d886be7eade22a7b59", "snapshot_id": "ca292176945b6478c1f7a051fd3043df9dd85601", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/gzorzo/norde/21ba99f35d7c01d8914f98d886be7eade22a7b59/resources/assets/js/store/users.js", "visit_date": "2023-05-28T19:04:08.041211", "added": "2024-11-19T00:01:18.424744+00:00", "created": "2021-06-08T17:04:22", "int_score": 2, "score": 2.4375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0060.json.gz" }
#pragma once #include <Matrix.hpp> namespace ace { namespace math { using namespace mv; using Matrix4 = Mat<4u, 4u, float>; static const Matrix4 s_identity4 = MakeIdentity<4u, float>(); static Matrix4 RotateZ4(float deg) { return MakeRotation<4u>(ToRad(deg), AXIS::Z); } } }
d3716b74aa62281c603dcaccd5a66ac6be615413
{ "blob_id": "d3716b74aa62281c603dcaccd5a66ac6be615413", "branch_name": "refs/heads/master", "committer_date": "2017-12-13T14:52:43", "content_id": "77274d86b6b5310806b785c9c0b844f87552f37e", "detected_licenses": [ "BSD-2-Clause" ], "directory_id": "b904609b155658101b37aac0a13187c005e61082", "extension": "h", "filename": "Matrix4.h", "fork_events_count": 1, "gha_created_at": "2017-09-11T06:20:59", "gha_event_created_at": "2017-09-29T10:24:30", "gha_language": "C++", "gha_license_id": null, "github_id": 103097573, "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 296, "license": "BSD-2-Clause", "license_type": "permissive", "path": "/include/Ace/Matrix4.h", "provenance": "stack-edu-0005.json.gz:430205", "repo_name": "Acerba/Acerba", "revision_date": "2017-12-13T14:52:43", "revision_id": "8f4489812f837202b8c3a5bf82c937b8388dee4a", "snapshot_id": "7d1313b0e7faf6e950d7913aa5ff9576b4950d6d", "src_encoding": "UTF-8", "star_events_count": 5, "url": "https://raw.githubusercontent.com/Acerba/Acerba/8f4489812f837202b8c3a5bf82c937b8388dee4a/include/Ace/Matrix4.h", "visit_date": "2021-08-29T08:27:17.420500", "added": "2024-11-18T20:39:56.104834+00:00", "created": "2017-12-13T14:52:43", "int_score": 2, "score": 2.03125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0023.json.gz" }
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class GroupService { private url = "https://e-xam.herokuapp.com/"; constructor( private http:HttpClient ) { } getGroups(){ let id = localStorage.getItem('token') return this.http.get(this.url+"teacher/groups/"+id) } deleteMessage(groupName, _id){ return this.http.delete(this.url+"teacher/chat/"+groupName+"/"+_id) } }
8d268ebbdbd62a658325d9deec50946b5ddb2626
{ "blob_id": "8d268ebbdbd62a658325d9deec50946b5ddb2626", "branch_name": "refs/heads/master", "committer_date": "2020-10-28T11:40:21", "content_id": "725f9b58fe427534b27646fbb5ac2da65ddabc34", "detected_licenses": [ "MIT" ], "directory_id": "5c92f0c388a9dd540a12441c56637485cc5ce696", "extension": "ts", "filename": "group.service.ts", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 242767982, "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 493, "license": "MIT", "license_type": "permissive", "path": "/src/app/services/teacher-services/group.service.ts", "provenance": "stack-edu-0074.json.gz:809147", "repo_name": "talalanjum/e-xam", "revision_date": "2020-10-28T11:40:21", "revision_id": "619f7ccc42d2092135659644c6c93a6d694590c0", "snapshot_id": "995656362c7a4eb7201901e76979ad822a0eaed2", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/talalanjum/e-xam/619f7ccc42d2092135659644c6c93a6d694590c0/src/app/services/teacher-services/group.service.ts", "visit_date": "2023-01-02T10:01:01.506510", "added": "2024-11-18T22:21:35.728547+00:00", "created": "2020-10-28T11:40:21", "int_score": 2, "score": 2.140625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0092.json.gz" }
<?php namespace vAMSYS\Http\ViewComposers; use Illuminate\Contracts\View\View; use Illuminate\Support\Facades\Request; use Illuminate\Support\Facades\Session; use vAMSYS\Airline; use vAMSYS\Repositories\PilotRepository; use vAMSYS\Repositories\UserRepository; class GlobalComposer { /** * Bind data to the view. * * @param View $view * @return void */ public function compose(View $view) { // Are we connecting from a known URL? if($airline = Airline::where('url', '=', Request::getHttpHost())->first()) Session::put('airlineId', $airline->id); if (Session::has('airlineId')) $view->with('airline', Airline::find(Session::get('airlineId'))); if (Request::user()) { $view->with('user', Request::user()); $view->with('pilot', PilotRepository::getCurrentPilot()); $airline = Airline::find(Session::get('airlineId')); $view->with('airlineStaff', UserRepository::hasRole($airline->prefix.'-staff', Request::user())); } } }
e23ed14e139554a31b9132bd6a9aac3b1255a1b8
{ "blob_id": "e23ed14e139554a31b9132bd6a9aac3b1255a1b8", "branch_name": "refs/heads/master", "committer_date": "2015-08-31T18:10:33", "content_id": "88897ee84dbd4086b8273863c3ff844178d08a62", "detected_licenses": [ "MIT" ], "directory_id": "4cb2f1afbcccf06237d3b014eca1b2b78f9367c1", "extension": "php", "filename": "GlobalComposer.php", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": null, "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1005, "license": "MIT", "license_type": "permissive", "path": "/app/Http/ViewComposers/GlobalComposer.php", "provenance": "stack-edu-0050.json.gz:725133", "repo_name": "CocoMC98000/vAMSYS", "revision_date": "2015-08-31T18:10:33", "revision_id": "f06ee8faad348a8405a1de8fcf6f4870738a7aa3", "snapshot_id": "4707d62fad78d8b70b8c8fa966ded264cc0a4d52", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/CocoMC98000/vAMSYS/f06ee8faad348a8405a1de8fcf6f4870738a7aa3/app/Http/ViewComposers/GlobalComposer.php", "visit_date": "2020-09-14T03:12:56.532528", "added": "2024-11-18T21:32:39.398357+00:00", "created": "2015-08-31T18:10:33", "int_score": 3, "score": 2.609375, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0068.json.gz" }
import { Component, OnInit } from '@angular/core'; import { ElectronService } from '../core/services/electron/electron.service'; import { Router } from '@angular/router' @Component({ selector: 'app-update', templateUrl: './update.component.html', styleUrls: ['./update.component.css'] }) export class UpdateComponent implements OnInit { private ipc: any; public downloadPercent: number; constructor(private router: Router, private electron: ElectronService) { this.ipc = electron.ipcRenderer; } ngOnInit(): void { this.ipc.on('renderer-update-service', (value: number) => { this.downloadPercent = value; }); } }
25230969fc2cdd92f87383dc2a566efee5d88392
{ "blob_id": "25230969fc2cdd92f87383dc2a566efee5d88392", "branch_name": "refs/heads/master", "committer_date": "2020-07-28T20:21:20", "content_id": "9fe98f951ea20b52081d8af95c883c97e4b6529b", "detected_licenses": [ "MIT", "Apache-2.0" ], "directory_id": "b963219795d94a56929be0da092097c0cb18fb62", "extension": "ts", "filename": "update.component.ts", "fork_events_count": 1, "gha_created_at": "2020-07-28T20:03:03", "gha_event_created_at": "2020-10-06T15:46:01", "gha_language": "TypeScript", "gha_license_id": "MIT", "github_id": 283315272, "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 668, "license": "MIT,Apache-2.0", "license_type": "permissive", "path": "/src/app/update/update.component.ts", "provenance": "stack-edu-0072.json.gz:323471", "repo_name": "mindmorass/electron-base", "revision_date": "2020-07-28T20:21:20", "revision_id": "648a585c3e1a7f00d6268088c8beabfac4ae866b", "snapshot_id": "226f8d452da8e2b01d12bfe6c28f4fbd530d89b0", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/mindmorass/electron-base/648a585c3e1a7f00d6268088c8beabfac4ae866b/src/app/update/update.component.ts", "visit_date": "2022-12-20T14:45:56.048444", "added": "2024-11-18T23:28:00.485302+00:00", "created": "2020-07-28T20:21:20", "int_score": 2, "score": 2.125, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0090.json.gz" }
/* eslint no-return-assign: "off", eqeqeq: "off" */ 'use strict'; /** * A simple event storage implementation intended to use for tests only. * Storage content resets on each app restart. */ module.exports = class InMemoryEventStorage { constructor() { this.nextId = 0; this._events = Promise.resolve([]); } commitEvents(events) { return this._events = this._events.then(data => data.concat(events)); } getAggregateEvents(aggregateId) { return this._events.then(events => events.filter(e => e.aggregateId == aggregateId)); } getSagaEvents(sagaId) { return this._events.then(events => events.filter(e => e.sagaId == sagaId)); } getEvents(eventTypes) { if (!eventTypes) return this._events; return this._events.then(events => events.filter(e => eventTypes.indexOf(e.type) !== -1)); } getNewId() { this.nextId += 1; return this.nextId; } };
6347dff0669763147b0543e4f495e4a4c696b28c
{ "blob_id": "6347dff0669763147b0543e4f495e4a4c696b28c", "branch_name": "refs/heads/master", "committer_date": "2016-12-05T18:25:55", "content_id": "f293bd9956d65c336632dea3d4deebe49778632e", "detected_licenses": [ "MIT" ], "directory_id": "209611d568db456dc0e556fc549bac0499d91ea4", "extension": "js", "filename": "InMemoryEventStorage.js", "fork_events_count": 0, "gha_created_at": null, "gha_event_created_at": null, "gha_language": null, "gha_license_id": null, "github_id": 120936080, "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 894, "license": "MIT", "license_type": "permissive", "path": "/src/infrastructure/InMemoryEventStorage.js", "provenance": "stack-edu-0035.json.gz:261788", "repo_name": "Apination/node-cqrs", "revision_date": "2016-12-05T18:25:55", "revision_id": "6dab4497bd99f196296de4b681a5c137bd0df407", "snapshot_id": "c7f40301595ee6f8db14216023abd9a3ad6f962c", "src_encoding": "UTF-8", "star_events_count": 0, "url": "https://raw.githubusercontent.com/Apination/node-cqrs/6dab4497bd99f196296de4b681a5c137bd0df407/src/infrastructure/InMemoryEventStorage.js", "visit_date": "2021-05-02T00:04:06.656636", "added": "2024-11-18T17:56:10.883216+00:00", "created": "2016-12-05T18:25:55", "int_score": 3, "score": 2.640625, "source": "stackv2", "file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0053.json.gz" }