language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
1,015
3.234375
3
[]
no_license
package com.example.demo; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; public class StringReader { public String x; public String StringReader(String str){ Map<Character,Integer> ContadordeChars = new HashMap<>(); for(Character c : str.toCharArray() ){ if(ContadordeChars.containsKey(c)){ ContadordeChars.put(c,ContadordeChars.get(c)+1); }else { ContadordeChars.put(c,1); } } Character [] key = ContadordeChars.keySet().toArray(new Character [0]); //System.out.println(Arrays.toString((key))); Integer [] values = ContadordeChars.values().toArray(new Integer[0]); //System.out.println(Arrays.toString(values)); for(int i =0; i <ContadordeChars.size();i++){ System.out.println(key[i] + ":" + values[i]); } //System.out.println(ContadordeChars); return str; } }
Java
UTF-8
373
2.609375
3
[ "BSD-3-Clause" ]
permissive
// .result=COMPILE_PASS import java.io.EOFException; import java.io.IOException; import java.util.*; public class Test { public interface A { int m(); } public interface B { default int m() { return 5; } } public class Inner extends Test implements B { public int m() { return 3; } public void testMethod() { A a = B.super::m; } } }
C
UTF-8
194
3.046875
3
[]
no_license
#include <stdio.h> #include <pwd.h> int main(int argc, char **argv){ struct passwd *u; while( (u = getpwent()) != NULL) { if (u->pw_uid >=1000) printf("%s\n", u->pw_name); } }
TypeScript
UTF-8
506
2.53125
3
[]
no_license
import { PipeTransform, Pipe } from '@angular/core'; import { ITableviews } from './tableviews'; @Pipe({ name: 'tableviewsFilterPipe' }) export class tableviewsFilterPipe implements PipeTransform { transform(value: ITableviews[], filterBy: string): ITableviews[] { filterBy = filterBy ? filterBy.toLocaleLowerCase() : null; return filterBy ? value.filter((tableviews: ITableviews) => tableviews.ViewName.toLocaleLowerCase().indexOf(filterBy) !== -1) : value; } }
TypeScript
UTF-8
6,490
2.734375
3
[ "MIT" ]
permissive
import { asyncScheduler, merge, of, VirtualTimeScheduler } from 'rxjs'; import { delay, observeOn, subscribeOn } from 'rxjs/operators'; import { createModule } from '../../src/createModule'; import { Epic } from '../../src/Epic'; import { Deps } from '../../src/types'; async function runEpic<T = any[]>( sourceEpic: Epic, sourceAction: any, storeName = 'test store' ): Promise<T[]> { const results: T[] = []; await merge( ...sourceEpic.toStream(sourceAction, {} as Deps, storeName) ).forEach(action => results.push(action)); return results; } describe('Epic#toStream', () => { describe('normally', () => { const Actions = createModule(Symbol('sample')).withActions({ a: null, b: null, c: null, })[1]; it('should return next Action from sourceAction', async () => { const epic = new Epic() .on(Actions.a, () => Promise.resolve(Actions.b())) .on(Actions.a, () => of(Actions.c())); const results = await runEpic(epic, Actions.a()); expect(results).toMatchObject([Actions.c(), Actions.b()]); }); it('should return next Action from Action Array', async () => { const epic = new Epic().on(Actions.a, () => [Actions.b(), Actions.c()]); const results = await runEpic(epic, Actions.a()); expect(results).toMatchObject([Actions.b(), Actions.c()]); }); it('should return next Acton from Action array Promise', async () => { const epic = new Epic().on(Actions.a, () => Promise.resolve([Actions.b(), Actions.c()]) ); const results = await runEpic(epic, Actions.a()); expect(results).toMatchObject([Actions.b(), Actions.c()]); }); it('should return next Acton from Action array Observable', async () => { const epic = new Epic().on(Actions.a, () => of([Actions.b(), Actions.c()]) ); const results = await runEpic(epic, Actions.a()); expect(results).toMatchObject([Actions.b(), Actions.c()]); }); describe('occurred error', () => { const epic = new Epic().on(Actions.a, () => { throw new Error('foo error'); }); it('should be empty result', async () => { const results = await runEpic(epic, Actions.a()); expect(results).toStrictEqual([]); }); it('should be threw', async () => { jest.useFakeTimers(); await runEpic(epic, Actions.a()); expect(() => jest.runAllTimers()).toThrowError('foo error'); }); }); }); describe('with delay', () => { let scheduler: VirtualTimeScheduler; beforeEach(() => { scheduler = new VirtualTimeScheduler(); asyncScheduler.now = scheduler.now.bind(scheduler); asyncScheduler.schedule = scheduler.schedule.bind(scheduler); }); it('should return next Action', () => { const Actions = createModule(Symbol('sample')).withActions({ ping: null, pong: null, })[1]; const epic = new Epic().on(Actions.ping, () => of(Actions.pong()).pipe(delay(500)) ); const results: any[] = []; const o = merge(...epic.toStream(Actions.ping(), {} as Deps)).pipe( observeOn(scheduler), subscribeOn(scheduler) ); expect(results).toStrictEqual([]); o.subscribe(r => results.push(r)); scheduler.flush(); expect(results).toStrictEqual([Actions.pong()]); }); }); describe('Invalid handler', () => { const Actions = createModule(Symbol('sample')).withActions({ a: null })[1]; beforeEach(() => { jest.resetAllMocks(); // tslint:disable-next-line: no-empty jest.spyOn(console, 'error').mockImplementation(() => {}); }); describe('returns `undefined`', () => { const epic = new Epic().on(Actions.a, () => undefined); it('should return empty action', async () => { const results = await runEpic(epic, Actions.a()); expect(results).toStrictEqual([]); }); it('should log error', async () => { await runEpic(epic, Actions.a(), 'FooStore'); expect(console.error).toBeCalledWith( 'Invalid action returned in epic.', { sourceAction: Actions.a(), action: undefined, store: 'FooStore', } ); }); }); describe('returns invalid Action', () => { const invalidAction = { type: 'this is invalid action' }; // @ts-expect-error const epic = new Epic().on(Actions.a, () => invalidAction); it('should return empty action', async () => { const results = await runEpic(epic, Actions.a()); expect(results).toStrictEqual([]); }); it('should log error', async () => { await runEpic(epic, Actions.a()); expect(console.error).toBeCalledWith( 'Invalid action returned in epic.', { sourceAction: Actions.a(), action: invalidAction, store: 'test store', } ); }); }); describe('returns invalid Action Array', () => { const invalidAction = { type: 'this is invalid action' }; // @ts-expect-error const epic = new Epic().on(Actions.a, () => [invalidAction]); it('should return empty action', async () => { const results = await runEpic(epic, Actions.a()); expect(results).toStrictEqual([]); }); it('should log error', async () => { await runEpic(epic, Actions.a()); expect(console.error).toBeCalledWith( 'Invalid action returned in epic.', { sourceAction: Actions.a(), action: [invalidAction], store: 'test store', } ); }); }); describe('returns invalid Promise Action Array', () => { const invalidAction = { type: 'this is invalid action' }; const epic = new Epic().on(Actions.a, () => // @ts-expect-error Promise.resolve([invalidAction]) ); it('should return empty action', async () => { const results = await runEpic(epic, Actions.a()); expect(results).toStrictEqual([]); }); it('should log error', async () => { await runEpic(epic, Actions.a()); expect(console.error).toBeCalledWith( 'Invalid action returned in epic.', { sourceAction: Actions.a(), action: [invalidAction], store: 'test store', } ); }); }); }); });
Java
UTF-8
3,479
2.25
2
[]
no_license
package com.example.book_search; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; public class Register extends AppCompatActivity { private Button RegisterButton,GoToLoginPageButton; private EditText Email,Password,ConfirmPassword,Username; private ProgressBar progressBar; private FirebaseAuth firebaseAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); RegisterButton = (Button)findViewById(R.id.RegisterButton); GoToLoginPageButton = (Button)findViewById(R.id.button1); Email = (EditText)findViewById(R.id.RegisterEmail); Username = (EditText)findViewById(R.id.RegisterUsername); Password = (EditText)findViewById(R.id.RegisterPassword); ConfirmPassword = (EditText)findViewById(R.id.RegisterConfirmPassword); progressBar = (ProgressBar)findViewById(R.id.RegisterProgress); firebaseAuth = FirebaseAuth.getInstance(); //Getting the current instance of a database from the firebase to perform various operation on database. if(firebaseAuth.getCurrentUser()!=null){ startActivity(new Intent(this,MainActivity.class)); finish(); } } public void RegisterNewUser(View view) { String email = Email.getText().toString(); String password = Password.getText().toString(); String confirmPassword = ConfirmPassword.getText().toString(); if(TextUtils.isEmpty(email)){ Email.setError("Email is required."); return; } if(TextUtils.isEmpty(password)){ Password.setError("Password is required."); return; } if(password.length() < 8){ Password.setError("Password must contain atleast 8 characters"); return; } if(!password.equals(confirmPassword)){ ConfirmPassword.setError("Password doesn't match Confirm password"); return; } progressBar.setVisibility(View.VISIBLE); firebaseAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if(task.isSuccessful()){ Toast.makeText(Register.this, "New user is successfully created", Toast.LENGTH_SHORT).show(); progressBar.setVisibility(View.GONE); startActivity(new Intent(Register.this,MainActivity.class)); } else { Toast.makeText(Register.this,task.getException().getMessage(),Toast.LENGTH_LONG).show(); progressBar.setVisibility(View.GONE); } } }); } public void Go_to_LoginPage(View view) { startActivity(new Intent(this,Login.class)); finish(); } }
TypeScript
UTF-8
707
2.53125
3
[]
no_license
import { Document } from 'mongoose'; import { ITeamDocument } from './teams.types'; export function isTeamCreator(this: ITeamDocument, userID: string): boolean { return this.createdBy === userID; } export async function deleteTeam(this: ITeamDocument): Promise<void> { await this.remove(); return; } export async function deleteUser( this: ITeamDocument, userID: string, ): Promise<ITeamDocument> { this.users = this.users.filter((id) => id !== userID); return this.save(); } export async function addUser( this: ITeamDocument, userID: string, ): Promise<ITeamDocument> { if (this.users.includes(userID)) return this; this.users.push(userID); await this.save(); return this; }
C
UTF-8
396
2.765625
3
[]
no_license
#ifndef _D_LIST_STACK_H_ #define _D_LIST_STACK_H_ #define MAX_STACK_SIZE 100 #define STACK_INCREMENT 10 #define ERROR -1 #define OK 0 typedef int ElemType; typedef struct { ElemType *bottom; ElemType *top; int stacksize; }SqStack; int init_stack(SqStack *S); int push(SqStack *S,ElemType e); ElemType pop(SqStack *S); void list_stack(SqStack *S); #endif
JavaScript
UTF-8
533
2.796875
3
[]
no_license
const testimonial = [...document.querySelectorAll('.testimonial')]; const leftArrows = [...document.querySelectorAll('.left-button')]; const rightArrows = [...document.querySelectorAll('.right-button')]; function newSlide(e){ testimonial.forEach((slide) => { slide.classList.toggle('hide'); slide.classList.toggle('show'); }); } leftArrows.forEach((arrow) => { arrow.addEventListener('click', newSlide); }); rightArrows.forEach((arrow) => { arrow.addEventListener('click', newSlide); });
Python
UTF-8
230
2.625
3
[]
no_license
from PIL import Image import numpy as np image = Image.open('test03.png') img_resized = image.resize((96,96)) F_image = image.convert(mode='L') F_image= F_image.save("test03_bw.png") arr=np.asarray(F_image) print(arr)
Java
UTF-8
211
1.6875
2
[]
no_license
package com.psycorp.security; /** * @author Vitaliy Proskura */ public class SecurityConstant { public static final String ACCESS_TOKEN_PREFIX = "Bearer"; public static final String JWT_TOKEN_PREFIX = "Jwt"; }
JavaScript
UTF-8
1,086
4.21875
4
[]
no_license
// In this kata you are required to, given a string, replace every letter with its position in the alphabet. // If anything in the text isn't a letter, ignore it and don't return it. // "a" = 1, "b" = 2, etc. //use charCodeAt to have the ASCII code of each letter //since alphabet starts at 97 in ASCII (a=97) and end at 122(z=122) //to have the position we substract 96 to ASCII code function alphabetPosition(text) { let stringOfNumbers = [] for (let i=0; i<text.length; i++) { const ascii = text[i].toLowerCase().charCodeAt() //console.log(ascii) //this is too specify the alphabet range if (ascii >=97 && ascii <=122 && ascii) stringOfNumbers.push(ascii-96) } return stringOfNumbers.join(' ') } alphabetPosition("The sunset sets at twelve o' clock.")//, "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11") //another solution function alphabetPosition(text) { let char = text.toLowerCase().replace(/[^a-z]/g,""); return [...char].map(x => x.charCodeAt() - 96).toString().replace(/,/g, " ") }
Markdown
UTF-8
7,764
2.515625
3
[]
no_license
## ssh综合练习(本项目可见ssh-practice的仓库) ### jar包导入 ### 包的建立 ### 注解环境搭建 struts2的bug,在action上面@Controller没用,因为在spring去创建action的时候,beanname是由struts传过去的,不管有没有controller(有没有将action纳入spring的管理),spring都能根据beanname这个类名去运用反射创建action 注意: spring整合struts和hibernate,在applicationContext.xml中的三点配置 1. spring注解开发中,要在applicationContext里面配置<context:component-scan base-package="com.forest"/> 2. spring整合hibernate的注解,是要在applicationContext.xml中声明sessionFactory的地方,将原本的 <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="hibernateProperties"> <value> hibernate.show_sql=true hibernate.format_sql=true hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.hbm2ddl.auto=update </value> </property> <property name="mappingDirectoryLocations"> <!-- mappingDirectoryLocations这个属性可以加载类路径下所有文件 --> <list> <value>classpath:com/forest1/domain</value> </list> </property> </bean> 变成(即只有最后一个property有变化,*此外,在这个配置之前,数据源也还是照常配置。*): <!-- hibernate核心文件的配置,声明sessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="hibernateProperties"> <value> hibernate.show_sql=true hibernate.format_sql=true hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.hbm2ddl.auto=update </value> </property> <!-- 映射相关的注解 --> <property name="packagesToScan"> <list> <value>com.forest.domain</value> </list> </property> </bean> 3. 事务管理器的配置。从如下: <!-- 事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 事务通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add" /> <tx:method name="del" /> <tx:method name="update" /> <tx:method name="find*" read-only="true" /> </tx:attributes> </tx:advice> <!-- 切面 --> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.forest1.service.*..*(..))" id="myPointcut" /> </aop:config> 到: <!-- 事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sesstionFactory" ref="sessionFactory"/> </bean> <!-- 开启事务注解驱动 --> <tx:annotation-driven transaction-manager="transactionManager"/> 在applicationContext.xml中的用到的标签需要在文件头上配置,如tx,aop等。 开发中,图片不会放在tomcat中,会放在磁盘上某处,并配置一个虚拟路径。不然每次重启tomat图片就不见了。 ### 添加用户 前端页面表单提交的地方。注意cusName,cusPhone等是name,而不是id。如果是id,无法在表单提交的时候传给后台。如果使用的name,那么会存为属性值,可以被后台获取到。 <form role="form" class="bg" method="post" encType="multipart/form-data" action="${pageContext.request.contextPath}/customer/addCustomer"> <div class="form-group"> <label for="CUSTOMER NAME">CUSTOMER NAME</label> <input type="text" class="form-control" name="cusName" placeholder="CUSTOMER NAME"> </div> <div class="form-group"> <label for="PHONE NUMBER">PHONE NUMBER</label> <input type="text" class="form-control" name="cusPhone" placeholder="PHONE NUMBER"> </div> <div class="form-group"> <label for="CUSTOMER IMAGE">CUSTOMER IMAGE</label> <input type="file" name="cusImg"> </div> <div class="checkbox"> <label> <input type="checkbox"> Check me out </label> </div> <button type="submit" class="btn btn-default">Submit</button> </form> ### 删除用户 //删除客户 function delCustomer(customerId) { location.href="${pageContext.request.contextPath}/customer/delCustomer?id="+customerId; } 删除客户的点击事件绑定的函数。这时只需要将id传给后台,删除对应id的用户。不需要获取数据回显页面,所以采取这种带参数的方法。可以和查询订单的点击事件绑定函数对比。 这里的参数只能是"id",不能写其他的。 另外,在删除订单时,不可以用上述类似方法,即: location.href="${pageContext.request.contextPath}/order/deleteOrder?id="+orderId; 如果要是该方法成立,则必须在customerAction中定义deleteOrder方法,并且定义orderId属性用于接收数据。不然,这里的location.href访问的还是CustomerAction,而不是OrderAction ### 查询与删除订单(包含分页) jsp页面的代码如下: //分页相关变量 var pageNum=1;//当前页码 var currentCount=5;//每页个数 var totalCount = 0;//总条数 var totalPage = 0//总页数 //定义cid的全局变量 var cid; //查询订单 function findOrders(customerId) { cid=customerId; $.post("${pageContext.request.contextPath}/order/findOrders",{"customerId":customerId,"pageNum":pageNum,"currentCount":currentCount},function(data) { $("#orderInfo").html(""); var pageBean = eval(data); var content = pageBean.content; $.each(content,function(i) { var content1="<tr><td>"+content[i].orderNum+"</td><td>"+content[i].price+"</td><td>"+content[i].receiverInfo +"</td><td>"+content[i].customer.cusName+"</td><td><a href='#' onclick=\"deleteOrder('"+content[i].orderNum+"')\">DELETE</a>&nbsp&nbsp</td></tr>"; $("#orderInfo").append(content1); }); //接收数据 pageNum = pageBean.pageNum; currentCount = pageBean.currentCount; totalCount = pageBean.totalCount; totalPage = pageBean.totalPage; //分页拼接 //清空page $("#page").html(""); $("#page").append("<ul class='pagination' id='pagUl'></ul>"); //判断是否能向上翻页 if (pageNum==1) { $("#pagUl").append("<li class='disabled'><a href='#' aria-label='Previous'> <span aria-hidden='true'>&laquo;</span></a></li>"); }else { $("#pagUl").append("<li class='active'><a href='#' aria-label='Previous' onclick='prePage()'><span aria-hidden='true'>&laquo;</span></a></li>"); } //判断中间数字 for (var i = 1; i <=totalPage; i++) { if (i==pageNum) { $("#pagUl").append("<li class='active'><a href='#' onclick='select("+i+")'>"+i+"</a></li>"); } else { $("#pagUl").append("<li><a href='#' onclick='select("+i+")'>"+i+"</a></li>"); } } //判断能否能向下翻页 if (pageNum==totalPage) { $("#pagUl").append("<li class='disabled'><a href='#' aria-label='Next'> <span aria-hidden='true'>&raquo;</span></a></li>"); }else { $("#pagUl").append("<li class='active'><a href='#' aria-label='Next' onclick='nextPage()'> <span aria-hidden='true'>&raquo;</span></a></li>"); } },"json"); } function prePage() { pageNum = pageNum-1; findOrders(cid); } function nextPage() { pageNum = pageNum+1; findOrders(cid); } function select(i) { pageNum=i; findOrders(cid); } //删除订单 function deleteOrder(orderId) { alert(orderId); $.post("${pageContext.request.contextPath}/order/deleteOrder",{"orderId":orderId},function(data) { findOrders(cid); }); }
Java
UTF-8
560
2.1875
2
[]
no_license
package com.wisdom.contactus.utils; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; import com.wisdom.common.model.Attachment; import com.wisdom.common.model.ContactUs; public class ContactUsMapper implements RowMapper<ContactUs> { public ContactUs mapRow(ResultSet rs, int index) throws SQLException { ContactUs u = new ContactUs(rs.getInt("id"), rs.getString("user_name"), rs.getString("user_phone"), rs.getString("user_company_name"),rs.getTimestamp("create_time")); return u; } }
Python
UTF-8
3,724
2.609375
3
[]
no_license
from discord.ext import commands import discord import Prefix class utility(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() @commands.has_permissions(manage_roles=True) async def mute(self, ctx, member : discord.Member, *, reason): if memeber == None: guild = ctx.guild for role in guild.roles: if role.name =="Muted": await member.add_roles(role) await ctx.send("{} has been muted for **{}**" .format(member.mention, reason)) return overwrite = discord.PermissionsOverwrite(send_messages=False) newRole = await guild.create_role(name="Muted") for channel in guild.text_channels: await channel.set_permissions(newRole, overwrite=overwrite) await member.add_roles(newRole) await ctx.send("{} was muted for {}" .format(member.mention,ctx.author.mention, reason)) await ctx.message.delete() @commands.command() @commands.has_permissions(manage_roles=True) async def unmute(self, ctx, member : discord.Member): guild = ctx.guild for role in guild.roles: if role.name == "Muted": await member.remove_roles(role) await ctx.send ("{} has been unmuted" .format(member.mention,ctx.author.mention)) return await ctx.message.delete() @commands.command() @commands.has_permissions(manage_messages=True) async def clear(self, ctx, amount =5): await ctx.channel.purge(limit=amount) await ctx.send(f'I have cleared **{amount}** messages') @commands.command() @commands.has_permissions(manage_roles=True) async def warn(self, ctx, member : discord.Member = None, *, reason=None): if member == None: await ctx.send('Who do you want to warn?') else: embed=discord.Embed( title=f'{member.name} has been warned!', description=f'Reason: {reason}', colour=discord.Colour.red() ) embed.set_thumbnail(url='https://media.discordapp.net/attachments/696121556119715890/707310613671706705/warning.png?width=784&height=519') await ctx.send(embed=embed) await ctx.message.delete() @commands.command() @commands.has_permissions(kick_members=True) async def kick(self, ctx, member : discord.Member = None, *, reason=None): if member == None: await ctx.send("Who do you want to kick?") else: await member.kick(reason=reason) embed=discord.Embed( title=f'{member.name} has been kicked', description=f'Reason: {reason}', colour=discord.Colour.red() ) await ctx.send(embed=embed) await ctx.message.delete() @commands.command() @commands.has_permissions(ban_members=True) async def ban(self, ctx, member : discord.Member = None, *, reason=None): if member == None: await ctx.send("Who do you want to ban?") else: await member.ban(reason=reason) embed=discord.Embed( title=f'{member.name} has been banned', description=f'Reason: {reason}', colour=discord.Colour.red() ) embed.set_thumbnail(url='https://media.discordapp.net/attachments/625842127284469760/704711229675012136/6623_banhammer.png') await ctx.send(embed=embed) await ctx.message.delete() def setup(bot): bot.add_cog(utility(bot))
PHP
UTF-8
940
3.109375
3
[]
no_license
<?php require_once __DIR__ . "/User.php"; class Customer extends User { private $country; private $city; private $zipCode; private $address; private $age; private $delivery; function __construct($username, $password, $mail, $country, $city, $zipCode, $address ) { parent::__construct($username, $password, $mail); $this->country = $country; $this->city = $city; $this->zipCode = $zipCode; $this->address = $address; // $this->age = $age; // $this->delivery = $delivery; // non ho capito } public function setDelivery($age) { if($age >= 65) { $this->age = $age; $this->delivery = 0; } else { $this->age = $age; $this->delivery = 5; } } } ?>
Java
UTF-8
4,710
2.25
2
[ "BSD-3-Clause" ]
permissive
package com.openxc.ford.mHealth.demo.tasks; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.os.AsyncTask; import com.openxc.ford.mHealth.demo.AppLog; import com.openxc.ford.mHealth.demo.Constants; import com.openxc.ford.mHealth.demo.model.Patient; import com.openxc.ford.mHealth.demo.web.WebService; public class PatientsRetriverTask extends AsyncTask<String, Patient, ArrayList<Patient>> { private final String TAG = AppLog.getClassName(); private final String TAG_ID = "uUid"; private final String TAG_NAME = "name"; private final String TAG_ADDRESS = "address1"; private final String TAG_VILLAGE = "village"; private final String TAG_POSTAL_CODE = "postalCode"; private final String TAG_CONTACT_NO = "phone"; private int tag = -1; private String value = null; public PatientsRetriverTask(int tag, String value) { this.tag = tag; this.value = value; } @Override protected void onPreExecute() { AppLog.enter(TAG, AppLog.getMethodName()); super.onPreExecute(); try { AppLog.info(TAG, "Waitting... for updating records."); Thread.sleep(1000); AppLog.info(TAG, "Records updated."); } catch (InterruptedException e) { e.printStackTrace(); } AppLog.exit(TAG, AppLog.getMethodName()); } @Override protected ArrayList<Patient> doInBackground(String... params) { AppLog.enter(TAG, AppLog.getMethodName()); AppLog.info(TAG, "Tag : " + tag); AppLog.info(TAG, "Value : " + value); String requestURL = null; switch (tag) { case Constants.TAG_PATIENT_BY_NAME: requestURL = Constants.URL_PATIENT_BY_PATIENT_NAME + value; break; case Constants.TAG_PATIENT_BY_POSTAL_CODE: requestURL = Constants.URL_PATIENT_BY_POSTAL_CODE + value; break; case Constants.TAG_PATIENT_BY_VILLAGE: requestURL = Constants.URL_PATIENT_BY_VILLAGE + value; break; default: break; } AppLog.info(TAG, "Request URL : " + requestURL); String responseString = WebService.getInstance().request(requestURL); AppLog.info(TAG, "Response String : " + responseString); ArrayList<Patient> patientsList = null; try { if (responseString.contains("object not found") || responseString.equalsIgnoreCase("[]")) { } else { patientsList = new ArrayList<Patient>(); JSONArray jsonArray = new JSONArray(responseString); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObj = jsonArray.getJSONObject(i); AppLog.info(TAG, "JSON Object : " + jsonObj); Patient patient = new Patient(); if (Constants.TAG_PATIENT_BY_NAME == tag) { try { String uuid = jsonObj.getString("uuid"); JSONObject jsonPerson = jsonObj .getJSONObject("person"); String name = jsonPerson.getString("display"); JSONObject jsonAddress = jsonPerson .getJSONObject("preferredAddress"); String address = jsonAddress.getString("address1"); String postal = jsonAddress.getString("postalCode"); String village = jsonAddress .getString("cityVillage"); JSONArray jsonContactAttribute = jsonPerson .getJSONArray("attributes"); JSONObject jsonContact = jsonContactAttribute .getJSONObject(0); String contact = jsonContact.getString("value"); patient.setId(uuid); patient.setName(name); patient.setAddress(address); patient.setVillage(village); patient.setPostalCode(postal); patient.setContactNumber(contact); } catch (JSONException e) { AppLog.error(TAG, "JSONException : " + e.toString()); continue; } } else { try { patient.setId(jsonObj.getString(TAG_ID)); patient.setName(jsonObj.getString(TAG_NAME)); patient.setAddress(jsonObj.getString(TAG_ADDRESS)); patient.setVillage(jsonObj.getString(TAG_VILLAGE)); patient.setPostalCode(jsonObj .getString(TAG_POSTAL_CODE)); patient.setContactNumber(jsonObj .getString(TAG_CONTACT_NO)); } catch (JSONException e) { AppLog.error(TAG, "JSONException : " + e.toString()); continue; } } AppLog.info(TAG, "Patient : " + patient); patientsList.add(patient); } } } catch (Exception e) { AppLog.error(TAG, "Error : " + e.toString()); return null; } AppLog.info(TAG, "Patient List : " + patientsList); AppLog.exit(TAG, AppLog.getMethodName()); return patientsList; } @Override protected void onPostExecute(ArrayList<Patient> patientsList) { AppLog.enter(TAG, AppLog.getMethodName()); super.onPostExecute(patientsList); AppLog.exit(TAG, AppLog.getMethodName()); } }
Java
UTF-8
1,094
2.71875
3
[]
no_license
import javax.servlet.*; import javax.servlet.http.*; // расширение javax.servlet для http import java.io.*; import java.io.IOException; import java.io.PrintWriter; import java.util.Enumeration; public class Bbb extends HttpServlet implements Servlet { protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Enumeration<String> headerNames = req.getHeaderNames(); PrintWriter pw = resp.getWriter(); pw.println("Headers from Servlet Aaa: "); while (headerNames.hasMoreElements()) { String key = headerNames.nextElement(); String value = req.getHeader(key); pw.println(key + ": " + value); } pw.println(); pw.println("Params from ServletA:"); pw.println("Param1: " + req.getParameter("Param1")); pw.println("Param2: " + req.getParameter("Param2")); pw.println("Param3: " + req.getParameter("Param3")); resp.setHeader("Header1", "Header1"); resp.setHeader("Header2", "Header2"); } }
Java
UTF-8
14,079
2.15625
2
[ "Apache-2.0" ]
permissive
package org.gbif.occurrence.processor.interpreting; import org.gbif.api.model.occurrence.Occurrence; import org.gbif.api.model.occurrence.VerbatimOccurrence; import org.gbif.api.vocabulary.OccurrenceIssue; import org.gbif.common.parsers.core.ParseResult; import org.gbif.dwc.terms.DcTerm; import org.gbif.dwc.terms.DwcTerm; import org.gbif.occurrence.processor.interpreting.result.DateYearMonthDay; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import com.google.common.collect.Range; import org.apache.commons.lang3.time.DateFormatUtils; import org.apache.commons.lang3.time.FastDateFormat; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class TemporalInterpreterTest { @Test public void testAllDates() { VerbatimOccurrence v = new VerbatimOccurrence(); v.setVerbatimField(DwcTerm.year, "1879"); v.setVerbatimField(DwcTerm.month, "11 "); v.setVerbatimField(DwcTerm.day, "1"); v.setVerbatimField(DwcTerm.eventDate, "1.11.1879"); v.setVerbatimField(DwcTerm.dateIdentified, "2012-01-11"); v.setVerbatimField(DcTerm.modified, "2014-01-11"); Occurrence o = new Occurrence(); TemporalInterpreter.interpretTemporal(v, o); assertDate("2014-01-11", o.getModified()); assertDate("2012-01-11", o.getDateIdentified()); assertDate("1879-11-01", o.getEventDate()); assertEquals(1879, o.getYear().intValue()); assertEquals(11, o.getMonth().intValue()); assertEquals(1, o.getDay().intValue()); assertEquals(0, o.getIssues().size()); } @Test public void testLikelyYearRanges() { assertTrue(TemporalInterpreter.VALID_RECORDED_YEAR_RANGE.contains(1900)); assertTrue(TemporalInterpreter.VALID_RECORDED_YEAR_RANGE.contains(1901)); assertTrue(TemporalInterpreter.VALID_RECORDED_YEAR_RANGE.contains(2010)); assertTrue(TemporalInterpreter.VALID_RECORDED_YEAR_RANGE.contains(2014)); assertFalse(TemporalInterpreter.VALID_RECORDED_YEAR_RANGE.contains(Calendar.getInstance().get(Calendar.YEAR) + 1)); assertFalse(TemporalInterpreter.VALID_RECORDED_YEAR_RANGE.contains(1580)); assertFalse(TemporalInterpreter.VALID_RECORDED_YEAR_RANGE.contains(900)); assertFalse(TemporalInterpreter.VALID_RECORDED_YEAR_RANGE.contains(90)); assertFalse(TemporalInterpreter.VALID_RECORDED_YEAR_RANGE.contains(0)); assertFalse(TemporalInterpreter.VALID_RECORDED_YEAR_RANGE.contains(-1900)); assertFalse(TemporalInterpreter.VALID_RECORDED_YEAR_RANGE.contains(2100)); } @Test public void testLikelyIdentified() { VerbatimOccurrence v = new VerbatimOccurrence(); v.setVerbatimField(DwcTerm.year, "1879"); v.setVerbatimField(DwcTerm.month, "11 "); v.setVerbatimField(DwcTerm.day, "1"); v.setVerbatimField(DwcTerm.eventDate, "1.11.1879"); v.setVerbatimField(DcTerm.modified, "2014-01-11"); Occurrence o = new Occurrence(); v.setVerbatimField(DwcTerm.dateIdentified, "1987-01-31"); TemporalInterpreter.interpretTemporal(v, o); assertEquals(0, o.getIssues().size()); v.setVerbatimField(DwcTerm.dateIdentified, "1787-03-27"); TemporalInterpreter.interpretTemporal(v, o); assertEquals(0, o.getIssues().size()); v.setVerbatimField(DwcTerm.dateIdentified, "2014-01-11"); TemporalInterpreter.interpretTemporal(v, o); assertEquals(0, o.getIssues().size()); Calendar cal = Calendar.getInstance(); v.setVerbatimField(DwcTerm.dateIdentified, (cal.get(Calendar.YEAR)+1) + "-01-11"); TemporalInterpreter.interpretTemporal(v, o); assertEquals(1, o.getIssues().size()); assertEquals(OccurrenceIssue.IDENTIFIED_DATE_UNLIKELY, o.getIssues().iterator().next()); v.setVerbatimField(DwcTerm.dateIdentified, "1599-01-11"); TemporalInterpreter.interpretTemporal(v, o); assertEquals(1, o.getIssues().size()); assertEquals(OccurrenceIssue.IDENTIFIED_DATE_UNLIKELY, o.getIssues().iterator().next()); } @Test public void testLikelyModified() { VerbatimOccurrence v = new VerbatimOccurrence(); v.setVerbatimField(DwcTerm.year, "1879"); v.setVerbatimField(DwcTerm.month, "11 "); v.setVerbatimField(DwcTerm.day, "1"); v.setVerbatimField(DwcTerm.eventDate, "1.11.1879"); v.setVerbatimField(DwcTerm.dateIdentified, "1987-01-31"); Occurrence o = new Occurrence(); v.setVerbatimField(DcTerm.modified, "2014-01-11"); TemporalInterpreter.interpretTemporal(v, o); assertEquals(0, o.getIssues().size()); Calendar cal = Calendar.getInstance(); v.setVerbatimField(DcTerm.modified, (cal.get(Calendar.YEAR) + 1) + "-01-11"); TemporalInterpreter.interpretTemporal(v, o); assertEquals(1, o.getIssues().size()); assertEquals(OccurrenceIssue.MODIFIED_DATE_UNLIKELY, o.getIssues().iterator().next()); v.setVerbatimField(DcTerm.modified, "1969-12-31"); TemporalInterpreter.interpretTemporal(v, o); assertEquals(1, o.getIssues().size()); assertEquals(OccurrenceIssue.MODIFIED_DATE_UNLIKELY, o.getIssues().iterator().next()); } @Test public void testLikelyRecorded() { VerbatimOccurrence v = new VerbatimOccurrence(); Calendar cal = Calendar.getInstance(); v.setVerbatimField(DwcTerm.eventDate, "24.12." + (cal.get(Calendar.YEAR) + 1)); Occurrence o = new Occurrence(); TemporalInterpreter.interpretTemporal(v, o); assertEquals(1, o.getIssues().size()); assertEquals(OccurrenceIssue.RECORDED_DATE_UNLIKELY, o.getIssues().iterator().next()); } @Test public void testGoodDate() { ParseResult<DateYearMonthDay> result = interpretRecordedDate("1984", "3", "22", null); assertResult(1984, 3, 22, "1984-03-22", result); } @Test public void testGoodOldDate() { ParseResult<DateYearMonthDay> result = interpretRecordedDate("1957", "3", "22", null); assertResult(1957, 3, 22, "1957-03-22", result); } @Test public void test0Month() { ParseResult<DateYearMonthDay> result = interpretRecordedDate("1984", "0", "22", null); assertResult(1984, null, 22, null, result); } @Test public void testOldYear() { ParseResult<DateYearMonthDay> result = interpretRecordedDate("1599", "3", "22", null); assertNullResult(result); } @Test public void testFutureYear() { ParseResult<DateYearMonthDay> result = interpretRecordedDate("2100", "3", "22", null); assertNullResult(result); } @Test public void testBadDay() { ParseResult<DateYearMonthDay> result = interpretRecordedDate("1984", "3", "32", null); assertResult(1984, 3, null, null, result); } @Test public void testStringGood() { ParseResult<DateYearMonthDay> result = interpretRecordedDate(null, null, null, "1984-03-22"); assertResult(1984, 3, 22, "1984-03-22", result); } @Test public void testStringTimestamp() { ParseResult<DateYearMonthDay> result = interpretRecordedDate(null, null, null, "1984-03-22T00:00"); assertResult(1984, 3, 22, "1984-03-22", result); } @Test public void testStringBad() { ParseResult<DateYearMonthDay> result = interpretRecordedDate(null, null, null, "22-17-1984"); assertNullResult(result); } @Test public void testStringWins() { ParseResult<DateYearMonthDay> result = interpretRecordedDate("1984", "3", null, "1984-03-22"); assertResult(1984, 3, 22, "1984-03-22", result); } @Test public void testStringLoses() { ParseResult<DateYearMonthDay> result = interpretRecordedDate("1984", "3", null, "22-17-1984"); assertResult(1984, 3, null, null, result); } // these two tests demonstrate the problem from POR-2120 // @Test // public void testOnlyYear() { // ParseResult<DateYearMonthDay> result = interpretRecordedDate("1984", null, null, null); // assertResult(1984, null, null, null, result); // // result = interpretRecordedDate(null, null, null, "1984"); // assertResult(1984, null, null, null, result); // // result = interpretRecordedDate("1984", null, null, "1984"); // assertResult(1984, null, null, null, result); // } // // @Test // public void testYearWithZeros() { // ParseResult<DateYearMonthDay> result = interpretRecordedDate("1984", "0", "0", "1984"); // System.out.println("Got result: " + result.getPayload().getDate()); // assertResult(1984, null, null, null, result); // // result = interpretRecordedDate(null, null, null, "1984"); // System.out.println("Got result: " + result.getPayload().getDate()); // assertResult(1984, null, null, null, result); // // result = interpretRecordedDate("1984", "0", "0", null); // assertResult(1984, null, null, null, result); // // result = interpretRecordedDate(null, null, null, "0-0-1984"); // assertEquals(ParseResult.STATUS.FAIL, result.getStatus()); // assertNull(result.getPayload()); // } // // @Test // public void testYearMonthNoDay() { // ParseResult<DateYearMonthDay> result = interpretRecordedDate("1984", "3", null, null); // System.out.println("Got result: " + result.getPayload().getDate()); // assertResult(1984, 3, null, null, result); // // result = interpretRecordedDate("1984", "3", null, "1984-03"); // System.out.println("Got result: " + result.getPayload().getDate()); // assertResult(1984, 3, null, null, result); // // result = interpretRecordedDate(null, null, null, "1984-03"); // System.out.println("Got result: " + result.getPayload().getDate()); // assertResult(1984, 3, null, null, result); // } @Test public void testOnlyMonth() { ParseResult<DateYearMonthDay> result = interpretRecordedDate(null, "3", null, null); assertResult(null, 3, null, null, result); } @Test public void testOnlyDay() { ParseResult<DateYearMonthDay> result = interpretRecordedDate(null, null, "23", null); assertResult(null, null, 23, null, result); } /** * Tests that a date representing 'now' is interpreted with CONFIDENCE.DEFINITE even after TemporalInterpreter * was instantiated. See POR-2860. */ @Test public void testNow() { // Makes sure the static content is loaded ParseResult<DateYearMonthDay> result = interpretEventDate(DateFormatUtils.ISO_DATETIME_FORMAT.format(Calendar.getInstance())); assertEquals(ParseResult.CONFIDENCE.DEFINITE, result.getConfidence()); // Sorry for this Thread.sleep, we need to run the TemporalInterpreter at least 1 second later until // we refactor to inject a Calendar of we move to new Java 8 Date/Time API try { Thread.sleep(1000); } catch (InterruptedException e) { fail(e.getMessage()); } Calendar cal = Calendar.getInstance(); result = interpretEventDate(DateFormatUtils.ISO_DATETIME_FORMAT.format(cal.getTime())); assertEquals(ParseResult.CONFIDENCE.DEFINITE, result.getConfidence()); } @Test public void testAllNulls() { ParseResult<DateYearMonthDay> result = interpretRecordedDate(null, null, null, null); assertNullResult(result); } @Test public void testDateStrings() { assertValidDate("1999-07-19", "1999-07-19"); assertValidDate("1999-07-19", "1999-07-19T00:00:00"); assertValidDate("1999-07-19", "19-07-1999"); assertValidDate("1999-07-19", "07-19-1999"); assertValidDate("1999-09-07", "07-09-1999"); assertValidDate("1999-06-07", "07-06-1999"); assertValidDate("1999-07-19", "19/7/1999"); assertValidDate("1999-07-19", "1999.7.19"); assertValidDate("1999-07-19", "19.7.1999"); assertValidDate("1999-07-19", "19.7.1999"); assertValidDate("1999-07-19", "19990719"); assertValidDate("2012-05-06", "20120506"); } private void assertValidDate(String expected, String input) { assertDate(expected, interpretRecordedDate(null, null, null, input).getPayload()); } /** * @param expected expected date in ISO yyyy-MM-dd format */ private void assertDate(String expected, DateYearMonthDay result) { if (expected == null) { if (result != null) { assertNull(result.getDate()); } } else { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); assertNotNull("Missing date", result.getDate()); assertEquals(expected, sdf.format(result.getDate())); } } /** * @param expected expected date in ISO yyyy-MM-dd format */ private void assertDate(String expected, Date result) { if (expected == null) { assertNull(result); } else { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); assertNotNull("Missing date", result); assertEquals(expected, sdf.format(result)); } } private void assertInts(Integer expected, Integer x) { if (expected == null) { assertNull(x); } else { assertEquals(expected, x); } } private void assertResult(Integer y, Integer m, Integer d, String date, ParseResult<DateYearMonthDay> result) { assertNotNull(result); assertInts(y, result.getPayload().getYear()); assertInts(m, result.getPayload().getMonth()); assertInts(d, result.getPayload().getDay()); assertDate(date, result.getPayload()); } private void assertNullResult(ParseResult<DateYearMonthDay> result) { assertNotNull(result); assertNull(result.getPayload()); } private ParseResult<DateYearMonthDay> interpretRecordedDate(String y, String m, String d, String date) { VerbatimOccurrence v = new VerbatimOccurrence(); v.setVerbatimField(DwcTerm.year, y); v.setVerbatimField(DwcTerm.month, m); v.setVerbatimField(DwcTerm.day, d); v.setVerbatimField(DwcTerm.eventDate, date); return TemporalInterpreter.interpretRecordedDate(v); } private ParseResult<DateYearMonthDay> interpretEventDate(String date) { VerbatimOccurrence v = new VerbatimOccurrence(); v.setVerbatimField(DwcTerm.eventDate, date); return TemporalInterpreter.interpretRecordedDate(v); } }
C#
UTF-8
3,430
3.03125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; namespace Chessington.GameEngine.Pieces { public class Pawn : Piece { public Pawn(Player player) : base(player) { } public Square Position { get; set; } public override IEnumerable<Square> GetAvailableMoves(Board board) { List<Square> availableMoves = new List<Square>(); var currentSquare = board.FindPiece(this); switch (Player) { case Player.Black: if (board.FindPosition(currentSquare.Row + 1, currentSquare.Col) == null) { availableMoves = AddMove(new Square(currentSquare.Row + 1, currentSquare.Col), availableMoves, board); if (FirstMove && board.FindPosition(currentSquare.Row + 2, currentSquare.Col) == null) { availableMoves = AddMove(new Square(currentSquare.Row + 2, currentSquare.Col), availableMoves, board); } } if (board.FindPosition(currentSquare.Row + 1, currentSquare.Col + 1) != null && board.FindPosition(currentSquare.Row + 1, currentSquare.Col + 1).Player == Player.White) { availableMoves = AddMove(new Square(currentSquare.Row + 1, currentSquare.Col + 1), availableMoves, board); } if (board.FindPosition(currentSquare.Row + 1, currentSquare.Col - 1) != null && board.FindPosition(currentSquare.Row + 1, currentSquare.Col - 1).Player == Player.White) { availableMoves = AddMove(new Square(currentSquare.Row + 1, currentSquare.Col - 1), availableMoves, board); } break; case Player.White: if (board.FindPosition(currentSquare.Row - 1, currentSquare.Col) == null) { availableMoves = AddMove(new Square(currentSquare.Row - 1, currentSquare.Col), availableMoves, board); if (FirstMove && board.FindPosition(currentSquare.Row - 2, currentSquare.Col) == null) { availableMoves = AddMove(new Square(currentSquare.Row - 2, currentSquare.Col), availableMoves, board); } } if (board.FindPosition(currentSquare.Row - 1, currentSquare.Col + 1) != null && board.FindPosition(currentSquare.Row - 1, currentSquare.Col + 1).Player == Player.Black) { availableMoves = AddMove(new Square(currentSquare.Row - 1, currentSquare.Col + 1), availableMoves, board); } if (board.FindPosition(currentSquare.Row - 1, currentSquare.Col - 1) != null && board.FindPosition(currentSquare.Row - 1, currentSquare.Col - 1).Player == Player.Black) { availableMoves = AddMove(new Square(currentSquare.Row - 1, currentSquare.Col - 1), availableMoves, board); } break; } return availableMoves; } } }
PHP
UTF-8
2,897
2.625
3
[ "LicenseRef-scancode-other-permissive" ]
permissive
<?php $student_id = $_POST['student_id']; $student_name = $_POST['student_name']; $student_fname = $_POST['student_fname']; $student_mname = $_POST['student_mname']; $gender = $_POST['gender']; $address = $_POST['address']; $mobile = $_POST['mobile']; $email = $_POST['email']; $class = $_POST['class']; $roll = $_POST['roll']; $section = $_POST['section']; $ctname = $_POST['ctname']; $result = $_POST['result']; if (!empty($student_id) || !empty($student_name) || !empty($student_fname) || !empty($student_mname) || !empty($gender) || !empty($address) || !empty($mobile) || !empty($email)|| !empty($class) || !empty($roll) || !empty($section) || !empty($ctname) || !empty($result)) { $host = "localhost"; $dbUsername = "root"; $dbPassword = ""; $dbname = "info"; //create connection $conn = new mysqli($host, $dbUsername, $dbPassword, $dbname); if (mysqli_connect_error()) { die('Connect Error('. mysqli_connect_errno().')'. mysqli_connect_error()); } else { $SELECT = "SELECT email FROM information WHERE email = ? LIMIT 1"; $INSERT = "INSERT INTO information (student_id,student_name,student_fname,student_mname,gender,address,mobile,email,class,roll,section,ctname,result) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; //Prepare statement $stmt = $conn->prepare($SELECT); $stmt->bind_param("s", $email); $stmt->execute(); $stmt->bind_result($email); $stmt->store_result(); $rnum = $stmt->num_rows; if ($rnum==0) { $stmt->close(); $stmt = $conn->prepare($INSERT); $stmt->bind_param("sssssssssssss", $student_id, $student_name, $student_fname, $student_mname,$gender, $address, $mobile, $email, $class, $roll, $section, $ctname, $result); $stmt->execute(); echo "New record inserted sucessfully"; } else { echo "Someone already register using this email"; } $stmt->close(); $conn->close(); } } else { echo "All field are required"; die(); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>PDF||Generator</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"> <link rel="stylesheet" href="style.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <form action="studentinfo.html" method="POST"> <button class="btn btn-danger" type="submit"><- Go back</button> </form> </div> </body> </html>
JavaScript
UTF-8
6,169
2.59375
3
[]
no_license
let isProcessPending = false; // for stopping multiple request simultaneously let recordsPerPage = 2; // you can set as you want to get data per ajax request let recordsOffset = 0; // get data from given no let recordsTotal = 0; // store total number of record let tweets_list = []; //get first time article as page load loadTweets({ action: "initialization" }); function loadTweets(params) { if (!!params && params.action === "VIEW_MORE") { recordsOffset = recordsOffset + recordsPerPage; } $.ajax({ type: "GET", url: "/explore/tweets", data: { recordsPerPage: recordsPerPage, recordsOffset: recordsOffset, }, success: function (response) { isProcessPending = false; // for making process done so new data can be fetched on scroll if (!!params && params.action === "VIEW_MORE") { tweets_list = response.data.tweets_list; } else { if (recordsOffset === 0) { tweets_list = response.data.tweets_list; recordsTotal = response.data.recordsTotal; } } console.log("Tweet list"); console.log(tweets_list); // form this you can append or manage html as you want tweets_list.forEach(function (tweet) { appendinHTML(tweet); }); }, error: function (xhr) { //Do Something to handle error isProcessPending = false; // for make process done so new data can be get on scroll }, }); } //on scroll new get data $(window).scroll(function () { let scrollPercent = Math.round( ($(window).scrollTop() / ($(document).height() - $(window).height())) * 100 ); // get new data only if scroll bar is greater 70% of screen if (scrollPercent > 70) { //this condition only satisfy ony one pending ajax completed and records offset is less than total record if (isProcessPending === false && recordsOffset < recordsTotal) { isProcessPending = true; loadTweets({ action: "VIEW_MORE" }); } } }); var tweetid; function appendinHTML(tweet) { let userid = $("#userId").text(); console.log(tweet); let exploreContainer = $("#exploreContainer"); exploreContainer.append( $(` <div class="tweetCards homepage_tweets mt-4 mb-4"> <div class="tweet_heading clearfix"> <div class="tweet_card_profile_pic d-inline-block"> <img src="${tweet.author.profile_pic}" alt="Profile Picture"> </div> <div class="tweet_username d-inline-block"> <p> <span class="font-weight-bold"></span> <br> <a href="/profile/${tweet.author.username}"> <span class="text-muted usernameLink"> @${tweet.author.username} </span> </a> </p> </div> <div class="d-inline-block float-right"> <small class="text-muted"> <span>${tweet.dateTime}</span> </small> </div> </div> <p class="tweetContent lead"> ${tweet.content} </p> <div class="actionButtons"> ${if(userid )} <button class="btn btn-primary liked likeBtn" tweet_id="${tweet._id}">Liked</button> {{else}} <button class="likeBtn btn btn-primary" tweet_id="${tweet._id}">Like</button> {{/ifSet}} <small class="no_of_likes" class="text-muted"> <span id="no_of_likes${tweet._id}">${tweet.likes.length}</span> likes </small> {{!-- =============== --}} {{!-- ========================= --}} <small> <a href="" class="text-muted" class="readComments" tweet_id="${tweet._id}"> <span>${tweet.comments.length}</span> Comments </a> </small> </div> <div class="commentsWrapper " id="commentsWrapper${tweet._id}"> <div class="comments_container d-flex"> <div class="tweet_card_profile_pic d-inline-block"> <img src="{{@root.currentUser.profile_pic}}" alt="Profile Picture"> </div> <div class="commentInfo pl-2"> <div class="user_info"> <span class="font-weight-bold"> {{@root.currentUser.name}} </span> <a href="/profile/{{@root.user.username}}"> <span class="text-muted usernameLink"> @{{@root.currentUser.username}} </span> </a> </div> <div class="user_comment"> <p> <input type="text" id="inputComment{{tweet._id}}" tweet_id="{{tweet._id}}" placeholder="Write a Comment...."> <button class="btn-sm btn btn-success commentPostBtn" tweet_id="{{tweet._id}}">Post</button> </p> </div> </div> </div> </div> </div>`) ); } function addComment(comment) { console.log("called"); let commentWrapper = $("#commentsWrapper" + tweetid); console.log(commentWrapper); commentWrapper.append( $( `<div class=" comments_container d-flex"> <div class=" tweet_card_profile_pic d-inline-block"> <img src="${comment.author.profile_pic}" alt="Profile Picture"> </div> <div class="commentInfo pl-2"> <div class="user_info"> <span class="font-weight-bold"> ${comment.author.name} </span> <a href="/profile/${comment.author.username}"> <span class="text-muted usernameLink"> @${comment.author.username} </span> </a> </div> <div class="user_comment"> <p> ${comment.content} </p> </div> </div> </div>` ) ); }
Java
UTF-8
179
2.890625
3
[]
no_license
public class Compra { protected double valorCompra; public Compra(Double valor) { this.valorCompra += valor; } public double total() { return this.valorCompra; } }
JavaScript
UTF-8
6,436
2.515625
3
[]
no_license
/* * This file holds all the redirections services * */ var baseURL; // holds the base url of the website $(document).ready(function(){ //First choice for local host, Second choice for remote Server baseURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname.split('/')[1]; //baseURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname.split('/')[1] + "/auctionbay"; $("a.login-link").on("click",function(event){ //console.log("login btn"); event.preventDefault(); window.location = baseURL+"/login-signup"; }); $("a.profile-link").on("click",function(event){ //console.log("login btn"); event.preventDefault(); var patharray = window.location.pathname.split( '/' ); var location = baseURL + "/" + patharray[2] + "/" + patharray[3] + "/profile"; window.location = location; }); $("a.view-auctions-ref").on("click",function(event){ event.preventDefault(); //console.log("window.location.href: " + window.location.href) //console.log("baseURL: " + baseURL) var location = window.location.href; var patharray = window.location.pathname.split( '/' ); if(patharray.length >= 4) { //console.log("path: " + patharray) location = baseURL + "/" + patharray[2] + "/" + patharray[3] + "/auctions"; window.location = location; } else { window.location = baseURL + "/auctions"; } var lastChar = location.substr(location.length - 1); }); $("a.rates-link").on("click",function(event){ event.preventDefault(); //console.log("window.location.href: " + window.location.href) //console.log("baseURL: " + baseURL) var location = window.location.href; var patharray = window.location.pathname.split( '/' ); if(patharray.length >= 4) { //console.log("path: " + patharray) location = baseURL + "/" + patharray[2] + "/" + patharray[3] + "/rates"; window.location = location; } else { window.location = baseURL + "/rates"; } }); /*$("a.rates-ref").on("click",function(event){ event.preventDefault(); console.log("window.location.href: " + window.location.href) console.log("baseURL: " + baseURL) var location = window.location.href; var patharray = window.location.pathname.split( '/' ); if(patharray.length >= 4) { console.log("path: " + patharray) location = baseURL + "/" + patharray[2] + "/" + patharray[3] + "/rates"; window.location = location; } else { window.location = baseURL + "/rates"; } });*/ $("a.messages-link").on("click",function(event){ event.preventDefault(); //console.log("window.location.href: " + window.location.href) //console.log("baseURL: " + baseURL) var location = window.location.href; var patharray = window.location.pathname.split( '/' ); if(patharray.length >= 4) { //console.log("path: " + patharray) location = baseURL + "/" + patharray[2] + "/" + patharray[3] + "/conversation"; window.location = location; } else { window.location = baseURL + "/conversation"; } }); $("a.create-auction-ref").on("click",function(event){ event.preventDefault(); //console.log("window.location.href: " + window.location.href) //console.log("baseURL: " + baseURL) var location = window.location.href; var patharray = window.location.pathname.split( '/' ); if(patharray.length >= 4) { //console.log("path: " + patharray) location = baseURL + "/" + patharray[2] + "/" + patharray[3] + "/manage-auctions"; window.location = location; } else { window.location = baseURL + "/manage-auctions"; } var lastChar = location.substr(location.length - 1); }); $("a.contact-ref").on("click",function(event){ //console.log("contact btn"); event.preventDefault(); window.location = baseURL+"/contact"; }); $("a.index-link").click(function(event){ //console.log("home btn"); event.preventDefault(); var result = checkUser(); if(result == 0){ document.location.href=baseURL; } else { var user = getUser(); window.location = baseURL + "/user/"+user; } }); $("a.login-panel-link").click(function(event){ event.preventDefault(); window.location = baseURL+"/login-signup"; }); $('a.contact-link').click(function(event){ event.preventDefault(); //console.log("window.location.href: " + window.location.href) //console.log("baseURL: " + baseURL) var location = window.location.href; var patharray = window.location.pathname.split( '/' ); if(patharray.length >= 4) { //console.log("path: " + patharray) location = baseURL + "/" + patharray[2] + "/" + patharray[3] + "/contact"; window.location = location; } else { window.location = baseURL + "/contact"; } }) $('a.contact-panel-link').click(function(event){ event.preventDefault(); var result = checkUser(); if(result == 0){ window.location = baseURL+"/contact" } else { var user = getUser(); window.location = baseURL + "/user/"+user+"/contact"; } }); $('a.mailbox-panel-link').click(function(event){ event.preventDefault(); //console.log("window.location.href: " + window.location.href) //console.log("baseURL: " + baseURL) var location = window.location.href; var lastChar = location.substr(location.length - 1); if(lastChar == "/"){ window.location = window.location.href+"conversation"; } else { window.location = window.location.href+"/conversation"; } }); $('a.view-auctions-panel-link').click(function(event){ event.preventDefault(); //console.log("window.location.href: " + window.location.href) //console.log("baseURL: " + baseURL) var location = window.location.href; var lastChar = location.substr(location.length - 1); if(lastChar == "/"){ window.location = window.location.href+"auctions"; } else { window.location = window.location.href+"/auctions"; } }); $('a.manage-panel-link').click(function(event){ event.preventDefault(); window.location = window.location.href+"/manage-auctions"; }); $('a.log-out').click(function(event){ event.preventDefault(); window.location = baseURL; }) function checkUser(){ var user="user"; var urlpath = window.location.href; if(urlpath.indexOf(user) == -1){ /* if not found then it return -1 then it is a guest */ return 0; } else { // it is registered user return 1; } } });
Python
UTF-8
338
3.03125
3
[]
no_license
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ res = 0 cur = 0 for i in range(1, len(prices)): cur = cur + prices[i] - prices[i - 1] cur = max(0, cur) res = max(res, cur) return res
Java
UTF-8
1,726
2.484375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package JPA1; import javafx.stage.Stage; import static org.testng.Assert.*; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * * @author PC */ public class JpaControlerNGTest { public JpaControlerNGTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @BeforeMethod public void setUpMethod() throws Exception { } @AfterMethod public void tearDownMethod() throws Exception { } /** * Test of start method, of class JpaControler. */ @Test public void testStart() throws Exception { System.out.println("start"); Stage primaryStage = null; JpaControler instance = new JpaControler(); instance.start(primaryStage); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of main method, of class JpaControler. */ @Test public void testMain() { System.out.println("main"); String[] args = null; JpaControler.main(args); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } }
C++
UTF-8
14,231
2.546875
3
[]
no_license
#include "sensirion_sf04.h" //=========================================================================== // Default constructor SF04::SF04(I2C &i2c, int i2cAddress, int calField, int resolution) : i2c(i2c), mi2cAddress(i2cAddress << 1) //=========================================================================== { u8t error = false; ready = false; int16_t wait = 200; // Unsure why, but without a wait between commands the values read out don't make sense. wait_us(wait); error |= softReset(); wait_us(wait); error |= ReadSerialNumber(&serialNumber); wait_us(wait); error |= ReadScaleFactor(&scaleFactor); wait_us(wait); error |= ReadFlowUnit(flowUnitStr); wait_us(wait); error |= setMeasResolution(resolution); // 9-16 bit wait_us(wait); error |= setCalibrationField(calField); wait_us(wait); if (error == false) { ready = true; } } //=========================================================================== // Set measurement resolution (9-16 bit), format is eSF04_RES_12BIT u8t SF04::setMeasResolution(u16t resolution) //=========================================================================== { ready = false; u8t error = false; //variable for error code nt16 registerValue; // variable for register value switch(resolution) { case 9 : resolution = eSF04_RES_9BIT; break; case 10 : resolution = eSF04_RES_10BIT; break; case 11 : resolution = eSF04_RES_11BIT; break; case 12 : resolution = eSF04_RES_12BIT; break; case 13 : resolution = eSF04_RES_13BIT; break; case 14 : resolution = eSF04_RES_14BIT; break; case 15 : resolution = eSF04_RES_15BIT; break; case 16 : resolution = eSF04_RES_16BIT; break; default: resolution = eSF04_RES_16BIT; break; } ReadRegister(SF04_ADV_USER_REG,&registerValue); // Read out current register value registerValue.u16 = (registerValue.u16 & ~eSF04_RES_MASK) | resolution; // Set resolution in Advanced User Register [11:9] WriteRegister(SF04_ADV_USER_REG,&registerValue); // Write out new register value ready = true; return error; } //=========================================================================== // Set calibration field (0-4) u8t SF04::setCalibrationField(u8t calfield) //=========================================================================== { ready = false; u8t error = false; //variable for error code nt16 registerValue; // variable for register value if (calfield > 8) { calfield = 0; } ReadRegister(SF04_USER_REG,&registerValue); // Read out current register value registerValue.u16 = (registerValue.u16 & ~eSF04_CF_MASK) | (calfield << 4); // Set calibration field in User Register [6:4] WriteRegister(SF04_USER_REG,&registerValue); // Write out new register value ready = true; return error; } //=========================================================================== // Enable Temperature/Vdd correction u8t SF04::setTempVddCorrectionBit(u8t value) //=========================================================================== { ready = false; u8t error = false; //variable for error code nt16 registerValue; // variable for register value if (value != 1) { value = 0; // Ensure value is 1 or 0 } ReadRegister(SF04_USER_REG,&registerValue); // Read out current register value registerValue.u16 = ((registerValue.u16 & ~0x400) | (value << 10)); // Set calibration field in User Register [bit 10] WriteRegister(SF04_USER_REG,&registerValue); // Write out new register value ready = true; return error; } //=========================================================================== // Force sensor reset bool SF04::softReset() //=========================================================================== { ready = false; char data_write = SF04_SOFT_RESET; if (i2c.write(mi2cAddress, &data_write, 1, false) == 0) { ready = true; return true; } else { ready = true; return false; } } //=========================================================================== // Compute CRC and return true if correct and false if not u8t SF04::checkCRC(u8t data[], u8t numBytes, u8t checksum) //=========================================================================== { u8t crc = 0; u8t byteCtr; for (byteCtr = 0; byteCtr < numBytes; byteCtr++) { crc ^= (data[byteCtr]); for (u8t bit = 8; bit > 0; bit--) { if (crc & 0x80) crc = (crc << 1) ^ SF04_POLYNOMIAL; else crc = (crc << 1); } } if (crc != checksum) return SF04_CHECKSUM_ERROR; else return 0; } //=========================================================================== u8t SF04::ReadRegister(etSF04Register eSF04Register, nt16 *pRegisterValue) //=========================================================================== { ready = false; u8t checksum; //variable for checksum byte u8t error = false; //variable for error code char dataWrite[1] = {eSF04Register}; char dataRead[3]; u8t data[2]; //data array for checksum verification int writeAddr = (mi2cAddress | I2C_WRITE); int readAddr = (mi2cAddress | I2C_READ); i2c.write(writeAddr, dataWrite, 1, true); i2c.read(readAddr, dataRead, 3, false); checksum = dataRead[2]; data[0] = dataRead[0]; data[1] = dataRead[1]; error |= checkCRC(data,2,checksum); pRegisterValue->s16.u8H = dataRead[0]; pRegisterValue->s16.u8L = dataRead[1]; ready = true; return error; } //=========================================================================== u8t SF04::WriteRegister(etSF04Register eSF04Register, nt16 *pRegisterValue) //=========================================================================== { ready = false; u8t error = 1; //variable for error code //-- check if selected register is writable -- if(!(eSF04Register == SF04_READ_ONLY_REG1 || eSF04Register == SF04_READ_ONLY_REG2)) { error=0; //-- write register to sensor -- int writeAddr = (mi2cAddress | I2C_WRITE); char dataWrite[3] = {(eSF04Register & ~0x01 | I2C_WRITE), pRegisterValue->s16.u8H, pRegisterValue->s16.u8L}; i2c.write(writeAddr, dataWrite, 3); } ready = true; return error; } //=========================================================================== u8t SF04::ReadEeprom(u16t eepromStartAdr, u16t size, nt16 eepromData[]) //=========================================================================== { ready = false; u8t checksum; //checksum u8t data[2]; //data array for checksum verification u8t error = 0; //error variable u16t i; //counting variable nt16 eepromStartAdrTmp; //variable for eeprom adr. as nt16 eepromStartAdrTmp.u16=eepromStartAdr; //-- write I2C sensor address and command -- i2c.start(); error |= i2c.write(mi2cAddress | I2C_WRITE); error |= i2c.write(SF04_EEPROM_R); eepromStartAdrTmp.u16=(eepromStartAdrTmp.u16<<4); // align eeprom adr left error |= i2c.write(eepromStartAdrTmp.s16.u8H); error |= i2c.write(eepromStartAdrTmp.s16.u8L); //-- write I2C sensor address for read -- i2c.start(); error |= i2c.write(mi2cAddress | I2C_READ); //-- read eeprom data and verify checksum -- for(i=0; i<size; i++) { eepromData[i].s16.u8H = data[0] = i2c.read(1); eepromData[i].s16.u8L = data[1] = i2c.read(1); checksum=i2c.read( (i < size-1) ? 1 : 0 ); //NACK for last byte error |= checkCRC(data,2,checksum); } i2c.stop(); ready = true; return error; } //=========================================================================== u8t SF04::Measure(etSF04MeasureType eSF04MeasureType)//, nt16 *pMeasurement) //=========================================================================== { ready = false; u8t checksum; //checksum u8t error=0; //error variable char dataWrite[1]; char dataRead[3]; u8t data[2]; //data array for checksum verification nt16 *pMeasurement; //-- write measurement command -- switch(eSF04MeasureType) { case FLOW : dataWrite[0] = SF04_TRIGGER_FLOW_MEASUREMENT; pMeasurement = &flow; setTempVddCorrectionBit(0); break; case TEMP : dataWrite[0] = SF04_TRIGGER_TEMP_MEASUREMENT; pMeasurement = &temperature; setTempVddCorrectionBit(1); break; case VDD : dataWrite[0] = SF04_TRIGGER_VDD_MEASUREMENT; pMeasurement = &vdd; setTempVddCorrectionBit(1); break; default: break; } int writeAddr = (mi2cAddress | I2C_WRITE); int readAddr = (mi2cAddress | I2C_READ); i2c.write(writeAddr, dataWrite, 1, true); i2c.read(readAddr, dataRead, 3, false); checksum = dataRead[2]; data[0] = dataRead[0]; data[1] = dataRead[1]; if (checkCRC(data,2,checksum) == 0) { pMeasurement->s16.u8H = dataRead[0]; pMeasurement->s16.u8L = dataRead[1]; } else { error |= SF04_CHECKSUM_ERROR; } ready = true; return error; } //=========================================================================== u8t SF04::ReadSerialNumber( nt32 *serialNumber ) //=========================================================================== { ready = false; nt16 registerValue; //register value for register u16t eepromBaseAdr; //eeprom base address of active calibration field u16t eepromAdr; //eeprom address of SF04's scale factor nt16 eepromData[2]; //serial number u8t error=0; //error variable //-- read "Read-Only Register 2" to find out the active configuration field -- error |= ReadRegister(SF04_READ_ONLY_REG2,&registerValue); //-- calculate eeprom address of product serial number -- eepromBaseAdr=(registerValue.u16 & 0x0007)*0x0300; //RO_REG2 bit<2:0>*0x0300 eepromAdr= eepromBaseAdr + SF04_EE_ADR_SN_PRODUCT; //-- read product serial number from SF04's eeprom-- error |= ReadEeprom( eepromAdr, 2, eepromData); serialNumber->s32.u16H=eepromData[0].u16; serialNumber->s32.u16L=eepromData[1].u16; ready = true; return error; } //=========================================================================== u8t SF04::ReadScaleFactor(nt16 *scaleFactor) //=========================================================================== { ready = false; u8t error = 0; //variable for error code nt16 registerValue; //register value for user register u16t eepromBaseAdr; //eeprom base address of active calibration field u16t eepromAdr; //eeprom address of SF04's scale factor //-- read "User Register " to find out the active calibration field -- error |= ReadRegister(SF04_USER_REG ,&registerValue); //-- calculate eeprom address of scale factor -- eepromBaseAdr = ((registerValue.u16 & 0x0070) >> 4) * 0x0300; //UserReg bit<6:4>*0x0300 eepromAdr = eepromBaseAdr + SF04_EE_ADR_SCALE_FACTOR; //-- read scale factor from SF04's eeprom-- error |= ReadEeprom( eepromAdr, 1, scaleFactor); ready = true; return error; } //=========================================================================== u8t SF04::ReadFlowUnit(char *flowUnitStr) //=========================================================================== { ready = false; //-- table for unit dimension, unit time, unit volume (x=not defined) -- const char *unitDimension[]= {"x","x","x","n","u","m","c","d","","-","h","k", "M","G","x","x" }; const char *unitTimeBase[] = {"","us","ms","s","min","h","day","x","x","x","x", "x","x","x","x","x" }; const char *unitVolume[] = {"ln","sl","x","x","x","x","x","x","l","g","x", "x","x","x","x","x","Pa","bar","mH2O","inH2O", "x","x","x","x","x","x","x","x","x","x","x","x" }; //-- local variables -- nt16 registerValue; //register value for user register u16t eepromBaseAdr; //eeprom base address of active calibration field u16t eepromAdr; //eeprom address of SF04's flow unit word nt16 flowUnit; //content of SF04's flow unit word u8t tableIndex; //index of one of the unit arrays u8t error=0; //-- read "User Register" to find out the active calibration field -- error |= ReadRegister(SF04_USER_REG ,&registerValue); //-- calculate eeprom address of flow unit-- eepromBaseAdr=((registerValue.u16 & 0x0070)>>4)*0x0300; //UserReg bit<6:4>*0x0300 eepromAdr= eepromBaseAdr + SF04_EE_ADR_FLOW_UNIT; //-- read flow unit from SF04's eeprom-- error |= ReadEeprom( eepromAdr, 1, &flowUnit); //-- get index of corresponding table and copy it to unit string -- tableIndex=(flowUnit.u16 & 0x000F)>>0; //flowUnit bit <3:0> strcpy(flowUnitStr, unitDimension[tableIndex]); tableIndex=(flowUnit.u16 & 0x1F00)>>8; //flowUnit bit <8:12> strcat(flowUnitStr, unitVolume[tableIndex]); tableIndex=(flowUnit.u16 & 0x00F0)>>4; //flowUnit bit <4:7> if(unitTimeBase[tableIndex] != "") { //check if time base is defined strcat(flowUnitStr, "/"); strcat(flowUnitStr, unitTimeBase[tableIndex]); } //-- check if unit string is feasible -- if(strchr(flowUnitStr,'x') != NULL ) error |= SF04_UNIT_ERROR; ready = true; return error; }
Markdown
UTF-8
63,210
3.71875
4
[]
no_license
#### 第 5 章 <J7T] ### 语句 内容 ........................ 178 ..................................................................................................................178 和大多数语言一样,C++提供了条件执行语句、重复执行相同代码的循环语句和用于 中断当前控制流的跳转语句。本章将详细介绍 C++语言所支持的这些语句。 Ht2> 通常情况下,语句是顺序执行的。但除非是最简单的程序,否则仅有顺序执行远远不 够。因此,C++语言提供了一组控制流(flow-of-control)语句以支持更复杂的执行路径。 ###### 50 5.1简单语句 C++语言中的大多数语句都以分号结束,一个表达式,比如 ival + 5,末尾加上分 号就变成了表达式语句(expression statement)。表达式语句的作用是执行表达式并丢弃掉 求值结果: ival + 5; // 一条没什么实际用处的表达式语句 cout << ival; // 一条有用的表达式语句 第一条语句没什么用处,因为虽然执行了加法,但是相加的结果没被使用。比较普遍的情 况是,表达式语句中的表达式在求值时附带有其他效果,比如给变量赋了新值或者输出了 结果。 空语句 最简单的语句是空语句(null statement),空语句中只含有一个单独的分号: ;//空语句 如果在程序的某个地方,语法上需要一条语句但是逻辑上不需要,此时应该使用空语 句。一种常见的情况是,当循环的全部工作在条件部分就可以完成时,我们通常会用到空 语句。例如,我们想读取输入流的内容直到遇到一个特定的值为止,除此之外什么事情也 不做: //重复读入教据直至到达文件末尾或某次愉入的值等于 sought while (cin » s && s != sought) ,-II空语句 while循环的条件部分首先从标准输入读取一个值并且隐式地检查 cin,判断读取是否 成功。假定读取成功,条件的后半部分检查读进来的值是否等于 sought 的值。如果发现 了想要的值,循环终止;否则,从 cin 中继续读取另一个值,再一次判断循环的条件。 Bert 使用空语句时应该加上注释,从而令读这段代码的人知道该语句是有意省略 偏嫩的 别漏写分号,也别多写分号 因为空语句是一条语句,所以可用在任何允许使用语句的地方。由于这个原因,某些 看起来非法的分号往往只不过是一条空语句而已,从语法上说得过去。下面的片段包含两 条语句:表达式语句和空语句。 I 173〉 ival = vl + v2;; //正确:第二个分号表示一条多余的空语句 多余的空语句一般来说是无害的,但是如果在 if 或者 while 的条件后面跟了一个额外的 分号就可能完全改变程序员的初衷。例如,下面的代码将无休止地循环下去: //出现了糟糕的情况:额外的分号,循环体是那条空语句 while (iter ! = svec . end () ) ; // while 循环体是那条空语句 ++iter; //递增运算不属于循环的一部分 虽然从形式上来看执行递增运算的语句前面有缩进,但它并不是循环的一部分。循环条件 后面跟着的分号构成了一条空语句,它才是真正的循环体。 ,!\ 多余的空语句并非总是无害的• WARNING 复合语句(块) 复合语句(compound statement)是指用花括号括起来的(可能为空的)语句和声明 的序列,复合语句也被称作块(block)。一个块就是一个作用域(参见 2.2.4节,第 43 页), 在块中引入的名字只能在块内部以及嵌套在块中的子块里访问。通常,名字在有限的区域 内可见,该区域从名字定义处开始,到名字所在的(最内层)块的结尾为止。 如果在程序的某个地方,语法上需要一条语句,但是逻辑上需要多条语句,则应该使 用复合语句。例如,while或者 for 的循环体必须是一条语句,但是我们常常需要在 循环体内做很多事情,此时就需要将多条语句用花括号括起来,从而把语句序列转变 成块。 举个例子,回忆 1.4+1节(第 10 页)的 while 循环: while (val <= 10) { sum += val; // 4巴 sum + val 的值赋给 sunu ++val; // 给 val 加 1 } 程序从逻辑上来说要执行两条语句,但是 while 循环只能容纳一条。此时,把要执行的 语句用花括号括起来,就将其转换成了一条(复合)语句。 块不以分号作为结束。 所谓空块,是指内部没有任何语句的一对花括号。空块的作用等价于空语句: while (cin » s && s != sought) { } //空块 ###### 5.1节练习 <3741 练习 5.1:什么是空语句?什么时候会用到空语句? 练习 5.2:什么是块?什么时候会用到块? 练习 5.3:使用逗号运算符(参见 4.10节,第 140 页)重写 1.4.1节(第 10 页)的 while 循环,使它不再需要块,观察改写之后的代码的可读性提高了还是降低了。 ##### 5.2语句作用域 可以在 if、switch、while和 for 语句的控制结构内定义变量。定义在控制结构 当中的变量只在相应语句的内部可见,一旦语句结束,变量也就超出其作用范围了: while (int i = get_num()) //每次迭代时创建并初始化 i cout « i << endl; i = 0; //错误:在循环外部无法访问 i 如果其他代码也需要访问控制变量,则变量必须定义在语句的外部: //寻找第一个负值元素 auto beg = v.begin(); while (beg != v.end() && *beg >= 0) ++beg; if (beg == v.end()) //此时我们知道 v 中的所有元素都大于等于 0 因为控制结构定义的对象的值马上要由结构本身使用,所以这些变量必须初始化。 5.2节练习 练习 5.4:说明下列例子的含义,如果存在问题,试着修改它。 (a) while (string::iterator iter != s.end()) { /*...*/ } (b) while (bool status = find (word) ) { /*..•*/ } if (!status) { /* ...*/ } ##### 5.3条件语句 C++语言提供了两种按条件执行的语句。一种是 if 语句,它根据条件决定控制流; 另外一种是 switch 语句,它计算一个整型表达式的值,然后根据这个值从几条执行路径 中选择一条。 龍 5.3.1 if语句 □ZD> if语句(if statement)的作用是:判断一个指定的条件是否为真,根据判断结果决定 是否执行另外一条语句。if语句包括两种形式:一种含有 else 分支,另外一种没有。简单 if语句的语法形式是 if {condition) statement if else语句的形式是 if (condition) statement else statement! 在这两个版本的 if 语句中,condition都必须用圆括号包围起来。condition可以是一个表 达式,也可以是一个初始化了的变量声明(参见 5.2节,第 155 页)。不管是表达式还是变 量,其类型都必须能转换成(参见 4.11节,第 141 页)布尔类型。通常情况下,statement 和 statement!是块语句。 如果 condition 为真,执行 statement。当仙如狀咐执行完成后,程序继续:执行 if 语 句后面的其他语句。 如果 condition 为假,跳过伽妃/wez^。对于简单 if 语句来说,程序继续执行 if 语句 后面的其他语句;对于 if else语句来说,执行伽 Zewezzd。 使用 if else语句 我们举个例子来说明 if 语句的功能,程序的目的是把数字形式表示的成绩转换成字 母形式。假设数字成绩的范围是从 0 到 100 (包括 100 在内),其中 100 分对应的字母形式 是“A++”,低于 60 分的成绩对应的字母形式是“F”。其他成绩每 10 个划分成一组:60 到 69 (包括 69 在内)对应字母“D”、70到 79 对应字母“C”,以此类推。使用 vector 对象存放字母成绩所有可能的取值: const vector<string> scores = {"F", "D", "C", "B", "A", "A++"}; 我们使用 if else语句解决该问题,根据成绩是否合格执行不同的操作: //如果 grade 小于 60,对应的字母是 F;否则计算其下标 string lettergrade; if (grade < 60) lettergrade = scores[0]; else lettergrade = scores[(grade - 50)/10]; 判断 grade 的值是否小于 60,根据结果选择执行 if 分支还是 else 分支。在 else 分支 中,由成绩计算得到一个下标,具体过程是:首先从 grade 中减去 50,然后执行整数除 法(参见 4.2节,在 125 页),去掉余数后所得的商就是数组 scores 对应的下标。 嵌套 if 语句 <1761 接下来让我们的程序更有趣点儿,试着给那些合格的成绩后面添加一个加号或减号。 如果成绩的末位是 8 或者 9,添加一个加号;如果末位是 0、1或 2,添加一个减号: if (grade % 10 > 7) lettergrade += '+';//末尾是 8 或者 9 的成绩添加一个加号 else if (grade % 10 < 3) lettergrade += ' - • ; //末尾是 0、1或者 2 的成绩添加一个减号 我们使用取模运算符(参见 4.2节,第 125 页)计算余数,根据余数决定添加哪种符号。 接着把这段添加符号的代码整合到转换成绩形式的代码中去: //如果成绩不合格,不需要考虑添加加号减号的问题 if (grade < 60) lettergrade = scores[0]; else { lettergrade = scores [ (grade - 50)/10]; // 获得字母形式的成绩 if (grade != 100) //只要不是 A++,就考虑添加加号或减号 if (grade % 10 > 7) lettergrade += '+';//末尾是 8 或者 9 的成绩添加一个加号 else if (grade % 10 < 3) lettergrade += ’-•;//末尾是 0、1或者 2 的成绩添加一个减号 } 注意,我们使用花括号把第一个 else 后面的两条语句组合成了一个块。如果 grade 不 小于 60 要做两件事:从数组 scores 中获取对应的字母成绩,然后根据条件设置加号或 减号, 注意使用花括号 有一种常见的错误,本来程序中有几条语句应该作为一个块来执行,但是我们忘了用 花括号把这些语句包围。在下面的例子中,添加加号减号的代码将被无条件地执行,这显 然违背了我们的初衷: if (grade < 60) lettergrade = scores[0]; else //错误:缺少花括号 lettergrade = scores[(grade - 50)/10]; //虽然下面的语句从形式上看有缩进,但是因为没有花括号, //所以无论什么情况都会执行接下来的代码 //不及格的成绩也会添加上加号或减号,这显然是错误的 if (grade != 100) if (grade % 10 > 7) lettergrade += '+';//末尾是 8 或者 9 的成绩添加一个加号 else if (grade % 10 < 3) lettergrade += 末尾是 0、1或者 2 的成绩添加一个减号 要想发现这个错误可能非常困难,毕竟这段代码“看起来”是正确的。 为了避免此类问题,有些编码风格要求在 if 或 else 之后必须写上花括号(对 while □IZ>和 for 语句的循环体两端也有同样的要求)。这么做的好处是可以避免代码混乱不清,以 后修改代码时如果想添加别的语句,也可以很容易地找到正确位置。 许多编辑器和开发环境都提供一种辅助工具,它可以自动地缩进代码以匹配其 语法结构。善用此类工具益处多多。 悬垂 else 当一个 if 语句嵌套在另一个 if 语句内部时,很可能 if 分支会多于 else 分支,事 实上,之前那个成绩转换的程序就有 4 个 if 分支,而只有 2 个 else 分支。这时候问题 出现了:我们怎么知道某个给定的 else 是和哪个 if 匹配呢? 这个问题通常称作悬垂 else Cdangling else),在那些既有 if 语句又有 if else语 句的编程语言中是个普遍存在的问题。不同语言解决该问题的思路也不同,就 CM 而言, 它规定 else 与离它最近的尚末匹配的 if 匹配,从而消除了程序的二义性。 当代码中 if 分支多于 else 分支时,程序员有时会感觉比较麻烦。举个例子来说明, 对于添加加号减号的那个最内层的 if else语句,我们用另外一组条件改写它: II错误:实际的执行过程并非像缩进格式显示的那样;else分支匹配的是内层 if 语句 if (grade % 10 >= 3) if (grade % 10 > 7) lettergrade += //末尾是 8 或者 9 的成绩添加一个加号 else lettergrade += //末尾是 3、4、5、6或者 7 的成绩添加一个减号! 从代码的缩进格式来看,程序的初衷应该是希望 else 和外层的 if 匹配,也就是说,我 们希望当 grade 的末位小于 3 时执行 else 分支。然而,不管我们是什么意图,也不管 程序如何缩进,这里的 else 分支其实是内层 if 语句的一部分。最终,上面的代码将在 末位大于 3 小于等于 7 的成绩后面添加减号!它的执行过程实际上等价于如下形式: //缩进格式与执行过程相符,但不是程序 M 的意图 if (grade % 10 >= 3) if (grade % 10 > 7) lettergrade += * + ';//末尾是 8 或者 9 的成绩添加一个加号 else lettergrade += 末尾是 3、4、5、6或者 7 的成绩添加一个减号! 使用花括号控制执行路径 要想使 else 分支和外层的 if 语句匹配起来,可以在内层 if 语句的两端加上花括 号,使其成为一个块: //末尾是 8 或者 9 的成绩添加一个加号,末尾是 0、1或者 2 的成绩添加一个减号 if (grade % 10 >= 3) { if (grade % 10 > 7) lettergrade += '+#; //末尾是 8 或者 9 的成绩添加一个加号 } else //花括号强迫 else 与外层 if 匹配 lettergrade //末尾是 0、1或者 2 的成绩添加一个减号 语句属于块,意味着语句一定在块的边界之内,因此内层 if 语句在关键字 else 前面的<3781 那个花括号处已经结束了。else不会再作为内层 if 的一部分。此时,最近的尚未匹配 的 if 是外层 if,也就是我们希望 else 匹配的那个。 ###### 5.3.1节练习 练习 5.5:写一段自己的程序,使用 if else语句实现把数字成绩转换成字母成绩的要求。 练习 5.6:改写上一题的程序,使用条件运算符(参见 4.7节,第 134 页)代替 if else 语句。 练习 5.7:改正下列代码段中的错误。 (a) if (ivall ! = ival2) ivall = ival2 else ivall = ival2 = 0; | (b) if | (ival < minval) minval = ival; | | | | | -------- | ------------------------------ | ------------------- | ----- | ---------- | | occurs = | 1; | | | | | (c) | if | (int ival | =get | _value ()) | | | | cout « *' | •ival | =’’ « ival | | | if | (!ival) | | | | | | cout « *' | 'ival | =0\n"; | | (d) | if | (ival = 0) | | | | | | ival = get value(); | | | 练习 5.8:什么是“悬垂 else” ? C++语言是如何处理 else 子句的? ###### 5.3.2 switch 语句 switch语句(switch statement)提供了一条便利的途径使得我们能够在若干固定选项 中做出选择。举个例子,假如我们想统计五个元音字母在文本中出现的次数,程序逻辑应 该如下所示: •从输入的内容中读取所有字符。 •令每一个字符都与元音字母的集合比较。 •如果字符与某个元音字母匹配,将该字母的数量加 U •显示结果= 例如,以(原书中)本章的文本作为输入内容,程序的输出结果将是: | Number | of | vowel | a: | 3195 | | ------ | ---- | ----- | ---- | ---- | | Number | of | vowel | e : | 6230 | | Number | of | vowel | i: | 3102 | | Number | of | vowel | o: | 3289 | | Number | of | vowel | u: | 1033 | □/§>要想实现这项功能,直接使用 switch 语句即可: //为每个元音字母初始化其计数值 unsigned aCnt = 0, eCnt = 0, iCnt = 0, oCnt = 0, uCnt = 0; char ch; while (cin >> ch) { //如果 ch 是元音字母,将其对应的计数值加 1 switch (ch) { case r az: ++aCnt; break; case z ez: ++eCnt; break; case * i*: ++iCnt; break; case ' or : ++oCnt; break; case r ur : ++uCnt; break; //输出结果 | cout « | "Number | of | vowel | a : | \t" | « aCnt « * \nz | | | | ------ | -------- | ---- | ----- | ---- | ---- | -------------- | ---- | ------- | | << | "Number | of | vowel | e : | \t" | « | eCnt | « ,\n. | | « | ’’Number | of | vowel | i : | \t” | « | iCnt | « z \nf | | « | "Number | of | vowel | o: | \t" | « | oCnt | « ’ \nr | | « | "Number | of | vowel | u: | \t" | « | uCnt | « endl | switch语句首先对括号里的表达式求值,该表达式紧跟在关键字 switch 的后面,可以 是一个初始化的变量声明(参见 5.2节,第 155 页)。表达式的值转换成整数类型,然后与 每个 case 标签的值比较。 如果表达式和某个 case 标签的值匹配成功,程序从该标签之后的第一条语句开始执 行,直到到达了 switch的结尾或者是遇到一条 break 语句为止。 我们将在 5.5.1节(第 170 页)详细介绍 break 语句,简言之,break语句的作用是 中断当前的控制流。此例中,break语句将控制权转移到 switch 语句外面。因为 switch 是 while 循环体内唯一的语句,所以从 switch 语句中断出来以后,程序的控制权将移 到 while 语句的右花括号处。此吋 while 语句内部没有其他语句要执行,所以 while 会返回去再一次判断条件是否满足。 如果 switch 语句的表达式和所有 case 都没有匹配上,将直接跳转到 switch 结构 之后的第一条语句。刚刚说过,在上面的例子中,退出 switch 后控制权回到 while 语 句的条件部分。 case关键字和它对应的值一起被称为 case 标签(case label)。case标签必须是整 型常量表达式(参见 2.4.4节,第 58 页): <J80~| char ch = getVal(); int ival = 42; switch(ch) { case 3.14: //错误:case标签不是一个整数 case ival: //错误:case标签不是一个常量 "... 任何两个 case 标签的值不能相冋,否则就会引发错误。另外,default也是一种特殊 的 case 标签,关于它的知识将在第 162 页介绍。 switch内部的控制流 理解程序在 case 标签之间的执行流程非常重要。如果某个 case 标签匹配成功,将 从该标签开始往后顺序执行所有 case 分支,除非程序显式地中断了这一过程,否则直到 switch的结尾处才会停下来。要想避免执行后续 case 分支的代码,我们必须显式地告 诉编译器终止执行过程。大多数情况下,在下一个 case 标签之前应该有一条 break 语 句。 然而,也有一些时候默认的 switch 行为才是程序真正需要的。每个 case 标签只能 对应一个值,但是有时候我们希望两个或更多个值共享同一组操作。此时,我们就故意省 略掉 break 语句,使得程序能够连续执行若干个 case 标签。 例如,也许我们想统计的是所有元音字母出现的总次数: unsigned vowelCnt = 0; // ... switch (ch) { //出现了 a、e、i、o或 u 中的任意一个都会将 vowelCnt 的值加 1 case z ar : case * ez: case # i# : case 'o#: case * u#: ++vowelCnt; break; 在上面的代码中,几个 case 标签连写在一起,中间没有 break 语句。因此只要 ch 是元 音字母,不管到底是五个中的哪一个都执行相同的代码。 C++程序的形式比较自由,所以 case 标签之后不一定非得换行,把几个 case 标签 写在一行里,强调这些 case 代表的是某个范围内的值: switch (ch) { //另一种合法的书写形式 case * a.' : case 1 e' case * iz : case z o# : case r u# : ++vowelCnt; break; I 181 > Best 一般不要省略 case 分支最后的 break 语句。:如果没写 break 语句,最好加 一段注释说清楚程序的逻辑 漏写 break 容易引发缺陷 有一种常见的错觉是程序只执行匹配成功的那个 case 分支的语句。例如,下面程序 的统计结果是错误的: //警告:不正确的程序逻辑! switch (ch) { | case * ar:++aCnt; | // | 此处应该有一条 break 语句 | | --------------------------- | ---- | ----------------------- | | case x er:++eCnt; | // | 此处应该有一条 break 语句 | | case # iz :++iCnt; | // | 此处应该有一条 break 语句 | | case f o1:++oCnt;case : | // | 此处应该有一条 break 语句 | | ++uCnt; | | | } 要想理解这段程序的执行过程,不妨假设 ch 的值是此时,程序直接执行 case -e-标签后面的代码,该代码把 eCnt 的值加 1。接下来,程序将跨越 case 标签的边界,接 着递增 iCnt、oCnt 和 uCnt。 Bert 尽管 switch 语句不是非得在最后一个标签后面写上 break,但是为了安全 起见,最好这么做。因为这样的话,即使以后再增加新的 case 分支,也不用 再在前面补充 break 语句了,, default 标签 如果没有任何一个 case 标签能匹配上 switch 表达式的值,程序将执行紧跟在 default标签(default label)后面的语句。例如,可以增加一个计数值来统计非元音字 母的数量,只要在 default 分支内不断递增名为 otherCnt 的变量就可以了: II如果 ch 是一个元音字母,将相应的计数值加 1 switch (ch) { case * az: case 'e' z case r i#: case * o' : case ru#: ++vowelCnt; break; default: ++otherCnt; break; } } 在这个版本的程序中,如果 ch 不是元音字母,就从 default 标签开始执行并把<182] otherCnt 加 lo 即使不准备在 default 标签下做任何工作,定义一个 default 标签也是有 卩™^ 用的。其目的在于告诉程序的读者,我们已经考虑到了默认的情况,只是目前 什么也没做。 标签不应该孤零零地出现,它后面必须跟上一条语句或者另外一个 case 标签。如果 switch结构以—空的 default 标签作为结束,则该 default 标签后面必须跟上一条 空语句或一个空块。 switch内部的变量定义 如前所述,switch的执行流程有可能会跨过某些 case 标签。如果程序跳转到了某 个特定的 case,则 switch 结构中该 case 标签之前的部分会被忽略掉。这种忽略掉一 部分代码的行为引出了一个有趣的问题:如果被略过的代码中含有变量的定义该怎么办? 答案是:如果在某处一个带有初值的变量位于作用域之外,在另一处该变量位于作用 域之内,则从前一处跳转到后一处的行为是非法行为。 case true: //因为程序的执行流程可能绕开下面的初始化语句,所以该 switch 语句不合法 string file_name; // 错误 int ival = 0 ; // 错误 int jval; / / 正确 控制流绕过一个隐式初始化的变量 控制流绕过一个显式初始化的变量 因为 jval 没有初始化 break; case false: //正确:jval虽然在作用域内,但是它没有被初始化 jval = next_num() ; // 正确:给 jval 赋一个值 if (file_name .empty () ) // file_name在作用域内,但是没有被初始化 // ... 假设上述代码合法,则一旦控制流直接跳到 false 分支,也就同时略过了变量 filename 和 ival 的初始化过程。此时这两个变量位于作用域之内,跟在 false 之后的代码试图 在尚未初始化的情况下使用它们,这显然是行不通的。因此 C++语言规定,不允许跨过变 量的初始化语句直接跳转到该变量作用域内的另一个位置。 如果需要为某个 case 分支定义并初始化一个变量,我们应该把变量定义在块内,从 而确保后面的所有 case 标签都在变量的作用域之外。 case true: { //正确:声明语句位于语句块内部 string file_name = get_file_name(); // ... } break; case false: if (file_name.empty()) // 错误:file_name 不在作用域之内 ###### |j83> | 5.3.2 节练习 练习 5.9:编写一段程序,使用一系列 if 语句统计从 cin 读入的文本中有多少元音字 母。 练习 5.10:我们之前实现的统计元音字母的程序存在一个问题,如果元音字母以大写形 式出现,不会被统计在内。编写一段程序,既统计元音字母的小写形式,也统计大写形 式,也就是说,新程序遇到,Y和,都应该递增 aCnt 的值,以此类推。 练习 5.11:修改统计元音字母的程序,使其也能统计空格、制表符和换行符的数量。 练习 5.12:修改统计元音字母的程序,使其能统计以下含有两个字符的字符序列的数量: ff、f 1 和 fi- 练习 5.13:下面显示的每个程序都含有一个常见的编程错误,指出错误在哪里,然后修 改它们。 (a) unsigned aCnt = 0, eCnt = 0, iouCnt = 0; char ch = next_text(); switch (ch) { case 'ar : aCnt++; case z er: eCnt++; default: iouCnt++; I (b) unsigned index = some_value(); switch (index) { case 1: int ix = get_value(); ivec[ ix ] = index; break; default: ix = ivec.size()-1; ivec[ ix ] = index; } (c) unsigned evenCnt = 0, oddCnt = 0; int digit = get_num() % 10; switch (digit) { case 1, 3, 5, 7, 9: oddcnt++; break; case 2, 4, 6, 8, 10: evencnt++; break; } (d) unsigned ival=512, jval=1024, kval=4096; unsigned bufsize; unsigned swt = get__bufCnt (); switch(swt) { | case ival: | | | | | ---------- | ------------------------- | ----- | -------------- | | | bufsize =break;case jval: | ival | * sizeof(int); | | | bufsize =break;case kval: | jval | * sizeof(int); | | | bufsizebreak; | =kval | * sizeof(int); | ##### 5.4迭代语句 迭代语句通常称为循环,它重复执行操作直到满足某个条件才停下来。while和 for 语句在执行循环体之前检杳条件,do while语句先执行循环体,然后再检查条件。 ###### 5.4.1 while 语句 只要条件为真,while语句(while statement)就重复地执行循环体,它的语法形式 是 while (condition) statement 在 while 结构中,只要 condition 的求值结果为真就一直执行 statement (常常是一个块)。 condition不能为空,如果 condition 第一次求值就得 false, statement 一次都不执行。 while的条件部分可以是一个表达式或者是一个带初始化的变量声明(参见 5.2节, 第 155 页)。通常来说,应该由条件本身或者是循环体设法改变表达式的值,否则循环可 能无法终止。 ![img](C++ Primer 5-49.jpg) 定义在 while 条件部分或者 while 循环体内的变量每次迭代都经历从创建到 销毁的过程, 使用 while 循环 当不确定到底要迭代多少次时,使用 while 循环比较合适,比如读取输入的内容就 是如此。还有一种情况也应该使用 while 循环,这就是我们想在循环结朿后访问循环控 制变量。例如: vector<int> v; <J85~1 int i; //重复读入数据,直至到达文件末尾或者遇到其他输入问题 while (cin >> i) v.push_back(i); //寻找第一不负值元素 auto beg = v.beginO ; while (beg != v.end() && *beg >= 0) ++beg; if (beg == v.end()) //此时我们知道 V 中的所有元素都大于等于 0 第一个循环从标准输入中读取数据,我们一开始不清楚循环要执行多少次,当 cin 读取 到无效数据、遇到其他一些输入错误或是到达文件末尾时循环条件失效。第二个循环重复 执行直到遇到一个负值为止,循环终止后,beg或者等于 v.end(),或者指向 v 中一个 小于 0 的元素。可以在 while 循环外继续使用 beg 的状态以进行其他处理。 ###### 5.4.1节练习 练习 5.14:编写一段程序,从标准输入中读取若干 string 对象并查找连续重复出现的 单词。所谓连续重复出现的意思是,一个单词后面紧跟着这个单词本身。耍求记录连续 重复出现的最大次数以及对应的单词,如果这样的单词存在,输出重复出现的最大次数: 如果不存在,输出一条信息说明任何单词都没有连续出现过。例如,如果输入是 how now now now brown cow cow 那么输出应该表明单词 now 连续出现了 3次。 ® 5.4.2传统的 for 语句 for语句的语法形式是 for (init-statemen; condition; expression) statement 关键字 for 及括号里的部分称作 for 语句头。 必须是以下三种形式中的一种:声明语句、表达式语句或者空语句,因 为这些语句都以分号作为结束,所以 for 语句的语法形式也可以看做 f or (initializer; condition; expression) statement 一般情况下,init-statement负责初始化一个值,这个值将随着循环的进行而改变。 conrfZZZon作为循环控制的条件,只要 condition 为真,就执行一次 sZfltonenZ。如果 cow/(+/Zon I 186>第一次的求值结果就是 false,则 statement 一次也不会执行。expression负责修改 init-statement初始化的变量,这个变量正好就是 condition 检查的对象,修改发生在每次循 环迭代之后。可以是一条单独的语句也可以是一条复合语句。 传统 for 循环的执行流程 我们以 3.2.3节(第 85 页)的 for 循环为例: //重复处理 s 中的字符直至我们处理完全部字符或者遇到了一个表示空白的字符 for (decltype(s.size()) index = 0; index != s.sizef) && !isspace(s[index]); ++index) s [index] = toupper (s [index] ) : //将当前字符改成大写形式 求值的顺序如下所示: 1-循环开始时,首先执行一次 init-statement。此例中,定义 index 并初始化为 0» 2.接下來判断 cont/tow。如果 index 不等于 s . size ()而且在 s [index]位置的 字符不是空白,则执行 for 循环体的内容。否则,循环终止。如果第一次迭代时 条件就为假,for循环体一次也不会执行。 3.如果条件为真,执行循环体。此例中,for循环体将 s[ index]位置的字符改写 成大写形式。 4.最后执行 expression。此例中,将 index 的值加 1。 这 4 步说明了 for循环第一次迭代的过程。其中第 1 步只在循环开始时执行一次,第 2、 3、4步重复执行直到条件为假时终止,也就是在 s 中遇到一个空白字符或者 index 大于 s . size ()时终止。 ![img](C++ Primer 5-50.jpg) 牢记 for 语句头中定义的对象只在 for 循环体内可见。因此在上面的例子中, for循环结束后 index 就不可用了。 for语句头中的多重定义 和其他的声明一■样,biit-statement也可以定义多个对象。但是 init-statement只能有一• 条声明语句,因此,所有变量的基础类型必须相同(参见 2.3节,第 45 页)。举个例子, 我们用下面的循环把 vector 的元素拷贝一份添加到原来的元素后面: //记录下 v 的大小,当到达原来的最后一个元素后结束循环 for (decltype(v.size()) i = 0, sz = v.size(); i != sz; ++i) v.push_back(v[i]); 在这个循环中,我们在 init-statement里同时定义了索引 i 和循环控制变量 sz。 省略 for 语句头的某些部分 <167~| for语句头能省略掉 init-statement、condition和 expression 中的任何一个(或者全部)。 如果无须初始化,则我们可以使用一条空语句作为 init-statement。例如,对于在 vector对象中寻找第一个负数的程序,完全能用 for 循环改写: auto beg = v.begin(); for ( /* 空语句 */; beg ! = v.end() && *beg >= 0; ++beg) ;//什么也不做 注意,分号必须保留以表明我们省略掉了 init-statement。说得更准确一点,分号表示的是 一个空的时。在这个循环中,因为所有要做的工作都在 for 语句头的条件和表 达式部分完成了,所以 for 循环体也是空的。其中,条件部分决定何时停止查找,表达 式部分递増迭代器。 省略 condition 的效果等价于在条件部分写了一个 true。因为条件的值永远是 true, 所以在循环体内必须有语句负责退出循环,否则循环就会无休止地执行下去: for (int i = 0; /* 条件为空 */ ; ++i) { //对 i 进行处理,循环内部的代码必须负责终止迭代过程! } 我们也能省略掉 for 语句头中的 expression,但是在这样的循环中就要求条件部分或 者循环体必须改变迭代变量的值。举个例子,之前有一个将整数读入 vector 的 while 循环,我们使用 for 语句改写它: vector<int> v; for (int i; cin >> i; /* 表达式为空 */ ) v.push_back(i); 因为条件部分能改变 i 的值,所以这个循环无须表达式部分。其中,条件部分不断检查输 入流的内容,只要读取完所有的输入或者遇到一个输入错误就终 iM 盾环。 1~188> ###### 5.4.2节练习 练习 5.15:说明下列循环的含义并改正其中的错误。 | (a) for | (int ix = 0; ix != sz; | ++ix) { | | | ---------- | ---------------------- | ----------------- | ----------------- | | if | (ix ! | =sz) | | | (b) intfor | // • ix;(ix | != sz; ++ix) { /* | | | (c) for | (int | ix = 0; ix != sz; | ++ix, ++ sz) { /* | 练习 5.16: while循环特别适用于那种条件保持不变、反复执行操作的情况,例如, 当未达到文件末尾时不断读取下一个值。for循环则更像是在按步骤迭代,它的索引值 在某个范围内依次变化。根据每种循环的习惯用法各自编写一段程序,然后分别用另一 种循环改写。如果只能使用一种循环,你倾向于使用哪种呢?为什么? 练习 5.17:假设有两个包含整数的 vector 对象,编写一段程序,检验其中一个 vector 对象是否是另一个的前缀。为了实现这一目标,对于两个不等长的 vector 对象,只需 挑出长度较短的那个,把它的所有元素和另一个 vector 对象比较即可。例如,如果两 个 vector 对象的元素分别是 0、1、1、2和 0、1、1、2、3、5、8,则程序的返回 结果应该为真。 ^6 5.4.3范围 for 语句 C++11新标准引入了一种更简单的 for 语句,这种语句可以遍历容器或其他序列的 所有元素。范围 for 语句(range for statement)的语法形式是: for (declaration : expression) statement 表示的必须是一个序列,比如用花括号括起来的初始值列表(参见 3.3.1节,第 88贞)、数组(参见 3.5节,第 101 页)或者 vector 或 string 等类型的对象,这些类 型的共同特点是拥有能返回迭代器的 begin 和 end 成员(参见 3.4节,第 95 页)。 t/ecZararion定义一个变量,序列中的每个元素都得能转换成该变量的类型(参见 4.11 节,第 141 页)。确保类型相容最简单的办法是使用 auto 类型说明符(参见 2.5.2节,第 61页),这个关键字可以令编译器帮助我们指定合适的类型。如果需要对序列中的元素执 行写操作,循环变量必须声明成引用类型。 每次迭代都会重新定义循环控制变量,并将其初始化成序列中的下一个值,之后才会 执行像往常一样,•statonenZ可以是一条单独的语句也可以是一个块。所有元素 都处理完毕后循环终止。 之前我们已经接触过几个这样的循环。接下来的例子将把 vector 对象中的每个元素 都翻倍,它涵盖了范围 for 语句的几乎所有语法特征: vector<int> v = {0,1,2,3,4,5,6,7,8,9}; //范围变量必须是引用类型,这样才能对元素执行写操作 for (auto &r : v) //对于 v 中的每一个元素 r *= 2; //将 v 中每个元素的值翻倍 for语句头声明了循环控制变量 r,并把它和 v 关联在一起,我们使用关键字 auto 令编 译器为 r 指定正确的类型。由于准备修改 v 的元素的值,因此将 r 声明成引用类型。此 时,在循环体内给 r 赋值,即改变了 r所绑定的元素的值。 范围 for 语句的定义来源于与之等价的传统 for 语句: for (auto beg = v.beginO , end = v.end() ; beg ! = end; ++beg) { auto &r = *beg; // r必须是引用类型,这样才能对元素执行写操作 r *= 2; //将 v 中每个元素的值翻倍 } 学习了范围 for 语句的原理之后,我们也就不难理解为什么在 3.3.2节(第 90 页)强调 不能通过范围 for 语句增加 vector 对象(或者其他容器)的元素了。在范围 for 语句<S 中,预存了 end(>的值。-旦在序列中添加(删除)元素,end函数的值就可能变得无效 了(参见 3.4.1节,第 98 页)。关于这一点,将在 9.3.6节(第 315 页)做更详细的介绍。 ###### 5.4.4 do while 语句 do while语句(do while statement)和 while 语句非常相似,唯一的区别是,do while 语句先执行循环体后检查条件。不管条件的值如何,我们都至少执行一次循环。do while 语句的语法形式如下所示: statement while (condition); do while语句应该在括号包围起来的条件后面用一个分号表示语句结束.:: 在 do 语句中,求 condition 的值之前首先执行一次 statement, condition不能为空。如果 的值为假,循环终止:否则,重复循环过程。使用的变量必须定义在循 环体之外。 我们可以使用 do while循环(不断地)执行加法运算: //不断提示用户输入一对数,然后求其和 string rsp; //作为循环的条件,不能完义在 do 的内部 do { cout << "please enter two values:"; int vail = 0, val2 = 0; cin >> vail >> val2; cout << "The sum of " << vail << " and " << val2 << "="<< vail + val2 << "\n\n" << "More? Enter yes or no:"; cin >> rsp; } while (!rsp•empty() && rsp [0] !=,n'); 循环首先提示用户输入两个数字,然后输出它们的和并询问用户是否继续。条件部分检查 用户做出的回答,如果用户没有回答,或者用户的回答以字母 n 开始,循环都将终止。否 则循环继续执行。 因为对于 do while来说先执行语句或者块,后判断条件,所以不允许在条件部分 定义变量: do { // ... mumble(foo); } while (int foo = get_foo () ) ; //错误:将变量声明放在了 do的条件部分 如果允许在条件部分定义变量,则变量的使用出现在定义之前,这显然是不合常理的! [J9Q> ###### 5.4.4节练习 练习 5.18:说明下列循环的含义并改正其中的错误。 (a) do int vl, v2; cout « "Please enter two numbers to sum:"; if (cin » vl >> v2) cout « "Sum is: " « vl + v2 « endl; while (cin); (b) do { // ... } while (int ival = get_response()); ⑹do { int ival = get_response(); } while (ival); 练习 5.19:编写一段程序,使用 do while循环重复地执行下述任务:首先提示用户 输入两个 string 对象,然后挑出较短的那个并输出它。 ##### 5.5跳转语句 跳转语句中断当前的执行过程。C杆语言提供了 4种跳转语句:break、continue, goto和 return。本章介绍前三种跳转语句,return语句将在 6.3节(第 199 页)进行 介绍。 ###### 5.5.1 break 语句 break 语句(break statement)负责终止离它最近的 while、do while、for 或 switch 语 句,并从这些语句之后的第一条语句开始继续执行。 break语句只能出现在迭代语句或者 switch 语句内部(包括嵌套在此类循环里的 语句或块的内部)。break语句的作用范围仅限于最近的循环或者 switch: string buf; while (cin >> buf && !buf.empty()) { switch(buf[0]) { case 1z //处理到第一个空白为止 for (auto it = buf.begin()+1; it != buf.end(); ++it) { if (*it == r *) break; // #1,离开 for 猸环 } // break #1将控制权转移到这里 //剩余的处理: break; // #2,离开 switch 语句 case f: //... } // 结束 switch //结束 switch: break #2将控制权转移到这里 } // 结束 while 标记为#1的 break 语句负责终止连字符 case 标签后面的 for 循环。它不但不会终止 switch语句,甚至连当前的 case 分支也终止不了。接下来,程序继续执行 for 循环之 后的第一条语句,这条语句可能接着处理连字符的情况,也可能是另一条用于终止当前分 支的 break 语句。 标记为#2的 break 语句负责终止 switch 语句,但是不能终止 while 循环。执行 完这个 break 后,程序继续执行 while 的条件部分。 ###### 5.5.1节练习 练习 5.20:编写一段程序,从标准输入中读取 string 对象的序列直到连续出现两个相 同的单词或者所有单词都读完为止。使用 while 循环一次读取一个单词,当一个单词 连续出现两次时使用 break 语句终止循环。输出连续重复出现的单词,或者输出一个 消息说明没有任何单词是连续重复出现的。 ###### 5.5.2 continue 语句 continue语句(continue statement)终止最近的循环中的当前迭代并立即开始下•次 迭代。continue语句只能出现在 for、while和 do while循环的内部,或者嵌套在此类循环 里的语句或块的内部。和 break 语句类似的是,出现在嵌套循环中的 continue 语句也仅作 用于离它最近的循环。和 break 语句不同的是,只有当 switch 语句嵌套在迭代语句内部时, 才能在 switch 里使用 continueo continue语句中断当前的迭代,但是仍然继续执行循环。对于 while 或者 do while 语句来说,继续判断条件的值;对于传统的 for 循环来说,继续执行 for 语句头的 expression'而对于范围./br语句来说,则是用序列中的下一个元素初始化循环控制变量。 例如,下面的程序每次从标准输入中读取一个单词。循环只对那些以下画线开头的单 词感兴趣,其他情况下,我们直接终止当前的迭代并获取下一个单词: string buf; while (cin » buf && !buf.empty()) { if (buf[0] != ) continue; //接着读取下一个输入 //程序执行过程到了这里?说明当前的输入是以下画线开始的;接着处理 buf…… } ###### 5.5.2节练习 练习 5.21:修改 5.5.1节(第 171 页)练习题的程序,使其找到的重复单词必须以大写 字母开头。 @ 5.5.3 goto 语句 goto语句(goto statement)的作用是从 goto 语句无条件跳转到同一函数内的另一条语句。 卩不要在租序中使用 goto 语句,因为它使得程序既难理解又难修改。 goto语句的语法形式是 goto label; 其中,是用于标识一条语句的标示符。带标签语句(labeled statement)是一种特殊的 语句,在它之前有一个标示符以及一个冒号: end: return; //带标签语句,可以作为 goto 的目标 标签标示符独立于变量或其他标示符的名字,因此,标签标示符可以和程序中其他实体的 标示符使用同一个名字而不会相互干扰。goto语句和控制权转向的那条带标签的语句必 须位于同一个函数之内。 和 switch 语句类似,goto语句也不能将程序的控制权从变量的作用域之外转移到 作用域之内: goto end; int ix = 10; II错误:goto语句绕过了一个带初始化的变量定义 end: //错误:此处的代码需要使用 ix,但是 goto 语句绕过了它的声明 ix = 42; 向后跳过一个已经执行的定义是合法的。跳回到变量定义之前意味着系统将销毁该变 量,然后重新创建它, //向后跳过一个带初始化的变量定义是合法的 begin: int sz = get_size(); if (sz <= 0) { goto begin; } 在上面的代码中,goto语句执行后将销毁 sz。因为跳回到 begin 的动作跨过了 sz的 定义语句,所以 sz 将重新定义并初始化。 ###### □M> 5.5.3节练习 练习 5.22:本节的最后一个例子跳回到 begin,其实使用循环能更好地完成该任务。 重写这段代码,注意不再使用 goto 语句。 ##### 穆 5.6 try语句块和异常处理 异常是指存在于运行时的反常行为,这些行为超出了函数正常功能的范围。典型的异 常包括失去数据库连接以及遇到意外输入等。处理反常行为可能是设计所有系统最难的一 部分。 当程序的某部分检测到一个它无法处理的问题时,需要用到异常处理。此时,检测出 问题的部分应该发出某种信号以表明程序遇到了故障,无法继续下去了,而且信号的发出 方无须知道故障将在何处得到解决,一旦发出异常信号,检测出问题的部分也就完成了任 务。 如果程序中含有可能引发异常的代码,那么通常也会有专门的代码处理问题。例如, 如果程序的问题是输入无效,则异常处理部分可能会要求用户重新输入正确的数据:如果 丢失了数据库连接,会发出报警信息。 异常处理机制为程序中异常检测和异常处理这两部分的协作提供支持。在 C++语言 中,异常处理包括: • throw表达式(throw expression),异常检测部分使用 throw 表达式来表示它遇到 了无法处理的问题。我们说 throw 引发(raise) 了异常。 • try语句块(try block),异常处理部分使用 try 语句块处理异常。try语句块以 关键字 try 开始,并以一■个或多个 catch 子句(catch clause)结束。try语句块 中代码抛出的异常通常会被某个 catch 子句处理。因为 catch 子句“处理"异常, 所以它们也被称作异常处理代码(exception handler)。 • 一套异常类(exception class),用于在 throw 表达式和相关的 catch 子句之间传 递异常的具体信息。 在本节的剩余部分,我们将分别介绍异常处理的这三个组成部分。在 18+1节(第 684 页) 还将介绍更多关于异常的知识。 ###### 5.6.1 throw 表达式 程序的异常检测部分使用 throw 表达式引发一个异常。throw表达式包含关键字 throw和紧随其后的一个表达式,其中表达式的类型就是抛出的异常类型。throw表达 式后面通常紧跟一个分号,从而构成一条表达式语句。 举个简单的例子,回忆 1.5.2节(第 20 页)把两个 Sales_item对象相加的程序。<J94l 这个程序检查它读入的记录是否是关于同一种书籍的,如果示是,输出一条信息然后 退出。 Sales_item iteml, item2; cin >> iteml >> item2; //首先检查 iteml 和 item2 是否表示同一种书籍 if (iteml.isbn() == item2.isbn()) { cout << iteml + item2 << endl; return 0; //表示成功 } else { cerr << "Data must refer to same ISBN" << endl; return -1; //表示失败 } 在真实的程序中,应该把対象相加的代码和用户交互的代码分离开来。此例中,我们 改写程序使得检查完成后不再直接输出一条信息,而是抛出一个异常: //首先检查两条数据是否是关于同一种书籍的 if (iteml.isbn() != item2.isbn()) throw runtime_error("Data must refer to same ISBN"); //如果程序执行到了 里,表示两个 ISBN 是相同的 cout << iteml + item2 << endl; 在这段代码中,如果 ISBN 不一样就抛出一个异常,该异常是类型 runtime_error的对 象。抛出异常将终止当前的函数,并把控制权转移给能处理该异常的代码。 类型 runtime_error是标准库异常类型的一种,定义在 stdexcept 头文件中。关 于标准库异常类型多的知识将在 5.6.3节(第 176 页)介绍。我们必须初始化 runtime_error的对象,方式是给它提供一个 string 对象或者一个 C 风格的字符串 (参见 3.5.7节,第 109 页),这个字符串中有一些关于异常的辅助信息。 ###### 5.6.2 try语句块 try语句块的通用语法形式是 try { program-statements } catch (exception-declaration) { handler-statements } catch (exception-declaration) { handler-statements }//... try语句块的一开始是关键字 try,随后紧跟着一个块,这个块就像大多数时候那样是花 括号括起来的语句序列。 |J95> 跟在 try 块之后的是一个或多个 catch 子句。catch子句包括三部分:关键字 catch、括号内一个(可能未命名的)对象的声明(称作异常声明,exception declaration) 以及一个块。当选中了某个 catch 子句处理异常之后,执行与之对应的块。catch—旦 完成,程序跳转到 try 语句块最后一个 catch 子句之后的那条语句继续执行。 try语句块中的 program-statements组成程序的正常逻辑,像其他任何块一样, program-statements可以有包括声明在内的任意 C++语句。一如往常,try语句块内声明 的变量在块外部无法访问,特别是在 catch 子句内也无法访问。 编写处理代码 在之前的例子里,我们使用了一个 throw 表达式以避免把两个代表不同书籍的 Sales_item相加。我们假设执行 Sales_item对象加法的代码是与用户交互的代码分 离开来 b。其中与用户交互的代码负责处理发生的异常,它的形式可能如下所示: while (cin >> iteml >> item2) { try { //执行添加两个 Sales_item对象的代码 //如果添加失败,代码抛出一个 runtime_error异常 } catch (runtime_error err) { //提醒用户两个 ISBN 必须一致,询问是否重新输入 cout << err.what() << "\nTry Again? Enter y or n" << endl; char c; cin >> c; if (!cin || c == 'n') break; // 跳出 while 循环 } 程序本来要执行的任务出现在 try 语句块中,这是因为这段代码可能会抛出一个 runtime_error #3^的异常- try语句块对应—t- catch子句,该子句负责处理类型为 runtime_error的异常。 如果 try 语句块的代码抛出了 runtime_error异常,接下来执行 catch 块内的语句。 在我们书写的 catch 子句中,输出一段示信息要求用户指定程序是否继续,如果用户 输入,n,,执行 break 语句并退出 while 循环;否则,直接执行 while 循环的右侧花 括号,意味着程序控制权跳回到 while 条件部分准备下一次迭代。 给用户的提示信息中输出了 err.whatO的返回值,我们知道 err 的类型是 runtime_error,因此能推断 what 是 runtime_error类的一个成员函数(参见 1.5.2 节,第 20_页)。每个标准库异常类都定义了名为 wlTat 的成员函数,这些函数没有参数, 返回值是 C 风格字符串(即 const char*)。其中,runtime_error的 what 成员返<196 I 回的是初始化一个具体对象时所用的 string 对象的副本。如果 I 一节编写的代码抛出异 常,则本节的 catch 子句输出 Data must refer to same ISBN Try Again? Enter y or n 函数在寻找处理代码的过程中退出 在复杂系统中,程序在遇到抛出异常的代码前,其执行路径可能已经经过了多个 try 语句块。例如,一个 try 语句块可能调用了包含另一个 try 语句块的函数,新的 try 语 句块可能调用了包含又一个 try 语句块的新函数,以此类推。 寻找处理代码的过程与函数调用链刚好相反。当异常被抛出时,首先搜索抛出该异常 的函数。如果没找到匹配的 catch 子句,终止该函数,并在调用该函数的函数中继续寻 找。如果还是没有找到匹配的 catch 子句,这个新的函数也被终止,继续搜索调用它的 函数。以此类推,沿着程序的执行路径逐层回退,直到找到适当类型的 catch 子句为止。 如果最终还是没能找到任何匹配的 catch 子句,程序转到名为 terminate 的柚准 库函数。该函数的行为与系统有关,一般情况下,执行该函数将导致程序非正常退出。 对于那些没有任何 try 语句块定义的异常,也按照类似的方式处理:毕竟,没有 try 语句块也就意味着没有匹配的 catch 子句。如果一段程序没有 try 语句块且发生了异常, 系统会调用 terminate 函数并终止当前程序的执行。 提示:编¥异常安全的代码非常 M 难 要好好理解这句话:异常中断了程序的正常流程:。异常发生时,调用者请求的一部 分计算可能已经完成了,另一部分则尚未完成。通常情况下,略过部分程序意味着某些 对象处理到一半就戛然而止,从而导致对象处于无效或未完成的状态,或者资源没有正 常释放,等等。那些在异常发生期间正确执行了 “清理"工作的程序被称作异常安全 (exception safe)的代码」然而经验表明,编写异常安全的代码非常困难,这部分知识也 (远远)超出了本书的范围。 对于一些程序来说,当异常发生时只是简单地终止程序。此时,我们不怎么需要担 心异常安全的问题, 但是对于那些确实要处理异常并继续执行的程序,就要加倍注意了。我们必须时刻 清楚异常何时发生,异常发生后程序应如何确保对象有效、资源无泄漏、程序处于合理 状态,等等。 我们会在本书中介绍一些比较常规的提升异常安全性的技术。但是读者需要注意, 如果你的程序要求非常鲁棒的异常处理,那么仅有我们介绍的这些技术恐怕还是不 够的。 EZ97> 5.6.3标准异常 C++标准库定义了一组类,用于报告标准库函数遇到的问题。这些异常类也可以在用 户编写的程序中使用,它们分别定义在 4 个头文件中: • exception头文件定义了最通用的异常类 exception。它只报告异常的发生, 不提供任何额外信息。 • stdexcept头文件定义了几种常用的异常类,详细信息在表 5.1中列出。 • new头文件定义了 bad_allOc异常类型,这种类型将在 12.1.2节(第 407 页)详 细介绍。 • type_info头文件定义了 bad_cast异常类型,这种类型将在 19.2节(第 731 页)详细介绍。 | 表 5.1: | <std except〉定义的异常类 | | ---------------- | ---------------------------------------------- | | exception | 最常见的问题 | | runtime_error | 只有在运行时 j 能检测出的问题 | | range error | 运行吋错误:生成的结果超出了有意义的值域范围 | | overflow_error | 运行时错误:计算上溢 | | underflow error | 运行吋错误:计算下溢 | | logic_error | 程序逻辑错误 | | domain error | 逻辑错误:参数对应的结果值不存在 | | invalid_argument | 逻辑错误:无效参数 | | length—error | 逻辑错误:试图创建一个超出该类型最大长度的对象 | | out of range | 逻辑错误:使用个超出有效范围的值 | 标准库异常类只定义了几种运算,包括创建或拷贝异常类型的对象,以及为异常类型 的对象赋值。 我们只能以默认初始化(参见 2.2.1节,第 40 页)的方式初始化 exception, bad_alloc和 bad_cast对象,不允许为这些对象提供初始值。 其他异常类型的行为则恰好相反:应该使用 string 对象或者 C 风格字符串初始化这 些类型的对象,但是不允许使用默认初始化的方式。当创建此类对象时,必须提供初始值, 该初始值含有错误相关的信息。 异常类型只定义了一个名为 what 的成员函数,该函数没有任何参数,返回值是一个 指向 C 风格字符串(参见 3.5.4节,第 109 页)的 const char*。该字符串的目的是提 供关于异常的一些文本信息。 what函数返回的 C 风格字符串的内容与异常对象的类型有关。如果异常类型有一个<S 字符串初始值,则 what 返回该字符串。对于其他无初始值的异常类型来说,what返回 的内容由编译器决定。 ###### 5.6.3节练习 练习 5.23:编写一段程序,从标准输入读取两个整数,输出第一个数除以第二个数的结 果。 练习 5.24:修改你的程序,使得当第二个数是 0 时抛出异常。先不要设定 catch 子句, 运行程序并真的为除数输入 0,看看会发生什么? 练习 5.25:修改上一题的程序,使用 try 语句块去捕获异常。catch子句应该为用户 输出一条提示信息,询问其是否输入新数并重新执行 try 语句块的内容。 Pi99> 小结 _ C++语言仅提供了有限的语句类型,它们中的大多数会影响程序的控制流程: • while、for和 do while语句,执行迭代操作。 • if和 switch 语句,提供条件分支结构。 • continue语句,终 it 循环的当前一次迭代。 • break语句,退出循环或者 switch 语句。 • goto语句,将控制权转移到一条带标签的语句。 • try和 catch,将-•段可能抛出异常的语句序列括在花括号里构成 try 语句块。 catch子句负责处理代码抛出的异常。 • throw表达式语句,存在于代码块中,将控制权转移到相关的 catch 子句, • return语句,终止函数的执行。我们将在第 6 章介绍 return 语句。 除此之外还有表达式语句和声明语句。表达式语句用〒求解表达式,关于变量的声明 和定义在第 2 章己经介绍过了。 术语表 块(block)包围在花括号内的由 0 条或多 条语句组成的序列:,块也是-条语句,所 以只要是能使用语句的地方,就可以使用 块。 break 语句(break statement)终止离它 最近的循环或 switch 语句。控制权转移 到循环或 switch 之后的第一条语句。 case 标签(case label)在 switch 语句 中紧跟在 case 关键字之后的常量表达式 (参见 2.4.4节,第 58 页)。在同一个 swi tch 语句中任意两个 case 标签的值不能相同。 catch子句(catch clause)由三部分组成: catch关键字、括号里的异常声明以及一 个语句块。catch子句的代码负责处理在 异常声明中定义的异常。 复合语句(compound statement)和块是 同义词。 continue 语句(continue statement)终止 离它最近的循环的当前迭代。控制权转移 到 while 或 do while语句的条件部分、 或者范 ffl for循环的下一次迭代、或者传 统 for 循环头部的表达式。 悬垂 else (dangling else)是一个俗语, 指的是如何处理嵌套 if 语句中 if 分支多 于 else 分支的情况。OH■语言规定,else 应该与前一个未匹配的 if 匹配在一起。使 用花括号可以把位于内层的 if 语句隐藏 起來,这样程序员就能更好地控制 else 该与哪个 if 匹配。 default 标签(default label)是--种特殊的 case标签,当 switch 表达式的值与所有 case标签都无法匹配吋,程序执行 default标签下的内容。 I 200>do while 语句(do while statement)与 while语句类似,区别是 do while语句 先执行循环体,再判断条件。循环体代码 至少会执行一次。. 异常类/exception class)是标准库定义 的一组类,用于表示程序发生的错误。表 5.1 (第 176 页)列出了不同用途的异常类。 异常声明(exception declaration)位于 catch子句中的声明,指定了该 catch 子句能处理的异常类型。 异常处理代码(exception handler)程序 某处引发异常后,用于处现该异常的另一 处代码。和 catch 子句是同义同。 异常安全(exception safe)是一个术语, 表示的含义是当抛出异常后,程序能执行 正确的行为。 表达式语句(expression statement)即一 条表达式后面跟上一个分号,令表达式执 行求值过程。 控制流(flow of control)程序的执行路径.。 for语句(for statement)提供迭代执行的 迭代语句。常常用子遍历一个容器或者重 复计算若干次。 goto语句(goto statement)令控制权无 条件转移到同一函数中一个指定的带标签 语句„ goto语句容易造成程序的控制流混 乱,应禁止使用•》 if else 语句(if else statement)判断条件, 根据其结果分别执行 if 分支或 else 分支 的语句。 if语句.(if statement)判断条件,根据其 结果有选择地执行语句。如果条件为真, 执行 if 分支的代码;如果条件为假,控制 权转移到 if 结构之后的第 '条语句。 带标签语句(labeled statement)前面带 有标签的语句。所谓标签是指一个标识符 以及紧跟着的■-个冒号。对于同一个标识 符来说,用作标签的同吋还能用于其他目 的,互不干扰。 空语句(null statement)只含有一个分号 的语句。 引发(raise)含义类似于 throw。在 C++ 语言中既可以说抛出异常,也可以说引发 异常。 范围 for 语句(range for statement)在-- 个序列中进行迭代的语句。 switch 语句(switch statement). —种条件 语句,首先求 switch 关键字后面表达式 的值,如果某个 case 标签的值与表达式 的值相等,程序直接跨过之前的代码从这 个 case 标签开始执行。3所有 case 标 签都无法匹配时,如果有 default 标签, 从 default 标签继续执行;如果没有,结 束 switch 语句。. terminate是一个标准库函数,当异常没有 被捕捉到吋调用。terminate终止当前程 序的执行。 throw 表达式(throw expression)--种中 断当前执行路径的表达式。throw表达式 抛出一个异常并把控制权转移到能处理该 异常的最近的 catch 子句。 try语句块(try block)跟在 try 关键字后 面的块,以及一个或多个 catch 子句。如 果 try 语句块的代码引发异常并且其中一 个 catch 子句匹配该异常类型,则异常被 该 catch 子句处理。否则,异常将由外围 try语句块处理,或者程序终 it。 while语句(while statement)只要指定的 条件为真,就,直迭代执行 H 标语句。随 着条件真值的不同,循坏可能执行多次, 也可能一次也不执行。
Java
UTF-8
679
2.515625
3
[]
no_license
package com.example.leaderboard; public class Form { private String email; private String firstName; private String lastName; private String linkToGithub; public Form( String firstName, String lastName, String email, String linkToGithub) { this.email = email; this.firstName = firstName; this.lastName = lastName; this.linkToGithub = linkToGithub; } public String getEmail() { return email; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getLinkToGithub() { return linkToGithub; } }
JavaScript
UTF-8
794
2.578125
3
[]
no_license
const express = require('express'); const axios = require('axios'); const cheerio = require('cheerio'); const app = express(); const PORT = 5000; const url = 'https://en.wikipedia.org/wiki/List_of_United_States_military_bases' axios(url) .then(res => { const html = res.data // console.log(html) const $ = cheerio.load(html) const info = [] $('.mw-editsection', html).each(function () { const title = $(this).text() const link = $(this).find('a').attr('href') info.push({ title, link }) }) console.log(info) }).catch(err => console.log(err)) //server listening on port app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
Java
UTF-8
3,215
2.65625
3
[]
no_license
package edu.ucdavis.ucdh.stu.core.manager.impl; import java.util.Date; import java.util.List; import edu.ucdavis.ucdh.stu.core.beans.BatchJobInstance; import edu.ucdavis.ucdh.stu.core.dao.BatchJobInstanceDao; import edu.ucdavis.ucdh.stu.core.manager.BatchJobInstanceManager; /** * <p>Concrete implementation of the BatchJobInstance manager interface.</p> */ public class BatchJobInstanceManagerImpl implements BatchJobInstanceManager { private BatchJobInstanceDao dao; /** * <p>Returns all BatchJobInstances in the database.</p> * * @return all BatchJobInstances in the database */ public List<BatchJobInstance> findAll() { return dao.findAll(); } /** * <p>Returns all BatchJobInstances in the database that * match the specified search criteria.</p> * * @param batchJobInstance an example BatchJobInstance * @return all BatchJobInstances in the database that * match the specified search criteria */ public List<BatchJobInstance> findByExample(BatchJobInstance batchJobInstance) { return dao.findByExample(batchJobInstance); } /** * <p>Returns all BatchJobInstances in the database that * match the specified search criteria.</p> * * @param propertyName the name of the specified property * @param propertyValue the search value for the specified * property * @return all BatchJobInstances in the database that * match the specified search criteria */ public List<BatchJobInstance> findByProperty(String propertyName, Object propertyValue) { return dao.findByProperty(propertyName, propertyValue); } /** * <p>Returns all BatchJobInstances in the database that * match the specified search criteria.</p> * * @param context the context of the job * @param name the name of the job * @param startDate the inclusive begin date of the desired run time period * @param endDate the inclusive end date of the desired run time period * @return all BatchJobInstances in the database that * match the specified search criteria */ public List<BatchJobInstance> findByContextNameAndDate(String context, String name, Date startDate, Date endDate) { return dao.findByContextNameAndDate(context, name, startDate, endDate); } /** * <p>Returns the BatchJobInstance with the specified id.</p> * * @param id the id of the requested batchJobInstance * @return the BatchJobInstance with the specified id */ public BatchJobInstance findById(Integer id) { return dao.findById(id); } /** * <p>Saves the BatchJobInstance passed.</p> * * @param batchJobInstance the batchJobInstance to save */ public void save(BatchJobInstance batchJobInstance) { dao.save(batchJobInstance); } /** * <p>Deletes the BatchJobInstance with the specified id.</p> * * @param batchJobInstance the batchJobInstance to delete */ public void delete(BatchJobInstance batchJobInstance) { dao.delete(batchJobInstance); } /** * <p>Sets the BatchJobInstanceDao.</p> * * @param batchJobInstanceDao the batchJobInstanceDao to set */ public void setBatchJobInstanceDao(BatchJobInstanceDao dao) { this.dao = dao; } }
Swift
UTF-8
2,317
2.578125
3
[]
no_license
// // Driver.swift // Project Recycle // // Created by Students on 11/29/16. // Copyright © 2016 Lee Yik Sheng. All rights reserved. // import Foundation import FirebaseAuth import FirebaseDatabase import UIKit class Driver{ var name: String var email: String var phoneNumber: String var profileImage: String var assignedOrderUIDArray: [String] var completedOrderUIDArray: [String] var driverUID: String init() { name = "" email = "" phoneNumber = "" profileImage = "" assignedOrderUIDArray = [] completedOrderUIDArray = [] driverUID = "" } convenience init(driverUID: String) { self.init() let driverDatabaseReference = FIRDatabase.database().reference(withPath: "drivers/\(driverUID)") driverDatabaseReference.observe(FIRDataEventType.value, with: { (snapshot) in guard let driverRawDataDictionary = snapshot.value as? [String: AnyObject] else { return } self.name = driverRawDataDictionary["name"] as! String self.email = driverRawDataDictionary["email"] as! String self.phoneNumber = driverRawDataDictionary["phoneNumber"] as! String self.profileImage = driverRawDataDictionary["profileImage"] as! String //: MARK - (TBD FEATURE) CONVERT TO URL AND DOWNLOAD THEN ASSIGN AS UIIMAGE self.driverUID = driverRawDataDictionary["driverID"] as! String if driverRawDataDictionary["assignedOrders"] == nil { self.assignedOrderUIDArray = [] } else { self.assignedOrderUIDArray = driverRawDataDictionary["assignedOrders"] as! [String] } if driverRawDataDictionary["completedOrders"] == nil { self.completedOrderUIDArray = [] } else { self.completedOrderUIDArray = driverRawDataDictionary["completedOrders"] as! [String] } let driverInitializationCompletionNotification = Notification(name: Notification.Name(rawValue: "DriverInitializationCompletionNotification"), object: nil, userInfo: nil) NotificationCenter.default.post(driverInitializationCompletionNotification) }) } }
Python
UTF-8
1,869
2.6875
3
[]
no_license
from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('dir', help='Processed power data directory.') parser.add_argument( 'file', nargs='?', default=None, help="""Resampled power NetCDF save file. (default: {dir}/pwr_resampled@{t0}--{t1}.nc)""", ) parser.add_argument( '-f', '--freq', default='30s', help='Time resample period. (default: %(default)s)', ) parser.add_argument( '-m', '--method', default='mean', help='Time resample method. (default: %(default)s)', ) parser.add_argument( '-t', '--index', default=None, metavar='T0[--T1]', help="""Time index to select before resampling. Pass "?" to print start and end of data. (default: %(default)s)""", ) args = parser.parse_args() import os import sys import numpy as np import xarray as xr datadir = os.path.normpath(args.dir) pwr = xr.open_mfdataset(os.path.join(datadir, 'pwr@*.nc'), concat_dim='t', engine='h5netcdf') if args.index == '?': tidx = pwr.indexes['t'] print('Data goes from {0} to {1}.'.format(tidx[0], tidx[-1])) sys.exit() elif args.index is not None: sections = args.index.split('--') if len(sections) == 1: index = sections[0].strip() elif len(sections) == 2: start = sections[0].strip() stop = sections[1].strip() index = slice(start, stop) else: raise ValueError('Index must be of the form "x" or "x to y"') pwr = pwr.sel(t=index) pwr_rs = pwr.resample(args.freq, dim='t', how=args.method) if args.file is None: tidx = pwr.indexes['t'] t0, t1 = [t.strftime('%Y%m%d%H%M%S') for t in tidx[0], tidx[-1]] fname = 'pwr_resampled@{0}--{1}.nc'.format(t0, t1) fname = fname.replace(' ', '_') fpath = os.path.join(datadir, fname) else: fpath = os.path.normpath(args.file) pwr_rs.to_netcdf(fpath, engine='h5netcdf')
Java
UTF-8
279
2.546875
3
[]
no_license
public class SubjectTest { public static void main(String[] args) { Subject sbj1 = new Subject(); sbj1.name = "자바프로그래밍"; // sbj1.score = -100; sbj1.setScore(-100); System.out.println(sbj1.getScore()); // System.out.println(sbj1.name + sbj1.score); } }
Java
UTF-8
813
1.867188
2
[]
no_license
package kodlamaio.hrmsdemo.entities.dtos; import kodlamaio.hrmsdemo.entities.concretes.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.hibernate.annotations.CreationTimestamp; import javax.persistence.*; import java.sql.Date; import java.time.LocalDateTime; import java.util.List; @Data @AllArgsConstructor @NoArgsConstructor public class CvDto { private int id; private String candidateId; private String githubLink; private String linkedinLink; private String description; private String photo; private LocalDateTime createdDate; private Date updatedDate; private List<Language> languages; private List<Talent> talents; private List<Education> educations; private List<JobExperience> jobExperiences; }
Java
UTF-8
1,482
2.609375
3
[]
no_license
package net.fenton.core.command; import net.fenton.core.player.FentonPlayer; import net.fenton.core.player.FentonPlayerHandler; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; /** * Created by Encast (2017-01-24 5:02 PM) */ public class ListCommand implements CommandExecutor { public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(label.equalsIgnoreCase("list")) { if(sender instanceof Player) { Player p = (Player) sender; String list = "§2§lPLAYERS: §7(" + Bukkit.getServer().getOnlinePlayers().size() + ") "; int count = 0; int max = FentonPlayerHandler.getInstance().getPlayers().values().size(); for(FentonPlayer fp : FentonPlayerHandler.getInstance().getPlayers().values()) { if(!fp.getSettings().getDisguise().isVanished()) { list += fp.getRank().getColour() + fp.getName(); if(count < (max - 1)) { list += "§7, "; } } count++; } p.sendMessage(list); } else { sender.sendMessage("Only players can use this command."); } } return true; } }
Java
UTF-8
131
1.859375
2
[ "Apache-2.0" ]
permissive
package io.github.dondragon2.spring.nonblocking.callbacks; public interface VoidCallback { void process() throws Exception; }
Shell
UTF-8
445
3.125
3
[]
no_license
#!/bin/sh if [[ "${SKIP_INSTALL}" == "YES" || "${WK_PLATFORM_NAME}" == maccatalyst || "${WK_PLATFORM_NAME}" == iosmac ]]; then exit 0; fi for (( i = 0; i < ${SCRIPT_INPUT_FILE_COUNT}; i++ )); do eval SRC_PLIST=\${SCRIPT_INPUT_FILE_${i}} eval DST_PLIST=\${SCRIPT_OUTPUT_FILE_${i}} DST_PLIST_DIR=$(dirname "$DST_PLIST") mkdir -p "$DST_PLIST_DIR" cp "$SRC_PLIST" "$DST_PLIST" plutil -convert binary1 "$DST_PLIST" done
Java
UTF-8
421
2.6875
3
[]
no_license
package com.example.gofp.head_first.sol.behavioral.strategy.classes; import com.example.gofp.binding.Systems; public class DecoyDuck extends Duck { public DecoyDuck() { this.quackBehaviour = new Squeak(); this.flyBehaviour = new NoFly(); this.swimBehaviour = new NoSwim(); } @Override public void display() { Systems.out.println("Decoy Duck"); } }
Java
UTF-8
204
1.726563
2
[]
no_license
package com.cchao.simplelib.ui.interfaces; /** * Description: 加载View * * @author cchao * @version 2017/8/4 */ public interface ILoadingView { void showLoading(); void hideLoading(); }
Java
UTF-8
1,278
2.96875
3
[]
no_license
package com.wangdong.multithreadprogram.shizhanzhinan.chapterthree; import lombok.extern.slf4j.Slf4j; import java.util.HashMap; import java.util.Map; /** * @description: 3-26 * @author wangdong */ @Slf4j public class StaticVisibilityExample { private static Map<String, String> taskConfig; static { log.info("The class being initialized..."); taskConfig = new HashMap<>(); taskConfig.put("url", "www.wangdong.com"); taskConfig.put("timeout", "1000"); } public static void changeConfig(String url, int timeout) { taskConfig = new HashMap<>(); taskConfig.put("url", url); taskConfig.put("timeout", String.valueOf(timeout)); } public static void init(){ Thread t = new Thread(){ @Override public void run(){ String url = taskConfig.get("url"); String timeout = taskConfig.get("timeout"); doTask(url,Integer.valueOf(timeout)); } }; t.start(); } private static void doTask(String url, Integer timeout) { log.info("url:{}",url); log.info("timeout:{}",timeout); } public static void main(String[] args) { StaticVisibilityExample.init(); } }
C++
UTF-8
277
2.84375
3
[]
no_license
#include <iostream> #include <string> using namespace std; #define REP(i, n) for(int i = 0; i < (int)(n); i++ ) int main() { string o, e; cin >> o >> e; REP(i, e.length()) cout << o[i] << e[i]; if(o.length() - e.length() == 1) cout << o.back(); cout << endl; }
Python
UTF-8
828
2.65625
3
[]
no_license
from ADT.ADTNode import ADTNode class SequenceNode(ADTNode): def accept(self, visitor): return visitor.visit_sequence(self) CDTNameAsBlock = "c.CASTCompoundStatement" CDTNameAsExpression = "c.CASTExpressionList" def __init__(self, id, nodes, resolverUtil): super().__init__(id) self.nodes = [] if "Nodes" in nodes: from ADT.Utils.ResolverUtil import resolveNodeViaType self.nodes.append(resolveNodeViaType(nodes["Nodes"]["$type"], nodes["Nodes"], resolverUtil)) if "$values" in nodes: for node in nodes["$values"]: from ADT.Utils.ResolverUtil import resolveNodeViaType self.nodes.append(resolveNodeViaType(node["$type"], node, resolverUtil)) def returnChildren(self): return self.nodes
C++
UTF-8
5,367
3.28125
3
[]
no_license
#define BUMPER_L_LED 12 // the pin for the left bumper LED #define BUMPER_C_LED 9 // the pin for the centre bumper LED #define BUMPER_R_LED 4 // the pin for the right bumper LED #define SPEED_LED1 8 // the pin for the LED #define SPEED_LED2 7 // the pin for the LED #define SPEED_LED3 6 // the pin for the LED #define SPEED_LED4 5 // the pin for the LED #define BUMPER_R 0 #define BUMPER_C 1 #define BUMPER_L 2 #define MOTOR_L 10 // the pin for the left motor power #define MOTOR_R 11 // the pin for the right motor power int speed_change_dir = 0; int max_speed = 255; int min_speed = 0; int zero_speed = 127; int speed_step = 42; // how much the speed in/decrease per each button press int current_speed = zero_speed; void setup() { pinMode(BUMPER_L_LED, OUTPUT); // tell Arduino LED is an output pinMode(BUMPER_C_LED, OUTPUT); // tell Arduino LED is an output pinMode(BUMPER_R_LED, OUTPUT); // tell Arduino LED is an output pinMode(SPEED_LED1, OUTPUT); // tell Arduino LED is an output pinMode(SPEED_LED2, OUTPUT); // tell Arduino LED is an output pinMode(SPEED_LED3, OUTPUT); // tell Arduino LED is an output pinMode(SPEED_LED4, OUTPUT); // tell Arduino LED is an output pinMode(BUMPER_R, INPUT); pinMode(BUMPER_C, INPUT); pinMode(BUMPER_L, INPUT); pinMode(MOTOR_L, OUTPUT); // tell Arduino LED is an output pinMode(MOTOR_R, OUTPUT); // tell Arduino LED is an output attachInterrupt(0, change_speed, FALLING); Serial.begin(9600); speed_change_dir = 1; randomSeed(analogRead(5)); digitalWrite(SPEED_LED1, HIGH); // always on } int check_bumpers() { int bumps = 0; if(analogRead(BUMPER_R) > 100) { digitalWrite(BUMPER_R_LED, HIGH); bumps = bumps + 1; } else { digitalWrite(BUMPER_R_LED, LOW); } if(analogRead(BUMPER_C) > 100) { digitalWrite(BUMPER_C_LED, HIGH); bumps = bumps + 2; } else { digitalWrite(BUMPER_C_LED, LOW); } if(analogRead(BUMPER_L) > 100) { digitalWrite(BUMPER_L_LED, HIGH); bumps = bumps + 4; } else { digitalWrite(BUMPER_L_LED, LOW); } return bumps; } /** * speed: 0 ... 127 ... 255 = full speed backward ... stop ... full speed forward */ void change_speed() { if (current_speed <= (max_speed - speed_step)) { current_speed = current_speed + speed_step; } else { current_speed = zero_speed; } digitalWrite(SPEED_LED1, HIGH); // always on if (current_speed >= (zero_speed + speed_step)) { digitalWrite(SPEED_LED2, HIGH); } else { digitalWrite(SPEED_LED2, LOW); } if (current_speed >= (zero_speed + 2 * speed_step)) { digitalWrite(SPEED_LED3, HIGH); } else { digitalWrite(SPEED_LED3, LOW); } if (current_speed >= (max_speed - speed_step)) { digitalWrite(SPEED_LED4, HIGH); } else { digitalWrite(SPEED_LED4, LOW); } } void loop() { Serial.println("------"); int bumps = 0; bumps = check_bumpers(); if (bumps > 0) { Serial.print("Bumps: "); Serial.println(bumps); // first go backwards a bit analogWrite(MOTOR_L, (zero_speed - speed_step)); analogWrite(MOTOR_R, (zero_speed - speed_step)); delay(300); // then turn switch (bumps) { case 1: // bumper right hit -> turn left a bit analogWrite(MOTOR_L, -current_speed); analogWrite(MOTOR_R, current_speed); delay(random(100, 300)); break; case 2: // bumper middle hit -> turn left or right a bit if (random(-1,2) < 0) { analogWrite(MOTOR_L, -current_speed); analogWrite(MOTOR_R, current_speed); } else { analogWrite(MOTOR_L, current_speed); analogWrite(MOTOR_R, -current_speed); } delay(random(100, 300)); break; case 3: // bumper right & middle hit -> turn left a bit more analogWrite(MOTOR_L, -current_speed); analogWrite(MOTOR_R, current_speed); delay(random(300, 600)); break; case 4: // bumper left hit -> turn right a bit analogWrite(MOTOR_L, current_speed); analogWrite(MOTOR_R, -current_speed); delay(random(100, 300)); break; case 5: // bumper left & right hit -> turn left or right a lot if (random(-1,2) < 0) { analogWrite(MOTOR_L, -current_speed); analogWrite(MOTOR_R, current_speed); } else { analogWrite(MOTOR_L, current_speed); analogWrite(MOTOR_R, -current_speed); } delay(random(600, 900)); break; case 6: // bumper left & middle hit -> turn right a bit more analogWrite(MOTOR_L, current_speed); analogWrite(MOTOR_R, -current_speed); delay(random(300, 600)); break; case 7: // all bumpers hit -> turn left or right a lot if (random(-1,2) < 0) { analogWrite(MOTOR_L, -current_speed); analogWrite(MOTOR_R, current_speed); } else { analogWrite(MOTOR_L, current_speed); analogWrite(MOTOR_R, -current_speed); } delay(random(600, 900)); break; } } else { analogWrite(MOTOR_L, current_speed); analogWrite(MOTOR_R, current_speed); } Serial.print("Speed: "); Serial.println(current_speed); delay(10); }
Java
WINDOWS-1250
2,728
3.25
3
[]
no_license
package prima3; /** * * @author alex * */ public class Prima3 { public Prima3() {}; /*** * Permite verificar si una persona es apta para reduccion de pago de PRIMA * @param puntos puntos de la licencia * @param puntosQuePuedePerder, cantidad de puntos que puede perder * @return boolean */ public static boolean isAptoParaReduccion(final int puntos, final int puntosQuePuedePerder){ final int calcular=30 - puntosQuePuedePerder; final boolean pase1=calcular <= puntos; final boolean pase2=puntos < 30; final boolean resultado=pase1 && pase2; return resultado; } /*** * Permite identificar el factor de edad para el calculo de PRIMA * @param edad del usuario * @return float */ public static double getFactorEdad(final int edad){ final double v;//value if ( 18 <= edad && edad < 25 ) { v = 2.8;} else if( 25 <= edad && edad < 35 ) {v = 1.8;} else if( 35 <= edad && edad < 45 ) {v = 1.0;} else if( 45 <= edad && edad < 65 ) {v = 0.8;} else if( 65 <= edad && edad <= 90) {v = 1.5;} else {v = -1;}//when wrong input return v; } /*** * Permite identificar el numero minimo para perder puntos a partir de la edad * @param edad del ususario * @return int */ public static int getPuntosQuePuedePerder(final int edad){ final int v;//value if ( 18 <= edad && edad < 25 ) { v = 1;} else if( 25 <= edad && edad < 35 ) {v = 3;} else if( 35 <= edad && edad < 45 ) {v = 5;} else if( 45 <= edad && edad < 65 ) {v = 7;} else if( 65 <= edad && edad <=90 ) {v = 5;} else {v =-1;}//when wrong input return v; } /*** * Retorna el valor de reduccion en el calculo de PRIMA * @param edad del usuario * @return int */ public static int getReduccion(int edad){ int v;//value if ( 18 <= edad && edad < 25 ) v = 50; else if( 25 <= edad && edad < 35 ) v = 50; else if( 35 <= edad && edad < 45 ) v = 100; else if( 45 <= edad && edad < 65 ) v = 150; else if( 65 <= edad && edad < 90 ) v = 200; else v =-1;//when wrong input return v; } /*** * Calcula el valor de la PRIMA * @param tarifaBsica del valor de la PRIMA * @param factorEdad, numero segun la edad * @param reduccionConductorSeguro, puntos minimos que puede perder * @return valor de PRIMA */ public static double getValorPrima(final int tarifaBsica,final double factorEdad,final int reduccionConductorSeguro){ return tarifaBsica * factorEdad - reduccionConductorSeguro; } }
Markdown
UTF-8
448
2.828125
3
[]
no_license
* 100% (1 lb, 453g) Cheese * 100% (1 lb, 453g) Milk or other fluid * 4% (18.12g) Sodium Citrate * 1.33% (6g) Salt * 0.5% (2.3g) Sodium Hexametaphosphate **Sous vide** 1. Cube cheese, and seal everything in a bag. 1. Sous vide at 75c for 15 minutes. 1. Blend until smooth. **Sauce Pan** 1. In medium saucepan, combine cubed cheese, fluid, SC, salt, and SHMP. 1. Heat on medium, stirring until melted/75c. 1. Blend with stick blender until smooth.
Python
UTF-8
2,606
2.65625
3
[ "Apache-2.0" ]
permissive
import abc from pypika.terms import Function from pypika.utils import format_alias_sql class _AbstractSearchString(Function, metaclass=abc.ABCMeta): def __init__(self, name, pattern: str, alias: str = None): super(_AbstractSearchString, self).__init__(self.clickhouse_function(), name, alias=alias) self._pattern = pattern @classmethod @abc.abstractmethod def clickhouse_function(cls) -> str: pass def get_sql(self, with_alias=False, with_namespace=False, quote_char=None, dialect=None, **kwargs): args = [] for p in self.args: if hasattr(p, "get_sql"): args.append('toString("{arg}")'.format(arg=p.get_sql(with_alias=False, **kwargs))) else: args.append(str(p)) sql = "{name}({args},'{pattern}')".format( name=self.name, args=",".join(args), pattern=self._pattern, ) return format_alias_sql(sql, self.alias, **kwargs) class Match(_AbstractSearchString): @classmethod def clickhouse_function(cls) -> str: return "match" class Like(_AbstractSearchString): @classmethod def clickhouse_function(cls) -> str: return "like" class NotLike(_AbstractSearchString): @classmethod def clickhouse_function(cls) -> str: return "notLike" class _AbstractMultiSearchString(Function, metaclass=abc.ABCMeta): def __init__(self, name, patterns: list, alias: str = None): super(_AbstractMultiSearchString, self).__init__(self.clickhouse_function(), name, alias=alias) self._patterns = patterns @classmethod @abc.abstractmethod def clickhouse_function(cls) -> str: pass def get_sql(self, with_alias=False, with_namespace=False, quote_char=None, dialect=None, **kwargs): args = [] for p in self.args: if hasattr(p, "get_sql"): args.append('toString("{arg}")'.format(arg=p.get_sql(with_alias=False, **kwargs))) else: args.append(str(p)) sql = "{name}({args},[{patterns}])".format( name=self.name, args=",".join(args), patterns=",".join(["'%s'" % i for i in self._patterns]), ) return format_alias_sql(sql, self.alias, **kwargs) class MultiSearchAny(_AbstractMultiSearchString): @classmethod def clickhouse_function(cls) -> str: return "multiSearchAny" class MultiMatchAny(_AbstractMultiSearchString): @classmethod def clickhouse_function(cls) -> str: return "multiMatchAny"
Java
UTF-8
224
2.3125
2
[]
no_license
package com.bridgelabz.practiceProblem.CabInvoiceGenerator; public class Ride { public double distance; public double time; public Ride(double distance,double time) { this.distance=distance; this.time=time; } }
Python
UTF-8
4,940
2.71875
3
[]
no_license
# -*- coding: utf-8 -*- __author__ = 'Wyben Gu' ''' Models for user,blog,comment. ''' from app import db from datetime import datetime def dump_datetime(value): """Deserialize datetime object into string form for JSON processing.""" if value is None: return None return value.strftime("%Y-%m-%d %H:%M:%S") class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80),unique=True) email = db.Column(db.String(120),unique=True) password = db.Column(db.String(120)) admin = db.Column(db.Boolean) image = db.Column(db.String(500)) register_date = db.Column(db.DateTime) def __init__(self, username, email, password, admin=False, image='',register_date=None): self.username = username self.email = email self.password = password self.admin = admin self.image = image if register_date is None: register_date = datetime.utcnow() self.register_date = register_date @property def serialize(self): '''Return object data in easily serializeable format''' return { 'id' : self.id, 'username' : self.username, 'password' : self.password, 'admin' : self.admin, 'image' : self.image, 'register_date' : dump_datetime(self.register_date) } def __repr__(self): return '<User %r>' % self.username class Blog(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(80)) summary = db.Column(db.String(200)) content = db.Column(db.Text) pub_date = db.Column(db.DateTime) category_id = db.Column(db.Integer, db.ForeignKey('category.id')) category = db.relationship('Category', backref=db.backref('blogs', lazy='dynamic')) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) author = db.relationship('User', backref=db.backref('blogs',lazy='dynamic')) def __init__(self, title, summary, content, category, author, pub_date=None): self.title = title self.summary = summary self.content = content if pub_date is None: pub_date = datetime.utcnow() self.pub_date = pub_date self.category = category self.author = author @property def serialize(self): '''Return object data in easily serializeable format''' return { 'id' : self.id, 'title' : self.title, 'summary' : self.summary, 'content' : self.content, 'pub_date' : dump_datetime(self.pub_date), 'category' : self.category.serialize, 'author' : self.author.serialize # This is an example how to deal with Many2Many relations #'many2many' : self.serialize_many2many } ''' @property def serialize_many2many(self): """ Return object's relations in easily serializeable format. NB! Calls many2many's serialize property. """ return [ item.serialize for item in self.many2many] ''' def __repr__(self): return '<Blog %r>' % self.title class Category(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50)) def __init__(self, name): self.name = name @property def serialize(self): '''Return object data in easily serializeable format''' return { 'id' : self.id, 'name' : self.name } def __repr__(self): return '<Category %r>' % self.name class Comment(db.Model): id = db.Column(db.Integer, primary_key=True) content = db.Column(db.Text) pub_date = db.Column(db.DateTime) blog_id = db.Column(db.Integer, db.ForeignKey('blog.id')) blog = db.relationship('Blog', backref=db.backref('bcomments',lazy='dynamic')) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) author = db.relationship('User', backref=db.backref('ucomments',lazy='dynamic')) def __init__(self, content, blog, author, pub_date=None): self.content = content self.blog = blog self.author = author if pub_date is None: pub_date = datetime.utcnow() self.pub_date = pub_date @property def serialize(self): '''Return object data in easily serializeable format''' return { 'id' : self.id, 'content' : self.content, 'pub_date' : dump_datetime(self.pub_date), 'blog' : self.blog.serialize, 'author' : self.author.serialize } def __repr__(self): return '<Comment %r>' % self.content
C
UTF-8
10,354
2.9375
3
[]
no_license
#include <sys/types.h> #include <ctype.h> #include <stdlib.h> #include <assert.h> #include <regex.h> #include "finder.h" #include "pattern.h" /*---------------------------------------------------------------------- * private types *----------------------------------------------------------------------*/ #define STACK_SIZE 100 #define MAKE_OP( op, pr ) (((pr) << 8) + op) #define PRIORITY( op ) ((op) >> 8) #define OPERATOR( op ) ((op) & 255) #define ARITY( op ) (OPERATOR(op) == '!' || OPERATOR(op) == '(' ? \ 1 : 2) #define isop( op ) ((op)=='&' || (op)=='|' || (op)=='!' || \ (op)=='(' || (op) == ')') typedef enum { ARG, OP, END } TokenType; typedef enum { OPERANDUS, OPERATOR, ACCEPT, ERROR } States; typedef struct { TokenType type; union { regex_t regex; int op; } data; } StackType; struct _Pattern { StackType stack[STACK_SIZE]; int n_stack; /* no. of elements in stack */ }; /*---------------------------------------------------------------------- * private functions *----------------------------------------------------------------------*/ static int operandus( Pattern pattern, StackType *token, char *token_str, int stack[], int *n_stack, bool *consumed ); static int operator( Pattern pattern, StackType *token, char *token_str, int stack[], int *n_stack, bool *consumed ); static bool pop_to_weaker_op( Pattern pattern, int stack[], int *n_stack, int priority ); static bool pop_to_left_parenthesis( Pattern pattern, int stack[], int *n_stack ); static int push_operator( Pattern pattern, int op ); static char *read_token( const char **regex_str, StackType *token ); static bool regex_compile( regex_t *regex, const char *str ); static bool evaluate( StackType stack[], int *n_stack, const char *buffer ); /*---------------------------------------------------------------------- * Pattern pattern_create( const char *regex_str ) *----------------------------------------------------------------------*/ Pattern pattern_create( const char *regex_str ) { Pattern pattern = (Pattern) malloc( sizeof(struct _Pattern) ); int stack[STACK_SIZE]; int n_stack = 0; char *token_str; bool consumed; StackType token; States state; if( !pattern ) return NULL; pattern->n_stack = 0; state = OPERANDUS; if( !(token_str=read_token(&regex_str, &token)) ) state = ERROR; while( state != ACCEPT && state != ERROR ) { switch( state ) { case OPERANDUS: state = operandus( pattern, &token, token_str, stack, &n_stack, &consumed ); break; case OPERATOR: state = operator( pattern, &token, token_str, stack, &n_stack, &consumed ); break; default: /* it can't happen */ assert( 1 ); } if( consumed && !(token_str=read_token(&regex_str, &token)) ) state = ERROR; } if( state == ERROR ) { free( pattern ); pattern = NULL; } return pattern; } /*---------------------------------------------------------------------- * int operandus( Pattern pattern, StackType *token, char *token_str, * int stack[], int *n_stack, bool *consumed ) *----------------------------------------------------------------------*/ static int operandus( Pattern pattern, StackType *token, char *token_str, int stack[], int *n_stack, bool *consumed ) { int state; *consumed = true; switch( token->type ) { case OP: if( ARITY(token->data.op) == 1 && OPERATOR(token->data.op) != ')' ) { stack[(*n_stack)++] = token->data.op; state = OPERANDUS; } else { /* arity == 2 or ')' */ state = ERROR; error( "unexpected operator: %c", OPERATOR(token->data.op) ); } break; case ARG: /* printf( "operandus:\t%s\n", token_str ); */ pattern->stack[pattern->n_stack++] = *token; state = OPERATOR; break; case END: state = ACCEPT; break; } return state; } /*---------------------------------------------------------------------- * int operator( Pattern pattern, StackType *token, char *token_str, * int stack[], int *n_stack, bool *consumed ) *----------------------------------------------------------------------*/ static int operator( Pattern pattern, StackType *token, char *token_str, int stack[], int *n_stack, bool *consumed ) { States state; StackType ttoken; *consumed = true; switch( token->type ) { case ARG: case OP: if( token->type == ARG || ARITY(token->data.op) == 1 ) { ttoken.type = OP; ttoken.data.op = MAKE_OP( '&', 10 ); /* default */ token = &ttoken; *consumed = false; } if( OPERATOR(token->data.op) == ')' ) { if( pop_to_left_parenthesis(pattern,stack,n_stack) ) { state = OPERATOR; } else { state = ERROR; error( "missing left parenthesis" ); } } else if( ARITY(token->data.op) == 2 ) { pop_to_weaker_op( pattern, stack, n_stack, PRIORITY(token->data.op) ); stack[(*n_stack)++] = token->data.op; state = OPERANDUS; } break; case END: if( pop_to_left_parenthesis(pattern, stack, n_stack) ) { state = ERROR; error( "missing right parenthesis" ); } else { state = OPERANDUS; } break; } return state; } /*---------------------------------------------------------------------- * bool pop_to_weaker_op( Pattern pattern, int stack[], int *n_stack, * int priority ) *----------------------------------------------------------------------*/ static bool pop_to_weaker_op( Pattern pattern, int stack[], int *n_stack, int priority ) { bool found = false; while( *n_stack > 0 && !found ) { found = PRIORITY(stack[*n_stack-1]) < priority; if( !found ) { push_operator( pattern, stack[--*n_stack] ); } } return found; } /*---------------------------------------------------------------------- * bool pop_to_left_parenthesis( Pattern pattern, * int stack[], int *n_stack ) *----------------------------------------------------------------------*/ static bool pop_to_left_parenthesis( Pattern pattern, int stack[], int *n_stack ) { bool found; for( found = false; *n_stack > 0 && !found; --*n_stack ) { found = OPERATOR(stack[*n_stack-1]) == '('; if( !found ) { push_operator( pattern, stack[*n_stack-1] ); } } return found; } /*---------------------------------------------------------------------- * int push_operator( Pattern pattern, int op ) *----------------------------------------------------------------------*/ static int push_operator( Pattern pattern, int op ) { pattern->stack[pattern->n_stack].type = OP; pattern->stack[pattern->n_stack].data.op = op; /* printf( "operator:\t%c\n", op ); */ return ++pattern->n_stack; } /*---------------------------------------------------------------------- * char *read_token( const char **regex_str, StackType *token ) *----------------------------------------------------------------------*/ static char *read_token( const char **regex_str, StackType *token ) { static char buffer[100]; char *pbuffer = buffer; bool rv = true; while( isspace(**regex_str) ) ++*regex_str; switch( **regex_str ) { case '\0': token->type = END; break; case '&': token->type = OP; token->data.op = MAKE_OP( **regex_str, 10 ); ++*regex_str; break; case '|': token->type = OP; token->data.op = MAKE_OP( **regex_str, 5 ); ++*regex_str; break; case '!': token->type = OP; token->data.op = MAKE_OP( **regex_str, 15 ); ++*regex_str; break; case '(': token->type = OP; token->data.op = MAKE_OP( **regex_str, 0 ); ++*regex_str; break; case ')': token->type = OP; token->data.op = MAKE_OP( **regex_str, 0 ); ++*regex_str; break; default: token->type = ARG; while( **regex_str && !isspace(**regex_str) && !isop(**regex_str) ) { if( **regex_str == '\\' ) { if( *++*regex_str ) *pbuffer++ = *(*regex_str)++; } else { *pbuffer++ = *(*regex_str)++; } } *pbuffer = '\0'; rv = regex_compile( &token->data.regex, buffer ); } return rv ? buffer : NULL; } /*---------------------------------------------------------------------- * bool regex_compile( regex_t *regex, const char *str ) *----------------------------------------------------------------------*/ static bool regex_compile( regex_t *regex, const char *str ) { int err; if( (err = regcomp(regex, str, REG_ICASE | REG_NOSUB | REG_EXTENDED)) != 0) { char errstr[100]; regerror( err, regex, errstr, 100 ); error( "can't compile regex: %s, %s", str, errstr ); return false; } return true; } /*---------------------------------------------------------------------- * void pattern_free( Pattern pattern ) *----------------------------------------------------------------------*/ void pattern_free( Pattern pattern ) { free( pattern ); } /*---------------------------------------------------------------------- * bool pattern_match( Pattern pattern, const char *str ) *----------------------------------------------------------------------*/ bool pattern_match( Pattern pattern, const char *str ) { int n_stack = pattern->n_stack; bool found; found = evaluate( pattern->stack, &n_stack, str ); return found; } /*---------------------------------------------------------------------- * bool evaluate( StackType stack[], int *n_stack, const char *buffer ) *----------------------------------------------------------------------*/ static bool evaluate( StackType stack[], int *n_stack, const char *buffer ) { bool rv; if( *n_stack == 0 ) { rv = false; } else if( stack[*n_stack-1].type == OP ) { int op = stack[--*n_stack].data.op; bool rv2 = evaluate( stack, n_stack, buffer ); switch( OPERATOR(op) ) { case '|': rv = rv2 || evaluate( stack, n_stack, buffer ); break; case '&': rv = rv2 && evaluate( stack, n_stack, buffer ); break; case '!': rv = !rv2; break; default: /* this can't be */ assert( 1 ); } } else { /* ARG */ rv = !regexec( &stack[--*n_stack].data.regex, buffer, 0, NULL, REG_NOTBOL | REG_NOTEOL ); } return rv; } /*---------------------------------------------------------------------- * test module *----------------------------------------------------------------------*/ /* int main( int argc, char *argv[] ) { Pattern pattern; prog_name = argv[0]; pattern = pattern_create( argv[1] ); pattern_free( pattern ); return 0; } */
Java
UHC
741
3.109375
3
[]
no_license
package day08; //Ŭ̾Ʈ Ӱ ʿϴ.SimpleServer Ŭ import java.io.InputStream; import java.net.Socket; import java.util.Arrays; public class SocketTest { public static void main(String[] args)throws Exception { // TODO Auto-generated method stub Socket socket = new Socket("localhost", 8888); System.out.println(" ߽ϴ."); //߰ κ. InputStream in = socket.getInputStream(); byte[] buff = new byte[20]; //Ŭ̾Ʈ Ʈ20 ͸ д´. ׷ "ȳϼ!!!" ´. in.read(buff); System.out.println(new String(buff)); in.close(); socket.close(); } }
C++
UTF-8
490
2.703125
3
[]
no_license
class Solution { public: int wiggleMaxLength(vector<int>& nums) { int n = nums.size(); if(n<2) { return n; } int prediff = nums[1]-nums[0]; int ret = prediff!=0?2:1; for(int i=2;i<n;++i) { int diff = nums[i]-nums[i-1]; if((diff>0&&prediff<=0)||(diff<0&&prediff>=0)) { ret++; prediff=diff; } } return ret; } };
Java
UTF-8
1,453
2.265625
2
[]
no_license
package ma.gfi.leap.api.LEAPAPI.core.services; import ma.gfi.leap.api.LEAPAPI.core.dao.models.RevisionProjet; import ma.gfi.leap.api.LEAPAPI.core.dao.repositories.RevisionProjetRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Collection; @Service public class RevisionProjetService implements IRevisionProjetService { @Autowired private RevisionProjetRepository RevisionProjetRepository; @Override public Collection<RevisionProjet> getAllRevisionProjets() { Collection<RevisionProjet> list = new ArrayList<>(); RevisionProjetRepository.findAll().forEach(e -> list.add(e)); return list; } @Override public RevisionProjet getRevisionProjetById(Long RevisionProjetId) { RevisionProjet RevisionProjet = RevisionProjetRepository.findById(RevisionProjetId).get(); return RevisionProjet; } @Override public RevisionProjet addRevisionProjet(RevisionProjet RevisionProjet) { return RevisionProjetRepository.save(RevisionProjet); } @Override public void updateRevisionProjet(RevisionProjet RevisionProjet) { RevisionProjetRepository.save(RevisionProjet); } @Override public void deleteRevisionProjet(Long RevisionProjetId) { RevisionProjetRepository.delete(getRevisionProjetById(RevisionProjetId)); } }
Java
UTF-8
424
1.554688
2
[]
no_license
package org.chock.shop.dto; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import java.util.List; /** * @auther: zhuohuahe * @date: 2019/11/12 09:27 * @description: */ @Getter @Setter @AllArgsConstructor @NoArgsConstructor public class AddOrderDto { private String orderToken; private Integer totalAmount; private String receiveAddressId; }
C++
UTF-8
391
2.765625
3
[]
no_license
#pragma once #include <string> using namespace std; class Book { public: bool lessThan(Book otherBook); // a.lessThan(b) bool operator <(Book otherBook);// a<b friend class Library; friend bool compareByAuthor(Book &, Book &); friend bool compareByName(Book &, Book &); private: string name; string author; string subject; unsigned int id; bool isDeleted; int checkOutBy; };
Python
UTF-8
249
3.484375
3
[]
no_license
n1 = input() def odd_even(n): odd = 0 even = 0 for i in n: if int(i) % 2 != 0: odd += int(i) else: even += int(i) return 'Odd sum = {}, Even sum = {}'.format(odd, even) print(odd_even(n1))
C++
UTF-8
1,008
3.0625
3
[]
no_license
/** * \class Diplodocus * \brief Diplodocus adalah salah satu binatang dalam game * * Diplodocus adalah binatang turunan dari EggProducingAnimal dan MeatProducingAnimal * sehingga Diplodocus bisa menghasilkan telur maupun daging * * \note Habitat Diplodocus adalah Grassland * dan bunyinya adalah "Rawr XD" * * \author Ahmad Rizal Alifio * */ #ifndef _DIPLODOCUS_H #define _DIPLODOCUS_H #include <iostream> #include "EggProducingAnimal.h" #include "MeatProducingAnimal.h" using namespace std; class Diplodocus : public EggProducingAnimal, public MeatProducingAnimal { private: public: /** * \brief Konstruk Diplodocus dengan parametered location, dan bunyi defaultnya * * Diplodocus akan memanggil konstruktor Animal * dengan parameter bunyi "Rawr XD" * * \param _x posisi x Diplodocus * \param _y posisi y Diplodocus */ Diplodocus(int _x, int _y); }; #endif
Python
UTF-8
215
3.234375
3
[]
no_license
def funkcja(): a = 100 b = 200 return a, b if __name__ == "__main__": print(funkcja()) wynik = funkcja() print(wynik[0]) print(wynik[1]) x, y = funkcja() print(x) print(y)
Markdown
UTF-8
10,645
3.171875
3
[]
no_license
## Producers Dagger Producers is an extension to Dagger that implements asynchronous dependency injection in Java. ### Overview This document assumes familiarity with the Dagger 2 API and with Guava’s ListenableFuture. Dagger Producers introduces new annotations @ProducerModule, @Produces, and @ProductionComponent as analogues of @Module, @Provides, and @Component. We refer to classes annotated @ProducerModule as producer modules, methods annotated @Produces as producer methods, and interfaces annotated @ProductionComponent as producer graphs (analogous to modules, provider methods, and object graphs). The key difference from ordinary Dagger is that producer methods may return ListenableFuture<T> and subsequent producer methods may depend on the unwrapped T; the framework handles scheduling the subsequent methods when the future is available. Here is a simple example that mimics a server’s request-handling flow: ```java @ProducerModule(includes = UserModule.class) final class UserResponseModule { @Produces static ListenableFuture<UserData> lookUpUserData( User user, UserDataStub stub) { return stub.lookUpData(user); } @Produces static Html renderHtml(UserData data, UserHtmlTemplate template) { return template.render(data); } } @Module final class ExecutorModule { @Provides @Production static Executor executor() { return Executors.newCachedThreadPool(); } } ``` In this example, the computation we’re describing here says: * call the lookUpUserData method * when the future is available, call the renderHtml method with the result (Note that we haven’t explicitly indicated where User, UserDataStub, or UserHtmlTemplate come from; we’re assuming that the Dagger module UserModule provides those types.) Each of these producer methods will be scheduled on the thread pool that we specify via the binding to @Production Executor. Note that even though the provides method that specifies the executor is unscoped, the production component will only ever get one instance from the provider; so in this case, only one thread pool will be created. To build this graph, we use a ProductionComponent: ```java @ProductionComponent(modules = {UserResponseModule.class, ExecutorModule.class}) interface UserResponseComponent { ListenableFuture<Html> html(); } // ... UserResponseComponent component = DaggerUserResponseComponent.create(); ListenableFuture<Html> htmlFuture = component.html(); ``` Dagger generates an implementation of the interface UserResponseComponent, whose method html() does exactly what we described above: first it calls lookUpUserData, and when that future is available, it calls renderHtml. Both producer methods are scheduled on the provided executor, so the execution model is entirely user-specified. Note that, as in the above example, producer modules can be used seamlessly with ordinary modules, subject to the restriction that provided types cannot depend on produced types. ### Exception handling By default, if a producer method throws an exception, or the future that it returns failed, then any dependent producer methods will be skipped - this models “propagating” an exception up a call stack. If a producer method would like to “catch” that exception, the method can request a Produced<T> instead of a T. For example: ```java @Produces static Html renderHtml( Produced<UserData> data, UserHtmlTemplate template, ErrorHtmlTemplate errorTemplate) { try { return template.render(data.get()); } catch (ExecutionException e) { return errorTemplate.render("user data failed", e.getCause()); } } ``` In this example, if the production of UserData threw an exception (either by a producer method throwing an exception, or by a future failing), then the renderHtml method catches it and returns an error template. If an exception propagates all the way up to the component’s entry point without any producer method catching it, then the future returned from the component will fail with an exception. ### Lazy execution Producer methods can request a Producer<T>, which is analogous to a Provider<T>: it delays the computation of the associated binding until a get() method is called. Producer<T> is non-blocking; its get() method returns a ListenableFuture, which can then be fed to the framework. For example: ```java @Produces static ListenableFuture<UserData> lookUpUserData( Flags flags, @Standard Producer<UserData> standardUserData, @Experimental Producer<UserData> experimentalUserData) { return flags.useExperimentalUserData() ? experimentalUserData.get() : standardUserData.get(); } ``` In this example, if the experimental user data is requested, then the standard user data is never computed. Note that the Flags may be a request-time flag, or even the result of an RPC, which lets users build very flexible conditional graphs. ### Multibindings Several bindings of the same type can be collected into a set or map, just like in ordinary Dagger. For example: ```java @ProducerModule final class UserDataModule { @Produces @IntoSet static ListenableFuture<Data> standardData(...) { ... } @Produces @IntoSet static ListenableFuture<Data> extraData(...) { ... } @Produces @IntoSet static Data synchronousData(...) { ... } @Produces @ElementsIntoSet static Set<ListenableFuture<Data>> rest(...) { ... } @Produces static ... collect(Set<Data> data) { ... } } ``` In this example, when all the producer methods that contribute to this set have completed futures, the Set<Data> is constructed and the collect() method is called. ### Map multibindings Map multibindings are similar to set multibindings: ```java @MapKey @interface DispatchPath { String value(); } @ProducerModule final class DispatchModule { @Produces @IntoMap @DispatchPath("/user") static ListenableFuture<Html> dispatchUser(...) { ... } @Produces @IntoMap @DispatchPath("/settings") static ListenableFuture<Html> dispatchSettings(...) { ... } @Produces static ListenableFuture<Html> dispatch( Map<String, Producer<Html>> dispatchers, Url url) { return dispatchers.get(url.path()).get(); } } ``` Note that here, dispatch() is requesting map values of the type Producer<Html>; this ensures that only the dispatch handler that was requested will be executed. Also note that DispatchPath is a [simple map key] (multibindings.md#simple-map-keys), but that [complex map keys] (multibindings.md#complex-map-keys) are supported as well. ### Scoping Producer methods and production components are implicitly scoped @ProductionScope. Like ordinary scoped bindings, each method will only be executed once within the context of a given component, and its result will be cached. This gives complete control over the lifetime of each binding — it is the same as the lifetime of its enclosing component instance. @ProductionScope may also be applied to ordinary provisions; they will then be scoped to the production component that they’re bound in. Production components may also additionally have other scopes, like ordinary components can. To supply the executor, bind @Production Executor in a ProductionComponent or ProductionSubcomponent. This binding will be implicitly scoped @ProductionScope. For subcomponents, the executor may be bound in any parent component, and its binding will be inherited in the subcomponent (like all bindings are). The executor binding will only be executed once per component instance, even if it is not scoped to the component; that is, it will be implicitly scoped @ProductionScope. ### Component dependencies Like ordinary Components, ProductionComponents may depend on other interfaces: ```java interface RequestComponent { ListenableFuture<Request> request(); } @ProducerModule final class UserDataModule { @Produces static ListenableFuture<UserData> userData( Request request, ...) { ... } } @ProductionComponent( modules = UserDataModule.class, dependencies = RequestComponent.class) interface UserDataComponent { ListenableFuture<UserData> userData(); } ``` Since the UserDataComponent depends on the RequestComponent, Dagger will require that an instance of the RequestComponent be provided when building the UserDataComponent; and then that instance will be used to satisfy the bindings of the getter methods that it offers: ```java ListenableFuture<UserData> userData = DaggerUserDataComponent.builder() .requestComponent(/* a particular RequestComponent */) .build() .userData(); ``` ### Subcomponents Dagger Producers introduces a new annotation @ProductionSubcomponent as an analogue to @Subcomponent. Production subcomponents may be subcomponents of either components or production components. A subcomponent inherits all bindings from its parent component, and so it is often a simpler way of building nested scopes; see subcomponents for more details. ### Monitoring ProducerMonitor can be used to monitor the execution of producer methods; its methods correspond to various places in a producer’s lifecycle. To install a ProducerMonitor, contribute into a set binding of ProductionComponentMonitor.Factory. For example: ```java @Module final class MyMonitorModule { @Provides @IntoSet static ProductionComponentMonitor.Factory provideMonitorFactory( MyProductionComponentMonitor.Factory monitorFactory) { return monitorFactory; } } @ProductionComponent(modules = {MyMonitorModule.class, MyProducerModule.class}) interface MyComponent { ListenableFuture<SomeType> someType(); } ``` When the component is created, each monitor factory contributed to the set will be asked to create a monitor for the component. The resulting (single) instance will be held for the lifetime of the component, and will be used to create individual monitors for each producer method. ### Timing, Logging and Debugging As of March 2016, not implemented yet Since graphs are constructed at compile-time, the graph will be able to be viewed immediately after compiling, likely via writing its structure to json or a proto. Statistics from producer execution (CPU usage of producer method invocations and latency of futures) will be available to export to many endpoints. While a graph is running, its current state will be able to be dumped. ### Optional bindings @BindsOptionalOf works for producers in much the same way as [for providers] (users-guide#optional-bindings). If Foo is produced, or if there is no binding for Foo, then a @Produces method can depend on any of: Optional<Foo> Optional<Producer<Foo>> Optional<Produced<Foo>>
TypeScript
UTF-8
510
3.109375
3
[ "MIT" ]
permissive
export default class ValidationUtils { /** * @description Checks if the provided string is "true" * * @param $stringBoolean * @returns {boolean} */ public static isTrue($stringBoolean){ return ( $stringBoolean === 'true'); }; /** * @description Checks if the provided string is "false" * * @param $stringBoolean * @returns {boolean} */ public static isFalse($stringBoolean){ return ( $stringBoolean === 'false'); }; }
Python
UTF-8
1,637
3.4375
3
[ "Apache-2.0" ]
permissive
import re import string class Owner: def __init__(self, dni, apellidos, nombre): self.nombre = nombre self.apellidos = apellidos self.dni = dni def muestraDatos(self): return [self.nombre, self.apellidos, self.dni] def getDni(self): return self.dni def validaDNI(self, dni): #comprueba la longitud del dni if len(dni)<9 or len(dni)>9: print('Error: DNI has 9 lenght.') return False # Convertimos las letras a mayuscula en caso de tener letras en minuscula dni = string.upper(dni) # Comprobamos que las caracteristicas del NIE se cumplan if re.match("[A-Z]", dni[0]): if 'X' in dni[0]: dni = dni.replace('X','0') elif 'Y' in dni[0]: dni = dni.replace('Y','1') elif 'Z' in dni[0]: dni = dni.replace('Z','2') else: print("Error: Invalid DNI") return False # Comprobamos que tenemos 8 digitos numericos if not re.match("\d{8}", dni[:8]): print("Error: DNI need 8 numeric numbers") return False # Comprobamos que tenemos una letra al final if not re.match("[A-Z]", dni[8]): print("Error: DNI needs one letter") return False # Comprobamos si la letra es correcta tabla = ("TRWAGMYFPDXBNJZSQVHLCKE") if tabla[int(dni[:8]) % 23]==dni[8]: print("Correct DNI") return True else: print("Error: Invalid DNI") return False
JavaScript
UTF-8
1,773
2.53125
3
[]
no_license
import React from 'react'; import InputForm from './InputForm'; import './InputWrapper.css'; class InputWrapper extends React.Component { constructor(props) { super(props) this.state = { topics: [], candidates: [], debates: [], errorOn: false } this.onSubmit = this.onSubmit.bind(this); } onSubmit(topics, candidates, debates) { this.setState({ topics: topics, candidates: candidates, debates: debates }, () => { if (this.state.topics.length) { this.setState({ errorOn: false }) this.props.onInputChange( { topics: this.state.topics, candidates: this.state.candidates, debates: this.state.debates } ) } else { this.setState({ errorOn: true }) this.props.onClear() } }); } render(){ return( <div> <InputForm topics={this.state.topics} candidates={this.state.candidates} debates={this.state.debates} onSubmit={this.onSubmit}> </InputForm> <ErrorMessage errorOn={this.state.errorOn}></ErrorMessage> </div> ) } } function ErrorMessage(props) { if (props.errorOn) { return ( <div className="error-message"> Please insert at least 1 topic! </div> ) } return null; } export default InputWrapper;
Java
UTF-8
2,344
3.3125
3
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
package com.example.simpleparadox.listycity; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class CityListTest { private CityList mockCityList() { CityList cityList = new CityList(); cityList.add(mockCity()); return cityList; } private City mockCity() { return new City("Edmonton", "Alberta"); } @Test void testAdd() { CityList cityList = mockCityList(); assertEquals(1, cityList.getCities().size()); City city = new City("Regina", "Saskatchewan"); cityList.add(city); assertEquals(2, cityList.getCities().size()); assertTrue(cityList.getCities().contains(city)); } @Test void testAddException() { CityList cityList = mockCityList(); City city = new City("Yellowknife", "Northwest Territories"); cityList.add(city); assertThrows(IllegalArgumentException.class, () -> cityList.add(city)); } @Test void testGetCities() { CityList cityList = mockCityList(); assertEquals(0, mockCity().compareTo(cityList.getCities().get(0))); City city = new City("Charlottetown", "Prince Edward Island"); cityList.add(city); assertEquals(0, city.compareTo(cityList.getCities().get(0))); assertEquals(0, mockCity().compareTo(cityList.getCities().get(1))); } @Test void testHasCities() { CityList cityList = mockCityList(); City city = new City("Vancouver", "British Columbia"); assertFalse(cityList.hasCity(city)); cityList.add(city); assertTrue(cityList.hasCity(city)); } @Test void testDeleteCity() { CityList cityList = mockCityList(); City city = new City("Vancouver", "British Columbia"); City mockCity = mockCity(); assertEquals(1, cityList.getCities().size()); assertDoesNotThrow(() -> cityList.delete(mockCity)); assertThrows(IllegalArgumentException.class, () -> cityList.delete(city)); assertEquals(0, cityList.getCities().size()); } @Test void testCountCity() { CityList cityList = mockCityList(); City city = new City("Vancouver", "British Columbia"); assertEquals(cityList.getCities().size(), cityList.countCities()); } }
Go
UTF-8
2,750
3.328125
3
[ "MIT" ]
permissive
package bloomd import ( "bufio" "io" "net" "os" "strconv" "strings" "time" ) // Connection materializes a concrete connection to bloomd type Connection struct { Server string Timeout time.Duration Socket *net.TCPConn File *os.File Attempts int Reader *bufio.Reader } // Create a TCP socket for the connection func (c *Connection) createSocket() (err error) { addr, err := net.ResolveTCPAddr("tcp", c.Server) if err != nil { return err } c.Socket, err = net.DialTCP("tcp", nil, addr) if err != nil { return err } c.Reader = bufio.NewReader(c.Socket) if c.Attempts == 0 { c.Attempts = 3 } return nil } // Send sends a command to the server func (c *Connection) Send(cmd string) error { if c.Socket == nil || c.Socket.LocalAddr() == nil { err := c.createSocket() if err != nil { return &BloomdError{ErrorString: err.Error()} } } for i := 0; i < c.Attempts; i++ { _, err := c.Socket.Write([]byte(cmd + "\n")) if err != nil { c.createSocket() break } return nil } return errSendFailed(cmd, strconv.Itoa(c.Attempts)) } // Read returns a single line from the socket file func (c *Connection) Read() (line string, err error) { if c.Socket == nil || c.Socket.LocalAddr() == nil { err := c.createSocket() if err != nil { return "", &BloomdError{ErrorString: err.Error()} } } l, rerr := c.Reader.ReadString('\n') if rerr != nil && rerr != io.EOF { return l, &BloomdError{ErrorString: rerr.Error()} } return strings.TrimRight(l, "\r\n"), nil } // ReadBlock reads a response block from the server. The servers responses are between // `start` and `end` which can be optionally provided. Returns an array of // the lines within the block. func (c *Connection) ReadBlock() (lines []string, err error) { first, err := c.Read() if err != nil { return lines, err } if first != "START" { return lines, &BloomdError{ErrorString: "Did not get block start START! Got '" + string(first) + "'!"} } for { line, err := c.Read() if err != nil { return lines, err } if line == "END" || line == "" { break } lines = append(lines, string(line)) } return lines, nil } // SendAndReceive is a convenience wrapper around `send` and `read`. Sends a command, // and reads the response, performing a retry if necessary. func (c *Connection) SendAndReceive(cmd string) (string, error) { err := c.Send(cmd) if err != nil { return "", err } return c.Read() } func (c *Connection) responseBlockToMap() (map[string]string, error) { lines, err := c.ReadBlock() if err != nil { return nil, err } theMap := make(map[string]string) for _, line := range lines { split := strings.SplitN(line, " ", 2) theMap[split[0]] = split[1] } return theMap, nil }
Java
UTF-8
2,708
1.78125
2
[]
no_license
package com.richotaru.notificationapi; import com.richotaru.notificationapi.dao.AppRepository; import com.richotaru.notificationapi.dao.ClientAccountRepository; import com.richotaru.notificationapi.dao.SubscriptionPlanRepository; import com.richotaru.notificationapi.service.NotificationService; import com.richotaru.notificationapi.service.SettingService; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.web.servlet.MockMvc; import javax.annotation.PostConstruct; import java.time.Duration; import java.time.LocalDateTime; @AutoConfigureMockMvc @SpringBootTest public abstract class IntegrationTest { @Autowired protected MockMvc mockMvc; @Autowired protected SettingService settingService; @Autowired protected AppRepository appRepository; @Autowired protected SubscriptionPlanRepository subscriptionPlanRepository; @Autowired protected ClientAccountRepository clientAccountRepository; @MockBean protected NotificationService notificationService; static LocalDateTime startTime; static LocalDateTime endTime; protected Long emailRequestLimitFree; protected Long smsRequestLimitFree; @BeforeEach public void before() { startTime = LocalDateTime.now(); Mockito.doNothing().when(notificationService).sendEmail(Mockito.any()); Mockito.doNothing().when(notificationService).sendSms(Mockito.any()); } @AfterEach public void after() { endTime = LocalDateTime.now(); System.out.println("----------------- STATS -----------------"); System.out.println(String.format("Test start time : %s", startTime)); System.out.println(String.format("Test end time : %s", endTime)); System.out.println(String.format("Execution time : %sms", Duration.between(startTime,endTime).toMillis())); System.out.println(String.format("Execution time in milliseconds : %sms", Duration.between(startTime,endTime).toMillis())); System.out.println("------------------------------------------"); } @PostConstruct private void init() { emailRequestLimitFree = settingService.getLong("EMAIL_LIMIT_FREE", 2); smsRequestLimitFree = settingService.getLong("SMS_LIMIT_FREE", 2); } }
Swift
UTF-8
1,445
2.890625
3
[]
no_license
// // CharactersListFlowCoordinator.swift // Marvel-Wiki // // Created by Ramzy on 15/08/2021. // import UIKit protocol CharactersListFlowCoordinatorDependencies { func makeCharactersListViewController(actions: CharactersListViewModelActions) -> CharactersListViewController func makeCharacterDetialsViewController(character: CharactersData) -> UIViewController } final class CharactersListFlowCoordinator { private weak var navigationController: UINavigationController? private let dependencies: CharactersListFlowCoordinatorDependencies private weak var charactersListViewController: CharactersListViewController? init(navigationController: UINavigationController, dependencies: CharactersListFlowCoordinatorDependencies) { self.navigationController = navigationController self.dependencies = dependencies } func start() { let actions = CharactersListViewModelActions(showChracterDetail: navigateToCharacterDetails) let vc = dependencies.makeCharactersListViewController(actions: actions) navigationController?.pushViewController(vc, animated: false) charactersListViewController = vc } private func navigateToCharacterDetails(character: CharactersData) { let vc = dependencies.makeCharacterDetialsViewController(character: character) navigationController?.pushViewController(vc, animated: true) } }
Java
UTF-8
2,010
3.625
4
[]
no_license
package ships.dev.functional; import java.util.Scanner; public class Game { private static final int boardSize = 7; private static final int numberOfShips = 3; private char[][] board = new char[boardSize][boardSize]; public static void main(String[] args){ Ships ships = new Ships(); Game Options = new Game(); System.out.println(); Options.createBoard(); ships.setBoard(Options.board); Options.setShips(ships); ships.showBoard(); Options.play(ships); } private void createBoard(){ for(int i = 0; i < boardSize; i++){ for(int j = 0; j < boardSize; j++){ board[i][j] = '0'; } } } private void setShips(Ships DC){ for(int counter = 0; counter < numberOfShips; counter++){ DC.setShip(); } } private void play(Ships DC){ int xMove, yMove; Scanner scanner = new Scanner(System.in); do{ // X Check do{ System.out.print("Enter X: "); String sX = scanner.nextLine(); xMove = Integer.parseInt(sX); if(xMove < 1 || xMove > 7){ System.out.println("Invalid enter, repeat pls."); } } while(xMove < 1 || xMove > 7); // Y Check do{ System.out.print("Enter Y: "); String sY = scanner.nextLine(); yMove = Integer.parseInt(sY); if(yMove < 1 || yMove > 7){ System.out.println("Invalid enter, repeat pls."); } } while(yMove < 1 || yMove > 7); // Shoot(X,Y) DC.checkHit(xMove - 1, yMove - 1 ); // Show Hidden Board DC.showHiddenBoard(); if(DC.numberOfHits == 9){ System.out.println("U won the game!"); } } while(DC.numberOfHits != 9); } }
Java
UTF-8
1,607
3.265625
3
[]
no_license
package leetcodeMedium; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.PriorityQueue; public class LCNo692 { public static void main(String[] args) { // TODO Auto-generated method stub String s1 = "b"; String s2 = "aab"; System.out.println(s1.compareTo(s2)); String[] words = new String[] {"i", "love", "leetcode", "i", "love", "coding"}; int k = 1; System.out.println(topKFrequent(words, k)); } public static List<String> topKFrequent(String[] words, int k) { List<String> res = new ArrayList<String>(); HashMap<String, Integer> map = new HashMap<String, Integer>(); PriorityQueue<String> heap = new PriorityQueue<String>(new Comparator<String>() { @Override public int compare(String o1, String o2) { // TODO Auto-generated method stub int value1 = map.get(o1); int value2 = map.get(o2); if (value1 == value2) { //System.out.println(o1.compareTo(o2)); return o2.compareTo(o1); } return value1 - value2; } }); for(String s : words) { if(map.containsKey(s)) { map.put(s, map.get(s)+1); }else { map.put(s, 1); } } for(String s : map.keySet()) { heap.offer(s); if(heap.size()>k) { heap.poll(); } } while(heap.size()!=0) { res.add(heap.poll()); } Collections.reverse(res); return res; } }
Shell
UTF-8
4,512
3.734375
4
[]
no_license
#!/usr/bin/env bash # # Create a path to a log file that encodes # into the path the date and time to minute resolution # LOG="$PWD/log.$(date +"%Y-%m-%dT%H:%m")" # To handle global redirection #exec 3>&1 4>&2 >>$LOG 2>&1 #exec 1>&3 2>&4 log() { typeset -r msg=$1 echo "$(date): $msg" } # # Update packages # log "Updating packages..." sudo yum update >> $LOG 2>&1 # # Packages for sane administration # log "Installing system adminstration packages..." sudo yum install -y man wget >> $LOG 2>&1 log "Installing EPEL gpg keys and package..." wget https://fedoraproject.org/static/0608B895.txt >> $LOG 2>&1 sudo mv 0608B895.txt /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6 >> $LOG 2>&1 sudo rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6 >> $LOG 2>&1 sudo rpm -ivh http://mirrors.mit.edu/epel/6/x86_64/epel-release-6-8.noarch.rpm >> $LOG 2>&1 # # Install packages required for Nagios # log "Installing required packages for Nagios..." sudo yum install -y wget httpd php gcc glibc glibc-common gd gd-devel make net-snmp mailx >> $LOG 2>&1 # # Required packages for RVM # log "Install required packages for RVM..." sudo yum install -y patch libyaml-devel libffi-devel autoconf gcc-c++ patch readline-devel openssl-devel automake libtool bison >> $LOG 2>&1 # # Required packages for Boundary Event Integration # log "Install required packages for Boundary Event Integration..." sudo yum install -y curl unzip >> $LOG 2>&1 # # Add the nagios user and groups # NAGIOS_USER=nagios NAGIOS_GROUP=nagios NAGIOS_CMD_GROUP=nagcmd VAGRANT_USER=vagrant log "Add required users and groups..." sudo useradd ${NAGIOS_USER} >> $LOG 2>&1 sudo groupadd ${NAGIOS_CMD_GROUP} >> $LOG 2>&1 sudo usermod -a -G ${NAGIOS_CMD_GROUP} ${NAGIOS_USER} >> $LOG 2>&1 echo "nagios" | sudo passwd nagios --stdin >> $LOG 2>&1 sudo usermod -a -G ${NAGIOS_CMD_GROUP} ${VAGRANT_USER} >> $LOG 2>&1 # # Download the Nagios distribution # log "Downloading Nagios core and plugins..." NAGIOS_CORE_DIR="nagios-3.5.1" NAGIOS_PLUGINS_DIR="nagios-plugins-2.0" NAGIOS_CORE_TAR="${NAGIOS_CORE_DIR}.tar.gz" NAGIOS_PLUGINS_TAR="${NAGIOS_PLUGINS_DIR}.tar.gz" # Nagios core wget http://prdownloads.sourceforge.net/sourceforge/nagios/${NAGIOS_CORE_TAR} >> $LOG 2>&1 # Nagios plugins wget http://nagios-plugins.org/download/${NAGIOS_PLUGINS_TAR} >> $LOG 2>&1 # Extract log "Extract Nagios core and plugins..." tar xvf "${NAGIOS_CORE_TAR}" >> $LOG 2>&1 tar xvf "${NAGIOS_PLUGINS_TAR}" >> $LOG 2>&1 # # Create directory to install Nagios # log "Create Nagios install directory..." NAGIOS_INSTALL=/usr/local/nagios NAGIOS_INSTALL_PERM=0755 sudo mkdir ${NAGIOS_INSTALL} >> $LOG 2>&1 sudo chown ${NAGIOS_USER}:${NAGIOS_GROUP} ${NAGIOS_INSTALL} >> $LOG 2>&1 sudo chmod ${NAGIOS_INSTALL_PERM} ${NAGIOS_INSTALL} >> $LOG 2>&1 # Build and install Nagios pushd nagios > /dev/null 2>&1 log "Build Nagios..." ./configure --with-command-group=${NAGIOS_CMD_GROUP} >> $LOG 2>&1 make all >> $LOG 2>&1 log "Install Nagios..." make install >> $LOG 2>&1 sudo make install-init >> $LOG 2>&1 make install-config >> $LOG 2>&1 make install-commandmode >> $LOG 2>&1 sudo make install-webconf >> $LOG 2>&1 # Copy contributions log "Install contributed event handlers..." cp -R contrib/eventhandlers ${NAGIOS_INSTALL}/libexec >> $LOG 2>&1 sudo chown -R ${NAGIOS_USER}:${NAGIOS_GROUP} ${NAGIOS_INSTALL}/libexec/eventhandlers >> $LOG 2>&1 popd > /dev/null 2>&1 log "$(id vagrant)" echo "export PATH=\$PATH:${NAGIOS_INSTALL}/libexec:${NAGIOS_INSTALL}/bin" >> /home/$VAGRANT_USER/.bash_profile log "Validate nagios configuration..." ${NAGIOS_INSTALL}/bin/nagios -v ${NAGIOS_INSTALL}/etc/nagios.cfg >> $LOG 2>&1 # Start the Nagios and httpd services log "Start nagios and httpd..." sudo /etc/init.d/nagios start >> $LOG 2>&1 sudo /etc/init.d/httpd start >> $LOG 2>&1 # Define our administrative user and password log "Configure nagios admin..." htpasswd -b -c ${NAGIOS_INSTALL}/etc/htpasswd.users nagiosadmin nagios123 >> $LOG 2>&1 log "Build Nagios plugins..." pushd "${NAGIOS_PLUGINS_DIR}" >> $LOG 2>&1 ./configure --with-nagios-user=${NAGIOS_USER} --with-nagios-group=${NAGIOS_GROUP} >> $LOG 2>&1 make >> $LOG 2>&1 make install >> $LOG 2>&1 popd >> $LOG 2>&1 # Configure startup log "Configuring nagios and httpd startup..." sudo chkconfig --add nagios >> $LOG 2>&1 sudo chkconfig --level 35 nagios on >> $LOG 2>&1 sudo chkconfig --add httpd >> $LOG 2>&1 sudo chkconfig --level 35 httpd on >> $LOG 2>&1 log "Details of the installation have been logged to $LOG"
Markdown
UTF-8
1,086
2.59375
3
[]
no_license
--- layout: post title: A test, a test date: '2010-09-06T02:14:00.000+10:00' author: Zarah Dominguez tags: - hello - android modified_time: '2010-09-06T03:31:38.537+10:00' blogger_id: tag:blogger.com,1999:blog-8588450866181483028.post-8641279766713478805 blogger_orig_url: http://www.zdominguez.com/2010/09/test-test.html --- I was thinking of starting a quick-tips style blog for software development (mostly for myself, since I tend to forget stuff a lot recently). And since I am working on Android now, this would most probably focus on tips and notes on application development for that platform. And now, I test [SyntaxHighlighter](http://alexgorbatchev.com/SyntaxHighlighter/). ```java @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView text = new TextView(); text.setText("Hello, Droid warriors!"); setContentView(text); } ``` And now I test external images! ![Imgur](https://i.imgur.com/g3M5YgK.png) Using HTML: <img src="https://i.imgur.com/g3M5YgK.png"> Now a GIF: ![GIF](https://i.imgur.com/Bz3DVdd.gifv)
PHP
UTF-8
1,381
3.203125
3
[ "MIT" ]
permissive
<?php namespace Noodlehaus\Writer; /** * Properties Writer. * * @package Config * @author Jesus A. Domingo <jesus.domingo@gmail.com> * @author Hassan Khan <contact@hassankhan.me> * @author Filip Š <projects@filips.si> * @author Mark de Groot <mail@markdegroot.nl> * @link https://github.com/noodlehaus/config * @license MIT */ class Properties extends AbstractWriter { /** * {@inheritdoc} * Writes an array to a Properties string. */ public function toString($config, $pretty = true) { return $this->toProperties($config); } /** * {@inheritdoc} */ public static function getSupportedExtensions() { return ['properties']; } /** * Converts array to Properties string. * @param array $arr Array to be converted * * @return string Converted array as Properties */ protected function toProperties(array $arr) { $converted = ''; foreach ($arr as $key => $value) { if (is_array($value)) { continue; } // Escape all space, ; and = characters in the key: $key = addcslashes($key, ' :='); // Escape all backslashes and newlines in the value: $value = preg_replace('/([\r\n\t\f\v\\\])/', '\\\$1', $value); $converted .= $key.' = '.$value.PHP_EOL; } return $converted; } }
Python
UTF-8
2,894
2.859375
3
[]
no_license
import xlsxwriter import os from time import sleep from datetime import datetime hclogin = "END0FTH3W0R1D" hclcount = 1 slcount = 1 kickcounter = 0 offloop = 1 loggoloop = 1 while hclcount == 1: if kickcounter < 3: hclinput = input("Please enter your application password: ") if hclinput == hclogin: print("Welcome to Syclone Attendance Tracker") time = datetime.now() current_time = time.strftime("%H:%M:%S") print("The time is " + current_time) hclcount = 0 else: print("You have entered the wrong password, please try again.") kickcounter = kickcounter + 1 else: print("You have failed too many times, please try again later") quit() kickcounter = 0 while offloop == 1: offline = input("Do you wish to use offline mode, or connect to the internet? (OFF/ON) ") if offline == "ON" or offline == "on": offloop = 0 while slcount == 1: if kickcounter < 3: slinput = input("Please enter your school: ") slist = {"DPSI-SKET", "RICK-ROLL"} if slinput in slist: print("You have chosen institution " + slinput) slcount = 0 while loggoloop == 1: print("Please login into your account for " + slinput) loggo = input("Your username: ") passo = input("Your password: ") lodict = { 'King Syclone':'Platinum', 'Aha Aha': 'Gold' } if lodict[loggo] == passo: print("Welcome to " + slinput + ", " + loggo) loggoloop = 0 else: print("Please try again, the account specifed doesn't exist") else: print("You have entered an invalid code, please try again.") kickcounter = kickcounter + 1 else: print("You have failed too many times, please try again later") elif offline == "OFF" or offline == "off": offloop = 0 else: print("You have put an invalid choice, please put the correct one") workbook = xlsxwriter.Workbook('venv/aylmao.xlsx') worksheet = workbook.add_worksheet() row = 1 col = 0 worksheet.write(0, 0, 'Name') worksheet.write(0, 1, 'Ticket') worksheet.write(0, 2, 'Age') worksheet.write(0, 3, 'Attendance') for item, cost, age in (dict): worksheet.write(row, col, item) worksheet.write(row, col + 1, cost) worksheet.write(row, col + 2, age) worksheet.write(row, col + 3, 'No') row += 1 workbook.close()
Python
UTF-8
24,103
2.90625
3
[ "MIT" ]
permissive
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from ressources import config as c from ressources.config import bcolors import time import base64 import random ########################### # LIVE CHAIN # ########################### """ This is a single-threaded simulation, so adding miners will not speed up block validation. On the contrary, as the simulation will have to deal with the different miners at the same time, it will be strongly slowed down. It is therefore recommended to keep the number of miners at a relatively low level. However, if the number of miners is high, the frequency of transactions and the difficulty of the proof of work must be reduced. Note that reducing the difficulty of the proof of work will not be sufficient if the transaction frequency is too high. Because all the calculation time will be spent verifying the transactions for each miner rather than calculating the proof of work. """ def network( limit: int, rangeBS: tuple = (1, 2), rangeTB: tuple = (3, 5), rangeAm: tuple = (1, 10), ): """ Loop that creates random users and transactions, stops when block limit is reached limit: stops when the number of block in the block-chain have reach limit rangeBS: range between each cycles of transactions (e.g. new cycle between every (1, 2) seconds) rangeTB: range of transactions per cycles (e.g. between (3, 5) transactions are generated per cycle) rangeAm: range between which amount of the transaction is choosen (e.g. transaction amount is between (1, 10)) Transaction frequency calculation: avg(rangeTB) / avg(rangeBS) = average number of transactions per second """ # List of most used french names names = [ "Martin", "Bernard", "Dubois", "Thomas", "Robert", "Richard", "Petit", "Durand", "Leroix", "Moreau", "Simon", "Laurent", "Lefebvre", "Michel", "Garcia", "David", "Bertrand", "Roux", "Vincent", "Fournier", "Morel", "Girard", "André", "Lefèvre", "Mercier", "Dupont", "Lambert", "Bonnet", "Francois", "Matinez", "Gobinet", "Mazoin", ] # While the limit is not reached, we generate random users and random transactions while len(c.BC_CHAIN) < limit: # random users generation if int(time.time() % 2) or len(c.BC_USERS) <= 2: addUser(random.choice(names)) nbUsers = len(c.BC_USERS) # random transactions generation if len(c.BC_USERS) > 2: for _ in range(random.randint(rangeTB[0], rangeTB[1])): sender = random.randrange(1, nbUsers) receiver = random.randrange(1, nbUsers) while sender == receiver: receiver = random.randrange(1, nbUsers) addTransaction(sender, receiver, random.randint(rangeAm[0], rangeAm[1])) time.sleep(random.randrange(rangeBS[0], rangeBS[1])) def mine(user: int): """ Try to validate the last block Restart the validation process when the chain has been changed Loop until the block has been validated by him or someone else user: user id of the miner """ cBIndex = len(c.BC_CHAIN) - 1 index = -1 cBlock = [] cUTXO = [] while cBIndex == (len(c.BC_CHAIN) - 1): res = validBlock(cBIndex, user, (index, cBlock, cUTXO)) if isinstance(res, tuple): index, cBlock, cUTXO = res def startLive( limit: int, maxMiner: int, rangeTB: tuple = (10, 15), rangeBS: tuple = (2, 3), rangeAm: tuple = (1, 10), ): """ Main function to start the live execution of the block-chain limit: stops when the number of block in the block-chain have reach limit maxMiner: maximal number of simultaneous miner rangeBS: range between each cycles of transactions (e.g. new cycle between every (1, 2) seconds) rangeTB: range of transactions per cycles (e.g. between (3, 5) transactions are generated per cycle) rangeAm: range between which amount of the transaction is choosen (e.g. transaction amount is between (1, 10)) """ import threading initChain() tN = threading.Thread( target=network, args=( limit, rangeTB, rangeBS, rangeAm, ), ) tN.daemon = True tN.start() cLogs = 0 while len(c.BC_CHAIN) < limit: cL = len(c.BC_CHAIN) selectedMiner = [] while not selectedMiner: nbMiner = min(len(c.BC_USERS) - 1, maxMiner) selectedMiner = random.sample(range(1, len(c.BC_USERS)), nbMiner) time.sleep(0.1) for miner in selectedMiner: tM = threading.Thread(target=mine, args=(miner,)) tM.daemon = True tM.start() while cL == len(c.BC_CHAIN): cLogs = displayLogs(cLogs) time.sleep(0.1) displayLogs(cLogs) print() displayBC() return validChain(0) ###################### # TESTS # ###################### def createTestBC(): """ Quick demonstration of how blockchain works """ c.BC_KEY_SIZE = 128 c.BC_POW_RATIO = 0.1 logState = 0 # create the 1st block initChain() logState = displayLogs(logState) # create 2 users Al = addUser("Hali") Bo = addUser("Baba") # valid the block -> reward money to miner (Alice) validBlock(len(c.BC_CHAIN) - 1, Al) logState = displayLogs(logState) validBlock(len(c.BC_CHAIN) - 1, Al) logState = displayLogs(logState) # with reward, alice have enough to send to Bob validBlock(len(c.BC_CHAIN) - 1, Bo) logState = displayLogs(logState) addTransaction(Al, Bo, 20) logState = displayLogs(logState) validBlock(len(c.BC_CHAIN) - 1, Al) logState = displayLogs(logState) print() displayBC() print("Chain valid: ", validChain(Al)) print("Last block valid: ", isValidBlock(Al, len(c.BC_CHAIN) - 1, True)) ###################### # CORE # ###################### def initChain(): """ Create the first block of the block-chain """ from core.hashbased import hashFunctions as hf # Reset variables c.BC_CHAIN = [] c.BC_USERS = [] c.BC_UTXO = [] c.BC_LOGS = [] firstBlock = [hf.sponge(b"Lorsqu'un canide aboie, ca fait BARK", c.BC_HASH_SIZE)] fBTB = arrayToBytes(firstBlock) firstBlock.append(hf.PoW(fBTB, getAdaptativePOWnb(len(fBTB), True))) c.BC_TIME_START = time.time() c.BC_CHAIN.append(firstBlock) c.BC_CHAIN.append([]) addUser("Network") def validChain(user: int): """ Check the integrity of the blockchain, return boolean user: user id of the user who perform the check, it can be 0 for network """ # Reset users UTXO to follow block-chain UTXO = [] # Don't check last block as it has not been validated for i in range(0, len(c.BC_CHAIN) - 1): vB = isValidBlock(i, user, False, UTXO) if vB is not True: if vB is not False: print("Unvalid block: ", i, " - Transaction: ", vB) else: print("Unvalid block previous hash or salt: ", i) return False return True def isValidBlock(blockI: int, user: int, lastValidedBlock: bool = False, UTXO: list = c.BC_UTXO): """ Check block integrity: previous hash, salt, transactions signature, transactions funds blockI: blockI: block id corresponding of its index in the block-chain user: user id of the user who perform the check lastValidedBlock: if the check only concernes the last validated block, transactions are not performed as we suppose the network has done it. UTXO: current state of UTXO """ from core.hashbased import hashFunctions as hf cBlock = c.BC_CHAIN[blockI] # check every transactions for i, b in enumerate(cBlock): # if it's a transaction, valid it if isinstance(b, list): if not validTransaction(user, b, UTXO): return i prevH = cBlock[-2] # do not check previous hash for the first block if blockI: prevBlockH = getBlockHash(blockI - 1) else: prevBlockH = prevH # Salt is verified bH = getBlockHash(blockI, False) saltValid = hf.nullBits(bH, getAdaptativePOWnb(len(arrayToBytes(cBlock[:-1])), blockI < 2)) # Previous hash is verified hashValid = prevBlockH == prevH # if the previous block calculated hash is the same that the one stored and the salt is ok, block is valid return saltValid and hashValid def validBlock(blockI: int, user: int, validated: tuple = (-1, [], [])): """ Valid a block referenced by its ID, verify the transactions, calcul the hash & salt Block format [transaction #0, transaction #1, transaction #2, ..., hash of block n-1, salt] blockI: block id corresponding of its index in the block-chain user: id of the miner (user which validated the block) validated: (lastIndexChecked, [validTransactions], [UTXO state]) already validated transactions """ from core.hashbased import hashFunctions as hf if not user: return False addLog(user, 0, [blockI]) # Make a copy of the current block and operate on the copy cBlock = c.BC_CHAIN[blockI].copy() # Length of block original = c.BC_CHAIN[blockI].copy() # Make a copy of current UTXO to check the transaction if validated[0] != -1: # if already validated transactions, get back the UTXO state of previous transactions cUTXO = validated[2] else: # No already validated transactions cUTXO = c.BC_UTXO.copy() unvalidTransactions = [] # verify every transactions, transactions are performled on the local copy of UTXO i = 0 for i, b in enumerate(cBlock): # if it's a transaction, valid it if isinstance(b, list): if i > validated[0]: # if the transaction is not valid, it's ingored -> removed of the block for validation if not validTransaction(user, b, cUTXO): addLog(user, 1, [transactionToString(b, cUTXO)]) unvalidTransactions.append(b) else: # Block already validated addLog(user, 8, [blockI]) return False # remove unvalid transactions from the local copy for transaction in unvalidTransactions: cBlock.remove(transaction) # add already validated transactions to the local copy cBlock = validated[1] + cBlock[validated[0] + 1:] # Calculating the hash of the previous block prevH = getBlockHash(c.BC_CHAIN[blockI - 1]) # Check if block as changed (e.g. new transaction, block validated by someone else) if c.BC_CHAIN[blockI] != original: addLog(user, 9, [blockI]) return (i, cBlock, cUTXO) # Calculating the proof of work -> mining bytesBlock = arrayToBytes(cBlock + [prevH]) nbNullBits = getAdaptativePOWnb(len(bytesBlock), blockI < 2) addLog(user, 5, [blockI, nbNullBits, len(bytesBlock)]) proof = hf.PoW(bytesBlock, nbNullBits, ("BC_CHAIN", blockI)) # return false if block as changed before POW has been found (e.g. new transaction, block validated by someone else) if not proof: addLog(user, 9, [blockI]) return (i, cBlock, cUTXO) # POW found addLog(user, 6, [blockI, proof]) # Check if block as changed (e.g. new transaction, block validated by someone else) if c.BC_CHAIN[blockI] != original: addLog(user, 9, [blockI]) return (i, cBlock, cUTXO) # Send the validation to the block-chain by validating the real block c.BC_CHAIN[blockI] = cBlock + [prevH, proof] addLog(user, 7, [blockI]) # Perform all transactions for t in cBlock: if isinstance(t, list): # Not supposed to happen, valided transaction can't be proceeded if not transitUTXO(t[0], t[1], t[2]): raise Exception("Valided transaction can't be proceeded") addLog(user, 4, [transactionToString(t)]) # Create a new block in the blockchain c.BC_CHAIN.append([]) # Reward the miner addTransaction(0, user, c.BC_MINER_REWARD) return True def addUser(username: str, autoGenerateKeys: bool = True, keys: list = []): """ Create an user with the corresponding username to the users list and return the corresponding user id which can be used as index username: name of the user autoGenerateKeys: generate elGammal keys for the user keys: base64 of tuple (public key, private key) if keys are not generated for the user """ from ressources.interactions import getIntKey if autoGenerateKeys: # generate keys algModule = __import__("core.asymmetric." + c.BC_SIGNING_ALG, fromlist=[""]) publicKey, privateKey = algModule.key_gen(c.BC_KEY_SIZE) else: # decode base64 tuple of key publicKey = getIntKey(keys[0], [2, 3][c.BC_SIGNING_ALG == "elGamal"]) privateKey = getIntKey(keys[1], [2, 3][c.BC_SIGNING_ALG == "elGamal"]) userID = len(c.BC_USERS) c.BC_USERS.append([userID, username, publicKey, privateKey]) return userID def addTransaction(sender: int, receiver: int, amount: int): """ Add the transaction to the last block of the block-chain Transaction format {sender ID -> receiver ID:: amount} -> signed by sender sender: user id of the sender receiver: user id of the receiver amount: amount send """ curBlock = c.BC_CHAIN[-1] transaction = [sender, receiver, amount] # sign the transaction using user defined transaction alogorithm algModule = __import__("core.asymmetric." + c.BC_SIGNING_ALG, fromlist=[""]) signature = algModule.signing(arrayToBytes(transaction), getUserKey(sender, 1)) transaction.append(signature) curBlock.append(transaction) addLog(0, 10, [len(c.BC_CHAIN) - 1, transactionToString(transaction)]) def getUserKey(user: int, key: int): """ Get the corresponding key of the user reprensented by its user id user: user id key: key type: 0 -> public key, 1 -> private key """ return c.BC_USERS[user][2 + key] def validTransaction(user: int, transaction: list, UTXO: list = None): """ Verify the given transaction user: user if of the user who perform the check transaction: array containing transaction information of the format {sender ID -> receiver ID:: amount} -> signed by sender UTXO: array of UTXO to use instead of default one: c.BC_UTXO """ if UTXO is None: UTXO = c.BC_UTXO core = transaction[:-1] signature = transaction[-1] sender = core[0] # First verify the transaction signature algModule = __import__("core.asymmetric." + c.BC_SIGNING_ALG, fromlist=[""]) if algModule.verifying(arrayToBytes(core), signature, getUserKey(sender, 0)): # Then perform the transaction, return true if the transaction can be performed if transitUTXO(sender, core[1], core[2], UTXO): return True addLog(user, 2, [transactionToString(transaction, UTXO)]) return False addLog(user, 3, [transactionToString(transaction, UTXO)]) return False def getUserBalance(user: int, UTXO: list = None): """ Get the balance of an user by counting all of his UTXO user: user ID of the user whose balance you want to get UTXO: array of UTXO to use instead of default one: c.BC_UTXO """ if UTXO is None: UTXO = c.BC_UTXO return sum([x[1] for x in getUserUTXO(user, UTXO)]) def getUserUTXO(user: int, UTXO: list = None): """ Get a list containing the amount of each UTXO for a given user user: user ID of the user whose UTXO you want to get UTXO: array of UTXO to use instead of default one: c.BC_UTXO """ if UTXO is None: UTXO = c.BC_UTXO amounts = [] for i, u in enumerate(UTXO): if u[0] == user: amounts.append([i, u[1]]) return amounts def transitUTXO(sender: int, receiver: int, amount: int, UTXO: list = None): """ Manage the transaction with UTXO sender: user id of the sender (0 if network) receiver: user id of the receiver amount: amount send UTXO: array of UTXO to use instead of default one: c.BC_UTXO """ if UTXO is None: UTXO = c.BC_UTXO # If the sender is the network, add the amount in one UTXO without check if not sender: UTXO.append([receiver, amount]) return True if not receiver: raise ValueError("Network can't be the destination of any transaction") # User UTXO senderUTXO = getUserUTXO(sender, UTXO) # User UTXO value senderUTXOam = [x[1] for x in senderUTXO] # Check if the user have enough money if sum(senderUTXOam) < amount: return False senderUTXOam.sort(reverse=True) # improved possible -> find the best combinaison of UTXO to reach the amount Ui = [] Uo = 0 # Find a combinaison of UTXO to reach the amount if amount in senderUTXOam: Ui.append(amount) else: for Uam in senderUTXOam: if sum(Ui) < amount: if sum(Ui) + Uam > amount: Uo = (sum(Ui) + Uam) - amount Ui.append(Uam) # Send one or more full UTXO senderUTXOam = [x[1] for x in senderUTXO] for i, Uam in enumerate(Ui): UTXOindex = senderUTXO[senderUTXOam.index(Uam)][0] if i == len(Ui) - 1: Uam = Uam - Uo UTXO[UTXOindex] = [receiver, Uam] # Receive the change if Uo: UTXO.append([sender, Uo]) return True def getAdaptativePOWnb(blockSize: int, firstBlock: bool = False): """ Returns an adaptive number of null bits required for POW validation Computed to get regressing POW execution time's depending of the size of a block blockSize: size of the block firstBlock: first block is not growing due to new transactions, it needs to have a fixed POW null bits size, this can be configured using c.BC_POW_FIRST """ import math if firstBlock: return c.BC_POW_FIRST # Number of null bits = 100 > (14131*x^-1.024) * c.BC_POW_RATIO > 1 return round(min(max(14131 * math.pow(blockSize, -1.024), 1) * c.BC_POW_RATIO, 100)) def addLog(user: int, logID: int, params: list = []): """ Add a log to the list user: user id of the emitter logID: id of the log, see displayLogs() to have the log id association params: list of param associated with the log """ c.BC_LOGS.append([time.time() - c.BC_TIME_START, user, logID, params]) def transactionToString(transaction: list, UTXO: list = None): """ Return a string from a transaction tansaction: array of the transaction UTXO: array of UTXO to use instead of default one: c.BC_UTXO, use to get balance of the users """ if UTXO is None: UTXO = c.BC_UTXO from ressources.interactions import getB64Keys sender = c.BC_USERS[transaction[0]] receiver = c.BC_USERS[transaction[1]] senderBalance = getUserBalance(sender[0], UTXO) receiverBalance = getUserBalance(receiver[0], UTXO) return f"{'{'}{sender[0]}.{sender[1]} ({senderBalance} $) -> {receiver[0]}.{receiver[1]} ({receiverBalance} $):: {transaction[2]} ${'}'} -> {getB64Keys(transaction[3])}" def displayLogs(last: int = 0): """ Display logs contained in c.BC_LOGS last: log id, display every logs after the id of the last one """ if not c.BC_LOGS: return 0 if not last: print("--------------- LOGS ---------------") i = 0 for i, log in enumerate(c.BC_LOGS): if i > last or not last: time = log[0] user = c.BC_USERS[log[1]] logID = log[2] params = log[3] header = f"{i}\t{'{:.2f}'.format(time)}\t{user[1]} ({user[0]})" core = "" if logID == 0: core = f"Start to validate block: {params[0]}" elif logID == 1: core = f"{bcolors.RED}Invalid transaction ignored: {params[0]}{bcolors.ENDC}" elif logID == 2: core = f"{bcolors.RED}Not enough money for transaction: {params[0]}{bcolors.ENDC}" elif logID == 3: core = f"{bcolors.RED}Wrong signature for transaction: {params[0]}{bcolors.ENDC}" elif logID == 4: core = f"{bcolors.OKGREEN}Transaction performed: {params[0]}{bcolors.ENDC}" elif logID == 5: core = f"Calculating POW({params[1]}-{params[2]}) for block: {params[0]}" elif logID == 6: core = f"{bcolors.OKGREEN}Found POW for block {params[0]}: {base64.b64encode(params[1]).decode()}{bcolors.ENDC}" elif logID == 7: core = f"{bcolors.OKGREEN}Block {params[0]} validated{bcolors.ENDC}" elif logID == 8: core = f"{bcolors.YELLOW}Block {params[0]} has already been validated{bcolors.ENDC}" elif logID == 9: core = f"{bcolors.YELLOW}Block {params[0]} changed before POW calculation{bcolors.ENDC}" elif logID == 10: core = f"{bcolors.OKCYAN}Transaction added to block {params[0]}: {params[1]}{bcolors.ENDC}" else: core = "Log ID unknown" if len(header) <= 25: header += "\t" print(f"{header}\t{core}") return i def displayBC(): """ Display the content of the blockchain """ print(f"{bcolors.BOLD}==================== BLOCK-CHAIN ({len(c.BC_CHAIN)} blocks) ===================={bcolors.ENDC}") print() print(f"{bcolors.BOLD}USERS:{bcolors.ENDC}") for i, u in enumerate(c.BC_USERS): print(f"\t{u[1]}({u[0]}): {getUserBalance(u[0])} $") print() print() for i, b in enumerate(c.BC_CHAIN): print(f"{bcolors.BOLD}BLOCK {i} - HASH: {base64.b64encode(getBlockHash(b)).decode()}{bcolors.ENDC}") print() complete = False print(f"\t{bcolors.OKCYAN}Transactions:{bcolors.ENDC}") for i, t in enumerate(b): if isinstance(t, list): print(f"\t\t{i}: {transactionToString(t)}") else: complete = True print() if complete: print(f"\t{bcolors.OKGREEN}Block has been validated:{bcolors.ENDC}") print(f"\t\tPrevious block hash: {base64.b64encode(b[-2]).decode()}") print(f"\t\tBlock salt: {base64.b64encode(b[-1]).decode()}") print() else: print(f"\t{bcolors.YELLOW}Block has not been validated yet{bcolors.ENDC}") print() print() def arrayToBytes(array: list): """ Convert an array to bytes, return base64 of array data array: data to convert """ byts = b"" for x in array: if not isinstance(x, (bytes, bytearray)): byts += str(x).encode() else: byts += x return base64.b64encode(byts) def getBlockHash(block, ignoreSalt: bool = True): """ Get an hash of the block block: block to hash -> format [transaction #0, transaction #1, transaction #2, ..., hash of block n-1, salt] ignoreSalt: if false, does not convert the the salt (last array index) to base64, used for POW verification """ from core.hashbased.hashFunctions import sponge if isinstance(block, int): block = c.BC_CHAIN[block] toHash = bytearray() if ignoreSalt: toHash = arrayToBytes(block) else: toHash = arrayToBytes(block[:-1]) + block[-1] return sponge(toHash, c.BC_HASH_SIZE)
Swift
UTF-8
558
3.046875
3
[]
no_license
// // testClassException .swift // swift_demo_T1000 // // Created by Rayan Taj on 20/10/2021. // import Foundation // // //print("Please enter a password : " , terminator: "\t") // //let password = Utils.readString() // //do{ // try checkPassword(password: password) //} catch is CapitalfirstLetter { // print("the first Letter Must be a capital letter") //}catch is NumberOfCharacters{ // print("Password length must be more than 8 characters") // //}catch is FirstLetterIsNotNumber { // print("first character should not be a number ") // //}
Markdown
UTF-8
1,687
2.53125
3
[]
no_license
--- course_id: 9-16-cellular-neurophysiology-spring-2002 layout: course_section menu: leftnav: identifier: 1ee23f802cb46686326694c8dfe9be1d name: Syllabus weight: 10 title: Syllabus type: course uid: 1ee23f802cb46686326694c8dfe9be1d --- Course Meeting Times -------------------- Lectures: 1 session / week, 1.5 hours / session Recitations: 1 session / week, 1.5 hours / session Course 9.16 (Undergraduate) and Couse 9.161 (Graduate) meet together. An additional project is required for graduate credit. Prerequisites ------------- * 9.01 for undergraduate students. * 9.011 for graduate students. Schedule -------- * Lecture 1.5 hr. and Recitation 1.5 hr. **Course Highlights** * Surveys the molecular and cellular mechanisms of neuronal communication. * Covers ion channels in excitable membrane, synaptic transmission, and synaptic plasticity. * Correlates the properties of ion channels and synaptic transmission with their physiological function such as learning and memory. * Discusses the organization principles for the formation of functional neural networks at synapse and cellular levels. Course Requirements ------------------- * 3 Problem sets * Lab Project * Class will be split into three groups; sign-up sheet will be provided in ses #8. * Class participation * Attendance * Participation and presentation in class * Graduate students only: final project * Final exam Books ----- * Johnston, and Wu. _Foundations of Cellular Neurophysiology_. MIT Press. * Hille. _Ionic Channels of Excitable Membranes_, 3rd Edition. Sinauer Associates, Inc. * Levitan, and Kaczmarek. _The Neuron_. Oxford University Press.
C#
UTF-8
1,332
3.1875
3
[]
no_license
public void BuildPerson() { var list = new People { PersonList = new List<List<Person>> { new List<Person> { new Person { Name = "test", Age = 21 } }, new List<Person> { new Person { Name = "test2", Age = 22 } }, new List<Person> { new Person { Name = "test3", Age = 23 } } } }; string output = JsonConvert.SerializeObject(list); var objList = JsonConvert.DeserializeObject<People>(output); var ListObjs = objList.PersonList; foreach(var obj in ListObjs) { var objj = obj.ToArray(); foreach(var person in objj) { string name = person.Name; int age = person.Age; } } }
C
UTF-8
3,278
3.453125
3
[]
no_license
/****************************************************************************** * File: main.c * Version: 1.2 * Date: 2017-10-18 * Author: J. Onokiewicz, M. van der Sluys * Description: OPS exercise 5: Queues ******************************************************************************/ #include "Queue.h" #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> #include <signal.h> void sigintHandler(int sig); void *producer(void *arguments); void *consumer(void *arguments); struct thread_args { queue_t *queue; data_t data; int interval; }; pthread_mutex_t lock; int endProgram = 0; int main() { signal(SIGINT, sigintHandler); pthread_t producerA, producerB, producerC, consumerA; queue_t queue = {NULL}; // Note: element of queue = NULL struct thread_args argsP_A = {NULL}, argsP_B = {NULL}, argsP_C = {NULL}, argsC_A = {NULL}; data_t baseData = {0, "new queue"}; data_t dataP_A = {1, "producer A"}; data_t dataP_B = {2, "producer B"}; data_t dataP_C = {3, "producer C"}; printf("setting arguments\n"); argsP_A.queue = &queue; argsP_B.queue = &queue; argsP_C.queue = &queue; argsC_A.queue = &queue; argsP_A.data = dataP_A; argsP_B.data = dataP_B; argsP_C.data = dataP_C; argsP_A.interval = 2; argsP_B.interval = 3; argsP_C.interval = 4; argsC_A.interval = 15; printf("initializing mutex\n"); pthread_mutex_init(&lock, NULL); printf("creating queue\n"); createQueue(&queue, baseData); printf("creating threads\n"); pthread_create(&producerA, NULL, producer, (void *) &argsP_A); pthread_create(&producerB, NULL, producer, (void *) &argsP_B); pthread_create(&producerC, NULL, producer, (void *) &argsP_C); pthread_create(&consumerA, NULL, consumer, (void *) &argsC_A); printf("threads created\n"); pthread_join(producerA, NULL); pthread_join(producerB, NULL); pthread_join(producerC, NULL); pthread_join(consumerA, NULL); pthread_mutex_destroy(&lock); printf("threads joined and mutex destroyed\n"); deleteQueue(&queue); printf("queue deleted\n"); return 0; } void *producer(void *arguments) { struct thread_args *args = (struct thread_args*)arguments; printf("new producer %d\n", args->data.intVal); while(!endProgram) { pthread_mutex_lock(&lock); printf("producer %d pushing\n", args->data.intVal); pushQueue(&args->queue, args->data); pthread_mutex_unlock(&lock); sleep(args->interval); } return; } void *consumer(void *arguments) { printf("new consumer\n"); struct thread_args *args = (struct thread_args*)arguments; printf("open file\n"); FILE *fp; fp = fopen ("queueFile.txt", "a"); if(fp = NULL) { printf("file failed to open\n"); exit(1); } while(!endProgram) { pthread_mutex_lock(&lock); printf("now consuming\n"); printf("write queue to file\n"); //writeQueueToFile(&args->queue, fp); printf("print queue\n"); //showQueue(&args->queue); printf("empty queue\n"); emptyQueue(&args->queue); pthread_mutex_unlock(&lock); sleep(args->interval); } printf("close file\n"); //fclose(fp); return; } void sigintHandler(int sig) { endProgram = 1; return; }
Python
UTF-8
935
2.921875
3
[]
no_license
import pygame from entities.entity import Entity class Platform(Entity): # if you want moving platforms, specify here minimum and maximum x and y values def __init__(self,x,y,dx,dy,width,height,world,passthrough=True,dropdown=True, min_x = 0, max_x = 700,image_file=None): super().__init__(x,y,dx,dy,width,height,world,color=(102,51,0),image_file=image_file) self.type = 'platform' self.passthrough = passthrough self.dropdown = dropdown self.min_x = min_x self.max_x = max_x def update(self): self.rect.x += self.dx if self.rect.x < self.min_x: self.dx *= -1 self.rect.x = self.min_x + 1 if self.rect.x + self.rect.width > self.max_x: self.dx *= -1 self.rect.x %= self.world.width self.rect.y += self.dy if self.rect.y > self.world.height: self.rect.y%= self.world.height
Markdown
UTF-8
577
2.71875
3
[ "MIT" ]
permissive
--- layout: post title: "How To Make A New Page" date: 2018-09-24 16:34:48 +0000 categories: jekyll gettingstarted --- # This is my new content about how to make a new page! 1. In the pages folder on your desktop, create a new file or copy an existing one to alter to your needs. Make sure this file ends with a ".md". This tells git that it is a markdown file. 1. Once you have saved, committed, pushed, and checked your page to be to your satisfaction, you're ready to make a link. 1. Copy your page's url and create a link to it on the homepage for easy access.
Python
UTF-8
7,487
2.96875
3
[]
no_license
__authour__ = 'Harry Burge' __date_created__ = '20/06/2020' __last_updated_by__ = 'Harry Burge' __last_updated_date__ = '20/06/2020' # Imports from bin.AI.ai_class import AI from random import randint from bin.Utils.game_util import normalise from bin.Game.Pieces.StarTrekChess.pawn_s import Pawn import copy ''' Simulate every move the AI could make - Make sure to be threaded Check a few of the values calculated with diffrent weighting to make like an A* search algorithm Will need to covert values from AI to be able to be smaller the better for the heuristic to work on a* This is due to it be shortest path some times on visualliser a peice doesn't change ''' class Bot(AI): def __init__(self): super().__init__() def suggest_move(self, board, team): view = [] # Heuristic value, moves to get to the state, depth for heuristic, move in self.calculate_best_moves(board, team, 4): view.append((heuristic, [move], 0)) yn = True while yn: print('Thinking') # Finds the moveset we will be investigating min_index = self.minimumn_heurstic_index(view) cur_min_heuristic, cur_min_moves, cur_min_depth = view[min_index] if cur_min_depth >= 1: yn = False else: # Gets board to current state of the move set found simulated_board = copy.deepcopy(board) for coords1, coords2 in cur_min_moves: simulated_board.move_piece(*coords1, *coords2) # Need to delete old thing from the view del view[min_index] # Go through the calcualted thing and put into view carrying on the data from prevoius generation for heuristic, move in self.calculate_best_moves(simulated_board, team, 4): view.append((cur_min_heuristic+heuristic, cur_min_moves+[move], cur_min_depth+1)) # Finds the moveset we will be investigating min_index = self.minimumn_heurstic_index(view) cur_min_heuristic, cur_min_moves, cur_min_depth = view[min_index] return cur_min_moves[0][0], cur_min_moves[0][1] def minimumn_heurstic_index(self, view): minh = 100000 mini = None for index, i in enumerate(view): if i[0] < minh: mini = index minh = i[0] return mini def calculate_best_moves(self, board, team, width): top_heuristics = [10]*width corresponding_moves = [((0,0,0), (0,0,0))]*width # Loop through all possible moves of all teams pieces for coord1, piece1 in board.get_pieces_search(True, team): for move in piece1.valid_move_coords(board, *coord1): if move['mv_type'] in ['Take', 'Move']: heuristic = self.heuristic_value_board_state(self.simulate_piece_move(board, *coord1, *move['coords']), team) if max(top_heuristics) > heuristic: index = top_heuristics.index(max(top_heuristics)) top_heuristics[index] = heuristic corresponding_moves[index] = (coord1, move['coords']) return [(top_heuristics[i], corresponding_moves[i]) for i in range(len(top_heuristics))] def heuristic_value_board_state(self, board, team): num_unsafe_peices = len(self.get_unsafe_pieces_on_team(board, team)) num_safe_pieces = len(self.get_safe_pieces_on_team(board, team)) num_same_row_pawns = self.count_pawns_same_column_on_team(board, team, Pawn) num_of_possible_attacks = 0 for coords, piece in board.get_pieces_search(True, team): num_of_possible_attacks += len(self.get_on_piece_attacking_pieces(board, *coords, piece)) #TODO: Create some for defending and people attacking pieces num_of_pieces_on_team = len(board.get_pieces_search(True, team)) num_of_pieces_off_team = len(board.get_pieces_search(False, team)) num_of_pawns_on_team = len(board.get_pieces_search(True, team, Pawn)) inv_num_unsafe_peices = num_of_pieces_on_team - num_unsafe_peices inv_num_same_row_pawns = num_of_pawns_on_team - num_same_row_pawns inv_num_of_possible_attacks = num_of_pieces_off_team - num_of_possible_attacks nor_inv_num_unsafe_peices = normalise(inv_num_unsafe_peices, num_of_pieces_on_team, 0) nor_num_safe_pieces = normalise(num_safe_pieces, num_of_pieces_on_team, 0) nor_inv_num_same_row_pawns = normalise(inv_num_same_row_pawns, num_of_pawns_on_team, 0) nor_inv_num_of_possible_attacks = normalise(inv_num_of_possible_attacks, num_of_pieces_off_team, 0) vals = [nor_inv_num_unsafe_peices, nor_num_safe_pieces, nor_inv_num_same_row_pawns, nor_inv_num_of_possible_attacks] weights = [1,1,1,1] sum_valxweight = 0 for i in range(len(vals)): sum_valxweight += vals[i]*weights[i] return sum_valxweight def get_unsafe_pieces_on_team(self, board, team): unsafe_pieces = [] for coords1, piece1 in board.get_pieces_search(True, team): unsafe = False for coords2, piece2 in board.get_pieces_search(False, team): if {'coords':coords1, 'mv_type':'Take'} in piece2.valid_move_coords(board, *coords2): unsafe = True if unsafe: unsafe_pieces.append((coords1, piece1)) return unsafe_pieces def get_safe_pieces_on_team(self, board, team): unsafe_pieces = self.get_unsafe_pieces_on_team(board, team) team_pieces = board.get_pieces_search(True, team) safe_pieces = [piece for piece in team_pieces if piece not in unsafe_pieces] return safe_pieces def count_pawns_same_column_on_team(self, board, team, pawn_class): count = 0 pawns = board.get_pieces_search(True, team, pawn_class) for coords1, peice1 in pawns: found = False for coords2, peice2 in pawns: if coords2 != coords1 and coords1[0] == coords2[0]: found = True if found: count += 1 return count def get_attacking_pieces_on_piece(self, board, x,y,z, on_piece): attacking_pieces = [] # All other team pieces team_pieces = board.get_pieces_search(True, on_piece.team) all_pieces = board.get_all_pieces() other_teams_pieces = [i for i in all_pieces if i not in team_pieces] for coords, piece in other_teams_pieces: valid_moves = piece.valid_move_coords(board, *coords) if {'coords':(x,y,z), 'mv_type':'Take'} in valid_moves: attacking_pieces.append((coords, piece)) return attacking_pieces def get_on_piece_attacking_pieces(self, board, x,y,z, on_piece): potential_attacks = [] valid_moves = on_piece.valid_move_coords(board, x,y,z) for move in valid_moves: if move['mv_type'] == 'Take': potential_attacks.append((move['coords'], board.get_gridpoi(*move['coords']))) return potential_attacks def simulate_piece_move(self, board, x1,y1,z1, x2,y2,z2): simulated_board = copy.deepcopy(board) if simulated_board.move_piece(x1,y1,z1, x2,y2,z2) == False: return False return simulated_board
TypeScript
UTF-8
414
3.171875
3
[ "MIT" ]
permissive
/** * Checks if a email is a valid formatted email. */ export function isValidEmail(email: string) { if(typeof email !== 'string') { throw new TypeError('Email must be typeof string.'); } // eslint-disable-next-line max-len return (/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/).test(email); }
C
UTF-8
179
3.234375
3
[]
no_license
#include "holberton.h" /** * _abs - finds the absolute value * @a: number thats type int * Return: a */ int _abs(int a) { if (a < 0) return (a * -1); else return (a); }
PHP
UTF-8
151
2.671875
3
[]
no_license
<?php namespace Package\Model; class User { public function __construct(){ } public function Display(){ echo "Frolov"; } }
PHP
UTF-8
4,182
2.703125
3
[ "MIT" ]
permissive
<?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Security\Core\User\UserInterface; /** * @ORM\Entity(repositoryClass="App\Repository\UserRepository") * @ORM\Table(name="sgl_users") */ class User implements UserInterface { /** * @ORM\Id() * @ORM\GeneratedValue() * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=100) */ private $firstName; /** * @ORM\Column(type="string", length=140) */ private $lastName; /** * @ORM\Column(type="string", length=254) */ private $email; /** * @ORM\Column(type="string", length=64) */ private $password; /** * @ORM\Column(type="boolean") */ private $isActive; /** * @ORM\Column(type="array") */ private $roles = []; /** * @ORM\ManyToOne(targetEntity="App\Entity\Center", inversedBy="users") */ private $center; private $imageProfile; /** * User constructor */ public function __construct() { $this->isActive = true; $this->roles = array('ROLE_STAFF'); } // End properties declarations // Begin getters and setters public function getId(): ?int { return $this->id; } public function getFirstName(): ?string { return $this->firstName; } public function setFirstName(string $firstName): self { $this->firstName = $firstName; return $this; } public function getLastName(): ?string { return $this->lastName; } public function setLastName(string $lastName): self { $this->lastName = $lastName; return $this; } public function getEmail(): ?string { return $this->email; } public function setEmail(string $email): self { $this->email = $email; return $this; } public function getPassword(): ?string { return $this->password; } public function setPassword(string $password): self { $this->password = $password; return $this; } // We can use this instead to encode the password the in entity's setter: // //public function setPassword($password) { // if ($password) // $this->password = password_hash($password, PASSWORD_DEFAULT); // OR $this->password = password_hash($password, PASSWORD_BCRYPT); // // return $this; //} public function getIsActive(): ?bool { return $this->isActive; } public function setIsActive(bool $isActive): self { $this->isActive = $isActive; return $this; } public function getRoles(): ?array { return $this->roles; } public function setRoles(array $roles): self { $this->roles = $roles; return $this; } public function getCenter(): ?Center { return $this->center; } public function setCenter(?Center $center): self { $this->center = $center; return $this; } /** * Returns the salt that was originally used to encode the password. * This can return null if the password was not encoded using a salt. * @return string|null The salt */ public function getSalt() { return null; } /** * Returns the username used to authenticate the user. * @return string The username */ public function getUsername() { return $this->email; } /** * Removes sensitive data from the user. * * This is important if, at any given point, sensitive information like * the plain-text password is stored on this object. */ public function eraseCredentials() { // TODO: Implement eraseCredentials() method. } /** * @return mixed */ public function getImageProfile() { return $this->imageProfile; } /** * @param mixed $imageProfile */ public function setImageProfile($imageProfile): void { $this->imageProfile = $imageProfile; } }
Ruby
UTF-8
842
3.546875
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require "pry" class Song attr_accessor :name ,:artist ,:genre @@count = 0 @@artists = [] @@genres = [] def initialize(name, artist, genre) @name = name @artist = artist @genre = genre @@count +=1 @@artists<<artist @@genres<<genre end def self.count @@count end def self.artists @@artists.uniq end def self.genres @@genres.uniq end def self.genre_count hash={} counter = 0 @@genres.each do |genre| hash[genre] ||= 0 counter = @@genres.select{|word| word==genre}.size hash[genre] = counter end hash end def self.artist_count hash = {} counter = 0 @@artists.each do |value| hash[value] ||= 0 counter = @@artists.select {|w| w == value}.size hash[value] = counter end hash end end
Python
UTF-8
1,175
2.6875
3
[]
no_license
import sys, fileinput source = fileinput.input() src = source.readline().strip() num = source.readline().strip() links = {} backpointers = {} backpointers[src]=(-1,0) for line in source: if '->' not in line: break (link, weight) = line.strip().split(':') weight = int(weight) (start, end) = link.split('->') print start, end, weight if start not in links: links[start]= {"in":[],"out":[]} if end not in links: links[end] = {"in":[],"out":[]} links[start]["out"].append((end,weight)) links[end]["in"].append((start, weight)) print src, num print links queue = [src] last = 0 maxpath = 0 while len(queue)>0: next = queue[-1] queue = queue[:-1] if backpointers[next][1]>maxpath: last = next maxpath = backpointers[next][1] thelinks = links[next]["out"] for (l,w) in thelinks: dist = w+backpointers[next][1] if l not in backpointers or backpointers[l][1]<dist: backpointers[l]=(next,dist) queue.append(l) print last, maxpath last = num print backpointers[last] backtrack = [last] while last!=src: last = backpointers[last][0] backtrack.append(last) backtrack.reverse() print backtrack print "->".join([str(l) for l in backtrack])
Markdown
UTF-8
2,477
2.9375
3
[]
no_license
# 创建数据集 在`K-Lab页面`下的`我的数据集`中点击蓝色`+`或直接点击`创建数据集`来进行数据集的创建。 ![image description](/image/dataset-create.png) 该功能分为两个步骤,数据集制作与数据集信息完善。 ### 数据集制作 * **上传数据集图片**:上传一个能够代表数据集内容的封面图片。 * **填写数据集名称**:对将要创建的数据集进行命名。 * **设置挂载目录**:挂载目录是可以在K-Lab Notebook中访问到数据集的地址,挂载目录的设置支持字母、数字及下划线,**在创建后不可修改**。以上传名为vgsalesGlobale.csv的数据文件为例,若设置挂载目录为 `first_dataset`,则在运行挂载了该数据集的K-Lab项目时,可以在 `/home/kesci/input/first_dataset/`目录下访问到该数据集。 * **填写数据集短描述**:简单介绍一下数据集内容。 * **数据集访问权限**:组织管理员创建数据集时可以为数据集设置访问权限。详情参见[数据集权限](/ch4/authority_dataset.md) * **添加文件**:K-Lab支持用户在一个数据集目录下面上传不超过**20个文件**,文件总大小不超过**500M**,上传文件格式不限。但推荐用户上传**csv格式文件**。K-lab支持csv格式文件内容的预览。若文件数目较多,建议压缩成zip文档后上传,K-Lab将自动解压一级目录下的zip文件。 点击创建即可完成数据集的制作。 ![image description](/image/组织版-创建数据集管理员.png) ### 数据集信息完善 创建好数据集后,创建者可以在K-Lab的数据集详情页面对**数据集文档**和**数据文件**进行编辑和完善,方便在进行协作时他人能够理解该数据的背景信息。 * **数据集文档**:数据集文档是对数据集背景信息及包含内容的概述。在数据集文档页面,点击右上角的编辑按钮,可以进入编辑状态,参考我们提供的模板,对数据集文档进行完善。 ![image description](/image/数据集文档.png) * **文件信息**:在文件信息页面,用户可以预览**csv文件**的前20行数据,点击编辑按钮后可以修改数据集标注,同时对每个文件编写简介。对于zip格式的文件,用户可以预览压缩包内的文件数量,名称及大小。 ![image description](/image/dataset-file-info.png) ![image description](/image/dataset-zip-file.png)
Shell
UTF-8
6,985
3.734375
4
[ "Apache-1.1" ]
permissive
#!/bin/bash project="fpm-refinery" version="0.1.0-1" projectdir="/vagrant/fpm-refinery" prefix="/opt/$project" box="$1" packagedir="$projectdir/pkg/$box" # # Prints a log message. # log() { if [[ -t 1 ]]; then echo -e "\x1b[1m\x1b[32m>>>\x1b[0m \x1b[1m$1\x1b[0m" else echo ">>> $1" fi } # # Prints a warn message. # warn() { if [[ -t 1 ]]; then echo -e "\x1b[1m\x1b[33m***\x1b[0m \x1b[1m$1\x1b[0m" >&2 else echo "*** $1" >&2 fi } # # Prints an error message. # error() { if [[ -t 1 ]]; then echo -e "\x1b[1m\x1b[31m!!!\x1b[0m \x1b[1m$1\x1b[0m" >&2 else echo "!!! $1" >&2 fi } # # Prints an error message and exists with -1. # fail() { error "$*" exit -1 } build() { local cache="$projectdir/cache" local builddir="/tmp/$project-builddir" case "$box" in fedora*|centos*|redhat*) yum -y install gcc gcc-c++ make rpm-build || return $? ;; debian*|ubuntu*) apt-get -y install build-essential || return $? ;; esac mkdir -p "$builddir" || { error "Could not create $builddir"; return $?; } build_ruby_install "0.5.0" \ "https://github.com/postmodern/ruby-install/archive/v0.5.0.tar.gz" \ "aa4448c2c356510cc7c2505961961a17bd3f3435842831e04c8516eb703afd19" \ || { error "Could not build ruby-install."; return 1; } build_libyaml "0.1.6" \ "http://pyyaml.org/download/libyaml/yaml-0.1.6.tar.gz" \ "7da6971b4bd08a986dd2a61353bc422362bd0edcc67d7ebaac68c95f74182749" \ || { error "Could not build libyaml."; return 1; } install_ruby "2.1.5" \ "http://cache.ruby-lang.org/pub/ruby" \ "0241b40f1c731cb177994a50b854fb7f18d4ad04dcefc18acc60af73046fb0a9" \ || { error "Could not build ruby."; return 1; } install_gem "fpm-cookery" "0.25.0" \ || { error "Could not install gem."; return 1; } } package() { if [[ -s "$projectdir/bootstrap.rb" ]]; then mkdir -p "$packagedir" "$prefix/embedded/bin/fpm-cook" package \ --pkg-dir "$packagedir" --tmp-root "/tmp/$project-builddir" \ "$projectdir/bootstrap.rb" || return $? else error "Missing $projectdir/bootstrap.rb" return 1 fi } build_ruby_install() { local version="$1" local url="$2" local checksum="$3" local filename="ruby-install-${version}.tar.gz" if [[ ! -s /usr/local/bin/ruby-install ]]; then download_and_verify || { error "Error downloading $url"; return 1; } cd "$builddir" tar -xvzf "$filename" || return $? cd "${filename%.tar.gz}" $sudo make install || return $? else log "$(/usr/local/bin/ruby-install --version) already present, skipping build." fi } build_libyaml() { local version="$1" local url="$2" local checksum="$3" local filename="yaml-${version}.tar.gz" if [[ ! -s "$prefix" ]]; then download_and_verify || return $? cd "$builddir" tar -xvzf "$filename" || return $? cd "${filename%.tar.gz}" ./configure --prefix="$prefix/embedded" || return $? make || return $? $sudo make install || return $? else log "libyaml already present, skipping build." fi } install_ruby() { local version="$1" local url="$2" local checksum="$3" local filename="ruby-${version}.tar.bz2" local no_dl= export PATH="$PATH:/usr/local/bin" if [[ ! -s "$prefix/embedded/bin/ruby" ]]; then if [[ -s "$cache/$filename" ]]; then cp -n "$cache/$filename" "$builddir" no_dl="--no-download" fi $sudo ruby-install -i "$prefix/embedded" -j2 -M "$url" -s "$builddir" "$no_dl" \ --sha256 "$checksum" \ ruby "$version" -- --disable-install-doc --enable-shared || return $? # Shrink! $sudo rm -f "$prefix/embedded/lib/libruby-static.a" find "$prefix/embedded" -name '*.so' -o -name '*.so.*' | $sudo xargs strip cp -n "$builddir/$filename" "$cache" || return $? else log "$("$prefix/embedded/bin/ruby" -v) already present, skipping build." fi } install_gem() { local gem="$1" local version="$2" local gembin="$prefix/embedded/bin/gem" local gemdir="$($sudo "$gembin" environment gemdir)" || return $? local gemcache="$cache/gems/${gemdir##*/}" if [[ ! -d "${gemdir}/gems/${gem}-${version}" ]]; then if [[ -s "${gemcache}/${gem}-${version}.gem" ]]; then # Install from cache log "Cached gem present. Installing $gem $version from cache." cd "$gemcache" $sudo "$gembin" install --no-document --local "${gem}-${version}.gem" || return $? else $sudo "$gembin" install --no-document "$gem" -v "$version" || return $? # cache gems - copy without overwriting existing files mkdir -p "$gemcache" || return $? cp -n "$gemdir/cache/"*.gem "$gemcache" || return $? fi else log "$gem $version already present, skipping build." fi } download_and_verify() { if [[ ! -s "$cache/$filename" ]]; then mkdir -p "$cache" || return $? download "$url" "$cache/$filename" || return $? fi if [[ ! -s "$cache/$filename" ]]; then error "Missing $cache/$filename, can't continue." return 1 fi verify "$cache/$filename" "$checksum" \ || { error "File checksum verification failed."; return $?; } cp -n "$cache/$filename" "$builddir" || return $? } # # Downloads a URL. # download() { local url="$1" local dest="$2" [[ -d "$dest" ]] && dest="$dest/${url##*/}" [[ -f "$dest" ]] && return # Auto-detect the downloader. if exists "curl"; then downloader="curl" elif exists "wget"; then downloader="wget" fi case "$downloader" in wget) wget --no-verbose -c -O "$dest.part" "$url" || return $? ;; curl) curl -s -f -L -C - -o "$dest.part" "$url" || return $? ;; "") error "Could not find wget or curl" return 1 ;; esac mv "$dest.part" "$dest" || return $? } # # Verify a file using a SHA256 checksum # verify() { local path="$1" local checksum="$2" # Auto-detect checksum verification util if exists "sha256sum"; then verifier="sha256sum" elif exists "shasum"; then verifier="shasum -a 256" fi if [[ -z "$verifier" ]]; then error "Unable to find the checksum utility." return 1 fi if [[ -z "$checksum" ]]; then error "No checksum given." return 1 fi local match='^'$checksum'\ ' if [[ ! "$($verifier "$path")" =~ $match ]]; then error "$path is invalid!" return 1 else log "File checksum verified OK." fi } # # Check whether a command exists - returns 0 if it does, 1 if it does not # exists() { local cmd="$1" if command -v $cmd >/dev/null 2>&1 then return 0 else return 1 fi } # Main logic # Build only if /opt/$project does not exist if [[ ! -d "/opt/$project" ]]; then build || fail "Building $project $version failed." else log "/opt/$project already exists - skipping build." fi if [[ ! -f "$projectdir/pkg/.$box-$project-$version.cookie" ]]; then package || fail "Packaging $project $version failed." touch "$projectdir/pkg/.$box-$project-$version.cookie" fi
C++
UTF-8
3,595
2.640625
3
[]
no_license
#ifndef _GUI_BUTTON_H #define _GUI_BUTTON_H #include "Label.h" #include "../Geometries/IGeometryQuads.h" #include "../Utils/ButtonAction.h" namespace jogy { enum InputBehaviour { None = 0, ReplaceTex, AddTex, Decal, Scale, Enlight }; // must return false if resulting in a closing event typedef tr1::function<bool (ComponentOwnerInterface*)> ClickCallback; class Button : public Component { public: // Constructor / destructor Button(); virtual ~Button(); // Inherited functions virtual u32 getType() { return GOTYPE_BUTTON; }; virtual void update(double delta); virtual void displayAt(int iXOffset, int iYOffset, Color cpntColor, Color docColor); virtual void moveTo(int xPxl, int yPxl); virtual void moveBy(int xPxl, int yPxl); virtual void setEnabled(bool bEnabled); // Input functions virtual Object * onButtonEvent(ButtonAction * pEvent); virtual Object * onCursorMoveEvent(int xPxl, int yPxl); virtual void onCursorMoveOutEvent(); // Member access functions string getText() { return m_pLabel->getText(); }; void setText(string sText); void setFontId(fontid id) { m_pLabel->setFontId(id); }; void setTextColor(Color textColor) { m_pLabel->setDiffuseColor(textColor); }; InputBehaviour getClickedOption() { return m_ClickedOption; }; InputBehaviour getHoverOption() { return m_HoverOption; }; void setClickedOption(InputBehaviour clickedOption) { m_ClickedOption = clickedOption; }; void setHoverOption(InputBehaviour hoverOption) { m_HoverOption = hoverOption; }; IGeometryQuads * getClickedGeometry() { return m_pGeometryClicked; }; IGeometryQuads * getHoverGeometry() { return m_pGeometryHover; }; IGeometryQuads * getBaseGeometry() { return m_pGeometryBase; }; void setCatchButton2Events(bool bCatch) { m_bCatchButton2Events = bCatch; }; void setCatchDoubleClicks(bool bCatch) { m_bCatchDoubleClicks = bCatch; }; void setMultiClicks(bool bMulti) { m_bMultiClicks = bMulti; }; void setBaseTexture(ITexture * pTex); void setClickCallback(ClickCallback clickCallback) { m_ClickCallback = clickCallback; }; Label * getLabel() { return m_pLabel; }; bool doClick(ButtonAction * pEvent); // Size & position virtual void onResize(int iOldWidth, int iOldHeight); void autoPad(int margin); void autoPadWidth(int margin, int minWidth = 0); // Other void attachImage(ITexture * pTex, IGeometryQuads * pImageGeo); // Builder virtual Button * build(); Button * withInputBehaviour(InputBehaviour clickedBehaviour, InputBehaviour hoverBehaviour) { m_ClickedOption = clickedBehaviour; m_HoverOption = hoverBehaviour; return this; } Button * withLabel(string sText, fontid fontId, Color textColor, IGeometryText * pLabelGeo); Button * withBaseGeometry(ITexture * pTex, IGeometryQuads * pGeo); Button * withClickedGeometry(ITexture * pTex, IGeometryQuads * pGeo); Button * withHoverGeometry(ITexture * pTex, IGeometryQuads * pGeo); protected: bool m_bMouseDown; bool m_bMouseOver; Label * m_pLabel; InputBehaviour m_ClickedOption; InputBehaviour m_HoverOption; IGeometryQuads * m_pGeometryClicked; IGeometryQuads * m_pGeometryHover; IGeometryQuads * m_pGeometryBase; IGeometryQuads * m_pGeometryAttachedImage; bool m_bClickState; bool m_bCatchButton2Events; bool m_bCatchDoubleClicks; bool m_bMultiClicks; float m_fMultiClicksTimer; ButtonAction m_MultiClicksEvent; ClickCallback m_ClickCallback; }; } #endif
Python
UTF-8
723
3.59375
4
[]
no_license
""" 二分 middle 2021-07-13 """ class Solution: def findNumberIn2DArray(self, matrix, target): if not matrix or not matrix[0]:return False n = len(matrix) m = len(matrix[0]) i = 0 j = m-1 while i<n and j>=0: if matrix[i][j]==target:return True elif matrix[i][j]>target:j-=1 else: i+=1 return False if __name__ == '__main__': matrix = [ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ] # target = 5 target = 20 print(Solution().findNumberIn2DArray(matrix, target))
Markdown
UTF-8
925
2.5625
3
[]
no_license
# Notes ## Pipeline **Data Fetching** Raw data is current stored in a network MySQL Server. Data fetching is performed in the file designated 1. **Preprocessing** Data preprocessing is performed in R. The data is reformated and recordeds are coded 1 or 0 to structure the training data. Preprocessing occurs according the file designated 2. **Neural Network Training** The neural network model is built and trained using Python according to the file designated 3. This is done using the Keras package. ## Kares Keras input explanation: input_shape, units, batch_size, dim, etc https://stackoverflow.com/questions/44747343/keras-input-explanation-input-shape-units-batch-size-dim-etc Choosing Optimizer https://www.dlology.com/blog/quick-notes-on-how-to-choose-optimizer-in-keras/ ## Convolutional Neural Network https://machinelearningmastery.com/cnn-models-for-human-activity-recognition-time-series-classification/
Java
UTF-8
1,193
2.015625
2
[ "Apache-2.0" ]
permissive
package org.itstack.naive.chat.interfaces.facade; import org.itstack.naive.chat.application.service.UserService; import org.itstack.naive.chat.interfaces.dto.UserInfoDto; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; /** * 虫洞栈:https://bugstack.cn * 公众号:bugstack虫洞栈 | 欢迎关注并获取更多专题案例源码 * Create by 小傅哥 on @2020 */ @Controller public class DDDController { @Resource(name = "userService") private UserService userService; @RequestMapping("/index") public String index(Model model) { return "index"; } @RequestMapping("/api/user/queryUserInfo") @ResponseBody public ResponseEntity queryUserInfo(@RequestBody UserInfoDto request) { return new ResponseEntity<>(userService.queryUserInfoById(request.getId()), HttpStatus.OK); } }
C++
UTF-8
451
2.53125
3
[]
no_license
#pragma once #include "GameObject.h" class Game; class View : public sf::RectangleShape { public: View(int texture, Game * game); ~View(); void draw(sf::RenderWindow &window); void Update(); void addObject(GameObject * obj); void eventHandler(sf::Vector2i &mousePosition, bool isPressed); Game * _parent; void removeLastObject(); void deleteLastObject(); private: sf::Texture * _background; protected: std::vector<GameObject *> _objects; };
JavaScript
UTF-8
979
3.390625
3
[ "Apache-2.0" ]
permissive
/* The purpose of this API is to provide a random saying such as one that would be found in a fortune cookie. */ function loadSayingsSync(){ if(!process.env.SAYINGS){ const arr= []; require('fs').readFileSync('sayings.txt', 'utf-8').split(/\r?\n/).forEach(function(line){ arr.push({saying:line}); }); console.log("Data initialized at : " + new Date()); process.env.SAYINGS = JSON.stringify(arr); } return JSON.parse(process.env.SAYINGS); } function getRandomSaying(){ const sayings = loadSayingsSync(); const max = sayings.length; const min = 0; const idx = Math.floor(Math.random()*(max-min+1)+min); return sayings[idx]; } exports.handler = async (event) => { const saying = JSON.stringify(getRandomSaying(), null, 4); console.log({saying,date:new Date()}); const response = { statusCode: 200, body: JSON.stringify(saying), }; return response; };
C#
UTF-8
686
2.875
3
[]
no_license
using UnityEngine; [System.Serializable] public class InputProvider { public enum Mode { Manual, AI } public enum Direction { Left, Rigth, None } AI ai = new AI(); public Mode mode = Mode.Manual; public Direction GetHorizontalInput() { if (mode == Mode.Manual) return GetManualHorizontalInput(); else return ai.WhereShouldIFly(); } static Direction GetManualHorizontalInput() { if (Input.GetAxisRaw("Horizontal") > 0) return Direction.Rigth; if (Input.GetAxisRaw("Horizontal") < 0) return Direction.Left; return Direction.None; } }
C++
UTF-8
854
3.28125
3
[]
no_license
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9. class Solution { public: int numSquares(int n) { vector<int> dp (n + 1, 1); unordered_set<int> square; square.insert(1); for (int i = 2; i <= n; i++) { int a = sqrt(i), res = INT_MAX; if (a * a == i) square.insert(i); else if (dp[i - 1] == 1) dp[i] = 2; else { int temp = INT_MAX; for(int s : square) { temp = min(temp, 1 + dp[i - s]); if (temp == 2) break; } dp[i] = temp; } } return dp[n]; } };
Python
UTF-8
2,338
2.9375
3
[]
no_license
from sys import argv from json import dumps ########## CONSTANTS ############## SEPARATORS = [' ', ' - ', ' "', '" ', ' "', '" "', '"'] UNIMPORTANT_SEPARATORS = {'" "'} DATA_DICT = { 0: 'IP', 1: 'domain', 2: 'dateTime', 3: 'HTTPRequest', 4: 'responseStatus', 5: 'client' } FILE_NAME = 'out_%04d.json' ## donno if it is a good idea, but wanted to print ## number of created files at the and CREATED_FILES_NUM = 0 ###### Helper functions ########### def parse_lines(line): data = [] for sep in SEPARATORS: if sep not in UNIMPORTANT_SEPARATORS: to_separate = line.find(sep) data.append(line[:to_separate]) line = line[to_separate + len(sep):] ## filter unimportant data else: to_separate = line.find(sep) line = line[to_separate + len(sep):] return data def convert_to_dict(data): json_element = {} for i in range(len(data)): json_element[DATA_DICT[i]] = data[i] return json_element ###### Main Function ################ def write_json(file, size): elements_added = 0 files_order = 1 json_list = [] for line in file: data = parse_lines(line) json_element = convert_to_dict(data) json_list.append(json_element) elements_added += 1 if elements_added >= size: ## convert to json json_list = dumps(json_list) ## write json list to_write = open(FILE_NAME % (files_order), 'w') to_write.write(json_list) to_write.close() ## empty variables json_list = [] elements_added = 0 files_order += 1 # for testing.. # decides how many files to write # if files_order > 3: # break global CREATED_FILES_NUM CREATED_FILES_NUM = files_order - 1 ###### Process flow ################# ## take the name of the file from first argument to script call file_name = str(argv[1]) ## take the number of values that are supposed to be in ## generated JSON file from second argument to script call size = int(argv[2]) ## open file and do magic with open(file_name, 'r') as log: ## initialize variables write_json(log, size) print ('Succesfully created %s json files from %s' % ( CREATED_FILES_NUM, file_name)) # #### Some stress testing ############ # f= open(file_name, 'r') # for i in range(100000): # line = f.readline() # if len(parse_lines(line)) != 6: # print line # print parse_lines(line) # break # f.close()
Python
UTF-8
2,885
2.75
3
[]
no_license
import json import sys import random import os import numpy as np from collections import deque from keras.models import Sequential from keras.layers import * from keras.optimizers import * class KerasAgent: def __init__(self, shape, action_size): self.weight_backup = "bombergirl_weight.model" self.shape = shape self.action_size = action_size self.memory = deque(maxlen=2000) self.learning_rate = 0.001 self.gamma = 0.95 self.exploration_rate = 1.0 self.exploration_min = 0.01 self.exploration_decay = 0.995 self.model = self._build_model() def _build_model(self): model = Sequential() # Convolutions. model.add(Conv2D( 16, kernel_size=(3, 3), strides=(1, 1), #data_format='channels_first', input_shape=self.shape )) model.add(Activation('relu')) model.add(Conv2D( 32, kernel_size=(3, 3), strides=(1, 1), data_format='channels_first' )) model.add(Activation('relu')) # Dense layers.² model.add(Flatten()) model.add(Dense(256)) model.add(Activation('relu')) model.add(Dense(self.action_size)) model.summary() model.compile(loss='mse', optimizer=Adam(lr=self.learning_rate)) #model.compile(RMSprop(), 'MSE') if os.path.isfile(self.weight_backup): model.load_weights(self.weight_backup) self.exploration_rate = self.exploration_min return model def save_model(self, name): self.model.save(self.weight_backup) self.model.save(name) def act(self, state): if np.random.rand() <= self.exploration_rate: return random.randrange(self.action_size) act_values = self.model.predict(state) return np.argmax(act_values[0]) def remember(self, state, action, reward, next_state, done): self.memory.append((state, action, reward, next_state, done)) def replay(self, sample_batch_size=256): if len(self.memory) < sample_batch_size: sample_batch_size=len(self.memory) sample_batch = random.sample(self.memory, sample_batch_size) for state, action, reward, next_state, done in sample_batch: target = reward if not done: target = (reward + self.gamma * np.amax(self.model.predict(next_state)[0])) target_f = self.model.predict(state) target_f[0][action] = target self.model.fit(state, target_f, epochs=1, verbose=0) if self.exploration_rate > self.exploration_min: self.exploration_rate *= self.exploration_decay
C++
UTF-8
381
2.984375
3
[ "Apache-2.0" ]
permissive
/* 王道考研机试指南 p87 GCD */ #include <stdio.h> int gcd(int a, int b) { if(b == 0) return a; return gcd(b, a%b); } int gcd1(int a, int b) { int t; while(b) { t = a%b; a = b; b = t; } return a; } int main() { int a, b; while(scanf("%d %d", &a, &b) != EOF) printf("%d\n", gcd(a, b)); return 0; }
Python
UTF-8
924
3.46875
3
[]
no_license
# chats # 读取档案 def read_file(filename): chats = [] with open(filename, 'r', encoding = 'utf-8-sig') as f: for line in f: chats.append(line.strip()) return chats # 转换格式 [名字:语句]的格式 def convert(chats): new = [] person = None for c in chats: if c == 'Allen': person = 'Allen' continue elif c =='Tom': person = 'Tom' continue if person: new.append(person + ':' + c) return new #写入档案 def write_file(filename, chats): with open(filename, 'w', encoding = 'utf-8-sig') as f: for c in chats: f.write(c + '\n') def main(): input_file_name = 'input.txt' output_file_name = 'output.txt' chats = read_file(input_file_name) chats = convert(chats) write_file(output_file_name, chats) if __name__ == '__main__': main()