language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
Java | UTF-8 | 2,925 | 2.109375 | 2 | [] | no_license | package com.myproject.helloandroid;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.app.*;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.content.Intent;
import android.net.Uri;
public class HelloAndroidActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello_android);
Button startBtn = (Button) findViewById(R.id.startBtn);
startBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "시작 버튼이 눌렸어요", Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(getApplicationContext(), NewActivity.class);
startActivity(myIntent);
}
});
Button start02Btn = (Button) findViewById(R.id.start02Btn);
start02Btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "경북대 접속 버튼 눌림", Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://knu.ac.kr/wbbs/"));
startActivity(myIntent);
}
});
Button start03Btn = (Button) findViewById(R.id.start03Btn);
start03Btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "전화 버튼 눌림", Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:01077881234"));
startActivity(myIntent);
}
});
Button start04Btn = (Button) findViewById(R.id.start04Btn);
start04Btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent myIntent = new Intent(getApplicationContext(), ImageActivity.class);
startActivity(myIntent);
}
});
Button start05Btn = (Button) findViewById(R.id.start05Btn);
start05Btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent myIntent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(myIntent);
}
});
Button changeLayoutBtn = (Button) findViewById(R.id.changeLayoutBtn);
changeLayoutBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent myIntent = new Intent(getApplicationContext(), ChangeLayoutActivity.class);
startActivity(myIntent);
}
});
}
} |
C# | UTF-8 | 1,930 | 3.421875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
namespace ReportRepair
{
class Program
{
private static int TargetSum = 2020;
static void Main(string[] args)
{
var exeFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var inputFile = Path.Combine(exeFolder, "input.txt");
var lines = File.ReadLines(inputFile);
var arr = lines.Select(x => int.Parse(x)).ToArray<int>();
PartOne(arr);
PartTwo(arr);
}
static void PartOne(int[] arr)
{
var seenSoFar = new HashSet<int>();
foreach (var val in arr)
{
if (seenSoFar.Contains(TargetSum - val))
{
Console.WriteLine($"{val} * {TargetSum - val} = {val * (TargetSum - val)}");
return;
}
seenSoFar.Add(val);
}
}
static void PartTwo(int[] arr)
{
Array.Sort(arr);
for (int i = 0; i < arr.Length; i++)
{
int newTargetSum = TargetSum - arr[i];
int left = 0, right = arr.Length - 1;
while (left < right)
{
if (arr[left] + arr[right] > newTargetSum)
{
right--;
}
else if (arr[left] + arr[right] < newTargetSum)
{
left++;
}
else
{
int res = arr[i] * arr[left] * arr[right];
Console.WriteLine($"{arr[i]} * {arr[left]} * {arr[right]} = {res}");
return;
}
}
}
}
}
}
|
Python | UTF-8 | 228 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | import pickle
class Dataset(list):
def __init__(self, file):
super().__init__()
if file is not None:
file = open(file, 'rb')
data = pickle.load(file)
self.extend(data)
|
TypeScript | UTF-8 | 1,809 | 2.765625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | /*
* Copyright (C) 2021 by Fonoster Inc (https://fonoster.com)
* http://github.com/fonoster/rox
*
* This file is part of Rox
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Effect } from "../@types/cerebro"
function deserializePayload(object: Record<string, any>): any {
let outputMessage = Array.isArray(object) ? [] : {};
Object.entries(object).forEach(([key, value]) => {
if (value.kind == 'structValue') {
outputMessage[key] = deserializePayload(value.structValue.fields);
} else if (value.kind == 'listValue') {
outputMessage[key] = deserializePayload(value.listValue.values);
} else if (value.kind == 'stringValue') {
outputMessage[key] = value.stringValue;
} else if (value.kind == 'boolValue') {
outputMessage[key] = value.boolValue;
} else {
outputMessage[key] = value;
}
});
return outputMessage as any
}
export function getRamdomValue(values: Record<string, string>[]) {
return values[Math.floor(Math.random() * values.length)]
}
export function transformPayloadToEffect(payload: Record<string, any>): Effect {
const o = deserializePayload(payload.fields)
const parameters = o.effect === 'say'
? { response: getRamdomValue(o.parameters.responses) }
: o.parameters
return {
type: o.effect,
parameters
}
}
|
Java | UTF-8 | 2,016 | 2 | 2 | [] | no_license | package com.tulingxueyuan.order.service.impl;
import com.tulingxueyuan.order.api.StockService;
import com.tulingxueyuan.order.mapper.OrderMapper;
import com.tulingxueyuan.order.pojo.Order;
import com.tulingxueyuan.order.service.OrderService;
import io.seata.spring.annotation.GlobalLock;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.skywalking.apm.toolkit.trace.Tag;
import org.apache.skywalking.apm.toolkit.trace.Tags;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/***
* @Author 徐庶 QQ:1092002729
* @Slogan 致敬大师,致敬未来的你
*/
@Service
public class OrderServiceImpl implements OrderService {
@Autowired
OrderMapper orderMapper;
@Autowired
StockService stockService;
/**
* 下单
* @return
*/
@GlobalTransactional
@Override
public Order create(Order order) {
// 插入能否成功?
orderMapper.insert(order);
// 扣减库存 能否成功?
stockService.reduct(order.getProductId());
// 异常
int a=1/0;
return order;
}
@Override
@Trace
@Tag(key="getAll",value="returnedObj")
public List<Order> all() throws InterruptedException {
TimeUnit.SECONDS.sleep(2);
return orderMapper.selectAll();
}
@Override
@Trace
@Tags({@Tag(key="getAll",value="returnedObj"),
@Tag(key="getAll",value="arg[0]")})
public Order get(Integer id) {
return orderMapper.selectByPrimaryKey(id);
}
}
|
PHP | UTF-8 | 3,673 | 2.703125 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace MaciejSz\Nbp\Test\Fixtures;
use MaciejSz\Nbp\CurrencyTradingRates\Domain\CurrencyTradingRate;
use MaciejSz\Nbp\CurrencyTradingRates\Domain\CurrencyTradingTable;
class FixturesRepository
{
public static function create(): self
{
return new self();
}
public function fetchJson(string $fixturePath): string
{
$contents = file_get_contents($this->getFullFixturePath($fixturePath, 'json'));
if (false === $contents) {
throw new \Exception("Cannot read fixture file: {$fixturePath}");
}
return $contents;
}
/**
* @return array<mixed>
*/
public function fetchArray(string $fixturePath): array
{
$data = json_decode($this->fetchJson($fixturePath), true);
assert(is_array($data));
return $data;
}
/**
* @return array<
* array{
* table: string,
* no: string,
* effectiveDate: string,
* rates: array<
* array{
* currency: string,
* code: string,
* mid: float
* }
* >
* }
* >
*/
public function fetchAverageTablesJson(string $table, string $from, string $to): array
{
// @phpstan-ignore-next-line
return $this->fetchArray("/api/exchangerates/tables/{$table}/{$from}/{$to}/data");
}
/**
* @return array<
* array{
* table: string,
* no: string,
* tradingDate: string,
* effectiveDate: string,
* rates: array<
* array{
* currency: string,
* code: string,
* bid: float,
* ask: float
* }
* >
* }
* >
*/
public function fetchTradingTablesJson(string $from, string $to): array
{
// @phpstan-ignore-next-line
return $this->fetchArray("/api/exchangerates/tables/C/{$from}/{$to}/data");
}
/**
* @return array<CurrencyTradingTable>
*/
public function fetchTradingTables(string $from, string $to): array
{
return require $this->getFullFixturePath("/api/exchangerates/tables/C/{$from}/{$to}/tables", 'php');
}
/**
* @return array<CurrencyTradingRate>
*/
public function fetchTradingRates(string $from, string $to): array
{
return require $this->getFullFixturePath("/api/exchangerates/tables/C/{$from}/{$to}/rates", 'php');
}
public function getFullFixturePath(string $basePath, string $fileExt): string
{
$expectedFixturesResourceDir = __DIR__ . '/../resources';
$fixturesResourceDir = realpath($expectedFixturesResourceDir);
if (false === $fixturesResourceDir) {
throw new \Exception("Fixtures resource dir is missing. Expected at: {$expectedFixturesResourceDir}");
}
$basePath = ltrim($basePath, '/');
$expectedFixtureFullPath =
$fixturesResourceDir
. "/{$basePath}"
. ((!empty($fileExt)) ? ".{$fileExt}" : '');
$fixtureFullPath = realpath($expectedFixtureFullPath);
if (false === $fixtureFullPath) {
throw new \Exception("Fixture file not found. Searched at: {$expectedFixtureFullPath}");
}
if (strpos($fixtureFullPath, $fixturesResourceDir) !== 0) {
throw new \Exception('Security breach: fixture file path cannot go above fixtures directory');
}
return $fixtureFullPath;
}
}
|
Java | UTF-8 | 4,888 | 2.359375 | 2 | [] | no_license | package com.zwq.blog.conf;
import com.zwq.blog.model.Menu;
import com.zwq.blog.model.RoleMenu;
import com.zwq.blog.model.User;
import com.zwq.blog.model.UserRole;
import com.zwq.blog.service.UserService;
import com.zwq.blog.vo.MenuVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* 自定义realm
* js中md5加密后这里进行第二次md5加密,所以数据库的密码是经过两次md5加密的
* @author zwq
* @date 2018/12/5.
*/
@Service
public class CustomRealm extends AuthorizingRealm{
@Autowired
UserService userService;
public CustomRealm() {
super.setName("customRealm");
}
/**
* 角色权限配置
* @param principals
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String userName = (String) principals.getPrimaryPrincipal();
User user = userService.getUserByUsername(userName);
List<UserRole> userRoles = userService.getRolesByUserId(user.getId());
Set<String> menus = new HashSet<String>();
Set<String> roles = new HashSet<String>();
for(UserRole userRole : userRoles){
roles.add(userRole.getRoleId()+"");
List<RoleMenu> menuList = userService.getMenuByRoles(userRole.getRoleId());
for(RoleMenu menu:menuList){
menus.add(menu.getMenuId()+"");
}
}
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
simpleAuthorizationInfo.setRoles(roles);
simpleAuthorizationInfo.setStringPermissions(menus);
return simpleAuthorizationInfo;
}
/**
* 登录配置
* @param token
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
UsernamePasswordToken upToken = (UsernamePasswordToken) token;
String userName = upToken.getUsername();
// Null username is invalid
if (userName == null) {
throw new AccountException("Null usernames are not allowed by this realm.");
}
User user = userService.getUserByUsername(userName);
if(user !=null){
List<MenuVo> menu = loadMenu(user.getId());
Session session = SecurityUtils.getSubject().getSession();
session.setAttribute("currUser",user);
session.setAttribute("menus",menu);
}
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userName, user.getPassword().toCharArray(), "customRealm");
info.setCredentialsSalt(ByteSource.Util.bytes(user.getSalt()));//加盐
return info;
}
private List<MenuVo> loadMenu(Long userId){
List<Menu> menus = userService.getMenuByUserId(userId);
List<MenuVo> list = new ArrayList<>();
for(Menu menu : menus){
if(menu.getParentId()==0){
//一级菜单
MenuVo parentMenu = new MenuVo();
parentMenu.setTitle(menu.getMenuName());
parentMenu.setIcon(menu.getIcon());
parentMenu.setSpread(false);
parentMenu.setHref(menu.getHref());
List<MenuVo> childList = new ArrayList<>();
for(Menu child : menus){
if(child.getParentId() == menu.getId()){
MenuVo childMenu = new MenuVo();
childMenu.setTitle(child.getMenuName());
childMenu.setIcon(child.getIcon());
childMenu.setSpread(false);
childMenu.setHref(child.getHref());
childList.add(childMenu);
}
}
parentMenu.setChildren(childList);
list.add(parentMenu);
}
}
return list;
}
public static void main(String[] args) {
Md5Hash md5Hash = new Md5Hash("1234"+"1qjjfei23@#jfSSjSS");
System.out.println(md5Hash.toString());//8562e6676b93e233dfad344ea1bc3e33
Md5Hash md5Has2h = new Md5Hash(md5Hash.toString(),"!QAZ@WSX#EDC");
System.out.println(md5Has2h.toString());//3d91615d1db44863c5dd41c11195c43b
}
}
|
C++ | UTF-8 | 3,186 | 2.75 | 3 | [] | no_license | #include "Memory.h"
#include "types.h"
#include "Optable.h"
#include <iterator>
namespace KNVM {
size_t OFFSET_CODE = 0x1000;
size_t OFFSET_DATA = 0x4000;
size_t OFFSET_STACK = 0x8000;
size_t MAX_MEMORY_SIZE = 0xc000;
void * _Public Memory::get() { return address; }
DWORD _Public Memory::getAlign() const { return align; }
DWORD _Public Memory::getSize() const { return size; }
DWORD _Public Memory::getCodeSize() const { return codesize; }
void _Public Memory::setCodeSize(DWORD codesize) { this->codesize = codesize; }
DWORD _Public Memory::getDataSize() const { return datasize; }
void _Public Memory::setDataSize(DWORD datasize) { this->datasize = datasize; }
Memory _Public Memory::getCodePage() const { return Memory((void *)((BYTE *)address + OFFSET_CODE), codesize); }
Memory _Public Memory::getDataPage() const { return Memory((void *)((BYTE *)address + OFFSET_DATA), datasize); }
Memory _Public Memory::getStackPage() const { return Memory((void *)((BYTE *)address + OFFSET_STACK), MAX_MEMORY_SIZE - OFFSET_STACK); }
Memory & _Public Memory::operator=(Memory &mem) {
if (address != nullptr)
VirtualFree(address, size, MEM_DECOMMIT);
this->address = mem.address;
this->size = mem.size;
this->protect = mem.protect;
return *this;
}
void * _Public Memory::operator+(DWORD range) { return (void *)((DWORD)address + range); }
void * _Public Memory::operator-(DWORD range) { return (void *)((DWORD)address - range); }
void * _Public Memory::operator++() {
address = (void *)((DWORD)address + align);
if ((DWORD)address > (DWORD)baseaddr + size)
throw "Memory Exceeded";
return address;
}
void * _Public Memory::operator--() {
address = (void *)((DWORD)address - align);
if ((DWORD)address < (DWORD)baseaddr)
throw "Memory Top Reached";
return address;
}
void * _Public Memory::operator+=(DWORD p) {
address = (void *)((DWORD)address + align * p);
if ((DWORD)address > (DWORD)baseaddr + size)
throw "Memory Exceeded";
return address;
}
void * _Public Memory::operator-=(DWORD p) {
address = (void *)((DWORD)address - align * p);
if ((DWORD)address < (DWORD)baseaddr)
throw "Memory Top Reached";
return address;
}
Memory &_Public Memory::operator+=(Asm asmbly) {
BYTE *code = (BYTE *)address + codesize;
std::memcpy(code, asmbly.code, asmbly.codesize);
codesize += asmbly.codesize;
return *this;
}
Memory &_Public Memory::operator+=(Function &func) {
DWORD size = func.getSize();
auto funcname = func.getName();
auto funcasmbly = func.getAsmbly();
BYTE *code = (BYTE *)address + codesize;
func.setBase(code);
for (auto iter = funcasmbly.begin(); iter != funcasmbly.end(); iter++) {
if (code + iter->codesize > (BYTE *)address + this->size)
throw "Code Memory Exceeded";
std::memcpy(code, iter->code, iter->codesize);
code += iter->codesize;
codesize += iter->codesize;
}
funcmap.insert(std::pair<std::string, Function>(funcname, func));
return *this;
}
Memory &_Public Memory::operator+=(char *ptr) {
datasize += snprintf((char *)address + datasize, size, "%s", ptr);
*((char *)address + datasize) = 0x00;
datasize++;
return *this;
}
} |
Java | UTF-8 | 419 | 1.71875 | 2 | [] | no_license | package com.sjw.wjs.module_login_mvp.module;
/**
* =========================================
* Author : yinshengpan
* Email : yinshp0423@163.com
* Created date : 2018/3/15 14:59
* Describe :
* ==========================================
*/
public interface ILoginModule {
//检查用户名是否为空
boolean checkNullUser(String name);
//检查密码是否为空
boolean checkNullPsd(String psd);
}
|
PHP | UTF-8 | 3,117 | 2.515625 | 3 | [
"Apache-2.0",
"MIT"
] | permissive | <?php
namespace MauticPlugin\MauticGSBundle\Google\google_api_php_client\src\Google\Service;
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* The "icons" collection of methods.
* Typical usage is:
* <code>
* $mapsengineService = new Google_Service_MapsEngine(...);
* $icons = $mapsengineService->icons;
* </code>
*/
class Google_Service_MapsEngine_ProjectsIcons_Resource extends Google_Service_Resource
{
/**
* Create an icon. (icons.create)
*
* @param string $projectId The ID of the project.
* @param Google_Icon $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_MapsEngine_Icon
*/
public function create($projectId, Google_Service_MapsEngine_Icon $postBody, $optParams = array())
{
$params = array('projectId' => $projectId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('create', array($params), "Google_Service_MapsEngine_Icon");
}
/**
* Return an icon or its associated metadata (icons.get)
*
* @param string $projectId The ID of the project.
* @param string $id The ID of the icon.
* @param array $optParams Optional parameters.
* @return Google_Service_MapsEngine_Icon
*/
public function get($projectId, $id, $optParams = array())
{
$params = array('projectId' => $projectId, 'id' => $id);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "Google_Service_MapsEngine_Icon");
}
/**
* Return all icons in the current project (icons.listProjectsIcons)
*
* @param string $projectId The ID of the project.
* @param array $optParams Optional parameters.
*
* @opt_param string pageToken The continuation token, used to page through
* large result sets. To get the next page of results, set this parameter to the
* value of nextPageToken from the previous response.
* @opt_param string maxResults The maximum number of items to include in a
* single response page. The maximum supported value is 50.
* @return Google_Service_MapsEngine_IconsListResponse
*/
public function listProjectsIcons($projectId, $optParams = array())
{
$params = array('projectId' => $projectId);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_MapsEngine_IconsListResponse");
}
} |
Java | UTF-8 | 2,630 | 2.375 | 2 | [
"Apache-2.0"
] | permissive | package com.study.study1.job;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author jiayq
* @Date 2020-11-05
*/
@Configuration
@EnableBatchProcessing
public class HelloJobConf {
@Autowired
public JobBuilderFactory jobBuilderFactory;
@Autowired
public StepBuilderFactory stepBuilderFactory;
private AtomicInteger atomicInteger = new AtomicInteger();
@Bean
public Job helloJob(Step step1) {
return jobBuilderFactory.get("importUserJob")
.incrementer(new RunIdIncrementer())
.flow(step1)
.end()
.build();
}
@Bean
public Step step1(ItemReader reader, ItemWriter writer, ItemProcessor processor) {
return stepBuilderFactory.get("step1")
.chunk(10)
.reader(reader)
.processor(processor)
.writer(writer)
.build();
}
@Bean
public ItemReader reader() {
return new ItemReader() {
@Override
public Object read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException {
if (atomicInteger.intValue() > 20){
return null;
}
System.out.println("reader : hello");
return "hello" + atomicInteger.incrementAndGet();
}
};
}
@Bean
public ItemWriter writer() {
return new ItemWriter() {
@Override
public void write(List items) throws Exception {
items.stream().forEach(x -> System.out.println("writer : " + x));
}
};
}
@Bean
public ItemProcessor processor() {
return new ItemProcessor() {
@Override
public Object process(Object item) throws Exception {
System.out.println("process : " + item);
return item;
}
};
}
}
|
C# | UTF-8 | 14,640 | 2.9375 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Abstractions.Enums;
using CS_Project;
namespace CS_Project.AditionalMethods
{
public static class CreatePPObj
{
#region CreatePlane
public static KeyValuePair<int, Plane> CreatePlane()
{
Plane newPlane = new Plane();
int key = 0;
try
{
Console.Clear();
Console.WriteLine("Building plane...");
Console.WriteLine("===================================");
key = CreatePlaneNumber();
Console.WriteLine("===================================");
newPlane.timeIn = DateTime.Now;
newPlane.timeOut = DateTime.Now;
TimeOut(key, newPlane);
//this.timeOut = this.timeOut.AddHours(3);
// ==================================================
newPlane.city = CreateCity();
Console.WriteLine("===================================");
AddAirline(newPlane);
Console.WriteLine("===================================");
AddTerminal(newPlane);
Console.WriteLine("===================================");
AddStatus(newPlane);
Console.WriteLine("===================================");
Console.Write("Enter gate code: ");
newPlane.gate = Console.ReadLine().Replace(" ", "");
Console.WriteLine("===================================");
Console.WriteLine("Press enter to continue...");
Console.ReadLine();
Console.Clear();
}
catch (Exception)
{
Console.WriteLine();
Console.WriteLine("Input correct data!");
Console.WriteLine("Press enter to continue...");
Console.ReadLine();
CreatePlane();
}
SpawnPassengers(key, newPlane);
return new KeyValuePair<int, Plane>(key, newPlane);
}
public static void SpawnPassengers(int keyPlane, Plane plane)
{
switch (plane.airline)
{
case Airline.UkraineInternationalAirlines:
plane.count = 25;
break;
case Airline.Windrose:
plane.count = 20;
break;
case Airline.SkyUpAirlines:
plane.count = 35;
break;
case Airline.AzurAirUkraine:
plane.count = 30;
break;
default:
Console.WriteLine("Error");
break;
}
for (int i = 0; i < plane.count; i++)
{
plane.Add(CreatePassportNum(i), CreatePassanger(keyPlane, i, plane.airline));
}
}
#region SubsidiaryMethod
static void TimeOut(int numm, Plane plane)
{
Random rnd = new Random(numm);
var num = rnd.Next(0, 3);
switch (num)
{
case 1:
{ plane.timeOut = plane.timeOut.AddMinutes(15); break; }
case 2:
{ plane.timeOut = plane.timeOut.AddMinutes(30); break; }
case 3:
{ plane.timeOut = plane.timeOut.AddMinutes(90); break; }
default:
{ plane.timeOut = plane.timeOut.AddMinutes(120); break; }
}
}
static int CreatePlaneNumber()
{
int key = 0;
try
{
Console.Write("Enter plane number: ");
key = Convert.ToInt32(Console.ReadLine().Replace(" ", ""));
}
catch (FormatException)
{
Console.WriteLine();
Console.WriteLine("Enter correct plane number!!!");
Console.WriteLine();
key = CreatePlaneNumber();
}
return key;
}
static string CreateCity()
{
string str = "Default";
try
{
Console.Write("Enter plane city: ");
str = Console.ReadLine().Replace(" ", "");
if (str == "")
{
throw new FormatException();
}
}
catch (FormatException)
{
Console.WriteLine();
Console.WriteLine("Enter correct city!!!");
Console.WriteLine();
str = CreateCity();
}
return str;
}
static void AddAirline(Plane plane)
{
try
{
Console.WriteLine("Choose airline:");
for (int i = 1; i <= Enum.GetNames(typeof(Airline)).Length; i++) // how it work: Enum.GetNames(typeof(Airline)).Length?
{
Console.WriteLine("{0}. {1}", i, Enum.GetName(typeof(Airline), i));
}
Console.Write("Enter number of Airline company: ");
var num = Convert.ToInt32(Console.ReadLine());
if (num > 4 || num < 1)
{
throw new FormatException();
}
switch (num)
{
case (int)Airline.UkraineInternationalAirlines:
{ plane.airline = Airline.UkraineInternationalAirlines; break; }
case (int)Airline.Windrose:
{ plane.airline = Airline.Windrose; break; }
case (int)Airline.SkyUpAirlines:
{ plane.airline = Airline.SkyUpAirlines; break; }
case (int)Airline.AzurAirUkraine:
{ plane.airline = Airline.AzurAirUkraine; break; }
default:
{ plane.airline = Airline.UkraineInternationalAirlines; break; }
}
}
catch (FormatException)
{
Console.WriteLine();
Console.WriteLine("Enter num from 1 to 4!!!");
Console.WriteLine();
AddAirline(plane);
}
}
static void AddTerminal(Plane plane)
{
try
{
Console.WriteLine("Choose terminal:");
for (int i = 1; i <= Enum.GetNames(typeof(Terminal)).Length; i++) // how it work: Enum.GetNames(typeof(Airline)).Length?
{
Console.WriteLine("{0}. {1}", i, Enum.GetName(typeof(Terminal), i));
}
Console.Write("Enter number of terminal: ");
var num = Convert.ToInt32(Console.ReadLine());
if (num > 4 || num < 1)
{
throw new FormatException();
}
switch (num)
{
case (int)Terminal.A:
{ plane.terminal = Terminal.A; break; }
case (int)Terminal.B:
{ plane.terminal = Terminal.B; break; }
case (int)Terminal.C:
{ plane.terminal = Terminal.C; break; }
case (int)Terminal.D:
{ plane.terminal = Terminal.D; break; }
default:
{ plane.terminal = Terminal.A; break; }
}
}
catch (FormatException)
{
Console.WriteLine();
Console.WriteLine("Enter num from 1 to 4!!!");
Console.WriteLine();
AddTerminal(plane);
}
}
static void AddStatus(Plane plane)
{
try
{
Console.WriteLine("Choose plane status:");
for (int i = 1; i <= Enum.GetNames(typeof(Status)).Length; i++) // how it work: Enum.GetNames(typeof(Airline)).Length?
{
Console.WriteLine("{0}. {1}", i, Enum.GetName(typeof(Status), i));
}
Console.Write("Enter number of plane status: ");
var num = Convert.ToInt32(Console.ReadLine());
if (num > 9 || num < 1)
{
throw new FormatException();
}
switch (num)
{
case (int)Status.CheckIn:
{ plane.status = Status.CheckIn; break; }
case (int)Status.GateClosed:
{ plane.status = Status.GateClosed; break; }
case (int)Status.Arrived:
{ plane.status = Status.Arrived; break; }
case (int)Status.DepartedAt:
{ plane.status = Status.DepartedAt; break; }
case (int)Status.Unknown:
{ plane.status = Status.Unknown; break; }
case (int)Status.Canceled:
{ plane.status = Status.Canceled; break; }
case (int)Status.ExpectedAt:
{ plane.status = Status.ExpectedAt; break; }
case (int)Status.Delayed:
{ plane.status = Status.Delayed; break; }
case (int)Status.InFlight:
{ plane.status = Status.InFlight; break; }
default:
{ plane.status = Status.Arrived; break; }
}
}
catch (FormatException)
{
Console.WriteLine();
Console.WriteLine("Enter num from 1 to 9!!!");
Console.WriteLine();
AddStatus(plane);
}
}
static string CreateGate()
{
string str = "Default";
try
{
Console.Write("Enter gate code: ");
str = Console.ReadLine().Replace(" ", "");
}
catch (FormatException)
{
Console.WriteLine();
Console.WriteLine("Enter correct gate!!");
Console.WriteLine();
str = CreateGate();
}
return str;
}
#endregion
#endregion
#region CreatePassangers
static Passenger CreatePassanger(int planeNum, int n, Airline airline)
{
Passenger newPass = new Passenger();
newPass.planeNum = planeNum;
newPass.airline = airline;
AddPropData(n, newPass);
return newPass;
}
#region SubsidiaryMethod
static void AddPropData(int n, Passenger passenger)
{
AddName(n, passenger);
AddSecondName(n, passenger);
AddNationality(n, passenger);
AddSex(n, passenger);
AddClassF(n, passenger);
AddDate(n, passenger);
AddPrice(passenger);
}
static void AddName(int n, Passenger passenger)
{
string[] arr = new string[] { "Max", "Jack", "James", "Kobe", "Michel" };
passenger.name = arr[new Random(n * n).Next(0, arr.Length)];
}
static void AddSecondName(int n, Passenger passenger)
{
string[] arr = new string[] { "Lukashevich", "Sparrow", "LeBron", "Bryant", "Jordan" };
passenger.secondName = arr[new Random(n).Next(0, arr.Length)];
}
static void AddNationality(int n, Passenger passenger)
{
string[] arr = new string[] { "Ukrain", "EU", "Japan", "USA", "Moldova" };
passenger.nationality = arr[new Random(n).Next(0, arr.Length)];
}
static int CreatePassportNum(int n)
{
//string[] arr = new string[] { "AA", "AE", "DQ", "GG", "WP" };
//return arr[new Random(n + 100).Next(0, arr.Length)] +
// new Random(n + 111).Next(100, 999) +
// arr[new Random(n + 222).Next(0, arr.Length)];
return new Random(n + 111).Next(1000, 9999);
}
static void AddSex(int n, Passenger passenger)
{
Sex[] arr = new Sex[] { Sex.Female, Sex.Male };
passenger.sex = arr[new Random(n).Next(0, arr.Length)];
}
static void AddClassF(int n, Passenger passenger)
{
Class[] arr = new Class[] { Class.Business, Class.Econom };
passenger.classF = arr[new Random(n).Next(0, arr.Length)];
}
static void AddDate(int n, Passenger passenger)
{
int day = new Random(n * 2).Next(1, 29);
int month = new Random(n * 3).Next(1, 12);
int year = new Random(n * 4).Next(1940, 2021);
passenger.dateOfBirthday = new DateTime(year, month, day);
}
static void AddPrice(Passenger passenger)
{
var price = (int)passenger.classF;
switch (passenger.airline)
{
case Airline.UkraineInternationalAirlines:
if (passenger.classF == Class.Business)
price += 5000;
else
price += 1000;
break;
case Airline.Windrose:
if (passenger.classF == Class.Business)
price += 55;
else
price += 15;
break;
case Airline.SkyUpAirlines:
if (passenger.classF == Class.Business)
price += 2555;
else
price += 1999;
break;
case Airline.AzurAirUkraine:
if (passenger.classF == Class.Business)
price += 228;
else
price += 322;
break;
default:
price += 1000;
break;
}
passenger.price = price;
}
#endregion
#endregion
}
}
|
JavaScript | UTF-8 | 155 | 3.171875 | 3 | [] | no_license | //P4-Coin flip
const HEAD=1;
let coinFlip=Math.floor(Math.random()*10)%2;
if(coinFlip==HEAD)
{
console.log("Head");
}
else
{
console.log("Tail");
} |
Python | UTF-8 | 1,166 | 2.703125 | 3 | [] | no_license | #!/bin/python3
from os import sys
from os import sys
import calcul
def intConvertisser(intStr):
try:
result = int(intStr)
except:
quit (84)
return result
def parser():
if (len(sys.argv) != 5):
quit (84)
nb = intConvertisser(sys.argv[1])
arithmMean = intConvertisser(sys.argv[2])
harmoMean = intConvertisser(sys.argv[3])
stdDev = intConvertisser(sys.argv[4])
if (harmoMean <= 0 or stdDev < 0 or nb < 0):
quit (84)
return nb, arithmMean, harmoMean, stdDev
def getNextValue():
print("Enter next value:", end=' ', flush=True)
line = sys.stdin.readline()
if (line == "END\n"):
quit (0)
try:
value = int(line)
except:
quit (84)
return value
nb, arithmMean, harmoMean, stdDev = parser()
value = 0
while (1):
value = getNextValue()
calcul.printNbValues(nb + 1)
stdDev = calcul.printStdDev(value, nb, arithmMean, stdDev)
arithmMean = calcul.printArithmMean(value, nb, arithmMean)
calcul.printQuadriMean(value, nb, arithmMean, stdDev)
harmoMean = calcul.printHarmoMean(value, nb, harmoMean)
print()
nb += 1 |
Java | UTF-8 | 4,525 | 2.265625 | 2 | [] | no_license | package org.pepo.record.service.record;
import lombok.AllArgsConstructor;
import org.pepo.record.SwaggerCodgen.model.RecordPagedResponseOpenApi;
import org.pepo.record.SwaggerCodgen.model.RecordResponseOpenApi;
import org.pepo.record.entity.Record;
import org.pepo.record.entity.Record_;
import org.pepo.record.mapper.RecordEntityOpenApiMapper;
import org.pepo.record.repository.record.RecordRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
@Service
@AllArgsConstructor
public class RecordServiceImpl implements RecordService {
@Autowired
private final RecordRepository recordRepository;
@Autowired
private final RecordEntityOpenApiMapper recordEntityOpenApiMapper;
@Override
public Iterable<RecordResponseOpenApi> findAll() {
List<RecordResponseOpenApi> list = new ArrayList<>();
Iterable<Record> recordIterable = recordRepository.findAll();
recordIterable.forEach(record -> list.add(recordEntityOpenApiMapper.recordToRecordResponseOpenApi(record)));
return list;
}
@Override
public RecordResponseOpenApi findById(final int id) {
Record record = recordRepository.findById(id).orElse(null);
return recordEntityOpenApiMapper.recordToRecordResponseOpenApi(record);
}
@Override
public RecordResponseOpenApi save(final Record record) {
return recordEntityOpenApiMapper.recordToRecordResponseOpenApi(recordRepository.save(record));
}
@Override
public RecordResponseOpenApi update(final Record record, final int recordId) {
record.setId(recordId);
return recordEntityOpenApiMapper.recordToRecordResponseOpenApi(recordRepository.save(record));
}
@Override
public void delete(final int id) {
recordRepository.deleteById(id);
}
@Override
public RecordPagedResponseOpenApi filteredRecords(final String name, final String artist, final String format, final String style,
final Integer page, final Integer size) {
List<RecordResponseOpenApi> list = new ArrayList<>();
RecordPagedResponseOpenApi responseOpenApi = new RecordPagedResponseOpenApi();
Pageable paging = PageRequest.of(page, size, Sort.by(Sort.Order.asc(Record_.NAME)));
Page<Record> recordPage = recordRepository.findFilteredRecords(name, artist, format, style, paging);
recordPage.getContent().forEach(record -> list.add(recordEntityOpenApiMapper.recordToRecordResponseOpenApi(record)));
responseOpenApi.setTotalElements(recordPage.getTotalElements());
responseOpenApi.setTotalPages(recordPage.getTotalPages());
responseOpenApi.setResult(list);
return responseOpenApi;
}
@Override
public List<RecordResponseOpenApi> findAll(final Integer page, final Integer size) {
List<RecordResponseOpenApi> list = new ArrayList<>();
List<Record> recordList;
if (page == null && size == null) {
recordList = StreamSupport.stream(recordRepository.findAll().spliterator(), false)
.collect(Collectors.toList());
}
else {
Pageable paging = PageRequest.of(page, size);
recordList = recordRepository.findAll(paging).getContent();
}
recordList.forEach(record -> list.add(recordEntityOpenApiMapper.recordToRecordResponseOpenApi(record)));
return list;
}
@Override
public RecordPagedResponseOpenApi findAllPaged(Integer page, Integer size) {
List<RecordResponseOpenApi> list = new ArrayList<>();
RecordPagedResponseOpenApi responseOpenApi = new RecordPagedResponseOpenApi();
Pageable paging = PageRequest.of(page, size);
Page<Record> recordPage = recordRepository.findAll(paging);
recordPage.getContent().forEach(record -> list.add(recordEntityOpenApiMapper.recordToRecordResponseOpenApi(record)));
responseOpenApi.setTotalElements(recordPage.getTotalElements());
responseOpenApi.setTotalPages(recordPage.getTotalPages());
responseOpenApi.setResult(list);
return responseOpenApi;
}
} |
Java | UTF-8 | 4,085 | 2.453125 | 2 | [] | no_license | import java.io.*;
import java.util.Date;
import java.util.List;
import data.Activity;
import org.apache.batik.svggen.SVGGraphics2D;
import org.apache.batik.svggen.SVGGraphics2DIOException;
import org.apache.batik.transcoder.image.JPEGTranscoder;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.dom.svg.SVGDOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.DOMImplementation;
import data.GPSData;
import travelStatistics.types.DailyPattern.PrintDailyPattern;
public class DOMRasterizer {
public Document createDocument2() throws IOException{
GPSData data = new GPSData("turkey.csv");
Date day = data.getMaxDateInFile();
DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;
Document doc = (Document)impl.createDocument(svgNS, "svg", null);
Element root = doc.getDocumentElement();
root.setAttributeNS(null, "width", "450");
root.setAttributeNS(null, "height", "500");
// Create a converter for this document.
SVGGraphics2D g = new SVGGraphics2D(doc);
List<Activity> activities = data.getDayActivities(day);
if (activities == null){
System.err.println("No data found for "+day);
return null;
}
PrintDailyPattern.print(g, activities, data.getStartingTimeInSec());
g.getRoot(root);
//Writer writer = new OutputStreamWriter(new FileOutputStream("out.svg"), "UTF-8");
//g.stream(root, writer);
//writer.close();
return doc;
}
public Document createDocument() throws SVGGraphics2DIOException, UnsupportedEncodingException {
GPSData data = new GPSData("turkey.csv");
Date day = data.getMaxDateInFile();
// Create a new document.
DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;
Document document =
impl.createDocument(svgNS, "svg", null);
Element root = document.getDocumentElement();
root.setAttributeNS(null, "width", "450");
root.setAttributeNS(null, "height", "500");
// Add some content to the document.
Element e;
e = document.createElementNS(svgNS, "rect");
e.setAttributeNS(null, "x", "10");
e.setAttributeNS(null, "y", "10");
e.setAttributeNS(null, "width", "200");
e.setAttributeNS(null, "height", "300");
e.setAttributeNS(null, "style", "fill:red;stroke:black;stroke-width:4");
root.appendChild(e);
e = document.createElementNS(svgNS, "circle");
e.setAttributeNS(null, "cx", "225");
e.setAttributeNS(null, "cy", "250");
e.setAttributeNS(null, "r", "100");
e.setAttributeNS(null, "style", "fill:green;fill-opacity:.5");
root.appendChild(e);
SVGGraphics2D g = new SVGGraphics2D(document);
PrintDailyPattern.print(g, data.getDayActivities(day), data.getStartingTimeInSec());
System.out.println(g.toString());
g.stream(new OutputStreamWriter(System.out, "UTF-8"));
return document;
}
public void save(Document document) throws Exception {
// Create a JPEGTranscoder and set its quality hint.
JPEGTranscoder t = new JPEGTranscoder();
t.addTranscodingHint(JPEGTranscoder.KEY_QUALITY,
new Float(.8));
// Set the transcoder input and output.
TranscoderInput input = new TranscoderInput(document);
OutputStream ostream = new FileOutputStream("out.jpg");
TranscoderOutput output = new TranscoderOutput(ostream);
// Perform the transcoding.
t.transcode(input, output);
ostream.flush();
ostream.close();
}
public static void main(String[] args) throws Exception {
// Runs the example.
DOMRasterizer rasterizer = new DOMRasterizer();
Document document = rasterizer.createDocument2();
rasterizer.save(document);
System.exit(0);
}
} |
Python | UTF-8 | 1,888 | 3.140625 | 3 | [] | no_license | # Write a Python Script that captures images from your webcam vide stream
# Extract all faces from the image frame(using harcascade)
# Store the information into numpy arrays
# 1. Read and show video stream, capture images
# 2. Detect Faces and show bounding box
# 3. Flatten the largest face image and save in numpy array
# 4. Repeat the above for multiple people to generate training data
import cv2
import numpy as np
# Init Camera
cap = cv2.VideoCapture(0)
# Face Detection
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
skip = 0
colected_images = 0
person_name = input()
face_data = []
while True:
ret, frame = cap.read()
if ret == False:
continue
# gray_frame can be used to save memory
# gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(frame, 1.3, 5)
faces = sorted(faces, key=lambda f: f[2]*f[3], reverse=True)
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.imshow('Frame', frame)
# Store Every 10th face
if skip % 10 == 0:
if len(faces) > 0:
lf = faces[0]
x = lf[0]
y = lf[1]
w = lf[2]
h = lf[3]
offset = 10
crop_face = frame[y-offset:y+h+offset, x-offset:x+w+offset]
cv2.imshow('Cropped Face', crop_face)
crop_face = cv2.resize(crop_face, (100, 100))
crop_face_flatten = np.reshape(crop_face, (-1,))
face_data.append(crop_face_flatten)
colected_images = colected_images+1
skip = skip+1
if colected_images == 20:
break
key_pressed = cv2.waitKey(1) & 0xFF
if key_pressed == ord('q'):
break
face_data = np.array(face_data)
np.save('./data/'+person_name+'.npy', face_data,)
cap.release()
cv2.destroyAllWindows()
|
PHP | UTF-8 | 7,548 | 2.859375 | 3 | [
"GPL-2.0-or-later",
"GPL-1.0-or-later",
"GPL-2.0-only",
"MIT",
"LicenseRef-scancode-generic-exception",
"LGPL-2.1-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-proprietary-license"
] | permissive | <?php
/**
* Progress bars widget
*
* @package vogue.
* @since 1.0.0
*/
// File Security Check
if ( ! defined( 'ABSPATH' ) ) { exit; }
/* Load the widget */
add_action( 'widgets_init', array( 'Presscore_Inc_Widgets_ProgressBars', 'presscore_register_widget' ) );
class Presscore_Inc_Widgets_ProgressBars extends WP_Widget {
/* Widget defaults */
public static $widget_defaults = array(
'title' => '',
'text' => '',
'fields' => array(),
);
/* Widget setup */
function __construct() {
/* Widget settings. */
$widget_ops = array( 'description' => _x( 'Progress bars', 'widget', 'the7mk2' ) );
/* Widget control settings. */
$control_ops = array( 'width' => 260 );
/* Create the widget. */
parent::__construct(
'presscore-progress-bars-widget',
DT_WIDGET_PREFIX . _x( 'Progress bars', 'widget', 'the7mk2' ),
$widget_ops,
$control_ops
);
}
/* Display the widget */
function widget( $args, $instance ) {
extract( $args );
$instance = wp_parse_args( (array) $instance, self::$widget_defaults );
/* Our variables from the widget settings. */
$title = apply_filters( 'widget_title', $instance['title'] );
$text = $instance['text'];
$fields = $instance['fields'];
/* translators: progress bar percents */
$percent_text = __( '%d%', 'the7mk2' );
echo $before_widget ;
// title
if ( $title ) {
echo $before_title . $title . $after_title;
}
// content
if ( $text ) {
echo '<div class="widget-info">' . apply_filters('get_the_excerpt', $text) . '</div>';
}
// fields
if ( !empty($fields) ) {
echo '<div class="skills animate-element">';
foreach ( $fields as $field ) {
$percent_field = sprintf( $percent_text, $field['percent'] );
if ( !empty($field['title']) || !empty($field['show_percent']) ) {
printf(
'<div class="skill-name">%s%s</div>',
$field['title'],
empty($field['show_percent']) ? '' : '<span>' . $percent_field . '</span>'
);
}
$field['percent'] = absint($field['percent']);
if ( $field['percent'] > 100 ) $field['percent'] = 100;
$style = '';
if ( $field['color'] ) {
$style = ' style="background-color: ' . esc_attr($field['color']) . '"';
}
printf(
'<div class="skill"><div class="skill-value" data-width="%d"%s></div></div>',
$field['percent'],
$style
);
}
echo '</div>';
}
echo $after_widget;
}
/* Update the widget settings */
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
$instance['text'] = $new_instance['text'];
$instance['fields'] = $this->presscore_validate_fields( $new_instance['fields'] );
return $instance;
}
/**
* Displays the widget settings controls on the widget panel.
* Make use of the get_field_id() and get_field_name() function
* when creating your form elements. This handles the confusing stuff.
*/
function form( $instance ) {
/* Set up some default widget settings. */
$instance = wp_parse_args( (array) $instance, self::$widget_defaults );
$fields = empty( $instance['fields'] ) ? array() : $instance['fields'];
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _ex('Title:', 'widget', 'the7mk2'); ?></label>
<input type="text" id="<?php echo $this->get_field_id( 'title' ); ?>" class="widefat" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo esc_attr($instance['title']); ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id( 'text' ); ?>"><?php _ex('Text:', 'widget', 'the7mk2'); ?></label>
<textarea id="<?php echo $this->get_field_id( 'text' ); ?>" rows="10" class="widefat" name="<?php echo $this->get_field_name( 'text' ); ?>"><?php echo esc_textarea($instance['text']); ?></textarea>
</p>
<h4><?php _ex('Fields:', 'widget', 'the7mk2'); ?></h4>
<div class="dt-widget-sortable-container">
<ul class="dt-widget-sortable dt-widget-progress-bar ui-sortable"><?php
foreach ( $fields as $index=>$field ) :
$field['color2'] = '#ffffff';
?>
<li class="ui-state-default" data-index="<?php echo $index; ?>">
<a href="javascript:void(0);" class="dt-widget-sortable-remove"></a>
<input type="text" name="<?php echo $this->get_field_name( 'fields' ) . "[$index]"; ?>[title]" placeholder="<?php echo esc_attr( __( 'Title', 'the7mk2' ) ); ?>" value="<?php echo esc_attr( $field['title'] ); ?>" /><br />
<input type="text" max="100" min="0" size="8" name="<?php echo $this->get_field_name( 'fields' ) . "[$index]"; ?>[percent]" placeholder="<?php echo esc_attr( __( 'Percent', 'the7mk2' ) ); ?>" value="<?php echo esc_attr( $field['percent'] ); ?>" />
<label><input type="checkbox" name="<?php echo $this->get_field_name( 'fields' ) . "[$index]"; ?>[show_percent]" value="1" <?php checked($field['show_percent']); ?> /> <?php echo esc_attr( __( 'Show', 'the7mk2' ) ); ?></label><br />
<input type="text" name="<?php echo $this->get_field_name( 'fields' ) . "[$index]"; ?>[color]" value="<?php echo esc_attr( $field['color'] ); ?>" class="dt-widget-colorpicker" />
<input type="text" name="<?php echo $this->get_field_name( 'fields' ) . "[$index]"; ?>[color2]" value="<?php echo esc_attr( $field['color2'] ); ?>" class="dt-widget-colorpicker" />
</li>
<?php endforeach;
?></ul>
<a href="javascript:void(0);" class="dt-widget-sortable-add button" data-fields-name="<?php echo $this->get_field_name( 'fields' ); ?>" data-field-type="progress-bar"><?php _ex( 'Add', 'widget', 'the7mk2' ); ?></a>
</div>
<div style="clear: both;"></div>
<?php
}
function presscore_validate_fields( $fields ) {
$allowed_fields = $field_defaults = array(
'title' => '',
'percent' => 100,
'show_percent' => true,
'color' => ''
);
unset( $field_defaults['show_percent'] );
foreach ( $fields as &$field ) {
$field = array_intersect_key($field, $allowed_fields);
$field = wp_parse_args($field, $field_defaults);
$field['percent'] = absint($field['percent']);
if ( $field['percent'] > 100 ) $field['percent'] = 100;
$field['show_percent'] = isset($field['show_percent']);
$field['title'] = esc_html($field['title']);
$field['color'] = esc_attr($field['color']);
}
unset($field);
return $fields;
}
public static function presscore_register_widget() {
register_widget( get_class() );
add_action( 'admin_footer', array(__CLASS__, 'presscore_admin_add_widget_templates') );
}
/**
* Add template for widget.
*/
public static function presscore_admin_add_widget_templates() {
if ( 'widgets.php' != $GLOBALS['hook_suffix'] ) {
return;
}
?>
<script type="text/html" id="tmpl-dt-widget-progress-bars-field">
<li class="ui-state-default" data-index="{{ data.nextIndex }}">
<a href="javascript:void(0);" class="dt-widget-sortable-remove"></a>
<input type="text" name="{{ data.fieldsName }}[{{ data.nextIndex }}][title]" placeholder="{{ data.title }}" value="" /><br />
<input type="text" max="100" min="0" size="8" name="{{ data.fieldsName }}[{{ data.nextIndex }}][percent]" placeholder="{{ data.percent }}" value="" />
<label><input type="checkbox" name="{{ data.fieldsName }}[{{ data.nextIndex }}][show_percent]" value="1" checked="checked" /> {{ data.showPercent }}</label><br />
<input type="text" name="{{ data.fieldsName }}[{{ data.nextIndex }}][color]" value="" class="dt-widget-colorpicker" />
</li>
</script>
<?php
}
}
|
PHP | UTF-8 | 976 | 2.65625 | 3 | [] | no_license | <?php
namespace Varspool\JobAdder\V2\Model;
class SubmitEmploymentModel
{
/**
* @var SubmitCurrentEmploymentModel
*/
protected $current;
/**
* @var SubmitIdealEmploymentModel
*/
protected $ideal;
/**
* @return SubmitCurrentEmploymentModel
*/
public function getCurrent()
{
return $this->current;
}
/**
* @param SubmitCurrentEmploymentModel $current
*
* @return self
*/
public function setCurrent(SubmitCurrentEmploymentModel $current = null)
{
$this->current = $current;
return $this;
}
/**
* @return SubmitIdealEmploymentModel
*/
public function getIdeal()
{
return $this->ideal;
}
/**
* @param SubmitIdealEmploymentModel $ideal
*
* @return self
*/
public function setIdeal(SubmitIdealEmploymentModel $ideal = null)
{
$this->ideal = $ideal;
return $this;
}
}
|
Python | UTF-8 | 4,159 | 2.59375 | 3 | [] | no_license | import csv
import itertools
import random
import numpy as np
import os
import json
from source.util import get_label
def generate_DB(newDataPath=None, rawDataPath=None, sample_for_line=20, hole_value=-1):
if rawDataPath is None:
rawDataPath = '../../data/16col_original_25000line_trainset.csv'
if newDataPath is None:
newDataPath = '../../data/samsung_db'
l2n = get_label.get_labels()
labels = ['주야', '요일', '발생지시도', '발생지시군구', '사고유형_대분류', '사고유형_중분류', '법규위반', '도로형태_대분류', '도로형태', '당사자종별_1당_대분류',
'당사자종별_2당_대분류']
l2n_idx = [l2n[label] for label in labels]
with open(rawDataPath, newline='') as f:
data = csv.reader(f, delimiter=',', quotechar='|')
print('raw data loaded')
raw = []
hole = []
for line_idx, line in enumerate(data):
if line_idx % 1000 == 0:
print('processing... {}/{}'.format(line_idx+1, 25001))
candidates = itertools.combinations(range(len(line)), 3) # 3개 조합 계산
seleted = random.sample(list(candidates), sample_for_line) # 모든 경우의 수 중 X개만 선택
for i in [2, 3, 4, 5, 6]:
line[i] = int(line[i])
for idx, element in enumerate(line):
if idx in [2, 3, 4, 5, 6]:
continue
if idx > 6:
line[idx] = l2n_idx[idx-5][element]
else:
line[idx] = l2n_idx[idx][element]
for candidate in seleted:
hole.append(list(candidate)) # 어디에 뚤렸는지 명시
raw.append(line) # 새 데이터 추가
shuffle_index = list(range(len(raw)))
random.shuffle(shuffle_index)
raw = np.array(raw)[shuffle_index] # 데이터 섞기
hole = np.array(hole)[shuffle_index]
np.save(newDataPath, {'data':raw, 'hole':hole})
print('data save: {}'.format(newDataPath + '.npy'))
def generate_test_DB(newDataPath=None, rawDataPath=None):
if rawDataPath is None:
rawDataPath = '../../data/test_kor.csv'
if newDataPath is None:
newDataPath = '../../data/samsung_test_db'
l2n = get_label.get_labels()
labels = ['주야', '요일', '발생지시도', '발생지시군구', '사고유형_대분류', '사고유형_중분류', '법규위반', '도로형태_대분류', '도로형태', '당사자종별_1당_대분류',
'당사자종별_2당_대분류']
l2n_idx = [l2n[label] for label in labels]
with open(rawDataPath, newline='') as f:
data = csv.reader(f, delimiter=',', quotechar='|')
print('raw data loaded')
raw = []
hole = []
for line_idx, line in enumerate(data):
if line_idx == 0: # 타이틀 생략
continue
if line_idx % 1000 == 0:
print('processing... {}/{}'.format(line_idx+1, 25001))
candidate = []
for i in [2, 3, 4, 5, 6]:
if line[i] == '':
line[i] = -1
candidate.append(i)
else:
line[i] = int(line[i])
for idx, element in enumerate(line):
if idx in [2, 3, 4, 5, 6]:
continue
if idx > 6:
if element == '':
line[idx] = -1
candidate.append(idx)
else:
line[idx] = l2n_idx[idx-5][element]
else:
if element == '':
line[idx] = -1
candidate.append(idx)
else:
line[idx] = l2n_idx[idx][element]
hole.append(list(candidate)) # 어디에 뚤렸는지 명시
raw.append(line) # 데이터 추가
np.save(newDataPath, {'data': raw, 'hole':hole})
print('data save: {}'.format(newDataPath + '.npy'))
if __name__ == '__main__':
generate_DB()
generate_test_DB() |
JavaScript | UTF-8 | 7,731 | 2.90625 | 3 | [] | no_license | /*eslint-env browser */
/*eslint no-var: "error"*/
/*eslint prefer-const: "error"*/
/*eslint-env es6*/
function displayScreen(currentDisplay) {
if (document.body.offsetWidth <= 600)
toggleSideBar();
const offreader = document.querySelector(".offreader");
offreader.style.display = "none";
home.style.display = "none";
about.style.display = "none";
if (currentDisplay === "about")
about.style.display = "block";
else if (currentDisplay === "home")
home.style.display = "block";
else {
offreader.style.display = "block";
setTimeout(function() {
getCurrentChapter();
}, 1000);
}
}
function disableButtons() {
btnScrape.disabled = true;
btnScrapeAndDrive.disabled = true;
btnRestore.disabled = true;
//const btns = document.getElementsByClassName("angka"); //change to delete story class button
//for (let i = 0; i < elems.length; i++) {
// btns[i].disabled = true;
//}
};
function enableButtons() {
btnScrape.disabled = false;
btnScrapeAndDrive.disabled = false;
btnRestore.disabled = false;
//const btns = document.getElementsByClassName("angka"); //change to delete story class button
//for (let i = 0; i < elems.length; i++) {
// btns[i].disabled = true;
//}
};
function toggleSideBar() {
const sidebar = document.querySelector(".sidebar");
const navToggle = document.querySelector(".nav-toggle");
const reader = document.querySelector(".reader");
navToggle.classList.toggle("active");
const style = window.getComputedStyle(sidebar);
var sidebarDisplay = (style.display === "none");
if (sidebarDisplay) {
sidebar.style.display = "block";
reader.style.display = "none";
} else {
sidebar.style.display = "none";
reader.style.display = "block";
}
}
function populateSelectOptions() {
const promise = new Promise(function(resolve, reject) {
const select = document.querySelectorAll(".chapters-select");
select[0].innerHTML = "";
select[1].innerHTML = "";
const optionHtml = document.createDocumentFragment(),
optionHtml2 = document.createDocumentFragment();
for (let i = 1; i <= Story.chapters; i++) {
optionHtml.appendChild(new Option(`Chapter: ${i}`, i));
optionHtml2.appendChild(new Option(`Chapter: ${i}`, i));
}
select[0].appendChild(optionHtml);
select[1].appendChild(optionHtml2);
function changeFn(e) {
console.log(this.value);
goToChapter(this.value);
e.preventDefault();
window.scrollTo(0, 0);
};
select[0].addEventListener("change", changeFn);
select[1].addEventListener("change", changeFn);
resolve();
});
return promise;
}
function closeMobileSidebar() {
const sidebar = document.querySelector(".sidebar");
const navToggle = document.querySelector(".nav-toggle");
if (navToggle.classList.contains("active")) {
navToggle.classList.remove("active");
sidebar.style.display = "none";
}
}
function goToChapter(chapter) {
Story.currentChapter = Number.parseInt(chapter);
updateNav();
getCurrentChapter();
}
function getCurrentChapter() {
window.scrollTo(0, 0);
if (!Number.isInteger(Story.currentChapter)) {
console.error("It's not a FUCKING NUMBER!");
}
const nextStoryPath = Story.id + "." + Story.currentChapter;
console.log("getCurrentChapter", nextStoryPath);
getChapter(nextStoryPath);
}
function changeToNextChapter(e) {
const next = document.querySelector(".next");
if (next.classList.contains("disable"))
return;
Story.currentChapter += 1;
getCurrentChapter();
updateNav();
e.preventDefault();
}
function changeToPreviousChapter(e) {
const prev = document.querySelector(".prev");
if (prev.classList.contains("disable"))
return;
if (Story.currentChapter > 1) {
Story.currentChapter -= 1;
getCurrentChapter();
updateNav();
}
e.preventDefault();
}
function updateNav() {
const chaptersSelect = document.querySelectorAll(".chapters-select");
chaptersSelect[0].selectedIndex = Story.currentChapter - 1;
chaptersSelect[1].selectedIndex = Story.currentChapter - 1;
if (Story.currentChapter > 1) {
previousChapterLink[0].classList.remove("disable");
previousChapterLink[1].classList.remove("disable");
if (Story.currentChapter == Story.chapters) {
nextChapterLink[0].classList.add("disable");
nextChapterLink[1].classList.add("disable");
} else {
nextChapterLink[0].classList.remove("disable");
nextChapterLink[1].classList.remove("disable");
}
} else if (Story.currentChapter === 1) {
previousChapterLink[0].classList.add("disable");
previousChapterLink[1].classList.add("disable");
if (Story.chapters > 1) {
nextChapterLink[0].classList.remove("disable");
nextChapterLink[1].classList.remove("disable");
}
}
}
function updateSideBarMenu() {
const promise = new Promise((resolve, reject) => {
var data = that.sidebarMenu;
const strList = document.querySelector(".sidebar-list");
strList.innerHTML = "";
data.forEach(function(obj, i) {
strList.insertAdjacentHTML("beforeend",
`
<div class="sidebar-list--item">
<div class="sidebar-list--delete-item" data-story="${i}"></div>
<a href="#" class="sidebar-list--text story-sel" data-story="${i}" title="${obj.storyName}">
${obj.storyName} - ${obj.totalOfChapters} chapters
</a>
</div>`);
});
const storySelector = document.querySelectorAll(".story-sel");
for (let i = storySelector.length - 1; i >= 0; i--) {
// delete item
var chapterDelete = storySelector[i].parentElement.children[0];
chapterDelete.addEventListener("click",
function(e) {
var storyId = data[e.target.dataset.story].storyId;
console.log('deleting', storyId);
deleteStoryProcess(storyId);
this.parentElement.style.display = 'none';
displayScreen("home");
enableButtons();
});
// story item
storySelector[i].addEventListener("click", function(e) {
const reader = document.querySelector(".reader");
reader.style.display = "block";
console.log(this.dataset.story);
const s = this.dataset.story;
console.log(data[s]);
Story.name = data[s].storyName;
Story.id = data[s].chapterId.split(".")[0];
Story.chapters = data[s].totalOfChapters;
chaptersTotal.textContent = Story.chapters;
title.textContent = Story.name;
Story.currentChapter = 1;
closeMobileSidebar();
getCurrentChapter();
updateNav();
populateSelectOptions();
displayScreen();
});
};
window.performance.mark('endUpdateSideBarMenu');
resolve();
});
return promise;
}
|
Markdown | UTF-8 | 905 | 2.546875 | 3 | [] | no_license | -- 겉 Layout 설계 --
네비를 그린다.
제목을 잡는다.
세부 네비를 잡는다.
갤러리 컨텐츠를 넣는다.
-- 당장 할 일 --
일정 scrollTop 이상이면, css position: fixed 이고,
일정 scrollTop 이하이면, css position: static
-- 문제점 --
-- 아이디어 --
scrollTop 실험하기
input의 checked는 html5에서 자동으로 형성되어 주는 듯하다.
:before 선택자 전에 content 를 삽입하는 것.
-- 필터 네비게이터 모듈 설계 --
필터 네비게이터
container 의 width 값이 - 30일 줄이야.
그래서 filter Navigator의 width 도 마찬가지로 0이다.
줄인다고 내 맘대로 줄어들지는 않네!
-- 문제점 --
스크롤 하고 사이즈 바꿀 때마다 계속 갱식하는게 출혈이 많다.
container를 제거하고 내가 새로 만드는게 낫지 않을까 한다.
|
Python | UTF-8 | 1,178 | 2.890625 | 3 | [] | no_license | #####packages#####
from pymongo import MongoClient
#####end-packages#####
#credentials
host = "localhost"
port = 27017
db = "customer"
def connect(): #this method can be used to establish a connection with database
try:
mongo_connection = MongoClient(host + ":" + str(port))
mongo_database = mongo_connection[db]
return mongo_database
except Exception as e:
pass
database = connect()
def get_db(): #this method returns the database
temp_list = []
result = database.customer_info.find({})
for cur in result:
cur["_id"] = str(cur["_id"])
temp_list.append(cur)
print(temp_list)
return temp_list
# not yet used
# def get_latest():
# #write the logic to add only latest element
# temp_list = []
# temp_list = database.customer_info.find().sort({"_id" : -1}).limit(1)
# value = None
# for cur in temp_list:
# value = cur
# return value
# not used #
# def show_results(request):
# try:
# li = get_db()
# if request.method == "POST":
# return dumps(li)
# else:
# pass
# except Exception as e:
# print e
|
C++ | UHC | 1,278 | 2.765625 | 3 | [] | no_license | #include "stdafx.h"
#include "cTimeManager.h"
cTimeManager::cTimeManager()
:m_fWorldTime(0.0f)
, m_fElapsedTime(0.0f)
{
m_dwLastUpdateTime = GetTickCount();
}
cTimeManager::~cTimeManager()
{
}
void cTimeManager::Update()
{
DWORD dwCurrentTime = GetTickCount();
// 1 ð = (ð -Ҷ ð)/1000.0
m_fElapsedTime = (dwCurrentTime - m_dwLastUpdateTime) / 1000.0f;
m_dwLastUpdateTime = dwCurrentTime;
m_lFPSframeCount++;
m_fFPStimeElapsed += m_fElapsedTime;
m_fWorldTime += m_fElapsedTime;
if (m_fFPStimeElapsed > 1.0f)
{
m_lFrameRate = m_lFPSframeCount;
m_lFPSframeCount = 0;
m_fFPStimeElapsed = 0.0f;
}
}
void cTimeManager::Render()
{
if (!g_pFontManager->GetIsSetup()) return;
g_pFontManager->TextFont(10, 10, D3DXVECTOR3(255,0,255), "FPS : %d", m_lFrameRate);
g_pFontManager->TextFont(10, 30, D3DXVECTOR3(255,0,255), "WorldTime : %f", m_fWorldTime);
g_pFontManager->TextFont(10, 50, D3DXVECTOR3(255,0,255), "ElapsedTime : %f", m_fElapsedTime);
}
float cTimeManager::GetElapsedTime()
{
return m_fElapsedTime;
}
float cTimeManager::GetLastUpdateTime()
{
return m_dwLastUpdateTime / 1000.0f;
}
float cTimeManager::GetWorldTime()
{
return m_fWorldTime;
}
void cTimeManager::Destory()
{
} |
Python | UTF-8 | 1,013 | 4.34375 | 4 | [] | no_license | '''
Given a binary tree, check whether it’s a binary search tree or not.
Approach A:
Iterate through the entire tree looking for contradictions
- False if Left Child > Right Child
Approach B:
Iterate
'''
import pytest
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def __repr__(self):
return str(self.value)
def is_bst(root, minValue=None, maxValue=None):
if root is None:
return True
if not minValue <= root.value <= maxValue:
return False
return is_bst(root.left, minValue, root.value) and \
is_bst(root.right, root.value, maxValue)
def test_is_bst():
# build an illegal tree
bst = Node(3, Node(2, Node(1), Node(4)), Node(5))
assert(is_bst(bst, float('-infinity'), float('infinity'))) == False
bst = Node(5, Node(3, Node(2), Node(5)), Node(7, None, Node(8)))
assert(is_bst(bst, float('-infinity'), float('infinity'))) == True
|
Java | UTF-8 | 276 | 1.664063 | 2 | [] | no_license | package liusheng.url.pipeline;
import liusheng.url.HandlerContext;
/**
* 年: 2020 月: 04 日: 04 小时: 14 分钟: 43
* 用户名: LiuSheng
*/
public interface Handler {
void handle(HandlerContext handlerContext, HandlerChain handlerChain) throws Exception;
}
|
PHP | UTF-8 | 1,697 | 3.125 | 3 | [] | no_license | <?php
namespace MartynBiz\Mongo\Traits;
/**
* Can be re-used for anything that requires singleton pattern
*/
trait Singleton
{
/**
* @var Singleton The reference to *Singleton* instance of this class
*/
private static $instances = array();
/**
* Returns the *Singleton* instance of this class.
*
* @return Singleton The *Singleton* instance.
*/
public static function getInstance($name='default')
{
if (! self::hasInstance($name)) {
static::$instances[$name] = new static();
}
return static::$instances[$name];
}
/**
* Returns the *Singleton* instance of this class.
*
* @return Singleton The *Singleton* instance.
*/
public static function hasInstance($name='default')
{
return isset(static::$instances[$name]);
}
/**
* Allows the instance to be swapped during tests
* @param Connection $instance New instance
*/
public static function setInstance(self $instance, $name='default')
{
static::$instances[$name] = $instance;
}
/**
* As this is a singleton instance, we wanna be able to re-instatiate (e.g. during
* tests as the same instance will be used for unit and integrated tests)
* @return void
*/
public function resetInstance($name=null)
{
if (is_null($name)) {
static::$instances = array();
} else {
unset(static::$instances[$name]);
}
}
/**
* Protected constructor to prevent creating a new instance of the
* *Singleton* via the `new` operator from outside of this class.
*/
protected function __construct()
{
}
}
|
C# | UTF-8 | 1,135 | 2.546875 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public interface IFadeable
{
//private Material[] materials;
void fadeToMaterial(List<Transform> fadeObjects);
//get all the current materials in a list
//if any of the materials are the same dont add the duplicates
//save a dictionary of the fadeObjects name as key and the associated material as value
// if (materials == null)
// {
// InitializeMaterials();
// }
// gameObject.AddComponent<MeshFilter>().mesh = mesh;
// //gameObject.AddComponent<MeshRenderer>().material = materials[depth];
// gameObject.AddComponent<MeshRenderer>().material = material;
//public void InitializeMaterials()
//{
// materials = new Material[maxDepth + 1];
// for (int i = 0; i <= maxDepth; i++)
// {
// float t = i / (maxDepth - 1f);
// t *= t;
// materials[i] = new Material(material);
// materials[i].color = Color.Lerp(Color.white, Color.red, t);
// }
// materials[maxDepth].color = Color.red;
//}
}
|
Java | UTF-8 | 2,393 | 2.359375 | 2 | [] | no_license | package Dao.impl;
import Dao.IAccountDao;
import entity.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
/**
* @author YZY
* @date 2020/3/29 - 19:44
*/
public class AccountDaoImpl implements IAccountDao {
private QueryRunner runner;
private JdbcTemplate jdbcTemplate;
private Account account;
public void setAccount(Account account) {
this.account = account;
}
@Override
public List<Account> findAccount() {
try {
return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public Account findById(Integer accountId) {
try {
return runner.query("select * from account where id = ?",new BeanHandler<Account>(Account.class),accountId);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public void saveAccount(String name,float money) {
String sql="insert into account(name,money) values(?,?)";
jdbcTemplate.update(sql,name,money);
/*try {
runner.update("insert into account(name,money) values(?,?)",account.getName(),account.getMoney());
} catch (SQLException e) {
throw new RuntimeException(e);
}*/
}
@Override
public void updateAccount(Account account) {
try {
runner.update("update account set name = ?,money = ? where id = ? ", account.getName(), account.getMoney(), account.getId());
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void saveAccount(Account account) {
}
/*@Override
public void deleteAccount(Integer accountId){
try {
runner.update("delete from account where id = ?",accountId);
} catch (Exception e) {
e.printStackTrace();
}
}*/
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
}
|
JavaScript | UTF-8 | 604 | 2.890625 | 3 | [
"MIT"
] | permissive | describe("Plane", function() {
var plane;
beforeEach(function() {
plane = new Plane();
});
describe("isAirbourne", function() {
it("Starts as not airbourne", function() {
expect(plane.isAirbourne()).toBe(true);
});
});
describe("land", function() {
it("Change plane to landed", function() {
plane.land();
expect(plane.isAirbourne()).toBe(false);
});
});
describe("takeOff", function() {
it("Changes plane to airbourne", function() {
plane.land();
plane.takeOff();
expect(plane.isAirbourne()).toBe(true);
});
});
});
|
Markdown | UTF-8 | 2,763 | 3.375 | 3 | [
"MIT"
] | permissive | # MSA_trimmer: Straightforward & minimalistic removal of poorly aligned regions in **M**ultiple **S**equence **A**lignments
This is a program to remove (trim) or mask columns of multiple sequence alignments in fasta format.
Columns are removed if they exceed a user-specified "gappyness" treshold, i.e. a threshold of
0.5 (``--trim_gappy 0.5``) would trim all columns where more than half of the sequences have a gap. You may also "hand-pick" columns
or whole regions of the alignment to be trimmed (``--trim_positions``).
If you want to preserve the original coordinates of the alignment, you may also chose to "mask" your alignment
instead of trimming it. This will not remove any columns, instead the whole column will be replaced with
a character of your choice (the gap character "-" by default).
Trimming works for both nucleotide/codon/CDS (``-c``) and peptide (``-p``) alignments. You may even trim a pair
of corresponding CDS and peptide alignments at the same time, to ensure the trimmed alignments will match. In that
case, only whole codons (chunks of three bases each) will be removed in order not to introduce a frame shift.
This is useful for applications that need a codon alignment such as CODEML.
usage: alignment_trimmer.py [-h] [-p PEP_ALIGNMENT_FASTA]
[-c CDS_ALIGNMENT_FASTA] [--trim_gappy TRIM_GAPPY]
[--trim_positions TRIM_POSITIONS [TRIM_POSITIONS ...]]
[--mask [MASK]]
A program to remove (trim) or mask columns of fasta multiple sequence
alignments. Columns are removed if they exceed a user-specified "gappyness"
treshold, and/or if they are specified by column index. Also works for codon
alignments. The trimmed alignment is written to [your_alignment]_trimmed.fa
optional arguments:
-h, --help show this help message and exit
-p PEP_ALIGNMENT_FASTA, --pep_alignment_fasta PEP_ALIGNMENT_FASTA
-c CDS_ALIGNMENT_FASTA, --cds_alignment_fasta CDS_ALIGNMENT_FASTA
--trim_gappy TRIM_GAPPY
the maximum allowed gap proportion for an MSA column,
all columns with a higher proportion of gaps will be
trimmed (default: off)
--trim_positions TRIM_POSITIONS [TRIM_POSITIONS ...]
specify columns to be trimmed from the alignment, e.g.
"1-10 42" to trim the first ten columns and the 42th
column
--mask [MASK] mask the alignment instead of trimming. if a character
is specified after --mask, that character will be used
for masking (default char: "-")
|
Java | UTF-8 | 3,521 | 3 | 3 | [] | no_license | package test3;
import java.util.Scanner;
public class Shujunihe {
int n = 9;// 9条数据
int m = 2;// x的维数
int cnt = 0;
double a[][] = new double[m + 1][m + 1];
double b[] = new double[m + 1];
int x1[] = new int[a.length];
int y1[] = new int[a.length];
int x2[] = { 1, 2, 3 };// 用来存放交换后变量x的位置
boolean fyl;
int xlh;
double x[] = { 1, 3, 4, 5, 6, 7, 8, 9, 10 };
double f[] = { 10, 5, 4, 2, 1, 1, 2, 3, 4 };
double c[] = { 1, 2, 3 };
public void printarray(double a[][]) {
for (int row = 0; row < a.length; row++) {
for (int c = 0; c < a[row].length; c++) {
System.out.print(" " + a[row][c]);
}
System.out.println();
}
}
public Shujunihe() {
restoreA();
restoreB();
quanzhuyuan(a, b);
printarray(a);
}
public void quanzhuyuan(double d[][], double c[])
{
double max;
int row, col;
double temp1, temp2;
int temp3;
double btemp1;
for (int i = 0; i < d.length; i++) {
max = Math.abs(d[i][i]);
row = i;
col = i;
for (int j = i; j < d.length; j++) {
for (int k = i; k < d.length; k++) {
if (Math.abs(d[j][k]) > max) {
max = Math.abs(d[j][k]);
row = j;
col = k;
}
}
}
/*
* for(int n=0;n<d.length;n++)//hang
*
* { temp1=a[i][n]; a[i][n]=a[row][n]; a[row][n]=temp1; btemp1=b[i];
* b[i]=b[row]; b[row]=btemp1; } for(int m=0;m<d.length;m++)//lie {
* temp2=a[m][i]; a[m][i]=a[m][col]; a[m][col]=temp2; }
*/
if (col != i && row != i) {
fyl = true;
xlh = col;
for (int n = 0; n < d.length; n++)// hang
{
temp1 = a[i][n];
a[i][n] = a[row][n];
a[row][n] = temp1;
btemp1 = b[i];
b[i] = b[row];
b[row] = btemp1;
}
for (int m = 0; m < d.length; m++)// lie
{
temp2 = a[m][i];
a[m][i] = a[m][col];
a[m][col] = temp2;
}
} else if (row != i && col == i) {
for (int n = 0; n < d.length; n++)// hang
{
temp1 = a[i][n];
a[i][n] = a[row][n];
a[row][n] = temp1;
btemp1 = b[i];
b[i] = b[row];
b[row] = btemp1;
}
} else if (col != i && row == i)
{
fyl = true;
for (int m = 0; m < d.length; m++)// lie
{
xlh = col;
temp2 = a[m][i];
a[m][i] = a[m][col];
a[m][col] = temp2;
}
}
if (fyl) {
temp3 = x2[i];
x2[i] = x2[xlh];
x2[xlh] = temp3;
x1[cnt] = i;
y1[cnt] = xlh;
cnt++;
fyl = false;
}
for (int j = i + 1; j < d.length; j++)// J表示行
{
double l = a[j][i] / a[i][i];
for (int e = i + 1; e < d.length; e++)// e表示j行对于的每一列
{
a[j][e] = a[j][e] - l * a[i][e];
}
b[j] = b[j] - l * b[i];
a[j][i] = 0;
}
}
}
public void restoreA() {
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= m; j++) {
a[i][j] = Sum(i, j);
}
}
a[0][0] = n;
}
public double Sum(int r, int c) {
double sum = 0;
for (int i = 0; i <= n - 1; i++) {
sum += Math.pow(x[i], r + c);
}
return sum;
}
public double Sumf(int r) {
double sum = 0;
for (int i = 0; i <= n - 1; i++) {
sum += f[i] * Math.pow(x[i], r);
}
return sum;
}
public void restoreB() {
for (int i = 0; i <= m; i++) {
b[i] = Sumf(i);
}
}
public static void main(String[] args) { // TODO Auto-generated method stub
new Shujunihe();
}
}
|
PHP | UTF-8 | 1,607 | 2.59375 | 3 | [] | no_license | <?php namespace Jenssegers\Mongodb;
use Jenssegers\Mongodb\Model;
use Jenssegers\Mongodb\DatabaseManager;
use Illuminate\Support\ServiceProvider;
use Illuminate\Validation\DatabasePresenceVerifier;
class MongodbServiceProvider extends ServiceProvider {
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$this->registerValidationPresenceVerifier();
Model::setConnectionResolver($this->app['mongodb']);
Model::setEventDispatcher($this->app['events']);
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
// The database manager is used to resolve various connections, since multiple
// connections might be managed. It also implements the connection resolver
// interface which may be used by other components requiring connections.
$this->app['mongodb'] = $this->app->share(function($app)
{
return new DatabaseManager($app);
});
}
/**
* Register MongoDB as the ConnectionResolverInterface on the DatabasePresenceVerifier.
* This allows Validation methods which utilize the PresenceVerifierInterface to use our
* MongoDB connection.
*
* @return void
*/
public function registerValidationPresenceVerifier()
{
$this->app['validation.presence'] = $this->app->share(function($app)
{
return new DatabasePresenceVerifier($app['mongodb']);
});
}
} |
Java | UTF-8 | 1,416 | 2.234375 | 2 | [] | no_license | package org.star.uml.designer.command;
import java.util.Collection;
import org.eclipse.emf.common.command.Command;
import org.eclipse.emf.common.command.AbstractCommand;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.impl.EReferenceImpl;
import org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand;
import org.eclipse.gmf.runtime.notation.Location;
import org.eclipse.gmf.runtime.notation.impl.ShapeImpl;
import org.eclipse.uml2.uml.internal.impl.ActorImpl;
public class VisibleShapeCommand extends AbstractCommand{
public static final String ID="org.star.uml.designer.command.VisibleShapeCommand";
private ShapeImpl shapeImple;
public VisibleShapeCommand() {
this.setLabel("Insert Shape");
}
@Override
public void execute() {
if(shapeImple.isVisible()){
shapeImple.setVisible(false);
}else{
shapeImple.setVisible(true);
}
}
@Override
public void redo() {
if(shapeImple.isVisible()){
shapeImple.setVisible(true);
}else{
shapeImple.setVisible(false);
}
}
@Override
public void undo() {
if(shapeImple.isVisible()){
shapeImple.setVisible(false);
}else{
shapeImple.setVisible(true);
}
}
@Override
public boolean canExecute() {
return true;
}
public void setShapeImpl(ShapeImpl shapeImple){
this.shapeImple = shapeImple;
}
}
|
Python | UTF-8 | 1,803 | 2.796875 | 3 | [] | no_license | import pygame
from constantes import *
class Game(object):
"""docstring for game."""
def __init__(self, item, windows, perso):
super(Game, self).__init__()
self.item = item
self.gameover = 0
self.win = 0
self.game = 1
self.over_loop = 0
self.main_loop = 1
self.windows = windows
self.perso = perso
self.sound_gameover = pygame.mixer.Sound("sound/gameover.wav")
self.sound_win = pygame.mixer.Sound("sound/win.wav")
self.message = ""
def game_loop(self):
if (self.perso.x, self.perso.y) == boss_pos:
if self.item.item_count < 3:
self.sound_gameover.play()
print("game over")
self.game = 0
self.over_loop = 1
self.message = "YOU LOSE! Try again? Y/N"
if self.item.item_count == 3:
self.sound_win.play()
print("gagne")
self.game = 0
self.over_loop = 1
self.message = "YOU WIN! Try again? Y/N"
def end_loop(self):
basicfont = pygame.font.SysFont(None, 48)
text = basicfont.render(self.message, True, (255, 0, 0))
textrect = text.get_rect()
textrect.centerx = self.windows.get_rect().centerx
textrect.centery = self.windows.get_rect().centery
self.windows.blit(text, textrect)
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_y:
self.game, self.over_loop = 1, 0
if event.key == pygame.K_n:
self.over_loop, self.game = 0, 0
|
Python | UTF-8 | 1,575 | 3.015625 | 3 | [] | no_license | from unittest import TestCase
from unittest.mock import patch
import dnd
class Test(TestCase):
def test_roll_one_sided_die_once(self):
expected = 1
actual = dnd.roll_die(1, 1)
self.assertEqual(expected, actual)
def test_roll_six_sided_die_once(self):
actual = dnd.roll_die(1, 6)
self.assertGreaterEqual(actual, 1)
self.assertLessEqual(actual, 6)
def test_roll_six_sided_die_twice(self):
actual = dnd.roll_die(2, 6)
self.assertGreaterEqual(actual, 2)
self.assertLessEqual(actual, 12)
def test_roll_ten_sided_die_ten_times(self):
actual = dnd.roll_die(10, 10)
self.assertGreaterEqual(actual, 10)
self.assertLessEqual(actual, 100)
@patch('random.randint', side_effect=[3, 3])
def test_roll_die_single_roll_two_times_same_value(self, mock_randint):
actual = dnd.roll_die(2, 3)
self.assertEqual(actual, 6)
@patch('random.randint', side_effect=[3, 3, 3])
def test_roll_die_single_roll_three_times_same_value(self, mock_randint):
actual = dnd.roll_die(3, 3)
self.assertEqual(actual, 9)
@patch('random.randint', side_effect=[3, 2, 1])
def test_roll_die_single_roll_three_times_different_value(self, mock_randint):
actual = dnd.roll_die(3, 3)
self.assertEqual(actual, 6)
@patch('random.randint', side_effect=[3, 5, 2, 1, 4, 4, 2])
def test_roll_die_single_roll_multiple_times_random_value(self, mock_randint):
actual = dnd.roll_die(7, 6)
self.assertEqual(actual, 21)
|
Java | UTF-8 | 594 | 1.84375 | 2 | [] | no_license | package com.ksquarej.edunomics.NavigationDrawer;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import com.ksquarej.edunomics.R;
public class Opportunitesfragment extends Fragment {
View v;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.opportunites_fragment, container, false);
return v;
}
}
|
C# | UTF-8 | 1,043 | 2.796875 | 3 | [] | no_license | using GameShopDemo.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GameShopDemo.Managers
{
class CampaignManager : Services.ICampaignService
{
public int LastId=0;
public void AddCampaign(List<Campaign> campaigns)
{
foreach (var campaign in campaigns)
{
Console.WriteLine("New Campaign: " + campaign.Name + " has been added.");
}
}
public void UpdateCampaign(List<Campaign> campaigns)
{
foreach (var campaign in campaigns)
{
Console.WriteLine("Current Campaign: " + campaign.Name + " has been updated.");
}
}
public void DeleteCampaign(List<Campaign> campaigns)
{
foreach (var campaign in campaigns)
{
Console.WriteLine("Campaign: " + campaign.Name + " has been deleted.");
}
}
}
}
|
Java | UTF-8 | 5,363 | 2.109375 | 2 | [] | no_license | package com.feit.feep.dbms.dao.impl;
import com.feit.feep.core.Global;
import com.feit.feep.dbms.build.BasicSqlBuild;
import com.feit.feep.dbms.build.FeepEntityRowMapper;
import com.feit.feep.dbms.build.GeneratorSqlBuild;
import com.feit.feep.dbms.dao.IFeepDictionaryDao;
import com.feit.feep.dbms.entity.dictionary.Dictionary;
import com.feit.feep.dbms.entity.query.FeepQueryBean;
import com.feit.feep.dbms.entity.query.FeepSQL;
import com.feit.feep.exception.dbms.TableException;
import com.feit.feep.util.FeepUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Map;
/**
* 数据字典dao实现类
* Created by ZhangGang on 2015/6/28 0028.
*/
@Repository
public class FeepDictionaryDao implements IFeepDictionaryDao {
private static final String TABLENAME = "feep_dictionary";
@Autowired
private JdbcTemplate jdbcTemplate;
private static final String KEY_ADDDICTIONARY = "sql.dbms.dictionary.addDictionary";
private static final String KEY_MODIFYDICTIONARY = "sql.dbms.dictionary.modifyDictionary";
private static final String KEY_FINDDICTIONARYBYID = "sql.dbms.dictionary.findDictionaryById";
private static final String KEY_DELETEDICTIONARYBYID = "sql.dbms.dictionary.deleteDictionaryById";
private static final String KEY_GETTOTALCOUNT = "sql.dbms.dictionary.getTotalCount";
@Override
public String addDictionary(Dictionary dictionary) throws TableException {
try {
String sql = GeneratorSqlBuild.getSqlByKey(KEY_ADDDICTIONARY);
if (FeepUtil.isNull(dictionary.getId())) {
dictionary.setId(FeepUtil.getUUID());
}
jdbcTemplate.update(sql, convertFeepDictionaryToParameterForInsert(dictionary));
return dictionary.getId();
} catch (Exception e) {
throw new TableException("addDictionary [" + dictionary.getDictionaryname() + "] error, " + e.getMessage(), e);
}
}
private Object[] convertFeepDictionaryToParameterForInsert(Dictionary dictionary) {
return new Object[]{dictionary.getId(), dictionary.getDictionaryname(), dictionary.getShowname(), dictionary.getDescription()};
}
private Object[] convertFeepDictionaryToParameterForUpdate(Dictionary dictionary) {
return new Object[]{dictionary.getDictionaryname(), dictionary.getShowname(), dictionary.getDescription(), dictionary.getId()};
}
@Override
public boolean modifyDictionary(Dictionary dictionary) throws TableException {
try {
int i = 0;
if (null != dictionary && !FeepUtil.isNull(dictionary.getId())) {
String sql = GeneratorSqlBuild.getSqlByKey(KEY_MODIFYDICTIONARY);
i = jdbcTemplate.update(sql, convertFeepDictionaryToParameterForUpdate(dictionary));
}
return i == 1;
} catch (Exception e) {
Global.getInstance().logError("modifyDictionary error", e);
throw new TableException(e);
}
}
@Override
public Dictionary findDictionaryById(String id) throws TableException {
Dictionary dictionary = null;
try {
String sql = GeneratorSqlBuild.getSqlByKey(KEY_FINDDICTIONARYBYID);
List<Dictionary> result = jdbcTemplate.query(sql, new Object[]{id}, FeepEntityRowMapper.getInstance(Dictionary.class));
if (null != result) {
dictionary = result.get(0);
}
return dictionary;
} catch (Exception e) {
throw new TableException(e);
}
}
@Override
public boolean deleteDictionaryById(String id) throws TableException {
String sql = GeneratorSqlBuild.getSqlByKey(KEY_DELETEDICTIONARYBYID);
try {
int count = jdbcTemplate.update(sql, id);
return count == 1;
} catch (Exception e) {
throw new TableException("deleteDictionaryById error ,id:" + id, e);
}
}
@Override
public List<Dictionary> queryDictionary(FeepQueryBean queryBean) throws TableException {
List<Dictionary> result;
try {
BasicSqlBuild basicSqlBuild = new BasicSqlBuild();
queryBean.setModuleName(TABLENAME);
queryBean.setFields(null);
FeepSQL sql = basicSqlBuild.getQuerySQL(queryBean);
if (FeepUtil.isNull(sql.getParams())) {
result = jdbcTemplate.query(sql.getSql(), FeepEntityRowMapper.getInstance(Dictionary.class));
} else {
result = jdbcTemplate.query(sql.getSql(), sql.getParams(), FeepEntityRowMapper.getInstance(Dictionary.class));
}
return FeepUtil.isNull(result) ? null : result;
} catch (Exception e) {
throw new TableException("queryDictionary error", e);
}
}
@Override
public int getTotalCount() throws TableException {
try {
String sql = GeneratorSqlBuild.getSqlByKey(KEY_GETTOTALCOUNT);
Map<String, Object> map = jdbcTemplate.queryForMap(sql);
return Integer.valueOf(map.get("count").toString());
} catch (Exception e) {
throw new TableException(e);
}
}
}
|
Python | UTF-8 | 1,671 | 2.875 | 3 | [] | no_license | import pandas as pd
from lxml import etree
import re
import os
import requests
def get_html(url):
headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'}
html=requests.get(url,headers=headers)
print(html.status_code)
html.encoding=html.apparent_encoding
return html.text
# 文学 流行 文化 生活 经管 科技
def parse_html(html):
Types=[]
# // *[ @ id = "content"] / div / div[1] / div[2]
# //*[@id="content"]/div/div[1]/div[2]/div[1]
# //*[@id="content"]/div/div[1]/div[2]
# //*[@id="content"]/div/div[1]/div[2]
html = etree.HTML(html)
# divs=html.xpath('//div[@class="article"]/div[2]/div')
divs = html.xpath('//div[@class="article"]/div[2]/div')
print(len(divs))
for div in divs:
type0=div.xpath('.//a[@class="tag-title-wrapper"]/@name')[0]
tds=div.xpath('.//td')
for td in tds:
name=td.xpath('.//a/text()')[0]
num=td.xpath('.//b/text()')[0]
num=Num(num)
bt={'type0':type0,'name':name,'num':num}
Types.append(bt)
return Types
def Num(info):
r = re.findall(r'[\(](.*?)[\)]', info)[0]
return int(r)
def run():
if 'bookType.csv' not in os.listdir():
url = 'https://book.douban.com/tag/'
html = get_html(url)
Types = parse_html(html)
typedf=pd.DataFrame(Types)
typedf.to_csv('bookType.csv')
else:
typedf = pd.read_csv('bookType.csv',encoding='utf_8_sig')
return typedf
if __name__ == '__main__':
run() |
C++ | UTF-8 | 10,562 | 2.90625 | 3 | [] | no_license | #include <chrono>
#include <thread>
#include <list>
#include "Punto.cpp"
#include "Rgb.cpp"
#include "Esfera.cpp"
#include "Plano.cpp"
#include "Camara.cpp"
#include "Luz.cpp"
#include "Matrix4.cpp"
#include "Listas.cpp"
#include "Interseccion.cpp"
#include "Imagen.cpp"
using namespace std::chrono;
//Implementacion del algoritmo PathTracer
class PathTracer{
public:
//Atributos
Listas lista;
Camara camara;
float numRayos;
float front;
Imagen imagen;
//Constructor
PathTracer(Listas& l, Camara& c, float& paths, float& f, Imagen& i){
lista=l;
camara=c;
numRayos=paths;
front=f;
imagen=i;
}
//Informa del progreso del algoritmo durante su ejecucion
void progreso(int numPixel, int total, bool& fin) {
auto percentCompleted = static_cast<int>(numPixel / static_cast<float>(total) * 100.0f);
cout << "Progress: [";
for (int i = 0; i < round(percentCompleted / 2); ++i) {
cout << "=";
}
if (total == numPixel){
cout << "] 100%\n";
fin=true;
}
else{
cout << "> " << percentCompleted << "%\r" << flush;
}
}
//Lanza rayo de sombra para comprobar si a P le llega luz desde la fuente de luz
bool rayoSombra(Punto P, Punto luz, Esfera esferaFinal){
//Direccion entre la fuente de luz y el punto en el que se quiere sabe el color (P)
Direccion wi=normalize(luz-P);
bool corta=false;
Punto P2;
float t1=INFINITY;
Esfera siguiente;
list<Esfera>::iterator it=lista.listaEsferas.begin();
//Se recorren todas las esferas para ver si hay alguna que corte el rayo de Sombra
while(it != lista.listaEsferas.end() && !corta){
siguiente=*it;
//No interesea comprobar la propia esfera intersectada por el rayo primario
if(!siguiente.iguales(esferaFinal)){
t1=INFINITY;
if(siguiente.intersectan(P,wi,t1)){
P2=P+wi*t1;
//Si la distancia entre P y P2(interseccion del rayo de sombra) es menor a la
//distancia entre P y la fuente de luz, quiere decir que la figura esta en medio
if(module(P-P2)<module(P-luz)){
//Impide que la luz llegue a P
corta=true;
}
}
}
++it;
}
return corta;
}
//Comprueba si el rayo lanzado intersecta alguna figura de la escena
//Si intersecta mas de una se tiene en cuenta el punto de corte mas cercano al plano de pixeles
Interseccion intersectaFigura(Direccion dirRayo, Punto posPixel){
float t0=INFINITY;
bool hayCorte=false;
bool esEsfera=false;
Esfera esferaFinal;
float t1=INFINITY;
//Se comprueba la interseccion con alguna esfera
for(Esfera &p : lista.listaEsferas){
t1=INFINITY;
if(p.intersectan(posPixel,dirRayo,t1)){
hayCorte=true;
if(t1<t0){
t0=t1;
esferaFinal=p;
esEsfera=true;
}
}
}
//Se comprueba la interseccion con algun plano
Punto P;
Plano planoFinal;
for(Plano &p : lista.listaPlanos){
t1=INFINITY;
if(p.intersectan(posPixel,dirRayo,t1)){
hayCorte=true;
if(t1<t0){
P=posPixel+dirRayo*t1;
if(p.estaDentro(P)){
t0=t1;
planoFinal=p;
esEsfera=false;
}
}
}
}
return Interseccion(esferaFinal,planoFinal,esEsfera,hayCorte,t0);
}
//Parte del calculo de la luz indirecta tras realizar las simplificaciones oportunas debido a las probabilidades
Rgb simplificacionIndirecta(Direccion rayoNuevo, Direccion dirRayo, Direccion normal, Rgb kd, Rgb ks, float pkd, float pks,float alfa){
//Kd
Rgb difuso=kd/pkd;
//Ks
Direccion wi = rayoNuevo;
Direccion wo = dirRayo*-1;
Direccion wr=Brdf().reflection(wi,normal);
Rgb especular= (ks*(alfa + 2) * pow(fabs(dot(wr, wo)), alfa)) / 2;
return difuso+especular;
}
//Calculo de la luz indirecta
Rgb LuzIndirecta(Direccion dirRayo, Interseccion t, Direccion normal, Rgb kd, Rgb ks, Rgb ksp, Rgb kr, float ior, float alfa) {
Direccion direccionNueva;
float random;
float bias=1e-4;
//Relacion entre coeficientes y ruleta rusa
float pkd=kd.max();
float pks=ks.max();
float pksp=ksp.max();
float pkr=kr.max();
//Normalizar probabilidades si superan el 0.9 (debe haber siempre un 10% de probabilidad de absorcion)
float total=(pkd+pks+pksp+pkr);
if(total>0.9){
pkd=pkd*0.9/total;
pks=pks*0.9/total;
pksp=pksp*0.9/total;
pkr=pkr*0.9/total;
}
random=Brdf().posAleatoria(0.0f,1.0f);
//RULETA RUSA
//Rebote como lambertiano (reflexion en direccion aleatoria)
if(random<pkd + pks){
direccionNueva=Brdf().direccionAleatoria(normal,t.getPoint());
return trazarCamino(t.getPoint(),direccionNueva)*simplificacionIndirecta(direccionNueva,dirRayo,normal,kd,ks,pkd,pks,alfa);
}
//Rebote como espejo(reflexion)
else if((pkd+pks)<random && random<(pkd+pks+pksp)){
direccionNueva=Brdf().reflection(dirRayo,normal);
return (ksp/pksp)*trazarCamino(t.getPoint()+normal*bias,direccionNueva);
}
//Rebote como transparente(refraccion)
else if((pkd+pks+pksp)<random && random<(pkd+pks+pksp+pkr)){
direccionNueva=Brdf().refraction(dirRayo,normal,ior);
return (kr/pkr)*trazarCamino(t.getPoint()-normal*bias,direccionNueva);
}
//Siempre 10% de probabilidad de absorción
else{
return Rgb(0,0,0);
}
}
//Calculo de la luz directa
Rgb LuzDirecta(Luz siguiente, Direccion dirRayo, Interseccion t, Direccion normal, Rgb kd, Rgb ks, float alfa){
Punto posLuz=siguiente.pos;
Rgb p=siguiente.pot*siguiente.rgb;
Esfera esfera=t.getEsfera();
//Si !corte (el rayo de sombra no corta ninguna figura) se computa el color en P
if((!kd.cero() || !ks.cero()) && !rayoSombra(t.getPoint(),posLuz,esfera)){
//Kd
Rgb difuso=kd/M_PI;
//Ks
Direccion wi=normalize(posLuz-t.getPoint());
Direccion wo = dirRayo*-1;
Direccion wr = Brdf().reflection(wi,normal);
Rgb especular= ks*((alfa + 2) / (2 * M_PI)) * pow(fabs(dot(wr, wo)), alfa);
//Li
Rgb Li(p.r/pow(module(posLuz-t.getPoint()),2),p.g/pow(module(posLuz-t.getPoint()),2),p.b/pow(module(posLuz-t.getPoint()),2));
//Termino del coseno
float cos=Brdf().max(float(0),dot(normalize(normal),wi));
return Li*(difuso+especular)*cos;
}
return Rgb(0,0,0);
}
//Indica de qué color hay que pintar el punto de interseccion de acuerdo a la figura intersectada
Rgb trazarCamino(Punto posPixel, Direccion dirRayo){
Direccion normal;
Rgb emite,kd,ks,ksp,kr,colorDirecta,colorIndirecta;
float brdf,ior,alfa;
//Si el rayo corta alguna figura de la escena...
Interseccion t = intersectaFigura(dirRayo,posPixel);
if(t.getCorte()){
//Punto mas cercano que corta el rayo
t.setPoint(posPixel+dirRayo*t.getT());
t.getInfo(dirRayo,normal,kd,ks,ksp,kr,ior,alfa,emite);
//Si el objeto intersectado emite se devuelve su potencia
if(!emite.cero()){
return emite;
}
//Si no emite, se procede a calcular la luz directa e indirecta
else{
//Se recorren las fuentes de luz porque color en P depende de la suma de las contribuciones de cada luz
for (Luz &l : lista.listaLuces){
//LUZ DIRECTA (NEXT EVENT ESTIMATION)
colorDirecta=colorDirecta + LuzDirecta(l,dirRayo,t,normal,kd,ks,alfa);
}
//LUZ INDIRECTA
colorIndirecta=LuzIndirecta(dirRayo,t,normal,kd,ks,ksp,kr,ior,alfa);
return colorDirecta+colorIndirecta;
//return colorDirecta;
}
}
//Color si el rayo no choca con nada
else{
return Rgb(0,0,0);
}
}
//Recorre w pixeles hacia la derecha y desde j1 hasta j2 en el eje vertical
void recorrerEscena(int w, int j1, int j2){
//Por cada pixel, lanzar un rayo y ver la luz que le llega
float x1,y1;
bool fin=false;
for(int y=j2-1;y>=j1;y--){
for(int x=0;x<w;x++){
for(int w=0;w<numRayos;w++){
//Se genera pos aleatoria a traves de la cual lanzar el rayo por el pixel actual
x1=Brdf().posAleatoria(0.0f,1.0f);
y1=Brdf().posAleatoria(0.0f,1.0f);
//Trazado del rayo desde la camara a traves del pixel
Punto posPixel(x+x1,y-y1,front);
Direccion dirRayo(posPixel-camara.o);
//Comprobar si el rayo intersecta una esfera
imagen(y,x) = imagen(y,x) + trazarCamino(posPixel,normalize(dirRayo));
}
imagen(y,x)={imagen(y,x).r/numRayos,imagen(y,x).g/numRayos,imagen(y,x).b/numRayos};
//Mostrar progreso de ejecucion (de uno de los threads)
if (j1 == 0 && !fin) {
progreso(imagen.getW() * (j2-y) + x, imagen.getW() * (j2 - j1),fin);
}
}
}
}
//Reparte la pantalla de pixeles a procesar entre threads para acelerar la ejecucion (paralelizacion)
void renderImageMultithread(){
auto start = high_resolution_clock::now();
//Numero de threads
int numThreads = std::thread::hardware_concurrency() - 1;
if (numThreads == 0) {
exit(0);
}
if (numThreads > 8) {
numThreads = 7;
}
int linesPorT = imagen.getH() / numThreads;
vector<thread> threads(static_cast<unsigned long>(numThreads));
//Division de la pantalla de pixeles segun el numero de threads disponibles
for (int i = 0; i < numThreads; i++) {
int start = i*linesPorT;
int end = start + linesPorT;
if (i != numThreads - 1){
threads[i] = thread(&PathTracer::recorrerEscena,this,imagen.getW(),start,end);
} else {
threads[i] = thread(&PathTracer::recorrerEscena,this,imagen.getW(),start,imagen.getH());
}
}
for (auto &thread : threads) {
thread.join();
}
imagen.write();
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);
//Coste temporal de la ejecucion del programa
cout << "Tiempo de ejecucion: " << (duration.count()/1000000)/60 << " min" << endl;
}
}; |
Go | UTF-8 | 3,585 | 3.09375 | 3 | [
"MIT"
] | permissive | package xorshift128plus
import (
"bytes"
"encoding/binary"
"fmt"
"strings"
"time"
"github.com/shivakar/random/prng"
"github.com/shivakar/random/prng/splitmix64"
)
var (
xorshift128plus *Xorshift128Plus
_ prng.Engine = xorshift128plus
)
// Xorshift128Plus implements a Xorshift PRNG with 128 bits of state and
// a maximal period of 2^128-1. The algorithm uses addition as the non-linear
// transformation function
type Xorshift128Plus struct {
seed uint64
state [2]uint64
}
// New returns a new instance of the Xorshift128Plus PRNG Engine.
// If the seed provided is 0, the engine is initialized with current time
func New(seed uint64) *Xorshift128Plus {
r := new(Xorshift128Plus)
r.Seed(seed)
return r
}
/*
* Implement 'Engine' interface
*/
// Uint64 returns a pseudo-random 64-bit value in [0, 2^64) as a uint64.
// Uint64 advances the internal state of the engine.
func (x *Xorshift128Plus) Uint64() uint64 {
s1 := x.state[0]
s0 := x.state[1]
x.state[0] = s0
s1 ^= s1 << 23
x.state[1] = s1 ^ s0 ^ (s1 >> 18) ^ (s0 >> 5)
return x.state[1] + s0
}
// Float64 returns a pseudo-random number in [0.0, 1.0) as a float64.
// Float64 advances the internal state of the engine.
func (x *Xorshift128Plus) Float64() float64 {
return float64(x.Uint64()>>11) / float64(1<<53)
}
// Float64OO returns a pseudo-random number in (0.0, 1.0) as a float64.
// Float6400 advances the internal state of the engine.
func (x *Xorshift128Plus) Float64OO() float64 {
return (float64(x.Uint64()>>12) + float64(0.5)) / float64(1<<52)
}
// Seed uses the provided value to initialize the engine
func (x *Xorshift128Plus) Seed(seed uint64) {
if seed == 0 {
seed = uint64(time.Now().UnixNano())
}
x.seed = seed
ms := splitmix64.New(seed)
x.state[0] = ms.Uint64()
x.state[1] = ms.Uint64()
}
// GetSeed returns the seed used to initialize the engine
func (x *Xorshift128Plus) GetSeed() uint64 { return x.seed }
// GetState returns the internal state of the engine as []byte
// GetState can be used to save the state, e.g. to a file
func (x *Xorshift128Plus) GetState() []byte {
const msg = "xorshift128plus: Error encoding state"
buf := new(bytes.Buffer)
data := []interface{}{
[]byte("xorshift128plus"),
uint64(x.seed),
uint64(x.state[0]),
uint64(x.state[1]),
}
for _, v := range data {
if err := binary.Write(buf, binary.LittleEndian, v); err != nil {
panic(strings.Join([]string{msg, err.Error()}, "\n"))
}
}
return buf.Bytes()
}
// SetState sets the internal state of the engine from a []byte
// SetState can be used to resume from a saved state
func (x *Xorshift128Plus) SetState(b []byte) {
const msg = "xorshift128plus: Error decoding state"
const algo = "xorshift128plus"
buf := bytes.NewReader(b)
nb := make([]byte, len(algo))
_, err := buf.Read(nb)
if err != nil {
panic(strings.Join([]string{msg, err.Error()}, "\n"))
}
if string(nb) != algo {
err = fmt.Errorf("Expected '%s', got '%s'", algo, string(nb))
panic(strings.Join([]string{msg, err.Error()}, "\n"))
}
if err = binary.Read(buf, binary.LittleEndian, &x.seed); err != nil {
panic(strings.Join([]string{msg, err.Error()}, "\n"))
}
if err = binary.Read(buf, binary.LittleEndian, &x.state[0]); err != nil {
panic(strings.Join([]string{msg, err.Error()}, "\n"))
}
if err = binary.Read(buf, binary.LittleEndian, &x.state[1]); err != nil {
panic(strings.Join([]string{msg, err.Error()}, "\n"))
}
}
// Reset reverts the internal state of the engine to its default state,
// except the seed
func (x *Xorshift128Plus) Reset() {
x.Seed(x.seed)
}
|
C++ | UTF-8 | 788 | 3.328125 | 3 | [] | no_license | #include <iostream>
using namespace std;
class Base {
public :
int a;
Base () {}
~Base () {}
virtual void fun() = 0;
private:
};
class Derived : public Base {
public:
int b;
Derived () {}
~Derived () {}
void fun ();
private:
};
class simplePattern {
public:
static simplePattern *handler;
static simplePattern *getHandler() {
if (handler == NULL) {
handler = new simplePattern();
}
return handler;
}
void printHandleAddr() {
cout<<"handler address: "<<handler<<endl;
}
~simplePattern(){}
private:
simplePattern(){}
simplePattern (simplePattern &a){}
simplePattern & operator=(simplePattern &a){return *this;}
};
simplePattern *simplePattern::handler = NULL;
|
JavaScript | UTF-8 | 416 | 2.734375 | 3 | [] | no_license | //Use this class to send message along with status code to global error handler
module.exports= class CustomError extends Error {
constructor(message, statusCode)
{
super(message); //Send message sent through new Instance of Custom error to error
this.statusCode= statusCode;
Error.captureStackTrace(this, this.constructor); //Add Custom error to stack error message
}
};
|
C# | UTF-8 | 777 | 2.625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
namespace selenium_training._11_PageObjects_and_other_design_patterns
{
public class LoginPage
{
public IWebDriver driver;
public string BaseUrl = "https://selenium2.com";
public void Login(string name, string password)
{
driver.Url = BaseUrl;
driver.FindElement(By.Id("username")).Clear();
driver.FindElement(By.Id("usernamre")).SendKeys(name);
driver.FindElement(By.Name("password")).Clear();
driver.FindElement(By.Name("password")).SendKeys(password);
driver.FindElement(By.Name("sumbit")).Click();
}
}
}
|
C# | UTF-8 | 7,739 | 3.0625 | 3 | [] | no_license | using System;
using TinyRadius.Net.Dictionaries;
using TinyRadius.Net.Util;
namespace TinyRadius.Net.Attributes
{
/// <summary>
/// This class represents a generic Radius attribute. Subclasses implement
/// methods to access the fields of special attributes.
/// </summary>
public class RadiusAttribute
{
private int _attributeType = -1;
/// <summary>
/// Constructs an empty Radius attribute.
/// </summary>
private byte[] _data;
/// <summary>
///
/// </summary>
public RadiusAttribute()
{
VendorId = -1;
Dictionary = DefaultDictionary.GetDefaultDictionary();
}
/// <summary>
/// Constructs a Radius attribute with the specified
/// type and data.
/// @param type attribute type, see AttributeTypes.///
/// @param data attribute data
/// </summary>
public RadiusAttribute(int type, byte[] data)
{
VendorId = -1;
Type = type;
Data = data;
}
/// <summary>
/// Returns the data for this attribute.
/// @return attribute data
/// </summary>
public byte[] Data
{
get { return _data; }
set
{
if (value == null)
throw new ArgumentNullException("Value", "attribute data is null");
_data = value;
}
}
/// <summary>
/// Returns the type of this Radius attribute.
/// @return type code, 0-255
/// </summary>
public int Type
{
get { return _attributeType; }
set
{
if (value < 0 || value > 255)
throw new ArgumentException("attribute type invalid: " + value);
_attributeType = value;
}
}
/// <summary>
/// Sets the value of the attribute using a string.
/// @param value value as a string
/// </summary>
public virtual string Value
{
set { throw new NotImplementedException("cannot set the value of attribute " + _attributeType + " as a string"); }
get { return RadiusUtil.GetHexString(Data); }
}
/// <summary>
/// Gets the Vendor-Id of the Vendor-Specific attribute this
/// attribute belongs to. Returns -1 if this attribute is not
/// a sub attribute of a Vendor-Specific attribute.
/// @return vendor ID
/// </summary>
public int VendorId { get; set; }
/// <summary>
/// Returns the dictionary this Radius attribute uses.
/// @return Hashtable instance
/// </summary>
public virtual IWritableDictionary Dictionary { get; set; }
/// <summary>
/// Returns this attribute encoded as a byte array.
/// @return attribute
/// </summary>
public virtual byte[] WriteAttribute()
{
if (Type == -1)
throw new ArgumentException("Type type not set");
if (Data == null)
throw new ArgumentException("attribute data not set");
var attr = new byte[2 + _data.Length];
attr[0] = (byte) Type;
attr[1] = (byte) (2 + _data.Length);
Array.Copy(_data, 0, attr, 2, _data.Length);
return attr;
}
/// <summary>
/// Reads in this attribute from the passed byte array.
/// @param data
/// </summary>
public virtual void ReadAttribute(byte[] data, int offset, int length)
{
if (length < 2)
throw new RadiusException("attribute Length too small: " + length);
int attrType = data[offset] & 0x0ff;
int attrLen = data[offset + 1] & 0x0ff;
var attrData = new byte[attrLen - 2];
Array.Copy(data, offset + 2, attrData, 0, attrLen - 2);
Type = attrType;
Data = attrData;
}
/// <summary>
/// String representation for debugging purposes.
/// @see java.lang.Object#toString()
/// </summary>
public override String ToString()
{
String name;
// determine attribute name
AttributeType at = GetAttributeTypeObject();
if (at != null)
name = at.Name;
else if (VendorId != -1)
name = "Unknown-Sub-Attribute-" + Type;
else
name = "Unknown-Attribute-" + Type;
// indent sub attributes
if (VendorId != -1)
name = " " + name;
return name + ": " + Value;
}
/// <summary>
/// Retrieves an AttributeType object for this attribute.
/// @return AttributeType object for (sub-)attribute or null
/// </summary>
public AttributeType GetAttributeTypeObject()
{
return VendorId != -1
? Dictionary.GetAttributeTypeByCode(VendorId, Type)
: Dictionary.GetAttributeTypeByCode(Type);
}
/// <summary>
/// Creates a RadiusAttribute object of the appropriate type.
/// @param dictionary Hashtable to use
/// @param vendorId vendor ID or -1
/// @param attributeType attribute type
/// @return RadiusAttribute object
/// </summary>
public static RadiusAttribute CreateRadiusAttribute(IWritableDictionary dictionary, int vendorId,
int attributeType)
{
var attribute = new RadiusAttribute();
AttributeType at = dictionary.GetAttributeTypeByCode(vendorId, attributeType);
if (at != null && at.Class != null)
{
try
{
attribute = (RadiusAttribute) Activator.CreateInstance(at.Class);
}
catch (Exception e)
{
// error instantiating class - should not occur
}
}
attribute.Type = attributeType;
attribute.Dictionary = dictionary;
attribute.VendorId = vendorId;
return attribute;
}
/// <summary>
/// Creates a Radius attribute, including vendor-specific
/// attributes. The default dictionary is used.
/// @param vendorId vendor ID or -1
/// @param attributeType attribute type
/// @return RadiusAttribute instance
/// </summary>
public static RadiusAttribute CreateRadiusAttribute(int vendorId, int attributeType)
{
IWritableDictionary dictionary = DefaultDictionary.GetDefaultDictionary();
return CreateRadiusAttribute(dictionary, vendorId, attributeType);
}
/// <summary>
/// Creates a Radius attribute. The default dictionary is
/// used.
/// @param attributeType attribute type
/// @return RadiusAttribute instance
/// </summary>
public static RadiusAttribute CreateRadiusAttribute(int attributeType)
{
IWritableDictionary dictionary = DefaultDictionary.GetDefaultDictionary();
return CreateRadiusAttribute(dictionary, -1, attributeType);
}
}
} |
Markdown | UTF-8 | 1,904 | 3.46875 | 3 | [] | no_license | #User manual
This php script was written to retrieve GitHub issues automatically on a repository.
To use it you only need the Curl library, and, of course, an access to a GitHub repository that contains issues.
You'll need to know how many hundreds of issues there are in this repo, because the GitHub API only allows groups of
100 pages gotten at a time.
So let's get started!
First, in a shell, go to the directory where issues.php is and run the following command:
`curl -u ":YourGitHubUserName" 'https://api.github.com/repos/:RepoOwnerUserName/:RepoName/issues?per_page=100&state=all' > issue1.json`
That is if you have less than 100 issues and you want all of them, even the closed ones.
If you want only the closed ones, change '&state=all' by '&state=closed'. If you want only the open ones, simply remove
this parameter.
Now let's see what to do if you have more than 100 issues.
You'll have to create multiple json files, with a number, like this : issueX.json, where X is your page number.
If you have between 100 and 199 issues, you'll have issue1.json and issue2.json, if you have between 200 and 299 issues,
you'll have issue1.json, issue2.json and issue3.json, etc...
Then, you just run the previous command X times, with an extra parameter. It will now look like this:
`curl -u ":YourGitHubUserName" 'https://api.github.com/repos/:RepoOwnerUserName/:RepoName/issues?per_page=100&state=all@page=X' > issueX.json`
Start with X=1, then increment X until you are sure you have gathered all the issues you want in this repo.
Finally, in your shell, run the following command :
`php issues.php > issues.csv`
Tadaaa! Your CSV file containing all the issues you wanted is now in that same directory!
Note that the encoding should be fine even for special characters like French accents when opened with Excel (which
have ANSI as its default encoding, and our CSV is encoded in UTF-8). |
Markdown | UTF-8 | 8,847 | 2.921875 | 3 | [] | no_license | ## Peripherals
### Mouse Sensor Lens
#### Q: Should you clean your mouse sensor lens regularly, at what frequency and what cleaning methods are recommended?
#### A: Yes, you should try to clear any debris not only from the lens but the tracking surface itself regularly to reduce the likelihood of such particles affecting the sensors capability to track accurately. Cleaning methods should be those simlar to those of camera sensors and lens. See findings and analysis for more information.
<details><summary>Findings and Analysis</summary>
* If you use a fabric tracking surface there is a higher liklihood it has many particles, fibers, hair or other substances which can then be transfered onto your mouse sensor lens.
* The assumed primary causes of such particles getting onto the lens are directly correlated to the conditions of the environment such as air circulation and filtration, rate at which these particles build up, those found directly on the tracking surface, the type of fabric, and the density of weave and threads.
**Observations: (See image sequences below)**
* Particles build up relatively quick if the tracking surface is not cleaned prior to the lens.
* The microscopic debris is not easily identifiable by sight, using a lint roller over the surface can greatly reduce the amount of particles which remain on the cloth tracking surface prior to cleaning lens.
* The particle debris built up over a 1 week period was minimal and had limited impact on user perceived tracking ability.
* Initial lens cleaning methods used included very gentle use of a cotton swab to loosen some debris followed by 1-2 shots of compressed air to achieve a clean sensor lens.
**Mouse Lens Particle Analysis - 1 days use without prior cleaning of the tracking surface**

