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
|
|---|---|---|---|---|---|---|---|
Markdown
|
UTF-8
| 1,296
| 3.046875
| 3
|
[] |
no_license
|
# BAMBU Backend Engineer Test
The People-Like-You API sends 10 potential investors similar with the person described in the query parameters.
- the endpoint is exposed at `people-like-you`
- each of the terms in the query parameters is optional
- the endpoint returns a JSON response with an array of scored suggested matches
- the suggestions are sorted by descending score
- each suggestion has a score between 0 and 1 indicating confidence in the suggestion (1 is most confident)
#### Main features
1. If there is no query parameter, the json response would be empty.
- Sample query: /people-like-you
2. If the parameters seem unlikely and no match found, the response would be empty json file.
- Sample query: /people-like-you?age=1000
3. If there are matches found, the json response would contain 10 elements sorting from the highest score to the lowest.
- Sample query: /people-like-you?age=23&latitude=40.71667&longitude=19.56667&monthlyIncome=5500&experienced=false
4. User can specify which parameter should have the highest weight. Then the matching algorithm will give the specified parameter highest weight.
- Sample query: http://localhost:8888/people-like-you?age=23&latitude=40.71667&longitude=19.56667&monthlyIncome=5500&experienced=false&most=monthlyIncome
|
Python
|
UTF-8
| 456
| 2.59375
| 3
|
[] |
no_license
|
from django import template
register = template.Library()
@register.filter(name='is_in_cart')
def is_in_cart(product,cart):
keys = cart.keys()
for productid in keys:
if int(productid) == product.id:
return True;
return False
@register.filter(name='cart_count')
def cart_count(product,cart):
keys = cart.keys()
for productid in keys:
print(productid, product.id)
if int(productid) == product.id:
return cart.get(productid);
return 0;
|
Markdown
|
UTF-8
| 389
| 2.546875
| 3
|
[] |
no_license
|
# Kyle-Biblio
# Description
C'est une bibliothèque de plusieurs exemple de code pour l'exercise.
# Dossier
Google Font contient : Html, css
Velveytyne contient : Html, css, webfont
Images contient : Html, css, img
# Sources
code : W3Schools.com
1.Css Image gallery
Font : Google font : Inide Flower
Veveltyne.fr : Backout
Image : Knowyourmeme.com
Pinterest.ch
|
JavaScript
|
UTF-8
| 955
| 2.5625
| 3
|
[] |
no_license
|
import * as C from './constant'
const defaultState = {
onFocus: false,
list: [],
pageNumber: 0,
mouseEnter: false,
}
export default (state = defaultState, action) => {
const newState = JSON.parse(JSON.stringify(state))
switch (action.type) {
case C.ON_FOCUS:
newState.onFocus = true
return newState
case C.SEARCH_ON_BLUR:
newState.onFocus = false
return newState
case C.SEARCH_PANEL_DATA:
newState.list = action.payload
return newState
case C.CHANGE_PAGE_NUMBER:
const len = newState.list.length
const maxPage = Math.ceil(len / 10)
newState.pageNumber < maxPage - 1
? newState.pageNumber++
: newState.pageNumber = 0
return newState
case C.SEARCH_MOUSE_ENTER:
newState.mouseEnter = true
return newState
case C.SEARCH_MOUSE_LEAVE:
newState.mouseEnter = false
return newState
default:
return state
}
}
|
C++
|
UTF-8
| 1,763
| 2.53125
| 3
|
[] |
no_license
|
//#define _CRT_SECURE_NO_WARNINGS
//
//#include <windows.h>
//#include <stdio.h>
//#include <conio.h>
//#include <tchar.h>
//#include <iostream>
//#include "atlstr.h"
//#define bufSize 256
//using namespace std;
//
//
//
//void main(int argc, char *argv[]) {
//
// if (argc < 3) {
// cout << "Incorrect count of argumens!";
// _getch();
// return;
// }
//
// TCHAR message[512];
// _tcscpy(message, A2T(argv[2]));
//
//
// LPCTSTR mapName = TEXT(argv[1]);
// LPCTSTR pBuf;
// HANDLE hMap;
//
// hMap = CreateFileMapping(/*hFile*/INVALID_HANDLE_VALUE, NULL,/* PAGE_READONLY */PAGE_READWRITE, NULL, bufSize/*NULL*/, mapName);
//
// cout << "Try to create file map\n";
//
// if (hMap == NULL) {
// cout << "Fail to create map file: \"" << mapName << "\"\n";
// cout << "Error: " << GetLastError();
// _getch();
// return;
// }
//
// cout << "FileMapping finished successfuly\n";
// cout << "File map was created, access by name: \"" << mapName <<"\"\n";
//
// pBuf = (LPCTSTR) MapViewOfFile(hMap, /*FILE_MAP_READ*/FILE_MAP_ALL_ACCESS, NULL, NULL,/*bufSize*/NULL);
//
// cout << "Try to get virtual adress\n";
//
// if (pBuf == NULL) {
// cout << "Fail while getting adress\n";
// cout << "Error: " << GetLastError();
// _getch();
// return;
// }
//
// cout << "Getting virtual adress was success\n";
//
// CopyMemory((PVOID)pBuf, message, (_tcslen(message) * sizeof(TCHAR)));
//
// if (GetLastError() == 0) {
// cout << "CopyMemory function done well.\n";
// }
// else {
// cout << "Fail while writing message to map object\n";
// _getch();
// return;
// }
// cout << "Press any key to close map file\n";
//
// _getch();
//
// UnmapViewOfFile(pBuf);
//
// CloseHandle(hMap);
//
// cout << "Press any key to close aplication\n";
// _getch();
//
//
//}
|
JavaScript
|
UTF-8
| 1,155
| 2.75
| 3
|
[] |
no_license
|
import { displayResult } from '../../utils/displayResult'
/**
* Moves folder to a new location.
* @param {string} paths - folder paths (source path and destination path separated by space).
* @param {object} sasjs - configuration object of SAS adapter.
* @param {string} accessToken - an access token for an authorized user.
*/
export const move = async (paths, sasjs, accessToken) => {
const pathMap = paths.split(' ')
if (pathMap.length !== 2) {
console.log(
chalk.redBright(
`Bad command.\nCommand example: sasjs folder move /Public/sourceFolder /Public/targetFolder`
)
)
return
}
const sourceFolder = pathMap[0]
let targetFolder = pathMap[1].split('/')
const targetFolderName = targetFolder.pop()
targetFolder = targetFolder.join('/')
const movedFolder = await sasjs
.moveFolder(sourceFolder, targetFolder, targetFolderName, accessToken)
.catch((err) => {
displayResult(err)
})
if (movedFolder) {
displayResult(
null,
null,
`Folder successfully moved from '${sourceFolder}' to '${
targetFolder + '/' + targetFolderName
}'.`
)
}
}
|
C++
|
UTF-8
| 866
| 3.265625
| 3
|
[] |
no_license
|
/*
* author : mike2ox
* BJO : 좌표 정렬하기2
* descript : https://www.acmicpc.net/problem/11651
* type : sort
*/
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
vector<pair<int, int>> xy;
int N;
int x, y;
void swap(int* a, int* b) {
int t = *a;
*a = *b;
*b = t;
}
bool compare(pair<int, int>& a, pair<int, int>& b) {
if (b.second > a.second)
return true;
else if (b.second == a.second) {
if (b.first > a.first)
return true;
else
return false;
}
else
return false;
}
int main() {
ios_base::sync_with_stdio("false");
cin >> N;
while (N--) {
cin >> x >> y;
xy.push_back(make_pair(x, y));
}
sort(xy.begin(), xy.end(), compare);
for (vector<pair<int, int>>::iterator itr = xy.begin(); itr != xy.end(); itr++)
cout << (*itr).first << " " << (*itr).second << '\n';
system("pause");
return 0;
}
|
Java
|
UTF-8
| 3,934
| 2.265625
| 2
|
[] |
no_license
|
package br.com.sococo.resumo.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import javax.validation.constraints.NotEmpty;
import java.io.Serializable;
import java.util.List;
import java.util.Objects;
@Entity
@Table(name = "usuario")
public class Usuario implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotEmpty(message = "O nome é obrigatório")
@Column(nullable = false)
private String nome;
private String sobrenome;
@NotEmpty(message = "O username é obrigatório")
@Column(nullable = false, unique = true)
private String username;
@NotEmpty(message = "O email é obrigatório")
@Column(nullable = false, unique = true)
private String email;
//@NotEmpty(message = "A senha é obrigatória")
@JsonIgnore
@Column(name = "password", nullable = false)
private String password;
@Column(name = "enabled")
private boolean enabled;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "usuario_permissao", joinColumns = @JoinColumn(name = "id_usuario")
, inverseJoinColumns = @JoinColumn(name = "id_permissao"))
private List<Permissao> permissoes;
public Usuario() {
}
public Usuario(Long id, String nome, String sobrenome, String username, Object o) {
}
public Usuario(String nome, String sobrenome, String username, String email, String password) {
this.nome = nome;
this.sobrenome = sobrenome;
this.username = username;
this.email = email;
this.password = password;
// addPerfil(Perfil.USER);
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getSobrenome() {
return sobrenome;
}
public void setSobrenome(String sobrenome) {
this.sobrenome = sobrenome;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
// public Set<Perfil> getPerfis() {
// return perfis.stream().map(x -> Perfil.toEnum(x)).collect(Collectors.toSet());
// }
//
// public void addPerfil(Perfil perfil) {
// perfis.add(perfil.getCod());
// }
public List<Permissao> getPermissoes() {
return permissoes;
}
public void setPermissoes(List<Permissao> permissoes) {
this.permissoes = permissoes;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Usuario usuario = (Usuario) o;
return Objects.equals(id, usuario.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Usuario{" +
"id=" + id +
", nome='" + nome + '\'' +
", sobrenome='" + sobrenome + '\'' +
", username='" + username + '\'' +
", password='" + password + '\'' +
", enabled=" + enabled +
'}';
}
}
|
C
|
UTF-8
| 272
| 3.4375
| 3
|
[] |
no_license
|
#include <stdio.h>
int sub(int x, int y) {
return x - y;
}
int main( ) {
int a = 5; int b = 10;
int diff1, diff2, diff3;
diff1 = sub(a,b);
diff2 = sub(100, b);
diff3 = sub(24, 25);
printf("diff1 = %d, diff2 = %d, diff3 = %d\n", diff1, diff2, diff3);
return 0;
}
|
Markdown
|
UTF-8
| 1,382
| 2.515625
| 3
|
[
"Apache-2.0"
] |
permissive
|
---
title: DebugServerNativeMethods.debugserver_client_receive_response method (1 of 2)
---
Receives and parses response of debugserver service.
```csharp
public static DebugServerError debugserver_client_receive_response(DebugServerClientHandle client,
out IntPtr response)
```
| parameter | description |
| --- | --- |
| client | The debugserver client |
| response | Response received for last command (can be NULL to ignore) |
## Return Value
DEBUGSERVER_E_SUCCESS on success, DEBUGSERVER_E_INVALID_ARG when client is NULL
## See Also
* enum [DebugServerError](../DebugServerError.md)
* class [DebugServerClientHandle](../DebugServerClientHandle.md)
* class [DebugServerNativeMethods](../DebugServerNativeMethods.md)
* namespace [iMobileDevice.DebugServer](../../iMobileDevice-net.md)
---
---
title: DebugServerNativeMethods.debugserver_client_receive_response method (2 of 2)
---
```csharp
public static DebugServerError debugserver_client_receive_response(DebugServerClientHandle client,
out string response)
```
## See Also
* enum [DebugServerError](../DebugServerError.md)
* class [DebugServerClientHandle](../DebugServerClientHandle.md)
* class [DebugServerNativeMethods](../DebugServerNativeMethods.md)
* namespace [iMobileDevice.DebugServer](../../iMobileDevice-net.md)
<!-- DO NOT EDIT: generated by xmldocmd for iMobileDevice-net.dll -->
|
Shell
|
UTF-8
| 358
| 2.640625
| 3
|
[] |
no_license
|
#!/bin/bash
HOST="ipnp29"
echo "Sending files to ${HOST}..."
cd ../hbook/D0Kpi
for CHANNEL in "D0Kpi" "D0Kpipi0" "D0K3pi"; do
cd ../${CHANNEL}
for STREAM in `seq 0 5`; do
HOSTDIR="bin/belle/DSRhoYield/data/${CHANNEL}/stream${STREAM}"
rsync DSRhoSkim_svd{1,2}_on_resonance_evtgen-*_s*${STREAM}.root ${HOST}:${HOSTDIR}/.
done
done
echo "All done."
|
Java
|
UTF-8
| 363
| 2.125
| 2
|
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ucuenca.edu.optii.ecu911.negocio.excepciones;
public class ValidacionPermisosAsignados_RolExcepcion
extends RuntimeException{
public ValidacionPermisosAsignados_RolExcepcion(String message) {
System.out.print(message);
}
}
|
Shell
|
UTF-8
| 316
| 3.109375
| 3
|
[] |
no_license
|
#!/bin/sh
if [ "$1" = "remove" -o "$1" = "deconfigure" ]; then
PKILL=$(which pkill)
PGREP=$(which pgrep)
FLAG=`$PGREP -f /usr/share/rootrun/rootrun-daemon/startrootrundbusdaemon.py`
if [ -n "$FLAG" ] ; then
$PKILL -f -9 /usr/share/rootrun/rootrun-daemon/startrootrundbusdaemon.py
fi
fi
|
C#
|
UTF-8
| 1,854
| 2.515625
| 3
|
[] |
no_license
|
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TheWorld.Models;
using TheWorld.ViewModels;
namespace TheWorld.Controllers.Api
{
[Route("api/trips")]
[Authorize]
public class TripsController : Controller
{
private IWorldRepository _repository;
private ILogger<TripsController> _logger;
public TripsController(IWorldRepository repository, ILogger<TripsController> logger)
{
_repository = repository;
_logger = logger;
}
[HttpGet("")]
public IActionResult GetAllTrips()
{
try
{
var result = _repository.GetAllTripsByUsername(User.Identity.Name);
return Ok(Mapper.Map<IEnumerable<TripViewModel>>(result));
}
catch (Exception ex)
{
_logger.LogError($"Failed to get All Trips: {ex.Message}");
return BadRequest("Error occurred");
}
}
[HttpPost("")]
public async Task<IActionResult> CreateNewTrip([FromBody]TripViewModel trip)
{
if (ModelState.IsValid)
{
var newTrip = Mapper.Map<Trip>(trip);
newTrip.UserName = User.Identity.Name;
_repository.AddTrip(newTrip);
if (await _repository.SaveChangesAsync())
{
return Created($"api/trips/{trip.Name}", Mapper.Map<TripViewModel>(newTrip));
}
}
return BadRequest("Failed to save the trip");
}
}
}
|
Java
|
UTF-8
| 3,097
| 2.640625
| 3
|
[] |
no_license
|
package com.csd.activitybase.utils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Sober_philer on 2017/3/3 09:09
* 网络链接状态的类
*/
public class NetWorkUtils {
private static NetWorkUtils netWorkUtils;
private NetWorkUtils(){}
public static NetWorkUtils getInstance(){
if(netWorkUtils == null)
netWorkUtils = new NetWorkUtils();
return netWorkUtils;
}
/**
* @param context
* @return -1:没有网络 1:WIFI网络2:wap网络3:net网络
*/
public static int getNetype(Context context)
{
int netType = -1;
ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if(networkInfo==null)
{
return netType;
}
int nType = networkInfo.getType();
if(nType== ConnectivityManager.TYPE_MOBILE)
{
if(networkInfo.getExtraInfo().toLowerCase().equals("cmnet"))
{
netType = 3;
}
else
{
netType = 2;
}
}
else if(nType== ConnectivityManager.TYPE_WIFI)
{
netType = 1;
}
return netType;
}
public static class NetWorkStateChageCallBack{
public void onNetDisConnect(){}
public void onNetConnect(){}
public void onWifiConnect(){}
public void onWifiDisConnect(){}
}
private static List<NetWorkStateChageCallBack> changeCallBackList = new ArrayList<>();
/**
* 注册网络变化的监听,不再使用或退出界面请一定要调用unregistCallBack方法,否则会发送严重内存泄漏
* @param netWorkStateChageCallBack
*/
public void registCallBack(NetWorkStateChageCallBack netWorkStateChageCallBack){
changeCallBackList.add(netWorkStateChageCallBack);
}
public void unRegistCallBack(NetWorkStateChageCallBack netWorkStateChageCallBack){
changeCallBackList.remove(netWorkStateChageCallBack);
}
public void clearAllCallBack(){
changeCallBackList.clear();
}
public void netWorkChange(boolean netWorkConnected, boolean wifiConnected){
if (wifiConnected){
for (NetWorkStateChageCallBack temp:changeCallBackList){
temp.onWifiConnect();
temp.onNetConnect();
}
return;
}
if(!wifiConnected){
for (NetWorkStateChageCallBack temp:changeCallBackList){
temp.onWifiDisConnect();
}
}
if(netWorkConnected){
for (NetWorkStateChageCallBack temp:changeCallBackList){
temp.onNetConnect();
}
}else {
for (NetWorkStateChageCallBack temp:changeCallBackList){
temp.onNetDisConnect();
}
}
}
}
|
TypeScript
|
UTF-8
| 1,846
| 2.546875
| 3
|
[
"Apache-2.0"
] |
permissive
|
import { inject, InjectionKey, provide, reactive, Ref } from 'vue'
import {
createTemplateRefList,
useFocusGroup,
useRovingTabIndex,
useIdGenerator,
} from 'vue-aria-composables'
interface AccordionOptions {
multiple?: boolean
orientation?: 'horizontal' | 'vertical'
}
export type AccordionState = Record<string, boolean>
export interface AccordionContext {
genHeaderAttrs: typeof genHeaderAttrs
genPanelAttrs: typeof genPanelAttrs
generateId: (n: string) => string
set: (name: string, isActive: boolean) => void
state: AccordionState
}
export type AccordionKey = InjectionKey<AccordionContext>
export const accordionKey = Symbol('disclosure') as AccordionKey
const genHeaderAttrs = (id: string, expanded: boolean, disabled: boolean) => {
return {
'aria-expanded': expanded,
'aria-controls': id,
'aria-disabled': disabled || undefined,
}
}
const genPanelAttrs = (id: string) => {
return {
id: id,
}
}
export function useAccordion(options: AccordionOptions = {}) {
//Accordion State
const state = reactive<AccordionState>({})
const set = (name: string, isActive: boolean) => {
if (!options.multiple) {
Object.keys(state).forEach((key: string) => void (state[key] = false))
}
state[name] = isActive
}
// A11y: Keyboard Control
const { elements, refFn } = createTemplateRefList()
const focusGroup = useFocusGroup(elements)
const rovingTabIndex = useRovingTabIndex(elements, focusGroup.hasFocus, {
orientation: options.orientation,
})
const generateId = useIdGenerator('accordion')
provide(accordionKey, {
genHeaderAttrs,
generateId,
genPanelAttrs,
set,
state,
})
return {
refFn,
genHeaderAttrs,
genPanelAttrs,
...rovingTabIndex,
}
}
export function useAccordionInjection() {
return inject(accordionKey)
}
|
TypeScript
|
UTF-8
| 881
| 2.84375
| 3
|
[] |
no_license
|
import path from 'path'
import fs, { Dirent } from 'fs'
import logger from '../../utils/logger'
type DirTuple = [string, string]
export type ModuleBooter = () => Module | Promise<Module>
export interface Module {
name: string
close: () => Promise<void>
context: object
}
export type ModulesLoader = () => Promise<Module[]>
export const loadModules: ModulesLoader = async (): Promise<Module[]> => {
const modules: Module[] = []
const modulePaths = fs
.readdirSync(__dirname, { withFileTypes: true })
.filter((folder: Dirent): boolean => folder.isDirectory())
.map((folder: Dirent): DirTuple => [folder.name, path.join(__dirname, folder.name)])
for (const [moduleName, modulePath] of modulePaths) {
const { boot } = await import(modulePath)
modules.push(await boot())
logger.info(`Module -> ${moduleName} ... loaded`)
}
return modules
}
|
C
|
UTF-8
| 1,859
| 3.734375
| 4
|
[] |
no_license
|
//习题10-4 递归求简单交错幂级数的部分和(15 分)
//本题要求实现一个函数,计算下列简单交错幂级数的部分和:
//f(x,n)=x−x
//2
//+x
//3
//−x
//4
//+⋯+(−1)
//n−1
//x
//n
//
//函数接口定义:
//double fn( double x, int n );
//其中题目保证传入的n是正整数,并且输入输出都在双精度范围内。函数fn应返回上述级数的部分和。建议尝试用递归实现。
//裁判测试程序样例:
//#include <stdio.h>
//
//double fn( double x, int n );
//
//int main()
//{
// double x;
// int n;
//
// scanf("%lf %d", &x, &n);
// printf("%.2f\n", fn(x,n));
//
// return 0;
//}
//
///* 你的代码将被嵌在这里 */
//输入样例:
//0.5 12
//输出样例:
//0.33
#include <stdio.h>
#include <math.h>
double fn( double x, int n );
int main()
{
double x;
int n;
scanf("%lf %d", &x, &n);
printf("%.2f\n", fn(x,n));
return 0;
}
//这是老子写的可行的 但是没用递归
//double fn( double x, int n )
//{
//
// double sum;
// int k=-1,i=1;
// double a;
// for(;i<=n;i++)
// { a=pow(x,i);
// if(i%2==0)
// {
// a*=k;
// }
// sum+=a;
// }
// return sum;
//}
//递归
double fn( double x, int n )
{
if(n==1)return x;
else return x*(1-fn(x,n-1));
}
////下面是错的
//double fn( double x, int n )
//{
//
// int i,k=-1;
// double sum,a;
// if(n==0)
// sum=1;
// if(n==1)
// sum=x;
// if(n>1){
//
//
// i=n-1;
//
// a=fn(x,i)*x;
// if(n%2==0)
// {a*=k;}
// i--;
// sum+=a;
// }
//
//
//
// return sum;
//}
//
|
Java
|
UTF-8
| 372
| 1.890625
| 2
|
[] |
no_license
|
package ollitos.platform;
import ollitos.geom.IBRectangle;
import ollitos.geom.IBTransformHolder;
import ollitos.gui.basic.IBDrawable;
import ollitos.gui.event.IBEventSource;
public interface IBScreen extends IBEventSource, IBTransformHolder{
void refresh();
IBRectangle originalSize();
void setDrawable( IBDrawable d );
IBDrawable drawable();
IBCanvas canvas();
}
|
Java
|
UTF-8
| 3,081
| 2.140625
| 2
|
[] |
no_license
|
package com.example.kila.myapplication;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Context mContext = this;
ImageButton mTabCenter;
private ArrayList<Fragment> mFragments = new ArrayList<>();
private String[] mTitles = {
"首页",
"消息",
"",
"联系人",
"更多"
};
private int[] mIconUnselectIds = {
R.mipmap.tab_home_unselect,
R.mipmap.tab_speech_unselect,
R.mipmap.dot,
R.mipmap.tab_contact_unselect,
R.mipmap.tab_more_unselect
};
private int[] mIconSelectIds = {
R.mipmap.tab_home_select,
R.mipmap.tab_speech_select,
R.mipmap.dot,
R.mipmap.tab_contact_select,
R.mipmap.tab_more_select
};
private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
private CommonTabLayout mTabLayout_3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFragments.add(SimpleCardFragment.getInstance("Switch Fragment 0"));
mFragments.add(SimpleCardFragment.getInstance("Switch Fragment 1"));
mFragments.add(new Fragment());
mFragments.add(SimpleCardFragment.getInstance("Switch Fragment 3"));
mFragments.add(SimpleCardFragment.getInstance("Switch Fragment 4"));
for (int i = 0; i < mTitles.length; i++) {
mTabEntities.add(new TabEntity(mTitles[i], mIconSelectIds[i], mIconUnselectIds[i]));
}
/** with Fragments */
mTabLayout_3 = findViewById(R.id.tl_3);
mTabLayout_3.setSpecialTab(2);
mTabLayout_3.setTabData(mTabEntities, this, R.id.fl_change, mFragments);
mTabLayout_3.setOnTabSelectListener(new OnTabSelectListener() {
@Override
public void onTabSelect(int position) {
// 这里是FlycoTabLayout的tab点击事件
}
@Override
public void onTabReselect(int position) {
}
});
mTabLayout_3.setCurrentTab(3);
// 显示未读红点
mTabLayout_3.showDot(1);
// 中间凸起按钮部分
mTabCenter = findViewById(R.id.tab_main_center);
mTabCenter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(mContext, "中间凸起按钮点击了", Toast.LENGTH_SHORT).show();
}
});
}
}
|
Java
|
UTF-8
| 6,658
| 2.203125
| 2
|
[] |
no_license
|
package app;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.Optional;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import gestion.Product;
import gestion.ProductServiceRemote;
import gestion.loader;
import gestion.loaderServiceRemote;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert.AlertType;
import javafx.stage.Stage;
public class updateProductController implements Initializable {
@FXML
private TextField product1;
@FXML
private TextField price1;
@FXML
private TextField qua1;
@FXML
private Button cancelB;
@FXML
private Button addP;
@FXML
private Label addMessage;
@FXML
void updateProduct() {
Context context;
ProductServiceRemote dao = null;
try {
context = new InitialContext();
String jndiname="PiDEV-ear/PiDEV-ejb/ProductService!gestion.ProductServiceRemote";
dao = (ProductServiceRemote)context.lookup(jndiname);
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(product1.getText().isEmpty()||qua1.getText().isEmpty()||price1.getText().isEmpty()) {
addMessage.setText("Complete missing information");
return ;
}
Product p=new Product();
p=dao.findProductByName(product1.getText());
if(!isValideProduct(product1.getText())) {
addMessage.setText("not a valide product name ");
return;
}
else if(!isInteger(qua1.getText())) {
addMessage.setText("none valide quantity ");
return;
}
else if(!isFloat(price1.getText())) {
addMessage.setText("none valide price tag ");
return;
}
else if(!pro.getName().equals(product1.getText())) {
if (p.getName().equals(product1.getText())) {
addMessage.setText("Product existe already ");
return;
}
}
int t=Integer.parseInt(qua1.getText());
float f=Float.parseFloat(price1.getText());
if (t<0||f<0) {
addMessage.setText("The price and the quantity should be positive ");
return;
}
else {
pro.setName(product1.getText());
pro.setQuantity(qua1.getText());
pro.setPrice(price1.getText());
Date in = new Date();
LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault());
Date out = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());
pro.setUpdateDate(out);
dao.updateproduct(pro);
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Information Dialog");
alert.setHeaderText("Success");
alert.setContentText("Product update successfully");
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.OK){
Stage primaryStage=new Stage();
try {
Parent root = FXMLLoader.load(getClass().getResource("home.fxml"));
Scene scene= new Scene(root);
primaryStage.setScene(scene);
//primaryStage.initStyle(StageStyle.UNDECORATED);
//primaryStage.setResizable(false);
primaryStage.setTitle("Product List");
primaryStage.show();
closeScene();
} catch(Exception e) {
e.printStackTrace();
}
}
return;
}
}
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
private Product pro=new Product();
public void initialize(URL url,ResourceBundle rb) {
//initItems();
loadProduct();
product1.setText(pro.getName());
price1.setText(pro.getPrice());
qua1.setText(pro.getQuantity());
}
public void loadProduct() {
Context context;
loaderServiceRemote dao = null;
try {
context = new InitialContext();
String jndiname="PiDEV-ear/PiDEV-ejb/loaderService!gestion.loaderServiceRemote";
dao = (loaderServiceRemote)context.lookup(jndiname);
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
loader l=new loader();
l=dao.findLoder(1);
Context context2;
ProductServiceRemote dao2 = null;
try {
context2 = new InitialContext();
String jndiname="PiDEV-ear/PiDEV-ejb/ProductService!gestion.ProductServiceRemote";
dao2 = (ProductServiceRemote)context2.lookup(jndiname);
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pro=dao2.findProdById(l.getUpdateId());
}
public void initItems() {
product1.setText(pro.getName());
price1.setPromptText(pro.getPrice());
qua1.setPromptText(pro.getQuantity());
}
@FXML
void cancelButton(ActionEvent event) {
Stage primaryStage=new Stage();
try {
Parent root = FXMLLoader.load(getClass().getResource("home.fxml"));
Scene scene= new Scene(root);
primaryStage.setScene(scene);
//primaryStage.initStyle(StageStyle.UNDECORATED);
//primaryStage.setResizable(false);
primaryStage.setTitle("Product List");
primaryStage.show();
closeScene();
} catch(Exception e) {
e.printStackTrace();
}
}
private void closeScene(){
// get a handle to the stage
Stage stage = (Stage) addMessage.getScene().getWindow();
// do what you have to do
stage.close();
}
public static boolean isInteger(String str) {
try {
int i=Integer.parseInt(str);
} catch (Exception e) {
return false;
}
return true;
}
public static boolean isFloat(String str) {
try {
float f=Float.parseFloat(str);
}
catch (Exception e) {
return false;
}
return true;
}
public static boolean isValideProduct(String str) {
/*String specialChar= "/w";Character.
if (str.matches(specialChar)){
return false;
}
else {
return true;
}*/
Pattern pattern = Pattern.compile("[a-zA-Z0-9]*");
Matcher matcher = pattern.matcher(str);
if (!matcher.matches()) {
return false ;
} else {
return true;
}
}
}
|
Python
|
UTF-8
| 2,847
| 2.671875
| 3
|
[] |
no_license
|
import time
import datetime
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
# driver = webdriver.Chrome(executable_path='C:\\_teach\\Silenium\\chromedriver.exe')
s = Service('C:/_teach/Silenium/chromedriver.exe')
driver = webdriver.Chrome(service=s)
base_url = 'https://demoqa.com/date-picker'
# login_standard_user = "standard_user"
# login_password_user = "secret_sauce"
driver.get(base_url)
# driver.maximize_window()
# driver.find_element(By.XPATH, "//input[@id='datePickerMonthYearInput']").send_keys(Keys.CONTROL + "a")
# driver.find_element(By.XPATH, "//input[@id='datePickerMonthYearInput']").send_keys(Keys.DELETE)
# new_date = driver.find_element(By.XPATH, "//input[@id='datePickerMonthYearInput']")
# time.sleep(3)
# new_date.send_keys('12/01/2222')
# time.sleep(3)
# Выбор даты в календаре и затем сброс на текщую дату
locator = driver.find_element(By.XPATH, "//input[@id='datePickerMonthYearInput']")
locator.click()
print('Выбрали поле ввода даты')
time.sleep(3)
# tomorow_day = driver.find_element(By.XPATH, "//div[@aria-label='Choose Thursday, October 13th, 2022']")
# tomorow_day.click()
# print('Выбрали дату завтрешнего дня')
# time.sleep(3)
# # Тукщая дата
# locator = driver.find_element(By.XPATH, "//input[@id='datePickerMonthYearInput']")
# locator.click()
# print('Выбрали поле ввода даты')
# time.sleep(3)
# return_today = driver.find_element(By.XPATH, "//div[contains(@class, 'react-datepicker__day--today')]")
# return_today.click()
# print('Вернулись на текущий день')
now_date = datetime.datetime.utcnow().strftime("%d")
need_date = int(now_date) + 1
print(need_date)
locator = "//div[@aria-label='Choose Thursday, October " + str(need_date) + "th, 2022']"
tomorrow_day = driver.find_element(By.XPATH, locator)
tomorrow_day.click()
print(locator)
# action = ActionChains(driver)
# elements_button = driver.find_element(By.XPATH, "//button[@id='doubleClickBtn']")
# action.double_click(elements_button).perform()
# result_duble_click = driver.find_element(By.XPATH, "//p[@id='doubleClickMessage']").text
# assert result_duble_click == 'You have done a double click'
# print('Двжды кликнули')
# time.sleep(2)
#
# action = ActionChains(driver)
# elements_button = driver.find_element(By.XPATH, "//button[@id='rightClickBtn']")
# action.context_click(elements_button).perform()
# result_context_click = driver.find_element(By.XPATH, "//p[@id='rightClickMessage']").text
# assert result_context_click == 'You have done a right click'
# print('Правой кликнули')
# time.sleep(2)
|
C
|
UTF-8
| 2,637
| 3.421875
| 3
|
[] |
no_license
|
//
// Created by asus on 2017/10/16.
//
#ifndef DATASTRUCTURE_TSMATRIX_H
#define DATASTRUCTURE_TSMATRIX_H
#include <stdio.h>
#define MAX_SIZE 100
#define N 10
#define T int
typedef struct {
int row , col;
T elem;
}Triple;
typedef struct{
Triple data[MAX_SIZE];
int rowNum , colNum , len;
}TSMatrix;
void Init(TSMatrix *matrix){
matrix->len = matrix->colNum = matrix->rowNum = 0;
}
//build the TSMatrix
//the data[0] wont use
int build(TSMatrix *matrix , T a[N][N] , int row , int col){
matrix->rowNum = row;
matrix->colNum = col;
if(a == NULL || row <= 0 || col <= 0 ){
return 0;
}
int i , j;
for( i = 0 ; i < row ; i ++){
for(j = 0 ; j < col ; j ++){
if(a[i][j] != 0){
matrix->len ++;
matrix->data[matrix->len].elem = a[i][j];
matrix->data[matrix->len].row = i + 1;
matrix->data[matrix->len].col = j + 1;
}
}
}
return 1;
}
//transpose the matrix
int Transpose(TSMatrix from , TSMatrix *to){
int position[MAX_SIZE] = {0};
int i;
to->colNum = from.rowNum;
to->rowNum = from.colNum;
to->len = from.len;
for(i = 1 ; i <= from.len ; i ++){
position[from.data[i].col + 1] ++;
}
position[1] = 1;
for(i = 2 ; i <= from.len ; i ++){
position[i] += position[i - 1];
}
int col , tempPosition;
for(i = 1 ; i <=from.len ; i ++){
col = from.data[i].col;
tempPosition = position[col];
to->data[tempPosition].elem = from.data[i].elem;
to->data[tempPosition].col = from.data[i].row;
to->data[tempPosition].row = from.data[i].col;
position[col] ++;
}
return 1;
}
void PrintMatrix(TSMatrix matrix){
int i , j;
int counter = 1;
for(i = 0 ; i < matrix.rowNum ; i ++){
for( j = 0 ; j < matrix.colNum ; j ++){
if(i + 1 == matrix.data[counter].row && j + 1== matrix.data[counter].col ){
printf("%d " , matrix.data[counter].elem);
counter ++;
} else{
printf("0 ");
}
}
printf("\n");
}
}
int main(){
TSMatrix matrix;
Init(&matrix);
int a[N][N];
int row , col;
scanf("%d%d" , &row , &col);
int i , j;
for(i = 0 ; i < row ; i ++){
for(j = 0 ; j < col ; j ++){
scanf("%d" , &a[i][j]);
}
}
build(&matrix , a , row , col);
TSMatrix toMatrix;
Init(&toMatrix);
Transpose(matrix ,&toMatrix );
PrintMatrix(toMatrix);
return 0;
}
#endif //DATASTRUCTURE_TSMATRIX_H
|
Markdown
|
UTF-8
| 1,250
| 3.8125
| 4
|
[
"MIT"
] |
permissive
|
# Bubble Sort

## 시간복잡도
( n - 1 ) + ( n - 2 ) + ... + 2 + 1 ---------> n ( n - 1 ) / 2
**O(n^2)**
느린편이지만 구현이 간단해서 자주 쓰인다고 한다.
## Code
```java
public class BubbleSort {
private static int[] arr = {5, 6, 2, 8, 7, 23, 4, 1};
public static void main(String[] args) throws IOException{
bubbleSort(arr, arr.length);
for(int i=0; i<arr.length; i++) {
System.out.println(arr[i]);
}
}
private static void bubbleSort(int [] arr, int n) {
//바꿔치기에 사용할 임시 변수
int tmp;
//위 그림보면 뒷자리부터 하나씩 완성되는 것을 바깥반복문으로(pass i)
for(int i=0; i<n; i++) {
//n-i-1 에 주목하기 (두개씩 비교하니 -1이 필요)
//아니면 j를 1부터 시작해서 n-i 까지로 바꾸고
//arr[j]와 arr[j-1]을 비교할 수도 있다.
for(int j=0; j < n - i - 1; j++) {
//뒤 숫자가 더 작으면 교환
if(arr[j] > arr[j+1]) {
tmp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = tmp;
}
}
}
}
}
```
|
Rust
|
UTF-8
| 908
| 2.78125
| 3
|
[] |
no_license
|
/*
* @Author: otae
* @Date: 2017-07-20 21:05:47
* @Last Modified by: otae
* @Last Modified time: 2017-07-25 01:32:28
*/
use color::*;
use float3::*;
pub struct FrameBuffer {
pub frame: Vec<Vec<char>>,
pub depth: Vec<Vec<f32>>,
pub colors: Vec<Vec<Color>>
}
impl FrameBuffer {
pub fn allocate(&mut self, width: i32, height: i32) {
for i in 0 .. height {
let mut line: Vec<char> = Vec::new();
let mut dline: Vec<f32> = Vec::new();
let mut cline: Vec<Color> = Vec::new();
for j in 0 .. width {
line.push('#');
dline.push(1000.0);
cline.push(Color {color: 7});
}
self.colors.push(cline);
self.depth.push(dline);
self.frame.push(line);
}
}
pub fn clear(&mut self) {
for j in 0 .. self.frame.len() {
for i in 0 .. self.frame[0].len () {
self.frame[i][j] = ' ';
self.colors[i][j] = Color{color: 5};
self.depth[i][j] = 1000.0;
}
}
}
}
|
Java
|
UTF-8
| 866
| 3.71875
| 4
|
[] |
no_license
|
public class IsBST {
Node root;
Node prev;
boolean isBST() {
prev = null;
return isBST(root);
}
boolean isBST(Node node) {
if (node != null) {
if (!isBST(node.left)) {
return false;
}
if (prev != null && node.key <= prev.key)
return false;
prev = node;
return isBST(node.right);
}
return true;
}
public static void main(String[] args) {
IsBST tree = new IsBST();
tree.root = new Node(4);
tree.root.left = new Node(2);
tree.root.right = new Node(5);
tree.root.left.left = new Node(1);
tree.root.left.right = new Node(3);
if (tree.isBST())
System.out.println("IS BST");
else
System.out.println("Not a BST");
}
}
|
Markdown
|
UTF-8
| 795
| 2.875
| 3
|
[] |
no_license
|
---
title: "Adding Audio Output to an Alexa Skill"
tags: [aws]
excerpt_separator: <!--more-->
---
It's pretty easy to add audio to an existing Alexa skill. The biggest trick is probably getting the audio converted into an Alexa-Friendly format. Here's how I did this:
<!--more-->
1. Exported my audio from Adobe Premier (or whatever you're using to build your audio files)
2. Used ffmpeg to convert the audio to the right format:
```
ffmpeg -i my.mp3 -ac 2 -codec:a libmp3lame -b:a 48k -ar 16000 my-converted.mp3
```
1. Upload my new converted audio into an s3 bucket
### Adding Audio to an Alexa Skill
Assuming you already have an existing skill, you can use this simple SSML to refer to your file:
```
<audio src="https://s3-us-west-2.amazonaws.com/yourbucketname/my_converted.mp3" />
```
|
C++
|
UTF-8
| 2,242
| 3.765625
| 4
|
[] |
no_license
|
#include <iostream>
using namespace std;
int main(){
//Initializing
char choice;
char i, j, record=0, totalrecord;
int id[record];
string name[record];
int price[record];
bool back=true;
string none;
//Menu
while(back=true){
cout<<"*******************************"<<endl;
cout<<"[A] Add Record"<<endl;
cout<<"[V] View Record"<<endl;
cout<<"[E] Edit Record"<<endl;
cout<<"[D] Delete Record"<<endl;
cout<<"[L] View All Record"<<endl;
cout<<"Enter your choice and press return: "<<endl;
cin >> choice;
switch (choice){
//Add Record
case 'a':
case 'A':
record++;
cout<<"Input ID: ";
cin>>id[record];
cout<<"Input Name: ";
cin>>name[record];
cout<<"Input Price: ";
cin>>price[record];
break;
//View Record
case 'v':
case 'V':
cout<<"Enter ID you wish to view: ";
cin>>id[record];
cout<<"ID Name Price"<<endl;
cout<<id[record]<<" "<<name[record]<<" "<<price[record]<<endl;
break;
//Edit Record
case 'e':
case 'E':
cout << "Enter ID you wish to edit: ";
cin>>id[record];
cout<<"Input NEW name: ";
cin>>name[record];
cout<<"Input NEW price: ";
cin>>price[record];
break;
//Delete Record
case 'd':
case 'D':
cout << "Enter ID you wish to delete";
cin>>id[record];
id[record]=0;
name[record]=none;
price[record]=0;
break;
//View All Records
case 'l':
case 'L':
cout<<"ID Name Price"<<endl;
for(i=1; i<totalrecord+1; i++){
cout<<id[i]<<" "<<name[i]<<" "<<price[i]<<endl;
}
break;
//Exit Program if invalid input
default:
back=false;
break;
}
}
return 0;
}
|
Java
|
UTF-8
| 6,321
| 1.914063
| 2
|
[] |
no_license
|
package com.gon.test;
import com.gon.RuntimeTaskHelper;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.HistoricTaskInstanceEntity;
import org.activiti.engine.management.TablePage;
import org.activiti.engine.task.IdentityLink;
import org.activiti.engine.task.Task;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.transaction.TransactionConfiguration;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.*;
/**
* 测试流程引擎
*
* @author yuanyp
*
*/
@TransactionConfiguration(defaultRollback=false)
@ContextConfiguration(locations = { "classpath:/spring/applicationContext*.xml" })
public class ProcessEngineTest extends
AbstractTransactionalJUnit4SpringContextTests {
static private Logger log = Logger.getLogger(ProcessEngineTest.class);
@Autowired
private ProcessEngineServer pes;
@Autowired
private RuntimeTaskHelper runtimeTaskHelper;
private String processName = "WF_QB";//"WF_Test_title";
/**
* 测试 testa
*/
//@Test
public void testSubmitTask() {
long s = System.currentTimeMillis();
String userid = "1001";
List<org.activiti.engine.task.Task> list = pes.getProcessInstanceTask("172509");
System.out.printf("用户任务列表>>" + list);
List<String> assList = new ArrayList<String>();
for(int i=0,j=1;i<j;i++){
assList.add("0"+ i + "");
}
Map<String, Object> assMap = new HashMap<String, Object>();
assMap.put("node7_users", assList);
// assMap.put("mulitiInstance", new MulitiInstanceCompleteTask());
pes.submitTask(list.get(0).getId(), assMap);
long e = System.currentTimeMillis();
System.out.printf("耗时>" + (e-s) + "\n");
}
//@Test
public void testSubmitTaskItem() {
long s = System.currentTimeMillis();
Map<String, Object> assMap = new HashMap<String, Object>();
// assMap.put("node16_users", Arrays.asList("node16_1"));
// assMap.put("gateway_node13", "node22");
pes.submitTask("222536", assMap);
long e = System.currentTimeMillis();
System.out.printf("耗时>" + (e-s) + "\n");
}
//@Test
public void testDeploy() {
try {
InputStream is = ClassLoader.getSystemResourceAsStream("process/test_003.bpmn");
System.out.printf("is》》:" + is);
System.out.printf("部署》》:" + pes.deploy(is));
} catch (Exception e) {
e.printStackTrace();
}
}
//@Test
public void testStart(){
List<String> assList = new ArrayList<String>();
assList.add("1001");
Map<String, Object> assMap = new HashMap<String, Object>();
assMap.put("node4_users", assList);
System.out.println("启动流程》》:"+pes.startProcess(processName,assMap));
}
/**
* 测试流程 多部门会签时,自循环
*/
//@Test
public void testZLC(){
List<String> assList = new ArrayList<String>();
assList.add("1001");
Map<String, Object> assMap = new HashMap<String, Object>();
assMap.put("node4_users", assList);
String processInsId = pes.startProcess(processName,assMap);
System.out.println("启动流程》》流程实例ID:"+processInsId);
List<Task> list = pes.getProcessInstanceTask(processInsId);//查询当前流程实例的TASK
System.out.printf("用户任务列表>>" + list);
assMap.clear();
assMap.put("node5_users", assList);
pes.submitTask(list.get(0).getId(), assMap);
list = pes.getProcessInstanceTask(processInsId);//查询当前流程实例的TASK
assMap.clear();
assList.clear();
assList.add("001");
assList.add("002");
assMap.put("gateway_node13", "node20");
assMap.put("node20_users", assList);
pes.submitTask(list.get(0).getId(), assMap);//完成任务进入子流程
//001用户发送给 001_1 001_2
list = pes.getProcessInstanceTask(processInsId);//查询当前流程实例的TASK
System.out.printf("用户任务列表>>" + list);
for(Task task : list){
List<IdentityLink> identityLinkList = pes.taskService.getIdentityLinksForTask(task.getId());
System.out.printf("任务ID>>" + task.getId() + "的候选人:" + identityLinkList);
System.out.printf("认领任务,任务ID>>" + task.getId() + ",候选人:" + identityLinkList.get(0).getUserId());
pes.taskService.claim(task.getId(),identityLinkList.get(0).getUserId());
}
List<Task> tasks = pes.getAssignTaskList("001",processName);
assMap.clear();
assList.clear();
assList.add("001_1");
assList.add("001_2");
assMap.put("node21_users", assList);
pes.submitTask(tasks.get(0).getId(), assMap);
//002用户发送给 002_1 002_2
tasks = pes.getAssignTaskList("002",processName);
assMap.clear();
assList.clear();
assList.add("002_1");
assList.add("002_2");
assList.add("002_3");
assMap.put("node21_users", assList);
pes.submitTask(tasks.get(0).getId(), assMap);
}
/**
* 注意需要先加签之后再提交当前任务
*/
@Test
public void testAddTask(){
// runtimeTaskHelper.addSign("105028","03");
CounterSignAddCmd cmd = new CounterSignAddCmd("232608","001_1_1");
String newTaskId = runtimeTaskHelper.getProcessEngine().getManagementService().executeCommand(cmd);
//UpdateHiTaskCmd updateHiTaskCmd = new UpdateHiTaskCmd(newTaskId);
// runtimeTaskHelper.getProcessEngine().getManagementService().executeCommand(updateHiTaskCmd);
// historicTaskInstance.setProcessDefinitionId(t.getProcessDefinitionId());
// historicTaskInstance.setExecutionId(newExecutionEntity.getId());
// historicTaskInstance.setProcessInstanceId(t.getProcessInstanceId());
// commandContext.getDbSqlSession().update(historicTaskInstance);
// cmd = new CounterSignAddCmd("185021","001_2_2");
// runtimeTaskHelper.getProcessEngine().getManagementService().executeCommand(cmd);
// pes.submitTask("247510", null);
}
}
|
Java
|
UTF-8
| 2,301
| 1.992188
| 2
|
[] |
no_license
|
package com.helfarre.BankApi.Controllers;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.helfarre.BankApi.Entities.Agence;
import com.helfarre.BankApi.Entities.compte;
import com.helfarre.BankApi.Entities.historiqueadmin;
import com.helfarre.BankApi.Repositories.BanquierJpaRepository;
import com.helfarre.BankApi.Repositories.chequeRepos;
import com.helfarre.BankApi.Repositories.compteRepository;
import com.helfarre.BankApi.Repositories.epargneRepository;
import com.helfarre.BankApi.Services.histoimpl;
@RestController
@RequestMapping("/histo")
public class historiqueController {
@Autowired
private histoimpl histserv;
@Autowired
private BanquierJpaRepository bgrepo;
@Autowired
private compteRepository compterepo;
@Autowired
private chequeRepos chequerepo;
@Autowired
private epargneRepository epargnerepo;
@GetMapping("/{id}")
public List<historiqueadmin>getbyagence(@PathVariable long id){
return histserv.getallbyagence(id);
}
@GetMapping("/infos/{id}")
public List<Double>getinfo(@PathVariable long id){
List<Double>test=new ArrayList<Double>();
test.add( (double) bgrepo.findByAgence_Id(id).size());
Optional<List<compte>> ttt=compterepo.findByLagence_Id(id);
int suspendu=0,ouvert=0,cheque=0,epargne=0;
if(ttt.isPresent()) {
for(int i=0;i<ttt.get().size();i++) {
if(ttt.get().get(i).getIs_suspended()==false) {
ouvert++;
if(ttt.get().get(i).getTypecompte().equals("cheque")) {cheque++;}
else {if(ttt.get().get(i).getTypecompte().equals("epargne"))epargne++;}
}
else {
suspendu++;
}
}
}
test.add( (double) ouvert);
test.add( (double) suspendu);
test.add( (double) cheque);
test.add( (double) epargne);
return test;
}
}
|
Java
|
UTF-8
| 3,940
| 2.28125
| 2
|
[] |
no_license
|
package dai.server.servlets;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.util.Vector;
import dai.shared.cmnSvcs.Logger;
import dai.shared.cmnSvcs.SessionMetaData;
import dai.shared.cmnSvcs.csSecurity;
import dai.shared.csAdapters.csDBAdapter;
import dai.shared.csAdapters.csDBAdapterFactory;
import dai.shared.csAdapters.csSessionAdapter;
import dai.shared.csAdapters.csSessionAdapterFactory;
public class XMLRptServlet_t
{
csDBAdapterFactory _dbAdapterFactory;
csSessionAdapterFactory _sessionAdapterFactory;
csDBAdapter _dbAdapter;
csSessionAdapter _sessionAdapter;
SessionMetaData _sessionMeta;
csSecurity _security;
Logger _logger;
ParseXMLRptData _xmlRptData;
public static void main (String argv [])
{
new XMLRptServlet_t();
}
//Initialize global variables
public XMLRptServlet_t()
{
System.out.println("Started Init");
_dbAdapterFactory = csDBAdapterFactory.getInstance();
_sessionAdapterFactory = csSessionAdapterFactory.getInstance();
_dbAdapter = _dbAdapterFactory.getDBAdapter();
_sessionAdapter = _sessionAdapterFactory.getSessionAdapter();
_sessionMeta = SessionMetaData.getInstance();
_logger = Logger.getInstance();
init();
}
//Process the HTTP Post request
public void init() {
//valid eCorp user Id
String userId = "";
try {
userId = "STEVE";
} catch (Exception e) {
e.printStackTrace();
}
//valid eCorp user password
String passwd = "";
try {
passwd = "fur";
} catch (Exception e) {
e.printStackTrace();
}
//The SQL Statement
String rptName = "";
try {
rptName = "cashReceipts.xml";
} catch (Exception e) {
e.printStackTrace();
}
//Validate the user's login.
boolean userValid = validateSecurity(userId, passwd);
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintWriter out = new PrintWriter (os);
out.println("<html>");
out.println("<head><title>Dynamic SQL Results</title>");
out.println("<H1>Dynamic SQL Results</H1>");
out.println("</head>");
//Generate the content.
if (userValid) {
// _xmlRptData = new ParseXMLRptData(rptName);
out.println(createDataTable(_xmlRptData.getSQLStmt(), _xmlRptData.getColHeadings()));
} else {
out.println(generateLoginErrorText());
}
out.println("<body>");
out.println("</body></html>");
out.close();
}
private boolean validateSecurity(String uid, String pwd) {
try {
_security = _sessionAdapter.connect(null, //not used at this time
uid,
pwd);
} catch (Exception e) {
return false;
}
_sessionMeta.setClientServerSecurity(_security);
return true;
}
private String createDataTable(String sqlStmt, String[] tableHeadings)
{
Vector recs = null;
String tableData = "";
try {
System.out.println(sqlStmt);
recs = _dbAdapter.getDynamicSQLResults(_sessionMeta.getClientServerSecurity(),
sqlStmt);
HTMLGenerator gen = new HTMLGenerator();
tableData = gen.createTable(recs, _xmlRptData);
} catch (Exception e) {
e.printStackTrace();
return e.getLocalizedMessage();
}
return tableData;
}
private String generateLoginErrorText() {
String ret = "<p>" +
"Unable to Login Please Check User Id and Password." +
"<p><I>(Note: User Id and Password are Case sensitive)<I>";
return ret;
}
}
|
Java
|
UTF-8
| 333
| 1.71875
| 2
|
[] |
no_license
|
package com.core.service;
import java.util.List;
import com.core.mongo.data.entity.User;
public interface UserService {
public User findUserData(String id);
public void resetUserData(User user);
public User saveUserData(User user, List<String> emailList);
public User validateUserData(User user);
}
|
Java
|
UTF-8
| 3,028
| 1.882813
| 2
|
[] |
no_license
|
package com.sinitek.sirm.org.web;
import com.sinitek.sirm.common.CommonServiceFactory;
import com.sinitek.sirm.common.support.LocalSetting;
import com.sinitek.sirm.common.sysmenu.service.ISysMenuService;
import com.sinitek.sirm.common.utils.NumberTool;
import com.sinitek.sirm.common.utils.StringUtil;
import com.sinitek.sirm.common.utils.TimeUtil;
import com.sinitek.sirm.common.web.SirmAction;
import com.sinitek.sirm.common.web.tag.PageLoadContext;
import com.sinitek.sirm.org.busin.service.OrgServiceFactory;
import com.sinitek.spirit.web.sysmenu.ISysMenu;
import com.sinitek.spirit.webcontrol.table.ITableAware;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
/**
* Created by IntelliJ IDEA.
* User: 刘钢
* Date: 14-3-10
* Time: 下午2:25
* To change this template use File | Settings | File Templates.
*/
public class MenuAccessDetailAction extends SirmAction implements ITableAware {
public static void loadpage(PageLoadContext context) throws Exception {
HttpServletRequest request = context.getRequest();
int menuid = NumberTool.safeToInteger(request.getParameter("menuid"), 0);
ISysMenuService sysMenuService = CommonServiceFactory.getSysMenuService();
ISysMenu sysMenu = sysMenuService.getSysMenuById(menuid);
if (null != sysMenu) {
request.setAttribute("menuname", sysMenu.getName());
}
int menucnt = NumberTool.safeToInteger(request.getParameter("menucnt"), 0);
request.setAttribute("menucnt", menucnt);
}
@Override
public Object getResult(Map<String, String> stringMap, HttpServletRequest request) throws Exception {
Map parammap = new HashMap();
String contextpath = LocalSetting.getSetting("app.js.contextpath", "");
String timestart = StringUtil.safeToString(stringMap.get("timestart"), "");
String timeend = StringUtil.safeToString(stringMap.get("timeend"), "");
String username = StringUtil.safeToString(stringMap.get("username"), "");
parammap.put("username", username);
if (!contextpath.isEmpty()) {
parammap.put("contextpath", contextpath + "/");
}
String menuid = StringUtil.safeToString(stringMap.get("menuid"), "");
if (!menuid.isEmpty()) {
parammap.put("menuid", NumberTool.safeToInteger(menuid, 0));
}
if (!timestart.isEmpty()) {
parammap.put("timestart", TimeUtil.formatDate(timestart + " 00:00:00", "yyyy-MM-dd HH:mm:ss"));
}
if (!timeend.isEmpty()) {
parammap.put("timeend", TimeUtil.formatDate(timeend + " 23:59:59", "yyyy-MM-dd HH:mm:ss"));
}
return OrgServiceFactory.getStatisticsService().menuAccessDetail(parammap);
}
@Override
public String setDefaultOrderBy(Map<String, String> stringMap, HttpServletRequest request) throws Exception {
return "cnt desc"; //To change body of implemented methods use File | Settings | File Templates.
}
}
|
SQL
|
UTF-8
| 1,202
| 3.5625
| 4
|
[] |
no_license
|
{{
config(
materialized = 'incremental',
cluster_by = 'user_id',
partition_by = {'field': 'created_at', 'data_type': 'timestamp'}
)
}}
WITH source_tbl AS (
SELECT
id AS user_id
, postcode,
, created_at,
, updated_at,
, loader_ingestion_time
FROM {{ checkout('users_extract') }}
{% if is_incremental() %}
WHERE loader_ingestion_time > (SELECT MAX(loader_ingestion_time) FROM {{ this }}) -- This incremental statement will load new user data daily as the loader ingestion time should update each time the extract process runs at midnight.
{% endif %}
)
, modified_source AS (
SELECT
{{
surrogate_key([
'source_tbl.user_id',
'source_tbl.updated_at'
])
}} AS id
, source_tbl.user_id AS user_id
, source_tbl.postcode AS postcode
, source_tbl.created_at AS created_at
, source_tbl.updated_at AS updated_at
, source_tbl.loader_ingestion_time AS loader_ingestion_time
FROM source_tbl
)
SELECT *
FROM modified_source
|
Java
|
GB18030
| 4,672
| 2.640625
| 3
|
[] |
no_license
|
package com.sl.v0.buglocation;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
public class BaseFunction {
/*ȡָĿ¼гCorpusļ*/
public static void CheckFileName(String path,List<File> files) {
File file = new File(path);
File[] tempList = file.listFiles();
for (int i = 0; i < tempList.length; i++) {
if (tempList[i].isDirectory()&&!(tempList[i].getName().equals("Corpus"))) {
// System.out.println("ļУ" + tempList[i]);
files.add(tempList[i]);
}
}
}
/*ȡĿ¼ļ*/
public static void GetFiles(String fileDir,List<File> fileList) {
File file = new File(fileDir);
File[] files = file.listFiles();// ȡĿ¼µļļ
if (files == null) {// Ŀ¼Ϊգֱ˳
return;
}
// Ŀ¼µļ
for (File f : files) {
if (f.isFile()) {
fileList.add(f);
} else if (f.isDirectory()) {
//System.out.println(f.getAbsolutePath());
GetFiles(f.getAbsolutePath(),fileList);
}
}
// for (File f1 : fileList) {
// System.out.println(f1.getName());
// }
}
public static ArrayList<String> TextWithFilter(String text)
{
ArrayList<String> re=new ArrayList<String>();
text=text.toLowerCase();/*ȫתСд*/
/*TODO:ȥStopWords.txtеĴ*/
//System.out.println(Thread.currentThread().getContextClassLoader().getResource("/").getPath());
//ArrayList<String> stopwords=ReadAllLines("E://StopWords.txt");
// String[] tmp1=text.split(" ");
// for(int i=0;i<tmp1.length;i++){
// text=tmp1[i];
// String[] tmp2=text.split("(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z](?:s[a-z]|[abcdefghijklmnopqrtuvwxyz]))");
// for(int j=0;j<tmp2.length;j++){
// text=tmp2[j];
// //System.out.println(text);
String[] cur=text.split("[^a-zA-Z]+");
for(int k=0;k<cur.length;k++){
//if(!re.contains(word))/*ȥ*/
//if(!stopwords.contains(cur[k]))/*stopwords.txt*/
re.add(cur[k]);
}
// }
// }
return re;
}
/*Stringʽȡļ*/
public static String ReadAllText(String filepath){
StringBuilder sb = new StringBuilder();
String s ="";
BufferedReader br;
try {
br = new BufferedReader(new FileReader(filepath));
while( (s = br.readLine()) != null) {
sb.append(s + "\n");
}
br.close();
} catch (FileNotFoundException e) {
// TODO Զɵ catch
e.printStackTrace();
} catch (IOException e) {
// TODO Զɵ catch
e.printStackTrace();
}
String str = sb.toString();
return str;
}
/*дļ*/
public static void WriteAllLines(String filePath,ArrayList<String> content){
try {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(filePath)),"UTF-8"));
for (int i=0;i<content.size();i++) {
bw.write(content.get(i));
bw.newLine();
}
bw.close();
} catch (Exception e) {
System.err.println("write errors :" + e);
}
}
/*жȡļ 洢*/
public static ArrayList<String> ReadAllLines(String filePath){
FileReader fileReader;
try {
fileReader = new FileReader(filePath);
BufferedReader bufferedReader =new BufferedReader(fileReader);
StringBuilder stringBuilder =new StringBuilder();
ArrayList<String> strings =new ArrayList<>();
String str=null;
while ((str=bufferedReader.readLine())!=null) {
//System.out.println(str);
if (str.trim().length()>2) {
strings.add(str);
}
// System.out.println(strings.size());
// for (int i = 0; i < strings.size(); i++) {
// System.out.println(strings.get(i));
// }
}
fileReader.close();
bufferedReader.close();
return strings;
} catch (FileNotFoundException e) {
// TODO Զɵ catch
e.printStackTrace();
} catch (IOException e) {
// TODO Զɵ catch
e.printStackTrace();
}
return null;
}
}
|
Ruby
|
UTF-8
| 120
| 3.296875
| 3
|
[] |
no_license
|
# n = 1
# if !n.zero?
# puts 'Not zero.'
# end
n = 1
unless n.zero?
puts 'Not zero'
else
puts 'This is zero.'
end
|
Shell
|
UTF-8
| 2,132
| 3.46875
| 3
|
[
"MIT"
] |
permissive
|
#!/bin/bash -e
if [ "$#" -ne 3 ]; then
cat <<-ENDOFMESSAGE
Please specify the base result file and the result file, as well as the output file as arguments.
Usage: ./parse.sh <base result file> <result file> <output file>
ENDOFMESSAGE
exit
fi
mkdir -p $(dirname $3)
header="machine,limits,benchmark,base_result,lower_is_better,result"
if [ ! -f "$3" ] || ! grep -q "$header" "$3"; then
echo "$header" | tee "$3"
fi
bn=`basename "$2" ".prof"`
machine=`echo "$bn" | cut -d _ -f 2`
limits=`echo "$bn" | cut -d _ -f 1`
test_list=('BuiltinFunctionCalls' 'BuiltinMethodLookup' 'CompareFloats' 'CompareFloatsIntegers'
'CompareIntegers' 'CompareInternedStrings' 'CompareLongs' 'CompareStrings' 'CompareUnicode'
'ComplexPythonFunctionCalls' 'ConcatStrings' 'ConcatUnicode' 'CreateInstances'
'CreateNewInstances' 'CreateStringsWithConcat' 'CreateUnicodeWithConcat' 'DictCreation'
'DictWithFloatKeys' 'DictWithIntegerKeys' 'DictWithStringKeys' 'ForLoops' 'IfThenElse'
'ListSlicing' 'NestedForLoops' 'NestedListComprehensions' 'NormalClassAttribute'
'NormalInstanceAttribute' 'PythonFunctionCalls' 'PythonMethodCalls' 'Recursion'
'SecondImport' 'SecondPackageImport' 'SecondSubmoduleImport' 'SimpleComplexArithmetic'
'SimpleDictManipulation' 'SimpleFloatArithmetic' 'SimpleIntFloatArithmetic'
'SimpleIntegerArithmetic' 'SimpleListComprehensions' 'SimpleListManipulation'
'SimpleLongArithmetic' 'SmallLists' 'SmallTuples' 'SpecialClassAttribute'
'SpecialInstanceAttribute' 'StringMappings' 'StringPredicates' 'StringSlicing' 'TryExcept'
'TryFinally' 'TryRaiseExcept' 'TupleSlicing' 'UnicodeMappings' 'UnicodePredicates'
'UnicodeProperties' 'UnicodeSlicing' 'WithFinally' 'WithRaiseExcept')
for test in "${test_list[@]}"; do
pattern="^\s*$test:.+?ms\s+\K[\d\.]+"
base_res=`grep -oP "$pattern" "$1"`
res=`grep -oP "$pattern" "$2"`
test_name=`echo "$test" | sed "s/[A-Z]/_\l&/g"`
echo "$machine,$limits,pybench$test_name,$base_res,True,$res" | tee -a "$3"
done
|
Java
|
UTF-8
| 398
| 1.929688
| 2
|
[] |
no_license
|
package DAO;
import java.util.ArrayList;
import Bean.BeanAlumno;
import util.ToolLista;
public interface DaoAlumno
{
public void ingresar (BeanAlumno al) throws Exception;
public void modificar (BeanAlumno al) throws Exception;
public void eliminar(BeanAlumno al) throws Exception;
public ArrayList<BeanAlumno> lista() throws Exception;
public ToolLista listarUsuarios() throws Exception;
}
|
Markdown
|
UTF-8
| 2,363
| 2.921875
| 3
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
---
id: hellomilvus.md
title: Hello Milvus
---
# Run Milvus using Python
After the Milvus server boots successfully, test the platform using our Python sample code.
1. Install pymilvus_orm and its dependencies:
```
pip install pymilvus-orm==2.0.0rc1
```
<div class="alert note">
Python version 3.6 or higher is required. View <a href="https://wiki.python.org/moin/BeginnersGuide/Download">Python documentation</a> for information about installing the correct version for your system.
</div>
2. Download sample code **hello_milvus.py**:
```
$ wget https://github.com/milvus-io/pymilvus-orm/blob/main/examples/hello_pymilvus_orm.py
```
3. Scan **hello_milvus.py**. This sample code does the following:
- Imports the pymilvus package:
```
import pymilvus_orm
```
- Connects to the Milvus server:
```
pymilvus_orm.connections.connect()
```
- Creates a collection:
```
from pymilvus_orm import schema, DataType, Collection
dim = 128
default_fields = [
schema.FieldSchema(name="count", dtype=DataType.INT64, is_primary=False),
schema.FieldSchema(name="score", dtype=DataType.FLOAT),
schema.FieldSchema(name="float_vector", dtype=DataType.FLOAT_VECTOR, dim=dim)
]
default_schema = schema.CollectionSchema(fields=default_fields, description="test collection")
collection = Collection(name="hello_milvus", data=None, schema=default_schema)
```
- Inserts vectors in the new collection:
```
import random
nb = 3000
vectors = [[random.random() for _ in range(dim)] for _ in range(nb)]
collection.insert([[i for i in range(nb)], [float(i) for i in range(nb)], vectors])
```
- Builds an IVF_FLAT index and loads the collection to memory:
```
default_index = {"index_type": "IVF_FLAT", "params": {"nlist": 128}, "metric_type": "L2"}
collection.create_index(field_name="float_vector", index_params=default_index)
collection.load()
```
- Conducts a vector similarity search:
```
topK = 5
search_params = {"metric_type": "L2", "params": {"nprobe": 10}}
res = collection.search(vectors[-2:], "float_vector", search_params, topK, "count > 100")
```
4. Run **hello_milvus.py**:
```
$ python3 hello_pymilvus_orm.py
```
*The returned results and query latency show as follows:*

