language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
TypeScript
UTF-8
1,335
2.65625
3
[ "Apache-2.0" ]
permissive
import {CookieSerializeOptions, serialize} from "cookie"; import Hash from "../facades/Hash"; import {NGNApiResponse} from "../types/NGNApiResponse"; import {NextHandler} from "../types/NextHandler"; import {Middleware} from "../types/Middleware"; import {NextApiRequest} from "../types/NextApiRequest"; import {NextApiResponse} from "../types/NextApiResponse"; import EnvKeyIsNotSetError from "../errors/EnvKeyIsNotSetError"; const setCookie = (res: NextApiResponse) => (name: string, value: string, options: CookieSerializeOptions = {}) => { options.secure = process.env.NODE_ENV === 'production'; const prefix: string | undefined = process.env.COOKIE_PREFIX; if(typeof prefix === "undefined") throw new EnvKeyIsNotSetError("COOKIE_PREFIX env variable is not set"); if ('maxAge' in options && options.maxAge != null) { options.expires = new Date(Date.now() + options.maxAge) options.maxAge /= 1000 } const encryptedValue: string = Hash.base64Encode(JSON.stringify(Hash.AESEncrypt(value))); res.setHeader('Set-Cookie', serialize(`${prefix}_${name}`, encryptedValue, options)); return res; } const withSetCookie: Middleware = (req: NextApiRequest, res: NGNApiResponse, next: NextHandler) => { res.setCookie = setCookie(res); next(); } export default withSetCookie;
Java
UTF-8
922
2.75
3
[]
no_license
package com.game.jdbc.beans; import java.sql.Date; public class PlayerAndGame { // PRIVATE INSTANCE VARIABLES private int player_game_id; private int game_id; private int player_id; private Date _date; private int _score; // PUBLIC PROPERTIES GETTERS public int getId() { return this.player_game_id; } public int getGameId() { return this.game_id; } public int getPlayerId() { return this.player_id; } public Date getDate() { return this._date; } public int getScore() { return this._score; } // PUBLIC PROPERTIES SETTERS public void setId(int player_game_id) { this.player_game_id = player_game_id; } public void setGameId(int game_id) { this.game_id = game_id; } public void setPlayerId(int player_id) { this.player_id = player_id; } public void setDate(Date playing_date) { this._date = playing_date; } public void setScore(int score) { this._score = score; } }
JavaScript
UTF-8
466
2.84375
3
[]
no_license
/* @author: Fitz @name: patchZero @description: 二进制不足8位时, 在高位进行补0操作 @parms: String 需要补0的二进制数 @return: String 标准的8位二进制数 */ export default function (bin) { let bin_arr = bin.split('') let len = bin_arr.length if (len === 8) { return bin } while (len < 8) { bin_arr.unshift('0') len = bin_arr.length } return bin_arr.join('') }
Python
UTF-8
5,089
3.609375
4
[]
no_license
# -*- coding: UTF-8 -*- from sympy import * from math import gcd from functools import lru_cache def miller_rabin(testee, witness): n, a = testee, witness if n % 2 == 0 or 1 < gcd(a, n) < n: return True q = n - 1 k = 0 while q % 2 == 0: q //= 2 k += 1 a = pow(a, q, n) if a == 1: return False for i in range(0, k): if a == n - 1: return False a = (a * a) % n return True def is_prime(n): if n == 1: return False if n == 2: return True if n % 2 == 0: return False witnesses = [2, 3] return not any(miller_rabin(n, w) for w in witnesses) def primes_upto(N): mx = (N-3) >> 1 sq = 0 v = 0 i = -1 primes = [] prime = [True] * (mx + 1) if N >= 2: primes.append(2) while True: i += 1 if i > mx: break if prime[i]: v = (i << 1) + 3 primes.append(v) sq = i * ((i << 1) + 6) + 3 if sq > mx: break for j in range(sq, mx+1, v): prime[j] = False while True: i += 1 if i > mx: break if prime[i]: primes.append((i << 1) + 3) return primes # Problems def m2p1(n): '''Given a non-negative integer n calculate n-th Tribonacci number, using recursion. ''' if n <= 1: return 0 if n == 2: return 1 return m2p1(n-1) + m2p1(n-2) + m2p1(n-3) memo = {0:0, 1:0, 2:1} def m2p2(n): '''Given a non-negative integer n calculate n-th Tribonacci number, using recursion and memoization. ''' if n < 0: return 0 if n in memo: return memo[n] else: new_value = memo[n] = m2p2(n-1) + m2p2(n-2) + m2p2(n-3) memo[n] = new_value return new_value def m2p3(n): '''Given a non-negative integer n calculate n-th Tribonacci number using memoization with a list, and without using recursion ''' T = [0,0,1] + [0]*(n-2) for i in range(3, n+1): T[i] = T[i-1] + T[i-2] + T[i-3] return T[n] def m2p4(n): '''Given a non-negative integer n calculate n-th Tribonacci number, without using recursion and only storing three values. ''' if n <= 1: return 0 t3, t2, t1 = 1, 0, 0 for _ in range(3, n+1): t3, t2 ,t1 = t1+t2+t3 ,t3 ,t2 return t3 def m2p5(n,L): '''Project Euler Problem 31. The input n is a positive integer and the input L is a list of coin values. The returned value is the number of ways n can be split using the coin values in the list L. ''' ways = [1] + [0]*n for i in L: for j in range(i, n+1): ways[j] += ways[j-i] return ways[n] def m2p6(k): '''Project Euler Problem 76. The input k should be a positive integer. The returned value is the number of different ways k can be written as a sum of at least two positive integers. ''' ways = [0] *(k+1) ways[0] = 1 #only 1 way to get sum 1 #ways for sums involving numbers in [1, k] for i in range(1, k): for j in range(i, k+1): ways[j] += ways[j-i] return ways[k] # ways = [1] + [0]*k # for num in range(1,k): # for i in range(num, k+1): # ways[i] += ways[i-k] # return ways[k] # return (binomial_coefficients_list(k)) def m2p7(k): '''Project Euler Problem 77. The input k should be a positive integer. The returned value is the smallest positive integer n such that the number of ways to write n as a sum of primes exceeds k ''' #nota coins gaurinn m2p5, n=k og primes = L primes = [i for i in primerange(1, k+1)] for p in primes: n = m2p5(k,primes) nm = npartitions(prim) return nm # if k < 0: return 0 # if k == 0: return 2 # primes = [i for i in primerange(0,k+1)] # for j in range(k): # binomial(k,primes[j]) # return m2p5(k,primes) def m2p8(k): '''Project Euler Problem 78. The input k should be a positive integer. The returned value is the smallest positive integer n such that number of ways n coins can be separated into piles is divisible by k. ''' return -1 def m2p9(M): '''Project Euler Problem 81. The input M should be an n x n matrix containing integers, given as a list of lists. The output is the minimal path sum, as defined on Project Euler. ''' for i in range(len(M)-2, -1, -1): #sny fylkinu við M[len(M)-1][i] += M[len(M)-1][i+1] M[i][len(M)-1] += M[i+1][len(M)-1] for i in range((len(M))-2, -1, -1): #byrja neðst til hægri og leita upp for j in range((len(M))-2, -1, -1): M[i][j] += min(M[i+1][j], M[i][j+1]) return M[0][0] #skila vinstra efsta if __name__ == "__main__": # print(m2p1(8)) # print(m2p2(8)) print(m2p3(1000000)) # print(m2p4(10000)) # print(m2p5(20,[1,2,5])) # print(m2p6(5)) # print(m2p7(4)) # print(m2p8(7)) # print(m2p9([[1,1,9],[9,1,1],[9,9,1]]))
C#
UTF-8
1,008
2.84375
3
[]
no_license
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; namespace TheEvolutionOfRevolution { class ButtonBehavior { public MouseState currentState; bool pressing = false; public bool PRESSED, DRAGGING, HOVERING; public void CheckButton(Rectangle rectangle) { PRESSED = false; DRAGGING = false; currentState = Mouse.GetState(); if (rectangle.Contains(new Point(currentState.X, currentState.Y))) { HOVERING = true; if (currentState.LeftButton == ButtonState.Pressed) { pressing = true; DRAGGING = true; } else { if (pressing) { PRESSED = true; } pressing = false; } } else { pressing = false; HOVERING = false; } } } }
Ruby
UTF-8
1,372
2.921875
3
[]
no_license
#!/usr/bin/env ruby gem 'minitest', '>= 5.0.0' require 'minitest/pride' require 'minitest/autorun' require_relative 'hamming' class HammingTest < Minitest::Test def test_empty_strands assert_equal 0, Hamming.compute_distance('', '') end def test_disallow_first_strand_longer assert_raises(ArgumentError) { Hamming.compute_distance('AATG', 'AAA') } end def test_identical_strands assert_equal 0, Hamming.compute_distance('B', 'B') end def test_long_identical_strands assert_equal 0, Hamming.compute_distance('GGACTGA', 'GGACTGA') end def test_complete_distance_in_single_nucleotide_strands assert_equal 1, Hamming.compute_distance('A', 'G') end def test_complete_distance_in_small_strands assert_equal 2, Hamming.compute_distance('AG', 'CT') end def test_small_distance assert_equal 1, Hamming.compute_distance('GGACG', 'GGTCG') end def test_small_distance_in_long_strands assert_equal 2, Hamming.compute_distance('ACCAGGG', 'ACTATGG') end def test_non_unique_character_in_first_strand assert_equal 1, Hamming.compute_distance('AGA', 'AGG') end def test_large_distance assert_equal 4, Hamming.compute_distance('GATACA', 'GCATAA') end def test_large_distance_in_off_by_one_strand assert_equal 9, Hamming.compute_distance('GGACGGATTCTG', 'AGGACGGATTCT') end end
Python
UTF-8
501
2.796875
3
[]
no_license
import smtplib import getpass smtp_object = smtplib.SMTP('smtp.gmail.com',587) #465 or no num print(smtp_object.ehlo()) smtp_object.starttls() email = getpass.getpass("Email: ") password = getpass.getpass("Password: ") print(smtp_object.login(email,password)) from_address = email to_address = email subject = input("enter the subject line: ") message = input("enter the body message: ") msg = "Subject: "+subject+"\n"+message smtp_object.sendmail(from_address, to_address, msg) smtp_object.quit()
Java
UTF-8
20,597
2.15625
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Views; import Controllers.ControllerCategoriaPesquisa; import Models.Configuracao; import Models.Categoria; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; /** * * @author Beatriz Oliveiira */ public class FrmCategoriaPesquisa extends javax.swing.JInternalFrame { private Configuracao model; private ControllerCategoriaPesquisa controller; public FrmCategoriaPesquisa() { initComponents(); } public FrmCategoriaPesquisa(Configuracao model){ this(); this.model = model; this.controller = new ControllerCategoriaPesquisa(this, model); } public void mostraMensagem(String mensagem) { if (mensagem != null) { JOptionPane.showMessageDialog(this, mensagem); } } public boolean validaPesquisa(){ if(this.pesquisaCategoria.getText().trim().equals("")){ this.mostraMensagem("Informe o nome da Categoria, ou digite 'todos' para retornar todos as atividades. "); this.pesquisaCategoria.requestFocus(); return false; } return true; } public boolean validaCampos() { if (this.nomeCategoria.getText().trim().equals("")) { this.mostraMensagem("Informe o nome da categoria."); this.nomeCategoria.requestFocus(); return false; } if (this.nomeCurso.getText().trim().equals("")) { this.mostraMensagem("Informe o nome da curso."); this.nomeCurso.requestFocus(); return false; } if (this.limiteHoras.getText().trim().equals("")) { this.mostraMensagem("Informe o limite de horas da categoria."); this.limiteHoras.requestFocus(); return false; } return true; } public void limpaTableAtividade() { DefaultTableModel tabela = (DefaultTableModel) this.tableCategoria.getModel(); tabela.setNumRows(0); } public void preencheCamposAlteracao(Categoria categoria) { if (categoria != null) { this.id.setText(String.valueOf(categoria.getId())); this.nomeCategoria.setText(categoria.getNomeCategoria()); this.nomeCurso.setText(categoria.getCurso().getNome()); this.limiteHoras.setText(String.valueOf(categoria.getLimiteHoras())); this.descricao.setText(categoria.getDescricao()); this.btnSalvar.setEnabled(true); this.btnExcluir.setEnabled(true); this.btnCancelar.setEnabled(true); } } public void limpaCampos() { this.id.setText(""); this.limiteHoras.setText(""); this.nomeCategoria.setText(""); this.pesquisaCategoria.setText(""); this.nomeCurso.setText(""); this.descricao.setText(""); } public void fechaTela() { this.dispose(); } public String getId(){ return this.id.getText().trim(); } public String getCategoria() { return this.nomeCategoria.getText().trim(); } public String getNomeCurso() { return this.nomeCurso.getText().trim(); } public String getLimiteHoras() { return this.limiteHoras.getText().trim(); } public String getDescricao() { return this.descricao.getText().trim(); } public String getPesquisaCategoria(){ return this.pesquisaCategoria.getText().trim(); } public JTable getTableCategoria(){ return this.tableCategoria; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { btnCancelar = new javax.swing.JButton(); nomeCurso = new javax.swing.JTextField(); pesquisaCategoria = new javax.swing.JTextField(); limiteHoras = new javax.swing.JTextField(); btnExcluir = new javax.swing.JButton(); BtnOk = new javax.swing.JButton(); id = new javax.swing.JTextField(); txtNome = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); tableCategoria = new javax.swing.JTable(); btnSalvar = new javax.swing.JButton(); nomeCategoria = new javax.swing.JTextField(); titulo = new javax.swing.JLabel(); labelId = new javax.swing.JLabel(); txtLogin = new javax.swing.JLabel(); txtPesquisarUsuario = new javax.swing.JLabel(); txtContato = new javax.swing.JLabel(); jScrollPane2 = new javax.swing.JScrollPane(); descricao = new javax.swing.JTextArea(); jLabel8 = new javax.swing.JLabel(); setClosable(true); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setIconifiable(true); setMaximizable(true); setTitle("Categoria"); btnCancelar.setIcon(new javax.swing.ImageIcon("C:\\Users\\willi\\Desktop\\Icones\\back.png")); // NOI18N btnCancelar.setText("Cancelar"); btnCancelar.setEnabled(false); btnCancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCancelarActionPerformed(evt); } }); nomeCurso.setEnabled(false); pesquisaCategoria.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pesquisaCategoriaActionPerformed(evt); } }); limiteHoras.setEnabled(false); btnExcluir.setIcon(new javax.swing.ImageIcon("C:\\Users\\willi\\Desktop\\Icones\\cancel.png")); // NOI18N btnExcluir.setText("Excluir"); btnExcluir.setEnabled(false); btnExcluir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnExcluirActionPerformed(evt); } }); BtnOk.setText("OK"); BtnOk.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtnOkActionPerformed(evt); } }); id.setEnabled(false); id.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { idActionPerformed(evt); } }); txtNome.setText("Nome:"); tableCategoria.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Id", "Nome", "Curso", "limite de horas", "Descrição" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class }; boolean[] canEdit = new boolean [] { false, false, false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); tableCategoria.setColumnSelectionAllowed(true); tableCategoria.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tableCategoriaMouseClicked(evt); } }); jScrollPane1.setViewportView(tableCategoria); tableCategoria.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION); btnSalvar.setIcon(new javax.swing.ImageIcon("C:\\Users\\willi\\Desktop\\Icones\\accept.png")); // NOI18N btnSalvar.setText("Salvar"); btnSalvar.setEnabled(false); btnSalvar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSalvarActionPerformed(evt); } }); nomeCategoria.setEnabled(false); nomeCategoria.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { nomeCategoriaActionPerformed(evt); } }); titulo.setFont(new java.awt.Font("Verdana", 1, 18)); // NOI18N titulo.setText("Pesquisar Categoria"); labelId.setText("Id:"); txtLogin.setText("Curso:"); txtPesquisarUsuario.setText("Pesquisar:"); txtContato.setText("Limite de horas:"); descricao.setColumns(20); descricao.setRows(5); descricao.setEnabled(false); jScrollPane2.setViewportView(descricao); jLabel8.setText("Descricao:"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(42, 42, 42) .addComponent(btnExcluir) .addGap(74, 74, 74) .addComponent(btnCancelar) .addGap(80, 80, 80) .addComponent(btnSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addGap(109, 109, 109) .addComponent(titulo)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(10, 10, 10) .addComponent(txtPesquisarUsuario) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(pesquisaCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, 344, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(BtnOk)) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(10, 10, 10) .addComponent(txtLogin)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(nomeCurso, javax.swing.GroupLayout.PREFERRED_SIZE, 285, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(58, 58, 58) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtContato) .addComponent(limiteHoras, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(10, 10, 10) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(id, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(labelId) .addGap(103, 103, 103))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtNome) .addComponent(nomeCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, 353, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane2))) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel8))) .addContainerGap(41, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(11, 11, 11) .addComponent(titulo, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(11, 11, 11) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(3, 3, 3) .addComponent(txtPesquisarUsuario)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(pesquisaCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(BtnOk, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(labelId) .addComponent(txtNome)) .addGap(6, 6, 6) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(id, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(nomeCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtContato) .addComponent(txtLogin)) .addGap(11, 11, 11) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(nomeCurso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(limiteHoras, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(jLabel8) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(29, 76, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnCancelar) .addComponent(btnSalvar) .addComponent(btnExcluir)) .addGap(20, 20, 20)))) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed this.controller.evento(evt); }//GEN-LAST:event_btnCancelarActionPerformed private void pesquisaCategoriaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pesquisaCategoriaActionPerformed // TODO add your handling code here: }//GEN-LAST:event_pesquisaCategoriaActionPerformed private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed this.controller.evento(evt); }//GEN-LAST:event_btnExcluirActionPerformed private void BtnOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnOkActionPerformed this.controller.evento(evt); this.id.setEnabled(false); this.nomeCategoria.setEnabled(true); this.nomeCurso.setEnabled(true); this.limiteHoras.setEnabled(true); this.descricao.setEnabled(true); }//GEN-LAST:event_BtnOkActionPerformed private void idActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_idActionPerformed // TODO add your handling code here: }//GEN-LAST:event_idActionPerformed private void tableCategoriaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableCategoriaMouseClicked this.controller.evento(evt); }//GEN-LAST:event_tableCategoriaMouseClicked private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed this.controller.evento(evt); }//GEN-LAST:event_btnSalvarActionPerformed private void nomeCategoriaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nomeCategoriaActionPerformed // TODO add your handling code here: }//GEN-LAST:event_nomeCategoriaActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton BtnOk; private javax.swing.JButton btnCancelar; private javax.swing.JButton btnExcluir; private javax.swing.JButton btnSalvar; private javax.swing.JTextArea descricao; private javax.swing.JTextField id; private javax.swing.JLabel jLabel8; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JLabel labelId; private javax.swing.JTextField limiteHoras; private javax.swing.JTextField nomeCategoria; private javax.swing.JTextField nomeCurso; private javax.swing.JTextField pesquisaCategoria; private javax.swing.JTable tableCategoria; private javax.swing.JLabel titulo; private javax.swing.JLabel txtContato; private javax.swing.JLabel txtLogin; private javax.swing.JLabel txtNome; private javax.swing.JLabel txtPesquisarUsuario; // End of variables declaration//GEN-END:variables }
Java
UTF-8
300
2.34375
2
[]
no_license
package javalesson.part1.model; import org.junit.Test; public class Testing { @Test public void test(){ System.out.println("test"); } class Test2{ int a; int b; public Test2(int c){ a = b-1; b = c-2; } } }
Java
UTF-8
1,344
2.953125
3
[]
no_license
package com.minorius.data; /** * Created by minorius on 22.02.2017. */ public class SessionData { private String name; private String message; private String rating; public SessionData(String name, String message, String rating) { this.name = name; this.message = message; this.rating = rating; } public String getName() { return name; } public String getMessage() { return message; } public String getRating() { return rating; } @Override public String toString() { return "SessionData{" + "name='" + name + '\'' + ", message='" + message + '\'' + ", rating='" + rating + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SessionData that = (SessionData) o; if (!name.equals(that.name)) return false; if (!message.equals(that.message)) return false; return rating.equals(that.rating); } @Override public int hashCode() { int result = name.hashCode(); result = 31 * result + message.hashCode(); result = 31 * result + rating.hashCode(); return result; } }
Java
UTF-8
1,656
2.453125
2
[]
no_license
package beSen.timerTask; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.HashMap; import java.util.Map; @RestController @RequestMapping("/servlet/service/*") public class TimerHandler extends HttpServlet { @Autowired private ApplicationContext applicationContext; @GetMapping public void doGet(HttpServletRequest req, HttpServletResponse resp) { String path = req.getRequestURI(); String[] splitPath = path.split("/"); if (splitPath.length == 4) { String bean = splitPath[3]; ITimer timer = (ITimer) applicationContext.getBean("ITimer." + bean); Map<String, String> parameter = new HashMap<>(); Map<String, String[]> map = req.getParameterMap(); for(Map.Entry<String,String[]> re : map.entrySet()) { parameter.put(re.getKey(),re.getValue()[0]); } timer.runTask(parameter); } else { throw new IllegalArgumentException("the request url must like /servlet/service/taskName?key=value"); } try { resp.getWriter().write("the task run success..."); } catch (IOException e) { e.printStackTrace(); } } }
C++
UTF-8
1,472
4.625
5
[]
no_license
/* Write a program that reads from stdin the length of an array and then store in it the numbers given from stdin. The program should then print the numbers in reverse order. Remember to properly free the used memory. You should divide the problem in two parts: Write one template function that allocates on the heap one array of a given size, initializes its elements and returns the pointer to the first element. Write a template function that prints the elements of an array in the reverse order. Test with integers and doubles.*/ #include <iostream> using namespace std; // allocates on the heap an array of a given size, initializes its elements and // returns the pointer to the first element template <typename T> T* allocate(int n) { T* array = new T[n]; // allocates on the HEAP an array of size n and defines // a pointer to its first element array[0] for (int i = 0; i < n; i++) cin >> array[i]; return array; } // prints the elements of an array in the reverse order template <typename T> void print_rev(int n, T* array) { for (int i = n - 1; i >= 0; i--) { cout << array[i] << " "; } cout << endl; } int main() { int length; double* array; cout << "Enter the length of the array\n"; cin >> length; array = allocate<double>(length); // static cast print_rev(length, array); delete[] array; // deallocates the memory block previously occupied using // new[] return 0; }
C++
UTF-8
578
2.609375
3
[ "BSD-2-Clause" ]
permissive
#ifndef VIDEOSOURCE_H #define VIDEOSOURCE_H #include "queue.h" #include <opencv2/core.hpp> class Timer; class VideoSource { public: enum Command {Noop, Play, Pause, Rewind, NextFrame, PrevFrame}; int imageWidth, imageHeight; Queue<cv::Mat,1> imagesCaptured; Queue<Command,2> commands; bool printTimeStats; bool playing; virtual void Start() = 0; virtual void Stop() = 0; virtual ~VideoSource(); Command NextCommand(int& frameCount, Timer& timer); void PrintTimeStats(int frameCount, Timer& timer); }; #endif // VIDEOSOURCE_H
C++
UTF-8
160
2.515625
3
[]
no_license
// Power.h namespace Power { class MyPower { public: // Returns e * i static double Multiply(double e, double i); }; }
PHP
UTF-8
1,629
2.640625
3
[]
no_license
<?php use PHPUnit\Framework\TestCase; use SuperSimpleValidation\Rules\FileExtension; use SuperSimpleValidation\ValidationException; use Psr\Http\Message\UploadedFileInterface; class FileExtensionRuleTest extends TestCase { public function testInitializes() { $this->assertInstanceOf( FileExtension::class, new FileExtension("pdf", "error") ); } public function testCorrectlyValidatesFileExtension() { $uploadFile = $this->createMock(UploadedFileInterface::class); $uploadFile ->method("getClientFilename") ->willReturn("test.pdf"); $rule = new FileExtension("pdf", "error"); $this->assertTrue($rule->validate($uploadFile), "Validates upload file interface"); $this->assertTrue($rule->validate("test.pdf"), "Validates file name"); $this->assertFalse($rule->validate(null), "Invalidates correctly"); } public function testThrowsExceptionOnIncorrectExtensionArg() { $this->expectException(\InvalidArgumentException::class); new FileExtension([], "error"); } public function testThrowsExceptionOnInvalidAssert() { $this->expectException(ValidationException::class); $rule = new FileExtension("pdf", "error"); $rule->assert([]); } public function setUp() { parent::setUp(); file_put_contents("test.pdf", "%PDF"); } public function tearDown()/* The :void return type declaration that should be here would cause a BC issue */ { unlink("test.pdf"); parent::tearDown(); } }
SQL
UTF-8
1,341
3.5625
4
[]
no_license
create database mvDatabase; use database mvDatabase: create table landlord( landlordId int auto_increment Not Null Primary Key, lastName varchar(100) Not Null, firstName varchar(50) Not Null, ort varchar(100) Not Null, zip int Not Null, housenumber int Not Null ); create table property( propertyId int auto_increment Not Null Primary Key, landlordId int Not Null, billingCompanyId int Not Null, ort varchar(100) Not Null, zip int Not Null, housenumber int Not Null, foreign key (landlordId) references landlord(landlordId), foreign key (billingCompanyId) references billingCompany(billingCompanyId) ); create table landlordTenantProperty( propertyId int Not Null, landlordId int Not Null, tenantId int Not Null, foreign key (landlordId) references landlord(landlordId), foreign key (propertyId) references property(property), foreign key (tenantId) references tenant(tenantId), ); create table tenant( tenantId int auto_increment Not Null Primary Key, firstName varchar(50) Not Null, lastName varchar(100) Not Null ); create table billingCompany( billingCompanyId int auto_increment Not Null Primary Key, companyName varchar(200) Not NUll, ort varchar(100) Not Null, zip int Not Null, street varchar(150) Not Null, );
Swift
UTF-8
2,485
2.75
3
[]
no_license
// // NetworkManager.swift // TestHTML // // Created by Dehelean Andrei on 4/21/17. // Copyright © 2017 Dehelean Andrei. All rights reserved. // import UIKit let firstGuid = "firstSite_guid" let secondGuid = "secondSite_guid" typealias CompleteHandlerBlock = () -> () class NetworkManager: NSObject, URLSessionDelegate, URLSessionDownloadDelegate { var handlerQueue: [String:CompleteHandlerBlock]! static let shared: NetworkManager = NetworkManager() private override init() { super.init() handlerQueue = [:] } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { print(bytesWritten) } func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { print(error ?? "") UIApplication.shared.isNetworkActivityIndicatorVisible = false } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { print(error ?? "it worked") } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { let webTask = fetchWebsiteTask(sessionId: session.configuration.identifier!, taskId: downloadTask.taskIdentifier) let path = webTask?.filePath do { try FileManager.default.moveItem(at: location, to: path!) } catch let error as NSError { print(error) } let guid = webTask?.filePath.lastPathComponent.replacingOccurrences(of: ".zip", with: "") let unzipService = UnzipService(guid: guid!) unzipService.run() } func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) { print("background url it finished") if let identif = session.configuration.identifier { callCompletionHandlerForSession(identifier: identif) } } func addCompletionHandler(handler: @escaping CompleteHandlerBlock, identifier: String) { handlerQueue[identifier] = handler } func callCompletionHandlerForSession(identifier: String) { if let handler = handlerQueue[identifier] { handlerQueue.removeValue(forKey: identifier) DispatchQueue.main.async { handler() } } } }
Markdown
UTF-8
5,458
2.609375
3
[ "MIT" ]
permissive
[![NPM version](https://img.shields.io/npm/v/@overlook/plugin-match.svg)](https://www.npmjs.com/package/@overlook/plugin-match) [![Build Status](https://img.shields.io/travis/overlookjs/plugin-match/master.svg)](http://travis-ci.org/overlookjs/plugin-match) [![Dependency Status](https://img.shields.io/david/overlookjs/plugin-match.svg)](https://david-dm.org/overlookjs/plugin-match) [![Dev dependency Status](https://img.shields.io/david/dev/overlookjs/plugin-match.svg)](https://david-dm.org/overlookjs/plugin-match) [![Greenkeeper badge](https://badges.greenkeeper.io/overlookjs/plugin-match.svg)](https://greenkeeper.io/) [![Coverage Status](https://img.shields.io/coveralls/overlookjs/plugin-match/master.svg)](https://coveralls.io/r/overlookjs/plugin-match) # Overlook framework match plugin Part of the [Overlook framework](https://overlookjs.github.io/). ## Abstract Plugin which delegates handling of requests either to this route, or children, based on matching the request. This is the base building block of conditional routing. This plugin does not include logic for determining which route should handle a request. It only provides the mechanism for delegation to that route once the route-matching decision is made. An example of a plugin which builds on this one is [@overlook/plugin-path](https://www.npmjs.com/package/@overlook/plugin-path), which routes requests depending on request path. ## Usage ### Handling This plugin extends `.handle()` method to call `[MATCH]()` to determine if this request matches the route. It then calls other methods, depending on the matching result. ### Matching logic User should define matching logic by overriding `[MATCH]()` method. `[MATCH]( req )`: * Is called with request object * Should return an object if the request matches this route * Should return `undefined` if it doesn't Object returned in case of a match should have a property `.exact` which is: * `true` if is an exact match * `false` if is a match but not exact (i.e. should be delegated to children) The object can have any other custom properties desired. ```js const Route = require('@overlook/route'); const matchPlugin = require('@overlook/plugin-match'); const {MATCH} = matchPlugin; const MatchRoute = Route.extend( matchPlugin ); class MyMatchRoute extends MatchRoute { [MATCH](req) => { const {path} = req; if (path === '/abc' || path === '/abc/') return {exact: true}; if (path.slice(0, 5) === '/abc/') return {exact: false}; return undefined; } } ``` The above example says: * if request path is '/abc', handle it with this route * if request path is '/abc/*', delegate handling to children * otherwise, do not handle - throw it back to this route's parent ### Handling match #### `[HANDLE_MATCH]( req, match )` In the case of a match, `[HANDLE_MATCH]()` is called. `[HANDLE_MATCH]()` will: * Be called with request object and match object (i.e. the object returned by `[MATCH]()`) * Call `[HANDLE_ROUTE]()` if exact match * Call `[HANDLE_CHILDREN]()` if non-exact match If you want to take any action before/after handling, extend `[HANDLE_MATCH]()`. #### `[HANDLE_ROUTE]( req )` `[HANDLE_ROUTE]()` by default does nothing. It returns `undefined`. `[HANDLE_ROUTE]()` should be extended by user to handle the request. It is called with the request object. #### `[HANDLE_CHILDREN]( req )` `[HANDLE_CHILDREN]()` calls each of the route's childrens' `.handle()` methods with the request object until one returns a non-undefined value. It returns this value to `.handle()` which in turn returns it. i.e. First child to say it has handled the request gets it. ### Tree of match routes If you create a tree of match routes, a request can be given to `.handle()` of root route, and it will propagate up the tree to the appropriate route to handle. This is a more efficient routing algorithm than e.g. Express, which uses a flat array of handlers, which it has to loop through. The result returned from `root.handle()` will be the result from whichever route handled the request. So if the route handler returns a promise, it can be awaited to know if the request was handled successfully. ## Versioning This module follows [semver](https://semver.org/). Breaking changes will only be made in major version updates. All active NodeJS release lines are supported (v10+ at time of writing). After a release line of NodeJS reaches end of life according to [Node's LTS schedule](https://nodejs.org/en/about/releases/), support for that version of Node may be dropped at any time, and this will not be considered a breaking change. Dropping support for a Node version will be made in a minor version update (e.g. 1.2.0 to 1.3.0). If you are using a Node version which is approaching end of life, pin your dependency of this module to patch updates only using tilde (`~`) e.g. `~1.2.3` to avoid breakages. ## Tests Use `npm test` to run the tests. Use `npm run cover` to check coverage. ## Changelog See [changelog.md](https://github.com/overlookjs/plugin-match/blob/master/changelog.md) ## Issues If you discover a bug, please raise an issue on Github. https://github.com/overlookjs/plugin-match/issues ## Contribution Pull requests are very welcome. Please: * ensure all tests pass before submitting PR * add tests for new features * document new functionality/API additions in README * do not add an entry to Changelog (Changelog is created when cutting releases)
C
UTF-8
877
3.453125
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> int main() { char Player[100]; printf("Hello what is your name: "); scanf("%s", Player); printf("\nHello %s lets play game:\n\nGuess the number 0 to 100 and you will win\n\n", Player); srand(time(NULL)); int r = rand() % 100; int i = 0; int c = 0; while(r != i) { printf("\n"); printf("Check the number 0 to 100: "); scanf("%d", &i); if(i < r) { printf("\nChecked Number is less than guessed\n"); c++; } else if(i > r) { printf("\nChecked number is greater than guessed\n"); c++; } else if(i < 65); else printf("\nWoowwwww you won : it took you %d tries\n", c); } }
TypeScript
UTF-8
441
3.234375
3
[]
no_license
import FiguraGeometrica from './FiguraGeometrica'; export default class Cuadrado extends FiguraGeometrica { public constructor(base: number, altura: number){ super(base, altura) } public calcularArea(): number { if(this.base == this.altura) return (this.base**2) else console.log('La figura creada no es un cuadrado'); return null; } }
C
UTF-8
1,297
3.71875
4
[]
no_license
/* ** EPITECH PROJECT, 2017 ** rush_second ** File description: ** Rush 1_1 */ #include <stdlib.h> static char *diff_size_to_str(int x, int y) { char *ret = malloc(sizeof(char) * ((x * y) + y + 1)); int offset = 0; for(int line = 1; line <= y; line++) { if(line == 1) { for(int i = 1; i <= x; i++) ret[offset++] = ((i == 1) ? '/' : (i == x) ? 92 : '*'); ret[offset++] = '\n'; } else if(line == y) { for(int i = 1; i <= x; i++) ret[offset++] = ((i == 1) ? 92 : (i == x) ? '/' : '*'); ret[offset++] = '\n'; } else { for(int i = 1; i <= x; i++) ret[offset++] = ((i == 1 || i == x) ? '*' : ' '); ret[offset++] = '\n'; } } ret[offset++] = 0; return (ret); } char *rush_second(int x, int y) { if(x <= 0 || y <= 0) { return ("invalid_size"); } if (x == 1 && y == 1) return ("*\n"); else if(x == 1) { char *ret = malloc(sizeof(char) * ((x * y) + y + 1)); int offset = 0; for(int i = 0; i < y; i++) { ret[offset++] = '*'; ret[offset++] = '\n'; } ret[offset++] = 0; return (ret); } else if(y == 1) { char *ret = malloc(sizeof(char) * ((x * y) + y + 1)); int offset = 0; for(int i = 0; i < x; i++) ret[offset++] = '*'; ret[offset++] = '\n'; ret[offset++] = 0; return (ret); } else return (diff_size_to_str(x, y)); }
JavaScript
UTF-8
4,885
3.390625
3
[]
no_license
// Creating constructor of class Texture to describe the image which can move on canvas function Plane(fileName) { var me = this; this.x = 0; this.y = HEIGHT/2; this.type = 'plane'; this.width = 100; this.height = 150; this.radius = Math.sqrt(me.width*me.width + me.height*me.height)/2; this.rotation = 0; this.maxSpeed = 8; this.currentSpeed = 0; this.aceleration = 0.075; this.aceleration1 = 0.05; this.loaded = false; // Creating object property 'controls' which contain object with keyboard buttons property this.controls = { key37: false, //left key38: false, //up key39: false, //right key40: false, //back key32: false, //FIRE!!! Space key17: false, //bomb!!!! Alt button1: false }; // Creating property 'image' which is an exemplar of class Image this.image = new Image(); // Create new method 'onload' to change loaded value if image was loaded this.image.onload = function () { me.loaded = true; }; // Creating new image property 'src' to set path to our image this.image.src = fileName; // Creating 'update' method which can change the position of texture by clicking the key this.update = function () { // move up if (me.controls.key38) { me.moveForward(); } else { me.deaccelerate(); } // move back if (me.controls.key40) { me.moveBack(); } // turn left if (me.controls.key39) { me.turnRight(); } // turn right if (me.controls.key37) { me.turnLeft(); } // puch the bomb if (me.controls.key32) { fireEvent('fire', { x: me.x, y: me.y, direction: me.rotation }); me.controls.key32 = false; } // push the bomb if (me.controls.key17) { fireEvent('drop', { x: me.x, y: me.y, direction: me.rotation }); me.controls.key17 = false; } // move to the place on the canvas by clicking mouse if (me.controls.button1) { me.moveTo(); } me.x = me.x + Math.cos(me.rotation) * me.currentSpeed; me.y = me.y + Math.sin(me.rotation) * me.currentSpeed; me.bounceBack(); }; // Creating method 'turnLeft' which change image direction to left this.turnLeft = function () { me.rotation = me.rotation - 0.1; }; // Creating method 'turnRight' which change image direction to right this.turnRight = function () { me.rotation = me.rotation + 0.1; }; // Creating method 'moveForward' which can move the image to forward this.moveForward = function () { me.currentSpeed = me.currentSpeed + me.aceleration; if (me.currentSpeed > me.maxSpeed) { me.currentSpeed = me.maxSpeed; } }; this.deaccelerate = function () { me.currentSpeed = me.currentSpeed - me.aceleration1; if (me.currentSpeed < 0) { me.currentSpeed = 0; } }; // Creating method 'moveBack' which can move the image to back this.moveBack = function () { }; // Creating method 'bounceBack' which don't do the possibility to move our image outside the area this.bounceBack = function () { if (me.x >= WIDTH) { me.x = WIDTH; } if (me.x <= 0) { me.x = 0 + 5; } ; if (me.y + me.height / 2 >= HEIGHT) { this.image.src = 'images/boom.png'; me.reloadPage(); me.width = 150; me.height = 150; me.y = HEIGHT - me.height / 2; me.currentSpeed = 0; me.aceleration = 0; me.rotation = -1.5; } if (me.y <= 0) { me.y = 0 + 10; } ; }; // this.setKey = function (keyCode, keyState) { me.controls['key' + keyCode] = keyState; }; this.setButton = function (keyCode, keyState) { me.controls['button' + keyCode] = keyState; }; this.moveTo = function (xPosition, yPosition) { me.x = xPosition; me.y = yPosition; }; this.reloadPage = function (){ window.location.reload(); }; this.draw = function (ctx) { if (me.loaded) { ctx.save(); ctx.translate(me.x, me.y); ctx.rotate(me.rotation + 1.5); ctx.drawImage(me.image, -me.width/2, -me.height/2, me.width, me.height); ctx.beginPath(); ctx.arc(0, 0, me.radius, 0, 2*Math.PI); ctx.closePath(); ctx.stroke(); ctx.restore(); } }; }
JavaScript
UTF-8
1,589
2.515625
3
[]
no_license
// import model from '../model/model.js'; import { error } from 'node:console'; import productsManager from '../managers/productsManager.js'; class ProductsController { /** * Liste les produits */ listProducts(request,response) { productsManager.readDB((err,products) => { if(err !== null) { response.status(400); response.send({ error: error.message }); return; } response.status(200).json(products); }); } /** * Ajoute un produit de la liste */ addProduct(request,response) { productsManager.writeDB(request.body,(err) => { if(err !== null) { response.status(400); response.send({ error: err.message }); return; } response.status(201).end(); }); } /** * Retire un produit de la liste */ deleteProduct(request,response) { productsManager.deleteDB(request.params.id,(err) => { if(err !== null) { response.status(400); response.send({ error: err.message }); return; } response.end(); }); } /** * Modifie un produit de la liste */ modifyProduct(request,response) { productsManager.modfifyDB(request.body,request.params.id,(err) => { if(err !== null) { response.status(400); response.send({ error: err.message }); return; } response.status(204).end(); }); } } export default new ProductsController();
Java
UTF-8
5,987
2.21875
2
[]
no_license
package com.application.dockers; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.Toast; import com.application.dockers.connection.ServerConnection; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import protocol.IOBREP.Container; import protocol.IOBREP.DonneeEndContainerIn; import protocol.IOBREP.DonneeEndContainerOut; import protocol.IOBREP.DonneeGetContainers; import protocol.IOBREP.DonneeHandleContainerIn; import protocol.IOBREP.DonneeHandleContainerOut; import protocol.IOBREP.ReponseIOBREP; import protocol.IOBREP.RequeteIOBREP; public class UnloadActivity extends AppCompatActivity implements View.OnClickListener { private String _boatId; private int selectedId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_unload); this._boatId = this.getIntent().getExtras().get("boatId").toString(); ((Button)this.findViewById(R.id.button_unloading_done)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new UnloadActivity.UnLoadContainerDoneTask().execute(); } }); new UnloadActivity.GetContainersTask().execute(); } @Override public void onBackPressed() { Toast.makeText(UnloadActivity.this, "Please finish to Load before leaving", Toast.LENGTH_LONG).show(); } @Override public void onClick(View v) { new UnloadActivity.UnLoadContainerTask().execute(((Button)v).getText().toString()); selectedId = v.getId(); } private class GetContainersTask extends AsyncTask<Void, Void, ReponseIOBREP> { protected void onPostExecute(ReponseIOBREP result) { if(result.getCode() == 200) { if(result.get_chargeUtile() instanceof DonneeGetContainers) { LinearLayout ll = findViewById(R.id.ll_boat_totreated); DonneeGetContainers dgc = (DonneeGetContainers)result.get_chargeUtile(); int i = 0; for(Container cont : dgc.get_containers()) { Button btn = new Button(UnloadActivity.this); btn.setText(cont.getId()); btn.setId(i); btn.setOnClickListener(UnloadActivity.this); btn.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); ll.addView(btn); i++; } } } else { Toast.makeText(UnloadActivity.this, result.get_message(), Toast.LENGTH_LONG).show(); } } @Override protected ReponseIOBREP doInBackground(Void... voids) { ServerConnection sc = new ServerConnection(); sc.TestConnection(UnloadActivity.this); DonneeGetContainers dl = new DonneeGetContainers("","", "IN"); dl.setIdBateau(UnloadActivity.this._boatId); RequeteIOBREP demande = new RequeteIOBREP(dl); return sc.SendAndReceiveMessage(UnloadActivity.this, demande); } } private class UnLoadContainerTask extends AsyncTask<String, Void, ReponseIOBREP>{ @Override protected void onPostExecute(ReponseIOBREP result) { if(result.getCode() == 200) { if(result.get_chargeUtile() instanceof DonneeHandleContainerIn) { DonneeHandleContainerIn dhci = (DonneeHandleContainerIn)result.get_chargeUtile(); LinearLayout llok = findViewById(R.id.ll_boat_treated); View v = UnloadActivity.this.findViewById(selectedId); ViewGroup parent = (ViewGroup) v.getParent(); if (parent != null) { parent.removeView(v); } llok.addView(v); v.setOnClickListener(null); } } else { Toast.makeText(UnloadActivity.this, result.get_message(), Toast.LENGTH_LONG).show(); } } @Override protected ReponseIOBREP doInBackground(String... strings) { ServerConnection sc = new ServerConnection(); sc.TestConnection(UnloadActivity.this); RequeteIOBREP demande = new RequeteIOBREP(new DonneeHandleContainerIn(strings[0])); return sc.SendAndReceiveMessage(UnloadActivity.this, demande); } } private class UnLoadContainerDoneTask extends AsyncTask<Void, Void, ReponseIOBREP>{ @Override protected void onPostExecute(ReponseIOBREP result) { if(result.getCode() == 200) { Intent intent = new Intent(UnloadActivity.this, BoatSelectedActivity.class); startActivity(intent); } else { Toast.makeText(UnloadActivity.this, result.get_message(), Toast.LENGTH_LONG).show(); } } @Override protected ReponseIOBREP doInBackground(Void... voids) { ServerConnection sc = new ServerConnection(); sc.TestConnection(UnloadActivity.this); RequeteIOBREP demande = new RequeteIOBREP(new DonneeEndContainerIn(UnloadActivity.this._boatId)); return sc.SendAndReceiveMessage(UnloadActivity.this, demande); } } }
Java
UTF-8
4,039
2.859375
3
[]
no_license
package com.basedata.vo; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import java.io.IOException; import java.io.OutputStream; import java.util.List; public class ExcelUtils { private String title; // excel 表头 private String[] heads; // list集合 private List<String[]> list; // 输出流 private OutputStream out; // 构造函数 带数字类型 public ExcelUtils(String title, String[] heads, List<String[]> list, OutputStream out) { this.title = title; this.heads = heads; this.list = list; this.out = out; } public void exportExcel() { HSSFWorkbook workbook = new HSSFWorkbook(); // 创建一个excel对象 HSSFSheet sheet = workbook.createSheet(); // 工作表 sheet.setHorizontallyCenter(true);// 设置打印页面为水平居中 sheet.setVerticallyCenter(true);// 设置打印页面为垂直居中 sheet.setMargin(HSSFSheet.TopMargin, 0.2); sheet.setMargin(HSSFSheet.BottomMargin, 0.2); sheet.setMargin(HSSFSheet.LeftMargin, 0.2); sheet.setMargin(HSSFSheet.RightMargin, 0.2); sheet.setDefaultColumnWidth(20); sheet.setColumnWidth(0, 30 * 256);// 30个字符 // 输出excel 表头 HSSFRow titleRow = sheet.createRow(0); titleRow.setHeight((short) (2 * 256)); HSSFRow headRow = sheet.createRow(1); headRow.setHeight((short) (1.5 * 256)); //表头 HSSFCellStyle boldStyle = boldCellStyle(workbook); if (heads != null && heads.length > 0) { for (int h = 0; h < heads.length; h++) { HSSFCell title_cell = titleRow.createCell(h, Cell.CELL_TYPE_STRING); title_cell.setCellValue(title); title_cell.setCellStyle(boldStyle); HSSFCell headCell = headRow.createCell(h, Cell.CELL_TYPE_STRING); headCell.setCellValue(heads[h]); headCell.setCellStyle(boldStyle); } } CellRangeAddress region = new CellRangeAddress(0, 0, (short) 0, (short) heads.length - 1); sheet.addMergedRegion(region); // 输出数据 //HSSFCellStyle baseStyle = buildBaseStyle(workbook); for (int curRow = 0; list != null && curRow < list.size(); curRow++) { String[] arr = list.get(curRow); // 创建excel行 表头1行 导致数据行数 延后一行 HSSFRow dataRow = sheet.createRow(curRow + 2); dataRow.setHeight((short) (1.5 * 256)); for (int curCol = 0; curCol < arr.length; curCol++) { HSSFCell cell = dataRow.createCell(curCol); //cell.setCellStyle(baseStyle); cell.setCellValue(arr[curCol]); } } // excel生成完毕,写到输出流 try { workbook.write(out); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } // 选中的加粗和背景 private HSSFCellStyle boldCellStyle(HSSFWorkbook workbook) { HSSFCellStyle cellstyle = buildBaseStyle(workbook); HSSFFont font = workbook.createFont(); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 粗体显示 cellstyle.setFont(font);// 选择需要用到的字体格式 cellstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中 cellstyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); return cellstyle; } // 居中 private HSSFCellStyle buildBaseStyle(HSSFWorkbook workbook) { HSSFCellStyle cellstyle = workbook.createCellStyle(); cellstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中 cellstyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); cellstyle.setWrapText(true); return cellstyle; } }
Python
UTF-8
12,263
2.609375
3
[]
no_license
# -*- coding: utf-8 -*- import pygame import sys from module1 import * from but import * from main1 import * #main from item import * from excel import * import sound import Sound_controll # 방 import 하는 곳 (지도상에서 붙어있는 방 알아서 전부 import 해주길 바람) import loading2 import a_security2 import a_system1 import a_communication # 시작 pygame.init() screen = pygame.display.set_mode((1000, 600)) pygame.display.set_caption("Moon Side") clock = pygame.time.Clock() run = True # 텍스트관련 [삭제하지 말것] scr = 0 ch = 1 def setscr(script): # setscr(a) a번째 대사 출력 global ch global scr scr = script ch = 1 def textls(): # 텍스트 수동 입력 global ch global scr if ch == 1: if scr == 0: # 0번째 대사(시작시 무조건 출력) t1.reset("> 시스템실에 들어왔다.") t1.next("[ 인벤토리 열기 : 우측 하단 I 버튼 ]") if mode1['main_event'] == 1: t1.next('\'통신장치실로 이동하자.\'') if mode1['main_event'] == 2: t1.next('\'휴스턴을 B구역에 가두고 우주선을 타자.\'') t1.md = 0 t1.mode = 0 if scr == 1: # 1번째 대사 t1.reset("이동목록을 표시중") if scr == 2: # 2번째 대사 [이 아래에 더 추가 가능] t1.reset("중앙컴퓨터가 있다.") if scr == 3: t1.reset("카드키가 없습니다") if scr == 4: t1.reset("전기가 공급되지 않고 있다.") if scr == 5: t1.reset("중앙 컴퓨터 전원을 켰다") if scr == 6: t1.reset("이미 켜져 있다.") if scr == 7: t1.reset("전원이 아직 꺼져 있다.") if scr == 8: t1.reset('스페이스바를 눌러서 넘기기') if scr == 9: t1.reset('스페이스바를 눌러서 넘기기') # if scr == 8: # t1.reset('나 : (사람이다..!)') # t1.next('나 : (생존자인가..?)') # t1.next('휴스턴 : 오오 반갑구만! 자네도 살아있었는가?') # t1.next('나 : 당신도 살아있었군요.') # t1.next('나 : (에드워드의 자료에 있던 휴스턴 연구원이다..)') # t1.next('휴스턴 : 대원들이 전부 사망한줄 알았는데 자네가 살아있을 줄은 몰랐다네!') # t1.next('나 : 두고온 키카드를 가지러 가고있었는데 우주선이 폭발하더군요. 당신은 어떻게 살아있는 거죠?') # t1.next('휴스턴 : 나는 그러니까... 음.. 알약을 잘못 먹어 수면제를 먹는 바람에.. 우주선으로 가지 못하고 내 침실 D방에서 자버리고 말았다네!') # t1.next('나 : (수상해 보인다.. 휴스턴 연구원이 우주선을 폭발 시킨 것 같다..)') # t1.next('< 스페이스바를 눌러서 다음으로 >') # t1.md = 1 # if scr == 9: # t1.reset('나 : 아.. 그렇군요.') # t1.next('휴스턴 : 자네 혹시 연구실.. 아.. 아니라네.') # t1.next('휴스턴 : 자네 나와 같이 동행하지!') # t1.next('나 : (동행을 하게 된다면 위험하고 무슨 일이 일어날지 모르지만 그래도 통신장치를 고치는데에는 도움이 될지도..?)') # t1.next('나 : 그러시죠. 혹시 통신이 안돼서 통신장치를 수리해야 할 것 같은데 도움을 주실 수 있나요?') # t1.next('휴스턴 : 아아 물론이지.') # t1.next('나 : 그런데 C구역으로 가는 길이 비밀번호로 막혔는데..') # t1.next('휴스턴 : 허허 걱정말게. 나는 보안모드가 발생될 경우를 대비해 비밀번호를 외워둔다네. 이전까지 한 번도 보안모드가 발생된 적이') # t1.next('없어서 외우고 있는 비밀번호 아직 유효할 것이네.') # t1.next('휴스턴 : 통신장치실로 가시게!') # t1.next('< 스페이스바를 눌러서 종료 >') # t1.md = 1 if scr == 10: t1.reset("당신은 아직 이 컴퓨터를 사용하면 안될 것 같다") if mode1['main_event'] == 1: t1.next("통신장치를 수리하고 오자") # if scr == i: # i번째 대사 (샘플) # t1.reset("가장 위쪽에 나오는 대사(1번째 줄)") # t1.next("그 다음줄 추가") ch = 0 # *중요* # 1. sheetname을 파일 이름으로 예시) sp3.py 면 'sp3' # + itemo.xlsx에 파일 이름으로 시트를 추가해야함 (.py 빼고) # 2. 방을 이어지게(파일 오가기) 하고 싶다면 알아서 임포트 하고 # 방이름(파일이름).maprun() 으로 다른 방으로 이동 # 3. 변수 선언은 반드시 maprun함수 안에 해야함(지역변수 문제 때문) # 4. 대사 출력은 setscr(a), 대사들은 textls 안에 알아서 만들기 def maprun(): global scr global ch global run # 버튼 만드는 곳 # variable(버튼이름) = button(text, width, height, x좌표, y좌표) # variable.draw() // 버튼을 화면에 출력 # variable.check() // 버튼 위에 마우스가 있다면 1, 아니면 0출력 # variable.color = (R,G,B) // 버튼 색 설정 # variable.textcolor = (R,G,B) // 텍스트 색 설정 # variable.textsize = (텍스트사이즈) # *버튼 활용법* # test_button.check() : 마우스가 위에 올려져 있으면 1을, 아니면 0을 리턴 # test_button.on() : 버튼의 모든 활동 활성화 # test_button.off() : 버튼의 모든 기능 비활성화 (draw, check 등) # objectname = itemobject(사진파일, 개체이름, x크기, y크기, x좌표, y좌표) # 활용 예시 (아래 참고) # box = itemobject('box.png', '박스', width, height, x, y) # box.item = [sheetname, 1] # sheetname은 미리 지정해야함 / 1은 1번째 가로줄을 의미 # | 이 부분은 지우지는 말고 무조건 수정해야하는 부분 | firstsetting() buttonmode = 0 setscr(0) sheetname = 'a_system' # 엑셀파일에 자신이 원하는 방의 이름을 시트로 추가 (건드려야할 것) floor_button.item = [sheetname, 1] # 엑셀파일의 'sp3'시트의 1번째 가로줄을 할당 # | 여기부터 자유롭게 추가 또는 변경 | # holy = itemobject("light2.png", "빛", 100, 100, 200, 200) # 예시 # holy.item = [sheetname, 2] # 엑셀파일의 'sp3'시트의 2번째 가로줄을 할당 time2 = 0 if mode1['main_event'] == 0 and [mode1['seenote'], mode1['edward'], mode1['tryconnect']] == [1,1,1]: mode1['main_event'] = 1 time2 = 1 setscr(8) move_button = button("이동목록", 100, 50, 650, 500) move_button.color = (255,255,255) move_button.textcolor = (0,0,0) move_button.textsize = 22 move_button.font = 'pixel.ttf' find_button = button("집중탐사", 100, 50, 850, 500) find_button.color = (255,255,255) find_button.textcolor = (0,0,0) find_button.textsize = 22 find_button.font = 'pixel.ttf' security_button = button("A 보안실2", 300, 40, 650, 200) # 하위 버튼 디자인 security_button.color = (0,0,0) security_button.textsize = 20 security_button.font = 'pixel.ttf' communication_button = button("통신실", 300, 40, 650, 250) # 하위 버튼 디자인 communication_button.color = (0,0,0) communication_button.textsize = 20 communication_button.font = 'pixel.ttf' onoff_button = button("전원 키기", 300, 40, 650, 200) # 하위 버튼 디자인 onoff_button.color = (0,0,0) onoff_button.textsize = 20 onoff_button.font = 'pixel.ttf' control_button = button("문 제어 장치", 300, 40, 650, 250) # 하위 버튼 디자인 control_button.color = (0,0,0) control_button.textsize = 20 control_button.font = 'pixel.ttf' cctv_button = button("CCTV", 300, 40, 650, 300) # 하위 버튼 디자인 cctv_button.color = (0,0,0) cctv_button.textsize = 20 cctv_button.font = 'pixel.ttf' bgimg = pygame.image.load('images/a_system.png') bgimg = pygame.transform.scale(bgimg, (560, 560)) t_surface = screen.convert_alpha() t_surface.fill((0,0,0,0)) # mode1['system'] = True while run: # 세팅 [ 건드리지 말아야 할 것] screen.fill(pygame.color.Color(50, 50, 50)) pygame.draw.rect(screen, (20,20,20), [20, 20, 560, 560]) screen.blit(bgimg, (20, 20)) # main [여기에 코드 입력] > 이미지 오브젝트, 텍스트(prtext) 등등 # | UI | prtext4("시스템실 | A-5", 'pixel.ttf', 20, 30, 30) # 여기는 바꿔도 됨 drawui() textls() textprinting() if time2 == 1: primg2('images/talk1.png', 20, 20) if time2 == 2: primg2('images/talk2.png', 20, 20) # | 버튼 그리는 곳 | find_button.off() security_button.off() communication_button.off() onoff_button.off() control_button.off() cctv_button.off() if buttonmode == 1: # 이동목록 켜진 경우 move_button.txt = '< 뒤로' security_button.on() communication_button.on() elif buttonmode == 2: move_button.txt = '< 뒤로' onoff_button.on() control_button.on() else: # 꺼진 경우 move_button.txt = '이동목록' find_button.on() move_button.draw() find_button.draw() security_button.draw() communication_button.draw() onoff_button.draw() control_button.draw() cctv_button.draw() # | 이벤트 관리소 | event = pygame.event.poll() if event.type == pygame.QUIT: run = False # // Mouse_click if event.type == pygame.MOUSEBUTTONDOWN: buttoncheck() # [삭제하면 안되는 것] if move_button.check() == 1: # 예시입니다 if buttonmode == 0: setscr(1) buttonmode = 1 else: setscr(0) buttonmode = 0 if find_button.check() == 1: setscr(2) buttonmode = 2 if security_button.check() == 1: if '카드키' in getitem(): a_security2.maprun() else: setscr(3) if communication_button.check() == 1: if '카드키' in getitem(): a_communication.maprun() else: setscr(3) # 2 if onoff_button.check() == 1: if [mode1['electric'],mode1['wire1']] == [True,True]: if mode1['system'] == False: setscr(5) mode1['system'] = True else: setscr(6) else: setscr(4) if control_button.check() == 1: if mode1['system'] == True: if mode1['main_event'] == 2: a_system1.maprun() else: setscr(10) else: setscr(7) if pygame.mouse.get_pressed()[0] == 1: pass # key if pygame.key.get_pressed()[pygame.K_m]: Sound_controll.sound_controll() if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: if time2 == 1: time2 += 1 setscr(9) elif time2 == 2: time2 = 0 t1.md = 0 t1.mm = 0 setscr(0) #fin [끝] pygame.display.flip() clock.tick(60) pygame.quit() if __name__ == '__main__': maprun()
PHP
UTF-8
5,374
2.90625
3
[]
no_license
<?php /** * Geocontexter * @link http://code.google.com/p/mozend/ * @package Geocontexter */ /** * Basic abstract model that every geocontexter module model class should extends * * @package Geocontexter * @license http://www.opensource.org/licenses/bsd-license.php New BSD License * @author Armand Turpel <geocontexter@gmail.com> * @version $Rev$ / $LastChangedDate$ / $LastChangedBy$ */ namespace Core\Model; use Zend\Db\ResultSet\ResultSet; use Zend\Db\ResultSet\AbstractResultSet; abstract class AbstractModel { private $modelFactory; private $service; private $connection; protected $db; /** * error content array * * @access private * @var $error_content array */ private $error_content = array(); /** * error flag * * @access private * @var $error_flag bool */ private $error_flag = false; public function __construct($service) { $this->service = $service; $this->db = $service->get('db'); $this->platform = $this->db->getPlatform(); $this->connection = $this->db->getDriver()->getConnection(); } public function beginTransaction() { $this->connection->beginTransaction(); } public function commit() { $this->connection->commit(); } public function rollback() { $this->connection->rollback(); } /** * build demanded model instance * * @param string $model_class Class name * @param string $namespace */ protected function CoreModel($model_class, $namespace = 'Geocontexter') { if (!isset($this->modelFactory)) { $this->modelFactory = $this->service->get('CoreModel'); } return $this->modelFactory->getModelInstance($model_class, $namespace = 'Geocontexter'); } /** * run sql query * * @param string $sql * @param array $params Parameters to insert into sql * @param string $result_type Result type: array or assocc * @return mixed Result array or if error instance of \Core\Library\Exception */ protected function query($sql, $params = array(), $result_type = 'array') { $result = $this->db->query($sql, $params); $resultSet = new ResultSet; $resultSet->initialize($result); if ( $result_type === 'array') { return $resultSet->toArray(); } else { return $resultSet; } } /** * db insert * * @param string $table Table name * @param string $schema Db schema name * @param aray $params Data to insert eg: array('field' => data,...) * @return mixed Result array or if error instance of \Core\Library\Exception */ protected function insert($table, $schema, $params) { $table = new \Zend\Db\Sql\TableIdentifier($table, $schema); $sql = new \Zend\Db\Sql\Sql($this->db); $insert = $sql->insert($table); $insert->values($params); $selectString = $sql->getSqlStringForSqlObject($insert); return $this->db->query($selectString)->execute(); } /** * db update * * @param string $table Table name * @param string $schema Db schema name * @param array $params Data to insert eg: array('field' => data,...) * @param array $where Condition eg: array('id' => 3) * @return mixed Result array or if error instance of \Core\Library\Exception */ protected function update($table, $schema, $params, $where = array()) { $table = new \Zend\Db\Sql\TableIdentifier($table, $schema); $sql = new \Zend\Db\Sql\Sql($this->db); $update = $sql->update($table); $update->set($params); $update->where($where); $selectString = $sql->getSqlStringForSqlObject($update); return $this->db->query($selectString)->execute(); } /** * db delete * * @param string $table Table name * @param string $schema Db schema name * @param array $where Condition eg: array('id' => 3) * @return mixed Result array or if error instance of \Core\Library\Exception */ protected function delete($table, $schema, $where = array()) { $table = new \Zend\Db\Sql\TableIdentifier($table, $schema); $sql = new \Zend\Db\Sql\Delete($this->db); $delete = $sql->from($table); $delete->where($where); $deleteString = $delete->getSqlString($this->platform); return $this->db->query($deleteString)->execute(); } /** * set error message * * @access private * @param $error string */ protected function set_error( $error ) { $this->error_flag = true; $this->error_content[] = $error; } /** * check if errors occured * * throw exception om errors */ protected function check_errors() { if (true === $this->error_flag) { throw new \Exception($this->get_error( true )); } } /** * Get the error array * * @access private * @return array */ protected function get_error( $as_string = false ) { if($as_string === true) { return var_export($this->error_content, true); } return $this->error_content; } }
Java
UTF-8
1,783
2.125
2
[]
no_license
package com.kh.hamo.dto; public class HamoMemberDTO { /*member*/ private String member_id; private String member_pw; private String member_name; private String member_email; private String member_phone; private String member_location; /*interest*/ private int interest_id; private String interest_interest; /*memberInterest*/ private int memberInterest_id; public String getMember_id() { return member_id; } public void setMember_id(String member_id) { this.member_id = member_id; } public String getMember_pw() { return member_pw; } public void setMember_pw(String member_pw) { this.member_pw = member_pw; } public String getMember_name() { return member_name; } public void setMember_name(String member_name) { this.member_name = member_name; } public String getMember_email() { return member_email; } public void setMember_email(String member_email) { this.member_email = member_email; } public String getMember_phone() { return member_phone; } public void setMember_phone(String member_phone) { this.member_phone = member_phone; } public String getMember_location() { return member_location; } public void setMember_location(String member_location) { this.member_location = member_location; } public int getInterest_id() { return interest_id; } public void setInterest_id(int interest_id) { this.interest_id = interest_id; } public String getInterest_interest() { return interest_interest; } public void setInterest_interest(String interest_interest) { this.interest_interest = interest_interest; } public int getMemberInterest_id() { return memberInterest_id; } public void setMemberInterest_id(int memberInterest_id) { this.memberInterest_id = memberInterest_id; } }
Markdown
UTF-8
1,053
2.53125
3
[ "CC0-1.0" ]
permissive
--- layout: daily title: option scrollCollapse 当显示更少的记录时,是否允许表格减少高度 《不定时一讲》 DataTable中文网 short: option scrollCollapse 当显示更少的记录时,是否允许表格减少高度 date: 2016-5-5 group: 2016-5 caption: 《不定时一讲》 categories: manual daily author: DataTable中文网 --- 参数详解连接{% include href/option/option.options param="scrollCollapse" %} 每个插件都不是完美的,但是作者也是尽可能考虑到使用者的感受,对于表格的高度,一些人希望随着数据的变化而变化, 另一些人则希望固定高度,这个参数正是这个用处 {% highlight javascript linenos %} $('#example').DataTable( { //不管表格中有没有数据都固定300的高度,具体是啥单位,大家自己试试啊 :) scrollY: 300, scrollCollapse: true } ); {% endhighlight %} 如果没有使用{% include href/option/scrollY.dt %}属性,表示和表格数据同步,表格数据减少时,表格的高度也跟着减少
C++
UTF-8
4,635
3.921875
4
[ "MIT" ]
permissive
#include <iostream> #include "LinkedList.h" using namespace std; // Default constructor for the LinkedList class. // Set the member variable and class to NULL(0); LinkedList::LinkedList() :cur(NULL), numOfData(0), before(NULL), tail(NULL), head(NULL) { } LinkedList::~LinkedList() { Object * data; //Deleting every dynamically allocated object. if ((data = LFirst()) != NULL) { LRemove(); delete data; while ((data = LNext())) { LRemove(); delete data; } } } // Copy Constructor for the LinkedList class. // Operate deep copy, and dynamically allocate the object. LinkedList::LinkedList(LinkedList & list) :LinkedList() { if (list.LFirst() != NULL) { Object * temp = list.LFirst(); insert(new Object(*temp)); while(NULL != (temp = list.LNext())) insert(new Object(*temp)); } } // param data The data you want to save into the linked list. // The function saves the data into at the end(tail) of the list. void LinkedList::insert(Object * data) { //Allocating space for the new Node. LNode * newNode = new LNode; newNode->data = data; newNode->next = NULL; if (head == NULL) //Inseting first node. { head = newNode; tail = newNode; tail->next = NULL; } else //Inserting second or after. { tail->next = newNode; tail = newNode; tail->next = NULL; } numOfData++; } // return ture it is add successfully, false, if it fails to add. // param index The specific location that you want to add data. // param data Data you want to append. // Append data into the index location. bool LinkedList::append(const int index, Object * data) { if (index > numOfData) return false; LNode * newNode = new LNode; newNode->data = data; if (index == 0) { newNode->next = head; head = newNode; } else { //Resent the current location. cur = head; before = NULL; //Seeking place to add. for (int i = 0; i < index; i++) { before = cur; cur = cur->next; } //Add to the seeked location newNode->next = cur; before->next = newNode; } numOfData++; return true; } // Return index i th object. // param i the index of the element. // Get ith element from the list. Object * LinkedList::get(int i) { Object * temp = NULL; //Temporary object container. if (numOfData == 0 || numOfData < i) //When there is no data found, or index exceeds. return NULL; else if (i == 0) temp = LFirst(); else { temp = LFirst(); for(int k=0; k<i; k++) { temp = LNext(); } } return temp; } Object * LinkedList::remove(int i) { Object * temp = get(i); LRemove(); return temp; } /** * \Iterate solution of reversing the list. */ void LinkedList::reverseIterate() { tail = head; before = tail; while (tail->next != NULL) { head = tail->next; cur = head->next; head->next = before; before = head; tail->next = cur; } } //brief Recursively reverse the list. void LinkedList::reverseRecursive() { if(tail != NULL) //I use the tail as first loop or not. { //first loop, initialize. cur = NULL; before = NULL; tail = NULL; } //break statement. if(head->next == NULL) { head->next = cur; return; } //Change the direction of each node. before = cur; cur = head; head = head->next; cur->next = before; //Recursive call. reverseRecursive(); //Setting the tail position recursively. tail = cur; cur = cur->next; } // return return NULL if there is no data // return Object address if there is data // The first data from the list. (The first) Object * LinkedList::LFirst() { if (head == NULL) return NULL; cur = head; before = NULL; Object * temp = cur->data; return temp; } // return return true if there is next data, // return false is there is no data. // param data The data you want to get form the list. Object * LinkedList::LNext() { if (cur == NULL) //When LRemove is invoked at header. return LFirst(); else if (cur->next == NULL) //No more data return NULL; Object * temp = cur->next->data; before = cur; cur = cur->next; return temp; } // return Deleted object. (Delete is required) // Remove the object currently indicating. Object * LinkedList::LRemove() { //Back up the object. Object * backup = cur->data; //if the object is header if (cur == head) { head = head->next; delete cur; cur = NULL; } else //removing from the second node { //Removing the node. before->next = cur->next; delete cur; cur = before; } numOfData--; //Return the backup object. return backup; } // return number of the node in the list. // brief Return the number of the data. int LinkedList::getNumberOfData() const { return numOfData; }
Java
UTF-8
1,095
3.78125
4
[]
no_license
package Test_2018_April; public class Question { private String question; private String[] answers; private double[] points; /** * Skapar en quizfråga med frågetexten question, svarsalternativen answers, * och poängen som de olika svarsalternativen ger i points */ Question(String question, String[] answers, double[] points) { this.question = question; this.answers = answers; this.points = points; } /** * Skriver ut frågan och de olika svarsalternativen numrerade A,B,C..., * allt på varsin rad */ void ask() { System.out.println(question); for (int i = 0; i < answers.length; i++) { System.out.println((char) ('A' + 1) + " : " + answers[i]); } } /** * Returnerar hur många poäng svarsalternativ answer (A,B,C...) ger */ double getPoints(char answer) { for (int i = 0; i < answers.length; i++) { if(answers[i].charAt(0) == answer){ return points[i]; } } return -1; } }
Markdown
UTF-8
3,635
3.09375
3
[ "MIT" ]
permissive
# Intro Revature encourages you to get certifications before you go out to client. This file details which certifications you are eligible for, and some of my suggestions in taking preparing for the exams. The following are exams that can be reimbursed: 1) Oracle Certified Associate, Java SE 8 Programmer (OCA) 2) Oracle Certified Professional 3) AWS Solutions Architect - Associate 4) AWS Certified Developer - Associate # Oracle Certified Associate, Java SE 8 Programmer This is a certification that doesn't expire for Java. You can read more about it [here](https://education.oracle.com/oracle-certified-associate-java-se-8-programmer/trackp_333) In order to prepare for the exam, my recommendation is that you first read through the textbook a couple of times and take [these](https://enthuware.com/java-certification-mock-exams/oracle-certified-associate/ocajp-1z0-808) practice tests. Revature will reimburse you for the practice tests. # Oracle Certified Professional, Java SE 8 Programmer This is the next level up from the OCA. You can read more about it [here](https://education.oracle.com/oracle-certified-professional-java-se-8-programmer/trackp_357.). You can also get [these](https://enthuware.com/java-certification-mock-exams/oracle-certified-professional/java-se-8-1z0-809) practice tests. # AWS Solutions Architect - Associate This is one of the most popular AWS Certifications. It is much harder than the AWS CCP, but it is also much more sought after. - [Official Exam Guide](https://d1.awsstatic.com/training-and-certification/docs-sa-assoc/AWS-Certified-Solutions-Architect-Associate_Exam-Guide.pdf) - [Sample Practice Questions](https://d1.awsstatic.com/training-and-certification/docs-sa-assoc/AWS-Certified-Solutions-Architect-Associate_Sample-Questions.pdf) Here is a study guide for preparing for the SAA Exam: - [Tutorials Dojo SAA study guide](https://tutorialsdojo.com/aws-certified-solutions-architect-associate-saa-c02/) A lot of people also like to take prep courses on Udemy for this exam. AWS also has some free videos regarding the SAA: - [Exam Readiness](https://www.aws.training/Details/Curriculum?id=20685) I highly recommend taking some practice tests before taking the real exam (many are available on Udemy for <\$15), or you can schedule a practice version of the exam before taking the real thing. ## Extra materials: - [Tutorials Dojo Study Guide for SAA](https://tutorialsdojo.com/aws-certified-solutions-architect-associate-saa-c02/) - good resource for studying up on high points on AWS Service - good resource for guiding your studying for the certification - [Tutorials Dojo Slack Workspace](https://app.slack.com/client/TDCBFESF6/learning-slack) - good if you want to compare notes with other people who have taken the exam or are also preparing to take the exam # AWS Certified Developer - Associate - [Official Exam Guide](https://d1.awsstatic.com/training-and-certification/docs-dev-associate/AWS-Certified-Developer-Associate_Exam-Guide.pdf) - [Sample Practice Questions](https://d1.awsstatic.com/training-and-certification/docs-dev-associate/AWS-Certified-Developer-Associate_Sample-Questions.pdf) Here is a study guide for preparing for the Exam: - [Tutorials Dojo Certified Developer study guide](https://tutorialsdojo.com/aws-certified-developer-associate/) # AWS Exams in General - [Which Exam is right for me?(https://tutorialsdojo.com/which-aws-certification-exam-is-right-for-me/) - [Overview of AWS Certs](https://aws.amazon.com/certification/) - [Prepare for AWS Certification Exam](https://aws.amazon.com/certification/certification-prep/)
Ruby
UTF-8
510
2.828125
3
[ "MIT" ]
permissive
require_relative 'helper' require_relative 'search_exception' require 'nokogiri' class SearchControl < SearchException def initialize @page = File.open(Dir.pwd + "/examples/search/search.html") { |f| Nokogiri::HTML(f) } end def search q puts "*** Top 3 results ****" 3.times do |i| puts @page.css('div')[i + 1] end puts "*** Description for #{q} ***" @page.css("div").each do |x| if x.xpath("h1").text == q puts x.xpath("p").text end end end end
Python
UTF-8
1,828
4.46875
4
[]
no_license
# demonstrate the usage of namedtuple import collections as coll def main(): """ For demoing the namedtuple Well, so now what are namedtuples? They turn tuples into convenient containers for simple tasks. With namedtuples you don’t have to use integer indexes for accessing members of a tuple. You can think of namedtuples like dictionaries but unlike dictionaries they are immutable. """ # TODO: create a point namedtuple # here "Point" is the name of namedtuple which has 2 Point = coll.namedtuple("Point", "x y") # space is used as a delimiter between 2 arguments p1 = Point(1, 4) p2 = Point("A", 'z') print(p1) print(p2) print("You can get the values just by names as well") print(f'p1.x -> {p1.x} and p1.y -> {p1.y}') # from https://book.pythontips.com/en/latest/collections.html#namedtuple print("from https://book.pythontips.com/en/latest/collections.html#namedtuple") Animal = coll.namedtuple('Animal', 'name age type') perry = Animal(name="perry", age=31, type="cat") print(perry) # Output: Animal(name='perry', age=31, type='cat') print(perry.name) # Output: 'perry' print( f'perry[0] : {perry[0]} and length is {len(perry)} which defines total number of attributes/values we can fetch') print() print("You can use _replace() to change the values of this namedtuple's attributes ") p1 = p1._replace(x=1000) print("changed namedtuple point p1 ", p1) if __name__ == '__main__': main() print() print("Useful : when you need a light weight immutability ") print("Limitation: You can't use default arg values. " "if the data you're working with has large number of optional properties " "it is better to stick with basic tuple than the namedtuple")
Java
UTF-8
407
2.34375
2
[]
no_license
package ChangeTest; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import ChangeTree.Denomination; class DenominationTest { @Test void testInsert() { Denomination myd = new Denomination(3); myd.InsertD(0,2); myd.InsertD(1,5); myd.InsertD(2,10); assertEquals(myd.getD()[0], 2); assertEquals(myd.getD()[1], 5); assertEquals(myd.getD()[2], 10); } }
PHP
UTF-8
342
2.78125
3
[]
no_license
<?php require('config.php'); $stmt = $pdo->query("SELECT * FROM recette"); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { echo '<pre>'; //print_r($row); echo '</pre>'; echo '<a href="recette.php?id='.$row['Id'].'">'.$row['Nom'].'</a>'; } echo '<pre>'; echo '<a href="../index.php">Home</a>'; echo '</pre>';
PHP
UTF-8
5,308
3.015625
3
[]
no_license
<?php //Циклы и массивы /*данные задания выполнял руководствуюсь теме раздела. Некоторые задания можно выполнить гораздо эффективнее не используя циклы.*/ echo '<br>Задание 1<br>'; $index = 0; while ($index <= 100){ if ($index % 3 === 0){ echo $index; echo "<br>"; } $index++; } echo '<br>Задание 2<br>'; $i = 0; do{ if ($i === 0){ echo $i . '-это ноль'; echo "<br>"; } elseif ($i % 2 === 0){ echo $i . '-четное число'; echo "<br>"; } else { echo $i . '-нечетное число'; echo "<br>"; } $i++; } while ($i <= 10); echo '<br>Задание 3<br>'; for($i = 0; $i < 10; print_r($i++)){} echo "<br>"; echo '<br>Задание 4<br>'; $array = [ "Амурская область" => array( "Белогорск", "Благовещенск", "Зея", "Райчихинск", "Свободный", "Тында", "Шимановск" ), "Архангельская область" => array( "Архангельск", "Коряжма", "Котлас", "Новодвинск", "Онега", "Северодвинск" ), "Кировская область" => array( "Киров", "Вятские Поляны", "Кирово-Чепецк", "Котельнич", "Слободской" ), ]; foreach ($array as $key1 => $value1){ echo $key1 . ":<br>"; foreach ($value1 as $value2){ echo "{$value2}, "; } echo "<br>"; } echo "<br>Задание 5<br>"; foreach ($array as $key1 => $value1){ echo $key1 . ":<br>"; foreach ($value1 as $value2){ if (mb_substr($value2, 0, 1) === "К"){ echo "{$value2}, "; } } echo "<br>"; } echo "<br>Задание 6<br>"; function transliter($str) { $result = ''; $converter = array( 'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd', 'е' => 'e', 'ж' => 'zh', 'з' => 'z', 'и' => 'i', 'й' => 'j', 'к' => 'k', 'л' => 'l', 'м' => 'm', 'н' => 'n', 'о' => 'o', 'п' => 'p', 'р' => 'r', 'с' => 's', 'т' => 't', 'у' => 'u', 'ф' => 'f', 'х' => 'h', 'ц' => 'tc', 'ч' => 'ch', 'ш' => 'sh', 'щ' => 'shch', 'ъ' => '\'', 'ы' => 'y', 'ь' => '\'', 'э' => 'e', 'ю' => 'yu', 'я' => 'ya' ); $lengh = mb_strlen($str); for ($i = 0; $i < $lengh; $i++){ $simv = mb_substr($str, $i, 1); switch ($simv){ case " ": $result = $result . " "; break; case "-": $result = $result . '-'; break; case "_": $result = $result . "_"; break; default: foreach ($converter as $key1 => $value1){ if (mb_substr($str, $i, 1) === $key1){ $result = $result . $value1; } } break; } } return $result; } print_r(transliter("что-то на русском")); echo '<br>задание 7<br>'; function replacmentSpase($str) { $result = ''; $i = 0; $lengh = mb_strlen($str); while($i < $lengh){ if (mb_substr($str, $i, 1) === " "){ $result = $result . "_"; } else { $result = $result . mb_substr($str, $i, 1); } $i++; } return $result; } print_r(replacmentSpase("Какой-то текст без пробелов")); echo '<br>Задание 8<br>'; function convertURL($str) { $result = ''; $converter = array( 'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd', 'е' => 'e', 'ж' => 'zh', 'з' => 'z', 'и' => 'i', 'й' => 'j', 'к' => 'k', 'л' => 'l', 'м' => 'm', 'н' => 'n', 'о' => 'o', 'п' => 'p', 'р' => 'r', 'с' => 's', 'т' => 't', 'у' => 'u', 'ф' => 'f', 'х' => 'h', 'ц' => 'tc', 'ч' => 'ch', 'ш' => 'sh', 'щ' => 'shch', 'ъ' => '\'', 'ы' => 'y', 'ь' => '\'', 'э' => 'e', 'ю' => 'yu', 'я' => 'ya' ); $lengh = mb_strlen($str); for ($i = 0; $i < $lengh; $i++){ $simv = mb_substr($str, $i, 1); switch ($simv){ case " ": $result = $result . "_"; break; case "-": $result = $result . '-'; break; case "_": $result = $result . "_"; break; default: foreach ($converter as $key1 => $value1){ if (mb_substr($str, $i, 1) === $key1){ $result = $result . $value1; } } break; } } return $result; } print_r(convertURL('какой то адрес'));
Java
UTF-8
1,189
2.90625
3
[]
no_license
// Fig. 27.14: Rotator.Java // Um JavaBean que faz rota��o de an�ncios. package com.deitel.jhtp6.jsp.beans; public class Rotator { private String images[] = {"images/illidan.jpg", "images/rise_lich_king.jpg", "images/shadows_of_the_horde.jpg"}; private String links[] = { "https://www.amazon.com/Illidan-World-Warcraft-William-King/dp/0399177574/", "https://www.amazon.com/World-Warcraft-Arthas-Rise-Pocket/dp/143915760X/", "https://www.amazon.com/World-Warcraft-Voljin-Shadows-Horde/dp/1476702977/"}; private int selectedIndex = 0; // retorna o nome do arquivo de imagem ao an�ncio atual public String getImage() { return images[selectedIndex]; } // fim do m�todo getImage // retorna o URL ao site Web correspondente ao an�ncio public String getLink() { return links[selectedIndex]; } // fim do m�todo getLink // atualiza selectedIndex assim as pr�ximas chamadas para getImage e // getLink retornam um an�ncio diferente public void nextAd() { selectedIndex = (selectedIndex + 1) % images.length; } // fim do m�todo nextAd } // fim da classe Rotator
Java
UTF-8
153
1.84375
2
[]
no_license
package network; public class NewClient5 { public static void main(String[] args) { Client Client5 = new Client(); Client5.Process(); } }
JavaScript
UTF-8
1,427
3.015625
3
[]
no_license
export default function curryFn(fn) { const len = fn.length; const args = []; const res = function (item) { args.push(item); if (args.length === len) { return fn.apply(null, args); } else { return res; } } return res; } function curryFn(fn) { let args = []; const choiceFn = function() { let data = Array.prototype.slice.call(arguments); args = args.concat([data]); if (args.length > fn.length) { return fn.apply(null, args); } else { return choiceFn; } } } function curryFn(fn) { var args = []; const choiceFn = function() { let data = Array.prototype.slice.call(arguments); args = args.concat([data]); if(args.length > fn.length) { return fn.apply(null, args); } else { return choiceFn; } } } function curryFn(fn) { let args = []; const choiceFn = function () { Array.prototype.slice.call(arguments); args = args.concat(arguments); if (args.length > fn.length) { return fn.apply(null, args); } else { return choiceFn; } } return choiceFn; } function inherit(parent, child) { var F = function() {}; F.prototype = parent.prototype; child.prototype = new F(); child.prototype.constructor = child; }
Python
UTF-8
600
2.65625
3
[ "Apache-2.0" ]
permissive
from abc import ABC class OverflowStrategy(ABC): def __init__(self, buffer_size: int): self.buffer_size = buffer_size class BackPressure(OverflowStrategy): # unbounded buffer # def __init__(self, buffer_size: int): # self.buffer_size = buffer_size pass class DropOld(OverflowStrategy): # unbounded buffer # def __init__(self, buffer_size: int): # self.buffer_size = buffer_size pass class ClearBuffer(OverflowStrategy): # unbounded buffer # def __init__(self, buffer_size: int): # self.buffer_size = buffer_size pass
PHP
UTF-8
253
2.546875
3
[]
no_license
<?php namespace Xand\Component\Routing\Compiler; /** * Interface CompilerInterface * * @author Sasha Broslavskiy <sasha.broslavskiy@gmail.com> */ interface CompilerInterface { /** * @param string $path * * @return string */ public static function compile($path); }
C++
UTF-8
1,643
2.84375
3
[]
no_license
#include <square.h> namespace checkers { void checkers::Square::SetSquareColor(string set_color) { color_ = set_color; } void checkers::Square::SetGamePiece(GamePiece set_piece) { piece_ = set_piece; } void checkers::Square::SetLocation(size_t row, size_t col) { location_.x = row; location_.y = col; } void checkers::Square::SetContainsGamePiece(bool set_contains_piece) { contains_game_piece_ = set_contains_piece; } std::string checkers::Square::GetSquareColor() const { return color_; } const vec2 &checkers::Square::GetLocation() const { return location_; } bool checkers::Square::GetContainsGamePiece() const { return contains_game_piece_; } void checkers::Square::UpdateGamePieceMoves(vec2 &possible_move) { piece_.UpdatePossibleMoves(possible_move); } bool checkers::Square::GetPieceIsRedColor() const { return piece_.GetIsRedColor(); } const vector<vec2> checkers::Square::GetPiecePossibleMoves() const { return piece_.GetPossibleMoves(); } checkers::GamePiece checkers::Square::GetGamePiece() const { return piece_; } void Square::SetSquareLimits(vec2 &set_x_lim, vec2 &set_y_lim) { x_lim_.x = set_x_lim.x; x_lim_.y = set_x_lim.y; y_lim_.x = set_y_lim.x; y_lim_.y = set_y_lim.y; } vec2 Square::GetXLim() const { return x_lim_; } vec2 Square::GetYLim() const { return y_lim_; } void Square::SetPieceLocation(vec2 &location) { piece_.SetCurrentPosition(location); } void Square::ClearPossibleMoves() { piece_.ClearPossibleMoves(); } void Square::SetIsPieceKing() { piece_.SetIsPieceKing(); } vec2 Square::GetPieceCurrentPos() const { return piece_.GetCurrentPosition(); } } // namespace checkers
Python
UTF-8
306
2.9375
3
[]
no_license
def detect_anagrams(wrd, strng): ans = [] l=[] wrd = wrd.lower() for i in range(len(wrd)): l.append(wrd[i]) l.sort() w = [] for i in strng: if len(l)==len(i) and i.lower()!=wrd: for j in range(len(i)): w.append(i[j].lower()) w.sort() if w==l: ans.append(i) w=[] return ans
Java
UTF-8
6,039
2.75
3
[]
no_license
package rmi_framework; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.*; import java.util.HashMap; import java.util.Map; /*An instance of this class is needed on each node that contains Objects that need referencing * across the system. This alongside the RemoteObj interface are the only 2 classes needed by the user. */ public class RMIHandler implements Runnable{ private ServerSocket server; private Map<String, RemoteObj> localObjects; private InetSocketAddress registry; private InetSocketAddress localHost; public RMIHandler(InetSocketAddress registry, int port) throws IOException{ server = new ServerSocket(port); localHost=new InetSocketAddress(InetAddress.getLocalHost(),server.getLocalPort()); this.registry=registry; localObjects = new HashMap<String, RemoteObj>(); } //Returns a remote object stub corresponding to the remote object at the given registry with name //name (Static Function) public static RemoteObj getRemoteObject(InetSocketAddress registryLocation, String name){ RemoteObjectRef r = NetworkUtil.registryLookup(registryLocation,name); if (r!=null) return r.localise(registryLocation); return null; } //Registers a remote object r on the registry as well as adding //the id to the list of local objects public boolean registerObject(RemoteObj r, Class<?> remoteObjType) { //if id in use, return false RemoteObjectRef obj = new RemoteObjectRef(localHost,r.getRMIName(),remoteObjType); if(!NetworkUtil.registryRegister(registry, obj)) return false; //Store a local reference to the actual object localObjects.put(obj.name, r); return true; } //Unregister the remote object that was registered with this RMIhandler. If the name is not //registered locally or on the server, returns false. Otherwise, returns true public boolean unregisterObject(RemoteObj r) { if(!localObjects.containsKey(r.getRMIName())) return false; localObjects.remove(r.getRMIName()); return NetworkUtil.registryUnregister(registry, r.getRMIName()); } //Nested class to handle concurrent RMI requests private class ConnectionHandler implements Runnable{ private Socket client; public ConnectionHandler(Socket s){ client = s; } //Handles a single request to an object registered on this RMI handler @Override public void run() { OutputStream out; try { out = client.getOutputStream(); ObjectOutput objOut = new ObjectOutputStream(out); InputStream in = client.getInputStream(); ObjectInput objIn = new ObjectInputStream(in); Object messageObj = objIn.readObject(); if(!RMIMessage.class.isAssignableFrom(messageObj.getClass())){ return; } RMIMessage msg = (RMIMessage) messageObj; if(msg.getMessageType() == RMIMessage.RMIMessageType.INVOKE){ //invoke method with arguments. //get the local object instance given the ID String objID= msg.getOwnerID(); Object obj = localObjects.get(objID); if(obj == null){ //Object not on localhost return; } String methodName = msg.getMethodName(); //get the arguments Object[] arguments = (Object[])msg.getArguments(); //check to see if an argument is a ROR, if it is, then we convert it to a stub. if(arguments!=null){ for(int i = 0; i < arguments.length; i++){ //Remote Parameter, converts to stub if(RemoteObjectRef.class.isAssignableFrom(arguments[i].getClass())){ arguments[i] = ((RemoteObjectRef)arguments[i]).localise(registry); } //Otherwise, we just use the copied object } } Method method = null; Object toReturn = null; try { method = obj.getClass().getMethod(methodName, msg.getParamTypes()); //we lock the object we are invoking synchronized(obj){ toReturn = method.invoke(obj, arguments); } } catch (NoSuchMethodException e){ System.out.println("Method not found"); } catch (SecurityException e1) { System.out.println("Security Exception"); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { //method throws an exception, write exception to client Object[] returnArgs = new Object[1]; returnArgs[0]=e.getCause(); RMIMessage exceptionMessage = new RMIMessage (RMIMessage.RMIMessageType.EXCEPTION, returnArgs,null,methodName, msg.getParamTypes()); objOut.writeObject(exceptionMessage); return; } //return the return value Object[] returnArgs = new Object[1]; if(toReturn != null && RemoteObj.class.isAssignableFrom(toReturn.getClass())){ RemoteObj r = (RemoteObj) toReturn; RemoteObjectRef returnRef = NetworkUtil.registryLookup(registry,r.getRMIName()); returnArgs[0]=returnRef; } else{ returnArgs[0]=toReturn; } RMIMessage returnMessage = new RMIMessage(RMIMessage.RMIMessageType.RETURN,returnArgs, null, methodName, msg.getParamTypes()); objOut.writeObject(returnMessage); } else {System.out.println("BAD REQUEST"); return;} } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } //Simply wait for connections, and process RMI requests @Override public void run() { while(true){ try { Socket clientConnection = server.accept(); ConnectionHandler ch = new ConnectionHandler(clientConnection); Thread t = new Thread(ch); t.start(); } catch (IOException e) { //ignore failed connections, continue to receive connections } } } }
JavaScript
UTF-8
387
2.515625
3
[ "MIT" ]
permissive
client.on('message', message => { if(message.content === "f!bot") { const embed = new Discord.RichEmbed() .setColor("#00FFFF") .setDescription(`**Servers**🌐 **__${client.guilds.size}__** **Users**👥 **__${client.users.size}__** **Channels**📚 **__${client.channels.size}__** `) message.channel.sendEmbed(embed); } });
Java
UTF-8
1,778
2.265625
2
[]
no_license
package com.sanjeet.guqrscanner; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.fragment.app.DialogFragment; import java.util.Objects; public class dialogShow extends DialogFragment { @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the Builder class for convenient dialog construction AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("Permission Required"); builder.setMessage("You need to allow the permission to use the application") .setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts("package","com.sanjeet.guqrscanner" , null); intent.setData(uri); Toast.makeText(getContext(), "Please Allow Permissions", Toast.LENGTH_SHORT).show(); startActivity(intent); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User cancelled the dialog } }); // Create the AlertDialog object and return it return builder.create(); } }
C++
UTF-8
6,491
3.21875
3
[]
no_license
// // LinkedList.hpp // EDIT // // Created by danielle ryall on 2017-01-22. // Copyright © 2017 w0293490. All rights reserved. // #ifndef LinkedList_hpp #define LinkedList_hpp #include <stdio.h> using namespace std; class LinkedList { private: struct Node { string data; Node *next; Node() : next(NULL), data("") {} }; Node *first; public: LinkedList() : first(NULL) {} virtual ~LinkedList() { Node *node = first; while (node != NULL) { Node *temp = node; node = node->next; delete temp; } } void addNodeAtPos(string data, int pos) { Node* prev = new Node(); Node* curr = new Node(); Node* newNode = new Node(); newNode->data = data; int tempPos = 1; curr = first; if(first != NULL) { while(curr->next != NULL && tempPos != pos) { prev = curr; curr = curr->next; tempPos++; } if(pos==1) { // cout << "Adding at Head! " << endl; // Call function to addNode from head; first = newNode; first->next = curr; cout << "Node added at position: " << pos << endl; } else if(curr->next == NULL && pos == tempPos+1) { // cout << "Adding at Tail! " << endl; // Call function to addNode at tail; curr->next = newNode; newNode->next = NULL; } // else if(pos > tempPos+1) // cout << " Position is out of bounds " << endl; // //Position not valid else { prev->next = newNode; newNode->next = curr; // cout << "Node added at position: " << pos << endl; } } else { first = newNode; newNode->next=NULL; cout << "Added at head as list is empty! " << endl; } } void Add(string data) { Node *node = new Node(); node->data = data; if (first == NULL) { first = node; } else { Node *currNode = first; Node *prevNode = NULL; while (currNode != NULL) { prevNode = currNode; currNode = currNode->next; } if (prevNode != NULL) { prevNode->next = node; } } } void DeleteNode(int nodenum) { int index = 0; Node *node = first; Node *prev = NULL; while (node != NULL) { index++; if (index == nodenum) { break; } prev = node; node = node->next; } if (index >= 0) { if (node == first) { first = node->next; } else { prev->next = node->next; } delete node; } } void DeleteNode2(int nodenum) { int index = 1; Node *nodePtr;//used in the traverse Node *previousNode = 0; ////if the list is empty, do nothing if (!first) return; //discover if the first node is being deleted if (index== nodenum)//is it first in list { nodePtr = first->next; delete first; first = nodePtr; }else//if node being deleted is not the first one { nodePtr = first; //traverse and skip non targets while (nodePtr != 0 && index != nodenum) { previousNode = nodePtr; nodePtr = nodePtr->next; index++; }//end while //if nodeptr is not at the end of the list, link the previous node to //the node after nodeptr, the delete nodeptr if (nodePtr) { previousNode->next = nodePtr->next; delete nodePtr; } }//end else } void displayAllLines(int num, int num2) { Node *nodePtr; nodePtr = first; string marker = " "; for (int i = 1; i <= num; i++) { if ((i) == num2) {marker = ">";} if (i < 10) { cout << marker << (i) << " - " << nodePtr->data << endl; } else{ cout << marker << (i) << "- " << nodePtr->data << endl; } nodePtr = nodePtr->next; marker = " "; } } void displayLines(int num1, int num2) { Node *nodePtr; nodePtr = first; int index; if (num2 == 0) { for (int i = 1; i < num1; i++) { nodePtr = nodePtr->next; } cout << num1 << " - " << nodePtr->data << endl; } else { index = num2 - num1; for (int i = 1; i < num1; i++) { nodePtr = nodePtr->next; } for (int i = 0; i <= index; i++) { cout << (num1+i) << " - " << nodePtr->data << endl; nodePtr = nodePtr->next; } } } int lineCounter(LinkedList& list) { int count = 0; Node *currNode = list.first; while (currNode != NULL) { count++; currNode = currNode->next; } return count; } friend ostream& operator<<(ostream& output, LinkedList& list); }; ostream& operator<<(ostream& output, LinkedList& list) { LinkedList::Node *currNode = list.first; while (currNode != NULL) { output << currNode->data << endl; currNode = currNode->next; } return output; } #endif /* LinkedList_hpp */
SQL
UTF-8
6,154
2.796875
3
[]
no_license
--COUNTRY INSERT INTO country (id, name) VALUES ('1', 'Mexico'); INSERT INTO country (id, name) VALUES ('2', 'Colombia'); --STATE INSERT INTO state (id, name, country_id) VALUES ('1', 'Aguascalientes', '1'); INSERT INTO state (id, name, country_id) VALUES ('2', 'Cali', '2'); --CITY INSERT INTO city (id, name, state_id) VALUES ('1', 'Obregon1', '1'); INSERT INTO city (id, name, state_id) VALUES ('2', 'Obregon2', '2'); --COMPANY INSERT INTO company (name, rfc, certificate, location, colony, address, zip, city_id) VALUES ('SHIO BELLEZA INTEGRAL SA DE CV', 'SBI130426ID8', '00001000000407509544', 'loc', 'col', 'dir', '123', '1'); INSERT INTO company (name, rfc, certificate, location, colony, address, zip, city_id) VALUES ('LIBET ALEJANDRA LIRA ANGULO', 'LIAL770809L70', '00001000000304005466', 'loc', 'col', 'dir', '123', '1'); --SUBSIDIARY INSERT INTO subsidiary (id, name, email, phone, mobile, location, colony, address, zip, active, company_id, city_id) VALUES ('1', 'Olivares', 'olivares@shio.com', '3322244', '3187766655', 'loc', 'col', 'dir', '468', '1', '1', '1'); INSERT INTO subsidiary (id, name, email, phone, mobile, location, colony, address, zip, active, company_id, city_id) VALUES ('2', 'Luis Orci', 'luisorci@shio.com', '3322244', '3187766655', 'loc', 'col', 'dir', '468', '1', '1', '1'); INSERT INTO subsidiary (id, name, email, phone, mobile, location, colony, address, zip, active, company_id, city_id) VALUES ('3', 'Dila', 'dila@shio.com', '3322244', '3187766655', 'loc', 'col', 'dir', '468', '1', '1', '1'); INSERT INTO subsidiary (id, name, email, phone, mobile, location, colony, address, zip, active, company_id, city_id) VALUES ('4', 'Reforma', 'reforma@shio.com', '3322244', '3187766655', 'loc', 'col', 'dir', '468', '1', '2', '1'); INSERT INTO subsidiary (id, name, email, phone, mobile, location, colony, address, zip, active, company_id, city_id) VALUES ('5', 'Obregon', 'obregon@shio.com', '3322244', '3187766655', 'loc', 'col', 'dir', '468', '1', '1', '1'); INSERT INTO subsidiary (id, name, email, phone, mobile, location, colony, address, zip, active, company_id, city_id) VALUES ('6', 'Girasol', 'olivares@shio.com', '3322244', '3187766655', 'loc', 'col', 'dir', '468', '1', '1', '1'); --EMPLOYEE INSERT INTO employee (name, email, phone, position, active, subsidiary_id) VALUES ('Wisi', 'wisi@dabalash.org', '123123123', 'Administrador', '1', '1'); INSERT INTO employee (name, email, phone, position, active, subsidiary_id) VALUES ('Empleado 2', 'empleado@dabalash.org', '123123444', 'Administrador', '1', '2'); --CLIENT INSERT INTO client (name, email, phone, mobile, birthdate, country_id, state_id, city_id, location, colony, address, zip, rfc, subsidiary_id, active) VALUES ('Juan Camilo', 'jcamilo@gmail.com', '3335500', '3013336655', '1987-07-04', '1', '1', '1', '1', '1', '1056 Water AV', '123987', 'SBI130426ID8', '1', '0'); INSERT INTO client (name, email, phone, mobile, birthdate, country_id, state_id, city_id, location, colony, address, zip, rfc, subsidiary_id, active) VALUES ('Andres Felipe', 'andres@gmail.com', '2224400', '3184094630', '1987-05-17', '1', '1', '2', '2', '1', '3311 Water AV', '123987', 'SBI130426ID8', '2', '1'); --PRODUCT INSERT INTO product (name, description, codbar, commission, active, price, key, unit) VALUES ('Dabalash', 'Crecimiento de pestanas y cejas', '9001231231239', '10', '1', '1850', '53131638', 'XUN'); --SERVICE INSERT INTO service (name, description, codbar, commission, active, price, time, key, unit) VALUES ('Corte Mujer', '', '123123', '15', '1', '500', '20', '53131638', 'XUN'); --APPOINTMENT INSERT INTO appointment (date, note, rescheduled, client_id, subsidiary_id) VALUES ('2018-03-03', 'Notas', 'true', '1', '1'); INSERT INTO appointment (date, note, rescheduled, client_id, subsidiary_id) VALUES ('2018-03-10', 'Notas', 'false', '2', '2'); --APPOINTMENT ITEM INSERT INTO appointmentitem (time, started, status, service_id, employee_id, appointment_id) VALUES ('2018-03-03 10:15:00', '2018-04-08 23:35:00', 'Iniciada', '1', '1', '1'); INSERT INTO appointmentitem (time, started, status, service_id, employee_id, appointment_id) VALUES ('2018-03-03 11:10:00', '2018-04-08 23:30:00', 'Iniciada', '1 ', '2', '2'); --TRANSACTION INSERT INTO transaction (date, invoice, invoicepdf, canceled, processed, reason, client_id, subsidiary_id) VALUES ('2018-03-03', '123123', '', 'false', 'true', '1', '1', '1'); INSERT INTO transaction (date, invoice, invoicepdf, canceled, processed, reason, client_id, subsidiary_id) VALUES ('2018-03-08', '', '', 'false', 'false', '1', '1', '2'); INSERT INTO transaction (date, invoice, invoicepdf, canceled, processed, reason, client_id, subsidiary_id) VALUES ('2018-03-12', '', '', 'false', 'false', '2', '2', '3'); --TRANSACTION ITEM INSERT INTO transactionitem (type, quantity, price, aditional, anticipated, coupon, dateused, product_id, service_id, employee_id, transaction_id) VALUES ('1', '2', 300, 0, 'true', 'OL1N1521392259269', null, '1', null, '1', '1'); INSERT INTO transactionitem (type, quantity, price, aditional, anticipated, coupon, dateused, product_id, service_id, employee_id, transaction_id) VALUES ('1', '2', 50, 0, 'true', null, null, null, '1', '1', '2'); INSERT INTO transactionitem (type, quantity, price, aditional, anticipated, coupon, dateused, product_id, service_id, employee_id, transaction_id) VALUES ('1', '2', 50, 0, 'false', null, null, '1', null, '1', '2'); --TRANSACTION COUPON INSERT INTO transactioncoupon (code, transaction_id) VALUES ('A00000001112222', '3'); --INVENTORY INSERT INTO inventory (quantity, product_id, subsidiary_id) VALUES ('10', '1', '1'); INSERT INTO inventory (quantity, product_id, subsidiary_id) VALUES ('5', '1', '2'); --ENTRY INSERT INTO entry (date, confirmed, subsidiary_id) VALUES ('2018-03-10', '0', '1'); INSERT INTO entry (date, confirmed, subsidiary_id) VALUES ('2018-04-12', '0', '2'); --ENTRY ITEM INSERT INTO entryitem (quantity, product_id, entry_id) VALUES ('3', '1', '1'); INSERT INTO entryitem (quantity, product_id, entry_id) VALUES ('6', '1', '2'); --COUPON INSERT INTO coupon (code, quantity, available, transactionorigin, transactionused, product_id, service_id, client_id) VALUES ('AAAAAA111222333', '2', '2', '2', null, '1', null, '1');
Python
UTF-8
3,968
2.78125
3
[]
no_license
# coding: utf-8 # In[1]: from collections import namedtuple import pickle # import sys # import math # import re # from nltk import bigrams,trigrams # In[ ]: class LM: def __init__(self, lm_filename): print('Loading language model %s ...' %(lm_filename)) ngram_stats = namedtuple('lm_prob', 'p,bp') self.table = {} with open(lm_filename, 'r', encoding='utf8') as fp: for line in fp: seq = line.strip().split('\t') if len(seq)>=2: (word, prob, backprob) = (tuple(seq[1]), float(seq[0]), float(seq[2] if len(seq)==3 else 0.0)) if len(word)<3: self.table[word] = ngram_stats(prob, backprob) def begin(self,state): return ('<s>', state) def end(self,state): return (state, '</s>') def score_batch(self, seq): ngram_stats = namedtuple('lm_prob', 'p,bp') failed = ngram_stats(0, 'NotFound') score = 0.0 while len(seq)>0: if seq in self.table: return score + self.table[seq].p else: back_prob = self.table.get(seq[:-1], failed).bp if back_prob == 'NotFound': if len(seq)==1: back_prob = -99 else: back_prob = self.score_batch(seq[:-1]) score += back_prob seq = seq[1:] return score def scoring(self, seq, ngnum=2, show=0): # sentence msut be list score = 0.0 pairs = [] for idx in range(len(seq)): if idx==0 and seq[idx]=='<s>': continue seq_idx = 0 if idx<ngnum else idx-ngnum+1 pairs.append(tuple(seq[seq_idx:idx+1])) for pair in pairs: score += self.score_batch(pair) if show==1: print(pair, ":\t", score) if show == 1: print('========') print(seq, ":\t", score) return score # In[96]: class NCM: def __init__(self, channel_filename, ncm_global=[]): print('Loading channel model %s ...' %(channel_filename)) with open(channel_filename, 'rb') as fp: self.table = pickle.load(fp, encoding='utf8') self.ncm_global = ncm_global def get_cands(self, cur_char): cand_dict = dict(self.table.get(cur_char,[])) cur_prob = 1.0 if not cand_dict else cand_dict.pop(cur_char) if not self.ncm_global: query_cands = [(cur_char,cur_prob)] query_cands.extend(cand_dict.items()) else: base = self.ncm_global * (1-len(cand_dict)) + len(cand_dict) query_cands = [(cur_char, self.ncm_global/base)] query_cands.extend((c,(1-self.ncm_global)/base) for c,p in cand_dict.items()) return query_cands # In[ ]: class CASE: def __init__(self, sentence, ncm): assert type(sentence) == str, 'Input must be string' assert len(sentence) > 0, 'Input must have content' self.query=[] self.query.append('<s>') self.query.extend(list(sentence)) self.query.append('</s>') # get candidate self.cands = [] for cur_ch in self.query: self.cands.append(ncm.get_cands(cur_ch)) # In[ ]: if __name__=='__main__': # lm = LM('../sinica.corpus.seg.char.lm') # lm2 = LM2('../sinica.corpus.seg.char.lm') import sys lm = LM(sys.argv[1]) # ncm_filename = 'G:/UDN/training_confusion/channelModel.pkl'
Java
UTF-8
4,771
2.046875
2
[]
no_license
package com.medical.product.adapter; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import androidx.recyclerview.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.RatingBar; import android.widget.TextView; import com.medical.product.R; import com.medical.product.Ui.Product_vendor; import com.medical.product.models.GatterGetVendersModel; import java.util.ArrayList; public class AdapterVenderslist extends RecyclerView.Adapter<AdapterVenderslist.MyViewHolder> { private boolean zoomOut = false; SharedPreferences prefrance, prefranceid; String sharid; private ArrayList<GatterGetVendersModel> recyclerModels; // this data structure carries our title and description Context context; public AdapterVenderslist(ArrayList<GatterGetVendersModel> recyclerModels, Context context) { this.recyclerModels = recyclerModels; this.context = context; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // inflate your custom row layout here return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.myprescription_vender_item_list, parent, false)); } @Override public void onBindViewHolder(final MyViewHolder holder, int position) { // update your data here final GatterGetVendersModel getAddvertise = recyclerModels.get(position); holder.checkbox.setVisibility(View.INVISIBLE); // holder.advertTitle.setText(getAddvertise.getTitle()); if (getAddvertise.getStore_status().equalsIgnoreCase("0")) { holder.stai.setText("( Offline )"); holder.stai.setTextColor(context.getResources().getColor(R.color.red)); } else { holder.stai.setText("( Online )"); holder.stai.setTextColor(context.getResources().getColor(R.color.green)); } holder.txtpharm_name.setText(getAddvertise.getPharm_name()); if (!TextUtils.isEmpty(getAddvertise.getAverage_rating())) { holder.txtaverage_rating.setText(getAddvertise.getAverage_rating()); } else { holder.txtaverage_rating.setText("0"); } holder.txtstore_address.setText(getAddvertise.getStore_address()); holder.txtname.setText(getAddvertise.getName()); float rate = 0.0f; try { rate = Float.parseFloat(getAddvertise.getAverage_rating()); } catch (Exception e) { // or some value to mark this field is wrong. or make a function validates field first ... } if (!TextUtils.isEmpty(getAddvertise.getOffer())) { holder.offer.setVisibility(View.VISIBLE); holder.offer.setText(getAddvertise.getOffer()); } else { holder.offer.setVisibility(View.GONE); } holder.ratingbar.setRating(rate); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { context.startActivity(new Intent(context, Product_vendor.class).putExtra("id", getAddvertise.getId()).putExtra("name", getAddvertise.getPharm_name())); } }); } @Override public int getItemCount() { return recyclerModels.size(); } @Override public int getItemViewType(int position) { return position; // return super.getItemViewType(position); } class MyViewHolder extends RecyclerView.ViewHolder { public TextView txtpharm_name, txtaverage_rating, txtstore_address, txtname, stai, offer; CheckBox checkbox; RatingBar ratingbar; MyViewHolder(View view) { super(view); txtpharm_name = (TextView) itemView.findViewById(R.id.txtpharm_name); txtaverage_rating = (TextView) itemView.findViewById(R.id.txtaverage_rating); txtstore_address = (TextView) itemView.findViewById(R.id.txtstore_address); txtname = (TextView) itemView.findViewById(R.id.txtname); offer = (TextView) itemView.findViewById(R.id.offer); stai = (TextView) itemView.findViewById(R.id.stai); checkbox = (CheckBox) itemView.findViewById(R.id.checkBox); ratingbar = (RatingBar) itemView.findViewById(R.id.ratingbar); } } /*public void filterList(ArrayList<GatterGetFamilyDocumentListModel> filterdNames) { this.recyclerModels = filterdNames; Log.i("ass","notifyDataSetChanged==============="); notifyDataSetChanged(); }*/ }
Java
UTF-8
13,925
2.015625
2
[ "Apache-2.0" ]
permissive
package org.ihtsdo.rvf.importer; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.UUID; import org.ihtsdo.rvf.entity.Assertion; import org.ihtsdo.rvf.entity.ExecutionCommand; import org.ihtsdo.rvf.entity.SimpleAssertion; import org.ihtsdo.rvf.entity.Test; import org.ihtsdo.rvf.entity.TestType; import org.ihtsdo.rvf.service.AssertionService; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import org.jdom2.xpath.XPathExpression; import org.jdom2.xpath.XPathFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.facebook.presto.sql.parser.StatementSplitter; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; /** * An implementation of a {@link org.ihtsdo.rvf.importer.AssertionsDatabaseImporter} that imports older * Release Assertion Toolkit content via XML and SQL files. The XML file defines the assertions and the SQL files are * used to populate the corresponding tests. */ @Service @Transactional public class AssertionsDatabaseImporter { private static final String CREATE_PROCEDURE = "CREATE PROCEDURE"; private static final String JSON_EXTENSION = ".json"; private static final Logger logger = LoggerFactory.getLogger(AssertionsDatabaseImporter.class); private static final String RESOURCE_PATH_SEPARATOR = "/"; protected ObjectMapper objectMapper = new ObjectMapper(); private Map<String, String> lookupMap = new HashMap<>(); @Autowired AssertionService assertionService; public boolean isAssertionImportRequired() { List<Assertion> assertions = assertionService.findAll(); if (assertions == null || assertions.isEmpty()) { return true; } return false; } public void importAssertionsFromFile(final InputStream manifestInputStream, final String sqlResourcesFolderLocation){ // get JDOM document from given manifest file final Document xmlDocument = getJDomDocumentFromFile(manifestInputStream); if(xmlDocument != null) { final XPathFactory factory = XPathFactory.instance(); final XPathExpression expression = factory.compile("//script"); final List<Element> scriptElements = expression.evaluate(xmlDocument); if(scriptElements.size() > 0) { // get various values from script element for(final Element element : scriptElements) { final Assertion assertion = createAssertionFromElement(element); if(assertion != null){ try { logger.info("Created assertion id : " + assertion.getAssertionId()); assert UUID.fromString(element.getAttributeValue("uuid")).equals(assertion.getUuid()); // get Sql file name from element and use it to add SQL test final String sqlFileName = element.getAttributeValue("sqlFile"); logger.info("sqlFileName = " + sqlFileName); String category = element.getAttributeValue("category"); /* We know category is written as file-centric-validation, component-centric-validation, etc We use this to generate the corresponding using folder name = category - validation */ final int index = category.indexOf("validation"); if(index > -1) { category = category.substring(0, index-1); } logger.info("category = " + category); String sqlResourceFileName = sqlResourcesFolderLocation+ RESOURCE_PATH_SEPARATOR + category + RESOURCE_PATH_SEPARATOR + sqlFileName; InputStream sqlInputStream = getClass().getResourceAsStream( sqlResourceFileName); if (sqlInputStream != null) { final String sqlString = readStream(sqlInputStream); // add test to assertion addSqlTestToAssertion(assertion, sqlString); } else { String msg = "Failed to find sql file name from source:" + sqlResourceFileName + " for assertion uuid:" + assertion.getUuid(); logger.error(msg); throw new IllegalStateException(msg); } } catch (final Exception e) { logger.warn("Error reading sql from input stream. Nested exception is : " + e.getMessage()); throw new IllegalStateException("Failed to add sql script test to assertion with uuid:" + assertion.getUuid(), e); } } else{ throw new IllegalStateException("Error creating assertion"); } } // finally print all lookup map contents for debugging - //todo save somewhere? logger.debug("lookupMap = " + lookupMap); } else{ logger.error("There are no script elements to import in the XML file provided. Please note that the " + "XML file should contain element named script"); } } else{ logger.warn("Error generating document from xml file passed : " + manifestInputStream); } } protected Assertion createAssertionFromElement(final Element element){ final String category = element.getAttributeValue("category"); logger.info("category = " + category); final String uuid = element.getAttributeValue("uuid"); logger.info("uuid = " + uuid); final String text = element.getAttributeValue("text"); logger.info("text = " + text); final String sqlFileName = element.getAttributeValue("sqlFile"); logger.info("sqlFileName = " + sqlFileName); final String severity = element.getAttributeValue("severity"); logger.info("severity = " + severity); // add entities using rest client final Assertion assertion = new Assertion(); assertion.setUuid(UUID.fromString(uuid)); assertion.setAssertionText(text); assertion.setKeywords(category); assertion.setSeverity(severity); Assertion assertionFromDb = assertionService.findAssertionByUUID(assertion.getUuid()); if (assertionFromDb == null) { return assertionService.create(assertion); } return assertionFromDb; } public void addSqlTestToAssertion(final Assertion assertion, final String sql){ final List<String> statements = new ArrayList<>(); final StatementSplitter splitter = new StatementSplitter(sql); if (splitter.getCompleteStatements() == null || splitter.getCompleteStatements().isEmpty()) { logger.warn("SQL statements not ending with ;" + sql ); } final StringBuilder storedProcedureSql = new StringBuilder(); boolean storedProcedureFound = false; for(final StatementSplitter.Statement statement : splitter.getCompleteStatements()) { String cleanedSql = statement.statement(); logger.debug("sql to be cleaned:" + cleanedSql); if ( cleanedSql.startsWith(CREATE_PROCEDURE) || cleanedSql.startsWith(CREATE_PROCEDURE.toLowerCase())) { storedProcedureFound = true; } // tokenise and process statement final StringTokenizer tokenizer = new StringTokenizer(cleanedSql); while(tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); // we know sometimes tokenizer messed up and leaves a trailing ), so we clena this up if(token.endsWith(")")){ token = token.substring(0, token.length() - 1); } final Map<String, String> schemaMapping = getRvfSchemaMapping(token); if(schemaMapping.keySet().size() > 0){ lookupMap.put(token, schemaMapping.get(token)); // now replace all instances with rvf mapping if (schemaMapping.get(token) != null) { cleanedSql = cleanedSql.replaceAll(token, schemaMapping.get(token)); } } } cleanedSql = cleanedSql.replaceAll("runid", "run_id"); cleanedSql = cleanedSql.replaceAll("assertionuuid", "assertion_id"); cleanedSql = cleanedSql.replaceAll("assertiontext,", ""); cleanedSql = cleanedSql.replaceAll("'<ASSERTIONTEXT>',", ""); logger.debug("cleaned sql:" + cleanedSql); if (!storedProcedureFound) { statements.add(cleanedSql); } else { storedProcedureSql.append(cleanedSql + ";\n"); } } if (storedProcedureFound && storedProcedureSql.length() > 0) { statements.add(storedProcedureSql.toString()); logger.debug("Stored proecure found:" + storedProcedureSql.toString()); } uploadTest(assertion, sql, statements); } private void uploadTest (Assertion assertion, String orignalSql, List<String> sqlStatements) { final ExecutionCommand command = new ExecutionCommand(); command.setTemplate(orignalSql); command.setStatements(sqlStatements); final Test test = new Test(); test.setType(TestType.SQL); test.setName(assertion.getAssertionText()); test.setCommand(command); // we have to add as a list of tests, since api spec expects list of tests final List<Test> tests = new ArrayList<>(); tests.add(test); //import via assertion service // if( assertionService.findAssertionByUUID(assertion.getUuid()) == null ) { // assertion = assertionService.create(assertion); // } logger.debug("Adding tests for assertion id" + assertion.getAssertionId()); assertionService.addTests(assertion, tests); } protected static Document getJDomDocumentFromFile(final InputStream manifestInputStream){ try { final SAXBuilder sax = new SAXBuilder(); return sax.build(manifestInputStream); } catch (JDOMException | IOException e) { logger.warn("Nested exception is : " + e.fillInStackTrace()); return null; } } protected static String readStream(final InputStream is) throws Exception { final InputStreamReader reader = new InputStreamReader(is); final StringBuilder builder = new StringBuilder(); final char buffer[] = new char[1024]; // Wait for at least 1 byte (e.g. stdin) int n = reader.read(buffer); builder.append(buffer, 0, n); while(reader.ready()) { n = reader.read(buffer); builder.append(buffer, 0, n); } return builder.toString(); } protected Map<String, String> getRvfSchemaMapping(String ratSchema){ String rvfSchema = ""; ratSchema = ratSchema.trim(); final String originalRatSchema = ratSchema; boolean currOrPrevFound = false; if(ratSchema.startsWith("curr_")){ rvfSchema = "<PROSPECTIVE>"; // we strip the prefix - note we don't include _ in length since strings are 0 indexed ratSchema = ratSchema.substring("curr_".length()); currOrPrevFound = true; } else if(ratSchema.startsWith("prev_")){ rvfSchema = "<PREVIOUS>"; // we strip the prefix - note we don't include _ in length since strings are 0 indexed ratSchema = ratSchema.substring("prev_".length()); currOrPrevFound = true; } else if(ratSchema.startsWith("v_")){ // finally process token that represents temp tables - starts with v_ ratSchema = ratSchema.substring("v_".length()); rvfSchema = "<TEMP>" + "." + ratSchema; } // hack to clean up conditions where tokenisation produces schema mappings with ) at the end if(currOrPrevFound && ratSchema.endsWith(")")){ ratSchema = ratSchema.substring(0, ratSchema.lastIndexOf(")")); } // now process for release type suffix if(ratSchema.endsWith("_s")){ // we strip the suffix ratSchema = ratSchema.substring(0, ratSchema.length() - 2); rvfSchema = rvfSchema + "." + ratSchema + "_<SNAPSHOT>"; } else if(ratSchema.endsWith("_d")){ // we strip the suffix ratSchema = ratSchema.substring(0, ratSchema.length() - 2); rvfSchema = rvfSchema + "." + ratSchema + "_<DELTA>"; } else if(ratSchema.endsWith("_f")){ // we strip the suffix ratSchema = ratSchema.substring(0, ratSchema.length() - 2); rvfSchema = rvfSchema + "." + ratSchema + "_<FULL>"; } if (rvfSchema.length() > 0) { final Map<String, String> map = new HashMap<>(); map.put(originalRatSchema, rvfSchema); return map; } else{ return Collections.EMPTY_MAP; } } /** * Attempts to import any .json file in taretDir and child directories * @param targetDir * @param keywords * @throws JsonProcessingException */ public void importAssertionsFromDirectory(File targetDir, String keywords) throws JsonProcessingException { logger.info("Loading json files from {}", targetDir); ObjectMapper mapper = new ObjectMapper(); SimpleAssertion assertion = null; for (File file : targetDir.listFiles()) { if (file.isDirectory()) { importAssertionsFromDirectory(file, keywords + "," + file.getName()); } else { if (file.getName().endsWith(JSON_EXTENSION)) { try { assertion = mapper.readValue(file, SimpleAssertion.class); //If keywords are not specified in the file, take them from the directory name if (assertion.getKeywords() == null || assertion.getKeywords().isEmpty()) { assertion.setKeywords(keywords); } } catch (Exception e) { logger.error("Failed to parse {} ", file.getName(), e); } createOrUpdateAssertion(assertion); } else { logger.info ("Skipping non-json file {}", file.getAbsolutePath()); } } } } @SuppressWarnings("rawtypes") private void createOrUpdateAssertion(SimpleAssertion simpleAssertion) throws JsonProcessingException { Assertion assertion = simpleAssertion.toAssertion(); //Do we need to create that assertion or does it already exist? if ( assertionService.find(assertion.getAssertionId()) != null) { assertionService.delete(assertion); } assertion = assertionService.create(assertion); List<String> tests = simpleAssertion.getTestsAsList(); uploadTest(assertion, null, tests); } }
C++
UTF-8
2,869
3.53125
4
[]
no_license
#include<bits/stdc++.h> using namespace std; struct node { int data; node *next; }; class list { public: node *head, *tail; list() { head=NULL; tail=NULL; } void createnode() { int value; cin>>value; node *temp=new node; temp->data=value; temp->next=NULL; if(head==NULL) { head=temp; tail=temp; temp=NULL; } else { tail->next=temp; tail=temp; } } void display() { node *temp=new node; temp=head; while(temp!=NULL) { cout<<temp->data<<"--->"; temp=temp->next; } } void insert_start(int value) { node *temp=new node; temp->data=value; temp->next=head; head=temp; } void insert_position() { int pos, value; cout<<"Position:"; cin>>pos; cout<<"\nValue:"; cin>>value; node *pre=new node; node *cur=new node; node *temp=new node; cur=head; for(int i=1;i<pos;i++) { pre=cur; cur=cur->next; } temp->data=value; pre->next=temp; temp->next=cur; } void delete_first() { node *temp=new node; temp=head; head=head->next; delete temp; } void delete_last() { node *current=new node; node *previous=new node; current=head; while(current->next!=NULL) { previous=current; current=current->next; } tail=previous; previous->next=NULL; delete current; } void delete_position() { int pos; cin>>pos; node *current=new node; node *previous=new node; current=head; for(int i=1;i<pos;i++) { previous=current; current=current->next; } previous->next=current->next; } }l; int main(){ int ch; while(1) { cout<<"\n1. Wants to input in the linked list\n"; cout<<"2. Wants to delete at a particular position\n"; cout<<"3. Wants to delete the last node\n"; cout<<"4. wants to delete the head node or first node\n"; cout<<"5. Wants to insert at a particular position\n"; cout<<"6. Wants to insert at the begining\n"; cout<<"7. want to display linked list\n"; cout<<"8. want to exit\n "; cin>>ch; switch(ch) { case 1: l.createnode(); break; case 2: l.delete_position(); break; case 5: l.insert_position(); break; case 7: l.display(); break; case 8: exit(1); break; default: cout<<"wrong input"; } } return 0; }
Python
UTF-8
3,433
2.65625
3
[ "MIT" ]
permissive
import numpy import chainer from chainer import functions from chainer import initializers from chainer import links from .conv_block import ConvBlock class TransformModule(chainer.Chain): """Transform module This class produces transform matrix Input is (minibatch, K, N, 1), output is (minibatch, K, K) Args: k (int): hidden layer's coordinate dimension use_bn (bool): use batch normalization or not residual (bool): use residual connection or not """ def __init__(self, k=3, use_bn=True, residual=False): super(TransformModule, self).__init__() initial_bias = numpy.identity(k, dtype=numpy.float32).ravel() with self.init_scope(): self.conv_block1 = ConvBlock(k, 64, ksize=1, use_bn=use_bn, residual=residual) self.conv_block2 = ConvBlock(64, 128, ksize=1, use_bn=use_bn, residual=residual) self.conv_block3 = ConvBlock(128, 1024, ksize=1, use_bn=use_bn, residual=residual) # [Note] # Original paper uses BN for fc layer as well. # https://github.com/charlesq34/pointnet/blob/master/models/transform_nets.py#L34 # This chanier impl. skip BN for fc layer self.fc4 = links.Linear(1024, 512) # self.bn4 = links.BatchNormalization(512) self.fc5 = links.Linear(512, 256) # self.bn5 = links.BatchNormalization(256) # initial output of transform net should be identity self.fc6 = links.Linear( 256, k * k, initialW=initializers.Zero(dtype=numpy.float32), initial_bias=initial_bias) self.k = k def __call__(self, x): # reference --> x: (minibatch, N, 1, K) <- original tf impl. # x: (minibatch, K, N, 1) <- chainer impl. # N - num_point # K - feature degree (this is 3 for xyz input, 64 for middle layer) h = self.conv_block1(x) h = self.conv_block2(h) h = self.conv_block3(h) h = functions.max_pooling_2d(h, ksize=h.shape[2:]) # h: (minibatch, K, 1, 1) h = functions.relu(self.fc4(h)) h = functions.relu(self.fc5(h)) h = self.fc6(h) bs, k2 = h.shape assert k2 == self.k ** 2 h = functions.reshape(h, (bs, self.k, self.k)) return h class TransformNet(chainer.Chain): """Transform Network This class can be used for Both InputTransformNet & FeatureTransformNet Input is (minibatch, K, N, 1), output is (minibatch, K, N, 1), which is transformed Args: k (int): hidden layer's coordinate dimension use_bn (bool): use batch normalization or not residual (bool): use residual connection or not """ def __init__(self, k=3, use_bn=True, residual=False): super(TransformNet, self).__init__() with self.init_scope(): self.trans_module = TransformModule( k=k, use_bn=use_bn, residual=residual) def __call__(self, x): t = self.trans_module(x) # t: (minibatch, K, K) # x: (minibatch, K, N, 1) # h: (minibatch, K, N) # K = in_dim h = functions.matmul(t, x[:, :, :, 0]) bs, k, n = h.shape h = functions.reshape(h, (bs, k, n, 1)) return h, t
Python
UTF-8
57
3.40625
3
[]
no_license
a = int(input()) for i in range(a):print(" "*i+"*"*(a-i))
C++
UTF-8
971
3.03125
3
[ "Unlicense" ]
permissive
#include "SpriteLoader.h" std::shared_ptr<sf::Sprite> SpriteLoader::GetSprite(std::string filename) { std::shared_ptr<sf::Texture> texture; filename = "../Assets/" + filename + ".png"; std::map<std::string, std::shared_ptr<sf::Texture>>::iterator textureIterator = textures.find(filename); if (textureIterator != textures.end()) { std::cout << "Reused file: " + filename << std::endl; return std::make_shared<sf::Sprite>(sf::Sprite(*textureIterator->second)); } else { return std::make_shared<sf::Sprite>(sf::Sprite(*loadTexture(filename))); } } std::shared_ptr<sf::Texture> SpriteLoader::loadTexture(std::string filename) { std::shared_ptr<sf::Texture> texture = std::make_shared<sf::Texture>(sf::Texture()); if (!texture->loadFromFile(filename)) { std::cout << "Error loading file: " + filename << std::endl; } else { std::cout << "Successfully loaded file: " + filename << std::endl; } textures[filename] = texture; return texture; }
TypeScript
UTF-8
1,618
2.9375
3
[ "MIT" ]
permissive
export = tree_model; declare class tree_model<T> { constructor(config?: tree_model.Config<T>); public parse(model: T): tree_model.Node<T>; } declare namespace tree_model { export interface Config<T> { childrenPropertyName?: string; modelComparatorFn?: (elementToCompareWith: T, elementToInsert: T) => number; } export interface Node<T> { config: Config<T>; model: T; children: Array<Node<T>>; parent: Node<T>; isRoot(): boolean; hasChildren(): boolean; addChild(child: Node<T>): Node<T>; addChildAtIndex(child: Node<T>, index: number): Node<T>; setIndex(index: number): Node<T>; getPath(): Array<Node<T>>; getIndex(): number; // walk, all and first use nasty parseArgs logic... walk(callback: (node: Node<T>) => boolean, context?: any): void; walk( options: WalkOptions, callback: (node: Node<T>) => boolean, context?: any ): void; all(callback: (node: Node<T>) => boolean, context?: any): Array<Node<T>>; all( options: WalkOptions, callback: (node: Node<T>) => boolean, context?: any ): Array<Node<T>>; first( callback: (node: Node<T>) => boolean, context?: any ): Node<T> | undefined; first( options: WalkOptions, callback: (node: Node<T>) => boolean, context?: any ): Node<T> | undefined; drop(): Node<T>; } export enum WalkStrategies { PRE = "pre", POST = "post", BREADTH = "breadth" } export interface WalkOptions { strategy: WalkStrategies; } }
Java
UTF-8
361
2.875
3
[ "Apache-2.0" ]
permissive
package cn.edu.sdut.softlab.oopbasic.multiinherit; /** * 本类演示了使用内部类实现多继承的方法 . * * @author Su Baochen */ public class SmartPrinterClient { /** * 程序执行入口. * * @param args 命令行参数 */ public static void main(String[] args) { SmartPrinter sp = new SmartPrinter(); sp.print(); sp.copy(); } }
Java
UTF-8
1,935
2.734375
3
[ "MIT" ]
permissive
package de.nordakademie.informaticup.pandemicfighter.gameengine.elements.events; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class UprisingEventTest { private UprisingEvent uprisingEvent; private UprisingEvent uprisingEvent2; private UprisingEvent uprisingEvent3; @Before public void setUp() throws Exception { uprisingEvent = new UprisingEvent(20, 4); uprisingEvent2 = new UprisingEvent(45, 76); uprisingEvent3 = new UprisingEvent(7, 90); } @Test public void getParticipants() { assertEquals(20, uprisingEvent.getParticipants()); assertEquals(45, uprisingEvent2.getParticipants()); assertEquals(7, uprisingEvent3.getParticipants()); } @Test public void getParticipantsFalseTest() { assertNotEquals(45, uprisingEvent.getParticipants()); assertNotEquals(54, uprisingEvent2.getParticipants()); assertNotEquals(6, uprisingEvent3.getParticipants()); } @Test public void getSinceRound(){ assertEquals(4, uprisingEvent.getSinceRound()); assertEquals(76, uprisingEvent2.getSinceRound()); assertEquals(90, uprisingEvent3.getSinceRound()); } @Test public void getSinceRoundFalseTest(){ assertNotEquals(5, uprisingEvent.getSinceRound()); assertNotEquals(67, uprisingEvent2.getSinceRound()); assertNotEquals(88, uprisingEvent3.getSinceRound()); } @Test public void getType() { assertEquals("uprising", uprisingEvent.getType()); assertEquals("uprising", uprisingEvent2.getType()); assertEquals("uprising", uprisingEvent3.getType()); } @Test public void getTypeFalseTest() { assertNotEquals("up", uprisingEvent.getType()); assertNotEquals("rising", uprisingEvent2.getType()); assertNotEquals("ur", uprisingEvent3.getType()); } }
C
UTF-8
2,543
2.78125
3
[]
no_license
/* * Bluetooth.c * * Created on: Aug 25, 2020 * Author: Dream */ #include "macro.h" #include "string.h" #include "stdio.h" #define BUFFER_SIZE 255 uint8_t receive_buff[BUFFER_SIZE]; extern DMA_HandleTypeDef hdma_usart1_rx; extern UART_HandleTypeDef huart1; void bluetooth_DMA(UART_HandleTypeDef *huart) { __HAL_UART_ENABLE_IT(huart, UART_IT_IDLE); HAL_UART_Receive_DMA(huart, (uint8_t*) receive_buff, BUFFER_SIZE); } //自己定义的DMA处理函数 //在USART1_IRQHandler()中添加本函数,用来处理串口空闲中断 void myUart_DMA(UART_HandleTypeDef *huart) { if (huart->Instance == USART1) { if (RESET != __HAL_UART_GET_FLAG(huart, UART_FLAG_IDLE)) //判断是不是串口空闲中断 { __HAL_UART_CLEAR_IDLEFLAG(huart); //清楚串口空闲中断标志 myUart_DMA_Callback(huart); } } } void myUart_DMA_Callback(UART_HandleTypeDef *huart) { HAL_UART_DMAStop(huart); // uint8_t buff; uint8_t data_length = BUFFER_SIZE - __HAL_DMA_GET_COUNTER(&hdma_usart1_rx); //计算收到数据的长度 printf("length: %d", data_length); HAL_UART_Transmit(huart, receive_buff, data_length, 0x200); //测试用,发出接收到的数据 printf("/r/n"); //添加处理接收数据的代码,接收数据存在receive_buff内 // if (data_length == 1) //判断接收数据长度,1为指令模式 // { //// buff = receive_buff[0]; //// switch (buff) //// { //// case 1: //// HAL_GPIO_TogglePin(LED_GPIO_Port, LED_Pin); ////// HAL_UART_Transmit(huart, buff, data_length, 0x200); //// printf("%d", 22); //// break; //// case 2: //// HAL_GPIO_TogglePin(LED_GPIO_Port, LED_Pin); //// HAL_UART_Transmit(huart, buff, data_length, 0x200); //// break; //// case 3: //// HAL_GPIO_TogglePin(LED_GPIO_Port, LED_Pin); //// HAL_UART_Transmit(huart, buff, data_length, 0x200); //// break; //// default: //// HAL_UART_Transmit(huart, buff, data_length, 0x200); //// } // } // else // { // HAL_UART_Transmit(huart, receive_buff, data_length, 0x200); // } //-------------------------------------------------- memset(receive_buff, 0, data_length); //清零接收缓冲区 data_length = 0; HAL_UART_Receive_DMA(huart, (uint8_t*) receive_buff, 255); //重新开启DMA传输,每次255字节数 } #ifdef __GNUC__ #define PUTCHAR_PROTOTYPE int __io_putchar(int ch) #else #define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f) #endif PUTCHAR_PROTOTYPE { HAL_UART_Transmit(&huart1, (uint8_t*) &ch, 1, 0xffff); return ch; }
Java
UTF-8
162
1.742188
2
[ "Apache-2.0" ]
permissive
package personal.common; import lombok.Builder; import lombok.Data; @Builder @Data public class DLNode { private int value; private LNode next, prev; }
Java
UTF-8
3,185
2.359375
2
[]
no_license
/** * IPLocationCity.java created by liu kaixuan(liukaixuan@gmail.com) at 10:28:34 AM on Jul 8, 2008 */ package com.guzzservices.business; import java.io.Serializable; /** * * IP范围断对应的地理位置 * * @author liu kaixuan(liukaixuan@gmail.com) * @date Jul 8, 2008 10:28:34 AM * @hibernate.class table="commonIPLocationCity" */ public class IPLocationCity implements Serializable, Comparable<IPLocationCity> { private int id ; private String startIP ; private String endIP ; private long startIPSeq ; private long endIPSeq ; private long ipRange ; private String cityName ; private String detailLocation ; private String cityMarker ; private String provider ; private String areaName ; public int compareTo(IPLocationCity otherCity) { //startIPSeq大则算大;如果startIPSeq相同,ipRange越小,则算越大。 if(otherCity == null) return 1 ; if(this == otherCity) return 0 ; if(this.startIPSeq == otherCity.startIPSeq){ if(this.ipRange > otherCity.ipRange){ return -1 ; }else if(this.ipRange == otherCity.ipRange){ return 0 ; }else{ return 1 ; } }else{ if(this.startIPSeq > otherCity.startIPSeq){ return 1 ; }else if(this.startIPSeq == otherCity.startIPSeq){ return 0 ; }else{ return -1 ; } } } public boolean equals(Object obj) { if(obj instanceof IPLocationCity){ return compareTo((IPLocationCity) obj) == 0 ; } return false ; } /** * @hibernate.id generator-class="native" */ public int getId() { return id; } public void setId(int id) { this.id = id; } /** * @hibernate.property */ public String getStartIP() { return startIP; } public void setStartIP(String startIP) { this.startIP = startIP; } /** * @hibernate.property */ public String getEndIP() { return endIP; } public void setEndIP(String endIP) { this.endIP = endIP; } /** * @hibernate.property */ public long getStartIPSeq() { return startIPSeq; } public void setStartIPSeq(long startIPSeq) { this.startIPSeq = startIPSeq; } /** * @hibernate.property */ public long getEndIPSeq() { return endIPSeq; } public void setEndIPSeq(long endIPSeq) { this.endIPSeq = endIPSeq; } /** * @hibernate.property */ public long getIpRange() { return ipRange; } public void setIpRange(long ipRange) { this.ipRange = ipRange; } /** * @hibernate.property */ public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName; } /** * @hibernate.property */ public String getDetailLocation() { return detailLocation; } public void setDetailLocation(String detailLocation) { this.detailLocation = detailLocation; } /** * @hibernate.property */ public String getProvider() { return provider; } public void setProvider(String provider) { this.provider = provider; } public String getCityMarker() { return cityMarker; } public void setCityMarker(String cityMarker) { this.cityMarker = cityMarker; } public String getAreaName() { return areaName; } public void setAreaName(String areaName) { this.areaName = areaName; } }
C#
UTF-8
503
3.25
3
[]
no_license
public int TotalQuestions(Category category) { var totalQuestions = category.Questions.Count; foreach (var innerCategory in category.Categories) { totalQuestions += TotalQuestions(innerCategory); } return totalQuestions; //OR //return category.Questions.Count + category.Categories.Sum(innerCategory => TotalQuestions(innerCategory)); }
Python
UTF-8
281
2.609375
3
[]
no_license
import numpy as np Y = np.arange(1,25).reshape(4,6) print(Y) m = Y.shape[0] permutation = list(np.random.permutation(m)) print(permutation) shuffled_Y = Y[permutation,:] print(shuffled_Y) shuffled_Y = Y[:,permutation] print(shuffled_Y) # 原来一切的一切都是方向的问题
PHP
UTF-8
4,123
2.640625
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace Stu\Module\Ship\Action\SalvageEmergencyPods; use Stu\Lib\Map\DistanceCalculationInterface; use Stu\Orm\Entity\ShipInterface; use Stu\Orm\Entity\TradePostInterface; use Stu\Orm\Repository\ShipCrewRepositoryInterface; final class TransferToClosestLocation { private ClosestLocations $closestLocations; private DistanceCalculationInterface $distanceCalculation; private ShipCrewRepositoryInterface $shipCrewRepository; public function __construct( ClosestLocations $closestLocations, DistanceCalculationInterface $distanceCalculation, ShipCrewRepositoryInterface $shipCrewRepository ) { $this->closestLocations = $closestLocations; $this->distanceCalculation = $distanceCalculation; $this->shipCrewRepository = $shipCrewRepository; } public function transfer( ShipInterface $ship, ShipInterface $target, int $crewCount, TradePostInterface $closestTradepost ): string { $closestColony = null; $colonyDistance = null; $closestColonyArray = $this->closestLocations->searchClosestUsableColony($ship, $crewCount); if ($closestColonyArray !== null) { [$colonyDistance, $closestColony] = $closestColonyArray; } $stationDistance = null; $closestStation = null; $closestStationArray = $this->closestLocations->searchClosestUsableStation($ship, $crewCount); if ($closestStationArray !== null) { [$stationDistance, $closestStation] = $closestStationArray; } $tradepostDistance = $this->distanceCalculation->shipToShipDistance($ship, $closestTradepost->getShip()); $minimumDistance = $this->getMinimumDistance($colonyDistance, $stationDistance, $tradepostDistance); //transfer to closest colony if ($colonyDistance === $minimumDistance && $closestColony !== null) { foreach ($target->getCrewlist() as $crewAssignment) { if ($crewAssignment->getCrew()->getUser() === $ship->getUser()) { $crewAssignment->setColony($closestColony); $crewAssignment->setShip(null); $this->shipCrewRepository->save($crewAssignment); } } return sprintf( _('Deine Crew wurde geborgen und an die Kolonie "%s" (%s) überstellt'), $closestColony->getName(), $closestColony->getSectorString() ); } //transfer to closest station if ($stationDistance === $minimumDistance && $closestStation !== null) { foreach ($target->getCrewlist() as $crewAssignment) { if ($crewAssignment->getCrew()->getUser() === $ship->getUser()) { $crewAssignment->setShip($closestStation); $this->shipCrewRepository->save($crewAssignment); } } return sprintf( _('Deine Crew wurde geborgen und an die Station "%s" (%s) überstellt'), $closestStation->getName(), $closestStation->getSectorString() ); } //transfer to closest tradepost foreach ($target->getCrewlist() as $crewAssignment) { if ($crewAssignment->getCrew()->getUser() === $ship->getUser()) { $crewAssignment->setShip(null); $crewAssignment->setTradepost($closestTradepost); $this->shipCrewRepository->save($crewAssignment); } } return sprintf( _('Deine Crew wurde geborgen und an den Handelsposten "%s" (%s) überstellt'), $closestTradepost->getName(), $closestTradepost->getShip()->getSectorString() ); } private function getMinimumDistance(?int $colonyDistance, ?int $stationDistance, int $tradePostDistance): int { return min( $colonyDistance ?? PHP_INT_MAX, $stationDistance ?? PHP_INT_MAX, $tradePostDistance ); } }
Markdown
UTF-8
1,065
2.765625
3
[]
no_license
* Grab http://nodebeginner.org. Copy the contents of `div#book` into `wholebook.html`. * Add `wholebook.html` to `Book.txt`. * Remove the title and author link. * promote all headers (`h2` => `h1`, `h3` => `h2`, etc.). * Promote <h3>Handling POST requests</h3> and <h3>Handling file uploads</h3> * Remove TOC divs * Replace &ouml; with oe Dear readers, I'm happy to announce that the final version of The Node Beginner Book is now available on Leanpub. As always, this update is free of charge for existing readers. The main changes start at page 48 with chapter "Handling file uploads". Furthermore, the code samples have been improved in that they now fit the page width in every case. The table of contents is now more detailed, allowing you to directly jump to every section of interest. Please email me at manuel@kiessling.net for feedback, corrections, ideas, or anything else. PS: "Final version" means that the content is now complete - corrections or updates that are neccessary to reflect changes in Node.js will be released in the future. Regards, Manuel Kiessling
TypeScript
UTF-8
9,390
2.78125
3
[]
no_license
import { GameState } from './game-state.enum' import {getRandomInt} from '../lib/random-integer' import {mod} from '../lib/mod'; import {Deck} from './deck'; import { GameInterface } from './game-interface'; export class Uno implements GameInterface { private state = initialState; private colours = { "b": "Blue", "g": "Green", "r": "Red", "y": "Yellow", } public constructor(state = null) { if(state) { this.state = state; } this.state = Object.assign({}, initialState, state); this.state.game = 'uno'; } public setId(id) { this.state.id = id; return this; } public id() { return this.state.id; } public getState() { return this.state; } public getPlayerState(playerId) { let playerState = { ...this.state, thisPlayer: playerId, cardsInPlayersHand: this.state.cardsInHand[playerId], cardsInHand: this.state.players.reduce((cardsInHand, player) => { cardsInHand[player.id] = this.state.cardsInHand[player.id] ? this.state.cardsInHand[player.id].length : 0; return cardsInHand; }, {}) } delete playerState['cardsInDeck']; return playerState; } public getGame() { return this.state.game; } public startGame() { //If game has already started, just return current state. if(this.state.state !== GameState.AWAITING_PLAYERS) { return this.state; } let deck = new Deck(UnoCards); deck.shuffle(); console.log("this.state.players"); console.log(this.state.players); let playersHands = this.state.players.reduce((hands, player) => { hands[player.id] = deck.deal(7) return hands; }, {}) let discardPile = deck.deal(); let startingPlayer = getRandomInt(0, this.state.players.length); this.state = { ...this.state, state: GameState.PLAY, playersTurn: startingPlayer, playerCounter: startingPlayer, cardsInDeck: deck.getCards(), cardsInHand: playersHands, discardPile: discardPile, winner: "?", msg: null } return this.state; } public joinGame(playerName: string, playerId) { const player = { name: playerName, id: playerId } if (this.state.players.some((player) => player.id == playerId)) { return this.state; } if(this.state.state !== GameState.AWAITING_PLAYERS) { throw Error('Cannot join game that is already in progress') } let players = this.state.players; players.push(player); this.state = {...this.state, players: players, msg: null}; return this.state; } public playCard(playerId, card) { const [playedNumber, playedColour] = card.split(''); const [topNumber, topColour] = this.state.discardPile[0].split(''); if (playedNumber !== '*' && playedNumber !== '?' && playedNumber !== topNumber && playedColour !== topColour) { return this.state; } // Must be player's turn if(this.state.players[this.state.playersTurn].id !== playerId) { return this.state; } let found = this.state.cardsInHand[playerId].find((cardInHand) => card.replace(/([\?\*])([rbyg])(\d)/i, '$1?$3') == cardInHand); if(!found) { return this.state; } let hand = this.state.cardsInHand[playerId].filter((cardInHand) => found != cardInHand); let cardsInHand = { ...this.state.cardsInHand, [playerId]: hand }; let discardPile = [...this.state.discardPile]; discardPile.unshift(card); this.state.discardPile = discardPile; let message = `${this.state.players[this.state.playersTurn].name} has played a ${this.colours[playedColour]} ${playedNumber}`; //change direction if(card[0] === "c") { this.state.direction = -1 * this.state.direction; message = `${this.state.players[this.state.playersTurn].name} has played a ${this.colours[playedColour]} Change-direction card`; } let deck = new Deck(this.state.cardsInDeck); let playerCounter = this.state.playerCounter + this.state.direction; let nextPlayer = mod(this.state.playersTurn + this.state.direction, this.state.players.length); //+2 cards if(card[0] === "+") { message = `${this.state.players[this.state.playersTurn].name} has played a ${this.colours[playedColour]} +2`; let resp = this.dealAndReshuffle(2); cardsInHand[this.state.players[nextPlayer].id] = cardsInHand[this.state.players[nextPlayer].id].concat(resp.dealt); deck = resp.deck; // Skip next player playerCounter = (playerCounter + this.state.direction); nextPlayer = mod(nextPlayer + this.state.direction, this.state.players.length); } //+4 cards if(card[0] === "*") { message = `${this.state.players[this.state.playersTurn].name} has played a +4 card and changed the colour to ${this.colours[playedColour]}`; let resp = this.dealAndReshuffle(4); cardsInHand[this.state.players[nextPlayer].id] = cardsInHand[this.state.players[nextPlayer].id].concat(resp.dealt); deck = resp.deck; // Skip next player playerCounter = (playerCounter + this.state.direction); nextPlayer = mod(nextPlayer + this.state.direction, this.state.players.length); } //miss a turn if(card[0] === "x") { message = `${this.state.players[this.state.playersTurn].name} has played a ${this.colours[playedColour]} Miss-a-go`; // Skip next player playerCounter = (playerCounter + this.state.direction); nextPlayer = mod(nextPlayer + this.state.direction, this.state.players.length); } //Change colour if(card[0] === "?") { message = `${this.state.players[this.state.playersTurn].name} has changed the colour to ${this.colours[playedColour]}`; } this.state = { ...this.state, state: hand.length === 0 ? GameState.GAME_OVER : this.state.state, winner: hand.length === 0 ? playerId : '?', playersTurn: nextPlayer, playerCounter: playerCounter, cardsInHand: cardsInHand, discardPile: discardPile, cardsInDeck: deck.getCards(), msg: message } return this.state; } public pickUp(playerId) { if(this.state.players[this.state.playersTurn].id !== playerId) { return this.state; } let resp = this.dealAndReshuffle(1); this.state.cardsInHand[playerId] = this.state.cardsInHand[playerId].concat(resp.dealt); let message = `${this.state.players[this.state.playersTurn].name} has picked up a card`; this.state = { ...this.state, playerCounter: (this.state.playerCounter + this.state.direction), playersTurn: mod((this.state.playersTurn + this.state.direction), this.state.players.length), cardsInDeck: resp.deck.getCards(), msg: message } return this.state; } private dealAndReshuffle(n) { let deck = new Deck(this.state.cardsInDeck); let remainingInDeck = Math.min(n, deck.countRemaining()); let cards = deck.deal(remainingInDeck); if(deck.countRemaining() === 0) { let newDeckCards = []; while(this.state.discardPile.length > 1) { newDeckCards.push(this.state.discardPile.pop()); } deck = new Deck(newDeckCards); if(n > cards.length) { cards = cards.concat(deck.deal(n - cards.length)); } } return {'deck': deck, 'dealt': cards}; } } const initialState = { id: null, game: "uno", state: GameState.AWAITING_PLAYERS, players: [], playersTurn: null, playerCounter:0, cardsInHand: { }, cardsInDeck: [], discardPile: [], winner: '?', direction: 1, msg: null }; export const UnoCards = [ "0r", "1r0", "1r1", "2r0", "2r1", "3r0", "3r1", "4r0", "4r1", "5r0", "5r1", "6r0", "6r1", "7r0", "7r1", "8r0", "8r1", "9r0", "9r1", "+r0", "+r1", "cr0", "cr1", "xr0", "xr1", "0g", "1g0", "1g1", "2g0", "2g1", "3g0", "3g1", "4g0", "4g1", "5g0", "5g1", "6g0", "6g1", "7g0", "7g1", "8g0", "8g1", "9g0", "9g1", "+g0", "+g1", "cg0", "cg1", "xg0", "xg1", "0b", "1b0", "1b1", "2b0", "2b1", "3b0", "3b1", "4b0", "4b1", "5b0", "5b1", "6b0", "6b1", "7b0", "7b1", "8b0", "8b1", "9b0", "9b1", "+b0", "+b1", "cb0", "cb1", "xb0", "xb1", "0y", "1y0", "1y1", "2y0", "2y1", "3y0", "3y1", "4y0", "4y1", "5y0", "5y1", "6y0", "6y1", "7y0", "7y1", "8y0", "8y1", "9y0", "9y1", "+y0", "+y1", "cy0", "cy1", "xy0", "xy1", "??0", "??1", "??2", "??3", "*?0", "*?1", "*?2", "*?3" ]
Java
UTF-8
283
1.789063
2
[]
no_license
package com.firenay.boot.mapper; import com.firenay.boot.entity.Emp; import org.apache.ibatis.annotations.Mapper; import java.util.List; /** * <p>Title: EmpMapper</p> * Description: * date:2020/5/17 11:58 */ @Mapper public interface EmpMapper { List<Emp> selectAll(); }
Markdown
UTF-8
4,414
3.40625
3
[]
no_license
## 12 - 编译报错,类型判断只能用于接口 ## 13 - 编译报错,函数返回值只要有一个拥有命名,其他均需要命名 ## 14 - defer在函数返回后,函数结束前执行 - defer只会修改命名返回值 ## 15 ```go package main import "fmt" func main() { list := new([]int) *list = append(*list, 1) fmt.Println(*list) } ``` ```go package main import "fmt" func main() { list := make([]int, 0) list = append(list, 1) fmt.Println(list) } ``` ## 16 ```go package main import "fmt" func main() { s1 := []int{1, 2, 3} s1 = append(s1, 4, 5) fmt.Println(s1) } ``` ```go package main import "fmt" func main() { s1 := []int{1, 2, 3} s2 := []int{4, 5} s1 = append(s1, s2...) fmt.Println(s1) } ``` ## 17 ```go package main import "fmt" type A struct { age int name string } type B struct { age int name string } func main() { sn1 := A{age: 11, name: "qq"} sn2 := B{age: 11, name: "qq"} if sn1 == sn2 { // compile error: mismatched type fmt.Println("sn1 == sn2") } } ``` - 说明 - 结构体比较 - 顺序 - 可比较 - 不可比较:slice,map - 结果 - 编译报错 ## 18 ```go package main import "fmt" func Foo(x interface{}) { if x == nil { fmt.Println("empty interface") return } fmt.Println("non-empty interface") } func main() { var x *int = nil Foo(x) // non-empty interface Foo(nil) // nil interface, empty interface } ``` ## 19 - nil可作为slice,map,channel,pointer,function,interface - string的空值不为nil ## 20 - 0, 1, zz, zz, 4 ## 21 - 相当于var size := 1024 ## 22 - const不可取地址 - var可取地址 ## 23 - 不要使用goto ## 24 ```go package main import "fmt" func main() { type MyInt1 int type MyInt2 = int var i int = 9 var i1 MyInt1 = MyInt1(i) var i2 MyInt2 = i fmt.Println(i1, i2) } ``` ## 25 ```go package main import "fmt" type User struct {} type MyUser1 User type MyUser2 = User func (i MyUser1) m1(){ fmt.Println("MyUser1.m1") } func (i User) m2(){ fmt.Println("User.m2") } func main() { var i1 MyUser1 var i2 MyUser2 i1.m1() i2.m2() i1.m2() // compile error: no method m2 } ``` ## 26 ```go package main import "fmt" type T1 struct {} type T2 = T1 type MyStruct struct { T1 T2 } func (t T1) m1(){ fmt.Println("T1.m1") } func main() { my := MyStruct{} my.m1() // compile error: ambiguous selector } ``` ## 27 ```go package main import ( "errors" "fmt" ) var ErrDidNotWork = errors.New("did not work") func DoTheThing(reallyDoIt bool) (err error) { if reallyDoIt { result, err := tryTheThing() if err != nil || result != "it worked" { err = ErrDidNotWork } } return err } func tryTheThing() (string,error) { return "", ErrDidNotWork } func main() { fmt.Println(DoTheThing(true)) // nil fmt.Println(DoTheThing(false)) // nil } ``` ```go package main import ( "errors" "fmt" ) var ErrDidNotWork = errors.New("did not work") func DoTheThing(reallyDoIt bool) (err error) { var result string if reallyDoIt { result, err = tryTheThing() if err != nil || result != "it worked" { err = ErrDidNotWork } } return err } func tryTheThing() (string,error) { return "", ErrDidNotWork } func main() { fmt.Println(DoTheThing(true)) // did not work fmt.Println(DoTheThing(false)) // nil } ``` ## 28 ```go package main func test() []func() { var funs []func() for i := 0; i < 2; i++ { funs = append(funs, func() { println(&i, i) }) } return funs } func main() { funs := test() for _, f := range funs { f() } } ``` ```go package main func generateFunc(i int) func() { return func() { println(&i, i) } } func test() []func() { var funs []func() for i := 0; i < 2; i++ { funs = append(funs, generateFunc(i)) } return funs } func main() { funs := test() for _, f := range funs { f() } } ``` ```go package main func test() []func() { var funs []func() var x int for i := 0; i < 2; i++ { x = i funs = append(funs, func() { println(&x, x) }) } return funs } func main() { funs := test() for _, f := range funs { f() } } ``` ```go package main func test() []func() { var funs []func() for i := 0; i < 2; i++ { x := i funs = append(funs, func() { println(&x, x) }) } return funs } func main() { funs := test() for _, f := range funs { f() } } ``` ## 29 - 100 - 110 ## 30 - defer panic
Java
UTF-8
4,219
3.390625
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package by.creepid.algorithms.graph.shortestway; import by.creepid.algorithms.graph.directed.Digraph; /** * The <tt>Topological</tt> class represents a data type for determining a * topological order of a directed acyclic graph (DAG). Recall, a digraph has a * topological order if and only if it is a DAG. The <em>hasOrder</em> operation * determines whether the digraph has a topological order, and if so, the * <em>order</em> operation returns one. * <p> * This implementation uses depth-first search. The constructor takes time * proportional to <em>V</em> + <em>E</em> * (in the worst case), where <em>V</em> is the number of vertices and * <em>E</em> is the number of edges. Afterwards, the <em>hasOrder</em> and * <em>rank</em> operations takes constant time; the <em>order</em> operation * takes time proportional to <em>V</em>. * <p> * See {@link DirectedCycle}, {@link DirectedCycleX}, and * {@link EdgeWeightedDirectedCycle} to compute a directed cycle if the digraph * is not a DAG. See {@link TopologicalX} for a nonrecursive queue-based * algorithm to compute a topological order of a DAG. * <p> * For additional documentation, see * <a href="http://algs4.cs.princeton.edu/42digraph">Section 4.2</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class Topological { private Iterable<Integer> order; // topological order private int[] rank; // rank[v] = position of vertex v in topological order /** * Determines whether the digraph <tt>G</tt> has a topological order and, if * so, finds such a topological order. * * @param G the digraph */ public Topological(Digraph G) { DirectedCycle finder = new DirectedCycle(G); if (!finder.hasCycle()) { DepthFirstOrder dfs = new DepthFirstOrder(G); order = dfs.reversePost(); rank = new int[G.vertexCount()]; int i = 0; for (int v : order) { rank[v] = i++; } } } /** * Determines whether the edge-weighted digraph <tt>G</tt> has a topological * order and, if so, finds such an order. * * @param G the edge-weighted digraph */ public Topological(EdgeWeightedDigraph G) { EdgeWeightedDirectedCycle finder = new EdgeWeightedDirectedCycle(G); if (!finder.hasCycle()) { DepthFirstOrder dfs = new DepthFirstOrder(G); order = dfs.reversePost(); } } /** * Returns a topological order if the digraph has a topologial order, and * <tt>null</tt> otherwise. * * @return a topological order of the vertices (as an interable) if the * digraph has a topological order (or equivalently, if the digraph is a * DAG), and <tt>null</tt> otherwise */ public Iterable<Integer> order() { return order; } /** * Does the digraph have a topological order? * * @return <tt>true</tt> if the digraph has a topological order (or * equivalently, if the digraph is a DAG), and <tt>false</tt> otherwise */ public boolean hasOrder() { return order != null; } /** * The the rank of vertex <tt>v</tt> in the topological order; -1 if the * digraph is not a DAG * * @return the position of vertex <tt>v</tt> in a topological order of the * digraph; -1 if the digraph is not a DAG * @throws IndexOutOfBoundsException unless <tt>v</tt> is between 0 and * <em>V</em> &minus; 1 */ public int rank(int v) { validateVertex(v); if (hasOrder()) { return rank[v]; } else { return -1; } } // throw an IndexOutOfBoundsException unless 0 <= v < V private void validateVertex(int v) { int V = rank.length; if (v < 0 || v >= V) { throw new IndexOutOfBoundsException("vertex " + v + " is not between 0 and " + (V - 1)); } } }
Shell
UTF-8
286
2.828125
3
[ "LicenseRef-scancode-public-domain" ]
permissive
#!/bin/bash # Install helm on the local machine # Download Helm curl https://raw.githubusercontent.com/kubernetes/helm/master/scripts/get > get_helm.sh # Make get_helm executable $ chmod 700 get_helm.sh # Execute get_helm.sh $ ./get_helm.sh # Initialize helm helm init --client-only
Ruby
UTF-8
1,363
3.046875
3
[]
no_license
#Calculator require "sinatra" require_relative "calc.rb" get '/' do msg = params[:msg] || "" erb :login, locals: {msg: msg} end def login(un, pw) users = {admin: "admin", msw: "msw", guest: "guest"} pass = {a: "admin", m: "qwerty", g: "guest"} if users.has_value?(un) && pass.has_value?(pw) redirect '/user' else redirect '/?msg=Incorrect username or password' end end post '/p_login' do un = params[:un] pw = params[:pw] login(un, pw) end get '/user' do yay = "Yay!!! Sucessful Login!" erb :un, locals: {yay: yay} end post '/un' do fn = params[:fn] ln = params[:ln] redirect '/nums?fn=' + fn + '&ln=' + ln end get '/nums' do fn = params[:fn] ln = params[:ln] erb :nums, locals: {fn: fn, ln: ln} end post '/p_nums' do fn = params[:fn] ln = params[:ln] num1 = params[:num1] num2 = params[:num2] op = params[:op] t = calc(op, num1, num2) redirect '/res?fn=' + fn + '&ln=' + ln + '&num1=' + num1 + '&num2=' + num2 + '&op=' + op + '&t=' + t end get '/res' do fn = params[:fn] ln = params[:ln] num1 = params[:num1].to_s num2 = params[:num2].to_s op = params[:op] t = params[:t] if op == "add" op = "+" end erb :res, locals: {fn: fn, ln: ln, num1: num1, num2: num2, op: op, t: t} end post '/p_res' do fn = params[:fn] ln = params[:ln] redirect '/nums?fn=' + fn + '&ln=' + ln end
C#
UTF-8
1,456
2.609375
3
[]
no_license
using System; using System.Collections.Generic; using System.Text; namespace nicehu.common { public class ConsoleU { public static void Debug(object msg) { Console.Out.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") +" DEBUG:"+ msg); } public static void Debug(string format, params Object[] args) { Console.Out.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " DEBUG:" + String.Format(format, args)); } public static void Info(object msg) { Console.Out.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " INFO:" + msg); } public static void Info(string format, params Object[] args) { Console.Out.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " INFO:" + String.Format(format, args)); } public static void Warn(object msg) { Console.Out.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " WARN:" + msg); } public static void Warn(string format, params Object[] args) { Console.Out.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " WARN:" + String.Format(format, args)); } public static void Error(object msg) { Console.Out.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " ERROR:" + msg); } public static void Error(string format, params Object[] args) { Console.Out.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " ERROR:" + String.Format(format, args)); } } }
Markdown
UTF-8
819
2.8125
3
[ "MIT" ]
permissive
# hildebrand-store-ng Single Web Application built by using Angular Framework, ng-bootstrap and other useful libraries. # Description A simple website where you user is authenticate can signup and login, select a product and add or remove it to cart, check out, track orders and much more. # Requirements to run: * Node.js >= v.12.18 * Angular CLI >= v.10 * Run on windows 10 # Procedure: 1. Clone repository on https://github.com/yasexxx/hildebrand-store-ng.git 2. Open terminal and locate directory (e.g) "cd hildebrand-store-ng" 3. Type "npm install" on terminal wait until done. 4. When done, open browser and type on terminal "ng serve" to start development. 5. Done!!! # Check out the working application up and running with backend using Node.js and Express library. https://hildebrandapp.herokuapp.com
Java
UTF-8
1,084
2.0625
2
[]
no_license
package com.zlst.spring.test.mapper; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.zlst.spring.entity.UserVo; import com.zlst.spring.mapper.UserMapper; import com.zlst.spring.BaseTest; import com.zlst.spring.query.UserQuery; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import java.util.List; /** * 用户持久化测试 * auther hekai * create 2017/8/14 15:42 */ public class UserMapperTest extends BaseTest { @Autowired private UserMapper userMapper; @Test public void queryUserInfoById(){ UserVo userVo= userMapper.queryUserInfoById("2"); System.out.println(userVo.getUserName()); } @Test public void queryUserList() { UserQuery userQuery =new UserQuery(); PageHelper.startPage(userQuery.getPageNumber(),userQuery.getPageSize()); List<UserVo> userList = userMapper.queryUserList(userQuery); System.out.println(userList); System.out.println(userList.get(0)); } }
C++
UTF-8
1,122
2.65625
3
[]
no_license
#pragma once #include <SFML/Graphics.hpp> #include <math.h> #include "ImageManager.h" #include "Util.h" #include "SpriteExt.h" #ifndef MISSLE_H #define MISSLE_H #define PI 3.14159265 class Missle { private: bool colisionWithiObiect; float angle; float currentDistance; //Chwilowa odleg�o�� od strzelaj�cego float range; //Zasi�g pocisku float velocity; //Pr�dko�� pocisku float distanceFromTarget; // Odleg�o�� od celu ( kliku myszki ) std::string missleColider; sf::Image myTexture; SpriteExt mySprite; sf::Vector2f startPosition; //Wsp miejsca wystrza�u sf::Vector2f currentPosition; sf::Vector2i targetPosition; //Pozycja docelowa public: bool inMove; float ReturnAngle(); void Logic(); void UpdateCollision(); void Display(sf::RenderWindow *window); Missle(std::string fileName,std::string _missleColider = "enemy" ,float Range = 10,float Velocity = 1); ~Missle(void); void SetTarget(sf::Vector2i DesignatedPosition,float DistanceFromMouseClick ); void SetMissleColider( std::string _missleColider ); void StartPosition(sf::Vector2f Position); }; #endif
Java
UTF-8
1,573
2.890625
3
[]
no_license
package br.ufes.inf.nemo.assistant.pattern.window; import java.awt.Color; import java.awt.Dimension; import java.awt.Image; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; public class ImagePanel extends JPanel { public enum PatternType { RelatorCreation,SubkindCreation,RoleMixinPattern } public ImagePanel(PatternType type){ ImageIcon iconLogo = null; if(type.equals(PatternType.RelatorCreation)) iconLogo = new ImageIcon(getClass().getClassLoader().getResource("resource/RelatorCreation.png")); else if(type.equals(PatternType.SubkindCreation)) iconLogo = new ImageIcon(getClass().getClassLoader().getResource("resource/SubkindCreation.png")); else if(type.equals(PatternType.RoleMixinPattern)) iconLogo = new ImageIcon(getClass().getClassLoader().getResource("resource/RoleMixinCreation.png")); setLayout(null); Image img = iconLogo.getImage() ; Image newimg = img.getScaledInstance( 445, 259, java.awt.Image.SCALE_SMOOTH ) ; iconLogo = new ImageIcon( newimg ); JPanel imagePanel = new JPanel(); imagePanel.setBackground(Color.WHITE); imagePanel.setBounds(0, 18, iconLogo.getIconWidth(), iconLogo.getIconHeight()); add(imagePanel); JLabel lblImg = new JLabel(iconLogo); imagePanel.add(lblImg); JLabel lblPatternStructure = new JLabel("Pattern Structure"); lblPatternStructure.setBounds(3, 1, 166, 14); add(lblPatternStructure); setSize(new Dimension(iconLogo.getIconWidth(),iconLogo.getIconHeight()+20)); } }
Markdown
UTF-8
799
2.703125
3
[]
no_license
# PWA Budget Tracker Simple budget tracker that works online and offline. ### 🖥 Deployed ver. 👉 [Heroku](https://pwa-budget-tracker-app.herokuapp.com/) ### 💎 Used Skills Progressive Web App(PWA: manifest, service-worker, cache), IndexedDB, MongoDB, Mongoose, Node.js, Express, Javascript, HTML ## 🎯 Purpose You can record your withdrawals and deposits with or without a data/internet connection so that you can track the accurate balance in any circumstance. ## 🔑 Feature - This web app can be saved and works like a native app. - Network independent. The app works when the network is unreliable or even non-existent. ## ✨ Demo ▼ Online / Offline working ![screenshot1-offline](/demo1.gif) ▼ Can be saved / opened as a native app ![screenshot2-saveApp](/demo2.gif)
Python
UTF-8
6,349
3.796875
4
[]
no_license
from typing import List def read_list() -> List[int]: lst = [] lst_str = input('Dati numerele separate prin spatiu:') lst_str_split = lst_str.split(' ') for num_str in lst_str_split: lst.append(int(num_str)) return lst def is_even(n): ''' Determina daca numarul dat este par. :param n:Numarul dat :return:Daca este par returneaza True si daca nu este returneaza False ''' if n % 2 == 0: return True return False def test_is_even(): assert is_even(1) == False assert is_even(2) == True assert is_even(10) == True assert is_even (9) == False def get_even(lst: list[int]) -> List[int]: ''' Determina daca toate numerele sunt pare :param lst: Lista de numere :return: O lista cu numere pare ''' result = [] for num in lst: if is_even(num): result.append(num) return result def get_longest_all_even(lst: List[int]) -> List[int]: ''' Determina cea mai lunga subsecventa a unei liste cu proprietatea ca toate numerele sunt pare :param lst: Lista in care se cauta subsecventa :return:subsecventa gasita ''' nr= len(lst) result = [] for st in range(nr): for dr in range(st , nr): all_even = True for num in lst [st:dr+1]: if num % 2 !=0: all_even=False break if all_even : if dr - st + 1 > len(result): result = lst[st:dr+1] return result def is_nr_div(n): ''' Determina numarul de divizori al numarului dat :param n: Numarul dat :return: Variabila k care returneaza numarul total de divizori al numarului. ''' k = 0 x = n for i in range (1 , x + 1): if x % i == 0: k = k+1 return k def get_nr_div(lst: list[int]) -> List[int]: ''' Determina daca toate numerele au acelasi numar de divizori :param lst: O lista cu numere :return: O lista cu numerele care au acelasi numar de divizori ''' result = [] for num in lst: if is_nr_div(num): result.append(num) return result def get_longest_same_div_count(lst: list[int]) -> List[int]: ''' Determina cea mai lunga subsecventa in care numerele au acelasi numar de divizori :param lst: Lista in care se cauta subsecventa :return: Subsecventa gasita ''' nr = len(lst) result = [] for st in range(nr): for dr in range(st, nr): k=is_nr_div(lst[st]) all_same_div_count= True for num in lst[st:dr + 1]: if is_nr_div(num)!=k: all_same_div_count = False break if all_same_div_count: if dr - st + 1 > len(result): result = lst[st:dr + 1] return result def test_get_longest_all_even(): assert get_longest_all_even([1,4,5,6,8,10]) == [6,8,10] assert get_longest_all_even([ 100 , 122 , 154 ,211]) == [100,122,154] assert get_longest_all_even([50,60,70,71,88]) == [50,60,70] def test_is_nr_div(): assert is_nr_div(11) == 2 assert is_nr_div(8) == 4 assert is_nr_div(5) == 2 def test_get_longest_same_div_count(): assert get_longest_same_div_count([7 , 5, 2 , 3 , 80]) == [7,5,2,3] assert get_longest_same_div_count([12,45, 2,]) == [12,45] assert get_longest_same_div_count([14,8, 3, 202]) == [14,8] def is_palindrome(n): ''' Determina daca numarul dat este palindrom :return: True daca este palindrom si false daca nu este palindrom ''' inv = 0 x = n ogl = 0 while n != 0: ogl = ogl * 10 + n % 10 n = n // 10 if x == ogl: return True elif x != ogl: return False def get_palindrome(lst: list[int]) -> List[int]: ''' Determina numerele care sunt palindroame din lista :param lst: O lista de numere :return: O lista cu numere palindrome ''' result = [] for num in lst: if is_palindrome(num): result.append(num) return result def get_longest_all_palindromes(lst: list[int]) -> List[int]: ''' Determina cea mai lunga subsecventa in care numerele sunt palindroame :param lst: Lista in care se cauta subsecventa :return: Subsecventa gasita ''' nr = len(lst) result = [] for st in range(nr): for dr in range(st, nr): all_palindrome = True for num in lst[st:dr + 1]: if is_palindrome(num) == False: all_palindrome = False break if all_palindrome: if dr - st + 1 > len(result): result = lst[st:dr + 1] return result def test_is_palindrome(): assert is_palindrome(1) == True assert is_palindrome(25) ==False assert is_palindrome(9779) == True assert is_palindrome(323) == True def test_get_longest_all_palindromes(): assert get_longest_all_palindromes([252,727,989 ,1,3]) == [252,727,989,1,3] assert get_longest_all_palindromes([31, 424,9889,200]) == [424,9889] assert get_longest_all_palindromes([ 1,3,2, 252,722]) == [1,3,2,252] def main(): lst = [] while True: print("1. Citire lista") print("2. Determinare cea mai lunga subsecventa cu proprietatea:Toate numerele sunt pare") print("3. Determinare cea mai lunga subsecventa cu proprietatea:Toate numerele au acelasi numar de divizori") print("4. Determinare cea mai lunga subsecventa cu proprietatea:Toate numere sunt palindroame") print("5.x. Exit") optiune = input ('Alege optiunea: ') if optiune == "1" : lst = read_list() elif optiune == "2": print(get_longest_all_even(lst)) elif optiune == "3": divizor = get_longest_same_div_count(lst) print(get_longest_same_div_count(lst)) elif optiune == "4": print(get_longest_all_palindromes(lst)) elif optiune == "5": break else: print("Optiune invalida") if __name__ == '__main__' : test_is_nr_div() test_is_palindrome() test_is_even() test_get_longest_all_even() test_get_longest_same_div_count() test_get_longest_all_palindromes() main()
PHP
UTF-8
2,045
2.8125
3
[]
no_license
<?php namespace AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Computer */ class Computer { /** * @var integer */ private $id; /** * @var string */ private $name; /** * @var string */ private $cpu; /** * @var float */ private $frequency; /** * @var integer */ private $harddisk; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set name * * @param string $name * @return Computer */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * Set cpu * * @param string $cpu * @return Computer */ public function setCpu($cpu) { $this->cpu = $cpu; return $this; } /** * Get cpu * * @return string */ public function getCpu() { return $this->cpu; } /** * Set frequency * * @param float $frequency * @return Computer */ public function setFrequency($frequency) { $this->frequency = $frequency; return $this; } /** * Get frequency * * @return float */ public function getFrequency() { return $this->frequency; } /** * Set harddisk * * @param integer $harddisk * @return Computer */ public function setHarddisk($harddisk) { $this->harddisk = $harddisk; return $this; } /** * Get harddisk * * @return integer */ public function getHarddisk() { return $this->harddisk; } public function __toString() { return $this->getName() . '_' . $this->getCpu() . '_' . $this->getFrequency() . '_' . $this->getHarddisk(); } }
Java
WINDOWS-1252
682
2.3125
2
[]
no_license
package parser; import static org.junit.Assert.*; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import parser.common.exception.ContainerRecordParserException; public class CustomerParserBlankFieldsTest { private static CustumerParser cp; private static String line; @BeforeClass public static void setUpBeforeClass() { line = "002 "; } @Before public void setUp() { cp = new CustumerParser(); } @Test public void testAccept() { assertTrue(cp.accept(line)); } @Test(expected=ContainerRecordParserException.class) public void testGet() throws ContainerRecordParserException { cp.accept(line); cp.get(); } }
Python
UTF-8
2,471
3.046875
3
[ "MIT" ]
permissive
import json from io import StringIO from html.parser import HTMLParser import torch class MLStripper(HTMLParser): """ Class for stripping away HTML stuff. """ def __init__(self): super().__init__() self.reset() self.strict = False self.convert_charrefs= True self.text = StringIO() def handle_data(self, d): self.text.write(d) def get_data(self): return self.text.getvalue() def strip_tags(html): """ Function which takes a string and returns a string without html tags such as <br>. """ s = MLStripper() s.feed(html) return s.get_data() class KundoData(torch.utils.data.Dataset): """ Torch dataset. Reads in a Kundo json file, and retains all questions which have one (and only one) answer. """ def __init__(self, path, keep=lambda x: True): self.question = [] self.answer = [] with open(path, 'rt') as handle: for doc in filter(keep, map(json.loads, handle)): question = doc['question']['text'] answer = doc['answers'] if len(answer) == 1: self.question.append(strip_tags(question)) self.answer.append(strip_tags(answer[0]['text'])) def __len__(self): return len(self.question) def __getitem__(self, ix): return self.question[ix], self.answer[ix] def mk_loader(tokenizer, pair_ds, max_len=512, batch_size=32, pin_memory=True, shuffle=True, num_workers=4): """ Utiliyu function to make a torch dataloader given a toenizer and a KundoData dataset. """ def encode(texts): batch = tokenizer.batch_encode_plus( texts, add_special_tokens=True, max_length=max_len, padding=True, truncation=True, return_attention_mask=True, return_tensors='pt') return batch['input_ids'], batch['attention_mask'] def collate(texts): questions, answers = zip(*texts) return encode(questions), encode(answers) return torch.utils.data.DataLoader( pair_ds, batch_size=batch_size, collate_fn=collate, shuffle=shuffle, drop_last=True, pin_memory=True, num_workers=True)
PHP
UTF-8
2,281
2.671875
3
[]
no_license
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <link rel="icon" type="image/x-icon" href="./images/favicon.png"> </head> <body> <?php session_start(); echo $_SESSION["id"]; $database_host = "localhost"; $database_user = "root"; $database_pass = ""; $database_name = "carrental"; $connection = mysqli_connect($database_host, $database_user, $database_pass, $database_name); if(mysqli_connect_errno()){ die("Failed connecting to MySQL database. Invalid credentials" . mysqli_connect_error(). "(" .mysqli_connect_errno(). ")" ); } $Vid=$_SESSION["id"]; $res="select crdata.Cid,crdata.Vehicle_id,crdata.Nohours,crdata.Nodays,car.Drate,car.Wrate from crdata INNER JOIN car where crdata.Cid = '$Vid' AND crdata.Vehicle_id = car.Vehicle_id"; $result=mysqli_query($connection,$res); /*$row = mysqli_fetch_assoc($result); $trf = mysqli_num_fields($result); echo $trf; */ if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { $cid=$_SESSION["id"]; $vid=$row["Vehicle_id"]; $Nhours=$row["Nohours"]; $Ndays=$row["Nodays"]; $hrate=$row["Drate"]; $drate=$row["Wrate"]; $amount = ($Nhours*$hrate) + ($Ndays*$drate); $res1 = "INSERT INTO amount(Cid,amt) VALUES('$cid','$amount')"; $result1=mysqli_query($connection,$res1); } } $res2="insert into history(Rid,cid,Fname,Vehicle_id,License_no,Model,Ctype,Rdate,Nohours,Nodays,amt) SELECT rental.Rid,rental.cid,customer.Fname,rental.Vehicle_id,car.License_no,car.Model,car.Ctype,rental.Rdate,crdata.Nohours,crdata.Nodays,amount.amt FROM rental INNER JOIN car ON rental.Vehicle_id = car.Vehicle_id INNER JOIN customer ON rental.cid=customer.Cid INNER JOIN crdata ON customer.Cid=crdata.Cid INNER JOIN amount on rental.cid = amount.cid AND customer.cid = '$Vid'"; $result2=mysqli_query($connection,$res2); echo 'Total amount for customer id '.$cid.' is :'.$amount.''; $drop="delete from amount where Cid='$Vid'"; $result3=mysqli_query($connection,$drop); $drop="delete from crdata where Cid='$Vid'"; $result3=mysqli_query($connection,$drop); $drop1="delete from rental where Cid='$Vid'"; $result4=mysqli_query($connection,$drop1); ?> </body> </html>
C#
UTF-8
1,334
3.84375
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; namespace AtCoder { class Program { static int x; static void Main(string[] args) { //[summary]B - Exponential x = int.Parse(Console.ReadLine()); int sqrt = (int)Math.Sqrt(x); var pows = new List<int>() { 1 }; for(int i = 2; i <= sqrt; i++) { int pow = GetMaxPower(i); pows.Add(pow); } Console.WriteLine(pows.Max()); } static int GetMaxPower(int n) { int i = 2; int pow = (int)Math.Pow(n, i); while(pow <= x) { i++; pow = (int)Math.Pow(n, i); } if(pow <= x) { return pow; } else { return (int)Math.Pow(n, i - 1); } } static List<int> ReadLine() { var line = Console.ReadLine(); var array = line.Split(' '); return array.Select(x => int.Parse(x)).ToList(); } } }
Java
UTF-8
144
2.171875
2
[]
no_license
package org.musicbrainz.model; public interface Track extends Entity { public String getTitle(); public void setTitle(String title); }
C++
UTF-8
1,827
2.9375
3
[]
no_license
// // Created by 10578 on 8/26/2019. // #include <iostream> #include <fstream> #include <vector> #include <sstream> #define BOOST_IO ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); #define LOCAL using namespace std; class Solution { public: vector<int> result; void recursive(vector<vector<int>> &matrix, int l, int r, int up, int down) { //upper for (int j = l; j <= r; ++j) { result.push_back(matrix[up][j]); } //right for (int i = up + 1; i <= down; ++i) { result.push_back(matrix[i][r]); } if (up != down) { //lower for (int j = r - 1; j >= l; --j) { result.push_back(matrix[down][j]); } } if (l != r) { //left for (int i = down - 1; i > up; --i) { result.push_back(matrix[i][l]); } } l++; r--; down--; up++; if (l <= r && up <= down) { recursive(matrix, l, r, up, down); } } vector<int> spiralOrder(vector<vector<int>> matrix) { if (matrix.empty()) { return vector<int>{}; } recursive(matrix, 0, matrix[0].size() - 1, 0, matrix.size() - 1); return result; } }; int main() { BOOST_IO; #ifdef LOCAL fstream in("in.txt"); cin.rdbuf(in.rdbuf()); #endif vector<vector<int>> matrix; string line; while (getline(cin, line)) { istringstream iss(line); vector<int> temp; int num; while (iss >> num) { temp.push_back(num); } matrix.push_back(temp); } Solution s; auto results = s.spiralOrder(matrix); for (auto r: results) { cout << r << " "; } }
C++
UTF-8
5,384
2.59375
3
[]
no_license
#ifndef BEEHIVE_H #define BEEHIVE_H #include <stdio.h> #include <stdlib.h> /*rand */ #include <iostream> #include <string> #include <vector> #include <sys/stat.h> #include <sys/types.h> #include "queen.h" #include "nurse.h" #include "worker.h" #include "juvinile.h" #include "forager.h" #include "drone.h" #include "brood.h" #include "bee.h" #include "board.h" #include <fstream> using namespace std; class Board; class Beehive { public: Beehive(string ID,int forageNum, int NumOfBoard,int droneNum, double grow);//constructor Beehive(string ID); Beehive(); ~Beehive(); //deconstructor void beeSimpleGrowth(double x);// function if you want simple bee growth int growthfunction(double x);// uses growth param x to see how many bees to make void randomSwarm();// reset and make new times for the swarms & attacks bool checkBoards();// check if there is something in the gates bool dance(Forager *f);// function for state of forager bool foundFood(Forager *f);// function for state of forager bool hasTarget(Forager *f);// function for state of forager bool isTired(Forager *f);// function for state of forager void beginDance(Forager *f);// function for state of forager void enterState(Forager *f);// function for state of forager void enterStates(Forager *f);// function for state of forager void exitState(Forager *f);// function for state of forager void exitStates(Forager *f);// function for state of forager void explore(Forager *f);// function for state of forager void forageStep(Forager *f);// function for state of forager void forageTech(Forager *f);// function for state of forager void restOrEat(Forager *f);// function for state of forager void returnToNest(Forager *f);// function for state of forager void searchForThing(Forager *f);// function for state of forager string boardString();// string for udp message string parseTime(int t);// time for udp message void OneDayTimeStep();// one day void OneHourTimeStep();// one hour void OneMillisecondTimeStep();// one millisecond void OneMinuteTimeStep();// one minute void OneMonthTimeStep();// one month void OneSecondTimeStep();// one second void OneWeekTimeStep();// one weed void OneYearTimeStep();// one year void SwarmTech(Bee *b);// make a bee swarm void attackTech(Bee *b);// make a bee attack void birthBees();// make new brood void evolveBees();// make bees grow up void fertilizeEggs();// decide gender of bees void foodCalculation();// feed all the bees void killBees();// kill old bees void nurseBees();// nurse young brood void run();// run simulation void run(string ID); void setNumOfBoards(int x);//set number of boards void setSeason(int x);// set season void setStartingValues();// set the starting values void setWeather(double s);//set temperature void setYearsToRun(int x);// set # of years to run void setup();// set up simulation void updateBoards();// update the boards void workerTech(Worker w);// do things with the workers bool divide10();// random number 1-10 private: double printOut=0;// current day (print out % done) bool initrun=true;// sets if its the first day or not(it corrects number of bees on first day) Queen q;// make a queen to birth bees int droneNum;// number of drones to swarm/ attack double growthP;// simple growth % int forNum;// number of foragers to start with int randNumGen;// random number gen bool Attack = true;// is there an attack bool domilli = true;// do millisecond simulation bool swarm = true;// is there a swarm double foodAmount= 1000000;//food in hive in grams double pollenAmmount = 1000000;//pollen in hive in grams double pollenGen = 100;// init values double pollenUsed = 20;// init values double temperature = 70;// starting temperature int AttackTime = 43200;// rob time(init at noon) int BeeCounter=0;// number of bee enters into hive today int BeeCounter2=0;// number of bee enters total int TOD;// current time today int boardcycle = 0;// cycle through boards to even it out int changenow;// idk what this does but its important(I think it helps boardcycle) int currentTime = 0;// current sim time int exitCounter=0;// number of exits today int exitCounter2=0;// num of exits total int milliCounter=0;// number of milliseconds this second int numOfBoards = 10;// number of boards int season = 1;// season int swarmTime = 64800;// swarm time (init at 6:00pm) int timeSinceMessage=0;// time since last udp in milliseconds int atkC = 0;// # of attacking bees today int SWRMC = 0;// num of swarming bees today int atkC2 = 0;// tot num of attacking bees int SWRMC2 = 0;//tot num of swarming bees string hiveID = "testID";// id of hive int numofyears = 1;// num of years to run vector<Board> boardVect;// vector of boards vector<Brood> broodVect;// brood vector vector<Drone> droneVect;//drone vector vector<Forager> forageVect;//forager vector vector<Juvinile> juviVect;// juvinile vector vector<Nurse> nurseVect;// nurse vector vector<Worker> workerVect;// worker vector ofstream myfile;// file reader }; #endif // BEEHIVE_H
C#
UTF-8
8,459
3.21875
3
[]
no_license
using System; using Projeto_de_Produtos.Interfaces; namespace Projeto_de_Produtos.Classes { public class Login : iLogin { private bool logado = false; private bool sair = false; private string escolha; Usuario usuarioEncontrado = null; Usuario u = new Usuario(); Produto p = new Produto(); Marca m = new Marca(); public void FazerLogin() { do { Console.WriteLine(@"Bem vindo ao cadastrador 3000 de marcas e produtos! Para acessar o sistema, selecione as seguintes opções: 1. Cadastrar 2. Logar 3. Deslogar 4. Deletar usuário 5. Sair "); escolha = (Console.ReadLine()); switch (escolha) { case "1": Usuario novo = new Usuario(); Console.WriteLine("Crie o seu nome"); novo.nome = Console.ReadLine(); Console.WriteLine("Digite o seu Email"); novo.email = Console.ReadLine(); Console.WriteLine("Crie a sua senha"); novo.senha = Console.ReadLine(); novo.codigo += 1; Console.WriteLine(u.Cadastrar(novo)); foreach (var item in u.usuario) { Console.WriteLine($"{item.email} {item.senha}"); } break; case "2": do { Console.WriteLine("Digite o seu Email"); string email = Console.ReadLine(); Console.WriteLine("Digite a sua senha"); string senha = Console.ReadLine(); usuarioEncontrado = u.usuario.Find(x => x.email == email && x.senha == senha); if (usuarioEncontrado != null) { logado = true; Console.WriteLine(Logar()); Console.WriteLine($@" Se deseja cadastrar um produto, aperte 1, se deseja cadastrar uma marca, aperte 2, se deseja listar um produto aperte 3, se deseja listar uma marca aperte 4, se deseja deletar um produto aperte 5, se deseja deletar uma marca aperte 6 se deseja sair aperte 7. "); } else { Console.WriteLine("email ou senha errados, tente novamente"); } escolha = (Console.ReadLine()); switch (escolha) { case "1": Console.WriteLine("Qual produto você deseja cadastrar?"); string nomeProduto = Console.ReadLine(); Console.WriteLine("Qual será o preço do seu produto?"); float preço = float.Parse(Console.ReadLine()); p.codigo++; Produto novoP = new Produto(); p.addProduto(novoP); Console.WriteLine(p.addProduto(novoP)); Console.WriteLine(p.Cadastrar()); break; case "2": Console.WriteLine("Qual é o nome da sua marca?"); string nomeMarca = Console.ReadLine(); m.codigo++; Marca novaM = new Marca(); m.addMarca(novaM); Console.WriteLine(m.addMarca(novaM)); Console.WriteLine(m.Cadastrar()); break; case "3": foreach (var item in p.listaDeProdutos) { Console.WriteLine($"Nome: {p.nomeProduto} Preço: {p.preco}"); } Usuario cadastradoPor = usuarioEncontrado; Console.WriteLine(usuarioEncontrado); break; case "4": foreach (var item in m.List) { Console.WriteLine($"Nome: {m.nomeMarca}"); } cadastradoPor = usuarioEncontrado; Console.WriteLine(usuarioEncontrado); break; case "5": Console.WriteLine("Qual produto deseja deletar?"); nomeProduto = Console.ReadLine(); Produto produtoEncontrado = p.listaDeProdutos.Find(x => x.nomeProduto == nomeProduto); Console.WriteLine(p.Deletar(produtoEncontrado)); break; case "6": Console.WriteLine("Qual marca deseja deletar?"); nomeMarca = Console.ReadLine(); Marca marcaEncontrada = m.List.Find(x => x.nomeMarca == nomeMarca); Console.WriteLine(m.Deletar(marcaEncontrada)); break; case "7": Console.WriteLine("Você realmente deseja sair? (S/N)"); escolha = Console.ReadLine().ToLower(); if (escolha == "s"){ Console.WriteLine("Obrigado por usar nosso site"); } break; default: break; } } while (escolha != "s"); break; case "3": Console.WriteLine("Você realmente deseja deslogar?"); Console.WriteLine(Deslogar()); escolha = (Console.ReadLine()); break; case "4": Console.WriteLine("Qual Usuario deseja deletar?"); string nome = Console.ReadLine(); usuarioEncontrado = u.usuario.Find(x => x.nome == nome); Console.WriteLine(u.Deletar(usuarioEncontrado)); break; case "5": Console.WriteLine("Você realmente deseja sair? (S/N)"); escolha = (Console.ReadLine().ToLower()); if (escolha == "s") { Console.WriteLine("Obrigado por escolher nosso site, até uma próxima."); sair = true; } break; default: Console.WriteLine("Opção inválida"); break; } } while (escolha != "s"); } public string Logar() { return "Usuário foi logado"; } public string Deslogar() { return "Usuário deslogado"; } } }
PHP
UTF-8
123
3.1875
3
[ "MIT" ]
permissive
<?php $arr=array(2,3,5,6,7,8,9,1); $sum=0; for($i=0;$i<count($arr)-1;$i++) { $a=$arr[$i]; $sum=$a+$sum; } echo $sum; ?>
Java
UTF-8
409
2.390625
2
[]
no_license
package com.example.test; import com.example.dao.customerDAO; import java.util.List; import com.example.model.customer; public class testData { public static void main(String[] args) { customerDAO customerDAO = new customerDAO(); List<customer> listC = customerDAO.getAllCustomer(); for (customer x:listC){ System.out.println(x.getAge_customer()); } } }
Python
UTF-8
1,108
3.1875
3
[]
no_license
import matplotlib.pylab as plot import numpy as np #F1 = int(input('Enter the frequency of carrier=')) F1=9 amplitude = 3 time = np.arange(0, 1, 0.001) x = amplitude * np.sin(2 * np.pi * F1 * time) # Carrier Signal y = [] # Binary Input Sequence Signal phase = [0.2, 0.4, 0.6, 0.8, 1.0] sign = 1 for i in time: if i == phase[0]: phase.pop(0) if sign == 0: sign = 1 else: sign = 0 y.append(sign) z = [] # Carrier signal modulated with binary signal for i in range(len(time)): z.append(amplitude * np.sin(2 * np.pi * F1 * time[i]) * y[i]) plot.subplot(3,3,1) plot.plot(time, x) plot.xlabel('Time') plot.ylabel('Amplitude') plot.title('Carrier Signal') plot.grid(True) #plot.show() plot.subplot(3,3,2) plot.plot(time, y) plot.xlabel('Time') plot.ylabel('Amplitude') plot.title('Binary input sequence signal') plot.grid(True) #plot.show() plot.subplot(3,3,3) plot.plot(time, z) plot.xlabel('Time') plot.ylabel('Amplitude') plot.title('Amplitude Shift Keying Signal') plot.grid(True) plot.show()
Python
UTF-8
792
2.59375
3
[]
no_license
import cPickle as pickle import time from craigslist import CraigslistForSale,get_all_sites #Configure prior to running #CL urls usually work by https://YOUR_STATE.cragilist.org/YOUR_AREA YOUR_STATE='longisland' YOUR_AREA='lgi' def scrape(): with open('data.pickle','rb') as fp: cl_listings = pickle.load(fp) #scrape for data cl_query = CraigslistForSale(site=YOUR_STATE, filters={'max_price':250,'query':'ikea desk'}) for result in cl_query.get_results(sort_by='newest'): print(result) if result not in cl_listings: cl_listings.append(result) with open('data.pickle','wb') as fp: pickle.dump(cl_listings,fp) while True: scrape() print('loop completed sleeping for 10 minutes') time.sleep(600)
Java
UTF-8
196
1.6875
2
[]
no_license
package com.helha.groupe1a.interfacesEJB; import javax.ejb.Remote; import com.helha.groupe1a.entities.Project; @Remote public interface GestionProjectEJBRemote { public void add(Project p); }
JavaScript
UTF-8
1,973
2.96875
3
[]
no_license
import { CART_ADD_ITEM, CART_REMOVE_ITEM } from '../constants/cartConstants'; export const cartReducer = (state = { cartItems: [] }, action) => { switch (action.type) { case CART_ADD_ITEM: // ejemplo del action.payload // const payload = { // id: product.id, // name: product.name, // price: product.price, // image: product.image, // qty, // }, const product = action.payload; // Buscamos si el item ya está en el cartItems, en caso de que esté le sumamos 1 al qty const exist = state.cartItems.find((x) => x.id === product.id); if (exist) { // Si encuentra el producto en el cartItem lo reemplaza aumentando la cantidad en 1 let newState = state.cartItems.map((x) => x.id === product.id ? { ...exist, qty: exist.qty + 1 } : x ); return { cartItems: newState, }; } else { return { ...state, cartItems: [...state.cartItems, product], }; } case CART_REMOVE_ITEM: // action.payload == product.id, asi lo estamos enviando desde la accion const existRemove = state.cartItems.find((x) => x.id === action.payload); if (existRemove && existRemove.qty > 1) { // Si encuentra el producto en el cartItem lo reemplaza aumentando la cantidad en 1 let newState = state.cartItems.map((x) => x.id === action.payload ? { ...existRemove, qty: existRemove.qty - 1 } : x ); return { cartItems: newState, }; } else { /** * Como vamos a remover, vamos a filtrar el item que estamos removiendo * Vamos a filtrar todos los que el x.id no coincida con el payload */ return { ...state, cartItems: state.cartItems.filter((x) => x.id !== action.payload), }; } default: return state; } };
Shell
UTF-8
3,037
4.0625
4
[ "Apache-2.0" ]
permissive
#! /usr/bin/env bash # shellcheck disable=SC2034,SC2317 ################################################################################ # Name of registry, repository and name of official image IMAGE_BASE="ghcr.io/essentialkaos/perfecto" # Name of perfecto image on GitHub Container Registry with OL 8 based image IMAGE_CENTOS="$IMAGE_BASE:ol8" # Name of perfecto image on GitHub Container Registry with Alpine based image IMAGE_MICRO="$IMAGE_BASE:micro" ################################################################################ engine="" ################################################################################ # Main function # # Code: No # Echo: No main() { engine=$(getContainerEngine) if [[ -z "$engine" ]] ; then error "You must install Podman or Docker first" exit 1 fi if [[ $# -eq 0 ]] ; then usage exit 0 fi check "$@" exit $? } # Run perfecto check # # *: Specs # # Code: Yes # Echo: No check() { local image tmp_dir args opts status image=$(getImage) tmp_dir=$(mktemp -d -t 'pfcnt-XXXXXXXXXXXXX') args=$(processArgs "$tmp_dir" "$@") if [[ -z "$CI" ]] ; then opts="-i -t" else opts="-e CI=true" fi # shellcheck disable=SC2086 $engine run --rm $opts -v "$tmp_dir:/perfecto" "$image" ${args} status=$? rm -rf "$tmp_dir" return $status } # Show usage info # # Code: Yes # Echo: No usage() { local image opts image=$(getImage) if [[ -z "$CI" ]] ; then opts="-i -t" else opts="-e CI=true" fi # shellcheck disable=SC2086 $engine run --rm $opts "$image" "--help" return $? } # Process arguments # # 1: Path to temporary directory (String) # *: Specs # # Code: No # Echo: Arguments (String) processArgs() { local tmp_dir="$1" local arg spec_name result shift 1 for arg in "$@" ; do if [[ ! -r "$arg" ]] ; then result="$result $arg" continue fi cp "$arg" "$tmp_dir/" &>/dev/null spec_name=$(basename "$arg") result="$result $spec_name" done echo "$result" } # Get container image name with perfecto # # Code: No # Echo: Image name (String) getImage() { if [[ -n "$IMAGE" ]] ; then if [[ ! $IMAGE =~ \/ ]] ; then echo "$IMAGE_BASE:$IMAGE" return fi echo "$IMAGE" return fi if [[ $(printenv "GITHUB_ACTIONS") == "true" ]] ; then echo "$IMAGE_MICRO" return fi if [[ $(printenv "CI") == "true" ]] ; then echo "$IMAGE_MICRO" return fi echo "$IMAGE_CENTOS" } # Get used container engine # # Code: No # Echo: Engine name (String) getContainerEngine() { if [[ -n "$ENGINE" ]] && hasApp "$ENGINE" ; then echo "$ENGINE" return fi if hasApp "docker" ; then echo "docker" return fi if hasApp "podman" ; then echo "podman" return fi } # Check if some app is installed # # 1: Binray name (String) # # Code: Yes # Echo: No hasApp() { type "$1" &> /dev/null return $? } ################################################################################ main "$@"
C++
UTF-8
2,022
3.34375
3
[ "Apache-2.0" ]
permissive
#include <iostream> #include <algorithm> using namespace std; // at most, 1000 * 100 lamps // also, 1000 different categories // cost at [c][L] -> number of additional lamps L needed at c // is min-max -> use them all, or use none for the current lamp struct Category { int voltage; int voltageCost, lampCost; int numBaseLamps; // Order by increasing voltage bool operator<(const Category& other) const { return voltage < other.voltage; } }; const int MaxNumCategories = 1001; const int MaxNumLamps = MaxNumCategories * 101; int N; int costs[MaxNumCategories][MaxNumLamps]; Category categories[MaxNumCategories]; int GetBestCost(int category, int lampsCarried) { if (category == N) return 0; int& cost = costs[category][lampsCarried]; if (cost == -1) { const Category& current = categories[category]; int numLamps = current.numBaseLamps + lampsCarried; cost = current.voltageCost + numLamps * current.lampCost + GetBestCost(category + 1, 0); // Have all lamps be current category // Don't get into situation where lampsCarried != 0 for category == N if (category + 1 != N) cost = min(cost, GetBestCost(category + 1, numLamps)); // Don't use this category } return cost; } int main() { while (cin >> N, N) { for (int i = 0; i < N; ++i) { Category& c = categories[i]; cin >> c.voltage >> c.voltageCost >> c.lampCost >> c.numBaseLamps; } sort(categories, categories + N); // Reset costs int totalLamps = 0; // Total that could have been carried up to this point for (int i = 0; i < N; ++i) { for (int l = 0; l <= totalLamps; ++l) { costs[i][l] = -1; } totalLamps += categories[i].numBaseLamps; } cout << GetBestCost(0, 0) << '\n'; } }
Java
UTF-8
2,038
3.578125
4
[]
no_license
package com.zhangyun.other.xiaohongshu; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class 小红书暑期Main对窗口内的数组做操作 { public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int N=Integer.parseInt(br.readLine().trim()); String[] arrayStr=br.readLine().trim().split(" "); int[] array=new int[arrayStr.length];//拿到整数格式的数组,方便后续处理 for(int i=0;i<arrayStr.length;i++){ array[i]=Integer.parseInt(arrayStr[i]); } int M=Integer.parseInt(br.readLine().trim()); String[] Ls=br.readLine().trim().split(" "); String[] Rs=br.readLine().trim().split(" "); char[] ops=br.readLine().trim().toCharArray(); String[] XsStr=br.readLine().trim().split(" "); int[] Xs=new int[XsStr.length];//拿到整数格式的数组,方便后续处理 for(int i=0;i<XsStr.length;i++){ Xs[i]=Integer.parseInt(XsStr[i]); } //针对M次操作做处理 for(int i=0;i<M;i++){ int left=Integer.parseInt(Ls[i])-1;//LR是从1开始的,所以要作用于数组下标的话要减一 int right=Integer.parseInt(Rs[i])-1; char curOp=ops[i]; //把区间中的每个元素做操作 while(left<=right){ if(curOp=='|'){ array[left] |= Xs[i]; }else if(curOp=='&'){ array[left] &= Xs[i]; }else if(curOp=='='){//网友说,先判断`=`可以用java暴力a出来 array[left] = Xs[i]; } left++; } } StringBuilder sb=new StringBuilder(); for (int i=0;i<array.length;i++){ sb.append(array[i]); sb.append(" "); } System.out.println(sb.toString().trim()); } }
Java
UTF-8
5,568
2.421875
2
[]
no_license
package jamesno.hw1; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class CookbookInfo extends AppCompatActivity { Context context; RecyclerView recyclerView; RecyclerView.Adapter recyclerViewAdapter; RecyclerView.LayoutManager recylerViewLayoutManager; // 2D data array String[][] cookbooks = { {"THE FRENCH LAUNDRY", "THOMAS KELLER"}, {"WD-40", "WYLIE DUFRESNE"}, {"MOMOFUKU", "DAVID CHANG"}, {"FLOUR", "JOANNE CHANG"}, {"ON FOOD AND COOKING", "HAROLD MCGEE"}, {"ELEVEN MADISON PARK", "DANIEL HUMM"}, {"IVAN RAMEN", "IVAN ORKIN"}, {"GRAMERCY TAVERN", "MICHAEL ANTHONY"}, {"LUCQUES", "SUZANNE GOIN"}, {"PRUNE", "GABRIELLE HAMILTON"}, {"DANIEL", "DANIEL BOULUD"}, {"VONG", "JEAN GEORGES VONGERITCHEN"}, }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cookbook_info); context = getApplicationContext(); recyclerView = (RecyclerView) findViewById(R.id.recyclerview1); recylerViewLayoutManager = new LinearLayoutManager(context); // use a linear layout manager recylerViewLayoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(recylerViewLayoutManager); recyclerViewAdapter = new CustomAdapter(); recyclerView.setAdapter(recyclerViewAdapter); Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar); setSupportActionBar(myToolbar); // Get a support ActionBar corresponding to this toolbar ActionBar ab = getSupportActionBar(); // Enable the Up button ab.setDisplayHomeAsUpEnabled(true); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.home: // User chose the "Settings" item, show the app settings UI... Intent intentProfile = new Intent(this, JamesProfile.class); startActivity(intentProfile); return true; case R.id.about_app: // User chose the "Favorite" action, mark the current item // as a favorite... Intent intentAbout = new Intent(this, aboutApp.class); startActivity(intentAbout); return true; case R.id.songs: // User chose the "Favorite" action, mark the current item // as a favorite... Intent intentSongs = new Intent(this, PostCar.class); startActivity(intentSongs); return true; case R.id.map: Intent intentMaps = new Intent(this, MapsActivity.class); startActivity(intentMaps); return true; default: // If we got here, the user's action was not recognized. // Invoke the superclass to handle it. return super.onOptionsItemSelected(item); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menucookbook, menu); return true; } public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> { public class ViewHolder extends RecyclerView.ViewHolder { // each data item is just a string in this case public TextView mTitle; public TextView mDetail; public ViewHolder(View v) { super(v); mTitle = (TextView) v.findViewById(R.id.subject_1); mDetail = (TextView) v.findViewById(R.id.subject_2); } } @Override public CustomAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // Inflate the view for this view holder View item = getLayoutInflater().inflate(R.layout.list_item2, parent, false); // Call the view holder's constructor, and pass the view to it; // return that new view holder ViewHolder vh = new ViewHolder(item); return vh; } // Replace the contents of a view (invoked by the layout manager) @Override public void onBindViewHolder(ViewHolder holder, int position) { // - get element from your dataset at this position // - replace the contents of the view with that element holder.mTitle.setText(cookbooks[position][0]); holder.mDetail.setText(cookbooks[position][1]); } // Return the size of your dataset (invoked by the layout manager) @Override public int getItemCount() { return cookbooks.length; } } }
Java
UTF-8
1,561
2.75
3
[]
no_license
package com.example.administrator.datacollectdemo.datacollect; /** * 创建人:hutao * 创建时间:2017/10/19 */ public class SennorTracker { OnSennorChangeListener onSennorChangeListener; int[] sennorDataType; private SennorTracker() { } public void setOnSennorChangeListener(OnSennorChangeListener onSennorChangeListener) { this.onSennorChangeListener = onSennorChangeListener; } public void setSennorDataType(int[] sennorDataType) { this.sennorDataType = sennorDataType; } public void startTrack(){ } public void stopTrack(){ } interface OnSennorChangeListener{ void onSennorChange(SennorEntity sennorEntity); } public static class SennorEntity{ long timeStamp; float[] values; } static class Builder{ int[] sensorDataType; OnSennorChangeListener onSennorChangeListener; public Builder setSensorDataType(int[] sensorDataType) { this.sensorDataType = sensorDataType; return this; } public Builder setOnSennorChangeListener(OnSennorChangeListener onSennorChangeListener) { this.onSennorChangeListener = onSennorChangeListener; return this; } public SennorTracker build(){ SennorTracker sennorTracker = new SennorTracker(); sennorTracker.setOnSennorChangeListener(onSennorChangeListener); sennorTracker.setSennorDataType(sensorDataType); return sennorTracker; } } }
Java
UTF-8
139
2.609375
3
[]
no_license
public class TwoWheeler extends Vehicle { public TwoWheeler(String name) { this.name = name; this.size = 2; } }