language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
2,165
2.015625
2
[]
no_license
package com.example.trang.note.activity; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import com.example.trang.note.R; import com.example.trang.note.adapter.NoteAdapter; import com.example.trang.note.fragment.CreateFragment; import com.example.trang.note.fragment.ListNoteFragment; import com.example.trang.note.manager.NoteManager; import com.example.trang.note.note.Note; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private CreateFragment createFragment; private ListNoteFragment listNoteFragment; private NoteManager manager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); showCreateFragment(); manager = new NoteManager(); manager.copyDatabase(this); } public void showCreateFragment() { if (createFragment == null) { createFragment = new CreateFragment(); } getFragmentManager().beginTransaction().replace(android.R.id.content, createFragment) .setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_OPEN) .commit(); } public void showListNoteFragment() { if (listNoteFragment == null) { listNoteFragment = new ListNoteFragment(); } getFragmentManager().beginTransaction().replace(android.R.id.content, listNoteFragment) .addToBackStack(null) .setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_OPEN) .commit(); } public void insertData(String content, String color, String date) { manager.insertDatabase(content, color, date); } public ArrayList<Note> getAllItemNote() { return manager.getAllNote(this); } public void deleteItemNote(int pos) { manager.deleteId(pos); } }
Python
UTF-8
2,314
2.640625
3
[]
no_license
import torch import torch.autograd as autograd import torch.nn as nn import torch.optim as optim import numpy as np import torch.nn.functional as F class WordEmb(nn.Module): def __init__(self, voc_size, emb_size, hidden_size, device, use_lstm): super(WordEmb, self).__init__() self.voc_size = voc_size self.emb_size = emb_size self.hidden_dim = hidden_size self.device = device self.use_lstm = use_lstm ## Words_emb self.words_emb = nn.Embedding(self.voc_size, self.emb_size) self._init_emb() ## LSTM if self.use_lstm: self.lstm = nn.LSTM(self.emb_size, self.hidden_dim // 2, num_layers=2, bidirectional=True) else: self._projection = nn.Linear(emb_size, hidden_size) def _init_emb(self): r = 0.5 / self.voc_size self.words_emb.weight.data.uniform_(-r, r).to(self.device) def init_hidden(self, batch_size, device): return (torch.randn(4, batch_size, self.hidden_dim // 2).to(device), torch.randn(4, batch_size, self.hidden_dim // 2).to(device)) def forward(self, sentences: torch.Tensor): """ Arg: sentence: (batch_size,seq_len,words_idx) Output: lstm_out: (batch_size,seq_len,hidden_size) """ embs = self.words_emb(sentences) embs = embs.transpose(0, 1) if self.use_lstm: batch_size = sentences.size(0) self.hiddens = self.init_hidden(batch_size, sentences.device) # print(embs.shape,self.hiddens) lstm_out, self.hiddens = self.lstm(embs, self.hiddens) return lstm_out.transpose(0, 1) else: return self._projection(embs) def eval(self, sentences: torch.Tensor): """ Arg: sentence: (batch_size,seq_len,words_idx) Output: lstm_out: (batch_size,seq_len,hidden_size) """ embs = self.words_emb(sentences).view(sentences.size(1), sentences.size(0), self.emb_size) self.hiddens = self.init_hidden(sentences.size(0)) lstm_out, self.hiddens = self.lstm(embs, self.hiddens) return lstm_out.transpose(0, 1)
PHP
UTF-8
10,334
2.65625
3
[]
no_license
<?php //nombre de la sesion, inicio de la sesión y conexion con la base de datos include ("sis/nombre_sesion.php"); //verifico si la sesión está creada y si no lo está lo envio al logueo if (!isset($_SESSION['correo'])) { header("location:logueo.php"); } ?> <?php //variables de la sesion include ("sis/variables_sesion.php"); ?> <?php //capturo las variables que pasan por URL o formulario if(isset($_POST['consultaBusqueda'])) $consultaBusqueda = $_POST['consultaBusqueda']; elseif(isset($_GET['consultaBusqueda'])) $consultaBusqueda = $_GET['consultaBusqueda']; else $consultaBusqueda = null; if(isset($_POST['recibir'])) $recibir = $_POST['recibir']; elseif(isset($_GET['recibir'])) $recibir = $_GET['recibir']; else $recibir = null; if(isset($_POST['producto_id'])) $producto_id = $_POST['producto_id']; elseif(isset($_GET['producto_id'])) $producto_id = $_GET['producto_id']; else $producto_id = null; if(isset($_POST['producto'])) $producto = $_POST['producto']; elseif(isset($_GET['producto'])) $producto = $_GET['producto']; else $producto = null; if(isset($_POST['unidad'])) $unidad = $_POST['unidad']; elseif(isset($_GET['unidad'])) $unidad = $_GET['unidad']; else $unidad = null; if(isset($_POST['produccion_producto_id'])) $produccion_producto_id = $_POST['produccion_producto_id']; elseif(isset($_GET['produccion_producto_id'])) $produccion_producto_id = $_GET['produccion_producto_id']; else $produccion_producto_id = null; if(isset($_POST['produccion_id'])) $produccion_id = $_POST['produccion_id']; elseif(isset($_GET['produccion_id'])) $produccion_id = $_GET['produccion_id']; else $produccion_id = null; if(isset($_POST['cantidad'])) $cantidad = $_POST['cantidad']; elseif(isset($_GET['cantidad'])) $cantidad = $_GET['cantidad']; else $cantidad = null; if(isset($_POST['mensaje'])) $mensaje = $_POST['mensaje']; elseif(isset($_GET['mensaje'])) $mensaje = $_GET['mensaje']; else $mensaje = null; if(isset($_POST['body_snack'])) $body_snack = $_POST['body_snack']; elseif(isset($_GET['body_snack'])) $body_snack = $_GET['body_snack']; else $body_snack = null; if(isset($_POST['mensaje_tema'])) $mensaje_tema = $_POST['mensaje_tema']; elseif(isset($_GET['mensaje_tema'])) $mensaje_tema = $_GET['mensaje_tema']; else $mensaje_tema = null; ?> <?php //consulto la información de la produccion $consulta = $conexion->query("SELECT * FROM producciones_p WHERE id = '$produccion_id'"); if ($fila = $consulta->fetch_assoc()) { $produccion_id = $fila['id']; $fecha = date('d M', strtotime($fila['fecha'])); $hora = date('h:i:s a', strtotime($fila['fecha'])); $destino = $fila['destino']; $estado = $fila['estado']; //consulto el local destino $consulta2 = $conexion->query("SELECT * FROM locales WHERE id = $destino"); if ($filas2 = $consulta2->fetch_assoc()) { $destino = $filas2['local']; } else { $destino = "No se ha asignado un local destino"; } } ?> <?php //agrego el componente producido al inventario del local o punto de venta if ($recibir == 'si') { $inventario_maximo = $cantidad; $inventario_minimo = floor(($cantidad * 20) / 100); //consutlo si ya existe este componente compuesto en el inventario $consulta_inventario = $conexion->query("SELECT * FROM inventario_productos WHERE producto_id = '$producto_id' and local_id = '$sesion_local_id'"); //si no existe lo creo en el inventario if ($consulta_inventario->num_rows == 0) { $crear_inventario = $conexion->query("INSERT INTO inventario_productos values ('', '$ahora', '$sesion_id', '$producto_id', '$producto', '$cantidad', '$unidad', '$inventario_minimo', '$inventario_maximo', '$sesion_local_id')"); $inventario_id = $conexion->insert_id; if ($crear_inventario) { $mensaje = number_format($cantidad, 0, ",", ".")." ".ucfirst($unidad)." de <b>".ucfirst($producto)."</b> creado en el inventario"; $body_snack = 'onLoad="Snackbar()"'; $mensaje_tema = "aviso"; } $cantidad_actual = 0; $nueva_cantidad = $cantidad_actual + $cantidad; $operacion = "suma"; $motivo = "primera produccion"; $descripcion = "produccion No $produccion_id"; } else { if ($fila_inventario = $consulta_inventario->fetch_assoc()) { $inventario_id = $fila_inventario['id']; $cantidad_actual = $fila_inventario['cantidad']; } $nueva_cantidad = $cantidad_actual + $cantidad; $inventario_maximo = $nueva_cantidad; $inventario_minimo = floor(($nueva_cantidad * 20) / 100); $operacion = "suma"; $motivo = "produccion"; $descripcion = "produccion No $produccion_id"; $actualizar_inventario = $conexion->query("UPDATE inventario_productos SET fecha = '$ahora', cantidad = '$nueva_cantidad', producto = '$producto', minimo = '$inventario_minimo', maximo = '$inventario_maximo' WHERE producto_id = '$producto_id' and local_id = '$sesion_local_id'"); if ($actualizar_inventario) { $mensaje = number_format($cantidad, 0, ",", ".")." ".ucfirst($unidad)." de <b>".ucfirst($producto)."</b> actualizado en el inventario"; $body_snack = 'onLoad="Snackbar()"'; $mensaje_tema = "aviso"; } } //actualizo el estado del componente en la produccion a recibido $actualizo_componente = $conexion->query("UPDATE producciones_p_productos SET estado = 'recibido' WHERE id = '$produccion_producto_id'"); //genero la novedad $insertar_novedad = $conexion->query("INSERT INTO inventario_novedades values ('', '$ahora', '$sesion_id', '$inventario_id', '$cantidad_actual', '$operacion', '$cantidad', '$nueva_cantidad', '$motivo', '$descripcion')"); } ?> <!DOCTYPE html> <html lang="es"> <head> <title>ManGo!</title> <?php //información del head include ("partes/head.php"); //fin información del head ?> </head> <body <?php echo $body_snack; ?>> <header class="rdm-toolbar--contenedor"> <div class="rdm-toolbar--fila"> <div class="rdm-toolbar--izquierda"> <a href="inventario_p_ver.php"><div class="rdm-toolbar--icono"><i class="zmdi zmdi-arrow-left zmdi-hc-2x"></i></div></a> <h2 class="rdm-toolbar--titulo">Recibir producción</h2> </div> </div> </header> <main class="rdm--contenedor-toolbar"> <?php //consulto los componentes $consulta = $conexion->query("SELECT * FROM producciones_p_productos WHERE produccion_id = '$produccion_id' and estado = 'enviado' ORDER BY fecha DESC"); if ($consulta->num_rows == 0) { //si ya no hay componentes por recibir cambio el estado del despacho a recibido $actualizo_produccion = $conexion->query("UPDATE producciones_p SET fecha_recibe = '$ahora', estado = 'recibido', usuario_recibe = '$sesion_id' WHERE id = '$produccion_id'"); header("location:inventario_p_ver.php"); } else { ?> <section class="rdm-lista"> <?php while ($fila = $consulta->fetch_assoc()) { $produccion_producto_id = $fila['id']; $fecha = date('Y/m/d', strtotime($fila['fecha'])); $hora = date('h:i:s a', strtotime($fila['fecha'])); $producto_id = $fila['producto_id']; $cantidad = $fila['cantidad']; $cantidadx = $fila['cantidad']; //consulto el producto $consulta2 = $conexion->query("SELECT * FROM productos WHERE id = $producto_id"); if ($filas2 = $consulta2->fetch_assoc()) { $producto = $filas2['producto']; } else { $producto = "No se ha asignado un producto"; } //consulto el inventario actual en el destino $consulta3 = $conexion->query("SELECT * FROM inventario_productos WHERE local_id = $sesion_local_id and producto_id = '$producto_id'"); if ($filas3 = $consulta3->fetch_assoc()) { $inventario_id = ucfirst($filas3['id']); $cantidad_actual = ucfirst($filas3['cantidad']); //si la cantidad actual es cero o negativa if ($cantidad_actual <= 0) { $cantidad_actual = 0; } } else { $cantidad_actual = "0"; $inventario_id = 1; } $cantidad_nueva = $cantidad_actual + $cantidad; ?> <article class="rdm-lista--item-sencillo"> <div class="rdm-lista--izquierda-sencillo"> <div class="rdm-lista--contenedor"> <div class="rdm-lista--icono"><i class="zmdi zmdi-labels zmdi-hc-2x"></i></div> </div> <div class="rdm-lista--contenedor"> <h2 class="rdm-lista--titulo"><?php echo ucfirst("$producto"); ?></h2> <h2 class="rdm-lista--texto-secundario"><?php echo number_format($cantidad_actual, 0, ",", "."); ?> + <span class="rdm-lista--texto-resaltado"><?php echo number_format($cantidad, 0, ",", "."); ?></span> = <?php echo number_format($cantidad_nueva, 0, ",", "."); ?> Unid</h2> </div> </div> <div class="rdm-lista--derecha"> <a href="produccion_p_recibir.php?recibir=si&produccion_producto_id=<?php echo "$produccion_producto_id";?>&producto_id=<?php echo "$producto_id";?>&producto=<?php echo "$producto";?>&unidad=Unid&cantidad=<?php echo "$cantidadx";?>&produccion_id=<?php echo "$produccion_id";?>"><div class="rdm-lista--icono"><i class="zmdi zmdi-check zmdi-hc-2x"></i></div></a> </div> </article> <?php } ?> </section> <?php } ?> </main> <div id="rdm-snackbar--contenedor"> <div class="rdm-snackbar--fila"> <div class="rdm-snackbar--primario-<?php echo $mensaje_tema; ?>"> <h2 class="rdm-snackbar--titulo"><?php echo "$mensaje"; ?></h2> </div> </div> </div> <footer> </footer> </body> </html>
Markdown
UTF-8
4,629
2.859375
3
[]
no_license
# 2313 软件工程实习 ```cpp //freopen("D:\\input.txt","r",stdin); //ios::sync_with_stdio(false); #include<bits/stdc++.h> using namespace std; #define MAXN 1005 #define MAXK 30 struct Stu{ int grade,finalGrade; char group; }; Stu stus[MAXN]; int groupGrades[MAXK][MAXK]; int groupFinalGrades[MAXK]; int n,k; bool cmp(const Stu&s1,const Stu&s2){ return s1.finalGrade!=s2.finalGrade ? s1.finalGrade>s2.finalGrade : s1.group<s2.group; } int main(){ //freopen("D:\\input.txt","r",stdin); //输入 cin>>n>>k; int grade; char grp; for(int i=0;i<n;i++){ cin>>grade>>grp; stus[i]={grade,0,grp}; } for(int i=0;i<k;i++){ for(int j=0;j<k;j++){ cin>>groupGrades[i][j]; } } //计算每组最终项目分 for(int i=0;i<k;i++){ int summ=0; float avg; for(int j=0;j<k;j++){ summ+=groupGrades[j][i]; } avg=(float)summ/k; summ=0; int cnt=0; for(int j=0;j<k;j++){ if(abs(avg-groupGrades[j][i])<=15.0){ summ+=groupGrades[j][i]; cnt++; } } groupFinalGrades[i]=round((float)summ/cnt); } //计算每个同学的最终得分 for(int i=0;i<n;i++){ stus[i].finalGrade=round((float)stus[i].grade*0.6+(float)groupFinalGrades[stus[i].group-'A']*0.4); } //排序 sort(stus,stus+n,cmp); //输出 for(int i=0;i<n;i++){ cout<<stus[i].finalGrade<<" "<<stus[i].group<<endl; } return 0; } ``` # 2314 程序员发橙子 ```cpp //freopen("D:\\input.txt","r",stdin); //ios::sync_with_stdio(false); #include<bits/stdc++.h> using namespace std; #define MAXN 1000005 int n; int a[MAXN]; int b[MAXN]; long long ans=0; void init(){ memset(b,0,sizeof(b)); } bool legal(int i,int j){ return (a[i]==a[j]&&b[i]==b[j] || a[i]<a[j]&&b[i]<b[j] || a[i]>a[j]&&b[i]>b[j]); } int main(){ //freopen("D:\\input.txt","r",stdin); init(); cin>>n; if(n==0){ cout<<0; return 0; } for(int i=0;i<n;i++){ cin>>a[i]; } b[0]=1; ans+=b[0]; for(int i=1;i<n;i++){ if(a[i]==a[i-1]){ b[i]=b[i-1]; ans+=b[i]; }else if(a[i]>a[i-1]){ b[i]=b[i-1]+1; ans+=b[i]; }else{ if(b[i-1]==1){ b[i-1]++; b[i]=1; ans+=2; for(int j=i-1;j>0;j--){ if(legal(j-1,j)){ break; }else{ int temp=b[j-1]; if(a[j-1]>a[j]){ b[j-1]=b[j]+1; ans+=(b[j-1]-temp); }else if(a[j-1]==a[j]){ b[j-1]=b[j]; ans+=(b[j-1]-temp); } } } }else{ b[i]=1; ans+=b[i]; } } } cout<<ans; return 0; } ``` # 2315 众数出现的次数 输入为a,b,a和b异或为c; 若a和c不一样,则累加a和c的次数,若a和c一样,则累加a的次数 ```cpp //freopen("D:\\input.txt","r",stdin); //ios::sync_with_stdio(false); #include<bits/stdc++.h> using namespace std; int n; map<int,int> mp; int main(){ //freopen("D:\\input.txt","r",stdin); cin>>n; int a,b,c; for(int i=0;i<n;i++){ cin>>a>>b; c=(a^b); //cout<<a<<" "<<b<<" "<<c<<endl;/////// if(a!=c){ mp[a]++; mp[c]++; }else{ mp[a]++; } } int maxCnt=-1,num; for(auto&i:mp){ if(i.second>maxCnt){ maxCnt=i.second; num=i.first; } } cout<<num; return 0; } ``` # 2316 特殊的翻转 ```cpp //freopen("D:\\input.txt","r",stdin); //ios::sync_with_stdio(false); #include<bits/stdc++.h> using namespace std; string input; vector<bool> vec; vector<int> cnts; int minTime=1e8; void swap2(int i){ cnts[i]++; if(i-1>=0)cnts[i-1]++; if(i+1<cnts.size())cnts[i+1]++; } void deswap2(int i){ cnts[i]--; if(i-1>=0)cnts[i-1]--; if(i+1<cnts.size())cnts[i+1]--; } bool isright(int i){ if(i<0)return true; return !((vec[i]&&cnts[i]%2==0) || (!vec[i]&&cnts[i]%2==1)); } void dfs(int i,int time){ if(i>=vec.size()){ //cout<<isright(i-2)<<" "<<isright(i-1)<<endl;////// if(isright(i-2)&&isright(i-1)){ if(time < minTime){ minTime=time; } } return; } if(!isright(i-2)){ return; } dfs(i+1,time); swap2(i); dfs(i+1,time+1); deswap2(i); } void convertToBin(char c, vector<bool>& a){ int temp=(isdigit(c)?c-'0':c-'A'+10); while(temp!=0){ a.push_back(temp%2); temp/=2; } for(int i=a.size();i<4;i++)a.push_back(false); reverse(a.begin(),a.end()); } int main(){ freopen("D:\\input.txt","r",stdin); cin>>input; for(int i=0;i<input.size();i++){ vector<bool> a; convertToBin(input[i],a); if(vec.size()==0){ auto it=a.begin(); while(it!=a.end()){ if(*it){ break; }else{ a.erase(it); it=a.begin(); } } } for(int j=0;j<a.size();j++){ vec.push_back(a[j]); } } cnts.resize(vec.size()); for(int i=0;i<cnts.size();i++)cnts[i]=0; //init cnts dfs(0,0); if(minTime!=1e8){ cout<<minTime; }else{ cout<<"No"; } } ``` 超时,因为我用的DFS
JavaScript
UTF-8
890
3.890625
4
[]
no_license
//Object Destructuring const person = { name: 'Hari', age: 23, location: { city: 'Atlanta', temp: 55 } }; const {name: firstName = 'Anonymous', age} = person; console.log(`${firstName} is ${age}.`); const {temp: temperature, city: cityName} = person.location; console.log(`It's ${temperature} in ${cityName}`); //Personal Challenge const book = { title: 'Baahubali', author: 'Vijayendra Prasad', publisher: { name: 'Arka Media' } }; const {name: publisherName = 'K Ragavendra Rao Presents'} = book.publisher; console.log(publisherName); //Array destructuring const address = ['550 Pharr Rd NE', 'Atlanta', 'GA', 30324]; const [, , state='Georgia'] = address; console.log(`You are in ${state}`); const item = ['Coffee (hot)', '$2.00', '$2.50', '$2.75']; const[itemName, , mediumPrice] = item; console.log(`A medium ${itemName} costs ${mediumPrice}`);
Ruby
UTF-8
2,119
3.734375
4
[]
no_license
require 'mathn.rb' #сплайны #сама функция f(x) def f(x) x**2 - Math::log10(x + 2) end #производная f(x) def df(x) 2*x - 1/(x + 2)/Math::log(10) end $a = 0.5 $b = 1.0 x1 = 0.53 x2 = 0.52 x3 = 0.97 x4 = 0.73 $h = ($b - $a)/10 #Табличные значения $xi = Array.new(11){|i| $a + $h * i} $fi = Array.new(11){|i| f($xi[i])} $dfi = Array.new(11){|i| df($xi[i])} class Spline #конструктор def initialize(xi, fi, dy0, dyn, h) n = xi.length @xi = xi @y = fi @a = Array.new(n) {0} @b = Array.new(n) {0} @m = Array.new(n) {0} temp = Array.new(n-2) { |i| 3*(@y[i+2] - @y[i])/h } temp[0] -= dy0 temp[n-3] -= dyn @m = pr(Array.new(n-2){1}, Array.new(n-2){4}, Array.new(n-2){1}, temp) @m.push(dyn) @m.unshift(dy0) for i in (0...n-1) @a[i] = 6/h*((@y[i+1] - @y[i])/h - (@m[i+1] + 2*@m[i])/3) @b[i] = 12/(h**2)*((@m[i+1] + @m[i])/2 - (@y[i+1] - @y[i])/h) end end #метод прогонки def pr(a, b, c, f) n = f.length a[0] = 0; c[n - 1] = 0; u = Array.new(f.length) alf = Array.new(f.length) bet = Array.new(f.length) alf[0] = -c[0]/b[0] bet[0] = f[0]/b[0] for i in (0...n-1) alf[i+1] = -c[i]/(alf[i]*a[i] + b[i]) bet[i+1] = (f[i] - bet[i]*a[i])/(alf[i]*a[i] + b[i]) end u[n-1] =(f[n-1] - bet[n-1]*a[n-1])/(b[n-1] + alf[n-1]*a[n-1]) for i in (0...n-1).to_a.reverse u[i] = alf[i+1]*u[i+1] + bet[i+1] end return u end #Получение значения def get_value(x) n = @xi.length k = -1 for i in (0...n-1) if (x >= @xi[i] and x <= @xi[i + 1]) k = i end end @y[k] + @m[k]*(x - @xi[k]) + @a[k]*((x - @xi[k])**2)/2 + @b[k]*((x - @xi[k])**3)/6 end end; s = Spline.new $xi, $fi, $dfi.first, $dfi.last, $h puts "S: #{s.get_value(x1)}" puts "f: #{f(x1)}" puts "R: #{f(x1) - s.get_value(x1)}\n\n" puts "S: #{s.get_value(x2)}" puts "f: #{f(x2)}" puts "R: #{f(x2) - s.get_value(x2)}\n\n" puts "S: #{s.get_value(x3)}" puts "f: #{f(x3)}" puts "R: #{f(x3) - s.get_value(x3)}\n\n" puts "S: #{s.get_value(x4)}" puts "f: #{f(x4)}" puts "R: #{f(x4) - s.get_value(x4)}\n\n"
PHP
UTF-8
296
2.703125
3
[]
no_license
<?php namespace testonaut\Selenese\Command; use testonaut\Selenese\Command; // title() class Title extends Command { public function runWebDriver(\WebDriver $session) { $title = $session->getTitle(); return $this->commandResult(true, true, 'Got page title: "' . $title . '"'); } }
Java
UTF-8
584
2.109375
2
[]
no_license
package com.shop.biz; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "productList") @XmlAccessorType(XmlAccessType.FIELD) public class ProductListVO { @XmlElement(name = "product") private List<ProductVO> productList; public List<ProductVO> getProductList() { return productList; } public void setProductList(List<ProductVO> productList) { this.productList = productList; } }
TypeScript
UTF-8
502
2.59375
3
[ "MIT" ]
permissive
import { IsAlphanumeric, IsAscii, IsNotEmpty, IsOptional, IsString, MaxLength, MinLength, } from 'class-validator'; import { IsObjectID } from 'util/CustomClassValidators'; export default class CreatePostsDto { @IsString() @IsAscii() @MinLength(5) @MaxLength(100) title: string; @IsString() @IsAscii() @IsNotEmpty() @MaxLength(5000) content: string; @IsObjectID() @IsAlphanumeric() @IsOptional() parent?: string; }
C++
UTF-8
1,123
3.03125
3
[]
no_license
/* this functions show why cloning is the rigth way to modify the value/vector withoiut changeing the original value/vector DO NOT COPY , COLNE IT*/ #include <Rcpp.h> using namespace Rcpp; // [[Rcpp::export]] List change_negatives_to_zero(NumericVector the_original) { // Set the copy to the original NumericVector the_copy = the_original; int n = the_original.size(); for(int i = 0; i < n; i++) { if(the_copy[i] < 0) the_copy[i] = 0; } return List::create(_["the_original"] = the_original, _["the_copy"] = the_copy); } // [[Rcpp::export]] List change_negatives_to_zero_with_cloning(NumericVector the_original) { // Clone the original to make the copy NumericVector the_copy = clone(the_original); int n = the_original.size(); for(int i = 0; i < n; i++) { if(the_copy[i] < 0) the_copy[i] = 0; } return List::create(_["the_original"] = the_original, _["the_copy"] = the_copy); } /*** R x <- c(0, -4, 1, -2, 2, 4, -3, -1, 3) change_negatives_to_zero(x) # Need to define x again because it's changed now x <- c(0, -4, 1, -2, 2, 4, -3, -1, 3) change_negatives_to_zero_with_cloning(x) */
PHP
UTF-8
795
2.59375
3
[]
no_license
<?php chdir(__DIR__); include_once("baseModel.php"); class EditorModel extends BaseModel { protected $tableName = "documents"; protected $primary = 'DocumentID'; protected $fillable = [ 'DocumentName', 'Alias', 'Tags', 'Text', 'UserID', 'LastUpdate' ]; protected $fieldMap = [ 'docName' => 'DocumentName', 'alias' => 'Alias', 'tags' => 'Tags', 'text' => 'Text', 'delete' => 'IsDeleted' ]; public function update ($id, $data) { $dataToUpdate = []; foreach ($data as $key => $value) { if (array_key_exists($key, $this->fieldMap)) $dataToUpdate[$this->fieldMap[$key]] = $value; } return parent::update($id, $dataToUpdate); // TODO: Change the autogenerated stub } }
Python
UTF-8
719
4.125
4
[ "MIT" ]
permissive
from time import sleep def contador(i, f, p): if p == 0: if i > f: p = -1 else: p = 1 print(f'{"-=" * 25} \nContagem de {i} a {f} de {p} em {p}:') for c in range(i, f, p): print(f'{c} ', end='') sleep(1) print() return 'Fim' print(f'{"-=" * 25} \nContagem de 0 a 10 de 1 em 1:') for c in range(0, 11): print(f'{c} ', end='') sleep(1) print(f"\n{'-=' * 25} \nContagem de 10 a 0 de 2 em 2:") for c in range(10, -1, -2): print(f'{c} ', end='') sleep(1) print(f'\n{"-=" * 25} \nAgora é sua vez de personalizar a contagem!') i = int(input('Inicio: ')) f = int(input('Fim: ')) p = int(input('Passo: ')) print(contador(i, f, p))
Python
UTF-8
8,924
2.78125
3
[ "MIT" ]
permissive
#!/usr/bin/env python3 # SPDX-FileCopyrightText: Christian Amsüss and the aiocoap contributors # # SPDX-License-Identifier: MIT """This script does not do anything really CoAP-related, but is a testing tool for multicast messages. It binds to multicast addresses of different scopes (ff02::1:2, ff05::1:5) on different ports (2002 and 2005), tries sending with different settings (zone set in source or destination), and reports the findings. It was written to verify observations made with `ping` -- namely, that for link-local addresses it is sufficient to give the zone identifier in the target (`ping ff02::1%eth0` works), but that for wider scopes like site-local, the zone identifier must be on the source address, even if that's empty (`ping ff05::1 -I eth0`). On Linux, it is required to set a source address for at least the ff05 class of addresses (and that working mental model is reflected in any error messages); FreeBSD behaves in a way that appears more sane and accepts a zone identifier even in the destination address. """ import argparse import socket import struct import time in6_pktinfo = struct.Struct("16sI") p = argparse.ArgumentParser(description=__doc__) p.add_argument("ifname", help="Network interface name to bind to and try to send to") p.add_argument("bindaddr", help="Address to bind to on the interface (default: %(default)s)", default="::", nargs="?") p.add_argument("unicast_addr", help="Address to send the initial unicast test messages to (default: %(default)s)", default="::1", nargs="?") p.add_argument("nonlocal_multicast", help="Address to use for the zone-free multicast test (default: %(default)s", default="ff35:30:2001:db8::1", nargs="?") args = p.parse_args() ifindex = socket.if_nametoindex(args.ifname) listen2 = socket.socket(family=socket.AF_INET6, type=socket.SOCK_DGRAM) listen2.bind((args.bindaddr, 2002)) s = struct.pack('16si', socket.inet_pton(socket.AF_INET6, 'ff02::1:2'), ifindex) listen2.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, s) listen5 = socket.socket(family=socket.AF_INET6, type=socket.SOCK_DGRAM) listen5.bind((args.bindaddr, 2005)) s = struct.pack('16si', socket.inet_pton(socket.AF_INET6, 'ff05::1:5'), ifindex) listen5.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, s) sender = socket.socket(family=socket.AF_INET6, type=socket.SOCK_DGRAM) sender.sendmsg([b"Test1"], [], 0, ('::1', 2002)) sender.sendmsg([b"Test2"], [], 0, ('::1', 2005)) time.sleep(0.2) assert listen2.recv(1024, socket.MSG_DONTWAIT) == b"Test1" assert listen5.recv(1024, socket.MSG_DONTWAIT) == b"Test2" print("Unicast tests passed") # Setting no interface index # # ff02: On FreeBSD this fails on send with OSError, on Linux only at receiving # ff05 fails on Linux and works on FreeBSD, but that could be an artefact of default routes. print("Sending to ff02::2".format(args.ifname)) try: sender.sendmsg([b"Test3"], [], 0, ('ff02::1:2', 2002, 0, 0)) time.sleep(0.2) assert listen2.recv(1024, socket.MSG_DONTWAIT) == b"Test3" except (OSError, BlockingIOError) as e: print("Erred with %r, as expected" % e) else: print("That was not expected to work!") print("Sending to ff05::5".format(args.ifname)) try: sender.sendmsg([b"Test4"], [], 0, ('ff05::1:5', 2005, 0, ifindex)) time.sleep(0.2) assert listen5.recv(1024, socket.MSG_DONTWAIT) == b"Test4" except (OSError, BlockingIOError) as e: print("Erred with %r, as expected" % e) else: print("That was not expected to work!") # Setting the ifindex in the destination only works for ff02 and not for ff05 print("Sending to ff02::2%{}".format(args.ifname)) sender.sendmsg([b"Test5"], [], 0, ('ff02::1:2', 2002, 0, ifindex)) time.sleep(0.2) assert listen2.recv(1024, socket.MSG_DONTWAIT) == b"Test5" print("Sending to ff05::5%{}".format(args.ifname)) sender.sendmsg([b"Test6"], [], 0, ('ff05::1:5', 2005, 0, ifindex)) time.sleep(0.2) try: assert listen5.recv(1024, socket.MSG_DONTWAIT) == b"Test6" except BlockingIOError: print("Failed as expected for Linux") else: print("That was not expected to work!") # Setting the ifindex in the source works for both print("Sending to ff02::2 from ::%{}".format(args.ifname)) dest = in6_pktinfo.pack(socket.inet_pton(socket.AF_INET6, '::'), ifindex) sender.sendmsg([b"Test7"], [(socket.IPPROTO_IPV6, socket.IPV6_PKTINFO, dest)], 0, ('ff02::1:2', 2002, 0, 0)) time.sleep(0.2) assert listen2.recv(1024, socket.MSG_DONTWAIT) == b"Test7" print("Sending to ff05::5 from {}".format(args.ifname)) dest = in6_pktinfo.pack(socket.inet_pton(socket.AF_INET6, '::'), ifindex) sender.sendmsg([b"Test8"], [(socket.IPPROTO_IPV6, socket.IPV6_PKTINFO, dest)], 0, ('ff05::1:5', 2005, 0, 0)) time.sleep(0.2) assert listen5.recv(1024, socket.MSG_DONTWAIT) == b"Test8" # Setting both works on both (unlike when testing this with ping) print("Sending to ff02::2%{} from ::%{}".format(args.ifname, args.ifname)) dest = in6_pktinfo.pack(socket.inet_pton(socket.AF_INET6, '::'), ifindex) sender.sendmsg([b"Test9"], [(socket.IPPROTO_IPV6, socket.IPV6_PKTINFO, dest)], 0, ('ff02::1:2', 2002, 0, ifindex)) time.sleep(0.2) assert listen2.recv(1024, socket.MSG_DONTWAIT) == b"Test9" print("Sending to ff05::5%{} from {}".format(args.ifname, args.ifname)) dest = in6_pktinfo.pack(socket.inet_pton(socket.AF_INET6, '::'), ifindex) sender.sendmsg([b"Test10"], [(socket.IPPROTO_IPV6, socket.IPV6_PKTINFO, dest)], 0, ('ff05::1:5', 2005, 0, ifindex)) time.sleep(0.2) assert listen5.recv(1024, socket.MSG_DONTWAIT) == b"Test10" # global addresses shouldn't need a thing (there's routability), but still do print("Binding to {} on {}".format(args.nonlocal_multicast, args.ifname)) listendb8 = socket.socket(family=socket.AF_INET6, type=socket.SOCK_DGRAM) listendb8.bind((args.bindaddr, 2008)) s = struct.pack('16si', socket.inet_pton(socket.AF_INET6, args.nonlocal_multicast), ifindex) listendb8.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, s) print("Sending to {}%{}".format(args.nonlocal_multicast, args.ifname)) sender.sendmsg([b"Test11"], [], 0, (args.nonlocal_multicast, 2008, 0, ifindex)) time.sleep(0.2) try: assert listendb8.recv(1024, socket.MSG_DONTWAIT) == b"Test11" except BlockingIOError: print("Failed as expected for Linux") else: print("That was not expected to work!") print("Sending to {} from {}".format(args.nonlocal_multicast, args.ifname)) dest = in6_pktinfo.pack(socket.inet_pton(socket.AF_INET6, '::'), ifindex) sender.sendmsg([b"Test12"], [(socket.IPPROTO_IPV6, socket.IPV6_PKTINFO, dest)], 0, (args.nonlocal_multicast, 2008, 0, 0)) time.sleep(0.2) assert listendb8.recv(1024, socket.MSG_DONTWAIT) == b"Test12" print("Sending to {} without interface".format(args.nonlocal_multicast)) sender.sendmsg([b"Test13"], [], 0, (args.nonlocal_multicast, 2008, 0, 0)) time.sleep(0.2) try: assert listendb8.recv(1024, socket.MSG_DONTWAIT) == b"Test13" except BlockingIOError: print("Failed as expected for Linux") else: print("That was not expected to work!") print("Now binding to {} without interface specification".format(args.nonlocal_multicast, args.ifname)) listendb8any = socket.socket(family=socket.AF_INET6, type=socket.SOCK_DGRAM) listendb8any.bind((args.bindaddr, 2018)) s = struct.pack('16si', socket.inet_pton(socket.AF_INET6, args.nonlocal_multicast), 0) listendb8any.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, s) print("Sending to {}%{}".format(args.nonlocal_multicast, args.ifname)) sender.sendmsg([b"Test14"], [], 0, (args.nonlocal_multicast, 2018, 0, ifindex)) time.sleep(0.2) try: assert listendb8.recv(1024, socket.MSG_DONTWAIT) == b"Test14" except BlockingIOError: print("Failed as expected") else: print("That was not expected to work!") print("Sending to {} from {}".format(args.nonlocal_multicast, args.ifname)) dest = in6_pktinfo.pack(socket.inet_pton(socket.AF_INET6, '::'), ifindex) sender.sendmsg([b"Test15"], [(socket.IPPROTO_IPV6, socket.IPV6_PKTINFO, dest)], 0, (args.nonlocal_multicast, 2018, 0, 0)) time.sleep(0.2) try: assert listendb8.recv(1024, socket.MSG_DONTWAIT) == b"Test15" except BlockingIOError: print("Failed as expected") else: print("That was not expected to work!") print("Sending to {} without interface".format(args.nonlocal_multicast)) sender.sendmsg([b"Test16"], [], 0, (args.nonlocal_multicast, 2018, 0, 0)) time.sleep(0.2) try: assert listendb8.recv(1024, socket.MSG_DONTWAIT) == b"Test16" except BlockingIOError: print("Failed as expected") else: print("That was not expected to work!")
Python
UTF-8
869
2.640625
3
[]
no_license
import pandas as pd import os import glob from settings.general import TAGS def glue_by_tags(data_path='data/', tags=[]): df = pd.DataFrame( columns=['text', 'hashtags', 'datetime', 'likes', 'owner', 'owner_followers', 'owner_number_posts']) if len(tags) > 0: for tag in tags: if not os.path.isdir(data_path + tag): continue for fname in glob.glob(data_path + tag + '/*.csv'): df = df.append(pd.read_csv(fname).drop('Unnamed: 0', axis=1)) else: subdirs = [x[0] for x in os.walk(data_path)] for subdir in subdirs[1:]: for fname in glob.glob(subdir + '/*.csv'): df = df.append(pd.read_csv(fname).drop('Unnamed: 0', axis=1)) df.to_csv('data/all_posts.csv') glue_by_tags('backups/all_posts/', TAGS)
C#
UTF-8
2,136
3.203125
3
[]
no_license
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ConsoleApp { public class Test_05 { //https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/bitwise-and-shift-operators public Test_05() { //Räkna antalet unika objekt i slaskHinken List<Object> slaskHinken = new(); slaskHinken.Add("överbliven text"); slaskHinken.Add("oj oj, vad mycket text det har blivit över"); slaskHinken.Add(23); slaskHinken.Add(23); slaskHinken.Add(new int()); slaskHinken.Add(new int()); slaskHinken.Add((Int64)(int.MaxValue) + 1); slaskHinken.Add((Int64)(int.MaxValue) - 1); slaskHinken.Add(new int[] { 1, 3, 5, 7, 9 }); slaskHinken.Add(new int[] { 1, 3, 5, 7, 19 }); UniqueItemsController(slaskHinken, 8, true, "Test_05 : Test1"); } public void UniqueItemsController(List<Object> items, int uniqueItems, bool correctCount, string message) { try { Assert.AreEqual(ItemsController(items, uniqueItems), correctCount, message); } catch (Exception e) { Debug.WriteLine(""); Debug.WriteLine(e.Message); } } public bool ItemsController(List<Object> items, int uniqueItems) { //YOUR CODE GOES HERE, MAKE ALL ASSERT TESTS PASS //Kan göras med generics och två loopar, eller med distinct int countedItems = items.Distinct().Count(); if (countedItems == uniqueItems) { Console.WriteLine($"countedItems: {countedItems}. uniqueItems: {uniqueItems} = OK"); return true; } else { Console.WriteLine($"countedItems: {countedItems}. uniqueItems: {uniqueItems} = EJ OK"); return false; } } } }
Java
UTF-8
2,467
2.0625
2
[ "MIT" ]
permissive
package com.reactnativenavigation.viewcontrollers.common; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.animation.TimeInterpolator; import android.content.Context; import android.view.View; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.DecelerateInterpolator; import com.reactnativenavigation.utils.UiUtils; import androidx.annotation.NonNull; import static android.view.View.ALPHA; import static android.view.View.TRANSLATION_Y; public class BaseAnimator { private static final int DURATION = 300; private static final TimeInterpolator DECELERATE = new DecelerateInterpolator(); private static final TimeInterpolator ACCELERATE_DECELERATE = new AccelerateDecelerateInterpolator(); private final float translationY; public BaseAnimator(Context context) { translationY = UiUtils.getWindowHeight(context); } @NonNull public AnimatorSet getDefaultPushAnimation(View view) { AnimatorSet set = new AnimatorSet(); set.setInterpolator(DECELERATE); set.setDuration(DURATION); ObjectAnimator translationY = ObjectAnimator.ofFloat(view, TRANSLATION_Y, this.translationY, 0); ObjectAnimator alpha = ObjectAnimator.ofFloat(view, ALPHA, 0, 1); translationY.setDuration(DURATION); alpha.setDuration(DURATION); set.playTogether(translationY, alpha); return set; } @NonNull public AnimatorSet getDefaultPopAnimation(View view) { AnimatorSet set = new AnimatorSet(); set.setInterpolator(ACCELERATE_DECELERATE); set.setDuration(DURATION); ObjectAnimator translationY = ObjectAnimator.ofFloat(view, TRANSLATION_Y, 0, this.translationY); ObjectAnimator alpha = ObjectAnimator.ofFloat(view, ALPHA, 1, 0); set.playTogether(translationY, alpha); return set; } @NonNull public AnimatorSet getDefaultSetStackRootAnimation(View view) { AnimatorSet set = new AnimatorSet(); set.setInterpolator(DECELERATE); set.setDuration(DURATION); ObjectAnimator translationY = ObjectAnimator.ofFloat(view, TRANSLATION_Y, this.translationY, 0); ObjectAnimator alpha = ObjectAnimator.ofFloat(view, ALPHA, 0, 1); translationY.setDuration(DURATION); alpha.setDuration(DURATION); set.playTogether(translationY, alpha); return set; } }
Python
UTF-8
1,302
3.703125
4
[]
no_license
class Automovel: def __init__(self, cap_dep, quant_comb, consumo): self.capacidade = cap_dep self.quantidade = quant_comb self.consumo = consumo def devolve_combustivel(self): return f'Quantidade de combustível: {self.quantidade}' def devolve_automonia(self): return f'Autonomia do automóvel: {(self.quantidade*100)/self.consumo}' def devolve_abastece(self, litros): self.quantidade += litros if(self.quantidade > self.capacidade): self.quantidade -= litros return ('Erro') else: return f'Autonomia do automóvel depois do abastecimento: {(self.quantidade*100)/self.consumo}' def devolve_percorre(self, km): autonomia = (self.quantidade*100)/self.consumo diferenca = autonomia - km if(diferenca > 0): return f'Autonomia do automóvel depois de percorrer {km}: {diferenca}' else: return 'Erro' #Chamar funções carro = Automovel(60,10,15) print(carro.devolve_combustivel()) print(carro.devolve_automonia()) print(carro.devolve_abastece(45)) print(carro.devolve_abastece(60)) #Testar a condição de erro print(carro.devolve_percorre(150)) print(carro.devolve_percorre(400)) #Testar a condição de erro
Java
UTF-8
540
2.9375
3
[]
no_license
package xtraprograms; import java.util.Scanner; public class P20 { public static void main(String[] args) { int n,t=1; Scanner read=new Scanner(System.in); System.out.println("Enter any no"); n=read.nextInt(); for(int i=1;i<=n;i++) { for(int a=1;a<=n-i;a++) { System.out.print(" "); } int k=1; for(int j=1;j<=t;j++) { if(j<i) { System.out.print(k); k=k+1; } else{ System.out.print(k); k=k-1; } //System.out.print(j); } System.out.println(); t=t+2; } } }
C++
UTF-8
370
2.703125
3
[]
no_license
#ifndef ARTICLE_H #define ARTICLE_H #include <string> using namespace std; class Article{ public: Article(string title = "", string author = "", string text = "", int id = -1); string getText(); string getTitle(); string getAuthor(); int getID(); private: string title; string author; string text; int id; }; #endif
C++
UTF-8
594
2.671875
3
[]
no_license
#include <iostream> #include <string> using namespace std; int main() { string s; cout << "vvedite stroky"; getline(cin, s); int d = s.size(); int pov = 1; int l = d; int o = 0; int mass[d]; for (int i = 0; i < d - 1; i++){ for (int k = i + 1; k <= d; k++){ if (s[i] == s[k]){ pov++; l--;} else{ mass[o] = pov; o++; pov = 1; i = k; }}} cout << "szhatiye"; for (int i = 0, o = 0; o < l; i += mass[o], o++){ if (mass[o] == 1){ cout << s[i];} else{ cout << mass[o] << s[i];}} return 0; }
PHP
UTF-8
591
2.703125
3
[ "MIT" ]
permissive
<?php namespace Test\Assignment02\Solution3; use Assignment02\Solution3\AccessLevel; class AccessLevelTest extends \PHPUnit_Framework_TestCase { /** * @test */ public function it_can_be_a_high_access_level() { $level = AccessLevel::high(); $this->assertTrue($level->isHigh()); $this->assertFalse($level->isLow()); } /** * @test */ public function it_can_be_a_low_access_level() { $level = AccessLevel::low(); $this->assertTrue($level->isLow()); $this->assertFalse($level->isHigh()); } }
Markdown
UTF-8
577
3.046875
3
[ "MIT" ]
permissive
--- title: "Regular Expressions: Find One or More Criminals in a Hunt" certificate: "Javascript Algorithms and Data Structures" order: 0 --- Certificate: *Javascript Algorithms and Data Structures* #### { Instructions } Write a greedy regex that finds one or more criminals within a group of other people. A criminal is represented by the capital letter C. #### { My Solution } ``` // example crowd gathering let crowd = 'P1P2P3P4P5P6CCCP7P8P9'; let reCriminals = /C+/; // Change this line let matchedCriminals = crowd.match(reCriminals); console.log(matchedCriminals); ```
C#
UTF-8
390
2.609375
3
[]
no_license
using System; using System.Collections.Generic; using System.Text; namespace FP_Exercise { public class BigRig : IVehicle { public BigRig() { } public void Drive() { Console.WriteLine("The BigRig is now moving along to make your delivery on time."); Console.WriteLine("bhunnn Bu Bu Bhunnnn!"); } } }
Java
UTF-8
11,788
1.820313
2
[]
no_license
package com.herenit.mobilenurse.mvp.orders; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.herenit.arms.base.adapter.rv.MultiItemTypeAdapter; import com.herenit.arms.di.component.AppComponent; import com.herenit.arms.mvp.IView; import com.herenit.arms.utils.ArmsUtils; import com.herenit.mobilenurse.R;import com.herenit.mobilenurse.R2; import com.herenit.mobilenurse.app.utils.EventBusUtils; import com.herenit.mobilenurse.criteria.common.Conditions; import com.herenit.mobilenurse.criteria.constant.CommonConstant; import com.herenit.mobilenurse.criteria.constant.KeyConstant; import com.herenit.mobilenurse.criteria.entity.Order; import com.herenit.mobilenurse.criteria.enums.TitleBarTypeEnum; import com.herenit.mobilenurse.criteria.message.eventbus.Event; import com.herenit.mobilenurse.custom.adapter.ConditionAdapter; import com.herenit.mobilenurse.custom.adapter.OrdersAdapter; import com.herenit.mobilenurse.custom.widget.layout.MeasuredGridLayoutManager; import com.herenit.mobilenurse.datastore.tempcache.SickbedTemp; import com.herenit.mobilenurse.mvp.base.BasicCommonFragment; import com.herenit.mobilenurse.mvp.base.ConditionWithListFragment; import com.scwang.smartrefresh.layout.SmartRefreshLayout; import com.scwang.smartrefresh.layout.api.RefreshLayout; import com.scwang.smartrefresh.layout.listener.OnRefreshListener; import org.greenrobot.eventbus.Subscribe; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import butterknife.BindView; /** * author: HouBin * date: 2019/3/6 15:46 * desc:医嘱列表界面,ViewPager载体,详细数据在 */ public class OrderListPagerFragment extends ConditionWithListFragment implements IView { //筛选条件Adapter private ConditionAdapter mConditionAdapter; //医嘱列表Adapter private OrdersAdapter mOrdersAdapter; //筛选条件数据 private List<Conditions> mConditionList = new ArrayList<>(); //医嘱列表数据 private List<Order> mOrderList = new ArrayList<>(); //刷新控件 @BindView(R2.id.srl_orderListPager_refreshLayout) SmartRefreshLayout mRefreshLayout; //底部“全选”、“执行”布局 @BindView(R2.id.ll_orderListPager_bottom) LinearLayout mLL_bottom; @BindView(R2.id.tv_orderListPager_selectAll) TextView mTv_selectAll;//全选 @BindView(R2.id.tv_orderListPager_execute) TextView mTv_execute;//执行 //要执行的医嘱列表 private List<Order> mExecuteOrders = new ArrayList<>(); @Override protected int layoutId() { return R.layout.fragment_order_list_pager; } @Override protected void initView(View contentView) { mOrdersAdapter = new OrdersAdapter(mContext, mOrderList); OrderListFragment parentFragment = (OrderListFragment) getParentFragment(); //获取当前页面是否处于编辑状态,并初始化设置给Adapter mOrdersAdapter.changeEditable(parentFragment.isEditable()); selectedItemChanged(); LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false) { @Override public boolean canScrollVertically() {//canScrollVertically方法返回false,可解决ScrollView嵌套RecyclerView造成的滑动卡顿问题 return false; } }; mRecyclerView.setLayoutManager(layoutManager); mRecyclerView.setAdapter(mOrdersAdapter); mRefreshLayout.setOnRefreshListener(new OnRefreshListener() { @Override public void onRefresh(@NonNull RefreshLayout refreshLayout) { refreshLayout.finishRefresh(CommonConstant.REFRESH_FAIL_TIMEOUT_MILLISECOND, false); //发送通知,刷新医嘱列表数据 String id = EventBusUtils.obtainPrivateId(getParentFragment().toString(), CommonConstant.EVENT_INTENTION_LOAD_DATA); EventBusUtils.post(id, true); } }); mOrdersAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() { @Override public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {//点击单条医嘱,进入医嘱详情界面 if (mOrdersAdapter.isEditable()) {//处于编辑状态,点击Item修改选中状态 mOrdersAdapter.editOrderListBySelectPosition(position); selectedItemChanged(); } else {//处于非编辑状态,点击Item跳转到详情界面 List<Order> currentOrders = mOrdersAdapter.getGroupOrdersByPosition(position); if (currentOrders == null || currentOrders.isEmpty()) return; Intent intent = new Intent(mContext, OrdersInfoActivity.class); intent.putExtra(KeyConstant.NAME_EXTRA_ORDER_LIST, (Serializable) currentOrders); // launchActivity(intent); getParentFragment().startActivityForResult(intent, CommonConstant.REQUEST_CODE_ORDER_INFO); } } @Override public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) { return false; } }); mTv_selectAll.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mOrdersAdapter.isSelectedAll()) {//已经全选,则清空选择 mOrdersAdapter.clearDataListSelect(); } else {//没有全选,则全选 mOrdersAdapter.selectAllCanExecuteOrders(); } selectedItemChanged(); } }); mTv_execute.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { List<Order> executeOrders = mOrdersAdapter.getSelectedOrders(); if (executeOrders == null || executeOrders.isEmpty()) return; //通知OrderListFragment执行医嘱} String id = EventBusUtils.obtainPrivateId(getParentFragment().toString(), CommonConstant.EVENT_INTENTION_EXECUTE_ORDERS); EventBusUtils.post(id, executeOrders); } }); } /** * 选中的医嘱列表发生改变,界面做出改变(是否全选状态、是否可以执行) */ private void selectedItemChanged() { OrderListFragment parentFragment = (OrderListFragment) getParentFragment(); if (parentFragment == null) return; if (!parentFragment.isEditable()) {//如果当前处于不可编辑状态,则不做任何操作 mLL_bottom.setVisibility(View.GONE); return; } mLL_bottom.setVisibility(View.VISIBLE); if (mOrdersAdapter.isSelectedAll()) {//全选状态 mTv_selectAll.setText(R.string.btn_selectAllCancel); } else { mTv_selectAll.setText(R.string.btn_selectAll); } List<Order> selectOrders = mOrdersAdapter.getSelectedOrders(); if (selectOrders == null || selectOrders.isEmpty()) { mTv_execute.setTextColor(ArmsUtils.getColor(mContext, R.color.royalBlueFuzzy)); mTv_execute.setText(R.string.btn_execute); } else { String execute = ArmsUtils.getString(mContext, R.string.btn_execute) + "(" + selectOrders.size() + ")"; mTv_execute.setText(execute); mTv_execute.setTextColor(ArmsUtils.getColor(mContext, R.color.bg_royalBlue)); } } // @Override // public void setUserVisibleHint(boolean isVisibleToUser) { // super.setUserVisibleHint(isVisibleToUser); // if (getUserVisibleHint()) {//当Fragment为可见状态的时候,在设置当前编辑状态,否则容易加载缓存界面出错 // selectedItemChanged(); // } // } /** * 刷新完成 */ public void finishRefresh() { if (mRefreshLayout != null) mRefreshLayout.finishRefresh(); } /** * 返回筛选条件的Adapter * * @return */ @Override public ConditionAdapter conditionAdapter() { // if (mConditionAdapter == null) mConditionAdapter = new ConditionAdapter(mContext, mConditionList, EventBusUtils.obtainPrivateId(this.toString(), CommonConstant.EVENT_INTENTION_CONDITION_CHANGED)); return mConditionAdapter; } /** * 筛选条件发生改变 */ @Override public void conditionChanged() { //通知OrderListFragment 加载医嘱列表 String id = EventBusUtils.obtainPrivateId(getParentFragment().toString(), CommonConstant.EVENT_INTENTION_LOAD_ORDER_LIST); EventBusUtils.post(id, null); //展示条件 mTv_selectCondition.setText(Conditions.getSelectedConditionString(mConditionList)); } @Override public void initData(@Nullable Bundle savedInstanceState) { super.initData(savedInstanceState); //发送通知,加载数据 String id = EventBusUtils.obtainPrivateId(getParentFragment().toString(), CommonConstant.EVENT_INTENTION_LOAD_DATA); EventBusUtils.post(id, false); } @Override public void setData(@Nullable Object data) { } /** * 更新条件UI * * @param conditionsList */ private void updateConditionsUI(List<Conditions> conditionsList) { mConditionList.clear(); if (conditionsList != null) mConditionList.addAll(conditionsList); mConditionAdapter.notifyDataSetChanged(); mTv_selectCondition.setText(Conditions.getSelectedConditionString(mConditionList)); } /** * 更新医嘱UI * * @param orderList */ private void updateOrdersUI(List<Order> orderList) { mOrderList.clear(); if (orderList != null) mOrderList.addAll(orderList); mOrdersAdapter.clearDataListSelect(); if (!mOrderList.isEmpty()) mScrollView.scrollTo(0, 0); } /** * EventBus事件接收 * * @param event */ @Subscribe public void onEventBusReceive(Event event) { String id = event.getId(); if (TextUtils.isEmpty(id)) return; String intention = EventBusUtils.getPrivateEventIntention(this.toString(), id); if (!TextUtils.isEmpty(intention)) {//私有事件消费 if (intention.equals(CommonConstant.EVENT_INTENTION_UPDATE_CONDITION)) {//刷新条件UI updateConditionsUI((List<Conditions>) event.getMessage()); } else if (intention.equals(CommonConstant.EVENT_INTENTION_UPDATE_ORDERS)) {//刷新医嘱列表UI updateOrdersUI((List<Order>) event.getMessage()); } else if (intention.equals(CommonConstant.EVENT_INTENTION_EDITABLE_CHANGED)) {//编辑状态发生改变 boolean editable = (boolean) event.getMessage(); if (mOrdersAdapter != null) mOrdersAdapter.changeEditable(editable);//调用Adapter改变当前是否可编辑状态 selectedItemChanged(); } } } }
C#
UTF-8
1,482
2.65625
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Login.AllUserControl { public partial class UC_Remove : UserControl { function fn = new function(); String query; public UC_Remove() { InitializeComponent(); } private void UC_Remove_Load(object sender, EventArgs e) { loadData(); } public void loadData() { query = "select * from items"; DataSet ds= fn.getData(query); dataGridView1.DataSource = ds.Tables[0]; } private void txtSearch_TextChanged(object sender, EventArgs e) { query = "select * from items where Item_Name like'" + txtSearch.Text + "%'"; DataSet ds = fn.getData(query); dataGridView1.DataSource = ds.Tables[0]; } private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { if(MessageBox.Show("Delete item ?","Important Message",MessageBoxButtons.OKCancel,MessageBoxIcon.Warning)==DialogResult.OK) { int id = int.Parse(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString()); query = "delete from items where id=" + id + ""; fn.SetData(query); loadData(); } } } }
Java
UTF-8
3,095
2.390625
2
[]
no_license
package com.example.mrwing.chess; import android.app.Activity; import android.content.Intent; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class NameInput extends Activity implements View.OnClickListener{ private String p1Set; private String p2Set; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTheme(android.R.style.Theme_NoTitleBar_Fullscreen); setContentView(R.layout.activity_name); Button boardButton = (Button) findViewById(R.id.complete); final EditText player1 = findViewById(R.id.player1_text); final EditText player2 = findViewById(R.id.player2_text); Intent intet = getIntent(); p1Set = intet.getExtras().getString("P1AI"); p2Set = intet.getExtras().getString("P2AI"); Log.i(this.getClass().getName(), p1Set); Log.i(this.getClass().getName(), p2Set); if(p1Set.equals("AI")) { player1.setText("A.I"); player1.setClickable(false); player1.setEnabled(false); player1.setFocusable(false); player1.setFocusableInTouchMode(false); } if(p2Set.equals("AI")) { player2.setText("A.I"); player2.setClickable(false); player2.setEnabled(false); player2.setFocusable(false); player2.setFocusableInTouchMode(false); } boardButton.setOnClickListener(this); //player1.set } @Override public void onClick(View view) { final EditText player1 = findViewById(R.id.player1_text); final EditText player2 = findViewById(R.id.player2_text); String player1_name = ""; String player2_name = ""; switch (view.getId()) { case R.id.complete: player1_name = player1.getText().toString(); player2_name = player2.getText().toString(); //A,I아닌데 이름이 A.I면 거름 if ((!p1Set.equals("AI") && player1_name.equals("A.I")) || (!p2Set.equals("AI") && player2_name.equals("A.I"))) { Toast.makeText(this, "A.I가 아닌 다른 이름을 입력해 주세요.", Toast.LENGTH_SHORT).show(); break; }else { //Toast.makeText(this, "Hi", Toast.LENGTH_SHORT).show(); Intent intent2board = new Intent(this, ChessBoard.class); intent2board.putExtra("P1NAME", player1_name); intent2board.putExtra("P2NAME", player2_name); startActivity(intent2board); finish(); break; } } } @Override public void onBackPressed() { super.onBackPressed(); Intent inentmain = new Intent(this, MainActivity.class); startActivity(inentmain); finish(); } }
Markdown
UTF-8
10,762
3.171875
3
[]
no_license
component : 일반적인 자바스크립트 파일 virtual dom : 내용이 변경되면 돔을 싹 다 바꾸는 것이 아니라 변경된 돔만 바꿈 - 설치 node.js 설치 후 원하는 경로에 가서 npx create-react-app my-app ### jsx 작성 규칙 - 하나의 root element를 가짐 - 모든 element는 closer 필요 - 각 태그는 두번 사용 할 수 없지만 태그 안에 태그를 넣을 순 있다. - App.js ```js import React, {Component} from 'react'; import {Fragment} from 'react'; class App extends Component { render() { return( <Fragment> <div> hello, React with class </div> <div> hello, React with class </div> </Fragment> ); } } export default App; ``` return 안에는 <div></div> 나 <p></p>하나로 전체 내용을 감싸줘야함 (하나의 root element를 가짐) ```js return( <div> hello, React with class </div> <div> hello, React with class </div> ); ``` 이런건 안됨 <div><p> 안쓸거면 <Fragment> 써주면 됨 (import 필요) - App.css ```js .App { text-align: center; } .App-logo { height: 40vmin; pointer-events: none; } @media (prefers-reduced-motion: no-preference) { .App-logo { animation: App-logo-spin infinite 20s linear; } } .App-header { background-color: #282c34; min-height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center; font-size: calc(10px + 2vmin); color: white; } .App-link { color: #61dafb; } @keyframes App-logo-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } ``` - 클래스 적용 ```js import React, {Component} from 'react'; import {Fragment} from 'react'; import './App.css'; class App extends Component { render() { return( <div className='App-link'> <div> hello, React with class </div> <div> hello, React with class </div> </div> ); } } export default App; ``` - text ```js import React, {Component} from 'react'; import {Fragment} from 'react'; import './App.css'; class App extends Component { render() { return( <div className='App-header'> <div> hello, React with class </div> <div> hello, React with class </div> <input type="text"/> //셀프 closer 모든 element는 closer 필요 </div> ); } } export default App; ``` - ```js import React, {Component} from 'react'; import {Fragment} from 'react'; import './App.css'; class App extends Component { render() { const name = "uk"; return( <div className='App-header'> <h1> Hello,{name} //각 태그는 두번 사용 할 수 없지만 태그 안에 태그를 넣을 순 있다. </h1> <input type="text"></input> </div> ); } } export default App; ``` - function() ```js import React, {Component} from 'react'; import {Fragment} from 'react'; import './App.css'; class App extends Component { render() { const time = 21; const name = "uk"; return( <div className='App-header'> { (function(){ if(time<12)return (<div>Good morning</div>); if(time<18)return (<div>Good afternoon</div>); if(time<22)return (<div>Good evening</div>); })() } </div> ); } } export default App; ``` ```js import React, {Component} from 'react'; import {Fragment} from 'react'; import './App.css'; class App extends Component { render() { const name = 'React'; const css = { color:'red', background:'black', padding:'20px', fontSize:'25px' }; return( <div className='App-header'> <div style={css}>Hello, {name}</div> </div> ); } } export default App; ``` ### props - 부모 컴포넌트가 자식 컴포넌트에게 전달하는 값 - 자식 컴포넌트에서는 props의 값을 수정할 수 없음 - props 값은 this. 키워드 이용하여 사용 ### state - 컴포넌트 내부에 선언하여 사용되는 보관용 데이터 값 - 동적인 데이터 처리 - MyIntro.js => class 이용 ```js import React, {Component} from 'react'; class MyIntro extends Component{ render(){ return( <div> <div style={this.props.style}> 안녕하세요, 제 이름은 <b>{this.props.card.name}</b> 입니다.<br/> </div> 이메일은 <b>{this.props.card.email}</b> 입니다.<br/> <div style={this.props.style1}>전화번호는 <b>{this.props.card.phone}</b> 입니다.<br/> </div> </div> ); } } export default MyIntro; ``` - MyIntro2.js ```js import React from 'react'; const MyIntro2 = function({card}){ return( < div > 안녕하세요, 제 이름은 <b> {card.name},<br/> 이메일은 {card.email},<br/> 전화번호는 {card.phone}</b> 입니다. </div> ) } export default MyIntro2 ``` - App.js ```js import React, {Component} from 'react'; import './App.css'; import MyIntro from './MyIntro'; class App extends Component{ render(){ const card={ name : 'UK', email:'[email protected]', phone: '010-5093-6442' } const css={ color:'red', background:'white' } const css1={ color:'blue', background:'white' } return( <MyIntro style={css} style1={css1} card={card} /> ); } } export default App; ``` ### React Counter button - Counter.js ```js import React, {Component} from 'react'; class Counter extends Component{ state = { count: 100 } handlePlus = () =>{ this.setState({ count: ++this.state.count }); } handleMinus = () =>{ this.setState({ count: --this.state.count }); } render(){ return( <div> <h1>Counter</h1> <h2>{this.state.count}</h2> <button onClick={this.handlePlus}>+</button> <button onClick={this.handleMinus}>-</button> </div> ); } } export default Counter; ``` - App.js ```js import React, {Component} from 'react'; import './App.css'; import Counter from './Counter'; class App extends Component{ render(){ return( <Counter/> ); } } export default App; ``` - 전개연산자 => ... ```js import React, {Component} from 'react'; class Counter extends Component{ state = { count: 100, info:{ name: 'React', age : 27 } } handlePlus = () =>{ this.setState({ count: ++this.state.count }); } handleMinus = () =>{ this.setState({ count: --this.state.count }); } handleChangeInfo = () =>{ //this.state.info의 name을 변경 this.setState({ info:{ ...this.state.info, //전개연산자를 안쓰면 info의 age값은 사라짐 나머지 속성을 유지하고 싶으면 전개연산자 쓰자 name:'Uk' } }); } render(){ return( <div> <h1>Counter</h1> <h2>{this.state.count}</h2> <button onClick={this.handlePlus}>+</button> <button onClick={this.handleMinus}>-</button> <button onClick={this.handleChangeInfo}>Change info name</button> {this.state.info.name}/{this.state.info.age} </div> ); } } export default Counter; ``` - 전개연산자 ```js const array = [1,2,3,4,5]; const newArray = [6,7,8,9,10]; newArray.push(array); newArray (6) [6, 7, 8, 9, 10, Array(5)] // 전개 연산자를 사용했을 경우 const newArray2 = [6,7,8,9,10]; newArray2.push(...array); 10 newArray2 (10) [6, 7, 8, 9, 10, 1, 2, 3, 4, 5] ``` ### 생명주기 메소드 - Counter.js ```js import React, {Component} from 'react'; const ErrorObject = () =>{ throw (new Error('에러 발생')); } class Counter extends Component{ state = { count: 0, error: false } // constructor(props){ // super(props); // this.state.count = this.props.init; // // console.log('call constructor'); // } componentDidCatch(error, info){ this.setState({ error: true }); } componentDidMount(){ console.log('componentDidMount'); } shouldComponentUpdate(nextProps, nextState){ console.log('shouldComponentUpdate'); if(nextState.number % 5 === 0) return false; return true; } componentWillUpdate(nextProps, nextState){ console.log("componentWillUpdate"); } componentDidUpdate(prevProps, prevState){ console.log('componentDidUpdate'); } handlePlus = () =>{ this.setState({ count: ++this.state.count }); } handleMinus = () =>{ this.setState({ count: --this.state.count }); } handleChangeInfo = () =>{ //this.state.info의 name을 변경 this.setState({ info:{ ...this.state.info, //전개연산자를 안쓰면 info의 age값은 사라짐 나머지 속성을 유지하고 싶으면 전개연산자 쓰자 name:'Uk' } }); } render(){ if(this.state.error) return (<h1>에러가 발생되었습니다.</h1>) ; return( <div> <h1>Counter</h1> <h2>{this.state.count}</h2> {this.state.count == 3 && <ErrorObject/>} <button onClick={this.handlePlus}>+</button> <button onClick={this.handleMinus}>-</button> <button onClick={this.handleChangeInfo}>Change info name</button> </div> ); } } export default Counter; ``` - App.js ```js import React, {Component} from 'react'; import './App.css'; import Counter from './Counter'; class App extends Component{ render(){ return( <Counter init="10"/> //초기값을 Counter component에 전달 ); } } export default App; ```
Java
UTF-8
432
2.71875
3
[]
no_license
import java.util.ArrayList; public class Test { public static void main(String[] args) { Sculpture sul = new Sculpture(); Circular c = new Circular(1,1 ); Square s = new Square(0, 1); ArrayList<Shape> sss = new ArrayList<>(); sss.add(c); sss.add(s); sul.store(sss); System.out.println(sul.hasBalance()); // second commit // third commit } }
Go
UTF-8
1,574
2.875
3
[ "Apache-2.0" ]
permissive
package harness import ( "fmt" "reflect" "github.com/kylelemons/godebug/pretty" promdata "github.com/prometheus/client_model/go" ) // FindPromMetric is a helper to take the metrics scraped from oplogtoredis, and get a particular // metric partition func FindPromMetric(metrics map[string]*promdata.MetricFamily, name string, labels map[string]string) *promdata.Metric { metric, ok := metrics[name] if !ok { panic("No such metric: " + name) } for _, metricPartition := range metric.Metric { partitionLabels := map[string]string{} for _, label := range metricPartition.Label { partitionLabels[*label.Name] = *label.Value } if reflect.DeepEqual(labels, partitionLabels) { return metricPartition } } panic(fmt.Sprintf("Could not find desired metric. Desired labels: %#v. All partitions:\n%s", labels, pretty.Sprint(metric))) } // FindPromMetricCounter is like FindPromMetric, but then extracts an integer ounter value func FindPromMetricCounter(metrics map[string]*promdata.MetricFamily, name string, labels map[string]string) int { val := FindPromMetric(metrics, name, labels).Counter.Value return int(*val) } // PromMetricOplogEntriesProcessed finds specifically the value of the otr_oplog_entries_received // metric, and returns the value of the {database: "testdb", status: "processed"} // partition func PromMetricOplogEntriesProcessed(metrics map[string]*promdata.MetricFamily) int { return FindPromMetricCounter(metrics, "otr_oplog_entries_received", map[string]string{ "database": "testdb", "status": "processed", }) }
Python
UTF-8
6,909
2.5625
3
[ "MIT" ]
permissive
from __future__ import division import abc import sys import matplotlib.pyplot as plt import scipy.optimize as opt from matplotlib import patches import numpy as np import numpy.random as rand import numpy.linalg as linalg def pretty_fig(n): plt.figure(n, figsize=(8, 8)) plt.rc('text', usetex=True) plt.rc('font',size=19) plt.rc('xtick.major',pad=5); plt.rc('xtick.minor',pad=5) plt.rc('ytick.major',pad=5); plt.rc('ytick.minor',pad=5) def to_radial(xs, ys): rs = np.sqrt(xs**2 + ys**2) thetas = np.arctan2(ys, xs) return rs, thetas def to_cartesian(rs, thetas): ys, xs = np.sin(thetas) * rs, np.cos(thetas) * rs return xs, ys def read_row(row): ts = [t for t in row.split(" ") if t != ""] return [float(ts[0]), float(ts[1]), float(ts[2]), float(ts[3])] def read_pts(file_name): with open(file_name) as fp: s = fp.read() lines = s.split("\n") caustic_rows = map(read_row, lines) xs, ys, zs, rs = map(np.array, zip(*caustic_rows)) return xs*rs, ys*rs, zs*rs def read_plane(file_name): with open(file_name) as fp: s = fp.read() lines = s.split("\n") caustic_rows = map(read_row, lines) xs, ys, zs, rs = map(np.array, zip(*caustic_rows)) if np.all(xs == 0): return ys*rs, zs*rs, 0 elif np.all(ys == 0): return xs*rs, zs*rs, 1 else: return xs*rs, ys*rs, 2 def plot_func(f, axis, c="k", pts=200, lw=3): theta0s = np.linspace(0, np.pi * 2, pts) x0s, x1s = np.cos(theta0s), np.sin(theta0s) if axis == 0: xs, ys, zs = np.zeros(pts), x0s, x1s elif axis == 1: xs, ys, zs = x0s, np.zeros(pts), x1s else: xs, ys, zs = x0s, x1s, np.zeros(pts) phis = np.arctan2(ys, xs) thetas = np.arccos(zs, np.ones(pts)) rs = f(phis, thetas) plt.plot(x0s*rs, x1s*rs, lw=lw, c=c) def penna_coeff(n, xs, ys, zs): phis = np.arctan2(ys, xs) rs = np.sqrt(xs**2 + ys**2 + zs**2) thetas = np.arccos(zs / rs) trig_coeffs = [] for k in xrange(2): cos_k = np.cos(thetas)**k for j in xrange(0, n+1): sin_j = np.sin(phis)**j for i in xrange(0, n+1): cos_i = np.cos(phis)**i sin_ij = np.sin(thetas)**(i+j) trig_coeffs.append(sin_ij * cos_k * sin_j * cos_i) trig_coeffs = np.array(trig_coeffs) def fit_func(p, phis, thetas): sum = np.zeros(len(phis)) for idx, coeffs in enumerate(trig_coeffs): sum += p[idx] * coeffs return sum def err_func(p, phis, thetas, rs): return rs - fit_func(p, phis, thetas) p_init = np.ones((n+1)*(n+1)*2) coeffs, _ = opt.leastsq(err_func, p_init, args=(phis, thetas, rs)) return coeffs def fast_penna_coeffs(n, xs, ys, zs): N = 2*n + 1 rs = np.sqrt(xs**2 + ys**2 + zs**2) rNs = rs**(N+1) M = [] for k in xrange(2): zks = zs**k for j in xrange(n+1): yjs = ys**j for i in xrange(n+1): xis = xs**i M.append(rs**(N-i-j-k)*xis*yjs*zks) M = np.matrix(M) return np.array(rNs * linalg.pinv(M))[0] def penna_func(c_ijks, N): def func(phis, thetas): trig_coeffs = [] idx = 0 for k in xrange(2): cos_k = np.cos(thetas)**k for j in xrange(0, N+1): sin_j = np.sin(phis)**j for i in xrange(0, N+1): cos_i = np.cos(phis)**i sin_ij = np.sin(thetas)**(i+j) trig_coeffs.append(sin_ij * cos_k * sin_j * cos_i) trig_coeffs = np.array(trig_coeffs) sum = np.zeros(len(phis)) for idx, coeffs in enumerate(trig_coeffs): sum += c_ijks[idx] * coeffs return sum return func def find_max_r(rs): vals, edges = np.histogram(rs, bins=2*(len(rs))**0.33) bin_rs = (edges[1:] + edges[:-1]) / 2 max = bin_rs[np.argmax(vals)] dr = edges[1] - edges[0] for (i, r) in enumerate(bin_rs): if r > max * 1.3: low_edges, high_edges = edges[:i], edges[i:-1] low_vals, high_vals = vals[:i], vals[i:] break pretty_fig(7) plt.bar(low_edges, low_vals, width=dr, color="r") plt.bar(high_edges, high_vals, width=dr, color="w") plt.xlabel("$r$ [Mpc/$h$]") plt.ylabel("Counts") return bin_rs[np.argmax(vals)] def filter_around_max(xs, ys, zs, eta=0.3): rs = np.sqrt(xs**2 + ys**2 + zs**2) max_r = find_max_r(rs) valid = (rs < max_r*(1+eta)) & (rs > max_r*(1-eta)) return max_r, xs[valid], ys[valid], zs[valid] def filter_around(vals, filter_vals, target, eta=0.3): valid = (filter_vals < target*(1+eta)) & (filter_vals > target*(1-eta)) return vals[valid] def chi2(func, phis, thetas, rs, n): deltas = func(phis, thetas) - rs return np.sum(deltas**2) / (len(rs) - n - 1) / np.mean(rs)**2 def multi_fit(xs, ys, zs, r_lims, n): rs = np.sqrt(xs**2 + ys**2 + zs**2) for lim in r_lims: lim_xs, lim_ys, lim_zs = xs[rs < lim], ys[rs < lim], zs[rs < lim] lim_rs = rs[rs < lim] print "R limit = %g (%d points)" % (lim, len(lim_xs)) if (n+1)*(n+1)*2 >= len(lim_xs): continue print len(lim_xs) c_ijks = penna_coeff(n, lim_xs, lim_ys, lim_zs) phis = np.arctan2(lim_ys, lim_xs) thetas = np.arccos(lim_zs / lim_rs) print "Chi^2 = %g" % chi2(penna_func(c_ijks, n), phis, thetas, lim_rs, n) if __name__ == "__main__": rs_file_name = sys.argv[1] plane_file_name = sys.argv[2] eta = 0.3 raw_xs, raw_ys, raw_zs = read_pts(rs_file_name) max_r, xs, ys, zs = filter_around_max(raw_xs, raw_ys, raw_zs, eta=eta) raw_p_x0s, raw_p_x1s, axis = read_plane(plane_file_name) p_rs = np.sqrt(raw_p_x0s**2 + raw_p_x1s**2) p_x0s = filter_around(raw_p_x0s, p_rs, max_r, eta=eta) p_x1s = filter_around(raw_p_x1s, p_rs, max_r, eta=eta) pretty_fig(0) if axis == 0: plt.title("X Slice") plt.ylabel("Z [Mpc/$h$]") plt.xlabel("Y [Mpc/$h$]") elif axis == 1: plt.title("Y Slice") plt.ylabel("Z [Mpc/$h$]") plt.xlabel("X [Mpc/$h$]") else: plt.title("Z Slice") plt.ylabel("Y [Mpc/$h$]") plt.xlabel("X [Mpc/$h$]") plot_func(lambda a, b: max_r*(1+eta), axis, c="r", lw=1) plot_func(lambda a, b: max_r*(1-eta), axis, c="r", lw=1) plt.plot(raw_p_x0s, raw_p_x1s, "wo") plt.plot(p_x0s, p_x1s, "ro") furthest_r = np.max(np.sqrt(xs**2 + ys**2 + zs**2)) multi_fit(xs, ys, zs, np.linspace(0, furthest_r, 20), 4) N = 4 c_ijks = penna_coeff(N, xs, ys, zs) plot_func(penna_func(c_ijks, N), axis) ylo, yhi = plt.ylim() xlo, xhi = plt.xlim() dist = max(max(yhi, xhi), -min(ylo, xlo)) plt.xlim((-dist, dist)) plt.ylim((dist, -dist)) plt.show()
PHP
UTF-8
1,054
2.53125
3
[ "BSD-3-Clause" ]
permissive
<?php use yii\db\Migration; /** * Handles the creation of table `units`. */ class m171009_032042_create_subdivision_table extends Migration { /** * @inheritdoc */ public function up() { $this->createTable('subdivision', [ 'id' => $this->primaryKey(), 'name' => $this->char(64)->notNull()->comment('наименование подразделения'), 'branch_id' => $this->integer()->comment('идентификатор филиала'), 'employee_id' => $this->integer()->comment('начальник подразделения'), 'subdivision_id' => $this->integer()->comment('главное подразделение'), 'description' => $this->text()->comment('описание подразделения') ]); $this->addCommentOnTable('subdivision', 'Подразделения в филиалах'); } /** * @inheritdoc */ public function down() { $this->dropTable('subdivision'); } }
Markdown
UTF-8
1,337
2.75
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: pointer_default attribute description: The \ pointer\_default\ attribute specifies the default pointer attribute for all pointers except top-level pointers that appear in parameter lists. ms.assetid: a6e83034-8adb-483d-8d1e-432a1aed22c6 keywords: - pointer_default attribute MIDL topic_type: - apiref api_name: - pointer_default api_type: - NA ms.topic: reference ms.date: 05/31/2018 --- # pointer\_default attribute The **\[pointer\_default\]** attribute specifies the default pointer attribute for all pointers except top-level pointers that appear in parameter lists. ``` syntax pointer_default ( ptr | ref | unique ) ``` ## Parameters This attribute has no parameters. ## Examples ``` syntax [ uuid(6B29FC40-CA47-1067-B31D-00DD010662DA), version(3.3), pointer_default(unique) ] interface dictionary { // Interface definition statements. } ``` ## See also <dl> <dt> [**interface**](interface.md) </dt> <dt> [Array and Sized-Pointer Attributes](array-and-sized-pointer-attributes.md) </dt> <dt> [**arrays**](arrays-1.md) </dt> <dt> [Arrays and Pointers](/windows/desktop/Rpc/arrays-and-pointers) </dt> <dt> [**ptr**](ptr.md) </dt> <dt> [**ref**](ref.md) </dt> <dt> [**unique**](unique.md) </dt> <dt> [Default Pointer Types](/windows/desktop/Rpc/default-pointer-types) </dt> </dl>    
Markdown
UTF-8
2,181
2.875
3
[ "Apache-2.0" ]
permissive
### Docker in Higher Education For quite some time now we have been receiving daily requests from students all over the world, asking for our help learning Docker, using Docker and teaching their peers how to use Docker. We love their enthusiasm, so we decided it was time to reach out to the student community and give them the helping hand they need! Understanding how to use Docker is now a must have skill for students. Here are 5 reasons why: - Understanding how to use Docker is one of the most important skills to learn if you want to advance in a career in tech, according to [Business Insider](http://www.businessinsider.com/fastest-growing-tech-skills-for-job-seekers-2017-3/#heres-the-chart-showing-the-overall-trends-from-the-last-year-you-may-notice-one-big-theme-demand-for-cloud-computing-skills-is-growing-mightily-stack-overflows-julia-silge-says-its-a-reflection-of-the-increased-complexity-of-the-modern-it-department-1). - You can just start coding instead of spending time setting up your environment. - You can collaborate easily with your peers and enable seamless group work: Docker eliminates any ‘works on my machine’ issues. - Docker allows you to easily build applications with a modern microservices architecture. - Using Docker will greatly enhance the security of your applications. ## Getting Started with Docker Are you a student who is excited about the prospect of using Docker but still don’t know exactly what Docker is or where to start learning? Now that your finals are over and you have all this free time on your hands, it’s the perfect time for you to get started! Here are a couple of resources to get you up to speed in time for the fall semester: - [Get Started with Docker](https://docs.docker.com/get-started/) (official documentation) - [Introduction to Docker Presentation](https://github.com/mikegcoleman/docker101/blob/master/Docker_101_Workshop_DockerCon.pdf) (slides) - [Docker Beginner labs](http://training.play-with-docker.com/) (Self paced training) <img width="100%" height="100%" src="https://i1.wp.com/blog.docker.com/wp-content/uploads/adc1a6ad-e95f-4fae-ab59-8c7a23244cfc-1.jpg?resize=676%2C531&ssl=1">
Markdown
UTF-8
5,720
3.078125
3
[]
no_license
--- title: "Activity Monitoring" author: "Rolando Mendoza" date: "October 18, 2015" output: html_document --- The purpose of this document is to analyze the data collected from a personal activity monitoring device such as Fitbit, Nike Fuelband, etc. The data came from an anonymous individual and it collected the number of steps taken in 5-minute intervals between the months of October and November 2012. ### Loading and preprocessing the data Load the data (i.e. read.csv()) ```r unzip("repdata-data-activity.zip") actDF <- read.csv(file="activity.csv", header=TRUE) ``` Process/transform the data (if necessary) into a format suitable for your analysis ```r actDF$date <- as.Date(actDF$date, format="%Y-%m-%d") ``` The dplyr package is also loaded which will be used later in the analysis ```r require(dplyr) ``` ### What is mean total number of steps taken per day? #### For this part of the assignment, missing values in the dataset are ignored Calculate the total number of steps taken per day ```r totalSteps <- aggregate(cbind(steps) ~ date, data=actDF, FUN=sum) ``` Make a histogram of the total number of steps taken each day ![plot of chunk unnamed-chunk-5](figure/unnamed-chunk-5-1.png) Calculate and report the mean and median of the total number of steps taken per day. ```r meanTotalSteps <- mean(totalSteps$steps, na.rm=TRUE) medianTotalSteps <- median(totalSteps$steps, na.rm=TRUE) ``` The mean of the total steps per day is **1.0766189 &times; 10<sup>4</sup>** and the median of the total steps per day is **10765**. ### What is the average daily activity pattern? Make a time series plot (i.e. type = "l") of the 5-minute interval (x-axis) and the average number of steps taken, averaged across all days (y-axis) ```r interval <- aggregate(actDF$steps, by=list(interval=actDF$interval), na.rm=TRUE, FUN=mean) ``` ![plot of chunk unnamed-chunk-8](figure/unnamed-chunk-8-1.png) Which 5-minute interval, on average across all the days in the dataset, contains the maximum number of steps? ```r maxInterval <- interval[which.max(interval$x),] ``` ```r maxInterval ``` ``` ## interval x ## 104 835 206.1698 ``` Interval **835** is the interval with the most steps at **206.1698113** steps. ### Imputing missing values #### Note that there are a number of days/intervals where there are missing values (coded as NA). The presence of missing days may introduce bias into some calculations or summaries of the data. Calculate and report the total number of missing values in the dataset (i.e. the total number of rows with NAs) ```r totalNAs <- sum(is.na(actDF$steps)) ``` ```r totalNAs ``` ``` ## [1] 2304 ``` There are **2304** intervals with missing values (NA). Devise a strategy for filling in all of the missing values in the dataset. The strategy does not need to be sophisticated. For example, you could use the mean/median for that day, or the mean for that 5-minute interval, etc. For this project, the mean of each interval will be used to replace the missing values. ```r meanTotalInterval <- tapply(actDF$steps, actDF$interval, mean, na.rm=TRUE) ``` Create a new dataset that is equal to the original dataset but with the missing data filled in. ```r noNADF <- actDF allNAs <- is.na(noNADF$steps) noNADF$steps[allNAs] <- meanTotalInterval[as.character(noNADF$interval[allNAs])] ``` Make a histogram of the total number of steps taken each day and Calculate and report the mean and median total number of steps taken per day. ```r totalStepsNoNA <- aggregate(cbind(steps) ~ date, data=noNADF, FUN=sum) ``` ![plot of chunk unnamed-chunk-16](figure/unnamed-chunk-16-1.png) Do these values differ from the estimates from the first part of the assignment? What is the impact of imputing missing data on the estimates of the total daily number of steps? ```r meanTotalStepsNoNA <- mean(totalStepsNoNA$steps, na.rm=TRUE) medianTotalStepsNoNA <- median(totalStepsNoNA$steps, na.rm=TRUE) meanDiff <- meanTotalStepsNoNA - meanTotalSteps medianDiff <- medianTotalStepsNoNA - medianTotalSteps ``` ```r meanDiff ``` ``` ## [1] 0 ``` ```r medianDiff ``` ``` ## [1] 1.188679 ``` The difference between the mean of the dataset with missing values and the dataset that was "data fixed" is **0**. The difference between the mean of the dataset with missing values and the dataset that was "data fixed" is **1.1886792**. ### Are there differences in activity patterns between weekdays and weekends? #### For this part the weekdays() function may be of some help here. Use the dataset with the filled-in missing values for this part. Create a new factor variable in the dataset with two levels - "weekday" and "weekend" indicating whether a given date is a weekday or weekend day. ```r noNADF <- mutate(noNADF, week=weekdays(date)) noNADF <- noNADF %>% mutate(typeOfWeek = ifelse(week=="Saturday" | week=="Sunday","weekend", "weekday")) ``` Make a panel plot containing a time series plot (i.e. type = "l") of the 5-minute interval (x-axis) and the average number of steps taken, averaged across all weekday days or weekend days (y-axis). See the README file in the GitHub repository to see an example of what this plot should look like using simulated data. ```r noNADFWeekend <- subset(noNADF, typeOfWeek == "weekend") noNADFWeekday <- subset(noNADF, typeOfWeek == "weekday") intervalWeekend <- aggregate(noNADFWeekend$steps, by=list(interval=noNADFWeekend$interval), na.rm=TRUE, FUN=mean) intervalWeekday <- aggregate(noNADFWeekday$steps, by=list(interval=noNADFWeekday$interval), na.rm=TRUE, FUN=mean) ``` ![plot of chunk unnamed-chunk-22](figure/unnamed-chunk-22-1.png) ![plot of chunk unnamed-chunk-22](figure/unnamed-chunk-22-2.png)
Java
UTF-8
282
2.921875
3
[]
no_license
package geometry; public class Vector{ public final double dx,dy; public Vector(double dx, double dy){ this.dx = dx; this.dy = dy; } public static Vector composing(Vector v1, Vector v2){ return new Vector(v1.dx+v2.dx, v1.dy+v2.dy); } }
Markdown
UTF-8
5,928
2.640625
3
[]
no_license
# SpringSecurity注销登录 当启用WebSecurityConfigurerAdapter的时候,logout支持会自动启用 logoutUrl() 访问那个地址会触发登出逻辑。**默认情况下CROS是开启的,另外必须是POST方法** logoutSuccessUrl() 当登出成功之后,会被重定向到的地址 logoutSuccessHandler()指定登出成功后的处理,如果指定了这个,那么`logoutSuccessUrl`就不会生效。 addLogoutHandler 添加登出时的Handler,在访问logout地址时会执行,内部是一个立碑,`SecurityContextLogoutHandler`默认会加到最后, invalidateHttpSession 在登出后,是否要清空当前session #### LogoutHandler LogoutHandler 即在程序执行logout时一起参与执行其中的处理逻辑,**不能抛出异常**,官方默认提供了几个实现。 - [PersistentTokenBasedRememberMeServices](https://links.jianshu.com/go?to=https%3A%2F%2Fdocs.spring.io%2Fspring-security%2Fsite%2Fdocs%2Fcurrent%2Fapi%2Forg%2Fspringframework%2Fsecurity%2Fweb%2Fauthentication%2Frememberme%2FPersistentTokenBasedRememberMeServices.html) - [TokenBasedRememberMeServices](https://links.jianshu.com/go?to=https%3A%2F%2Fdocs.spring.io%2Fspring-security%2Fsite%2Fdocs%2Fcurrent%2Fapi%2Forg%2Fspringframework%2Fsecurity%2Fweb%2Fauthentication%2Frememberme%2FTokenBasedRememberMeServices.html) 移除Token - [CookieClearingLogoutHandler ](https://links.jianshu.com/go?to=https%3A%2F%2Fdocs.spring.io%2Fspring-security%2Fsite%2Fdocs%2Fcurrent%2Fapi%2Forg%2Fspringframework%2Fsecurity%2Fweb%2Fauthentication%2Flogout%2FCookieClearingLogoutHandler.html) 清楚Cookie - [CsrfLogoutHandler](https://links.jianshu.com/go?to=https%3A%2F%2Fdocs.spring.io%2Fspring-security%2Fsite%2Fdocs%2Fcurrent%2Fapi%2Forg%2Fspringframework%2Fsecurity%2Fweb%2Fcsrf%2FCsrfLogoutHandler.html) 移除CSRF TOKEN - [SecurityContextLogoutHandler](https://links.jianshu.com/go?to=https%3A%2F%2Fdocs.spring.io%2Fspring-security%2Fsite%2Fdocs%2Fcurrent%2Fapi%2Forg%2Fspringframework%2Fsecurity%2Fweb%2Fauthentication%2Flogout%2FSecurityContextLogoutHandler.html) - [HeaderWriterLogoutHandler](https://links.jianshu.com/go?to=https%3A%2F%2Fdocs.spring.io%2Fspring-security%2Fsite%2Fdocs%2Fcurrent%2Fapi%2Forg%2Fspringframework%2Fsecurity%2Fweb%2Fauthentication%2Flogout%2FHeaderWriterLogoutHandler.html) #### LogoutSuccessHandler 在调用完LogoutHandler之后,并且处理成功后调用,**可以抛出异常**,官方默认提供了两个 - [SimpleUrlLogoutSuccessHandler](https://links.jianshu.com/go?to=https%3A%2F%2Fdocs.spring.io%2Fspring-security%2Fsite%2Fdocs%2Fcurrent%2Fapi%2Forg%2Fspringframework%2Fsecurity%2Fweb%2Fauthentication%2Flogout%2FSimpleUrlLogoutSuccessHandler.html) 不需要直接指定,在指定logoutSuccessUrl()会自己使用 - HttpStatusReturningLogoutSuccessHandler 返回登出成功后的状态码 ```java @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() //开启httpsecurity 配置 允许基于该限制访问HttpServletRequest使用RequestMatcher的实现(即,经由URL模式) //省略其他 //省略其他 //省略其他 //省略其他 //省略其他 .and() // 开启新的配置 .logout() //注销登录配置 .logoutUrl("/logout") //注销url 默认也是logout .clearAuthentication(true) //是否清除认证信息 .invalidateHttpSession(true) //表示是否使session失效 .addLogoutHandler(new LogoutHandler() { //不可以抛出异常,抛出异常后注销失败 @Override public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) { //在logout 中用户可以实现一些自己的数据清除操作 //而且SpringSecurity 中提供了几个默认的实现 // 1. CookieClearingLogoutHandler 清除cookie // 2. CsrfLogoutHandler 移除CSRF TOKEN // 3. CompositeLogoutHandler System.out.println("注销操作"); } }) .logoutSuccessHandler(new LogoutSuccessHandler() { //可以抛出异常 @Override public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException { //这里处理注销成功后的逻辑,可以像登录成功后那样返回一段json ,或者提示跳转到某个页面 httpServletResponse.setContentType("application/json;charset=utf-8"); //设置返回格式 httpServletResponse.setStatus(200); //设置状态 System.out.println("处理注销成功后的逻辑"); Result<Object> result = Result.setResult(ResultCodeEnum.LOGOUT_SUCCESS); ObjectMapper om = new ObjectMapper(); //jackson的json库 PrintWriter writer = httpServletResponse.getWriter(); //获取返回输出流 writer.write(om.writeValueAsString(result)); //输出 writer.flush(); writer.close(); } }) .and() .csrf() //关闭 csrf .disable(); //应用 } ``` 测试 访问 `http://localhost:8080/login` post方式 ,参数 `username=admin&password=root` 登陆成功 访问 `http://localhost:8080/logout` 结果 ```json { "code": 200, "message": "登陆成功", "success": true, "data": {} } ```
Python
UTF-8
762
3.40625
3
[]
no_license
class Tree: def __init__(self): pass def BinaryTree(self,r): return [r,[],[]] def insertLeft(self,root,newBranch): t = root.pop(1) if len(t) > 1: root.insert(1,[newBranch,t,[]]) else: root.insert(1,[newBranch,[],[]]) return root def insertRight(self,root,newBranch): t = root.pop(2) if len(t) > 1: root.insert(2,[newBranch,[],t]) else: root.insert(2,[newBranch,[],[]]) return root def getRootVal(self,root): return root[0] def setRootVal(self,root,newVal): root[0] = newVal def getLeftChild(self,root): return root[1] def getRightChild(self,root): return root[2]
C++
UTF-8
482
3.296875
3
[]
no_license
//tsimple example of how to use std::array<T,N> // // #include<array> #include<iostream> int main() { std::array<int,10> arr, other_arr; arr.fill(5); arr[3]=3; for(auto& el:arr) std::cout << el << ' '; std::cout << '\n'; for(auto& el:other_arr) std::cout << el << ' '; std::cout << '\n'; arr.swap(other_arr); for(auto& el:arr) std::cout << el << ' '; std::cout << '\n'; for(auto& el:other_arr) std::cout << el << ' '; }
Java
UTF-8
13,035
1.96875
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 Interfaz; import base_de_datos.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.ResourceBundle; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.embed.swing.SwingFXUtils; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.image.PixelReader; import javafx.scene.image.WritableImage; import javafx.scene.layout.Pane; import javax.imageio.ImageIO; import modelo.DetectarRostro; import modelo.ReconocimientoRostroPCA; import org.opencv.core.Mat; import org.opencv.videoio.VideoCapture; /** * FXML Controller class * * @author sebas */ public class ControladoresDeInterfaz implements Initializable { // Boton de encendido y apagado @FXML private Button botonOnOff; // panel de la imagen @FXML private ImageView imagenCamara; // un temporizador para adquirir la transmisión de video public ScheduledExecutorService timer; // el objeto OpenCV que realiza la captura de video public VideoCapture captura = new VideoCapture(); // una bandera para cambiar el comportamiento del botón private boolean BanderaCamara = false; // la identificación de la cámara que se utilizará private static int camaraId = 0; private static OpenCV opencv = new OpenCV(); @FXML private Pane paneAdaptable; @FXML private Pane panelFondo; @FXML private ImageView fondo; @FXML private Button botonCapturar; private Image foto =null; @FXML private Button GuardarRostro; @FXML private Button BuscarSimilitudes; @FXML private ImageView imagenBtnGuardarRostro; @FXML private ImageView imgBusqsimilitudes; @FXML private ImageView imgCapturaImagen; @FXML private Pane paneGuardarRostro; @FXML private ImageView fondoGuardarRostro; @FXML private Pane paneBuscarSimilitud; @FXML private ImageView fondoBuscarSimilitud; @FXML private ImageView imgConfirmar; @FXML private Button botonAtrasGR; @FXML private Button botonAtrasBS; @FXML private ImageView imgGurardarGR; @FXML private Button botonConfirmarBS; @FXML private ImageView imgActualGR; @FXML private ImageView imgActualBR; @FXML private Button guardadoTotal; @FXML private TextField nombreDePersona; @FXML private TextField infoDePersona; @FXML private TextField dd; @FXML private TextField mm; @FXML private TextField year; @FXML private ComboBox<String> comboBoxGR; Image nuevaFoto; @FXML private ComboBox<String> comboBoxBR; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { // carga de fondos pantalla principal Image imageFondo = new Image(new File("recursos/background.png").toURI().toString()); fondo.setImage(imageFondo); fondo.fitWidthProperty().bind(panelFondo.widthProperty()); fondo.fitHeightProperty().bind(panelFondo.heightProperty()); // carga de fondo pantalla Guardar rostro fondoGuardarRostro.setImage(imageFondo); fondoGuardarRostro.fitWidthProperty().bind(paneGuardarRostro.widthProperty()); fondoGuardarRostro.fitHeightProperty().bind(paneGuardarRostro.heightProperty()); // carga de fondo pantalla buscar similitud fondoBuscarSimilitud.setImage(imageFondo); fondoBuscarSimilitud.fitWidthProperty().bind(paneBuscarSimilitud.widthProperty()); fondoBuscarSimilitud.fitHeightProperty().bind(paneBuscarSimilitud.heightProperty()); // carga de imagen botones estandar Image imageBotonEstandar = new Image(new File("recursos/boton_estandar.png").toURI().toString()); imagenBtnGuardarRostro.setImage(imageBotonEstandar); imgBusqsimilitudes.setImage(imageBotonEstandar); imgConfirmar.setImage(imageBotonEstandar); imgGurardarGR.setImage(imageBotonEstandar); // pantalla(camara) adaptable imagenCamara.fitWidthProperty().bind(paneAdaptable.widthProperty()); imagenCamara.fitHeightProperty().bind(paneAdaptable.heightProperty()); // carga de la foto de captura de imegen Image imageBotonCaptura = new Image(new File("recursos/boton_foto.png").toURI().toString()); imgCapturaImagen.setImage(imageBotonCaptura); ObservableList<String> items = FXCollections.observableArrayList(); items.addAll("PCA"); comboBoxGR.setItems(items); comboBoxGR.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { if(newValue.equals("PCA")){ ReconocimientoRostroPCA reconocimiento = new ReconocimientoRostroPCA(); Mat imageShow = reconocimiento.run("imagenes/imagenMuestra2.png"); Image imageToShow = opencv.matImagen(imageShow); imgActualGR.setImage(imageToShow); } } }); comboBoxBR.setItems(items); comboBoxBR.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { if(newValue.equals("PCA")){ ReconocimientoRostroPCA reconocimiento = new ReconocimientoRostroPCA(); Mat imageShow = reconocimiento.run("imagenes/imagenMuestra2.png"); Image imageToShow = opencv.matImagen(imageShow); imgActualBR.setImage(imageToShow); } } }); } @FXML private void encenderCamara(ActionEvent event) { if (!BanderaCamara) { // iniciar la captura de video captura.open(camaraId); DetectarRostro dr = new DetectarRostro(); if (captura.isOpened()) { BanderaCamara = true; // tomar un fotograma cada 33 ms (30 fotogramas / seg) Runnable frameGrabber = new Runnable() { @Override public void run() { // procesa eficazmente un solo fotograma Mat frame = opencv.inicioImagen(captura); //marca rostro frame = dr.detecta(frame); // convertir y mostrar el marco Image imageToShow = opencv.matImagen(frame); botonCapturar.setOnAction((event) -> { foto = imageToShow; try { BufferedImage bufferedImage = SwingFXUtils.fromFXImage(foto, null); //Archivos de salida File outputfile2 = new File("imagenes/imagenMuestra.png"); outputfile2.deleteOnExit(); //Se crea el archivo que ve el usuario ImageIO.write(bufferedImage, "png", outputfile2); PixelReader fotoAnterior = foto.getPixelReader(); nuevaFoto = new WritableImage(fotoAnterior,DetectarRostro.datos.get(0),DetectarRostro.datos.get(1),DetectarRostro.datos.get(2), DetectarRostro.datos.get(3)); BufferedImage bufferedImage2 = SwingFXUtils.fromFXImage(nuevaFoto, null); //Archivos de salida File outputfile3 = new File("imagenes/imagenMuestra2.png"); outputfile3.deleteOnExit(); ImageIO.write(bufferedImage2, "png", outputfile3); imgActualBR.setImage(nuevaFoto); imgActualGR.setImage(nuevaFoto); System.out.println("foto tomada"); } catch (IOException ex) { ex.printStackTrace(); } }); opencv.actualizacionImagen(imagenCamara, imageToShow); } }; timer = Executors.newSingleThreadScheduledExecutor(); timer.scheduleAtFixedRate(frameGrabber, 0, 33, TimeUnit.MILLISECONDS); botonOnOff.setText("ON"); } else { System.err.println("Imposible encender la conexión de la cámara"); } } else { // la cámara no está activa en este momento BanderaCamara = false; // actualizar de nuevo el contenido del botón botonOnOff.setText("OFF"); // detener el temporizador opencv.detenerImagen(timer, captura); } } @FXML private void ventanaGuardarRostro(ActionEvent event) { ReconocimientoRostroPCA rp = new ReconocimientoRostroPCA(); //rp.run("imagenes/imagenMuestra.png"); paneBuscarSimilitud.setVisible(false); paneGuardarRostro.setVisible(true); } @FXML private void ventanaBuscarSimilitudes(ActionEvent event) { paneGuardarRostro.setVisible(false); paneBuscarSimilitud.setVisible(true); } @FXML private void ventanaPrimaria1(ActionEvent event) { paneGuardarRostro.setVisible(false); paneBuscarSimilitud.setVisible(false); } @FXML private void ventanaprimaria(ActionEvent event) { paneGuardarRostro.setVisible(false); paneBuscarSimilitud.setVisible(false); } public ArrayList<Usuario> datos = new ArrayList(); int i=0; @FXML private void guardadoDePersona(ActionEvent event) { try { File img = new File("imagenes/imagenMuestra.png"); Image foto2 = nuevaFoto; if(!nombreDePersona.getText().isEmpty() && !infoDePersona.getText().isEmpty() && !dd.getText().isEmpty() && !mm.getText().isEmpty() && !year.getText().isEmpty()){ Usuario nuevoUsuario = new Usuario(nombreDePersona.getText(),infoDePersona.getText(),dd.getText()+"/"+mm.getText()+"/"+year.getText()); datos.add(nuevoUsuario); try { BufferedImage bufferedImage = SwingFXUtils.fromFXImage(foto2, null); //Archivos de salida String nombreGuardado = nombreDePersona.getText()+i; File outputfile2 = new File("carpeta_Fotos/"+nombreGuardado+".png"); outputfile2.deleteOnExit(); i++; //Se crea el archivo que ve el usuario ImageIO.write(bufferedImage, "png", outputfile2); System.out.println("Usuario guardado"); paneGuardarRostro.setVisible(false); paneBuscarSimilitud.setVisible(false); } catch (IOException ex) { ex.printStackTrace(); } } } catch (Exception e) { } } }
C#
UTF-8
1,457
2.65625
3
[ "MIT" ]
permissive
using System; using Microsoft.Extensions.CommandLineUtils; using Microsoft.Extensions.Logging; namespace Company.ConsoleApplication1 { public class Application { private readonly IRootCommand[] _rootCommands; private readonly ILogger _logger; public Application(IRootCommand[] rootCommands, ILogger<Application> logger) { _rootCommands = rootCommands; _logger = logger; } public int Run(string[] args) { try { var app = new CommandLineApplication { Name = "Company.ConsoleApplication1", FullName = "APPLICATION-FULL-NAME", Description = "APPLICATION-DESCRIPTION", }; app.HelpOption("-?|-h|--help"); RegisterCommands(app); return app.Execute(args); } catch (Exception e) { _logger.LogError(new EventId(), e, "Unexpected exception"); return 1; } } private void RegisterCommands(CommandLineApplication app) { foreach (var command in _rootCommands) { app.Command(command.Name, command.Configure()); } app.OnExecute(() => { app.ShowHelp(); return 0; }); } } }
C++
UTF-8
298
2.859375
3
[]
no_license
// // Created by sumesh on 1/8/2016. // #include <iostream> using namespace std; struct s{ int a; char c; int b; }; int main(){ cout<< sizeof(s)<<endl; static_assert(sizeof(s) == sizeof(int)+ sizeof(char) + sizeof(int), "unexpected paddding in struct s"); }
Python
UTF-8
1,697
2.546875
3
[]
no_license
import numpy as np import torch import torch.nn.functional as F from torch.autograd import Variable # from geotnf.point_tnf import normalize_axis, unnormalize_axis def read_flo_file(filename, verbose=False): """ Read from .flo optical flow file (Middlebury format) :param flow_file: name of the flow file :return: optical flow data in matrix adapted from https://github.com/liruoteng/OpticalFlowToolkit/ """ f = open(filename, 'rb') magic = np.fromfile(f, np.float32, count=1) data2d = None if 202021.25 != magic: raise TypeError('Magic number incorrect. Invalid .flo file') else: w = np.fromfile(f, np.int32, count=1) h = np.fromfile(f, np.int32, count=1) if verbose: print("Reading %d x %d flow file in .flo format" % (h, w)) data2d = np.fromfile(f, np.float32, count=int(2 * w * h)) # reshape data into 3D array (columns, rows, channels) data2d = np.resize(data2d, (h[0], w[0], 2)) f.close() return data2d def write_flo_file(flow, filename): """ Write optical flow in Middlebury .flo format :param flow: optical flow map :param filename: optical flow file path to be saved :return: None from https://github.com/liruoteng/OpticalFlowToolkit/ """ # forcing conversion to float32 precision flow = flow.astype(np.float32) f = open(filename, 'wb') magic = np.array([202021.25], dtype=np.float32) (height, width) = flow.shape[0:2] w = np.array([width], dtype=np.int32) h = np.array([height], dtype=np.int32) magic.tofile(f) w.tofile(f) h.tofile(f) flow.tofile(f) f.close()
Java
UTF-8
4,427
2.078125
2
[]
no_license
package com.example.testmoodle.util; import java.util.ArrayList; import org.json.JSONException; import org.json.JSONObject; import android.os.Parcel; import android.os.Parcelable; import android.util.Log; public class Course implements Parcelable { private int id; private String shortName; private String fulltName; private int enrolledUserCount; private String idNumber; private int visible; private ArrayList<CourseContent> courseContents = new ArrayList<CourseContent>(); private ArrayList<Module> assignment = new ArrayList<Module>(); private ArrayList<Document> document = new ArrayList<Document>(); private ArrayList<Module> forum = new ArrayList<Module>(); public ArrayList<Module> getForum() { return forum; } public void setForum(ArrayList<Module> forum) { this.forum = forum; } public ArrayList<Document> getDocument() { return document; } public void setDocument(ArrayList<Document> document) { this.document = document; } public ArrayList<Module> getAssignment() { return assignment; } public void setAssignment(ArrayList<Module> assignment) { this.assignment = assignment; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getShortName() { return shortName; } public void setShortName(String shortName) { this.shortName = shortName; } public String getFulltName() { return fulltName; } public void setFulltName(String fulltName) { this.fulltName = fulltName; } public int getEnrolledUserCount() { return enrolledUserCount; } public void setEnrolledUserCount(int enrolledUserCount) { this.enrolledUserCount = enrolledUserCount; } public String getIdNumber() { return idNumber; } public void setIdNumber(String idNumber) { this.idNumber = idNumber; } public int getVisible() { return visible; } public void setVisible(int visible) { this.visible = visible; } public ArrayList<CourseContent> getCourseContents() { return courseContents; } public void setCourseContents(ArrayList<CourseContent> courseContents) { this.courseContents = courseContents; } public void populateCourse(JSONObject jsonObject) { try { if (jsonObject != null) { String id = jsonObject.getString("id"); this.setId(Integer.valueOf(id)); Log.d("LoggigTracker", id); String shortname = jsonObject.optString("shortname"); if (shortname != null && shortname.trim().length() > 0) this.setShortName(shortname); String fullname = jsonObject.optString("fullname"); if (fullname != null && fullname.trim().length() > 0) this.setFulltName(fullname); String enrolledusercount = jsonObject .optString("enrolledusercount"); if (enrolledusercount != null && enrolledusercount.trim().length() > 0) this.setEnrolledUserCount(Integer .valueOf(enrolledusercount)); String idnumber = jsonObject.optString("idnumber"); if (idnumber != null && idnumber.trim().length() > 0) this.setIdNumber(idnumber); String visible = jsonObject.optString("visible"); if (visible != null && visible.trim().length() > 0) this.setVisible(Integer.valueOf(visible)); Log.d("LoggingTracker", shortname); Log.d("LoggingTracker", fullname); } } catch (JSONException e) { e.printStackTrace(); } } public int describeContents() { return 0; } // this is used to regenerate your object. All Parcelables must have a // CREATOR that implements these two methods public static final Parcelable.Creator<Course> CREATOR = new Parcelable.Creator<Course>() { public Course createFromParcel(Parcel in) { return new Course(in); } public Course[] newArray(int size) { return new Course[size]; } }; // write your object's data to the passed-in Parcel public void writeToParcel(Parcel dest, int flags) { dest.writeInt(id); dest.writeString(shortName); dest.writeString(fulltName); dest.writeInt(enrolledUserCount); dest.writeString(idNumber); dest.writeInt(visible); dest.writeTypedList(courseContents); } private Course(Parcel in) { this.id = in.readInt(); this.shortName = in.readString(); this.fulltName = in.readString(); this.enrolledUserCount = in.readInt(); this.idNumber = in.readString(); this.visible = in.readInt(); in.readTypedList(this.courseContents, CourseContent.CREATOR); } public Course() { // TODO Auto-generated constructor stub } }
Markdown
UTF-8
5,727
2.921875
3
[]
no_license
### Set up: 1. Insert some mock data into database. 2. Log in as 'user3' with password '123'. 3. Click 'Resource Status' on the Main Menu. ### Test for Resource in use: * Run the following query against the database and confirm the output match the displayed information in the form. The `deploy_schedule_id` will be used in the next step. ``` SELECT Resource.id resource_id, Resource.name resource_name, Incident.description, All_user.name owner_name, Deploy_Schedule.start_date, Deploy_Schedule.end_date, Deploy_Schedule.id deploy_schedule_id, Incident.id incident_id FROM Resource INNER JOIN Request ON Resource.id = Request.requesting_resource_id INNER JOIN Incident ON Request.incident_id = Incident.id INNER JOIN Deploy_Schedule ON (Resource.id = Deploy_Schedule.resource_id AND Incident.id = Deploy_Schedule.responding_incident_id) INNER JOIN ( SELECT username, name FROM Municipality UNION SELECT username, name FROM Government_Agency UNION SELECT username, name FROM Company UNION SELECT username, concat(firstname, ' ', lastname) as name FROM Individual ) AS All_user ON Resource.owner_username = All_user.username WHERE Deploy_Schedule.start_date <= sysdate() AND Deploy_Schedule.end_date > sysdate() AND Incident.reporter_username = 'user3'; ``` * Click 'Return' for a resource in the form. Confirm that the record disappears. Run query against the Deploy_Schedule table to check the return date has been updated to current sysdate. ``` select * from Deploy_Schedule where id = $deploy_schedule_id ``` ### Test for Resource Requested by me: * Run the following query against the database and confirm the output match the displayed information in the form: ``` SELECT Resource.id resource_id, Resource.name resource_name, Incident.description, All_user.name owner_name, Request.expected_return_date, Request.id request_id FROM Request INNER JOIN Resource ON Request.requesting_resource_id = Resource.id INNER JOIN Incident ON Request.incident_id = Incident.id INNER JOIN ( SELECT username, name FROM Municipality UNION SELECT username, name FROM Government_Agency UNION SELECT username, name FROM Company UNION SELECT username, concat(firstname, ' ', lastname) as name FROM Individual ) AS All_user ON Resource.owner_username = All_user.username WHERE Request.sender_username = 'user3' and Request.status = 'Pending'; ``` * Pick a request, run the following query to confirm the record exists in the Request table. Then click 'Cancel' for that request. Confirm that the record disappears from the form. Run the query again to confirm the request has been deleted. The query should now return null. ``` select * from Request where id = $request_id ``` ### Test for Resource Requests received by me: * Run the following query against the database and confirm the output match the displayed information in the form: ``` SELECT Resource.id resource_id, Resource.name resource_name, Incident.description, All_user.name requester_name, Request.expected_return_date, Request.id request_id, Incident.id incident_id FROM Request INNER JOIN Resource ON Request.requesting_resource_id = Resource.id INNER JOIN Incident ON Request.incident_id = Incident.id INNER JOIN ( SELECT username, name FROM Municipality UNION SELECT username, name FROM Government_Agency UNION SELECT username, name FROM Company UNION SELECT username, concat(firstname, ' ', lastname) as name FROM Individual ) AS All_user ON Request.sender_username = All_user.username WHERE Resource.owner_username = 'user3' AND Request.status = 'Pending'; ``` * Pick a request, run the following query to confirm the record exists in the Request table. Then click 'Reject' for that request. Confirm that the record disappears from the form. Run the query again to confirm the request has been deleted. The query should now return null. ``` select * from Request where id = $request_id ``` * Click 'Deploy' for a resource. Confirm that the record disappears from the form, and it should appear in the 'Resource in use' form if login as the requesting user. Then run query against the Request table to check the request status has been changed to 'Accepted'. Run another query against the Deploy_Schedule table to confirm a new row has been inserted with correctly information. ``` select * from Request where id = $request_id; ``` ``` select * from Deploy_Schedule where resource_id = $resource_id and responding_incident_id = $incident_id; ``` ### Test for Repair Schedule/In-progress: * Run the following query the database and confirm the output match the displayed information in the form. Confirm that resources that are currently in-repair do not have a 'Cancel' button. ``` SELECT Repair_Schedule.resource_id, Resource.name resource_name, Repair_Schedule.start_date, Repair_Schedule.end_date, Repair_Schedule.id repair_schedule_id FROM Repair_Schedule INNER JOIN Resource ON Repair_Schedule.resource_id = Resource.id WHERE Resource.owner_username = 'user3' AND Repair_Schedule.end_date > sysdate(); ``` * Run the following query for a resource, confirm that there is a record in Repair_Schedule before clicking 'Cancel', and the record is removed after clicking the button. ``` select * from Repair_Schedule where id = $repair_schedule_id; ```
C#
UTF-8
14,508
2.984375
3
[ "MIT" ]
permissive
using BrowserInterop.Extensions; using Microsoft.AspNetCore.Components; using Microsoft.JSInterop; using System; using System.Collections.Generic; using System.Globalization; using System.Threading.Tasks; namespace BrowserInterop { /// <summary> /// Give access to window.console API https://developer.mozilla.org/en-US/docs/Web/API/Console/ /// </summary> public class WindowConsole { /// <summary> /// Set to false if you want to disable all the calls to a console function /// </summary> public static bool IsEnabled { get; set; } = true; private readonly IJSRuntime jsRuntime; private readonly JsRuntimeObjectRef windowObject; internal WindowConsole(IJSRuntime jsRuntime, JsRuntimeObjectRef windowObject) { this.jsRuntime = jsRuntime; this.windowObject = windowObject; } /// <summary> /// Will print an error with the given objects in the output if the assertion is not verified /// </summary> /// <param name="assertion">true or false</param> /// <param name="printedObjects">object to print in the console</param> /// <returns></returns> public async ValueTask Assert(bool assertion, params object[] printedObjects) { if (IsEnabled) await jsRuntime.InvokeInstanceMethod(windowObject, "console.assert", assertion, printedObjects).ConfigureAwait(false); } /// <summary> /// Will print an error with the given message in the output if the assertion is not verified /// Note : in the browser API, the format is a C format but here it seems better to use .net string.Format /// </summary> /// <param name="assertion">true or false</param> /// <param name="message">message format</param> /// <param name="formatParameters">string.Format parameters</param> /// <returns></returns> public async ValueTask Assert(bool assertion, string message, params object[] formatParameters) { if (IsEnabled) await jsRuntime.InvokeInstanceMethod(windowObject, "console.assert", assertion, string.Format(CultureInfo.InvariantCulture, message, formatParameters)).ConfigureAwait(false); } /// <summary> /// Clear the console /// </summary> /// <returns></returns> public async ValueTask Clear() { if (IsEnabled) await jsRuntime.InvokeInstanceMethod(windowObject, "console.clear").ConfigureAwait(false); } /// <summary> /// Logs the number of times that this particular call to Count() has been called /// </summary> /// <param name="label">If supplied, Count() outputs the number of times it has been called with that label. If omitted, Count() behaves as though it was called with the "default" label.</param> /// <returns></returns> public async ValueTask Count(string label = null) { if (IsEnabled) await jsRuntime.InvokeInstanceMethod(windowObject, "console.count", label ?? "default").ConfigureAwait(false); } /// <summary> /// Reset a counter /// </summary> /// <param name="label">If supplied,resets this label counter else, resets the default label.</param> /// <returns></returns> public async ValueTask CountReset(string label = null) { if (IsEnabled) await jsRuntime.InvokeInstanceMethod(windowObject, "console.countReset", label ?? "default").ConfigureAwait(false); } /// <summary> /// Will print the given object at the debug level in the console /// </summary> /// <param name="printedObjects">object to print in the console</param> /// <returns></returns> public async ValueTask Debug(params object[] printedObjects) { if (IsEnabled) await jsRuntime.InvokeInstanceMethod(windowObject, "console.debug", printedObjects).ConfigureAwait(false); } /// <summary> /// Will print the given message at the debug level in the console /// Note : in the browser API, the format is a C format but here it seems better to use .net string.Format /// </summary>$ /// <param name="message">message format</param> /// <param name="formatParameters">string.Format parameters</param> /// <returns></returns> public async ValueTask Debug(string message, params object[] formatParameters) { if (IsEnabled) await jsRuntime.InvokeInstanceMethod(windowObject, "console.debug", string.Format(CultureInfo.InvariantCulture, message, formatParameters)).ConfigureAwait(false); } /// <summary> /// Display the object in the console as an interactive list /// </summary> /// <param name="data">the object to display</param> /// <returns></returns> public async ValueTask Dir(object data) { if (IsEnabled) await jsRuntime.InvokeInstanceMethod(windowObject, "console.dir", data).ConfigureAwait(false); } /// <summary> /// Display the HTML element as interactive in the console /// </summary> /// <param name="element">the HTML element ref to display</param> /// <returns></returns> public async ValueTask DirXml(ElementReference element) { if (IsEnabled) await jsRuntime.InvokeInstanceMethod(windowObject, "console.dirxml", element).ConfigureAwait(false); } /// <summary> /// Will print the given object at the error level in the console /// </summary> /// <param name="printedObjects">object to print in the console</param> /// <returns></returns> public async ValueTask Error(params object[] printedObjects) { if (IsEnabled) await jsRuntime.InvokeInstanceMethod(windowObject, "console.error", printedObjects).ConfigureAwait(false); } /// <summary> /// Will print the given message at the error level in the console /// Note : in the browser API, the format is a C format but here it seems better to use .net string.Format /// </summary>$ /// <param name="message">message format</param> /// <param name="formatParameters">string.Format parameters</param> /// <returns></returns> public async ValueTask Error(string message, params object[] formatParameters) { if (IsEnabled) await jsRuntime.InvokeInstanceMethod(windowObject, "console.error", string.Format(CultureInfo.InvariantCulture, message, formatParameters)).ConfigureAwait(false); } /// <summary> /// Creates a new group for the next logs in the console /// </summary> /// <param name="label">The group label</param> /// <returns></returns> public async ValueTask GroupStart(string label) { if (IsEnabled) await jsRuntime.InvokeInstanceMethod(windowObject, "console.group", label).ConfigureAwait(false); } /// <summary> /// End the current console group /// </summary> /// <returns></returns> public async ValueTask GroupEnd() { if (IsEnabled) await jsRuntime.InvokeInstanceMethod(windowObject, "console.groupEnd").ConfigureAwait(false); } /// <summary> /// Helper method for creating console group with the using syntax : the group will be closed when Dispose is called /// </summary> /// <param name="label">group label</param> /// <returns></returns> public async ValueTask<IAsyncDisposable> Group(string label) { if (!IsEnabled) return EmptyAsyncDisposable.Instance; await GroupStart(label).ConfigureAwait(false); return new ActionAsyncDisposable(GroupEnd); } /// <summary> /// Will print the given object at the log level in the console /// </summary> /// <param name="printedObjects">object to print in the console</param> /// <returns></returns> public async ValueTask Log(params object[] printedObjects) { if (IsEnabled) await jsRuntime.InvokeInstanceMethod(windowObject, "console.log", printedObjects).ConfigureAwait(false); } /// <summary> /// Will print the given message at the log level in the console /// Note : in the browser API, the format is a C format but here it seems better to use .net string.Format /// </summary>$ /// <param name="message">message format</param> /// <param name="formatParameters">string.Format parameters</param> /// <returns></returns> public async ValueTask Log(string message, params object[] formatParameters) { if (IsEnabled) await jsRuntime.InvokeInstanceMethod(windowObject, "console.log", string.Format(CultureInfo.InvariantCulture, message, formatParameters)).ConfigureAwait(false); } /// <summary> /// Start a profiling session with the given name /// </summary> /// <param name="name">The profiling session name</param> /// <returns></returns> public async ValueTask ProfileStart(string name = null) { if (IsEnabled) await jsRuntime.InvokeInstanceMethod(windowObject, "console.profile", name).ConfigureAwait(false); } /// <summary> /// End the profiling session withe the given name /// </summary> /// <returns></returns> public async ValueTask ProfileEnd(string name = null) { if (IsEnabled) await jsRuntime.InvokeInstanceMethod(windowObject, "console.profileEnd", name).ConfigureAwait(false); } /// <summary> /// Helper method for profiling with the using syntax : /// the profiling session will be closed when Dispose is called. /// You can see a profiling session by going in dev tool => 3 dots menu => more tools => Javascript Profiler /// </summary> /// <param name="name">profiler name</param> /// <returns></returns> public async ValueTask<IAsyncDisposable> Profile(string name = null) { if (!IsEnabled) return EmptyAsyncDisposable.Instance; await ProfileStart(name).ConfigureAwait(false); return new ActionAsyncDisposable(() => ProfileEnd(name)); } /// <summary> /// Display object list as a table /// </summary> /// <param name="objectToDisplay">Objects to display</param> /// <param name="columns">Columns to display, if no parameters then all the columns are displayed</param> /// <returns></returns> public async ValueTask Table<T>(IEnumerable<T> objectToDisplay, params string[] columns) { if (IsEnabled) await jsRuntime.InvokeInstanceMethod(windowObject, "console.table", objectToDisplay, columns).ConfigureAwait(false); } /// <summary> /// Start a timer, it's label and execution time will be shown on the profiling session (only the ones in the Performance tab, not the ones started with the Profile method) and on the console /// </summary> /// <param name="label">The label displayed</param> /// <returns></returns> public async ValueTask TimeStart(string label) { if (IsEnabled) await jsRuntime.InvokeInstanceMethod(windowObject, "console.time", label).ConfigureAwait(false); } /// <summary> /// End a timer, it's label and execution time will be shown on the profiling (not the one started) session and on the console /// </summary> /// <param name="label">The label displayed</param> /// <returns></returns> public async ValueTask TimeEnd(string label) { if (IsEnabled) await jsRuntime.InvokeInstanceMethod(windowObject, "console.timeEnd", label).ConfigureAwait(false); } /// <summary> /// Helper method for starting and ending a timer around a piece of code with the using syntax : /// the timer session will be ended when Dispose is called. /// </summary> /// <param name="label">The label displayed</param> /// <returns></returns> public async ValueTask<IAsyncDisposable> Time(string label) { if (!IsEnabled) return EmptyAsyncDisposable.Instance; await TimeStart(label).ConfigureAwait(false); return new ActionAsyncDisposable(() => TimeEnd(label)); } /// <summary> /// Display the given timer time in the console, it must be done when the timer is running /// </summary> /// <param name="label">The label displayed</param> /// <returns></returns> public async ValueTask TimeLog(string label) { if (IsEnabled) await jsRuntime.InvokeInstanceMethod(windowObject, "console.timeLog", label).ConfigureAwait(false); } /// <summary> /// Display a marker on the profiling sessions /// </summary> /// <param name="label">The label displayed</param> /// <returns></returns> public async ValueTask TimeStamp(string label) { if (IsEnabled) await jsRuntime.InvokeInstanceMethod(windowObject, "console.timeStamp", label).ConfigureAwait(false); } /// <summary> /// Will print the current browser stack trace (not the .net runtime stacktrace, for this use Environment.StackTrace) with this objects /// </summary> /// <param name="printedObjects">objects to print in the console</param> /// <returns></returns> public async ValueTask Trace(params object[] printedObjects) { if (IsEnabled) await jsRuntime.InvokeInstanceMethod(windowObject, "console.trace", printedObjects).ConfigureAwait(false); } } }
Java
UTF-8
3,400
2
2
[ "Apache-2.0" ]
permissive
/* * TopStack (c) Copyright 2012-2013 Transcend Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the License); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an AS IS BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * */ package com.msi.tough.model.monitor; import java.util.HashMap; import java.util.Map; import javax.persistence.Column; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; /** * This is all the necessary information to connect to a hypervisor. mduong: * added hibernate annotations * * @author heathm mduong * */ @Entity @Table(name = "hypervisors") public class HypervisorConfigBean { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @Column(name = "username") private String username; @Column(name = "type") private String type; @Column(name = "protocol") private String proto; @Column(name = "password") private String password; // TODO: make encrypted @Column(name = "host") private String host; @Column(name = "enable") private String enable; @Column(name = "account_id") private Integer accountId; @ElementCollection @Column(name = "options") private Map<String, String> options = new HashMap<String, String>(); public HypervisorConfigBean() { } public HypervisorConfigBean(final String given_username, final String given_type, final String given_proto, final String given_password, final String given_host, final Map<String, String> given_options) { username = given_username; type = given_type; proto = given_proto; password = given_password; host = given_host; options = given_options; } public Integer getAccountId() { return accountId; } public String getEnable() { return enable; } public String getHost() { return host; } public long getId() { return id; } public String getOption(final String name) { return options.get(name); } public Map<String, String> getOptions() { return options; } public String getPassword() { return password; } public String getProto() { return proto; } public String getType() { return type; } public String getUsername() { return username; } public void setAccountId(final Integer accountId) { this.accountId = accountId; } public void setEnable(final String enable) { this.enable = enable; } public void setHost(final String host) { this.host = host; } public void setId(final long id) { this.id = id; } public void setOptions(final Map<String, String> options) { this.options = options; } public void setPassword(final String password) { this.password = password; } public void setProto(final String proto) { this.proto = proto; } public void setType(final String type) { this.type = type; } public void setUsername(final String username) { this.username = username; } }
Python
UTF-8
5,017
2.625
3
[]
no_license
"""Original code: https://www.kaggle.com/sergemsu/kalman-faces """ import pathlib import math import os import logging import itertools from multiprocessing import Pool import configargparse import pandas as pd import numpy as np from tqdm import tqdm from scipy import interpolate from matplotlib import pyplot as plt import face_landmarks from cli_utils import is_dir FACE_ZONES = [0, 64, 128, 273, 337, 401, 464, 527, 587, 714, 841, 873, 905, 937, 969] def angle_variation(ps): dps = np.diff(ps, axis=0) angles = [] for i in range(len(dps) - 1): e1, e2 = dps[i], dps[i + 1] x = np.clip(e1.dot(e2) / (np.linalg.norm(e1) * np.linalg.norm(e2) + 0.00001), -1, 1) angle = math.degrees(math.acos(x)) angles.append(angle) return np.mean(angles) def kalman(x_observ, Q=1e-5, R=0.0001): n = len(x_observ) x_hat = np.zeros(n) # a posteri estimate of x P = np.zeros(n) # a posteri error estimate x_hatminus = np.zeros(n) # a priori estimate of x P_minus = np.zeros(n) # a priori error estimate K = np.zeros(n) # gain or blending factor # intial guesses x_hat[0] = x_observ[0] P[0] = 1.0 for k in range(1, n): # time update x_hatminus[k] = x_hat[k-1] P_minus[k] = P[k-1]+Q # measurement update K[k] = P_minus[k] / (P_minus[k] + R) x_hat[k] = x_hatminus[k] + K[k]*(x_observ[k] - x_hatminus[k]) P[k] = (1 - K[k])*P_minus[k] return x_hat def bidir_kalman(x_observ, Q=1e-5, R=0.0003, iters=2): n = len(x_observ) for _ in range(iters): x_forw = kalman(x_observ, Q, R) x_back = np.flip(kalman(np.flip(x_observ), Q, R)) k = 7 x_full = np.zeros(n+k) x_full[:k] = x_forw[:k] x_full[k:n] = 0.5 * (x_forw[k:] + x_back[:n-k]) x_full[n:] = x_back[n-k:] f = interpolate.interp1d(np.linspace(0, n+k, n+k), x_full, kind='quadratic') x_observ = f(np.linspace(0, n + k, n)) return x_observ def fix_landmars(landmark): landmark = landmark.astype(float) for i in range(1, len(FACE_ZONES)): zone = landmark[FACE_ZONES[i-1]:FACE_ZONES[i]] x_filt = bidir_kalman(zone[:, 0], iters=1) y_filt = bidir_kalman(zone[:, 1], iters=1) np.copyto(zone, np.array([x_filt, y_filt]).T) return landmark def compute_stat(image_name, landmark): stat1 = angle_variation(landmark[:64, :]) stat2 = angle_variation(landmark[64: 128, :]) return (image_name, stat1, stat2) def fix_faces(image_dir, out_path): logger = logging.getLogger("kp.main") image_dir_pathlib = pathlib.Path(image_dir) face_landmarks_path = image_dir_pathlib.parent / "landmarks.csv" face_landmarks: pd.DataFrame = pd.read_csv(face_landmarks_path, sep='\t', engine="c", index_col="file_name") image_names = face_landmarks.index.tolist() with Pool(max(1, os.cpu_count() // 2)) as workers: stats = workers.starmap(compute_stat, zip( image_names, face_landmarks.to_numpy().reshape(len(image_names), -1, 2) ) ) stats = pd.DataFrame(data=stats, columns=["file", "stat1", "stat2"]).set_index("file") noisy = stats[(stats['stat1'] > 70) & (stats['stat2'] > 70)].index logger.info("Detect %d noisy annotations", len(noisy)) fixed_landmarks = face_landmarks.copy(deep=True) def save_debug_image(input_img_path, landmarks, fixed, out_path): image = plt.imread(input_img_path) fig = plt.figure() axes = fig.subplots(1, 2) axes[0].imshow(image) axes[0].set_label("Before") axes[0].plot(landmarks[:, 0], landmarks[:, 1], "go") axes[1].imshow(image) axes[1].set_label("After") axes[1].plot(fixed[:, 0], fixed[:, 1], "go") fig.savefig(out_path) num_save = 0 for image_name in tqdm(noisy, desc="Fix landmarks", total=len(noisy)): landmark = face_landmarks.loc[image_name].to_numpy().reshape(-1, 2) fixed = fix_landmars(landmark) fixed_landmarks.loc[image_name] = np.round(fixed.reshape(-1)).astype(int) if num_save < 5: save_debug_image(image_dir_pathlib / image_name, landmark, fixed, out_path.with_name(f"{num_save}_savefix_landmarks_debug.jpg")) num_save += 1 fixed_landmarks.to_csv(out_path, index=True, sep="\t", encoding="utf-8") logger.info("Save new landmarks to '%s'", out_path) def main(args): out_path = pathlib.Path(args.out_file) out_path.parent.mkdir(parents=True, exist_ok=True) fix_faces(args.image_dir, out_path) if __name__ == "__main__": parser = configargparse.ArgParser() parser.add_argument("-c", is_config_file=True) parser.add_argument("--image_dir", required=True, type=is_dir) parser.add_argument("--out_file", required=True, type=str) args = parser.parse_args() main(args)
Java
UTF-8
1,151
2.328125
2
[]
no_license
package io.chuumong.booksearch.ui.adapter; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import javax.inject.Inject; import io.chuumong.booksearch.ui.fragment.FragmentHolder; import io.chuumong.booksearch.ui.fragment.SearchFragment; public class ViewPagerAdapter extends FragmentPagerAdapter { private final FragmentHolder fragmentHolder; @Inject public ViewPagerAdapter(FragmentManager fm, FragmentHolder fragmentHolder) { super(fm); this.fragmentHolder = fragmentHolder; } @Override public Fragment getItem(int position) { switch (position) { case 0: return fragmentHolder.getSearchFragment(); case 1: return fragmentHolder.getSearchHistoryFragment(); case 2: return fragmentHolder.getSettingFragment(); } return null; } @Override public int getCount() { return 3; } public SearchFragment getSearchFragment() { return fragmentHolder.getSearchFragment(); } }
Java
UTF-8
1,153
2.328125
2
[]
no_license
package com.kolibree.sdkws.data.model; import androidx.annotation.Keep; import com.google.gson.JsonObject; /** Created by mdaniel on 11/11/2015. */ @Keep public final class BrushPass { private static final String FIELD_PASSE_DATETIME = "pass_datetime"; private static final String FIELD_PASSE_EFFECTIVE_TIME = "effective_time"; private int pass_datetime; private int pass_effective_time; public BrushPass(int pass_datetime, int pass_effective_time) { this.pass_datetime = pass_datetime; this.pass_effective_time = pass_effective_time; } public int getPass_datetime() { return pass_datetime; } public void setPass_datetime(int pass_datetime) { this.pass_datetime = pass_datetime; } public int getPass_effective_time() { return pass_effective_time; } public void setPass_effective_time(int pass_effective_time) { this.pass_effective_time = pass_effective_time; } public JsonObject toJSON() { final JsonObject json = new JsonObject(); json.addProperty(FIELD_PASSE_DATETIME, pass_datetime); json.addProperty(FIELD_PASSE_EFFECTIVE_TIME, pass_effective_time); return json; } }
JavaScript
UTF-8
334
2.515625
3
[]
no_license
let loggerObj = { }; const logHandler = { get: function(obj, prop) { return prop in loggerObj ? loggerObj[prop] : () => {}; } } let loggerProxy = new Proxy(loggerObj, logHandler); export function setLogger(logger) { loggerObj = logger; } export function getLogger() { return loggerProxy; }
Java
UTF-8
8,894
2.21875
2
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
package org.broadinstitute.hellbender.tools.walkers; import htsjdk.variant.variantcontext.*; import org.broadinstitute.hellbender.GATKBaseTest; import org.broadinstitute.hellbender.testutils.VariantContextTestUtils; import org.broadinstitute.hellbender.utils.variant.GATKVCFConstants; import org.broadinstitute.hellbender.utils.variant.GATKVariantContextUtils; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.util.*; import java.util.function.Function; public class GenotypeGVCFsUnitTest extends GATKBaseTest { public static final int MIN_DP = 15; public static final int DP = 3; public static final Function<GenotypeBuilder, GenotypeBuilder> ADD_DP = b -> b.DP(DP); public static final Allele REF = Allele.create("A", true); public static final Allele ALT = Allele.create("C", false); @DataProvider(name = "variantContexts") public Object[][] variantContexts() { return new Object[][]{ { getHetWithGenotype(Collections.singletonList(new GenotypeBuilder("SAMPLE", Arrays.asList(ALT, ALT)) .DP(DP) .attribute(GATKVCFConstants.MIN_DP_FORMAT_KEY, MIN_DP) .attribute(GATKVCFConstants.STRAND_BIAS_BY_SAMPLE_KEY, new int[]{1, 1, 1, 1}) .attribute(GATKVCFConstants.HAPLOTYPE_CALLER_PHASING_GT_KEY, "bad") .PL(new int[]{50, 20, 0}).make())), false, Collections.singletonList(new GenotypeBuilder("SAMPLE", Arrays.asList(ALT, ALT)) .DP(MIN_DP) .attribute(GATKVCFConstants.HAPLOTYPE_CALLER_PHASING_GT_KEY, GenotypeGVCFs.PHASED_HOM_VAR_STRING) .AD(new int[]{MIN_DP, 0}) .PL(new int[]{50, 20, 0}).make()) }, { getHetWithGenotype(Collections.singletonList(new GenotypeBuilder("SAMPLE", Arrays.asList(REF,REF)) .GQ(20) .DP(MIN_DP) .PL(new int[]{0,15,50}).make())), true, Collections.singletonList(new GenotypeBuilder("SAMPLE", Arrays.asList(REF, REF)) .DP(MIN_DP) .AD(new int[]{MIN_DP, 0}) .attribute(GATKVCFConstants.REFERENCE_GENOTYPE_QUALITY, 20).make()) } }; } @Test(dataProvider= "variantContexts") public void testCleanupGenotypeAnnotations(VariantContext vc, boolean createRefGTs, List<Genotype> expected){ final List<Genotype> genotypes = GenotypeGVCFsEngine.cleanupGenotypeAnnotations(vc, createRefGTs); VariantContextTestUtils.assertGenotypesAreEqual(genotypes.get(0), expected.get(0)); } private VariantContext getHetWithGenotype(List<Genotype> genotypes){ return new VariantContextBuilder().alleles(Arrays.asList(REF, ALT)) .loc("1",100,100) .genotypes(genotypes).make(); } @SafeVarargs private static List<Genotype> generateGenotypes(Function<GenotypeBuilder, GenotypeBuilder>... customizations){ final List<Genotype> genotypes = new ArrayList<>(); for(int i = 0; i< customizations.length; i++) { final Function<GenotypeBuilder, GenotypeBuilder> customization = customizations[i]; final GenotypeBuilder builder = new GenotypeBuilder("Sample_" + i); final GenotypeBuilder applied = customization.apply(builder); genotypes.add(applied.make()); } return genotypes; } @DataProvider public Object[][] getMinDPData(){ final Function<GenotypeBuilder, GenotypeBuilder> addMinDP = b -> b.attribute(GATKVCFConstants.MIN_DP_FORMAT_KEY, MIN_DP); return new Object[][]{ {getHetWithGenotype( generateGenotypes(addMinDP)), MIN_DP}, //MIN_DP only {getHetWithGenotype( generateGenotypes(ADD_DP)), DP}, // DP only {getHetWithGenotype( generateGenotypes(addMinDP.andThen(ADD_DP))), MIN_DP} //MIN_DP replaces DP }; } @Test(dataProvider = "getMinDPData") public void testMinDPReplacedWithDP(VariantContext vc, int expectedDepth){ Assert.assertEquals(GenotypeGVCFsEngine.cleanupGenotypeAnnotations(vc, false).get(0).getDP(), expectedDepth); Assert.assertNull(GenotypeGVCFsEngine.cleanupGenotypeAnnotations(vc, false).get(0).getExtendedAttribute(GATKVCFConstants.MIN_DP_FORMAT_KEY)); } @Test public void testSBRemoved(){ final VariantContext vcWithSB = getHetWithGenotype(generateGenotypes(b -> b.attribute(GATKVCFConstants.STRAND_BIAS_BY_SAMPLE_KEY, new int[]{6, 11, 11, 10}))); Assert.assertNotNull(vcWithSB.getGenotype("Sample_0").getAnyAttribute(GATKVCFConstants.STRAND_BIAS_BY_SAMPLE_KEY)); final Genotype afterCleanup = GenotypeGVCFsEngine.cleanupGenotypeAnnotations(vcWithSB, true).get(0); Assert.assertNull(afterCleanup.getExtendedAttribute(GATKVCFConstants.STRAND_BIAS_BY_SAMPLE_KEY)); } @Test public void testADCreated(){ final VariantContext noAD = getHetWithGenotype(generateGenotypes(ADD_DP)); Assert.assertNull(noAD.getGenotype("Sample_0").getAD()); final Genotype afterCleanup = GenotypeGVCFsEngine.cleanupGenotypeAnnotations(noAD, true).get(0); Assert.assertEquals(afterCleanup.getAD(), new int[]{DP, 0}); } @Test public void testPhasingUpdate(){ final VariantContext withPhasing = getHetWithGenotype(generateGenotypes(b -> b.attribute(GATKVCFConstants.HAPLOTYPE_CALLER_PHASING_GT_KEY, "bad") .alleles(Arrays.asList(ALT,ALT)), b -> b.attribute(GATKVCFConstants.HAPLOTYPE_CALLER_PHASING_GT_KEY, "something").alleles(Arrays.asList(REF,REF)))); final Genotype homVarAfterCleanup = GenotypeGVCFsEngine.cleanupGenotypeAnnotations(withPhasing, true).get(0); Assert.assertEquals(homVarAfterCleanup.getAnyAttribute(GATKVCFConstants.HAPLOTYPE_CALLER_PHASING_GT_KEY), GenotypeGVCFs.PHASED_HOM_VAR_STRING); final Genotype homRefAfterCleaning = GenotypeGVCFsEngine.cleanupGenotypeAnnotations(withPhasing, true).get(1); Assert.assertEquals(homRefAfterCleaning.getAnyAttribute(GATKVCFConstants.HAPLOTYPE_CALLER_PHASING_GT_KEY), "something"); } @Test public void testRGQ0IsNoCall(){ final List<Allele> noCall = GATKVariantContextUtils.noCallAlleles(2); final VariantContext gq0 = getHetWithGenotype(generateGenotypes(b -> b.GQ(0).DP(10).alleles(noCall), // GQ = 0 (b -> b.DP(10).alleles(noCall)))); //no GQ final List<Genotype> genotypes = GenotypeGVCFsEngine.cleanupGenotypeAnnotations(gq0, true); for( Genotype genotype : genotypes ){ Assert.assertEquals(genotype.getAlleles(), noCall); } } @DataProvider public Object[][] getVariantsForIsProperlyPolymorphic(){ return new Object[][]{ {new VariantContextBuilder("test", "1", 1, 1, Collections.singleton(REF)).make(), false}, {new VariantContextBuilder("test", "1", 1, 1, Arrays.asList(REF, ALT)).make(), true}, {new VariantContextBuilder("test", "1", 1, 1, Arrays.asList(REF, Allele.NON_REF_ALLELE)).make(), false}, {new VariantContextBuilder("test", "1", 1, 1, Arrays.asList(REF, Allele.SPAN_DEL)).make(), false}, {new VariantContextBuilder("test", "1", 1, 2, Arrays.asList(REF, Allele.create("<SOME_SYMBOLIC_ALLELE>"))).make(), false}, {new VariantContextBuilder("test", "1", 1, 1, Arrays.asList(REF, ALT, Allele.create("G"))).make(), true}, {null, false} }; } @Test(dataProvider = "getVariantsForIsProperlyPolymorphic") public void testIsProperlyPolymorphic(VariantContext vc, boolean expected){ Assert.assertEquals(GATKVariantContextUtils.isProperlyPolymorphic(vc), expected); } @DataProvider public Object[][] getSpanningAndNonSpanningAlleles(){ return new Object[][]{ {Allele.SPAN_DEL, true}, {GATKVCFConstants.SPANNING_DELETION_SYMBOLIC_ALLELE_DEPRECATED, true}, {Allele.NON_REF_ALLELE, false}, {Allele.NO_CALL, false}, {Allele.create("A", true), false} }; } @Test(dataProvider = "getSpanningAndNonSpanningAlleles") public void testIsSpanningDeletion(Allele allele, boolean expected){ Assert.assertEquals(GATKVCFConstants.isSpanningDeletion(allele), expected); } }
C#
UTF-8
842
2.609375
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PowerUp : MonoBehaviour{ protected Player player; [SerializeField] protected float despawnTimer; [SerializeField] protected bool willDespawnAfterTimer; public PowerUp() { willDespawnAfterTimer = false; } public PowerUp(float despawnTimer) { this.despawnTimer = despawnTimer; } // Start is called before the first frame update private void Start() { if (willDespawnAfterTimer) { StartCoroutine(startDespawnTimer()); } } public virtual void ProcessPowerUp(Player player) { } public IEnumerator startDespawnTimer() { Debug.Log("Despawning soon"); yield return new WaitForSeconds(despawnTimer); Destroy(gameObject); } }
TypeScript
UTF-8
2,715
2.78125
3
[]
no_license
import * as PIXI from 'pixi.js'; import { GameConfig } from '../models/game-config'; import { IsometricStack } from '../models/isometric-stack'; import { Tile } from '../models/tile'; import { isoToIndex } from '../utils/iso-to-index'; export interface CoordsUpdate { cartesianIndicatorText: string; tileIndicatorText: string; tileHovered: Tile; } export interface PositionalUpdate { delx: number; dely: number; draggedx: number; draggedy: number; newContainerPositionX: number; newContainerPositionY: number; draggedIndicatorText: string; containerIndicatorText: string; containerParentIndicatorText: string; } export const isCoordsUpdate = ( update: CoordsUpdate | PositionalUpdate, ): update is CoordsUpdate => (update as CoordsUpdate).cartesianIndicatorText !== undefined && (update as CoordsUpdate).tileIndicatorText !== undefined; export const isPositionalUpdate = ( update: CoordsUpdate | PositionalUpdate, ): update is PositionalUpdate => (update as PositionalUpdate).delx !== undefined && (update as PositionalUpdate).dely !== undefined; export const mouseMoveInteraction = ( { data }: PIXI.InteractionEvent, myContainer: IsometricStack, config: GameConfig, dragging: boolean, draggedx: number, draggedy: number, tileClicked?: Tile, ): CoordsUpdate | PositionalUpdate => { const { x, y } = data.getLocalPosition(myContainer); const [i, j] = isoToIndex(x, y, config); const parentPosition = data.getLocalPosition(myContainer.parent); if (!dragging) { return { cartesianIndicatorText: `${x.toFixed(2)}, ${y.toFixed(2)}`, tileIndicatorText: isoToIndex(x, y, config).toString(), tileHovered: { i, j, x: x * myContainer.scale.x, y: y * myContainer.scale.y, z: 0, }, }; } else { const tileDragged = tileClicked || { x: 0, y: 0, }; return { delx: myContainer.position.x, dely: myContainer.position.y, draggedx: draggedx + myContainer.position.x / 1000, draggedy: draggedy + myContainer.position.y / 1000, newContainerPositionX: parentPosition.x - tileDragged.x, newContainerPositionY: parentPosition.y - tileDragged.y, draggedIndicatorText: `dragged: { x: ${draggedx.toFixed( 2, )}, y: ${draggedy.toFixed(2)}}`, containerIndicatorText: `myContainer = { x: ${(x - tileDragged.x).toFixed( 2, )}, y: ${(y - tileDragged.y).toFixed(2)}}`, containerParentIndicatorText: `myContainer.parent = { x: ${data .getLocalPosition(myContainer.parent) .x.toFixed(2)}, y: ${data .getLocalPosition(myContainer.parent) .y.toFixed(2)} }`, }; } };
Java
UTF-8
2,478
2.3125
2
[]
no_license
package org.khandora.mit.controller; import lombok.RequiredArgsConstructor; import org.khandora.mit.dto.TaskDto; import org.khandora.mit.model.Task; import org.khandora.mit.model.User; import org.khandora.mit.repository.TaskRepository; import org.khandora.mit.repository.UserRepository; import org.modelmapper.ModelMapper; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; @CrossOrigin(origins = "http://localhost:4200") @RequiredArgsConstructor @RestController @RequestMapping("/api/task") public class TaskController { private final ModelMapper modelMapper; private final TaskRepository taskRepository; private final UserRepository userRepository; @GetMapping public List<Task> getAllTask() { return taskRepository.findAll(); } @GetMapping("/{id}") public Task getTask(@PathVariable(value = "id") Long taskId) { return taskRepository.findById(taskId).orElseThrow( () -> new RuntimeException("Error task with id "+ taskId +" not found")); } @PostMapping("/{username}") public Task createTask(@PathVariable(value = "username") String username, @Valid @RequestBody TaskDto taskDto) { User user = userRepository.findByUserName(username).orElseThrow(() -> new RuntimeException("Error user with name "+ username +" not found")); Task task = modelMapper.map(taskDto, Task.class); task.setUser(user); return taskRepository.save(task); } @PostMapping("/{id}/edit") public Task editTask(@PathVariable(value = "id") Long taskId, @Valid @RequestBody TaskDto taskDto) { Task rqTask = modelMapper.map(taskDto, Task.class); Task rpTask = taskRepository.findById(taskId).orElseThrow( () -> new RuntimeException("Error task with id "+ taskId +" not found")); rpTask.setLevel(rqTask.getLevel()); rpTask.setSubject(rqTask.getSubject()); rpTask.setQuestion(rqTask.getQuestion()); return taskRepository.save(rpTask); } @DeleteMapping("/{id}") public ResponseEntity<Long> deleteTask(@PathVariable (value = "id") Long taskId) { Task task = taskRepository.findById(taskId).orElseThrow( () -> new RuntimeException("Error task with id "+ taskId +" not found" )); taskRepository.delete(task); return ResponseEntity.ok().build(); } }
C++
UTF-8
5,429
3.09375
3
[]
no_license
#include "postfix.h" #include "stack.h" string TPostfix::ToPostfix() { TStack<char> STACK(MaxStackSize); //создаем стэк int L = infix.length(); //размер инф string OPERATIONS = "+-*/()"; //используемые операции for (int i = 0; i < L; i++) //проходимся по infix { for (int k = 0; k < 6; k++) // если не операция { if (infix[i] != OPERATIONS[k]) { postfix += infix[i]; } } if ((infix[i] >= '0') && (infix[i] <= '9')) { if (i != L) //если не последний элемент { if ((infix[i + 1] < '0') || (infix[i + 1] > '9')) //если следующий не цифра { postfix += '\\'; // разделитель // } } else // если последний { postfix += '\\'; } } if (infix[i] == '(') //если ( , то в стэк { STACK.PUSH_El(infix[i]); } if (infix[i] == ')') // если ), то всё из стэка в постфикс { char a = STACK.POP_El(); while (a != '(') { postfix += a; a = STACK.POP_El(); } } for (int k = 0; k < 4; k++) // если не операция { if (infix[i] == OPERATIONS[k]) //если операция { if (STACK.Empty() == true) //если стэк пуст, то операцию в стэк { STACK.PUSH_El(infix[i]); } else { int b1 = OPERATIONS.find(infix[i]); // ищем индекс операции while (STACK.Empty() == false) { char s = STACK.POP_El(); //последний элемент, который решал в стэке if (s == '(') //если ( { STACK.PUSH_El(s); //возвращаем в стэк break; } int b2 = OPERATIONS.find(s); // ищем индекс операции s if (operation_priority[b2] <= operation_priority[b1]) { postfix += s; } else { STACK.PUSH_El(s); break; } } STACK.PUSH_El(infix[i]); } } } } while (STACK.Empty() == false) //записываем из стэка постфикс { postfix += STACK.POP_El(); } return postfix; } double TPostfix::Calculate() { if (postfix.length() == 0) { ToPostfix(); //создаем постфиксную форму } int LEN = postfix.length(); //размер постф TStack<char> STACK(MaxStackSize); string nameArguments; //массив имен double *Arguments = new double[LEN]; //массив значений for (int i = 0; i < LEN; i++) //проходимся по postfix { bool IsNotOperation; for (int k = 0; k < 6; k++) // если не операция { if (postfix[i] != operations[k]) { IsNotOperation = true; //это не операция } else IsNotOperation = false; //это операция } if (IsNotOperation == true) { double z; bool FirstTime; if ((postfix[i] < '0') || (postfix[i] > '9')) //cимвол не цифра { for (int j = 0; j < nameArguments.length(); j++) //проходим по массиву имен пременных { if (postfix[j] != nameArguments[j]) // если первый раз встр { FirstTime = true; } else { FirstTime = false; } } if (FirstTime == true) //переменная встр первый раз { nameArguments += postfix[i]; //записали имя переменной cout << "Введите значение переменной - " << postfix[i] << endl; cin >> z; Arguments[nameArguments.length() - 1] = z; //записали значение переменной в массив заначений } else if (FirstTime == false) // если встречается переменная не в первый раз { z = Arguments[nameArguments.find(postfix[i])]; //в р записываем значение соответсвующей переменной } } else { string NUMBER; while (postfix[i] != '\\') //пока не найдем разделитель { NUMBER += postfix[i]; i++; } z = stoi(NUMBER); //преобразует строку в число } STACK.PUSH_El(z); //положили в стэк } else if (IsNotOperation == false) { double arg1, arg2, Res; arg2 = STACK.POP_El(); //Взяли из стека последний элемент arg1 = STACK.POP_El(); //Взяли из стека предпоследний элемент switch (postfix[i]) //определяем операцию { case '+': //если + Res = arg1 + arg2; break; case '-': //если - Res = arg1 - arg2; break; case '*': //если * Res = arg1 * arg2; break; case '/': //если / Res = arg1 / arg2; break; } STACK.PUSH_El(Res); //положили в стек результат операции } } delete[] Arguments; //удаляем массив значений double result = STACK.POP_El(); return result; //возвращаем единственный элемент стека }
Java
UTF-8
2,766
2.4375
2
[]
no_license
package com.example.hw_1; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; import java.util.List; public class NumberListFragment extends Fragment implements View.OnClickListener { private NumberItemAdapter adapter; private List<NumberItem> numbers = new ArrayList<>(); private static String ELEMS_NUM_KEY = "ELEMS_NUM"; private int numbersSize; public NumberListFragment() { super(); } static NumberListFragment newInstance() { return new NumberListFragment(); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); int elemsNum = getResources().getInteger(R.integer.elements_num); if (savedInstanceState != null) { elemsNum = savedInstanceState.getInt(ELEMS_NUM_KEY, elemsNum); } for (int i = 0; i < elemsNum; ++i) { numbers.add(createItemToAdd()); ++numbersSize; } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_number_list, parent, false); RecyclerView recyclerView = view.findViewById(R.id.recycleview); NumberItemAdapter.NumberClicker listener = (NumberItemAdapter.NumberClicker) getActivity(); adapter = new NumberItemAdapter(numbers, listener); recyclerView.setAdapter(adapter); recyclerView.setLayoutManager(new GridLayoutManager(getContext(), getResources().getInteger(R.integer.columns_num))); view.findViewById(R.id.button).setOnClickListener(this); return view; } @Override public void onDetach() { super.onDetach(); adapter.clearRefs(); } @Override public void onSaveInstanceState(@NonNull Bundle state) { state.putInt(ELEMS_NUM_KEY, numbersSize); super.onSaveInstanceState(state); } @Override public void onClick(View view) { addItem(); } private void addItem() { NumberItem item = createItemToAdd(); numbers.add(item); ++numbersSize; adapter.notifyItemInserted(item.num - 1); } private NumberItem createItemToAdd() { int index = numbers.size() + 1; return new NumberItem(index, getResources().getColor(index % 2 == 0 ? R.color.evenNumber : R.color.oddNumber)); } }
C++
UTF-8
2,367
3.3125
3
[]
no_license
#include <iostream> #include <algorithm> #include <tuple> #include <vector> #include <cmath> #include <string> #include <iomanip> using namespace std; /* основная идея: если у нас есть две точки a, b, причем a <= b, и: a) искомое число x находится ближе к a, то можно утвержать, что x принадлежит (-∞, (b - a) / 2] b) искомое число x находится ближе к b, то можно утвержать, что x принадлежит [(b - a) / 2, +∞) из этой идеи можно по каждым двум частотам последовательности и информации, какая из частот ближе к искомой, последовательно обновлять допустимые границы искомой частоты */ struct Data { double value; bool isCloserThanPrevious; }; pair<double, double> findRange (const vector<Data>& sequence) { double minFrequency = 30; double maxFrequency = 4000; for (int i = 1; i < sequence.size(); ++i) { if ((sequence[i-1].value < sequence[i].value) ^ sequence[i].isCloserThanPrevious) { double possibleMax = (sequence[i].value + sequence[i-1].value) / 2; maxFrequency = min(maxFrequency, possibleMax); } else { double possibleMin = (sequence[i].value + sequence[i-1].value) / 2; minFrequency = max(minFrequency, possibleMin); } } return {minFrequency, maxFrequency}; } int main () { const vector<Data> inputSequence = [] { vector<Data> inputSequence; int n; cin >> n; inputSequence.reserve(n); double frequency; string relation; cin >> frequency; inputSequence.push_back({frequency, true}); for (int i = 1; i < n; ++i) { cin >> frequency; cin >> relation; if (relation == "closer") { inputSequence.push_back({frequency, true}); } else { inputSequence.push_back({frequency, false}); } } return inputSequence; } (); auto answer = findRange(inputSequence); cout << setprecision(7) << answer.first << ' ' << answer.second; return 0; }
Java
UTF-8
4,422
3.25
3
[]
no_license
package com.ww.JavaSerializable03; import java.io.Serializable; /** * @author: Sun * @create: 2019-11-07 18:35 * @version: v1.0 */ public class JavaSerializable03 implements Serializable { /** *《手册》第9页“OOP规约”部分有一段关于序列化的约定 *【强制】当序列化类新增属性时,请不要修改serialVersionUID字段,以避免反序列失败;如果完全不兼容升级, * 避免反序列化混乱,那么请修改serialVersionUID 值。 * 说明:注意serialVersionUID值不一致会抛出序列化运行时异常。 */ /** * 本节问题: * 1、序列化和反序列化到底是什么? * 答案:把对象转换为字节序列存储于磁盘或者进行网络传输的过程称为对象的序列化。 * 反序列化正好相反,是从网络传输过来的数据或此判断中读取序列化数据并转化成内存对象的过程。 * * 2、为什么需要序列化和反序列化? * 大家可以回忆一下,平时都是如果将文字文件、图片文件、视频文件、软件安装包等传给小伙伴时,这些资源在计算机中存储的方式是怎样的。 * 进而再思考,Java中的对象如果需要存储或者传输应该通过什么形式呢? * * 我们都知道,一个文件通常是一-个m个字节的序列: B0, B1, ... Bk, ... Bm-1。所有的I/O设备(例如网络、磁盘和终端)都被模型化为文件, * 而所有的输入和输出都被当作对应文件的读和写来执行。因此本质上讲,文本文件,图片、视频和安装包等文件底层都被转化为二进制字节流来传输的, * 对方得文件就需要对文件进行解析,因此就需要有能够根据不同的文件类型来解码出文件的内容的程序。 * * 试想一个典型的场景:如果要实现Java远程方法调用,就需要将调用结果通过网路传输给调用方,如果调用方和服务提供方不在一台机器上 * 就很难共享内存,就需要将Java对象进行传输。而想要将Java中的对象进行网络传输或存储到文件中,就需要将对象转化为二进制字节流, * 这就是所谓的序列化。存储或传输之后必然就需要将二进制流读取并解析成Java对象,这就是所谓的反序列化。 * * 答案:为了方便存储到文件系统、数据库系统或网络传输等。 * * 3、它的主要使用场景有哪些? * · 远程方法调用(RPC) 的框架里会用到序列化。 * · 将对象存储到文件中时,需要用到序列化。 * · 将对象存储到缓存数据库(如Redis) 时需要用到序列化。 * · 通过序列化和反序列化的方式实现对象的深拷贝。 * * 3、Java序列化常见的方案有哪些? * Java原生序列化、Hessian序列化、Kryo序列化、JSON序列化等。 * * 4、各种常见序列化方案的区别有哪些? * · Java序列化的优点是:对对象的结构描述清晰,反序列化更安全。主要缺点是:效率低,序列化后的二进制流较大。 * · Hession序列化二进制流较Java序列化更小,且序列化和反序列化耗时更短。但是父类和子类有相同类型属性时,由于先序列化子类再序列化父类, * 因此反序列化时子类的同名属性会被父类的值覆盖掉,开发时要特别注意这种情况。 * · Kryo优点是:速度快、序列化后二进制流体积小、反序列化超快。但是缺点是:跨语言支持复杂。注册模式序列化更快,但是编程更加复杂。 * · JSON序列化的优势在于可读性更强。主要缺点是:没有携带类型信息,只有提供了准确的类型信息才能准确地进行反序列化,这点也特别容易引发线上问题。 * * 5、实际的业务开发中有哪些坑点? */ /** * 包装类型不可强转,为什么包装类型不可强转? * Integer i = 100000; * Long l = (Long) i; * <p> * 并不是包装类型不可强转,而是只有具有子父类关系的类才可以相关强制转换。 * 子类对象声明为父类类型后,可以通过强制转型转换为子类类型 * 父类对象声明为父类类型后,不可以通过强制转换转换为子类型 */ }
Swift
UTF-8
7,221
3.03125
3
[]
no_license
// // ComplicationController.swift // TendApp WatchKit Extension // // Created by Mateus Augusto M Ferreira on 16/06/20. // Copyright © 2020 Mateus Augusto M Ferreira. All rights reserved. // import ClockKit /// Classe ComplicationController. class ComplicationController: NSObject, CLKComplicationDataSource { // MARK: - Timeline Configuration /// Função que determina se a sua complication pode fornecer entradas da linha do tempo para o futuro ou o passado. /// - Parameters: /// - complication: Complication ligada ao pedido. /// - handler: O manipulador para executar com as instruções de Viagem no tempo. Este bloco não tem valor de retorno e aceita o seguinte parâmetro: /// direções /// As instruções de viagem no tempo com suporte. Você pode combinar os valores do tipo CLKComplicationTimeTravelDirections ao especificar esse valor. func getSupportedTimeTravelDirections(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimeTravelDirections) -> Void) { handler([.forward, .backward]) } /// Função que recupera a data mais antiga para a qual sua complicação está preparada para fornecer dados. /// - Parameters: /// - complication: Complication ligada ao pedido. /// - handler: O manipulador para executar com a data de início. Este bloco não tem valor de retorno e aceita o seguinte parâmetro: /// direções /// date /// A data de início dos seus dados. Por períodos anteriores a essa data, o WatchKit escurece seus dados para indicar que a linha do tempo não continua. Se você especificar zero, o ClockKit não solicitará mais dados anteriores. func getTimelineStartDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) { handler(nil) } /// Função que recupera a última data dos dados que seu aplicativo pode fornecer. /// - Parameters: /// - complication: Complication ligada ao pedido. /// - handler: O manipulador para executar com a data final. Este bloco não tem valor de retorno e aceita o seguinte parâmetro: /// date /// A data final para seus dados. Se você especificar zero, o ClockKit não solicitará mais dados futuros. func getTimelineEndDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) { handler(nil) } /// Função que retorna o comportamento de privacidade para a complicação especificada. /// - Parameters: /// - complication: Complication ligada ao pedido. /// - handler: O manipulador para executar com a data final. Este bloco não tem valor de retorno e aceita o seguinte parâmetro: /// behavior /// O comportamento de privacidade a ser aplicado à complicação especificada. Você pode especificar diferentes comportamentos de privacidade para diferentes famílias de complicações. func getPrivacyBehavior(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationPrivacyBehavior) -> Void) { handler(.showOnLockScreen) } // MARK: - Timeline Population /// Função que recupera a entrada da linha do tempo que você deseja exibir agora. /// - Parameters: /// - complication: Complication ligada ao pedido. /// - handler: O manipulador para executar com a data final. Este bloco não tem valor de retorno e aceita o seguinte parâmetro: /// updateInterval /// O objeto CLKComplicationTimelineEntry a ser exibido agora. func getCurrentTimelineEntry(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimelineEntry?) -> Void) { // Call the handler with the current timeline entry handler(nil) } /// Função que recupera entradas anteriores da linha do tempo para a complicação. /// - Parameters: /// - complication: Complication ligada ao pedido. /// - date: A data final para fornecer entradas passadas. As datas para as entradas da linha do tempo devem ocorrer antes dessa data e estar o mais próximo possível da data. /// - limit: O número máximo de entradas a serem fornecidas. /// - handler: O manipulador para executar com os dados futuros da linha do tempo. Este bloco não tem valor de retorno e aceita o seguinte parâmetro: /// entries /// Uma matriz de objetos CLKComplicationTimelineEntry que representam os dados passados. O número de entradas na matriz deve ser menor ou igual ao valor no parâmetro limit. Se você especificar zero, o ClockKit não tentará estender ainda mais a linha do tempo. func getTimelineEntries(for complication: CLKComplication, before date: Date, limit: Int, withHandler handler: @escaping ([CLKComplicationTimelineEntry]?) -> Void) { // Call the handler with the timeline entries prior to the given date handler(nil) } /// Função que recupera entradas futuras da linha do tempo para a complication. /// - Parameters: /// - complication: Complication ligada ao pedido. /// - date: A data de início para fornecer entradas futuras. As datas para as entradas da linha do tempo devem ocorrer após essa data e estar o mais próximo possível da data. /// - limit: O número máximo de entradas a serem fornecidas. /// - handler: O manipulador para executar com os dados futuros da linha do tempo. Este bloco não tem valor de retorno e aceita o seguinte parâmetro: /// entries /// Uma matriz de objetos CLKComplicationTimelineEntry que representam os dados futuros. O número de entradas na matriz deve ser menor ou igual ao valor no parâmetro limit. Se você especificar zero, o ClockKit não tentará estender ainda mais a linha do tempo. func getTimelineEntries(for complication: CLKComplication, after date: Date, limit: Int, withHandler handler: @escaping ([CLKComplicationTimelineEntry]?) -> Void) { // Call the handler with the timeline entries after to the given date handler(nil) } // MARK: - Placeholder Templates /// Função que obtém um modelo localizável que mostra dados de exemplo para a complicação especificada. /// - Parameters: /// - complication: A complication ligada ao pedido. Use as informações da família de complicações neste objeto para determinar qual conjunto de modelos é válido. Por exemplo, se a família de complicações for CLKComplicationFamily.utilitarianLarge, você instancia a classe CLKComplicationTemplateUtilitarianLargeFlat para o seu modelo. /// - handler: O manipulador para executar com os dados futuros da linha do tempo. Este bloco não tem valor de retorno e aceita o seguinte parâmetro: /// template /// O objeto de modelo que contém seus dados de espaço reservado. Os dados neste modelo são armazenados em cache e exibidos para sua complicação. func getLocalizableSampleTemplate(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTemplate?) -> Void) { // This method will be called once per supported complication, and the results will be cached handler(nil) } }
Java
UTF-8
795
2.25
2
[]
no_license
package bzh.terrevirtuelle.navisu.api.option; /** * NaVisu * * @author tibus * @param <V> * @param <T> * @date 15/02/2014 17:22 */ public abstract class OptionsPanelCtrl<V extends OptionsPanel, T> { protected ModelChangedEvents<T> modelChangedListener; public abstract void load(V view, T model); public abstract void store(V view, T model); public abstract boolean valid(V view); public abstract String getTitle(); public abstract Class<V> getViewType(); public abstract Class<T> getModelType(); public void setOnModelCHangedListener(ModelChangedEvents<T> modelChangedListener) { this.modelChangedListener = modelChangedListener; } protected ModelChangedEvents<T> getModelChangedListener() { return this.modelChangedListener; } }
PHP
UTF-8
813
2.515625
3
[]
no_license
<?php /* Plugin Name: Ordain ᚨ Description: 検索結果を日付降順に変更する簡易なプラグイン。 Version: 0.0.1 Author: アルム=バンド */ /** * ordainAnsuz (ᚨ) : 検索結果を日付降順に変更する */ class ordainAnsuz { /** * __construct : コンストラクタ * */ public function __construct() { add_filter( 'posts_search_orderby', [ $this, 'jera', ] ); } /** * jera (ᛃ) : 日付降順にする * * @return {string} 'post_date desc' : 日付降順を指定する ORCER BY句 の一部 * */ public function jera () { return 'post_date desc'; } } // instantiate $ab_wp_plugin_ordainAnsuz = new ordainAnsuz();
Markdown
UTF-8
4,375
2.734375
3
[ "Apache-2.0" ]
permissive
# Watson Hands On Labs - 📷 Image Analysis The labs cover several [Watson Services][wdc_services] that are available on [IBM Bluemix][bluemix] to build a simple image analysis application. Throughout the workshop, we will navigate through Bluemix, Bluemix Devops Services, Github, and the source code of our application in order to demonstrate how apps can be created quickly and easily using the [IBM Bluemix][bluemix] platform, and the value of [Watson Services][wdc_services] and Cognitive capabilities through APIs. So let’s get started. The first thing to do is to build out the shell of our application in Bluemix. ## Creating a [IBM Bluemix][bluemix] Account 1. Go to [https://bluemix.net/](https://bluemix.net/) 2. Create a Bluemix account if required. 3. Log in with your IBM ID (the ID used to create your Bluemix account) **Note:** The confirmation email from Bluemix mail may take up to 1 hour. ## Running the application locally The application uses [Node.js](http://nodejs.org/) and [npm](https://www.npmjs.com/) so you will have to download and install them as part of the steps below. 1. Install [Node.js](http://nodejs.org/) 2. Install the Bluemix CLI and the CF CLI -> Links 3. Run the following commands to connect to your Bluemix account: `bluemix api https://api.ng.bluemix.net/` `bluemix login` 4. List all the Bluemix services `cf marketplace` 5. From that list, create a Visual Recognition and a Text-to-Speech service: `cf cs watson_vision_combined free visual_recognition_name` `cf cs text_to_speech standard text_to_speech_name` 6. Create new credentials for each of those services, to do so: `cf create-service-key SERVICE_NAME KEY_NAME` 7. Retrieve those new credentials using the following command: `cf service-key SERVICE_NAME KEY_NAME` 7. Edit config.js to add the credentials previously retrieved 8. Go to the project folder in a terminal and run: `npm install` 5. Start the application `node app.js` 7. Go to `http://localhost:3000` ## Add additional functionality to the application: Ability to read signs 1. In app.js, uncomment line 28 `app.post('/recognizetext', app.upload.single('images_file'), vr.recognizeText);` 2. In routes/vr.js, uncomment from line 53 to the end 3. In public/js/ui.js, uncomment from line 143 to line 151 4. In public/index.html, uncomment the second part of the line 47 `OR <a id="capture-button-recognizetext">Recognize Text on an Image</a>` 5. In public/js/ui.js, uncomment from line 194 to line 197 6. Save the different files 7. Quit the process in the terminal (CTRL + C) 8. Restart the application `node app.js` ## Add additional services to the application In this section we'll see how to add the possibility of translating the text recognized to an other language before it's spoken by the Text-to-Speech service 1. Create a language translation service `cf cs language_translation standard language_translation_name` 2. Create new credentials and retrieve them as seen in the first section 3. Edit the config.js file to add them, save the file 4. In app.js, uncomment lines 22 and 32 5. In public/index.html, uncomment from line 40 to 45 6. Create a new file `lt.js` in the `routes` folder and paste in the following: 'use strict'; var watson = require('watson-developer-cloud'); var config = require('../config'); var languageTranslation = watson.language_translator({ version: config.watson.language_translation.version, username: process.env.USERNAME || config.watson.language_translation.username, password: process.env.PASSWORD || config.watson.language_translation.password }); module.exports.translate = function(req, res, next) { var params = { text: req.body.text, model_id: req.body.model, }; languageTranslation.translate(params, function(error, result) { if (error) return next(error); else return res.json(result); }); }; ``` 7. Save 8. Restart the app # Congratulations You have completed the Image Analysis Lab! :bowtie: [bluemix]: https://console.ng.bluemix.net/ [wdc_services]: http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/services-catalog.html [lt_service]: http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/language-translation.html
Java
UTF-8
15,559
1.5625
2
[]
no_license
/******************************************************************************* * Copyright (c) 2012 Curtis Larson (QuackWare). * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html ******************************************************************************/ package com.quackware.crowdsource.ui; import static com.quackware.crowdsource.util.C.D; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.SharedPreferences.Editor; import android.os.AsyncTask; import android.os.Bundle; import android.preference.EditTextPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; import android.preference.PreferenceScreen; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.Preference.OnPreferenceClickListener; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Toast; import com.quackware.crowdsource.MyApplication; import com.quackware.crowdsource.MyDataStore; import com.quackware.crowdsource.R; import com.quackware.crowdsource.ServerUtil; public class CrowdPreference extends PreferenceActivity implements OnPreferenceChangeListener, OnPreferenceClickListener { private static final int CHANGE_PASSWORD_DIALOG = 1; private static final int LOGIN_DIALOG = 2; private static final String TAG = "CrowdPreference"; private static final String SETTINGS_FILE = "SettingsFile"; private static final String ET_USERNAME = "editTextUsername"; private static final String ET_PASSWORD = "editTextPassword"; private static final String ET_PASSWORD2 = "editTextPassword2"; private static final String BUTTON_PREF = "savePrefs"; private MyDataStore _dataStore; private ChangePasswordTask _changePasswordTask; private LoginTask _loginTask; private ServerUtil _su; private boolean _fromCrowdTalk; // TODO When they try to change any account information make them login // first? @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); setEditTextListeners(); setClickListeners(); loadPreferences(); } private void loadPreferences() { _su = ((MyApplication) CrowdPreference.this.getApplication()) .getServerUtil(); _dataStore = (MyDataStore) getLastNonConfigurationInstance(); if (_dataStore != null) { _changePasswordTask = _dataStore.getChangePasswordTask(); _loginTask = _dataStore.getCPLoginTask(); } try { _fromCrowdTalk = getIntent().getExtras() .getBoolean("fromCrowdTalk"); } catch (Exception ex) { _fromCrowdTalk = false; } } private void setClickListeners() { Preference changePasswordPref = (Preference) findPreference("changePassword"); changePasswordPref.setOnPreferenceClickListener(this); PreferenceScreen accountPrefScreen = (PreferenceScreen) findPreference("userAccountPreferenceScreen"); accountPrefScreen.setOnPreferenceClickListener(this); } private void setEditTextListeners() { ((EditTextPreference) findPreference("editTextLocationInterval")) .setOnPreferenceChangeListener(this); ((EditTextPreference) findPreference("editTextLocationInterval")) .setText("10"); } @Override public void onStop() { super.onStop(); // Thread because this actually lags the switch from crowdpreference // back to another activity. // And we don't need to really display a dialog or anything. // We don't want to log out if we are simply editting the settings from // the tab view. if (!_fromCrowdTalk) { new Thread(new Runnable() { @Override public void run() { if (isFinishing()) { if (_su.isAuthenticated()) { _su.logout(); } } } }).start(); } } @Override public Object onRetainNonConfigurationInstance() { if (_dataStore == null) { _dataStore = new MyDataStore(); } if (_changePasswordTask != null) { _changePasswordTask.detatch(); } if (_loginTask != null) { _loginTask.detatch(); } _dataStore.setChangePasswordTask(_changePasswordTask); _dataStore.setCPLoginTask(_loginTask); return _dataStore; } protected Dialog onCreateDialog(int id) { if (D) Log.i(TAG, "onCreateDialog called with id: " + id); switch (id) { case LOGIN_DIALOG: LayoutInflater factory = LayoutInflater.from(this); final View userNamePasswordView = factory.inflate(R.layout.login, null); // We need to disable the checkbox this time since they are just // logging in to view preferences. CheckBox cb = (CheckBox) userNamePasswordView .findViewById(R.id.autoLoginCB); cb.setVisibility(View.GONE); return new AlertDialog.Builder(CrowdPreference.this).setTitle( "Login").setView(userNamePasswordView).setCancelable(false) .setPositiveButton("Login", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { EditText te = (EditText) userNamePasswordView .findViewById(R.id.passwordET); String password = te.getText().toString(); te.setText(""); te = (EditText) userNamePasswordView .findViewById(R.id.usernameET); String username = te.getText().toString(); te.setText(""); te.requestFocus(); if (username.equals("") || password.equals("")) { // Blank data, prompt them. Toast .makeText( getApplicationContext(), getString(R.string.ERROR_BADFIELDS), Toast.LENGTH_SHORT) .show(); if (D) Log .w(TAG, "User provided a blank username or password in login"); PreferenceScreen ps = (PreferenceScreen) CrowdPreference.this .findPreference("userAccountPreferenceScreen"); ps.getDialog().dismiss(); } else { if (D) Log.i(TAG, "Starting login task"); if (_loginTask == null) { _loginTask = new LoginTask( CrowdPreference.this); _loginTask.execute(username, password); } else { _loginTask .attach(CrowdPreference.this); } } } }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // We have to go back! PreferenceScreen ps = (PreferenceScreen) CrowdPreference.this .findPreference("userAccountPreferenceScreen"); ps.getDialog().dismiss(); // Text stuff. ((EditText) userNamePasswordView .findViewById(R.id.usernameET)) .setText(""); ((EditText) userNamePasswordView .findViewById(R.id.usernameET)) .requestFocus(); ((EditText) userNamePasswordView .findViewById(R.id.passwordET)) .setText(""); } }).create(); case CHANGE_PASSWORD_DIALOG: LayoutInflater _factory = LayoutInflater.from(this); final View createAccountView = _factory.inflate( R.layout.changepassword, null); return new AlertDialog.Builder(CrowdPreference.this).setTitle( "Change Password").setView(createAccountView) .setPositiveButton("Save", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { EditText te = (EditText) createAccountView .findViewById(R.id.CFoldpasswordET); String oldPassword = te.getText() .toString(); te.requestFocus(); te.setText(""); te = (EditText) createAccountView .findViewById(R.id.CFnewpasswordET); String newPassword = te.getText() .toString(); te.setText(""); if ((!oldPassword.equals("")) && (!newPassword.equals(""))) { if (D) Log .i(TAG, "Starting change password spinner"); if (_changePasswordTask == null) { _changePasswordTask = new ChangePasswordTask( CrowdPreference.this); _changePasswordTask.execute( oldPassword, newPassword); } else { _changePasswordTask .attach(CrowdPreference.this); } } else { // User did not enter the same password // twice, take appropriate action. // Or they entered blank passwords. Toast .makeText( getApplicationContext(), getString(R.string.ERROR_BADFIELDS), Toast.LENGTH_LONG) .show(); } } }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ((EditText) createAccountView .findViewById(R.id.CFoldpasswordET)) .requestFocus(); ((EditText) createAccountView .findViewById(R.id.CFoldpasswordET)) .setText(""); ((EditText) createAccountView .findViewById(R.id.CFnewpasswordET)) .setText(""); } }).create(); default: return super.onCreateDialog(id); } } @Override public boolean onPreferenceClick(Preference preference) { if (preference.getKey().equals("changePassword")) { showDialog(CHANGE_PASSWORD_DIALOG); } else if (preference.getKey().equals("userAccountPreferenceScreen")) { if (!_su.isAuthenticated()) { showDialog(LOGIN_DIALOG); } else if (_su.isAnonymous()) { Toast .makeText( getApplicationContext(), getString(R.string.ERROR_ANON_EDIT), Toast.LENGTH_LONG).show(); } } return true; } public class ChangePasswordTask extends AsyncTask<String, Void, Boolean> { private CrowdPreference activity; private ProgressDialog _changePasswordSpinner; public ChangePasswordTask(CrowdPreference cp) { attach(cp); } @Override protected void onPreExecute() { _changePasswordSpinner = new ProgressDialog(CrowdPreference.this); _changePasswordSpinner .setProgressStyle(ProgressDialog.STYLE_SPINNER); _changePasswordSpinner .setMessage(getString(R.string.serverConnect)); _changePasswordSpinner.setCancelable(false); _changePasswordSpinner.show(); } @Override protected Boolean doInBackground(String... args) { // [0] = username // [1] = oldPassword // [2] = newPassword return ((MyApplication) CrowdPreference.this.getApplication()) .getServerUtil().changePassword(args[0], args[1]); } protected void onPostExecute(Boolean result) { if (D) Log.i(TAG, "Attempting to dismiss change password spinner"); if (_changePasswordSpinner != null) { _changePasswordSpinner.dismiss(); _changePasswordSpinner = null; } if (!result) { Toast.makeText(getApplicationContext(), getString(R.string.ERROR_CHANGE_PASSWORD), Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), getString(R.string.SUCCESSFULL_CHANGE_PASSWORD), Toast.LENGTH_SHORT) .show(); } } public void attach(CrowdPreference cp) { activity = cp; } public void detatch() { activity = null; } } @Override public boolean onPreferenceChange(Preference preference, Object newValue) { String key = preference.getKey(); if (key.equals("editTextLocationInterval")) { try { Integer.parseInt(newValue.toString()); } catch (Exception ex) { Toast.makeText(getApplicationContext(), getString(R.string.ERROR_INT), Toast.LENGTH_SHORT) .show(); return false; } } return true; /* * Preference buttonPref = (Preference)findPreference(BUTTON_PREF); * String key = preference.getKey(); String usernameText = * ((EditTextPreference)findPreference(ET_USERNAME)).getText(); String * passwordText = * ((EditTextPreference)findPreference(ET_PASSWORD)).getText(); String * password2Text = * ((EditTextPreference)findPreference(ET_PASSWORD2)).getText(); //Check * to see if they were editing either of the passwords. * if(key.equals(ET_PASSWORD) || key.equals(ET_PASSWORD2)) { * * } * * //Enable the button only after everything has been filled in. * if(key.equals(ET_USERNAME) && !newValue.equals("")) { * if(!passwordText.equals("") && !password2Text.equals("")) { * buttonPref.setEnabled(true); } } else if(key.equals(ET_PASSWORD) && * !newValue.equals("")) { if(!usernameText.equals("") && * !password2Text.equals("")) { buttonPref.setEnabled(true); } } else * if(key.equals(ET_PASSWORD2) && !newValue.equals("")) { * if(!passwordText.equals("") && !usernameText.equals("")) { * buttonPref.setEnabled(true); } } */ } public class LoginTask extends AsyncTask<String, Integer, Boolean> { private ProgressDialog _loginSpinner; private CrowdPreference activity = null; private String _username; private String _password; public LoginTask(CrowdPreference crowdPreference) { attach(crowdPreference); } public void attach(CrowdPreference cs) { activity = cs; } public void detatch() { activity = null; } @Override protected Boolean doInBackground(String... arg) { _username = arg[0]; _password = arg[1]; return _su.login(arg[0], arg[1]); } protected void onPostExecute(Boolean result) { if (D) Log.i(TAG, "Attempting to dismiss login spinner"); if (_loginSpinner != null) { _loginSpinner.dismiss(); _loginSpinner = null; } if (result) { // We need to save the username and password for later. Editor edit = PreferenceManager.getDefaultSharedPreferences( getApplicationContext()).edit(); edit.putString("editTextUsername", _username); edit.putString("editTextPassword", _password); edit.commit(); } else { PreferenceScreen ps = (PreferenceScreen) CrowdPreference.this .findPreference("userAccountPreferenceScreen"); ps.getDialog().dismiss(); Toast.makeText(getApplicationContext(), getString(R.string.ERROR_LOGIN), Toast.LENGTH_SHORT) .show(); } activity.removeLoginTask(); } @Override protected void onPreExecute() { _loginSpinner = new ProgressDialog(CrowdPreference.this); _loginSpinner.setProgressStyle(ProgressDialog.STYLE_SPINNER); _loginSpinner.setMessage(getString(R.string.loggingIn)); _loginSpinner.setCancelable(false); _loginSpinner.show(); } } private void removeLoginTask() { _loginTask = null; } }
JavaScript
UTF-8
12,166
2.546875
3
[]
no_license
import React, { Component } from 'react'; import Board from '../board/board.js'; import Chat from '../chat/chat.js'; import { easyBot, mediumBot, hardBot } from '../../bots/bots.js'; import { checkWin } from '../../utils/gameLogic.js'; import './game.css'; import SocketContext from '../socket-context.js' import Dropdown from 'react-dropdown'; import 'react-dropdown/style.css'; import InfoPanel from '../infoPanel/infoPanel.js'; class Game extends Component { constructor(props) { super(props); this.onDropdownSelect = this.onDropdownSelect.bind(this); this.w = parseInt(this.props.width); this.h = parseInt(this.props.height); this.threshold = 5; this.bots = [ { label: 'Easy', bot: easyBot, }, { label: 'Medium', bot: mediumBot, }, { label: 'Hard', bot: hardBot, }, ]; this.state = { squares: Array(this.w * this.h).fill(null), stepNumber: 0, winner: null, highlight: [], moves: [], replayIndex: null, playerXScore: 0, playerOScore: 0, selectedBotIndex: 0, clientID: null, // Variables for multiplayer roomName: null, readyToPlay: false, clients: [], } this.playerOnePiece = "X"; this.playerTwoPiece = "O"; } _handleKeyDown = (event) => { if (this.state.winner !== null) { switch(event.keyCode) { case 37: // left arrow this.goBack(); break; case 39: // right arrow this.goForward(); break; default: break; } } } componentDidMount() { window.addEventListener('popstate', (event) => { this.setState({ roomName: null, readyToPlay: false, }); }); var roomName = window.location.pathname.substring(1); if (roomName !== "") { this.props.socket.emit('joinRoom', roomName); // An attempt was made to join a room this.setState({ room: true, playerXScore: 0, playerOScore: 0, roomName: roomName, }); } this.props.socket.on('welcome', function(clientID) { this.setState({ clientID: clientID, }); }.bind(this)); // For replay document.addEventListener("keydown", this._handleKeyDown); this.props.socket.on('declareMove', function(msg){ console.log('client declareMove: ' + msg); console.log(this); this.handleClick(msg['index'], false); }.bind(this)); this.props.socket.on('roomCreated', function(data) { window.history.pushState('room', 'Room ' + data['roomName'], '/' + data['roomName']); // reset the scores this.setState({ playerXScore: 0, playerOScore: 0, roomName: data['roomName'], clients: data['clients'], }); this.resetGame(); }.bind(this)); this.props.socket.on('roomDenied', function(roomName) { console.log('roomDenied %s', roomName); window.history.pushState('room', 'Lobby', '/'); this.setState({ roomName: null, readyToPlay: false, }); }.bind(this)); this.props.socket.on('roomUpdated', function(data) { console.log("[Client] Someone joined this room"); console.log(data['clients']); if(data['clients'].length >= 2) { // Two clients are in the room, somehow signal that a game can be started and who's move is it first this.setState({ clients: data['clients'], roomName: data['roomName'], }); } else { this.setState({ clients: data['clients'], roomName: data['roomName'], }); } }.bind(this)); this.props.socket.on('gameStarted', function(roomName) { this.setState({ readyToPlay: true, }); this.resetGame(); }.bind(this)); } resetGame() { // Reset the state of the game this.setState({ squares: Array(this.w * this.h).fill(null), stepNumber: 0, winner: null, highlight: [], moves: [], replayIndex: null, }); } createGame() { this.props.socket.emit('createGame'); } goBack() { if (this.state.winner !== null && this.state.replayIndex >= 0) { const nextSquares = this.state.squares.slice(0); nextSquares[this.state.moves[this.state.replayIndex]] = null; this.setState({ squares: nextSquares, replayIndex: this.state.replayIndex - 1, highlight: [], }); } } goForward() { if (this.state.winner !== null && this.state.replayIndex < (this.state.moves.length - 1)) { const nextSquares = this.state.squares.slice(0); let move = ((this.state.replayIndex + 1) % 2 === 0) ? this.playerOnePiece : this.playerTwoPiece; nextSquares[this.state.moves[this.state.replayIndex + 1]] = move; var winningMoves = []; if (this.state.replayIndex + 1 === this.state.moves.length - 1) { // Probably could make this logic better winningMoves = checkWin(nextSquares.slice(0), this.w, this.h, this.threshold)["squares"]; } this.setState({ squares: nextSquares, replayIndex: this.state.replayIndex + 1, highlight: winningMoves }); } } handleWinner(squares, nextMoves) { if (this.state.winner == null) { var win = checkWin(squares.slice(0), this.w, this.h, this.threshold); if (win !== null) { if (win['player'] === this.playerOnePiece) { this.setState({ playerXScore: this.state.playerXScore + 1, }); } else { this.setState({ playerOScore: this.state.playerOScore + 1, }); } this.setState({ winner: win['player'], highlight: win['squares'], replayIndex: nextMoves.length - 1, readyToPlay: false, }); return true; } else { return false; } } } onDropdownSelect(test) { this.setState({ selectedBotIndex: test['value'], }); } handleClick(i, playerMoved) { if (this.state.winner !== null || (this.state.roomName !== null && !this.state.readyToPlay)) { return; } var playerMove = this.state.moves.length % 2; if (this.state.roomName !== null && this.state.clientID !== this.state.clients[playerMove] && playerMoved) { // It isn't your move return; } if (this.state.squares[i] === null && this.state.roomName !== null) { this.props.socket.emit('handleMove', { index: i, roomName: this.state.roomName }); } var move = this.playerOnePiece; var nextMove = this.playerTwoPiece; if (playerMove === 1) { move = this.playerTwoPiece; nextMove = this.playerOnePiece; } const nextSquares = this.state.squares.slice(0); let nextMoves = this.state.moves.slice(0); if (nextSquares[i] === null && this.state.winner === null) { nextSquares[i] = move; nextMoves = nextMoves.concat([i]); this.setState({ squares: nextSquares, stepNumber: this.state.stepNumber + 1, moves: nextMoves, }); // console.log("[Game] handleClick " + i); if (this.handleWinner(nextSquares, nextMoves)) { return; } // Trigger the bot... if (this.state.roomName === null) { var botIndex = this.state.selectedBotIndex; var botMove = this.bots[botIndex]['bot'].evaluate(nextSquares, this.w, this.h, nextMove); console.log("Bot Move: " + botMove + " " + botIndex); nextSquares[botMove] = nextMove; nextMoves = nextMoves.concat([botMove]); this.setState({ squares: nextSquares, stepNumber: this.state.stepNumber + 1, moves: nextMoves, }); // console.log("[Game] handleClick " + i); if (this.handleWinner(nextSquares, nextMoves)) { return; } } } } startGame() { if (this.state.clients.length >= 2) { this.setState({ readyToPlay: true, }); this.resetGame(); this.props.socket.emit('startGame', this.state.roomName); } } render() { // TODO: Move Panel out to its own component let dropdownOptions = [] for (let i = 0; i < this.bots.length; i++) { let option = { label: this.bots[i]['label'], value: i, } dropdownOptions.push(option) } var playerMove = this.state.moves.length % 2; if (this.state.roomName === null) { playerMove = -1; } var playerXIcon = ""; if (this.state.roomName !== null && this.state.clients[0] === this.state.clientID) { playerXIcon = "currentPlayer"; } else if (this.state.roomName !== null) { playerXIcon = "otherPlayer"; } var playerOIcon = ""; if (this.state.roomName !== null && this.state.clients[1] === this.state.clientID) { playerOIcon = "currentPlayer"; } else if (this.state.roomName !== null && this.state.clients.length > 1) { playerOIcon = "otherPlayer"; } var lastMove = null; if (this.state.moves.length > 0 && this.state.roomName !== null && (this.state.replayIndex === null)) { lastMove = this.state.moves[this.state.moves.length - 1]; } return ( <div className="gameContainer"> <div className="boardContainer"> <Board squares={this.state.squares} highlight={this.state.highlight} // Highlighted squares on a win height={this.h} width={this.w} onClick={i => this.handleClick(i, true)} lastMove={lastMove} /> </div> <div className="gamePanel"> <InfoPanel boldPlayerX={(playerMove === 0 && this.state.readyToPlay)} boldPlayerO={(playerMove === 1 && this.state.readyToPlay)} playerXScore={this.state.playerXScore} playerOScore={this.state.playerOScore} playerXIcon={playerXIcon} playerOIcon={playerOIcon} /> <div className="controlPanel"> <button className={(this.state.roomName !== null && !this.state.readyToPlay) ? "start coolButton" : "start coolButton hidden"} onClick={() => this.startGame()} disabled={this.state.clients.length < 2}> Start Game </button> <Chat roomName={this.state.roomName} expand={this.state.readyToPlay} replay={this.state.winner !== null} /> <button className={(this.state.roomName === null) ? "create coolButton" : "create coolButton hidden"} onClick={() => this.createGame()}> Create Room </button> <button className={(this.state.roomName === null) ? "reset coolButton" : "reset coolButton hidden"} onClick={() => this.resetGame()}> Reset Game </button> <Dropdown className={(this.state.roomName === null) ? "dropdown" : "dropdown hidden"} options={dropdownOptions} onChange={this.onDropdownSelect} value={dropdownOptions[this.state.selectedBotIndex]['label']} placeholder="Select an option" disabled={this.state.moves.length > 0} /> <div className={(this.state.winner !== null) ? "replay" : "replay hidden"}> <button className="back moveButton" onClick={()=> this.goBack()}> <i className="fas fa-chevron-left"></i> </button> <button className="forward moveButton" onClick={()=> this.goForward()}> <i className="fas fa-chevron-right"></i> </button> </div> </div> </div> </div> ); } } const GameSocket = props => ( <SocketContext.Consumer> {socket => <Game {...props} socket={socket} />} </SocketContext.Consumer> ) export default GameSocket;
Java
UTF-8
843
1.625
2
[]
no_license
package com.google.android.gms.internal.ads; import android.text.TextUtils; import androidx.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; @ParametersAreNonnullByDefault /* compiled from: com.google.android.gms:play-services-ads@@19.5.0 */ public final class zzabk { public static void zza(zzabi zzabi, @Nullable zzabj zzabj) { if (zzabj.mo15171a() == null) { throw new IllegalArgumentException("Context can't be null. Please set up context in CsiConfiguration."); } else if (!TextUtils.isEmpty(zzabj.mo15172b())) { zzabi.zza(zzabj.mo15171a(), zzabj.mo15172b(), zzabj.mo15173c(), zzabj.mo15174d()); } else { throw new IllegalArgumentException("AfmaVersion can't be null or empty. Please set up afmaVersion in CsiConfiguration."); } } }
TypeScript
UTF-8
265
3.28125
3
[]
no_license
export class Person { public name: string; public age: number | null; public comment: string; constructor(name: string, age: number | null, comment: string) { this.name = name; this.age = age; this.comment = comment; } }
C#
WINDOWS-1252
1,788
2.90625
3
[]
no_license
//============================================================== // Forex Strategy Builder // Copyright Miroslav Popov. All rights reserved. //============================================================== // THIS CODE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE. //============================================================== using System; using ForexStrategyBuilder.Infrastructure.Interfaces; namespace ForexStrategyBuilder.Infrastructure.Entities { public class InstrumentProperties : IInstrumentProperties { public InstrumentProperties(string symbol) { Symbol = symbol; Digits = symbol.Contains("JPY") ? 3 : 5; BaseFileName = symbol; IsFiveDigits = Digits == 3 || Digits == 5; Point = 1/Math.Pow(10, Digits); Pip = IsFiveDigits ? 10*Point : Point; } public string Symbol { get; set; } public string BaseFileName { get; set; } public int Digits { get; set; } public double Point { get; set; } public double Pip { get; set; } public bool IsFiveDigits { get; set; } /// <summary> /// Returns a clone of the class. /// </summary> public InstrumentProperties GetClone() { return new InstrumentProperties(Symbol) { Symbol = Symbol, Digits = Digits, Point = Point, Pip = Pip, IsFiveDigits = IsFiveDigits, BaseFileName = BaseFileName, }; } } }
Java
UTF-8
3,297
1.539063
2
[]
no_license
package p004o; import android.graphics.LightingColorFilter; import android.support.p000v4.view.ViewCompat; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.libroserver.apk.R; /* renamed from: o.hf */ final class C0400hf extends BaseAdapter { /* renamed from: ˮ͈ */ OnClickListener f1133 = new C0401hg(this); /* renamed from: 櫯 */ OnClickListener f1134; /* renamed from: 鷭 */ C0605oe[] f1135; C0400hf(C0605oe[] oeVarArr, OnClickListener onClickListener) { this.f1135 = oeVarArr; this.f1134 = onClickListener; } public final int getCount() { return this.f1135.length; } public final Object getItem(int i) { return null; } public final long getItemId(int i) { return 0; } /* access modifiers changed from: 0000 */ /* renamed from: 鷭 */ public final int mo3774(RelativeLayout relativeLayout) { for (int i = 0; i < this.f1135.length; i++) { if (relativeLayout == this.f1135[i].f2971) { return i; } } return -1; } public final View getView(int i, View view, ViewGroup viewGroup) { RelativeLayout relativeLayout = (RelativeLayout) ((LayoutInflater) viewGroup.getContext().getSystemService("layout_inflater")).inflate(R.layout.skills_entry, null); this.f1135[i].f2971 = relativeLayout; C0605oe oeVar = this.f1135[i]; ImageView imageView = (ImageView) oeVar.f2971.findViewById(R.id.imageView1); TextView textView = (TextView) oeVar.f2971.findViewById(R.id.textView2); TextView textView2 = (TextView) oeVar.f2971.findViewById(R.id.textView3); Button button = (Button) oeVar.f2971.findViewById(R.id.button1); ((TextView) oeVar.f2971.findViewById(R.id.textView1)).setText(oeVar.f2973.f1071); if (!oeVar.f2974.f1049 || !oeVar.f2972) { button.setVisibility(4); } else { button.setVisibility(0); } button.setOnClickListener(this.f1133); if (oeVar.f2974.f1051 > 0) { textView.setText("Lv : " + oeVar.f2974.f1051); oeVar.f2971.setBackgroundColor(-13421773); imageView.setColorFilter(new LightingColorFilter(-1, 0)); } else { textView.setText("Not learned"); oeVar.f2971.setBackgroundColor(ViewCompat.MEASURED_STATE_MASK); imageView.setColorFilter(new LightingColorFilter(-4473925, 0)); } C0453ix ixVar = C1014.f6147.f51; ixVar.mo3871(imageView, C1014.f6158.f674.mo3609(C1014.f6158.f674.f609.mo3752(oeVar.f2974.f1053).f1073), ixVar.f1456); if (oeVar.f2974.f1051 > 0) { if (oeVar.f2974.f1052 == 0) { textView2.setText("Passive"); } else { textView2.setText("SP : " + oeVar.f2974.f1050); } } else { textView2.setText(null); } oeVar.f2971.setOnClickListener(this.f1134); return relativeLayout; } }
Python
UTF-8
3,594
2.71875
3
[]
no_license
import requests from io import BytesIO from PIL import Image, ImageDraw import cognitive_face as CF import urllib import urllib.request as ur import cv2 import numpy as np import matplotlib.pyplot as plt KEY = '6a294681f0f640f3a8b60b1c7de8ea85' # Replace with a valid subscription key (keeping the quotes in place). CF.Key.set(KEY) # If you need to, you can change your base API url with: # CF.BaseUrl.set('https://westus.api.cognitive.microsoft.com/face/v1.0/detect') BASE_URL = 'https://eastus.api.cognitive.microsoft.com/face/v1.0/' # Replace with your regional Base URL CF.BaseUrl.set(BASE_URL) # You can use this example JPG or replace the URL below with your own URL to a JPEG image. img_url = 'https://raw.githubusercontent.com/malhotraguy/traspod/master/1.jpg' result = CF.face.detect(img_url) print(result) #Convert width height to a point in a rectangle def getRectangle(faceDictionary): rect = faceDictionary['faceRectangle'] left = rect['left'] top = rect['top'] bottom = left + rect['height'] right = top + rect['width'] return ((left, top), (bottom, right)) #Download the image from the url response = requests.get(img_url) img = Image.open(BytesIO(response.content)) #For each face returned use the face rectangle and draw a red box. draw = ImageDraw.Draw(img) for face in result: draw.rectangle(getRectangle(face), outline='red') #Display the image in the users default image browser. img.show() def url_to_image(url): """ a helper function that downloads the image, converts it to a NumPy array, and then reads it into OpenCV format """ resp = ur.urlopen(url) image = np.asarray(bytearray(resp.read()), dtype="uint8") image = cv2.imdecode(image, cv2.IMREAD_COLOR) # return the image return image img = url_to_image(img_url) plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) plt.axis('off') height = result[0]['faceRectangle']['height'] left = result[0]['faceRectangle']['left'] top = result[0]['faceRectangle']['top'] width = result[0]['faceRectangle']['width'] plt.imshow(cv2.cvtColor(img[top:top+height, left:left+width], cv2.COLOR_BGR2RGB)) plt.axis('off') url1 = 'https://raw.githubusercontent.com/malhotraguy/traspod/master/10.jpg' url2 = 'https://raw.githubusercontent.com/malhotraguy/traspod/master/5.jpg' url3 = 'https://raw.githubusercontent.com/malhotraguy/traspod/master/4.jpg' url4 = 'https://raw.githubusercontent.com/malhotraguy/traspod/master/3.jpg' urls = [url1, url2, url3, url4] for url in urls: plt.imshow(cv2.cvtColor(url_to_image(url), cv2.COLOR_BGR2RGB)) plt.axis('off') plt.show() results = [] for url in urls: r = CF.face.detect(url) results += r, all_faceid = [f['faceId'] for image in results for f in image] test_url = 'https://raw.githubusercontent.com/malhotraguy/traspod/master/2.jpg' plt.imshow(cv2.cvtColor(url_to_image(test_url), cv2.COLOR_BGR2RGB)) test_result = CF.face.detect(test_url) test_faceId = test_result[0]['faceId'] for f in all_faceid: r = CF.face.verify(f, test_faceId) print(r) identical_face_id = [f for f in all_faceid if CF.face.verify(f, test_faceId)['isIdentical'] == True] for i in range(len(results)): for face in results[i]: if face['faceId'] in identical_face_id: height = face['faceRectangle']['height'] left = face['faceRectangle']['left'] top = face['faceRectangle']['top'] width = face['faceRectangle']['width'] plt.imshow(cv2.cvtColor(url_to_image(urls[i])[top:top+height, left:left+width], cv2.COLOR_BGR2RGB)) plt.axis('off') plt.show()
JavaScript
UTF-8
916
2.90625
3
[]
no_license
// 回调 // 事件监听 // promise // yield function* // async await import path from 'path' import events from 'events' import util from '../../common/utils/index.js' const Async = Object.create(null) // #事件监听 Async.eventDemo = () => { const obj = new events.EventEmitter() obj.addListener("look", function(){ console.log("你愁啥") }) obj.emit("look") } // #Promise Async.promiseDemo = () => { util.readFile(path.resolve(__dirname + "/a.txt")).then(function(success){ console.log("successa:") console.log(success) }) util.readFile(path.resolve(__dirname + "/b.txt")).then(function(success){ console.log("successb:") console.log(success) }) } // #yield function* ES7 Async.yieldFn = function* (){ const fa = yield util.readFile(path.resolve(__dirname + "/a.txt")) const fb = yield util.readFile(path.resolve(__dirname + "/b.txt")) } Async.d export default Async
JavaScript
UTF-8
2,673
2.953125
3
[]
no_license
/* global fetch, WebSocket, location */ (() => { const messages = document.querySelector('#messages') const msgBox = document.querySelector('.msgBox') const elStatus = document.querySelector('#status') const elTyping = document.querySelector('#typing') const inputContainer = document.querySelector('#inputContainer') const wsButton = document.querySelector('#wsButton') const wsInput = document.querySelector('#wsInput') let ws let typingTimeout const receiveMessage = message => { elTyping.innerHTML = '' const div = document.createElement('div') div.classList.add('message') div.classList.add('other') div.innerHTML = `<span>${message.date}</span>${message.text}` messages.appendChild(div) msgBox.scrollTop = msgBox.scrollHeight } const typingMessage = () => { elTyping.innerHTML = 'User is typing...' if (typingTimeout) { clearTimeout(typingTimeout) } typingTimeout = setTimeout(() => { elTyping.innerHTML = '' }, 1500) } const messageTypeMap = { receive: receiveMessage, typing: typingMessage, } const init = () => { if (ws) { ws.onerror = ws.onopen = ws.onclose = null ws.close() } ws = new WebSocket(`ws://${location.host}`) ws.onerror = () => showStatus('Error') ws.onopen = () => showStatus('Connected') ws.onclose = () => showStatus('Session Disconnected') ws.onmessage = event => { const res = JSON.parse(event.data) // const { type, text } = res console.log(res.type, res.text) messageTypeMap[res.type](res) } wsInput.focus() } const fmt = message => { const { type, text } = message const msg = { type, text, date: new Date().toLocaleTimeString(), } return msg } const showStatus = status => { elStatus.innerHTML = status } wsInput.oninput = ev => { const text = wsInput.value console.log(text) try { const data = fmt({ text, type: 'typing' }) ws.send(JSON.stringify(data)) } catch(e) { console.log(e) } } inputContainer.onsubmit = ev => { ev.preventDefault() const text = wsInput.value wsInput.value = '' try { const data = fmt({ text, type: 'receive' }) ws.send(JSON.stringify(data)) const div = document.createElement('div') div.classList.add('message') div.classList.add('self') div.innerHTML = `<span>${data.date}</span>${text}` messages.appendChild(div) msgBox.scrollTop = msgBox.scrollHeight } catch(e) { console.log(e) } } window.addEventListener('beforeunload', () => ws.close()) init() })()
Markdown
UTF-8
1,028
2.53125
3
[ "BSD-2-Clause" ]
permissive
# NoBrew Powerline install ## Steps ### Get this package to your computer Get the Mac native development toaols necessary for the rest to work: ```xcode-select --install ``` Press "install" on the dialog box. See more details [here](http://osxdaily.com/2014/02/12/install-command-line-tools-mac-os-x/) ### Fonts Install on your machine the fonts. Options (following [this great resource](https://gist.github.com/kevin-smets/8568070)): * [SourceCodePro for Powerline](https://github.com/powerline/fonts/blob/master/SourceCodePro/Source%20Code%20Pro%20for%20Powerline.otf) * [SourceCodePro Awesome](https://github.com/Falkor/dotfiles/blob/master/fonts/SourceCodePro%2BPowerline%2BAwesome%2BRegular.ttf) * [Dozens of additional fonts](https://github.com/powerline/fonts) ### Get the installation script Clone/download the `powerline-mac-no-brew` repository from [here](https://github.com/uri-yanover/powerline-mac-no-brew) ### Run the installation script ``` bash powerline-mac-no-brew/install_powerline.sh ``` ### Enjoy!
Java
UTF-8
5,762
2.53125
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 preguntasrepuestas; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import javax.swing.ListModel; /** * * @author cmsanchez */ public class ManejadorArchivos { ArrayList<String> preguntas; ArrayList<String> repuestas; String usuario = System.getProperty("user.name"); String carpeta = "C:\\Users\\"+usuario+"\\Documents\\PreguntasRepuestas\\"; int opcion = 0; public void CrearCarpeta() { File car = new File(carpeta); if(!car.exists()) { car.mkdir(); } } public boolean existenPregunta() { preguntas = Preguntas(); return preguntas.isEmpty(); } public void AgregarPregunta(ListModel Preguntas) { try { CrearCarpeta(); File archivo = new File(carpeta+"Preguntas.txt"); BufferedWriter bw; bw = new BufferedWriter(new FileWriter(archivo)); for(int j = 0; j < Preguntas.getSize();j++) { Object pregunta = Preguntas.getElementAt(j); bw.write((String)pregunta); bw.newLine(); } bw.close(); }catch(Exception ex) { } } public void AgregarRepuesta(ListModel repuestas) { try { CrearCarpeta(); File archivo = new File(carpeta+"Repuestas.txt"); if(!archivo.exists()) { archivo.createNewFile(); } BufferedWriter bw; bw = new BufferedWriter(new FileWriter(archivo)); for(int j = 0; j < repuestas.getSize();j++) { Object repuesta = repuestas.getElementAt(j); bw.write((String)repuesta); bw.newLine(); } bw.close(); }catch(Exception ex) { } } public ArrayList<String> Preguntas() { try { CrearCarpeta(); File archivo = new File(carpeta+"Preguntas.txt"); if(!archivo.exists()) { archivo.createNewFile(); } BufferedReader br; br = new BufferedReader(new FileReader(archivo)); String linea; preguntas = new ArrayList<String>(); int i = 1; while((linea = br.readLine())!= null) { preguntas.add(linea); i++; } br.close(); return preguntas; }catch(Exception ex) { } return preguntas; } public ArrayList<String> Repuestas() { try { CrearCarpeta(); File archivo = new File(carpeta+"Repuestas.txt"); if(!archivo.exists()) { archivo.createNewFile(); } BufferedReader br; br = new BufferedReader(new FileReader(archivo)); String linea; repuestas = new ArrayList<String>(); int i = 1; while((linea = br.readLine())!= null) { repuestas.add(linea); i++; } br.close(); return repuestas; }catch(Exception ex) { } return repuestas; } public void AgregarConfiguracion(String Configuracion) { try { CrearCarpeta(); File archivo = new File(carpeta+"Configuracion.txt"); if(!archivo.exists()) { archivo.createNewFile(); } BufferedWriter bw; bw = new BufferedWriter(new FileWriter(archivo)); bw.write(Configuracion); bw.newLine(); bw.close(); }catch(Exception ex) { } } public String Configuracion() { String line = "0,0"; try { CrearCarpeta(); File archivo = new File(carpeta+"Configuracion.txt"); if(!archivo.exists()) { archivo.createNewFile(); AgregarConfiguracion("0,0"); } BufferedReader br; br = new BufferedReader(new FileReader(archivo)); line = br.readLine(); br.close(); return line; }catch(Exception ex) { } return line; } }
C++
UTF-8
3,981
3.5
4
[]
no_license
/* \author Aaron Brown */ // Quiz on implementing kd tree #ifndef kdtree3D_h #define kdtree3D_h #include <iostream> #include <string> #include <vector> // Structure to represent node of kd tree template<typename PointT> struct PtNode { PointT point; int id; PtNode<PointT>* left; PtNode<PointT>* right; // func to create a new point node PtNode<PointT>(PointT arr, int setId) : point(arr), id(setId), left(NULL), right(NULL) {} }; template <typename PointT> struct KdTree { PtNode<PointT>* root; KdTree() : root(NULL) {} // 1. build tree - double pointer method void insertHelper1(PtNode<PointT>** node, int depth, PointT point, int id) { if (*node == NULL) // dereference the double pointer to see node { *node = new PtNode<PointT>(point, id); // assign new members } else { // cd either is 0,1 or 3, nums tells if compairing x, y or z values uint cd = depth % 3; if ((cd == 0 && point.x < (*node)->point.x) || (cd == 1 && point.y < (*node)->point.y) || (cd == 2 && point.z < (*node)->point.z)) insertHelper1(&((*node)->left), depth+1, point, id); else insertHelper1(&((*node)->right), depth+1, point, id); } } // 2. build tree - pointer reference method void insertHelper2(PtNode<PointT> *&node, int depth, PointT point, int id) { // node inside recursion is an alias of the node outside recursion. // So if we change any of these two to hold some other address, the other pointer will also change. if (node == NULL) { node = new PtNode<PointT>(point, id); // assign new members } else { // cd either is 0,1 or 3, nums tells if compairing x, y or z values uint cd = depth % 3; if ((cd == 0 && point.x < node->point.x) || (cd == 1 && point.y < node->point.y) || (cd == 2 && point.z < node->point.z)) insertHelper2(node->left, depth+1, point, id); else insertHelper2(node->right, depth+1, point, id); } } void insert(PointT point, int id) { // TODO: Fill in this function to insert a new point into the tree // the function should create a new node and place correctly with in the root // insertHelper1(&root, 0, point, id); // pass in the memo address of root (a pointer to root) insertHelper2(root, 0, point, id);// pass in pointer reference } void searchHelper(PointT target, PtNode<PointT> * node, int depth, float distanceTol, std::vector<int> &ids) { if (node == NULL) return; // check IF within the cube if ((node->point.x >= target.x - distanceTol) && (node->point.x <= target.x + distanceTol) && (node->point.y >= target.y - distanceTol) && (node->point.y <= target.y + distanceTol) && (node->point.z >= target.z - distanceTol) && (node->point.z <= target.z + distanceTol)) { // check IF within the sphere float dis = (node->point.x - target.x) * (node->point.x - target.x) + (node->point.y - target.y) * (node->point.y - target.y) + (node->point.z - target.z) * (node->point.z - target.z); if (dis <= distanceTol * distanceTol) ids.push_back(node->id); } int cd = depth % 3; //cd either is 0 or 1 or 2 (x,y or z) // IF within left boundary if ((cd == 0 && node->point.x > target.x - distanceTol) || (cd == 1 && node->point.y > target.y - distanceTol) || (cd == 2 && node->point.z > target.z - distanceTol)) searchHelper(target, node->left, depth+1, distanceTol, ids); // IF within right boundary if ((cd == 0 && node->point.x < target.x + distanceTol) || (cd == 1 && node->point.y < target.y + distanceTol) || (cd == 2 && node->point.z < target.z + distanceTol)) searchHelper(target, node->right, depth+1, distanceTol, ids); } // return a list of point's ids in the tree that are within distance of target point std::vector<int> search(PointT target, float distanceTol) { std::vector<int> ids; searchHelper(target, root, 0, distanceTol, ids); return ids; } }; #endif
Python
UTF-8
533
2.8125
3
[]
no_license
from collections import defaultdict lines = open('input.txt').read().splitlines() kids = defaultdict(dict) for l in lines: words = l.split(' ') outer = tuple(words[:2]) inner = [words[4+i:4+3+i] for i in range(0, len(words)-4, 4)] for i in inner: count = i[0] if count != 'no': kids[outer][tuple(i[1:])] = int(count) def process(dad): c = 0 for k, v in kids[dad].items(): c += v * (1+process(k)) return c res = process(('shiny','gold')) # print(cont) print(res)
PHP
UTF-8
5,246
2.953125
3
[]
no_license
<?php class StudentsController extends AppController{ // La vue index sert de page d'accueil public function index() { // On test si des paramètres sont passés dans $_POST if(!empty($this->data)){ // Test des paramètres si ils sont suffisant pour modifier un élève if(is_string($this->data['Student']['id']) && is_string($this->data['Student']['nom'])){ // Requête pour update de l'élève $this->Student->save($this->data); $this->Flash('Modification effectué', '../'); // Si les paramètres sont insuffisant pour un update, on ajoute un nouvel élève } else if(is_string($this->data['Student']['nom'])) { // Requête pour l'ajout d'un élève $this->Student->save($this->data); $this->Flash('Enregistrement effectué', '../'); // Test des paramètres pour supprimer un élève } else if(is_numeric($this->data['Student']['liste_eleves'])) { // On récupère la liste des élèves classés par nom $chosenStudent= $this->select_name(); // On supprime l'élève $this->Student->delete($chosenStudent['Student']['id']); $this->Flash('Suppression effectué', '../'); // Test des paramètres pour la condition d'ajout d'une note } else if(is_string($this->data['Student']['id']) && is_string($this->data['Student']['matiere']) && is_string($this->data['Student']['note'])) { // On récupère le nom de l'élève $resultStudent = $this->Student->find('all', array( 'conditions' => array( 'Student.id' => $this->data['Student']['id'] ))); $chosenStudent = $resultStudent[0]; // On charge le modèle Subject puis on récupére la liste des matières $this->loadModel(Subject::class); $resultSubject = $this->Subject->find('all', array('order' => 'matiere')); $idmatiere = $resultSubject[$this->data['Student']['matiere']]; // On charge le modèle Bulletin pour insertion (nom prénom/matière/note) $this->loadModel(Bulletin::class); $this->Bulletin->save(array( 'Bulletin' => array( 'nom_eleve' => $chosenStudent['Student']['nom'].' '.$chosenStudent['Student']['prenom'], 'matiere' => $idmatiere['Subject']['matiere'], 'note' => $this->data['Student']['note'] ))); $this->Flash('Note ajoutée', '../'); } } } // Action pour l'ajout d'un élève public function addStudent() { } // Action choix de l'élève à modifier public function chooseStudentModify() { // Récupération de la liste d'élève classé par nom $options = $this->select_list_name(); $this->set(compact('options')); } // Action pour modifier les valeurs d'un élève public function modifyStudent() { // Récupération de la liste d'élève classé par nom $chosenStudent = $this->select_name(); $this->set(compact('chosenStudent')); } // Action pour choix de l'élève à supprimer public function remove() { // Récupération de la liste d'élève classé par nom $options = $this->select_list_name(); $this->set(compact('options')); } // Action choix de l'élève pour ajouter une note public function chooseStudentAddNote() { // Récupération de la liste d'élève classé par nom $options = $this->select_list_name(); $this->set(compact('options')); } // Action pour sélectionner la matière et la note public function studentAddNote() { // Remplit le champ nom prénom de l'élève auquel sera ajoutée la note $chosenStudent = $this->select_name(); $this->set(compact('chosenStudent')); // Remplit le champ du choix de la matière $matieres = $this->select_list_subject(); $this->set(compact('matieres')); // Remplit le champ du choix de la note $notes = $this->select_list_note(); $this->set(compact('notes')); } //////////////////////////////////////////////////////////////////// // // FONCTIONS // /////////////////////////////////////////////////////////////////// public function select_list_name() { $result = $this->Student->find('all', array('order' => 'nom')); // Création d'un tableau de (noms prénoms) pour les passer à la vue foreach ($result as $name): $options[] = $name['Student']['nom'].' '.$name['Student']['prenom']; endforeach; return $options; } public function select_name() { $result = $this->Student->find('all', array('order' => 'nom')); // On met le nom dans une variable pour l'envoyer à la vue $chosenStudent = $result[$this->data['Student']['liste_eleves']]; return $chosenStudent; } public function select_list_subject() { $this->loadModel(Subject::class); $resultSubjects = $this->Subject->find('all', array('order' => 'matiere')); // Création d'un tableau des matières pour les passer à la vue foreach ($resultSubjects as $matiere): $matieres[] = $matiere['Subject']['matiere']; endforeach; return $matieres; } public function select_list_note() { $this->loadModel(Note::class); $resultNotes = $this->Note->find('all', array('order' => 'note')); // Création d'un tableau des notes pour les passer à la vue foreach ($resultNotes as $note): $notes[] = $note['Note']['note']; endforeach; return $notes; } } ?>
Python
UTF-8
514
3.953125
4
[]
no_license
def num_beers(n): while n > 0: print (str(n) + " bottles of beer on the wall") print (str(n) + " bottles of beer") print ("Take one down pass it around") print (str(n - 1)+" bottles of beer on the wall!") num_beers(n - 1) return else: print ("No bottles of beer on the wall") print ("No bottles of beer") print ("Somebody better go back to the mall") print ("Cause there's no more bottles of beer on the wall!") num_beers(99)
Python
UTF-8
286
3.984375
4
[]
no_license
#usr/bin/python3 a = 5 b = 3 c = 4.0 # Penjumlahan d = a + b print("Penjumlahan a + b adalah", d) # Pengurangan d = a - b print("Pengurangan a - b adalah", d) # Perkalian d = a * c print("Perkalian a * c adalah", d) # Pembagian d = a / b print("Pembagian a / b adalah", d)
Java
UTF-8
5,973
2.71875
3
[]
no_license
/** * Used to create XML file with list of questions and their properties * for QuestionsViewer needs. * @author Oloieri Lilian * */ import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class XMLWriter { // D�claration d'un document XML private Document objDocumentXML; private String xmlString; private Element rootElement; private SmacUI ui; // Constructor public XMLWriter(SmacUI ui) { this.ui = ui; } /** * init the xml and construct the root element - questions * late will add the question elements to the root in the separate method * called after each flash created */ public void initXMLDoc() { try { // Cr�er une nouvelle instance de DocumentBuilderFactory qui va permettre // de cr�er un document XML dans lequel on va pouvoir �crire et lire des // cha�nes de caract�res format�es en XML DocumentBuilderFactory objXMLFactory = DocumentBuilderFactory.newInstance(); // D�finir les propri�t�s de la factory objXMLFactory.setValidating(false); objXMLFactory.setIgnoringComments(true); objXMLFactory.setIgnoringElementContentWhitespace(false); objXMLFactory.setExpandEntityReferences(true); // Cr�er un nouveau DocumentBuilder qui va permettre de cr�er un // document XML DocumentBuilder objCreateurDocumentXML = objXMLFactory.newDocumentBuilder(); // Cr�er un nouveau Document avec le cr�ateur de document XML // qui va contenir le code XML � retourner au client objDocumentXML = objCreateurDocumentXML.newDocument(); // Cr�er root element du XML rootElement = objDocumentXML.createElement("questions"); objDocumentXML.appendChild(rootElement); } catch (ParserConfigurationException pce) { ui.outputMessage("erreur_transformation xml..."); } } /** * If the questions.xml existe, take it and init the doc xml by him * @param flashFolderName */ public void getOldXml(String flashName) { try { // Cr�er une nouvelle instance de DocumentBuilderFactory qui va permettre // de cr�er un document XML dans lequel on va pouvoir �crire et lire des // cha�nes de caract�res format�es en XML DocumentBuilderFactory objXMLFactory = DocumentBuilderFactory.newInstance(); // D�finir les propri�t�s de la factory objXMLFactory.setValidating(false); objXMLFactory.setIgnoringComments(true); objXMLFactory.setIgnoringElementContentWhitespace(false); objXMLFactory.setExpandEntityReferences(true); // Cr�er un nouveau DocumentBuilder qui va permettre de cr�er un // document XML DocumentBuilder objCreateurDocumentXML = objXMLFactory.newDocumentBuilder(); // Cr�er un nouveau Document avec le cr�ateur de document XML // qui va contenir le code XML � retourner au client objDocumentXML = objCreateurDocumentXML.parse(new File(flashName)); // Cr�er root element du XML rootElement = objDocumentXML.getDocumentElement(); ui.outputMessage("root ..." + rootElement.toString()); } catch (ParserConfigurationException pce) { ui.outputMessage("erreur_transformation ..." + pce.getMessage()); } catch(IOException ioe) { ui.outputMessage("erreur_transformation ..." + ioe.getMessage()); } catch(SAXException saxe) { ui.outputMessage("erreur_transformation ..." + saxe.getMessage()); } } /** * Add the question element to the xml root after each flash created * @param nameString * @param idString * @param langueString */ public void addQuestions(String nameString, int idQ, String langueString) { //Create the question element Element question = objDocumentXML.createElement("question"); rootElement.appendChild(question); // Create name element Element name = objDocumentXML.createElement("name"); name.appendChild(objDocumentXML.createTextNode(nameString)); question.appendChild(name); // Create id element Element id = objDocumentXML.createElement("id"); id.appendChild(objDocumentXML.createTextNode(Integer.toString(idQ))); question.appendChild(id); // Create language element Element lang = objDocumentXML.createElement("lang"); lang.appendChild(objDocumentXML.createTextNode(langueString)); question.appendChild(lang); } /** * Write the final xml containing all the questions in xml file * will be executed after all flash's created * @param flashFolder */ public void writeXmlFile(String flashName) { try{ //write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(objDocumentXML); StreamResult result = new StreamResult(new File(flashName)); transformer.transform(source, result); }catch(TransformerException tfe){ ui.outputMessage(tfe.getMessage()); } } /** * Verify if the question with question_id = qid existe in the xml doc * @param qid * @return */ public boolean verifyQuestion(int qid) { NodeList questions = rootElement.getChildNodes(); for(int i = 0; i < questions.getLength(); i++) { Node question = questions.item(i); Node idNode = question.getFirstChild().getNextSibling(); //System.out.println(idNode.toString() + " " + rootElement.toString()); String idValue = idNode.getNodeValue().toString(); if(Integer.getInteger(idValue) == qid) return false; } return true; }// end method } // end class
Java
UTF-8
193
1.890625
2
[]
no_license
package com.codeup.adlister.dao; import com.codeup.adlister.models.Category; import java.util.List; public interface Categories { List<Category> all(); void insert(Category cat); }
Python
UTF-8
1,070
4.34375
4
[]
no_license
import random secret_number = random.randint(1, 10) trys = 0 print("I am thinking of a number between 1 and 10.") while trys < 5: try: print("You have " + str(5 - trys) + " guesses left.") number = int(input("What's the number? ")) if number == secret_number: print("Yes! You win!") trys = 5 cont = input("Do you want to play again (Y or N)? ").upper() if cont == "Y": trys = 0 elif cont == "N": print("Bye!") break elif number < secret_number: trys += 1 print("%d is too low." % (number)) elif number > secret_number: trys += 1 print("%d is too high." % (number)) while trys == 5: print("You ran out of guesses!") cont = input("Do you want to play again (Y or N)? ").upper() if cont == "Y": trys = 0 elif cont == "N": print("Bye!") break except: pass
PHP
UTF-8
2,136
2.5625
3
[]
no_license
<?php /** * Created by PhpStorm. * User: denny * Date: 04/05/2017 * Time: 16:03 */ namespace Main\Model; use Main\Entity\ResourcesEntity; use Main\InterFaces\Model\ResourcesModelInterFace; use System\Model\DaoModel; use Zend\Db\Adapter\AdapterInterface; use Zend\Hydrator\HydratorInterface; class ResourcesModel extends DaoModel implements ResourcesModelInterFace { /** * ResourcesModel constructor. * @param AdapterInterface $db * @param HydratorInterface $hydrator * @param ResourcesEntity $entity */ public function __construct(AdapterInterface $db, HydratorInterface $hydrator, ResourcesEntity $entity) { parent::__construct($db,$hydrator,$entity); } /** * 获取多维数组 * @param $category * @return array|\Zend\Db\ResultSet\HydratingResultSet */ public function multiResources($category="admin") { $list= $this->selectAll(['where'=>['status'=>1,'category'=>$category]]); $list=$list->toArray(); $list=$this->combination($list,0); return $list; } /** * @param $data * @param $pid * @return array */ public function combination($data, $pid) { $array = []; foreach ($data as $key => $val) { if ($val['parent_id'] == $pid) { $array[$key] = $val; $array[$key]['parents'] = $this->combination($data, $val['id']); } } return $array; } /** * 获取相关父类信息 * @param $id * @param array $arr * @param int $parentId * @return array|mixed */ public function getCascade($id,$arr=[],$parentId=0){ $accessData= $this->selectOne(['id'=>$id,'status'=>1],false); if($accessData==null) return []; $arr[$parentId]=$accessData; if($accessData['parent_id']!=0 && $accessData['parent_id']!=null){ $arr=$this->getCascade($accessData['parent_id'],$arr,$parentId+1); } return $arr; } }
Python
UTF-8
2,428
3.390625
3
[]
no_license
#!/usr/bin/env python3 """ @author: Timothy Baker @date: 02-18-2019 assemble_shortest_contig.py Dependencies: biopython """ import sys from Bio import SeqIO def assemble_overlap(sequence_list, contig=""): """ takes in a list of sequences and instantiates an empty string contig Args: sequence_list (lst) : list of strings contig (str) : empty Returns: recursively concatenates elements of the list together so long as sequence A's suffix matches sequence B's prefix """ # if the list is 0, return the contig # occurs after last 2 elements are concatenated together if not sequence_list: return contig # initializes the contig to the first element in the list if not contig: contig = sequence_list.pop(0) return assemble_overlap(sequence_list, contig) else: # iterates through the elements for idx, seq in enumerate(sequence_list): length = len(seq) # begins to index prefix sequences half the length of the sequence for prefix in range(length // 2): diff = length - prefix # if the initial and subsequent contigs prefix starts with the sequence # suffix then it removes the ith element from the list and recursively # calls itself to concatenate the contig and iterating sequence together if contig.startswith(seq[prefix:]): sequence_list.pop(idx) return assemble_overlap(sequence_list, seq[:prefix] + contig) # else if the contig's suffix is the iterative sequence's prefix # removes the element and recursively calls itself to concatenate # the contig and iterating sequence together if contig.endswith(seq[:diff]): sequence_list.pop(idx) return assemble_overlap(sequence_list, contig + seq[diff:]) def main(): """ runs main script """ # requires the fasta/txt file is in the same directory fasta_text = sys.argv[1] fasta_list = list(SeqIO.parse(fasta_text, "fasta")) sequence_list = [str(record.seq) for record in fasta_list] result = assemble_overlap(sequence_list) with open('overlap-output.txt', 'w') as output: output.write(str(result)) if __name__ == '__main__': main()
Python
UTF-8
1,434
3.1875
3
[]
no_license
#v1.0 对更新用户信息的脚本进行测试,使用unittest框架技术 #更新个人信息时,需要用到登录接口获取的sessionID #接口说明: #接口访问地址:http://localhost:8080/jwshoplogin/user/update_information.do #接口传入参数:1.email 2.phone 3.answer 4.question #接口预期返回值:email已存在,请更换email再尝试更新 更新个人信息失败 更新个人信息成功 #脚本实现 #导入相关测试类 import unittest import requests #定义测试类,继承unittest框架 class test_updateuser(unittest.TestCase): def setUp(self): url="http://localhost:8080/jwshoplogin/user/login.do" userinfo={"username":"meimei","password":"123456"} response=requests.post(url,userinfo) self.session=dict(response.cookies)['JSESSIONID'] print(self.session) def test_case1(self): url="http://localhost:8080/jwshoplogin/user/update_information.do" userinfo={"email":"[email protected]", "phone":"13211111111", "answer":"西游记1", "question":"喜欢的书1"} # session = {"JSESSIONID": "23A54B7E221BD45BAE2F3E9F142EB8CB"} session={'JSESSIONID':self.session} response=requests.post(url,userinfo,cookies=session).text print(response) self.assertIn("更新个人信息成功",response) if __name__ == '__main__': unittest.main()
Markdown
UTF-8
2,439
3.625
4
[ "CC0-1.0" ]
permissive
--- title: Alignment tab changed to `\cr` category: errors permalink: /FAQ-altabcr --- This is an error you may encounter in LaTeX when a tabular environment is being processed. "Alignment tabs" are the `&` signs that separate the columns of a `tabular` (or `array` or matrix) environment; so the error message ```latex ! Extra alignment tab has been changed to \cr ``` could arise from a simple typo, such as: ```latex \begin{tabular}{ll} hello & there & jim \\ goodbye & now \end{tabular} ``` where the second `&` in the first line of the table is more than the two-column `ll` column specification can cope with. In this case, an extra `l` in that solves the problem. (If you continue from the error in this case, `jim` will be moved to a row of his own.) Another simple typo that can provoke the error is: ```latex \begin{tabular}{ll} hello & there goodbye & now \end{tabular} ``` where the `\\` has been missed from the first line of the table. In this case, if you continue from the error, you will find that LaTeX has made a table equivalent to: ```latex \begin{tabular}{ll} hello & there goodbye\\ now \end{tabular} ``` (with the second line of the table having only one cell). Rather more difficult to spot is the occurrence of the error when you're using alignment instructions in a `p` column: ```latex \usepackage{array} ... \begin{tabular}{l>{\raggedright}p{2in}} here & we are again \\ happy & as can be \end{tabular} ``` the problem here (as explained in [tabular cell alignment](FAQ-tabcellalign)) is that the `\raggedright` command in the column specification has overwritten `tabular`s definition of `\\`, so that `happy` appears in a new line of the second column, and the following `&` appears to LaTeX just like the second `&` in the first example above. Get rid of the error in the way described in [tabular cell alignment](FAQ-tabcellalign)&nbsp;&mdash; either use `\tabularnewline` explicitly, or use the `\RBS` trick described there. The [`amsmath`](https://ctan.org/pkg/amsmath) package adds a further twist; when typesetting a matrix (the package provides many matrix environments), it has a fixed maximum number of columns in a matrix&nbsp;&mdash; exceed that maximum, and the error will appear. By default, the maximum is set to 10, but the value is stored in counter `MaxMatrixCols` and may be changed (in the same way as any counter): ```latex \setcounter{MaxMatrixCols}{20} ```
Markdown
UTF-8
1,430
2.671875
3
[]
no_license
# 如何解决json字符串中包含制表符 错误信息: ``` Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Unescaped control character around character 135.) UserInfo=0x170e79d00 {NSDebugDescription=Unescaped control character around character 135.} ``` 如何处理: 最关键的地方: ``` -(NSString *)removeUnescapedCharacter:(NSString *)inputStr { NSCharacterSet *controlChars = [NSCharacterSet controlCharacterSet];//获取那些特殊字符 NSRange range = [inputStr rangeOfCharacterFromSet:controlChars];//寻找字符串中有没有这些特殊字符 if (range.location != NSNotFound) { NSMutableString *mutable = [NSMutableString stringWithString:inputStr]; while (range.location != NSNotFound) { [mutable deleteCharactersInRange:range];//去掉这些特殊字符 range = [mutable rangeOfCharacterFromSet:controlChars]; } return mutable; } return inputStr; } ``` 举例: ``` NSString *responseString = [NSMutableString stringWithString:[request responseString]]; responseString =[self removeUnescapedCharacter:responseString]; NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding]; NSError *error; NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error]; ```
Python
UTF-8
927
2.984375
3
[]
no_license
import unittest from hypothesis import strategies as st, given from src.algorithms.search import linear_search from src.algorithms.search import unbound_linear_search from tests.search import _search class TestBoundLinearSearch(unittest.TestCase): @given(st.lists(st.integers()), st.integers()) def runTest(self, sequence, item): sequence.sort() self.assertEqual(linear_search(sequence, item, True), _search(sequence, item, True)) self.assertEqual(linear_search(sequence, item, False), _search(sequence, item, False)) class TestUnboundLinearSearch(unittest.TestCase): @given(st.lists(st.integers()), st.integers()) def runTest(self, sequence, item): sequence.sort() self.assertEqual(unbound_linear_search(sequence, item, True), _search(sequence, item, True)) self.assertEqual(unbound_linear_search(sequence, item, False), _search(sequence, item, False))
C++
UTF-8
430
3.078125
3
[]
no_license
#include <vector> class Solution { public: int maxSubArray(std::vector<int>& nums) { int max_sum = nums[0]; int sum_thus_far = 0; for(auto n : nums) { sum_thus_far += n; if(sum_thus_far > max_sum) max_sum = sum_thus_far; if(sum_thus_far < 0) sum_thus_far = 0; } return max_sum; } };
C
UTF-8
153
3.0625
3
[]
no_license
#include "libft.h" size_t ft_intlen(int *s) { size_t cont; cont = 0; if (!s) return (0); while (s[cont] != -1) { cont++; } return (cont); }
PHP
UTF-8
567
2.875
3
[]
no_license
<?php ob_start(); //NE PAS MODIFIER $titre = "Exo 6 : La Boucle for "; //Mettre le nom du titre de la page que vous voulez ?> <!-- mettre ici le code --> <?php $random = rand(5,20); echo "<h2>Voici la table de multiplication de $random :</h2>"; for ($i=1; $i <= 10; $i++) { echo $random ." * ". $i . " = ".($random * $i). "<br>"; } ?> <?php /************************ * NE PAS MODIFIER * PERMET d INCLURE LE MENU ET LE TEMPLATE ************************/ $content = ob_get_clean(); require "../../global/common/template.php"; ?>
C
UTF-8
242
3.5
4
[]
no_license
#include "holberton.h" /** * puts2 - prints every other character of a string * @str: checked char * Return: always 0 (success) */ void puts2(char *str) { int i; while (str[i] != '\0') { _putchar (str[i]); i += 2; } _putchar ('\n'); }
Markdown
UTF-8
1,152
3.546875
4
[]
no_license
# 17. 电话号码的字母组合 给定一个仅包含数字 `2-9` 的字符串,返回所有它能表示的字母组合。 给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。 ![](https://assets.leetcode-cn.com/aliyun-lc-upload/original_images/17_telephone_keypad.png) #### 示例: <pre> <strong>输入:</strong> "23" <strong>输出:</strong> ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. </pre> #### 说明: 尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。 ## 题解 (Python) ### 1. 回溯 ```Python class Solution: digit_to_letters = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'} def letterCombinations(self, digits: str) -> List[str]: if not digits: return [] if len(digits) == 1: return list(self.digit_to_letters[digits]) sub = self.letterCombinations(digits[1:]) return [c + s for s in sub for c in self.digit_to_letters[digits[0]]] ```
PHP
UTF-8
1,188
2.515625
3
[]
no_license
<?php namespace AppBundle\Entity; use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB; /** * A snapshot image * * @MongoDB\Document(repositoryClass="AppBundle\Repository\ImageRepository") */ class Image { /** * @MongoDB\Id */ private $id; /** * @MongoDB\Timestamp */ private $timestamp; /** * @MongoDB\String */ public $data; /** * Set data * * @param string $data * @return self */ public function setData($data) { $this->data = $data; return $this; } /** * Get data * * @return string $data */ public function getData() { return $this->data; } /** * Get id * * @return int $id */ public function getId() { return $this->id; } /** * Set ts * * @param int $timestamp * @return self */ public function setTimestamp($timestamp) { $this->timestamp = $timestamp; return $this; } /** * Get ts * * @return int */ public function getTimestamp() { return $this->timestamp; } }
Markdown
UTF-8
820
2.765625
3
[]
no_license
# Registration --- - [Description](/{{route}}/{{version}}/registration/#description) - [Procedure](/{{route}}/{{version}}/registration/#procedure) <a name="description"></a> ## Description `Appointment Management System` cannot be accessed without registration. This system's features are not accessible for guests. To access the features of the system `registration` is required. <a name="procedure"></a> ## Procedure If any `visitor` of this application is not an `authenticated user` then `login` and `registration` view is accessible only, until the visitor get registered and become an `authenticated user`. The registration form consists of following fields, | # | Fields | | : | : | | 1 | Name | | 2 | Email | | 3 | Password | | 4 | Confirm Password |
C++
UTF-8
676
2.921875
3
[ "MIT" ]
permissive
#include <iostream> using namespace std ; int main (){ int mese, anno ; cout << "inserire numero del mese: "<<endl; cin >> mese ; if (mese==2){ cout << "inserire l'anno': "<<endl; cin >> anno ;} switch (mese) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: cout << "il mese ha 31 giorni"<<endl ; break ; case 4: case 6: case 9: case 11: cout << "il mese ha 30 giorni"<<endl ; break ; case 2: if (anno%4==0) cout << "il mese ha 29 giorni"<<endl ; else cout << "il mese ha 28 giorni"<<endl ; break; default : cout << "non hai selezionato un mese esistente" <<endl ; } system ("pause"); }
Markdown
UTF-8
932
2.546875
3
[]
no_license
# LDA Topic Modeling ## Analyzing and vectorizing contents of Social Network groups. ### Contents description * loading_texts.ipynb - Notebook with VK app authorization and pipeline of VK groups content downloading. * vk_tools.py - Module file with functions for handy loading and formatting of VK contents, used in loading_texts.ipynb * preprocessing.ipynb - Notebook with dataset exploration code, filtering and preprocessing. * training_pipeline.ipynb - Notebook with dataset all the models(TF-IDF, CountVectorizer, LDA) training, and some last step preparation to it. * preprocessing_tools.py - Module file with functions for preprocessing. Barely used them for data exploration in preprocessing.ipynb, don\`t need this file at all, just put it all along with the rest of code. ### Preprocessing steps include: * Lowercasing * Remove extra spacing * Remove punctuation * Removing digits * Remove stopwords * Lemmatization
Markdown
UTF-8
1,386
2.953125
3
[]
no_license
News Manager ------------ The `NewsManager` class will be in charge of providing news from Reddit API. It will be responsible for performing the server request and give you a list of news with our already created News UI Model. The main idea behind this is to make your API call to be executed outside of your Main UI Thread, in another thread. Observable ---------- The `NewsManager` class will provide a method that will return an `Observable` object which will allows you to run a piece of code (like an API call) in another context (in this case in a new thread). ```kotlin fun getNews(): Observable<List<RedditNewsItem>> { ... } ``` This Observable object will be created from the `NewsManager`. We will provide the implementation of this object: ```kotlin fun getNews(): Observable<List<RedditNewsItem>> { return Observable.create { subscriber -> //code to tun in another context ... //actions on subscriber subscriber.onCompleted() } } ``` \ \ Task: ----- Complete the `getNews()` functions in `NewsManager.kt` to create and return `Observable`, that will generate news for subscriber (will be added in the next task). <div class='hint'>You should declare an implementation of Observable.</div> <div class='hint'>You should also invoke the create method of the Observable in the lower placeholder.</div>
SQL
UTF-8
118
2.859375
3
[]
no_license
SELECT A.row_num, A.col_num, A.value * B.value FROM A, B WHERE A.row_num = B.row_num AND A.col_num = B.col_num;
Python
UTF-8
2,999
2.578125
3
[]
no_license
from PIL import Image from torch.utils.data import Dataset import torchvision import torch import os import cv2 import xml.etree.ElementTree as ET import numpy as np from torchvision import transforms class VOCDataset(Dataset): CLASS_NAME = ( "__background__", "pottedplant", "person", "horse", "chair", "car" ) def __init__(self, root_dir, resize = [1080,720], split='trainval', use_difficult=False, transforms = None): super(VOCDataset,self).__init__() self.root = root_dir self.split = split self.use_difficult = use_difficult self._ann_path = os.path.join(self.root, 'Annotations', "%s.xml") self._img_path = os.path.join(self.root, 'JPEGImages', "%s.jpg") self._imgset_path = os.path.join(self.root,'ImageSets', 'Main', "%s.txt") with open(self._imgset_path % self.split) as f: self.img_ids = f.readlines() self.img_ids = [x.strip() for x in self.img_ids] self.name2id = dict(zip(VOCDataset.CLASS_NAME, range(len(VOCDataset.CLASS_NAME)))) self.new_size = tuple(resize) self.mean = [0.485,0.456, 0.406] self.std = [0.229, 0.224, 0.225] print("INFO: VOC Dataset init finished !") def __len__(self): return len(self.img_ids) def _read_img_rgb(self, path): img = cv2.imread(path) img = cv2.resize(img,self.new_size) return cv2.cvtColor(img, cv2.COLOR_BGR2RGB) def __getitem__(self, index): img_id = self.img_ids[index] img = self._read_img_rgb(self._img_path % img_id) anno = ET.parse(self._ann_path % img_id).getroot() boxes = [] classes = [] for obj in anno.iter("object"): difficult = int(obj.find("difficult").text) == 1 if not self.use_difficult and difficult: continue _box = obj.find("bndbox") box = [ _box.find("xmin").text, _box.find("ymin").text, _box.find("xmax").text, _box.find("ymax").text, ] TO_REMOVE = 1 # 由于像素是网格存储,坐标2实质表示第一个像素格,所以-1 box = tuple( map(lambda x: x - TO_REMOVE, list(map(float, box))) ) boxes.append(box) name = obj.find("name").text.lower().strip() classes.append(self.name2id[name]) # 将类别映射回去 boxes = np.array(boxes, dtype=np.float32) img = transforms.ToTensor()(img) boxes = torch.from_numpy(boxes) classes = torch.tensor(classes) return img, boxes, classes if __name__ == '__main__': dataset = VOCDataset(r'D:\VOCdevkit\VOC2007',split='train') img, boxes, classes = dataset[0] print(img.shape) train_loader = torch.utils.data.DataLoader(dataset, batch_size=10,num_workers=2) print(train_loader)
Java
UTF-8
3,171
2.21875
2
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
/* * Copyright 2013 National Technical University of Athens * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package eu.sociosproject.sociosapi.junit.comparator; import eu.sociosproject.sociosvoc.Activity; import eu.sociosproject.sociosvoc.MediaItem; import eu.sociosproject.sociosvoc.ObjectId; /** * * @author pielakm * */ public class ActivityComparator extends AbstractComparator<Activity> { @Override public Boolean isTheSameProps(Activity t1, Activity t2) { AbstractComparator<ObjectId> objIdCompare = new ObjectIdComparator(); int result = objIdCompare.compare(t1.getAppId(), t2.getAppId()); if (result != 0){ this.setErrorMessage(objIdCompare.getErrorMessage()); return false; } if (!isTheSameValues(t1.getBody(), t2.getBody(), "body")) return false; result = objIdCompare.compare(t1.getBodyId(), t2.getBodyId()); if (result != 0){ this.setErrorMessage(objIdCompare.getErrorMessage()); return false; } result = objIdCompare.compare(t1.getExternalId(), t2.getExternalId()); if (result != 0){ this.setErrorMessage(objIdCompare.getErrorMessage()); return false; } result = objIdCompare.compare(t1.getId(), t2.getId()); if (result != 0){ this.setErrorMessage(objIdCompare.getErrorMessage()); return false; } AbstractComparator<MediaItem> mediaItemCompare = new MediaItemComparator(); result = mediaItemCompare.compareList(t1.getMediaItems(), t2.getMediaItems(), "mediaItemsList"); if (result != 0){ this.setErrorMessage(mediaItemCompare.getErrorMessage()); return false; } if (!isTheSameValues(t1.getPostedTime(), t2.getPostedTime(), "postedTime")) return false; if (!isTheSameValues(t1.getPriority(), t2.getPriority(), "priority")) return false; if (!isTheSameValues(t1.getStreamFaviconUrl(), t2.getStreamFaviconUrl(), "streamFaviconUrl")) return false; if (!isTheSameValues(t1.getStreamSourceUrl(), t2.getStreamSourceUrl(), "streamSourceUrl")) return false; if (!isTheSameValues(t1.getStreamTitle(), t2.getStreamTitle(), "streamTitle")) return false; if (!isTheSameValues(t1.getTemplateParams(), t2.getTemplateParams(), "templateParams")) return false; if (!isTheSameValues(t1.getTitle(), t2.getTitle(), "title")) return false; result = objIdCompare.compare(t1.getTitleId(), t2.getTitleId()); if (result != 0) return false; if (!isTheSameValues(t1.getUrl(), t2.getUrl(), "url")) return false; result = objIdCompare.compare(t1.getUserId(), t2.getUserId()); if (result != 0){ this.setErrorMessage(objIdCompare.getErrorMessage()); return false; } return true; } }