<br/>
*Congratulations! You have successfully booted Milvus Standalone and run your first vector similarity search.*
|
Java
|
UTF-8
| 133
| 1.632813
| 2
|
[] |
no_license
|
package com.inter;
/**
* Created by Administrator on 2017/12/13.
*/
public interface RmiTest {
public String test(String s);
}
|
PHP
|
UTF-8
| 3,681
| 2.984375
| 3
|
[] |
no_license
|
<?php
include('utils/databaseSetup.php');
// This page won't work without a suitable PHP email setup
function genPassword($len)
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $len; $i++)
{
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
function addUser($email, $name, $target)
{
global $mysqli;
$pw = genPassword(8);
$hashPass = md5($pw);
$query = "insert into user values('" . $email . "','" . $name . "','" . $hashPass . "'," . $target . ")";
$res = $mysqli->query($query);
if($res)
{
mail($email, 'Thanks for Joining!', 'Thanks for joining the diet tracker, '
. 'your goal is to eat less than ' . $target . ' calories per day, good luck!'
. 'Your password is ' . $pw . ' and can be changed after logging in.'
. 'Please visit http://[host]/login.php to get started.');
return true;
}
return false;
}
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if(isset($_POST['email']))
{
$email = $_POST['email'];
if(isset($_POST['name']))
{
$name = $_POST['name'];
if(isset($_POST['target']) && $_POST['target'] != "")
$target = $_POST['target'];
else
$target = '2000';
$errorMessage = '';
if(addUser($email, $name, $target))
{
header("Location: login.php");
}
else
{
$errorMessage = 'A user with that email address already exists';
}
}
else
{
$errorMessage = 'Please enter a name';
}
}
else
{
$errorMessage = 'Please enter an email address';
}
}
else
{
$errorMessage = '';
}
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=0.9">
<title>Diet Tracker Registration</title>
<link rel="stylesheet" href="lib/bootstrap-3.2.0-dist/css/bootstrap.min.css"/>
<script src="lib/jquery-2.1.1.min.js"></script>
<script src="lib/bootstrap-3.2.0-dist/js/bootstrap.min.js"></script>
<style>
main
{
padding: 10px;
}
.container
{
margin-top: 100px;
max-width: 500px;
text-align: center;
}
.container .alert
{
margin-top: 25px;
}
</style>
</head>
<body>
<main>
<section class="container">
<h1>Diet Tracker Registration</h1>
Your password will be emailed to the address you provide <br/> <br/>
<form action="register.php" method="POST">
<input type="email" name="email" class="form-control" placeholder="Email" requried/> <br/>
<input type="text" name="name" class="form-control" placeholder="Name" required/> <br/>
<input type="number" min="1000" max="3000" name="target" class="form-control" placeholder="Calorie Target (optional)"/> <br/>
<button type="submit" class="btn btn-default btn-lg btn-block">Register</button>
</form>
<?php
if($errorMessage != '')
{
?>
<div class="alert alert-danger"><strong>Oops!</strong> <?= $errorMessage ?></div>
<?php
}
?>
</section>
</main>
</body>
</html>
|
C#
|
UTF-8
| 383
| 3.25
| 3
|
[
"MIT"
] |
permissive
|
using System;
namespace Chars_to_String
{
class Program
{
static void Main(string[] args)
{
string word = string.Empty;
for (int i = 0; i < 3; i++)
{
char character = char.Parse(Console.ReadLine());
word += character;
}
Console.WriteLine(word);
}
}
}
|
Markdown
|
UTF-8
| 1,656
| 2.96875
| 3
|
[] |
no_license
|
1,完成一个商城购物车的程序。
商品信息在文件存储的,存储形式:
name price
电脑 1999
鼠标 10
游艇 20
.......
要求:
1,用户先给自己的账户充钱:比如先充3000元。
2,读取商品信息文件将文件中的数据转化成下面的格式:
goods = [{"name": "电脑", "price": 1999},
{"name": "鼠标", "price": 10},
{"name": "游艇", "price": 20},
...... ]
3,页面显示 序号 + 商品名称 + 商品价格,如:
1 电脑 1999
2 鼠标 10
…
n 购物车结算
q或者Q退出程序。
(升级:没有买商品(在购物车中) 存到一个文件中)Shopping_car = {0:{"name": "电脑", "price": 1999,mount:3}}
4,用户输入选择的商品序号,然后打印商品名称及商品价格,并将此商品,添加到购物车,用户还可继续添加商品。
5,如果用户输入的商品序号有误,则提示输入有误,并重新输入。
6,用户输入n为购物车结算,依次显示用户购物车里面的商品,数量及单价,若充值的钱数不足,(升级:充钱功能)则让用户删除某商品,直至可以购买,若充值的钱数充足,则可以直接购买。
7,用户输入Q或者q退出程序(打印未购买的商品)。
8,输入N退出程序之后,依次显示用户购买的商品,数量,单价,以及此次共消费多少钱,账户余额多少,并将购买信息写入文件。
完成1-3要求为C。
完成1-4要求为 C+。
完成1-6要求为B。
完成全部要求并且没有BUG为A 或者A +。
|
JavaScript
|
UTF-8
| 1,441
| 2.890625
| 3
|
[] |
no_license
|
/*eslint-disable*/
import axios from 'axios';
import { showAlert } from './alerts';
export const login = async (email, password) => {
try {
const res = await axios({
method: 'POST',
url: 'http://127.0.0.1:3000/api/v1/users/login', // it will go to directly to user routes
data: {
email,
password,
},
});
console.log(res);
if (res.data.status === 'success') {
//alert('You are successfully login');
showAlert('success', 'Logged in Successfully');
window.setTimeout(() => {
location.assign('/'); // to reload home page as we given / in location.assign
}, 1500);
}
console.log(res);
} catch (err) {
// console.log(err.response.data);
//alert(err.response.data.message);
showAlert('error', err.response.data.message);
}
};
//document.querySelector('form').addEventListener('submit', (e) => {
// e.preventDefault();
// const email = document.getElementById('email').value;
// const password = document.getElementById('password').value;
// login(email, password);
export const logOut = async () => {
try {
const res = await axios({
method: 'GET',
url: 'http://127.0.0.1:3000/api/v1/users/logout',
});
if (res.data.status === 'success') location.reload(); //true will force a reload from server and not from browser
} catch (err) {
showAlert('Error', 'Errorlogging out! try again');
}
};
|
Markdown
|
UTF-8
| 1,164
| 3.71875
| 4
|
[] |
no_license
|
Why does FixedArrayQueue require an explicit constructor?
Answer:
-------
FixedArrayQueue has an uninitialized array named data.
But, If we want to use the array in FixedArrayQueue, then we have to allocate memory for it.
For this we need the capacity of the array.
To pass this capacity as argument(Input to the constructor) then FixedArrayQueue require an explicit constructor.
What happens when you offer an item to a full FixedArrayQueue?
Answer:
-------
Full FixedArrayQueue means there is no slot to insert new element.
In this case, offer returns false.
What happens when you poll an empty FixedArrayQueue?
Answer:
-------
Empty FixedArrayQueue means there are no elements in the array.
In this case, offer returns null.
What is the time and (extra) space complexity of each of the FixedArrayQueue methods?
Answer:
-------
Time complexity Space complexity
offer - O(1) O(1)
peek - O(1) O(1)
poll - O(1) O(1)
isEmpty - O(1) O(1)
size - O(1) O(1)
asList - O(n) O(n)
Where n is the size of the array
|
Markdown
|
UTF-8
| 3,675
| 2.90625
| 3
|
[] |
no_license
|
Reproducible Research - Peer Assessment 1
========================================================
This document processes and summarizes the dataset 'Activity monitoring data'. The dataset contains the number of **steps** taken in a 5-minute interval, the **date** the activity measurement was recorded, and an identifier for the 5-minute **interval** in which the measurement was recorded.
```r
opts_chunk$set(echo = TRUE, results = "asis")
library(ggplot2)
```
**Read the dataset**
```r
df <- read.csv("activity.csv",as.is=T)
df$date <- as.Date(df$date)
```
**Summarize the total number of steps for each day and show histogram (ignore NAs).**
```r
sry1 <- aggregate(df$steps,list(df$date),sum)
names(sry1) <- c("date","steps")
sry1 <- na.omit(sry1)
qplot(steps, data=sry1, geom="histogram", binwidth =1000)
```

