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
|
|---|---|---|---|---|---|---|---|
C#
|
UTF-8
| 6,721
| 2.9375
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
namespace 魔王的试炼
{
/// <summary>
/// 可携带道具类,为背包类提供数据单元
/// </summary>
abstract class Property
{
/// <summary>
/// 以道具名称创建道具的实例
/// </summary>
/// <param name="index">道具图像索引</param>
/// <param name="name">道具名称</param>
/// <param name="isConsumables">道具是否是消耗品</param>
/// <param name="keyCode">使用按键</param>
/// <param name="number">道具拥有数量, 默认为0</param>
public Property(MotaElement index, PropName name, bool isConsumables, System.Windows.Forms.Keys keyCode, int number = 0)
{
this.FaceIndex = (int)index;
this.Name = name;
this.count = number;
this.UseKeyCode = keyCode;
this.Consumable = isConsumables;
}
/// <summary>
/// 获取或设置道具名称
/// </summary>
public PropName Name { get; set; }
/// <summary>
/// 标示道具是否是消耗品
/// </summary>
public bool Consumable { get; set; }
public delegate void CountChangeHandle();
/// <summary>
/// 道具数量改变时触发的事件
/// </summary>
public event CountChangeHandle CountChangeEvent = null;
private int count;
/// <summary>
/// 获取或设置道具的拥有数量
/// </summary>
public int Count
{
get { return count; }
set
{
count = value;
if (CountChangeEvent != null)
{
CountChangeEvent();
}
}
}
/// <summary>
/// 如果道具是可消耗的话,减少道具数量1
/// </summary>
protected void CutDown()
{
if (Consumable)
{
Count--;
}
}
/// <summary>
/// 获取或设置使用道具的按键
/// </summary>
public System.Windows.Forms.Keys UseKeyCode { get; set; }
/// <summary>
/// 使用道具
/// </summary>
/// <param name="user">道具使用者</param>
public abstract void Use(IPropUser user);
private int FaceIndex;
/// <summary>
/// 获取道具显示在道具栏里的图像
/// </summary>
public Bitmap Icon
{
get { return MotaImage.GetImage(FaceIndex)[0]; }
}
/// <summary>
/// 根据道具名称获取描述信息
/// </summary>
/// <param name="name">道具名称</param>
/// <returns>描述字符串</returns>
public static string GetDescribe(PropName name)
{
string desc = string.Empty;
switch (name)
{
case PropName.怪物手册:
desc += "获得怪物手册!\r\n按空格即可查看所在楼层的怪物信息以及可预测的基本伤害";
break;
case PropName.楼层传送器:
desc += "获得楼层传送器!\r\n按J即可打开楼层跳转界面";
break;
case PropName.破墙镐:
desc += "获得破墙镐!\r\n按P使用破墙镐,可以破坏一堵墙。获取宝物、打开密道时使用最佳。";
break;
case PropName.自然之靴:
desc += "获得自然之靴!\r\n获得后可以无伤害地在路障陷阱中自由行走,非消耗品";
break;
case PropName.上楼器:
desc += "获得上楼器!\r\n上楼器可以无视当前楼层的任何阻碍而进入下一层按U使用此道具.";
break;
case PropName.道具包:
desc += "";
break;
case PropName.怪物侦测器:
desc += "获得怪物侦测器!\r\n获得后可以用鼠标右键点击怪物查看怪物的详细信息,比怪物手册更加先进!";
break;
default:
break;
}
return desc;
}
/// <summary>
/// 根据描述字符串获取道具类型
/// </summary>
/// <param name="args">描述字符串</param>
/// <returns>道具类型</returns>
public static PropName GetProp(string args)
{
Dictionary<string, PropName> propDic = new Dictionary<string, PropName>();
propDic.Add("黄钥匙", PropName.黄钥匙);
propDic.Add("蓝钥匙", PropName.蓝钥匙);
propDic.Add("红钥匙", PropName.红钥匙);
propDic.Add("道具包", PropName.道具包);
propDic.Add("怪物手册", PropName.怪物手册);
propDic.Add("怪物侦测器", PropName.怪物侦测器);
propDic.Add("楼层传送器", PropName.楼层传送器);
propDic.Add("破墙镐", PropName.破墙镐);
propDic.Add("上楼器", PropName.上楼器);
propDic.Add("自然之靴", PropName.自然之靴);
propDic.Add("事件钥", PropName.事件钥);
propDic.Add("NULL", PropName.NULL);
return propDic[args];
}
/// <summary>
/// 根据道具类型获取道具名称
/// </summary>
/// <param name="prop">描述字符串</param>
/// <returns>名称</returns>
public static string GetName(PropName prop)
{
Dictionary<PropName, string> propDic = new Dictionary<PropName, string>();
propDic.Add(PropName.黄钥匙, "黄钥匙");
propDic.Add(PropName.蓝钥匙, "蓝钥匙");
propDic.Add(PropName.红钥匙, "红钥匙");
propDic.Add(PropName.道具包, "道具包");
propDic.Add(PropName.怪物手册, "怪物手册");
propDic.Add(PropName.怪物侦测器, "怪物侦测器");
propDic.Add(PropName.楼层传送器, "楼层传送器");
propDic.Add(PropName.破墙镐, "破墙镐");
propDic.Add(PropName.上楼器, "上楼器");
propDic.Add(PropName.自然之靴, "自然之靴");
propDic.Add(PropName.事件钥, "事件钥");
propDic.Add(PropName.NULL, "NULL");
return propDic[prop];
}
}
}
|
Python
|
UTF-8
| 1,451
| 3.3125
| 3
|
[] |
no_license
|
#!/usr/bin/env python
"""
_Counter_
Conditional with a Maximum Counter.
When the conditional is run, it compares a
counter parameter in the ControlPoint to a maximum
value stored in the conditional attributes
"""
from ShREEK.ControlPoints.Conditional import Conditional
import ShREEK.ControlPoints.ControlPointFactory as Factory
class Counter(Conditional):
"""
_Counter_
Compare a counter value to a maximum value,
trigger the OnSuccess Action if the counter is
equal to or greater than the max, otherwise trigger
the OnFail Action
"""
def __init__(self):
Conditional.__init__(self)
self.attrs['Maximum'] = 5
def setMaximum(self, maxValue):
"""
set the max value for the counter
"""
self.attrs["Maximum"] = maxValue
def evaluate(self, controlPoint):
"""
_evaluate_
Check the Counter Parameter in the controlPoint.
If the parameter does not exist, then add it, and
set it to 1.
Otherwise compare the value to the maximum and
"""
params = controlPoint.getParameters()
value = int(params.get("Counter", 1))
maxVal = int(self.attrs["Maximum"])
result = False
if value >= maxVal:
result = True
controlPoint.addParameter("Counter", value + 1)
return result
Factory.registerConditional(Counter)
|
Java
|
UTF-8
| 7,402
| 2
| 2
|
[] |
no_license
|
package com.ultrapower.baozouqiwen.adapter;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONObject;
import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.ultrapower.baozouqiwen.BaozouApplication;
import com.ultrapower.baozouqiwen.R;
import com.ultrapower.baozouqiwen.model.MainListInfo;
import com.ultrapower.baozouqiwen.util.BitmapCache;
import com.ultrapower.baozouqiwen.util.StringUtil;
import com.ultrapower.baozouqiwen.util.VolleyUtil;
import com.ultrapower.baozouqiwen.vo.MainListViewVo;
import com.ultrapower.baozouqiwen.vo.MainListViewVos;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class DropDownRrfreshListViewAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private List<MainListInfo> mList = new ArrayList<MainListInfo>();
private RequestQueue rq;
private int currentNews;// 已经加载的条数
private int newsAmount;// 新闻总条数
private volatile int dataNumForOneRequest;//一条请求获取到的新闻条数
private List<Integer> requestCache=new ArrayList<Integer>();
public DropDownRrfreshListViewAdapter(Context pContext,List<MainListInfo> mList, RequestQueue rq) {
mInflater = LayoutInflater.from(pContext);
this.rq=rq;
this.mList=mList;
refeshData();
}
@Override
public int getCount() {
return mList.size();
}
@Override
public Object getItem(int position) {
return mList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (getCount() == 0) {
return null;
}
ViewHolder holder = null;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.mImage = (NetworkImageView) convertView
.findViewById(R.id.ivIcon);
holder.mTitle = (TextView) convertView
.findViewById(R.id.tvTitle);
//convertView.setTag(holder);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
MainListInfo ai = mList.get(position);
//holder.mImage.setImageBitmap(ai.getIcon());
holder.mImage.setImageUrl(ai.getIconUrl(), new ImageLoader(rq, BitmapCache.getInstance()));
holder.mImage.setDefaultImageResId(R.drawable.imgload);
holder.mImage.setErrorImageResId(R.drawable.imgerror);
holder.mTitle.setText(ai.getTitle());
holder.id=ai.getId();
return convertView;
}
private void getDataFromNetwork(final String params){
Log.v("network", "开始获取list数据");
@SuppressWarnings("unchecked")
JsonObjectRequest jsonReq=VolleyUtil.createJsonObjectReq(BaozouApplication.MainListViewSourecUrl+params, null, new Listener(){
@Override
public void onResponse(Object response) {
if(null!=response){
Log.v("network", "开始解析list数据");
Log.v("分页调试","url="+BaozouApplication.MainListViewSourecUrl+params+"response 为"+response.toString());
Gson gson=new Gson();
MainListViewVos datas= gson.fromJson(response.toString(), MainListViewVos.class);
addVosToModels(datas);
}else{
Log.e("network", "获取数据失败");
}
}
},new ErrorListener(){
@Override
public void onErrorResponse(VolleyError error) {
Log.v("newtwork", "网络错误");
}});
VolleyUtil.addReqToQueue(rq, jsonReq);
}
private void getDataFromNetwork(){
Log.v("network", "开始获取list数据");
@SuppressWarnings("unchecked")
JsonObjectRequest jsonReq=VolleyUtil.createJsonObjectReq(BaozouApplication.MainListViewSourecUrl, null, new Listener(){
@Override
public void onResponse(Object response) {
if(null!=response){
Log.v("network", "开始解析list数据");
Gson gson=new Gson();
MainListViewVos datas= gson.fromJson(response.toString(), MainListViewVos.class);
addVosToModels(datas);
}else{
Log.e("network", "获取数据失败");
}
}
},new ErrorListener(){
@Override
public void onErrorResponse(VolleyError error) {
Log.v("newtwork", "网络错误");
}});
VolleyUtil.addReqToQueue(rq, jsonReq);
}
private void addVosToModels(MainListViewVos datas) {
int num;
if(datas!=null&&datas.getDl()!=null&&(num=datas.getDl().size())>0)
{
dataNumForOneRequest=num;
currentNews+=dataNumForOneRequest;
for(MainListViewVo vo:datas.getDl()){
MainListInfo mInfo=new MainListInfo();
//mInfo.setIcon(null);
mInfo.setIconUrl(BaozouApplication.MianListViewIconUrl+StringUtil.changeDataFormat(vo.getRq()));
mInfo.setId(vo.getId());
mInfo.setTitle((StringUtil.deCode(vo.getBt(), "ISO-8859-1", "utf-8")).replaceAll(""", "\""));
mList.add(mInfo);
}
this.notifyDataSetChanged();
}
}
public static class ViewHolder {
private NetworkImageView mImage;
private TextView mTitle;
private String id;
public String getId() {
return id;
}
}
public void refeshData() {
this.mList.clear();
this.currentNews=0;
this.requestCache.clear();
getAmoutpages();
}
private void getAmoutpages() {
Log.v("network", "开始获取新闻总数");
@SuppressWarnings("unchecked")
StringRequest stringReq= new StringRequest(BaozouApplication.MainListViewNewsAountUrl, new Listener(){
@Override
public void onResponse(Object response) {
if(null!=response){
Log.v("network", "开始解析数据");
newsAmount=Integer.parseInt(response.toString());
Log.v("总新闻个数", response.toString());
getDataFromNetwork();
}else{
Log.e("network", "获取新闻总数数据失败");
}
}
},new ErrorListener(){
@Override
public void onErrorResponse(VolleyError error) {
Log.v("newtwork", "网络错误");
}});
VolleyUtil.addReqToQueue(rq, stringReq);
}
public void getMoreData() {
int remainNews= newsAmount- currentNews;
if(remainNews==0)// 数据全部获取完成 到达列表末端
return ;
if(remainNews<=dataNumForOneRequest){
int _i=currentNews+dataNumForOneRequest;
if(requestCache.contains(_i))
return;
requestCache.add(_i);
this.getDataFromNetwork("f="+_i);
}
else{
int _i=currentNews+dataNumForOneRequest;
if(requestCache.contains(_i))
return;
requestCache.add(_i);
this.getDataFromNetwork("f="+_i);
}
}
}
|
Java
|
UTF-8
| 720
| 2.78125
| 3
|
[] |
no_license
|
package items;
import java.util.ArrayList;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import logicClasses.Item;
public class LitCandle extends Item {
String itemName = "litcandle";
public LitCandle() {
super(new Sprite(new Texture(Gdx.files.internal("images/candle_lit.png"))));
this.setName(itemName);
}
@Override
public void draw(SpriteBatch spriteBatch) {
sprite.setX(position.x);
sprite.setY(position.y);
sprite.draw(spriteBatch);
}
@Override
public String toString(){
return "Lit Candle: Lights up the room and your soul.";
}
}
|
Python
|
UTF-8
| 1,670
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
import numpy as np
import neighbourlist
import system
import numba as nb
@nb.jit(nopython = True)
def LJ_potential_ij(r, sigmaii, epsilonii, sigmajj, epsilonjj, r_c, r_s):
sigmaij = 0.5 * (sigmaii + sigmajj) # Lorentz-Berthelot: https://en.wikipedia.org/wiki/Combining_rules
epsilonij = np.sqrt(epsilonii * epsilonjj)
r_cut = r_c + r_s
q = (sigmaij / r)**6
q_c = (sigmaij/r_cut)**6
return (4.0 * epsilonij * q * (q - 1.0) # return lennard jones interaction energy between particle i and particle j
- 4.0 * epsilonij * q_c *(q_c - 1.0)) # subtract value of potential at r_cut to avoid discontinuity # precompute!!!!!!
@nb.jit
def LJ_potential(particles, r_c, r_s):
'''Computes the total Lennard Jones potential of the system configuration of *box*.
arguments:
box (Box): object of the class Box. Includes the above 2 variables in the object...
(will be used when running the actual simulation, the 2 others (possibly) when testing)
r_c (float): cutoff radius for LJ potential
r_s (float): size of skin region for LJ potential
'''
if particles[0].neighbourlist is None:
raise Exception('compute neighbourlists for particles before computing LJ potential!')
LJpot = 0.0
for particlei in particles:
for particlej in particlei.neighbourlist:
r = np.linalg.norm(particlei.position - particlej.position)
LJpot += LJ_potential_ij(r, particlei.sigmaLJ, particlei.epsilonLJ,
particlej.sigmaLJ, particlej.epsilonLJ, r_c, r_s)
return LJpot/2 # fix? find cleverer solution
|
Java
|
UTF-8
| 1,358
| 2.390625
| 2
|
[] |
no_license
|
package Module.Team;
import Module.FilterEntity;
import Module.User.UserModel;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.ws.rs.QueryParam;
import java.util.List;
public class SearchTeamEntity extends FilterEntity{
@QueryParam("id")public Integer id;
@QueryParam("name") public String name;
@QueryParam("locationId") public Integer locationId;
@QueryParam("leaderEmployeeId")public Integer leaderEmployeeId;
public List<Predicate> applyTo(CriteriaBuilder builder, List<Predicate> predicates, Root<TeamModel> root){
if (id != null) {
predicates.add(builder.equal(root.get(TeamModel_.id), id));
}
if (name != null && !name.isEmpty()) {
predicates.add(builder.like(builder.lower(root.get(TeamModel_.name)), "%" + name.toLowerCase() + "%"));
}
if (locationId != null) {
predicates.add(builder.equal(root.get(TeamModel_.locationId), locationId));
}
if (leaderEmployeeId != null) {
predicates.add(builder.equal(root.get(TeamModel_.leaderEmployeeId), leaderEmployeeId));
}
return predicates;
}
}
|
Python
|
UTF-8
| 19,964
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
# -*- mode: python; coding: utf-8 -*-
# Copyright 2017-2018 Peter Williams and collaborators.
# Licensed under the MIT License.
"""Train and use artificial neural network approximations ("regressions") of
synchrotron radiative transfer coefficients as a function of various physical
input parameters.
The meat of the neural network code is in the ``impl`` module to avoid
importing Keras unless needed.
"""
from __future__ import absolute_import, division, print_function
__all__ = '''
AbsLogMapping
DirectMapping
DomainRange
LogMapping
LogitMapping
Mapping
NegLogMapping
NinthRootMapping
SampleData
SignMapping
basic_load
detrivialize_stokes_basis
mapping_from_dict
mapping_from_samples
'''.split()
from collections import OrderedDict
from six.moves import range
import numpy as np
import pandas as pd
from pwkit.io import Path
class Mapping(object):
"""An abstract base class for parameter transformations.
Mapping classes are used to translate the physical parameters fed into
*neurosynchro* into normalized values that are easier to work with
numerically. You will not normally need to use them directly.
"""
desc = None # set by subclasses
trainer = None
phys_bounds_mode = 'empirical'
"Blah blah"
normalization_mode = 'gaussian'
out_of_sample = 'ignore'
def __init__(self, name):
self.name = name
@classmethod
def from_info_and_samples(cls, info, phys_samples):
"""Create a new :class:`Mapping` from a dictionary of information and a set of samples.
**Call signature**
*info*
A dictionary of attributes, passed into :meth:`Mapping.from_dict`.
*phys_samples*
A 1D Numpy array of samples of this parameter, in no particular order.
Return value
A new instance of :class:`Mapping` (or one of its subclasses) with initialized
bounds parameters.
"""
inst = cls.from_dict(info, load_bounds=False)
valid = np.isfinite(phys_samples) & inst._is_valid(phys_samples)
n_rej = phys_samples.size - valid.sum()
print('%s: rejecting %d samples out of %d' % (inst.name, n_rej, phys_samples.size))
phys_samples = phys_samples[valid]
if phys_samples.size < 3:
raise Exception('not enough valid samples for %s' % inst.name)
if inst.phys_bounds_mode == 'empirical':
inst.p_min = phys_samples.min()
inst.p_max = phys_samples.max()
elif inst.phys_bounds_mode == 'theta':
inst.p_min = 0.
inst.p_max = 0.5 * np.pi
else:
raise ValueError('unrecognized phys_bounds_mode value %r for %s' %
(inst.phys_bounds_mode, inst.name))
# Pluggable "transform"
transformed = inst._to_xform(phys_samples)
if inst.normalization_mode == 'gaussian':
inst.x_mean = transformed.mean()
inst.x_std = transformed.std()
elif inst.normalization_mode == 'unit_interval':
# Maps the physical values to the unit interval [0, 1].
inst.x_mean = transformed.min()
inst.x_std = transformed.max() - inst.x_mean
if inst.x_std == 0:
inst.x_std = 1.
else:
raise ValueError('unrecognized normalization_mode value %r for %s' %
(inst.normalization_mode, inst.name))
# Normalize
normed = (transformed - inst.x_mean) / inst.x_std
inst.n_min = normed.min()
inst.n_max = normed.max()
return inst
def __repr__(self):
return '<Mapping %s %s mean=%r sd=%r>' % (self.name, self.desc, self.x_mean, self.x_std)
def phys_to_norm(self, phys):
"""Map "physical" parameters to normalized values
**Argument**
*phys*
An array of "physical" input values (see :ref:`transformations`).
**Return values**
This method returns a tuple ``(normalized, oos)``.
*normalized*
The normalized versions of the input data.
*oos*
An array of booleans of the same shape as the input data. True
values indicate inputs that were out of the sample that was used to
define the mapping.
"""
# note: using prefix ~ instead of np.logical_not fails for scalars
oos = np.logical_not((phys >= self.p_min) & (phys <= self.p_max)) # catches NaNs
any_oos = np.any(oos)
if any_oos:
if self.out_of_sample == 'ignore':
pass
elif self.out_of_sample == 'clip':
phys = np.clip(phys, self.p_min, self.p_max)
elif self.out_of_sample == 'nan':
phys = phys.copy()
phys[oos] = np.nan
else:
raise Exception('unrecognized out-of-sample behavior %r' % self.out_of_sample)
return (self._to_xform(phys) - self.x_mean) / self.x_std, any_oos
def norm_to_phys(self, norm):
"""Map "normalized" parameters to "physical" values
**Argument**
*norm*
An array of "normalized" input values (see :ref:`transformations`).
**Return values**
This method returns a tuple ``(phys, oos)``.
*phys*
The physical versions of the input data.
*oos*
An array of booleans of the same shape as the input data. True
values indicate inputs that were out of the sample that was used to
define the mapping.
"""
oos = np.logical_not((norm >= self.n_min) & (norm <= self.n_max)) # catches NaNs
any_oos = np.any(oos)
if any_oos:
if self.out_of_sample == 'ignore':
pass
elif self.out_of_sample == 'clip':
norm = np.clip(norm, self.n_min, self.n_max)
elif self.out_of_sample == 'nan':
norm = norm.copy()
norm[oos] = np.nan
else:
raise Exception('unrecognized out-of-sample behavior %r' % self.out_of_sample)
return self._from_xform(norm * self.x_std + self.x_mean), any_oos
def to_dict(self):
"""Serialize this :class:`Mapping` into an ordered dictionary."""
d = OrderedDict()
d['name'] = self.name
d['maptype'] = self.desc
if self.phys_bounds_mode is not None:
d['phys_bounds_mode'] = self.phys_bounds_mode
if self.normalization_mode is not None:
d['normalization_mode'] = self.normalization_mode
if self.trainer is not None:
d['trainer'] = self.trainer
if self.out_of_sample is not None:
d['out_of_sample'] = self.out_of_sample
d['x_mean'] = self.x_mean
d['x_std'] = self.x_std
d['phys_min'] = self.p_min
d['phys_max'] = self.p_max
d['norm_min'] = self.n_min
d['norm_max'] = self.n_max
return d
@classmethod
def from_dict(cls, info, load_bounds=True):
"""Deserialize an ordered dictionary into a new :class:`Mapping` instance.
**Call signature**
*info*
A dictionary of parameters, as generated by :meth:`Mapping.to_dict`.
*load_bounds* (default: :const:`True`)
If true, deserialize bounds information such as the maximum and minimum
observed physical values. If :const:`False`, these are left uninitialized.
Return value
A new :class:`Mapping` instance.
"""
if str(info['maptype']) != cls.desc:
raise ValueError('info is for maptype %s but this class is %s' % (info['maptype'], cls.desc))
inst = cls(str(info['name']))
if 'phys_bounds_mode' in info:
inst.phys_bounds_mode = info['phys_bounds_mode']
if 'normalization_mode' in info:
inst.normalization_mode = info['normalization_mode']
if 'trainer' in info:
inst.trainer = info['trainer']
if 'out_of_sample' in info:
inst.out_of_sample = info['out_of_sample']
if load_bounds:
inst.x_mean = float(info['x_mean'])
inst.x_std = float(info['x_std'])
inst.p_min = float(info['phys_min'])
inst.p_max = float(info['phys_max'])
inst.n_min = float(info['norm_min'])
inst.n_max = float(info['norm_max'])
return inst
class AbsLogMapping(Mapping):
desc = 'abs_log'
def _to_xform(self, p):
return np.log10(np.abs(p))
def _from_xform(self, x):
return 10**x # XXX not invertible!
def _is_valid(self, p):
return p != 0
class DirectMapping(Mapping):
desc = 'direct'
def _to_xform(self, p):
return p
def _from_xform(self, x):
return x
def _is_valid(self, p):
return np.ones(p.shape, dtype=np.bool)
class LogMapping(Mapping):
desc = 'log'
def _to_xform(self, p):
return np.log10(p)
def _from_xform(self, x):
return 10**x
def _is_valid(self, p):
return (p > 0)
class LogitMapping(Mapping):
desc = 'logit'
def _to_xform(self, p):
return np.log(p / (1. - p))
def _from_xform(self, x):
return np.exp(x) / (np.exp(x) + 1)
def _is_valid(self, p):
# Infinities are hard to deal with so we don't allow p = 0 or p = 1.
return (p > 0) & (p < 1)
class NegLogMapping(Mapping):
desc = 'neg_log'
def _to_xform(self, p):
return np.log10(-p)
def _from_xform(self, x):
return -(10**x)
def _is_valid(self, p):
return (p < 0)
class NinthRootMapping(Mapping):
desc = 'ninth_root'
def _to_xform(self, p):
return np.cbrt(np.cbrt(p))
def _from_xform(self, x):
return x**9
def _is_valid(self, p):
return np.ones(p.shape, dtype=np.bool)
class SignMapping(Mapping):
desc = 'sign'
def _to_xform(self, p):
return np.sign(p)
def _from_xform(self, x):
return np.sign(x) # XXX not reversible!
def _is_valid(self, p):
return (p != 0.)
_mappings = {
'abs_log': AbsLogMapping,
'direct': DirectMapping,
'log': LogMapping,
'logit': LogitMapping,
'neg_log': NegLogMapping,
'ninth_root': NinthRootMapping,
'sign': SignMapping,
}
class Passthrough(object):
def __init__(self, d):
self.d = d
def to_dict(self):
return self.d
def mapping_from_info_and_samples(info, phys_samples):
"""Create a :class:`Mapping` subclass from configuration data and sample data.
**Call signature**
*info*
A dictionary of configuration info, loaded from ``nn_config.toml`` or
created by :meth:`Mapping.to_dict`.
*phys_samples*
A 1D array of training data used to initialize the bounds of this mapping.
Return value
A new :class:`Mapping` instance. The particular subclass used depends on the
``maptype`` setting, as documented in the :ref:`map-types`.
"""
cls = _mappings[info['maptype']]
return cls.from_info_and_samples(info, phys_samples)
def mapping_from_dict(info):
"""Create a :class:`Mapping` subclass from configuration data.
**Call signature**
*info*
A dictionary of configuration info, loaded from ``nn_config.toml`` or
created by :meth:`Mapping.to_dict`.
Return value
A new :class:`Mapping` instance. The particular subclass used depends on the
``maptype`` setting, as documented in the :ref:`map-types`.
Unlike :func:`mapping_from_info_and_samples`, the bounds data are not initialized
if they are not already defined in the configuration dictionary.
"""
maptype = str(info['maptype'])
cls = _mappings[maptype]
return cls.from_dict(info)
def basic_load(datadir, drop_metadata=True):
"""Load a directory of textual tables (such as training set data).
**Call signature**
*datadir*
A path to a directory of textual tables; format described below.
*drop_metadata* (default ``True``)
If true, columns marked as metadata will be dropped from the returned
table.
Return value
A :class:`pandas.DataFrame` of data, concatenating all of the input tables.
The data format is documented in :ref:`make-training-set`. Briefly, each
file in *datadir* whose name ends with ``.txt`` will be loaded as a table
using :func:`pandas.read_table`. The recommended format is tab-separated
values with a single header row. Column names should end in type
identifiers such as ``(lin)`` to identify their roles, although this
function ignores this information except to drop columns whose names end
in ``(meta)`` if so directed.
"""
datadir = Path(datadir)
chunks = []
for item in datadir.glob('*.txt'):
chunks.append(pd.read_table(str(item)))
data = pd.concat(chunks, ignore_index=True)
if drop_metadata:
# Drop `foo(mtea)` columns
for col in data.columns:
if col.endswith('(meta)'):
del data[col]
return data
class DomainRange(object):
n_params = None
n_results = None
pmaps = None
rmaps = None
@classmethod
def from_info_and_samples(cls, info, df):
inst = cls()
inst.n_params = len(info['params'])
inst.n_results = len(info['results'])
inst.pmaps = []
inst.rmaps = []
for i, pinfo in enumerate(info['params']):
if not df.columns[i].startswith(pinfo['name'] + '('):
raise Exception('alignment error: expect data column %d to be %r; got %r' % (i, pinfo['name'], df.columns[i]))
inst.pmaps.append(mapping_from_info_and_samples(pinfo, df[df.columns[i]].values))
n = inst.n_params
for i, rinfo in enumerate(info['results']):
if not df.columns[n+i].startswith(rinfo['name'] + '(res)'):
raise Exception('alignment error: expect data column %d to be %r; got %r' % (n + i, rinfo['name'], df.columns[n + i]))
inst.rmaps.append(mapping_from_info_and_samples(rinfo, df[df.columns[n+i]].values))
return inst
@classmethod
def from_serialized(cls, config_path, result_to_extract=None):
"""`result_to_extract` is a total lazy hack for the training tool."""
import pytoml
with Path(config_path).open('rt') as f:
info = pytoml.load(f)
inst = cls()
inst.pmaps = []
inst.rmaps = []
extracted_info = None
for subinfo in info['params']:
inst.pmaps.append(mapping_from_dict(subinfo))
for i, subinfo in enumerate(info['results']):
if result_to_extract is not None and subinfo['name'] == result_to_extract:
extracted_info = subinfo
extracted_info['_index'] = i
inst.rmaps.append(mapping_from_dict(subinfo))
inst.n_params = len(inst.pmaps)
inst.n_results = len(inst.rmaps)
if result_to_extract is not None:
return inst, extracted_info
return inst
def __repr__(self):
return '\n'.join(
['<%s n_p=%d n_r=%d' % (self.__class__.__name__, self.n_params, self.n_results)] +
[' P%d=%r,' % (i, m) for i, m in enumerate(self.pmaps)] +
[' R%d=%r,' % (i, m) for i, m in enumerate(self.rmaps)] +
['>'])
def into_info(self, info):
info['params'] = [m.to_dict() for m in self.pmaps]
info['results'] = [m.to_dict() for m in self.rmaps]
def load_and_normalize(self, datadir):
df = basic_load(datadir)
for i, pmap in enumerate(self.pmaps):
if not df.columns[i].startswith(pmap.name + '('):
raise Exception('alignment error: expect data column %d to be %s(...); got %s' % (i, pmap.name, df.columns[i]))
n = self.n_params
for i, rmap in enumerate(self.rmaps):
if df.columns[n+i] != rmap.name + '(res)':
raise Exception('alignment error: expect data column %d to be %s(res); got %s' % (n + i, rmap.name, df.columns[n + i]))
return SampleData(self, df)
class SampleData(object):
df = None
domain_range = None
phys = None
norm = None
oos_flags = 0
def __init__(self, domain_range, df):
self.df = df
self.domain_range = domain_range
self.phys = df.values
self.norm = np.empty_like(self.phys)
for i in range(self.domain_range.n_params):
self.norm[:,i], flag = self.domain_range.pmaps[i].phys_to_norm(self.phys[:,i])
if flag:
self.oos_flags |= (1 << i)
for i in range(self.domain_range.n_results):
j = i + self.domain_range.n_params
self.norm[:,j], flag = self.domain_range.rmaps[i].phys_to_norm(self.phys[:,j])
if flag:
self.oos_flags |= (1 << j)
@property
def phys_params(self):
return self.phys[:,:self.domain_range.n_params]
@property
def phys_results(self):
return self.phys[:,self.domain_range.n_params:]
@property
def norm_params(self):
return self.norm[:,:self.domain_range.n_params]
@property
def norm_results(self):
return self.norm[:,self.domain_range.n_params:]
def detrivialize_stokes_basis(coeffs, psi):
"""Re-express coefficients in a basis in which the magnetic field can rotate
on the sky.
**Arguments**
*coeffs*
Radiative transfer coefficients in the Stokes basis where the Stokes U
axis is aligned with the magnetic field. This is an array of shape ``(S,
8)`` where *S* is the shape of *psi*. Along the inner axis of the array,
the coefficients are: ``(j_I, alpha_I, j_Q, alpha_Q, j_V, alpha_V,
rho_Q, rho_V)``. This is the representation returned by
:meth:`neurosynchro.impl.PhysicalApproximator.compute_all_nontrivial`.
*psi*
The angle(s) between the magnetic field as projected on the sky and some
invariant Stokes U axis, in radians. XXX: sign convention?
**Return value**
An array of radiative transfer coefficients in which the Stokes U terms
are no longer trivial. The shape is ``(S, 11)``. Along the inner axis of
the array, the coefficients are: ``(j_I, alpha_I, j_Q, alpha_Q, j_U,
alpha_U, j_V, alpha_V, rho_Q, rho_U, rho_V)``.
**Details**
Synchrotron calculations are generally performed in a basis in which the
Stokes U axis is aligned with the magnetic field, which means that the
corresponding radiative transfer coefficients are zero ("trivial"). In
actual work, however, the magnetic field orientation is not guaranteed to
be constant along the direction of propagation. If the Stokes U axis is
held fixed along the integration, the Stokes U coefficients become
nontrivial. This function transforms coefficients from the former basis
to the latter.
See Shcherbakov & Huang (2011MNRAS.410.1052S), equations 50-51. Note
that the linear polarization axis rotates at twice the rate that psi
does, because linear polarization is an *orientation* not an *angle*.
"""
ji = coeffs[...,0]
ai = coeffs[...,1]
jq = coeffs[...,2]
aq = coeffs[...,3]
jv = coeffs[...,4]
av = coeffs[...,5]
rq = coeffs[...,6]
rv = coeffs[...,7]
twochi = 2 * (np.pi - psi) # note the sign convention!
s = np.sin(twochi)
c = np.cos(twochi)
xformed = np.empty(coeffs.shape[:-1] + (11,))
xformed[...,0] = ji # j_I
xformed[...,1] = ai # alpha_I
xformed[...,2] = c * jq # j_Q
xformed[...,3] = c * aq # alpha_Q
xformed[...,4] = s * jq # j_U
xformed[...,5] = s * aq # alpha_U
xformed[...,6] = jv # j_V
xformed[...,7] = av # alpha_V
xformed[...,8] = c * rq # rho_Q
xformed[...,9] = s * rq # rho_U
xformed[...,10] = rv # rho_V
return xformed
|
Markdown
|
UTF-8
| 6,610
| 2.953125
| 3
|
[] |
no_license
|
Dreckig OS development has halted. It has been reincarnated as <a href="https://github.com/WizardOfHaas/d264b">d264b</a> in glorious 64 bit!
If anyone wants to take the reigns and go down the road Dreckig OS was on let me know and I'll set you up.
<pre>
________________________
=====|Dreckig OS User Manual|==
====|Alpha v0.007 |===
===|January 2013 |====
==|Dr. Sean Haas |=====
------------------------
---What is Dreckig OS?---
Simply put, Dreckig OS is an ultra secure operating system based around the experimental megalithic kernel architecture.
In this archetecture, everything is inside the kernel, including user programs. This makes it run quickly and securely.
---The command line---
The command line in Dreckig OS is a mixture of native commands, lang commands and brainfuck(yes, really). Any time you are
able to give input you can hit the esc key to be dropped down to the command line.
Native commands:
These are initiated with a one word command, and if any other data is needed the user is prompted.
Unprivleged: For everyone
help - terse help message
re - reboot
info - show some system info
clear - clear screen
log - super secure locking mechanism
bf - the brainfuck vm
hist - show command history
lo -log out (quit also works)
dte - the Dreckig Text Editor
crypt - stenographic file system manager
Priveleged: For group 0
dump - show contents at a given memory adress (dec)
regs - show register contents
ps - list proccesses
kill - kill a proccess
user - user control system
hash - low level access to hashfs
chr - chroot, change root directory
lang commands:
These are run in the lang interpreter, usually more than one word long. I developed lang as a way to write simple scripts
in Dreckig OS. One of it's biggest quirks is in it's variables, both of them. lang only has two variables, "var" and "bak"
Here is a quick list of more useful functions:
some text > -- displays "some text"
prompt < -- get input from user qith prompt "prompt", stores in var
file name > -- display file "name"
run file -- runs lang file "file"
# cmd -- runs "cmd" as a native command
asr cmd -- run cmd as root
Brainfuck!:
This is the fun part(or at least it was fun to write!). Either enter a piece of brainfuck code straight at the command
line, or use the bf virtual machine to run an entire file of code.
The subtleties of this language will not be covered here.
---The file system---
HashFS, the main file system used by Dreckig OS is based off of a simple hashing function. The idea being that the only
data you need to access a file is it's name. When you want to access a file you provide it's name, the hash function is then
applied to it, and the resulting hash points to where it is located on the disk. All files are up to 512 bytes in length.
Since there are no file tables, you can't list the files on a disk.
This leads to the next file system, CryptFS, a cryptographical file
system. A CryptFS disk is first initialized to random data before it is used, then all data written to it is encrypted, making
it indistinguishable from the garbage on the disk. It uses the same scheme to order files as HashFS.
---Users---
When Dreckig OS is booted up you will first be prompted for a username and password. The default priveleged acount is
root, it's password is root! Users are managed through the "user" command(only accessable while logged in as a user in group 0)
The user command has a few subcommands:
list - list all user accounts
add - make new user with specified name/password/group
kill - remove user with specified name
init - write a new initial user file to disk
How useres are handled is in the file named "user" on the currently inserted disk. This file has an entry for every user
with the user's name, a hash of their password, and their user group. User group 0 is the most priveleged, the user group is
stored as a char. The init subcommand just writes a "user" file to disk with an entry for root.
Now, how are user differant user's files kept seperate? Well, that is kinda a hack. As long as you are not in user group
0 then your user group id is prefixed to the name of every file you access. So if someone in group 1 tried to access the
"user" file they would get "1user" instead.
When you log in the script "run" is run. It is written in lang, and is in plaintext. When you add a new user you should
write a quick run script for them so that is doesn't hit random junk and hang/crash. The usual group based access rescticions
apply, such that group 1 runs "1run".
You can also access files in a specific user group by appending a username to the file name, such as:
sean:run
If sean is in user group 1 then this is the same as '1test'.
---Encryption---
The crypt command handles CryptFS, the stenographic file system for Dreckig OS. Basically it is just used to format a
disk and turn encryption on and off. Subcommands:
init - format a disk for CryptFS(Just full it with garbage)
on - turn on encryption
off - turn off encryption
stat - show CryptFS status
When you first log in encryption is turned off, so you need to turn it on if you want to use it. Also, don't run init on
a boot disk, insert a new disk first, it reflects on your good judgement. If you have to run it on a boot disk then go ahead,
it will just wipe *all* data on the disk, I mean **all**, every single sector. You can, however, turn encryption on for any
disk, even the dook disk.
---Editing text---
The text editor in Dreckig OS is DTE, the Dreckig Text Editor. It is almost useable! To make a file just type "dte" at
the command line, it will then prompt for a file name. If the file is empty ti will drop out to a proptless mode and let you
type. When you are done just type "quit" on a line alone, it will then write the file to disk.
If the file has data in it(Which is always the case if the disk is formated for CryptFS.) then that data will be
displayed. Then, you will be prompted for a line number. If you enter the line number(First one is 0!), then that line will be
displayed and you will be prompted for the data to replace it. When done with that line you will be given the line prompt
again. You can also enter commands here:
q - quit without saving
w - write file and quit
t - display file
</pre>
|
Shell
|
UTF-8
| 983
| 3.359375
| 3
|
[] |
no_license
|
#!/usr/bin/bash
#set -e
# keep track of the last executed command
#trap 'last_command=$current_command; current_command=$BASH_COMMAND' DEBUG
# echo an error message before exiting
#trap 'echo "\"${last_command}\" command failed with exit code $?." >&2' EXIT
bin_dir="/local/datasets"
inputFile=$1
outputDir=$2
DATABASES=$3
OPERATION=$4
#python sumstat2avinput.py $1 # argument1 is the summary statistic file we want to annotate
# here we convert it into annovar input format. the output is avinput_version.txt file
#echo $DATABASES
#echo $OPERATION
perl "${bin_dir}/table_annovar.pl" "${inputFile}" "${bin_dir}/humandb/" -buildver hg19 \
-out "${outputDir}/annotation_output" -remove -protocol "${DATABASES}" \
-operation "${OPERATION}" -nastring . -csvout -polish -xref "${bin_dir}/example/gene_xref.txt"
#echo "the output file is annotation_output.refGene.variant_function "
#less annotation_output.refGene.variant_function
#this is the final output we are looking for.
|
C++
|
UTF-8
| 6,585
| 3.1875
| 3
|
[] |
no_license
|
#include <gtest/gtest.h>
#include <iostream>
#include "utils.h"
#include "command_buffer.h"
TEST(CommandBuffer, Simple)
{
std::ostringstream result;
CommandBuffer buf(3, [&result](const Bulk& bulk) { result << bulk << "\n"; });
for (int i = 0; i < 3; i++)
buf.pushCommand("1");
ASSERT_EQ(buf.getLinesCount(), 3);
ASSERT_EQ(buf.getCommandsCount(), 3);
ASSERT_EQ(buf.getBulksCount(), 1);
ASSERT_EQ(result.str(), "bulk: 1, 1, 1\n");
}
TEST(CommandBuffer, Single)
{
std::ostringstream result;
CommandBuffer buf(1, [&result](const Bulk& bulk) { result << bulk << "\n"; });
for (int i = 0; i < 3; i++) {
buf.pushCommand("1");
}
ASSERT_EQ(buf.getLinesCount(), 3);
ASSERT_EQ(buf.getCommandsCount(), 3);
ASSERT_EQ(buf.getBulksCount(), 3);
ASSERT_EQ(result.str(), "bulk: 1\nbulk: 1\nbulk: 1\n");
}
TEST(CommandBuffer, Many)
{
std::ostringstream result;
CommandBuffer buf(2, [&result](const Bulk& bulk) { result << bulk << "\n"; });
for (int i = 0; i < 4; i++) {
buf.pushCommand("o");
}
ASSERT_EQ(buf.getLinesCount(), 4);
ASSERT_EQ(buf.getCommandsCount(), 4);
ASSERT_EQ(buf.getBulksCount(), 2);
ASSERT_EQ(result.str(), "bulk: o, o\nbulk: o, o\n");
}
TEST(CommandBuffer, Flush)
{
std::ostringstream result;
{
CommandBuffer buf(2, [&result](const Bulk& bulk) { result << bulk << "\n"; });
for (int i = 0; i < 3; i++) {
buf.pushCommand("k");
}
buf.flush();
ASSERT_EQ(buf.getLinesCount(), 3);
ASSERT_EQ(buf.getCommandsCount(), 3);
ASSERT_EQ(buf.getBulksCount(), 2);
}
ASSERT_EQ(result.str(), "bulk: k, k\nbulk: k\n");
}
TEST(CommandBuffer, Group)
{
std::ostringstream result;
{
CommandBuffer buf(2, [&result](const Bulk& bulk) { result << bulk << "\n"; });
buf.pushCommand("0"); // a group breaks previously unfinished bulk (thus sending it to output)
buf.pushGroup();
buf.pushCommand("1");
buf.pushCommand("2");
buf.pushCommand("3");
buf.popGroup();
ASSERT_EQ(buf.getLinesCount(), 6);
ASSERT_EQ(buf.getCommandsCount(), 4);
ASSERT_EQ(buf.getBulksCount(), 2);
}
ASSERT_EQ(result.str(), "bulk: 0\nbulk: 1, 2, 3\n");
}
TEST(CommandBuffer, Other)
{
std::ostringstream result;
{
CommandBuffer buf(1, [&result](const Bulk& bulk) { result << bulk << "\n"; });
buf.pushGroup();
buf.pushCommand("cmd1");
buf.pushCommand("cmd2");
buf.pushGroup();
buf.pushCommand("cmd3");
buf.pushCommand("cmd4");
buf.popGroup();
buf.pushCommand("cmd5");
buf.pushCommand("cmd6");
buf.popGroup();
ASSERT_EQ(buf.getLinesCount(), 10);
ASSERT_EQ(buf.getCommandsCount(), 6);
ASSERT_EQ(buf.getBulksCount(), 1);
}
ASSERT_EQ(result.str(), "bulk: cmd1, cmd2, cmd3, cmd4, cmd5, cmd6\n");
}
TEST(CommandBuffer, GroupNested)
{
std::ostringstream result;
{
// nested {} doesn't do anything
CommandBuffer buf(2, [&result](const Bulk& bulk) { result << bulk << "\n"; });
buf.pushGroup();
buf.pushCommand("1");
buf.pushGroup();
buf.pushCommand("2");
buf.popGroup();
buf.pushCommand("3");
buf.popGroup();
ASSERT_EQ(buf.getLinesCount(), 7);
ASSERT_EQ(buf.getCommandsCount(), 3);
ASSERT_EQ(buf.getBulksCount(), 1);
}
ASSERT_EQ(result.str(), "bulk: 1, 2, 3\n");
}
TEST(CommandBuffer, GroupTerminate)
{
std::ostringstream result;
{
// unfinished group should be terminated if it hasn't been closed with }
CommandBuffer buf(2, [&result](const Bulk& bulk) { result << bulk << "\n"; });
buf.pushGroup();
buf.pushCommand("1");
buf.pushCommand("2");
buf.pushCommand("3");
ASSERT_EQ(buf.getLinesCount(), 4);
ASSERT_EQ(buf.getCommandsCount(), 3);
ASSERT_EQ(buf.getBulksCount(), 0);
}
ASSERT_EQ(result.str(), "");
}
///////////////////////////////////
TEST(CommandBuffer, ParseString)
{
std::ostringstream result;
{
// unfinished group should be terminated if it hasn't been closed with }
CommandBuffer buf(2, [&result](const Bulk& bulk) { result << bulk << "\n"; });
buf.receiveText("{");
buf.receiveText("\ncmd1");
buf.receiveText("\n}\n");
ASSERT_EQ(buf.getLinesCount(), 3);
ASSERT_EQ(buf.getCommandsCount(), 1);
ASSERT_EQ(buf.getBulksCount(), 1);
}
ASSERT_EQ(result.str(), "bulk: cmd1\n");
}
TEST(CommandBuffer, ParseString2)
{
std::ostringstream result;
{
// unfinished group should be terminated if it hasn't been closed with }
CommandBuffer buf(3, [&result](const Bulk& bulk) { result << bulk << "\n"; });
buf.receiveText("cm");
buf.receiveText("d1\n");
buf.receiveText("cmd2\n");
buf.receiveText("cmd3");
buf.receiveText("\n");
ASSERT_EQ(buf.getLinesCount(), 3);
ASSERT_EQ(buf.getCommandsCount(), 3);
ASSERT_EQ(buf.getBulksCount(), 1);
}
ASSERT_EQ(result.str(), "bulk: cmd1, cmd2, cmd3\n");
}
TEST(CommandBuffer, ParseString3)
{
std::ostringstream result;
{
// unfinished group should be terminated if it hasn't been closed with }
CommandBuffer buf(1, [&result](const Bulk& bulk) { result << bulk << "\n"; });
buf.receiveText("{\ncmd1\ncmd2");
buf.receiveText("\n{\ncmd3\n");
buf.receiveText("cmd4\n}\n");
buf.receiveText("cmd5\ncm");
buf.receiveText("d6\n}\n");
ASSERT_EQ(buf.getLinesCount(), 10);
ASSERT_EQ(buf.getCommandsCount(), 6);
ASSERT_EQ(buf.getBulksCount(), 1);
}
ASSERT_EQ(result.str(), "bulk: cmd1, cmd2, cmd3, cmd4, cmd5, cmd6\n");
}
///////////////////////////////////
TEST(Utils, StripSpaces)
{
std::string str;
str = "abc";
stripSpaces(str);
ASSERT_EQ(str, "abc");
str = " a";
stripSpaces(str);
ASSERT_EQ(str, "a");
str = "b ";
stripSpaces(str);
ASSERT_EQ(str, "b");
str = " c ";
stripSpaces(str);
ASSERT_EQ(str, "c");
str = " ";
stripSpaces(str);
ASSERT_EQ(str, "");
str = " ";
stripSpaces(str);
ASSERT_EQ(str, "");
str = "";
stripSpaces(str);
ASSERT_EQ(str, "");
}
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
C
|
UTF-8
| 842
| 3.21875
| 3
|
[] |
no_license
|
/*Yansen Sheng*/
#include <stdio.h>
int main() {
char *h="Hello";
char *g="Goodbye";
char *c[]={
"/*Yansen Sheng*/%c",
"#include <stdio.h>%c",
"int main() {%c",
" char *h=%cHello%c;%c",
" char *g=%cGoodbye%c;%c",
" char *c[]={%c",
" %c%s%c%c%c",
" };%c",
" puts(h);%c",
" for(int i=0;i<6;i++)%c",
" if(i==3||i==4)%c",
" printf(c[i],34,34,10);%c",
" else%c",
" printf(c[i],10);%c",
" for(i=0;i<21;i++)%c",
" printf(c[6],34,c[i],34,44,10);%c",
" for(i=7;i<21;i++)%c",
" printf(c[i],10);%c",
" puts(g);%c",
" return 0;%c",
"}%c",
};
puts(h);
for(int i=0;i<6;i++)
if(i==3||i==4)
printf(c[i],34,34,10);
else
printf(c[i],10);
for(i=0;i<21;i++)
printf(c[6],34,c[i],34,44,10);
for(i=7;i<21;i++)
printf(c[i],10);
puts(g);
return 0;
}
|
JavaScript
|
UTF-8
| 1,049
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
$(document).ready(function() {
$("#formOne").submit(function(event) {
var blanks = ["animal", "food", "number", "adjective", "nounplural", "noun", "partofbody"];
blanks.forEach(function(blank) {
var userInput = $("input#" + blank).val();
$("." + blank).text(userInput);
});
// Old code from week 2:
// var animalInput= $("input#animal").val();
// var foodInput = $("input#food").val();
// var numberInput = $("input#number").val();
// var adjectiveInput = $("input#adjective").val();
// var nounPluralInput = $("input#nounplural").val();
// var nounInput = $("input#noun").val();
// var partOfBodyInput = $("input#partofbody").val()
//
// $(".animal").text(animalInput);
// $(".food").text(foodInput);
// $(".number").text(numberInput);
// $(".adjective").text(adjectiveInput);
// $(".nounplural").text(nounPluralInput);
// $(".noun").text(nounInput);
// $(".partofbody").text(partOfBodyInput);
$("#story").show();
event.preventDefault();
})
})
|
C#
|
UTF-8
| 1,458
| 2.6875
| 3
|
[] |
no_license
|
using AlienCompadre_DAL.Connection;
using AlienCompadre_Entities;
using System.Data;
using System.Data.SqlClient;
namespace AlienCompadre_DAL.Handler {
public class ClsHandlerDAL {
/// <summary>
/// Inserta las estadisticas de la partida en la base de datos.
/// </summary>
/// <param name="stats">Stadisticas de la partida</param>
/// <returns> Numero de filas afectadas</returns>
public int insertarStats_DAL(ClsStats stats) {
int filas = 0;
ClsMyConnection gestConexion = new ClsMyConnection();
SqlConnection conexion = gestConexion.getConnection();
SqlCommand miComando = new SqlCommand();
//Definir los parametros del comando
miComando.CommandText = "INSERT INTO stats(name, score) values (@nombre, @puntos)";
//Añadimos los parametros
if (stats.Name != "") {
miComando.Parameters.Add("@nombre", SqlDbType.VarChar).Value = stats.Name;
} else {
miComando.Parameters.Add("@nombre", SqlDbType.Int).Value = "null";
}
miComando.Parameters.Add("@puntos", SqlDbType.VarChar).Value = stats.Score;
miComando.Connection = conexion;
filas = miComando.ExecuteNonQuery();
//Cerramos la conexion
gestConexion.closeConnection(ref conexion);
return filas;
}
}
}
|
Python
|
UTF-8
| 443
| 2.734375
| 3
|
[] |
no_license
|
import requests
# cookies
# requests.get("http://httpbin.org/cookies/set/number/123456789")
# r = requests.get("http://httpbin.org/cookies")
# print(r.text)
#session
s = requests.session()
s.get("http://httpbin.org/cookies/set/number/123456789")
r = s.get("http://httpbin.org/cookies")
print(r.text)
# 利用session可以做到模拟同一个会话而不用担心cookies的问题,通常用于模拟登陆之后再进行下一步的操作
|
Python
|
UTF-8
| 321
| 3.234375
| 3
|
[] |
no_license
|
class Ex(Exception):
pass
def foo():
print("foo")
raise RuntimeError
try:
foo()
except Ex:
print("Exception detected")
except ZeroDivisionError:
print("durch 0 geteilt, welt explodiert")
except RuntimeError as er:
print("RuntimeError", er)
else:
print("keine exception")
print("weiter")
|
Rust
|
UTF-8
| 882
| 3.515625
| 4
|
[] |
no_license
|
extern crate tap;
use tap::*;
#[test]
fn filter_map() {
let values: &[Result<i32, &str>] = &[Ok(3), Err("foo"), Err("bar"), Ok(8)];
let _ = values.iter().filter_map(|result| {
// It is especially useful in filter maps, allowing error information to
// be logged/printed before the information is discarded.
result
.tap_err(|error| println!("Invalid entry: {}", error))
.ok()
});
}
#[test]
fn basic() {
let mut foo = 5;
// The `tap` extension can be used on all types
if 10.tap(|v| foo += *v) > 0 {
assert_eq!(foo, 15);
}
// Results have `tap_err` & `tap_ok` available.
let _: Result<i32, i32> = Err(5).tap_err(|e| foo = *e);
assert_eq!(foo, 5);
// Options have `tap_some` & `tap_none` available.
let _: Option<i32> = None.tap_none(|| foo = 10);
assert_eq!(foo, 10);
}
|
Java
|
UTF-8
| 774
| 3.46875
| 3
|
[] |
no_license
|
class myNewThread implements Runnable{
Thread t;
public void run(){
try{
for(int m = 0; m < 5 ; m++){
System.out.println("Child Thread: " + m);
Thread.sleep(1000);
//t.join();
}
}catch(Exception e){
e.printStackTrace();
}
System.out.println("Exiting Child Thread");
}
}
public class multiThreadInterface {
public static void main(String ar[]){
Thread mt = new Thread(new myNewThread());
try{
mt.start();
mt.join();
for (int i = 0; i < 5; i++) {
System.out.println("Main Thread: " + i);
Thread.sleep(500);
}
}catch(Exception e){
e.printStackTrace();
}
try{
}catch(Exception e){
e.printStackTrace();
}
System.out.println("Main Thread Exiting");
}
}
|
Python
|
UTF-8
| 711
| 3.734375
| 4
|
[] |
no_license
|
"""
http://rosalind.info/problems/tree/
Given: A positive integer n (n≤1000) and an adjacency list corresponding to a
graph on n nodes that contains no cycles.
Return: The minimum number of edges that can be added to the graph to produce
a tree.
>>> problem(10, [(1, 2), (2, 8), (4, 10), (5, 9), (6, 10), (7, 9)])
3
"""
def problem(n, edges):
return n - len(edges) - 1
if __name__ == '__main__':
import doctest
from os.path import dirname
doctest.testmod()
dataset = open(dirname(__file__) + "/rosalind_tree.txt").readlines()
n = int(dataset[0])
edges = []
for i in range(1, len(dataset)):
edges.append(map(int, dataset[i].split()))
print problem(n, edges)
|
Java
|
UTF-8
| 2,206
| 2.140625
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.solutio.licita.filtros;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author Matheus Oliveira
*/
public class FiltroLogin implements Filter {
private static Logger log = Logger.getGlobal();
@Override
public void init(FilterConfig filterConfig) throws ServletException {
//TODO
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpSession sessao = req.getSession(true);
if (req.getRequestURI().contains("login") || req.getRequestURI().equals("/Licita/")) {
if (sessao.getAttribute("usuario") == null) {
log.log(Level.INFO, "Redirecionando para: {0}", req.getRequestURL());
chain.doFilter(request, response);
} else {
((HttpServletResponse) response)
.sendRedirect(((HttpServletRequest) request).getContextPath() + "/restrito/index.xhtml");
}
} else if (sessao.getAttribute("usuario") != null && !sessao.isNew()) {
log.log(Level.INFO, "Redirecionando para: {0}", req.getRequestURL());
chain.doFilter(request, response);
} else {
((HttpServletResponse) response)
.sendRedirect(((HttpServletRequest) request).getContextPath() + "/restrito/login/login.xhtml");
}
}
@Override
public void destroy() {
//TODO
}
}
|
Java
|
UTF-8
| 1,110
| 2.53125
| 3
|
[] |
no_license
|
package simplehl7.model;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import simplehl7.parser.HL7Parser;
public class HL7Component {
private final List<String> subComponents = new ArrayList<String>();
private final HL7MessageConfig messageConfig;
public HL7Component(final HL7MessageConfig messageConfig) {
this.messageConfig = messageConfig;
}
public HL7Component(final String fullComponent, final HL7MessageConfig messageConfig) {
this(messageConfig);
setComponent(fullComponent);
}
public void setComponent(final String fullComponent) {
this.subComponents.clear();
if(!StringUtils.isBlank(fullComponent)) {
final String delimiter = Character.toString(messageConfig.getSubComponentDelimiter());
final String[] newSubComponents = fullComponent.trim().split(Pattern.quote(delimiter));
for(String newSubComponent: newSubComponents) {
subComponents.add(HL7Parser.unescape(newSubComponent, messageConfig));
}
}
}
public List<String> getSubComponents() {
return subComponents;
}
}
|
Python
|
UTF-8
| 1,090
| 2.671875
| 3
|
[] |
no_license
|
import csv
from bs4 import BeautifulSoup
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
# for chrome
# driver = webdriver.Chrome("C:\Users\Admin\Desktop\chromedriver.exe")
driver = webdriver.Chrome(ChromeDriverManager().install())
# url function
def get_url(search_term):
urlLink = "https://www.jumia.co.ke/catalog/?q={}"
# removing empty spaces
search_term = search_term.replace(' ','+')
# url formating
return urlLink.format(search_term)
# url
url = get_url('monitor')
driver.get(url)
soup = BeautifulSoup(driver.page_source,'html.parser')
results = soup.find_all('article',{'class':'prd _fb col c-prd'})
item = results[0]
name = item.h3.text
price = item.find('div','prc').text
discountblock = item.find('div','s-prc-w')
oldprice = discountblock.find('div','old').text
discount = discountblock.find('div','tag _dsct _sm').text
rating = item.find('div','stars _s').text
revBlock = item.find('div','rev').text
reviews = revBlock.replace(rating,'')
print(reviews)
|
Python
|
UTF-8
| 370
| 3.4375
| 3
|
[] |
no_license
|
from bs4 import BeautifulSoup
markup = "<h2 style='color:red'>Topics</h2><ul><li>Requests</li><li>Beautiful Soup</li></ul>"
bs = BeautifulSoup(markup, "html.parser")
print(bs.h2.text)
print(bs.h2['style'])
print("Using find_all() attribute")
for li in bs.find_all("li"):
print(li.text)
print("Using children attribute")
for li in bs.ul.children:
print(li.text)
|
Java
|
UTF-8
| 1,369
| 2.671875
| 3
|
[] |
no_license
|
Naive custom TrustManager (empty checkServerTrusted)
SSLContext sslContext = SSLContext.getInstance("SSL");
TrustManager trustManagerNaive = new X509TrustManager(){
@Override
public void checkClientTrusted(
X509Certificate[] chain,
String authType)
throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
@Override
public void checkServerTrusted(
X509Certificate[] chain,
String authType)
throws CertificateException {
// TODO Auto-generated method stub
}
};
sslContext.init(null, new TrustManager[]{trustManagerNaive}, null);
SSLSocketFactory socketFactory = (SSLSocketFactory)sslContext.getSocketFactory();
SSLSocket socket = (SSLSocket)socketFactory.createSocket(host, Integer.parseInt(port_number_et.getText().toString()));
//Native Android behavior (does not accept any untrusted certificate)
SSLSocketFactory socketFactory = (SSLSocketFactory)SSLSocketFactory.getDefault();
SSLSocket socket = (SSLSocket)socketFactory.createSocket(host, Integer.parseInt(port_number_et.getText().toString()));
|
C#
|
UTF-8
| 1,060
| 2.6875
| 3
|
[] |
no_license
|
using Game1.Sprite;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.Runtime.Serialization;
namespace Game1.Particle
{
class ShieldDeflect : IParticle
{
private ISprite sprite;
private Vector2 position;
private const int existFrames = 2;
private int frames = 0;
private bool exist = true;
public ShieldDeflect(Vector2 position)
{
sprite = ParticleSpriteFactory.Instance.CreateShieldDeflect();
this.position = position;
}
public void Update(GameTime gameTime)
{
//nothing to do here
}
public void Draw(SpriteBatch spriteBatch, Color color)
{
if (frames < existFrames)
{
sprite.Draw(spriteBatch, position, color);
frames++;
}
else
{
exist = false;
}
}
public bool ShouldDelete()
{
return !exist;
}
}
}
|
Java
|
UTF-8
| 4,413
| 3.28125
| 3
|
[] |
no_license
|
package exercise6registerapp;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Double> marks1 = new ArrayList<>();
marks1.add(4d);
marks1.add(3d);
marks1.add(4.5d);
Student student1 = new Student(marks1, "235409", "Jan", "Kowalski");
List<Double> marks2 = new ArrayList<>();
marks2.add(3d);
marks2.add(5d);
marks2.add(4d);
Student student2 = new Student(marks2, "115409", "Stanisław", "Nowak");
List<Double> marks3 = new ArrayList<>();
marks3.add(2d);
marks3.add(3d);
marks3.add(3d);
Student student3 = new Student(marks3, "215408", "Patrycja", "Zając");
List<Double> marks4 = new ArrayList<>();
marks4.add(5d);
marks4.add(3.5d);
marks4.add(4.5d);
Student student4 = new Student(marks4, "525439", "Zuzanna", "Mała");
List<Double> marks5 = new ArrayList<>();
marks5.add(3.5d);
marks5.add(2d);
marks5.add(4.5d);
Student student5 = new Student(marks5, "135437", "Tomasz", "Skała");
List<Student> students = new ArrayList<>();
students.add(student1);
Register register = new Register(students);
register.addStudent(student2);
System.out.println(register.getStudents().toString());
System.out.println();
register.addStudents(student3, student4, student5);
System.out.println(register.getStudents().toString());
System.out.println();
register.removeStudent(student5);
System.out.println(register.getStudents().toString());
System.out.println();
register.removeStudent("12413");
System.out.println();
register.removeStudents(student1, student4);
System.out.println(register.getStudents().toString());
System.out.println();
register.removeStudent("115409");
System.out.println(register.getStudents().toString());
System.out.println();
register.removeStudent("215408");
System.out.println(register.getStudents().toString());
System.out.println();
register.addStudents(student1, student2, student3, student4, student5);
System.out.println(register.getStudents().toString());
System.out.println();
register.getStudent("123456");
System.out.println();
Student theStudent = register.getStudent("235409");
System.out.println(theStudent);
System.out.println();
List<Student> theStudentsNotAll = register.getStudents("025439", "123456", "542310", "678952", "215408");
for (Student student : theStudentsNotAll) {
System.out.println(student);
}
System.out.println();
List<Student> theStudents = register.getStudents("235409", "115409", "135437");
for (Student student : theStudents) {
System.out.println(student);
}
System.out.println();
register.getStudentsAverage("123456");
System.out.println();
Double studentsAverage = register.getStudentsAverage("025439");
System.out.println(studentsAverage);
System.out.println();
List<Student> onTheLineStudents = register.getOnTheLineStudents();
if (onTheLineStudents.size() == 0) {
System.out.println("No on the line students :)");
} else {
for (Student onTheLineStudent : onTheLineStudents) {
System.out.println(onTheLineStudent);
}
}
System.out.println();
List<Student> sortedStudents = register.sortStudentsByIndex();
for (Student sortedStudent : sortedStudents) {
System.out.println(sortedStudent);
}
System.out.println();
register.addMark("123456", 4.5d);
System.out.println();
register.addMark("235409", 4.5d);
List<Double> marks = register.getStudent("235409").getMarks();
System.out.println(marks);
System.out.println();
register.addMark(5d, "123456");
System.out.println();
register.addMark(5d, "098765", students.get(0).getIndexNum(), students.get(1).getIndexNum(), "135437", "728423");
for (Student student : students) {
System.out.println(student);
}
}
}
|
Python
|
UTF-8
| 564
| 4.3125
| 4
|
[] |
no_license
|
import tkinter
# Let's create the Tkinter window
window = tkinter.Tk()
window.title("GUI")
# In order to display the image in a GUI, you will use the 'PhotoImage' method of Tkinter. It will an image from the directory (specified path) and store the image in a variable.
icon = tkinter.PhotoImage(file = "Ax1.png")
# Finally, to display the image you will make use of the 'Label' method and pass the 'image' variriable as a parameter and use the pack() method to display inside the GUI.
label = tkinter.Label(window, image = icon)
label.pack()
window.mainloop()
|
Java
|
UTF-8
| 4,520
| 2.875
| 3
|
[] |
no_license
|
package ru.yandex.C;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Solution solution = new Solution();
solution.solve(in, out);
out.close();
}
private static class Solution {
public void solve(InputReader in, PrintWriter out) {
String s = in.next();
int q = in.nextInt();
List<Pair> list = parseString(s);
for (int i = 1; i < list.size(); ++i) {
list.get(i).cnt += list.get(i - 1).cnt;
list.get(i).fenceLen += list.get(i - 1).fenceLen;
}
for (int i = 0; i < q; ++i) {
long l = in.nextLong();
long r = in.nextLong();
int li = getPosition(l, list);
int ri = getPosition(r, list);
if (li == ri) {
out.println((digLen(r - l + 1) + 1));
continue;
}
long ls = list.get(li).cnt, lr = l;
if (li - 1 >= 0) {
long val = list.get(li - 1).cnt;
ls -= val;
lr -= val;
}
long rr = r;
if (ri - 1 >= 0) {
long val = list.get(ri - 1).cnt;
rr -= val;
}
long result = 2 + digLen(ls - lr + 1) + digLen(rr);
if (li + 1 < ri) {
result += list.get(ri - 1).fenceLen - list.get(li).fenceLen;
}
out.println(result);
}
}
private int digLen(long d) {
if (d == 1) return 0;
int cnt = 0;
while (d > 0) {
d /= 10;
++cnt;
}
return cnt;
}
private int getPosition(long pos, List<Pair> list) {
int l = 0, r = list.size() - 1;
while (r - l > 1) {
int m = (l + r) / 2;
if (list.get(m).cnt > pos)
r = m;
else l = m;
}
if (list.get(l).cnt >= pos) return l;
return r;
}
private class Pair {
public long cnt;
public char c;
public long fenceLen;
public Pair(long cnt, char c, long fenceLen) {
this.cnt = cnt;
this.c = c;
this.fenceLen = fenceLen;
}
@Override
public String toString() {
return "Pair{" +
"cnt=" + cnt +
", c=" + c +
", fenceLen=" + fenceLen +
'}';
}
}
private List<Pair> parseString(String s) {
List<Pair> result = new ArrayList<>();
for (int i = 0; i < s.length(); ++i) {
int cnt = 0;
while (i < s.length() && Character.isDigit(s.charAt(i))) {
char q = s.charAt(i);
cnt = cnt * 10 + q - '0';
++i;
}
if (cnt == 0)
cnt = 1;
char c = s.charAt(i);
result.add(new Pair(cnt, c, 1 + digLen(cnt)));
}
return result;
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
|
Markdown
|
UTF-8
| 2,923
| 2.765625
| 3
|
[] |
no_license
|
---
date: 2017-04-01 17:03
status: public
title: 'BZOJ 1001 [BeiJing2006]狼抓兔子'
---
[题目链接] (http://www.lydsy.com/JudgeOnline/problem.php?id=1001)
# Solution
平面图转对偶图
平面图最小割 = 对偶图最短路
``` c++
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <functional>
using namespace std;
inline char getc()
{
static const int len = 1 << 15;
static char buf[len], *s, *t;
if (s == t)
{
t = (s = buf) + fread(buf, 1, len, stdin);
if (s == t)
return EOF;
}
return *s++;
}
inline void read(register int &x)
{
static char ch;
x = 0;
while (ch < '0')
ch = getc();
while (ch >= '0')
x = (x << 1) + (x << 3) + ch - '0', ch = getc();
}
template <typename T> inline bool tense(T &a, const T &b)
{
return b < a ? a = b, true : false;
}
template <typename T> inline bool relax(T &a, const T &b)
{
return a < b ? a = b, true : false;
}
const int maxn = 2e6 + 10;
const int maxm = 6e6 + 10;
struct edge
{
int to, len;
edge *next;
edge() {}
edge(int to, int len, edge *next) :to(to), len(len), next(next) {}
void* operator new(size_t);
}*head[maxn], mem[maxm];
void* edge :: operator new(size_t)
{
static edge *p = mem;
return p++;
}
void add(int x, int y, int z)
{
head[x] = new edge(y, z, head[x]);
head[y] = new edge(x, z, head[y]);
}
typedef pair <int, int> point;
point heap[maxm];
int f[maxm];
bool v[maxm];
int dijkstra(int S, int T)
{
memset(f, 0x3f, sizeof(f));
int size;
heap[size = 1] = point(f[S] = 0, S);
while (size)
{
int x = heap[1].second;
pop_heap(heap + 1, heap + size-- + 1, greater <point> ());
if (v[x])
continue;
v[x] = true;
for (edge *p = head[x]; p; p = p->next)
if (tense(f[p->to], f[x] + p->len))
heap[++size] = point(f[p->to], p->to),
push_heap(heap + 1, heap + size + 1, greater <point> ());
}
return f[T];
}
int main()
{
int n, m;
read(n);
read(m);
if (n == 1 || m == 1)
{
n = max(n, m) - 1;
int ans = ~0u >> 1, x;
while (n--)
read(x), tense(ans, x);
printf("%d\n", ans);
}
else
{
int mask = (n - 1) * (m - 1);
int S = (n - 1) * (m - 1) * 2 + 1;
int T = (n - 1) * (m - 1) * 2 + 2;
for (int i = 1, x; i <= n; i++)
for (int j = 1; j < m; j++)
{
read(x);
if (i == 1)
add((i - 1) * (m - 1) + j, T, x);
else if (i == n)
add((i - 2) * (m - 1) + mask + j, S, x);
else
add((i - 2) * (m - 1) + mask + j, (i - 1) * (m - 1) + j, x);
}
for (int i = 1, x; i < n; i++)
for (int j = 1; j <= m; j++)
{
read(x);
if (j == 1)
add(S, (i - 1) * (m - 1) + mask + 1, x);
else if (j == m)
add(i * (m - 1), T, x);
else
add((i - 1) * (m - 1) + j - 1, (i - 1) * (m - 1) + mask + j, x);
}
for (int i = 1, x; i < n; i++)
for (int j = 1; j < m; j++)
{
read(x);
add((i - 1) * (m - 1) + j, (i - 1) * (m - 1) + j + mask, x);
}
printf("%d\n", dijkstra(S, T));
}
}
```
|
Java
|
UTF-8
| 2,283
| 2.203125
| 2
|
[] |
no_license
|
package com.dp.ggomjirak.my.dao;
import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Repository;
@Repository
public class LikeBookmarkDaoImpl implements LikeBookmarkDao {
private static final String NAMESPACE = "com.dp.ggomjirak.likeBookmark.";
@Inject
SqlSession sqlSession;
@Override
public void updateLikeCount(int hobby_no, int count) {
Map<String, Integer> map = new HashMap<>();
map.put("hobby_no", hobby_no);
map.put("count", count);
sqlSession.update(NAMESPACE + "updateLikeCount", map);
}
@Override
public void insertLike(int hobby_no, String user_id) {
Map<String, Object> map = new HashMap<>();
map.put("hobby_no", hobby_no);
map.put("user_id", user_id);
sqlSession.insert(NAMESPACE + "insertLike", map);
}
@Override
public void deleteLike(int hobby_no, String user_id) {
Map<String, Object> map = new HashMap<>();
map.put("hobby_no", hobby_no);
map.put("user_id", user_id);
sqlSession.delete(NAMESPACE + "deleteLike", map);
}
@Override
public int likeCheck(int hobby_no, String user_id) {
Map<String, Object> map = new HashMap<>();
map.put("hobby_no", hobby_no);
map.put("user_id", user_id);
int count = sqlSession.selectOne(NAMESPACE + "likeCheck", map);
return count;
}
@Override
public int likeAll(int hobby_no) {
int count = sqlSession.selectOne(NAMESPACE + "likeAll", hobby_no);
System.out.println("dao count:" + count);
return count;
}
@Override
public void insertBookmark(int hobby_no, String user_id) {
Map<String, Object> map = new HashMap<>();
map.put("hobby_no", hobby_no);
map.put("user_id", user_id);
sqlSession.insert(NAMESPACE + "insertBookmark", map);
}
@Override
public void deleteBookmark(int hobby_no, String user_id) {
Map<String, Object> map = new HashMap<>();
map.put("hobby_no", hobby_no);
map.put("user_id", user_id);
sqlSession.delete(NAMESPACE + "deleteBookmark", map);
}
@Override
public int bookmarkCheck(int hobby_no, String user_id) {
Map<String, Object> map = new HashMap<>();
map.put("hobby_no", hobby_no);
map.put("user_id", user_id);
int count = sqlSession.selectOne(NAMESPACE + "bookmarkCheck", map);
return count;
}
}
|
C++
|
UTF-8
| 2,233
| 3.25
| 3
|
[] |
no_license
|
#include "stdafx.h"
#include "Directory.h"
#include <iostream>
Directory::Directory(const std::string& dirName, const Directory *parentDir)
: Entity(!dirName.empty() ? dirName : throw std::invalid_argument("Directory name cannot be empty"), parentDir)
{}
Directory::~Directory()
{
for (EntType::iterator iter = entities.begin(), endIter = entities.end(); iter != endIter; ++iter)
delete *iter;
}
void Directory::addFile(const std::string& fileName, const std::string& content)
{
entities.insert(new File(fileName, this, content));
}
void Directory::addDirectory(const std::string& dirName)
{
entities.insert(new Directory(dirName, this));
}
void Directory::removeEntity(const std::string& entName)
{
const Entity *tempPtr = getEntity(entName);
if (tempPtr != nullptr)
{
entities.erase(&Entity(entName, this));
delete tempPtr;
}
else
throw std::invalid_argument("No " + entName + " entity found");
}
bool Directory::containsEntity(const std::string& name) const
{
return getEntity(name) != nullptr;
}
const Entity * Directory::getEntity(const std::string name) const
{
EntType::const_iterator iter = entities.find(&Entity(name, this));
return iter != entities.end() ? *iter : nullptr;
}
int Directory::nrOfEntities() const
{
return entities.size();
}
bool Directory::operator==(const Directory& right) const
{
return Entity::operator==(right);
}
bool Directory::operator<(const Directory& right) const
{
return Entity::operator<(right);
}
const Directory* Directory::getSubdirectory(const std::string dirName) const
{
const Entity *ent;
if ( ( ent = getEntity(dirName) ) != nullptr )
{
const Directory *dir = nullptr;
if ((dir = dynamic_cast< const Directory *>(ent)) != 0)
return dir;
}
throw std::invalid_argument("No such directory found \"" + dirName + "\"");
}
std::string Directory::toString() const
{
std::string toReturn;
toReturn = "." + std::string("\t<DIR>\n");
if (this->parent != nullptr)
toReturn += ".." + std::string("\t<DIR>\n");
for each (Entity * ent in entities)
{
if (dynamic_cast< const Directory *>(ent) != nullptr )
toReturn += ent->getName() + "\t<DIR>\n";
else
toReturn += ent->getName() + "\t<FILE>\n";
}
return toReturn;
}
|
Java
|
UTF-8
| 903
| 2
| 2
|
[] |
no_license
|
package br.com.mind5.paymentPartner.partnerPagarme.orderPagarme.model.checker;
import br.com.mind5.model.checker.ModelChecker;
import br.com.mind5.model.checker.ModelCheckerOption;
import br.com.mind5.model.checker.ModelCheckerTemplateForward;
import br.com.mind5.payment.setupPartner.info.SetuparInfo;
import br.com.mind5.payment.setupPartner.model.checker.SetuparCheckExist;
import br.com.mind5.paymentPartner.partnerPagarme.orderPagarme.info.OrdapaInfo;
public final class OrdapaCheckSetupar extends ModelCheckerTemplateForward<OrdapaInfo, SetuparInfo> {
public OrdapaCheckSetupar(ModelCheckerOption option) {
super(option);
}
@Override protected ModelChecker<SetuparInfo> getCheckerHook(ModelCheckerOption option) {
return new SetuparCheckExist(option);
}
@Override protected SetuparInfo toForwardClass(OrdapaInfo baseRecord) {
return SetuparInfo.copyFrom(baseRecord);
}
}
|
C++
|
UTF-8
| 644
| 2.984375
| 3
|
[] |
no_license
|
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
string solve(string a, string b) {
string ret = "";
bool carry = 0;
bool first_non_zero = 0;
for (size_t i = 0, j = 0; i<a.size() || j<b.size(); i++, j++) {
int aa = i<a.size()?a[i]-'0':0;
int bb = j<b.size()?b[j]-'0':0;
int sum = aa+bb+carry;
carry = sum>=10;
int cc = sum%10;
if (!cc) {
if (first_non_zero) ret += '0';
} else {
first_non_zero = 1;
ret += cc+'0';
}
}
if (carry) ret += '1';
return ret;
}
int main() {
int t; cin >> t;
while (t--) {
string a, b; cin >> a >> b;
cout << solve(a, b) << endl;
}
return 0;
}
|
Java
|
UTF-8
| 567
| 3.015625
| 3
|
[] |
no_license
|
package team.six.youth.luowang.problem67;
public class Solution {
public String addBinary(String a, String b) {
if(a==null || b==null) return null;
int iA = a.length()-1;
int iB = b.length()-1;
int sum = 0;
StringBuilder sb = new StringBuilder();
while(iA >= 0 || iB >= 0 || sum == 1){
sum += iA >=0 ? (a.charAt(iA--)-'0') : 0;
sum += iB >=0 ? (b.charAt(iB--)-'0') : 0;
sb.insert(0,(char)(sum%2+'0'));
sum /= 2;
}
return sb.toString();
}
}
|
C++
|
SHIFT_JIS
| 1,204
| 2.625
| 3
|
[] |
no_license
|
#ifndef DTR_ELEMENT_DICTIONARY_ITEM_HPP
#define DTR_ELEMENT_DICTIONARY_ITEM_HPP
#include <string>
namespace dtr
{
//! f[^vf^O̍
class Element_Dictionary_Item
{
public:
//! \z
explicit Element_Dictionary_Item( const std::string& name, const std::string& vr, const std::string& vm, bool retired );
//! O擾
const std::string& get_name() const {
return name_;
}
//! l\擾
const std::string& get_vr() const {
return vr_;
}
//! lx擾
const std::string& get_vm() const {
return vm_;
}
//! ޖǂ擾
bool get_retired() const {
return retired_;
}
private:
std::string name_;
std::string vr_;
std::string vm_;
bool retired_;
};
} // namespace dtr
#endif
|
TypeScript
|
UTF-8
| 7,225
| 2.890625
| 3
|
[] |
no_license
|
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
// We can use this for any-to-any component communication through the use of the Services.
// BehaviorSubject
// * Is a type of subject (which is a type of Observable)
// * Can be subscribed to
// * Subscribers can receive updated results
// * A subject is an observer (so we can send values to it)
// * Needs an initial value (must always return a value on subscription)
// * On subscription returns last value of subject
// * Can use the getValue() method in no observable code
import { BehaviorSubject } from 'rxjs';
import { map } from 'rxjs/operators';
import { JwtHelperService } from '@auth0/angular-jwt';
import { environment } from '../../environments/environment';
import { User } from '../_models/user';
// This allows us to make the service injectible. Components does not need this decorator
// since components are automatically injectible.
@Injectable({
// Any components that will use this service will tell it which module is providing the service. In this
// case it is the root module with is the app.module.ts. When we add a new service, then we need to
// add it on our app.module.ts under the providers:[] array.
providedIn: 'root'
})
export class AuthService {
// This is defined in the environment.ts
baseUrl = environment.apiUrl + 'auth/';
jwtHelper = new JwtHelperService();
decodedToken: any;
currentUser: User;
photoUrl = new BehaviorSubject<string>('../../assets/user.png');
// Making the this.currentPhotoUrl property 'asObservable' mean we are able to subscribe
// to this.currentPhotoUrl property and if this is updated, then ANY components
// subscribing to it gets updated too. This is even if the application is refreshed,
// we log-in, we log-out, anything we do on any occasion the
// this.changeMemberPhoto(photoUrl: string)
// is going to be called, our photo url will be updated everywhere or any component
// that is subscribing to the this.currentPhotoUrl observable.
currentPhotoUrl = this.photoUrl.asObservable();
constructor(private http: HttpClient) { }
// This method will update the 'this.photoUrl' behavior subject
changeMemberPhoto(photoUrl: string) {
// This will update the value of the this.photoUrl instead of
// the default which is '../../assets/user.png'
if (photoUrl) {
this.photoUrl.next(photoUrl);
}
}
// This will take the model parameter that we have specified in the nav.component.ts
login(model: any) {
// Observable -- is a stream of data that is coming back from the server and in order
// get this observable data, we need to subscribe to it
// We will return an http POST with first parameter as the URL, second is the Body which we will send the
// model that will contain like
// {
// "Username": "john",
// "Password": "password"
// }
// and the third part is if we need to add options for this request like Headers. Do we need add Headers
// for this specific request. This is a post request and typically you might want to send Headers depending
// on the API you are using. Since we are using ASP.NET CORE, it is expected to receive the content
// as application/json. This is also the default header for Angular
// Since this just a log-in request, we don't need a third parameter.
// The response will return a token (as seen in Postman). And in order to do Observable when it comes back
// from the server, we need to use rxjs operator. We are using rxjs 6 for this course since we are using Angular 6.
return this.http.post(this.baseUrl + 'login', model)
// And in order to use rxjs map operators in Angular 6, we need to pass it through a pipe() method.
// This allows us to chain rxjs operators with our request
// We already know (from Postman), that we will get an object as a return for this request with 'token' as key and
// the actual token as value as defined in \DatingApp.API\Controllers\AuthController.cs
// var token = tokenHandler.CreateToken(tokenDescriptor);
// return Ok(new
// {
// token = tokenHandler.WriteToken(token)
// });
.pipe(
// We are now using the rxjs map operator
// We will pass in the response
map((response: any) => {
// This will contain the token response
const responseUser = response;
if (responseUser) {
localStorage.setItem('token', responseUser.token);
// The .setItem second parameter accepts a string and what we are getting
// back from our API server is an object. So, we will use JSON.stringify
// to convert the string into an object
localStorage.setItem('user', JSON.stringify(responseUser.user));
this.decodedToken = this.jwtHelper.decodeToken(responseUser.token);
this.currentUser = responseUser.user;
this.changeMemberPhoto(this.currentUser.photoUrl);
}
})
);
}
register(user: User) {
return this.http.post(this.baseUrl + 'register', user);
}
loggedIn() {
const token = localStorage.getItem('token');
// We will use a third party library called angular-jwt to manage the
// token we stored in the localStorage
// What we CANNOT DO is to validate the token since the key to validate the
// token is on the server \DatingApp.API\appsettings.json and we don't have
// access to that in the client application and we don't really need to do that
// in our client application since the client application is compiled into
// javascript and since javascript is run on the client-side, we don't want
// end-users to have access to the validation key
// Confusing names: angular 1 is renamed as angularjs
// and angular 2 is renamed as angular
// @auth0/angular-jwt: https://github.com/auth0/angular2-jwt and go for
// version 2.0.0
// If there is a value in this token, and is not expired,
// then it will return true else it will return false
return !this.jwtHelper.isTokenExpired(token);
}
roleMatch(allowedRoles): boolean {
/**
Our token is looking like
eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.
eyJuYW1laWQiOiIxMSIsInVuaXF1ZV9uYW1lIjoiQWRtaW4iLCJyb2xlIjpbIkFkbWluIiwi
TW9kZXJhdG9yIl0sIm5iZiI6MTU0NDMzNzU3MywiZXhwIjoxNTQ0NDIzOTczLCJpYXQi
OjE1NDQzMzc1NzN9.qJV0KHOdhBtZLQ-jR_KJC8JqAcr89holAUnQe7kAvAHBPrhMnAw1
8Nkeao5ebnk2UvPfPEYdcZhcQ4sk_ZK0ew
and if we debug it on jwt.io, the below is the result:
{
"nameid": "11",
"unique_name": "Admin",
"role": [
"Admin",
"Moderator"
],
"nbf": 1544337573,
"exp": 1544423973,
"iat": 1544337573
}
The token is stored in the this.decodedToken field so we can get the roles
if we will use this.decodedToken.role
*/
const userRoles = this.decodedToken.role as Array<string>;
let isMatch = false;
allowedRoles.forEach(element => {
// .includes determine whether an array includes a certain element, returning
// true or false as appropriate
if (userRoles.includes(element)) {
// If we will use return true, this method will not work correctly.
// Therefore, we need to add the field isMatch = true.
isMatch = true;
return;
}
});
return isMatch;
}
}
|
TypeScript
|
UTF-8
| 1,533
| 2.59375
| 3
|
[] |
no_license
|
import { Action } from 'redux';
import { ThunkAction, ThunkDispatch, } from 'redux-thunk';
import { getRides, addRide, deleteRide } from './rides/actions'
import { AppState } from '.'
import axios from "axios";
const config = {
headers: {
"Content-Type": "application/json"
}
};
export const thunkGetRides = (): ThunkAction<void, AppState, null, Action<string>> =>
async (dispatch: ThunkDispatch<AppState, null, Action<string>>): Promise<void> => {
const response = await axios.get('api/getData')
const data = await response.data.data;
dispatch(getRides(data))
}
export const thunkAddRide = (acceptedVerifiedRide: any): ThunkAction<void, AppState, null, Action<string>> =>
async (dispatch: ThunkDispatch<AppState, null, Action<string>>): Promise<void> => {
console.log('soon will post to bed')
const body = JSON.stringify(acceptedVerifiedRide);
const response = await axios
.post("/api/putData", body, config)
console.log(response)
dispatch(addRide(response.data.item))
}
export const thunkDeleteRide = (id: string): ThunkAction<void, AppState, null, Action<string>> =>
async (dispatch: ThunkDispatch<AppState, null, Action<string>>): Promise<void> => {
console.log('soon will delete to bed', id)
// const body = JSON.stringify({ id: id });
const response = await axios
.delete(`/api/deleteData/?id=${id}`, config)
console.log(response)
dispatch(deleteRide(id))
}
|
Python
|
UTF-8
| 433
| 3.484375
| 3
|
[
"MIT"
] |
permissive
|
import math
# y = 11
# x = 13
# y1 = 1
# y2 = 0
# x1 = 1
# x2 = 0
# radius = 10
#
# m = (y1 - y2) / (x1 - x2)
# b = y1 - m * x1
# temp_x = (y-b)/m
# print ("x", temp_x )
# print ("y", m * temp_x + b)
# print ((y-b)/m, m * (y-b)/m + b)
# temp_y = m * x + b
# print ("y", temp_y )
# print ("x", (temp_y - b)/m)
# print (((m * x + b) - b)/m , m * x + b)
a = 3
b = 7
c = 5
s = (a+b+c)/2
Area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print(Area)
|
Markdown
|
UTF-8
| 2,181
| 2.546875
| 3
|
[] |
no_license
|
### [2013-05-14](/news/2013/05/14/index.md)
# Several boats carrying over 100 Rohingya Muslims away from an oncoming cyclone capsize off the coast of Myanmar leaving only 42 survivors.
### Source:
1. [Wall Street Journal](http://online.wsj.com/article/SB10001424127887324216004578482850082867838.html)
### Related:
1. [Bangladesh accuses the Myanmar Army of laying landmines on the border between both countries to prevent the return of fleeing Rohingya refugees. Myanmar denies the Bangladeshi claims. ](/news/2017/09/6/bangladesh-accuses-the-myanmar-army-of-laying-landmines-on-the-border-between-both-countries-to-prevent-the-return-of-fleeing-rohingya-refug.md) _Context: Myanmar, Rohingya people_
2. [More than 123,000 Rohingya refugees have fled Myanmar and crossed into Bangladesh due to escalating violence by the Myanmar Army. ](/news/2017/09/5/more-than-123-000-rohingya-refugees-have-fled-myanmar-and-crossed-into-bangladesh-due-to-escalating-violence-by-the-myanmar-army.md) _Context: Myanmar, Rohingya people_
3. [At least 14 Rohingya people, including 10 children, fleeing violence in Myanmar are killed when their boat apparently hits a submerged object and capsizes just yards from the Bangladesh coast. ](/news/2017/09/28/at-least-14-rohingya-people-including-10-children-fleeing-violence-in-myanmar-are-killed-when-their-boat-apparently-hits-a-submerged-objec.md) _Context: Myanmar, Rohingya people_
4. [Bangladeshi Prime Minister Sheikh Hasina accuses the Burmese government of "atrocities" against the Rohingya people and calls for these alleged atrocities to stop. ](/news/2017/09/12/bangladeshi-prime-minister-sheikh-hasina-accuses-the-burmese-government-of-atrocities-against-the-rohingya-people-and-calls-for-these-alle.md) _Context: Myanmar, Rohingya people_
5. [Twenty-six bodies of women and children are recovered after three boats carrying ethnic Rohingya fleeing violence in Myanmar sink in the Naf River in Bangladesh's Cox's Bazar District. ](/news/2017/08/31/twenty-six-bodies-of-women-and-children-are-recovered-after-three-boats-carrying-ethnic-rohingya-fleeing-violence-in-myanmar-sink-in-the-naf.md) _Context: Myanmar, Rohingya people_
|
Markdown
|
UTF-8
| 2,208
| 2.859375
| 3
|
[] |
no_license
|
# Debugging
Debugging is a technique of finding and resolving of defects that prevent correct operations of software systems
In the early days of computing, debugging was cumbersome but now debugging is more seamless because of various tools called debuggers.
We can use debuggers in various languages and various IDEs.
Here are some of the debugging techniques for the most common IDEs in some common OOP languages.
## Debugging Process: Steps involved in debugging are:
* Identifying the problem
* Assigning the report to software engineer to the defect to verify that it is genuine.
* Defect Analysis using modeling, documentations, finding and testing candidate flaws, etc.
* Defect Resolution by making required changes to the system.
* Validation of corrections.
## Common Debugging Tools
### Python
* [Debug your Python code - Visual Studio](https://docs.microsoft.com/en-us/visualstudio/python/debugging-python-in-visual-studio?view=vs-2017)
* [Debugging in Python](https://www.codementor.io/gbozee/debugging-in-python-9ia7lof32)
* [Python Debugging With Pdb](https://realpython.com/python-debugging-pdb/)
### Java
* [Java Debugging with Eclipse](http://www.vogella.com/tutorials/EclipseDebugging/article.html)
## Concepts in Debugging
* Compiler: A computer program that transforms a source code into object code to create a machine executable program. A compiler error is the most common error when usually there is some missing syntax that does not allow the program to be executed.
* Breakpoint: A breakpoint is an intentional stopping or pausing point in the program temporarily added to inspect the underlying mechanics and check for errors.
* Exceptional Breakpoints
* Conditional Breakpoints
## Sources
* https://courses.edx.org/courses/course-v1:TUMx+SEECx+1T2018/courseware/66ff53b993894fcea837c84de9a437dc/215fa958631b44a1b0da1aa2f5806bdb/1?activate_block_id=block-v1%3ATUMx%2BSEECx%2B1T2018%2Btype%40vertical%2Bblock%4083c92969b1514801824d11c5a47955ff
* https://courses.edx.org/courses/course-v1:TUMx+SEECx+1T2018/course/#block-v1:TUMx+SEECx+1T2018+type@chapter+block@66ff53b993894fcea837c84de9a437dc
* https://www.geeksforgeeks.org/software-engineering-debugging/
|
Markdown
|
UTF-8
| 763
| 3.15625
| 3
|
[] |
no_license
|
## Overview
This Flask application contains the basic user management functionality (register, login, logout) to demonstrate the use of py.test.
## Motivation
After reading Brian Okken's book (Python Testing with py.test), I was convinced that I should learn about py.test and then figure out how to use it to test Flask applications.
## How to Run
In the top-level directory:
$ export FLASK_APP=main.py
$ flask run
## Key Python Modules Used
- Flask: micro-framework for web application development
- Jinga2 - templating engine
- SQLAlchemy - ORM (Object Relational Mapper)
- Flask-Bcrypt - password hashing
- Flask-Login - support for user management
- Flask-WTF - simplifies forms
This application is written using Python 3.6.
## Unit Testing
TBD
|
PHP
|
UTF-8
| 767
| 2.875
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
<?php declare(strict_types = 1);
namespace PharIo\Phive;
use PharIo\Version\Version;
class UnsupportedRelease implements Release {
/** @var string */
private $name;
/** @var Version */
private $version;
/** @var string */
private $reason;
public function __construct(string $name, Version $version, string $reason) {
$this->name = $name;
$this->version = $version;
$this->reason = $reason;
}
public function isSupported(): bool {
return false;
}
public function getVersion(): Version {
return $this->version;
}
public function getReason(): string {
return $this->reason;
}
public function getName(): string {
return $this->name;
}
}
|
Swift
|
UTF-8
| 3,211
| 2.875
| 3
|
[] |
no_license
|
//
// TimeCircuitsViewController.swift
// OutaTime
//
// Created by Michael on 12/18/19.
// Copyright © 2019 Michael. All rights reserved.
//
import UIKit
class TimeCircuitsViewController: UIViewController {
@IBOutlet weak var destinationTimeLabel: UILabel!
@IBOutlet weak var presentTimeLabel: UILabel!
@IBOutlet weak var lastTimeDepartedLabel: UILabel!
@IBOutlet weak var speedMPHLabel: UILabel!
var currentSpeed = 0
var destinationDate: Date?
var timer = Timer()
let now = Date()
var dateFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateFormat = "MMM dd,yyyy"
formatter.timeZone = TimeZone(secondsFromGMT: 0)
return formatter
}
func dateString(date: Date) -> String {
let timeRightNow = dateFormatter.string(from: now)
return timeRightNow
}
func updateViews() {
presentTimeLabel.text = dateString(date: now)
speedMPHLabel.text = "\(currentSpeed) MPH"
lastTimeDepartedLabel.text = "--- -- ----"
}
override func viewDidLoad() {
super.viewDidLoad()
updateViews()
// Do any additional setup after loading the view.
}
@IBAction func travelBackButtonTapped(_ sender: Any) {
startTimer()
}
func showAlert() {
guard let presentTimeLabel = presentTimeLabel.text else { return }
let timeTravelAlert = UIAlertController(title: "Time Travel Successful!", message: "Your new date is \(presentTimeLabel)", preferredStyle: .alert)
let okAlert = UIAlertAction(title: "Ok", style: .default, handler: nil)
timeTravelAlert.addAction(okAlert)
present(timeTravelAlert, animated: true, completion: nil)
}
func updateSpeed(timer: Timer) {
if currentSpeed >= 88 {
resetTimer()
lastTimeDepartedLabel.text = presentTimeLabel.text
presentTimeLabel.text = destinationTimeLabel.text
currentSpeed = 0
speedMPHLabel.text = String(currentSpeed)
showAlert()
} else {
currentSpeed += 1
speedMPHLabel.text = String(currentSpeed)
}
}
func startTimer() {
timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true, block: updateSpeed)
}
func resetTimer() {
timer.invalidate()
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ModalDestinationDatePickerSegue" {
guard let datePickerVC = segue.destination as? DatePickerViewController else { return }
datePickerVC.delegate = self
}
}
}
extension TimeCircuitsViewController: DatePickerDelegate {
func destinationDateWasChosen(date: Date) {
destinationDate = date
destinationTimeLabel.text = dateFormatter.string(from: date)
}
}
|
Python
|
UTF-8
| 946
| 2.65625
| 3
|
[] |
no_license
|
# docker 설치 및 사용하기
# docker install
# window pro 일때는 docker for windows
# window pro 외 docker toolbox
# 실행후 docker run hello-world를 이용하여 설치 확인
# docker pull continuumio/miniconda3 이미지 다운
# docker run -i -t continuumio/miniconda3 /bin/bash
# python3 -c "print(3*5)" 컨테이너에 담아 실행
# 빠져 나올때 exit
# 컨테이너 상태를 설정하기 위해서 (pip3 or pip)
# pip install beautifulsoup4
# pip install requests
# - 해쉬를 확인하기
# docker ps -a
# - 저장하기
# docker commit c7b81850d08f mlearn:init [저장해쉬][저장이름]:[태그]
# - 실행하기
# docker run -i -t mlearn:init
# - 마운트 (끼워넣기)
# docker run -i -t -v /c/users/user/sample:/sample mlearn:init
# 해당 git 에서 실행할 때
# docker run -i -t -v /c/users/user/git/study-python/Deep-Learning/chapter02:/chapter02 mlearn:init
# cd chapter ~~
# python ex ~~
|
Python
|
UTF-8
| 639
| 2.515625
| 3
|
[] |
no_license
|
from solution import Solution
from eval_module import quality
import json
TRAIN_DIR = 'train/txts/'
if __name__ == "__main__":
train = []
with open("train/gold_labels.txt", "r") as read_file:
for doc_info in read_file.readlines():
doc_dict = json.loads(doc_info)
docname = TRAIN_DIR + doc_dict['id'] + '.txt'
with open(docname, 'r') as f:
train.append((f.read(), doc_dict['label']))
solution = Solution()
test_data = [x[0] for x in train]
test_labels = [x[1] for x in train]
result = solution.predict(test_data)
print(quality(result, test_labels))
|
Go
|
UTF-8
| 3,002
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
package xweb
import (
"FishChatServer2/common/net/trace"
"FishChatServer2/common/net/xweb/context"
ctx "golang.org/x/net/context"
"net/http"
)
const (
_family = "go_http_server"
)
// web http pattern router
type Router struct {
mux *http.ServeMux
pattern string
}
// NewRouter new a router.
func NewRouter(mux *http.ServeMux) *Router {
return &Router{mux: mux}
}
func (r *Router) join(pattern string) string {
return r.pattern + pattern
}
func (r *Router) Group(pattern string) *Router {
return &Router{mux: r.mux, pattern: r.join(pattern)}
}
// Handler is an adapter which allows the usage of an http.Handler as a
// request handle.
func (r *Router) Handle(method, pattern string, handlers ...Handler) {
r.mux.HandleFunc(r.join(pattern), func(w http.ResponseWriter, r *http.Request) {
handler(method, w, r, handlers)
})
return
}
func (r *Router) HandlerFunc(method, pattern string, handlers ...HandlerFunc) {
r.mux.HandleFunc(r.join(pattern), func(w http.ResponseWriter, r *http.Request) {
handleFunc(method, w, r, handlers)
})
return
}
// Get is a shortcut for router.Handle("GET", path, handle)
func (r *Router) Get(pattern string, handlers ...Handler) {
r.mux.HandleFunc(r.join(pattern), func(w http.ResponseWriter, r *http.Request) {
handler("GET", w, r, handlers)
})
return
}
func (r *Router) Post(pattern string, handlers ...Handler) {
r.mux.HandleFunc(r.join(pattern), func(w http.ResponseWriter, r *http.Request) {
handler("POST", w, r, handlers)
})
return
}
// GetFunc is a shortcut for router.HandleFunc("GET", path, handle)
func (r *Router) GetFunc(pattern string, handlers ...HandlerFunc) {
r.mux.HandleFunc(r.join(pattern), func(w http.ResponseWriter, r *http.Request) {
handleFunc("GET", w, r, handlers)
})
return
}
// PostFunc is a shortcut for router.HandleFunc("GET", path, handle)
func (r *Router) PostFunc(pattern string, handlers ...HandlerFunc) {
r.mux.HandleFunc(r.join(pattern), func(w http.ResponseWriter, r *http.Request) {
handleFunc("POST", w, r, handlers)
})
return
}
func handler(method string, w http.ResponseWriter, r *http.Request, handlers []Handler) {
t := trace.WithHTTP(r)
t.ServerReceive(_family, r.URL.Path, "")
defer t.ServerSend()
if r.Method != method {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
c := context.NewContext(trace.NewContext(ctx.Background(), t), r, w)
for _, h := range handlers {
h.ServeHTTP(c)
if err := c.Err(); err != nil {
break
}
}
}
func handleFunc(method string, w http.ResponseWriter, r *http.Request, handlers []HandlerFunc) {
t := trace.WithHTTP(r)
t.ServerReceive(_family, r.URL.Path, "")
defer t.ServerSend()
if r.Method != method {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
c := context.NewContext(trace.NewContext(ctx.Background(), t), r, w)
for _, h := range handlers {
h(c)
if err := c.Err(); err != nil {
break
}
}
}
|
Go
|
UTF-8
| 10,261
| 2.703125
| 3
|
[
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] |
permissive
|
package bitQuery
import (
"github.com/edendoron/bit-framework/configs/rafael.com/bina/bit"
query "github.com/edendoron/bit-framework/internal/bitQuery"
"github.com/edendoron/bit-framework/internal/models"
"google.golang.org/protobuf/types/known/timestamppb"
"reflect"
"testing"
"time"
)
// test filterBitStatus
func TestFilterBitStatus1BitStatus(t *testing.T) {
// filter 1 failure from 1 bitStatus
var statusSlice = []bit.BitStatus{
{Failures: []*bit.BitStatus_RportedFailure{failure0, failure1}},
}
var expectedResult = []bit.BitStatus{
{Failures: []*bit.BitStatus_RportedFailure{failure1}},
}
maskedTests := []uint64{1}
query.FilterBitStatus(&statusSlice, maskedTests)
if !reflect.DeepEqual(statusSlice, expectedResult) {
if len(expectedResult) != len(statusSlice) {
t.Errorf("test failure filterBitStatus, expected %v statuses, got %v", len(expectedResult), len(statusSlice))
return
}
for i := range statusSlice {
if !reflect.DeepEqual(expectedResult[i].Failures, statusSlice[i].Failures) {
t.Errorf("test failure filterBitStatus, status array at index %v, expected %v failures, got %v", i, len(expectedResult[i].Failures), len(statusSlice[i].Failures))
}
}
}
}
func TestFilterBitStatus2BitStatus(t *testing.T) {
// filter 2 failures from different bitStatus
statusSlice := []bit.BitStatus{
{Failures: []*bit.BitStatus_RportedFailure{failure0, failure1}},
{Failures: []*bit.BitStatus_RportedFailure{failure2, failure3}},
}
expectedResult := []bit.BitStatus{
{Failures: []*bit.BitStatus_RportedFailure{failure1}},
{Failures: []*bit.BitStatus_RportedFailure{failure2}},
}
maskedTests := []uint64{1, 4}
query.FilterBitStatus(&statusSlice, maskedTests)
if !reflect.DeepEqual(statusSlice, expectedResult) {
if len(expectedResult) != len(statusSlice) {
t.Errorf("test failure filterBitStatus, expected %v statuses, got %v", len(expectedResult), len(statusSlice))
return
}
for i := range statusSlice {
if !reflect.DeepEqual(expectedResult[i].Failures, statusSlice[i].Failures) {
t.Errorf("test failure filterBitStatus, status array at index %v, expected %v failures, got %v", i, len(expectedResult[i].Failures), len(statusSlice[i].Failures))
}
}
}
}
func TestFilterBitStatusAllFailures(t *testing.T) {
// filter all failures in one bit status (bit status array is not empty)
statusSlice := []bit.BitStatus{
{Failures: []*bit.BitStatus_RportedFailure{failure0, failure1}},
{Failures: []*bit.BitStatus_RportedFailure{failure2, failure3}},
}
expectedResult := []bit.BitStatus{
{Failures: []*bit.BitStatus_RportedFailure{failure2, failure3}},
}
maskedTests := []uint64{1, 2}
query.FilterBitStatus(&statusSlice, maskedTests)
if !reflect.DeepEqual(statusSlice, expectedResult) {
if len(expectedResult) != len(statusSlice) {
t.Errorf("test failure filterBitStatus, expected %v statuses, got %v", len(expectedResult), len(statusSlice))
return
}
for i := range statusSlice {
if !reflect.DeepEqual(expectedResult[i].Failures, statusSlice[i].Failures) {
t.Errorf("test failure filterBitStatus, status array at index %v, expected %v failures, got %v", i, len(expectedResult[i].Failures), len(statusSlice[i].Failures))
}
}
}
// filter all failures (bit status array is empty)
statusSlice = []bit.BitStatus{
{Failures: []*bit.BitStatus_RportedFailure{failure0, failure1}},
}
expectedResult = []bit.BitStatus{}
maskedTests = []uint64{1, 2}
query.FilterBitStatus(&statusSlice, maskedTests)
if !reflect.DeepEqual(statusSlice, expectedResult) {
if len(expectedResult) != len(statusSlice) {
t.Errorf("test failure filterBitStatus, expected %v statuses, got %v", len(expectedResult), len(statusSlice))
return
}
for i := range statusSlice {
if !reflect.DeepEqual(expectedResult[i].Failures, statusSlice[i].Failures) {
t.Errorf("test failure filterBitStatus, status array at index %v, expected %v failures, got %v", i, len(expectedResult[i].Failures), len(statusSlice[i].Failures))
}
}
}
}
// test filterReports
func TestFilterReports(t *testing.T) {
// filter 2 reports by tag
var reportSlice = []models.TestReport{report0, report1, report2}
var expectedResult = []models.TestReport{report2}
filter := "tag"
var values = []string{"hostname123", "north"}
query.FilterReports(&reportSlice, filter, values)
if !reflect.DeepEqual(reportSlice, expectedResult) {
if len(expectedResult) != len(reportSlice) {
t.Errorf("test failure filterReports, expected %v reports, got %v", len(expectedResult), len(reportSlice))
return
}
}
// filter all reports by field
reportSlice = []models.TestReport{report0, report1, report2}
expectedResult = []models.TestReport{}
filter = "field"
values = []string{"temp"}
query.FilterReports(&reportSlice, filter, values)
if !reflect.DeepEqual(reportSlice, expectedResult) {
if len(expectedResult) != len(reportSlice) {
t.Errorf("test failure filterReports, expected %v reports, got %v", len(expectedResult), len(reportSlice))
return
}
}
// filter no reports by tag
reportSlice = []models.TestReport{report3, report4, report5}
expectedResult = []models.TestReport{report3, report4, report5}
filter = "tag"
values = []string{"hostname", "server02"}
query.FilterReports(&reportSlice, filter, values)
if !reflect.DeepEqual(reportSlice, expectedResult) {
if len(expectedResult) != len(reportSlice) {
t.Errorf("test failure filterReports, expected %v reports, got %v", len(expectedResult), len(reportSlice))
return
}
}
}
// temp variables for tests
var failure0 = &bit.BitStatus_RportedFailure{
FailureData: &bit.FailureDescription{
UnitName: "system test check",
TestName: "volts test",
TestId: 1,
BitType: []string{"CBIT"},
Description: "this is a mock failure to test services",
AdditionalInfo: "the failure finds voltage problem",
Purpose: "check voltage is within 1-7 range, with a deviation of 10%",
Severity: 1,
OperatorFailure: []string{
"unable to start",
"normal functionality is damaged",
},
LineReplacentUnits: []string{
"line1",
"line2",
},
FieldReplacemntUnits: []string{
"field1",
"field2",
"field3",
},
},
}
var failure1 = &bit.BitStatus_RportedFailure{
FailureData: &bit.FailureDescription{
UnitName: "system test check",
TestName: "temperature test",
TestId: 2,
BitType: []string{"CBIT"},
Description: "this is a mock failure to test services",
AdditionalInfo: "the failure finds temperature problem",
Purpose: "check temperature is within 60-80 range, with a deviation of 8",
Severity: 2,
OperatorFailure: []string{
"can't ignite",
"normal functionality is damaged",
},
LineReplacentUnits: []string{
"line1",
"line2",
},
FieldReplacemntUnits: []string{
"field1",
"field2",
"field3",
},
},
}
var failure2 = &bit.BitStatus_RportedFailure{
FailureData: &bit.FailureDescription{
UnitName: "system test check",
TestName: "pressure test",
TestId: 3,
BitType: []string{"CBIT, PBIT"},
Description: "this is a mock failure to test services",
AdditionalInfo: "the failure finds air pressure problem",
Purpose: "check pressure is out of 0-20 range, with a deviation of 16 percent",
Severity: 24,
OperatorFailure: []string{
"OperatorFailure1",
"OperatorFailure2",
"OperatorFailure3",
},
LineReplacentUnits: []string{
"line1",
"line2",
},
FieldReplacemntUnits: []string{
"field1",
"field2",
"field3",
},
},
Timestamp: timestamppb.Now(),
}
var failure3 = &bit.BitStatus_RportedFailure{
FailureData: &bit.FailureDescription{
UnitName: "system test check",
TestName: "oil test",
TestId: 4,
BitType: []string{"CBIT"},
Description: "this is a mock failure to test services",
AdditionalInfo: "the failure finds oil problem",
Purpose: "check oil is within 0-9 range, with a deviation of 1",
Severity: 1,
OperatorFailure: []string{
"unable to start",
"normal functionality is damaged",
},
LineReplacentUnits: []string{
"line1",
"line2",
},
FieldReplacemntUnits: []string{
"field1",
"field2",
"field3",
},
},
}
var report0 = models.TestReport{
TestId: 123,
ReportPriority: 12,
Timestamp: time.Now(),
TagSet: []models.KeyValue{
{Key: "hostname", Value: "server02"},
},
FieldSet: []models.KeyValue{
{Key: "volts", Value: "6.5"},
},
}
var report1 = models.TestReport{
TestId: 124,
ReportPriority: 12,
Timestamp: time.Now(),
TagSet: []models.KeyValue{
{Key: "hostname", Value: "server01"},
{Key: "ss", Value: "longstanding"},
},
FieldSet: []models.KeyValue{
{Key: "volts", Value: "10"},
{Key: "oil", Value: "4"},
},
}
var report2 = models.TestReport{
TestId: 125,
ReportPriority: 12,
Timestamp: time.Now(),
TagSet: []models.KeyValue{
{Key: "hostname123", Value: "north"},
},
FieldSet: []models.KeyValue{
{Key: "AirPressure", Value: "-1"},
},
}
var report3 = models.TestReport{
TestId: 126,
ReportPriority: 12,
Timestamp: time.Now(),
TagSet: []models.KeyValue{
{Key: "hostname123", Value: "north"},
{Key: "host", Value: "north east"},
{Key: "hostname", Value: "server02"},
},
FieldSet: []models.KeyValue{
{Key: "AirPressure", Value: "-3.3"},
{Key: "TemperatureCelsius", Value: "68"},
},
}
var report4 = models.TestReport{
TestId: 127,
ReportPriority: 12,
Timestamp: time.Now(),
TagSet: []models.KeyValue{
{Key: "hostname123", Value: "north"},
{Key: "host", Value: "north east"},
{Key: "hostname", Value: "server02"},
},
FieldSet: []models.KeyValue{
{Key: "AirPressure", Value: "50"},
{Key: "TemperatureCelsius", Value: "60"},
},
}
var report5 = models.TestReport{
TestId: 129,
ReportPriority: 12,
Timestamp: time.Now(),
TagSet: []models.KeyValue{
{Key: "hostname123", Value: "north"},
{Key: "host", Value: "north east"},
{Key: "hostname", Value: "server02"},
},
FieldSet: []models.KeyValue{
{Key: "AirPressure", Value: "10"},
{Key: "TemperatureCelsius", Value: "72"},
},
}
|
Java
|
UTF-8
| 344
| 1.921875
| 2
|
[] |
no_license
|
package com.gdn.pickup;
import com.gdn.request.PickupChoiceRequest;
import com.gdn.response.PickupChoiceResponse;
import com.gdn.response.WebResponse;
import javax.mail.MessagingException;
public interface PickupService {
WebResponse<PickupChoiceResponse> savePickup(PickupChoiceRequest pickupChoiceRequest) throws MessagingException;
}
|
Python
|
UTF-8
| 11,035
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
"""
This module implements the LLE_SMOTE method.
"""
import numpy as np
from numpy.linalg import LinAlgError
from sklearn.manifold import LocallyLinearEmbedding
from ..base import coalesce, coalesce_dict
from ..base import NearestNeighborsWithMetricTensor
from ..base import OverSamplingSimplex
from .._logger import logger
_logger = logger
__all__= ['LLE_SMOTE']
class LLE_SMOTE(OverSamplingSimplex):
"""
References:
* BibTex::
@INPROCEEDINGS{lle_smote,
author={Wang, J. and Xu, M. and Wang,
H. and Zhang, J.},
booktitle={2006 8th international Conference
on Signal Processing},
title={Classification of Imbalanced Data by Using
the SMOTE Algorithm and Locally Linear
Embedding},
year={2006},
volume={3},
number={},
pages={},
keywords={artificial intelligence;
biomedical imaging;medical computing;
imbalanced data classification;
SMOTE algorithm;
locally linear embedding;
medical imaging intelligence;
synthetic minority oversampling
technique;
high-dimensional data;
low-dimensional space;
Biomedical imaging;
Back;Training data;
Data mining;Biomedical engineering;
Research and development;
Electronic mail;Pattern recognition;
Performance analysis;
Classification algorithms},
doi={10.1109/ICOSP.2006.345752},
ISSN={2164-5221},
month={Nov}}
Notes:
* There might be numerical issues if the nearest neighbors contain
some element multiple times.
"""
categories = [OverSamplingSimplex.cat_extensive,
OverSamplingSimplex.cat_dim_reduction,
OverSamplingSimplex.cat_metric_learning]
def __init__(self,
proportion=1.0,
n_neighbors=5,
*,
n_components=2,
nn_params=None,
ss_params=None,
n_jobs=1,
random_state=None,
**_kwargs):
"""
Constructor of the sampling object
Args:
proportion (float): proportion of the difference of n_maj
and n_min to sample e.g. 1.0 means that after
sampling the number of minority samples will
be equal to the number of majority samples
n_neighbors (int): control parameter of the nearest neighbor
component
n_components (int): dimensionality of the embedding space
nn_params (dict): additional parameters for nearest neighbor calculations, any
parameter NearestNeighbors accepts, and additionally use
{'metric': 'precomputed', 'metric_learning': '<method>', ...}
with <method> in 'ITML', 'LSML' to enable the learning of
the metric to be used for neighborhood calculations
n_jobs (int): number of parallel jobs
random_state (int/RandomState/None): initializer of random_state,
like in sklearn
"""
nn_params = coalesce(nn_params, {})
ss_params_default = {'n_dim': 2, 'simplex_sampling': 'random',
'within_simplex_sampling': 'random',
'gaussian_component': None}
ss_params = coalesce_dict(ss_params, ss_params_default)
super().__init__(**ss_params, random_state=random_state)
self.check_greater_or_equal(proportion, 'proportion', 0)
self.check_greater_or_equal(n_neighbors, 'n_neighbors', 2)
self.check_greater_or_equal(n_components, 'n_components', 1)
self.check_n_jobs(n_jobs, 'n_jobs')
self.proportion = proportion
self.n_neighbors = n_neighbors
self.n_components = n_components
self.nn_params = nn_params
self.n_jobs = n_jobs
@ classmethod
def parameter_combinations(cls, raw=False):
"""
Generates reasonable parameter combinations.
Returns:
list(dict): a list of meaningful parameter combinations
"""
parameter_combinations = {'proportion': [0.1, 0.25, 0.5, 0.75,
1.0, 1.5, 2.0],
'n_neighbors': [3, 5, 7],
'n_components': [2, 3, 5]}
return cls.generate_parameter_combinations(parameter_combinations, raw)
def solve_for_weights(self,
xi, # pylint: disable=invalid-name
Z): # pylint: disable=invalid-name
"""
Solve for locally linear embedding weights
Args:
xi (np.array): vector
Z (np.array): matrix of neighbors in rows
Returns:
np.array: reconstruction weights
Following https://cs.nyu.edu/~roweis/lle/algorithm.html
"""
Z = Z - xi # pylint: disable=invalid-name
Z = Z.T # pylint: disable=invalid-name
C = np.dot(Z.T, Z) # pylint: disable=invalid-name
try:
weights = np.linalg.solve(C, np.repeat(1.0, C.shape[0]))
if np.linalg.norm(weights) > 1e8:
weights = np.repeat(1.0, C.shape[0])
except LinAlgError:
weights = np.repeat(1.0, C.shape[0])
return weights/np.sum(weights)
def embed_in_original_space(self,
X_min_transformed, # pylint: disable=invalid-name
X_min,
nnmt,
samples_raw):
"""
Carry out the embedding in the original feature space
Args:
X_min_transformed (np.array): the minority samples after LLE
X_min (np.array): the original minority samples
nnmt (obj): fitted nearest neighbors object
samples_raw (np.array): the raw samples
Returns:
np.array: the final samples
"""
ind = nnmt.kneighbors(samples_raw, return_distance=False)
samples = []
for idx, sample in enumerate(samples_raw):
weights = self.solve_for_weights(sample, X_min_transformed[ind[idx]])
samples.append(np.dot(weights, X_min[ind[idx]]))
return np.vstack(samples)
def sampling_algorithm(self, X, y):
"""
Does the sample generation according to the class parameters.
Args:
X (np.ndarray): training set
y (np.array): target labels
Returns:
(np.ndarray, np.array): the extended training set and target labels
"""
# determine the number of samples to generate
n_to_sample = self.det_n_to_sample(self.proportion)
if n_to_sample == 0:
return self.return_copies(X, y, "Sampling is not needed")
# extracting minority samples
X_min = X[y == self.min_label]
n_components = np.min([self.n_components, X.shape[1]])
n_neighbors = np.min([self.n_neighbors, X_min.shape[0] - 1])
# do the locally linear embedding
lle = LocallyLinearEmbedding(n_neighbors=n_neighbors,
n_components=n_components,
eigen_solver='dense',
n_jobs=self.n_jobs)
lle.fit(X_min)
X_min_transformed = lle.transform(X_min) # pylint: disable=invalid-name
# fitting the nearest neighbors model for sampling
n_neighbors = min([self.n_neighbors + 1, len(X_min_transformed)])
nn_params= {**self.nn_params}
nn_params['metric_tensor']= self.metric_tensor_from_nn_params(nn_params,
lle.transform(X),
y)
nnmt= NearestNeighborsWithMetricTensor(n_neighbors=n_neighbors,
n_jobs=self.n_jobs,
**(nn_params))
nnmt.fit(X_min_transformed)
ind = nnmt.kneighbors(X_min_transformed, return_distance=False)
samples_raw = self.sample_simplex(X=X_min_transformed,
indices=ind,
n_to_sample=n_to_sample)
samples = self.embed_in_original_space(X_min_transformed, # pylint: disable=invalid-name
X_min,
nnmt,
samples_raw)
# generating samples
#samples = []
#for _ in range(n_to_sample):
# idx = self.random_state.randint(len(X_min))
# random_coords = self.random_state.choice(ind[idx][1:])
# xi = self.sample_between_points(X_min_transformed[idx],
# X_min_transformed[random_coords])
# Z = X_min_transformed[ind[idx][1:]]
# w = solve_for_weights(xi, Z)
# samples.append(np.dot(w, X_min[ind[idx][1:]]))
return (np.vstack([X, samples]),
np.hstack([y, np.repeat(self.min_label, len(samples))]))
def get_params(self, deep=False):
"""
Returns:
dict: the parameters of the current sampling object
"""
return {'proportion': self.proportion,
'n_neighbors': self.n_neighbors,
'n_components': self.n_components,
'nn_params': self.nn_params,
'n_jobs': self.n_jobs,
**OverSamplingSimplex.get_params(self)}
|
C++
|
UTF-8
| 2,292
| 3.46875
| 3
|
[] |
no_license
|
#include <vector>
#include "gtest/gtest.h"
#include <iostream>
using namespace std;
class Solution
{
public:
Solution() : pattern_length(0), repeats(0), arr(0) {}
bool containsPattern(vector<int> &arr, int m, int k)
{
this->arr = arr;
pattern_length = m;
repeats = k;
for (int start_slice = 0; start_slice < int(arr.size()) - pattern_length * (repeats - 1); start_slice++)
{
int count = 1;
for (int start_pattern = start_slice + pattern_length;
start_pattern <= int(arr.size()) - pattern_length;)
{
if (are_slices_equal(start_slice, start_pattern))
{
++count;
start_pattern += pattern_length;
}
else
{
break;
}
}
if (count >= repeats)
{
return true;
}
}
return false;
}
private:
int pattern_length;
int repeats;
vector<int> arr;
bool are_slices_equal(int start_slice, int start_pattern)
{
for (int i = 0; i < pattern_length; i++)
{
if (arr[start_slice + i] != arr[start_pattern + i])
{
return false;
}
}
return true;
}
};
TEST(TestSuite, test_case_1)
{
Solution solution;
vector<int> input{1, 2, 4, 4, 4, 4};
ASSERT_TRUE(solution.containsPattern(input, 1, 3));
}
TEST(TestSuite, test_case_2)
{
Solution solution;
vector<int> input{1, 2, 1, 2, 1, 1, 1, 3};
ASSERT_TRUE(solution.containsPattern(input, 2, 2));
}
TEST(TestSuite, test_case_3)
{
Solution solution;
vector<int> input{1, 2, 1, 2, 1, 3};
ASSERT_FALSE(solution.containsPattern(input, 2, 3));
}
TEST(TestSuite, test_case_4)
{
Solution solution;
vector<int> input{1, 2, 3, 1, 2};
ASSERT_FALSE(solution.containsPattern(input, 2, 2));
}
TEST(TestSuite, test_case_5)
{
Solution solution;
vector<int> input{2, 2, 2, 2};
ASSERT_FALSE(solution.containsPattern(input, 2, 3));
}
TEST(TestSuite, test_case_6)
{
Solution solution;
vector<int> input{2, 2};
ASSERT_TRUE(solution.containsPattern(input, 1, 2));
}
|
Java
|
UTF-8
| 784
| 1.890625
| 2
|
[] |
no_license
|
package com.valor.model.web.response;
import java.util.Set;
/**
* @author Kemp.Cheng
* created on: 2019/11/19
* Copyright Valoroso Ltd. (c) 2019. All rights reserved.
*/
public class UpmsDetailsResponse {
private SysUserResponse upmsUserResponse;
private Set<SysAuthorityResponse> upmsAuthResponses;
public SysUserResponse getUpmsUserResponse() {
return upmsUserResponse;
}
public void setUpmsUserResponse(SysUserResponse upmsUserResponse) {
this.upmsUserResponse = upmsUserResponse;
}
public Set<SysAuthorityResponse> getUpmsAuthResponses() {
return upmsAuthResponses;
}
public void setUpmsAuthResponses(Set<SysAuthorityResponse> upmsAuthResponses) {
this.upmsAuthResponses = upmsAuthResponses;
}
}
|
C++
|
UTF-8
| 9,354
| 2.84375
| 3
|
[] |
no_license
|
#include <MicroView.h>
#include <Servo.h>
#include <EEPROM.h>
// This pin is for "up" button
const byte pin_up_button = 6;
// This pin is for "down"button
const byte pin_down_button = 5;
// Default gear
byte current_gear = 4;
// Pin for enable "tuning" mode
// (during which we can change the "gears" array's values)
const byte pin_tuning_mode = 0;
const byte pin_tune_up = 1;
const byte pin_tune_down = 3;
// This pin is connected with rear light
const byte pin_rear_light = A0;
// This pin is for button, which will handle rear light
const byte pin_rear_light_button = A5;
bool rear_light_button_pressed = false;
// Flag for "tuning" mode
bool tuning = false;
byte gear_up_pressed, gear_down_pressed, tune_mode_pressed, tune_up_pressed, tune_down_pressed = 0;
// Class for interacting with rear durailleur's servo
Servo rear_durailleur_servo;
const byte pin_rear_durailleur_servo = 2;
const byte gears_count = 11;
// Defines, which servo angle corresponds to each gear
byte gears_angles[gears_count] = {20, 40, 60, 80, 100, 120, 140, 160, 180};
byte current_angle;
// Allow me to intriduce the "Overshifting" - it's the future of bicycle shifting!
// When you switch to the next gear, the durailleur goes over it for an overshift_timeout
// (and after it back to the target gear) -
// and this will surely shifts you gear even in cases of a large transmission wear or dirt!
bool overshifting_enabled = true;
bool overshift_up_in_process = false, overshift_down_in_process = false;
byte overshift_timer, overshift_angle;
byte overshift_timeout = 30;
char message[20];
// Cycles to show messages on the bottom of the screen
int message_show_time = 200;
int message_timer = 0;
bool show_message = false;
/*---------------------------------------------------------------*/
void setup()
{
// Start MicroView screen
uView.begin();
// Define servo's pin
rear_durailleur_servo.attach(pin_rear_durailleur_servo);
// Configuring pins as inputs and enabling pull-up resistors
pinMode(pin_up_button, INPUT);
digitalWrite(pin_up_button, HIGH);
pinMode(pin_down_button, INPUT);
digitalWrite(pin_down_button, HIGH);
pinMode(pin_tune_up, INPUT);
digitalWrite(pin_tune_up, HIGH);
pinMode(pin_tuning_mode, INPUT);
// Configure this pin as input because rear light needs conection to ground (digital low)
// to be switched and I don't know what will be if connect it to 3.3V (digital high)
pinMode(pin_rear_light, OUTPUT);
pinMode(pin_rear_light_button, INPUT);
byte g;
// Reading stored gears angles from EEPROMovershift_down
for(byte i = 0; i < gears_count; i++)
{
g = EEPROM.read(i);
if (g != 255) // "Virgin" EEPROM's byte value is 255, so we don't need it
gears_angles[i] = g;
}
// Read saved current gear
current_gear = EEPROM.read(gears_count);
if (current_gear == 255)
current_gear = 4;
}
void save_to_EEPROM()
{
for(byte i = 0; i < gears_count; i++)
{
uView.clear(PAGE);
uView.setCursor(0, 0);
uView.print("Write EEPROM...");
uView.setCursor(0, 10);
uView.print("Gear "); uView.print(i + 1); uView.print(" val "); uView.print(gears_angles[i]);
uView.display();
// "Update" procedure is more sparing for EEPROM because it doesn't write value if it's the same
EEPROM.update(i, gears_angles[i]);
}
}
// Internal voltmeter reading
long readVcc() {
// Read 1.1V reference against AVcc
// set the reference to Vcc and the measurement to the internal 1.1V reference
#if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
#elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ADMUX = _BV(MUX5) | _BV(MUX0) ;
#else
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
#endif
delay(2); // Wait for Vref to settle
ADCSRA |= _BV(ADSC); // Start conversion
while (bit_is_set(ADCSRA,ADSC)); // measuring
uint8_t low = ADCL; // must read ADCL first - it then locks ADCH
uint8_t high = ADCH; // unlocks both
long result = (high<<8) | low;
result = 1125300L / result; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000
return result; // Vcc in millivolts
}
void loop()
{
uView.clear(PAGE);
if (digitalRead(pin_tuning_mode) == LOW)
tune_mode_pressed++;
else
tune_mode_pressed = 0;
if (digitalRead(pin_tune_up) == LOW)
tune_up_pressed++;
else
tune_up_pressed = 0;
if (digitalRead(pin_tune_down) == LOW)
tune_down_pressed++;
else
tune_down_pressed = 0;
// Detection of short-press of the "gear up" button or "tune up" button when not in tuning mode
if (digitalRead(pin_up_button) == LOW || (!tuning && tune_up_pressed == 1))
gear_up_pressed++;
else
gear_up_pressed = 0;
// Detection of shrt-press of the "gear down" button or "tune down" button when not in tuning mode
if (digitalRead(pin_down_button) == LOW || (!tuning && tune_down_pressed == 1))
gear_down_pressed++;
else
gear_down_pressed = 0;
// Detection of rear light button short-pressing
if (digitalRead(pin_rear_light_button) == LOW)
{
// State change detected
if (!rear_light_button_pressed)
{
// I don't know what will be if send to rear light HIGH signal,
// so we will just change this pin from input to output with low (ground) signal
// on each button pressing
pinMode(pin_rear_light, OUTPUT);
digitalWrite(pin_rear_light, LOW);
rear_light_button_pressed = true;
}
}
else // Detection of button release
{
// State change detected
if (rear_light_button_pressed)
{
pinMode(pin_rear_light, INPUT);
rear_light_button_pressed = false;
}
}
// If the "tuning mode" button has been pressed for 100 loops
// (long press)
if (tune_mode_pressed == 100)
{
if (!tuning)
tuning = true;
else
{
tuning = false;
// Saving new values to EEPROM
save_to_EEPROM();
}
}
// Short press on "tune mode" button - saving current ger to EEPROM
// (If we save current gear each time we switch it, EEPROM's writing cycles will last too soon.
// So we have button to save when we are to switch system off)
if (tune_mode_pressed == 1)
{
// Save to the next cell after all gears
EEPROM.update(gears_count, current_gear);
strcpy(message, "Gear saved");
message_timer = 0;
show_message = true;
}
uView.setCursor(0, 20);
if (tuning)
uView.print("tune: on");
else
uView.print("tune: off");
if (tuning && tune_up_pressed == 1 && (gears_angles[current_gear] < gears_angles[current_gear + 1] || current_gear == gears_count - 1))
gears_angles[current_gear]++;
if (tuning && tune_down_pressed == 1 && (gears_angles[current_gear] > gears_angles[current_gear - 1] || current_gear == 0))
gears_angles[current_gear]--;
if ( (gear_up_pressed == 1 || (!tuning && tune_up_pressed == 1) ) && current_gear < gears_count - 1)
{
current_gear++;
if (overshifting_enabled)
{
overshift_up_in_process = true;
overshift_timer = 0;
}
}
if (gear_down_pressed == 1 && current_gear > 0)
{
current_gear--;
if (overshifting_enabled)
{
overshift_down_in_process = true;
overshift_timer = 0;
}
}
if (!overshifting_enabled)
// If there is no overshifting, just switch to the next gear
current_angle = gears_angles[current_gear];
else
{
if (overshift_up_in_process || overshift_down_in_process)
{
if (overshift_timer < overshift_timeout)
{
overshift_timer++;
if (overshift_up_in_process)
if (current_gear != gears_count - 1) // Go to the middle from current to next
current_angle = gears_angles[current_gear] + (gears_angles[current_gear + 1] - gears_angles[current_gear]) / 3;
else // If we switched to the last gear
// Let's try to go over border
current_angle = gears_angles[current_gear] + 10;
if (overshift_down_in_process)
if (current_gear != 0)
current_angle = gears_angles[current_gear] - (gears_angles[current_gear] - gears_angles[current_gear - 1]) / 3;
else // If we switched to the first gear
// Let's try to go over border
current_angle = 0;
}
else
{ // If overshift timer is out, switch to the target gear
overshift_up_in_process = false;
overshift_down_in_process = false;
current_angle = gears_angles[current_gear];
}
}
else // Hold current gear
current_angle = gears_angles[current_gear];
}
// Set the servo to the current gear's angle
rear_durailleur_servo.write(current_angle);
// Display info on the screen
uView.setCursor(0, 0);
uView.print("gear: "); uView.print(current_gear + 1);
uView.setCursor(0, 10);
uView.print("angle: "); uView.print(current_angle);
uView.setCursor(0, 30);
uView.print("uV: "); uView.print(readVcc());
if (show_message)
{
uView.setCursor(0, 40);
uView.print(message);
if (message_timer < message_show_time)
message_timer++;
else
{
message_timer = 0;
show_message = false;
// message = "";
}
}
uView.display();
}
|
C
|
GB18030
| 844
| 3.734375
| 4
|
[] |
no_license
|
/****************************** (C) COPYRIGHT 2016 *******************************
* ܣָָȽϴС
* Ҫ㣺ָʹãעָ뺯ͺָ
*
********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
int min(int a, int b);
/*************************************************
Function: main
Description:
Calls: scanf printf
Called By:
Input:
Output:
Return: 0
*************************************************/
int main(void)
{
int (*pMin)(int, int) = min;
int a, b;
// pMin = min;
printf("input the two number:\n");
scanf("%d%d", &a, &b);
printf("Min:%d", (*pMin)(a, b));
}
int min(int a, int b)
{
if (a > b)
return b;
else
return a;
}
|
SQL
|
UTF-8
| 2,781
| 3.140625
| 3
|
[] |
no_license
|
-- phpMyAdmin SQL Dump
-- version 4.5.1
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Apr 20, 2017 at 07:22 PM
-- Server version: 10.1.16-MariaDB
-- PHP Version: 5.6.24
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `taxi`
--
-- --------------------------------------------------------
--
-- Table structure for table `booking`
--
CREATE TABLE `booking` (
`id` int(250) NOT NULL,
`Name` varchar(250) NOT NULL,
`Place` varchar(250) NOT NULL,
`Time` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `booking`
--
INSERT INTO `booking` (`id`, `Name`, `Place`, `Time`) VALUES
(5, 'Anshul', 'Malad', '2017/04/19'),
(6, 'Anshul', 'Malad', '2017/04/20'),
(7, 'Ravi', 'Andheri', '2017/04/20'),
(8, 'Giridhar', 'Bandra', '2017/04/20'),
(9, 'Ravi', 'Borivali', '2017/04/20'),
(10, 'Sumit', 'Virar', '2017/04/21'),
(11, 'Ravi', 'Andheri', '2017/04/20');
-- --------------------------------------------------------
--
-- Table structure for table `car`
--
CREATE TABLE `car` (
`id` int(250) NOT NULL,
`Name` varchar(250) NOT NULL,
`Place` varchar(250) NOT NULL,
`Type` varchar(250) NOT NULL,
`Price` varchar(250) NOT NULL,
`image` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `car`
--
INSERT INTO `car` (`id`, `Name`, `Place`, `Type`, `Price`, `image`) VALUES
(1, 'Maruti Swift', 'Goregaon', 'Hatchback', '500', 'swift.jpg'),
(2, 'Hyundai i20', 'Goregaon', 'Hatchback', '800', 'i20.jpg'),
(3, 'Mahindra XUV500', 'Borivali', 'SUV', '1200', 'xuv.jpg'),
(4, 'Mercedes Benz', 'Andheri', 'Luxury', '2000', 'mercedes.jpg'),
(5, 'Hyundai i20', 'Bandra', 'Hatchback', '1200', 'i20.jpg'),
(6, 'BMW', 'Churchgate', 'Luxury', '2500', 'bmw.jpg'),
(7, 'Rangerover', 'Dadar', 'Luxury', '2500', 'rangerover.jpg');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `booking`
--
ALTER TABLE `booking`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `car`
--
ALTER TABLE `car`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `booking`
--
ALTER TABLE `booking`
MODIFY `id` int(250) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13;
--
-- AUTO_INCREMENT for table `car`
--
ALTER TABLE `car`
MODIFY `id` int(250) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
C++
|
UTF-8
| 923
| 3.046875
| 3
|
[] |
no_license
|
// [49191] 순위 : https://programmers.co.kr/learn/courses/30/lessons/49191
#include <string>
#include <vector>
using namespace std;
bool map[101][101];
//플로이드 와샬
void solve(int n) {
//k: 거쳐가는 지점, i: 출발 지점, j: 도착 지점
for(int k = 1; k <= n; k++) {
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
if(map[i][k] && map[k][j])
map[i][j] = true;
}
}
}
}
int solution(int n, vector<vector<int>> results) {
int answer = 0;
for(int i = 0; i < results.size(); i++) {
int a = results[i][0];
int b = results[i][1];
map[a][b] = true;
}
solve(n);
for(int i = 1; i <= n; i++) {
int cnt = 0;
for(int j = 1; j <= n; j++) {
if(map[i][j] || map[j][i]) cnt++;
}
if(cnt == n-1) answer++;
}
return answer;
}
|
Java
|
UTF-8
| 362
| 1.804688
| 2
|
[] |
no_license
|
package com.baizhi.service;
import com.baizhi.entity.Banner;
import java.util.List;
/**
* Created by Administrator on 2018/8/29.
*/
public interface BannerService {
//查询所有
List<Banner> queryAll();
//添加
void add(Banner banner);
//修改状态
void update(Banner banner);
//删除
void delete(Banner banner);
}
|
C++
|
UTF-8
| 276
| 3.671875
| 4
|
[] |
no_license
|
#include<stdio.h>
int power(int n)
{
if(n==0) return 1;//if n=0,return 1
else return 2*power(n-1);//else return n*2^(n-1)
}
int main()
{
int a;
printf("Please input the exponent of 2:\n");
scanf("%d",&a);
printf("2 to the power of %d is %d\n",a,power(a));
return 0;
}
|
C++
|
UTF-8
| 993
| 3.421875
| 3
|
[
"Apache-2.0"
] |
permissive
|
#include "Test.hpp"
TEST(NameOfTheFirstTest, "This text indicates what's tested")
{
ASSERT_THROW(throw std::exception(), std::exception, "This test checks that an exception gets raised");
ASSERT_PASS(; , "This test checks that no exception gets raised");
};
TEST(NameOfTheSecondTest, "The tests can be splitted in multiples sections")
{
ASSERT_BOOL(true, "This checks that the given expression is true");
ASSERT_EQUAL(2, 2., "This checks the equality between 2 expressions");
ASSERT_EQUAL(2, 3, "All tests can be made skipable by adding the 'SKIP' keyword", SKIP);
};
TEST(NameOfTheThirdTest, "Each section will display its own message")
{
ASSERT_PASS_RPT(;, "Each test can be repeated a given number of time to prevent randomness", 5000);
ASSERT_THROW_RPT(; , std::exception, "Even repeatable tests can be made skipable", 5000, SKIP);
ASSERT_PERF(for (int i = 0; i < 6500; i++) { ; }, 1000, 0.01, "This checks that an action doesn't take more time than it should on average");
};
|
C++
|
UTF-8
| 2,982
| 3.265625
| 3
|
[] |
no_license
|
#include "provided.h"
#include <string>
#include <vector>
#include <iostream>
#include <istream>
using namespace std;
class GenomeImpl
{
public:
GenomeImpl(const string& nm, const string& sequence);
static bool load(istream& genomeSource, vector<Genome>& genomes);
int length() const;
string name() const;
bool extract(int position, int length, string& fragment) const;
private:
string m_name;
string m_sequence;
};
GenomeImpl::GenomeImpl(const string& nm, const string& sequence)
{
m_name = nm;
m_sequence = sequence;
}
bool GenomeImpl::load(istream& genomeSource, vector<Genome>& genomes)
{
genomes.clear();
string newGenome, nm, sequence = "";
bool passedFirst = false;
while (getline(genomeSource, newGenome))
{
if (newGenome == "")
return false;
else if (newGenome[0] == '>')
{
if (newGenome.substr(1) == "")
return false;
if (sequence != "")
{
Genome ng(nm, sequence);
genomes.push_back(ng);
}
else if (passedFirst)
return false;
nm = newGenome.substr(1);
sequence = "";
}
else
{
if (nm == "")
return false;
for (int i = 0; i < newGenome.length(); i++)
{
switch (newGenome[i])
{
case 'A':
case 'C':
case 'T':
case 'G':
case 'N':
{
sequence += newGenome[i];
break;
}
default:
{
return false;
}
}
}
passedFirst = true;
}
//newGenome = "";
}
if (nm != "" && sequence != "")
{
Genome ng(nm, sequence);
genomes.push_back(ng);
}
return passedFirst;
}
int GenomeImpl::length() const
{
return m_sequence.length();
}
string GenomeImpl::name() const
{
return m_name;
}
bool GenomeImpl::extract(int position, int length, string& fragment) const
{
int i = position;
for (; i < position + length && i < this->length(); i++)
{
fragment += m_sequence[i];
}
if (i < (length - 1))
return false;
else
return true;
}
//******************** Genome functions ************************************
// These functions simply delegate to GenomeImpl's functions.
// You probably don't want to change any of this code.
Genome::Genome(const string& nm, const string& sequence)
{
m_impl = new GenomeImpl(nm, sequence);
}
Genome::~Genome()
{
delete m_impl;
}
Genome::Genome(const Genome& other)
{
m_impl = new GenomeImpl(*other.m_impl);
}
Genome& Genome::operator=(const Genome& rhs)
{
GenomeImpl* newImpl = new GenomeImpl(*rhs.m_impl);
delete m_impl;
m_impl = newImpl;
return *this;
}
bool Genome::load(istream& genomeSource, vector<Genome>& genomes)
{
return GenomeImpl::load(genomeSource, genomes);
}
int Genome::length() const
{
return m_impl->length();
}
string Genome::name() const
{
return m_impl->name();
}
bool Genome::extract(int position, int length, string& fragment) const
{
return m_impl->extract(position, length, fragment);
}
|
JavaScript
|
UTF-8
| 2,953
| 2.875
| 3
|
[] |
no_license
|
/**
* detect IE
* returns version of IE or false, if browser is not Internet Explorer
*/
function detectIE() {
var ua = window.navigator.userAgent;
// Test values; Uncomment to check result …
// IE 10
// ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';
// IE 11
// ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';
// Edge 12 (Spartan)
// ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';
// Edge 13
// ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586';
var msie = ua.indexOf('MSIE ');
if (msie > 0) {
// IE 10 or older => return version number
return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
}
var trident = ua.indexOf('Trident/');
if (trident > 0) {
// IE 11 => return version number
var rv = ua.indexOf('rv:');
return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
}
var edge = ua.indexOf('Edge/');
if (edge > 0) {
// Edge (IE 12+) => return version number
return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
}
// other browser
return false;
}
var IEversion = detectIE();
console.log(IEversion);
if (!IEversion || IEversion > 10) {
'use strict';
var images = document.querySelectorAll('.js-lazy-image'),
config = {
rootMargin: '50px 0px',
threshold: 0.01
},
imageCount = images.length,
observer,
dataset;
if (!('IntersectionObserver' in window)) loadImagesImmediately(images);
else {
observer = new IntersectionObserver(onIntersection, config);
for (var image, i = 0; i < images.length; i++)(image = images[i], !image.classList.contains('js-lazy-image--handled')) && observer.observe(image)
}
function fetchImage(a) {
return new Promise(function(b, c) {
var d = new Image;
d.src = a, d.onload = b, d.onerror = c
})
}
function preloadImage(a) {
var b = a.dataset.src;
return b ? fetchImage(b).then(function() {
applyImage(a, b)
}) : void 0
}
function loadImagesImmediately(a) {
for (var d, b = Array.from(a), c = 0; c < a.length; c++) d = a[c], preloadImage(d)
}
function disconnect() {
observer && observer.disconnect()
}
function onIntersection(a) {
0 === imageCount && observer.disconnect();
for (var c, b = 0; b < a.length; b++) c = a[b], 0 < c.intersectionRatio && (imageCount--, observer.unobserve(c.target), preloadImage(c.target))
}
function applyImage(a, b) {
a.classList.add('js-lazy-image--handled'), a.src = b, a.classList.add('fade-in')
}
} else if (IEversion && IEversion <= 10) {
console.log(IEversion);
var img = $('img');
for (var i = 0; i < img.length; i++) {
image = img[i];
$(image).attr( 'src', $(image).attr('data-src') )
}
}
|
Markdown
|
UTF-8
| 2,533
| 2.625
| 3
|
[
"MIT",
"Artistic-2.0",
"ISC",
"Apache-2.0"
] |
permissive
|
---
lang: en
title: 'Migrating components contributing Models'
keywords: LoopBack 4, LoopBack 3, Migration, Extensions, Components, Models
sidebar: lb4_sidebar
permalink: /doc/en/lb4/migration-extensions-models.html
---
Please review the content in [Migrating models](../models/overview.md) first.
Going forward, we assume that you are already familiar with the differences
between LoopBack 3 Models and LoopBack 4 Entities & Repositories, and understand
how to migrate model-related functionality from a LoopBack 3 application to
LoopBack 4.
## Import LoopBack 3 models
The first step is to import LoopBack 3 model definitions into your LoopBack 4
component. This will convert LB3 model JSON files into LB4 TypeScript classes,
as explained in
[Import Model definition](../models/core.md#import-model-definition) and
[Importing models from LoopBack 3 projects](../../Importing-LB3-models.md).
1. Create a small LB3 app that is using your component.
2. In your LB4 extension project, run `lb4 import-lb3-models <path-to-lb3-app>`
to import model(s) contributed by the component from the LB3 app you created
in the previous step. Change the base class of the imported model(s) from
`Entity` to `Model` if needed.
## Migrate behavior-less models
Sometimes, a LoopBack 3 model does not provide any behavior, it is just
describing the shape of data (e.g. data fields in a push notification object).
Such models can be converted to LoopBack 4 models as follows:
1. Import the LoopBack 3 model to your LoopBack 4 project as explained in
[Import LoopBack 3 models](#import-loopback-3-models).
2. Ensure that your component's main index file exports all models:
```ts
// src/index.ts
export * from './models';
```
3. Update your documentation to instruct users to import the models directly
from the extension, instead of relying on loopback-boot to pick them up.
```ts
import {MyModel} from 'my-extension';
```
4. Optionally, if you want your models to be injectable, add them to the
artifacts contributed by the extension.
```ts
import {MyModel} from './models';
export class MyComponent implements Component {
models: [MyModel];
}
```
## Advanced scenarios
LoopBack 4 does not yet provide recipes for extensions sharing models together
with their persistence behavior and their REST APIs. Please join the discussion
in [loopback-next#5476](https://github.com/strongloop/loopback-next/issues/5476)
to let us know about your use cases and to subscribe for updates.
|
C++
|
UTF-8
| 3,657
| 2.96875
| 3
|
[] |
no_license
|
//
// main.cpp
// Codeforces
//
// Created by loyinglin.
// Copyright loyinglin. All rights reserved.
/************************** 题解 **********************
[题目链接](https://codeforces.com/contest/1828/problem/B)
**题目大意:**
有1到n的n个整数数组a,现在这n个整数是unsort的状态,也就是至少存在一个整数a[i] ≠ i;
可以选择一个整数k,对于数组中任意两个整数a[i]和a[j],只要满足i-j=k,则可以交换a[i]和a[j];
想知道,如果想要把数组调整为有序状态(a[i] = i),整数k最大值可能为多少?
**输入:**
第一行,整数𝑡 表示t个样例 𝑡 (1≤𝑡≤10000)
每个样例2行,第一行整数𝑛 (1≤𝑛≤2⋅1e5)
第二行 n个整数,a1,a2,…,a𝑛 (1≤a𝑖≤𝑛 )
**输出:**
对于每个样例,输出k的最大可能值;
**Examples**
**input**
7
3
3 1 2
4
3 4 1 2
7
4 2 6 7 5 3 1
9
1 6 7 4 9 2 3 8 5
6
1 5 3 4 2 6
10
3 10 5 2 9 6 7 8 1 4
11
1 11 6 4 8 3 7 5 9 10 2
**output**
1
2
3
4
3
2
3
**题目解析:**
首先,题目一定有解,比如说k=1的时候,就可以使用冒泡排序,最终使得数组有序;
当k=2的时候,奇数位置的数字可以互相交换,偶数位置的数字可以相互交换;那么要求所有数字与所属位置的距离,应该都为2,或者2的倍数(多次交换,即可得到2的倍数距离);
当k=3的时候,与k=2类似,位置1、2、3只能和4、5、6等位置交换;
..
这样我们将整数数组与所属位置进行匹配,就可以得到整数数组b,排除掉b[i]=0的部分(已经匹配);
只要存在最大公约数k,对于所有的b[i]都有b[i]%k==0,那么这个k是可行的。
那么怎么找到这个k?
有个简单的做法,我们找到最大的整数,将整数进行因数分解,再分别判断每个因素是否为最大公约数即可。
(仔细分析一下,发现这里不要最大整数,取任意整数均可)
************************* 题解 ***********************/
#include<cstdio>
#include<cmath>
#include<stack>
#include<map>
#include<set>
#include<queue>
#include<deque>
#include<string>
#include<utility>
#include<sstream>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long lld;
class Solution {
static const int N = 201010;
int a[N], b[N];
public:
void solve() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
for (int i = 0; i < n; ++i) cin >> a[i];
for (int i = 0; i < n; ++i) b[i] = abs(a[i] - i - 1);
sort(b, b + n, greater<int>());
vector<int> tmp;
tmp.push_back(1);
tmp.push_back(b[0]);
for (int i = 2; i * i <= b[0]; ++i) {
if (b[0] % i == 0) {
tmp.push_back(i);
tmp.push_back(b[0] / i);
}
}
sort(tmp.begin(), tmp.end(), greater<int>());
int ans = 0;
for (int i = 0; i < tmp.size() && !ans; ++i) {
int ok = 1;
for (int j = 0; j < n && b[j] != 0; ++j) {
if (b[j] % tmp[i] != 0) {
ok = 0;
break;
}
}
if (ok) {
ans = tmp[i];
}
}
cout << ans << endl;
}
}
}
ac;
int main(int argc, const char * argv[]) {
// insert code here...
ac.solve();
return 0;
}
|
JavaScript
|
UTF-8
| 265
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
$(function(){
$("form").on("submit", function(event) {
var args = $(this).find("#args").val()
//- $(this).find("#args").val('')
$.getJSON("/run?args="+args, function(output){
$("#output").text(output)
})
return false
})
})
|
Markdown
|
UTF-8
| 5,679
| 2.796875
| 3
|
[] |
no_license
|
## About
Bootstrap Material Design is a project done by [FezVrasta](http://fezvrasta.github.io/). It is a theme compatible for [bootstrap 3](http://getbootstrap.com/) and it's really a nice theme that everyone can work with [Laravel 5](https://laravel.com/). You can read more about in this [here](http://fezvrasta.github.io/bootstrap-material-design/#getting-started).
## Getting started
### Download the zip
Grab the latest stable [zip archive](https://github.com/FezVrasta/material-design-icons-svg/archive/master.zip) of this project. Then skip all steps and proceed to Post Install.
### Composer
```sh
$ composer create-project laravel/laravel laravel-bootstrap-md "5.2.*" --prefer-dist
```
### Laravel (if you have laravel installed)
```sh
$ laravel new laravel-bootstrap-md
```
### Bower
`cd` into the public folder in your project's root directory
```sh
$ bower install bootstrap-material-design
```
Add the necessary links to your `<head>` element for fonts and stylsheets:
```html
<!-- Bootstrap Material -->
<link rel="stylesheet" type="text/css" href="{{ URL::asset('bower_components/bootstrap/dist/css/bootstrap.css') }}">
<link rel="stylesheet" type="text/css" href="{{ URL::asset('bower_components/bootstrap-material-design/dist/css/material-icons.css') }}">
<link rel="stylesheet" type="text/css" href="{{ URL::asset('bower_components/bootstrap-material-design/dist/css/bootstrap-material-design.min.css') }}">
<link rel="stylesheet" type="text/css" href="{{ URL::asset('bower_components/bootstrap-material-design/dist/css/ripples.min.css') }}">
<!-- End of Bootstrap Material -->
```
And before your `</body>` element for scripts:
```html
<!-- Bootstrap Material -->
<script type="text/javascript" src="{{ URL::asset('bower_components/jquery/dist/jquery.min.js') }}"></script>
<script type="text/javascript" src="{{ URL::asset('bower_components/bootstrap/dist/js/bootstrap.min.js') }}"></script>
<script type="text/javascript" src="{{ URL::asset('bower_components/bootstrap-material-design/dist/js/material.min.js') }}"></script>
<script type="text/javascript" src="{{ URL::asset('bower_components/bootstrap-material-design/dist/js/ripples.min.js') }}"></script>
<script type="text/javascript" src="{{ URL::asset('bower_components/bootstrap-material-design/dist/js/snackbar.min.js') }}"></script>
<!-- IMPORTANT -->
<script>
$.material.init();
</script>
<!-- End of Bootstrap Material -->
```
**Note**: Material Design Theme don't include material icons when you bower install it. But it's already have been setup in this project and you can run it locally. But if your project is tend for online use you can follow this [github](https://github.com/FezVrasta/material-design-icons-svg).
## Post install
`cd` into project root directory and run:
```sh
$ composer install
```
After all dependencies were already installed, don't forget to generate your key:
```sh
$ php artisan key:generate
```
**All Done!**
## Toastr [optional]
I also find it awesome if I include [Toastr](https://packagist.org/packages/oriceon/toastr-5-laravel) in this project.
### Bower
`cd` into public folder of your project and run:
```sh
$ bower install toastr
```
see [toastr.js](https://github.com/CodeSeven/toastr)
And add this necessary links after your `<head>` element:
```html
<!-- Toastr -->
<link rel="stylesheet" type="text/css" href="{{ URL::asset('bower_components/toastr/toastr.min.css') }}">
<script type="text/javascript" src="{{ URL::asset('bower_components/jquery/dist/jquery.min.js') }}"></script>
<script type="text/javascript" src="{{ URL::asset('bower_components/toastr/toastr.min.js') }}"></script>
<!-- End of Toastr -->
```
### Installation
1. Either run `composer require oriceon/toastr-5-laravel` or add `"oriceon/toastr-5-laravel": "dev-master"` to the `require` key in `composer.json` and run `composer update`.
2. Add `Kamaln7\Toastr\ToastrServiceProvider::class,` to the providers key in `config/app.php`.
3. Add `'Toastr' => Kamaln7\Toastr\Facades\Toastr::class,` to the `aliases` key in `config/app.php`.
Run:
```sh
$ php artisan vendor:publish
```
### Laravel Authentication [for toastr demo]
`cd` back into your project root directory and run:
```sh
$ php artisan make:auth
```
**Note**: If you run this command it is important for all your neccessary links above to put in `<yourproject>/resources/views/layouts/app.blade.php`.
1. Configure your `.env` file and run `php artisan migrate`. Cloning or downloading this project will not provide with `.env` file, so you must run this command to make your `.env` file:
```sh
$ php -r "copy('.env.example', '.env');"
```
2. Open your project in your favorite editor and go to `<yourproject>/resources/views/auth`, open `login.blade.php` and replace it with [login.blade.php](https://github.com/alexela8882/laravel-bootstrap-md/tree/master/resources/views/auth/login.blade.php)
3. Open `register.blade.php` and replace with [register.blade.php](https://github.com/alexela8882/laravel-bootstrap-md/tree/master/resources/views/auth/register.blade.php)
4. Open `AuthController.php` and put this code in `protected function validator(array $data)`:
```js
$title = "Oops!";
$message = "Please make sure to fill all required fields.";
$options = [
'progressBar' => true,
'positionClass' => 'toast-top-right',
'timeOut' => 6000,
];
Toastr::error($message, $title, $options);
```
Run:
```sh
$ php artisan serve
```
Go to [http://localhost:8000](http://localhost:8000).
Try to register with the invalid authentication and Toastr will appear.
**Congratulations!!!**
|
C#
|
UTF-8
| 1,439
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
using TensorShader;
using TensorShader.Layers;
using static TensorShader.Field;
namespace MNIST {
public static class Model {
public static Field CNN(Field x, int classes) {
Convolution2D conv1 =
new(
inchannels: 1, outchannels: 4,
kwidth: 3, kheight: 3,
use_bias: true,
pad_mode: PaddingMode.Zero, label: "conv1");
Convolution2D conv2 =
new(
inchannels: 4, outchannels: 8,
kwidth: 3, kheight: 3,
use_bias: true,
pad_mode: PaddingMode.Zero, label: "conv2");
Convolution2D conv3 =
new(
inchannels: 8, outchannels: 16,
kwidth: 3, kheight: 3,
use_bias: true,
pad_mode: PaddingMode.Zero, label: "conv3");
Field h1 = Relu(conv1.Forward(x));
Field h2 = MaxPooling2D(h1, stride: 2);
Field h3 = Relu(conv2.Forward(h2));
Field h4 = MaxPooling2D(h3, stride: 2);
Field h5 = Relu(conv3.Forward(h4));
Dense fc =
new(
inchannels: h5.Shape.DataSize, outchannels: classes,
use_bias: true, label: "fc");
Field y = fc.Forward(h5);
return y;
}
}
}
|
Java
|
UTF-8
| 391
| 2.21875
| 2
|
[] |
no_license
|
package br.com.anteros.bean.validation.constraints.validators;
import java.util.function.Function;
import br.com.anteros.bean.validation.constraints.Numeric;
import br.com.anteros.core.utils.StringUtils;
public class NumericValidator extends GenericStringValidator<Numeric> {
@Override
public Function<String, Boolean> condition() {
return StringUtils::isNumeric;
}
}
|
Java
|
UTF-8
| 5,401
| 2.75
| 3
|
[] |
no_license
|
import Exceptions.NegativeParameterException;
import Model.PhysicalRunway;
import Model.Runway;
import junit.framework.TestCase;
import org.junit.Before;
import org.junit.Test;
/**
Used the values from the scenarios to test if the calculations
are done correctly.
Runways used for testing are 09L and 27R.
*/
public class Testing extends TestCase
{
PhysicalRunway runway;
Runway runway1;
Runway runway2;
int testLDA1;
int testLDA2;
int testTORA1;
int testTORA2;
int testTODA1;
int testTODA2;
int testASDA1;
int testASDA2;
String testStatus1;
String testStatus2;
@Before
public void setUp()
{
runway1 = new Runway("09L",3595, 3902, 3902, 3902, 306);
runway2 = new Runway("27R",3884, 3884, 3962, 3884, 0);
runway = new PhysicalRunway(runway1, runway2);
}
@Test
public void testLandingOverObstacle()// throws NegativeParameterException
{
testLDA1 = 2985;
//testStatus1 = "RESTRICTED OPERATIONS";
try {
runway1.landingOverObstacle(-50, 12);
}
catch(NegativeParameterException e)
{
e.printStackTrace();
}
assertEquals("Calculations not correct", testLDA1, runway1.getLDA());
//assertEquals("Status is wrong", testStatus1, runway1.getStatus());
testLDA2 = 2774;
//testStatus2 = "CLOSED";
try {
runway2.landingOverObstacle(50, 20);
}
catch(NegativeParameterException e)
{
e.printStackTrace();
}
assertEquals("Calculations are not correct", testLDA2, runway2.getLDA());
//assertEquals("Status is wrong", testStatus2, runway2.getStatus());
}
@Test
public void testTakeOffAwayObstacle() //throws NegativeParameterException
{
testTORA1 = 3346;
//testStatus1 = "RESTRICTED OPERATIONS";
try {
runway1.takeOffAwayObstacle(-50);
}
catch(NegativeParameterException e)
{
e.printStackTrace();
}
assertEquals("Calculations not correct", testTORA1, runway1.getTORA());
testTODA1 = testTORA1 + runway1.getClearway();
assertEquals("Calculations not correct", testTODA1, runway1.getTODA());
testASDA1 = testTORA1 + runway1.getStopway();
assertEquals("Calculations not correct", testASDA1, runway1.getASDA());
//assertEquals("Status is wrong", testStatus1, runway1.getStatus());
testTORA2 = 3534;
//testStatus2 = "CLOSED";
try {
runway2.takeOffAwayObstacle(50);
}
catch(NegativeParameterException e)
{
e.printStackTrace();
}
assertEquals("Calculations not correct", testTORA2, runway2.getTORA());
testTODA2 = testTORA2 + runway2.getClearway();
assertEquals("Calculations not correct", testTODA2, runway2.getTODA());
testASDA2 = testTORA2 + runway2.getStopway();
assertEquals("Calculations not correct", testASDA2, runway2.getASDA());
//assertEquals("Status is wrong", testStatus2, runway2.getStatus());
}
@Test
public void testLandingTowardsObstacle() //throws NegativeParameterException
{
testLDA1 = 3246;
//testStatus1 = "RESTRICTED OPERATIONS";
try {
runway1.landingTowardsObstacle(3546);
}
catch(NegativeParameterException e)
{
e.printStackTrace();
}
assertEquals("Calculations not correct", testLDA1, runway1.getLDA());
//assertEquals("Status is wrong", testStatus1, runway1.getStatus());
testLDA2 = 3346;
//testStatus2 = "CLOSED";
try {
runway2.landingTowardsObstacle(3646);
}
catch(NegativeParameterException e)
{
e.printStackTrace();
}
assertEquals("Calculations not correct", testLDA2, runway2.getLDA());
//assertEquals("Status is wrong", testStatus2, runway2.getStatus());
}
@Test
public void testTakeOffTowardsObstacle() //throws NegativeParameterException
{
testTORA1 = 2792;
//testStatus1 = "RESTRICTED OPERATIONS";
try {
runway1.takeOffTowardsObstacle(3546, 20);
}
catch(NegativeParameterException e)
{
e.printStackTrace();
}
assertEquals("Calculations not correct", testTORA1, runway1.getTORA());
testTODA1 = testTORA1;
assertEquals("Calculations not correct", testTODA1, runway1.getTODA());
testASDA1 = testTORA1;
assertEquals("Calculations not correct", testASDA1, runway1.getASDA());
//assertEquals("Status is wrong", testStatus1, runway1.getStatus());
testTORA2 = 2986;
//testStatus2 = "CLOSED";
try {
runway2.takeOffTowardsObstacle(3646, 12);
}
catch(NegativeParameterException e)
{
e.printStackTrace();
}
assertEquals("Calculations not correct", testTORA2, runway2.getTORA());
testTODA2 = testTORA2;
assertEquals("Calculations not correct", testTODA2, runway2.getTODA());
testASDA2 = testTORA2;
assertEquals("Calculations not correct", testASDA2, runway2.getASDA());
//assertEquals("Status is wrong", testStatus2, runway2.getStatus());
}
}
|
Markdown
|
UTF-8
| 1,576
| 3.234375
| 3
|
[] |
no_license
|
## Welcome to Command Line Hangman!
### Hello! Thanks for checking this out. Here I have created a command line version of hangman using node.js and a the [inquirer](https://www.npmjs.com/package/inquirer) and [random-word](https://www.npmjs.com/package/random-word) packages from [npm](https://www.npmjs.com).
### This version of hangman has several exciting features!
* selects a random word and allows a specific number of guess attempts for each of the word's letters
* get points for guessing correctly
* lose points for failing
* save favorite words in an array attached to the username
* stores user data (points, name, favorite words array)
### How do I play?
1. go ahead and clone this respository! `git clone git@github.com:xezian/command-line-hangman.git`
2. once you have cloned this git repo run `npm install` from the same directory you cloned
3. then run the game by calling `node main.js` from the command line.
### Technical details
* Makes extensive use of modular composition
* Makes extensive use of constructor functions
* Has a really good time with JSON objects
### Where is this going?
* I have a few ideas for additional functionality which I may implement in the future.
* For me, this is more of an exercise in coding than anything, in an attempt to develop my skills as a developer.
* On that note, I appreciate any feedback or communication about the game itself or (even better) my code, including any ideas about how I can improve either.
## Thanks for swinging by,
## and hang in there.
### Copyright
Jason A. Leo (c) 2018. All Rights Reserved.
|
PHP
|
UTF-8
| 600
| 2.703125
| 3
|
[] |
no_license
|
<?php
namespace App\Models;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
class Visitor extends Model
{
protected $table = 'visitors';
protected $fillable = ['url', 'ip', 'hits', 'meta'];
public function log()
{
$ip = request()->ip();
$url = url()->full();
$visitor = $this->where(['ip' => $ip, 'url' => $url])->first();
if($visitor) {
if($visitor->updated_at < Carbon::now()->subMinutes(60)->toDateTimeString())
{
$visitor->hits += 1;
$visitor->update();
}
} else {
$this->ip = $ip;
$this->url = $url;
$this->save();
}
}
}
|
Markdown
|
UTF-8
| 458
| 2.828125
| 3
|
[] |
no_license
|
#Contents#
* table of contents
{:toc}
## Definition
A _bisimplicial object_ in a [[category]] $C$ is a [[functor]]
$$
F : \Delta^{op} \times \Delta^{op} \to C
$$
where $\Delta$ is the [[simplex category]].
This is the same as a [[simplicial object]] in the [[category]] of [[simplicial object]]s in $C$.
## Examples
* [[bisimplicial set]]
* [[bisimplicial group]]
## Related concepts
* [[simplicial object]]
[[!redirects bisimplicial objects]]
|
C#
|
UTF-8
| 641
| 3.296875
| 3
|
[] |
no_license
|
using System;
namespace BankOfKurtovoKonare
{
public class Deposit : Account
{
public Deposit(Customer customer, decimal balance, decimal interest)
: base(customer, balance, interest)
{
}
public override decimal CalculateInterest(int months)
{
if (0 < this.Balance && this.Balance < 1000)
{
return 0;
}
decimal result = this.Balance * (1 + this.Interest * months);
return result;
}
public void Withdraw(decimal money)
{
this.Balance -= money;
}
}
}
|
Python
|
UTF-8
| 3,851
| 3.296875
| 3
|
[] |
no_license
|
# imports the file that serves the website & for creating objects from class Movie
import movie_zone
import media
toy_story = media.Movie("Toy story",
"Woody (Tom Hanks), a good-hearted cowboy doll who"
" belongs to a young boy named Andy (John Morris),"
" sees his position as Andy's favorite toy jeopardized"
" when his parents buy him a Buzz Lightyear"
" (Tim Allen) action figure.",
"https://upload.wikimedia.org/wikipedia/en/1/13/"
"Toy_Story.jpg",
"https://www.youtube.com/watch?v=vwyZH85NQC4")
print(toy_story.poster_image_url)
avatar = media.Movie("Avatar",
"Humans. Sam Worthington as Jake Sully, a Marine veteran,"
" paralyzed from the waist down that volunteers to go to"
" Pandora as an avatar driver."
" There he falls in love with the Na'vi princess, Neytiri."
" He is the main protagonist of the film.",
"https://upload.wikimedia.org/wikipedia/en/b/b0/Avatar-Teaser-Poster.jpg",
"https://www.youtube.com/watch?v=cRdxXPV9GNQ")
a_beautiful_mind = media.Movie("A Beautiful Mind",
"A Beautiful Mind is a 2001 American"
" biographical drama film based on the life of"
" John Nash, a Nobel Laureate in Economics."
" The film was directed by Ron Howard,"
" from a screenplay written by Akiva Goldsman.",
"https://upload.wikimedia.org/wikipedia/en/b/b8/A_Beautiful_Mind_Poster.jpg",
"https://www.youtube.com/watch?v=aS_d0Ayjw4o")
midnight_in_paris = media.Movie("Midnight in Paris",
"Midnight in Paris is a 2011 American-French "
"romantic comedy film written and directed by",
"https://upload.wikimedia.org/wikipedia/en/9/9f/Midnight_in_Paris_Poster.jpg",
"https://www.youtube.com/watch?v=FAfR8omt-CY")
shawshank_redemption = media.Movie("The Shawshank Redemption",
"Plot. In 1947 Portland, Maine, banker Andy"
" Dufresne is convicted of murdering his wife"
" and her lover, and is sentenced to two"
" consecutive life sentences at the Shawshank"
" State Penitentiary. "
"Andy is befriended by contraband smuggler, "
"Ellis Redding, an inmate serving a life"
" sentence.",
"https://www.movieposter.com/posters/archive/main/42/MPW-21321",
"https://www.youtube.com/watch?v=6hB3S9bIaco")
pulp_fiction = media.Movie("Pulp Fiction",
"Jules Winnfield and Vincent Vega are two hitmen "
"who are out to retrieve a suitcase stolen from "
"their employer, mob boss Marsellus Wallace."
"Wallace has also asked Vincent to take his wife "
"Mia out a few days later when Wallace himself will"
" be out of town.",
"https://upload.wikimedia.org/wikipedia/en/8/82/Pulp_Fiction_cover.jpg",
"https://www.youtube.com/watch?v=wZBfmBvvotE")
movies = [toy_story, avatar, a_beautiful_mind, midnight_in_paris,
shawshank_redemption, pulp_fiction]
movie_zone.open_movies_page(movies)
|
C#
|
UTF-8
| 2,104
| 2.671875
| 3
|
[] |
no_license
|
using System.Windows;
using System.Windows.Controls;
using Presentation.Contexts;
using Presentation.PasswordEdit;
using Presentation.Validation;
namespace UI
{
/// <summary>
/// Interaction logic for PasswordEditDialog.xaml
/// </summary>
public partial class PasswordEditDialog : IPasswordEditView
{
/// <summary>
/// Создаёт новый объект класса PasswordEditDialog.
/// </summary>
public PasswordEditDialog()
{
InitializeComponent();
}
/// <summary>
/// Получает или задаёт контекст представления для изменения пароля.
/// </summary>
public IPasswordEditContext PasswordDataContext
{
get { return (IPasswordEditContext)DataContext; }
set { DataContext = value; }
}
/// <summary>
/// Обработчик стандартного события нажатия на кнопку OK.
/// </summary>
/// <param name="sender">Отправитель события.</param>
/// <param name="e">Аргументы события.</param>
private void OkButton_OnClick(object sender, RoutedEventArgs e)
{
foreach (var child in PasswordsGrid.Children)
{
if (Validation.GetHasError((DependencyObject)child))
{
var errorMessage = Validation.GetErrors((DependencyObject)child)[0].Exception.Message;
if (IsNotError(errorMessage)) continue;
var control = (UIElement)child;
control.Focus();
return;
}
}
DialogResult = true;
}
public bool IsNotError(string errorMassage)
{
return errorMassage == ValidatorMessages.HasNoErrors
|| errorMassage == ValidatorMessages.NormalPassword
|| errorMassage == ValidatorMessages.StrongPassword;
}
}
}
|
Python
|
UTF-8
| 260
| 3.265625
| 3
|
[] |
no_license
|
import tkinter
top = tkinter.Tk()
# button = tkinter.Button(top, text ='Click me', )
# button.pack()
c = tkinter.Canvas(top, bg='yellow', height=500, width=500)
img = tkinter.PhotoImage(file='1.gif')
c.create_image(150, 150, image=img)
c.pack()
top.mainloop()
|
Java
|
UTF-8
| 1,360
| 2.15625
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.dutchconnected.fruithuis;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;
import org.hibernate.tool.hbm2ddl.SchemaExport;
/**
*
* @author P_jaz
*/
public class Main {
private static SessionFactory factory;
public static void main(String[] args) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
factory = new Configuration().
configure().
//addPackage("com.xyz") //add package if used.
addAnnotatedClass(Category.class).
addAnnotatedClass(Order.class).
addAnnotatedClass(Product.class).
addAnnotatedClass(ProductOrder.class).
addAnnotatedClass(ProductUnitUser.class).
addAnnotatedClass(Unit.class).
addAnnotatedClass(User.class).
buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
}
}
|
C++
|
UTF-8
| 1,080
| 2.984375
| 3
|
[] |
no_license
|
//
// unknown_type_handling.hpp
// cpp_xcode
//
// Created by Lin on 4/11/17.
// Copyright © 2017 Runskey. All rights reserved.
//
#ifndef unknown_type_handling_hpp
#define unknown_type_handling_hpp
//#include <stdio.h>
// Note that in C++14 you don't need the decltype, templates can deduce an auto return type
// See http://en.cppreference.com/w/cpp/language/auto
// C++ language has no such thing as typeof. You must be looking at some compiler-specific extension. If you are talking about GCC's typeof, then a similar feature is present in C++11 through the keyword decltype. Again, C++ has no such typeof keyword.
// typeid is a C++ language operator which returns type identification information at run time. It basically returns a type_info object, which is equality-comparable with other type_info objects.
// what's the difference between auto and decltype?
// See https://www.cnblogs.com/QG-whz/p/4952980.html
template <typename X, typename Y>
auto unknown_return_type(X x, Y y) -> decltype(x*y)
{
return x * y;
}
#endif /* unknown_type_handling_hpp */
|
Java
|
UTF-8
| 666
| 2.59375
| 3
|
[] |
no_license
|
package com.cwtcn.kmlib.protocol;
/**
* 3.45获取佩戴对象图像
*
* @author Allen
*/
public class WearerAvatarGetReq extends Packet {
public static final String CMD = "G_WEARER_AVATAR";
private String wearID;
public WearerAvatarGetReq() {
super(CMD);
}
public WearerAvatarGetReq(String wearId) {
super(CMD);
this.wearID = wearId;
}
@Override
protected Packet dup() {
return this;
}
@Override
public String encodeArgs() {
put(CMD);
put(wearID);//用wearID做为时间戳,便于返回时处理数据
put(wearID);
return para2String();
}
}
|
C#
|
UTF-8
| 3,224
| 2.859375
| 3
|
[
"Unlicense"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
namespace Buruku {
public class BulkService : IBulkService {
private String tableName;
private String connectionString;
private SqlConnection connection;
public IBulkService ForTable(String tableName) {
this.tableName = tableName;
return this;
}
public IBulkService UseConnectionString(String connectionString) {
if (connection != null)
throw new InvalidOperationException("Connection is defined. Only one method will be used.");
this.connectionString = connectionString;
return this;
}
public IBulkService UseSqlConnection(SqlConnection connection) {
if (!String.IsNullOrEmpty(connectionString))
throw new InvalidOperationException("ConnectionString is used. Only one method will be used.");
this.connection = connection;
return this;
}
public void Insert<T>(IEnumerable<T> dataList) where T : class {
if (dataList == null)
throw new ArgumentNullException("dataList");
if (!dataList.Any())
throw new ArgumentOutOfRangeException("dataList");
DataTable dt = ConvertToBulkDataTable(dataList);
const SqlBulkCopyOptions Options = SqlBulkCopyOptions.TableLock | SqlBulkCopyOptions.UseInternalTransaction | SqlBulkCopyOptions.CheckConstraints;
var bulk = String.IsNullOrEmpty(connectionString) ?
new SqlBulkCopy(connection, Options, connection.BeginTransaction()) :
new SqlBulkCopy(connectionString, Options);
bulk.DestinationTableName = tableName;
bulk.WriteToServer(dt);
}
private DataTable ConvertToBulkDataTable<T>(IEnumerable<T> dataList) where T : class {
var dt = new DataTable();
Type tType = typeof(T);
PropertyInfo[] props = tType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in props) {
var attr = prop.GetCustomAttributes(typeof(BulkColumnAttribute), false).SingleOrDefault() as BulkColumnAttribute;
dt.Columns.Add(attr == null ? prop.Name : attr.BulkColumnName);
}
foreach (T data in dataList) {
PropertyInfo[] iprops = data.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
DataRow dr = dt.NewRow();
foreach (DataColumn col in dt.Columns) {
String column = col.ColumnName;
PropertyInfo prop = iprops.Single(p => {var attr = p.GetCustomAttributes(typeof(BulkColumnAttribute), false).SingleOrDefault() as BulkColumnAttribute; return (attr == null ? p.Name : attr.BulkColumnName) == column; });
dr[column] = prop.GetValue(data, null);
}
dt.Rows.Add(dr);
}
return dt;
}
}
}
|
Shell
|
UTF-8
| 4,171
| 2.703125
| 3
|
[] |
no_license
|
#!/bin/bash
build_trilinos()
{
export TRILINOS=/opt/deal.II/Trilinos/11.4.3
cd /mnt
if [ -d trilinos-11.4.3-Source ] ; then
rm -rf trilinos-11.4.3-Source
fi
tar xf trilinos-11.4.3-Source.tar.bz2
cd trilinos-11.4.3-Source
mkdir build && cd build
cmake \
-DTPL_ENABLE_MKL=ON \
-DTPL_ENABLE_MPI=ON \
-DTPL_MKL_INCLUDE_DIRS=$MKLROOT/include \
-DTPL_MKL_LIBRARIES=$MKLROOT/lib/intel64/libmkl_rt.so \
-DTPL_BLAS_LIBRARIES=$MKLROOT/lib/intel64/libmkl_rt.so \
-DTPL_LAPACK_LIBRARIES=$MKLROOT/lib/intel64/libmkl_rt.so \
-DMPI_BASE_DIR=$I_MPI_ROOT/intel64/ \
-DTrilinos_ENABLE_Amesos=ON \
-DTrilinos_ENABLE_Epetra=ON \
-DTrilinos_ENABLE_Ifpack=ON \
-DTrilinos_ENABLE_AztecOO=ON \
-DTrilinos_ENABLE_Sacado=ON \
-DTrilinos_ENABLE_Teuchos=ON \
-DTrilinos_ENABLE_MueLu:BOOL=ON \
-DTrilinos_ENABLE_ML=ON \
-DTrilinos_ENABLE_PyTrilinos=OFF \
-DTrilinos_ENABLE_SEACAS=OFF \
-DTrilinos_VERBOSE_CONFIGURE=OFF \
-DBUILD_SHARED_LIBS=ON \
-DCMAKE_VERBOSE_MAKEFILE=OFF \
-DCMAKE_BUILD_TYPE=RELEASE \
-DCMAKE_CXX_FLAGS="-g -O3" \
-DCMAKE_C_FLAGS="-g -O3" \
-DCMAKE_FORTRAN_FLAGS="-g -O5" \
-DCMAKE_INSTALL_PREFIX=$TRILINOS ..
make -j 20 && make install
export INCLUDE=$TRILINOS/include:$INCLUDE
export LIBRARY_PATH=$TRILINOS/lib:$LIBRARY_PATH
export LD_LIBRARY_PATH=$TRILINOS/lib:$LD_LIBRARY_PATH
}
build_petsc()
{
export PETSC=/opt/deal.II/petsc-3.6.4
cd /mnt
if [ -d petsc-3.6.4 ] ; then
rm -rf petsc-3.6.4
fi
tar xf petsc-3.6.4.tar.gz
cd petsc-3.6.4
cp ../hypre.tar.bz2 .
export PETSC_ARCH=linux-x86_64-gnu-intelmpi
export PETSC_DIR=/mnt/petsc-3.6.4
./config/configure.py --download-hypre=./hypre.tar.bz2 --prefix=$PETSC --with-blas-lapack-dir=$MKLROOT/lib/intel64/ --with-mpi-dir=$I_MPI_ROOT/intel64/
make PETSC_DIR=/mnt/petsc-3.6.4/ PETSC_ARCH=linux-x86_64-gnu-intelmpi all
make PETSC_DIR=/mnt/petsc-3.6.4/ PETSC_ARCH=linux-x86_64-gnu-intelmpi install
export INCLUDE=$PETSC/include:$INCLUDE
export LIBRARY_PATH=$PETSC/lib:$LIBRARY_PATH
export LD_LIBRARY_PATH=$PETSC/lib:$LD_LIBRARY_PATH
}
build_p4est()
{
export P4EST=/opt/deal.II/p4est
cd /mnt
if [ -d p4est-1.1 ] ; then
rm -rf p4est-1.1
fi
if [ -d p4est-build ] ; then
rm -rf p4est-build
fi
./p4est-setup.sh p4est-1.1.tar.gz $P4EST
export INCLUDE=$P4EST/FAST/include:$INCLUDE
export LIBRARY_PATH=$P4EST/FAST/lib:$LIBRARY_PATH
export LD_LIBRARY_PATH=$P4EST/FAST/lib:$LD_LIBRARY_PATH
}
build_metis()
{
export METIS=/opt/deal.II/metis
cd /mnt
if [ -d metis-5.1.0 ] ; then
rm -rf metis-5.1.0
fi
tar xf metis-5.1.0.tar.gz
cd metis-5.1.0
make config prefix=$METIS
make -j 20 && make install
export INCLUDE=$METIS/include:$INCLUDE
export LIBRARY_PATH=$METIS/lib:$LIBRARY_PATH
export LD_LIBRARY_PATH=$METIS/lib:$LD_LIBRARY_PATH
}
build_dealii()
{
export DEALII=/opt/deal.II/deal.II
cd /mnt
if [ -d dealii-8.4.1 ] ; then
rm -rf dealii-8.4.1
fi
tar xf dealii-8.4.1.tar.gz && cd dealii-8.4.1
mkdir build && cd build
cmake \
-DDEAL_II_WITH_MPI=ON \
-DDEAL_II_WITH_LAPACK=ON \
-DLAPACK_LIBRARIES=$MKLROOT/lib/intel64/libmkl_rt.so \
-DLAPACK_DIR=$MKLROOT/lib/intel64/ \
-DDEAL_II_WITH_P4EST=ON \
-DP4EST_DIR=$P4EST \
-DDEAL_II_WITH_TRILINOS=ON \
-DTRILINOS_DIR=$TRILINOS \
-DDEAL_II_WITH_PETSC=ON \
-DPETSC_ARCH=$PETSC_ARCH \
-DPETSC_DIR=$PETSC \
-DMETIS_DIR=$METIS \
-DCMAKE_INSTALL_PREFIX=$DEALII ..
make -j 20 && make install
}
build_aspect()
{
export ASPECT=/opt/deal.II/aspect
cd /mnt
if [ -d aspect-1.4.0 ] ; then
rm -rf aspect-1.4.0
fi
tar xf aspect-1.4.0.tar.gz
cd aspect-1.4.0
mkdir build && cd build
cmake \
-DDEAL_II_DIR=$DEALII \
-DCMAKE_INSTALL_PREFIX=$ASPECT ..
make -j 20
cp aspect $ASPECT
}
build_metis
build_trilinos
build_petsc
build_p4est
build_dealii
build_aspect
cd /mnt
if [ -d deal.II ] ; then
rm -rf deal.II
fi
cp -r /opt/deal.II /mnt
|
PHP
|
UTF-8
| 6,911
| 3.140625
| 3
|
[] |
no_license
|
<?php
require_once 'dbCredentials.php';
/**
* Class SkiModel handles all ski related queries to the database.
*/
class SkiModel {
protected $db;
public function __construct()
{
$this->db = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset=utf8',
DB_USER, DB_PWD,
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}
/**
* Gets all skies in the database with the optional model filter
* @param string $model optional filter for skies
* @return array an array of all skies found with the optional model filter
*/
function getAllSkies(string $column = "", string $model = ""): array
{
$res = array();
$query = "SELECT model, type_of_skiing, temperature, grip_system, size, weight_class, description, historical, photo_url, msrpp FROM `skiis`";
if(strlen($model) > 0){ // if optional parameter, then filter on that parameter
$query .= " WHERE " . $column . " = :model";
$stmt = $this->db->prepare($query);
$stmt->bindValue(':model', $model);
} else {
$stmt = $this->db->prepare($query);
}
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
array_push($res, $row);
}
return $res;
}
/**
* Creates a new ski in the database.
* @param array $resource the data/body for the ski to be created.
* @return array a message to returned to the client after the ski is created
*/
function createSki(array $resource): array
{
$res = array();
$this->db->beginTransaction();
$rec = $this->verifyResource($resource, true);
if($rec['error_code'] != RESTConstants::HTTP_OK){
return $rec;
}
$query = "INSERT INTO `skiis` (model, type_of_skiing, temperature, grip_system, size, weight_class, description, historical, photo_url, msrpp) VALUES (:model, :type_of_skiing, :temperature, :grip_system, :size, :weight_class, :description, :historical, :photo_url, :msrpp)";
$stmt = $this->db->prepare($query);
$stmt->bindValue(':model', $resource['model']);
$stmt->bindValue(':type_of_skiing', $resource['type_of_skiing']);
$stmt->bindValue(':temperature', $resource['temperature']);
$stmt->bindValue(':grip_system', $resource['grip_system']);
$stmt->bindValue(':size', $resource['size']);
$stmt->bindValue(':weight_class', $resource['weight_class']);
$stmt->bindValue(':description', $resource['description']);
$stmt->bindValue(':historical', $resource['historical']);
$stmt->bindValue(':photo_url', $resource['photo_url']);
$stmt->bindValue(':msrpp', $resource['msrpp']);
$stmt->execute();
$product_id = intval($this->db->lastInsertId());
$this->db->commit();
$res['message'] = 'New ski has been created with product id: ' . $product_id;
return $res;
}
/**
* verifyResource checks that every function which has body requirements has the correct fields.
* @param array $resource is the data to verify
* @param bool $ignoreId if id should be ignored (is not in use)
* @return array returns an array of error_code, possibly an error message as well
*/
function verifyResource(array $resource, bool $ignoreId = false): array
{
$res = array();
if (!array_key_exists('model', $resource)) {
$res['error_code'] = RESTConstants::HTTP_BAD_REQUEST;
$res['error_message'] = 'key model is missing from body';
return $res;
}
if (!array_key_exists('type_of_skiing', $resource)) {
$res['error_code'] = RESTConstants::HTTP_BAD_REQUEST;
$res['error_message'] = 'key type_of_skiing is missing from body';
return $res;
}
if (!array_key_exists('temperature', $resource)) {
$res['error_code'] = RESTConstants::HTTP_BAD_REQUEST;
$res['error_message'] = 'key temperature is missing from body';
return $res;
}
if (!array_key_exists('grip_system', $resource)) {
$res['error_code'] = RESTConstants::HTTP_BAD_REQUEST;
$res['error_message'] = 'key grip_system is missing from body';
return $res;
}
if (!array_key_exists('size', $resource)) {
$res['error_code'] = RESTConstants::HTTP_BAD_REQUEST;
$res['error_message'] = 'key size is missing from body';
return $res;
}
if (!array_key_exists('weight_class', $resource)) {
$res['error_code'] = RESTConstants::HTTP_BAD_REQUEST;
$res['error_message'] = 'key weight_class is missing from body';
return $res;
}
if (!array_key_exists('description', $resource)) {
$res['error_code'] = RESTConstants::HTTP_BAD_REQUEST;
$res['error_message'] = 'key description is missing from body';
return $res;
}
if (!array_key_exists('historical', $resource)) {
$res['error_code'] = RESTConstants::HTTP_BAD_REQUEST;
$res['error_message'] = 'key historical is missing from body';
return $res;
}
if (!array_key_exists('photo_url', $resource)) {
$res['error_code'] = RESTConstants::HTTP_BAD_REQUEST;
$res['error_message'] = 'key photo_url is missing from body';
return $res;
}
if (!array_key_exists('msrpp', $resource)) {
$res['error_code'] = RESTConstants::HTTP_BAD_REQUEST;
$res['error_message'] = 'key msrpp is missing from body';
return $res;
}
if(intval($resource['size']) % 5 != 2) {
$res['error_code'] = RESTConstants::HTTP_BAD_REQUEST;
$res['error_message'] = 'size needs to be a number with interval 5 from the number 2';
return $res;
}
$weightclass = explode("-", $resource['weight_class']);
if(count($weightclass) != 2){
$res['error_code'] = RESTConstants::HTTP_BAD_REQUEST;
$res['error_message'] = 'weight_class has wrong format. Example of right format: 70-80';
return $res;
}
if (!ctype_digit($weightclass[0]) || !ctype_digit($weightclass[1])) {
$res['error_code'] = RESTConstants::HTTP_BAD_REQUEST;
$res['error_message'] = 'weight_class must be number';
return $res;
}
if ($weightclass[0] % 10 != 0 || $weightclass[1] - $weightclass[0] != 10) {
$res['error_code'] = RESTConstants::HTTP_BAD_REQUEST;
$res['error_message'] = 'weight_class must be in 10 intervals';
return $res;
}
$res['error_code'] = RESTConstants::HTTP_OK;
return $res;
}
}
|
Java
|
UTF-8
| 414
| 2.359375
| 2
|
[] |
no_license
|
package com.fairbit.App;
import com.google.gson.Gson;
/**
* Created by fatih.kose on 18.08.2017.
*/
public class Main {
/**
* Entry point
* @param args
*/
public static void main(String[] args) {
Person person = new Person();
person.setId(500);
person.setName("John Wayne");
Gson gson = new Gson();
System.out.println(gson.toJson(person));
}
}
|
Java
|
UTF-8
| 4,358
| 1.898438
| 2
|
[] |
no_license
|
package com.meuapttestemobile.presentation.Shot;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.meuapttestemobile.R;
import com.meuapttestemobile.data.model.Shot;
import com.meuapttestemobile.presentation.BaseActivity;
import com.meuapttestemobile.presentation.EndlessRecyclerOnScrollListener;
import com.meuapttestemobile.presentation.PresenterModule;
import com.meuapttestemobile.presentation.UiComponent;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
public class ShotActivity extends BaseActivity implements ShotViewContract {
@Inject
ShotPresenterContract presenter;
private SwipeRefreshLayout swipeRefresh;
private List<Shot> shots = new ArrayList<>();
private ShotAdapter adapter;
private final String keySavedInstanceState = "shots";
static {
System.loadLibrary("keys");
}
public native String getNativeKey();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shots);
UiComponent uiComponent = getAppComponent().plus(new PresenterModule(this));
uiComponent.inject(this);
setupUI();
if (savedInstanceState == null) {
getShots(1);
} else {
setupShotList(savedInstanceState.getParcelableArrayList(keySavedInstanceState));
}
}
private void setupUI() {
setupToolbar();
setupSwipeRefresh();
configShotList();
}
private void configShotList() {
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
RecyclerView shotsList = findViewById(R.id.shotsList);
shotsList.addOnScrollListener(
new EndlessRecyclerOnScrollListener(layoutManager) {
@Override
public void onLoadMore(int currentPage) {
getShots(currentPage);
}
});
shotsList.setLayoutManager(layoutManager);
shotsList.addItemDecoration(new DividerItemDecoration(shotsList.getContext(), layoutManager.getOrientation()));
this.adapter = new ShotAdapter(this);
shotsList.setAdapter(adapter);
shotsList.setHasFixedSize(true);
}
private void setupToolbar() {
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle(getString(R.string.title_shot_activity));
setSupportActionBar(toolbar);
}
private void setupSwipeRefresh() {
swipeRefresh = findViewById(R.id.swipeRefresh);
swipeRefresh.setOnRefreshListener(() -> {
adapter.clearItems();
shots.clear();
configShotList();
getShots(1);
});
}
private void getShots(int page) {
RelativeLayout offlineState = findViewById(R.id.offline_state);
if (isOnline(this)) {
presenter.getShots(getNativeKey(), page);
offlineState.setVisibility(View.GONE);
} else {
showLoadingIndicator(false);
offlineState.setVisibility(View.VISIBLE);
}
}
@Override
public void setupShotList(@NotNull List<Shot> shots) {
this.shots.addAll(shots);
adapter.addItem(shots);
}
@Override
public void showError() {
Toast.makeText(this, getString(R.string.error_message_shot), Toast.LENGTH_LONG).show();
}
@Override
public void showLoadingIndicator(boolean isLoading) {
swipeRefresh.setRefreshing(isLoading);
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
if (shots != null && !shots.isEmpty()) {
savedInstanceState.putParcelableArrayList(keySavedInstanceState,
(ArrayList<? extends Parcelable>) shots);
}
}
}
|
Python
|
UTF-8
| 256
| 3.234375
| 3
|
[] |
no_license
|
class Debito:
def debitar(self, valor, tipo):
if (tipo == 'poupanca'):
print('Debitar poupanca')
elif (tipo == 'conta corrente'):
print('Debitar conta corrente')
conta = Debito()
conta.debitar(100, 'poupanca')
|
Python
|
UTF-8
| 1,969
| 2.875
| 3
|
[] |
no_license
|
"""
Stitches all normal tissue into one using only the given immune genes
"""
import csv
import sqlite3
from os import listdir
from os.path import isfile, join
#Variables
Src = "./Data/Transposed Gene Expression"
Destination = "./Data/Normal Immune Genes/NormalTissue_Combined.tsv"
Genes = "./Data/Trajanoski_CellRep_immune_signatures.txt"
Label = "Normal"
ImmuneGenes = {}
#Adds Immune Gene names in ImmuneGene
with open(Genes, 'r') as doc:
doc = csv.reader(doc, delimiter = "\t")
ImmuneGenes['barcode'] = None
for row in doc:
geneName = row[0].strip()
geneNumber = row[len(row)-1].strip()
ImmuneGenes[geneName + "|" + geneNumber] = None
ImmuneGenes.pop("Metagene|EntrezGene.ID")
def coerce(val):
if str(val).lower() in ['na', '!value', '#value!']:
return None
return float(val)
files = [join(Src, f) for f in listdir(Src) if isfile(join(Src, f)) and Label in f]
#Open connection
path = './cancer'
connection = sqlite3.connect(path)
c = connection.cursor()
#Get all distinct barcode's
command = "Select distinct barcode from n_expression"
c.execute(command)
barcodes = c.fetchall()
#Print ImmuneGenes
print(ImmuneGenes)
with open('./Data/Normal Immune Genes/NormalTissue_Combined.tsv', 'a') as new:
new = csv.writer(new, delimiter = '\t')
#Add header
new.writerow(list(ImmuneGenes.keys()))
#Add rest of rows
for barcode in barcodes:
#Get details for barcode
command = 'select * from n_expression where barcode=?'
c.execute(command, barcode)
barcode = barcode[0].strip()
ImmuneGenes['barcode'] = barcode
for row in c.fetchall():
gene_id = row[2]
val = coerce(row[3])
ImmuneGenes[gene_id] = val
new.writerow(list(ImmuneGenes.values()))
#Clean ImmuneGenes
for key in ImmuneGenes.keys():
ImmuneGenes[key] = None
|
Markdown
|
UTF-8
| 313
| 2.828125
| 3
|
[] |
no_license
|
# 2021-Sep-2
https://leetcode.com/problems/happy-number/
## Notes
Javascript Hints: The implementation of the logic is pretty easy, I use % to get digits and calculte the result until it hits 1. The tricky part is to get out of an infinity loop, the idea is to use a set and store the results we have calculated.
|
Python
|
UTF-8
| 1,108
| 2.9375
| 3
|
[
"MIT"
] |
permissive
|
import os
from Code.ItemTable import ItemTable
class WikifierOutputData:
def __init__(self):
self.file_location = None
self.item_table = None
def get_file_location(self) -> str:
"""
This function return the file location
:return:
"""
return self.file_location
def get_item_table(self) -> ItemTable:
"""
This function returns the item table
:return:
"""
return self.item_table
def set_file_location(self, file_location: str) -> None:
"""
This function sets the file location
:param file_location:
:return:
"""
self.file_location = file_location
def set_item_table(self, item_table: ItemTable) -> None:
"""
This function sets the item table
:param item_table:
:return:
"""
self.item_table = item_table
def reset(self) -> None:
"""
This function deletes the wikified output file and resets all the class members
:return:
"""
if self.file_location:
os.remove(self.file_location)
self.file_location = None
def reset_item_table(self) -> None:
"""
This function resets the item table object
:return:
"""
self.item_table = None
|
JavaScript
|
UTF-8
| 1,285
| 2.515625
| 3
|
[] |
no_license
|
import React, { Component } from "react";
import { Form, Button, Row } from "react-bootstrap";
export default class EditItem extends Component {
state = {
name: this.props.item.name,
picture: this.props.item.picture,
text: this.props.item.text,
};
changeHandler = (e) => {
console.log("I am editing the: ", e.target.name);
//allow a re render in item.jsx
this.setState({ [e.target.name]: e.target.value });
};
submitHandler = () => {
this.props.editItem(this.state, this.props.item._id);
};
render() {
let { name, picture, text } = this.state;
return (
<div>
<h1>Edit Profile</h1>
<div>
<Row>
<Form.Control
name="name"
value={name}
onChange={this.changeHandler}
/>
</Row>
<Row>
<Form.Control
name="picture"
value={picture}
onChange={this.changeHandler}
/>
</Row>
<Row>
<Form.Control
name="text"
value={text}
onChange={this.changeHandler}
/>
</Row>
<Button onClick={this.submitHandler}>Submit</Button>
</div>
</div>
);
}
}
|
C++
|
UTF-8
| 1,098
| 2.765625
| 3
|
[] |
no_license
|
#pragma once
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/convex_hull_3.h>
#include <CGAL/Polyhedron_3.h>
#include <vector>
#include <CGAL/draw_polyhedron.h>
typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef K::Point_3 Point_3;
typedef std::vector<Point_3> Points;
typedef CGAL::Polyhedron_3<K> Polyhedron_3;
typedef Polyhedron_3::Vertex_iterator Vertex_iterator;
void convex_hull_3_calc(Points &points, Points &res) {
points.push_back(Point_3(0, 0, 0));
points.push_back(Point_3(0, 0, 1));
points.push_back(Point_3(0, 1, 0));
points.push_back(Point_3(1, 0, 0));
points.push_back(Point_3(0, 1, 1));
points.push_back(Point_3(1, 0, 1));
points.push_back(Point_3(1, 1, 0));
points.push_back(Point_3(1, 1, 1));
points.push_back(Point_3(0.6, 0.5, 0.2));
points.push_back(Point_3(0.4, 0.1, 0.3));
Polyhedron_3 poly;
CGAL::convex_hull_3(points.begin(), points.end(), poly);
for (Vertex_iterator v = poly.vertices_begin(); v != poly.vertices_end(); ++v)
//std::cout << v->point() << std::endl;
res.push_back(v->point());
}
|
Python
|
UTF-8
| 257
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
from test_patterns import test_patterns
test_patterns(
'This is some text -- with punctuation.',
[('[^-. ]+', 'sequences without -, ., or space')],
)
#This pattern finds all of the
# substrings that do not contain the characters -, ., or a space.
|
C++
|
UTF-8
| 11,333
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: lasso_entropy_scoring_function.h
* Author: nilu
*
* Created on June 7, 2017, 5:06 AM
*/
#include "lasso_entropy_scoring_function.h"
#include <mlpack/methods/lars/lars.hpp>
#include <mlpack/core.hpp>
#include <cmath>
#include <iostream>
using namespace std;
using namespace mlpack;
namespace scoring
{
double LassoEntropyScoringFunction::calculate_entropy(const arma::vec & x, const double original_dev, int choice)
{
const double pi = M_PI;
const double k1 = 36.0/(8*sqrt(3) - 9.0);
const double k2a = 1.0/(2.0-6.0/pi);
const double k2b = 24/(16.0*sqrt(3)-27.0);
const double Hnu = 0.5*(1.0+log(2.0*pi));
const double root2overpi = sqrt(2.0/pi);
const double rootonehalf = sqrt(0.5);
const int num = x.n_rows;
double sumX=0.0;
double sumX2=0.0;
for(int i=0; i<num; i++)
{
sumX += x(i);
sumX2 += x(i)*x(i);
}
double dev = sqrt(sumX2/(num-1));
if(dev < 1e-16 * original_dev and dev < 1e-16) // deviation very small, then no error basically, return a big negative number
{
const double entropy = -1e16*log(1e16);
cout << "Extremely small error deviation, set entropy = " << entropy
<< ", dev = " << dev << ", original dev = " << original_dev
<< endl;
return -entropy;
}
const double inv_dev = 1.0/dev;
// Alternatively, use inv_dev1
//const double dev = sqrt((trans(x)*x)(0,0)/double(num-1));
//const double inv_dev1 = 1.0/dev;
cout << "k1 = " << k1
<< ", k2a = " << k2a
<< ", k2b = " << k2b
<< ", dev = " << dev
<< endl;
cout << "Calculating entropy for " << x.n_rows
<< " elements, sample mean = " << sumX/num
<< ", sample dev = " << sqrt(sumX2/(num-1))
// << " (alt " << dev << " )"
<< endl;
// for(int i=0; i<num; i++)
// cout << " " << x(i);
cout << endl;
if(0 == choice)
{
double Xexp = 0.0D;
double Xabs = 0.0D;
for(int i=0; i < num; i++)
{
const double sx = x(i)*inv_dev;
Xexp += sx*exp(-0.5*sx*sx);
Xabs += abs(sx);
}
Xexp /= num;
Xabs /= num;
const double XabsMinus = Xabs - root2overpi;
cout << "choice 0, Xexp = " << Xexp << ", Xabs = " << Xabs
<< ", XabsMinus^2 = " << XabsMinus*XabsMinus << endl;
return Hnu-(k1*Xexp*Xexp + k2a*XabsMinus*XabsMinus) - log(inv_dev);
}
else
{
double Xexp = 0.0D;
double Xexp2= 0.0D;
for(int i=0; i < num; i++)
{
const double sx = x(i)*inv_dev;
const double tmp = exp(-0.5*sx*sx);
Xexp += sx*tmp;
Xexp2+= tmp;
}
Xexp /= num;
Xexp2/= num;
const double XexpMinus = Xexp2 - rootonehalf;
cout << "choice 1, Xexp = " << Xexp << ", Xexp2 = " << Xexp2
<< ", XexpMinus^2 = " << XexpMinus*XexpMinus << endl;
return Hnu-(k1*Xexp*Xexp + k2b*XexpMinus*XexpMinus) - log(inv_dev);
}
}//end method calculate_entropy
//constructor
LassoEntropyScoringFunction::LassoEntropyScoringFunction(
datastructures::BayesianNetwork& network
, int which_score_
, std::string data_file_name_
, double lambda_
, scoring::Constraints *constraints
, bool enableDeCamposPruning
)
: which_score(which_score_)
, variableCount(network.size())
, num_rows(0) // will get correct value at the end of constructor
, lambda(lambda_)
{
this->network = network;
this->constraints = constraints;
this->enableDeCamposPruning = enableDeCamposPruning;
data_file_name = data_file_name_;
// read data
//arma::mat raw_data0;
raw_data.load(data_file_name);
//raw_data=trans(raw_data0);
cout << "Dimension of raw_data, rows " << raw_data.n_rows
<< ", cols " << raw_data.n_cols
<< endl;
norm_data = raw_data;
const_cast<int&>(variableCount) = raw_data.n_cols;
const_cast<int&>(num_rows) = raw_data.n_rows;
raw_data_mean = arma::vec(variableCount);
raw_data_dev = arma::vec(variableCount);
raw_data_entropy = arma::vec(variableCount);
for(int i=0; i < variableCount; i++)
{
arma::vec x = raw_data.col(i);
double mean_x = mean(x);
x -= mean_x;
double dev_x = sqrt(var(x));
double dev_x2= num_rows*dev_x; //sqrt(arma::dot(x,x)*num_rows);
cout << "Raw data for variable #" << i
<< ", mean " << mean_x
<< ", dev " << dev_x
<< ", dev2 "<< dev_x2 << ", dev2/dev = " << dev_x2/dev_x
<< ", sqrtN = " << sqrt(num_rows)
<< ", num_rows " << num_rows
<< ", variableCount " << variableCount
<< endl;
//normalize data
for(int j=0; j<num_rows;j++)
{
raw_data(j,i) = raw_data(j,i) - mean_x ;
norm_data(j,i) = raw_data(j,i) / dev_x2 ; // normalize by dev_x2 = sqrt(num_rows)*dev_x, to avoid adjusting lambda with n_rows
}
raw_data_mean(i) = mean_x;
raw_data_dev(i) = dev_x;
raw_data_entropy(i) = calculate_entropy(x, dev_x); // Calculate the independent entropy, use 0.0 as initial reference
}
// we should normalize raw_data here, named normalized_data =
//normalize(raw_data);,
}
float LassoEntropyScoringFunction::calculateScore(int variable, varset parents, FloatMap &cache)
{
// check if this violates the constraints
if (constraints != NULL && !constraints->satisfiesConstraints(variable, parents)) {
invalidParents.insert(parents);
return variableCount;// trying to return a big number here, but not too big to cause overflow
}
arma::uvec parent_vec(variableCount);
//arma::mat X(num_rows,1);
//X.fill(1.0);
int num_parents = 0;
for(int i=0; i<variableCount; i++)
{
if(i != variable and VARSET_GET(parents, i))
{
parent_vec(num_parents++) = i;
//X.insert_cols(num_parents++, raw_data.col(i));
//cout<<X[i]<<endl;
}
}
arma::vec Y=raw_data.col(variable);
const double dev_y = raw_data_dev(variable);
if(0 == num_parents )
{
// Return 0.0 as there is no entropy reduction
double entropy1 = 0.0; //raw_data_entropy(variable); //calculate_entropy(Y, raw_data_entropy(variable), raw_data_dev(variable)); //first approach
// We calculate entropy2 just for comparison purpose
double entropy2 = 0.0; //raw_data_entropy(variable); //calculate_entropy(Y, raw_data_entropy(variable), raw_data_dev(variable), 1); //second approach
double lasso_score = 0;
for(int i=0; i<Y.n_rows;i++)
lasso_score += Y(i)*Y(i);
cout << "Calculated independent entropy, storing OLS score, variable # " << variable
<< ", parents " << std::hex << parents << std::dec
<< ", dev " << sqrt(var(Y))
<< ", entropy1 = " << entropy1
<< ", entropy2 = " << entropy2
<< ", lasso_score = " << lasso_score
<< ", rows = " << num_rows
<< ", cols = " << variableCount
<< endl;
double the_score = entropy1;
switch(which_score)
{
case 0:
the_score = lasso_score;
break;
case 2:
the_score = entropy2;
break;
case 1:
default:
the_score = entropy1;
}
cache[parents] = -the_score;
return -the_score;
}
arma::mat X=norm_data.cols(parent_vec.head(num_parents));
arma::vec beta;
regression::LARS lasso1(true, lambda);
lasso1.Train(X,Y,beta,false);// use true if X is column-major, and false if X is row-major
cout<<"beta.n_rows = "<< beta.n_rows
<< ", num_parents = " << num_parents
<< ", X.n_rows = " << X.n_rows
<< ", X.n_cols = " << X.n_cols
//<< ", beta = " << beta
<<endl;
// arma::vec beta_full(variableCount);
// for(int i=0; i < num_parents; i++)
// {
// beta_full
// }
arma::vec Yhat= X*beta; //raw_data_mean(variable);
//Yhat.fill(0.0);
arma::vec error = Yhat- Y;
const double error_dev = sqrt(var(error));
double entropy1 = calculate_entropy(error, raw_data_dev(variable)) - raw_data_entropy(variable); //first approach
// We calculate entropy2 just for comparison purpose
double entropy2 = calculate_entropy(error, raw_data_dev(variable), 1) - raw_data_entropy(variable); //second approach
double sum_abs_beta = 0;
double sum_error_sq = 0;
for(int i=0; i<beta.n_rows;i++)
sum_abs_beta += abs(beta(i));
for(int i=0; i<error.n_rows;i++)
sum_error_sq += error(i)*error(i);
//double lasso_score = (trans(error)*error)(0,0) + lambda*sum_abs_beta; //ideally use this one, reduce one loop above
double lasso_score = sum_error_sq + lambda*sum_abs_beta;
cout << "Calculated dependent entropy, storing OLS score, variable # " << variable
<< ", parents " << std::hex << parents << std::dec
<< ", entropy1 = " << entropy1
<< ", entropy2 = " << entropy2
<< ", lambda " << lambda
<< ", lasso_score = " << lasso_score
<< ", rows = " << num_rows
<< ", cols = " << variableCount
//<< ", beta " << beta(0) << ", " << beta(1) << ", " << beta(2) << ", " << beta(3) << ", " << beta(4)
<< endl;
// if very few columns, print beta in full scale, i.e., those non-parent columns will have coefficient 0
if(variableCount < 10)
{
int j=0;
cout << "Beta vector: ";
for(int i=0; i < variableCount; i++)
{
if(i==parent_vec(j))
{
cout << " " << beta(j)/raw_data_dev(j);
j++;
}
else
cout << " 0.0";
}
cout << endl;
}
double the_score = entropy1;
switch(which_score)
{
case 0:
the_score = lasso_score;
break;
case 2:
the_score = entropy2;
break;
case 1:
default:
the_score = entropy1;
}
// check whether some beta's are zero
cout << "Clearing zero beta's bits,";
for(int i=0; i < num_parents; i++)
{
if(abs(beta(i)) < 0.01)
{
const int parent_index = parent_vec(i);
VARSET_CLEAR(parents, parent_index);
cout << " " << parent_index ;
}
}
cout << endl;
FloatMap::const_iterator iter = cache.find(parents);
if( iter == cache.end())
cache[parents] = -the_score;
else
{
cout << "parents " << std::hex << parents << std::dec
<< " already exists with score " << iter->second
<< ", ignored new value " << -the_score
<< endl;
}
return -the_score;
}
}//end namespace scoring
|
Ruby
|
UTF-8
| 1,094
| 2.921875
| 3
|
[] |
no_license
|
class Neuronio
AT=0.5
attr_accessor :sigma, :sinapses, :v, :y, :e, :x_atual, :id
def initialize sinapses = []
@sinapses = sinapses
end
def calcular_v vetor_x
@x_atual = vetor_x
@x_atual
sum = 0
@x_atual.each_with_index do |x, i|
sum += @sinapses[i] * x
end
@v = sum
end
def calcular_y
@y = 1 / (1+ exp(-Neuronio::AT * @v))
end
def calcular_sigma somatorio = @e
@sigma = Neuronio::AT * @y*(1-@y) * somatorio
end
def calcular_erro yd
@e = yd - @y
end
def atualizar_sinapses eta
puts "Atualizar sinapses - neuronio #{@id}"
novow,deltaWx =[],0
@sinapses.each_with_index do |wx,i|
deltaWx = eta * @sigma * @x_atual[i]
wx += deltaWx
novow << wx
end
puts "Delta = " + deltaWx.to_s
@sinapses = novow
puts self
end
def to_s
sinapses_s = @sinapses.empty? ? "" : "SINAPSES = #{@sinapses} "
erro_s = @e.nil? ? "" :"ERRO = #{@e} "
sigma_s = @sigma.nil? ? "" : "SIGMA = #{@sigma} "
"ID #{@id} " + sinapses_s + erro_s + sigma_s
end
end
|
Java
|
UTF-8
| 409
| 3.546875
| 4
|
[] |
no_license
|
//Use various access modifiers
class Check {
private int a=3; //declare variables with various access modifiers
public int b=10;
protected int c=5;
int d=15;
void disp() { //display private instance member
System.out.println(getA());
}
}
public class CheckDemo {
public static void main(String[] args) {
Check check=new Check(); //Create object of class Check
check.disp();
}
}
|
PHP
|
UTF-8
| 899
| 2.78125
| 3
|
[] |
no_license
|
<?php
declare(strict_types=1);
namespace Codewars\Kata\Tests\kyu5;
use Codewars\Kata\kyu5\TrainMergedStringChecker;
use PHPUnit\Framework\TestCase;
class TrainMergedStringCheckerTest extends TestCase
{
public function testSampleTestCase() {
$sut = new TrainMergedStringChecker();
$this->assertEquals(true, $sut->isMerge('codewars', 'code', 'wars'));
$this->assertEquals(true, $sut->isMerge('codewars', 'cdw', 'oears'));
$this->assertEquals(false, $sut->isMerge('codewars', 'cod', 'wars'));
$this->assertEquals(false, $sut->isMerge('codewars', 'code', 'warss'));
$this->assertEquals(true, $sut->isMerge('Bananas from Bahamas', 'Bahas', 'Bananas from am'));
$this->assertEquals(true, $sut->isMerge("double letters", "dbletrs", "oue lte"));
$this->assertEquals(true, $sut->isMerge("aabbbbccccccdd", "abbcccd", "abbcccd"));
}
}
|
Java
|
UTF-8
| 4,271
| 2.046875
| 2
|
[
"MIT",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
package com.faforever.client.filter;
import com.faforever.client.i18n.I18n;
import com.faforever.client.test.PlatformTest;
import org.apache.commons.lang3.Range;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.verify;
@SuppressWarnings("unchecked")
public class RangeSliderFilterControllerTest extends PlatformTest {
@Mock
private I18n i18n;
@InjectMocks
private RangeSliderFilterController<Object> instance;
@BeforeEach
public void setUp() throws Exception {
loadFxml("theme/filter/range_slider_filter.fxml", clazz -> instance, instance);
runOnFxThreadAndWait(() -> {
instance.setText("text");
instance.setMinMaxValue(-1000, 1000);
});
}
@Test
public void testTextFieldsAndRangeSliderAreBound() {
runOnFxThreadAndWait(() -> instance.lowValueTextField.setText("-500"));
assertEquals(-500, instance.rangeSlider.getLowValue());
runOnFxThreadAndWait(() -> instance.highValueTextField.setText("500"));
assertEquals(500, instance.rangeSlider.getHighValue());
runOnFxThreadAndWait(() -> instance.rangeSlider.setLowValue(-750));
assertEquals("-750", instance.lowValueTextField.getText());
runOnFxThreadAndWait(() -> instance.rangeSlider.setHighValue(750));
assertEquals("750", instance.highValueTextField.getText());
runOnFxThreadAndWait(() -> instance.rangeSlider.setLowValue(-1000));
assertEquals("", instance.lowValueTextField.getText());
runOnFxThreadAndWait(() -> instance.rangeSlider.setHighValue(1000));
assertEquals("", instance.highValueTextField.getText());
}
@Test
public void testGetObservableValueWhenNoChange() {
assertEquals(AbstractRangeSliderFilterController.NO_CHANGE, instance.valueProperty().getValue());
}
@Test
public void testChangeLowValueAndGetObservableValue() {
runOnFxThreadAndWait(() -> instance.lowValueTextField.setText("-500"));
assertEquals(Range.between(-500, 1000), instance.valueProperty().getValue());
}
@Test
public void testChangeHighValueAndGetObservableValue() {
runOnFxThreadAndWait(() -> instance.highValueTextField.setText("500"));
assertEquals(Range.between(-1000, 500), instance.valueProperty().getValue());
}
@Test
public void testChangeValuesAndGetObservableValue() {
runOnFxThreadAndWait(() -> {
instance.lowValueTextField.setText("-500");
instance.highValueTextField.setText("500");
});
assertEquals(Range.between(-500, 500), instance.valueProperty().getValue());
}
@Test
public void testResetFilter() {
runOnFxThreadAndWait(() -> {
instance.lowValueTextField.setText("-500");
instance.highValueTextField.setText("500");
instance.resetFilter();
});
assertEquals(AbstractRangeSliderFilterController.NO_CHANGE, instance.valueProperty().getValue());
}
@Test
public void testSetTex() {
verify(i18n).get("filter.range", "text", 0, 0);
}
@Test
public void testHasLowDefaultValue() {
assertTrue(instance.hasDefaultLowValue());
runOnFxThreadAndWait(() -> instance.lowValueTextField.setText("-500"));
assertFalse(instance.hasDefaultLowValue());
}
@Test
public void testHasHighDefaultValue() {
assertTrue(instance.hasDefaultHighValue());
runOnFxThreadAndWait(() -> instance.highValueTextField.setText("500"));
assertFalse(instance.hasDefaultHighValue());
}
@Test
public void testHasDefaultValue() {
assertTrue(instance.hasDefaultValue());
runOnFxThreadAndWait(() -> instance.lowValueTextField.setText("-500"));
assertFalse(instance.hasDefaultValue());
runOnFxThreadAndWait(() -> instance.lowValueTextField.setText("500"));
assertFalse(instance.hasDefaultValue());
runOnFxThreadAndWait(() -> {
instance.lowValueTextField.setText("-1000");
instance.highValueTextField.setText("1000");
});
assertTrue(instance.hasDefaultValue());
}
@Test
public void testGetRoot() {
assertEquals(instance.root, instance.getRoot());
}
}
|
C++
|
GB18030
| 6,132
| 2.6875
| 3
|
[] |
no_license
|
#include "itemwindow.h"
#include "ui_itemwindow.h"
itemWindow::itemWindow(QWidget *parent) :
QDialog(parent),
ui(new Ui::itemWindow)
{
ui->setupUi(this);
if(false == itemDelButtonFlag)
{
ui->pushButton_7->hide(); //ɾť
ui->pushButton_8->hide(); //水ť
ui->lineEdit->clear();
ui->dateEdit->setDateTime(QDateTime::currentDateTime()); //Ϊǰʱ
ui->comboBox->setCurrentIndex(0);
ui->comboBox_2->setCurrentIndex(0);
ui->textEdit->clear();
}
else
{
ui->pushButton_6->hide(); //ť
fillTable();
}
}
itemWindow::~itemWindow()
{
delete ui;
}
void itemWindow::on_pushButton_5_clicked()
{
//
this->close();
}
void itemWindow::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.drawPixmap(0, 0, QPixmap(":/png/bk.png").scaled(this->width(), this->height(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
}
void itemWindow::on_pushButton_6_clicked()
{
//
QString titleStr; //
QString dateStr; //
int sortInt; //
int dittoInt; //ظ
QString remarkStr;//ע
titleStr = ui->lineEdit->text().trimmed();
qDebug() << titleStr << endl;
dateStr = ui->dateEdit->dateTime().toString("yyyy.MM.dd");
qDebug() << dateStr << endl;
sortInt = ui->comboBox->currentIndex();
qDebug() << sortInt << endl;
dittoInt = ui->comboBox_2->currentIndex();
qDebug() << dittoInt << endl;
remarkStr = ui->textEdit->toPlainText();
qDebug() << remarkStr << endl;
QString sql;
QSqlQuery query;
int idNum = 0;
//ݱ,жǷظ
sql = "select noteid from note where title = '" + titleStr + "'";
query.exec(sql);
if (query.next())
{
//ظ
QMessageBox::warning(this,tr("Warning"),tr("Title already exists!"),QMessageBox::Yes);
}
else
{
//ȡС
sql = "select noteid from note";
query.exec(sql);
while(query.next())
{
if(idNum < query.value(0).toInt())
idNum = query.value(0).toInt();
}
idNum++;
sql = "insert into note values ('" + QString::number(idNum, 10)
+ "', '" + titleStr + "', '" + dateStr + "', '"
+ QString::number(sortInt, 10) + "', '" + QString::number(dittoInt, 10) + "', '" + remarkStr + "')";
query.exec(sql);
//뵹ձ
idNum = 0;
int dayResult = 0;
//ȡС
sql = "select dayid from day";
query.exec(sql);
while(query.next())
{
if(idNum < query.value(0).toInt())
idNum = query.value(0).toInt();
}
idNum++;
dayResult = datedef(dateStr, dittoInt);
qDebug() << "ʣ:" << dayResult << endl;
sql = "insert into day values ('" + QString::number(idNum, 10)
+ "', '" + titleStr + "', '" + QString::number(dayResult, 10) + "', '"
+ QString::number(sortInt, 10) + "')";
query.exec(sql);
this->close();
}
}
void itemWindow::on_pushButton_7_clicked()
{
//ݱɾ
QString sql;
QSqlQuery query;
sql = "delete from note where title = '" + ui->lineEdit->text().trimmed() + "'";
query.exec(sql);
sql = "delete from day where title = '" + ui->lineEdit->text().trimmed() + "'";
query.exec(sql);
this->close();
}
void itemWindow::on_pushButton_8_clicked()
{
//
QString titleStr; //
QString dateStr; //
int sortInt; //
int dittoInt; //ظ
QString remarkStr;//ע
titleStr = ui->lineEdit->text().trimmed();
dateStr = ui->dateEdit->dateTime().toString("yyyy.MM.dd");
sortInt = ui->comboBox->currentIndex();
dittoInt = ui->comboBox_2->currentIndex();
remarkStr = ui->textEdit->toPlainText();
QString sql;
QSqlQuery query;
//ɾԭļ¼
sql = "delete from note where noteid = '" + QString::number(noteid, 10) + "'";
query.exec(sql);
sql = "delete from day where dayid = '" + QString::number(dayid, 10) + "'";
query.exec(sql);
//µ
sql = "insert into note values ('" + QString::number(noteid, 10)
+ "', '" + titleStr + "', '" + dateStr + "', '"
+ QString::number(sortInt, 10) + "', '" + QString::number(dittoInt, 10) + "', '" + remarkStr + "')";
query.exec(sql);
int dayResult = 0;
dayResult = datedef(dateStr, dittoInt);
sql = "insert into day values ('" + QString::number(dayid, 10)
+ "', '" + titleStr + "', '" + QString::number(dayResult, 10) + "', '"
+ QString::number(sortInt, 10) + "')";
query.exec(sql);
this->close();
}
void itemWindow::fillTable()
{
//Ϣ
QString sql;
QSqlQuery query;
dayid = 0;
noteid = 0;
//ȡС
qDebug() << viewTitle << endl;
sql = "select dayid from day where title = '" + viewTitle + "'";
query.exec(sql);
while (query.next())
{
dayid = query.value(0).toInt();
}
qDebug() << dayid << endl;
sql = "select noteid from note where title = '" + viewTitle + "'";
query.exec(sql);
while (query.next())
{
noteid = query.value(0).toInt();
}
qDebug() << noteid << endl;
sql = "select * from note where noteid = '" + QString::number(noteid, 10) + "'";
query.exec(sql);
while (query.next())
{
ui->lineEdit->setText(query.value(1).toString());
ui->dateEdit->setDateTime(QDateTime::fromString(query.value(2).toString(), "yyyy.MM.dd"));
ui->comboBox->setCurrentIndex(query.value(3).toInt());
ui->comboBox_2->setCurrentIndex(query.value(4).toInt());
ui->textEdit->setText(query.value(5).toString());
}
}
void itemWindow::closeEvent(QCloseEvent *e)
{
//ڹرϢ
windowsPos = this->QWidget::pos(); //ȡλ
}
|
Python
|
UTF-8
| 1,178
| 3.109375
| 3
|
[] |
no_license
|
interest_rate=float(input("rate of growth for fund:"))
principal=float(input("amount invested in SIP per month:"))
duration=float(input("Duration of SIP in year:"))
fd_interest=float(input("interest rate of Debt:"))
def sipcalculator(principal,interest_rate,duration):
"""
takes interset ,principal and duration in year as input and computes return amout
"""
duration_in_month=int(duration*12)
# print("duration in month",duration_in_month)
amount=0
if duration==0:
return principal
else:
amount = principal*((1+(interest_rate/100))**duration)
# print (amount)
# print (duration_in_month)
duration = float((duration_in_month -1)/12)
# print (duration)
return amount + sipcalculator(principal,interest_rate,duration)
amount_returned = sipcalculator(principal,interest_rate,duration)
amount_returned_by_fd = sipcalculator(principal,fd_interest,duration)
print("amount returned after"+ " " +str(int(amount_returned)))
print ("original invested amount" + " "+str(int(principal*12*duration)))
print("amount returned by FD in same duration" +" "+ str(int(amount_returned_by_fd)))
|
Rust
|
UTF-8
| 7,182
| 2.515625
| 3
|
[] |
no_license
|
peg::parser!(
pub grammar parser() for str {
use fazic::enums::*;
use fazic::nodes::*;
pub rule parse_all() -> Entry
= i:integer() _ a:(all() ++ ":") { entry_node(&Some(i), a) }
/ a:(all() ++ ":") { entry_node(&None, a) }
/ i:integer() _ { entry_node(&Some(i), vec![]) }
rule all() -> Vec<NodeElement>
= _ c:command() _ { c }
// _ e:expression() _ { vec![e] }
rule command() -> Vec<NodeElement>
= v:variable() _ "=" _ e:expression() { nodes("let", vec![v, e]) }
/ ("LET" / "let") _ v:variable() _ "=" _ e:expression() { nodes("let", vec![v, e]) }
/ ("?" / "PRINT" / "print") _ e:expression() { nodes("print", vec![e]) }
/ ("GOTO" / "goto") _ i:integer() { nodes("goto", vec![i]) }
/ ("GOSUB" / "gosub") _ i:integer() { nodes("gosub", vec![i]) }
/ ("FOR" / "for") _ v:variable() _ "=" _ e:expression() _ ("TO" / "to") _ t:expression() _ ("STEP" / "step") _ s:expression() { nodes("for", vec![v, e, t, s]) }
/ ("FOR" / "for") _ v:variable() _ "=" _ e:expression() _ ("TO" / "to") _ t:expression() { nodes("for", vec![v, e, t, number_node("1")]) }
/ ("IF" / "if") _ e:expression() _ ("GOTO" / "goto") _ i:integer() {
vec![node("if", vec![e]), node("goto", vec![i])]
}
/ ("IF" / "if") _ e:expression() _ ("GOSUB" / "gosub") _ i:integer() {
vec![node("if", vec![e]), node("gosub", vec![i])]
}
/ ("IF" / "if") _ e:expression() _ ("THEN" / "then") _ i:integer() {
vec![node("if", vec![e]), node("goto", vec![i])]
}
/ ("IF" / "if") _ e:expression() _ ("THEN" / "then") _ a:all() {
let mut vec = nodes("if", vec![e]);
vec.extend(a);
vec
}
/ ("DOT" / "dot") _ x:expression() _ "," _ y:expression() { nodes("dot", vec![x, y]) }
/ ("LINE" / "line") _ x:expression() _ "," _ y:expression() _ "," _ x2:expression() _ "," _ y2:expression() { nodes("line", vec![x, y, x2, y2]) }
/ ("CIRCLE" / "circle") _ x:expression() _ "," _ y:expression() _ "," _ r:expression() { nodes("circle", vec![x, y, r]) }
/ ("CLEAR" / "clear") _ color:expression() { nodes("clear", vec![color]) }
/ ("SRAND" / "srand") _ x:expression() { nodes("srand", vec![x]) }
/ ("NEXT" / "next" ) _ v:(variable() ++ (_ "," _) ) {
let mut vec = vec![];
for variable in v.into_iter() {
vec.extend(nodes("next", vec![variable]));
};
vec
}
/ ("LOAD" / "load") _ s:string() { nodes("load", vec![s]) }
/ ("SAVE" / "save") _ s:string() { nodes("save", vec![s]) }
/ ("DIR" / "dir") { nodes("dir", vec![]) }
/ ("NEXT" / "next" ) { nodes("next", vec![]) }
/ ("COLOR" / "color") _ e:expression() { nodes("color", vec![e]) }
/ ("FLIP" / "flip") { nodes("flip", vec![]) }
/ ("MODE" / "mode") _ i:integer() { nodes("mode", vec![i]) }
/ ("RETURN" / "return") { nodes("return", vec![]) }
/ ("LIST" / "list") { nodes("list", vec![]) }
/ ("CLR" / "clr") { nodes("clr", vec![]) }
/ ("CONT" / "cont") { nodes("cont", vec![]) }
/ ("STOP" / "stop") { nodes("stop", vec![]) }
/ ("NEW" / "new") { nodes("new", vec![]) }
/ ("RUN" / "run") { nodes("run", vec![]) }
/ ("END" / "end") { nodes("end", vec![]) }
/ ("REM" / "rem") * { nodes("rem", vec![]) }
rule function() -> NodeElement
= ("ABS(" / "abs(") _ e:expression() _ ")" { node("abs", vec![e]) }
/ ("RND(" / "rnd(") _ e:expression() _ ")" { node("rnd", vec![e]) }
/ ("SIN(" / "sin(") _ e:expression() _ ")" { node("sin", vec![e]) }
/ ("COS(" / "cos(") _ e:expression() _ ")" { node("cos", vec![e]) }
/ ("TAN(" / "tan(") _ e:expression() _ ")" { node("tan", vec![e]) }
/ ("ATN(" / "atn(") _ e:expression() _ ")" { node("atn", vec![e]) }
/ ("EXP(" / "exp(") _ e:expression() _ ")" { node("exp", vec![e]) }
/ ("LOG(" / "log(") _ e:expression() _ ")" { node("log", vec![e]) }
/ ("SQR(" / "sqr(") _ e:expression() _ ")" { node("sqr", vec![e]) }
/ ("SGN(" / "sgn(") _ e:expression() _ ")" { node("sgn", vec![e]) }
/ ("LEN(" / "len(") _ e:expression() _ ")" { node("len", vec![e]) }
/ ("CHR(" / "chr(") _ e:expression() _ ")" { node("chr", vec![e]) }
/ ("ASC(" / "asc(") _ e:expression() _ ")" { node("asc", vec![e]) }
/ ("INT(" / "int(") _ e:expression() _ ")" { node("int", vec![e]) }
/ ("VAL(" / "val(") _ e:expression() _ ")" { node("val", vec![e]) }
/ ("STR(" / "str(") _ e:expression() _ ")" { node("str", vec![e]) }
/ ("TIME()" / "time()") { node("time", vec![]) }
rule expression() -> NodeElement=precedence! {
l:(@) ("AND" / "and") r:@ { node("and", vec![l, r]) }
l:(@) ("OR" / "or") r:@ { node("or", vec![l, r]) }
--
l:(@) "=" r:@ { node("eq", vec![l, r]) }
l:(@) "==" r:@ { node("eq", vec![l, r]) }
l:(@) "!=" r:@ { node("neq", vec![l, r]) }
l:(@) "<>" r:@ { node("neq", vec![l, r]) }
l:(@) "<" r:@ { node("lt", vec![l, r]) }
l:(@) ">" r:@ { node("gt", vec![l, r]) }
l:(@) "<=" r:@ { node("lteq", vec![l, r]) }
l:(@) ">=" r:@ { node("gteq", vec![l, r]) }
l:(@) "=<" r:@ { node("lteq", vec![l, r]) }
l:(@) "=>" r:@ { node("gteq", vec![l, r]) }
--
l:(@) "+" r:@ { node("add", vec![l, r]) }
l:(@) "-" r:@ { node("sub", vec![l, r]) }
--
l:(@) "*" r:@ { node("mul", vec![l, r]) }
l:(@) "/" r:@ { node("div", vec![l, r]) }
l:(@) "%" r:@ { node("mod", vec![l, r]) }
--
l:@ "^" r:(@) { node("pow", vec![l, r]) }
--
t:term() { t }
}
rule term() -> NodeElement
= _ f:float() _ { f }
/ _ i:integer() _ { i }
/ _ s:string() _ { s }
/ _ f:function() _ { f }
/ _ "(" _ e:expression() _ ")" _ { e }
/ _ "-" _ t:term() _ { node("neg", vec![t]) }
/ _ ("NOT" / "not") _ e:expression() _ { node("not", vec![e]) }
/ _ v:variable() _ { v }
rule float() -> NodeElement
= f:$(['0'..='9']* "." ['0'..='9']+) { number_node(f) }
rule integer() -> NodeElement
= i:$(['0'..='9']+) { number_node(i) }
rule string() -> NodeElement
= "\"" s:$([^'"']*) "\"" { string_node(s) }
/ "'" s:$([^'\'']*) "'" { string_node(s) }
rule variable() -> NodeElement
= v:$(['a'..='z'|'A'..='Z']+) { variable_node(v) }
rule _ = quiet!{" "*}
}
);
|
JavaScript
|
UTF-8
| 3,257
| 3.4375
| 3
|
[] |
no_license
|
var identity = function(x) {
return x;
};
function add(x,y) {
return x+y;
}
function mul(x,y) {
return x*y;
}
var identityf = function(x) {
return identity(x);
};
console.log(identityf(1));
var addf = function(x) {
return function(y){
return x+y;
};
};
console.log(addf(3)(4));
var applyf = function(x) {
if(x==='add') {
return function(y,z) {
return y+z;
};
}
else if (x==='mul'){
return function(y,z) {
return y*z;
};
}
else {
return null;
}
};
var applyfnew = function(binary) {
return function(x) {
return function(y) {
return binary(x,y);
};
};
};
console.log(applyf('mul')(5,6));
console.log(applyfnew(mul)(50)(6));
var curry = function(func, x) {
return function(y) {
return func(x,y);
};
};
console.log(curry(mul,11)(6));
var incOne = function(x) {
return x +1;
};
console.log(incOne(incOne(1)));
var incTwo = function(x) {
return identity(x+1);
};
console.log(incTwo(incTwo(4)));
var incThree = addf(1);
var incFour = curry(add,1);
var incFive = applyfnew(add)(1);
console.log([incThree(incThree(4)),incFour(incFour(4)),incFive(incFive(4))]);
var methodize = function(func){
return function(y) {
return func(this,y);
};
};
Number.prototype.add = methodize(add);
Number.prototype.mul = methodize(mul);
console.log((3).add(4));
console.log((3).mul(4));
function demethodize(func) {
return function(x,y) {
return func.call(x,y);
};
}
console.log(demethodize(Number.prototype.add)(3,4));
function twice(func) {
return function(x) {
return func(x,x);
};
}
var double = twice(add);
var square = twice(mul);
console.log([double(8),square(9)]);
function composeu(func1,func2) {
return function(x) {
return func2(func1(x));
};
}
console.log(composeu(double,square)(3));
function composeb(func1,func2){
return function(x,y,z) {
return func2(func1(x,y),z);
};
}
console.log(composeb(add,mul)(3,4,5));
function once(func) {
return function(x,y) {
var f = func;
func = null;
return f(x,y);
};
}
var addOnce = once(add);
console.log(addOnce(3,4));
//console.log(addOnce(3,4)); // Calling it again will throw the error
function counterf(x) {
return {
inc : function() {
x = x+1;
return x;
},
dec : function() {
x = x-1;
return x;
}
};
}
var counter = counterf(10);
console.log(counter.inc());
function revocable(func) {
return {
invoke : function(x){
return func(x);
},
revoke: function(){
func = null;
return;
}
}
}
var temp = revocable(double);
console.log(temp.invoke(7));
//console.log(temp.revoke(8));
//console.log(temp.invoke(8));
// your code goes here
function check_word(word) {
return words.hasOwnProperty(word); // better way to chck key than [] operator because of constructor string
}
var words = {
'name':'saurabh',
'team':'core'
};
console.log(check_word('name'));
|
TypeScript
|
UTF-8
| 1,244
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
import { convertArrayToCSV } from '../csv'
describe('utils/csv', () => {
it('converts to a valid CSV', () => {
const obj = [
{ exampleCol: 'test', exampleCol2: 'test2', __typename: 'example' },
{ exampleCol: 'test4', exampleCol2: 'test3', __typename: 'example' },
]
expect(convertArrayToCSV(obj)).toEqual(
'exampleCol,exampleCol2\n"test","test2"\n"test4","test3"',
)
})
it('escapes comma values correctly', () => {
const obj = [
{ exampleCol: 'test', modalities: 'PET,MRI', __typename: 'example' },
{ exampleCol: 'test4', modalities: 'MRI', __typename: 'example' },
]
expect(convertArrayToCSV(obj)).toEqual(
'exampleCol,modalities\n"test","PET,MRI"\n"test4","MRI"',
)
})
it('escapes double quotes', () => {
const obj = [
{
exampleCol: 'test',
modalities: 'PET,MRI',
name: 'A "Dataset"',
__typename: 'example',
},
{
exampleCol: 'test4',
modalities: 'MRI',
name: 'Another Dataset',
__typename: 'example',
},
]
expect(convertArrayToCSV(obj)).toEqual(
'exampleCol,modalities,name\n"test","PET,MRI","A ""Dataset"""\n"test4","MRI","Another Dataset"',
)
})
})
|
PHP
|
UTF-8
| 1,339
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
*
* @OA\Schema(
* @OA\Xml(name="Requisition"),
* @OA\Property(property="id", type="integer", example="05"),
* @OA\Property(property="user_id", type="integer", example="05"),
* @OA\Property(property="department_id", type="integer", example="05"),
* @OA\Property(property="reference_no", type="string", example="ASR05"),
* @OA\Property(property="description", type="string", example="Requisition Desription"),
* @OA\Property(property="type", type="string", enum={"purchase", "request"}, example="Category Name"),
* @OA\Property(property="status", type="string", enum={"pending", "approved", "declined"}, example="label"),
* @OA\Property(property="created_at", type="date", example="2020-10-20"),
* @OA\Property(property="updated_at", type="date", example="2020-12-22"),
* )
* Class Requisition
*
*/
class Requisition extends Model
{
use HasFactory;
protected $guarded = [''];
public function items()
{
return $this->hasMany(Item::class);
}
public function requisitor()
{
return $this->belongsTo(User::class, 'user_id');
}
public function department()
{
return $this->belongsTo(Department::class, 'department_id');
}
}
|
Java
|
UTF-8
| 516
| 2.328125
| 2
|
[] |
no_license
|
package rnsr.rag.grammar.interfaces;
import rnsr.rag.grammar.VariableSet;
import rnsr.rag.grammar.exception.VariableNotBoundException;
import rnsr.rag.grammar.exception.VariableNotFoundException;
/**
* Indicates that this term may contain variables which can be resolved
*/
public interface IResolvable<T>
{
/**
* Returns a deep clone of the object with all variables resolved to their bound terms
*/
public T resolve(VariableSet variables) throws VariableNotBoundException, VariableNotFoundException;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.