**Mouse Lens Particle Analysis - Build over 1 week, prior cleaning of both tracking surface and lens**

**Tracking Surface Particle Removal via Generic Lint Roller**

**Recommendations**
* To clean the mouse sensor lens you would want to use an air dust blower like those used on cameras which should not produce any moisture unlike cans of compressed air, and a lens/sensor brush which would be less likely to scratch the plastic or glass lens.
* Cleaning weekly or every two weeks after the initial tracking surface and lens would probably be sufficient as maintenance to ensure consistent performance overtime.
* Use a mildly adhesive lint roller to remove smaller debris and particles prior to cleaning the mouse sensor lens.
* You can purchase an Illuminated Jewelers Eye Loupe with approximately 40-60x zoom which is affordable, portable and functional to observe the conditions of your mousepad or mouse sensor lens.
</details>
### Mouse Lift Off Distance (LOD)
#### Q: Does the mouse LOD affect tracking on different surfaces, and do wear patterns also influence tracking with the same LOD?
#### A: The LOD may have positive or negative influence on mouse tracking, users experience, type of surface and its particulates will also influence the sensors capability to track movement accurately.
<details><summary>Findings and Analysis</summary>
* The lift of distance (LOD) of a mouse refers to the distance in which the sensor will register input from its surface, and usually measured in millimeters.
* The most common benefits of a low LOD is to reduce unwanted tracking when a user briefly lifts the peripheral off the tracking surface and respositions it in an existing area which is preferred or in preparation for the next intended gesture.
* Users that tend to have lower sensitivity where their preferred application sensitivity and the use case (game/application) require them to reposition their mouse frequently prefer a lower lift off distance throughout the session.
* Likewise a user with a higher sensitivity may be less likely to resposition their mouse dependent on their play style, techniques and the use case. A higher sensitivity would reduce the amount of physical movement required to cover the same distance in the application.
**Mousepad - HyperX Fury S XXL - Wear**
* The area circled in blue in the image below represents a common wear pattern from repeated casual gaming use (slightly over 1 years time) and is likely a combination of degradation of the mouse surface due to friction, temperature, transfer of skincells or material from the peripheral, mouse skates or plastic.