**Show mean and median:**
```r
sry1mean <- as.integer(round(mean(sry1$steps,na.rm=T)))
sry1median <- median(sry1$steps,na.rm=T)
```
**The mean of number of steps per day is 10766, and the median of number of steps is 10765.**
**Calculate average number of steps for each interval across all days and show a line graph:**
```r
sry2 <- aggregate(df$steps[!is.na(df$steps)],list(df$interval[!is.na(df$steps)]),FUN=mean)
names(sry2) <- c("interval","avg_steps")
g <- ggplot(sry2,aes(interval,avg_steps)) + geom_line()
g <- g + labs(title="Average Steps for Each Interval")
g <- g + labs(x="Interval") + labs(y="Average Steps")
print(g)
```

```r
sry2mx <- sry2[sry2$avg_steps == max(sry2$avg_steps),]
```
**The maximum average number of steps is 206 for the interval 835.**
```r
nnas <- nrow(df[is.na(df),])
```
**The number of missing values in the dataset are 2304.**
**A sensible and simple approach to filling in the missing values is to replace them with the average of number of steps for the 5-minute intervals taken over all days. The following code fills in the missing values using such an approach.**
```r
df2 <- df
for (i in which(is.na(df))) {
df2$steps[i] <- sry2$avg_steps[which(sry2$interval == df2$interval[i])]
}
```
**Summarize the number of steps for each day, with missing values filled in, and show a histogram.**
```r
sry3 <- aggregate(df2$steps,list(df2$date),sum)
names(sry3) <- c("date","steps")
qplot(steps, data=sry3, geom="histogram", binwidth = 1000)
```

