text
stringlengths
1
1.05M
<reponame>cleanlyer/cleanly<filename>src/actions/types.js export const UPDATE_USER_LOCATION = 'UPDATE_USER_LOCATION' export const SEND_REPORT = 'SEND_REPORT' export const SEND_CLEAN = 'SEND_CLEAN' export const UPDATE_SCORE = 'UPDATE_SCORE' export const GET_GARBAGE = 'GET_GARBAGE' export const GET_GARBAGE_OFFLINE = 'GET_GARBAGE_OFFLINE' export const SEND_REPORT_OFFLINE = 'SEND_REPORT_OFFLINE' export const SEND_CLEAN_OFFLINE = 'SEND_CLEAN_OFFLINE' export const LOGIN = 'LOGIN'
class ParsingError(Exception): pass class FileError(Exception): pass def parseFile(file_path): try: with open(file_path, 'r') as file: line_number = 0 for line in file: line_number += 1 if ':' not in line: raise ParsingError(f"Invalid format in line: {line_number}") key, value = line.strip().split(':') print(f"Parsed key: {key}, value: {value}") except FileNotFoundError: raise FileError(f"Error reading file: {file_path}")
<filename>webapp/src/app/shared/phaser/entities/selection-box.ts import {Point} from '../../interfaces/cross-code-map'; import {Helper} from '../helper'; import {SortableGroup} from '../../interfaces/sortable'; import {CCEntity} from './cc-entity'; export class SelectionBox { private active = false; private start: Point; private game: Phaser.Game; private graphics: Phaser.Graphics; private selectedEntities: Set<CCEntity>; constructor(game: Phaser.Game) { this.game = game; this.selectedEntities = new Set<CCEntity>(); const group: SortableGroup = game.add.group(); group.zIndex = 10000; this.graphics = game.add.graphics(0, 0, group); } public onInputDown(pos: Point) { this.active = true; this.start = pos; this.selectedEntities.clear(); } public update(entities: CCEntity[]) { if (!this.active) { return; } const pos = Helper.screenToWorld(this.game.input.mousePointer); const start = this.start; let x1 = start.x; let y1 = start.y; let x2 = pos.x; let y2 = pos.y; if (x2 < x1) { const tmp = x1; x1 = x2; x2 = tmp; } if (y2 < y1) { const tmp = y1; y1 = y2; y2 = tmp; } const rect = new Phaser.Rectangle(x1, y1, x2 - x1, y2 - y1); this.graphics.clear(); this.graphics.beginFill(0x3335ed, 0.3); this.graphics.lineStyle(1, 0x3335ed, 0.8); this.graphics.drawRect(rect.x, rect.y, rect.width, rect.height); this.graphics.endFill(); entities.forEach(e => { const events = e.collisionImage.events; if (rect.intersects(e.getBoundingBox(), 0)) { events.onInputOver.dispatch(); this.selectedEntities.add(e); } else { events.onInputOut.dispatch(); this.selectedEntities.delete(e); } }); } public onInputUp(): Set<CCEntity> { if (!this.active) { return; } this.graphics.clear(); this.active = false; this.selectedEntities.forEach(e => { e.collisionImage.events.onInputOut.dispatch(); }); return this.selectedEntities; } }
package week1.controller; import org.junit.After; import org.junit.Before; import org.junit.Test; import week1.model.IncomeExpenses; import week1.model.Seller; import week1.utils.InitUtils; import static org.junit.Assert.*; public class ISellerControllerImplTest { private Seller mainSeller; private ISellerControllerImpl ISellerControllerImpl; @Before public void setUp() throws Exception { mainSeller = InitUtils.createDepartment(); ISellerControllerImpl = new ISellerControllerImpl(); } @After public void tearDown() throws Exception { mainSeller = null; ISellerControllerImpl = null; } @Test public void calculateAllSellerSalary() throws Exception { assertEquals(27.65, ISellerControllerImpl.calculateAllSellerSalary(mainSeller),0.01); } @Test public void calculateDepartmentCosts() throws Exception { assertEquals(123, ISellerControllerImpl.calculateDepartamentCosts(mainSeller),0.001); } @Test public void calculateIncomeAndExpenses() throws Exception { IncomeExpenses incomeExpenses = new IncomeExpenses(); incomeExpenses.setIncome(615.00); incomeExpenses.setExpenses(123.00); assertEquals(incomeExpenses, ISellerControllerImpl.calculateIncomeAndExpenses(mainSeller)); } }
<reponame>kostovmichael/react-examples import React, {Component} from 'react'; class HorizontalScroll extends Component { componentDidMount() { const scope = this; this._container.addEventListener('scroll', (e) => { console.log('xscroll'); window.clearTimeout(scope.scrollTimer); //滚动结束触发 scope.scrollTimer = window.setTimeout(scope.scrollEndCallback, 250, e); }); } scrollEndCallback(e) { console.log('scroll end', e); } render() { //Warning: Unsupported style property overflow-x. Did you mean overflowX? Check the render method of `xScroll`. const styles = { container: { border: '1px solid #ddd', overflowX: 'auto', overflowY: 'hidden' }, list: { width: '2000px' }, item: { float: 'left', width: '150px', height: '100px', marginLeft: '10px', border: '1px solid #ddd' } }; const items = [1, 2, 3, 4, 5].map((el, index) => { return ( <li style={styles.item} key={index}>{el}</li> ); }); return ( <div ref={(ref) => this._container = ref} style={styles.container}> <ul style={styles.list}> {items} </ul> </div> ); } }; export default HorizontalScroll;
package com.wyp.materialqqlite.ui; import java.io.File; import com.wyp.materialqqlite.ImageCache; import com.wyp.materialqqlite.R; import com.wyp.materialqqlite.AppData; import com.wyp.materialqqlite.Utils; import com.wyp.materialqqlite.qqclient.QQClient; import com.wyp.materialqqlite.qqclient.protocol.protocoldata.GroupInfo; import com.wyp.materialqqlite.qqclient.protocol.protocoldata.GroupList; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class GroupListAdapter extends BaseAdapter { private Context m_Context; private GroupList m_groupList; private ImageCache m_imgCache; private QQClient m_QQClient; private int m_cxAvatar, m_cyAvatar; private int m_pxAvatarRound; public GroupListAdapter(Context context, GroupList groupList) { m_Context = context; m_groupList = groupList; m_imgCache = new ImageCache(); m_QQClient = AppData.getAppData().getQQClient(); m_cxAvatar = (int)context.getResources().getDimension(R.dimen.GList_cxAvatar); m_cyAvatar = (int)context.getResources().getDimension(R.dimen.GList_cyAvatar); m_pxAvatarRound = (int)context.getResources().getDimension(R.dimen.pxAvatarRound); } @Override public int getCount() { if (m_groupList != null) return m_groupList.getGroupCount(); else return 0; } @Override public Object getItem(int position) { if (m_groupList != null) return m_groupList.getGroup(position); else return 0; } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = LayoutInflater.from(m_Context).inflate(R.layout.group_list_item, parent, false); holder = new ViewHolder(); holder.m_imgAvatar = (ImageView)convertView.findViewById(R.id.glistitem_imgAvatar); holder.m_txtName = (TextView)convertView.findViewById(R.id.glistitem_txtName); convertView.setTag(holder); } else { holder = (ViewHolder)convertView.getTag(); } if (null == holder || null == m_groupList) return convertView; GroupInfo groupInfo = m_groupList.getGroup(position); if (groupInfo != null) { Bitmap bmp = getGroupHeadPic(groupInfo.m_nGroupCode); if (bmp != null) holder.m_imgAvatar.setImageBitmap(bmp); else holder.m_imgAvatar.setImageResource(R.drawable.list_grouphead_normal); holder.m_txtName.setText(groupInfo.m_strName); } return convertView; } private Bitmap getGroupHeadPic(int nGroupCode) { GroupList groupList = m_QQClient.getGroupList(); GroupInfo groupInfo = groupList.getGroupByCode(nGroupCode); if (null == groupInfo) { return null; } if (0 == groupInfo.m_nGroupNumber) { m_QQClient.updateGroupNum(groupInfo.m_nGroupCode); return null; } Bitmap bmp = m_imgCache.get(groupInfo.m_nGroupNumber); if (bmp != null) { return bmp; } String strFileName = m_QQClient.getGroupHeadPicFullName(groupInfo.m_nGroupNumber); File file = new File(strFileName); if (!file.exists()) { m_QQClient.updateGroupHeadPic(groupInfo.m_nGroupCode, groupInfo.m_nGroupNumber); return null; } LoadImageTask task = new LoadImageTask(); task.m_strKey = String.valueOf(groupInfo.m_nGroupNumber); task.m_strFileName = strFileName; task.execute(""); return null; } static class ViewHolder { ImageView m_imgAvatar; TextView m_txtName; } class LoadImageTask extends AsyncTask<String, Integer, Boolean> { public String m_strKey = ""; public String m_strFileName = ""; public Bitmap m_Bitmap = null; @Override protected Boolean doInBackground(String... params) { File file = new File(m_strFileName); int nTime = (int)(file.lastModified() / 1000); if (!Utils.isToday(nTime)) { file.delete(); return true; } m_Bitmap = BitmapFactory.decodeFile(m_strFileName); if (m_Bitmap != null) { m_Bitmap = Utils.zoomImg(m_Bitmap, m_cxAvatar, m_cyAvatar); m_Bitmap = Utils.getRoundedCornerBitmap(m_Bitmap, m_pxAvatarRound); } return m_Bitmap != null; } @Override protected void onPostExecute(Boolean result) { if (result) { m_imgCache.put(m_strKey, m_Bitmap); GroupListAdapter.this.notifyDataSetChanged(); } } } }
<filename>examples/led.py #!/usr/bin/env python # -*- coding: utf-8 -*- """ :mod:`led` ================== Created by hbldh <<EMAIL>> Created on 2016-04-02 """ from __future__ import division from __future__ import print_function from __future__ import absolute_import import time from pymetawear.discover import select_device from pymetawear.client import MetaWearClient address = select_device() c = MetaWearClient(str(address), debug=True) print("New client created: {0}".format(c)) print("Blinking 10 times with green LED...") pattern = c.led.load_preset_pattern('blink', repeat_count=10) c.led.write_pattern(pattern, 'g') c.led.play() time.sleep(5.0) c.disconnect()
<gh_stars>0 package software.amazon.jsii.tests.calculator; /** * The negation operation ("-value") */ @software.amazon.jsii.Jsii(module = software.amazon.jsii.tests.calculator.$Module.class, fqn = "jsii-calc.Negate") public class Negate extends software.amazon.jsii.tests.calculator.UnaryOperation implements software.amazon.jsii.tests.calculator.IFriendlier { protected Negate(final software.amazon.jsii.JsiiObject.InitializationMode mode) { super(mode); } public Negate(final software.amazon.jsii.tests.calculator.lib.Value operand) { super(software.amazon.jsii.JsiiObject.InitializationMode.Jsii); software.amazon.jsii.JsiiEngine.getInstance().createNewObject(this, java.util.stream.Stream.of(java.util.Objects.requireNonNull(operand, "operand is required")).toArray()); } /** * String representation of the value. */ public java.lang.String toString() { return this.jsiiCall("toString", java.lang.String.class); } /** * Say hello! */ public java.lang.String hello() { return this.jsiiCall("hello", java.lang.String.class); } /** * Say goodbye. */ public java.lang.String goodbye() { return this.jsiiCall("goodbye", java.lang.String.class); } /** * Say farewell. */ public java.lang.String farewell() { return this.jsiiCall("farewell", java.lang.String.class); } /** * The value. */ public java.lang.Number getValue() { return this.jsiiGet("value", java.lang.Number.class); } }
<gh_stars>1-10 package jadx.core.dex.attributes.nodes; import jadx.core.dex.attributes.*; public class LoopLabelAttr implements IAttribute { private final LoopInfo loop; public LoopLabelAttr(LoopInfo loop) { this.loop = loop; } public LoopInfo getLoop() { return loop; } @Override public AType<LoopLabelAttr> getType() { return AType.LOOP_LABEL; } @Override public String toString() { return "LOOP_LABEL: " + loop; } }
package com.basics.exercises; public class ComputePI { public static void main(String[] args) { calculatePi(); } private static void calculatePi() { } }
import NewPostForm from './NewPostForm' import PostList from './PostList' export { NewPostForm, PostList }
#!/bin/ksh # *****************************COPYRIGHT**************************** # (c) British Crown Copyright 2009, the Met Office. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the # following conditions are met: # # * Redistributions of source code must retain the above # copyright notice, this list of conditions and the following # disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials # provided with the distribution. # * Neither the name of the Met Office nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # *****************************COPYRIGHT******************************* # *****************************COPYRIGHT******************************* clear make test_isccp_cloud_types || exit 1 # Test RNG gives correct results ./test_congvec.ksh || exit 1 echo Running ISCCP simulator tests - may take a few minutes.... rm -f stdout ./rcsid isccp_cloud_types.f77 > stdout for top_height_direction in 1 2 do for top in 1 2 3 do for overlap in 1 2 3 do echo $top > stdin echo $overlap >> stdin echo $top_height_direction >> stdin ( echo top=$top echo overlap=$overlap echo top_height_direction=$top_height_direction rm -f ftn09.* if [ $(hostname) = "tx01" ] then dir=$(pwd) rsh sx601 "cd $dir ; ./test_isccp_cloud_types < stdin" else ./test_isccp_cloud_types < stdin fi ) | sed 's/ \./ 0./g;s/ *$//' >> stdout for file in ftn09.* do export LC_ALL=C #sort < $file | uniq -c >> stdout sort < $file |sort >> stdout done done done done if diff stdout stdout.expected > stdout.diff then echo tests passed ok. exit 0 else echo there may be a problem with the test - files stdout and stdout.expected do not match. echo tkdiff stdout stdout.expected less stdout.diff exit 1 fi
adb shell rm /storage/sdcard1/scd.db adb shell "su -c 'cp /data/data/com.theah64.soundclouddownloader/databases/scd.db /storage/sdcard1/scd.db'" adb pull /storage/sdcard1/scd.db
module Travis module Api module V0 module Event class Job include Formats attr_reader :job def initialize(job, options = {}) @job = job # @options = options end def data(extra = {}) { 'job' => job_data, } end private def job_data { 'queue' => job.queue, 'created_at' => job.created_at, 'started_at' => job.started_at, 'finished_at' => job.finished_at, } end end end end end end
#!/bin/bash # # Sample REST API to de-identify a FHIR JSON. The API takes a configuration file and a FHIR JSON as input and # returns de-identified data. # # The expected response: # { # "data": [ # { # "resourceType": "Patient", # "id": "example", # "name": [ # { # "use": "official", # "family": "NATHO", # "given": [ # "EA72C79594296E45B8C2A296644D988581F58CFAC6601D122ED0A8BD7C02E8BF", # "9345A35A6FDF174DFF7219282A3AE4879790DBB785C70F6FFF91E32FAFD66EAB" # ] # }, # { # "use": "usual", # "given": [ # "96BD923157C731249A40C36426FC326062AD3B2904ED6792B3F404F223D35651" # ] # } # ], # "telecom": [ # { # "system": "phone", # "value": "+1-3478057810", # "use": "work", # "rank": 1 # } # ], # "birthDate": "1974" # } # ] # } # curl -k -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{ "config":"{\"rules\":[{\"name\":\"HASH\",\"maskingProviders\":[{\"type\":\"HASH\"}]},{\"name\":\"PHONE\",\"maskingProviders\":[{\"type\":\"PHONE\"}]},{\"name\":\"NAME\",\"maskingProviders\":[{\"type\":\"NAME\"}]},{\"name\":\"MaskBirthDay\",\"maskingProviders\":[{\"type\":\"DATETIME\",\"generalizeYear\":true}]}],\"json\":{\"schemaType\":\"FHIR\",\"messageTypeKey\":\"resourceType\",\"messageTypes\":[\"Patient\"],\"maskingRules\":[{\"jsonPath\":\"/fhir/Patient/name/given\",\"rule\":\"HASH:null\"},{\"jsonPath\":\"/fhir/Patient/name/family\",\"rule\":\"NAME:null\"},{\"jsonPath\":\"/fhir/Patient/telecom/value\",\"rule\":\"PHONE:null\"},{\"jsonPath\":\"/fhir/Patient/birthDate\",\"rule\":\"MaskBirthDay:null\"}]}}" , "data": [ "{\"resourceType\":\"Patient\",\"id\":\"example\",\"name\":[{\"use\":\"official\",\"family\":\"Chalmers\",\"given\":[\"Peter\",\"James\"]},{\"use\":\"usual\",\"given\":[\"Jim\"]}],\"telecom\":[{\"system\":\"phone\",\"value\":\"+1-3471234567\",\"use\":\"work\",\"rank\":1}],\"birthDate\":\"1974-12-25\"}" ], "schemaType": "FHIR" }' 'https://localhost:8443/api/v1/deidentification'
<filename>statroid/src/main/java/subbiah/veera/statroid/data/DBHelper.java package subbiah.veera.statroid.data; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import static subbiah.veera.statroid.data.Constants.DBConstants.DATABASE_NAME; import static subbiah.veera.statroid.data.Constants.DBConstants.DATABASE_VERSION; import static subbiah.veera.statroid.data.Constants.DBConstants.READ; import static subbiah.veera.statroid.data.Constants.DBConstants.SQL_CREATE_ENTRIES; import static subbiah.veera.statroid.data.Constants.DBConstants.TABLE_NAME; import static subbiah.veera.statroid.data.Constants.DBConstants.WRITE; import static subbiah.veera.statroid.data.Constants.DOWNLOAD_NET; import static subbiah.veera.statroid.data.Constants.UPLOAD_NET; /** * Created by Veera.Subbiah on 17/09/17. */ @SuppressWarnings("unused") public class DBHelper extends SQLiteOpenHelper { private static final String TAG = "DBHelper"; private final SQLiteDatabase db; private static DBHelper writeInstance; private static DBHelper readInstance; public static synchronized DBHelper init(Context context, int MODE) { if(MODE == READ && readInstance != null) return readInstance; else if(MODE == WRITE && writeInstance != null) return writeInstance; return new DBHelper(context, MODE); } private DBHelper(Context context, int MODE) { super(context, DATABASE_NAME, null, DATABASE_VERSION); if (MODE == READ) { db = getReadableDatabase(); readInstance = this; } else { db = getWritableDatabase(); writeInstance = this; } } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(SQL_CREATE_ENTRIES); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Logger.d(TAG, "onUpgrade: 2:52 PM " + oldVersion + " to " + newVersion); db.execSQL("ALTER TABLE " + TABLE_NAME + " ADD " + UPLOAD_NET + " NUMERIC DEFAULT 0;"); db.execSQL("ALTER TABLE " + TABLE_NAME + " ADD " + DOWNLOAD_NET + " NUMERIC DEFAULT 0;"); } public Cursor read(String[] projection, String selection, String[] selectionArgs, String sortOrder) { if(db.isOpen()) return db.query(TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder); else return null; } public void write(String[] projection, double[] values) { if(projection.length != values.length) return; ContentValues record = new ContentValues(); for (int i = 0; i < projection.length; i++) { record.put(projection[i], values[i]); } db.insert(TABLE_NAME, null, record); } public int remove(String selection, String[] selectionArgs) { return db.delete(TABLE_NAME, selection, selectionArgs); } public int update(String[] projection, String[] values, String selection, String[] selectionArgs) { if(projection.length != values.length) return -1; ContentValues record = new ContentValues(); for (int i = 0; i < projection.length; i++) { record.put(projection[i], values[i]); } return db.update(TABLE_NAME, record, selection, selectionArgs); } public void reset(int MODE) { Logger.d(TAG, "reset: closing db"); if(MODE == READ) { readInstance = null; } else { writeInstance = null; } db.close(); } public static boolean isClosed(int MODE) { if(MODE == READ) { return readInstance == null || readInstance.db == null || !readInstance.db.isOpen(); } else { return writeInstance == null || writeInstance.db == null || !writeInstance.db.isOpen(); } } }
<filename>Template/FlightSearchResultsCell.h // // FlightSearchResultsCell.h // Template // // Created by Stadelman, Stan on 9/19/14. // Copyright (c) 2014 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @interface FlightSearchResultsCell : UITableViewCell @property (strong, nonatomic) IBOutlet UILabel *departureTimeLabel; @property (strong, nonatomic) IBOutlet UILabel *arrivalTimeLabel; @property (strong, nonatomic) IBOutlet UILabel *descriptionLabel; @property (weak, nonatomic) IBOutlet UILabel *priceLabel; @end
<filename>intro/part07-07_dice_roller/test/test_dice_roller.py<gh_stars>0 import unittest from unittest.mock import patch from tmc import points from tmc.utils import load, load_module, reload_module, get_stdout, check_source from functools import reduce import os import textwrap from random import randint exercise = 'src.dice_roller' @points('7.dice_roller') class DiceRollerTest(unittest.TestCase): @classmethod def setUpClass(cls): with patch('builtins.input', side_effect=[AssertionError("Asking input from the user was not expected")]): cls.module = load_module(exercise, 'en') def test_0a_main_program_ok(self): ok, line = check_source(self.module) message = """The code for testing the functions should be placed inside if __name__ == "__main__": block. The following row should be moved: """ self.assertTrue(ok, message+line) def test1_function_roll_exists_and_return_value_is_correct(self): try: from src.dice_roller import roll except: self.assertTrue(False, f'Your code should contain function named as roll(die: str)') try: result = roll("A") except: self.assertTrue(False, f'Make sure, that following function call works roll("A")') try: result = roll("B") except: self.assertTrue(False, f'Make sure, that following function call works roll("B")') try: result = roll("C") except: self.assertTrue(False, f'Make sure, that following function call works roll("C")') self.assertTrue(type(result) == int, f'Function roll does not return a integer, when executing the following code roll("A")') def test_2_correct_results_with_throws_die_A(self): from src.dice_roller import roll expected = [3, 6] count = {3:0, 6:0} times = 60000 for i in range(times): result = roll("A") self.assertTrue(result in expected, f'When calling roll("A") result must be 3 or 6, now result was {result}') count[result] += 1 n = 3 m = 5 self.assertTrue(m*9700 < count[n] < m*10300, f'When calling roll("A") {times} times, number {n} should be the result approx {m*times//6} times, now it was thrown {count[n]} times, your dice cannot work properly!') n = 6 m = 1 self.assertTrue(m*9700 < count[n] < m*10300, f'When calling roll("A") {times} times, number {n} should be the result approx {m*times//6} times, now it was thrown {count[n]} times, your dice cannot work properly!') def test_2_correct_results_with_throws_die_B(self): from src.dice_roller import roll expected = [2, 5] count = {2:0, 5:0} times = 60000 for i in range(times): result = roll("B") self.assertTrue(result in expected, f'When calling roll("B") result must be 2 or 5, now result was {result}') count[result] += 1 n = 2 m = 3 self.assertTrue(m*9700 < count[n] < m*10300, f'When calling roll("B") {times} times, number {n} should be the result approx {m*times//6} times, now it was thrown {count[n]} times, your dice cannot work properly!') n = 5 m = 3 self.assertTrue(m*9700 < count[n] < m*10300, f'When calling roll("B") {times} times, number {n} should be the result approx {m*times//6} times, now it was thrown {count[n]} times, your dice cannot work properly!') def test_2_correct_results_with_throws_die_C(self): from src.dice_roller import roll expected = [1, 4] count = {1:0, 4:0} times = 60000 for i in range(times): result = roll("C") self.assertTrue(result in expected, f'When calling roll("C") result must be 1 or 4, now result was {result}') count[result] += 1 n = 1 m = 1 self.assertTrue(m*9700 < count[n] < m*10300, f'When calling roll("C") {times} times, number {n} should be the result approx {m*times//6} times, now it was thrown {count[n]} times, your dice cannot work properly!') n = 4 m = 5 self.assertTrue(m*9700 < count[n] < m*10300, f'When calling roll("C") {times} times, number {n} should be the result approx {m*times//6} times, now it was thrown {count[n]} times, your dice cannot work properly!') def test_3_function_play_exists_and_return_value_is_correct(self): try: from src.dice_roller import play except: self.assertTrue(False, f'Your code should contain function named as play(die1: str, die2: str, times: int)') try: result = play("A", "B", 10) except: self.assertTrue(False, f'Make sure, that following function call works play("A", "B", 10)') try: result = play("C", "A", 10) except: self.assertTrue(False, f'Make sure, that following function call works play("C", "A", 10)') try: result = play("B", "C", 10) except: self.assertTrue(False, f'Make sure, that following function call works play("B", "C", 10)') self.assertTrue(type(result) == tuple, f'Function play is expected to return a tuple, which contains three integers, when executing the following code play("B", "C", 10).\nThe function returned {result}') self.assertTrue(len(result) == 3, f'Function play is expected to return a tuple, which contains three integers, when executing the following code play("B", "C", 10).\nThe function returned {result}') self.assertTrue(type(result[0]) == int, f'Function play is expected to return a tuple, which contains three integers, when executing the following code play("B", "C", 10).\nThe function returned {result}') self.assertTrue(type(result[1]) == int, f'Function play is expected to return a tuple, which contains three integers, when executing the following code play("B", "C", 10).\nThe function returned {result}') self.assertTrue(type(result[2]) == int, f'Function play is expected to return a tuple, which contains three integers, when executing the following code play("B", "C", 10).\nThe function returned {result}') def test_4_return_values_make_sense(self): from src.dice_roller import play n1 = "A" n2 = "B" code = f'play("{n1}", "{n2}", 100)' result = play(n1, n2, 100) self.assertEqual(result[0] + result[1] , 100, f'When calling {code} sum of the wins must be 100, now the return value was {result}') self.assertTrue(result[0] > 0 and result[1] > 0, f'When calling {code} both of must have wins, now the return value was {result}') self.assertTrue(result[2] == 0, f'When calling {code} the result cannot include ties, the return value was {result}') n1 = "C" n2 = "A" code = f'play("{n1}", "{n2}", 100)' result = play(n1, n2, 100) self.assertEqual(result[0] + result[1] , 100, f'When calling {code} sum of the wins must be 100, now the return value was {result}') self.assertTrue(result[0] > 0 and result[1] > 0, f'When calling {code} both of must have wins, now the return value was {result}') self.assertTrue(result[2] == 0, f'When calling {code} the result cannot include ties, the return value was {result}') n1 = "B" n2 = "C" code = f'play("{n1}", "{n2}", 100)' result = play(n1, n2, 100) self.assertEqual(result[0] + result[1] , 100, f'When calling {code} sum of the wins must be 100, now the return value was {result}') self.assertTrue(result[0] > 0 and result[1] > 0, f'When calling {code} both of must have wins, now the return value was {result}') self.assertTrue(result[2] == 0, f'When calling {code} the result cannot include ties, the return value was {result}') n1 = "C" n2 = "C" code = f'play("{n1}", "{n2}", 1000)' result = play(n1, n2, 1000) self.assertEqual(result[0] + result[1] + result[2], 1000, f'When calling {code} sum of the wins must be 100, now the return value was {result}') self.assertTrue(result[0] > 0 and result[1] > 0, f'When calling {code} both of must have wins, now the return value was {result}') self.assertTrue(result[2] > 0, f'When calling {code} the result must have ties, the return value was {result}') def test_5_A_against_B(self): from src.dice_roller import play wons = { "A":0, "B":0, "C": 0} times = 100 for i in range(times): n1 = "A" n2 = "B" result = play(n1, n2, 100) code = f'play("{n1}", "{n2}", 100)' wons[n1] += result[0] wons[n2] += result[1] self.assertTrue(wons[n1] > wons[n2], f'When calling {times} times {code} dice {n1} is expected to win more often') def test_5_B_against_C(self): from src.dice_roller import play wons = { "A":0, "B":0, "C": 0} times = 100 for i in range(times): n1 = "B" n2 = "C" result = play(n1, n2, 100) code = f'play("{n1}", "{n2}", 100)' wons[n1] += result[0] wons[n2] += result[1] self.assertTrue(wons[n1] > wons[n2], f'When calling {times} times {code} dice {n1} is expected to win more often') def test_5_C_against_A(self): from src.dice_roller import play wons = { "A":0, "B":0, "C": 0} times = 100 for i in range(times): n1 = "C" n2 = "A" result = play(n1, n2, 100) code = f'play("{n1}", "{n2}", 100)' wons[n1] += result[0] wons[n2] += result[1] self.assertTrue(wons[n1] > wons[n2], f'When calling {times} times {code} dice {n1} is expected to win more often') if __name__ == '__main__': unittest.main()
<reponame>CN-3211/vt-cesium2.0 import { Viewer, Matrix4, Cartesian3, Math, Rectangle, Camera, EasingFunction, } from 'cesium' class FlyTo { private viewer: Viewer constructor(viewer: Viewer) { this.viewer = viewer } flyTo(options: { destination: Cartesian3 | Rectangle orientation?: any duration?: number complete?: Camera.FlightCompleteCallback cancel?: Camera.FlightCancelledCallback endTransform?: Matrix4 maximumHeight?: number pitchAdjustHeight?: number flyOverLongitude?: number flyOverLongitudeWeight?: number convert?: boolean easingFunction?: EasingFunction.Callback }): void { this.viewer.camera.flyTo(options) } flyToEarth(): void { this.flyTo({ destination: Cartesian3.fromDegrees(110, 16, 20000000), orientation: { heading: Math.toRadians(0), pitch: Math.toRadians(-90), roll: 0.0, }, duration: 1, }) } flyToChina(): void { this.flyTo({ destination: Cartesian3.fromDegrees(109, 33.2, 5000000), orientation: { heading: Math.toRadians(0), pitch: Math.toRadians(-90), roll: 0.0, }, duration: 1, }) } } export default FlyTo
public class StatCalculator { public static Stats getStats(int[] arr) { int sum = 0; int min = arr[0]; int max = arr[0]; int mode = 0; int mostFrequentNumOccurrence = 0; for (int i=0; i<arr.length; i++) { sum += arr[i]; if (arr[i] < min) { min = arr[i]; } if (arr[i] > max) { max = arr[i]; } int occurrence = 0; for (int j=0; j<arr.length; j++) { if (arr[i] == arr[j]) { occurrence++; } if (occurrence > mostFrequentNumOccurrence) { mode = arr[i]; mostFrequentNumOccurrence = occurrence; } } } int mean = sum/arr.length; int range = max - min; Arrays.sort(arr); int median = arr[arr.length/2]; return new Stats(mean, median, mode, range); } static class Stats { int mean; int median; int mode; int range; public Stats(int mean, int median, int mode, int range) { this.mean = mean; this.median = median; this.mode = mode; this.range = range; } } }
import React from "react"; /** * convert text to html */ class DangerHTML extends React.Component { htmlDecode(input) { var e = document.createElement("div"); e.innerHTML = input; return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue; } render() { return ( <div className={this.props.style} dangerouslySetInnerHTML={{ __html: this.htmlDecode(this.props.content) }} /> ); } } export default DangerHTML;
// https://open.kattis.com/problems/mirror #include <iostream> #include <vector> using namespace std; typedef vector<char> vc; typedef vector<vc> vvc; int main() { int t; cin >> t; for (int i = 0; i < t; i++) { int r, c; cin >> r >> c; vvc v(r); for (int j = 0; j < r; j++) { v[j] = vc(c); for (int k = 0; k < c; k++) { cin >> v[j][k]; } } cout << "Test " << i + 1 << endl; for (int j = r - 1; j >= 0; j--) { for (int k = c - 1; k >= 0; k--) { cout << v[j][k]; } cout << endl; } } }
<filename>src/main/java/aufgabe11_7/Bunop.java package aufgabe11_7; public enum Bunop { // utf8: "Köpfchen in das Wasser, Schwänzchen in die Höh." -CIA-Verhörmethode Not(3); private int order; Bunop(int precedence) { this.order = precedence; } public int getPriority() { return order; } }
<reponame>Ziezi/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup- /* TITLE String Manipulation Chapter3Drill.cpp Bjarne Stroustrup "Programming: Principles and Practice Using C++" COMMENT Objective: I/O interaction and basic string manipulation. Input: Reqeusts information (name, age, sex) Output: It prints standard text depending on the input information. Author: <NAME> Data: 1.2.2015 */ #include "../../std_lib_facilities.h" int main() { // comparison variables; avoiding "magical" literals const char male ='m'; const char female ='f'; const char other = 'o'; cout << "Please enter your first name (followed by CR-(Enter)):\n"; string first_name; cin >> first_name; cout << "Dear," << first_name << "!\n"; cout << "\t" << "greetings from Greece, here it is mildly hot summer, perfect for vacation.\n"; cout << "\t" << "I hope you are great, can not wait to see you!\n"; cout << "What was our common friend name?\n"; string friend_name; cout << "Have you seen" << friend_name << "lately?\n"; cout << "What is" << friend_name << "'s gender (m/f/o)?\n"; char friend_sex = 0; while (friend_sex != male || friend_sex != female || friend_sex != other) { cout << "Select from the three (char) options: ""m"" for: male, ""f"" for: female, ""o"" for: other" << endl; cin >> friend_sex; } if (friend_sex == male) { cout << "If you see" << friend_name << ", please ask him to call me.\n"; } else if (friend_sex == female) { cout << "If you see" << friend_name << ", please ask her to call me.\n"; } else if (friend_sex == other) { cout << "If you see" << friend_name << ", please tell that I asked for a phonecall. \n"; } cout << "How old were you?\n"; int age = 0; cin >> age; if (age < 0 || age > 100) { error("You are kidding!?"); } if (age = 12) { cout << "I heard that you are turning" << age + 1 << "next month.\n"; } if (age = 17) { cout << "Next year you will able to vote.\n"; } if (age > 70) { cout << "I hope you are enjoing retirement.\n"; } cout << "Yours sincerely," << "\v\v" << "Chris\n"; }
cd /root/Desktop/route_commands_m2/ssh_tunnel # logs into Ubiquiti M2 Bullet in the background and generates a SSH tunnel echo "DEBUG: Opening SSH Tunneling, enter PASSWORD" ssh -f -N -D 1080 REDACTED_LOGIN@REDACTED_SUBNET.1 echo "Proxy tunnel opened on 127.0.0.1 PORT 1080" echo "DEBUG: Sudoing to superuser" # sudo su # saves a copy of previous proxychains config echo "DEBUG: Backing up old proxychains conf if it exists" cp -r /etc/proxychains.conf /etc/proxychains.conf.save cat /root/Desktop/route_commands_m2/ssh_tunnel/default_config.conf > /etc/proxychains.conf # echos a new proxychains file, completely replacing the old config echo "$default_config" > /etc/proxychains.conf echo "Copied new proxychains config, default proxy port: 1080" # tells user how to use proxychains echo "Setup complete, please precede all of your commands with 'proxychains <cmd>'" # any additional scripts that I want to run # assault mode script. Auto starts besside-ng, comment out to disable proxychains python /root/Desktop/route_commands_m2/Cylon-Raider-Lite/project_wardriver_xpress/m2_main.py
from .tmdb import ( TmdbMovieAdapter, TmdbMovieCastAdapter, TmdbMovieListAdapter, TmdbPersonAdapter, ) class MovieInformation: def __init__(self, movie_id): self.movie_id = movie_id def get_movie_details(self): movie_adapter = TmdbMovieAdapter() movie_details = movie_adapter.get_movie_details(self.movie_id) print("Movie Details:") print(f"Title: {movie_details['title']}") print(f"Release Date: {movie_details['release_date']}") print(f"Overview: {movie_details['overview']}") print(f"Average Vote: {movie_details['vote_average']}") def get_cast_details(self): cast_adapter = TmdbMovieCastAdapter() cast_details = cast_adapter.get_cast_details(self.movie_id) print("\nCast Details:") for actor in cast_details: print(f"Name: {actor['name']}") print(f"Character: {actor['character']}") print(f"Order: {actor['order']}") print("--------------------") # Example usage movie_info = MovieInformation(12345) # Replace 12345 with the actual movie ID movie_info.get_movie_details() movie_info.get_cast_details()
public static void fibonacci(int n) { int first = 0, second = 1, next; System.out.println("First " + n + " terms: "); for (int i = 0; i < n; ++i) { if(i <= 1) next = i; else { next = first + second; first = second; second = next; } System.out.println(next); } }
<filename>src/services/chat/redux/actions/data.ts import { IAppReduxState, IDependencies } from 'shared/types/app'; import { ActionCreator, Dispatch } from 'redux'; import SocketSubscriber from 'services/sockets/SocketSubscriber'; const subscriber: SocketSubscriber = new SocketSubscriber(); export function updateMetaData(eventType: string, actionType: string, data: any): any { return { type: 'CHAT:WS_UPDATE', payload: { atype: actionType, data } }; } export function subscribeToEvent(type: string): ActionCreator<void> { return (dispatch: Dispatch<IAppReduxState>, _getState: () => IAppReduxState, extra: IDependencies) => { const { sockets } = extra; function onChange(actionType: string, data: any): void { dispatch(updateMetaData(type, actionType, data)); } subscriber.subscribe(sockets, type, onChange); dispatch({ type: 'CHAT:SUBSCRIBE_TO_EVENT' }); }; } export function unsubscribeFromEvent(type: string): ActionCreator<void> { return (dispatch: Dispatch<IAppReduxState>, _getState: () => IAppReduxState, extra: IDependencies) => { const { sockets } = extra; subscriber.unsubscribe(sockets, type); dispatch({ type: 'CHAT:UNSUBSCRIBE_FROM_EVENT' }); }; }
import { SystemStyleObject } from "@chakra-ui/styled-system"; import { Dict, StringOrNumber } from "@chakra-ui/utils"; import { ThemingProps } from "./system.types"; export declare function useChakra<T extends Dict = Dict>(): { theme: T; colorMode: import("@chakra-ui/color-mode").ColorMode; toggleColorMode: () => void; setColorMode: (value: any) => void; }; export declare function useToken<T extends StringOrNumber>(scale: string, token: T | T[], fallback?: T | T[]): any; export declare function useProps<P extends ThemingProps>(themeKey: string, props: P, isMulti: true): { styles: Record<string, SystemStyleObject>; props: Omit<P, keyof ThemingProps>; }; export declare function useProps<P extends ThemingProps>(themeKey: string, props?: P, isMulti?: boolean): { styles: SystemStyleObject; props: Omit<P, keyof ThemingProps>; }; //# sourceMappingURL=hooks.d.ts.map
#!/bin/bash declare -a projects old_dir=$(pwd); projects=( $( cat <$(dirname $0)/config/backends.cfg ) ) for dir in "${projects[@]}"; do echo Setup dev project ${dir}; cd ${dir}; ./setup-dev.sh; done; cd ${old_dir}
#!/bin/bash set -e RESOURCE_NAME=${1:-ccmlin008-80} SRUN_TIMEOUT_MIN=${2:-120} export MLPROCESSORS_FORCE_RUN=FALSE export NUM_WORKERS=2 export MKL_NUM_THREADS=$NUM_WORKERS export NUMEXPR_NUM_THREADS=$NUM_WORKERS export OMP_NUM_THREADS=$NUM_WORKERS export DISPLAY="" COLLECTION=spikeforest KACHERY_NAME=kbucket compute-resource-start $RESOURCE_NAME \ --allow_uncontainerized \ --collection $COLLECTION --kachery_name $KACHERY_NAME \ --srun_opts "-c 2 -n 80 -p ccm --time $SRUN_TIMEOUT_MIN"
package io.opensphere.wfs.envoy; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.net.URLEncoder; import java.security.GeneralSecurityException; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; import org.apache.log4j.Logger; import org.xml.sax.SAXException; import io.opensphere.core.Toolbox; import io.opensphere.core.cache.CacheDeposit; import io.opensphere.core.cache.DefaultCacheDeposit; import io.opensphere.core.cache.accessor.PropertyAccessor; import io.opensphere.core.cache.accessor.SerializableAccessor; import io.opensphere.core.data.DataRegistry; import io.opensphere.core.data.util.DataModelCategory; import io.opensphere.core.data.util.SimpleQuery; import io.opensphere.core.model.LatLonAlt; import io.opensphere.core.server.HttpServer; import io.opensphere.core.server.ResponseValues; import io.opensphere.core.server.ServerProvider; import io.opensphere.core.util.Utilities; import io.opensphere.wfs.placenames.GMLPlaceNameSAXHandler311; import io.opensphere.wfs.placenames.PlaceNameData; import io.opensphere.wfs.placenames.PlaceNameTile; /** Helper class for the WMS envoy. */ public final class WFSEnvoyPlaceNameHelper { /** Logger reference. */ private static final Logger LOGGER = Logger.getLogger(WFSEnvoyPlaceNameHelper.class); /** * Build the URL for requesting the place name data. * * @param placeNameTile The tile for which data will be requested. * @param serverURL Base url for the server. * @return The URL for the request. */ private static URL buildPlaceNameURL(PlaceNameTile placeNameTile, String serverURL) { String server = serverURL; if (server == null) { return null; } StringBuffer sb = new StringBuffer(server); if (sb.charAt(sb.length() - 1) != '?') { sb.append('?'); } StringBuilder filter = new StringBuilder(512); filter.append("<Filter xmlns=\"http://www.opengis.net/ogc\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + "xmlns:gml=\"http://www.opengis.net/gml\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" " + "xmlns:smil20=\"http://www.w3.org/2001/SMIL20\" " + "xmlns:smil20lang=\"http://www.w3.org/2001/SMIL20/Language\"><And><BBOX><PropertyName>GEOM</PropertyName>" + "<gml:Envelope><gml:lowerCorner>"); LatLonAlt lowerLeft = placeNameTile.getKey().getBounds().getLowerLeft().getLatLonAlt(); LatLonAlt upperRight = placeNameTile.getKey().getBounds().getUpperRight().getLatLonAlt(); filter.append(lowerLeft.getLonD()).append(' '); filter.append(lowerLeft.getLatD()); filter.append("</gml:lowerCorner><gml:upperCorner>"); filter.append(upperRight.getLonD()).append(' '); filter.append(upperRight.getLatD()); filter.append("</gml:upperCorner></gml:Envelope></BBOX>"); filter.append(placeNameTile.getLayer().getConfiguration().getFilter()).append("</And></Filter>"); StringBuilder ab = new StringBuilder(131); // @formatter:off ab.append("version=1.1.0&TypeName=Place_Names" + "&Request=GetFeature" + "&Service=WFS" + "&OUTPUTFORMAT=text/xml;+subtype=gml/3.1.1" + "&MAXFEATURES=1500" + "&FILTER="); // @formatter:on sb.append(ab); try { sb.append(URLEncoder.encode(filter.toString(), "ISO-8859-1")); return new java.net.URL(sb.toString()); } catch (UnsupportedEncodingException e1) { LOGGER.error("Failed to encode string to URL : " + filter, e1); } catch (MalformedURLException e) { LOGGER.error("Failed to create URL from string : " + sb.toString(), e); } return null; } /** * Read the image off of the provided stream. * * @param stream The stream which contains the data. * @return The extracted data. * @throws IOException when connection to the server has a failure. */ private static PlaceNameData getPlaceNamesFromStream(InputStream stream) throws IOException { PlaceNameData placeNames = null; GMLPlaceNameSAXHandler311 handler = new GMLPlaceNameSAXHandler311(); try { SAXParserFactory.newInstance().newSAXParser().parse(stream, handler); placeNames = handler.getPlaceNameData(); } catch (SAXException | ParserConfigurationException e) { LOGGER.error("Failed to parse place names.", e); } return placeNames; } /** * Open a connection to the server and return the input stream. * * @param url The server URL. * @param response The optional HTTP response. * @param toolbox The system toolbox. * @return The input stream. * @throws IOException If an error occurs connection to the server. * @throws GeneralSecurityException If authentication fails. * @throws URISyntaxException If the url could not be converted to a URI. */ private static InputStream openServerConnection(URL url, ResponseValues response, Toolbox toolbox) throws IOException, GeneralSecurityException, URISyntaxException { ServerProvider<HttpServer> provider = toolbox.getServerProviderRegistry().getProvider(HttpServer.class); HttpServer serverConnection = provider.getServer(url); return serverConnection.sendGet(url, response); } /** * Retrieve place names from the server or cache. * * @param serverURL Base URL for the server. * @param source Source to use with the data registry. * @param placeNameTile Tile for which place names are desired. * @param dataRegistry Data registry. * @param toolbox The system toolbox. */ public static void retrievePlaceNameData(String serverURL, String source, final PlaceNameTile placeNameTile, DataRegistry dataRegistry, Toolbox toolbox) { String family = PlaceNameData.class.getName(); String category = placeNameTile.getLayer().getConfiguration().getDataSetName(); DataModelCategory dataModelCategory = new DataModelCategory(source, family, category); SimpleQuery<PlaceNameData> query = new SimpleQuery<>(dataModelCategory, PlaceNameData.PROPERTY_DESCRIPTOR); dataRegistry.performLocalQuery(query); List<PlaceNameData> results = query.getResults(); PlaceNameData placeNames = results.isEmpty() ? null : results.get(0); if (placeNames != null) { placeNameTile.receiveData(placeNames); return; } // Not in the cache, so request from the server. URL url = WFSEnvoyPlaceNameHelper.buildPlaceNameURL(placeNameTile, serverURL); InputStream stream = null; try { ResponseValues response = new ResponseValues(); stream = WFSEnvoyPlaceNameHelper.openServerConnection(url, response, toolbox); placeNames = WFSEnvoyPlaceNameHelper.getPlaceNamesFromStream(stream); if (placeNames != null && !placeNames.getPlaceNames().isEmpty()) { placeNameTile.receiveData(placeNames); dataRegistry.removeModels(dataModelCategory, false); Date expiration = new Date(System.currentTimeMillis() + 3600000); Collection<? extends PropertyAccessor<PlaceNameData, ?>> accessors = Collections .singleton(SerializableAccessor.getHomogeneousAccessor(PlaceNameData.PROPERTY_DESCRIPTOR)); CacheDeposit<PlaceNameData> deposit = new DefaultCacheDeposit<>(dataModelCategory, accessors, Collections.singleton(placeNames), true, expiration, false); dataRegistry.addModels(deposit); return; } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug(placeNameTile.getServerName() + ": No places name results returned for layer " + category); } } } catch (GeneralSecurityException | IOException | URISyntaxException e) { LOGGER.error("Failed to read place names for URL [" + url + "] placeNameKey [" + placeNameTile.getKeyString() + "]: ", e); } finally { Utilities.closeQuietly(stream); } } /** Disallow construction. */ private WFSEnvoyPlaceNameHelper() { } }
import { module, test } from 'qunit'; import { setupTest } from 'ember-qunit'; module('Unit | Route | tutorials/development', function (hooks) { setupTest(hooks); test('it exists', function (assert) { let route = this.owner.lookup('route:tutorials/development'); assert.ok(route); }); }); //# sourceMappingURL=development-test.js.map
import torch list = torch.tensor([1, 9, 6, 3]) mean = list.mean() print("The mean of the given list is:", mean)
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors. # # 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 PROBLEM=translate_iwslt17 DATA_DIR=$1 TMP_DIR=$2 IWSLT17_ORIG_DATA_PATH=$3 IWSLT17_OVERLAP_DATA_PATH=$4 mkdir -p $DATA_DIR $TMP_DIR python -m language.labs.consistent_zero_shot_nmt.bin.t2t_datagen \ --data_dir=$DATA_DIR \ --iwslt17_orig_data_path=$IWSLT17_ORIG_DATA_PATH \ --iwslt17_overlap_data_path=$IWSLT17_OVERLAP_DATA_PATH \ --problem=$PROBLEM \ --tmp_dir=$TMP_DIR \ --alsologtostderr
<filename>src/args/processes-parser.ts import { isObject } from "lodash" import { argsParser } from "@/args/parser" import { globalVariableSelector } from "@/module/selector/vim-variable" import type { ArgsOptions, CustomProcessesVimVariable, ProcessesName, UserProcesses } from "@/type" const parseOptions = (options: ArgsOptions): UserProcesses | null => { const processesArgs = options.processes if (processesArgs == null) { return null } if (typeof processesArgs === "string") { return { type: "global_variable", value: processesArgs } } throw new Error("--processes option can only be used once") } export const parseProcesses = (defaultProcessesName: ProcessesName, args: string): UserProcesses | undefined => { const parser = argsParser() const options = parser.parse(args) const parsedOptions = parseOptions(options) if (parsedOptions != null) { return parsedOptions } const customProcessesDictionary = globalVariableSelector("fzfPreviewCustomProcesses") if ( isObject(customProcessesDictionary) && isObject((customProcessesDictionary as CustomProcessesVimVariable)[defaultProcessesName]) ) { return { type: "custom_processes_variable", value: defaultProcessesName } } return undefined }
// First Function function fibonacci(num) { if (num <= 1) return num; return fibonacci(num - 1) + fibonacci(num - 2); } // Second Function - Using Dynamic Programming function fibonacciDP(num, memo=[]) { if (memo[num] !== undefined) return memo[num]; if (num <= 1) return num; memo[num] = fibonacciDP(num - 1, memo) + fibonacciDP (num - 2, memo); return memo[num] } // Testing console.log(fibonacci(9)); console.log(fibonacciDP(9));
<reponame>amazinigmech2418/CanvasLib<filename>webglLib.js // Get context for WebGL function WebGLCanvas(query) { if(document.querySelectorAll(query).length==0) { document.body.innerHTML += "<canvas>hi</canvas>"; var iidd = query.split("#"); if (iidd.length > 1) { document.querySelectorAll("canvas")[document.querySelectorAll("canvas").length-1].id = iidd[1]; } var cllass = query.split("."); if (cllass.length > 1) { document.querySelectorAll("canvas")[document.querySelectorAll("canvas").length-1].class = cllass[1]; } } this.canvas = document.querySelectorAll(query)[0]; this.ctx = document.querySelectorAll(query)[0].getContext("webgl"); } /* Usage: var glcanvas = new WebGLCanvas("#canvasID"); // Use any query selector to get a canvas or create a new one! var webGLcontext = glcanvas.ctx; // This gets the WebGL context. // Use webGLcontext to control the canvas with WebGL. */
<gh_stars>0 const flexibleConfigurationLists = { TextArea: { props: { autosize: { label: "自适应内容高度", defaultValue: true, value: true, type: "boolean|object".split("|") }, defaultValue: { label: "输入框默认值", defaultValue: "", value: "", type: "string" }, value: { label: "输入框值", defaultValue: "", value: "", type: "string" }, onPressEnter: { label: "回车按键回调", type: "func", value: null, defaultValue: null } } } }; export default flexibleConfigurationLists;
<reponame>chlds/util /* **** Notes Write. Remarks: write di,si ; write contents into a storage */ # define CAR # include <stdio.h> # include "./../../../incl/config.h" signed(__cdecl wr_ds_w(signed short(**argp))) { auto signed short *w; auto signed i,r; auto signed short flag; auto fl_t fl; auto signed threshold = (0x03); auto signed char *perm = ("rdonly,binary"); if(!argp) return(0x00); if(!(*argp)) return(0x00); r = init_fl(0x00,&fl); if(!r) { printf("%s \n","<< Error at fn. init_fl()"); return(0x00); } AND(r,0x00); r = (threshold+(~r)); while(r) { w = (*argp); argp++; *(--r+(R(v,fl))) = (void*) (w); if(!w) return(0x00); } return(xt_w(perm,w,&fl,wr_ds_w_r)); }
<reponame>Martin-BG/Softuni-Java-MVC-Spring-Feb-2019<gh_stars>1-10 package org.softuni.cardealer.service; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import org.modelmapper.ModelMapper; import org.softuni.cardealer.domain.entities.CarSale; import org.softuni.cardealer.domain.entities.PartSale; import org.softuni.cardealer.domain.models.service.CarSaleServiceModel; import org.softuni.cardealer.domain.models.service.PartSaleServiceModel; import org.softuni.cardealer.repository.CarSaleRepository; import org.softuni.cardealer.repository.PartSaleRepository; import org.springframework.boot.test.context.SpringBootTest; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; @RunWith(MockitoJUnitRunner.class) @SpringBootTest public class SaleServiceTests { @Mock private CarSaleRepository carSaleRepository; @Mock private PartSaleRepository partSaleRepository; @Mock private ModelMapper modelMapper; @InjectMocks private SaleServiceImpl service; @Before public void initTests() { Mockito.when(modelMapper.map(eq(null), any())) .thenThrow(new IllegalArgumentException()); } @Test public void saleCar_validInputData_correctMethodsAndArgumentsUsed() { CarSale carSale = mock(CarSale.class); CarSaleServiceModel model = mock(CarSaleServiceModel.class); Mockito.when(modelMapper.map(model, CarSale.class)).thenReturn(carSale); Mockito.when(carSaleRepository.saveAndFlush(carSale)).thenReturn(carSale); Mockito.when(modelMapper.map(carSale, CarSaleServiceModel.class)).thenReturn(model); CarSaleServiceModel result = service.saleCar(model); Mockito.verify(modelMapper).map(model, CarSale.class); Mockito.verify(carSaleRepository).saveAndFlush(carSale); Mockito.verify(modelMapper).map(carSale, CarSaleServiceModel.class); Assert.assertEquals(model, result); } @Test(expected = IllegalArgumentException.class) public void saleCar_nullInput_throwsIllegalArgumentException() { service.saleCar(null); } @Test public void salePart_validInputData_correctMethodsAndArgumentsUsed() { PartSale partSale = mock(PartSale.class); PartSaleServiceModel model = mock(PartSaleServiceModel.class); Mockito.when(modelMapper.map(model, PartSale.class)).thenReturn(partSale); Mockito.when(partSaleRepository.saveAndFlush(partSale)).thenReturn(partSale); Mockito.when(modelMapper.map(partSale, PartSaleServiceModel.class)).thenReturn(model); PartSaleServiceModel result = service.salePart(model); Mockito.verify(modelMapper).map(model, PartSale.class); Mockito.verify(partSaleRepository).saveAndFlush(partSale); Mockito.verify(modelMapper).map(partSale, PartSaleServiceModel.class); Assert.assertEquals(model, result); } @Test(expected = IllegalArgumentException.class) public void salePart_nullInput_throwsIllegalArgumentException() { service.saleCar(null); } }
<gh_stars>1-10 package aserg.gtf.task; public abstract class GitDev { private static int id = 1; public static int getNewId(){ return id++; } protected int devId; private String name; private String email; private String shaExample; private int gitHubId=0; public GitDev(String name, String email, String shaExample) { this.name = name; this.email = email; this.shaExample = shaExample; } // public AliasDev addAlias(GitDev dev, String pairStr){ // AliasDev aliasDev; // if (this instanceof SingleDev) { // aliasDev = new AliasDev(this, pairStr); // aliasDev.addDev(this); // } // else // aliasDev = (AliasDev) this; // // aliasDev.addDev(dev); // aliasDev.normalizeId(this.devId); // return aliasDev; // } public int getDevId() { return devId; } public void setDevId(int devId) { this.devId = devId; } public abstract void normalizeId(int newId); public String getName() { return name; } public String getEmail() { return email; } public static String getPairString(String name, String email){ return name.toUpperCase()+"**"+email.toUpperCase(); } public String getPairString(){ return getPairString(this.name, this.email); } @Override public boolean equals(Object obj) { GitDev other = (GitDev)obj; return this.getPairString().equals(other.getPairString()); } @Override public int hashCode() { // TODO Auto-generated method stub return getPairString().hashCode(); } public String getShaExample() { return shaExample; } @Override public String toString() { return name+"**"+email + "(" + getDevId()+ " - "+ gitHubId + ")"; } public int getGitHubId() { return gitHubId; } public void setGitHubId(int gitHubId) { this.gitHubId = gitHubId; } }
/*- * ========================LICENSE_START================================= * TeamApps * --- * Copyright (C) 2014 - 2021 TeamApps.org * --- * 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. * =========================LICENSE_END================================== */ import * as log from "loglevel"; import {AbstractUiToolContainer} from "../AbstractUiToolContainer"; import {TeamAppsEvent} from "../../util/TeamAppsEvent"; import {UiToolbarButtonGroupConfig} from "../../../generated/UiToolbarButtonGroupConfig"; import {UiToolbarButtonConfig} from "../../../generated/UiToolbarButtonConfig"; import {createUiDropDownButtonClickInfoConfig, UiDropDownButtonClickInfoConfig} from "../../../generated/UiDropDownButtonClickInfoConfig"; import {DEFAULT_TEMPLATES} from "../../trivial-components/TrivialCore"; import {TeamAppsUiContext} from "../../TeamAppsUiContext"; import {doOnceOnClickOutsideElement, insertAfter, parseHtml} from "../../Common"; import {UiToolAccordionCommandHandler, UiToolAccordionConfig, UiToolAccordionEventSource} from "../../../generated/UiToolAccordionConfig"; import {AbstractUiToolContainer_ToolbarButtonClickEvent, AbstractUiToolContainer_ToolbarDropDownItemClickEvent} from "../../../generated/AbstractUiToolContainerConfig"; import {TeamAppsUiComponentRegistry} from "../../TeamAppsUiComponentRegistry"; import {UiItemView} from "../../UiItemView"; import {OrderedDictionary} from "../../util/OrderedDictionary"; import {UiComponent} from "../../UiComponent"; import {UiToolAccordionButton} from "./UiToolAccordionButton"; require("jquery-ui/ui/scroll-parent.js") export class UiToolAccordion extends AbstractUiToolContainer<UiToolAccordionConfig> implements UiToolAccordionCommandHandler, UiToolAccordionEventSource { public static DEFAULT_TOOLBAR_MAX_HEIGHT = 70; public readonly onToolbarButtonClick: TeamAppsEvent<AbstractUiToolContainer_ToolbarButtonClickEvent> = new TeamAppsEvent<AbstractUiToolContainer_ToolbarButtonClickEvent>(this); public readonly onToolbarDropDownItemClick: TeamAppsEvent<AbstractUiToolContainer_ToolbarDropDownItemClickEvent> = new TeamAppsEvent<AbstractUiToolContainer_ToolbarDropDownItemClickEvent>(this); private buttonGroupsById: OrderedDictionary<UiButtonGroup> = new OrderedDictionary<UiButtonGroup>(); private $mainDomElement: HTMLElement; private $backgroundColorDiv: HTMLElement; constructor(config: UiToolAccordionConfig, context: TeamAppsUiContext) { super(config, context); this.$mainDomElement = parseHtml(`<div class="UiToolAccordion teamapps-blurredBackgroundImage"></div>`); this.$backgroundColorDiv = parseHtml('<div class="background-color-div"></div>'); this.$mainDomElement.appendChild(this.$backgroundColorDiv); let allButtonGroups = [...config.leftButtonGroups, ...config.rightButtonGroups]; for (let i = 0; i < allButtonGroups.length; i++) { const buttonGroupConfig = allButtonGroups[i]; let buttonGroup = this.createButtonGroup(buttonGroupConfig); this.buttonGroupsById.push(buttonGroupConfig.groupId, buttonGroup); this.$backgroundColorDiv.appendChild(buttonGroup.getMainDomElement()); } this.refreshEnforcedButtonWidth(); } public doGetMainElement(): HTMLElement { return this.$mainDomElement; } private createButtonGroup(buttonGroupConfig: UiToolbarButtonGroupConfig): UiButtonGroup { return new UiButtonGroup(buttonGroupConfig, this, this._context, AbstractUiToolContainer.$sizeTestingContainer); } public setButtonHasDropDown(groupId: string, buttonId: string, hasDropDown: boolean): void { this.buttonGroupsById.getValue(groupId).setButtonHasDropDown(buttonId, hasDropDown); } public setDropDownComponent(groupId: string, buttonId: string, component: UiComponent): void { this.buttonGroupsById.getValue(groupId).setDropDownComponent(buttonId, component); } public setButtonVisible(groupId: string, buttonId: string, visible: boolean) { this.buttonGroupsById.getValue(groupId).setButtonVisible(buttonId, visible); this.refreshEnforcedButtonWidth(); } setButtonColors(groupId: string, buttonId: string, backgroundColor: string, hoverBackgroundColor: string): void { this.buttonGroupsById.getValue(groupId).setButtonColors(buttonId, backgroundColor, hoverBackgroundColor); } public setButtonGroupVisible(groupId: string, visible: boolean) { this.buttonGroupsById.getValue(groupId).setVisible(visible); this.refreshEnforcedButtonWidth(); } public addButtonGroup(buttonGroupConfig: UiToolbarButtonGroupConfig) { const existingButtonGroup = this.buttonGroupsById.getValue(buttonGroupConfig.groupId); if (existingButtonGroup) { this.removeButtonGroup(buttonGroupConfig.groupId); } const buttonGroup = this.createButtonGroup(buttonGroupConfig); this.buttonGroupsById.push(buttonGroupConfig.groupId, buttonGroup); let allButtonGroups = this.buttonGroupsById.values; let otherGroupIndex = 0; for (; otherGroupIndex < allButtonGroups.length; otherGroupIndex++) { let otherGroup = allButtonGroups[otherGroupIndex]; if (otherGroup.position > buttonGroupConfig.position) { break; } } if (allButtonGroups[otherGroupIndex]) { this.$backgroundColorDiv.insertBefore(buttonGroup.getMainDomElement(), allButtonGroups[otherGroupIndex].getMainDomElement()); } else { this.$backgroundColorDiv.appendChild(buttonGroup.getMainDomElement()); } this.refreshEnforcedButtonWidth(); } public removeButtonGroup(groupId: string): void { const buttonGroup = this.buttonGroupsById.getValue(groupId); if (buttonGroup) { this.buttonGroupsById.remove(groupId); buttonGroup.getMainDomElement().remove(); } this.refreshEnforcedButtonWidth(); } public addButton(groupId: string, buttonConfig: UiToolbarButtonConfig, neighborButtonId: string, beforeNeighbor: boolean) { this.buttonGroupsById.getValue(groupId).addButton(buttonConfig, neighborButtonId, beforeNeighbor); this.refreshEnforcedButtonWidth(); } public removeButton(groupId: string, buttonId: string): void { this.buttonGroupsById.getValue(groupId).removeButton(buttonId); this.refreshEnforcedButtonWidth(); } updateButtonGroups(buttonGroups: UiToolbarButtonGroupConfig[]): void { // TODO implement only if really needed } public refreshEnforcedButtonWidth() { let maxButtonWidth = this.buttonGroupsById.values .filter(group => group.isVisible()) .reduce((maxButtonWidth, buttonGroup) => Math.max(maxButtonWidth, buttonGroup.getMaxOptimizedButtonWidth()), 1); this.buttonGroupsById.values.forEach(group => group.setEnforcedButtonWidth(maxButtonWidth)); } public onResize(): void { this.buttonGroupsById.values.forEach(group => group.onResize()); } } class UiButtonGroup { private static logger = log.getLogger("UiToolAccordion.UiButtonGroup"); private config: UiToolbarButtonGroupConfig; private visible: boolean = true; private $buttonGroupWrapper: HTMLElement; private $buttonGroup: HTMLElement; private buttonsById: { [index: string]: UiToolAccordionButton } = {}; private buttons: UiToolAccordionButton[] = []; private $buttonRows: HTMLElement[] = []; private enforcedButtonWidth: number = 1; constructor(buttonGroupConfig: UiToolbarButtonGroupConfig, private toolAccordion: UiToolAccordion, private context: TeamAppsUiContext, private $sizeTestingContainer: HTMLElement) { const $buttonGroupWrapper = parseHtml('<div class="button-group-wrapper"></div>'); const $buttonGroup = parseHtml(`<div class="toolbar-button-group" id="${this.toolAccordionId}_${buttonGroupConfig.groupId}">`); $buttonGroupWrapper.appendChild($buttonGroup); this.config = buttonGroupConfig; this.$buttonGroupWrapper = $buttonGroupWrapper; this.$buttonGroup = $buttonGroup; for (let j = 0; j < buttonGroupConfig.buttons.length; j++) { this.addButton(buttonGroupConfig.buttons[j]); } this.setVisible(buttonGroupConfig.visible); } private get toolAccordionId() { return this.toolAccordion.getId(); } public get position() { return this.config.position; } private createButton(buttonConfig: UiToolbarButtonConfig): UiToolAccordionButton { let button = new UiToolAccordionButton(buttonConfig, this.context); button.onClick.addListener(eventObject => { let dropdownClickInfo: UiDropDownButtonClickInfoConfig = null; if (button.hasDropDown) { if (button.$dropDown == null) { this.createDropDown(button); } let dropdownVisible = $(button.$dropDown).is(":visible"); dropdownClickInfo = createUiDropDownButtonClickInfoConfig(!dropdownVisible, button.dropDownComponent != null); if (!dropdownVisible) { if (button.dropDownComponent != null) { button.$dropDown.appendChild(button.dropDownComponent.getMainElement()); } this.showDropDown(button); doOnceOnClickOutsideElement(button.getMainDomElement(), e => $(button.$dropDown).slideUp(200)) } else { $(button.$dropDown).slideUp(200); } } this.toolAccordion.onToolbarButtonClick.fire({ groupId: this.config.groupId, buttonId: button.id, dropDownClickInfo: dropdownClickInfo }); }) return button; } private createDropDown(button: UiToolAccordionButton) { button.$dropDown = parseHtml(`<div class="tool-accordion-dropdown"></div>`); button.$dropDownSourceButtonIndicator = parseHtml(`<div class="source-button-indicator">`); button.$dropDown.appendChild(button.$dropDownSourceButtonIndicator); if (button.dropDownComponent) { this.setButtonDropDownComponent(button, button.dropDownComponent); } else { button.$dropDown.appendChild(parseHtml(DEFAULT_TEMPLATES.defaultSpinnerTemplate)); } return button.$dropDown; } private showDropDown(button: UiToolAccordionButton) { UiButtonGroup.logger.debug(button.$dropDown.offsetHeight); const me = this; button.$dropDown.style.display = "none"; this.insertDropdownUnderButtonRow(button); $(button.$dropDown).slideDown({ duration: 200, progress: (animation, progress: number, remainingMs: number) => { let buttonHeight = button.getMainDomElement().offsetHeight; let dropDownHeight = button.$dropDown.offsetHeight; let totalInterestingPartHeight = buttonHeight + dropDownHeight; let buttonY = button.getMainDomElement().getBoundingClientRect().top - me.getMainDomElement().closest('.UiToolAccordion').getBoundingClientRect().top; let $scrollContainer = $(me.getMainDomElement()).scrollParent(); let scrollY = $scrollContainer.scrollTop(); let viewPortHeight = $scrollContainer[0].offsetHeight; if (scrollY < buttonY + totalInterestingPartHeight - viewPortHeight) { scrollY = buttonY + totalInterestingPartHeight - viewPortHeight; $scrollContainer.scrollTop(scrollY); UiButtonGroup.logger.debug(scrollY); } if (buttonY < scrollY) { // TODO scrollY $scrollContainer.scrollTop(buttonY); } } }); $(button.$dropDownSourceButtonIndicator).position({ my: "center bottom", at: "center bottom", of: button.getMainDomElement() }); } private insertDropdownUnderButtonRow(button: UiToolAccordionButton) { let $row = this.$buttonRows.filter($row => $.contains($row, button.getMainDomElement()))[0]; insertAfter(button.$dropDown, $row); } public setDropDownComponent(buttonId: string, component: UiComponent) { let button = this.buttonsById[buttonId]; this.setButtonDropDownComponent(button, component); } setButtonHasDropDown(buttonId: string, hasDropDown: boolean) { const button = this.buttonsById[buttonId]; if (button != null) { button.hasDropDown = hasDropDown; } } private setButtonDropDownComponent(button: UiToolAccordionButton, component: UiComponent) { if (button.dropDownComponent != null) { button.dropDownComponent.getMainElement().remove(); } button.dropDownComponent = component; if (component != null) { if (component instanceof UiItemView) { component.onItemClicked.addListener(eventObject => { this.toolAccordion.onToolbarDropDownItemClick.fire({ groupId: this.config.groupId, buttonId: button.id, dropDownGroupId: eventObject.groupId, dropDownItemId: eventObject.itemId }); }); } if (button.$dropDown != null) { button.$dropDown.querySelectorAll<HTMLElement>(":scope :not(.source-button-indicator)").forEach(b => b.remove()); // remove spinner or old component, if present... if ($(button.$dropDown).is(":visible")) { button.$dropDown.appendChild(component.getMainElement()); } } } } public getMaxOptimizedButtonWidth(): number { return this.buttons .filter(button => button.visible) .reduce((maxWidth, button) => Math.max(maxWidth, button.optimizedWidth), 0); } public setEnforcedButtonWidth(enforcedButtonWidth: number) { this.enforcedButtonWidth = enforcedButtonWidth; this.updateRows(); } public setButtonVisible(buttonId: string, visible: boolean) { const button = this.buttonsById[buttonId]; if (button) { button.visible = visible; this.updateVisibility(); this.updateRows(); } } public addButton(buttonConfig: UiToolbarButtonConfig, neighborButtonId?: string, beforeNeighbor?: boolean) { const button = this.createButton(buttonConfig); const existingButton = this.buttonsById[buttonConfig.buttonId]; if (existingButton) { this.removeButton(buttonConfig.buttonId); } this.buttonsById[buttonConfig.buttonId] = button; const neighborButton = this.buttonsById[neighborButtonId]; if (neighborButton) { let neighborButtonIndex = this.buttons.indexOf(neighborButton); if (beforeNeighbor) { this.buttons.splice(neighborButtonIndex, 0, button); } else { this.buttons.splice(neighborButtonIndex + 1, 0, button); } } else { this.buttons.push(button); } this.updateVisibility(); this.updateRows(); } public removeButton(buttonId: string): void { const button = this.buttonsById[buttonId]; if (button) { delete this.buttonsById[buttonId]; this.buttons = this.buttons.filter(b => b.id !== buttonId); button.getMainDomElement().remove(); } this.updateVisibility(); this.updateRows(); } public updateRows() { let availableWidth = this.$buttonGroupWrapper.offsetWidth; if (availableWidth == 0) { return; } this.$buttonRows.forEach($row => { $row.remove(); $row.innerHTML = ''; }); let buttonsPerRow = Math.floor(availableWidth / Math.max(16, this.enforcedButtonWidth)); if (buttonsPerRow === 0) { buttonsPerRow = 1; } let visibleButtonsCount = 0; for (let i = 0; i < this.buttons.length; i++) { let button = this.buttons[i]; if (button.visible) { let rowIndex = Math.floor(visibleButtonsCount / buttonsPerRow); let $row = this.$buttonRows[rowIndex] || (this.$buttonRows[rowIndex] = parseHtml(`<div class="button-row">`)); button.getMainDomElement().style.flexBasis = this.enforcedButtonWidth + "px"; $row.appendChild(button.getMainDomElement()); visibleButtonsCount++; } } // fill with dummy elements for (let i = visibleButtonsCount; i % buttonsPerRow != 0; i++) { let rowIndex = Math.floor(i / buttonsPerRow); let $row = this.$buttonRows[rowIndex]; $row.appendChild(parseHtml(`<div class="row-filler" style="flex-basis: ${this.enforcedButtonWidth}px">`)); } this.$buttonRows.forEach($row => { if ($row.children.length > 0) { this.$buttonGroup.appendChild($row); } }); } public setVisible(visible: boolean) { this.visible = visible; this.updateVisibility(); } public isVisible() { return this.visible; } private updateVisibility() { let hasVisibleButton = this.buttons.some(b => b.visible); this.$buttonGroupWrapper.classList.toggle("hidden", !(this.visible && hasVisibleButton)); } public getMainDomElement(): HTMLElement { return this.$buttonGroupWrapper; } public onResize(): void { this.updateRows(); this.buttons.forEach(b => { if (b.$dropDown) { this.insertDropdownUnderButtonRow(b); } }) } setButtonColors(buttonId: string, backgroundColor: string, hoverBackgroundColor: string) { this.buttons.filter(b => b.id === buttonId)[0].setColors(backgroundColor, hoverBackgroundColor); } } TeamAppsUiComponentRegistry.registerComponentClass("UiToolAccordion", UiToolAccordion);
import {expect} from "chai"; import proxyquire = require("proxyquire"); import {execVim} from "../src/exec_vim"; import {VimHelp, RTPProvider} from "../src/vimhelp"; let execVimStub = execVim; const VimHelpProxied = proxyquire("../src/vimhelp", { "./exec_vim": { execVim: (vimBin: string, commands: string[]) => execVimStub(vimBin, commands), } }).VimHelp as typeof VimHelp; process.on("unhandledRejection", (reason) => { console.log(reason); }); describe("vimhelp", () => { describe("VimHelp", () => { let vimhelp: VimHelp; beforeEach(() => { vimhelp = new VimHelpProxied(); }); describe(".search()", () => { function hijackExecVim() { before(() => { execVimStub = async (_vimBin, commands) => commands.join("\n"); }); after(() => { execVimStub = execVim; }); } it("returns Promise object", () => { expect(vimhelp.search("help")).to.be.instanceof(Promise); }); describe("the result", () => { // XXX: These test may fail when Vim's help will be updated. it("is a text from Vim's help", async () => { const helpText = await vimhelp.search("help"); expect(helpText).to.include("*help*"); }); it("keeps the whitespaces of head", async () => { const helpText = await vimhelp.search("G"); expect(helpText).to.match(/^\s/); }); it("doesn't have the blank chars in tail", async () => { const helpText = await vimhelp.search("G"); expect(helpText).to.not.match(/\n$/); }); it("contains a range of before of a next tag from a tag", async () => { const helpText = await vimhelp.search("CTRL-J"); const lines = helpText.split("\n"); expect(lines).to.have.lengthOf(5); expect(lines[0]).to.include("*j*"); }); it("can treat a tag at the head of file", async () => { const helpText = await vimhelp.search("helphelp.txt"); expect(helpText).to.include("*helphelp.txt*"); }); it("does not contain separator", async () => { const helpText = await vimhelp.search("o_CTRL-V"); expect(helpText).to.not.include("==="); }); it("can separate section when the line ends with >", async () => { const helpText = await vimhelp.search("E32"); expect(helpText).to.include("E32"); expect(helpText).to.not.include("E141"); }); it("can handle a tag that is placed to head of line", async () => { const helpText = await vimhelp.search("[:alpha:]"); const lines = helpText.split("\n"); expect(lines).to.have.lengthOf(1); expect(helpText).to.include("[:alpha:]"); expect(helpText).to.not.include("[:blank:]"); }); }); it("removes extra commands", async () => { const helpText = await vimhelp.search("help\nenew\nput ='abc'\np\nqall!"); expect(helpText).to.include("*help*"); }); it("can not execute extra commands by |", async () => { try { await vimhelp.search("help|enew"); } catch (error) { expect(error).to.have.property("errorText") .that.to.match(/^E149:.*helpbarenew/); return; } expect.fail(); }); context("when the help does not exist", () => { it("throws error", async () => { try { await vimhelp.search("never-never-exist-help"); } catch (error) { expect(error.errorText).to.match(/^E149:/); return; } expect.fail(); }); }); context("when rtp provider is set", () => { hijackExecVim(); beforeEach(() => { vimhelp.setRTPProvider(() => ["/path/to/plugin"]); }); it("is set rtp from provider", async () => { const commands = await vimhelp.search("word"); expect(commands).to.include("set runtimepath+=/path/to/plugin"); }); }); context("when helplang is set", () => { hijackExecVim(); beforeEach(() => { vimhelp.helplang = ["ja", "en"]; }); it("sets 'helplang' options", async () => { const commands = await vimhelp.search("word"); expect(commands).to.include("set helplang=ja,en"); }); }); }); describe(".setRTPProvider()", () => { let provider: RTPProvider; beforeEach(() => { provider = () => ["/path/to/plugin"]; }); it("sets a rtp provider", () => { vimhelp.setRTPProvider(provider); expect(vimhelp.rtpProvider).to.eql(provider); }); }); }); });
import matplotlib.pyplot as plt def plot_maxmass_histogram(maxmass_after): plt.hist(maxmass_after, bins=50, alpha=0.5, label='after', histtype='step') plt.legend(loc='best') plt.show() maxmass_after = [56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94] plot_maxmass_histogram(maxmass_after)
<reponame>piglovesyou/react-apollo-loader-example /** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import useStyles from 'isomorphic-style-loader/useStyles'; import s from './Login.css'; type PropTypes = { title: string; }; const Login = (props: PropTypes) => { useStyles(s); return ( <div className={s.root}> <div className={s.container}> <h1>{props.title}</h1> <p className={s.lead}> Log in with your username or company email address. </p> <div className={s.formGroup}> <a className={s.facebook} href="/login/facebook"> <svg className={s.icon} width="30" height="30" viewBox="0 0 30 30" xmlns="http://www.w3.org/2000/svg" > <path d="M22 16l1-5h-5V7c0-1.544.784-2 3-2h2V0h-4c-4.072 0-7 2.435-7 7v4H7v5h5v14h6V16h4z" /> </svg> <span>Log in with Facebook</span> </a> </div> <div className={s.formGroup}> <a className={s.google} href="/login/google"> <svg className={s.icon} width="30" height="30" viewBox="0 0 30 30" xmlns="http://www.w3.org/2000/svg" > <path d={ 'M30 13h-4V9h-2v4h-4v2h4v4h2v-4h4m-15 2s-2-1.15-2-2c0 0-.5-1.828 1-3 ' + '1.537-1.2 3-3.035 3-5 0-2.336-1.046-5-3-6h3l2.387-1H10C5.835 0 2 3.345 2 7c0 ' + '3.735 2.85 6.56 7.086 6.56.295 0 .58-.006.86-.025-.273.526-.47 1.12-.47 1.735 ' + '0 1.037.817 2.042 1.523 2.73H9c-5.16 0-9 2.593-9 6 0 3.355 4.87 6 10.03 6 5.882 ' + '0 9.97-3 9.97-7 0-2.69-2.545-4.264-5-6zm-4-4c-2.395 0-5.587-2.857-6-6C4.587 ' + '3.856 6.607.93 9 1c2.394.07 4.603 2.908 5.017 6.052C14.43 10.195 13 13 11 ' + '13zm-1 15c-3.566 0-7-1.29-7-4 0-2.658 3.434-5.038 7-5 .832.01 2 0 2 0 1 0 ' + '2.88.88 4 2 1 1 1 2.674 1 3 0 3-1.986 4-7 4z' } /> </svg> <span>Log in with Google</span> </a> </div> <div className={s.formGroup}> <a className={s.twitter} href="/login/twitter"> <svg className={s.icon} width="30" height="30" viewBox="0 0 30 30" xmlns="http://www.w3.org/2000/svg" > <path d={ 'M30 6.708c-1.105.49-2.756 1.143-4 1.292 1.273-.762 2.54-2.56 ' + '3-4-.97.577-2.087 1.355-3.227 1.773L25 5c-1.12-1.197-2.23-2-4-2-3.398 0-6 ' + '2.602-6 6 0 .4.047.7.11.956L15 10C9 10 5.034 8.724 2 5c-.53.908-1 1.872-1 ' + '3 0 2.136 1.348 3.894 3 5-1.01-.033-2.17-.542-3-1 0 2.98 4.186 6.432 7 7-1 ' + '1-4.623.074-5 0 .784 2.447 3.31 3.95 6 4-2.105 1.648-4.647 2.51-7.53 2.51-.5 ' + '0-.988-.03-1.47-.084C2.723 27.17 6.523 28 10 28c11.322 0 17-8.867 17-17 ' + '0-.268.008-.736 0-1 1.2-.868 2.172-2.058 3-3.292z' } /> </svg> <span>Log in with Twitter</span> </a> </div> <strong className={s.lineThrough}>OR</strong> <form method="post"> <div className={s.formGroup}> <label className={s.label} htmlFor="usernameOrEmail"> Username or email address: <input className={s.input} id="usernameOrEmail" type="text" name="usernameOrEmail" autoFocus // eslint-disable-line jsx-a11y/no-autofocus /> </label> </div> <div className={s.formGroup}> <label className={s.label} htmlFor="password"> Password: <input className={s.input} id="password" type="password" name="password" /> </label> </div> <div className={s.formGroup}> <button className={s.button} type="submit"> Log in </button> </div> </form> </div> </div> ); }; export default Login;
#! /bin/bash gcc client.c network.c -o client
#include <Windows.h> #include <wrl.h> #include <windows.ui.notifications.h> #include <windows.data.xml.dom.h> using namespace Windows::UI::Notifications; using namespace Windows::Data::Xml::Dom; using namespace Microsoft::WRL; class NotificationManager { public: void showToastNotification(const std::wstring& message) { ComPtr<IToastNotifier> notifier; ToastNotificationManager::CreateToastNotifier(&notifier); ComPtr<IXmlDocument> toastXml; hstring xml = L"<toast><visual><binding template='ToastText01'><text id='1'>" + message + L"</text></binding></visual></toast>"; HRESULT hr = Windows::Data::Xml::Dom::XmlDocument::LoadFromXml(xml, &toastXml); if (SUCCEEDED(hr)) { ToastNotification toast(toastXml.Get()); notifier->Show(toast.Get()); } } void showToastNotificationWithAction(const std::wstring& message, const std::wstring& action) { ComPtr<IToastNotifier> notifier; ToastNotificationManager::CreateToastNotifier(&notifier); ComPtr<IXmlDocument> toastXml; hstring xml = L"<toast><visual><binding template='ToastText01'><text id='1'>" + message + L"</text></binding></visual><actions><action content='" + action + L"' arguments='" + action + L"'/></actions></toast>"; HRESULT hr = Windows::Data::Xml::Dom::XmlDocument::LoadFromXml(xml, &toastXml); if (SUCCEEDED(hr)) { ToastNotification toast(toastXml.Get()); notifier->Show(toast.Get()); } } };
<filename>fw/H263SlaveFirmwareCBR_bin.h // This file was automatically generated from ../release/H263SlaveFirmwareCBR.dnl using dnl2c. extern unsigned long aui32H263CBR_SlaveMTXTOPAZFWText[]; extern unsigned long ui32H263CBR_SlaveMTXTOPAZFWTextSize; extern unsigned long aui32H263CBR_SlaveMTXTOPAZFWData[]; extern unsigned long ui32H263CBR_SlaveMTXTOPAZFWDataSize; extern unsigned long aui32H263CBR_SlaveMTXTOPAZFWTextReloc[]; extern unsigned char aui8H263CBR_SlaveMTXTOPAZFWTextRelocType[]; extern unsigned long aui32H263CBR_SlaveMTXTOPAZFWTextRelocFullAddr[]; extern unsigned long aui32H263CBR_SlaveMTXTOPAZFWDataReloc[]; extern unsigned long ui32H263CBR_SlaveMTXTOPAZFWDataRelocSize; extern unsigned long ui32H263CBR_SlaveMTXTOPAZFWTextOrigin; extern unsigned long ui32H263CBR_SlaveMTXTOPAZFWDataOrigin;
<gh_stars>0 /*- * ========================LICENSE_START================================= * O-RAN-SC * %% * Copyright (C) 2020 Nordix 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. * ========================LICENSE_END=================================== */ package org.oransc.enrichment; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertTrue; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParser; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.lang.invoke.MethodHandles; import java.util.ArrayList; import java.util.Collection; import org.json.JSONObject; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.oransc.enrichment.clients.AsyncRestClient; import org.oransc.enrichment.clients.AsyncRestClientFactory; import org.oransc.enrichment.configuration.ApplicationConfig; import org.oransc.enrichment.configuration.ImmutableWebClientConfig; import org.oransc.enrichment.configuration.WebClientConfig; import org.oransc.enrichment.controller.ConsumerSimulatorController; import org.oransc.enrichment.controller.ProducerSimulatorController; import org.oransc.enrichment.controllers.consumer.ConsumerConsts; import org.oransc.enrichment.controllers.consumer.ConsumerEiJobInfo; import org.oransc.enrichment.controllers.consumer.ConsumerEiJobStatus; import org.oransc.enrichment.controllers.consumer.ConsumerEiTypeInfo; import org.oransc.enrichment.controllers.producer.ProducerConsts; import org.oransc.enrichment.controllers.producer.ProducerJobInfo; import org.oransc.enrichment.controllers.producer.ProducerRegistrationInfo; import org.oransc.enrichment.controllers.producer.ProducerRegistrationInfo.ProducerEiTypeRegistrationInfo; import org.oransc.enrichment.controllers.producer.ProducerStatusInfo; import org.oransc.enrichment.exceptions.ServiceException; import org.oransc.enrichment.repository.EiJob; import org.oransc.enrichment.repository.EiJobs; import org.oransc.enrichment.repository.EiProducers; import org.oransc.enrichment.repository.EiType; import org.oransc.enrichment.repository.EiTypes; import org.oransc.enrichment.tasks.ProducerSupervision; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.boot.web.servlet.server.ServletWebServerFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.web.reactive.function.client.WebClientResponseException; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; @ExtendWith(SpringExtension.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) @TestPropertySource( properties = { // "server.ssl.key-store=./config/keystore.jks", // "app.webclient.trust-store=./config/truststore.jks", // "app.vardata-directory=./target"}) class ApplicationTest { private final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private final String EI_TYPE_ID = "typeId"; private final String EI_PRODUCER_ID = "producerId"; private final String EI_JOB_PROPERTY = "\"property1\""; private final String EI_JOB_ID = "jobId"; @Autowired ApplicationContext context; @Autowired EiJobs eiJobs; @Autowired EiTypes eiTypes; @Autowired EiProducers eiProducers; @Autowired ApplicationConfig applicationConfig; @Autowired ProducerSimulatorController producerSimulator; @Autowired ConsumerSimulatorController consumerSimulator; @Autowired ProducerSupervision producerSupervision; private static Gson gson = new GsonBuilder().create(); /** * Overrides the BeanFactory. */ @TestConfiguration static class TestBeanFactory { @Bean public ServletWebServerFactory servletContainer() { return new TomcatServletWebServerFactory(); } } @LocalServerPort private int port; @BeforeEach void reset() { this.eiJobs.clear(); this.eiTypes.clear(); this.eiProducers.clear(); this.producerSimulator.getTestResults().reset(); this.consumerSimulator.getTestResults().reset(); } @AfterEach void check() { assertThat(this.producerSimulator.getTestResults().errorFound).isFalse(); } @Test void createApiDoc() throws FileNotFoundException { String url = "/v2/api-docs"; ResponseEntity<String> resp = restClient().getForEntity(url).block(); assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK); String indented = (new JSONObject(resp.getBody())).toString(4); try (PrintStream out = new PrintStream(new FileOutputStream("../docs/offeredapis/swagger/ecs-api.json"))) { out.print(indented); } } @Test void testGetEiTypes() throws Exception { putEiProducerWithOneType(EI_PRODUCER_ID, "test"); String url = ConsumerConsts.API_ROOT + "/eitypes"; String rsp = restClient().get(url).block(); assertThat(rsp).isEqualTo("[\"test\"]"); } @Test void testGetEiTypesEmpty() throws Exception { String url = ConsumerConsts.API_ROOT + "/eitypes"; String rsp = restClient().get(url).block(); assertThat(rsp).isEqualTo("[]"); } @Test void testGetEiType() throws Exception { putEiProducerWithOneType(EI_PRODUCER_ID, "test"); String url = ConsumerConsts.API_ROOT + "/eitypes/test"; String rsp = restClient().get(url).block(); ConsumerEiTypeInfo info = gson.fromJson(rsp, ConsumerEiTypeInfo.class); assertThat(info).isNotNull(); } @Test void testGetEiTypeNotFound() throws Exception { String url = ConsumerConsts.API_ROOT + "/eitypes/junk"; testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND, "Could not find EI type: junk"); } @Test void testGetEiJobsIds() throws Exception { putEiProducerWithOneType(EI_PRODUCER_ID, EI_TYPE_ID); putEiJob(EI_TYPE_ID, "jobId"); final String JOB_ID_JSON = "[\"jobId\"]"; String url = ConsumerConsts.API_ROOT + "/eijobs?eiTypeId=typeId"; String rsp = restClient().get(url).block(); assertThat(rsp).isEqualTo(JOB_ID_JSON); url = ConsumerConsts.API_ROOT + "/eijobs?owner=owner"; rsp = restClient().get(url).block(); assertThat(rsp).isEqualTo(JOB_ID_JSON); url = ConsumerConsts.API_ROOT + "/eijobs?owner=JUNK"; rsp = restClient().get(url).block(); assertThat(rsp).isEqualTo("[]"); url = ConsumerConsts.API_ROOT + "/eijobs"; rsp = restClient().get(url).block(); assertThat(rsp).isEqualTo(JOB_ID_JSON); url = ConsumerConsts.API_ROOT + "/eijobs?eiTypeId=typeId&&owner=owner"; rsp = restClient().get(url).block(); assertThat(rsp).isEqualTo(JOB_ID_JSON); url = ConsumerConsts.API_ROOT + "/eijobs?eiTypeId=JUNK"; rsp = restClient().get(url).block(); assertThat(rsp).isEqualTo("[]"); } @Test void testGetEiJob() throws Exception { putEiProducerWithOneType(EI_PRODUCER_ID, EI_TYPE_ID); putEiJob(EI_TYPE_ID, "jobId"); String url = ConsumerConsts.API_ROOT + "/eijobs/jobId"; String rsp = restClient().get(url).block(); ConsumerEiJobInfo info = gson.fromJson(rsp, ConsumerEiJobInfo.class); assertThat(info.owner).isEqualTo("owner"); assertThat(info.eiTypeId).isEqualTo(EI_TYPE_ID); } @Test void testGetEiJobNotFound() throws Exception { putEiProducerWithOneType(EI_PRODUCER_ID, EI_TYPE_ID); String url = ConsumerConsts.API_ROOT + "/eijobs/junk"; testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND, "Could not find EI job: junk"); } @Test void testGetEiJobStatus() throws Exception { putEiProducerWithOneType(EI_PRODUCER_ID, EI_TYPE_ID); putEiJob(EI_TYPE_ID, "jobId"); verifyJobStatus("jobId", "ENABLED"); } @Test void testDeleteEiJob() throws Exception { putEiProducerWithOneType(EI_PRODUCER_ID, EI_TYPE_ID); putEiJob(EI_TYPE_ID, "jobId"); assertThat(this.eiJobs.size()).isEqualTo(1); String url = ConsumerConsts.API_ROOT + "/eijobs/jobId"; restClient().delete(url).block(); assertThat(this.eiJobs.size()).isZero(); ProducerSimulatorController.TestResults simulatorResults = this.producerSimulator.getTestResults(); await().untilAsserted(() -> assertThat(simulatorResults.jobsStopped.size()).isEqualTo(1)); assertThat(simulatorResults.jobsStopped.get(0)).isEqualTo("jobId"); } @Test void testDeleteEiJobNotFound() throws Exception { putEiProducerWithOneType(EI_PRODUCER_ID, EI_TYPE_ID); String url = ConsumerConsts.API_ROOT + "/eijobs/junk"; testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND, "Could not find EI job: junk"); } @Test void testPutEiJob() throws Exception { // Test that one producer accepting a job is enough putEiProducerWithOneType(EI_PRODUCER_ID, EI_TYPE_ID); putEiProducerWithOneTypeRejecting("simulateProducerError", EI_TYPE_ID); String url = ConsumerConsts.API_ROOT + "/eijobs/jobId"; String body = gson.toJson(eiJobInfo()); ResponseEntity<String> resp = restClient().putForEntity(url, body).block(); assertThat(this.eiJobs.size()).isEqualTo(1); assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.CREATED); ProducerSimulatorController.TestResults simulatorResults = this.producerSimulator.getTestResults(); await().untilAsserted(() -> assertThat(simulatorResults.jobsStarted.size()).isEqualTo(1)); ProducerJobInfo request = simulatorResults.jobsStarted.get(0); assertThat(request.id).isEqualTo("jobId"); // One retry --> two calls await().untilAsserted(() -> assertThat(simulatorResults.noOfRejectedCreate).isEqualTo(2)); assertThat(simulatorResults.noOfRejectedCreate).isEqualTo(2); resp = restClient().putForEntity(url, body).block(); assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK); EiJob job = this.eiJobs.getJob("jobId"); assertThat(job.getOwner()).isEqualTo("owner"); } @Test void putEiProducerWithOneType_rejecting() throws JsonMappingException, JsonProcessingException, ServiceException { putEiProducerWithOneTypeRejecting("simulateProducerError", EI_TYPE_ID); String url = ConsumerConsts.API_ROOT + "/eijobs/jobId"; String body = gson.toJson(eiJobInfo()); testErrorCode(restClient().put(url, body), HttpStatus.CONFLICT, "Job not accepted by any producers"); ProducerSimulatorController.TestResults simulatorResults = this.producerSimulator.getTestResults(); // There is one retry -> 2 calls await().untilAsserted(() -> assertThat(simulatorResults.noOfRejectedCreate).isEqualTo(2)); assertThat(simulatorResults.noOfRejectedCreate).isEqualTo(2); } @Test void testPutEiJob_jsonSchemavalidationError() throws Exception { putEiProducerWithOneType(EI_PRODUCER_ID, EI_TYPE_ID); String url = ConsumerConsts.API_ROOT + "/eijobs/jobId"; // The element with name "property1" is mandatory in the schema ConsumerEiJobInfo jobInfo = new ConsumerEiJobInfo("typeId", jsonObject("{ \"XXstring\" : \"value\" }"), "owner", "targetUri", "jobStatusUrl"); String body = gson.toJson(jobInfo); testErrorCode(restClient().put(url, body), HttpStatus.CONFLICT, "Json validation failure"); } @Test void testGetEiProducerTypes() throws Exception { final String EI_TYPE_ID_2 = EI_TYPE_ID + "_2"; putEiProducerWithOneType("producer1", EI_TYPE_ID); putEiJob(EI_TYPE_ID, "jobId"); putEiProducerWithOneType("producer2", EI_TYPE_ID_2); putEiJob(EI_TYPE_ID_2, "jobId2"); String url = ProducerConsts.API_ROOT + "/eitypes"; ResponseEntity<String> resp = restClient().getForEntity(url).block(); assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(resp.getBody()).contains(EI_TYPE_ID); assertThat(resp.getBody()).contains(EI_TYPE_ID_2); } @Test void testReplacingEiProducerTypes() throws Exception { final String REPLACED_TYPE_ID = "replaced"; putEiProducerWithOneType(EI_PRODUCER_ID, REPLACED_TYPE_ID); putEiProducerWithOneType(EI_PRODUCER_ID, EI_TYPE_ID); String url = ProducerConsts.API_ROOT + "/eitypes"; ResponseEntity<String> resp = restClient().getForEntity(url).block(); assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(resp.getBody()).contains(EI_TYPE_ID); assertThat(resp.getBody()).doesNotContain(REPLACED_TYPE_ID); } @Test void testChangingEiTypeGetRejected() throws Exception { putEiProducerWithOneType("producer1", "typeId1"); putEiProducerWithOneType("producer2", "typeId2"); putEiJob("typeId1", "jobId"); String url = ConsumerConsts.API_ROOT + "/eijobs/jobId"; String body = gson.toJson(eiJobInfo("typeId2", "jobId")); testErrorCode(restClient().put(url, body), HttpStatus.CONFLICT, "Not allowed to change type for existing EI job"); } @Test void testPutEiProducer() throws Exception { String url = ProducerConsts.API_ROOT + "/eiproducers/eiProducerId"; String body = gson.toJson(producerEiRegistratioInfo(EI_TYPE_ID)); ResponseEntity<String> resp = restClient().putForEntity(url, body).block(); assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.CREATED); assertThat(this.eiTypes.size()).isEqualTo(1); EiType type = this.eiTypes.getType(EI_TYPE_ID); assertThat(type.getProducerIds()).contains("eiProducerId"); assertThat(this.eiProducers.size()).isEqualTo(1); assertThat(this.eiProducers.get("eiProducerId").getEiTypes().iterator().next().getId()).isEqualTo(EI_TYPE_ID); resp = restClient().putForEntity(url, body).block(); assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK); resp = restClient().getForEntity(url).block(); assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(resp.getBody()).isEqualTo(body); } @Test void testPutEiProducerExistingJob() throws Exception { putEiProducerWithOneType(EI_PRODUCER_ID, EI_TYPE_ID); putEiJob(EI_TYPE_ID, "jobId"); String url = ProducerConsts.API_ROOT + "/eiproducers/eiProducerId"; String body = gson.toJson(producerEiRegistratioInfo(EI_TYPE_ID)); restClient().putForEntity(url, body).block(); ProducerSimulatorController.TestResults simulatorResults = this.producerSimulator.getTestResults(); await().untilAsserted(() -> assertThat(simulatorResults.jobsStarted.size()).isEqualTo(2)); ProducerJobInfo request = simulatorResults.jobsStarted.get(0); assertThat(request.id).isEqualTo("jobId"); } @Test void testPutProducerAndEiJob() throws Exception { String url = ProducerConsts.API_ROOT + "/eiproducers/eiProducerId"; String body = gson.toJson(producerEiRegistratioInfo(EI_TYPE_ID)); restClient().putForEntity(url, body).block(); assertThat(this.eiTypes.size()).isEqualTo(1); this.eiTypes.getType(EI_TYPE_ID); url = ConsumerConsts.API_ROOT + "/eijobs/jobId"; body = gson.toJson(eiJobInfo()); restClient().putForEntity(url, body).block(); ProducerSimulatorController.TestResults simulatorResults = this.producerSimulator.getTestResults(); await().untilAsserted(() -> assertThat(simulatorResults.jobsStarted.size()).isEqualTo(1)); ProducerJobInfo request = simulatorResults.jobsStarted.get(0); assertThat(request.id).isEqualTo("jobId"); } @Test void testGetEiJobsForProducer() throws JsonMappingException, JsonProcessingException, ServiceException { putEiProducerWithOneType(EI_PRODUCER_ID, EI_TYPE_ID); putEiJob(EI_TYPE_ID, "jobId1"); putEiJob(EI_TYPE_ID, "jobId2"); // PUT a consumer String url = ProducerConsts.API_ROOT + "/eiproducers/eiProducerId"; String body = gson.toJson(producerEiRegistratioInfo(EI_TYPE_ID)); restClient().putForEntity(url, body).block(); url = ProducerConsts.API_ROOT + "/eiproducers/eiProducerId/eijobs"; ResponseEntity<String> resp = restClient().getForEntity(url).block(); assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK); ProducerJobInfo[] parsedResp = gson.fromJson(resp.getBody(), ProducerJobInfo[].class); assertThat(parsedResp[0].typeId).isEqualTo(EI_TYPE_ID); assertThat(parsedResp[1].typeId).isEqualTo(EI_TYPE_ID); } @Test void testDeleteEiProducer() throws Exception { putEiProducerWithOneType("eiProducerId", EI_TYPE_ID); putEiProducerWithOneType("eiProducerId2", EI_TYPE_ID); assertThat(this.eiProducers.size()).isEqualTo(2); EiType type = this.eiTypes.getType(EI_TYPE_ID); assertThat(type.getProducerIds()).contains("eiProducerId"); assertThat(type.getProducerIds()).contains("eiProducerId2"); putEiJob(EI_TYPE_ID, "jobId"); assertThat(this.eiJobs.size()).isEqualTo(1); deleteEiProducer("eiProducerId"); assertThat(this.eiProducers.size()).isEqualTo(1); assertThat(this.eiTypes.getType(EI_TYPE_ID).getProducerIds()).doesNotContain("eiProducerId"); verifyJobStatus("jobId", "ENABLED"); deleteEiProducer("eiProducerId2"); assertThat(this.eiProducers.size()).isZero(); assertThat(this.eiTypes.size()).isZero(); verifyJobStatus("jobId", "DISABLED"); } @Test void testJobStatusNotifications() throws JsonMappingException, JsonProcessingException, ServiceException { ConsumerSimulatorController.TestResults consumerCalls = this.consumerSimulator.getTestResults(); ProducerSimulatorController.TestResults producerCalls = this.producerSimulator.getTestResults(); putEiProducerWithOneType("eiProducerId", EI_TYPE_ID); putEiJob(EI_TYPE_ID, "jobId"); putEiProducerWithOneType("eiProducerId2", EI_TYPE_ID); await().untilAsserted(() -> assertThat(producerCalls.jobsStarted.size()).isEqualTo(2)); deleteEiProducer("eiProducerId2"); assertThat(this.eiTypes.size()).isEqualTo(1); // The type remains, one producer left deleteEiProducer("eiProducerId"); assertThat(this.eiTypes.size()).isZero(); // The type is gone assertThat(this.eiJobs.size()).isEqualTo(1); // The job remains await().untilAsserted(() -> assertThat(consumerCalls.status.size()).isEqualTo(1)); assertThat(consumerCalls.status.get(0).state).isEqualTo(ConsumerEiJobStatus.EiJobStatusValues.DISABLED); putEiProducerWithOneType("eiProducerId", EI_TYPE_ID); await().untilAsserted(() -> assertThat(consumerCalls.status.size()).isEqualTo(2)); assertThat(consumerCalls.status.get(1).state).isEqualTo(ConsumerEiJobStatus.EiJobStatusValues.ENABLED); } @Test void testJobStatusNotifications2() throws JsonMappingException, JsonProcessingException, ServiceException { // Test replacing a producer with new and removed types // Create a job putEiProducerWithOneType(EI_PRODUCER_ID, EI_TYPE_ID); putEiJob(EI_TYPE_ID, EI_JOB_ID); // change the type for the producer, the EI_TYPE_ID is deleted putEiProducerWithOneType(EI_PRODUCER_ID, "junk"); verifyJobStatus(EI_JOB_ID, "DISABLED"); ConsumerSimulatorController.TestResults consumerCalls = this.consumerSimulator.getTestResults(); await().untilAsserted(() -> assertThat(consumerCalls.status.size()).isEqualTo(1)); assertThat(consumerCalls.status.get(0).state).isEqualTo(ConsumerEiJobStatus.EiJobStatusValues.DISABLED); putEiProducerWithOneType(EI_PRODUCER_ID, EI_TYPE_ID); verifyJobStatus(EI_JOB_ID, "ENABLED"); await().untilAsserted(() -> assertThat(consumerCalls.status.size()).isEqualTo(2)); assertThat(consumerCalls.status.get(1).state).isEqualTo(ConsumerEiJobStatus.EiJobStatusValues.ENABLED); } @Test void testGetProducerEiType() throws JsonMappingException, JsonProcessingException, ServiceException { putEiProducerWithOneType(EI_PRODUCER_ID, EI_TYPE_ID); String url = ProducerConsts.API_ROOT + "/eitypes/" + EI_TYPE_ID; ResponseEntity<String> resp = restClient().getForEntity(url).block(); assertThat(resp.getBody()).contains(EI_PRODUCER_ID); } @Test void testGetProducerIdentifiers() throws JsonMappingException, JsonProcessingException, ServiceException { putEiProducerWithOneType(EI_PRODUCER_ID, EI_TYPE_ID); String url = ProducerConsts.API_ROOT + "/eiproducers"; ResponseEntity<String> resp = restClient().getForEntity(url).block(); assertThat(resp.getBody()).contains(EI_PRODUCER_ID); } @Test void testProducerSupervision() throws JsonMappingException, JsonProcessingException, ServiceException { putEiProducerWithOneTypeRejecting("simulateProducerError", EI_TYPE_ID); { // Create a job putEiProducerWithOneType(EI_PRODUCER_ID, EI_TYPE_ID); putEiJob(EI_TYPE_ID, EI_JOB_ID); deleteEiProducer(EI_PRODUCER_ID); } assertThat(this.eiProducers.size()).isEqualTo(1); assertThat(this.eiTypes.size()).isEqualTo(1); assertProducerOpState("simulateProducerError", ProducerStatusInfo.OperationalState.ENABLED); this.producerSupervision.createTask().blockLast(); this.producerSupervision.createTask().blockLast(); // Now we have one producer that is disabled, but the job will be enabled until // the producer/type is removed assertThat(this.eiProducers.size()).isEqualTo(1); assertProducerOpState("simulateProducerError", ProducerStatusInfo.OperationalState.DISABLED); verifyJobStatus(EI_JOB_ID, "ENABLED"); // After 3 failed checks, the producer and the type shall be deregisterred this.producerSupervision.createTask().blockLast(); assertThat(this.eiProducers.size()).isEqualTo(0); assertThat(this.eiTypes.size()).isEqualTo(0); verifyJobStatus(EI_JOB_ID, "DISABLED"); // Job disabled status notification shall be received ConsumerSimulatorController.TestResults consumerResults = this.consumerSimulator.getTestResults(); await().untilAsserted(() -> assertThat(consumerResults.status.size()).isEqualTo(1)); assertThat(consumerResults.status.get(0).state).isEqualTo(ConsumerEiJobStatus.EiJobStatusValues.DISABLED); } @Test void testGetStatus() throws JsonMappingException, JsonProcessingException, ServiceException { putEiProducerWithOneTypeRejecting("simulateProducerError", EI_TYPE_ID); putEiProducerWithOneTypeRejecting("simulateProducerError2", EI_TYPE_ID); String url = "/status"; ResponseEntity<String> resp = restClient().getForEntity(url).block(); assertThat(resp.getBody()).contains("hunky dory"); } @Test void testEiJobDatabase() throws Exception { putEiProducerWithOneType(EI_PRODUCER_ID, EI_TYPE_ID); putEiJob(EI_TYPE_ID, "jobId1"); putEiJob(EI_TYPE_ID, "jobId2"); assertThat(this.eiJobs.size()).isEqualTo(2); { // Restore the jobs EiJobs jobs = new EiJobs(this.applicationConfig); jobs.restoreJobsFromDatabase(); assertThat(jobs.size()).isEqualTo(2); jobs.remove("jobId1"); jobs.remove("jobId2"); } { // Restore the jobs, no jobs in database EiJobs jobs = new EiJobs(this.applicationConfig); jobs.restoreJobsFromDatabase(); assertThat(jobs.size()).isEqualTo(0); } logger.warn("Test removing a job when the db file is gone"); this.eiJobs.remove("jobId1"); assertThat(this.eiJobs.size()).isEqualTo(1); } private void deleteEiProducer(String eiProducerId) { String url = ProducerConsts.API_ROOT + "/eiproducers/" + eiProducerId; restClient().deleteForEntity(url).block(); } private void verifyJobStatus(String jobId, String expStatus) { String url = ConsumerConsts.API_ROOT + "/eijobs/" + jobId + "/status"; String rsp = restClient().get(url).block(); assertThat(rsp).contains(expStatus); } private void assertProducerOpState(String producerId, ProducerStatusInfo.OperationalState expectedOperationalState) { String statusUrl = ProducerConsts.API_ROOT + "/eiproducers/" + producerId + "/status"; ResponseEntity<String> resp = restClient().getForEntity(statusUrl).block(); ProducerStatusInfo statusInfo = gson.fromJson(resp.getBody(), ProducerStatusInfo.class); assertThat(statusInfo.opState).isEqualTo(expectedOperationalState); } ProducerEiTypeRegistrationInfo producerEiTypeRegistrationInfo(String typeId) throws JsonMappingException, JsonProcessingException { return new ProducerEiTypeRegistrationInfo(jsonSchemaObject(), typeId); } ProducerRegistrationInfo producerEiRegistratioInfoRejecting(String typeId) throws JsonMappingException, JsonProcessingException { Collection<ProducerEiTypeRegistrationInfo> types = new ArrayList<>(); types.add(producerEiTypeRegistrationInfo(typeId)); return new ProducerRegistrationInfo(types, // baseUrl() + ProducerSimulatorController.JOB_ERROR_URL, baseUrl() + ProducerSimulatorController.SUPERVISION_ERROR_URL); } ProducerRegistrationInfo producerEiRegistratioInfo(String typeId) throws JsonMappingException, JsonProcessingException { Collection<ProducerEiTypeRegistrationInfo> types = new ArrayList<>(); types.add(producerEiTypeRegistrationInfo(typeId)); return new ProducerRegistrationInfo(types, // baseUrl() + ProducerSimulatorController.JOB_URL, baseUrl() + ProducerSimulatorController.SUPERVISION_URL); } private ConsumerEiJobInfo eiJobInfo() throws JsonMappingException, JsonProcessingException { return eiJobInfo(EI_TYPE_ID, EI_JOB_ID); } ConsumerEiJobInfo eiJobInfo(String typeId, String eiJobId) throws JsonMappingException, JsonProcessingException { return new ConsumerEiJobInfo(typeId, jsonObject(), "owner", "targetUri", baseUrl() + ConsumerSimulatorController.getJobStatusUrl(eiJobId)); } private Object jsonObject(String json) { try { return JsonParser.parseString(json).getAsJsonObject(); } catch (Exception e) { throw new NullPointerException(e.toString()); } } private Object jsonSchemaObject() { // a json schema with one mandatory property named "string" String schemaStr = "{" // + "\"$schema\": \"http://json-schema.org/draft-04/schema#\"," // + "\"type\": \"object\"," // + "\"properties\": {" // + EI_JOB_PROPERTY + " : {" // + " \"type\": \"string\"" // + " }" // + "}," // + "\"required\": [" // + EI_JOB_PROPERTY // + "]" // + "}"; // return jsonObject(schemaStr); } private Object jsonObject() { return jsonObject("{ " + EI_JOB_PROPERTY + " : \"value\" }"); } private EiJob putEiJob(String eiTypeId, String jobId) throws JsonMappingException, JsonProcessingException, ServiceException { String url = ConsumerConsts.API_ROOT + "/eijobs/" + jobId; String body = gson.toJson(eiJobInfo(eiTypeId, jobId)); restClient().putForEntity(url, body).block(); return this.eiJobs.getJob(jobId); } private EiType putEiProducerWithOneTypeRejecting(String producerId, String eiTypeId) throws JsonMappingException, JsonProcessingException, ServiceException { String url = ProducerConsts.API_ROOT + "/eiproducers/" + producerId; String body = gson.toJson(producerEiRegistratioInfoRejecting(eiTypeId)); restClient().putForEntity(url, body).block(); return this.eiTypes.getType(eiTypeId); } private EiType putEiProducerWithOneType(String producerId, String eiTypeId) throws JsonMappingException, JsonProcessingException, ServiceException { String url = ProducerConsts.API_ROOT + "/eiproducers/" + producerId; String body = gson.toJson(producerEiRegistratioInfo(eiTypeId)); restClient().putForEntity(url, body).block(); return this.eiTypes.getType(eiTypeId); } private String baseUrl() { return "https://localhost:" + this.port; } private AsyncRestClient restClient(boolean useTrustValidation) { WebClientConfig config = this.applicationConfig.getWebClientConfig(); config = ImmutableWebClientConfig.builder() // .keyStoreType(config.keyStoreType()) // .keyStorePassword(config.keyStorePassword()) // .keyStore(config.keyStore()) // .keyPassword(config.keyPassword()) // .isTrustStoreUsed(useTrustValidation) // .trustStore(config.trustStore()) // .trustStorePassword(config.trustStorePassword()) // .build(); AsyncRestClientFactory restClientFactory = new AsyncRestClientFactory(config); return restClientFactory.createRestClient(baseUrl()); } private AsyncRestClient restClient() { return restClient(false); } private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains) { testErrorCode(request, expStatus, responseContains, true); } private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains, boolean expectApplicationProblemJsonMediaType) { StepVerifier.create(request) // .expectSubscription() // .expectErrorMatches( t -> checkWebClientError(t, expStatus, responseContains, expectApplicationProblemJsonMediaType)) // .verify(); } private boolean checkWebClientError(Throwable throwable, HttpStatus expStatus, String responseContains, boolean expectApplicationProblemJsonMediaType) { assertTrue(throwable instanceof WebClientResponseException); WebClientResponseException responseException = (WebClientResponseException) throwable; assertThat(responseException.getStatusCode()).isEqualTo(expStatus); assertThat(responseException.getResponseBodyAsString()).contains(responseContains); if (expectApplicationProblemJsonMediaType) { assertThat(responseException.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_PROBLEM_JSON); } return true; } }
// Define the protocol protocol CollectionViewProtocol { var indexTitle: String? { get } var header: CollectionItemType? { get set } var footer: CollectionItemType? { get set } } // Implement the class conforming to the protocol class CustomCollectionView: CollectionViewProtocol { var indexTitle: String? var header: CollectionItemType? var footer: CollectionItemType? // Implement any additional functionality or initialization as needed }
#!/usr/bin/env bash # # Copyright (c) .NET Foundation and contributors. All rights reserved. # Licensed under the MIT license. See LICENSE file in the project root for full license information. # Debian Packaging Script # Currently Intended to build on ubuntu14.04 set -e SOURCE="${BASH_SOURCE[0]}" while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" SOURCE="$(readlink "$SOURCE")" [[ "$SOURCE" != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located done DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" source "$DIR/../common/_common.sh" REPOROOT="$DIR/../.." help(){ echo "Usage: $0" echo "" echo "Options:" echo " --input <input directory> Package the entire contents of the directory tree." echo " --output <output debfile> The full path to which the package will be written." echo " --package-name <package name> Package to identify during installation. Example - 'dotnet-sharedframework'" echo " --framework-nuget-name <name> The name of the nuget package that produced this shared framework." echo " --framework-nuget-version <ver> The versionf of the nuget package that produced this shared framework." echo " --obj-root <object root> Root folder for intermediate objects." echo " --version <version> Version for the debain package." exit 1 } while [[ $# > 0 ]]; do lowerI="$(echo $1 | awk '{print tolower($0)}')" case $lowerI in -o|--output) OUTPUT_DEBIAN_FILE=$2 shift ;; -i|--input) REPO_BINARIES_DIR=$2 shift ;; -p|--package-name) SHARED_FRAMEWORK_DEBIAN_PACKAGE_NAME=$2 shift ;; --framework-nuget-name) SHARED_FRAMEWORK_NUGET_NAME=$2 shift ;; --framework-nuget-version) SHARED_FRAMEWORK_NUGET_VERSION=$2 shift ;; --obj-root) OBJECT_DIR=$2 shift ;; --version) SHARED_FRAMEWORK_DEBIAN_VERSION=$2 shift ;; --help) help ;; *) break ;; esac shift done PACKAGING_ROOT="$REPOROOT/packaging/sharedframework/debian" PACKAGING_TOOL_DIR="$REPOROOT/tools/DebianPackageTool" PACKAGE_OUTPUT_DIR="$OBJECT_DIR/deb_output" PACKAGE_LAYOUT_DIR="$OBJECT_DIR/deb_intermediate" TEST_STAGE_DIR="$OBJECT_DIR/debian_tests" execute_build(){ create_empty_debian_layout copy_files_to_debian_layout update_debian_json create_debian_package } create_empty_debian_layout(){ header "Creating empty debian package layout" rm -rf "$PACKAGE_LAYOUT_DIR" mkdir -p "$PACKAGE_LAYOUT_DIR" mkdir "$PACKAGE_LAYOUT_DIR/\$" mkdir "$PACKAGE_LAYOUT_DIR/package_root" mkdir "$PACKAGE_LAYOUT_DIR/samples" mkdir "$PACKAGE_LAYOUT_DIR/docs" } copy_files_to_debian_layout(){ header "Copying files to debian layout" # Copy Built Binaries cp -a "$REPO_BINARIES_DIR/." "$PACKAGE_LAYOUT_DIR/package_root" # Copy config file cp "$PACKAGING_ROOT/dotnet-sharedframework-debian_config.json" "$PACKAGE_LAYOUT_DIR/debian_config.json" } create_debian_package(){ header "Packing .deb" mkdir -p "$PACKAGE_OUTPUT_DIR" "$PACKAGING_TOOL_DIR/package_tool" -i "$PACKAGE_LAYOUT_DIR" -o "$PACKAGE_OUTPUT_DIR" -n "$SHARED_FRAMEWORK_DEBIAN_PACKAGE_NAME" -v "$SHARED_FRAMEWORK_DEBIAN_VERSION" } update_debian_json() { header "Updating debian.json file" sed -i "s/%SHARED_FRAMEWORK_DEBIAN_PACKAGE_NAME%/$SHARED_FRAMEWORK_DEBIAN_PACKAGE_NAME/g" "$PACKAGE_LAYOUT_DIR"/debian_config.json sed -i "s/%SHARED_FRAMEWORK_NUGET_NAME%/$SHARED_FRAMEWORK_NUGET_NAME/g" "$PACKAGE_LAYOUT_DIR"/debian_config.json sed -i "s/%SHARED_FRAMEWORK_NUGET_VERSION%/$SHARED_FRAMEWORK_NUGET_VERSION/g" "$PACKAGE_LAYOUT_DIR"/debian_config.json } test_debian_package(){ header "Testing debian Shared Framework package" install_bats run_package_integrity_tests } install_bats() { rm -rf $TEST_STAGE_DIR git clone https://github.com/sstephenson/bats.git $TEST_STAGE_DIR } run_package_integrity_tests() { # Set LAST_VERSION_URL to enable upgrade tests # export LAST_VERSION_URL="$PREVIOUS_VERSION_URL" $TEST_STAGE_DIR/bin/bats $PACKAGE_OUTPUT_DIR/test_package.bats } execute_build DEBIAN_FILE=$(find $PACKAGE_OUTPUT_DIR -iname "*.deb") test_debian_package mv -f "$DEBIAN_FILE" "$OUTPUT_DEBIAN_FILE"
/*package com.codefinity.microcontinuum.common.serializer; import java.lang.reflect.Type; import java.util.Date; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; public class AbstractSerializer { private Gson gson; protected AbstractSerializer(boolean isCompact) { this(false, isCompact); } protected AbstractSerializer(boolean isPretty, boolean isCompact) { super(); if (isPretty && isCompact) { this.buildForPrettyCompact(); } else if (isCompact) { this.buildForCompact(); } else { this.build(); } } protected Gson gson() { return this.gson; } private void build() { this.gson = new GsonBuilder().registerTypeAdapter(Date.class, new DateSerializer()) .registerTypeAdapter(Date.class, new DateDeserializer()).serializeNulls().create(); } private void buildForCompact() { this.gson = new GsonBuilder().registerTypeAdapter(Date.class, new DateSerializer()) .registerTypeAdapter(Date.class, new DateDeserializer()).create(); } private void buildForPrettyCompact() { this.gson = new GsonBuilder().registerTypeAdapter(Date.class, new DateSerializer()) .registerTypeAdapter(Date.class, new DateDeserializer()).setPrettyPrinting().create(); } private class DateSerializer implements JsonSerializer<Date> { public JsonElement serialize(Date source, Type typeOfSource, JsonSerializationContext context) { return new JsonPrimitive(Long.toString(source.getTime())); } } private class DateDeserializer implements JsonDeserializer<Date> { public Date deserialize(JsonElement json, Type typeOfTarget, JsonDeserializationContext context) throws JsonParseException { long time = Long.parseLong(json.getAsJsonPrimitive().getAsString()); return new Date(time); } } } */
import Color from 'color'; function calculateAverageColor(colorLevels: ColorLevelsObject): Color { const colorValues = Object.values(colorLevels); const totalRed = colorValues.reduce((acc, color) => acc + color.red(), 0); const totalGreen = colorValues.reduce((acc, color) => acc + color.green(), 0); const totalBlue = colorValues.reduce((acc, color) => acc + color.blue(), 0); const averageRed = totalRed / colorValues.length; const averageGreen = totalGreen / colorValues.length; const averageBlue = totalBlue / colorValues.length; return Color.rgb(averageRed, averageGreen, averageBlue); }
import { DispatchW, State } from "../../shared/context"; import { Dispatch } from "react"; import { useState } from "react"; import CSS from "csstype"; const openStyles: CSS.Properties = { opacity: 1, visibility: "visible", }; const closedStyles: CSS.Properties = { opacity: 0, visibility: "hidden", }; type WalletDialogProps = { open: Boolean; setOpen: Dispatch<Boolean>; dispatch: DispatchW; state: State; }; const WalletDialog = ({ open, setOpen, dispatch, state, }: WalletDialogProps) => { const [wallet, setWallet] = useState<string>(""); const [message, setMessage] = useState<string>(""); function setTimeoutToClearMessage() { setTimeout(() => { setMessage(""); }, 4000); } function setTimeoutToCloseDialog() { setTimeout(() => { setOpen(!open); }, 4500); } return ( <div className="dialog" style={open ? openStyles : closedStyles}> <div className="dialog__content"> <div className="dialog__content-info"> <h3>Change your Wallet Address in the input below</h3> <div className="dialog__content-info--danger"> <p> It is your responsibility to check your wallet address, |WE| do not take any responsibility for incorrectly inputed wallet details. </p> </div> </div> {message.length > 1 ? ( <div style={{ color: "#FF6868" }}>{message}</div> ) : ( <></> )} <div className="dialog__content-input"> <input type="text" placeholder={state.walletAddress} onChange={(e) => setWallet(e.target.value)} /> <button className="save" onClick={() => { if (wallet.length > 40) { dispatch({ type: "CHANGE_WALLET_ADDRESS", payload: wallet }); setMessage("Successfully changed your wallet"); setTimeoutToCloseDialog(); } else { //TODO: Clear input on error setWallet(""); setMessage( "Wallet Address must be at least 40 characters long and start with 0x.." ); } setTimeoutToClearMessage(); }} > Save Wallet </button> </div> <p className="dialog__content-close" onClick={() => setOpen(!open)}> &times; </p> </div> </div> ); }; export default WalletDialog;
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; exports.default = renderProp; function renderProp(key, type, value) { if (type === 'func') { return key + '={() => alert(\'INSERT YOUR ' + key + ' function\')}'; } else if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' || typeof value === 'boolean') { return key + '={' + JSON.stringify(value) + '}'; } else if (type === 'element' || type === 'node') return key + '={' + value + '}';else if (typeof value === 'number') return key + '={' + value + '}';else return key + '="' + value + '"'; }
<filename>backend/controller/developerController.js const { pool } = require('../db/cloudDatabase') exports.getADeveloper = async (req, res) => { const sql = "SELECT * FROM DEVELOPER WHERE DNAME = $1;" try { const { rows } = await pool.query(sql, [req.params.dname]); res.status(200).json(rows); } catch (error) { res.status(500).json(error.stack); } } exports.postADeveloper = async (req, res) => { const sql = 'INSERT INTO DEVELOPER VALUES ($1);' try { await pool.query(sql, [req.body.dname]); res.status(200).send({ message: 'Insert developer ' + req.body.dname + ' succefully.' }) } catch (error) { res.json(error.stack); } } exports.getAllDeveloper = async (_req, res) => { try { const { rows } = await pool.query('SELECT * FROM DEVELOPER;'); res.status(200).json(rows); } catch (error) { res.json(error.stack); } } exports.deleteADeveloper = async (req, res) => { try { await pool.query('DELETE FROM DEVELOPER WHERE DNAME = $1', [req.params.dname]); res.status(200).json('DELETED developer with name ' + req.params.dnmae); } catch (error) { res.json(error.stack); } } exports.getLocationWithDName = async (req, res) => { const sql = "SELECT * FROM DLOCATION_TABLE WHERE DName = $1;" try { const { rows } = await pool.query(sql, [req.params.dname]); res.status(200).json(rows); } catch (error) { res.json(error.stack); } } exports.postLocationWithDName = async (req, res) => { const sql = 'INSERT INTO DLOCATION_TABLE VALUES($1, $2);' const params = [req.params.dname, req.body.location] try { await pool.query(sql, params); res.status(200).json({ message: 'Insert succefully' }) } catch (error) { res.json(error.stack); } } exports.deleteLocation = async (req, res) => { const sql = 'DELETE FROM DLOCATION_TABLE WHERE DNAME = $1 AND LOCATION = $2;' const params = [req.params.dname, req.params.location] try { await pool.query(sql, params); res.status(200).json({ message: 'Deleted succefully' }) } catch (error) { res.json(error.stack); } } exports.getAllVideoGamesWithDName = async (req, res) => { //All video games this developer develops const sql = "SELECT * FROM DEVELOPS AS D NATURAL JOIN VIDEO_GAME WHERE D.DNAME = $1;" const params = [req.params.dname] try { const { rows } = await pool.query(sql, params); res.status(200).json(rows); } catch (error) { res.json(error.stack); } } exports.postADevelop = async (req, res) => { const sql = 'INSERT INTO DEVELOPS VALUES ($1, $2);' const params = [req.body.v_id, req.params.dname] try { await pool.query(sql, params); res.status(200).json('INSERTED SUCCEFULLY'); } catch (error) { res.json(error.stack); } } exports.deleteADevelop = async (req, res) => { const params = [req.params.v_id, , req.params.dname] const sql = 'DELETE FROM DEVELOPS WHERE V_ID = $1 AND DNAME = $2;' try { await pool.query(sql, params); res.status(200).json({ message: 'DELETED SUCCEFULLY' }) } catch (error) { res.json(error.stack); } }
#!/bin/sh # # Run the Coverage test # make distclean if ! make CC=gcc COVERAGE=1 lcov_reset check lcov_capture lcov_html; then exit 1 fi
#!/bin/bash #SBATCH -J Act_tanh_1 #SBATCH --mail-user=eger@ukp.informatik.tu-darmstadt.de #SBATCH --mail-type=FAIL #SBATCH -e /work/scratch/se55gyhe/log/output.err.%j #SBATCH -o /work/scratch/se55gyhe/log/output.out.%j #SBATCH -n 1 # Number of cores #SBATCH --mem-per-cpu=6000 #SBATCH -t 23:59:00 # Hours, minutes and seconds, or '#SBATCH -t 10' -only mins #module load intel python/3.5 python3 /home/se55gyhe/Act_func/sequence_tagging/arg_min/PE-my.py tanh 412 Adam 3 0.30605350107437956 0.0011029725384177544 glorot_uniform 0.05
#!/bin/bash # Copyright 2015 The Kubernetes 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. # A script to the k8s worker in docker containers. # Authors @wizard_cxy @resouer set -e # Make sure docker daemon is running if ( ! ps -ef | grep "/usr/bin/docker" | grep -v 'grep' &> /dev/null ); then echo "Docker is not running on this machine!" exit 1 fi # Make sure k8s version env is properly set K8S_VERSION=${K8S_VERSION:-"1.2.2"} FLANNEL_VERSION=${FLANNEL_VERSION:-"0.5.5"} FLANNEL_IFACE=${FLANNEL_IFACE:-"eth0"} FLANNEL_IPMASQ=${FLANNEL_IPMASQ:-"true"} ARCH=${ARCH:-"amd64"} # Run as root if [ "$(id -u)" != "0" ]; then echo >&2 "Please run as root" exit 1 fi # Make sure master ip is properly set if [ -z ${MASTER_IP} ]; then echo "Please export MASTER_IP in your env" exit 1 fi echo "K8S_VERSION is set to: ${K8S_VERSION}" echo "FLANNEL_VERSION is set to: ${FLANNEL_VERSION}" echo "FLANNEL_IFACE is set to: ${FLANNEL_IFACE}" echo "FLANNEL_IPMASQ is set to: ${FLANNEL_IPMASQ}" echo "MASTER_IP is set to: ${MASTER_IP}" echo "ARCH is set to: ${ARCH}" # Check if a command is valid command_exists() { command -v "$@" > /dev/null 2>&1 } lsb_dist="" # Detect the OS distro, we support ubuntu, debian, mint, centos, fedora dist detect_lsb() { case "$(uname -m)" in *64) ;; *) echo "Error: We currently only support 64-bit platforms." exit 1 ;; esac if command_exists lsb_release; then lsb_dist="$(lsb_release -si)" fi if [ -z ${lsb_dist} ] && [ -r /etc/lsb-release ]; then lsb_dist="$(. /etc/lsb-release && echo "$DISTRIB_ID")" fi if [ -z ${lsb_dist} ] && [ -r /etc/debian_version ]; then lsb_dist='debian' fi if [ -z ${lsb_dist} ] && [ -r /etc/fedora-release ]; then lsb_dist='fedora' fi if [ -z ${lsb_dist} ] && [ -r /etc/os-release ]; then lsb_dist="$(. /etc/os-release && echo "$ID")" fi lsb_dist="$(echo ${lsb_dist} | tr '[:upper:]' '[:lower:]')" case "${lsb_dist}" in amzn|centos|debian|ubuntu) ;; *) echo "Error: We currently only support ubuntu|debian|amzn|centos." exit 1 ;; esac } # Start the bootstrap daemon bootstrap_daemon() { # Detecting docker version so we could run proper docker_daemon command [[ $(eval "docker --version") =~ ([0-9][.][0-9][.][0-9]*) ]] && version="${BASH_REMATCH[1]}" local got=$(echo -e "${version}\n1.8.0" | sed '/^$/d' | sort -nr | head -1) if [[ "${got}" = "${version}" ]]; then docker_daemon="docker -d" else docker_daemon="docker daemon" fi ${docker_daemon} \ -H unix:///var/run/docker-bootstrap.sock \ -p /var/run/docker-bootstrap.pid \ --iptables=false \ --ip-masq=false \ --bridge=none \ --dns 10.1.7.88 --dns 10.1.7.77 --insecure-registry=docker.hikvision.com.cn --insecure-registry=10.33.40.144 \ --graph=/var/lib/docker-bootstrap \ 2> /var/log/docker-bootstrap.log \ 1> /dev/null & sleep 5 } DOCKER_CONF="" # Start k8s components in containers start_k8s() { # Start flannel flannelCID=$(docker -H unix:///var/run/docker-bootstrap.sock run \ -d \ --restart=on-failure \ --net=host \ --privileged \ -v /dev/net:/dev/net \ 10.33.40.144/coreos/flannel:${FLANNEL_VERSION} \ /opt/bin/flanneld \ --ip-masq="${FLANNEL_IPMASQ}" \ --etcd-endpoints=http://${MASTER_IP}:4001 \ --iface="${FLANNEL_IFACE}") sleep 10 # Copy flannel env out and source it on the host docker -H unix:///var/run/docker-bootstrap.sock \ cp ${flannelCID}:/run/flannel/subnet.env . source subnet.env # Configure docker net settings, then restart it case "${lsb_dist}" in centos) DOCKER_CONF="/etc/sysconfig/docker" echo "OPTIONS=\"\$OPTIONS --mtu=${FLANNEL_MTU} --bip=${FLANNEL_SUBNET}\"" | tee -a ${DOCKER_CONF} if ! command_exists ifconfig; then yum -y -q install net-tools fi ifconfig docker0 down yum -y -q install bridge-utils && brctl delbr docker0 && systemctl restart docker ;; amzn) DOCKER_CONF="/etc/sysconfig/docker" echo "OPTIONS=\"\$OPTIONS --mtu=${FLANNEL_MTU} --bip=${FLANNEL_SUBNET}\"" | tee -a ${DOCKER_CONF} ifconfig docker0 down yum -y -q install bridge-utils && brctl delbr docker0 && service docker restart ;; ubuntu|debian) # TODO: today ubuntu uses systemd. Handle that too DOCKER_CONF="/etc/default/docker" echo "DOCKER_OPTS=\"\$DOCKER_OPTS --mtu=${FLANNEL_MTU} --bip=${FLANNEL_SUBNET}\"" | tee -a ${DOCKER_CONF} ifconfig docker0 down apt-get install bridge-utils brctl delbr docker0 service docker stop while [ `ps aux | grep /usr/bin/docker | grep -v grep | wc -l` -gt 0 ]; do echo "Waiting for docker to terminate" sleep 1 done service docker start ;; *) echo "Unsupported operations system ${lsb_dist}" exit 1 ;; esac # sleep a little bit sleep 5 # Start kubelet & proxy in container # TODO: Use secure port for communication docker run \ --net=host \ --pid=host \ --privileged \ --restart=on-failure \ -d \ -v /sys:/sys:ro \ -v /var/run:/var/run:rw \ -v /:/rootfs:ro \ -v /var/lib/docker/:/var/lib/docker:rw \ -v /var/lib/kubelet/:/var/lib/kubelet:rw \ 10.33.40.144/google_containers/hyperkube-${ARCH}:${K8S_VERSION} \ /hyperkube kubelet \ --allow-privileged=true \ --api-servers=http://${MASTER_IP}:8080 \ --address=0.0.0.0 \ --enable-server \ --cluster-dns=10.0.0.10 \ --cluster-domain=cluster.local \ --containerized \ --v=2 docker run \ -d \ --net=host \ --privileged \ --restart=on-failure \ 10.33.40.144/google_containers/hyperkube-${ARCH}:${K8S_VERSION} \ /hyperkube proxy \ --master=http://${MASTER_IP}:8080 \ --v=2 } echo "Detecting your OS distro ..." detect_lsb echo "Starting bootstrap docker ..." bootstrap_daemon echo "Starting k8s ..." start_k8s echo "Worker done!"
public static boolean searchMatrix(int[][] matrix, int target) { if (matrix == null || matrix.length == 0) return false; int row = 0; int col = matrix[0].length - 1; while (row < matrix.length && col >= 0) { if (matrix[row][col] == target) return true; else if (matrix[row][col] < target) row++; else col--; } return false; }
import { getAPIURI } from "../../common"; import { UserProfile } from "../UserProfile"; class UserProfileClient { static uploadProfile(userProfile) { return fetch(getAPIURI() + "myProfile", { method: "POST", headers: { "Content-Type": "application/json; charset=utf-8", Authorization: "Basic " + btoa(userProfile.email + ":" + userProfile.password), }, body: userProfile.toJson(), }); } static getProfile(userProfile) { return fetch(getAPIURI() + "myProfile", { method: "GET", headers: { "Content-Type": "application/json; charset=utf-8", Authorization: "Basic " + btoa(userProfile.email + ":" + userProfile.password), }, }) .then(r => new Promise((resolve, reject) => { if (r.ok) { resolve(r.json()); } else { throw new Error('Login failed'); } })) .then(data => new UserProfile(data)) .then(newUserProfile => { newUserProfile.password = <PASSWORD>; return newUserProfile; }); } } export { UserProfileClient };
from typing import Dict, Any def filter_kwargs(**kwargs: Any) -> Dict[str, Any]: return {key: value for key, value in kwargs.items() if value is not None}
import multer from 'multer' import path from 'path' import {v4 as uuidV4} from 'uuid' import express from "express"; import {MConfiguration} from "../../model/configuration"; export class Multer { static config: MConfiguration constructor(config: MConfiguration) { Multer.config = config; } midUploadFile(fieldName: string): express.RequestHandler<any, any, any, any, Record<string, any>> { const storage = multer.diskStorage({ destination: Multer.config.uploads, filename: (req, file, cb) => { cb(null, uuidV4() + path.extname(file.originalname).toLocaleLowerCase()) } }) const cMulter = multer({ storage: storage, dest: Multer.config.uploads }) return cMulter.single(fieldName) } }
<gh_stars>0 #! /usr/bin/env python import os, shutil, subprocess from colorama import Fore, Style class Palladin: def __init__(self): self.config = os.path.expanduser("~/.config/") self.mercy = ["palladin"] if not os.path.exists(self.config + "palladin"): os.mkdir(self.config + "palladin") try: with open(self.config + "palladin/mercy.list") as f: for name in f: self.mercy.append(name.rstrip()) except FileNotFoundError: pass def inspect(self): suspicious = lambda x: subprocess.run(("which", x), capture_output=True).returncode slain = 0 try: for name in os.listdir(self.config): if suspicious(name) and name not in self.mercy: print("My lord, I have found a suspicious one - " + color(Fore.YELLOW, name)) choice = input("Shall I slay him? (y/[n]): ") if choice == "y": self.slay(name) slain += 1 negative(color(Fore.RED, "As you wish, my lord.")) else: positive(color(Fore.GREEN, "I admire your grace, my lord!")) choice = input("Shall I save him forever? (y/[n]): ") if choice == "y": self.remember(name) positive(color(Fore.GREEN, "He will be safe.")) else: negative(color(Fore.RED, "If we meet again, he will know my wrath!")) except KeyboardInterrupt: negative("\nMy work is done if you think so, my lord:", Palladin.report(slain)) else: positive("My work is done, my lord:", Palladin.report(slain)) def slay(self, name): if os.path.isdir(self.config + name): shutil.rmtree(self.config + name) else: os.remove(self.config + name) def remember(self, name): with open(self.config + "palladin/mercy.list", "a") as f: f.write(name + "\n") def report(slain): return (str(slain) if slain else "no") + (" enemy was" if slain == 1 else " enemies were") + " slain." color = lambda c, x: c + x + Style.RESET_ALL def positive(*args): colored = (color(Fore.GREEN, arg) for arg in args) print(*colored) def negative(*args): colored = (color(Fore.RED, arg) for arg in args) print(*colored) if __name__ == "__main__": try: Palladin().inspect() except KeyboardInterrupt: print("\nMy work is done if you think so, my lord.")
#!/bin/bash ../.port_include.sh port=quake version=0.65 workdir=SerenityQuake-master useconfigure=false curlopts="-L" files="https://github.com/SerenityOS/SerenityQuake/archive/master.tar.gz quake.tar.gz" makeopts="V=1 SYMBOLS_ON=Y" depends=SDL2
def generate_fibonacci(n): fib_arr = [0, 1] while len(fib_arr) < n: num = fib_arr[-2] + fib_arr[-1] fib_arr.append(num) return fib_arr print(generate_fibonacci(5))
class QueueTrack < ActiveRecord::Base end
package com.github.saphyra.authservice.redirection.impl; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Component; import com.github.saphyra.authservice.common.CommonAuthProperties; import com.github.saphyra.authservice.common.RequestHelper; import com.github.saphyra.authservice.redirection.domain.RedirectionContext; import com.github.saphyra.util.CookieUtil; import lombok.RequiredArgsConstructor; @Component @RequiredArgsConstructor class RedirectionContextFactory { private final CookieUtil cookieUtil; private final CommonAuthProperties commonAuthProperties; private final RequestHelper requestHelper; RedirectionContext create(HttpServletRequest request) { return RedirectionContext.builder() .requestUri(request.getRequestURI()) .requestMethod(requestHelper.getMethod(request)) .isRest(requestHelper.isRestCall(request)) .accessTokenId(cookieUtil.getCookie(request, commonAuthProperties.getAccessTokenIdCookie())) .userId(cookieUtil.getCookie(request, commonAuthProperties.getUserIdCookie())) .request(request) .build(); } }
#!/bin/bash ########################## # SMP Script for CANDIDE # ########################## # Receive email when job finishes or aborts #PBS -M tobias.liaudat@cea.fr #PBS -m ea # Set a name for the job #PBS -N val_aziz_models # Join output and errors in one file #PBS -j oe # Set maximum computing time (e.g. 5min) #PBS -l walltime=90:00:00 # Request number of cores #PBS -l nodes=n16:ppn=2:hasgpu # Full path to environment export SPENV="$HOME/.conda/envs/shapepipe" export CONFDIR="$HOME/github/aziz_repos/deep_mccd/jobs" # Activate conda environment module load tensorflow/2.4 module load intel/19.0/2 source activate shapepipe # Run ShapePipe using full paths to executables /home/tliaudat/.local/bin/shapepipe_run.py -c $CONFDIR/config_files/val_high_aziz_models.ini # Return exit code exit 0
/* Info: JavaScript for JavaScript Basics Lesson 5, JavaScript DOM and Events, Task 1, Like / Unlike Button Author: Removed for reasons of anonymity Successfully checked as valid in JSLint Validator at: http://www.jslint.com/ and JSHint Validator at: http://www.jshint.com/ */ 'use strict'; function changeText() { var output = document.getElementById("ld-button"); var currentValue = output.innerHTML; if (currentValue === "Like") { currentValue = "Unlike"; } else { currentValue = "Like"; } output.innerHTML = currentValue; }
class BidStatusPresenter::Over::Vendor::Winner::PendingAcceptance < BidStatusPresenter::Base def header I18n.t('statuses.bid_status_presenter.over.winner.pending_acceptance.header') end def body I18n.t( 'statuses.bid_status_presenter.over.winner.pending_acceptance.body', delivery_url: auction.delivery_url ) end end
/* * 将specs 数组对象转换为字符串 * */ import { Joiner } from './joiner' const parseSpecValue = function (specs) { if (!specs) { return } const joiner = new Joiner(';', 2) specs.map((spec) => { joiner.join(spec.value) }) return joiner.getStr() } export { parseSpecValue }
public static void distinctElements(int arr[]) { int n = arr.length; // Pick all elements one by one for (int i = 0; i < n; i++) { // Check if the picked element // is already printed int j; for (j = 0; j < i; j++) if (arr[i] == arr[j]) break; // If not printed earlier, // then print it if (i == j) System.out.println( arr[i] ); } }
<gh_stars>0 import threading from hks_pylib.logger.logger import Display from hks_pylib.logger.standard import StdLevels, StdUsers from hks_pylib.logger.logger_generator import StandardLoggerGenerator from _simulator.server import ThesisListener from simulator.configuration.parser import parse_server, parse_channel class ThesisServerSimulator(object): def __init__(self, server_path, channel_path): server_configuration = parse_server(server_path) channel_configuration = parse_channel(channel_path) logger_generator = StandardLoggerGenerator(server_configuration["log"]) host = channel_configuration["host"] tport = channel_configuration["tport"] cipher = channel_configuration["cipher"] print = logger_generator.generate("Console", {StdUsers.USER: [StdLevels.INFO]}) self._print = lambda *args, **kwargs:\ print( StdUsers.USER, StdLevels.INFO, *args, **kwargs ) self.__listener = ThesisListener( address=(host, tport), cipher=cipher, name="Thesis Listener", logger_generator=logger_generator, display={StdUsers.USER: Display.ALL, StdUsers.DEV: Display.ALL} ) def start(self): threading.Thread( target=self.__listener.quickstart, name="Thesis Server" ).start()
<gh_stars>1-10 # Copyright 2022 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import google.auth project_id = google.auth.default()[1] def main(project_id, dataset_id, table_id): # [START retail_import_products_from_big_query] # TODO: Set project_id to your Google Cloud Platform project ID. # project_id = "my-project" # TODO: Set dataset_id # dataset_id = "products" # TODO: Set table_id # table_id = "products" # Import products into a catalog from big query table using Retail API import time from google.cloud.retail import ( BigQuerySource, ImportProductsRequest, ProductInputConfig, ProductServiceClient, ) default_catalog = f"projects/{project_id}/locations/global/catalogs/default_catalog/branches/default_branch" # TO CHECK ERROR HANDLING USE THE TABLE WITH INVALID PRODUCTS: # table_id = "products_some_invalid" # get import products from big query request def get_import_products_big_query_request(reconciliation_mode): # TO CHECK ERROR HANDLING PASTE THE INVALID CATALOG NAME HERE: # default_catalog = "invalid_catalog_name" big_query_source = BigQuerySource() big_query_source.project_id = project_id big_query_source.dataset_id = dataset_id big_query_source.table_id = table_id big_query_source.data_schema = "product" input_config = ProductInputConfig() input_config.big_query_source = big_query_source import_request = ImportProductsRequest() import_request.parent = default_catalog import_request.reconciliation_mode = reconciliation_mode import_request.input_config = input_config print("---import products from big query table request---") print(import_request) return import_request # call the Retail API to import products def import_products_from_big_query(): # TRY THE FULL RECONCILIATION MODE HERE: reconciliation_mode = ImportProductsRequest.ReconciliationMode.INCREMENTAL import_big_query_request = get_import_products_big_query_request( reconciliation_mode ) big_query_operation = ProductServiceClient().import_products( import_big_query_request ) print("---the operation was started:----") print(big_query_operation.operation.name) while not big_query_operation.done(): print("---please wait till operation is done---") time.sleep(30) print("---import products operation is done---") if big_query_operation.metadata is not None: print("---number of successfully imported products---") print(big_query_operation.metadata.success_count) print("---number of failures during the importing---") print(big_query_operation.metadata.failure_count) else: print("---operation.metadata is empty---") if big_query_operation.result is not None: print("---operation result:---") print(big_query_operation.result()) else: print("---operation.result is empty---") import_products_from_big_query() # [END retail_import_products_from_big_query] if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("dataset_id", nargs="?", default="products") parser.add_argument("table_id", nargs="?", default="products") args = parser.parse_args() main(project_id, args.dataset_id, args.table_id)
<gh_stars>0 import React from 'react'; import PropTypes from 'prop-types'; import { compose, graphql } from 'react-apollo'; import gql from 'graphql-tag'; import { AutoAndManualForm } from '../components'; import { queries } from '../graphql'; import withFormMutations from './withFormMutations'; const AutoAndManualFormContainer = props => { const { segmentsQuery, emailTemplatesQuery, customerCountsQuery } = props; // TODO change query to get only customerCounts const customerCounts = customerCountsQuery.customerCounts || { all: 0, byBrand: {}, byIntegrationType: {}, bySegment: {}, byTag: {} }; const counts = customerCounts.bySegment || {}; const updatedProps = { ...props, segments: segmentsQuery.segments || [], templates: emailTemplatesQuery.emailTemplates || [], counts }; return <AutoAndManualForm {...updatedProps} />; }; AutoAndManualFormContainer.propTypes = { segmentsQuery: PropTypes.object, emailTemplatesQuery: PropTypes.object, customerCountsQuery: PropTypes.object }; export default withFormMutations( compose( graphql(gql(queries.emailTemplates), { name: 'emailTemplatesQuery' }), graphql(gql(queries.segments), { name: 'segmentsQuery' }), graphql(gql(queries.customerCounts), { name: 'customerCountsQuery' }) )(AutoAndManualFormContainer) );
<reponame>prinsmike/go-start<filename>mongo/query_filternotequal.go package mongo import ( "labix.org/v2/mgo/bson" ) /////////////////////////////////////////////////////////////////////////////// // query_filterNotEqual type query_filterNotEqual struct { query_filterBase selector string value interface{} } func (self *query_filterNotEqual) bsonSelector() bson.M { return bson.M{self.selector: bson.M{"$ne": self.value}} } func (self *query_filterNotEqual) Selector() string { return self.selector }
package com.symulakr.dinstar.smsserver.message.enums; public enum SmsResult implements AsByte { SUCCEED(0, "Succeed"), FAIL(1, "Fail"), TIMEOUT(2, "Timeout"), BAD_REQUEST(3, "Bad request"), PORT_UNAVAILABLE(4, "Port unavailable"), PARTIAL_SUCCEED(5, "Partial succeed"), OTHER_ERROR(0xFF, "other error"), ; private int code; private String description; SmsResult(int code, String description) { this.code = code; this.description = description; } @Override public byte asByte() { return (byte) code; } public String getDescription() { return description; } }
import os import time def script_runner(script,thereshold,interval): for _ in range(thereshold): script_result = openFile(script) if script_result==0: return 0 else : if _==thereshold-2: break else: time.sleep(interval) return 1 def openFile(script): return os.system(script)
package unet.uncentralized.jkademlia.KademliaNode; import unet.uncentralized.jkademlia.Node.KID; import unet.uncentralized.jkademlia.Node.Node; import unet.uncentralized.jkademlia.Routing.KBucket; import unet.uncentralized.jkademlia.Socket.KSocket; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.security.NoSuchAlgorithmException; import java.util.List; public class Receiver extends Thread { private KademliaNode kad; private KSocket socket; private DataInputStream in; private DataOutputStream out; private byte v; public Receiver(KademliaNode kad, KSocket socket){ this.kad = kad; this.socket = socket; } @Override public void run(){ try{ in = socket.getInputStream(); out = socket.getOutputStream(); v = in.readByte(); switch(in.readByte()){ case 0x00: //PING ping(); break; case 0x01: //FIND_NODE findNode(); break; case 0x02: //FIND_VALUE findValue(); break; case 0x03: //STORE store(); break; case 0x04: //RESOLVE_EXTERNAL_IP resolve(); break; } }catch(IOException | NoSuchAlgorithmException e){ //e.printStackTrace(); }finally{ socket.close(); } } private void ping()throws IOException, NoSuchAlgorithmException { if(v == 0x00){ Node n = new Node(in); out.writeByte(0x00); //SEND PONG if(verify(n)){ kad.getRoutingTable().insert(n); kad.startRefresh(); //INIT BUCKET REFRESH } } } private void findNode()throws IOException, NoSuchAlgorithmException { if(v == 0x00){ Node s = new Node(in); //READ THE KEY IN QUESTION byte[] bid = new byte[KID.ID_LENGTH/8]; in.read(bid); KID k = new KID(bid); //NOW FIND THE CLOSEST List<Node> nodes = kad.getRoutingTable().findClosestWithLocal(k, KBucket.MAX_BUCKET_SIZE); if(nodes.size() < 2){ out.writeInt(0); }else{ out.writeInt(nodes.size()); for(Node n : nodes){ n.toStream(out); } } if(verify(s)){ kad.getRoutingTable().insert(s); kad.startRefresh(); //INIT BUCKET REFRESH } } } private void findValue()throws IOException { if(v == 0x00){ byte[] bid = new byte[KID.ID_LENGTH/8]; in.read(bid); KID k = new KID(bid); if(kad.getStorage().has(k)){ String v = kad.getStorage().get(k); //if(v == null){ // out.writeByte(0x01); //}else{ out.writeByte(0x00); out.writeInt(v.getBytes().length); out.write(v.getBytes()); //} }else{ out.writeByte(0x01); } } } private void store()throws IOException { if(v == 0x00){ byte[] bid = new byte[KID.ID_LENGTH/8]; in.read(bid); KID k = new KID(bid); byte[] buffer = new byte[in.readInt()]; in.read(buffer); kad.getStorage().put(k, new String(buffer)); } } private void resolve()throws IOException { InetAddress address = ((InetSocketAddress) socket.getRemoteSocketAddress()).getAddress(); if(address instanceof Inet4Address){ out.writeByte(0x04); }else if(address instanceof Inet6Address){ out.writeByte(0x06); } out.write(address.getAddress()); } private boolean verify(Node n){ try{ KSocket v = new KSocket(n); v.close(); return true; }catch(IOException e){ return false; } } }
#!/bin/bash source $(dirname $0)/_git-multi-util.sh __git_init_parent_dirs 1 for project_dir in "${git_parent_dirs[@]}" ; do cd "$project_dir" `which echo` -n "Pulling $project_dir... " git pull done
#!/bin/bash export DEVCTL_RELEASE_BOT_VERSION=v0.0.44 curl -LO https://github.com/alex-held/devctl-release-bot/releases/download/${DEVCTL_RELEASE_BOT_VERSION}/devctl-release-bot_${DEVCTL_RELEASE_BOT_VERSION}_linux_amd64.tar.gz tar -xvf devctl-release-bot_${DEVCTL_RELEASE_BOT_VERSION}_linux_amd64.tar.gz ./devctl-release-bot action
/*************************************************************************** * (C) Copyright 2003-2020 - Stendhal * *************************************************************************** *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ package games.stendhal.common; import java.util.Arrays; import java.util.List; /** * Constants about slots */ public final class Constants { /** * All the slots considered to be "with" the entity. Listed in priority * order (i.e. bag first). */ // TODO: let the slots decide that themselves public static final String[] CARRYING_SLOTS = { "pouch", "bag", "keyring", "portfolio", "back", "belt", "head", "rhand", "lhand", "armor", "finger", "cloak", "legs", "feet" }; /** * Modes that can be used for setting combat karma. */ public final static List<String> KARMA_SETTINGS = Arrays.asList( "never", "normal", "always"); }
import { v1 } from '@google-cloud/firestore' export const backup = async (projectId: string, bucketUrl: string, collectionIds: Array<string> = []) => { try { const client = new v1.FirestoreAdminClient() const databaseName = client.databasePath(projectId, '(default)') const responses = await client.exportDocuments({ name: databaseName, outputUriPrefix: bucketUrl, collectionIds, }) const { 0: response } = responses return response } catch (error) { console.log(error.message) permissionsError(projectId) } return null } export const restore = async (projectId: string, bucketUrl: string, collectionIds: Array<string> = []) => { try { const client = new v1.FirestoreAdminClient() const databaseName = client.databasePath(projectId, '(default)') const responses = await client.importDocuments({ name: databaseName, inputUriPrefix: bucketUrl, collectionIds, }) const { 0: response } = responses return response } catch (error) { console.log(error.message) permissionsError(projectId) } return null } function permissionsError(projectId) { console.log(` Please make sure you have all the permissions enabled: - Enabled billing (Only GCP projects with billing enabled can use the export and import feature.) see: https://cloud.google.com/billing/docs/how-to/modify-project') - Add "Cloud Datastore Import Export Admin" and "Storage Admin" to the service account you are using. see: https://firebase.google.com/docs/firestore/solutions/schedule-export#configure_access_permissions' check: https://console.cloud.google.com/iam-admin/iam?project=${projectId} `) }
# -*- coding: utf-8 -*- from __future__ import unicode_literals import django.contrib.postgres.fields.jsonb from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('transport', '0016_auto_20170308_1924'), ] operations = [ migrations.RemoveField( model_name='stop', name='administrative_area_code', ), migrations.RemoveField( model_name='stop', name='bearing', ), migrations.RemoveField( model_name='stop', name='bus_stop_type', ), migrations.RemoveField( model_name='stop', name='cleardown_code', ), migrations.RemoveField( model_name='stop', name='common_name_lang', ), migrations.RemoveField( model_name='stop', name='creation_datetime', ), migrations.RemoveField( model_name='stop', name='crossing', ), migrations.RemoveField( model_name='stop', name='crossing_lang', ), migrations.RemoveField( model_name='stop', name='default_wait_time', ), migrations.RemoveField( model_name='stop', name='easting', ), migrations.RemoveField( model_name='stop', name='grand_parent_locality_name', ), migrations.RemoveField( model_name='stop', name='grid_type', ), migrations.RemoveField( model_name='stop', name='indicator_lang', ), migrations.RemoveField( model_name='stop', name='landmark', ), migrations.RemoveField( model_name='stop', name='landmark_lang', ), migrations.RemoveField( model_name='stop', name='locality_centre', ), migrations.RemoveField( model_name='stop', name='modification', ), migrations.RemoveField( model_name='stop', name='modification_datetime', ), migrations.RemoveField( model_name='stop', name='northing', ), migrations.RemoveField( model_name='stop', name='notes', ), migrations.RemoveField( model_name='stop', name='notes_lang', ), migrations.RemoveField( model_name='stop', name='nptg_locality_code', ), migrations.RemoveField( model_name='stop', name='parent_locality_name', ), migrations.RemoveField( model_name='stop', name='plate_code', ), migrations.RemoveField( model_name='stop', name='revision_number', ), migrations.RemoveField( model_name='stop', name='short_common_name', ), migrations.RemoveField( model_name='stop', name='short_common_name_lang', ), migrations.RemoveField( model_name='stop', name='status', ), migrations.RemoveField( model_name='stop', name='stop_type', ), migrations.RemoveField( model_name='stop', name='street', ), migrations.RemoveField( model_name='stop', name='street_lang', ), migrations.RemoveField( model_name='stop', name='suburb', ), migrations.RemoveField( model_name='stop', name='suburb_lang', ), migrations.RemoveField( model_name='stop', name='timing_status', ), migrations.RemoveField( model_name='stop', name='town', ), migrations.RemoveField( model_name='stop', name='town_lang', ), migrations.AddField( model_name='stop', name='data', field=django.contrib.postgres.fields.jsonb.JSONField(blank=True, null=True), ), migrations.AddField( model_name='stop', name='last_modified', field=models.DateTimeField(auto_now=True), ), ]
import sys def simulate_sorbet_cli(args): output = [] for arg in args: if arg == "--silence-dev-message": output.append("Developer messages silenced.") elif arg == "--suggest-typed": output.append("Suggesting type annotations.") elif arg == "--autocorrect": output.append("Attempting to autocorrect.") elif arg.startswith("--typed="): mode = arg.split("=")[1] output.append(f"Type checking mode: {mode}.") elif arg.startswith("--isolate-error-code="): code = arg.split("=")[1] output.append(f"Isolating error code: {code}.") return "\n".join(output) # Example usage args = ["--silence-dev-message", "--suggest-typed", "--typed=strict", "--isolate-error-code=7022"] output = simulate_sorbet_cli(args) print(output)
import Vue from 'vue' const eventHub = new Vue() export default { computed: { eventHub () { return eventHub }, token () { return this.store.getters.sessionData.SPAToken } }, methods: { formatNumber (number) { const x = 3 const n = 0 const regExp = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\.' : '$') + ')' return number.toString().replace(/[^0-9,]/g, '').replace(new RegExp(',', 'g'), '').replace(new RegExp(regExp, 'g'), '$&,') }, customMask (number) { // const numLen = number ? number.length : 0 var numLen = 0 if (number != null) { var num = number while (num >= 1) { numLen += 1 num = num / 10 } } if (numLen <= 3) { return '####' } const pref = numLen % 3 const groupLen = numLen / 3 if (pref === 0) { return '###' + ',###'.repeat(groupLen - 1) + '#' } return '#'.repeat(pref) + ',###'.repeat(groupLen) + '#' }, formatDate (date) { if (!date) { return null } const [year, month, day] = date.split('-') return `${month}/${day}/${year}` }, parseDate (date) { if (!date) { return null } const [month, day, year] = date.split('/') return `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}` } } }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var util_1 = require("@antv/util"); var fecha_1 = tslib_1.__importDefault(require("fecha")); var view_layer_1 = tslib_1.__importDefault(require("../../base/view-layer")); var constant_1 = require("./constant"); var util_2 = require("./util"); var global_1 = require("../../base/global"); var date_1 = require("../../util/date"); var factory_1 = require("../../components/factory"); var EventParser = tslib_1.__importStar(require("./event")); /** * 日历图 */ var CalendarLayer = /** @class */ (function (_super) { tslib_1.__extends(CalendarLayer, _super); function CalendarLayer() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.type = 'calendar'; return _this; } CalendarLayer.getDefaultOptions = function () { var _a; return util_1.deepMix({}, _super.getDefaultOptions.call(this), { xAxis: { line: { visible: false, }, grid: { visible: false, }, tickLine: { visible: false, }, label: { visible: true, autoRotate: false, autoHide: false, }, }, yAxis: { line: { visible: false, }, grid: { visible: false, }, tickLine: { visible: false, }, label: { visible: true, autoRotate: false, autoHide: false, }, }, legend: { visible: false }, meta: (_a = {}, _a[constant_1.DAY_FIELD] = { type: 'cat', alias: 'Day', values: [0, 1, 2, 3, 4, 5, 6], }, _a[constant_1.WEEK_FIELD] = { type: 'cat', alias: 'Month', }, _a), tooltip: { visible: true, showTitle: true, showCrosshairs: false, showMarkers: false, title: 'date', }, }); }; /** * 复写父类的数据处理类,主要完成: * 1. 生成 polygon 的 x y field(虚拟的,无需用户传入) * * @param data */ CalendarLayer.prototype.processData = function (data) { var dateField = this.options.dateField; var dateRange = this.options.dateRange; // 给与默认值是当前这一年 if (util_1.isNil(dateRange)) { var dates = util_1.map(data, function (datum) { return fecha_1.default.parse("" + datum[dateField], constant_1.FORMATTER); }); dateRange = date_1.getDateRange(dates); } return util_2.generateCalendarData(data, dateRange, dateField); }; CalendarLayer.prototype.addGeometry = function () { var _a = this.options, valueField = _a.valueField, colors = _a.colors, tooltip = _a.tooltip; var polygonConfig = { type: 'polygon', position: { fields: [constant_1.WEEK_FIELD, constant_1.DAY_FIELD], }, shape: { values: ['calendar-polygon'], }, color: { fields: [valueField], values: colors, }, label: this.extractLabel(), }; if (tooltip && (tooltip.fields || tooltip.formatter)) { this.geometryTooltip(polygonConfig); } this.setConfig('geometry', polygonConfig); }; CalendarLayer.prototype.geometryTooltip = function (geomConfig) { geomConfig.tooltip = {}; var tooltipOptions = this.options.tooltip; if (tooltipOptions.fields) { geomConfig.tooltip.fields = tooltipOptions.fields; } if (tooltipOptions.formatter) { geomConfig.tooltip.callback = tooltipOptions.formatter; if (!tooltipOptions.fields) { geomConfig.tooltip.fields = [constant_1.WEEK_FIELD, constant_1.DAY_FIELD]; } } }; CalendarLayer.prototype.extractLabel = function () { var props = this.options; var label = props.label; if (label && label.visible === false) { return false; } var valueField = this.options.valueField; return factory_1.getComponent('label', tslib_1.__assign({ plot: this, fields: [valueField], position: 'top', offset: 0 }, label)); }; /** * 写入坐标系配置,默认增加镜像 */ CalendarLayer.prototype.coord = function () { // 默认做镜像处理 var coordinateConfig = { type: 'rect', cfg: {}, actions: [['reflect', 'y']], }; this.setConfig('coordinate', coordinateConfig); }; /** * 无需 geometry parser,直接使用 polygon 即可 */ CalendarLayer.prototype.geometryParser = function () { return ''; }; CalendarLayer.prototype.axis = function () { var xAxis_parser = factory_1.getComponent('axis', { plot: this, dim: 'x', }); var yAxis_parser = factory_1.getComponent('axis', { plot: this, dim: 'y', }); var axesConfig = {}; axesConfig[constant_1.WEEK_FIELD] = xAxis_parser; axesConfig[constant_1.DAY_FIELD] = yAxis_parser; /** 存储坐标轴配置项到config */ this.setConfig('axes', axesConfig); }; CalendarLayer.prototype.scale = function () { _super.prototype.scale.call(this); var monthWeek = util_2.getMonthCenterWeek(this.options.dateRange); // 拿出 scale 二次加工,主要是配置 x y 中的标题显示 var scales = this.config.scales; var _a = this.options, _b = _a.weeks, weeks = _b === void 0 ? constant_1.WEEKS : _b, _c = _a.months, months = _c === void 0 ? constant_1.MONTHS : _c; var x = scales[constant_1.WEEK_FIELD]; var y = scales[constant_1.DAY_FIELD]; // 1. 设置 formatter x.formatter = function (v) { var m = monthWeek[v]; return m !== undefined ? months[m] : ''; }; y.formatter = function (v) { return weeks[v] || ''; }; // 2. 设置 alias var _d = this.options, xAxis = _d.xAxis, yAxis = _d.yAxis; x.alias = util_1.get(xAxis, ['title', 'text'], x.alias); y.alias = util_1.get(yAxis, ['title', 'text'], y.alias); this.setConfig('scales', scales); }; CalendarLayer.prototype.parseEvents = function () { _super.prototype.parseEvents.call(this, EventParser); }; return CalendarLayer; }(view_layer_1.default)); exports.default = CalendarLayer; // 注册到池子中 global_1.registerPlotType('calendar', CalendarLayer); //# sourceMappingURL=layer.js.map
#!/bin/sh #This sample search script uses the "length" hint returned by #the librato API in a while loop to page through search results source ${SBHOME}/shellbrato.sh #DEBUG=1 #(uncomment to see debug info from shellbrato) OFFSET=0 #make an initial query to populate the length and offset variables R=$(listMetrics) RE="${RE}${R}" LENGTH=$(echo ${R} | ${JQ} .query.length) OFFSET=$((${OFFSET}+${LENGTH})) #continue to loop as long as the API returns 100 for length while [ "${LENGTH}" -eq 100 ] do R=$(listMetrics ${OFFSET}) RE="${RE}${R}" LENGTH=$(echo ${R} | ${JQ} .query.length) OFFSET=$((${OFFSET}+${LENGTH})) done echo ${RE} #| ${JQ} . debug "pages: $(((${OFFSET}/100)+1))" debug "Total metrics: ${OFFSET}"
function findPermutations(arr) { const permutations = []; // base case if (arr.length === 1) { permutations.push(arr); return permutations; } // recursive case for (let i = 0; i < arr.length; i++) { const currentNumber = arr[i]; const remaining = [...arr.slice(0, i), ...arr.slice(i + 1)]; const recursiveResults = findPermutations(remaining); for (let j = 0; j < recursiveResults.length; j++) { permutations.push([currentNumber, ...recursiveResults[j]]); } } return permutations; }
package riaken_core import ( "regexp" "testing" "github.com/sendgrid/riaken-core/rpb" ) // Example from http://docs.basho.com/riak/latest/dev/using/mapreduce/ func TestQueryMapReduce(t *testing.T) { client := dial() defer client.Close() session := client.Session() defer session.Release() // Test Data bucket := session.GetBucket("training") object1 := bucket.Object("foo") if _, err := object1.Store([]byte("pizza data goes here")); err != nil { t.Error(err.Error()) } object2 := bucket.Object("bar") if _, err := object2.Store([]byte("pizza pizza pizza pizza")); err != nil { t.Error(err.Error()) } object3 := bucket.Object("baz") if _, err := object3.Store([]byte("nothing to see here")); err != nil { t.Error(err.Error()) } object4 := bucket.Object("bam") if _, err := object4.Store([]byte("pizza pizza pizza")); err != nil { t.Error(err.Error()) } request := []byte(`{ "inputs":"training", "query":[{"map":{"language":"javascript", "source":"function(riakObject) { var val = riakObject.values[0].data.match(/pizza/g); return [[riakObject.key, (val ? val.length : 0 )]]; }"}}]}`) contentType := []byte("application/json") // Query query := session.Query() var result []byte // Loop until done is received from Riak. for out, err := query.MapReduce(request, contentType); !out.GetDone(); out, err = query.MapReduce(request, contentType) { if err != nil { t.Error(err.Error()) break } result = append(result, out.GetResponse()...) } // [["foo",1],["baz",0],["bar",4],["bam",3]] m, err := regexp.MatchString(`["foo",1]`, string(result)) if err != nil { t.Error(err.Error()) } if !m { t.Error("Mismatched foo result") } m, err = regexp.MatchString(`["bar",4]`, string(result)) if err != nil { t.Error(err.Error()) } if !m { t.Error("Mismatched bar result") } m, err = regexp.MatchString(`["baz",0]`, string(result)) if err != nil { t.Error(err.Error()) } if !m { t.Error("Mismatched baz result") } m, err = regexp.MatchString(`["bam",3]`, string(result)) if err != nil { t.Error(err.Error()) } if !m { t.Error("Mismatched bam result") } // Cleanup if _, err := object1.Delete(); err != nil { t.Error(err.Error()) } if _, err := object2.Delete(); err != nil { t.Error(err.Error()) } if _, err := object3.Delete(); err != nil { t.Error(err.Error()) } if _, err := object4.Delete(); err != nil { t.Error(err.Error()) } } func TestQuerySecondaryIndexes(t *testing.T) { client := dial() defer client.Close() session := client.Session() defer session.Release() // Setup bucket := session.GetBucket("b1") object := bucket.Object("o1") opts := &rpb.RpbPutReq{ Content: &rpb.RpbContent{ Indexes: []*rpb.RpbPair{ &rpb.RpbPair{ Key: []byte("animal_bin"), Value: []byte("chicken"), }, }, }, } if _, err := object.Do(opts).Store([]byte("o1-data")); err != nil { t.Error(err.Error()) } // Query query := session.Query() data, err := query.SecondaryIndexes([]byte("b1"), []byte("animal_bin"), []byte("chicken"), nil, nil, 0, nil) if err != nil { t.Error(err.Error()) } if len(data.GetKeys()) == 0 { t.Error("expected results") } else { if string(data.GetKeys()[0]) != "o1" { t.Error("expected first key to be o1") } } // Cleanup if _, err := object.Delete(); err != nil { t.Error(err.Error()) } } func TestQuerySearch(t *testing.T) { client := dial() defer client.Close() session := client.Session() defer session.Release() // Setup bucket := session.GetBucket("b3") object := bucket.Object("o1") object.ContentType([]byte("application/json")) if _, err := object.Store([]byte(`{"food": "pizza"}`)); err != nil { t.Error(err.Error()) } // Query query := session.Query() data, err := query.Search([]byte("b3"), []byte("food:pizza")) if err != nil { t.Error(err.Error()) } if data.GetNumFound() == 0 { t.Error("expected results") } // Cleanup if _, err := object.Delete(); err != nil { t.Error(err.Error()) } } func TestQuerySearchCompound(t *testing.T) { client := dial() defer client.Close() session := client.Session() defer session.Release() // Setup bucket := session.GetBucket("b3") object := bucket.Object("o2") object.ContentType([]byte("application/json")) if _, err := object.Store([]byte(`{"food": "pizza", "drink": "beer wine whiskey"}`)); err != nil { t.Error(err.Error()) } // Query query := session.Query() data, err := query.Search([]byte("b3"), []byte("food:pizza AND drink:beer")) if err != nil { t.Error(err.Error()) } if data.GetNumFound() == 0 { t.Error("expected results") } // Cleanup if _, err := object.Delete(); err != nil { t.Error(err.Error()) } }
#!/bin/sh set -ex pushd "$(dirname "$0")" USER=`whoami` # Validate the docs code examples. If something broke, please alert @docs-stitch-team. ./docs-examples/validate_all.sh ./generate_docs.sh browser analytics ./generate_docs.sh server analytics ./generate_docs.sh react-native analytics if ! which aws; then echo "aws CLI not found. see: https://docs.aws.amazon.com/cli/latest/userguide/installing.html" popd > /dev/null exit 1 fi BRANCH_NAME=`git branch | grep -e "^*" | cut -d' ' -f 2` USER_BRANCH="${USER}/${BRANCH_NAME}" aws s3 --profile 10gen-noc cp ../docs-browser s3://docs-mongodb-org-staging/stitch/"$USER_BRANCH"/sdk/js/ --recursive --acl public-read aws s3 --profile 10gen-noc cp ../docs-server s3://docs-mongodb-org-staging/stitch/"$USER_BRANCH"/sdk/js-server/ --recursive --acl public-read aws s3 --profile 10gen-noc cp ../docs-react-native s3://docs-mongodb-org-staging/stitch/"$USER_BRANCH"/sdk/react-native/ --recursive --acl public-read echo echo "Staged URLs:" echo " https://docs-mongodbcom-staging.corp.mongodb.com/stitch/$USER_BRANCH/sdk/js/index.html" echo " https://docs-mongodbcom-staging.corp.mongodb.com/stitch/$USER_BRANCH/sdk/js-server/index.html" echo " https://docs-mongodbcom-staging.corp.mongodb.com/stitch/$USER_BRANCH/sdk/react-native/index.html" popd > /dev/null
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.Cursor; public class DatabaseHelper extends SQLiteOpenHelper { public DatabaseHelper(Context context) { super(context, "contactDatabase.db", null, 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE contacts (name TEXT, email TEXT)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } public Cursor getContacts() { SQLiteDatabase db = this.getReadableDatabase(); Cursor res = db.rawQuery("SELECT * FROM contacts", null); return res; } } // Print contacts from database DatabaseHelper dbHelper = new DatabaseHelper(context); Cursor cursor = dbHelper.getContacts(); while (cursor.moveToNext()) { String name = cursor.getString(cursor.getColumnIndex("name")); String email = cursor.getString(cursor.getColumnIndex("email")); System.out.println(name + ": " + email); } cursor.close();
<reponame>nimbus-cloud/cli package app import ( "cf/terminal" "github.com/codegangsta/cli" "os" "strings" "text/tabwriter" "text/template" ) var appHelpTemplate = `{{.Title "NAME:"}} {{.Name}} - {{.Usage}} {{.Title "USAGE:"}} [environment variables] {{.Name}} [global options] command [arguments...] [command options] {{.Title "VERSION:"}} {{.Version}} {{range .Commands}} {{.SubTitle .Name}}{{range .CommandSubGroups}} {{range .}} {{.Name}} {{.Description}} {{end}}{{end}}{{end}} {{.Title "ENVIRONMENT VARIABLES"}} CF_COLOR=false Do not colorize output CF_HOME=path/to/dir/ Override path to default config directory CF_STAGING_TIMEOUT=15 Max wait time for buildpack staging, in minutes CF_STARTUP_TIMEOUT=5 Max wait time for app instance startup, in minutes CF_TRACE=true Print API request diagnostics to stdout CF_TRACE=path/to/trace.log Append API request diagnostics to a log file HTTP_PROXY=proxy.example.com:8080 Enable HTTP proxying for API requests {{.Title "GLOBAL OPTIONS"}} --version, -v Print the version --help, -h Show help ` type groupedCommands struct { Name string CommandSubGroups [][]cmdPresenter } func (c groupedCommands) SubTitle(name string) string { return terminal.HeaderColor(name + ":") } type cmdPresenter struct { Name string Description string } func newCmdPresenter(app *cli.App, maxNameLen int, cmdName string) (presenter cmdPresenter) { cmd := app.Command(cmdName) presenter.Name = presentCmdName(*cmd) padding := strings.Repeat(" ", maxNameLen-len(presenter.Name)) presenter.Name = presenter.Name + padding presenter.Description = cmd.Description return } func presentCmdName(cmd cli.Command) (name string) { name = cmd.Name if cmd.ShortName != "" { name = name + ", " + cmd.ShortName } return } type appPresenter struct { cli.App Commands []groupedCommands } func (p appPresenter) Title(name string) string { return terminal.HeaderColor(name) } func getMaxCmdNameLength(app *cli.App) (length int) { for _, cmd := range app.Commands { name := presentCmdName(cmd) if len(name) > length { length = len(name) } } return } func newAppPresenter(app *cli.App) (presenter appPresenter) { maxNameLen := getMaxCmdNameLength(app) presenter.Name = app.Name presenter.Usage = app.Usage presenter.Version = app.Version presenter.Name = app.Name presenter.Flags = app.Flags presenter.Commands = []groupedCommands{ { Name: "GETTING STARTED", CommandSubGroups: [][]cmdPresenter{ { newCmdPresenter(app, maxNameLen, "login"), newCmdPresenter(app, maxNameLen, "logout"), newCmdPresenter(app, maxNameLen, "passwd"), newCmdPresenter(app, maxNameLen, "target"), }, { newCmdPresenter(app, maxNameLen, "api"), newCmdPresenter(app, maxNameLen, "auth"), }, }, }, { Name: "APPS", CommandSubGroups: [][]cmdPresenter{ { newCmdPresenter(app, maxNameLen, "apps"), newCmdPresenter(app, maxNameLen, "app"), }, { newCmdPresenter(app, maxNameLen, "push"), newCmdPresenter(app, maxNameLen, "scale"), newCmdPresenter(app, maxNameLen, "delete"), newCmdPresenter(app, maxNameLen, "rename"), }, { newCmdPresenter(app, maxNameLen, "start"), newCmdPresenter(app, maxNameLen, "stop"), newCmdPresenter(app, maxNameLen, "restart"), }, { newCmdPresenter(app, maxNameLen, "events"), newCmdPresenter(app, maxNameLen, "files"), newCmdPresenter(app, maxNameLen, "logs"), }, { newCmdPresenter(app, maxNameLen, "env"), newCmdPresenter(app, maxNameLen, "set-env"), newCmdPresenter(app, maxNameLen, "unset-env"), }, { newCmdPresenter(app, maxNameLen, "stacks"), }, { newCmdPresenter(app, maxNameLen, "ssh"), }, }, }, { Name: "SERVICES", CommandSubGroups: [][]cmdPresenter{ { newCmdPresenter(app, maxNameLen, "marketplace"), newCmdPresenter(app, maxNameLen, "services"), newCmdPresenter(app, maxNameLen, "service"), }, { newCmdPresenter(app, maxNameLen, "create-service"), newCmdPresenter(app, maxNameLen, "delete-service"), newCmdPresenter(app, maxNameLen, "rename-service"), }, { newCmdPresenter(app, maxNameLen, "bind-service"), newCmdPresenter(app, maxNameLen, "unbind-service"), }, { newCmdPresenter(app, maxNameLen, "create-user-provided-service"), newCmdPresenter(app, maxNameLen, "update-user-provided-service"), }, }, }, { Name: "ORGS", CommandSubGroups: [][]cmdPresenter{ { newCmdPresenter(app, maxNameLen, "orgs"), newCmdPresenter(app, maxNameLen, "org"), }, { newCmdPresenter(app, maxNameLen, "create-org"), newCmdPresenter(app, maxNameLen, "delete-org"), newCmdPresenter(app, maxNameLen, "rename-org"), }, }, }, { Name: "SPACES", CommandSubGroups: [][]cmdPresenter{ { newCmdPresenter(app, maxNameLen, "spaces"), newCmdPresenter(app, maxNameLen, "space"), }, { newCmdPresenter(app, maxNameLen, "create-space"), newCmdPresenter(app, maxNameLen, "delete-space"), newCmdPresenter(app, maxNameLen, "rename-space"), }, }, }, { Name: "DOMAINS", CommandSubGroups: [][]cmdPresenter{ { newCmdPresenter(app, maxNameLen, "domains"), newCmdPresenter(app, maxNameLen, "create-domain"), newCmdPresenter(app, maxNameLen, "delete-domain"), newCmdPresenter(app, maxNameLen, "create-shared-domain"), newCmdPresenter(app, maxNameLen, "delete-shared-domain"), }, }, }, { Name: "ROUTES", CommandSubGroups: [][]cmdPresenter{ { newCmdPresenter(app, maxNameLen, "routes"), newCmdPresenter(app, maxNameLen, "create-route"), newCmdPresenter(app, maxNameLen, "map-route"), newCmdPresenter(app, maxNameLen, "unmap-route"), newCmdPresenter(app, maxNameLen, "delete-route"), }, }, }, { Name: "BUILDPACKS", CommandSubGroups: [][]cmdPresenter{ { newCmdPresenter(app, maxNameLen, "buildpacks"), newCmdPresenter(app, maxNameLen, "create-buildpack"), newCmdPresenter(app, maxNameLen, "update-buildpack"), newCmdPresenter(app, maxNameLen, "delete-buildpack"), }, }, }, { Name: "USER ADMIN", CommandSubGroups: [][]cmdPresenter{ { newCmdPresenter(app, maxNameLen, "create-user"), newCmdPresenter(app, maxNameLen, "delete-user"), }, { newCmdPresenter(app, maxNameLen, "org-users"), newCmdPresenter(app, maxNameLen, "set-org-role"), newCmdPresenter(app, maxNameLen, "unset-org-role"), }, { newCmdPresenter(app, maxNameLen, "space-users"), newCmdPresenter(app, maxNameLen, "set-space-role"), newCmdPresenter(app, maxNameLen, "unset-space-role"), }, }, }, { Name: "ORG ADMIN", CommandSubGroups: [][]cmdPresenter{ { newCmdPresenter(app, maxNameLen, "quotas"), newCmdPresenter(app, maxNameLen, "set-quota"), }, }, }, { Name: "SERVICE ADMIN", CommandSubGroups: [][]cmdPresenter{ { newCmdPresenter(app, maxNameLen, "service-auth-tokens"), newCmdPresenter(app, maxNameLen, "create-service-auth-token"), newCmdPresenter(app, maxNameLen, "update-service-auth-token"), newCmdPresenter(app, maxNameLen, "delete-service-auth-token"), }, { newCmdPresenter(app, maxNameLen, "service-brokers"), newCmdPresenter(app, maxNameLen, "create-service-broker"), newCmdPresenter(app, maxNameLen, "update-service-broker"), newCmdPresenter(app, maxNameLen, "delete-service-broker"), newCmdPresenter(app, maxNameLen, "rename-service-broker"), }, { newCmdPresenter(app, maxNameLen, "migrate-service-instances"), newCmdPresenter(app, maxNameLen, "purge-service-offering"), }, }, }, { Name: "ADVANCED", CommandSubGroups: [][]cmdPresenter{ { newCmdPresenter(app, maxNameLen, "curl"), }, }, }, } return } func showAppHelp(helpTemplate string, appToPrint interface{}) { app := appToPrint.(*cli.App) presenter := newAppPresenter(app) w := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\t', 0) t := template.Must(template.New("help").Parse(helpTemplate)) t.Execute(w, presenter) w.Flush() }
import { NgModule, ModuleWithProviders } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ColidMatSnackBarComponent } from './colid-mat-snack-bar/colid-mat-snack-bar.component'; import { MatSnackBarModule } from '@angular/material/snack-bar'; import { ColidMatSnackBarService } from './colid-mat-snack-bar.service'; import { MatButtonModule } from '@angular/material/button'; import { MatIconModule } from '@angular/material/icon'; @NgModule({ declarations: [ColidMatSnackBarComponent], imports: [ CommonModule, MatSnackBarModule, MatButtonModule, MatIconModule ], entryComponents: [ ColidMatSnackBarComponent ] }) export class ColidSnackBarModule { static forRoot(): ModuleWithProviders { return { ngModule: ColidSnackBarModule, providers: [ ColidMatSnackBarService ] }; } }
"use strict"; /** * @name Throwable * @author <NAME> */ Object.defineProperty(exports, "__esModule", { value: true }); exports.Throwable = void 0; class Throwable extends Error { constructor(message, code) { super(message); this.name = this.constructor.name; this.message = message; this.code = code; this.type = 'Exception'; // Tracking Pevious Errors on `process` variable. if (!process.__haluka_last_throwable) { process.__haluka_last_throwable = this; } } getPrevious() { return process.__haluka_last_throwable; } toString() { return `Uncaught ${this.constructor.name} [${this.code}]: ${this.message}`; } } exports.Throwable = Throwable; //# sourceMappingURL=Throwable.js.map
<reponame>WGBH/django-pbsmmapi<filename>pbsmmapi/asset/models.py # -*- coding: utf-8 -*- from __future__ import unicode_literals import json from django.db import models from django.utils.translation import ugettext_lazy as _ from ..abstract.models import PBSMMGenericAsset from .helpers import check_asset_availability AVAILABILITY_GROUPS = ( ('Station Members', 'station_members'), ('All Members', 'all_members'), ('Public', 'public') ) # remember the closing slash PBSMM_ASSET_ENDPOINT = 'https://media.services.pbs.org/api/v1/assets/' PBSMM_LEGACY_ASSET_ENDPOINT = 'https://media.services.pbs.org/api/v1/assets/legacy/?tp_media_id=' YES_NO = ( (1, 'Yes'), (0, 'No'), ) class PBSMMAbstractAsset(PBSMMGenericAsset): """ These are fields unique to Assets. Each object model has a *-Asset table, e.g., PBSMMEpisode has PBSMMEpisodeAsset, PBSMMShow has PBSShowAsset, etc. Aside from the FK reference to the parent, each of these *-Asset models are identical in structure. """ # These fields are unique to Asset legacy_tp_media_id = models.BigIntegerField( _('COVE ID'), null=True, blank=True, unique=True, help_text='(Legacy TP Media ID)', ) availability = models.TextField( _('Availability'), null=True, blank=True, help_text='JSON serialized Field', ) duration = models.IntegerField( _('Duration'), null=True, blank=True, help_text="(in seconds)", ) object_type = models.CharField( # This is 'clip', etc. _('Object Type'), max_length=40, null=True, blank=True, ) # CAPTIONS has_captions = models.BooleanField( _('Has Captions'), default=False, ) # TAGS, Topics tags = models.TextField( _('Tags'), null=True, blank=True, help_text='JSON serialized field', ) topics = models.TextField( _('Topics'), null=True, blank=True, help_text='JSON serialized field', ) # PLAYER FIELDS player_code = models.TextField( _('Player Code'), null=True, blank=True, ) # CHAPTERS chapters = models.TextField( _('Chapters'), null=True, blank=True, help_text="JSON serialized field", ) content_rating = models.CharField( _('Content Rating'), max_length=100, null=True, blank=True, ) content_rating_description = models.TextField( _('Content Rating Description'), null=True, blank=True, ) # This is a custom field that lies outside of the API. # It alloes the content producer to define WHICH Asset is shown on the parental object's Detail page. # Since the PBSMM API does not know how to distinguish mutliple "clips" from one another, this is necessary # to show a Promo vs. a Short Form video, etc. # # ... thanks PBS. override_default_asset = models.PositiveIntegerField( _('Override Default Asset'), null=False, choices=YES_NO, default=0 ) class Meta: abstract = True ### # Properties and methods ### def __unicode__(self): return "%d | %s (%d) | %s" % ( self.pk, self.object_id, self.legacy_tp_media_id, self.title ) def __object_model_type(self): """ This handles the correspondence to the "type" field in the PBSMM JSON object. Basically this just makes it easy to identify whether an object is an asset or not. """ return 'asset' object_model_type = property(__object_model_type) def asset_publicly_available(self): """ This is mostly for tables listing Assets in the Admin detail page for ancestral objects: e.g., an Episode's page in the Admin has a list of the episode's assets, and this provides a simple column to show availability in that list. """ if self.availability: a = json.loads(self.availability) p = a.get('public', None) if p: return check_asset_availability(start=p['start'], end=p['end'])[0] return None asset_publicly_available.short_description = 'Pub. Avail.' asset_publicly_available.boolean = True def __is_asset_publicly_available(self): """ Am I available to the public? True/False. """ return self.asset_publicly_available is_asset_publicly_available = property(__is_asset_publicly_available) def __duration_hms(self): """ Show the asset's duration as #h ##m ##s. """ if self.duration: d = self.duration hours = d // 3600 if hours > 0: hstr = '%dh' % hours else: hstr = '' d %= 3600 minutes = d // 60 if hours > 0: mstr = '%02dm' % minutes else: if minutes > 0: mstr = '%2dm' % minutes else: mstr = '' seconds = d % 60 if minutes > 0: sstr = '%02ds' % seconds else: sstr = '%ds' % seconds return ' '.join((hstr, mstr, sstr)) return '' duration_hms = property(__duration_hms) def __formatted_duration(self): """ Show the Asset's duration as ##:##:## """ if self.duration: seconds = self.duration hours = seconds // 3600 seconds %= 3600 minutes = seconds // 60 seconds %= 60 return "%d:%02d:%02d" % (hours, minutes, seconds) return '' formatted_duration = property(__formatted_duration) def __is_default(self): """ Return True/False if the Asset is the "default" Asset for it's parent. """ if self.override_default_asset: return True return False is_default = property(__is_default)
from pony.orm import Database, PrimaryKey, Optional, db_session class ORMProject(db.Entity): _table_ = 'mantis_project_table' id = PrimaryKey(int, column='id') name = Optional(str, column='name') class ORMProjectManager: def __init__(self, host, database, user, password): self.db = Database() self.db.bind(provider='mysql', host=host, database=database, user=user, password=password) def connect_to_database(self): self.db.generate_mapping(create_tables=True) @db_session def get_project_by_id(self, project_id): project = ORMProject.get(id=project_id) if project: return project.name else: return None @db_session def insert_project(self, project_name): new_project = ORMProject(name=project_name) commit()
python transformers/examples/language-modeling/run_language_modeling.py --model_name_or_path train-outputs/512+512+512-HPMI/model --tokenizer_name model-configs/1536-config --eval_data_file ../data/wikitext-103-raw/wiki.valid.raw --output_dir eval-outputs/512+512+512-HPMI/1024+0+512-shuffled-N-VB-256 --do_eval --per_device_eval_batch_size 1 --dataloader_drop_last --augmented --augmentation_function shuffle_remove_all_but_nouns_and_verbs_first_two_thirds_sixth --eval_function last_sixth_eval