text
stringlengths
1
1.05M
def is_palindrome(string): # reverse the string rev_string = string[::-1] # check if the string is equal to its reverse if (string == rev_string): return True return False # Example usage: result = is_palindrome('racecar') # result = True
package gate import ( "encoding/json" "fmt" "net/http" "net/url" "testing" "time" . "github.com/strengthening/goghostex" ) func TestSwap_GetExchangeRule(t *testing.T) { config := &APIConfig{ Endpoint: "", HttpClient: &http.Client{ Transport: &http.Transport{ Proxy: func(req *http.Request) (*url.URL, error) { return url.Parse("socks5://127.0.0.1:1090") }, }, }, ApiKey: "", ApiSecretKey: "", Location: time.Now().Location(), } gateCli := New(config) //if rule, resp, err := gateCli.Swap.GetExchangeRule(Pair{Currency{"AMPL", ""}, USDT}); err != nil { // t.Error(err) // return //} else { // fmt.Print(rule) // fmt.Print(string(resp)) //} //if rule, resp, err := gateCli.Swap.GetTicker( // Pair{Currency{"AMPL", ""}, USDT}, //); err != nil { // t.Error(err) // return //} else { // fmt.Print(rule) // fmt.Print(string(resp)) //} //if depth, resp, err := gateCli.Swap.GetDepth( // Pair{Currency{"AMPL", ""}, USDT}, // 50, //); err != nil { // t.Error(err) // return //} else { // fmt.Print(depth) // fmt.Print(string(resp)) //} //if klines, resp, err := gateCli.Swap.GetKline( // Pair{Currency{"AMPL", ""}, USDT}, // KLINE_PERIOD_1MIN, // 50, // 0, //); err != nil { // t.Error(err) // return //} else { // body, _ := json.Marshal(klines) // fmt.Print(string(body)) // fmt.Print(string(resp)) //} //if fees, resp, err := gateCli.Swap.GetFundingFees( // Pair{Currency{"AMPL", ""}, USDT}, //); err != nil { // t.Error(err) // return //} else { // body, _ := json.Marshal(fees) // fmt.Print(string(body)) // fmt.Print(string(resp)) //} //if fees, err := gateCli.Swap.GetFundingFee( // Pair{Currency{"AMPL", ""}, USDT}, //); err != nil { // t.Error(err) // return //} else { // body, _ := json.Marshal(fees) // fmt.Print(string(body)) // //fmt.Print(string(resp)) //} if _, resp, err := gateCli.Swap.GetAccount(); err != nil { t.Error(err) return } else { //body, _ := json.Marshal(fees) fmt.Print(string(resp)) //fmt.Print(string(resp)) } } func TestSwap_TradeAPI(t *testing.T) { config := &APIConfig{ Endpoint: "", HttpClient: &http.Client{ Transport: &http.Transport{ Proxy: func(req *http.Request) (*url.URL, error) { return url.Parse("socks5://127.0.0.1:1090") }, }, }, ApiKey: "", ApiSecretKey: "", Location: time.Now().Location(), } gateCli := New(config) pair := BTC_USDT rule, _, err := gateCli.Swap.GetTicker(pair) if err != nil { t.Error(err) return } order := &SwapOrder{ Price: rule.Last * 1.1, Amount: 0.001, PlaceType: NORMAL, Type: OPEN_LONG, Pair: pair, Exchange: GATE, } if resp, err := gateCli.Swap.PlaceOrder(order); err != nil { t.Error(err) return } else { fmt.Println("~~~~~~~~~~~~") fmt.Println(string(resp)) fmt.Println(order) } if resp, err := gateCli.Swap.GetOrder(order); err != nil { t.Error(err) return } else { fmt.Println("~~~~~~~~~~~~") fmt.Println(string(resp)) fmt.Println(order) orderRaw, _ := json.Marshal(order) fmt.Println(string(orderRaw)) } //time.Sleep(5*time.Second) //if resp, err := gateCli.Swap.GetOrder(order); err != nil { // t.Error(err) // return //} else { // fmt.Println("~~~~~~~~~~~~") // fmt.Println(string(resp)) // fmt.Println(err) //} }
<filename>container/src/main/java/no/mnemonic/commons/container/ComponentNode.java package no.mnemonic.commons.container; import no.mnemonic.commons.component.ComponentConfigurationException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; class ComponentNode { private final String objectName; private final Object object; private boolean started; private Set<ComponentNode> initializationDependencies = new HashSet<>(); private Set<ComponentNode> destructionDependencies = new HashSet<>(); ComponentNode(String objectName, Object object) { this.object = object; this.objectName = objectName; } @Override public String toString() { return String.format("%s / %s", objectName, object.getClass().getName()); } Object getObject() { return object; } String getObjectName() { return objectName; } boolean isStarted() { return started; } void setStarted(boolean set) { this.started = set; } /** * @return set of nodes which should be destroyed before this node */ Set<ComponentNode> getDestructionDependencies() { return this.destructionDependencies; } /** * @return set of nodes which should be initialized before this node */ Set<ComponentNode> getInitializationDependencies() { return this.initializationDependencies; } /** * Add init dependency to n, i.e. n should initialize before this node * * @param n node to dependency */ void addInitializationDependency(ComponentNode n) { List<ComponentNode> depTree = n.resolveInitializationDependencyPath(this); if (depTree != null) { throwCircularDependencyException(depTree); } this.initializationDependencies.add(n); } /** * Add destroy dependency to n, i.e. n should be destroyed before this node * * @param n node to dependency */ void addDestructionDependency(ComponentNode n) { List<ComponentNode> depTree = n.resolveDestructionDependencyPath(this); if (depTree != null) { throwCircularDependencyException(depTree); } this.destructionDependencies.add(n); } //private methods /** * Check if node n is set to initialize before this node * * @param n node to check * @return initialization dependency path back to node n */ private List<ComponentNode> resolveInitializationDependencyPath(ComponentNode n) { List<ComponentNode> dependencyPath = new ArrayList<>(); dependencyPath.add(this); // if n is set to initialize after this, then return true if (this.getInitializationDependencies().contains(n)) { dependencyPath.add(n); return dependencyPath; } // if any node which is set to initialize before this node // (i.e. this node is initialized after that node) // also is set to initialize before n, then // return true for (ComponentNode previous : this.getInitializationDependencies()) { List<ComponentNode> prevDependencyPath = previous.resolveInitializationDependencyPath(n); if (prevDependencyPath != null) { dependencyPath.addAll(prevDependencyPath); return dependencyPath; } } // if not, there is no indication that we are set to start before n return null; } /** * Check if node n is set to destroy before this node * * @param n node to check * @return destruction dependency path back to node n */ private List<ComponentNode> resolveDestructionDependencyPath(ComponentNode n) { List<ComponentNode> dependencyPath = new ArrayList<>(); dependencyPath.add(this); // if n is listed to destroy before this, then return true if (this.getDestructionDependencies().contains(n)) { dependencyPath.add(n); return dependencyPath; } // if any node which is set to destroy before this node (we have a destroy dependency on) // has a destroy dependency on n, then we also have a destroy dependency on n. for (ComponentNode previous : this.getDestructionDependencies()) { List<ComponentNode> prevDependencyPath = previous.resolveDestructionDependencyPath(n); if (prevDependencyPath != null) { dependencyPath.addAll(prevDependencyPath); return dependencyPath; } } // if not, there is no indication that n is set to destroy before us return null; } private void throwCircularDependencyException(List<ComponentNode> depTree) { StringBuilder buf = new StringBuilder("Circular dependency: "); buf.append(this.getObjectName()); for (ComponentNode nn : depTree) { buf.append(" -> ").append(nn.getObjectName()); } throw new ComponentConfigurationException(buf.toString()); } }
<filename>app/src/main/java/com/landenlabs/all_uiTest/FragGridViewDemo.java package com.landenlabs.all_uiTest; /* * Copyright (C) 2019 <NAME> (<EMAIL>) * * 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 android.content.Context; import android.content.res.ColorStateList; import android.graphics.Color; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.AnimatedVectorDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.util.TypedValue; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.FrameLayout; import android.widget.GridView; import android.widget.ImageView; import android.widget.RadioGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import androidx.transition.AutoTransition; import androidx.transition.ChangeBounds; import androidx.transition.ChangeTransform; import androidx.transition.TransitionManager; import androidx.transition.TransitionSet; import java.util.Locale; import utils.TextViewExt1; import utils.Translation; /** * Fragment demonstrate GridView with expanding cell and callouts. */ public class FragGridViewDemo extends FragBottomNavBase { private GridView gridview; private FrameLayout overlay; private RadioGroup rg; private int nextElevation = 1; private static final long ANIM_MILLI = 2000; @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, R.layout.frag_gridview_demo); setBarTitle("GridView Expanding Cell Demo"); gridview = root.findViewById(R.id.page1_gridview); gridview.setClipChildren(false); gridview.setAdapter(new Page1Adapter(requireActivity())); overlay = root.findViewById(R.id.page1_overlay); rg = root.findViewById(R.id.page1_rg); return root; } @Override public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) { menu.clear(); // See setHasOptionsMen(true) } private ColorStateList colorRed = new ColorStateList( new int[][]{ new int[]{}}, new int[]{ 0xffff0000 } // RED ); private ColorStateList colorGreen = new ColorStateList( new int[][]{ new int[]{}}, new int[]{ 0xff00ff00 } // GREEN ); private void doAction(View view, int pos) { overlay.removeAllViews(); switch (rg.getCheckedRadioButtonId()) { case R.id.page1_tagRB: if (view.getBackground() == null) { // Draw animated gradient of two possible colors. view.setBackgroundResource(R.drawable.bg_anim_gradient); view.setBackgroundTintList(Math.random() > 0.5 ? colorRed : colorGreen); ((AnimatedVectorDrawable) view.getBackground()).start(); } else { view.setBackground(null); } break; case R.id.page1_grow1RB: expandView(view, pos, 1); break; case R.id.page1_grow2RB: expandView(view, pos, 2); break; case R.id.page1_detailsRB: openDetailView(view, pos); break; case R.id.page1_resetRB: gridview.setAdapter(new Page1Adapter(requireActivity())); gridview.requestLayout(); nextElevation = 0; break; } } /** * Animate expansion of tapped view cell. */ private void expandView(View view, int pos, int expandStyle) { View rootView = view.getRootView(); int numCol = TestData.WxData.columns(); int numRow = TestData.WXDATA.length; int col = pos % numCol; int row = pos / numCol; GridView.LayoutParams params = (GridView.LayoutParams) view.getLayoutParams(); // Record layout change and animate it slowly TransitionSet transitionSet = new TransitionSet(); transitionSet.setDuration(ANIM_MILLI); transitionSet.addTransition(new AutoTransition()); transitionSet.addTransition(new Translation()); transitionSet.addTransition(new ChangeTransform()); transitionSet.addTransition(new ChangeBounds()); TransitionManager.beginDelayedTransition((ViewGroup) rootView, transitionSet); if (expandStyle == 1) { float growPercent = 1.2f; params.width = Math.round(view.getWidth() * growPercent); params.height = Math.round(view.getHeight() * growPercent); // Change origin if (col + 1 == numCol) { view.setTranslationX(view.getWidth() - params.width); gridview.setClipChildren(false); } else if (row + 1 == numRow) { view.setTranslationY(view.getHeight() - params.height); gridview.setClipChildren(false); } } else { float growPercent = 0.2f; view.setPivotX( (col < numCol/2) ? 0 : view.getWidth()); view.setPivotY( (row < numRow/2) ? 0 : view.getHeight()); view.setScaleX(view.getScaleX() + growPercent); view.setScaleY(view.getScaleY() + growPercent); } // Change color and elevation view.setBackgroundResource(R.drawable.bg_red); view.setElevation(nextElevation); nextElevation += 8; view.requestLayout(); view.invalidate(); } private void openDetailView(View view, int pos) { int numCol = TestData.WxData.columns(); int col = pos % numCol; int row = pos / numCol; Rect viewRect = new Rect(); view.getGlobalVisibleRect(viewRect); overlay.removeAllViews(); Rect overlayRect = new Rect(); overlay.getGlobalVisibleRect(overlayRect); Rect detailRect = new Rect(viewRect.left - overlayRect.left, viewRect.top - overlayRect.top, viewRect.right - overlayRect.left, viewRect.bottom - overlayRect.top); TextViewExt1 detailTv = new TextViewExt1(getContext()); detailTv.setMarker(R.drawable.bg_white_varrow); detailTv.setText(TestData.WXDATA[row].getDetails(col)); detailTv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18); detailTv.setTextColor(Color.WHITE); Drawable icon = detailTv.getContext().getDrawable(R.drawable.wx_sun_30d); detailTv.setForeground(icon); detailTv.setForegroundGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL); int padPx = 20; detailTv.setPadding(padPx, 40, padPx, 150); int detailWidthPx = 500; int detailHeightPx = ViewGroup.LayoutParams.WRAP_CONTENT; overlay.addView(detailTv, detailWidthPx, detailHeightPx); int margin = 10; int detailLeft = Math.max(margin, detailRect.centerX() - detailWidthPx / 2); if (detailLeft + detailHeightPx > overlayRect.width() - margin) { detailLeft = overlayRect.width() - detailHeightPx - margin; } detailTv.setX(detailLeft); detailTv.setY(detailRect.bottom - padPx); float markerCenterShiftX = viewRect.centerX() - (detailLeft + detailWidthPx/2f + overlayRect.left); detailTv.setPointer(markerCenterShiftX); } // ============================================================================================= // Adapter required to fill GridView cell values. private final static int leftCellPadPx = 10; private final static int rightCellPadPx = 10; @SuppressWarnings("Convert2Lambda") class Page1Adapter extends BaseAdapter { private final Context mContext; private final int rowHeightPx; Page1Adapter(Context context) { mContext = context; rowHeightPx = context.getResources().getDimensionPixelSize(R.dimen.page_row_height); } public int getCount() { return TestData.size(); } public Object getItem(int position) { return null; } public long getItemId(int position) { return 0; } // Create view cell per row per column using WxHourlyData as data source. public View getView(int position, View convertView, ViewGroup parent) { View view; GridView.LayoutParams lp = new GridView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, rowHeightPx); int topCellPadPx = 0; int row = position / TestData.WxData.columns(); switch (position % TestData.WxData.columns()) { default: case TestData.COL_TIME: view = makeText(TestData.WXDATA[row].time, position); break; case TestData.COL_TEMP: view = makeText(TestData.WXDATA[row].temp, position); break; case TestData.COL_WxICON: view = makeImage(TestData.WXDATA[row].wxicon, position); break; case TestData.COL_RAIN: view = makeRain(TestData.WXDATA[row].rainPercent, position); topCellPadPx = 50; // Special case to force icon to slide down. break; } view.setLayoutParams(lp); view.setPadding(leftCellPadPx, topCellPadPx, rightCellPadPx, 0); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { doAction(view, position); } }); return view; } @SuppressWarnings("unused") private TextView makeText(String text, final int pos) { TextView textView = new TextView(mContext); textView.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24); textView.setText(text); textView.setTypeface(null, Typeface.BOLD); textView.setTextColor(Color.WHITE); return textView; } @SuppressWarnings("unused") private ImageView makeImage(int drawableRes, final int pos) { ImageView imageView = new ImageView(mContext); imageView.setImageResource(drawableRes); return imageView; } private View makeRain(float percentRain, final int pos) { String text = String.format(Locale.US, "%.0f%%", percentRain); boolean showNone = percentRain < 5; TextView textView = makeText(showNone ? "None" : text, pos); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, showNone ? 16:20); int iconRes = percentRain > 50 ? R.drawable.wx_mixed : R.drawable.wx_rain; Drawable icon = ContextCompat.getDrawable(mContext, iconRes); textView.setCompoundDrawablePadding(40); textView.setCompoundDrawablesRelativeWithIntrinsicBounds(icon, null, null, null); return textView; } } }
<reponame>tribock/orbos package resources import ( "fmt" "github.com/caos/orbos/mntr" "github.com/caos/orbos/pkg/kubernetes" "github.com/caos/orbos/pkg/tree" ) type AdaptFuncToEnsure func(monitor mntr.Monitor, desired *tree.Tree, current *tree.Tree) (QueryFunc, error) type AdaptFuncToDelete func(monitor mntr.Monitor, desired *tree.Tree, current *tree.Tree) (DestroyFunc, error) type Querier interface { Query(k8sClient kubernetes.ClientInt, queried map[string]interface{}) (EnsureFunc, error) } type QueryFunc func(k8sClient kubernetes.ClientInt, queried map[string]interface{}) (EnsureFunc, error) func (q QueryFunc) Query(k8sClient kubernetes.ClientInt, queried map[string]interface{}) (EnsureFunc, error) { return q(k8sClient, queried) } type Ensurer interface { Ensure(k8sClient kubernetes.ClientInt) error } type EnsureFunc func(k8sClient kubernetes.ClientInt) error func (e EnsureFunc) Ensure(k8sClient kubernetes.ClientInt) error { return e(k8sClient) } type Destroyer interface { Destroy(k8sClient kubernetes.ClientInt) error } type DestroyFunc func(k8sClient kubernetes.ClientInt) error func (d DestroyFunc) Destroy(k8sClient kubernetes.ClientInt) error { return d(k8sClient) } type TestableDestroyer struct { DestroyFunc Arguments interface{} } func ToTestableDestroy(destroyFunc DestroyFunc, adapterArguments interface{}) *TestableDestroyer { return &TestableDestroyer{ DestroyFunc: destroyFunc, Arguments: adapterArguments, } } type TestableQuerier struct { QueryFunc Arguments interface{} } func ToTestableQuerier(queryFunc QueryFunc, adapterArguments interface{}) *TestableQuerier { return &TestableQuerier{ QueryFunc: queryFunc, Arguments: adapterArguments, } } func WrapFuncs(monitor mntr.Monitor, query QueryFunc, destroy DestroyFunc) (QueryFunc, DestroyFunc, error) { return func(client kubernetes.ClientInt, queried map[string]interface{}) (ensureFunc EnsureFunc, err error) { monitor.Info("querying...") ensurer, err := query(client, queried) if err != nil { return nil, fmt.Errorf("error while querying: %w", err) } monitor.Info("queried") return func(k8sClient kubernetes.ClientInt) error { monitor.Info("ensuring...") if err := ensurer.Ensure(k8sClient); err != nil { return fmt.Errorf("error while destroying: %w", err) } monitor.Info("ensured") return nil }, nil }, func(client kubernetes.ClientInt) error { monitor.Info("destroying...") err := destroy(client) if err != nil { return fmt.Errorf("error while destroying: %w", err) } monitor.Info("destroyed") return nil }, nil } var _ QueriersReducerFunc = QueriersToEnsurer type QueriersReducerFunc func(monitor mntr.Monitor, infoLogs bool, queriers []Querier, k8sClient kubernetes.ClientInt, queried map[string]interface{}) (EnsureFunc, error) func QueriersToEnsurer(monitor mntr.Monitor, infoLogs bool, queriers []Querier, k8sClient kubernetes.ClientInt, queried map[string]interface{}) (EnsureFunc, error) { if infoLogs { monitor.Info("querying...") } else { monitor.Debug("querying...") } ensurers := make([]EnsureFunc, 0) for _, querier := range queriers { ensurer, err := querier.Query(k8sClient, queried) if err != nil { return nil, fmt.Errorf("error while querying: %w", err) } ensurers = append(ensurers, ensurer) } if infoLogs { monitor.Info("queried") } else { monitor.Debug("queried") } return func(k8sClient kubernetes.ClientInt) error { if infoLogs { monitor.Info("ensuring...") } else { monitor.Debug("ensuring...") } for _, ensurer := range ensurers { if err := ensurer.Ensure(k8sClient); err != nil { return fmt.Errorf("error while ensuring: %w", err) } } if infoLogs { monitor.Info("ensured") } else { monitor.Debug("ensured") } return nil }, nil } func ReduceDestroyers(monitor mntr.Monitor, destroyers []Destroyer) DestroyFunc { return func(k8sClient kubernetes.ClientInt) error { monitor.Info("destroying...") for _, destroyer := range destroyers { if err := destroyer.Destroy(k8sClient); err != nil { return fmt.Errorf("error while destroying: %w", err) } } monitor.Info("destroyed") return nil } } func DestroyerToQuerier(destroyer Destroyer) QueryFunc { return func(k8sClient kubernetes.ClientInt, queried map[string]interface{}) (ensureFunc EnsureFunc, err error) { return destroyer.Destroy, nil } } func DestroyersToQueryFuncs(destroyers []Destroyer) []QueryFunc { queriers := make([]QueryFunc, len(destroyers)) for i, destroyer := range destroyers { queriers[i] = DestroyerToQuerier(destroyer) } return queriers }
# install zsh apt install zsh # make zsh default shell if it not the case if echo $SHELL | grep -qv '/usr/bin/zsh'; then chsh -s $(which zsh); fi # install zsh ZSH=~/.oh-my-zsh if [ -d "$ZSH" ]; then echo "Oh My Zsh is already installed. Skipping.." else echo "Installing Oh My Zsh..." curl -L http://install.ohmyz.sh | sh fi # install zsh-autosuggestions if [ -d ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions ]; then echo "zsh-autosuggestions is already installed. Skipping.." else git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions fi # install powerlevel10k if [ -d ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/themes/powerlevel10k ]; then echo "powerlevel10k is already installed. Skipping.." else git clone --depth=1 https://github.com/romkatv/powerlevel10k.git ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/themes/powerlevel10k fi # link configs ln -fs $(pwd)/.zshrc ~/.zshrc ln -fs $(pwd)/.p10k.zsh ~/.p10k.zsh
<filename>controllers/booksController.js const db = require("../models"); // Defining methods for the booksController module.exports = { findAll: function(req, res) { db.Book .find(req.query) .then(dbModel => res.json(dbModel)) .catch(err => res.status(422).json(err)); }, create: function(req, res) { db.Book .findOneAndUpdate( {id: req.body.id}, req.body, {upsert: true, new: true} ) .then(dbModel => res.json(dbModel)) .catch(err => res.status(422).json(err)); }, remove: function(req, res) { console.log(req.params.id) db.Book .deleteOne({ id: req.params.id }) .then(dbModel => res.json(dbModel)) .catch(err => res.status(422).json(err)); } };
# From https://gist.github.com/ccsevers/10295174 import os.path import numpy as np from .utils import take_subset from pylearn2.datasets.dataset import Dataset from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix from pylearn2.utils.iteration import (SequentialSubsetIterator, FiniteDatasetIterator, resolve_iterator_class) import functools import logging import numpy import warnings from pylearn2.space import CompositeSpace, Conv2DSpace, VectorSpace, IndexSpace from pylearn2.utils import safe_zip try: import scipy.sparse except ImportError: warnings.warn("Couldn't import scipy.sparse") import theano import gzip floatX = theano.config.floatX logger = logging.getLogger(__name__) class SparseExpanderDataset(Dataset): """ SparseExpanderDataset takes a numpy/scipy sparse matrix and calls .todense() as the batches are passed out of the iterator. """ def __init__(self, X_path=None, y_path=None, from_scipy_sparse_dataset=None, zipped_npy=False, means_path=None, stds_path=None, start_fraction=None, end_fraction=None, start=None, stop=None): self.X_path = X_path self.y_path = y_path if self.X_path != None: if zipped_npy == True: logger.info('... loading sparse data set from a zip npy file') self.X = scipy.sparse.csr_matrix( numpy.load(gzip.open(X_path)), dtype=floatX) else: logger.info('... loading sparse data set from a npy file') self.X = scipy.sparse.csr_matrix( numpy.load(X_path).item(), dtype=floatX) else: logger.info('... building from given sparse dataset') self.X = from_scipy_sparse_dataset.astype(floatX) if self.y_path != None: if zipped_npy == True: logger.info('... loading sparse data set from a zip npy file') #self.y = scipy.sparse.csr_matrix( # numpy.load(gzip.open(y_path)), dtype=floatX).todense() self.y = numpy.load(gzip.open(y_path)) if not isinstance(self.y, np.ndarray): print("calling y.item") self.y = y.item() else: logger.info('... loading sparse data set from a npy file') self.y = numpy.load(y_path) if not isinstance(self.y, np.ndarray): print("calling y.item") self.y = self.y.item() # We load y as a sparse matrix, but convert it to a dense array, # because otherwise MLP.mean_of_targets breaks. orig_shape = self.y.shape if scipy.sparse.issparse(self.y): self.y = np.asarray(self.y.todense()) # Only make this a column vector if it's not one-hot. if 1 in orig_shape or len(orig_shape) == 1: nrow = np.max(orig_shape) self.y = self.y.reshape((nrow, 1)) else: self.y = None self.y = self.y.astype(floatX) self.X, self.y = take_subset(self.X, self.y, start_fraction, end_fraction, start, stop) self.data_n_rows = self.X.shape[0] self.num_examples = self.data_n_rows self.fancy = False self.stochastic = False X_space = VectorSpace(dim=self.X.shape[1]) X_source = 'features' if y_path is None: space = X_space source = X_source else: if self.y.ndim == 1: dim = 1 else: dim = self.y.shape[-1] y_space = VectorSpace(dim=dim) y_source = 'targets' space = CompositeSpace((X_space, y_space)) source = (X_source, y_source) if means_path is not None: self.means = np.load(means_path) if stds_path is not None: self.stds = np.load(stds_path) self.data_specs = (space, source) self.X_space = X_space self._iter_data_specs = (self.X_space, 'features') def get_design_matrix(self): return self.X def get_batch_design(self, batch_size, include_labels=False): """ method inherited from Dataset """ self.iterator(mode='sequential', batch_size=batch_size) return self.next() def get_batch_topo(self, batch_size): """ method inherited from Dataset """ raise NotImplementedError('Not implemented for sparse dataset') def get_data_specs(self): """ Returns the data_specs specifying how the data is internally stored. This is the format the data returned by `self.get_data()` will be. """ return self.data_specs def get_data(self): """ Returns ------- data : numpy matrix or 2-tuple of matrices Returns all the data, as it is internally stored. The definition and format of these data are described in `self.get_data_specs()`. """ if self.y is None: return self.X else: return (self.X, self.y) def get_num_examples(self): return self.X.shape[0] @functools.wraps(Dataset.iterator) def iterator(self, mode=None, batch_size=None, num_batches=None, topo=None, targets=None, rng=None, data_specs=None, return_tuple=False): """ method inherited from Dataset """ self.mode = mode self.batch_size = batch_size self._targets = targets self._return_tuple = return_tuple if data_specs is None: data_specs = self._iter_data_specs # If there is a view_converter, we have to use it to convert # the stored data for "features" into one that the iterator # can return. # if space, source = data_specs if isinstance(space, CompositeSpace): sub_spaces = space.components sub_sources = source else: sub_spaces = (space,) sub_sources = (source,) convert = [] for sp, src in safe_zip(sub_spaces, sub_sources): if src == 'features': conv_fn = lambda x: x.todense() elif src == 'targets': conv_fn = lambda x: x else: conv_fn = None convert.append(conv_fn) if mode is None: if hasattr(self, '_iter_subset_class'): mode = self._iter_subset_class else: raise ValueError('iteration mode not provided and no default ' 'mode set for %s' % str(self)) else: mode = resolve_iterator_class(mode) return FiniteDatasetIterator(self, mode(self.X.shape[0], batch_size, num_batches, rng), data_specs=data_specs, return_tuple=return_tuple, convert=convert) def __iter__(self): return self def next(self): indx = self.subset_iterator.next() try: rval = self.X[indx].todense() if self.center: rval = rval - self.means if self.scale: rval = rval / self.stds except IndexError: # the ind of minibatch goes beyond the boundary import ipdb; ipdb.set_trace() rval = tuple(rval) if not self._return_tuple and len(rval) == 1: rval, = rval return rval
package co.tinode.tindroid; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.ProgressBar; import android.widget.Toast; import java.util.Map; import co.tinode.tindroid.media.VxCard; import co.tinode.tinodesdk.MeTopic; import co.tinode.tinodesdk.NotConnectedException; import co.tinode.tinodesdk.NotSynchronizedException; import co.tinode.tinodesdk.PromisedReply; import co.tinode.tinodesdk.Tinode; import co.tinode.tinodesdk.model.Description; import co.tinode.tinodesdk.model.MsgServerInfo; import co.tinode.tinodesdk.model.MsgServerPres; import co.tinode.tinodesdk.model.PrivateType; import co.tinode.tinodesdk.model.Subscription; /** * Activity holds the following fragments: * ContactsFragment * ChatListFragment * ContactListFragment * * AccountInfoFragment * * This activity owns 'me' topic. */ public class ContactsActivity extends AppCompatActivity implements ContactListFragment.OnContactsInteractionListener { private static final String TAG = "ContactsActivity"; static final String FRAGMENT_CONTACTS = "contacts"; static final String FRAGMENT_EDIT_ACCOUNT = "edit_account"; private ChatListAdapter mChatListAdapter; private MeListener mMeTopicListener = null; private MeTopic mMeTopic = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_contacts); getSupportFragmentManager().beginTransaction() .replace(R.id.contentFragment, new ContactsFragment(), FRAGMENT_CONTACTS) .commit(); mChatListAdapter = new ChatListAdapter(this); mMeTopicListener = new MeListener(); } /** * This interface callback lets the main contacts list fragment notify * this activity that a contact has been selected. * * @param contactUri The contact Uri to the selected contact. */ @Override public void onContactSelected(Uri contactUri) { // Otherwise single pane layout, start a new ContactDetailActivity with // the contact Uri //Intent intent = new Intent(this, ContactDetailActivity.class); //intent.setData(contactUri); //startActivity(intent); } /** * This interface callback lets the main contacts list fragment notify * this activity that a contact is no longer selected. */ @Override public void onSelectionCleared() { } /** * onResume restores subscription to 'me' topic and sets listener. */ @Override @SuppressWarnings("unchecked") public void onResume() { super.onResume(); final Tinode tinode = Cache.getTinode(); tinode.setListener(new ContactsEventListener(tinode.isConnected())); UiUtils.setupToolbar(this, null, null, false); if (mMeTopic == null) { mMeTopic = tinode.getMeTopic(); if (mMeTopic == null) { // The very first launch of the app. mMeTopic = new MeTopic<>(tinode, mMeTopicListener); Log.d(TAG, "Initialized NEW 'me' topic"); } else { mMeTopic.setListener(mMeTopicListener); Log.d(TAG, "Loaded existing 'me' topic"); } } else { mMeTopic.setListener(mMeTopicListener); } if (!mMeTopic.isAttached()) { topicAttach(); } else { Log.d(TAG, "onResume() called: topic is attached"); } } @SuppressWarnings("unchecked") private void topicAttach() { try { setProgressIndicator(true); mMeTopic.subscribe(null, mMeTopic .getMetaGetBuilder() .withGetDesc() .withGetSub() .build()) .thenApply(new PromisedReply.SuccessListener() { @Override public PromisedReply onSuccess(Object result) throws Exception { setProgressIndicator(false); return null; } }, new PromisedReply.FailureListener() { @Override public PromisedReply onFailure(Exception err) throws Exception { setProgressIndicator(false); return null; } }); } catch (NotSynchronizedException ignored) { setProgressIndicator(false); /* */ } catch (NotConnectedException ignored) { /* offline - ignored */ setProgressIndicator(false); Toast.makeText(this, R.string.no_connection, Toast.LENGTH_SHORT).show(); } catch (Exception err) { Log.i(TAG, "Subscription failed", err); setProgressIndicator(false); Toast.makeText(this, "Failed to attach", Toast.LENGTH_LONG).show(); } } private void datasetChanged() { mChatListAdapter.resetContent(); runOnUiThread(new Runnable() { @Override public void run() { mChatListAdapter.notifyDataSetChanged(); } }); } @Override public void onPause() { super.onPause(); Cache.getTinode().setListener(null); } @Override @SuppressWarnings("unckecked") public void onStop() { super.onStop(); if (mMeTopic != null) { mMeTopic.setListener(null); } } /** * Show progress indicator based on current status * @param active should be true to show progress indicator */ public void setProgressIndicator(final boolean active) { if (isFinishing() || isDestroyed()) { return; } runOnUiThread(new Runnable() { @Override public void run() { ProgressBar progressBar = findViewById(R.id.toolbar_progress_bar); if (progressBar != null) { progressBar.setVisibility(active ? View.VISIBLE : View.GONE); } } }); } protected ChatListAdapter getChatListAdapter() { return mChatListAdapter; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Enable options menu by returning true return true; } private class MeListener extends MeTopic.MeListener<VxCard> { @Override public void onInfo(MsgServerInfo info) { Log.d(TAG, "Contacts got onInfo update '" + info.what + "'"); } @Override public void onPres(MsgServerPres pres) { if (pres.what.equals("msg")) { datasetChanged(); } else if (pres.what.equals("off") || pres.what.equals("on")) { datasetChanged(); } } @Override public void onMetaSub(final Subscription<VxCard,PrivateType> sub) { if (sub.pub != null) { sub.pub.constructBitmap(); } } @Override public void onMetaDesc(final Description<VxCard,PrivateType> desc) { if (desc.pub != null) { desc.pub.constructBitmap(); } } @Override public void onSubsUpdated() { datasetChanged(); } @Override public void onContUpdate(final Subscription<VxCard,PrivateType> sub) { // Method makes no sense in context of MeTopic. throw new UnsupportedOperationException(); } } void showAccountInfoFragment() { FragmentManager fm = getSupportFragmentManager(); Fragment fragment = fm.findFragmentByTag(FRAGMENT_EDIT_ACCOUNT); FragmentTransaction trx = fm.beginTransaction(); if (fragment == null) { fragment = new AccountInfoFragment(); trx.add(R.id.contentFragment, fragment, FRAGMENT_EDIT_ACCOUNT); } trx.addToBackStack(FRAGMENT_EDIT_ACCOUNT) .show(fragment) .commit(); } public void selectTab(final int pageIndex) { FragmentManager fm = getSupportFragmentManager(); ContactsFragment contacts = (ContactsFragment) fm.findFragmentByTag(FRAGMENT_CONTACTS); contacts.selectTab(pageIndex); } private class ContactsEventListener extends UiUtils.EventListener { ContactsEventListener(boolean online) { super(ContactsActivity.this, online); } @Override public void onLogin(int code, String txt) { super.onLogin(code, txt); topicAttach(); } } }
package com.jeeneee.realworld.comment.dto; import com.jeeneee.realworld.comment.domain.Comment; import com.jeeneee.realworld.comment.dto.SingleCommentResponse.CommentInfo; import com.jeeneee.realworld.user.domain.User; import java.util.List; import java.util.stream.Collectors; import lombok.AccessLevel; import lombok.Getter; import lombok.NoArgsConstructor; @Getter @NoArgsConstructor(access = AccessLevel.PRIVATE) public class MultipleCommentResponse { private List<CommentInfo> comments; public MultipleCommentResponse(List<CommentInfo> comments) { this.comments = comments; } public static MultipleCommentResponse of(List<Comment> comments, User user) { return new MultipleCommentResponse(comments.stream() .map(comment -> CommentInfo.of(comment, user)) .collect(Collectors.toList())); } }
api_key=<YOUR_API_KEY> app_key=<YOUR_APP_KEY> # pass a single hostname as an argument to search for the specified host host=$1 # Find a host to add a tag to host_name=$(curl -G "https://api.datadoghq.com/api/v1/search" \ -d "api_key=${api_key}" \ -d "application_key=${app_key}" \ -d "q=hosts:$host" | cut -d'"' -f6) curl "https://api.datadoghq.com/api/v1/tags/hosts/${host_name}?api_key=${api_key}&application_key=${app_key}"
from __future__ import unicode_literals from django.db import models from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.base_user import AbstractBaseUser from django.utils.translation import ugettext_lazy as _ # Create your models here. class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_staff', True) if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) username = models.CharField(_('first and last name'), max_length=30, blank=True) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) is_active = models.BooleanField(_('active'), default=True) is_staff = models.BooleanField(_('is_staff'), default=False) is_superuser = models.BooleanField(_('is_superUser'), default=False) last_login = models.DateTimeField(_('last login'), auto_now=True) telephone = models.CharField(max_length=32, null=True) birthdate = models.DateField(null=True) gender = models.CharField(max_length=20, null=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: verbose_name = _('user') verbose_name_plural = _('users') db_table ="keep_user" def get_full_name(self): ''' Returns the first_name plus the last_name, with a space in between. ''' full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() def get_short_name(self): ''' Returns the short name for the user. ''' return self.first_name
import { LearnsetArgs } from '#arguments/LearnsetArgs'; import { ArrayMinSize, ArrayUnique, IsString } from 'class-validator'; import { ArgsType, Field } from 'type-graphql'; @ArgsType() export class FuzzyLearnsetArgs extends LearnsetArgs { @Field(() => [String], { description: 'The moves to match against the Pokémon' }) @ArrayUnique() @ArrayMinSize(1) public moves!: string[]; @Field(() => String, { description: 'The Pokémon for which to get the learnset' }) @IsString() public pokemon!: string; }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {Binding, Path} from '@romejs/js-compiler'; import inheritLoc from './inheritLoc'; import { AnyNode, exportLocalDeclaration, exportLocalSpecifier, identifier, referenceIdentifier, } from '@romejs/js-ast'; import getBindingIdentifiers from './getBindingIdentifiers'; import isVariableIdentifier from './isVariableIdentifier'; import assertSingleOrMultipleNodes from './assertSingleOrMultipleNodes'; import {AnyVariableIdentifier} from '@romejs/js-ast/unions'; // This methods allows either passing in Bindings that could be present within deep scopes, // or local names for the scope in the passed Path export default function renameBindings( path: Path, oldToNewMapping: Map<Binding | string, string>, ): AnyNode | Array<AnyNode> { if (oldToNewMapping.size === 0) { return path.node; } const oldBindingToNewName: Map<Binding, string> = new Map(); // get a list of the current bindings for this scope const oldNameToBinding: Map<string, undefined | Binding> = new Map(); for (const [oldName, newName] of oldToNewMapping) { if (typeof oldName === 'string') { const binding = path.scope.getBinding(oldName); oldNameToBinding.set(oldName, binding); } else { oldBindingToNewName.set(oldName, newName); } } // discover nodes to replace first without manipulating the AST as that will change the scope and binding objects const replaceNodesWithName: Map<AnyVariableIdentifier, string> = new Map(); path.traverse( 'renameBindingsCollector', (path) => { const {node, scope} = path; if (!isVariableIdentifier(node)) { return; } const binding = scope.getBinding(node.name); // oldName -> newName if ( oldToNewMapping.has(node.name) && binding === oldNameToBinding.get(node.name) ) { const newName = oldToNewMapping.get(node.name); if (newName === undefined) { throw new Error('Should exist'); } replaceNodesWithName.set(node, newName); } // Binding -> newName if (binding !== undefined && oldBindingToNewName.has(binding)) { const newName = oldBindingToNewName.get(binding); if (newName === undefined) { throw new Error('Should exist'); } replaceNodesWithName.set(node, newName); } }, ); if (replaceNodesWithName.size === 0) { return path.node; } // const replaced: Set<AnyNode> = new Set(); // replace the nodes const renamedNode = path.reduce( { name: 'renameBindings', enter(path): AnyNode | Array<AnyNode> { const {node} = path; // Retain the correct exported name for `export function` and `export class` if ( node.type === 'ExportLocalDeclaration' && node.declaration !== undefined && (node.declaration.type === 'FunctionDeclaration' || node.declaration.type === 'ClassDeclaration') ) { const newName = replaceNodesWithName.get(node.declaration.id); if (newName !== undefined) { replaced.add(node.declaration.id); const oldName = node.declaration.id.name; return ([ node.declaration, exportLocalDeclaration.create({ specifiers: [ exportLocalSpecifier.create({ loc: node.declaration.id.loc, local: referenceIdentifier.quick(newName), exported: identifier.quick(oldName), }), ], }), ] as Array<AnyNode>); } } // Retain the correct exported names for `export const` if ( node.type === 'ExportLocalDeclaration' && node.declaration !== undefined ) { const bindings = getBindingIdentifiers(node.declaration); let includesAny = false; for (const node of bindings) { if (replaceNodesWithName.has(node)) { includesAny = true; break; } } if (includesAny) { return ([ node.declaration, exportLocalDeclaration.create({ specifiers: bindings.map((node) => { let local: string = node.name; const newName = replaceNodesWithName.get(node); if (newName !== undefined) { local = newName; replaced.add(node); } return exportLocalSpecifier.create({ loc: node.loc, local: referenceIdentifier.quick(local), exported: identifier.quick(node.name), }); }), }), ] as Array<AnyNode>); } } if (isVariableIdentifier(node)) { const newName = replaceNodesWithName.get(node); if (newName !== undefined) { replaced.add(node); return { ...node, name: newName, loc: inheritLoc(node, node.name), }; } } return node; }, }, { noScopeCreation: true, }, ); // if (replaced.size !== replaceNodesWithName.size) { console.log({replaced, replaceNodesWithName}); throw new Error('Missed some bindings'); } return assertSingleOrMultipleNodes(renamedNode); }
import pygame, pygcurse from pygame.locals import * import LED_display as LD import stt_thread as ST import HC_SR04 as RS import threading import time import copy import list_set import sys import scoreboard WINWIDTH = 32 WINHEIGHT = 16 FPS = 20 delay = 0.03 mode_list = ['mouse', 'keyboard', 'sensor'] #mode = mode_list[1] mode = sys.argv[1] isfullscreen = False if mode == 'mouse': isfullscreen = True iScreen = [[0 for i in range(WINWIDTH)] for j in range(WINHEIGHT)] # - Pygcurse board win = pygcurse.PygcurseWindow(WINWIDTH, WINHEIGHT, fullscreen=isfullscreen) t=threading.Thread(target=LD.main, args=()) t.setDaemon(True) t.start() def main(): newGame = True gameOver = False gameWin = 0 start_time = time.time() mainClock = pygame.time.Clock() while True: if gameOver: oScreen = copy.deepcopy(iScreen) print_GameOver(oScreen) drawMatrix(oScreen) time.sleep(3) pygame.quit() scoreboard.main('brick', 0) sys.exit() elif gameWin == 2: oScreen = copy.deepcopy(iScreen) print_Clear(oScreen) drawMatrix(oScreen) time_score = round(time.time() - start_time) time.sleep(3) pygame.quit() scoreboard.main('brick', time_score) sys.exit() if newGame: pygame.mouse.set_pos(win.centerx * win.cellwidth, (win.bottom) * win.cellheight) mousex, mousey = pygame.mouse.get_pos() before_cellx_arr = [WINWIDTH//2] * 3 cellx, celly = WINWIDTH//2, WINHEIGHT -2 ballx, bally = cellx, WINHEIGHT - 3 ball_direction = {'NW' : [-1, -1], 'N' : [0, -1], 'NE' : [1, -1], 'SW' : [-1, 1], 'S' : [0, 1], 'SE' : [1, 1]} ballspeed = 2 ballspeed = 4 - ballspeed ballcnt = 0 ballmv = ball_direction['N'] bricks =[[1,1], [6,1], [11,1], [16,1], [21, 1], [26,1], [3,4], [8,4], [13,4], [18,4], [23,4]] if mode == 'keyboard': counter = 0 moveRight = False moveLeft = False gameOver = False newGame = False if mode == 'mouse' or mode == 'keyboard': for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE) or (event.type == KEYDOWN and event.key == ord('q')): pygame.quit() sys.exit() if (event.type == KEYDOWN and event.key == ord('v')): time_score = round(time.time() - start_time) t2=threading.Thread(target=ST.ST_main, args=('b', str(time_score))) t2.setDaemon(True) t2.start() # Input # mouse mode if mode == 'mouse': if event.type == MOUSEMOTION and not gameOver: mousex, mousey = event.pos cellx, celly = win.getcoordinatesatpixel(mousex, mousey) celly = WINHEIGHT - 2 # keyboard mode elif mode == 'keyboard': if event.type == KEYDOWN: if event.key == K_LEFT or event.key == ord('a'): if not gameOver: cellx -= 1 counter += 1 moveRight = False moveLeft = True if event.key == K_RIGHT or event.key == ord('d'): if not gameOver: cellx += 1 counter += 1 moveLeft == False moveRight = True if event.type == KEYUP: if event.key == K_LEFT or event.key == ord('a'): counter = 0 moveLeft = False if event.key == K_RIGHT or event.key == ord('d'): counter = 0 moveRight = False elif mode == 'sensor': for event in pygame.event.get(): if (event.type == KEYUP and event.key == ord('v')): time_score = round(time.time() - start_time) t2=threading.Thread(target=ST.ST_main, args=('d', str(time_score))) t2.setDaemon(True) t2.start() if not gameOver: cellx = RS.get_distance()-10 # Act oScreen = copy.deepcopy(iScreen) drawBricks(bricks, oScreen) if mode == 'keyboard': if not gameOver: if counter > 2: if moveRight: cellx += 1 if moveLeft: cellx -= 1 elif moveRight or moveLeft: counter += 1 if cellx < 2: cellx = 2 if cellx > WINWIDTH-3: cellx = WINWIDTH-3 elif mode == 'mouse': if cellx < 2: cellx = 2 if cellx > WINWIDTH-3: cellx = WINWIDTH-3 elif mode == 'sensor': if not gameOver: if cellx < 1 or cellx > WINWIDTH -2: cellx = before_cellx_arr[-1] if abs(cellx - before_cellx_arr[-1]) > 10: cellx = before_cellx_arr[-1] else: cellx = sum(before_cellx_arr[1:]+[cellx],1)//len(before_cellx_arr) before_cellx_arr.pop(0) before_cellx_arr.append(cellx) cellx = before_cellx_arr[-1] # Ball check hit = oScreen[bally][ballx] if ballcnt == 0: # Hit wall if bally <= 0 or bally >= WINHEIGHT -1 or ballx <= 0 or ballx >= WINWIDTH - 1: if bally <= 0: ballmv = [ballmv[0], -ballmv[1]] if ballx <= 0 or ballx >= WINWIDTH - 1: ballmv = [-ballmv[0], ballmv[1]] if bally >= WINHEIGHT - 1: gameOver = True ballmv = [-ballmv[0], -ballmv[1]] # GameOver # Hit brick elif hit == 3: bricks = breakBrick(ballx, bally, oScreen, bricks) for key, value in ball_direction.items(): if ballmv == value: direction = key if direction[0] == 'N': direction = 'S' + direction[1:] elif direction[0] == 'S': direction = 'N' + direction[1:] ballmv = ball_direction[direction] # Hit pad elif (bally == celly-1 or bally == celly) and ballx >= cellx -2 and ballx <= cellx + 2: if ballx < cellx: ballmv = ball_direction['NW'] elif ballx > cellx: ballmv = ball_direction['NE'] else: ballmv = ball_direction['N'] # Draw ball if not gameOver: oScreen[bally][ballx] = 2 else: oScreen[bally][ballx] = 4 # Ball movement if ballcnt >= ballspeed: ballx += ballmv[0] bally += ballmv[1] ballcnt = 0 else: ballcnt += 1 # - Draw Matrix # consoleMatrix(oScreen) #pygcurseMatrix(oScreen) if len(bricks) == 0: gameWin += 1 drawPad(cellx, celly, oScreen) drawMatrix(oScreen) mainClock.tick(FPS) def breakBrick(x, y, screen, bricks): for brick in bricks: if x >= brick[0] and x <= brick[0] + 3 and y >= brick[1] and y <= brick[1] + 1: bricks.pop(bricks.index(brick)) break return bricks def drawBricks(bricks, screen): for brick in bricks: for i in range(brick[0], brick[0]+4): for j in range(brick[1], brick[1]+2): screen[j][i] = 3 def drawPad(x, y, screen): for i in range(x-2,x+3,1): screen[y][i] = 1 def drawMatrix(array): for x in range(len(array[0])): for y in range(len(array)): if array[y][x] == 0: LD.set_pixel(x, y, 0) elif array[y][x] == 1: LD.set_pixel(x, y, 3) elif array[y][x] == 2: LD.set_pixel(x, y, 6) elif array[y][x] == 3: LD.set_pixel(x, y, 2) elif array[y][x] == 4: LD.set_pixel(x, y, 1) else: continue # color = 0 : 'None', 1 : 'Red', 2 : 'Green', 3 : 'Yellow', 4 : 'Blue', 5 : 'Purple', 6 : 'Crystal', 7 : 'White' def drawChar(char, screen, width, height, direction, color): for i in range(width): for j in range(height): if char[j][i] == 1: screen[direction[1]+j][direction[0]+i] = color def print_Clear(oScreen): drawChar(list_set.alpha_C, oScreen, 5, 7, (1,4), 2) drawChar(list_set.alpha_l, oScreen, 5, 7, (7, 4), 2) drawChar(list_set.alpha_e, oScreen, 5, 7, (13, 4), 2) drawChar(list_set.alpha_a, oScreen, 5, 7, (19, 4), 2) drawChar(list_set.alpha_r, oScreen, 5, 7, (25, 4), 2) def print_GameOver(oScreen): drawChar(list_set.alpha_G, oScreen, 5, 7, (1,1), 4) drawChar(list_set.alpha_a, oScreen, 5, 7, (7,1), 4) drawChar(list_set.alpha_m, oScreen, 5, 7, (13,1), 4) drawChar(list_set.alpha_e, oScreen, 5, 7, (19,1), 4) drawChar(list_set.alpha_O, oScreen, 5, 7, (8, 9), 4) drawChar(list_set.alpha_v, oScreen, 5, 7, (14, 9), 4) drawChar(list_set.alpha_e, oScreen, 5, 7, (20, 9), 4) drawChar(list_set.alpha_r, oScreen, 5, 7, (26, 9), 4) if __name__ == '__main__': main()
var cluster = require("cluster"); if (cluster.isMaster) module.exports = require("./master.js")(); else module.exports = require("./worker.js")();
package cn.leancloud.codec; import junit.framework.TestCase; public class Base64EncoderTest extends TestCase { public Base64EncoderTest(String name) { super(name); } public void testCommonFunc() throws Exception { String input = "searchQuery.orderByAscending"; String encodeString = Base64Encoder.encode(input); assertTrue(input.equals(Base64Decoder.decode(encodeString))); } }
<reponame>davidrmthompson/positronic-economist<filename>posec/applications/position_auctions_externalities.py from collections import namedtuple, Counter from posec import mathtools from position_auctions import Permutations, _PositionAuctionOutcome, NoExternalityPositionAuction import math import posec import string # FIXME: I'm overloading externality type as a word. I want something more general than continuation probability # (to allow for the rich externality model), but that's not it. _ExternalityOutcome = namedtuple( "ExternalityOutcome", ["higher_externality_types", "my_ppc"]) _ExternalityType = namedtuple( "ExternalityType", ["value", "ctr", "quality", "externality_type"]) _ExternalityWeightedBid = namedtuple( "WeightedBid", ["bid", "effective_bid", "externality_type"]) class HybridSetting(posec.ProjectedSetting): def __init__(self, valuations, ctrs, qualities, continuation_probabilities): self.n = len(valuations) projectedAllocations = mathtools.powerSet( continuation_probabilities, Counter) allocations = Permutations(range(self.n)) payments = posec.RealSpace(self.n) self.O = posec.CartesianProduct( allocations, payments, memberType=_PositionAuctionOutcome) self.Theta = [] for i in range(self.n): self.Theta.append( _ExternalityType(tuple(valuations[i]), tuple(ctrs[i]), qualities[i], continuation_probabilities[i])) self.Psi = posec.CartesianProduct( projectedAllocations, posec.RealSpace(), memberType=_ExternalityOutcome) def ctr(self, i, theta, projectedAllocation): return mathtools.product(projectedAllocation) * theta[i].ctr[len(projectedAllocation)] def u(self, i, theta, po, a_i): projectedAllocation = po.higher_externality_types if projectedAllocation == None: return 0.0 p = len(projectedAllocation) ppc = po.my_ppc ctr = self.ctr(i, theta, projectedAllocation) v = theta[i].value[p] return ctr * (v - ppc) class ExternalityPositionAuction(NoExternalityPositionAuction): def makeOutcome(self, alloc, price): return _ExternalityOutcome(alloc, price) def makeBid(self, theta_i, b, eb): return _ExternalityWeightedBid(b, eb, theta_i.externality_type) def projectedAllocations(self, i, theta_i, a_N): ''' Returns a list of all the projected allocations (a projected allocation is the list of externality types of agents ranked above i) ''' possible_externality_types = set( [theta_j.externality_type for theta_j in a_N.types]) higher_externality_types = Counter() for theta_j in possible_externality_types: m = a_N.sum([a for a in a_N.actions if a.effective_bid > a_N[ i].effective_bid and a.externality_type == theta_j]) higher_externality_types[theta_j] += m if self.tieBreaking == "Uniform": equal_externality_types = Counter() for theta_j in possible_externality_types: m = a_N.sum( [a for a in a_N.actions if a.effective_bid == a_N[i].effective_bid and a.externality_type == theta_j]) if theta_j == theta_i.externality_type: m -= 1 equal_externality_types[theta_j] += m print equal_externality_types subsets = mathtools.powerSet( list(equal_externality_types.elements()), Counter) return [higher_externality_types + subset for subset in subsets] raise BaseException("Lexigraphic tie-breaking is not working yet") # GENERATOR FUNCTIONS #### class _CascadeOrHybridFactory: def __init__(self, alpha_function, value_genrator_function): self.alpha_function = alpha_function self.value_genrator_function = value_genrator_function def __call__(self, n, m, k, seed=None): import random as r r.seed(seed) valuations = [] ctrs = [] qualities = [] continuation_probabilities = [] for i in range(n): value, quality = self.value_genrator_function(r, k) valuations.append([value] * n) qualities.append(quality) ctrs.append( [quality * alpha for alpha in self.alpha_function(n, m, r)]) continuation_probabilities.append(r.random()) return HybridSetting(valuations, ctrs, qualities, continuation_probabilities) def _uni_distro(r, k): return r.random() * k, r.random() def _make_flat_alpha(n, m, r): return [1.0] * m + [1.0] * (n - m) def _make_UNI_alpha(n, m, r): alphaPrime = 1.0 alpha = [] for i in range(m): a = alphaPrime * r.random() alpha.append(a) alphaPrime = a for i in range(n - m): alpha.append(0.0) return alpha def _make_LP_alpha(n, m, r): a = 1.0 + 0.5 * r.random() # Polynomial decay factor alpha = [] for i in range(m): alpha.append(math.pow(i + 1, -a)) for i in range(n - m): alpha.append(0.0) return alpha from posec.applications.position_auctions import LNdistro as _ln_distro cascade_UNI = _CascadeOrHybridFactory(_make_flat_alpha, _uni_distro) cascade_LN = _CascadeOrHybridFactory(_make_flat_alpha, _ln_distro) hybrid_UNI = _CascadeOrHybridFactory(_make_UNI_alpha, _uni_distro) hybrid_LN = _CascadeOrHybridFactory(_make_LP_alpha, _ln_distro) GENERATORS = {"cascade_UNI": cascade_UNI, "cascase_LN": cascade_LN, "hybrid_UNI": hybrid_UNI, "hybrid_LN": hybrid_LN} # def richExternality(n,m,k,seed): # import random as r # setting = CascadeSetting(n,m,k) # setting.T = [] # r.seed(seed) # print seed,r.random() # for i in range(n): # t = RichExternalityType(setting) # beta = r.random() # t.value = r.random()*k # print beta,t.value # t.q = beta # t.advertiserCTRFactor = beta # t.ctrDict = richExternalityDictionary(n,r) # setting.T.append(t) # print t # return setting # def richExternality_LN(n,m,k,seed): # import random as r # setting = CascadeSetting(n,m,k) # setting.T = [] # r.seed(seed) # for i in range(n): # t = RichExternalityType(setting) # t.value, beta = LNdistro(r,k) # t.q = beta # t.advertiserCTRFactor = beta # setting.T.append(t) # t.ctrDict = richExternalityDictionary(n,r) # return setting # GENERATORS = { # "BHN-LN":BHN_LN, # "CAS-LN":cascade_LN,"V-LN":LP,"BSS-LN":BSS_LN,"EOS-LN":EOS_LN,"EOS":EOS,"BHN":BHN,"V":Varian,"BSS":BSS,"CAS":CascadeSetting, # "HYB-LN":hybrid_LN,"HYB":hybrid,"RE":richExternality, "RE-LN":richExternality_LN # }
<reponame>Chiki1601/LOVE-calculator-in-JS<gh_stars>0 // button listener var button = document.querySelector('button'); button.addEventListener('click', function(e){ var yourName = document.querySelector ("#yourName").value; var crushName = document.querySelector ("#crushName").value; var loveScore = Math.random(); loveScore = Math.floor(loveScore * 100) + 1 ; // A place for % result to be printed out var resultNumber = document.querySelector("#resultNumber"); // A place for the following explanation to be printed out var explanation = document.querySelector("#explanation"); // Hiding form for result var hideForResult = document.querySelector('.hideForResult'); // Showing Try Again button var tryAgain = document.querySelector('#tryAgain'); // Shortcut for result var yourResultIs = yourName + " & " + crushName + ", your compatibility is " + loveScore + "%."; if (loveScore >= 70) { explanation.style.visibility = "visible"; resultNumber.style.visibility = "visible"; resultNumber.innerHTML = loveScore + "%"; explanation.innerHTML = yourResultIs + "High change there 😏"; hideForResult.style.display = "none"; tryAgain.style.visibility = "visible"; } else if (loveScore >= 40 && loveScore < 70) { explanation.style.visibility = "visible"; resultNumber.style.visibility = "visible"; resultNumber.innerHTML = loveScore + "%"; explanation.innerHTML = yourResultIs + "That's not bad 🤔"; hideForResult.style.display = "none"; tryAgain.style.visibility = "visible"; } else { explanation.style.visibility = "visible"; resultNumber.style.visibility = "visible"; resultNumber.innerHTML = loveScore + "%"; explanation.innerHTML = yourResultIs + "ugh, as if! 🤧"; hideForResult.style.display = "none"; tryAgain.style.visibility = "visible"; } });
#!/bin/bash /vagrant/scripts/ping.sh | grep --color -A 2 "statistics"
import pandas as pd import numpy as np import random # Read the data frame df = pd.read_csv('input.csv') # Generate the random numbers randoms = [random.uniform(0, 1) for _ in range(len(df))] # Add the random numbers to the data frame as a new column df['random'] = randoms # Write the updated data frame to a CSV file df.to_csv('output.csv', index=False)
export source_model="imagenet_resnet_26" export target_model="imagenet_resnet_18" export mapping1="0:0;1:1|0:0;1:1|0:0;1:1|0:0;1:1" for mapping in $mapping1; do python open_lth.py lottery_branch change_depth --num_workers 16 --default_hparams=imagenet_resnet_50 --model_name $source_model --rewinding_steps 5ep --replicate=$replicate \ --target_model_name $target_model --block_mapping "${mapping}" --levels=0-5 done export source_model="imagenet_resnet_26" export target_model="imagenet_resnet_34" export mapping1="0:0;1:1,2|0:0;1:1,2;2:3|0:0;1:1,2;2:3,4;3:5|0:0;1:1;2:2" for mapping in $mapping1; do python open_lth.py lottery_branch change_depth --num_workers 16 --default_hparams=imagenet_resnet_50 --model_name $source_model --rewinding_steps 5ep --replicate=$replicate \ --target_model_name $target_model --block_mapping "${mapping}" --levels=0-5 done
#!/usr/bin/env bash ############################################################################### # Copyright 2017 The Apollo Authors. 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. ############################################################################### DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" cd "${DIR}/.." source "${DIR}/apollo_base.sh" # Usage: # scripts/switch_vehicle.sh <vehicle_data_path> # # <vehicle_data_path> is a directory containing vehicle specified data. # E.g.: modules/calibration/data/mkz8 VEHICLE_PATH=$1 if [ -d ${VEHICLE_PATH} ]; then ${APOLLO_BIN_PREFIX}/modules/dreamview/backend/hmi/vehicle_manager_main \ --vehicle_data_path="${VEHICLE_PATH}" else error "Cannot open directory: ${VEHICLE_PATH}" info "Available vehicles:" find modules/calibration/data -maxdepth 1 -mindepth 1 -type d fi
<reponame>NajibAdan/kitsu-server<gh_stars>0 class DramaCharacterPolicy < ApplicationPolicy end
from django.apps import AppConfig class GrocerylistConfig(AppConfig): name = 'grocerylist'
import random def generateRandomSequence(n): if n % 2 == 0: symbols = ['!', '@', '#', '$', '%'] return ''.join(random.choice(symbols) for _ in range(n)) else: return ''.join(str(random.randint(0, 9)) for _ in range(n)) # Example usage print(generateRandomSequence(5)) # Possible output: "@#%$!" print(generateRandomSequence(6)) # Possible output: "##$@!@" print(generateRandomSequence(7)) # Possible output: "1234567"
#!/usr/bin/env bash BASE_DIR="$HOME/.vim" PACK_DIR="$BASE_DIR/pack/phix" PLUGINS=( # "dracula/vim" "ctrlpvim/ctrlp.vim" "vim-airline/vim-airline" "vim-airline/vim-airline-themes" "scrooloose/nerdtree" "freitass/todo.txt-vim" "terryma/vim-multiple-cursors" "airblade/vim-gitgutter" "gabrielelana/vim-markdown" # "leafgarland/typescript-vim" # "bigfish/vim-js-context-coloring" "pangloss/vim-javascript" ) mkdir -p $PACK_DIR # Get latest .vimrc from dotfiles repo curl -o $HOME/.vimrc https://raw.githubusercontent.com/Phixyn/dotfiles/master/.vimrc # The basename for this repo is 'vim', so clone it outside of the # loop to give it a more descriptive name. git clone https://github.com/dracula/vim.git "$PACK_DIR/start/dracula" # Git clone remaining plugins into pack/start folder for PLUGIN in ${PLUGINS[@]}; do DIRNAME="$(basename $PLUGIN)" git clone https://github.com/$PLUGIN.git "$PACK_DIR/start/$DIRNAME" done echo "[INFO] Vim setup done."
#ifndef _EN_SHOPNUTS_H_ #define _EN_SHOPNUTS_H_ #include "z3D/z3D.h" typedef struct EnShopnuts { /* 0x000 */ Actor actor; /* 0x1A4 */ char unk_1A4[0x6FC]; } EnShopnuts; // size 0x8A0 #endif //_EN_SHOPNUTS_H_
<gh_stars>1-10 package io.miti.jarman.util; import java.io.DataInputStream; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * Parse a .class file and return the list of referenced Java classes. * * @author mwallace * @version 1.0 */ public final class ClassStreamParser { /** * For correcting indexes to constant pools with long and double entries. */ private int indexCorrection = 0; /** * List of all strings in the constant pool. */ private Map<Integer, String> strings = new HashMap<Integer, String>(); /** * The set of indexes into strings holding class names. */ private Set<Integer> classes = new HashSet<Integer>(); /** * Default constructor. */ public ClassStreamParser() { super(); } /** * Parse the stream. * * @param stream the input data stream * @param names the array to fill with class names * @throws IOException an error occurred while reading */ public void parseStream(final DataInputStream stream, final List<String> names) throws IOException { // Verify this is a valid class file (starts with 0xCAFEBABE) if (readHeader(stream)) { final int poolSize = readU2(stream); for (int n = 1; n < poolSize; n++) { savePoolEntryIfIsClassReference(n, stream); } // Save the strings to our output array for (Integer index : classes) { names.add(strings.get(index)); } } } /** * Read the header and return whether this is a valid class file. * * @param stream the input stream * @return whether this is a valid class file * @throws IOException error during reading */ private boolean readHeader(final DataInputStream stream) throws IOException { int result = readU4(stream); // magic byte if (result != 0xCAFEBABE) { return false; } // Read the rest of the header (before the constant pool) readU2(stream); // minor version readU2(stream); // major version return true; } /** * Check the pool entry and save the class names. * * @param index the pool entry index * @param stream the input data stream * @throws IOException an error occurred during reading */ private void savePoolEntryIfIsClassReference(final int index, final DataInputStream stream) throws IOException { final int tag = readU1(stream); switch (tag) { case 1: // Utf8 saveStringFromUtf8Entry(index, stream); break; case 7: // Class saveClassEntry(stream); break; case 8: // String readU2(stream); break; case 3: // Integer case 4: // Float readU4(stream); break; case 5: // Long case 6: // Double readU4(stream); readU4(stream); indexCorrection++; break; case 9: // Fieldref case 10: // Methodref case 11: // InterfaceMethodref case 12: // NameAndType readU2(stream); readU2(stream); break; default: break; } } /** * Read a string from the stream. * * @param index the index to store the string in * @param stream the input data stream * @throws IOException error during reading */ private void saveStringFromUtf8Entry(final int index, final DataInputStream stream) throws IOException { String content = readString(stream); strings.put(index, content); } /** * Save a string as a class name. * * @param stream the input data stream * @throws IOException error during reading */ private void saveClassEntry(final DataInputStream stream) throws IOException { int nameIndex = readU2(stream); classes.add(nameIndex - indexCorrection); } /** * Read a string. * * @param stream the input data stream * @return the read data * @throws IOException error during reading */ private String readString(final DataInputStream stream) throws IOException { String name = null; try { name = stream.readUTF(); } catch (java.io.EOFException e) { logError("EOFException in readString: ", e); } catch (java.io.UTFDataFormatException e) { logError("UTFDataFormatException in readString: ", e); } return name; } /** * Read an unsigned byte. * * @param stream the input data stream * @return the read data * @throws IOException error during reading */ private int readU1(final DataInputStream stream) throws IOException { int result = 0; try { result = stream.readUnsignedByte(); } catch (java.io.EOFException e) { logError("EOFException in readU1: ", e); } catch (java.io.UTFDataFormatException e) { logError("UTFDataFormatException in readU1: ", e); } return result; } /** * Read an unsigned short. * * @param stream the input data stream * @return the read data * @throws IOException error during reading */ private int readU2(final DataInputStream stream) throws IOException { return stream.readUnsignedShort(); } /** * Read an integer. * * @param stream the input data stream * @return the read data * @throws IOException error during reading */ private int readU4(final DataInputStream stream) throws IOException { return stream.readInt(); } /** * Log an exception. * * @param msg the text message * @param e the exception */ private void logError(final String msg, final Exception e) { System.err.println(msg + e.getMessage()); } }
<filename>src/main/java/com/github/choonster/entitylivingbaseitemhandlertestmod/client/gui/GuiHandler.java package com.github.choonster.entitylivingbaseitemhandlertestmod.client.gui; import com.github.choonster.entitylivingbaseitemhandlertestmod.client.gui.inventory.GuiEntityInventory; import com.github.choonster.entitylivingbaseitemhandlertestmod.inventory.ContainerEntityInventory; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import net.minecraftforge.fml.common.network.IGuiHandler; import javax.annotation.Nullable; public class GuiHandler implements IGuiHandler { public static final int ID_ENTITY_INVENTORY = 0; @Nullable @Override public Object getServerGuiElement(final int ID, final EntityPlayer player, final World world, final int x, final int y, final int z) { switch (ID) { case ID_ENTITY_INVENTORY: final Entity entity = world.getEntityByID(x); if (entity instanceof EntityLivingBase) { return new ContainerEntityInventory((EntityLivingBase) entity, player); } break; } return null; } @Nullable @Override public Object getClientGuiElement(final int ID, final EntityPlayer player, final World world, final int x, final int y, final int z) { switch (ID) { case ID_ENTITY_INVENTORY: final Entity entity = world.getEntityByID(x); if (entity instanceof EntityLivingBase) { return new GuiEntityInventory(new ContainerEntityInventory((EntityLivingBase) entity, player)); } break; } return null; } }
<filename>iwkats_core/core/settings.cc #include "settings.h" IWKATS_NAMESPACE_BEGIN Settings::Settings(QObject *parent) : QSettings(parent) { } Settings::~Settings() { } void Settings::setValue(const QString &key, const QVariant &value) { QSettings::setValue(key, value); } QVariant Settings::value(const QString &key, const QVariant &defalutValue) const { return QSettings::value(key, defalutValue); } IWKATS_NAMESPACE_END
const PosterRegistryProxyContractData = require('paradigm-contracts').contracts.PosterRegistryProxy; const TruffleContract = require('truffle-contract'); class PosterRegistry { constructor(options, treasury) { this.web3 = options.web3; this.treasury = treasury; this.initializing = this.init(options); } async init(options) { const PosterRegistryProxyContract = TruffleContract(PosterRegistryProxyContractData); PosterRegistryProxyContract.setProvider(this.web3.currentProvider); if (options.posterRegistryProxyAddress) { this.contract = PosterRegistryProxyContract.at(options.posterRegistryProxyAddress); } else { this.contract = await PosterRegistryProxyContract.deployed().catch(() => { throw new Error('Invalid network for PosterRegistry') }); } this.coinbase = await this.web3.eth.getCoinbase().catch(() => undefined); } async tokensContributed() { await this.initializing; return await this.contract.tokensContributed.call(); } async tokensRegisteredFor(address) { await this.initializing; return await this.contract.tokensRegisteredFor.call(address); } async registerTokens(amount) { await this.initializing; const coinbase = await this.web3.eth.getCoinbase(); const hasBalance = await this.treasury.currentBalance(coinbase).then((bal) => bal.gte(amount)); if(!hasBalance) { console.log(`${coinbase} has insufficient available Treasury balance; Depositing Tokens`); await this.treasury.deposit(value); } return await this.contract.registerTokens(amount, { from: this.coinbase }); } async releaseTokens(amount) { await this.initializing; return await this.contract.releaseTokens(amount, { from: this.coinbase }); } } module.exports = PosterRegistry;
/*- * #%L * hms-lambda-handler * %% * Copyright (C) 2019 Amazon Web Services * %% * 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. * #L% */ package com.amazonaws.athena.hms; import org.apache.thrift.TException; import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; public class TestPaginator { @Test public void testEmptyPaginatorWithAllEntries() throws TException { StringPaginator paginator = new StringPaginator(new HashMap<>()); PaginatedResponse<String> result = paginator.paginateByNames(null, (short) -1); assertNotNull(result); assertNull(result.getNextToken()); assertNotNull(result.getEntries()); assertTrue(result.getEntries().isEmpty()); } @Test public void testEmptyPaginatorWithZeroEntry() throws TException { StringPaginator paginator = new StringPaginator(new HashMap<>()); PaginatedResponse<String> result = paginator.paginateByNames(null, (short) 0); assertNotNull(result); assertNull(result.getNextToken()); assertNotNull(result.getEntries()); assertTrue(result.getEntries().isEmpty()); } @Test public void testEmptyPaginatorWithPageEntry() throws TException { StringPaginator paginator = new StringPaginator(new HashMap<>()); PaginatedResponse<String> result = paginator.paginateByNames(null, (short) 4); assertNotNull(result); assertNull(result.getNextToken()); assertNotNull(result.getEntries()); assertTrue(result.getEntries().isEmpty()); } @Test public void testStringPaginatorWithAllEntries() throws TException { StringPaginator paginator = new StringPaginator(getData(6)); PaginatedResponse<String> result = paginator.paginateByNames(null, (short) -1); assertNotNull(result); assertNull(result.getNextToken()); assertNotNull(result.getEntries()); assertEquals(6, result.getEntries().size()); } @Test public void testStringPaginatorWithZeroEntry() throws TException { StringPaginator paginator = new StringPaginator(getData(6)); PaginatedResponse<String> result = paginator.paginateByNames(null, (short) 0); assertNotNull(result); assertNull(result.getNextToken()); assertNotNull(result.getEntries()); assertEquals(0, result.getEntries().size()); result = paginator.paginateByNames(Paginator.encrypt("k2"), (short) 0); assertNotNull(result); assertEquals(Paginator.encrypt("k2"), result.getNextToken()); assertNotNull(result.getEntries()); assertEquals(0, result.getEntries().size()); } @Test public void testStringPaginatorWithPageEntry() throws TException { StringPaginator paginator = new StringPaginator(getData(9)); PaginatedResponse<String> result = paginator.paginateByNames(null, (short) 4); assertNotNull(result); assertEquals(Paginator.encrypt("k4"), result.getNextToken()); assertNotNull(result.getEntries()); List<String> list = result.getEntries(); assertEquals(4, list.size()); for (int i = 0; i < 4; i++) { assertEquals("v" + i, list.get(i)); } result = paginator.paginateByNames(result.getNextToken(), (short) 4); assertNotNull(result); assertEquals(Paginator.encrypt("k8"), result.getNextToken()); assertNotNull(result.getEntries()); list = result.getEntries(); assertEquals(4, list.size()); for (int i = 0; i < 4; i++) { assertEquals("v" + (i + 4), list.get(i)); } result = paginator.paginateByNames(result.getNextToken(), (short) 4); assertNotNull(result); assertNull(result.getNextToken()); assertNotNull(result.getEntries()); list = result.getEntries(); assertEquals(1, list.size()); assertEquals("v8", list.get(0)); } @Test public void testGetAllEntriesWithFullPages() throws TException { StringPaginator paginator = new StringPaginator(getData(16)); Set<String> resultSet = new HashSet<>(); PaginatedResponse<String> result; String nextToken = null; do { result = paginator.paginateByNames(nextToken, (short) 4); if (result != null && result.getEntries() != null && !result.getEntries().isEmpty()) { resultSet.addAll(result.getEntries()); } nextToken = result.getNextToken(); } while (nextToken != null); assertEquals(16, resultSet.size()); for (int i = 0; i < 16; i++) { assertTrue(resultSet.contains("v" + i)); } } @Test public void testGetAllEntriesWithoutFullPages() throws TException { StringPaginator paginator = new StringPaginator(getData(19)); Set<String> resultSet = new HashSet<>(); PaginatedResponse<String> result; String nextToken = null; do { result = paginator.paginateByNames(nextToken, (short) 5); if (result != null && result.getEntries() != null && !result.getEntries().isEmpty()) { resultSet.addAll(result.getEntries()); } nextToken = result.getNextToken(); } while (nextToken != null); assertEquals(19, resultSet.size()); for (int i = 0; i < 19; i++) { assertTrue(resultSet.contains("v" + i)); } } @Test public void testEncrypDecrypt() { String original = ""; String encrypted = Paginator.encrypt(original); assertEquals(original, Paginator.decrypt(encrypted)); original = "my@Test-_name"; encrypted = Paginator.encrypt(original); assertEquals(original, Paginator.decrypt(encrypted)); } private Map<String, String> getData(int num) { Map<String, String> map = new HashMap<>(); for (int i = 0; i < num; i++) { map.put("k" + i, "v" + i); } return map; } static class StringPaginator extends Paginator<String> { private final Map<String, String> map; public StringPaginator(Map<String, String> map) { this.map = map; } @Override protected Collection<String> getNames() throws TException { return map.keySet(); } @Override protected List<String> getEntriesByNames(List<String> names) throws TException { List<String> list = new ArrayList<>(); if (names != null && !names.isEmpty()) { for (String name : names) { list.add(map.get(name)); } } return list; } } }
<filename>src/csvpp.js function csvpp_trim_whitespace(i_sString) { var sResult = new String(); var sResultForward = new String(); var bWhitespace = true; for (i = i_sString.length - 1; i >= 0; i--) { var chI = i_sString.charAt(i); if (!bWhitespace || chI != ' ' && chI != '\r' && chI != '\f') { sResult += chI; bWhitespace = false; } } bWhitespace = true; for (i = i_sString.length - 1; i >= 0; i--) { var chI = sResult.charAt(i); if (!bWhitespace || chI != ' ' && chI != '\r' && chI != '\f') { sResultForward += chI; bWhitespace = false; } } return sResultForward; } class CSV { constructor() { this._eError = "none"; this._vData = new Array(); } parse_csv(i_sData, i_sTokens, i_sStringDelim, i_bTrim_Whitespace, i_bPreserve_String_Delim) { var nLine = 0; var nDataCursor = 0; this._vData = new Array(); if (i_sData !== null && i_sData.length != 0 && i_sTokens !== null && i_sTokens.length != 0 && i_sStringDelim !== null && i_sStringDelim.length != 0) { var sCurr = new String(); nLine++; var chCurr = i_sData.charAt(nDataCursor); nDataCursor++; var chLast = 0; var vLine = new Array(); var sElement = new String(); while (nDataCursor < i_sData.length && this._eError == "none") { // bypass whitespace if (chCurr == '\f' || chCurr == '\r' || chCurr == '\n') { if (chLast != '\f' && chLast != '\r' && chLast != '\n') { if (i_bTrim_Whitespace) sElement = csvpp_trim_whitespace(sElement); vLine.push(sElement); this._vData.push(vLine); sElement = new String(); vLine = new Array(); nLine++; } } else if (nDataCursor < i_sData.length) { var pTokenCursor = 0; var bIsToken = false; while (!bIsToken && pTokenCursor < i_sTokens.length) { bIsToken = chCurr == i_sTokens.charAt(pTokenCursor); pTokenCursor++; } if (bIsToken) { if (i_bTrim_Whitespace) sElement = csvpp_trim_whitespace(sElement); vLine.push(sElement); sElement = new String(); } else { var pStringCursor = 0; var bIsStringStart = false; var nStringDelim = -1; while (!bIsStringStart && pStringCursor < i_sStringDelim.length) { nStringDelim++; bIsStringStart = chCurr == i_sStringDelim.charAt(pStringCursor); pStringCursor++; } if (bIsStringStart) { if (i_bPreserve_String_Delim) { sElement += chCurr; } chLast = chCurr; chCurr = i_sData.charAt(nDataCursor); nDataCursor++; var bIsStringDone = chCurr == i_sStringDelim.charAt(nStringDelim); while (!bIsStringDone && nDataCursor < i_sData.length && chCurr != '\f' && chCurr != '\r' && chCurr != '\n') { sElement += chCurr; chLast = chCurr; chCurr = i_sData.charAt(nDataCursor); nDataCursor++; bIsStringDone = chCurr == i_sStringDelim[nStringDelim]; } if (bIsStringDone && i_bPreserve_String_Delim) { sElement += chCurr; } if (!bIsStringDone) { if (nDataCursor < i_sData.length) this._eError == "unterminated string eof"; else this._eError == "unterminated string eol"; } } else { sElement += chCurr; } } } if (nDataCursor < i_sData.length && this._eError == "none") { chLast = chCurr; chCurr = i_sData.charAt(nDataCursor); nDataCursor++; } } if (chLast != '\f' && chLast != '\r' && chLast != '\n' && this._eError == "none") { if (i_bTrim_Whitespace) sElement = csvpp_trim_whitespace(sElement); vLine.push(sElement); this._vData.push(vLine); } } } at(row, col) { return this._vData[row][col]; } }
<filename>app/static/zcvbn-async.js (function() { var a; a = function() { var a, b; b = document.createElement("script"); b.src = "//dl.dropbox.com/u/209/zxcvbn/zxcvbn.js"; b.type = "text/javascript"; b.async = !0; a = document.getElementsByTagName("script")[0]; return a.parentNode.insertBefore(b, a) }; null != window.attachEvent ? window.attachEvent("onload", a) : window.addEventListener("load", a, !1) }).call(this);
let THREE = require('n3d-threejs'); let TWEEN = require('tween.js'); let Stats = require('stats-js'); let Bar = require('./Bar'); let $ = require('jquery'); let width = window.innerWidth; let height = window.innerHeight; let scene, stats, camera, renderer, light, rootContainer, texture, onClickCallback; let bars = { t0: { container: new THREE.Object3D(), objects: [] }, t1: { container: new THREE.Object3D(), objects: [] }, t2: { container: new THREE.Object3D(), objects: [] } }; let initTime, currentTime; let currentHighlighted = -1; let startX, startY, moveX, moveY; const nbBars = 64; function init () { initTime = Date.now(); stats = new Stats(); stats.domElement.style.position = 'absolute'; stats.domElement.style.left = '0px'; stats.domElement.style.top = '0px'; document.body.appendChild( stats.domElement ); scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera( 60, width/height, 0.1, 10000 ); camera.position.z = 2.5; light = new THREE.DirectionalLight( 0xffffff , 0.5); // soft white light light.position.set( 0, 0, 2 ); scene.add( light ); renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize( width, height ); renderer.setClearColor(0x141A33); document.body.appendChild( renderer.domElement ); rootContainer = new THREE.Object3D(); rootContainer.add( bars.t0.container ); rootContainer.add( bars.t1.container ); rootContainer.add( bars.t2.container ); scene.add( rootContainer ); texture = THREE.ImageUtils.loadTexture('assets/images/texture.png', {}, function () { generateBars(); }); initEvents(); animate(); } function setOnClick( callback ) { onClickCallback = callback; } function animate () { requestAnimationFrame( animate ); update(); render(); } function update () { stats.update(); TWEEN.update(); // camera.rotation.z += 0.001; let lastTime = currentTime; currentTime = Date.now() - initTime; let sin1 = Math.sin(currentTime * 0.001) * 0.1; let sin2 = Math.sin(currentTime * 0.001 + 2 * Math.PI / 3) * 0.1; let sin3 = Math.sin(currentTime * 0.001 + 4 * Math.PI / 3) * 0.1; bars.t0.objects.forEach(bar => { bar.mesh.position.y = sin3 * 0.4 * bar.randConst; // bar.mesh.position.z = sin1 * 0.5 * bar.randConst; // bar.mesh.rotation.x = sin1 * 0.01; }); bars.t1.objects.forEach(bar => { bar.mesh.position.y = sin1 * 0.4 * bar.randConst; // bar.mesh.position.z = sin2 * 0.5 * bar.randConst; // bar.mesh.rotation.x = sin2 * 0.01; }); bars.t2.objects.forEach(bar => { bar.mesh.position.y = sin2 * 0.4 * bar.randConst; // bar.mesh.position.z = sin3 * 0.5 * bar.randConst; // bar.mesh.rotation.x = sin3 * 0.01; }); if ( moveX && moveX > -1 ) { rootContainer.rotation.set(0, - moveX , 0 ); } else if ( moveX === -1 ) { var tween = new TWEEN.Tween( rootContainer.rotation, { y: rootContainer.rotation.y } ) .to( { y: 0 }, 400 ) .easing( TWEEN.Easing.Quartic.InOut ) .start(); moveX = null; } } function render () { renderer.render( scene, camera ); } function generateBars () { let randWidth, randHeight, randType, randX, randZ, randOpacity, size, pos, bar; for ( let i = 0; i < nbBars; i++ ) { randWidth = 0.01 + Math.random() / 20; randHeight = 0.5 + Math.random() * 1; randX = ( randomInt( 0, 100 ) - 50 ) / 90; randZ = Math.random() - 0.5; randType = randomInt( 0, 2 ); randOpacity = randomInt( 7, 10 ) * 0.1; size = new THREE.Vector3( randWidth, randHeight, randWidth * 0.001 ); pos = new THREE.Vector3( randX, 0, randZ ); bar = new Bar( size, pos, randType, randOpacity, texture ); bars['t' + randType].objects.push(bar); bars['t' + randType].container.add(bar.mesh); } } function highlightT( type ) { // console.log(type) if (currentHighlighted > -1) { var unHighlight = currentHighlighted; currentHighlighted = -1; var tween = new TWEEN.Tween( { x: 100 } ) .to( { x: 0 }, 750 ) .easing( TWEEN.Easing.Quartic.InOut ) .onUpdate( function () { bars['t' + unHighlight].objects.forEach(bar => { bar.mesh.scale.x = 1 + this.x * 0.02 * bar.randConst; bar.mesh.scale.y = 1 + this.x * 0.002 * bar.randConst; }); bars['t' + unHighlight].container.position.set(0, 0, this.x * 0.004); } ) .start(); } if (type !== currentHighlighted && type > -1) { currentHighlighted = type; $('.dimensions-select').removeClass('t0 t1 t2').addClass('t' + type); var tween = new TWEEN.Tween( { x: 0 } ) .to( { x: 100 }, 750 ) .easing( TWEEN.Easing.Quartic.InOut ) .onUpdate( function () { bars['t' + type].objects.forEach(bar => { bar.mesh.scale.x = 1 + this.x * 0.02 * bar.randConst; bar.mesh.scale.y = 1 + this.x * 0.002 * bar.randConst; }); bars['t' + type].container.position.set(0, 0, this.x * 0.004); } ) .start(); } } function highlightNext () { if (currentHighlighted === 2) { highlightT( 0 ); } else { highlightT( currentHighlighted + 1 ); } } function highlightPrev () { if (currentHighlighted <= 0) { highlightT( 2 ); } else { highlightT( currentHighlighted - 1 ); } } function initEvents () { renderer.domElement.addEventListener("touchstart", onTouchStart, false); renderer.domElement.addEventListener("touchmove", onTouchMove, false); renderer.domElement.addEventListener("touchend", onTouchEnd, false); renderer.domElement.addEventListener("click", onClick, false); window.addEventListener('resize', onWindowResize, false); } function onClick () { onClickCallback(currentHighlighted); } function onTouchStart ( event ) { startX = event.touches[0].clientX; startY = event.touches[0].clientY; } function onTouchMove ( event ) { moveX = (startX - event.touches[0].clientX) / width; moveY = (startY - event.touches[0].clientY) / height; } function onTouchEnd ( event ) { if ( moveX > 0.2 ) { highlightNext(); } else if ( moveX < -0.2 ) { highlightPrev(); } moveX = -1; moveY = -1; } function randomInt ( min, max ) { return Math.floor( Math.random() * ( max - min + 1 ) + min ); } function onWindowResize () { renderer.setSize( window.innerWidth, window.innerHeight ); camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); } module.exports = { init: init, highlightT: highlightT, setOnClick: setOnClick };
#!/usr/bin/env sh SCRIPT_DIR=`dirname ${BASH_SOURCE[0]}` source $SCRIPT_DIR/helper.sh ScriptInit ${BASH_SOURCE[0]} cd $PRG_DIR # check and delete virtual environment directories PYTHON_DEV_ENV=$PRG_DIR/dev_python_env APP_TOOLS=$PRG_DIR/tools [ -d $PYTHON_DEV_ENV ] && echo "Removing Python virtual environment at: $PYTHON_DEV_ENV" && $(rm -rf $PYTHON_DEV_ENV) [ -d $APP_TOOLS ] && echo "Removing Local tool virtualenv at: $APP_TOOLS" && $(rm -rf $APP_TOOLS) # unset environment variables unset DEV_ENV_HOME unset ENV_BIN unset ENV_PYTHON unset ENV_PIP cd $SAVED
<filename>quicktests/js/scale_interactive.js function makeData() { "use strict"; return [makeRandomData(50), makeRandomData(50)]; } function run(div, data, Plottable) { "use strict"; var svg = div.append("svg").attr("height", 500); data = _.cloneDeep(data); var dataseries = data[0].splice(0, 20); var xScale = new Plottable.Scale.Linear(); var xAxisLeft = new Plottable.Axis.Numeric(xScale, "bottom").tickLabelPosition("left"); var xAxisCenter = new Plottable.Axis.Numeric(xScale, "bottom"); var xAxisRight = new Plottable.Axis.Numeric(xScale, "bottom").tickLabelPosition("right"); var xAxisTable = new Plottable.Component.Table([[xAxisLeft], [xAxisCenter], [xAxisRight]]); var xAxisLeft2 = new Plottable.Axis.Numeric(xScale, "top").tickLabelPosition("left"); var xAxisCenter2 = new Plottable.Axis.Numeric(xScale, "top"); var xAxisRight2 = new Plottable.Axis.Numeric(xScale, "top").tickLabelPosition("right"); var xAxisTable2 = new Plottable.Component.Table([[xAxisLeft2], [xAxisCenter2], [xAxisRight2]]); var yScale = new Plottable.Scale.Linear(); var yAxisTop = new Plottable.Axis.Numeric(yScale, "left").tickLabelPosition("top"); var yAxisMiddle = new Plottable.Axis.Numeric(yScale, "left"); var yAxisBottom = new Plottable.Axis.Numeric(yScale, "left").tickLabelPosition("bottom"); var yAxisTable = new Plottable.Component.Table([[yAxisTop, yAxisMiddle, yAxisBottom]]); var yAxisTop2 = new Plottable.Axis.Numeric(yScale, "right").tickLabelPosition("top"); var yAxisMiddle2 = new Plottable.Axis.Numeric(yScale, "right"); var yAxisBottom2 = new Plottable.Axis.Numeric(yScale, "right").tickLabelPosition("bottom"); var yAxisTable2 = new Plottable.Component.Table([[yAxisTop2, yAxisMiddle2, yAxisBottom2]]); var renderAreaD1 = new Plottable.Plot.Scatter(xScale, yScale).addDataset(dataseries); var gridlines = new Plottable.Component.Gridlines(xScale, yScale); var basicTable = new Plottable.Component.Table([[null, xAxisTable2, null], [yAxisTable, renderAreaD1.merge(gridlines), yAxisTable2], [null, xAxisTable, null]]); basicTable.renderTo(svg); renderAreaD1.registerInteraction( new Plottable.Interaction.PanZoom(xScale, yScale) ); }
<reponame>song28/reservoir // 截取前边的非0数据, export function getPrefixAdcd(addvcd) { if(addvcd){ return addvcd.replace(/(0+)$/g,""); }else{ return ''; } } // 获取行政区编码的有效长度 export function getAdcdLen(addvcd){ if(addvcd){ addvcd = addvcd.replace(/(0+)$/g,""); let len = addvcd.length; let resLen; if(len <= 2){ resLen = 2; }else if(len <= 4){ resLen = 4; }else if(len <= 6){ resLen = 6; }else if(len <= 9){ resLen = 9; } return resLen; }else{ return null; } } // 获取下级行政区编码的有效长度 export function getChildAdcdLen(addvcd){ if(addvcd){ addvcd = addvcd.replace(/(0+)$/g,""); let len = addvcd.length; let resLen; if(len <= 2){ resLen = 4; }else if(len <= 4){ resLen = 6; }else if(len <= 6){ resLen = 9; }else if(len <= 9){ resLen = 12; } return resLen; }else{ return null; } }
package ru.job4j.coffeemachine; import org.junit.Test; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; /** * CoffeeMachineTest. * * @author <NAME> (<EMAIL>) * @version $Id$ * @since 0.1 */ public class CoffeeMachineTest { @Test public void whenValueIs50AndPriceIs35() { CoffeeMachine machine = new CoffeeMachine(); int[] expected = new int[] {10, 5}; assertThat(machine.changes(50, 35), is(expected)); } @Test public void whenValueIs500AndPriceIs111() { CoffeeMachine machine = new CoffeeMachine(); int[] expected = new int[] {200, 100, 50, 10, 10, 10, 5, 2, 2}; assertThat(machine.changes(500, 111), is(expected)); } @Test public void whenValueIs50AndPriceIs50() { CoffeeMachine machine = new CoffeeMachine(); int[] expected = new int[] {}; assertThat(machine.changes(50, 50), is(expected)); } @Test public void whenValueIs50AndPriceIs51() { CoffeeMachine machine = new CoffeeMachine(); int[] expected = new int[] {}; assertThat(machine.changes(50, 51), is(expected)); } }
<reponame>heySeattleW/wxshop public class PlatformApi { }
<form action="form_action.php" method="post"> Name:<br> <input type="text" name="name" value=""><br> Email:<br> <input type="text" name="email" value=""><br><br> <input type="submit" value="Submit"> </form>
<reponame>elixir-europe/plant-faidare package fr.inra.urgi.faidare.elasticsearch.document; import com.google.common.collect.ImmutableList; import java.beans.PropertyDescriptor; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Metadata about an Elasticsearch document * * @author gcornut */ public class DocumentMetadata<VO> { private final String documentType; private final String idField; private final Class<VO> documentClass; private final String[] excludedFields; private final Map<String, Field> fieldsByName; private final Map<List<String>, Field> fieldByPath; public DocumentMetadata(String documentType, String idField, Class<VO> documentClass, String[] excludedFields, Map<String, Field> fieldsByName) { this.documentType = documentType; this.idField = idField; this.documentClass = documentClass; this.excludedFields = excludedFields; this.fieldsByName = fieldsByName; this.fieldByPath = flattenDocumentFieldTree(ImmutableList.<String>of(), fieldsByName); } public String getDocumentType() { return documentType; } /** * Flatten the document field paths into a single map indexed by document field path (java path or JSON path) */ private static Map<List<String>, Field> flattenDocumentFieldTree(List<String> path, Map<String, Field> values) { Map<List<String>, Field> fieldByPath = new HashMap<>(); for (String name : values.keySet()) { Field field = values.get(name); List<String> newPath = ImmutableList.<String>builder().addAll(path).add(name).build(); fieldByPath.put(newPath, field); Map<String, Field> fieldsByName = field.fieldsByName; if (fieldsByName != null) { fieldByPath.putAll(flattenDocumentFieldTree(newPath, fieldsByName)); } } return fieldByPath; } public String getIdField() { return idField; } public String[] getExcludedFields() { return excludedFields; } public Class<VO> getDocumentClass() { return documentClass; } public Map<String, Field> getFieldsByName() { return fieldsByName; } public Field getByPath(List<String> documentFieldPath) { return fieldByPath.get(documentFieldPath); } public static class Field { private final boolean nestedObject; private final List<String> path; private final List<String> jsonPath; private final PropertyDescriptor descriptor; private final Map<String, Field> fieldsByName; private final Class<?> fieldClass; Field(List<String> path, List<String> jsonPath, Class<?> fieldClass, boolean nestedObject, PropertyDescriptor descriptor, Map<String, Field> fieldsByName) { this.jsonPath = jsonPath; this.nestedObject = nestedObject; this.path = path; this.fieldClass = fieldClass; this.descriptor = descriptor; this.fieldsByName = fieldsByName; } public Class<?> getFieldClass() { return fieldClass; } public boolean isNestedObject() { return nestedObject; } public List<String> getPath() { return path; } public List<String> getJsonPath() { return jsonPath; } public PropertyDescriptor getDescriptor() { return descriptor; } } }
import { Client } from "../src/index"; import { RequestErrType } from "../src/xhr/client"; const base = `https://jsonplaceholder.typicode.com`; const mock = { url: suffix => base + suffix, wait: ms => new Promise(resolve => setTimeout(resolve, ms)), }; Client.Timeout = 2000; interface Geo { lat: string; lng: string; } interface Address { street: string; suite: string; city: string; zipcode: string; geo: Geo; } interface Company { name: string; catchPhrase: string; bs: string; } interface User { id: number; name: string; username: string; email: string; address: Address; phone: string; website: string; company: Company; } describe("Client", async () => { it("should exist", async () => { expect(Client).toBeDefined(); }); it("should make a GET request", async () => { let result = await Client.get<User>(mock.url("/users/1")); expect(result.unwrap().data).toMatchSnapshot(); expect(result.unwrap().data.id).toBeDefined(); expect(typeof result.unwrap().data.id == "number").toBe(true); expect(typeof result.unwrap().data.name == "string").toBe(true); expect( Object.entries(result.unwrap().headers).map(([k, v]) => [k, typeof v]) ).toMatchSnapshot(); }); it("should make POST request", async () => { let data = { title: "foo", body: "bar", userId: 1, }; let result = await Client.post(mock.url("/posts"), data); expect(result.is_ok()).toBe(true); expect(result.unwrap().data).toMatchSnapshot(); }); it("should make PUT request", async () => { let data = { id: 1, title: "foo", body: "baz", userId: 1, }; let result = await Client.put(mock.url("/posts/1"), data); expect(result.is_ok()).toBe(true); expect(result.unwrap().data).toMatchSnapshot(); }); it("should make PATCH request", async () => { let data = { title: "bar", }; let result = await Client.patch(mock.url("/posts/1"), data); expect(result.is_ok()).toBe(true); expect(result.unwrap().data).toMatchSnapshot(); }); it("should make DELETE request", async () => { let result = await Client.delete(mock.url("/posts/1")); expect(result.is_ok()).toBe(true); expect(result.unwrap().data).toMatchSnapshot(); }); it("should abort with cancel token", async () => { let request = Client.create("GET", mock.url("/posts")); let cancel = request.getCancelToken(); enum Code { Abort = 1, HttpStatusErr = 2, Timeout = 3, XhrErr = 4, } // Spawn off the request let p1 = request.send(); let p2 = request.send(); // Cancel it right away cancel(); // Await the promise that was canceled let result = await p1; expect(result.is_err()).toBe(true); // extract the wrapped error value let err = result.unwrap_err(); expect(err.type).toBe(RequestErrType.Abort); expect( err.match({ Abort: () => Code.Abort, HttpStatusErr: () => Code.HttpStatusErr, Timeout: () => Code.Timeout, XhrErr: () => Code.XhrErr, }) ).toBe(Code.Abort); // Check the promises are the same expect(p1).toBe(p2); }); });
# Copyright © 2018 Software AG, Darmstadt, Germany and/or its licensors # # SPDX-License-Identifier: Apache-2.0 # # 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. #!/bin/bash WD=$(cd "$(dirname "$0")";pwd) if [ -z "$TC_HOME" ]; then echo "Please initialize the environment variable TC_HOME to the location of your extracted TerracottaDB kit" exit 1 fi if [ -z "$TC_VERSION" ]; then echo "Please initialize the environment variable TC_VERSION to the version of your extracted TerracottaDB kit" exit 1 fi if [ ! -d "${JAVA_HOME}" ]; then echo "$0: the JAVA_HOME environment variable is not defined correctly" exit 2 fi uname | grep CYGWIN > /dev/null && TC_HOME=$(cygpath -w -p "${TC_HOME}") echo "Starting build and servlet container on port 8082" ./mvnw verify cargo:run -Pcargo,8082
const express = require('express'); const app = express(); const bodyParser = require('body-parser'); let hours = { 'mon': 0, 'tue': 0, 'wed': 0, 'thu': 0, 'fri': 0 }; let person = { name: '', role: '', hours }; app.use(bodyParser.json()); app.post('/clockIn', function (req, res) { person.name = req.body.name; person.role = req.body.role; person.hours = req.body.workingHours; res.status(200).send('Clocked in successfully'); }); app.post('/clockOut', function (req, res) { let day = new Date().getDay(); let times = person.hours[Object.keys(person.hours)[day - 1]].split(' - '); let start = parseInt(times[0].split(':')[0] + times[0].split(':')[1]); let end = parseInt(times[1].split(':')[0] + times[1].split(':')[1]); let hoursWorked = end - start; hours[Object.keys(person.hours)[day - 1]] = hours[Object.keys(person.hours)[day - 1]] + hoursWorked; res.status(200).send('Clocked out successfully'); }); app.get('/hoursWorked', function (req, res) { let totalHoursWorked = 0; for (let day of Object.keys(hours)) { totalHoursWorked += hours[day]; } res.status(200).send(totalHoursWorked); }); let port = process.env.PORT || 4000; app.listen(port, function () { console.log(`Time & Attendance listening on port ${port}!`); });
if (( ${+commands[ansible]} )); then avdiff() { [[ $# -eq 2 ]] || { echo "Usage: $0 FILENAME FILENAME" >&2; exit 1 } command diff -dy -W${COLUMNS} \ =(command ansible-vault view "$1") \ =(command ansible-vault view "$2") } avdiffs() { [[ $# -eq 2 ]] || { echo "Usage: $0 FILENAME FILENAME" >&2; exit 1 } command diff -dy -W${COLUMNS} --suppress-common-lines \ =(command ansible-vault view "$1") \ =(command ansible-vault view "$2") } fi
class Animal: def __init__(self, name): self.name = name def make_sound(self): print("Generic animal sound") def display_info(self): print("Animal name:", self.name) class Cat(Animal): def make_sound(self): print(self.name + ": meowww..") # Example usage if __name__ == "__main__": animal = Animal("Tom") animal.display_info() animal.make_sound() cat = Cat("Whiskers") cat.display_info() cat.make_sound()
<filename>node_modules/googleapis/build/src/apis/replicapool/index.d.ts /*! THIS FILE IS AUTO-GENERATED */ import { replicapool_v1beta1 } from './v1beta1'; import { replicapool_v1beta2 } from './v1beta2'; export declare const VERSIONS: { 'v1beta1': typeof replicapool_v1beta1.Replicapool; 'v1beta2': typeof replicapool_v1beta2.Replicapool; }; export declare function replicapool(version: 'v1beta1'): replicapool_v1beta1.Replicapool; export declare function replicapool(options: replicapool_v1beta1.Options): replicapool_v1beta1.Replicapool; export declare function replicapool(version: 'v1beta2'): replicapool_v1beta2.Replicapool; export declare function replicapool(options: replicapool_v1beta2.Options): replicapool_v1beta2.Replicapool;
<reponame>proworkdev/pims import { Component, OnInit } from '@angular/core'; import {Router} from "@angular/router"; import { UserService } from '../../../user.service'; import { ActivatedRoute } from '@angular/router'; import { FormBuilder, Validators, FormGroup } from '@angular/forms'; import { AlertsService } from '@jaspero/ng2-alerts'; import { NgxEditorModule } from 'ngx-editor'; @Component({ selector: 'app-edit-product', templateUrl: './edit-product.component.html', styleUrls: ['./edit-product.component.scss'] }) export class EditProductComponent implements OnInit { htmlContent= "test"; sku:number; title = ''; image1:string = ''; image2:string = ''; image3:string = ''; image4:string = ''; image5:string = ''; image6:string = ''; image7:string = ''; eBay_Category_Id =''; tag:string = ''; qty= ''; ref_Id = ''; ref_Type=''; store_category_name:string; gmo_brand:string; gmo_mpn:string; gmo_category:string; item_specific_1_name:string; item_specific_2_name:string; item_specific_3_name:string; item_specific_4_name:string; item_specific_5_name:string; item_specific_6_name:string; item_specific_7_name:string; item_specific_8_name:string; item_specific_9_name:string; item_specific_1_value:string; item_specific_2_value:string; item_specific_3_value:string; item_specific_4_value:string; item_specific_5_value:string; item_specific_6_value:string; item_specific_7_value:string; item_specific_8_value:string; item_specific_9_value:string; description:string; id:number; hide:boolean; imgarray:any = []; index:number= 0; private sub: any; constructor( private router: Router, private userService: UserService, private activatedRoute: ActivatedRoute, private _alert: AlertsService ) { } ngOnInit() { this.sub = this.activatedRoute.params.subscribe(params => { this.id = +params['id']; // (+) converts string 'id' to a number this.hide = false; }); //console.log(this.id); this.userService.getProductByID(this.id).subscribe((data) => { var result = data.data[0]; this.id = result.table_id; this.sku = result.SKU; this.title = result.Title; this.image1 = result.Image1; this.image2 = result.Image2; this.image3 = result.Image3; this.image4 = result.Image4; this.image5 = result.Image5; this.image6 = result.Image6; this.image7 = result.Image7; this.tag = result.Tag; this.eBay_Category_Id = result.Ebay_category_id; this.qty= result.Qty; this.ref_Id = result.Ref_Id; this.ref_Type= result.Ref_type; this.store_category_name = result.Store_category_name; this.gmo_brand = result.GMO_Brand; this.gmo_mpn = result.GMO_MPN; this.gmo_category = result.GMO_Category; this.item_specific_1_name = result.Item_Specifics1_Name; this.item_specific_2_name = result.Item_Specifics2_Name; this.item_specific_3_name = result.Item_Specifics3_Name; this.item_specific_4_name = result.Item_Specifics4_Name; this.item_specific_5_name = result.Item_Specifics5_Name; this.item_specific_6_name = result.Item_Specifics6_Name; this.item_specific_7_name = result.Item_Specifics7_Name; this.item_specific_8_name = result.Item_Specifics8_Name; this.item_specific_9_name = result.Item_Specifics9_Name; this.item_specific_1_value = result.Item_Specifics1_Value; this.item_specific_2_value = result.Item_Specifics2_Value; this.item_specific_3_value = result.Item_Specifics3_Value; this.item_specific_4_value = result.Item_Specifics4_Value; this.item_specific_5_value = result.Item_Specifics5_Value; this.item_specific_6_value = result.Item_Specifics6_Value; this.item_specific_7_value = result.Item_Specifics7_Value; this.item_specific_8_value = result.Item_Specifics8_Value; this.item_specific_9_value = result.Item_Specifics9_Value; this.description = result.Description; console.log(this.item_specific_1_value); this.imgarray = [ { src: result.Image1, show: false }, { src: result.Image2, show: false }, { src: result.Image3, show: false }, { src: result.Image4, show: false }, { src: result.Image5, show: false }, { src: result.Image6, show: false }, { src: result.Image7, show: false }, ] }, err => { let error; let message; error = JSON.parse(err._body); message = error.message; const type = 'error'; // this._alert.create(type, message); alert(message); } ); }; public updateProduct(id,sku,title,image1,image2,image3,image4,image5,image6,image7,eBay_Category_Id,ref_Id,item_specific_1_name,item_specific_2_name,item_specific_3_name,item_specific_4_name,item_specific_5_name,item_specific_6_name,item_specific_7_name,item_specific_8_name,item_specific_9_name,store_category_name,gmo_brand,gmo_mpn,gmo_category,item_specific_1_value,item_specific_2_value,item_specific_3_value,item_specific_4_value,item_specific_5_value,item_specific_6_value,item_specific_7_value,item_specific_8_value,item_specific_9_value,description ){ let stype= ''; // console.log(id); this.userService.updateProductSku(id,sku,title,image1,image2,image3,image4,image5,image6,image7,eBay_Category_Id,ref_Id,item_specific_1_name,item_specific_2_name,item_specific_3_name,item_specific_4_name,item_specific_5_name,item_specific_6_name,item_specific_7_name,item_specific_8_name,item_specific_9_name,store_category_name,gmo_brand,gmo_mpn,gmo_category,item_specific_1_value,item_specific_2_value,item_specific_3_value,item_specific_4_value,item_specific_5_value,item_specific_6_value,item_specific_7_value,item_specific_8_value,item_specific_9_value,description ).subscribe((data) => { let message = data.message; const type = 'success'; this._alert.create(type, message); //this.router.navigate(['theme/product']); }, err => { let error; let message; } ); } public editImgTitle(imgarray: { src: string, show: boolean }){ console.log(imgarray,name); //this.show = true; this.hide = true; this.imgarray.map((l) => { if (l.src === imgarray.src) { l.show = !l.show; } else { l.show = false; } }) } }
def is_perfect(n): sum = 0 for i in range(1, n): if (n % i == 0): sum += i return sum == n
<filename>tailwind.config.js const defaultTheme = require('tailwindcss/defaultTheme') const colors = require('tailwindcss/colors') module.exports = { purge: { layers: ['utilities'], content: [ './src/**/*.php', './resources/views/**/*.php', './resources/js/**/*.js', './packages/forms/src/**/*.php', './packages/forms/resources/views/**/*.php', './packages/tables/src/**/*.php', './packages/tables/resources/views/**/*.php', ], }, theme: { extend: { fontFamily: { sans: ['Commissioner', ...defaultTheme.fontFamily.sans], mono: ['Space Mono', ...defaultTheme.fontFamily.mono], }, colors: { primary: { 100: 'var(--f-primary-100)', 200: 'var(--f-primary-200)', 300: 'var(--f-primary-300)', 400: 'var(--f-primary-400)', 500: 'var(--f-primary-500)', 600: 'var(--f-primary-600)', 700: 'var(--f-primary-700)', 800: 'var(--f-primary-800)', 900: 'var(--f-primary-900)', }, success: { 100: 'var(--f-success-100)', 200: 'var(--f-success-200)', 300: 'var(--f-success-300)', 400: 'var(--f-success-400)', 500: 'var(--f-success-500)', 600: 'var(--f-success-600)', 700: 'var(--f-success-700)', 800: 'var(--f-success-800)', 900: 'var(--f-success-900)', }, danger: { 100: 'var(--f-danger-100)', 200: 'var(--f-danger-200)', 300: 'var(--f-danger-300)', 400: 'var(--f-danger-400)', 500: 'var(--f-danger-500)', 600: 'var(--f-danger-600)', 700: 'var(--f-danger-700)', 800: 'var(--f-danger-800)', 900: 'var(--f-danger-900)', }, gray: { 100: 'var(--f-gray-100)', 200: 'var(--f-gray-200)', 300: 'var(--f-gray-300)', 400: 'var(--f-gray-400)', 500: 'var(--f-gray-500)', 600: 'var(--f-gray-600)', 700: 'var(--f-gray-700)', 800: 'var(--f-gray-800)', 900: 'var(--f-gray-900)', }, blue: { 100: 'var(--f-blue-100)', 200: 'var(--f-blue-200)', 300: 'var(--f-blue-300)', 400: 'var(--f-blue-400)', 500: 'var(--f-blue-500)', 600: 'var(--f-blue-600)', 700: 'var(--f-blue-700)', 800: 'var(--f-blue-800)', 900: 'var(--f-blue-900)', }, white: 'var(--f-white)', defaultPrimary: colors.lightBlue, defaultSuccess: colors.emerald, defaultDanger: colors.rose, defaultGray: colors.coolGray, defaultBlue: colors.blue, defaultWhite: colors.white }, keyframes: { shake: { '10%, 90%': { transform: 'translate3d(-1px, 0, 0)', }, '20%, 80%': { transform: 'translate3d(2px, 0, 0)', }, '30%, 50%, 70%': { transform: 'translate3d(-4px, 0, 0)', }, '40%, 60%': { transform: 'translate3d(4px, 0, 0)', }, }, }, typography: (theme) => ({ DEFAULT: { css: { a: { color: theme('colors.secondary.700'), '&:hover': { color: theme('colors.secondary.500'), }, }, }, }, }), }, }, variants: { extend: { padding: ['direction'], translate: ['direction'], space: ['direction'], } }, plugins: [ require('@tailwindcss/forms'), require('@tailwindcss/typography'), require('tailwindcss-dir'), ], }
if input_field < min_input or input_field > max_input: raise ValueError('Input must be between %d and %d' % (min_input, max_input))
import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import {NgxPaginationModule} from 'ngx-pagination'; import { MODULE_COMPONENTS, MODULE_ROUTES } from './dashboard.routes'; import { OrderBy } from './datatables/orderby' import {DatatableComponent} from './datatables/datatable.component'; import {ColumnComponent} from './datatables/column.component'; @NgModule({ imports: [ CommonModule, FormsModule, RouterModule.forChild(MODULE_ROUTES), NgxPaginationModule ], declarations: [ MODULE_COMPONENTS, DatatableComponent, ColumnComponent, OrderBy ] }) export class DashboardModule{}
# Copyright (C) 2008-2011, Gostai S.A.S. # # This software is provided "as is" without warranty of any kind, # either expressed or implied, including but not limited to the # implied warranties of fitness for a particular purpose. # # See the LICENSE file for more information. me=$(basename "$0") stderr () { local i for i do echo >&2 "$me (wrapper): $i" done } run () { verbose "run: $*" "$@" } error () { local exit="$1" shift stderr "$@" exit $exit } verbose () { case "$verbose: $VERBOSE " in (true:* | *" $me "* | *" x "*) stderr "$@" ;; esac } fatal () { error 1 "$@" } # Look for, and load, `msvc_env.sh'. load_msvc_env () { local i # Skip if we can't run it. for i in ~/share/wine ~/.wine/drive_c "$(dirname "$0")" ~/bin do local f="$i/msvc_env.sh" verbose "trying to load $f" if test -f "$f"; then . "$f" verbose "loaded $f" return 0 fi done return 1 } # setup # ----- # Load our configuration script and set up $repath; $VS_PATH, # $VCXX_PATH and $VCXX_BIN (Unix paths). setup () { load_msvc_env || error 72 "cannot load msvc_env.sh" repaths='cygpath winepath' for repath in $repaths '' do $repath --version >/dev/null 2>&1 && break done test -n "$repath" || error 72 "program not found: $repaths" VS_PATH=$($repath -u "$VSINSTALLDIR") VCXX_PATH=$($repath -u "$VCINSTALLDIR") VCXX_BIN=$VCXX_PATH/bin test -x "$VCXX_BIN/cl.exe" || error 72 "cl.exe not found in $VCXX_BIN" } # filter_wine() # ------------- # Stdin -> Stdout. filter_wine() { sed -e '/err:secur32:SECUR32_initSchannelSP.*not found/d' \ -e '/fixme:heap:HeapSetInformation (nil) 1 (nil) 0/d' } # Same as run, but neutralize Wine warnings, and Microsoft banners. # Needs $stdout, $stderr and return status. run_filter () { local status=0 run "$@" >$stdout 2>$stderr || status=$? # Warnings from wine. filter_wine <$stderr >&2 sed -e '/Microsoft (R) Library Manager/d' \ -e '/Microsoft (R) Windows (R) Resource Compiler/d' \ -e '/Copyright (C) Microsoft Corporation/d' \ -e 's/\r//g' \ -e '/^ *$/d' \ <$stdout return $status }
#!/bin/bash set -e -x # Replace native compilation flags with more generic ones. cp make.inc.manylinux make.inc # Clean up the build and make the library. make clean make lib # Test to make sure everything is ok. make test # Needed for pip install to work export FINUFFT_DIR=$(pwd) # Needed for auditwheel to find the dynamic libraries export LD_LIBRARY_PATH=${FINUFFT_DIR}/lib:${LD_LIBRARY_PATH} pys=(/opt/python/*/bin) # Filter out old Python versions pys=(${pys[@]//*27*/}) pys=(${pys[@]//*34*/}) pys=(${pys[@]//*35*/}) pys=(${pys[@]//*pp38-pypy38_pp73*/}) # build wheel for PYBIN in "${pys[@]}"; do "${PYBIN}/pip" install --upgrade pip "${PYBIN}/pip" install auditwheel wheel twine numpy "${PYBIN}/pip" wheel ./python -w python/wheelhouse done # fix wheel for whl in python/wheelhouse/finufft-*.whl; do auditwheel repair "$whl" -w python/wheelhouse/ done # test wheel for PYBIN in "${pys[@]}"; do "${PYBIN}/pip" install finufft -f ./python/wheelhouse/ "${PYBIN}/python" ./python/test/run_accuracy_tests.py done
def printStars(n): for i in range(1,n+1): for j in range(1,i+1): print("*", end="") print("\n") if __name__ == "__main__": n = 5 printStars(n)
#!/bin/bash set -e # Available configuration variables. declare -A vars=( \ [groupid]=groupid \ [awtenantcode]=awtenantcode \ [host]=host ) # Work out which of the available variables have been set. declare -A varsSet for var in "${!vars[@]}"; do value=${vars[$var]} if [[ -v $value ]]; then varsSet[$var]=${!value} fi done keys=(${!varsSet[@]}) lastIndex=$(( ${#varsSet[@]} - 1 )) # Iterate over the set variables and echo out the corresponding JSON. echo "{" for (( i=0 ; i < "${#varsSet[@]}" ; i++ )); do key=(${keys[$i]}) value=(${varsSet[$key]}) kvPair=" \"$key\": \"$value\"" # If this is the last variable, don't print out a comma at the end of the # line. if [[ ! $i -eq $lastIndex ]]; then kvPair+=","; fi echo "$kvPair" done echo "}"
#include <iostream> // A linked list node struct Node { int data; struct Node *next; }; // Function to create a new node struct Node *newNode(int key) { Node *temp = new Node; temp->data = key; temp->next = NULL; return temp; }; // Function to insert a new node at the beginning // of the linked list struct Node *insertAtBeginning(struct Node *head, int key) { // Allocate memory for the new node Node *temp = newNode(key); // Link the old head to the new node temp->next = head; // Set the new node as the head head = temp; return head; }; // Function to insert a new node after a given node struct Node *insertAfter(struct Node *head, int key, struct Node *prev) { //NULL should not be passed as a prev node if (prev == NULL) return NULL; // Allocate memory for the new node Node *temp = newNode(key); // Link the old prev_node's next to the newly // created node temp->next = prev->next; prev->next = temp; return head; }; // Function to insert a new node at the end struct Node* insertAtEnd(struct Node *head, int key) { // Allocate memory for the new node Node *temp = newNode(key); // If the linked list is empty, then // make the new node as head if (head == NULL) return temp; // Otherwise, traverse to the last node Node *ptr = head; while (ptr->next != NULL) ptr = ptr->next; // Create the new node's link ptr->next = temp; return head; };
#!/bin/bash echo "Cloning LICENSE to balm packages" cat LICENSE ls -db ./packages/*/ | xargs -n 1 cp LICENSE
#!/usr/bin/env sh # generated from catkin/cmake/template/local_setup.sh.in # since this file is sourced either use the provided _CATKIN_SETUP_DIR # or fall back to the destination set at configure time : ${_CATKIN_SETUP_DIR:=/home/ub/cvbridge_build_ws/devel/.private/cv_bridge} CATKIN_SETUP_UTIL_ARGS="--extend --local" . "$_CATKIN_SETUP_DIR/setup.sh" unset CATKIN_SETUP_UTIL_ARGS
<reponame>MarkoIvanetic/habit-project<gh_stars>0 import React, { useState } from 'react' import PropTypes, { number, shape } from 'prop-types' import { AddCircleOutline, RemoveCircleOutline } from '@material-ui/icons' import { Button, Grid, Popover, TableCell as RaTableCell, Typography } from '@material-ui/core' import RemoveCircleOutlineIcon from '@material-ui/icons/RemoveCircleOutline' import { makeStyles, styled } from '@material-ui/core/styles' const TableCell = styled(RaTableCell)( ({ theme }) => ({ padding: 0, '&:hover': { background: theme.palette.grey[200], cursor: 'pointer' } }), { name: 'HbtTableCell' } ) const CalendarCell = ({ habits, data }) => { const [anchorEl, setAnchorEl] = useState(null) const [score, setScore] = useState(0) const handleClick = event => { setAnchorEl(event.currentTarget) } const handleClose = () => { setAnchorEl(null) } const open = Boolean(anchorEl) const id = open ? 'simple-popover' : undefined return ( <TableCell align="right"> <div style={{ position: 'relative' }}> <Typography style={{ padding: '8px' }} onClick={handleClick}> {score} </Typography> <Popover id={id} open={open} anchorEl={anchorEl} onClose={handleClose} anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }} transformOrigin={{ vertical: 'top', horizontal: 'center' }}> <Grid container direction="column" justify="center" alignItems="center"> <Button size="small" onClick={() => setScore(score + data.points)}> <AddCircleOutline /> </Button> <Button size="small" onClick={() => setScore(score > data.points ? score - data.points : 0)}> <RemoveCircleOutline /> </Button> </Grid> </Popover> </div> </TableCell> ) } CalendarCell.propTypes = { data: shape({ points: number }), habits: shape([]) } CalendarCell.defaultProps = { habits: [] } export default CalendarCell
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { I18n } from '@aws-amplify/core'; import React from 'react'; import Form from 'react-bootstrap/Form'; import { CreatedBy, FormControlElement, GreengrassCoreDeviceDomIds, UserGreengrassCoreDevice } from '../../util/types'; type GreengrassCoreDeviceInputFormRequest = { createdBy: CreatedBy; domIds: GreengrassCoreDeviceDomIds; greengrassCoreDeviceName: string; greengrassCoreDevices: UserGreengrassCoreDevice[]; handleValueChange: (event: React.ChangeEvent<FormControlElement>) => void; isGreengrassCoreDeviceNameValid: boolean; }; /** * Renders the Greengrass core device input form. * @param props The Greengrass core device input properties * @returns The Greengrass core device input form */ export default function GreengrassCoreDeviceInputForm(props: GreengrassCoreDeviceInputFormRequest): JSX.Element { const { createdBy, domIds, greengrassCoreDeviceName, greengrassCoreDevices, handleValueChange, isGreengrassCoreDeviceNameValid } = props; return ( <Form.Group> <Form.Label> {I18n.get('greengrass.core.device.name')} <span className="red-text">*</span> </Form.Label> {createdBy === CreatedBy.SYSTEM && ( <> <Form.Text muted>{I18n.get('description.greengrass.core.device.name')}</Form.Text> <Form.Control id={domIds.greengrassCoreDeviceName} type="text" required defaultValue={greengrassCoreDeviceName} placeholder={I18n.get('placeholder.greengrass.core.device.name')} onChange={handleValueChange} isInvalid={!isGreengrassCoreDeviceNameValid} /> <Form.Control.Feedback type="invalid"> {I18n.get('invalid.greengrass.core.device.name')} </Form.Control.Feedback> </> )} {createdBy === CreatedBy.USER && ( <> <Form.Text muted>{I18n.get('description.existing.greengrass.core.device.name')}</Form.Text> <Form.Control data-testid="user-greengrass-core-device-select" id={domIds.greengrassCoreDeviceName} as="select" onChange={handleValueChange} value={greengrassCoreDeviceName}> {greengrassCoreDevices.length === 0 && <option>{I18n.get('no.available.greengrass.core.devices')}</option>} {greengrassCoreDevices.length > 0 && greengrassCoreDevices.map((greengrassCoreDevice: UserGreengrassCoreDevice) => ( <option key={`greengrass-core-device-${greengrassCoreDevice.coreDeviceThingName}`} value={greengrassCoreDevice.coreDeviceThingName}> {greengrassCoreDevice.coreDeviceThingName} ({greengrassCoreDevice.status}) </option> ))} </Form.Control> </> )} </Form.Group> ); }
<reponame>tdrv90/freeCodeCamp // (1) Using var, declare a global variable myGlobal outside of any function. Initialize it with a value of 10. // (2) Inside function fun1, assign 5 to oopsGlobal without using the var keyword. // Declare your variable here var myGlobal = 10; function fun1() { // Assign 5 to oopsGlobal Here oopsGlobal = 5; } // Only change code above this line function fun2() { var output = ""; if (typeof myGlobal != "undefined") { output += "myGlobal: " + myGlobal; } if (typeof oopsGlobal != "undefined") { output += " oopsGlobal: " + oopsGlobal; } console.log(output); }
class LinearEquation { int coefficient; int constant; public LinearEquation(int coefficient, int constant) { this.coefficient = coefficient; this.constant = constant; } public int getCoefficient() { return coefficient; } public int getConstant() { return constant; } public int getResult() { return coefficient * 5 + constant; } }
<reponame>luoyefeiwu/learn_reactNative import React, {Component} from 'react'; import {WebView} from 'react-native-webview'; import {StyleSheet} from 'react-native'; export default class Map extends Component { render() { return ( <WebView source={{uri: 'https://m.baidu.com'}} style={styles.webview} /> ); } } const styles = StyleSheet.create({ webview: { width: '100%', height: '100%', }, });
<filename>lib/showVersion.js const packageJson = require('../package.json'); module.exports = () => { console.log(`${packageJson.version}`); };
const http = require('http'); const fs = require('fs'); const server = http.createServer((req, res) => { fs.readFile('./index.html', 'utf-8', (err, data) => { if (err) { res.writeHead(500); res.end('Error'); } else { res.writeHead(200, { 'Content-Type': 'text/html' }); res.end(data); } }); }); const port = 5000; server.listen(port, () => { console.log(`Server running on port ${port}`); }); <!DOCTYPE html> <html> <head> <title>Web Server</title> </head> <body> <h1>Form</h1> <form> <input type="text" name="name" placeholder="Enter Your Name"> <input type="email" name="email" placeholder="Enter Your Email"> <input type="password" name="password" placeholder="Enter Your Password"> <input type="submit" value="Submit"> </form> </body> </html>
<gh_stars>0 export interface Livre { id: number; Name: String; ImageUrl: string; ShortDescription: string; Price: number; Category: string; Etoile: number }
/* * Copyright 2018-2020 <NAME> * * 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.pranavpandey.android.dynamic.support.setting; import android.content.Context; import android.content.SharedPreferences; import android.content.res.TypedArray; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.AttrRes; import androidx.annotation.LayoutRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.pranavpandey.android.dynamic.preferences.DynamicPreferences; import com.pranavpandey.android.dynamic.support.R; import com.pranavpandey.android.dynamic.support.model.DynamicAppTheme; import com.pranavpandey.android.dynamic.support.theme.DynamicTheme; import com.pranavpandey.android.dynamic.support.theme.view.DynamicThemePreview; /** * A {@link DynamicSpinnerPreference} to display and edit the dynamic theme. */ public class DynamicThemePreference extends DynamicSpinnerPreference { /** * Default theme value for this preference. */ private String mDefaultTheme; /** * Current theme value for this preference. */ private String mTheme; /** * Current dynamic theme value for this preference. */ private DynamicAppTheme mDynamicAppTheme; /** * {@code true} if theme preview is enabled. */ private boolean mThemeEnabled; /** * Theme preview used by this preference. */ private DynamicThemePreview mThemePreview; /** * Theme preview icon used by this preference. */ private ImageView mThemePreviewIcon; /** * Theme preview description used by this preference. */ private TextView mThemePreviewDescription; /** * On click listener to receive theme click events. */ private View.OnClickListener mOnThemeClickListener; public DynamicThemePreference(@NonNull Context context) { super(context); } public DynamicThemePreference(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public DynamicThemePreference(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onLoadAttributes(@Nullable AttributeSet attrs) { super.onLoadAttributes(attrs); TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.DynamicThemePreference); try { mDefaultTheme = a.getString( R.styleable.DynamicThemePreference_ads_theme); } finally { a.recycle(); } if (mDefaultTheme == null) { mDefaultTheme = DynamicTheme.getInstance().get().toJsonString(); } mThemeEnabled = true; } @Override protected @LayoutRes int getLayoutRes() { return R.layout.ads_preference_theme; } @Override protected void onInflate() { super.onInflate(); mThemePreview = findViewById(R.id.ads_theme_preview); mThemePreviewIcon = findViewById(R.id.ads_theme_preview_icon); mThemePreviewDescription = findViewById(R.id.ads_theme_preview_description); mThemePreviewDescription.setText(R.string.ads_theme_background_aware_desc); } @Override public @Nullable String getPreferenceKey() { return getAltPreferenceKey(); } @Override protected void onUpdate() { super.onUpdate(); mTheme = DynamicPreferences.getInstance() .load(super.getPreferenceKey(), mDefaultTheme); mDynamicAppTheme = DynamicTheme.getInstance().getTheme(mTheme); if (mDynamicAppTheme != null) { mThemePreview.setDynamicTheme(mDynamicAppTheme); mThemePreviewDescription.setVisibility( mDynamicAppTheme.isBackgroundAware() ? VISIBLE : GONE); } } @Override protected void onEnabled(boolean enabled) { super.onEnabled(enabled); mThemePreview.setEnabled(enabled && mThemeEnabled); mThemePreviewIcon.setEnabled(enabled && mThemeEnabled); mThemePreviewDescription.setEnabled(enabled && mThemeEnabled); } /** * Enable or disable the theme preview. * * @param enabled {@code true} to enable the theme preview. */ public void setThemeEnabled(boolean enabled) { this.mThemeEnabled = enabled; setEnabled(isEnabled()); } /** * Get the default theme value for this preference. * * @return The default theme value for this preference. */ public @Nullable String getDefaultTheme() { return mDefaultTheme; } /** * Set the default theme value for this preference. * * @param defaultTheme The default theme value to be set. */ public void setDefaultTheme(@NonNull String defaultTheme) { this.mDefaultTheme = defaultTheme; onUpdate(); } /** * Get the current theme value for this preference. * * @return The current theme value for this preference. */ public @Nullable String getTheme() { return mTheme; } /** * Set the current theme value of this preference. * * @param theme The theme value to be set. * @param save {@code true} to update the shared preferences. */ public void setTheme(@NonNull String theme, boolean save) { this.mTheme = theme; if (getPreferenceKey() != null && save) { DynamicPreferences.getInstance().save(getPreferenceKey(), theme); } } /** * Set the current theme value of this preference. * * @param theme The theme value to be set. */ public void setTheme(@NonNull String theme) { setTheme(theme, true); } /** * Returns the on click listener to receive theme click events. * * @return The on click listener to receive theme click events. */ public OnClickListener getOnThemeClickListener() { return mOnThemeClickListener; } /** * Set the on click listener for theme to receive the click events and to perform * edit operation. * * @param onThemeClickListener The on click listener to be set. */ public void setOnThemeClickListener(@Nullable View.OnClickListener onThemeClickListener) { this.mOnThemeClickListener = onThemeClickListener; mThemePreview.setOnActionClickListener(mOnThemeClickListener); onEnabled(isEnabled()); } /** * Get the theme preview used by this preference. * * @return The theme preview used by this preference. */ public DynamicThemePreview getThemePreview() { return mThemePreview; } /** * Get the root view for the theme preview used by this preference. * * @return The root view for the theme preview used by this preference. */ public ViewGroup getThemePreviewRoot() { return findViewById(R.id.ads_theme_preview_root); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { super.onSharedPreferenceChanged(sharedPreferences, key); if (key.equals(super.getPreferenceKey())) { mTheme = DynamicPreferences.getInstance().load(super.getPreferenceKey(), mTheme); onUpdate(); } } }
// Copyright 2013 The Apache Software Foundation // // 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.apache.tapestry5.ioc.internal; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import org.apache.tapestry5.ioc.annotations.Advise; import org.apache.tapestry5.ioc.annotations.IntermediateType; import org.apache.tapestry5.plastic.MethodAdvice; import org.apache.tapestry5.plastic.MethodInvocation; final public class TestAdvice implements MethodAdvice { public static final String ANNOTATION_FOUND = "Annotation found!"; @Override public void advise(MethodInvocation invocation) { final Method method = invocation.getMethod(); boolean annotationFoundInMethod = checkAnnotation(method.getAnnotation(Advise.class)); boolean annotationFoundThroughAnnotationProvider = checkAnnotation(invocation.getAnnotation(Advise.class)); IntermediateType parameterAnnotation = null; final Annotation[][] parameterAnnotations = method.getParameterAnnotations(); if (parameterAnnotations.length > 0 && parameterAnnotations[0].length > 0) { parameterAnnotation = (IntermediateType) parameterAnnotations[0][0]; } boolean annotationParameter = parameterAnnotation != null && parameterAnnotation.value() == String.class; if (annotationFoundInMethod && annotationFoundThroughAnnotationProvider && annotationParameter) { invocation.setReturnValue(ANNOTATION_FOUND); } else { invocation.proceed(); } } private boolean checkAnnotation(Advise annotation) { return annotation != null && "id".equals(annotation.id()) && NonAnnotatedServiceInterface.class.equals(annotation.serviceInterface()); } }
<filename>robocode.core/src/main/java/net/sf/robocode/ui/IWindowManager.java /** * Copyright (c) 2001-2017 <NAME> and Robocode contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://robocode.sourceforge.net/license/epl-v10.html */ package net.sf.robocode.ui; import net.sf.robocode.gui.IWindowManagerBase; import net.sf.robocode.repository.IRobotSpecItem; import robocode.control.events.IBattleListener; import robocode.control.snapshot.ITurnSnapshot; import javax.swing.*; /** * @author <NAME> (original) * @author <NAME>. /<NAME> (contributor naval) */ public interface IWindowManager extends IWindowManagerBase { void init(); void setEnableGUI(boolean enable); boolean isGUIEnabled(); boolean isSlave(); boolean isShowResultsEnabled(); boolean isIconified(); void setSlave(boolean slave); void showRobocodeFrame(boolean visible, boolean iconified); void showSplashScreen(); void cleanup(); void closeCompetitionServer(); void sendRobot(String ipString, int portNumber, IRobotSpecItem robot); JFrame getRobocodeFrame(); void setBusyPointer(boolean enabled); void setStatus(String s); ITurnSnapshot getLastSnapshot(); void addBattleListener(IBattleListener listener); void removeBattleListener(IBattleListener listener); void runIntroBattle(); }
package io.cattle.platform.process.progress; import io.cattle.platform.engine.process.ProcessState; public interface ProcessProgress { ProcessProgressInstance get(); void init(ProcessState state); void checkPoint(String name); }
// import Chat from "../../components/chat/chat4" // import Sidebar from "../components/sidebar/Sidebar"; // import Rightbar from "../../components/rightbar/Rightbar"; // import RightMess from "../../components/rightbar/RightMess" // import Sidebar from "../../components/sidebar/Sidebar2" import Chat from "./Chat" // import s from "./message.module.css" import { useLocation } from 'react-router-dom' export default function Message(){ const location = useLocation() let contact = { show: true } if(location.state){ contact = location.state } // console.log(contact) return( <div > <Chat contact={contact}/> </div> ) }
<gh_stars>0 const test = require('ava'); const times = require('lodash/times'); const Queue = require('../queue'); test.cb('Array size: 20, prefetch: 5', t => { const emails = []; const queue = new Queue({emails, prefetch: 5}); times(20, () => { emails.push({from: 'Identifi <<EMAIL>>', to: '<EMAIL>', content: 'sample email'}); }); queue.on('dispatch', data => { t.is(data.dispatched.length, 5); }); queue.on('done', t.end); queue.dispatch(); }); test.cb('Array size: 3, prefetch: 5', t => { const emails = []; const queue = new Queue({emails, prefetch: 5}); times(3, () => { emails.push({from: 'Identifi <<EMAIL>>', to: '<EMAIL>', content: 'sample email'}); }); queue.on('dispatch', data => { t.is(data.dispatched.length, 3); }); queue.on('done', t.end); queue.dispatch(); }); test.cb('Array size: 1, prefetch: 5', t => { const queue = new Queue({ emails: [{from: 'Identifi <<EMAIL>>', to: '<EMAIL>', content: 'sample email'}], prefetch: 5 }); queue.on('dispatch', data => { t.is(data.dispatched.length, 1); }); queue.on('done', t.end); queue.dispatch(); }); test.cb('Array size: 1, prefetch: 1', t => { const queue = new Queue({ emails: [{from: 'Identifi <<EMAIL>>', to: '<EMAIL>', content: 'sample email'}], prefetch: 5 }); queue.on('dispatch', data => { t.is(data.dispatched.length, 1); }); queue.on('done', t.end); queue.dispatch(); }); test.cb('Array size: 0, prefetch: 5', t => { const queue = new Queue({emails: [], prefetch: 5}); queue.on('dispatch', () => { t.fail(); }); queue.on('done', t.end); queue.dispatch(); });
<reponame>NajibAdan/kitsu-server # rubocop:disable Metrics/LineLength # == Schema Information # # Table name: anime_staff # # id :integer not null, primary key # role :string # created_at :datetime # updated_at :datetime # anime_id :integer not null, indexed, indexed => [person_id] # person_id :integer not null, indexed => [anime_id], indexed # # Indexes # # index_anime_staff_on_anime_id (anime_id) # index_anime_staff_on_anime_id_and_person_id (anime_id,person_id) UNIQUE # index_anime_staff_on_person_id (person_id) # # Foreign Keys # # fk_rails_cdd9599b2a (person_id => people.id) # fk_rails_f8b16cdc79 (anime_id => anime.id) # # rubocop:enable Metrics/LineLength FactoryBot.define do factory :anime_staff do association :anime, factory: :anime, strategy: :build association :person, factory: :person, strategy: :build end end
DELETE FROM students WHERE id NOT IN ( SELECT min_id FROM ( SELECT MIN(id) as min_id FROM students GROUP BY name ) as temp_table )
#!/bin/bash set -e function abort() { echo "$@" exit 1 } function cleanup() { echo " --> Stopping container" docker stop $ID >/dev/null docker rm $ID >/dev/null } PWD=`pwd` echo " --> Starting container" ID=`docker run -d $NAME:$VERSION` sleep 1 echo " --> Running node --version" RETVAL=`docker exec $ID /usr/bin/node --version` if [[ "$RETVAL" != "v$NODEVERSION" ]]; then abort "Wrong version returned" fi trap cleanup EXIT
package com.yoga.tenant.tenant.service; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service public class TenantChangedObserver { private List<TenantChangedListener> changedListeners = new ArrayList<>(); public void register(TenantChangedListener entry) { synchronized (TenantChangedObserver.class) { changedListeners.add(entry); } } public void unregister(TenantChangedListener entry) { synchronized (TenantChangedObserver.class) { changedListeners.remove(entry); } } public void onCreated(long tenantId, String name, String code) throws Exception { for (TenantChangedListener listener : changedListeners) { listener.onCreated(tenantId, name, code); } } public void onModuleChanged(long tenantId, String[] modules) throws Exception { for (TenantChangedListener listener : changedListeners) { listener.onModuleChanged(tenantId, modules); } } public void onMenuAdded(long tenantId, String name, String url) throws Exception { for (TenantChangedListener listener : changedListeners) { listener.onMenuAdded(tenantId, name, url); } } public void onMenuDeleted(long tenantId, String name, String url) { for (TenantChangedListener listener : changedListeners) { listener.onMenuDeleted(tenantId, name, url); } } public void onDeleted(long tenantId) { for (TenantChangedListener listener : changedListeners) { listener.onDeleted(tenantId); } } public void onRenew(long tenantId) { for (TenantChangedListener listener : changedListeners) { listener.onRenew(tenantId); } } }
#!/bin/sh # 当前目录 CURRENT_DIR=$( cd "$(dirname "$0")" pwd ) #Install docker if which docker >/dev/null; then echo "检测到 Docker 已安装,跳过安装步骤" docker -v echo "启动 Docker " service docker start 2>&1 | tee -a ${CURRENT_DIR}/install.log else if [[ -d "$CURRENT_DIR/docker" ]]; then echo "... 离线安装 docker" cp $CURRENT_DIR/docker/centos-local.tgz /root/ cd /root && tar -xvzf centos-local.tgz cd /root/docker-ce-local &&rpm -ivh createrepo-0.9.9-28.el7.noarch.rpm mkdir -p /etc/yum.repos.d/repobak && mv /etc/yum.repos.d/CentOS* /etc/yum.repos.d/repobak cp $CURRENT_DIR/docker/docker-ce-local.repo /etc/yum.repos.d/docker-ce-local.repo cd /root/docker-ce-local &&createrepo /root/docker-ce-local && yum makecache cd $CURRENT_DIR/docker/ &&yum install -y container-selinux-2.9-4.el7.noarch.rpm &&yum install -y docker-ce echo "... 启动 docker" sudo systemctl start docker 2>&1 | tee -a ${CURRENT_DIR}/install.log echo '{"registry-mirrors":["https://registry.docker-cn.com"]}'>/etc/docker/daemon.json cat /etc/docker/daemon.json service docker restart else echo "... 在线安装 docker" curl -fsSL https://get.docker.com -o get-docker.sh 2>&1 | tee -a ${CURRENT_DIR}/install.log sudo sh get-docker.sh 2>&1 | tee -a ${CURRENT_DIR}/install.log echo "... 启动 docker" service docker start 2>&1 | tee -a ${CURRENT_DIR}/install.log fi fi ##Install Latest Stable Docker Compose Release if which docker-compose >/dev/null; then echo "检测到 Docker Compose 已安装,跳过安装步骤" docker-compose -v else if [[ -d "$CURRENT_DIR/docker-compose" ]]; then echo "... 离线安装 docker-compose" cd $CURRENT_DIR/docker-compose/ && cp docker-compose /usr/local/bin/ chmod +x /usr/local/bin/docker-compose docker-compose -version echo "... 离线安装 docker-compose 成功" else echo "... 在线安装 docker-compose" curl -L "https://github.com/docker/compose/releases/download/1.14.0-rc2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose 2>&1 | tee -a ${CURRENT_DIR}/install.log chmod +x /usr/local/bin/docker-compose ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose docker-compose -version echo "... 在线安装 docker-compose 成功" fi fi
<reponame>ArielYanarico/github-summary import parse from 'parse-link-header'; import {api} from '../settings' //const api = 'https://api.github.com'; const headers = {} export const getUsersSince = (sinceId) => fetch(`${api}/users?since=${sinceId}`, { headers }) .then(res => res.json()); export const getReposPaginated = (userName, page) => fetch(`${api}/users/${userName}/repos?page=${page}`, { headers }) .then(res => ({ link: parse(res.headers.get('Link')), json: res.json() })); export const getAllIssuesFromRepo = (repoFullName) => fetch(`${api}/search/issues?q=repo:${repoFullName}+type:issue`, { headers }) .then(res => res.json());
#!/bin/bash # 1 : String prefix # 2 : String config_file # 3 : int num_partitions # 4 : boolean verbose java -jar $OTMMPIHOME/target/otm-mpi-1.0-SNAPSHOT-jar-with-dependencies.jar $1 $2 $3 $4
const url = 'https://jsonplaceholder.typicode.com/todos'; fetch(url) .then(response => response.json()) .then(json => { console.log(json); });
#! /bin/bash # # Copyright 2021 Alexander Grund # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) # # Executes the install phase for GHA # Needs env variables: # - B2_COMPILER # - B2_CXXSTD # - B2_SANITIZE set -ex BOOST_CI_TARGET_BRANCH="${GITHUB_BASE_REF:-$GITHUB_REF}" export BOOST_CI_TARGET_BRANCH="${BOOST_CI_TARGET_BRANCH##*/}" # Extract branch name export BOOST_CI_SRC_FOLDER="${GITHUB_WORKSPACE//\\//}" echo "BOOST_CI_TARGET_BRANCH=$BOOST_CI_TARGET_BRANCH" >> $GITHUB_ENV echo "BOOST_CI_SRC_FOLDER=$BOOST_CI_SRC_FOLDER" >> $GITHUB_ENV if [[ "$B2_SANITIZE" == "yes" ]]; then B2_ASAN=1 B2_UBSAN=1 if [[ -f $BOOST_CI_SRC_FOLDER/ubsan-blacklist ]]; then B2_CXXFLAGS="${B2_CXXFLAGS:+$B2_CXXFLAGS }-fsanitize-blacklist=libs/$SELF/ubsan-blacklist" fi if [[ -f $BOOST_CI_SRC_FOLDER/.ubsan-ignorelist ]]; then B2_CXXFLAGS="${B2_CXXFLAGS:+$B2_CXXFLAGS }-fsanitize-blacklist=libs/$SELF/.ubsan-ignorelist" fi fi . $(dirname "${BASH_SOURCE[0]}")/../common_install.sh # Persist the environment for all future steps # Set by common_install.sh echo "SELF=$SELF" >> $GITHUB_ENV echo "BOOST_ROOT=$BOOST_ROOT" >> $GITHUB_ENV echo "B2_TOOLSET=$B2_TOOLSET" >> $GITHUB_ENV echo "B2_COMPILER=$B2_COMPILER" >> $GITHUB_ENV # Usually set by the env-key of the "Setup Boost" step [ -z "$B2_CXXSTD" ] || echo "B2_CXXSTD=$B2_CXXSTD" >> $GITHUB_ENV [ -z "$B2_CXXFLAGS" ] || echo "B2_CXXFLAGS=$B2_CXXFLAGS" >> $GITHUB_ENV [ -z "$B2_DEFINES" ] || echo "B2_DEFINES=$B2_DEFINES" >> $GITHUB_ENV [ -z "$B2_INCLUDE" ] || echo "B2_INCLUDE=$B2_INCLUDE" >> $GITHUB_ENV [ -z "$B2_LINKFLAGS" ] || echo "B2_LINKFLAGS=$B2_LINKFLAGS" >> $GITHUB_ENV [ -z "$B2_TESTFLAGS" ] || echo "B2_TESTFLAGS=$B2_TESTFLAGS" >> $GITHUB_ENV [ -z "$B2_ADDRESS_MODEL" ] || echo "B2_ADDRESS_MODEL=$B2_ADDRESS_MODEL" >> $GITHUB_ENV [ -z "$B2_LINK" ] || echo "B2_LINK=$B2_LINK" >> $GITHUB_ENV [ -z "$B2_VISIBILITY" ] || echo "B2_VISIBILITY=$B2_VISIBILITY" >> $GITHUB_ENV [ -z "$B2_STDLIB" ] || echo "B2_STDLIB=$B2_STDLIB" >> $GITHUB_ENV [ -z "$B2_THREADING" ] || echo "B2_THREADING=$B2_THREADING" >> $GITHUB_ENV [ -z "$B2_VARIANT" ] || echo "B2_VARIANT=$B2_VARIANT" >> $GITHUB_ENV [ -z "$B2_ASAN" ] || echo "B2_ASAN=$B2_ASAN" >> $GITHUB_ENV [ -z "$B2_TSAN" ] || echo "B2_TSAN=$B2_TSAN" >> $GITHUB_ENV [ -z "$B2_UBSAN" ] || echo "B2_UBSAN=$B2_UBSAN" >> $GITHUB_ENV [ -z "$B2_FLAGS" ] || echo "B2_FLAGS=$B2_FLAGS" >> $GITHUB_ENV
SELECT category, COUNT(*) AS movie_count FROM movies GROUP BY category;
import React, { useState, useContext } from "react"; import { ListUsersContext } from "../context/ListUsersContext"; import { API } from "../config"; import UserNew from "./UserNew"; const UserNewContainer = () => { const [username, setUsername] = useState(""); const { setGetUsers } = useContext(ListUsersContext); const handleChange = (evt) => { setUsername(evt.target.value); }; const handleSubmit = async (evt) => { try { evt.preventDefault(); let config = { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json", }, body: JSON.stringify({ username: username }), }; await fetch(API, config); setUsername(""); setGetUsers(true); } catch (err) { console.error(err); } }; return ( <UserNew username={username} handleChange={handleChange} handleSubmit={handleSubmit} /> ); }; export default UserNewContainer;
package qwop_ai; import org.apache.commons.lang3.ArrayUtils; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.*; // Learning matrix is expressed as an arraylist of arrays of the form: // { [ distance, ctrl0, ctrl1, ctrl2, ... ctrl9 ] // ... // ... // ... // } // Where the values of the ctrl(n) entries are the "score" of taking that action // at the distance. // For the controls, the index mapping is as follows: // ctrl 0 -> no-op or "" // ctrl 1 -> q // ctrl 2 -> w // ctrl 3 -> o // ctrl 4 -> p // ctrl 5 -> qo // ctrl 6 -> qp // ctrl 7 -> wo // ctrl 8 -> wp // . public class QLearning { private final String[] CONTROLS = {"", "q", "w", "o", "p", "qo", "qp", "wo", "wp"}; private final double LEARNING_RATE = 0.5; private final double DISCOUNT_FACTOR = 0.5; private final double TIME_DEDUCTION = 0.2; private double _score = 0; private HashMap<String, ArrayList<Double>> _matrix; public QLearning(){ _matrix = new HashMap<String, ArrayList<Double>>(); } public String getDecision(double distance){ ArrayList<Double> choices = _matrix.get(String.valueOf(distance)); if (choices == null){ _matrix.put(String.valueOf(distance), newAL()); choices = newAL(); } int max_index = 0; double max = choices.get(0); for (int i=0; i<9; i++){ if(choices.get(i) > max){ max = choices.get(i); max_index = i; } } return CONTROLS[max_index]; } public void recordOutcome(double distance, double outcome, String actionTaken){ List<Double> choices = _matrix.get(String.valueOf(distance)); if (choices == null){ _matrix.put(String.valueOf(distance), newAL()); choices = newAL(); } int actionIndex = ArrayUtils.indexOf(CONTROLS, actionTaken); if(actionIndex <0 || actionIndex >8){ return; } double previousQ = choices.get(actionIndex); System.out.println(qLearningEq(previousQ, outcome)); choices.set(actionIndex, qLearningEq(previousQ, outcome)); } private double qLearningEq(double oldValue, double newValue){ double learned_value = (newValue - oldValue) - TIME_DEDUCTION ; return oldValue + (LEARNING_RATE * learned_value); } private void readMatrixFile(){ //_matrix.clear(); String csvFile = "matrix.txt"; BufferedReader br = null; String line = ""; try { br = new BufferedReader(new FileReader(csvFile)); while ((line = br.readLine()) != null) { String[] values = line.split(","); _matrix.put(values[0], stringArrTodoubleArr(Arrays.copyOfRange(values, 1, 9))); System.out.println(_matrix.toString()); } } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } } private ArrayList<Double> stringArrTodoubleArr(String[] arr){ ArrayList<Double> result = new ArrayList<Double>(); for (int i=0; i<9; i++){ result.add(Double.valueOf(arr[i])); } return result; } private ArrayList<Double> newAL(){ ArrayList<Double> list = new ArrayList<Double>(10); while(list.size() < 10) list.add(0.0); return list; } public void saveMatrixFile(){ TreeSet<String> keys = new TreeSet<String>(); keys.addAll(_matrix.keySet()); for (String key : keys){ System.out.println(key + _matrix.get(key).toString()); } } }
#!/usr/bin/env bash # we need bash 4 for associative arrays if [ "${BASH_VERSION%%[^0-9]*}" -lt "4" ]; then echo "BASH VERSION < 4: ${BASH_VERSION}" >&2 exit 1 fi # associative array for the platforms that will be verified in build_main_platforms() # this will be eval'd in the functions below because arrays can't be exported # Uno is ATmega328, Zero is SAMD21G18, ESP8266, Leonardo is ATmega32u4, M4 is SAMD51, Mega is ATmega2560, ESP32 export MAIN_PLATFORMS='declare -A main_platforms=( [uno]="arduino:avr:uno" [zero]="arduino:samd:arduino_zero_native" [esp8266]="esp8266:esp8266:huzzah:eesz=4M3M,xtal=80" [leonardo]="arduino:avr:leonardo" [m4]="adafruit:samd:adafruit_metro_m4:speed=120" [mega2560]="arduino:avr:mega:cpu=atmega2560" [esp32]="esp32:esp32:featheresp32:FlashFreq=80" )' # associative array for other platforms that can be called explicitly in .travis.yml configs # this will be eval'd in the functions below because arrays can't be exported export AUX_PLATFORMS='declare -A aux_platforms=( [trinket]="adafruit:avr:trinket5" [gemma]="arduino:avr:gemma" )' export CPLAY_PLATFORMS='declare -A cplay_platforms=( [cplayClassic]="arduino:avr:circuitplay32u4cat" [cplayExpress]="arduino:samd:adafruit_circuitplayground_m0" [cplayExpressAda]="adafruit:samd:adafruit_circuitplayground_m0" [cplayBluefruit]="adafruit:nrf52:cplaynrf52840:softdevice=s140v6,debug=l0" )' export SAMD_PLATFORMS='declare -A samd_platforms=( [zero]="arduino:samd:arduino_zero_native", [cplayExpress]="arduino:samd:adafruit_circuitplayground_m0", [m4]="adafruit:samd:adafruit_metro_m4:speed=120" )' export M4_PLATFORMS='declare -A m4_platforms=( [m4]="adafruit:samd:adafruit_metro_m4:speed=120", [trellis_m4]="adafruit:samd:adafruit_trellis_m4:speed=120", [grand_central_m4]="adafruit:samd:adafruit_grand_central_m4:speed=120" )' export ARCADA_PLATFORMS='declare -A arcada_platforms=( [pybadge]="adafruit:samd:adafruit_pybadge_m4:speed=120", [pygamer]="adafruit:samd:adafruit_pygamer_m4:speed=120", [hallowing_m4]="adafruit:samd:adafruit_hallowing_m4:speed=120", [cplayExpressAda]="adafruit:samd:adafruit_circuitplayground_m0" )' export IO_PLATFORMS='declare -A io_platforms=( [zero]="arduino:samd:arduino_zero_native", [m4wifi]="adafruit:samd:adafruit_metro_m4_airliftlite:speed=120", [esp8266]="esp8266:esp8266:huzzah:eesz=4M3M,xtal=80" [esp32]="esp32:esp32:featheresp32:FlashFreq=80" )' export NRF5X_PLATFORMS='declare -A nrf5x_platforms=( [nrf52840]="adafruit:nrf52:feather52840:softdevice=s140v6,debug=l0")' # make display available for arduino CLI /sbin/start-stop-daemon --start --quiet --pidfile /tmp/custom_xvfb_1.pid --make-pidfile --background --exec /usr/bin/Xvfb -- :1 -ac -screen 0 1280x1024x16 sleep 3 export DISPLAY=:1.0 #This condition is to avoid reruning install when build argument is passed if [[ $# -eq 0 ]] ; then # define colors GRAY='\033[1;30m'; RED='\033[0;31m'; LRED='\033[1;31m'; GREEN='\033[0;32m'; LGREEN='\033[1;32m'; ORANGE='\033[0;33m'; YELLOW='\033[1;33m'; BLUE='\033[0;34m'; LBLUE='\033[1;34m'; PURPLE='\033[0;35m'; LPURPLE='\033[1;35m'; CYAN='\033[0;36m'; LCYAN='\033[1;36m'; LGRAY='\033[0;37m'; WHITE='\033[1;37m'; echo -e "\n########################################################################"; echo -e "${YELLOW}INSTALLING ARDUINO IDE" echo "########################################################################"; # if .travis.yml does not set version if [ -z $ARDUINO_IDE_VERSION ]; then export ARDUINO_IDE_VERSION="1.8.11" echo "NOTE: YOUR .TRAVIS.YML DOES NOT SPECIFY ARDUINO IDE VERSION, USING $ARDUINO_IDE_VERSION" fi # if newer version is requested if [ ! -f $HOME/arduino_ide/$ARDUINO_IDE_VERSION ] && [ -f $HOME/arduino_ide/arduino ]; then echo -n "DIFFERENT VERSION OF ARDUINO IDE REQUESTED: " shopt -s extglob cd $HOME/arduino_ide/ rm -rf * if [ $? -ne 0 ]; then echo -e """$RED""\xe2\x9c\x96"; else echo -e """$GREEN""\xe2\x9c\x93"; fi cd $OLDPWD fi # if not already cached, download and install arduino IDE echo -n "ARDUINO IDE STATUS: " if [ ! -f $HOME/arduino_ide/arduino ]; then echo -n "DOWNLOADING: " wget --quiet https://downloads.arduino.cc/arduino-$ARDUINO_IDE_VERSION-linux64.tar.xz if [ $? -ne 0 ]; then echo -e """$RED""\xe2\x9c\x96"; else echo -e """$GREEN""\xe2\x9c\x93"; fi echo -n "UNPACKING ARDUINO IDE: " [ ! -d $HOME/arduino_ide/ ] && mkdir $HOME/arduino_ide tar xf arduino-$ARDUINO_IDE_VERSION-linux64.tar.xz -C $HOME/arduino_ide/ --strip-components=1 if [ $? -ne 0 ]; then echo -e """$RED""\xe2\x9c\x96"; else echo -e """$GREEN""\xe2\x9c\x93"; fi touch $HOME/arduino_ide/$ARDUINO_IDE_VERSION else echo -n "CACHED: " echo -e """$GREEN""\xe2\x9c\x93" fi # define output directory for .hex files export ARDUINO_HEX_DIR=arduino_build_$TRAVIS_BUILD_NUMBER # link test library folder to the arduino libraries folder ln -s $TRAVIS_BUILD_DIR $HOME/arduino_ide/libraries/Adafruit_Test_Library # add the arduino CLI to our PATH export PATH="$HOME/arduino_ide:$PATH" echo -e "\n########################################################################"; echo -e "${YELLOW}INSTALLING DEPENDENCIES" echo "########################################################################"; # install dependancy libraries in library.properties grep "depends=" $HOME/arduino_ide/libraries/Adafruit_Test_Library/library.properties | sed 's/depends=//' | sed -n 1'p' | tr ',' '\n' | while read word; do arduino --install-library "$word"; done # install the zero, esp8266, and adafruit board packages echo -n "ADD PACKAGE INDEX: " DEPENDENCY_OUTPUT=$(arduino --pref "boardsmanager.additional.urls=https://adafruit.github.io/arduino-board-index/package_adafruit_index.json,http://arduino.esp8266.com/stable/package_esp8266com_index.json,https://dl.espressif.com/dl/package_esp32_index.json" --save-prefs 2>&1) if [ $? -ne 0 ]; then echo -e """$RED""\xe2\x9c\x96"; else echo -e """$GREEN""\xe2\x9c\x93"; fi # This is a hack, we have to install by hand so lets delete it echo "Removing ESP32 cache" rm -rf ~/.arduino15/packages/esp32 echo -n "Current packages list:" [ -d ~/.arduino15/packages/ ] && ls ~/.arduino15/packages/ INSTALL_ESP32=$([[ $INSTALL_PLATFORMS == *"esp32"* || -z "$INSTALL_PLATFORMS" ]] && echo 1 || echo 0) INSTALL_ZERO=$([[ $INSTALL_PLATFORMS == *"zero"* || -z "$INSTALL_PLATFORMS" ]] && echo 1 || echo 0) INSTALL_ESP8266=$([[ $INSTALL_PLATFORMS == *"esp8266"* || -z "$INSTALL_PLATFORMS" ]] && echo 1 || echo 0) INSTALL_AVR=$([[ $INSTALL_PLATFORMS == *"avr"* || -z "$INSTALL_PLATFORMS" ]] && echo 1 || echo 0) INSTALL_SAMD=$([[ $INSTALL_PLATFORMS == *"samd"* || -z "$INSTALL_PLATFORMS" ]] && echo 1 || echo 0) INSTALL_NRF52=$([[ $INSTALL_PLATFORMS == *"nrf52"* || -z "$INSTALL_PLATFORMS" ]] && echo 1 || echo 0) if [[ $INSTALL_ESP32 == 1 ]]; then echo -n "ESP32: " DEPENDENCY_OUTPUT=$(arduino --install-boards esp32:esp32 2>&1) if [ $? -ne 0 ]; then echo -e "\xe2\x9c\x96 OR CACHED"; else echo -e """$GREEN""\xe2\x9c\x93"; fi fi if [[ $INSTALL_ZERO == 1 ]]; then echo -n "ZERO: " DEPENDENCY_OUTPUT=$(arduino --install-boards arduino:samd 2>&1) if [ $? -ne 0 ]; then echo -e "\xe2\x9c\x96 OR CACHED"; else echo -e """$GREEN""\xe2\x9c\x93"; fi fi if [[ $INSTALL_ESP8266 == 1 ]]; then echo -n "ESP8266: " DEPENDENCY_OUTPUT=$(arduino --install-boards esp8266:esp8266 2>&1) if [ $? -ne 0 ]; then echo -e "\xe2\x9c\x96 OR CACHED"; else echo -e """$GREEN""\xe2\x9c\x93"; fi fi if [[ $INSTALL_AVR == 1 ]]; then echo -n "ADAFRUIT AVR: " DEPENDENCY_OUTPUT=$(arduino --install-boards adafruit:avr 2>&1) if [ $? -ne 0 ]; then echo -e "\xe2\x9c\x96 OR CACHED"; else echo -e """$GREEN""\xe2\x9c\x93"; fi fi if [[ $INSTALL_SAMD == 1 ]]; then echo -n "ADAFRUIT SAMD: " DEPENDENCY_OUTPUT=$(arduino --install-boards adafruit:samd 2>&1) if [ $? -ne 0 ]; then echo -e "\xe2\x9c\x96 OR CACHED"; else echo -e """$GREEN""\xe2\x9c\x93"; fi fi if [[ $INSTALL_NRF52 == 1 ]]; then echo -n "ADAFRUIT NRF5X: " pip3 install --user setuptools pip3 install --user adafruit-nrfutil pip3 install --user pyserial sudo pip3 install setuptools sudo pip3 install adafruit-nrfutil sudo pip3 install pyserial DEPENDENCY_OUTPUT=$(arduino --install-boards adafruit:nrf52 2>&1) if [ $? -ne 0 ]; then echo -e "\xe2\x9c\x96 OR CACHED"; else echo -e """$GREEN""\xe2\x9c\x93"; fi fi # install random lib so the arduino IDE grabs a new library index # see: https://github.com/arduino/Arduino/issues/3535 echo -n "UPDATE LIBRARY INDEX: " DEPENDENCY_OUTPUT=$(arduino --install-library USBHost > /dev/null 2>&1) if [ $? -ne 0 ]; then echo -e """$RED""\xe2\x9c\x96"; else echo -e """$GREEN""\xe2\x9c\x93"; fi # set the maximal compiler warning level echo -n "SET BUILD PREFERENCES: " DEPENDENCY_OUTPUT=$(arduino --pref "compiler.warning_level=all" --save-prefs 2>&1) if [ $? -ne 0 ]; then echo -e """$RED""\xe2\x9c\x96"; else echo -e """$GREEN""\xe2\x9c\x93"; fi # init the json temp var for the current platform export PLATFORM_JSON="" # init test stats counters export PASS_COUNT=0 export SKIP_COUNT=0 export FAIL_COUNT=0 export PDE_COUNT=0 # close if [[ $# -eq 0 ]] ; then fi # build all of the examples for the passed platform #Sourcing and defining functions function build_platform() { # arrays can't be exported, so we have to eval eval $MAIN_PLATFORMS eval $AUX_PLATFORMS eval $CPLAY_PLATFORMS eval $M4_PLATFORMS eval $ARCADA_PLATFORMS eval $IO_PLATFORMS eval $NRF5X_PLATFORMS # reset platform json var PLATFORM_JSON="" # expects argument 1 to be the platform key local platform_key=$1 # placeholder for platform local platform="" # track the exit code for this platform local exit_code=0 # grab all pde and ino example sketches declare -a examples if [ "$PLATFORM_CHECK_ONLY_ON_FILE" = true ]; then # loop through results and add them to the array examples=($( for f in $(find . -type f -iname '*.ino' -o -iname '*.pde'); do # TODO: distinguish platforms if [ -e "$(dirname $f)/.$platform_key.test" ]; then echo "$f" fi done )) else # loop through results and add them to the array examples=($(find $PWD -name "*.pde" -o -name "*.ino")) fi # get the last example in the array local last="${examples[@]:(-1)}" # grab the platform info from array or bail if invalid if [[ ${main_platforms[$platform_key]} ]]; then platform=${main_platforms[$platform_key]} elif [[ ${aux_platforms[$platform_key]} ]]; then platform=${aux_platforms[$platform_key]} elif [[ ${cplay_platforms[$platform_key]} ]]; then platform=${cplay_platforms[$platform_key]} elif [[ ${m4_platforms[$platform_key]} ]]; then platform=${m4_platforms[$platform_key]} elif [[ ${arcada_platforms[$platform_key]} ]]; then platform=${arcada_platforms[$platform_key]} elif [[ ${io_platforms[$platform_key]} ]]; then platform=${io_platforms[$platform_key]} elif [[ ${nrf5x_platforms[$platform_key]} ]]; then platform=${nrf5x_platforms[$platform_key]} else echo "NON-STANDARD PLATFORM KEY: $platform_key" platform=$platform_key fi echo -e "\n########################################################################"; echo -e -n "${YELLOW}SWITCHING TO ${platform_key}: " # switch to the requested board. # we have to avoid reading the exit code of local: # "when declaring a local variable in a function, the local acts as a command in its own right" local platform_stdout platform_stdout=$(arduino --board $platform --save-prefs 2>&1) # grab the exit status of the arduino board change local platform_switch=$? # notify if the platform switch failed if [ $platform_switch -ne 0 ]; then # heavy X echo -e """$RED""\xe2\x9c\x96" echo -e "arduino --board ${platform} --save-prefs 2>&1" echo $platform_stdout exit_code=1 else # heavy checkmark echo -e """$GREEN""\xe2\x9c\x93" fi echo "########################################################################"; # loop through example sketches for example in "${examples[@]}"; do # store the full path to the example's sketch directory local example_dir=$(dirname $example) # store the filename for the example without the path local example_file=$(basename $example) # is this the last example in the loop local last_example=0 if [ "$last" == "$example" ]; then last_example=1 fi echo -n "$example_file: " # continue to next example if platform switch failed if [ $platform_switch -ne 0 ]; then # heavy X echo -e """$RED""\xe2\x9c\x96" # add json PLATFORM_JSON="${PLATFORM_JSON}$(json_sketch 0 $example_file $last_example)" # increment fails FAIL_COUNT=$((FAIL_COUNT + 1)) # mark fail exit_code=1 continue fi # ignore this example if there is an all platform skip if [[ -f "${example_dir}/.test.skip" ]]; then # right arrow echo -e "\xe2\x9e\x9e" # add json PLATFORM_JSON="${PLATFORM_JSON}$(json_sketch -1 $example_file $last_example)" # increment skips SKIP_COUNT=$((SKIP_COUNT + 1)) continue fi # ignore this example if there is a skip file preset for this specific platform if [[ -f "${example_dir}/.${platform_key}.test.skip" ]]; then # right arrow echo -e "\xe2\x9e\x9e" # add json PLATFORM_JSON="${PLATFORM_JSON}$(json_sketch -1 $example_file $last_example)" # increment skips SKIP_COUNT=$((SKIP_COUNT + 1)) continue fi # make sure that all examples are .ino files if [[ $example =~ \.pde$ ]]; then # heavy X echo -e """$RED""\xe2\x9c\x96" echo -e "-------------------------- DEBUG OUTPUT --------------------------\n" echo "${LRED}PDE EXTENSION. PLEASE UPDATE TO INO" echo -e "\n------------------------------------------------------------------\n" # add json PLATFORM_JSON="${PLATFORM_JSON}$(json_sketch 0 $example_file $last_example)" # increment fails FAIL_COUNT=$((FAIL_COUNT + 1)) # mark as fail exit_code=1 continue fi # get the sketch name so we can place the generated files in the respective folder local sketch_filename_with_ending=$(basename -- "$example") local sketch_filename="${sketch_filename_with_ending%.*}" local build_path=$ARDUINO_HEX_DIR/$platform_key/$sketch_filename # verify the example, and save stdout & stderr to a variable # we have to avoid reading the exit code of local: # "when declaring a local variable in a function, the local acts as a command in its own right" local build_stdout build_stdout=$(arduino --verify --pref build.path=$build_path --preserve-temp-files $example 2>&1) # echo output if the build failed if [ $? -ne 0 ]; then # heavy X echo -e """$RED""\xe2\x9c\x96" echo -e "----------------------------- DEBUG OUTPUT -----------------------------\n" echo "$build_stdout" echo -e "\n------------------------------------------------------------------------\n" # add json PLATFORM_JSON="${PLATFORM_JSON}$(json_sketch 0 $example_file $last_example)" # increment fails FAIL_COUNT=$((FAIL_COUNT + 1)) # mark as fail exit_code=1 else # heavy checkmark echo -e """$GREEN""\xe2\x9c\x93" # add json PLATFORM_JSON="${PLATFORM_JSON}$(json_sketch 1 "$example_file" $last_example)" # increment passes PASS_COUNT=$((PASS_COUNT + 1)) fi done return $exit_code } # build all examples for every platform in $MAIN_PLATFORMS function build_main_platforms() { # arrays can't be exported, so we have to eval eval $MAIN_PLATFORMS # track the build status all platforms local exit_code=0 # var to hold platforms local platforms_json="" # get the last element in the array local last="${main_platforms[@]:(-1)}" # loop through platforms in main platforms assoc array for p_key in "${!main_platforms[@]}"; do # is this the last platform in the loop local last_platform=0 if [ "$last" == "${main_platforms[$p_key]}" ]; then last_platform=1 fi # build all examples for this platform build_platform $p_key # check if build failed if [ $? -ne 0 ]; then platforms_json="${platforms_json}$(json_platform $p_key 0 "$PLATFORM_JSON" $last_platform)" exit_code=1 else platforms_json="${platforms_json}$(json_platform $p_key 1 "$PLATFORM_JSON" $last_platform)" fi done # exit code is opposite of json build status if [ $exit_code -eq 0 ]; then json_main_platforms 1 "$platforms_json" else json_main_platforms 0 "$platforms_json" fi return $exit_code } # build all examples for every platform in $AUX_PLATFORMS function build_aux_platforms() { # arrays can't be exported, so we have to eval eval $AUX_PLATFORMS # track the build status all platforms local exit_code=0 # var to hold platforms local platforms_json="" # get the last element in the array local last="${aux_platforms[@]:(-1)}" # loop through platforms in main platforms assoc array for p_key in "${!aux_platforms[@]}"; do # is this the last platform in the loop local last_platform=0 if [ "$last" == "${aux_platforms[$p_key]}" ]; then last_platform=1 fi # build all examples for this platform build_platform $p_key # check if build failed if [ $? -ne 0 ]; then platforms_json="${platforms_json}$(json_platform $p_key 0 "$PLATFORM_JSON" $last_platform)" exit_code=1 else platforms_json="${platforms_json}$(json_platform $p_key 1 "$PLATFORM_JSON" $last_platform)" fi done # exit code is opposite of json build status if [ $exit_code -eq 0 ]; then json_main_platforms 1 "$platforms_json" else json_main_platforms 0 "$platforms_json" fi return $exit_code } function build_cplay_platforms() { # arrays can't be exported, so we have to eval eval $CPLAY_PLATFORMS # track the build status all platforms local exit_code=0 # var to hold platforms local platforms_json="" # get the last element in the array local last="${cplay_platforms[@]:(-1)}" # loop through platforms in main platforms assoc array for p_key in "${!cplay_platforms[@]}"; do # is this the last platform in the loop local last_platform=0 if [ "$last" == "${cplay_platforms[$p_key]}" ]; then last_platform=1 fi # build all examples for this platform build_platform $p_key # check if build failed if [ $? -ne 0 ]; then platforms_json="${platforms_json}$(json_platform $p_key 0 "$PLATFORM_JSON" $last_platform)" exit_code=1 else platforms_json="${platforms_json}$(json_platform $p_key 1 "$PLATFORM_JSON" $last_platform)" fi done # exit code is opposite of json build status if [ $exit_code -eq 0 ]; then json_main_platforms 1 "$platforms_json" else json_main_platforms 0 "$platforms_json" fi return $exit_code } function build_samd_platforms() { # arrays can't be exported, so we have to eval eval $SAMD_PLATFORMS # track the build status all platforms local exit_code=0 # var to hold platforms local platforms_json="" # get the last element in the array local last="${samd_platforms[@]:(-1)}" # loop through platforms in main platforms assoc array for p_key in "${!samd_platforms[@]}"; do # is this the last platform in the loop local last_platform=0 if [ "$last" == "${samd_platforms[$p_key]}" ]; then last_platform=1 fi # build all examples for this platform build_platform $p_key # check if build failed if [ $? -ne 0 ]; then platforms_json="${platforms_json}$(json_platform $p_key 0 "$PLATFORM_JSON" $last_platform)" exit_code=1 else platforms_json="${platforms_json}$(json_platform $p_key 1 "$PLATFORM_JSON" $last_platform)" fi done # exit code is opposite of json build status if [ $exit_code -eq 0 ]; then json_main_platforms 1 "$platforms_json" else json_main_platforms 0 "$platforms_json" fi return $exit_code } function build_m4_platforms() { # arrays can't be exported, so we have to eval eval $M4_PLATFORMS # track the build status all platforms local exit_code=0 # var to hold platforms local platforms_json="" # get the last element in the array local last="${m4_platforms[@]:(-1)}" # loop through platforms in main platforms assoc array for p_key in "${!m4_platforms[@]}"; do # is this the last platform in the loop local last_platform=0 if [ "$last" == "${m4_platforms[$p_key]}" ]; then last_platform=1 fi # build all examples for this platform build_platform $p_key # check if build failed if [ $? -ne 0 ]; then platforms_json="${platforms_json}$(json_platform $p_key 0 "$PLATFORM_JSON" $last_platform)" exit_code=1 else platforms_json="${platforms_json}$(json_platform $p_key 1 "$PLATFORM_JSON" $last_platform)" fi done # exit code is opposite of json build status if [ $exit_code -eq 0 ]; then json_main_platforms 1 "$platforms_json" else json_main_platforms 0 "$platforms_json" fi return $exit_code } function build_io_platforms() { # arrays can't be exported, so we have to eval eval $IO_PLATFORMS # track the build status all platforms local exit_code=0 # var to hold platforms local platforms_json="" # get the last element in the array local last="${io_platforms[@]:(-1)}" # loop through platforms in main platforms assoc array for p_key in "${!io_platforms[@]}"; do # is this the last platform in the loop local last_platform=0 if [ "$last" == "${io_platforms[$p_key]}" ]; then last_platform=1 fi # build all examples for this platform build_platform $p_key # check if build failed if [ $? -ne 0 ]; then platforms_json="${platforms_json}$(json_platform $p_key 0 "$PLATFORM_JSON" $last_platform)" exit_code=1 else platforms_json="${platforms_json}$(json_platform $p_key 1 "$PLATFORM_JSON" $last_platform)" fi done # exit code is opposite of json build status if [ $exit_code -eq 0 ]; then json_main_platforms 1 "$platforms_json" else json_main_platforms 0 "$platforms_json" fi return $exit_code } function build_arcada_platforms() { # arrays can't be exported, so we have to eval eval $ARCADA_PLATFORMS # track the build status all platforms local exit_code=0 # var to hold platforms local platforms_json="" # get the last element in the array local last="${arcada_platforms[@]:(-1)}" # loop through platforms in main platforms assoc array for p_key in "${!arcada_platforms[@]}"; do # is this the last platform in the loop local last_platform=0 if [ "$last" == "${arcada_platforms[$p_key]}" ]; then last_platform=1 fi # build all examples for this platform build_platform $p_key # check if build failed if [ $? -ne 0 ]; then platforms_json="${platforms_json}$(json_platform $p_key 0 "$PLATFORM_JSON" $last_platform)" exit_code=1 else platforms_json="${platforms_json}$(json_platform $p_key 1 "$PLATFORM_JSON" $last_platform)" fi done # exit code is opposite of json build status if [ $exit_code -eq 0 ]; then json_main_platforms 1 "$platforms_json" else json_main_platforms 0 "$platforms_json" fi return $exit_code } function build_nrf5x_platforms() { # arrays can't be exported, so we have to eval eval $NRF5X_PLATFORMS # track the build status all platforms local exit_code=0 # var to hold platforms local platforms_json="" # get the last element in the array local last="${nrf5x_platforms[@]:(-1)}" # loop through platforms in main platforms assoc array for p_key in "${!nrf5x_platforms[@]}"; do # is this the last platform in the loop local last_platform=0 if [ "$last" == "${nrf5x_platforms[$p_key]}" ]; then last_platform=1 fi # build all examples for this platform build_platform $p_key # check if build failed if [ $? -ne 0 ]; then platforms_json="${platforms_json}$(json_platform $p_key 0 "$PLATFORM_JSON" $last_platform)" exit_code=1 else platforms_json="${platforms_json}$(json_platform $p_key 1 "$PLATFORM_JSON" $last_platform)" fi done # exit code is opposite of json build status if [ $exit_code -eq 0 ]; then json_main_platforms 1 "$platforms_json" else json_main_platforms 0 "$platforms_json" fi return $exit_code } # generate json string for a sketch function json_sketch() { # -1: skipped, 0: failed, 1: passed local status_number=$1 # the filename of the sketch local sketch=$2 # is this the last sketch for this platform? 0: no, 1: yes local last_sketch=$3 # echo out the json echo -n "\"$sketch\": $status_number" # echo a comma unless this is the last sketch for the platform if [ $last_sketch -ne 1 ]; then echo -n ", " fi } # generate json string for a platform function json_platform() { # the platform key from main platforms or aux platforms local platform_key=$1 # 0: failed, 1: passed local status_number=$2 # the json string for the verified sketches local sketch_json=$3 # is this the last platform we are building? 0: no, 1: yes local last_platform=$4 echo -n "\"$platform_key\": { \"status\": $status_number, \"builds\": { $sketch_json } }" # echo a comma unless this is the last sketch for the platform if [ $last_platform -ne 1 ]; then echo -n ", " fi } # generate final json string function json_main_platforms() { # 0: failed, 1: passed local status_number=$1 # the json string for the main platforms local platforms_json=$2 local repo=$(git config --get remote.origin.url) echo -e "\n||||||||||||||||||||||||||||| JSON STATUS ||||||||||||||||||||||||||||||" echo -n "{ \"repo\": \"$repo\", " echo -n "\"status\": $status_number, " echo -n "\"passed\": $PASS_COUNT, " echo -n "\"skipped\": $SKIP_COUNT, " echo -n "\"failed\": $FAIL_COUNT, " echo "\"platforms\": { $platforms_json } }" echo -e "||||||||||||||||||||||||||||| JSON STATUS ||||||||||||||||||||||||||||||\n" } #If there is an argument if [[ ! $# -eq 0 ]] ; then # define output directory for .hex files export ARDUINO_HEX_DIR=arduino_build_$TRAVIS_BUILD_NUMBER # link test library folder to the arduino libraries folder ln -s $TRAVIS_BUILD_DIR $HOME/arduino_ide/libraries/Adafruit_Test_Library # add the arduino CLI to our PATH export PATH="$HOME/arduino_ide:$PATH" "$@" fi
def factorial(n: int) -> int: if n == 0: return 1 else: result = 1 for i in range(1, n + 1): result *= i return result
<filename>src/entity/Role.ts import {Column, Entity, Index, ManyToMany, PrimaryGeneratedColumn} from "typeorm"; import {Length} from "class-validator"; import {User} from "./User"; @Entity() export class Role { @PrimaryGeneratedColumn("uuid") id: string; @Column() @Index({unique: true}) @Length(3, 64) name: string; @ManyToMany(() => User, user => user.roles) users: User[]; }
#!/bin/bash # This is entrypoint for docker image of spree sandbox on docker cloud cd store-frontend && RAILS_ENV=development bundle exec rails s -p 3000 -b '0.0.0.0'
/* * Copyright (C) 2019 by J.J. (<EMAIL>) * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.amolla.service.port; import com.amolla.sdk.ITube; import com.amolla.sdk.Tube; import com.amolla.sdk.ErroNo; import com.amolla.sdk.To; import com.amolla.sdk.set.OtherDevice; import com.amolla.jni.PortUartNative; import com.amolla.service.DynamicReceiver; import com.amolla.service.DynamicController; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.BroadcastReceiver; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; public class UartService extends ITube.Stub { private static final String TAG = UartService.class.getSimpleName(); private static final boolean DEBUG = DynamicController.DEBUG_ALL || false; private static final int MSG_SCREEN_CHANGED = 1000; private static enum PORT_UART { PORT_UART_OPEN, PORT_UART_CLOSE, PORT_UART_SEND_BREAK, PORT_UART_READ, PORT_UART_WRITE } private PortUartNative mUartNative; private DynamicController mControl; public UartService(Context context, String path) { mUartNative = new PortUartNative(path); mControl = new DynamicController(context, TAG); mControl.setHandler(new Handler(mControl.getLooper()) { @Override public synchronized void handleMessage(Message msg) { switch (msg.what) { case MSG_SCREEN_CHANGED: final String action = (String) msg.obj; if (mUartNative != null) mUartNative.sleep(action.equals(Intent.ACTION_SCREEN_OFF)); break; default:break; } } }); mControl.registerReceiver(new DynamicReceiver(this), DynamicReceiver.getFilter(PORT_UART.class)); setRequests(); } private void setRequests() { long reqUartClockEnable = -1; long reqUartClockDisable = -1; try { reqUartClockEnable = Long.parseLong(mControl.getDefinition("REQ_UART_CLOCK_ENABLED")); } catch (Exception e) {}; try { reqUartClockDisable = Long.parseLong(mControl.getDefinition("REQ_UART_CLOCK_DISABLED")); } catch (Exception e) {}; if (mUartNative != null && mUartNative.setRequests(reqUartClockEnable, reqUartClockDisable)) { IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); mControl.registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Message msg = mControl.getHandler().obtainMessage(); msg.what = MSG_SCREEN_CHANGED; msg.obj = intent.getAction(); mControl.getHandler().sendMessage(msg); } }, filter); } } private void setConsoleAsSerial(boolean enable) { if (mUartNative != null && Tube.check("STATIC_SAME_AS_CONSOLE", mUartNative.getPortPath())) { OtherDevice.get().setUsingConsoleAsSerial(enable); } } @Override public int doAction(String key, Bundle val) { int result = ErroNo.FAILURE.code(); if (key == null || key.isEmpty()) { result = ErroNo.ILLEGAL_ARGUMENT.code(); if (DEBUG) Log.e(TAG, ErroNo.toString(result)); return result; } if (mUartNative == null) { result = ErroNo.ILLEGAL_STATE.code(); if (DEBUG) Log.e(TAG, key + " " + ErroNo.toString(result)); return result; } try { if (key.indexOf(PORT_UART.class.getSimpleName()) == 0) { switch (PORT_UART.valueOf(key)) { case PORT_UART_OPEN: if (val == null || val.isEmpty()) { result = ErroNo.ILLEGAL_ARGUMENT.code(); break; } if (mUartNative.isAlreadyOpen()) { result = ErroNo.TOO_BUSY.code(); break; } setConsoleAsSerial(true); result = mUartNative.open(val.getInt(To.P0), val.getInt(To.P1), val.getBoolean(To.P2)); break; case PORT_UART_CLOSE: result = mUartNative.close(val.getInt(To.P0)); setConsoleAsSerial(false); break; case PORT_UART_SEND_BREAK: result = mUartNative.sendBreak(val.getInt(To.P0)); break; case PORT_UART_READ: break; case PORT_UART_WRITE: break; default: throw new IllegalArgumentException(); } } } catch (IllegalArgumentException e) { result = ErroNo.UNSUPPORTED.code(); Log.e(TAG, "Not implemented doAction( " + key + " )"); } if (DEBUG) Log.d(TAG, key + " " + ErroNo.toString(result)); return result; } @Override public int setValue(String key, Bundle val) { int result = ErroNo.FAILURE.code(); if (key == null || key.isEmpty() || val == null || val.isEmpty()) { result = ErroNo.ILLEGAL_ARGUMENT.code(); if (DEBUG) Log.e(TAG, ErroNo.toString(result)); return result; } if (mUartNative == null) { result = ErroNo.ILLEGAL_STATE.code(); if (DEBUG) Log.e(TAG, key + " " + ErroNo.toString(result)); return result; } try { if (key.indexOf(PORT_UART.class.getSimpleName()) == 0) { switch (PORT_UART.valueOf(key)) { case PORT_UART_OPEN: break; case PORT_UART_CLOSE: break; case PORT_UART_SEND_BREAK: break; case PORT_UART_READ: break; case PORT_UART_WRITE: result = mUartNative.write(val.getInt(To.P0), val.getByteArray(To.P1), val.getInt(To.P2), val.getInt(To.P3)); break; default: throw new IllegalArgumentException(); } } } catch (IllegalArgumentException e) { result = ErroNo.UNSUPPORTED.code(); Log.e(TAG, "Not implemented setValue( " + key + " )"); } if (DEBUG) Log.d(TAG, key + " " + ErroNo.toString(result)); return result; } @Override public Bundle getValue(String key, Bundle val) { Bundle result = new Bundle(); if (key == null || key.isEmpty()) { result.putInt(To.R0, ErroNo.ILLEGAL_ARGUMENT.code()); if (DEBUG) Log.e(TAG, ErroNo.toString(result.getInt(To.R0))); return result; } if (mUartNative == null) { result.putInt(To.R0, ErroNo.ILLEGAL_STATE.code()); if (DEBUG) Log.e(TAG, key + " " + ErroNo.toString(result.getInt(To.R0))); return result; } try { if (key.indexOf(PORT_UART.class.getSimpleName()) == 0) { switch (PORT_UART.valueOf(key)) { case PORT_UART_OPEN: break; case PORT_UART_CLOSE: break; case PORT_UART_SEND_BREAK: break; case PORT_UART_READ: if (val == null || val.isEmpty()) { result.putInt(To.R0, ErroNo.ILLEGAL_ARGUMENT.code()); break; } result.putInt(To.R0, mUartNative.read(val.getInt(To.P0), val.getByteArray(To.P1), val.getInt(To.P2))); break; case PORT_UART_WRITE: break; default: throw new IllegalArgumentException(); } } } catch (IllegalArgumentException e) { result.putInt(To.R0, ErroNo.UNSUPPORTED.code()); Log.e(TAG, "Not implemented getValue( " + key + " )"); } if (DEBUG) Log.d(TAG, key + " " + result); return result; } }
#!/bin/bash # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT license. # -------------------------------------------------------------------------------------------- set -euo pipefail # $1 > buildimage-acr.txt # $2 > runtime-images-acr.txt declare imagefilter="oryxdevmcr.azurecr.io/public/oryx" function tagBuildImageForIntegrationTest() { local devbuildImageName="$1" local devbuildImageType="$2" local buildDefName="$BUILD_DEFINITIONNAME" local buildNumber="$RELEASE_TAG_NAME" # Always use specific build number based tag and then use the same tag to create a 'latest' tag and push it if [ -z "$devbuildImageType" ]; then buildImage=$devbuildImageName:$buildDefName.$buildNumber # Trim the build number tag and append the '':latest' to end of it newtag=$devbuildImageName:latest else buildImage=$devbuildImageName:$devbuildImageType-$buildDefName.$buildNumber newtag=$devbuildImageName:$devbuildImageType fi echo "Pulling the build image $buildImage ..." docker pull "$buildImage" | sed 's/^/ /' echo echo "Tagging the source image with tag $newtag ..." docker tag "$buildImage" "$newtag" | sed 's/^/ /' echo echo ------------------------------------------------------------------------------- } echo "Build image filter is set" tagBuildImageForIntegrationTest "$imagefilter/build" "" tagBuildImageForIntegrationTest "$imagefilter/build" "lts-versions" tagBuildImageForIntegrationTest "$imagefilter/build" "azfunc-jamstack" tagBuildImageForIntegrationTest "$imagefilter/build" "github-actions" tagBuildImageForIntegrationTest "$imagefilter/build" "github-actions-buster" tagBuildImageForIntegrationTest "$imagefilter/build" "vso" tagBuildImageForIntegrationTest "$imagefilter/build" "vso-focal" tagBuildImageForIntegrationTest "$imagefilter/cli" "" tagBuildImageForIntegrationTest "$imagefilter/cli-buster" "" tagBuildImageForIntegrationTest "$imagefilter/pack" "" # Extract language string from string (e.g extract 'python' from 'category=python') if [ -n "$TESTINTEGRATIONCASEFILTER" ];then # For DB tests we want all the runtime images to be present at thae agent machine if [[ "$TESTINTEGRATIONCASEFILTER" != *db* ]];then imagefilter=$(echo $TESTINTEGRATIONCASEFILTER | cut -d'=' -f 2) fi fi # Always convert filter for runtime images to lower case echo "Runtime image filter is set for "$imagefilter while read sourceImage; do # Always use specific build number based tag and then use the same tag to create a version tag and push it if [[ "$sourceImage" != *:latest ]]; then if [[ "$sourceImage" == *"$imagefilter"* ]]; then echo "Pulling the runtime image $sourceImage ..." docker pull "$sourceImage" | sed 's/^/ /' # Trim the build number tag and append the version to end of it image="${sourceImage%:*}" echo echo "image $image" tagName="${sourceImage#$image:*}" echo "tagName $tagName" version="${tagName%%-*}" if [[ "$tagName" == *-fpm* ]]; then version="$version"-fpm fi echo "version $version" newtag="$image:$version" echo echo "Tagging the source image with tag $newtag ..." docker tag "$sourceImage" "$newtag" | sed 's/^/ /' echo echo ------------------------------------------------------------------------------- fi fi done <"$2"
# -*- coding: utf-8 -*- import os def getFile(dicPath,fileExten=[]): if not os.path.isdir(dicPath): error = dicPath+'dicPath is not dir' raise IOError(error) return None dirList = [dicPath] fileList = [] for path in dirList: allFile = [path+'/'+thisFile for thisFile in os.listdir(path) if not thisFile.startswith('.')] dirList.extend([thisFile for thisFile in allFile if os.path.isdir(thisFile)]) if len(fileExten) == 0: print(fileExten) fileList.extend(allFile) else: fileList.extend([thisFile for thisFile in allFile if os.path.splitext(thisFile)[1][1:] in fileExten]) print('\n===========================================\n\n') print(fileList) print('\n===========================================\n') return fileList # 根据文件夹查询项目名 def getProjName(dir): for file in os.listdir(dir): if file.endswith('.xcodeproj'): projName = os.path.splitext(file)[0] return projName return '' # 查询项目名和根目录 def projNameAndRootDir(): curPath = os.getcwd() while (getProjName(curPath) == ''): curPath = os.path.dirname(curPath) projName = getProjName(curPath) return (projName, curPath) defaultExcludeSrcDir = ["Pods","Scripts","proto","UnUsedFiles",".gitignore",".git",".DS_Store","ZhuiYin.xcworkspace"] defaultSrcTypes = ['.h', '.m', '.mm'] allSrcFilePaths = [] # 排除掉excludeDir目录名(数组)符合targetTypes(数组)类型的所有文件目录,传空数组则用默认定义 def allSrcFilePath(excludeDir, targetTypes): allSrcFilePaths.clear() rootDir = projNameAndRootDir()[1] recursiveSrcFilePath(rootDir, excludeDir, targetTypes) return allSrcFilePaths def recursiveSrcFilePath(rootPath, excludeDir, targetTypes): isDir = os.path.isdir(rootPath) if isDir: for file in os.listdir(rootPath): exclude = defaultExcludeSrcDir if len(excludeDir) > 0: exclude = excludeDir if file in exclude: continue filePath = os.path.join(rootPath, file) recursiveSrcFilePath(filePath, excludeDir, targetTypes) else: fileType = os.path.splitext(rootPath)[1] srcTypes = defaultSrcTypes if len(targetTypes) > 0: srcTypes = targetTypes if fileType in srcTypes: allSrcFilePaths.append(rootPath) allFilePaths = [] # 工程下所有文件路径,有缓存 def allProjFilePaths(): if len(allFilePaths) > 0 : return allFilePaths rootDir = projNameAndRootDir()[1] recursiveFilePath(rootDir) return allFilePaths def recursiveFilePath(path): isDir = os.path.isdir(path) if isDir: for fileName in os.listdir(path): recursiveFilePath(os.path.join(path, fileName)) else: allFilePaths.append(path) # 工程下所有以<name>结尾的文件路径 def allFilePathsEndwith(name): dir_list = [] if len(name) == 0: return dir_list filePaths = allProjFilePaths() for filePath in filePaths: fileName = os.path.split(filePath)[1] if fileName.endswith(name): dir_list.append(filePath) return dir_list def _recursiveDic(dirPath, file_list, ext_list): for dir in os.listdir(dirPath): file_path = os.path.join(dirPath, dir) if os.path.isdir(file_path): _recursiveDic(file_path, file_list, ext_list) else : fileName, fileExt = os.path.splitext(file_path) if fileExt in ext_list: file_list.append(file_path); def recursiveDir(path, extList): fileList = [] isDir = os.path.isdir(path) if isDir: _recursiveDic(path, fileList, extList) return fileList def walkFilesInPath(rootDir, fileHandler, handlerArgs = (), fileExtList = defaultSrcTypes, excludeDir = defaultExcludeSrcDir): for dir in os.listdir(rootDir): if dir in excludeDir: continue path = os.path.join(rootDir, dir) if os.path.isdir(path): walkFilesInPath(path, fileHandler, handlerArgs, fileExtList, excludeDir) else : fileName, fileExt = os.path.splitext(path) if fileExt in fileExtList: fileHandler(path, handlerArgs)
#!/bin/bash aws cloudformation create-stack \ --stack-name WebForm \ --template-body file://WebForm.yaml \ --capabilities CAPABILITY_NAMED_IAM \ --parameters file://WebForm-parameters.json \ --region us-east-1
<gh_stars>0 #include "Session.h" #include "QtSnmpData.h" #include "RequestValuesJob.h" #include "RequestSubValuesJob.h" #include "SetValueJob.h" #include "defines.h" #include <QDateTime> #include <QHostAddress> #include <math.h> namespace qtsnmpclient { namespace { const int default_response_timeout = 10000; const quint16 SnmpPort = 161; QString errorStatusText( const int val ) { switch( val ) { case 0: return "No errors"; case 1: return "Too big"; case 2: return "No such name"; case 3: return "Bad value"; case 4: return "Read only"; case 5: return "Other errors"; default: Q_ASSERT( false ); break; } return QString( "Unsupported error(%1)" ).arg( val ); } } Session::Session( QObject*const parent ) : QObject( parent ) , m_community( "public" ) , m_socket( new QUdpSocket( this ) ) , m_response_wait_timer( new QTimer( this ) ) { connect( m_socket, SIGNAL(readyRead()), SLOT(onReadyRead()) ); connect( m_response_wait_timer, SIGNAL(timeout()), SLOT(onResponseTimeExpired()) ); m_response_wait_timer->setInterval( default_response_timeout ); } QHostAddress Session::agentAddress() const { return m_agent_address; } void Session::setAgentAddress( const QHostAddress& value ) { bool ok = !value.isNull(); ok = ok && ( QHostAddress( QHostAddress::Any ) != value ); if( ok ) { m_agent_address = value; m_socket->close(); m_socket->bind(); } else { qWarning() << Q_FUNC_INFO << "attempt to set invalid agent address( " << value << ")"; } } QByteArray Session::community() const { return m_community; } void Session::setCommunity( const QByteArray& value ) { m_community = value; } int Session::responseTimeout() const { return m_response_wait_timer->interval(); } void Session::setResponseTimeout( const int value ) { if( value != m_response_wait_timer->interval() ) { m_response_wait_timer->setInterval( value ); } } bool Session::isBusy() const { return !m_current_work.isNull() || !m_work_queue.isEmpty(); } qint32 Session::requestValues( const QStringList& oid_list ) { const qint32 work_id = createWorkId(); addWork( JobPointer( new RequestValuesJob( this, work_id, oid_list) ) ); return work_id; } qint32 Session::requestSubValues( const QString& oid ) { const qint32 work_id = createWorkId(); addWork( JobPointer( new RequestSubValuesJob( this, work_id, oid ) ) ); return work_id; } qint32 Session::setValue( const QByteArray& community, const QString& oid, const int type, const QByteArray& value ) { const qint32 work_id = createWorkId(); addWork( JobPointer( new SetValueJob( this, work_id, community, oid, type, value ) ) ); return work_id; } void Session::addWork( const JobPointer& work ) { IN_QOBJECT_THREAD( work ); const int queue_limit = 10; if( m_work_queue.count() < queue_limit ) { m_work_queue.push_back( work ); startNextWork(); } else { qWarning() << Q_FUNC_INFO << "The snmp request( " << work->description() << ") " << "for the agent (" << m_agent_address.toString() << ") has dropped, " << "because of the queue is full."; } } void Session::startNextWork() { if( m_current_work.isNull() && !m_work_queue.isEmpty() ){ m_current_work = m_work_queue.takeFirst(); m_current_work->start(); } } void Session::completeWork( const QtSnmpDataList& values ) { Q_ASSERT( ! m_current_work.isNull() ); emit responseReceived( m_current_work->id(), values ); m_current_work.clear(); startNextWork(); } void Session::onResponseTimeExpired() { qWarning() << Q_FUNC_INFO << "There is no any snmp response received " << "from the agent( " << m_agent_address.toString() << ") " << " for the request (" << m_request_id << "). " << "The current work: " << m_current_work->description() << " will be canceled."; cancelWork(); } void Session::cancelWork() { if( !m_current_work.isNull() ) { emit requestFailed( m_current_work->id() ); m_current_work.clear(); } m_response_wait_timer->stop(); m_request_id = -1; startNextWork(); } void Session::sendRequestGetValues( const QStringList& names ) { Q_ASSERT( -1 == m_request_id ); if( -1 == m_request_id ) { updateRequestId(); QtSnmpData full_packet = QtSnmpData::sequence(); full_packet.addChild( QtSnmpData::integer( 0 ) ); full_packet.addChild( QtSnmpData::string( m_community ) ); QtSnmpData request( QtSnmpData::GET_REQUEST_TYPE ); request.addChild( QtSnmpData::integer( m_request_id ) ); request.addChild( QtSnmpData::integer( 0 ) ); request.addChild( QtSnmpData::integer( 0 ) ); QtSnmpData seq_all_obj = QtSnmpData::sequence(); for( const auto& oid_key : names ) { QtSnmpData seq_obj_info = QtSnmpData::sequence(); seq_obj_info.addChild( QtSnmpData::oid( oid_key.toLatin1() ) ); seq_obj_info.addChild( QtSnmpData::null() ); seq_all_obj.addChild( seq_obj_info ); } request.addChild( seq_all_obj ); full_packet.addChild( request ); sendDatagram( full_packet.makeSnmpChunk() ); } else { qWarning() << Q_FUNC_INFO << "We are already waiting a response " << "from the agent (" << m_agent_address.toString() << ")"; } } void Session::sendRequestGetNextValue( const QString& name ) { Q_ASSERT( -1 == m_request_id ); if( -1 == m_request_id ) { updateRequestId(); QtSnmpData full_packet = QtSnmpData::sequence(); full_packet.addChild( QtSnmpData::integer( 0 ) ); full_packet.addChild( QtSnmpData::string( m_community ) ); QtSnmpData request( QtSnmpData::GET_NEXT_REQUEST_TYPE ); request.addChild( QtSnmpData::integer( m_request_id ) ); request.addChild( QtSnmpData::integer( 0 ) ); request.addChild( QtSnmpData::integer( 0 ) ); QtSnmpData seq_all_obj = QtSnmpData::sequence(); QtSnmpData seq_obj_info = QtSnmpData::sequence(); seq_obj_info.addChild( QtSnmpData::oid( name.toLatin1() ) ); seq_obj_info.addChild( QtSnmpData::null() ); seq_all_obj.addChild( seq_obj_info ); request.addChild( seq_all_obj ); full_packet.addChild( request ); sendDatagram( full_packet.makeSnmpChunk() ); } else { qWarning() << Q_FUNC_INFO << "We are already waiting a response " << "from the agent (" << m_agent_address.toString() << ")"; } } void Session::sendRequestSetValue( const QByteArray& community, const QString& name, const int type, const QByteArray& value ) { Q_ASSERT( -1 == m_request_id ); if( -1 == m_request_id ) { updateRequestId(); auto pdu_packet = QtSnmpData::sequence(); pdu_packet.addChild( QtSnmpData::integer( 0 ) ); pdu_packet.addChild( QtSnmpData::string( community ) ); auto request_type = QtSnmpData( QtSnmpData::SET_REQUEST_TYPE ); request_type.addChild( QtSnmpData::integer( m_request_id ) ); request_type.addChild( QtSnmpData::integer( 0 ) ); request_type.addChild( QtSnmpData::integer( 0 ) ); auto seq_all_obj = QtSnmpData::sequence(); auto seq_obj_info = QtSnmpData::sequence(); seq_obj_info.addChild( QtSnmpData::oid( name.toLatin1() ) ); seq_obj_info.addChild( QtSnmpData( type, value ) ); seq_all_obj.addChild( seq_obj_info ); request_type.addChild( seq_all_obj ); pdu_packet.addChild( request_type ); sendDatagram( pdu_packet.makeSnmpChunk() ); } else { qWarning() << Q_FUNC_INFO << "We are already waiting a response " << "from the agent (" << m_agent_address.toString() << ")"; } } void Session::onReadyRead() { while( m_socket->hasPendingDatagrams() ) { // NOTE: // The field size sets a theoretical limit of 65,535 bytes // (8 byte header + 65,527 bytes of data) for a UDP datagram. // However the actual limit for the data length, // which is imposed by the underlying IPv4 protocol, // is 65,507 bytes (65,535 − 8 byte UDP header − 20 byte IP header). const int max_datagram_size = 65507; const int size = static_cast< int >( m_socket->pendingDatagramSize() ); bool ok = (size > 0); ok = ok && ( size <= max_datagram_size ); if( ok ) { QByteArray datagram; datagram.resize( size ); const auto read_size = m_socket->readDatagram( datagram.data(), size ); if( size == read_size ) { const auto& list = getResponseData( datagram ); if( !list.isEmpty() ) { Q_ASSERT( !m_current_work.isNull() ); m_current_work->processData( list ); } } else { qWarning() << Q_FUNC_INFO << "Not all bytes have been read (" << read_size << "/" << size << ") " << " from the agent (" << m_agent_address.toString() << ")"; } } else { qWarning() << Q_FUNC_INFO << "There is an invalid size of UDP datagram received:" << size << " " << "from the agent (" << m_agent_address.toString() << "). " << "All data will be read from the socket"; m_socket->readAll(); } } } QtSnmpDataList Session::getResponseData( const QByteArray& datagram ) { QtSnmpDataList result; const auto list = QtSnmpData::parseData( datagram ); for( const auto& packet : list ) { const QtSnmpDataList resp_list = packet.children(); if( 3 == resp_list.count() ) { const auto& resp = resp_list.at( 2 ); if( QtSnmpData::GET_RESPONSE_TYPE != resp.type() ) { qWarning() << Q_FUNC_INFO << "Unexpected response's type " << "(" << resp.type() << " vs " << QtSnmpData::GET_RESPONSE_TYPE << ") " << "in a response of the agent (" << m_agent_address.toString() << "). " << "The datagram will be ignored."; continue; } const auto& children = resp.children(); if( 4 != children.count() ) { qWarning() << Q_FUNC_INFO << "Unexpected child count " << "(" << children.count() << " vs 4) " << "in a response of the agent (" << m_agent_address.toString() << "). " << "The datagram will be ignored."; continue; } const auto& request_id_data = children.at( 0 ); if( QtSnmpData::INTEGER_TYPE != request_id_data.type() ) { qWarning() << Q_FUNC_INFO << "Unexpected request id's type " << "(" << request_id_data.type() << " vs " << QtSnmpData::INTEGER_TYPE << ") " << "in a response of the agent (" << m_agent_address.toString() << "). " << "The datagram will be ignored."; continue; } const int response_req_id = request_id_data.intValue(); if( response_req_id == m_request_id ) { m_response_wait_timer->stop(); m_request_id = -1; } else { QStringList history; for( const auto item : m_request_history_queue ) { history << QString::number( item ); } qWarning() << Q_FUNC_INFO << "Unexpected request id " << "(" << response_req_id << " vs " << m_request_id << ") " << "in a response of the agent (" << m_agent_address.toString() << "). " << "History (request id list): " << history.join( ", " ) << " " << "The datagram will be ignored."; continue; } const auto& error_state_data = children.at( 1 ); if( QtSnmpData::INTEGER_TYPE != error_state_data.type() ) { qWarning() << Q_FUNC_INFO << "Unexpected error state's type " << "(" << error_state_data.type() << " vs " << QtSnmpData::INTEGER_TYPE << ") " << "in a response of the agent (" << m_agent_address.toString() << "). " << "The datagram will be ignored."; continue; } const auto& error_index_data = children.at( 2 ); if( QtSnmpData::INTEGER_TYPE != error_index_data.type() ) { qWarning() << Q_FUNC_INFO << "Unexpected error index's type " << "(" << error_index_data.type() << " vs " << QtSnmpData::INTEGER_TYPE << ") " << "in a response of the agent (" << m_agent_address.toString() << "). " << "The datagram will be ignored."; continue; } const int err_st = error_state_data.intValue(); const int err_in = error_index_data.intValue(); if( err_st || err_in ) { qWarning() << Q_FUNC_INFO << "An error message received " << "( status: " << errorStatusText( err_st ) << "; " << " index: " << err_in << ") " << "from the agent (" << m_agent_address.toString() << ") " << "The last request will be resend with new ID."; writeDatagram( m_last_request_datagram ); continue; } const auto& variable_list_data = children.at( 3 ); Q_ASSERT( QtSnmpData::SEQUENCE_TYPE == variable_list_data.type() ); if( QtSnmpData::SEQUENCE_TYPE != variable_list_data.type() ) { qWarning() << Q_FUNC_INFO << "Unexpected variable list's type " << "(" << variable_list_data.type() << " vs " << QtSnmpData::SEQUENCE_TYPE << ") " << "in a response of the agent (" << m_agent_address.toString() << "). " << "The datagram will be ignored."; continue; } const auto& variable_list = variable_list_data.children(); for( int i = variable_list.count() - 1; i >= 0; --i ) { const auto& variable = variable_list.at( i ); if( QtSnmpData::SEQUENCE_TYPE == variable.type() ) { const QtSnmpDataList& items = variable.children(); if( 2 == items.count() ) { const auto& object = items.at( 0 ); if( QtSnmpData::OBJECT_TYPE == object.type() ) { auto result_item = items.at( 1 ); result_item.setAddress( object.data() ); result << result_item; } else { qWarning() << Q_FUNC_INFO << "Unexpected object's type " << "(" << object.type() << " vs " << QtSnmpData::OBJECT_TYPE << ") " << "in a response of the agent (" << m_agent_address.toString() << "). " << "The datagram will be ignored."; } } else { qWarning() << Q_FUNC_INFO << "Unexpected item count " << "(" << items.count() << " vs 2) " << "in a response of the agent (" << m_agent_address.toString() << "). " << "The datagram will be ignored."; } } else { qWarning() << Q_FUNC_INFO << "Unexpected variable's type " << "(" << variable.type() << " vs " << QtSnmpData::SEQUENCE_TYPE << ") " << "in a response of the agent (" << m_agent_address.toString() << "). " << "The datagram will be ignored."; } } } else { qWarning() << Q_FUNC_INFO << "Unexpected top packet's children count " << "(" << resp_list.count() << " vs 3) " << "in a response of the agent (" << m_agent_address.toString() << "). " << "The datagram will be ignored."; } } return result; } bool Session::writeDatagram( const QByteArray& datagram ) { const auto res = m_socket->writeDatagram( datagram, m_agent_address, SnmpPort ); if( -1 == res ) { qWarning() << Q_FUNC_INFO << "Unable to send a datagram " << "to the agent [" << m_agent_address.toString() << "]"; } else if( res < datagram.size() ) { qWarning() << Q_FUNC_INFO << "Unable to send all bytes of the datagram " "to the agent [" << m_agent_address.toString() << "]"; } else if( res > datagram.size() ) { qWarning() << Q_FUNC_INFO << "There are more bytes (" << res << ") " << "than the datagram contains (" << datagram.size() << ") " << "have been sent to the agent (" << m_agent_address.toString() << ")"; } return res == datagram.size(); } void Session::sendDatagram( const QByteArray& datagram ) { if( writeDatagram( datagram ) ) { m_last_request_datagram = datagram; Q_ASSERT( ! m_response_wait_timer->isActive() ); m_response_wait_timer->start(); } else { // NOTE: If we can't send a datagram at once, // then we wont try to resend it again. // We assume that the network has cirtical problem in that case, // therefore sending the datagram again wont be successed. // So we will cancel the current work. cancelWork(); } } qint32 Session::createWorkId() { ++m_work_id; if( m_work_id < 1 ) { m_work_id = 1; } else if( m_work_id > 0x7FFF ) { m_work_id = 1; } return m_work_id; } void Session::updateRequestId() { m_request_id = 1 + abs( rand() ) % 0x7FFF; m_request_history_queue.enqueue( m_request_id ); while( m_request_history_queue.count() > 10 ) { m_request_history_queue.dequeue(); } } } // namespace qtsnmpclient
#!/bin/bash -e export TIMESTAMP=${TIMESTAMP:-1} function stdout_keepalive() { while true; do # print every 5 minutes, travis stalls after 10. sleep 300 # Print to stdout periodically in order to keep the travis job # from timing out due to inactivity. echo "travis stdout keepalive msg, ignore me." done } stdout_keepalive & # when not on a release do extensive checks if [ -z "$TRAVIS_TAG" ]; then make bazel-build-verify else make fi make build-verify # verify that we set version on the packages built by go(goveralls depends on go-build target) make apidocs make client-python make manifests DOCKER_PREFIX="docker.io/kubevirt" DOCKER_TAG=$TRAVIS_TAG # skip getting old CSVs here (no QUAY_REPOSITORY), verification might fail because of stricter rules over time; falls back to latest if not on a tag make olm-verify if [[ $TRAVIS_CPU_ARCH == "amd64" ]]; then make prom-rules-verify fi
def longest_consecutive_sequence(string): s = string.split() max_length = 0 current_length = 0 for word in s: if word[0] == string[0]: current_length += 1 if current_length > max_length: max_length = current_length else: current_length = 0 return max_length string="The" longest_sequence = longest_consecutive_sequence(string) print("The longest sequence beginning with '%s' is %s words long." % (string, longest_sequence))
package com.cgfy.gateway.filter; import com.cgfy.gateway.bean.SysExceptionLogInfoInsertInputBean; import com.cgfy.gateway.bean.SysUserInfo; import com.cgfy.gateway.config.GatewayIpCheckProperties; //import com.cgfy.gateway.feign.UumsRemoteService; import com.cgfy.gateway.feign.AuthFeignClient; import com.cgfy.gateway.feign.UserFeignClient; import com.cgfy.gateway.util.HttpUtil; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.codehaus.jettison.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.core.Ordered; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DataBufferUtils; import org.springframework.data.redis.core.BoundValueOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.http.server.reactive.ServerHttpResponseDecorator; import org.springframework.stereotype.Component; import org.springframework.util.MultiValueMap; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; @Component @Slf4j public class RequestIpGlobalFilter implements GlobalFilter, Ordered { public static final String GATEWAY_PROXY_CLIENT_IP = "CGFY-GATEWAY-PROXY-CLIENT-IP"; private final static String REQUEST_DATA_MAP_KEY = "RequestIpGlobalFilter.request_data_map_key"; private final static String IP_CHECK_LOG_COUNT_REDIS_NAMESPACE = "RequestIpGlobalFilter.ip_check_log_count:"; private boolean isInit = false; private Map<String, Map<String, Integer>> allowIpMap = null; @Autowired private AuthFeignClient authFeign; @Autowired private UserFeignClient userFeign; @Autowired private GatewayIpCheckProperties gatewayIpCheckProperties; @Autowired private RedisTemplate<String, Object> redisTemplate; /* (non-Javadoc) * @see org.springframework.cloud.gateway.filter.GlobalFilter#filter(org.springframework.web.server.ServerWebExchange, org.springframework.cloud.gateway.filter.GatewayFilterChain) */ @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { ServerHttpRequest request = exchange.getRequest(); String requestURI = request.getURI().getPath(); HttpHeaders headers = request.getHeaders(); String ip = HttpUtil.getIpAddr(request); String clientType=HttpUtil.getClientType(headers); String tokenInfo=HttpUtil.getTokenInfo(headers); log.info("拦截请求URI:"+requestURI+",IP:"+ip+",客户端类型:"+clientType+",token:"+tokenInfo); Map<String, String> headerMap = new HashMap<>(); for(String key : headers.keySet()) { headerMap.put(key, headers.getFirst(key)); } boolean isFilter = gatewayIpCheckProperties.getEnable(); // 判断请求是否需要IP校验 if(isFilter) { if(requestURI.startsWith("/error")) { isFilter = false; }else { List<String> optLogIgnore = gatewayIpCheckProperties.getUrlPrefixIgnore(); if (optLogIgnore != null && !optLogIgnore.isEmpty()) { for (String item : optLogIgnore) { if (requestURI.startsWith(item)) { isFilter = false; break; } } } } } if(isFilter) { boolean isAllowIp = false; if(StringUtils.isEmpty(ip) || "localhost".equalsIgnoreCase(ip)|| "127.0.0.1".equalsIgnoreCase(ip)) { isAllowIp = true; }else { // 获取允许访问的IP信息 Map<String, Map<String, Integer>> ipMap = getAllowIpMap(); String start = ip.substring(0, ip.lastIndexOf(".")); //获取该ip段的起始ip的最后一段 String end = ip.substring(ip.lastIndexOf(".")+1); int lastLeg = 0; try { lastLeg = Integer.parseInt(end); } catch (Exception e) { // TODO: handle exception } Map<String, Integer> map = ipMap.get(start); if(map!=null && !map.isEmpty()) { Integer ipStart = map.get("start"); Integer ipEnd = map.get("end"); if(lastLeg >= ipStart && lastLeg<= ipEnd) { isAllowIp = true; } } } isFilter = !isAllowIp; } if(isFilter) { if(requestURI.startsWith("/oauth/token")) { // 登录IP 校验 return loginFilter(exchange, chain, ip); }else { // 其他 IP 校验 return otherFilter(exchange, chain, ip); } } ServerHttpRequest newRequest = exchange.getRequest().mutate() .header(GATEWAY_PROXY_CLIENT_IP, ip) .build(); return chain.filter(exchange.mutate().request(newRequest).build()); } private Mono<Void> loginFilter(ServerWebExchange exchange, GatewayFilterChain chain, String ip) { ServerHttpRequest request = exchange.getRequest(); String username = ""; String clientId = ""; String grantType = ""; Map<String, String> paramMap = new HashMap<String, String>(); MultiValueMap<String, String> queryParams = request.getQueryParams(); if(queryParams!=null) { username = queryParams.getFirst("username"); clientId = queryParams.getFirst("client_id"); grantType = queryParams.getFirst("grant_type"); paramMap.put("username", username); paramMap.put("clientId", clientId); paramMap.put("grantType", grantType); } // 未从路径上获取到参数时,从requesBody中获取 if(StringUtils.isEmpty(username)) { ServerHttpResponseDecorator response = new ServerHttpResponseDecorator(exchange.getResponse()); ServerWebExchange newEx = exchange.mutate() .request(new RecorderServerHttpRequestDecorator(request)) .response(response) .build(); newEx.getAttributes().put(REQUEST_DATA_MAP_KEY, paramMap); return recorderOriginalRequest(newEx).then(Mono.defer(new Supplier<Mono<Void>>() { @Override public Mono<Void> get() { Map<String, String> paramMap = newEx.getAttribute(REQUEST_DATA_MAP_KEY); String username = paramMap.get("username"); String clientId = paramMap.get("client_id"); String grantType = paramMap.get("grant_type"); String expType = "登录IP异常"; String expMsg = "用户【" + username + "】在客户端【" + clientId + "】 验证类型 【" + grantType + "】" + "登录IP【" + ip + "】未被允许!"; String msg = "{\"error\":\"invalid_ip\",\"error_description\": \"请求失败,您的IP被限制访问!如有需要,请联系管理员。\"}"; String id = UUID.randomUUID().toString().replaceAll("-", ""); SysExceptionLogInfoInsertInputBean input = new SysExceptionLogInfoInsertInputBean(); input.setId(id); input.setExpType(expType); input.setExpMsg(expMsg); input.setExpTime(new Date()); input.setUserLoginName(username); input.setIp(ip); writeLog(input); ServerHttpResponse response = newEx.getResponse(); response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8); response.setStatusCode(HttpStatus.BAD_REQUEST); byte[] bytes = msg.getBytes(StandardCharsets.UTF_8); DataBuffer buffer = response.bufferFactory().wrap(bytes); return response.writeWith(Mono.just(buffer)); } })); }else { String expType = "登录IP异常"; String expMsg = "用户【" + username + "】在客户端【" + clientId + "】 验证类型 【" + grantType + "】" + "登录IP【" + ip + "】未被允许!"; String msg = "{\"error\":\"invalid_ip\",\"error_description\": \"请求失败,您的IP被限制访问!如有需要,请联系管理员。\"}"; String id = UUID.randomUUID().toString().replaceAll("-", ""); SysExceptionLogInfoInsertInputBean input = new SysExceptionLogInfoInsertInputBean(); input.setId(id); input.setExpType(expType); input.setExpMsg(expMsg); input.setExpTime(new Date()); input.setUserLoginName(username); input.setIp(ip); this.writeLog(input); ServerHttpResponse response = exchange.getResponse(); response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8); response.setStatusCode(HttpStatus.BAD_REQUEST); byte[] bytes = msg.getBytes(StandardCharsets.UTF_8); DataBuffer buffer = response.bufferFactory().wrap(bytes); return response.writeWith(Mono.just(buffer)).then(chain.filter(exchange)); } } private Mono<Void> recorderOriginalRequest(ServerWebExchange exchange) { ServerHttpRequest newRequest = exchange.getRequest(); HttpHeaders headers = newRequest.getHeaders(); MediaType contentType = headers.getContentType(); Map<String, String> paramMap = exchange.getAttribute(REQUEST_DATA_MAP_KEY); Charset charset = null; if (MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(contentType)) { long length = headers.getContentLength(); if(length>0) { charset = getMediaTypeCharset(contentType); } } if(charset!=null) { Flux<DataBuffer> body = newRequest.getBody(); return doRecordBody(paramMap, body, charset); }else { return Mono.empty(); } } private Mono<Void> doRecordBody(Map<String, String> paramMap, Flux<DataBuffer> body, Charset charset) { return DataBufferUtils.join(body).doOnNext(buffer -> { CharBuffer charBuffer = charset.decode(buffer.asByteBuffer()); if(charBuffer!=null) { Map<String, String> bodyMap = null; try { bodyMap = HttpUtil.parseParamString(charBuffer.toString()); } catch (Exception e) { // TODO: handle exception } if(bodyMap!=null && !bodyMap.isEmpty()) { for(String key : bodyMap.keySet()) { paramMap.put(key, bodyMap.get(key)); } } } DataBufferUtils.release(buffer); }).then(); } private Mono<Void> otherFilter(ServerWebExchange exchange, GatewayFilterChain chain, String ip) { ServerHttpRequest request = exchange.getRequest(); String requestURI = request.getURI().getPath(); HttpHeaders headers = request.getHeaders(); Map<String, String> headerMap = new HashMap<>(); for(String key : headers.keySet()) { headerMap.put(key, headers.getFirst(key)); } String userId = ""; String userName = ""; SysUserInfo user = this.getCurrentUser(headerMap); if(user!=null) { userId = user.getId(); userName = user.getLoginName(); // userLoginName = user.getLoginName(); } String expType = "请求IP异常"; String expMsg = "请求【" + requestURI + "】中的IP【" + ip + "】未被允许!"; String msg = "{\"error\":\"invalid_ip\",\"error_description\": \"请求失败,您的IP被限制访问!如有需要,请联系管理员。\"}"; String id = UUID.randomUUID().toString().replaceAll("-", ""); SysExceptionLogInfoInsertInputBean input = new SysExceptionLogInfoInsertInputBean(); input.setId(id); input.setExpType(expType); input.setExpMsg(expMsg); input.setExpTime(new Date()); input.setUserId(userId); input.setUserLoginName(userName); input.setIp(ip); this.writeLog(input); ServerHttpResponse response = exchange.getResponse(); response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8); response.setStatusCode(HttpStatus.BAD_REQUEST); byte[] bytes = msg.getBytes(StandardCharsets.UTF_8); DataBuffer buffer = response.bufferFactory().wrap(bytes); return response.writeWith(Mono.just(buffer)); } private Charset getMediaTypeCharset(MediaType mediaType) { if (mediaType != null && mediaType.getCharset() != null) { return mediaType.getCharset(); } else { return StandardCharsets.UTF_8; } } private void writeLog(SysExceptionLogInfoInsertInputBean input) { if(input!=null) { long checkLogCount = -1; String ip = input.getIp(); String redisKey = IP_CHECK_LOG_COUNT_REDIS_NAMESPACE + ip; boolean isHasKey = redisTemplate.hasKey(redisKey); if(isHasKey) { String loginCountStr = Objects.toString(redisTemplate.opsForValue().get(redisKey)); try { checkLogCount = Long.parseLong(loginCountStr); } catch (Exception e) { // TODO: handle exception } } /** 24小时内,只记录10次日志 **/ if(checkLogCount<10) { try { //userFeign.saveExceptionLog(input); if(isHasKey) { BoundValueOperations<String, Object> boundValueOps = redisTemplate.boundValueOps(redisKey); boundValueOps.increment(1l); }else { BoundValueOperations<String, Object> boundValueOps = redisTemplate.boundValueOps(redisKey); boundValueOps.increment(1l); boundValueOps.expire(1, TimeUnit.DAYS); } } catch (Exception e) { e.printStackTrace(); } } } } /** * 返回登录用户信息 * * @param headerMap * @return */ private SysUserInfo getCurrentUser(Map<String, String> headerMap) { SysUserInfo user = null; try { //String rvStr = authFeign.getCurrentUser(headerMap); String rvStr = "cgfy"; log.debug("principal info:\t" + rvStr); if (rvStr != null && rvStr.length() > 0) { JSONObject rvObj = new JSONObject(rvStr); if (rvStr != null) { JSONObject principalObj = rvObj.getJSONObject("principal"); if (principalObj != null) { JSONObject infoObj = principalObj.getJSONObject("info"); if (infoObj != null) { user = new SysUserInfo(); user.setId(Objects.toString(infoObj.get("id"), "")); user.setLoginName(Objects.toString(infoObj.get("loginName"), "")); user.setName(Objects.toString(infoObj.get("name"), "")); } } } } } catch (Exception e) { e.printStackTrace(); } return user; } private Map<String, Map<String, Integer>> getAllowIpMap(){ if(!isInit) { List<String> allowIPRange = gatewayIpCheckProperties.getAllowIPRange(); if(allowIPRange!=null && !allowIPRange.isEmpty()) { allowIpMap = new HashMap<String, Map<String, Integer>>(); for(String ipRange : allowIPRange) { if(ipRange != null && !"".equals(ipRange.trim())) { //对该段的ip进行解析 String[] ips = ipRange.split("-"); if(ips.length > 0 && ips.length < 3) { String from = ips[0];//得到该段的起始ip String to = ips[1]; //得到该段的结束ip //获取该ip段地址的前三段,因为起始和结束的ip的前三段一样 String share = from.substring(0, from.lastIndexOf(".")); //获取该ip段的起始ip的最后一段 int start = Integer.parseInt(from.substring(from.lastIndexOf(".")+1)); //获取该ip段的结束ip的最后一段 int end = Integer.parseInt(to.substring(to.lastIndexOf(".")+1)); Map<String, Integer> lastLegMap = new HashMap<String, Integer>(); lastLegMap.put("start", start); lastLegMap.put("end", end); allowIpMap.put(share, lastLegMap); } else { throw new RuntimeException("配置文件有错,请检查!"); } } } } isInit = true; } return allowIpMap; } @Override public int getOrder() { return -201; } }
package de.rieckpil.blog; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class JUnit5Test { @Test public void testMe() { var sum = 2 + 2; assertEquals(4, sum); } }