```r
sry3mean <- as.integer(round(mean(sry3$steps)))
sry3median <- as.integer(round(median(sry3$steps)))
```
**After flling in missing values, the mean of number of steps per day is 10766, and the median of number of steps is 10766.**
Evidently, the substitution of missing values did not change the average daily mean and median by much. The reason for this is that the replacement values were themselves mean of the steps over 5-minute intervals across all days.
**Factorize the dataset into weekdays and weekends.**
```r
df2$wday <- gsub("(Mon|Tues|Wednes|Thurs|Fri)day","Weekday",
gsub("(Satur|Sun)day","Weekend",weekdays(df2$date)))
df2$wday <- factor(df2$wday)
```
**Summarize the number of steps for each 5-minute interval over weekdays and weekends and plot a graph.**
```r
sry4 <- aggregate(df2$steps,list(df2$wday,df2$interval),mean)
names(sry4) <- c("wday","interval","avg_steps")
g <- ggplot(sry4,aes(interval,avg_steps)) + geom_line()
g <- g + stat_bin() + facet_wrap(~wday,ncol=1)
g <- g + labs(title="Average Steps for Each Interval")
g <- g + labs(x = "Interval") + labs(y = "Average Steps")
print(g)
```

|
Java
|
UTF-8
| 3,406
| 2.484375
| 2
|
[] |
no_license
|
package fr.pagelib.termapp;
import fr.pagelib.termapp.wsc.Configuration;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Main extends Application {
private MainController mainController;
@Override
public void start(Stage primaryStage) throws Exception
{
// Load configuration
try {
String configPath = System.getenv("PAGELIB_TERMAPP_CONFIG");
if (configPath == null) configPath = "config.json";
System.out.println("Loading configuration from file " + configPath);
Configuration.setConfig(configPath);
}
catch (FileNotFoundException e) {
System.err.println("Unable to find configuration file.");
Platform.exit();
}
catch (IOException e) {
System.err.println("Unexpected IOException while reading configuration file: " + e);
e.printStackTrace();
Platform.exit();
}
FXMLLoader loader = new FXMLLoader(getClass().getResource("views/main.fxml"));
AnchorPane root = (AnchorPane) loader.load();
primaryStage.setTitle("PageLib terminal app");
primaryStage.setScene(new Scene(root, 800, 600));
primaryStage.show();
this.mainController = loader.getController();
// Load and set up pages
addPage(this.mainController.homePage, MainController.Page.HOME, "views/home.fxml");
addPage(this.mainController.loginPage, MainController.Page.LOGIN, "views/login.fxml");
addPage(this.mainController.sourcePage, MainController.Page.SOURCE, "views/source.fxml");
addPage(this.mainController.cloudDocumentPage, MainController.Page.CLOUD_DOCUMENT, "views/cloudDocument.fxml");
addPage(this.mainController.usbDocumentPage, MainController.Page.USB_DOCUMENT, "views/usbDocument.fxml");
addPage(this.mainController.jobSettingsPage, MainController.Page.JOB_SETTINGS, "views/jobSettings.fxml");
addPage(this.mainController.cartPage, MainController.Page.CART, "views/cart.fxml");
addPage(this.mainController.printingPage, MainController.Page.PRINTING, "views/printing.fxml");
// Set up the printer (will throw PrinterNotFoundException if no match)
this.mainController.printingController.findPrinter(Configuration.getConfig().getPrinterNameRegex());
this.mainController.showPage(MainController.Page.HOME);
}
private PageController addPage(AnchorPane containerPage, MainController.Page page, String fxmlFileName)
throws IOException
{
// Load the page's AnchorPane and add it to the root window
FXMLLoader loader = new FXMLLoader(getClass().getResource(fxmlFileName));
AnchorPane pane = (AnchorPane) loader.load();
containerPage.getChildren().add(pane);
// Load the page's controller and bind it with the MainController
PageController controller = loader.getController();
controller.setMainController(this.mainController);
this.mainController.setPageController(page, controller);
return controller;
}
public static void main(String[] args) {
launch(args);
}
}
|
Python
|
UTF-8
| 1,224
| 3.046875
| 3
|
[] |
no_license
|
class Solution:
def countVowelPermutation(self, n: int) -> int:
a_vowel_permutation_count = [1] * n
e_vowel_permutation_count = [1] * n
i_vowel_permutation_count = [1] * n
o_vowel_permutation_count = [1] * n
u_vowel_permutation_count = [1] * n
MOD = 10 ** 9 + 7
for i in range(1, n):
a_vowel_permutation_count[i] = (e_vowel_permutation_count[i - 1] + i_vowel_permutation_count[i - 1] + u_vowel_permutation_count[i - 1]) % MOD
e_vowel_permutation_count[i] = (a_vowel_permutation_count[i - 1] + i_vowel_permutation_count[i - 1]) % MOD
i_vowel_permutation_count[i] = (e_vowel_permutation_count[i - 1] + o_vowel_permutation_count[i - 1]) % MOD
o_vowel_permutation_count[i] = (i_vowel_permutation_count[i - 1]) % MOD
u_vowel_permutation_count[i] = (i_vowel_permutation_count[i - 1] + o_vowel_permutation_count[i - 1]) % MOD
result = 0
result = (a_vowel_permutation_count[n - 1] + e_vowel_permutation_count[n - 1] + \
i_vowel_permutation_count[n - 1] + o_vowel_permutation_count[n - 1] + \
u_vowel_permutation_count[n - 1]) % MOD
return result
|
JavaScript
|
UTF-8
| 1,608
| 2.609375
| 3
|
[] |
no_license
|
const mongoose = require('mongoose');
const crypto = require('crypto');
const jwt = require('jsonwebtoken');
const { secret } = require('../../../../config')[process.env.NODE_ENV];
const UserSchema = new mongoose.Schema(
{
email: {
type: String,
lowercase: true,
required: true
},
auth: {
hash: {
type: String
},
salt: {
type: String
}
}
},
{ versionKey: false, timestamps: true }
);
// Taken shamelessly from
// https://github.com/gothinkster/node-express-realworld-example-app
/**
* Use function() instead of () =>, as this will be bound to current
* scope in latter. Use REGULAR functions!
* */
UserSchema.methods.generateJWT = function() {
const today = new Date();
const exp = new Date(today);
exp.setDate(today.getDate() + 60);
return jwt.sign(
{
id: this._id,
email: this.email,
exp: parseInt(exp.getTime() / 1000, 0)
},
secret
);
};
UserSchema.methods.validPassword = function(password) {
const hash = crypto.pbkdf2Sync(password, this.auth.salt, 10000, 512, 'sha512').toString('hex');
return this.auth.hash === hash;
};
UserSchema.methods.setPassword = function(password) {
this.auth = {
hash: '',
salt: ''
};
this.auth.salt = crypto.randomBytes(16).toString('hex');
this.auth.hash = crypto
.pbkdf2Sync(password, this.auth.salt, 10000, 512, 'sha512')
.toString('hex');
};
UserSchema.methods.toAuthJSON = function() {
return {
email: this.email,
token: this.generateJWT()
};
};
module.exports = mongoose.model('user', UserSchema);
|
PHP
|
UTF-8
| 2,972
| 2.78125
| 3
|
[] |
no_license
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* Format class
* Return API Response object
*
* @author Wonder Jung, @cafeclass
* @license MIT
*/
class MY_Response
{
public static $EVENT_UNKNOWN_ERROR_OCCURED = "Unknown error has occured!";
private $CI=null;
public function __construct()
{
// Do something...
$this->CI =& get_instance();
if(!isset($this->CI)) {
return;
}
if(!isset($this->CI->my_error)) {
return;
}
}
/*
* @ Desc : 원격 통신뒤의 데이터($output)만 전달하는 경우.
*/
public function getResBodySuccessData($data=null)
{
$response_body =
$this->getResBodySuccess(
// $query=""
"",
// $data=null
$data,
// $error=null
$this->CI->my_error->get(),
// $extra=null
null
);
return $response_body;
}
public function getResBodySuccess($query=null, $data=null, $error=null, $extra=null)
{
return $this->getResBody(true, "Done", $query, $data, $error, $extra);
}
public function getResBodyFail($message="", $query=null, $data=null, $error=null, $extra=null)
{
return $this->getResBody(false, $message, $query, $data, $error, $extra);
}
/*
* @ Desc : 응답 코드에 메시지만 전달하는 경우.
*/
public function getResBodyFailMsg($message="")
{
if(empty($message))
{
return null;
}
$response_body =
$this->getResBodyFail(
// $message=""
$message,
// $query=""
"",
// $data=null
null,
// $error=null
$this->CI->my_error->get(),
// $extra=null
null
);
return $response_body;
}
/*
* @ Desc : 응답 코드에 메시지만 전달하는 경우.
*/
public function getResBodyFailMsgData($message="", $data=null)
{
if(empty($message))
{
return null;
}
$response_body =
$this->getResBodyFail(
// $message=""
$message,
// $query=""
"",
// $data=null
$data,
// $error=null
$this->CI->my_error->get(),
// $extra=null
null
);
return $response_body;
}
public function getResBody($success=false, $message="", $query=null, $data=null, $error=null, $extra=null)
{
$response_body = [
'success' => $success,
'message' => $message,
'query' => $query,
'data' => $data,
'error' => $error,
'extra' => $extra
];
return $response_body;
}
}
|
Java
|
UTF-8
| 5,504
| 2.15625
| 2
|
[] |
no_license
|
package org.ivdnt.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.ivdnt.openconvert.filehandling.DirectoryHandling;
import org.ivdnt.openconvert.filehandling.SimpleInputOutputProcess;
import org.ivdnt.openconvert.filehandling.SimpleProcessException;
import org.w3c.dom.Document;
/**
* Wrapper voor de xsltc engine. Deze klasse zet met behulp van de XSLT engine (o.a. Transformer.java) een XML
* artikel om in HTML.
*/
public class XSLTTransformer extends SimpleInputOutputProcess
{
private Transformer transformer = null;
private TransformerFactory tFactory;
private String xslInUri = null;
private boolean useSaxon = true;
InputStream xslReader = null;
int jobId=0;
private synchronized void nextJob()
{
jobId++;
setParameter("jobNumber","" + jobId);
}
public XSLTTransformer(String xslInUri)
{
String key = "javax.xml.transform.TransformerFactory";
// N.B. Aangepast ivm nieuwe Javaversie (1.5 of 1.6), was vroeger:
// com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl
String value = "org.apache.xalan.processor.TransformerFactoryImpl";
if (useSaxon)
{
value = "net.sf.saxon.TransformerFactoryImpl";
}
Properties props = System.getProperties();
props.put(key, value);
System.setProperties(props);
tFactory = TransformerFactory.newInstance();
this.xslInUri = xslInUri;
loadStylesheet();
if (this.transformer == null)
{
System.err.println("EEK!");
System.exit(1);
}
}
public XSLTTransformer(InputStream xslReader)
{
String key = "javax.xml.transform.TransformerFactory";
// N.B. Aangepast ivm nieuwe Javaversie (1.5 of 1.6), was vroeger:
// com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl
String value = "org.apache.xalan.processor.TransformerFactoryImpl";
if (useSaxon)
{
value = "net.sf.saxon.TransformerFactoryImpl";
}
Properties props = System.getProperties();
props.put(key, value);
System.setProperties(props);
tFactory = TransformerFactory.newInstance();
this.xslReader = xslReader;
loadStylesheet();
if (this.transformer == null)
{
System.err.println("EEK!");
System.exit(1);
}
}
private void loadStylesheet()
{
if (xslInUri != null)
{
try
{
this.transformer = tFactory.newTransformer(new StreamSource(this.xslInUri));
} catch (TransformerConfigurationException e)
{
e.printStackTrace();
}
}
if (xslReader != null)
{
try
{
this.transformer = tFactory.newTransformer(new StreamSource(xslReader));
} catch (TransformerConfigurationException e)
{
e.printStackTrace();
}
}
}
public XSLTTransformer(Transformer transformer)
{
this.transformer = transformer;
}
public void setParameter(String name, String value)
{
transformer.setParameter(name, value);
}
/**
* Voert de transformatie uit. De input bestaat uit een String met de XML code.
* @param instring
*
* @param(STring instring
* De input string
* @param out
* java.io.Writer object Het resultaat van het transformeren van de XML code.
* @throws TransformerConfigurationException
* @throws TransformerException
* @throws IOException
*/
public void transformString(String instring, Writer out)
throws TransformerConfigurationException, TransformerException, IOException
{
StreamSource source = new StreamSource(new StringReader(instring));
StreamResult result = new StreamResult(out);
transformer.transform(source, result);
out.flush();
}
public Document transformDocument(Document inDocument)
{
try
{
DOMSource source = new DOMSource(inDocument);
DOMResult result = new DOMResult();
transformer.transform(source, result);
return (Document) result.getNode();
} catch (Exception e)
{
e.printStackTrace();
return null;
}
}
/*
* Dit gaat niet goed als de input niet utf8 is
*/
public void transformFile(String inFileName, String outFileName)
{
try {
handleFile(inFileName, outFileName);
} catch (SimpleProcessException e) {
e.printStackTrace();
}
}
public void transformStream(Reader reader, Writer writer) {
try {
nextJob();
transformer.transform(new StreamSource(reader), new StreamResult(writer));
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void handleStream(InputStream is, Charset ics, OutputStream os) throws SimpleProcessException, IOException {
if (ics == null)
ics = StandardCharsets.UTF_8;
try (
Reader reader = new InputStreamReader(is, ics);
Writer writer = new OutputStreamWriter(os, ics);
) {
transformStream(reader, writer);
} catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
XSLTTransformer p = new XSLTTransformer(args[0]);
DirectoryHandling.tagAllFilesInDirectory(p, args[1], args[2]);
}
}
|
C++
|
UTF-8
| 6,651
| 2.640625
| 3
|
[
"Apache-2.0"
] |
permissive
|
/**
* \file SpectrumCollection.cpp
* AUTHOR: Barbara Frewen
* CREATE DATE: 11 April 2011
* \brief Abstract class for accessing spectra from a file.
*/
#include "SpectrumCollection.h"
#include "model/ProteinIndex.h"
#include "model/Peak.h"
#include "util/utils.h"
#ifndef _MSC_VER
#include "unistd.h"
#endif
#include "parameter.h"
#include <cerrno>
#include <cstring>
#include "io/carp.h"
#include "util/WinCrux.h"
#include <iostream>
using namespace std;
using namespace Crux;
namespace Crux {
/**
* Instantiates a new spectrum_collection object from a filename.
* Resolves any relative paths. Confirms that file exists.
*/
SpectrumCollection::SpectrumCollection (
const string& filename ///< The spectrum collection filename.
)
: filename_(filename), is_parsed_(false), num_charged_spectra_(0) {
#if DARWIN
char path_buffer[PATH_MAX];
char* absolute_path_file = realpath(filename.c_str(), path_buffer);
#else
char* absolute_path_file = realpath(filename.c_str(), NULL);
#endif
if (absolute_path_file == NULL) {
carp(CARP_FATAL, "Error from spectrum file '%s'. (%s)",
filename.c_str(), strerror(errno));
}
if(access(absolute_path_file, F_OK)) {
carp(CARP_FATAL, "File %s could not be opened\n", absolute_path_file);
}
filename_ = absolute_path_file;
#ifndef DARWIN
free(absolute_path_file);
#endif
}
/**
* Copy constructor. Creates copies of each spectrum for the new
* collection.
*/
SpectrumCollection::SpectrumCollection(
SpectrumCollection& old_collection
) : filename_(old_collection.filename_),
is_parsed_(old_collection.is_parsed_),
num_charged_spectra_(old_collection.num_charged_spectra_) {
// copy spectra
for (SpectrumIterator spectrum_iterator = old_collection.begin();
spectrum_iterator != old_collection.end();
++spectrum_iterator) {
Spectrum* old_spectrum = *spectrum_iterator;
Spectrum* new_spectrum = new Spectrum(*old_spectrum);
this->addSpectrumToEnd(new_spectrum);
}
}
/**
* Default destructor
*/
SpectrumCollection::~SpectrumCollection() {
for (SpectrumIterator spectrum_iterator = this->begin();
spectrum_iterator != this->end();
++spectrum_iterator) {
delete *spectrum_iterator;
}
spectra_.clear();
}
/**
* \returns the begining of the spectra deque
*/
SpectrumIterator SpectrumCollection::begin() {
return spectra_.begin();
}
/**
* \returns the end of the spectra deque
*/
SpectrumIterator SpectrumCollection::end() {
return spectra_.end();
}
/*
* Parses a single spectrum from a spectrum_collection with first scan
* number equal to first_scan.
* \returns The newly allocated Spectrum or NULL if scan number not found.
*/
Spectrum* SpectrumCollection::getSpectrum(
int first_scan ///< The first scan of the spectrum to retrieve -in
) {
Spectrum* spectrum = new Spectrum();
bool success = getSpectrum(first_scan, spectrum);
if (success) {
return spectrum;
} else {
delete spectrum;
return NULL;
}
}
/**
* Parses a single spectrum from a spectrum_collection with first scan
* number equal to first_scan. Removes any existing information in the
* given spectrum.
* \returns True if the spectrum was allocated, false on error.
*/
bool SpectrumCollection::getSpectrum(
int first_scan, ///< The first scan of the spectrum to retrieve -in
Spectrum* spectrum ///< Put the spectrum info here
) {
map<int, Spectrum*>::const_iterator i = spectraByScan_.find(first_scan);
if (i != spectraByScan_.end()) {
spectrum->copyFrom(i->second);
return true;
}
for (SpectrumIterator spectrum_iterator = this->begin();
spectrum_iterator != this->end();
++spectrum_iterator) {
if ((*spectrum_iterator)->getFirstScan() == first_scan) {
spectrum->copyFrom(*spectrum_iterator);
return true;
}
}
return false;
}
/**
* Adds a spectrum to the spectrum_collection.
* adds the spectrum to the end of the spectra array
* should only be used when the adding in increasing scan num order
* when adding in random order should use add_spectrum
* spectrum must be heap allocated
*/
void SpectrumCollection::addSpectrumToEnd(
Spectrum* spectrum ///< spectrum to add to spectrum_collection -in
) {
// set spectrum
spectra_.push_back(spectrum);
num_charged_spectra_ += spectrum->getNumZStates();
}
/**
* Adds a spectrum to the spectrum_collection.
* adds the spectrum in correct order into the spectra array
* spectrum must be heap allocated
*/
void SpectrumCollection::addSpectrum(
Spectrum* spectrum ///< spectrum to add to spectrum_collection -in
) {
unsigned int add_index = 0;
// find correct location
// TODO -- replace with binary search if necessary.
for(; add_index < spectra_.size(); ++add_index) {
if(spectra_[add_index]->getFirstScan() >
spectrum->getFirstScan()) {
break;
}
}
spectra_.insert(spectra_.begin()+add_index, spectrum);
num_charged_spectra_ += spectrum->getNumZStates();
}
// FIXME maybe a faster way? can't perform binary search since we must know the array index
/**
* Removes a spectrum from the spectrum_collection.
*/
void SpectrumCollection::removeSpectrum(
Spectrum* spectrum ///< spectrum to be removed from spectrum_collection -in
) {
int scan_num = spectrum->getFirstScan();
unsigned int spectrum_index = 0;
// find where the spectrum is located in the spectrum array
for(; spectrum_index < spectra_.size(); ++spectrum_index) {
if(scan_num == spectra_[spectrum_index]->getFirstScan() ) {
break;
}
}
num_charged_spectra_ -= spectrum->getNumZStates();
delete spectra_[spectrum_index];
spectra_[spectrum_index] = NULL;
spectra_.erase(spectra_.begin() + spectrum_index);
}
/**
* \returns A pointer to the name of the file from which the spectra
* were parsed.
*/
const char* SpectrumCollection::getFilename() {
return filename_.c_str();
}
/**
* \returns The current number of spectrum in the
* spectrum_collection. Zero if the file has not yet been parsed.
*/
int SpectrumCollection::getNumSpectra() {
return spectra_.size();
}
/**
* \returns The current number of spectra assuming differnt
* charge(i.e. one spectrum with two charge states are counted as two
* spectra) in the spectrum_collection. Zero if the file has not been
* parsed.
*/
int SpectrumCollection::getNumChargedSpectra() {
return num_charged_spectra_;
}
/**
* \returns True if the spectrum_collection file has been parsed.
*/
bool SpectrumCollection::getIsParsed() {
return is_parsed_;
}
} // namespace Crux
/*
* Local Variables:
* mode: c
* c-basic-offset: 2
* End:
*/
|
Java
|
UTF-8
| 426
| 1.6875
| 2
|
[] |
no_license
|
package com.gmail.neooxpro.di.app;
import com.gmail.neooxpro.di.module.ContactDetailsModule;
import com.gmail.neooxpro.lib.di.containers.NotificationReceiverContainer;
import com.gmail.neooxpro.lib.di.scope.ContactsDetailsScope;
import dagger.Subcomponent;
@ContactsDetailsScope
@Subcomponent(modules = {ContactDetailsModule.class})
public interface NotificationReceiverComponent extends NotificationReceiverContainer {
}
|
Python
|
UTF-8
| 2,669
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
import unittest
from caes import ICAES
class TestICAES(unittest.TestCase):
def setUp(self):
# calculate stage pressures
cmp_p0 = 101.3 # kPa
cmp_p2 = 10.0e3 # kPa
cmp_p1 = (1.43 * cmp_p0 * cmp_p2) ** 0.5 # kPa
exp_p0 = 7.0e3 # kPa
exp_p2 = 101.3 # kPa
exp_p1 = (1.43 * exp_p0 * exp_p2) ** 0.5 # kPa
# test conditions
T_atm_K = 293.15
T_atm_C = T_atm_K - 273.15
inputs = ICAES.get_default_inputs()
inputs['p_atm'] = cmp_p0 # kPa
inputs['T_atm'] = T_atm_C # C
inputs['depth'] = 900.0 # [m]
inputs['PR_type'] = 'fixed'
# inputs['n_stages_cmp'] = 2
inputs['PR_cmp'] = [cmp_p1 / cmp_p0, cmp_p2 / cmp_p1]
inputs['ML_cmp1'] = 1.0*(1.65/(cmp_p1/1000)-0.05)
inputs['ML_cmp2'] = 5.0*(1.65/(cmp_p2/1000)-0.05)
inputs['ML_cmp3'] = -1.0
# inputs['n_stages_exp'] = 2
inputs['PR_exp'] = [exp_p0 / exp_p1, exp_p1 / exp_p2]
inputs['ML_exp1'] = 5.0*(1.65/(exp_p0/1000)-0.05)
inputs['ML_exp2'] = 1.0*(1.65/(exp_p1/1000)-0.05)
inputs['ML_exp3'] = -1.0
self.sys = ICAES(inputs=inputs)
# overwrite calculated air and water properties
self.sys.M = 29.0
self.sys.cp = 1.004
self.sys.gamma = 1.4
self.sys.c_water = 4.1816
self.sys.T_store_init = T_atm_K # [K]
self.sys.T_store = T_atm_K # [K]
self.sys.T2 = T_atm_K # [K]
self.sys.T3 = T_atm_K # [K]
self.sys.m_store =self.sys.m_store * 1.2 # increase amount of air to stay within pressure limits
# solve two timesteps (index 0 = compression, index 1 = expansion)
self.sys.update(m_dot=10.0, delta_t=2.0)
self.sys.update(m_dot=-10.0, delta_t=1.0)
self.sys.data.to_csv('test_perf.csv')
# self.data.to_csv('single_cycle_timeseries.csv')
# compresor tests
def test_cmp_nLP(self):
self.assertAlmostEqual(self.sys.data.loc[0, 'cmp_n0'], 1.046, places=3)
def test_cmp_nHP(self):
self.assertAlmostEqual(self.sys.data.loc[0, 'cmp_n1'], 1.092, places=3)
def test_cmp_wLP(self):
self.assertAlmostEqual(self.sys.data.loc[0, 'cmp_w_stg0'], -219.737, places=3)
# expander tests
def test_exp_nLP(self):
self.assertAlmostEqual(self.sys.data.loc[1, 'exp_n1'], 1.039, places=3)
def test_exp_nHP(self):
self.assertAlmostEqual(self.sys.data.loc[1, 'exp_n0'], 1.062, places=3)
def test_exp_wHP(self):
self.assertAlmostEqual(self.sys.data.loc[1, 'exp_w_stg0'], 154.024, places=3)
if __name__ == '__main__':
unittest.main()
|
C
|
UTF-8
| 974
| 3.890625
| 4
|
[] |
no_license
|
#include "stdio.h"
int main(void)
{
int st,ed;
printf("从哪一个数开始:");scanf("%d",&st);
printf("到哪一个数结束:");scanf("%d",&ed);
int n = 0;/*记录输出了几次*/
int i,j;
for(i = st; i <= ed; i++){
/*如果i的值是2或三输出i*/
if (2 == i || 3 == i){
printf("%4d", i);
n++;
}
/*令j从2开始递增并用每一个i去除以j*/
for(j = 2; j <= i / 2; j++){
if(0 == i % j)
break;/*如果i除尽了j泽结束if并跳出该子循环即使i+1*/
if(i / 2 == j){
printf("%4d", i);/*因为i是int型,所以当i/2=j时,即在前j个都未除尽则说明i是素数*/
n++; /*每输出一个值令n的值加一*/
}
/*每输出10个则换行*/
if(10 == n){
n = 0;
printf("\n");
}
}
}
return 0;
}
|
Python
|
UTF-8
| 586
| 2.78125
| 3
|
[] |
no_license
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# import seaborn as sns
# sns.set_style('whitegrid')
import pandas_datareader.data as web
import datetime
start_date = datetime.datetime(2010, 1, 1)
end_date = datetime.datetime.today()
APPL = pd.DataFrame(web.DataReader('AAPL', 'google', start_date, end_date))
# print APPL
# APPL = web.DataReader('AAPL')
# APPL.sort_values()
# APPL.loc[2] = [1,1,1,1,np.NaN]
# s = APPL.iloc[3]
# # print s
# APPL.append(s, ignore_index=True)
print APPL
plt.plot(APPL['Close'])
plt.title('Apple Inc Ticker Price')
plt.show()
|
TypeScript
|
UTF-8
| 323
| 2.84375
| 3
|
[] |
no_license
|
import deepReadOnly from './deepReadOnly'
export default function deepFreeze<T extends any>(obj: T): deepReadOnly<T> {
Object.getOwnPropertyNames(obj).forEach(name => {
const v = obj[name]
obj[name] = v && typeof v === 'object' ? deepFreeze(obj[name]) : v
})
return Object.freeze(obj) as deepReadOnly<T>
}
|
Markdown
|
UTF-8
| 4,187
| 3.0625
| 3
|
[] |
no_license
|
---
layout: post
title: Validation in Windows Forms DateTimePicker Control | Syncfusion
description: SfDateTimeEdit control provides an support to validation of date and time value when the enter key is pressed.
platform: WindowsForms
control: SfDateTimeEdit
documentation: ug
---
# Validation in Windows Forms DateTimePicker (SfDateTimeEdit)
The `SfDateTimeEdit` control validates the DateTime value when the <kbd>Enter</kbd> key is pressed, so that the control lost its focus or the date is picked from the drop-down calendar.
## Validation reset option
The [ValidationOption](https://help.syncfusion.com/cr/windowsforms/Syncfusion.WinForms.Input.SfDateTimeEdit.html#Syncfusion_WinForms_Input_SfDateTimeEdit_ValidationOption) that helps you to decide how the value will be changed when the validation is failed. If the validation is failed, the value will reset with previous date-time [Value](https://help.syncfusion.com/cr/windowsforms/Syncfusion.WinForms.Input.SfDateTimeEdit.html#Syncfusion_WinForms_Input_SfDateTimeEdit_Value) or `MinValue` or `MaxValue`. If the validating event is not handled then the validation will be done based on the `ValidationOption` of the SfDateTimeEdit.
The validation results can be obtained based on the input provided to `Value` or `DateTimeText` of the SfDateTimeEdit. If the provided input has invalid date-time format or value that meets minimum or maximum value constraint, then the validation results will be failed.
* **Reset**: A control that maintains the previous value before validating. If the validation is failed then the value will be reset with the previous value.
* **MinValue**: Resets value with the `MinValue`, when the validation is failed.
* **MaxValue**: Resets value with the `MaxValue`, when the validation is failed.
{% tabs %}
{% highlight C# %}
Syncfusion.WinForms.Input.SfDateTimeEdit dateTimeEdit = new Syncfusion.WinForms.Input.SfDateTimeEdit();
this.Controls.Add(dateTimeEdit);
dateTimeEdit.Value = new DateTime(2018, 2, 1);
dateTimeEdit.DateTimeEditingMode = DateTimeEditingMode.Default;
// On Validation failed the value will be reset with MinValue.
dateTimeEdit.ValidationOption = ValidationResetOption.MinValue;
{% endhighlight %}
{% highlight VB %}
Dim dateTimeEdit As Syncfusion.WinForms.Input.SfDateTimeEdit = New Syncfusion.WinForms.Input.SfDateTimeEdit
Me.Controls.Add(dateTimeEdit)
dateTimeEdit.Value = New DateTime(2018, 2, 1)
dateTimeEdit.DateTimeEditingMode = DateTimeEditingMode.Default
' On Validation failed the value will be reset with MinValue.
dateTimeEdit.ValidationOption = ValidationResetOption.MinValue
{% endhighlight %}
{% endtabs %}
The given value can be treated as a date/time value. It can be validated based on the DateTime format with culture. The following error indicating image will be shown, when the validation test is failed.

## Handle validation
The `ValidatingEventArgs` provides data for the [Validating](https://help.syncfusion.com/cr/windowsforms/Syncfusion.WinForms.Input.SfDateTimeEdit.html) event of the SfDateTimeEdit control. By handling the `Validating` event, it is possible to find the cause for validation failure with error message in the `ValidatingEventArgs`.
* **IsError**: Indicates whether the entered date and time is valid or invalid.
* **ErrorMessage**: Updates the cause of the error. The error may be caused due to minimum or maximum value constraint met or incorrect date time format.
{% tabs %}
{% highlight C# %}
// Invoking Validating event
this.dateTimeEdit.Validating += DateTimeEdit_Validating;
private void DateTimeEdit_Validating(object sender, ValidatingEventArgs e)
{
if (e.IsError)
{
MessageBox.Show(e.ErrorMessage);
}
}
{% endhighlight %}
{% highlight VB %}
' Invoking Validating event
Me.dateTimeEdit.Validating = (Me.dateTimeEdit.Validating + DateTimeEdit_Validating)
Private Sub DateTimeEdit_Validating(ByVal sender As Object, ByVal e As ValidatingEventArgs)
If e.IsError Then
MessageBox.Show(e.ErrorMessage)
End If
End Sub
{% endhighlight %}
{% endtabs %}
|
Java
|
UTF-8
| 474
| 1.890625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package edu.drexel.cis.dragon.nlp.tool.xtract;
import edu.drexel.cis.dragon.nlp.Sentence;
public abstract interface WordPairGenerator
{
public abstract int generate(Sentence paramSentence);
public abstract WordPairStat getWordPairs(int paramInt);
public abstract void setMaxSpan(int paramInt);
}
/* Location: C:\dragontoolikt\dragontool.jar
* Qualified Name: dragon.nlp.tool.xtract.WordPairGenerator
* JD-Core Version: 0.6.2
*/
|
Python
|
UTF-8
| 572
| 3.34375
| 3
|
[] |
no_license
|
class Solution:
# @param {integer[]} nums
# @return {string}
# sort by n/(pow(10,len)-1)
# edge case: all are "0"s
def largestNumber(self, nums):
if nums == []:
return 0
lis = []
for i in range(0, len(nums)):
n = nums[i]
n_len = len(str(n))
lis.append([float(n)/(pow(10,n_len)-1), n])
lis.sort(key = lambda x:-x[0])
ans = ''
for [k, n] in lis:
ans = ans + str(n)
if len(ans) == ans.count('0'):
return "0"
return ans
|
Swift
|
UTF-8
| 1,131
| 3.65625
| 4
|
[] |
no_license
|
class Node {
var value: Int
var leftChildren: Node?
var rightChildren: Node?
init(value: Int) {
self.value = value
}
}
class BinarySearchTree {
var root: Node?
func append(value: Int, node: inout Node?) -> Void {
let newNode = Node(value: value)
if let nodeToCompare = node {
if newNode.value > nodeToCompare.value {
append(value: value, node: &nodeToCompare.rightChildren)
} else {
append(value: value, node: &nodeToCompare.leftChildren)
}
} else {
node = newNode
}
}
func search(value: Int, node: Node?) -> Bool {
if let nodeToCompare = node {
if value == nodeToCompare.value {
return true
} else {
if value > node!.value {
return search(value: value, node: node?.rightChildren)
} else {
return search(value: value, node: node?.leftChildren)
}
}
} else {
return false
}
}
}
|
Markdown
|
UTF-8
| 471
| 2.625
| 3
|
[] |
no_license
|
# Scenario 8
- **Titre** : Connection
- **Objectif**: Connection d'un utilisateur
- **Précondition(s)**:
- Avoir installé l'application en local
## Etapes
- D1 : L'internaute ouvre l'application en cliquant sur l'exécutable de l'application
- D2 : L'application affiche un écran de connexion
- D3 : L'internaute entre ses identifiants afin de se connecter
- D4 : L'internaute clique sur le bouton de connexion
- D5 : L'internaute accède à la page d'accueil
|
Java
|
UTF-8
| 3,231
| 2.203125
| 2
|
[] |
no_license
|
package de.eschoenawa.wifiar.activities;
import android.Manifest;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.NavUtils;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import de.eschoenawa.wifiar.R;
import de.eschoenawa.wifiar.utils.ImageHolder;
import de.eschoenawa.wifiar.utils.Utils;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;
@RuntimePermissions
public class HeatmapImageActivity extends AppCompatActivity {
private ImageView imgView;
private Bitmap image;
private Bitmap rotatedImage;
@SuppressLint("ClickableViewAccessibility")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_heatmap_image);
imgView = findViewById(R.id.heatmap);
ImageHolder imageHolder = ImageHolder.getInstance();
rotatedImage = image = imageHolder.getImage();
imageHolder.clear();
imgView.setImageBitmap(image);
imgView.setOnTouchListener((v, event) -> {
float xOffset = imgView.getWidth() / 2;
float yOffset = imgView.getHeight() / 2;
float x = event.getX();
float y = event.getY();
if (event.getAction() == MotionEvent.ACTION_MOVE) {
float angle = (float) Math.toDegrees(Math.atan2(x - xOffset, yOffset - y));
rotate(angle);
}
return true;
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
HeatmapImageActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
}
public void onClickSave(View view) {
HeatmapImageActivityPermissionsDispatcher.saveImageWithPermissionCheck(this);
}
@NeedsPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
public void saveImage() {
long timestamp = System.currentTimeMillis();
Utils.saveBitmap(rotatedImage, "heatmap_" + timestamp + ".png");
Toast.makeText(this, "Heatmap gespeichert!", Toast.LENGTH_SHORT).show();
NavUtils.navigateUpFromSameTask(this);
}
@OnPermissionDenied(Manifest.permission.WRITE_EXTERNAL_STORAGE)
public void savePermissionDenied() {
Toast.makeText(this, "Um das Bild zu speichern benötigt WifiAR Zugriff auf Ihren Speicher!", Toast.LENGTH_LONG).show();
}
private void rotate(float toDegrees) {
if (image == null) {
return;
}
Matrix matrix = new Matrix();
matrix.postRotate(toDegrees);
rotatedImage = Bitmap.createBitmap(image, 0, 0, image.getWidth(), image.getHeight(), matrix, true);
imgView.setImageBitmap(rotatedImage);
}
}
|
PHP
|
UTF-8
| 1,456
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
<?php
/**
* Created by PhpStorm.
* User: Alexeenko Sergey Aleksandrovich
* Email: sergei_alekseenk@list.ru
* Company: http://machineheads.ru
* @see https://github.com/mheads-dev/yii2-dbfiles
* Date: 19.03.2019
* Time: 12:08
*/
namespace mheads\dbfiles;
class ImageFile extends File
{
/** @var int */
protected $validateMinWidth;
/** @var int */
protected $validateMaxWidth;
/** @var int */
protected $validateMinHeight;
/** @var int */
protected $validateMaxHeight;
public function rules()
{
$rules = parent::rules();
$rules['file'][1] = 'image';
if($this->validateMinWidth !== NULL)
{
$rules['file']['minWidth'] = $this->validateMinWidth;
}
if($this->validateMaxWidth !== NULL)
{
$rules['file']['maxWidth'] = $this->validateMaxWidth;
}
if($this->validateMinHeight !== NULL)
{
$rules['file']['minHeight'] = $this->validateMinHeight;
}
if($this->validateMaxHeight !== NULL)
{
$rules['file']['maxHeight'] = $this->validateMaxHeight;
}
return $rules;
}
/**
* @param $value int
*/
public function setValidateMinWidth($value)
{
$this->validateMinWidth = $value;
}
/**
* @param $value int
*/
public function setValidateMaxWidth($value)
{
$this->validateMaxWidth = $value;
}
/**
* @param $value int
*/
public function setValidateMinHeight($value)
{
$this->validateMinHeight = $value;
}
/**
* @param $value int
*/
public function setValidateMaxHeight($value)
{
$this->validateMaxHeight = $value;
}
}
|
PHP
|
UTF-8
| 979
| 3.09375
| 3
|
[] |
no_license
|
<?php
require_once("db_obj.php");
class category_list {
public $cat_list;
public $cat_main_list;
public function __construct() {
}
public function load() {
$sql_str = "SELECT id, parent_id, name FROM category";
$result = sqlite_query($db, $sql_str);
while($row = $result->fetchArray()) {
$cat = new category($row["id"], $row["parent_id"], $row["name"]);
array_push($this->cat_list, $cat);
}
}
private function sort_cat_list() {
foreach($this->cat_list as $cat)
foreach($this->cat_list as $sub_cat)
if($cat->id == $sub_cat->parent_id)
array_push($cat->sub_cat_list, $sub_cat);
foreach($this->cat_list as $cat)
if($cat->parent_id == -1)
array_push($this->cat_main_list, $cat);
}
}
class category {
public $db;
public $sub_cat_list;
public $id;
public $parent_id;
public $name;
public function __construct($id, $parent_id, $name) {
$this->id = $id;
$this->parent_id = $parent_id;
$this->name = $name;
}
}
?>
|
C++
|
UHC
| 1,096
| 2.765625
| 3
|
[] |
no_license
|
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
// 14391
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
int N, M;
int arr[5][5];
cin >> N >> M;
for(int i = 0; i < N; i++){
string s; cin >> s;
for(int j = 0; j < M; j++) arr[i][j] = s[j] - '0';
}
int ans = 0;
// غ
for(int state = 0; state < (1 << N*M); state++){
int tmpS = 0;
for(int i = 0; i < N; i++){
int rowS = 0;
for(int j = 0; j < M; j++){
int idx = i * M + j;
if ((state | (1 << idx)) == state){
rowS = rowS * 10 + arr[i][j];
}
else{
tmpS += rowS;
rowS = 0;
}
}
tmpS += rowS;
}
for(int j = 0; j < M; j++){
int colS = 0;
for(int i = 0; i < N; i++){
int idx = j + i * M;
if ((state | (1 << idx)) != state){
colS = colS * 10 + arr[i][j];
}
else{
tmpS += colS;
colS = 0;
}
}
tmpS += colS;
}
ans = max(ans, tmpS);
}
cout << ans;
return 0;
}
|
Ruby
|
UTF-8
| 319
| 3.453125
| 3
|
[] |
no_license
|
puts "this program keeps track of how much you worked out"
puts "please enter the number of minutes you worked out today"
minWorkOut = gets.to_i
puts "OK, you worked out #{minWorkOut} minutes today"
f = File.open("my_exercise_history", "a")
f.write(minWorkOut)
f.close
f = File.open("my_exercise_history.txt", "w")
|
C++
|
UTF-8
| 2,499
| 3.453125
| 3
|
[] |
no_license
|
#include "Vector2.h"
vec2::vec2()
{
xpos = 0;
ypos = 0;
}
vec2::vec2(float x, float y)
{
this->xpos = x;
this->ypos = y;
}
vec2 vec2::operator+(const vec2 & rhs) const
{
vec2 vec;
vec.xpos = xpos + rhs.xpos;
vec.ypos = ypos + rhs.ypos;
return vec;
}
vec2 vec2::operator-(const vec2 & rhs) const
{
vec2 vec;
vec.xpos = xpos + rhs.xpos;
vec.ypos = ypos + rhs.ypos;
return vec;
}
vec2 & vec2::operator+=(const vec2 & rhs)
{
xpos += rhs.xpos;
ypos += rhs.ypos;
return *this;
}
vec2 & vec2::operator-=(const vec2 & rhs)
{
xpos -= rhs.xpos;
ypos -= rhs.ypos;
return *this;
}
bool vec2::operator==(const vec2 & rhs) const
{
return ((xpos >= (rhs.xpos - FLT_EPSILON) && xpos <= (rhs.xpos + FLT_EPSILON)) &&
(ypos >= (rhs.ypos - FLT_EPSILON) && ypos <= (rhs.ypos + FLT_EPSILON)));
}
bool vec2::operator!=(const vec2 & rhs) const
{
return !((xpos >= (rhs.xpos - FLT_EPSILON) && xpos <= (rhs.xpos + FLT_EPSILON)) &&
(ypos >= (rhs.ypos - FLT_EPSILON) && ypos <= (rhs.ypos + FLT_EPSILON)));
}
vec2 vec2::operator-() const
{
vec2 vec;
vec.xpos = -xpos;
vec.ypos = -ypos;
return vec;
}
float vec2::magnitude() const
{
float magnitude = (xpos * xpos + ypos * ypos);
sqrt(magnitude);
return magnitude;
}
float vec2::dot(const vec2 & rhs) const
{
return ((xpos * rhs.xpos) + (ypos * rhs.ypos));
}
vec2 & vec2::normalize()
{
float mag = magnitude();
xpos /= mag;
ypos /= mag;
return *this;
}
vec2 vec2::getNormalized() const
{
vec2 normal;
float mag = normal.magnitude();
std::cout << mag << std::endl;
normal.xpos = xpos / mag;
normal.ypos = ypos / mag;
return normal;
}
vec2 & vec2::scale(const vec2 & rhs)
{
xpos = xpos * rhs.xpos;
ypos = ypos * rhs.ypos;
return *this;
}
vec2 vec2::getScaled(const vec2 & rhs) const
{
vec2 scaled{ xpos, ypos };
scaled.xpos = scaled.xpos * rhs.xpos;
scaled.ypos = scaled.ypos * rhs.ypos;
return scaled;
}
vec2 vec2::operator*(const float rhs) const
{
vec2 times;
times.xpos = xpos * rhs;
times.ypos = ypos * rhs;
return times;
}
vec2 & vec2::operator*=(const float rhs)
{
xpos *= rhs;
ypos *= rhs;
return *this;
}
vec2 & vec2::operator/=(const float rhs)
{
xpos /= rhs;
ypos /= rhs;
return *this;
}
vec2 operator*(const float lhs, const vec2 & rhs)
{
vec2 bob;
bob.xpos = lhs * rhs.xpos;
bob.ypos = lhs * rhs.ypos;
return bob;
}
|
Java
|
UTF-8
| 3,280
| 2.796875
| 3
|
[
"Apache-2.0"
] |
permissive
|
/**
* @author Sogrey
* @date 2015-11-27上午10:44:04
*/
package com.sogrey.frame.utils;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
/**
* @author Sogrey
* @date 2015-11-27上午10:44:04
*/
public class FrontUtils {
// android字体大小根据分辨率自动调整
// 手机设备太多,分辨率也不一样,看到网上大部分的适应字体的方法是定义values320×480或value-hdpi方式去处理。
// 采用第一种的就惨了,很多设备的分辨率是不一样的,难道要每种都定义吗?
// 采用第二种的在平板电脑里没有效果。
// 最后还是代码的方式方便快捷。。。
public static void changeViewSize(Context mcontext, int viewGroupId,
int resTitleId, int wpx, int hpx) {
ViewGroup viewGroup = (ViewGroup) LayoutInflater.from(mcontext).inflate(viewGroupId, null);
changeViewSize(viewGroup, resTitleId, wpx, hpx);
}
// 遍历设置字体
public static void changeViewSize(ViewGroup viewGroup, int resTitleId,
int screenWidth, int screenHeight) {// 传入Activity顶层Layout,屏幕宽,屏幕高
int adjustFontSize = adjustFontSize(screenWidth, screenHeight);
for (int i = 0; i < viewGroup.getChildCount(); i++) {
View v = viewGroup.getChildAt(i);
if (v instanceof ViewGroup) {
changeViewSize((ViewGroup) v, resTitleId, screenWidth,
screenHeight);
} else if (v instanceof Button) {// 按钮加大这个一定要放在TextView上面,因为Button也继承了TextView
((Button) v).setTextSize(adjustFontSize + 2);
} else if (v instanceof TextView) {
if (v.getId() == resTitleId) {// 顶部标题
((TextView) v).setTextSize(adjustFontSize + 4);
} else {
((TextView) v).setTextSize(adjustFontSize);
}
}
}
}
// 获取字体大小
public static int adjustFontSize(int screenWidth, int screenHeight) {
screenWidth = screenWidth > screenHeight ? screenWidth : screenHeight;
/**
* 1. 在视图的 onsizechanged里获取视图宽度,一般情况下默认宽度是320,所以计算一个缩放比率 rate = (float)
* w/320 w是实际宽度 2.然后在设置字体尺寸时 paint.setTextSize((int)(8*rate));
* 8是在分辨率宽为320 下需要设置的字体大小 实际字体大小 = 默认字体大小 x rate
*/
int rate = (int) (5 * (float) screenWidth / 320); // 我自己测试这个倍数比较适合,当然你可以测试后再修改
return rate < 15 ? 15 : rate; // 字体太小也不好看的
}
// 最后在Avtivity的oncreate完后调用一下changeViewSize就行了。。。文字大了那么它对应的背景也就跟着大,所以建议控件的背景图片用9宫格类型的图片,看起来舒服。
// 另外附加,如果你开发的应用想在平板电脑上浏览无碍请在AndroidManifest.xml文件中的manifest节点(DTD建议放在application节点上面)里加入:
// <supports-screens
// android:anyDensity="true"
// android:largeScreens="true"
// android:normalScreens="true"
// android:smallScreens="true"
// android:resizeable="true"/>
}
|
JavaScript
|
UTF-8
| 444
| 2.640625
| 3
|
[] |
no_license
|
import React from 'react';
const Cart = (props) => {
const cart = props.cart;
//console.log(cart);
let total=0;
for(let i=0;i<cart.length;i++){
const product = cart[i];
total=total+product.price;
}
return (
<div>
<h4>Order Summary</h4>
<p>Items Ordered: {cart.length}</p>
<p>Total Price: {total}</p>
</div>
);
};
export default Cart;
|
Markdown
|
UTF-8
| 2,163
| 2.859375
| 3
|
[
"MIT",
"CC-BY-SA-3.0"
] |
permissive
|
## Examples
Welcome to the code examples section!
Here you'll find usage examples and recipes. For a full list of examples, take a look in our
[storybook page](https://researchgate.github.io/react-intersection-observer/?selectedKind=Examples).
* [Basic usage on Window](https://researchgate.github.io/react-intersection-observer/?selectedKind=Examples&selectedStory=Window)
* [Usage within a scroller/frame](https://researchgate.github.io/react-intersection-observer/?selectedKind=Examples&selectedStory=Frame)
* [Using thresholds](https://researchgate.github.io/react-intersection-observer/?selectedKind=Examples&selectedStory=Thresholds)
* [Using the rootMargin option](https://researchgate.github.io/react-intersection-observer/?selectedKind=Examples&selectedStory=Margin)
* [Unobserving the target after an intersection](https://researchgate.github.io/react-intersection-observer/?selectedKind=Examples&selectedStory=Once)
## Recipes
Here you
[will find useful code snippets](https://researchgate.github.io/react-intersection-observer/?selectedKind=Recipes) to
common situations that can be approached with ReactIntersectionObserver:
* [Higher Order Component](docs/components/HigherOrderComponent/)
* [Tracking Ad Impressions](docs/components/ImpressionTracking/)
* [Viewable Monitor](docs/components/ViewableMonitor/)
* [Graceful Degradation](docs/components/NativeObserver/)
### Can I submit a new recipe?
Yes, of course!
1. Fork the code repo.
2. Create your new recipe in the correct subfolder within `docs/docs/components/` (create a new folder if it doesn't
already exist).
3. Make sure you have included a README as well as your source file.
4. Submit a PR.
_If you haven't yet, please read our
[contribution guidelines](https://github.com/researchgate/react-intersection-observer/blob/master/.github/CONTRIBUTING.md)._
### What license are the recipes released under?
By default, all newly submitted code is licensed under the MIT license.
### How else can I contribute?
Recipes don't always have to be code - great documentation, tutorials, general tips and even general improvements to our
examples folder are greatly appreciated.
|
Python
|
UTF-8
| 859
| 2.640625
| 3
|
[] |
no_license
|
import enum_val as e_val
from SodukoClass import Soduko
import get
def update_rigt_arr(soduko):
key = e_val.Direction.Right
for n in range(0, len(soduko.S)):
soduko.pos_val[key].append(get.zero_right_line(n, soduko))
def update_down_arr(soduko):
key = e_val.Direction.Down
for n in range(0, len(soduko.S)):
soduko.pos_val[key].append(get.zero_down_line(n, soduko))
def update_square_arr(soduko):
key = e_val.Direction.Square
sq = soduko.squareSize
for n in range(0, sq):
for p in range(0, sq):
pos = ((p % sq) * sq, (n % sq) * sq)
rel = (0,0)
soduko.pos_val[key].append(get.zero_square(rel, pos, soduko))
def setup_dict(soduko):
soduko.pos_val = {
e_val.Direction.Down : [],
e_val.Direction.Right : [],
e_val.Direction.Square : []
}
|
Swift
|
UTF-8
| 578
| 2.609375
| 3
|
[] |
no_license
|
//
// PlayerViewCell.swift
// foostourney
//
// Created by Mahesh Chauhan on 14/10/19.
// Copyright © 2019 Mahesh Chauhan. All rights reserved.
//
import UIKit
// UITableViewCell to hold the content of a single player cell on SelectPlayersViewController.
class PlayerViewCell: UITableViewCell {
@IBOutlet weak var name: UILabel!
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
accessoryType = selected ? UITableViewCell.AccessoryType.checkmark : UITableViewCell.AccessoryType.none
}
}
|
C#
|
UTF-8
| 3,878
| 2.640625
| 3
|
[] |
no_license
|
using System;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
namespace MoveAppSettingsBetweenComputers
{
public partial class Form1 : Form
{
string sourceComputer;
string destinationComputer;
string userAccountToCopy;
int appSettingsLocationLineCount = File.ReadAllLines("appSettingsLocation.txt").Length;
public Form1()
{
InitializeComponent();
//checkBox1.Text = applocation1;
checkBox1.Text = valueFromFile("appSettingsLocation.txt", 0);
//checkBox2.Text = valueFromFile("appSettingsLocation.txt", 1);
//checkBox3.Text = returnCMDoutput("powershell.exe", "(Get-WmiObject -Class win32_bios).serialnumber");
checkBox4.Text = returnCMDoutput("cmd.exe", "/c hostname");
proceedButton.Enabled = true;
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
}
private string valueFromFile (string file,int lineNumber)
{
return File.ReadLines(file).Skip(lineNumber).Take(1).First();
}
private string returnCMDoutput(string command, string arguments)
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = @command;
//provide powershell script full path
startInfo.Arguments = @arguments;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
Process process = new Process();
process.StartInfo = startInfo;
// execute script call start process
process.Start();
// get output information
string output = process.StandardOutput.ReadToEnd();
// catch error information
string errors = process.StandardError.ReadToEnd();
return output;
}
private void performCMDinWindow(string command, string arguments)
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = @command;
//provide powershell script full path
startInfo.Arguments = @arguments;
startInfo.RedirectStandardOutput = false;
startInfo.RedirectStandardError = false;
startInfo.UseShellExecute = true;
startInfo.CreateNoWindow = false;
Process process = new Process();
process.StartInfo = startInfo;
// execute script call start process
process.Start();
}
private void oldComputer_TextChanged(object sender, EventArgs e)
{
sourceComputer = oldComputer.Text;
}
private void proceedButton_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(oldComputer.Text) || String.IsNullOrEmpty(newComputer.Text) || String.IsNullOrEmpty(userAccount.Text))
{
MessageBox.Show("Please provide missing information");
}
else { performCMDinWindow("cmd.exe", "/c script.bat" + " "
+ sourceComputer + " "
+ destinationComputer + " "
+ userAccountToCopy); }
}
private void userAccount_TextChanged(object sender, EventArgs e)
{
userAccountToCopy = userAccount.Text;
}
private void newComputer_TextChanged(object sender, EventArgs e)
{
destinationComputer = newComputer.Text;
}
}
}
|
C#
|
UTF-8
| 650
| 2.625
| 3
|
[] |
no_license
|
public class MainAbstractFactory{
public static void Main(string[] args){
AbstractFactory factoryWhite = FactoryCreator.createFactoryWhite();
AbstractFactory factoryBlack = FactoryCreator.createFactoryBlack();
Apartment whiteApartment = factoryWhite.createApartment();
Apartment blackApartment = factoryBlack.createApartment();
House whiteHouse = factoryWhite.createHouse();
House blackHouse = factoryBlack.createHouse();
whiteApartment.getApartmentColor();
blackApartment.getApartmentColor();
whiteHouse.getHouseColor();
blackHouse.getHouseColor();
}
}
|
C#
|
UTF-8
| 5,006
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
using Microsoft.Toolkit.Uwp.Notifications;
using Quickstart_Alarms.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Notifications;
namespace Quickstart_Alarms
{
public static class AlarmHelper
{
private const int DAYS_IN_ADVANCE_TO_SCHEDULE = 5;
public static void ScheduleAlarm(MyAlarm alarm)
{
EnsureScheduled(alarm, checkForExisting: false);
}
public static void RemoveAlarm(MyAlarm alarm)
{
var notifier = ToastNotificationManager.CreateToastNotifier();
var tag = GetTag(alarm);
// Find all of the scheduled toasts for the alarm
var scheduledNotifs = notifier.GetScheduledToastNotifications()
.Where(i => i.Tag.Equals(tag));
// Remove all of those from the schedule
foreach (var n in scheduledNotifs)
{
notifier.RemoveFromSchedule(n);
}
}
public static void EnsureScheduled(MyAlarm alarm)
{
EnsureScheduled(alarm, checkForExisting: true);
}
private static void EnsureScheduled(MyAlarm alarm, bool checkForExisting)
{
var notifier = ToastNotificationManager.CreateToastNotifier();
IReadOnlyList<ScheduledToastNotification> existing = null;
if (checkForExisting)
{
var tag = GetTag(alarm);
existing = notifier.GetScheduledToastNotifications()
.Where(i => i.Tag.Equals(tag))
.ToList();
}
DateTime now = DateTime.Now;
DateTime[] alarmTimes = GetAlarmTimesForAlarm(alarm);
foreach (var time in alarmTimes)
{
if (time.AddSeconds(5) > now)
{
// If the alarm isn't scheduled already
if (!checkForExisting || !existing.Any(i => i.DeliveryTime == time))
{
var scheduledNotif = GenerateAlarmNotification(alarm, time);
notifier.AddToSchedule(scheduledNotif);
}
}
}
}
private static string GetTag(MyAlarm alarm)
{
// Tag needs to be 16 chars or less, so hash the Id
return alarm.Id.GetHashCode().ToString();
}
private static ScheduledToastNotification GenerateAlarmNotification(MyAlarm alarm, DateTime alarmTime)
{
// Using NuGet package Microsoft.Toolkit.Uwp.Notifications
ToastContent content = new ToastContent()
{
Scenario = ToastScenario.Alarm,
Visual = new ToastVisual()
{
BindingGeneric = new ToastBindingGeneric()
{
Children =
{
new AdaptiveText()
{
Text = $"Alarm: {alarm.Name}"
},
new AdaptiveText()
{
Text = alarmTime.ToString()
}
}
}
},
Actions = new ToastActionsSnoozeAndDismiss()
};
// We can easily enable Universal Dismiss by generating a RemoteId for the alarm that will be
// the same on both devices. We'll just use the alarm delivery time. If an alarm on one device
// has the same delivery time as an alarm on another device, it'll be dismissed when one of the
// alarms is dismissed.
string remoteId = (alarmTime.Ticks / 10000000 / 60).ToString(); // Minutes
return new ScheduledToastNotification(content.GetXml(), alarmTime)
{
Tag = GetTag(alarm),
// RemoteId is a 1607 feature, if you support older systems, use ApiInformation to check if property is present
RemoteId = remoteId
};
}
private static DateTime[] GetAlarmTimesForAlarm(MyAlarm alarm)
{
if (alarm.IsOneTime())
{
return new DateTime[] { alarm.SingleFireTime };
}
else
{
DateTime today = DateTime.Today;
List<DateTime> answer = new List<DateTime>();
for (int i = 0; i < DAYS_IN_ADVANCE_TO_SCHEDULE; i++)
{
if (alarm.DaysOfWeek.Contains(today.DayOfWeek))
{
answer.Add(today.Add(alarm.TimeOfDay));
}
today = today.AddDays(1);
}
return answer.ToArray();
}
}
}
}
|
Java
|
UTF-8
| 113
| 1.632813
| 2
|
[
"MIT"
] |
permissive
|
package com.codingblocks.lecture_9.interfeace_example;
public interface TA extends Teacher, Student {
}
|
Markdown
|
UTF-8
| 528
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
# Projetos Python
Alguns projetos criados em Python
## Ping-Pong
Jogo que simula uma mesa de Ping-Pong 2D. Para executar é necessário ter instalado a boblioteca Pygame.
- Possíveis configurações no jogo
- Tamanho dos blocos
- Máximo de tentativas
- Escrevi um algoritmo que joga sozinho, para liga-lo deve trocar a variavel inicial 'joga_sozinho' para False
## Snake
Adaptação do jogo Snake para a linguagem Python.
- Possíveis configurações no jogo
- Tamanho dos blocos
- Máximo de tentativas
|
C++
|
UTF-8
| 1,461
| 2.796875
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
#pragma once
#include <list>
#include <string>
#include "math/Vector2.h"
namespace gfx
{
namespace gui
{
class Gui;
class GuiElement
{
public:
GuiElement(Gui & gui, GuiElement * parent, math::Vector2i position = math::Vector2i(0, 0));
virtual ~GuiElement();
virtual void animate(double deltaTime);
virtual void draw();
virtual bool onMouseButtonPressed(uint8_t button, int x, int y);
virtual bool onMouseButtonReleased(uint8_t button, int x, int y);
virtual bool onMouseMoved(int x, int y);
virtual void onVisibilityChange(bool isVisible);
void addChild(GuiElement * child);
bool removeChild(GuiElement * childToRemove);
std::list<GuiElement *> const & getChildren() const { return children; };
GuiElement * getParent() const { return parent; };
void setParent(GuiElement * newParent);
bool isVisible() const { return !hidden; };
void hide() { hidden = true; onVisibilityChange(!hidden); };
void show() { hidden = false; onVisibilityChange(!hidden); };
bool isTrulyVisible() const;
math::Vector2i getPosition() const { return position; };
void setPosition(math::Vector2i position) { this->position = position; };
math::Vector2i getAbsolutePosition() const { return absolutePosition; };
void updateAbsolutePosition();
private:
GuiElement * parent;
std::list<GuiElement *> children;
math::Vector2i position;
math::Vector2i absolutePosition;
bool hidden;
protected:
Gui & gui;
};
} // namespace gui
} // namespace gfx
|
Python
|
UTF-8
| 316
| 3.21875
| 3
|
[] |
no_license
|
import os
import glob
# Function to rename multiple files
def main():
for file in glob.glob('*-&-*'):
src = os.path.basename(file)
dest = src.replace("-&-", "-")
os.rename(src, dest)
print(dest)
# Driver Code
if __name__ == '__main__':
# Calling main() function
main()
|
C++
|
UTF-8
| 247
| 2.578125
| 3
|
[] |
no_license
|
#ifndef PLANET_
#define PLANET_
#include <string>
#include <iostream>
class Planet{
private:
int time_s;
std::string _name;
public:
void set_time(int);
void set_name(std::string);
int get_time();
std::string get_name();
};
#endif
|
C
|
UTF-8
| 1,241
| 3.15625
| 3
|
[] |
no_license
|
#include <stdio.h>
#include "another.h"
#include <stdlib.h>
int main(){
tryGess();
printf("\nNext task is about matrix from thierd lab\n");
matrixShort();
return 0;
}
void matrixShort(){
int n,m,i,j;
int *a = NULL;
printf("Input rows: ");
scanf("%d", &n);
printf("Input colons: ");
scanf("%d", &m);
a = (int*)malloc(n*m*sizeof(int));
for(i =0; i<n; i++){
for(j= 0; j<m;j++){
printf("a[%d][%d] : ", i,j);
scanf("%d",(a + i*m + j));
}
}
showMatrix(a, n ,m);
printf("%d",seekNumOfStrLongestSeq(a, n, m));
free(a);
}
int seekNumOfStrLongestSeq(int *a, int n, int m){
int maxl=0,l,strNum;
for(int i=0;i<n;i++){
l=0;
for(int j=0;j<m;j++){
l=0;
for(int e=j; e<m-1; e++){
if(*(a + i*m + e) == *(a + i*m + e+1)){
l+=1;
}
if(l>maxl){
maxl=l;
strNum=i;
}
}
}
}
return strNum;
}
void tryGess(){
int l = 1, r =10, m ,flag;
printf("Make up the number from %d to %d \n", l ,r);
while(1){
m = (r+ l)/2;
printf("If it is yours : %d , press '0'\nif it is so hight press 1,\nif it is so low, press -1\n", m);
scanf("%d", &flag);
if(flag == 0){
break;
}
if(flag == 1){
r = m-1;
}
if(flag == -1){
l = m+1;
}
else{
continue;
}
}
}
|
Java
|
UTF-8
| 6,842
| 2.40625
| 2
|
[] |
no_license
|
/*
* @(#)MailboxConnection.java 1.00 2005/02/05
*
* Copyright (c) 2005, Stephan Sann
*
* 05.02.2005 ssann Vers. 1.0 created
*/
package de.lotk.yawebmail.business;
import java.io.Serializable;
import java.util.TreeSet;
import javax.mail.Folder;
import javax.mail.Message;
import de.lotk.yawebmail.application.Lifecycle;
import de.lotk.yawebmail.bean.LoginDataBean;
import de.lotk.yawebmail.bean.RetrieveMessagesResultBean;
import de.lotk.yawebmail.exceptions.AccessDeniedException;
import de.lotk.yawebmail.exceptions.ConnectionEstablishException;
import de.lotk.yawebmail.exceptions.LogoutException;
import de.lotk.yawebmail.exceptions.MailboxFolderException;
import de.lotk.yawebmail.exceptions.MessageDeletionException;
import de.lotk.yawebmail.exceptions.MessageMovementException;
import de.lotk.yawebmail.exceptions.MessageRetrieveException;
import de.lotk.yawebmail.exceptions.YawebmailCertificateException;
/**
* Stellt Methoden zur Abfrage einer Mailbox bereit.
*
* @author Stephan Sann
* @version 1.0
*/
public interface MailboxConnection extends Lifecycle, Serializable {
// ----------------------------------------------------- oeffentliche Methoden
/**
* Setzt die Login-Daten fuer diese Mailbox-Connection.
*/
public void setLoginData(LoginDataBean loginData);
/**
* Fuehrt ein Login am Mailbox-Host aus.
*/
public void login() throws ConnectionEstablishException,
AccessDeniedException, YawebmailCertificateException;
/**
* Fuehrt ein Login am Mailbox-Host aus und wechselt in den uebergebenen
* Ordner.
*
* @param folderName Names des Ordners, in den gewechselt werden soll.
*/
public void login(String folderName) throws ConnectionEstablishException,
AccessDeniedException, MailboxFolderException,
YawebmailCertificateException;
/**
* Fuehrt ein Logout am Mailbox-Host aus.
*/
public void logout() throws LogoutException;
/**
* Testet ob mit den Daten eines LoginDataBean-Objektes ein Login
* durchgefuehrt werden kann.<br/>
* Wenn diese Methode keine Exception wirft kann davon ausgegangen werden,
* dass ein Login moeglich ist.
*/
public void validateLoginData() throws ConnectionEstablishException,
AccessDeniedException, YawebmailCertificateException;
/**
* Liefert den aktuellen Mailfolder als "javax.mail.Folder"-Objekt.
*
* @return Aktuelles <code>Folder</code>-Objekt.
*/
public Folder getCurrentFolder() throws MailboxFolderException;
/**
* Wechselt den aktuellen Mailfolder.
*
* @param folderName Folder, in den gewechselt werden soll.
*/
public void changeFolder(String folderName) throws MailboxFolderException;
/**
* Retrieves all messages of the current folder.
*
* @return <code>RetrieveMessagesResultBean</code> containig all messages.
*/
public RetrieveMessagesResultBean getMessages() throws MailboxFolderException,
MessageRetrieveException;
/**
* Get the Message objects for message numbers ranging from start
* through end, both start and end inclusive. Note that message
* numbers start at 1, not 0.
*
* @param aStartNumber The number of the first message
* @param anEndNumber The number of the last message
* @param adjustParameters This enables the method to adjust the start-
* and/or teh end-number if they are out of range
* of the messages in the current folder.
* @return <code>RetrieveMessagesResultBean</code> containig all messages.
*/
public RetrieveMessagesResultBean getMessages(int aStartNumber, int
anEndNumber, boolean adjustParameters) throws MailboxFolderException,
MessageRetrieveException;
/**
* Liefert eine Nachricht aus dem aktuell gewaehlten Folder.
*
* @return <code>Message</code> gemaess Parameter.
*/
public Message getMessage(int messageNumber) throws MailboxFolderException,
MessageRetrieveException;
/**
* Retrieves the envelopes of all messages in the current folder.
*
* @return <code>RetrieveMessagesResultBean</code> containig all envelopes.
*/
public RetrieveMessagesResultBean getEnvelopes() throws
MailboxFolderException, MessageRetrieveException;
/**
* Get the Message objects filled with the Envelope-data for teh message
* numbers ranging from start through end, both start and end inclusive. Note
* that message numbers start at 1, not 0.
*
* @param aStartNumber The number of the first message
* @param anEndNumber The number of the last message
* @param adjustParameters This enables the method to adjust the start-
* and/or teh end-number if they are out of range
* of the messages in the current folder.
* @return <code>RetrieveMessagesResultBean</code> containig all envelopes.
*/
public RetrieveMessagesResultBean getEnvelopes(int aStartNumber, int
anEndNumber, boolean adjustParameters) throws MailboxFolderException,
MessageRetrieveException;
/**
* Markiert eine Mail im aktuell gewaehlten Folder als geloescht.
*
* @param messageNumber Die zu loeschende Message.
*/
public void setDeletedFlag(int messageNumber) throws MailboxFolderException,
MessageDeletionException;
/**
* Markiert mehrere Mails im aktuell gewaehlten Folder als geloescht.
*
* @param messageNumbers Die zu loeschenden Messages.
*/
public void setMultipleDeletedFlags(int[] messageNumbers) throws
MailboxFolderException, MessageDeletionException;
/**
* Liefert den Delimiter, der Folder von Unter-Foldern trennt. Darf erst
* aufgerufen werden, wenn zumindest einmal ein Login erfolgt ist.
*/
public char getFolderSeparator() throws Exception;
/**
* Liefert ein TreeSet mit allen Foldern des Accounts.
*
* @return <code>TreeSet</code>-Objekt mit Foldern des Accounts.
*/
public TreeSet getAllFolders() throws Exception;
/**
* Erstellt einen neuen Ordner.
*
* @param folderName Name des zu erstellenden Folders.
*/
public void createFolder(String folderName) throws MailboxFolderException;
/**
* Loescht einen bestehenden Ordner.
*
* @param folderName Name des zu loeschenden Folders.
*/
public void deleteFolder(String folderName) throws MailboxFolderException;
/**
* Verschiebt Messages in einen anderen Ordner.
*
* @param messageNumbers Die zu verschiebenden Messages.
* @param targetFolderName Name des Ziel-Ordners
*/
public void moveMessages(int[] messageNumbers, String targetFolderName) throws
MailboxFolderException, MessageMovementException;
}
|
PHP
|
UTF-8
| 2,630
| 2.546875
| 3
|
[
"Apache-2.0"
] |
permissive
|
<?php
namespace execut\widget\dropdownContent;
use yii\helpers\Html;
use yii\jui\InputWidget;
/**
* Widget for render custom dropdown
*
* @author eXeCUT
*/
class DropdownContent extends InputWidget
{
/**
* Flag for use less compiler
*
* @var bool
*/
public $isDebugMode = false;
/**
* Options for container object
*
* @var array
*/
public $containerOptions = [];
/**
* Template for render widget
*
* @var string
*/
public $template = '{input}{container}';
/**
* Html options for html input of dropdown
*
* @var array
*/
public $inputOptions = [];
/**
* Renders the widget.
*/
public function run()
{
DropdownContentAsset::$isDebugMode = $this->isDebugMode;
DropdownContentAsset::register($this->view);
$parts = [
'{input}' => $this->renderWidget(),
'{container}' => $this->renderContainer()
];
$result = strtr($this->template, $parts);
$options = [
'id' => $this->id,
];
Html::addCssClass($options, 'dropdown-content');
echo Html::tag('div', $result, $options);
$this->registerWidget('dropdownContent', $this->id);
}
/**
* Render container
*
* @return string
*/
public function renderContainer() {
return $this->getContainer()->render();
}
/**
* Get dropdown container
*
* @return Container
*/
public function getContainer() {
$container = \yii::createObject(array_merge([
'class' => Container::className(),
], $this->containerOptions, [
'owner' => $this,
]));
return $container;
}
/**
* Renders the dropdown widget.
*
* @return string the rendering result.
*/
public function renderWidget()
{
$result = '<div class="dropdown-wrapper">';
$options = [
'autocomplete' => 'off'
];
if ($this->hasModel()) {
$result .= Html::activeHiddenInput($this->model, $this->attribute, $options);
} else {
$result .= Html::hiddenInput($this->name, $this->value, $options);
}
$result .= Html::textInput($this->id . '_input', null, array_merge([
'class' => [
'form-control'
],
'autocomplete' => 'off',
], $this->inputOptions)) . '<div class="controll-wrapper"><span class="caret"></span><span class="clear">×</span></div></div>';
return $result;
}
}
|
Java
|
UTF-8
| 1,048
| 2.359375
| 2
|
[] |
no_license
|
package com.example.RedditClone.users;
import com.example.RedditClone.helpers.Parameters;
import com.example.RedditClone.helpers.Redirects;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet(name = "UserLogoutServlet", value = "/user-logout")
public class UserLogoutServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession session = request.getSession(true);
User sessionUser = (User)session.getAttribute(Parameters.SessionParams.sessionUser);
if (sessionUser != null)
{
session.removeAttribute(Parameters.SessionParams.sessionUser);
}
response.sendRedirect(Redirects.UserRedirects.userLogin);
}
}
|
C++
|
UTF-8
| 448
| 2.546875
| 3
|
[] |
no_license
|
#include <iostream>
using namespace std;
int main()
{
long long int t;
cin>>t;cout<<endl;
for(int i=0;i<t;i++)
{
long long int n,sum=0;
cin>>n;
long long int a[n];
for(int j=0;j<n;j++)
cin>>a[j];
cout<<endl;
for(int j=0;j<n;j++)
sum=sum+a[j];
if(sum%n==0)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
return 0;
}
|
Markdown
|
UTF-8
| 4,457
| 4.03125
| 4
|
[] |
no_license
|
# 解析式:
问题引入:
对一个列表里所有数值求平方;
lst = list(range(10))
## 列表解析:
之所以叫列表解析是因为得到的结果是list,迭代的对象可以是任意可迭代对象;
列表解析中,不支持break语句,自然也不支持for...else语句;
[ expression for e in iterator]
```python
lst = list(range(10))
ret = []
for x in lst:
ret.append(x ** 2)
ret = [ x ** 2 for x in lst]
```
* 代码简介,可读性强;
* 效率比普通迭代稍高;
```python
[expression for e in iterator if condision]
```
```python
lst = list(range(10))
ret = list()
In [9]: %%timeit
...: for x in lst:
...: if x % 2 == 0:
...: ret.append(x)
...:
1000000 loops, best of 3: 1.67 µs per loop
In [11]: %%timeit
...: [ ret.append(x) for x in lst if x % 2 == 0]
...:
100000 loops, best of 3: 2.33 µs per loop
```
* 带多个if
- 多个if间默认为and关系;
ret = [ x for x in lst if x > 0 if x < 5 if x % 2 == 0]
```python
ret = []
for x in lst:
if x > 0:
if x < 5:
if x % 2 == 0:
ret.append(x)
```
- 多个if语句的,都可以转换为条件的逻辑运算,所以一般来说,不会带多个if语句;
* 也可以带多个for语句:
[(x,y) for x in range(5) for y in range(5,10)]
相当于逐层嵌套;
```python
ret = []
for x in range(5):
for y in range(5,10):
ret.append((x,y))
```
```python
多个for语句,也可跟多个if语句;
[(x,y) for x in range(5) if x > 0 for y in range(5,10) if y < 9]
```
使用列表解析的目的是为了让代码更简洁。
```python
[x for x in [y for y in range(10)]]
```
跟着感觉走,如果解析式不能让代码更简洁的情况下,就不要再使用了;
一眼看不出解析式的结果是什么的时候,就不要用了;
---
---
问题引入:
偶数求平方,奇数求立方;
## if表达式:
**x if cond else y**
当条件满足时返回x,当条件不满足时返回y;
使用该表达式与列表解析式结合使用:
[x ** 2 if x % 2 == 0 else x ** 3 for x in lst]
```python
ret = []
for x in lst:
if x % 2 == 0:
ret.append(x ** 2)
else:
ret.append(x ** 3)
```
```python
x = 3
x ** 2 if x % 2 == 0 else x ** 3
ret = 0
if x % 2 == 0:
ret = x ** 2
else:
ret = x ** 3
```
---
---
## 生成器解析:
列表解析返回的是列表;
range(10000000)
并非马上生成了所有元素;
列表解析是马上生成了所有元素;
(x ** 2 for x in range(10000))
列表解析的中括号变成小括号;
生成器解析式返回的是一个生成器;
```python
g = (x ** 2 for x in range(100000000000))
```
生成器只有在取值的时候才开始计算;
### 什么时候用列表解析,什么时候用生成器解析?
需要用下标访问的时候,用列表解析;
只需要对结果迭代的时候,优先使用生成器解析;
---
---
## 集合解析:
{x for x in range(10)}
s = { x for x in range(10)}
操作和列表解析式一样的;
---
---
## 字典解析
{ str(key): v for key in range(10) for v in range(11,20)}
## 迭代器:
可迭代对象:
r = range(5)
r.__iter__()
可迭代对象,都拥有__iter__()方法;
for x in range(5):
pass
for in 语句要求遍历一个可迭代对象;
可迭代对象:
7种数据结构;
range
dict.keys
dict.items
dict.values
### 迭代器是可迭代对象;
it = iter(range(5))
有__next__方法的可迭代对象叫迭代器;
上述可迭代对象中,没有迭代器;
**可迭代对象可以转换为迭代器**
iter()函数可以把一个可迭代对象转换为迭代器;
**为什么要转换?**
next函数可以从迭代器中取出下一个元素;
迭代器会保存一个指针,指向可迭代对象的当前元素;
调用next函数的时候,会返回当前元素,并且把指针指向下一个元素;
当没有下一个元素时,会抛出StopIteration异常;
**for in循环可迭代对象; 首先调用iter方法转换为迭代器,然后不断的调用next方法,知道抛出StopIteration异常**
```python
# 迭代器的实现:
it = iter(iteratable):
while True:
try:
next(it)
except StopIteration:
return
```
|
C#
|
UTF-8
| 687
| 3.71875
| 4
|
[] |
no_license
|
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class Test
{
public static void Main()
{
var lists = new List<List<int>>
{
new List<int> { 1, 2, 3 }, // 6
new List<int> { 3 }, // 3
new List<int> { 3, 3 }, // 6
new List<int> { 1, 2 }, // 3
new List<int> { 6 } // 6
};
Console.WriteLine(lists.GetSumList(6).Count); // 3
}
}
public static class ListHelpers
{
public static List<List<int>> GetSumList(this List<List<int>> list, int sum)
{
return list.Where(x => x.Sum() == sum).ToList();
}
}
|
C#
|
UTF-8
| 1,493
| 2.921875
| 3
|
[] |
no_license
|
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace Assets
{
[Serializable()]
public class RespondMovement
{
private int dice;
private int tokenID;
public int Dice
{
get
{
return dice;
}
set
{
dice = value;
}
}
public int TokenID
{
get
{
return tokenID;
}
set
{
tokenID = value;
}
}
public string SerializeObject()
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream memStr = new MemoryStream();
try
{
bf.Serialize(memStr, this);
memStr.Position = 0;
return Convert.ToBase64String(memStr.ToArray());
}
finally
{
memStr.Close();
}
}
public RespondMovement DeserializeObject(string str)
{
BinaryFormatter bf = new BinaryFormatter();
byte[] b = Convert.FromBase64String(str);
MemoryStream ms = new MemoryStream(b);
try
{
return (RespondMovement)bf.Deserialize(ms);
}
finally
{
ms.Close();
}
}
}
}
|
Python
|
UTF-8
| 256
| 2.71875
| 3
|
[] |
no_license
|
N = int(input())
P = [int(input()) for _ in range(N)]
V = [-1] * (N+1)
for i in range(N):
V[P[i]] = i+1
# print(V)
c = 0
ans = 0
for i in range(1, N+1):
if V[i-1] > V[i]:
c = 1
else:
c += 1
ans = max(c, ans)
print(N-ans)
|
Java
|
UTF-8
| 3,818
| 2.734375
| 3
|
[] |
no_license
|
package com.alex.gl.shape;
import static org.lwjgl.opengl.GL11.*;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.ARBMultisample;
import org.lwjgl.opengl.Display;
import org.lwjgl.util.Point;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: elenaliux
* Date: 8/18/13
* Time: 7:20 PM
*/
public class ShapeTool {
static int spin;
/**
* Serpinsky triangle.
*/
public static void serpinsky() {
Point[] points = new Point[]{new Point(10, 10), new Point(700, 20), new Point(400, 600)};
for (int i = 0; i < 3; i++) {
drawDot(points[i].getX(), points[i].getY());
}
drawTriangle(points[0], points[1], points[2], 10);
glFlush();
}
private static void drawTriangle(Point p1, Point p2, Point p3, int level) {
if (level > 0) {
Point p12 = createPoint(p1, p2);
Point p13 = createPoint(p1, p3);
Point p23 = createPoint(p2, p3);
drawDot(p12.getX(), p12.getY());
drawDot(p23.getX(), p23.getY());
drawDot(p13.getX(), p13.getY());
drawTriangle(p1, p12, p13, level - 1);
drawTriangle(p2, p12, p23, level - 1);
drawTriangle(p3, p23, p13, level - 1);
} else {
return;
}
}
/**
* Draws dot.
* @param x - coord X
* @param y - coord Y
*/
public static void drawDot(int x, int y) {
glBegin(GL_POINTS);
glVertex2i(x, y);
glEnd();
}
/**
* Draws cube.
*/
public static void drawCube() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPolygonMode(GL_BACK, GL_LINE);
glEnable(GL_CULL_FACE);
glCullFace(GL_FRONT);
glPushMatrix();
glTranslated(100, 100, 0);
glRotated(spin, 1, 1, 1);
glBegin(GL_QUAD_STRIP);
draw();
glEnd();
glPopMatrix();
glFlush();
}
private static void draw() {
glVertex3i(-50, -50, 50);
glVertex3i(-50, 50, 50);
glVertex3i(50, -50, 50);
glVertex3i(50, 50, 50);
glVertex3i(50, -50, -50);
glVertex3i(50, 50, -50);
glVertex3i(-50, -50, -50);
glVertex3i(-50, 50, -50);
glVertex3i(-50, -50, 50);
glVertex3i(-50, 50, 50);
}
/**
* Draw polygon.
*
* @param points - list of points.
*/
public static void drawPoly(List<Point> points) {
glBegin(GL_LINE_STRIP);
for (Point point : points) {
glVertex2i(point.getX(), point.getY());
}
glEnd();
}
/**
* Draws chess board.
* @param width - width
* @param height - height
*/
public static void drawChessBoard(int width, int height) {
int rwidth = width / 8;
int rheight = height / 8;
int draw = -1;
glColor3f(0, 0, 0);
for (int j = 0; j < 8; j++) {
for (int i = 0; i < 8; i++) {
int x = i * rwidth;
int y = j * rheight;
if (draw > 0) {
glRecti(x, y, x + rwidth, y + rheight);
}
draw *= -1;
}
draw *= -1;
}
}
private static Point createPoint(Point p, Point p2) {
return new Point(((p.getX() + p2.getX()) / 2), (p.getY() + p2.getY()) / 2);
}
/**
* Animator inner class.
*/
public static class Animator extends Thread {
public void run() {
try {
while (!Thread.interrupted()) {
Thread.sleep(50);
spin += 1;
if (spin > 360) spin -= 360;
}
} catch (InterruptedException e) {
}
}
}
}
|
Python
|
UTF-8
| 651
| 3.046875
| 3
|
[] |
no_license
|
from datetime import datetime, timedelta
from time import sleep
def runAndWait(function, duration):
'''run a function and wait until its given quota runs out
@param function:function function to be called
@param duration:int duration of quota in milliseconds
'''
stop = datetime.now() + \
timedelta(milliseconds=duration)
function()
remaining = stop - datetime.now()
if remaining.days < 0: # input processing needed too long
remaining = -1
else:
remaining = round(remaining.microseconds / 1000000, 3)
if remaining > 0:
sleep(remaining)
|
Java
|
UTF-8
| 4,075
| 2.671875
| 3
|
[
"Apache-2.0"
] |
permissive
|
package org.spiderland.Psh.BitstringGA;
import java.util.ArrayList;
import org.spiderland.Psh.GA;
import org.spiderland.Psh.GAIndividual;
abstract public class BitstringGA extends GA {
private static final long serialVersionUID = 1L;
protected int _size;
protected String _GAMutationMode;
protected float _GAMutationPercent;
protected void InitFromParameters() throws Exception {
_size = (int) GetFloatParam("bitstring-size");
String defaultGAMutationMode = "one-bit";
float defaultGAMutationPercent = 10.0f;
_GAMutationMode = GetParam("ga-mutation-mode", true);
if (_GAMutationMode == null) {
_GAMutationMode = defaultGAMutationMode;
}
if (!_GAMutationMode.equals("one-bit") && !_GAMutationMode.equals("per-bit")){
throw new Exception("ERROR: ga-mutation-mode must be set to one-bit or per-bit." +
"\nCurrently set to " + _GAMutationMode);
}
_GAMutationPercent = GetFloatParam("ga-mutation-percent", true);
if (Float.isNaN(_GAMutationPercent)) {
_GAMutationPercent = defaultGAMutationPercent;
}
super.InitFromParameters();
}
@Override
protected void InitIndividual(GAIndividual inIndividual) {
BitstringGAIndividual bgai = (BitstringGAIndividual) inIndividual;
ArrayList<Boolean> bits = new ArrayList<Boolean>();
for(int i = 0; i < _size; i++){
bits.add(_RNG.nextBoolean());
}
bgai.setBitstring(bits);
}
@Override
protected String Report() {
String report = super.Report();
report += "Best individual: "
+ _populations[_currentPopulation][_bestIndividual] + "\n";
report += "Best fitness: " + _bestMeanFitness + "\n\n";
// Find worst individual that was allowed to reproduce
int worstIndividual = 0;
float worstFitness = _populations[_currentPopulation][0].GetFitness();
for(int i = 1; i < _survivalPopulationSize; i++){
if(_populations[_currentPopulation][i].GetFitness() > worstFitness){
worstIndividual = i;
worstFitness = _populations[_currentPopulation][i].GetFitness();
}
}
report += "Worst reproducing individual: "
+ _populations[_currentPopulation][worstIndividual] + "\n";
report += "Worst reproducing individual's fitness: " + worstFitness + "\n\n";
report += "Population mean fitness: " + _populationMeanFitness + "\n";
report += ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n\n";
return report;
}
@Override
protected String FinalReport() {
String report = super.FinalReport();
if (Success()) {
report += "Successful individual: "
+ _populations[_currentPopulation][_bestIndividual] + "\n";
} else {
report += "Best failed individual: "
+ _populations[_currentPopulation][_bestIndividual] + "\n";
}
report += "Fitness: " + _bestMeanFitness + "\n";
return report;
}
/**
* One-point crossover.
*/
@Override
protected GAIndividual ReproduceByCrossover(int inIndex) {
BitstringGAIndividual a = (BitstringGAIndividual) ReproduceByClone(inIndex);
BitstringGAIndividual b = (BitstringGAIndividual) TournamentSelect(
_tournamentSize, inIndex);
int size = a._bits.size();
// index represents the index of the cut. The resulting child will be
// a from 0 to index - 1 with b from index to size - 1 appended.
int index = _RNG.nextInt(size - 1) + 1;
for(int i = index; i < size; i++){
a._bits.set(i, b._bits.get(i));
}
return a;
}
/**
* Single-point bit flip mutation.
*/
@Override
protected GAIndividual ReproduceByMutation(int inIndex) {
BitstringGAIndividual a = (BitstringGAIndividual) ReproduceByClone(inIndex);
if (_GAMutationMode.equals("one-bit")) {
int index = _RNG.nextInt(a._bits.size());
boolean flipped = !a._bits.get(index);
a._bits.set(index, flipped);
}
if(_GAMutationMode.equals("per-bit")){
for(int i = 0; i < a._bits.size(); i++){
if(_RNG.nextInt(100) <= _GAMutationPercent){
a._bits.set(i, !a._bits.get(i));
}
}
}
return a;
}
}
|
C++
|
UHC
| 523
| 2.78125
| 3
|
[] |
no_license
|
#include <string>
#include <vector>
#include <queue>
using namespace std;
int solution(vector<int> scoville, int K) {
int answer = 0;
int n, m;
priority_queue<int,vector<int>,greater<int>> q;
for(int i = 0; i<scoville.size(); i++){
q.push(scoville[i]);
}
while(q.top() < K && q.size() > 1) {
n = q.top(); q.pop();
m = q.top(); q.pop();
q.push(n+2*m);
answer++;
}
if(q.top()<K) return -1;
return answer;
}
//priority_queue
|
Java
|
UTF-8
| 17,423
| 1.882813
| 2
|
[] |
no_license
|
package me.firerising.campmc.claim;
import com.songoda.core.compatibility.CompatibleMaterial;
import com.songoda.core.compatibility.CompatibleSound;
import com.songoda.core.compatibility.ServerVersion;
import com.songoda.core.utils.PlayerUtils;
import me.firerising.campmc.Main;
import me.firerising.campmc.events.ClaimDeleteEvent;
import me.firerising.campmc.events.ClaimTransferOwnershipEvent;
import me.firerising.campmc.claim.region.ClaimCorners;
import me.firerising.campmc.claim.region.ClaimedChunk;
import me.firerising.campmc.claim.region.ClaimedRegion;
import me.firerising.campmc.claim.region.RegionCorners;
import me.firerising.campmc.member.ClaimMember;
import me.firerising.campmc.member.ClaimPerm;
import me.firerising.campmc.member.ClaimPermissions;
import me.firerising.campmc.member.ClaimRole;
import me.firerising.campmc.settings.Settings;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.boss.BarColor;
import org.bukkit.boss.BarStyle;
import org.bukkit.boss.BossBar;
import org.bukkit.entity.Player;
import java.util.*;
public class Claim {
private int id;
private String name = null;
private Main owner;
private final Set<Main> members = new HashSet<>();
private final Set<ClaimedRegion> claimedRegions = new HashSet<>();
private final Set<UUID> bannedPlayers = new HashSet<>();
private Location home = null;
private boolean locked = false;
private final ClaimSettings claimSettings = new ClaimSettings()
.setEnabled(ClaimSetting.HOSTILE_MOB_SPAWNING, Settings.DEFAULT_CLAIM_HOSTILE_MOB_SPAWN.getBoolean())
.setEnabled(ClaimSetting.FIRE_SPREAD, Settings.DEFAULT_CLAIM_FIRE_SPREAD.getBoolean())
.setEnabled(ClaimSetting.MOB_GRIEFING, Settings.DEFAULT_CLAIM_MOB_GRIEFING.getBoolean())
.setEnabled(ClaimSetting.LEAF_DECAY, Settings.DEFAULT_CLAIM_LEAF_DECAY.getBoolean())
.setEnabled(ClaimSetting.PVP, Settings.DEFAULT_CLAIM_PVP.getBoolean())
.setEnabled(ClaimSetting.TNT, Settings.DEFAULT_CLAIM_TNT.getBoolean())
.setEnabled(ClaimSetting.FLY, Settings.DEFAULT_CLAIM_FLY.getBoolean());
private ClaimPermissions memberPermissions = new ClaimPermissions()
.setAllowed(ClaimPerm.BREAK, Settings.DEFAULT_MEMBER_BREAK.getBoolean())
.setAllowed(ClaimPerm.INTERACT, Settings.DEFAULT_MEMBER_INTERACT.getBoolean())
.setAllowed(ClaimPerm.PLACE, Settings.DEFAULT_MEMBER_PLACE.getBoolean())
.setAllowed(ClaimPerm.MOB_KILLING, Settings.DEFAULT_MEMBER_MOB_KILL.getBoolean())
.setAllowed(ClaimPerm.REDSTONE, Settings.DEFAULT_MEMBER_REDSTONE.getBoolean())
.setAllowed(ClaimPerm.DOORS, Settings.DEFAULT_MEMBER_DOORS.getBoolean())
.setAllowed(ClaimPerm.TRADING, Settings.DEFAULT_MEMBER_TRADE.getBoolean());
private ClaimPermissions visitorPermissions = new ClaimPermissions()
.setAllowed(ClaimPerm.BREAK, Settings.DEFAULT_VISITOR_BREAK.getBoolean())
.setAllowed(ClaimPerm.INTERACT, Settings.DEFAULT_VISITOR_INTERACT.getBoolean())
.setAllowed(ClaimPerm.PLACE, Settings.DEFAULT_VISITOR_PLACE.getBoolean())
.setAllowed(ClaimPerm.MOB_KILLING, Settings.DEFAULT_VISITOR_MOB_KILL.getBoolean())
.setAllowed(ClaimPerm.REDSTONE, Settings.DEFAULT_VISITOR_REDSTONE.getBoolean())
.setAllowed(ClaimPerm.DOORS, Settings.DEFAULT_VISITOR_DOORS.getBoolean())
.setAllowed(ClaimPerm.TRADING, Settings.DEFAULT_VISITOR_TRADE.getBoolean());
private PowerCell powerCell = new PowerCell(this);
private BossBar bossBarVisitor = null;
private BossBar bossBarMember = null;
public void setId(int id) {
this.id = id;
}
public int getId() {
return this.id;
}
public ClaimedChunk getFirstClaimedChunk() {
return this.claimedRegions.iterator().next().getFirstClaimedChunk();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
if (bossBarMember != null)
bossBarMember.setTitle(name);
if (bossBarVisitor != null)
bossBarVisitor.setTitle(name);
}
public String getDefaultName() {
return Main.getInstance().getLocale()
.getMessage("general.claim.defaultname")
.processPlaceholder("name", owner.getName())
.getMessage();
}
public BossBar getVisitorBossBar() {
if (bossBarVisitor == null)
bossBarVisitor = Bukkit.getServer().createBossBar(this.name, BarColor.YELLOW, BarStyle.SOLID);
return bossBarVisitor;
}
public BossBar getMemberBossBar() {
if (bossBarMember == null)
bossBarMember = Bukkit.getServer().createBossBar(this.name, BarColor.GREEN, BarStyle.SOLID);
return bossBarMember;
}
public ClaimMember getOwner() {
return owner;
}
public ClaimMember setOwner(UUID owner) {
return this.owner = new ClaimMember(this, owner, null, ClaimRole.OWNER);
}
public ClaimMember setOwner(OfflinePlayer owner) {
return this.owner = new ClaimMember(this, owner.getUniqueId(), owner.getName(), ClaimRole.OWNER);
}
public boolean transferOwnership(OfflinePlayer newOwner) {
if (newOwner.getUniqueId() == owner.getUniqueId())
return false;
ClaimTransferOwnershipEvent event = new ClaimTransferOwnershipEvent(this, owner.getPlayer(), newOwner);
Bukkit.getPluginManager().callEvent(event);
if (event.isCancelled()) {
return false;
}
boolean wasNameChanged = name.equals(getDefaultName());
removeMember(newOwner.getUniqueId());
owner.setRole(ClaimRole.MEMBER);
addMember(owner);
setOwner(newOwner);
if (!wasNameChanged)
setName(getDefaultName());
return true;
}
public Set<ClaimMember> getMembers() {
return members;
}
public Set<ClaimMember> getOwnerAndMembers() {
Set<ClaimMember> members = new HashSet<>(this.members);
members.add(this.owner);
return members;
}
public ClaimMember addMember(ClaimMember member) {
this.members.add(member);
return member;
}
public ClaimMember addMember(OfflinePlayer player, ClaimRole role) {
ClaimMember newMember = new ClaimMember(this, player.getUniqueId(), player.getName(), role);
this.members.add(newMember);
return newMember;
}
public ClaimMember getMember(UUID uuid) {
if (owner.getUniqueId().equals(uuid))
return owner;
return members.stream()
.filter(member -> member.getUniqueId().equals(uuid))
.findFirst()
.orElse(null);
}
/**
* Search for a member by username
*
* @param name name to search
* @return Member instance matching this username, if any
*/
public ClaimMember getMember(String name) {
if (name == null) return null;
if (name.equals(owner.getName())) return owner;
return members.stream()
.filter(member -> name.equals(member.getName()))
.findFirst()
.orElse(null);
}
public ClaimMember getMember(OfflinePlayer player) {
return getMember(player.getUniqueId());
}
public void removeMember(UUID uuid) {
Optional<ClaimMember> optional = this.members.stream().filter(member -> member.getUniqueId().equals(uuid)).findFirst();
optional.ifPresent(this.members::remove);
}
public void removeMember(ClaimMember member) {
this.members.remove(member);
}
public void removeMember(OfflinePlayer player) {
this.removeMember(player.getUniqueId());
}
public boolean playerHasPerms(Player player, ClaimPerm claimPerm) {
ClaimMember member = getMember(player);
if (player.hasPermission("ultimateclaims.bypass.perms")
|| player.getUniqueId().equals(owner.getUniqueId())) return true;
if (member == null) return false;
return member.getRole() == ClaimRole.VISITOR && getVisitorPermissions().hasPermission(claimPerm)
|| member.getRole() == ClaimRole.MEMBER && getMemberPermissions().hasPermission(claimPerm);
}
public boolean isOwnerOrMember(OfflinePlayer player) {
if (player.getUniqueId().equals(owner.getUniqueId())) return true;
return this.members.stream().anyMatch(member -> member.getRole() == ClaimRole.MEMBER);
}
public boolean containsChunk(Chunk chunk) {
final String world = chunk.getWorld().getName();
return claimedRegions.stream().anyMatch(r -> r.containsChunk(world, chunk.getX(), chunk.getZ()));
}
public boolean containsChunk(String world, int chunkX, int chunkZ) {
return claimedRegions.stream().anyMatch(r -> r.containsChunk(world, chunkX, chunkZ));
}
public ClaimedRegion getPotentialRegion(Chunk chunk) {
ClaimedChunk newChunk = new ClaimedChunk(chunk);
return newChunk.getAttachedRegion(this);
}
public boolean addClaimedChunk(Chunk chunk, Player player) {
animateChunk(chunk, player, Material.EMERALD_BLOCK);
return addClaimedChunk(chunk.getWorld().getName(), chunk.getX(), chunk.getZ());
}
public boolean isNewRegion(Chunk chunk) {
return isNewRegion(chunk.getWorld().getName(), chunk.getX(), chunk.getZ());
}
public boolean isNewRegion(String world, int x, int z) {
ClaimedChunk newChunk = new ClaimedChunk(world, x, z);
return newChunk.getAttachedRegion(this) == null;
}
public boolean addClaimedChunk(String world, int x, int z) {
ClaimedChunk newChunk = new ClaimedChunk(world, x, z);
ClaimedRegion region = newChunk.getAttachedRegion(this);
if (region == null) {
claimedRegions.add(new ClaimedRegion(newChunk, this));
return true;
} else {
region.addChunk(newChunk);
newChunk.mergeRegions(this);
}
return false;
}
public void addClaimedRegion(ClaimedRegion region) {
claimedRegions.add(region);
}
public void removeClaimedRegion(ClaimedRegion region) {
claimedRegions.remove(region);
}
public ClaimedChunk removeClaimedChunk(Chunk chunk, Player player) {
animateChunk(chunk, player, Material.REDSTONE_BLOCK);
ClaimedChunk newChunk = getClaimedChunk(chunk);
for (ClaimedRegion region : new ArrayList<>(claimedRegions)) {
List<ClaimedRegion> claimedRegions = region.removeChunk(newChunk);
if (!claimedRegions.isEmpty()) {
this.claimedRegions.remove(region);
this.claimedRegions.addAll(claimedRegions);
}
if (region.getChunks().isEmpty()) {
this.claimedRegions.remove(region);
Main.getInstance().getDataManager().deleteClaimedRegion(region);
}
}
return newChunk;
}
public Set<ClaimedRegion> getClaimedRegions() {
return Collections.unmodifiableSet(claimedRegions);
}
public ClaimedRegion getClaimedRegion(Chunk chunk) {
for (ClaimedChunk claimedChunk : getClaimedChunks())
if (claimedChunk.equals(chunk))
return claimedChunk.getRegion();
return null;
}
public List<ClaimedChunk> getClaimedChunks() {
List<ClaimedChunk> chunks = new ArrayList<>();
for (ClaimedRegion claimedRegion : claimedRegions)
chunks.addAll(claimedRegion.getChunks());
return chunks;
}
public ClaimedChunk getClaimedChunk(Chunk chunk) {
for (ClaimedChunk claimedChunk : getClaimedChunks())
if (claimedChunk.equals(chunk))
return claimedChunk;
return null;
}
public int getClaimSize() {
return claimedRegions.stream().map(r -> r.getChunks().size()).mapToInt(Integer::intValue).sum();
}
public int getMaxClaimSize(Player player) {
return PlayerUtils.getNumberFromPermission(player, "ultimateclaims.maxclaims", Settings.MAX_CHUNKS.getInt());
}
public void animateChunk(Chunk chunk, Player player, Material material) {
int bx = chunk.getX() << 4;
int bz = chunk.getZ() << 4;
World world = player.getWorld();
Random random = new Random();
if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_13))
for (int xx = bx; xx < bx + 16; xx++) {
for (int zz = bz; zz < bz + 16; zz++) {
for (int yy = player.getLocation().getBlockY() - 5; yy < player.getLocation().getBlockY() + 5; yy++) {
Block block = world.getBlockAt(xx, yy, zz);
CompatibleMaterial m = CompatibleMaterial.getMaterial(block);
if (!m.isOccluding() || m.isInteractable()) continue;
Bukkit.getScheduler().runTaskLater(Main.getInstance(), () -> {
player.sendBlockChange(block.getLocation(), material, (byte) 0);
Bukkit.getScheduler().runTaskLater(Main.getInstance(), () ->
player.sendBlockChange(block.getLocation(), block.getBlockData()), random.nextInt(30) + 1);
player.playSound(block.getLocation(), CompatibleSound.BLOCK_METAL_STEP.getSound(), 1F, .2F);
}, random.nextInt(30) + 1);
}
}
}
}
public List<RegionCorners> getCorners() {
if (this.claimedRegions.size() <= 0) return null;
List<RegionCorners> result = new ArrayList<>();
for (ClaimedRegion region : claimedRegions) {
RegionCorners regionCorners = new RegionCorners();
for (ClaimedChunk cChunk : region.getChunks()) {
double[] xArr = new double[2],
zArr = new double[2];
int cX = cChunk.getX() * 16,
cZ = cChunk.getZ() * 16;
xArr[0] = cX;
zArr[0] = cZ;
xArr[1] = cX + 16;
zArr[1] = cZ + 16;
regionCorners.addCorners(new ClaimCorners(cChunk.getChunk(), xArr, zArr));
}
result.add(regionCorners);
}
return result;
}
public boolean hasPowerCell() {
return powerCell.location != null;
}
public PowerCell getPowerCell() {
return powerCell;
}
public void setPowerCell(PowerCell powerCell) {
this.powerCell = powerCell;
}
public ClaimPermissions getMemberPermissions() {
return memberPermissions;
}
public void setMemberPermissions(ClaimPermissions memberPermissions) {
this.memberPermissions = memberPermissions;
}
public ClaimPermissions getVisitorPermissions() {
return visitorPermissions;
}
public void setVisitorPermissions(ClaimPermissions visitorPermissions) {
this.visitorPermissions = visitorPermissions;
}
public void banPlayer(UUID uuid) {
this.bannedPlayers.add(uuid);
}
public void unBanPlayer(UUID uuid) {
this.bannedPlayers.remove(uuid);
}
public boolean isBanned(UUID uuid) {
return this.bannedPlayers.contains(uuid);
}
public void destroy(ClaimDeleteReason reason) {
ClaimDeleteEvent event = new ClaimDeleteEvent(this, reason);
Bukkit.getPluginManager().callEvent(event);
if (event.isCancelled()) {
return;
}
this.claimedRegions.clear();
if (Bukkit.getPluginManager().isPluginEnabled("dynmap"))
Main.getInstance().getDynmapManager().refresh(this);
this.powerCell.destroy();
Main.getInstance().getDataManager().deleteClaim(this);
Main.getInstance().getClaimManager().removeClaim(this);
// we've just unclaimed the chunk we're in, so we've "moved" out of the claim
if (bossBarMember != null) bossBarMember.removeAll();
if (bossBarVisitor != null) bossBarVisitor.removeAll();
getOwnerAndMembers().forEach(m -> m.setPresent(false));
members.clear();
}
public Set<UUID> getBannedPlayers() {
return bannedPlayers;
}
public void setOwner(ClaimMember owner) {
this.owner = owner;
}
public boolean isLocked() {
return locked;
}
public void setLocked(boolean locked) {
this.locked = locked;
}
public Location getHome() {
return home;
}
public void setHome(Location home) {
this.home = home;
}
public ClaimSettings getClaimSettings() {
return claimSettings;
}
public String getPowercellTimeRemaining() {
if (hasPowerCell())
return powerCell.getTimeRemaining();
else
return null;
}
@Override
public boolean equals(Object obj) {
if (obj == null || getClass() != obj.getClass())
return false;
return this.id == ((Claim) obj).id;
}
@Override
public int hashCode() {
int hash = 7;
hash = 31 * hash + this.id;
return hash;
}
}
|
Java
|
UTF-8
| 2,117
| 2.34375
| 2
|
[] |
no_license
|
package com.ntgclarity.smartcompound.dataaccess.daoimpl;
import java.util.List;
import java.util.Map;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;
import com.ntgclarity.smartcompound.common.entity.Compound;
import com.ntgclarity.smartcompound.common.entity.Service;
import com.ntgclarity.smartcompound.common.entity.Tenant;
import com.ntgclarity.smartcompound.dataaccess.base.BaseDAO;
import com.ntgclarity.smartcompound.dataaccess.dao.ServiceDAO;
@Repository
public class ServiceDAOImpl extends BaseDAO implements ServiceDAO {
public List<Service> getAllServices(Compound comp) {
Query query = getCurrentSession().createQuery(
"select o from Service o where o.compound.id=1");
List<Service> result = query.list();
return result;
}
@Override
public Service getService(Long id) {
return (Service) super.get(Service.class, id);
}
@Override
public Service updateService(Service service) {
// TODO Auto-generated method stub
return (Service) super.saveOrUpdate(service);
}
/**
* methodCreater:nessma create Service this metohd will call saveOrUpdate()
* in the super class BaseDAO
**/
@Override
public Service insertService(Service service) {
return (Service) super.saveOrUpdate(service);
}
@Override
public List<Service> loadServices(int first, int pageSize,
String sortField, boolean ascending, Map<String, Object> filters) {
return super.load(Service.class, first, pageSize, sortField, ascending,
filters);
}
@Override
public int getNumOfServicesRows(Map<String, Object> filters) {
return super.getNumOfRows(Service.class, filters);
}
@Override
public List<Service> getCompoundServices(Compound compound, String searchParam) {
// return (List<Service>) super.getAllByCompound(Service.class, compound);
Query query = getCurrentSession().createQuery(
"from " + Service.class.getCanonicalName()
+ " x where x.compound =:compound AND x.serviceName LIKE :serviceName");
query.setParameter("compound", compound);
query.setParameter("serviceName", "%" + searchParam + "%");
return query.list();
}
}
|
Java
|
UTF-8
| 2,722
| 2.578125
| 3
|
[] |
no_license
|
package com.github.prypurity.xiaviccore.Utils.Listeners;
import com.github.prypurity.xiaviccore.Main;
import com.github.prypurity.xiaviccore.Utils.Utils;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import java.util.ArrayList;
import java.util.HashMap;
public class TeleportHandler implements Listener {
private static ArrayList<Player> disabledPlayers = new ArrayList<>();
private static HashMap<Player, Location> lastLocations = new HashMap<>();
public static void processPlayerTeleport(Player player) {
lastLocations.put(player, player.getLocation());
}
public static void processPlayerToggle(Player player) {
if (disabledPlayers.contains(player)) {
disabledPlayers.remove(player);
Utils.chat(player, Main.messages.getString("TpToggleOff"));
} else {
disabledPlayers.add(player);
Utils.chat(player, Main.messages.getString("TpToggleOn"));
}
}
public static void teleport(Player player, Location location) {
processPlayerTeleport(player);
player.teleport(location);
}
// change - if true: teleport player2 to player1 else teleport player1 to player2
public static boolean teleport(Player p1, Player p2, boolean change) {
if (change) {
if (!disabledPlayers.contains(p1)) {
teleport(p2, p1.getLocation());
return true;
}
}
if (!disabledPlayers.contains(p2)) {
teleport(p1, p2.getLocation());
return true;
}
return false;
}
public static boolean remoteTp(Player player, Location location) {
if (!disabledPlayers.contains(player)) {
teleport(player, location);
return true;
}
return true;
}
// 0 - teleport successful
// 1 - player1 disabled
// 2 - player2 disabled
public static int remoteTp(Player p1, Player p2) {
if (disabledPlayers.contains(p1)) return 1;
if (disabledPlayers.contains(p2)) return 2;
teleport(p1, p2.getLocation());
return 0;
}
public static Location getLastLocation(Player player) throws Exception {
if (!lastLocations.containsKey(player)) throw new Exception();
return lastLocations.get(player);
}
public static boolean isDisabled(Player player) {
return disabledPlayers.contains(player);
}
@EventHandler
public static void onDeath(PlayerDeathEvent e) {
lastLocations.put(e.getEntity(), e.getEntity().getLocation());
}
}
|
Java
|
UTF-8
| 360
| 1.578125
| 2
|
[] |
no_license
|
package org.esupportail.helpdesk.data.dao.repositories;
import org.esupportail.helpdesk.data.dao.entities.HTicket;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
public interface HTicketRepository extends JpaRepository<HTicket, Long>, QueryDslPredicateExecutor<HTicket> {
}
|
Java
|
UTF-8
| 5,095
| 2.171875
| 2
|
[
"MIT"
] |
permissive
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2014 Andreas Alanko, Emil Nilsson, Sony Mobile Communications AB.
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.sonymobile.jenkins.plugins.gitlab.gitlabauth.folder;
import com.cloudbees.hudson.plugins.folder.Folder;
import com.sonymobile.gitlab.exceptions.GitLabApiException;
import com.sonymobile.gitlab.model.GitLabAccessLevel;
import com.sonymobile.gitlab.model.GitLabGroupInfo;
import com.sonymobile.jenkins.plugins.gitlab.gitlabauth.GitLab;
import com.sonymobile.jenkins.plugins.gitlab.gitlabauth.authorization.GitLabFolderAuthorization;
import hudson.model.TopLevelItem;
/**
* Info holder class used to display information about a folder and the associated group.
*
* @author Andreas Alanko
*/
public class GroupFolderInfo {
/** Folder property associated with this object. */
private final GitLabFolderAuthorization folderProperty;
/** GitLab group associated with this object. */
private final GitLabGroupInfo group;
/**
* Creates an info object for the provided folder property.
*
* @param folderProperty the folder property
*/
public GroupFolderInfo(GitLabFolderAuthorization folderProperty) {
this.folderProperty = folderProperty;
this.group = null;
}
public GroupFolderInfo(GitLabGroupInfo group) {
this.folderProperty = null;
this.group = group;
}
/**
* Create an group folder info object from an item.
*
* @param item the top level item
* @return a group folder info object or null if the item isn't a group folder
*/
public static GroupFolderInfo createFromItem(TopLevelItem item) {
if (item instanceof Folder) {
GitLabFolderAuthorization property = ((Folder)item).getProperties().get(GitLabFolderAuthorization.class);
if (property != null) {
return new GroupFolderInfo(property);
}
}
// not a group folder
return null;
}
/**
* Gets the group info object.
*
* @return the group info object
*/
public GitLabGroupInfo getGroup() throws GitLabApiException {
if (group == null) {
return folderProperty.getGroup();
}
return group;
}
/**
* Gets the group ID.
*
* @return the group ID
*/
public int getGroupId() {
if (group == null) {
return folderProperty.getGroupId();
}
return group.getId();
}
/**
* Gets the group name.
*
* @return the group name
*/
public String getGroupName() {
if (group == null) {
return folderProperty.getGroupName();
}
return group.getName();
}
/**
* Gets the folder name.
*
* @return the folder name
*/
public String getFolderName() {
if (group == null) {
return folderProperty.getFolderName();
}
// Might need to return something else.
return group.getName();
}
/**
* Gets the group path.
*
* @return the group path
*/
public String getGroupPath() {
if (group == null) {
return folderProperty.getGroupPath();
}
return group.getPath();
}
/**
* Gets the group URL.
*
* @return the group URL
*/
public String getGroupUrl() {
if (group == null) {
return folderProperty.getGroupUrl();
}
return GitLab.getUrlForGroup(group);
}
/**
* Gets the GitLab access level for a user ID in this GitLab group.
*
* Will never return null.
*
* @param userId the user ID
* @return the GitLab access level
*/
public GitLabAccessLevel getAccessLevelForUser(int userId) {
try {
return GitLab.getAccessLevelInGroup(userId, getGroupId());
} catch (GitLabApiException e) {
return GitLabAccessLevel.NONE;
}
}
}
|
Java
|
UTF-8
| 687
| 2.859375
| 3
|
[] |
no_license
|
package com.prashant;
public class Main {
public static void main(String[] args) {
Bank bank = new Bank("State Bank of India");
bank.addBranch("Patna");
bank.addCustomer("Patna","Prashant",10000.00);
bank.addCustomer("patna","Viresh",20000.00);
bank.addCustomer("patna","Aanand",400000.00);
bank.addBranch("Delhi");
bank.addCustomer("Delhi","Anirudha",500000.00);
bank.addTransactionAmount("patna","prashant",50);
bank.addTransactionAmount("patna","viresh",500);
bank.addTransactionAmount("patna","Anand",600);
bank.listCustomers("patna",true);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.