repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
qisibajie/gildedrosekata
|
src/main/java/com/refactor/bootcamp/duplicated_code/example_3/Engineer.java
|
package com.refactor.bootcamp.duplicated_code.example_3;
public abstract class Engineer {
protected final double unit;
public Engineer(double unit) {
this.unit = unit;
}
abstract String getType();
}
|
ruiaa/toolpck
|
app/src/main/java/com/ruiaa/toolpck/tool/hardware/vibrate/VibratorActivity.java
|
package com.ruiaa.toolpck.tool.hardware.vibrate;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import com.ruiaa.toolpck.R;
import com.ruiaa.toolpck.base.ToolbarActivity;
import com.ruiaa.toolpck.databinding.ActivityVibratorBinding;
import com.ruiaa.toolpck.util.ResUtil;
import com.ruiaa.toolpck.util.ThemeUtil;
public class VibratorActivity extends ToolbarActivity{
private ActivityVibratorBinding binding;
private VibratorUtil vibratorUtil;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding= DataBindingUtil.setContentView(this,R.layout.activity_vibrator);
vibratorUtil=VibratorUtil.getInstance(this);
fixKeyboardAdjustResizeNoEffect();
initOldData();
setTurnOnOff();
setToolbar();
setLimitless();
setRepeat();
}
@Override
protected void onDestroy() {
vibratorUtil.release();
super.onDestroy();
}
private void setToolbar(){
initToolbar();
setToolbarLeftBack();
setTitle(R.string.vibrate);
}
private void initOldData(){
binding.activityVibratorSwitch.setSelected(vibratorUtil.isTurnOn());
binding.activityVibratorLimitlessSwitch.setChecked(vibratorUtil.isLimitless());
if (vibratorUtil.getContinueTime()!=0){
binding.activityVibratorTimeInput.setText(String.valueOf(vibratorUtil.getContinueTime()));
}
binding.activityVibratorRepeatSwitch.setChecked(vibratorUtil.isRepeat());
if (vibratorUtil.getVibratorTimeInPeriod()!=0){
binding.activityVibratorRepeatStartInput.setText(String.valueOf(vibratorUtil.getVibratorTimeInPeriod()));
}
if (vibratorUtil.getWaitTimeInPeriod()!=0){
binding.activityVibratorRepeatStopInput.setText(String.valueOf(vibratorUtil.getWaitTimeInPeriod()));
}
}
private void setTurnOnOff(){
vibratorUtil.setOnStopListener(()->{
binding.activityVibratorSwitch.setSelected(false);
});
binding.activityVibratorSwitch.setOnClickListener(view -> {
view.setSelected(vibratorUtil.setTurnOn(!view.isSelected()));
});
binding.activityVibratorSwitch.setSvgColor(ResUtil.getColorStateList(ThemeUtil.getNightModeSwitch()?R.color.color_turn_on_off_night:R.color.color_trun_on_off_day));
}
private void setLimitless(){
binding.activityVibratorLimitlessSwitch.setOnCheckedChangeListener((view, checked) -> {
vibratorUtil.setLimitless(checked);
binding.activityVibratorTimeInput.setEnabled(!checked);
});
binding.activityVibratorTimeInput.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
if (editable.toString().isEmpty()) return;
vibratorUtil.setContinueTime(Long.valueOf(editable.toString()));
}
});
}
private void setRepeat(){
binding.activityVibratorRepeatSwitch.setOnCheckedChangeListener((view, checked) -> {
vibratorUtil.setRepeat(checked);
});
binding.activityVibratorRepeatStartInput.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (vibratorUtil.isTurnOn()){
vibratorUtil.setTurnOn(false);
binding.activityVibratorSwitch.setSelected(false);
}
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (vibratorUtil.isTurnOn()){
vibratorUtil.setTurnOn(false);
binding.activityVibratorSwitch.setSelected(false);
}
}
@Override
public void afterTextChanged(Editable editable) {
if (editable.toString().isEmpty()) return;
vibratorUtil.setVibratorTimeInPeriod(Long.valueOf(editable.toString()));
}
});
binding.activityVibratorRepeatStopInput.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (vibratorUtil.isTurnOn()){
vibratorUtil.setTurnOn(false);
binding.activityVibratorSwitch.setSelected(false);
}
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (vibratorUtil.isTurnOn()){
vibratorUtil.setTurnOn(false);
binding.activityVibratorSwitch.setSelected(false);
}
}
@Override
public void afterTextChanged(Editable editable) {
if (editable.toString().isEmpty()) return;
vibratorUtil.setWaitTimeInPeriod(Long.valueOf(editable.toString()));
}
});
}
}
|
enthought/traits-futures
|
traits_futures/tests/test_version.py
|
# (C) Copyright 2018-2021 Enthought, Inc., Austin, TX
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in LICENSE.txt and may be redistributed only under
# the conditions described in the aforementioned license. The license
# is also available online at http://www.enthought.com/licenses/BSD.txt
#
# Thanks for using Enthought open source!
import re
import unittest
import traits_futures.version
# Regex matching a version number of one of the two forms
#
# <nnn>.<nnn>.<nnn>
#
# or
#
# <nnn>.<nnn>.<nnn>.dev<nnn>
#
# We may want to relax the format in the future for alphas, betas and the like.
VERSION_MATCHER = re.compile(r"\A\d+\.\d+.\d+(?:\.dev\d+)?\Z")
class TestVersion(unittest.TestCase):
def test_version_string(self):
version = traits_futures.version.version
self.assertIsInstance(version, str)
match = VERSION_MATCHER.match(version)
self.assertIsNotNone(
match, msg="{!r} appears to be an invalid version".format(version)
)
def test_top_level_package_version(self):
self.assertEqual(
traits_futures.__version__, traits_futures.version.version
)
|
mykola-myhailov/fishpay-android
|
app/src/main/java/com/myhailov/mykola/fishpay/activities/MyGoodsActivity.java
|
package com.myhailov.mykola.fishpay.activities;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.chauthai.swipereveallayout.SwipeRevealLayout;
import com.chauthai.swipereveallayout.ViewBinderHelper;
import com.myhailov.mykola.fishpay.R;
import com.myhailov.mykola.fishpay.activities.goods.CreateGoodsActivity;
import com.myhailov.mykola.fishpay.activities.goods.GoodsFilterActivity;
import com.myhailov.mykola.fishpay.activities.goods.ReviewGoodsActivity;
import com.myhailov.mykola.fishpay.api.ApiClient;
import com.myhailov.mykola.fishpay.api.BaseCallback;
import com.myhailov.mykola.fishpay.api.results.GoodsResults;
import com.myhailov.mykola.fishpay.utils.PrefKeys;
import com.myhailov.mykola.fishpay.utils.TokenStorage;
import com.myhailov.mykola.fishpay.utils.Utils;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import belka.us.androidtoggleswitch.widgets.ToggleSwitch;
import static com.myhailov.mykola.fishpay.utils.Keys.CATEGORY;
import static com.myhailov.mykola.fishpay.utils.Keys.GOODS_ID;
import static com.myhailov.mykola.fishpay.utils.Keys.MAX_PRICE;
import static com.myhailov.mykola.fishpay.utils.Keys.MIN_PRICE;
public class MyGoodsActivity extends DrawerActivity {
private static final int CODE_FILTER = 564;
private ArrayList<GoodsResults> publicGoods = new ArrayList<>(), privateGoods = new ArrayList<>();
private List<GoodsResults> filteredGoods = new ArrayList<>();
private List<String> category;
private String minPrice, maxPrice;
private RecyclerView recyclerView;
private ToggleSwitch toggleSwitch;
private GoodsAdapter goodsAdapter;
private TextView tvInform;
private TextView tvInform2;
private String filterQuery = "";
private long id;
private int tabPosition = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawer_my_goods);
initDrawerToolbar(getString(R.string.my_purchases));
findViewById(R.id.ivPlus).setOnClickListener(this);
id = getMyId();
createDrawer();
initToggleButtons();
initViews();
sendRequestGoods();
initSearchView();
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.ivPlus:
context.startActivity(new Intent(context, CreateGoodsActivity.class));
break;
case R.id.tv_filter:
Intent intent = new Intent(context, GoodsFilterActivity.class);
intent.putExtra(MAX_PRICE, getMaxPrice());
startActivityForResult(intent, CODE_FILTER);
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CODE_FILTER) {
if (data != null) {
category = data.getStringArrayListExtra(CATEGORY);
minPrice = data.getStringExtra(MIN_PRICE);
maxPrice = data.getStringExtra(MAX_PRICE);
if (tabPosition == 0) {
filterGoods(publicGoods);
} else filterGoods(privateGoods);
// Map<String, String> parameters = new HashMap<>();
//
// parameters.put("visibility", "public");
// parameters.put("priceFrom", Utils.UAHtoPenny(minPrice) + "");
// parameters.put("priceTo", Utils.UAHtoPenny(maxPrice) + "");
// publicGoods.clear();
// getGoods(category, parameters);
// parameters.put("visibility", "private");
// getGoods(category, parameters);
}
}
}
private void initViews() {
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
tvInform = findViewById(R.id.tv_clear);
tvInform2 = findViewById(R.id.tv_clear2);
findViewById(R.id.tv_filter).setOnClickListener(this);
}
private void filterGoods(List<GoodsResults> lists) {
filteredGoods.clear();
for (GoodsResults list : lists) {
if (list.getPrice() >= Utils.UAHtoPenny(minPrice) && list.getPrice() <= Utils.UAHtoPenny(maxPrice)) {
if (!category.isEmpty()) {
for (String s : category) {
if (s.equals(list.getCategory())) {
filteredGoods.add(list);
break;
}
}
} else {
filteredGoods.add(list);
}
}
}
recyclerView.setAdapter(new GoodsAdapter((ArrayList) filteredGoods));
}
private void initSearchView() {
SearchView searchView = findViewById(R.id.search);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
filterQuery = query;
filter();
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
filterQuery = newText;
filter();
return true;
}
});
searchView.setQueryHint(getString(R.string.search_by_name));
EditText searchEditText = searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
searchEditText.setHintTextColor(getResources().getColor(R.color.grey_material_500));
searchEditText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
}
public int getMaxPrice() {
int maxPrice = 0;
for (GoodsResults publicGood : publicGoods) {
if (maxPrice < publicGood.getPrice()) {
maxPrice = publicGood.getPrice();
}
}
return maxPrice;
}
private void filter() {
if (filterQuery == null || filterQuery.equals("")) {
if (tabPosition == 0) {
recyclerView.setAdapter(new GoodsAdapter(publicGoods));
} else {
recyclerView.setAdapter(new GoodsAdapter(privateGoods));
}
return;
}
if (tabPosition == 0) {
filterList(publicGoods);
} else {
filterList(privateGoods);
}
}
private void filterList(List<GoodsResults> goods) {
List<GoodsResults> filteredGoods = new ArrayList<>();
String search = filterQuery.toLowerCase();
for (GoodsResults item : goods) {
String title = item.getTitle().toLowerCase();
if (title.contains(search)) {
filteredGoods.add(item);
}
}
recyclerView.setAdapter(new GoodsAdapter((ArrayList) filteredGoods));
}
private void sendRequestGoods() {
publicGoods.clear();
getGoods("public");
getGoods("private");
getUserGoods();
}
private void getGoods(List<String> categories, Map<String, String> parameters) {
ApiClient.getApiInterface()
.getGoods(TokenStorage.getToken(context), categories, parameters)
.enqueue(new BaseCallback<ArrayList<GoodsResults>>(context, true) {
@Override
protected void onResult(int code, ArrayList<GoodsResults> result) {
if (result != null && result.size() != 0) {
publicGoods.addAll(result);
Collections.sort(publicGoods, new Comparator<GoodsResults>() {
@Override
public int compare(GoodsResults o1, GoodsResults o2) {
if (o1.getCreatedAt() == null || o2.getCreatedAt() == null)
return 0;
return o2.getCreatedAt().compareTo(o1.getCreatedAt());
}
});
goodsAdapter = new GoodsAdapter(publicGoods);
recyclerView.setAdapter(goodsAdapter);
}
if (publicGoods.isEmpty()) {
showListEmpty(true);
} else showListEmpty(false);
}
});
}
private void getGoods(String visibility) {
ApiClient.getApiInterface()
.getGoods(TokenStorage.getToken(context), visibility)
.enqueue(new BaseCallback<ArrayList<GoodsResults>>(context, true) {
@Override
protected void onResult(int code, ArrayList<GoodsResults> result) {
if (result != null && result.size() != 0) {
publicGoods.addAll(result);
Collections.sort(publicGoods, new Comparator<GoodsResults>() {
@Override
public int compare(GoodsResults o1, GoodsResults o2) {
if (o1.getCreatedAt() == null || o2.getCreatedAt() == null)
return 0;
return o2.getCreatedAt().compareTo(o1.getCreatedAt());
}
});
goodsAdapter = new GoodsAdapter(publicGoods);
recyclerView.setAdapter(goodsAdapter);
}
if (publicGoods.isEmpty()) {
showListEmpty(true);
} else showListEmpty(false);
}
});
}
private void getUserGoods() {
ApiClient.getApiInterface()
.getUserGoods(TokenStorage.getToken(context))
.enqueue(new BaseCallback<ArrayList<GoodsResults>>(context, true) {
@Override
protected void onResult(int code, ArrayList<GoodsResults> result) {
if (result != null && result.size() != 0) {
privateGoods.addAll(result);
}
}
});
}
private void showListEmpty(boolean flag) {
if (flag) {
tvInform.setVisibility(View.VISIBLE);
tvInform2.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.GONE);
} else {
tvInform.setVisibility(View.GONE);
tvInform2.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
}
}
private void deleteGoods(final long id) {
ApiClient.getApiInterface().deleteGoods(TokenStorage.getToken(context), id + "")
.enqueue(new BaseCallback<Object>(context, true) {
@Override
protected void onResult(int code, Object result) {
GoodsResults deleteGoods = new GoodsResults();
for (GoodsResults publicGood : publicGoods) {
if (publicGood.getId() == id) {
deleteGoods = publicGood;
}
}
publicGoods.remove(deleteGoods);
for (GoodsResults publicGood : privateGoods) {
if (publicGood.getId() == id) {
deleteGoods = publicGood;
}
}
privateGoods.remove(deleteGoods);
goodsAdapter.notifyDataSetChanged();
toast(getString(R.string.deleted));
}
});
}
private long getMyId() {
return Long.valueOf(context.getSharedPreferences(PrefKeys.USER_PREFS, MODE_PRIVATE)
.getString(PrefKeys.ID, ""));
}
private void initToggleButtons() {
toggleSwitch = findViewById(R.id.toggleSwitch);
ArrayList<String> labels = new ArrayList<>();
labels.add(getString(R.string.all));
labels.add(getString(R.string.my));
toggleSwitch.setLabels(labels);
toggleSwitch.setCheckedTogglePosition(0);
toggleSwitch.setOnToggleSwitchChangeListener(new ToggleSwitch.OnToggleSwitchChangeListener() {
@Override
public void onToggleSwitchChangeListener(int position, boolean isChecked) {
if (position == 0) {
if (tabPosition != position) {
tabPosition = 0;
if (publicGoods.size() != 0) {
filter();
showListEmpty(false);
} else {
showListEmpty(true);
}
}
} else {
if (tabPosition != position) {
tabPosition = 1;
if (privateGoods.size() != 0) {
filter();
showListEmpty(false);
} else {
showListEmpty(true);
}
}
}
}
});
}
private class ViewHolder extends RecyclerView.ViewHolder {
private SwipeRevealLayout swipe_layout;
private TextView tvPrice, tvTitle, tvDelete;
private ImageView ivPhoto;
private View container;
public ViewHolder(View itemView) {
super(itemView);
swipe_layout = itemView.findViewById(R.id.swipe_layout);
tvPrice = itemView.findViewById(R.id.tvPrice);
tvTitle = itemView.findViewById(R.id.tvTitle);
ivPhoto = itemView.findViewById(R.id.ivPhoto);
tvDelete = itemView.findViewById(R.id.tv_delete);
container = itemView.findViewById(R.id.container);
}
}
private class GoodsAdapter extends RecyclerView.Adapter<ViewHolder> {
private ArrayList<GoodsResults> goods;
private final ViewBinderHelper viewBinderHelper = new ViewBinderHelper();
private Picasso picasso = new Picasso.Builder(context).build();
public GoodsAdapter(ArrayList<GoodsResults> goods) {
this.goods = goods;
viewBinderHelper.setOpenOnlyOne(true);
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.goods_item, parent, false);
return new ViewHolder(itemView);
}
@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final GoodsResults item = goods.get(position);
holder.tvTitle.setText(item.getTitle());
holder.tvPrice.setText(Utils.pennyToUah(item.getPrice()));
Utils.displayGoods(picasso, holder.ivPhoto, item.getMainPhoto(), item.getId());
viewBinderHelper.bind(holder.swipe_layout, item.getId() + "");
if (item.getUserId() != id) {
holder.swipe_layout.setLockDrag(true);
} else {
holder.swipe_layout.setLockDrag(false);
}
holder.container.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent;
if (item.getUserId() != id) {
intent = new Intent(context, ReviewGoodsActivity.class);
} else {
intent = new Intent(context, CreateGoodsActivity.class);
}
intent.putExtra(GOODS_ID, item.getId());
startActivity(intent);
}
});
holder.tvDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
deleteGoods(item.getId());
}
});
}
@Override
public int getItemCount() {
return goods.size();
}
}
}
|
visdata/UrbanMotionAnalysis
|
mergeSrcDst.py
|
__author__ = 'lenovo'
# merge 7,8,9, 17,18,19
# 23,385044,1475161225,39.90723,116.45485,dst
# 23,1338467,1475163136,39.89888,116.66258,src
# 23,1720138,1475161225,40.0033,116.40127,src
# 23,1849304,1475164192,39.91667,116.11279,src
# 23,1849304,1475164192,39.91667,116.11279,dst
# 23,1910973,1475162934,39.86825,116.36176,src
# 23,1910973,1475162934,39.86658,116.35802,dst
# 23,2486485,1475162648,39.98419,116.3808,dst
# 23,4715751,1475163322,39.84465,116.3479,src
# 23,4715751,1475163322,40.00897,116.34595,dst
# 23,5034586,1475162154,39.83362,116.25628,dst
# 23,5096657,1475161373,39.87622,116.32081,dst
# travelhourid, deviceId, stayrecordTimestamp, latlngofstayrecord, src/dst
import sys;
import string;
import time;
from util.tripFlow.base import getFormatGID
readPath = '/datahouse/tripflow/SRCDST-BJ/bj-byhour-tf/';
writePath = '/datahouse/tripflow/SRCDST-BJ/bj-byhour-res/';
startIndex = 175;
endIndex = 177;
# from_array=[0]*10000000;
#to_array=[0]*10000000;
MAX_INDEX = 0;
def main():
start_time = time.time();
global MAX_INDEX;
from_array = [0] * 10000000;
to_array = [0] * 10000000;
srcStayRecordDict = {}
dstStayRecordDict = {}
for file_index in range(startIndex, endIndex + 1):
filename_r = "traveldata-" + str(file_index);
filename_w = str(file_index % 24) + "-" + str(file_index);
content = file(readPath + filename_r, 'r').read();
records = content.split("\n");
for record_index in range(len(records) - 1):
record = records[record_index];
columns = record.split(",");
gridId = getFormatGID([columns[4], columns[3]])["gid"]
key = str(columns[1])+'-'+str(columns[2])
if gridId > MAX_INDEX:
MAX_INDEX = gridId;
if columns[5] == "src" and not srcStayRecordDict.has_key(key):
srcStayRecordDict[key] = True
from_array[gridId] = from_array[gridId] + 1;
elif columns[5] == "dst" and not dstStayRecordDict.has_key(key):
dstStayRecordDict[key] = True
to_array[gridId] = to_array[gridId] + 1;
#resultFile = file(writePath + filename_w, 'w');
# for i in range(MAX_INDEX + 1):
# resultFile.write(str(i) + "," + str(from_array[i]) + "," + str(to_array[i]) + "\n");
# from_array[i] = 0;
# to_array[i] = 0;
# resultFile.close();
# MAX_INDEX = 0;
filename_w = str(4175) + "-" + str(4175);
resultFile = file(writePath + filename_w, 'w');
for i in range(MAX_INDEX + 1):
resultFile.write(str(i) + "," + str(from_array[i]) + "," + str(to_array[i]) + "\n");
from_array[i] = 0;
to_array[i] = 0;
resultFile.close();
MAX_INDEX = 0;
print "Complete Time:" + str(time.time() - start_time);
if __name__ == '__main__':
main()
|
ccubukcu/GeNIE
|
src/main/java/com/genie/utils/LoggableEntity.java
|
<gh_stars>1-10
package com.genie.utils;
/**
*
* @author ccubukcu
*/
public interface LoggableEntity {
}
|
bcloutier/PSNM
|
PythonPrograms/Programs/PythonCode/BackwardEulerNewtonIteration.py
|
<reponame>bcloutier/PSNM
#!/usr/bin/env python
"""
A program to solve y'=y^2 using the backward Euler
method and Newton iteration
This is not optimized and is very simple
"""
import time
import matplotlib.pyplot as plt
N = 1000 # Number of timesteps
tmax = 0.99 # Maximum value
t0 = 0 # Initial t value
y0 = 1 # Initial value y(t0) = y0
tol = 0.1**10 # Tolerance for fixed point iterations
h = (tmax - t0)/N # Time step
y = [y0] # List for discrete solutions
t = [t0] # List with grid of discrete values of t
T0 = time.clock() #Start timing
for i in xrange(N):
yold = y[i]
ynew = y[i]
err =1
while err > tol:
ynew = yold-(yold-y[i]-h*(yold**2))/(1-2*h*yold)
err = abs(ynew-yold)
yold = ynew
y.append(ynew)
t.append(t[-1]+h)
T = time.clock() - T0 # Stop timing
print "Exact value y(%f) = %f " % (t[N], 1/(1-t[N]))
print "Value given by approx y_n(%f) = %f" % (t[N], y[N])
print "The error = y-y_n = %f " % (abs(1/(1-t[N]) - y[N]))
print "Time taken = %f " % (T)
yexact = [1.0/(1.0-x) for x in t]
plt.figure();
plt.plot(t,y,'r+',t,yexact,'b-.');
plt.xlabel('Time')
plt.ylabel('Solution')
plt.legend(('Backward Euler', 'Exact Solution'))
plt.title('Numerical solution of dy/dt=y^2')
plt.show()
|
huangkaizhan/KZAnimation
|
KZAnimation/KZAnimation/Classes/Lib/AnimationCreater_lib.h
|
<gh_stars>0
//
// AnimationCreater.h
// 动画测试
//
// Created by huangkaizhan on 2017/3/4.
// Copyright © 2017年 huangkaizhan. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "AnimationModel_lib.h"
@interface AnimationCreater_lib : NSObject
/**
根据动画模型创建帧动画对象
@param model 动画模型
@return 帧动画
*/
+ (CAKeyframeAnimation *)createKeyFrameAnimationWithModel:(AnimationModel_lib *)model;
@end
|
atsid/avaje-ebeanorm
|
src/main/java/com/avaje/ebeaninternal/server/util/BeanCollectionFactory.java
|
<reponame>atsid/avaje-ebeanorm
package com.avaje.ebeaninternal.server.util;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import com.avaje.ebean.bean.BeanCollection;
import com.avaje.ebean.common.BeanList;
import com.avaje.ebean.common.BeanMap;
import com.avaje.ebean.common.BeanSet;
import com.avaje.ebeaninternal.api.SpiQuery;
/**
* Creates the BeanCollections.
* <p>
* Creates the BeanSet BeanMap and BeanList objects.
* </p>
*/
public class BeanCollectionFactory {
private static class BeanCollectionFactoryHolder {
private static BeanCollectionFactory me = new BeanCollectionFactory();
}
private static final int defaultListInitialCapacity = 20;
private static final int defaultSetInitialCapacity = 32;
private static final int defaultMapInitialCapacity = 32;
private BeanCollectionFactory() {
}
/**
* Create a BeanCollection for the given parameters.
*/
public static BeanCollection<?> create(BeanCollectionParams params) {
return BeanCollectionFactoryHolder.me.createMany(params);
}
private BeanCollection<?> createMany(BeanCollectionParams params) {
SpiQuery.Type manyType = params.getManyType();
switch (manyType) {
case MAP:
return createMap(params);
case LIST:
return createList(params);
case SET:
return createSet(params);
default:
throw new RuntimeException("Invalid Arg " + manyType);
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private BeanMap createMap(BeanCollectionParams params) {
return new BeanMap(new LinkedHashMap(defaultMapInitialCapacity));
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private BeanSet createSet(BeanCollectionParams params) {
return new BeanSet(new LinkedHashSet(defaultSetInitialCapacity));
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private BeanList createList(BeanCollectionParams params) {
return new BeanList(new ArrayList(defaultListInitialCapacity));
}
}
|
rohit0718/tp
|
src/test/java/seedu/address/logic/commands/DetailCommandTest.java
|
<filename>src/test/java/seedu/address/logic/commands/DetailCommandTest.java
package seedu.address.logic.commands;
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 seedu.address.commons.core.Messages.MESSAGE_MODULE_DETAILS_LISTED;
import static seedu.address.commons.core.Messages.MESSAGE_MODULE_NOT_FOUND;
import static seedu.address.logic.commands.CommandTestUtil.assertCommandSuccess;
import static seedu.address.logic.commands.CommandTestUtil.preparePredicate;
import static seedu.address.model.Model.PREDICATE_SHOW_ALL_MODULES;
import static seedu.address.testutil.TypicalModules.CS2103T;
import static seedu.address.testutil.TypicalModules.MA1521;
import static seedu.address.testutil.TypicalModules.getTypicalModBook;
import static seedu.address.testutil.TypicalModules.getTypicalModules;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
import seedu.address.model.Model;
import seedu.address.model.ModelManager;
import seedu.address.model.UserPrefs;
import seedu.address.model.module.ModuleCode;
import seedu.address.model.module.predicates.HasModuleCodePredicate;
/**
* Contains integration tests (interaction with the Model) for {@code DetailCommand}
*/
public class DetailCommandTest {
private Model model = new ModelManager(getTypicalModBook(), new UserPrefs());
private Model expectedModel = new ModelManager(getTypicalModBook(), new UserPrefs());
@Test
public void equals() {
HasModuleCodePredicate firstPredicate =
new HasModuleCodePredicate(new ModuleCode("CS2103T"));
HasModuleCodePredicate secondPredicate =
new HasModuleCodePredicate(new ModuleCode("CS2101"));
DetailCommand detailFirstCommand = new DetailCommand(firstPredicate);
DetailCommand detailSecondCommand = new DetailCommand(secondPredicate);
// same object -> returns true
assertTrue(detailFirstCommand.equals(detailFirstCommand));
// same values -> returns true
DetailCommand detailFirstCommandCopy = new DetailCommand(firstPredicate);
assertTrue(detailFirstCommand.equals(detailFirstCommandCopy));
// different types -> returns false
assertFalse(detailFirstCommand.equals(1));
// null -> returns false
assertFalse(detailFirstCommand.equals(null));
// different code -> returns false
assertFalse(detailFirstCommand.equals(detailSecondCommand));
}
@Test
public void execute_validKeyword_moduleFound() {
String expectedMessage = String.format(MESSAGE_MODULE_DETAILS_LISTED, CS2103T.getCode());
CommandResult expectedResult = new CommandResult(expectedMessage, false, GuiState.DETAILS);
HasModuleCodePredicate predicate = preparePredicate(CS2103T.getCode().toString());
DetailCommand command = new DetailCommand(predicate);
expectedModel.updateFilteredModuleList(predicate);
assertCommandSuccess(command, model, expectedResult, expectedModel);
assertEquals(Arrays.asList(CS2103T), model.getFilteredModuleList());
}
@Test
public void execute_moduleNotFound_listAllModules() {
String expectedMessage = String.format(MESSAGE_MODULE_NOT_FOUND, MA1521.getCode());
CommandResult expectedResult = new CommandResult(expectedMessage, false, GuiState.SUMMARY);
HasModuleCodePredicate predicate = preparePredicate(MA1521.getCode().toString());
DetailCommand command = new DetailCommand(predicate);
expectedModel.updateFilteredModuleList(PREDICATE_SHOW_ALL_MODULES);
assertCommandSuccess(command, model, expectedResult, expectedModel);
assertEquals(getTypicalModules(), model.getFilteredModuleList());
}
}
|
newsdata/SHWVideoTemplate
|
SHWVideoTemplate/Frameworks/SHWMixMobile.framework/Headers/BPVideoMaskTypeDefine.h
|
<filename>SHWVideoTemplate/Frameworks/SHWMixMobile.framework/Headers/BPVideoMaskTypeDefine.h
//
// BPVideoMaskType.h
// BeiPaiVideoEditor
//
// Created by yehot on 2019/12/4.
// Copyright © 2019 <NAME>. All rights reserved.
//
#ifndef BPVideoMaskType_h
#define BPVideoMaskType_h
/// 此字段持久化在 json 中,枚举值不能改,只能新增!
typedef NS_ENUM(NSInteger, BPVideoMaskType) { // 画幅比例
BPVideoMaskType_Origin = 0, /// 使用视频原始尺寸
BPVideoMaskType3x4 = 1, /// 3:4
BPVideoMaskType1x1 = 2, /// 1:1
BPVideoMaskType16x9 = 3, /// 16:9
};
#endif /* BPVideoMaskType_h */
|
kjgarza/frame_experiment
|
test/functional/posts_controller_test.rb
|
require 'test_helper'
class PostsControllerTest < ActionController::TestCase
fixtures :all
include AuthenticatedTestHelper
test "get index" do
create_test_posts
get :index
assert_response :success
end
test "should handle geting index when post owner are deleted" do
create_test_posts
#delete one post owner
Post.first.user.delete
assert_nil Post.first.user
get :index
assert_response :success
end
test "show post" do
post = Factory(:post)
get :show, :id => post.id, :topic_id => post.topic.id, :forum_id => post.forum.id
assert_redirected_to forum_topic_path(post.forum_id, post.topic_id)
assert_nil flash[:error]
end
test "should handle showing when post owner are deleted" do
post = Factory(:post)
post.user.delete
post.reload
assert_nil post.user
get :show, :id => post.id, :topic_id => post.topic.id, :forum_id => post.forum.id
assert_redirected_to forum_topic_path(post.forum_id, post.topic_id)
assert_nil flash[:error]
end
test "get edit" do
post = Factory(:post)
login_as(post.user)
get :edit, :id => post.id, :topic_id => post.topic.id, :forum_id => post.forum.id
assert_response :success
end
test "should handle geting edit when post owner are deleted" do
post = Factory(:post)
post.user.delete
post.reload
assert_nil post.user
login_as(:quentin)
get :edit, :id => post.id, :topic_id => post.topic.id, :forum_id => post.forum.id
assert_response :success
end
test "should create post" do
login_as(Factory(:user))
topic = Factory(:topic)
assert_difference('Post.count',1) do
post :create, :post => {:body => 'something'}, :topic_id => topic.id, :forum_id => topic.forum.id
end
post = assigns(:post)
assert_redirected_to forum_topic_path(:forum_id => post.forum.id, :id => post.topic.id, :anchor => post.dom_id, :page => '1')
assert_nil flash[:error]
end
test "should update post" do
post = Factory(:post)
assert_not_equal 'something', post.body
login_as(post.user)
put :update, :post => {:body => 'something'}, :id => post.id, :topic_id => post.topic.id, :forum_id => post.forum.id
updated_post = assigns(:post)
assert_redirected_to forum_topic_path(:forum_id => updated_post.forum.id, :id => updated_post.topic.id, :anchor => updated_post.dom_id, :page => '1')
assert_nil flash[:error]
assert_equal 'something', updated_post.body
end
test "should handle updating post when post owner is deleted" do
post = Factory(:post)
post.user.delete
post.reload
assert_nil post.user
assert_not_equal 'something', post.body
login_as(:quentin)
put :update, :post => {:body => 'something'}, :id => post.id, :topic_id => post.topic.id, :forum_id => post.forum.id
updated_post = assigns(:post)
assert_redirected_to forum_topic_path(:forum_id => updated_post.forum.id, :id => updated_post.topic.id, :anchor => updated_post.dom_id, :page => '1')
assert_nil flash[:error]
assert_equal 'something', updated_post.body
end
test 'should destroy' do
post = Factory(:post)
login_as(post.user)
delete :destroy, :id => post.id, :topic_id => post.topic.id, :forum_id => post.forum.id
assert_redirected_to forum_path(post.forum.id)
assert_nil flash[:error]
assert_nil Post.find_by_id(post.id)
end
test 'should handle destroying when post owner is deleted' do
post = Factory(:post)
post.user.delete
post.reload
assert_nil post.user
login_as(:quentin)
delete :destroy, :id => post.id, :topic_id => post.topic.id, :forum_id => post.forum.id
assert_redirected_to forum_path(post.forum.id)
assert_nil flash[:error]
assert_nil Post.find_by_id(post.id)
end
private
def create_test_posts
#create some post
i = 0
while i<5
Factory(:post)
i += 1
end
end
end
|
Rarysoft/u4
|
src/main/java/com/rarysoft/u4/Launcher.java
|
/*
* MIT License
*
* Copyright (c) 2020 Rarysoft Enterprises
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.rarysoft.u4;
import com.rarysoft.u4.game.physics.ViewFinder;
import com.rarysoft.u4.game.u5.U5MapEnhancer;
import com.rarysoft.u4.game.u5.U5SurfaceMapper;
import com.rarysoft.u4.game.u5.U5TileMapper;
import com.rarysoft.u4.i18n.Messages;
import com.rarysoft.u4.game.*;
import com.rarysoft.u4.game.npc.DialogTemplate;
import com.rarysoft.u4.game.npc.Dialogs;
import com.rarysoft.u4.ui.graphics.Charset;
import com.rarysoft.u4.game.Tiles;
import com.rarysoft.u4.game.physics.WayFinder;
import com.rarysoft.u4.game.party.*;
import com.rarysoft.u4.ui.*;
import com.rarysoft.u4.ui.util.FrameHelper;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Random;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Launcher {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
try {
new Launcher().run(args != null && args.length > 0 && args[0].equalsIgnoreCase("u5"));
} catch (IOException e) {
e.printStackTrace();
}
});
}
/**
* Launches the game.
* <p>
* The main details worth knowing about this method are:
* <li>The system look and feel is used.</li>
* <li>A log file is created in <code>${user.home}/.u4/u4.log</code>.</li>
* <li>The icon <code>${project.dir}/images/icon.png</code> is used.</li>
* <li>The main window is displayed centered on the user's screen.</li>
*/
public void run(boolean useU5TileSet) throws IOException {
initializeLogFile();
Messages messages = initializeMessages("i18n/messages");
Tiles tiles = initializeTiles(useU5TileSet ? "/data/u5/tiles.ega" : "/data/shapes.ega", useU5TileSet);
Charset charset = initializeCharset("/data/charset.ega");
BufferedImage icon = initializeIcon("/images/ankh.png");
Maps maps = initializeMaps("/data", useU5TileSet);
MapEnhancer mapEnhancer = useU5TileSet ? new U5MapEnhancer() : new DefaultMapEnhancer();
Dialogs dialogs = initializeConversations("/data", messages);
UiBuilder uiBuilder = new UiBuilder();
JFrame gameWindow = uiBuilder.buildGameWindow(messages.windowTitle());
Game game = initializeGame(messages, gameWindow, dialogs);
Party party = initializeParty("/data/party.sav");
uiBuilder.buildGamePanel(gameWindow, game, tiles, charset);
gameWindow.setIconImage(icon);
FrameHelper.enableExitOnClose(gameWindow);
FrameHelper.center(gameWindow);
FrameHelper.maximize(gameWindow);
FrameHelper.show(gameWindow);
game.start(new GameState(mapEnhancer, maps, party));
}
private void initializeLogFile() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
String logPath = String.format("%s%s.u4", System.getProperty("user.home"), File.separator);
Path path = Paths.get(logPath);
if (! path.toFile().exists()) {
Files.createDirectory(path);
}
Logger.getGlobal().addHandler(new FileHandler(String.format("%s%su4.log", logPath, File.separator)));
}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException | IOException e) {
e.printStackTrace(System.out);
}
}
private Messages initializeMessages(String filename) {
return new Messages(filename);
}
private Tiles initializeTiles(String filename, boolean useU5TileSet) throws IOException {
return Tiles.fromStream(Launcher.class.getResourceAsStream(filename), useU5TileSet ? new U5TileMapper() : new DefaultTileMapper());
}
private Charset initializeCharset(String filename) throws IOException {
return Charset.fromStream(Launcher.class.getResourceAsStream(filename));
}
private Maps initializeMaps(String directory, boolean useU5TileSet) throws IOException {
return Maps.fromFiles(directory, useU5TileSet ? new U5SurfaceMapper() : null);
}
private Dialogs initializeConversations(String directory, Messages messages) throws IOException {
return Dialogs.fromFiles(directory, new DialogTemplate() {
@Override
public String speakingTemplate(String pronoun) {
return messages.speechCitizenSpeaking(pronoun);
}
@Override
public String introTemplate(String lookResponse) {
return messages.speechCitizenIntro(lookResponse);
}
@Override
public String nameTemplate(String nameResponse) {
return messages.speechCitizenName(nameResponse);
}
@Override
public String descriptionTemplate(String lookResponse) {
return messages.speechCitizenDescribe(lookResponse);
}
@Override
public String noJoinTemplate() {
return messages.speechCitizenNoJoin();
}
@Override
public String unknownTemplate() {
return messages.speechCitizenUnknown();
}
@Override
public String byeTemplate() {
return messages.speechCitizenBye();
}
});
}
private BufferedImage initializeIcon(String filename) {
try {
return ImageIO.read(Launcher.class.getResource(filename));
}
catch (IOException e) {
Logger.getGlobal().log(Level.SEVERE, null, e);
return null;
}
}
private Game initializeGame(Messages messages, JFrame gameWindow, Dialogs dialogs) {
Game game = new Game(messages, dialogs, new Random(), new ViewFinder(), new WayFinder());
gameWindow.addKeyListener(new KeyboardListener(game));
return game;
}
private Party initializeParty(String filename) throws IOException {
PartyLoader partyLoader = new PartyLoader(new CharacterLoader());
return partyLoader.load(Launcher.class.getResourceAsStream(filename));
}
}
|
ramitos/TermKit
|
src/public/js/output/widgets/icon.js
|
console.log('REQUIRED: WIDGET.ICON');
var widgets = require('../factory').widgets,
node = require('../node');
/**
* Widget: File icon.
*
* Icon loading is collectively throttled.
*/
var icon = module.exports = function (properties) {
console.log('NEW OUTPUT.FRAME.WIDGET.ICON');
// Initialize node.
node.call(this, properties);
this.updateElement();
this.queue();
};
// Process icon updates.
icon.queue = [];
icon.limit = 4;
icon.process = function () {
if (widgets.icon.queue.length && widgets.icon.limit > 0) {
widgets.icon.limit--;
var icon = widgets.icon.queue.shift();
icon.process();
}
};
icon.prototype = $.extend(new node(), {});
icon.prototype.$markup = function () {
// Return active markup for this widget.
var $outputNode = $('<div class="termkitOutputNode widgetIcon"></div>').data('controller', this);
return $outputNode;
};
icon.prototype.setDefaultIcon = function (callback) {
// Set default icon.
var image = new Image(),
extension = (this.properties.stats.mode & 0x4000) ? '...' : this.properties.name.split('.').pop(),
defaultUrl = 'termkit-icon-default:///' + encodeURIComponent(extension);
image.onload = function () {
callback && callback();
};
image.src = defaultUrl;
if (!this.noDefault) {
this.$element.css({
background: 'url('+ defaultUrl +')',
backgroundSize: '32px 32px',
});
}
};
icon.prototype.setOwnIcon = function (callback) {
var that = this;
// Set file-specific icon.
var image = new Image(),
path = this.properties.path + '/' + this.properties.name,
previewUrl = 'termkit-icon-preview:///' + encodeURIComponent(path);
image.onload = function () {
this.noDefault = true;
that.$element.css({
background: 'url('+ previewUrl +')'
});
callback && callback();
};
image.src = previewUrl;
};
icon.prototype.queue = function () {
// Queue icon updates to avoid choking webkit.
widgets.icon.queue.push(this);
widgets.icon.process();
};
icon.prototype.process = function () {
// Process the icon update.
function yield() {
widgets.icon.limit++;
widgets.icon.process();
}
this.setOwnIcon(yield);
};
icon.prototype.updateElement = function () {
// Update markup to match.
var that = this;
this.setDefaultIcon();
this.$element.data('controller', this);
};
|
alearcy/composer_controller
|
app/src/store/actions/elementsAction.js
|
import * as actions from '../../constants/actionConstants';
export function lockElement(obj) {
return {
type: actions.LOCK_ELEMENT,
payload: obj.id
};
}
export function updateElementSize(ref, id) {
return {
type: actions.UPDATE_ELEMENT_SIZE,
payload: {
ref,
id
}
};
}
export function updateElementPos(pos, id) {
return {
type: actions.UPDATE_ELEMENT_POS,
payload: {
pos,
id
}
};
}
export function loadElements(elements) {
return {
type: actions.LOAD_ELEMENTS,
payload: elements
};
}
export function saveElementForm(values) {
return {
type: actions.SAVE_ELEMENT_FORM,
payload: values
};
}
export function editElement(id) {
return {
type: actions.HANDLE_EDIT_ELEMENT,
payload: id
};
}
export function elementFormRequest(form) {
return {
type: actions.ELEMENT_FORM_REQUEST,
payload: form
};
}
export function createButton(currentTab) {
return {
type: actions.CREATE_BUTTON,
payload: currentTab
};
}
export function createSlider(currentTab) {
return {
type: actions.CREATE_SLIDER,
payload: currentTab
};
}
export function createLabel(currentTab) {
return {
type: actions.CREATE_LABEL,
payload: currentTab
};
}
export function importElementFromFile(elements) {
return {
type: actions.IMPORT_ELEMENTS_FROM_FILE,
payload: elements,
}
}
export function deleteElement(id) {
return {
type: actions.DELETE_ELEMENT,
payload: id,
}
}
export function deleteElementsFromTab(id) {
return {
type: actions.DELETE_ELEMENTS_FROM_TAB,
payload: id,
}
}
|
tiagoadmstz/angular-spring-algaworks
|
algamoney-api/src/main/java/io/github/tiagoadmstz/algamoney/api/properties/config/AlgamoneyApiProperties.java
|
package io.github.tiagoadmstz.algamoney.api.properties.config;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Data
@ConfigurationProperties("algamoney")
public class AlgamoneyApiProperties {
private String allowOrigin = "http://localhost:8000";
private final Security security;
public AlgamoneyApiProperties() {
this.security = new Security();
}
@Getter
@Setter
public static class Security {
private Boolean enableHttps;
}
}
|
MitaliBo/public
|
junk/errors/debug_test.go
|
// Copyright 2017 <NAME>. All rights reserved.
// Copyright 2016 The Upspin Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build debug
package errors_test
import (
"fmt"
"regexp"
"strings"
"testing"
"cirello.io/errors"
)
var errorLines = strings.Split(strings.TrimSpace(`
.*/cirello.io/errors/debug_test.go:\d+: cirello.io/errors_test.func1:
.*/cirello.io/errors/debug_test.go:\d+: ...T.func2:
.*/cirello.io/errors/debug_test.go:\d+: ...func3:
.*/cirello.io/errors/debug_test.go:\d+: ...func4: op:
valid.UserName: bad-username
`), "\n")
var errorLineREs = make([]*regexp.Regexp, len(errorLines))
func init() {
for i, s := range errorLines {
errorLineREs[i] = regexp.MustCompile(fmt.Sprintf("^%s$", s))
}
}
// Test that the error stack includes all the function calls between where it
// was generated and where it was printed. It should not include the name
// of the function in which the Error method is called. It should coalesce
// the call stacks of nested errors into one single stack, and present that
// stack before the other error values.
func TestDebug(t *testing.T) {
got := printErr(t, func1())
lines := strings.Split(got, "\n")
for i, re := range errorLineREs {
if i >= len(lines) {
// Handled by line number check.
break
}
if !re.MatchString(lines[i]) {
t.Errorf("error does not match at line %v, got:\n\t%q\nwant:\n\t%q", i, lines[i], re)
}
}
// Check number of lines after checking the lines themselves,
// as the content check will likely be more illuminating.
if got, want := len(lines), len(errorLines); got != want {
t.Errorf("got %v lines of errors, want %v", got, want)
}
}
func printErr(t *testing.T, err error) string {
return err.Error()
}
func func1() error {
var t T
return t.func2()
}
type T struct{}
func (T) func2() error {
return errors.E("op", func3())
}
func func3() error {
return func4()
}
func func4() error {
return errors.E("valid.UserName", errors.Str("bad-username"))
}
|
jwestmoreland/eZdsp-DBG-sim
|
tmp1/c55x-sim2/foo/c5535_bsl_revc/ezdsp5535_v1/c55xx_csl/ccs_v3.3_examples/memory/example2/csl_saram_retention_example.c
|
<filename>tmp1/c55x-sim2/foo/c5535_bsl_revc/ezdsp5535_v1/c55xx_csl/ccs_v3.3_examples/memory/example2/csl_saram_retention_example.c
/* ============================================================================
* Copyright (c) Texas Instruments Inc 2002, 2003, 2004, 2005, 2008
*
* Use of this software is controlled by the terms and conditions found in the
* license agreement under which this software has been supplied.
* ============================================================================
*/
/** @file csl_saram_retention_example.c
*
* @brief SARAM memory retention mode test example source file
*
*
* \page page9 MEMORY EXAMPLE DOCUMENTATION
*
* \section MEM2 MEMORY EXAMPLE2 - SARAM RETENTION MODE TEST
*
* \subsection MEM2x TEST DESCRIPTION:
* This test verifies the memory retention mode feature of the C5505/C5515
* SARAM. Internal memory of the C5505/C5515 DSP can be placed into a low power
* memory retention while retaining the content stored in the memory. This low
* power mode is activated through the Sleep Mode Memory Control. When the
* memory is placed in this mode, no accesses can occur. When the memory
* retention mode is enabled, inline diodes will be added to reduce the local
* power supply to the on-chip RAM. Memory retention mode can be enabled/disabled
* for the DARAM and SARAM independently.
*
* A data buffer is allocated in the SARAM is initialized with some
* data. CSL memory module is initialized and memory retention mode for
* SARAM is enabled using the CSL API MEM_enableRetentionMode(). Memory
* retention mode will be disabled after few CPU cycles by using the CSL API
* MEM_disableRetentionMode(). Data in the SARAM buffer is verified after
* few CPU cycles of delay. Buffer should contain the data with which it was
* initialized before enabling the memory retention mode. This proves that
* the data stored in the SARAM is retained when it is placed into memory
* retention mode and is accessible after disabling the memory retention mode.
*
* NOTE: DURING MEMORY RETENTION MODE TEST FOR SARAM ALL THE PROGRAM SECTIONS
* SHOULD BE PLACED IN THE DARAM. ACCESSING THE DATA IN THE SARAM BY ANY WAY
* (CCS WATCH WINDOW, MEMORY WINDOW OR PLACING THE MOUSE POINTER ON THE SARAM
* DATA BUFFER TO VIEW THE VALUE) AFTER ENABLING THE MEMORY RETENTION MODE
* WILL CORRUPT ALL THE DATA IN SARAM.
*
* NOTE: THIS TEST HAS BEEN DEVELOPED TO WORK WITH CHIP VERSIONS C5505 AND
* C5515. MAKE SURE THAT PROPER CHIP VERSION MACRO IS DEFINED IN THE FILE
* c55xx_csl\inc\csl_general.h.
*
* \subsection MEM2y TEST PROCEDURE:
* @li Open the CCS and connect the target (C5505/C5515 EVM)
* @li Open the project "CSL_MEMORY_SARAM_RetentionExample_Out.pjt" and build it
* @li Load the program on to the target
* @li Set the PLL frequency to 12.288MHz
* @li Run the program and observe the test result
* @li Repeat the test at PLL frequencies 40, 60, 75 and 100MHz
* @li Repeat the test in Release mode
*
* \subsection MEM2z TEST RESULT:
* @li All the CSL APIs should return success
* @li SARAM buffer data verification after disabling the memory retention
* mode should be successful
*
* ============================================================================
*/
/* ============================================================================
* Revision History
* ================
* 06-May-2008 Created for Testing SARAM memory retention mode on C5505 PG1.4
* ============================================================================
*/
#include <csl_mem.h>
#include <csl_general.h>
#include <stdio.h>
#define CSL_SARAM_BUF_SIZE (100u)
#define CSL_SARAM_TEST_DATA (0x1234u)
#define CSL_SARAM_DELAY (100u)
/* Allocate .global section in SARAM for testing SARAM Retention Mode */
#pragma DATA_SECTION (testData,".global")
Uint16 testData[CSL_SARAM_BUF_SIZE];
#define CSL_SARAM_TEST_PASSED (1u)
#define CSL_SARAM_TEST_FAILED (0)
/**
* \brief Tests SARAM retention mode
*
* \param none
*
* \return Test result
*/
CSL_Status CSL_SARAM_RetentionTest(void);
/**
* \brief main function
*
* \param none
*
* \return none
*/
/////INSTRUMENTATION FOR BATCH TESTING -- Part 1 --
///// Define PaSs_StAtE variable for catching errors as program executes.
///// Define PaSs flag for holding final pass/fail result at program completion.
volatile Int16 PaSs_StAtE = 0x0001; // Init to 1. Reset to 0 at any monitored execution error.
volatile Int16 PaSs = 0x0000; // Init to 0. Updated later with PaSs_StAtE when and if
///// program flow reaches expected exit point(s).
/////
void main(void)
{
CSL_Status status;
printf("SARAM Memory Retention Mode test!\n\n");
status = CSL_SARAM_RetentionTest();
if (CSL_SARAM_TEST_PASSED == status)
{
printf("\nSARAM Memory Retention Mode test Passed!!\n");
}
else
{
printf("\nSARAM Memory Retention Mode test Failed!!\n");
/////INSTRUMENTATION FOR BATCH TESTING -- Part 2 --
///// Reseting PaSs_StAtE to 0 if error detected here.
PaSs_StAtE = 0x0000; // Was intialized to 1 at declaration.
/////
}
/////INSTRUMENTATION FOR BATCH TESTING -- Part 3 --
///// At program exit, copy "PaSs_StAtE" into "PaSs".
PaSs = PaSs_StAtE; //If flow gets here, override PaSs' initial 0 with
///// // pass/fail value determined during program execution.
///// Note: Program should next exit to C$$EXIT and halt, where DSS, under
///// control of a host PC script, will read and record the PaSs' value.
/////
}
/**
* \brief Tests SARAM retention mode
*
* \param none
*
* \return Test result
*/
CSL_Status CSL_SARAM_RetentionTest(void)
{
CSL_Status status;
CSL_Status result;
volatile Uint16 looper;
result = CSL_SARAM_TEST_FAILED;
/* Initialize the memory module */
status = MEM_init();
if (status != CSL_SOK)
{
printf("MEM_init failed");
return (result);
}
/* Initialize SARAM data buffer */
for (looper = 0; looper < CSL_SARAM_BUF_SIZE; looper++)
{
testData[looper] = CSL_SARAM_TEST_DATA;
}
printf("Enabling the Memory Retention Mode\n");
/* Enable memory retention mode for SARAM */
status = MEM_enableRetentionMode (CSL_MEM_SARAM);
if (status != CSL_SOK)
{
printf ("Enabling SARAM Memory Retention Mode Failed!\n");
return (result);
}
printf("Wait for few CPU Cycles....\n");
/* Give a small delay */
for (looper = 0; looper < CSL_SARAM_DELAY; looper++)
{
__asm("\tNOP");
}
printf("Disabling the Memory Retention Mode\n");
/* Disable memory retention mode for SARAM */
status = MEM_disableRetentionMode (CSL_MEM_SARAM);
if (status != CSL_SOK)
{
printf ("Disabling SARAM Memory Retention Mode Failed!\n");
return (result);
}
/* Give a small delay */
for (looper = 0; looper < CSL_SARAM_DELAY; looper++)
{
__asm("\tNOP");
}
/* Verify the data */
for (looper = 0; looper < CSL_SARAM_BUF_SIZE; looper++)
{
if((testData[looper] != CSL_SARAM_TEST_DATA))
{
printf("SARAM data is not Retained!\n");
return (result);
}
}
printf("SARAM Data Buffer verification successful\n");
printf("SARAM data is Retained!\n");
result = CSL_SARAM_TEST_PASSED;
return (result);
}
|
WachterJud/qaul.net_legacy
|
pjproject_android/pjsip/src/test/uri_test.c
|
<reponame>WachterJud/qaul.net_legacy<filename>pjproject_android/pjsip/src/test/uri_test.c<gh_stars>1-10
/* $Id: uri_test.c 3553 2011-05-05 06:14:19Z nanang $ */
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "test.h"
#include <pjsip.h>
#include <pjlib.h>
#define THIS_FILE "uri_test.c"
#define ALPHANUM "abcdefghijklmnopqrstuvwxyz" \
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" \
"0123456789"
#define MARK "-_.!~*'()"
#define USER_CHAR ALPHANUM MARK "&=+$,;?/"
#define PASS_CHAR ALPHANUM MARK "&=+$,"
#define PARAM_CHAR ALPHANUM MARK "[]/:&+$"
#define POOL_SIZE 8000
#if defined(PJ_DEBUG) && PJ_DEBUG!=0
# define LOOP_COUNT 10000
#else
# define LOOP_COUNT 40000
#endif
#define AVERAGE_URL_LEN 80
#define THREAD_COUNT 4
static struct
{
pj_highprec_t parse_len, print_len, cmp_len;
pj_timestamp parse_time, print_time, cmp_time;
} var;
/* URI creator functions. */
static pjsip_uri *create_uri0( pj_pool_t *pool );
static pjsip_uri *create_uri1( pj_pool_t *pool );
static pjsip_uri *create_uri2( pj_pool_t *pool );
static pjsip_uri *create_uri3( pj_pool_t *pool );
static pjsip_uri *create_uri4( pj_pool_t *pool );
static pjsip_uri *create_uri5( pj_pool_t *pool );
static pjsip_uri *create_uri6( pj_pool_t *pool );
static pjsip_uri *create_uri7( pj_pool_t *pool );
static pjsip_uri *create_uri8( pj_pool_t *pool );
static pjsip_uri *create_uri9( pj_pool_t *pool );
static pjsip_uri *create_uri10( pj_pool_t *pool );
static pjsip_uri *create_uri11( pj_pool_t *pool );
static pjsip_uri *create_uri12( pj_pool_t *pool );
static pjsip_uri *create_uri13( pj_pool_t *pool );
static pjsip_uri *create_uri14( pj_pool_t *pool );
static pjsip_uri *create_uri15( pj_pool_t *pool );
static pjsip_uri *create_uri16( pj_pool_t *pool );
static pjsip_uri *create_uri17( pj_pool_t *pool );
static pjsip_uri *create_uri25( pj_pool_t *pool );
static pjsip_uri *create_uri26( pj_pool_t *pool );
static pjsip_uri *create_uri27( pj_pool_t *pool );
static pjsip_uri *create_uri28( pj_pool_t *pool );
static pjsip_uri *create_uri29( pj_pool_t *pool );
static pjsip_uri *create_uri30( pj_pool_t *pool );
static pjsip_uri *create_uri31( pj_pool_t *pool );
static pjsip_uri *create_uri32( pj_pool_t *pool );
static pjsip_uri *create_uri33( pj_pool_t *pool );
static pjsip_uri *create_uri34( pj_pool_t *pool );
static pjsip_uri *create_uri35( pj_pool_t *pool );
static pjsip_uri *create_uri36( pj_pool_t *pool );
static pjsip_uri *create_uri37( pj_pool_t *pool );
static pjsip_uri *create_uri38( pj_pool_t *pool );
static pjsip_uri *create_dummy( pj_pool_t *pool );
#define ERR_NOT_EQUAL -1001
#define ERR_SYNTAX_ERR -1002
struct uri_test
{
pj_status_t status;
char str[PJSIP_MAX_URL_SIZE];
pjsip_uri *(*creator)(pj_pool_t *pool);
const char *printed;
pj_size_t len;
} uri_test_array[] =
{
{
PJ_SUCCESS,
"sip:localhost",
&create_uri0
},
{
PJ_SUCCESS,
"sip:user@localhost",
&create_uri1
},
{
PJ_SUCCESS,
"sip:user:password@localhost:5060",
&create_uri2, },
{
/* Port is specified should not match unspecified port. */
ERR_NOT_EQUAL,
"sip:localhost:5060",
&create_uri3
},
{
/* All recognized parameters. */
PJ_SUCCESS,
"sip:localhost;transport=tcp;user=ip;ttl=255;lr;maddr=127.0.0.1;method=ACK",
&create_uri4
},
{
/* Params mixed with other params and header params. */
PJ_SUCCESS,
"sip:localhost;pickup=hurry;user=phone;message=I%20am%20sorry"
"?Subject=Hello%20There&Server=SIP%20Server",
&create_uri5
},
{
/* SIPS. */
PJ_SUCCESS,
"sips:localhost",
&create_uri6,
},
{
/* Name address */
PJ_SUCCESS,
"<sip:localhost>",
&create_uri7
},
{
/* Name address with display name and SIPS scheme with some redundant
* whitespaced.
*/
PJ_SUCCESS,
" Power Administrator <sips:localhost>",
&create_uri8
},
{
/* Name address. */
PJ_SUCCESS,
" \"User\" <sip:user@localhost:5071>",
&create_uri9
},
{
/* Escaped sequence in display name (display=Strange User\"\\\"). */
PJ_SUCCESS,
" \"Strange User\\\"\\\\\\\"\" <sip:localhost>",
&create_uri10,
},
{
/* Errorneous escaping in display name. */
ERR_SYNTAX_ERR,
" \"Rogue User\\\" <sip:localhost>",
&create_uri11,
},
{
/* Dangling quote in display name, but that should be OK. */
PJ_SUCCESS,
"Strange User\" <sip:localhost>",
&create_uri12,
},
{
/* Special characters in parameter value must be quoted. */
PJ_SUCCESS,
"sip:localhost;pvalue=\"hello world\"",
&create_uri13,
},
{
/* Excercise strange character sets allowed in display, user, password,
* host, and port.
*/
PJ_SUCCESS,
"This is -. !% *_+`'~ me <sip:a19A&=+$,;?/%2c:%40a&Zz=+$,@"
"my_proxy09.MY-domain.com:9801>",
&create_uri14,
},
{
/* Another excercise to the allowed character sets to the hostname. */
PJ_SUCCESS,
"sip:" ALPHANUM "-_.com",
&create_uri15,
},
{
/* Another excercise to the allowed character sets to the username
* and password.
*/
PJ_SUCCESS,
"sip:" USER_CHAR ":" PASS_CHAR "@host",
&create_uri16,
},
{
/* Excercise to the pname and pvalue, and mixup of other-param
* between 'recognized' params.
*/
PJ_SUCCESS,
"sip:host;user=ip;" PARAM_CHAR "%21=" PARAM_CHAR "%21"
";lr;other=1;transport=sctp;other2",
&create_uri17,
},
{
/* 18: This should trigger syntax error. */
ERR_SYNTAX_ERR,
"sip:",
&create_dummy,
},
{
/* 19: Syntax error: whitespace after scheme. */
ERR_SYNTAX_ERR,
"sip :host",
&create_dummy,
},
{
/* 20: Syntax error: whitespace before hostname. */
ERR_SYNTAX_ERR,
"sip: host",
&create_dummy,
},
{
/* 21: Syntax error: invalid port. */
ERR_SYNTAX_ERR,
"sip:user:password",
&create_dummy,
},
{
/* 22: Syntax error: no host. */
ERR_SYNTAX_ERR,
"sip:user@",
&create_dummy,
},
{
/* 23: Syntax error: no user/host. */
ERR_SYNTAX_ERR,
"sip:@",
&create_dummy,
},
{
/* 24: Syntax error: empty string. */
ERR_SYNTAX_ERR,
"",
&create_dummy,
},
{
/* 25: Simple tel: URI with global context */
PJ_SUCCESS,
"tel:+1-201-555-0123",
&create_uri25,
"tel:+1-201-555-0123"
},
{
/* 26: Simple tel: URI with local context */
PJ_SUCCESS,
"tel:7042;phone-context=example.com",
&create_uri26,
"tel:7042;phone-context=example.com"
},
{
/* 27: Simple tel: URI with local context */
PJ_SUCCESS,
"tel:863-1234;phone-context=+1-914-555",
&create_uri27,
"tel:863-1234;phone-context=+1-914-555"
},
{
/* 28: Comparison between local and global number */
ERR_NOT_EQUAL,
"tel:+1",
&create_uri28,
"tel:+1"
},
{
/* 29: tel: with some visual chars and spaces */
PJ_SUCCESS,
"tel:(44).1234-*#+Deaf",
&create_uri29,
"tel:(44).1234-*#+Deaf"
},
{
/* 30: isub parameters */
PJ_SUCCESS,
"tel:+1;isub=/:@&$,-_.!~*'()[]/:&$aA1%21+=",
&create_uri30,
"tel:+1;isub=/:@&$,-_.!~*'()[]/:&$aA1!+%3d"
},
{
/* 31: extension number parsing and encoding */
PJ_SUCCESS,
"tel:+1;ext=+123",
&create_uri31,
"tel:+1;ext=%2b123"
},
{
/* 32: context parameter parsing and encoding */
PJ_SUCCESS,
"tel:911;phone-context=+1-911",
&create_uri32,
"tel:911;phone-context=+1-911"
},
{
/* 33: case-insensitive comparison */
PJ_SUCCESS,
"tel:911;phone-context=emergency.example.com",
&create_uri33,
"tel:911;phone-context=emergency.example.com"
},
{
/* 34: parameter only appears in one URL */
ERR_NOT_EQUAL,
"tel:911;p1=p1;p2=p2",
&create_uri34,
"tel:911;p1=p1;p2=p2"
},
{
/* 35: IPv6 in host and maddr parameter */
PJ_SUCCESS,
"sip:user@[::1];maddr=[::01]",
&create_uri35,
"sip:user@[::1];maddr=[::01]"
},
{
/* 36: IPv6 in host and maddr, without username */
PJ_SUCCESS,
"sip:[::1];maddr=[::01]",
&create_uri36,
"sip:[::1];maddr=[::01]"
},
{
/* 37: Non-ASCII UTF-8 in display name, with quote */
PJ_SUCCESS,
"\"\xC0\x81\" <sip:localhost>",
&create_uri37,
"\"\xC0\x81\" <sip:localhost>"
},
{
/* 38: Non-ASCII UTF-8 in display name, without quote */
PJ_SUCCESS,
"\xC0\x81 <sip:localhost>",
&create_uri38,
"\"\xC0\x81\" <sip:localhost>"
}
};
static pjsip_uri *create_uri0(pj_pool_t *pool)
{
/* "sip:localhost" */
pjsip_sip_uri *url = pjsip_sip_uri_create(pool, 0);
pj_strdup2(pool, &url->host, "localhost");
return (pjsip_uri*)url;
}
static pjsip_uri *create_uri1(pj_pool_t *pool)
{
/* "sip:user@localhost" */
pjsip_sip_uri *url = pjsip_sip_uri_create(pool, 0);
pj_strdup2( pool, &url->user, "user");
pj_strdup2( pool, &url->host, "localhost");
return (pjsip_uri*) url;
}
static pjsip_uri *create_uri2(pj_pool_t *pool)
{
/* "sip:user:password@localhost:5060" */
pjsip_sip_uri *url = pjsip_sip_uri_create(pool, 0);
pj_strdup2( pool, &url->user, "user");
pj_strdup2( pool, &url->passwd, "password");
pj_strdup2( pool, &url->host, "localhost");
url->port = 5060;
return (pjsip_uri*) url;
}
static pjsip_uri *create_uri3(pj_pool_t *pool)
{
/* Like: "sip:localhost:5060", but without the port. */
pjsip_sip_uri *url = pjsip_sip_uri_create(pool, 0);
pj_strdup2(pool, &url->host, "localhost");
return (pjsip_uri*)url;
}
static pjsip_uri *create_uri4(pj_pool_t *pool)
{
/* "sip:localhost;transport=tcp;user=ip;ttl=255;lr;maddr=12172.16.31.10;method=ACK" */
pjsip_sip_uri *url = pjsip_sip_uri_create(pool, 0);
pj_strdup2(pool, &url->host, "localhost");
pj_strdup2(pool, &url->transport_param, "tcp");
pj_strdup2(pool, &url->user_param, "ip");
url->ttl_param = 255;
url->lr_param = 1;
pj_strdup2(pool, &url->maddr_param, "127.0.0.1");
pj_strdup2(pool, &url->method_param, "ACK");
return (pjsip_uri*)url;
}
#define param_add(list,pname,pvalue) \
do { \
pjsip_param *param; \
param=PJ_POOL_ALLOC_T(pool, pjsip_param); \
param->name = pj_str(pname); \
param->value = pj_str(pvalue); \
pj_list_insert_before(&list, param); \
} while (0)
static pjsip_uri *create_uri5(pj_pool_t *pool)
{
/* "sip:localhost;pickup=hurry;user=phone;message=I%20am%20sorry"
"?Subject=Hello%20There&Server=SIP%20Server"
*/
pjsip_sip_uri *url = pjsip_sip_uri_create(pool, 0);
pj_strdup2(pool, &url->host, "localhost");
pj_strdup2(pool, &url->user_param, "phone");
//pj_strdup2(pool, &url->other_param, ";pickup=hurry;message=I%20am%20sorry");
param_add(url->other_param, "pickup", "hurry");
param_add(url->other_param, "message", "I am sorry");
//pj_strdup2(pool, &url->header_param, "?Subject=Hello%20There&Server=SIP%20Server");
param_add(url->header_param, "Subject", "Hello There");
param_add(url->header_param, "Server", "SIP Server");
return (pjsip_uri*)url;
}
static pjsip_uri *create_uri6(pj_pool_t *pool)
{
/* "sips:localhost" */
pjsip_sip_uri *url = pjsip_sip_uri_create(pool, 1);
pj_strdup2(pool, &url->host, "localhost");
return (pjsip_uri*)url;
}
static pjsip_uri *create_uri7(pj_pool_t *pool)
{
/* "<sip:localhost>" */
pjsip_name_addr *name_addr = pjsip_name_addr_create(pool);
pjsip_sip_uri *url;
url = pjsip_sip_uri_create(pool, 0);
name_addr->uri = (pjsip_uri*) url;
pj_strdup2(pool, &url->host, "localhost");
return (pjsip_uri*)name_addr;
}
static pjsip_uri *create_uri8(pj_pool_t *pool)
{
/* " Power Administrator <sips:localhost>" */
pjsip_name_addr *name_addr = pjsip_name_addr_create(pool);
pjsip_sip_uri *url;
url = pjsip_sip_uri_create(pool, 1);
name_addr->uri = (pjsip_uri*) url;
pj_strdup2(pool, &name_addr->display, "Power Administrator");
pj_strdup2(pool, &url->host, "localhost");
return (pjsip_uri*)name_addr;
}
static pjsip_uri *create_uri9(pj_pool_t *pool)
{
/* " \"User\" <sip:user@localhost:5071>" */
pjsip_name_addr *name_addr = pjsip_name_addr_create(pool);
pjsip_sip_uri *url;
url = pjsip_sip_uri_create(pool, 0);
name_addr->uri = (pjsip_uri*) url;
pj_strdup2(pool, &name_addr->display, "User");
pj_strdup2(pool, &url->user, "user");
pj_strdup2(pool, &url->host, "localhost");
url->port = 5071;
return (pjsip_uri*)name_addr;
}
static pjsip_uri *create_uri10(pj_pool_t *pool)
{
/* " \"Strange User\\\"\\\\\\\"\" <sip:localhost>" */
pjsip_name_addr *name_addr = pjsip_name_addr_create(pool);
pjsip_sip_uri *url;
url = pjsip_sip_uri_create(pool, 0);
name_addr->uri = (pjsip_uri*) url;
pj_strdup2(pool, &name_addr->display, "Strange User\\\"\\\\\\\"");
pj_strdup2(pool, &url->host, "localhost");
return (pjsip_uri*)name_addr;
}
static pjsip_uri *create_uri11(pj_pool_t *pool)
{
/* " \"Rogue User\\\" <sip:localhost>" */
pjsip_name_addr *name_addr = pjsip_name_addr_create(pool);
pjsip_sip_uri *url;
url = pjsip_sip_uri_create(pool, 0);
name_addr->uri = (pjsip_uri*) url;
pj_strdup2(pool, &name_addr->display, "Rogue User\\");
pj_strdup2(pool, &url->host, "localhost");
return (pjsip_uri*)name_addr;
}
static pjsip_uri *create_uri12(pj_pool_t *pool)
{
/* "Strange User\" <sip:localhost>" */
pjsip_name_addr *name_addr = pjsip_name_addr_create(pool);
pjsip_sip_uri *url;
url = pjsip_sip_uri_create(pool, 0);
name_addr->uri = (pjsip_uri*) url;
pj_strdup2(pool, &name_addr->display, "Strange User\"");
pj_strdup2(pool, &url->host, "localhost");
return (pjsip_uri*)name_addr;
}
static pjsip_uri *create_uri13(pj_pool_t *pool)
{
/* "sip:localhost;pvalue=\"hello world\"" */
pjsip_sip_uri *url;
url = pjsip_sip_uri_create(pool, 0);
pj_strdup2(pool, &url->host, "localhost");
//pj_strdup2(pool, &url->other_param, ";pvalue=\"hello world\"");
param_add(url->other_param, "pvalue", "\"hello world\"");
return (pjsip_uri*)url;
}
static pjsip_uri *create_uri14(pj_pool_t *pool)
{
/* "This is -. !% *_+`'~ me <sip:a19A&=+$,;?/%2c:%40a&Zz=+$,@my_proxy09.my-domain.com:9801>" */
pjsip_name_addr *name_addr = pjsip_name_addr_create(pool);
pjsip_sip_uri *url;
url = pjsip_sip_uri_create(pool, 0);
name_addr->uri = (pjsip_uri*) url;
pj_strdup2(pool, &name_addr->display, "This is -. !% *_+`'~ me");
pj_strdup2(pool, &url->user, "a19A&=+$,;?/,");
pj_strdup2(pool, &url->passwd, "@a&Zz=+$,");
pj_strdup2(pool, &url->host, "my_proxy09.MY-domain.com");
url->port = 9801;
return (pjsip_uri*)name_addr;
}
static pjsip_uri *create_uri15(pj_pool_t *pool)
{
/* "sip:abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.com" */
pjsip_sip_uri *url;
url = pjsip_sip_uri_create(pool, 0);
pj_strdup2(pool, &url->host, ALPHANUM "-_.com");
return (pjsip_uri*)url;
}
static pjsip_uri *create_uri16(pj_pool_t *pool)
{
/* "sip:" USER_CHAR ":" PASS_CHAR "@host" */
pjsip_sip_uri *url;
url = pjsip_sip_uri_create(pool, 0);
pj_strdup2(pool, &url->user, USER_CHAR);
pj_strdup2(pool, &url->passwd, PASS_CHAR);
pj_strdup2(pool, &url->host, "host");
return (pjsip_uri*)url;
}
static pjsip_uri *create_uri17(pj_pool_t *pool)
{
/* "sip:host;user=ip;" PARAM_CHAR "%21=" PARAM_CHAR "%21;lr;other=1;transport=sctp;other2" */
pjsip_sip_uri *url;
url = pjsip_sip_uri_create(pool, 0);
pj_strdup2(pool, &url->host, "host");
pj_strdup2(pool, &url->user_param, "ip");
pj_strdup2(pool, &url->transport_param, "sctp");
param_add(url->other_param, PARAM_CHAR "!", PARAM_CHAR "!");
param_add(url->other_param, "other", "1");
param_add(url->other_param, "other2", "");
url->lr_param = 1;
return (pjsip_uri*)url;
}
static pjsip_uri *create_uri25(pj_pool_t *pool)
{
/* "tel:+1-201-555-0123" */
pjsip_tel_uri *uri = pjsip_tel_uri_create(pool);
uri->number = pj_str("+1-201-555-0123");
return (pjsip_uri*)uri;
}
static pjsip_uri *create_uri26(pj_pool_t *pool)
{
/* tel:7042;phone-context=example.com */
pjsip_tel_uri *uri = pjsip_tel_uri_create(pool);
uri->number = pj_str("7042");
uri->context = pj_str("example.com");
return (pjsip_uri*)uri;
}
static pjsip_uri *create_uri27(pj_pool_t *pool)
{
/* "tel:863-1234;phone-context=+1-914-555" */
pjsip_tel_uri *uri = pjsip_tel_uri_create(pool);
uri->number = pj_str("863-1234");
uri->context = pj_str("+1-914-555");
return (pjsip_uri*)uri;
}
/* "tel:1" */
static pjsip_uri *create_uri28(pj_pool_t *pool)
{
pjsip_tel_uri *uri = pjsip_tel_uri_create(pool);
uri->number = pj_str("1");
return (pjsip_uri*)uri;
}
/* "tel:(44).1234-*#+Deaf" */
static pjsip_uri *create_uri29(pj_pool_t *pool)
{
pjsip_tel_uri *uri = pjsip_tel_uri_create(pool);
uri->number = pj_str("(44).1234-*#+Deaf");
return (pjsip_uri*)uri;
}
/* "tel:+1;isub=/:@&$,-_.!~*'()[]/:&$aA1%21+=" */
static pjsip_uri *create_uri30(pj_pool_t *pool)
{
pjsip_tel_uri *uri = pjsip_tel_uri_create(pool);
uri->number = pj_str("+1");
uri->isub_param = pj_str("/:@&$,-_.!~*'()[]/:&$aA1!+=");
return (pjsip_uri*)uri;
}
/* "tel:+1;ext=+123" */
static pjsip_uri *create_uri31(pj_pool_t *pool)
{
pjsip_tel_uri *uri = pjsip_tel_uri_create(pool);
uri->number = pj_str("+1");
uri->ext_param = pj_str("+123");
return (pjsip_uri*)uri;
}
/* "tel:911;phone-context=+1-911" */
static pjsip_uri *create_uri32(pj_pool_t *pool)
{
pjsip_tel_uri *uri = pjsip_tel_uri_create(pool);
uri->number = pj_str("911");
uri->context = pj_str("+1-911");
return (pjsip_uri*)uri;
}
/* "tel:911;phone-context=emergency.example.com" */
static pjsip_uri *create_uri33(pj_pool_t *pool)
{
pjsip_tel_uri *uri = pjsip_tel_uri_create(pool);
uri->number = pj_str("911");
uri->context = pj_str("EMERGENCY.EXAMPLE.COM");
return (pjsip_uri*)uri;
}
/* "tel:911;p1=p1;p2=p2" */
static pjsip_uri *create_uri34(pj_pool_t *pool)
{
pjsip_tel_uri *uri = pjsip_tel_uri_create(pool);
pjsip_param *p;
uri->number = pj_str("911");
p = PJ_POOL_ALLOC_T(pool, pjsip_param);
p->name = p->value = pj_str("p1");
pj_list_insert_before(&uri->other_param, p);
return (pjsip_uri*)uri;
}
/* "sip:user@[::1];maddr=[::01]" */
static pjsip_uri *create_uri35( pj_pool_t *pool )
{
pjsip_sip_uri *url;
url = pjsip_sip_uri_create(pool, 0);
url->user = pj_str("user");
url->host = pj_str("::1");
url->maddr_param = pj_str("::01");
return (pjsip_uri*)url;
}
/* "sip:[::1];maddr=[::01]" */
static pjsip_uri *create_uri36( pj_pool_t *pool )
{
pjsip_sip_uri *url;
url = pjsip_sip_uri_create(pool, 0);
url->host = pj_str("::1");
url->maddr_param = pj_str("::01");
return (pjsip_uri*)url;
}
/* "\"\xC0\x81\" <sip:localhost>" */
static pjsip_uri *create_uri37( pj_pool_t *pool )
{
pjsip_name_addr *name;
pjsip_sip_uri *url;
name = pjsip_name_addr_create(pool);
name->display = pj_str("\xC0\x81");
url = pjsip_sip_uri_create(pool, 0);
url->host = pj_str("localhost");
name->uri = (pjsip_uri*)url;
return (pjsip_uri*)name;
}
/* "\xC0\x81 <sip:localhost>" */
static pjsip_uri *create_uri38( pj_pool_t *pool )
{
pjsip_name_addr *name;
pjsip_sip_uri *url;
name = pjsip_name_addr_create(pool);
name->display = pj_str("\xC0\x81");
url = pjsip_sip_uri_create(pool, 0);
url->host = pj_str("localhost");
name->uri = (pjsip_uri*)url;
return (pjsip_uri*)name;
}
static pjsip_uri *create_dummy(pj_pool_t *pool)
{
PJ_UNUSED_ARG(pool);
return NULL;
}
/*****************************************************************************/
/*
* Test one test entry.
*/
static pj_status_t do_uri_test(pj_pool_t *pool, struct uri_test *entry)
{
pj_status_t status;
int len;
char *input;
pjsip_uri *parsed_uri, *ref_uri;
pj_str_t s1 = {NULL, 0}, s2 = {NULL, 0};
pj_timestamp t1, t2;
if (entry->len == 0)
entry->len = pj_ansi_strlen(entry->str);
#if defined(PJSIP_UNESCAPE_IN_PLACE) && PJSIP_UNESCAPE_IN_PLACE!=0
input = pj_pool_alloc(pool, entry->len + 1);
pj_memcpy(input, entry->str, entry->len);
input[entry->len] = '\0';
#else
input = entry->str;
#endif
/* Parse URI text. */
pj_get_timestamp(&t1);
var.parse_len = var.parse_len + entry->len;
parsed_uri = pjsip_parse_uri(pool, input, entry->len, 0);
if (!parsed_uri) {
/* Parsing failed. If the entry says that this is expected, then
* return OK.
*/
status = entry->status==ERR_SYNTAX_ERR ? PJ_SUCCESS : -10;
if (status != 0) {
PJ_LOG(3,(THIS_FILE, " uri parse error!\n"
" uri='%s'\n",
input));
}
goto on_return;
}
pj_get_timestamp(&t2);
pj_sub_timestamp(&t2, &t1);
pj_add_timestamp(&var.parse_time, &t2);
/* Create the reference URI. */
ref_uri = entry->creator(pool);
/* Print both URI. */
s1.ptr = (char*) pj_pool_alloc(pool, PJSIP_MAX_URL_SIZE);
s2.ptr = (char*) pj_pool_alloc(pool, PJSIP_MAX_URL_SIZE);
pj_get_timestamp(&t1);
len = pjsip_uri_print( PJSIP_URI_IN_OTHER, parsed_uri, s1.ptr, PJSIP_MAX_URL_SIZE);
if (len < 1) {
status = -20;
goto on_return;
}
s1.ptr[len] = '\0';
s1.slen = len;
var.print_len = var.print_len + len;
pj_get_timestamp(&t2);
pj_sub_timestamp(&t2, &t1);
pj_add_timestamp(&var.print_time, &t2);
len = pjsip_uri_print( PJSIP_URI_IN_OTHER, ref_uri, s2.ptr, PJSIP_MAX_URL_SIZE);
if (len < 1) {
status = -30;
goto on_return;
}
s2.ptr[len] = '\0';
s2.slen = len;
/* Full comparison of parsed URI with reference URI. */
pj_get_timestamp(&t1);
status = pjsip_uri_cmp(PJSIP_URI_IN_OTHER, parsed_uri, ref_uri);
if (status != 0) {
/* Not equal. See if this is the expected status. */
status = entry->status==ERR_NOT_EQUAL ? PJ_SUCCESS : -40;
if (status != 0) {
PJ_LOG(3,(THIS_FILE, " uri comparison mismatch, status=%d:\n"
" uri1='%s'\n"
" uri2='%s'",
status, s1.ptr, s2.ptr));
}
goto on_return;
} else {
/* Equal. See if this is the expected status. */
status = entry->status==PJ_SUCCESS ? PJ_SUCCESS : -50;
if (status != PJ_SUCCESS) {
goto on_return;
}
}
var.cmp_len = var.cmp_len + len;
pj_get_timestamp(&t2);
pj_sub_timestamp(&t2, &t1);
pj_add_timestamp(&var.cmp_time, &t2);
/* Compare text. */
if (entry->printed) {
if (pj_strcmp2(&s1, entry->printed) != 0) {
/* Not equal. */
PJ_LOG(3,(THIS_FILE, " uri print mismatch:\n"
" printed='%s'\n"
" expectd='%s'",
s1.ptr, entry->printed));
status = -60;
}
} else {
if (pj_strcmp(&s1, &s2) != 0) {
/* Not equal. */
PJ_LOG(3,(THIS_FILE, " uri print mismatch:\n"
" uri1='%s'\n"
" uri2='%s'",
s1.ptr, s2.ptr));
status = -70;
}
}
on_return:
return status;
}
static int simple_uri_test(void)
{
unsigned i;
pj_pool_t *pool;
pj_status_t status;
PJ_LOG(3,(THIS_FILE, " simple test"));
for (i=0; i<PJ_ARRAY_SIZE(uri_test_array); ++i) {
pool = pjsip_endpt_create_pool(endpt, "", POOL_SIZE, POOL_SIZE);
status = do_uri_test(pool, &uri_test_array[i]);
pjsip_endpt_release_pool(endpt, pool);
if (status != PJ_SUCCESS) {
PJ_LOG(3,(THIS_FILE, " error %d when testing entry %d",
status, i));
return status;
}
}
return 0;
}
#if INCLUDE_BENCHMARKS
static int uri_benchmark(unsigned *p_parse, unsigned *p_print, unsigned *p_cmp)
{
unsigned i, loop;
pj_status_t status = PJ_SUCCESS;
pj_timestamp zero;
pj_time_val elapsed;
pj_highprec_t avg_parse, avg_print, avg_cmp, kbytes;
pj_bzero(&var, sizeof(var));
zero.u32.hi = zero.u32.lo = 0;
var.parse_len = var.print_len = var.cmp_len = 0;
var.parse_time.u32.hi = var.parse_time.u32.lo = 0;
var.print_time.u32.hi = var.print_time.u32.lo = 0;
var.cmp_time.u32.hi = var.cmp_time.u32.lo = 0;
for (loop=0; loop<LOOP_COUNT; ++loop) {
for (i=0; i<PJ_ARRAY_SIZE(uri_test_array); ++i) {
pj_pool_t *pool;
pool = pjsip_endpt_create_pool(endpt, "", POOL_SIZE, POOL_SIZE);
status = do_uri_test(pool, &uri_test_array[i]);
pjsip_endpt_release_pool(endpt, pool);
if (status != PJ_SUCCESS) {
PJ_LOG(3,(THIS_FILE, " error %d when testing entry %d",
status, i));
pjsip_endpt_release_pool(endpt, pool);
goto on_return;
}
}
}
kbytes = var.parse_len;
pj_highprec_mod(kbytes, 1000000);
pj_highprec_div(kbytes, 100000);
elapsed = pj_elapsed_time(&zero, &var.parse_time);
avg_parse = pj_elapsed_usec(&zero, &var.parse_time);
pj_highprec_mul(avg_parse, AVERAGE_URL_LEN);
pj_highprec_div(avg_parse, var.parse_len);
if (avg_parse == 0)
avg_parse = 1;
avg_parse = 1000000 / avg_parse;
PJ_LOG(3,(THIS_FILE,
" %u.%u MB of urls parsed in %d.%03ds (avg=%d urls/sec)",
(unsigned)(var.parse_len/1000000), (unsigned)kbytes,
elapsed.sec, elapsed.msec,
(unsigned)avg_parse));
*p_parse = (unsigned)avg_parse;
kbytes = var.print_len;
pj_highprec_mod(kbytes, 1000000);
pj_highprec_div(kbytes, 100000);
elapsed = pj_elapsed_time(&zero, &var.print_time);
avg_print = pj_elapsed_usec(&zero, &var.print_time);
pj_highprec_mul(avg_print, AVERAGE_URL_LEN);
pj_highprec_div(avg_print, var.parse_len);
if (avg_print == 0)
avg_print = 1;
avg_print = 1000000 / avg_print;
PJ_LOG(3,(THIS_FILE,
" %u.%u MB of urls printed in %d.%03ds (avg=%d urls/sec)",
(unsigned)(var.print_len/1000000), (unsigned)kbytes,
elapsed.sec, elapsed.msec,
(unsigned)avg_print));
*p_print = (unsigned)avg_print;
kbytes = var.cmp_len;
pj_highprec_mod(kbytes, 1000000);
pj_highprec_div(kbytes, 100000);
elapsed = pj_elapsed_time(&zero, &var.cmp_time);
avg_cmp = pj_elapsed_usec(&zero, &var.cmp_time);
pj_highprec_mul(avg_cmp, AVERAGE_URL_LEN);
pj_highprec_div(avg_cmp, var.cmp_len);
if (avg_cmp == 0)
avg_cmp = 1;
avg_cmp = 1000000 / avg_cmp;
PJ_LOG(3,(THIS_FILE,
" %u.%u MB of urls compared in %d.%03ds (avg=%d urls/sec)",
(unsigned)(var.cmp_len/1000000), (unsigned)kbytes,
elapsed.sec, elapsed.msec,
(unsigned)avg_cmp));
*p_cmp = (unsigned)avg_cmp;
on_return:
return status;
}
#endif /* INCLUDE_BENCHMARKS */
/*****************************************************************************/
int uri_test(void)
{
enum { COUNT = 1, DETECT=0, PARSE=1, PRINT=2 };
struct {
unsigned parse;
unsigned print;
unsigned cmp;
} run[COUNT];
unsigned i, max, avg_len;
char desc[200];
pj_status_t status;
status = simple_uri_test();
if (status != PJ_SUCCESS)
return status;
#if INCLUDE_BENCHMARKS
for (i=0; i<COUNT; ++i) {
PJ_LOG(3,(THIS_FILE, " benchmarking (%d of %d)...", i+1, COUNT));
status = uri_benchmark(&run[i].parse, &run[i].print, &run[i].cmp);
if (status != PJ_SUCCESS)
return status;
}
/* Calculate average URI length */
for (i=0, avg_len=0; i<PJ_ARRAY_SIZE(uri_test_array); ++i) {
avg_len += uri_test_array[i].len;
}
avg_len /= PJ_ARRAY_SIZE(uri_test_array);
/*
* Print maximum parse/sec
*/
for (i=0, max=0; i<COUNT; ++i)
if (run[i].parse > max) max = run[i].parse;
PJ_LOG(3,("", " Maximum URI parse/sec=%u", max));
pj_ansi_sprintf(desc, "Number of SIP/TEL URIs that can be <B>parsed</B> with "
"<tt>pjsip_parse_uri()</tt> per second "
"(tested with %d URI set, with average length of "
"%d chars)",
(int)PJ_ARRAY_SIZE(uri_test_array), avg_len);
report_ival("uri-parse-per-sec", max, "URI/sec", desc);
/* URI parsing bandwidth */
report_ival("uri-parse-bandwidth-mb", avg_len*max/1000000, "MB/sec",
"URI parsing bandwidth in megabytes (number of megabytes "
"worth of URI that can be parsed per second)");
/* Print maximum print/sec */
for (i=0, max=0; i<COUNT; ++i)
if (run[i].print > max) max = run[i].print;
PJ_LOG(3,("", " Maximum URI print/sec=%u", max));
pj_ansi_sprintf(desc, "Number of SIP/TEL URIs that can be <B>printed</B> with "
"<tt>pjsip_uri_print()</tt> per second "
"(tested with %d URI set, with average length of "
"%d chars)",
(int)PJ_ARRAY_SIZE(uri_test_array), avg_len);
report_ival("uri-print-per-sec", max, "URI/sec", desc);
/* Print maximum detect/sec */
for (i=0, max=0; i<COUNT; ++i)
if (run[i].cmp > max) max = run[i].cmp;
PJ_LOG(3,("", " Maximum URI comparison/sec=%u", max));
pj_ansi_sprintf(desc, "Number of SIP/TEL URIs that can be <B>compared</B> with "
"<tt>pjsip_uri_cmp()</tt> per second "
"(tested with %d URI set, with average length of "
"%d chars)",
(int)PJ_ARRAY_SIZE(uri_test_array), avg_len);
report_ival("uri-cmp-per-sec", max, "URI/sec", desc);
#endif /* INCLUDE_BENCHMARKS */
return PJ_SUCCESS;
}
|
v0idp/virtuoso-codegen
|
include/Firebase/Firestore/FirestoreCpp.hpp
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: Firebase.Firestore.DocumentSnapshotProxy
#include "Firebase/Firestore/DocumentSnapshotProxy.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: Firebase::Firestore
namespace Firebase::Firestore {
// Forward declaring type: QueryProxy
class QueryProxy;
// Forward declaring type: QuerySnapshotProxy
class QuerySnapshotProxy;
// Forward declaring type: WriteBatchProxy
class WriteBatchProxy;
// Forward declaring type: FieldToValueMap
class FieldToValueMap;
// Forward declaring type: FieldValueProxy
class FieldValueProxy;
// Forward declaring type: DocumentReferenceProxy
class DocumentReferenceProxy;
// Forward declaring type: SetOptionsProxy
class SetOptionsProxy;
// Forward declaring type: FieldValueVector
class FieldValueVector;
// Forward declaring type: DocumentSnapshotVector
class DocumentSnapshotVector;
}
// Forward declaring namespace: System::Threading::Tasks
namespace System::Threading::Tasks {
// Forward declaring type: Task
class Task;
}
// Completed forward declares
// Type namespace: Firebase.Firestore
namespace Firebase::Firestore {
// Forward declaring type: FirestoreCpp
class FirestoreCpp;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::Firebase::Firestore::FirestoreCpp);
DEFINE_IL2CPP_ARG_TYPE(::Firebase::Firestore::FirestoreCpp*, "Firebase.Firestore", "FirestoreCpp");
// Type namespace: Firebase.Firestore
namespace Firebase::Firestore {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: Firebase.Firestore.FirestoreCpp
// [TokenAttribute] Offset: FFFFFFFF
class FirestoreCpp : public ::Il2CppObject {
public:
// static public System.Boolean QueryEquals(Firebase.Firestore.QueryProxy lhs, Firebase.Firestore.QueryProxy rhs)
// Offset: 0xD5BA8C
static bool QueryEquals(::Firebase::Firestore::QueryProxy* lhs, ::Firebase::Firestore::QueryProxy* rhs);
// static public System.Boolean QuerySnapshotEquals(Firebase.Firestore.QuerySnapshotProxy lhs, Firebase.Firestore.QuerySnapshotProxy rhs)
// Offset: 0xD5BC5C
static bool QuerySnapshotEquals(::Firebase::Firestore::QuerySnapshotProxy* lhs, ::Firebase::Firestore::QuerySnapshotProxy* rhs);
// static public System.Boolean DocumentSnapshotEquals(Firebase.Firestore.DocumentSnapshotProxy lhs, Firebase.Firestore.DocumentSnapshotProxy rhs)
// Offset: 0xD53AB0
static bool DocumentSnapshotEquals(::Firebase::Firestore::DocumentSnapshotProxy* lhs, ::Firebase::Firestore::DocumentSnapshotProxy* rhs);
// static public System.Int32 QueryHashCode(Firebase.Firestore.QueryProxy query)
// Offset: 0xD5BEC4
static int QueryHashCode(::Firebase::Firestore::QueryProxy* query);
// static public System.Int32 QuerySnapshotHashCode(Firebase.Firestore.QuerySnapshotProxy snapshot)
// Offset: 0xD5BFEC
static int QuerySnapshotHashCode(::Firebase::Firestore::QuerySnapshotProxy* snapshot);
// static public System.Int32 DocumentSnapshotHashCode(Firebase.Firestore.DocumentSnapshotProxy snapshot)
// Offset: 0xD53B84
static int DocumentSnapshotHashCode(::Firebase::Firestore::DocumentSnapshotProxy* snapshot);
// static public Firebase.Firestore.FieldToValueMap ConvertFieldValueToMap(Firebase.Firestore.FieldValueProxy fieldValue)
// Offset: 0xD49EF8
static ::Firebase::Firestore::FieldToValueMap* ConvertFieldValueToMap(::Firebase::Firestore::FieldValueProxy* fieldValue);
// static public Firebase.Firestore.FieldValueProxy ConvertMapToFieldValue(Firebase.Firestore.FieldToValueMap wrapper)
// Offset: 0xD4DA60
static ::Firebase::Firestore::FieldValueProxy* ConvertMapToFieldValue(::Firebase::Firestore::FieldToValueMap* wrapper);
// static public Firebase.Firestore.FieldValueProxy ConvertSnapshotToFieldValue(Firebase.Firestore.DocumentSnapshotProxy snapshot, Firebase.Firestore.DocumentSnapshotProxy/Firebase.Firestore.ServerTimestampBehavior stb)
// Offset: 0xD5C294
static ::Firebase::Firestore::FieldValueProxy* ConvertSnapshotToFieldValue(::Firebase::Firestore::DocumentSnapshotProxy* snapshot, ::Firebase::Firestore::DocumentSnapshotProxy::ServerTimestampBehavior stb);
// static public System.Void WriteBatchUpdate(Firebase.Firestore.WriteBatchProxy batch, Firebase.Firestore.DocumentReferenceProxy doc, Firebase.Firestore.FieldValueProxy fieldValue)
// Offset: 0xD5C40C
static void WriteBatchUpdate(::Firebase::Firestore::WriteBatchProxy* batch, ::Firebase::Firestore::DocumentReferenceProxy* doc, ::Firebase::Firestore::FieldValueProxy* fieldValue);
// static public System.Threading.Tasks.Task DocumentReferenceSetAsync(Firebase.Firestore.DocumentReferenceProxy doc, Firebase.Firestore.FieldValueProxy fieldValue, Firebase.Firestore.SetOptionsProxy options)
// Offset: 0xD52314
static ::System::Threading::Tasks::Task* DocumentReferenceSetAsync(::Firebase::Firestore::DocumentReferenceProxy* doc, ::Firebase::Firestore::FieldValueProxy* fieldValue, ::Firebase::Firestore::SetOptionsProxy* options);
// static public System.Threading.Tasks.Task DocumentReferenceUpdateAsync(Firebase.Firestore.DocumentReferenceProxy doc, Firebase.Firestore.FieldValueProxy fieldValue)
// Offset: 0xD520E0
static ::System::Threading::Tasks::Task* DocumentReferenceUpdateAsync(::Firebase::Firestore::DocumentReferenceProxy* doc, ::Firebase::Firestore::FieldValueProxy* fieldValue);
// static public System.Void WriteBatchSet(Firebase.Firestore.WriteBatchProxy writeBatch, Firebase.Firestore.DocumentReferenceProxy document, Firebase.Firestore.FieldValueProxy data, Firebase.Firestore.SetOptionsProxy options)
// Offset: 0xD5C78C
static void WriteBatchSet(::Firebase::Firestore::WriteBatchProxy* writeBatch, ::Firebase::Firestore::DocumentReferenceProxy* document, ::Firebase::Firestore::FieldValueProxy* data, ::Firebase::Firestore::SetOptionsProxy* options);
// static public Firebase.Firestore.FieldValueVector ConvertFieldValueToVector(Firebase.Firestore.FieldValueProxy value)
// Offset: 0xD4784C
static ::Firebase::Firestore::FieldValueVector* ConvertFieldValueToVector(::Firebase::Firestore::FieldValueProxy* value);
// static public Firebase.Firestore.FieldValueProxy ConvertVectorToFieldValue(Firebase.Firestore.FieldValueVector wrapper)
// Offset: 0xD4DE08
static ::Firebase::Firestore::FieldValueProxy* ConvertVectorToFieldValue(::Firebase::Firestore::FieldValueVector* wrapper);
// static public Firebase.Firestore.DocumentSnapshotVector QuerySnapshotDocuments(Firebase.Firestore.QuerySnapshotProxy snapshot)
// Offset: 0xD5CA48
static ::Firebase::Firestore::DocumentSnapshotVector* QuerySnapshotDocuments(::Firebase::Firestore::QuerySnapshotProxy* snapshot);
}; // Firebase.Firestore.FirestoreCpp
#pragma pack(pop)
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: Firebase::Firestore::FirestoreCpp::QueryEquals
// Il2CppName: QueryEquals
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::Firebase::Firestore::QueryProxy*, ::Firebase::Firestore::QueryProxy*)>(&Firebase::Firestore::FirestoreCpp::QueryEquals)> {
static const MethodInfo* get() {
static auto* lhs = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "QueryProxy")->byval_arg;
static auto* rhs = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "QueryProxy")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Firebase::Firestore::FirestoreCpp*), "QueryEquals", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{lhs, rhs});
}
};
// Writing MetadataGetter for method: Firebase::Firestore::FirestoreCpp::QuerySnapshotEquals
// Il2CppName: QuerySnapshotEquals
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::Firebase::Firestore::QuerySnapshotProxy*, ::Firebase::Firestore::QuerySnapshotProxy*)>(&Firebase::Firestore::FirestoreCpp::QuerySnapshotEquals)> {
static const MethodInfo* get() {
static auto* lhs = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "QuerySnapshotProxy")->byval_arg;
static auto* rhs = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "QuerySnapshotProxy")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Firebase::Firestore::FirestoreCpp*), "QuerySnapshotEquals", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{lhs, rhs});
}
};
// Writing MetadataGetter for method: Firebase::Firestore::FirestoreCpp::DocumentSnapshotEquals
// Il2CppName: DocumentSnapshotEquals
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::Firebase::Firestore::DocumentSnapshotProxy*, ::Firebase::Firestore::DocumentSnapshotProxy*)>(&Firebase::Firestore::FirestoreCpp::DocumentSnapshotEquals)> {
static const MethodInfo* get() {
static auto* lhs = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "DocumentSnapshotProxy")->byval_arg;
static auto* rhs = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "DocumentSnapshotProxy")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Firebase::Firestore::FirestoreCpp*), "DocumentSnapshotEquals", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{lhs, rhs});
}
};
// Writing MetadataGetter for method: Firebase::Firestore::FirestoreCpp::QueryHashCode
// Il2CppName: QueryHashCode
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(::Firebase::Firestore::QueryProxy*)>(&Firebase::Firestore::FirestoreCpp::QueryHashCode)> {
static const MethodInfo* get() {
static auto* query = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "QueryProxy")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Firebase::Firestore::FirestoreCpp*), "QueryHashCode", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{query});
}
};
// Writing MetadataGetter for method: Firebase::Firestore::FirestoreCpp::QuerySnapshotHashCode
// Il2CppName: QuerySnapshotHashCode
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(::Firebase::Firestore::QuerySnapshotProxy*)>(&Firebase::Firestore::FirestoreCpp::QuerySnapshotHashCode)> {
static const MethodInfo* get() {
static auto* snapshot = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "QuerySnapshotProxy")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Firebase::Firestore::FirestoreCpp*), "QuerySnapshotHashCode", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{snapshot});
}
};
// Writing MetadataGetter for method: Firebase::Firestore::FirestoreCpp::DocumentSnapshotHashCode
// Il2CppName: DocumentSnapshotHashCode
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(::Firebase::Firestore::DocumentSnapshotProxy*)>(&Firebase::Firestore::FirestoreCpp::DocumentSnapshotHashCode)> {
static const MethodInfo* get() {
static auto* snapshot = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "DocumentSnapshotProxy")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Firebase::Firestore::FirestoreCpp*), "DocumentSnapshotHashCode", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{snapshot});
}
};
// Writing MetadataGetter for method: Firebase::Firestore::FirestoreCpp::ConvertFieldValueToMap
// Il2CppName: ConvertFieldValueToMap
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Firebase::Firestore::FieldToValueMap* (*)(::Firebase::Firestore::FieldValueProxy*)>(&Firebase::Firestore::FirestoreCpp::ConvertFieldValueToMap)> {
static const MethodInfo* get() {
static auto* fieldValue = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "FieldValueProxy")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Firebase::Firestore::FirestoreCpp*), "ConvertFieldValueToMap", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{fieldValue});
}
};
// Writing MetadataGetter for method: Firebase::Firestore::FirestoreCpp::ConvertMapToFieldValue
// Il2CppName: ConvertMapToFieldValue
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Firebase::Firestore::FieldValueProxy* (*)(::Firebase::Firestore::FieldToValueMap*)>(&Firebase::Firestore::FirestoreCpp::ConvertMapToFieldValue)> {
static const MethodInfo* get() {
static auto* wrapper = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "FieldToValueMap")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Firebase::Firestore::FirestoreCpp*), "ConvertMapToFieldValue", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{wrapper});
}
};
// Writing MetadataGetter for method: Firebase::Firestore::FirestoreCpp::ConvertSnapshotToFieldValue
// Il2CppName: ConvertSnapshotToFieldValue
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Firebase::Firestore::FieldValueProxy* (*)(::Firebase::Firestore::DocumentSnapshotProxy*, ::Firebase::Firestore::DocumentSnapshotProxy::ServerTimestampBehavior)>(&Firebase::Firestore::FirestoreCpp::ConvertSnapshotToFieldValue)> {
static const MethodInfo* get() {
static auto* snapshot = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "DocumentSnapshotProxy")->byval_arg;
static auto* stb = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "DocumentSnapshotProxy/ServerTimestampBehavior")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Firebase::Firestore::FirestoreCpp*), "ConvertSnapshotToFieldValue", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{snapshot, stb});
}
};
// Writing MetadataGetter for method: Firebase::Firestore::FirestoreCpp::WriteBatchUpdate
// Il2CppName: WriteBatchUpdate
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(::Firebase::Firestore::WriteBatchProxy*, ::Firebase::Firestore::DocumentReferenceProxy*, ::Firebase::Firestore::FieldValueProxy*)>(&Firebase::Firestore::FirestoreCpp::WriteBatchUpdate)> {
static const MethodInfo* get() {
static auto* batch = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "WriteBatchProxy")->byval_arg;
static auto* doc = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "DocumentReferenceProxy")->byval_arg;
static auto* fieldValue = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "FieldValueProxy")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Firebase::Firestore::FirestoreCpp*), "WriteBatchUpdate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{batch, doc, fieldValue});
}
};
// Writing MetadataGetter for method: Firebase::Firestore::FirestoreCpp::DocumentReferenceSetAsync
// Il2CppName: DocumentReferenceSetAsync
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Threading::Tasks::Task* (*)(::Firebase::Firestore::DocumentReferenceProxy*, ::Firebase::Firestore::FieldValueProxy*, ::Firebase::Firestore::SetOptionsProxy*)>(&Firebase::Firestore::FirestoreCpp::DocumentReferenceSetAsync)> {
static const MethodInfo* get() {
static auto* doc = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "DocumentReferenceProxy")->byval_arg;
static auto* fieldValue = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "FieldValueProxy")->byval_arg;
static auto* options = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "SetOptionsProxy")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Firebase::Firestore::FirestoreCpp*), "DocumentReferenceSetAsync", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{doc, fieldValue, options});
}
};
// Writing MetadataGetter for method: Firebase::Firestore::FirestoreCpp::DocumentReferenceUpdateAsync
// Il2CppName: DocumentReferenceUpdateAsync
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Threading::Tasks::Task* (*)(::Firebase::Firestore::DocumentReferenceProxy*, ::Firebase::Firestore::FieldValueProxy*)>(&Firebase::Firestore::FirestoreCpp::DocumentReferenceUpdateAsync)> {
static const MethodInfo* get() {
static auto* doc = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "DocumentReferenceProxy")->byval_arg;
static auto* fieldValue = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "FieldValueProxy")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Firebase::Firestore::FirestoreCpp*), "DocumentReferenceUpdateAsync", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{doc, fieldValue});
}
};
// Writing MetadataGetter for method: Firebase::Firestore::FirestoreCpp::WriteBatchSet
// Il2CppName: WriteBatchSet
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(::Firebase::Firestore::WriteBatchProxy*, ::Firebase::Firestore::DocumentReferenceProxy*, ::Firebase::Firestore::FieldValueProxy*, ::Firebase::Firestore::SetOptionsProxy*)>(&Firebase::Firestore::FirestoreCpp::WriteBatchSet)> {
static const MethodInfo* get() {
static auto* writeBatch = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "WriteBatchProxy")->byval_arg;
static auto* document = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "DocumentReferenceProxy")->byval_arg;
static auto* data = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "FieldValueProxy")->byval_arg;
static auto* options = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "SetOptionsProxy")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Firebase::Firestore::FirestoreCpp*), "WriteBatchSet", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{writeBatch, document, data, options});
}
};
// Writing MetadataGetter for method: Firebase::Firestore::FirestoreCpp::ConvertFieldValueToVector
// Il2CppName: ConvertFieldValueToVector
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Firebase::Firestore::FieldValueVector* (*)(::Firebase::Firestore::FieldValueProxy*)>(&Firebase::Firestore::FirestoreCpp::ConvertFieldValueToVector)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "FieldValueProxy")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Firebase::Firestore::FirestoreCpp*), "ConvertFieldValueToVector", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: Firebase::Firestore::FirestoreCpp::ConvertVectorToFieldValue
// Il2CppName: ConvertVectorToFieldValue
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Firebase::Firestore::FieldValueProxy* (*)(::Firebase::Firestore::FieldValueVector*)>(&Firebase::Firestore::FirestoreCpp::ConvertVectorToFieldValue)> {
static const MethodInfo* get() {
static auto* wrapper = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "FieldValueVector")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Firebase::Firestore::FirestoreCpp*), "ConvertVectorToFieldValue", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{wrapper});
}
};
// Writing MetadataGetter for method: Firebase::Firestore::FirestoreCpp::QuerySnapshotDocuments
// Il2CppName: QuerySnapshotDocuments
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Firebase::Firestore::DocumentSnapshotVector* (*)(::Firebase::Firestore::QuerySnapshotProxy*)>(&Firebase::Firestore::FirestoreCpp::QuerySnapshotDocuments)> {
static const MethodInfo* get() {
static auto* snapshot = &::il2cpp_utils::GetClassFromName("Firebase.Firestore", "QuerySnapshotProxy")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Firebase::Firestore::FirestoreCpp*), "QuerySnapshotDocuments", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{snapshot});
}
};
|
MashMB/1pass
|
1pass-app/gui/helpwidget.go
|
// Contextual help widget.
//
// @author TSS
package gui
import (
"fmt"
"strings"
"github.com/jroimartin/gocui"
)
const (
mainHelp string = `Exit: CTRL+Q
Lock: CTRL+L`
)
type helpWidget struct {
name string
title string
help string
}
func newHelpWidget() *helpWidget {
return &helpWidget{
name: "help",
title: "Help",
}
}
func (hw *helpWidget) update(ui *gocui.Gui) error {
view, err := ui.View(hw.name)
if err != nil {
return err
}
view.Clear()
body := ""
mainLines := strings.Split(mainHelp, "\n")
for _, line := range mainLines {
body = body + line + "\t\t\t\t"
}
if hw.help != "" {
lines := strings.Split(hw.help, "\n")
for idx, line := range lines {
body = body + line
if idx != len(lines)-1 {
body = body + "\t\t\t\t"
}
}
}
fmt.Fprint(view, body)
return nil
}
func (hw *helpWidget) Layout(ui *gocui.Gui) error {
maxX, maxY := ui.Size()
if view, err := ui.SetView(hw.name, 0, maxY-3, maxX-1, maxY-1); err != nil {
if err != gocui.ErrUnknownView {
return err
}
view.Title = hw.title
hw.update(ui)
}
return nil
}
|
RdecKa/bark
|
bark/runtime/scenario/scenario_generation/config_readers/dynamic_model_config_readers.py
|
<gh_stars>0
# Copyright (c) 2020 fortiss GmbH
#
# Authors: <NAME>, <NAME>, <NAME> and
# <NAME>
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
from bark.runtime.scenario.scenario_generation.config_readers.config_readers_interfaces import ConfigReaderDynamicModels
from bark.core.models.dynamic import *
from bark.runtime.commons.parameters import ParameterServer
# this config reader defines dynamic models with fixed type for all agents
class FixedDynamicType(ConfigReaderDynamicModels):
def create_from_config(self, config_param_object, road_corridor, agent_states, **kwargs):
model_type = config_param_object["ModelType", "Type of dynamic model \
used for all vehicles", "SingleTrackModel"]
dynamic_models = []
for _ in agent_states:
bark_model = self.model_from_model_type(model_type)
dynamic_models.append(bark_model)
return dynamic_models, {}, config_param_object
def default_params(self):
return {"ModelType": "SingleTrackModel"}
def model_from_model_type(self, model_type):
params = ParameterServer()
bark_model = eval("{}(params)".format(model_type))
return bark_model
|
vovietanh/tomox-sdk-ui
|
src/store/models/walletPage.js
|
// @flow
import {
getAccountBalancesDomain,
getAccountDomain,
getTokenDomain,
getTransferTokensFormDomain,
} from '../domains'
import * as actionCreators from '../actions/walletPage'
import { quoteTokenSymbols } from '../../config/quotes'
import { push } from 'connected-react-router'
import type { State, ThunkAction } from '../../types'
export default function walletPageSelector(state: State) {
const accountBalancesDomain = getAccountBalancesDomain(state)
const accountDomain = getAccountDomain(state)
const tokenDomain = getTokenDomain(state)
const transferTokensFormDomain = getTransferTokensFormDomain(state)
const tokens = tokenDomain.tokens()
const quoteTokens = quoteTokenSymbols
const baseTokens = tokenDomain
.symbols()
.filter(symbol => quoteTokens.indexOf(symbol) !== -1)
const tokenData = accountBalancesDomain.getBalancesAndAllowances(tokens)
return {
tomoBalance: accountBalancesDomain.formattedTomoBalance(),
balancesLoading: accountBalancesDomain.loading(),
tokenData,
quoteTokens,
baseTokens,
accountAddress: accountDomain.address(),
authenticated: accountDomain.authenticated(),
currentBlock: accountDomain.currentBlock(),
showHelpModal: accountDomain.showHelpModal(),
connected: true,
gas: transferTokensFormDomain.getGas(),
gasPrice: transferTokensFormDomain.getGasPrice(),
}
}
export function redirectToTradingPage(symbol: string): ThunkAction {
return async (dispatch, getState) => {
const quoteTokenIndex = quoteTokenSymbols.indexOf(symbol)
let baseTokenSymbol, quoteTokenSymbol
if (quoteTokenIndex === 0) {
baseTokenSymbol = quoteTokenSymbols[1]
quoteTokenSymbol = quoteTokenSymbols[0]
} else {
baseTokenSymbol = symbol
quoteTokenSymbol = quoteTokenSymbols[0]
}
const pair = `${baseTokenSymbol}/${quoteTokenSymbol}`
dispatch(actionCreators.updateCurrentPair(pair))
dispatch(push('/trade'))
}
}
|
gamblor21/Adafruit_Learning_System_Guides
|
Getting_Started_With_Raspberry_Pi_Pico/traffic_light_crossing/code.py
|
<gh_stars>100-1000
"""Traffic light with pedestrian crossing simulator example for Pico. Turns on red, amber and green
LEDs in traffic light-like sequence. When button is pressed, upon light sequence completion, the
red LED turns on and the buzzer beeps to indicate pedestrian crossing is active.
REQUIRED HARDWARE:
* Red LED on pin GP11.
* Amber LED on pin GP14.
* Green LED on pin GP13.
* Button switch on pin GP16.
* Piezo buzzer on pin GP13.
"""
import time
import board
import digitalio
import pwmio
red_led = digitalio.DigitalInOut(board.GP11)
red_led.direction = digitalio.Direction.OUTPUT
amber_led = digitalio.DigitalInOut(board.GP14)
amber_led.direction = digitalio.Direction.OUTPUT
green_led = digitalio.DigitalInOut(board.GP13)
green_led.direction = digitalio.Direction.OUTPUT
button = digitalio.DigitalInOut(board.GP16)
button.switch_to_input(pull=digitalio.Pull.DOWN)
buzzer = pwmio.PWMOut(board.GP12, frequency=660, duty_cycle=0, variable_frequency=True)
button_pressed = False
def waiting_for_button(duration):
global button_pressed # pylint: disable=global-statement
end = time.monotonic() + duration
while time.monotonic() < end:
if button.value:
button_pressed = True
while True:
if button_pressed:
red_led.value = True
for _ in range(10):
buzzer.duty_cycle = 2 ** 15
waiting_for_button(0.2)
buzzer.duty_cycle = 0
waiting_for_button(0.2)
button_pressed = False
red_led.value = True
waiting_for_button(5)
amber_led.value = True
waiting_for_button(2)
red_led.value = False
amber_led.value = False
green_led.value = True
waiting_for_button(5)
green_led.value = False
amber_led.value = True
waiting_for_button(3)
amber_led.value = False
|
Rikoshet-234/xray-oxygen
|
code/engine.vc2008/xrGame/stalker_combat_actions.h
|
////////////////////////////////////////////////////////////////////////////
// Module : stalker_combat_actions.h
// Created : 25.03.2004
// Modified : 26.03.2004
// Author : <NAME>
// Description : Stalker combat action classes
////////////////////////////////////////////////////////////////////////////
#pragma once
#include "stalker_combat_action_base.h"
#include "random32.h"
class CCoverPoint;
namespace MonsterSpace
{
enum EBodyState;
enum EMovementType;
}
//////////////////////////////////////////////////////////////////////////
class CStalkerActionGetItemToKill : public CStalkerActionCombatBase
{
protected:
using inherited = CStalkerActionCombatBase;
public:
CStalkerActionGetItemToKill (CAI_Stalker *object, LPCSTR action_name = "");
virtual void initialize ();
virtual void execute ();
virtual void finalize ();
};
//////////////////////////////////////////////////////////////////////////
class CStalkerActionMakeItemKilling : public CStalkerActionCombatBase
{
protected:
using inherited = CStalkerActionCombatBase;
public:
CStalkerActionMakeItemKilling (CAI_Stalker *object, LPCSTR action_name = "");
virtual void initialize ();
virtual void execute ();
virtual void finalize ();
};
//////////////////////////////////////////////////////////////////////////
class CStalkerActionRetreatFromEnemy : public CStalkerActionCombatBase
{
protected:
using inherited = CStalkerActionCombatBase;
public:
CStalkerActionRetreatFromEnemy (CAI_Stalker *object, LPCSTR action_name = "");
virtual void execute ();
virtual void finalize ();
virtual _edge_value_type weight (const CSConditionState &condition0, const CSConditionState &condition1) const;
};
//////////////////////////////////////////////////////////////////////////
class CStalkerActionGetReadyToKill : public CStalkerActionCombatBase
{
protected:
using inherited = CStalkerActionCombatBase;
private:
MonsterSpace::EBodyState m_body_state;
MonsterSpace::EMovementType m_movement_type;
bool m_affect_properties;
bool m_enable_enemy_change;
public:
CStalkerActionGetReadyToKill(bool affect_properties, CAI_Stalker *object, LPCSTR action_name = "");
virtual void initialize ();
virtual void execute ();
virtual void finalize ();
};
//////////////////////////////////////////////////////////////////////////
class CStalkerActionKillEnemy : public CStalkerActionCombatBase
{
protected:
using inherited = CStalkerActionCombatBase;
public:
CStalkerActionKillEnemy (CAI_Stalker *object, LPCSTR action_name = "");
virtual void initialize ();
virtual void execute ();
virtual void finalize ();
};
//////////////////////////////////////////////////////////////////////////
class CStalkerActionTakeCover : public CStalkerActionCombatBase
{
protected:
using inherited = CStalkerActionCombatBase;
private:
MonsterSpace::EBodyState m_body_state;
MonsterSpace::EMovementType m_movement_type;
public:
CStalkerActionTakeCover (CAI_Stalker *object, LPCSTR action_name = "");
virtual void initialize ();
virtual void execute ();
};
//////////////////////////////////////////////////////////////////////////
class CStalkerActionLookOut : public CStalkerActionCombatBase
{
protected:
using inherited = CStalkerActionCombatBase;
private:
u32 m_last_change_time;
CRandom32 m_crouch_look_out_random;
public:
CStalkerActionLookOut (CAI_Stalker *object, LPCSTR action_name = "");
virtual void initialize ();
virtual void execute ();
};
//////////////////////////////////////////////////////////////////////////
class CStalkerActionHoldPosition : public CStalkerActionCombatBase
{
protected:
using inherited = CStalkerActionCombatBase;
public:
CStalkerActionHoldPosition (CAI_Stalker *object, LPCSTR action_name = "");
virtual void initialize ();
virtual void execute ();
};
//////////////////////////////////////////////////////////////////////////
class CStalkerActionDetourEnemy : public CStalkerActionCombatBase
{
const CCoverPoint *m_enemy_cover;
protected:
using inherited = CStalkerActionCombatBase;
public:
CStalkerActionDetourEnemy (CAI_Stalker *object, LPCSTR action_name = "");
virtual void initialize ();
virtual void execute ();
virtual void finalize ();
};
//////////////////////////////////////////////////////////////////////////
class CStalkerActionPostCombatWait : public CStalkerActionCombatBase
{
protected:
using inherited = CStalkerActionCombatBase;
public:
CStalkerActionPostCombatWait(CAI_Stalker *object, LPCSTR action_name = "");
virtual void initialize ();
};
//////////////////////////////////////////////////////////////////////////
class CStalkerActionHideFromGrenade : public CStalkerActionCombatBase
{
protected:
using inherited = CStalkerActionCombatBase;
public:
CStalkerActionHideFromGrenade(CAI_Stalker *object, LPCSTR action_name = "");
virtual void initialize ();
virtual void execute ();
};
//////////////////////////////////////////////////////////////////////////
class CStalkerActionSuddenAttack : public CStalkerActionCombatBase
{
protected:
using inherited = CStalkerActionCombatBase;
public:
CStalkerActionSuddenAttack (CAI_Stalker *object, LPCSTR action_name = "");
virtual void initialize ();
virtual void execute ();
};
//////////////////////////////////////////////////////////////////////////
class CStalkerActionKillEnemyIfPlayerOnThePath : public CStalkerActionCombatBase
{
protected:
using inherited = CStalkerActionCombatBase;
public:
CStalkerActionKillEnemyIfPlayerOnThePath(CAI_Stalker *object, LPCSTR action_name = "");
virtual void initialize ();
virtual void execute ();
virtual void finalize ();
};
//////////////////////////////////////////////////////////////////////////
class CStalkerActionCriticalHit : public CStalkerActionCombatBase
{
protected:
using inherited = CStalkerActionCombatBase;
public:
CStalkerActionCriticalHit (CAI_Stalker *object, LPCSTR action_name = "");
virtual void initialize ();
virtual void finalize ();
};
//////////////////////////////////////////////////////////////////////////
class CStalkerCombatActionThrowGrenade : public CStalkerActionCombatBase
{
protected:
using inherited = CStalkerActionCombatBase;
ALife::_OBJECT_ID m_grenade_id;
public:
CStalkerCombatActionThrowGrenade(CAI_Stalker *object, LPCSTR action_name = "");
virtual void initialize ();
virtual void execute ();
virtual void finalize ();
};
//////////////////////////////////////////////////////////////////////////
class CStalkerCombatActionSmartCover : public CStalkerActionCombatBase
{
using inherited = CStalkerActionCombatBase;
bool m_check_can_kill_enemy;
public:
CStalkerCombatActionSmartCover (CAI_Stalker *object, LPCSTR action_name = "");
virtual void initialize ();
virtual void execute ();
virtual void finalize ();
};
|
akatz2/openessence-demo
|
open-detectors/src/main/java/edu/jhuapl/bsp/detector/Ears.java
|
<reponame>akatz2/openessence-demo<filename>open-detectors/src/main/java/edu/jhuapl/bsp/detector/Ears.java
/*
* Copyright (c) 2013 The Johns Hopkins University/Applied Physics Laboratory
* All rights reserved.
*
* This material may be used, modified, or reproduced by or for the U.S.
* Government pursuant to the rights granted under the clauses at
* DFARS 252.227-7013/7014 or FAR 52.227-14.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* NO WARRANTY. THIS MATERIAL IS PROVIDED "AS IS." JHU/APL DISCLAIMS ALL
* WARRANTIES IN THE MATERIAL, WHETHER EXPRESS OR IMPLIED, INCLUDING (BUT NOT
* LIMITED TO) ANY AND ALL IMPLIED WARRANTIES OF PERFORMANCE,
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT OF
* INTELLECTUAL PROPERTY RIGHTS. ANY USER OF THE MATERIAL ASSUMES THE ENTIRE
* RISK AND LIABILITY FOR USING THE MATERIAL. IN NO EVENT SHALL JHU/APL BE
* LIABLE TO ANY USER OF THE MATERIAL FOR ANY ACTUAL, INDIRECT,
* CONSEQUENTIAL, SPECIAL OR OTHER DAMAGES ARISING FROM THE USE OF, OR
* INABILITY TO USE, THE MATERIAL, INCLUDING, BUT NOT LIMITED TO, ANY DAMAGES
* FOR LOST PROFITS.
*/
package edu.jhuapl.bsp.detector;
import java.util.ArrayList;
import java.util.Collections;
/**
* Runs the CDC Ears algorithms C1, C2, and C3.
*/
public class Ears {
public Ears() {
}
/**
* Runs the CDC Ears algorithms C1.
*
* @param data data array from first day to last, no interuptions.
*/
public static double[] calculateC1(double[] data) {
return calculate(data, 7, 0, 0, 1, .1, 2);
}
/**
* Runs the CDC Ears algorithms C2.
*
* @param data data array from first day to last, no interuptions.
*/
public static double[] calculateC2(double[] data) {
return calculate(data, 7, 2, 0, 1, .1, 2);
}
/**
* Runs the CDC Ears algorithms C3.
*
* @param data data array from first day to last, no interuptions.
*/
public static double[] calculateC3(double[] data) {
return calculate(data, 7, 2, 1, 1, .1, 2);
}
/**
* Calculates the results of the CDC ears algorithms.
*
* @param data data array from first day to last, no interuptions.
* @param baseline how many days of baseline to use.
* @param baseLag how many days of guardband to use.
* @param cusumFlag whether or not to use the cusum part of the algorithm.
* @param cusumK CUSUM K value
* @param minSigma minimum sigma allowed
* @param thresh what the threshold should be set at.
*/
private static double[] calculate(double[] data, int baseline, int baseLag, int cusumFlag,
double cusumK, double minSigma, double thresh) {
double sigmaEstimate = minSigma;
double[] earStat = new double[data.length];
for (int i = 0; i < earStat.length; i++) {
earStat[i] = 0;
}
double cusum0 = 0;
double cusum1 = 0;
int ndxBase = 0;
double estMean = 0;
double estSigma = 0;
double currSum = 0;
for (int i = baseline + baseLag; i < data.length; i++) {
ndxBase = i - (baseline + baseLag);
ArrayList list = new ArrayList();
for (int j = 0; j < baseline; j++) {
list.add(new Double(data[ndxBase]));
ndxBase++;
}
estMean = getAverage(list);
estSigma = Math.max(minSigma, getStdDev(list));
currSum = Math.max(0, data[i] - estMean - cusumK * estSigma) / estSigma;
if (Double.isNaN(currSum) || Double.isInfinite(currSum)) {
currSum = 0;
}
earStat[i] = currSum + cusumFlag * (cusum0 + cusum1);
cusum0 = cusum1;
if (currSum >= thresh) {
cusum1 = 0;
} else {
cusum1 = currSum;
}
}
return earStat;
}
/**
* Computes the standard deviation.
*
* @param list data list from first to last day with no interuptions
*/
public static double getStdDev(ArrayList list) {
double sum = 0;
double avg = getAverage(list);
double value = 0;
for (int i = 0; i < list.size(); i++) {
value = ((Double) list.get(i)).doubleValue();
sum = sum + ((value - avg) * (value - avg));
}
double stddev = Math.sqrt(sum / (list.size() - 1));
if (Double.isNaN(stddev) || Double.isInfinite(stddev)) {
return 0;
} else {
return stddev;
}
}
/**
* Computes the median.
*
* @param list data list from first to last day with no interuptions
*/
public static double getMedian(ArrayList list) {
Collections.sort(list);
int size = list.size();
int index = (int) Math.ceil(size / 2);
double value = ((Double) (list.get(index))).doubleValue();
if (Double.isNaN(value) || Double.isInfinite(value)) {
return 0;
} else {
return value;
}
}
/**
* Computes the average.
*
* @param list data list from first to last day with no interuptions
*/
public static double getAverage(ArrayList list) {
double sum = 0;
double value = 0;
int count = 0;
for (int i = 0; i < list.size(); i++) {
value = ((Double) list.get(i)).doubleValue();
count++;
sum = sum + value;
}
double average = (sum / count);
if (Double.isNaN(average) || Double.isInfinite(average)) {
return 0;
} else {
return average;
}
}
/**
* Tests the CDC Ears algorithms C1.
*
* @param data data array from first day to last, no interuptions.
*/
public static double[] gettestC1(double[] data) {
return calculate(data, 7, 0, 0, 1, .02, 2);
}
/**
* Tests the CDC Ears algorithms C2.
*
* @param data data array from first day to last, no interuptions.
*/
public static double[] gettestC2(double[] data) {
return calculate(data, 7, 2, 0, 1, .02, 2);
}
/**
* Tests the CDC Ears algorithms C3.
*
* @param data data array from first day to last, no interuptions.
*/
public static double[] gettestC3(double[] data) {
return calculate(data, 7, 2, 1, 1, .02, 2);
}
/**
* Tests the Ears algorithms using a data array.
*
* @param args command line arguments - none needed
*/
public static void main(String[] args) {
double[] data = {6, 142, 124, 145, 9, 6, 184, 130, 140, 136, 136, 20, 3, 169, 170, 134, 106,
181, 22, 1, 7, 233, 196, 153, 155, 19, 2, 277, 198, 192, 191, 218, 25, 4,
281, 161, 199, 182, 197, 19, 15, 272, 235, 227, 169, 153, 34, 7, 8, 299,
210, 135, 135, 18, 12, 163, 120, 85, 91, 87, 17, 3, 167, 130, 86, 87, 88,
11, 5, 128, 103, 86, 101, 79, 13, 4, 113, 92, 82, 85, 59, 16, 9, 101, 100,
76, 68, 83, 7, 5, 110, 98, 60, 37, 91, 6, 1, 53, 87, 115, 93, 83, 8, 4, 126,
96, 84, 73, 67, 6, 3, 143, 88, 90, 92, 109, 8, 2, 150, 130, 91, 93, 101, 3,
0, 157, 119, 106, 104, 84, 6, 1, 140, 100, 90, 51, 92, 9, 2, 111, 103, 95,
89, 46, 16, 3, 1, 78, 77, 78, 59, 4, 2, 69, 70, 61, 53, 47, 5, 0, 68, 75,
55, 49, 42, 2, 1, 45, 44, 38, 32, 39, 6, 0, 62, 53, 39, 42, 39, 3, 2, 45,
44, 30, 1, 1, 6, 2, 32, 33, 13, 16, 34, 6, 0, 39, 30, 26, 21, 21, 4, 1, 29,
34, 20, 25, 21, 3, 3, 44, 1};
double[] data2 = {25, 35, 30, 9, 4, 40, 30, 37, 28, 24, 13, 3, 30, 34, 25, 32, 20, 27, 16,
57, 77, 46, 16, 19, 12, 6, 48, 42, 32, 27, 38, 20, 11, 57, 44, 40, 32, 24,
13, 4, 26, 46, 32, 18, 25, 20, 3, 40, 36, 32, 34, 25, 15, 8, 11, 33, 22,
36, 30, 13, 3, 13, 64, 44, 42, 32, 15, 7, 45, 34, 39, 22, 40, 13, 6, 37,
40, 32, 39, 38, 11, 5, 44, 37, 46, 22, 29, 16, 9, 42, 43, 33, 25, 32, 1,
11, 45, 24, 30, 25, 34, 5, 9, 29, 26, 25, 28, 20, 8, 5, 24, 23, 34, 21, 19,
12, 1, 30, 30, 24, 32, 38, 7, 5, 38, 22, 14, 18, 21, 5, 5, 22, 16, 13, 15,
15, 3, 1, 14, 17, 9, 20, 5, 3, 3, 8, 3, 1, 0};
double[] predsC1 = Ears.calculateC1(data2);
double[] predsC2 = Ears.calculateC2(data2);
double[] predsC3 = Ears.calculateC3(data2);
for (int i = 0; i < predsC1.length; i++) {
System.out.println(predsC1[i]);
}
System.out.println("");
System.out.println("");
System.out.println("");
for (int i = 0; i < predsC1.length; i++) {
if (predsC1[i] >= 2) {
System.out.println(predsC1[i]);
} else {
System.out.println("-1");
}
}
System.out.println("");
System.out.println("");
System.out.println("");
for (int i = 0; i < predsC2.length; i++) {
System.out.println(predsC2[i]);
}
System.out.println("");
System.out.println("");
System.out.println("");
for (int i = 0; i < predsC2.length; i++) {
if (predsC2[i] >= 2) {
System.out.println(predsC2[i]);
} else {
System.out.println("-1");
}
}
System.out.println("");
System.out.println("");
System.out.println("");
for (int i = 0; i < predsC3.length; i++) {
System.out.println(predsC3[i]);
}
System.out.println("");
System.out.println("");
System.out.println("");
for (int i = 0; i < predsC3.length; i++) {
if (predsC3[i] >= 2) {
System.out.println(predsC3[i]);
} else {
System.out.println("-1");
}
}
}
}
|
mzcstech/mzcsfrontend
|
src/components/socialsecurity/store/reducer.js
|
<reponame>mzcstech/mzcsfrontend<gh_stars>1-10
// import * as actionType from './actionType'
import {fromJS} from 'immutable'
let PrivilegeReducer = fromJS({
personinformations:[]
})
export default (state = PrivilegeReducer, action) => {
if(action.type === "EDIT_PERSONINFORMATIONS" ){
return state.merge({personinformations:action.personInformation})
}
return state;
}
|
umjammer/vavi-nio-file-discutils
|
src/main/java/DiscUtils/OpticalDisk/DiscImageFile.java
|
<gh_stars>0
//
// Copyright (c) 2008-2011, <NAME>
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
package DiscUtils.OpticalDisk;
import java.io.Closeable;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import DiscUtils.Core.FileLocator;
import DiscUtils.Core.Geometry;
import DiscUtils.Core.VirtualDiskLayer;
import DiscUtils.Streams.SparseStream;
import DiscUtils.Streams.StreamBuffer;
import DiscUtils.Streams.Buffer.BufferStream;
import DiscUtils.Streams.Util.Ownership;
import dotnet4j.io.FileAccess;
import dotnet4j.io.Stream;
/**
* Represents a single optical disc image file.
*/
public final class DiscImageFile extends VirtualDiskLayer {
public static final int Mode1SectorSize = 2048;
public static final int Mode2SectorSize = 2352;
private final OpticalFormat _format;
private Closeable _toDispose;
/**
* Initializes a new instance of the DiscImageFile class.
*
* @param stream The stream to interpret.
*/
public DiscImageFile(Stream stream) {
this(stream, Ownership.None, OpticalFormat.None);
}
/**
* Initializes a new instance of the DiscImageFile class.
*
* @param stream The stream to interpret.
* @param ownsStream Indicates if the new instance should control the
* lifetime of the stream.
* @param format The disc image format.
*/
public DiscImageFile(Stream stream, Ownership ownsStream, OpticalFormat format) {
if (ownsStream == Ownership.Dispose) {
_toDispose = stream;
}
if (format == OpticalFormat.None) {
if (stream.getLength() % Mode1SectorSize == 0 && stream.getLength() % Mode2SectorSize != 0) {
_format = OpticalFormat.Mode1;
} else if (stream.getLength() % Mode1SectorSize != 0 && stream.getLength() % Mode2SectorSize == 0) {
_format = OpticalFormat.Mode2;
} else {
throw new dotnet4j.io.IOException("Unable to detect optical disk format");
}
} else {
_format = format;
}
setContent(stream instanceof SparseStream ? (SparseStream) stream : (SparseStream) null);
if (getContent() == null) {
setContent(SparseStream.fromStream(stream, Ownership.None));
}
if (_format == OpticalFormat.Mode2) {
Mode2Buffer converter = new Mode2Buffer(new StreamBuffer(getContent(), Ownership.None));
setContent(new BufferStream(converter, FileAccess.Read));
}
}
public long getCapacity() {
return getContent().getLength();
}
private SparseStream _content;
SparseStream getContent() {
return _content;
}
void setContent(SparseStream value) {
_content = value;
}
/**
* Gets the Geometry of the disc.
*
* Optical discs don't fit the CHS model, so dummy CHS data provided, but
* sector size is accurate.
*/
public Geometry getGeometry() {
// Note external sector size is always 2048 - 2352 just has extra header
// & error-correction info
return new Geometry(1, 1, 1, Mode1SectorSize);
}
/**
* Gets a value indicating if the layer only stores meaningful sectors.
*/
public boolean isSparse() {
return false;
}
/**
* Gets a value indicating whether the file is a differencing disk.
*/
public boolean needsParent() {
return false;
}
public FileLocator getRelativeFileLocator() {
return null;
}
/**
* Gets the content of this layer.
*
* @param parent The parent stream (if any).
* @param ownsParent Controls ownership of the parent stream.
* @return The content as a stream.
*/
public SparseStream openContent(SparseStream parent, Ownership ownsParent) {
if (ownsParent == Ownership.Dispose && parent != null) {
try {
parent.close();
} catch (IOException e) {
throw new dotnet4j.io.IOException(e);
}
}
return SparseStream.fromStream(getContent(), Ownership.None);
}
/**
* Gets the possible locations of the parent file (if any).
*
* @return Array of strings, empty if no parent.
*/
public List<String> getParentLocations() {
return Arrays.asList();
}
/**
* Disposes of underlying resources.
*/
public void close() throws IOException {
if (_toDispose != null) {
_toDispose.close();
_toDispose = null;
}
if (getContent() != null) {
getContent().close();
setContent(null);
}
}
}
|
rizkimohamadd/aplikasi-akademik
|
src/main/java/id/ac/tazkia/akademik/aplikasiakademik/dao/PresensiMahasiswaDao.java
|
<reponame>rizkimohamadd/aplikasi-akademik
package id.ac.tazkia.akademik.aplikasiakademik.dao;
import id.ac.tazkia.akademik.aplikasiakademik.dto.RekapMissAttendance;
import id.ac.tazkia.akademik.aplikasiakademik.entity.*;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import java.time.LocalDateTime;
import java.util.List;
public interface PresensiMahasiswaDao extends PagingAndSortingRepository<PresensiMahasiswa, String> {
@Query("select new id.ac.tazkia.akademik.aplikasiakademik.dto.RekapMissAttendance(p.krsDetail.krs.id, p.krsDetail.jadwal.matakuliahKurikulum.matakuliah.namaMatakuliah, count(p)) " +
"from PresensiMahasiswa p where p.krsDetail.krs = :krs and p.status = 'AKTIF' and p.statusPresensi not in ('HADIR') " +
"group by p.krsDetail "+
"order by p.krsDetail.jadwal.matakuliahKurikulum.matakuliah.namaMatakuliah")
List<RekapMissAttendance> rekapMissAttendance(@Param("krs")Krs krs);
@Query("select p from PresensiMahasiswa p where p.waktuMasuk >= :mulai and p.waktuMasuk < :sampai")
Iterable<PresensiMahasiswa> findByTanggal(@Param("mulai") LocalDateTime mulai, @Param("sampai") LocalDateTime sampai);
List<PresensiMahasiswa> findBySesiKuliah(SesiKuliah sesiKuliah);
List<PresensiMahasiswa> findBySesiKuliahAndStatus(SesiKuliah sesiKuliah,StatusRecord statusRecord);
PresensiMahasiswa findByMahasiswaAndSesiKuliahAndStatus(Mahasiswa mahasiswa,SesiKuliah sesiKuliah,StatusRecord statusRecord);
List<PresensiMahasiswa> findByKrsDetailAndStatusAndStatusPresensi(KrsDetail krsDetail, StatusRecord status,StatusPresensi statusPresensi);
List<PresensiMahasiswa> findByKrsDetailJadwalAndStatus(Jadwal jadwal, StatusRecord statusRecord);
}
|
hao-wang/Montage
|
js-test-suite/testsuite/c64e2674ba637178daf0f0175f0643cc.js
|
load("201224b0d1c296b45befd2285e95dd42.js");
// Test that Debugger.Frame.prototype.environment works at all pcs of a script
// with an aliased block scope.
var g = newGlobal();
var dbg = new Debugger(g);
dbg.onDebuggerStatement = function (frame) {
frame.onStep = (function () { frame.environment; });
};
g.eval("debugger; for (let i of [1,2,3]) print(i);");
|
Semestre5/AMT_Projet
|
src/test/java/DbOpsTests/TestCategories.java
|
package DbOpsTests;
import com.DAO.Access.ArticleOps;
import com.DAO.Access.CategoryOps;
import com.DAO.Objects.Article;
import com.DAO.Objects.Category;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
public class TestCategories {
/*
@Test
public void testInsertCat(){
Integer id = 0;
id++;
String name = "Cat"+id;
Category cat = new Category ("Cat "+id);
CategoryOps.addCategory( cat.getName() );
}
*/
@Test
public void testFetchAllCat() {
// List des category
List<Category> cats = CategoryOps.fetchAll();
assertNotNull(cats);
}
@Test
public void testInsertCategoriesToArticle(){
Article art = ArticleOps.fetchOne(2);
System.out.println("Article is :"+art.getName());
Integer id = 7;
Category cat = CategoryOps.fetchOne(id);
art.addCategory(cat);
System.out.println("Article"+art.getName()+"is under"+art.getCategories());
assertNotNull(art);
assertNotNull(cat);
art.removeCategory(cat);
}
@Test
public void testFetchArticleByCategory(){
Category cat = CategoryOps.fetchOne(2);
assertNotNull(cat);
List<?> articles = ArticleOps.fetchAllByCategory(cat);
System.out.println("There is "+articles.size()+" article under this category");
}
}
|
mfleming/cassandra-dtest
|
meta_tests/dtest_config_test.py
|
<reponame>mfleming/cassandra-dtest<filename>meta_tests/dtest_config_test.py
import os
from re import search
from unittest import TestCase
from dtest_config import DTestConfig
from mock import Mock, patch
from pytest import UsageError, raises
import ccmlib.repository
import ccmlib.common
def _mock_responses(responses, default_response=None):
return lambda input: responses[input] if input in responses else \
"%s/meta_tests/cassandra-dir-4.0-beta" % os.getcwd() if input == "--cassandra-dir" else default_response
def _check_with_params(params):
config = Mock()
config.getoption.side_effect = _mock_responses(params)
config.getini.side_effect = _mock_responses({})
dTestConfig = DTestConfig()
dTestConfig.setup(config)
return dTestConfig
def _check_with_params_expect(params, pattern):
with raises(UsageError, match=pattern):
_check_with_params(params)
class DTestConfigTest(TestCase):
def test_invalid_cass_dir_no_version(self):
_check_with_params_expect({
'--cassandra-dir': 'blah'
}, "The Cassandra directory blah does not seem to be valid")
def test_cass_dir_and_version(self):
_check_with_params_expect({
'--cassandra-version': '3.11'
}, "Cassandra build directory is already defined")
def test_no_cass_dir(self):
with patch.object(ccmlib.repository, "setup") as mocked_setup:
mocked_setup.side_effect = _mock_responses({'3.2': ("%s/meta_tests/cassandra-dir-3.2" % os.getcwd(), '3.2.0')})
c = _check_with_params({
'--cassandra-dir': None,
'--cassandra-version': '3.2'
})
assert c.cassandra_version == '3.2'
assert search("^3.2", str(c.cassandra_version_from_build))
def test_valid_cass_dir_no_version(self):
c = _check_with_params({
})
assert c.cassandra_version is None
assert c.cassandra_version_from_build == '4.0-beta'
def test_no_cass_dir_no_version(self):
_check_with_params_expect({
'--cassandra-dir': None
}, "You must provide either --cassandra-dir or --cassandra-version")
def test_illegal_args_combinations_for_resource_intensive_tests(self):
_check_with_params_expect({
'--only-resource-intensive-tests': True,
'--skip-resource-intensive-tests': True
}, 'does not make any sense')
_check_with_params_expect({
'--force-resource-intensive-tests': True,
'--skip-resource-intensive-tests': True
}, 'does not make any sense')
_check_with_params_expect({
'--only-resource-intensive-tests': True,
'--force-resource-intensive-tests': True,
'--skip-resource-intensive-tests': True
}, 'does not make any sense')
def test_legal_args_combinations_for_resource_intensive_tests(self):
c = _check_with_params({
'--only-resource-intensive-tests': True
})
assert c.only_resource_intensive_tests
assert not c.skip_resource_intensive_tests
assert not c.force_execution_of_resource_intensive_tests
c = _check_with_params({
'--only-resource-intensive-tests': True,
'--force-resource-intensive-tests': True
})
assert c.only_resource_intensive_tests
assert not c.skip_resource_intensive_tests
assert c.force_execution_of_resource_intensive_tests
c = _check_with_params({
'--skip-resource-intensive-tests': True
})
assert not c.only_resource_intensive_tests
assert c.skip_resource_intensive_tests
assert not c.force_execution_of_resource_intensive_tests
c = _check_with_params({
})
assert not c.only_resource_intensive_tests
assert not c.skip_resource_intensive_tests
assert not c.force_execution_of_resource_intensive_tests
def off_heap_memtables_not_supported(self):
_check_with_params_expect({
'--cassandra-dir': "%s/meta_tests/cassandra-dir-3.2" % os.getcwd(),
'--use-off-heap-memtables': True
}, "The selected Cassandra version 3.2 doesn't support the provided option")
def off_heap_memtables_supported(self):
c = _check_with_params({
'--use-off-heap-memtables': True
})
assert c.use_off_heap_memtables
|
jmar910/ember-data-github
|
tests/helpers/utils/defined-attribute-assertion-builder.js
|
export default function(keys) {
return function(object, message) {
let allDefined = true;
let undefinedKeys = [];
keys.forEach(key => {
if (object.get(key) === undefined) {
allDefined = false;
undefinedKeys.push(key);
}
});
let realMessage = message || 'Undefined keys';
this.pushResult({
result: allDefined,
actual: allDefined,
expected: true,
message: `${realMessage}: ${undefinedKeys.join(',')}`
});
}
}
|
MilkyBoat/present-for-best-TA
|
src/main/java/com/android/cglib/p008dx/p015c/p017b/C0243l.java
|
package com.android.cglib.p008dx.p015c.p017b;
import bsh.ParserConstants;
import com.android.cglib.p008dx.p020d.C0295i;
/* renamed from: com.android.cglib.dx.c.b.l */
public final class C0243l {
/* renamed from: a */
public static String m1721a(int i) {
switch (i) {
case 1:
return "nop";
case 2:
return "move";
case 3:
return "move-param";
case 4:
return "move-exception";
case 5:
return "const";
case 6:
return "goto";
case 7:
return "if-eq";
case 8:
return "if-ne";
case 9:
return "if-lt";
case 10:
return "if-ge";
case 11:
return "if-le";
case 12:
return "if-gt";
case 13:
return "switch";
case 14:
return "add";
case 15:
return "sub";
case 16:
return "mul";
case 17:
return "div";
case 18:
return "rem";
case 19:
return "neg";
case 20:
return "and";
case 21:
return "or";
case 22:
return "xor";
case 23:
return "shl";
case 24:
return "shr";
case 25:
return "ushr";
case 26:
return "not";
case 27:
return "cmpl";
case 28:
return "cmpg";
case 29:
return "conv";
case 30:
return "to-byte";
case 31:
return "to-char";
case 32:
return "to-short";
case 33:
return "return";
case 34:
return "array-length";
case 35:
return "throw";
case 36:
return "monitor-enter";
case 37:
return "monitor-exit";
case ParserConstants.LONG /*38*/:
return "aget";
case ParserConstants.NATIVE /*39*/:
return "aput";
case ParserConstants.NEW /*40*/:
return "new-instance";
case ParserConstants.NULL /*41*/:
return "new-array";
case ParserConstants.PACKAGE /*42*/:
return "filled-new-array";
case ParserConstants.PRIVATE /*43*/:
return "check-cast";
case ParserConstants.PROTECTED /*44*/:
return "instance-of";
case ParserConstants.PUBLIC /*45*/:
return "get-field";
case 46:
return "get-static";
case 47:
return "put-field";
case 48:
return "put-static";
case 49:
return "invoke-static";
case 50:
return "invoke-virtual";
case 51:
return "invoke-super";
case 52:
return "invoke-direct";
case 53:
return "invoke-interface";
case 55:
return "move-result";
case 56:
return "move-result-pseudo";
case 57:
return "fill-array-data";
default:
StringBuilder sb = new StringBuilder();
sb.append("unknown-");
sb.append(C0295i.m2050e(i));
return sb.toString();
}
}
}
|
KyuBlade/Amazehing
|
core/src/com/omega/amazehing/game/entity/component/ai/path/PathComponent.java
|
package com.omega.amazehing.game.entity.component.ai.path;
import com.badlogic.ashley.core.Component;
import com.badlogic.gdx.utils.Pool.Poolable;
import com.omega.amazehing.game.ai.pathfinding.ConnectionGraphPath;
public class PathComponent implements Component, Poolable {
private ConnectionGraphPath path;
public PathComponent() {
}
public ConnectionGraphPath getPath() {
return path;
}
public PathComponent setPath(ConnectionGraphPath path) {
this.path = path;
return this;
}
@Override
public void reset() {
path = null;
}
}
|
wanglei339/wms-test
|
wms-api/src/main/java/com/lsh/wms/api/service/wave/IWaveService.java
|
<reponame>wanglei339/wms-test
package com.lsh.wms.api.service.wave;
import com.lsh.base.common.exception.BizCheckedException;
import com.lsh.wms.model.wave.WaveRequest;
/**
* Created by zengwenjun on 16/9/6.
*/
public interface IWaveService {
String createAndReleaseWave(WaveRequest request) throws BizCheckedException;
}
|
Mattlk13/vscode-nextgenas
|
check-royale-version/src/main/java/com/as3mxml/vscode/CheckRoyaleVersion.java
|
<gh_stars>0
/*
Copyright 2016-2019 Bowler Hat LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.as3mxml.vscode;
import org.apache.royale.compiler.tree.as.IASNode;
/**
* Checks that the Apache Royale version is compatible with the
* ActionScript/MXML language server.
*/
public class CheckRoyaleVersion
{
public static final int GOOD_VERSION = 0;
public static final int BAD_VERSION = 100;
public static final int EXCEPTION_VERSION = 101;
private static final int MIN_MAJOR = 0;
private static final int MIN_MINOR = 9;
private static final int MIN_REVISION = 6;
public static void main(String[] args)
{
try
{
String sdkVersion = IASNode.class.getPackage().getImplementationVersion();
//remove -SNAPSHOT, if present. then, split on the "." character.
String[] versionParts = sdkVersion.split("-")[0].split("\\.");
int major = 0;
int minor = 0;
int revision = 0;
if (versionParts.length >= 3)
{
major = Integer.parseInt(versionParts[0]);
minor = Integer.parseInt(versionParts[1]);
revision = Integer.parseInt(versionParts[2]);
}
if (major > MIN_MAJOR)
{
//major version is valid
System.exit(GOOD_VERSION);
}
else if (major == MIN_MAJOR)
{
if (minor > MIN_MINOR)
{
//minor version is valid
System.exit(GOOD_VERSION);
}
else if (minor == MIN_MINOR)
{
if (revision >= MIN_REVISION)
{
//revision is valid
System.exit(GOOD_VERSION);
}
}
}
//version is too old!
System.exit(BAD_VERSION);
}
catch(Exception e)
{
System.exit(EXCEPTION_VERSION);
}
}
}
|
ChinaLym/Shoulder-Framework
|
shoulder-build/shoulder-base/shoulder-batch/src/main/java/org/shoulder/batch/repository/JdbcBatchRecordPersistentService.java
|
<filename>shoulder-build/shoulder-base/shoulder-batch/src/main/java/org/shoulder/batch/repository/JdbcBatchRecordPersistentService.java<gh_stars>1-10
package org.shoulder.batch.repository;
import org.shoulder.batch.model.BatchRecord;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import javax.annotation.Nonnull;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
/**
* 批量处理记录mapper
*
* @author lym
*/
public class JdbcBatchRecordPersistentService implements BatchRecordPersistentService {
private static String ALL_COLUMNS = "id, data_type, operation, total_num ,success_num ,fail_num, creator, " +
"create_time";
private static String INSERT = "INSERT INTO batch_record (" + ALL_COLUMNS + ") " +
"VALUES (?,?,?,?,?,?,?,?)";
private static String QUERY_BY_ID = "SELECT " + ALL_COLUMNS + " FROM batch_record where id=?";
private static String QUERY_BY_USER =
"SELECT " + ALL_COLUMNS + " FROM batch_record where data_type=? and creator=?";
private static String QUERY_FIND_ALL = "SELECT " + ALL_COLUMNS +
" FROM batch_record_detail WHERE recordId=?, AND status in (?)";
private final JdbcTemplate jdbc;
private RowMapper<BatchRecord> mapper = new BatchRecordRowMapper();
public JdbcBatchRecordPersistentService(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
public JdbcBatchRecordPersistentService(DataSource dataSource) {
this.jdbc = new JdbcTemplate(dataSource);
}
/**
* 单条插入
*
* @param record 批量处理记录
*/
@Override
public void insert(BatchRecord record) {
jdbc.update(INSERT, flatFieldsToArray(record));
}
private Object[] flatFieldsToArray(BatchRecord batchRecord) {
Object[] fields = new Object[8];
fields[0] = batchRecord.getId();
fields[1] = batchRecord.getDataType();
fields[2] = batchRecord.getOperation();
fields[3] = batchRecord.getTotalNum();
fields[4] = batchRecord.getSuccessNum();
fields[5] = batchRecord.getFailNum();
fields[6] = batchRecord.getCreator();
fields[7] = batchRecord.getCreateTime();
return fields;
}
/**
* 根据 任务标识 获取批处理记录
*
* @param recordId 主键
* @return 记录
*/
@Override
public BatchRecord findById(String recordId) {
return jdbc.queryForObject(QUERY_BY_ID, mapper, recordId);
}
/**
* 根据条件分页查询批处理记录
*
* @param dataType 查询条件
* @param pageNum 查询条件
* @param pageSize 查询条件
* @param currentUserCode 查询条件
* @return 查询结果
*/
@Override
public List<BatchRecord> findByPage(String dataType, Integer pageNum, Integer pageSize,
String currentUserCode) {
return jdbc.queryForList(QUERY_BY_USER + " limit ?,?", BatchRecord.class, dataType, currentUserCode, pageNum - 1,
pageSize);
}
/**
* 根据用户编码查询最近批处理的记录
*
* @return 上次批量处理记录
*/
@Override
public BatchRecord findLast(String dataType, String currentUserCode) {
return jdbc.queryForObject(QUERY_BY_USER + " limit 1", mapper, dataType, currentUserCode);
}
/**
* Row mapper for BatchRecord.
*
* @author lym
*/
private static class BatchRecordRowMapper implements RowMapper<BatchRecord> {
@Override
public BatchRecord mapRow(@Nonnull ResultSet resultSet, int i) throws SQLException {
return BatchRecord.builder()
.id(resultSet.getString(1))
.dataType(resultSet.getString(2))
.operation(resultSet.getString(3))
.totalNum(resultSet.getInt(4))
.successNum(resultSet.getInt(5))
.failNum(resultSet.getInt(6))
.creator(resultSet.getLong(7))
.createTime(resultSet.getDate(8))
.build();
}
}
}
|
carlosraphael/specification-pattern
|
src/test/java/com/github/carlosraphael/specificationpattern/predicate/PredicatesTest.java
|
package com.github.carlosraphael.specificationpattern.predicate;
import com.github.carlosraphael.specificationpattern.entity.Specification;
import com.github.carlosraphael.specificationpattern.entity.SpecificationOperator;
import com.github.carlosraphael.specificationpattern.entity.fieldspecification.FieldOperator;
import com.google.common.collect.ImmutableSet;
import org.junit.Test;
import java.util.Collections;
import java.util.Set;
import java.util.function.Predicate;
import static com.github.carlosraphael.specificationpattern.SampleDataFactory.amountOfFiveHundred;
import static com.github.carlosraphael.specificationpattern.SampleDataFactory.createFieldSpecification;
import static com.github.carlosraphael.specificationpattern.SampleDataFactory.eurCurrency;
import static com.github.carlosraphael.specificationpattern.SampleDataFactory.sourceAmountFieldMapping;
import static com.github.carlosraphael.specificationpattern.SampleDataFactory.sourceCurrencyFieldMapping;
import static java.util.Optional.empty;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
/**
* @author <EMAIL>
*/
public class PredicatesTest {
@Test
public void predicateIsCreatedBasedOnOneSpecification() {
// given
Specification specification = createFieldSpecification(
sourceCurrencyFieldMapping(), FieldOperator.EQUALS, eurCurrency(), SpecificationOperator.AND);
// when
Predicate javaPredicate = Predicates.asPredicate(ImmutableSet.of(specification));
// then
assertThat(javaPredicate, is(notNullValue()));
assertThat(((SpecificationPredicate)javaPredicate).combinedPredicate, is(equalTo(empty())));
}
@Test
public void predicateIsCreatedBasedOnCombinedOfTwoSpecification() {
// given
Specification specificationForSourceCurrency = createFieldSpecification(
sourceCurrencyFieldMapping(), FieldOperator.EQUALS, eurCurrency(), SpecificationOperator.AND);
Specification specificationForSourceAmount = createFieldSpecification(
sourceAmountFieldMapping(), FieldOperator.EQUALS, amountOfFiveHundred(), SpecificationOperator.AND);
// when
Predicate javaPredicate = Predicates.asPredicate(ImmutableSet.of(
specificationForSourceCurrency, specificationForSourceAmount));
// then
assertThat(javaPredicate, is(notNullValue()));
assertThat(((SpecificationPredicate)javaPredicate).combinedPredicate, not(equalTo(empty())));
}
@Test(expected = NullPointerException.class)
public void nullPointerExceptionIsThrownWhenNoSpecificationIsSupplied() {
// given
Set<Specification> nullSpecification = null;
// when
Predicates.asPredicate(nullSpecification);
// then NullPointerException is thrown
}
@Test(expected = IllegalStateException.class)
public void illegalStateExceptionIsThrownWhenEmptySpecificationIsSupplied() {
// given
Set<Specification> emptySpecification = Collections.EMPTY_SET;
// when
Predicates.asPredicate(emptySpecification);
// then NullPointerException is thrown
}
}
|
takashiharano/util
|
java/src/test/java/com/libutil/test/str/StrUtilTest.java
|
package com.libutil.test.str;
import com.libutil.FileUtil;
import com.libutil.StrUtil;
import com.libutil.test.Log;
public class StrUtilTest {
public static void main(String args[]) {
text2arrayTest();
countStrPatternTest();
quoteTest();
intnum2decimalTest();
trimZerosTest();
encodeUriTest();
decodeUriTest();
escapeHtmlTest();
}
private static void text2arrayTest() {
String str = FileUtil.readText("C:/test/a.txt");
String[] arr = StrUtil.text2array(str);
for (int i = 0; i < arr.length; i++) {
Log.d("str=" + arr[i]);
}
}
private static void countStrPatternTest() {
String str = "abc123abc456xyz";
Log.d("bc=" + StrUtil.countStrPattern(str, "bc"));
Log.d("\\d\\d=" + StrUtil.countStrPattern(str, "\\d\\d"));
}
private static void quoteTest() {
Log.d(StrUtil.quote("abc"));
Log.d(StrUtil.quote("a\"b\"c"));
Log.d(StrUtil.quote("a\"b\"c", "\"", "\""));
Log.d(StrUtil.quote("a\"b\"c", "'"));
Log.d(StrUtil.quote("a\"b\"'c", "'"));
}
private static void intnum2decimalTest() {
Log.d("----");
Log.d(StrUtil.intnum2decimal(1000, 3));
Log.d(StrUtil.intnum2decimal(100, 3));
Log.d(StrUtil.intnum2decimal(10, 3));
Log.d(StrUtil.intnum2decimal(1, 3));
Log.d(StrUtil.intnum2decimal(0, 3));
Log.d("----");
Log.d(StrUtil.intnum2decimal(-1000, 3));
Log.d(StrUtil.intnum2decimal(-100, 3));
Log.d(StrUtil.intnum2decimal(-10, 3));
Log.d(StrUtil.intnum2decimal(-1, 3));
Log.d(StrUtil.intnum2decimal(-0, 3));
}
private static void trimZerosTest() {
Log.d("----");
_trimZerosTest("123");
_trimZerosTest("0123");
_trimZerosTest("123.1");
_trimZerosTest("0123.10");
_trimZerosTest("1230");
_trimZerosTest("01230");
_trimZerosTest("-123");
_trimZerosTest("-0123");
_trimZerosTest("-123.1");
_trimZerosTest("-0123.10");
_trimZerosTest("-123.01");
_trimZerosTest("-123.010");
_trimZerosTest("0");
_trimZerosTest("0.0");
_trimZerosTest("-0");
_trimZerosTest("-0.0");
}
private static void _trimZerosTest(String v) {
Log.d(v + ": " + StrUtil.trimZeros(v));
}
private static void encodeUriTest() {
_encodeUriTest("abc");
_encodeUriTest("abc=123");
_encodeUriTest(" &%+-/*=.");
_encodeUriTest("あいう");
}
private static void _encodeUriTest(String s) {
Log.d(s + ": " + StrUtil.encodeUri(s));
}
private static void decodeUriTest() {
_decodeUriTest("abc");
_decodeUriTest("abc%3D123");
_decodeUriTest("+%26%25%2B-%2F*%3D.");
_decodeUriTest("%E3%81%82%E3%81%84%E3%81%86");
}
private static void _decodeUriTest(String s) {
Log.d(s + ": " + StrUtil.decodeUri(s));
}
private static void escapeHtmlTest() {
String str = "&<>\"'";
String escaped = StrUtil.escapeHtml(str);
Log.d(escaped);
}
}
|
WenjieXu/ogs
|
MeshLib/MeshEnums.h
|
<filename>MeshLib/MeshEnums.h
/**
* \file
* \author <NAME>
* \date 2012-05-02
* \brief Definition of mesh-related Enumerations.
*
* \copyright
* Copyright (c) 2013, OpenGeoSys Community (http://www.opengeosys.org)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.org/project/license
*
*/
#ifndef MESHENUMS_H
#define MESHENUMS_H
#include <string>
/**
* \brief Types of mesh elements supported by OpenGeoSys.
*/
enum class MeshElemType
{
INVALID,
LINE,
QUAD,
HEXAHEDRON,
TRIANGLE,
TETRAHEDRON,
PRISM,
PYRAMID
};
/**
* \brief Types of mesh elements supported by OpenGeoSys.
*/
enum class CellType
{
INVALID,
LINE2,
LINE3,
TRI3,
TRI6,
QUAD4,
QUAD8,
QUAD9,
TET4,
TET10,
HEX8,
HEX20,
HEX27,
PRISM6,
PRISM15,
PRISM18,
PYRAMID5
};
/**
* \brief Describes a mesh quality metric.
*/
enum class MeshQualityType
{
INVALID = 0,
AREA,
VOLUME,
EDGERATIO,
EQUIANGLESKEW
};
/// Given a MeshElemType this returns the appropriate string.
const std::string MeshElemType2String(const MeshElemType t);
/// Given a string of the shortened name of the element type, this returns the corresponding MeshElemType.
MeshElemType String2MeshElemType(const std::string &s);
const std::string MeshQualityType2String(const MeshQualityType t);
#endif //MESHENUMS_H
|
geant-multicloud/MCMS-mastermind
|
src/waldur_core/core/signals.py
|
<filename>src/waldur_core/core/signals.py
import django.dispatch
# TODO: Make all the serializers emit this signal
pre_serializer_fields = django.dispatch.Signal(providing_args=['fields'])
# This signal allows to implement deletion validation in dependent
# application without introducing circular dependency
pre_delete_validate = django.dispatch.Signal(providing_args=['instance', 'user'])
|
Grimace1975/bclcontrib-scriptsharp
|
ref.neo/sys/osx/showcursor.c
|
/*
cc -o showcursor showcursor.c -framework IOKit
*/
#include <IOKit/IOKitLib.h>
#include <IOKit/hidsystem/IOHIDShared.h>
#include <assert.h>
mach_port_t masterPort;
io_connect_t OpenEventDriver( void )
{
register kern_return_t kr;
mach_port_t ev, service, iter;
kr = IOServiceGetMatchingServices( masterPort, IOServiceMatching( kIOHIDSystemClass ), &iter);
assert( KERN_SUCCESS == kr);
service = IOIteratorNext( iter );
assert(service);
kr = IOServiceOpen( service, mach_task_self(), kIOHIDParamConnectType, &ev);
assert( KERN_SUCCESS == kr );
IOObjectRelease( service );
IOObjectRelease( iter );
return( ev );
}
void TestParams( io_connect_t ev, boolean_t show )
{
kern_return_t kr;
kr = IOHIDSetCursorEnable( ev, show );
assert(KERN_SUCCESS == kr);
}
int main(int argc, char **argv)
{
kern_return_t kr;
boolean_t show;
if (argc != 2)
show = 1;
else
show = (atoi(argv[0]) != 0);
assert( KERN_SUCCESS == ( kr = IOMasterPort( bootstrap_port, &masterPort) ));
TestParams( OpenEventDriver(), show);
return( 0 );
}
|
stazman/sfsourcer
|
app/models/pledge.rb
|
<gh_stars>0
class Pledge < ApplicationRecord
belongs_to :funding_project
has_many :fp_backer_pledges
has_many :fp_backers, through: :fp_backer_pledges
# has_many :funding_project_pledges
# has_many :funding_projects, through: :funding_project_pledges
# validates_presence_of :amount
# validates :amount, numericality: true
# def funding_project_title=(funding_project_title)
# self.funding_project.title = FundingProject.find_by(title: funding_project_title)
# end
def fp_backer_name
self.try(:fp_backer).try(:name)
end
def fp_backer_name=(name)
fpb = FpBacker.find_or_create_by(name: name)
self.fp_backer = fpb
end
# def funding_project_attributes=(funding_project_attributes)
# funding_project_attributes.values.each do |fp_attribute|
# fp = FundingProject.find(fp_attribute)
# self.funding_projects << fp
# end
# end
end
# def funding_project_name
# self.try(:funding_project).try(:name)
# end
# def fp_backed_name
# self.try(:fp_backed).try(:name)
# end
# # but how does this work from just the parameters??? what mechanism takes what instance through the strong params and how does it do it?
# def fp_backed_name=(name)
# fpb = FpBacked.find_or_create_by(name: name)
# self.fp_backed = fpb
# end
|
KevinHe666/learn-interview
|
learn/src/main/java/com/kevin/learn/learn/jvm/class1/ClassYoung/TestMaxObject.java
|
<filename>learn/src/main/java/com/kevin/learn/learn/jvm/class1/ClassYoung/TestMaxObject.java<gh_stars>1-10
package com.kevin.learn.learn.jvm.class1.ClassYoung;
/**
* @Description: 测试大对象
* @Author: Kevin
* @Create 2019-07-03 11:02
*/
public class TestMaxObject {
public static void main(String[] args) {
//10M的大对象 直接在老年代分配 1M老年代没分配
byte[] bytes = new byte[1024 * 1024 * 10];
}
}
|
ashariati/gtsam-3.2.1
|
doc/html/a00083.js
|
<gh_stars>10-100
var a00083 =
[
[ "EssentialMatrixFactor", "a00083.html#a9edbb5ac88824e6c9e87b5b979e5b5a5", null ],
[ "EssentialMatrixFactor", "a00083.html#ae683f489d5cfad2f4ea6a9840820808c", null ],
[ "clone", "a00083.html#ac0c66faf7d8a3ac8e16fc35f09689d9a", null ],
[ "evaluateError", "a00083.html#a74623d11b896657a1ad3454480d2ae99", null ],
[ "print", "a00083.html#a746727a5e43f0adf31c3dcdfb12ee49f", null ]
];
|
Aaron1011/travis-core
|
spec/travis/features_spec.rb
|
require 'spec_helper'
describe Travis::Features do
before do
Travis.instance_variable_set(:@config, nil)
end
it "should delegate to rollout" do
expect { Travis::Features.info(:short_urls) }.to_not raise_error
end
describe "feature checks" do
include Support::ActiveRecord
before do
Travis::Features.activate_all(:feature)
end
after do
Travis::Features.deactivate_user(:feature, user)
Travis::Features.deactivate_repository(:feature, repository)
Travis::Features.deactivate_all(:feature)
end
let(:repository) {Factory(:repository)}
let!(:user) {Factory(:user)}
let(:organization) {Factory(:org)}
it "should return true if the repository's owner is activated" do
expect {
Travis::Features.activate_user(:feature, user)
}.to change {Travis::Features.active?(:feature, repository)}
end
it "should return false if the repository's owner isn't activated" do
Travis::Features.active?(:feature, repository).should == false
end
it "should allow enabling the repository" do
Travis::Features.activate_repository(:feature, repository)
end
it "should be active when the repository was activated" do
expect {
Travis::Features.activate_repository(:feature, repository)
}.to change {Travis::Features.active?(:feature, repository)}
end
it "shouldn't be active when the repository was deactivated" do
Travis::Features.activate_repository(:feature, repository)
expect {
Travis::Features.deactivate_repository(:feature, repository)
}.to change {Travis::Features.active?(:feature, repository)}
end
describe "for users" do
it "should be active when enabled for a user" do
Travis::Features.activate_user(:feature, user)
Travis::Features.user_active?(:feature, user).should == true
end
it "shouldn't be active when disable for a user" do
Travis::Features.deactivate_user(:feature, user)
Travis::Features.user_active?(:feature, user).should == false
end
end
describe "for features" do
it "should allow enabling features completely" do
Travis::Features.enable_for_all(:feature)
Travis::Features.active?(:feature, repository).should == true
end
it "shouldn't be active when the feature was disabled completely" do
Travis::Features.enable_for_all(:feature)
expect {
Travis::Features.disable_for_all(:feature)
}.to change {
Travis::Features.active?(:feature, repository)
}
end
end
describe "for owners" do
it "allows enabling features for an owner" do
Travis::Features.activate_owner(:feature, repository.owner)
Travis::Features.owner_active?(:feature, repository.owner).should == true
end
it "allows disabling features for an owner" do
Travis::Features.activate_owner(:feature, repository.owner)
Travis::Features.owner_active?(:feature, repository.owner).should == true
Travis::Features.deactivate_owner(:feature, repository.owner)
Travis::Features.owner_active?(:feature, repository.owner).should == false
end
it "allows enabling features for an organization" do
Travis::Features.activate_owner(:feature, organization)
Travis::Features.owner_active?(:feature, organization).should == true
end
end
end
end
|
Tikubonn/nanafy
|
test/nanafy/nanafy-symbol/src/test-nanafy-symbol.h
|
extern void test_nanafy_symbol ();
|
huluobo11/demo-collection
|
firstboot01/src/main/java/com/hu/service/impl/MenusServiceImpl.java
|
package com.hu.service.impl;
import com.hu.dao.MenusRepository;
import com.hu.pojo.Menus;
import com.hu.service.MenusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
@Service
public class MenusServiceImpl implements MenusService {
@Resource
private JdbcTemplate jdbcTemplate;
@Autowired
private MenusRepository menusRepository;
@Override
public void save(Menus menus) {
menusRepository.save(menus);
}
@Override
public List<Menus> getFirst(int parentId) {
return menusRepository.getFirst(parentId);
}
@Override
public List<Menus> getSecond(int parentId) {
return menusRepository.getSecond(parentId,parentId+"");
}
@Override
public List<Menus> getThird(int parentId) {
Optional<Menus> optional = menusRepository.findById(parentId);
Menus menus = null;
if (optional.isPresent()) {
menus =optional.get();
}
int parentId1 = menus.getParentId();
String level = parentId1 + "" + parentId;
return menusRepository.getThird(parentId, level);
}
}
|
nippur72/basicv2
|
src/main/java/com/sixtyfour/Assembler.java
|
<filename>src/main/java/com/sixtyfour/Assembler.java
package com.sixtyfour;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.sixtyfour.config.CompilerConfig;
import com.sixtyfour.elements.mnemonics.Mnemonic;
import com.sixtyfour.parser.assembly.AssemblyParser;
import com.sixtyfour.parser.assembly.ConstantValue;
import com.sixtyfour.parser.assembly.ConstantsContainer;
import com.sixtyfour.parser.assembly.LabelAndCode;
import com.sixtyfour.parser.assembly.LabelsContainer;
import com.sixtyfour.system.Cpu;
import com.sixtyfour.system.Machine;
import com.sixtyfour.system.Program;
import com.sixtyfour.system.ProgramPart;
import com.sixtyfour.util.MemoryException;
import com.sixtyfour.util.VarUtils;
/**
* Assembler is for parsing/compiling and executing 6502 assembler programs. The
* program will be compiled into actual 6502 binary code. When running it, it
* will be copied into the machines 64kb of memory and executed from there by
* using a 6502 emulation layer.
*
* @author EgonOlsen
*/
public class Assembler implements ProgramExecutor {
private String[] code = null;
private int codeStart = -1;
private int startAddr = 0;
private Machine machine = null;
private Program program = null;
private boolean running = false;
private Map<Integer, String> addr2code = new HashMap<Integer, String>();
/**
* Instantiates a new compiler for an assembler program. No
* interpretation/compilation will take place at this stage.
*
* @param code
* the assembler code
*/
public Assembler(String code) {
this(code.split("\n"));
}
/**
* Instantiates a new compiler for an assembler program. No
* interpretation/compilation will take place at this stage. This
* constructor takes an array of code lines as input. Each code line should
* represent a line in the assembler program.
*
* @param code
* the assembler code
*/
public Assembler(String[] code) {
this(code, null);
}
/**
* Instantiates a new compiler for an assembler program. No
* interpretation/compilation will take place at this stage. This
* constructor takes an list of code lines as input. Each code line should
* represent a line in the assembler program.
*
* @param code
* the assembler code
*/
public Assembler(List<String> code) {
this(code.toArray(new String[code.size()]), null);
}
/**
* Instantiates a new compiler for an assembler program. No
* interpretation/compilation will take place at this stage.
*
* @param code
* the assembler code
* @param machine
* the machine instance that should be used to run the code. If
* null is given, a new one will be created.
*/
public Assembler(String code, Machine machine) {
this(code.split("\n"), machine);
}
/**
* Instantiates a new compiler for an assembler program. No
* interpretation/compilation will take place at this stage. This
* constructor takes an array of code lines as input. Each code line should
* represent a line in the assembler program.
*
* @param code
* the assembler code
* @param machine
* the machine instance that should be used to run the code. If
* null is given, a new one will be created.
*/
public Assembler(String[] code, Machine machine) {
this.code = Arrays.copyOf(code, code.length);
if (machine == null) {
this.machine = new Machine();
} else {
this.machine = machine;
}
}
/**
* Compiles the code. This can be called before calling the actual run
* method to precompile the code. It doesn't have to though, because run()
* will call it on its own if needed. After compilation, the compiled
* program can be obtained via getProgram(); The compiled Program instance
* has a starting address set that is based on the first block of actual
* opcodes in the assembler listing. If this assumption isn't true for a
* particular program, you have to set the value manually before executing
* the actual program.
*/
@Override
public void compile(CompilerConfig config) {
Logger.log("Running assembler...");
Machine compileMachine = new Machine();
ConstantsContainer ccon = new ConstantsContainer();
LabelsContainer lcon = new LabelsContainer(compileMachine);
int addr = 0;
int cnt = 0;
long startTime = System.nanoTime();
List<Integer> lineBreaks = new ArrayList<Integer>();
Program prg = new Program();
prg.setLabelsContainer(lcon);
boolean initial = true;
Set<Integer> usedAddrs = new HashSet<>();
for (String line : code) {
String oLine = line;
cnt++;
line = line.replace('\t', ' ').trim();
if (line.startsWith(";")) {
// Ignore comment lines
continue;
}
line = AssemblyParser.truncateComments(line);
if (line.length() == 0) {
continue;
}
ConstantValue cv = AssemblyParser.getConstant(config, line, ccon);
if (cv != null) {
ccon.put(cv);
if (cv.getName().equals("*")) {
if (initial) {
initial = false;
} else {
ProgramPart part = new ProgramPart();
part.setAddress(startAddr);
part.setEndAddress(addr);
part.setLineAddresses(createAndResetOpas(lineBreaks));
prg.addPart(part);
}
addr = cv.getValue();
startAddr = addr;
}
continue;
}
boolean isData = line.startsWith(".");
if (!isData) {
Mnemonic mne = AssemblyParser.getMnemonic(line);
if (mne == null) {
LabelAndCode lac = AssemblyParser.getLabel(line);
if (lac != null) {
if (lac.getCode().startsWith(".")) {
isData = true;
} else {
mne = AssemblyParser.getMnemonic(lac.getCode());
}
lcon.put(lac.getLabel(), addr);
line = lac.getCode();
} else {
raiseError("Syntax error at: " + oLine + "/" + addr, addr, cnt);
}
}
if (!isData) {
if (mne != null) {
if (codeStart == -1) {
codeStart = addr;
}
try {
lineBreaks.add(addr);
addr2code.put(addr, line);
int oldAddr = addr;
addr = mne.parse(config, line, addr, compileMachine, ccon, lcon);
flagAddress(usedAddrs, oldAddr, addr);
} catch (RuntimeException re) {
raiseError("Error at line: " + oLine, re, addr, cnt);
}
} else {
if (!line.trim().isEmpty()) {
raiseError("Unknown mnemonic in: " + oLine, addr, cnt);
}
}
}
}
if (isData) {
String lineUpper = VarUtils.toUpper(line.trim());
int[] data = AssemblyParser.getBinaryData(config, addr, line, ccon, lcon);
lineBreaks.add(addr);
System.arraycopy(data, 0, compileMachine.getRam(), addr, data.length);
if (lineUpper.startsWith(".STRG")) {
// If it's a string, the length might have changed due to
// place holder conversions to control codes. So we set the
// actual length here.
compileMachine.getRam()[addr - 1] = data.length;
}
int oldAddr = addr;
addr += data.length;
flagAddress(usedAddrs, oldAddr, addr);
}
}
if (lcon.hasDelayedLabels()) {
raiseError("Undefined label: " + lcon.getFirstDelayedLabel(), addr, cnt);
}
if (addr != startAddr) {
ProgramPart part = new ProgramPart();
part.setAddress(startAddr);
part.setEndAddress(addr);
part.setLineAddresses(createAndResetOpas(lineBreaks));
prg.addPart(part);
}
for (ProgramPart part : prg.getParts()) {
part.setBytes(Arrays.copyOfRange(compileMachine.getRam(), part.getAddress(), part.getEndAddress()));
}
prg.setCodeStart(codeStart == -1 ? startAddr : codeStart);
program = prg;
for (int i = 0; i < prg.getParts().size(); i++) {
ProgramPart pp = prg.getParts().get(i);
String start = getHex(pp.getAddress());
String end = getHex(pp.getEndAddress());
Logger.log("Part " + i + ": " + start + " - " + end);
}
Logger.log(cnt + " lines compiled in: " + (System.nanoTime() - startTime) / 1000000L + "ms");
}
/**
* Runs the program. This will also compile it if needed (i.e. if it hasn't
* been done before), unpause and reset the cpu and execute the program in a
* 6502 emulation.
*/
@Override
public void run(CompilerConfig config) {
if (program == null) {
compile(config);
}
Cpu cpu = machine.getCpu();
cpu.setPaused(false);
cpu.reset();
running = true;
cpu.execute(program);
running = false;
}
/**
* Similar to run(), but the program won't be compiled automatically and the
* cpu won't be reset.
*/
@Override
public void start(CompilerConfig config) {
if (program == null) {
throw new RuntimeException("Program hasn't been compiled!");
}
Cpu cpu = machine.getCpu();
cpu.setPaused(false);
running = true;
cpu.execute(program);
running = false;
}
/**
* Gets the machine.
*
* @return the machine
*/
@Override
public Machine getMachine() {
return machine;
}
/**
* Gets the machine's cpu. This cpu is used to execute machine language
* code. It's a 6502 emulation. If you want to add tracing or get more
* options/details, this is the place to go.
*
* @return
*/
@Override
public Cpu getCpu() {
return machine.getCpu();
}
/**
* Returns the RAM's content. The RAM is a representation of 64KB of 8bit
* wide memory. However, the returned array is of type int[]. It will
* contains values in the range of[0..255] only though.
*
* @return the RAM
*/
@Override
public int[] getRam() {
return machine.getRam();
}
/**
* Stops a currently running program after the next commands has been
* executed.
*/
@Override
public void runStop() {
machine.getCpu().stop();
}
/**
* Gets the compiled program. If compile() hasn't been called yet, null will
* be returned.
*
* @return the program or null
*/
public Program getProgram() {
return program;
}
/**
* Returns the code line associated to an address.
*
* @param addr
* the address
* @return the code line or null if none could be found
*/
public String getCodeLine(int addr) {
return addr2code.get(addr);
}
/**
* Sets a new program. Actually, there's no need to call this method in
* normal code.
*
* @param program
* the new program
*/
public void setProgram(Program program) {
this.program = program;
}
/**
* Dumps the compiled program into a kind of monitor view. If the program
* hasn't been compiled yet, an empty string will be returned.
*/
@Override
public String toString() {
if (program == null) {
return "";
}
Program prg = program;
StringBuilder sb = new StringBuilder();
int cnt = 1;
for (ProgramPart part : prg.getParts()) {
if (sb.length() > 0) {
sb.append("\n");
}
sb.append("Part: " + cnt++);
int start = part.getAddress();
int lineIndex = 0;
for (int i = start; i < start + part.getBytes().length; i++) {
if (lineIndex < part.getLineAddresses().length && i == part.getLineAddresses()[lineIndex]) {
lineIndex++;
sb.append("\n");
sb.append("." + Integer.toString(i, 16));
sb.append("\t");
}
int val = AssemblyParser.getLowByte(part.getBytes()[i - start]);
String num = Integer.toString(val, 16);
if (num.length() == 1) {
num = "0" + num;
}
sb.append(num).append(" ");
}
}
return sb.toString();
}
private int[] createAndResetOpas(List<Integer> lineBreaks) {
int[] opas = new int[lineBreaks.size()];
int c = 0;
for (Integer i : lineBreaks) {
opas[c++] = i;
}
lineBreaks.clear();
return opas;
}
private void raiseError(String txt, Throwable t, int addr, int cnt) {
throw new RuntimeException("Line " + cnt + "\t." + Integer.toHexString(addr) + "\t" + txt, t);
}
private void raiseError(String txt, int addr, int cnt) {
throw new RuntimeException("Line " + cnt + "\t." + Integer.toHexString(addr) + "\t" + txt);
}
private String getHex(int inty) {
String p = Integer.toHexString(inty);
if (p.length() < 4) {
p = "000".substring(0, 4 - p.length()) + p;
}
return "$" + p;
}
private void flagAddress(Set<Integer> used, int start, int endExcl) {
for (int i = start; i < endExcl; i++) {
if (used.contains(i)) {
throw new MemoryException("Overlapping memory addresses @ $" + Integer.toHexString(i));
}
used.add(i);
}
}
@Override
public boolean isRunning() {
return running;
}
}
|
tophatmonocle/dd-trace-py
|
ddtrace/utils/formats.py
|
<reponame>tophatmonocle/dd-trace-py<gh_stars>0
import os
from .deprecation import deprecation
def get_env(integration, variable, default=None):
"""Retrieves environment variables value for the given integration. It must be used
for consistency between integrations. The implementation is backward compatible
with legacy nomenclature:
* `DATADOG_` is a legacy prefix with lower priority
* `DD_` environment variables have the highest priority
* the environment variable is built concatenating `integration` and `variable`
arguments
* return `default` otherwise
"""
key = '{}_{}'.format(integration, variable).upper()
legacy_env = 'DATADOG_{}'.format(key)
env = 'DD_{}'.format(key)
value = os.getenv(env)
legacy = os.getenv(legacy_env)
if legacy:
# Deprecation: `DATADOG_` variables are deprecated
deprecation(
name='DATADOG_',
message='Use `DD_` prefix instead',
version='1.0.0',
)
value = value or legacy
return value if value else default
def deep_getattr(obj, attr_string, default=None):
"""
Returns the attribute of `obj` at the dotted path given by `attr_string`
If no such attribute is reachable, returns `default`
>>> deep_getattr(cass, "cluster")
<cassandra.cluster.Cluster object at 0xa20c350
>>> deep_getattr(cass, "cluster.metadata.partitioner")
u'org.apache.cassandra.dht.Murmur3Partitioner'
>>> deep_getattr(cass, "i.dont.exist", default="default")
'default'
"""
attrs = attr_string.split('.')
for attr in attrs:
try:
obj = getattr(obj, attr)
except AttributeError:
return default
return obj
def asbool(value):
"""Convert the given String to a boolean object. Accepted
values are `True` and `1`."""
if value is None:
return False
if isinstance(value, bool):
return value
return value.lower() in ("true", "1")
|
WonderingBug/presto
|
presto-cache/src/main/java/com/facebook/presto/cache/alluxio/AlluxioCachingClientFileSystem.java
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.cache.alluxio;
import alluxio.AlluxioURI;
import alluxio.client.file.FileInStream;
import alluxio.client.file.FileOutStream;
import alluxio.client.file.URIStatus;
import alluxio.conf.AlluxioConfiguration;
import alluxio.grpc.CreateDirectoryPOptions;
import alluxio.grpc.CreateFilePOptions;
import alluxio.grpc.DeletePOptions;
import alluxio.grpc.ExistsPOptions;
import alluxio.grpc.FreePOptions;
import alluxio.grpc.GetStatusPOptions;
import alluxio.grpc.ListStatusPOptions;
import alluxio.grpc.MountPOptions;
import alluxio.grpc.OpenFilePOptions;
import alluxio.grpc.RenamePOptions;
import alluxio.grpc.ScheduleAsyncPersistencePOptions;
import alluxio.grpc.SetAclAction;
import alluxio.grpc.SetAclPOptions;
import alluxio.grpc.SetAttributePOptions;
import alluxio.grpc.UnmountPOptions;
import alluxio.security.authorization.AclEntry;
import alluxio.security.authorization.Mode;
import alluxio.wire.BlockLocationInfo;
import alluxio.wire.FileInfo;
import alluxio.wire.MountPointInfo;
import alluxio.wire.SyncPointInfo;
import com.facebook.presto.hive.HiveFileContext;
import com.facebook.presto.hive.filesystem.ExtendedFileSystem;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.hash.Hashing.md5;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Objects.requireNonNull;
public class AlluxioCachingClientFileSystem
implements alluxio.client.file.FileSystem
{
private final AlluxioConfiguration alluxioConfiguration;
private final ExtendedFileSystem fileSystem;
public AlluxioCachingClientFileSystem(
ExtendedFileSystem fileSystem,
AlluxioConfiguration alluxioConfiguration)
{
this.fileSystem = requireNonNull(fileSystem, "fileSystem is null");
this.alluxioConfiguration = requireNonNull(alluxioConfiguration, "alluxioConfiguration is null");
}
@Override
public void createDirectory(AlluxioURI alluxioURI, CreateDirectoryPOptions options)
throws IOException
{
FsPermission permission = new FsPermission(Mode.fromProto(options.getMode()).toShort());
fileSystem.mkdirs(toPath(alluxioURI), permission);
}
@Override
public FileInStream openFile(AlluxioURI alluxioURI, OpenFilePOptions options)
throws IOException
{
return new AlluxioCachingInputStream(fileSystem.open(toPath(alluxioURI)));
}
@Override
public FileInStream openFile(URIStatus uriStatus, OpenFilePOptions options)
throws IOException
{
// URIStatus is the mechanism to pass the hiveFileContext to the source filesystem
// hiveFileContext is critical to use to open file.
checkState(uriStatus instanceof AlluxioURIStatus);
HiveFileContext hiveFileContext = ((AlluxioURIStatus) uriStatus).getHiveFileContext();
try {
return new AlluxioCachingInputStream(fileSystem.openFile(new Path(uriStatus.getPath()), hiveFileContext));
}
catch (Exception e) {
throw new IOException("Failed to open file", e);
}
}
@Override
public FileOutStream createFile(AlluxioURI alluxioURI, CreateFilePOptions options)
{
throw new UnsupportedOperationException("CreateFile operation is not supported");
}
@Override
public void delete(AlluxioURI alluxioURI, DeletePOptions options)
{
throw new UnsupportedOperationException("Delete operation is not supported");
}
@Override
public boolean exists(AlluxioURI alluxioURI, ExistsPOptions options)
{
throw new UnsupportedOperationException("Exists operation is not supported");
}
@Override
public AlluxioConfiguration getConf()
{
return alluxioConfiguration;
}
@Override
public URIStatus getStatus(AlluxioURI alluxioURI, GetStatusPOptions options)
throws IOException
{
return toUriStatus(fileSystem.getFileStatus(toPath(alluxioURI)));
}
@Override
public List<URIStatus> listStatus(AlluxioURI alluxioURI, ListStatusPOptions options)
throws IOException
{
return Arrays.stream(fileSystem.listStatus(toPath(alluxioURI))).map(this::toUriStatus).collect(Collectors.toList());
}
@Override
public boolean isClosed()
{
throw new UnsupportedOperationException("isClosed is not supported");
}
@Override
public void free(AlluxioURI alluxioURI, FreePOptions options)
{
throw new UnsupportedOperationException("Free is not supported.");
}
@Override
public List<BlockLocationInfo> getBlockLocations(AlluxioURI alluxioURI)
{
throw new UnsupportedOperationException("GetBlockLocations is not supported.");
}
@Override
public void mount(AlluxioURI alluxioURI1, AlluxioURI alluxioURI2, MountPOptions options)
{
throw new UnsupportedOperationException("Mount is not supported.");
}
@Override
public void updateMount(AlluxioURI alluxioURI, MountPOptions options)
{
throw new UnsupportedOperationException("UpdateMount is not supported.");
}
@Override
public Map<String, MountPointInfo> getMountTable()
{
throw new UnsupportedOperationException("GetMountTable is not supported.");
}
@Override
public List<SyncPointInfo> getSyncPathList()
{
throw new UnsupportedOperationException("GetSyncPathList is not supported.");
}
@Override
public void persist(AlluxioURI alluxioURI, ScheduleAsyncPersistencePOptions options)
{
throw new UnsupportedOperationException("Persist is not supported.");
}
@Override
public void rename(AlluxioURI source, AlluxioURI destination, RenamePOptions options)
{
throw new UnsupportedOperationException("ReverseResolve is not supported.");
}
@Override
public AlluxioURI reverseResolve(AlluxioURI alluxioURI)
{
throw new UnsupportedOperationException("ReverseResolve is not supported.");
}
@Override
public void setAcl(AlluxioURI alluxioURI, SetAclAction action, List<AclEntry> entries, SetAclPOptions options)
{
throw new UnsupportedOperationException("SetAcl is not supported.");
}
@Override
public void startSync(AlluxioURI alluxioURI)
{
throw new UnsupportedOperationException("StartSync is not supported.");
}
@Override
public void stopSync(AlluxioURI alluxioURI)
{
throw new UnsupportedOperationException("StopSync is not supported.");
}
@Override
public void setAttribute(AlluxioURI alluxioURI, SetAttributePOptions options)
{
throw new UnsupportedOperationException("SetAttribute is not supported.");
}
@Override
public void unmount(AlluxioURI alluxioURI, UnmountPOptions options)
{
throw new UnsupportedOperationException("unmount is not supported.");
}
@Override
public void close()
throws IOException
{
fileSystem.close();
}
private Path toPath(AlluxioURI alluxioURI)
{
return new Path(alluxioURI.toString());
}
private URIStatus toUriStatus(FileStatus status)
{
//FilePath is a unique identifier for a file, however it can be a long string
//hence using md5 hash of the file path as the identifier in the cache.
FileInfo info = new FileInfo();
info.setFileIdentifier(md5().hashString(status.getPath().toString(), UTF_8).toString());
info.setLength(status.getLen()).setPath(status.getPath().toString());
info.setFolder(status.isDirectory()).setBlockSizeBytes(status.getBlockSize());
info.setLastModificationTimeMs(status.getModificationTime()).setLastAccessTimeMs(status.getAccessTime());
info.setOwner(status.getOwner()).setGroup(status.getGroup());
return new URIStatus(info);
}
}
|
ITUROBLAB/-itu_odv_ws-idincern-
|
Arduino Libraries/libraries/ros_lib/waypoints/waypoint_group.h
|
<filename>Arduino Libraries/libraries/ros_lib/waypoints/waypoint_group.h
#ifndef _ROS_waypoints_waypoint_group_h
#define _ROS_waypoints_waypoint_group_h
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include "ros/msg.h"
namespace waypoints
{
class waypoint_group : public ros::Msg
{
public:
typedef const char* _name_type;
_name_type name;
uint32_t wp_list_length;
typedef char* _wp_list_type;
_wp_list_type st_wp_list;
_wp_list_type * wp_list;
waypoint_group():
name(""),
wp_list_length(0), wp_list(NULL)
{
}
virtual int serialize(unsigned char *outbuffer) const
{
int offset = 0;
uint32_t length_name = strlen(this->name);
varToArr(outbuffer + offset, length_name);
offset += 4;
memcpy(outbuffer + offset, this->name, length_name);
offset += length_name;
*(outbuffer + offset + 0) = (this->wp_list_length >> (8 * 0)) & 0xFF;
*(outbuffer + offset + 1) = (this->wp_list_length >> (8 * 1)) & 0xFF;
*(outbuffer + offset + 2) = (this->wp_list_length >> (8 * 2)) & 0xFF;
*(outbuffer + offset + 3) = (this->wp_list_length >> (8 * 3)) & 0xFF;
offset += sizeof(this->wp_list_length);
for( uint32_t i = 0; i < wp_list_length; i++){
uint32_t length_wp_listi = strlen(this->wp_list[i]);
varToArr(outbuffer + offset, length_wp_listi);
offset += 4;
memcpy(outbuffer + offset, this->wp_list[i], length_wp_listi);
offset += length_wp_listi;
}
return offset;
}
virtual int deserialize(unsigned char *inbuffer)
{
int offset = 0;
uint32_t length_name;
arrToVar(length_name, (inbuffer + offset));
offset += 4;
for(unsigned int k= offset; k< offset+length_name; ++k){
inbuffer[k-1]=inbuffer[k];
}
inbuffer[offset+length_name-1]=0;
this->name = (char *)(inbuffer + offset-1);
offset += length_name;
uint32_t wp_list_lengthT = ((uint32_t) (*(inbuffer + offset)));
wp_list_lengthT |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1);
wp_list_lengthT |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2);
wp_list_lengthT |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3);
offset += sizeof(this->wp_list_length);
if(wp_list_lengthT > wp_list_length)
this->wp_list = (char**)realloc(this->wp_list, wp_list_lengthT * sizeof(char*));
wp_list_length = wp_list_lengthT;
for( uint32_t i = 0; i < wp_list_length; i++){
uint32_t length_st_wp_list;
arrToVar(length_st_wp_list, (inbuffer + offset));
offset += 4;
for(unsigned int k= offset; k< offset+length_st_wp_list; ++k){
inbuffer[k-1]=inbuffer[k];
}
inbuffer[offset+length_st_wp_list-1]=0;
this->st_wp_list = (char *)(inbuffer + offset-1);
offset += length_st_wp_list;
memcpy( &(this->wp_list[i]), &(this->st_wp_list), sizeof(char*));
}
return offset;
}
const char * getType(){ return "waypoints/waypoint_group"; };
const char * getMD5(){ return "c03d3488d6139e5ffcdaeff205e40b93"; };
};
}
#endif
|
justinctlam/MarbleStrike
|
game/code/common/engine/system/fixedstring.hpp
|
#ifndef FIXED_STRING_HPP
#define FIXED_STRING_HPP
//////////////////////////////////////////////////////
// INCLUDES
//////////////////////////////////////////////////////
#include <string.h>
#include "common/engine/system/fixedstring.hpp"
#include "common/engine/system/memory.hpp"
#include "common/engine/system/assert.hpp"
#include "common/engine/system/stringutilities.hpp"
#include "common/engine/system/systemdefines.hpp"
//////////////////////////////////////////////////////
// CLASSES
//////////////////////////////////////////////////////
namespace System
{
template <unsigned length>
class FixedString
{
public:
FixedString();
~FixedString();
FixedString( const char* text );
FixedString( const FixedString& otherString );
FixedString& operator=( const char* text );
FixedString& operator=( const FixedString& otherString );
FixedString& operator+=( const char* text );
FixedString& operator+=( const FixedString& otherString );
bool operator==( const char* text ) const;
bool operator==( const FixedString& otherString ) const;
char operator[]( const int index ) const;
char& operator[]( const int index );
operator char*();
operator const char*() const;
int SetSize( int size );
int GetSize() const;
bool Replace( const char* match, const char* str );
void ReplaceAll( const char* match, const char* str );
const char* GetRawData() const
{
return mData;
}
private:
void Copy( const FixedString& otherString );
void Clean();
char mData[length];
int mNumCharacters;
};
template <unsigned length>
FixedString<length>::FixedString()
: mNumCharacters( 1 )
{
mData[0] = '\0';
}
//===========================================================================
template <unsigned length>
FixedString<length>::FixedString( const char* text )
: mNumCharacters( 1 )
{
int stringLength = static_cast<int>( strlen( text ) );
mNumCharacters = stringLength + 1;
Assert( mNumCharacters < length, "" );
System::StringCopy( mData, mNumCharacters, text );
}
//===========================================================================
template <unsigned length>
FixedString<length>::FixedString( const FixedString &otherString )
: mNumCharacters( 1 )
{
Copy( otherString );
}
//===========================================================================
template <unsigned length>
FixedString<length>::~FixedString()
{
Clean();
}
//===========================================================================
template <unsigned length>
FixedString<length>& FixedString<length>::operator= ( const FixedString &otherString )
{
//
// Check for self assignment
//
if ( this != &otherString )
{
Copy( otherString );
}
return *this;
}
//===========================================================================
template <unsigned length>
FixedString<length>& FixedString<length>::operator= ( const char* text )
{
int stringLength = static_cast<int>( strlen( text ) );
//
// Make sure that the current string data is not the same as the text data
//
if ( mData == text )
{
Assert( mData != text, "Self Assignment" );
}
Clean();
mNumCharacters = stringLength + 1;
Assert( mNumCharacters < length, "" );
System::StringCopy( mData, mNumCharacters, text );
return *this;
}
//===========================================================================
template <unsigned length>
FixedString<length>& FixedString<length>::operator+= ( const char* text )
{
int stringLength = static_cast<int>( strlen( text ) );
mNumCharacters += stringLength;
Assert( mNumCharacters < length, "" );
System::StringConcat( mData, mNumCharacters, text );
return *this;
}
//===========================================================================
template <unsigned length>
FixedString<length>& FixedString<length>::operator+= ( const FixedString& otherString )
{
int stringLength = otherString.GetSize();
mNumCharacters += stringLength;
Assert( mNumCharacters < length, "" );
System::StringConcat( mData, mNumCharacters, otherString );
return *this;
}
//===========================================================================
template <unsigned length>
bool FixedString<length>::operator==( const char* text ) const
{
if ( strcmp( mData, text ) == 0 )
{
return true;
}
else
{
return false;
}
}
//===========================================================================
template <unsigned length>
bool FixedString<length>::operator==( const FixedString<length>& otherString ) const
{
if ( strcmp( mData, otherString ) == 0 )
{
return true;
}
else
{
return false;
}
}
//===========================================================================
template <unsigned length>
char FixedString<length>::operator[]( const int index ) const
{
return mData[index];
}
//===========================================================================
template <unsigned length>
char& FixedString<length>::operator[]( const int index )
{
return mData[index];
}
//===========================================================================
template <unsigned length>
FixedString<length>::operator char*()
{
return mData;
}
//===========================================================================
template <unsigned length>
FixedString<length>::operator const char*() const
{
return mData;
}
//===========================================================================
template <unsigned length>
void FixedString<length>::Copy( const FixedString &otherString )
{
Clean();
mNumCharacters = otherString.mNumCharacters;
Assert( mNumCharacters < length, "" );
System::StringCopy( mData, otherString.GetSize() + 1, otherString );
}
//===========================================================================
template <unsigned length>
void FixedString<length>::Clean()
{
mNumCharacters = 1;
mData[0] = '\0';
}
//===========================================================================
template <unsigned length>
int FixedString<length>::GetSize() const
{
return mNumCharacters - 1;
}
//===========================================================================
template <unsigned length>
bool FixedString<length>::Replace( const char* match, const char* str )
{
char* indexChar = 0;
indexChar = strstr( mData, match );
if ( indexChar )
{
int index = static_cast<int>( indexChar - mData );
char newString[256];
int dataLength = static_cast<int>( strlen( mData ) );
UNUSED_ALWAYS( dataLength );
Assert( ( dataLength + 1 ) < 256, "" );
int strLength = static_cast<int>( strlen( str ) );
UNUSED_ALWAYS( strLength );
Assert( ( strLength + 1 ) < 256, "" );
System::StringNCopy( newString, 256, mData, index );
newString[index] = '\0';
System::StringConcat( newString, 256, str );
int matchLength = static_cast<int>( strlen( match ) );
System::StringConcat( newString, 256, &mData[index + matchLength] );
*this = newString;
return true;
}
else
{
return false;
}
}
//===========================================================================
template <unsigned length>
void FixedString<length>::ReplaceAll( const char* match, const char* str )
{
bool replaceSuccess = false;
do
{
replaceSuccess = Replace( match, str );
}
while( replaceSuccess == true );
}
}
#endif
|
texpert/faker
|
test/test_faker_one_piece.rb
|
<reponame>texpert/faker<filename>test/test_faker_one_piece.rb
require_relative 'test_helper'
class TestFakerOnePiece < Test::Unit::TestCase
def setup
@tester = Faker::OnePiece
end
def test_character
assert @tester.character.match(/\w+/)
end
def test_sea
assert @tester.sea.match(/\w+/)
end
def test_island
assert @tester.island.match(/\w+/)
end
def test_location
assert @tester.location.match(/\w+/)
end
def test_quote
assert @tester.quote.match(/\w+/)
end
def test_akuma_no_mi
assert @tester.akuma_no_mi.match(/\w+/)
end
end
|
OpenSourceCTF/website
|
client/components/server-picker/container.js
|
<reponame>OpenSourceCTF/website
import React, { Component } from 'react'
import { observer, inject } from 'mobx-react'
import PropTypes from 'prop-types'
import ServerPickerPage from './server-picker'
@inject('matchmaking')
@observer
class ServerPickerPageContainer extends Component {
static propTypes = {
matchmaking: PropTypes.object.isRequired
}
render () {
const { matchmaking } = this.props
return (
<ServerPickerPage
servers={matchmaking.serversSortedByPing}
selectedServer={matchmaking.chosenServer}
selectServer={matchmaking.setServer}
/>
)
}
}
export default ServerPickerPageContainer
|
matt-clarson/gratitude-journal
|
gratitude_journal_service/entries/tests/test_delete_entry.py
|
<reponame>matt-clarson/gratitude-journal<gh_stars>0
from tests.utils import TestCase
from unittest.mock import Mock
from django.contrib.auth.models import AnonymousUser, User
from graphene import Schema
from graphene.test import Client
from entries.models import Entry
from entries.schema import Query, Mutation
from entries.tests.fixtures import TEST_ENTRY_MUTATION, TEST_DELETE_MUTATION
class TestDeleteEntry(TestCase):
def setUp(self):
self.schema = Schema(query=Query, mutation=Mutation)
self.client = Client(self.schema)
self.user1 = User.objects.create(username="user1")
self.user2 = User.objects.create(username="user2")
self.unauthorised_user = AnonymousUser()
def tearDown(self):
self.user1.delete()
self.user2.delete()
Entry.objects.all().delete()
def test_delete_entry(self):
self.client.execute(TEST_ENTRY_MUTATION, context=Mock(user=self.user1))
entry = Entry.objects.all()[0]
response = self.client.execute(TEST_DELETE_MUTATION(entry.id), context=Mock(user=self.user1))
self.assertEqual(len(Entry.objects.all()), 0)
self.assertMatchSnapshot(response)
def test_deleting_non_existant_entry(self):
response = self.client.execute(TEST_DELETE_MUTATION(1000), context=Mock(user=self.user1))
self.assertMatchSnapshot(response)
def test_deleting_non_owned_entry(self):
self.client.execute(TEST_ENTRY_MUTATION, context=Mock(user=self.user1))
entry = Entry.objects.all()[0]
response = self.client.execute(TEST_DELETE_MUTATION(entry.id), context=Mock(user=self.user2))
self.assertEqual(len(Entry.objects.all()), 1)
self.assertMatchSnapshot(response)
def test_unauthorised_deletion(self):
response = self.client.execute(TEST_DELETE_MUTATION(1), context=Mock(user=self.unauthorised_user))
self.assertMatchSnapshot(response)
|
resource-watch/manager
|
components/admin/coredatasets/CoreDatasetsTab.js
|
<reponame>resource-watch/manager
import React from 'react';
import PropTypes from 'prop-types';
// Components
import CoreDatasetsIndex from 'components/admin/coredatasets/pages/index';
import CoreDatasetsNew from 'components/admin/coredatasets/pages/new';
import CoreDatasetsShow from 'components/admin/coredatasets/pages/show';
export default function CoreDatasetsTab(props) {
const { tab, subtab, id } = props;
return (
<div className="c-resources-tab">
{!id &&
<CoreDatasetsIndex tab={tab} subtab={subtab} id={id} />
}
{id && id === 'new' &&
<CoreDatasetsNew tab={tab} subtab={subtab} id={id} />
}
{id && id !== 'new' &&
<CoreDatasetsShow tab={tab} subtab={subtab} id={id} />
}
</div>
);
}
CoreDatasetsTab.propTypes = {
tab: PropTypes.string,
id: PropTypes.string,
subtab: PropTypes.string
};
|
kos-lang/kos
|
inc/kos_memory.h
|
/* SPDX-License-Identifier: MIT
* Copyright (c) 2014-2021 <NAME>
*/
#ifndef KOS_MEMORY_H_INCLUDED
#define KOS_MEMORY_H_INCLUDED
#include "kos_api.h"
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Variable-size allocator without ability to free items */
struct KOS_MEMPOOL_S {
size_t free_size;
void *next_free;
void *buffers;
};
typedef struct KOS_MEMPOOL_S KOS_MEMPOOL;
KOS_API void KOS_mempool_init(KOS_MEMPOOL *mempool);
KOS_API void KOS_mempool_init_small(KOS_MEMPOOL *mempool, size_t initial_size);
KOS_API void KOS_mempool_destroy(KOS_MEMPOOL *mempool);
KOS_API void *KOS_mempool_alloc(KOS_MEMPOOL *mempool, size_t size);
/* Dynamic array of bytes */
struct KOS_VECTOR_S {
char *buffer;
size_t size;
size_t capacity;
double local_buffer_[2];
};
typedef struct KOS_VECTOR_S KOS_VECTOR;
KOS_API void KOS_vector_init(KOS_VECTOR *vector);
KOS_API void KOS_vector_destroy(KOS_VECTOR *vector);
KOS_API int KOS_vector_reserve(KOS_VECTOR *vector, size_t capacity);
KOS_API int KOS_vector_resize(KOS_VECTOR *vector, size_t size);
KOS_API int KOS_vector_concat(KOS_VECTOR *dest, KOS_VECTOR *src);
#ifdef __cplusplus
}
#endif
#endif
|
chevah/compat
|
chevah/compat/tests/normal/testing/test_assertion.py
|
# Copyright (c) 2015 <NAME>.
# See LICENSE for details.
"""
Tests for the assertion helpers.
"""
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import os
from chevah.compat.exceptions import CompatError
from chevah.compat.testing import ChevahTestCase, mk
class TestAssertionMixin(ChevahTestCase):
"""
Test for assertions.
ChevahTestCase is inheriting the assertion mixin and we can test it.
"""
def check_assertWorkingFolderIsClean(self, content):
"""
Common tests for assertWorkingFolderIsClean.
"""
with self.assertRaises(AssertionError) as context:
self.assertWorkingFolderIsClean()
message = context.exception.args[0].decode('utf-8')
for member in content:
self.assertContains(member, message)
# Calling it again will not raise any error since the folder is clean.
self.assertWorkingFolderIsClean()
def test_assertTempIsClean_clean_temp(self):
"""
No error is raised if temp folder is clean.
"""
self.assertTempIsClean()
def test_assertTempIsClean_dirty(self):
"""
If temp is not clean an error is raised and then temp folders
is cleaned.
"""
temp_segments = mk.fs.createFileInTemp()
with self.assertRaises(AssertionError) as context:
self.assertTempIsClean()
message = context.exception.args[0].decode('utf-8')
self.assertStartsWith(u'Temporary folder is not clean.', message)
self.assertContains(temp_segments[-1], message)
self.assertFalse(mk.fs.exists(temp_segments))
def test_assertWorkingFolderIsClean_with_folder(self):
"""
An error is raised if current working folder contains a temporary
folder and folder is cleaned.
"""
# Our compat filesystem API does not support creating files in
# current working directory so we use direct API call to OS.
name = mk.string()
os.mkdir(mk.fs.getEncodedPath(name))
self.check_assertWorkingFolderIsClean([name])
def test_assertWorkingFolderIsClean_with_file(self):
"""
An error is raised if current working folder contains a temporary
file and file is cleaned.
"""
name = mk.string()
open(mk.fs.getEncodedPath(name), 'a').close()
self.check_assertWorkingFolderIsClean([name])
def test_assertWorkingFolderIsClean_with_file_and_folder(self):
"""
An error is raised if current working folder contains a temporary
folder and file, and folder and folder is cleaned.
"""
file_name = mk.string()
folder_name = mk.string()
open(mk.fs.getEncodedPath(file_name), 'a').close()
os.mkdir(mk.fs.getEncodedPath(folder_name))
self.check_assertWorkingFolderIsClean([file_name, folder_name])
def test_assertIsEmpty(self):
"""
Raise an exception when not empty and otherwise does nothing.
"""
self.assertIsEmpty(())
self.assertIsEmpty([])
self.assertIsEmpty('')
self.assertIsEmpty(set())
with self.assertRaises(AssertionError) as context:
self.assertIsEmpty((1, 2))
self.assertEqual(
'Iterable is not empty.\n(1, 2).', context.exception.args[0])
def test_assertCompatError_no_CompatError(self):
"""
Will show the details if error is not an CompatError.
"""
exception = self.assertRaises(
AssertionError,
self.assertCompatError,
u'123-id',
Exception('generic-error')
)
self.assertEqual(
"Error generic-error not CompatError but "
"<type 'exceptions.Exception'>",
exception.args[0],
)
def test_assertCompatError_bad_id(self):
"""
Will show the details if error is not an CompatError.
"""
exception = self.assertRaises(
AssertionError,
self.assertCompatError,
u'123-id',
CompatError(u'456', u'Some details.')
)
self.assertEqual(
'Error id for CompatError 456 - Some details. is not 123-id, '
'but 456.',
exception.args[0],
)
def test_assertIteratorItemsEqual_no_iterable(self):
"""
Raise an exception if the actual value is not iterable.
"""
sut = [1, 3]
exception = self.assertRaises(
AssertionError,
self.assertIteratorItemsEqual,
[],
sut,
)
self.assertEqual(
'Value is not iterable.',
exception.args[0],
)
def test_assertIteratorItemsEqual_ok(self):
"""
Is equal even if elements are in a different order.
"""
iterator = iter([2])
value = [1, b'3', u'a', iterator]
sut = iter(value)
self.assertIteratorItemsEqual([b'3', 1, u'a', iterator], sut)
def test_assertIteratorItemsEqual_less(self):
"""
It fails if the values are not equal.
"""
value = [1, b'3', u'a']
sut = iter(value)
exception = self.assertRaises(
AssertionError,
self.assertIteratorItemsEqual,
[1],
sut,
)
# The check here is more complicated since the message relies on the
# assertEqual implementation.
self.assertStartsWith(
"Element counts were not equal:",
exception.args[0],
)
def test_assertEqual_unicode_vs_bytestring_in_list(self):
"""
Fails with AssertionError when asserting that lists containing
a Unicode string vs. a bytestring are equal.
"""
unicode_list = [u'text']
bytes_list = [b'text']
with self.assertRaises(AssertionError) as context:
self.assertEqual(unicode_list, bytes_list)
self.assertEqual('First is unicode while second is str for "text".',
context.exception.message)
def test_assertEqual_unicode_vs_bytestring_in_nested_list(self):
"""
Fails with AssertionError when asserting that nested lists containing
a Unicode string vs. a bytestring are equal.
"""
unicode_list = [[u'text']]
bytes_list = [[b'text']]
with self.assertRaises(AssertionError) as context:
self.assertEqual(unicode_list, bytes_list)
self.assertEqual('First is unicode while second is str for "text".',
context.exception.message)
def test_assertEqual_unicode_vs_bytestring_in_tuple(self):
"""
Fails with AssertionError when asserting that tuples containing
a Unicode string vs. a bytestring are equal.
"""
unicode_tuple = (u'text',)
bytes_tuple = (b'text',)
with self.assertRaises(AssertionError) as context:
self.assertEqual(unicode_tuple, bytes_tuple)
self.assertEqual('First is unicode while second is str for "text".',
context.exception.message)
def test_assertEqual_unicode_vs_bytestring_in_set(self):
"""
Fails with AssertionError when asserting that sets containing
a Unicode string vs. a bytestring are equal.
"""
unicode_set = set([u'text'])
bytes_set = set([b'text'])
with self.assertRaises(AssertionError) as context:
self.assertEqual(unicode_set, bytes_set)
self.assertEqual('First is unicode while second is str for "text".',
context.exception.message)
def test_assertEqual_unicode_vs_bytestring_in_dict_keys(self):
"""
Fails with AssertionError when asserting that lists containing
a Unicode string vs. a bytestring are equal.
"""
unicode_dict = {u'key': 'value'}
bytes_dict = {b'key': 'value'}
with self.assertRaises(AssertionError) as context:
self.assertEqual(unicode_dict, bytes_dict)
self.assertEqual('First is unicode while second is str for "key".',
context.exception.message)
def test_assertEqual_unicode_vs_bytestring_in_dict_values(self):
"""
Fails with AssertionError when asserting that lists containing
a Unicode string vs. a bytestring are equal.
"""
unicode_dict = {'key': u'value'}
bytes_dict = {'key': b'value'}
with self.assertRaises(AssertionError) as context:
self.assertEqual(unicode_dict, bytes_dict)
self.assertEqual('First is unicode while second is str for "value".',
context.exception.message)
|
fergy/aplit_linux-5
|
fs/cifs/cache.c
|
/*
* fs/cifs/cache.c - CIFS filesystem cache index structure definitions
*
* Copyright (c) 2010 Novell, Inc.
* Authors(s): <NAME> (<EMAIL>>
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "fscache.h"
#include "cifs_debug.h"
/*
* CIFS filesystem definition for FS-Cache
*/
struct fscache_netfs cifs_fscache_netfs = {
.name = "cifs",
.version = 0,
};
/*
* Register CIFS for caching with FS-Cache
*/
int cifs_fscache_register(void)
{
return fscache_register_netfs(&cifs_fscache_netfs);
}
/*
* Unregister CIFS for caching
*/
void cifs_fscache_unregister(void)
{
fscache_unregister_netfs(&cifs_fscache_netfs);
}
/*
* Server object for FS-Cache
*/
const struct fscache_cookie_def cifs_fscache_server_index_def = {
.name = "CIFS.server",
.type = FSCACHE_COOKIE_TYPE_INDEX,
};
/*
* Auxiliary data attached to CIFS superblock within the cache
*/
struct cifs_fscache_super_auxdata {
u64 resource_id; /* unique server resource id */
};
char *extract_sharename(const char *treename)
{
const char *src;
char *delim, *dst;
int len;
/* skip double chars at the beginning */
src = treename + 2;
/* share name is always preceded by '\\' now */
delim = strchr(src, '\\');
if (!delim)
return ERR_PTR(-EINVAL);
delim++;
len = strlen(delim);
/* caller has to free the memory */
dst = kstrndup(delim, len, GFP_KERNEL);
if (!dst)
return ERR_PTR(-ENOMEM);
return dst;
}
static enum
fscache_checkaux cifs_fscache_super_check_aux(void *cookie_netfs_data,
const void *data,
uint16_t datalen,
loff_t object_size)
{
struct cifs_fscache_super_auxdata auxdata;
const struct cifs_tcon *tcon = cookie_netfs_data;
if (datalen != sizeof(auxdata))
return FSCACHE_CHECKAUX_OBSOLETE;
memset(&auxdata, 0, sizeof(auxdata));
auxdata.resource_id = tcon->resource_id;
if (memcmp(data, &auxdata, datalen) != 0)
return FSCACHE_CHECKAUX_OBSOLETE;
return FSCACHE_CHECKAUX_OKAY;
}
/*
* Superblock object for FS-Cache
*/
const struct fscache_cookie_def cifs_fscache_super_index_def = {
.name = "CIFS.super",
.type = FSCACHE_COOKIE_TYPE_INDEX,
.check_aux = cifs_fscache_super_check_aux,
};
static enum
fscache_checkaux cifs_fscache_inode_check_aux(void *cookie_netfs_data,
const void *data,
uint16_t datalen,
loff_t object_size)
{
struct cifs_fscache_inode_auxdata auxdata;
struct cifsInodeInfo *cifsi = cookie_netfs_data;
if (datalen != sizeof(auxdata))
return FSCACHE_CHECKAUX_OBSOLETE;
memset(&auxdata, 0, sizeof(auxdata));
auxdata.eof = cifsi->server_eof;
auxdata.last_write_time_sec = cifsi->vfs_inode.i_mtime.tv_sec;
auxdata.last_change_time_sec = cifsi->vfs_inode.i_ctime.tv_sec;
auxdata.last_write_time_nsec = cifsi->vfs_inode.i_mtime.tv_nsec;
auxdata.last_change_time_nsec = cifsi->vfs_inode.i_ctime.tv_nsec;
if (memcmp(data, &auxdata, datalen) != 0)
return FSCACHE_CHECKAUX_OBSOLETE;
return FSCACHE_CHECKAUX_OKAY;
}
const struct fscache_cookie_def cifs_fscache_inode_object_def = {
.name = "CIFS.uniqueid",
.type = FSCACHE_COOKIE_TYPE_DATAFILE,
.check_aux = cifs_fscache_inode_check_aux,
};
|
kfr2/singularity-core
|
src/components/BrowseAddonsWindow/index.js
|
import './BrowseAddonsWindow.css';
import 'simplebar/dist/simplebar.min.css';
import SimpleBar from 'simplebar-react';
import * as React from 'react';
import { Row, Col, Form, DropdownButton, Dropdown } from 'react-bootstrap';
import BootstrapTable from 'react-bootstrap-table-next';
import InfiniteScroll from 'react-infinite-scroller'
const { ipcRenderer } = require('electron');
import CategoryButton from '../CategoryButton';
import UpdateAddonButton from '../Buttons/UpdateAddonButton';
import GameMenuButton from '../Buttons/GameMenuButton';
import LoadingSpinner from '../LoadingSpinner';
export default class BrowseAddonsWindow extends React.Component {
constructor(props) {
super(props);
this.state = {
gameId: this.props.gameId,
gameVersion: this.props.gameVersion,
addonVersion: '',
gameName: '',
installedAddons: [],
addonList: [],
hasMoreAddons: true,
categories: [],
page: 0,
pageSize: 50,
selectedView: 1,
activeTab: 1,
errorMessage: '',
currentlyUpdating: [],
erroredUpdates: [],
searchFilter: '',
typing: false,
typingTimeout: 0,
selectedCategory: '',
noAddonsFound: false,
additionalAddons: true,
searching: true,
loadingMore: false
}
this.installAddon = this.installAddon.bind(this);
this.refreshSearch = this.refreshSearch.bind(this);
this.toggleView = this.toggleView.bind(this);
this.loadMoreAddons = this.loadMoreAddons.bind(this);
this.addonInstalledListener = this.addonInstalledListener.bind(this);
this.addonSearchListener = this.addonSearchListener.bind(this);
this.additionalAddonsListener = this.additionalAddonsListener.bind(this);
this.addonSearchErrorListener = this.addonSearchErrorListener.bind(this);
this.addonSearchNoResultListener = this.addonSearchNoResultListener.bind(this);
this.changeFilter = this.changeFilter.bind(this);
this.toggleCategory = this.toggleCategory.bind(this);
}
componentDidUpdate(prevProps) {
if (this.props.gameVersion !== prevProps.gameVersion) {
ipcRenderer.send('addon-search', this.state.gameId, this.state.gameVersion, this.state.searchFilter, 0, this.state.page, this.state.pageSize);
const gameSettings = ipcRenderer.sendSync('get-game-settings', this.props.gameId);
const addonVersion = ipcRenderer.sendSync('get-game-addon-version', this.state.gameId, this.props.gameVersion);
this.setState({
installedAddons: gameSettings[this.props.gameVersion].installedAddons,
gameName: gameSettings[this.props.gameVersion].name,
addonList: [],
selectedCategory: '',
page: 0,
searching: true,
gameVersion: this.props.gameVersion,
addonVersion: addonVersion
});
}
}
componentDidMount() {
ipcRenderer.send('addon-search', this.state.gameId, this.state.gameVersion, this.state.searchFilter, this.state.selectedCategory, this.state.page, this.state.pageSize);
ipcRenderer.on('addon-installed', this.addonInstalledListener);
ipcRenderer.on('addon-search-result', this.addonSearchListener);
ipcRenderer.on('additional-addon-search-result', this.additionalAddonsListener);
ipcRenderer.on('addon-search-error', this.addonSearchErrorListener);
ipcRenderer.on('addon-search-no-result', this.addonSearchNoResultListener);
const gameSettings = ipcRenderer.sendSync('get-game-settings', this.state.gameId);
var categories = ipcRenderer.sendSync('get-game-addon-categories', this.state.gameId);
const addonVersion = ipcRenderer.sendSync('get-game-addon-version', this.state.gameId, this.state.gameVersion);
categories.unshift({
'categoryId': 0,
'name': 'All',
'parentCategoryId': 0,
'rootCategoryId': 0,
})
this.setState({
gameName: gameSettings[this.state.gameVersion].name,
installedAddons: gameSettings[this.state.gameVersion].installedAddons,
categories: categories,
searching: true,
'addonVersion': addonVersion
});
}
componentWillUnmount() {
ipcRenderer.removeListener('addon-installed', this.addonInstalledListener);
ipcRenderer.removeListener('addon-search-result', this.addonSearchListener);
ipcRenderer.removeListener('additional-addon-search-result', this.additionalAddonsListener);
ipcRenderer.removeListener('additional-addon-search-result', this.additionalAddonsListener);
ipcRenderer.removeListener('addon-search-error', this.addonSearchErrorListener);
}
addonInstalledListener(event, installedAddon) {
let installedAddons = this.state.installedAddons.map((addon) => {
if (addon.addonId !== installedAddon.addonId) {
return addon;
} else {
return installedAddon;
}
})
if (!installedAddons.includes(installedAddon)) {
installedAddons.splice(0, 0, installedAddon)
}
let currentlyUpdating = this.state.currentlyUpdating.filter(obj => {
return obj !== installedAddon.addonId;
})
let erroredUpdates = this.state.erroredUpdates.filter(obj => {
return obj !== installedAddon.addonId;
})
this.setState({
installedAddons: installedAddons,
currentlyUpdating: currentlyUpdating,
erroredUpdates: erroredUpdates
});
}
addonSearchListener(event, addons) {
if (addons && addons.length > 0) {
this.setState({
addonList: addons,
noAddonsFound: false,
searching: false,
loadingMore: false
})
} else {
this.setState({
addonList: addons,
noAddonsFound: true,
searching: false,
loadingMore: false
})
}
}
addonSearchNoResultListener(event) {
this.setState({
searching: false,
loadingMore: false,
additionalAddons: false
});
}
addonSearchErrorListener(event) {
this.setState({
searching: false,
loadingMore: false,
additionalAddons: false
});
}
additionalAddonsListener(event, addons) {
var a = this.state.addonList;
var newPage = this.state.page + 1;
if (addons && addons.length > 0) {
this.setState({
addonList: a.concat(addons),
page: newPage,
noAddonsFound: false,
searching: false,
loadingMore: false
})
} else {
this.setState({
page: newPage,
additionalAddons: false,
searching: false
})
}
}
installAddon(addon) {
let branch = 1;
ipcRenderer.send('install-addon', this.state.gameId, this.state.gameVersion, addon, branch);
let currentlyUpdating = this.state.currentlyUpdating.slice();
currentlyUpdating.splice(0, 0, addon.addonId)
this.setState({
currentlyUpdating: currentlyUpdating
});
setTimeout(() => {
if (this.state.currentlyUpdating.includes(addon.addonId)) {
let erroredUpdates = this.state.erroredUpdates.slice();
erroredUpdates.splice(0, 0, addon.addonId);
let currentlyUpdating = this.state.currentlyUpdating.filter(obj => {
return obj !== addon.addonId;
})
this.setState({
erroredUpdates: erroredUpdates,
currentlyUpdating: currentlyUpdating
});
}
}, 30000);
}
refreshSearch() {
this.setState({
addonList: [],
searching: true,
page: 0,
additionalAddons: true,
currentlyUpdating: [],
erroredUpdates: []
})
ipcRenderer.send('addon-search', this.state.gameId, this.state.gameVersion, this.state.searchFilter, this.state.selectedCategory, this.state.page, this.state.pageSize);
}
loadMoreAddons() {
ipcRenderer.send('addon-search', this.state.gameId, this.state.gameVersion, this.state.searchFilter, this.state.selectedCategory, this.state.page + 1, this.state.pageSize);
this.setState({
loadingMore: true
})
}
toggleView(selectedtab) {
this.setState({
selectedView: selectedtab
});
}
toggleCategory(category) {
if (category == null) {
category = 0
}
ipcRenderer.send('addon-search', this.state.gameId, this.state.gameVersion, this.state.searchFilter, category, 0, this.state.pageSize);
this.setState({
selectedCategory: category,
page: 0,
searching: true
})
}
changeFilter(event) {
const self = this;
if (this.state.typingTimeout) {
clearTimeout(this.state.typingTimeout);
}
this.setState({
searchFilter: event.target.value,
typing: false,
typingTimeout: setTimeout(function () {
self.refreshSearch();
}, 700)
});
}
render() {
var selectedCat = this.state.categories.filter(category => {
return parseInt(category.categoryId) === parseInt(this.state.selectedCategory)
})
var selectedCategoryName = 'Category';
if (selectedCat.length > 0) {
selectedCategoryName = selectedCat[0].name
}
const browseAddonsColumns = [{
dataField: 'addonName',
text: 'Addon',
formatter: (cellContent, row, rowIndex) => {
if (!row.primaryCategory) {
console.log(row);
}
return (
<div className="browse-addon-title-column">
<img className="browse-addon-table-img" src={row.primaryCategory.iconUrl} />
<a href="#" className="browse-addon-name" onClick={() => this.props.onSelectAddon(row.addonId)}>{cellContent}</a>
</div>
);
}
}, {
dataField: 'addonId',
text: 'Action',
formatExtraData: {
installedAddons: this.state.installedAddons,
gameVersion: this.state.gameVersion,
addonVersion: this.state.addonVersion,
currentlyUpdating: this.state.currentlyUpdating,
erroredUpdates: this.state.erroredUpdates
},
formatter: (cellContent, row, rowIndex, extraData) => {
if (extraData.erroredUpdates.includes(row.addonId)) {
return <span className="label label-danger">ERROR...</span>;
} else if (extraData.currentlyUpdating.includes(row.addonId)) {
return (
<span className="label label-danger">Updating...</span>
);
} else {
let installed = false;
var installedFileDate;
for (var i = 0; i < extraData.installedAddons.length; i++) {
if (extraData.installedAddons[i].addonId == cellContent.toString()) {
installed = true;
installedFileDate = Date.parse(extraData.installedAddons[i].fileDate);
}
}
if (!installed) {
return (
<UpdateAddonButton handleClick={this.installAddon} clickData={row} type='Install' />
);
}
else {
for (var i = 0; i < row.latestFiles.length; i++) {
if (row.latestFiles[i].gameVersionFlavor == extraData.addonVersion && row.latestFiles[i].releaseType == 1) {
const fileDate = Date.parse(row.latestFiles[i].fileDate);
if (fileDate > installedFileDate) {
return (
<UpdateAddonButton handleClick={this.installAddon} clickData={row} type='Update' />
);
} else {
return (
<span className="label label-danger">Up To Date</span>
);
}
}
}
}
}
}
}, {
dataField: 'totalDownloadCount',
text: 'Downloads',
formatter: (cellContent, row, rowIndex) => {
if (cellContent > 1000000) {
var downloadCount = cellContent.toString().slice(0, -5);
let lastNum = downloadCount.charAt(downloadCount.length - 1);
return downloadCount.slice(0, -1) + '.' + lastNum + "M";
} else if (cellContent > 1000) {
var downloadCount = cellContent.toString().slice(0, -2);
let lastNum = downloadCount.charAt(downloadCount.length - 1);
return downloadCount.slice(0, -1) + '.' + lastNum + "K";
} else {
return cellContent;
}
}
}, {
dataField: 'latestFiles',
text: 'Latest',
formatExtraData: this.state.gameVersion,
formatter: (cellContent, row, rowIndex, gameVersion) => {
for (var i = 0; i < cellContent.length; i++) {
if (cellContent[i].gameVersionFlavor == gameVersion && cellContent[i].releaseType == 1) {
const fileDate = new Date(Date.parse(cellContent[i].fileDate));
let [month, date, year] = fileDate.toLocaleDateString().split("/");
return (
year + '-' + month + '-' + date
);
}
}
}
}, {
dataField: 'categories',
text: 'Category',
formatter: (cellContent, row, rowIndex) => {
if (cellContent[0] && cellContent[0].name) {
return (
cellContent[0].name
);
}
return('')
}
}, {
dataField: 'category',
isDummyField: true,
text: 'Game Version',
formatExtraData: this.state.addonVersion,
formatter: (cellContent, row, rowIndex, addonVersion) => {
for (var i = 0; i < row.latestFiles.length; i++) {
if (row.latestFiles[i].gameVersionFlavor == addonVersion && row.latestFiles[i].releaseType == 1) {
return (
row.latestFiles[i].gameVersion[0]
);
}
}
}
}, {
dataField: 'author',
text: 'Author'
}]
return (
<div className="BrowseAddonsWindow">
<Row>
<Col className="browse-addon-window-content">
<Row className="addon-window-menu">
<Col xs={7} className="browse-addon-buttons">
<div className="browse-addon-game-button"><GameMenuButton handleClick={this.refreshSearch} type='Refresh' /></div>
<div className="browse-addon-game-button hidden"><GameMenuButton handleClick={() => { }} type='Featured' /></div>
<DropdownButton id="category-dropdown"
title={selectedCategoryName}
onSelect={this.toggleCategory}>
{this.state.categories && this.state.categories.map((category, index, a) => (
<Dropdown.Item
key={category.categoryId}
eventKey={category.categoryId}
>{category.name}</Dropdown.Item>
))}
</DropdownButton>
</Col>
<Col xs={5}>
<Form.Group>
<Form.Control
type='text'
name='searchFilter'
className='addon-search-field'
placeholder='Search'
defaultValue={this.state.searchFilter}
onChange={this.changeFilter.bind(this)}
/>
</Form.Group>
</Col>
</Row>
{!this.state.searching
? (this.state.selectedView == 'featured'
? (<div className="category-window">
<Row>
<h1 className="category-window-title">Categories</h1>
</Row>
<Row className="category-selection">
{this.state.categories && this.state.categories.map((category, index, a) => (
<CategoryButton
key={category.categoryId}
categoryId={category.categoryId}
categoryName={category.name}
categoryIcon={category.iconUrl} />
))}
</Row>
</div>
) : (
this.state.noAddonsFound
? <div className="search-error">Looks like we couldn't find any addons for that search...</div>
: <SimpleBar scrollbarMaxSize={50} className={process.platform === 'darwin' ? "addon-table-scrollbar mac" : "addon-table-scrollbar"} >
<Row className="addon-table">
<Col xs={12}>
{this.state.addonList ? (
<BootstrapTable
keyField={'addonId'}
className="browse-addon-table"
headerClasses='browse-addons-header'
data={this.state.addonList}
columns={browseAddonsColumns}>
</BootstrapTable>
) : (
''
)}
</Col>
</Row>
{this.state.loadingMore
? <LoadingSpinner />
: ''
}
<Row>
<Col xs={12}>
{this.state.additionalAddons
? <div className="load-more" onClick={this.loadMoreAddons}>load more</div>
:''
}
</Col>
</Row>
</SimpleBar>
)
): (
<div className = "loading"><LoadingSpinner /></div>
)}
</Col>
</Row>
</div>
)
}
}
|
ScarlettRay/WeiBoManger
|
weiboapi/src/main/java/xyz/iamray/weiboapi/spider/action/DeliverBlogAction.java
|
<reponame>ScarlettRay/WeiBoManger
package xyz.iamray.weiboapi.spider.action;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import xyz.iamray.action.impl.AbstractJsonObjectCrawlerAction;
import xyz.iamray.repo.CrawlMes;
import xyz.iamray.weiboapi.common.constant.TextConstant;
import xyz.iamray.weiboapi.common.exception.WbException;
import xyz.iamray.weiboapi.pojo.Blog;
/**
* @author winray
* @since v1.0.1
* {@link xyz.iamray.weiboapi.api.impl.DeliverBlogAPI}
*/
@Slf4j
public class DeliverBlogAction extends AbstractJsonObjectCrawlerAction<Blog> {
public static final DeliverBlogAction INSTANCE = new DeliverBlogAction();
@Override
public Blog crawl(JSONObject jsonObject, CrawlMes crawlMes) {
if(jsonObject.getInteger("code") == 100000){
//进行一些属性的设置
return getAttribute(TextConstant.API_INPUT,Blog.class);
}else{
throw new WbException(jsonObject.toJSONString());
}
}
}
|
hasancelik/hazelcast-stabilizer
|
simulator/src/main/java/com/hazelcast/simulator/cluster/WorkerConfigurationConverter.java
|
<filename>simulator/src/main/java/com/hazelcast/simulator/cluster/WorkerConfigurationConverter.java<gh_stars>0
/*
* Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.simulator.cluster;
import com.hazelcast.simulator.common.SimulatorProperties;
import com.hazelcast.simulator.coordinator.WorkerParameters;
import com.hazelcast.simulator.protocol.registry.ComponentRegistry;
import com.hazelcast.simulator.worker.WorkerType;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import java.io.File;
import static com.hazelcast.simulator.coordinator.WorkerParameters.initClientHzConfig;
import static com.hazelcast.simulator.coordinator.WorkerParameters.initMemberHzConfig;
import static com.hazelcast.simulator.utils.FileUtils.fileAsText;
import static com.hazelcast.simulator.utils.FileUtils.newFile;
import static com.hazelcast.simulator.worker.WorkerType.MEMBER;
import static java.lang.String.format;
public class WorkerConfigurationConverter implements Converter {
private final int defaultHzPort;
private final String licenseKey;
private final WorkerParameters workerParameters;
private final SimulatorProperties simulatorProperties;
private final ComponentRegistry componentRegistry;
public WorkerConfigurationConverter(int defaultHzPort, String licenseKey, WorkerParameters workerParameters,
SimulatorProperties simulatorProperties, ComponentRegistry componentRegistry) {
this.defaultHzPort = defaultHzPort;
this.licenseKey = licenseKey;
this.workerParameters = workerParameters;
this.simulatorProperties = simulatorProperties;
this.componentRegistry = componentRegistry;
}
@Override
public boolean canConvert(Class type) {
return (type == WorkerConfiguration.class);
}
@Override
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
WorkerConfiguration workerConfiguration = (WorkerConfiguration) source;
writer.addAttribute("name", workerConfiguration.getName());
writer.addAttribute("type", workerConfiguration.getType().name());
writer.addAttribute("hzVersion", workerConfiguration.getHzVersion());
writer.addAttribute("hzConfigFile", workerConfiguration.getHzConfig());
writer.addAttribute("jvmOptions", workerConfiguration.getJvmOptions());
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
String name = reader.getAttribute("name");
String type = reader.getAttribute("type");
String hzVersion = reader.getAttribute("hzVersion");
String hzConfig = reader.getAttribute("hzConfig");
String hzConfigFile = reader.getAttribute("hzConfigFile");
String jvmOptions = reader.getAttribute("jvmOptions");
WorkerType workerType = WorkerType.valueOf(type);
if (hzVersion == null) {
hzVersion = workerParameters.getHazelcastVersionSpec();
}
hzConfig = getHzConfig(hzConfig, hzConfigFile, workerType);
if (jvmOptions == null) {
jvmOptions = getDefaultJvmOptions(workerType);
}
return new WorkerConfiguration(name, workerType, hzVersion, hzConfig, jvmOptions);
}
private String getHzConfig(String hzConfig, String hzConfigFile, WorkerType workerType) {
if (hzConfig != null) {
return initHzConfig(hzConfig, workerType);
}
if (hzConfigFile != null) {
return getHzConfigFromFile(hzConfigFile, workerType);
}
return getDefaultHzConfig(workerType);
}
private String initHzConfig(String hzConfig, WorkerType workerType) {
if (workerType == MEMBER) {
return initMemberHzConfig(hzConfig, componentRegistry, defaultHzPort, licenseKey, simulatorProperties);
}
return initClientHzConfig(hzConfig, componentRegistry, defaultHzPort, licenseKey);
}
private String getHzConfigFromFile(String hzConfigFile, WorkerType workerType) {
File file = newFile(hzConfigFile);
if (!file.exists()) {
throw new IllegalArgumentException(format("Hazelcast configuration for Worker [%s] does not exist", file));
}
return initHzConfig(fileAsText(file), workerType);
}
private String getDefaultHzConfig(WorkerType workerType) {
return (workerType == MEMBER) ? workerParameters.getMemberHzConfig() : workerParameters.getClientHzConfig();
}
private String getDefaultJvmOptions(WorkerType workerType) {
return (workerType == MEMBER) ? workerParameters.getMemberJvmOptions() : workerParameters.getClientJvmOptions();
}
}
|
gritwyplay/Storm
|
src/lib/support/expect/withinRange.js
|
<reponame>gritwyplay/Storm
export default (chai, _) => {
const Assertion = chai.Assertion
const flag = _.flag
Assertion.addMethod('withinRange', function(floor, ceiling, msg) {
if (msg) flag(this, 'message', msg)
const value = this._obj
this.assert(
value >= floor && value <= ceiling,
'expected #{this} to be within ' + floor + 'and ' + ceiling,
'expected #{this} to not be within ' + floor + 'and ' + ceiling
)
})
}
|
NaturalHistoryMuseum/taxonworks
|
app/models/nomenclatural_rank/icnp/higher_classification_group/subclass.rb
|
<reponame>NaturalHistoryMuseum/taxonworks
class NomenclaturalRank::Icnp::HigherClassificationGroup::Subclass < NomenclaturalRank::Icnp::HigherClassificationGroup
def self.parent_rank
NomenclaturalRank::Icnp::HigherClassificationGroup::ClassRank
end
def self.validate_name_format(taxon_name)
super
return true if taxon_name.name.length < 2
taxon_name.errors.add(:name, 'name must end in -idae') if not(taxon_name.name =~ /.*idae\Z/)
end
def self.valid_name_ending
'idae'
end
def self.valid_parents
[NomenclaturalRank::Icnp::HigherClassificationGroup::ClassRank.to_s]
end
end
|
xbabka01/retdec-regression-tests
|
bugs/unhandled-type-catched-assert/float_P61501.c
|
<filename>bugs/unhandled-type-catched-assert/float_P61501.c
/* File: P61501.c Version: 1.5 Date: 2001/10/31
* CVSA, ANSI/ISO C Validation Suite
* Type: Positive test for Clause 6 (Language)
* Copyright 1997, PERENNIAL, All Rights Reserved
*/
/*--------------------------------------------------------------------*\
------------------- TESTPLAN SEGMENT -------------------
>REFS: ISO/ANSI C draft, X3J11/97-037: 6.5.7 Initialization
>WHAT: 00-09. When an aggregate type that has static storage duration
is not initialized explicitly, then its arithmetic type members
are initialized to zero. 6.5.7;10b (2)
>HOW: 00. Declare a static structure with a float member which is not
initialized. Verify that the member is initialized to zero.
01. Declare a static structure with a double member which is not
initialized. Verify that the member is initialized to zero.
02. Declare a static structure with a long double member which
is not initialized. Verify that the member is intialized to
zero.
03. Declare a static structure with a signed char member which
is not initialized. Verify that the member is initialized to
zero.
04. Declare a static structure with an int member which is not
intialized. Verify that the member is initialized to zero.
05. Declare a static structure with a structure member that
has its own character type member. Verify that the member of
the structure member is initialized to zero.
06. Declare a static structure with a structure member that has
its own short int type member. Verify that the member of the
structure member is initialized to zero.
07. Declare a static structure with a structure member that has
its own long int type member. Verify that the member of the
structure member is initialized to zero.
08. Declare a static structure with a structure member that has
its own unsigned short int member. Verify that the member of
the structure member is initialized to zero.
09. Declare a static structure with a structure member that has
its own unsigned long int member. Verify that the member of the
structure member is initialized to zero.
>NOTE: This assertion comes from Defect Report #016 which caused a
modification to ISO 9899:1990 in Technichal Corrigendum 1.
\*--------------------------------------------------------------------*/
#include <math.h>
#include "include/tsthd.h"
#include "include/scaffold.c"
static struct {
float f;
double d;
long double ld;
signed char sc;
int i;
struct {
char c;
short int si;
long int li;
unsigned short int usi;
unsigned long int uli;
}b;
}a;
extern int locflg;
/*--------------------------------------------------------------------*/
char prgnam[] = "P61501.c";
int main(int argc, char *argv[])
{
setup();
post("ISO/ANSI C draft, X3J11/97-037: 6.5.7 Initialization\n");
/*--------------------------------------------------------------------*/
blenter(); /* block 00 */
if (a.f != 0){
locflg = FAILED;
post("float member not initialized to zero.\n");
}
blexit();
/*--------------------------------------------------------------------*/
blenter(); /* block 01 */
if (a.d != 0){
locflg = FAILED;
post("double member not initialized to zero.\n");
}
blexit();
/*--------------------------------------------------------------------*/
blenter(); /* block 02 */
if (a.ld != 0){
locflg = FAILED;
post("long double member not initialized to zero.\n");
}
blexit();
/*--------------------------------------------------------------------*/
blenter(); /* block 03 */
if (a.sc != 0){
locflg = FAILED;
post("signed char member not initialized to zero.\n");
}
blexit();
/*--------------------------------------------------------------------*/
blenter(); /* block 04 */
if (a.i != 0){
locflg = FAILED;
post("int member not initialized to zero.\n");
}
blexit();
/*--------------------------------------------------------------------*/
blenter(); /* block 05 */
if (a.b.c != 0){
locflg = FAILED;
post("Char in structure within structure not initialized"
" to zero.\n");
}
blexit();
/*--------------------------------------------------------------------*/
blenter(); /* block 06 */
if (a.b.si != 0){
locflg = FAILED;
post("short int in structure within structure not "
"initialized to zero.\n");
}
blexit();
/*--------------------------------------------------------------------*/
blenter(); /* block 07 */
if (a.b.li != 0){
locflg = FAILED;
post("long int in structure within structure not "
"initialized to zero.\n");
}
blexit();
/*--------------------------------------------------------------------*/
blenter(); /* block 08 */
if (a.b.usi != 0){
locflg = FAILED;
post("Unsigned short int in structure within structure "
"not initialized to zero.\n");
}
blexit();
/*--------------------------------------------------------------------*/
blenter(); /* block 09 */
if (a.b.uli != 0){
locflg = FAILED;
post("Unsigned long int in structure within structure "
"not initialized to zero.\n");
}
blexit();
/*--------------------------------------------------------------------*/
return(anyfail());
}
|
chachi21/owl-s
|
src/impl/owls/grounding/JavaParameterImpl.java
|
<gh_stars>1-10
package impl.owls.grounding;
import org.mindswap.owl.OWLIndividual;
import org.mindswap.owls.grounding.JavaParameter;
import org.mindswap.owls.vocabulary.MoreGroundings;
public class JavaParameterImpl extends JavaVariableImpl implements
JavaParameter {
public JavaParameterImpl(OWLIndividual ind) {
super(ind);
}
public String getParameterIndex() {
if (hasProperty(MoreGroundings.paramIndex))
return getProperty(MoreGroundings.paramIndex).getLexicalValue();
return "";
}
public void removeParameterIndex() {
if (hasProperty(MoreGroundings.paramIndex))
removeProperties(MoreGroundings.paramIndex);
}
public void setParameterIndex(int index) {
setProperty(MoreGroundings.paramIndex, index);
}
public String getTransformator() {
if (hasProperty(MoreGroundings.transformatorClass))
return getProperty(MoreGroundings.transformatorClass).getLexicalValue();
return "";
}
public void removeTransformator() {
if (hasProperty(MoreGroundings.transformatorClass))
removeProperties(MoreGroundings.transformatorClass);
}
public void setTransformator(String transformator) {
setProperty(MoreGroundings.transformatorClass, transformator);
}
}
|
MightyKnight/Fabric---Discord-Link
|
versions/fabric/1.16.5/src/main/java/fr/arthurbambou/fdlink/compat_1_16/Message1_16.java
|
<reponame>MightyKnight/Fabric---Discord-Link<filename>versions/fabric/1.16.5/src/main/java/fr/arthurbambou/fdlink/compat_1_16/Message1_16.java
package fr.arthurbambou.fdlink.compat_1_16;
import fr.arthurbambou.fdlink.api.minecraft.Message;
import fr.arthurbambou.fdlink.api.minecraft.style.Style;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
public class Message1_16 implements Message {
private String message;
private Style style = Style.EMPTY;
private TextType type;
private String key;
private Object[] args;
private List<Message> sibblings = new ArrayList<>();
private UUID authorUUID;
public Message1_16(String message) {
this.message = message;
this.type = TextType.LITERAL;
}
public Message1_16(String key, String message, Object... args) {
this.key = key;
this.message = message;
this.args = args;
this.type = TextType.TRANSLATABLE;
}
@Override
public Message1_16 setAuthorUUID(UUID uuid) {
if (UUID.fromString("00000000-0000-0000-0000-000000000000").equals(uuid)) {
this.authorUUID = null;
} else {
this.authorUUID = uuid;
}
return this;
}
@Override
public boolean hasAuthorUUID() {
return true;
}
@Override
public UUID getAuthorUUID() {
return this.authorUUID;
}
@Override
public String getMessage() {
return this.message;
}
@Override
public Style getStyle() {
return this.style;
}
@Override
public Message1_16 setStyle(Style style) {
this.style = style;
return this;
}
@Override
public MessageObjectType getType() {
return MessageObjectType.TEXT;
}
@Override
public TextType getTextType() {
return this.type;
}
@Override
public String getKey() {
return this.key;
}
@Override
public Object[] getArgs() {
return this.args;
}
@Override
public List<Message> getSibblings() {
return this.sibblings;
}
@Override
public Message1_16 addSibbling(Message message) {
this.sibblings.add(message);
return this;
}
}
|
ironydips/new-ui-bathwaterkids
|
app/pickup-delivery-management/delivery-trucks/delivery-trucks-assign-modal/delivery-trucks-assign-modal.component.js
|
<reponame>ironydips/new-ui-bathwaterkids
(function(angular) {
'use strict';
function deliverytruckModalController($state, TruckService, DriverService, PickupTruckService) {
var ctrl = this;
ctrl.assign = (ctrl.resolve && ctrl.resolve.details) || {};
ctrl.init = function() {
ctrl.loader = true;
TruckService.getAllTrucks()
.then(function(truckDetails) {
ctrl.loader = false;
ctrl.trucks = truckDetails.data;
})
.catch(function(err) {
console.log('Error getting truck details:');
console.log(err);
});
DriverService.getAllDrivers()
.then(function(response) {
ctrl.loader = false;
ctrl.drivers = response.data;
})
.catch(function(err) {
console.log('Error getting driver list details:');
console.log(err);
})
};
ctrl.assign = function(driverid, truckid) {
PickupTruckService.assignDriverToTruck(driverid, truckid)
.then(function(result) {
//ctrl.modalInstance.close('update');
})
.catch(function(err) {
console.log('Error in assigning truck & driver');
console.log(err);
});
};
ctrl.cancel = function() {
ctrl.modalInstance.close();
}
ctrl.init();
}
angular.module('deliverytruckModal')
.component('deliverytruckModal', {
templateUrl: 'pickup-delivery-management/delivery-trucks/delivery-trucks-assign-modal/delivery-trucks-assign-modal.template.html',
controller: ['$state', 'TruckService', 'DriverService', 'PickupTruckService', deliverytruckModalController],
bindings: {
modalInstance: '<',
resolve: '<'
}
});
})(window.angular);
|
Samspson/golang_learn_ubuntu
|
go_basic/ch3/musicer/src/mlibrary/manager_test.go
|
<gh_stars>0
package mlibrary
import (
"testing"
)
func TestOps(t *testing.T) {
mm := NewMusicManager()
if mm == nil {
t.Error("NewMusicManger failed.")
}
if mm.Len() != 0 {
t.Error("NewMusicManger failed, not empty.")
}
m0 := &MusicEntry{
"1", "My Heart Will Go On", "<NAME>", Pop, "http://qbox.me//24501234", MP3}
mm.Add(m0)
if mm.Len() != 1 {
t.Error("NewMusicManger.Add() failed.")
}
m :=mm.Find(m0.Name) {
t.Error("NewMusicManger.Find() failed.")
}
if m.Id != m0.Id || m.Artist != m0.Artist ||
m.Name != m0.Name || m.Genre != m0.Genre ||
m.Source != m0.Source || m.Type != m0.Type {
t.Error("NewMusicManger.Find failed. Found item mismatch.")
}
m, err := mm.Get(0)
if m == nil {
t.Error("NewMusicManger.Get() failed.", err)
}
m = mm.Remove(0)
if m == nil || mm.Len() != 0 {
t.Error("NewMusicManger.Remove() failed", err)
}
}
|
alexus37/AugmentedRealityChess
|
pythonAnimations/pyOpenGLChess/engineDirectory/oglc-env/lib/python2.7/site-packages/OpenGLContext/testingcontext.py
|
"""Functions for acquiring and instantiating available testing contexts
Testing modules can use these abstract functions to allow for
automatic adaptation to new interactive contexts. You should
not use this module for real world applications, as it is
unlikely that nontrivial code will be completely stable across
all interactive context classes."""
import traceback, string, os, sys, optparse
from OpenGLContext import plugins, context, contextdefinition
# Test-runner can specify the base-class explicitly...
CONFIGURED_BASE = None
REQUIRED_EXTENSION_MISSING = 3 # process return-code for a missing extension
def getVRML( preference= None ):
"""Retrieve the preferred testing context:
returns BaseContext (a class derived from context.Context)
"""
if CONFIGURED_BASE:
return CONFIGURED_BASE
return context.Context.getContextType(
preference, plugins.VRMLContext
)
def getInteractive( preference= None ):
"""Retrieve the preferred testing context:
returns BaseContext (a class derived from context.Context)
"""
if CONFIGURED_BASE:
return CONFIGURED_BASE
return context.Context.getContextType(
preference, plugins.InteractiveContext
)
|
rob-blackbourn/scratch-python
|
blog-rest-api/blog_rest_api/server.py
|
<reponame>rob-blackbourn/scratch-python
import logging
logger = logging.getLogger(__name__)
from aiohttp import web
import asyncio
from motor.motor_asyncio import AsyncIOMotorClient
from blog_rest_api.config import CONFIG
from blog_rest_api.controllers import AuthController, UserController
from blog_rest_api.models import (User, Permission)
from blog_rest_api.utils import Struct
from blog_rest_api.initialisation import initialize, configure
def start():
logging.basicConfig(level=logging.DEBUG)
loop = asyncio.get_event_loop()
client = AsyncIOMotorClient(io_loop=loop)
app = web.Application()
app['db'] = client.blog
app['config'] = Struct(CONFIG)
app.on_startup.append(initialize)
configure(app)
web.run_app(app)
if __name__ == "__main__":
start()
|
francisvm/swift
|
lib/AST/TypeJoinMeet.cpp
|
//===--- TypeJoinMeet.cpp - Swift Type "join" and "meet" -----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements the "join" operation for types (and, eventually,
// "meet").
//
//===----------------------------------------------------------------------===//
#include "swift/AST/ASTContext.h"
#include "swift/AST/CanTypeVisitor.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Type.h"
#include "swift/AST/Types.h"
#include "llvm/ADT/SmallPtrSet.h"
using namespace swift;
// FIXME: This is currently woefully incomplete, and is only currently
// used for optimizing away extra exploratory work in the constraint
// solver. It should eventually encompass all of the subtyping rules
// of the language.
struct TypeJoin : CanTypeVisitor<TypeJoin, CanType> {
CanType First;
TypeJoin(CanType First) : First(First) {
assert(First && "Unexpected null type!");
}
static CanType getSuperclassJoin(CanType first, CanType second);
CanType visitClassType(CanType second);
CanType visitBoundGenericClassType(CanType second);
CanType visitArchetypeType(CanType second);
CanType visitDynamicSelfType(CanType second);
CanType visitMetatypeType(CanType second);
CanType visitExistentialMetatypeType(CanType second);
CanType visitBoundGenericEnumType(CanType second);
CanType visitOptionalType(CanType second);
CanType visitType(CanType second) {
// FIXME: Implement all the visitors.
// llvm_unreachable("Unimplemented type visitor!");
return First->getASTContext().TheAnyType;
}
public:
static CanType join(CanType first, CanType second) {
assert(!first->hasTypeVariable() && !second->hasTypeVariable() &&
"Cannot compute join of types involving type variables");
assert(first->getWithoutSpecifierType()->isEqual(first) &&
"Expected simple type!");
assert(second->getWithoutSpecifierType()->isEqual(second) &&
"Expected simple type!");
// If the types are equivalent, the join is obvious.
if (first == second)
return first;
// Until we handle all the combinations of joins, we need to make
// sure we visit the optional side.
OptionalTypeKind otk;
if (second->getAnyOptionalObjectType(otk))
return TypeJoin(first).visit(second);
return TypeJoin(second).visit(first);
}
};
CanType TypeJoin::getSuperclassJoin(CanType first, CanType second) {
if (!first->mayHaveSuperclass() || !second->mayHaveSuperclass())
return first->getASTContext().TheAnyType;
/// Walk the superclasses of `first` looking for `second`. Record them
/// for our second step.
llvm::SmallPtrSet<CanType, 8> superclassesOfFirst;
for (Type super = first; super; super = super->getSuperclass()) {
auto canSuper = super->getCanonicalType();
// If we have found the second type, we're done.
if (canSuper == second)
return canSuper;
superclassesOfFirst.insert(canSuper);
}
// Look through the superclasses of second to determine if any were also
// superclasses of first.
for (Type super = second; super; super = super->getSuperclass()) {
auto canSuper = super->getCanonicalType();
// If we found the first type, we're done.
if (superclassesOfFirst.count(canSuper))
return canSuper;
}
// There is no common superclass; we're done.
return first->getASTContext().TheAnyType;
}
CanType TypeJoin::visitClassType(CanType second) {
return getSuperclassJoin(First, second);
}
CanType TypeJoin::visitBoundGenericClassType(CanType second) {
return getSuperclassJoin(First, second);
}
CanType TypeJoin::visitArchetypeType(CanType second) {
return getSuperclassJoin(First, second);
}
CanType TypeJoin::visitDynamicSelfType(CanType second) {
return getSuperclassJoin(First, second);
}
CanType TypeJoin::visitMetatypeType(CanType second) {
if (First->getKind() != second->getKind())
return First->getASTContext().TheAnyType;
auto firstInstance =
First->castTo<AnyMetatypeType>()->getInstanceType()->getCanonicalType();
auto secondInstance =
second->castTo<AnyMetatypeType>()->getInstanceType()->getCanonicalType();
auto joinInstance = join(firstInstance, secondInstance);
if (!joinInstance)
return First->getASTContext().TheAnyType;
return MetatypeType::get(joinInstance)->getCanonicalType();
}
CanType TypeJoin::visitExistentialMetatypeType(CanType second) {
if (First->getKind() != second->getKind())
return First->getASTContext().TheAnyType;
auto firstInstance =
First->castTo<AnyMetatypeType>()->getInstanceType()->getCanonicalType();
auto secondInstance =
second->castTo<AnyMetatypeType>()->getInstanceType()->getCanonicalType();
auto joinInstance = join(firstInstance, secondInstance);
if (!joinInstance)
return First->getASTContext().TheAnyType;
return ExistentialMetatypeType::get(joinInstance)->getCanonicalType();
}
CanType TypeJoin::visitBoundGenericEnumType(CanType second) {
if (First->getKind() != second->getKind())
return First->getASTContext().TheAnyType;
OptionalTypeKind otk1, otk2;
auto firstObject = First->getAnyOptionalObjectType(otk1);
auto secondObject = second->getAnyOptionalObjectType(otk2);
if (otk1 == OTK_Optional || otk2 == OTK_Optional) {
auto canFirst = firstObject->getCanonicalType();
auto canSecond = secondObject->getCanonicalType();
// Compute the join of the unwrapped type. If there is none, we're done.
auto unwrappedJoin =
join(canFirst ? canFirst : First, canSecond ? canSecond : second);
// FIXME: More general joins of enums need to be handled.
if (!unwrappedJoin)
return First->getASTContext().TheAnyType;
return OptionalType::get(unwrappedJoin)->getCanonicalType();
}
// FIXME: More general joins of enums need to be handled.
return First->getASTContext().TheAnyType;
}
Type Type::join(Type first, Type second) {
assert(first && second && "Unexpected null type!");
if (!first || !second) {
if (first)
return Type(ErrorType::get(first->getASTContext()));
if (second)
return Type(ErrorType::get(second->getASTContext()));
return Type();
}
return TypeJoin::join(first->getCanonicalType(), second->getCanonicalType());
}
|
green-fox-academy/eugene2candy
|
week-02/day-3/is-in-list.js
|
<gh_stars>0
'use strict';
// Check if array contains all of the following elements: 4,8,12,16
// Create a function that accepts 'listOfNumbers' as an input
// it should return "true" if it contains all, otherwise "false"
let listOfNumbers = [2, 4, 6, 8, 10, 12, 14, 16];
function checkNums(params) {
let mes;
if (params.indexOf(4) && params.indexOf(8) && params.indexOf(12) && params.indexOf(16)) {
mes = true;
} else {
mes = false;
}
return mes;
}
console.log(checkNums(listOfNumbers));
module.exports = checkNums;
|
tico88612/Solution-Note
|
UVa/11388.cpp
|
//
// 11388.cpp
//
//
// Created by 楊承昊 on 2017/4/28.
//
//
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(0);cin.tie(0);
int T;
cin>>T;
while(T--)
{
long long int ans=0;
long long int G,L,sum;
cin>>G>>L;
sum=G*L;
if(L%G)
{
ans=0;
}
else
{
ans=G;
}
if(ans!=0)
cout<<ans<<" "<<sum/ans<<endl;
else
cout<<"-1"<<endl;
}
return 0;
}
|
NovasomIndustries/Utils-2019.01
|
rock/app/music/music/middle/musiclistwidget.cpp
|
#include "musiclistwidget.h"
#include "constant.h"
#include <QHBoxLayout>
#ifdef DEVICE_EVB
int header_height = 70;
#else
int header_height = 35;
#endif
PlayListHeader::PlayListHeader(QWidget *parent) : BaseWidget(parent)
{
setFixedHeight(header_height);
setCursor(Qt::PointingHandCursor);
initLayout();
}
void PlayListHeader::initLayout()
{
QHBoxLayout *layout = new QHBoxLayout;
m_listCountInfo = new QLabel(tr("song(0)"), this);
m_listCountInfo->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
QLabel *songTypeInfo = new QLabel(tr("type"), this);
songTypeInfo->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
layout->addWidget(m_listCountInfo);
layout->addWidget(songTypeInfo);
layout->setContentsMargins(20, 0, 25, 0);
layout->setSpacing(0);
setLayout(layout);
}
void PlayListHeader::updateSongCountText(int songCount)
{
m_listCountInfo->setText(tr("music(%1)").arg(QString::number(songCount)));
}
MusicListWidget::MusicListWidget(QWidget *parent) : BaseWidget(parent)
, m_playlist(new MediaList(this))
{
initLayout();
initConnection();
}
void MusicListWidget::initLayout()
{
QVBoxLayout *layout = new QVBoxLayout;
m_header = new PlayListHeader(this);
m_table = new MusicListTable(this);
layout->addWidget(m_header);
layout->addWidget(m_table);
layout->setMargin(0);
layout->setSpacing(0);
setLayout(layout);
}
void MusicListWidget::initConnection()
{
connect(m_table, SIGNAL(cellClicked(int,int)), this, SIGNAL(tableClick(int,int)));
connect(m_table, SIGNAL(longPressedEvent(int)), this, SIGNAL(tableLongPressed(int)));
}
void MusicListWidget::setPlayingMediaContent(QString filaPath)
{
QList<QString> pathList = m_playlist->getPathList();
int index = -1;
for (int i = 0; i < pathList.size(); i++) {
if (pathList.at(i) == filaPath) {
index = i;
break;
}
}
if (index != -1) {
m_table->playingItemChanged(index);
m_playlist->setCurrentIndex(index);
}
}
void MusicListWidget::setOriginState()
{
m_table->setOriginState();
}
void MusicListWidget::deleteItem(int row)
{
m_table->removeTableItem(row);
m_playlist->removeItem(row);
m_header->updateSongCountText(m_table->rowCount());
}
void MusicListWidget::insertIntoTable(const QFileInfo &fileInfo)
{
QString fileName = fileInfo.baseName();
QString fileSuffix = fileInfo.suffix();
QString filePath = fileInfo.absoluteFilePath();
m_table->insertIntoTable(fileName, fileSuffix);
m_playlist->addPlayList(filePath);
m_header->updateSongCountText(m_table->rowCount());
}
void MusicListWidget::updateLocalList(QFileInfoList fileInfoList)
{
// remove table and set song count first
m_table->clearTable();;
m_playlist->clearList();
m_header->updateSongCountText(m_table->rowCount());
for (int i = 0; i < fileInfoList.size(); i++) {
QFileInfo fileInfo = fileInfoList.at(i);
if (!m_playlist->getPathList().contains(fileInfo.absoluteFilePath()))
insertIntoTable(fileInfo);
}
}
|
Paschalis/android-llvm
|
tools/class2greylist/src/com/android/class2greylist/MemberDumpingVisitor.java
|
<gh_stars>10-100
package com.android.class2greylist;
import org.apache.bcel.classfile.DescendingVisitor;
import org.apache.bcel.classfile.EmptyVisitor;
import org.apache.bcel.classfile.Field;
import org.apache.bcel.classfile.FieldOrMethod;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
/**
* A class file visitor that simply prints to stdout the signature of every member within the class.
*/
public class MemberDumpingVisitor extends EmptyVisitor {
private final Status mStatus;
private final DescendingVisitor mDescendingVisitor;
/**
* Creates a visitor for a class.
*
* @param clazz Class to visit
*/
public MemberDumpingVisitor(JavaClass clazz, Status status) {
mStatus = status;
mDescendingVisitor = new DescendingVisitor(clazz, this);
}
public void visit() {
mDescendingVisitor.visit();
}
@Override
public void visitMethod(Method method) {
visitMember(method, "L%s;->%s%s");
}
@Override
public void visitField(Field field) {
visitMember(field, "L%s;->%s:%s");
}
private void visitMember(FieldOrMethod member, String signatureFormatString) {
AnnotationContext context = new AnnotatedMemberContext(mStatus,
(JavaClass) mDescendingVisitor.predecessor(), member,
signatureFormatString);
System.out.println(context.getMemberDescriptor());
}
}
|
arthurpaimarnold/go-hdb
|
internal/protocol/message.go
|
<gh_stars>1-10
/*
Copyright 2014 SAP SE
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package protocol
import (
"fmt"
"github.com/SAP/go-hdb/internal/protocol/encoding"
)
const (
messageHeaderSize = 32 //nolint:varcheck
)
//message header
type messageHeader struct {
sessionID int64
packetCount int32
varPartLength uint32
varPartSize uint32
noOfSegm int16
}
func (h *messageHeader) String() string {
return fmt.Sprintf("session id %d packetCount %d varPartLength %d, varPartSize %d noOfSegm %d",
h.sessionID,
h.packetCount,
h.varPartLength,
h.varPartSize,
h.noOfSegm)
}
func (h *messageHeader) encode(enc *encoding.Encoder) error {
enc.Int64(h.sessionID)
enc.Int32(h.packetCount)
enc.Uint32(h.varPartLength)
enc.Uint32(h.varPartSize)
enc.Int16(h.noOfSegm)
enc.Zeroes(10) //messageHeaderSize
return nil
}
func (h *messageHeader) decode(dec *encoding.Decoder) error {
h.sessionID = dec.Int64()
h.packetCount = dec.Int32()
h.varPartLength = dec.Uint32()
h.varPartSize = dec.Uint32()
h.noOfSegm = dec.Int16()
dec.Skip(10) //messageHeaderSize
return dec.Error()
}
|
ignisf/feedbin
|
config/initializers/whitelist.rb
|
Feedbin::Application.config.whitelist = HTML::Pipeline::SanitizationFilter::WHITELIST.clone
Feedbin::Application.config.whitelist[:attributes][:all] += ['id']
Feedbin::Application.config.whitelist[:attributes]['source'] = ['src']
Feedbin::Application.config.whitelist[:attributes]['video'] = ['src']
Feedbin::Application.config.whitelist[:attributes]['audio'] = ['src']
Feedbin::Application.config.whitelist[:attributes]['td'] = ['style']
Feedbin::Application.config.whitelist[:elements] += ['figure', 'figcaption', 'audio', 'video', 'source']
Feedbin::Application.config.whitelist[:protocols]['img']['src'] += ['data']
Feedbin::Application.config.whitelist[:protocols]['video'] = {'src' => ['http', 'https']}
Feedbin::Application.config.whitelist[:protocols]['audio'] = {'src' => ['http', 'https']}
Feedbin::Application.config.whitelist[:css] = {
properties: ['padding']
}
Feedbin::Application.config.evernote_whitelist = {
:elements => %w(
a abbr acronym address area b bdo big blockquote br caption center cite code col colgroup dd
del dfn div dl dt em font h1 h2 h3 h4 h5 h6 hr i img ins kbd li map ol p pre q s samp small
span strike strong sub sup table tbody td tfoot th thead title tr tt u ul var xmp
),
:remove_contents => ['script', 'style', 'iframe', 'object', 'embed'],
:attributes => {
'a' => ['href'],
'img' => ['src'],
:all => ['align', 'alt', 'border', 'cellpadding', 'cellspacing', 'cite', 'cols', 'colspan', 'color',
'coords', 'datetime', 'dir', 'disabled', 'enctype', 'for', 'height', 'hreflang', 'label', 'lang',
'longdesc', 'name', 'rel', 'rev', 'rows', 'rowspan', 'selected', 'shape', 'size', 'span', 'start',
'summary', 'target', 'title', 'type','valign', 'value', 'vspace', 'width']
},
:protocols => {
'a' => {'href' => ['http', 'https', :relative]},
'img' => {'src' => ['http', 'https', :relative]}
}
}
|
tommywaltion/BOTS
|
commands/ban.js
|
<reponame>tommywaltion/BOTS
const discord = require("discord.js")
module.exports.run = async(bot, message, args) => {
if(!message.member.hasPermission('MENAGE_MESSAGES')){
message.channel.send(`You dont have the permission to use this commands`);
return;
}
let bUser = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[0]));
if(!bUser) {
message.delete();
return message.channel.send("Cant find the specific user!")
}
let bReason = args.slice(1).join(" ");
if(!bReason) return message.channel.send("Please put a reason!");
let banEmbed = new Discord.RichEmbed()
.setTitle("Ban report!")
.addField("Banned by", `${message.author}`, true)
.addField("Banned", kUser, true)
.addField("Reason", kReason)
.addField("Time", message.createdAt)
.setColor("#B01010");
message.delete().catch(O_o=>{});
message.guild.member(bUser).ban(bReason);
message.channel.send(`Baneed: ${kUser}, By: ${message.author}, Reason: ${bReason}`);
message.guild.channels.find("name", "log-channel").sendEmbed(banEmbed);
}
module.exports.config = {
name: "ban",
aliases: ["ban","bans","b","punish"]
}
|
luwei0917/GlpG_Nature_Communication
|
src/USER-SMD/smd_material_models.cpp
|
<gh_stars>1-10
/* ----------------------------------------------------------------------
*
* *** Smooth Mach Dynamics ***
*
* This file is part of the USER-SMD package for LAMMPS.
* Copyright (2014) <NAME>, <EMAIL>
* Fraunhofer Ernst-Mach Institute for High-Speed Dynamics, EMI,
* Eckerstrasse 4, D-79104 Freiburg i.Br, Germany.
*
* ----------------------------------------------------------------------- */
/* ----------------------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
http://lammps.sandia.gov, Sandia National Laboratories
<NAME>, <EMAIL>
Copyright (2003) Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
certain rights in this software. This software is distributed under
the GNU General Public License.
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
#include <iostream>
#include "math_special.h"
#include <stdio.h>
#include <Eigen/Eigen>
using namespace LAMMPS_NS::MathSpecial;
using namespace std;
using namespace Eigen;
#define MIN(A,B) ((A) < (B) ? (A) : (B))
#define MAX(A,B) ((A) > (B) ? (A) : (B))
/* ----------------------------------------------------------------------
linear EOS for use with linear elasticity
input: initial pressure pInitial, isotropic part of the strain rate d, time-step dt
output: final pressure pFinal, pressure rate p_rate
------------------------------------------------------------------------- */
void LinearEOS(double lambda, double pInitial, double d, double dt, double &pFinal, double &p_rate) {
/*
* pressure rate
*/
p_rate = lambda * d;
pFinal = pInitial + dt * p_rate; // increment pressure using pressure rate
//cout << "hurz" << endl;
}
/* ----------------------------------------------------------------------
shock EOS
input:
current density rho
reference density rho0
current energy density e
reference energy density e0
reference speed of sound c0
shock Hugoniot parameter S
Grueneisen parameter Gamma
initial pressure pInitial
time step dt
output:
pressure rate p_rate
final pressure pFinal
------------------------------------------------------------------------- */
void ShockEOS(double rho, double rho0, double e, double e0, double c0, double S, double Gamma, double pInitial, double dt,
double &pFinal, double &p_rate) {
double mu = rho / rho0 - 1.0;
double pH = rho0 * square(c0) * mu * (1.0 + mu) / square(1.0 - (S - 1.0) * mu);
pFinal = (pH + rho * Gamma * (e - e0));
//printf("shock EOS: rho = %g, rho0 = %g, Gamma=%f, c0=%f, S=%f, e=%f, e0=%f\n", rho, rho0, Gamma, c0, S, e, e0);
//printf("pFinal = %f\n", pFinal);
p_rate = (pFinal - pInitial) / dt;
}
/* ----------------------------------------------------------------------
polynomial EOS
input:
current density rho
reference density rho0
coefficients 0 .. 6
initial pressure pInitial
time step dt
output:
pressure rate p_rate
final pressure pFinal
------------------------------------------------------------------------- */
void polynomialEOS(double rho, double rho0, double e, double C0, double C1, double C2, double C3, double C4, double C5, double C6,
double pInitial, double dt, double &pFinal, double &p_rate) {
double mu = rho / rho0 - 1.0;
if (mu > 0.0) {
pFinal = C0 + C1 * mu + C2 * mu * mu + C3 * mu * mu * mu; // + (C4 + C5 * mu + C6 * mu * mu) * e;
} else {
pFinal = C0 + C1 * mu + C3 * mu * mu * mu; // + (C4 + C5 * mu) * e;
}
pFinal = -pFinal; // we want the mean stress, not the pressure.
//printf("pFinal = %f\n", pFinal);
p_rate = (pFinal - pInitial) / dt;
}
/* ----------------------------------------------------------------------
Tait EOS based on current density vs. reference density.
input: (1) reference sound speed
(2) equilibrium mass density
(3) current mass density
output:(1) pressure
(2) current speed of sound
------------------------------------------------------------------------- */
void TaitEOS_density(const double exponent, const double c0_reference, const double rho_reference, const double rho_current,
double &pressure, double &sound_speed) {
double B = rho_reference * c0_reference * c0_reference / exponent;
double tmp = pow(rho_current / rho_reference, exponent);
pressure = B * (tmp - 1.0);
double bulk_modulus = B * tmp * exponent; // computed as rho * d(pressure)/d(rho)
sound_speed = sqrt(bulk_modulus / rho_current);
// if (fabs(pressure) > 0.01) {
// printf("tmp = %f, press=%f, K=%f\n", tmp, pressure, bulk_modulus);
// }
}
/* ----------------------------------------------------------------------
perfect gas EOS
input: gamma -- adiabatic index (ratio of specific heats)
J -- determinant of deformation gradient
volume0 -- reference configuration volume of particle
energy -- energy of particle
pInitial -- initial pressure of the particle
d -- isotropic part of the strain rate tensor,
dt -- time-step size
output: final pressure pFinal, pressure rate p_rate
------------------------------------------------------------------------- */
void PerfectGasEOS(const double gamma, const double vol, const double mass, const double energy, double &pFinal, double &c0) {
/*
* perfect gas EOS is p = (gamma - 1) rho e
*/
if (energy > 0.0) {
pFinal = (1.0 - gamma) * energy / vol;
//printf("gamma = %f, vol%f, e=%g ==> p=%g\n", gamma, vol, energy, *pFinal__/1.0e-9);
c0 = sqrt((gamma - 1.0) * energy / mass);
} else {
pFinal = c0 = 0.0;
}
}
/* ----------------------------------------------------------------------
linear strength model for use with linear elasticity
input: lambda, mu : Lame parameters
input: sigmaInitial_dev, d_dev: initial stress deviator, deviatoric part of the strain rate tensor
input: dt: time-step
output: sigmaFinal_dev, sigmaFinal_dev_rate__: final stress deviator and its rate.
------------------------------------------------------------------------- */
void LinearStrength(const double mu, const Matrix3d sigmaInitial_dev, const Matrix3d d_dev, const double dt,
Matrix3d &sigmaFinal_dev__, Matrix3d &sigma_dev_rate__) {
/*
* deviatoric rate of unrotated stress
*/
sigma_dev_rate__ = 2.0 * mu * d_dev;
/*
* elastic update to the deviatoric stress
*/
sigmaFinal_dev__ = sigmaInitial_dev + dt * sigma_dev_rate__;
}
/* ----------------------------------------------------------------------
linear strength model for use with linear elasticity
input: lambda, mu : Lame parameters
input: F: deformation gradient
output: total stress tensor, deviator + pressure
------------------------------------------------------------------------- */
//void PairTlsph::LinearStrengthDefgrad(double lambda, double mu, Matrix3d F, Matrix3d *T) {
// Matrix3d E, PK2, eye, sigma, S, tau;
//
// eye.setIdentity();
//
// E = 0.5 * (F * F.transpose() - eye); // strain measure E = 0.5 * (B - I) = 0.5 * (F * F^T - I)
// tau = lambda * E.trace() * eye + 2.0 * mu * E; // Kirchhoff stress, work conjugate to above strain
// sigma = tau / F.determinant(); // convert Kirchhoff stress to Cauchy stress
//
////printf("l=%f, mu=%f, sigma xy = %f\n", lambda, mu, sigma(0,1));
//
//// E = 0.5 * (F.transpose() * F - eye); // Green-Lagrange Strain E = 0.5 * (C - I)
//// S = lambda * E.trace() * eye + 2.0 * mu * Deviator(E); // PK2 stress
//// tau = F * S * F.transpose(); // convert PK2 to Kirchhoff stress
//// sigma = tau / F.determinant();
//
// //*T = sigma;
//
// /*
// * neo-hookean model due to Bonet
// */
//// lambda = mu = 100.0;
//// // left Cauchy-Green Tensor, b = F.F^T
// double J = F.determinant();
// double logJ = log(J);
// Matrix3d b;
// b = F * F.transpose();
//
// sigma = (mu / J) * (b - eye) + (lambda / J) * logJ * eye;
// *T = sigma;
//}
/* ----------------------------------------------------------------------
linear strength model for use with linear elasticity
input: lambda, mu : Lame parameters
input: sigmaInitial_dev, d_dev: initial stress deviator, deviatoric part of the strain rate tensor
input: dt: time-step
output: sigmaFinal_dev, sigmaFinal_dev_rate__: final stress deviator and its rate.
------------------------------------------------------------------------- */
void LinearPlasticStrength(const double G, const double yieldStress, const Matrix3d sigmaInitial_dev, const Matrix3d d_dev,
const double dt, Matrix3d &sigmaFinal_dev__, Matrix3d &sigma_dev_rate__, double &plastic_strain_increment) {
Matrix3d sigmaTrial_dev, dev_rate;
double J2;
/*
* deviatoric rate of unrotated stress
*/
dev_rate = 2.0 * G * d_dev;
/*
* perform a trial elastic update to the deviatoric stress
*/
sigmaTrial_dev = sigmaInitial_dev + dt * dev_rate; // increment stress deviator using deviatoric rate
/*
* check yield condition
*/
J2 = sqrt(3. / 2.) * sigmaTrial_dev.norm();
if (J2 < yieldStress) {
/*
* no yielding has occured.
* final deviatoric stress is trial deviatoric stress
*/
sigma_dev_rate__ = dev_rate;
sigmaFinal_dev__ = sigmaTrial_dev;
plastic_strain_increment = 0.0;
//printf("no yield\n");
} else {
//printf("yiedl\n");
/*
* yielding has occured
*/
plastic_strain_increment = (J2 - yieldStress) / (3.0 * G);
/*
* new deviatoric stress:
* obtain by scaling the trial stress deviator
*/
sigmaFinal_dev__ = (yieldStress / J2) * sigmaTrial_dev;
/*
* new deviatoric stress rate
*/
sigma_dev_rate__ = sigmaFinal_dev__ - sigmaInitial_dev;
//printf("yielding has occured.\n");
}
}
/* ----------------------------------------------------------------------
Johnson Cook Material Strength model
input:
G : shear modulus
cp : heat capacity
espec : energy / mass
A : initial yield stress under quasi-static / room temperature conditions
B : proportionality factor for plastic strain dependency
a : exponent for plastic strain dpendency
C : proportionality factor for logarithmic plastic strain rate dependency
epdot0 : dimensionality factor for plastic strain rate dependency
T : current temperature
T0 : reference (room) temperature
Tmelt : melting temperature
input: sigmaInitial_dev, d_dev: initial stress deviator, deviatoric part of the strain rate tensor
input: dt: time-step
output: sigmaFinal_dev, sigmaFinal_dev_rate__: final stress deviator and its rate.
------------------------------------------------------------------------- */
void JohnsonCookStrength(const double G, const double cp, const double espec, const double A, const double B, const double a,
const double C, const double epdot0, const double T0, const double Tmelt, const double M, const double dt, const double ep,
const double epdot, const Matrix3d sigmaInitial_dev, const Matrix3d d_dev, Matrix3d &sigmaFinal_dev__,
Matrix3d &sigma_dev_rate__, double &plastic_strain_increment) {
Matrix3d sigmaTrial_dev, dev_rate;
double J2, yieldStress;
double deltaT = espec / cp;
double TH = deltaT / (Tmelt - T0);
TH = MAX(TH, 0.0);
double epdot_ratio = epdot / epdot0;
epdot_ratio = MAX(epdot_ratio, 1.0);
//printf("current temperature delta is %f, TH=%f\n", deltaT, TH);
yieldStress = (A + B * pow(ep, a)) * (1.0 + C * log(epdot_ratio)); // * (1.0 - pow(TH, M));
/*
* deviatoric rate of unrotated stress
*/
dev_rate = 2.0 * G * d_dev;
/*
* perform a trial elastic update to the deviatoric stress
*/
sigmaTrial_dev = sigmaInitial_dev + dt * dev_rate; // increment stress deviator using deviatoric rate
/*
* check yield condition
*/
J2 = sqrt(3. / 2.) * sigmaTrial_dev.norm();
if (J2 < yieldStress) {
/*
* no yielding has occured.
* final deviatoric stress is trial deviatoric stress
*/
sigma_dev_rate__ = dev_rate;
sigmaFinal_dev__ = sigmaTrial_dev;
plastic_strain_increment = 0.0;
//printf("no yield\n");
} else {
//printf("yiedl\n");
/*
* yielding has occured
*/
plastic_strain_increment = (J2 - yieldStress) / (3.0 * G);
/*
* new deviatoric stress:
* obtain by scaling the trial stress deviator
*/
sigmaFinal_dev__ = (yieldStress / J2) * sigmaTrial_dev;
/*
* new deviatoric stress rate
*/
sigma_dev_rate__ = sigmaFinal_dev__ - sigmaInitial_dev;
//printf("yielding has occured.\n");
}
}
/* ----------------------------------------------------------------------
isotropic maximum strain damage model
input:
current strain
maximum value of allowed principal strain
output:
return value is true if any eigenvalue of the current strain exceeds the allowed principal strain
------------------------------------------------------------------------- */
bool IsotropicMaxStrainDamage(const Matrix3d E, const double maxStrain) {
/*
* compute Eigenvalues of strain matrix
*/
SelfAdjointEigenSolver < Matrix3d > es;
es.compute(E); // compute eigenvalue and eigenvectors of strain
double max_eigenvalue = es.eigenvalues().maxCoeff();
if (max_eigenvalue > maxStrain) {
return true;
} else {
return false;
}
}
/* ----------------------------------------------------------------------
isotropic maximum stress damage model
input:
current stress
maximum value of allowed principal stress
output:
return value is true if any eigenvalue of the current stress exceeds the allowed principal stress
------------------------------------------------------------------------- */
bool IsotropicMaxStressDamage(const Matrix3d S, const double maxStress) {
/*
* compute Eigenvalues of strain matrix
*/
SelfAdjointEigenSolver < Matrix3d > es;
es.compute(S); // compute eigenvalue and eigenvectors of strain
double max_eigenvalue = es.eigenvalues().maxCoeff();
if (max_eigenvalue > maxStress) {
return true;
} else {
return false;
}
}
/* ----------------------------------------------------------------------
Johnson-Cook failure model
input:
output:
------------------------------------------------------------------------- */
double JohnsonCookFailureStrain(const double p, const Matrix3d Sdev, const double d1, const double d2, const double d3,
const double d4, const double epdot0, const double epdot) {
double vm = sqrt(3. / 2.) * Sdev.norm(); // von-Mises equivalent stress
if (vm < 0.0) {
cout << "this is sdev " << endl << Sdev << endl;
printf("vm=%f < 0.0, surely must be an error\n", vm);
exit(1);
}
// determine stress triaxiality
double triax = p / (vm + 0.01 * fabs(p)); // have softening in denominator to avoid divison by zero
if (triax < 0.0) {
triax = 0.0;
} else if (triax > 3.0) {
triax = 3.0;
}
// Johnson-Cook failure strain, dependence on stress triaxiality
double jc_failure_strain = d1 + d2 * exp(d3 * triax);
// include strain rate dependency if parameter d4 is defined and current plastic strain rate exceeds reference strain rate
if (d4 > 0.0) { //
if (epdot > epdot0) {
double epdot_ratio = epdot / epdot0;
jc_failure_strain *= (1.0 + d4 * log(epdot_ratio));
//printf("epsdot=%f, epsdot0=%f, factor = %f\n", epdot, epdot0, (1.0 + d4 * log(epdot_ratio)));
//exit(1);
}
}
return jc_failure_strain;
}
|
GoogleForCreators/web-stories-wp
|
packages/migration/src/migrations/test/v0042_removeTrackName.js
|
/*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Internal dependencies
*/
import removeTrackName from '../v0042_removeTrackName';
describe('removeTrackName', () => {
it('should move properties', () => {
expect(
removeTrackName({
backgroundAudio: {
src: 'https://example.com/audio.mp3',
id: 123,
mimeType: 'audio/mpeg',
},
pages: [
{
backgroundAudio: {
loop: true,
resource: {
src: 'https://example.com/audio.mp3',
id: 123,
mimeType: 'audio/mpeg',
},
tracks: [
{
track: 'https://example.com/track.vtt',
trackId: 123,
trackName: 'track.vtt',
id: 'rersd-fdfd-fdfd-fdfd',
srcLang: '',
label: '',
kind: 'captions',
},
],
},
elements: [],
},
],
})
).toStrictEqual({
backgroundAudio: {
resource: {
src: 'https://example.com/audio.mp3',
id: 123,
mimeType: 'audio/mpeg',
},
},
pages: [
{
backgroundAudio: {
loop: true,
resource: {
src: 'https://example.com/audio.mp3',
id: 123,
mimeType: 'audio/mpeg',
},
tracks: [
{
track: 'https://example.com/track.vtt',
trackId: 123,
id: 'rersd-fdfd-fdfd-fdfd',
srcLang: '',
label: '',
kind: 'captions',
},
],
},
elements: [],
},
],
});
});
});
|
vjeko/CorfuDB
|
generator/src/main/java/org/corfudb/generator/StringIndexer.java
|
package org.corfudb.generator;
import org.corfudb.runtime.collections.CorfuTable;
import org.corfudb.runtime.collections.CorfuTable.Index;
import java.util.Iterator;
import java.util.Optional;
import java.util.stream.Stream;
public class StringIndexer implements CorfuTable.IndexRegistry<String, String> {
public static final CorfuTable.IndexName BY_VALUE = () -> "BY_VALUE";
public static final CorfuTable.IndexName BY_FIRST_CHAR = () -> "BY_FIRST_LETTER";
private static final CorfuTable.Index<String, String, ? extends Comparable<?>> BY_VALUE_INDEX =
new CorfuTable.Index<>(
BY_VALUE,
(CorfuTable.IndexFunction<String, String, String>) (key, val) -> val);
private static final CorfuTable.Index<String, String, ? extends Comparable<?>> BY_FIRST_CHAR_INDEX =
new CorfuTable.Index<>(
BY_FIRST_CHAR,
(CorfuTable.IndexFunction<String, String, String>) (key, val) ->
Character.toString(val.charAt(0)));
@Override
public Iterator<Index<String, String, ? extends Comparable<?>>> iterator() {
return Stream.of(BY_VALUE_INDEX, BY_FIRST_CHAR_INDEX).iterator();
}
@Override
public Optional<CorfuTable.Index<String, String, ? extends Comparable<?>>> get(CorfuTable.IndexName name) {
String indexName = (name != null)? name.get() : null;
if (BY_VALUE.get().equals(indexName)) {
return Optional.of(BY_VALUE_INDEX);
} else if (BY_FIRST_CHAR.get().equals(indexName)) {
return Optional.of(BY_FIRST_CHAR_INDEX);
} else {
return Optional.empty();
}
}
}
|
ayoub-root/graflow
|
test/unit/Hub.js
|
<filename>test/unit/Hub.js<gh_stars>10-100
import { Hub } from '../../src/graflow'
describe('Hub', () => {
it('should return a component that emits an object with last input (name/value)', () => {
const hub = Hub('a', 'b')
const listener = spy()
hub.on(listener)
hub.send('a', 1)
expect(listener).to.have.been.calledOnce
expect(listener.getCall(0).args[0]).to.be.deep.equal({a: 1})
hub.send('b', 2)
expect(listener).to.have.been.calledTwice
expect(listener.getCall(1).args[0]).to.be.deep.equal({b: 2})
hub.send('a', 10)
expect(listener).to.have.been.calledThrice
expect(listener.getCall(2).args[0]).to.be.deep.equal({a: 10})
})
})
|
segfaultxavi/nem.core
|
src/test/java/org/nem/core/test/NotificationUtils.java
|
package org.nem.core.test;
import org.hamcrest.MatcherAssert;
import org.hamcrest.core.IsEqual;
import org.nem.core.model.*;
import org.nem.core.model.mosaic.*;
import org.nem.core.model.namespace.NamespaceId;
import org.nem.core.model.observers.*;
import org.nem.core.model.primitive.*;
import java.util.Collection;
/**
* Static class providing helper functions for creating and validating notifications.
*/
public class NotificationUtils {
// region notify *
/**
* Raises a credit notification on the specified observer.
*
* @param observer The observer.
* @param account The account.
* @param amount The amount.
*/
public static void notifyCredit(final TransactionObserver observer, final Account account, final Amount amount) {
observer.notify(new BalanceAdjustmentNotification(NotificationType.BalanceCredit, account, amount));
}
/**
* Raises a debit notification on the specified observer.
*
* @param observer The observer.
* @param account The account.
* @param amount The amount.
*/
public static void notifyDebit(final TransactionObserver observer, final Account account, final Amount amount) {
observer.notify(new BalanceAdjustmentNotification(NotificationType.BalanceDebit, account, amount));
}
/**
* Raises a balance transfer notification on the specified observer.
*
* @param observer The observer.
* @param sender The sender.
* @param recipient The recipient.
* @param amount The amount.
*/
public static void notifyTransfer(final TransactionObserver observer, final Account sender, final Account recipient,
final Amount amount) {
observer.notify(new BalanceTransferNotification(sender, recipient, amount));
}
// endregion
// region assert *
/**
* Asserts that the specified notification is an account notification.
*
* @param notification The notification to test.
* @param expectedAccount The expected account.
*/
public static void assertAccountNotification(final Notification notification, final Account expectedAccount) {
final AccountNotification n = (AccountNotification) notification;
MatcherAssert.assertThat(n.getType(), IsEqual.equalTo(NotificationType.Account));
MatcherAssert.assertThat(n.getAccount(), IsEqual.equalTo(expectedAccount));
}
/**
* Asserts that the specified notification is a balance credit notification.
*
* @param notification The notification to test.
* @param expectedAccount The expected account.
* @param expectedAmount The expected amount.
*/
public static void assertBalanceCreditNotification(final Notification notification, final Account expectedAccount,
final Amount expectedAmount) {
final BalanceAdjustmentNotification n = (BalanceAdjustmentNotification) notification;
MatcherAssert.assertThat(n.getType(), IsEqual.equalTo(NotificationType.BalanceCredit));
MatcherAssert.assertThat(n.getAccount(), IsEqual.equalTo(expectedAccount));
MatcherAssert.assertThat(n.getAmount(), IsEqual.equalTo(expectedAmount));
}
/**
* Asserts that the specified notification is a balance debit notification.
*
* @param notification The notification to test.
* @param expectedAccount The expected account.
* @param expectedAmount The expected amount.
*/
public static void assertBalanceDebitNotification(final Notification notification, final Account expectedAccount,
final Amount expectedAmount) {
final BalanceAdjustmentNotification n = (BalanceAdjustmentNotification) notification;
MatcherAssert.assertThat(n.getType(), IsEqual.equalTo(NotificationType.BalanceDebit));
MatcherAssert.assertThat(n.getAccount(), IsEqual.equalTo(expectedAccount));
MatcherAssert.assertThat(n.getAmount(), IsEqual.equalTo(expectedAmount));
}
/**
* Asserts that the specified notification is a block harvest notification.
*
* @param notification The notification to test.
* @param expectedAccount The expected account.
* @param expectedAmount The expected amount.
*/
public static void assertBlockHarvestNotification(final Notification notification, final Account expectedAccount,
final Amount expectedAmount) {
final BalanceAdjustmentNotification n = (BalanceAdjustmentNotification) notification;
MatcherAssert.assertThat(n.getType(), IsEqual.equalTo(NotificationType.BlockHarvest));
MatcherAssert.assertThat(n.getAccount(), IsEqual.equalTo(expectedAccount));
MatcherAssert.assertThat(n.getAmount(), IsEqual.equalTo(expectedAmount));
}
/**
* Asserts that the specified notification is a balance transfer notification.
*
* @param notification The notification to test.
* @param expectedSender The expected sender.
* @param expectedRecipient The expected recipient.
* @param expectedAmount The expected amount.
*/
public static void assertBalanceTransferNotification(final Notification notification, final Account expectedSender,
final Account expectedRecipient, final Amount expectedAmount) {
final BalanceTransferNotification n = (BalanceTransferNotification) notification;
MatcherAssert.assertThat(n.getType(), IsEqual.equalTo(NotificationType.BalanceTransfer));
MatcherAssert.assertThat(n.getSender(), IsEqual.equalTo(expectedSender));
MatcherAssert.assertThat(n.getRecipient(), IsEqual.equalTo(expectedRecipient));
MatcherAssert.assertThat(n.getAmount(), IsEqual.equalTo(expectedAmount));
}
/**
* Asserts that the specified notification is a mosaic transfer notification.
*
* @param notification The notification to test.
* @param expectedSender The expected sender.
* @param expectedRecipient The expected recipient.
* @param expectedMosaicId The expected mosaic id.
* @param expectedQuantity The expected quantity.
*/
public static void assertMosaicTransferNotification(final Notification notification, final Account expectedSender,
final Account expectedRecipient, final MosaicId expectedMosaicId, final Quantity expectedQuantity) {
final MosaicTransferNotification n = (MosaicTransferNotification) notification;
MatcherAssert.assertThat(n.getType(), IsEqual.equalTo(NotificationType.MosaicTransfer));
MatcherAssert.assertThat(n.getSender(), IsEqual.equalTo(expectedSender));
MatcherAssert.assertThat(n.getRecipient(), IsEqual.equalTo(expectedRecipient));
MatcherAssert.assertThat(n.getMosaicId(), IsEqual.equalTo(expectedMosaicId));
MatcherAssert.assertThat(n.getQuantity(), IsEqual.equalTo(expectedQuantity));
}
/**
* Asserts that the specified notification is a importance transfer notification.
*
* @param notification The notification to test.
* @param expectedLessor The expected lessor.
* @param expectedLessee The expected lessee.
* @param expectedMode The expected mode.
*/
public static void assertImportanceTransferNotification(final Notification notification, final Account expectedLessor,
final Account expectedLessee, final ImportanceTransferMode expectedMode) {
final ImportanceTransferNotification n = (ImportanceTransferNotification) notification;
MatcherAssert.assertThat(n.getType(), IsEqual.equalTo(NotificationType.ImportanceTransfer));
MatcherAssert.assertThat(n.getLessor(), IsEqual.equalTo(expectedLessor));
MatcherAssert.assertThat(n.getLessee(), IsEqual.equalTo(expectedLessee));
MatcherAssert.assertThat(n.getMode(), IsEqual.equalTo(expectedMode));
}
/**
* Asserts that the specified notification is a transaction hashes notification.
*
* @param notification The notification to test.
* @param pairs The expected transaction hashes.
*/
public static void assertTransactionHashesNotification(final Notification notification, final Collection<HashMetaDataPair> pairs) {
final TransactionHashesNotification n = (TransactionHashesNotification) notification;
MatcherAssert.assertThat(n.getType(), IsEqual.equalTo(NotificationType.TransactionHashes));
MatcherAssert.assertThat(n.getPairs(), IsEquivalent.equivalentTo(pairs));
}
/**
* Asserts that the specified notification is a cosignatory modification notification.
*
* @param notification The notification to test.
* @param expectedMultisig The expected multisig account.
* @param expectedModification The expected multisig cosignatory modification.
*/
public static void assertCosignatoryModificationNotification(final Notification notification, final Account expectedMultisig,
final MultisigCosignatoryModification expectedModification) {
final MultisigCosignatoryModificationNotification n = (MultisigCosignatoryModificationNotification) notification;
MatcherAssert.assertThat(n.getType(), IsEqual.equalTo(NotificationType.CosignatoryModification));
MatcherAssert.assertThat(n.getMultisigAccount(), IsEqual.equalTo(expectedMultisig));
MatcherAssert.assertThat(n.getModification(), IsEqual.equalTo(expectedModification));
}
/**
* Asserts that the specified notification is a minimum cosignatories modification notification.
*
* @param notification The notification to test.
* @param expectedMultisig The expected multisig account.
* @param expectedModification The expected multisig minimum cosignatories modification.
*/
public static void assertMinCosignatoriesModificationNotification(final Notification notification, final Account expectedMultisig,
final MultisigMinCosignatoriesModification expectedModification) {
final MultisigMinCosignatoriesModificationNotification n = (MultisigMinCosignatoriesModificationNotification) notification;
MatcherAssert.assertThat(n.getType(), IsEqual.equalTo(NotificationType.MinCosignatoriesModification));
MatcherAssert.assertThat(n.getMultisigAccount(), IsEqual.equalTo(expectedMultisig));
MatcherAssert.assertThat(n.getModification(), IsEqual.equalTo(expectedModification));
}
/**
* Asserts that the specified notification is a provision namespace notification.
*
* @param notification The notification to test.
* @param expectedOwner The expected owner.
* @param expectedNamespaceId The expected namespace id.
*/
public static void assertProvisionNamespaceNotification(final Notification notification, final Account expectedOwner,
final NamespaceId expectedNamespaceId) {
final ProvisionNamespaceNotification n = (ProvisionNamespaceNotification) notification;
MatcherAssert.assertThat(n.getType(), IsEqual.equalTo(NotificationType.ProvisionNamespace));
MatcherAssert.assertThat(n.getOwner(), IsEqual.equalTo(expectedOwner));
MatcherAssert.assertThat(n.getNamespaceId(), IsEqual.equalTo(expectedNamespaceId));
}
/**
* Asserts that the specified notification is a mosaic definition creation notification.
*
* @param notification The notification to test.
* @param expectedMosaicDefinition The expected mosaic definition.
*/
public static void assertMosaicDefinitionCreationNotification(final Notification notification,
final MosaicDefinition expectedMosaicDefinition) {
final MosaicDefinitionCreationNotification n = (MosaicDefinitionCreationNotification) notification;
MatcherAssert.assertThat(n.getType(), IsEqual.equalTo(NotificationType.MosaicDefinitionCreation));
MatcherAssert.assertThat(n.getMosaicDefinition().getCreator(), IsEqual.equalTo(expectedMosaicDefinition.getCreator()));
MatcherAssert.assertThat(n.getMosaicDefinition().getId(), IsEqual.equalTo(expectedMosaicDefinition.getId()));
MatcherAssert.assertThat(n.getMosaicDefinition().getDescriptor(), IsEqual.equalTo(expectedMosaicDefinition.getDescriptor()));
final MosaicProperties properties = n.getMosaicDefinition().getProperties();
final MosaicProperties expectedProperties = expectedMosaicDefinition.getProperties();
MatcherAssert.assertThat(properties.getDivisibility(), IsEqual.equalTo(expectedProperties.getDivisibility()));
MatcherAssert.assertThat(properties.getInitialSupply(), IsEqual.equalTo(expectedProperties.getInitialSupply()));
MatcherAssert.assertThat(properties.isSupplyMutable(), IsEqual.equalTo(expectedProperties.isSupplyMutable()));
MatcherAssert.assertThat(properties.isTransferable(), IsEqual.equalTo(expectedProperties.isTransferable()));
}
/**
* Asserts that the specified notification is a mosaic supply change notification.
*
* @param notification The notification to test.
* @param expectedSupplier The expected supplier.
* @param expectedMosaicId The expected mosaic id.
* @param expectedSupplyChange The expected supply change.
* @param expectedSupplyType The expected supply type.
*/
public static void assertMosaicSupplyChangeNotification(final Notification notification, final Account expectedSupplier,
final MosaicId expectedMosaicId, final Supply expectedSupplyChange, final MosaicSupplyType expectedSupplyType) {
final MosaicSupplyChangeNotification n = (MosaicSupplyChangeNotification) notification;
MatcherAssert.assertThat(n.getType(), IsEqual.equalTo(NotificationType.MosaicSupplyChange));
MatcherAssert.assertThat(n.getSupplier(), IsEqual.equalTo(expectedSupplier));
MatcherAssert.assertThat(n.getMosaicId(), IsEqual.equalTo(expectedMosaicId));
MatcherAssert.assertThat(n.getDelta(), IsEqual.equalTo(expectedSupplyChange));
MatcherAssert.assertThat(n.getSupplyType(), IsEqual.equalTo(expectedSupplyType));
}
// endregion
}
|
TingYunAPM/go
|
framework/gin/example/server_h/main.go
|
<reponame>TingYunAPM/go
package main
import (
"fmt"
"net/http"
"github.com/TingYunAPM/go"
"github.com/TingYunAPM/go/framework/gin"
"github.com/gin-gonic/gin"
)
func main() {
err := tingyun.AppInit("tingyun.json")
if err != nil {
fmt.Println(err)
}
defer tingyun.AppStop()
// router := gin.Default()
router := tingyun_gin.Default()
router.POST("/upload", func(c *gin.Context) {
// single file
file, _ := c.FormFile("file")
fmt.Println(file.Filename)
// Upload the file to specific dst.
// c.SaveUploadedFile(file, dst)
c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))
})
router.Run(":8026")
}
// curl -X POST http://127.0.0.1:8026/upload -F "file=@`pwd`/server_h/main.go"
|
troy0820/openshift-azure
|
vendor/github.com/openshift/origin/pkg/oc/cli/admin/diagnostics/diagnostics/cluster/aggregated_logging/serviceaccounts_test.go
|
<reponame>troy0820/openshift-azure<gh_stars>10-100
package aggregated_logging
import (
"errors"
"testing"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
kapi "k8s.io/kubernetes/pkg/apis/core"
"github.com/openshift/origin/pkg/oc/cli/admin/diagnostics/diagnostics/log"
)
type mockServiceAccountDiagnostic struct {
accounts kapi.ServiceAccountList
fakeDiagnostic
}
func newMockServiceAccountDiagnostic(t *testing.T) *mockServiceAccountDiagnostic {
return &mockServiceAccountDiagnostic{
accounts: kapi.ServiceAccountList{},
fakeDiagnostic: *newFakeDiagnostic(t),
}
}
func (m *mockServiceAccountDiagnostic) serviceAccounts(project string, options metav1.ListOptions) (*kapi.ServiceAccountList, error) {
if m.err != nil {
return &m.accounts, m.err
}
return &m.accounts, nil
}
func (d *mockServiceAccountDiagnostic) addServiceAccountNamed(name string) {
meta := metav1.ObjectMeta{Name: name}
d.accounts.Items = append(d.accounts.Items, kapi.ServiceAccount{ObjectMeta: meta})
}
func TestCheckingServiceAccountsWhenFailedResponseFromClient(t *testing.T) {
d := newMockServiceAccountDiagnostic(t)
d.err = errors.New("Some Error")
checkServiceAccounts(d, d, fakeProject)
d.assertMessage("AGL0505",
"Exp an error when unable to retrieve service accounts because of a client error",
log.ErrorLevel)
}
func TestCheckingServiceAccountsWhenMissingExpectedServiceAccount(t *testing.T) {
d := newMockServiceAccountDiagnostic(t)
d.addServiceAccountNamed("foobar")
checkServiceAccounts(d, d, fakeProject)
d.assertMessage("AGL0515",
"Exp an error when an expected service account was not found.",
log.ErrorLevel)
}
func TestCheckingServiceAccountsIsOk(t *testing.T) {
d := newMockServiceAccountDiagnostic(t)
for _, name := range serviceAccountNames.List() {
d.addServiceAccountNamed(name)
}
checkServiceAccounts(d, d, fakeProject)
d.assertNoErrors()
}
|
sohaniwso2/carbon-registry-1
|
components/registry/org.wso2.carbon.registry.resource.ui/src/main/java/org/wso2/carbon/registry/resource/ui/CommandHandler.java
|
/*
* Copyright (c) 2006, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.registry.resource.ui;
import org.wso2.carbon.registry.resource.ui.processors.SetDescriptionProcessor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletConfig;
import java.util.Map;
import java.util.HashMap;
public class CommandHandler {
private static Map <String, UIProcessor> processors = new HashMap <String, UIProcessor> ();
private static boolean initiated = false;
public static String process(
HttpServletRequest request, HttpServletResponse response, ServletConfig config)
throws Exception {
synchronized (processors) {
if (!initiated) {
initiated = true;
init();
}
}
String command = request.getParameter("command");
UIProcessor processor = processors.get(command);
return processor.process(request, response, config);
}
public static void init() {
//processors.put("set.description", new SetDescriptionProcessor());
}
}
|
spheenik/clarity
|
src/main/java/skadistats/clarity/processor/sendtables/FieldGenerator.java
|
package skadistats.clarity.processor.sendtables;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntSet;
import org.slf4j.Logger;
import skadistats.clarity.io.s2.Field;
import skadistats.clarity.io.s2.FieldType;
import skadistats.clarity.io.s2.S2DTClass;
import skadistats.clarity.io.s2.S2DecoderFactory;
import skadistats.clarity.io.s2.Serializer;
import skadistats.clarity.io.s2.SerializerId;
import skadistats.clarity.io.s2.field.ArrayField;
import skadistats.clarity.io.s2.field.VectorField;
import skadistats.clarity.io.s2.field.PointerField;
import skadistats.clarity.io.s2.field.SerializerField;
import skadistats.clarity.io.s2.field.ValueField;
import skadistats.clarity.logger.PrintfLoggerFactory;
import skadistats.clarity.model.BuildNumberRange;
import skadistats.clarity.wire.s2.proto.S2NetMessages;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static skadistats.clarity.LogChannel.sendtables;
public class FieldGenerator {
private final Logger log = PrintfLoggerFactory.getLogger(sendtables);
private final S2NetMessages.CSVCMsg_FlattenedSerializer protoMessage;
private final FieldData[] fieldData;
private final IntSet checkedNames;
private final List<PatchFunc> patchFuncs;
private final Map<SerializerId, Serializer> serializers = new HashMap<>();
public FieldGenerator(S2NetMessages.CSVCMsg_FlattenedSerializer protoMessage, int buildNumber) {
this.protoMessage = protoMessage;
this.fieldData = new FieldData[protoMessage.getFieldsCount()];
this.checkedNames = new IntOpenHashSet();
this.patchFuncs = new ArrayList<>();
for (Map.Entry<BuildNumberRange, PatchFunc> patchEntry : PATCHES.entrySet()) {
if (patchEntry.getKey().appliesTo(buildNumber)) {
this.patchFuncs.add(patchEntry.getValue());
}
}
}
public void createFields() {
for (int i = 0; i < fieldData.length; i++) {
fieldData[i] = generateFieldData(protoMessage.getFields(i));
}
for (int i = 0; i < protoMessage.getSerializersCount(); i++) {
Serializer serializer = generateSerializer(protoMessage.getSerializers(i));
serializers.put(serializer.getId(), serializer);
}
}
public S2DTClass createDTClass(String name) {
SerializerField field = new SerializerField(
FieldType.forString(name),
serializers.get(new SerializerId(name, 0))
);
return new S2DTClass(field);
}
private FieldData generateFieldData(S2NetMessages.ProtoFlattenedSerializerField_t proto) {
return new FieldData(
FieldType.forString(sym(proto.getVarTypeSym())),
fieldNameFunction(proto),
new ProtoDecoderProperties(
proto.hasEncodeFlags() ? proto.getEncodeFlags() : null,
proto.hasBitCount() ? proto.getBitCount() : null,
proto.hasLowValue() ? proto.getLowValue() : null,
proto.hasHighValue() ? proto.getHighValue() : null,
proto.hasVarEncoderSym() ? sym(proto.getVarEncoderSym()) : null
),
proto.hasFieldSerializerNameSym() ?
new SerializerId(
sym(proto.getFieldSerializerNameSym()),
proto.getFieldSerializerVersion()
) : null
);
}
private Serializer generateSerializer(S2NetMessages.ProtoFlattenedSerializer_t proto) {
SerializerId sid = new SerializerId(
sym(proto.getSerializerNameSym()),
proto.getSerializerVersion()
);
Field[] fields = new Field[proto.getFieldsIndexCount()];
String[] fieldNames = new String[proto.getFieldsIndexCount()];
for (int i = 0; i < fields.length; i++) {
int fi = proto.getFieldsIndex(i);
if (fieldData[fi].field == null) {
fieldData[fi].field = createField(sid, fieldData[fi]);
}
fields[i] = fieldData[fi].field;
fieldNames[i] = fieldData[fi].name;
}
return new Serializer(sid, fields, fieldNames);
}
private Field createField(SerializerId sId, FieldData fd) {
for (PatchFunc patchFunc : patchFuncs) {
patchFunc.execute(sId, fd);
}
FieldType elementType;
switch (fd.category) {
case ARRAY:
elementType = fd.fieldType.getElementType();
break;
case VECTOR:
elementType = fd.fieldType.getGenericType();
break;
default:
elementType = fd.fieldType;
}
Field elementField;
if (fd.serializerId != null) {
if (fd.category == FieldCategory.POINTER) {
elementField = new PointerField(
elementType,
serializers.get(fd.serializerId)
);
} else {
elementField = new SerializerField(
elementType,
serializers.get(fd.serializerId)
);
}
} else {
elementField = new ValueField(
elementType,
S2DecoderFactory.createDecoder(fd.decoderProperties, elementType.getBaseType())
);
}
switch (fd.category) {
case ARRAY:
return new ArrayField(
fd.fieldType,
elementField,
fd.getArrayElementCount()
);
case VECTOR:
return new VectorField(
fd.fieldType,
elementField
);
default:
return elementField;
}
}
private String sym(int i) {
return protoMessage.getSymbols(i);
}
private String fieldNameFunction(S2NetMessages.ProtoFlattenedSerializerField_t field) {
int nameSym = field.getVarNameSym();
String name = sym(nameSym);
if (!checkedNames.contains(nameSym)) {
if (name.indexOf('.') != -1) {
log.warn("replay contains field with invalid name '%s'. Please open a github issue!", name);
}
checkedNames.add(nameSym);
}
return name;
}
private enum FieldCategory {
POINTER,
VECTOR,
ARRAY,
VALUE
}
private static class FieldData {
private final FieldType fieldType;
private final String name;
private final ProtoDecoderProperties decoderProperties;
private final SerializerId serializerId;
private final FieldCategory category;
private Field field;
public FieldData(FieldType fieldType, String name, ProtoDecoderProperties decoderProperties, SerializerId serializerId) {
this.fieldType = fieldType;
this.name = name;
this.decoderProperties = decoderProperties;
this.serializerId = serializerId;
if (determineIsPointer()) {
category = FieldCategory.POINTER;
} else if (determineIsVector()) {
category = FieldCategory.VECTOR;
} else if (determineIsArray()) {
category = FieldCategory.ARRAY;
} else {
category = FieldCategory.VALUE;
}
}
private boolean determineIsPointer() {
if (fieldType.isPointer()) return true;
switch (fieldType.getBaseType()) {
case "CBodyComponent":
case "CLightComponent":
case "CPhysicsComponent":
case "CRenderComponent":
case "CPlayerLocalData":
return true;
}
return false;
}
private boolean determineIsVector() {
if (serializerId != null) return true;
switch(fieldType.getBaseType()) {
case "CUtlVector":
case "CNetworkUtlVectorBase":
return true;
default:
return false;
}
}
private boolean determineIsArray() {
return fieldType.getElementCount() != null && !"char".equals(fieldType.getBaseType());
}
private int getArrayElementCount() {
String elementCount = fieldType.getElementCount();
switch (elementCount) {
case "MAX_ITEM_STOCKS":
return 8;
case "MAX_ABILITY_DRAFT_ABILITIES":
return 48;
default:
return Integer.parseInt(elementCount);
}
}
}
private static final SerializerId SID_PITCH_YAW = new SerializerId("CBodyComponentBaseAnimatingOverlay", 3);
private interface PatchFunc {
void execute(SerializerId serializerId, FieldData field);
}
private static final Map<BuildNumberRange, PatchFunc> PATCHES = new LinkedHashMap<>();
static {
PATCHES.put(new BuildNumberRange(null, 954), (serializerId, field) -> {
switch (field.name) {
case "m_flMana":
case "m_flMaxMana":
ProtoDecoderProperties up = field.decoderProperties;
if (up.highValue == 3.4028235E38f) {
up.lowValue = null;
up.highValue = 8192.0f;
}
}
});
PATCHES.put(new BuildNumberRange(null, 990), (serializerId, field) -> {
switch (field.name) {
case "dirPrimary":
case "localSound":
case "m_attachmentPointBoneSpace":
case "m_attachmentPointRagdollSpace":
case "m_flElasticity":
case "m_location":
case "m_poolOrigin":
case "m_ragPos":
case "m_vecEndPos":
case "m_vecEyeExitEndpoint":
case "m_vecGunCrosshair":
case "m_vecLadderDir":
case "m_vecPlayerMountPositionBottom":
case "m_vecPlayerMountPositionTop":
case "m_viewtarget":
case "m_WorldMaxs":
case "m_WorldMins":
case "origin":
case "vecExtraLocalOrigin":
case "vecLocalOrigin":
field.decoderProperties.encoderType = "coord";
break;
case "angExtraLocalAngles":
case "angLocalAngles":
case "m_angInitialAngles":
case "m_ragAngles":
case "m_vLightDirection":
field.decoderProperties.encoderType = "QAngle";
break;
case "m_vecLadderNormal":
field.decoderProperties.encoderType = "normal";
break;
case "m_angRotation":
field.decoderProperties.encoderType = SID_PITCH_YAW.equals(serializerId) ? "qangle_pitch_yaw" : "QAngle";
break;
}
});
PATCHES.put(new BuildNumberRange(1016, 1026), (serializerId, field) -> {
switch (field.name) {
case "m_bWorldTreeState":
case "m_ulTeamLogo":
case "m_ulTeamBaseLogo":
case "m_ulTeamBannerLogo":
case "m_iPlayerIDsInControl":
case "m_bItemWhiteList":
case "m_iPlayerSteamID":
field.decoderProperties.encoderType = "fixed64";
}
});
PATCHES.put(new BuildNumberRange(null, null), (serializerId, field) -> {
switch (field.name) {
case "m_flSimulationTime":
case "m_flAnimTime":
field.decoderProperties.encoderType = "simulationtime";
}
});
PATCHES.put(new BuildNumberRange(null, null), (serializerId, field) -> {
switch (field.name) {
case "m_flRuneTime":
ProtoDecoderProperties up = field.decoderProperties;
if (up.highValue == Float.MAX_VALUE && up.lowValue == -Float.MAX_VALUE) {
up.lowValue = null;
up.highValue = null;
}
}
});
}
}
|
Devteamvietnam/iTap
|
src/main/java/com/devteam/module/customer/entity/Address.java
|
<gh_stars>1-10
package com.devteam.module.customer.entity;
import com.fasterxml.jackson.annotation.JsonBackReference;
import lombok.*;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
@Getter
@Setter
@NoArgsConstructor
@RequiredArgsConstructor
@Entity
@Table(name = "address")
public class Address {
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
private String id;
private String streetAddress;
private @NonNull String city;
private @NonNull String stateCode;
private @NonNull String country;
private @NonNull String zipCode;
@ManyToOne
@JsonBackReference
private Customer customer;
}
|
wahello/openshift-installer
|
terraform/aws/vendor/github.com/hashicorp/terraform-provider-aws/internal/service/servicediscovery/service.go
|
package servicediscovery
import (
"fmt"
"log"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/servicediscovery"
"github.com/hashicorp/aws-sdk-go-base/tfawserr"
multierror "github.com/hashicorp/go-multierror"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/hashicorp/terraform-provider-aws/internal/conns"
tftags "github.com/hashicorp/terraform-provider-aws/internal/tags"
"github.com/hashicorp/terraform-provider-aws/internal/tfresource"
"github.com/hashicorp/terraform-provider-aws/internal/verify"
)
func ResourceService() *schema.Resource {
return &schema.Resource{
Create: resourceServiceCreate,
Read: resourceServiceRead,
Update: resourceServiceUpdate,
Delete: resourceServiceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"arn": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"dns_config": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"dns_records": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"ttl": {
Type: schema.TypeInt,
Required: true,
},
"type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice(servicediscovery.RecordType_Values(), false),
},
},
},
},
"namespace_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"routing_policy": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: servicediscovery.RoutingPolicyMultivalue,
ValidateFunc: validation.StringInSlice(servicediscovery.RoutingPolicy_Values(), false),
},
},
},
},
"force_destroy": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"health_check_config": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"failure_threshold": {
Type: schema.TypeInt,
Optional: true,
},
"resource_path": {
Type: schema.TypeString,
Optional: true,
},
"type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice(servicediscovery.HealthCheckType_Values(), false),
},
},
},
},
"health_check_custom_config": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"failure_threshold": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
},
},
},
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"namespace_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"tags": tftags.TagsSchema(),
"tags_all": tftags.TagsSchemaComputed(),
},
CustomizeDiff: verify.SetTagsDiff,
}
}
func resourceServiceCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*conns.AWSClient).ServiceDiscoveryConn
defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig
tags := defaultTagsConfig.MergeTags(tftags.New(d.Get("tags").(map[string]interface{})))
name := d.Get("name").(string)
input := &servicediscovery.CreateServiceInput{
CreatorRequestId: aws.String(resource.UniqueId()),
Name: aws.String(name),
}
if v, ok := d.GetOk("description"); ok {
input.Description = aws.String(v.(string))
}
if v, ok := d.GetOk("dns_config"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil {
input.DnsConfig = expandServiceDiscoveryDnsConfig(v.([]interface{})[0].(map[string]interface{}))
}
if v, ok := d.GetOk("health_check_config"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil {
input.HealthCheckConfig = expandServiceDiscoveryHealthCheckConfig(v.([]interface{})[0].(map[string]interface{}))
}
if v, ok := d.GetOk("health_check_custom_config"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil {
input.HealthCheckCustomConfig = expandServiceDiscoveryHealthCheckCustomConfig(v.([]interface{})[0].(map[string]interface{}))
}
if v, ok := d.GetOk("namespace_id"); ok {
input.NamespaceId = aws.String(v.(string))
}
if len(tags) > 0 {
input.Tags = Tags(tags.IgnoreAWS())
}
log.Printf("[DEBUG] Creating Service Discovery Service: %s", input)
output, err := conn.CreateService(input)
if err != nil {
return fmt.Errorf("error creating Service Discovery Service (%s): %w", name, err)
}
d.SetId(aws.StringValue(output.Service.Id))
return resourceServiceRead(d, meta)
}
func resourceServiceRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*conns.AWSClient).ServiceDiscoveryConn
defaultTagsConfig := meta.(*conns.AWSClient).DefaultTagsConfig
ignoreTagsConfig := meta.(*conns.AWSClient).IgnoreTagsConfig
service, err := FindServiceByID(conn, d.Id())
if !d.IsNewResource() && tfresource.NotFound(err) {
log.Printf("[WARN] Service Discovery Service (%s) not found, removing from state", d.Id())
d.SetId("")
return nil
}
if err != nil {
return fmt.Errorf("error reading Service Discovery Service (%s): %w", d.Id(), err)
}
arn := aws.StringValue(service.Arn)
d.Set("arn", arn)
d.Set("description", service.Description)
if err := d.Set("dns_config", flattenServiceDiscoveryDnsConfig(service.DnsConfig)); err != nil {
return fmt.Errorf("error setting dns_config: %w", err)
}
if err := d.Set("health_check_config", flattenServiceDiscoveryHealthCheckConfig(service.HealthCheckConfig)); err != nil {
return fmt.Errorf("error setting health_check_config: %w", err)
}
if err := d.Set("health_check_custom_config", flattenServiceDiscoveryHealthCheckCustomConfig(service.HealthCheckCustomConfig)); err != nil {
return fmt.Errorf("error setting health_check_custom_config: %w", err)
}
d.Set("name", service.Name)
d.Set("namespace_id", service.NamespaceId)
tags, err := ListTags(conn, arn)
if err != nil {
return fmt.Errorf("error listing tags for resource (%s): %w", arn, err)
}
tags = tags.IgnoreAWS().IgnoreConfig(ignoreTagsConfig)
//lintignore:AWSR002
if err := d.Set("tags", tags.RemoveDefaultConfig(defaultTagsConfig).Map()); err != nil {
return fmt.Errorf("error setting tags: %w", err)
}
if err := d.Set("tags_all", tags.Map()); err != nil {
return fmt.Errorf("error setting tags_all: %w", err)
}
return nil
}
func resourceServiceUpdate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*conns.AWSClient).ServiceDiscoveryConn
if d.HasChangesExcept("tags", "tags_all") {
input := &servicediscovery.UpdateServiceInput{
Id: aws.String(d.Id()),
Service: &servicediscovery.ServiceChange{
Description: aws.String(d.Get("description").(string)),
},
}
if v, ok := d.GetOk("dns_config"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil {
input.Service.DnsConfig = expandServiceDiscoveryDnsConfigChange(v.([]interface{})[0].(map[string]interface{}))
}
if v, ok := d.GetOk("health_check_config"); ok && len(v.([]interface{})) > 0 && v.([]interface{})[0] != nil {
input.Service.HealthCheckConfig = expandServiceDiscoveryHealthCheckConfig(v.([]interface{})[0].(map[string]interface{}))
}
output, err := conn.UpdateService(input)
if err != nil {
return fmt.Errorf("error updating Service Discovery Service (%s): %w", d.Id(), err)
}
if output != nil && output.OperationId != nil {
if _, err := WaitOperationSuccess(conn, aws.StringValue(output.OperationId)); err != nil {
return fmt.Errorf("error waiting for Service Discovery Service (%s) update: %w", d.Id(), err)
}
}
}
if d.HasChange("tags_all") {
o, n := d.GetChange("tags_all")
if err := UpdateTags(conn, d.Get("arn").(string), o, n); err != nil {
return fmt.Errorf("error updating Service Discovery Service (%s) tags: %s", d.Id(), err)
}
}
return resourceServiceRead(d, meta)
}
func resourceServiceDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*conns.AWSClient).ServiceDiscoveryConn
if d.Get("force_destroy").(bool) {
input := &servicediscovery.ListInstancesInput{
ServiceId: aws.String(d.Id()),
}
var deletionErrs *multierror.Error
err := conn.ListInstancesPages(input, func(page *servicediscovery.ListInstancesOutput, lastPage bool) bool {
if page == nil {
return !lastPage
}
for _, instance := range page.Instances {
err := deregisterServiceDiscoveryInstance(conn, d.Id(), aws.StringValue(instance.Id))
if err != nil {
log.Printf("[ERROR] %s", err)
deletionErrs = multierror.Append(deletionErrs, err)
continue
}
}
return !lastPage
})
if err != nil {
deletionErrs = multierror.Append(deletionErrs, fmt.Errorf("error listing Service Discovery Instances: %w", err))
}
err = deletionErrs.ErrorOrNil()
if err != nil {
return err
}
}
log.Printf("[DEBUG] Deleting Service Discovery Service: (%s)", d.Id())
_, err := conn.DeleteService(&servicediscovery.DeleteServiceInput{
Id: aws.String(d.Id()),
})
if tfawserr.ErrCodeEquals(err, servicediscovery.ErrCodeServiceNotFound) {
return nil
}
if err != nil {
return fmt.Errorf("error deleting Service Discovery Service (%s): %w", d.Id(), err)
}
return nil
}
func expandServiceDiscoveryDnsConfig(configured map[string]interface{}) *servicediscovery.DnsConfig {
result := &servicediscovery.DnsConfig{}
result.NamespaceId = aws.String(configured["namespace_id"].(string))
dnsRecords := configured["dns_records"].([]interface{})
drs := make([]*servicediscovery.DnsRecord, len(dnsRecords))
for i := range drs {
raw := dnsRecords[i].(map[string]interface{})
dr := &servicediscovery.DnsRecord{
TTL: aws.Int64(int64(raw["ttl"].(int))),
Type: aws.String(raw["type"].(string)),
}
drs[i] = dr
}
result.DnsRecords = drs
if v, ok := configured["routing_policy"]; ok && v != "" {
result.RoutingPolicy = aws.String(v.(string))
}
return result
}
func flattenServiceDiscoveryDnsConfig(config *servicediscovery.DnsConfig) []map[string]interface{} {
if config == nil {
return nil
}
result := map[string]interface{}{}
if config.NamespaceId != nil {
result["namespace_id"] = *config.NamespaceId
}
if config.RoutingPolicy != nil {
result["routing_policy"] = *config.RoutingPolicy
}
if config.DnsRecords != nil {
drs := make([]map[string]interface{}, 0)
for _, v := range config.DnsRecords {
dr := map[string]interface{}{}
dr["ttl"] = *v.TTL
dr["type"] = *v.Type
drs = append(drs, dr)
}
result["dns_records"] = drs
}
if len(result) < 1 {
return nil
}
return []map[string]interface{}{result}
}
func expandServiceDiscoveryDnsConfigChange(configured map[string]interface{}) *servicediscovery.DnsConfigChange {
result := &servicediscovery.DnsConfigChange{}
dnsRecords := configured["dns_records"].([]interface{})
drs := make([]*servicediscovery.DnsRecord, len(dnsRecords))
for i := range drs {
raw := dnsRecords[i].(map[string]interface{})
dr := &servicediscovery.DnsRecord{
TTL: aws.Int64(int64(raw["ttl"].(int))),
Type: aws.String(raw["type"].(string)),
}
drs[i] = dr
}
result.DnsRecords = drs
return result
}
func expandServiceDiscoveryHealthCheckConfig(configured map[string]interface{}) *servicediscovery.HealthCheckConfig {
if len(configured) < 1 {
return nil
}
result := &servicediscovery.HealthCheckConfig{}
if v, ok := configured["failure_threshold"]; ok && v.(int) != 0 {
result.FailureThreshold = aws.Int64(int64(v.(int)))
}
if v, ok := configured["resource_path"]; ok && v.(string) != "" {
result.ResourcePath = aws.String(v.(string))
}
if v, ok := configured["type"]; ok && v.(string) != "" {
result.Type = aws.String(v.(string))
}
return result
}
func flattenServiceDiscoveryHealthCheckConfig(config *servicediscovery.HealthCheckConfig) []map[string]interface{} {
if config == nil {
return nil
}
result := map[string]interface{}{}
if config.FailureThreshold != nil {
result["failure_threshold"] = *config.FailureThreshold
}
if config.ResourcePath != nil {
result["resource_path"] = *config.ResourcePath
}
if config.Type != nil {
result["type"] = *config.Type
}
if len(result) < 1 {
return nil
}
return []map[string]interface{}{result}
}
func expandServiceDiscoveryHealthCheckCustomConfig(configured map[string]interface{}) *servicediscovery.HealthCheckCustomConfig {
if len(configured) < 1 {
return nil
}
result := &servicediscovery.HealthCheckCustomConfig{}
if v, ok := configured["failure_threshold"]; ok && v.(int) != 0 {
result.FailureThreshold = aws.Int64(int64(v.(int)))
}
return result
}
func flattenServiceDiscoveryHealthCheckCustomConfig(config *servicediscovery.HealthCheckCustomConfig) []map[string]interface{} {
if config == nil {
return nil
}
result := map[string]interface{}{}
if config.FailureThreshold != nil {
result["failure_threshold"] = *config.FailureThreshold
}
if len(result) < 1 {
return nil
}
return []map[string]interface{}{result}
}
func deregisterServiceDiscoveryInstance(conn *servicediscovery.ServiceDiscovery, serviceID, instanceID string) error {
input := &servicediscovery.DeregisterInstanceInput{
InstanceId: aws.String(instanceID),
ServiceId: aws.String(serviceID),
}
log.Printf("[INFO] Deregistering Service Discovery Service (%s) Instance: %s", serviceID, instanceID)
output, err := conn.DeregisterInstance(input)
if err != nil {
return fmt.Errorf("error deregistering Service Discovery Service (%s) Instance (%s): %w", serviceID, instanceID, err)
}
if output != nil && output.OperationId != nil {
if _, err := WaitOperationSuccess(conn, aws.StringValue(output.OperationId)); err != nil {
return fmt.Errorf("error waiting for Service Discovery Service (%s) Instance (%s) deregister: %w", serviceID, instanceID, err)
}
}
return nil
}
|
Newcoin-Foundation/iosdk
|
dist/overmind/api/index.js
|
<reponame>Newcoin-Foundation/iosdk<filename>dist/overmind/api/index.js<gh_stars>0
import actions from "./actions";
import effects from "./effects";
import state from "./state";
export default {
actions,
effects,
state
};
//# sourceMappingURL=index.js.map
|
Ssstlis/izumi
|
distage/distage-core-api/src/main/scala/izumi/distage/model/planning/PlanningObserver.scala
|
<gh_stars>100-1000
package izumi.distage.model.planning
import izumi.distage.model.PlannerInput
import izumi.distage.model.plan.ExecutableOp
import izumi.distage.model.reflection.DIKey
import izumi.fundamentals.graphs.DG
import izumi.fundamentals.platform.language.unused
/**
* Execute side-effects to observe planning algorithm execution, e.g. log, write GraphViz files, etc.
*
* @see GraphDumpObserver
*/
trait PlanningObserver {
def onPlanningFinished(@unused input: PlannerInput, @unused plan: DG[DIKey, ExecutableOp]): Unit = {}
}
|
sergey-plevako-badoo/FBSimulatorControl
|
FBSimulatorControl/Events/FBSimulatorLoggingEventSink.h
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#import <Foundation/Foundation.h>
#import <FBSimulatorControl/FBSimulatorEventSink.h>
@class FBSimulator;
NS_ASSUME_NONNULL_BEGIN
/**
An Event Relay that writes messages to a logger.
*/
@interface FBSimulatorLoggingEventSink : NSObject <FBSimulatorEventSink>
/**
Creates a new Logging Event Sink for the provided Simulator.
@param simulator the Simulator to log events for. Will not be retained. Must not be nil.
@param logger the Logger to write messages to. May be nil.
@return a new FBSimulatorLoggingEventSink instance.
*/
+ (instancetype)withSimulator:(FBSimulator *)simulator logger:(nullable id<FBControlCoreLogger>)logger;
@end
NS_ASSUME_NONNULL_END
|
zack-vii/mdsplus
|
java/jdevices/src/main/java/ZELOS2150GVSetup.java
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* ZELOS2150GVSetup.java
*
* Created on Nov 9, 2011, 11:23:55 AM
*/
/**
*
* @author F.Molon
*/
public class ZELOS2150GVSetup extends DeviceSetup {
/** Creates new form ZELOS2150GVSetup */
public ZELOS2150GVSetup() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
deviceButtons1 = new DeviceButtons();
jPanel1 = new javax.swing.JPanel();
jPanel8 = new javax.swing.JPanel();
deviceField16 = new DeviceField();
deviceField17 = new DeviceField();
deviceDispatch1 = new DeviceDispatch();
jPanel2 = new javax.swing.JPanel();
deviceChoice1 = new DeviceChoice();
deviceField1 = new DeviceField();
deviceField2 = new DeviceField();
jPanel3 = new javax.swing.JPanel();
deviceChoice2 = new DeviceChoice();
deviceField3 = new DeviceField();
deviceChoice3 = new DeviceChoice();
jPanel4 = new javax.swing.JPanel();
deviceChoice4 = new DeviceChoice();
deviceField4 = new DeviceField();
deviceField5 = new DeviceField();
jPanel5 = new javax.swing.JPanel();
deviceField6 = new DeviceField();
deviceField7 = new DeviceField();
deviceField8 = new DeviceField();
deviceField9 = new DeviceField();
jPanel6 = new javax.swing.JPanel();
deviceField10 = new DeviceField();
deviceField11 = new DeviceField();
deviceField12 = new DeviceField();
deviceField13 = new DeviceField();
jPanel7 = new javax.swing.JPanel();
deviceField14 = new DeviceField();
deviceField15 = new DeviceField();
jPanel9 = new javax.swing.JPanel();
deviceChoice5 = new DeviceChoice();
deviceField18 = new DeviceField();
jPanel20 = new javax.swing.JPanel();
deviceChoice8 = new DeviceChoice();
deviceField19 = new DeviceField();
deviceField20 = new DeviceField();
setDeviceProvider("localhost");
setDeviceTitle("Zelos 2150 GV Camera Device");
setDeviceType("ZELOS2150GV");
setHeight(600);
setWidth(700);
getContentPane().add(deviceButtons1, java.awt.BorderLayout.PAGE_END);
jPanel1.setLayout(new java.awt.GridLayout(9, 0));
deviceField16.setIdentifier("");
deviceField16.setLabelString("Name: ");
deviceField16.setOffsetNid(1);
deviceField16.setTextOnly(true);
jPanel8.add(deviceField16);
deviceField17.setIdentifier("");
deviceField17.setLabelString("Comment:");
deviceField17.setNumCols(15);
deviceField17.setOffsetNid(2);
jPanel8.add(deviceField17);
jPanel8.add(deviceDispatch1);
jPanel1.add(jPanel8);
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Exposure"));
deviceChoice1.setChoiceItems(new String[] {"YES", "NO"});
deviceChoice1.setIdentifier("");
deviceChoice1.setLabelString("Automatic: ");
deviceChoice1.setOffsetNid(5);
deviceChoice1.setUpdateIdentifier("");
jPanel2.add(deviceChoice1);
deviceField1.setIdentifier("");
deviceField1.setLabelString("Exp. Time[s]: ");
deviceField1.setNumCols(4);
deviceField1.setOffsetNid(4);
jPanel2.add(deviceField1);
deviceField2.setIdentifier("");
deviceField2.setLabelString("Exp. Level[0-255]: ");
deviceField2.setNumCols(4);
deviceField2.setOffsetNid(6);
jPanel2.add(deviceField2);
jPanel1.add(jPanel2);
jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Gain"));
deviceChoice2.setChoiceItems(new String[] {"YES", "NO"});
deviceChoice2.setIdentifier("");
deviceChoice2.setLabelString("Automatic: ");
deviceChoice2.setOffsetNid(7);
deviceChoice2.setUpdateIdentifier("");
jPanel3.add(deviceChoice2);
deviceField3.setIdentifier("");
deviceField3.setLabelString("Gain[0-511]: ");
deviceField3.setNumCols(4);
deviceField3.setOffsetNid(8);
jPanel3.add(deviceField3);
deviceChoice3.setChoiceItems(new String[] {"YES", "NO"});
deviceChoice3.setIdentifier("");
deviceChoice3.setLabelString("Slow Scan: ");
deviceChoice3.setOffsetNid(9);
deviceChoice3.setUpdateIdentifier("");
jPanel3.add(deviceChoice3);
jPanel1.add(jPanel3);
jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Synchronization"));
deviceChoice4.setChoiceItems(new String[] {"INTERNAL", "EXTERNAL"});
deviceChoice4.setIdentifier("");
deviceChoice4.setLabelString("Synch.:");
deviceChoice4.setOffsetNid(20);
deviceChoice4.setUpdateIdentifier("");
jPanel4.add(deviceChoice4);
deviceField4.setIdentifier("");
deviceField4.setLabelString("Int. Period[s]:");
deviceField4.setNumCols(4);
deviceField4.setOffsetNid(21);
jPanel4.add(deviceField4);
deviceField5.setIdentifier("");
deviceField5.setLabelString("Ext. Timebase: ");
deviceField5.setNumCols(20);
deviceField5.setOffsetNid(22);
jPanel4.add(deviceField5);
jPanel1.add(jPanel4);
jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Frame Area: "));
deviceField6.setIdentifier("");
deviceField6.setLabelString("Start X:");
deviceField6.setNumCols(4);
deviceField6.setOffsetNid(10);
jPanel5.add(deviceField6);
deviceField7.setIdentifier("");
deviceField7.setLabelString("Start Y:");
deviceField7.setNumCols(4);
deviceField7.setOffsetNid(11);
jPanel5.add(deviceField7);
deviceField8.setIdentifier("");
deviceField8.setLabelString("Width: ");
deviceField8.setNumCols(4);
deviceField8.setOffsetNid(12);
jPanel5.add(deviceField8);
deviceField9.setIdentifier("");
deviceField9.setLabelString("Height: ");
deviceField9.setNumCols(4);
deviceField9.setOffsetNid(13);
jPanel5.add(deviceField9);
jPanel1.add(jPanel5);
jPanel5.getAccessibleContext().setAccessibleName("Frame Area");
jPanel6.setBorder(javax.swing.BorderFactory.createTitledBorder("Measure Area: "));
deviceField10.setIdentifier("");
deviceField10.setLabelString("Start X:");
deviceField10.setNumCols(4);
deviceField10.setOffsetNid(14);
jPanel6.add(deviceField10);
deviceField11.setIdentifier("");
deviceField11.setLabelString("Start Y:");
deviceField11.setNumCols(4);
deviceField11.setOffsetNid(15);
jPanel6.add(deviceField11);
deviceField12.setIdentifier("");
deviceField12.setLabelString("Width: ");
deviceField12.setNumCols(4);
deviceField12.setOffsetNid(16);
jPanel6.add(deviceField12);
deviceField13.setIdentifier("");
deviceField13.setLabelString("Height: ");
deviceField13.setNumCols(4);
deviceField13.setOffsetNid(17);
jPanel6.add(deviceField13);
jPanel1.add(jPanel6);
jPanel6.getAccessibleContext().setAccessibleName("Measure Area");
jPanel7.setBorder(javax.swing.BorderFactory.createTitledBorder("Binning"));
deviceField14.setIdentifier("");
deviceField14.setLabelString("Horizontal[1-8]:");
deviceField14.setNumCols(4);
deviceField14.setOffsetNid(19);
jPanel7.add(deviceField14);
deviceField15.setIdentifier("");
deviceField15.setLabelString("Vertical[1-8]:");
deviceField15.setNumCols(4);
deviceField15.setOffsetNid(18);
jPanel7.add(deviceField15);
jPanel1.add(jPanel7);
jPanel9.setBorder(javax.swing.BorderFactory.createTitledBorder("Data Storage and Streaming"));
deviceChoice5.setChoiceItems(new String[] {"Stream and Store", "Only Stream", "Only Store"});
deviceChoice5.setIdentifier("");
deviceChoice5.setLabelString("Enable:");
deviceChoice5.setOffsetNid(24);
deviceChoice5.setUpdateIdentifier("");
jPanel9.add(deviceChoice5);
deviceField18.setIdentifier("");
deviceField18.setLabelString("Localhost Port:");
deviceField18.setNumCols(4);
deviceField18.setOffsetNid(25);
jPanel9.add(deviceField18);
jPanel1.add(jPanel9);
jPanel20.setBorder(javax.swing.BorderFactory.createTitledBorder("Dynamic Range for Streaming"));
deviceChoice8.setBorder(null);
deviceChoice8.setChoiceItems(new String[] {"YES", "NO"});
deviceChoice8.setLabelString("Auto Adjustment:");
deviceChoice8.setOffsetNid(26);
jPanel20.add(deviceChoice8);
deviceField19.setIdentifier("");
deviceField19.setLabelString("Manual Low Limit:");
deviceField19.setNumCols(4);
deviceField19.setOffsetNid(27);
jPanel20.add(deviceField19);
deviceField20.setIdentifier("");
deviceField20.setLabelString("Manual High Limit:");
deviceField20.setNumCols(4);
deviceField20.setOffsetNid(28);
jPanel20.add(deviceField20);
jPanel1.add(jPanel20);
getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private DeviceButtons deviceButtons1;
private DeviceChoice deviceChoice1;
private DeviceChoice deviceChoice2;
private DeviceChoice deviceChoice3;
private DeviceChoice deviceChoice4;
private DeviceChoice deviceChoice5;
private DeviceChoice deviceChoice8;
private DeviceDispatch deviceDispatch1;
private DeviceField deviceField1;
private DeviceField deviceField10;
private DeviceField deviceField11;
private DeviceField deviceField12;
private DeviceField deviceField13;
private DeviceField deviceField14;
private DeviceField deviceField15;
private DeviceField deviceField16;
private DeviceField deviceField17;
private DeviceField deviceField18;
private DeviceField deviceField19;
private DeviceField deviceField2;
private DeviceField deviceField20;
private DeviceField deviceField3;
private DeviceField deviceField4;
private DeviceField deviceField5;
private DeviceField deviceField6;
private DeviceField deviceField7;
private DeviceField deviceField8;
private DeviceField deviceField9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel20;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanel7;
private javax.swing.JPanel jPanel8;
private javax.swing.JPanel jPanel9;
// End of variables declaration//GEN-END:variables
}
|
linjorejoy/Online-customer-care-and-Service-centre
|
CustomerCare/src/main/java/com/cts/proj/service/UserService.java
|
<gh_stars>1-10
package com.cts.proj.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cts.proj.model.User;
import com.cts.proj.model.UserSecretQuestion;
import com.cts.proj.repository.UserRepository;
@Service
public class UserService {
@Autowired
UserRepository userRepository;
public long getLastId() {
long lastId = 3000;
for (User user : userRepository.findAll()) {
if (user.getUserId() > lastId) {
lastId = user.getUserId();
}
}
return lastId;
}
public User getUser(long userId) {
return userRepository.getOne(userId);
}
public List<User> getAllUsers() {
return userRepository.findAll();
}
public boolean deleteUser(User user) {
userRepository.delete(user);
return true;
}
public boolean deleteUser(long userid) {
userRepository.deleteById(userid);
return true;
}
public boolean addUser(User user) {
userRepository.save(user);
return true;
}
public boolean updateUser(User user) {
userRepository.save(user);
return true;
}
public String getPasswordSHA(long userId) {
return userRepository.getOne(userId).getPassword();
}
public User findUser(String userId, String mob, String email) {
return userRepository.findUser(userId, mob, email);
}
public boolean checkAnswer(List<UserSecretQuestion> list, String ans1, String ans2, String ans3) {
String sq1 = list.get(0).getAnswer();
String sq2 = list.get(1).getAnswer();
String sq3 = list.get(2).getAnswer();
// String sq1="aa";
// String sq2="bb";
// String sq3="cc";
if (sq1.equals(ans1) && sq2.equals(ans2) && sq3.equals(ans3)) {
return true;
}
System.out.println(sq1 + " : " + ans1 + " : " + sq1.equals(ans1));
System.out.println(sq2 + " : " + ans2 + " : " + sq2.equals(ans2));
System.out.println(sq3 + " : " + ans3 + " : " + sq3.equals(ans3));
return false;
}
public User findUserId(String email) {
return userRepository.findUser(email);
}
public boolean validateAnswer(List<UserSecretQuestion> list, String ans1, String ans2, String ans3) {
String sq1 = list.get(0).getAnswer();
String sq2 = list.get(1).getAnswer();
String sq3 = list.get(2).getAnswer();
if (sq1.trim().equalsIgnoreCase(ans1.trim()) && sq2.trim().equalsIgnoreCase(ans2.trim())
&& sq3.trim().equalsIgnoreCase(ans3.trim())) {
return true;
}
return false;
}
}
|
marciojrtorres/poocomhonrajava
|
complexidade/TV4.java
|
class TV {
private String modelo;
private boolean ligada = false;
private int canal = 14;
private int volume = 10;
// 0 (zero) significa que não há anterior
private int canalAnterior = 0;
TV(String modelo) {
this.modelo = modelo;
this.ligada = false; // a TV, por padrão, está desligada
this.canal = 14; // inicia no canal 14
this.volume = 10; // inicia com o volume 10
}
String modelo() {
return this.modelo;
}
boolean ligada() {
return this.ligada;
}
int canal() {
return this.canal;
}
int volume() {
return this.volume;
}
void ligarDesligar() {
if (this.ligada == true) { // ou só `if (this.ligada)`
this.ligada = false;
this.canalAnterior = 0;
} else {
this.ligada = true;
}
// ou na forma reduzida:
// ligada = !ligada;
}
void aumentarVolume() {
if (this.ligada && this.volume < 100) {
this.volume = this.volume + 1;
}
// ou na forma reduzida;
// if (ligada && volume < 100) volume++;
}
void baixarVolume() {
if (this.ligada && this.volume > 0) {
this.volume = this.volume - 1;
}
}
void subirCanal() {
if (ligada) {
this.canalAnterior = this.canal;
this.canal = this.canal < 69 ? this.canal + 1 : 14;
}
}
void descerCanal() {
if (ligada) {
this.canalAnterior = this.canal;
this.canal = this.canal > 14 ? this.canal - 1 : 69;
}
}
void irParaCanal(int novoCanal) {
if (novoCanal >= 14 && novoCanal <= 69) { // é válido?
this.canalAnterior = this.canal;
this.canal = novoCanal;
}
}
void voltar() {
if (this.canalAnterior > 0) {
int permuta = this.canal;
this.canal = this.canalAnterior;
this.canalAnterior = permuta;
}
}
}
|
TeamSPoon/CYC_JRTL_with_CommonLisp_OLD
|
demos/WorkflowEditor/src/eu/larkc/ui/server/LineFile.java
|
/*
This file is part of the LarKC platform
http://www.larkc.eu/
Copyright 2010 LarKC project consortium
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package eu.larkc.ui.server;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class LineFile {
public static List<String> load( String filename ) throws IOException {
List<String> result = new ArrayList<String>();
FileReader fr = new FileReader( filename );
BufferedReader reader = new BufferedReader( fr );
String line;
while( ( line = reader.readLine() ) != null ) {
line = line.trim();
if( line.length() > 0 )
result.add( line );
}
fr.close();
return result;
}
public static void save( String filename, List<String> lines ) throws IOException {
FileWriter fw = new FileWriter( filename );
PrintWriter writer = new PrintWriter( new BufferedWriter( fw ) );
for( String line : lines ) {
writer.println( line );
}
writer.flush();
writer.close();
fw.close();
}
}
|
OpenGGEngine/OpenGG-Project
|
modules/console/classes/com/opengg/core/console/GGConsole.java
|
<gh_stars>1-10
/*
* 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.opengg.core.console;
import com.opengg.core.GGInfo;
import com.opengg.core.thread.ThreadManager;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author Javier
*/
public class GGConsole {
private static final List<GGMessage> messages = new ArrayList<>();
private static final List<ConsoleListener> listeners = new ArrayList<>();
private static final List<LoggerOutputConsumer> consumers = new ArrayList<>();
private static boolean initialized = false;
public static void initialize() {
if (initialized) return;
var currentOut = System.out;
ThreadManager.setDefaultUncaughtExceptionHandler(new GGThreadExceptionHandler());
ThreadManager.runDaemon(() -> {
Scanner in = new Scanner(System.in);
while (GGInfo.isEnded()) {
acceptUserInput(in.nextLine());
}
}, "ConsoleListener");
GGConsole.addOutputConsumer(new DefaultLoggerOutputConsumer(Level.DEBUG, currentOut::println));
if (GGInfo.isRedirectStandardOut()) {
var loggingStream = new PrintStream(currentOut) {
@Override
public void println(String x) {
GGConsole.log(x);
}
@Override
public void println(Object x) {
GGConsole.log(x != null ? x.toString() : null);
}
};
var errorStream = new PrintStream(currentOut) {
@Override
public void println(String x) {
GGConsole.error(x);
}
@Override
public void println(Object x) {
GGConsole.error(x != null ? x.toString() : null);
}
};
System.setOut(loggingStream);
System.setErr(errorStream);
}
initialized = true;
}
public static void saveLogs(Path logsDirectory) {
var time = Instant.now();
try {
Files.createDirectories(logsDirectory);
Files.list(logsDirectory)
.filter(Files::isRegularFile)
.sorted(Comparator.comparingLong(f -> {
try {
var attrib = Files.readAttributes(f, BasicFileAttributes.class);
return -attrib.creationTime().toMillis();
} catch (IOException e) {
e.printStackTrace();
return 0;
}
})).skip(10)
.forEach(f -> {
try {
Files.delete(f);
} catch (IOException e) {
e.printStackTrace();
}
});
var logString = messages.stream().map(GGMessage::toString).collect(Collectors.joining("\n"));
var logName = GGInfo.getApplicationName()
+ "_Log_" +
Instant.now()
.truncatedTo(ChronoUnit.MILLIS)
.atZone(ZoneId.systemDefault()).toLocalDateTime()
.format(DateTimeFormatter.ISO_DATE_TIME)
// .replace( "-" , "" )
.replace("T", "_")
.replace(":", "-") +
".log";
Files.writeString(logsDirectory.resolve(logName), logString);
} catch (IOException e) {
e.printStackTrace();
}
}
public static List<GGMessage> getAllMessages() {
return List.copyOf(messages);
}
public static GGMessage getMostRecent() {
return messages.get(messages.size() - 1);
}
public static void log(String message) {
write(message, Level.INFO);
}
public static void debug(String message) {
write(message, Level.DEBUG);
}
public static void warning(String message) {
write(message, Level.WARNING);
}
public static void warn(String message) {
write(message, Level.WARNING);
}
public static void error(String message) {
write(message, Level.ERROR);
}
public static void exception(Throwable message) {
var trace = new StringWriter();
var pw = new PrintWriter(trace);
message.printStackTrace(pw);
write(message.getMessage() + " at " + trace, Level.ERROR);
}
private static void write(String message, Level level) {
GGMessage m = new GGMessage(message, getSender(), level);
messages.add(m);
consume(m);
}
private static void consume(GGMessage message) {
for (var consumer : consumers) {
consumer.onMessage(message);
}
}
public static void addOutputConsumer(LoggerOutputConsumer consumer) {
consumers.add(consumer);
}
private static String getSender() {
StackTraceElement[] e = Thread.currentThread().getStackTrace();
return (e[4].getClassName()).substring(e[4].getClassName().lastIndexOf('.') + 1);
}
public static void acceptUserInput(String string) {
String[] strings = string.split(" ");
UserCommand command = new UserCommand();
command.time = Calendar.getInstance().getTime();
command.command = strings[0];
command.argCount = strings.length - 1;
command.args = Arrays.copyOfRange(strings, 1, strings.length);
for (ConsoleListener listener : listeners) {
listener.onConsoleInput(command);
}
}
public static void addListener(ConsoleListener listener) {
listeners.add(listener);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.