**Microscopic image of the fabric consistency**

**Demo: How does LOD affect sensor tracking over degraded fabric surfaces?**
* As a demonstration I've selected a brand new Razer Viper Mini (Model:RZ01-0325, Firmware: 1.03, Polling: 1000hz) to demonstrate how the sensors LOD calibration setting reacts to the surface and the area of wear on the HyperX Fury S XXL.
* Video: https://www.youtube.com/watch?v=A1u5M7Cn4ik
* **Observations:**
* There is minimal impact to mouse tracking on less used areas with both low and high LOD calibration
* Tracking across common wear patterns (although visually negligable) with a low LOD has a signficant impact on mouse tracking.
* Using a higher LOD to accomodate for the tracking issues on worn area provides a more consistent user experience except the concerns with higher LOD itself, although there may be a very subtle difference in tracking when the sensor is transitioning between both worn and less used surface areas.
**Recommendations for tracking on fabric surfaces**
* Ensure your surface is consistent and level for optimal tracking
* For cloth mousepads, you may be able to increase the consistency of the surface by washing your mousepad with a mild detergent on target areas, see if others with your mousepad have done similar with success.
* Not all surfaces may be compatible with your mouses sensor LOD calibration, and not all mice have a wide range of LOD calibration settings which could result in a poor user experience depending on the surface.
* Test regularly for tracking inconsistencies, compare slightly worn areas to less used areas.
* Particles on the mouse sensor lens may also impact your tests and observations, consult with or see your manufacturers guidelines for cleaning your sensors lens.
</details>
### Mousepad Surfaces
#### Q: How are the HyperX Fury S Speed and Control fabrics different in texture? Do they have noticeably different resistance as a tracking surface?
#### A: Yes, the overall physical texture of the mousepad is quite different, one being ultra smooth similar to silk (Speed) where as the other as a more rough feeling to the touch but not necessarily abrasive. Both however have very similar resistance when moving the mouse on the tracking surface when using 100% PTFE mouse skates.
<details><summary>Findings and Analysis</summary>
* There are visual microscopic differences between each tracking surface, upon closer look you can see that the speed version of the HyperX Fury S has a much tigher weave in comparison giving the fabric which gives it an ultra smooth finish, the standard version of the pad although very consistent texture is much looser and feels abbrasive to the touch.

