repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
valjoux/valjoux
packages/util-quarter/index.js
export { monthToQuarter } from './src/monthToQuarter'
kjthegod/chromium
chrome/android/java/src/org/chromium/chrome/browser/NavigationPopup.java
<filename>chrome/android/java/src/org/chromium/chrome/browser/NavigationPopup.java // Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.text.TextUtils; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.HeaderViewListAdapter; import android.widget.ListPopupWindow; import android.widget.PopupWindow; import android.widget.TextView; import org.chromium.base.CalledByNative; import org.chromium.base.ThreadUtils; import org.chromium.content_public.browser.NavigationController; import org.chromium.content_public.browser.NavigationEntry; import org.chromium.content_public.browser.NavigationHistory; import org.chromium.ui.base.LocalizationUtils; import java.util.HashSet; import java.util.Set; /** * A popup that handles displaying the navigation history for a given tab. */ public class NavigationPopup extends ListPopupWindow implements AdapterView.OnItemClickListener { private static final int FAVICON_SIZE_DP = 16; private static final int MAXIMUM_HISTORY_ITEMS = 8; private final Context mContext; private final NavigationController mNavigationController; private final NavigationHistory mHistory; private final NavigationAdapter mAdapter; private final ListItemFactory mListItemFactory; private final int mFaviconSize; private long mNativeNavigationPopup; /** * Constructs a new popup with the given history information. * * @param context The context used for building the popup. * @param navigationController The controller which takes care of page navigations. * @param isForward Whether to request forward navigation entries. */ public NavigationPopup( Context context, NavigationController navigationController, boolean isForward) { super(context, null, android.R.attr.popupMenuStyle); mContext = context; mNavigationController = navigationController; mHistory = mNavigationController.getDirectedNavigationHistory( isForward, MAXIMUM_HISTORY_ITEMS); mAdapter = new NavigationAdapter(); float density = mContext.getResources().getDisplayMetrics().density; mFaviconSize = (int) (density * FAVICON_SIZE_DP); setModal(true); setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); setOnItemClickListener(this); setAdapter(new HeaderViewListAdapter(null, null, mAdapter)); mListItemFactory = new ListItemFactory(context); } /** * @return Whether a navigation popup is valid for the given page. */ public boolean shouldBeShown() { return mHistory.getEntryCount() > 0; } @Override public void show() { if (mNativeNavigationPopup == 0) initializeNative(); super.show(); } @Override public void dismiss() { if (mNativeNavigationPopup != 0) { nativeDestroy(mNativeNavigationPopup); mNativeNavigationPopup = 0; } super.dismiss(); } private void initializeNative() { ThreadUtils.assertOnUiThread(); mNativeNavigationPopup = nativeInit(); Set<String> requestedUrls = new HashSet<String>(); for (int i = 0; i < mHistory.getEntryCount(); i++) { NavigationEntry entry = mHistory.getEntryAtIndex(i); if (entry.getFavicon() != null) continue; String url = entry.getUrl(); if (!requestedUrls.contains(url)) { nativeFetchFaviconForUrl(mNativeNavigationPopup, url); requestedUrls.add(url); } } nativeFetchFaviconForUrl(mNativeNavigationPopup, nativeGetHistoryUrl()); } @CalledByNative private void onFaviconUpdated(String url, Object favicon) { for (int i = 0; i < mHistory.getEntryCount(); i++) { NavigationEntry entry = mHistory.getEntryAtIndex(i); if (TextUtils.equals(url, entry.getUrl())) entry.updateFavicon((Bitmap) favicon); } mAdapter.notifyDataSetChanged(); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { NavigationEntry entry = (NavigationEntry) parent.getItemAtPosition(position); mNavigationController.goToNavigationIndex(entry.getIndex()); dismiss(); } private void updateBitmapForTextView(TextView view, Bitmap bitmap) { Drawable faviconDrawable = null; if (bitmap != null) { faviconDrawable = new BitmapDrawable(mContext.getResources(), bitmap); ((BitmapDrawable) faviconDrawable).setGravity(Gravity.FILL); } else { faviconDrawable = new ColorDrawable(Color.TRANSPARENT); } faviconDrawable.setBounds(0, 0, mFaviconSize, mFaviconSize); view.setCompoundDrawables(faviconDrawable, null, null, null); } private static class ListItemFactory { private static final int LIST_ITEM_HEIGHT_DP = 48; private static final int PADDING_DP = 8; private static final int TEXT_SIZE_SP = 18; private static final float FADE_LENGTH_DP = 25.0f; private static final float FADE_STOP = 0.75f; int mFadeEdgeLength; int mFadePadding; int mListItemHeight; int mPadding; boolean mIsLayoutDirectionRTL; Context mContext; public ListItemFactory(Context context) { mContext = context; computeFadeDimensions(); } private void computeFadeDimensions() { // Fade with linear gradient starting 25dp from right margin. // Reaches 0% opacity at 75% length. (Simulated with extra padding) float density = mContext.getResources().getDisplayMetrics().density; float fadeLength = (FADE_LENGTH_DP * density); mFadeEdgeLength = (int) (fadeLength * FADE_STOP); mFadePadding = (int) (fadeLength * (1 - FADE_STOP)); mListItemHeight = (int) (density * LIST_ITEM_HEIGHT_DP); mPadding = (int) (density * PADDING_DP); mIsLayoutDirectionRTL = LocalizationUtils.isLayoutRtl(); } public TextView createListItem() { TextView view = new TextView(mContext); view.setFadingEdgeLength(mFadeEdgeLength); view.setHorizontalFadingEdgeEnabled(true); view.setSingleLine(); view.setTextSize(TEXT_SIZE_SP); view.setMinimumHeight(mListItemHeight); view.setGravity(Gravity.CENTER_VERTICAL); view.setCompoundDrawablePadding(mPadding); if (!mIsLayoutDirectionRTL) { view.setPadding(mPadding, 0, mPadding + mFadePadding , 0); } else { view.setPadding(mPadding + mFadePadding, 0, mPadding, 0); } return view; } } private class NavigationAdapter extends BaseAdapter { @Override public int getCount() { return mHistory.getEntryCount(); } @Override public Object getItem(int position) { return mHistory.getEntryAtIndex(position); } @Override public long getItemId(int position) { return ((NavigationEntry) getItem(position)).getIndex(); } @Override public View getView(int position, View convertView, ViewGroup parent) { TextView view; if (convertView != null && convertView instanceof TextView) { view = (TextView) convertView; } else { view = mListItemFactory.createListItem(); } NavigationEntry entry = (NavigationEntry) getItem(position); String entryText = entry.getTitle(); if (TextUtils.isEmpty(entryText)) entryText = entry.getVirtualUrl(); if (TextUtils.isEmpty(entryText)) entryText = entry.getUrl(); view.setText(entryText); updateBitmapForTextView(view, entry.getFavicon()); return view; } } private static native String nativeGetHistoryUrl(); private native long nativeInit(); private native void nativeDestroy(long nativeNavigationPopup); private native void nativeFetchFaviconForUrl(long nativeNavigationPopup, String url); }
tanjahennis/scoreboard
src/reducers/errors.js
<reponame>tanjahennis/scoreboard export default (state = [], { type, payload } = {}) => { return state }
AnriKaede/ZY2017IM
ZYChat-EaseMob/ZYChat/Dependcy/GJCFAssetsPicker/View/GJCFAssetsPickerScrollView.h
// // GJAssetsPickerScrollView.h // GJAssetsPickerViewController // // Created by ZYVincent QQ:1003081775 on 14-9-8. // Copyright (c) 2014年 ZYProSoft. All rights reserved. // #import <UIKit/UIKit.h> #import "GJCFAssetsPickerPreviewItemViewController.h" /* 支持缩放的UIScrollView */ @interface GJCFAssetsPickerScrollView : UIScrollView<UIScrollViewDelegate> /* 用来显示当前图片的 */ @property (nonatomic,strong)UIImageView *contentImageView; /* 图片数据源 */ @property (nonatomic,weak)id<GJCFAssetsPickerPreviewItemViewControllerDataSource> dataSource; /* 当前索引 */ @property (nonatomic,assign)NSInteger index; @end
simple858/tsf-simple-demo
opensource-zuul-demo/src/main/java/com/tencent/tsf/demo/zuul/filter/TestFilter.java
package com.tencent.tsf.demo.zuul.filter; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; import com.netflix.zuul.exception.ZuulException; import org.apache.commons.lang.StringUtils; import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants; import org.springframework.cloud.netflix.zuul.util.ZuulRuntimeException; import org.springframework.http.HttpStatus; import javax.servlet.http.HttpServletRequest; public class TestFilter extends ZuulFilter { private static final String ACTION_PARAMETER = "action"; @Override public String filterType() { // pre 类型的过滤器 return FilterConstants.PRE_TYPE; } @Override public int filterOrder() { // token 检验应该放在第一位来进行校验,因此需要放在最前面 return FilterConstants.SERVLET_DETECTION_FILTER_ORDER - 1; } @Override public boolean shouldFilter() { // 过滤器是否应该执行, true:表示应该执行 false:表示跳过这个过滤器执行 return true; } @Override public Object run() { RequestContext requestContext = RequestContext.getCurrentContext(); // 获取到 request HttpServletRequest request = requestContext.getRequest(); // 判断请求参数中是否存在 action 参数 String action = request.getParameter(ACTION_PARAMETER); if (StringUtils.isNotBlank(action)) { // 不进行路由 if (action.equals("no_routing")) { requestContext.setSendZuulResponse(false); } else if (action.equals("forbidden")) { requestContext.setSendZuulResponse(false); requestContext.setResponseStatusCode(HttpStatus.FORBIDDEN.value()); } else if (action.equals("unauthorized")) { throw new ZuulRuntimeException(new ZuulException(this.filterType() + ":" + this.getClass().getSimpleName(), HttpStatus.UNAUTHORIZED.value(), "Unauthorized")); } } return null; } }
yizhouyan/SeqDB
src/interactive/mining/baseline/top/parameterspace/GlobalParameterSpace.java
package interactive.mining.baseline.top.parameterspace; /** * Created by yizhouyan on 7/9/17. */ public class GlobalParameterSpace { private LocalParameterSpace localParameterSpace; private int minGlobalSupport; private int violationLocalSupport; private int thresholdForLocalFSOutliers; public GlobalParameterSpace(int minLocalSupport, int eventGap, int seqGap, int minGlobalSupport, int violationLocalSupport, int thresholdForLocalFSOutliers){ this.localParameterSpace = new LocalParameterSpace(minLocalSupport, eventGap, seqGap); this.minGlobalSupport = minGlobalSupport; this.violationLocalSupport = violationLocalSupport; this.thresholdForLocalFSOutliers = thresholdForLocalFSOutliers; } public LocalParameterSpace getLocalParameterSpace() { return localParameterSpace; } public void setLocalParameterSpace(LocalParameterSpace localParameterSpace) { this.localParameterSpace = localParameterSpace; } public int getMinGlobalSupport() { return minGlobalSupport; } public void setMinGlobalSupport(int minGlobalSupport) { this.minGlobalSupport = minGlobalSupport; } public int getViolationLocalSupport() { return violationLocalSupport; } public void setViolationLocalSupport(int violationLocalSupport) { this.violationLocalSupport = violationLocalSupport; } public int getThresholdForLocalFSOutliers() { return thresholdForLocalFSOutliers; } public void setThresholdForLocalFSOutliers(int thresholdForLocalFSOutliers) { this.thresholdForLocalFSOutliers = thresholdForLocalFSOutliers; } }
raychorn/chrome_gui
vyperlogix/misc/paths.py
<gh_stars>1-10 __copyright__ = """\ (c). Copyright 2008-2020, Vyper Logix Corp., All Rights Reserved. Published under Creative Commons License (http://creativecommons.org/licenses/by-nc/3.0/) restricted to non-commercial educational use only., http://www.VyperLogix.com for details THE AUTHOR VYPER LOGIX CORP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE ! USE AT YOUR OWN RISK. """ def _findUsingPath(t,p): import time,Queue from vyperlogix import misc from vyperlogix.misc import threadpool Qs = {} Q = threadpool.ThreadQueue(10) q = Queue.Queue(10) @threadpool.threadify(Q) def do_scan_for_file(target,top,statsDict,topdown=True): for root, dirs, files in os.walk(top,topdown=topdown): for f in files: if (f.split(os.sep)[-1] == target) or (f.find(target) > -1): p = os.sep.join([root,f]) print '(+++).do_scan_for_file().1 q.put_nowait(%s)' % (p) q.put_nowait(p) print '(+++).do_scan_for_file().2 del statsDict["%s"]' % (top) del statsDict[top] return print '(+++).do_scan_for_file().3 del statsDict["%s"]' % (top) del statsDict[top] ptoks = p.split(';') if (len(ptoks) == 1): ptoks = p.split(':') ptoks = [p for p in ptoks if (len(p) > 0)] for i in xrange(len(ptoks)): f = ptoks[i] if (f.startswith('%') and f.endswith('%')): f = f.replace('%','') f = os.environ.get(f,None) ptoks[i] = f for drive in [d for d in getCurrentWindowsLogicalDrives()]: try: for dir in [os.path.join(drive,tt) for tt in os.listdir(drive) if (not tt.startswith('$')) and (tt.find('Program Files') > -1) and (os.path.isdir(os.path.join(drive,tt)))]: ptoks.append(dir) except WindowsError: pass ptoks = list(set(ptoks)) for f in ptoks: if (misc.isStringValid(f)) and (os.path.exists(f)) and (os.path.isdir(f)): Qs[f] = 1 do_scan_for_file(t,f,Qs) isDone = False while (not isDone): try: p = q.get_nowait() except: p = None print '(+++)._findUsingPath().1 Sleeping on "%s".' % (p) time.sleep(1) if (misc.isStringValid(p)): Q.setIsRunning = False print '(+++)._findUsingPath().2 Return "%s".' % (p) return p isDone = (len(Qs) == 0) print '(+++)._findUsingPath().3 Return None.' Q.setIsRunning = False return None
komamj/Audient
app/src/main/java/com/xinshang/audient/mine/MineFragment.java
/* * Copyright 2017 Koma * * 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.xinshang.audient.mine; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.View; import com.xinshang.audient.AudientApplication; import com.xinshang.audient.R; import com.xinshang.audient.model.entities.Favorite; import com.xinshang.audient.model.entities.MessageEvent; import com.xinshang.common.base.BaseFragment; import com.xinshang.common.util.Constants; import com.xinshang.common.util.LogUtils; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.List; import javax.inject.Inject; import butterknife.BindView; import butterknife.OnClick; public class MineFragment extends BaseFragment implements MineContract.View { private static final String TAG = MineFragment.class.getSimpleName(); @BindView(R.id.recycler_view) RecyclerView mRecyclerView; @BindView(R.id.swipe_refresh_layout) SwipeRefreshLayout mSwipeRefreshLayout; @Inject MinePresenter mPresenter; private boolean mIsPrepared; private boolean mIsLoaded; private FavoriteAdapter mAdapter; public MineFragment() { } public static MineFragment newInstance() { MineFragment fragment = new MineFragment(); return fragment; } @OnClick(R.id.iv_add_playlist) void showAddPlaylistDilog() { AddFavoritesDialog.show(getChildFragmentManager()); } @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); LogUtils.i(TAG, "setUserVisibleHint isVisibleToUser : " + isVisibleToUser); if (isVisibleToUser && mIsPrepared && !mIsLoaded) { if (mPresenter != null) { mPresenter.subscribe(); } } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LogUtils.i(TAG, "onCreate"); DaggerMineComponent.builder() .audientRepositoryComponent( (((AudientApplication) getActivity().getApplication()).getRepositoryComponent())) .minePresenterModule(new MinePresenterModule(this)) .build() .inject(this); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); LogUtils.i(TAG, "onViewCreated"); mSwipeRefreshLayout.setColorSchemeResources(R.color.colorAccent, R.color.colorPrimaryDark, R.color.colorPrimary); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { if (mPresenter != null) { mPresenter.loadFavorites(); } } }); mAdapter = new FavoriteAdapter(mContext); mAdapter.setListener(new FavoriteAdapter.EventListner() { @Override public void onModifyEventChange(Favorite favorite) { EditNameDialogFragment.show(getChildFragmentManager(), favorite); } @Override public void onDeleteEventChange(Favorite favorite) { if (mPresenter != null) { mPresenter.deleteMyFavorite(favorite); } } }); mRecyclerView.setHasFixedSize(true); GridLayoutManager layoutManager = new GridLayoutManager(mContext, 2); layoutManager.setOrientation(LinearLayoutManager.VERTICAL); mRecyclerView.setLayoutManager(layoutManager); mRecyclerView.setAdapter(mAdapter); mIsPrepared = true; EventBus.getDefault().register(this); } @Subscribe(threadMode = ThreadMode.MAIN) public void onMessageEvent(MessageEvent messageEvent) { LogUtils.i(TAG, "onMessageEvent"); if (TextUtils.equals(messageEvent.getMessage(), Constants.MESSAGE_MY_FAVORITES_CHANGED)) { if (mPresenter != null) { mIsLoaded = false; mPresenter.loadFavorites(); } } } @Override public void onDestroy() { super.onDestroy(); LogUtils.i(TAG, "onDestroy"); EventBus.getDefault().unregister(this); if (mPresenter != null) { mPresenter.unSubscribe(); } } @Override public int getLayoutId() { return R.layout.fragment_mine; } @Override public void setPresenter(MineContract.Presenter presenter) { } @Override public boolean isActive() { return this.isAdded(); } @Override public void showLoadingError() { } @Override public void setLoadingIndicator(final boolean isActive) { mSwipeRefreshLayout.post(new Runnable() { @Override public void run() { mSwipeRefreshLayout.setRefreshing(isActive); } }); } @Override public void showEmpty(boolean forceShow) { } @Override public void showFavorites(List<Favorite> favorites) { mIsLoaded = true; mAdapter.replace(favorites); } }
applied-systems-biology/misa-imagej
src/main/java/org/hkijena/misa_imagej/ui/workbench/plotbuilder/MISAPlotSeriesGenerator.java
<filename>src/main/java/org/hkijena/misa_imagej/ui/workbench/plotbuilder/MISAPlotSeriesGenerator.java /* * Copyright by <NAME> * Research Group Applied Systems Biology - Head: Prof. Dr. <NAME> * https://www.leibniz-hki.de/en/applied-systems-biology.html * HKI-Center for Systems Biology of Infection * Leibniz Institute for Natural Product Research and Infection Biology - Hans Knöll Insitute (HKI) * Adolf-Reichwein-Straße 23, 07745 Jena, Germany * * This code is licensed under BSD 2-Clause * See the LICENSE file provided with this code for the full license. */ package org.hkijena.misa_imagej.ui.workbench.plotbuilder; import java.util.function.Function; public class MISAPlotSeriesGenerator<T> { private String name; private Function<Integer, T> generatorFunction; public MISAPlotSeriesGenerator(String name, Function<Integer, T> generatorFunction) { this.name = name; this.generatorFunction = generatorFunction; } public String getName() { return name; } public Function<Integer, T> getGeneratorFunction() { return generatorFunction; } }
yashdeeph709/Algorithms
Algorithms/src/com/sorting/QuickSort.java
package com.sorting; public class QuickSort { public static void main(String args[]) { int[] array={38, 27, 43, 3, 9, 82, 10}; qsort(array,0,array.length-1); printArray(array); } public static void qsort(int[] array,int start,int end){ if(start<end){ int partition_key=hPartition(array,start,end); printArray(array); qsort(array,partition_key+1,end); qsort(array,start,partition_key-1); } } private static void printArray(int[] array) { for(int i=0;i<array.length;i++){ System.out.print(array[i]+","); } System.out.println(); } private static int partition(int[] array, int start, int end) { int pivot_index=end; for(int i=end-1;i>=0;i--){ if(array[pivot_index]<array[i]){ int j=i; while(j!=pivot_index){ int temp=array[j+1]; array[j+1]=array[j]; array[j]=temp; j++; } pivot_index=j-1; } } return pivot_index; } private static int standardPartition(int[] array,int start,int end){ int pivot=array[end]; int pIndex=start; for(int i=start;i<end;i++){ if(array[i]<=pivot){ int temp=array[pIndex]; array[pIndex]=array[i]; array[i]=temp; pIndex+=1; } } int temp=array[pIndex]; array[pIndex]=array[end]; array[end]=temp; return pIndex; } private static int hPartition(int[] array,int start,int end){ int pivot = array[start]; int i = start - 1; int j = end + 1; System.out.println("Partition called with start="+start+" end="+end); while(true){ while(array[--j] > pivot); while(array[++i] < pivot); if(i>=j){ break; } int temp=array[i]; array[i]=array[j]; array[j]=temp; } return j; } }
LyricGan/Grace
library_gson/src/main/java/com/lyricgan/gson/adapter/BooleanTypeAdapter.java
package com.lyricgan.gson.adapter; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import java.io.IOException; /** * 自定义json布尔类型解析 * @author <NAME> */ public class BooleanTypeAdapter extends TypeAdapter<Boolean> { @Override public void write(JsonWriter out, Boolean value) throws IOException { out.value(value); } @Override public Boolean read(JsonReader in) throws IOException { JsonToken token = in.peek(); if (token == JsonToken.BOOLEAN) { return in.nextBoolean(); } if (token == JsonToken.NULL) { in.nextNull(); return false; } if (token == JsonToken.STRING) { try { return Boolean.valueOf(in.nextString()); } catch (IOException e) { e.printStackTrace(); } return false; } return false; } }
cheechang/cppcc
vs2017/ui/mainwindow/chat/bubble/MiniVedioMessageWidget.cpp
#include "MiniVedioMessageWidget.h" //#include "MiniVedioMessageWidgetWidget.h" #include <QWidget> #include <QProgressBar> #include <QMouseEvent> #include <QVBoxLayout> #include <QStackedWidget> #include <QLabel> #include <QMovie> #include <QFileInfo> #include <QTimer> #include <QEventLoop> #include <QTime> #include "common/ChineseInfos.hpp" #include "common/UIUtils.h" #include "controls/PushButton.h" #include "controls/ClickQLabel.h" #include <log/log.h> #include "MyRightMenu.h" namespace ui { MiniVedioMessageWidget::MiniVedioMessageWidget(QWidget *parent):AbstractMessageWidget(parent), m_process(NULL),moviePlay(NULL),imglabel(NULL),mimgwidget(NULL),mstackwidget(NULL), mainlayout(NULL),m_strUrl(""),m_strCachePath(""),m_strImgUrl(""),m_strImgPath(""),m_strVedioPath(""), IsSetValue(false) { m_oriWidth = 0; initWidgets(); } MiniVedioMessageWidget::~MiniVedioMessageWidget() { if (m_process) { m_process->kill(); } m_process = NULL; } void MiniVedioMessageWidget::setLoadVideo() { imglabel->setMovie(moviePlay); moviePlay->start(); } void MiniVedioMessageWidget::initWidgets() { mstackwidget = new QStackedWidget(this); imglabel = new ClickQLabel(this); connect(imglabel,SIGNAL(clicked()),this,SLOT(onSerPlayVideo())); imglabel->setPixmap(QPixmap(":/chat/VideoPlayer")); moviePlay = new QMovie(":/chat/loadVideo"); mainlayout = new QVBoxLayout(this); mainlayout->addWidget(imglabel, 0, Qt::AlignCenter); mainlayout->setContentsMargins(0,0,0,0); mimgwidget = new QLabel(this); mimgwidget->setLayout(mainlayout); mstackwidget->addWidget(mimgwidget); this->setCentralWidget(mstackwidget); CONNECT_SERVICE(DownVedioMsgResult(int, const std::string&, int64, bool)); CONNECT_SERVICE(DownLoadImg(int, const std::string&, int64)); } void MiniVedioMessageWidget::SetMsg(MsgDataPtr& msg) { AbstractMessageWidget::setMsg(msg); data::MsgMiniVedio* videomsg = (data::MsgMiniVedio*)msg.get(); //m_RightMenu.setMenuState(MENU_SILENT_PLAY, true); //connect(&m_RightMenu, SIGNAL(signalCtrlSilentPlayMenu(int64,int64)), // this, SLOT(onCtrlSilentPlayMenu())); SetSourcePath(videomsg->vedioFileName, videomsg->preImgPath, videomsg->vedioHight, videomsg->vedioWideth, videomsg->encryptKey); QString path = QString::fromStdString(m_strVedioPath); if (UIUtils::IsFileExist(path)) { if(m_strCachePath == "") { m_strCachePath = (UIUtils::GetDataFullPath(DATACACHEPATH_USERVIDEO) + UIUtils::GetNameByUrl(path)).toStdString(); if(!IsSetValue) { IsSetValue = true; } } } downLoadImg(m_strImgUrl, true); Log(LOG_LEV_INFO, LOG_FILE, "enkey:%s,path:%s", videomsg->encryptKey.c_str(), videomsg->localVedioPath.c_str()); } void MiniVedioMessageWidget::SetSourcePath(std::string pVideopath, std::string pPreImgPath, int64 pHight, int64 pWideth,std::string encryptkey) { m_strVedioPath = (UIUtils::GetDataFullPath(DATAPATH_USERVIDEO) + UIUtils::GetNameByUrl(pVideopath.c_str())).toStdString(); m_strUrl = pVideopath; m_strImgUrl = pPreImgPath; vedioHight = pHight; vedioWideth = pWideth; encyptkey = encryptkey; } QSize MiniVedioMessageWidget::suggestWidth(int width) { return QSize(200, 220); } QString MiniVedioMessageWidget::decryptFile(const std::string& url, std::string& Key) { QString path = QString::fromUtf8(url.data()); QString destPath = UIUtils::GetDataFullPath(DATACACHEPATH_USERVIDEO) + UIUtils::GetNameByUrl(QString::fromUtf8(url.data())); if (UIUtils::IsFileExist(path)) { if(Key.empty()) { QFile file(path); file.copy(destPath); } else { bool bret = m_chatcontrol->decryptFile(Key, path.toUtf8().data(), destPath.toUtf8().data()); Log(LOG_LEV_INFO,LOG_FILE,"decryfile:%d",bret); } m_strCachePath = destPath.toStdString(); } return destPath; } void MiniVedioMessageWidget::onSerDownLoadAduioMsg(std::string url,bool isSilent) { Log(LOG_LEV_INFO,LOG_FILE,"url=%s",url.c_str()); CSharedPtr<data::DownLoadFile> download = CNull; download = CMakePtr<data::DownLoadFile>(); download->bisP2P = false; download->bIsResume = false; data::MsgMiniVedio* vediomsg = (data::MsgMiniVedio*)msg().get(); download->encryptKey = vediomsg->encryptKey; download->fileName = vediomsg->vedioFileName; QString localPath = UIUtils::GetDataFullPath(DATAPATH_USERVIDEO); Log(LOG_LEV_INFO,LOG_FILE,"Enter onSerDownLoadAduioMsg path=%s",localPath.toLocal8Bit().data()); QString path = UIUtils::GetDataFullPath(DATAPATH_USERVIDEO) + UIUtils::GetNameByUrl(vediomsg->vedioFileName.c_str()); download->localPath = path.toUtf8().data(); download->fromUserId = vediomsg->fromId; download->localId = vediomsg->localId; download->msgid = vediomsg->msgId; download->url = vediomsg->vedioFileName; download->targetId = vediomsg->targetId; Log(LOG_LEV_INFO,LOG_FILE,"Enter onSerDownLoadAduioMsg path=%s",path.toLocal8Bit().data()); m_chatcontrol->DownLoadFile(download, CBind(&MiniVedioMessageWidget::signalSerDownVedioMsgResult, this, CPlaceholders _1, CPlaceholders _2, CPlaceholders _3, isSilent)); } void MiniVedioMessageWidget::onSerDownVedioMsgResult(int code, const std::string& path, int64 senderID, bool isSilent) { Log(LOG_LEV_INFO, LOG_FILE, "code = %d", code); if (!code) { std::string key = ((data::MsgMiniVedio*)(msg().get()))->encryptKey; if (key.empty()) { m_strVedioPath = path; } else { m_strVedioPath = decryptFile(path, key).toStdString(); } /*data::MsgMiniVedio* vediomsg = (data::MsgMiniVedio*)msg().get(); if (vediomsg->vedioHight <vediomsg->vedioWideth){ m_strCachePath = srcConvertMp4(m_strVedioPath.c_str()).toStdString(); } else{ m_strCachePath = m_strVedioPath; }*/ m_strCachePath = m_strVedioPath; } setFinishLoad(); } void MiniVedioMessageWidget::dealVideopalyerPro() { QProcess killPro; QString c = "taskkill /im ffplay.exe /f"; killPro.execute(c); killPro.close(); } void MiniVedioMessageWidget::palyMinVideo(bool isSilent) { Log(LOG_LEV_INFO,LOG_FILE,"Enter palyMinVideo"); imglabel->setPixmap(QPixmap(":/chat/VideoPlayer")); QString path = QString::fromStdString(m_strVedioPath); path = UIUtils::RepairLocalFilePath(path); if (UIUtils::IsFileExist(path)) { if(m_strCachePath == "") { m_strCachePath = (UIUtils::GetDataFullPath(DATACACHEPATH_USERVIDEO) + UIUtils::GetNameByUrl(path)).toStdString(); } QString tempath= QString::fromStdString(m_strCachePath); if(!UIUtils::IsFileExist(tempath)) { decryptFile(path.toStdString(),encyptkey); } Log(LOG_LEV_INFO,LOG_FILE,"Enter Exsit palyMinVideo"); dealVideopalyerPro(); QFile file(tempath); if (!file.exists()){ return; } QString ExeName = QString("ffplay.exe"); QStringList arguments; m_process = new QProcess(this); arguments << "-window_title"; arguments << APP_NAME; arguments << "-autoexit"; arguments << "-x"; arguments << "360"; arguments << "-y"; arguments << "460"; arguments << tempath; m_process->start(ExeName, arguments); } else { Log(LOG_LEV_INFO,LOG_FILE,"Enter palyMinVideo onSerDownLoadAduioMsg"); setLoadVideo(); onSerDownLoadAduioMsg(m_strUrl,isSilent); } } void MiniVedioMessageWidget::onSerPlayVideo() { palyMinVideo(); } void MiniVedioMessageWidget::downLoadImg(std::string& url,bool isSrc) { QString path = UIUtils::GetDataFullPath(DATACACHEPATH_USERIMG) + UIUtils::GetPicNameByUrl(QString::fromUtf8(url.data())); path = UIUtils::RepairLocalFilePath(path); if (UIUtils::IsFileExist(path)) { m_strImgPath = path.toStdString(); PlayFinish(); } else { int64 id = this->targetId(); m_chatcontrol->DownLoadImage(id, url, CBind(&MiniVedioMessageWidget::signalSerDownLoadImg, this, CPlaceholders _1, CPlaceholders _2, CPlaceholders _3)); } } void MiniVedioMessageWidget::onSerDownLoadImg(int err, const std::string& imgname, int64 targetid) { if ( !err) { std::string url = imgname; m_strImgPath = enctrptFile(url,encyptkey).toStdString(); setImgBackgroundColor(); mstackwidget->setCurrentWidget(mimgwidget); //onSerPlayVideo(); } } QString MiniVedioMessageWidget::enctrptFile(std::string&url,std::string&encrptkey,FileDefaultPathType filepath/*=DATAPATH_USERIMG*/,FileCachePathType cacheType/*=DATACACHEPATH_USERIMG*/) { QString path = UIUtils::GetDataFullPath(filepath)+QString::fromUtf8(url.data()); QString destPath = UIUtils::GetDataFullPath(cacheType)+UIUtils::GetNameByUrl(QString::fromUtf8(url.data())); if ( UIUtils::IsFileExist(path) && !encrptkey.empty()) { bool bret = m_chatcontrol->decryptFile(encrptkey,path.toUtf8().data(),destPath.toUtf8().data()); if ( !bret) { destPath=""; } } else{ QFile file(path); file.copy(destPath); } return destPath; } void MiniVedioMessageWidget::setImgBackgroundColor() { QPixmap pix; bool ret = pix.load(m_strImgPath.c_str()); pix = pix.scaled(this->size(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation); mimgwidget->setPixmap(pix); } void MiniVedioMessageWidget::PlayFinish() { mstackwidget->setCurrentWidget(mimgwidget); } QString MiniVedioMessageWidget::srcConvertMp4(QString srcPath) { if ((srcPath.right(4) != ".mp4") || (srcPath.length() == 0) || (srcPath == "")) { printf("format error, is not mp4 file!"); return ""; } QString ExeName = QString("ffmpeg.exe"); QStringList processAgrc; QString outAviPath = srcPath; QString tmpFile = srcPath; tmpFile = tmpFile.replace(".mp4", "_temp.mp4"); QFile file(srcPath); file.rename(tmpFile); if (m_process != NULL) { m_process->kill(); m_process = NULL; } m_process = new QProcess; QObject::connect(m_process, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(onFormatConvertFinished(int, QProcess::ExitStatus)), Qt::QueuedConnection); //processAgrc << "-i" << srcPath << "-vf" <<"transpose=1"<< "-qscale" << "4" << "-r" << "24" << "-y" << outAviPath; processAgrc << "-i" << tmpFile << "-vf" << "transpose=1" << outAviPath; m_process->start(ExeName, processAgrc); QTime dieTime = QTime::currentTime().addMSecs(100); while (QTime::currentTime() < dieTime) QCoreApplication::processEvents(QEventLoop::AllEvents, 100); return outAviPath; } void MiniVedioMessageWidget::onFormatConvertFinished(int exitCode, QProcess::ExitStatus exitStatus) { printf("convert success!!!"); m_process->deleteLater(); m_process = NULL; QString tmpFile = m_strCachePath.c_str(); tmpFile = tmpFile.replace(".mp4", "_temp.mp4"); QFile file(tmpFile); file.remove(); } QString MiniVedioMessageWidget::GetAviVideoPath(QString pVideoPath) { if ((pVideoPath.right(4) != ".mp4") || (pVideoPath.length() == 0) || (pVideoPath == "")) { printf("format error, is not mp4 file!"); return ""; } QString destPath = UIUtils::GetDataFullPath(DATACACHEPATH_USERVIDEO) + UIUtils::GetNameByUrl(QString::fromUtf8(pVideoPath.toStdString().c_str())); QString outAviPath = destPath; QFile fileInfo(destPath); QString fileSize = QString::number(fileInfo.size()); outAviPath.replace(".mp4", fileSize + "_temp.avi"); fileInfo.close(); return outAviPath; } void MiniVedioMessageWidget::paintEvent(QPaintEvent *e) { if(mimgwidget && mimgwidget->isVisible()){ if(m_oriWidth != this->size().width()){ m_oriWidth = this->size().width(); setImgBackgroundColor(); } } AbstractMessageWidget::paintEvent(e); } void MiniVedioMessageWidget::onCtrlSilentPlayMenu() { palyMinVideo(true); } void MiniVedioMessageWidget::setFinishLoad() { moviePlay->stop(); imglabel->setPixmap(QPixmap(":/chat/VideoPlayer")); } }
miguelsrrobo/C-C-
Qt/Qt_Aula_05/mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_clicked() { QMessageBox::StandardButton resposta = QMessageBox::question(this,"","Deseja fechar o programa?",QMessageBox::Yes|QMessageBox::No); if(resposta == QMessageBox::Yes){ QApplication::quit(); }else{ QMessageBox::about(this,"","Programa não foi fechado"); if (QMessageBox::Ok) { QApplication::quit(); } //qDebug() << "Program não foi fechado" << resposta; } }
wuman/fbpcf
fbpcf/mpc_framework/engine/communication/IPartyCommunicationAgentFactory.h
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <memory> #include "fbpcf/mpc_framework/engine/communication/IPartyCommunicationAgent.h" namespace fbpcf::mpc_framework::engine::communication { /** * An communication factory API */ class IPartyCommunicationAgentFactory { public: virtual ~IPartyCommunicationAgentFactory() = default; /** * create an agent that talks to a certain party. */ virtual std::unique_ptr<IPartyCommunicationAgent> create(int id) = 0; }; } // namespace fbpcf::mpc_framework::engine::communication
seifgh/home-seller-web-app
front-end-pages/properties-react-page/src/components/Header.js
<gh_stars>0 import React, {useContext, useState} from 'react'; import { Link } from 'react-router-dom'; import HeaderSearch from './header/HeaderSearch'; import HeaderUser from './header/HeaderUser'; import logo from './../images/logo.png'; import { GlobalContext } from './../state-manager/globalState'; import { REACT_ROUTERS_URLS } from './../Settings'; function Header() { const {fetchSetProperties, screen_types, setProperties, resetFilters} = useContext(GlobalContext), {is_desktop, is_laptop} = screen_types, [ show_menu, setShowMenu ] = useState(false); function reloadProperties(){ setProperties({data: []}); resetFilters(); } if (is_desktop || is_laptop){ return( <header> <nav className="active" > <a href="/" className="logo" > <img alt="logo" src={logo} /> </a> <div className="links"> <a className="link" href="/">Home</a> <Link onClick={() => reloadProperties()} className="active link" to={REACT_ROUTERS_URLS.properties} >Properties</Link> <a className="link" href={REACT_ROUTERS_URLS.sell_property}>Sell your home</a> </div> <div className="right-links"> <HeaderSearch /> <HeaderUser /> </div> </nav> </header> ) } return( <header> <nav className="active" > <button onClick={ () => setShowMenu(!show_menu) } className={`menu${ show_menu ? ' active' : ''}`} ><i className="fa fa-bars"/></button> <a href="/" className="logo" > <img alt="logo" src={logo} /> </a> <HeaderUser /> </nav> <div className={`links${show_menu ? ' show' : ''}`}> <HeaderSearch onClick={() => setShowMenu(false)} /> <a className="link" href="/">Home</a> <Link onClick={() =>{ reloadProperties(); setShowMenu(false)}} className="active link" to={REACT_ROUTERS_URLS.properties} >Properties</Link> <a className="link" href={REACT_ROUTERS_URLS.sell_property} >Sell your home</a> <a className="link" href={REACT_ROUTERS_URLS.sign_up} >Sign up</a> </div> </header> ) } export default Header;
EDS-APHP/LightICE
src/drivers/philips/intellivue/data/AttributeValueList.java
<filename>src/drivers/philips/intellivue/data/AttributeValueList.java /******************************************************************************* * Copyright (c) 2014, MD PnP Program * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ package drivers.philips.intellivue.data; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Collection; import java.util.List; import java.util.Map; import drivers.philips.intellivue.Formatable; import drivers.philips.intellivue.Parseable; import drivers.philips.intellivue.attribute.Attribute; import drivers.philips.intellivue.attribute.AttributeFactory; import drivers.philips.intellivue.util.Util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author <NAME> * */ public class AttributeValueList implements Parseable, Formatable, Util.PrefixLengthShort.Builder<Attribute<?>> { private final List<Attribute<?>> list = new java.util.ArrayList<Attribute<?>>(); private final List<AttributeValueAssertion> recycle = new java.util.ArrayList<AttributeValueAssertion>(); private final Map<OIDType, Attribute<?>> map = new java.util.HashMap<OIDType, Attribute<?>>(); @Override public Attribute<?> build() { return newAVA(); } private AttributeValueAssertion newAVA() { if (recycle.isEmpty()) { return new AttributeValueAssertion(); } else { return recycle.remove(0); } } public void reset() { for (Formatable f : list) { if (f instanceof AttributeValueAssertion) { recycle.add((AttributeValueAssertion) f); } } list.clear(); map.clear(); } @Override public void format(ByteBuffer bb) { Util.PrefixLengthShort.write(bb, list); } @Override public void parse(ByteBuffer bb) { parse(bb, true); } public void parseMore(ByteBuffer bb) { parse(bb, false); } private void parse(ByteBuffer bb, boolean clear) { Util.PrefixLengthShort.read(bb, list, clear, this); for (Attribute<?> a : list) { map.put(a.getOid(), a); } } public void put(OIDType type, Attribute<?> a) { list.add(a); map.put(type, a); // TODO this is ugly // ByteBuffer bb = ByteBuffer.allocate(5000); // bb.order(ByteOrder.BIG_ENDIAN); // computeRelative.format(bb); // bb.flip(); // byte[] buf = new byte[bb.remaining()]; // bb.get(buf); // add(type, buf); } public boolean remove(OIDType type) { Attribute<?> a = map.remove(type); if (null != a) { list.remove(a); if (a instanceof AttributeValueAssertion) { recycle.add((AttributeValueAssertion) a); } return true; } else { return false; } } private static final Logger log = LoggerFactory.getLogger(AttributeValueList.class); public <T extends Value> Attribute<T> getAttribute(AttributeId attrId, Class<T> valueClass) { return getAttribute(attrId, valueClass, null); } @SuppressWarnings("unchecked") public <T extends Value> Attribute<T> getAttribute(OIDType oid, Class<T> valueClass, Attribute<T> attr) { Attribute<?> a = get(oid); if (a != null && valueClass.isInstance(a.getValue())) { return (Attribute<T>) a; } else { attr = null == attr ? AttributeFactory.getAttribute(oid, valueClass) : attr; return get(oid, attr) ? attr : null; } } public <T extends Value> Attribute<T> getAttribute(AttributeId attrId, Class<T> valueClass, Attribute<T> attr) { return getAttribute(attrId.asOid(), valueClass, attr); } @SuppressWarnings("unchecked") public <T extends Value> Attribute<T> getAttribute(Attribute<T> attr) { return getAttribute(attr.getOid(), (Class<T>) attr.getValue().getClass(), attr); } public Attribute<?> get(OIDType type) { return map.get(type); } public boolean get(Attribute<?> p) { return get(p.getOid(), p); } public boolean get(OIDType type, Attribute<?> p) { Attribute<?> a = map.get(type); if (a == null) { return false; } else if (a instanceof AttributeValueAssertion) { if (p == null) { return false; } else { int idx = list.indexOf(a); ByteBuffer bb = ByteBuffer.wrap(((AttributeValueAssertion) a).getValue().getArray()); bb.order(ByteOrder.BIG_ENDIAN); p.parse(bb); list.set(idx, p); map.put(type, p); recycle.add((AttributeValueAssertion) a); return true; } } else if (a.getValue() instanceof ByteArray) { int idx = list.indexOf(a); ByteArray ba = (ByteArray) a.getValue(); p.parse(ByteBuffer.wrap(ba.getArray()).order(ByteOrder.BIG_ENDIAN)); list.set(idx, p); map.put(type, p); return true; } else { return false; } } public void add(OIDType type, byte[] value) { AttributeValueAssertion ava = newAVA(); ava.setValue(value); ava.setOid(type); add(ava); } public void add(AttributeValueAssertion ava) { list.add(ava); map.put(ava.getOid(), ava); } public void add(Attribute<?> attr) { put(attr.getOid(), attr); } public Collection<Attribute<?>> getList() { return list; } public Map<OIDType, Attribute<?>> getMap() { return map; } @Override public java.lang.String toString() { StringBuilder sb = new StringBuilder("{"); for (Attribute<?> a : list) { if (null == a) { sb.append(a).append(","); } else { if (a instanceof AttributeValueAssertion) { Class<?> cls = AttributeFactory.valueType(a.getOid()); if (!ByteArray.class.equals(cls)) { Attribute<?> _a = AttributeFactory.getAttribute(a.getOid()); if (null != _a) { if (get(_a)) { a = _a; } } } } sb.append(AttributeId.valueOf(a.getOid().getType())); sb.append("=").append(a); sb.append(","); } } if (sb.length() > 1) { sb.delete(sb.length() - 1, sb.length()); } sb.append("}"); return sb.toString(); } }
Yorafa/TextAdventure
src/test/java/entity/PocketTest.java
<gh_stars>0 package entity; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import static org.junit.Assert.*; public class PocketTest { private Pocket pocket; private Pokemon testPokemon; @Before public void setUp() { pocket = new Pocket(); BasePokemonData basePokemonData = new BasePokemonData(PokemonType.ELECTRICITY, 1, 1, 1, 1); PokemonData pokemonData = new PokemonData(PokemonType.ELECTRICITY, 1, 1, 1, 1); testPokemon = new Pokemon("test", basePokemonData, 1, 0, 1, pokemonData); } @Test(timeout = 50) public void testGetBattlePokemon() { assertNull(pocket.getBattlePokemon()); } @Test(timeout = 50) public void testSetBattlePokemon() { pocket.setBattlePokemon(testPokemon); assertEquals(testPokemon, pocket.getBattlePokemon()); } @Test(timeout = 50) public void testGetPokemons() { assertEquals(new ArrayList<>(), pocket.getPokemons()); } @Test(timeout = 50) public void testAdd() { pocket.add(testPokemon); assertNotEquals(new ArrayList<>(), pocket.getPokemons()); } @Test(timeout = 50) public void testGet() { pocket.add(testPokemon); assertEquals(testPokemon, pocket.get(0)); } @Test(timeout = 50) public void testSize() { assertEquals(0, pocket.size()); pocket.add(testPokemon); assertEquals(1, pocket.size()); } }
comprakt/comprakt-fuzz-tests
output/a9f0d2e1903742379a6072eccc947aa0.java
class JuFpp { public boolean y2ca; public int[] WYW () throws XX0xdMI { { ; ; { void _K_lHig2r; } ( this.anpK66O3o).f5JODo0N; while ( false[ 13.g8SGAPM]) if ( this.V) if ( !new Rsg0Q6LuEb().J_hvT) -!( -new boolean[ !!null[ -!-!true[ -new LwYcp5().fPe_]]].inccTE).gO0w; ; sgkp_qUGKa[][] XAf; return; { ; } ; Fz5pdhMi0LxMe[] ENktNnEcEdPp5; !!!!-true.Omm; int ihV4kCTm; boolean[][][][][] xcH; boolean[] W8MMsCZPzAAX; boolean[][] G66h9; int[] YkFoRHTaHTYalL; void[][][] M6YVunq; } return; int zWo; ; o ntSk7sl3LES2; ; } public static void i (String[] a_Mj) { boolean Z89pkCvvMZQcx; while ( this.oEJ7PqoDklP) { if ( --this.P0JVx6) { B6lNtkFvOoxEk _qB8B; } } { int joaRy3; if ( null.p0RT) ---true[ null.F34oAV4Z2_Vy]; if ( -!HwPkADFl().eDXEts1FixFlGP) while ( new NhY1keOu7TFPS().k5jGRQEzsu()) { while ( -false.ao_n8FsnJBXWX) return; } while ( !( null._n()).fov) return; if ( 46417699.oxp3SmcM5E) ; int[][][][] wRQZHNli7g; return; ; while ( --new nTntlibw[ !this[ null.H6_kBy()]][ !!-!-!true[ ( TdE[ -!-b7g5B_Qrt().upwU9()]).C8i1vJvqBB2u]]) return; return; { { ds3[][][][][] N5uM5lcQUfxvh1; } } } while ( !new void[ ( -!!!-true.fppuNf3nEoc33())[ iZ().b]].mCUxw0()) if ( new wHRY1ngi028[ true.nuCPyzkg].qywVaTclDo()) ; PAx9wLQl[][] pI6wvq3iOolPS3; if ( !!new C().lazfMUW9iT) while ( !!this.g805WmSk2z()) if ( !new Ba4()[ true[ -!new kxDLoBE().z7dn3Kwo()]]) if ( -( !null.Sr())[ -!15442490.rsx0oQtlwo]) while ( g6o3ByX[ -!-true.q2Ya]) if ( ( ----QbGSLEVj().YcKA0J_CBX).mhpE) return;else while ( ----tnjIYT0F7[ -true.Xa]) ; while ( false.vqFB9tYkuCWY) ; ; int[][][] Sx = -new void[ new qbOGXeYw().Y()].X() = --!-q.nBF7wrR; int[] vaPINPUI2yj = null.lsGgxeqwmM4A(); } public int[][][][][][] jfxOQdeNoQ0ej; public void h_pRR (rz W0, boolean oNnTN_mcRrgpD3) { boolean WMRELsgm6qG; return; new int[ -new BvyK[ !!-true.Sac2Lanr()]._p6iyWje][ !this.tABHBimntoAk_]; int Dur6mOhc4; jg8BSyq2SGPs[] ICjr0gHWmowWd = -true.Z8HZ2lRkgshw() = -false.OsrIWv; boolean GSO; boolean IHq9yoEh; void upCY = new void[ !tIf4svEpU().QBiX].Kh(); return; return this.u92t9Ar(); int hmJDErbAqfA; void uW7I5 = ------Du4j6BTDtw84Y()[ !!!( lF_yC.pk9MqvE).QqPptRsy3cB]; return; boolean[][] mumys2NsO8at; if ( !!false[ !false.zd4xSzePB1P()]) ; true[ --new I6QHQIwK().u8t0gbn()]; if ( ( -this.TBs).TAJMn7zwVYHI()) return;else ; if ( new n9sVsZg[ !null[ cq_cxk[ --new bBXt06u21YS1z()[ new boolean[ -OXRj3kuuvZVj_G()[ -tvjgbBA[ new nSDbwg4J9WY()[ !null.t_0_()]]]].RPuQHupUr_wo]]]][ 392411599.xE7]) if ( ( false.pmmpVl2SkOVy()).TncreOfTUxhV()) while ( -!!--!( -!BRnSlM9w1dv().tC0QSR7fCYmM).cI4aSLYuKjltn) { void[] Ne_TcWVnHBG; }else ( !!new boolean[ !!nh_SI77O.iuPY_bErGMGkXm][ new bysGH6vlX4t().nVJrTJOAUcd5W]).JiMB5(); o04Ycy_lvY Fe2; while ( !!--new void[ this.v9U()]._PQy3jbKaBr3H()) if ( !new boolean[ new void[ new int[ -new boolean[ false.lersyS7wAlSMX].oouEfK].aDY1ELzDsih_N1][ this.K]].Qx0Ldbm7AYjdDH) { xcqAzk[] ul2k0gXTsO; } } public boolean lSIx4iKfV6S; public d[][] engWhgho3X; public static void an (String[] n) throws qtOi { { while ( pnh515gWyxa3A().J) true[ new y().wcZwOpSjG0M()]; { return; } boolean[][][][][][] bLL3ncaqcd; { ; } boolean yXc0Z5N; int nl5Q6w; if ( !null[ true.i]) if ( --5[ !true.y0nQzA()]) { Vq qF6; } boolean g4doYTs_MV6yC; YYPgW[] Tgk; } boolean[][][][][] vJED3xKZN = !02838931.naOvFfRqI = this.RSzov(); int[] VKlrmAyH; while ( this.gDdJJ) ; rfn[] VI7NQJT85 = new S3WmTDYRjU3z()[ !( !!this.QuGCRw8).Z8()] = new L5QSN6uW0C[ !--false[ -!null.NF82Oyt2rLf0e]][ ( -new WW()._Ej9qDfFKnl5).fKfoVQmRoosU()]; ; int VjGCnoJ_h = -new u34NHM().m; void C08USBP8Me; boolean[][][][] oc = new void[ false[ !!-true.fG5Cnbejve1]].URkGRVTz() = -!--new Rsimn().fJOZ3ET(); boolean Q6DPr9C = !new jdVqc().vRSNv(); ; while ( !-( -new v6d9h7aMSZ().mpFFEPHbD).f) return; boolean G_Zr = -new void[ !!3[ -06150832.x7iGfEfh()]].frquTMPqB(); } } class BK { public static void lWYfwdstjo (String[] rVuwzZim23KCLO) throws LlfC { ; if ( !T_Wo[ new pL7dDNQ9Z3[ -!this.XSH3P()].R()]) return;else return; void lBrG_xr76AvCAo; int[] Nc3ixd; while ( --this.C) return; while ( false.ZSeTeioml5C()) while ( -new OiGjsOyjiI9wX().vgEqVYVaE2bIJn) return; { wnkIRksW[] iDI9gN; int[] qfj53L; void[][][] pN; boolean trdh2Bp6kmAwu7; lX9El8r jEX7zQ; void[] onPgqmW76kvHO6; ; void cvPCAhWC; void K; !-C().NbccgkgLP_V7a4(); while ( uebTcFBmfZP.dZWcW7Ul5Ut2U4) while ( true.M5Bv86()) return; int[][][] yXojfE8B6xn7MM; 47886146.nPbV_Kfc; false.ze; Mcrosj1n[] TdyfipUa3hKb; int DMADN; { boolean[] gJf3QAZK; } ; return; void aTqE7vkJhdDAf; } hdk95MM YVP2ES_oaW; { void[] ghvX_dE2I; while ( -null.LtxxMsXeSQ()) -!WcE4[ !null.KeqSvx]; return; ; boolean[][][] S6WwxYC_enUc; boolean i19; int bKWQr; boolean PJ80H; int[] ezdrB; aT87FK Bbk5L; if ( this[ !new void[ !true[ new tFxfrG7wh().cPDb2iaxM()]][ !null[ !null[ -this[ -new P7O()[ -pT.w7XyAZWfTeL6()]]]]]]) ; if ( -true.W()) ; ; return; if ( -!null[ ( XBHuKR9G3.wJ7Zif0wM0oaR3).FiImfav]) if ( -!!ZSZvhO().NtspoppJ()) -new boolean[ Cu0[ -!!-!!!true[ !!316833.kj()]]].cWjcoAZcp6Yh(); } int[][][] w9QeVUNEr = !new int[ n7LWQVXr_2().hBIZ()].QcCPEncyK; AbORuyvTJDpgF7[][][] tjsUX; } public boolean[] Cbse () throws uqTom8TV7Sffv { ; } public int uK81DkfAYoM (int[][][][][][][] cKCESb, boolean[][][] wFC_nJ8SNN_3U, void y8uWguU, D3J GhMr19v_U3W, Wu2mhLkY2A[] t) throws PyYCfELqib7KRL { while ( !Sz2QeKxPg4().d1BPEW0lW0d3Hg) if ( true.K8hm2u6M9TIU) ; while ( -false[ -new IDz7xIDh[ u().PE29OuaV9ki()][ new int[ -null.zVb0IIV5K7C()].fHXAcgk()]]) ; gmNuOZryQD[] uwHI = WLddvBS()[ u.aedjkh8XDY8u] = ( _fdse8Gda[ !!!!wPzHIEAEB[ !iho.JpvbRp()]]).aWAh5p5u; ; if ( --QWKbsaol.oUmzORfU()) return; { HMBUdZgCFrEU6[][][] Zd4; void k2zQ; int OWdTBZEVq; while ( true[ !new void[ 14789.ouK1O][ !-( SxNYCs().vVyr85).ocs4wW1acrq]]) return; while ( -false.LNst0tb()) if ( !this[ Xm_RWtYB36Z9c.TKvV]) { boolean pc3m; } ; ; boolean[] pPIimwNy94a; sQdZGD[] z; ; return; { !this.WNurcDyz7TNG(); } 974996.axV(); while ( this.nP1ueXdZ) while ( qZ.C2uS()) -602901.EF(); ; this[ QXqsATIi8().aRGbLzK_0T15X]; } if ( -null[ -!!-!-null.gq0FazcFX()]) while ( -!---null[ this[ -this[ ( false.kzsJi4zQ8b).QYh20GKBjbT]]]) ; p8Ak_oh[] f52m1BWusD = new Or().tRUlKboxu70; if ( false[ false[ -new cNWj3HBfBcSGFX().XCSGnyDFWJ8]]) if ( -true.L()) while ( -true.r0vprZE20) while ( !new dvGEs6V1GbNwz[ !new int[ null.j1PlZ4TV2is3V].YY].Z7CGnX) ;else { fNlNN[][] TWJ; } { int bAv; return; boolean[][][] xnty9wPuQwqX; while ( -new int[ ( --699601561.h1dC()).JyDlQWM()].QKe9SXR) ; } boolean hV; if ( -!-!null[ ( -null[ !false.Q7cz()]).bfx2LzF9Gb]) { boolean moNT5zGQm; }else return; } public void m3NFmTg5; public static void kNn (String[] ELTMaOh) throws uZJ { if ( false.gr87tg7RiUA()) while ( new void[ !-!this[ !this.Lti()]].iaatXM()) while ( --t6X().f38) ; boolean[][][][][] aeU = new G_yOJtGXM6t[ this.o4rDZftulK()][ -new int[ true.enSW0caUlP0N].CSz()]; if ( new cfK()[ this[ !-new s().NHjX]]) -new e[ new twnCzUz().HDKPKs()].qzZDD9HNUGN(); int QgXVLc3J; boolean[] YPhd; } } class yj7lgUt04468 { public boolean KAcnal5hW; public q069ci8 MQG (xsVk9 FlvsYez, boolean Khdj, boolean bpmUQIgo8dkok2, boolean Vc45cBr3oWS, void uBmfRGiOaoPi1) throws TLK6S4OD4o5D0 { int[][][][] Y1WYKrGoTU5V = -new FTTEySJh().MMmOb6w; boolean MurowbJlt0btv = --Sk95pRRFJYQ3zA().yHqAbP512gU1Mu; return; boolean[] q76OG30; int[] qNIJgnsDpDRC3x; } public static void H58N2o_ (String[] h7B6jLs0PJC) throws isTW { return -( new i4AA9kZ5WQXR9()[ !new int[ true[ new n_LqcDr8cE().u]].mvkAhJur5DIM_I]).Sb3wp7xkWuj; int[][][][][] oxs; int[] kHdUJsL; iLYauOOX0xEE rXQF1Hs8fCg = -( --this.t0zLGkUVILVk).Q7Pzv5no5() = new QIaYodgWwko9()[ ZHNRa.l()]; void DpkLvL3ZkBbV2 = --false.lF7pI() = 21519679.YIZTJmjT_F; -!false.lpcnSdGSn5oUH; ; int[] Yr9n; boolean[] Qk9Syfi; ; { return; -!null.ex(); !-qrxd()[ a8EsJo_WPaKb[ !!-XFA1B0xz().w()]]; kWAQNtBMDlh[] GP; ; boolean DkhDxhRQPqias; { void bsdB0C; } while ( --!null.IRyU7qIuv) new DxYqBWc()[ !true.I_A1]; boolean[] x; int[] yHVrDBBk60Lm; while ( new Of().I()) return; while ( -192675.h) while ( !new vJvPKuG().OwBFaPy()) while ( !!--!null.yQP6ROzqlQ_MK()) !x3tAq()[ uURb.aHLTHtI()]; int IPqxSIho; if ( null._NA()) if ( FqiegIikshqi3S.wgl6mJ4WIR) if ( new trCTBbcy()[ ( Grof2.aWagXfuKvxGe).OTy]) -G7A0C_().PmK(); int YXlFuRNW; } while ( -new boolean[ !95438288[ 96381034.sZ()]].OvGljSCGH()) return; boolean vFpbiHro; } public int fpD18nqHwWk6a; } class zW9ZXtRQElQ { } class sfeZ { } class VbuekowvZHC { } class ofRPCyl1 { public boolean myXBjboVf () throws iVAYdWW { !!!!new boolean[ !glVXAIuq()[ new b37nop564e().B0IDAO5()]][ !NlhQ().buiNxG6yt]; { { e5YAU9[][][] qP0_OqWndvw9Fv; } { 9681._hKw; } } } public static void x (String[] y) { u9KSFozRWvc ktlZsEAe9kk7g = -oaHQHAsyX.g = 497545[ !this.zwW]; eZ4 VXngaDa50NPg1w = new int[ !-new hTPmL6AE6zR0nh()[ -!true.q_nAWb()]].U3ukE5QzLbE; while ( false[ ( !-new lZl5_35().H9n()).Jdu]) ; int M7LCVn4sgO; { while ( !-new boolean[ -( -this.Sr8FExE)[ null.JKK3UX8ePcCke()]][ -!false._5U4SmnRWKr()]) new boolean[ -!-Tk7j().Um0GOyoIZqr09Q][ !!--new l()[ 7364.q7Xm()]]; ; int[][][][][] gHP; boolean AOMcMmt; -ZCA().OtLl4WgkdE(); void UCTI6w; m[] LMY0fSo97vaQ; ; int[][] j; beG8t8GO[] nrI_; if ( -!false.aS2cIBZPln8) !false.PUjB1G2(); ; { return; } ; int[] PAqdrn5x; return; if ( this[ new void[ new gE5()[ !!true[ !y9db.Z]]].CMzw9tch]) new xo9ob87KSSSn().Fj; } boolean[][] vKF; Dj1 rOTon; ; { int i1atr1G; while ( ZfX7J.hSE) if ( this.bd3cD) while ( this.JPmdrpjjog()) { int[] bZesN1u; } while ( false.DD) if ( x()[ -this.TAETOfkIsV]) while ( !!true.RxhPGyU) ; if ( xiuAHgq1G8().uYzxn) !( -!!ubOR[ !!!true.X_xTKMr()])[ !-nsy03L3BcTX.OeYXSMOO6Rl]; int[] Bc3; !this.FYkwgLcckf; { while ( -this.KwWg_utY5nx_8p()) if ( 44[ null.NW()]) { !cgM8.QI8s(); } } if ( true.lR84sU()) return; int[] uHlwu6WIHhn; void[][] Cczg9k; void[] k; boolean h2N; { boolean bXzxJIGNWJH8k; } boolean[] mzeNB; { boolean A; } } while ( null.ujBZ6bIqlCrfk) return; q7oSRrIiLd xuvxYabcD4k67 = mW6fBikTBb6().U9zZ8n = o.uA; } public void[][][][][][] AIo0heP1w (void eXyt8, int ZDdAVTLG, boolean GN) throws otvLVd2 { this.Ih8(); { return; int t5xieh4; boolean huUfCQ; return; } boolean[][][] b9JW7AC1W9YME; if ( -this.p5kwWELj()) if ( Y.CUFXlldU2()) ;else if ( !this[ false[ !!( !true[ new MTFzpUW()[ !-555.NuaQrFn8A5Kj34]])[ VFwLRof[ new HiquggJTvcuRc().R]]]]) ; void JAQn = !new int[ !!--52969102.Tc1heH()].w4t599otL; if ( true.my()) ;else ; void ijcuIhOcJjfi = !!cP26LNQMWkn46z().I0RNli73shm3; int JmgaB3btSEelE = -false.RX(); true[ !!true[ new _yvOUzE_0_wvB().w()]]; while ( HS4OvFu5xNn6().MTBC444a_vv1VW()) ; ; int FsOvv1VIsHx2c = new GTyiGtcv9Oq82().o2ct35MoWPPKn8 = -null.LjYm(); N_lAlCIpQxjpL3[] z = !new nBP().PS6a8XbqFA7; if ( --ytS4e6x70().Ty4LO4f3ph_ugq()) while ( ( -!!null.KZ()).VNRdGEXPHb) return;else ; } } class bWS3xaqwh { } class H9 { public int SzWBakxBF7; public boolean G_1l3hFubK3H; public int W; public boolean eq (boolean Fu807dZPZ2, X0qd8i[] ROt12PezX1MxD, int[][][][] _A5dhcNN) { -m9QF.B(); ; void jU3dmjfM; } public int[][] XLRDx () { if ( -new O8Pn09j().X4) new RhDPyJO7n().Xm8KwrCqKxVw4J();else { while ( !new boolean[ this[ -!!this.BS1xTa8DcYV8H()]].s_cDY()) return; } void wgEw7XDtBv = this.qDV; boolean[] AveImeOCxTy6 = !-!!!it.RMl3JMk(); naFCrFSzDLj_1l zh = new int[ true.KiwTcC()].jD5I8K_(); return --!51448993.npT; nBXqK qKDpKpvhviA = 2489[ 646969.HfU06FhXHHKjQ] = MeNY2StsXR()[ !-( -!!-this.T8zJ4mfoXjS5W()).jxr6AE]; void[][] d5nV3 = V[ -!new int[ !XQSO1C6nHg.P5Y56fzIKnKv][ new void[ ---new boolean[ -!true.uVckfclR7c()].vlwSGbrZFRlg][ ( ( --HR5Kgaqb[ ( -new boolean[ --pIkIy7XqcRCVB[ ( true[ h_HSM2.YWi4j9fPTdct]).Bjj]].q8Vhtoesrgp())[ this.rrIJrdhX]])[ !!false.kkWetE50d()])[ true.bRJlS13dCgqd3H()]]]] = !false.sMKjP_Rmo(); void[] y0n4Tew = --new lu5xOqw().QrfLM1uBsg6; { H7ELxSJm_7pu0[] yT1Bs; ; return; { if ( new int[ !null.RDgVxZpkz_].xTTcG0v) -!!1.cgIPbARnCfd; } } int[] fpUgZFAftX_u = -!-false[ 009091[ ( new BnWE().P77bWWOEV())[ -FH()[ null.JGQFqLa62zJ()]]]] = -!!new boolean[ -!-!null.HWAJ][ !!!new int[ true[ !-!agqDfArm()[ null.aaxzeLb_MTw()]]].Bd()]; { while ( -this.H()) { ; } { return; } void qe; tF5w[] qKF2n0ZlUNelX; while ( true.VMQ()) { return; } { return; } boolean[] v9i_PWX6JSAC; return; this._5DN7fKamL; ---399690[ new G9S().JhXiogel6jN()]; JG5 _m; boolean DLEppSMWB2k; SV2q7Yf[] eREAakP; S a8ht8aNd7Z; int[] w; new BaJxCuFB7[ fI6EFYyr297[ 4703655.K09zFO]].pBb(); } } public void SRK7kohJWLLsMz; public void[] u3uThyCiM5oJ3O; public boolean[] nMBg (void[] yxDKp4_ykgaLd) { return; while ( this[ new h[ -vP9NW425.w].LA7v]) if ( new E0YpUKhql[ !-new TQdAVcZT().ffkA3F1bnl9jaz]._eFrWLwbM) while ( null[ false.ZWLruxdSHv]) g_jD[ -145[ false[ ( mAoQrBKyv8().EpXwD)[ -!!this.ojR0Q()]]]]; ; boolean[][][] mt9waNHPPr0 = hdTTE7sb6vG()[ -t3Z.F0naqVDg3ez()] = new void[ null.yhB1iqrvUg0il].hsDVI1YtK; void[][][] S; { void[] qy6s1H; boolean aQ; boolean g2NO; ; boolean[] ZaEXYOmC; return; { int dHGkZ; } if ( U4whnX2.F_SayuOBacEQ) return; Qo GROOkUq; return; int[][] WyfiiWOcotBMr; } -!-34.HdTE; if ( -7952.fFvB9W) { void[][][] B8uC4id; } KeYIm84Rx[][] G8XL = null.GCB5KfG47L_okK(); jBd[][][][][] sOyVt28KC = new boolean[ !!( !!--!!3717[ -new O2pfdSg9ccoX0A().yKNzAy]).oHZBmbOWkOxKv0].s; void[] NT7R = !!!-true.S7() = !--!znQ().ZDfL3v8NXbmZr(); ; { _MDoCtg0[][] DA; while ( !jiaVG2LU3J.oqvXTZ()) if ( this.P_MWt961oI1nuH) if ( -wqyRZEIGc().L1) return; new int[ !( !-new v60q3mm[ 539062866._O0()].cqSZW())[ !this.UwiMsO_()]][ !true[ -null.zUpCYGHWiTjDA()]]; boolean mhdCHf; void uZ; ; if ( ( -!new YetXcJAyMM().WNPGf7MM9R6())[ !this[ new tHhbA_2bO96().hZ6Q()]]) !-new boolean[ !-cUm6VXkIO5r.kl9].H(); int YR; int aRUcq67c; return; return; boolean y; void xG9t; void qBmtFEMNqhC; while ( !yNM0ASHQrmsfW().gIZqMvVNifY8ZH()) ; ; true.dYIui; void ElfKhpv_dSQzJ7; void[][] YADCmrzWjBG; -null.c; } } public static void Z4Sn8XNjw (String[] QKW7) { FK1hx4qkZfC jt4eNB2I; if ( false.OdQR()) if ( false[ false.Uq45err7mF4zb]) return;else if ( !a_cGw3QB5.R2zWVxMBmn) return; ; this[ -new XOgru().hV6Nm9c4NQ]; if ( -( false.W2JxmkV0xBrihM()).LI8vLSy) ( !-!new r45LG0MFSgePCk[ this.ESDcsgE].wFD60tmaKwTY3).FDC0wGYKKin;else true[ !----!new void[ 5029709.NxSw6vbnxUd()].iC1IoD]; wswynXntw[][][] xtO8LN4H8 = -!-!new boolean[ ( MMXbRpJBHZyPLr._De)[ true[ false[ -this.WlRrlOFeBjJq]]]].IgVcr2; } } class e6hpEh8q { }
MarcOliva/Rest-Api-Colegio
src/main/java/com/oliva/marc/controller/TeacherController.java
package com.oliva.marc.controller; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import com.oliva.marc.exception.ModeloNotFoundException; import com.oliva.marc.model.entity.Teacher; import com.oliva.marc.service.ITeacherService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @RestController @RequestMapping("/profesores") @Api(value = "Servicio Web RESTful de profesores") public class TeacherController { @Autowired private ITeacherService teacherService; @ApiOperation("Retorna una lista de profesores") @GetMapping public ResponseEntity<List<Teacher>> listar() { List<Teacher> teachers = new ArrayList<>(); teachers = teacherService.findAll(); return new ResponseEntity<List<Teacher>>(teachers, HttpStatus.OK); } @ApiOperation("Retorna una lista de profesores por id") @GetMapping(value = "/{id}") public ResponseEntity<Teacher> listarId(@PathVariable("id") Long id) { Optional<Teacher> teacher = teacherService.findById(id); if (!teacher.isPresent()) { throw new ModeloNotFoundException("ID: " + id); } return new ResponseEntity<Teacher>(teacher.get(), HttpStatus.OK); } @ApiOperation("Registra un profesor") @PostMapping public ResponseEntity<Teacher> registrar(@RequestBody Teacher teacher) { Teacher teacherNew = new Teacher(); teacherNew = teacherService.insert(teacher); URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(teacherNew.getId()) .toUri(); return ResponseEntity.created(location).build(); } @ApiOperation("Modifica un profesor") @PutMapping public ResponseEntity<Teacher> actualizar(@RequestBody Teacher teacher) { teacherService.update(teacher); return new ResponseEntity<Teacher>(HttpStatus.OK); } @ApiOperation("Elimina un profesor") @DeleteMapping(value = "/{id}") public void eliminar(@PathVariable Long id) { Optional<Teacher> teacher = teacherService.findById(id); if (!teacher.isPresent()) { throw new ModeloNotFoundException("ID: " + id); } else { teacherService.delete(id); } } }
DeltixInc/ValueTypes4Java
java/test7/src/test/java/deltix/vtype/test/SafeArrayCopy.java
<reponame>DeltixInc/ValueTypes4Java /* * Copyright 2017-2018 Deltix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package deltix.vtype.test; /** * Stub implementation of a typical array copying method, used in some tests. */ public class SafeArrayCopy { // @SafeVarargs // public static <Generic> Generic[] asArray(Generic... array) { // return array; // } public static <Generic> void safeArrayCopy(Generic[] src, int srcPos, Generic[] dest, int destPos, int length) { System.arraycopy(src, srcPos, dest, destPos, length); } public static void safeArrayCopy(int[] src, int srcPos, int[] dest, int destPos, int length) { System.arraycopy(src, srcPos, dest, destPos, length); } public static void safeArrayCopy(byte[] src, int srcPos, byte[] dest, int destPos, int length) { System.arraycopy(src, srcPos, dest, destPos, length); } public static void safeArrayCopy(long[] src, int srcPos, long[] dest, int destPos, int length) { System.arraycopy(src, srcPos, dest, destPos, length); } public static void safeArrayCopy(double[] src, int srcPos, double[] dest, int destPos, int length) { System.arraycopy(src, srcPos, dest, destPos, length); } }
mohdab98/cmps252_hw4.2
src/cmps252/HW4_2/UnitTesting/record_1928.java
package cmps252.HW4_2.UnitTesting; import static org.junit.jupiter.api.Assertions.*; import java.io.FileNotFoundException; import java.util.List; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import cmps252.HW4_2.Customer; import cmps252.HW4_2.FileParser; @Tag("35") class Record_1928 { private static List<Customer> customers; @BeforeAll public static void init() throws FileNotFoundException { customers = FileParser.getCustomers(Configuration.CSV_File); } @Test @DisplayName("Record 1928: FirstName is Ricky") void FirstNameOfRecord1928() { assertEquals("Ricky", customers.get(1927).getFirstName()); } @Test @DisplayName("Record 1928: LastName is Quituqua") void LastNameOfRecord1928() { assertEquals("Quituqua", customers.get(1927).getLastName()); } @Test @DisplayName("Record 1928: Company is Babin, Bill J Jr") void CompanyOfRecord1928() { assertEquals("Babin, Bill J Jr", customers.get(1927).getCompany()); } @Test @DisplayName("Record 1928: Address is 3755 Lake City Hwy #-1") void AddressOfRecord1928() { assertEquals("3755 Lake City Hwy #-1", customers.get(1927).getAddress()); } @Test @DisplayName("Record 1928: City is Warsaw") void CityOfRecord1928() { assertEquals("Warsaw", customers.get(1927).getCity()); } @Test @DisplayName("Record 1928: County is Kosciusko") void CountyOfRecord1928() { assertEquals("Kosciusko", customers.get(1927).getCounty()); } @Test @DisplayName("Record 1928: State is IN") void StateOfRecord1928() { assertEquals("IN", customers.get(1927).getState()); } @Test @DisplayName("Record 1928: ZIP is 46580") void ZIPOfRecord1928() { assertEquals("46580", customers.get(1927).getZIP()); } @Test @DisplayName("Record 1928: Phone is 574-268-8651") void PhoneOfRecord1928() { assertEquals("574-268-8651", customers.get(1927).getPhone()); } @Test @DisplayName("Record 1928: Fax is 574-268-7329") void FaxOfRecord1928() { assertEquals("574-268-7329", customers.get(1927).getFax()); } @Test @DisplayName("Record 1928: Email is <EMAIL>") void EmailOfRecord1928() { assertEquals("<EMAIL>", customers.get(1927).getEmail()); } @Test @DisplayName("Record 1928: Web is http://www.rickyquituqua.com") void WebOfRecord1928() { assertEquals("http://www.rickyquituqua.com", customers.get(1927).getWeb()); } }
kkcookies99/UAST
Dataset/Leetcode/train/1/116.js
var XXX = function(nums, target) { for(var i = 0; i < nums.length - 1; i++){ for( k = i + 1; k < nums.length -1 ; k++){ if(nums[i]+nums[k] == target){ return [i,k]; } } } }; undefined for (i = 0; i < document.getElementsByTagName("code").length; i++) { console.log(document.getElementsByTagName("code")[i].innerText); }
TileDB-Inc/TileDB-CF-Py
tests/netcdf_engine/test_convert_timestamp.py
# Copyright 2021 TileDB Inc. # Licensed under the MIT License. import numpy as np import pytest import tiledb from tiledb.cf import NetCDF4ConverterEngine netCDF4 = pytest.importorskip("netCDF4") class TestCopyAtTimestamp: """Test copying a simple NetCDF file at a specified timestamp. NetCDF File: dimensions: x (8) variables: f (x) = np.linspace(0, 1, 8) """ attr_data = np.linspace(0, 1, 8) def test_copy_to_timestamp(self, tmpdir): uri = str(tmpdir.mkdir("output").join("timestamp_array")) timestamp = 1 with netCDF4.Dataset("tmp", mode="w", diskless=True) as dataset: dataset.setncatts({"title": "test timestamp"}) dataset.createDimension("x", 8) var = dataset.createVariable("f", np.float64, ("x",)) var[:] = self.attr_data converter = NetCDF4ConverterEngine.from_group(dataset) converter.convert_to_array( uri, input_netcdf_group=dataset, timestamp=timestamp ) with tiledb.open(uri, timestamp=(1, 1)) as array: assert array.meta["title"] == "test timestamp" result_data = array[:]["f"] np.testing.assert_equal(self.attr_data, result_data)
starmarke/starmarke
node_modules/istanbul-lib-instrument/src/index.js
const { defaults } = require('@istanbuljs/schema'); const Instrumenter = require('./instrumenter'); const programVisitor = require('./visitor'); const readInitialCoverage = require('./read-coverage'); /** * createInstrumenter creates a new instrumenter with the * supplied options. * @param {Object} opts - instrumenter options. See the documentation * for the Instrumenter class. */ function createInstrumenter(opts) { return new Instrumenter(opts); } module.exports = { createInstrumenter, programVisitor, readInitialCoverage, defaultOpts: defaults.instrumenter };
webdevhub42/Lambda
WEEKS/CD_Sata-Structures/_RESOURCES/CODESIGNAL/tennis_set.py
def tennisSet(score1, score2): return ( True if score1 == 6 and score2 < 5 or score1 < 5 and score2 == 6 or score1 == 7 and 5 <= score2 < 7 or score2 == 7 and 5 <= score1 < 7 else False )
flomar/CrypTool-VS2015
trunk/CrypTool/PrimePolynom.h
<gh_stars>0 /************************************************************************** Copyright [2009] [CrypTool Team] This file is part of CrypTool. 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. **************************************************************************/ #ifndef POLY_H #define POLY_H #include <vector> #include "gmp.h" #include "gmpxx.h" // using namespace std; //typedef mpz_class INT; class PrimePolynom { public: PrimePolynom(); PrimePolynom(const std::vector<mpz_class>& v); mpz_class operator[](int pos); int operator==(const PrimePolynom& p); int operator!=(const PrimePolynom& p); PrimePolynom operator+(const PrimePolynom& p); PrimePolynom operator*(const PrimePolynom& p); PrimePolynom operator^(mpz_class b); PrimePolynom mod_pol(int r); int get_degree(); static void set_m(const mpz_class& n); static void set_field(int r); static int get_field(void); static vector<mpz_class> create_rhs(); int print(); private: std::vector<mpz_class> vec; int degree; static int field; static mpz_class m; int ref_deg(); }; #endif
cycloidio/cycloid-cli
client/client/organization_config_repositories/create_config_repository_responses.go
// Code generated by go-swagger; DO NOT EDIT. package organization_config_repositories // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "fmt" "io" "github.com/go-openapi/errors" "github.com/go-openapi/runtime" "github.com/go-openapi/swag" "github.com/go-openapi/validate" strfmt "github.com/go-openapi/strfmt" models "github.com/cycloidio/cycloid-cli/client/models" ) // CreateConfigRepositoryReader is a Reader for the CreateConfigRepository structure. type CreateConfigRepositoryReader struct { formats strfmt.Registry } // ReadResponse reads a server response into the received o. func (o *CreateConfigRepositoryReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { switch response.Code() { case 200: result := NewCreateConfigRepositoryOK() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return result, nil case 404: result := NewCreateConfigRepositoryNotFound() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 411: result := NewCreateConfigRepositoryLengthRequired() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 422: result := NewCreateConfigRepositoryUnprocessableEntity() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result default: result := NewCreateConfigRepositoryDefault(response.Code()) if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } if response.Code()/100 == 2 { return result, nil } return nil, result } } // NewCreateConfigRepositoryOK creates a CreateConfigRepositoryOK with default headers values func NewCreateConfigRepositoryOK() *CreateConfigRepositoryOK { return &CreateConfigRepositoryOK{} } /*CreateConfigRepositoryOK handles this case with default header values. Success creation */ type CreateConfigRepositoryOK struct { Payload *CreateConfigRepositoryOKBody } func (o *CreateConfigRepositoryOK) Error() string { return fmt.Sprintf("[POST /organizations/{organization_canonical}/config_repositories][%d] createConfigRepositoryOK %+v", 200, o.Payload) } func (o *CreateConfigRepositoryOK) GetPayload() *CreateConfigRepositoryOKBody { return o.Payload } func (o *CreateConfigRepositoryOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(CreateConfigRepositoryOKBody) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewCreateConfigRepositoryNotFound creates a CreateConfigRepositoryNotFound with default headers values func NewCreateConfigRepositoryNotFound() *CreateConfigRepositoryNotFound { return &CreateConfigRepositoryNotFound{} } /*CreateConfigRepositoryNotFound handles this case with default header values. The response sent when any of the entities present in the path is not found. */ type CreateConfigRepositoryNotFound struct { /*The length of the response body in octets (8-bit bytes). */ ContentLength uint64 Payload *models.ErrorPayload } func (o *CreateConfigRepositoryNotFound) Error() string { return fmt.Sprintf("[POST /organizations/{organization_canonical}/config_repositories][%d] createConfigRepositoryNotFound %+v", 404, o.Payload) } func (o *CreateConfigRepositoryNotFound) GetPayload() *models.ErrorPayload { return o.Payload } func (o *CreateConfigRepositoryNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { // response header Content-Length contentLength, err := swag.ConvertUint64(response.GetHeader("Content-Length")) if err != nil { return errors.InvalidType("Content-Length", "header", "uint64", response.GetHeader("Content-Length")) } o.ContentLength = contentLength o.Payload = new(models.ErrorPayload) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewCreateConfigRepositoryLengthRequired creates a CreateConfigRepositoryLengthRequired with default headers values func NewCreateConfigRepositoryLengthRequired() *CreateConfigRepositoryLengthRequired { return &CreateConfigRepositoryLengthRequired{} } /*CreateConfigRepositoryLengthRequired handles this case with default header values. The request has a body but it doesn't have a Content-Length header. */ type CreateConfigRepositoryLengthRequired struct { } func (o *CreateConfigRepositoryLengthRequired) Error() string { return fmt.Sprintf("[POST /organizations/{organization_canonical}/config_repositories][%d] createConfigRepositoryLengthRequired ", 411) } func (o *CreateConfigRepositoryLengthRequired) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { return nil } // NewCreateConfigRepositoryUnprocessableEntity creates a CreateConfigRepositoryUnprocessableEntity with default headers values func NewCreateConfigRepositoryUnprocessableEntity() *CreateConfigRepositoryUnprocessableEntity { return &CreateConfigRepositoryUnprocessableEntity{} } /*CreateConfigRepositoryUnprocessableEntity handles this case with default header values. All the custom errors that are generated from the Cycloid API */ type CreateConfigRepositoryUnprocessableEntity struct { /*The length of the response body in octets (8-bit bytes). */ ContentLength uint64 Payload *models.ErrorPayload } func (o *CreateConfigRepositoryUnprocessableEntity) Error() string { return fmt.Sprintf("[POST /organizations/{organization_canonical}/config_repositories][%d] createConfigRepositoryUnprocessableEntity %+v", 422, o.Payload) } func (o *CreateConfigRepositoryUnprocessableEntity) GetPayload() *models.ErrorPayload { return o.Payload } func (o *CreateConfigRepositoryUnprocessableEntity) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { // response header Content-Length contentLength, err := swag.ConvertUint64(response.GetHeader("Content-Length")) if err != nil { return errors.InvalidType("Content-Length", "header", "uint64", response.GetHeader("Content-Length")) } o.ContentLength = contentLength o.Payload = new(models.ErrorPayload) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewCreateConfigRepositoryDefault creates a CreateConfigRepositoryDefault with default headers values func NewCreateConfigRepositoryDefault(code int) *CreateConfigRepositoryDefault { return &CreateConfigRepositoryDefault{ _statusCode: code, } } /*CreateConfigRepositoryDefault handles this case with default header values. The response sent when an unexpected error happened, as known as an internal server error. */ type CreateConfigRepositoryDefault struct { _statusCode int /*The length of the response body in octets (8-bit bytes). */ ContentLength uint64 Payload *models.ErrorPayload } // Code gets the status code for the create config repository default response func (o *CreateConfigRepositoryDefault) Code() int { return o._statusCode } func (o *CreateConfigRepositoryDefault) Error() string { return fmt.Sprintf("[POST /organizations/{organization_canonical}/config_repositories][%d] createConfigRepository default %+v", o._statusCode, o.Payload) } func (o *CreateConfigRepositoryDefault) GetPayload() *models.ErrorPayload { return o.Payload } func (o *CreateConfigRepositoryDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { // response header Content-Length contentLength, err := swag.ConvertUint64(response.GetHeader("Content-Length")) if err != nil { return errors.InvalidType("Content-Length", "header", "uint64", response.GetHeader("Content-Length")) } o.ContentLength = contentLength o.Payload = new(models.ErrorPayload) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } /*CreateConfigRepositoryOKBody create config repository o k body swagger:model CreateConfigRepositoryOKBody */ type CreateConfigRepositoryOKBody struct { // data // Required: true Data *models.ConfigRepository `json:"data"` } // Validate validates this create config repository o k body func (o *CreateConfigRepositoryOKBody) Validate(formats strfmt.Registry) error { var res []error if err := o.validateData(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (o *CreateConfigRepositoryOKBody) validateData(formats strfmt.Registry) error { if err := validate.Required("createConfigRepositoryOK"+"."+"data", "body", o.Data); err != nil { return err } if o.Data != nil { if err := o.Data.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("createConfigRepositoryOK" + "." + "data") } return err } } return nil } // MarshalBinary interface implementation func (o *CreateConfigRepositoryOKBody) MarshalBinary() ([]byte, error) { if o == nil { return nil, nil } return swag.WriteJSON(o) } // UnmarshalBinary interface implementation func (o *CreateConfigRepositoryOKBody) UnmarshalBinary(b []byte) error { var res CreateConfigRepositoryOKBody if err := swag.ReadJSON(b, &res); err != nil { return err } *o = res return nil }
hxcorp/DongTai-agent-java
dongtai-core/src/main/java/io/dongtai/iast/core/handler/hookpoint/service/url/KafkaUrlHandler.java
<reponame>hxcorp/DongTai-agent-java package io.dongtai.iast.core.handler.hookpoint.service.url; import java.util.ArrayList; import java.util.List; public class KafkaUrlHandler implements ServiceUrlHandler { @Override public List<ServiceUrl> processUrl(String host, String port) { List<ServiceUrl> urls = new ArrayList<ServiceUrl>(); String[] hosts = host.split(","); for (String url : hosts) { if (url.isEmpty()) { continue; } String[] hostAndPort = url.split(":"); if (hostAndPort.length == 2 && !hostAndPort[0].isEmpty() && !hostAndPort[1].isEmpty()) { urls.add(new ServiceUrl(hostAndPort[0], hostAndPort[1])); } } return urls; } }
yennanliu/Python_basics
leetcode_python/Tree/average-of-levels-in-binary-tree.py
""" Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10-5 of the actual answer will be accepted. Example 1: Input: root = [3,9,20,null,15,7] Output: [3.00000,14.50000,11.00000] Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11]. Example 2: Input: root = [3,9,20,15,7] Output: [3.00000,14.50000,11.00000] Constraints: The number of nodes in the tree is in the range [1, 104]. -231 <= Node.val <= 231 - 1 """ # TODO : implement bfs as well # V0 # IDEA : DFS class Solution(object): def averageOfLevels(self, root): """ :type root: TreeNode :rtype: List[float] """ res = [] l = 0 self.dfs(root, l, res) return [sum(line) / float(len(line)) for line in res] def dfs(self, root, level, res): if not root: return ### NOTE : this trick if level >= len(res): res.append([]) res[level].append(root.val) if root.left: self.dfs(root.left, level + 1, res) if root.right: self.dfs(root.right, level + 1, res) # V0' # IDEA : DFS class Solution(object): def averageOfLevels(self, root): """ :type root: TreeNode :rtype: List[float] """ res = [] self.dfs(root, 0, res) return [sum(line) / float(len(line)) for line in res] def dfs(self, root, level, res): if not root: return ### NOTE : this trick if level >= len(res): res.append([]) res[level].append(root.val) self.dfs(root.left, level + 1, res) self.dfs(root.right, level + 1, res) # V1 # https://blog.csdn.net/fuxuemingzhu/article/details/79088554 # DFS V1 # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def averageOfLevels(self, root): """ :type root: TreeNode :rtype: List[float] """ info = [] # the first element is sum of the level,the second element is nodes in this level def dfs(node, depth=0): if not node: return if len(info) <= depth: info.append([0, 0]) info[depth][0] += node.val info[depth][1] += 1 # print(info) dfs(node.left, depth + 1) dfs(node.right, depth + 1) dfs(root) return [s / float(c) for s,c in info] # V1' # https://blog.csdn.net/fuxuemingzhu/article/details/79088554 # DFS V2 # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def averageOfLevels(self, root): """ :type root: TreeNode :rtype: List[float] """ res = [] self.getLevel(root, 0, res) return [sum(line) / float(len(line)) for line in res] def getLevel(self, root, level, res): if not root: return if level >= len(res): res.append([]) res[level].append(root.val) self.getLevel(root.left, level + 1, res) self.getLevel(root.right, level + 1, res) # V1'' # https://blog.csdn.net/fuxuemingzhu/article/details/79088554 # BFS # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def averageOfLevels(self, root): """ :type root: TreeNode :rtype: List[float] """ que = collections.deque() res = [] que.append(root) while que: size = len(que) row = [] for _ in range(size): node = que.popleft() if not node: continue row.append(node.val) que.append(node.left) que.append(node.right) if row: res.append(sum(row) / float(len(row))) return res # V2 # Time: O(n) # Space: O(h) class Solution(object): def averageOfLevels(self, root): """ :type root: TreeNode :rtype: List[float] """ result = [] q = [root] while q: total, count = 0, 0 next_q = [] for n in q: total += n.val count += 1 if n.left: next_q.append(n.left) if n.right: next_q.append(n.right) q = next_q result.append(float(total) / count) return result
JJediny/us-digital-registry
db/migrate/20120510200447_create_agency_contacts.rb
class CreateAgencyContacts < ActiveRecord::Migration def change create_table :agency_contacts do |t| t.string :email t.string :agency_id t.timestamps end add_index :agency_contacts, :agency_id end end
aps337/unum-sdk
src/uclibc/uClibc-0.9.33.2/test/nptl/tst-cond12.c
/* Copyright (C) 2003 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by <NAME> <<EMAIL>>, 2003. The GNU C 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. The GNU C 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 the GNU C Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #include <errno.h> #include <pthread.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/mman.h> #include <sys/wait.h> static char fname[] = "/tmp/tst-cond12-XXXXXX"; static int fd; static void prepare (void); #define PREPARE(argc, argv) prepare () static int do_test (void); #define TEST_FUNCTION do_test () #include "../test-skeleton.c" static void prepare (void) { fd = mkstemp (fname); if (fd == -1) { printf ("mkstemp failed: %m\n"); exit (1); } add_temp_file (fname); if (ftruncate (fd, 1000) < 0) { printf ("ftruncate failed: %m\n"); exit (1); } } static int do_test (void) { struct { pthread_mutex_t m; pthread_cond_t c; int var; } *p = mmap (NULL, sizeof (*p), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); if (p == MAP_FAILED) { printf ("initial mmap failed: %m\n"); return 1; } pthread_mutexattr_t ma; if (pthread_mutexattr_init (&ma) != 0) { puts ("mutexattr_init failed"); return 1; } if (pthread_mutexattr_setpshared (&ma, 1) != 0) { puts ("mutexattr_setpshared failed"); return 1; } if (pthread_mutex_init (&p->m, &ma) != 0) { puts ("mutex_init failed"); return 1; } if (pthread_mutexattr_destroy (&ma) != 0) { puts ("mutexattr_destroy failed"); return 1; } pthread_condattr_t ca; if (pthread_condattr_init (&ca) != 0) { puts ("condattr_init failed"); return 1; } if (pthread_condattr_setpshared (&ca, 1) != 0) { puts ("condattr_setpshared failed"); return 1; } if (pthread_cond_init (&p->c, &ca) != 0) { puts ("mutex_init failed"); return 1; } if (pthread_condattr_destroy (&ca) != 0) { puts ("condattr_destroy failed"); return 1; } if (pthread_mutex_lock (&p->m) != 0) { puts ("initial mutex_lock failed"); return 1; } p->var = 42; pid_t pid = fork (); if (pid == -1) { printf ("fork failed: %m\n"); return 1; } if (pid == 0) { void *oldp = p; p = mmap (NULL, sizeof (*p), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); if (p == oldp) { puts ("child: mapped to same address"); kill (getppid (), SIGKILL); exit (1); } munmap (oldp, sizeof (*p)); if (pthread_mutex_lock (&p->m) != 0) { puts ("child: mutex_lock failed"); kill (getppid (), SIGKILL); exit (1); } p->var = 0; #ifndef USE_COND_SIGNAL if (pthread_cond_broadcast (&p->c) != 0) { puts ("child: cond_broadcast failed"); kill (getppid (), SIGKILL); exit (1); } #else if (pthread_cond_signal (&p->c) != 0) { puts ("child: cond_signal failed"); kill (getppid (), SIGKILL); exit (1); } #endif if (pthread_mutex_unlock (&p->m) != 0) { puts ("child: mutex_unlock failed"); kill (getppid (), SIGKILL); exit (1); } exit (0); } do pthread_cond_wait (&p->c, &p->m); while (p->var != 0); if (TEMP_FAILURE_RETRY (waitpid (pid, NULL, 0)) != pid) { printf ("waitpid failed: %m\n"); kill (pid, SIGKILL); return 1; } return 0; }
jrbeverly/JCompiler
src/test/resources/e2e/web_examples/NonThisFieldAccess.java
<filename>src/test/resources/e2e/web_examples/NonThisFieldAccess.java public class NonThisFieldAccess { public NonThisFieldAccess() {} public int x; public void m() { new NonThisFieldAccess().x = 42; } }
ToucanToco/releaseman
src/actions/close-pull-request.js
import { logInfo, logTaskStart } from '../log' const CLOSE_PULL_REQUEST = 'CLOSE_PULL_REQUEST' const closePullRequest = ({ getters }) => async ({ isSkipped, number }) => { logTaskStart('Close pull request') if (isSkipped) { return undefined } logInfo(`Closing pull request #${number}...`) await getters.query('pullRequests.close')({ number: number }) return undefined } export { CLOSE_PULL_REQUEST } export default closePullRequest
lechium/tvOS142Headers
System/Library/PrivateFrameworks/TelephonyUtilities.framework/TUCallProviderManagerDataSource.h
<gh_stars>1-10 /* * This header is generated by classdump-dyld 1.5 * on Tuesday, November 10, 2020 at 10:14:37 PM Mountain Standard Time * Operating System: Version 14.2 (Build 18K57) * Image Source: /System/Library/PrivateFrameworks/TelephonyUtilities.framework/TelephonyUtilities * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. Updated by <NAME>. */ @class NSDictionary; @protocol TUCallProviderManagerDataSource <NSObject> @property (nonatomic,readonly) BOOL currentProcessCanAccessInitialState; @property (nonatomic,copy,readonly) NSDictionary * providersByIdentifier; @property (nonatomic,copy,readonly) NSDictionary * localProvidersByIdentifier; @property (nonatomic,copy,readonly) NSDictionary * pairedHostDeviceProvidersByIdentifier; @property (assign,nonatomic,__weak) id<TUCallProviderManagerDataSourceDelegate> delegate; @required -(void)invalidate; -(id<TUCallProviderManagerDataSourceDelegate>)delegate; -(void)setDelegate:(id)arg1; -(void)launchAppForDialRequest:(id)arg1 completion:(/*^block*/id)arg2; -(void)donateUserIntentForProviderWithIdentifier:(id)arg1; -(BOOL)openURL:(id)arg1 isSensitive:(BOOL)arg2 error:(id*)arg3; -(void)blockUntilInitialStateReceived; -(BOOL)currentProcessCanAccessInitialState; -(NSDictionary *)providersByIdentifier; -(NSDictionary *)localProvidersByIdentifier; -(NSDictionary *)pairedHostDeviceProvidersByIdentifier; @end
hackercowboy/codecowboys.io
src/pages/_app.page.js
/* eslint-disable react/jsx-props-no-spreading */ import React from 'react'; import PropTypes from 'prop-types'; import { IntlProvider } from 'react-intl'; import { useRouter } from 'next/router'; import CookieConsent from '../components/CookieConsent'; import messages from '../i18n'; import 'react-image-gallery/styles/css/image-gallery.css'; import '../styles/styles.scss'; function MyApp({ Component, pageProps }) { const { locale, defaultLocale } = useRouter(); const language = locale && locale.startsWith('de') ? 'de' : 'en'; return ( <IntlProvider locale={locale} defaultLocale={defaultLocale} messages={messages[language]} > <CookieConsent /> <Component {...pageProps} /> </IntlProvider> ); } MyApp.propTypes = { Component: PropTypes.elementType.isRequired, // eslint-disable-next-line react/forbid-prop-types pageProps: PropTypes.object.isRequired, }; export default MyApp;
mouhsinelonly/el-student-spa
src/routes/Home/components/Navbar/MobileNavbar.js
// @flow import * as React from 'react' import { IndexLink, Link } from 'react-router' import './Navbar.scss' import Icon from 'components/Icon' import { Translate } from 'react-localize-redux' export const MobileNavbar = (): React.Element<'ul'> => <ul className='hidden-sm-up c-mobile-navbar'> <li className='c-mobile-navbar__nav-item'> <IndexLink aria-label='home page' activeClassName={'active'} className='c-mobile-navbar__nav-link' to='/'> <Icon name='home-black' /> </IndexLink> </li> <li className='c-mobile-navbar__nav-item'> <Link activeClassName={'active'} className='c-mobile-navbar__nav-link' to='/our_vision'> <Translate id='home.navbar_about' /> </Link> </li> <li className='c-mobile-navbar__nav-item'> <Link activeClassName={'active'} className='c-mobile-navbar__nav-link' to='/info'> <Translate id='home.navbar_study_mobile' /> </Link> </li> <li className='c-mobile-navbar__nav-item hidden-xs-up'> <Link activeClassName={'active'} className='c-mobile-navbar__nav-link' to='/blog'> <Translate id='home.navbar_news' /> </Link> </li> <li className='c-mobile-navbar__nav-item'> <Link activeClassName={'active'} className='c-mobile-navbar__nav-link btn-white' to='/contact'> <Translate id='home.navbar_contact' /> </Link> </li> <li className='c-mobile-navbar__nav-item'> <Link activeClassName={'active'} className='c-mobile-navbar__nav-link btn-white' to='/eshop'> <Translate id='home.navbar_eshop' /> </Link> </li> </ul> export default MobileNavbar
clambin/sciensano
apiclient/vaccines/apiclient_test.go
package vaccines_test import ( "context" "github.com/clambin/sciensano/apiclient/vaccines" "github.com/clambin/sciensano/apiclient/vaccines/fake" "github.com/clambin/sciensano/measurement" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "net/http" "net/http/httptest" "testing" "time" ) func TestClient_GetBatches(t *testing.T) { server := fake.Server{} apiServer := httptest.NewServer(http.HandlerFunc(server.Handler)) client := vaccines.Client{ URL: apiServer.URL, HTTPClient: &http.Client{}, } batches, err := client.GetBatches(context.Background()) require.NoError(t, err) require.Len(t, batches, 3) assert.Equal(t, 300, batches[0].(*vaccines.Batch).Amount) assert.Equal(t, 200, batches[1].(*vaccines.Batch).Amount) assert.Equal(t, 100, batches[2].(*vaccines.Batch).Amount) server.Fail = true _, err = client.GetBatches(context.Background()) require.Error(t, err) apiServer.Close() _, err = client.GetBatches(context.Background()) require.Error(t, err) } func BenchmarkClient_GetBatches(b *testing.B) { server := fake.Server{} apiServer := httptest.NewServer(http.HandlerFunc(server.Handler)) client := vaccines.Client{ URL: apiServer.URL, HTTPClient: &http.Client{}, } for i := 0; i < 5000; i++ { _, err := client.GetBatches(context.Background()) require.NoError(b, err) } } func TestBatch_Measurement(t *testing.T) { b := vaccines.Batch{ Date: vaccines.Timestamp{Time: time.Now()}, Manufacturer: "A", Amount: 200, } assert.NotZero(t, b.GetTimestamp()) assert.Empty(t, b.GetGroupFieldValue(measurement.GroupByAgeGroup)) assert.Equal(t, "A", b.GetGroupFieldValue(measurement.GroupByManufacturer)) assert.Equal(t, 200.0, b.GetTotalValue()) assert.Equal(t, []string{"total"}, b.GetAttributeNames()) assert.Equal(t, []float64{200}, b.GetAttributeValues()) } func TestClient_Refresh(t *testing.T) { server := fake.Server{} apiServer := httptest.NewServer(http.HandlerFunc(server.Handler)) client := vaccines.Client{ URL: apiServer.URL, HTTPClient: &http.Client{}, } response, err := client.Update(context.Background()) require.NoError(t, err) assert.Len(t, response, 1) require.Contains(t, response, "Vaccines") assert.NotNil(t, response["Vaccines"]) apiServer.Close() _, err = client.Update(context.Background()) assert.Error(t, err) }
aconstlink/snakeoil
geometry/3d/helper.h
<gh_stars>1-10 //------------------------------------------------------------ // snakeoil (c) <NAME> // Distributed under the MIT license //------------------------------------------------------------ #ifndef _SNAKEOIL_GEOMETRY_3D_HELPER_H_ #define _SNAKEOIL_GEOMETRY_3D_HELPER_H_ #include "../typedefs.h" #include <snakeoil/math/vector/vector3.hpp> namespace so_geo { namespace so_3d { struct helper { /// @param index the vector index static void_t vector_to_array( size_t index, so_math::vec3f_cref_t in_vec, floats_ref_t to ) { to[index+0] = in_vec.x() ; to[index+1] = in_vec.y() ; to[index+2] = in_vec.z() ; } }; } } #endif
gaurangkumar/crosswalk
runtime/common/xwalk_switches.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "xwalk/runtime/common/xwalk_switches.h" namespace switches { // Specifies the icon file for the app window. const char kAppIcon[] = "app-icon"; // Disables the usage of Portable Native Client. const char kDisablePnacl[] = "disable-pnacl"; // Forces the maximum disk space to be used by the disk cache, in bytes. const char kDiskCacheSize[] = "disk-cache-size"; // Enable all the experimental features in XWalk. const char kExperimentalFeatures[] = "enable-xwalk-experimental-features"; // List the command lines feature flags. const char kListFeaturesFlags[] = "list-features-flags"; const char kXWalkAllowExternalExtensionsForRemoteSources[] = "allow-external-extensions-for-remote-sources"; // Specifies the data path directory, which XWalk runtime will look for its // state, e.g. cache, localStorage etc. const char kXWalkDataPath[] = "data-path"; #if !defined(OS_ANDROID) // Specifies if remote inspector can be opened when right clicking on the // application. const char kXWalkEnableInspector[] = "enable-inspector"; // Specifies if XWalk should disable form data completion. const char kXWalkDisableSaveFormData[] = "disable-save-form-data"; #endif #if defined(OS_ANDROID) // Specifies the separated folder to save user data on Android. const char kXWalkProfileName[] = "profile-name"; #endif // By default, an https page cannot run JavaScript, CSS or plug-ins from http // URLs. This provides an override to get the old insecure behavior. const char kAllowRunningInsecureContent[] = "allow-running-insecure-content"; // By default, an https page can load images, fonts or frames from an http // page. This switch overrides this to block this lesser mixed-content problem. const char kNoDisplayingInsecureContent[] = "no-displaying-insecure-content"; #if defined(ENABLE_PLUGINS) // Use the PPAPI (Pepper) Flash found at the given path. const char kPpapiFlashPath[] = "ppapi-flash-path"; // Report the given version for the PPAPI (Pepper) Flash. The version should be // numbers separated by '.'s (e.g., "12.3.456.78"). If not specified, it // defaults to "10.2.999.999". const char kPpapiFlashVersion[] = "ppapi-flash-version"; #endif // Specifies the user data directory, which is where the browser will look for // all of its state. const char kUserDataDir[] = "user-data-dir"; // Overrides per-origin quota settings to unlimited storage for all // apps/origins. const char kUnlimitedStorage[] = "unlimited-storage"; } // namespace switches
johan-hanson/etheder
etheder-engine/src/main/java/se/webinfostudio/game/etheder/service/research/ResearchService.java
package se.webinfostudio.game.etheder.service.research; import java.util.List; import javax.inject.Named; import se.webinfostudio.game.etheder.entity.research.Research; /** * * @author <NAME> */ @Named public class ResearchService { // @Inject // private ResearchRepository researchRepository; /** * Finds all researches. * * @return a list of researches */ public List<Research> findAll() { // return researchRepository.findAll(); return null; } /** * Find a research by its id. * * @param researchId the research id * @return {@link Research} */ public Research findById(final Long researchId) { // return (Research) researchRepository.findById(researchId); return null; } /** * Saves a list of Researches. * * @param researches a list of Research * @return a list of researches */ public List<Research> save(final List<Research> researches) { for (final Research research : researches) { // researchRepository.create(research); } return researches; } }
rwietter/codebase
javascript/FunctionalJS/#1-Module/functions/challenges/genericReturnFunction.js
<filename>javascript/FunctionalJS/#1-Module/functions/challenges/genericReturnFunction.js<gh_stars>0 function sum(a) { return (b) => (c) => a + b + c; } const getSum = sum(3)(4); console.log(getSum(5));
Glitch0011/DirectX11-Demo
Smooth_Graphics/Include/VertexBufferController (Travesty's conflicted copy 2014-10-09).h
#include <d3d11.h> #include <vector> #include <SimpleVertex.h> #include <string> #include <NamedResource.h> #include <BufferController.h> using namespace std; namespace SmoothGraphics { class VertexBuffer : public Buffer { protected: ID3D11UnorderedAccessView* resourceView; public: VertexBuffer(wstring name) : Buffer(name, nullptr) { this->buffer = nullptr; this->resourceView = nullptr; } virtual HRESULT Init(ID3D11Device* device) = 0; virtual HRESULT Set(ID3D11DeviceContext*) = 0; virtual HRESULT Release() = 0; ID3D11Buffer* Get() { return this->buffer; } ID3D11UnorderedAccessView* ResourceView() { return this->resourceView; } }; class TriangleVertexBuffer : public VertexBuffer { public: vector<SimpleVertex> vertices; TriangleVertexBuffer(wstring name) : VertexBuffer(name) { float size = 5; vertices = vector<SimpleVertex>(size * size * size); int i = 0; float spacing = 1.0f; for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { for (int z = 0; z < size; z++) { auto c_x = (1.0f / (float)size) * x; auto c_y = (1.0f / (float)size) * y; auto c_z = (1.0f / (float)size) * z; vertices[i++] = SimpleVertex(x * spacing, y * spacing, z * spacing, c_x, c_y, c_z); } } } } D3D11_BUFFER_DESC GetDescription() { D3D11_BUFFER_DESC descBuf; ZeroMemory(&descBuf, sizeof(descBuf)); this->Get()->GetDesc(&descBuf); return descBuf; } HRESULT CreateBufferResourceView(ID3D11Device* device) { D3D11_UNORDERED_ACCESS_VIEW_DESC viewDescription; ZeroMemory(&viewDescription, sizeof(D3D11_UNORDERED_ACCESS_VIEW_DESC)); viewDescription.ViewDimension = D3D11_UAV_DIMENSION_BUFFER; viewDescription.Buffer.FirstElement = 0; auto description = this->GetDescription(); if (description.MiscFlags & D3D11_RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS) { // This is a Raw Buffer viewDescription.Format = DXGI_FORMAT_R32_TYPELESS; viewDescription.Buffer.Flags = D3D11_BUFFER_UAV_FLAG_RAW; viewDescription.Buffer.NumElements = description.ByteWidth / 4; } else if (this->GetDescription().MiscFlags & D3D11_RESOURCE_MISC_BUFFER_STRUCTURED) { // This is a Structured Buffer viewDescription.Format = DXGI_FORMAT_UNKNOWN; viewDescription.Buffer.NumElements = description.ByteWidth / description.StructureByteStride; } else { return E_INVALIDARG; } return device->CreateUnorderedAccessView(this->Get(), &viewDescription, &this->resourceView); } HRESULT Init(ID3D11Device* device) { D3D11_BUFFER_DESC bd; ZeroMemory(&bd, sizeof(bd)); bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof(SimpleVertex) * this->vertices.size(); bd.BindFlags = D3D11_BIND_VERTEX_BUFFER | D3D11_BIND_UNORDERED_ACCESS; bd.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS; bd.StructureByteStride = sizeof(SimpleVertex); bd.CPUAccessFlags = 0; D3D11_SUBRESOURCE_DATA InitData; ZeroMemory(&InitData, sizeof(InitData)); InitData.pSysMem = vertices.data(); auto res = device->CreateBuffer(&bd, &InitData, &this->buffer); if (FAILED(res)) { return res; } return this->CreateBufferResourceView(device); } HRESULT Set(ID3D11DeviceContext* immediateContext) { UINT stride = sizeof(SimpleVertex); UINT offset = 0; immediateContext->IASetVertexBuffers(0, 1, &this->buffer, &stride, &offset); return S_OK; } HRESULT Release() { this->buffer->Release(); return S_OK; } }; class VertexBufferController { ID3D11Device* device; BufferController* bufferController; public: VertexBufferController(ID3D11Device* device, BufferController* bufferController) { this->device = device; this->bufferController = bufferController; } ~VertexBufferController() { } HRESULT Init() { return S_OK; } void AddVertexBuffer(VertexBuffer* buffer) { buffer->Init(this->device); this->bufferController->AddBuffer(buffer); } VertexBuffer* operator[](const wstring& name) { return dynamic_cast<VertexBuffer*>(this->bufferController->Get(name)); } VertexBuffer* Get(const wstring& name) { return this->operator[](name); } }; }
FlavioFalcao/open-source-search-engine
urlinfo.cpp
// <NAME>, copyright Jan 2002 // normalizes urls from stdin #include "gb-include.h" #include "Url.h" #include "Mem.h" #include "Titledb.h" #include "HttpMime.h" #include "SiteGetter.h" //#include "Tfndb.h" //#include "Msg50.h" //#include "Msg16.h" bool mainShutdown ( bool urgent ) { return true; } bool closeAll ( void *state , void (* callback)(void *state) ) {return true;} bool allExit ( ) { return true; } //long g_qbufNeedSave = false; //SafeBuf g_qbuf; bool sendPageSEO(class TcpSocket *s, class HttpRequest *hr) {return true;} int main ( int argc , char *argv[] ) { bool addWWW = true; bool stripSession = true; // check for arguments for (long i = 1; i < argc; i++) { if (strcmp(argv[i], "-w") == 0) addWWW = false; else if (strcmp(argv[i], "-s") == 0) stripSession = false; } // initialize //g_mem.init(100*1024); hashinit(); //g_conf.m_tfndbExtBits = 23; loop: // read a url from stddin char sbuf[1024]; if ( ! fgets ( sbuf , 1024 , stdin ) ) exit(1); char *s = sbuf; char fbuf[1024]; // decode if we should if ( strncmp(s,"http%3A%2F%2F",13) == 0 || strncmp(s,"https%3A%2F%2F",13) == 0 ) { urlDecode(fbuf,s,gbstrlen(s)); s = fbuf; } // old url printf("###############\n"); printf("old: %s",s); long slen = gbstrlen(s); // remove any www. if !addWWW if (!addWWW) { if (slen >= 4 && strncasecmp(s, "www.", 4) == 0) { slen -= 4; memmove(s, &s[4], slen); } else { // get past a :// long si = 0; while (si < slen && ( s[si] != ':' || s[si+1] != '/' || s[si+2] != '/' ) ) si++; // remove the www. if (si + 7 < slen) { si += 3; if (strncasecmp(&s[si], "www.", 4) == 0) { slen -= 4; memmove(&s[si], &s[si+4], slen-si); } } } } // set it Url u; u.set ( s , slen , addWWW , /*add www?*/ stripSession ); /*strip session ids?*/ // print it char out[1024*3]; char *p = out; sprintf ( p , "dom: "); p += gbstrlen ( p ); memcpy ( p , u.getDomain() , u.getDomainLen() ); p += u.getDomainLen(); char c = *p; *p = '\0'; printf("%s\n",out); *p = c; // host p = out; sprintf ( p , "host: "); p += gbstrlen ( p ); memcpy ( p , u.getHost() , u.getHostLen() ); p += u.getHostLen(); c = *p; *p = '\0'; printf("%s\n",out); *p = c; // then the whole url printf("url: %s\n", u.getUrl() ); /* long siteLen; char *site = u.getSite ( &siteLen , NULL , false ); if ( site ) { c = site[siteLen]; site[siteLen] = '\0'; } printf("site: %s\n", site ); if ( site ) site[siteLen] = c; */ SiteGetter sg; sg.getSite ( u.getUrl() , NULL , // tagrec 0 , // timestamp NULL, // coll 0 , // niceness //false , // addtags NULL , // state NULL ); // callback if ( sg.m_siteLen ) printf("site: %s\n",sg.m_site); printf("isRoot: %li\n",(long)u.isRoot()); /* bool perm = ::isPermalink ( NULL , // coll NULL , // Links ptr &u , // the url CT_HTML , // contentType NULL , // LinkInfo ptr false );// isRSS? printf ("isPermalink: %li\n",(long)perm); */ // print the path too p = out; p += sprintf ( p , "path: " ); memcpy ( p , u.getPath(), u.getPathLen() ); p += u.getPathLen(); if ( u.getFilename() ) { p += sprintf ( p , "\nfilename: " ); memcpy ( p , u.getFilename(), u.getFilenameLen() ); p += u.getFilenameLen(); *p = '\0'; printf("%s\n", out ); } // encoded char dst[MAX_URL_LEN+200]; urlEncode ( dst,MAX_URL_LEN+100, u.getUrl(), u.getUrlLen(), false ); // are we encoding a request path? printf("encoded: %s\n",dst); // the probable docid long long pd = g_titledb.getProbableDocId(&u); printf("pdocid: %llu\n", pd ); printf("dom8: 0x%lx\n", (long)g_titledb.getDomHash8FromDocId(pd) ); //printf("ext23: 0x%lx\n",g_tfndb.makeExt(&u)); if ( u.isLinkLoop() ) printf("islinkloop: yes\n"); else printf("islinkloop: no\n"); long long hh64 = u.getHostHash64(); printf("hosthash64: 0x%016llx\n",hh64); unsigned long hh32 = u.getHostHash32(); printf("hosthash32: 0x%08lx (%lu)\n",hh32,hh32); long long dh64 = u.getDomainHash64(); printf("domhash64: 0x%016llx\n",dh64); long long uh64 = u.getUrlHash64(); printf("urlhash64: 0x%016llx\n",uh64); //if(isUrlUnregulated(NULL ,0,&u)) printf("unregulated: yes\n"); //else printf("unregulated: no\n"); goto loop; }
wgiacomin/node-api
src/models/Cliente.js
<reponame>wgiacomin/node-api const Sequelize = require('sequelize') class Cliente extends Sequelize.Model{ static init(sequelize){ super.init( { nome: Sequelize.STRING, cnpj: Sequelize.STRING, endereco: Sequelize.STRING, associado: Sequelize.INTEGER, }, { sequelize, } ) } static associate(models){ this.belongsTo(models.Associado, { foreignKey: 'id', foreignKeyConstraint: true}) this.hasMany(models.Entrega, {foreignKey: 'id'}) } } module.exports = Cliente
SticksDev/SPOT
src/scouting/public/js/waiting.js
<reponame>SticksDev/SPOT<filename>src/scouting/public/js/waiting.js let hints = ["If you misclick a button, you can always press UNDO to undo your mistake!","Show up to scout on time! Try to be there a few minutes in advance.","Stay focused when scouting. Data you collect helps your team greatly.","If you ever have an issue, make sure to notify the scouting team.","Before you leave, let the scouting team know so they can replace you."] function shuffleArray(array) { for (var i = array.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); var temp = array[i]; array[i] = array[j]; array[j] = temp; } } function toggleHintElement(hintElement) { //resize hint container to be the element's height if it is active setTimeout(() => { document.querySelector("#waiting .hint").style.height = Math.max(activeHint.offsetHeight, document.querySelector("#waiting .hint").offsetHeight) + "px"; document.querySelector("#waiting").style.paddingBottom = Math.max(activeHint.offsetHeight, document.querySelector("#waiting .hint").offsetHeight) + 45 + "px"; }, 250) //toggle the hint element's visibility if (hintElement.classList.contains("visible")) { hintElement.classList.remove("visible") } else { hintElement.classList.add("visible") } } //shuffle hints + create interval shuffleArray(hints); let [activeHint, inactiveHint] = document.querySelectorAll("#waiting .hint-text"); activeHint.innerText = hints[0]; toggleHintElement(activeHint); //resize the hint container's height on page height change window.addEventListener("resize", () => { document.querySelector("#waiting .hint").style.height = activeHint.offsetHeight + "px"; console.log() document.querySelector("#waiting").style.paddingBottom = activeHint.offsetHeight + 45 + "px"; }) window.addEventListener("orientationchange", function() { document.querySelector("#waiting .hint").style.height = activeHint.offsetHeight + "px"; console.log() document.querySelector("#waiting").style.paddingBottom = activeHint.offsetHeight + 45 + "px"; }, false); //cycle through the hints let hintNum = 1; setInterval(() => { toggleHintElement(activeHint); toggleHintElement(inactiveHint); [activeHint, inactiveHint] = [inactiveHint, activeHint]; activeHint.innerText = hints[hintNum++ % hints.length] }, 6969)
xieweiAlex/Leetcode_solutions
September/week4/NumDecodings.java
package September.week4; /* A message containing letters from A-Z is being encoded to numbers using the following mapping way: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Beyond that, now the encoded string can also contain the character '*', which can be treated as one of the numbers from 1 to 9. Given the encoded message containing digits and the character '*', return the total number of ways to decode it. Also, since the answer may be very large, you should return the output mod 109 + 7. Example 1: Input: "*" Output: 9 Explanation: The encoded message can be decoded to the string: "A", "B", "C", "D", "E", "F", "G", "H", "I". Example 2: Input: "1*" Output: 9 + 9 = 18 Note: The length of the input string will fit in range [1, 105]. The input string will only contain the character '*' and digits '0' - '9'. https://leetcode.com/problems/decode-ways-ii/description/ https://discuss.leetcode.com/topic/95251/java-dp-o-n-time-and-o-1-space/2 ** hard * */ public class NumDecodings { public static int numDecodings(String s) { long[] res = new long[2]; res[0] = ways(s.charAt(0)); if(s.length() < 2) return (int)res[0]; res[1] = res[0] * ways(s.charAt(1)) + ways(s.charAt(0), s.charAt(1)); for(int j = 2; j < s.length(); j++) { long temp = res[1]; res[1] = (res[1] * ways(s.charAt(j)) + res[0] * ways(s.charAt(j-1), s.charAt(j))) % 1000000007; res[0] = temp; } return (int)res[1]; } private static int ways(int ch) { if(ch == '*') return 9; if(ch == '0') return 0; return 1; } private static int ways(char ch1, char ch2) { String str = "" + ch1 + "" + ch2; if(ch1 != '*' && ch2 != '*') { if(Integer.parseInt(str) >= 10 && Integer.parseInt(str) <= 26) return 1; } else if(ch1 == '*' && ch2 == '*') { return 15; } else if(ch1 == '*') { if(Integer.parseInt(""+ch2) >= 0 && Integer.parseInt(""+ch2) <= 6) return 2; else return 1; } else { if(Integer.parseInt(""+ch1) == 1 ) { return 9; } else if(Integer.parseInt(""+ch1) == 2 ) { return 6; } } return 0; } }
luongnvUIT/prowide-iso20022
model-reda-types/src/generated/java/com/prowidesoftware/swift/model/mx/dic/FundPaymentType1Code.java
<filename>model-reda-types/src/generated/java/com/prowidesoftware/swift/model/mx/dic/FundPaymentType1Code.java package com.prowidesoftware.swift.model.mx.dic; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for FundPaymentType1Code. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="FundPaymentType1Code"&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"&gt; * &lt;enumeration value="DRAF"/&gt; * &lt;enumeration value="CACC"/&gt; * &lt;enumeration value="CHEQ"/&gt; * &lt;enumeration value="CRDT"/&gt; * &lt;enumeration value="DDEB"/&gt; * &lt;enumeration value="CARD"/&gt; * &lt;/restriction&gt; * &lt;/simpleType&gt; * </pre> * */ @XmlType(name = "FundPaymentType1Code") @XmlEnum public enum FundPaymentType1Code { /** * Payment instrument is a bankers draft. * */ DRAF, /** * Payment instrument is a cash account. * */ CACC, /** * Payment instrument is a cheque. * */ CHEQ, /** * Payment instrument is a credit transfer. * */ CRDT, /** * Payment instrument is a direct debit. * */ DDEB, /** * Payment instrument is a payment card. * */ CARD; public String value() { return name(); } public static FundPaymentType1Code fromValue(String v) { return valueOf(v); } }
intel-go/omniscidb
Tests/ArrowSQLRunner/SQLiteComparator.h
<gh_stars>1-10 /* * Copyright 2021 OmniSci, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "QueryEngine/ArrowResultSet.h" #include "Shared/sqltypes.h" #include "SqliteConnector/SqliteConnector.h" namespace TestHelpers { constexpr double EPS = 1.25e-5; class SQLiteComparator { public: SQLiteComparator(bool use_row_iterator = true) : connector_("sqliteTestDB", ""), use_row_iterator_(use_row_iterator) {} void query(const std::string& query_string) { connector_.query(query_string); } void batch_insert(const std::string& table_name, std::vector<std::vector<std::string>>& insert_vals) { connector_.batch_insert(table_name, insert_vals); } void compare(ResultSetPtr omnisci_results, const std::string& query_string, const ExecutorDeviceType device_type); void compare_arrow_output(std::unique_ptr<ArrowResultSet>& arrow_omnisci_results, const std::string& sqlite_query_string, const ExecutorDeviceType device_type); // added to deal with time shift for now testing void compare_timstamp_approx(ResultSetPtr omnisci_results, const std::string& query_string, const ExecutorDeviceType device_type); private: SqliteConnector connector_; bool use_row_iterator_; }; } // namespace TestHelpers
grbd/GBD.Embedded.CMake4Mbed
lib/mbed/extra_targets/cmsis/TARGET_Atmel/TARGET_SAM21/utils/cmsis/samd21/include/component/comp_pac.h
#ifndef _SAMD21_PAC_COMPONENT_ #define _SAMD21_PAC_COMPONENT_ /* ========================================================================== */ /** SOFTWARE API DEFINITION FOR PAC */ /* ========================================================================== */ /** \addtogroup SAMD21_PAC Peripheral Access Controller */ /*@{*/ #define PAC_U2211 #define REV_PAC 0x101 /* -------- PAC_WPCLR : (PAC Offset: 0x0) (R/W 32) Write Protection Clear -------- */ #if !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) typedef union { struct { uint32_t :1; /*!< bit: 0 Reserved */ uint32_t WP:31; /*!< bit: 1..31 Write Protection Clear */ } bit; /*!< Structure used for bit access */ uint32_t reg; /*!< Type used for register access */ } PAC_WPCLR_Type; #endif /* !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */ #define PAC_WPCLR_OFFSET 0x0 /**< \brief (PAC_WPCLR offset) Write Protection Clear */ #define PAC_WPCLR_RESETVALUE 0x00000000ul /**< \brief (PAC_WPCLR reset_value) Write Protection Clear */ #define PAC_WPCLR_WP_Pos 1 /**< \brief (PAC_WPCLR) Write Protection Clear */ #define PAC_WPCLR_WP_Msk (0x7FFFFFFFul << PAC_WPCLR_WP_Pos) #define PAC_WPCLR_WP(value) ((PAC_WPCLR_WP_Msk & ((value) << PAC_WPCLR_WP_Pos))) #define PAC_WPCLR_MASK 0xFFFFFFFEul /**< \brief (PAC_WPCLR) MASK Register */ /* -------- PAC_WPSET : (PAC Offset: 0x4) (R/W 32) Write Protection Set -------- */ #if !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) typedef union { struct { uint32_t :1; /*!< bit: 0 Reserved */ uint32_t WP:31; /*!< bit: 1..31 Write Protection Set */ } bit; /*!< Structure used for bit access */ uint32_t reg; /*!< Type used for register access */ } PAC_WPSET_Type; #endif /* !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */ #define PAC_WPSET_OFFSET 0x4 /**< \brief (PAC_WPSET offset) Write Protection Set */ #define PAC_WPSET_RESETVALUE 0x00000000ul /**< \brief (PAC_WPSET reset_value) Write Protection Set */ #define PAC_WPSET_WP_Pos 1 /**< \brief (PAC_WPSET) Write Protection Set */ #define PAC_WPSET_WP_Msk (0x7FFFFFFFul << PAC_WPSET_WP_Pos) #define PAC_WPSET_WP(value) ((PAC_WPSET_WP_Msk & ((value) << PAC_WPSET_WP_Pos))) #define PAC_WPSET_MASK 0xFFFFFFFEul /**< \brief (PAC_WPSET) MASK Register */ /** \brief PAC hardware registers */ #if !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) typedef struct { __IO PAC_WPCLR_Type WPCLR; /**< \brief Offset: 0x0 (R/W 32) Write Protection Clear */ __IO PAC_WPSET_Type WPSET; /**< \brief Offset: 0x4 (R/W 32) Write Protection Set */ } Pac; #endif /* !(defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */ /*@}*/ #endif /* _SAMD21_PAC_COMPONENT_ */
zparnold/aws-sdk-go-v2
service/applicationautoscaling/types/enums.go
<reponame>zparnold/aws-sdk-go-v2 // Code generated by smithy-go-codegen DO NOT EDIT. package types type AdjustmentType string // Enum values for AdjustmentType const ( AdjustmentTypeChangeincapacity AdjustmentType = "ChangeInCapacity" AdjustmentTypePercentchangeincapacity AdjustmentType = "PercentChangeInCapacity" AdjustmentTypeExactcapacity AdjustmentType = "ExactCapacity" ) type MetricAggregationType string // Enum values for MetricAggregationType const ( MetricAggregationTypeAverage MetricAggregationType = "Average" MetricAggregationTypeMinimum MetricAggregationType = "Minimum" MetricAggregationTypeMaximum MetricAggregationType = "Maximum" ) type MetricStatistic string // Enum values for MetricStatistic const ( MetricStatisticAverage MetricStatistic = "Average" MetricStatisticMinimum MetricStatistic = "Minimum" MetricStatisticMaximum MetricStatistic = "Maximum" MetricStatisticSamplecount MetricStatistic = "SampleCount" MetricStatisticSum MetricStatistic = "Sum" ) type MetricType string // Enum values for MetricType const ( MetricTypeDynamodbreadcapacityutilization MetricType = "DynamoDBReadCapacityUtilization" MetricTypeDynamodbwritecapacityutilization MetricType = "DynamoDBWriteCapacityUtilization" MetricTypeAlbrequestcountpertarget MetricType = "ALBRequestCountPerTarget" MetricTypeRdsreaderaveragecpuutilization MetricType = "RDSReaderAverageCPUUtilization" MetricTypeRdsreaderaveragedatabaseconnections MetricType = "RDSReaderAverageDatabaseConnections" MetricTypeEc2spotfleetrequestaveragecpuutilization MetricType = "EC2SpotFleetRequestAverageCPUUtilization" MetricTypeEc2spotfleetrequestaveragenetworkin MetricType = "EC2SpotFleetRequestAverageNetworkIn" MetricTypeEc2spotfleetrequestaveragenetworkout MetricType = "EC2SpotFleetRequestAverageNetworkOut" MetricTypeSagemakervariantinvocationsperinstance MetricType = "SageMakerVariantInvocationsPerInstance" MetricTypeEcsserviceaveragecpuutilization MetricType = "ECSServiceAverageCPUUtilization" MetricTypeEcsserviceaveragememoryutilization MetricType = "ECSServiceAverageMemoryUtilization" MetricTypeAppstreamaveragecapacityutilization MetricType = "AppStreamAverageCapacityUtilization" MetricTypeComprehendinferenceutilization MetricType = "ComprehendInferenceUtilization" MetricTypeLambdaprovisionedconcurrencyutilization MetricType = "LambdaProvisionedConcurrencyUtilization" MetricTypeCassandrareadcapacityutilization MetricType = "CassandraReadCapacityUtilization" MetricTypeCassandrawritecapacityutilization MetricType = "CassandraWriteCapacityUtilization" ) type PolicyType string // Enum values for PolicyType const ( PolicyTypeStepscaling PolicyType = "StepScaling" PolicyTypeTargettrackingscaling PolicyType = "TargetTrackingScaling" ) type ScalableDimension string // Enum values for ScalableDimension const ( ScalableDimensionEcsservicedesiredcount ScalableDimension = "ecs:service:DesiredCount" ScalableDimensionEc2spotfleetrequesttargetcapacity ScalableDimension = "ec2:spot-fleet-request:TargetCapacity" ScalableDimensionEmrinstancegroupinstancecount ScalableDimension = "elasticmapreduce:instancegroup:InstanceCount" ScalableDimensionAppstreamfleetdesiredcapacity ScalableDimension = "appstream:fleet:DesiredCapacity" ScalableDimensionDynamodbtablereadcapacityunits ScalableDimension = "dynamodb:table:ReadCapacityUnits" ScalableDimensionDynamodbtablewritecapacityunits ScalableDimension = "dynamodb:table:WriteCapacityUnits" ScalableDimensionDynamodbindexreadcapacityunits ScalableDimension = "dynamodb:index:ReadCapacityUnits" ScalableDimensionDynamodbindexwritecapacityunits ScalableDimension = "dynamodb:index:WriteCapacityUnits" ScalableDimensionRdsclusterreadreplicacount ScalableDimension = "rds:cluster:ReadReplicaCount" ScalableDimensionSagemakervariantdesiredinstancecount ScalableDimension = "sagemaker:variant:DesiredInstanceCount" ScalableDimensionCustomresourcescalabledimension ScalableDimension = "custom-resource:ResourceType:Property" ScalableDimensionComprehenddocclassifierendpointinferenceunits ScalableDimension = "comprehend:document-classifier-endpoint:DesiredInferenceUnits" ScalableDimensionLambdafunctionprovisionedconcurrency ScalableDimension = "lambda:function:ProvisionedConcurrency" ScalableDimensionCassandratablereadcapacityunits ScalableDimension = "cassandra:table:ReadCapacityUnits" ScalableDimensionCassandratablewritecapacityunits ScalableDimension = "cassandra:table:WriteCapacityUnits" ) type ScalingActivityStatusCode string // Enum values for ScalingActivityStatusCode const ( ScalingActivityStatusCodePending ScalingActivityStatusCode = "Pending" ScalingActivityStatusCodeInprogress ScalingActivityStatusCode = "InProgress" ScalingActivityStatusCodeSuccessful ScalingActivityStatusCode = "Successful" ScalingActivityStatusCodeOverridden ScalingActivityStatusCode = "Overridden" ScalingActivityStatusCodeUnfulfilled ScalingActivityStatusCode = "Unfulfilled" ScalingActivityStatusCodeFailed ScalingActivityStatusCode = "Failed" ) type ServiceNamespace string // Enum values for ServiceNamespace const ( ServiceNamespaceEcs ServiceNamespace = "ecs" ServiceNamespaceEmr ServiceNamespace = "elasticmapreduce" ServiceNamespaceEc2 ServiceNamespace = "ec2" ServiceNamespaceAppstream ServiceNamespace = "appstream" ServiceNamespaceDynamodb ServiceNamespace = "dynamodb" ServiceNamespaceRds ServiceNamespace = "rds" ServiceNamespaceSagemaker ServiceNamespace = "sagemaker" ServiceNamespaceCustom_resource ServiceNamespace = "custom-resource" ServiceNamespaceComprehend ServiceNamespace = "comprehend" ServiceNamespaceLambda ServiceNamespace = "lambda" ServiceNamespaceCassandra ServiceNamespace = "cassandra" )
wenkokke/LambdaCalc
src/main/java/lambdacalc/impl/ISymbolPrinter.java
<gh_stars>1-10 package lambdacalc.impl; import static lombok.AccessLevel.PRIVATE; import lambdacalc.Symbol; import lambdacalc.SymbolPrinter; import lambdacalc.TypePrinter; import lambdacalc.Types; import lombok.RequiredArgsConstructor; import lombok.experimental.FieldDefaults; @RequiredArgsConstructor @FieldDefaults(makeFinal=true,level=PRIVATE) public final class ISymbolPrinter implements SymbolPrinter { TypePrinter typePrinter; @Override public final String format(Symbol symbol) { if (symbol.getType().equals(Types.STAR)) { return symbol.getName(); } else { return symbol.getName() + ":" + typePrinter.format(symbol.getType()); } } }
fabiojna02/OpenCellular
firmware/coreboot/src/vendorcode/amd/agesa/f15tn/Proc/Common/AmdInitReset.c
/* $NoKeywords:$ */ /** * @file * * AMD AGESA Basic Level Public APIs * * Contains basic Level Initialization routines. * * @xrefitem bom "File Content Label" "Release Content" * @e project: AGESA * @e sub-project: Interface * @e \$Revision: 63425 $ @e \$Date: 2011-12-22 11:24:10 -0600 (Thu, 22 Dec 2011) $ * */ /***************************************************************************** * * Copyright (c) 2008 - 2012, Advanced Micro Devices, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Advanced Micro Devices, Inc. nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL ADVANCED MICRO DEVICES, INC. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ****************************************************************************** */ /*---------------------------------------------------------------------------------------- * M O D U L E S U S E D *---------------------------------------------------------------------------------------- */ #include "AGESA.h" #include "amdlib.h" #include "Ids.h" #include "cpuCacheInit.h" #include "cpuServices.h" #include "AdvancedApi.h" #include "GeneralServices.h" #include "OptionsHt.h" #include "AmdFch.h" #include "Filecode.h" #include "heapManager.h" #include "CreateStruct.h" CODE_GROUP (G1_PEICC) RDATA_GROUP (G1_PEICC) #define FILECODE PROC_COMMON_AMDINITRESET_FILECODE extern BLDOPT_FCH_FUNCTION BldoptFchFunction; /*---------------------------------------------------------------------------------------- * D E F I N I T I O N S A N D M A C R O S *---------------------------------------------------------------------------------------- */ extern CONST OPTION_HT_INIT_RESET HtOptionInitReset; extern BUILD_OPT_CFG UserOptions; /*---------------------------------------------------------------------------------------- * T Y P E D E F S A N D S T R U C T U R E S *---------------------------------------------------------------------------------------- */ /*---------------------------------------------------------------------------------------- * P R O T O T Y P E S O F L O C A L F U N C T I O N S *---------------------------------------------------------------------------------------- */ AGESA_STATUS AmdInitResetExecutionCacheAllocateInitializer ( IN AMD_CONFIG_PARAMS *StdHeader, IN EXECUTION_CACHE_REGION *AmdExeAddrMapPtr ); /*---------------------------------------------------------------------------------------- * E X P O R T E D F U N C T I O N S *---------------------------------------------------------------------------------------- */ /*------------------------------------------------------------------------------------*/ /** * Initializer routine that will be invoked by the wrapper to initialize the input * structure for the AllocateExecutionCache. * * Parameters: * @param[in] StdHeader Opaque handle to standard config header * @param[in] AmdExeAddrMapPtr Our Service interface struct * * @retval AGESA_SUCCESS Always Succeeds. * */ AGESA_STATUS AmdInitResetExecutionCacheAllocateInitializer ( IN AMD_CONFIG_PARAMS *StdHeader, IN EXECUTION_CACHE_REGION *AmdExeAddrMapPtr ) { ASSERT (AmdExeAddrMapPtr != NULL); LibAmdMemFill (AmdExeAddrMapPtr, 0, sizeof (EXECUTION_CACHE_REGION) * MAX_CACHE_REGIONS, StdHeader); return AGESA_SUCCESS; } /*---------------------------------------------------------------------------------------*/ /** * Main entry point for the AMD_INIT_RESET function. * * This entry point is responsible for establishing the HT links to the program * ROM and for performing basic processor initialization. * * @param[in,out] ResetParams Required input parameters for the AMD_INIT_RESET * entry point. * * @return Aggregated status across all internal AMD reset calls invoked. * */ AGESA_STATUS AmdInitReset ( IN OUT AMD_RESET_PARAMS *ResetParams ) { AGESA_STATUS AgesaStatus; AGESA_STATUS CalledAgesaStatus; WARM_RESET_REQUEST Request; UINT8 PrevRequestBit; UINT8 PrevStateBits; IDS_PERF_TIMESTAMP (&ResetParams->StdHeader); AgesaStatus = AGESA_SUCCESS; // Setup ROM execution cache CalledAgesaStatus = AllocateExecutionCache (&ResetParams->StdHeader, &ResetParams->CacheRegion[0]); if (CalledAgesaStatus > AgesaStatus) { AgesaStatus = CalledAgesaStatus; } //IDS_EXTENDED_HOOK (IDS_INIT_RESET_BEFORE, NULL, NULL, &ResetParams->StdHeader); // Init Debug Print function IDS_HDT_CONSOLE_INIT (&ResetParams->StdHeader); IDS_HDT_CONSOLE (MAIN_FLOW, "\nAmdInitReset: Start\n\n"); IDS_HDT_CONSOLE (MAIN_FLOW, "\n*** %s ***\n\n", &UserOptions.VersionString); AGESA_TESTPOINT (TpIfAmdInitResetEntry, &ResetParams->StdHeader); ASSERT (ResetParams != NULL); PrevRequestBit = FALSE; PrevStateBits = WR_STATE_COLD; IDS_PERF_TIMESTAMP (&ResetParams->StdHeader); if (IsBsp (&ResetParams->StdHeader, &AgesaStatus)) { CalledAgesaStatus = BldoptFchFunction.InitReset (ResetParams); AgesaStatus = (CalledAgesaStatus > AgesaStatus) ? CalledAgesaStatus : AgesaStatus; } // If a previously requested warm reset cannot be triggered in the // current stage, store the previous state of request and reset the // request struct to the current post stage GetWarmResetFlag (&ResetParams->StdHeader, &Request); if (Request.RequestBit == TRUE) { if (Request.StateBits >= Request.PostStage) { PrevRequestBit = Request.RequestBit; PrevStateBits = Request.StateBits; Request.RequestBit = FALSE; Request.StateBits = Request.PostStage - 1; SetWarmResetFlag (&ResetParams->StdHeader, &Request); } } // Initialize the PCI MMIO access mechanism InitializePciMmio (&ResetParams->StdHeader); IDS_PERF_TIMESTAMP (&ResetParams->StdHeader); // Initialize Hyper Transport Registers if (HtOptionInitReset.HtInitReset != NULL) { IDS_HDT_CONSOLE (MAIN_FLOW, "HtInitReset: Start\n"); CalledAgesaStatus = HtOptionInitReset.HtInitReset (&ResetParams->StdHeader, &ResetParams->HtConfig); IDS_HDT_CONSOLE (MAIN_FLOW, "HtInitReset: End\n"); if (CalledAgesaStatus > AgesaStatus) { AgesaStatus = CalledAgesaStatus; } } // Warm Reset, should be at the end of AmdInitReset GetWarmResetFlag (&ResetParams->StdHeader, &Request); // If a warm reset is requested in the current post stage, trigger the // warm reset and ignore the previous request if (Request.RequestBit == TRUE) { if (Request.StateBits < Request.PostStage) { AgesaDoReset (WARM_RESET_WHENEVER, &ResetParams->StdHeader); } } else { // Otherwise, if there's a previous request, restore it // so that the subsequent post stage can trigger the warm reset if (PrevRequestBit == TRUE) { Request.RequestBit = PrevRequestBit; Request.StateBits = PrevStateBits; SetWarmResetFlag (&ResetParams->StdHeader, &Request); } } // Check for Cache As Ram Corruption IDS_CAR_CORRUPTION_CHECK (&ResetParams->StdHeader); IDS_HDT_CONSOLE (MAIN_FLOW, "\nAmdInitReset: End\n\n"); AGESA_TESTPOINT (TpIfAmdInitResetExit, &ResetParams->StdHeader); IDS_PERF_TIMESTAMP (&ResetParams->StdHeader); return AgesaStatus; } /*---------------------------------------------------------------------------------------*/ /** * Initialize defaults and options for Amd Init Reset. * * @param[in] StdHeader Header * @param[in] AmdResetParams The Reset Init interface to initialize. * * @retval AGESA_SUCCESS Always Succeeds. */ AGESA_STATUS AmdInitResetConstructor ( IN AMD_CONFIG_PARAMS *StdHeader, IN AMD_RESET_PARAMS *AmdResetParams ) { ASSERT (AmdResetParams != NULL); AmdResetParams->StdHeader = *StdHeader; AmdInitResetExecutionCacheAllocateInitializer (&AmdResetParams->StdHeader, &AmdResetParams->CacheRegion[0]); // Initialize Hyper Transport input structure if (HtOptionInitReset.HtResetConstructor != NULL) { HtOptionInitReset.HtResetConstructor (&AmdResetParams->StdHeader, &AmdResetParams->HtConfig); } BldoptFchFunction.InitResetConstructor (AmdResetParams); return AGESA_SUCCESS; }
knmcguire/gap_sdk
examples/native/pulpos/periph/esp8266/AT_RING_BUFFER.h
<filename>examples/native/pulpos/periph/esp8266/AT_RING_BUFFER.h #include <stdio.h> #include <rt/rt_api.h> #include "Gap8.h" #include <stdint.h> int AT_COMMAND_Init(int baudrate); void AT_COMMAND_Write(char *command, int length); int AT_COMMAND_Read(char *r_buf, int length);
waweber/colorbot
colorbot/twitter/drawing.py
<reponame>waweber/colorbot import pngcanvas def create_png(r, g, b): """Create a PNG from r, g, b, data. RGB should be on the [-1.0, 1.0] scale. Returns: bytes: PNG image bytes """ r = round((r + 1) / 2 * 255) g = round((g + 1) / 2 * 255) b = round((b + 1) / 2 * 255) canvas = pngcanvas.PNGCanvas(150, 150, bgcolor=(r, g, b, 0xff)) data = canvas.dump() return data
execomrt/newton-dynamics
newton-4.00/doc/html/classd_bezier_spline.js
var classd_bezier_spline = [ [ "dBezierSpline", "classd_bezier_spline.html#abffbe67d583c6185d6cd9d58cac6c3a4", null ], [ "dBezierSpline", "classd_bezier_spline.html#a7fa17ee6b58141b0cb6f61c62c34f837", null ], [ "~dBezierSpline", "classd_bezier_spline.html#a80a79a2bdec4ebda389b71a97e7c5432", null ], [ "CalculateLength", "classd_bezier_spline.html#a91cd815ac0ec6bc466edec971bfbaf95", null ], [ "CreateFromKnotVectorAndControlPoints", "classd_bezier_spline.html#aad29b164dc789f86baf2ed06befeba52", null ], [ "CurveAllDerivatives", "classd_bezier_spline.html#acd62b908b8092b1032c06987a5d49f64", null ], [ "CurveDerivative", "classd_bezier_spline.html#a173fbb2070bed5b00dcc73d2dae83e5f", null ], [ "CurvePoint", "classd_bezier_spline.html#a18ee8cc99ad46515e4e2ea1cdf3991e5", null ], [ "FindClosestKnot", "classd_bezier_spline.html#a450128bfdd62344e86467ae9a30caa89", null ], [ "GetControlPoint", "classd_bezier_spline.html#aeeb16a10d171062afa6f1de4064337c2", null ], [ "GetControlPointArray", "classd_bezier_spline.html#a11632d0c95d0936e4a96fe3cc9acf141", null ], [ "GetControlPointArray", "classd_bezier_spline.html#af94fa47269afc9151a8a0b801079c2e0", null ], [ "GetControlPointCount", "classd_bezier_spline.html#ad2a1d16eccce06488ce472d3a2b4532f", null ], [ "GetDegree", "classd_bezier_spline.html#a99bed3d079a9ac43a2d770ea06c8cac4", null ], [ "GetKnot", "classd_bezier_spline.html#aac97feadc9d71824be3ca2be5e4e6b1c", null ], [ "GetKnotArray", "classd_bezier_spline.html#a594d67fe665e066341b975a8bdd62247", null ], [ "GetKnotArray", "classd_bezier_spline.html#a21d0b8ad3a30765298a7fa085531c7e6", null ], [ "GetKnotCount", "classd_bezier_spline.html#aefc0e2cbe00d1b8d66c7462d41555cf8", null ], [ "GlobalCubicInterpolation", "classd_bezier_spline.html#a071686aa54a82ae556de258c6d7ec831", null ], [ "InsertKnot", "classd_bezier_spline.html#a3f5369d3f28e50cf9b5baa8e675cdbd0", null ], [ "operator=", "classd_bezier_spline.html#aa6d03af8d90b24cbd7ab310a0726a5cc", null ], [ "RemoveKnot", "classd_bezier_spline.html#a4fea2e388deda6418cae644f46af8fb1", null ], [ "SetControlPoint", "classd_bezier_spline.html#a5d39c69c111731881500150eed5b33f6", null ] ];
halak/bibim
extlibs/freetype-2.5.2/src/pfr/PaxHeaders.20920/pfrobjs.h
30 atime=1386526222.311500098 30 ctime=1374498495.918317191
wjsi/mars
mars/tensor/base/tile.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 1999-2021 Alibaba Group Holding Ltd. # # 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. import numpy as np def tile(A, reps): """ Construct a tensor by repeating A the number of times given by reps. If `reps` has length ``d``, the result will have dimension of ``max(d, A.ndim)``. If ``A.ndim < d``, `A` is promoted to be d-dimensional by prepending new axes. So a shape (3,) array is promoted to (1, 3) for 2-D replication, or shape (1, 1, 3) for 3-D replication. If this is not the desired behavior, promote `A` to d-dimensions manually before calling this function. If ``A.ndim > d``, `reps` is promoted to `A`.ndim by pre-pending 1's to it. Thus for an `A` of shape (2, 3, 4, 5), a `reps` of (2, 2) is treated as (1, 1, 2, 2). Note : Although tile may be used for broadcasting, it is strongly recommended to use Mars' broadcasting operations and functions. Parameters ---------- A : array_like The input tensor. reps : array_like The number of repetitions of `A` along each axis. Returns ------- c : Tensor The tiled output tensor. See Also -------- repeat : Repeat elements of a tensor. broadcast_to : Broadcast a tensor to a new shape Examples -------- >>> import mars.tensor as mt >>> a = mt.array([0, 1, 2]) >>> mt.tile(a, 2).execute() array([0, 1, 2, 0, 1, 2]) >>> mt.tile(a, (2, 2)).execute() array([[0, 1, 2, 0, 1, 2], [0, 1, 2, 0, 1, 2]]) >>> mt.tile(a, (2, 1, 2)).execute() array([[[0, 1, 2, 0, 1, 2]], [[0, 1, 2, 0, 1, 2]]]) >>> b = mt.array([[1, 2], [3, 4]]) >>> mt.tile(b, 2).execute() array([[1, 2, 1, 2], [3, 4, 3, 4]]) >>> mt.tile(b, (2, 1)).execute() array([[1, 2], [3, 4], [1, 2], [3, 4]]) >>> c = mt.array([1,2,3,4]) >>> mt.tile(c,(4,1)).execute() array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]) """ from ..merge import concatenate try: tup = tuple(reps) except TypeError: tup = (reps,) d = len(tup) if A.ndim < d: A = A[tuple(np.newaxis for _ in range(d - A.ndim))] elif A.ndim > d: tup = (1,) * (A.ndim - d) + tup a = A for axis, rep in enumerate(tup): if rep == 0: slc = (slice(None),) * axis + (slice(0),) a = a[slc] elif rep < 0: raise ValueError("negative dimensions are not allowed") elif rep > 1: a = concatenate([a] * rep, axis=axis) return a
Twinparadox/AlgorithmProblem
Baekjoon/4806.cpp
<reponame>Twinparadox/AlgorithmProblem #include <iostream> #include <string> using namespace std; int main(void) { cin.ignore(); string s; int cnt = 0; while (getline(cin, s)) cnt++; cout << cnt; }
priya1puresoftware/python-slack-sdk
integration_tests/web/test_admin_conversations.py
import asyncio import logging import os import time import unittest from integration_tests.env_variable_names import ( SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN, SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID, SLACK_SDK_TEST_GRID_TEAM_ID, SLACK_SDK_TEST_GRID_USER_ID, ) from integration_tests.helpers import async_test from slack_sdk.web import WebClient from slack_sdk.web.async_client import AsyncWebClient class TestWebClient(unittest.TestCase): """Runs integration tests with real Slack API""" # TODO: admin_conversations_disconnectShared - not_allowed_token_type # TODO: admin_conversations_ekm_listOriginalConnectedChannelInfo - enable the feature def setUp(self): self.logger = logging.getLogger(__name__) self.org_admin_token = os.environ[SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN] self.sync_client: WebClient = WebClient(token=self.org_admin_token) self.async_client: AsyncWebClient = AsyncWebClient(token=self.org_admin_token) self.team_id = os.environ[SLACK_SDK_TEST_GRID_TEAM_ID] self.idp_group_id = os.environ[SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID] self.user_id = os.environ[SLACK_SDK_TEST_GRID_USER_ID] self.channel_name = f"test-channel-{int(round(time.time() * 1000))}" self.channel_rename = f"test-channel-renamed-{int(round(time.time() * 1000))}" def tearDown(self): pass def test_sync(self): client = self.sync_client conv_creation = client.admin_conversations_create( is_private=False, name=self.channel_name, team_id=self.team_id, ) self.assertIsNotNone(conv_creation) created_channel_id = conv_creation.data["channel_id"] self.assertIsNotNone( client.admin_conversations_invite( channel_id=created_channel_id, user_ids=[self.user_id], ) ) self.assertIsNotNone( client.admin_conversations_archive( channel_id=created_channel_id, ) ) self.assertIsNotNone( client.admin_conversations_unarchive( channel_id=created_channel_id, ) ) self.assertIsNotNone( client.admin_conversations_rename( channel_id=created_channel_id, name=self.channel_rename, ) ) search_result = client.admin_conversations_search( limit=1, sort="member_count", sort_dir="desc", ) self.assertIsNotNone(search_result.data["next_cursor"]) self.assertIsNotNone(search_result.data["conversations"]) self.assertIsNotNone( client.admin_conversations_getConversationPrefs( channel_id=created_channel_id, ) ) self.assertIsNotNone( client.admin_conversations_setConversationPrefs( channel_id=created_channel_id, prefs={}, ) ) self.assertIsNotNone( client.admin_conversations_getTeams( channel_id=created_channel_id, ) ) self.assertIsNotNone( client.admin_conversations_setTeams( team_id=self.team_id, channel_id=created_channel_id, org_channel=True, ) ) time.sleep(2) # To avoid channel_not_found self.assertIsNotNone( client.admin_conversations_convertToPrivate( channel_id=created_channel_id, ) ) time.sleep(2) # To avoid internal_error self.assertIsNotNone( client.admin_conversations_archive( channel_id=created_channel_id, ) ) time.sleep(2) # To avoid internal_error self.assertIsNotNone( client.admin_conversations_delete( channel_id=created_channel_id, ) ) @async_test async def test_async(self): # await asyncio.sleep(seconds) are included to avoid rate limiting errors client = self.async_client conv_creation = await client.admin_conversations_create( is_private=False, name=self.channel_name, team_id=self.team_id, ) self.assertIsNotNone(conv_creation) created_channel_id = conv_creation.data["channel_id"] self.assertIsNotNone( await client.admin_conversations_invite( channel_id=created_channel_id, user_ids=[self.user_id], ) ) self.assertIsNotNone( await client.admin_conversations_archive( channel_id=created_channel_id, ) ) self.assertIsNotNone( await client.admin_conversations_unarchive( channel_id=created_channel_id, ) ) self.assertIsNotNone( await client.admin_conversations_rename( channel_id=created_channel_id, name=self.channel_rename, ) ) self.assertIsNotNone(await client.admin_conversations_search()) self.assertIsNotNone( await client.admin_conversations_getConversationPrefs( channel_id=created_channel_id, ) ) self.assertIsNotNone( await client.admin_conversations_setConversationPrefs( channel_id=created_channel_id, prefs={}, ) ) self.assertIsNotNone( await client.admin_conversations_getTeams( channel_id=created_channel_id, ) ) self.assertIsNotNone( await client.admin_conversations_setTeams( team_id=self.team_id, channel_id=created_channel_id, org_channel=True, ) ) await asyncio.sleep(2) # To avoid channel_not_found self.assertIsNotNone( await client.admin_conversations_convertToPrivate( channel_id=created_channel_id, ) ) await asyncio.sleep(2) # To avoid internal_error self.assertIsNotNone( await client.admin_conversations_archive( channel_id=created_channel_id, ) ) await asyncio.sleep(2) # To avoid internal_error self.assertIsNotNone( await client.admin_conversations_delete( channel_id=created_channel_id, ) )
blbarker/atk
engine-plugins/graph-plugins/src/test/scala/org/trustedanalytics/atk/plugins/orientdb/GraphDbFactoryTest.scala
<gh_stars>1-10 /** * Copyright (c) 2015 Intel Corporation  * * 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.trustedanalytics.atk.plugins.orientdb import java.io.File import com.tinkerpop.blueprints.impls.orient.{ OrientGraphNoTx, OrientGraph } import org.scalatest.{ Matchers, WordSpec } import org.trustedanalytics.atk.testutils.DirectoryUtils class GraphDbFactoryTest extends WordSpec with Matchers { "graph database factory" should { val userName: String = "admin" val password: String = "<PASSWORD>" val host = "host" val port = "port" val rootPassword = "<PASSWORD>" "creates a graph database and takes input arguments" in { val dbUri: String = "memory:OrientTestDb" val dbConfig = new DbConfiguration(dbUri, userName, password, port, host, rootPassword) //Tested method val graph: OrientGraphNoTx = GraphDbFactory.createGraphDb(dbConfig) //Results validation graph.isClosed shouldBe false graph.shutdown() graph.isClosed shouldBe true } "connect to OrientDB" in { var tmpDir: File = null val dbName = "OrientDbTest" tmpDir = DirectoryUtils.createTempDirectory("orient-graph-for-unit-testing") val dbUri = "plocal:" + tmpDir.getAbsolutePath + "/" + dbName val dbConfig = new DbConfiguration(dbUri, userName, password, port, host, rootPassword) //Tested method val orientDb = GraphDbFactory.graphDbConnector(dbConfig) //Results validation orientDb.isClosed shouldBe false orientDb.shutdown() orientDb.isClosed shouldBe true //clean up: delete the database directory DirectoryUtils.deleteTempDirectory(tmpDir) } } }
fxiao/gitlab
ee/lib/ee/gitlab/search_results.rb
# frozen_string_literal: true module EE module Gitlab module SearchResults extend ::Gitlab::Utils::Override private override :projects def projects super.with_compliance_framework_settings end end end end
GuillaumeSimo/autoforecast
autoforecast/metrics/metrics.py
import numpy as np from sklearn.metrics import mean_absolute_error, mean_absolute_percentage_error, mean_squared_error def encode(data, col="bank"): map_col_to_col_id = {col: col_id for col_id, col in enumerate(data[col].unique())} data[f"{col}_token"] = data[col].map(map_col_to_col_id) return data, map_col_to_col_id def smape_score(y_test, y_pred): """ https://www.statology.org/smape-python/ """ y_test_ = [] y_pred_ = [] for test, pred in zip(y_test, y_pred): if abs(test) < 50 and abs(pred) < 50: y_test_.append(1) y_pred_.append(1) elif abs(test - pred) < 100: y_test_.append(1) y_pred_.append(1) else: y_test_.append(test) y_pred_.append(pred) y_test = np.array(y_test_) y_pred = np.array(y_pred_) if len(y_test) == 0: return 0.0 return ( 1 / len(y_test) * np.sum(2 * np.abs(y_pred - y_test) / (np.abs(y_test) + np.abs(y_pred)) * 100) ) def get_metrics(y_pred, y_test, y_naive=None): mse = mean_squared_error(y_pred, y_test) rmse = np.sqrt(mse) rmsle = np.log(rmse) mape = mean_absolute_percentage_error(y_test, y_pred) mae = mean_absolute_error(y_true=y_test, y_pred=y_pred) y_pred = np.array(y_pred) y_test = np.array(y_test) # https://en.wikipedia.org/wiki/Symmetric_mean_absolute_percentage_error# smape = smape_score(y_pred, y_test) y_pred = np.array([0.0 if pred_ < 1e-6 else pred_ for pred_ in y_pred]) mase = None if y_naive is not None: mae_naive = mean_absolute_error(y_true=y_test, y_pred=y_naive) if mae_naive == 0.0: if mae != 0.0: mae_naive = mae else: mase = 0.0 mae_naive = mae if mae_naive == 0.0 else mae_naive if mase is None: mase = mae / mae_naive return { "mse": mse, "rmse": rmse, "rmsle": rmsle, "mape": mape, "mae": mae, "smape": smape, "mase": mase, }
constrainedlearning/advbench
advbench/scripts/train_no_validation.py
<reponame>constrainedlearning/advbench import argparse from itertools import combinations_with_replacement import torch import random import numpy as np import os import json import pandas as pd import time from humanfriendly import format_timespan from advbench import datasets from advbench import algorithms from advbench import attacks from advbench import hparams_registry from advbench.lib import misc, meters, plotting, logging from torch.cuda.amp import autocast from torchsummary import summary try: import wandb wandb_log=True except ImportError: wandb_log=False PD_ALGORITHMS = [ 'Gaussian_DALE', 'Laplacian_DALE', 'Gaussian_DALE_PD', 'Gaussian_DALE_PD_Reverse', 'Laplacian_DALE_PD_Reverse', 'MH_DALE_PD_Reverse', 'KL_DALE_PD', ] def main(args, hparams, test_hparams): device = args.device print(f"Using {device}") hparams['model'] = args.model if args.perturbation=='SE': hparams['epsilon'] = torch.tensor([hparams[f'epsilon_{i}'] for i in ("rot","tx","ty")]).to(device) test_hparams['epsilon'] = torch.tensor([test_hparams[f'epsilon_{tfm}'] for tfm in ("rot","tx","ty")]).to(device) elif args.perturbation=='Translation': hparams['epsilon'] = torch.tensor([hparams[f'epsilon_{i}'] for i in ("tx","ty")]).to(device) test_hparams['epsilon'] = torch.tensor([test_hparams[f'epsilon_{tfm}'] for tfm in ("tx","ty")]).to(device) aug = args.augment if args.auto_augment: dataset = vars(datasets)[args.dataset](args.data_dir, augmentation= aug, auto_augment=True) elif args.auto_augment_wo_translations: dataset = vars(datasets)[args.dataset](args.data_dir, augmentation= aug, auto_augment=True, exclude_translations=True) else: dataset = vars(datasets)[args.dataset](args.data_dir, augmentation= aug) if args.epochs>0: dataset.N_EPOCHS = args.epochs train_ldr, val_ldr, test_ldr = datasets.to_loaders(dataset, hparams, device=device) kw_args = {"perturbation": args.perturbation} if args.algorithm in PD_ALGORITHMS: if args.algorithm.endswith("Reverse"): kw_args["init"] = 0.0 else: kw_args["init"] = 1.0 algorithm = vars(algorithms)[args.algorithm]( dataset.INPUT_SHAPE, dataset.NUM_CLASSES, hparams, device, **kw_args).to(device) adjust_lr = None if dataset.HAS_LR_SCHEDULE is False else dataset.adjust_lr try: summary(algorithm.classifier, input_size=dataset.INPUT_SHAPE, device=device) except: print("Model summary failed, currently does not support devices other than cpu or cuda.") test_attacks = { a: vars(attacks)[a](algorithm.classifier, test_hparams, device, perturbation=args.perturbation) for a in args.test_attacks} columns = ['Epoch', 'Accuracy', 'Eval-Method', 'Split', 'Train-Alg', 'Dataset', 'Trial-Seed', 'Output-Dir'] results_df = pd.DataFrame(columns=columns) def add_results_row(data): defaults = [args.algorithm, args.dataset, args.trial_seed, args.output_dir] results_df.loc[len(results_df)] = data + defaults if wandb_log: name = f"{args.flags}{args.perturbation} {args.algorithm} {args.model} {args.seed}" wandb.init(project=f"DAug-{args.dataset}", name=name) wandb.config.update(args) wandb.config.update(hparams) wandb.config.update({"test_"+key:val for key, val in test_hparams.items()}) train_eval, test_eval = [], [] if args.perturbation =="SE": translations = list(combinations_with_replacement(dataset.TRANSLATIONS, r=2)) for tx, ty in translations: eval_dict = {"tx": tx, "ty": ty} eval_dict["grid"] = logging.AngleGrid(algorithm, train_ldr, max_perturbations=dataset.ANGLE_GSIZE, tx=tx, ty=ty) train_eval.append(eval_dict.copy()) eval_dict["grid"] = logging.AngleGrid(algorithm, test_ldr, max_perturbations=dataset.ANGLE_GSIZE, tx=tx, ty=ty) test_eval.append(eval_dict.copy()) total_time = 0 step = 0 for epoch in range(0, dataset.N_EPOCHS): if adjust_lr is not None: adjust_lr(algorithm.optimizer, epoch, hparams) if wandb_log: wandb.log({'lr': algorithm.optimizer.param_groups[0]['lr'], 'epoch': epoch, 'step':step}) timer = meters.TimeMeter() epoch_start = time.time() for batch_idx, (imgs, labels) in enumerate(train_ldr): step+=imgs.shape[0] timer.batch_start() imgs, labels = imgs.to(device), labels.to(device) algorithm.step(imgs, labels) if batch_idx % dataset.LOG_INTERVAL == 0: print(f'Train epoch {epoch}/{dataset.N_EPOCHS} ', end='') print(f'({100. * batch_idx / len(train_ldr):.0f}%)]\t', end='') for name, meter in algorithm.meters.items(): if meter.print: print(f'{name}: {meter.val:.3f} (avg. {meter.avg:.3f})\t', end='') if wandb_log: wandb.log({name+"_avg": meter.avg, 'epoch': epoch, 'step':step}) print(f'Time: {timer.batch_time.val:.3f} (avg. {timer.batch_time.avg:.3f})') timer.batch_end() # save clean accuracies on validation/test sets if dataset.TEST_INTERVAL is None or epoch % dataset.TEST_INTERVAL == 0: test_clean_acc = misc.accuracy(algorithm, test_ldr, device) if wandb_log: wandb.log({'test_clean_acc': test_clean_acc, 'epoch': epoch, 'step':step}) add_results_row([epoch, test_clean_acc, 'ERM', 'Test']) if (epoch % dataset.ATTACK_INTERVAL == 0 and epoch>0) or epoch == dataset.N_EPOCHS-1: train_clean_acc = misc.accuracy(algorithm, val_ldr, device) if wandb_log: wandb.log({'train_clean_acc': train_clean_acc, 'epoch': epoch, 'step':step}) add_results_row([epoch, train_clean_acc, 'ERM', 'Train']) # compute save and log adversarial accuracies on validation/test sets test_adv_accs = [] for attack_name, attack in test_attacks.items(): test_adv_acc, test_adv_acc_mean, adv_loss, accs, loss, deltas = misc.adv_accuracy_loss_delta(algorithm, test_ldr, device, attack) add_results_row([epoch, test_adv_acc, attack_name, 'Test']) test_adv_accs.append(test_adv_acc) train_adv_acc, train_adv_acc_mean, train_adv_loss, train_accs, train_loss, train_deltas = misc.adv_accuracy_loss_delta(algorithm, val_ldr, device, attack) add_results_row([epoch, train_adv_acc, attack_name, 'Train']) test_adv_accs.append(test_adv_acc) if wandb_log: print(f"Logging {attack_name}...") wandb.log({'test_acc_adv_'+attack_name: test_adv_acc,'mean_test_acc_adv'+attack_name: test_adv_acc_mean, 'test_loss_adv_'+attack_name: adv_loss, 'test_loss_adv_mean_'+attack_name: loss.mean(), 'epoch': epoch, 'step':step}) wandb.log({'train_acc_adv_'+attack_name: train_adv_acc,'mean_train_acc_adv'+attack_name: train_adv_acc_mean, 'train_loss_adv_'+attack_name: train_adv_loss, 'train_loss_adv_mean_'+attack_name: loss.mean(), 'epoch': epoch, 'step':step}) if args.perturbation!="Linf": plotting.plot_perturbed_wandb(deltas, loss, name="test_loss_adv"+attack_name, wandb_args = {'epoch': epoch, 'step':step}, plot_mode="table") plotting.plot_perturbed_wandb(deltas, accs, name="test_acc_adv"+attack_name, wandb_args = {'epoch': epoch, 'step':step}, plot_mode="table") plotting.plot_perturbed_wandb(train_deltas, train_loss, name="train_loss_adv"+attack_name, wandb_args = {'epoch': epoch, 'step':step}, plot_mode="table") plotting.plot_perturbed_wandb(train_deltas, train_accs, name="train_acc_adv"+attack_name, wandb_args = {'epoch': epoch, 'step':step}, plot_mode="table") if args.log_imgs: imgs, labels = next(iter(test_ldr)) if algorithms.FFCV_AVAILABLE: with autocast(): attacked = attack(imgs.to(device), labels.to(device))[0] else: attacked = attack(imgs.to(device), labels.to(device))[0] for i in range(10): if attacked.shape[0] > imgs.shape[0]: og = imgs[0].to(device) else: og = imgs[i].to(device) wb_pert = wandb.Image(torch.stack([attacked[i], og]), caption=f"Perturbed and original image {i} {attack_name}") wandb.log({'Test image '+attack_name: wb_pert,'epoch': epoch, 'step':step}) if args.perturbation =="SE" and wandb_log and ((epoch % dataset.LOSS_LANDSCAPE_INTERVAL == 0 and epoch>0) or epoch == dataset.N_EPOCHS-1): # log loss landscape print(f"plotting and logging loss landscape") for eval, split in zip([train_eval, test_eval], ['train', 'test']): for eval_dict in eval: deltas, loss, acc = eval_dict["grid"].eval_perturbed(single_img=False) tx, ty = eval_dict["tx"], eval_dict["ty"] plotting.plot_perturbed_wandb(deltas[:, 0], loss, name=f"{split} angle vs loss ({tx},{ty})", wandb_args = {'epoch': epoch, 'step':step, 'tx':tx, 'ty':ty}) plotting.plot_perturbed_wandb(deltas[:, 0], acc, name=f"{split} angle vs accuracy ({tx},{ty})", wandb_args = {'epoch': epoch, 'step':step, 'tx':tx, 'ty':ty}) plotting.plot_perturbed_wandb(deltas[:, 0], acc, name=f"{split} angle vs accuracy ({tx},{ty})", wandb_args = {'epoch': epoch, 'step':step, 'tx':tx, 'ty':ty}) epoch_end = time.time() total_time += epoch_end - epoch_start # print results print(f'Epoch: {epoch+1}/{dataset.N_EPOCHS}\t', end='') print(f'Epoch time: {format_timespan(epoch_end - epoch_start)}\t', end='') print(f'Total time: {format_timespan(total_time)}\t', end='') print(f'Training alg: {args.algorithm}\t', end='') print(f'Dataset: {args.dataset}\t', end='') print(f'Path: {args.output_dir}') for name, meter in algorithm.meters.items(): if meter.print: print(f'Avg. train {name}: {meter.avg:.3f}\t', end='') if dataset.TEST_INTERVAL is None or epoch % dataset.TEST_INTERVAL == 0: print(f'\nClean val. accuracy: {test_clean_acc:.3f}\t', end='') if (epoch % dataset.ATTACK_INTERVAL == 0 and epoch>0) or epoch == dataset.N_EPOCHS-1: for attack_name, acc in zip(test_attacks.keys(), test_adv_accs): print(f'{attack_name} val. accuracy: {acc:.3f}\t', end='') print('\n') # save results dataframe to file results_df.to_pickle(os.path.join(args.output_dir, 'results.pkl')) # reset all meters meters_df = algorithm.meters_to_df(epoch) meters_df.to_pickle(os.path.join(args.output_dir, 'meters.pkl')) algorithm.reset_meters() # Save model model_filepath = os.path.join(args.output_dir, f'{name}_ckpt.pkl') torch.save(algorithm.state_dict(), model_filepath) # Push it to wandb if wandb_log: wandb.save(model_filepath) with open(os.path.join(args.output_dir, 'done'), 'w') as f: f.write('done') if __name__ == '__main__': parser = argparse.ArgumentParser(description='Adversarial robustness evaluation') parser.add_argument('--data_dir', type=str, default='./advbench/data') parser.add_argument('--output_dir', type=str, default='train_output') parser.add_argument('--dataset', type=str, default='MNIST', help='Dataset to use') parser.add_argument('--algorithm', type=str, default='ERM', help='Algorithm to run') parser.add_argument('--perturbation', type=str, default='Linf', help=' Linf or Rotation') parser.add_argument('--test_attacks', type=str, nargs='+', default=['PGD_Linf']) parser.add_argument('--hparams', type=str, help='JSON-serialized hparams dict') parser.add_argument('--hparams_seed', type=int, default=0, help='Seed for hyperparameters') parser.add_argument('--trial_seed', type=int, default=0, help='Trial number') parser.add_argument('--seed', type=int, default=0, help='Seed for everything else') parser.add_argument('--model', type=str, default='resnet18', help='Model to use') parser.add_argument('--optimizer', type=str, default='SGD', help='Optimizer to use') parser.add_argument('--log_imgs', action='store_true') parser.add_argument('--label_smoothing', type=float, default=0.0) parser.add_argument('--auto_augment', action='store_true') parser.add_argument('--augment', action='store_true') parser.add_argument('--auto_augment_wo_translations', action='store_true') parser.add_argument('--device', type=str, default='cuda', help='Device to use') parser.add_argument('--eps', type=float, default=0.0, help="Constraint level") parser.add_argument('--flags', type=str,default='', help='add to exp name') parser.add_argument('--epochs', type=int,default=0, help='custom number of epochs, use defaults if 0') parser.add_argument('--max_rot', type=int,default=0, help='max angle in degrees') parser.add_argument('--max_trans', type=int,default=0, help='max translation in pixels') args = parser.parse_args() os.makedirs(os.path.join(args.output_dir), exist_ok=True) print('Args:') for k, v in sorted(vars(args).items()): print(f'\t{k}: {v}') with open(os.path.join(args.output_dir, 'args.json'), 'w') as f: json.dump(args.__dict__, f, indent=2) if args.dataset not in vars(datasets): raise NotImplementedError(f'Dataset {args.dataset} is not implemented.') if args.hparams_seed == 0: hparams = hparams_registry.default_hparams(args.algorithm, args.perturbation, args.dataset) else: seed = misc.seed_hash(args.hparams_seed, args.trial_seed) hparams = hparams_registry.random_hparams(args.algorithm, args.perturbation, args.dataset, seed) if args.eps > 0: hparams['l_dale_pd_inv_margin'] = args.eps if args.max_rot > 0: hparams['epsilon_rot'] = args.max_rot if args.max_trans > 0: hparams['epsilon_tx'] = args.max_trans hparams['epsilon_ty'] = args.max_trans hparams['optimizer'] = args.optimizer hparams['label_smoothing'] = args.label_smoothing print ('Hparams:') for k, v in sorted(hparams.items()): print(f'\t{k}: {v}') with open(os.path.join(args.output_dir, 'hparams.json'), 'w') as f: json.dump(hparams, f, indent=2) test_hparams = hparams_registry.test_hparams(args.algorithm, args.perturbation, args.dataset) print('Test hparams:') for k, v in sorted(test_hparams.items()): print(f'\t{k}: {v}') with open(os.path.join(args.output_dir, 'test_hparams.json'), 'w') as f: json.dump(test_hparams, f, indent=2) torch.manual_seed(args.seed) random.seed(args.seed) np.random.seed(args.seed) main(args, hparams, test_hparams)
pengshangxian/wujie
pages/mycenter-extend/groupinfomation/groupinfomation.js
<gh_stars>0 // pages/mycenter-extend//groupinfomation/groupinfomation.js const util = require('../../../utils/util.js') Page({ /** * 页面的初始数据 */ data: { }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { util.request("/WxUserInfo/MyGroup", {}, "POST", false).then((res) => { console.log(res) this.setData({ list: res.data }) }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { }, applyassistant:function(e){ var list = e.currentTarget.dataset.current list = JSON.stringify(list) wx.navigateTo({ url: `../groupassistant1/groupassistant1?list=${list}`, }) }, deleteassistant:function(e){ var id = e.currentTarget.dataset.current; console.log(id) util.request("/WxUserInfo/ShutRobot", { F_GUID: id }, "POST", false).then((res) => { console.log(res) // this.setData({ // list: res.data // }) util.request("/WxUserInfo/MyGroup", {}, "POST", false).then((res) => { console.log(res) this.setData({ list: res.data }) }) }) } })
ascensio/scala-algo
src/org.salgo/sequences/searching/KnuthMorrisPratt.scala
package org.salgo.sequences.searching import scala.annotation.tailrec object KnuthMorrisPratt extends StringSearchAlgorithm { override def search(pattern: String, text: String, stopAtFirstMatch: Boolean, numberOfCharacters: Int): Seq[Int] = { val patternLength = pattern.length val textLength = text.length lazy val lookup = this.buildLookup(pattern) @tailrec def searchRecursive(offset: Int, index: Int, acc: Seq[Int]): Seq[Int] = { @tailrec def findMatchingPatternIndex(pIdx: Int, tIdx: Int): (Boolean, Int) = (pIdx + 1, tIdx + 1) match { case (p, t) if p >= patternLength || t >= textLength => (false, p) case (p, t) if p == patternLength - 1 => (true, p) case (p, t) if pattern(p) == text(t) => findMatchingPatternIndex(p, t) case (p, t) => (false, p) } if (offset + index >= textLength) acc else { val (found, patternMatchIndex) = findMatchingPatternIndex(index, offset) (found, patternMatchIndex) match { case (true, pi) => if (stopAtFirstMatch) Seq(offset) else searchRecursive(offset + pattern.length, 0, acc :+ offset) case (false, pi) => val lookupValue = lookup(pi) if (lookupValue > -1) searchRecursive(offset + pi - lookupValue, lookupValue, acc) else searchRecursive(offset + 1, 0, acc) } } } if (textLength > 0 && patternLength > 0) searchRecursive(0, 0, Seq.empty[Int]) else Seq.empty[Int] } private def buildLookup(pattern: String) : Array[Int] = { val patternLength = pattern.length @tailrec def buildLookupRecursive(cnd: Int, pos: Int, lookup: Array[Int]) : Array[Int] = (cnd, pos) match { case (c, p) if p >= patternLength => lookup case (c, p) if pattern(p - 1) == pattern(c) => lookup(pos) = cnd buildLookupRecursive(cnd + 1, pos + 1, lookup) case (c, p) if c > 0 => buildLookupRecursive(lookup(c), p, lookup) case (c, p) => lookup(p) = 0 buildLookupRecursive(c, p + 1, lookup) } buildLookupRecursive(0, 2, Array.fill[Int](pattern.length)(0)) } }
chromium7/mangovodo
django_project/celery.py
<reponame>chromium7/mangovodo<filename>django_project/celery.py import os from celery import Celery # Set the default django settings module for the 'celery' program os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_project.settings.production') app = Celery('mangovodo') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks()
AndreaVoltan/MyKratos7.0
kratos/solving_strategies/schemes/residual_based_bdf_displacement_scheme.h
<filename>kratos/solving_strategies/schemes/residual_based_bdf_displacement_scheme.h // | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: <NAME> // #if !defined(KRATOS_RESIDUAL_BASED_BDF_DISPLACEMENT_SCHEME ) #define KRATOS_RESIDUAL_BASED_BDF_DISPLACEMENT_SCHEME /* System includes */ /* External includes */ /* Project includes */ #include "solving_strategies/schemes/residual_based_bdf_scheme.h" #include "includes/variables.h" #include "includes/checks.h" namespace Kratos { ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /** * @class ResidualBasedBDFDisplacementScheme * @ingroup KratosCore * @brief BDF integration scheme (displacement based) * @details The \f$ n \f$ order Backward Differentiation Formula (BDF) method is a two step \f$ n \f$ order accurate method. * Look at the base class for more details * @see ResidualBasedBDFScheme * @author <NAME> */ template<class TSparseSpace, class TDenseSpace> class ResidualBasedBDFDisplacementScheme : public ResidualBasedBDFScheme<TSparseSpace, TDenseSpace> { public: ///@name Type Definitions ///@{ /// Pointer definition of ResidualBasedBDFDisplacementScheme KRATOS_CLASS_POINTER_DEFINITION( ResidualBasedBDFDisplacementScheme ); /// Base class definition typedef Scheme<TSparseSpace,TDenseSpace> BaseType; typedef ResidualBasedImplicitTimeScheme<TSparseSpace,TDenseSpace> ImplicitBaseType; typedef ResidualBasedBDFScheme<TSparseSpace,TDenseSpace> BDFBaseType; /// Data type definition typedef typename BDFBaseType::TDataType TDataType; /// Matrix type definition typedef typename BDFBaseType::TSystemMatrixType TSystemMatrixType; /// Vector type definition typedef typename BDFBaseType::TSystemVectorType TSystemVectorType; /// Local system matrix type definition typedef typename BDFBaseType::LocalSystemVectorType LocalSystemVectorType; /// Local system vector type definition typedef typename BDFBaseType::LocalSystemMatrixType LocalSystemMatrixType; /// DoF array type definition typedef typename BDFBaseType::DofsArrayType DofsArrayType; /// DoF vector type definition typedef typename Element::DofsVectorType DofsVectorType; /// Nodes containers definition typedef ModelPart::NodesContainerType NodesArrayType; /// Elements containers definition typedef ModelPart::ElementsContainerType ElementsArrayType; /// Conditions containers definition typedef ModelPart::ConditionsContainerType ConditionsArrayType; ///@} ///@name Life Cycle ///@{ /** * @brief Constructor. The BDF method (parameters) * @param ThisParameters Parameters with the integration order */ explicit ResidualBasedBDFDisplacementScheme(Parameters ThisParameters) : ResidualBasedBDFDisplacementScheme(ThisParameters.Has("integration_order") ? static_cast<std::size_t>(ThisParameters["integration_order"].GetInt()) : 2) { // Validate default parameters Parameters default_parameters = Parameters(R"( { "integration_order" : 2 })" ); ThisParameters.ValidateAndAssignDefaults(default_parameters); } /** * @brief Constructor. The BDF method * @param Order The integration order * @todo The ideal would be to use directly the dof or the variable itself to identify the type of variable and is derivatives */ explicit ResidualBasedBDFDisplacementScheme(const std::size_t Order = 2) :BDFBaseType(Order) { } /** Copy Constructor. */ explicit ResidualBasedBDFDisplacementScheme(ResidualBasedBDFDisplacementScheme& rOther) :BDFBaseType(rOther) { } /** * Clone */ typename BaseType::Pointer Clone() override { return Kratos::make_shared<ResidualBasedBDFDisplacementScheme>(*this); } /** Destructor. */ ~ResidualBasedBDFDisplacementScheme () override {} ///@} ///@name Operators ///@{ ///@} ///@name Operations ///@{ /** * @brief Performing the prediction of the solution * @details It predicts the solution for the current step x = xold + vold * Dt * @param rModelPart The model of the problem to solve * @param rDofSet Set of all primary variables * @param A LHS matrix * @param Dx Incremental update of primary variables * @param b RHS Vector */ void Predict( ModelPart& rModelPart, DofsArrayType& rDofSet, TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b ) override { KRATOS_TRY; ProcessInfo& current_process_info = rModelPart.GetProcessInfo(); const double delta_time = current_process_info[DELTA_TIME]; // Updating time derivatives (nodally for efficiency) const int num_nodes = static_cast<int>( rModelPart.Nodes().size() ); #pragma omp parallel for for(int i = 0; i< num_nodes; ++i) { auto it_node = rModelPart.Nodes().begin() + i; //ATTENTION::: the prediction is performed only on free nodes const array_1d<double, 3>& dot2un1 = it_node->FastGetSolutionStepValue(ACCELERATION, 1); const array_1d<double, 3>& dotun1 = it_node->FastGetSolutionStepValue(VELOCITY, 1); const array_1d<double, 3>& un1 = it_node->FastGetSolutionStepValue(DISPLACEMENT, 1); const array_1d<double, 3>& dot2un0 = it_node->FastGetSolutionStepValue(ACCELERATION); array_1d<double, 3>& dotun0 = it_node->FastGetSolutionStepValue(VELOCITY); array_1d<double, 3>& un0 = it_node->FastGetSolutionStepValue(DISPLACEMENT); if (it_node->HasDofFor(ACCELERATION_X)) { if (it_node -> IsFixed(ACCELERATION_X)) { dotun0[0] = (dot2un0[0] - BDFBaseType::mBDF[1] * dotun1[0])/BDFBaseType::mBDF[0]; un0[0] = (dotun0[0] - BDFBaseType::mBDF[1] * un1[0])/BDFBaseType::mBDF[0]; } } else if (it_node->HasDofFor(VELOCITY_X)) { if (it_node -> IsFixed(VELOCITY_X)) { un0[0] = (dotun1[0] - BDFBaseType::mBDF[1] * un1[0])/BDFBaseType::mBDF[0]; } } else if (it_node -> IsFixed(DISPLACEMENT_X) == false) { un0[0] = un1[0] + delta_time * dotun1[0] + 0.5 * std::pow(delta_time, 2) * dot2un1[0]; } if (it_node->HasDofFor(ACCELERATION_Y)) { if (it_node -> IsFixed(ACCELERATION_Y)) { dotun0[1] = (dot2un0[1] - BDFBaseType::mBDF[1] * dotun1[1])/BDFBaseType::mBDF[0]; un0[1] = (dotun0[1] - BDFBaseType::mBDF[1] * un1[1])/BDFBaseType::mBDF[0]; } } else if (it_node->HasDofFor(VELOCITY_Y)) { if (it_node -> IsFixed(VELOCITY_Y)) { un0[1] = (dotun1[1] - BDFBaseType::mBDF[1] * un1[1])/BDFBaseType::mBDF[0]; } } else if (it_node -> IsFixed(DISPLACEMENT_Y) == false) { un0[1] = un1[1] + delta_time * dotun1[1] + 0.5 * std::pow(delta_time, 2) * dot2un1[1]; } // For 3D cases if (it_node -> HasDofFor(DISPLACEMENT_Z)) { if (it_node->HasDofFor(ACCELERATION_Z)) { if (it_node -> IsFixed(ACCELERATION_Z)) { dotun0[2] = (dot2un0[2] - BDFBaseType::mBDF[1] * dotun1[2])/BDFBaseType::mBDF[0]; un0[2] = (dotun0[2] - BDFBaseType::mBDF[1] * un1[2])/BDFBaseType::mBDF[0]; } } else if (it_node->HasDofFor(VELOCITY_Y)) { if (it_node -> IsFixed(VELOCITY_Y)) { un0[2] = (dotun1[2] - BDFBaseType::mBDF[1] * un1[2])/BDFBaseType::mBDF[0]; } } else if (it_node -> IsFixed(DISPLACEMENT_Z) == false) { un0[2] = un1[2] + delta_time * dotun1[2] + 0.5 * std::pow(delta_time, 2) * dot2un1[2]; } } for (std::size_t i_order = 2; i_order < BDFBaseType::mOrder + 1; ++i_order) { const array_1d<double, 3>& dotun = it_node->FastGetSolutionStepValue(VELOCITY, i_order); const array_1d<double, 3>& un = it_node->FastGetSolutionStepValue(DISPLACEMENT, i_order); if (it_node->HasDofFor(ACCELERATION_X)) { if (it_node -> IsFixed(ACCELERATION_X)) { dotun0[0] -= (BDFBaseType::mBDF[i_order] * dotun[0])/BDFBaseType::mBDF[0]; un0[0] -= (BDFBaseType::mBDF[i_order] * un[0])/BDFBaseType::mBDF[0]; } } else if (it_node->HasDofFor(VELOCITY_X)) { if (it_node -> IsFixed(VELOCITY_X)) { un0[0] -= (BDFBaseType::mBDF[i_order] * un[0])/BDFBaseType::mBDF[0]; } } if (it_node->HasDofFor(ACCELERATION_Y)) { if (it_node -> IsFixed(ACCELERATION_Y)) { dotun0[1] -= (BDFBaseType::mBDF[i_order] * dotun[1])/BDFBaseType::mBDF[0]; un0[1] -= (BDFBaseType::mBDF[i_order] * un[1])/BDFBaseType::mBDF[0]; } } else if (it_node->HasDofFor(VELOCITY_Y)) { if (it_node -> IsFixed(VELOCITY_X)) { un0[1] -= (BDFBaseType::mBDF[i_order] * un[1])/BDFBaseType::mBDF[0]; } } // For 3D cases if (it_node -> HasDofFor(DISPLACEMENT_Z)) { if (it_node->HasDofFor(ACCELERATION_Z)) { if (it_node -> IsFixed(ACCELERATION_Z)) { dotun0[1] -= (BDFBaseType::mBDF[i_order] * dotun[2])/BDFBaseType::mBDF[0]; un0[1] -= (BDFBaseType::mBDF[i_order] * un[2])/BDFBaseType::mBDF[0]; } } else if (it_node->HasDofFor(VELOCITY_Y)) { if (it_node -> IsFixed(VELOCITY_X)) { un0[1] -= (BDFBaseType::mBDF[i_order] * un[2])/BDFBaseType::mBDF[0]; } } } } // Updating time derivatives UpdateFirstDerivative(it_node); UpdateSecondDerivative(it_node); } KRATOS_CATCH( "" ); } /** * @brief This function is designed to be called once to perform all the checks needed * on the input provided. * @details Checks can be "expensive" as the function is designed * to catch user's errors. * @param rModelPart The model of the problem to solve * @return Zero means all ok */ int Check(ModelPart& rModelPart) override { KRATOS_TRY; const int err = BDFBaseType::Check(rModelPart); if(err!=0) return err; // Check for variables keys // Verify that the variables are correctly initialized KRATOS_CHECK_VARIABLE_KEY(DISPLACEMENT) KRATOS_CHECK_VARIABLE_KEY(VELOCITY) KRATOS_CHECK_VARIABLE_KEY(ACCELERATION) // Check that variables are correctly allocated for(auto& rnode : rModelPart.Nodes()) { KRATOS_CHECK_VARIABLE_IN_NODAL_DATA(DISPLACEMENT,rnode) KRATOS_CHECK_VARIABLE_IN_NODAL_DATA(VELOCITY,rnode) KRATOS_CHECK_VARIABLE_IN_NODAL_DATA(ACCELERATION,rnode) KRATOS_CHECK_DOF_IN_NODE(DISPLACEMENT_X, rnode) KRATOS_CHECK_DOF_IN_NODE(DISPLACEMENT_Y, rnode) KRATOS_CHECK_DOF_IN_NODE(DISPLACEMENT_Z, rnode) } KRATOS_CATCH( "" ); return 0; } ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ /// Turn back information as a string. std::string Info() const override { return "ResidualBasedBDFDisplacementScheme"; } /// Print information about this object. void PrintInfo(std::ostream& rOStream) const override { rOStream << Info(); } /// Print object's data. void PrintData(std::ostream& rOStream) const override { rOStream << Info(); } ///@} ///@name Friends ///@{ protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ /** * @brief Updating first time derivative (velocity) * @param itNode the node interator */ inline void UpdateFirstDerivative(NodesArrayType::iterator itNode) override { array_1d<double, 3>& dotun0 = itNode->FastGetSolutionStepValue(VELOCITY); noalias(dotun0) = BDFBaseType::mBDF[0] * itNode->FastGetSolutionStepValue(DISPLACEMENT); for (std::size_t i_order = 1; i_order < BDFBaseType::mOrder + 1; ++i_order) noalias(dotun0) += BDFBaseType::mBDF[i_order] * itNode->FastGetSolutionStepValue(DISPLACEMENT, i_order); } /** * @brief Updating second time derivative (acceleration) * @param itNode the node interator */ inline void UpdateSecondDerivative(NodesArrayType::iterator itNode) override { array_1d<double, 3>& dot2un0 = itNode->FastGetSolutionStepValue(ACCELERATION); noalias(dot2un0) = BDFBaseType::mBDF[0] * itNode->FastGetSolutionStepValue(VELOCITY); for (std::size_t i_order = 1; i_order < BDFBaseType::mOrder + 1; ++i_order) noalias(dot2un0) += BDFBaseType::mBDF[i_order] * itNode->FastGetSolutionStepValue(VELOCITY, i_order); } ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@{ private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ ///@} ///@name Private Access ///@{ ///@} ///@} ///@name Serialization ///@{ ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ ///@} }; /* Class ResidualBasedBDFDisplacementScheme */ ///@} ///@name Type Definitions ///@{ ///@} ///@name Input and output ///@{ ///@} } /* namespace Kratos.*/ #endif /* KRATOS_RESIDUAL_BASED_BDF_DISPLACEMENT_SCHEME defined */
scottcmerritt/feedbacker
app/models/feedbacker/data_log.rb
<reponame>scottcmerritt/feedbacker module Feedbacker class DataLog < ApplicationRecord self.table_name = "data_logs" scope :recent, -> { order('created_at DESC') } def marshaled? self.value[0...2] != "[{" end def load_value begin return JSON.parse(self.value) if !marshaled? JSON.parse(Marshal.load(self.value)) #return JSON.parse(Marshal.load(self.value)) if Marshal.load(self.value).kind_of?(String) #JSON.parse(self.value) rescue begin JSON.parse(self.value) rescue nil end end end def old_load_value begin return Marshal.load(self.value) rescue Exception => ex Rails.logger.debug "ERROR::: inside load_value1 #{ex}" decoded = ActiveRecord::Base.connection.unescape_bytea(self.value) begin return Marshal.load(decoded) rescue Exception => ex Rails.logger.debug "ERROR::: inside load_value2 #{ex}" end end end def self.add domain: "log", key:, value: end def self.db_rows start: 120 datefmt = "%b %e, %Y %l:%M %p" #{}"%b %Y, %e %y" rows = DataLog.where(domain:"db",key:"rows").order("created_at DESC") rows = rows.where("created_at > ?",start.days.ago) hash_rows = [] rows.each do |row| ca = row.created_at #.strftime(datefmt) #row.created_at.strftime(datefmt) begin #hash_rows.push({data:JSON.parse(row.load_value),created_at:ca,note:row.note}) hash_rows.push({data:row.load_value,created_at:ca,note:row.note}) rescue Exception => ex Rails.logger.debug "Error::: db_rows: #{ex}" end end hash_rows end def self.db_rows_fmt start: 120, table_filters: nil table_filters = nil if !table_filters.nil? && table_filters.length == 0 dates = {} tables = {} DataLog.db_rows(start:start).each do |snapshot| datekey = snapshot[:created_at] dates[datekey] = {} unless snapshot.nil? || snapshot[:data].nil? snapshot[:data].each do |row| begin if table_filters.nil? || (table_filters.include?(row["table"]) || table_filters.any?{|s| s[row["table"]]}) tables[row["table"]] = {} unless tables.key?(row["table"]) tables[row["table"]][datekey] = row["count"] end rescue end end end end result = [] tables.each do |k,v| result.push({"name":k,"data":v}) end result end def self.mock_data user_id:nil DataLog.all.order("id DESC").offset(6).destroy_all (2..60).step(2) do |num| # (1...20).each do |num| date_ago = (num).days.ago dt = "WHERE (created_at < '#{date_ago}')" #ActiveRecord::Base.connection.execute("select count(*) from #{tbl} #{dt}")[0]["count"] %> rows = [] ActiveRecord::Base.connection.tables.each do |t| begin res_count = ActiveRecord::Base.connection.execute("select count(*) from #{t} #{dt}")[0]["count"] rescue res_count = ActiveRecord::Base.connection.execute("select count(*) from #{t}")[0]["count"] end rows.push({"table"=>t, "count"=>res_count}) end rows = rows.sort_by{|row| -row["count"]} DataLog.create(created_at:date_ago,note:"cleaning db",created_by:user_id,domain:"db",key:"rows", value:Marshal.dump(rows.to_json)) end end end end
marynaKhromova/kyma
components/helm-broker/internal/controller/broker/cluster_broker_facade_test.go
<gh_stars>0 package broker import ( "fmt" "testing" "context" "github.com/kubernetes-incubator/service-catalog/pkg/apis/servicecatalog/v1beta1" "github.com/kyma-project/kyma/components/helm-broker/internal/controller/automock" "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/kubernetes/scheme" "sigs.k8s.io/controller-runtime/pkg/client/fake" ) func TestClusterServiceBrokerCreateHappyPath(t *testing.T) { // GIVEN require.NoError(t, v1beta1.AddToScheme(scheme.Scheme)) cli := fake.NewFakeClientWithScheme(scheme.Scheme) brokerSyncer := &automock.ClusterBrokerSyncer{} brokerSyncer.On("Sync").Once().Return(nil) defer brokerSyncer.AssertExpectations(t) svcURL := fmt.Sprintf("http://%s.%s.svc.cluster.local/cluster", fixService(), fixWorkingNs()) sut := NewClusterBrokersFacade(cli, brokerSyncer, fixWorkingNs(), fixService(), fixBrokerName(), logrus.New()) // WHEN err := sut.Create() // THEN require.NoError(t, err) sb := &v1beta1.ClusterServiceBroker{} err = cli.Get(context.Background(), types.NamespacedName{Name: fixBrokerName()}, sb) require.NoError(t, err) assert.Equal(t, svcURL, sb.Spec.URL) require.NoError(t, err) } func TestClusterServiceBrokerDeleteHappyPath(t *testing.T) { // GIVEN require.NoError(t, v1beta1.AddToScheme(scheme.Scheme)) cli := fake.NewFakeClientWithScheme(scheme.Scheme) brokerSyncer := &automock.ClusterBrokerSyncer{} defer brokerSyncer.AssertExpectations(t) sut := NewClusterBrokersFacade(cli, brokerSyncer, fixWorkingNs(), fixService(), fixBrokerName(), logrus.New()) // WHEN err := sut.Delete() // THEN require.NoError(t, err) } func TestClusterServiceBrokerDeleteNotFoundErrorsIgnored(t *testing.T) { // GIVEN require.NoError(t, v1beta1.AddToScheme(scheme.Scheme)) cli := fake.NewFakeClientWithScheme(scheme.Scheme) brokerSyncer := &automock.ClusterBrokerSyncer{} defer brokerSyncer.AssertExpectations(t) sut := NewClusterBrokersFacade(cli, brokerSyncer, fixWorkingNs(), fixService(), fixBrokerName(), logrus.New()) // WHEN err := sut.Delete() // THEN require.NoError(t, err) } func TestClusterServiceBrokerDoesNotExist(t *testing.T) { // GIVEN require.NoError(t, v1beta1.AddToScheme(scheme.Scheme)) cli := fake.NewFakeClientWithScheme(scheme.Scheme) brokerSyncer := &automock.ClusterBrokerSyncer{} defer brokerSyncer.AssertExpectations(t) sut := NewClusterBrokersFacade(cli, brokerSyncer, fixWorkingNs(), fixService(), fixBrokerName(), logrus.New()) // WHEN ex, err := sut.Exist() // THEN require.NoError(t, err) assert.False(t, ex) } func TestClusterServiceBrokerExist(t *testing.T) { // GIVEN require.NoError(t, v1beta1.AddToScheme(scheme.Scheme)) cli := fake.NewFakeClientWithScheme(scheme.Scheme, &v1beta1.ClusterServiceBroker{ ObjectMeta: meta_v1.ObjectMeta{ Name: fixBrokerName(), }}) brokerSyncer := &automock.ClusterBrokerSyncer{} defer brokerSyncer.AssertExpectations(t) sut := NewClusterBrokersFacade(cli, brokerSyncer, fixWorkingNs(), fixService(), fixBrokerName(), logrus.New()) // WHEN ex, err := sut.Exist() // THEN require.NoError(t, err) assert.True(t, ex) } func fixBrokerName() string { return "helm-broker" }
bgerxx/woodpecker
integrationtest/vm/virtualrouter/test_stub.py
<filename>integrationtest/vm/virtualrouter/test_stub.py<gh_stars>0 ''' Create an unified test_stub to share test operations @author: Youyk ''' import os import subprocess import sys import time import threading import zstacklib.utils.ssh as ssh import zstackwoodpecker.test_lib as test_lib import zstackwoodpecker.test_util as test_util import zstackwoodpecker.zstack_test.zstack_test_vm as zstack_vm_header import zstackwoodpecker.zstack_test.zstack_test_volume as zstack_volume_header import zstackwoodpecker.zstack_test.zstack_test_security_group as zstack_sg_header import zstackwoodpecker.zstack_test.zstack_test_eip as zstack_eip_header import zstackwoodpecker.zstack_test.zstack_test_vip as zstack_vip_header import zstackwoodpecker.test_state as test_state import zstackwoodpecker.operations.net_operations as net_ops import zstackwoodpecker.operations.account_operations as acc_ops import zstackwoodpecker.operations.resource_operations as res_ops import apibinding.inventory as inventory import random Port = test_state.Port rule1_ports = Port.get_ports(Port.rule1_ports) rule2_ports = Port.get_ports(Port.rule2_ports) rule3_ports = Port.get_ports(Port.rule3_ports) rule4_ports = Port.get_ports(Port.rule4_ports) rule5_ports = Port.get_ports(Port.rule5_ports) denied_ports = Port.get_denied_ports() #rule1_ports = [1, 22, 100] #rule2_ports = [9000, 9499, 10000] #rule3_ports = [60000, 60010, 65535] #rule4_ports = [5000, 5501, 6000] #rule5_ports = [20000, 28999, 30000] #test_stub.denied_ports = [101, 4999, 8990, 15000, 30001, 49999] target_ports = rule1_ports + rule2_ports + rule3_ports + rule4_ports + rule5_ports + denied_ports def create_vlan_vm(l3_name=None, disk_offering_uuids=None, system_tags=None, session_uuid = None, instance_offering_uuid = None): image_name = os.environ.get('imageName_net') image_uuid = test_lib.lib_get_image_by_name(image_name).uuid if not l3_name: l3_name = os.environ.get('l3VlanNetworkName1') l3_net_uuid = test_lib.lib_get_l3_by_name(l3_name).uuid return create_vm([l3_net_uuid], image_uuid, 'vlan_vm', \ disk_offering_uuids, system_tags=system_tags, \ instance_offering_uuid = instance_offering_uuid, session_uuid = session_uuid) def create_lb_vm(l3_name=None, disk_offering_uuids=None, session_uuid = None): ''' Load Balance VM will only use L3VlanNetworkName6 ''' image_name = os.environ.get('imageName_net') image_uuid = test_lib.lib_get_image_by_name(image_name).uuid if not l3_name: l3_name = os.environ.get('l3VlanNetworkName6') l3_net_uuid = test_lib.lib_get_l3_by_name(l3_name).uuid return create_vm([l3_net_uuid], image_uuid, 'vlan_lb_vm', disk_offering_uuids, session_uuid = session_uuid) def create_sg_vm(l3_name=None, disk_offering_uuids=None, session_uuid = None): ''' SG test need more network commands in guest. So it needs VR image. ''' image_name = os.environ.get('imageName_net') image_uuid = test_lib.lib_get_image_by_name(image_name).uuid if not l3_name: #l3_name = 'guestL3VlanNetwork1' l3_name = os.environ.get('l3VlanNetworkName1') l3_net_uuid = test_lib.lib_get_l3_by_name(l3_name).uuid return create_vm([l3_net_uuid], image_uuid, 'vlan_vm', disk_offering_uuids, session_uuid = session_uuid) def create_windows_vm(l3_name=None, disk_offering_uuids=None, session_uuid = None): ''' Create windows platform type vm. ''' image_name = os.environ.get('imageName_windows') image_uuid = test_lib.lib_get_image_by_name(image_name).uuid if not l3_name: #l3_name = 'guestL3VlanNetwork1' l3_name = os.environ.get('l3VlanNetworkName1') l3_net_uuid = test_lib.lib_get_l3_by_name(l3_name).uuid return create_vm([l3_net_uuid], image_uuid, 'windows_vm', disk_offering_uuids, session_uuid = session_uuid) def create_windows_vm_2(l3_name=None, disk_offering_uuids=None, session_uuid = None, instance_offering_uuid = None): ''' Create windows platform type vm. ''' image_name = os.environ.get('imageName_windows') image_uuid = test_lib.lib_get_image_by_name(image_name).uuid if not l3_name: #l3_name = 'guestL3VlanNetwork1' l3_name = os.environ.get('l3VlanNetworkName1') l3_net_uuid = test_lib.lib_get_l3_by_name(l3_name).uuid return create_vm([l3_net_uuid], image_uuid, 'windows_vm', disk_offering_uuids, instance_offering_uuid = instance_offering_uuid, session_uuid = session_uuid) def create_other_vm(l3_name=None, disk_offering_uuids=None, session_uuid = None): ''' Create other platform type vm. ''' image_name = os.environ.get('imageName_other') image_uuid = test_lib.lib_get_image_by_name(image_name).uuid if not l3_name: #l3_name = 'guestL3VlanNetwork1' l3_name = os.environ.get('l3VlanNetworkName1') l3_net_uuid = test_lib.lib_get_l3_by_name(l3_name).uuid return create_vm([l3_net_uuid], image_uuid, 'other_vm', disk_offering_uuids, session_uuid = session_uuid) def create_basic_vm(disk_offering_uuids=None, session_uuid = None): image_name = os.environ.get('imageName_net') image_uuid = test_lib.lib_get_image_by_name(image_name).uuid l3_name = os.environ.get('l3VlanNetworkName1') l3_net_uuid = test_lib.lib_get_l3_by_name(l3_name).uuid return create_vm([l3_net_uuid], image_uuid, 'basic_no_vlan_vm', disk_offering_uuids, session_uuid = session_uuid) def create_user_vlan_vm(l3_name=None, disk_offering_uuids=None, session_uuid = None): image_name = os.environ.get('imageName_net') image_uuid = test_lib.lib_get_image_by_name(image_name).uuid if not l3_name: l3_name = os.environ.get('l3NoVlanNetworkName1') l3_net_uuid = test_lib.lib_get_l3_by_name(l3_name).uuid return create_vm([l3_net_uuid], image_uuid, 'user_vlan_vm', disk_offering_uuids, session_uuid = session_uuid) def create_specified_ps_vm(l3_name=None, ps_uuid=None, session_uuid = None): image_name = os.environ.get('imageName_net') image_uuid = test_lib.lib_get_image_by_name(image_name).uuid if not l3_name: l3_name = os.environ.get('l3NoVlanNetworkName1') l3_net_uuid = test_lib.lib_get_l3_by_name(l3_name).uuid return create_vm([l3_net_uuid], image_uuid, 'user_vlan_vm', session_uuid = session_uuid, ps_uuid = ps_uuid) def create_vlan_sg_vm(disk_offering_uuids=None, session_uuid = None): image_name = os.environ.get('imageName_net') image_uuid = test_lib.lib_get_image_by_name(image_name).uuid l3_name = os.environ.get('l3VlanNetworkName1') l3_net_uuid = test_lib.lib_get_l3_by_name(l3_name).uuid return create_vm([l3_net_uuid], image_uuid, 'vlan_sg_vm', disk_offering_uuids, session_uuid = session_uuid) def create_dnat_vm(disk_offering_uuids=None, session_uuid = None): image_name = os.environ.get('imageName_net') image_uuid = test_lib.lib_get_image_by_name(image_name).uuid l3_name = os.environ.get('l3VlanDNATNetworkName') l3_net_uuid = test_lib.lib_get_l3_by_name(l3_name).uuid return create_vm([l3_net_uuid], image_uuid, 'vlan_sg_vm', disk_offering_uuids, session_uuid = session_uuid) def create_vm_with_user_args(system_tags = None, session_uuid = None): image_name = os.environ.get('imageName_net') image_uuid = test_lib.lib_get_image_by_name(image_name).uuid l3_name = os.environ.get('l3VlanNetworkName1') l3_net_uuid = test_lib.lib_get_l3_by_name(l3_name).uuid return create_vm([l3_net_uuid], image_uuid, 'user_args_vm', system_tags = system_tags, session_uuid = session_uuid) # parameter: vmname; l3_net: l3_net_description, or [l3_net_uuid,]; image_uuid: def create_vm(l3_uuid_list, image_uuid, vm_name = None, \ disk_offering_uuids = None, default_l3_uuid = None, \ system_tags = None, instance_offering_uuid = None, session_uuid = None, ps_uuid=None): vm_creation_option = test_util.VmOption() conditions = res_ops.gen_query_conditions('type', '=', 'UserVm') if not instance_offering_uuid: instance_offering_uuid = res_ops.query_resource(res_ops.INSTANCE_OFFERING, conditions)[0].uuid vm_creation_option.set_instance_offering_uuid(instance_offering_uuid) vm_creation_option.set_l3_uuids(l3_uuid_list) vm_creation_option.set_image_uuid(image_uuid) vm_creation_option.set_name(vm_name) vm_creation_option.set_data_disk_uuids(disk_offering_uuids) vm_creation_option.set_default_l3_uuid(default_l3_uuid) vm_creation_option.set_system_tags(system_tags) vm_creation_option.set_session_uuid(session_uuid) vm_creation_option.set_ps_uuid(ps_uuid) vm = zstack_vm_header.ZstackTestVm() vm.set_creation_option(vm_creation_option) vm.create() return vm def create_vm_with_iso(l3_uuid_list, image_uuid, vm_name = None, root_disk_uuids = None, instance_offering_uuid = None, \ disk_offering_uuids = None, default_l3_uuid = None, system_tags = None, \ session_uuid = None, ps_uuid=None): vm_creation_option = test_util.VmOption() conditions = res_ops.gen_query_conditions('type', '=', 'UserVm') if not instance_offering_uuid: instance_offering_uuid = res_ops.query_resource(res_ops.INSTANCE_OFFERING, conditions)[0].uuid vm_creation_option.set_instance_offering_uuid(instance_offering_uuid) vm_creation_option.set_l3_uuids(l3_uuid_list) vm_creation_option.set_image_uuid(image_uuid) vm_creation_option.set_name(vm_name) vm_creation_option.set_root_disk_uuid(root_disk_uuids) vm_creation_option.set_data_disk_uuids(disk_offering_uuids) vm_creation_option.set_default_l3_uuid(default_l3_uuid) vm_creation_option.set_system_tags(system_tags) vm_creation_option.set_session_uuid(session_uuid) vm_creation_option.set_ps_uuid(ps_uuid) vm = zstack_vm_header.ZstackTestVm() vm.set_creation_option(vm_creation_option) vm.create() return vm def create_volume(volume_creation_option=None, session_uuid = None): if not volume_creation_option: disk_offering = test_lib.lib_get_disk_offering_by_name(os.environ.get('smallDiskOfferingName')) volume_creation_option = test_util.VolumeOption() volume_creation_option.set_disk_offering_uuid(disk_offering.uuid) volume_creation_option.set_name('vr_test_volume') volume_creation_option.set_session_uuid(session_uuid) volume = zstack_volume_header.ZstackTestVolume() volume.set_creation_option(volume_creation_option) volume.create() return volume def create_sg(sg_creation_option=None, session_uuid = None): if not sg_creation_option: sg_creation_option = test_util.SecurityGroupOption() sg_creation_option.set_name('test_sg') sg_creation_option.set_description('test sg description') sg_creation_option.set_session_uuid(session_uuid) sg = zstack_sg_header.ZstackTestSecurityGroup() sg.set_creation_option(sg_creation_option) sg.create() return sg def create_vlan_vm_with_volume(l3_name=None, disk_offering_uuids=None, disk_number=None, session_uuid = None): if not disk_offering_uuids: disk_offering = test_lib.lib_get_disk_offering_by_name(os.environ.get('smallDiskOfferingName')) disk_offering_uuids = [disk_offering.uuid] if disk_number: for i in range(disk_number - 1): disk_offering_uuids.append(disk_offering.uuid) return create_vlan_vm(l3_name, disk_offering_uuids, \ session_uuid = session_uuid) def create_eip(eip_name=None, vip_uuid=None, vnic_uuid=None, vm_obj=None, \ session_uuid = None): if not vip_uuid: l3_name = os.environ.get('l3PublicNetworkName') l3_uuid = test_lib.lib_get_l3_by_name(l3_name).uuid vip_uuid = net_ops.acquire_vip(l3_uuid).uuid eip_option = test_util.EipOption() eip_option.set_name(eip_name) eip_option.set_vip_uuid(vip_uuid) eip_option.set_vm_nic_uuid(vnic_uuid) eip_option.set_session_uuid(session_uuid) eip = zstack_eip_header.ZstackTestEip() eip.set_creation_option(eip_option) if vnic_uuid and not vm_obj: test_util.test_fail('vm_obj can not be None in create_eip() API, when setting vm_nic_uuid.') eip.create(vm_obj) return eip def create_vip(vip_name=None, l3_uuid=None, session_uuid = None): if not vip_name: vip_name = 'test vip' if not l3_uuid: l3_name = os.environ.get('l3PublicNetworkName') l3_uuid = test_lib.lib_get_l3_by_name(l3_name).uuid vip_creation_option = test_util.VipOption() vip_creation_option.set_name(vip_name) vip_creation_option.set_l3_uuid(l3_uuid) vip_creation_option.set_session_uuid(session_uuid) vip = zstack_vip_header.ZstackTestVip() vip.set_creation_option(vip_creation_option) vip.create() return vip def create_vr_vm(test_obj_dict, l3_name, session_uuid = None): ''' ''' vr_l3_uuid = test_lib.lib_get_l3_by_name(l3_name).uuid vrs = test_lib.lib_find_vr_by_l3_uuid(vr_l3_uuid) temp_vm = None if not vrs: #create temp_vm1 for getting vlan1's vr for test pf_vm portforwarding temp_vm = create_vlan_vm(l3_name, session_uuid = session_uuid) test_obj_dict.add_vm(temp_vm) vr = test_lib.lib_find_vr_by_vm(temp_vm.vm)[0] temp_vm.destroy(session_uuid) test_obj_dict.rm_vm(temp_vm) else: vr = vrs[0] if not test_lib.lib_is_vm_running(vr): test_lib.lib_robot_cleanup(test_obj_dict) test_util.test_skip('vr: %s is not running. Will skip test.' % vr.uuid) return vr def share_admin_resource(account_uuid_list): def get_uuid(resource): temp_list = [] for item in resource: temp_list.append(item.uuid) return temp_list resource_list = [] resource_list.extend(get_uuid(res_ops.get_resource(res_ops.INSTANCE_OFFERING))) resource_list.extend(get_uuid(res_ops.get_resource(res_ops.IMAGE))) resource_list.extend(get_uuid(res_ops.get_resource(res_ops.L3_NETWORK))) resource_list.extend(get_uuid(res_ops.get_resource(res_ops.DISK_OFFERING))) acc_ops.share_resources(account_uuid_list, resource_list) def get_vr_by_private_l3_name(l3_name): vr_l3_uuid = test_lib.lib_get_l3_by_name(l3_name).uuid vrs = test_lib.lib_find_vr_by_l3_uuid(vr_l3_uuid) if not vrs: #create temp_vm for getting vlan1's vr temp_vm = create_vlan_vm(l3_name) vr = test_lib.lib_find_vr_by_vm(temp_vm.vm)[0] temp_vm.destroy() else: vr = vrs[0] return vr def exercise_parallel(func, ops_num=10, thread_threshold=3): for ops_id in range(ops_num): thread = threading.Thread(target=func, args=(ops_id, )) while threading.active_count() > thread_threshold: time.sleep(0.5) exc = sys.exc_info() thread.start() while threading.activeCount() > 1: exc = sys.exc_info() time.sleep(0.1) def sleep_util(timestamp): while True: if time.time() >= timestamp: break time.sleep(0.5) def create_test_file(vm_inv, test_file): ''' the bandwidth is for calculate the test file size, since the test time should be finished in 60s. bandwidth unit is KB. ''' file_size = 1024 * 2 seek_size = file_size / 1024 - 1 cmd = 'dd if=/dev/zero of=%s bs=1K count=1 seek=%d' \ % (test_file, seek_size) if not test_lib.lib_execute_command_in_vm(vm_inv, cmd): test_util.test_fail('test file is not created') def attach_mount_volume(volume, vm, mount_point): volume.attach(vm) import tempfile script_file = tempfile.NamedTemporaryFile(delete=False) script_file.write(''' mkdir -p %s device="/dev/`ls -ltr --file-type /dev | awk '$4~/disk/ {print $NF}' | grep -v '[[:digit:]]' | tail -1`" mount ${device}1 %s ''' % (mount_point, mount_point)) script_file.close() vm_inv = vm.get_vm() if not test_lib.lib_execute_shell_script_in_vm(vm_inv, script_file.name): test_util.test_fail("mount operation failed in [volume:] %s in [vm:] %s" % (volume.get_volume().uuid, vm_inv.uuid)) os.unlink(script_file.name) def scp_file_to_vm(vm_inv, src_file, target_file): vm_ip = vm_inv.vmNics[0].ip vm_username = test_lib.lib_get_vm_username(vm_inv) vm_password = test_lib.lib_get_vm_password(vm_inv) ssh.scp_file(src_file, target_file, vm_ip, vm_username, vm_password) def make_ssh_no_password(vm_inv): vm_ip = vm_inv.vmNics[0].ip ssh.make_ssh_no_password(vm_ip, test_lib.lib_get_vm_username(vm_inv), \ test_lib.lib_get_vm_password(vm_inv)) def create_named_vm(vm_name=None, disk_offering_uuids=None, session_uuid = None): image_name = os.environ.get('imageName_net') image_uuid = test_lib.lib_get_image_by_name(image_name).uuid l3_name = os.environ.get('l3VlanNetworkName1') l3_net_uuid = test_lib.lib_get_l3_by_name(l3_name).uuid if not vm_name: vm_name = 'named_vm' return create_vm([l3_net_uuid], image_uuid, vm_name, disk_offering_uuids, session_uuid = session_uuid) def time_convert(log_str): time_str = log_str.split()[0]+' '+log_str.split()[1] time_microscond = time_str.split(',')[1] time_str = time_str.split(',')[0] time_tuple = time.strptime(time_str, "%Y-%m-%d %H:%M:%S") return int(time.mktime(time_tuple)*1000+int(time_microscond)) def get_stage_time(vm_name, begin_time): mn_server_log = "/usr/local/zstacktest/apache-tomcat/logs/management-server.log" file_obj = open(mn_server_log) for line in file_obj.readlines(): if line.find('APICreateVmInstanceMsg') != -1 and line.find(vm_name) != -1: time_stamp = time_convert(line) if int(time_stamp) >= begin_time: api_id = line.split('{"', 1)[1].split(',')[-3].split(':')[1].strip('"') break file_obj.close log_str = '' select_bs_time = select_bs_end_time = select_bs_begin_time = 0 allocate_host_time = allocate_host_end_time = allocate_host_begin_time = 0 allocate_ps_time = allocate_ps_end_time = allocate_ps_begin_time = 0 local_storage_allocate_capacity_time = local_storage_allocate_capacity_end_time = local_storage_allocate_capacity_begin_time = 0 allocate_volume_time = allocate_volume_end_time = allocate_volume_begin_time = 0 allocate_nic_time = allocate_nic_end_time = allocate_nic_begin_time = 0 instantiate_res_time = instantiate_res_end_time = instantiate_res_begin_time = 0 instantiate_res_pre_time = instantiate_res_pre_end_time = instantiate_res_pre_begin_time = 0 create_on_hypervisor_time = create_on_hypervisor_end_time = create_on_hypervisor_begin_time = 0 instantiate_res_post_time = instantiate_res_post_end_time = instantiate_res_post_begin_time = 0 file_obj = open(mn_server_log) for line in file_obj.readlines(): if line.find(api_id) != -1 and line.find('SimpleFlowChain') != -1 and line.find('VmImageSelectBackupStorageFlow') != -1 and line.find('start executing flow') != -1: select_bs_begin_time = time_convert(line) if line.find(api_id) != -1 and line.find('SimpleFlowChain') != -1 and line.find('VmImageSelectBackupStorageFlow') != -1 and line.find('successfully executed flow') != -1: select_bs_end_time = time_convert(line) if line.find(api_id) != -1 and line.find('SimpleFlowChain') != -1 and line.find('VmAllocateHostFlow') != -1 and line.find('start executing flow') != -1: allocate_host_begin_time = time_convert(line) if line.find(api_id) != -1 and line.find('SimpleFlowChain') != -1 and line.find('VmAllocateHostFlow') != -1 and line.find('successfully executed flow') != -1: allocate_host_end_time = time_convert(line) if line.find(api_id) != -1 and line.find('SimpleFlowChain') != -1 and line.find('VmAllocatePrimaryStorageFlow') != -1 and line.find('start executing flow') != -1: allocate_ps_begin_time = time_convert(line) if line.find(api_id) != -1 and line.find('SimpleFlowChain') != -1 and line.find('VmAllocatePrimaryStorageFlow') != -1 and line.find('successfully executed flow') != -1: allocate_ps_end_time = time_convert(line) if line.find(api_id) != -1 and line.find('SimpleFlowChain') != -1 and line.find('LocalStorageAllocateCapacityFlow') != -1 and line.find('start executing flow') != -1: local_storage_allocate_capacity_begin_time = time_convert(line) if line.find(api_id) != -1 and line.find('SimpleFlowChain') != -1 and line.find('LocalStorageAllocateCapacityFlow') != -1 and line.find('successfully executed flow') != -1: local_storage_allocate_capacity_end_time = time_convert(line) if line.find(api_id) != -1 and line.find('SimpleFlowChain') != -1 and line.find('VmAllocateVolumeFlow') != -1 and line.find('start executing flow') != -1: allocate_volume_begin_time = time_convert(line) if line.find(api_id) != -1 and line.find('SimpleFlowChain') != -1 and line.find('VmAllocateVolumeFlow') != -1 and line.find('successfully executed flow') != -1: allocate_volume_end_time = time_convert(line) if line.find(api_id) != -1 and line.find('SimpleFlowChain') != -1 and line.find('VmAllocateNicFlow') != -1 and line.find('start executing flow') != -1: allocate_nic_begin_time = time_convert(line) if line.find(api_id) != -1 and line.find('SimpleFlowChain') != -1 and line.find('VmAllocateNicFlow') != -1 and line.find('successfully executed flow') != -1: allocate_nic_end_time = time_convert(line) if line.find(api_id) != -1 and line.find('SimpleFlowChain') != -1 and line.find('VmInstantiateResourcePreFlow') != -1 and line.find('start executing flow') != -1: instantiate_res_pre_begin_time = time_convert(line) if line.find(api_id) != -1 and line.find('SimpleFlowChain') != -1 and line.find('VmInstantiateResourcePreFlow') != -1 and line.find('successfully executed flow') != -1: instantiate_res_pre_end_time = time_convert(line) if line.find(api_id) != -1 and line.find('SimpleFlowChain') != -1 and line.find('VmCreateOnHypervisorFlow') != -1 and line.find('start executing flow') != -1: create_on_hypervisor_begin_time = time_convert(line) if line.find(api_id) != -1 and line.find('SimpleFlowChain') != -1 and line.find('VmCreateOnHypervisorFlow') != -1 and line.find('successfully executed flow') != -1: create_on_hypervisor_end_time = time_convert(line) if line.find(api_id) != -1 and line.find('SimpleFlowChain') != -1 and line.find('VmInstantiateResourcePostFlow') != -1 and line.find('start executing flow') != -1: instantiate_res_post_begin_time = time_convert(line) if line.find(api_id) != -1 and line.find('SimpleFlowChain') != -1 and line.find('VmInstantiateResourcePostFlow') != -1 and line.find('successfully executed flow') != -1: instantiate_res_post_end_time = time_convert(line) file_obj.close() if select_bs_end_time != 0 and select_bs_begin_time != 0: select_bs_time = select_bs_end_time - select_bs_begin_time if allocate_host_end_time != 0 and allocate_host_begin_time != 0: allocate_host_time = allocate_host_end_time - allocate_host_begin_time if allocate_ps_end_time != 0 and allocate_ps_begin_time != 0: allocate_ps_time = allocate_ps_end_time - allocate_ps_begin_time if local_storage_allocate_capacity_end_time != 0 and local_storage_allocate_capacity_begin_time != 0: local_storage_allocate_capacity_time = local_storage_allocate_capacity_end_time - local_storage_allocate_capacity_begin_time if allocate_volume_end_time != 0 and allocate_volume_begin_time != 0: allocate_volume_time = allocate_volume_end_time - allocate_volume_begin_time if allocate_nic_end_time != 0 and allocate_volume_begin_time != 0: allocate_nic_time = allocate_nic_end_time - allocate_nic_begin_time if instantiate_res_pre_end_time != 0 and instantiate_res_pre_begin_time != 0: instantiate_res_pre_time = instantiate_res_pre_end_time - instantiate_res_pre_begin_time if create_on_hypervisor_end_time != 0 and create_on_hypervisor_begin_time != 0: create_on_hypervisor_time = create_on_hypervisor_end_time - create_on_hypervisor_begin_time if instantiate_res_post_end_time != 0 and instantiate_res_post_begin_time != 0: instantiate_res_post_time = instantiate_res_post_end_time - instantiate_res_post_begin_time return [select_bs_time, allocate_host_time, allocate_ps_time, local_storage_allocate_capacity_time, allocate_volume_time, allocate_nic_time, instantiate_res_pre_time, create_on_hypervisor_time, instantiate_res_post_time] def execute_shell_in_process(cmd, timeout=10, logfd=None): if not logfd: process = subprocess.Popen(cmd, executable='/bin/sh', shell=True, universal_newlines=True) else: process = subprocess.Popen(cmd, executable='/bin/sh', shell=True, stdout=logfd, stderr=logfd, universal_newlines=True) start_time = time.time() while process.poll() is None: curr_time = time.time() TEST_TIME = curr_time - start_time if TEST_TIME > timeout: process.kill() test_util.test_logger('[shell:] %s timeout ' % cmd) return False time.sleep(1) test_util.test_logger('[shell:] %s is finished.' % cmd) return process.returncode def find_ps_local(): ps_list = res_ops.get_resource(res_ops.PRIMARY_STORAGE) for ps in ps_list: if ps.type == inventory.LOCAL_STORAGE_TYPE: return ps test_util.test_logger("Can not find local primary storage ") return None def find_ps_nfs(): ps_list = res_ops.get_resource(res_ops.PRIMARY_STORAGE) for ps in ps_list: if ps.type == inventory.NFS_PRIMARY_STORAGE_TYPE: return ps test_util.test_logger("Can not find NFS primary storage ") return None def ensure_hosts_connected(wait_time): for i in range(wait_time): time.sleep(1) host_list = res_ops.query_resource(res_ops.HOST) for host in host_list: if not "connected" in host.status.lower(): test_util.test_logger("found not connected ps status: %s" %(host.status)) break else: return else: test_util.test_fail("host status didn't change to Connected within %s, therefore, failed" % (wait_time)) def create_vm_with_random_offering(vm_name, image_name=None, l3_name=None, session_uuid=None, instance_offering_uuid=None, host_uuid=None, disk_offering_uuids=None, root_password=<PASSWORD>, ps_uuid=None, system_tags=None): if image_name: imagename = os.environ.get(image_name) image_uuid = test_lib.lib_get_image_by_name(imagename).uuid else: conf = res_ops.gen_query_conditions('format', '!=', 'iso') conf = res_ops.gen_query_conditions('system', '=', 'false', conf) image_uuid = random.choice(res_ops.query_resource(res_ops.IMAGE, conf)).uuid if l3_name: l3name = os.environ.get(l3_name) l3_net_uuid = test_lib.lib_get_l3_by_name(l3name).uuid else: l3_net_uuid = random.choice(res_ops.get_resource(res_ops.L3_NETWORK)).uuid if not instance_offering_uuid: conf = res_ops.gen_query_conditions('type', '=', 'UserVM') instance_offering_uuid = random.choice(res_ops.query_resource(res_ops.INSTANCE_OFFERING, conf)).uuid vm_creation_option = test_util.VmOption() vm_creation_option.set_l3_uuids([l3_net_uuid]) vm_creation_option.set_image_uuid(image_uuid) vm_creation_option.set_instance_offering_uuid(instance_offering_uuid) vm_creation_option.set_name(vm_name) if system_tags: vm_creation_option.set_system_tags(system_tags) if disk_offering_uuids: vm_creation_option.set_data_disk_uuids(disk_offering_uuids) if root_password: vm_creation_option.set_root_password(<PASSWORD>) if host_uuid: vm_creation_option.set_host_uuid(host_uuid) if session_uuid: vm_creation_option.set_session_uuid(session_uuid) if ps_uuid: vm_creation_option.set_ps_uuid(ps_uuid) vm = zstack_vm_header.ZstackTestVm() vm.set_creation_option(vm_creation_option) vm.create() return vm def create_multi_volumes(count=10, host_uuid=None, ps=None): volume_list = [] for i in xrange(count): disk_offering = random.choice(res_ops.get_resource(res_ops.DISK_OFFERING)) volume_creation_option = test_util.VolumeOption() volume_creation_option.set_disk_offering_uuid(disk_offering.uuid) if ps: volume_creation_option.set_primary_storage_uuid(ps.uuid) if ps.type == inventory.LOCAL_STORAGE_TYPE: if not host_uuid: host_uuid = random.choice(res_ops.get_resource(res_ops.HOST)).uuid volume_creation_option.set_system_tags(['localStorage::hostUuid::{}'.format(host_uuid)]) volume = create_volume(volume_creation_option) volume_list.append(volume) for volume in volume_list: volume.check() if ps: for volume in volume_list: assert volume.get_volume().primaryStorageUuid == ps.uuid return volume_list def migrate_vm_to_random_host(vm): test_util.test_dsc("migrate vm to random host") if not test_lib.lib_check_vm_live_migration_cap(vm.vm): test_util.test_skip('skip migrate if live migrate not supported') target_host = test_lib.lib_find_random_host(vm.vm) current_host = test_lib.lib_find_host_by_vm(vm.vm) vm.migrate(target_host.uuid) new_host = test_lib.lib_get_vm_host(vm.vm) if not new_host: test_util.test_fail('Not find available Hosts to do migration') if new_host.uuid != target_host.uuid: test_util.test_fail('[vm:] did not migrate from [host:] %s to target [host:] %s, but to [host:] %s' % (vm.vm.uuid, current_host.uuid, target_host.uuid, new_host.uuid)) else: test_util.test_logger('[vm:] %s has been migrated from [host:] %s to [host:] %s' % (vm.vm.uuid, current_host.uuid, target_host.uuid)) def generate_pub_test_vm(tbj): disk_offering_uuids = [random.choice(res_ops.get_resource(res_ops.DISK_OFFERING)).uuid] l3_name_list = ['l3PublicNetworkName', 'l3NoVlanNetworkName1', 'l3NoVlanNetworkName2'] pub_l3_vm, flat_l3_vm, vr_l3_vm = [create_vm_with_random_offering(vm_name='test_vm', image_name='imageName_net', disk_offering_uuids=random.choice([None, disk_offering_uuids]), l3_name=name) for name in l3_name_list] for vm in pub_l3_vm, flat_l3_vm, vr_l3_vm: vm.check() tbj.add_vm(vm) return pub_l3_vm, flat_l3_vm, vr_l3_vm
mryx00/LiteBlog
gunSelf-admin/src/main/java/com/stylefeng/gunSelf/modular/system/dao/BlogtagRelaMapper.java
<filename>gunSelf-admin/src/main/java/com/stylefeng/gunSelf/modular/system/dao/BlogtagRelaMapper.java package com.stylefeng.gunSelf.modular.system.dao; import com.stylefeng.gunSelf.modular.system.model.BlogtagRela; import com.baomidou.mybatisplus.mapper.BaseMapper; /** * <p> * Mapper 接口 * </p> * * @author stylezhang123 * @since 2019-05-09 */ public interface BlogtagRelaMapper extends BaseMapper<BlogtagRela> { }
znerd/xins
src/java/org/xins/server/EngineState.java
<gh_stars>0 /* * $Id: EngineState.java,v 1.13 2007/03/15 17:08:41 agoubard Exp $ * * Copyright 2003-2007 Orange Nederland Breedband B.V. * See the COPYRIGHT file for redistribution and use restrictions. */ package org.xins.server; import org.xins.common.MandatoryArgumentChecker; /** * State of an <code>Engine</code>. * * @version $Revision: 1.13 $ $Date: 2007/03/15 17:08:41 $ * @author <a href="mailto:<EMAIL>"><NAME></a> */ final class EngineState { static final Type INTERMEDIATE_STATE = new Type(); static final Type USABLE_STATE = new Type(); static final Type ERROR_STATE = new Type(); /** * The <em>INITIAL</em> state. */ static final EngineState INITIAL = new EngineState("INITIAL", INTERMEDIATE_STATE); /** * The <em>BOOTSTRAPPING_FRAMEWORK</em> state. */ static final EngineState BOOTSTRAPPING_FRAMEWORK = new EngineState("BOOTSTRAPPING_FRAMEWORK", INTERMEDIATE_STATE); /** * The <em>FRAMEWORK_BOOTSTRAP_FAILED</em> state. */ static final EngineState FRAMEWORK_BOOTSTRAP_FAILED = new EngineState("FRAMEWORK_BOOTSTRAP_FAILED", ERROR_STATE); /** * The <em>CONSTRUCTING_API</em> state. */ static final EngineState CONSTRUCTING_API = new EngineState("CONSTRUCTING_API", INTERMEDIATE_STATE); /** * The <em>API_CONSTRUCTION_FAILED</em> state. */ static final EngineState API_CONSTRUCTION_FAILED = new EngineState("API_CONSTRUCTION_FAILED", ERROR_STATE); /** * The <em>BOOTSTRAPPING_API</em> state. */ static final EngineState BOOTSTRAPPING_API = new EngineState("BOOTSTRAPPING_API", INTERMEDIATE_STATE); /** * The <em>API_BOOTSTRAP_FAILED</em> state. */ static final EngineState API_BOOTSTRAP_FAILED = new EngineState("API_BOOTSTRAP_FAILED", ERROR_STATE); /** * The <em>INITIALIZING_API</em> state. */ static final EngineState INITIALIZING_API = new EngineState("INITIALIZING_API", INTERMEDIATE_STATE); /** * The <em>API_INITIALIZATION_FAILED</em> state. */ static final EngineState API_INITIALIZATION_FAILED = new EngineState("API_INITIALIZATION_FAILED", ERROR_STATE); /** * The <em>READY</em> state. */ static final EngineState READY = new EngineState("READY", USABLE_STATE); /** * The <em>DISPOSING</em> state. */ static final EngineState DISPOSING = new EngineState("DISPOSING", INTERMEDIATE_STATE); /** * The <em>DISPOSED</em> state. */ static final EngineState DISPOSED = new EngineState("DISPOSED", INTERMEDIATE_STATE); /** * The name of this state. Cannot be <code>null</code>. */ private final String _name; /** * The type of this state. Never <code>null</code>. */ private final Type _type; /** * Constructs a new <code>EngineState</code> object. * * @param name * the name of this state, cannot be <code>null</code>. * * @param type * the type of this state, cannot be <code>null</code>. * * @throws IllegalArgumentException * if <code>name == null || type == null</code>. */ EngineState(String name, Type type) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("name", name, "type", type); // Initialize fields _name = name; _type = type; } /** * Returns the name of this state. * * @return * the name of this state, cannot be <code>null</code>. */ public String getName() { return _name; } /** * Checks if this state is an error state. * * @return * <code>true</code> if this is an error state, <code>false</code> * otherwise. */ public boolean isError() { return _type == ERROR_STATE; } /** * Checks if this state allows function invocations. * * @return * <code>true</code> if this state allows function invocations, * <code>false</code> otherwise. */ public boolean allowsInvocations() { return _type == USABLE_STATE; } /** * Returns a textual representation of this object. * * @return * the name of this state, never <code>null</code>. */ public String toString() { return _name; } /** * Categorization of an engine state. * * @version $Revision: 1.13 $ $Date: 2007/03/15 17:08:41 $ * @author <a href="mailto:<EMAIL>"><NAME></a> */ static class Type { /** * Constructs a new instance. */ private Type() { // empty } } }
guoshucan/mpaas
ghost.framework.module/src/main/java/ghost/framework/module/data/bind/entity/package-info.java
<gh_stars>1-10 package ghost.framework.module.data.bind.entity;
gutenye/react-mc
src/Dialog/__tests__/Surface.test.js
<filename>src/Dialog/__tests__/Surface.test.js import React from 'react' import { shallow } from 'enzyme' import Surface from '../Surface' it('renders without crashing', () => { shallow(<Surface />) })
ahmadmo/cbox
src/main/java/org/telegram/bot/cbox/ChatSession.java
<filename>src/main/java/org/telegram/bot/cbox/ChatSession.java package org.telegram.bot.cbox; import com.google.common.cache.RemovalListener; import com.google.common.cache.RemovalNotification; import org.telegram.bot.cbox.model.FileItem; import org.telegram.bot.messaging.KeyPair; import org.telegram.bot.util.concurrent.CacheManager; import org.telegram.bot.util.concurrent.TimeProperty; import java.util.concurrent.atomic.AtomicReference; /** * @author ahmad */ public final class ChatSession { private static final CacheManager<KeyPair, ChatSession> SESSIONS = new CacheManager<>(TimeProperty.minutes(30), new RemovalListener<KeyPair, ChatSession>() { @Override public void onRemoval(RemovalNotification<KeyPair, ChatSession> notification) { ChatSession session = notification.getValue(); if (session != null) { session.versionHolder.clear(); } } }); private final KeyPair key; private final FileVersionHolder versionHolder = new FileVersionHolder(); private final FileFilter filter = new FileFilter(); private final Mood mood = new Mood(); private final AtomicReference<ChatState> currentChatState = new AtomicReference<>(ChatState.NONE); private final AtomicReference<ChatContext> currentChatContext = new AtomicReference<>(ChatContext.NONE); private final AtomicReference<String> currentSearchQuery = new AtomicReference<>(); private final AtomicReference<FileItem> currentFile = new AtomicReference<>(); public ChatSession(KeyPair key) { this.key = key; } public FileVersionHolder getVersionHolder() { return versionHolder; } public FileFilter getFilter() { return filter; } public Mood getMood() { return mood; } public ChatState getCurrentChatState() { return currentChatState.get(); } public void setCurrentChatState(ChatState state) { currentChatState.set(state); } public ChatContext getCurrentChatContext() { return currentChatContext.get(); } public void setCurrentChatContext(ChatContext context) { currentChatContext.set(context); } public String getCurrentSearchQuery() { return currentSearchQuery.get(); } public void setCurrentSearchQuery(String query) { currentSearchQuery.set(query); } public FileItem getCurrentFile() { return currentFile.get(); } public void setCurrentFile(FileItem fileItem) { currentFile.set(fileItem); } @Override public int hashCode() { return key.hashCode(); } @Override public boolean equals(Object obj) { return obj == this || obj != null && obj instanceof ChatSession && key.equals(((ChatSession) obj).key); } public static ChatSession get(KeyPair key) { ChatSession session = SESSIONS.retrieve(key); if (session == null) { final ChatSession s = SESSIONS.cacheIfAbsent(key, session = new ChatSession(key)); if (s != null) { session = s; } } return session; } }
UOC/dlkit
dlkit/primordium/mapping/coordinate_primitives.py
""" Basic coordinate implementions of osid.mapping.coordinate. Can be used by implementations and consumer applications alike. """ from dlkit.abstract_osid.mapping import primitives as abc_mapping_primitives from dlkit.abstract_osid.osid.errors import NullArgument, InvalidArgument from ..osid.primitives import OsidPrimitive from ..type.primitives import Type class BasicCoordinate(abc_mapping_primitives.Coordinate, OsidPrimitive): """ A coordinate represents a position. In this case a position in an N dimentional space where N is defined by the number of values in the values list. values and uncertanty list elements must be of type float or int. """ def __init__(self, values, uncertainty_minus=None, uncertainty_plus=None): self._values = self._float_list(values) self._dimensions = len(self._values) self._zero_uncertainty = None if uncertainty_minus is None: uncertainty_minus = self._get_zero_uncertainty() if uncertainty_plus is None: uncertainty_plus = self._get_zero_uncertainty() self._uncertainty_minus = self._float_list(uncertainty_minus, self._dimensions) self._uncertainty_plus = self._float_list(uncertainty_plus, self._dimensions) def _float_list(self, value_list, dimensions=None): if not isinstance(value_list, list): raise InvalidArgument('arguments must be list of floating point or integer values') if dimensions is not None and len(value_list) != dimensions: raise InvalidArgument('dimensions of uncertainty must match dimensions of values') return_list = list() for value in value_list: if isinstance(value, float) or isinstance(value, int): return_list.append(float(value)) else: raise InvalidArgument('arguments must be list of floating point or integer values') return return_list def _get_zero_uncertainty(self): if self._zero_uncertainty is None: uncertainty_list = list() for num in range(self._dimensions): uncertainty_list.append(0) self._zero_uncertainty = uncertainty_list return self._zero_uncertainty def _compare(self, other, method): """see https://regebro.wordpress.com/2010/12/13/python-implementing-rich-comparison-the-correct-way/""" # This needs to be updated to take uncertainty into account: if isinstance(other, abc_mapping_primitives.Coordinate): if self.get_dimensions() != other.get_dimensions(): return False other_values = other.get_values() for index in range(self._dimensions): if not method(self._values[index], other_values[index]): return False return True return NotImplemented def __lt__(self, other): return self._compare(other, lambda s, o: s < o) def __le__(self, other): return self._compare(other, lambda s, o: s <= o) def __eq__(self, other): return self._compare(other, lambda s, o: s == o) def __ge__(self, other): return self._compare(other, lambda s, o: s >= o) def __gt__(self, other): return self._compare(other, lambda s, o: s > o) def __ne__(self, other): result = self.__eq__(other) if result is NotImplemented: return result return not result def get_coordinate_type(self): return Type(identifier='basic_coordinate', authority='ODL.MIT.EDU', namespace='mapping.Coordinate', display_name='Basic Coordinate', display_label='Basic Coordinate', description='Coordinate Type for a Basic Coordinate', domain='mapping.Coordinate') coordinate_type = property(fget=get_coordinate_type) def get_dimensions(self): return self._dimensions dimensions = property(fget=get_dimensions) def get_values(self): return self._values values = property(fget=get_values) def defines_uncertainty(self): return (self._uncertainty_minus != self._zero_uncertainty and self._uncertainty_plus != self._zero_uncertainty) def get_uncertainty_minus(self): return self._uncertainty_minus uncertainty_minus = property(fget=get_uncertainty_minus) def get_uncertainty_plus(self): return self._uncertainty_plus uncertainty_plus = property(fget=get_uncertainty_plus)
jeanluctritsch/CommunityServer
web/studio/ASC.Web.Studio/addons/talk/js/talk.tabscontainer.js
<gh_stars>0 /* * * (c) Copyright Ascensio System Limited 2010-2021 * * 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. * */ window.ASC = window.ASC || {}; window.ASC.TMTalk = window.ASC.TMTalk || {}; window.ASC.TMTalk.tabsContainer = (function ($) { var isInit = false, tablistContainer = null, defaultTab = null, defaultContact = null, incomingMessages = {}, roomIds = {}; var translateSymbols = function (str, toText) { var symbols = [ ['&lt;', '<'], ['&gt;', '>'], ['&and;', '\\^'], ['&sim;', '~'], ['&amp;', '&'] ]; if (typeof str !== 'string' || str.length === 0) { return ''; } // replace html to symbols if (typeof toText === 'undefined' || toText === true) { var symInd = symbols.length; while (symInd--) { str = str.replace(new RegExp(symbols[symInd][0], 'g'), symbols[symInd][1]); } // replace symbols to html } else { var symInd = symbols.length; while (symInd--) { str = str.replace(new RegExp(symbols[symInd][1], 'g'), symbols[symInd][0]); } } return str; }; var setNodes = function () { if (tablistContainer === null) { var nodes = null; tablistContainer = document.getElementById('talkTabContainer'); nodes = ASC.TMTalk.dom.getElementsByClassName(tablistContainer, 'tab default', 'li'); defaultTab = nodes.length > 0 ? nodes[0] : null; defaultTab = defaultTab.cloneNode(true); defaultTab.className = defaultTab.className.replace(/\s*default\s*/, ' ').replace(/^\s+|\s+$/g, ''); } }; var init = function () { if (isInit === true) { return undefined; } isInit = true; // TODO ASC.TMTalk.contactsManager.bind(ASC.TMTalk.contactsManager.events.comeContact, onUpdateContact); ASC.TMTalk.contactsManager.bind(ASC.TMTalk.contactsManager.events.leftContact, onUpdateContact); ASC.TMTalk.mucManager.bind(ASC.TMTalk.mucManager.events.updateSubject, onUpdateSubject); ASC.TMTalk.roomsManager.bind(ASC.TMTalk.roomsManager.events.createRoom, onCreateRoom); ASC.TMTalk.roomsManager.bind(ASC.TMTalk.roomsManager.events.openRoom, onOpenRoom); ASC.TMTalk.roomsManager.bind(ASC.TMTalk.roomsManager.events.closeRoom, onCloseRoom); ASC.TMTalk.mucManager.bind(ASC.TMTalk.mucManager.events.updateRoom, onUpdateConference); ASC.TMTalk.messagesManager.bind(ASC.TMTalk.messagesManager.events.recvMessageFromConference, onRecvMessageFromConference); ASC.TMTalk.messagesManager.bind(ASC.TMTalk.messagesManager.events.composingMessageFromChat, onComposingMessageFromChat); ASC.TMTalk.messagesManager.bind(ASC.TMTalk.messagesManager.events.pausedMessageFromChat, onPausedMessageFromChat); ASC.TMTalk.messagesManager.bind(ASC.TMTalk.messagesManager.events.recvMessageFromChat, onRecvMessageFromChat); ASC.TMTalk.messagesManager.bind(ASC.TMTalk.messagesManager.events.recvOfflineMessagesFromChat, onRecvOfflineMessageFromChat); TMTalk.bind(TMTalk.events.pageFocus, onPageFocus); TMTalk.bind(TMTalk.events.pageKeyup, onPageKeyup); }; var onPageFocus = function () { var currentRoomData = ASC.TMTalk.roomsManager.getRoomData(); if (currentRoomData !== null) { var jid = '', nodes = null, nodesInd = 0; jid = currentRoomData.id; nodes = ASC.TMTalk.dom.getElementsByClassName(tablistContainer, 'tab', 'li'); nodesInd = nodes.length; while (nodesInd--) { if (nodes[nodesInd].getAttribute('data-cid') === jid) { ASC.TMTalk.dom.removeClass(nodes[nodesInd], 'new-message'); var state = ASC.TMTalk.dom.getElementsByClassName(nodes[nodesInd], 'state', 'div'); state[0].innerText = ""; } } } }; var onPageKeyup = function (evt) { switch (evt.keyCode) { case 48 : case 49 : case 50 : case 51 : case 52 : case 53 : case 54 : case 55 : case 56 : case 57 : if (evt.altKey === true) { var ntab = null, tabnum = evt.keyCode - 48, tabs = ASC.TMTalk.dom.getElementsByClassName(tablistContainer, 'tab', 'li'), tabsInd = 0; //tabsInd = tabs.length; //while (tabsInd--) { // if (ASC.TMTalk.dom.hasClass(tabs[tabsInd], 'current')) { // ntab = ASC.TMTalk.dom.nextElementSibling(tabs[tabsInd]); // break; // } //} //if (!ntab && tabs.length > 0) { // for (var i = 0, n = tabs.length; i < n; i++) { // if (ASC.TMTalk.dom.hasClass(tabs[i], 'default')) { // continue; // } // ntab = tabs[i]; // break; // } //} if (tabs.length >= tabnum) { for (var i = 0, n = tabs.length; i < n; i++) { if (ASC.TMTalk.dom.hasClass(tabs[i], 'default')) { continue; } if (--tabnum === 0) { ntab = tabs[i]; break; } } } if (ntab && !ASC.TMTalk.dom.hasClass(ntab, 'current')) { var roomId = ntab.getAttribute('data-roomid'); if (roomId) { ASC.TMTalk.roomsManager.openRoom(roomId); } } } break; } }; var onComposingMessageFromChat = function (jid) { var nodes = null, nodesInd = 0; nodes = ASC.TMTalk.dom.getElementsByClassName(tablistContainer, 'tab', 'li'); nodesInd = nodes.length; while (nodesInd--) { if (nodes[nodesInd].getAttribute('data-cid') === jid) { ASC.TMTalk.dom.addClass(nodes[nodesInd], 'typing'); break; } } }; var onPausedMessageFromChat = function (jid) { var nodes = null, nodesInd = 0; nodes = ASC.TMTalk.dom.getElementsByClassName(tablistContainer, 'tab', 'li'); nodesInd = nodes.length; while (nodesInd--) { if (nodes[nodesInd].getAttribute('data-cid') === jid) { ASC.TMTalk.dom.removeClass(nodes[nodesInd], 'typing'); break; } } }; var onRecvOfflineMessageFromChat = function(jid, name, date, body) { onRecvMessageFromChat(jid, name, date, body, true); }; var onRecvMessageFromChat = function (jid, name, date, body, isOffline) { var currentRoomData = ASC.TMTalk.roomsManager.getRoomData(); if (TMTalk.properties.focused === false || currentRoomData !== null && currentRoomData.id !== jid) { var found = false, nodes = null, nodesInd = 0; nodes = ASC.TMTalk.dom.getElementsByClassName(tablistContainer, 'tab', 'li'); nodesInd = nodes.length; while (nodesInd--) { if (nodes[nodesInd].getAttribute('data-cid') === jid) { ASC.TMTalk.dom.addClass(nodes[nodesInd], 'new-message'); found = true; } } if (found === false) { incomingMessages[jid] = true; } var openedRooms = localStorageManager.getItem("openedRooms") != undefined ? localStorageManager.getItem("openedRooms") : {}; if (openedRooms[jid]) { openedRooms[jid].inBackground = true; localStorageManager.setItem("openedRooms", openedRooms); } } }; var onRecvMessageFromConference = function (roomjid, name, displaydate, date, body, isMine) { var currentRoomData = ASC.TMTalk.roomsManager.getRoomData(); if (TMTalk.properties.focused === false || currentRoomData !== null && currentRoomData.id !== roomjid) { var found = false, nodes = null, nodesInd = 0; nodes = ASC.TMTalk.dom.getElementsByClassName(tablistContainer, 'tab', 'li'); nodesInd = nodes.length; while (nodesInd--) { if (nodes[nodesInd].getAttribute('data-cid') === roomjid) { ASC.TMTalk.dom.addClass(nodes[nodesInd], 'new-message'); found = true; } } } }; var onUpdateContact = function (jid, status, resource) { var classname = '', roomId = '', node = null, nodes = null, nodesInd = 0; if (!roomIds.hasOwnProperty(jid)) { return undefined; } roomId = roomIds[jid].id; nodes = ASC.TMTalk.dom.getElementsByClassName(tablistContainer, 'tab', 'li'); nodesInd = nodes.length; while (nodesInd--) { if (nodes[nodesInd].getAttribute('data-roomid') === roomId) { node = nodes[nodesInd]; classname = 'tab ' + status.className; if (ASC.TMTalk.dom.hasClass(node, 'current')) { classname += ' current'; } if (ASC.TMTalk.dom.hasClass(node, 'master')) { classname += ' master'; } if (ASC.TMTalk.dom.hasClass(node, 'new-message')) { classname += ' new-message'; } if (ASC.TMTalk.dom.hasClass(node, 'hidden')) { classname += ' hidden'; } node.className = classname; break; } } var currentRoomData = ASC.TMTalk.roomsManager.getRoomData(); if (currentRoomData !== null && currentRoomData.type === 'chat' && currentRoomData.id === jid) { setStatus('chat', {show : status.title, message : typeof resource === 'object' ? resource.message : ''}, 1); } }; var onUpdateSubject = function (roomjid, subject) { var currentRoomData = ASC.TMTalk.roomsManager.getRoomData(); if (currentRoomData !== null && currentRoomData.type === 'conference' && currentRoomData.id === roomjid) { setStatus('conference', {confsubject : subject}, 1); } }; var onUpdateConference = function (roomjid, room) { var tab = null, tabs = null, tabsInd = 0, nodes = null, roomId = ''; var roomdata = ASC.TMTalk.roomsManager.getRoomDataById(roomjid); if (roomdata === null) { return undefined; } roomId = roomdata.roomId; tabs = ASC.TMTalk.dom.getElementsByClassName(tablistContainer, 'tab', 'li'); tabsInd = tabs.length; while (tabsInd--) { if (tabs[tabsInd].getAttribute('data-roomid') === roomId) { tab = tabs[tabsInd]; nodes = ASC.TMTalk.dom.getElementsByClassName(tab, 'tab-title', 'div'); if (nodes.length > 0) { nodes[0].innerHTML = translateSymbols(room.name, false); } } } }; var onCreateRoom = function (roomId, data) { var tabname = '', classname = '', nodes = null, newtab = null; if (defaultTab === null) { throw 'no templates tab'; } newtab = defaultTab.cloneNode(true); newtab.setAttribute('data-roomid', roomId); classname = newtab.className; switch (data.type) { case 'chat' : roomIds[data.id] = { id : roomId, data : data }; newtab.setAttribute('data-cid', data.id); tabname = ASC.TMTalk.contactsManager.getContactName(data.id); classname += ' ' + ASC.TMTalk.contactsManager.getContactStatus(data.id).className; if (data.id === ASC.TMTalk.connectionManager.getDomain()) { classname += ' master'; } if (incomingMessages.hasOwnProperty(data.id)) { classname += ' new-message'; delete incomingMessages[data.id]; } break; case 'conference' : roomIds[data.id] = { id : roomId, data : data }; newtab.setAttribute('data-cid', data.id); tabname = ASC.TMTalk.mucManager.getConferenceName(data.id); classname += ' ' + data.type; break; case 'mailing' : roomIds[data.id] = { id : roomId, data : data }; newtab.setAttribute('data-cid', data.id); tabname = ASC.TMTalk.msManager.getListName(data.id); classname += ' ' + data.type; break; } newtab.className = classname; nodes = ASC.TMTalk.dom.getElementsByClassName(newtab, 'tab-title', 'div'); if (nodes.length > 0) { nodes[0].innerHTML = translateSymbols(tabname, false); nodes[0].setAttribute('title', tabname); } nodes = ASC.TMTalk.dom.getElementsByClassName(tablistContainer, 'tabs', 'ul'); if (nodes.length > 0) { nodes[0].appendChild(newtab); } }; var onOpenRoom = function (roomId, data, inBackground) { var pageHasFocus = false, nodes = null, currentTab = null, showSibling = false; if (inBackground !== true) { pageHasFocus = TMTalk.properties.focused; nodes = ASC.TMTalk.dom.getElementsByClassName(tablistContainer, 'tab', 'li'); for (var i = 0, n = nodes.length; i < n; i++) { if (nodes[i].getAttribute('data-roomid') === roomId) { currentTab = nodes[i]; ASC.TMTalk.dom.addClass(currentTab, 'current'); if (pageHasFocus === true) { ASC.TMTalk.dom.removeClass(currentTab, 'new-message'); var state = ASC.TMTalk.dom.getElementsByClassName(currentTab, 'state', 'div'); state[0].innerText = ""; } if (ASC.TMTalk.dom.hasClass(currentTab, 'hidden')) { showSibling = true; ASC.TMTalk.dom.removeClass(currentTab, 'hidden'); } } else { ASC.TMTalk.dom.removeClass(nodes[i], 'current'); if (showSibling === true) { ASC.TMTalk.dom.removeClass(nodes[i], 'hidden'); } } } } }; var onCloseRoom = function (roomId, data) { var isCurrent = false, node = null, nodes = null, nodesInd = 0; nodes = ASC.TMTalk.dom.getElementsByClassName(tablistContainer, 'tab', 'li'); nodesInd = nodes.length; while (nodesInd--) { if (nodes[nodesInd].getAttribute('data-roomid') === roomId) { node = nodes[nodesInd]; isCurrent = ASC.TMTalk.dom.hasClass(node, 'current'); var newCurrentRoom = null; if (isCurrent === true) { newCurrentRoom = ASC.TMTalk.dom.nextElementSibling(node); if (newCurrentRoom === null) { newCurrentRoom = ASC.TMTalk.dom.prevElementSibling(node); } } if (newCurrentRoom !== null && ASC.TMTalk.dom.hasClass(newCurrentRoom, 'default')) { newCurrentRoom = null; } node.parentNode.removeChild(node); if (newCurrentRoom !== null) { var roomId = newCurrentRoom.getAttribute('data-roomid'); if (roomId) { ASC.TMTalk.roomsManager.openRoom(roomId); } } if (isCurrent === true && newCurrentRoom === null) { resetStatus('information', {}, -1); } break; } } }; var resetStatus = function (type, value, priorityLevel) { var infoblocknode = document.getElementById('talkTabInfoBlock'); if (!infoblocknode) { return undefined; } priorityLevel = priorityLevel && isFinite(+priorityLevel) ? +priorityLevel : -1; infoblocknode.setAttribute('data-level', priorityLevel); setStatus(type, value, priorityLevel); }; var setStatus = function (type, value, priorityLevel) { var nodes = null, infoblocknode = null, lastPriorityLevel = -1; infoblocknode = document.getElementById('talkTabInfoBlock'); if (!infoblocknode) { return undefined; } priorityLevel = priorityLevel && isFinite(+priorityLevel) ? +priorityLevel : -1; lastPriorityLevel = infoblocknode.getAttribute('data-level'); lastPriorityLevel = lastPriorityLevel && isFinite(+lastPriorityLevel) ? +lastPriorityLevel : -1; if (value.hasOwnProperty('title')) { nodes = ASC.TMTalk.dom.getElementsByClassName(infoblocknode, 'information', 'span'); if (nodes.length > 0) { nodes[0].innerHTML = value.title; } } if (value.hasOwnProperty('hint')) { nodes = ASC.TMTalk.dom.getElementsByClassName(infoblocknode, 'hint', 'span'); if (nodes.length > 0) { nodes[0].innerHTML = value.hint; } } if (value.hasOwnProperty('department')) { nodes = ASC.TMTalk.dom.getElementsByClassName(infoblocknode, 'department', 'span'); if (nodes.length > 0) { if (value.department) { jQuery(nodes[0]).show(); nodes[0].innerHTML = Encoder.htmlEncode(value.department); } else { jQuery(nodes[0]).hide(); } } } if (value.hasOwnProperty('show')) { nodes = ASC.TMTalk.dom.getElementsByClassName(infoblocknode, 'show', 'span'); if (nodes.length > 0) { nodes[0].innerHTML = value.show; } } if (value.hasOwnProperty('message')) { nodes = ASC.TMTalk.dom.getElementsByClassName(infoblocknode, 'message', 'span'); if (nodes.length > 0) { nodes[0].innerHTML = value.message; } } if (value.hasOwnProperty('confsubject')) { nodes = ASC.TMTalk.dom.getElementsByClassName(infoblocknode, 'conference-subject', 'span'); if (nodes.length > 0) { nodes[0].innerHTML = value.confsubject; } } if (priorityLevel < lastPriorityLevel) { return undefined; } infoblocknode.setAttribute('data-level', priorityLevel); switch (type.toLowerCase()) { case 'information' : ASC.TMTalk.dom.removeClass(infoblocknode, 'hint'); ASC.TMTalk.dom.removeClass(infoblocknode, 'chat'); ASC.TMTalk.dom.removeClass(infoblocknode, 'conference'); ASC.TMTalk.dom.addClass(infoblocknode, 'information'); break; case 'chat' : ASC.TMTalk.dom.removeClass(infoblocknode, 'hint'); ASC.TMTalk.dom.removeClass(infoblocknode, 'conference'); ASC.TMTalk.dom.removeClass(infoblocknode, 'information'); ASC.TMTalk.dom.addClass(infoblocknode, 'chat'); break; case 'conference' : ASC.TMTalk.dom.removeClass(infoblocknode, 'hint'); ASC.TMTalk.dom.removeClass(infoblocknode, 'chat'); ASC.TMTalk.dom.removeClass(infoblocknode, 'information'); ASC.TMTalk.dom.addClass(infoblocknode, 'conference'); break; case 'hint' : ASC.TMTalk.dom.removeClass(infoblocknode, 'chat'); ASC.TMTalk.dom.removeClass(infoblocknode, 'information'); ASC.TMTalk.dom.removeClass(infoblocknode, 'conference'); ASC.TMTalk.dom.addClass(infoblocknode, 'hint'); break; } }; var prevTab = function () { var ptab = null, nodes = null, nodesInd = 0; nodes = ASC.TMTalk.dom.getElementsByClassName(tablistContainer, 'tab', 'li'); nodesInd = nodes.length; while (nodesInd--) { if (ASC.TMTalk.dom.hasClass(nodes[nodesInd], 'current')) { ptab = ASC.TMTalk.dom.prevElementSibling(nodes[nodesInd]); break; } } if (ptab !== null) { var roomId = ptab.getAttribute('data-roomid'); if (roomId) { ASC.TMTalk.roomsManager.openRoom(roomId); } } }; var nextTab = function () { var ntab = null, nodes = null, nodesInd = 0; nodes = ASC.TMTalk.dom.getElementsByClassName(tablistContainer, 'tab', 'li'); nodesInd = nodes.length; while (nodesInd--) { if (ASC.TMTalk.dom.hasClass(nodes[nodesInd], 'current')) { ntab = ASC.TMTalk.dom.nextElementSibling(nodes[nodesInd]); break; } } if (ntab === null) { for (var i = 0, n = nodes.length; i < n; i++) { if (ASC.TMTalk.dom.hasClass(nodes[i], 'default')) { continue; } ntab = nodes[i]; break; } } if (ntab !== null) { var roomId = ntab.getAttribute('data-roomid'); if (roomId) { ASC.TMTalk.roomsManager.openRoom(roomId); } } }; return { init : init, nodes : setNodes, setStatus : setStatus, resetStatus : resetStatus, prevTab : prevTab, nextTab : nextTab }; })(jQuery); (function ($) { function onChoseMoveTab (selectedElement, selectedTargets) { if (selectedTargets.length === 0) { return undefined; } if (ASC.TMTalk.dom.hasClass(selectedTargets[0], 'tab')) { var selectedTab = selectedElement, targetTab = selectedTargets[0]; if (ASC.TMTalk.dom.hasClass(selectedTab, 'tab') && ASC.TMTalk.dom.hasClass(targetTab, 'tab')) { selectedTab.parentNode.insertBefore(selectedTab, targetTab); } } } $(function () { ASC.TMTalk.tabsContainer.nodes(); if ($.browser.safari) { $('#talkTabContainer ul.tabs:first').mousedown(function () { if (window.getSelection) { window.getSelection().removeAllRanges(); } return false; }); } $('#talkTabContainer ul.tabs:first') .bind($.browser.safari || ($.browser.msie && $.browser.version < 9) ? 'mousewheel' : 'DOMMouseScroll', function (evt) { var tablistContainer = document.getElementById('talkTabContainer'), i = 0, n = 0, tabs = null, firsttab = null, lasttab = null, wheelDelta = 0; wheelDelta = evt.wheelDelta ? -evt.wheelDelta / 120 : evt.detail ? evt.detail / 3 : 0; if (wheelDelta === 0) { return undefined; } tabs = ASC.TMTalk.dom.getElementsByClassName(tablistContainer, 'tab', 'li'); for (var i = 0, n = tabs.length; i < n; i++) { if (!ASC.TMTalk.dom.hasClass(tabs[i], 'default')) { firsttab = tabs[i]; break; } } i = tabs.length; while (i--) { if (!ASC.TMTalk.dom.hasClass(tabs[i], 'default')) { lasttab = tabs[i]; break; } } if (firsttab === null || lasttab === null) { return undefined; } if (wheelDelta < 0 && ASC.TMTalk.dom.hasClass(firsttab, 'hidden')) { wheelDelta *= -1; var nodes = ASC.TMTalk.dom.getElementsByClassName(tablistContainer, 'tab hidden', 'li'); var nodesInd = nodes.length; while (wheelDelta > 0 && nodesInd--) { if (ASC.TMTalk.dom.hasClass(nodes[nodesInd], 'default')) { continue; } ASC.TMTalk.dom.removeClass(nodes[nodesInd], 'hidden'); wheelDelta--; } } else if (wheelDelta > 0 && lasttab.offsetTop >= lasttab.offsetHeight) { for (i = 0, n = tabs.length; wheelDelta > 0 && i < n; i++) { if (ASC.TMTalk.dom.hasClass(tabs[i], 'default') || ASC.TMTalk.dom.hasClass(tabs[i], 'hidden')) { continue; } ASC.TMTalk.dom.addClass(tabs[i], 'hidden'); wheelDelta--; } } if (ASC.TMTalk.dom.hasClass(firsttab, 'hidden')) { ASC.TMTalk.dom.addClass(tablistContainer, 'has-hidden'); } else { ASC.TMTalk.dom.removeClass(tablistContainer, 'has-hidden'); } if (lasttab.offsetTop >= lasttab.offsetHeight) { ASC.TMTalk.dom.addClass(tablistContainer, 'has-repressed'); } else { ASC.TMTalk.dom.removeClass(tablistContainer, 'has-repressed'); } }) .mousedown(function (evt) { var element = evt.target; if (!element || typeof element !== 'object') { return undefined; } if (ASC.TMTalk.dom.hasClass(element, 'tab-title')) { var tab = element.parentNode.parentNode; if (ASC.TMTalk.dom.hasClass(tab, 'tab')) { var tablistContainer = document.getElementById('talkTabContainer'), nodes = null, tabsInd = 0, tabs = null, targets = []; tabs = ASC.TMTalk.dom.getElementsByClassName(tablistContainer, 'tab', 'li'); tabsInd = tabs.length; while (tabsInd--) { if (ASC.TMTalk.dom.hasClass(tabs[tabsInd], 'default')) { continue; } targets.push(tabs[tabsInd]); } ASC.TMTalk.dragMaster.start( evt, tab, targets, {onChose : onChoseMoveTab}, function (el) { var name = '', nodes = null, classname = ''; nodes = ASC.TMTalk.dom.getElementsByClassName(el, 'tab-title', 'div'); name = nodes.length > 0 ? nodes[0].innerHTML : 'none'; if (!name) { name = el.getAttribute('data-name'); } classname = 'tab-dragable'; this.style.width = el.offsetWidth + 'px'; nodes = ASC.TMTalk.dom.getElementsByClassName(this, 'title', 'div'); if (nodes.length > 0) { nodes[0].innerHTML = name; } var contactjid = el.getAttribute('data-cid'); if (contactjid) { var status = ASC.TMTalk.contactsManager.getContactStatus(contactjid); if (status) { classname += ' ' + status.className; } } if (ASC.TMTalk.dom.hasClass(el, 'master')) { classname += ' master'; } if (ASC.TMTalk.dom.hasClass(el, 'current')) { classname += ' current'; } this.className = classname; } ); } } }) .mouseup(function (evt) { var element = evt.target; if (evt.which === 2) { var selectTab = element.parentNode.parentNode; if (ASC.TMTalk.dom.hasClass(selectTab, 'tab')) { var roomId = selectTab.getAttribute('data-roomid'); if (roomId) { ASC.TMTalk.roomsManager.closeRoom(roomId); } } } }) .click(function (evt) { var element = evt.target; if (ASC.TMTalk.dom.hasClass(element, 'button-talk') && ASC.TMTalk.dom.hasClass(element, 'close')) { var selectTab = element.parentNode.parentNode; if (ASC.TMTalk.dom.hasClass(selectTab, 'tab')) { var roomId = selectTab.getAttribute('data-roomid'); var jid = selectTab.getAttribute('data-cid'); if (roomId) { ASC.TMTalk.roomsManager.closeRoom(roomId); } if (jid && !ASC.TMTalk.dom.hasClass(selectTab, 'conference')) { ASC.TMTalk.messagesManager.clearCurrentHistory(jid); } } } else if (ASC.TMTalk.dom.hasClass(element, 'tab-title') || ASC.TMTalk.dom.hasClass(element, 'state') || ASC.TMTalk.dom.hasClass(ASC.TMTalk.dom.lastElementChild(element), 'tab-title')) { var selectTab = null; if (ASC.TMTalk.dom.hasClass(ASC.TMTalk.dom.lastElementChild(element), 'tab-title')) { selectTab = element.parentNode; } else { selectTab = element.parentNode.parentNode; } if (ASC.TMTalk.dom.hasClass(selectTab, 'tab')) { if (!ASC.TMTalk.dom.hasClass(selectTab, 'current')) { var roomId = selectTab.getAttribute('data-roomid'); if (roomId) { ASC.TMTalk.roomsManager.openRoom(roomId); } } } } }); $('#talkTabContainer div.navigation:first').click(function (evt) { var element = evt.target; if (ASC.TMTalk.dom.hasClass(element, 'size') || ASC.TMTalk.dom.hasClass(element, 'countHiddenTabs') || ASC.TMTalk.dom.hasClass(element, 'all') || ASC.TMTalk.dom.hasClass(element, 'pointer-down')) { var $container = null; var nodes = ASC.TMTalk.dom.getElementsByClassName(document.getElementById('talkTabContainer'), 'tab hidden', 'li'); var hiddenLen = (nodes.length === 1 && ASC.TMTalk.dom.hasClass(nodes[0], 'default')) ? 0 : nodes.length; if (($container = $('#talkTabContainer div.navigation:first div.popupContainerClass:first')).is(':hidden') && hiddenLen!==0) { $container.show('fast', function () { if ($.browser.msie) { window.focus(); } $(document).one('click', function () { $('#talkTabContainer div.navigation:first div.popupContainerClass:first').hide(); }); }); } }else if (ASC.TMTalk.dom.hasClass(element, 'button-talk') && ASC.TMTalk.dom.hasClass(element, 'move-to-left')) { var tablistContainer = document.getElementById('talkTabContainer'), nodes = null, lasttab = null; nodes = ASC.TMTalk.dom.getElementsByClassName(tablistContainer, 'tab hidden', 'li'); if (nodes.length > 0) { ASC.TMTalk.dom.removeClass(nodes[nodes.length - 1], 'hidden'); } nodes = ASC.TMTalk.dom.getElementsByClassName(tablistContainer, 'tab hidden', 'li'); var hiddenLen = (nodes.length === 1 && ASC.TMTalk.dom.hasClass(nodes[0], 'default')) ? 0 : nodes.length; if (hiddenLen > 0) { ASC.TMTalk.dom.addClass(tablistContainer, 'has-hidden'); } else { ASC.TMTalk.dom.removeClass(tablistContainer, 'has-hidden'); } nodes = ASC.TMTalk.dom.getElementsByClassName(tablistContainer, 'tab', 'li'); if (nodes.length > 0 && ASC.TMTalk.dom.hasClass(nodes[nodes.length - 1], 'default') === false) { lasttab = nodes[nodes.length - 1]; if (lasttab.offsetTop >= lasttab.offsetHeight) { ASC.TMTalk.dom.addClass(tablistContainer, 'has-repressed'); } else { ASC.TMTalk.dom.removeClass(tablistContainer, 'has-repressed'); } } } else if (ASC.TMTalk.dom.hasClass(element, 'move-to-right')) { var tablistContainer = document.getElementById('talkTabContainer'), nodes = null, nodesInd = 0, lasttab = null; nodes = ASC.TMTalk.dom.getElementsByClassName(tablistContainer, 'tab', 'li'); if (nodes.length > 0 && ASC.TMTalk.dom.hasClass(nodes[nodes.length - 1], 'default') === false) { lasttab = nodes[nodes.length - 1]; } if (lasttab === null || lasttab.offsetTop < lasttab.offsetHeight) { return undefined; } for (var i = 0, n = nodes.length; i < n; i++) { if (ASC.TMTalk.dom.hasClass(nodes[i], 'hidden')) { continue; } ASC.TMTalk.dom.addClass(nodes[i], 'hidden'); break; } nodes = ASC.TMTalk.dom.getElementsByClassName(tablistContainer, 'tab hidden', 'li'); var hiddenLen = (nodes.length === 1 && ASC.TMTalk.dom.hasClass(nodes[0], 'default')) ? 0 : nodes.length; if (hiddenLen > 0) { ASC.TMTalk.dom.addClass(tablistContainer, 'has-hidden'); } else { ASC.TMTalk.dom.removeClass(tablistContainer, 'has-hidden'); } nodes = ASC.TMTalk.dom.getElementsByClassName(tablistContainer, 'tab', 'li'); if (nodes.length > 0 && ASC.TMTalk.dom.hasClass(nodes[nodes.length - 1], 'default') === false) { lasttab = nodes[nodes.length - 1]; if (lasttab.offsetTop >= lasttab.offsetHeight) { ASC.TMTalk.dom.addClass(tablistContainer, 'has-repressed'); } else { ASC.TMTalk.dom.removeClass(tablistContainer, 'has-repressed'); } } } else if (ASC.TMTalk.dom.hasClass(element, 'hiddenContactTitle')) { var needHiddenTab = jq("#talkTabContainer li.tab[data-cid='" + element.parentNode.getAttribute('data-cid') + "'].hidden"); if (needHiddenTab.length !== 0) { jq("#talkTabContainer li.tab:not(.hidden):first").addClass('hidden'); needHiddenTab.removeClass('hidden'); findHiddenTabs(document.getElementById('talkTabContainer')); if (!needHiddenTab.hasClass('current')) { var roomId = needHiddenTab[0].getAttribute('data-roomid'); if (roomId) { ASC.TMTalk.roomsManager.openRoom(roomId); } } } } }); var findHiddenTabs = function (tablistContainer) { var countHiddenMessages = 0; var nodes = ASC.TMTalk.dom.getElementsByClassName(tablistContainer, 'tab hidden', 'li'); var hiddenLen = (nodes.length === 1 && ASC.TMTalk.dom.hasClass(nodes[0], 'default')) ? 0 : nodes.length; var containerHiddenTabs = ASC.TMTalk.dom.getElementsByClassName(tablistContainer, 'popupContainerClass hiddenTabs', 'div'); var nodesContact = ASC.TMTalk.dom.getElementsByClassName(containerHiddenTabs[0], 'contact default', 'li'); var newcontact, newcontacttitle, classname, contactjid, titleHiddenTab = null; var defaultContact = nodesContact.length > 0 ? nodesContact[0] : null; var listHiddenTabs = ASC.TMTalk.dom.getElementsByClassName(containerHiddenTabs[0], 'contactlist', 'ul'); if (hiddenLen >= 2) { jq("div.popupContainerClass.hiddenTabs li").not(".default").remove(); jq('div#talkTabContainer div.navigation div.size div.hiddennewmessage:first').hide(); for (var i = 1; i < nodes.length; i++) { newcontact = defaultContact.cloneNode(true); newcontact.className = newcontact.className.replace(/\s*default\s*/, ' ').replace(/^\s+|\s+$/g, ''); contactjid = nodes[i].getAttribute('data-cid'); newcontact.setAttribute('data-cid', contactjid); titleHiddenTab = ASC.TMTalk.dom.getElementsByClassName(nodes[i], 'tab-title', 'div'); classname = newcontact.className; classname += ' ' + ASC.TMTalk.contactsManager.getContactStatus(contactjid).className; if (contactjid === ASC.TMTalk.connectionManager.getDomain()) { classname += ' master'; } if (ASC.TMTalk.dom.hasClass(nodes[i], 'conference')) { classname += ' room'; } if (ASC.TMTalk.dom.hasClass(nodes[i], 'mailing')) { classname += ' mailing'; } if (ASC.TMTalk.dom.hasClass(nodes[i], 'new-message')) { classname += ' new-message'; countHiddenMessages += ASC.TMTalk.contactsContainer.findUnreadMessages(newcontact, nodes[i].getAttribute('data-cid'),true); jq('div#talkTabContainer div.navigation div.size div.hiddennewmessage:first').show(); if (countHiddenMessages < 10) { jq('div#talkTabContainer div.navigation div.size div.hiddennewmessage:first').removeClass('many-message'); jq('div#talkTabContainer div.navigation div.size div.hiddennewmessage:first').addClass('few-message'); } else { jq('div#talkTabContainer div.navigation div.size div.hiddennewmessage:first').addClass('many-message'); jq('div#talkTabContainer div.navigation div.size div.hiddennewmessage:first').removeClass('few-message'); } jq('div#talkTabContainer div.navigation div.size div.hiddennewmessage:first').html(countHiddenMessages); } newcontact.className = classname; newcontacttitle = ASC.TMTalk.dom.getElementsByClassName(newcontact, 'title', 'div'); ASC.TMTalk.dom.addClass(newcontacttitle[0], 'hiddenContactTitle'); newcontacttitle[0].title = titleHiddenTab[0].getAttribute('title'); newcontacttitle[0].innerHTML = titleHiddenTab[0].innerHTML; listHiddenTabs[0].appendChild(newcontact); } } }; $(window).resize(function () { var tablistContainer = document.getElementById('talkTabContainer'), nodes = null, lastTab = null, currentTab = null; nodes = ASC.TMTalk.dom.getElementsByClassName(tablistContainer, 'tab current', 'li'); if (nodes.length > 0) { currentTab = nodes[0]; } nodes = ASC.TMTalk.dom.getElementsByClassName(tablistContainer, 'tab', 'li'); if (nodes.length > 0) { lastTab = nodes[nodes.length - 1]; if (ASC.TMTalk.dom.hasClass(lastTab, 'default')) { lastTab = null; } if (nodes.length > 1) { ASC.TMTalk.dom.addClass(tablistContainer, 'overflow'); } else { ASC.TMTalk.dom.removeClass(tablistContainer, 'overflow'); } } // has hidden tabs if (lastTab && lastTab.offsetTop < lastTab.offsetHeight) { nodes = ASC.TMTalk.dom.getElementsByClassName(tablistContainer, 'tab hidden', 'li'); var nodesInd = nodes.length; while (nodesInd--) { ASC.TMTalk.dom.removeClass(nodes[nodesInd], 'hidden'); if (lastTab.offsetTop >= lastTab.offsetHeight) { ASC.TMTalk.dom.addClass(nodes[nodesInd], 'hidden'); break; } } } // if need to hide if (currentTab && currentTab.offsetTop >= currentTab.offsetHeight) { if (!ASC.TMTalk.dom.hasClass(currentTab, 'hidden')) { nodes = ASC.TMTalk.dom.getElementsByClassName(tablistContainer, 'tab', 'li'); for (var i = 0, n = nodes.length; i < n; i++) { ASC.TMTalk.dom.addClass(nodes[i], 'hidden'); if (currentTab.offsetTop < currentTab.offsetHeight) { for (var j = i + i; j < n; j++) { if (nodes[j].offsetTop >= nodes[j].offsetHeight && !ASC.TMTalk.dom.hasClass(nodes[j], 'hidden')) { ASC.TMTalk.dom.addClass(nodes[j], 'hidden'); } } break; } } } } else if (currentTab) { var allNodes = ASC.TMTalk.dom.getElementsByClassName(tablistContainer, 'tab', 'li'); for (var i = 0, n = allNodes.length; i < n; i++) { if (allNodes[i].offsetTop >= allNodes[i].offsetHeight && !ASC.TMTalk.dom.hasClass(allNodes[i], 'hidden')) { ASC.TMTalk.dom.addClass(allNodes[i], 'hidden'); } } } nodes = ASC.TMTalk.dom.getElementsByClassName(tablistContainer, 'tab hidden', 'li'); var hiddenLen = (nodes.length === 1 && ASC.TMTalk.dom.hasClass(nodes[0], 'default')) ? 0 : nodes.length; findHiddenTabs(tablistContainer); var hiddenTabs = ASC.TMTalk.dom.getElementsByClassName(tablistContainer, 'size', 'div'); var sizeHiddenTabs = hiddenTabs.length > 0 ? hiddenTabs[0] : null; if (sizeHiddenTabs !== null) { hiddenTabs = ASC.TMTalk.dom.getElementsByClassName(sizeHiddenTabs, 'all', 'span'); var num = hiddenLen !==0 ? hiddenLen-1:0; hiddenTabs[0].innerHTML = num; if (num <= 0) ASC.TMTalk.dom.addClass(sizeHiddenTabs, 'hidden'); else ASC.TMTalk.dom.removeClass(sizeHiddenTabs, 'hidden'); } if (hiddenLen > 0 || (lastTab && lastTab.offsetTop >= lastTab.offsetHeight)) { if (hiddenLen > 0) { ASC.TMTalk.dom.addClass(tablistContainer, 'has-hidden'); } else { ASC.TMTalk.dom.removeClass(tablistContainer, 'has-hidden'); } if (lastTab && lastTab.offsetTop >= lastTab.offsetHeight) { ASC.TMTalk.dom.addClass(tablistContainer, 'has-repressed'); } else { ASC.TMTalk.dom.removeClass(tablistContainer, 'has-repressed'); } } }); }); })(jQuery);
uw-it-cte/uw-restclients
restclients/test/uwnetid/subscription_60.py
<filename>restclients/test/uwnetid/subscription_60.py from django.test import TestCase from restclients.uwnetid.subscription_60 import is_current_staff,\ is_current_faculty, get_kerberos_subs, is_current_clinician from restclients.exceptions import DataFailureException from restclients.test import fdao_uwnetid_override @fdao_uwnetid_override class KerberosSubsTest(TestCase): def test_get_kerberos_subs_permits(self): self.assertTrue(is_current_staff("bill")) self.assertFalse(is_current_faculty("bill")) self.assertFalse(is_current_staff("phil")) self.assertTrue(is_current_faculty("phil")) self.assertTrue(is_current_clinician("james")) self.assertTrue(is_current_clinician("fred")) self.assertFalse(is_current_clinician("bill")) subs = get_kerberos_subs("bill") self.assertTrue(subs.is_status_active()) subs = get_kerberos_subs("phil") self.assertTrue(subs.is_status_active()) def test_unpermitted(self): subs = get_kerberos_subs("none") self.assertFalse(subs.is_status_active()) self.assertFalse(subs.is_status_inactive()) self.assertFalse(subs.permitted) def test_expiring_subs(self): subs = get_kerberos_subs("eight") self.assertTrue(subs.is_status_active()) self.assertFalse(subs.is_status_inactive()) self.assertFalse(subs.permitted) def test_invalid_user(self): #Testing error message in a 200 response self.assertRaises(DataFailureException, is_current_staff, "invalidnetid") #Testing non-200 response self.assertRaises(DataFailureException, is_current_faculty, "jnewstudent")
kxxcn/Squad
app/src/main/java/dev/kxxcn/app_squad/ui/main/match/MatchAdpater.java
<filename>app/src/main/java/dev/kxxcn/app_squad/ui/main/match/MatchAdpater.java package dev.kxxcn.app_squad.ui.main.match; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.support.annotation.NonNull; import android.support.v4.view.PagerAdapter; import android.support.v7.widget.CardView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.ImageView; import android.widget.RelativeLayout; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import butterknife.BindView; import butterknife.ButterKnife; import dev.kxxcn.app_squad.R; import dev.kxxcn.app_squad.util.AdapterUtils; import static dev.kxxcn.app_squad.util.AdapterUtils.setupItem; /** * Created by kxxcn on 2018-04-26. */ public class MatchAdpater extends PagerAdapter { private static final int MATCH = 0; private static final int RECRUITMENT = 1; private static final int PLAYER = 2; @BindView(R.id.rl_background) RelativeLayout mBackground; @BindView(R.id.cardView) CardView mCardView; @BindView(R.id.iv_match_card) ImageView iv_match_card; private Activity mActivity; private Context mContext; private LayoutInflater mLayoutInflater; private final AdapterUtils.LibraryObject[] LIBRARIES; private String[] mBackgroundColors; private String[] mHighlightColors; private int txtColor; private int[] imgs = {R.drawable.card_match, R.drawable.card_recruit, R.drawable.card_player}; public MatchAdpater(Activity activity, Context context) { mActivity = activity; mContext = context; mLayoutInflater = LayoutInflater.from(context); LIBRARIES = new AdapterUtils.LibraryObject[]{ new AdapterUtils.LibraryObject( R.drawable.stadium, context.getString(R.string.match_title_match) ), new AdapterUtils.LibraryObject( R.drawable.player, context.getString(R.string.match_title_recruitment) ), new AdapterUtils.LibraryObject( R.drawable.football, context.getString(R.string.match_title_player) ), }; mBackgroundColors = context.getResources().getStringArray(R.array.match_card_background); mHighlightColors = context.getResources().getStringArray(R.array.match_card_highlight); txtColor = context.getResources().getColor(R.color.match_font); } @Override public int getCount() { return LIBRARIES.length; } @Override public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { return view.equals(object); } @Override public int getItemPosition(@NonNull Object object) { return POSITION_NONE; } @Override @NonNull public Object instantiateItem(@NonNull ViewGroup container, final int position) { final View view = mLayoutInflater.inflate(R.layout.item_match, container, false); ButterKnife.bind(this, view); initUI(position); setupItem(view, LIBRARIES[position], txtColor); mCardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showRegistrationPage(position); } }); container.addView(view); return view; } @Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { container.removeView((View) object); } private void initUI(int position) { Glide.with(mContext).load(imgs[position]).diskCacheStrategy(DiskCacheStrategy.NONE).into(iv_match_card); } private void showRegistrationPage(int position) { MatchDialog dialog = new MatchDialog(mActivity, mContext, position, null); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); WindowManager.LayoutParams params = new WindowManager.LayoutParams(); params.copyFrom(dialog.getWindow().getAttributes()); params.width = WindowManager.LayoutParams.MATCH_PARENT; params.height = WindowManager.LayoutParams.MATCH_PARENT; dialog.show(); Window window = dialog.getWindow(); window.setAttributes(params); } }
mrkyle7/app-runner
src/test/java/com/danielflower/apprunner/runners/RustRunnerTest.java
<filename>src/test/java/com/danielflower/apprunner/runners/RustRunnerTest.java package com.danielflower.apprunner.runners; import org.apache.commons.io.output.StringBuilderWriter; import org.junit.BeforeClass; import org.junit.Test; import scaffolding.Photocopier; import java.util.Optional; import static com.danielflower.apprunner.runners.ProcessStarterTest.startAndStop; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assume.assumeTrue; import static scaffolding.TestConfig.config; public class RustRunnerTest { private static RustRunnerFactory runnerFactory; private StringBuilderWriter buildLog = new StringBuilderWriter(); private StringBuilderWriter consoleLog = new StringBuilderWriter(); @BeforeClass public static void ignoreTestIfNotSupported() throws Exception { Optional<RustRunnerFactory> runnerFactoryMaybe = RustRunnerFactory.createIfAvailable(config); assumeTrue("Skipping rust test because cargo not detected", runnerFactoryMaybe.isPresent()); runnerFactory = runnerFactoryMaybe.get(); } @Test public void canStartAndStopCargoProjects() throws Exception { // doing it twice proves the port was cleaned up run(1); run(2); } @Test public void theVersionIsReported() { assertThat(runnerFactory.versionInfo(), containsString("cargo")); } private void run(int attempt) throws Exception { String appName = "rust"; AppRunner runner = runnerFactory.appRunner(Photocopier.copySampleAppToTempDir(appName)); startAndStop(attempt, appName, runner, 45688, buildLog, consoleLog, containsString("Rust sample app is running"), containsString(" 0 failed")); } }
cccaaannn/homeworks
2-java/other/ProgrammingChallenge/ShoppingListProblem/src/com/can/ShoppingListProcessor.java
<filename>2-java/other/ProgrammingChallenge/ShoppingListProblem/src/com/can/ShoppingListProcessor.java package com.can; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; public class ShoppingListProcessor { boolean logErrors; RomanNumeralParser romanNumeralParser; ShoppingListProcessor(boolean logErrors) { this.logErrors = logErrors; this.romanNumeralParser = new RomanNumeralParser(); } private ArrayList<List<String>> readShoppingListFile(String inputTextPath) { /* Reads and cleans shopping list file. */ try (BufferedReader br = new BufferedReader(new FileReader(inputTextPath))) { ArrayList<List<String>> lines = new ArrayList<List<String>>(); String line; while ((line = br.readLine()) != null) { // Clean punctuation and spaces, convert to lowercase, split elements into List<String> List<String> cleanLine = Arrays.asList(line.replaceAll("\\p{Punct}", "").strip().toLowerCase().split("\\s+")); lines.add(cleanLine); } return lines; } catch (IOException e) { e.printStackTrace(); } return null; } private HashMap<String, Integer> solveShoppingListEquation(List<String> shoppingEquation, HashMap<String, Integer> knownVariables) throws ShoppingListEquationException, IllegalArgumentException { /* Tries to solve a shoppingEquation, by subtracting leftSum from equRight to find the unknown. shoppingEquations has to have one unknown otherwise we can not solve them so the function throws a ShoppingListEquationException if there are more than one unknown */ // check if question has 'is' in it int locationOfIs = shoppingEquation.indexOf("is"); if(locationOfIs == -1){ throw new IllegalArgumentException("This line does not contains 'is' '" + shoppingEquation + "', skipping this line..."); } List<String> equLeft = shoppingEquation.subList(0, locationOfIs); String equRightRoman = shoppingEquation.get(shoppingEquation.size() - 1); int equRight; try { // try to convert int first equRight = Integer.valueOf(equRightRoman); } catch (NumberFormatException e) { // try roman numeral conversion if (!equRightRoman.equals("") && this.romanNumeralParser.isConvertible(equRightRoman)) { equRight = this.romanNumeralParser.toDecimal(equRightRoman); } else { throw new IllegalArgumentException("Can not convert token '" + equRightRoman + "' roman to decimal, skipping this line..."); } } // finding the solution String unkown = ""; int leftSum = 0; for (String variable : equLeft) { if (knownVariables.containsKey(variable)) { leftSum += knownVariables.get(variable); } else if (unkown.equals("")) { unkown = variable; } // if there are more than one unknown we can't solve this else { throw new ShoppingListEquationException("There are more than one unknown"); } } int solution = equRight - leftSum; // check if all the values in the equation are known if(!unkown.equals("")){ knownVariables.put(unkown, solution); } return knownVariables; } private void printAnswerList(List question, int sum) { /* Prints the answer formatted as required ex: tomato potato strawberry is 140 */ for (var element : question) { System.out.print(element + " "); } System.out.print("is " + sum + "\n"); } private void answerQuestions(ArrayList<List<String>> questions, HashMap<String, Integer> shoppingItems) { /* Iterates over given questions, tries to find prices of the items on the shoppingItems If finds a price increases the sum else displays error message */ System.out.println("ANSWERS"); for (List<String> question : questions) { int sum = 0; String unknownValue = ""; for (String questionElement : question) { if (shoppingItems.containsKey(questionElement)) { sum += shoppingItems.get(questionElement); } else { unknownValue = questionElement; break; } } if (unknownValue.equals("")) { printAnswerList(question, sum); } else { if(this.logErrors) System.out.println("invalid input, value of '" + unknownValue + "' is unknown"); } } } public void process(String inputTextPath) { /* Processes the given text with these steps 1- reads the file 2- iterates the lines while separating them for different precesses 3- tries to solve equation lines 4- answers questions */ ArrayList<List<String>> questions = new ArrayList<List<String>>(); // ex:[["tomato", "potato", "strawberry"], [...]] ArrayList<List<String>> equations = new ArrayList<List<String>>(); // ex: [["potato", "carrot", "strawberry", "is", "102"], [...]] HashMap<String, Integer> shoppingItems = new HashMap<String, Integer>(); // ex: {"apple": 3, "melon": 1} // read the file ArrayList<List<String>> textLines = this.readShoppingListFile(inputTextPath); // Check if text exists if(textLines == null){ System.out.println("There is a problem on the file on the path " + inputTextPath); return; } // Iterate over the input text line by line for (List<String> line : textLines) { // this line is a variable like if (line.size() == 3 && line.get(1).equals("is")) { String romanVal = line.get(2); int decimalVal; // try converting int first try{ decimalVal = Integer.valueOf(romanVal); shoppingItems.put(line.get(0), decimalVal); // apple is 6 } catch (NumberFormatException e){ // roman numeral conversion if(!romanVal.equals("") && this.romanNumeralParser.isConvertible(romanVal)){ decimalVal = this.romanNumeralParser.toDecimal(romanVal); shoppingItems.put(line.get(0), decimalVal); // apple is IV } else{ if(this.logErrors) System.out.println("Roman number is formatted wrong '" + romanVal + "' is not convertible from roman to decimal, skipping this line..."); } } } // this line is a question else if (line.get(0).equals("what")) { // ex: [what, is, the, price, of, tomato, peach, apple, carrot] returns [tomato, peach, apple, carrot] questions.add(line.subList(line.indexOf("of") + 1, line.size())); } // this line is equation like else { equations.add(line); } } // if equation order is not allow us to solve some of them on the first try, this loop will try to solve all of it until there is no progress. int oldLen = 0; do { System.out.println(); oldLen = shoppingItems.size(); // iterate over equations, try to solve them for (List equation : equations) { try { shoppingItems = this.solveShoppingListEquation(equation, shoppingItems); } catch (ShoppingListEquationException e) { if(this.logErrors) System.out.println("Can not solve " + equation + " I might try it again after other ones solved."); } catch (IllegalArgumentException e){ if(this.logErrors) System.out.println(e.getMessage()); } } }while (shoppingItems.size() > oldLen); // answer the questions System.out.println(); this.answerQuestions(questions, shoppingItems); } }
peZhmanParsaee/js-design-patterns
decorator/level-db-decorator/run.js
const level = require("level"); const levelSubscribe = require("./levelSubscribe"); var db = level(__dirname + "/db", { valueEncoding: "json" }); db = levelSubscribe(db); db.subscribe({ doctype: "tweet", language: "en" }, function (k, val) { console.log(val); }); db.put(1, { doctype: "tweet", text: "hi", language: "en" }); db.put(2, { doctype: "company", name: "Microsoft" });
leongold/ovirt-engine
backend/manager/modules/common/src/main/java/org/ovirt/engine/core/common/queries/GetJobsByCorrelationIdQueryParameters.java
package org.ovirt.engine.core.common.queries; public class GetJobsByCorrelationIdQueryParameters extends VdcQueryParametersBase { private static final long serialVersionUID = 758029173419093849L; private String correlationId; public void setCorrelationId(String correlationId) { this.correlationId = correlationId; } public String getCorrelationId() { return correlationId; } }
MacBry/StowarzyszenieNaukiJavy
MacBry-Maciej-Bryja/SimpleTodoApp1/src/main/java/com/mac/bry/simpleTodo/appController/MainController.java
<reponame>MacBry/StowarzyszenieNaukiJavy package com.mac.bry.simpleTodo.appController; import java.nio.charset.Charset; import java.util.Random; import com.mac.bry.simpleTodo.DAO.UserDAO; import com.mac.bry.simpleTodo.Enums.LoginOption; import com.mac.bry.simpleTodo.entity.User; import com.mac.bry.simpleTodo.utilitis.DataReader; import com.mac.bry.simpleTodo.utilitis.EmailSender; import com.mac.bry.simpleTodo.utilitis.PasswordUtillity; public class MainController { private DataReader dataReader; private UserDAO userDAO; private TaskController taskController; private User loggedUser; public MainController() { super(); this.dataReader = new DataReader(); this.userDAO = new UserDAO(); this.taskController = new TaskController(); } public void programLoop() { LoginOption option; printLoginOptions(); while ((option = LoginOption.createFromInt(dataReader.readNumber())) != LoginOption.EXIT) { switch (option) { case LOGIN: if(login()) {; taskController.taskLoop(); } else { System.out.println("Try again"); login(); } break; case REGISTR: registr(); break; case PASSWORD_RESET: resetPassword(); break; default: System.err.println("\nNo such option"); programLoop(); break; } } } private void resetPassword() { String newPassword = dataReader.generateRandomString(); String tempMail = dataReader.readString(" your email"); EmailSender.configureEmail(tempMail, newPassword); newPassword = PasswordUtillity.getHashedPassword(newPassword); userDAO.editUserPassword(userDAO.findUserByLogin(dataReader.readString("Login")), newPassword); } private void printLoginOptions() { System.out.println("Chose Option: "); for (LoginOption option : LoginOption.values()) { System.out.println(option); } } private boolean login () { User tempUser = dataReader.readUser(); this.loggedUser = userDAO.findUserByLogin(tempUser.getLogin()); taskController.setLoggedUser(this.loggedUser); return userDAO.login(tempUser); } private void registr () { userDAO.addUser(dataReader.readAndCreateUser()); programLoop(); } }
6days9weeks/Novus
discord/ext/vbu/web/utils/oauth_models.py
import typing import discord class OauthGuild(object): """ A guild object from an oauth integration. Attributes: id (int): The ID of the guild. name (str): The name of the guild. icon (discord.Asset): The guild's icon. owner_id (int): The ID of the owner for the guild. This will either be the ID of the authenticated user or `0`. features (typing.List[str]): A list of features that the guild has.sa """ def __init__(self, bot, guild_data, user): self.id: int = int(guild_data.get("id")) self.name: str = guild_data.get("name") self._icon: typing.Optional[str] = guild_data.get("icon") self.owner_id: int = user.id if guild_data.get("owner") else 0 self.features: typing.List[str] = guild_data.get("features") self._bot: discord.Client = bot @property def icon(self) -> typing.Optional[discord.Asset]: """Optional[:class:`Asset`]: Returns the guild's icon asset, if available.""" if self._icon is None: return None return discord.Asset._from_guild_icon(None, self.id, self._icon) async def fetch_guild(self, bot=None) -> typing.Optional[discord.Guild]: """ Fetch the original :class:`discord.Guild` object from the API using the authentication from the bot given. Args: bot: The bot object that you want to use to fetch the guild. Returns: typing.Optional[discord.Guild]: The guild instance. """ bot = bot or self._bot try: return await bot.fetch_guild(self.id) except discord.HTTPException: return None class OauthUser(object): """ A user object from an oauth integration. Attributes: id (int): The ID of the user. username (str): The user's username. avatar (discord.Asset): The user's avatar asset. discriminator (str): The user's discrimiator. public_flags (discord.PublicUserFlags): The user's public flags. locale (str): The locale of the user. mfa_enabled (bool): Whether or not the user has MFA enabled. """ def __init__(self, user_data): self.id: int = int(user_data['id']) self.username: str = user_data.get("username") self._avatar: str = user_data.get("avatar") self.discriminator: str = user_data.get("discriminator") self.public_flags: discord.PublicUserFlags = discord.PublicUserFlags._from_value(user_data.get("public_flags", 0)) self.locale: str = user_data.get("locale") self.mfa_enabled: bool = user_data.get("mfa_enabled", False) @property def avatar(self) -> typing.Optional[discord.Asset]: """Optional[:class:`Asset`]: Returns the guild's icon asset, if available.""" if self._avatar is None: return None return discord.Asset._from_avatar(None, self.id, self._avatar) class OauthMember(OauthUser): """ A user object from an oauth integration. Attributes: id (int): The ID of the user. username (str): The user's username. avatar (str): The user's avatar hash. avatar_url (discord.Asset): The user's avatar. discriminator (str): The user's discrimiator. public_flags (discord.PublicUserFlags): The user's public flags. locale (str): The locale of the user. mfa_enabled (bool): Whether or not the user has MFA enabled. guild (OauthGuild): The guild object that this member is a part of. guild_permissions (discord.Permissions): The permissions that this member has on the guild. """ def __init__(self, bot, guild_data, user_data): super().__init__(user_data) self.guild: OauthGuild = OauthGuild(bot, guild_data, self) self.guild_permissions: discord.Permissions = discord.Permissions(guild_data['permissions'])
ishiura-compiler/CF3
testsuite/EXP_3/test554.c
<filename>testsuite/EXP_3/test554.c /* CF3 Copyright (c) 2015 ishiura-lab. Released under the MIT license. https://github.com/ishiura-compiler/CF3/MIT-LICENSE.md */ #include<stdio.h> #include<stdint.h> #include<stdlib.h> #include"test1.h" int64_t x1 = 24330344757235LL; int32_t t0 = -15125; volatile int32_t x9 = INT32_MAX; int16_t x14 = -1; int64_t x16 = -1LL; uint16_t x28 = UINT16_MAX; static int8_t x29 = 3; int32_t x30 = 3470599; int8_t x31 = INT8_MAX; int32_t x37 = -290; volatile int32_t t8 = -1409026; int32_t t10 = 379791958; uint8_t x63 = UINT8_MAX; uint8_t x64 = 14U; int16_t x67 = INT16_MAX; static int16_t x68 = INT16_MAX; volatile int32_t t15 = 213; volatile int64_t x95 = INT64_MIN; static volatile int32_t t18 = -50527139; volatile int16_t x105 = INT16_MAX; int32_t x112 = 0; int64_t x118 = -1LL; uint32_t x119 = 1U; int16_t x130 = INT16_MAX; int32_t x141 = INT32_MIN; int8_t x143 = INT8_MAX; int32_t t26 = -2783633; int32_t x145 = INT32_MIN; int8_t x147 = INT8_MAX; static int32_t x150 = INT32_MIN; static uint16_t x151 = 26U; static volatile int8_t x157 = 0; static uint64_t x169 = 196885614LLU; volatile uint16_t x172 = 6U; volatile int32_t t32 = 1; int32_t x182 = -11; static int32_t t34 = -316; volatile int32_t x186 = -1; volatile uint16_t x191 = UINT16_MAX; volatile int32_t t39 = -2445122; int64_t x230 = INT64_MIN; int8_t x231 = -1; uint64_t x232 = 27439LLU; volatile int32_t t46 = -257683768; int32_t t47 = -79541074; int32_t x252 = 225711; int16_t x288 = -1; volatile int16_t x290 = -237; int64_t x296 = INT64_MAX; volatile int32_t t56 = -475; uint64_t x303 = 446LLU; int64_t x306 = INT64_MIN; uint16_t x310 = 109U; int32_t x313 = -1; int32_t t62 = -3177; volatile int64_t x326 = INT64_MIN; int64_t x327 = 275743494633425LL; int16_t x328 = 1114; static int32_t x345 = INT32_MIN; int32_t t68 = 33473; uint64_t x363 = 270309LLU; static uint64_t x364 = 4230LLU; static volatile int32_t t69 = -542; int64_t x369 = INT64_MIN; uint8_t x387 = 70U; volatile int8_t x390 = 0; int32_t x392 = -1; int32_t t76 = -220112; static int32_t t79 = 38433; static uint16_t x411 = 25U; static int8_t x413 = -1; int16_t x419 = -1; uint32_t x438 = 1454599U; volatile int8_t x442 = 11; uint32_t x446 = UINT32_MAX; volatile int32_t t87 = 98510743; static int8_t x457 = -1; int32_t x458 = 25783255; volatile int8_t x459 = 1; int64_t x465 = -1LL; int8_t x467 = 0; uint8_t x468 = 0U; volatile int32_t t91 = -133304480; int16_t x469 = 195; int8_t x470 = 3; volatile int32_t t92 = 788527250; volatile int32_t t93 = -12; int64_t x482 = INT64_MAX; uint64_t x485 = 1LLU; volatile int32_t t95 = 25; volatile uint32_t x507 = 651U; volatile int16_t x508 = INT16_MIN; int32_t x512 = 27302; int16_t x513 = 1; int64_t x514 = INT64_MAX; static uint8_t x516 = 121U; static int16_t x519 = 10; int64_t x521 = INT64_MIN; int32_t t103 = 29871; int16_t x531 = -1; int32_t t106 = 193093; int64_t x542 = INT64_MIN; volatile int32_t t107 = 23908807; int16_t x545 = 867; static volatile int32_t t108 = -247082511; int8_t x549 = INT8_MAX; static int64_t x551 = -521160664303LL; uint8_t x552 = UINT8_MAX; volatile int32_t t109 = 1; int8_t x561 = -1; int32_t x572 = 3195; int32_t x574 = INT32_MIN; volatile uint16_t x588 = 0U; int64_t x593 = INT64_MIN; volatile int16_t x595 = INT16_MAX; volatile uint64_t x608 = 0LLU; int8_t x622 = -3; uint64_t x629 = 6622124LLU; static int8_t x633 = INT8_MIN; static uint16_t x636 = UINT16_MAX; static uint64_t x637 = UINT64_MAX; uint64_t x649 = 7870356879LLU; uint16_t x651 = UINT16_MAX; static int32_t t128 = 233; int16_t x654 = INT16_MAX; int32_t x660 = -3; int32_t x663 = 1; int8_t x671 = INT8_MAX; volatile int16_t x673 = INT16_MAX; volatile int8_t x675 = INT8_MIN; int32_t t133 = 0; static uint64_t x678 = 38LLU; int16_t x680 = INT16_MAX; uint32_t x686 = 2184U; int32_t t135 = -176969913; volatile int32_t x705 = -746; uint32_t x722 = UINT32_MAX; int16_t x738 = 127; volatile int16_t x739 = 8741; static int32_t t145 = 205; int16_t x757 = -411; static uint32_t x759 = 4U; int8_t x762 = INT8_MIN; int64_t x783 = -1LL; volatile uint16_t x791 = 121U; int32_t x796 = -1; int16_t x800 = INT16_MAX; volatile int32_t t153 = 1138; uint16_t x802 = UINT16_MAX; static volatile int64_t x804 = -1LL; volatile int32_t x810 = -116; int8_t x816 = -1; int32_t x817 = INT32_MAX; uint16_t x821 = UINT16_MAX; uint16_t x824 = UINT16_MAX; uint32_t x827 = 22983138U; volatile int32_t t160 = -107293; int8_t x829 = 0; static volatile int32_t x831 = INT32_MIN; uint32_t x832 = 2U; int32_t t161 = 887; int64_t x834 = INT64_MAX; int64_t x835 = INT64_MIN; volatile int32_t t163 = 526550624; int32_t x853 = INT32_MAX; int32_t x855 = INT32_MIN; volatile int16_t x867 = INT16_MAX; int32_t t168 = -50; uint64_t x892 = UINT64_MAX; static uint64_t x895 = 134212438066760920LLU; int16_t x909 = INT16_MAX; static volatile int32_t x912 = 2953; int32_t t172 = -38; int8_t x917 = 11; int16_t x930 = INT16_MIN; uint8_t x931 = 50U; static uint32_t x937 = UINT32_MAX; volatile uint32_t x940 = UINT32_MAX; uint8_t x964 = 10U; volatile int32_t t179 = 81175152; int64_t x966 = -30106796LL; int16_t x971 = INT16_MIN; volatile int64_t x976 = -47LL; static uint8_t x979 = 0U; uint8_t x980 = 95U; volatile int32_t t183 = -263; static uint8_t x991 = 11U; static uint32_t x996 = 19247338U; volatile int32_t t187 = -61841359; static uint16_t x1014 = 1940U; volatile int32_t t190 = -14137971; static int32_t x1017 = INT32_MIN; int16_t x1021 = -5; uint32_t x1022 = 1461U; volatile int32_t t192 = -49; int8_t x1028 = INT8_MIN; uint8_t x1031 = 0U; uint32_t x1032 = UINT32_MAX; static int16_t x1037 = INT16_MIN; volatile uint16_t x1041 = UINT16_MAX; int8_t x1052 = INT8_MAX; void f0(void) { volatile uint64_t x2 = UINT64_MAX; uint64_t x3 = UINT64_MAX; static int8_t x4 = 10; t0 = ((x1&x2)==(x3*x4)); if (t0 != 0) { NG(); } else { ; } } void f1(void) { uint16_t x5 = 73U; static int16_t x6 = -1; uint16_t x7 = 4417U; int16_t x8 = 1961; int32_t t1 = 1563245; t1 = ((x5&x6)==(x7*x8)); if (t1 != 0) { NG(); } else { ; } } void f2(void) { volatile int64_t x10 = INT64_MIN; static volatile int64_t x11 = 21LL; static uint8_t x12 = 9U; int32_t t2 = 175795; t2 = ((x9&x10)==(x11*x12)); if (t2 != 0) { NG(); } else { ; } } void f3(void) { int64_t x13 = INT64_MAX; int16_t x15 = -17; int32_t t3 = -10574; t3 = ((x13&x14)==(x15*x16)); if (t3 != 0) { NG(); } else { ; } } void f4(void) { volatile int64_t x17 = INT64_MIN; uint16_t x18 = 13U; uint16_t x19 = UINT16_MAX; uint8_t x20 = 2U; volatile int32_t t4 = -14933; t4 = ((x17&x18)==(x19*x20)); if (t4 != 0) { NG(); } else { ; } } void f5(void) { int32_t x25 = INT32_MIN; volatile uint8_t x26 = 0U; uint8_t x27 = 83U; volatile int32_t t5 = -908377737; t5 = ((x25&x26)==(x27*x28)); if (t5 != 0) { NG(); } else { ; } } void f6(void) { int32_t x32 = 8583917; volatile int32_t t6 = -7806; t6 = ((x29&x30)==(x31*x32)); if (t6 != 0) { NG(); } else { ; } } void f7(void) { volatile int32_t x33 = -12864409; static int32_t x34 = INT32_MAX; int8_t x35 = -2; uint8_t x36 = 29U; static int32_t t7 = -489; t7 = ((x33&x34)==(x35*x36)); if (t7 != 0) { NG(); } else { ; } } void f8(void) { int64_t x38 = -11LL; int32_t x39 = 90859306; uint32_t x40 = 341006809U; t8 = ((x37&x38)==(x39*x40)); if (t8 != 0) { NG(); } else { ; } } void f9(void) { volatile int32_t x41 = -91099; int64_t x42 = INT64_MAX; int16_t x43 = INT16_MIN; static volatile int32_t x44 = -1; static volatile int32_t t9 = -53617679; t9 = ((x41&x42)==(x43*x44)); if (t9 != 0) { NG(); } else { ; } } void f10(void) { uint64_t x45 = 56LLU; int32_t x46 = INT32_MIN; static volatile uint8_t x47 = 45U; static volatile uint64_t x48 = UINT64_MAX; t10 = ((x45&x46)==(x47*x48)); if (t10 != 0) { NG(); } else { ; } } void f11(void) { int32_t x57 = INT32_MAX; int64_t x58 = -68400033LL; volatile uint64_t x59 = UINT64_MAX; volatile int32_t x60 = INT32_MIN; int32_t t11 = 0; t11 = ((x57&x58)==(x59*x60)); if (t11 != 0) { NG(); } else { ; } } void f12(void) { int32_t x61 = INT32_MIN; static volatile uint32_t x62 = 213402U; static volatile int32_t t12 = 34257; t12 = ((x61&x62)==(x63*x64)); if (t12 != 0) { NG(); } else { ; } } void f13(void) { volatile int16_t x65 = -695; volatile uint8_t x66 = 1U; int32_t t13 = -74536936; t13 = ((x65&x66)==(x67*x68)); if (t13 != 0) { NG(); } else { ; } } void f14(void) { static uint32_t x73 = UINT32_MAX; volatile int8_t x74 = INT8_MAX; static uint64_t x75 = UINT64_MAX; uint32_t x76 = 1365092170U; volatile int32_t t14 = 1; t14 = ((x73&x74)==(x75*x76)); if (t14 != 0) { NG(); } else { ; } } void f15(void) { static int32_t x81 = 415; int64_t x82 = 61511LL; uint16_t x83 = 3U; volatile int8_t x84 = INT8_MIN; t15 = ((x81&x82)==(x83*x84)); if (t15 != 0) { NG(); } else { ; } } void f16(void) { static int32_t x89 = INT32_MAX; int64_t x90 = INT64_MAX; int16_t x91 = -1; volatile int8_t x92 = 10; int32_t t16 = 179; t16 = ((x89&x90)==(x91*x92)); if (t16 != 0) { NG(); } else { ; } } void f17(void) { uint16_t x93 = UINT16_MAX; uint32_t x94 = 575U; volatile int16_t x96 = 1; volatile int32_t t17 = 0; t17 = ((x93&x94)==(x95*x96)); if (t17 != 0) { NG(); } else { ; } } void f18(void) { int64_t x97 = -1LL; int32_t x98 = -1; volatile uint8_t x99 = 1U; int32_t x100 = -942172034; t18 = ((x97&x98)==(x99*x100)); if (t18 != 0) { NG(); } else { ; } } void f19(void) { volatile int16_t x101 = INT16_MIN; int16_t x102 = -1; volatile uint64_t x103 = 52LLU; volatile int16_t x104 = INT16_MIN; static volatile int32_t t19 = 645; t19 = ((x101&x102)==(x103*x104)); if (t19 != 0) { NG(); } else { ; } } void f20(void) { int32_t x106 = INT32_MIN; int16_t x107 = INT16_MIN; int64_t x108 = 40563601214LL; volatile int32_t t20 = 3279537; t20 = ((x105&x106)==(x107*x108)); if (t20 != 0) { NG(); } else { ; } } void f21(void) { volatile uint32_t x109 = 2751350U; uint16_t x110 = UINT16_MAX; static uint8_t x111 = 3U; int32_t t21 = 1647495; t21 = ((x109&x110)==(x111*x112)); if (t21 != 0) { NG(); } else { ; } } void f22(void) { int16_t x113 = 112; int16_t x114 = -1; int8_t x115 = INT8_MIN; static int32_t x116 = -1; volatile int32_t t22 = -21421; t22 = ((x113&x114)==(x115*x116)); if (t22 != 0) { NG(); } else { ; } } void f23(void) { int32_t x117 = INT32_MIN; int32_t x120 = INT32_MIN; volatile int32_t t23 = -7; t23 = ((x117&x118)==(x119*x120)); if (t23 != 0) { NG(); } else { ; } } void f24(void) { static int64_t x129 = INT64_MIN; volatile int8_t x131 = -17; int16_t x132 = 0; int32_t t24 = -593; t24 = ((x129&x130)==(x131*x132)); if (t24 != 1) { NG(); } else { ; } } void f25(void) { int8_t x137 = INT8_MIN; volatile int8_t x138 = INT8_MIN; int8_t x139 = INT8_MAX; uint8_t x140 = 1U; int32_t t25 = 61; t25 = ((x137&x138)==(x139*x140)); if (t25 != 0) { NG(); } else { ; } } void f26(void) { int8_t x142 = 7; int16_t x144 = -844; t26 = ((x141&x142)==(x143*x144)); if (t26 != 0) { NG(); } else { ; } } void f27(void) { int64_t x146 = INT64_MIN; uint64_t x148 = UINT64_MAX; volatile int32_t t27 = -234; t27 = ((x145&x146)==(x147*x148)); if (t27 != 0) { NG(); } else { ; } } void f28(void) { int16_t x149 = INT16_MIN; int16_t x152 = INT16_MIN; static volatile int32_t t28 = 23936; t28 = ((x149&x150)==(x151*x152)); if (t28 != 0) { NG(); } else { ; } } void f29(void) { uint64_t x153 = 922LLU; int64_t x154 = INT64_MIN; int64_t x155 = -28494LL; volatile int8_t x156 = -1; volatile int32_t t29 = -61; t29 = ((x153&x154)==(x155*x156)); if (t29 != 0) { NG(); } else { ; } } void f30(void) { volatile int64_t x158 = INT64_MAX; int16_t x159 = -3062; int8_t x160 = INT8_MIN; int32_t t30 = -213; t30 = ((x157&x158)==(x159*x160)); if (t30 != 0) { NG(); } else { ; } } void f31(void) { volatile int64_t x165 = INT64_MIN; int16_t x166 = INT16_MAX; int8_t x167 = INT8_MIN; int32_t x168 = -1; volatile int32_t t31 = 37141; t31 = ((x165&x166)==(x167*x168)); if (t31 != 0) { NG(); } else { ; } } void f32(void) { volatile uint64_t x170 = 3410704999142LLU; int16_t x171 = -196; t32 = ((x169&x170)==(x171*x172)); if (t32 != 0) { NG(); } else { ; } } void f33(void) { static int8_t x177 = -1; int16_t x178 = INT16_MIN; int32_t x179 = -1; volatile int16_t x180 = INT16_MIN; static volatile int32_t t33 = 1292; t33 = ((x177&x178)==(x179*x180)); if (t33 != 0) { NG(); } else { ; } } void f34(void) { int16_t x181 = INT16_MIN; int16_t x183 = INT16_MAX; static int16_t x184 = 1; t34 = ((x181&x182)==(x183*x184)); if (t34 != 0) { NG(); } else { ; } } void f35(void) { static int32_t x185 = INT32_MIN; int64_t x187 = -79061LL; int32_t x188 = 1928; static int32_t t35 = -52005049; t35 = ((x185&x186)==(x187*x188)); if (t35 != 0) { NG(); } else { ; } } void f36(void) { uint8_t x189 = UINT8_MAX; int64_t x190 = -1LL; int32_t x192 = -189; static int32_t t36 = 103772531; t36 = ((x189&x190)==(x191*x192)); if (t36 != 0) { NG(); } else { ; } } void f37(void) { volatile uint16_t x193 = UINT16_MAX; int16_t x194 = INT16_MIN; int64_t x195 = 3263513452484108051LL; uint64_t x196 = UINT64_MAX; volatile int32_t t37 = -536; t37 = ((x193&x194)==(x195*x196)); if (t37 != 0) { NG(); } else { ; } } void f38(void) { int32_t x197 = INT32_MAX; int8_t x198 = -1; volatile int16_t x199 = INT16_MIN; volatile int8_t x200 = INT8_MAX; int32_t t38 = -15; t38 = ((x197&x198)==(x199*x200)); if (t38 != 0) { NG(); } else { ; } } void f39(void) { int8_t x205 = INT8_MAX; int32_t x206 = INT32_MIN; int8_t x207 = -1; int16_t x208 = INT16_MAX; t39 = ((x205&x206)==(x207*x208)); if (t39 != 0) { NG(); } else { ; } } void f40(void) { int16_t x209 = INT16_MIN; static volatile int8_t x210 = -1; static int16_t x211 = INT16_MIN; int16_t x212 = 79; int32_t t40 = 343383221; t40 = ((x209&x210)==(x211*x212)); if (t40 != 0) { NG(); } else { ; } } void f41(void) { int8_t x213 = 16; uint64_t x214 = UINT64_MAX; uint16_t x215 = UINT16_MAX; uint64_t x216 = UINT64_MAX; static volatile int32_t t41 = 2195080; t41 = ((x213&x214)==(x215*x216)); if (t41 != 0) { NG(); } else { ; } } void f42(void) { int16_t x217 = 4749; volatile uint64_t x218 = 50588LLU; int8_t x219 = -1; int64_t x220 = 71LL; static volatile int32_t t42 = -30404215; t42 = ((x217&x218)==(x219*x220)); if (t42 != 0) { NG(); } else { ; } } void f43(void) { volatile uint64_t x221 = 101334343355517LLU; uint16_t x222 = 17U; int16_t x223 = INT16_MIN; uint64_t x224 = 5LLU; volatile int32_t t43 = 659275; t43 = ((x221&x222)==(x223*x224)); if (t43 != 0) { NG(); } else { ; } } void f44(void) { int16_t x225 = -1; int16_t x226 = INT16_MIN; volatile uint16_t x227 = 456U; uint32_t x228 = 47U; static volatile int32_t t44 = 1082630; t44 = ((x225&x226)==(x227*x228)); if (t44 != 0) { NG(); } else { ; } } void f45(void) { volatile int64_t x229 = INT64_MIN; static volatile int32_t t45 = -1504; t45 = ((x229&x230)==(x231*x232)); if (t45 != 0) { NG(); } else { ; } } void f46(void) { int8_t x233 = -1; int8_t x234 = INT8_MAX; int64_t x235 = 2LL; uint8_t x236 = 115U; t46 = ((x233&x234)==(x235*x236)); if (t46 != 0) { NG(); } else { ; } } void f47(void) { int32_t x241 = INT32_MIN; volatile uint64_t x242 = 15887772LLU; volatile int16_t x243 = 9; uint16_t x244 = 47U; t47 = ((x241&x242)==(x243*x244)); if (t47 != 0) { NG(); } else { ; } } void f48(void) { int16_t x245 = INT16_MAX; uint16_t x246 = 478U; int64_t x247 = 1119LL; volatile int32_t x248 = INT32_MAX; volatile int32_t t48 = 3841562; t48 = ((x245&x246)==(x247*x248)); if (t48 != 0) { NG(); } else { ; } } void f49(void) { int32_t x249 = -86; int16_t x250 = -1; uint64_t x251 = 62322096228886LLU; static int32_t t49 = -1438; t49 = ((x249&x250)==(x251*x252)); if (t49 != 0) { NG(); } else { ; } } void f50(void) { int32_t x253 = INT32_MAX; int8_t x254 = INT8_MIN; static int8_t x255 = -1; uint64_t x256 = UINT64_MAX; volatile int32_t t50 = 167289; t50 = ((x253&x254)==(x255*x256)); if (t50 != 0) { NG(); } else { ; } } void f51(void) { uint8_t x257 = UINT8_MAX; int16_t x258 = INT16_MIN; int16_t x259 = INT16_MIN; int16_t x260 = -9; static int32_t t51 = -98826835; t51 = ((x257&x258)==(x259*x260)); if (t51 != 0) { NG(); } else { ; } } void f52(void) { uint64_t x265 = 24337272827518288LLU; static volatile int64_t x266 = INT64_MAX; int8_t x267 = -59; int8_t x268 = -3; int32_t t52 = -5812; t52 = ((x265&x266)==(x267*x268)); if (t52 != 0) { NG(); } else { ; } } void f53(void) { static uint8_t x281 = 122U; int8_t x282 = INT8_MAX; static volatile int8_t x283 = INT8_MIN; int8_t x284 = -1; volatile int32_t t53 = 14417174; t53 = ((x281&x282)==(x283*x284)); if (t53 != 0) { NG(); } else { ; } } void f54(void) { volatile int64_t x285 = 319093492186439350LL; volatile uint16_t x286 = UINT16_MAX; volatile int16_t x287 = INT16_MIN; volatile int32_t t54 = -1; t54 = ((x285&x286)==(x287*x288)); if (t54 != 0) { NG(); } else { ; } } void f55(void) { int64_t x289 = -1LL; int16_t x291 = -1; int8_t x292 = 3; static volatile int32_t t55 = 5; t55 = ((x289&x290)==(x291*x292)); if (t55 != 0) { NG(); } else { ; } } void f56(void) { int8_t x293 = INT8_MIN; volatile int64_t x294 = INT64_MAX; static uint64_t x295 = UINT64_MAX; t56 = ((x293&x294)==(x295*x296)); if (t56 != 0) { NG(); } else { ; } } void f57(void) { int64_t x297 = -61837163824158595LL; int8_t x298 = INT8_MIN; uint32_t x299 = 102407U; static volatile int16_t x300 = INT16_MAX; int32_t t57 = -3; t57 = ((x297&x298)==(x299*x300)); if (t57 != 0) { NG(); } else { ; } } void f58(void) { int32_t x301 = -1; uint64_t x302 = 2533LLU; int16_t x304 = INT16_MIN; int32_t t58 = -2; t58 = ((x301&x302)==(x303*x304)); if (t58 != 0) { NG(); } else { ; } } void f59(void) { uint8_t x305 = UINT8_MAX; int8_t x307 = INT8_MIN; int8_t x308 = 1; int32_t t59 = -126; t59 = ((x305&x306)==(x307*x308)); if (t59 != 0) { NG(); } else { ; } } void f60(void) { volatile int32_t x309 = INT32_MIN; int64_t x311 = -3756665152094LL; int32_t x312 = -1; int32_t t60 = 238684269; t60 = ((x309&x310)==(x311*x312)); if (t60 != 0) { NG(); } else { ; } } void f61(void) { int8_t x314 = INT8_MAX; int16_t x315 = -3680; static int64_t x316 = 5808816933142LL; volatile int32_t t61 = -62; t61 = ((x313&x314)==(x315*x316)); if (t61 != 0) { NG(); } else { ; } } void f62(void) { volatile int16_t x321 = 57; int64_t x322 = INT64_MAX; uint8_t x323 = UINT8_MAX; int32_t x324 = -1; t62 = ((x321&x322)==(x323*x324)); if (t62 != 0) { NG(); } else { ; } } void f63(void) { int8_t x325 = -6; int32_t t63 = 39066; t63 = ((x325&x326)==(x327*x328)); if (t63 != 0) { NG(); } else { ; } } void f64(void) { static int8_t x329 = 7; int16_t x330 = -1; volatile int16_t x331 = INT16_MIN; static uint64_t x332 = UINT64_MAX; volatile int32_t t64 = -29; t64 = ((x329&x330)==(x331*x332)); if (t64 != 0) { NG(); } else { ; } } void f65(void) { int8_t x337 = INT8_MIN; int16_t x338 = -1; static uint8_t x339 = 37U; int16_t x340 = -999; volatile int32_t t65 = 27028; t65 = ((x337&x338)==(x339*x340)); if (t65 != 0) { NG(); } else { ; } } void f66(void) { int16_t x341 = INT16_MAX; static int8_t x342 = 17; volatile uint64_t x343 = 7811319LLU; volatile uint64_t x344 = UINT64_MAX; static int32_t t66 = 120316619; t66 = ((x341&x342)==(x343*x344)); if (t66 != 0) { NG(); } else { ; } } void f67(void) { int64_t x346 = -1LL; static int16_t x347 = 4; int8_t x348 = INT8_MIN; volatile int32_t t67 = 66619386; t67 = ((x345&x346)==(x347*x348)); if (t67 != 0) { NG(); } else { ; } } void f68(void) { uint64_t x349 = UINT64_MAX; uint16_t x350 = 127U; static int64_t x351 = -1LL; volatile uint64_t x352 = 12660775862181LLU; t68 = ((x349&x350)==(x351*x352)); if (t68 != 0) { NG(); } else { ; } } void f69(void) { int16_t x361 = INT16_MAX; int16_t x362 = -178; t69 = ((x361&x362)==(x363*x364)); if (t69 != 0) { NG(); } else { ; } } void f70(void) { int64_t x365 = INT64_MAX; static int8_t x366 = -3; uint64_t x367 = 767372LLU; int16_t x368 = -1; volatile int32_t t70 = 5860841; t70 = ((x365&x366)==(x367*x368)); if (t70 != 0) { NG(); } else { ; } } void f71(void) { int32_t x370 = 99316804; uint32_t x371 = 4262727U; static uint8_t x372 = 57U; volatile int32_t t71 = -286; t71 = ((x369&x370)==(x371*x372)); if (t71 != 0) { NG(); } else { ; } } void f72(void) { static uint8_t x373 = UINT8_MAX; int64_t x374 = -1LL; int16_t x375 = -2; uint32_t x376 = 2134540865U; volatile int32_t t72 = -37002105; t72 = ((x373&x374)==(x375*x376)); if (t72 != 0) { NG(); } else { ; } } void f73(void) { uint32_t x381 = 304U; int32_t x382 = INT32_MIN; volatile uint64_t x383 = UINT64_MAX; int64_t x384 = -1LL; int32_t t73 = 1022; t73 = ((x381&x382)==(x383*x384)); if (t73 != 0) { NG(); } else { ; } } void f74(void) { uint32_t x385 = 4515341U; uint8_t x386 = UINT8_MAX; uint64_t x388 = 25LLU; volatile int32_t t74 = 57373; t74 = ((x385&x386)==(x387*x388)); if (t74 != 0) { NG(); } else { ; } } void f75(void) { int64_t x389 = INT64_MAX; uint64_t x391 = UINT64_MAX; int32_t t75 = 62; t75 = ((x389&x390)==(x391*x392)); if (t75 != 0) { NG(); } else { ; } } void f76(void) { static int64_t x393 = 1011126813636631LL; static int8_t x394 = INT8_MIN; int8_t x395 = -25; volatile int32_t x396 = -3; t76 = ((x393&x394)==(x395*x396)); if (t76 != 0) { NG(); } else { ; } } void f77(void) { int64_t x397 = -4LL; volatile uint16_t x398 = 3U; int16_t x399 = -1; int16_t x400 = INT16_MIN; int32_t t77 = 294096; t77 = ((x397&x398)==(x399*x400)); if (t77 != 0) { NG(); } else { ; } } void f78(void) { int8_t x401 = INT8_MAX; uint32_t x402 = 456068U; volatile int16_t x403 = 2969; uint8_t x404 = 116U; volatile int32_t t78 = -130876; t78 = ((x401&x402)==(x403*x404)); if (t78 != 0) { NG(); } else { ; } } void f79(void) { static int8_t x405 = INT8_MIN; int8_t x406 = -2; int16_t x407 = INT16_MIN; uint16_t x408 = UINT16_MAX; t79 = ((x405&x406)==(x407*x408)); if (t79 != 0) { NG(); } else { ; } } void f80(void) { volatile int32_t x409 = -1; int16_t x410 = INT16_MIN; volatile int16_t x412 = 20; int32_t t80 = -151726891; t80 = ((x409&x410)==(x411*x412)); if (t80 != 0) { NG(); } else { ; } } void f81(void) { int64_t x414 = INT64_MIN; uint32_t x415 = UINT32_MAX; int8_t x416 = INT8_MIN; static volatile int32_t t81 = -67369; t81 = ((x413&x414)==(x415*x416)); if (t81 != 0) { NG(); } else { ; } } void f82(void) { static int8_t x417 = -10; int16_t x418 = 1080; uint16_t x420 = UINT16_MAX; volatile int32_t t82 = 11043732; t82 = ((x417&x418)==(x419*x420)); if (t82 != 0) { NG(); } else { ; } } void f83(void) { uint16_t x421 = UINT16_MAX; int8_t x422 = 7; volatile uint64_t x423 = 1LLU; int64_t x424 = 137575272596LL; int32_t t83 = 6826815; t83 = ((x421&x422)==(x423*x424)); if (t83 != 0) { NG(); } else { ; } } void f84(void) { uint64_t x433 = 13LLU; static uint32_t x434 = 1738652458U; int16_t x435 = INT16_MAX; int8_t x436 = INT8_MIN; int32_t t84 = -12261394; t84 = ((x433&x434)==(x435*x436)); if (t84 != 0) { NG(); } else { ; } } void f85(void) { int32_t x437 = INT32_MAX; static volatile int64_t x439 = 423589899784869LL; volatile int16_t x440 = -6478; volatile int32_t t85 = -6264423; t85 = ((x437&x438)==(x439*x440)); if (t85 != 0) { NG(); } else { ; } } void f86(void) { int32_t x441 = 210068017; volatile int16_t x443 = -1; uint16_t x444 = UINT16_MAX; int32_t t86 = 945089; t86 = ((x441&x442)==(x443*x444)); if (t86 != 0) { NG(); } else { ; } } void f87(void) { uint64_t x445 = 56566780065004LLU; int16_t x447 = -576; static uint64_t x448 = 2085LLU; t87 = ((x445&x446)==(x447*x448)); if (t87 != 0) { NG(); } else { ; } } void f88(void) { int64_t x449 = INT64_MIN; int8_t x450 = INT8_MAX; uint32_t x451 = 1416U; volatile int8_t x452 = INT8_MIN; volatile int32_t t88 = -9568739; t88 = ((x449&x450)==(x451*x452)); if (t88 != 0) { NG(); } else { ; } } void f89(void) { uint16_t x453 = 7U; static uint8_t x454 = 19U; uint8_t x455 = UINT8_MAX; volatile uint32_t x456 = 154508944U; volatile int32_t t89 = -1288055; t89 = ((x453&x454)==(x455*x456)); if (t89 != 0) { NG(); } else { ; } } void f90(void) { int32_t x460 = INT32_MAX; static volatile int32_t t90 = 8667580; t90 = ((x457&x458)==(x459*x460)); if (t90 != 0) { NG(); } else { ; } } void f91(void) { volatile int64_t x466 = -1LL; t91 = ((x465&x466)==(x467*x468)); if (t91 != 0) { NG(); } else { ; } } void f92(void) { static int16_t x471 = -45; volatile uint32_t x472 = UINT32_MAX; t92 = ((x469&x470)==(x471*x472)); if (t92 != 0) { NG(); } else { ; } } void f93(void) { int16_t x477 = INT16_MIN; volatile int16_t x478 = 52; static uint8_t x479 = 1U; int16_t x480 = -5; t93 = ((x477&x478)==(x479*x480)); if (t93 != 0) { NG(); } else { ; } } void f94(void) { int64_t x481 = -3582763LL; int64_t x483 = -1LL; volatile uint64_t x484 = UINT64_MAX; int32_t t94 = 887263; t94 = ((x481&x482)==(x483*x484)); if (t94 != 0) { NG(); } else { ; } } void f95(void) { static int16_t x486 = INT16_MAX; volatile int8_t x487 = INT8_MAX; volatile uint32_t x488 = UINT32_MAX; t95 = ((x485&x486)==(x487*x488)); if (t95 != 0) { NG(); } else { ; } } void f96(void) { static uint16_t x489 = UINT16_MAX; static int16_t x490 = INT16_MIN; static int8_t x491 = INT8_MIN; volatile int8_t x492 = INT8_MIN; int32_t t96 = -36929274; t96 = ((x489&x490)==(x491*x492)); if (t96 != 0) { NG(); } else { ; } } void f97(void) { int32_t x497 = INT32_MIN; static uint16_t x498 = 0U; volatile uint64_t x499 = UINT64_MAX; static int64_t x500 = -2837238LL; int32_t t97 = -2; t97 = ((x497&x498)==(x499*x500)); if (t97 != 0) { NG(); } else { ; } } void f98(void) { uint16_t x501 = 1320U; int32_t x502 = 14905346; uint8_t x503 = 15U; int8_t x504 = -40; int32_t t98 = 497; t98 = ((x501&x502)==(x503*x504)); if (t98 != 0) { NG(); } else { ; } } void f99(void) { static volatile int8_t x505 = -38; uint32_t x506 = UINT32_MAX; static volatile int32_t t99 = 59; t99 = ((x505&x506)==(x507*x508)); if (t99 != 0) { NG(); } else { ; } } void f100(void) { uint32_t x509 = 207U; static uint32_t x510 = 22U; volatile uint32_t x511 = 2078309U; volatile int32_t t100 = -144123953; t100 = ((x509&x510)==(x511*x512)); if (t100 != 0) { NG(); } else { ; } } void f101(void) { volatile int8_t x515 = 12; int32_t t101 = -436004027; t101 = ((x513&x514)==(x515*x516)); if (t101 != 0) { NG(); } else { ; } } void f102(void) { uint32_t x517 = 0U; uint64_t x518 = 103327328022LLU; int16_t x520 = 28; volatile int32_t t102 = 1; t102 = ((x517&x518)==(x519*x520)); if (t102 != 0) { NG(); } else { ; } } void f103(void) { int16_t x522 = INT16_MIN; uint32_t x523 = UINT32_MAX; uint8_t x524 = 15U; t103 = ((x521&x522)==(x523*x524)); if (t103 != 0) { NG(); } else { ; } } void f104(void) { static uint32_t x525 = UINT32_MAX; uint8_t x526 = UINT8_MAX; uint32_t x527 = 80U; volatile uint32_t x528 = UINT32_MAX; static int32_t t104 = 2; t104 = ((x525&x526)==(x527*x528)); if (t104 != 0) { NG(); } else { ; } } void f105(void) { volatile uint16_t x529 = 104U; int32_t x530 = INT32_MIN; int16_t x532 = INT16_MAX; volatile int32_t t105 = 709888; t105 = ((x529&x530)==(x531*x532)); if (t105 != 0) { NG(); } else { ; } } void f106(void) { static int16_t x537 = INT16_MAX; int16_t x538 = INT16_MIN; volatile int8_t x539 = INT8_MIN; int8_t x540 = INT8_MIN; t106 = ((x537&x538)==(x539*x540)); if (t106 != 0) { NG(); } else { ; } } void f107(void) { uint16_t x541 = 103U; uint16_t x543 = UINT16_MAX; int8_t x544 = 1; t107 = ((x541&x542)==(x543*x544)); if (t107 != 0) { NG(); } else { ; } } void f108(void) { int64_t x546 = INT64_MIN; int8_t x547 = 12; uint32_t x548 = 3653580U; t108 = ((x545&x546)==(x547*x548)); if (t108 != 0) { NG(); } else { ; } } void f109(void) { volatile int16_t x550 = -21; t109 = ((x549&x550)==(x551*x552)); if (t109 != 0) { NG(); } else { ; } } void f110(void) { int64_t x557 = INT64_MIN; int8_t x558 = INT8_MIN; uint8_t x559 = UINT8_MAX; int64_t x560 = 5979668918LL; static int32_t t110 = 0; t110 = ((x557&x558)==(x559*x560)); if (t110 != 0) { NG(); } else { ; } } void f111(void) { volatile int8_t x562 = INT8_MAX; int32_t x563 = -1; static int64_t x564 = -36LL; int32_t t111 = -61; t111 = ((x561&x562)==(x563*x564)); if (t111 != 0) { NG(); } else { ; } } void f112(void) { static uint32_t x569 = 4U; static uint16_t x570 = UINT16_MAX; static uint32_t x571 = 4682801U; volatile int32_t t112 = -1; t112 = ((x569&x570)==(x571*x572)); if (t112 != 0) { NG(); } else { ; } } void f113(void) { volatile int32_t x573 = INT32_MAX; volatile uint64_t x575 = 2244LLU; uint32_t x576 = 1910284U; int32_t t113 = -1455409; t113 = ((x573&x574)==(x575*x576)); if (t113 != 0) { NG(); } else { ; } } void f114(void) { int64_t x577 = -1LL; int64_t x578 = INT64_MAX; int32_t x579 = -1; static uint64_t x580 = UINT64_MAX; int32_t t114 = -154919; t114 = ((x577&x578)==(x579*x580)); if (t114 != 0) { NG(); } else { ; } } void f115(void) { uint64_t x581 = 179820493LLU; static uint16_t x582 = 356U; static uint16_t x583 = UINT16_MAX; int32_t x584 = -1; int32_t t115 = 127065981; t115 = ((x581&x582)==(x583*x584)); if (t115 != 0) { NG(); } else { ; } } void f116(void) { uint32_t x585 = 1186U; volatile int64_t x586 = -159669LL; int16_t x587 = INT16_MIN; int32_t t116 = -5; t116 = ((x585&x586)==(x587*x588)); if (t116 != 0) { NG(); } else { ; } } void f117(void) { uint32_t x589 = 51U; static uint64_t x590 = 12659355506458181LLU; int16_t x591 = -1; int8_t x592 = 55; static int32_t t117 = 59467905; t117 = ((x589&x590)==(x591*x592)); if (t117 != 0) { NG(); } else { ; } } void f118(void) { uint8_t x594 = 4U; static uint8_t x596 = 14U; static int32_t t118 = -2; t118 = ((x593&x594)==(x595*x596)); if (t118 != 0) { NG(); } else { ; } } void f119(void) { uint64_t x605 = UINT64_MAX; static int8_t x606 = -1; uint8_t x607 = UINT8_MAX; int32_t t119 = 297285; t119 = ((x605&x606)==(x607*x608)); if (t119 != 0) { NG(); } else { ; } } void f120(void) { int64_t x609 = INT64_MIN; int32_t x610 = -4789389; int8_t x611 = -1; int8_t x612 = INT8_MIN; volatile int32_t t120 = 125133; t120 = ((x609&x610)==(x611*x612)); if (t120 != 0) { NG(); } else { ; } } void f121(void) { uint32_t x613 = 13764141U; static uint8_t x614 = 60U; int32_t x615 = -12687; volatile uint32_t x616 = 4173586U; volatile int32_t t121 = -52602131; t121 = ((x613&x614)==(x615*x616)); if (t121 != 0) { NG(); } else { ; } } void f122(void) { static volatile int16_t x617 = INT16_MIN; uint64_t x618 = 553157LLU; uint8_t x619 = UINT8_MAX; static int32_t x620 = -3; static volatile int32_t t122 = 122820462; t122 = ((x617&x618)==(x619*x620)); if (t122 != 0) { NG(); } else { ; } } void f123(void) { static uint8_t x621 = 110U; static volatile uint8_t x623 = UINT8_MAX; volatile uint64_t x624 = 90752013LLU; static volatile int32_t t123 = 5823; t123 = ((x621&x622)==(x623*x624)); if (t123 != 0) { NG(); } else { ; } } void f124(void) { static uint32_t x625 = 24635U; uint16_t x626 = UINT16_MAX; int8_t x627 = -1; int32_t x628 = INT32_MAX; int32_t t124 = -906854564; t124 = ((x625&x626)==(x627*x628)); if (t124 != 0) { NG(); } else { ; } } void f125(void) { uint8_t x630 = UINT8_MAX; int8_t x631 = 3; uint8_t x632 = 97U; volatile int32_t t125 = 2; t125 = ((x629&x630)==(x631*x632)); if (t125 != 0) { NG(); } else { ; } } void f126(void) { volatile uint16_t x634 = 10U; int16_t x635 = INT16_MIN; int32_t t126 = 498577683; t126 = ((x633&x634)==(x635*x636)); if (t126 != 0) { NG(); } else { ; } } void f127(void) { uint32_t x638 = 0U; uint64_t x639 = UINT64_MAX; volatile int8_t x640 = INT8_MIN; volatile int32_t t127 = -949329; t127 = ((x637&x638)==(x639*x640)); if (t127 != 0) { NG(); } else { ; } } void f128(void) { uint16_t x650 = 92U; int16_t x652 = -1; t128 = ((x649&x650)==(x651*x652)); if (t128 != 0) { NG(); } else { ; } } void f129(void) { volatile int32_t x653 = INT32_MIN; volatile int64_t x655 = -1LL; uint32_t x656 = 255U; int32_t t129 = -69228; t129 = ((x653&x654)==(x655*x656)); if (t129 != 0) { NG(); } else { ; } } void f130(void) { uint8_t x657 = 7U; uint16_t x658 = 137U; int16_t x659 = INT16_MAX; volatile int32_t t130 = 626039; t130 = ((x657&x658)==(x659*x660)); if (t130 != 0) { NG(); } else { ; } } void f131(void) { int8_t x661 = INT8_MAX; int16_t x662 = INT16_MAX; int64_t x664 = INT64_MAX; volatile int32_t t131 = -21; t131 = ((x661&x662)==(x663*x664)); if (t131 != 0) { NG(); } else { ; } } void f132(void) { int64_t x669 = INT64_MIN; static int32_t x670 = INT32_MIN; uint64_t x672 = UINT64_MAX; volatile int32_t t132 = 2405336; t132 = ((x669&x670)==(x671*x672)); if (t132 != 0) { NG(); } else { ; } } void f133(void) { int16_t x674 = -5; int16_t x676 = -1001; t133 = ((x673&x674)==(x675*x676)); if (t133 != 0) { NG(); } else { ; } } void f134(void) { volatile int16_t x677 = -1; volatile uint32_t x679 = UINT32_MAX; int32_t t134 = 7096534; t134 = ((x677&x678)==(x679*x680)); if (t134 != 0) { NG(); } else { ; } } void f135(void) { int32_t x685 = INT32_MAX; int16_t x687 = INT16_MIN; int8_t x688 = INT8_MIN; t135 = ((x685&x686)==(x687*x688)); if (t135 != 0) { NG(); } else { ; } } void f136(void) { uint8_t x697 = UINT8_MAX; int16_t x698 = 0; int32_t x699 = -59; static int16_t x700 = -1; int32_t t136 = 1; t136 = ((x697&x698)==(x699*x700)); if (t136 != 0) { NG(); } else { ; } } void f137(void) { int8_t x701 = INT8_MAX; int64_t x702 = -12502861126646765LL; static int16_t x703 = 742; uint16_t x704 = UINT16_MAX; static int32_t t137 = -201955; t137 = ((x701&x702)==(x703*x704)); if (t137 != 0) { NG(); } else { ; } } void f138(void) { static int32_t x706 = -251716544; static int16_t x707 = -1; uint32_t x708 = UINT32_MAX; int32_t t138 = -530732; t138 = ((x705&x706)==(x707*x708)); if (t138 != 0) { NG(); } else { ; } } void f139(void) { int64_t x709 = 12960874LL; uint64_t x710 = 138856934544LLU; int8_t x711 = INT8_MIN; static int8_t x712 = -1; int32_t t139 = -520061845; t139 = ((x709&x710)==(x711*x712)); if (t139 != 0) { NG(); } else { ; } } void f140(void) { int16_t x713 = 2891; volatile int8_t x714 = 0; int8_t x715 = -1; int8_t x716 = 0; static volatile int32_t t140 = -11041; t140 = ((x713&x714)==(x715*x716)); if (t140 != 1) { NG(); } else { ; } } void f141(void) { volatile uint64_t x721 = 787850LLU; volatile int16_t x723 = INT16_MIN; volatile uint8_t x724 = 0U; volatile int32_t t141 = -6147; t141 = ((x721&x722)==(x723*x724)); if (t141 != 0) { NG(); } else { ; } } void f142(void) { int8_t x725 = 8; volatile int32_t x726 = INT32_MAX; int32_t x727 = INT32_MIN; uint32_t x728 = 111U; volatile int32_t t142 = -979091027; t142 = ((x725&x726)==(x727*x728)); if (t142 != 0) { NG(); } else { ; } } void f143(void) { int32_t x733 = -4414405; static int64_t x734 = INT64_MAX; uint16_t x735 = 195U; int64_t x736 = -4012LL; volatile int32_t t143 = -1327; t143 = ((x733&x734)==(x735*x736)); if (t143 != 0) { NG(); } else { ; } } void f144(void) { static uint32_t x737 = UINT32_MAX; static uint8_t x740 = UINT8_MAX; volatile int32_t t144 = -337632; t144 = ((x737&x738)==(x739*x740)); if (t144 != 0) { NG(); } else { ; } } void f145(void) { int64_t x745 = INT64_MAX; int64_t x746 = -1LL; int8_t x747 = -44; int64_t x748 = -17511386760299528LL; t145 = ((x745&x746)==(x747*x748)); if (t145 != 0) { NG(); } else { ; } } void f146(void) { int64_t x758 = 265205022LL; volatile uint32_t x760 = UINT32_MAX; int32_t t146 = -94; t146 = ((x757&x758)==(x759*x760)); if (t146 != 0) { NG(); } else { ; } } void f147(void) { volatile int32_t x761 = -40969317; int8_t x763 = INT8_MIN; static int32_t x764 = -95698; int32_t t147 = -208303242; t147 = ((x761&x762)==(x763*x764)); if (t147 != 0) { NG(); } else { ; } } void f148(void) { int32_t x765 = -57; int8_t x766 = -10; static int8_t x767 = INT8_MIN; static int64_t x768 = 18230LL; int32_t t148 = -11389; t148 = ((x765&x766)==(x767*x768)); if (t148 != 0) { NG(); } else { ; } } void f149(void) { volatile uint64_t x777 = UINT64_MAX; int16_t x778 = INT16_MAX; int64_t x779 = -479117LL; uint64_t x780 = 160LLU; int32_t t149 = 212237161; t149 = ((x777&x778)==(x779*x780)); if (t149 != 0) { NG(); } else { ; } } void f150(void) { int64_t x781 = -1LL; volatile int16_t x782 = -5513; uint16_t x784 = 210U; static int32_t t150 = 225195; t150 = ((x781&x782)==(x783*x784)); if (t150 != 0) { NG(); } else { ; } } void f151(void) { int64_t x789 = INT64_MIN; static uint8_t x790 = 24U; static volatile int16_t x792 = -1; volatile int32_t t151 = -1; t151 = ((x789&x790)==(x791*x792)); if (t151 != 0) { NG(); } else { ; } } void f152(void) { static int32_t x793 = -1003; int32_t x794 = -1; uint64_t x795 = 133273579LLU; volatile int32_t t152 = 2; t152 = ((x793&x794)==(x795*x796)); if (t152 != 0) { NG(); } else { ; } } void f153(void) { static int64_t x797 = INT64_MIN; int8_t x798 = INT8_MAX; static volatile uint8_t x799 = 2U; t153 = ((x797&x798)==(x799*x800)); if (t153 != 0) { NG(); } else { ; } } void f154(void) { uint32_t x801 = 73U; int16_t x803 = INT16_MAX; int32_t t154 = 39306356; t154 = ((x801&x802)==(x803*x804)); if (t154 != 0) { NG(); } else { ; } } void f155(void) { int32_t x805 = INT32_MAX; int16_t x806 = -2753; int64_t x807 = INT64_MIN; volatile uint64_t x808 = UINT64_MAX; int32_t t155 = -137; t155 = ((x805&x806)==(x807*x808)); if (t155 != 0) { NG(); } else { ; } } void f156(void) { int16_t x809 = INT16_MAX; static uint16_t x811 = UINT16_MAX; int16_t x812 = -1; volatile int32_t t156 = 105; t156 = ((x809&x810)==(x811*x812)); if (t156 != 0) { NG(); } else { ; } } void f157(void) { uint64_t x813 = UINT64_MAX; uint16_t x814 = 10298U; int64_t x815 = -1LL; int32_t t157 = 75710475; t157 = ((x813&x814)==(x815*x816)); if (t157 != 0) { NG(); } else { ; } } void f158(void) { int8_t x818 = INT8_MAX; int8_t x819 = INT8_MAX; int8_t x820 = INT8_MIN; volatile int32_t t158 = -416728158; t158 = ((x817&x818)==(x819*x820)); if (t158 != 0) { NG(); } else { ; } } void f159(void) { volatile int32_t x822 = -55051727; volatile uint8_t x823 = UINT8_MAX; int32_t t159 = -12393436; t159 = ((x821&x822)==(x823*x824)); if (t159 != 0) { NG(); } else { ; } } void f160(void) { static int64_t x825 = -54240419LL; volatile uint8_t x826 = 20U; uint16_t x828 = 10U; t160 = ((x825&x826)==(x827*x828)); if (t160 != 0) { NG(); } else { ; } } void f161(void) { static int8_t x830 = INT8_MIN; t161 = ((x829&x830)==(x831*x832)); if (t161 != 1) { NG(); } else { ; } } void f162(void) { volatile uint64_t x833 = 10077076LLU; volatile uint32_t x836 = 0U; volatile int32_t t162 = 10843; t162 = ((x833&x834)==(x835*x836)); if (t162 != 0) { NG(); } else { ; } } void f163(void) { int64_t x837 = -1LL; uint8_t x838 = UINT8_MAX; int8_t x839 = INT8_MIN; uint64_t x840 = 45732919591LLU; t163 = ((x837&x838)==(x839*x840)); if (t163 != 0) { NG(); } else { ; } } void f164(void) { int64_t x845 = -1LL; uint64_t x846 = 2131372745LLU; volatile int8_t x847 = INT8_MIN; int8_t x848 = INT8_MAX; volatile int32_t t164 = -750; t164 = ((x845&x846)==(x847*x848)); if (t164 != 0) { NG(); } else { ; } } void f165(void) { static int32_t x854 = 129040; volatile uint64_t x856 = 1LLU; volatile int32_t t165 = 27687; t165 = ((x853&x854)==(x855*x856)); if (t165 != 0) { NG(); } else { ; } } void f166(void) { int16_t x865 = INT16_MIN; int8_t x866 = 1; int8_t x868 = -1; int32_t t166 = -2; t166 = ((x865&x866)==(x867*x868)); if (t166 != 0) { NG(); } else { ; } } void f167(void) { int64_t x869 = INT64_MIN; int8_t x870 = INT8_MAX; int64_t x871 = 15997832LL; int32_t x872 = 1; static int32_t t167 = -6; t167 = ((x869&x870)==(x871*x872)); if (t167 != 0) { NG(); } else { ; } } void f168(void) { volatile int32_t x881 = INT32_MIN; uint8_t x882 = 14U; int16_t x883 = -1; volatile int8_t x884 = 3; t168 = ((x881&x882)==(x883*x884)); if (t168 != 0) { NG(); } else { ; } } void f169(void) { uint16_t x885 = UINT16_MAX; static int8_t x886 = -1; int16_t x887 = INT16_MIN; int8_t x888 = -1; int32_t t169 = -1971; t169 = ((x885&x886)==(x887*x888)); if (t169 != 0) { NG(); } else { ; } } void f170(void) { int16_t x889 = 3; uint8_t x890 = UINT8_MAX; static uint32_t x891 = UINT32_MAX; volatile int32_t t170 = -940811475; t170 = ((x889&x890)==(x891*x892)); if (t170 != 0) { NG(); } else { ; } } void f171(void) { int8_t x893 = INT8_MIN; uint16_t x894 = 1723U; int8_t x896 = 2; int32_t t171 = -13089; t171 = ((x893&x894)==(x895*x896)); if (t171 != 0) { NG(); } else { ; } } void f172(void) { uint32_t x910 = 84285U; static int8_t x911 = INT8_MAX; t172 = ((x909&x910)==(x911*x912)); if (t172 != 0) { NG(); } else { ; } } void f173(void) { int64_t x918 = -78LL; uint32_t x919 = 1798064U; int32_t x920 = -1; volatile int32_t t173 = 109291; t173 = ((x917&x918)==(x919*x920)); if (t173 != 0) { NG(); } else { ; } } void f174(void) { int16_t x929 = -250; int16_t x932 = INT16_MIN; volatile int32_t t174 = -3615027; t174 = ((x929&x930)==(x931*x932)); if (t174 != 0) { NG(); } else { ; } } void f175(void) { int32_t x933 = INT32_MIN; uint16_t x934 = 2U; static uint32_t x935 = 6328705U; int16_t x936 = -516; volatile int32_t t175 = 1478; t175 = ((x933&x934)==(x935*x936)); if (t175 != 0) { NG(); } else { ; } } void f176(void) { volatile int16_t x938 = INT16_MIN; static int16_t x939 = 1316; int32_t t176 = -149; t176 = ((x937&x938)==(x939*x940)); if (t176 != 0) { NG(); } else { ; } } void f177(void) { int8_t x945 = INT8_MIN; volatile int64_t x946 = -1LL; static int32_t x947 = -2998; static int8_t x948 = 5; int32_t t177 = -1009208893; t177 = ((x945&x946)==(x947*x948)); if (t177 != 0) { NG(); } else { ; } } void f178(void) { static int16_t x953 = INT16_MAX; uint64_t x954 = 1561LLU; static uint32_t x955 = 4U; volatile int64_t x956 = -74997523972833LL; int32_t t178 = 178505745; t178 = ((x953&x954)==(x955*x956)); if (t178 != 0) { NG(); } else { ; } } void f179(void) { volatile uint8_t x961 = 7U; volatile int16_t x962 = INT16_MAX; int64_t x963 = 4374555LL; t179 = ((x961&x962)==(x963*x964)); if (t179 != 0) { NG(); } else { ; } } void f180(void) { uint32_t x965 = 387100U; uint16_t x967 = 9546U; uint64_t x968 = 4LLU; static volatile int32_t t180 = -10332205; t180 = ((x965&x966)==(x967*x968)); if (t180 != 0) { NG(); } else { ; } } void f181(void) { uint16_t x969 = 37U; int8_t x970 = 6; uint32_t x972 = UINT32_MAX; int32_t t181 = -405; t181 = ((x969&x970)==(x971*x972)); if (t181 != 0) { NG(); } else { ; } } void f182(void) { static uint8_t x973 = 0U; int32_t x974 = INT32_MIN; static int8_t x975 = INT8_MIN; int32_t t182 = 2711879; t182 = ((x973&x974)==(x975*x976)); if (t182 != 0) { NG(); } else { ; } } void f183(void) { int8_t x977 = INT8_MIN; int64_t x978 = INT64_MIN; t183 = ((x977&x978)==(x979*x980)); if (t183 != 0) { NG(); } else { ; } } void f184(void) { int16_t x985 = INT16_MAX; static uint16_t x986 = 11097U; uint16_t x987 = 1U; volatile int16_t x988 = INT16_MAX; int32_t t184 = 467866170; t184 = ((x985&x986)==(x987*x988)); if (t184 != 0) { NG(); } else { ; } } void f185(void) { int64_t x989 = INT64_MIN; uint8_t x990 = 30U; volatile uint8_t x992 = UINT8_MAX; int32_t t185 = -559; t185 = ((x989&x990)==(x991*x992)); if (t185 != 0) { NG(); } else { ; } } void f186(void) { int16_t x993 = INT16_MAX; volatile int64_t x994 = -8LL; uint64_t x995 = 3342413767437278LLU; volatile int32_t t186 = -12791963; t186 = ((x993&x994)==(x995*x996)); if (t186 != 0) { NG(); } else { ; } } void f187(void) { int64_t x997 = INT64_MIN; static int64_t x998 = 0LL; volatile int8_t x999 = INT8_MIN; volatile uint64_t x1000 = 873LLU; t187 = ((x997&x998)==(x999*x1000)); if (t187 != 0) { NG(); } else { ; } } void f188(void) { int32_t x1001 = 1984; static uint64_t x1002 = 4213859619LLU; static uint8_t x1003 = 94U; int8_t x1004 = INT8_MAX; int32_t t188 = 30808; t188 = ((x1001&x1002)==(x1003*x1004)); if (t188 != 0) { NG(); } else { ; } } void f189(void) { volatile int64_t x1005 = 100282409893941470LL; uint8_t x1006 = UINT8_MAX; int32_t x1007 = -1; volatile int16_t x1008 = INT16_MAX; static volatile int32_t t189 = -2; t189 = ((x1005&x1006)==(x1007*x1008)); if (t189 != 0) { NG(); } else { ; } } void f190(void) { int8_t x1013 = INT8_MIN; uint8_t x1015 = 1U; int8_t x1016 = -1; t190 = ((x1013&x1014)==(x1015*x1016)); if (t190 != 0) { NG(); } else { ; } } void f191(void) { uint16_t x1018 = UINT16_MAX; static uint32_t x1019 = UINT32_MAX; uint64_t x1020 = UINT64_MAX; int32_t t191 = -108; t191 = ((x1017&x1018)==(x1019*x1020)); if (t191 != 0) { NG(); } else { ; } } void f192(void) { uint16_t x1023 = 21U; static uint8_t x1024 = UINT8_MAX; t192 = ((x1021&x1022)==(x1023*x1024)); if (t192 != 0) { NG(); } else { ; } } void f193(void) { uint16_t x1025 = UINT16_MAX; static volatile uint64_t x1026 = 1154934980LLU; uint16_t x1027 = 64U; volatile int32_t t193 = -4234807; t193 = ((x1025&x1026)==(x1027*x1028)); if (t193 != 0) { NG(); } else { ; } } void f194(void) { uint32_t x1029 = UINT32_MAX; int16_t x1030 = -1; volatile int32_t t194 = 369064431; t194 = ((x1029&x1030)==(x1031*x1032)); if (t194 != 0) { NG(); } else { ; } } void f195(void) { volatile int32_t x1033 = -1; int8_t x1034 = INT8_MIN; static int64_t x1035 = -20LL; static uint16_t x1036 = UINT16_MAX; volatile int32_t t195 = 1022; t195 = ((x1033&x1034)==(x1035*x1036)); if (t195 != 0) { NG(); } else { ; } } void f196(void) { int32_t x1038 = INT32_MAX; volatile int16_t x1039 = INT16_MIN; int8_t x1040 = 2; int32_t t196 = 1876; t196 = ((x1037&x1038)==(x1039*x1040)); if (t196 != 0) { NG(); } else { ; } } void f197(void) { static int16_t x1042 = 2; int64_t x1043 = -73713707LL; volatile int32_t x1044 = -1; static int32_t t197 = 2; t197 = ((x1041&x1042)==(x1043*x1044)); if (t197 != 0) { NG(); } else { ; } } void f198(void) { uint8_t x1045 = 29U; uint64_t x1046 = 608946981LLU; static int64_t x1047 = -1LL; int16_t x1048 = 0; volatile int32_t t198 = -576656035; t198 = ((x1045&x1046)==(x1047*x1048)); if (t198 != 0) { NG(); } else { ; } } void f199(void) { volatile int64_t x1049 = INT64_MIN; int8_t x1050 = -1; int16_t x1051 = INT16_MIN; static int32_t t199 = 3; t199 = ((x1049&x1050)==(x1051*x1052)); if (t199 != 0) { NG(); } else { ; } } int main(void) { f0(); f1(); f2(); f3(); f4(); f5(); f6(); f7(); f8(); f9(); f10(); f11(); f12(); f13(); f14(); f15(); f16(); f17(); f18(); f19(); f20(); f21(); f22(); f23(); f24(); f25(); f26(); f27(); f28(); f29(); f30(); f31(); f32(); f33(); f34(); f35(); f36(); f37(); f38(); f39(); f40(); f41(); f42(); f43(); f44(); f45(); f46(); f47(); f48(); f49(); f50(); f51(); f52(); f53(); f54(); f55(); f56(); f57(); f58(); f59(); f60(); f61(); f62(); f63(); f64(); f65(); f66(); f67(); f68(); f69(); f70(); f71(); f72(); f73(); f74(); f75(); f76(); f77(); f78(); f79(); f80(); f81(); f82(); f83(); f84(); f85(); f86(); f87(); f88(); f89(); f90(); f91(); f92(); f93(); f94(); f95(); f96(); f97(); f98(); f99(); f100(); f101(); f102(); f103(); f104(); f105(); f106(); f107(); f108(); f109(); f110(); f111(); f112(); f113(); f114(); f115(); f116(); f117(); f118(); f119(); f120(); f121(); f122(); f123(); f124(); f125(); f126(); f127(); f128(); f129(); f130(); f131(); f132(); f133(); f134(); f135(); f136(); f137(); f138(); f139(); f140(); f141(); f142(); f143(); f144(); f145(); f146(); f147(); f148(); f149(); f150(); f151(); f152(); f153(); f154(); f155(); f156(); f157(); f158(); f159(); f160(); f161(); f162(); f163(); f164(); f165(); f166(); f167(); f168(); f169(); f170(); f171(); f172(); f173(); f174(); f175(); f176(); f177(); f178(); f179(); f180(); f181(); f182(); f183(); f184(); f185(); f186(); f187(); f188(); f189(); f190(); f191(); f192(); f193(); f194(); f195(); f196(); f197(); f198(); f199(); return 0; }
datatok/djobi
djobi-core/src/main/java/io/datatok/djobi/engine/events/JobAwareEvent.java
package io.datatok.djobi.engine.events; import io.datatok.djobi.engine.Job; import io.datatok.djobi.event.Event; public abstract class JobAwareEvent extends Event { protected Job job; public JobAwareEvent(Job job) { this.job = job; } public Job getJob() { return job; } public void setJob(Job job) { this.job = job; } }
Missouri-BMI/popmednet
Lpp.Dns.Portal/js/Dialogs/MetadataBulkEditPropertiesEditor.js
<gh_stars>0 var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); /// <reference path="../../Scripts/page/Page.ts" /> var Dialog; (function (Dialog) { var MetadataBulkEditPropertiesEditor; (function (MetadataBulkEditPropertiesEditor) { var vm; var dvm; var DataMartsViewModel = /** @class */ (function () { function DataMartsViewModel(routing) { var self = this; self.DataMartID = routing.DataMartID; self.RequestDataMartID = routing.ID; self.DataMartName = routing.DataMart; self.Selected = ko.observable(false); } return DataMartsViewModel; }()); MetadataBulkEditPropertiesEditor.DataMartsViewModel = DataMartsViewModel; var MetadataBulkEditPropertiesEditorViewModel = /** @class */ (function (_super) { __extends(MetadataBulkEditPropertiesEditorViewModel, _super); function MetadataBulkEditPropertiesEditorViewModel(bindingControl, defaultPriority, defaultDueDate, isRequestLevel) { var _this = _super.call(this, bindingControl) || this; var self = _this; self.IsRequestLevel = isRequestLevel; _this.InfoText = isRequestLevel ? 'The following values will be applied to the selected requests.' : 'The following values will be applied to the selected datamarts.'; self.Priority = ko.observable(defaultPriority); self.DueDate = ko.observable(defaultDueDate); self.PrioritySelected = ko.observable(false); self.DueDateSelected = ko.observable(false); self.ApplyToRoutings = ko.observable(false); self.Priority.subscribe(function (v) { return self.PrioritySelected(true); }); self.DueDate.subscribe(function (v) { return self.DueDateSelected(true); }); self.onApply = function () { var stringDate = ""; if (self.DueDate() != null) { stringDate = self.DueDate().toDateString(); } var results = { UpdatePriority: self.PrioritySelected(), UpdateDueDate: self.DueDateSelected(), PriorityValue: self.Priority(), DueDateValue: self.DueDate(), ApplyToRoutings: self.ApplyToRoutings(), stringDate: stringDate }; self.Close(results); }; self.onCancel = function () { self.Close(null); }; return _this; } return MetadataBulkEditPropertiesEditorViewModel; }(Global.DialogViewModel)); MetadataBulkEditPropertiesEditor.MetadataBulkEditPropertiesEditorViewModel = MetadataBulkEditPropertiesEditorViewModel; function init() { var window = Global.Helpers.GetDialogWindow(); var parameters = (window.options).parameters; var defaultPriority = (parameters.defaultPriority); var defaultDueDate = (parameters.defaultDueDate); var isRequestLevel = (parameters.isRequestLevel || false); $(function () { var bindingControl = $("MetadataBulkEditPropertiesEditor"); vm = new MetadataBulkEditPropertiesEditorViewModel(bindingControl, defaultPriority, defaultDueDate, isRequestLevel); ko.applyBindings(vm, bindingControl[0]); }); } init(); })(MetadataBulkEditPropertiesEditor = Dialog.MetadataBulkEditPropertiesEditor || (Dialog.MetadataBulkEditPropertiesEditor = {})); })(Dialog || (Dialog = {}));
ftdi-paul-jiao/stm32L4_Eve_example
FT_Esd_Framework/Ft_Esd.c
<filename>FT_Esd_Framework/Ft_Esd.c /* Copyright (C) 2015-2016 Future Technology Devices International Ltd THIS SOFTWARE IS PROVIDED BY FUTURE TECHNOLOGY DEVICES INTERNATIONAL LIMITED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL FUTURE TECHNOLOGY DEVICES INTERNATIONAL LIMITED BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES LOSS OF USE, DATA, OR PROFITS OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Author: <NAME> <<EMAIL>> */ #include "Ft_Esd.h" void Ft_Esd_Noop(void *context) { // no-op } /* end of file */
mikiec84/OpenSPIFe
gov.nasa.ensemble.core.jscience/src/gov/nasa/ensemble/core/jscience/util/STKDateFormat.java
/******************************************************************************* * Copyright 2014 United States Government as represented by the * Administrator of the National Aeronautics and Space Administration. * 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 gov.nasa.ensemble.core.jscience.util; import java.text.FieldPosition; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Date; public class STKDateFormat extends SimpleDateFormat { private static final int MAX_DIGITS_TO_RIGHT_OF_DECIMAL = 3; public STKDateFormat() { super("d MMM yyyy H:mm:ss.SSS"); } @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { return super.format(date, toAppendTo, fieldPosition); } @Override public Date parse(String source, ParsePosition pos) { int needToTrim = numberOfSurplusDigits(source); if (needToTrim > 0) { source = source.substring(0, source.length()-needToTrim); } return super.parse(source, pos); } private int numberOfSurplusDigits(String string) { int decimalPosition = string.lastIndexOf('.'); if (decimalPosition == -1) return 0; int length = string.length(); int numberOfDigits = length-decimalPosition-1; if (numberOfDigits <= MAX_DIGITS_TO_RIGHT_OF_DECIMAL) { return 0; } else { return numberOfDigits - MAX_DIGITS_TO_RIGHT_OF_DECIMAL; } } }
asmaloney/gactar
actr/modules/modules.go
<reponame>asmaloney/gactar // Package modules implements several ACT-R modules. package modules import ( "github.com/asmaloney/gactar/actr/buffer" "github.com/asmaloney/gactar/actr/params" "github.com/asmaloney/gactar/util/container" ) // ModuleInterface provides an interface for the ACT-R concept of a "module". type ModuleInterface interface { ModuleName() string NumBuffers() int BufferNames() []string HasBuffer(name string) bool OnlyBuffer() *buffer.Buffer LookupBuffer(name string) buffer.BufferInterface SetParam(param *params.Param) (err error) } type Module struct { Name string Buffers []buffer.Buffer } func (m Module) ModuleName() string { return m.Name } func (m Module) NumBuffers() int { return len(m.Buffers) } func (m Module) BufferNames() (names []string) { for _, buff := range m.Buffers { names = append(names, buff.BufferName()) } return } func (m Module) HasBuffer(name string) bool { names := m.BufferNames() return container.Contains(name, names) } func (m Module) OnlyBuffer() *buffer.Buffer { if m.Buffers == nil || len(m.Buffers) > 1 { return nil } return &m.Buffers[0] } func (m Module) LookupBuffer(name string) buffer.BufferInterface { for _, buff := range m.Buffers { if buff.Name == name { return buff } } return nil }
ducis/operating-system-labs
sr/lsri/kernel/system/do_privctl.c
/* The kernel call implemented in this file: * m_type: SYS_PRIVCTL * * The parameters for this kernel call are: * m2_i1: CTL_ENDPT (process endpoint of target) * m2_i2: CTL_REQUEST (privilege control request) * m2_p1: CTL_ARG_PTR (pointer to request data) */ #include "kernel/system.h" #include "kernel/ipc.h" #include <signal.h> #include <string.h> #include <minix/endpoint.h> #if USE_PRIVCTL /*===========================================================================* * do_privctl * *===========================================================================*/ PUBLIC int do_privctl(struct proc * caller, message * m_ptr) { /* Handle sys_privctl(). Update a process' privileges. If the process is not * yet a system process, make sure it gets its own privilege structure. */ struct proc *rp; proc_nr_t proc_nr; sys_id_t priv_id; int ipc_to_m, kcalls; int i, r; struct io_range io_range; struct mem_range mem_range; struct priv priv; int irq; /* Check whether caller is allowed to make this call. Privileged proceses * can only update the privileges of processes that are inhibited from * running by the RTS_NO_PRIV flag. This flag is set when a privileged process * forks. */ if (! (priv(caller)->s_flags & SYS_PROC)) return(EPERM); if(m_ptr->CTL_ENDPT == SELF) proc_nr = _ENDPOINT_P(caller->p_endpoint); else if(!isokendpt(m_ptr->CTL_ENDPT, &proc_nr)) return(EINVAL); rp = proc_addr(proc_nr); switch(m_ptr->CTL_REQUEST) { case SYS_PRIV_ALLOW: /* Allow process to run. Make sure its privilege structure has already * been set. */ if (!RTS_ISSET(rp, RTS_NO_PRIV) || priv(rp)->s_proc_nr == NONE) { return(EPERM); } RTS_UNSET(rp, RTS_NO_PRIV); return(OK); case SYS_PRIV_DISALLOW: /* Disallow process from running. */ if (RTS_ISSET(rp, RTS_NO_PRIV)) return(EPERM); RTS_SET(rp, RTS_NO_PRIV); return(OK); case SYS_PRIV_SET_SYS: /* Set a privilege structure of a blocked system process. */ if (! RTS_ISSET(rp, RTS_NO_PRIV)) return(EPERM); /* Check whether a static or dynamic privilege id must be allocated. */ priv_id = NULL_PRIV_ID; if (m_ptr->CTL_ARG_PTR) { /* Copy privilege structure from caller */ if((r=data_copy(caller->p_endpoint, (vir_bytes) m_ptr->CTL_ARG_PTR, KERNEL, (vir_bytes) &priv, sizeof(priv))) != OK) return r; /* See if the caller wants to assign a static privilege id. */ if(!(priv.s_flags & DYN_PRIV_ID)) { priv_id = priv.s_id; } } /* Make sure this process has its own privileges structure. This may * fail, since there are only a limited number of system processes. * Then copy privileges from the caller and restore some defaults. */ if ((i=get_priv(rp, priv_id)) != OK) { printf("do_privctl: unable to allocate priv_id %d: %d\n", priv_id, i); return(i); } priv_id = priv(rp)->s_id; /* backup privilege id */ *priv(rp) = *priv(caller); /* copy from caller */ priv(rp)->s_id = priv_id; /* restore privilege id */ priv(rp)->s_proc_nr = proc_nr; /* reassociate process nr */ for (i=0; i< NR_SYS_CHUNKS; i++) /* remove pending: */ priv(rp)->s_notify_pending.chunk[i] = 0; /* - notifications */ priv(rp)->s_int_pending = 0; /* - interrupts */ sigemptyset(&priv(rp)->s_sig_pending); /* - signals */ reset_timer(&priv(rp)->s_alarm_timer); /* - alarm */ priv(rp)->s_asyntab= -1; /* - asynsends */ priv(rp)->s_asynsize= 0; /* Set defaults for privilege bitmaps. */ priv(rp)->s_flags= DEF_SYS_F; /* privilege flags */ priv(rp)->s_trap_mask= DEF_SYS_T; /* allowed traps */ ipc_to_m = DEF_SYS_M; /* allowed targets */ kcalls = DEF_SYS_KC; /* allowed kernel calls */ for(i = 0; i < SYS_CALL_MASK_SIZE; i++) { priv(rp)->s_k_call_mask[i] = (kcalls == NO_C ? 0 : (~0)); } /* Set the default signal manager. */ priv(rp)->s_sig_mgr = DEF_SYS_SM; /* Set defaults for resources: no I/O resources, no memory resources, * no IRQs, no grant table */ priv(rp)->s_nr_io_range= 0; priv(rp)->s_nr_mem_range= 0; priv(rp)->s_nr_irq= 0; priv(rp)->s_grant_table= 0; priv(rp)->s_grant_entries= 0; /* Override defaults if the caller has supplied a privilege structure. */ if (m_ptr->CTL_ARG_PTR) { /* Copy s_flags and signal manager. */ priv(rp)->s_flags = priv.s_flags; priv(rp)->s_sig_mgr = priv.s_sig_mgr; /* Copy IRQs */ if(priv.s_flags & CHECK_IRQ) { if (priv.s_nr_irq < 0 || priv.s_nr_irq > NR_IRQ) return EINVAL; priv(rp)->s_nr_irq= priv.s_nr_irq; for (i= 0; i<priv.s_nr_irq; i++) { priv(rp)->s_irq_tab[i]= priv.s_irq_tab[i]; #if 0 printf("do_privctl: adding IRQ %d for %d\n", priv(rp)->s_irq_tab[i], rp->p_endpoint); #endif } } /* Copy I/O ranges */ if(priv.s_flags & CHECK_IO_PORT) { if (priv.s_nr_io_range < 0 || priv.s_nr_io_range > NR_IO_RANGE) return EINVAL; priv(rp)->s_nr_io_range= priv.s_nr_io_range; for (i= 0; i<priv.s_nr_io_range; i++) { priv(rp)->s_io_tab[i]= priv.s_io_tab[i]; #if 0 printf("do_privctl: adding I/O range [%x..%x] for %d\n", priv(rp)->s_io_tab[i].ior_base, priv(rp)->s_io_tab[i].ior_limit, rp->p_endpoint); #endif } } /* Copy memory ranges */ if(priv.s_flags & CHECK_MEM) { if (priv.s_nr_mem_range < 0 || priv.s_nr_mem_range > NR_MEM_RANGE) return EINVAL; priv(rp)->s_nr_mem_range= priv.s_nr_mem_range; for (i= 0; i<priv.s_nr_mem_range; i++) { priv(rp)->s_mem_tab[i]= priv.s_mem_tab[i]; #if 0 printf("do_privctl: adding mem range [%x..%x] for %d\n", priv(rp)->s_mem_tab[i].mr_base, priv(rp)->s_mem_tab[i].mr_limit, rp->p_endpoint); #endif } } /* Copy trap mask. */ priv(rp)->s_trap_mask = priv.s_trap_mask; /* Copy target mask. */ memcpy(&ipc_to_m, &priv.s_ipc_to, sizeof(ipc_to_m)); /* Copy kernel call mask. */ memcpy(priv(rp)->s_k_call_mask, priv.s_k_call_mask, sizeof(priv(rp)->s_k_call_mask)); } /* Fill in target mask. */ for (i=0; i < NR_SYS_PROCS; i++) { if (ipc_to_m & (1 << i)) set_sendto_bit(rp, i); else unset_sendto_bit(rp, i); } return(OK); case SYS_PRIV_SET_USER: /* Set a privilege structure of a blocked user process. */ if (!RTS_ISSET(rp, RTS_NO_PRIV)) return(EPERM); /* Link the process to the privilege structure of the root user * process all the user processes share. */ priv(rp) = priv_addr(USER_PRIV_ID); return(OK); case SYS_PRIV_ADD_IO: if (RTS_ISSET(rp, RTS_NO_PRIV)) return(EPERM); /* Only system processes get I/O resources? */ if (!(priv(rp)->s_flags & SYS_PROC)) return EPERM; #if 0 /* XXX -- do we need a call for this? */ if (strcmp(rp->p_name, "fxp") == 0 || strcmp(rp->p_name, "rtl8139") == 0) { printf("setting ipc_stats_target to %d\n", rp->p_endpoint); ipc_stats_target= rp->p_endpoint; } #endif /* Get the I/O range */ data_copy(caller->p_endpoint, (vir_bytes) m_ptr->CTL_ARG_PTR, KERNEL, (vir_bytes) &io_range, sizeof(io_range)); priv(rp)->s_flags |= CHECK_IO_PORT; /* Check I/O accesses */ i= priv(rp)->s_nr_io_range; if (i >= NR_IO_RANGE) { printf("do_privctl: %d already has %d i/o ranges.\n", rp->p_endpoint, i); return ENOMEM; } priv(rp)->s_io_tab[i].ior_base= io_range.ior_base; priv(rp)->s_io_tab[i].ior_limit= io_range.ior_limit; priv(rp)->s_nr_io_range++; return OK; case SYS_PRIV_ADD_MEM: if (RTS_ISSET(rp, RTS_NO_PRIV)) return(EPERM); /* Only system processes get memory resources? */ if (!(priv(rp)->s_flags & SYS_PROC)) return EPERM; /* Get the memory range */ if((r=data_copy(caller->p_endpoint, (vir_bytes) m_ptr->CTL_ARG_PTR, KERNEL, (vir_bytes) &mem_range, sizeof(mem_range))) != OK) return r; priv(rp)->s_flags |= CHECK_MEM; /* Check memory mappings */ i= priv(rp)->s_nr_mem_range; if (i >= NR_MEM_RANGE) { printf("do_privctl: %d already has %d mem ranges.\n", rp->p_endpoint, i); return ENOMEM; } priv(rp)->s_mem_tab[i].mr_base= mem_range.mr_base; priv(rp)->s_mem_tab[i].mr_limit= mem_range.mr_limit; priv(rp)->s_nr_mem_range++; return OK; case SYS_PRIV_ADD_IRQ: if (RTS_ISSET(rp, RTS_NO_PRIV)) return(EPERM); /* Only system processes get IRQs? */ if (!(priv(rp)->s_flags & SYS_PROC)) return EPERM; data_copy(caller->p_endpoint, (vir_bytes) m_ptr->CTL_ARG_PTR, KERNEL, (vir_bytes) &irq, sizeof(irq)); priv(rp)->s_flags |= CHECK_IRQ; /* Check IRQs */ i= priv(rp)->s_nr_irq; if (i >= NR_IRQ) { printf("do_privctl: %d already has %d irq's.\n", rp->p_endpoint, i); return ENOMEM; } priv(rp)->s_irq_tab[i]= irq; priv(rp)->s_nr_irq++; return OK; case SYS_PRIV_QUERY_MEM: { phys_bytes addr, limit; struct priv *sp; /* See if a certain process is allowed to map in certain physical * memory. */ addr = (phys_bytes) m_ptr->CTL_PHYSSTART; limit = addr + (phys_bytes) m_ptr->CTL_PHYSLEN - 1; if(limit < addr) return EPERM; if(!(sp = priv(rp))) return EPERM; if (!(sp->s_flags & SYS_PROC)) return EPERM; for(i = 0; i < sp->s_nr_mem_range; i++) { if(addr >= sp->s_mem_tab[i].mr_base && limit <= sp->s_mem_tab[i].mr_limit) return OK; } return EPERM; } default: printf("do_privctl: bad request %d\n", m_ptr->CTL_REQUEST); return EINVAL; } } #endif /* USE_PRIVCTL */
vsilyaev/tensorflow
tensorflow/core/kernels/transpose_op.h
<reponame>vsilyaev/tensorflow #ifndef TENSORFLOW_KERNELS_TRANSPOSE_OP_H_ #define TENSORFLOW_KERNELS_TRANSPOSE_OP_H_ #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/tensor_types.h" namespace tensorflow { template <typename Device, typename T> class TransposeOp : public OpKernel { public: explicit TransposeOp(OpKernelConstruction* context); void Compute(OpKernelContext* context) override; }; } // namespace tensorflow #endif // TENSORFLOW_KERNELS_TRANSPOSE_OP_H_
EmileRouxTriton/player-sdk
src/lib/dojo/cldr/nls/en-au/japanese.js
<reponame>EmileRouxTriton/player-sdk<gh_stars>100-1000 define( //begin v1.x content { "dateFormat-short": "d/MM/yy GGGGG", "dateFormat-medium": "dd/MM/y G", "dateFormat-long": "d MMMM y G", "dateFormat-full": "EEEE, d MMMM y G" } //end v1.x content );
Vilsol/NMSWrapper
src/main/java/me/vilsol/nmswrapper/wraps/unparsed/NMSEnchantmentProtection.java
package me.vilsol.nmswrapper.wraps.unparsed; import me.vilsol.nmswrapper.*; import me.vilsol.nmswrapper.reflections.*; import me.vilsol.nmswrapper.wraps.*; @ReflectiveClass(name = "EnchantmentProtection") public class NMSEnchantmentProtection extends NMSEnchantment { public NMSEnchantmentProtection(Object nmsObject){ super(nmsObject); } public NMSEnchantmentProtection(int i, NMSMinecraftKey minecraftKey, int i1, int i2){ super("EnchantmentProtection", new Object[]{int.class, NMSMinecraftKey.class, int.class, int.class}, new Object[]{i, minecraftKey, i1, i2}); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EnchantmentProtection#a(net.minecraft.server.v1_9_R1.Entity, double) */ @ReflectiveMethod(name = "a", types = {NMSEntity.class, double.class}) public double a(NMSEntity entity, double d){ return (double) NMSWrapper.getInstance().exec(nmsObject, entity, d); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EnchantmentProtection#b(int) */ @ReflectiveMethod(name = "b", types = {int.class}) public int b(int i){ return (int) NMSWrapper.getInstance().exec(nmsObject, i); } /** * @see net.minecraft.server.v1_9_R1.EnchantmentProtection#getMaxLevel() */ @ReflectiveMethod(name = "getMaxLevel", types = {}) public int getMaxLevel(){ return (int) NMSWrapper.getInstance().exec(nmsObject); } }
ejezie/La-Marzocco
assets/js/contact.js
$(document).ready(function(){ $("#submitEnquiry").click(function(){ var enquiryMessage = $("#enquiryMessage").val(); if(enquiryMessage.trim() != ''){ getUserProfile(function(profile_res){ console.log("profile_res : " , profile_res) if(profile_res.status == 200){ var fname = safeAccess(["data","user","first_name"],profile_res,"") var lname = safeAccess(["data","user","last_name"],profile_res,"") var email = safeAccess(["data","user","email"],profile_res,"") var message = "First Name : "+fname+" \nLast Name : "+lname+" \nEmail Id : "+email+" \nEnquiry : "+enquiryMessage console.log(message) sendEnquiryMail(message,function(res){ console.log("res : " , res) if(res.data.status == true){ notifySuccess("Enquiry Sent") $('#enquiryMessage').val(''); }else{ notifyError("Something went wrong") } }) } }) }else{ notifyError("Enter valid message") } }) });
MarianMacik/thorntail
plugins/gradle/tooling-api/src/main/java/org/wildfly/swarm/plugin/gradle/DependencyDescriptor.java
/* * Copyright 2018 Red Hat, Inc, and individual contributors. * * 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.wildfly.swarm.plugin.gradle; import java.io.File; import java.io.Serializable; import org.gradle.tooling.model.Dependency; import org.gradle.tooling.model.GradleModuleVersion; import org.wildfly.swarm.tools.ArtifactSpec; /** * The {@code DependencyDescriptor} type represents a dependency's coordinates that can serialized over the wire. This is * required for scenarios where integrations happen via Gradle's tooling API (e.g., Arquillian adapters). It would be nice * if the actual ArtifactSpec type had a parent interface so that we can avoid having to use this scheme of doing things. */ public interface DependencyDescriptor extends GradleModuleVersion, Dependency, Serializable { /** * Get the scope (compile, runtime, test, etc.) for this artifact descriptor. */ default String getScope() { return "compile"; } /** * Get the packaging type associated with this dependency. */ String getType(); /** * Get the classifier associated with this dependency. */ String getClassifier(); /** * Get the location of the resolved artifact (if available). */ File getFile(); /** * Translate this descriptor in to a reference of {@link ArtifactSpec}. */ default ArtifactSpec toArtifactSpec() { return new ArtifactSpec(getScope(), getGroup(), getName(), getVersion(), getType(), getClassifier(), getFile()); } }
Elliot-Coupe/qiskit-terra
qiskit/opflow/list_ops/__init__.py
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. r""" List Operators (:mod:`qiskit.opflow.list_ops`) ============================================================== .. currentmodule:: qiskit.opflow.list_ops List Operators are classes for storing and manipulating lists of Operators, State functions, or Measurements, and include some rule or ``combo_fn`` defining how the Operator functions of the list constituents should be combined to form to cumulative Operator function of the :class:`ListOp`. For example, a :class:`SummedOp` has an addition-based ``combo_fn``, so once the Operators in its list are evaluated against some bitstring to produce a list of results, we know to add up those results to produce the final result of the :class:`SummedOp`'s evaluation. In theory, this ``combo_fn`` can be any function over classical complex values, but for convenience we've chosen for them to be defined over NumPy arrays and values. This way, large numbers of evaluations, such as after calling :meth:`~ListOp.to_matrix` on the list constituents, can be efficiently combined. While the combination function is defined over classical values, it should be understood as the operation by which each Operators' underlying function is combined to form the underlying Operator function of the :class:`ListOp`. In this way, the :mod:`.list_ops` are the basis for constructing large and sophisticated Operators, State Functions, and Measurements. The base :class:`ListOp` class is particularly interesting, as its ``combo_fn`` is "the identity list Operation". Meaning, if we understand the ``combo_fn`` as a function from a list of complex values to some output, one such function is returning the list as\-is. This is powerful for constructing compact hierarchical Operators which return many measurements in multiple dimensional lists. For example, if we want to estimate the gradient of some Observable measurement with respect to some parameters in the State function, we can construct separate evaluation Operators for each parameter's gradient which we must keep track of ourselves in a list, or we can construct a single :class:`ListOp` containing the evaluation Operators for each parameter, so the :meth:`~ListOp.eval` function returns the full gradient vector. Another excellent example of this power is constructing a Quantum kernel matrix: .. code-block:: data_sfn_list_op = ListOp(data_circuit_state_fns) qkernel_op_circuits = ~data_sfn_list_op @ data_sfn_list_op qkernel_sampled = CircuitSampler(backend).convert(qkernel_op_circuits) qkernel_sampled.eval() This will return the two dimensional Quantum kernel matrix, where each element is the inner product of some pair of the data State functions, or in other terms, a measurement of one data :class:`~.state_fns.CircuitStateFn` by another. You'll encounter the :class:`ListOp` subclasses (:class:`SummedOp`, :class:`ComposedOp`, or :class:`TensoredOp`) more often as lazy results of Operator construction operations than as something you need to explicitly construct. Any time we don't know how to efficiently add, compose, or tensor two :mod:`.primitive_ops` or :mod:`.state_fns` together, they're returned in a :class:`SummedOp`, :class:`ComposedOp`, or :class:`TensoredOp`, respectively, so we can still work with their combined function and perhaps convert them into an efficiently combine-able format later. Note: Combination functions do not always behave predictably, and you must understand the conversions you're making when you working with :mod:`.list_ops`. Most notably - sampling a sum of two circuits on Quantum hardware does not incorporate interference between the wavefunctions! In this case, we're sending our State functions through a depolarizing channel before adding them, rather than adding them directly before the measurement. List Operators =============== .. autosummary:: :toctree: ../stubs/ :nosignatures: ListOp ComposedOp SummedOp TensoredOp """ from .list_op import ListOp from .summed_op import SummedOp from .composed_op import ComposedOp from .tensored_op import TensoredOp __all__ = ["ListOp", "SummedOp", "TensoredOp", "ComposedOp"]
iSYSTEMLabs/testIDEA
testidea/si.isystem.itest.plugin.core/src/si/isystem/itest/common/SimpleProgressMonitor.java
package si.isystem.itest.common; import org.eclipse.core.runtime.IProgressMonitor; public class SimpleProgressMonitor implements IProgressMonitor { private boolean m_isCanceled = false; @Override public void beginTask(String name, int totalWork) { m_isCanceled = false; } @Override public void done() {} @Override public void internalWorked(double work) {} @Override public boolean isCanceled() { return m_isCanceled; } @Override public void setCanceled(boolean isCanceled) { m_isCanceled = isCanceled; } @Override public void setTaskName(String name) {} @Override public void subTask(String name) {} @Override public void worked(int work) {} }
burberius/eve-esi
src/test/java/net/troja/eve/esi/model/SystemPlanetTest.java
<filename>src/test/java/net/troja/eve/esi/model/SystemPlanetTest.java /* * EVE Swagger Interface * An OpenAPI for EVE Online * * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package net.troja.eve.esi.model; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; /** * Model tests for SystemPlanet */ public class SystemPlanetTest { private final SystemPlanet model = new SystemPlanet(); /** * Model tests for SystemPlanet */ @Test public void testSystemPlanet() { // TODO: test SystemPlanet } /** * Test the property 'planetId' */ @Test public void planetIdTest() { // TODO: test planetId } /** * Test the property 'moons' */ @Test public void moonsTest() { // TODO: test moons } /** * Test the property 'asteroidBelts' */ @Test public void asteroidBeltsTest() { // TODO: test asteroidBelts } }