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
| 5,094
| 1.898438
| 2
|
[] |
no_license
|
package com.bonelf.auth.config;
import com.bonelf.auth.core.oauth2.granter.mail.MailAuthenticationProvider;
import com.bonelf.auth.core.oauth2.granter.mobile.MobileAuthenticationProvider;
import com.bonelf.auth.core.oauth2.granter.openid.OpenIdAuthenticationProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
/**
* <p>
* 签权服务
* </p>
* @author bonelf
* @since 2020/11/17 15:37
*/
@Slf4j
@Configuration
@EnableWebSecurity
public class WebServerSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
@Qualifier("userDetailsService")
private UserDetailsService userDetailsService;
@Autowired
@Qualifier("mobileUserDetailsService")
private UserDetailsService mobileUserDetailsService;
@Autowired
@Qualifier("openidUserDetailsService")
private UserDetailsService openidUserDetailsService;
@Autowired
@Qualifier("mailUserDetailsService")
private UserDetailsService mailUserDetailsService;
/**
* @description 其他请在网关bonelf.anno-url过滤
* @author bonelf
* @date 2020-11-18 16:20
*/
@Override
public void configure(WebSecurity web) {
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**")
.antMatchers("/swagger-ui/index.html")
.antMatchers("/oauth/token_key")
.antMatchers("/v2/api-docs");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
log.debug("HttpSecurity configure method");
http.csrf().disable();
SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setTargetUrlParameter("redirectTo");
http.authorizeRequests()
.antMatchers("/assets/**").permitAll()
.antMatchers("/actuator/**").permitAll()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login")
.successHandler(successHandler).and()
.logout().logoutUrl("/logout")
.and()
.httpBasic().and()
.csrf().disable();
}
/**
* 注入自定义的userDetailsService实现,获取用户信息,设置密码加密方式
* 多种验证方式
* @param authenticationManagerBuilder
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
// 设置手机验证码登录的AuthenticationProvider
authenticationManagerBuilder.authenticationProvider(mobileAuthenticationProvider());
authenticationManagerBuilder.authenticationProvider(mailAuthenticationProvider());
// 设置微信登录的AuthenticationProvider
authenticationManagerBuilder.authenticationProvider(openIdAuthenticationProvider());
}
/**
* 将 AuthenticationManager 注册为 bean , 方便配置 oauth server 的时候使用
*/
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
/**
* 创建手机验证码登录的AuthenticationProvider
* @return mobileAuthenticationProvider
*/
@Bean
public MobileAuthenticationProvider mobileAuthenticationProvider() {
MobileAuthenticationProvider mobileAuthenticationProvider = new MobileAuthenticationProvider(this.mobileUserDetailsService);
mobileAuthenticationProvider.setPasswordEncoder(passwordEncoder());
return mobileAuthenticationProvider;
}
@Bean
public MailAuthenticationProvider mailAuthenticationProvider() {
MailAuthenticationProvider mailAuthenticationProvider = new MailAuthenticationProvider(this.mailUserDetailsService);
mailAuthenticationProvider.setPasswordEncoder(passwordEncoder());
return mailAuthenticationProvider;
}
@Bean
public OpenIdAuthenticationProvider openIdAuthenticationProvider() {
return new OpenIdAuthenticationProvider(this.openidUserDetailsService);
}
}
|
Java
|
UTF-8
| 2,505
| 2.453125
| 2
|
[] |
no_license
|
package me.sheepyang.onlylive.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import me.sheepyang.onlylive.R;
import me.sheepyang.onlylive.greenentity.PlayerGoods;
import me.sheepyang.onlylive.utils.MathUtil;
/**
* Created by SheepYang on 2016/10/28 21:26.
*/
public class PlayerGoodsAdapter extends BaseAdapter {
private Context mContext;
private List<PlayerGoods> mData;
public PlayerGoodsAdapter(Context context, List<PlayerGoods> playerGoodsList) {
mContext = context;
mData = playerGoodsList;
}
@Override
public int getCount() {
return mData == null ? 0 : mData.size();
}
@Override
public PlayerGoods getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return mData.get(position).getId();
}
public void updata(List<PlayerGoods> playerGoodsList) {
mData = playerGoodsList;
notifyDataSetChanged();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder vh;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.item_player_goods, null);
vh = new ViewHolder(convertView);
convertView.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
PlayerGoods playerGoods = mData.get(position);
vh.tvName.setText(playerGoods.getName());
if (MathUtil.lt(playerGoods.getPrice(), "0")) {
vh.tvPrice.setText("有价无市");// 没有市价,表示现在市场不能够出售该物品
} else {
vh.tvPrice.setText(playerGoods.getPrice() + "");
}
vh.tvNumber.setText("数量:" + playerGoods.getNumber() + "");
vh.tvPaid.setText(playerGoods.getPaid() + "");
return convertView;
}
static class ViewHolder {
@BindView(R.id.tv_name)
TextView tvName;
@BindView(R.id.tv_price)
TextView tvPrice;
@BindView(R.id.tv_number)
TextView tvNumber;
@BindView(R.id.tv_paid)
TextView tvPaid;
ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
}
|
JavaScript
|
UTF-8
| 3,647
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
app
.controller('RunnerCtrl', function($scope, $state, $rootScope, $animate, $interval){
console.log("Runner");
//Time Calculator
//TODO: This is a Directive
$scope.time = "00:00:00";
var elapsedSeconds = 0;
var timer = $interval(function(){
if(!$rootScope._RUNNING) return;
elapsedSeconds++;
$scope.time = secondsToTime(elapsedSeconds);
},1000)
function secondsToTime(s){
var sec_num = parseInt(s, 10); // don't forget the second param
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
var time = hours+':'+minutes+':'+seconds;
return time;
}
//Distance Calculator
//TODO: This is a Directive
$scope.dist_unit = "km";
$scope.dist_traveled = 0.00;
var last_position = { lat:null, lon:null };
var geo_options = {
enableHighAccuracy: true,
maximumAge : 30000,
timeout : 27000
};
var watchPosition = navigator.geolocation.watchPosition(function(position){
if(!$rootScope._RUNNING) return;
console.log("User has moved");
//if the last position wasn't null, calculate distance traveled
var lat = position.coords.latitude;
var lon = position.coords.longitude;
if(last_position.lat && last_position.lon){
var newDist = getDistanceFromLatLonInKm(last_position.lat, last_position.lon, lat, lon);
if($scope.dist_unit == "mi"){
newDist *= 0.621371;
}
$scope.dist_traveled += newDist
}
last_position.lat = lat;
last_position.lon = lon;
}, null, geo_options);
$scope.changeUnits = function(){
if($scope.dist_unit == 'mi') {
$scope.dist_unit = "km";
$scope.dist_traveled = $scope.dist_traveled * 1.60934;
}
else
{
$scope.dist_unit = 'mi';
$scope.dist_traveled = $scope.dist_traveled * 0.621371;
}
}
function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2-lat1); // deg2rad below
var dLon = deg2rad(lon2-lon1);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; // Distance in km
return d;
}
function deg2rad(deg) {
return deg * (Math.PI/180)
}
//Newt Calculator
//TODO: This is a Directive
$scope.newts = 0;
$scope.spawn = 0;
$scope.spawnText = "";
$scope.newtFound = function(){
$scope.spawnText = "+1";
$scope.newts++;
$scope.spawn = 1;
setTimeout(function(){
$scope.spawn = 0;
$scope.$apply();
},100)
};
$scope.reset = function(){
//TODO: Change this
var res = confirm("Are you sure you want to reset?");
if(res){
$scope.time = "00:00:00";
elapsedSeconds = 0;
$newts = 0;
$scope.dist_traveled = 0;
} else {
}
}
//Save Variables
$scope.saveData = function(){
$rootScope.data = {
time:$scope.time,
distance:$scope.dist_traveled,
distance_units:$scope.dist_unit,
newts:$scope.newtFound
};
$state.go('done');
}
})
|
Java
|
UTF-8
| 1,397
| 1.875
| 2
|
[] |
no_license
|
/*******************************************************************************
* Copyright 2011, 2013 Model Driven Solutions, Inc.
* All rights reserved worldwide. This program and the accompanying materials
* are made available for use under the terms of the GNU General Public License
* (GPL) version 3 that accompanies this distribution and is available at
* http://www.gnu.org/licenses/gpl-3.0.html. For alternative licensing terms,
* contact Model Driven Solutions.
*******************************************************************************/
package org.modeldriven.alf.eclipse.uml;
public class CallBehaviorAction extends CallAction implements
org.modeldriven.alf.uml.CallBehaviorAction {
public CallBehaviorAction() {
this(org.eclipse.uml2.uml.UMLFactory.eINSTANCE
.createCallBehaviorAction());
}
public CallBehaviorAction(org.eclipse.uml2.uml.CallBehaviorAction base) {
super(base);
}
public org.eclipse.uml2.uml.CallBehaviorAction getBase() {
return (org.eclipse.uml2.uml.CallBehaviorAction) this.base;
}
public org.modeldriven.alf.uml.Behavior getBehavior() {
return (org.modeldriven.alf.uml.Behavior) wrap(this.getBase()
.getBehavior());
}
public void setBehavior(org.modeldriven.alf.uml.Behavior behavior) {
this.getBase().setBehavior(
behavior == null ? null : ((Behavior) behavior).getBase());
}
}
|
C++
|
UTF-8
| 986
| 2.671875
| 3
|
[] |
no_license
|
#include "JanelaPrincipal.h"
#include <iostream>
JanelaPrincipal::JanelaPrincipal() : button01("OK"), button02("Close") {
set_title("Analizar");
set_size_request(800, 600);
set_border_width(2);
add(frame01);
frame01.set_shadow_type(Gtk::SHADOW_ETCHED_OUT);
button01.signal_clicked().connect(sigc::mem_fun(*this, &JanelaPrincipal::on_button01_clicked));
button01.set_size_request(64, 16);
button_box.pack_start(button01);
button01.show();
button02.signal_clicked().connect(sigc::mem_fun(*this, &JanelaPrincipal::on_button02_clicked));
button02.set_size_request(64, 16);
button_box.pack_start(button02);
button02.show();
button_box.set_valign(Gtk::ALIGN_END);
button_box.set_halign(Gtk::ALIGN_END);
frame01.add(button_box);
button_box.show();
frame01.show();
show();
}
void JanelaPrincipal::on_button01_clicked() {
std::cout << "Button01 clicked.\n";
}
void JanelaPrincipal::on_button02_clicked() {
std::cout << "Button02 clicked.\n";
}
|
Python
|
UTF-8
| 711
| 3.171875
| 3
|
[] |
no_license
|
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
currents = np.array([25.90,27.80,29.70,31.80,33.9,36,38]) # in mA
power = ((20-0)/(currents[-1]-currents[0]))*(currents- currents[0]) # in mW
print(power)
coincidence_counts = np.array([1.22,7.28,14.98,24.26,29.5,38.68,42.6])
# in counts per second
slope,intercept,r_value, p_value, std_err = stats.linregress(power,coincidence_counts)
print(r_value**2,slope,intercept)
plt.figure()
plt.plot(power,coincidence_counts,'rx',label = 'Raw Data')
plt.plot(power,slope*power + intercept,label = 'Best Fit')
plt.title('Coincidence Counts vs. Laser Pump Power')
plt.xlabel('Power (in mW)')
plt.ylabel(r'Counts (in $s^{-1}$)')
plt.show()
|
PHP
|
UTF-8
| 979
| 3.296875
| 3
|
[] |
no_license
|
<?php
// MySql i eh nativa do php
class db{
//host - endereco que o MySql esta instalado
private $host = 'localhost';
//usuario
private $usuario = 'root';
//senha
private $senha = '';
//banco de dados
private $database = "twitter_clone";
// Methods
function conecta_mysql(){
// Para criar a conexao com o mysql
$con = mysqli_connect($this->host, $this->usuario, $this->senha, $this->database);
// Necessario setar o charset de comunicacao entre banco e aplicacao (frontend - arquivos - comunicao com DB estao no mesmo charset - baixa possibilidade de erro de caracteres)
mysqli_set_charset($con, 'utf8');
// Verificar se houve erro com DB
if (mysqli_connect_errno()){
echo "Error trying to connect with MySQL".mysqli_connect_error();
}
return $con;
}
}
?>
|
C#
|
UTF-8
| 5,091
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
namespace Yfy.Api.ShareLink
{
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel;
using System.Collections.Generic;
/// <summary>
/// 通用分享链接对象
/// </summary>
public class YfyShareLink : YfyObject
{
/// <summary>
/// 分享标识符
/// </summary>
[JsonProperty("unique_name")]
public string UniqueName { get; set; }
/// <summary>
/// 完整分享链接
/// </summary>
[JsonProperty("share_link")]
public string ShareLinkUrl { get; set; }
/// <summary>
/// 分享链接权限(公开和企业)
/// </summary>
[JsonProperty("access")]
[JsonConverter(typeof(LowerStringEnumConverter))]
[DefaultValue(ShareLinkAccess.Public)]
public ShareLinkAccess Access { get; set; }
/// <summary>
/// 是否有密码
/// </summary>
[JsonProperty("password_protected", DefaultValueHandling = DefaultValueHandling.Ignore)]
[DefaultValue(false)]
public bool PasswordProtected { get; set; }
/// <summary>
/// 过期时间(yyyy-MM-dd)
/// </summary>
[JsonProperty("due_time")]
[JsonConverter(typeof(ChinaDateTimeConverter))]
public DateTime DueTime { get; set; }
/// <summary>
/// 是否禁止下载
/// </summary>
[JsonProperty("disable_download", DefaultValueHandling = DefaultValueHandling.Ignore)]
[DefaultValue(false)]
public bool DisableDownload { get; set; }
/// <summary>
/// 创建时间
/// </summary>
[JsonProperty("created_at")]
[DefaultValue(0)]
public int CreatedAt { get; set; }
/// <summary>
/// 最后修改时间
/// </summary>
[JsonProperty("modified_at")]
[DefaultValue(0)]
public int ModifiedAt { get; set; }
/// <summary>
/// 该分享链接中内容的总下载次数
/// </summary>
[JsonProperty("download_count_total")]
[DefaultValue(0)]
public int DownloadCountTotal { get; set; }
/// <summary>
/// 该分享链接的总共查看次数
/// </summary>
[JsonProperty("view_count")]
[DefaultValue(0)]
public int ViewCount { get; set; }
}
/// <summary>
/// 通用分享链接集合
/// </summary>
public class YfyShareLinkCollection
{
/// <summary>
/// 分享链接
/// </summary>
[JsonProperty("share_links")]
public List<YfyShareLink> ShareLinks { get; set; }
/// <summary>
/// 分享链接总数
/// </summary>
[JsonProperty("total_count")]
public int TotalCount { get; set; }
/// <summary>
/// 分页索引
/// </summary>
[JsonProperty("page_id")]
public int PageId { get; set; }
/// <summary>
/// 分页容量
/// </summary>
[JsonProperty("page_capacity")]
public int PageCapacity { get; set; }
/// <summary>
/// 分页总页数
/// </summary>
[JsonProperty("page_count")]
public int PageCount { get; set; }
}
/// <summary>
/// 分享链接访问权限
/// </summary>
public enum ShareLinkAccess
{
/// <summary>
/// 公开
/// </summary>
Public,
/// <summary>
/// 公司内访问
/// </summary>
Company,
}
internal class ChinaDateTimeConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(DateTime));
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
DateTime date = (DateTime)value;
writer.WriteValue(string.Format("{0:yyyy-MM-dd}", date));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var value = reader.Value.ToString();
DateTime? date = value == "" ? (DateTime?)null : DateTime.Parse(value);
return date;
}
}
internal class LowerStringEnumConverter : JsonConverter
{
private static StringEnumConverter sec = new StringEnumConverter();
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(ShareLinkAccess));
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var str = value.ToString().ToLower();
writer.WriteValue(str);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return sec.ReadJson(reader, objectType, existingValue, serializer);
}
}
}
|
Java
|
UTF-8
| 528
| 2.359375
| 2
|
[] |
no_license
|
package org.study.commands;
import javax.servlet.http.HttpServletRequest;
public class Error404Command implements Command {
/**
* this command return error 404 page
*/
@Override
public String execute(HttpServletRequest request) {
return "jsp/404.jsp";
}
/**
* this method always return true for indicated command. This pages is in access for any unregistered user
*/
@Override
public boolean checkPermissions(HttpServletRequest request) {
return true;
}
}
|
Python
|
UTF-8
| 4,379
| 3.28125
| 3
|
[] |
no_license
|
# 改变图片对比度
import cv2
import numpy as np
def image_rename(old_name, output_path, operate_name, suq_number):
"""
:param old_name: 待水平移动的图形名称(完全路径)
:param output_path: 水平移动后保存的文件夹路径
:param operate_name: 操作名称(用于图像命名)
:param suq_number: 水平移动的序号
:return: 返回新的名称(包含完全路径)
"""
ima_name = old_name.split("\\").pop()
ima_name = ima_name.split(".")
str_suq_number = str(suq_number).rjust(3, '0')
new_name = output_path + "\\" + ima_name[0] + "_" + operate_name + str_suq_number + "." + ima_name[1]
return new_name
def image_edge(img):
'''
寻找图片最外层的轮廓,并将轮廓外层涂为黑色,轮廓内层涂为白色
:param img: 待处理图像
:return: 二值图
'''
ret, thresh = cv2.threshold(cv2.cvtColor(img.copy(), cv2.COLOR_BGR2GRAY) , 15, 255, cv2.THRESH_BINARY)
contours, hier = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
black = cv2.cvtColor(np.zeros((img.shape[0], img.shape[1]), dtype=np.uint8), cv2.COLOR_GRAY2BGR)
for cnt in contours:
hull = cv2.convexHull(cnt)
cv2.fillPoly(black, [hull], (255, 255, 255))
return black
def image_contrast_2(ima_name, parameters, output_path, suq_number):
ima = cv2.imdecode(np.fromfile(ima_name, dtype=np.uint8), -1)
rows, cols, chunnel = ima.shape
blank = np.zeros([rows, cols, chunnel], ima.dtype) # np.zeros(img1.shape, dtype=uint8)
ima_change = cv2.addWeighted(ima, parameters[0], blank, 1 - parameters[0], parameters[1])
print(ima.shape)
ima_edge = image_edge(ima)
print(ima_edge.shape)
for x in range(rows):
for y in range(cols):
if ima_edge[x,y][0] < 10:
ima_change[x,y] = [0,0,0]
cv2.imshow('test', ima)
cv2.waitKey()
cv2.imshow('test2', ima_change)
cv2.waitKey()
ima_new_name = image_rename(ima_name, output_path, "C", suq_number)
cv2.imencode('.jpg', ima_change)[1].tofile(ima_new_name)
PATH = '.\\picture\\0.jpg'
image_contrast_2(PATH, [1.2,150], '.\\picture', 2)
'''
ret, thresh = cv2.threshold(cv2.cvtColor(img.copy(), cv2.COLOR_BGR2GRAY) , 10, 255, cv2.THRESH_BINARY)
cv2.imshow('test', thresh)
cv2.waitKey()
# findContours函数查找图像里的图形轮廓
# 函数参数thresh是图像对象
# 层次类型,参数cv2.RETR_EXTERNAL是获取最外层轮廓,cv2.RETR_TREE是获取轮廓的整体结构
# 轮廓逼近方法
# 输出的返回值,image是原图像、contours是图像的轮廓、hier是层次类型
contours, hier = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 创建新的图像black
black = cv2.cvtColor(np.zeros((img.shape[1], img.shape[0]), dtype=np.uint8), cv2.COLOR_GRAY2BGR)
cv2.imshow('test', black)
cv2.waitKey()
for cnt in contours:
print(cnt.shape)
# 轮廓周长也被称为弧长。可以使用函数 cv2.arcLength() 计算得到。这个函数的第二参数可以用来指定对象的形状是闭合的(True) ,还是打开的(一条曲线)
epsilon = 0.01 * cv2.arcLength(cnt, True)
print(epsilon)
# 函数approxPolyDP来对指定的点集进行逼近,cnt是图像轮廓,epsilon表示的是精度,越小精度越高,因为表示的意思是是原始曲线与近似曲线之间的最大距离。
# 第三个函数参数若为true,则说明近似曲线是闭合的,它的首位都是相连,反之,若为false,则断开。
approx = cv2.approxPolyDP(cnt, epsilon, True)
print(approx.shape)
# convexHull检查一个曲线的凸性缺陷并进行修正,参数cnt是图像轮廓。
hull = cv2.convexHull(cnt)
print(hull.shape)
# 勾画图像原始的轮廓
#cv2.drawContours(black, [cnt], -1, (0, 255, 0), 2)
# 用多边形勾画轮廓区域
#cv2.drawContours(black, [approx], -1, (255, 255, 0), 2)
# 修正凸性缺陷的轮廓区域
#cv2.drawContours(black, [hull], -1, (0, 0, 255), 2)
#cv2.polylines(black, [hull], True, (0, 0, 255))
cv2.fillPoly(black, [hull], (255, 255, 255))
# 显示图像
cv2.imshow("hull", black)
print(black.shape)
cv2.waitKey()
cv2.destroyAllWindows()
'''
|
Java
|
UTF-8
| 25,460
| 2.203125
| 2
|
[
"BSD-3-Clause",
"Apache-2.0",
"BSD-2-Clause"
] |
permissive
|
/*
* ScanCmd.java
*
* Copyright (c) 1997 Sun Microsystems, Inc.
*
* See the file "license.terms" for information on usage and
* redistribution of this file, and for a DISCLAIMER OF ALL
* WARRANTIES.
*
* RCS: @(#) $Id: ScanCmd.java,v 1.6 2009/07/23 10:42:15 rszulgo Exp $
*
*/
package tcl.lang.cmd;
import tcl.lang.Command;
import tcl.lang.Interp;
import tcl.lang.StrtoulResult;
import tcl.lang.TCL;
import tcl.lang.TclDouble;
import tcl.lang.TclException;
import tcl.lang.TclInteger;
import tcl.lang.TclList;
import tcl.lang.TclNumArgsException;
import tcl.lang.TclObject;
import tcl.lang.TclString;
import tcl.lang.Util;
/**
* This class implements the built-in "scan" command in Tcl.
*/
public class ScanCmd implements Command {
/*
* The code in this class is almost a literal translation 8.4 C Tcl's
* tclScan.c, with changes to eliminate goto and pointer arithmetic. We also
* assume that %i, %d, %x will always be resolved to a 64-bit long,
* regardless of %l or %L. This is consistent with a 64-bit compiled C TCL.
*/
/** Don't skip blanks. */
private final int SCAN_NOSKIP = 0x1;
/** Suppress assignment. */
private final int SCAN_SUPPRESS = 0x2;
/** Read an unsigned value. */
private final int SCAN_UNSIGNED = 0x4;
/** A width value was supplied. */
private final int SCAN_WIDTH = 0x8;
/** Asked for a wide value. */
private final int SCAN_LONGER = 0x400;
/** asked for bignum value */
private final int SCAN_BIG = 0x800;
/**
* This procedure is invoked to process the "scan" Tcl command. See the user
* documentation for details on what it does.
*
*/
public void cmdProc(Interp interp, TclObject objv[]) throws TclException {
String format;
int numVars = -1;
int totalVars = -1;
if (objv.length < 3) {
throw new TclNumArgsException(interp, 1, objv, "string format ?varName varName ...?");
}
format = objv[2].toString();
numVars = objv.length - 3;
/*
* Check for errors in the format string
*/
totalVars = validateFormat(interp, format, numVars);
/*
* Allocate space for the result objects
*/
TclObject[] objs = new TclObject[totalVars];
for (int i = 0; i < totalVars; i++) {
objs[i] = null;
}
String string = objv[1].toString();
/*
* Iterate over the format string filling in the result objects until we
* reach the end of input, the end of the format string, or there is a
* mismatch.
*/
int objIndex = 0;
int nconversions = 0;
int formatIndex = 0;
int stringIndex = 0;
boolean underflow = false;
DONE: while (formatIndex < format.length()) {
char sch;
char ch = format.charAt(formatIndex++);
int flags = 0;
/*
* If we see whitespace in the format, skip whitespace in the
* string.
*/
if (Character.isWhitespace(ch)) {
while (stringIndex < string.length() && Character.isWhitespace(string.charAt(stringIndex))) {
++stringIndex;
}
if (stringIndex == string.length()) {
break DONE;
}
continue;
}
boolean isLiteral;
if (ch == '%') {
ch = format.charAt(formatIndex++);
isLiteral = (ch == '%');
} else {
isLiteral = true;
}
if (isLiteral) {
if (stringIndex == string.length()) {
underflow = true;
break DONE;
}
sch = string.charAt(stringIndex++);
if (ch != sch) {
break DONE;
}
continue;
}
/*
* Check for assignment suppression ('*') or an XPG3-style
* assignment ('%n$').
*/
long value;
if (ch == '*') {
flags |= SCAN_SUPPRESS;
ch = format.charAt(formatIndex++);
} else if ((ch < 0x80) && Character.isDigit(ch)) { /*
* INTL: "C"
* locale.
*/
Util.strtoul(format, formatIndex - 1, 10, interp.strtoulResult);
value = interp.strtoulResult.value;
if (format.charAt(interp.strtoulResult.index) == '$') {
formatIndex = interp.strtoulResult.index + 1;
ch = format.charAt(formatIndex++);
objIndex = (int) (value - 1);
}
}
/*
* Parse any width specifier.
*/
int width;
if ((ch < 0x80) && Character.isDigit(ch)) { /* INTL: "C" locale. */
Util.strtoul(format, formatIndex - 1, 10, interp.strtoulResult);
width = (int) interp.strtoulResult.value;
formatIndex = interp.strtoulResult.index;
ch = format.charAt(formatIndex++);
} else {
width = 0;
}
/*
* Handle any size specifier.
*/
switch (ch) {
case 'l':
// Rest of JTCL does not have bignum support, so we won't add it
// here
// if (formatIndex < format.length() &&
// format.charAt(formatIndex) == 'l') {
// flags |= SCAN_BIG;
// formatIndex++;
// ch = format.charAt(formatIndex++);
// break;
// }
case 'L':
flags |= SCAN_LONGER;
/*
* Fall through so we skip to the next character.
*/
case 'h':
ch = format.charAt(formatIndex++);
}
/*
* Handle the various field types.
*/
char op = ' ';
int radix = 0;
switch (ch) {
case 'n':
if ((flags & SCAN_SUPPRESS) == 0) {
TclObject objPtr = TclInteger.newInstance(stringIndex);
objs[objIndex++] = objPtr;
}
nconversions++;
continue;
case 'd':
op = 'i';
radix = 10;
break;
case 'i':
op = 'i';
radix = 0; // get it from prefix
break;
case 'o':
op = 'i';
radix = 8;
break;
case 'x':
op = 'i';
radix = 16;
break;
case 'b':
op = 'i';
radix = 2;
break;
case 'u':
op = 'i';
radix = 10;
flags |= SCAN_UNSIGNED;
break;
case 'f':
case 'e':
case 'g':
op = 'f';
break;
case 's':
op = 's';
break;
case 'c':
op = 'c';
flags |= SCAN_NOSKIP;
break;
case '[':
op = '[';
flags |= SCAN_NOSKIP;
break;
}
/*
* At this point, we will need additional characters from the string
* to proceed.
*/
if (stringIndex >= string.length()) {
underflow = true;
break DONE;
}
/*
* Skip any leading whitespace at the beginning of a field unless
* the format suppresses this behavior.
*/
if ((flags & SCAN_NOSKIP) == 0) {
while (stringIndex < string.length()) {
if (Character.isWhitespace(string.charAt(stringIndex))) {
++stringIndex;
} else {
break;
}
}
if (stringIndex == string.length()) {
underflow = true;
break DONE;
}
}
/*
* Perform the requested scanning operation.
*/
switch (op) {
case 's':
/*
* Scan a string up to width characters or whitespace.
*/
if (width == 0) {
width = Integer.MAX_VALUE;
}
int end = stringIndex;
while (end < string.length()) {
sch = string.charAt(end);
if (Character.isWhitespace(sch)) {
break;
}
end++;
if (--width == 0) {
break;
}
}
if ((flags & SCAN_SUPPRESS) == 0) {
TclObject objPtr = TclString.newInstance(string.substring(stringIndex, end));
objs[objIndex++] = objPtr;
}
stringIndex = end;
break;
case '[': {
CharSet cset = new CharSet(format, formatIndex);
formatIndex = cset.getEndOfFormat();
if (width == 0) {
width = Integer.MAX_VALUE;
}
end = stringIndex;
while (end < string.length()) {
sch = string.charAt(end);
if (!cset.charInSet(sch)) {
break;
}
++end;
if (--width == 0) {
break;
}
}
if (stringIndex == end) {
/*
* Nothing matched the range, stop processing.
*/
break DONE;
}
if ((flags & SCAN_SUPPRESS) == 0) {
TclObject objPtr = TclString.newInstance(string.substring(stringIndex, end));
objs[objIndex++] = objPtr;
}
stringIndex = end;
break;
}
case 'c':
/*
* Scan a single Unicode character.
*/
sch = string.charAt(stringIndex++);
if ((flags & SCAN_SUPPRESS) == 0) {
TclObject objPtr = TclInteger.newInstance(sch);
objs[objIndex++] = objPtr;
}
break;
case 'i':
/*
* Scan an unsigned or signed integer.
*/
if (width == 0)
Util.strtoul(string, stringIndex, radix, interp.strtoulResult);
else {
if (stringIndex + width > string.length()) {
underflow = true;
break DONE;
}
String truncString = string.substring(0, stringIndex + width);
Util.strtoul(truncString, stringIndex, radix, interp.strtoulResult);
}
if (interp.strtoulResult.errno != TCL.INVALID_INTEGER) {
long v;
if (interp.strtoulResult.errno == TCL.INTEGER_RANGE) {
v = -1;
} else {
v = interp.strtoulResult.value;
}
stringIndex = interp.strtoulResult.index;
if ((flags & SCAN_SUPPRESS) == 0) {
objs[objIndex++] = TclInteger.newInstance(v);
}
} else {
if (width == 1 || string.length() == 1) {
/* special case when we underflow; see scan-4.44 */
underflow = (string.charAt(stringIndex) == '-' || string.charAt(stringIndex) == '+');
}
break DONE;
}
break;
case 'f':
/*
* scan a floating point number
*/
if (width == 0)
Util.strtod(string, stringIndex, -1, interp.strtodResult);
else {
if (stringIndex + width > string.length()) {
underflow = true;
break DONE;
}
String truncString = string.substring(0, stringIndex + width);
Util.strtod(truncString, stringIndex, -1, interp.strtodResult);
}
if (interp.strtodResult.errno == 0) {
stringIndex = interp.strtodResult.index;
if ((flags & SCAN_SUPPRESS) == 0) {
objs[objIndex++] = TclDouble.newInstance(interp.strtodResult.value);
}
} else {
if (width == 1 || string.length() == 1) {
/* special case when we underflow; see scan-4.55 */
underflow = (string.charAt(stringIndex) == '-' || string.charAt(stringIndex) == '+');
}
break DONE;
}
break;
}
nconversions++;
}
int result = 0;
if (numVars > 0) {
/*
* In this case, variables were specified (classic scan).
*/
StringBuffer varErrors = null;
for (int i = 0; i < totalVars; i++) {
if (objs[i] == null) {
continue;
}
result++;
try {
interp.setVar(objv[i + 3].toString(), objs[i], 0);
} catch (TclException e) {
// custom error message
if (varErrors == null)
varErrors = new StringBuffer();
// yes, errors really do get appended with no spaces
// between. See scan.test scan-4.61
varErrors.append("couldn't set variable \"").append(objv[i + 3].toString()).append('"');
}
}
if (varErrors != null)
throw new TclException(interp, varErrors.toString());
} else {
/*
* Here no vars were specified, we want a list returned (inline
* scan)
*/
TclObject objPtr = TclList.newInstance();
for (int i = 0; i < totalVars; i++) {
if (objs[i] != null) {
TclList.append(interp, objPtr, objs[i]);
} else {
/*
* More %-specifiers than matching chars, so we just spit
* out empty strings for these.
*/
TclList.append(interp, objPtr, TclString.newInstance(""));
}
}
interp.setResult(objPtr);
}
if (underflow && (nconversions == 0)) {
if (numVars > 0) {
interp.setResult(-1);
} else {
interp.setResult("");
}
} else if (numVars > 0) {
interp.setResult(result);
}
}
/**
* Parse the format string and verify that it is properly formed and that
* there are exactly enough variables on the command line.
*
* @param interp
* The current interpreter
* @param format
* The format string
* @param numVars
* The number of variables passed to the scan command
* @return Number of variables that will be required.
* @throws TclException
* if any invalid scan format is encountered.
*/
private int validateFormat(Interp interp, String format, int numVars) throws TclException {
boolean gotXpg = false;
boolean gotSequential = false;
int xpgSize = 0;
int objIndex = 0;
int flags = 0;
int[] nassign = new int[numVars == 0 ? 1 : numVars];
int value;
/*
* Initialize an array that records the number of times a variable is
* assigned to by the format string. We use this to detect if a variable
* is multiply assigned or left unassigned.
*/
for (int i = 0; i < nassign.length; i++) {
nassign[i] = 0;
}
int formatIndex = 0;
while (formatIndex < format.length()) {
char ch = format.charAt(formatIndex++);
flags = 0;
if (ch != '%') {
continue;
}
ch = format.charAt(formatIndex++);
if (ch == '%') {
continue;
}
if (ch == '*') {
flags |= SCAN_SUPPRESS;
ch = format.charAt(formatIndex++);
} else {
if (ch < 0x80 && Character.isDigit(ch)) {
/*
* Check for an XPG3-style %n$ specification. Note: there
* must not be a mixture of XPG3 specs and non-XPG3 specs in
* the same format string.
*/
StrtoulResult result = new StrtoulResult();
Util.strtoul(format, formatIndex - 1, 10, result);
int endIndex = result.index;
if (endIndex >= format.length()) {
// ran out of format characters before finding conversion character
throw new TclException(interp, "bad scan conversion character \"\"");
}
if (format.charAt(endIndex) != '$') {
/* notXpg */
gotSequential = true;
if (gotXpg) {
errorBadField(interp, '$');
}
} else {
formatIndex = endIndex + 1;
ch = format.charAt(formatIndex++);
gotXpg = true;
if (gotSequential) {
errorBadField(interp, '$');
}
value = (int) result.value;
objIndex = value - 1;
if ((objIndex < 0) || (numVars != 0 && (objIndex >= numVars))) {
errorDiffVars(interp, gotXpg);
} else if (numVars == 0) {
/*
* In the case where no vars are specified, the user
* can specify %9999$ legally, so we have to
* consider special rules for growing the assign
* array. 'value' is guaranteed to be > 0.
*/
xpgSize = (xpgSize > (int) result.value) ? xpgSize : (int) result.value;
}
}
} else {
/* notGpg: */
gotSequential = true;
if (gotXpg) {
errorCannotMix(interp, '$');
}
}
}
/* xpgCheckDone: */
/*
* Parse any width specifier.
*/
if ((ch < 0x80) && Character.isDigit(ch)) {
StrtoulResult result = new StrtoulResult();
Util.strtoul(format, formatIndex - 1, 10, result);
if (result.errno != 0) {
value = 0;
} else {
value = (int) result.value;
}
formatIndex = result.index;
flags |= SCAN_WIDTH;
ch = format.charAt(formatIndex++);
}
/*
* Handle any size specifier.
*/
switch (ch) {
case 'l':
// don't support bignum yet, since rest of JTCL does not
// if (format.charAt(formatIndex)=='l') {
// flags |= SCAN_BIG;
// ++formatIndex;
// ch = format.charAt(formatIndex++);
// break;
// }
case 'L':
flags |= SCAN_LONGER;
case 'h':
ch = format.charAt(formatIndex++);
}
if (!((flags & SCAN_SUPPRESS) != 0) && numVars > 0 && (objIndex >= numVars)) {
errorDiffVars(interp, gotXpg);
}
/*
* Handle the various field types.
*/
switch (ch) {
case 'c':
if ((flags & SCAN_WIDTH) != 0) {
errorCharFieldWidth(interp);
}
// Fall through !
case 'n':
case 's':
if ((flags & (SCAN_LONGER | SCAN_BIG)) != 0) {
errorLonger(interp, ch);
}
// Fall through !
case 'd':
case 'e':
case 'f':
case 'g':
case 'i':
case 'o':
case 'x':
case 'b':
break;
case 'u':
if ((flags & SCAN_BIG) != 0) {
throw new TclException(interp, "unsigned bignum scans are invalid");
}
break;
/*
* Bracket terms need special checking
*/
case '[':
if ((flags & (SCAN_LONGER | SCAN_BIG)) != 0) {
errorLonger(interp, ch);
}
if (formatIndex >= format.length()) {
errorBadSet(interp);
}
ch = format.charAt(formatIndex++);
if (ch == '^') {
if (formatIndex >= format.length()) {
errorBadSet(interp);
}
ch = format.charAt(formatIndex++);
}
if (ch == ']') {
if (formatIndex >= format.length()) {
errorBadSet(interp);
}
ch = format.charAt(formatIndex++);
}
while (ch != ']') {
if (formatIndex >= format.length()) {
errorBadSet(interp);
}
ch = format.charAt(formatIndex++);
}
break;
default:
errorBadConvChar(interp, ch);
}
if (!((flags & SCAN_SUPPRESS) != 0)) {
if (objIndex >= nassign.length) {
/*
* Expand the nassign buffer. If we are using XPG
* specifiers, make sure that we grow to a large enough
* size. xpgSize is guaranteed to be at least one larger
* than objIndex.
*/
int nspace;
if (xpgSize > 0)
nspace = xpgSize;
else
nspace = nassign.length + 16;
int[] newNassign = new int[nspace];
System.arraycopy(nassign, 0, newNassign, 0, nassign.length);
for (int i = nassign.length; i < newNassign.length; i++) {
newNassign[i] = 0;
}
nassign = newNassign;
}
nassign[objIndex]++;
objIndex++;
}
}
/*
* Verify that all of the variable were assigned exactly once.
*/
if (numVars == 0) {
if (xpgSize != 0) {
numVars = xpgSize;
} else {
numVars = objIndex;
}
}
for (int i = 0; i < numVars; i++) {
if (nassign[i] > 1) {
errorMultipleAssignments(interp);
} else if (xpgSize == 0 && nassign[i] == 0) {
/*
* If the space is empty, and xpgSize is 0 (means XPG wasn't
* used, and/or numVars != 0), then too many vars were given
*/
errorNotAssigned(interp);
}
}
return numVars; /* equiv to C Tcl *totalSubs */
}
/**
* Called whenever the number of varName args do not match the number of
* found and valid formatSpecifiers (matched and unmatched).
*
* @param interp
* - The TclInterp which called the cmdProc method .
*/
private static final void errorDiffVars(Interp interp, boolean gotXpg) throws TclException {
if (gotXpg) {
throw new TclException(interp, "\"%n$\" argument index out of range");
} else {
throw new TclException(interp, "different numbers of variable names and field specifiers");
}
}
/**
* Called whenever the current char in the frmtArr is erroneous
*
* @param interp
* - The TclInterp which called the cmdProc method .
* @param fieldSpecifier
* - The erroneous character
*/
private static final void errorCannotMix(Interp interp, char fieldSpecifier) throws TclException {
throw new TclException(interp, "cannot mix \"%\" and \"%n" + fieldSpecifier + "\" conversion specifiers");
}
/**
* Called whenever the current char in the frmtArr is erroneous
*
* @param interp
* - The TclInterp which called the cmdProc method .
* @param fieldSpecifier
* - The erroneous character
*/
private static final void errorBadField(Interp interp, char fieldSpecifier) throws TclException {
throw new TclException(interp, "cannot mix \"%\" and \"%n" + fieldSpecifier + "\" conversion specifiers");
}
/**
* Called whenever the a width field is used in a char ('c') format
* specifier
*
* @param interp
* - The TclInterp which called the cmdProc method .
*/
private static final void errorCharFieldWidth(Interp interp) throws TclException {
throw new TclException(interp, "field width may not be specified in %c conversion");
}
/**
* Called whenever a long conversion is invalid specifier
*
* @param interp
* - The TclInterp which called the cmdProc method .
*/
private static final void errorLonger(Interp interp, char ch) throws TclException {
throw new TclException(interp, "'l' modifier may not be specified in " + ch + " conversion");
}
/**
* Called whenever a set is invalid
*
* @param interp
* - The TclInterp which called the cmdProc method .
*/
private static final void errorBadSet(Interp interp) throws TclException {
throw new TclException(interp, "unmatched [ in format string");
}
/**
* Called whenever a bad conversion character is found
*
* @param interp
* - The TclInterp which called the cmdProc method .
*/
private static final void errorBadConvChar(Interp interp, char ch) throws TclException {
throw new TclException(interp, "bad scan conversion character \"" + ch + "\"");
}
/**
* Called whenever a variable is assigned multiple times
*
* @param interp
* - The TclInterp which called the cmdProc method .
*/
private static final void errorMultipleAssignments(Interp interp) throws TclException {
throw new TclException(interp, "variable is assigned by multiple \"%n$\" conversion specifiers");
}
/**
* Called whenever a variable is not assigned
*
* @param interp
* - The TclInterp which called the cmdProc method .
*/
private static final void errorNotAssigned(Interp interp) throws TclException {
throw new TclException(interp, "variable is not assigned by any conversion specifiers");
}
/**
* Encapsulates a character set such as [ab0-9]
*
*/
private static class CharSet {
/**
* True if CharSet starts with '^' indicating it has chars to be
* excluded
*/
boolean exclude = false;
/**
* List of chars in the character set
*/
String chars = null;
/**
* Ranges of chars in the character set; may be null
*/
Range[] ranges = null;
/**
* Index of the first character after the end of the charset's ']' in
* the format string passed to the constructor
*/
int endOfFormat;
/**
* Create a new CharSet
*
* @param format
* Format string which may contain other format information
* @param formatIndex
* index of first character in format after opening '[' of
* Charset
*/
CharSet(String format, int formatIndex) {
char ch;
int offset = 0;
int endIndex = 0;
ch = format.charAt(formatIndex);
offset = 1;
if (ch == '^') {
exclude = true;
formatIndex += offset;
ch = format.charAt(formatIndex);
offset = 1;
}
endIndex = formatIndex + offset;
/*
* Find the close bracket, but get past the first one
*/
if (ch == ']') {
ch = format.charAt(endIndex++);
}
int nranges = 0;
while (ch != ']' && endIndex < format.length()) {
if (ch == '-')
nranges++;
ch = format.charAt(endIndex++);
}
StringBuffer charsbuf = new StringBuffer();
if (nranges > 0) {
ranges = new Range[nranges];
} else {
ranges = null;
}
nranges = 0;
ch = format.charAt(formatIndex++);
char start = ch;
if (ch == ']' || ch == '-') {
charsbuf.append(ch);
ch = format.charAt(formatIndex++);
}
while (ch != ']') {
char nextChar = (formatIndex < format.length()) ? format.charAt(formatIndex) : 0;
if (nextChar == '-') {
/*
* This may be first char of a range, so don't add it yet
*/
start = ch;
} else if (ch == '-') {
/*
* Check to see if this is the last character in the set, in
* which case it is not a range and we should add the
* previous character as well as the dash.
*/
if (nextChar == ']') {
charsbuf.append(start);
charsbuf.append(ch);
} else {
ch = format.charAt(formatIndex++);
ranges[nranges] = new Range(start, ch);
nranges++;
}
} else {
charsbuf.append(ch);
}
ch = format.charAt(formatIndex++);
}
endOfFormat = formatIndex;
chars = charsbuf.toString();
}
/**
* @return the next character to continue processing from in the format
* string
*/
int getEndOfFormat() {
return endOfFormat;
}
/**
*
* @param ch
* character to test
* @return true if a character is included in the character set
*/
private boolean charInSet(char ch) {
boolean match = false;
if (chars.indexOf(ch) >= 0) {
match = true;
} else if (ranges != null) {
for (int i = 0; i < ranges.length; i++) {
if (ranges[i] != null && ranges[i].isInRange(ch)) {
match = true;
break;
}
}
}
return exclude ? !match : match;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append('[');
if (exclude)
sb.append('^');
if (chars != null)
sb.append(chars);
if (ranges != null) {
for (Range r : ranges) {
if (r != null)
sb.append(r.start).append('-').append(r.end);
}
}
sb.append(']');
return sb.toString();
}
}
/**
* Represents a range of characters, such as [a-z]
*
*/
private static class Range {
char start;
char end;
/**
* Create a new Range of characters
*
* @param a
* one character in range
* @param b
* other character in range
*/
Range(char a, char b) {
if (a < b) {
start = a;
end = b;
} else {
start = b;
end = a;
}
}
/**
* Test if a character is within the range of this Range
*
* @param c
* character to test
* @return true if character is inclusively within this Range
*/
final boolean isInRange(char c) {
return (c >= start && c <= end);
}
}
}
|
Java
|
UTF-8
| 5,989
| 2.984375
| 3
|
[] |
no_license
|
package controllers;
import java.util.LinkedList;
import java.util.List;
import models.Mate;
import models.MatePostTable;
import models.Seeker;
import models.SeekerPostTable;
import models.User;
import play.mvc.Controller;
public class ProfileController extends Controller {
/*
* This function maintains the profile of mate and seeker. It loads the mate and seeker in their
* mate/seeker table then math with the user table to fetch the data and show it in the mate/seeker
* details.
*
* Applied/Requested events
* Open Seeker events will be kept in a List of SeekerPosts called openedEvents
* Close Seeker events will be kept in a List of SeekerPosts called closedEvents
* Complete Seeker events will be kept in a List of SeekerPosts called completedEvents
*/
public static void profileView(String id) {
System.out.println("User id: " + id);
/*
* if userType is seeker then this condition will be true
*/
User user = User.findById(Long.parseLong(id));
System.out.println("FOUND IN PROFILE: "+user.email);
if (user.type.equalsIgnoreCase("seeker")) {
Seeker seeker = Seeker.find("userSeeker_id", Long.parseLong(id)).first();
System.out.println(seeker.id + " " + seeker.userSeeker.email);
//It will fetch the user data through the user and seeker relationship
User userseeker = seeker.userSeeker;
//It will fetch all the posts given by the seeker(user)
List<SeekerPostTable> postsRequestedforHelp = seeker.posts;
//Declaration and initialization of open,close,completed Events List
List<SeekerPostTable> completedEvents = new LinkedList<>();
List<SeekerPostTable> closedEvents = new LinkedList<>();
List<SeekerPostTable> openedEvents = new LinkedList<>();
//assigning the events to the separate List which have been already created.
for (SeekerPostTable seekerpostIteraotr : postsRequestedforHelp) {
if (seekerpostIteraotr.status.equalsIgnoreCase("open")) {
openedEvents.add(seekerpostIteraotr);
}
if (seekerpostIteraotr.status.equalsIgnoreCase("close")) {
closedEvents.add(seekerpostIteraotr);
}
if (seekerpostIteraotr.status.equalsIgnoreCase("complete")) {
completedEvents.add(seekerpostIteraotr);
}
}
//It will fetch all the posts posted by mate(user)
List<MatePostTable> postsAppliedtoGetHelp = seeker.postsAppliedforHelp;
//Declaration and initialization of open,close,completed Events List opened by mate
List<MatePostTable> completedEventsofMatePost = new LinkedList<>();
List<MatePostTable> closedEventsofMatePost = new LinkedList<>();
List<MatePostTable> openedEventsofMatePost = new LinkedList<>();
//assigning the events to the separate List which have been already created.
for (MatePostTable matepostIterator : postsAppliedtoGetHelp) {
if (matepostIterator.status.equalsIgnoreCase("open")) {
openedEventsofMatePost.add(matepostIterator);
}
if (matepostIterator.status.equalsIgnoreCase("close")) {
closedEventsofMatePost.add(matepostIterator);
}
if (matepostIterator.status.equalsIgnoreCase("complete")) {
completedEventsofMatePost.add(matepostIterator);
}
}
//Rendering the seeker data, its details and its events
render(user, userseeker, openedEvents, closedEvents, completedEvents, openedEventsofMatePost,
closedEventsofMatePost, completedEventsofMatePost);
}
/*
* if userType is mate then this condition will be true
*/
if (user.type.equalsIgnoreCase("mate")) {
Mate mate = Mate.find("userMate_id", Long.parseLong(id)).first();
System.out.println(mate.id + " " + mate.userMate.email);
//It will fetch the user data through the user and mate relationship
User usermate = mate.userMate;
//It will fetch all the posts given by the mate(user)
List<SeekerPostTable> postsMateAppliedtoHelp = mate.postsWantTohelp;
//Declaration and initialization of open,close,completed Events List
List<SeekerPostTable> completedEvents = new LinkedList<>();
List<SeekerPostTable> closedEvents = new LinkedList<>();
List<SeekerPostTable> openedEvents = new LinkedList<>();
//assigning the events to the separate List which have been already created.
for (SeekerPostTable seekerpostIteraotr : postsMateAppliedtoHelp) {
if (seekerpostIteraotr.status.equalsIgnoreCase("open")) {
openedEvents.add(seekerpostIteraotr);
}
if (seekerpostIteraotr.status.equalsIgnoreCase("close")) {
closedEvents.add(seekerpostIteraotr);
}
if (seekerpostIteraotr.status.equalsIgnoreCase("complete")) {
completedEvents.add(seekerpostIteraotr);
}
}
//It will fetch all the posts posted by mate(user)
List<MatePostTable> postsAppliedtoGetHelp = mate.posts;
//Declaration and initialization of open,close,completed Events List opened by mate
List<MatePostTable> completedEventsofMatePost = new LinkedList<>();
List<MatePostTable> closedEventsofMatePost = new LinkedList<>();
List<MatePostTable> openedEventsofMatePost = new LinkedList<>();
//assigning the events to the separate List which have been already created.
for (MatePostTable matepostIterator : postsAppliedtoGetHelp) {
if (matepostIterator.status.equalsIgnoreCase("open")) {
openedEventsofMatePost.add(matepostIterator);
}
if (matepostIterator.status.equalsIgnoreCase("close")) {
closedEventsofMatePost.add(matepostIterator);
}
if (matepostIterator.status.equalsIgnoreCase("complete")) {
completedEventsofMatePost.add(matepostIterator);
}
}
// System.out.println(postsMateAppliedtoHelp.get(0).matesWantToHelp.get(0).userMate.firstName);
// System.out.println(postsMateAppliedtoHelp.get(0).matesWantToHelp.get(1).userMate.firstName);
render(user, usermate, openedEvents, closedEvents, completedEvents, openedEventsofMatePost,
closedEventsofMatePost, completedEventsofMatePost);
}
}
}
|
C++
|
UTF-8
| 871
| 3.921875
| 4
|
[] |
no_license
|
#include <iostream>
#include <string>
using namespace std;
/**
Chapter 1
Palindrome Permutation: Given a string, write a function to check if it is a permutation of a palindrome. A palindrome is a word or phrase that is the same forwards and backwards. A permutation
is a rearrangement of letters. The palindrome does not need to be limited to just dictionary words.
EXAMPLE
Input: Tac t Coa
Output: Tru e (permutations : "tac o cat" , "atc o eta" , etc. )
**/
bool permutation(string s, string t) {
if (s.size() != t.size()) {
return false;
}
std::sort(s.begin(), s.end());
std::sort(t.begin(), t.end());
for (int i=0; i<s.size(); i++){
if (s[i] != t[i]) {
return false;
}
}
printf("t is a permutation of s\n");
return true;
}
int main () {
string s = "hello";
string t = "olleh";
bool isIt = permutation(s,t);
return 0;
}
|
Markdown
|
UTF-8
| 9,995
| 2.84375
| 3
|
[] |
no_license
|
Putting empty filament spools to good use
============================================
**Table of Contents**
1. [Introduction](#introduction)
2. [Features](#features)
3. [Versions](#versions)
4. [Usage](#usage)
5. [Finishing off](#finishing-off)
6. [Pictures](#pictures)
Introduction
------------
3D printing has a tendency to generate many empty filament spools. I have always
kept the empty spools, hoping that I could someday put them to good use.
I recently did some research into what others do with their empty filament
spools and was delighted to see them being used for drawer storage units by
simply printing drawers that fit into the spools. I always have a shortage of
small drawers for electronic components, bolts, nuts, etc.
<img alt="Spool Drawer " src="images/IMG_20180325_113002.jpg" height="200px" />
I found many different designs on Thingiverse for spool drawers, but immediately
realized that most of these designs were for specific types of empty spools.
Besides that, they mostly only give the STL files, so you are stuck with the
sizes the author chose for her system.
Not wanting to go through them all, trying to find one that will fit my empty
spools, and also wanting options to customize the drawer sizes, I settle on a
very simplistic, but clever design by **[keynes87]** made in [OpenSCAD].
Since OpenSCAD has a very useful parametric customizer interface, which is also
available on Thingiverse for customizing things, and the fact that I love
parametric design, [keynes87]'s design was the perfect candidate to build on.
[TOC]
----
Features
--------
* Supply spool dimensions to make drawer sizing and preview easy
* Allows 2 to 5 equal sized drawers per layer
* Can have 1 or 2 layers, with different drawer heights per layer.
* Allows adjusting the drawer wall and bottom thickness
* Has an assembly preview option to get an idea of the final assembly.
* Can simulate opening one drawer for visual help, or to test clearances -
with equal sized drawers, 5 per layer is about as much as is possible
before drawers starts interfering.
* With multi layer option selected and drawers of different height, both
drawers will be drawn in print mode.
* Can generate a thin tester outline of the drawer to test fit the spool
before final print.
* Can generate templates for exact drilling of the hinge holes in the
spool. See note below.
* Color support in assembly mode.
[TOC]
----
Versions
--------
* **v1.0** - First release
* **v1.1** - Fixed bug in generating the hinge holes and add option for finger
notch instead of handle. With the changes in the hinge hole
generation, drawers created with the same parameters in v1.0 will
**not** align with v1.1 and later drawers!
* **v1.2** - Now able to export SVG/DXF templates from OpenSCAD after learning that
OpenSCAD can only do these exports from 2D objects!
[TOC]
----
Usage
-----
To easily use the customizer features, you need the latest (2018+) version of
[OpenSCAD] installed on your computer. With older versions that do not support
the customizer, you can still modify the variables in the file - they are well
commented.
Open the `.scad` file in [OpenSCAD] then start customizing the design based on
your spool holder and requirements. The general order is normally:
1. Start with the `mode` set to `assembly` (under **General parameters**) - this
allows a simulated view of the final drawer system.
![Assembly mode][assymode]
2. Enter the measured values of your spool under the **Spool dimensions**
section. **Note** that when measuring the inner height of the spool, do it at
the hub as far as possible. I've notice that the measurement on the brim is
not always the same as at the inner hub which then means your drawers does
fit very well.
![Spool Dimensions][spooldims]
3. Next set your desired base drawer dimensions in the **Drawer Base** section.
**Note** that the `drawHeight` value should be non-zero for two layers of
drawers. Making this value 0 will make a single layer of drawers the inner
height of the spool minus 1mm for clearance.
With a non-zero value, this value will be the height for the bottom layer
drawers.
![Drawer Base][drawerbase]
4. Set the number of drawers you want in the **Drawer Configuration** section.
Here you can also select or unselect _dual layers_ if `drawHeight` is not
zero.
With dual layers, you can also adjust the gap between the layers with the
`layersGap` parameter.
Here you also select whether to have a handle (original) or newer finger
notch option for access to open drawer. The default now is the finger notch
since it prints quicker and saves plastic.
![Drawer Config][drawerconf]
5. In `assembly` mode, you can simulate opening one of the drawers by adjusting
the `openAngle` value under the **Drawer Configuration** section. Here it is
also sometimes helpful to disable drawing the spool by unselecting
`showSpool` in the **General parameters** section.
![Drawer Opened][draweropen]
6. You can modify the spool and drawer colors by changing the color names based
on the names from the OpenSCAD [color] transformation options.
![Drawer Color][drawercolor]
7. To test that your drawer config fits your spool, set the mode to `tester` in
the **General parameters** section and print the drawer outline that is
generated. Fit this to your spool to make sure your settings are correct.
![Test Mode][testmode]
8. Once you are ready to generate the STLs for printing, change the mode to
`print` in the **General parameters** section. If you have dual drawer
layers, then a model for one drawer from each layer will be generated.
![Print Mode][printmode]
9. To drill holes in the exact spots for the hinges in the spool, you can
generate a template by setting the mode to one of the `template?` modes in
the **General parameters** section.:
![Template1 Mode][template1mode]
![Template2 Mode][template2mode]
![Template3 Mode][template3mode]
Templates 2 and 3 could be 3D printed if your print area is large enough and
you want a template that can be used on future spools of the same size.
Template1 you probably do not want to print.
Another option is to export the template as a DXF or SVG file, then print a
2D copy at the exact dimension on paper as a template.
In order to export as SVG/DXF, check the `tempalte2D` options under the
`General Parameters` section, and once the display has updated, **Render**
the template (press **F6**). The result will be a 2D rendition than can now
be exported as an SVG or DXF file.
[TOC]
----
Finishing off
-------------
To complete the drawer case, I used:
* M3 threaded rod for the drawer hinges, cut to the correct spool width and
fastened with M3 nuts top and bottom. These should have been M4 rods, the
spool has these ridges on the outside on exactly the point where the holes
were supposed to go, and this made it difficult to get the holes in the
exact spot even with the template. The result was that with M4 the
tolerances were too tight :-(
* Two [spool holders], from this great design by _[Sylvain Rochette]_,
customized for this specific spool. Each spool holder contains a 608ZZ
bearing.
* A piece of M8 threaded rod for the central pillar.
* A base made from scrap 18mm plywood.
I drilled an 8mm hole in the wood, then enlarged the hole to 12mm on the
underside, just deep enough for the height of an M8 nut.
I then stuck the rod through from the top with a washer and M8 nut on the
top, threaded another nut on the bottom and started tightening the top nut.
This sunk the bottom into the base. I finished of getting it snug and level
at the bottom with a few taps from a hammer.
This allows the threaded rod to be removed should I later need a longer rod
if I want to add another spool on top.
* With the rod in place, I then placed the drawer spool on the rod, marked the
circle dimension on the base and cut it out with a jig saw.
* Final assembly is:
- M8 rod screwed into the sunken M8 nut at the base bottom
- A washer and M8 nut on the top and tightened to secure the rod in place.
- Another washer on top of the M8 nut for the spool holder bearing to rest
on - not strictly required, but it mkes me feel better :-)
- The drawer spool.
- A washer on the top spool holder bearing - again, not strictly required.
- An M8 nut, or wingnut to secure the lot.
[TOC]
----
Pictures
--------
<img alt="Sample 1" src="images/IMG_20180326_061526.jpg" width="32%" /> <img alt="Sample 2" src="images/IMG_20180326_061446.jpg" width="32%" /> <img alt="Sample 3" src="images/IMG_20180325_113042.jpg" width="32%" />
<img alt="Sample 4" src="images/IMG_20180325_113220.jpg" width="32%" /> <img alt="Sample 5" src="images/IMG_20180325_112945.jpg" width="32%" />
[TOC]
----
[TOC]: /#
<!-- External links -->
[keynes87]: https://www.thingiverse.com/keynes87
[OpenSCAD]: http://www.openscad.org/
[color]: https://en.wikibooks.org/wiki/OpenSCAD_User_Manual/Transformations#color
[spool holders]: https://www.thingiverse.com/thing:596838
[Sylvain Rochette]: https://www.thingiverse.com/labidus/about
[Gimp]: https://www.gimp.org/
<!-- Image links -->
[assymode]: images/AssemblyMode.png
[spooldims]: images/SpoolDims.png
[drawerbase]: images/DrawerBase.png
[drawerconf]: images/DrawerConf.png
[drawercolor]: images/DrawerColor.png
[draweropen]: images/DrawerAngle.png "Open Drawer. Also note drawerHeight is set and dual layer is off."
[testmode]: images/TesterMode.png
[printmode]: images/PrintMode.png "This is dual layers. Single layer will generate only one drawer."
[template1mode]: images/Template1Mode.png
[template2mode]: images/Template2Mode.png
[template3mode]: images/Template3Mode.png
[gimpcropscale]: images/GimpCrop.png
|
Java
|
UTF-8
| 2,689
| 2.03125
| 2
|
[] |
no_license
|
package ddw.com.richang.adapter;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import org.xutils.x;
import java.util.List;
import ddw.com.richang.R;
import ddw.com.richang.model.RiCheckIndustry;
import ddw.com.richang.ui.everyday.ContentDetailActivity;
/**
* 专栏 (except精选)
* Created by zzp on 2016/6/21.
*/
public class CheckIndustryAdapter extends RecyclerView
.Adapter<CheckIndustryAdapter.ViewHolder> {
private Context mContext;
private List<RiCheckIndustry> mListData;
public CheckIndustryAdapter(Context context, List<RiCheckIndustry> listData) {
this.mContext = context;
this.mListData = listData;
}
@Override
public int getItemCount() {
return mListData.size();
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_comprehensive_layout,
parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
x.image().bind(holder.mImageView, mListData.get(position).getAc_poster());
holder.mTitle.setText(mListData.get(position).getAc_title());
holder.mTime.setText(mListData.get(position).getAc_time());
holder.mCardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mContext, ContentDetailActivity.class);
intent.putExtra("ac_id", mListData.get(position).getAc_id());
mContext.startActivity(intent);
}
});
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private final CardView mCardView;
private final ImageView mImageView;
private final TextView mTitle;
private final TextView mTime;
public ViewHolder(View itemView) {
super(itemView);
mCardView = (CardView) itemView.findViewById(R.id.comprehensive_cardView);
mTime = (TextView) itemView.findViewById(R.id.comprehensive_txt_time);
mImageView = (ImageView) itemView.findViewById(R.id.comprehensive_img_poster);
mTitle = (TextView) itemView.findViewById(R.id.comprehensive_txt_title);
}
}
}
|
C++
|
UTF-8
| 2,102
| 3.140625
| 3
|
[
"MIT"
] |
permissive
|
#pragma once
#include "ec3/graphics/geometry/static-geometry.h"
namespace ec
{
/**
* \brief Kind of static geometry that represents a cylinder.
*/
class CylinderGeometry : public StaticGeometry
{
public:
/**
* \brief CylinderGeometry constructor.
* \param radius Top and bottom circle radii.
* \param height The height of the cylinder.
* \param latitude Number of rows.
* \param longitude Number of columns.
*/
explicit CylinderGeometry(float radius = 0.5f,
float height = 1.0f,
int latitude = 2,
int longitude = 20);
~CylinderGeometry();
/**
* \brief Change the dimensions of the cylinder.
* \param radius Top and bottom circle radii.
* \param height The height of the cylinder.
* \param latitude Number of rows.
* \param longitude Number of columns.
*/
void resize(float radius,
float height,
int latitude,
int longitude);
/**
* \brief Get the radius of top/bottom shape
* \return The radius
*/
float getRadius() const;
/**
* \brief Get the vertical dimension.
* \return The height.
*/
float getHeight() const;
/**
* \brief Get the number of circles around the y-axis.
* \return The latitude.
*/
int getLatitude() const;
/**
* \brief Get resolution of top/bottom circle
* (number of vertices per circle).
* \return The longitude.
*/
int getLongitude() const;
private:
/**
* \brief Initialize the cylinder geometry data.
* \param radius Top and bottom circle radii.
* \param height The height of the cylinder.
* \param latitude Number of rows.
* \param longitude Number of columns.
*/
void init(float radius = 0.5f,
float height = 1.0f,
int latitude = 15,
int longitude = 15);
/**
* \brief Initialize vertices and texture coordinates.
*/
void initVerticesAndTexCoords();
/**
* \brief Initialize indices.
*/
void initIndices();
float m_radius;
float m_height;
int m_latitude;
int m_longitude;
};
}
|
TypeScript
|
UTF-8
| 3,869
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
module Fayde.WebGL {
import ShapeArrangePipeDef = minerva.shapes.shape.arrange.ShapeArrangePipeDef;
enum LoadStatus {
NotLoaded = 0,
Loaded = 1,
LoadFailed = 2,
Loading = 3,
}
export class ShaderBase extends DependencyObject implements IShader {
static SourceProperty = DependencyProperty.Register("Source", () => String, ShaderBase, undefined, (d: ShaderBase, args) => d.OnSourceChanged(args.OldValue, args.NewValue));
static UriProperty = DependencyProperty.Register("Uri", () => Uri, ShaderBase, undefined, (d: ShaderBase, args) => d.OnUriChanged(args.OldValue, args.NewValue));
static IsLoadedProperty = DependencyProperty.Register("IsLoaded", () => Boolean, ShaderBase, false);
Source: string;
Uri: Uri;
IsLoaded: boolean;
protected $shader: WebGLShader = null;
private $loadStatus = LoadStatus.NotLoaded;
private $loadErr = null;
private $compiled = false;
protected OnSourceChanged(oldSource: string, newSource: string) {
this.$compiled = false;
if (this.$loadStatus !== LoadStatus.Loading) {
this.SetCurrentValue(ShaderBase.UriProperty, undefined);
}
if (!newSource) {
this.$loadStatus = LoadStatus.NotLoaded;
this.SetCurrentValue(ShaderBase.IsLoadedProperty, false);
} else {
this.$loadStatus = LoadStatus.Loaded;
this.SetCurrentValue(ShaderBase.IsLoadedProperty, true);
}
}
protected OnUriChanged(oldUri: Uri, newUri: Uri) {
this.$compiled = false;
if (!newUri)
return;
this.SetCurrentValue(ShaderBase.SourceProperty, undefined);
}
load(forceLoad?: boolean): Promise<IShader> {
if (forceLoad === true)
this.SetCurrentValue(ShaderBase.SourceProperty, undefined);
if (this.$loadStatus === LoadStatus.Loaded)
return Promise.resolve(this);
if (this.$loadStatus === LoadStatus.LoadFailed)
return Promise.reject<IShader>(this.$loadErr);
var uri = this.Uri;
if (Uri.isNullOrEmpty(uri))
return Promise.reject<IShader>("Cannot load shader if no Uri is specified.");
this.$loadStatus = LoadStatus.Loading;
this.$loadErr = null;
return new Promise<IShader>((resolve, reject) => {
(<any>require)(['text!' + this.Uri], (src) => {
this.SetCurrentValue(ShaderBase.SourceProperty, src);
resolve(this);
}, (err) => {
this.$loadStatus = LoadStatus.LoadFailed;
reject(this.$loadErr = err);
});
});
}
compile(gl: WebGLRenderingContext): boolean {
if (!!this.$compiled)
return true;
var src = this.Source;
if (!src)
return false;
var shader = this.$shader = gl.createShader(this.getType(gl));
gl.shaderSource(shader, src);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
console.error("An error occurred compiling the shaders.", gl.getShaderInfoLog(shader));
throw new Error("An error occurred compiling the shaders.");
}
this.$compiled = true;
return true;
}
use(gl: WebGLRenderingContext, program: WebGLProgram) {
gl.attachShader(program, this.$shader);
}
protected getType(gl: WebGLRenderingContext): number {
return -1;
}
}
Fayde.Markup.Content(ShaderBase, ShaderBase.SourceProperty);
}
|
Python
|
UTF-8
| 21,306
| 2.8125
| 3
|
[
"Apache-2.0"
] |
permissive
|
import festim
import fenics as f
import pytest
def add_functions(trap, V, id=1):
trap.solution = f.Function(V, name="c_t_{}".format(id))
trap.previous_solution = f.Function(V, name="c_t_n_{}".format(id))
trap.test_function = f.TestFunction(V)
def test_error_wrong_type_material():
"""Checks that an error is raised when the wrong type is given to
materials
"""
msg = "Accepted types for materials are str or festim.Material"
with pytest.raises(TypeError, match=msg):
festim.Trap(1, 1, 1, 1, materials=True, density=1)
with pytest.raises(TypeError, match=msg):
festim.Trap(1, 1, 1, 1, materials=[True, "mat_name"], density=1)
with pytest.raises(TypeError, match=msg):
festim.Trap(1, 1, 1, 1, materials=1, density=1)
with pytest.raises(TypeError, match=msg):
festim.Trap(1, 1, 1, 1, materials=[1, 2], density=1)
def test_error_if_duplicate_material():
mat1 = festim.Material(1, D_0=1, E_D=0, name="name1")
mat2 = festim.Material(2, D_0=1, E_D=0, name="name2")
materials = festim.Materials([mat1, mat2])
with pytest.raises(ValueError, match="Duplicate materials in trap"):
festim.Trap(1, 1, 1, 1, [mat1, mat1], 1).make_materials(materials)
with pytest.raises(ValueError, match="Duplicate materials in trap"):
festim.Trap(1, 1, 1, 1, ["name1", "name1", mat2], 1).make_materials(materials)
with pytest.raises(ValueError, match="Duplicate materials in trap"):
festim.Trap(1, 1, 1, 1, ["name1", mat1, mat1], 1).make_materials(materials)
with pytest.raises(ValueError, match="Duplicate materials in trap"):
festim.Trap(1, 1, 1, 1, ["name2", mat2], 1).make_materials(materials)
with pytest.raises(ValueError, match="Duplicate materials in trap"):
festim.Trap(1, 1, 1, 1, [mat2, mat2], 1).make_materials(materials)
with pytest.raises(ValueError, match="Duplicate materials in trap"):
festim.Trap(1, 1, 1, 1, ["name1", mat1], 1).make_materials(materials)
class TestCreateTrappingForm:
mesh = f.UnitIntervalMesh(10)
V = f.FunctionSpace(mesh, "P", 1)
my_mobile = festim.Mobile()
my_mobile.solution = f.Function(V, name="c_m")
my_mobile.previous_solution = f.Function(V, name="c_m_n")
my_mobile.test_function = f.TestFunction(V)
my_temp = festim.Temperature(value=100)
my_temp.T = f.interpolate(f.Constant(100), V)
my_temp.T_n = f.interpolate(f.Constant(100), V)
dx = f.dx()
dt = festim.Stepsize(initial_value=1)
mat1 = festim.Material(1, D_0=1, E_D=1, S_0=2, E_S=3, name="mat1")
mat2 = festim.Material(2, D_0=2, E_D=2, S_0=3, E_S=4, name="mat2")
def test_steady_state(self):
# build
my_trap = festim.Trap(
k_0=1, E_k=2, p_0=3, E_p=4, materials=self.mat1, density=1 + festim.x
)
my_trap.F = 0
my_trap.solution = f.Function(self.V, name="c_t")
my_trap.previous_solution = f.Function(self.V, name="c_t_n")
my_trap.test_function = f.TestFunction(self.V)
my_mats = festim.Materials([self.mat1])
# run
my_trap.create_trapping_form(self.my_mobile, my_mats, self.my_temp, self.dx)
# test
v = my_trap.test_function
expected_form = (
-my_trap.k_0
* f.exp(-my_trap.E_k / festim.k_B / self.my_temp.T)
* self.my_mobile.solution
* (my_trap.density[0] - my_trap.solution)
* v
* self.dx(1)
)
expected_form += (
my_trap.p_0
* f.exp(-my_trap.E_p / festim.k_B / self.my_temp.T)
* my_trap.solution
* v
* self.dx(1)
)
print("expected F:", expected_form)
print("produced F_trapping:", my_trap.F_trapping)
print("produced F:", my_trap.F)
assert my_trap.F.equals(expected_form)
assert my_trap.F_trapping.equals(expected_form)
def test_transient(self):
# build
my_trap = festim.Trap(
k_0=1, E_k=2, p_0=3, E_p=4, materials=self.mat1, density=1 + festim.x
)
my_trap.F = 0
my_trap.solution = f.Function(self.V, name="c_t")
my_trap.previous_solution = f.Function(self.V, name="c_t_n")
my_trap.test_function = f.TestFunction(self.V)
my_mats = festim.Materials([self.mat1])
# run
my_trap.create_trapping_form(
self.my_mobile, my_mats, self.my_temp, self.dx, dt=self.dt
)
# test
v = my_trap.test_function
expected_form = (
((my_trap.solution - my_trap.previous_solution) / self.dt.value)
* my_trap.test_function
* self.dx
)
expected_form += (
-my_trap.k_0
* f.exp(-my_trap.E_k / festim.k_B / self.my_temp.T)
* self.my_mobile.solution
* (my_trap.density[0] - my_trap.solution)
* v
* self.dx(1)
)
expected_form += (
my_trap.p_0
* f.exp(-my_trap.E_p / festim.k_B / self.my_temp.T)
* my_trap.solution
* v
* self.dx(1)
)
print("expected F:", expected_form)
print("produced F_trapping:", my_trap.F_trapping)
print("produced F:", my_trap.F)
assert my_trap.F.equals(expected_form)
assert my_trap.F_trapping.equals(expected_form)
def test_chemical_potential(self):
# build
my_trap = festim.Trap(
k_0=1, E_k=2, p_0=3, E_p=4, materials=self.mat1, density=1 + festim.x
)
my_trap.F = 0
my_trap.solution = f.Function(self.V, name="c_t")
my_trap.previous_solution = f.Function(self.V, name="c_t_n")
my_trap.test_function = f.TestFunction(self.V)
my_mats = festim.Materials([self.mat1])
mobile = festim.Theta()
mobile.solution = f.Function(self.V, name="theta_m")
mobile.previous_solution = f.Function(self.V, name="theta_m_n")
mobile.test_function = f.TestFunction(self.V)
# run
my_trap.create_trapping_form(mobile, my_mats, self.my_temp, self.dx)
# test
v = my_trap.test_function
S = self.mat1.S_0 * f.exp(-self.mat1.E_S / festim.k_B / self.my_temp.T)
c_0 = mobile.solution * S
expected_form = (
-my_trap.k_0
* f.exp(-my_trap.E_k / festim.k_B / self.my_temp.T)
* c_0
* (my_trap.density[0] - my_trap.solution)
* v
* self.dx(1)
)
expected_form += (
my_trap.p_0
* f.exp(-my_trap.E_p / festim.k_B / self.my_temp.T)
* my_trap.solution
* v
* self.dx(1)
)
print("expected F:")
print(expected_form)
print("produced F_trapping:")
print(my_trap.F_trapping)
print("produced F:")
print(my_trap.F)
assert my_trap.F.equals(expected_form)
assert my_trap.F_trapping.equals(expected_form)
def test_2_materials(self):
# build
my_trap = festim.Trap(
k_0=1,
E_k=2,
p_0=3,
E_p=4,
materials=[self.mat1, self.mat2],
density=1 + festim.x,
)
my_trap.F = 0
my_trap.solution = f.Function(self.V, name="c_t")
my_trap.previous_solution = f.Function(self.V, name="c_t_n")
my_trap.test_function = f.TestFunction(self.V)
my_mats = festim.Materials([self.mat1, self.mat2])
# run
my_trap.create_trapping_form(self.my_mobile, my_mats, self.my_temp, self.dx)
# test
v = my_trap.test_function
expected_form = 0
for mat in my_trap.materials:
expected_form += (
-my_trap.k_0
* f.exp(-my_trap.E_k / festim.k_B / self.my_temp.T)
* self.my_mobile.solution
* (my_trap.density[0] - my_trap.solution)
* v
* self.dx(mat.id)
)
expected_form += (
my_trap.p_0
* f.exp(-my_trap.E_p / festim.k_B / self.my_temp.T)
* my_trap.solution
* v
* self.dx(mat.id)
)
print("expected F:", expected_form)
print("produced F_trapping:", my_trap.F_trapping)
print("produced F:", my_trap.F)
assert my_trap.F.equals(expected_form)
assert my_trap.F_trapping.equals(expected_form)
def test_multi_parameters_trap(self):
# build
my_trap = festim.Trap(
k_0=[1, 2],
E_k=[2, 2],
p_0=[3, 2],
E_p=[4, 2],
materials=[self.mat1, self.mat2],
density=[1 + festim.x, 1 + festim.t],
)
my_trap.sources = [festim.Source(2 + festim.x + festim.t, volume=1, field="1")]
my_trap.F = 0
add_functions(my_trap, self.V, id=1)
my_mats = festim.Materials([self.mat1, self.mat2])
# run
my_trap.create_trapping_form(self.my_mobile, my_mats, self.my_temp, self.dx)
# test
v = my_trap.test_function
expected_form = 0
for i in range(2):
expected_form += (
-my_trap.k_0[i]
* f.exp(-my_trap.E_k[i] / festim.k_B / self.my_temp.T)
* self.my_mobile.solution
* (my_trap.density[i] - my_trap.solution)
* v
* self.dx(my_trap.materials[i].id)
)
expected_form += (
my_trap.p_0[i]
* f.exp(-my_trap.E_p[i] / festim.k_B / self.my_temp.T)
* my_trap.solution
* v
* self.dx(my_trap.materials[i].id)
)
print("expected F:", expected_form)
print("produced F_trapping:", my_trap.F_trapping)
print("produced F:", my_trap.F)
assert my_trap.F.equals(expected_form)
assert my_trap.F_trapping.equals(expected_form)
def test_steady_state_trap_not_defined_everywhere(self):
# build
my_trap = festim.Trap(
k_0=1, E_k=2, p_0=3, E_p=4, materials=self.mat1, density=1 + festim.x
)
my_trap.sources = [festim.Source(2 + festim.x + festim.t, volume=1, field="1")]
my_trap.F = 0
add_functions(my_trap, self.V, id=1)
my_mats = festim.Materials([self.mat1, self.mat2])
# run
my_trap.create_trapping_form(self.my_mobile, my_mats, self.my_temp, self.dx)
# test
v = my_trap.test_function
expected_form = 0
expected_form += (
-my_trap.k_0
* f.exp(-my_trap.E_k / festim.k_B / self.my_temp.T)
* self.my_mobile.solution
* (my_trap.density[0] - my_trap.solution)
* v
* self.dx(self.mat1.id)
)
expected_form += (
my_trap.p_0
* f.exp(-my_trap.E_p / festim.k_B / self.my_temp.T)
* my_trap.solution
* v
* self.dx(self.mat1.id)
)
expected_form += my_trap.solution * v * self.dx(self.mat2.id)
print("expected F:", expected_form)
print("produced F_trapping:", my_trap.F_trapping)
print("produced F:", my_trap.F)
assert my_trap.F.equals(expected_form)
assert my_trap.F_trapping.equals(expected_form)
def test_expression_as_density(self):
"""Test that create_trapping_form creates the correct formulation when
a fenics.Expression is given as density
"""
# build
density = f.Expression("2 + x[0]", degree=2)
my_trap = festim.Trap(
k_0=1, E_k=2, p_0=3, E_p=4, materials=self.mat1, density=density
)
my_trap.F = 0
add_functions(my_trap, self.V, id=1)
my_mats = festim.Materials([self.mat1])
# run
my_trap.create_trapping_form(self.my_mobile, my_mats, self.my_temp, self.dx)
# test
v = my_trap.test_function
k = my_trap.k_0 * f.exp(-my_trap.E_k / festim.k_B / self.my_temp.T)
p = my_trap.p_0 * f.exp(-my_trap.E_p / festim.k_B / self.my_temp.T)
expected_form = (
-k
* self.my_mobile.solution
* (my_trap.density[0] - my_trap.solution)
* v
* self.dx(1)
)
expected_form += p * my_trap.solution * v * self.dx(1)
print("expected F:", expected_form)
print("produced F_trapping:", my_trap.F_trapping)
print("produced F:", my_trap.F)
assert my_trap.F.equals(expected_form)
assert my_trap.F_trapping.equals(expected_form)
def test_user_expression_as_density(self):
"""Test that create_trapping_form creates the correct formulation when
a fenics.UserExpression is given as density
"""
# build
class CustomExpression(f.UserExpression):
def eval(self, value, x):
value[0] = x
my_trap = festim.Trap(
k_0=1,
E_k=2,
p_0=3,
E_p=4,
materials=self.mat1,
density=CustomExpression(),
)
my_trap.F = 0
add_functions(my_trap, self.V, id=1)
my_mats = festim.Materials([self.mat1])
# run
my_trap.create_trapping_form(self.my_mobile, my_mats, self.my_temp, self.dx)
# test
v = my_trap.test_function
k = my_trap.k_0 * f.exp(-my_trap.E_k / festim.k_B / self.my_temp.T)
p = my_trap.p_0 * f.exp(-my_trap.E_p / festim.k_B / self.my_temp.T)
expected_form = (
-k
* self.my_mobile.solution
* (my_trap.density[0] - my_trap.solution)
* v
* self.dx(1)
)
expected_form += p * my_trap.solution * v * self.dx(1)
print("expected F:", expected_form)
print("produced F_trapping:", my_trap.F_trapping)
print("produced F:", my_trap.F)
assert my_trap.F.equals(expected_form)
assert my_trap.F_trapping.equals(expected_form)
def test_with_trap_names(self):
my_trap = festim.Trap(
k_0=1,
E_k=2,
p_0=3,
E_p=4,
materials=["mat1"],
density=1,
)
my_trap.F = 0
add_functions(my_trap, self.V, id=1)
my_mats = festim.Materials([self.mat1])
# run
my_trap.create_trapping_form(self.my_mobile, my_mats, self.my_temp, self.dx)
# test
v = my_trap.test_function
k = my_trap.k_0 * f.exp(-my_trap.E_k / festim.k_B / self.my_temp.T)
p = my_trap.p_0 * f.exp(-my_trap.E_p / festim.k_B / self.my_temp.T)
expected_form = (
-k
* self.my_mobile.solution
* (my_trap.density[0] - my_trap.solution)
* v
* self.dx(1)
)
expected_form += p * my_trap.solution * v * self.dx(1)
print("expected F:", expected_form)
print("produced F_trapping:", my_trap.F_trapping)
print("produced F:", my_trap.F)
assert my_trap.F.equals(expected_form)
assert my_trap.F_trapping.equals(expected_form)
def test_2_materials_names_and_object(self):
# build
my_trap = festim.Trap(
k_0=1,
E_k=2,
p_0=3,
E_p=4,
materials=[self.mat1, "mat2"],
density=1 + festim.x,
)
my_trap.F = 0
my_trap.solution = f.Function(self.V, name="c_t")
my_trap.previous_solution = f.Function(self.V, name="c_t_n")
my_trap.test_function = f.TestFunction(self.V)
my_mats = festim.Materials([self.mat1, self.mat2])
# run
my_trap.create_trapping_form(self.my_mobile, my_mats, self.my_temp, self.dx)
# test
v = my_trap.test_function
expected_form = 0
for mat_id in [self.mat1.id, self.mat2.id]:
expected_form += (
-my_trap.k_0
* f.exp(-my_trap.E_k / festim.k_B / self.my_temp.T)
* self.my_mobile.solution
* (my_trap.density[0] - my_trap.solution)
* v
* self.dx(mat_id)
)
expected_form += (
my_trap.p_0
* f.exp(-my_trap.E_p / festim.k_B / self.my_temp.T)
* my_trap.solution
* v
* self.dx(mat_id)
)
print("expected F:", expected_form)
print("produced F_trapping:", my_trap.F_trapping)
print("produced F:", my_trap.F)
assert my_trap.F.equals(expected_form)
assert my_trap.F_trapping.equals(expected_form)
class TestCreateSourceForm:
mesh = f.UnitIntervalMesh(10)
V = f.FunctionSpace(mesh, "P", 1)
my_mobile = festim.Mobile()
my_mobile.solution = f.Function(V, name="c_m")
my_mobile.previous_solution = f.Function(V, name="c_m_n")
my_mobile.test_function = f.TestFunction(V)
my_temp = festim.Temperature(value=100)
my_temp.T = f.interpolate(f.Constant(100), V)
dx = f.dx()
dt = festim.Stepsize(initial_value=1)
mat1 = festim.Material(1, D_0=1, E_D=1, S_0=2, E_S=3)
mat2 = festim.Material(2, D_0=2, E_D=2, S_0=3, E_S=4)
def test(self):
# build
my_trap = festim.Trap(
k_0=1, E_k=2, p_0=3, E_p=4, materials=self.mat1, density=1
)
my_trap.sources = [festim.Source(2 + festim.x + festim.t, volume=1, field="1")]
my_trap.F = 0
my_trap.test_function = f.TestFunction(self.V)
# run
my_trap.create_source_form(self.dx)
# test
source = my_trap.sub_expressions[0]
v = my_trap.test_function
expected_form = -source * v * self.dx(1)
assert my_trap.F.equals(expected_form)
assert my_trap.F_source.equals(expected_form)
class TestCreateForm:
mesh = f.UnitIntervalMesh(10)
V = f.FunctionSpace(mesh, "P", 1)
my_mobile = festim.Mobile()
my_mobile.solution = f.Function(V, name="c_m")
my_mobile.previous_solution = f.Function(V, name="c_m_n")
my_mobile.test_function = f.TestFunction(V)
my_temp = festim.Temperature(value=100)
my_temp.T = f.interpolate(f.Constant(100), V)
dx = f.dx()
dt = festim.Stepsize(initial_value=1)
mat1 = festim.Material(1, D_0=1, E_D=1, S_0=2, E_S=3)
mat2 = festim.Material(2, D_0=2, E_D=2, S_0=3, E_S=4)
my_mats = festim.Materials([mat1, mat2])
def test_form_is_zero_by_default(self):
my_empty_mats = festim.Materials([])
my_trap = festim.Trap(1, 1, 1, 1, [], 1)
my_trap.create_form(self.my_mobile, my_empty_mats, self.my_temp, self.dx)
assert my_trap.F == 0
def test_1_mat_steady(self):
# build
my_trap = festim.Trap(1, 1, 1, 1, materials=self.mat1, density=1)
add_functions(my_trap, self.V, id=1)
my_trap.F = 0
my_trap.create_trapping_form(
self.my_mobile, self.my_mats, self.my_temp, self.dx
)
expected_form = my_trap.F
# run
my_trap.create_form(self.my_mobile, self.my_mats, self.my_temp, self.dx)
# test
print(my_trap.F)
print(expected_form)
assert my_trap.F.equals(expected_form)
def test_1_mat_transient(self):
# build
my_trap = festim.Trap(1, 1, 1, 1, materials=self.mat1, density=1)
add_functions(my_trap, self.V, id=1)
my_trap.F = 0
my_trap.create_trapping_form(
self.my_mobile, self.my_mats, self.my_temp, self.dx, self.dt
)
expected_form = my_trap.F
# run
my_trap.create_form(
self.my_mobile, self.my_mats, self.my_temp, self.dx, self.dt
)
# test
print(my_trap.F)
print(expected_form)
assert my_trap.F.equals(expected_form)
def test_2_mats_transient(self):
# build
my_trap = festim.Trap(1, 1, 1, 1, materials=[self.mat1, self.mat2], density=1)
add_functions(my_trap, self.V, id=1)
my_trap.F = 0
my_trap.create_trapping_form(
self.my_mobile, self.my_mats, self.my_temp, self.dx, self.dt
)
expected_form = my_trap.F
# run
my_trap.create_form(
self.my_mobile, self.my_mats, self.my_temp, self.dx, self.dt
)
# test
print(my_trap.F)
print(expected_form)
assert my_trap.F.equals(expected_form)
def test_1_mat_and_source(self):
# build
my_trap = festim.Trap(1, 1, 1, 1, materials=self.mat2, density=1)
my_trap.sources = [festim.Source(1 + festim.x + festim.y, volume=1, field="1")]
add_functions(my_trap, self.V, id=1)
my_trap.F = 0
my_trap.create_trapping_form(
self.my_mobile, self.my_mats, self.my_temp, self.dx, self.dt
)
expected_form = my_trap.F
# run
my_trap.create_form(
self.my_mobile, self.my_mats, self.my_temp, self.dx, self.dt
)
# test
expected_form += my_trap.F_source
print(my_trap.F)
print(expected_form)
assert my_trap.F.equals(expected_form)
|
Java
|
UTF-8
| 472
| 2.5
| 2
|
[] |
no_license
|
package vo;
public class SeatVO {
private String seatName,seatTf;
public SeatVO() {
super();
}
public SeatVO(String seatName, String seatTf) {
super();
this.seatName = seatName;
this.seatTf = seatTf;
}
public String getSeatName() {
return seatName;
}
public void setSeatName(String seatName) {
this.seatName = seatName;
}
public String getSeatTf() {
return seatTf;
}
public void setSeatTf(String seatTf) {
this.seatTf = seatTf;
}
}
|
Java
|
UTF-8
| 206
| 1.859375
| 2
|
[] |
no_license
|
package com.example.ferdy.birms.api;
import com.example.ferdy.birms.model.ApiBerita;
public class JSONBerita {
ApiBerita[] data;
public ApiBerita[] getDataBerita(){
return data;
}
}
|
Go
|
UTF-8
| 659
| 4.15625
| 4
|
[
"CC-BY-3.0"
] |
permissive
|
package main
import "fmt"
import "math"
// `const` declares a constant value.
const s string = "constant"
func main() {
fmt.Println(s)
// A `const` statement can appear anywhere a `var` statement can.
const n = 500000000
// Constant expressions perform arithmetic with arbitrary precision.
const d = 3e20 / n
fmt.Println(d)
// A numeric constant has no type until it's given one, such by an
// explicit cast.
fmt.Println(int64(d))
// A number can be given a type by using it in a context that requires
// one, such as a variable assignment or function call.
// For example, here `math.Sin` expects a `float64`.
fmt.Println(math.Sin(n))
}
|
Java
|
GB18030
| 4,507
| 2.078125
| 2
|
[] |
no_license
|
package com.cx.controller;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.cx.pagelist.PageInfo;
import com.cx.pojo.Flight;
import com.cx.pojo.User;
import com.cx.service.FlightService;
import com.cx.service.UserService;
@Controller
public class AppIndexController {
@Autowired
private UserService userserv;
@Autowired
private FlightService fliserv;
@RequestMapping("/login") // û¼
public String login(String email, String password, HttpServletRequest request) {
HttpSession session = request.getSession();
if (userserv.userlogin(email, password) != null) {
session.setAttribute("uname", userserv.userlogin(email, password));// û
User user = userserv.getUserByemail(email);
session.setAttribute("userid", user.getUserId());// ûID
} else {
session.setAttribute("backnews", "¼");
}
return "main/index";
}
@RequestMapping("/logout") // ûdz
public String logout(HttpServletRequest request) {
HttpSession session = request.getSession();
session.invalidate();
return "main/index";
}
@RequestMapping("/trip") // ѯƱ
public ModelAndView alladmin(HttpServletRequest request, HttpServletResponse response) {
//õ
String departure=request.getParameter("departure");
String destination=request.getParameter("destination");
String deptime=request.getParameter("deptime");
String destime=request.getParameter("destime");
String idea=request.getParameter("idea");
HttpSession session=request.getSession();
int currentPage = request.getParameter("page") == null ? 1 : Integer.parseInt(request.getParameter("page"));
int pageSize = 3;
if (currentPage <= 0) {
currentPage = 1;
}
int currentResult = (currentPage - 1) * pageSize;//ӵڼʼȡ
PageInfo page = new PageInfo();
page.setShowCount(pageSize);
page.setCurrentResult(currentResult);
List<Flight> list = new ArrayList<>();
if (idea==null) {
if (deptime!=null) {
list = fliserv.findRoundtrip(departure, destination, deptime, destime,page); // ѯƱ
}
else {
list = fliserv.findSingletrip(departure, destination, destime,page);//ѯ
}
session.setAttribute("depa",departure);
session.setAttribute("destn",destination);
session.setAttribute("dept",deptime);
session.setAttribute("destime",destime);
}
else {
if (deptime!=null) {
list = fliserv.findRoundtrip((String)session.getAttribute("depa"),
(String)session.getAttribute("destn"), (String)session.getAttribute("dept"),
(String)session.getAttribute("destime"),page); // ѯƱ
}
else {
list = fliserv.findSingletrip((String)session.getAttribute("depa"),
(String)session.getAttribute("destn"),(String)session.getAttribute("destime"),page);//ѯ
}
}
int totalCount = page.getTotalResult();//õtotal
int lastPage = 0;
if (totalCount % pageSize == 0) {
lastPage = totalCount / pageSize;
} else {
lastPage = 1 + totalCount / pageSize;//ҳ
}
System.out.println("latpage"+lastPage+"totalcount"+totalCount);
if (currentPage >= lastPage) {
currentPage = lastPage;
}
String string="<h4><a href=\""+request.getRequestURI()+"?page="+(currentPage-1)+"\"><<</a>";
StringBuffer pageStr = new StringBuffer();
pageStr.append(string);
for (int i = 1; i < lastPage+1; i++) {
if (i==currentPage) {
pageStr.append("<a href=\"#\">"+i+"</a>");
}
else {
pageStr.append("<a href=\""+request.getRequestURI()+"?page="+i+"\">"+i+"</a>");
}
}
pageStr.append("<a href=\""+request.getRequestURI()+"?page="+(currentPage+1)+"\">>></a></h4>");
// ƶͼҲlist.jsp
ModelAndView mav = new ModelAndView("main/products");
mav.addObject("list",list);
mav.addObject("page",page);
mav.addObject("pageStr", pageStr);
return mav;
}
}
|
Python
|
UTF-8
| 1,511
| 4.53125
| 5
|
[] |
no_license
|
"""
Let's learn about list comprehensions! You are given three integers x,y and z representing
the dimensions of a cuboid along with an integer n. Print a list of all possible coordinates
given by (i,j,k) on a 3D grid where the sum of i+j+k is not equal to n. Here, 0<=i<=x;0<=j<=y;
0<=k<=z. Please use list comprehensions rather than multiple loops, as a learning exercise.
Example::
x=1,y=1,z=2,n=3
All permutations of [i,j,k] are:
[[0,0,0],[0,0,1],[0,0,2],[0,1,0],[0,1,1],[0,1,2],[1,0,0],[1,0,1],[1,0,2],[1,1,0],[1,1,1],[1,1,2]]
Since, n=3, i+j+k !=3
[[0,0,0],[0,0,1],[0,0,2],[0,1,0],[0,1,1],[1,0,0],[1,0,1],[1,1,0],[1,1,2]]
"""
if __name__ == '__main__':
x = int(input("x="))
y = int(input("y="))
z = int(input("z="))
n = int(input("n="))
x_list=[x for x in range(x+1)]
y_list=[y for y in range(y+1)]
z_list=[z for z in range(z+1)]
Permutations=[[i,j,k] for i in x_list for j in y_list for k in z_list if i+j+k!=n]
print(Permutations)
"""
Alternatively,
print ([[i,j,k] for i in range(x+1) for j in range(y+1) for k in range(z+1) if i + j + k != n ])
"""
"""
>> ListOfNumbers = [ x for x in range(10) ] # List of integers from 0 to 9
>> ListOfNumbers
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print([[x, y] for x in [1, 2, 3] for y in [4, 5, 6]])
[[1, 4], [1, 5], [1, 6], [2, 4], [2, 5], [2, 6], [3, 4], [3, 5], [3, 6]]
>> ListOfThreeMultiples = [x for x in range(10) if x % 3 == 0] # Multiples of 3 below 10
>> ListOfThreeMultiples
[0, 3, 6, 9]
"""
|
Markdown
|
UTF-8
| 3,575
| 3.078125
| 3
|
[
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] |
permissive
|
# Output #
Neptune's output directory contains the following items:
| Item | Type | Description |
|---|---|---|
| candidates | directory | The directory containing signature candidates in extracted order. |
| filtered | directory | The directory containing filtered signature candidates in extracted order. |
| sorted | directory | The directory containing filtered signatures in signature-score sorted order. |
| consolidated | directory | The directory containing the consolidate signatures from multiple sorted-signature reference files. |
| database | directory | The directory containing Neptune's BLAST constructed databases. |
| aggregate.kmers | file | The *k*-mer file containing all observed k-mers. |
| receipt.txt | file | The file containing Neptune's run receipt. |
A file with the same name as each reference will be placed in each output directory (candidates, filtered, sorted), corresponding to the reference file from which it was derived.
## Candidates ##
The candidate signatures are the sequences produced from the signature extraction step. These signatures will relatively sensitive, but not necessarily specific. This is because signature extraction is done using exact *k*-mer matches. The candidate signatures are guaranteed to contain no more exact matches with any exclusion *k*-mer than specified by the `--exhits` parameter. However, there may be inexact matches with exclusion targets.
## Filtered ##
The filtering step is designed to remove signatures which are not interesting enough to warrant further investigation, because the negative component of their score is prohibitively large. The filtering step removes signatures that align sufficiently with any exclusion target. The filtered signatures are a subset of the candidate signatures.
## Sorted ##
The sorted signatures files are organized as FASTA records containing the same signatures as their filtered signatures counterparts. However, the signatures are listed in descending order by their signature score. Signatures are assigned a score corresponding to their highest-scoring BLAST alignments with all inclusion and exclusion targets, which is a sum of a positive inclusion component and a negative exclusion component. This score is maximized when all inclusion targets contain a region exactly matching the entire signature and there exists no exclusion targets that match the signature.
## Consolidated ##
The sorted signatures from all references are combined into a single "consolidated.fasta" file, located within the "consolidated" directory. Signatures are added to the consolidated signatures file in a greedy manner by selecting the next highest scoring signature available from all references. While effort is taken to prevent signatures from overlapping entirely, it is possible for consolidate signatures to have a small amount of overlap. In many circumstances, this output might be considered the final output of Neptune.
## Databases ##
The databases directory contains BLAST databases constructed from the inclusion and exclusion files.
## Aggregate k-mers ##
The aggregated *k*-mers file, aggregated.kmers, contains a list of all *k*-mers observed in the inclusion and exclusion groups. These *k*-mers are sorted and followed by two integers: the number of inclusion and exclusion targets the *k*-mer appears in, respectively.
## Run Receipt ##
The run receipt contains information about the Neptune execution. It contains a list of all the files in the inclusion and exclusion group, and the command line parameters used for the execution.
|
Python
|
UTF-8
| 617
| 3.671875
| 4
|
[
"MIT"
] |
permissive
|
import random
# Takes a number of vertices and a floating point number between 0 and 1
# and generates a weighted graph with distinct weights that has that many vertices and an edge between
# any two given vertices with the given probability
#
vertices = int(input())
edge_prob = float(input())
graph = []
edges = 0
for i in range(vertices - 1):
for j in range(i + 1 ,vertices):
if random.random() < edge_prob:
graph.append((i, j))
edges += 1
weights = list(range(1, edges + 1))
random.shuffle(weights)
for i in range(edges):
print(graph[i][0], graph[i][1], weights[i])
|
Python
|
UTF-8
| 392
| 3.984375
| 4
|
[] |
no_license
|
print("{0} is {1} years old".format("小王", 25))
print('{0:.3}'.format(1/3))
# decimal (.) precision of 3 for float
#'0.333'
print('{0:_^11}'.format('hello'))
# fill with underscores (_) with the text
#centered (^) to 11 width
#'___hello___'
print('{name} wrote {book}'.format(name='Swaroop', book='A Byte of Python'))
# keyword-based
#'Swaroop wrote A Byte of Python'
|
Markdown
|
UTF-8
| 1,183
| 3.046875
| 3
|
[] |
no_license
|
# Arcade Game Project
## Arcade Game
Arcade Game is a game where users can earn more scores as they successfully move across the board to reach the water area without colliding with any enemies (as known as the bugs) with variety of speed depending on the levels.
## Basic Functionality
In this game you have a Player and Enemies (bugs). The goal of the player is to reach the water, without colliding into any one of the enemies.
* The player can move left, right, up and down
* The enemies move at varying speeds on the paved block portion of the game board
* Once a the player collides with an enemy, the game is reset and the player moves back to the starting square
* Once the player reaches the water (i.e., the top of the game board), the game is won
## How to get this game
To play this game, navigate to https://thuctonhuyen.github.io/arcade-game/ OR open index.html after cloning/downloading this project and start playing by moving your player horizontally and/or vertically to reach the water area without colliding with the enemies to get your score incremented.
## Dependencies
* Google Font Baloo Thambi (https://fonts.googleapis.com/css?family=Baloo+Thambi)
|
C#
|
UTF-8
| 1,622
| 2.734375
| 3
|
[] |
no_license
|
using System;
using System.Collections.Immutable;
namespace MechArena
{
[Serializable()]
class Component_Position : Component
{
private int x, y;
private bool blocksMovement;
public int X { get { return this.x; } }
public int Y { get { return this.y; } }
public bool BlocksMovement { get { return this.blocksMovement; } }
public Component_Position(int x, int y, bool blocksMovement)
{
this.x = x;
this.y = y;
this.blocksMovement = blocksMovement;
}
protected override IImmutableSet<SubEntitiesSelector> _MatchingSelectors()
{
return ImmutableHashSet<SubEntitiesSelector>.Empty;
}
private void HandleMove(GameEvent_MoveSingle ev)
{
if (ev.GameArena.IsWalkableAndOpen(this.x + (int)ev.X, this.y + (int)ev.Y))
{
this.x += (int)ev.X;
this.y += (int)ev.Y;
}
ev.Completed = true;
}
protected override GameEvent _HandleEvent(GameEvent ev)
{
if (ev is GameEvent_MoveSingle)
this.HandleMove((GameEvent_MoveSingle)ev);
return ev;
}
private void HandleQueryPosition(GameQuery_Position q)
{
q.RegisterPosition(this.x, this.y, this.blocksMovement);
}
protected override GameQuery _HandleQuery(GameQuery q)
{
if (q is GameQuery_Position)
this.HandleQueryPosition((GameQuery_Position)q);
return q;
}
}
}
|
Python
|
UTF-8
| 969
| 3.265625
| 3
|
[] |
no_license
|
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
no = 0
i = 0
d = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
#jump = False
while i <= len(s)-1:
#jump=False
if i+1< len(s) and s[i]=='I' and s[i+1]=='V':
no+=4
i+=2
#jump=True
continue
if i+1< len(s) and s[i] == 'I' and s[i + 1] == 'X':
no+=9
i+=2
#jump = True
continue
if i+1< len(s) and s[i]=='X' and s[i+1]=='L':
no+=40
i+=2
#jump = True
continue
if i+1< len(s) and s[i] == 'X' and s[i + 1] == 'C':
no+=90
i+=2
#jump = True
continue
if i+1< len(s) and s[i] == 'C' and s[i + 1] == 'D':
no+=400
i+=2
#jump = True
continue
if i+1< len(s) and s[i] == 'C' and s[i + 1] == 'M':
no+=900
i+=2
#jump = True
continue
no+=d[s[i]]
i+=1
return no
if __name__=='__main__':
s = Solution()
print(s.romanToInt("MDCXCV"))
|
C++
|
UTF-8
| 1,297
| 2.859375
| 3
|
[] |
no_license
|
#include <SPI.h>
int hexDigitValue[] = {0x03, /* 0 */
0x9F, /* 1 */
0x25, /* 2 */
0x0D, /* 3 */
0x99, /* 4 */
0x49, /* 5 */
0x41, /* 6 */
0x1F, /* 7 */
0x01, /* 8 */
0x09};/* 9 */
const int slaveSelectPin = 10;
int button_number;
void button_init(){
pinMode(7, INPUT_PULLUP);
pinMode(6, INPUT_PULLUP);
pinMode(5, INPUT_PULLUP);
pinMode(4, INPUT_PULLUP);
pinMode(3, INPUT_PULLUP);
pinMode(2, INPUT_PULLUP);
pinMode(1, INPUT_PULLUP);
pinMode(0, INPUT_PULLUP);
}
void setup() {
// Инициализируем кнопки
button_init();
// Инициализируем SPI и ножку отвечающую за переход в режим хранения
pinMode(slaveSelectPin, OUTPUT);
SPI.begin();
}
void loop() {
// Считываем значение, подаваемое на кнопки в виде 8-разрядного числа
button_number = PIND;
// Передаём данные
digitalWrite(slaveSelectPin, HIGH);
SPI.transfer(hexDigitValue[button_number % 10]);
SPI.transfer(hexDigitValue[(button_number / 10) % 10]);
SPI.transfer(hexDigitValue[button_number / 100]);
digitalWrite(slaveSelectPin, LOW);
}
|
PHP
|
UTF-8
| 3,447
| 2.59375
| 3
|
[] |
no_license
|
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
//* @name profesor.php
//* @author Prof. Ing. Pablo Eduardo Hernandez
//* @Fecha: Octubre 2016
//* @Funcion: este controlador sirve para de las notas por el profesor
//* @Perfiles: Profesor
class Profesor extends CI_Controller
{
function __construct()
{
parent::__construct();
/* Me fijo si tengo un usuario valido*/
if(empty($_SESSION['id_user']))
{
$this->session->set_flashdata('flash_data','Debe estar logueado para operar ');
redirect('login');
}
/* Me fijo si el perfil del usuario corresponde con el rol que deberia ser para esta clase*/
if($_SESSION['rol'] <> "profesor")
{
redirect('home');
}
/* Standard Libraries of codeigniter are required */
$this->load->database('default');
$this->load->helper('url');
//$this->load->library('grocery_crud_categories') ;
/* ------------------ */
$this->load->library('grocery_CRUD');
}
public function notas()
{
//Para traer el ID del profesor
if(!empty($_SESSION['id_user']))
{
$sql = ("SELECT profesor_id FROM profesor WHERE `profesor_dni`={$_SESSION['username']}");
$query= $this->db->query($sql);
$row = $query->row();
if (isset($row))
{
$condicion= $row->profesor_id;
}
}
$crud = new grocery_CRUD();
$crud->set_table('materia_alumno');
$crud->set_theme('datatables');
$crud->unset_columns('profesor_id');
$crud->unset_delete();
$crud->unset_add();
$crud->unset_fields('profesor_id');
//Cambiamos algunos campos a solo lectura
$state = $crud->getState();
$state_info = $crud->getStateInfo();
if($state == 'edit')
{
$crud->field_type('carrera_id','readonly');
$crud->field_type('materia_id','readonly');
$crud->field_type('alumno_id','readonly');
$crud->field_type('fecha_final','hidden');
$crud->field_type('Final','hidden');
}
$crud->display_as("carrera_id","Carrera");
$crud->set_relation('carrera_id','carrera','carrera_nombre');
$crud->display_as("materia_id","Materia");
$crud->set_relation('materia_id','materia','materia_nombre');
$crud->display_as("alumno_id","Alumno");
$crud->set_relation('alumno_id','alumno','alumno_nombre');
$crud->set_language('spanish');
$crud->where('profesor_id =', $condicion);
$crud->display_as("1Parcial","Primer Parcial");
$crud->display_as("2Parcial","Segundo Parcial");
$crud->display_as("1Recu","Primer Recuperatorio");
$crud->display_as("2Recu","Segundo Recuperatorio");
$output = $crud->render();
$this->_example_output($output);
}
function _example_output($output = null)
{
$this->load->view('Principal.php', $output);
}
}
|
Swift
|
UTF-8
| 875
| 2.90625
| 3
|
[] |
no_license
|
class RootPresenter: RootPresenterType {
weak var controller: RootViewControllerType?
private let repository: RepositoryType
private var currentPage: Int = 1
init(repository: RepositoryType = Repository()) {
self.repository = repository
}
func getRepositories(nextPage: Bool) {
repository.requestRepositories(page: getPage(nextPage: nextPage)) { result in
switch result {
case .success(let model):
let viewModels = RootAdapter().adapt(model: model)
self.controller?.show(viewModels: viewModels)
case .failure:
self.controller?.showError()
}
}
}
private func getPage(nextPage: Bool) -> String {
if nextPage {
currentPage = currentPage + 1
}
return "\(currentPage)"
}
}
|
Python
|
UTF-8
| 584
| 2.75
| 3
|
[] |
no_license
|
from bs4 import BeautifulSoup
import re
from event import Event
html = open('schedule.txt', 'r').read()
soup = BeautifulSoup(html, 'html.parser')
schedule = []
schedule_html = soup.find_all(class_=re.compile('^seasonRowItem'))
for event in schedule_html:
attributes = []
for element in event.find_all('p'):
attributes.append(element.get_text().strip(' \t\n\r'))
schedule.append(attributes)
reference = ['Date', 'Time', 'Home or Away', 'Opponent', 'Location', 'Notes', '']
events = []
for event in schedule:
events.append(Event(event))
for event in events:
print(event)
|
Python
|
UTF-8
| 1,489
| 2.96875
| 3
|
[] |
no_license
|
import random
import math
x = [-10.0, 15.0, 30.0]
target = [ 14.0, 59.0, 86.0]
# glorot_uniform
fan_in = 1 # the number of input units in the weight tensor
fan_out = 1 # the number of output units in the weight tensor
limit = math.sqrt(6 / (fan_in + fan_out))
W1 = random.uniform(-limit, limit) # ~ [-1.73, 1.73]
B1 = 0.0
W2 = random.uniform(-limit, limit)
B2 = 0.0
def feed_forward(x):
H = x * W1 + B1
y = H * W2 + B2
return (H, y)
def calc_derivatives(x, target):
(H, y) = feed_forward(x)
dW2 = 0.0001 * -2 * (target - y) * H
dB2 = 0.0001 * -2 * (target - y) * 1
dW1 = 0.0001 * -2 * (target - y) * W2 * x
dB1 = 0.0001 * -2 * (target - y) * W2 * 1
return (dW2, dB2, dW1, dB1)
for step in range(0, 5000):
sum_of_W1_derivatives = 0
sum_of_B1_derivatives = 0
sum_of_W2_derivatives = 0
sum_of_B2_derivatives = 0
for sample in zip(x, target):
(x_sample, target_sample) = sample
(dW2, dB2, dW1, dB1) = calc_derivatives(x_sample, target_sample)
sum_of_W1_derivatives = sum_of_W1_derivatives + dW1
sum_of_B1_derivatives = sum_of_B1_derivatives + dB1
sum_of_W2_derivatives = sum_of_W2_derivatives + dW2
sum_of_B2_derivatives = sum_of_B2_derivatives + dB2
W1 = W1 - sum_of_W1_derivatives / len(x)
B1 = B1 - sum_of_B1_derivatives / len(x)
W2 = W2 - sum_of_W2_derivatives / len(x)
B2 = B2 - sum_of_B2_derivatives / len(x)
(_, answer) = feed_forward(22)
print(answer)
|
Markdown
|
UTF-8
| 2,264
| 3.859375
| 4
|
[
"MIT"
] |
permissive
|
# 1. 两数之和(Two Sum)
## 描述

## 解法分析
### 解法1
求解的关键则是 $k = target - nums[i]$, k 是否在数组 $nums$ 中,且 k 的索引不等于 i。
先将数组 $nums$ 转化为字典 $ref$,其中字典的 key 为数组 $nums$ 存储的数据, 字典的 value 为数据对应在 $nums$ 中的 index。这样只需要遍历字典 $ref$的 key,计算 $searchback = target - some_key$, 并判断 $searchback$ 是否是不等于 some_key 的 key。
空间复杂度: 借用了字典来存储 nums, *O(N)*
平均时间复杂度:*O(N/2)*
最坏时间复杂度: *O(N)* 因为有可能遍历到字典最后两个数据才能得出结果。
```Python
# 1 two sum 两数之和
__author__ = "Yang Xuan (jumpthepig@gmail.com)"
def twoSum(nums, target):
# Change list into dictionary.
# dictionary_keys are values of list nums
# dictionary_value are indexes of list nums
ref = {value: index for (index, value) in enumerate(nums)}
for index, value in enumerate(nums):
searchback = ref.get(target - value, None)
if searchback and searchback != index:
return [index, searchback]
continue
args = ([2, 7, 11, 15], 9)
assert twoSum(*args) == [0, 1]
```
```c++
vector<int> twoSum(vector<int>& nums, int target) {
std::map<int,int> dictionary;
std::vector<int> result;
for (int i = 0; i < nums.size(); ++i) {
dictionary[nums[i]] = i;
}
for (int j = 0; j < nums.size(); ++j){
int tmp = target - nums[j];
std::map<int, int>::iterator tmp_ptr = dictionary.find(tmp);
if (tmp_ptr != dictionary.end() && tmp_ptr->second != j) {
result.push_back(j);
result.push_back(tmp_ptr->second);
break;
}
}
return result;
}
```
### 解法2 暴力法
时间复杂度 $O(N^2)$
```c++
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
for (int i = 0; i < nums.size(); ++i) {
for (int j = i + 1; j < nums.size(); ++j) {
if ( nums[i] + nums[j] == target ) {
result.push_back(i);
result.push_back(j);
return result;
}
}
}
return result;
}
```
|
Java
|
UTF-8
| 4,809
| 2.234375
| 2
|
[] |
no_license
|
package com.focus.test1android;
/**
* Created by AdrianHsu on 15/8/3.
*/
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.facebook.AccessToken;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.HttpMethod;
import com.facebook.login.widget.ProfilePictureView;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseRelation;
import com.parse.ParseUser;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Arrays;
import java.util.List;
public class AddFriendActivity extends Activity {
static final String TAG = "AddFriendActivity";
private static ProfilePictureView userProfilePictureView;
private static TextView userNameView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.friend);
showFriendList();
}
public void showFriendList() {
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/me/friends",
null,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
/* handle the result */
Log.v(TAG, response.toString());
JSONObject json = response.getJSONObject();
try {
JSONArray jarray = json.getJSONArray("data");
Log.v(TAG, jarray.toString());
userProfilePictureView = (ProfilePictureView) findViewById(R.id.userProfilePicture);
userNameView = (TextView) findViewById(R.id.userName);
userProfilePictureView.setProfileId(jarray.getJSONObject(0).getString("id"));
userNameView.setText(jarray.getJSONObject(0).getString("name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
).executeAsync();
}
// UserDetailsActivity with take this function, thus makes it static
public static void registerFriendList() {
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/me/friends",
null,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
/* handle the result */
Log.v(TAG, response.toString());
JSONObject json = response.getJSONObject();
try {
// jarray is with data include "facebookId" and "name"
JSONArray jarray = json.getJSONArray("data");
for(int i = 0 ; i < jarray.length(); i++) {
final ParseObject myFriendRelation = new ParseObject("FriendRelation");
Log.v(TAG, "friend " + i + ": " + jarray.getJSONObject(i));
ParseUser currentUser = ParseUser.getCurrentUser();
long tmpFacebookId = jarray.getJSONObject(i).getLong("id");
String userObjectId = currentUser.getObjectId();
// self info of this friend-and-I relationship
myFriendRelation.put("user", currentUser);
myFriendRelation.put("profile", jarray.getJSONObject(i));
myFriendRelation.put("facebookId", tmpFacebookId);
myFriendRelation.put("userObjectId", userObjectId);
// take facebookId as key to get friend info
ParseQuery<ParseObject> query = ParseQuery.getQuery("_User");
query.whereEqualTo("facebookId", tmpFacebookId);
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> friend, ParseException e) {
if (e == null) {
// prevent from null pointer exception
if (friend.size() != 0) {
Log.i(TAG, friend.get(0).getString("installationId"));
// choose friend.get(0) since there's only one friend
// matches the given facebookId
myFriendRelation.put("installationId",
friend.get(0).getString("installationId"));
myFriendRelation.saveInBackground();
Log.i(TAG, "done relation");
} else {
Log.d(TAG, "Error: There is no friend of you with this facebookId");
}
} else {
Log.d(TAG, "Error: " + e.getMessage());
}
}
});
}
ParseUser.getCurrentUser().saveInBackground();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
).executeAsync();
}
}
|
Python
|
UTF-8
| 8,645
| 3.109375
| 3
|
[] |
no_license
|
import sys
class ConvertDatatypeDict(dict):
"""
A dict that converts values for certain keys.
The keys for which the corresponding value should be converted can be
specified via the attributes self.decs and self.hexs.
The conversion must be done explicitly via convert_datatypes(self)
self.decs: A list of keys for which the values are interpreted as
*decimal* integer literals.
self.hexs: A list of keys for which the values are interpreted as
*hexadecimal* integer literals.
The value -1 represents an unknown/invalid value for every key in self.decs
and self.hexs.
"""
decs = []
hexs = []
def convert_datatypes(self):
"""
Converts datatypes for the keys specified in self.decs and self.hexs
"""
self._convert2int(self.decs, 10)
self._convert2int(self.hexs, 16)
def _convert2int(self, keys, base=10, err_val=-1):
for k in keys:
if self.get(k):
try:
self[k] = int(self[k], base)
except ValueError:
self[k] = err_val
class TincNode(object):
"""
Represents a node of a tinc VPN.
"""
def __init__(self):
"""
Initialize TincNode object
"""
self.name = None
"""Node name"""
self.network = []
"""List of networks owned by the node"""
self.peer_info = {}
"""Dictionary with further information about that node. See PeerInfo"""
def __repr__(self):
return "%s %s" % (self.name, self.network)
def add_network(self, network):
"""
Adds a network to the list of networks if it's not in the list already.
:param network: Network to add
"""
if network not in self.network:
self.network.append(network)
class PeerInfo(ConvertDatatypeDict):
"""
Represents information about a node of a tinc VPN.
node, id, host, port, cipher, digest, maclength, compression, options,
status_int, nexthop, via, distance, pmtu, minmtu, maxmtu, last_state_change
"""
decs = ['port', 'distance', 'pmtu', 'minmtu', 'maxmtu',
'last_state_change']
hexs = ['cipher', 'digest', 'maclength', 'compression', 'options',
'status_int']
class TincEdge(ConvertDatatypeDict):
"""
Represents an edge of a tinc VPN.
from, to, host, local_host, local_port, options, weight, avg_rtt
Depending on the protocol version of tincd avg_rtt may not be defined.
"""
decs = ['port', 'local_port', 'weight', 'avg_rtt']
hexs = ['options']
class TincConnection(ConvertDatatypeDict):
"""
Represents a meta connection of a tinc VPN.
node, host, port, options, socket, status_int
"""
decs = ['port']
hexs = ['options', 'status_int']
class TincInfo(object):
"""
TincInfo parses data retrieved from tincd's control socket.
"""
def __init__(self):
"""
Initialize TincInfo object
"""
self.connections = []
self.nodes = {}
self.edges = []
# parse
def parse_networks(self, data=None):
"""
Parse all known subnets in the VPN and store them in the network list
of the corresponding node.
If parse_nodes() was executed before peer_info is also present.
:param data: Data to parse. If not specified ValueError will be raised.
:return: A dictionary of nodes
"""
if not data:
raise ValueError('No data to parse networks given.')
for line in [l for l in data.splitlines() if len(l.split(" ")[2:])]:
i = line.split(" ")[2:]
try:
net, node_name = i
except ValueError as ve:
print('Cannot parse line [{}]'.format(line))
raise ve
node = self.nodes.setdefault(node_name, TincNode())
node.name = node_name
node.add_network(net)
return self.nodes
def parse_edges(self, data=None):
"""
Parse all known connections in the VPN and store the information
in a list of edges. An edge holds the following information:
from, to, host, local_host, local_port, options, weight, avg_rtt
Depending on the protocol version of tincd avg_rtt may not be defined.
:param data: Data to parse. If not specified ValueError will be raised.
:return: A list of edges
"""
if not data:
raise ValueError('No data to parse edges given.')
# from, to, host, port, local_host, local_port, &options, &weight
purpose = ["from", "to", "host", "_a", "port", "local_host",
"_b", "local_port", "options", "weight", "avg_rtt"]
# edges = []
# for i in [z for z in answer.splitlines() if len(z.split(" ")[2:]) > 0]:
# edges.append(self.meta_parse(i.split(" ")[2:], purpose, TincEdge()))
self.edges = map(lambda i : self.meta_parse(i.split(" ")[2:], purpose, TincEdge()),
[z for z in data.splitlines() if len(z.split(" ")[2:])])
return self.edges
def parse_connections(self, data=None):
"""
Parse all meta connections and store information in a list.
A connection holds the following information:
node, host, port, options, socket, status_int
:param data: Data to parse. If not specified ValueError will be raised.
:return: A list of meta connections
"""
if not data:
raise ValueError('No data to parse connections given.')
# connections = []
# node, host, port, &options, &socket, &status_int
purpose = ["node", "host", "_a", "port",
"options", "socket", "status_int"]
for i in [z for z in data.splitlines() if len(z.split(" ")[2:])]:
self.connections.append(self.meta_parse(i.split(" ")[2:], purpose, TincConnection()))
return self.connections
def parse_nodes(self, data=None):
"""
Parse information about all known nodes in the VPN.
The peer_info of a node holds the following information:
node, id, host, port, cipher, digest, maclength, compression, options,
status_int, nexthop, via, distance, pmtu, minmtu, maxmtu,
last_state_change
If parse_networks() was excecuted before the networks owned by a node
are also present.
:param data: Data to parse. If not specified ValueError will be raised.
:return: A dictionary of nodes where nodes[nodename].peer_info contains
the mentioned information.
"""
if not data:
raise ValueError('No data to parse nodes given.')
# node, id, host, port, &cipher, &digest, &maclength, &compression, &options,
# &status_int, nexthop, via, &distance, &pmtu, &minmtu, &maxmtu, &last_state_change)
purpose = ['node', 'id', 'host', '_a', 'port', 'cipher', 'digest', 'maclength',
'compression', 'options', 'status_int', 'nexthop', 'via', 'distance',
'pmtu', 'minmtu', 'maxmtu', 'last_state_change']
for i in [z for z in data.splitlines() if len(z.split(" ")[2:])]:
x = self.meta_parse(i.split(" ")[2:], purpose, PeerInfo())
n = self.nodes.setdefault(x['node'], TincNode())
n.peer_info = x
return self.nodes
@staticmethod
def meta_parse(_tmp, purpose, t_obj):
for k, v in zip(purpose, _tmp):
t_obj[k] = v
t_obj.convert_datatypes()
return t_obj
# info
def get_max_weight(self):
"""
Compute the maximal weight of all parsed edges.
:return: The maximal weight
"""
max_weight = 0
for edge in self.edges:
if int(edge['weight']) > max_weight:
max_weight = int(edge['weight'])
return max_weight
def get_min_weight(self):
"""
Compute the minimal weight of all parsed edges.
:return: The minimal weight
"""
min_weight = sys.maxint
for edge in self.edges:
if int(edge['weight']) < min_weight:
min_weight = int(edge['weight'])
return min_weight
def edge_count(self, node):
"""
Compute the count of edges for a given node name.
:param node: The node name
:return: Edge count
"""
# return len(filter(lambda i : i['from'] == node, self.edges))
return len([e for e in self.edges if e['from'] == node])
|
Python
|
UTF-8
| 791
| 2.921875
| 3
|
[] |
no_license
|
line = lambda: map(int, raw_input().split())
def main():
for t in range(input()):
points = [tuple(line()) for n in range(input())]
print 'Case #{}:'.format(t + 1)
solve(points)
def solve(points):
if len(points) == 1:
print 0
return
res = {}
for p1 in range(len(points)):
for p2 in range(p1):
x1, y1 = points[p1]
x2, y2 = points[p2]
a, b = 0, 0
for x, y in points:
det = (x2-x1)*(y-y1) - (y2-y1)*(x-x1)
if det < 0: a += 1
if det > 0: b += 1
res[p1] = min(res.get(p1, 10000), a, b)
res[p2] = min(res.get(p2, 10000), a, b)
#print res, points
for x in range(len(points)):
print res[x]
main()
|
Swift
|
UTF-8
| 1,700
| 2.71875
| 3
|
[] |
no_license
|
//
// adf.swift
// CustomPresentation
//
// Created by Nguyen, Cong on 2020/12/25.
//
import UIKit
class AnimatedTransitioning: NSObject, UIViewControllerAnimatedTransitioning {
let isPresenting: Bool
init(isPresenting: Bool) {
self.isPresenting = isPresenting
super.init()
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.3
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
if isPresenting {
let presented = transitionContext.viewController(forKey: .to)!
let presenting = transitionContext.viewController(forKey: .from)!
let containerView = transitionContext.containerView
containerView.addSubview(presented.view)
presented.view.frame = transitionContext.viewController(forKey: .to)!.presentationController!.frameOfPresentedViewInContainerView
presented.view.frame.origin.x = -presented.view.frame.width
UIView.animate(withDuration: 0.3, animations: {
presented.view.frame.origin.x = 0
presenting.view.frame.origin.x = presented.view.frame.width
}) { _ in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
} else {
let presented = transitionContext.viewController(forKey: .from)!
let presenting = transitionContext.viewController(forKey: .to)!
UIView.animate(withDuration: 0.3, animations: {
presented.view.frame.origin.x = -presented.view.frame.width
presenting.view.frame.origin.x = 0
}) { _ in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
}
}
|
C++
|
UTF-8
| 2,486
| 2.78125
| 3
|
[] |
no_license
|
#include<iostream>
#include<vector>
#include<deque>
#define MAXN 13
using namespace std;
typedef unsigned long long int64;
int p, r, n;
inline void printSeq(const deque<int> &seq)
{
for (int i = 0; i < seq.size(); i++)
cout << seq[i] << ' ';
cout << endl;
}
inline int getData(const deque<int> &seq, const int &num, int &nextLeft, int &nextRight, int &max)
{
register int maxLeft = 0, maxRight = 0;
register int biggerThanNum = 0;
register int lowerThanNum = 0;
nextLeft = nextRight = 0;
for (register int i = 0, k = seq.size()-1; i < seq.size(); i++, k--)
{
if (seq[i] > maxLeft)
{
maxLeft = seq[i];
nextLeft++;
}
if (seq[k] > maxRight)
{
maxRight = seq[k];
nextRight++;
}
if (seq[k] > num)
biggerThanNum++;
else
lowerThanNum++;
}
if (num > maxLeft)
{
nextLeft++;
maxLeft = num;
}
if (num > seq[seq.size()-1])
nextRight = biggerThanNum+1;
else nextRight++;
max = maxLeft;
return lowerThanNum;
}
int64 backtrack(int left, int right, vector<bool> &processed, deque<int> &seq)
{
if (left == p && right == r && seq.size() == n)
{
cout << "Contou 1:";
printSeq(seq);
return 1;
}
printSeq(seq);
//backtrack...
int64 subtotal = 0;
for (register int i = 1; i <= n; i++)
{
if (processed[i]) continue;
register int nextLeft, nextRight, max;
register int qntRight = getData(seq, i, nextLeft, nextRight, max);
register int qntLeft = n - max;
// inserindo a direita
//cout << i << ":" << qntLeft << " " << qntRight << endl;
if (qntLeft >= (p - nextLeft) && (r - nextRight) <= (n - seq.size() +1) &&
nextLeft <= p && nextRight <= r)
{
vector<bool> nextProcessed = processed;
nextProcessed[i] = true;
deque<int> nextSeq = seq;
nextSeq.push_back(i);
subtotal += backtrack(nextLeft, nextRight, nextProcessed, nextSeq);
}
}
//cout << "Subtotal: " << subtotal << endl;
return subtotal;
}
int main()
{
vector<int64> fatorial(MAXN+1, 0);
fatorial[0] = 1;
int nTest;
cin >> nTest;
while (nTest--)
{
cin >> n >> p >> r;
int64 total = 0;
for (int i = 1; i <= n; i++)
{
deque<int> seq(1, i);
vector<bool> processed(n+1, false);
processed[i] = true;
total += backtrack(1, 1, processed, seq);
}
cout << "Total:" << total << endl;
/*
int resto = (n+1) - (p+r);
if (resto && !fatorial[resto])
{
fatorial[resto] = 1;
for (int i = resto; i > 0; i--)
fatorial[resto] *= i;
}
cout << (total * fatorial[resto]) << endl;
*/
}
}
|
Java
|
UTF-8
| 338
| 1.851563
| 2
|
[
"Apache-2.0"
] |
permissive
|
package main.model.db.dao.integrations.tts;
import main.model.db.dao.DAO;
import main.model.dto.integrations.tts.TestTrackingTypeDto;
public class TestTrackingTypeDao extends DAO<TestTrackingTypeDto> {
public TestTrackingTypeDao(){
super(TestTrackingTypeDto.class);
select = "{call SELECT_INT_TTS_TYPE()}";
}
}
|
TypeScript
|
UTF-8
| 3,211
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
import type { Consola, ConsolaLogObject } from 'consola';
import consola from 'consola';
// In ice.js, we use DEBUG_TAG instead of DEBUG to avoid other libs which use `DEBUG` as their flag log debug info.
// eslint-disable-next-line camelcase
const { DEBUG_TAG, npm_lifecycle_event } = process.env;
function getEnableAndDisabledNamespaces(namespaces?: string) {
const enabledNamespaces: RegExp[] = [];
const disabledNamespaces: RegExp[] = [];
// Support namespace wildcards rules which are same as https://github.com/debug-js/debug#wildcards
const namespaceSplits = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
for (const namespaceSplit of namespaceSplits) {
if (!namespaceSplit) {
// ignore empty strings
continue;
}
const formatNamespace = namespaceSplit.replace(/\*/g, '.*?');
if (formatNamespace[0] === '-') {
disabledNamespaces.push(new RegExp(`^${formatNamespace.slice(1)}$`));
} else {
enabledNamespaces.push(new RegExp(`^${formatNamespace}$`));
}
}
return { enabledNamespaces, disabledNamespaces };
}
const { enabledNamespaces, disabledNamespaces } = getEnableAndDisabledNamespaces(DEBUG_TAG);
function enabled(namespace: ICELogNamespace) {
for (const disabledNamespace of disabledNamespaces) {
if (disabledNamespace.test(namespace)) {
return false;
}
}
for (const enabledNamespace of enabledNamespaces) {
if (enabledNamespace.test(namespace)) {
return true;
}
}
}
export type ICELogNamespace = string;
export type CreateLoggerReturnType = Pick<Consola, |
'fatal' |
'error' |
'warn' |
'log' |
'info' |
'start' |
'success' |
'ready' |
'debug' |
'trace'
> & { briefError?: (message: ConsolaLogObject | any, ...args: any[]) => void };
export type CreateLogger = (namespace?: ICELogNamespace) => CreateLoggerReturnType;
export const createLogger: CreateLogger = (namespace) => {
function briefError(message: ConsolaLogObject | any, ...args: any[]) {
consola.error(message, ...args);
if (!DEBUG_TAG) {
// eslint-disable-next-line camelcase
consola.log(`run \`DEBUG_TAG=${namespace || '*'} npm run ${npm_lifecycle_event || 'start'}\` to view error details`);
}
}
function extendLoggerInstance(instance: Consola): CreateLoggerReturnType {
const logger = {} as CreateLoggerReturnType;
['fatal', 'error', 'warn', 'log', 'info', 'start', 'success', 'ready', 'debug', 'trace'].forEach((method) => {
logger[method] = instance[method];
});
logger.briefError = briefError;
return logger;
}
if (DEBUG_TAG) {
consola.level = 4;
}
if (!namespace) {
return extendLoggerInstance(consola);
}
if (DEBUG_TAG) {
if (enabled(namespace)) {
return extendLoggerInstance(consola.withTag(namespace));
} else {
return {
fatal() { },
error() { },
warn() { },
log() { },
info() { },
start() { },
success() { },
ready() { },
debug() { },
trace() { },
briefError() {},
};
}
} else {
return extendLoggerInstance(consola.withTag(namespace));
}
};
export const logger = createLogger();
|
Java
|
UTF-8
| 2,620
| 2.6875
| 3
|
[] |
no_license
|
package org.apache.xalan.templates;
import org.apache.xpath.XPathVisitor;
/**
* A derivation from this class can be passed to a class that implements
* the XSLTVisitable interface, to have the appropriate method called
* for each component of an XSLT stylesheet. Aside from possible other uses, the
* main intention is to provide a reasonable means to perform expression
* rewriting.
*/
public class XSLTVisitor extends XPathVisitor
{
/**
* Visit an XSLT instruction. Any element that isn't called by one
* of the other visit methods, will be called by this method.
*
* @param elem The xsl instruction element object.
* @return true if the sub expressions should be traversed.
*/
boolean visitInstruction(ElemTemplateElement elem)
{
return true;
}
/**
* Visit an XSLT stylesheet instruction.
*
* @param elem The xsl instruction element object.
* @return true if the sub expressions should be traversed.
*/
boolean visitStylesheet(ElemTemplateElement elem)
{
return true;
}
/**
* Visit an XSLT top-level instruction.
*
* @param elem The xsl instruction element object.
* @return true if the sub expressions should be traversed.
*/
boolean visitTopLevelInstruction(ElemTemplateElement elem)
{
return true;
}
/**
* Visit an XSLT top-level instruction.
*
* @param elem The xsl instruction element object.
* @return true if the sub expressions should be traversed.
*/
boolean visitTopLevelVariableOrParamDecl(ElemTemplateElement elem)
{
return true;
}
/**
* Visit an XSLT variable or parameter declaration.
*
* @param elem The xsl instruction element object.
* @return true if the sub expressions should be traversed.
*/
boolean visitVariableOrParamDecl(ElemVariable elem)
{
return true;
}
/**
* Visit a LiteralResultElement.
*
* @param elem The literal result object.
* @return true if the sub expressions should be traversed.
*/
boolean visitLiteralResultElement(ElemLiteralResult elem)
{
return true;
}
/**
* Visit an Attribute Value Template (at the top level).
*
* @param owner The owner of the expression, to which the expression can
* be reset if rewriting takes place.
* @param elem The attribute value template object.
* @return true if the sub expressions should be traversed.
*/
boolean visitAVT(AVT elem)
{
return true;
}
/**
* Visit an extension element.
* @param elem The extension object.
* @return true if the sub expressions should be traversed.
*/
boolean visitExtensionElement(ElemExtensionCall elem)
{
return true;
}
}
|
Markdown
|
UTF-8
| 8,184
| 3.40625
| 3
|
[] |
no_license
|
# # 概述
文本在HTML页面中是最基本的表现形式,通过文本能最有效而详细的说明网页中的内容。但若不对页面中的文本做任何处理,那会给用户浏览带来一些不好的体验。如果通过CSS对文本进行设置后,不仅让用户浏览体验更佳的好,也会让页面的美观程度提升一个高度。
# # 文本设置 *
## 01. [text-align](https://developer.mozilla.org/zh-CN/docs/Web/CSS/text-align)
文本对其方式
```css
text-align: left | right | center;
```
## 02. [text-indent](https://developer.mozilla.org/zh-CN/docs/Web/CSS/text-indent)
段落首行缩进2个字符
```css
text-indent: 2em;
```
## 03. [text-decoration](https://developer.mozilla.org/zh-CN/docs/Web/CSS/text-decoration)
文本装饰线
```css
text-decoration: none | underline | overline | line-through;
```
## 04. [text-transform](https://developer.mozilla.org/zh-CN/docs/Web/CSS/text-transform)
大小写转换
```css
text-transform:none | capitalize | uppercase | lowercase;
```
## 05. [text-shadow](https://developer.mozilla.org/zh-CN/docs/Web/CSS/text-shadow)
文本阴影
```css
text-shadow: H V blur color;
```
- H:水平偏移,“0”表示维持原位,正数为向右偏移,负数为向左偏移。单位为像素“px”。
- V:垂直偏移,“0”表示维持原位,正数为向下偏移,负数为向上偏移。单位为像素“px”。
- blur :模糊距离,用 **正数** 表示阴影模糊的单位距离,距离越大模糊程度越高。单位为像素“px”。
- color:阴影颜色,支持Web技术中的常用颜色模式:“颜色英文单词”、“HEX”、“RGBa”、“HSLa”。
```html
<p style="text-shadow: 2px 2px 5px #000;">Hello, World!</p>
```
## 06. [line-height](https://developer.mozilla.org/zh-CN/docs/Web/CSS/line-height)
文本行高
```css
line-height: normal | <length>
```
## 07. [word-spacing](https://developer.mozilla.org/zh-CN/docs/Web/CSS/word-spacing)
单词间距
```css
word-spacing: normal | <length>
```
## 08. [letter-spacing](https://developer.mozilla.org/zh-CN/docs/Web/CSS/letter-spacing)
字符间距
```css
letter-spacing: normal | <length>
```
## 09. [white-space](https://developer.mozilla.org/zh-CN/docs/Web/CSS/white-space)
空格换行处理
```css
white-space: normal | nowrap | pre | pre-wrap | pre-line | break-spaces
```
## 10. [text-overflow](https://developer.mozilla.org/zh-CN/docs/Web/CSS/text-overflow)
文本裁切
```css
text-overflow: clip | ellipsis;
```
> 提示:该属性不能单独使用,必须要配合文本换行处理属性“white-space”和内容溢出处理属性“overflow”来使用,否则会达不到所期望的效果。

## 11. [overflow-wrap](https://developer.mozilla.org/zh-CN/docs/Web/CSS/overflow-wrap)
用来说明当一个不能被分开的字符串太长而不能填充其包裹盒时,为防止其溢出,浏览器是否允许这样的单词中断换行。
```css
overflow-wrap: normal | break-word;
```
## 12. [color](https://developer.mozilla.org/zh-CN/docs/Web/CSS/color)
文本颜色
```css
color: <named-color> | <hex-color> | <rgb()> | <hsl()> | transparent | inherit
```
## 13. [word-break](https://developer.mozilla.org/zh-CN/docs/Web/CSS/word-break)
单词内断行
```css
word-break:normal | break-all | keep-all
```
# # 字体设置 *
## 01. [font-style](https://developer.mozilla.org/zh-CN/docs/Web/CSS/font-style)
字体样式
```css
font-style: normal | italic | oblique
```
## 03. [font-weight](https://developer.mozilla.org/zh-CN/docs/Web/CSS/font-weight)
字体粗细
```css
font-weight: normal | bold | lighter | bolder | <number>
```
## 04. [font-size](https://developer.mozilla.org/zh-CN/docs/Web/CSS/font-size)
字体大小
```css
font-size: <number> | <percent> [px | rem | em | vw | vh]
```
## 05. [font-family](https://developer.mozilla.org/zh-CN/docs/Web/CSS/font-family)
```css
font-family: 字体名称;
```
## 06. [font](https://developer.mozilla.org/zh-CN/docs/Web/CSS/font)
`font` 属性用于设置字体样式的组合值写法,其语法形式为:
```css
font: [font-style font-weight] font-size font-family;
font: [font-style font-weight] font-size/line-height font-family;
```
其中,font-style 与 font-weight 为可选项,如果不设置即为默认值 `normal`。
## 07. 自定义字体
语法形式:
```css
@font-face {
font-family: '设置字体名称';
src: url('字体路径');
}
```
代码示例:
```html
<!--CSS 部分-->
<style type="text/css">
<!--自定义字体-->
@font-face {
/*字体名称*/
font-family: '经典隶变简';
/*字体路径*/
src: url('fonts/经典隶变简.TTF');
}
@font-face {
/*字体名称*/
font-family: '华文行楷';
/*字体路径*/
src: url('fonts/华文行楷.ttf');
}
.box {
width: 200px;
height: 50px;
border: 1px solid gray;
border-radius: 5px;
margin: 30px auto;
text-align: center;
}
div.t1 {
font: normal bold 20px/50px '经典隶变简';
}
div.t2 {
font: 20px/50px '华文行楷';
}
</style>
<!--HTML 部分-->
<div class="box t1">为中华之崛起而编程</div>
<div class="box t2">为中华之崛起而编程</div>
```

> 提示:可以再 [这里](http://font.chinaz.com/) 下载您想要的字体。
## 07. 在线字体/图标
- 有字库:https://www.youziku.com/
- 阿里矢量图:http://www.iconfont.cn/
- Font Awesome:http://fontawesome.dashgame.com/
# # 扩展
## 01. 文字两端对齐 *
```html
<div>用户名</div>
<div>密码</div>
<div>手机号</div>
<div>验证码</div>
<div>联系地址</div>
```
```css
div {
width: 120px;
padding: 5px;
margin: 2px;
border: 1px solid #ff4500;
border-radius: 5px;
text-align-last: justify; /*两端对齐*/
}
```

## 02. 纵向显示文字 *
纵向显示文字可通过 `writing-mode` 属性设置,其语法形式为:
```
writing-mode:horizontal-tb | vertical-rl | vertical-lr
```
默认值为:`horizontal-tb`
- horizontal-tb:水平方向自上而下的书写方式。即 left-right-top-bottom(类似IE私有值lr-tb)
- vertical-rl:垂直方向自右而左的书写方式。即 top-bottom-right-left(类似IE私有值tb-rl)
- vertical-lr:垂直方向自左而右的书写方式。即 top-bottom-left-right
```html
<p>
沁园春·雪<br/>
北国风光,千里冰封,万里雪飘。
望长城内外,惟余莽莽;大河上下,顿失滔滔。
山舞银蛇,原驰蜡象,欲与天公试比高。
须晴日,看红装素裹,分外妖娆。
江山如此多娇,引无数英雄竞折腰。
惜秦皇汉武,略输文采;唐宗宋祖,稍逊风骚。
一代天骄,成吉思汗,只识弯弓射大雕。
俱往矣,数风流人物,还看今朝。<br>
毛泽东作于一九三二年六月
</p>
```
```css
@charset "UTF-8";
@font-face {
font-family: 'maozedong';
src: url(../fonts/maozedong.ttf);
}
p {
width: 700px;
height: 380px;
border-radius: 5px;
border: 1px solid rgba(18,5,25,0.67);
margin: 0 auto;
padding: 10px;
/*竖排显示文字*/
/*right to left(从右向左), 从左向右是 writing-mode: vertical-lr;*/
writing-mode: vertical-rl;
/*IE浏览器的从右向左,从左向右是 writing-mode: lr-tb;*/
writing-mode: tb-rl; /*兼容 IE*/
-webkit-writing-mode: vertical-rl; /*兼容 Safari*/
font-family: maozedong;
/*文字竖排显示的情况下,相当于设置列宽*/
line-height: 50px;
letter-spacing: 3px;
font-size: 26px;
}
```

## 03. 文本溢出 *
```css
/*单行*/
div {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
/*多行*/
div {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 5; /*显示行数*/
overflow: hidden;
}
```
|
Python
|
UTF-8
| 196
| 3.4375
| 3
|
[] |
no_license
|
import math
for xp in range(30):
lvl = math.sqrt(xp * 2 / 5.0)
print lvl, xp
for lvl in range(1, 20):
xp = (lvl ** 2 / 2.0) * 5
xp2 = xp - ((lvl - 1) ** 2 / 2.0) * 5
print lvl, int(xp), xp2
|
Java
|
UTF-8
| 6,266
| 2.0625
| 2
|
[] |
no_license
|
package com.dummy.myerp.consumer.dao.impl.db.dao;
import com.dummy.myerp.consumer.dao.impl.DaoProxyImpl;
import com.dummy.myerp.model.bean.comptabilite.CompteComptable;
import com.dummy.myerp.model.bean.comptabilite.EcritureComptable;
import com.dummy.myerp.model.bean.comptabilite.JournalComptable;
import com.dummy.myerp.model.bean.comptabilite.LigneEcritureComptable;
import com.dummy.myerp.technical.exception.NotFoundException;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.Date;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class ComptabiliteDaoImplTest extends ConsumerHelperTest {
private static DaoProxyImpl daoProxy;
private ComptabiliteDaoImpl comptabiliteDao;
private EcritureComptable ecritureComptableSample;
@BeforeEach
public void setUp() {
daoProxy = (DaoProxyImpl) ConsumerHelperTest.getBean("DaoProxy");
comptabiliteDao = (ComptabiliteDaoImpl) daoProxy.getComptabiliteDao();
ecritureComptableSample = new EcritureComptable();
ecritureComptableSample.setJournal(new JournalComptable("AC", "Achat"));
ecritureComptableSample.setDate(Date.from(Instant.now()));
ecritureComptableSample.setLibelle("Libelle");
ecritureComptableSample.setReference("AC-2019/00001");
}
@AfterEach
public void reInit() {
ecritureComptableSample = null;
}
@Test
@Order(1)
void getListCompteComptableTest() {
List<CompteComptable> compteComptableList;
compteComptableList = comptabiliteDao.getListCompteComptable();
assertEquals(7, compteComptableList.size());
}
@Test
@Order(1)
void getListJournalComptableTest() {
List<JournalComptable> journalComptableList;
journalComptableList = comptabiliteDao.getListJournalComptable();
assertEquals(4, journalComptableList.size());
}
@Test
@Order(2)
void getListEcritureComptableTest() {
List<EcritureComptable> ecritureComptableList = comptabiliteDao.getListEcritureComptable();
assertEquals(5, ecritureComptableList.size());
}
@Test
@Order(3)
void getEcritureComptableTest() throws NotFoundException {
EcritureComptable ecritureComptableSample;
ecritureComptableSample = comptabiliteDao.getEcritureComptable(-1);
assertEquals("AC-2016/00001", ecritureComptableSample.getReference());
}
@Test
@Order(4)
void getEcritureComptableByRefTest() throws NotFoundException {
EcritureComptable ecritureComptableSample;
ecritureComptableSample = comptabiliteDao.getEcritureComptableByRef("BQ-2016/00003");
assertEquals("Paiement Facture F110001", ecritureComptableSample.getLibelle());
}
@Test
@Order(5)
void loadListLigneEcritureTest() throws NotFoundException {
EcritureComptable ecritureComptableSample = comptabiliteDao.getEcritureComptable(-1);
comptabiliteDao.loadListLigneEcriture(ecritureComptableSample);
assertEquals(3, ecritureComptableSample.getListLigneEcriture().size());
}
@Test
@Order(6)
void insertEcritureComptableTest() throws NotFoundException {
comptabiliteDao.insertEcritureComptable(ecritureComptableSample);
assertEquals(ecritureComptableSample.getReference(), comptabiliteDao.getEcritureComptableByRef(ecritureComptableSample.getReference()).getReference());
}
@Test
@Order(7)
void insertListLigneEcritureComptableTest() throws NotFoundException {
ecritureComptableSample = comptabiliteDao.getListEcritureComptable().get(comptabiliteDao.getListEcritureComptable().size() - 1);
ecritureComptableSample.getListLigneEcriture().add(new LigneEcritureComptable(new CompteComptable(706),
null, null,
new BigDecimal(123)));
ecritureComptableSample.getListLigneEcriture().add(new LigneEcritureComptable(new CompteComptable(706),
null, null,
new BigDecimal(123)));
comptabiliteDao.insertListLigneEcritureComptable(ecritureComptableSample);
assertEquals(2, ecritureComptableSample.getListLigneEcriture().size());
}
@Test
@Order(8)
void updateEcritureComptableTest() throws NotFoundException {
ecritureComptableSample = comptabiliteDao.getEcritureComptableByRef("AC-2016/00001");
ecritureComptableSample.setLibelle("Nouveau libelle 1234");
comptabiliteDao.updateEcritureComptable(ecritureComptableSample);
assertEquals("Nouveau libelle 1234", comptabiliteDao.getEcritureComptableByRef("AC-2016/00001").getLibelle());
}
@Test
@Order(9)
void deleteEcritureComptableTest() throws NotFoundException {
EcritureComptable ecritureComptableSample = new EcritureComptable();
ecritureComptableSample.setJournal(new JournalComptable("AC", "Achat"));
ecritureComptableSample.setDate(new Date());
ecritureComptableSample.setLibelle("Libelle");
ecritureComptableSample.setReference("AC-2019/99999");
comptabiliteDao.insertEcritureComptable(ecritureComptableSample);
comptabiliteDao.deleteEcritureComptable(comptabiliteDao.getEcritureComptableByRef("AC-2019/99999").getId());
assertThrows(NotFoundException.class, () -> comptabiliteDao.getEcritureComptableByRef("AC-2019/99999"));
}
@Test
@Order(10)
void deleteListLigneEcritureComptableTest() throws NotFoundException {
comptabiliteDao.insertListLigneEcritureComptable(ecritureComptableSample);
comptabiliteDao.deleteListLigneEcritureComptable(comptabiliteDao.getEcritureComptableByRef("AC-2019/00001").getId());
assertEquals(0, comptabiliteDao.getEcritureComptableByRef("AC-2019/00001").getListLigneEcriture().size());
}
}
|
C++
|
UTF-8
| 1,501
| 2.796875
| 3
|
[] |
no_license
|
#include "async_io.h"
#include <QThread>
Async_IO::Async_IO(usb_dev_handle *_handle) :
canceled(false), handle(_handle), rxactive(false), txactive(false), TxSize(0), RxSize(0)
{
/* Make the thread delete itself when it is finished */
QObject::connect(
this, SIGNAL(finished()),
this, SLOT(deleteLater())
);
txbuffer = (uint8_t *) malloc(16384);
rxbuffer = (uint8_t *) malloc(16384);
}
void Async_IO::onCanceled()
{
canceled = true;
}
void Async_IO::Operation()
{
int res = 0;
while(!canceled)
{
while(rxactive);
rxactive = true;
res = usb_bulk_read(handle, EP_IN, (char*) rxbuffer + RxSize, 16384-RxSize, 5000);
if(res>0)
RxSize += res;
rxactive = false;
while(txactive);
txactive = true;
res = usb_bulk_write(handle, EP_OUT, (char*) txbuffer, TxSize, 5000);
if(res>0)
TxSize -= res;
txactive = false;
Sleep(1000);
}
}
bool Async_IO::FifoWrite(uint16_t length, uint8_t *data)
{
while(txactive);
if(length+TxSize > 16384)
return false;
txactive = true;
memcpy(txbuffer+TxSize, data, length);
TxSize += length;
txactive = false;
}
bool Async_IO::FifoRead(uint16_t *length, uint8_t *data)
{
while(rxactive);
if(!RxSize)
return false;
rxactive = true;
memcpy(data, rxbuffer, RxSize);
*length = RxSize;
RxSize = 0;
rxactive = false;
return true;
}
|
C
|
UTF-8
| 4,770
| 2.78125
| 3
|
[] |
no_license
|
#include <linux/module.h> // Needed by all modules
#include <linux/moduleparam.h> /* Needed for module parameters */
#include <linux/kernel.h> // Needed for KERN_* and printk
#include <linux/init.h> // Needed for __init and __exit macros
#include <linux/fs.h> /* Provides file ops structure */
#include <asm/io.h> // Needed for IO reads and writes
#include "xparameters.h" // Needed for IO reads and writes
#include <linux/ioport.h> // Used for io memory allocation
#include <linux/sched.h> /* Provides access to the "current" process
task structure */
#include <asm/uaccess.h> /* Provides utilities to bring user space
data into kernel space. Note, it is
processor arch specific. */
#include<linux/slab.h>
// From xparameters.h, physical address of multiplier
#define PHY_ADDR XPAR_MULTIPLY_0_S00_AXI_BASEADDR
// Size of physical address range for multiply
#define MEMSIZE XPAR_MULTIPLY_0_S00_AXI_HIGHADDR \
- XPAR_MULTIPLY_0_S00_AXI_BASEADDR + 1
// Name of the device
#define DEVICE_NAME "multiplier"
#define BUF_LEN 8
// Major number assigned to the device driver
static int Major;
// virtual address pointing to multiplier
void* virt_addr;
int init_module(void);
void cleanup_module(void);
static int device_open(struct inode *, struct file *);
static int device_release(struct inode *, struct file *);
static ssize_t device_read(struct file *, char *, size_t, loff_t *);
static ssize_t device_write(struct file *, const char *, size_t, loff_t *);
/* This structure defines the function pointers to our functions for
opening, closing, reading and writing the device file. There are
lots of other pointers in this structure which we are not using,
see the whole definition in linux/fs.h */
static struct file_operations fops = {
.read = device_read,
.write = device_write,
.open = device_open,
.release = device_release
};
/* This function is run upon module load. This is where you setup data
structures and reserve resources used by the module */
static int __init my_init(void)
{
// Linux kernel's version of printf
printk(KERN_INFO "Mapping virtual address...\n");
// map virtual address to multiplier physical address
virt_addr = ioremap(PHY_ADDR, MEMSIZE);
// use ioremap, print the physical and virtual address
printk("Physical address of the multiplication peripheral: %x\n", PHY_ADDR);
printk("Virtual address of the multiplication peripheral: %x\n",
*(int *)virt_addr);
// register the device
Major = register_chrdev(0, DEVICE_NAME, &fops);
/* Negative values indicate a problem */
if (Major < 0) {
/* Make sure you release any other resources you've already
grabbed if you get here so you don't leave the kernel in a
broken state. */
printk(KERN_ALERT "Registering char device failed with %d\n", Major);
return Major;
}
// print the major number assigned to the device
printk("Char device registered with major number %d\n", Major);
printk(KERN_INFO "Run:\nmknod /dev/%s c %d 0' to register device.\n",
DEVICE_NAME, Major);
// A non 0 return means init_module failed; module can't be loaded
return 0;
}
/* This function is run just prior to the module's removal from the system.
You should release ALL resources used by your module here (otherwise be
prepared for a reboot). */
static void __exit my_exit(void)
{
printk(KERN_ALERT "unmapping virtual address space...\n");
unregister_chrdev(Major, DEVICE_NAME);
iounmap((void*)virt_addr);
}
static int device_open(struct inode *inode, struct file *file)
{
printk("Device is opened!\n");
return 0;
}
static int device_release(struct inode *inode, struct file *file)
{
printk("Device is closed!\n");
return 0;
}
static ssize_t device_read(struct file *filp, char *buffer, size_t length,
loff_t *offset)
{
int bytes_read = 0;
for (bytes_read = 0; bytes_read < length; bytes_read++){
put_user((char)ioread8(virt_addr+bytes_read), buffer + bytes_read);
}
return bytes_read;
}
static ssize_t device_write(struct file *flip, const char __user *buffer,
size_t length, loff_t *offset)
{
int bytes_written = 0;
char buf;
for (bytes_written = 0; bytes_written < length; bytes_written ++){
get_user(buf, buffer + bytes_written);
iowrite8(buf, virt_addr + bytes_written);
}
return bytes_written;
}
// These define info that can be displayed by modinfo
MODULE_LICENSE("GPL");
MODULE_AUTHOR("ECEN449 Student (and others)");
MODULE_DESCRIPTION("Simple multiplier module");
// Here we define which functions we want to use for initialization and cleanup
module_init(my_init);
module_exit(my_exit);
|
C++
|
UTF-8
| 12,373
| 3.109375
| 3
|
[] |
no_license
|
//
// ParallelSearch.h
// FinalProject
//
// Created by Matt on 12/5/15.
// Copyright (c) 2015 Matt. All rights reserved.
//
#ifndef FinalProject_ParallelSearch_h
#define FinalProject_ParallelSearch_h
#include <vector> // std::vector, size_t
#include <algorithm> // make_heap, push_heap, pop_heap, find
#include <unordered_set> // hash table
#include <memory> // std::shared_ptr
#include <limits> // std::numeric_limits<size_t>
#include <stack> // std::stack
#include <queue> // std::queue
#include <thread> // std::thread
#include <future> // std::future
#include <atomic> // std::atomic
#include <iostream>
// unordered_set hash override call to
// T's hashState()
template<class S>
class PTHash {
public:
std::size_t operator()(std::shared_ptr<S> s) const {
return s->hashState();
}
};
// unordered_set equality override call to
// T's isStateEqual()
template<class R>
class PTEqual {
public:
bool operator()(std::shared_ptr<R> a, std::shared_ptr<R> b) const {
return a->isStateEqual(b);
}
};
// GraphSearch Template Class
template <class T>
class ParallelSearch {
private:
// std::heap cost comparison override call to
// T's getCost()
static bool costComparator(const std::shared_ptr<T> a, const std::shared_ptr<T> b) {
return a->getCost() > b->getCost();
}
// std::heap cost comparison override call to
// T's getCost() + T's getHeuristic()
static bool heuristicComparator(const std::shared_ptr<T> a, const std::shared_ptr<T> b) {
return (a->getCost() + a->getHeuristic()) > (b->getCost() + b->getHeuristic());
}
// Count of explored nodes for most recently ran search
size_t exploredCount;
// Uniform Cost Search with Branch and Bound
std::vector<T> UniformSearchBnB(std::shared_ptr<T> start, T goal, std::atomic<size_t>* upperBound) {
// Eventual solution
std::vector<T> solution;
std::shared_ptr<T> best;
// Copy start node
std::shared_ptr<T> node(new T((*start)));
// Initialize Data Structures
std::vector<std::shared_ptr<T>> frontier;
std::make_heap(frontier.begin(), frontier.end(), costComparator);
std::unordered_set<std::shared_ptr<T>, PTHash<T>, PTEqual<T>> explored;
//exploredCount = 0;
// Enqueue start
frontier.push_back(node);
std::push_heap(frontier.begin(), frontier.end(), costComparator);
for (;;) {
if (frontier.empty()) {
return solution;
}
// Dequeue top node from frontier
node = frontier.front();
std::pop_heap(frontier.begin(), frontier.end(), costComparator);
frontier.pop_back();
// Place in explored
explored.emplace(node);
// Is this the goal state?
if (node->isGoal(goal)) {
best = node;
(*upperBound) = node->getCost();
std::cout << "New Upper Bound = " << (*upperBound) << std::endl;
break;
}
// Is this above the upper bound?
if (node->getCost() >= (*upperBound)) {
continue;
}
// Find neighbors
std::vector<std::shared_ptr<T>> candidates = node->neighbors();
for (auto& n : candidates) {
// Skip if >= upperBound
if ((n->getCost() + node->getCost()) >= (*upperBound)) {
continue;
}
// If its the goal and lower, update best
if (n->isGoal(goal)) {
best = n;
(*upperBound) = n->getCost() + node->getCost();
std::cout << "New Upper Bound = " << (*upperBound) << std::endl;
}
// Update previous pointer
n->setPrevious(node);
// Check if already explored
if (explored.find(n) == explored.end()) {
// Check if already in frontier
auto it = std::find(frontier.begin(), frontier.end(), n);
if (it == frontier.end()) {
// Add to frontier
n->setCost(n->getCost() + node->getCost());
n->setPrevious(node);
frontier.push_back(n);
std::push_heap(frontier.begin(), frontier.end(), costComparator);
}
}
}
}
// best is the solution
// Find path
while (best->getPrevious() != nullptr) {
T temp = (*best);
solution.insert(solution.begin(), temp);
best = best->getPrevious();
}
return solution;
}
// Breadth First Search
// Runs BFS to a specified depth and returns nodes in the frontier
std::vector<T> BreadthFirstSearch(T start, T goal, std::queue<std::shared_ptr<T>>& frontier, std::unordered_set<std::shared_ptr<T>, PTHash<T>, PTEqual<T>>& explored, size_t depth) {
// Eventual solution
std::vector<T> solution;
std::shared_ptr<T> lastNode = nullptr;
// Copy start node
std::shared_ptr<T> node(new T(start));
node->setCost(0);
// Initialize Data Structures
exploredCount = 0;
size_t upperBound = std::numeric_limits<size_t>::max();
frontier.push(node);
for (;;) {
if (frontier.empty() || frontier.size() >= depth) {
break;
}
// Dequeue top node from frontier
node = frontier.front();
frontier.pop();
// Mark as visited
explored.emplace(node);
// Check if goal and save the pointer if it is
if (node->isGoal(goal) && node->getCost() < upperBound) {
lastNode = node;
upperBound = node->getCost();
}
// Find neighbors
std::vector<std::shared_ptr<T>> candidates = node->neighbors();
for (auto& n : candidates) {
// Check if already explored
if (explored.find(n) == explored.end()) {
n->setCost(n->getCost() + node->getCost());
n->setPrevious(node);
// Place in explored
explored.emplace(n);
// Check if goal and save the pointer if it is
if (n->isGoal(goal)) {
lastNode = n;
}
// Place in queue
frontier.push(n);
}
}
}
if (lastNode == nullptr) {
throw std::runtime_error("No solution was found.");
}
// Find path
while (lastNode->getPrevious() != nullptr) {
T temp = (*lastNode);
solution.insert(solution.begin(), temp);
lastNode = lastNode->getPrevious();
}
solution.insert(solution.begin(), start);
exploredCount = explored.size();
return solution;
}
// Depth First Search
std::vector<T> DepthFirstSearch(std::shared_ptr<T> start, T goal, std::atomic<size_t>* upperBound) {
// Eventual solution
std::vector<T> solution;
std::shared_ptr<T> lastNode = nullptr;
// Copy start node
std::shared_ptr<T> node(new T((*start)));
// Initialize Data Structures
std::stack<std::shared_ptr<T>> frontier;
std::unordered_set<unsigned int> explored;
frontier.push(node);
for (;;) {
if (frontier.empty()) {
break;
}
// Dequeue top node from frontier
node = frontier.top();
frontier.pop();
// Is this above the upper bound?
if (node->getCost() >= (*upperBound)) {
continue;
}
// Check if goal and save the pointer if it is
if (node->isGoal(goal) && node->getCost() < (*upperBound)) {
lastNode = node;
(*upperBound) = node->getCost();
std::cout << "New Upper Bound = " << (*upperBound) << std::endl;
}
// Find neighbors
std::vector<std::shared_ptr<T>> candidates = node->neighbors();
for (auto& n : candidates) {
n->setCost(n->getCost() + node->getCost());
n->setPrevious(node);
// Place in queue
frontier.push(n);
}
}
if (lastNode == nullptr) {
throw std::runtime_error("No solution was found.");
}
// Find path
while (lastNode->getPrevious() != nullptr) {
T temp = (*lastNode);
solution.insert(solution.begin(), temp);
lastNode = lastNode->getPrevious();
}
exploredCount = explored.size();
return solution;
}
public:
// Default Constructor
ParallelSearch() : exploredCount(0) {
}
// Getter for nodes explored
size_t getLastExploredCount() {
return exploredCount;
}
// Parallel Graph Search
std::vector<T> ParallelGraphSearch(T start, T goal, size_t numThreads) {
// Initialize BFS structures
std::queue<std::shared_ptr<T>> frontier;
std::unordered_set<std::shared_ptr<T>, PTHash<T>, PTEqual<T>> explored;
try {
// Run BFS
std::vector<T> solution = BreadthFirstSearch(start, goal, frontier, explored, numThreads);
return solution;
}
catch (std::runtime_error& err) {
// No solution was found so run UCS in parallel speculatively
T temp(start);
temp.setCost(std::numeric_limits<size_t>::max());
std::vector<T> lowestSolution;
lowestSolution.push_back(temp);
std::atomic<size_t> upperBound(std::numeric_limits<size_t>::max());
while (frontier.size() > 0) {
std::vector<std::future<std::vector<T>>> results;
size_t threadsSpawned = 0;
// Spawn threads
for (threadsSpawned=0; (threadsSpawned<numThreads) && (threadsSpawned<frontier.size()); threadsSpawned++) {
auto startNode = frontier.front();
frontier.pop();
results.push_back(std::async(std::launch::async, &ParallelSearch::DepthFirstSearch, this, startNode, goal, &upperBound));
}
// Wait for results
for (auto& i : results) {
i.wait();
}
// Find the best solution
for (size_t i=0; i<results.size(); i++) {
// Get result
try {
auto futureRes = results.at(i).get();
if (futureRes.size() > 0) {
if (futureRes.at(futureRes.size()-1).getCost() < lowestSolution.at(lowestSolution.size()-1).getCost()) {
lowestSolution = futureRes;
}
}
}
catch (std::runtime_error& e) {
// No result
}
}
}
// Check if solution was actually found
if (lowestSolution[0].getCost() == std::numeric_limits<size_t>::max()) {
throw std::runtime_error("No solution was found.");
}
else {
lowestSolution.insert(lowestSolution.begin(), start);
return lowestSolution;
}
}
}
};
#endif
|
PHP
|
UTF-8
| 350
| 2.671875
| 3
|
[] |
no_license
|
<?php
namespace Example\Tests\Model;
use Example\Model\ValueObject;
class DummyValueObject implements ValueObject
{
/**
* @param ValueObject $object
* @return bool
*/
public function equals(ValueObject $object): bool
{
}
/**
* @return string
*/
public function __toString(): string
{
}
}
|
Markdown
|
UTF-8
| 1,191
| 3.234375
| 3
|
[] |
no_license
|
# [剑指 Offer 53 - I. 在排序数组中查找数字 I](https://leetcode-cn.com/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof/)
统计一个数字在排序数组中出现的次数。
示例 1:
输入: nums = [5,7,7,8,8,10], target = 8
输出: 2
示例 2:
输入: nums = [5,7,7,8,8,10], target = 6
输出: 0
提示:
0 <= nums.length <= 105
-109 <= nums[i] <= 109
nums 是一个非递减数组
-109 <= target <= 109
注意:本题与主站 34 题相同(仅返回值不同):https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
```c++
class Solution {
public:
int search(vector<int>& nums, int target) {
int l = 0, r = nums.size() - 1;
while (l < r) {
int mid = l + r >> 1;
if (nums[mid] >= target) r = mid;
else l = mid + 1;
}
int k = l;
while (k < nums.size() && nums[k] == target) k++;
return k - l;
}
};
```
|
Java
|
UTF-8
| 828
| 3.3125
| 3
|
[] |
no_license
|
package offline;
import java.util.Map.Entry;
public class Line {
private Dictionary dic;
private String[] words;
public Line(String[] split) {
this.words = split;
//fill the dictionary
this.dic = new Dictionary();
for(int i = 0; i < words.length; i++)
this.dic.put(words[i]);
}
public double sim(Line other) {
double sim = 0;
for(Entry<String, Integer> w1: this.dic.entrySet())
for(Entry<String, Integer> w2: other.dic.entrySet())
if(w1.getKey().equalsIgnoreCase(w2.getKey()))
sim++;
sim = 2*sim/(this.dic.size() + other.dic.size());
return sim;
}
public int getDicSize() {
return dic.size();
}
public Dictionary getDic() {
return dic;
}
public String toString() {
String buffer = "";
for(String str: words)
buffer += str + " ";
return buffer;
}
}
|
C++
|
UTF-8
| 954
| 3.171875
| 3
|
[
"MIT"
] |
permissive
|
//Analog Joystick Servo Example Code
//by Kreezy(KRosa) 1.12.2018
//Example Video can be found @ https://youtu.be/b58vSDy8nB8
#include <Servo.h> // includes the Servo library
Servo myservo; // create servo object to control a servo
const int X_pin = 0; // analog pin connected to X output
int val; // variable to read the value from the analog pin
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
Serial.begin(9600); // starts serial comm for debugging @ 9600baud
}
void loop() {
{
val = analogRead(X_pin); // reads the value of the analog sticks X Axis (value between 0 and 1023)
val = map(val, 0, 1023, 20, 180); // scale it to use it with the servo (value between 0 and 180)
myservo.write(val); // sets the servo position according to the scaled value
Serial.println(val);
delay(15); // waits for the servo to get there
}
}
|
Java
|
UTF-8
| 503
| 1.890625
| 2
|
[] |
no_license
|
package csumbcapstonegroup22spring2019.demodb.linechart;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.stereotype.Repository;
import csumbcapstonegroup22spring2019.demodb.entities.linechart.LineChart;
@Repository
public interface ILineChartRepository extends MongoRepository<LineChart, String>{
@Query (value = "{'id':?0}")
LineChart findByRepoId(String id);
}
|
C++
|
UTF-8
| 730
| 3.03125
| 3
|
[] |
no_license
|
/* DwyaneTalk@gmail.com
* by lutao
* leetCodeC++ : Trapping Rain Water
* : https://leetcode.com/problems/house-robber-ii/
*/
#include <iostream>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <hash_set>
using namespace std;
class Solution {
public:
int rob(vector<int>& nums) {
int numSize = nums.size();
if(numSize == 1) return nums[0];
return max(rob_range(nums, 0, numSize - 2), rob_range(nums, 1, numSize - 1));
}
int rob_range(vector<int>& num, int lo, int hi) {
int ans = 0, pre1 = 0, pre2 = 0;
for(; lo <= hi; ++lo) {
ans = max(pre1, pre2 + num[lo]);
pre2 = pre1;
pre1 = ans;
}
return ans;
}
};
|
C++
|
UTF-8
| 1,103
| 2.78125
| 3
|
[] |
no_license
|
#include "Movie.h"
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <string>
using namespace std;
class MovieReader {
public:
vector<Movie> getMovies();
vector<string> getGenres();
MovieReader();
void readFile1(unordered_map<string, Movie> movieMap, unordered_set<string> genreSet);
void readFile2(unordered_map<string, Movie> movieMap);
unordered_map<string, Movie> movieMap;
string max_movie_name_revenue = "";
int max_revenue = 0;
std::string getMaxMovie();
/*
1. create hashmap for movies hashset for genres
2. read file one and populate hashmap and hashset for genres
3. read file two and populate hashmap and hashset for genres
4. store hashmap values in movies, hashset values in genres
*/
private:
unordered_set<string> genreSet;
vector<Movie> movies;
vector<string> genres;
};
// MovieReader reader = new MovieReader();
// reader.populateData();
// Movies movies = reader.getMovies();
|
Ruby
|
UTF-8
| 989
| 2.859375
| 3
|
[] |
no_license
|
# == Schema Information
#
# Table name: rule_totals
#
# id :integer not null, primary key
# challenge_id :integer
# exercise_unit_id :integer
# num_exercise_units :integer
# time_period_id :integer
# num_time_periods :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class RuleTotal < ActiveRecord::Base
# The goal is X Units in Y Period.
validates :challenge, presence: true
validates :exercise_unit, presence: true
validates :time_period, presence: true
validates :num_time_periods, presence: true, numericality: {only_integer: true, greater_than: 0}
validates :num_exercise_units, presence: true, numericality: {only_integer: true, greater_than: 0}
belongs_to :challenge
belongs_to :exercise_unit
belongs_to :time_period
def in_english
"Goal: reach #{num_exercise_units} #{exercise_unit.name} in #{num_time_periods} #{time_period.name}."
end
end
|
Java
|
UTF-8
| 4,771
| 2.328125
| 2
|
[] |
no_license
|
package pl.timetable.service;
import org.apache.log4j.Logger;
import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pl.timetable.api.CourseRequest;
import pl.timetable.dto.CourseDto;
import pl.timetable.entity.Course;
import pl.timetable.entity.Subject;
import pl.timetable.exception.EntityDuplicateFoundException;
import pl.timetable.exception.EntityNotFoundException;
import pl.timetable.repository.CourseRepository;
import pl.timetable.repository.SubjectRepository;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
@Transactional
public class CourseServiceImpl extends AbstractService<CourseDto, CourseRequest> {
public static final Logger LOGGER = Logger.getLogger(CourseServiceImpl.class);
@Autowired
private CourseRepository courseRepository;
@Autowired
private SubjectRepository subjectRepository;
@Override
public List<CourseDto> findAll() {
List<Course> entityCourses = courseRepository.findAll().orElse(Collections.emptyList());
return entityCourses.stream().map(course -> {
Hibernate.initialize(course.getSubjectSet());
return mapEntityToDto(course);
}).collect(Collectors.toList());
}
@Override
public void create(CourseRequest request) throws EntityNotFoundException {
Course course = new Course();
course.setName(request.getName());
if (Objects.nonNull(request.getSubject())) {
course.getSubjectSet().add(getSubject(request.getSubject()));
}
courseRepository.create(course);
}
@Override
public CourseDto update(CourseRequest request, int id) throws EntityNotFoundException {
Course course = new Course();
course.setName(request.getName());
course.getSubjectSet().add(getSubject(request.getSubject()));
course.setId(id);
return mapEntityToDto(courseRepository.update(course));
}
@Override
public void delete(int id) throws EntityNotFoundException {
Course course = Optional.ofNullable(courseRepository.getById(id))
.orElseThrow(() -> new EntityNotFoundException(id, "Course"));
courseRepository.remove(course);
}
public void deleteParameter(int id, int parameterId) throws EntityNotFoundException {
Course course = Optional.ofNullable(courseRepository.getById(id))
.orElseThrow(() -> new EntityNotFoundException(id, "Course"));
Subject subjectFounded = course.getSubjectSet().stream().filter(subject -> parameterId == subject.getId()).findAny()
.orElseThrow(() -> new EntityNotFoundException(parameterId, "Subject"));
course.getSubjectSet().remove(subjectFounded);
courseRepository.update(course);
}
public void addParameter(int id, int parameterId) throws EntityNotFoundException, EntityDuplicateFoundException {
Course course = Optional.ofNullable(courseRepository.getById(id))
.orElseThrow(() -> new EntityNotFoundException(id, "Course"));
course.getSubjectSet().stream()
.filter(subject -> subject.getId() == parameterId).findAny().ifPresent(
subject -> new EntityDuplicateFoundException(parameterId, "Subject")
);
Subject subjectToAdd = subjectRepository.getById(parameterId);
course.getSubjectSet().add(subjectToAdd);
courseRepository.update(course);
}
@Override
public CourseDto get(int id) throws EntityNotFoundException {
Course course = Optional.ofNullable(courseRepository.getById(id))
.orElseThrow(() -> new EntityNotFoundException(id, "Course"));
Hibernate.initialize(course.getSubjectSet());
return mapEntityToDto(course);
}
public List<Subject> getParameters(int id) throws EntityNotFoundException {
return Optional.ofNullable(courseRepository.getParameters(id))
.orElseThrow(() -> new EntityNotFoundException(id, "SubjectList"));
}
private Subject getSubject(Integer subjectId) throws EntityNotFoundException {
return Optional.ofNullable(subjectRepository.getById(subjectId))
.orElseThrow(() -> new EntityNotFoundException(subjectId, "Subject"));
}
private CourseDto mapEntityToDto(Course course) {
CourseDto courseDto = new CourseDto();
courseDto.setId(course.getId());
courseDto.setName(course.getName());
courseDto.setSubjectSet(course.getSubjectSet());
return courseDto;
}
}
|
Swift
|
UTF-8
| 2,545
| 2.71875
| 3
|
[] |
no_license
|
//
// Created by Pierluigi Cifani on 26/02/16.
// Copyright © 2016 BlurSoftware. All rights reserved.
//
import Cocoa
class RegionController: NSViewController {
weak var pickerDelegate: RegionPickerObserver? {
didSet {
//Europe is the default region
self.setSelectedRegion(.Europe)
}
}
@IBOutlet weak var oceaniaButton: NSButton!
@IBOutlet weak var europeButton: NSButton!
@IBOutlet weak var americasButton: NSButton!
@IBOutlet weak var asiaButton: NSButton!
@IBOutlet weak var africaButton: NSButton!
//TODO: This should be handled with a CollectionView or TableView, so we don't have all these IBActions
@IBAction func onSelectAfrica(sender: AnyObject) {
setSelectedRegion(.Africa)
}
@IBAction func onSelectEurope(sender: AnyObject) {
setSelectedRegion(.Europe)
}
@IBAction func onSelectAmericas(sender: AnyObject) {
setSelectedRegion(.America)
}
@IBAction func onSelectOceania(sender: AnyObject) {
setSelectedRegion(.Oceania)
}
@IBAction func onSelectAsia(sender: AnyObject) {
setSelectedRegion(.Asia)
}
func setSelectedRegion(region: Region) {
switch region {
case .Africa:
oceaniaButton.state = NSOffState
europeButton.state = NSOffState
americasButton.state = NSOffState
asiaButton.state = NSOffState
africaButton.state = NSOnState
case .America:
oceaniaButton.state = NSOffState
europeButton.state = NSOffState
americasButton.state = NSOnState
asiaButton.state = NSOffState
africaButton.state = NSOffState
case .Asia:
oceaniaButton.state = NSOffState
europeButton.state = NSOffState
americasButton.state = NSOffState
asiaButton.state = NSOnState
africaButton.state = NSOffState
case .Europe:
oceaniaButton.state = NSOffState
europeButton.state = NSOnState
americasButton.state = NSOffState
asiaButton.state = NSOffState
africaButton.state = NSOffState
case .Oceania:
oceaniaButton.state = NSOnState
europeButton.state = NSOffState
americasButton.state = NSOffState
asiaButton.state = NSOffState
africaButton.state = NSOffState
}
pickerDelegate?.onRegionPicked(region)
}
}
|
Markdown
|
UTF-8
| 8,781
| 2.65625
| 3
|
[] |
no_license
|
---
inFeed: true
hasPage: true
inNav: false
inLanguage: null
keywords: []
description: Analytics is so much more than just a chart depicting the trend in some data.
datePublished: '2016-08-05T01:50:47.548Z'
dateModified: '2016-08-05T01:50:18.537Z'
title: ''
author: []
via: {}
authors: []
publisher: {}
starred: false
sourcePath: >-
_posts/2016-08-05-analytics-is-so-much-more-than-just-a-chart-depicting-the-tr.md
url: analytics-is-so-much-more-than-just-a-chart-depicting-the-tr/index.html
_type: Article
---
Analytics is so much more than just a chart depicting the trend in some data.
Fundamentally it includes that simple chart generated in Excel and extends to the smarts behind Artificial Intelligence !
**Rise of data analytics!**
As you can see from the below chart the rise of "data analytics" has been quite steep and is gaining in popularity as has machine learning, predictive analytics and advanced analytics. All these are focused essentially on leveraging more value from the growing volume of data being generated in our lives.
The figures vary but regardless they are large. IDC, Forbes and others state the analytics industry is worth between [US$48.6B][0]to[US$125B][1], again both indicating a CAGR (compound annual growth rate) of 20-30%. So there is a lot invested in this area!
More importantly are the financial returns available.
For example, technology research firm International Data Corporation (IDC) found in one study that analytical projects aimed at improving production had a median**ROI of 277 percent**("Competing on Analytics", Thomas H. Davenport)
Given this rise of importance in analytics and related fields, it is worth understanding it better and pursuing it.
**So what is Analytics?**
Well[Wikipedia][2]says that it is the "_discovery and communication of meaningful patterns in data_". Modern data analytics is often thought to be found at the intersection of computer programming and statistics/maths clearly communicated through compelling data visualisation.
_...and who wields this awesome power ...._
The person that shapes the analytics can be either a data analyst or scientist. I subscribe to [Sebastian Thrun's][3](@ Udacity) suggestion that the data analyst applies statistical/mathematical models & functions to real world problems, where the Data Scientist title reserved for someone who not only does this but also develops new techniques / methodologies. A data analyst needs to have a combination of skills/knowledge in computer science (programming), mathematics (incl. statistics) and domain expertise (knowledge of business).

Although the key aspect here is the discovery and communication of meaningful patterns in data, it should**never be forgotten that Analytics has no value if it is not directed at ACHIEVING SOME OBJECTIVE**for real world outcomes.
Some of the objectives or applications of data analytics are as follows:
* Marketing optimisation
* Product & service recommendation - cross sell & up-sell
* Customer defection & acquisition
* Fraud detection
* Credit Risk management e.g. likelihood of loan default
* Predictive maintenance of machinery
* Energy usage in buildings
* Employee defection & acquisition
source:[Microsoft Cortana Analytics][4]
**Why is it on the rise?**
Business is surrounded by change and there are several specific factors that are having an immediate impact. These factors are:
* Personalisation
* Cloud Services
* Digital Footprints
* Pervasive Intelligent Compute
* Competition & the Pace of Change
* Learning Organisation
Let's go through them one by one.
Personalisation
* Growing digital lifestyles and expectations of personalised experiences and enhanced services / relationships. There is dual benefit in society here. Firstly for companies there is less money wasted on activities and services that are generalised. On the flip side for the consumer, the more personalised the service the more valued it will be. Take Google advertising as an example. If their advertising was highly generic, then you are likely to be annoyed by the constant barrage of advertising. However the smarter that advertising becomes the more likely you are to accept or event welcome the advertising... it becomes a blur between Advertising and Concierge. In this example byscanning your transactional activity (emails & search) Google can identify that you are probably going on an overseas holiday and as such advertising about upcoming events in that city/country as well as present travel insurance options that maybe useful information for you.
Cloud Services
* The benefits of Cloud Services such as Microsoft Azure are scale, elasticity, flexibility and total cost of ownership
* Cloud Services make it easier to develop and build such personalisation services and to be able to scale these as required.
* You also have the flexibility of adopting footprints of varying levels of control from Infrastructure As A Service (IAAS) e.g Azure Virtual Machines, Platform As A Services (PAAS) such as Azure SQL Datawarehouse and Azure Machine Learning, and Software As A Service (SAAS) e.g. Power BI.
* From elasticity comes the support for agile and iterative learning business models. New virtual machines for technology implementations can be created and removed on demand, reducing cost of ownership whilst facilitating experimentation.

Digital Footprints
* Explosion of data. It is said 90% of the world's data created in the last 2 years. This data comes from social networks, emails, websites, blogs, cloud services.
* In part this is driven by mobile adoption of cloud services, but increasingly data growth will come from new applications of technology including sensors.
* Society is moving from product consumption towards services consumption. More and more of these services are being digitised and because of this they are being delivered to global markets as a commodity.
* An increasing amount of data (aka Big Data) puts in front of us the challenge on how to processes and extract meaning... how to discover those patterns.
Pervasive Intelligent Compute
* Increasing compute capacity spread across mobile and cloud combined with increased data availability is leading to improved advanced algorithms and analytical capabilities.
* The Internet of Things, which is the incorporation of everyday physical objects onto the internet), growth such as sensors (in clothing, vehicles, appliances, etc) will provide a greater flood of data. This will be exacerbated by the pervasive growth in devices that incorporate micro and nano computing capabilities.
* It also means the development of products and services that we haven't even thought of yet, as we seek to creatively combine current and future technologies, all of which will leave behind a data tsunami.
Competition & the Pace of Change
* The behavioural motivations of business, government and individuals drives the pursuit of more effective technological capability. For business this is the pursuit of competitive advantage and the profits that follow. However improvement in technological tools such as cloud services has brought greater agility in the delivery of creativity, differentiation & ultimately value to market... meaning shorter design and delivery times as well as faster iterative improvement in products and services being the delivered. All this amounts to a constant and increasing pace of change.
**So we come back to data analytics. Where does it fit in?**
Fundamentally the foundation of a digital environment is data. And even when that world is physical & real, we seek to record, measure and describe it using data. Organisations seek to improve performance and attain a competitive advantage and Analytics (data) provides that capability and enables them to influence and shape better real world outcomes whether that be an improvement in sales, better performing workforce, more effective advertising or fraud avoidance.
Organisations that have an analytics strategy and capability are highly correlated to have better performance. Indeed those that do not have this capability are at a significant risk of becoming out-competed, disrupted and destined for a corporate graveyard !
[0]: http://www.idc.com/getdoc.jsp?containerId=prUS40560115
[1]: http://www.forbes.com/sites/gilpress/2014/12/11/6-predictions-for-the-125-billion-big-data-analytics-market-in-2015/#744888a02b20
[2]: https://en.wikipedia.org/wiki/Analytics
[3]: https://en.wikipedia.org/wiki/Sebastian_Thrun
[4]: https://www.microsoft.com/en-au/server-cloud/cortana-analytics-suite/overview.aspx
|
JavaScript
|
UTF-8
| 1,417
| 2.96875
| 3
|
[] |
no_license
|
const mySub = document.querySelector("form input[type=submit]");
const myNum = document.querySelector("form input[type=number]");
const myText = document.querySelector("form input[type=text]");
const myColor = document.querySelector("form input.bgCol");
const myTxtColor = document.querySelector("form input.teCol");
const myResult = document.querySelector("form div.results");
let eleNum, eleTxt, eleType, eleCol, eleTeCol;
document.forms[0].onsubmit = (e) => {
e.preventDefault();
};
myNum.oninput = () => (eleNum = myNum.value);
myText.oninput = () => (eleTxt = myText.value.trim());
myColor.oninput = () => (eleCol = myColor.value);
myTxtColor.oninput = () => (eleTeCol = myTxtColor.value);
mySub.onclick = () => {
document.querySelectorAll(".results .box").forEach((box) => {
box.remove();
});
document.querySelector("select").value === "Div"
? (eleType = "div")
: (eleType = "section");
for (let i = 0; i < eleNum; i++) {
let myElem = document.createElement(eleType);
myElem.className = "box";
myElem.setAttribute("title", "Element");
myElem.setAttribute("id", `id-${i + 1}`);
myElem.setAttribute("style", `background-color: ${eleCol};color: ${eleTeCol};`);
let myText = document.createTextNode(eleTxt);
myElem.appendChild(myText);
myResult.appendChild(myElem);
}
};
|
Swift
|
UTF-8
| 3,637
| 2.96875
| 3
|
[] |
no_license
|
//
// PlaceManager.swift
// Places
//
// Created by Shubhang Dixit on 21/10/19.
// Copyright © 2019 Shubhang. All rights reserved.
//
import Foundation
class PlaceManager {
static let shared = PlaceManager()
var places : [Place] = []
var dataDidChange = false
func fetchPlaces(success: @escaping () -> Void, failure: @escaping (Error?)-> Void) {
NetworkManager.shared.getPlacesList(success: {[weak self] data in
do {
if let parsedData = try JSONSerialization.jsonObject(with: data!) as?
[[String:Any]] {
for pData in parsedData {
self?.places.append(Place.init(withDictionary: pData))
}
success()
} else {
failure(nil)
}
} catch let error as NSError {
failure(error)
}
}) { error in
failure(error)
}
}
func fetchPlaceDetails(forPlace place: Place, success: @escaping (Place) -> Void, failure: @escaping (Error?)-> Void) {
guard let iD = place.id, let placeID = Int(iD) else {
failure(nil)
return
}
NetworkManager.shared.getPlaceDetail(forID: placeID, success: { data in
do {
if let parsedData = try JSONSerialization.jsonObject(with: data!) as? [String:Any] {
let newPlace = Place.init(withDictionary: parsedData)
success(newPlace)
} else {
failure(nil)
}
} catch let error as NSError {
failure(error)
}
}) { error in
failure(error)
}
}
func saveNewPlace(withFirstName title: String, description :String?, imageUrl: String?, longitute : Double, latitute : Double, success: @escaping () -> Void, failure: @escaping (Error?)-> Void) {
let placeDictionary = Place.getDictionaryForPlace(withTitle: title, description: description, imageUrl: imageUrl, latitude: latitute, longitute: longitute)
NetworkManager.shared.postAPlace(withData: placeDictionary, success: {[weak self] data in
do {
if let parsedData = try JSONSerialization.jsonObject(with: data!) as? [String:Any] {
self?.addNewPlaceToDS(withData: parsedData)
self?.dataDidChange = true
success()
} else {
failure(nil)
}
} catch let error as NSError {
failure(error)
}
success()
}) { error in
failure(error)
}
}
func saveChanges(forPlaceID iD : Int, data : [String : Any], success: @escaping () -> Void, failure: @escaping (Error?)-> Void) {
NetworkManager.shared.updatePlace(forID: iD, withData: data, success: {[weak self] data in
do {
if let parsedData = try JSONSerialization.jsonObject(with: data!) as? [String:Any] {
success()
} else {
failure(nil)
}
} catch let error as NSError {
failure(error)
}
success()
}) { error in
failure(error)
}
}
func addNewPlaceToDS(withData place:[String:Any]) {
let newPlace = Place.init(withDictionary: place)
self.places.append(newPlace)
}
}
|
Java
|
UTF-8
| 1,772
| 2.15625
| 2
|
[
"MIT"
] |
permissive
|
package net.tecgurus.banco.model.service;
import java.util.Date;
import java.util.List;
import net.tecgurus.banco.model.dao.iface.ClienteDao;
import net.tecgurus.banco.model.dao.impl.ClienteDaoMysql;
import net.tecgurus.banco.model.dto.Banco;
import net.tecgurus.banco.model.dto.Cliente;
public final class ClienteService {
private ClienteDao dao = new ClienteDaoMysql();
public List<Cliente> filtrarClientes(String claveBanco, String nombre, String aPaterno, String aMaterno, boolean status) {
Banco banco = new Banco();
banco.setClave(claveBanco);
Cliente cliente = new Cliente();
cliente.setNombre(nombre);
cliente.setApellidoPaterno(aPaterno);
cliente.setApellidoMaterno(aMaterno);
cliente.setStatus(status);
cliente.setBanco(banco);
return dao.listar(cliente);
}
public List<Cliente> listarClientes() {
return dao.listarTodos();
}
public Cliente buscarPorId(int id) {
return dao.buscarPorId(id);
}
public Cliente crearCliente(String nombre, String apellidoPaterno, String apellidoMaterno, Date fechaNacimiento, boolean status, String claveBanco) {
Banco banco = new Banco();
banco.setClave(claveBanco);
Cliente cliente = new Cliente(nombre, apellidoPaterno, apellidoMaterno, fechaNacimiento, status, banco);
return dao.crear(cliente);
}
public boolean actualizarCliente(int numeroCliente, String nombre, String apellidoPaterno, String apellidoMaterno, Date fechaNacimiento, boolean status, String claveBanco) {
Banco banco = new Banco();
banco.setClave(claveBanco);
Cliente cliente = new Cliente(numeroCliente, nombre, apellidoPaterno, apellidoMaterno, fechaNacimiento, status, banco);
return dao.actualizar(cliente);
}
public boolean eliminarClientePorId(int id) {
return dao.eliminar(id);
}
}
|
Shell
|
UTF-8
| 2,660
| 3.0625
| 3
|
[] |
no_license
|
#!/usr/bin/env bash
set -x
set -euo pipefail
# TODO: maybe we need to upload our own AMI or something?
REGION="us-west-2"
#AMI_ID="ami-073449580ff8e82b5" #NixOS-20.03.2351.f8248ab6d9e-aarch64-linux
#AMI_ID="ami-09d0dda914bed4052" # Amazon Linux 2
AMI_ID="ami-053c71bfc2f2ae88d" # NixOS-20.09alpha417.a780c60f9f7-aarch64-linux
#INSTANCE_TYPE="m6gd.metal" # failed
#INSTANCE_TYPE="m6g.metal" # failed
INSTANCE_TYPE="m6g.8xlarge"
tag="devenv"
INDEX="1"
# TODO: aws cli can query built-in, remove jq usage
awsweeper-tag "${tag}"
vpc="$(aws ec2 create-vpc \
--cidr-block "10.${INDEX}.0.0/16" \
--region "${REGION}" \
| jq -r '.Vpc.VpcId')"
sub="$(aws ec2 create-subnet \
--vpc-id "${vpc}" \
--region "${REGION}" \
--cidr-block "10.${INDEX}.1.0/24" | jq -r '.Subnet.SubnetId')"
gw="$(aws ec2 create-internet-gateway --region "${REGION}" | jq -r '.InternetGateway.InternetGatewayId')"
aws ec2 attach-internet-gateway \
--vpc-id "${vpc}" \
--internet-gateway-id "${gw}" \
--region "${REGION}"
rt="$(aws ec2 create-route-table --vpc-id "${vpc}" --region "${REGION}" | jq -r '.RouteTable.RouteTableId')"
aws ec2 create-route \
--route-table-id "${rt}" \
--destination-cidr-block 0.0.0.0/0 \
--gateway-id "${gw}" \
--region "${REGION}"
aws ec2 associate-route-table \
--subnet-id "${sub}" \
--route-table-id "${rt}" \
--region "${REGION}"
sg="$(aws ec2 create-security-group \
--description "${vpc}-ssh" \
--vpc-id "${vpc}" \
--group-name "${vpc}-ssh" \
--region "${REGION}" | jq -r '.GroupId')"
aws ec2 authorize-security-group-ingress \
--group-id "${sg}" \
--protocol tcp \
--port 22 \
--cidr 0.0.0.0/0 \
--region "${REGION}"
inst="$(aws ec2 run-instances \
--image-id "${AMI_ID}" \
--count 1 \
--region "${REGION}" \
--subnet-id "${sub}" \
--security-group-id "${sg}" \
--instance-type "${INSTANCE_TYPE}" \
--block-device-mappings "[{\"DeviceName\": \"/dev/xvda\",\"Ebs\":{\"VolumeSize\":100,\"VolumeType\":\"gp2\"}}]" \
--key-name "colemickens" \
--associate-public-ip-address | jq -r '.Instances[0].InstanceId')"
aws ec2 create-tags \
--resources "${vpc}" "${sub}" "${gw}" "${rt}" "${sg}" "${inst}" \
--region "${REGION}" \
--tags "Key=project,Value=${tag}"
ip="$(aws ec2 describe-instances \
--region "${REGION}" \
--instance-ids "${inst}" \
--query 'Reservations[0].Instances[0].PublicIpAddress' \
--output text)"
until ssh-keyscan -H "${ip}" >> ~/.ssh/known_hosts; do sleep 2; done
export REMOTE="root@${ip}"
until ssh -oBatchMode=yes ${REMOTE} uptime; do sleep 2; done
~/code/nixcfg/nixup build \
'.#bundles.aarch64-linux' \
"${REMOTE}" 'cole@localhost'
|
Java
|
UTF-8
| 11,357
| 1.664063
| 2
|
[] |
no_license
|
package com.neteast.rmp.dao.domain;
public class ScPortalGlobalParmsExample extends ScPortalGlobalParms {
/**
* This field was generated by Abator for iBATIS.
* This field corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
public static final int EXAMPLE_IGNORE = 0;
/**
* This field was generated by Abator for iBATIS.
* This field corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
public static final int EXAMPLE_NULL = 1;
/**
* This field was generated by Abator for iBATIS.
* This field corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
public static final int EXAMPLE_NOT_NULL = 2;
/**
* This field was generated by Abator for iBATIS.
* This field corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
public static final int EXAMPLE_EQUALS = 3;
/**
* This field was generated by Abator for iBATIS.
* This field corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
public static final int EXAMPLE_NOT_EQUALS = 4;
/**
* This field was generated by Abator for iBATIS.
* This field corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
public static final int EXAMPLE_GREATER_THAN = 5;
/**
* This field was generated by Abator for iBATIS.
* This field corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
public static final int EXAMPLE_GREATER_THAN_OR_EQUAL = 6;
/**
* This field was generated by Abator for iBATIS.
* This field corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
public static final int EXAMPLE_LESS_THAN = 7;
/**
* This field was generated by Abator for iBATIS.
* This field corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
public static final int EXAMPLE_LESS_THAN_OR_EQUAL = 8;
/**
* This field was generated by Abator for iBATIS.
* This field corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
public static final int EXAMPLE_LIKE = 9;
/**
* This field was generated by Abator for iBATIS.
* This field corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
private boolean combineTypeOr;
/**
* This field was generated by Abator for iBATIS.
* This field corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
private int id_Indicator;
/**
* This field was generated by Abator for iBATIS.
* This field corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
private int parmCode_Indicator;
/**
* This field was generated by Abator for iBATIS.
* This field corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
private int parmName_Indicator;
/**
* This field was generated by Abator for iBATIS.
* This field corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
private int parmType_Indicator;
/**
* This field was generated by Abator for iBATIS.
* This field corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
private int parmValue_Indicator;
/**
* This field was generated by Abator for iBATIS.
* This field corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
private int dicUrl_Indicator;
/**
* This field was generated by Abator for iBATIS.
* This field corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
private int dicDisplayField_Indicator;
/**
* This field was generated by Abator for iBATIS.
* This field corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
private int dicValueField_Indicator;
/**
* This field was generated by Abator for iBATIS.
* This field corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
private int description_Indicator;
/**
* This method was generated by Abator for iBATIS.
* This method corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
public void setCombineTypeOr(boolean combineTypeOr) {
this.combineTypeOr = combineTypeOr;
}
/**
* This method was generated by Abator for iBATIS.
* This method corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
public boolean isCombineTypeOr() {
return combineTypeOr;
}
/**
* This method was generated by Abator for iBATIS.
* This method corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
public int getId_Indicator() {
return id_Indicator;
}
/**
* This method was generated by Abator for iBATIS.
* This method corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
public void setId_Indicator(int id_Indicator) {
this.id_Indicator = id_Indicator;
}
/**
* This method was generated by Abator for iBATIS.
* This method corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
public int getParmCode_Indicator() {
return parmCode_Indicator;
}
/**
* This method was generated by Abator for iBATIS.
* This method corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
public void setParmCode_Indicator(int parmCode_Indicator) {
this.parmCode_Indicator = parmCode_Indicator;
}
/**
* This method was generated by Abator for iBATIS.
* This method corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
public int getParmName_Indicator() {
return parmName_Indicator;
}
/**
* This method was generated by Abator for iBATIS.
* This method corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
public void setParmName_Indicator(int parmName_Indicator) {
this.parmName_Indicator = parmName_Indicator;
}
/**
* This method was generated by Abator for iBATIS.
* This method corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
public int getParmType_Indicator() {
return parmType_Indicator;
}
/**
* This method was generated by Abator for iBATIS.
* This method corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
public void setParmType_Indicator(int parmType_Indicator) {
this.parmType_Indicator = parmType_Indicator;
}
/**
* This method was generated by Abator for iBATIS.
* This method corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
public int getParmValue_Indicator() {
return parmValue_Indicator;
}
/**
* This method was generated by Abator for iBATIS.
* This method corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
public void setParmValue_Indicator(int parmValue_Indicator) {
this.parmValue_Indicator = parmValue_Indicator;
}
/**
* This method was generated by Abator for iBATIS.
* This method corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
public int getDicUrl_Indicator() {
return dicUrl_Indicator;
}
/**
* This method was generated by Abator for iBATIS.
* This method corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
public void setDicUrl_Indicator(int dicUrl_Indicator) {
this.dicUrl_Indicator = dicUrl_Indicator;
}
/**
* This method was generated by Abator for iBATIS.
* This method corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
public int getDicDisplayField_Indicator() {
return dicDisplayField_Indicator;
}
/**
* This method was generated by Abator for iBATIS.
* This method corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
public void setDicDisplayField_Indicator(int dicDisplayField_Indicator) {
this.dicDisplayField_Indicator = dicDisplayField_Indicator;
}
/**
* This method was generated by Abator for iBATIS.
* This method corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
public int getDicValueField_Indicator() {
return dicValueField_Indicator;
}
/**
* This method was generated by Abator for iBATIS.
* This method corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
public void setDicValueField_Indicator(int dicValueField_Indicator) {
this.dicValueField_Indicator = dicValueField_Indicator;
}
/**
* This method was generated by Abator for iBATIS.
* This method corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
public int getDescription_Indicator() {
return description_Indicator;
}
/**
* This method was generated by Abator for iBATIS.
* This method corresponds to the database table sc_portal_global_parms
*
* @abatorgenerated Mon Apr 08 20:00:15 CST 2013
*/
public void setDescription_Indicator(int description_Indicator) {
this.description_Indicator = description_Indicator;
}
}
|
Java
|
UTF-8
| 773
| 2
| 2
|
[] |
no_license
|
package com.zdw.helloworld;
import com.zdw.helloworld.api.HelloWorldInterfaces;
import org.apache.servicecomb.provider.rest.common.RestSchema;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author zdb
* @date 2020-04-12 21:21
*/
@RestController
@RestSchema(schemaId = "providerController")
public class ProviderController implements HelloWorldInterfaces {
@GetMapping("hello")
@Override
public String sayHello(String name) {
System.out.println("名称是:"+name);
return "请求成功,返回名称:"+name;
}
}
|
Java
|
UTF-8
| 5,719
| 1.90625
| 2
|
[] |
no_license
|
package cn.cgnb.service.impl;
import cn.cgnb.bean.DBSourceBean;
import cn.cgnb.bean.DSBean;
import cn.cgnb.bean.IdNameInfo;
import cn.cgnb.bean.SyncTableInfo;
import cn.cgnb.conf.PageParam;
import cn.cgnb.conf.PageResult;
import cn.cgnb.datasources.OracleClient;
import cn.cgnb.datasources.OracleClientNew;
import cn.cgnb.service.ConfigT0Service;
import cn.cgnb.service.ConfigT0ServiceNew;
import kafka.common.TopicAndPartition;
import kafka.utils.ZkUtils;
import org.apache.kafka.common.security.JaasUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import scala.collection.Iterator;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Created by ah on 2018/5/7.
*/
@Service
public class ConfigT0ServiceNewImpl implements ConfigT0ServiceNew{
@Value("${zkUrl}")
private String zkUrl;
@Autowired
private OracleClientNew oracleClient;
private SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
private final static Logger logger = LoggerFactory.getLogger(ConfigT0ServiceNewImpl.class);
/**
* 1、获取kafka中topic
* 2、topic相关信息存放到 t_kafka_topic
* 返回 topic_id -> topic_name
* @return
*/
public List<IdNameInfo> getAllTopics(boolean flag){
// 存放所有的topics
List<IdNameInfo> topics = new ArrayList<IdNameInfo>();
// 存放topic_name 和topic_partition 分区数量
Map<String,Integer> topics_partitions = new HashMap<>();
if(flag){
ZkUtils zkutils = ZkUtils.apply(zkUrl,30000,30000, JaasUtils.isZkSecurityEnabled());
scala.collection.Set<TopicAndPartition> allPartitions = zkutils.getAllPartitions();
Iterator<TopicAndPartition> partitions = allPartitions.iterator();
while(partitions.hasNext()){
TopicAndPartition tp = partitions.next();
String topic= tp.topic();
// 去除 --from-beginning和__consumer_offsets
if("__consumer_offsets".equals(topic) || "--from-beginning".equals(topic)
||"offsets".equals(topic) )
continue;
// 分区是从0 开始 所以每个topic 分区数为 分区+1
topics_partitions.put(topic,tp.partition()+1);
}
// 同时将topic信息存放到t_kafka_topic表 同时返回id——name一一对应的map
topics = oracleClient.saveTopic(topics_partitions);
}
else{
topics = oracleClient.selectTopics();
}
return topics;
}
/**
* 得到所有数据源id
*
* @return
*/
@Override
public List<IdNameInfo> getAllSids() {
return oracleClient.selectAllSiddb();
}
/**
* 数据源操作
* @param dbBean
*/
@Override
public void savaDB(DBSourceBean dbBean) {
oracleClient.insertDB(dbBean);
}
/**
* 根据表名,查找表的字段
* @return
*/
@Override
public List<String> getTabCols(DSBean dsBean) {
List<String> cols = oracleClient.getCols(dsBean);
return cols;
}
/**
* 根据数据库 查询所有表
* @param db_id
* @return
*/
@Override
public List<String> getTabls(String db_id) {
List<String> tabs = oracleClient.getTabs(db_id);
return tabs;
}
/**
* 分页查询信息
* @param src_id
* @param src_table_name
* @param tag_id
* @param tag_table_name
* @param topic
* @param is_released
* @param parm
* @return
*/
@Override
public PageResult<SyncTableInfo> querySyncInfos(String src_id, String src_table_name
, String tag_id , String tag_table_name, String topic , String is_released, PageParam parm){
PageResult<SyncTableInfo> result = oracleClient.querySyncInfos( src_id, src_table_name
, tag_id , tag_table_name, topic,is_released,parm);
return result;
}
/**
* 查询 dim_src2std_desc中system_id
*
* @return
*/
@Override
public List<String> queryStdSys(){
return oracleClient.queryStdSys();
}
public List<String> queryStds(String system_id){
return oracleClient.queryStds(system_id);
}
/**
* 保存 更新为 注册
* @param id
*/
@Override
public void updateSaveSync(String id) {
String release_time = sdf.format(new Date());
oracleClient.updateSaveSync(id,release_time);
}
/**
*
* 根据模板中的数据 ,将保存或者注册的信息插入到配置表
*
* @param sti
*/
@Override
public void saveConf(SyncTableInfo sti) {
String create_time = sdf.format(new Date());
String release_time="";
// 判断是否注册,如果注册,注册时间为create_time 否则为空
if(sti.getIs_released()=="1"){
release_time = create_time;
sti.setRelease_user("admin");
}
sti.setCreate_time(create_time);
sti.setRelease_time(release_time);
sti.setCreate_user("admin");
oracleClient.insertConf(sti);
}
/**
* 进入编辑页面
* @param id
* @return
*/
public SyncTableInfo editSyncInfo(String id){
SyncTableInfo sti = oracleClient.editSyncInfo(id);
return sti;
}
}
|
Markdown
|
UTF-8
| 5,452
| 3.0625
| 3
|
[] |
no_license
|
---
layout: page
title: "Q168046: HOWTO: STL Sample for [list::rbegin, rend, reverse, rev_iterator"
permalink: /kb/168/Q168046/
---
## Q168046: HOWTO: STL Sample for [list::rbegin, rend, reverse, rev_iterator
{% raw %}
Article: Q168046
Product(s): Microsoft C Compiler
Version(s): 4.2,5.0,6.0
Operating System(s):
Keyword(s): kbcode kbVC420 kbVC500 kbVC600
Last Modified: 29-APR-2002
-------------------------------------------------------------------------------
The information in this article applies to:
- The Standard C++ Library, used with:
- Microsoft Visual C++, 32-bit Enterprise Edition, versions 4.2, 5.0, 6.0
- Microsoft Visual C++, 32-bit Professional Edition, versions 4.2, 5.0, 6.0
- Microsoft Visual C++, 32-bit Learning Edition, version 6.0
- Microsoft Visual C++.NET (2002)
-------------------------------------------------------------------------------
SUMMARY
=======
The sample code below illustrates how to use the [list::rbegin, list::rend,
list::reverse_iterator, list::reverse] STL function(s) in Visual C++.
NOTE: There are some differences in the implementation of the Standard C++
Library components in Visual C++ version 4.2 versus later revisions. The
relevant sections of code below compile conditionally based upon the value of
_MSC_VER.
MORE INFORMATION
================
Required Header
---------------
<list>
<string>
<iostream>
Prototype
---------
const_reverse_iterator rbegin() const;
reverse_iterator rbegin();
const_reverse_iterator rend() const;
reverse_iterator rend();
typedef reverse_bidirectional_iterator<iterator,
value_type, reference, A::types<T>::pointer,
difference_type> reverse_iterator;
void reverse();
NOTE: The class/parameter names in the prototype may not match the version in the
header file. Some have been modified to improve readability.
Description
-----------
This example shows how to iteratate through a list backwards. It also shows how
to reverse a list.
Sample Code
-----------
//////////////////////////////////////////////////////////////////////
//
// Compile options needed: -GX
//
// rev.cpp : This example shows how to iteratate through a list
// backwards. It also shows how to reverse a list.
//
// Functions:
//
// list::rbegin
// list::rend
// list::reverse_iterator
// list::reverse
//
// Written by Andrew Bradnan
// Copyright (c) 1996 Microsoft Corporation. All rights reserved.
//////////////////////////////////////////////////////////////////////
#pragma warning(disable:4786)
#include <list>
#include <string>
#include <iostream>
using namespace std;
#if _MSC_VER > 1020 // if VC++ version is > 4.2
using namespace std; // std c++ libs implemented in std
#endif
typedef list<string, allocator<string> > LISTSTR;
// We use this object so that list::sort() can sort in a different
// order.Normally greater<> is used. We override it here to switch to
// less.
struct less_str : greater<string> {
bool operator()(const string& _X, const string& _Y) const
{return (_X < _Y); }
};
void main()
{
LISTSTR test;
LISTSTR::iterator i;
LISTSTR::reverse_iterator r;
test.push_back("one");
test.push_back("two");
test.push_back("three");
// one two three
cout << "Forwards" << endl << " ";
for (i = test.begin(); i != test.end(); ++i)
cout << *i << " ";
cout << endl;
// three two one
cout << "Backwards" << endl << " ";
for (r = test.rbegin(); r != test.rend(); ++r)
cout << *r << " ";
cout << endl;
// Switch the order
test.reverse();
// three two one
cout << "Reversed" << endl << " ";
for (i = test.begin(); i != test.end(); ++i)
cout << *i << " ";
cout << endl;
// sort alphabetically (decending by default)
test.sort();
// two three one
cout << "Sorted descending" << endl << " ";
for (i = test.begin(); i != test.end(); ++i)
cout << *i << " ";
cout << endl;
test.sort(less_str());
// One three two
cout << "Sorted ascending" << endl << " ";
for (i = test.begin(); i != test.end(); ++i)
cout << *i << " ";
cout << endl;
}
Program Output
--------------
Forwards
one two three
Backwards
three two one
Reversed
three two one
Sorted descending
one three two
Sorted ascending
two three one
REFERENCES
==========
Visual C++ Books On Line: Visual C++ Books:C/C++:Standard C++ Library Reference.
Additional query words: STL STLSample [list::rbegin, list::rend, list::reverse_iterator, list::reverse]
======================================================================
Keywords : kbcode kbVC420 kbVC500 kbVC600
Technology : kbVCsearch kbAudDeveloper kbVCLibrary
Version : :4.2,5.0,6.0
Issue type : kbhowto
=============================================================================
{% endraw %}
|
Python
|
UTF-8
| 227
| 3.828125
| 4
|
[] |
no_license
|
import turtle
t = turtle.Turtle()
t.pensize(5)
t.rt(90)
def square():
t.fd(100)
for i in range(3):
t.lt(90)
t.fd(200)
t.lt(90)
t.fd(100)
for i in range(5):
square()
t.lt(72)
turtle.done()
|
Java
|
UTF-8
| 29,096
| 2.859375
| 3
|
[] |
no_license
|
package cop5556sp17;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import cop5556sp17.Parser.SyntaxException;
import cop5556sp17.Scanner.IllegalCharException;
import cop5556sp17.Scanner.IllegalNumberException;
public class ParserTest2 {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void testFactor0() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "abc";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
parser.factor();
}
@Test
public void testFactor1() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "xyz123";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
parser.factor();
}
@Test
public void testFactor2() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "123";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
parser.factor();
}
@Test
public void testFactor3() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "TRUE";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
parser.factor();
}
@Test
public void testArg() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = " (3,5) ";
Scanner scanner = new Scanner(input);
scanner.scan();
System.out.println(scanner);
Parser parser = new Parser(scanner);
parser.arg();
}
@Test
public void testArg1() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = " (abc,235,xy1) ";
Scanner scanner = new Scanner(input);
scanner.scan();
System.out.println(scanner);
Parser parser = new Parser(scanner);
parser.arg();
}
@Test
public void testArg2() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "(ifEmpty)";
Scanner scanner = new Scanner(input);
scanner.scan();
System.out.println(scanner);
Parser parser = new Parser(scanner);
parser.arg();
}
@Test
public void testArg3() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "(abc >= 567)";
Scanner scanner = new Scanner(input);
scanner.scan();
System.out.println(scanner);
Parser parser = new Parser(scanner);
parser.arg();
}
@Test
public void testArg4() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "567(";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
parser.arg();
}
@Test
public void testArgerror() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = " (3,) ";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
thrown.expect(Parser.SyntaxException.class);
parser.arg();
}
@Test
public void testArgerror1() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = " (3, ,j) ";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
thrown.expect(Parser.SyntaxException.class);
parser.arg();
}
@Test
public void testArgerror2() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = " ) ";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
parser.arg();
}
@Test
public void testArgerror3() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = " ( ) ";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
thrown.expect(Parser.SyntaxException.class);
parser.arg();
}
@Test
public void testProgram0() throws IllegalCharException, IllegalNumberException, SyntaxException{
String input = "prog0 {}";
Parser parser = new Parser(new Scanner(input).scan());
parser.parse();
}
@Test
public void testProgram1() throws IllegalCharException, IllegalNumberException, SyntaxException{
String input = "prog01 {sleep abc;}";
Parser parser = new Parser(new Scanner(input).scan());
parser.parse();
}
@Test
public void testProgram2() throws IllegalCharException, IllegalNumberException, SyntaxException{
String input = "prog02 url www , file f1 , boolean i , integer no {integer abc}";
Parser parser = new Parser(new Scanner(input).scan());
parser.parse();
}
@Test
public void testProgram3() throws IllegalCharException, IllegalNumberException, SyntaxException{
String input = "prog02 url www , file f1 {while (a | b) { if (a + b) { convolve ( a , b , 7+9) |-> abc -> hide ( n , m ) ; xyz <- 23*5+1 ; } } }";
Parser parser = new Parser(new Scanner(input).scan());
parser.program();
}
@Test
public void testProgram4() throws IllegalCharException, IllegalNumberException, SyntaxException{
String input = "prog4 { if (23 + abc > 56 - dwedwd) {pr -> Hi;}}";
Parser parser = new Parser(new Scanner(input).scan());
parser.parse();
}
@Test
public void testElem() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "abc * 123 / 11";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
parser.elem();
}
@Test
public void testExp() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "abc & TRUE | 4%2 != 2*67 + 100/5 ";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
parser.expression();
}
@Test
public void customTest10a() throws Exception
{
String input = "sum <- sum2;";
Scanner scanner=new Scanner(input);
scanner.scan();
Parser parser=new Parser(scanner);
parser.statement();
}
//statement ::= assign ;
@Test
public void customTest10b() throws Exception
{
String input = "sum -> sum2 |-> abc;";
Scanner scanner=new Scanner(input);
scanner.scan();
Parser parser=new Parser(scanner);
parser.statement();
}
//statement ::= assign ;
@Test
public void customTest10c() throws Exception
{
String input = "abc url abc , integer abc {abc -> blur |-> hide -> blur ( 123, 123, 123); }";
Scanner scanner=new Scanner(input);
scanner.scan();
Parser parser=new Parser(scanner);
parser.parse();
}
@Test
public void customTest10d() throws Exception
{
String input = "prog1 url www, boolean sup{integer a boolean b3 sleep abc & 23 | 4%2 != 100*6 + 125/5; hey |-> hi -> hello; z1 <- c2 * 42/4; while(something2!=true) { if(4+4 == b4){sleep 68%4;}}}";
Scanner scanner=new Scanner(input);
scanner.scan();
Parser parser=new Parser(scanner);
parser.parse();
}
@Test
public void customTest240() throws Exception
{
String input = "while ((screen width)) { frame intcoiwn239999 }";
Scanner scanner=new Scanner(input);
scanner.scan();
Parser parser=new Parser(scanner);
thrown.expect(SyntaxException.class);
parser.statement();
}
//statement ::= ifStatement
@Test
public void customTest251() throws Exception
{
String input = "if ((screenwidth) < (screenheight) { frame intcoiwn23 }";
Scanner scanner=new Scanner(input);
scanner.scan();
//System.out.println(scanner.tokens);
Parser parser=new Parser(scanner);
thrown.expect(SyntaxException.class);
parser.statement();
}
//statement ::= assign ;
@Test
public void customTest261() throws Exception
{
String input = "sum <- sum2";
Scanner scanner=new Scanner(input);
scanner.scan();
Parser parser=new Parser(scanner);
thrown.expect(SyntaxException.class);
parser.statement();
}
//statement ::= chain ;
@Test
public void customTest271() throws Exception
{
String input = "name name333;";
Scanner scanner=new Scanner(input);
scanner.scan();
Parser parser=new Parser(scanner);
thrown.expect(SyntaxException.class);
parser.statement();
}
//@Rule
//public ExpectedException thrown = ExpectedException.none();
@Test
public void testFactor10() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "abc";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
parser.factor();
}
@Test
public void testArg1111() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = " (3,5) ";
Scanner scanner = new Scanner(input);
scanner.scan();
System.out.println(scanner);
Parser parser = new Parser(scanner);
parser.arg();
}
@Test
public void testArgerror11() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = " (3,) ";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
thrown.expect(Parser.SyntaxException.class);
parser.arg();
}
@Test
public void testProgram10() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "prog0 {}";
Parser parser = new Parser(new Scanner(input).scan());
parser.parse();
}
@Test
public void testFactor() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "()";
Parser parser = new Parser(new Scanner(input).scan());
thrown.expect(Parser.SyntaxException.class);
parser.factor();
String input1 = "screenheight";
Parser parser1 = new Parser(new Scanner(input1).scan());
parser1.factor();
String input2 = "screenheight1234";
Parser parser2 = new Parser(new Scanner(input2).scan());
parser2.factor();
String input3 = "screenheight 1234"; // Note that 1234 will not be
// parsed with this method call
Parser parser3 = new Parser(new Scanner(input3).scan());
parser3.factor();
}
@Test
public void testElem1() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "(abc*1234%5/def&true)";
Parser parser = new Parser(new Scanner(input).scan());
parser.elem();
String input1 = "(abc*1234%5/def&&true)"; // strongOp not followed by
// factor
Parser parser1 = new Parser(new Scanner(input1).scan());
thrown.expect(Parser.SyntaxException.class);
parser1.elem();
}
@Test
public void testTerm1() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "(abc*1234%5/def&true)";
Parser parser = new Parser(new Scanner(input).scan());
parser.term();
String input1 = "abc*1234%5/def&true|false&21+121-something";
Parser parser1 = new Parser(new Scanner(input1).scan());
parser1.term();
String input2 = "abc*1234%5/def&true|false&21+121-something/";
Parser parser2 = new Parser(new Scanner(input2).scan());
thrown.expect(Parser.SyntaxException.class);
parser2.term();
String input3 = "abc*1234%5/def&true|false&21+121-something and someMorething";
Parser parser3 = new Parser(new Scanner(input3).scan());
thrown.expect(Parser.SyntaxException.class);
parser3.term();
}
@Test
public void testExpression1() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "(something)<=somethingMore>somethingLess!=nothing==void";
Parser parser = new Parser(new Scanner(input).scan());
parser.expression();
}
@Test
public void testArg12() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "";
Parser parser = new Parser(new Scanner(input).scan());
parser.arg();
String input1 = "(something)<=somethingMore>somethingLess!=nothing==void";
Parser parser1 = new Parser(new Scanner(input1).scan());
parser1.arg();
String input2 = "(something)<=somethingMore>somethingLess!=nothing==void, (), 1234, a*b, ,";
Parser parser2 = new Parser(new Scanner(input2).scan());
parser2.arg();
}
@Test
public void testChainElem1() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "abc blur";// blur will be ignored
Parser parser = new Parser(new Scanner(input).scan());
parser.chainElem();
String input1 = "blur";
Parser parser1 = new Parser(new Scanner(input1).scan());
parser1.chainElem();
String input2 = "blur123";
Parser parser2 = new Parser(new Scanner(input2).scan());
parser2.chainElem();
}
@Test
public void testIf11() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "if";
Parser parser = new Parser(new Scanner(input).scan());
thrown.expect(Parser.SyntaxException.class);
parser.parse();
// parser.ifStatement();
String input1 = "if(){";
Parser parser1 = new Parser(new Scanner(input1).scan());
thrown.expect(Parser.SyntaxException.class);
// parser1.ifStatement();
parser1.parse();
String input2 = "if(){}";
Parser parser2 = new Parser(new Scanner(input2).scan());
// parser2.ifStatement();
parser2.parse();
String input3 = "if(abc>=123){integer def while(1){def -> blur}}";
Parser parser3 = new Parser(new Scanner(input3).scan());
parser3.parse();
// parser3.ifStatement();
String input4 = "if(abc>=123){integer def while(1){def -> blur somethingToCauseError}}";
Parser parser4 = new Parser(new Scanner(input4).scan());
parser4.parse();
thrown.expect(Parser.SyntaxException.class);
// parser4.ifStatement();
}
// @Rule
// public ExpectedException thrown = ExpectedException.none();
@Test
public void testFactor01() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "abc";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
parser.factor();
}
@Test
public void strongOp() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "%";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
// parser.strongOp();
}
@Test
public void testIllegalElem() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "abc*teddy%";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
thrown.expect(Parser.SyntaxException.class);
parser.elem();
}
@Test
public void testElem2() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "abc* teddy\r\n&bloody%turds/owl";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
parser.elem();
}
@Test
public void testIllegalTerm() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "abc* teddy\r\n&bloody%turds/owl+screenheight-screenwidth|toodles|";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
thrown.expect(Parser.SyntaxException.class);
parser.term();
}
@Test
public void testTerm() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "abc* teddy\r\n&bloody%turds/owl-screenheight";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
parser.term();
}
@Test
public void testIllegalExpression() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "screenheight-screenwidth!=";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
thrown.expect(Parser.SyntaxException.class);
parser.expression();
}
@Test
public void testExpression() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "screenheight-screenwidth!=plato";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
parser.expression();
}
@Test
public void testArg23() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = " (3,5) ";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
parser.arg();
}
@Test
public void testArgerror22() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = " (3,) ";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
thrown.expect(Parser.SyntaxException.class);
parser.arg();
}
@Test
public void testChainElem() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "blur (3,5) ";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
parser.chainElem();
}
@Test
public void testChainElemErr() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "blur (3,) ";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
thrown.expect(Parser.SyntaxException.class);
parser.chainElem();
}
@Test
public void testChain() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "blur (3,5)->blur (3,5)->blur (3,5)";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
parser.chain();
}
@Test
public void testChainErr() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "blur (3,5)->blur (3,5)->->->blur (3,) ";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
thrown.expect(Parser.SyntaxException.class);
parser.chain();
}
@Test
public void testAssign() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "blurcrazy<-screenheight-screenwidth!=plato";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
// parser.assign();
}
@Test
public void testAssignErr() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "blurcrazy<-screenheight-screenwidth!=";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
thrown.expect(Parser.SyntaxException.class);
parser.parse();
// parser.assign();
}
@Test
public void testDec2() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "integer blue";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
parser.dec();
}
@Test
public void testDecErr() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "integer blur";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
thrown.expect(Parser.SyntaxException.class);
parser.dec();
}
@Test
public void testParamDec2() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "url blue";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
parser.paramDec();
}
@Test
public void testParamDecErr() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "url blur";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
thrown.expect(Parser.SyntaxException.class);
parser.paramDec();
}
@Test
public void testBlock() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "{integer blue sleep screenheight-screenwidth!=plato;}";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
parser.block();
}
@Test
public void testBlockErr() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "{integer blue sleep\n screenheight-screenwidth!=plato;";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
thrown.expect(Parser.SyntaxException.class);
parser.block();
}
@Test
public void testWhileStatement() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "while(true){integer blue sleep\n screenheight-screenwidth!=plato;}";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
parser.statement();
}
@Test
public void testWhileStatementErr() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "while(true)\r\n integer blue sleep\n screenheight-screenwidth!=plato;}";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
thrown.expect(Parser.SyntaxException.class);
parser.statement();
}
@Test
public void testIfStatement() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "if(screenheight-screenwidth!=plato){integer blue sleep\n screenheight-screenwidth!=plato;}";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
parser.statement();
}
@Test
public void testIfStatementErr() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "if(screenheight-screenwidth!=plato)\r\n {integer blue sleep\n -screenwidth!=plato;}";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
thrown.expect(Parser.SyntaxException.class);
parser.statement();
}
@Test
public void testStatement3() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "if(screenheight-screenwidth!=plato)\r\n {integer blue sleep\n screenheight-screenwidth!=plato;blurcrazy<-screenheight-screenwidth!=plato;}";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
parser.statement();
}
@Test
public void testStatementErr() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "if(screenheight-screenwidth!=plato)\r\n {integer blue sleep\n screenheight-screenwidth!=;blurcrazy<-screenheight-screenwidth!=plato;} ";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
thrown.expect(Parser.SyntaxException.class);
parser.statement();
}
@Test
public void testProgram() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "toodles {if(screenheight-screenwidth!=plato)\r\n {integer blue sleep\n screenheight-screenwidth!=test;blurcrazy<-screenheight-screenwidth!=plato;}}";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
parser.program();
}
@Test
public void testProgramErr() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "terrible{if(screenheight-screenwidth!=plato)\r\n {integer blue sleep\n screenheight-screenwidth!=;blurcrazy<-screenheight-screenwidth!=plato;}} ";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
thrown.expect(Parser.SyntaxException.class);
parser.program();
}
@Test
public void testProgram00() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "prog0 {}";
Parser parser = new Parser(new Scanner(input).scan());
parser.parse();
}
@Test
public void testIf1() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = " if(ab>) ";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
thrown.expect(Parser.SyntaxException.class);
parser.parse();
// parser.ifStatement();
}
@Test
public void testIf2() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = " if(8> ";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
thrown.expect(Parser.SyntaxException.class);
parser.parse();
// parser.ifStatement();
}
@Test
public void testBlock1() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = " as} ";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
thrown.expect(Parser.SyntaxException.class);
parser.block();
}
@Test
public void testBlock2() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = " {as} ";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
thrown.expect(Parser.SyntaxException.class);
parser.block();
}
@Test
public void testBlock3() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = " {if(){}} ";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
thrown.expect(Parser.SyntaxException.class);
parser.block();
}
@Test
public void testBlock4() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = " {if(){}} ";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
thrown.expect(Parser.SyntaxException.class);
parser.block();
}
@Test
public void testBlock5() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = " {if(abc23 false){}} ";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
thrown.expect(Parser.SyntaxException.class);
parser.block();
}
@Test
public void testBlock6() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = " {if(abc23)} false) ";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
thrown.expect(Parser.SyntaxException.class);
parser.block();
}
@Test
public void testBlock7() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = " {if(abc23){} ";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
thrown.expect(Parser.SyntaxException.class);
parser.block();
}
@Test
public void testBlock8() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = " {int <- abc ; } ";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
// thrown.expect(Parser.SyntaxException.class);
parser.block();
}
@Test
public void testStatement() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = " {int <- abc ; } ";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
parser.block();
}
@Test
public void testCombine() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = " abc{int <- abc ; }\nxyz<-true ";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
parser.program();
// parser.assign();
}
@Test
public void testParamDec() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = " \nurl\nabc_1578 ";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
parser.paramDec();
}
@Test
public void testDec() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = " frame\n \n \n _$56 ";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
parser.dec();
}
@Test
public void testWhile() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = " _$ {while(true){}} ";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
parser.program();
}
@Test
public void testIf() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = " _$ {if(true){}} ";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
parser.program();
}
@Test
public void testExpression2() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = " $ {$ <- (a3<999999);} ";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
parser.program();
}
@Test
public void blockFail() throws IllegalCharException, IllegalNumberException, SyntaxException {
String input = "abc {";
Scanner scanner = new Scanner(input);
scanner.scan();
Parser parser = new Parser(scanner);
thrown.expect(Parser.SyntaxException.class);
parser.program();
}
}
|
Python
|
UTF-8
| 2,081
| 2.9375
| 3
|
[] |
no_license
|
from bottle import route, run, request
import json
import os
"""
curl -X PUT -d key=value -d key2=value2 localhost:8080/tokens/
curl -X GET localhost:8080/tokens/
"""
boardTokens = {'0' : '', '1' : '', '2' : '', '3' : '', '4' : '', '5' : '', '6' : '', '7' : '', '8' : ''}
X = "X"
O = "O"
isXAssigned = False
isOAssigned = False
@route('/')
def home():
return "home"
@route('/tokens/put/', method = 'POST')
def tokens_put():
key = request.forms.get("key")
value = request.forms.get("value")
boardTokens[key] = value;
return { "success" : True }
@route('/tokens/get/', method = 'GET')
def tokens_get():
return boardTokens
@route('/available_token/', method = "GET")
def available_token():
result = ""
global isXAssigned, isOAssigned
if not isXAssigned:
isXAssigned = True
result = X
elif not isOAssigned:
isOAssigned = True
result = O
return { "token" : result }
@route('/get_winner/', method = "GET")
def get_winner():
result = ""
T = boardTokens
if T['0'] == T['1'] and T['1'] == T['2'] and T['0'] != '':
result = T['0']
if T['3'] == T['4'] and T['4'] == T['5'] and T['3'] != '':
result = T['3']
if T['6'] == T['7'] and T['7'] == T['8'] and T['6'] != '':
result = T['6']
if T['0'] == T['3'] and T['3'] == T['6'] and T['0'] != '':
result = T['0']
if T['1'] == T['4'] and T['4'] == T['7'] and T['1'] != '':
result = T['1']
if T['2'] == T['5'] and T['5'] == T['8'] and T['2'] != '':
result = T['2']
if T['0'] == T['4'] and T['4'] == T['8'] and T['0'] != '':
result = T['0']
if T['2'] == T['4'] and T['4'] == T['6'] and T['2'] != '':
result = T['2']
# check for tie
if len(result) == 0:
tie = True
for key in boardTokens:
if boardTokens[key] == '':
tie = False
break
if tie:
result = "None"
return { "winner" : result }
run(host='localhost', port=8080, debug=True)
|
Markdown
|
UTF-8
| 3,087
| 2.546875
| 3
|
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
---
title: balloonUI element
description: The optional balloonUI element is used to display a message balloon on the client computer.
keywords: ["balloonUI element Print Devices"]
topic_type:
- apiref
ms.topic: reference
api_name:
- balloonUI
api_type:
- Schema
ms.date: 09/06/2022
---
# balloonUI element
The optional **balloonUI** element is used to display a message balloon on the client computer.
The **balloonUI** element is defined in the *asyncui* namespace at this URI:
```xml
https://schemas.microsoft.com/2003/print/asyncui/v1/request
```
This resource may not be available in some languages and countries.
## Usage
```xml
<balloonUI
iconID = "xs:string"
resourceDll = "xs:string">
child elements
</balloonUI>
```
## Attributes
| Attribute | Type | Required | Description |
|--|--|--|--|
| **iconID** | xs:string | No | An optional attribute that specifies a printer icon to display in the event notification message. The attribute value specifies the location of the icon in the resource DLL. The icon must be 32 x 32 pixels in size, with any color depth. |
| **resourceDll** | xs:string | No | An optional attribute that specifies a resource DLL that contains the printer icon to display in the event notification message. This DLL should be a dependent file of the printer driver and must be present in the driver resource folder (for example, %SYSTEMROOT%\system32\spool\drivers\w32x86\3). |
## Child elements
| Element | Description |
|--|--|
| [**body**](body.md) | A required element that provides text that is displayed in the event notification message. This text should provide the user specific details about the printer event. |
| [**title**](title.md) | A required element that provides text that is displayed in the title of the event notification message. |
## Parent elements
| Element | Description |
|--|--|
| [**requestOpen**](requestopen.md) | An element that is used to open an event notification message on the client computer. |
## Remarks
If the attributes **iconID** and **resourceDll** are not specified, a generic printer icon is displayed in the balloon message. To display a custom printer icon, specify values for both attributes.
## Examples
The following code example shows how to use an interactive balloon to pass **CDATA** type data to a DLL.
```xml
<?xml version="1.0" ?>
<asyncPrintUIRequest xmlns="https://schemas.microsoft.com/2003/print/asyncui/v1/request">
<v1>
<requestOpen>
<balloonUI iconID="1" resourceDll="IHV.dll">
<title stringID="1234" resourceDll="IHV.dll" />
<body stringID="100" resourceDll="IHV.dll">
<parameter stringID="<5>" />
<parameter stringID="1002" resourceDll="IHV.dll" />
</body>
<action dll="adc.dll" entrypoint="def" />
IHV Data to pass into dll
MUST BE CDATA
</action>
</balloonUI>
</requestOpen>
</v1>
</asyncPrintUIRequest>
```
## See also
[**action**](action.md)
[**body**](body.md)
[**requestOpen**](requestopen.md)
[**title**](title.md)
|
JavaScript
|
UTF-8
| 714
| 2.5625
| 3
|
[] |
no_license
|
const { USER_LOGGED_SUCCESS, FETCH_TODO_ITEMS } = require('./type');
const initialState = {
user: {},
loading: false,
error: '',
logged: false,
};
export const loggedReduce = (state = initialState, action) => {
switch (action.type) {
case USER_LOGGED_SUCCESS:
console.log(action.payload);
return {
error: null,
loading: false,
user: action.payload, //-- storing the user data in single object
};
default:
return state;
}
};
export const todosReducer = (state = [{}], action) => {
switch (action.type) {
case FETCH_TODO_ITEMS:
console.log(action.payload);
return {
error: null,
loading: false,
items: action.payload,
};
default:
return state;
}
};
|
Python
|
UTF-8
| 232
| 2.53125
| 3
|
[] |
no_license
|
N=int(input())
W=list(map(int,input().split()))
l=[]
for i in range(1,N+1):
S1=0
S2=0
for j in range(N):
if (j+1)<=i:
S1+=W[j]
else:
S2+=W[j]
l.append(abs(S1-S2))
print(min(l))
|
C++
|
UTF-8
| 233
| 3.046875
| 3
|
[] |
no_license
|
#include "animaux.h"
//Constructeur
Animaux::Animaux(std::string nom, double poids){
this->nom = nom;
this->poids = poids;
}
//Affichage
void Animaux::afficherInfos(){
std::cout<< nom <<" ("<<poids<<" kg)"<<std::endl;
}
|
TypeScript
|
UTF-8
| 120
| 2.78125
| 3
|
[] |
no_license
|
let idade : number = 18
if (idade >= 18 && idade <= 67){
console.log("sim")
}
else{
console.log("não")
}
|
C++
|
UTF-8
| 9,847
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
/*------------------------------------------------------------------------------
* CppToolbox: LuaWrapper
* https://github.com/pirminschmid/CppToolbox
*
* Copyright (c) 2017, Pirmin Schmid, MIT license
*----------------------------------------------------------------------------*/
#include <ctime>
#include <iostream>
#include "LuaWrapper.h"
namespace lua {
LuaWrapper::LuaWrapper() {
L_ = luaL_newstate();
luaL_openlibs(L_);
// make callback functions available in Lua
lua_register(L_, "cb_datestr2seconds", callback_datestr2seconds);
lua_register(L_, "cb_seconds2datestr", callback_seconds2datestr);
}
LuaWrapper::~LuaWrapper() {
if (L_ != nullptr) {
lua_close(L_);
L_ = nullptr;
}
}
bool LuaWrapper::loadFile(const std::string &file_name) {
int result = luaL_loadfile(L_, file_name.c_str());
lua_pcall(L_, 0, 0, 0);
return result == LUA_OK;
}
std::string LuaWrapper::getErrorString() {
std::string r = lua_tostring(L_, -1);
return r;
}
bool LuaWrapper::check(LuaWrapper::ApiType expected_type, const std::string &name) {
lua_getglobal(L_, name.c_str());
bool ok = false;
switch(expected_type) {
case kFunction:
ok = lua_isfunction(L_, -1) != 0;
break;
case kInt:
ok = lua_isinteger(L_, -1) != 0;
break;
case kDouble:
ok = lua_isnumber(L_, -1) != 0;
break;
case kString:
ok = lua_isstring(L_, -1) != 0;
break;
}
lua_pop(L_, 1);
return ok;
}
//--- variable access ------------------------------------------------------
std::string LuaWrapper::getString(const std::string &variable_name) {
lua_getglobal(L_, variable_name.c_str());
if (!lua_isstring(L_, -1)) {
std::cerr << "LuaWrapper ERROR: string variable " << variable_name << " not found" << std::endl;
return std::string("");
}
std::string r = lua_tostring(L_, -1);
lua_pop(L_, 1);
return r;
}
void LuaWrapper::setString(const std::string &variable_name, const std::string &value) {
lua_pushstring(L_, value.c_str());
lua_setglobal(L_, variable_name.c_str());
}
double LuaWrapper::getDouble(const std::string &variable_name) {
lua_getglobal(L_, variable_name.c_str());
if (!lua_isnumber(L_, -1)) {
std::cerr << "LuaWrapper ERROR: double variable " << variable_name << " not found" << std::endl;
return 0.0;
}
double r = static_cast<double>(lua_tonumber(L_, -1));
lua_pop(L_, 1);
return r;
}
void LuaWrapper::setDouble(const std::string &variable_name, double value) {
lua_pushnumber(L_, value);
lua_setglobal(L_, variable_name.c_str());
}
LuaWrapper::int_type LuaWrapper::getInt(const std::string &variable_name) {
lua_getglobal(L_, variable_name.c_str());
if (!lua_isinteger(L_, -1)) {
std::cerr << "LuaWrapper ERROR: integer variable " << variable_name << " not found" << std::endl;
return 0;
}
int_type r = static_cast<int_type>(lua_tointeger(L_, -1));
lua_pop(L_, 1);
return r;
}
void LuaWrapper::setInt(const std::string &variable_name, LuaWrapper::int_type value) {
lua_pushinteger(L_, value);
lua_setglobal(L_, variable_name.c_str());
}
//--- function calls -------------------------------------------------------
LuaWrapper::int_type LuaWrapper::callInt2Int(const std::string &function_name, LuaWrapper::int_type arg1) {
lua_getglobal(L_, function_name.c_str());
if (!lua_isfunction(L_, -1)) {
std::cerr << "LuaWrapper ERROR: function " << function_name << " not found" << std::endl;
return 0;
}
lua_pushinteger(L_, arg1);
if (lua_pcall(L_, 1, 1, 0) != 0) {
std::cerr << "LuaWrapper ERROR: function " << function_name << ": error during execution" << std::endl;
return 0;
}
if (!lua_isinteger(L_, -1)) {
std::cerr << "LuaWrapper ERROR: function " << function_name << " did not return an integer value" << std::endl;
return 0;
}
int_type r = lua_tointeger(L_, -1);
lua_pop(L_, 1);
return r;
}
std::string LuaWrapper::callString2String(const std::string &function_name, const std::string &arg1) {
lua_getglobal(L_, function_name.c_str());
if (!lua_isfunction(L_, -1)) {
std::cerr << "LuaWrapper ERROR: function " << function_name << " not found" << std::endl;
return std::string("");
}
lua_pushstring(L_, arg1.c_str());
if (lua_pcall(L_, 1, 1, 0) != 0) {
std::cerr << "LuaWrapper ERROR: function " << function_name << ": error during execution" << std::endl;
return std::string("");
}
if (!lua_isstring(L_, -1)) {
std::cerr << "LuaWrapper ERROR: function " << function_name << " did not return a string value" << std::endl;
return std::string("");
}
std::string r = lua_tostring(L_, -1);
lua_pop(L_, 1);
return r;
}
LuaWrapper::int_type LuaWrapper::callString2Int(const std::string &function_name, const std::string &arg1) {
lua_getglobal(L_, function_name.c_str());
if (!lua_isfunction(L_, -1)) {
std::cerr << "LuaWrapper ERROR: function " << function_name << " not found" << std::endl;
return 0;
}
lua_pushstring(L_, arg1.c_str());
if (lua_pcall(L_, 1, 1, 0) != 0) {
std::cerr << "LuaWrapper ERROR: function " << function_name << ": error during execution" << std::endl;
return 0;
}
if (!lua_isinteger(L_, -1)) {
std::cerr << "LuaWrapper ERROR: function " << function_name << " did not return an integer value" << std::endl;
return 0;
}
int_type r = lua_tointeger(L_, -1);
lua_pop(L_, 1);
return r;
}
LuaWrapper::int_type LuaWrapper::callStringInt2Int(const std::string &function_name, const std::string &arg1,
LuaWrapper::int_type arg2) {
lua_getglobal(L_, function_name.c_str());
if (!lua_isfunction(L_, -1)) {
std::cerr << "LuaWrapper ERROR: function " << function_name << " not found" << std::endl;
return 0;
}
lua_pushstring(L_, arg1.c_str());
lua_pushinteger(L_, arg2);
if (lua_pcall(L_, 2, 1, 0) != 0) {
std::cerr << "LuaWrapper ERROR: function " << function_name << ": error during execution" << std::endl;
return 0;
}
if (!lua_isinteger(L_, -1)) {
std::cerr << "LuaWrapper ERROR: function " << function_name << " did not return an integer value" << std::endl;
return 0;
}
int_type r = lua_tointeger(L_, -1);
lua_pop(L_, 1);
return r;
}
std::string LuaWrapper::callStringString2String(const std::string &function_name, const std::string &arg1,
const std::string &arg2) {
lua_getglobal(L_, function_name.c_str());
if (!lua_isfunction(L_, -1)) {
std::cerr << "LuaWrapper ERROR: function " << function_name << " not found" << std::endl;
return std::string("");
}
lua_pushstring(L_, arg1.c_str());
lua_pushstring(L_, arg2.c_str());
if (lua_pcall(L_, 2, 1, 0) != 0) {
std::cerr << "LuaWrapper ERROR: function " << function_name << ": error during execution" << std::endl;
return std::string("");
}
if (!lua_isstring(L_, -1)) {
std::cerr << "LuaWrapper ERROR: function " << function_name << " did not return a string value" << std::endl;
return std::string("");
}
std::string r = lua_tostring(L_, -1);
lua_pop(L_, 1);
return r;
}
std::string LuaWrapper::callStringIntInt2String(const std::string &function_name, const std::string &arg1,
LuaWrapper::int_type arg2, LuaWrapper::int_type arg3) {
lua_getglobal(L_, function_name.c_str());
if (!lua_isfunction(L_, -1)) {
std::cerr << "LuaWrapper ERROR: function " << function_name << " not found" << std::endl;
return std::string("");
}
lua_pushstring(L_, arg1.c_str());
lua_pushinteger(L_, arg2);
lua_pushinteger(L_, arg3);
if (lua_pcall(L_, 3, 1, 0) != 0) {
std::cerr << "LuaWrapper ERROR: function " << function_name << ": error during execution" << std::endl;
return std::string("");
}
if (!lua_isstring(L_, -1)) {
std::cerr << "LuaWrapper ERROR: function " << function_name << " did not return a string value" << std::endl;
return std::string("");
}
std::string r = lua_tostring(L_, -1);
lua_pop(L_, 1);
return r;
}
int callback_datestr2seconds(lua_State *state) {
int args = lua_gettop(state);
if (args != 2) {
std::cerr << "callback_datestr2seconds(): ERROR: Need 2 arguments";
lua_pushinteger(state, 0);
return 1;
}
std::tm tm = {};
char *r = strptime(lua_tostring(state, 1), lua_tostring(state, 2), &tm);
if (r == nullptr) {
std::cerr << "callback_datestr2seconds(): ERROR. cannot convert the date using given format string" << std::endl;
lua_pushstring(state, "");
return 1;
}
std::time_t t = std::mktime(&tm);
// may be a float on some systems
lua_pushinteger(state, static_cast<int64_t >(t));
return 1; // number of arguments
}
int callback_seconds2datestr(lua_State *state) {
int args = lua_gettop(state);
if (args != 2) {
std::cerr << "callback_seconds2datestr(): ERROR: Need 2 arguments" << std::endl;
lua_pushstring(state, "");
return 1;
}
std::time_t t = static_cast<std::time_t>(lua_tointeger(state, 1));
std::tm *tm = std::localtime(&t);
char buffer[256];
std::size_t r = strftime(buffer, sizeof(buffer), lua_tostring(state, 2), tm);
if (r == 0) {
std::cerr << "callback_seconds2datestr(): ERROR. cannot convert the date using given format string" << std::endl;
lua_pushstring(state, "");
return 1;
}
lua_pushstring(state, buffer);
return 1; // number of arguments
}
}
|
Markdown
|
UTF-8
| 16,566
| 2.796875
| 3
|
[] |
no_license
|
---
layout: post
category: product
title: "Import AI 156: The 7,500 images that break image recognition systems; open source software for deleting objects from videos; and what it takes to do multilingual translation"
date: 2019-07-22 17:56:29
link: https://vrhk.co/2y3ce2w
image:
domain: jack-clark.net
author: "Jack Clark"
icon: https://s2.wp.com/i/webclip.png
excerpt: "Want 7,500 images designed to trick your object recognition system? Check out the ‘Natural Adversarial Examples’ dataset:…Can your AI system deal with these naturally occurring optical illusions?…Have you ever been fiddling in the kitchen and dropped an orange-colored ceramic knife into a pile of orange peels and temporarily lost it? I have! These kinds of visual puzzles can be confusing for humans, and are even more tricky for machines to deal with. Therefore, researchers with the University of Berkeley, the University of Washington and the University of Chicago have developed and released a dataset full of these ‘natural adversarial examples’, which should help researchers test the robustness of AI systems and develop more powerful ones.
Imagenet-A: You can get the data as an ImageNet classifier test called ImageNet-A, which consists of around 7,500 images designed to confuse and frustrate modern image recognition systems.
How hard are ‘natural adversarial examples’? Extremely hard! The researchers tested out DenseNet-121 and ResNeXt-50 models on the dataset and show that both obtain an accuracy rate of less than 3% on ImageNet-A (compared to accuracies of 97%+ on standard ImageNet). Things don’t improve much when they try to train their AI systems with techniques designed to increase robustness of classifiers, finding that using things like adversarial training, styleized imagenet augmentation, uncertainty metrics, and other approaches don’t work particularly well.
Why this matters: Being able to measure all the ways in which AI systems fail is a superpower, because such measurements can highlight the ways existing systems break and point researchers towards problems that can be worked on. I hope we’ll see more competitions that use datasets like this to test how resilient algorithms are to confounding examples. Read more: Natural Adversarial Examples (Arxiv). Get the code and the ‘IMAGENET-A’ dataset here (Natural Adversarial Examples GitHub).
####################################################
Computer, delete! Open source software for editing videos:…AI is making video-editing much cheaper and more effective…Ever wanted to pick a person or an animal or other object in a video and make it disappear? I’m sure the thought has struck some of you sometimes. Now, open source AI projects let you do just this: Video Object Removal is a new GitHub project that does what it says. The technology lets you draw a bounding box around an object in a video, and then the AI system will try to remove the person and inpaint the scene behind them. The software is based on two distinct technologies: Deep Video Inpainting, and Fast Online Object Tracking and Segmentation: A Unifying Approach.
Why this matters: Media is going to change radically as a consequence of the proliferation of AI tools like this – get ready for a world where images and video are so easy to manipulate that they become just another paintbrush, and be prepared to disbelieve everything you see online. Get the code from the GitHub page here (GitHub).
####################################################
Breaking drones to let others make smarter drones:…’ALFA” datasets gives researchers flight data for when things go wrong…Researchers with the Robotics Institute at Carnegie Mellon University have released ALFA, a dataset containing flight data and telemetry from a model plane, including data when the plane breaks. ALFA will make it easier for people to assess how well fault-spotting and fault-remediation algorithms work when exposed to real world failures.
ALFA consists of data for 47 autonomous flights with scenarios for eight different types of faults, including engine, rudder, and elevator errors. The data represents 66 minutes of normal flight and 13 minutes of post-fault flight time taking place over a mixture of fields and woodland near Pittsburgh, and there’s also a larger unprocessed dataset representing “several hours of raw autonomous, autopilot-assisted, and manual flight data with tens of different faults scenarios”.
Hardware: To collect the dataset, the researchers used a modified Carbon Z T-28 model plane, equipped with an onboard Nvidia Jetson TX2 computer, and running ‘Pixhawk’ autopilot software modified so that the researchers can remotely break the plan, generating the failure data.
Why this matters: Science tends to spend more time and resources inventing things and making forward progress on problems, rather than breaking things and casting a skeptical eye on recent events (mostly); datasets like ALFA make it easier for people to study failures, which will ultimately make it easier to develop more robust systems. Read more: ALFA: A Dataset for UAV Fault and Anomaly Detection (Arxiv). Get the ALFA data here (AIR Lab Failure and Anomaly (ALFA) Dataset website).
####################################################
How far are we from training a single AI system to translate between all languages?…Study involves 25 billion parallel sentences across 103 languages…How good are modern multilingual machine learning-based translation systems – that is, systems which can translate between a multitude of different languages, typically via using the same massive trained model? A new study from Google – which it says may be the largest ever conducted of its kind – analyzes the performance of these systems in the wild.
Data: For the study, the researchers evaluate “a massive open-domain dataset containing over 25 billion parallel sentences in 103 languages” using a large-scale machine translation system. They think that “this is the largest multilingual NMT system to date, in terms of the amount of training data and number of languages considered at the same time”. The datasets are distributed somewhat unevenly, though, reflecting the differing levels of documentation available for different languages. “The number of parallel sentences per language in our corpus ranges from around tens of thousands to almost 2 billion”, they write; there is a discrepancy of almost 5 orders of magnitude between the languages with the greatest and smallest amounts of data in the corpus. Google generated this data by crawling and extracting parallel sentences from the web, it writes.
Desirable features: An excellent multilingual translation system should have the following properties, according to the researchers:
Maximum throughput in terms of number of languages considered within a single model.
Positive transfer towards low-resource languages.
Minimum interference (negative transfer) for high-resource languages.
Models that perform well in “realistic, open-domain settings”.
When More Data Does Not Equal Better Data: One of the main findings of the study is the difficulty of training large models on such varied datasets, the researchers write. “In a large multi-task setting, high resource tasks are starved for capacity while low resource tasks benefit significantly from transfer, and the extent of interference and transfer are strongly related.” They develop some sampling techniques to train models to be more resilient to this, but find this involves its own tradeoffs between large-data and small-data languages as well. In many ways, the complexity of the task of large-scale machine translation, seems to hide subtle difficulties: “Performance degrades for all language pairs, especially the high and medium resource ones, as the number of tasks grows”, they write.
Scale: To improve performance, the researchers test our three variants of the ‘Transformer’ componen…"
---
### Import AI 156: The 7,500 images that break image recognition systems; open source software for deleting objects from videos; and what it takes to do multilingual translation
Want 7,500 images designed to trick your object recognition system? Check out the ‘Natural Adversarial Examples’ dataset:…Can your AI system deal with these naturally occurring optical illusions?…Have you ever been fiddling in the kitchen and dropped an orange-colored ceramic knife into a pile of orange peels and temporarily lost it? I have! These kinds of visual puzzles can be confusing for humans, and are even more tricky for machines to deal with. Therefore, researchers with the University of Berkeley, the University of Washington and the University of Chicago have developed and released a dataset full of these ‘natural adversarial examples’, which should help researchers test the robustness of AI systems and develop more powerful ones.
Imagenet-A: You can get the data as an ImageNet classifier test called ImageNet-A, which consists of around 7,500 images designed to confuse and frustrate modern image recognition systems.
How hard are ‘natural adversarial examples’? Extremely hard! The researchers tested out DenseNet-121 and ResNeXt-50 models on the dataset and show that both obtain an accuracy rate of less than 3% on ImageNet-A (compared to accuracies of 97%+ on standard ImageNet). Things don’t improve much when they try to train their AI systems with techniques designed to increase robustness of classifiers, finding that using things like adversarial training, styleized imagenet augmentation, uncertainty metrics, and other approaches don’t work particularly well.
Why this matters: Being able to measure all the ways in which AI systems fail is a superpower, because such measurements can highlight the ways existing systems break and point researchers towards problems that can be worked on. I hope we’ll see more competitions that use datasets like this to test how resilient algorithms are to confounding examples. Read more: Natural Adversarial Examples (Arxiv). Get the code and the ‘IMAGENET-A’ dataset here (Natural Adversarial Examples GitHub).
####################################################
Computer, delete! Open source software for editing videos:…AI is making video-editing much cheaper and more effective…Ever wanted to pick a person or an animal or other object in a video and make it disappear? I’m sure the thought has struck some of you sometimes. Now, open source AI projects let you do just this: Video Object Removal is a new GitHub project that does what it says. The technology lets you draw a bounding box around an object in a video, and then the AI system will try to remove the person and inpaint the scene behind them. The software is based on two distinct technologies: Deep Video Inpainting, and Fast Online Object Tracking and Segmentation: A Unifying Approach.
Why this matters: Media is going to change radically as a consequence of the proliferation of AI tools like this – get ready for a world where images and video are so easy to manipulate that they become just another paintbrush, and be prepared to disbelieve everything you see online. Get the code from the GitHub page here (GitHub).
####################################################
Breaking drones to let others make smarter drones:…’ALFA” datasets gives researchers flight data for when things go wrong…Researchers with the Robotics Institute at Carnegie Mellon University have released ALFA, a dataset containing flight data and telemetry from a model plane, including data when the plane breaks. ALFA will make it easier for people to assess how well fault-spotting and fault-remediation algorithms work when exposed to real world failures.
ALFA consists of data for 47 autonomous flights with scenarios for eight different types of faults, including engine, rudder, and elevator errors. The data represents 66 minutes of normal flight and 13 minutes of post-fault flight time taking place over a mixture of fields and woodland near Pittsburgh, and there’s also a larger unprocessed dataset representing “several hours of raw autonomous, autopilot-assisted, and manual flight data with tens of different faults scenarios”.
Hardware: To collect the dataset, the researchers used a modified Carbon Z T-28 model plane, equipped with an onboard Nvidia Jetson TX2 computer, and running ‘Pixhawk’ autopilot software modified so that the researchers can remotely break the plan, generating the failure data.
Why this matters: Science tends to spend more time and resources inventing things and making forward progress on problems, rather than breaking things and casting a skeptical eye on recent events (mostly); datasets like ALFA make it easier for people to study failures, which will ultimately make it easier to develop more robust systems. Read more: ALFA: A Dataset for UAV Fault and Anomaly Detection (Arxiv). Get the ALFA data here (AIR Lab Failure and Anomaly (ALFA) Dataset website).
####################################################
How far are we from training a single AI system to translate between all languages?…Study involves 25 billion parallel sentences across 103 languages…How good are modern multilingual machine learning-based translation systems – that is, systems which can translate between a multitude of different languages, typically via using the same massive trained model? A new study from Google – which it says may be the largest ever conducted of its kind – analyzes the performance of these systems in the wild.
Data: For the study, the researchers evaluate “a massive open-domain dataset containing over 25 billion parallel sentences in 103 languages” using a large-scale machine translation system. They think that “this is the largest multilingual NMT system to date, in terms of the amount of training data and number of languages considered at the same time”. The datasets are distributed somewhat unevenly, though, reflecting the differing levels of documentation available for different languages. “The number of parallel sentences per language in our corpus ranges from around tens of thousands to almost 2 billion”, they write; there is a discrepancy of almost 5 orders of magnitude between the languages with the greatest and smallest amounts of data in the corpus. Google generated this data by crawling and extracting parallel sentences from the web, it writes.
Desirable features: An excellent multilingual translation system should have the following properties, according to the researchers:
Maximum throughput in terms of number of languages considered within a single model.
Positive transfer towards low-resource languages.
Minimum interference (negative transfer) for high-resource languages.
Models that perform well in “realistic, open-domain settings”.
When More Data Does Not Equal Better Data: One of the main findings of the study is the difficulty of training large models on such varied datasets, the researchers write. “In a large multi-task setting, high resource tasks are starved for capacity while low resource tasks benefit significantly from transfer, and the extent of interference and transfer are strongly related.” They develop some sampling techniques to train models to be more resilient to this, but find this involves its own tradeoffs between large-data and small-data languages as well. In many ways, the complexity of the task of large-scale machine translation, seems to hide subtle difficulties: “Performance degrades for all language pairs, especially the high and medium resource ones, as the number of tasks grows”, they write.
Scale: To improve performance, the researchers test our three variants of the ‘Transformer’ componen…
|
C#
|
UTF-8
| 435
| 2.6875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Robots
{
public class Robot
{
public Robot(string name, int maximumBattery)
{
Name = name;
MaximumBattery = maximumBattery;
Battery = maximumBattery;
}
public string Name { get; set; }
public int Battery { get; set; }
public int MaximumBattery { get; }
}
}
|
JavaScript
|
UTF-8
| 1,736
| 2.71875
| 3
|
[] |
no_license
|
import * as PIXI from 'pixi.js';
function createCard(param) {
let stage = param.stage;
let screen = param.screen;
let position = param.position;
let stats = param.stats;
let container = new PIXI.Container();
// Создаем карту
let parity_of_parties = {
radius: 1.25,
width: 5,
height: 7
};
let card_height = screen.size.height * 0.2;
let card_width = card_height * parity_of_parties.width / parity_of_parties.height;
let card_radius = card_height * parity_of_parties.radius / parity_of_parties.height;
let card_line_thickness = card_height * 0.15 / parity_of_parties.height;
if(card_line_thickness < 1){
card_line_thickness = 1;
}
let graphics = new PIXI.Graphics();
graphics.lineStyle(card_line_thickness, 0xFF00FF, 1);
graphics.beginFill(0xFF00BB, 0.25);
graphics.drawRoundedRect(150, 200, card_width, card_height, card_radius);
graphics.endFill();
container.addChild(graphics);
let style = new PIXI.TextStyle({
fontFamily: 'Arial',
fontSize: 36,
fontStyle: 'italic',
fontWeight: 'bold',
fill: ['#ffffff', '#00ff99'], // gradient
stroke: '#4a1850',
strokeThickness: 5,
dropShadow: true,
dropShadowColor: '#000000',
dropShadowBlur: 4,
dropShadowAngle: Math.PI / 6,
dropShadowDistance: 6,
wordWrap: true,
wordWrapWidth: 440
});
let richText = new PIXI.Text('Rich text with a lot of options and across multiple lines', style);
// container.addChild(richText);
if(stage){
stage.addChild(container);
}
return graphics;
}
export default createCard;
|
JavaScript
|
UTF-8
| 431
| 3.859375
| 4
|
[] |
no_license
|
window.clear();
Array.prototype.myUsecase = function(){
var res = [];
for (var i = 0; i < this.length; i++){
res.push(this[i] * 2);
}
return this.concat(res);
}
var arr = [1, 2, 4];
console.log((arr.myUsecase()).push(1234));
console.log(arr);
String.prototype.ss = function(){
return this.toUpperCase();
}
var sst = "samplesdfsdfsdf"
console.log(sst.ss());
console.log(sst);
|
Markdown
|
UTF-8
| 1,705
| 2.5625
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
OX3-Ruby-API-Client
===================
For OpenX API access using the Ruby API Client you will need:
### 1. Your credentials:
- consumer_key,
- consumer_secret,
- email address and password for your user of your OpenX instance.
#### To use Ruby API Client:
- install ruby
<code>$ sudo apt-get install ruby</code>
### 2 Set up your environment. There are three libraries that you will need:
<code>$ sudo gem install oauth </code>
<code>$ sudo gem install json</code>
<code>$ sudo gem install awesome_print</code>
### 3. Now, being in your workspace, clone the repository:
<code>$ git clone https://github.com/openx/ODS-Ruby-API-Client.git</code>
### 4. Edit 'my_config.rb' file
- Place your credentials into the 'cfg' variables, and your request body in 'my_settings' variable.
You'll find some requests at http://openxcorporate-ui3.openxenterprise.com/data/1.0/ods.html
- If you want to know, what is the available date range for selected report, please adjust the 'date_range' variable to reflect 'my_settings".
- Adjust 'my_post_settings' variable to create a valid site/adunit etc.
#### NOTE THAT THE REQUEST BODY HAS TO BE AN ESCAPED JSON STRING
(you can use this online tool https://www.freeformatter.com/json-escape.html to escape your strings)
### 5. Run ruby scripts
- 'pull_fields.rb' to receive all available fields
<code>$ruby pull_fields.rb</code>
- 'date_range.rb' to check what is the available date range for selected report (earliest possible StartDate, closest possible EndDate)
<code>$ruby date_range.rb</code>
- 'pull_report.rb' to receive your report
<code>$ruby pull_report.rb</code>
- 'ox_post.rb' to create your adunit/site etc.
<code>$ruby ox_post.rb</code>
|
Python
|
UTF-8
| 349
| 3.203125
| 3
|
[] |
no_license
|
def formatsum(items):
out = ''
items = map(str, items)
for i in items:
if i == 'None' or i == '' or i[0] == '0':
continue
if i[0] == '-':
if out == '':
out += i
else:
out += ' - ' + i[1:]
else:
if i[0] == '+':
i = i[1:]
if out == '':
out += i
else:
out += ' + ' + i
return out if not out=='' else '0'
|
Java
|
UTF-8
| 752
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
package com.jeromewagener.game.objects.producer;
import com.jeromewagener.game.objects.GameObject;
import com.jeromewagener.game.levels.Level;
import com.jeromewagener.game.objects.particle.BloodParticle;
import com.jeromewagener.game.objects.particle.Particle;
public class Producer extends GameObject {
public static void produceDebrisParticles(Level level, int x, int y, int amount, int life) {
for (int i=0; i<amount; i++) {
level.getParticleList().add(new Particle(x, y, life));
}
}
public static void produceBloodParticles(Level level, int x, int y, int amount, int life) {
for (int i=0; i<amount; i++) {
level.getParticleList().add(new BloodParticle(x, y, life));
}
}
}
|
PHP
|
UTF-8
| 5,008
| 3.34375
| 3
|
[
"MIT"
] |
permissive
|
<!DOCTYPE html>
<html>
<head></head>
<body>
<input type="number" id="number-input" onchange="onInputChange()">
<p id="output-p">
<?php
function convertNumberToWordsForIndia($number){
$words = array(
'0'=> '' ,'1'=> 'one' ,'2'=> 'two' ,'3' => 'three','4' => 'four','5' => 'five',
'6' => 'six','7' => 'seven','8' => 'eight','9' => 'nine','10' => 'ten',
'11' => 'eleven','12' => 'twelve','13' => 'thirteen','14' => 'fouteen','15' => 'fifteen',
'16' => 'sixteen','17' => 'seventeen','18' => 'eighteen','19' => 'nineteen','20' => 'twenty',
'30' => 'thirty','40' => 'fourty','50' => 'fifty','60' => 'sixty','70' => 'seventy',
'80' => 'eighty','90' => 'ninty');
//First find the length of the number
$number_length = strlen($number);
//Initialize an empty array
$number_array = array(0,0,0,0,0,0,0,0,0);
$received_number_array = array();
//Store all received numbers into an array
for($i=0;$i<$number_length;$i++){ $received_number_array[$i] = substr($number,$i,1); }
//Populate the empty array with the numbers received - most critical operation
for($i=9-$number_length,$j=0;$i<9;$i++,$j++){ $number_array[$i] = $received_number_array[$j]; }
$number_to_words_string = "";
//Finding out whether it is teen ? and then multiplying by 10, example 17 is seventeen, so if 1 is preceeded with 7 multiply 1 by 10 and add 7 to it.
for($i=0,$j=1;$i<9;$i++,$j++){
if($i==0 || $i==2 || $i==4 || $i==7){
if($number_array[$i]=="1"){
$number_array[$j] = 10+$number_array[$j];
$number_array[$i] = 0;
}
}
}
$value = "";
for($i=0;$i<9;$i++){
if($i==0 || $i==2 || $i==4 || $i==7){ $value = $number_array[$i]*10; }
else{ $value = $number_array[$i]; }
if($value!=0){ $number_to_words_string.= $words["$value"]." "; }
if($i==1 && $value!=0){ $number_to_words_string.= "Crores "; }
if($i==3 && $value!=0){ $number_to_words_string.= "Lakhs "; }
if($i==5 && $value!=0){ $number_to_words_string.= "Thousand "; }
if($i==6 && $value!=0){ $number_to_words_string.= "Hundred & "; }
}
if($number_length>9){ $number_to_words_string = "Sorry This does not support more than 99 Crores"; }
return ucwords("INR ".strtolower($number_to_words_string)." Only.");
}
echo convertNumberToWordsForIndia(3453);
?>
</p>
<script>
function convertNumberToText(number) {
var fraction = Math.round(frac(number)*100);
var f_text = "";
if(fraction > 0) {
f_text = "AND "+convert_number(fraction)+" PAISE";
}
return "INR "+convert_number(number)+" "+f_text+" only";
}
function frac(f) {
return f % 1;
}
function convert_number(number)
{
if ((number < 0) || (number > 999999999))
{
return "NUMBER OUT OF RANGE!";
}
var Gn = Math.floor(number / 10000000); /* Crore */
number -= Gn * 10000000;
var kn = Math.floor(number / 100000); /* lakhs */
number -= kn * 100000;
var Hn = Math.floor(number / 1000); /* thousand */
number -= Hn * 1000;
var Dn = Math.floor(number / 100); /* Tens (deca) */
number = number % 100; /* Ones */
var tn= Math.floor(number / 10);
var one=Math.floor(number % 10);
var res = "";
if (Gn>0)
{
res += (convert_number(Gn) + " CRORE");
}
if (kn>0)
{
res += (((res=="") ? "" : " ") +
convert_number(kn) + " LAKH");
}
if (Hn>0)
{
res += (((res=="") ? "" : " ") +
convert_number(Hn) + " THOUSAND");
}
if (Dn)
{
res += (((res=="") ? "" : " ") +
convert_number(Dn) + " HUNDRED");
}
var ones = Array("", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX","SEVEN", "EIGHT", "NINE", "TEN", "ELEVEN", "TWELVE", "THIRTEEN","FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTEEN","NINETEEN");
var tens = Array("", "", "TWENTY", "THIRTY", "FOURTY", "FIFTY", "SIXTY","SEVENTY", "EIGHTY", "NINETY");
if (tn>0 || one>0)
{
if (!(res==""))
{
res += " AND ";
}
if (tn < 2)
{
res += ones[tn * 10 + one];
}
else
{
res += tens[tn];
if (one>0)
{
res += ("-" + ones[one]);
}
}
}
if (res=="")
{
res = "zero";
}
return res;
}
function onInputChange() {
var number = document.getElementById("number-input").value;
document.getElementById("output-p").innerHTML = convertNumberToText(number);
}
</script>
</body>
</html>
|
Go
|
UTF-8
| 562
| 2.828125
| 3
|
[] |
no_license
|
package offer
import (
"testing"
)
func Test_peakIndexInMountainArray(t *testing.T) {
tests := []struct {
arr []int
want int
}{
{[]int{1, 2, 3}, 2},
{[]int{1, 2, 1}, 1},
{[]int{3, 2, 1}, 0},
{[]int{1, 3, 5, 4, 2}, 2},
{[]int{0, 10, 5, 2}, 1},
{[]int{3, 4, 5, 1}, 2},
{[]int{24, 69, 100, 99, 79, 78, 67, 36, 26, 19}, 2},
}
for _, tt := range tests {
t.Run("test", func(t *testing.T) {
if got := peakIndexInMountainArray(tt.arr); got != tt.want {
t.Errorf("peakIndexInMountainArray() = %v, want %v", got, tt.want)
}
})
}
}
|
Python
|
UTF-8
| 2,250
| 3.109375
| 3
|
[] |
no_license
|
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
class damped_driven_pendlum():
def __init__(self):
#Some useful constants
self.c = 0.05
self.F = 0.3
self.w = 0.7
self.dt = 1e-6
self.x = [1.0]
self.v = [0.0]
self.a = []
self.t = [0.0]
self.absTime = 0.0
self.a.append(self.getA())
self.pv = []
self.px = []
self.pcnt = 1
def getX(self):
x, v, a = self.x[-1], self.v[-1], self.a[-1]
dt = self.dt
return x + v*dt + 0.5*a*dt*dt
def getV(self):
v, a = self.v[-1], self.a[-1]
dt = self.dt
return v + a*dt
def getA(self):
x, v= self.x[-1], self.v[-1]
c, F, w = self.c, self.F, self.w
absTime = self.absTime
return -c*v - np.sin(x) + F*np.cos(w*absTime)
def update(self):
self.absTime += self.dt
self.a.append(self.getA())
self.v.append(self.getV())
self.x.append(self.getX())
self.t.append(self.absTime)
pass
def simulator(self, iter_num):
for i in range(iter_num):
if(i % 50000 == 0):
print(str(100*i//iter_num) + "% done")
self.update()
if(self.w*self.t[-1] > 2*np.pi*self.pcnt):
self.pcnt += 1
self.pv.append(self.v[-1])
self.px.append(self.x[-1])
def plot(self):
mode = ["VT", "VX", "VX_P"]
fig, ax = plt.subplots(7, 3)
for i in range(7):
self.__init__()
self.F = 0.4 + 0.1*i
print("[For condition : F = " + str(self.F) + "]")
self.simulator(1000000)
for j in range(3):
if(mode[j] == "VX"):
ax[i, j].plot(self.x, self.v)
ax[i, j].set_xlim(-np.pi, np.pi)
elif(mode[j] == "VT"):
ax[i, j].plot(self.t, self.v)
ax[i, j].set_xlim(0, np.pi*20)
#ax[i, j].set_ylim(-self.v[int(21*np.pi)],self.v[int(21*np.pi)])
elif(mode[j] == "VX_P"):
ax[i, j].plot(self.px, self.pv, "o", s = 0.1)
ax[i, j].set_xlim(-np.pi, np.pi)
# Opposite Initial Condition
self.__init__()
self.F = -0.4 - 0.1*i
self.x = [-1.0]
self.v = [0.0]
self.a = [self.getA()]
print("[For condition : F = -" + str(self.F) + "]")
self.simulator(1000000)
for j in range(3):
if(mode[j] == "VX"):
ax[i, j].plot(self.x, self.v)
ax[i, j].set_xlim(-np.pi, np.pi)
plt.show()
osc = damped_driven_pendlum()
osc.plot()
|
C++
|
UTF-8
| 1,008
| 2.90625
| 3
|
[] |
no_license
|
#include<stdio.h>
#include<stdlib.h>
#include<vector>
#include<list>
#include<utility>
#include<cstdio>
using namespace std;
struct planet
{
long long int p;
int no;
};
int cmpfunc(const void *p, const void *q)
{
int l = ((struct planet *)p)->p;
int r = ((struct planet *)q)->p;
return (l - r);
}
int main()
{
int T; scanf("%d",&T);
while(T--)
{
int n,i,j; scanf("%d",&n);
struct planet p[n];
struct node* head[n];
for(i=0;i<n;i++)
{
scanf("%lld",&p[i].p);
p[i].no=i+1;
head[i]=NULL;
}
qsort(p,n,sizeof(struct planet),cmpfunc);
vector< list<int> >AL(n+1);
for(i=0;i<n-1;i++)
{
int s,e;
scanf("%d %d",&s,&e);
AL[s].push_back(e);
AL[e].push_back(s);
}
for(i=1;i<=n;i++)
AL[i].push_back(i);
for(i=1;i<=n;i++)
{
int f=n-1;
list<int>::iterator itr =AL[i].begin();
while(itr!=AL[i].end())
{
if(*itr==p[f].no)
{
itr =AL[i].begin();
f--;
}
else
++itr;
}
printf("%d ",p[f].no);
}
}
}
|
Markdown
|
UTF-8
| 4,656
| 3.28125
| 3
|
[] |
no_license
|
Todays refactoring was first coined by the [GangOfFour](http://www.dofactory.com/) and has many resources on the web that have
different usages of this pattern.
Two different aims of the factory pattern can be found on the GoF website [here](http://dofactory.com/Patterns/PatternFactory.aspx) and [here](http://dofactory.com/Patterns/PatternAbstract.aspx).
Often in code some involved setup of objects is required in order to get them into a state where we can begin working with them.
Usually this setup is nothing more than creating a new instance of the object and working with it in whatever manner we need.
Sometimes however the creation requirements of this object may grow and clouds the original code that was used to create the object.
This is where a Factory class comes into play.
For a full description of the factory pattern you can [read more here](http://en.wikipedia.org/wiki/Factory_method_pattern).
On the complex endof the factory pattern is for creating families of objects using Abstract Factory.
Our usage is on the basic end where we have one factory class creating one specific instance for us. Take a look at the code before:
```Java
public class PoliceCar {
private int mileage;
private boolean serviceRequired;
public int getMileage() {
return mileage;
}
public void setMileage(int mileage) {
this.mileage = mileage;
}
public boolean isServiceRequired() {
return serviceRequired;
}
public void setServiceRequired(boolean serviceRequired) {
this.serviceRequired = serviceRequired;
}
}
public class PoliceCarController {
public PoliceCar createPoliceCar(int mileage, boolean serviceRequired){
PoliceCar car = new PoliceCar();
car.setMileage(mileage);
car.setServiceRequired(serviceRequired);
//and some other logic as the system grows
return car;
}
}
```
As we can see, the new action is responsible for creating a PoliceCar and then setting some initial properties on the police car depending on some external input. This works fine for simple setup, but over time this can grow and the burden of creating the police car is put on the controller which isn’t really
something that the controller should be tasked with.
In this instance we can extract our creation code and place in a Factory class that has the distinct responsibility of create instances of PoliceCar’s.
```Java
public class PoliceCar {
private int mileage;
private boolean serviceRequired;
public int getMileage() {
return mileage;
}
public void setMileage(int mileage) {
this.mileage = mileage;
}
public boolean isServiceRequired() {
return serviceRequired;
}
public void setServiceRequired(boolean serviceRequired) {
this.serviceRequired = serviceRequired;
}
}
public interface PoliceCarFactory {
public PoliceCar create(int mileage, boolean serviceRequired);
}
public class PoliceCarFactoryImpl implements PoliceCarFactory {
@Override
public PoliceCar create(int mileage, boolean serviceRequired) {
PoliceCar car = new PoliceCar();
car.setMileage(mileage);
car.setServiceRequired(serviceRequired);
// and some other logic as the system grows
return car;
}
}
public class PoliceCarController {
private PoliceCarFactory policeCarFactory;
public PoliceCarController(PoliceCarFactory policeCarFactory){
this.policeCarFactory = policeCarFactory;
}
public PoliceCar createPoliceCar(int mileage, boolean serviceRequired){
return policeCarFactory.create(mileage, serviceRequired);
}
}
```
Now that we have the creation logic put off to a factory, we can add to that one class that is tasked with
creating instances for us without the worry of missing something during setup or duplicating code.
#### Original C# code from the book:
```cs
public class PoliceCarController {
public PoliceCar New(int mileage, bool serviceRequired) {
PoliceCar policeCar = new PoliceCar();
policeCar.ServiceRequired = serviceRequired;
policeCar.Mileage = mileage;
return policeCar;
}
}
//solution:
public interface IPoliceCarFactory {
PoliceCar Create(int mileage, bool serviceRequired);
}
public class PoliceCarFactory : IPoliceCarFactory {
public PoliceCar Create(int mileage, bool serviceRequired) {
PoliceCar policeCar = new PoliceCar();
policeCar.ReadForService = serviceRequired;
policeCar.Mileage = mileage;
return policeCar;
}
}
public class PoliceCarController {
public IPoliceCarFactory PoliceCarFactory { get; set; }
public PoliceCarController(IPoliceCarFactory policeCarFactory){
PoliceCarFactory = policeCarFactory;
}
public PoliceCar New(int mileage, bool serviceRequired) {
return PoliceCarFactory.Create(mileage, serviceRequired);
}
}
```
|
Java
|
UTF-8
| 2,372
| 2.390625
| 2
|
[] |
no_license
|
package com.kamingpan.infrastructure.demo.entity.constant;
import java.util.HashMap;
import java.util.Map;
/**
* 示例常量
*
* @author kamingpan
* @since 2019-04-09
*/
public class DemoConstant {
private static Map<String, String> fieldMap;
/**
* 字段解析
*
* @return 字段解析
*/
public static Map<String, String> getFieldMap() {
if (null != DemoConstant.fieldMap) {
return DemoConstant.fieldMap;
}
DemoConstant.fieldMap = new HashMap<String, String>();
DemoConstant.fieldMap.put("name", "名称");
DemoConstant.fieldMap.put("phone", "手机号码");
DemoConstant.fieldMap.put("picture", "图片");
DemoConstant.fieldMap.put("hobby", "爱好");
DemoConstant.fieldMap.put("email", "电子邮箱");
DemoConstant.fieldMap.put("status", "状态");
DemoConstant.fieldMap.put("attachment", "附件");
DemoConstant.fieldMap.put("introduction", "介绍");
DemoConstant.fieldMap.put("remark", "备注");
return DemoConstant.fieldMap;
}
/**
* 状态
*/
public static final class Status {
/**
* 正常
*/
public static final Integer ENABLE = 0;
/**
* 禁用
*/
public static final Integer DISABLE = 1;
}
/**
* 权限字符串
*/
public static final class Authentication {
/**
* 列表
*/
public static final String LIST = "hasPermission('', '" + "demo:list" + "')";
/**
* 详情
*/
public static final String INFO = "hasPermission('', '" + "demo:info" + "')";
/**
* 新增
*/
public static final String INSERT = "hasPermission('', '" + "demo:insert" + "')";
/**
* 修改
*/
public static final String UPDATE = "hasPermission('', '" + "demo:update" + "')";
/**
* 删除
*/
public static final String DELETE = "hasPermission('', '" + "demo:delete" + "')";
/**
* 启用
*/
public static final String ENABLE = "hasPermission('', '" + "demo:enable" + "')";
/**
* 禁用
*/
public static final String DISABLE = "hasPermission('', '" + "demo:disable" + "')";
}
}
|
C++
|
UTF-8
| 4,455
| 3.1875
| 3
|
[
"Apache-2.0"
] |
permissive
|
#pragma once
#include <map>
#include <list>
#include <optional>
#include <string>
#include <set>
#include <initializer_list>
#include <DataTypes/IDataType.h>
#include <Core/Names.h>
namespace DB
{
struct NameAndTypePair
{
public:
NameAndTypePair() = default;
NameAndTypePair(const String & name_, const DataTypePtr & type_)
: name(name_), type(type_), type_in_storage(type_) {}
NameAndTypePair(const String & name_in_storage_, const String & subcolumn_name_,
const DataTypePtr & type_in_storage_, const DataTypePtr & subcolumn_type_);
String getNameInStorage() const;
String getSubcolumnName() const;
bool isSubcolumn() const { return subcolumn_delimiter_position != std::nullopt; }
const DataTypePtr & getTypeInStorage() const { return type_in_storage; }
bool operator<(const NameAndTypePair & rhs) const
{
return std::forward_as_tuple(name, type->getName()) < std::forward_as_tuple(rhs.name, rhs.type->getName());
}
bool operator==(const NameAndTypePair & rhs) const
{
return name == rhs.name && type->equals(*rhs.type);
}
String dump() const;
String name;
DataTypePtr type;
private:
DataTypePtr type_in_storage;
std::optional<size_t> subcolumn_delimiter_position;
};
/// This needed to use structured bindings for NameAndTypePair
/// const auto & [name, type] = name_and_type
template <int I>
const std::tuple_element_t<I, NameAndTypePair> & get(const NameAndTypePair & name_and_type)
{
if constexpr (I == 0)
return name_and_type.name;
else if constexpr (I == 1)
return name_and_type.type;
}
/// auto & [name, type] = name_and_type
template <int I>
std::tuple_element_t<I, NameAndTypePair> & get(NameAndTypePair & name_and_type)
{
if constexpr (I == 0)
return name_and_type.name;
else if constexpr (I == 1)
return name_and_type.type;
}
using NamesAndTypes = std::vector<NameAndTypePair>;
class NamesAndTypesList : public std::list<NameAndTypePair>
{
public:
NamesAndTypesList() = default;
NamesAndTypesList(std::initializer_list<NameAndTypePair> init) : std::list<NameAndTypePair>(init) {}
template <typename Iterator>
NamesAndTypesList(Iterator begin, Iterator end) : std::list<NameAndTypePair>(begin, end) {}
void readText(ReadBuffer & buf);
void writeText(WriteBuffer & buf) const;
String toString() const;
static NamesAndTypesList parse(const String & s);
/// All `rhs` elements must be different.
bool isSubsetOf(const NamesAndTypesList & rhs) const;
/// Hamming distance between sets
/// (in other words, the added and deleted columns are counted once, the columns that changed the type - twice).
size_t sizeOfDifference(const NamesAndTypesList & rhs) const;
/// If an element changes type, it is present both in deleted (with the old type) and in added (with the new type).
void getDifference(const NamesAndTypesList & rhs, NamesAndTypesList & deleted, NamesAndTypesList & added) const;
Names getNames() const;
DataTypes getTypes() const;
/// Remove columns which names are not in the `names`.
void filterColumns(const NameSet & names);
/// Leave only the columns whose names are in the `names`. In `names` there can be superfluous columns.
NamesAndTypesList filter(const NameSet & names) const;
/// Leave only the columns whose names are in the `names`. In `names` there can be superfluous columns.
NamesAndTypesList filter(const Names & names) const;
/// Unlike `filter`, returns columns in the order in which they go in `names`.
NamesAndTypesList addTypes(const Names & names) const;
/// Check that column contains in list
bool contains(const String & name) const;
/// Try to get column by name, returns empty optional if column not found
std::optional<NameAndTypePair> tryGetByName(const std::string & name) const;
/// Try to get column position by name, returns number of columns if column isn't found
size_t getPosByName(const std::string & name) const noexcept;
};
using NamesAndTypesLists = std::vector<NamesAndTypesList>;
}
namespace std
{
template <> struct tuple_size<DB::NameAndTypePair> : std::integral_constant<size_t, 2> {};
template <> struct tuple_element<0, DB::NameAndTypePair> { using type = DB::String; };
template <> struct tuple_element<1, DB::NameAndTypePair> { using type = DB::DataTypePtr; };
}
|
Java
|
UTF-8
| 1,338
| 3.34375
| 3
|
[] |
no_license
|
package StructuralDP.CompositeDesign;
import java.util.ArrayList;
import java.util.Iterator;
/**
* Created by shalvi on 09/04/16.
*/
public class SongGroup extends SongComponent {
ArrayList songComponents;
String groupName;
String groupDescription;
public SongGroup(String newGroupName, String newGroupDescription){
this.groupDescription=newGroupDescription;
this.groupName=newGroupName;
songComponents = new ArrayList();
}
public String getGroupName() {
return groupName;
}
public String getGroupDescription() {
return groupDescription;
}
public void addComponent(SongComponent newSongComponent){
songComponents.add(newSongComponent);
}
public void removeComponent(SongComponent deleteSongComponent){
songComponents.remove(deleteSongComponent);
}
public SongComponent getComponent(int index){
return (SongComponent)songComponents.get(index);
}
public void displaySongInfo(){
System.out.println(getGroupName()+ " "+ getGroupDescription()+"\n");
Iterator songIterator = songComponents.iterator();
while(songIterator.hasNext()){
SongComponent songComponent = (SongComponent) songIterator.next();
songComponent.displaySongInfo();
}
}
}
|
Java
|
UTF-8
| 1,158
| 1.953125
| 2
|
[] |
no_license
|
package cn.t09.auth.sys.controller;
import cn.t09.auth.sys.entity.Role;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import javax.annotation.Resource;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
/**
* Created by gcjun on 2019/6/6.
*/
public class RoleControllerTest extends BaseTest{
@Resource
MetaObjectHandler handler;
@Test
public void add() throws Exception {
System.out.println(handler);
Role role = new Role();
role.setRoleName("333");
role.setRemark("333");
role.setDeptId(1L);
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders
.post("/sys/roles").contentType(MediaType.APPLICATION_JSON_UTF8)
.content(JSON.toJSONString(role));
mockMvc.perform(requestBuilder)
.andDo(MockMvcResultHandlers.print());
}
}
|
PHP
|
UTF-8
| 690
| 3.09375
| 3
|
[] |
no_license
|
<?php
/*
* Logic to delete a product from the database is here
*/
require('database.php');
$productCode = $_POST['productCode'];
if (isset($_POST['btnDeleteProduct'])) {
//write the SQL to delete a product from the database\
$query = "delete from products where productCode='$productCode'";
// wrap it in a try-catch block and use the database error page to display any
// errors
try{
//if the product is successfully deleted from the database
$db->exec($query);
//navigate to the product list page
header("Location: ./ProductList.php");
}catch(Exception $e){
echo "Encountered an exception: " . $e->getMessage();
}
}
?>
|
C
|
UTF-8
| 288
| 2.828125
| 3
|
[] |
no_license
|
#include "libft.h"
void *ft_memmove(void *s1, const void *s2, size_t n)
{
unsigned char *str;
if (!s1 || !s2)
return (NULL);
str = (unsigned char*)malloc(sizeof(*str) * n);
ft_memcpy(str, s2, n);
ft_memcpy(s1, str, n);
free(str);
return (s1);
}
|
C++
|
UTF-8
| 457
| 2.625
| 3
|
[] |
no_license
|
/**
* \file main.c
* \brief Minecraft painting generator
* \author Erik Le Normand
* \version 1.0
* \date 29/07/2014
*
* This program is a tool to create and edit the Minecraft image where are all paintings.
* These tables are decorative objects that can be seen in game.
**/
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
|
Java
|
GB18030
| 2,186
| 2.28125
| 2
|
[] |
no_license
|
package com.hospital.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.bs.model.BsAreaDomain;
import com.bs.model.BsCityDomain;
import com.hospital.service.IBsCityService;
import com.hospital.service.impl.BsCityServiceImpl;
import net.sf.json.JSONObject;
/**
* Servlet implementation class BsCityServlet
*/
@WebServlet("/bsCity.do")
public class BsCityServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//hospital_management.jspgetType
//ͬһservletҪʵֶܣҪһ־getType
String getType=req.getParameter("getType");
JSONObject jsonObject = new JSONObject();
if("city".equals(getType)) {
//hospital_manahement.jspprovinceCode
String provinceCode=req.getParameter("provinceCode");
//System.out.println("ɻȡʡ:"+provinceCode);
IBsCityService bsCityService=new BsCityServiceImpl();
List<BsCityDomain> citys= bsCityService.queryCity(provinceCode);
jsonObject.put("citys", citys);
}else if("area".equals(getType)) {
String cityCode = req.getParameter("cityCode");
IBsCityService bsCityService = new BsCityServiceImpl();
List<BsAreaDomain> areas = bsCityService.queryArea(cityCode);
jsonObject.put("areas", areas);
}
//첽ˢӦϢ
resp.setContentType("application/json; charset=utf-8");
//õӡ
PrintWriter writer=resp.getWriter();
//System.out.println(jsonObject.toString());
writer.print(jsonObject);
writer.close();
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(req, resp);
}
}
|
C++
|
UTF-8
| 1,815
| 2.921875
| 3
|
[
"MIT"
] |
permissive
|
#include <gtest/gtest.h>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
TEST(Json_nlohman, parse)
{
json array1 = json::array();
json my_json = json::array
(
{
{"Si-9.15", "RTS-9.15", "GAZP-9.15"},
{100024, 100027, 100050},
{"Futures contract for USD/RUB", "Futures contract for index RTS",
"Futures contract for Gazprom shares"}
}
);
for (unsigned long int j = 0; j < my_json.size(); j++)
{ int count = 0;
json obj = json::object();
for (unsigned long int i = 0; i < my_json.size(); i++, count++) {
switch (count)
{
case 0:
obj["ticker"] = my_json[i][j];
break;
case 1:
obj["id"] = my_json[i][j];
break;
case 2:
obj["description"] = my_json[i][j];
break;
}
}
array1.push_back(obj);
}
my_json = array1;
EXPECT_EQ(my_json[0]["ticker"], "Si-9.15");
EXPECT_EQ(my_json[1]["ticker"], "RTS-9.15");
EXPECT_EQ(my_json[2]["ticker"], "GAZP-9.15");
EXPECT_EQ(my_json[0]["id"], 100024);
EXPECT_EQ(my_json[1]["id"], 100027);
EXPECT_EQ(my_json[2]["id"], 100050);
EXPECT_EQ(my_json[0]["description"], "Futures contract for USD/RUB");
EXPECT_EQ(my_json[1]["description"], "Futures contract for index RTS");
EXPECT_EQ(my_json[2]["description"], "Futures contract for Gazprom shares");
}
|
PHP
|
UTF-8
| 813
| 2.90625
| 3
|
[] |
no_license
|
<?php
namespace App\Exceptions;
use App\Models\User;
use Exception;
use App\Models\Slack\Messenger;
use Illuminate\Support\Collection;
class SlackableException extends Exception{
/**
* @param User|Collection|string $users
* @param string $message
* @param integer $code
* @param Exception $previous
*/
public function __construct($recipient, $message, $code = 0, Exception $previous = null){
$slack = new Messenger();
if(is_string($recipient) || $recipient instanceof User) $recipient = (new Collection())->push($recipient);
if($recipient instanceof Collection){
foreach ($recipient as $user){
$slack->to($user)->send($message);
}
}
parent::__construct($message, $code, $previous);
}
}
|
C++
|
UTF-8
| 1,212
| 2.546875
| 3
|
[] |
no_license
|
#ifndef SIGNATURE_H
#define SIGNATURE_H
#include <QWidget>
namespace Ui {
class Signature;
}
class Signature : public QWidget
{
Q_OBJECT
public:
explicit Signature(QWidget *parent = nullptr);
~Signature();
void RecupererSignature(int &nbTempsT,int &nbMesureT);
void NouvelleSignature(int newNbTemps,int newNbMesure);
private:
Ui::Signature *ui;
int nbTemps;
int nbMesure;
signals:
void Valide();
private slots:
void on_pushButtonValider_clicked();
void on_toolButtonUnTemps_clicked();
void on_toolButtonDeuxTemps_clicked();
void on_toolButtonTroisTemps_clicked();
void on_toolButtonQuatreTemps_clicked();
void on_toolButtonCinqTemps_clicked();
void on_toolButtonSiTemps_clicked();
void on_toolButtonSeptTemps_clicked();
void on_toolButtonHuitTemps_clicked();
void on_toolButtonNeufTemps_clicked();
void on_toolButtonDixTemps_clicked();
void on_toolButtonOnzeTemps_clicked();
void on_toolButtonDouzeTemps_clicked();
void on_toolButtonUneMesure_clicked();
void on_toolButtonDeuxMesure_clicked();
void on_toolButtonQuatreMsure_clicked();
void on_toolButtonHuitMesure_clicked();
};
#endif // SIGNATURE_H
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.