* During use both provide nearly the same experience or feeling of resistance unlike some other cloth pads marketed as Control pads when using 100% PTFE mouse skates.
* The primary potential differences otherwise are:
* How each feel to the touch.
* If the mouse tracks better/worst given the differences in the weave/texture.
* The color of the fabrics, which may also have some impact to tracking. Speed has a colored pattern where as the Standard version is a solid black color.
</details>
|
Markdown | UTF-8 | 6,245 | 3.046875 | 3 | [] | no_license | ## 这什么?
这是 FEX 团队对外首页的源码,将文章提交到这里后就会在 <http://fex.baidu.com> 上展现。
## 环境搭建
这个系统是基于 [jekyll](http://jekyllrb.com/) 搭建的,为了方便本地编辑和看效果,需要将本项目 clone 至本地环境,并在本机安装 jekyll 环境。
### docker 版本
由于 ruby 编译经常出问题,所以制作了个 docker 镜像,安装好 docker 后,首先运行如下命令
docker run -it -v `pwd`:/build fexpublic/jekyll:latest bash
其中 pwd 是指当前目录,如果不是用 bash,可以直接写全路径
进入 bash 之后,就能使用如下命令编译了
jekyll build --incremental
然后在 `_site` 目录下是最终结果,可以通过 `python -m SimpleHTTPServer 8080` 这样的静态服务查看效果
上传一般只需要上传 `index.html`、`feed.xml`、`sitemap.xml`、`weekly` 和 `blog`相应目录就好了,不要全部上传,会很大
### Mac/Linux 下
请使用如下命令(其中 gem 是 [Ruby](https://www.ruby-lang.org/) 的包管理工具)安装 jekyll(如果遇到权限问题请在前面加 sudo):
gem install jekyll jekyll-paginate redcarpet
如果在 Mac 下安装遇到编译报错,可以试试用 [Brew](http://brew.sh/) 安装新版 ruby
brew install ruby
如果 gem 安装不上,请试试国内镜像
gem sources --remove https://rubygems.org/
gem sources -a https://ruby.taobao.org/
### Windows 下
jekyll 官方对 winodws 的支持程度很低,推荐使用 [Building portable Jekyll for Windows](http://www.madhur.co.in/blog/2013/07/20/buildportablejekyll.html),另外这里附上网盘地址方便大家下载:[PortableJekyll 1.3.0[百度网盘]](http://pan.baidu.com/s/1dDqtzUT)
下边以 PortableJekyll 的解压目录为 `e:\jekyll` 介绍环境变量的配置:
1. 在环境变量中新建变量:
JEKYLL_HOME 取值为 `e:\jekyll`
2. 为 PATH 变量添加如下内容:
`%JEKYLL_HOME%\ruby\bin;%JEKYLL_HOME%\devkit\bin;%JEKYLL_HOME%\git\bin;%JEKYLL_HOME%\Python\App;%JEKYLL_HOME%\devkit\mingw\bin;%JEKYLL_HOME%\curl\bin`
完成 jekyll 配置后,通过如下命令检查是否配置成功:
jekyll -h
### 本地预览
完成 jekyll 的安装后,在源码目录运行如下命令,就能在 localhost:4000 中预览了:
jekyll serve --watch
## 如何编辑?
### 新建草稿
新文章编写时请先浏览 `_drafts` 目录,这里存放的是草稿,它不会在首页显示,请参考里面的 `2014-05-06-empty.md` 文件,新建文件名要遵循这样的格式,以日期开头,后面接着是文章的对外 url 子路径,中间以 `-` 分隔,后续标题有多个单词时也以 `-` 作为分隔符,建议只用英文单词或拼音,目前不确定中文是否可行。
需要注意的是草稿不会出现在首页列表中,如果想本地预览草稿效果,可以加 `--drafts` 参数,如下所示:
jekyll serve --watch --drafts
### 个人信息
每篇文章都会附上个人相关信息,所以请先编辑 `_data\authors.yml` 文件,按照其中的格式新增一项,需要注意以下几点:
* 这是 YAML 格式,每行的开头是两个空格,而不是 TAB
* `author` 字段需要和你所写文章开头的 `author` 属性保持一致,这样才能正确展现
* `url` 字段可以连接到个人主页或微博等
* `intro` 是个人简介,会在每篇文章中展现
* `avatar` 是个人头像,尺寸暂定 120 x 120,请放在 `img/avatar` 目录下
* 为何不用 gavatar?因为不是所有人都希望公开自己的邮箱,而且这样操作起来会简单些
### 图片存放地
请将图片放在 `img` 目录里,每篇文章新建一个目录,在文章中的引用方式为:

### 发布
如果觉得文章可以对外展示了,不过还得先找个 280x150 的图片作为首页封面,放到 `/img/<文章名>/cover.jpg` 下,然后将文章移到 `_posts` 目录下,提交后就可以了。
### 小技巧
* jekyll 最终生成的文件会放在 `_site` 目录下,可以通过浏览这个目录来确认效果
* img 目录的主要用途是放图片,但也可以放其它文件静态,如 zip 等
* 不常见的语法高亮缩写可以[参考这里](http://tinker.kotaweaver.com/blog/?p=152)
## 写什么?
虽然对外会觉得这是团队 Blog,但其实准确来说这里是每个团队成员的个人分享,每篇文章都只代表个人观点,所以如果有什么值得分享的话题,请不要有太多顾虑,想写什么就写什么,借助这个平台来提升自己的影响力吧。
具体内容形式将包括但不限于:
* 技术介绍、经验总结
* FEX 新开源项目及升级版本介绍
* 优秀文章的翻译
* 优秀资源(书籍、开源项目)等的推荐
* 内部分享的 PPT(推荐使用 [Speaker Deck](https://speakerdeck.com/) 存放)
另外,如果你对目前界面的哪些细节不满意,也欢迎直接修改相关源码。
### 对于写作风格的约定
请参考 [Markdown 编写规范](https://github.com/fex-team/styleguide/blob/master/markdown.md),另外在根目录下个脚本 format.js,可以通过它来自动加空格。
## 其它问题
* 如何添加周报
* 请在文件头中添加tag: weekly,使weekly目录下能显示此文章。另外文章命名规则`日期-fex-weekly-日期号.md`
* 为什么某篇文章没显示出来?
* 你确定放到 `_posts` 下了是吧?
* 有可能是用了 `{% xxx }%`,因为页面会当成 Liquid 模板进行解析,所以请使用 `{% raw %}{% xxx %}{% endraw %}` 来包含起来
* 那你肯定没在本地预览过,估计是有报错
* 文章发布前需要找谁审核么?
* 不需要,因为每篇文章都是以个人名义发表的
* 为何不用 WordPress?
* WordPress 环境搭建麻烦,不利于修改
* 简单来说就是:用起来不爽
* 为何不用时下流行的 Hexo?
* Hexo 是将生成后的页面放 github 中,多人编辑出现冲突时合并麻烦
* 我不是 FEX 团队成员,可以在这里发表文章么?
* 真的?可以啊,请提 pull request
|
Java | UTF-8 | 1,571 | 2.078125 | 2 | [] | no_license | package com.project.digital_store.func.security.manager;
import com.project.digital_store.base.Result;
import com.project.digital_store.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/security/manager")
public class SecurityManagerController {
@Autowired
private SecurityManagerService securityManagerService;
@RequestMapping("/user")
public List<User> userList() {
return securityManagerService.getUserList();
}
@RequestMapping("/unuse/{u_id}")
public Result unuseUser(@PathVariable String u_id) {
securityManagerService.unuseUser(u_id);
return Result.success("用户已被成功禁用!");
}
@RequestMapping("/use/{u_id}")
public Result useUser(@PathVariable String u_id) {
securityManagerService.useUser(u_id);
return Result.success("用户已被成功启用!");
}
@RequestMapping("/unuses/{u_id}")
public Result unuseSeller(@PathVariable String u_id) {
securityManagerService.unuseSeller(u_id);
return Result.success("商家已被成功禁用!");
}
@RequestMapping("/uses/{u_id}")
public Result useSeller(@PathVariable String u_id) {
securityManagerService.useSeller(u_id);
return Result.success("商家已被成功启用!");
}
}
|
C | UTF-8 | 1,296 | 3 | 3 | [] | no_license | //
// math_3d.h
// lesson02
//
// Created by green on 16/5/4.
// Copyright © 2016年 xyz.chenchangqing. All rights reserved.
//
#ifndef math_3d_h
#define math_3d_h
struct Vector3f
{
float x;
float y;
float z;
Vector3f() {}
Vector3f(float _x, float _y, float _z)
{
x = _x;
y = _y;
z = _z;
}
Vector3f(const float* pFloat)
{
x = pFloat[0];
y = pFloat[0];
z = pFloat[0];
}
Vector3f(float f)
{
x = y = z = f;
}
Vector3f& operator+=(const Vector3f& r)
{
x += r.x;
y += r.y;
z += r.z;
return *this;
}
Vector3f& operator-=(const Vector3f& r)
{
x -= r.x;
y -= r.y;
z -= r.z;
return *this;
}
Vector3f& operator*=(float f)
{
x *= f;
y *= f;
z *= f;
return *this;
}
operator const float*() const
{
return &(x);
}
Vector3f Cross(const Vector3f& v) const;
Vector3f& Normalize();
void Rotate(float Angle, const Vector3f& Axis);
void Print() const
{
printf("(%.02f, %.02f, %.02f)", x, y, z);
}
};
#endif /* math_3d_h */
|
Python | UTF-8 | 57 | 2.59375 | 3 | [] | no_license | import sys
words=eval(sys.stdin.readlines())
print(words) |
C++ | UTF-8 | 2,666 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <string>
#include <cmath>
using namespace std;
const int mod = 2;
struct matrix
{
vector< vector<int> > v;
int r, c;
matrix(){}
matrix(int a, int b):r(a), c(b)
{
v.resize(r);
for(int i = 0;i < r;i++)
v[i].resize(c);
}
vector <int> & operator [](int i)
{
return v[i];
}
void operator = (int t)
{
for(int i = 0;i < r;i++) fill(v[i].begin(), v[i].end(), t);
}
matrix operator * (matrix b)
{
matrix temp(r, b.c);
for(int i = 0;i < temp.r;i++)
for(int j = 0;j < temp.c;j++)
{
int p = 0;
for(int k = 0;k < c;k++)
{
p += v[i][k] * b[k][j];
p %= 2;
}
temp[i][j] = p;
}
return temp;
}
};
matrix id(int n)
{
matrix a(n, n);
for(int i = 0;i < n;i++) a[i][i] = 1;
return a;
}
matrix operator ^ (matrix a, int n)
{
if(n == 0)
return id(a.c);
matrix ans = a ^ (n/2);
ans = ans * ans;
if(n % 2)
ans = ans * a;
return ans;
}
int main()
{
int tc;
scanf("%d",&tc);
for(int cas = 0;cas < tc;cas++)
{
int n, t;
scanf(" %d %d", &n, &t);
vector <string> name;
vector <vector<string> > rel;
rel.resize(n);
matrix ans(1, n);
matrix tr(n, n);
tr = 0;
for(int i = 0;i < n;i++)
{
string input;
cin >> input;
name.push_back(input);
int value, num;
scanf("%d %d", &value, &num);
ans[0][i] = value;
for(int j = 0;j < num;j++)
{
cin >> input;
rel[i].push_back(input);
}
}
for(int i = 0;i < n;i++)
{
for(int j = 0;j < rel[i].size();j++)
{
for(int k = 0;k < n;k++)
{
if(name[k] == rel[i][j])
{
tr[i][k] = 1;
break;
}
}
}
}
for(int i = 0;i < n;i++) tr[i][i] += 1;
/*for(int i = 0;i < n;i++)
* for(int j = 0;j < n;j++)
* printf("%d%c",tr[i][j],j==n-1?'\n':' ');*/
ans = ans * (tr ^ (t - 1));
int fin = 0;
for(int i = 0;i < n;i++) if(ans[0][i]) fin++;
printf("%d\n", fin);
}
}
|
PHP | UTF-8 | 2,333 | 2.78125 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
namespace BasicTests;
use CommonTestClass;
use kalanis\kw_cache\CacheException;
use kalanis\kw_cache\Format;
use kalanis\kw_cache\Simple\Variable;
class FormatsTest extends CommonTestClass
{
/**
* @throws CacheException
*/
public function testInit(): void
{
$factory = new Format\Factory();
$this->assertInstanceOf(Format\Format::class, $factory->getFormat(new Variable()));
}
/**
* @throws CacheException
*/
public function testRaw(): void
{
$format = new Format\Raw();
$this->assertEquals('aaaaaaa', $format->unpack($format->pack('aaaaaaa')));
$this->assertEquals('ear/a4vw-z.7v2!3#z', $format->unpack($format->pack('ear/a4vw-z.7v2!3#z')));
$cont = $this->complicatedStructure(true);
$this->assertEquals($cont, $format->unpack($format->pack($cont)));
}
/**
* @throws CacheException
*/
public function testSerialized(): void
{
$format = new Format\Serialized();
$this->assertEquals('aaaaaaa', $format->unpack($format->pack('aaaaaaa')));
$this->assertEquals('ear/a4vw-z.7v2!3#z', $format->unpack($format->pack('ear/a4vw-z.7v2!3#z')));
$cont = $this->complicatedStructure(true);
$this->assertEquals($cont, $format->unpack($format->pack($cont)));
}
/**
* @throws CacheException
*/
public function testFormat(): void
{
$format = new Format\Format();
$this->assertEquals('aaaaaaa', $format->unpack($format->pack('aaaaaaa')));
$this->assertEquals('ear/a4vw-z.7v2!3#z', $format->unpack($format->pack('ear/a4vw-z.7v2!3#z')));
$this->assertEquals(false, $format->unpack($format->pack(false)));
$this->assertEquals(1.75, $format->unpack($format->pack(1.75)));
$cont = $this->complicatedStructure(false);
$this->assertEquals($cont, $format->unpack($format->pack($cont)));
}
protected function complicatedStructure(bool $withObject = false)
{
$stdCl = new \stdClass();
$stdCl->any = 'sdgghsdfh6976h4sd';
$stdCl->sdg = 43.5424;
$stdCl->ddd = new \stdClass();
$stdCl->ddd->df56sh43 = 4351254;
return ['6g8a7' => 'dfh4dg364sd6g', 'hzsdfgh' => 35.4534, 'sfkg' => false] + ($withObject ? ['hdhg' => $stdCl] : []);
}
}
|
TypeScript | UTF-8 | 1,002 | 2.75 | 3 | [
"MIT"
] | permissive | import {Injectable} from '@nestjs/common';
import {InjectRepository} from '@nestjs/typeorm';
import {Repository} from 'typeorm';
import {Task} from '../entities/task.entity';
@Injectable()
export class TasksService {
constructor( @InjectRepository(Task) private tasksRepo: Repository<Task>
) {}
findAll(){
return this.tasksRepo.find();
}
findOne(id: number) {
return this.tasksRepo.findOne(id);
}
create(body: any){
/* const newTask = this.tasks.create(body) crea todos los atributos*/
const newTask = new Task();
newTask.name = body.name;
return this.tasksRepo.save(newTask);
}
async update (id: number, body: any) {
const task = await this.tasksRepo.findOne(id);
/* Uno a uno task.completed = true; */
this.tasksRepo.merge(task,body);
return this.tasksRepo.save(task);
}
async delete (id:number){
await this.tasksRepo.delete(id);
return true;
}
}
|
Java | UTF-8 | 4,992 | 2.5 | 2 | [] | no_license | package com.base.library.view.timingView;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.view.View;
import com.base.library.R;
import com.base.library.util.CodeUtil;
/**
* Created by wangdongyi on 2017/2/23.
* 定时控件
*/
public class TimingView extends View {
/**
* 第一圈的颜色
*/
private int mFirstColor;
/**
* 第二圈的颜色
*/
private int mSecondColor;
/**
* 圈的宽度
*/
private int mCircleWidth;
/**
* 画笔
*/
private Paint mPaint;
/**
* 当前进度
*/
private int mProgress;
/**
* 速度
*/
private int mSpeed = 10;
/**
* 是否应该开始下一个
*/
private boolean isNext = false;
private boolean working = true;
private onRunListen onRunListen;
public Runnable refreshRunnable;
private Thread mThread;
public TimingView(Context context) {
super(context);
init();
}
public TimingView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
/**
* 获取自定义控件的一些值
*
* @param context
* @param attrs
* @param defStyleAttr
*/
public TimingView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.timingView, defStyleAttr, 0);
// mFirstColor = a.getColor(R.styleable.timingView_CircleColor, Color.GRAY);
// mSpeed = a.getInt(R.styleable.timingView_CircleSpeed, 20);
// mCircleWidth = CodeUtil.dip2px(getContext(), a.getInt(R.styleable.timingView_CircleWidth, 10));
// a.recycle();
init();
}
private void init() {
mCircleWidth = CodeUtil.dip2px(getContext(), 3);
mFirstColor = ContextCompat.getColor(getContext(), R.color.white);
mSecondColor = ContextCompat.getColor(getContext(), R.color.blue);
mPaint = new Paint();
working = true;
refreshRunnable = new Runnable() {
@Override
public void run() {
while (working) {
mProgress++;
if (mProgress == 360) {
if (getOnRunListen() != null) {
getOnRunListen().onFinish();
}
working = false;
}
postInvalidate();
try {
Thread.sleep(mSpeed);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
//绘图线程
mThread = new Thread(refreshRunnable);
mThread.start();
}
@Override
protected void onDraw(Canvas canvas) {
int centre = getWidth() / 2; // 获取圆心的x坐标
int radius = centre - mCircleWidth / 2;// 半径
mPaint.setStrokeWidth(mCircleWidth); // 设置圆环的宽度
mPaint.setAntiAlias(true); // 消除锯齿
mPaint.setTextSize(CodeUtil.sp2px(getContext(), 12));
mPaint.setTextAlign(Paint.Align.CENTER);
mPaint.setStyle(Paint.Style.STROKE); // 设置空心
RectF oval = new RectF(centre - radius, centre - radius, centre + radius, centre + radius); // 用于定义的圆弧的形状和大小的界限
if (!isNext) {// 第一颜色的圈完整,第二颜色跑
mPaint.setColor(mFirstColor); // 设置圆环的颜色
canvas.drawCircle(centre, centre, radius, mPaint); // 画出圆环
mPaint.setColor(mSecondColor); // 设置圆环的颜色
canvas.drawArc(oval, -90, mProgress, false, mPaint); // 根据进度画圆弧
} else {
mPaint.setColor(mSecondColor); // 设置圆环的颜色
canvas.drawCircle(centre, centre, radius, mPaint); // 画出圆环
mPaint.setColor(mFirstColor); // 设置圆环的颜色
canvas.drawArc(oval, -90, mProgress, false, mPaint); // 根据进度画圆弧
}
}
public TimingView.onRunListen getOnRunListen() {
return onRunListen;
}
public void setOnRunListen(TimingView.onRunListen onRunListen) {
this.onRunListen = onRunListen;
}
public interface onRunListen {
void onFinish();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
closeHandler();
}
public void closeHandler() {
if (working) {
if (mThread != null && mThread.isAlive()) {
mThread.interrupt();
mThread = null;
}
working = false;
}
}
}
|
Java | UTF-8 | 5,721 | 2.078125 | 2 | [] | no_license | package com.denizenscript.depenizen.bungee;
import com.denizenscript.depenizen.common.socket.server.ClientConnection;
import com.denizenscript.depenizen.common.socket.server.SocketServer;
import com.denizenscript.depenizen.common.socket.server.packet.ServerPacketOutEvent;
import net.md_5.bungee.api.ServerPing;
import net.md_5.bungee.api.connection.PendingConnection;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.PlayerDisconnectEvent;
import net.md_5.bungee.api.event.PostLoginEvent;
import net.md_5.bungee.api.event.ProxyPingEvent;
import net.md_5.bungee.api.event.ServerSwitchEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.event.EventHandler;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class EventManager implements Listener {
private static long nextEventId;
private static final Map<Long, Map<String, String>> eventDeterminations = new HashMap<>();
private static final Map<String, List<ClientConnection>> eventSubscriptions = new HashMap<>();
public static void subscribe(String event, ClientConnection client) {
if (!eventSubscriptions.containsKey(event)) {
eventSubscriptions.put(event, new ArrayList<ClientConnection>());
}
eventSubscriptions.get(event).add(client);
}
public static void unsubscribe(String event, ClientConnection client) {
if (eventSubscriptions.containsKey(event)) {
eventSubscriptions.get(event).remove(client);
}
}
@EventHandler
public void onProxyPing(ProxyPingEvent event) {
if (!isSubscribedTo("ProxyPing")) {
return;
}
Map<String, String> context = new HashMap<>();
PendingConnection connection = event.getConnection();
context.put("address", connection.getAddress().toString());
ServerPing ping = event.getResponse();
context.put("protocol", String.valueOf(ping.getVersion().getProtocol()));
context.put("true-version", ping.getVersion().getName()); // true version name
context.put("version", String.valueOf(connection.getVersion())); // legacy protocol version
ServerPing.Players players = ping.getPlayers();
context.put("num_players", String.valueOf(players.getOnline()));
context.put("max_players", String.valueOf(players.getMax()));
context.put("motd", ping.getDescription());
Map<String, String> determinations = sendEventPacket(true, "ProxyPing", context);
if (determinations != null) {
players.setOnline(Integer.valueOf(determinations.get("num_players")));
players.setMax(Integer.valueOf(determinations.get("max_players")));
ping.setDescription(determinations.get("motd"));
ping.getVersion().setName(determinations.get("version"));
}
}
@EventHandler
public void onPostLogin(PostLoginEvent event) {
if (!isSubscribedTo("PostLogin")) {
return;
}
Map<String, String> context = new HashMap<>();
ProxiedPlayer player = event.getPlayer();
context.put("uuid", player.getUniqueId().toString());
context.put("name", player.getName());
sendEventPacket(false, "PostLogin", context);
}
@EventHandler
public void onPlayerDisconnect(PlayerDisconnectEvent event) {
if (!isSubscribedTo("PlayerDisconnect")) {
return;
}
Map<String, String> context = new HashMap<>();
ProxiedPlayer player = event.getPlayer();
context.put("uuid", player.getUniqueId().toString());
context.put("name", player.getName());
sendEventPacket(false, "PlayerDisconnect", context);
}
@EventHandler
public void onServerSwitch(ServerSwitchEvent event) {
if (!isSubscribedTo("ServerSwitch")) {
return;
}
Map<String, String> context = new HashMap<>();
ProxiedPlayer player = event.getPlayer();
context.put("uuid", player.getUniqueId().toString());
context.put("name", player.getName());
context.put("server", player.getServer().getInfo().getName());
sendEventPacket(false, "ServerSwitch", context);
}
private static boolean isSubscribedTo(String name) {
return eventSubscriptions.containsKey(name) && !eventSubscriptions.get(name).isEmpty();
}
private static Map<String, String> sendEventPacket(boolean getResponse, String name, Map<String, String> context) {
long id = nextEventId;
nextEventId++;
ServerPacketOutEvent packet = new ServerPacketOutEvent(id, name, context, getResponse);
SocketServer socketServer = DepenizenPlugin.getCurrentInstance().getSocketServer();
if (socketServer != null) {
for (ClientConnection client : eventSubscriptions.get(name)) {
client.trySend(packet);
}
if (getResponse) {
waitForResponse(id);
return eventDeterminations.get(id);
}
}
return null;
}
private static void waitForResponse(long id) {
try {
synchronized (eventDeterminations) {
while (!eventDeterminations.containsKey(id)) {
eventDeterminations.wait();
}
}
}
catch (Exception e) {
dB.echoError(e);
}
}
public static void respond(long id, Map<String, String> determinations) {
synchronized (eventDeterminations) {
eventDeterminations.put(id, determinations);
eventDeterminations.notify();
}
}
}
|
JavaScript | UTF-8 | 1,920 | 3.078125 | 3 | [] | no_license | function disable(el) {
el.disabled = true;
}
function enable(el) {
el.disabled = false;
}
function focus(el) {
el.focus();
}
export function $(el) {
return document.querySelector(el);
}
export function $$(el) {
return document.querySelectorAll(el);
}
export function text(el, text) {
el.textContent = text;
}
export function bgColor(el, color) {
el.style.backgroundColor = color;
}
export function renderGuesses(guesses) {
text($(".guesses"), guesses.join(", "));
}
export function renderSuccess(message) {
var lastResult = $(".lastResult");
var lowOrHi = $(".lowOrHi");
bgColor(lastResult, "green");
text(lastResult, message);
text(lowOrHi, "");
}
export function renderError(
userGuess,
randomNumber,
errorMessage,
lowErroMessage,
highErrorMessage
) {
var lastResult = $(".lastResult");
var lowOrHi = $(".lowOrHi");
var lowHiText = userGuess < randomNumber ? lowErroMessage : highErrorMessage;
text(lastResult, errorMessage);
text(lowOrHi, lowHiText);
bgColor(lastResult, "red");
}
export function renderGameOver(buttonLabel, callback) {
disable($(".guessField"));
disable($(".guessSubmit"));
var resetButton = document.createElement("button");
resetButton.className = "reset-button";
text(resetButton, buttonLabel);
resetButton.addEventListener("click", callback);
document.body.appendChild(resetButton);
}
export function renderResetGame() {
var resetParas = $$(".resultParas p");
var resetButton = $(".reset-button");
var lastResult = $(".lastResult");
for (var i = 0; i < resetParas.length; i++) {
resetParas[i].textContent = "";
}
resetButton.parentNode.removeChild(resetButton);
renderResetGuessField();
enable($(".guessSubmit"));
bgColor(lastResult, "white");
}
export function renderResetGuessField() {
var guessField = $(".guessField");
guessField.value = "";
enable(guessField);
focus(guessField);
}
|
PHP | UTF-8 | 1,267 | 3.015625 | 3 | [] | no_license | <?php
class EnqueteManager
{
private $db;
public function __construct($db)
{
$this->db = $db;
}
public function addEnquete($enquete)
{
$requete = $this->db->prepare(
'INSERT INTO enquetes (en_nom, oi_num, organisateur, proto_num, date_deb, date_fin)
VALUES (:en_nom, :oi_num, :organisateur, :proto_num, :date_deb, :date_fin);');
$requete->bindValue(':en_nom', $enquete->getEnqueteNom());
$requete->bindValue(':oi_num', $enquete->getOiseauNum());
$requete->bindValue(':organisateur', $enquete->getOrganisateur());
$requete->bindValue(':proto_num', $enquete->getProtocoleNum());
$requete->bindValue(':date_deb', $enquete->getDateDebut());
$requete->bindValue(':date_fin', $enquete->getDateFin());
$retour = $requete->execute();
return $retour;
}
public function getNumByNom($nom)
{
$requete = $this->db->prepare(
'SELECT en_num FROM enquetes WHERE en_nom = :nom');
$requete->bindValue(':nom', $nom, PDO::PARAM_STR);
$requete->execute();
$enqueteNum = $requete->fetch(PDO::FETCH_ASSOC);
return $enqueteNum['en_num'];
}
}
?>
|
Shell | UTF-8 | 779 | 3.03125 | 3 | [] | no_license | #!/bin/bash
[ -z "$1" ] && exit 1
NAME=$1
shift
if [ "${NAME}" -ge 0 2>/dev/null ]
then
ENTRY=$( \
ldapsearch -x -LLL -h ldap.corp.redhat.com \
-b ou=users,dc=redhat,dc=com \
"(|(employeeNumber=${NAME})(rhatOraclePersonID=${NAME}))" $@ \
)
elif echo "${NAME}" | grep -q @
then
ENTRY=$( \
ldapsearch -x -LLL -h ldap.corp.redhat.com \
-b ou=users,dc=redhat,dc=com \
"(mail=*${NAME}*)" $@ \
)
else
ENTRY=$( \
ldapsearch -x -LLL -h ldap.corp.redhat.com \
-b ou=users,dc=redhat,dc=com \
"(|(cn=*${NAME}*)(uid=${NAME}))" $@ \
)
fi
#export LESS_TERMCAP_so=$'\E[30;43m'
#export LESS_TERMCAP_se=$'\E[0m'
export LESS_TERMCAP_so=$'\E[38;5;0m\E[48;5;208m'
export LESS_TERMCAP_se=$'\E[0m'
echo "$ENTRY" | less -R -p "${NAME}"
|
Java | UTF-8 | 14,369 | 2.28125 | 2 | [] | no_license | package f1app.gui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.Border;
import f1app.core.Circuit;
import f1app.core.Circuits;
import f1app.core.F1Coord;
import f1app.core.LapTime;
import f1app.core.Tyres;
public class MainPanel extends JPanel {
private static final long serialVersionUID = 1L;
private F1Coord f1Coord;
private List<CircuitPanel> circuits;
private CircuitPanel selectedCircuitPanel;
private JPanel upperPanel;
// Listeners for different events
private CircuitPanelListener circuitListener;
private LapButtonsListener lapsButtonsListener;
private JScrollPane scrollPane;
private JPanel lowerPanel;
private JPanel informationPanel;
private JPanel circuitPanel;
private JLabel circuitMap;
// Components for the informationPanel, these need to be set by information from the core system
private JLabel trackLabel;
private JLabel trackLength;
private JLabel lapRecord;
private JLabel seasonRecord;
private JLabel optionTyreTime;
private JLabel primeTyreTime;
private JLabel intermediateTyreTime;
private JLabel wetTyreTime;
private JButton addTimeButton;
private JButton deleteTimeButton;
public MainPanel() {
setup();
}
private void setup() {
f1Coord = F1Coord.getInstance();
circuits = new ArrayList<>();
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
// upperPanel
upperPanel = new JPanel();
setupUpperPanel();
scrollPane = new JScrollPane(upperPanel);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
gc.weightx = 1;
gc.weighty = 1;
gc.gridx = 1;
gc.gridy = 1;
gc.fill = GridBagConstraints.BOTH;
add(scrollPane, gc);
// lowerPanel
lowerPanel = new JPanel();
setupLowerPanel();
gc.gridy = 2;
add(lowerPanel, gc);
// load Australia CircuitPanel
fireUpdateCircuitTime(f1Coord.getCircuit(Circuits.AUSTRALIA));
}
private void setupUpperPanel() {
circuitListener = new CircuitPanelListener();
upperPanel.setLayout(new GridBagLayout());
GridBagConstraints gcUpper = new GridBagConstraints();
int gridXNumber = 1;
gcUpper.weightx = 1;
gcUpper.weighty = 1;
gcUpper.gridx = gridXNumber;
gcUpper.gridy = 1;
gcUpper.fill = GridBagConstraints.VERTICAL;
gcUpper.anchor = GridBagConstraints.FIRST_LINE_START;
for (Circuits circuit : Circuits.values()) {
gridXNumber++;
gcUpper.gridx = gridXNumber;
CircuitPanel circuitPanel = new CircuitPanel(circuit.getCountry(), circuit.getCircuitName());
circuits.add(circuitPanel);
circuitPanel.addMouseListener(circuitListener);
upperPanel.add(circuitPanel, gcUpper);
}
}
private void setupLowerPanel() {
lowerPanel.setLayout(new GridBagLayout());
GridBagConstraints gcLower = new GridBagConstraints();
gcLower.weightx = 1;
gcLower.weighty = 1;
gcLower.gridx = 1;
gcLower.gridy = 1;
gcLower.fill = GridBagConstraints.BOTH;
setupInformationPanel();
lowerPanel.add(informationPanel, gcLower);
setupCircuitPanel();
gcLower.gridx = 2;
lowerPanel.add(circuitPanel, gcLower);
selectedCircuitPanel = circuits.get(0);
}
private void setupInformationPanel() {
informationPanel = new JPanel();
informationPanel.setPreferredSize(new Dimension(250, 100));
informationPanel.setBackground(Color.GREEN);
informationPanel.setLayout(new GridBagLayout());
GridBagConstraints gcInformationPanel = new GridBagConstraints();
// Add components to the information panel
gcInformationPanel.weightx = 1;
gcInformationPanel.weighty = 1;
gcInformationPanel.gridx = 1;
gcInformationPanel.gridy = 1;
gcInformationPanel.gridwidth = 2;
trackLabel = new JLabel("Track Name Label");
informationPanel.add(trackLabel, gcInformationPanel);
gcInformationPanel.gridy = 2;
gcInformationPanel.gridwidth = 1;
gcInformationPanel.anchor = GridBagConstraints.LINE_END;
informationPanel.add(new JLabel("Length: "), gcInformationPanel);
gcInformationPanel.gridy = 3;
informationPanel.add(new JLabel("Record: "), gcInformationPanel);
gcInformationPanel.gridy = 4;
informationPanel.add(new JLabel("2013 Time: "), gcInformationPanel);
gcInformationPanel.gridy = 2;
gcInformationPanel.gridx = 2;
gcInformationPanel.anchor = GridBagConstraints.LINE_START;
trackLength = new JLabel("1.5 Miles");
informationPanel.add(trackLength, gcInformationPanel);
gcInformationPanel.gridy = 3;
gcInformationPanel.gridx = 2;
lapRecord = new JLabel("1:10:43 - Michael Schumacher");
informationPanel.add(lapRecord, gcInformationPanel);
gcInformationPanel.gridy = 4;
gcInformationPanel.gridx = 2;
seasonRecord = new JLabel("1:12:01 - Sebastien Vettel");
informationPanel.add(seasonRecord, gcInformationPanel);
gcInformationPanel.gridx = 1;
gcInformationPanel.gridy = 5;
gcInformationPanel.anchor = GridBagConstraints.LAST_LINE_END;
// TODO NEXT B: Make this "Lap Times" text bold/underlined
informationPanel.add(new JLabel("Lap Times: "), gcInformationPanel);
gcInformationPanel.gridx = 1;
gcInformationPanel.gridy = 6;
gcInformationPanel.anchor = GridBagConstraints.LINE_END;
informationPanel.add(new JLabel(Tyres.OPTION + ": "), gcInformationPanel);
gcInformationPanel.gridy = 7;
informationPanel.add(new JLabel(Tyres.PRIME + ": "), gcInformationPanel);
gcInformationPanel.gridy = 8;
informationPanel.add(new JLabel(Tyres.INTER + ": "), gcInformationPanel);
gcInformationPanel.gridy = 9;
informationPanel.add(new JLabel(Tyres.WET + ": "), gcInformationPanel);
gcInformationPanel.gridx = 2;
gcInformationPanel.gridy = 6;
gcInformationPanel.anchor = GridBagConstraints.LINE_START;
optionTyreTime = new JLabel();
informationPanel.add(optionTyreTime, gcInformationPanel);
gcInformationPanel.gridy = 7;
primeTyreTime = new JLabel();
informationPanel.add(primeTyreTime, gcInformationPanel);
gcInformationPanel.gridy = 8;
intermediateTyreTime = new JLabel();
informationPanel.add(intermediateTyreTime, gcInformationPanel);
gcInformationPanel.gridy = 9;
wetTyreTime = new JLabel();
informationPanel.add(wetTyreTime, gcInformationPanel);
// The JPanel to hold the two buttons that add and remove times
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(Color.GREEN);
FlowLayout flow = (FlowLayout) buttonPanel.getLayout();
flow.setHgap(20);
ActionListener buttonActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JButton buttonPressed = (JButton)e.getSource();
if(buttonPressed == addTimeButton) {
lapsButtonsListener.addLapPressed(selectedCircuitPanel.countryName);
} else {
lapsButtonsListener.deleteLapPressed(selectedCircuitPanel.countryName);
}
}
};
addTimeButton = new JButton("Add Time");
addTimeButton.addActionListener(buttonActionListener);
deleteTimeButton = new JButton("Delete Time");
deleteTimeButton.addActionListener(buttonActionListener);
buttonPanel.add(addTimeButton);
buttonPanel.add(deleteTimeButton);
gcInformationPanel.gridwidth = 2;
gcInformationPanel.weighty = 0.2;
gcInformationPanel.gridx = 1;
gcInformationPanel.gridy = 10;
gcInformationPanel.fill = GridBagConstraints.BOTH;
informationPanel.add(buttonPanel, gcInformationPanel);
addTimeButton.setPreferredSize(deleteTimeButton.getPreferredSize());
// Set the first track displayed (Australia)
Circuits selectedCircuitType = Circuits.AUSTRALIA;
Circuit circuit = f1Coord.getCircuit(selectedCircuitType);
trackLabel.setText(selectedCircuitType.getCircuitName());
trackLength.setText(circuit.getLength());
lapRecord.setText(circuit.getLapRecord());
seasonRecord.setText(circuit.getTime2013());
}
private void updateInformationPanel() {
// Two switches, one to add a lap time and one to clear the displayed lap time if there is none stored
String text = null;
for (Map.Entry<Tyres, LapTime> entry : selectedCircuitPanel.times.entrySet()) {
if(entry.getValue() == null)
text = "";
else
text = entry.getValue().toString();
switch (entry.getKey()) {
case OPTION:
optionTyreTime.setText(text);
break;
case PRIME:
primeTyreTime.setText(text);
break;
case INTER:
intermediateTyreTime.setText(text);
break;
case WET:
wetTyreTime.setText(text);
break;
}
}
}
private void setupCircuitPanel() {
circuitPanel = new JPanel();
circuitPanel.setBackground(Color.WHITE);
circuitPanel.setLayout(new GridBagLayout());
GridBagConstraints gcCircuitPanel = new GridBagConstraints();
gcCircuitPanel.weightx = 1;
gcCircuitPanel.weighty = 1;
gcCircuitPanel.gridx = 1;
gcCircuitPanel.gridy = 1;
gcCircuitPanel.anchor = GridBagConstraints.CENTER;
circuitMap = new JLabel(new ImageIcon(this.getClass().getResource("/Resources/Images/" + "australia" + "track.png")));
circuitPanel.add(circuitMap, gcCircuitPanel);
}
private ImageIcon loadImage(String imageName) {
return new ImageIcon(this.getClass().getResource("/Resources/Images/" + imageName + ".png"));
}
/**
* @param addLapListener the addLapListener to set
*/
public void setLapsButtonsListener(LapButtonsListener addLapListener) {
this.lapsButtonsListener = addLapListener;
}
/**
* Updates the times Map in the CircuitPanel object that has been edited, also changes the displayed CircuitPanel if necessary.
* @param circuit, the Circuit object that has been updated
*/
public void fireUpdateCircuitTime(Circuit circuit) {
for (CircuitPanel circuitPanel : circuits) {
if (circuitPanel.countryName.equals(circuit.getCircuitType().getCountry())) {
circuitPanel.updateTimes(circuit.getCircuitTimes());
if(selectedCircuitPanel != circuitPanel) {
// Sets the displayed CircuitPanel as the one that has just been edited
circuitListener.mouseClicked(new MouseEvent(circuitPanel, MouseEvent.MOUSE_PRESSED, 0, 0, 0, 0, 1, false));
}
break;
}
}
}
/**
* JPanel that displays a circuit`s name, location and image
* @author Charlie
*
*/
private class CircuitPanel extends JPanel {
private static final long serialVersionUID = 1L;
private String countryName;
private String circuitName;
private JLabel circuitLabel;
private JLabel countryLabel;
private JLabel circuitPicture;
private ImageIcon circuitImage;
private Border border;
private Map<Tyres, LapTime> times;
public CircuitPanel(String countryName, String circuitName) {
Circuits circuit = Circuits.valueOf(countryName.toUpperCase().replace(" ", "_"));
times = f1Coord.getCircuit(circuit).getCircuitTimes();
this.countryName = countryName;
this.circuitName = circuitName;
setup();
}
private void setup() {
setPreferredSize(new Dimension((MainFrame.WIDTH / 4), 40));
setLayout(new GridBagLayout());
GridBagConstraints gcCircuit = new GridBagConstraints();
countryLabel = new JLabel(countryName);
gcCircuit.weightx = 1;
gcCircuit.weighty = 1;
gcCircuit.gridx = 1;
gcCircuit.gridy = 1;
add(countryLabel, gcCircuit);
circuitLabel = new JLabel(circuitName);
gcCircuit.gridy = 2;
add(circuitLabel, gcCircuit);
String imageName = countryName.replace(" ", "_");
circuitImage = loadImage(imageName + "icon");
circuitPicture = new JLabel(circuitImage);
gcCircuit.gridy = 3;
add(circuitPicture, gcCircuit);
border = BorderFactory.createLineBorder(Color.black);
setBorder(border);
// If Australia then displayed as default
if (countryName.equals("Australia")) {
setFontColor(Color.WHITE);
setBackground(Color.GRAY);
}
}
/**
* Sets the font color for the circuit and country JLabels
* @param aColor the color to set the text to
*/
public void setFontColor(Color aColor) {
circuitLabel.setForeground(aColor);
countryLabel.setForeground(aColor);
}
/**
* Returns the color of the font of the circuit and country JLabels
* @return the font color of the circuitLabel
*/
public Color getFontColor() {
return circuitLabel.getForeground();
}
// TODO NEXT B: give images a see through background for hightlighting
// TODO NEXT B: Need to fit four circuits across the top of the MainPanel perfectly.
public void updateTimes(Map<Tyres, LapTime> times) {
this.times = times;
// Check if the current circuit is displayed
if (selectedCircuitPanel == this) {
updateInformationPanel();
}
}
}
/***
* Listens for mouse clicks on the CircuitPanels and changes the user interface to reflect the selected circuit
* @author Charlie
*
*/
private class CircuitPanelListener extends MouseAdapter {
/* (non-Javadoc)
* @see java.awt.event.MouseAdapter#mouseClicked(java.awt.event.MouseEvent)
*/
@Override
public void mouseClicked(MouseEvent e) {
CircuitPanel clicked = (CircuitPanel) e.getSource();
// Set the previously clicked CircuitPanel back to the default colours
for (CircuitPanel circuitPanel : circuits) {
if (circuitPanel.getFontColor() == Color.WHITE) {
circuitPanel.setFontColor(Color.BLACK);
circuitPanel.setBackground(Color.WHITE);
}
}
// Highlight the newly selected CircuitPanel
clicked.setFontColor(Color.WHITE);
clicked.setBackground(Color.GRAY);
// Change the circuit picture
circuitMap.setIcon(loadImage(clicked.countryName.toLowerCase().replace(" ", "_") + "track"));
// Change the information displayed
Circuits selectedCircuitType = Circuits.valueOf(clicked.countryName.toUpperCase().replace(" ", "_"));
Circuit circuit = f1Coord.getCircuit(selectedCircuitType);
trackLabel.setText(selectedCircuitType.getCircuitName());
trackLength.setText(circuit.getLength());
lapRecord.setText(circuit.getLapRecord());
seasonRecord.setText(circuit.getTime2013());
// Set the currently selected circuit panel
selectedCircuitPanel = clicked;
updateInformationPanel();
}
}
}
|
PHP | UTF-8 | 2,404 | 2.828125 | 3 | [] | no_license | <?php
namespace Shepherd\Bundle\ProcessPoolBundle;
use Shepherd\Bundle\ProcessPoolBundle\Exception\ProcessExecutionError;
use Psr\Log\LoggerInterface;
use Symfony\Component\Process\Process;
class ProcessPool
{
/** @var LoggerInterface */
private $logger;
/** @var array */
private $pool = [];
/** @var int */
private $maxProcesses;
/** @var Boolean */
private $failOnError;
/**
* ProcessPool constructor.
* @param LoggerInterface $logger
* @param int $maxProcesses
* @param bool $failOnError
*/
public function __construct(LoggerInterface $logger, $maxProcesses, $failOnError = false)
{
$this->logger = $logger;
$this->maxProcesses = $maxProcesses;
$this->failOnError = $failOnError;
}
/**
* @param Process $process
*/
public function append(Process $process)
{
$this->pool[] = $process;
}
/**
* @return int
*/
private function getActiveProcessCount()
{
return count(array_filter($this->pool, function ($process) {
/** @var Process $process */
return $process->isRunning();
}));
}
public function start()
{
$this->logger->debug('Starting queue consumption.');
while (count($this->pool) > 0) {
/** @var Process $process */
foreach ($this->pool as $key => $process) {
usleep(50000);
if ($process->isRunning()) {
continue;
}
if ($process->isTerminated()) {
if (!$process->isSuccessful()) {
$this->logger->error('sub process failed.', array(
'command' => $process->getCommandLine(),
'output' => $process->getOutput()
));
if ($this->failOnError) {
throw new ProcessExecutionError("The process returned non-zero exit code.");
}
}
unset($this->pool[$key]);
continue;
}
if ($this->getActiveProcessCount() < $this->maxProcesses) {
$process->start();
}
}
}
$this->logger->debug('All processes are done.');
}
}
|
JavaScript | UTF-8 | 3,219 | 2.53125 | 3 | [] | no_license | import React, { Component } from "react";
import PropTypes from "prop-types";
import "./carousel.scss";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faChevronLeft, faChevronRight } from "@fortawesome/free-solid-svg-icons";
import Image from "../media/image";
import Container from "./container"
export default class Carousel extends Component {
constructor(props) {
super(props)
this.state = { activeImg: 0, numberImgs: props.children.length, seconds: 0, changeSeconds: this.props.changeSeconds, interval: null }
}
changeImg(direction) {
let current = this.state.activeImg
if (direction === 0) {
if ((current - 1) >= 0) { current-- }
} else {
if ((current + 1) < this.state.numberImgs) { current++ }
}
// Update the current img and reset the change timer
this.setState({ activeImg: current, seconds: 0 })
}
changeImagePill(index) {
// Update the current img and reset the change timer
this.setState({ activeImg: index, seconds: 0 })
}
changeImgTimer() {
let current = this.state.activeImg
if ((current + 1) < this.state.numberImgs) {
current++
} else {
current = 0
}
// Update the current img and reset the change timer
this.setState({ activeImg: current, seconds: 0 })
}
tick() {
// If the time + 1 !== the number of seconds chosen to change the img then increment the count otherwise reset it
this.setState(prevState => ({ seconds: prevState.seconds + 1 }), () => { this.state.seconds > this.state.changeSeconds ? this.setState({ seconds: 0 }, this.changeImgTimer()) : null })// this.changeImgTick())
}
componentDidMount() {
// Initiate the timer if the changeSeconds value is greater than or equal than 0
this.state.changeSeconds >= 0 ? this.setState({ interval: setInterval(() => this.tick(), 1000) }) : null
//clearInterval(this.state.interval)
}
componentWillUnmount() {
clearInterval(this.state.interval)
}
render() {
let carouselChildren = React.Children.map(this.props.children, (child, index) => {
if (index === this.state.activeImg) {
return child
}
})
let carouselPills = React.Children.map(this.props.children, (child, index) => {
return <div key={index} className={index === this.state.activeImg ? "carousel-pill active" : "carousel-pill"} style={{ width: 100 / this.state.numberImgs + "%" }} onClick={() => this.changeImagePill(index)} />
})
return (
<div className="carousel">
<div className="carousel-img-container">
{carouselChildren}
</div>
<div className="carousel-mover chevron-left" onClick={() => this.changeImg(0)}><FontAwesomeIcon icon={faChevronLeft} size={"5x"} /></div>
<div className="carousel-mover chevron-right" onClick={() => this.changeImg(1)}><FontAwesomeIcon icon={faChevronRight} size={"5x"} /></div>
{
this.props.pills === true ?
<div className="carousel-pill-container">
{carouselPills}
</div>
: null
}
</div>
);
}
}
Carousel.propTypes = {
pills: PropTypes.bool.isRequired,
changeSeconds: PropTypes.number.isRequired
} |
C | UTF-8 | 12,126 | 2.71875 | 3 | [] | no_license | #ifndef _DIFF_H_
#define _DIFF_H_
enum TeXPos
{
TeX_start = 1,
TeX_print = 2,
TeX_finish = 3
};
enum DiffStatus
{
diff = 1,
nodiff = 2,
enddiff = 3,
bread = 4,
bread2 = 5,
bread3 = 6
};
enum TeXPhrase
{
StartDiff = 1,
FinishDiff = 2,
ShortDiff = 3,
PresentDiff = 4,
InDiff = 5
};
enum NodeTypes
{
symbol_t = 1,
value_t = 2,
op_t = 3,
const_t = 4
};
char * readfile(char * filename, int * pos)
{
assert(filename != NULL);
assert(pos != NULL);
FILE * file = fopen(filename, "r");
if (file == NULL)
{
printf("%s\n", "Error reading file int f. readfile");
return NULL;
}
fseek(file, 0, SEEK_END);
*pos = ftell(file);
char * text = (char*)calloc(*pos + 1, sizeof(char));
fseek(file, 0, SEEK_SET);
fread(text, sizeof(char), *pos, file);
fclose(file);
return text;
}
Node * TreeCopy(tree * t, Node * top, Node * n, char branch)
{
assert(t != NULL);
assert(n != NULL);
Node * new_node = NodeAlloc(t);
new_node->word = strdup(n->word);
new_node->type = n->type;
new_node->parent = top;
if(top != NULL)
{
if(branch == 'L')
{
top->left = new_node;
}
else if (branch == 'R')
{
top->right = new_node;
}
}
if (n->left != NULL) TreeCopy(t, new_node, n->left, 'L');
if (n->right != NULL) TreeCopy(t, new_node, n->right, 'R');
return new_node;
}
/*Node * TreeCopy(tree * t, Node * top, Node * n, char branch)
{
assert(t != NULL);
assert(n != NULL);
if (top != NULL)
{
char * per = top->word;
}
return _TreeCopy(t, top, n, branch);
}*/
Node * TypeNode(tree * t, int type, char * data, Node * l, Node * r)
{
Node * n = NodeAlloc(t);
if(type == op_t)
{
n->left = l;
n->right = r;
if(l != NULL) l->parent = n;
if(r != NULL) r->parent = n;
n->type = op_t;
n->word = strdup(data);
}
else
{
n->left = NULL;
n->right = NULL;
n->type = type;
n->word = strdup(data);
}
return n;
}
Node * PrintTexDescent(tree * t, Node * n, FILE * file_TeX, int status, int * rec)
{
assert(t != NULL);
assert(n != NULL);
(*rec)++;
if (status == diff) fprintf(file_TeX, "\\left( ");
if (n->word[0] == '/') fprintf(file_TeX, "\\frac{");
if (strcmp("log", n->word) == 0) fprintf(file_TeX, "\\log_");
if ((n->word[0] == '+') || (n->word[0] == '-'))
if (n->parent != NULL)
{
if (strcmp("sqrt", n->parent->word) != 0) fprintf(file_TeX, "\\left( ");
}
else fprintf(file_TeX, "\\left( ");
if (n->left != NULL)
{
if (strcmp("sqrt", n->word) == 0) fprintf(file_TeX, "\\%s {", n->word);
if ((n->right == NULL) && (strcmp("sqrt", n->word) != 0)) fprintf(file_TeX, "%s \\left( ", n->word);
fprintf(file_TeX, "{");
PrintTexDescent(t, n->left, file_TeX, nodiff, rec);
fprintf(file_TeX, "}");
if (n->right != NULL)
{
if ((n->word[0] != '/') && (strcmp("log", n->word) != 0)) fprintf(file_TeX, "%s ", n->word);
}
else if (strcmp("sqrt", n->word) != 0) fprintf(file_TeX, "\\right) ");
else fprintf(file_TeX, "} ");
}
if (n->word[0] == '/') fprintf(file_TeX, "}{");
if (n->right != NULL)
{
if (strcmp("log", n->word) == 0) fprintf(file_TeX, "\\left( ");
fprintf(file_TeX, "{");
PrintTexDescent(t, n->right, file_TeX, nodiff, rec);
fprintf(file_TeX, "}");
if (strcmp("log", n->word) == 0) fprintf(file_TeX, "\\right) ");
}
if ((n->left == NULL) && (n->right == NULL)) fprintf(file_TeX, "%s ", n->word);
if (n->word[0] == '/') fprintf(file_TeX, "}");
if ((n->word[0] == '+') || (n->word[0] == '-'))
if (n->parent != NULL)
{
if (strcmp("sqrt", n->parent->word) != 0) fprintf(file_TeX, "\\right) ");
}
else fprintf(file_TeX, "\\right) ");
if (status == diff) fprintf(file_TeX, "\\right)' ");
return n;
}
void TeXPrint(tree * t, Node * n, int pos, int status)
{
switch (pos)
{
case TeX_start:
{
FILE * file_TeX = fopen("differ.tex","w+");
assert(file_TeX != NULL);
fprintf(file_TeX, "\\documentclass[a4paper,12pt]{article}\n");
fprintf(file_TeX, "\\usepackage[T2A]{fontenc}\n\\usepackage[utf8]{inputenc}\n\\usepackage[english,russian]{babel}\n");
fprintf(file_TeX, "\\usepackage{amsmath,amsfonts,amssymb,amsthm,mathtools}\n");
fprintf(file_TeX, "\\author{By Borisenkov Ivan} \n\\title{Differentiator \\LaTeX{}} \n\\date{\\today}");
fprintf(file_TeX, "\\begin{document}\n\\maketitle\n\\newpage");
fclose(file_TeX);
break;
}
case TeX_print:
{
assert(t != NULL);
assert(n != NULL);
int recurs = 0;
FILE * file_TeX = fopen("differ.tex", "a+");
assert(file_TeX != NULL);
fprintf(file_TeX, "\\begin{equation}\n");
PrintTexDescent(t, n, file_TeX, status, &recurs);
if (status != enddiff) fprintf(file_TeX, "=");
fprintf(file_TeX, "\n\\end{equation}\n");
fclose(file_TeX);
break;
}
case TeX_finish:
{
FILE *file_TeX = fopen("differ.tex", "a+");
assert(file_TeX != NULL);
fprintf(file_TeX, "\\end{document}\n");
fclose(file_TeX);
break;
}
default: break;
}
}
void MoyaLubovKMatanu(int phrase, int status)
{
FILE * file_TeX = fopen("differ.tex", "a+");
assert(file_TeX != NULL);
switch (phrase)
{
case StartDiff:
fprintf(file_TeX, "\nПрезренный, тебе что, неизвестно, как найти такую производную?\n");
fprintf(file_TeX, "Так уж и быть, я найду её для тебя. Слишком изи фор ми.\n");
break;
case FinishDiff:
fprintf(file_TeX, "Видишь, презренный. Я же говорил, что это проще простого.\n");
fprintf(file_TeX, "А теперь вон с глаз моих!\n");
break;
case InDiff:
if(status == 0) fprintf(file_TeX, "Чтобы ты хотя бы что-то понял, я рассмотрю производные функции по частям\n");
else switch (status)
{
case diff:
fprintf(file_TeX, "Понимаешь ли ты, что это изи. Состатб+лежатб, ща всё сделаем\n");
break;
case nodiff:
fprintf(file_TeX, "Очевидно, что,\n");
break;
case enddiff:
fprintf(file_TeX, "Оставив некоторые преобразования на додумку читателю, запишем,\n");
break;
case bread:
fprintf(file_TeX, "Как же мне надоело заниматься такой фигнёй. Какие блин производные я создан для чего-то большего!\n");
break;
case bread2:
fprintf(file_TeX, "Кстати, а я рассказвал тебе сказку о паравозике, который смог?\n");
break;
case bread3:
fprintf(file_TeX, "ЕСКЕРЕ КСЕРЕ ЛЕТС ГЕТЬ ИТ\n");
break;
default: break;
}
break;
case ShortDiff:
fprintf(file_TeX, "Произведём элементарные преобразования.\n");
break;
case PresentDiff:
fprintf(file_TeX, "Вот так это выглядит, презренный.\n");
break;
default: break;
}
fclose(file_TeX);
}
void TypeIdentify(tree * diffTree, Node * n)
{
if (!n) return;
bool not_finished = true;
#define DIFF_(Name, Type, Declaration)\
if (strcmp(#Name, n->word) == 0) {\
n->type = Type;\
not_finished = false;\
}
#include "func.h"
#undef DIFF_
if (not_finished)
{
if ('0' <= (n->word[0]) && (n->word[0]) <= '9')
{
n->type = value_t;
}
else if ((strcmp("pi", n->word) == 0) || (strcmp("e", n->word) == 0) || (strcmp("π", n->word) == 0))
{
n->type = const_t;
}
else
{
n->type = symbol_t;
}
}
TypeIdentify(diffTree, n->left);
TypeIdentify(diffTree, n->right);
}
void Variable(int * rofl)
{
if((*rofl)%4 == 0 && (*rofl) != 1)
{
MoyaLubovKMatanu(InDiff, bread);
(*rofl)++;
}
else if((*rofl)%6== 0 && (*rofl) != 1)
{
MoyaLubovKMatanu(InDiff, bread2);
(*rofl)++;
}
else if((*rofl)%7 == 0 && (*rofl) != 1)
{
MoyaLubovKMatanu(InDiff, bread3);
(*rofl)++;
}
else if((*rofl)%11 == 0 && (*rofl) != 1)
{
MoyaLubovKMatanu(InDiff, enddiff);
(*rofl) = 3;
}
else
{
MoyaLubovKMatanu(InDiff, nodiff);
}
}
Node * Differenciator (tree * t, Node * n, int * rofl)
{
assert(t != NULL);
assert(n != NULL);
(*rofl)++;
Node * indif = NULL;
if (n->type == value_t || n->type == const_t)
{
char * dc = (char*)calloc(2, sizeof(char));
assert(dc != NULL);
memcpy(dc, "0", 2);
indif = TypeNode(t, value_t, dc, NULL, NULL);
assert(indif != NULL);
}
if(n->type == symbol_t)
{
char * dx = (char*)calloc(2, sizeof(char));
assert(dx != NULL);
memcpy(dx, "1", 2);
indif = TypeNode(t, value_t, dx, NULL, NULL);
assert(indif != NULL);
}
if(n->type == op_t)
{
#define DIFF_(Name, Type, Declaration)\
if (strcmp(#Name, n->word) == 0) {\
indif = Declaration;\
assert(indif != NULL);\
Variable(rofl);\
TeXPrint(t, n, TeX_print, diff);\
TeXPrint(t, indif, TeX_print, enddiff);\
}
#include "func.h"
#undef DIFF_
}
return indif;
}
void NodeDelete(Node * n)
{
if(!n) return;
NodeDelete(n->left);
NodeDelete(n->right);
free(n->word);
free(n);
}
void ShortAdd(tree * t, Node * n)
{
if (!n || n->type != op_t) return;
if(n->type == op_t && n->word[0] == '+' && strcmp(n->left->word, "0") == 0)
{
NodeDelete(n->left);
if(n->parent->left == n)
{
n->parent->left = TreeCopy(t, n->parent, n->right, 'L');
n = n->parent->left;
}
else
{
n->parent->right = TreeCopy(t, n->parent, n->right, 'R');
n = n->parent->right;
}
}
if(n->type == op_t && n->word[0] == '+' && strcmp(n->right->word, "0") == 0)
{
NodeDelete(n->right);
if(n->parent->left == n)
{
n->parent->left = TreeCopy(t, n->parent, n->left, 'L');
n = n->parent->left;
}
else
{
n->parent->right = TreeCopy(t, n->parent, n->left, 'R');
n = n->parent->right;
}
}
if(n->left != NULL) ShortAdd(t, n->left);
if(n->right != NULL) ShortAdd(t, n->right);
}
void ShortMul(tree * t, Node * n)
{
if (!n || n->type != op_t) return;
if(n->type == op_t && n->word[0] == '*' && strcmp(n->left->word, "0") == 0)
{
n->word = strdup(n->left->word);
n->type = value_t;
NodeDelete(n->left);
NodeDelete(n->right);
n->left = NULL;
n->right = NULL;
}
if(n->type == op_t && n->word[0] == '*' && strcmp(n->right->word, "0") == 0)
{
n->word = strdup(n->right->word);
n->type = value_t;
NodeDelete(n->left);
NodeDelete(n->right);
n->left = NULL;
n->right = NULL;
}
if(n->type == op_t && n->word[0] == '*' && strcmp(n->right->word, "1") == 0)
{
NodeDelete(n->right);
if(n->parent->left == n)
{
n->parent->left = TreeCopy(t, n->parent, n->left, 'L');
n = n->parent->left;
}
else
{
n->parent->right = TreeCopy(t, n->parent, n->left, 'R');
n = n->parent->right;
}
}
if(n->type == op_t && n->word[0] == '*' && strcmp(n->left->word, "1") == 0)
{
NodeDelete(n->left);
if(n->parent->left == n)
{
n->parent->left = TreeCopy(t, n->parent, n->right, 'L');
n = n->parent->left;
}
else
{
n->parent->right = TreeCopy(t, n->parent, n->right, 'R');
n = n->parent->right;
}
}
if(n->left != NULL) ShortMul(t, n->left);
if(n->right != NULL) ShortMul(t, n->right);
}
void ShortTree(tree * t)
{
assert(t != NULL);
Node * n = t->root;
ShortAdd(t, n);
// ShortDiv(t, n);
// ShortSub(t, n);
ShortMul(t, n);
ShortAdd(t, n);
}
#endif
|
Markdown | UTF-8 | 2,515 | 2.984375 | 3 | [] | no_license | ---
title: "Please, allow me to rant a moment"
author: "Glen Campbell"
date: "2014-05-28T17:00:00-07:00"
category: essays
tags: [code, jekyll, assumptions]
comments: true
---
We're using [jekyll](http://jekyllrb.com) on some projects at work, so I thought that I would try it out on my laptop. I found the Jekyll [Quick-start guide](http://jekyllrb.com/docs/quickstart/), and it seems pretty straightforward:
<img src="http://cdn.broadpool.com/Screen-Shot-2014-05-28-at-9.18.08-AM.png" alt="Jekyll quick start" width="680" height="289" class="center">
The problem, of course, is that it doesn't work:
<img src="http://cdn.broadpool.com/Screen-Shot-2014-05-28-at-9.20.55-AM.png" alt="fail" width="563" height="76" class="center">
<br style="clear:both;">
Apparently, Jekyll wants you to install this as root. Or, perhaps, the writer is running on a different system that permits regular users to install new software without privileges. Or something else: who knows? The fact of the matter is, these simple "quick start" instructions are a complete and utter failure. At this point, I have two options:
1. I can walk away, knowing that if I try to fix this, I'm going to dive into a multi-hour, multi-day fiasco of repetitive trial-and-error.
2. I can try to fix it and hope for the best. And probably dive into a multi-hour, multi-day fiasco of repetitive trial-and-error.
You who develop software: is this what you want?
I use this as a simple, most recent example, but it happens all the time. People who write Java code assume that every single human being on the face of the earth has a Java development environment set up exactly like theirs. Folks who code in Python assume that you have the exact same Python version and installed libraries as they do.
Here's a hint: before you release any documentation, ever, spin up a new, clean standard server using a common operating system like Ubuntu or Microsoft Windows. Run your code examples there. If they don't work for you then, they won't work for anyone else using it.
Moreover, if they *do* actually work, they *still* probably won't work for a bunch of users.
Document your dependencies: if the writer of Jekyll's quick start guide had added a footnote with his or her assumptions about operating system, environment, and dependencies, then I would at least have had some idea that there might be problems.
An old rule of thumb is "Under-promise and over-deliver." Documentation like this takes the exact opposite approach, and it pisses users off.
|
Java | UTF-8 | 754 | 1.960938 | 2 | [] | no_license | package com.ctl.security.ips.maestro.jms;
import com.ctl.security.ips.common.jms.bean.EventBean;
import com.ctl.security.ips.maestro.service.EventNotifyService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Mockito.verify;
@RunWith(MockitoJUnitRunner.class)
public class EventListenerTest {
@InjectMocks
private EventListener classUnderTest;
@Mock
private EventNotifyService eventNotifyService;
@Test
public void testNotify() throws Exception {
EventBean eventBean = null;
classUnderTest.notify(eventBean);
verify(eventNotifyService).notify(eventBean);
}
} |
SQL | UTF-8 | 560 | 2.78125 | 3 | [] | no_license | delete from user_has_interest;
delete from participants;
delete from messages;
delete from chat;
delete from user_wishes;
delete from tbl_friends;
delete from user_info;
delete from users;
insert into users (id, confirmed, email, password, username) values
(1, true, 'a', 'a', 'a'),
(2, true, 'b', 'b', 'b');
insert into user_info (id, first_name, last_name, user_id) values
(1, 'A', 'A', 1),
(2, 'B', 'B', 2);
insert into tbl_friends (friend_id, user_id) values
(1, 2),
(2, 1);
insert into user_has_interest (user_id, interest_id) values
(2, 11),
(1, 7);
|
Markdown | UTF-8 | 8,363 | 2.65625 | 3 | [] | no_license | # `@makkii/app-eth`
Ethereum application client.
This library uses some third-party service:
- Web3 JsonRPC - you can pass in jsonrpc in [EthApiClient](#ethapiclient) Constructor
- Explorer Api - To get transaction history, token history, we have two solutions:
- `http://api.ethplorer.io`
- `http://api.etherscan.io/api`
- Transaction Explorer - To show transaction detail page:
- `https://www.etherchain.org/tx/<txHash>`
- `https://api.etherscan.io/tx/<txHash>`
- Remote Api - we setup our own server to provide token list and icons.
## Installation
```bash
$ npm install @makkii/app-eth
```
## Usage
```javascript
import { EthApiClient, EthKeystoreClient, EthLocalSigner } from '@makkii/app-eth';
const api_client = new EthApiClient({
network: 'mainnet',
jsonrpc: '***'
});
api_client.getBalance('0x...')
.then(console.log)
.catch(error=>console.log(error));
const keystore_client = new EthKeystoreClient();
api_client.buildTransaction(
'0x...', // from address
'0x...', // to address
0, // amount
{
gasPrice: 10,
gasLimit: 21000,
isTokenTransfer: false
}
).then(function(unsignedTx) {
keystore_client.signTransaction(unsignedTx, new EthLocalSigner(), {
private_key: '***'
}).then(function(signedTx) {
console.log(signedTx);
});
});
```
## API
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->
#### Table of Contents
- [EthLocalSinger](#ethlocalsinger)
- [signTransaction](#signtransaction)
- [Parameters](#parameters)
- [IEthConfig](#iethconfig)
- [network](#network)
- [jsonrpc](#jsonrpc)
- [explorer_api](#explorer_api)
- [explorer](#explorer)
- [remote_api](#remote_api)
- [EthKeystoreClient](#ethkeystoreclient)
- [validatePrivateKey](#validateprivatekey)
- [Parameters](#parameters-1)
- [getAccountFromMnemonic](#getaccountfrommnemonic)
- [Parameters](#parameters-2)
- [EthUnsignedTx](#ethunsignedtx)
- [EthPendingTx](#ethpendingtx)
- [EthApiClient](#ethapiclient)
- [Parameters](#parameters-3)
- [getNetwork](#getnetwork)
- [getBlockByNumber](#getblockbynumber)
- [Parameters](#parameters-4)
- [getBlockNumber](#getblocknumber)
- [getTransactionStatus](#gettransactionstatus)
- [Parameters](#parameters-5)
- [getTransactionsByAddress](#gettransactionsbyaddress)
- [Parameters](#parameters-6)
- [sendTransaction](#sendtransaction)
- [Parameters](#parameters-7)
- [getTopTokens](#gettoptokens)
- [Parameters](#parameters-8)
### EthLocalSinger
Ethereum's signer using private key, implements IkeystoreSigner.
#### signTransaction
Sign transaction
##### Parameters
- `transaction` **[EthUnsignedTx](#ethunsignedtx)**
- `params` **{private_key: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)}** parameters object, example: { private_key: '' }}
- `tx` EthUnsignedTx transaction object to sign.
Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)>** transaction hash string
### IEthConfig
Ethereum configuration interface
#### network
Network name
Type: (`"mainnet"` \| `"ropsten"`)
#### jsonrpc
JsonRPC endpoint
Type: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)
#### explorer_api
api endpoint that used to query transaction information
Type: {provider: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String), url: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String), key: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)}
#### explorer
Transaction explorer page
Type: {provider: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String), url: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)}
#### remote_api
app server endpoint that provides token, icons, etc.
Type: [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)
### EthKeystoreClient
Ethereum keystore client that implements IsingleKeystoreClient
#### validatePrivateKey
throws not implemented error
##### Parameters
- `privateKey` **([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [Buffer](https://nodejs.org/api/buffer.html))**
#### getAccountFromMnemonic
Get account from mnemonic
##### Parameters
- `address_index` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** index in hd wallet
- `mnemonic` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** mnemonic phrase
Returns **any** account object: { private_key: '', public_key: '', address: '', index: '' }
### EthUnsignedTx
Ethereum unsigned transaction
- to: string;
- from: string;
- nonce: string;
- value: BigNumber;
- gasPrice: number;
- gasLimit: number;
- data?: any;
- network: string;
### EthPendingTx
Ethereum pending transaction
- hash: string;
- status: "PENDING";
- to: string;
- from: string;
- value: BigNumber;
- tknTo?: string;
- tknValue: BigNumber;
- gasPrice: number;
- gasLimit: number;
### EthApiClient
Ethereum api client that implements IsingleApiFullClient
#### Parameters
- `config` **[IEthConfig](#iethconfig)**
#### getNetwork
Get network name: mainnet, amity.
#### getBlockByNumber
Get block by number, block information doesn't contains transaction details
##### Parameters
- `blockNumber` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** block number's hex string
Returns **any** eth_getBlockNumber response's result
#### getBlockNumber
Get latest block number
Returns **any** eth_getBlockNumber response's result
#### getTransactionStatus
Get transaction status.
##### Parameters
- `hash` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** transaction hash
Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<any>** if eth_getTransactionReceipt is null, returns null;
else return object { status: true/false, blockNumber: intger, gasUsed: integer }
#### getTransactionsByAddress
Get transactions by the given address
##### Parameters
- `address` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** account address
- `page` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** page number
- `size` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** page size
- `timestamp` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?** earlier than this timestamp
Returns **any** array of object structure which contains:<br>- **hash**: string, with prefix 0x
- **timestamp**: milli-seconds from 1970
- **from**: sender
- **to**: receiver
- **value**: transfer amount
- **status**: 'CONFIRMED' or 'FAILED'
- **blockNumber**: hex string
- **fee**: integer
#### sendTransaction
Send transaction
##### Parameters
- `unsignedTx` **[EthUnsignedTx](#ethunsignedtx)** unsigned transaction build by buildTransaction
- `signer` **T** localSigner or hardware
- `signerParams` **any** localSigner: {private_key} hardware:{derivationIndex}
Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[EthPendingTx](#ethpendingtx)>**
#### getTopTokens
Get top tokens
##### Parameters
- `topN` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?** default 20
Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<Token>>**
|
JavaScript | UTF-8 | 1,477 | 4.09375 | 4 | [] | no_license | // 2019/6/28
// part1
console.log(a);
var a = 1;
console.log(a);
// 上边代码等价如下 解析器眼中的代码
var a;
console.log(a);//undefined
a = 1;
console.log(a);//1
// 思考如下代码输出什么 值类型
console.log(a,b);//undefined undefined
var b = 23;
console.log(a,b);//undefined 23
var a = b;
console.log(a,b);//23 23
// 思考如下代码输出什么 引用类型
console.log(obj1,obj2);//undefined undefined
var obj1 = {x:23};
console.log(obj1,obj2);//{x:23} undefined
var obj2 = obj1;
console.log(obj1,obj2);//{x:23} {x:23}
obj2.x =25;
console.log(obj1,obj2);// {x:25} {x:25}
// part2
foo();
function foo(){
console.log("f_1");
}
function foo(){
console.log("f_2");
}
// 上面代码等价如下,解析器眼中的代码
function foo(){
console.log("f_1");
}
function foo(){
console.log("f_2");
}
foo();//f_2
// part3
foo();
var foo = function(){
console.log("foo");
};
// 思考以下代码是否会报错
console.log(foo);//输出什么 undefined
var foo = function(){
console.log("foo");
};
foo();//是否会报错 不会报错,输出foo
// 上述等价形式如下
var foo;
console.log(foo);
foo = function(){
console.log("foo");
};
foo();
// part4
AA();
function AA(){
console.log("AA_1");
}
var AA = function AA(){
console.log("AA_2");
};
AA();
//上边代码等价如下
function AA(){
console.log("AA_1");
}
var AA;
AA();//AA_1
AA = function AA(){
console.log("AA_2");
};
AA();//AA_2 |
Java | UTF-8 | 1,244 | 2.75 | 3 | [
"MIT"
] | permissive | package com.oaksoft.utils.utils.xmljson;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
class LocalDateDeserializer extends JsonDeserializer<LocalDate> {
@Override
public LocalDate deserialize(JsonParser jp, DeserializationContext context) throws IOException {
LocalDate date = null;
switch (jp.getCurrentToken()) {
case VALUE_STRING:
if (jp.getCurrentToken() == JsonToken.VALUE_STRING) {
String str = jp.getText().trim();
if (str.length() != 0) {
date = LocalDate.parse(str, DateTimeFormatter.ISO_DATE);
}
}
break;
}
if (date == null) {
context.handleUnexpectedToken(LocalDate.class, jp);
return null; // shouldn't get here the previous call is supposed to throw an exception
} else {
return date;
}
}
}
|
C++ | UTF-8 | 758 | 2.890625 | 3 | [] | no_license | #pragma once
#include "UE4DevelopmentLibrary/Stream.hpp"
struct FVector : public SerializeInterface
{
public:
FVector(const FVector& rhs) {
FVector::operator=(rhs);
}
void operator=(const FVector& rhs) {
x = rhs.x;
y = rhs.y;
z = rhs.z;
}
FVector(float _x, float _y, float _z)
: x(_x), y(_y), z(_z)
{
}
FVector() : FVector(0.0, 0.0, 0.0)
{
}
virtual void Write(OutputStream& output) const {
output << x;
output << y;
output << z;
}
virtual void Read(InputStream& input) {
input >> x;
input >> y;
input >> z;
}
public:
float x;
float y;
float z;
};
using Location = FVector;
using Rotation = FVector; |
Python | UTF-8 | 327 | 3.953125 | 4 | [] | no_license | print("enter the no. of elements:")
n = int(input())
print("enter the elements one after other separated by space:")
a = list(map(int,input().split()))
for i in range(1,n):
key = a[i]
j = i-1
while j>=0 and a[j]>key:
a[j+1] = a[j]
j = j-1
a[j+1] = key
print("Sorted Array is",a)
|
Java | UTF-8 | 572 | 2.0625 | 2 | [] | no_license | package com.company.common.model.factory;
import com.company.common.model.browser.AbstractWebBrowserInterface;
public interface AbstractWebBrowserFactoryInterface {
public AbstractWebBrowserInterface createIeWebBrowser() throws Exception;
public AbstractWebBrowserInterface createFirefoxWebBrowser() throws Exception;
public AbstractWebBrowserInterface createChromeWebBrowser() throws Exception;
public AbstractWebBrowserInterface createHtmlUnitWebBrowser() throws Exception;
public AbstractWebBrowserInterface createMockWebBrowser() throws Exception;
}
|
Markdown | UTF-8 | 3,312 | 2.546875 | 3 | [
"MIT"
] | permissive | ---
layout: post
title: "Ruby Meetup December 20, 2015"
date: 2015-12-23 18:37
comments: true
categories: [activities, meetup]
author: josisusan
---
After months of hurdles and fuel crisis, we’re finally continuing our monthly Ruby Meetup. Around 30 ruby enthusiasts showed up for the december meetup held on 20th December 2015. I was very glad and a little nervous to host the event for the very first time. I would like to thank [Saroj](https://twitter.com/zoraslapen){:.rnw-link} dai for providing me the opportunity to host the event.
{% include image.html
img="https://secure.meetupstatic.com/photos/event/8/8/9/7/600_445174967.jpeg"
title="RubyNepal Meetup Banner"
class="center-image"
caption="RubyNepal Meetup Banner"
%}
First speaker was [Ludwine Probst](https://twitter.com/nivdul){:.rnw-link}, data engineer from France. Despite having Mathematics as her academic background, she talked about how she is enjoying her career as a software developer. She also shared her experience as a developer in France. She explained her journey from France to Asian countries to know more about the woman involvement on IT world. Rather than a talk, it was an interactive session with the meetup participants.
{% include image.html
img="https://secure.meetupstatic.com/photos/event/d/9/9/e/600_445315710.jpeg"
title="Ludwine Probst interacting with Audience"
class="center-image"
caption="Ludwine Probst interacting with Audience"
%}
{% include image.html
img="https://secure.meetupstatic.com/photos/event/d/9/d/f/600_445315775.jpeg"
title="Ganesh Kunwar talking about TDD in Rails"
class="center-image"
caption="Ganesh Kunwar talking about TDD in Rails"
%}
Second speaker was [Ganesh Kunwar](https://twitter.com/gkunwar1){:.rnw-link}, Sr. Ruby Developer from Jyaasa on the topic "Test Driven Development(TDD Basics)". He briefly explained on how TDD can be practiced easily with gems like RSpec, Test/Unit, Capybara with some code samples. He shared his experience on TDD workflow on codebase. He shed some light on TDD (Test Driven Development) and DDT (Development Driven Test) approach which not only clarified the value of TDD in QC (Quality Control) but also significantly improving the overall architecture of the system design itself. You can download the slides [here](https://files.meetup.com/18762323/Test%20Driven%20Development%20%28TDD%29%20-%20Ruby%20Nepal%20Meetup%20-%20Dec%2020%2C2015.pdf){:.rnw-link}
A big thank you to [CloudFactory](https://www.cloudfactory.com/home){:.rnw-link} for sponsoring December RubyNepal Meetup and [Innovation Hub Kathmandu](https://www.facebook.com/IHKathmandu){:.rnw-link} for the awesome venue.
We are using github issue to manage our meetup presentation. You can open [issue](https://github.com/RubyNepal/rorh/issues){:.rnw-link} if you want to share your experience or present on topic that intrests you.
See you at next [Ruby and Rails meetup](https://www.meetup.com/Nepal-Ruby-Users-Group/){:.rnw-link}
{% include image.html
img="https://secure.meetupstatic.com/photos/event/d/9/8/4/highres_445315684.jpeg"
title="Audience at RubyNepal Meetup"
class="center-image"
caption="Audience at RubyNepal Meetup"
%}
> Susan Joshi - [josisusan](https://twitter.com/josisusan){:.rnw-link}
> Co-organiser, Ruby and Rails Meetup
|
Java | UTF-8 | 400 | 2.9375 | 3 | [] | no_license | package SelfStudy;
class Data1{
int value;
}
class Data2{
int value;
Data2(int x) { // 매개변수가 있는 생성자
value = x;
}
}
public class ch6_23_ConstructorTest {
public static void main(String[] args) {
Data1 d1 = new Data1();
// Data2 d2 = new Data2(); // complie error 발생
// Data2 d2 = new Data2(x); 와 같이 정의된 생성자를 같이 호출해줘야 함
}
}
|
TypeScript | UTF-8 | 2,702 | 3.1875 | 3 | [
"MIT"
] | permissive | const STATE_PLAINTEXT = Symbol('plaintext');
const STATE_HTML = Symbol('html');
const STATE_COMMENT = Symbol('comment');
// eslint-disable-next-line @typescript-eslint/ban-types
function striptags(html: string | String = '') {
// if not string, then safely return an empty string
if (typeof html !== 'string' && !(html instanceof String)) {
return '';
}
let state = STATE_PLAINTEXT;
let tag_buffer = '';
let depth = 0;
let in_quote_char = '';
let output = '';
const { length } = html;
for (let idx = 0; idx < length; idx++) {
const char = html[idx];
if (state === STATE_PLAINTEXT) {
switch (char) {
case '<':
state = STATE_HTML;
tag_buffer = tag_buffer + char;
break;
default:
output += char;
break;
}
} else if (state === STATE_HTML) {
switch (char) {
case '<':
// ignore '<' if inside a quote
if (in_quote_char) break;
// we're seeing a nested '<'
depth++;
break;
case '>':
// ignore '>' if inside a quote
if (in_quote_char) {
break;
}
// something like this is happening: '<<>>'
if (depth) {
depth--;
break;
}
// this is closing the tag in tag_buffer
in_quote_char = '';
state = STATE_PLAINTEXT;
// tag_buffer += '>';
tag_buffer = '';
break;
case '"':
case '\'':
// catch both single and double quotes
if (char === in_quote_char) {
in_quote_char = '';
} else {
in_quote_char = in_quote_char || char;
}
tag_buffer = tag_buffer + char;
break;
case '-':
if (tag_buffer === '<!-') {
state = STATE_COMMENT;
}
tag_buffer = tag_buffer + char;
break;
case ' ':
case '\n':
if (tag_buffer === '<') {
state = STATE_PLAINTEXT;
output += '< ';
tag_buffer = '';
break;
}
tag_buffer = tag_buffer + char;
break;
default:
tag_buffer = tag_buffer + char;
break;
}
} else if (state === STATE_COMMENT) {
switch (char) {
case '>':
if (tag_buffer.slice(-2) === '--') {
// close the comment
state = STATE_PLAINTEXT;
}
tag_buffer = '';
break;
default:
tag_buffer = tag_buffer + char;
break;
}
}
}
return output;
}
export = striptags;
|
Java | UTF-8 | 595 | 1.882813 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package mx.com.pixup.portal.dao.interfaces;
import java.util.List;
import mx.com.pixup.portal.model.Municipio;
/**
*
* @author mflores
*/
public interface MunicipioDao {
Municipio insertMunicipio(Municipio municipio);
List<Municipio> findAllMunicipios();
Municipio findById(Integer id);
Municipio updateMunicipio(Municipio municipio);
void deleteMunicipio(Municipio municipio);
}
|
C++ | UTF-8 | 4,795 | 2.875 | 3 | [] | no_license | #include "cComMoveTo.h"
#include <iostream>
#include <GLFW/glfw3.h>
void cComMoveTo::setMyID( int myID )
{
this->m_uniqueID = myID;
return;
}
cComMoveTo::cComMoveTo()
{
this->initPosition = glm::vec3( 0.0f, 0.0f, 0.0f );
this->finalPosition = glm::vec3( 0.0f, 0.0f, 0.0f );
this->direction = glm::vec3( 0.0f, 0.0f, 0.0f );
this->distanceToTarget = 0.0f;
this->velocity = 0.0f;
this->initialTime = 0;
this->elapsedTime = 0;
this->smoothRange1 = 0.1f;
this->smoothRange2 = 0.99f;
this->hasStarted = false;
this->isCommandDone = false;
return;
}
cComMoveTo::~cComMoveTo()
{
return;
}
void cComMoveTo::init( glm::vec3 destination, float time, glm::vec3 theSmoothStepParam )
{
this->finalPosition = destination;
this->duration = time;
// This way we make sure they are not 0, and mantain their init values
if( theSmoothStepParam.x != 0 ) this->smoothRange1 = theSmoothStepParam.x;
if( theSmoothStepParam.y != 0 ) this->smoothRange2 = theSmoothStepParam.y;
//theSmoothStepParam.z? //Not used right now
return;
}
void cComMoveTo::update( double deltaTime )
{
if( this->hasStarted == false )
{
//std::cout << "ID: " << this->theGO->getID()
// << " - MoveTo: " << this->finalPosition.x << ", "
// << this->finalPosition.y << ", "
// << this->finalPosition.z
// << std::endl;
if( this->targetGO != nullptr ) // Get the position from the target GO
this->finalPosition = this->targetGO->position;
this->initialTime = glfwGetTime();
this->hasStarted = true;
this->initPosition = this->theGO->position;
this->direction = glm::normalize( finalPosition - initPosition );
this->distanceToTarget = glm::distance( finalPosition, initPosition );
// This is the average velocity it would take to reach the destination
this->velocity = (float) this->distanceToTarget / this->duration;
}
// Calculate remaining distance
float remainingDistance = glm::distance( this->finalPosition, this->theGO->position );
this->elapsedTime = glfwGetTime() - this->initialTime;
//float range1 = this->smoothRange1 * this->distanceToTarget;
//float range2 = this->smoothRange2 * this->distanceToTarget;
float range1 = this->smoothRange1 * this->duration;
float range2 = this->smoothRange2 * this->duration;
float traveledDistance = glm::distance( this->initPosition, this->theGO->position );
// Using the smooth step 2x to calculate aceleration and deceleration
//float factor = glm::smoothstep( -0.1f, range1, traveledDistance ) * ( 1 - glm::smoothstep( range2, this->distanceToTarget + 0.1f , traveledDistance ) );
float factor = glm::smoothstep( -0.1f, range1, ( float )this->elapsedTime ) * ( 1 - glm::smoothstep( range2, this->duration, (float)this->elapsedTime ) );
factor = factor * this->velocity;
//this->direction = glm::normalize( this->finalPosition - this->theGO->position );
this->theGO->vel = this->direction * factor;
// Calculate delta position according to the velocity based on time elapsed
glm::vec3 deltaPosition = ( float )deltaTime * this->theGO->vel;
// Where the object will be
glm::vec3 nextPosition = this->theGO->position += deltaPosition;
float nextDistance = glm::distance( finalPosition, nextPosition );
//if( nextDirection != this->direction )
if( nextDistance > remainingDistance )
{ // It means it has inverted the direction, or that it has passed the final position
this->theGO->position = this->finalPosition;
// Set the Velocity to 0
this->theGO->vel = glm::vec3( 0.0f, 0.0f, 0.0f );
}
else
{
this->theGO->position += deltaPosition;
}
//std::cout
// << "ID: " << this->theGO->getID()
// << " | Max.vel: " << this->velocity
// << " | Elapsed Time: " << this->elapsedTime
// << " | Vel.: " << this->theGO->vel.x
// << ", " << this->theGO->vel.y << ", " << this->theGO->vel.z
// << " - Traveled distancet: " << traveledDistance
// //<< " | Distance: " << remainingDistance
// << std::endl;
return;
}
bool cComMoveTo::isDone()
{
if( this->isCommandDone ) return true;
// If the GO is on destination, clear the velocity
if( this->theGO->position == this->finalPosition ||
this->elapsedTime >= this->duration )
{
this->isCommandDone = true;
// Set the Velocity
//std::cout << "ID: " << this->theGO->getID()
// << " final position: " << this->theGO->position.x << ", "
// << this->theGO->position.y << ", "
// << this->theGO->position.z
// << std::endl;
this->theGO->vel = glm::vec3( 0.0f, 0.0f, 0.0f );
return true;
}
else
return false;
}
void cComMoveTo::setMyGO( cGameObject* myGO )
{
this->theGO = myGO;
return;
}
cGameObject* cComMoveTo::getMyGO()
{
return this->theGO;
}
void cComMoveTo::setTargetGO( cGameObject* target )
{
this->targetGO = target;
return;
}
cGameObject* cComMoveTo::getTargetGO()
{
return this->targetGO;
}
|
PHP | UTF-8 | 3,974 | 2.75 | 3 | [
"BSD-3-Clause",
"MIT"
] | permissive | <?php
/**
* Translation file for Portuguese language.
*
* @author Felippe Roberto Bayestorff Duarte <felippeduarte@gmail.com>
* @link https://github.com/rlanvin/php-rrule
*/
return array(
'yearly' => array(
'1' => 'anual',
'else' => 'cada %{interval} anos' // cada 8 anos
),
'monthly' => array(
'1' => 'mensal',
'else' => 'cada %{interval} meses' //cada 8 meses
),
'weekly' => array(
'1' => 'semanal',
'2' => 'qualquer outra semana',
'else' => 'cada %{interval} semanas' // cada 8 semanas
),
'daily' => array(
'1' => 'diário',
'2' => 'qualquer outro dia',
'else' => 'cada %{interval} dias' // cada 8 dias
),
'hourly' => array(
'1' => 'cada hora',
'else' => 'cada %{interval} horas'// cada 8 horas
),
'minutely' => array(
'1' => 'cada minuto',
'else' => 'cada %{interval} minutos'// cada 8 minutos
),
'secondly' => array(
'1' => 'cada segundo',
'else' => 'cada %{interval} segundos'// cada 8 segundos
),
'dtstart' => ', começando de %{date}',
'timeofday' => ' às %{date}',
'startingtimeofday' => ' começando de %{date}',
'infinite' => ', para sempre',
'until' => ', até %{date}',
'count' => array(
'1' => ', uma vez',
'else' => ', %{count} vezes'
),
'and' => 'e ',
'x_of_the_y' => array(
'yearly' => '%{x} do ano', // e.g. the first Monday of the year, or the first day of the year
'monthly' => '%{x} do mês',
),
'bymonth' => ' em %{months}',
'months' => array(
1 => 'Janeiro',
2 => 'Fevereiro',
3 => 'Março',
4 => 'Abril',
5 => 'Maio',
6 => 'Junho',
7 => 'Julho',
8 => 'Agosto',
9 => 'Setembro',
10 => 'Outubro',
11 => 'Novembro',
12 => 'Dezembro',
),
'byweekday' => ' em %{weekdays}',
'weekdays' => array(
1 => 'Segunda-feira',
2 => 'Terça-feira',
3 => 'Quarta-feira',
4 => 'Quinta-feira',
5 => 'Sexta-feira',
6 => 'Sábado',
7 => 'Domingo',
),
'nth_weekday' => array(
'1' => 'o(a) primero(a) %{weekday}', // e.g. the first Monday
'2' => 'o(a) segundo(a) %{weekday}',
'3' => 'o(a) terceiro(a) %{weekday}',
'else' => 'o %{n}º %{weekday}'
),
'-nth_weekday' => array(
'-1' => 'o(a) último(a) %{weekday}', // e.g. the last Monday
'-2' => 'o(a) penúltimo(a) %{weekday}',
'-3' => 'o(a) antepeúltimo(a) %{weekday}',
'else' => 'o %{n}º até o último %{weekday}'
),
'byweekno' => array(
'1' => ' na semana %{weeks}',
'else' => ' nas semanas # %{weeks}'
),
'nth_weekno' => '%{n}',
'bymonthday' => ' no %{monthdays}',
'nth_monthday' => array(
'1' => 'o 1º',
'2' => 'o 2º',
'3' => 'o 3º',
'21' => 'o 21º',
'22' => 'o 22º',
'23' => 'o 23º',
'31' => 'o 31º',
'else' => 'o %{n}º'
),
'-nth_monthday' => array(
'-1' => 'o último dia',
'-2' => 'o penúltimo dia',
'-3' => 'o antepenúltimo dia',
'-21' => 'o 21º até o último dia',
'-22' => 'o 22º até o último dia',
'-23' => 'o 23º até o último dia',
'-31' => 'o 31º até o último dia',
'else' => 'o %{n}º até o último dia'
),
'byyearday' => array(
'1' => ' no %{yeardays} dia',
'else' => ' nos %{yeardays} dias'
),
'nth_yearday' => array(
'1' => 'o primero',
'2' => 'o segundo',
'3' => 'o tercero',
'else' => 'o %{n}º'
),
'-nth_yearday' => array(
'-1' => 'o último',
'-2' => 'o penúltimo',
'-3' => 'o antepenúltimo',
'else' => 'o %{n}º até o último'
),
'byhour' => array(
'1' => ' a %{hours}',
'else' => ' a %{hours}'
),
'nth_hour' => '%{n}h',
'byminute' => array(
'1' => ' ao minuto %{minutes}',
'else' => ' aos minutos %{minutes}'
),
'nth_minute' => '%{n}',
'bysecond' => array(
'1' => ' ao segundo %{seconds}',
'else' => ' aos segundos %{seconds}'
),
'nth_second' => '%{n}',
'bysetpos' => ', mas somente %{setpos} ocorrência deste conjunto',
'nth_setpos' => array(
'1' => 'o primero',
'2' => 'o segundo',
'3' => 'o terceiro',
'else' => 'o %{n}º'
),
'-nth_setpos' => array(
'-1' => 'o último',
'-2' => 'o penúltimo',
'-3' => 'o antepenúltimo',
'else' => 'o %{n}º até o último'
)
);
|
C# | UTF-8 | 1,221 | 2.859375 | 3 | [] | no_license | using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Data.SqlClient;
namespace BlazorDapperCRUD.Data
{
public class VideoService : IVideoService
{
private readonly SqlConnectionConfiguration _configuration;
public VideoService(SqlConnectionConfiguration configuration)
{
_configuration = configuration;
}
public async Task<bool> VideoInsert(Video video)
{
using (var conn = new SqlConnection(_configuration.Value))
{
var parameters = new DynamicParameters();
parameters.Add("Title",video.Title,DbType.String);
parameters.Add("DatePublished", video.DatePublished, DbType.Date);
parameters.Add("IsActive", video.IsActive, DbType.Boolean);
const string query = @"INSERT INTO Video (Title, DatePublished, IsActive) VALUES (@Title, @DatePublished, @IsActive)";
await conn.ExecuteAsync(query, new {video.Title, video.DatePublished, video.IsActive}, commandType: CommandType.Text);
}
return true;
}
}
}
|
JavaScript | UTF-8 | 781 | 2.796875 | 3 | [] | no_license | /**
* Created by NiiTTrox on 26.03.2017.
*/
var data = [
{"title": "PushUps", "dur": 45},
{"title": "Kniebeuge", "dur": 60},
{"title": "Baumstamm rechts", "dur": 30},
{"title": "Baumstamm links", "dur": 30},
{"title": "SitUps", "dur": 45}
];
window.addEventListener("load", function () {
var feedElem = document.getElementById("Feed");
for (var i = 0; i < data.length; i++) {
feedElem.innerHTML += "Titel: " + data[i].title + " - " + data[i].dur + "s<br/>";
}
var count = 0;
feedElem.addEventListener("click", function (event) {
count++;
console.log(count + "x geklickt.");
if (count == 10) {
alert("Lass das :)");
}
event.preventDefault();
});
});
|
Markdown | UTF-8 | 574 | 2.984375 | 3 | [] | no_license | Part 2-
Pass 17 through the function, hard code it in main.
Part 3-
I would have tested it by print statements since it does not
return anything.
Part 4-
From part 2 and part 3, part 2 is a void function, meaning it
has no return type. In part 3, we are returning the data in a
string array. We did that because we can test the data with
the java test class. Part 3 is being stored in a Arrary while
part is being stored in a list. You would use a Array
when you know exactly how many inputs of n. you would use an
List when you do not know how many n's there are. |
Markdown | UTF-8 | 900 | 3.375 | 3 | [] | no_license | ## colgroup 中 col 标签指定 width 不生效
有时候,使用 table 开发页面的时候,会存在表格合并和拆分的需求。
列合并在 td 上使用 colspan,行合并在 td 上使用 rowspan 即可。那如何去固定每列的宽度呢?
可以通过使用 colgroup 和 col 标签,给 col 标签配置 width 属性,就可以实现。然而,width 属性在 html5 中已经被废弃了,那怎么使用才能固定列宽呢?
可以给 col 标签加类名,类中指定 width,就能完美实现了。
注意:表格列的宽度会根据内容的宽度自动调整,所以即使你指定了 td 的宽度,内容过宽时,整个表格的布局还是会发生改变,需要给 table 标签的样式属性添加 `table-layout: fixed`
### 参考链接
1. [colgroup 中 col 标签指定 width 不生效的问题](https://www.cnblogs.com/roooobin/p/15689159.html)
|
JavaScript | UTF-8 | 1,614 | 3.0625 | 3 | [] | no_license | // in this file create an express application - use the middle-ware built into express
// to serve up static files from the public directory (index.html and client.js - you
// can also serve up css files from the public directory this way if you want)
// you need to support a '/trucks' endpoint, and a dynamic route for '/trucks/:name'
'use strict';
var trucks = require('./trucks');
var express = require('express');
var app = express();
var serveStatic = express.static('public');
app.use(serveStatic);
// (/trucks) This route returns the list of all trucks in the module.
app.get('/trucks', function (request, response) {
var allTrucks = trucks.getTrucks();
response.send(allTrucks);
});
// (/trucks/:name) This route returns a single truck object that matches the name parameter passed in the route.
app.get('/trucks/:name', function (request, response) {
var truckParam = request.params.name;
var truckName = trucks.getTruck(truckParam);
response.send(truckName);
});
// (/food-types) This route returns the list of all possible food types served by trucks in the module
app.get('/food-types', function (request, response) {
var allFoodTypes = trucks.getFoodTypes();
response.send(allFoodTypes);
});
// (/food-types/:type) This route returns the list of all trucks that serve the food type that matches (case insensitive) the type parameter passed in the route.
app.get('/food-types/:type', function (request, response) {
var foodParam = request.params.type;
var foodType = trucks.filterByFoodType(foodParam);
response.send(foodType);
});
app.listen(3000, function () {
});
|
C | UTF-8 | 303 | 3.359375 | 3 | [] | no_license | #include<stdio.h>
#include<string.h>
size_t strlenA(const char *str)
{
const char *newStr;
newStr=str;
size_t a=0;
while (*newStr!='\0')
{
newStr++;
a++;
}
return a;
}
void main()
{
const char *s1="Amit Kumar Upadhyay";
printf("Number of characters in string = %d",strlenA(s1));
} |
Python | UTF-8 | 1,749 | 3.03125 | 3 | [] | no_license | import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import praw
reddit = praw.Reddit(client_id='x_IAA3B1ypV01Q',
client_secret='vt_BW5GESY4n0yGCuUoaxkoKWug',
user_agent='champagnefruit'
)
nltk.download('vader_lexicon')
sid = SentimentIntensityAnalyzer()
def get_text_negative_proba(text):
return sid.polarity_scores(text)['neg']
def get_text_neutral_proba(text):
return sid.polarity_scores(text)['neu']
def get_text_positive_proba(text):
return sid.polarity_scores(text)['pos']
def get_submission_comments(url):
submission = reddit.submission(url=url)
submission.comments.replace_more()
return submission.comments
def process_comments(neg,pos,neu,comments):
for i in comments:
positive = get_text_positive_proba(i.body)
neutral = get_text_neutral_proba(i.body)
negative = get_text_negative_proba(i.body)
if (positive > neutral and positive > negative):
pos.append(i.body)
elif(neutral >positive and neutral > negative):
neu.append(i.body)
elif(negative >positive and negative > neutral):
neg.append(i.body)
process_comments(neg,pos,neu,i.replies)
def main():
comments = get_submission_comments('https://www.reddit.com/r/learnprogramming/comments/5w50g5/eli5_what_is_recursion/')
print(comments[0].body)
print(comments[0].replies[0].body)
neg = [] #et_text_negative_proba(comments[0].replies[0].body)
pos = [] #get_text_positive_proba(comments[0].replies[0].body)
neu = [] #get_text_neutral_proba(comments[0].replies[0].body)
process_comments(neg,pos,neu,comments)
print(neg)
print(pos)
print(neu)
main()
|
Python | UTF-8 | 2,497 | 3.125 | 3 | [] | no_license | """
This is a unittest test suite for the function files_finder in the module similar_files_finder.
"""
import unittest
import os
from supertool.similar_files_finder import files_finder
PATH = os.path.abspath(os.path.dirname(__file__))
class PositiveTests(unittest.TestCase):
"""
This test case contains the positive tests for the function files_finder.
"""
def test_two_files_in_the_same_directory(self):
"""
This tests checks if the function is working correctly for the directory containing two files.
"""
test_dir = os.path.join(PATH, 'TEST_FILES', 'test1')
os.makedirs(test_dir, exist_ok=True)
with open(os.path.join(test_dir, 'file1.txt'), 'w') as file:
print('abacaba', file=file)
with open(os.path.join(test_dir, 'file2.txt'), 'w') as file:
print('abacaba', file=file)
files = files_finder(test_dir)
self.assertEqual([file.name for file in files], ['file1.txt', 'file2.txt'])
def test_four_files_in_different_directories(self):
"""
This test checks if the function is working correctly for the directory with two files and a subdirectory with
another two files.
"""
test_dir = os.path.join(PATH, 'TEST_FILES', 'test3')
os.makedirs(test_dir, exist_ok=True)
with open(os.path.join(test_dir, 'file1.txt'), 'w') as file:
print('abacaba', file=file)
with open(os.path.join(test_dir, 'file2.py'), 'w') as file:
print('abacaba123', file=file)
test_sub_dir = os.path.join(test_dir, 'sub_dir')
os.makedirs(test_sub_dir, exist_ok=True)
with open(os.path.join(test_sub_dir, 'file3.txt'), 'w') as file:
print('abacaba', file=file)
with open(os.path.join(test_sub_dir, 'file4.md'), 'w') as file:
print('abacaba123', file=file)
files = files_finder(test_dir)
self.assertEqual([file.name for file in files], ['file1.txt', 'file2.py', 'file3.txt', 'file4.md'])
class NegativeTests(unittest.TestCase):
def test_not_existing_directory(self):
"""
This test checks if the function deals correctly with not existing directory given as an argument.
"""
with self.assertRaises(FileNotFoundError) as error:
files_finder('kjahdbfhbadsjhfbasdjhfb')
self.assertEqual(error.exception.args[0], 'such directory does not exist')
if __name__ == '__main__':
unittest.main() |
Java | UTF-8 | 1,930 | 2.234375 | 2 | [] | no_license | package josep.com.firebaseenintents;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class Atendre_client extends MenuMain {
private DatabaseReference actual_numero;
private Button b_nou;
private Button b_reiniciar;
private TextView text_num_acual_cua;
private int n;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_atendre_client);
FirebaseDatabase db=FirebaseDatabase.getInstance();
actual_numero =db.getReference("actual_numero");
text_num_acual_cua = (TextView) findViewById(R.id.text_NumFb);
b_nou= (Button) findViewById(R.id.b_agafarNumero);
//b_reiniciar= (Button) findViewById(R.id.b_reiniciar);
// b_nou.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// NouClient(view);
// }
// });
}
public void NouClient(View view) {
actual_numero.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String valor=dataSnapshot.getValue(String.class);
n=Integer.parseInt(valor);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
n++;
setN_actual_numero(n);
text_num_acual_cua.setText(""+getN_actual_numero());
actual_numero.setValue(""+getN_actual_numero());
}
}
|
Python | UTF-8 | 4,148 | 3.046875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/python
'''
Learning Machines
Taught by Patrick Hebron at NYU ITP
Multilayer Perceptron (MLP) implementation.
'''
import numpy as np
import Activation
from MnistReporter import *
class Mlp:
class Layer:
def __init__(self,input_size,output_size):
wlimit = np.sqrt( 6.0 / float( input_size + output_size ) )
self.weights = np.random.uniform( -wlimit, wlimit, ( input_size, output_size ) )
self.bias = np.zeros( output_size )
def __init__(self, name, layer_sizes, activation_fn_name):
self.name = name
# Create layers:
self.layers = []
for i in range( len( layer_sizes ) - 1 ):
self.layers.append( self.Layer( layer_sizes[ i ], layer_sizes[ i + 1 ] ) )
# Set activation function:
if activation_fn_name == 'tanh':
self.activation_fn = Activation.tanh
self.activation_dfn = Activation.dtanh
else:
self.activation_fn = Activation.sigmoid
self.activation_dfn = Activation.dsigmoid
def getErrorRate(self, labels, guesses):
'''returns mean square error'''
return np.mean( np.square( labels - guesses ) )
def predictSignal(self, input):
# Setup signals:
activations = [ input ]
outputs = [ input ]
# Feed forward through layers:
for i in range( 1, len( self.layers ) + 1 ):
# Compute activations:
curr_act = np.dot( outputs[ i - 1 ], self.layers[ i - 1 ].weights ) + self.layers[ i - 1 ].bias
# Append current signals:
activations.append( curr_act )
outputs.append( self.activation_fn( curr_act ) )
# Return signals:
return activations, outputs
def predict(self, input):
# Feed forward:
activations, outputs = self.predictSignal( input )
# Return final layer output:
return outputs[ -1 ]
def trainEpoch(self, training_samples, training_labels, learn_rate, batch_size):
error = 0.0
num_rows = training_samples.shape[ 0 ]
num_layers = len( self.layers )
# Iterate over each training batch:
for bstart in range( 0, num_rows, batch_size ):
# Compute batch stop index:
bstop = min( bstart + batch_size, num_rows )
# Compute batch size:
bsize = bstop - bstart
# Compute batch multiplier:
bmult = learn_rate * ( 1.0 / float( bsize ) )
# Slice data:
bsamples = training_samples[ bstart:bstop, : ]
blabels = training_labels[ bstart:bstop, : ]
# Feed forward:
bactivations, boutputs = self.predictSignal( bsamples )
# Prepare batch deltas:
bdeltas = []
# Back propagate from final outputs:
bdeltas.append( self.activation_dfn( bactivations[ num_layers ] ) * ( boutputs[ num_layers ] - blabels ) )
# Back propagate remaining layers:
for i in range( num_layers - 1, 0, -1 ):
bdeltas.append( self.activation_dfn( bactivations[ i ] ) * np.dot( bdeltas[ -1 ], self.layers[ i ].weights.T ) )
# Apply batch deltas:
for i in range( num_layers ):
self.layers[ i ].weights -= bmult * np.dot( boutputs[ i ].T, bdeltas[ num_layers - i - 1 ] )
self.layers[ i ].bias -= bmult * np.sum( bdeltas[ num_layers - i - 1 ], axis = 0 )
# Scale batch error and accumulate total:
error += self.getErrorRate( blabels, boutputs[ -1 ] ) * ( float( bsize ) / float( num_rows ) )
# Return training error:
return error
def train(self, training_samples, training_labels, validation_samples, validation_labels, learn_rate, epochs, batch_size = 10, report_freq = 10, report_buff = 100):
# Setup error reporter:
error_reporter = MnistSupervisedReporter( self.name, report_freq, report_buff )
# Iterate over each training epoch:
for epoch in range( epochs ):
# Perform training:
training_error = self.trainEpoch( training_samples, training_labels, learn_rate, batch_size )
# Report error, if applicable:
if ( epoch + 1 ) % report_freq == 0:
# Compute validation error:
validation_guesses = self.predict( validation_samples )
validation_error = self.getErrorRate( validation_labels, validation_guesses )
# Update error reporter:
error_reporter.update( epoch, training_error, validation_error, validation_labels, validation_guesses )
# Save final training visualization to image:
error_reporter.saveImage( 'report_' + self.name + '_training.png' )
|
Shell | UTF-8 | 1,353 | 3.46875 | 3 | [] | no_license | #! /bin/bash
if [ -z $music_folder ]; then
music_folder="/home/${USER}/"
fi
if [ ! -z $1 ]; then
music_folder=$1
fi
if [ -z "$(pidof spotify)" ]; then
echo "spotify not running... exit..."
exit 1
fi
pulse_sink=$(
pactl list sink-inputs \
| fgrep --regexp='Sink' --regexp='media.name = "Spotify"' \
| head -n2 | tail -n1 \
| grep -o '[0-9]*'
)
current_record_artist=""
current_record_title=""
while true; do
spotify_metadata=$(dbus-send --print-reply --dest=org.mpris.MediaPlayer2.spotify \
/org/mpris/MediaPlayer2 org.freedesktop.DBus.Properties.Get \
string:org.mpris.MediaPlayer2.Player string:Metadata 2>/dev/null)
artist=$(echo $spotify_metadata | grep -o 'artist.*autoRating' | grep -o '"[a-zA-Z0-9].* ]' | tr -d '"]')
title=$(echo $spotify_metadata | grep -o 'title.*trackNumber' | grep -o '"[a-zA-Z0-9].*)' | tr -d '")')
if [ -z "$artist" ]; then
killall ffmpeg 2> /dev/null
continue
fi
if [ "$artist" = "$current_record_artist" ] && [ "$title" = "$current_record_title" ] ; then
sleep 1
continue
else
killall ffmpeg 2>/dev/null
fi
current_record_artist=$artist
current_record_title=$title
filename="${music_folder}${artist}- ${title::-1}.mp3"
ffmpeg -hide_banner -loglevel panic -nostats -f pulse -ac 2 -i "$pulse_sink" \
-metadata title="$title" -metadata artist="$artist" "$filename" &
done
|
JavaScript | UTF-8 | 832 | 3.25 | 3 | [] | no_license | function add (answer1,answer2,answer3) {
return (answer1 + answer2 + answer3);
}
$(document).ready(function() {
$("form#intro").submit(function(event) {
event.preventDefault();
$(".intro").hide();
$(".quiz").show();
});
$("form#quiz").submit(function(event) {
event.preventDefault();
let answer1 = parseInt($("input:radio[name=chargingCreature]:checked").val());
let answer2 = parseInt($("input:radio[name=essay]:checked").val());
let answer3 = parseInt($("input:radio[name=money]:checked").val());
let result = add(answer1, answer2, answer3);
if (result <= 3) {
$("#harry").show();
} else if (result > 3 && result <= 7) {
$("#ron").show();
} else if (result > 7) {
$("#hermione").show();
}
$(".quiz").hide();
// $(".results").show();
});
});
|
Python | UTF-8 | 1,060 | 3.375 | 3 | [] | no_license | # # 6/6/2020
# Another way to visualize your XGBoost models is to examine the importance of each feature column in the original dataset within the model.
# One simple way of doing this involves counting the number of times each feature is split on across all boosting rounds (trees) in the model, and then visualizing the result as a bar graph, with the features ordered according to how many times they appear. XGBoost has a plot_importance() function that allows you to do exactly this, and you'll get a chance to use it in this exercise!
# Create the DMatrix: housing_dmatrix
housing_dmatrix = xgb.DMatrix(data= X, label= y)
# Create the parameter dictionary: params
params = {"objective": "reg:linear", "max_depth": 4}
# Train the model: xg_reg
xg_reg = xgb.train(params=params, dtrain= housing_dmatrix, num_boost_round= 10)
# Plot the feature importances
xgb.plot_importance(xg_reg)
plt.show()
# <script.py> output:
# [03:56:22] WARNING: /workspace/src/objective/regression_obj.cu:152: reg:linear is now deprecated in favor of reg:squarederror.
|
Python | UTF-8 | 1,309 | 2.75 | 3 | [] | no_license | import configuration
class GCodeContext:
def __init__(self):
self.drawing = False
self.start_codes = configuration.start_codes
self.stop_codes = configuration.stop_codes
# delay between startup and start of extrusion
self.startup_lag = 0.0
self.stop_lag = 0.0
self.draw_speed = configuration.draw_rate
self.travel_speed = configuration.travel_rate
self.last = None
self.codes = configuration.preamble
def start(self):
if not self.drawing:
self.codes.extend(self.start_codes)
self.drawing = True
def stop(self):
if self.drawing:
self.codes.extend(self.stop_codes)
self.drawing = False
def draw_line_to(self,x,y,stop=True):
if self.last == (x,y):
return
self.start()
self.codes.append("G1 X%f Y%f F%f" % (x,y,self.draw_speed))
self.last = (x,y)
if stop:
self.stop()
def travel_to(self,x,y,start=True):
if self.last == (x,y):
return
self.stop()
self.codes.append("G1 X%f Y%f F%f" % (x,y,self.travel_speed))
self.last = (x,y)
if start:
self.start()
def finish():
self.codes.extend(configuration.postscript)
|
SQL | UTF-8 | 8,012 | 4.5625 | 5 | [] | no_license | -- Create these queries to develop greater fluency in SQL, an important database language.
USE sakila;
-- 1a. Display the first and last names of all actors from the table actor.
SELECT first_name, last_name
FROM actor;
-- 1b. Display the first and last name of each actor in a single column in upper case letters. Name the column Actor Name.
SELECT UPPER(CONCAT(first_name, ' ', last_name)) AS 'Actor Name'
FROM actor;
-- 2a. You need to find the ID number, first name, and last name of an actor, of whom you know only the first name, "Joe."
-- What is one query would you use to obtain this information?
select * from actor
where first_name = 'Joe';
-- 2b. Find all actors whose last name contain the letters GEN:
select * from actor
where last_name LIKE '%GEN%';
-- 2c. Find all actors whose last names contain the letters LI. This time, order the rows by last name and first name, in that order:
select * from actor
where last_name LIKE '%LI%'
order by last_name, first_name;
-- 2d. Using IN, display the country_id and country columns of the following countries: Afghanistan, Bangladesh, and China:
SELECT country_id, country
FROM country
WHERE country IN ('Afghanistan', 'Bangladesh', 'China');
-- 3a. You want to keep a description of each actor. You don't think you will be performing queries on a description,
-- so create a column in the table actor named description and use the data type BLOB (Make sure to research the type BLOB,
-- as the difference between it and VARCHAR are significant).
ALTER TABLE `sakila`.`actor`
ADD COLUMN `Description` BLOB NULL AFTER `last_update`;
-- 3b. Very quickly you realize that entering descriptions for each actor is too much effort. Delete the description column.
ALTER TABLE `sakila`.`actor`
DROP COLUMN `Description`;
-- 4a. List the last names of actors, as well as how many actors have that last name.
select last_name, count(*) as actor_count
from actor group by last_name
order by actor_count desc;
-- 4b. List last names of actors and the number of actors who have that last name, but only for names that are shared by at least two actors.
select last_name, count(*) as actor_count2
from actor
group by last_name
having count(actor_id) > 1;
-- 4c. The actor HARPO WILLIAMS was accidentally entered in the actor table as GROUCHO WILLIAMS. Write a query to fix the record.
UPDATE `sakila`.`actor` SET `first_name` = 'HARPO' WHERE (`actor_id` = '172');
-- 4d. Perhaps we were too hasty in changing GROUCHO to HARPO. It turns out that GROUCHO was the correct name after all! In a single query,
-- if the first name of the actor is currently HARPO, change it to GROUCHO.
UPDATE `sakila`.`actor` SET `first_name` = 'GROUCHO' WHERE (`actor_id` = '172');
-- 5a. You cannot locate the schema of the address table. Which query would you use to re-create it?
show create table address;
-- 6a. Use JOIN to display the first and last names, as well as the address, of each staff member. Use the tables staff and address:
select staff.first_name, staff.last_name, staff.address_id, address.address
from address
inner join staff on staff.address_id = address.address_id;
-- 6b. Use JOIN to display the total amount rung up by each staff member in August of 2005. Use tables staff and payment.
select staff.first_name, staff.last_name, sum(payment.amount)
from staff
inner join payment on staff.staff_id = payment.staff_id
where payment_date LIKE "2005-05-%";
-- 6c. List each film and the number of actors who are listed for that film. Use tables film_actor and film. Use inner join.
select count(film_actor.actor_id), film.title
from film
inner join film_actor
using (film_id)
group by film.title;
-- 6d. How many copies of the film Hunchback Impossible exist in the inventory system?
select count(*)
from inventory
where film_id IN
(
select film_id
from film
where title = "Hunchback Impossible"
);
-- 6e. Using the tables payment and customer and the JOIN command, list the total paid by each customer. List the customers alphabetically by last name:
select customer.first_name, customer.last_name, sum(payment.amount)
from customer
inner join payment using (customer_id)
group by last_name;
-- 7a. The music of Queen and Kris Kristofferson have seen an unlikely resurgence. As an unintended consequence,
-- films starting with the letters K and Q have also soared in popularity. Use subqueries to display the titles of movies starting with the
-- letters K and Q whose language is English.
select title
from film
where title LIKE "K%" or title LIKE "Q%" and title IN
(
select title
from film
where language_id IN
(
select language_id
from language
where name = "English"
)
);
-- 7b. Use subqueries to display all actors who appear in the film Alone Trip.
select first_name, last_name
from actor
where actor_id IN
(
select actor_id
from film_actor
where film_id IN
(
select film_id
from film
where title = "Alone Trip"
)
);
-- 7c. You want to run an email marketing campaign in Canada, for which you will need the names and email addresses of all Canadian customers.
-- Use joins to retrieve this information.
select customer.first_name, customer.last_name, customer.email,
customer.address_id, address.city_id, city.country_id,
country.country_id
from customer
inner join address on customer.address_id = address.address_id
inner join city on city.country_id = country.country_id
where country.country = "Canada";
-- 7d. Sales have been lagging among young families, and you wish to target all family movies for a promotion. Identify all movies categorized as family films.
select title
from film
where film_id IN
(
select film_id
from film_category
where category_id IN
(
select category_id
from category
where name = "Family"
)
);
-- 7e. Display the most frequently rented movies in descending order.
select title
from film group by title
order by rental_rate desc;
-- 7f. Write a query to display how much business, in dollars, each store brought in.
SELECT
store.store_id, SUM(amount) AS revenue
FROM
store
INNER JOIN
staff ON store.store_id = staff.store_id
INNER JOIN
payment ON payment.staff_id = staff.staff_id
GROUP BY store.store_id;
-- 7g. Write a query to display for each store its store ID, city, and country.
SELECT
store.store_id, city.city, country.country
FROM
store
INNER JOIN
address ON store.address_id = address.address_id
INNER JOIN
city ON address.city_id = city.city_id
INNER JOIN
country ON city.country_id = country.country_id;
-- 7h. List the top five genres in gross revenue in descending order. (Hint: you may need to use the following tables:
-- category, film_category, inventory, payment, and rental.)
SELECT
name, SUM(p.amount) AS gross_revenue
FROM
category c
INNER JOIN
film_category fc ON fc.category_id = c.category_id
INNER JOIN
inventory i ON i.film_id = fc.film_id
INNER JOIN
rental r ON r.inventory_id = i.inventory_id
RIGHT JOIN
payment p ON p.rental_id = r.rental_id
GROUP BY name
ORDER BY gross_revenue DESC
LIMIT 5;
-- 8a. In your new role as an executive, you would like to have an easy way of viewing the Top five genres by gross revenue.
-- Use the solution from the problem above to create a view. If you haven't solved 7h, you can substitute another query to create a view.
DROP VIEW IF EXISTS top_five_genres;
CREATE VIEW top_five_genres AS
SELECT
name, SUM(p.amount) AS gross_revenue
FROM
category c
INNER JOIN
film_category fc ON fc.category_id = c.category_id
INNER JOIN
inventory i ON i.film_id = fc.film_id
INNER JOIN
rental r ON r.inventory_id = i.inventory_id
RIGHT JOIN
payment p ON p.rental_id = r.rental_id
GROUP BY name
ORDER BY gross_revenue DESC
LIMIT 5;
-- 8b. How would you display the view that you created in 8a?
SELECT * FROM top_five_genres;
-- 8c. You find that you no longer need the view top_five_genres. Write a query to delete it.
Drop view top_five_genres |
C++ | UTF-8 | 830 | 2.53125 | 3 | [] | no_license | #pragma once
namespace Stormancer
{
class Document
{
public:
std::string id;
std::string type;
long long version;
//Stored document
std::string content;
MSGPACK_DEFINE(id, type, version, content)
};
class PutResult
{
public:
//true if the server could store/update the record, false in case of update conflict.
bool success;
//version of the document
long long version;
//currently stored document, if success == false
std::string content;
MSGPACK_DEFINE(success, version, content)
};
class SearchRequest
{
public:
std::string Type;
std::unordered_map < std::string, std::string > Must;
int Skip = 0;
int Size = 50;
MSGPACK_DEFINE(Type, Must, Skip, Size)
};
class SearchResponse
{
public:
std::vector<std::string> Hits;
long Total;
MSGPACK_DEFINE(Hits, Total)
};
} |
Python | UTF-8 | 560 | 2.609375 | 3 | [] | no_license | # importar el archivo de la conexión a la BD
from configdb import get_connection
def add_user(email, name, passwd ):
cnn = get_connection()
with cnn.cursor() as cursor:
cursor.execute("INSERT INTO user (email, name, passwd) VALUES (%s,%s,%s)",(email, name, passwd))
cnn.commit()
cnn.close()
def update_user( email, name, passwd):
cnn = get_connection()
with cnn.cursor() as cursor:
cursor.execute("UPDATE user SET name = %s, passwod = %s WHERE email = %s",(name, passwd, email))
cnn.commit()
cnn.close()
|
Python | UTF-8 | 2,484 | 2.65625 | 3 | [] | no_license | import click
import json
from api import make_api_request
from commands.config import value_or_config
@click.group('spaces', help='List, view, update, and delete spaces')
def spaces():
pass
@click.command('list', help='List all spaces you have access to')
@click.option('-t',
'--team-id',
help='The team ID you want to access',
required=False)
@click.option('-a',
'--archived',
help='Include archived spaces',
is_flag=True,
default=False,
required=False)
@click.option('--include-features',
help='Include feature information',
is_flag=True,
default=False,
required=False)
@click.option('--include-statuses',
help='Include any custom status information',
is_flag=True,
default=False,
required=False)
def list_spaces(team_id, archived, include_features, include_statuses):
team_id = value_or_config(team_id, 'team-id')
response = make_api_request('team/%s/space?archived=%s' %
(team_id, str(archived)))
if 'spaces' in response:
for space in response['spaces']:
if not include_features and 'features' in space:
del space['features']
if not include_statuses and 'statuses' in space:
del space['statuses']
click.echo(json.dumps(response, indent=4, sort_keys=True))
@click.command('get', help='Get a single space and associated information')
@click.option('-s', '--space-id', help='The ID of the space to return')
@click.option('--include-features',
help='Include feature information',
is_flag=True,
default=False,
required=False)
@click.option('--include-statuses',
help='Include any custom status information',
is_flag=True,
default=False,
required=False)
def get_space(space_id, include_features, include_statuses):
space_id = value_or_config(space_id, 'space-id')
response = make_api_request('space/%s' % space_id)
if not include_features and 'features' in response:
del response['features']
if not include_statuses and 'statuses' in response:
del response['statuses']
click.echo(json.dumps(response, indent=4, sort_keys=True))
spaces.add_command(list_spaces)
spaces.add_command(get_space)
|
JavaScript | UTF-8 | 1,282 | 3.03125 | 3 | [
"Apache-2.0"
] | permissive | // @flow
import type {Point} from './utils'
const GESTURE_INTERVAL = 3000 // milis
const STROKES_TO_SHAKE = 5
const MIN_STROKE_LENGTH = 20 // px
let shakes = 0
let lastX = null
let lastY = null
let firstXInDir = 0
let lastDir = null
let gestureTimeout = null
export const resetGesture = () => {
gestureTimeout && clearTimeout(gestureTimeout)
gestureTimeout = null
lastX = lastY = null
lastDir = null
shakes = 0
}
export const checkShaking = ({x, y}: Point) => {
if (lastX == null || lastY == null || lastX === x) {
// start gesture
lastX = firstXInDir = x
lastY = y
gestureTimeout = setTimeout(() => {
resetGesture() // gesture must be finished before GESTURE_INTERVAL ends
}, GESTURE_INTERVAL)
return false
}
const dir = x - lastX > 0 ? 1 : -1
if (dir !== lastDir && Math.abs(y - lastY) < 2 * MIN_STROKE_LENGTH) {
// if x direction changed, while y movement is small enough:
if (Math.abs(x - firstXInDir) > MIN_STROKE_LENGTH) {
// if x movement is big enough, consider this a 'shake' stroke
shakes++
}
lastDir = dir
firstXInDir = x
}
lastX = x
if (shakes >= STROKES_TO_SHAKE) {
// if enough shakes, consider this a shaking gesture
resetGesture()
return true
}
return false
}
|
Java | UTF-8 | 13,437 | 2.078125 | 2 | [] | no_license | package paneles;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.RowSorter.SortKey;
import javax.swing.SortOrder;
import javax.swing.SwingWorker;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import app.App;
import daos.DeporteDAO;
import dominio.Deporte;
import dtos.VerInterfazCompetenciaDTO;
import gestores.GestorCompetencia;
import gestores.GestorDeporte;
import gui.Gui;
import gui.MyIcon;
import gui.MyJComboBox;
import gui.MyJTable;
import gui.MyJTextField;
import gui.MyPaginator;
import gui.MyTitle;
import gui.PanelPersonalizado;
import gui.PredefinedRowSorter;
import guiejemplos.BubbleLabelRight;
public class PanelMisCompetencias extends PanelPersonalizado {
PanelMisCompetenciasTM tablemodel;
App padre;
MyIcon cargando1;
MyIcon cargando2;
VerInterfazCompetenciaDTO filtro;
MyJTable table;
MyJTextField camponombre;
MyJComboBox combodeporte;
MyJComboBox combomodalidad;
MyJComboBox comboestado;
GestorCompetencia gestorCompetencia;
MyPaginator paginador;
public PanelMisCompetencias(App padre) {
super();
this.padre = padre;
gestorCompetencia = new GestorCompetencia();
GestorDeporte gestorDeporte = new GestorDeporte();
this.setPreferredSize(new Dimension(700, 734));
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[] {142, 0};
gridBagLayout.rowHeights = new int[] {30, 218, 30, 30, 30};
gridBagLayout.columnWeights = new double[]{1.0, 0.0};
gridBagLayout.rowWeights = new double[]{0.0, 0.0, 1.0};
setLayout(gridBagLayout);
MyTitle myTitle = new MyTitle("Mis Competencias");
GridBagConstraints gbc_myTitle = new GridBagConstraints();
gbc_myTitle.fill = GridBagConstraints.HORIZONTAL;
gbc_myTitle.insets = new Insets(0, 0, 5, 5);
gbc_myTitle.gridx = 0;
gbc_myTitle.gridy = 0;
add(myTitle, gbc_myTitle);
JPanel panel = new JPanel();
panel.setBorder(new CompoundBorder(new TitledBorder(new LineBorder(new Color(0, 0, 0), 2, true), "Filtros", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)), new EmptyBorder(5, 5, 5, 5)));
panel.setBounds(new Rectangle(30, 50, 0, 0));
GridBagConstraints gbc_panel = new GridBagConstraints();
gbc_panel.anchor = GridBagConstraints.NORTH;
gbc_panel.insets = new Insets(0, 30, 5, 30);
gbc_panel.fill = GridBagConstraints.HORIZONTAL;
gbc_panel.gridx = 0;
gbc_panel.gridy = 1;
add(panel, gbc_panel);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[] {30, 30, 30, 0};
gbl_panel.rowHeights = new int[] {20, 30, 30, 30, 30};
gbl_panel.columnWeights = new double[]{0.0, 1.0, 0.0, 0.0};
gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0};
panel.setLayout(gbl_panel);
JLabel lblNewLabel = new JLabel("Nombre de la competencia");
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.insets = new Insets(5, 5, 5, 5);
gbc_lblNewLabel.anchor = GridBagConstraints.WEST;
gbc_lblNewLabel.gridx = 0;
gbc_lblNewLabel.gridy = 0;
panel.add(lblNewLabel, gbc_lblNewLabel);
camponombre = new MyJTextField("Ingrese uno...");
GridBagConstraints gbc_myJTextField = new GridBagConstraints();
gbc_myJTextField.insets = new Insets(5, 5, 5, 5);
gbc_myJTextField.gridwidth = 2;
gbc_myJTextField.fill = GridBagConstraints.HORIZONTAL;
gbc_myJTextField.gridx = 1;
gbc_myJTextField.gridy = 0;
panel.add(camponombre, gbc_myJTextField);
JLabel label_2 = new JLabel("Deporte");
GridBagConstraints gbc_label_2 = new GridBagConstraints();
gbc_label_2.anchor = GridBagConstraints.WEST;
gbc_label_2.insets = new Insets(10, 5, 5, 5);
gbc_label_2.gridx = 0;
gbc_label_2.gridy = 1;
panel.add(label_2, gbc_label_2);
combodeporte = new MyJComboBox();
GridBagConstraints gbc_myJComboBox = new GridBagConstraints();
gbc_myJComboBox.gridwidth = 2;
gbc_myJComboBox.insets = new Insets(10, 5, 5, 5);
gbc_myJComboBox.fill = GridBagConstraints.HORIZONTAL;
gbc_myJComboBox.gridx = 1;
gbc_myJComboBox.gridy = 1;
panel.add(combodeporte, gbc_myJComboBox);
cargando1 = new MyIcon("icon/loading3.gif",24,24,true);
GridBagConstraints gbc_lblNewLabel_1 = new GridBagConstraints();
gbc_lblNewLabel_1.insets = new Insets(0, 0, 5, 0);
gbc_lblNewLabel_1.gridx = 3;
gbc_lblNewLabel_1.gridy = 1;
panel.add(cargando1, gbc_lblNewLabel_1);
JLabel label = new JLabel("Modalidad");
GridBagConstraints gbc_label = new GridBagConstraints();
gbc_label.anchor = GridBagConstraints.WEST;
gbc_label.insets = new Insets(10, 5, 5, 5);
gbc_label.gridx = 0;
gbc_label.gridy = 2;
panel.add(label, gbc_label);
combomodalidad = new MyJComboBox(new String[] {"Liga", "Eliminatoria Simple", "Eliminatoria Doble" });
GridBagConstraints gbc_myJComboBox_1 = new GridBagConstraints();
gbc_myJComboBox_1.gridwidth = 2;
gbc_myJComboBox_1.insets = new Insets(10, 5, 5, 5);
gbc_myJComboBox_1.fill = GridBagConstraints.HORIZONTAL;
gbc_myJComboBox_1.gridx = 1;
gbc_myJComboBox_1.gridy = 2;
panel.add(combomodalidad, gbc_myJComboBox_1);
JLabel label_1 = new JLabel("Estado");
GridBagConstraints gbc_label_1 = new GridBagConstraints();
gbc_label_1.anchor = GridBagConstraints.WEST;
gbc_label_1.insets = new Insets(10, 5, 5, 10);
gbc_label_1.gridx = 0;
gbc_label_1.gridy = 3;
panel.add(label_1, gbc_label_1);
comboestado = new MyJComboBox(new String[] {"CREADA","PLANIFICADA","ENDISPUTA","FINALIZADA"});
GridBagConstraints gbc_myJComboBox_2 = new GridBagConstraints();
gbc_myJComboBox_2.insets = new Insets(10, 5, 5, 5);
gbc_myJComboBox_2.gridwidth = 2;
gbc_myJComboBox_2.fill = GridBagConstraints.HORIZONTAL;
gbc_myJComboBox_2.gridx = 1;
gbc_myJComboBox_2.gridy = 3;
panel.add(comboestado, gbc_myJComboBox_2);
JButton botonbuscar = new JButton("Buscar");
botonbuscar.setIcon(Gui.emoji("icon/lupa.png", 24, 24, false));
GridBagConstraints gbc_btnNewButton_2 = new GridBagConstraints();
gbc_btnNewButton_2.insets = new Insets(5, 5, 0, 5);
gbc_btnNewButton_2.gridx = 2;
gbc_btnNewButton_2.gridy = 4;
panel.add(botonbuscar, gbc_btnNewButton_2);
JScrollPane scrollPane = new JScrollPane();
GridBagConstraints gbc_scrollPane = new GridBagConstraints();
gbc_scrollPane.fill = GridBagConstraints.BOTH;
gbc_scrollPane.insets = new Insets(10, 0, 5, 5);
gbc_scrollPane.gridx = 0;
gbc_scrollPane.gridy = 2;
add(scrollPane, gbc_scrollPane);
tablemodel = new PanelMisCompetenciasTM();
table = new MyJTable(tablemodel);
table.setJTableColumnsWidth(36,14,25,19,6);
scrollPane.setViewportView(table);
cargando2 = new MyIcon("icon/loading3.gif",24,24,true,false,true);
GridBagConstraints gbc_cargando2 = new GridBagConstraints();
gbc_cargando2.anchor = GridBagConstraints.NORTH;
gbc_cargando2.insets = new Insets(0, 0, 5, 0);
gbc_cargando2.gridx = 1;
gbc_cargando2.gridy = 2;
add(cargando2, gbc_cargando2);
JPanel panel_1 = new JPanel();
GridBagConstraints gbc_panel_1 = new GridBagConstraints();
gbc_panel_1.insets = new Insets(0, 0, 5, 5);
gbc_panel_1.fill = GridBagConstraints.BOTH;
gbc_panel_1.gridx = 0;
gbc_panel_1.gridy = 3;
add(panel_1, gbc_panel_1);
GridBagLayout gbl_panel_1 = new GridBagLayout();
gbl_panel_1.columnWidths = new int[]{334, 0, 0, 0};
gbl_panel_1.rowHeights = new int[]{0, 0, 0};
gbl_panel_1.columnWeights = new double[]{1.0, 0.0, 0.0, Double.MIN_VALUE};
gbl_panel_1.rowWeights = new double[]{0.0, 1.0, Double.MIN_VALUE};
panel_1.setLayout(gbl_panel_1);
paginador = new MyPaginator(tablemodel.getRowsperpage());
GridBagLayout gridBagLayout_1 = (GridBagLayout) paginador.getLayout();
gridBagLayout_1.rowWeights = new double[]{0.0};
gridBagLayout_1.rowHeights = new int[]{23};
gridBagLayout_1.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0};
gridBagLayout_1.columnWidths = new int[]{25, 25, 25, 25, 0};
GridBagConstraints gbc_myPaginator = new GridBagConstraints();
gbc_myPaginator.anchor = GridBagConstraints.WEST;
gbc_myPaginator.insets = new Insets(0, 0, 5, 5);
gbc_myPaginator.fill = GridBagConstraints.VERTICAL;
gbc_myPaginator.gridx = 0;
gbc_myPaginator.gridy = 0;
panel_1.add(paginador, gbc_myPaginator);
JButton botonvolver = new JButton("Volver");
GridBagConstraints gbc_botonvolver = new GridBagConstraints();
gbc_botonvolver.anchor = GridBagConstraints.EAST;
gbc_botonvolver.fill = GridBagConstraints.VERTICAL;
gbc_botonvolver.insets = new Insets(0, 0, 5, 5);
gbc_botonvolver.gridx = 1;
gbc_botonvolver.gridy = 0;
panel_1.add(botonvolver, gbc_botonvolver);
JButton botonnuevacompetancia = new JButton(" Nueva competencia");
botonnuevacompetancia.setIcon(Gui.emoji("icon/mas_negro.png", 24, 24, false));
GridBagConstraints gbc_nuevacompetencia = new GridBagConstraints();
gbc_nuevacompetencia.anchor = GridBagConstraints.EAST;
gbc_nuevacompetencia.insets = new Insets(0, 0, 5, 0);
gbc_nuevacompetencia.gridx = 2;
gbc_nuevacompetencia.gridy = 0;
panel_1.add(botonnuevacompetancia, gbc_nuevacompetencia);
SwingWorker<String[], Void> trabajador1 = new SwingWorker<String[], Void>(){
private String[] t;
@Override
protected String[] doInBackground() throws Exception {
t = gestorDeporte
.getAllDeportes()
.stream()
.map(d->d.getNombre())
.collect(Collectors.toList())
.toArray(new String[0]);
return t;
}
@Override
protected void done() {
combodeporte.setModel(new DefaultComboBoxModel<String>(t!=null?t:new String[] {" "}));
cargando1.setVisible(false);
}
};
trabajador1.execute();
SwingWorker<PanelMisCompetenciasTM, Void> trabajador2 = new SwingWorker<PanelMisCompetenciasTM, Void>(){
private PanelMisCompetenciasTM t;
@Override
protected PanelMisCompetenciasTM doInBackground() throws Exception {
cargando2.setVisible(true);
t= new PanelMisCompetenciasTM(gestorCompetencia.getCompetencias());
// List<VerInterfazCompetenciaDTO> lista = new ArrayList<VerInterfazCompetenciaDTO>();
// for(int i=0; i<50; i++) {
// lista.add(new VerInterfazCompetenciaDTO(i, "xd"+i, "xd", "xd", "xd"));
// }
// t = new PanelMisCompetenciasTM(lista);
return t;
}
@Override
protected void done() {
tablemodel=t;
if(t!=null) {
table.setModel(t);
table.setJTableColumnsWidth(36,14,25,19,6);
cargando2.setVisible(false);
paginador.setDataSize(t.getTam());
// table.ordenar();
}
else {
Gui.imprimir("Hubo un error cargando la tabla desde la db");
}
}
};
trabajador2.execute();
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if(table.getSelectedColumn()==4) {
padre.nuevoPanel(new PanelVerCompetenciaConMensajes(padre, (int)tablemodel.getValueAt(table.getSelectedRow(), 5)));
Gui.imprimir("cambiar a panel ver competencia");
}
}
});
botonbuscar.addActionListener(e->{
PanelMisCompetencias.Trabajador3 t = this.new Trabajador3();
t.execute();
});
botonnuevacompetancia.addActionListener(e->{
padre.nuevoPanel(new PanelAltaCompetenciaConMensajes(padre));
});
botonvolver.addActionListener(e->{
padre.volverAtras();
});
paginador.getFirst().addActionListener(e->{
tablemodel.setActualPage(1);
});
paginador.getBack().addActionListener(e->{
tablemodel.setActualPage(tablemodel.getActualpage()-1);
});
paginador.getNext().addActionListener(e->{
tablemodel.setActualPage(tablemodel.getActualpage()+1);
});
paginador.getLast().addActionListener(e->{
tablemodel.setActualPage(tablemodel.getTotalpages());
});
}
class Trabajador3 extends SwingWorker<PanelMisCompetenciasTM, Void>{
public PanelMisCompetenciasTM t;
@Override
public PanelMisCompetenciasTM doInBackground() throws Exception {
PanelMisCompetencias.this.cargando2.setVisible(true);
VerInterfazCompetenciaDTO filtro = new VerInterfazCompetenciaDTO();
filtro.setNombre(PanelMisCompetencias.this.camponombre.getText());
filtro.setDeporte(PanelMisCompetencias.this.combodeporte.getSelectedItem());
filtro.setModalidad(PanelMisCompetencias.this.combomodalidad.getSelectedItem());
filtro.setEstado(PanelMisCompetencias.this.comboestado.getSelectedItem());
this.t= new PanelMisCompetenciasTM(PanelMisCompetencias.this.gestorCompetencia.getCompetencias(filtro));
return this.t;
}
@Override
public void done() {
PanelMisCompetencias.this.tablemodel=this.t;
if(this.t!=null) {
PanelMisCompetencias.this.table.setModel(this.t);
PanelMisCompetencias.this.table.setJTableColumnsWidth(36,14,25,19,6);
PanelMisCompetencias.this.cargando2.setVisible(false);
PanelMisCompetencias.this.paginador.setDataSize(this.t.getTam());
// PanelMisCompetencias.this.paginador.setPage(1);
}
else {
Gui.imprimir("Hubo un error haciendo la consulta en la db");
}
}
}
}
|
Markdown | UTF-8 | 9,394 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | # 金史
## 简介
《金史》撰成于元代,全书一百三十五卷,其中本纪十九卷,志三十九卷,表四卷,列传七十三卷,记载了上起金太祖完颜阿骨打出生(1068年),下至金哀宗天兴三年(1234年)蒙古灭金,共一百二十年的历史。是反映女真族所建金朝的兴衰始末的重要史籍。历代对《金史》的评价很高,认为它不仅超过了《宋史》、《辽史》,也比《元史》高出一筹。
[卷一本纪第一___](卷一本纪第一.md)
[卷二本纪第二___](卷二本纪第二.md)
[卷三本纪第三___](卷三本纪第三.md)
[卷四本纪第四___](卷四本纪第四.md)
[卷五本纪第五___](卷五本纪第五.md)
[卷六本纪第六___](卷六本纪第六.md)
[卷七本纪第七___](卷七本纪第七.md)
[卷八本纪第八___](卷八本纪第八.md)
[卷九本纪第九___](卷九本纪第九.md)
[卷十本纪第十___](卷十本纪第十.md)
[卷十一本纪第十一___](卷十一本纪第十一.md)
[卷十二本纪第十二___](卷十二本纪第十二.md)
[卷十三本纪第十三___](卷十三本纪第十三.md)
[卷十四本纪第十四___](卷十四本纪第十四.md)
[卷十五本纪第十五___](卷十五本纪第十五.md)
[卷十六本纪第十六___](卷十六本纪第十六.md)
[卷十七本纪第十七___](卷十七本纪第十七.md)
[卷十八本纪第十八___](卷十八本纪第十八.md)
[卷十九本纪第十九___](卷十九本纪第十九.md)
[卷二十志第一___](卷二十志第一.md)
[卷二十一志第二___](卷二十一志第二.md)
[卷二十二志第三___](卷二十二志第三.md)
[卷二十三志第四___](卷二十三志第四.md)
[卷二十四志第五___](卷二十四志第五.md)
[卷二十五志第六___](卷二十五志第六.md)
[卷二十六志第七___](卷二十六志第七.md)
[卷二十七志第八___](卷二十七志第八.md)
[卷二十八志第九___](卷二十八志第九.md)
[卷二十九志第十___](卷二十九志第十.md)
[卷三十志第十一___](卷三十志第十一.md)
[卷三十一志第十二___](卷三十一志第十二.md)
[卷三十二志第十三___](卷三十二志第十三.md)
[卷三十三志第十四___](卷三十三志第十四.md)
[卷三十四志第十五___](卷三十四志第十五.md)
[卷三十五志第十六___](卷三十五志第十六.md)
[卷三十六志第十七___](卷三十六志第十七.md)
[卷三十七志第十八___](卷三十七志第十八.md)
[卷三十八志第十九___](卷三十八志第十九.md)
[卷三十九志第二十___](卷三十九志第二十.md)
[卷四十志第二十一___](卷四十志第二十一.md)
[卷四十一志第二十二___](卷四十一志第二十二.md)
[卷四十二志第二十三___](卷四十二志第二十三.md)
[卷四十三志第二十四___](卷四十三志第二十四.md)
[卷四十四志第二十五___](卷四十四志第二十五.md)
[卷四十五志第二十六___](卷四十五志第二十六.md)
[卷四十六志第二十七___](卷四十六志第二十七.md)
[卷四十七志第二十八___](卷四十七志第二十八.md)
[卷四十八志第二十九___](卷四十八志第二十九.md)
[卷四十九志第三十___](卷四十九志第三十.md)
[卷五十志第三十一___](卷五十志第三十一.md)
[卷五十一志第三十二___](卷五十一志第三十二.md)
[卷五十二志第三十三___](卷五十二志第三十三.md)
[卷五十三志第三十四___](卷五十三志第三十四.md)
[卷五十四志第三十五___](卷五十四志第三十五.md)
[卷五十五志第三十六___](卷五十五志第三十六.md)
[卷五十六志第三十七___](卷五十六志第三十七.md)
[卷五十七志第三十八___](卷五十七志第三十八.md)
[卷五十八志第三十九___](卷五十八志第三十九.md)
[卷五十九表第一___](卷五十九表第一.md)
[卷六十表第二___](卷六十表第二.md)
[卷六十一表第三___](卷六十一表第三.md)
[卷六十二表第四___](卷六十二表第四.md)
[卷六十三列传第一___](卷六十三列传第一.md)
[卷六十四列传第二___](卷六十四列传第二.md)
[卷六十五列传第三___](卷六十五列传第三.md)
[卷六十六列传第四___](卷六十六列传第四.md)
[卷六十七列传第五___](卷六十七列传第五.md)
[卷六十八列传第六___](卷六十八列传第六.md)
[卷六十九列传第七___](卷六十九列传第七.md)
[卷七十列传第八___](卷七十列传第八.md)
[卷七十一列传第九___](卷七十一列传第九.md)
[卷七十二列传第十___](卷七十二列传第十.md)
[卷七十三列传第十一___](卷七十三列传第十一.md)
[卷七十四列传第十二___](卷七十四列传第十二.md)
[卷七十五列传第十三___](卷七十五列传第十三.md)
[卷七十六列传第十四___](卷七十六列传第十四.md)
[卷七十七列传第十五___](卷七十七列传第十五.md)
[卷七十八列传第十六___](卷七十八列传第十六.md)
[卷七十九列传第十七___](卷七十九列传第十七.md)
[卷八十列传第十八___](卷八十列传第十八.md)
[卷八十一列传第十九___](卷八十一列传第十九.md)
[卷八十二列传第二十___](卷八十二列传第二十.md)
[卷八十三列传第二十一___](卷八十三列传第二十一.md)
[卷八十四列传第二十二___](卷八十四列传第二十二.md)
[卷八十五列传第二十三___](卷八十五列传第二十三.md)
[卷八十六列传第二十四___](卷八十六列传第二十四.md)
[卷八十七列传第二十五___](卷八十七列传第二十五.md)
[卷八十八列传第二十六___](卷八十八列传第二十六.md)
[卷八十九列传第二十七___](卷八十九列传第二十七.md)
[卷九十列传第二十八___](卷九十列传第二十八.md)
[卷九十一列传第二十九___](卷九十一列传第二十九.md)
[卷九十二列传第三十___](卷九十二列传第三十.md)
[卷九十三列传第三十一___](卷九十三列传第三十一.md)
[卷九十四列传第三十二___](卷九十四列传第三十二.md)
[卷九十五列传第三十三___](卷九十五列传第三十三.md)
[卷九十六列传第三十四___](卷九十六列传第三十四.md)
[卷九十七列传第三十五___](卷九十七列传第三十五.md)
[卷九十八列传第三十六___](卷九十八列传第三十六.md)
[卷九十九列传第三十七___](卷九十九列传第三十七.md)
[卷一百列传第三十八___](卷一百列传第三十八.md)
[卷一百一列传第三十九___](卷一百一列传第三十九.md)
[卷一百二列传第四十___](卷一百二列传第四十.md)
[卷一百三列传第四十一___](卷一百三列传第四十一.md)
[卷一百四列传第四十二___](卷一百四列传第四十二.md)
[卷一百五列传第四十三___](卷一百五列传第四十三.md)
[卷一百六列传第四十四___](卷一百六列传第四十四.md)
[卷一百七列传第四十五___](卷一百七列传第四十五.md)
[卷一百八列传第四十六___](卷一百八列传第四十六.md)
[卷一百九列传第四十七___](卷一百九列传第四十七.md)
[卷一百十列传第四十八___](卷一百十列传第四十八.md)
[卷一百十一列传第四十九___](卷一百十一列传第四十九.md)
[卷一百十二列传第五十___](卷一百十二列传第五十.md)
[卷一百十三列传第五十一___](卷一百十三列传第五十一.md)
[卷一百十四列传第五十二___](卷一百十四列传第五十二.md)
[卷一百十五列传第五十三___](卷一百十五列传第五十三.md)
[卷一百十六列传第五十四___](卷一百十六列传第五十四.md)
[卷一百十七列传第五十五___](卷一百十七列传第五十五.md)
[卷一百十八列传第五十六___](卷一百十八列传第五十六.md)
[卷一百十九列传第五十七___](卷一百十九列传第五十七.md)
[卷一百二十列传第五十八___](卷一百二十列传第五十八.md)
[卷一百二十一列传第五十九___](卷一百二十一列传第五十九.md)
[卷一百二十二列传第六十___](卷一百二十二列传第六十.md)
[卷一百二十三列传第六十一___](卷一百二十三列传第六十一.md)
[卷一百二十四列传第六十二___](卷一百二十四列传第六十二.md)
[卷一百二十五列传第六十三___](卷一百二十五列传第六十三.md)
[卷一百二十六列传第六十四___](卷一百二十六列传第六十四.md)
[卷一百二十七列传第六十五___](卷一百二十七列传第六十五.md)
[卷一百二十八列传第六十六___](卷一百二十八列传第六十六.md)
[卷一百二十九列传第六十七___](卷一百二十九列传第六十七.md)
[卷一百三十列传第六十八___](卷一百三十列传第六十八.md)
[卷一百三十一列传第六十九___](卷一百三十一列传第六十九.md)
[卷一百三十二列传第七十___](卷一百三十二列传第七十.md)
[卷一百三十三列传第七十一___](卷一百三十三列传第七十一.md)
[卷一百三十四列传第七十二___](卷一百三十四列传第七十二.md)
[卷一百三十五列传第七十三___](卷一百三十五列传第七十三.md)
[附录进金史表___](附录进金史表.md) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.