text
stringlengths
1
1.05M
import ConnectionsList from "../ConnectionsList"; import { mount, shallow } from "enzyme"; import { forcePromiseResolve } from "../../test/testhelpers"; import { componentWithStore, createMockStore } from "../../test/testhelpers"; import { getPreFabSocialGraph } from "../../test/testGraphs"; import { getPrefabProfile } from "../../test/testProfiles"; import { getPrefabFeed } from "../../test/testFeeds"; const profile = getPrefabProfile(0); const graphs = getPreFabSocialGraph(); const feed = getPrefabFeed(); const store = createMockStore({ user: { profile: profile }, profiles: { profiles: [] }, graphs: { graphs: graphs }, feed: { feed: feed }, }); describe("ConnectionsList", () => { it("renders without crashing", async () => { const component = shallow(componentWithStore(ConnectionsList, store)); await forcePromiseResolve(); expect(() => component).not.toThrow(); }); describe("button displays correct list title", () => { it("displays correct list title on followers click", async () => { const component = mount(componentWithStore(ConnectionsList, store)); await forcePromiseResolve(); component.find(".ConnectionsList__button").first().simulate("click"); expect(component.find("ConnectionsListProfiles").prop("listStatus")).toBe( 0 ); }); it("displays correct list title on following click", async () => { const component = mount(componentWithStore(ConnectionsList, store)); await forcePromiseResolve(); component.find(".ConnectionsList__button").last().simulate("click"); expect(component.find("ConnectionsListProfiles").prop("listStatus")).toBe( 2 ); }); it("hides list on double click", async () => { const component = mount(componentWithStore(ConnectionsList, store)); await forcePromiseResolve(); component.find(".ConnectionsList__button").last().simulate("click"); component.find(".ConnectionsList__button").last().simulate("click"); expect(component.find("ConnectionsListProfiles").prop("listStatus")).toBe( 0 ); }); it("switches back and forth between lists", async () => { const component = mount(componentWithStore(ConnectionsList, store)); await forcePromiseResolve(); component.find(".ConnectionsList__button").first().simulate("click"); component.find(".ConnectionsList__button").last().simulate("click"); expect(component.find("ConnectionsListProfiles").prop("listStatus")).toBe( 2 ); }); }); });
package br.edu.ufcspa.tc6m.controle; import android.app.Activity; import android.app.DatePickerDialog; import android.app.Dialog; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.Image; import android.net.Uri; import android.os.Bundle; import android.os.PersistableBundle; import android.provider.MediaStore; import android.provider.Settings; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.RadioButton; import android.widget.Toast; import java.io.File; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import br.edu.ufcspa.tc6m.dao.PacienteDAO; import br.edu.ufcspa.tc6m.modelo.Paciente; import br.edu.ufcspa.tc6m.R; public class FormularioActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener { public static final int REQUEST_CODE_CAMERA = 123; private FormularioHelper helper; private Long idPaciente; private EditText date; private String caminhoFoto; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_formulario); iniciaComponentes(); } private void iniciaComponentes() { Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true); idPaciente = null; helper = new FormularioHelper(this); Intent intent = getIntent(); Paciente paciente = (Paciente) intent.getSerializableExtra("paciente"); if (paciente != null) { helper.preencheFormulário(paciente); idPaciente = paciente.getId(); } date = (EditText) findViewById(R.id.edTextDataNascimento); //Text Watcher para aceitar apenas datas no formato dd/mm/aaaa TextWatcher watcherData = new TextWatcher() { private String current = ""; private String ddmmyyyy = "DDMMAAAA"; private Calendar cal = Calendar.getInstance(); @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (!s.toString().equals(current)) { String clean = s.toString().replaceAll("[^\\d.]", ""); String cleanC = current.replaceAll("[^\\d.]", ""); int cl = clean.length(); int sel = cl; for (int i = 2; i <= cl && i < 6; i += 2) { sel++; } //Fix for pressing delete next to a forward slash if (clean.equals(cleanC)) sel--; if (clean.length() < 8) { clean = clean + ddmmyyyy.substring(clean.length()); } else { //This part makes sure that when we finish entering numbers //the date is correct, fixing it otherwise int day = Integer.parseInt(clean.substring(0, 2)); int mon = Integer.parseInt(clean.substring(2, 4)); int year = Integer.parseInt(clean.substring(4, 8)); if (mon > 12) mon = 12; cal.set(Calendar.MONTH, mon - 1); year = (year < 1900) ? 1900 : (year > Calendar.getInstance().get(Calendar.YEAR)) ? Calendar.getInstance().get(Calendar.YEAR) : year; cal.set(Calendar.YEAR, year); // ^ first set year for the line below to work correctly //with leap years - otherwise, date e.g. 29/02/2012 //would be automatically corrected to 28/02/2012 day = (day > cal.getActualMaximum(Calendar.DATE)) ? cal.getActualMaximum(Calendar.DATE) : day; clean = String.format(Locale.getDefault(), "%02d%02d%02d", day, mon, year); } clean = String.format("%s/%s/%s", clean.substring(0, 2), clean.substring(2, 4), clean.substring(4, 8)); sel = sel < 0 ? 0 : sel; current = clean; date.setText(current); date.setSelection(sel < current.length() ? sel : current.length()); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }; date.addTextChangedListener(watcherData); ImageButton btData = (ImageButton) findViewById(R.id.btData); btData.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Calendar now = Calendar.getInstance(); DatePickerDialog dpd = new DatePickerDialog(FormularioActivity.this, FormularioActivity.this, now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH)); dpd.show(); } }); //INICIA O BOTÃO DA CAMERA ImageButton btFoto = (ImageButton) findViewById(R.id.btFoto); btFoto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intentCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); caminhoFoto = getExternalFilesDir(null) + "/" + System.currentTimeMillis() + ".jpg"; File arquivoFoto = new File(caminhoFoto); intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(arquivoFoto)); startActivityForResult(intentCamera, REQUEST_CODE_CAMERA); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK) { //se a ação nao foi cancelada if (requestCode == REQUEST_CODE_CAMERA) { //Abre a foto tirada helper.carregaImagem(caminhoFoto); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_formulario, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_formulario: if (helper.validateFields()) { Paciente paciente = helper.pegaPacienteFromFields(idPaciente); PacienteDAO dao = new PacienteDAO(this); if (idPaciente == null) { dao.insere(paciente); Toast.makeText(getApplicationContext(), "Paciente " + paciente.getNome() + " adicionado!", Toast.LENGTH_LONG).show(); } else { dao.altera(paciente); Intent intentVaiProPerfil = new Intent(FormularioActivity.this, PerfilActivity.class); intentVaiProPerfil.putExtra("paciente", paciente); startActivity(intentVaiProPerfil); Toast.makeText(getApplicationContext(), "Paciente " + paciente.getNome() + " alterado!", Toast.LENGTH_LONG).show(); } dao.close(); finish(); } else { Toast.makeText(getApplicationContext(), "Preencha todos os campos!", Toast.LENGTH_LONG).show(); } break; } return super.onOptionsItemSelected(item); } @Override public void onSaveInstanceState(Bundle savedInstanceState) { savedInstanceState.putString("caminho_foto", caminhoFoto); super.onSaveInstanceState(savedInstanceState); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); caminhoFoto = savedInstanceState.getString("caminho_foto"); if (caminhoFoto != null) { System.out.println("foto" + savedInstanceState.getString("caminho_foto")); helper.carregaImagem(caminhoFoto); } } @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { EditText edTextData = (EditText) findViewById(R.id.edTextDataNascimento); String strData = String.format(Locale.getDefault(), "%02d", dayOfMonth) + "/" + String.format(Locale.getDefault(), "%02d", monthOfYear + 1) + "/" + String.format(Locale.getDefault(), "%04d", year); edTextData.setText(strData); } }
#!/bin/bash # Copyright 2016 Korea University & EMCS Labs (Author: Hyungwon Yang) # Apache 2.0 # # This script duplicates a givien text file that transcribed wav file # along with the names of all wave files. # Let's say you have 100 wave files recorded "I want to go to school". # All the wave files are written in their distinctive labels such as test01.wav, test02.wav and so on. # And you have one text file that transrbied "I want to go to school", then you can use this script # for generating all the transcribed text files that corresponds to the name of each wave file. # Argument setting. if [ $# -ne 2 ]; then echo "Input arguements are incorrectly provided. Two arguments should be assigned." echo "1. Text file." echo "2. Wave file directory." echo "*** USAGE ***" echo 'Ex. sh text4allwav $textfile_name $wave_file_directory ' && return fi # Text file txt_file=$1 # Wave file directory wav_dir=$2 # Get the text file. txt_snt=`cat $txt_file` # Get the name of wave files # Wave list wav_list=`ls $wav_dir` for turn in $wav_list; do txt_name=`echo $turn | tr -s '.wav' '.txt'` echo $txt_snt > $wav_dir/$txt_name done echo "Text files are generated."
#!/usr/bin/env sh # generated from catkin/python/catkin/environment_cache.py # based on a snapshot of the environment before and after calling the setup script # it emulates the modifications of the setup script without recurring computations # new environment variables # modified environment variables export CMAKE_PREFIX_PATH="/home/robond/Desktop/WhereAmI/catkin_ws/devel:$CMAKE_PREFIX_PATH" export LD_LIBRARY_PATH="/home/robond/Desktop/WhereAmI/catkin_ws/devel/lib:$LD_LIBRARY_PATH" export PKG_CONFIG_PATH="/home/robond/Desktop/WhereAmI/catkin_ws/devel/lib/pkgconfig:$PKG_CONFIG_PATH" export PWD="/home/robond/Desktop/WhereAmI/catkin_ws/build" export ROSLISP_PACKAGE_DIRECTORIES="/home/robond/Desktop/WhereAmI/catkin_ws/devel/share/common-lisp" export ROS_PACKAGE_PATH="/home/robond/Desktop/WhereAmI/catkin_ws/src:$ROS_PACKAGE_PATH"
<reponame>reekoheek/yesbee 'use strict'; const Message = require('../message'); const co = require('co'); const _ = require('lodash'); const HEARTBEAT = 60000; module.exports = function *(execution) { if (!process.send) { throw new Error('Worker must be forked from daemon process'); } // var exchanges = {}; execution.context.isWorker = true; execution.context.shutdown = function() { process.send({ method: 'shutdown' }); }; // execution.context.consume = function(message) { // return new Promise(function(resolve, reject) { // exchanges[message.id] = [resolve, reject, message]; // process.send({ // method: 'upstream', // message: message.dump() // }); // }); // }; var name = execution.opts.service || execution.opts.s; var service = yield execution.context.services.resolve({ name: name }); yield service.start(); process.on('message', function(data) { switch (data.method) { case 'init': execution.args.push.apply(execution.args, data.message.args); _.defaults(execution.opts, data.message.opts); break; case 'consume': co(function *() { var message = Message.unserialize(data.message); try { message = yield execution.context.components.get(message.uri).request(message); } catch(e) { message.error = e; } process.send({ method: 'consume', message: message.dump() }); }); break; // case 'upstream': // var message = Message.unserialize(data.message); // var exchange = exchanges[message.id]; // exchange[2].merge(message); // if (message.error) { // exchange[1](message.error); // } else { // exchange[0](message); // } // break; default: execution.logger({$name: '@worker', level: 'error', message: 'Unsupported rpc method: ' + data.method}); } }); process.send({ method: 'started' }); (function heartbeat() { // console.log('heartbeat', new Date()); setTimeout(heartbeat, HEARTBEAT); })(); };
rosparam load picop/picop.yaml physical_displays/picop rosparam load picop/vdisp.yaml virtual_displays/picop/vdisp rosparam load picop/vdisp_mirror.yaml virtual_displays/picop/vdisp_mirror
<gh_stars>0 package cn.cerc.jbean.services; import cn.cerc.jbean.core.AbstractService; import cn.cerc.jbean.core.IStatus; import cn.cerc.jbean.core.ServiceException; import cn.cerc.jbean.other.SystemTable; import cn.cerc.jdb.core.DataSet; import cn.cerc.jdb.core.Record; import cn.cerc.jdb.mysql.SqlQuery; public class SvrUserOption extends AbstractService { @Override public IStatus execute(DataSet dataIn, DataSet dataOut) throws ServiceException { Record head = dataIn.getHead(); SqlQuery ds = new SqlQuery(this); ds.add(String.format("select Value_ from %s", SystemTable.get(SystemTable.getUserOptions))); ds.add(String.format("where UserCode_=N'%s' and Code_=N'%s'", this.getUserCode(), head.getString("Code_"))); ds.open(); dataOut.appendDataSet(ds); return success(); } }
#!/bin/bash C_RESET='\033[0m' C_RED='\033[0;31m' C_GREEN='\033[0;32m' C_BLUE='\033[0;34m' C_YELLOW='\033[1;33m' C_PURPLE='\033[1;35m' # println echos string function println() { echo -e "$1" } # errorln echos i red color function errorln() { println "${C_RED}${1}${C_RESET}" } # successln echos in green color function successln() { println "${C_GREEN}${1}${C_RESET}" } # infoln echos in blue color function infoln() { println "${C_BLUE}${1}${C_RESET}" } # warnln echos in yellow color function warnln() { println "${C_YELLOW}${1}${C_RESET}" } function debugln() { println "${C_PURPLE}${1}${C_RESET}" } # fatalln echos in red color and exits with fail status function fatalln() { errorln "$1" exit 1 } # print_times prints char specifies at $1 n times (n specifies at $2) function print_times() { str=$1 num=$2 v=$(printf "%-${num}s" "$str") echo -ne "${v// /${str}}" } function prettytime() { local minutes=$(( $1 / 60 )) local seconds=$(( $1 % 60 )) if [[ $minutes -ge 1 ]]; then echo -ne "${minutes}m ${seconds}s" else echo -ne "${seconds}s" fi } export -f errorln export -f successln export -f infoln export -f warnln export -f print_times
class Story { constructor() { this.chapters = []; this.currentChapterIndex = 0; } addChapter(title, content) { this.chapters.push({ title, content }); } getCurrentChapter() { if (this.chapters.length === 0) { return { title: "The End", content: "" }; } return this.chapters[this.currentChapterIndex]; } nextChapter() { this.currentChapterIndex++; if (this.currentChapterIndex >= this.chapters.length) { return { title: "The End", content: "" }; } return this.getCurrentChapter(); } reset() { this.currentChapterIndex = 0; } } // Test the Story class const myStory = new Story(); myStory.addChapter("Chapter 1", "Once upon a time..."); myStory.addChapter("Chapter 2", "In a land far, far away..."); console.log(myStory.getCurrentChapter()); // Output: { title: "Chapter 1", content: "Once upon a time..." } myStory.nextChapter(); console.log(myStory.getCurrentChapter()); // Output: { title: "Chapter 2", content: "In a land far, far away..." } myStory.nextChapter(); console.log(myStory.getCurrentChapter()); // Output: { title: "The End", content: "" } myStory.reset(); console.log(myStory.getCurrentChapter()); // Output: { title: "Chapter 1", content: "Once upon a time..." }
const strs = ["a", "b", "c"]; const ints = [1, 2, 3]; const combineArrays = (strs, ints) => { const obj = {}; for (let i = 0; i < strs.length; i++) { const str = strs[i]; const int = ints[i]; obj[str] = int; } return obj; }; const obj = combineArrays(strs, ints); console.log(obj); // Output: {a: 1, b: 2, c: 3}
// 1240. 단순 2진 암호코드 // 2019.07.03 #include<iostream> #include<algorithm> #include<string> #include<map> using namespace std; int main() { int t; cin >> t; // 맵에 문제에있는 암호를 미리 저장함 map<string, int> password; password["<PASSWORD>"] = 0; password["<PASSWORD>"] = 1; password["<PASSWORD>"] = 2; password["<PASSWORD>"] = 3; password["<PASSWORD>"] = 4; password["<PASSWORD>"] = 5; password["<PASSWORD>"] = 6; password["<PASSWORD>"] = 7; password["<PASSWORD>"] = 8; password["<PASSWORD>"] = 9; for (int test_case = 1; test_case <= t; test_case++) { string code[51]; int arr[9]; int x, y; cin >> x >> y; for (int i = 0; i < x; i++) { cin >> code[i]; } int cnt = 8; for (int m = 0; m < x; m++) { for (int i = y - 1; i >= 0; i--) { if (i - 7 < 0) { break; } string tmp = code[m].substr(i - 7, 7); // 맵에 있는거라면 값을 추출 if (password.find(tmp) != password.end()) { i -= 6; arr[cnt--] = password[tmp]; } } // 모두 추출했다면 종료 if (cnt == 0) { break; } } // 추출한것으로 암호코드를 계산 int ans = 0; // 홀수 자리의 합 x 3 for (int i = 1; i < 9; i += 2) { ans += arr[i]; } int tmp = ans; tmp *= 3; // 짝수 자리의 합 for (int i = 2; i <= 8; i += 2) { ans += arr[i]; tmp += arr[i]; } // 10으로 나누어 떨어진다면 올바른 암호코드이므로 미리 계산한 합 출력 if (tmp % 10 == 0) { cout << "#" << test_case << " " << ans << endl; } else { cout << "#" << test_case << " 0" << endl; } } }
#!/usr/bin/env sh # 当发生错误时中止脚本 set -e # 构建 yarn build # cd 到构建输出的目录下 cd dist # 部署到自定义域域名 # echo 'www.example.com' > CNAME git init git add -A git commit -m 'deploy' # 部署到 https://<USERNAME>.github.io # git push -f git@github.com:<USERNAME>/<USERNAME>.github.io.git master # 部署到 https://<USERNAME>.github.io/<REPO> git push -f git@gitee.com:inviernoQAQ/easy-bill-vue-website.git master:gh-pages cd -
#!/usr/bin/env bash echo Building justondavies/go_keyring:build sudo docker build \ --network host \ --file dockerfiles/all.docker \ --tag justondavies/go_keyring:build \ ./ sudo docker create \ --name build_extract \ justondavies/go_keyring:build rm -rf ./build/browser* sudo docker cp \ build_extract:/go/src/github.com/justondavies/go_keyring/build \ ./ sudo docker rm -f build_extract sudo chown -R $USER:$USER ./build chmod -R 700 ./build
<filename>NetBeans login project/src/finalproject/UserRoles.java<gh_stars>0 /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package finalproject; import static finalproject.FinalProject.loginScreen; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author <NAME> */ public class UserRoles { public static void userScreen(int userRole) throws IOException { Scanner userIn= new Scanner(System.in); // Scanner for user input String currentLine; String logOut; //If/else tree uses the value of userRole from logInScreen() to discern the type of user who has logged on if (userRole == 1) { try (BufferedReader br = new BufferedReader(new FileReader("admin.txt"))) { //Loads the admin text file while ((currentLine = br.readLine()) != null) { //Loop runs through the file and prints contents until there is no content left System.out.println(currentLine); } } catch (FileNotFoundException ex) { Logger.getLogger(UserRoles.class.getName()).log(Level.SEVERE, null, ex); } } else if (userRole == 2) { try (BufferedReader br = new BufferedReader(new FileReader("veterinarian.txt"))) { //Loads the vet text file while ((currentLine = br.readLine()) != null) { System.out.println(currentLine); } } catch (FileNotFoundException ex) { Logger.getLogger(UserRoles.class.getName()).log(Level.SEVERE, null, ex); } } else { try (BufferedReader br = new BufferedReader(new FileReader("zookeeper.txt"))) { //Loads the zookeeper text file while ((currentLine = br.readLine()) != null) { System.out.println(currentLine); } } catch (FileNotFoundException ex) { Logger.getLogger(UserRoles.class.getName()).log(Level.SEVERE, null, ex); } } System.out.println("Type exit to log out"); // Loop checks to see if the user enters exit to log out do{ logOut = userIn.nextLine(); }while(!logOut.equals("exit")); // If exit is entered the loop ends and the if statement runs if(logOut.equals("exit")) {// Log the user out by calling the login screen loginScreen(); } } }
function(page, done) { var dom = page.getIdleDom(); const what = 'idle'; var lable = 'HEAD'; //if (some requirement) var meta_ks = dom.querySelectorAll('meta[name="keywords"]'); if (meta_ks.length > 0) { if(meta_ks > 1) { done(this.createResult(lable, 'Multiple unnecessary meta keywords tags found.'+this.partialCodeLink(meta_ks), 'warning', what)); } //some category of stuff your are testing i.e.: 'DOM', 'HEAD', 'BODY', 'HTTP', 'SPEED', ... var msg = 'Unnecessary meta keywords tag: '+meta_ks[0]['content']; //you can create a link showing only the partial code of a nodeList //msg = msg+' '+this.partialCodeLink(dom); msg = msg+this.partialCodeLink(meta_ks); var type = 'warning'; //should be 'info', 'warning', 'error' done(this.createResult(lable, msg, type, what)); } done(); }
<filename>scs-web/src/main/java/com/zhcs/service/MonitordevService.java package com.zhcs.service; import com.zhcs.entity.MonitordevEntity; import java.util.List; import java.util.Map; //***************************************************************************** /** * <p>Title:MonitordevService</p> * <p>Description: 监控设备</p> * <p>Copyright: Copyright (c) 2017</p> * <p>Company: 深圳市智慧城市管家信息科技有限公司 </p> * @author 刘晓东 - Alter * @version v1.0 2017年2月23日 */ //***************************************************************************** public interface MonitordevService { MonitordevEntity queryObject(Long id); List<MonitordevEntity> queryList(Map<String, Object> map); int queryTotal(Map<String, Object> map); void save(MonitordevEntity monitordev); void update(MonitordevEntity monitordev); void delete(Long id); void deleteBatch(Long[] ids); }
<gh_stars>100-1000 import BlueKit from './app/Page.react'; export default BlueKit
import _ from 'lodash'; import cx from 'classnames'; /* * == BSD2 LICENSE == * Copyright (c) 2017, Tidepool Project * * This program is free software; you can redistribute it and/or modify it under * the terms of the associated License, which is identical to the BSD 2-Clause * License as published by the Open Source Initiative at opensource.org. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the License for more details. * * You should have received a copy of the License along with this program; if * not, you can obtain one from Tidepool Project at tidepool.org. * == BSD2 LICENSE == */ import PropTypes from 'prop-types'; import React, { PureComponent } from 'react'; import { TransitionMotion, spring } from 'react-motion'; import { classifyBgValue } from '../../../utils/bloodglucose'; import { springConfig } from '../../../utils/constants'; import withDefaultYPosition from '../common/withDefaultYPosition'; import styles from './CBGMedianAnimated.css'; export class CBGMedianAnimated extends PureComponent { static defaultProps = { sliceWidth: 16, }; static propTypes = { bgBounds: PropTypes.shape({ veryHighThreshold: PropTypes.number.isRequired, targetUpperBound: PropTypes.number.isRequired, targetLowerBound: PropTypes.number.isRequired, veryLowThreshold: PropTypes.number.isRequired, }).isRequired, datum: PropTypes.shape({ firstQuartile: PropTypes.number, id: PropTypes.string.isRequired, max: PropTypes.number, median: PropTypes.number, min: PropTypes.number, msFrom: PropTypes.number.isRequired, msTo: PropTypes.number.isRequired, msX: PropTypes.number.isRequired, ninetiethQuantile: PropTypes.number, tenthQuantile: PropTypes.number, thirdQuartile: PropTypes.number, }).isRequired, defaultY: PropTypes.number.isRequired, displayingMedian: PropTypes.bool.isRequired, showingCbgDateTraces: PropTypes.bool.isRequired, sliceWidth: PropTypes.number.isRequired, xScale: PropTypes.func.isRequired, yScale: PropTypes.func.isRequired, }; constructor(props) { super(props); this.willEnter = this.willEnter.bind(this); this.willLeave = this.willLeave.bind(this); } willEnter() { const { defaultY } = this.props; return { height: 0, median: defaultY, opacity: 0, }; } willLeave() { const { defaultY } = this.props; const shrinkOut = spring(0, springConfig); return { height: shrinkOut, median: spring(defaultY, springConfig), opacity: shrinkOut, }; } render() { const { bgBounds, datum, defaultY, displayingMedian, showingCbgDateTraces, sliceWidth, xScale, yScale, } = this.props; const medianClasses = datum.median ? cx({ [styles.median]: true, [styles[`${classifyBgValue(bgBounds, datum.median, 'fiveWay')}FadeIn`]]: !showingCbgDateTraces, [styles[`${classifyBgValue(bgBounds, datum.median, 'fiveWay')}FadeOut`]]: showingCbgDateTraces, }) : cx({ [styles.median]: true, [styles.transparent]: true, }); const strokeWidth = sliceWidth / 8; const medianWidth = sliceWidth - strokeWidth; const medianHeight = medianWidth * 0.75; const binLeftX = xScale(datum.msX) - medianWidth / 2 + strokeWidth / 2; const width = medianWidth - strokeWidth; const shouldRender = displayingMedian && (_.get(datum, 'median') !== undefined); return ( <TransitionMotion defaultStyles={shouldRender ? [{ key: 'median', style: { height: 0, median: defaultY, opacity: 0, }, }] : []} styles={shouldRender ? [{ key: 'median', style: { height: spring(medianHeight, springConfig), median: spring(yScale(datum.median) - medianHeight / 2, springConfig), opacity: spring(1.0, springConfig), }, }] : []} willEnter={this.willEnter} willLeave={this.willLeave} > {(interpolateds) => { if (interpolateds.length === 0) { return null; } const { key, style } = interpolateds[0]; return ( <rect className={medianClasses} id={`cbgMedian-${key}`} width={width} height={style.height} x={binLeftX} y={style.median} opacity={style.opacity} /> ); }} </TransitionMotion> ); } } export default withDefaultYPosition(CBGMedianAnimated);
#!/usr/bin/env bash set -e # Notes: install required libraries #sudo apt-get install libboost-all-dev #sudo apt-get install libwebsocketpp-dev mkdir -p build pushd build cmake .. cmake --build . --target install popd
<filename>AP2/src/teorica/Empregado.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package teorica; /** * * @author PauloCésar */ public abstract class Empregado { private String nome, sobrenome, cpf; public Empregado(){} public Empregado(String nome, String sobrenome, String cpf) { this.nome = nome; this.sobrenome = sobrenome; this.cpf = cpf; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getSobrenome() { return sobrenome; } public void setSobrenome(String sobrenome) { this.sobrenome = sobrenome; } public String getCpf() { return cpf; } public void setCpf(String cpf) { this.cpf = cpf; } public abstract double vencimento(); @Override public String toString(){ return "Nome: "+this.nome+" "+this.sobrenome+"\n CPF: "+this.cpf; } }
// Fees.java // Displays tuition and book fees import java.util.Scanner; class Fees { public static void main(String[] args) { double creditHours; final double HOUR_FEE = 85; double tuitionFee; double bookFee; final double ATHLETIC_FEE = 65; double sum; Scanner input = new Scanner(System.in); System.out.print("Enter credit hours "); creditHours = input.nextDouble(); System.out.print("Enter book fees "); bookFee = input.nextDouble(); sum = (creditHours * HOUR_FEE) + bookFee + ATHLETIC_FEE; System.out.println("Credit hours = " + creditHours); System.out.println("Rate per hour is $" + HOUR_FEE); System.out.println("So tuition is $" + (creditHours * HOUR_FEE)); System.out.println("Book fee is $" + bookFee); System.out.println("Athletic fee is $" + ATHLETIC_FEE); System.out.println("Total fees:$" + sum); } }
def find_two_add_up_to_target(nums, target): for num1 in nums: for num2 in nums: if num1 + num2 == target: return True return False
from pathlib import Path import shutil def organize_files(source_dir, dest_dir): source_path = Path(source_dir) dest_path = Path(dest_dir) # Move files based on naming conventions for file in source_path.iterdir(): if file.is_file(): if file.name.startswith('dir1'): shutil.move(str(file), str(dest_path / 'c1' / file.name)) elif file.name.startswith('dir2'): shutil.move(str(file), str(dest_path / 'c2' / file.name)) elif file.name.startswith('dir3'): shutil.move(str(file), str(dest_path / 'c3' / file.name)) # Perform checks assert (dest_path / 'c1').exists(), "Directory 'c1' does not exist in the destination directory" assert (dest_path / 'c2').exists(), "Directory 'c2' does not exist in the destination directory" assert (dest_path / 'c3').exists(), "Directory 'c3' does not exist in the destination directory" destfile1 = dest_path / 'c1' / 'dir1_srcfile1.name' assert destfile1.exists(), "File 'dir1_srcfile1.name' not found in 'c1' directory" assert destfile1.read_text() == dir1_tmp_txt1, "File content mismatch for 'dir1_srcfile1.name' in 'c1' directory" # Additional checks for other files can be added similarly # Example usage source_directory = '/path/to/source_directory' destination_directory = '/path/to/destination_directory' organize_files(source_directory, destination_directory)
#!/bin/bash set -eu # Install the system dependencies needed by OASIS # date > /tmp/provision.notes echo "Installing dependencies for OASIS on Ubuntu Trusty" >> /tmp/provision.notes APTOPTS=-y export DEBIAN_FRONTEND=noninteractive # pre-answer interactive configuration for Postfix debconf-set-selections <<< "postfix postfix/mailname string local.dev" debconf-set-selections <<< "postfix postfix/main_mailer_type string 'Internet Site'" # Remove repos we don't need sed -i '/trusty-backports/{s/^/#/}' /etc/apt/sources.list sed -i '/deb-src/{s/^/#/}' /etc/apt/sources.list apt-get update apt-get upgrade ${APTOPTS} # Apache apt-get install ${APTOPTS} apache2 libapache2-mod-wsgi # PostgreSQL apt-get install ${APTOPTS} postgresql postgresql-client # Mail and memcached apt-get install ${APTOPTS} postfix unzip memcached # generate secure passwords apt-get install ${APTOPTS} pwgen # We'd prefer these by pip, but they like to compile stuff during install so need lots of dev things installed. apt-get install ${APTOPTS} python-psycopg2 python-bcrypt python-lxml python-pillow python-ldap # Ubuntu pip is a bit old, but installing it means we can use it to install a newer one apt-get install ${APTOPTS} --no-install-recommends python-pip # Upgrade pip pip install --upgrade pip # otherwise bash gives us the previous version hash -r pip install --upgrade setuptools pip install pipenv echo "Ubuntu Trusty System Dependencies installed"
package suffixtree; import suffixtree.exceptions.*; import java.util.HashMap; import java.util.Collection; import java.util.Map; /** * General node usable for any tree consisting of * nodes that have from zero to multiple children. * * @param <L> Type of edge labels used in the tree */ public class Node<L> { // Maps edge labels onto the edges themselves private Map<L, Edge<L>> edges = new HashMap<>(); /** * Checks whether the node has an outgoing edge * having the specified edge label. * * @param edgeLabel the label to search for * @return true if edge does not exist * @throws IllegalArgumentException if label is null */ public boolean hasEdgeOut(final L edgeLabel) throws IllegalArgumentException { if (edgeLabel == null) { throw new IllegalArgumentException("Null label"); } else { return edges.containsKey(edgeLabel); } } /** * Adds an outgoing edge to the node with the specified label. * Upon creation, the edge automatically leads to a new node. * * @param edgeLabel the new outgoing edge's label * @return the new outgoing edge * @throws EdgeOutAlreadyExistsException if edge with the same label already exists * @throws IllegalArgumentException if label is null */ public Edge<L> addEdgeOut(final L edgeLabel) throws EdgeOutAlreadyExistsException, IllegalArgumentException { if (edgeLabel == null) { throw new IllegalArgumentException("Null label"); } else if (hasEdgeOut(edgeLabel)) { // Avoided by using !hasEdgeOut before calling method throw new EdgeOutAlreadyExistsException("Node already had edge out for " + edgeLabel); } else { final Edge<L> newEdge = new Edge<>(edgeLabel); edges.put(edgeLabel, newEdge); return newEdge; } } /** * Gets the outgoing edge with the specified label if it exists. * * @param edgeLabel label of edge to find * @return the outgoing edge * @throws NoEdgeOutException if edge with the specified label does not exist * @throws IllegalArgumentException if label is null */ public Edge<L> getEdgeOut(final L edgeLabel) throws NoEdgeOutException, IllegalArgumentException { if (edgeLabel == null) { throw new IllegalArgumentException("Null label"); } else if (!hasEdgeOut(edgeLabel)) { // Avoided by using hasEdgeOut before calling method throw new NoEdgeOutException("Node did not have edge out for " + edgeLabel); } else { return edges.get(edgeLabel); // Edge exists } } /** * Returns true if the node has no outward edges */ public boolean isLeaf() { return edges.isEmpty(); } /** * Returns the collection of values in the map */ public Collection<Edge<L>> getEdges() { return edges.values(); } /** * Replaces an outward edge with another edge and connects the * old outward edge's node to the new edge. It essentially removes * the map entry and recreates it with a new key (the new label) * and the same value (the edge) but with a changed label. * * @param oldLabel label of edge to be replaced * @param newLabel label of new edge * @throws EdgeOutAlreadyExistsException if edge with the same label already exists * @throws NoEdgeOutException if edge with the specified old label does not exist * @throws IllegalArgumentException if a label is null */ public void replaceEdge(final L oldLabel, final L newLabel) throws EdgeOutAlreadyExistsException, NoEdgeOutException, IllegalArgumentException { if (oldLabel == null || newLabel == null) { throw new IllegalArgumentException("Null label"); } else if (!hasEdgeOut(oldLabel)) { // Avoided by using hasEdgeOut before calling method throw new NoEdgeOutException("Node did not have edge out for " + oldLabel); } else if (hasEdgeOut(newLabel)) { // Avoided by using !hasEdgeOut before calling method throw new EdgeOutAlreadyExistsException("Node already had edge out for " + newLabel); } else { final Edge<L> oldEdge = edges.remove(oldLabel); edges.put(newLabel, oldEdge); // Set key oldEdge.setLabel(newLabel); // Set value } } /** * Returns "( )" */ @Override public String toString() { return "( )"; } }
<filename>src/items/actors/package-info.java<gh_stars>0 /** * Package for the different actors a population can have. */ package items.actors;
package mesos import ( "errors" ) var ( ErrInvalidResponse = errors.New("Invalid response from Mesos") ErrDoesNotExist = errors.New("The resource does not exist") ErrInternalServerError = errors.New("Mesos returned an internal server error") ErrSlaveStateLoadError = errors.New("An error was encountered loading the state of one or more Mesos slaves") ErrClusterDiscoveryError = errors.New("An error was encountered while running Mesos cluster discovery") )
#!/bin/bash #curl "http://httpbin.org/post" \ curl "" \ --include \ --request POST \ --data-urlencode "credentials[email]=$EMAIL" \ --data-urlencode "credentials[password]=$PASSWORD" \ --data-urlencode "credentials[password_confirmation]=$PASSWORD" # --header "Content-Type: application/x-www-form-urlencoded" # data output from curl doesn't have a trailing newline echo
<reponame>geyan0124/common-admin package com.common.system.entity; import java.beans.Transient; import java.util.Date; import com.baomidou.mybatisplus.annotations.TableField; import com.baomidou.mybatisplus.activerecord.Model; import com.baomidou.mybatisplus.annotations.TableName; import java.io.Serializable; import java.util.List; /** * <p> * * </p> * * @author yangxiufeng * @since 2017-09-12 */ @TableName("rc_base_area") public class RcBaseArea extends Model<RcBaseArea> { private static final long serialVersionUID = 1L; private String code; private String name; @TableField("parent_code") private String parentCode; private Integer level; @TableField("create_time") private Date createTime; @TableField("update_time") private Date updateTime; @TableField(exist=false) private List<RcBaseArea> children; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getParentCode() { return parentCode; } public void setParentCode(String parentCode) { this.parentCode = parentCode; } public Integer getLevel() { return level; } public void setLevel(Integer level) { this.level = level; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } @Override protected Serializable pkVal() { return this.code; } public List<RcBaseArea> getChildren() { return children; } public void setChildren(List<RcBaseArea> children) { this.children = children; } @Override public String toString() { return "RcBaseArea{" + "code=" + code + ", name=" + name + ", parentCode=" + parentCode + ", level=" + level + ", createTime=" + createTime + ", updateTime=" + updateTime + "}"; } }
import { DatabaseReference, FirebaseOperation, DatabaseSnapshot } from '../interfaces'; import { checkOperationCases } from '../utils'; export function createDataOperationMethod<T>(ref: DatabaseReference, operation: string) { return function dataOperation<T>(item: FirebaseOperation, value: T) { return checkOperationCases(item, { stringCase: () => ref.child(<string>item)[operation](value), firebaseCase: () => (<DatabaseReference>item)[operation](value), snapshotCase: () => (<DatabaseSnapshot<T>>item).ref[operation](value) }); } }
#!/bin/bash # 导入 .env 环境变量 source ./.env # 要备份的表 tables="admin_menu admin_permission_menu admin_permissions admin_role_menu admin_role_permissions admin_role_users admin_roles admin_settings admin_users tags types lessons tagables videos" # 执行备份 mysqldump --host="${DB_HOST}" --port=${DB_PORT} --user="${DB_USERNAME}" --password="${DB_PASSWORD}" -t ${DB_DATABASE} ${tables} > database/admin.sql
def calculateSphereVolume(radius): volume = (4/3) * (3.142) * (radius**3) return round(volume, 2) radius = 5 result = calculateSphereVolume(radius) print(result) # Output: 523.6
def get_nth(arr, n): return arr[n-1] arr = [2, 4, 7, 12, 15, 16, 23] result = get_nth(arr, 3) print(result)
import React from 'react' import classNames from 'utils/classnames' import PropTypes from 'prop-types' const SidePanel = (props) => { const { className, children } = props const modifiedClassName = classNames('side-panel', className) return ( <nav role='navigation' className={modifiedClassName}> <ul className='side-panel__list no-list-style'> {children} </ul> </nav> ) } SidePanel.propTypes = { className: PropTypes.string } export default SidePanel
#!/bin/bash ORNG='\033[0;33m' NC='\033[0m' W='\033[1;37m' LP='\033[1;35m' YLW='\033[1;33m' LBBLUE='\e[104m' 1='gmail' 2='error' 3='login' 4='password' 5='authenticator' 6='sms' 7='touchscreen' HOSTOPT='' # CredSniper Options Selections cred_opts(){ echo -e "${W}Please choose the module to use${NC}" echo -e "${YLW}1 = Gmail" echo -e "2 = Error" echo -e "3 = Login" echo -e "4 = Password" echo -e "5 = Authenticator" echo -e "6 = Sms" echo -e "7 = Touchscreen" echo -e "${LP}Gmail works best${NC}" read MODULE echo -e "${W}Would you like to enable 2 Factor Authentication?(y/n)${NC}" read 2FA_ANS if [[ ${2FA_ANS} == "y" ]]; then 2FA='--twofactor' else 2FA='' fi echo -e "${W}Would you like to enable SSL?(y/n)${NC}" read EN_SSL if [[ ${EN_SSL} == "y" ]]; then SSL='--ssl' PORT='443' echo -e "${W}Please enter the hostname to be used for SSL${NC}" read HOSTNAME HOSTOPT="--hostname ${HOSTNAME}" else SSL='' PORT='80' fi echo -e "${W}Please enter the final URL for target to be redirected to after phishing${NC}" read FURL } # CredSniper Start cd tools/CredSniper echo -e "${ORNG}" figlet -f mini "CredSniper" echo -e "${NC}" cred_opts echo -e "${LP}===============================================================================================${NC}" echo -e "${W}Module: ${YLW}${MODULE}${NC}" echo -e "${W}2FA Enabled: ${YLW}${2FA_ANS}${NC}" echo -e "${W}SSL Enabled: ${YLW}${EN_SSL}${NC}" if [[ ${EN_SSL} == "y" ]]; then echo -e "${W}SSL Hostname: ${YLW}${HOSTNAME}${NC}" else echo "" fi echo -e "${W}Final Redirection URL: ${YLW}${FURL}${NC}" echo -e "${W}Are the options above correct?(y/n)${NC}" read CORRECT if [[ ${CORRECT} == "n" ]]; then cred_opts else echo -e "${YLW}Great! Time to Start Phishing!${NC}" fi echo -e "${LP}===============================================================================================${NC}" source bin/activate python3 credsniper.py --module ${MODULE} ${2FA} --port ${PORT} --final ${FURL} ${SSL} ${HOSTOPT} cd ../.. ./tigershark
from bs4 import BeautifulSoup import requests import collections URL = "https://example.com" page = requests.get(URL) soup = BeautifulSoup(page.content, 'html.parser') text = soup.get_text().split() wordcount = collections.Counter(text) top_words = wordcount.most_common(10) print(top_words)
<filename>rangeCompress/code/python/read_Lbl.py # # Import necessary libraries # import os def lbl_Parse(fname): # # Define instrument modes # # # Subsurface sounding # SSInstrMode = { 'SS01': {'Mode': 'SS01', 'Presum': 32, 'BitsPerSample': 8}, 'SS02': {'Mode': 'SS02','Presum': 28, 'BitsPerSample': 6}, 'SS03': {'Mode': 'SS03','Presum': 16, 'BitsPerSample': 4}, 'SS04': {'Mode': 'SS04','Presum': 8, 'BitsPerSample': 8}, 'SS05': {'Mode': 'SS05','Presum': 4, 'BitsPerSample': 6}, 'SS06': {'Mode': 'SS06','Presum': 2, 'BitsPerSample': 4}, 'SS07': {'Mode': 'SS07','Presum': 1, 'BitsPerSample': 8}, 'SS08': {'Mode': 'SS08','Presum': 32, 'BitsPerSample': 6}, 'SS09': {'Mode': 'SS09','Presum': 28, 'BitsPerSample': 4}, 'SS10': {'Mode': 'SS10','Presum': 16, 'BitsPerSample': 8}, 'SS11': {'Mode': 'SS11','Presum': 8, 'BitsPerSample': 6}, 'SS12': {'Mode': 'SS12','Presum': 4, 'BitsPerSample': 4}, 'SS13': {'Mode': 'SS13','Presum': 2, 'BitsPerSample': 8}, 'SS14': {'Mode': 'SS14','Presum': 1, 'BitsPerSample': 6}, 'SS15': {'Mode': 'SS15','Presum': 32, 'BitsPerSample': 4}, 'SS16': {'Mode': 'SS16','Presum': 28, 'BitsPerSample': 8}, 'SS17': {'Mode': 'SS17','Presum': 16, 'BitsPerSample': 6}, 'SS18': {'Mode': 'SS18','Presum': 8, 'BitsPerSample': 4}, 'SS19': {'Mode': 'SS19','Presum': 4, 'BitsPerSample': 8}, 'SS20': {'Mode': 'SS20','Presum': 2, 'BitsPerSample': 6}, 'SS21': {'Mode': 'SS21','Presum': 1, 'BitsPerSample': 4}, } # # Receive only # ROInstrMode = { 'RO01': {'Presum': 32, 'BitsPerSample': 8}, 'RO02': {'Presum': 28, 'BitsPerSample': 6}, 'RO03': {'Presum': 16, 'BitsPerSample': 4}, 'RO04': {'Presum': 8, 'BitsPerSample': 8}, 'RO05': {'Presum': 4, 'BitsPerSample': 6}, 'RO06': {'Presum': 2, 'BitsPerSample': 4}, 'RO07': {'Presum': 1, 'BitsPerSample': 8}, 'RO08': {'Presum': 32, 'BitsPerSample': 6}, 'RO09': {'Presum': 28, 'BitsPerSample': 4}, 'RO10': {'Presum': 16, 'BitsPerSample': 8}, 'RO11': {'Presum': 8, 'BitsPerSample': 6}, 'RO12': {'Presum': 4, 'BitsPerSample': 4}, 'RO13': {'Presum': 2, 'BitsPerSample': 8}, 'RO14': {'Presum': 1, 'BitsPerSample': 6}, 'RO15': {'Presum': 32, 'BitsPerSample': 4}, 'RO16': {'Presum': 28, 'BitsPerSample': 8}, 'RO17': {'Presum': 16, 'BitsPerSample': 6}, 'RO18': {'Presum': 8, 'BitsPerSample': 4}, 'RO19': {'Presum': 4, 'BitsPerSample': 8}, 'RO20': {'Presum': 2, 'BitsPerSample': 6}, 'RO21': {'Presum': 1, 'BitsPerSample': 4} } # # Now parse LBL File # if os.path.isfile(fname): # # Initialize dictionary # lblDic = {'INSTR_MODE_ID': [], 'PRI': [], 'GAIN_CONTROL': [], 'COMPRESSION': [], 'RECORD_BYTES': [], 'FILE_RECORDS': [] } with open(fname) as f: lines = f.readlines() # # Remove end of line characters from list # lines = [x.rstrip('\n') for x in lines] lineCount = len(lines) # # Remove all blank rows # lines = [x for x in lines if x] print("{} empty lines removed.".format(lineCount - len(lines))) lineCount = len(lines) # # Remove comments # lines = [x for x in lines if "/*" not in x] print("{} comment lines removed.".format(lineCount - len(lines))) lineCount = len(lines) # # Start parsing # print("Parsing {} lines in LBL file.".format(lineCount)) for _i in range(lineCount): # # For this simple test all I should need out of the LBL file are: # INSTRUMENT_MODE_ID # if lines[_i].split('=')[0].strip() == 'INSTRUMENT_MODE_ID': lblDic['INSTR_MODE_ID'] = lines[_i].split('=')[1].strip() if lines[_i].split('=')[0].strip() == 'MRO:PULSE_REPETITION_INTERVAL': lblDic['PRI'] = lines[_i].split('=')[1].strip() if lines[_i].split('=')[0].strip() == 'MRO:MANUAL_GAIN_CONTROL': lblDic['GAIN_CONTROL'] = lines[_i].split('=')[1].strip() if lines[_i].split('=')[0].strip() == 'MRO:COMPRESSION_SELECTION_FLAG': lblDic['COMPRESSION'] = lines[_i].split('=')[1].strip().strip('"') if lines[_i].split('=')[0].strip() == 'RECORD_BYTES': if lblDic['RECORD_BYTES'] == []: lblDic['RECORD_BYTES'] = int(lines[_i].split('=')[1].strip()) if lines[_i].split('=')[0].strip() == 'FILE_RECORDS': if lblDic['FILE_RECORDS'] == []: lblDic['FILE_RECORDS'] = int(lines[_i].split('=')[1].strip()) # # Find the instrument mode # if lblDic['INSTR_MODE_ID'][0:2] == 'SS': lblDic['INSTR_MODE_ID'] = SSInstrMode[lblDic['INSTR_MODE_ID']] elif lblDic['INSTR_MODE_ID'][0:2] == 'RO': lblDic['INSTR_MODE_ID'] = ROInstrMode[lblDic['INSTR_MODE_ID']] return lblDic else: print("{} file not found. Please check path and try again.".format(fname)) return
public class PrimeNumber { public static void main(String[] args) { int n = 25; for(int i = 2; i <= n; i++) { boolean isPrime = true; // Check if i is prime for(int j = 2; j < i; j++) { if(i % j == 0) { isPrime = false; break; } } // Print the number if(isPrime) { System.out.print(i + " "); } } } } // Prints: 2 3 5 7 11 13 17 19 23
package io.cattle.platform.core.constants; import io.cattle.platform.core.addon.metadata.InstanceInfo; import io.cattle.platform.core.model.Instance; import io.cattle.platform.core.util.PortSpec; import io.cattle.platform.core.util.SystemLabels; import io.cattle.platform.object.util.DataAccessor; import io.cattle.platform.util.type.CollectionUtils; import io.github.ibuildthecloud.gdapi.exception.ClientVisibleException; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; public class InstanceConstants { public static final String ACTION_SOURCE_USER = "user"; public static final String ACTION_SOURCE_EXTERNAL = "external"; public static final String TYPE = "instance"; public static final String TYPE_CONTAINER = "container"; public static final String FIELD_AGENT_INSTANCE = "agentInstance"; public static final String FIELD_BLKIO_DEVICE_OPTIONS = "blkioDeviceOptions"; public static final String FIELD_BLKIO_WEIGHT = "blkioWeight"; public static final String FIELD_CAP_ADD = "capAdd"; public static final String FIELD_CAP_DROP = "capDrop"; public static final String FIELD_CGROUP_PARENT = "cgroupParent"; public static final String FIELD_COMMAND = "command"; public static final String FIELD_COUNT = "count"; public static final String FIELD_CPU_PERIOD = "cpuPeriod"; public static final String FIELD_CPU_QUOTA = "cpuQuota"; public static final String FIELD_CPU_SET = "cpuSetCpu"; public static final String FIELD_CPUSET_MEMS = "cpuSetMems"; public static final String FIELD_CPU_SHARES = "cpuShares"; public static final String FIELD_CREATE_INDEX = "createIndex"; public static final String FIELD_CREATE_ONLY = "createOnly"; public static final String FIELD_DATA_VOLUME_MOUNTS = "dataVolumeMounts"; public static final String FIELD_DATA_VOLUMES = "dataVolumes"; public static final String FIELD_DEPENDS_ON = "dependsOn"; public static final String FIELD_DEPLOYMENT_UNIT_ID = "deploymentUnitId"; public static final String FIELD_DEPLOYMENT_UNIT_UUID = "deploymentUnitUuid"; public static final String FIELD_DEVICES = "devices"; public static final String FIELD_DISKS = "disks"; public static final String FIELD_DNS = "dns"; public static final String FIELD_DNS_OPT = "dnsOpt"; public static final String FIELD_DNS_SEARCH = "dnsSearch"; public static final String FIELD_DOCKER_INSPECT = "dockerInspect"; public static final String FIELD_DOCKER_IP = "dockerIp"; public static final String FIELD_DOMAIN_NAME = "domainName"; public static final String FIELD_ENTRY_POINT = "entryPoint"; public static final String FIELD_ENVIRONMENT = "environment"; public static final String FIELD_EXIT_CODE = "exitCode"; public static final String FIELD_EXPOSE = "expose"; public static final String FIELD_EXTRA_HOSTS = "extraHosts"; public static final String FIELD_GROUP_ADD = "groupAdd"; public static final String FIELD_HEALTH_CHECK = "healthCheck"; public static final String FIELD_HEALTHCHECK_STATES = "healthcheckStates"; public static final String FIELD_HOSTNAME = "hostname"; public static final String FIELD_IMAGE_PRE_PULL = "prePullOnUpgrade"; @Deprecated public static final String FIELD_IMAGE_UUID = "imageUuid"; public static final String FIELD_IMAGE = "image"; public static final String FIELD_IPC_CONTAINER_ID = "ipcContainerId"; public static final String FIELD_IPC_MODE = "ipcMode"; public static final String FIELD_ISOLATION = "isolation"; public static final String FIELD_KERNEL_MEMORY = "kernelMemory"; public static final String FIELD_LABELS = "labels"; public static final String FIELD_LAST_START = "lastStart"; public static final String FIELD_LAUNCH_CONFIG_NAME = "launchConfigName"; public static final String FIELD_LINKS = "instanceLinks"; public static final String FIELD_LB_RULES_ON_REMOVE = "lbRulesOnRemove"; public static final String FIELD_LOG_CONFIG = "logConfig"; public static final String FIELD_LXC_CONF = "lxcConf"; public static final String FIELD_MANAGED_IP = "managedIp"; public static final String FIELD_MEMORY = "memory"; public static final String FIELD_MEMORY_RESERVATION = "memoryReservation"; public static final String FIELD_MEMORY_SWAP = "memorySwap"; public static final String FIELD_MEMORY_SWAPPINESS = "memorySwappiness"; public static final String FIELD_METADATA = "metadata"; public static final String FIELD_MOUNTS = "mounts"; public static final String FIELD_NETWORK_CONTAINER_ID = "networkContainerId"; public static final String FIELD_NETWORK_IDS = "networkIds"; public static final String FIELD_NETWORK_MODE = "networkMode"; public static final String FIELD_OOMKILL_DISABLE = "oomKillDisable"; public static final String FIELD_OOM_SCORE_ADJ = "oomScoreAdj"; public static final String FIELD_PID_CONTAINER_ID = "pidContainerId"; public static final String FIELD_PID_MODE = "pidMode"; public static final String FIELD_PORT_BINDINGS = "publicEndpoints"; public static final String FIELD_PORTS = "ports"; public static final String FIELD_PREVIOUS_REVISION_ID = "previousRevisionId"; public static final String FIELD_PRIMARY_IP_ADDRESS = "primaryIpAddress"; public static final String FIELD_PRIMARY_MAC_ADDRESSS = "primaryMacAddress"; public static final String FIELD_PRIMARY_NETWORK_ID = "primaryNetworkId"; public static final String FIELD_PRIVILEGED = "privileged"; public static final String FIELD_PUBLISH_ALL_PORTS = "publishAllPorts"; public static final String FIELD_READ_ONLY = "readOnly"; public static final String FIELD_REQUESTED_HOST_ID = "requestedHostId"; public static final String FIELD_REQUESTED_IP_ADDRESS = "requestedIpAddress"; public static final String FIELD_RESTART_POLICY = "restartPolicy"; public static final String FIELD_RETAIN_IP = "retainIp"; public static final String FIELD_REVISION_CONFIG = "config"; public static final String FIELD_REVISION_ID = "revisionId"; public static final String FIELD_SECRETS = "secrets"; public static final String FIELD_SECURITY_OPT = "securityOpt"; public static final String FIELD_SERVICE_ID = "serviceId"; public static final String FIELD_SERVICE_IDS = "serviceIds"; public static final String FIELD_SERVICE_INDEX = "serviceIndex"; public static final String FIELD_SHM_SIZE = "shmSize"; public static final String FIELD_SHOULD_RESTART = "shouldRestart"; public static final String FIELD_SIDEKICK_TO = "sidekickTo"; public static final String FIELD_STACK_ID = "stackId"; public static final String FIELD_START_RETRY_COUNT = "startRetryCount"; public static final String FIELD_STDIN_OPEN = "stdinOpen"; public static final String FIELD_STOPPED = "stopped"; public static final String FIELD_STOP_SIGNAL = "stopSignal"; public static final String FIELD_STOP_SOURCE = "stopSource"; public static final String FIELD_STORAGE_OPT = "storageOpt"; public static final String FIELD_SYSCTLS = "sysctls"; public static final String FIELD_SYSTEM_CONTAINER = "systemContainer"; public static final String FIELD_TMPFS = "tmpfs"; public static final String FIELD_TTY = "tty"; public static final String FIELD_ULIMITS = "ulimits"; public static final String FIELD_USER = "user"; public static final String FIELD_UTS = "uts"; public static final String FIELD_VCPU = "vcpu"; public static final String FIELD_VOLUME_DRIVER = "volumeDriver"; public static final String FIELD_VOLUMES_FROM = "dataVolumesFrom"; public static final String FIELD_WORKING_DIR = "workingDir"; public static final String DOCKER_ATTACH_STDIN = "AttachStdin"; public static final String DOCKER_ATTACH_STDOUT = "AttachStdout"; public static final String DOCKER_TTY = "Tty"; public static final String DOCKER_CMD = "Cmd"; public static final String DOCKER_CONTAINER = "Container"; public static final String PULL_NONE = "none"; public static final String PULL_ALL = "all"; public static final String PULL_EXISTING = "existing"; public static final String PROCESS_DATA_NO_OP = "containerNoOpEvent"; public static final String REMOVE_OPTION = "remove"; public static final String PROCESS_ALLOCATE = "instance.allocate"; public static final String PROCESS_DEALLOCATE = "instance.deallocate"; public static final String PROCESS_START = "instance.start"; public static final String PROCESS_STOP = "instance.stop"; public static final String KIND_CONTAINER = "container"; public static final String KIND_VIRTUAL_MACHINE = "virtualMachine"; public static final String STATE_RUNNING = "running"; public static final String STATE_STOPPED = "stopped"; public static final String STATE_STOPPING = "stopping"; public static final String STATE_STARTING = "starting"; public static final String STATE_RESTARTING = "restarting"; public static final String ON_STOP_REMOVE = "remove"; public static final String EVENT_INSTANCE_FORCE_STOP = "compute.instance.force.stop"; public static final String VOLUME_CLEANUP_STRATEGY_NONE = "none"; public static final String VOLUME_CLEANUP_STRATEGY_UNNAMED = "unnamed"; public static final String VOLUME_CLEANUP_STRATEGY_ALL = "all"; public static final Set<String> VOLUME_REMOVE_STRATEGIES = CollectionUtils.set( VOLUME_CLEANUP_STRATEGY_NONE, VOLUME_CLEANUP_STRATEGY_UNNAMED, VOLUME_CLEANUP_STRATEGY_ALL); public static final List<String> validStatesForStop = Arrays.asList(InstanceConstants.STATE_RUNNING, InstanceConstants.STATE_STARTING); public static final List<String> skipStatesForStop = Arrays.asList(CommonStatesConstants.REMOVED, CommonStatesConstants.REMOVING, InstanceConstants.STATE_STOPPED, InstanceConstants.STATE_STOPPING); public static final List<String> validStatesForStart = Arrays.asList(InstanceConstants.STATE_STOPPED); public static final List<String> skipStatesForStart = Arrays.asList(CommonStatesConstants.REMOVED, CommonStatesConstants.REMOVING, InstanceConstants.STATE_RUNNING, InstanceConstants.STATE_STARTING); public static boolean isRancherAgent(Instance instance) { Map<String, Object> labels = DataAccessor.fieldMap(instance, InstanceConstants.FIELD_LABELS); return ("rancher-agent".equals(labels.get("io.rancher.container.system")) && "rancher-agent".equals(instance.getName())); } public static List<PortSpec> getPortSpecs(Instance instance) { List<PortSpec> result = new ArrayList<>(); for (String portSpec : DataAccessor.fieldStringList(instance, FIELD_PORTS)) { try { result.add(new PortSpec(portSpec)); } catch (ClientVisibleException e) { } } return result; } public static boolean isNativeKubernetesPOD(InstanceInfo instance) { return instance.isHidden() && instance.isNativeContainer() && instance.getLabels() != null && "POD".equals(instance.getLabels().get(SystemLabels.LABEL_K8S_CONTAINER_NAME)) && StringUtils.isBlank(instance.getLabels().get("annotation." + SystemLabels.LABEL_RANCHER_UUID)); } public static boolean isKubernetes(Instance instance) { if (instance == null) { return false; } return ClusterConstants.ORCH_KUBERNETES.equals(DataAccessor.getLabel(instance, SystemLabels.LABEL_ORCHESTRATION)); } }
#!/bin/bash source ./venv/bin/activate while true do python3 Source/mailfilter.py --interactive done
#!/bin/bash set -ex /usr/bin/ossutil config -e $ENDPOINT -i $ACCESS_KEY_ID -k $ACCESS_KEY_SECRET /usr/bin/ossutil $@
// // XHLoadingNavigationItemTitleView.h // XHLoadingNavigationItemTitleView // // Created by qtone-1 on 14-4-10. // Copyright (c) 2014年. All rights reserved. // #import <UIKit/UIKit.h> @interface XHLoadingNavigationItemTitleView : UIView @property (nonatomic, strong) UIColor *titleColor; // default is [UIColor whiteColor] @property (nonatomic, strong) UIFont *titleFont; // default is @property (nonatomic, assign, readonly) BOOL animating; // default is NO + (XHLoadingNavigationItemTitleView *)initNavigationItemTitleView; - (void)setIndicatorView:(UIView *)indicatorView; - (void)setTitle:(NSString *)title; - (void)startAnimating; - (void)stopAnimating; @end
def filter_strings(list_of_strings): return list(filter(lambda x: x.isalpha(), list_of_strings)) print (filter_strings(list_of_strings)) # Output: ['Hello', 'World', 'This is a string.']
#!/usr/bin/env sh set -e arch=$1 if [[ $arch == "" ]]; then arch=amd64 fi BASEIMAGE=amd64/alpine:3.6 if [[ $arch == "arm64" ]]; then BASEIMAGE=arm64v8/alpine:3.6 fi root_path=$(dirname $0)/../.. cni_tag=$(cat ${root_path}/version/next/CNI_Plugins) agent_tag=$(cat ${root_path}/version/next/CNI_Agent) image=ccr.ccs.tencentyun.com/tkeimages/tke-cni-agent echo "build cni-agent linux-${arch}_${agent_tag} with cni-plugins ${cni_tag}" docker build --build-arg BASEIMAGE=${BASEIMAGE} --build-arg arch=${arch} --build-arg cni_tag=${cni_tag} -t ${image}:linux-${arch}_${agent_tag} -f ${root_path}/scripts/next/Dockerfile . docker push ccr.ccs.tencentyun.com/tkeimages/tke-cni-agent:linux-${arch}_${agent_tag}
package csv // Path is the name of CSV file ready for PostgresSQL copy command. const Path = "cnpj.csv.gz"
#!/bin/bash # Install test # include err() and new() functions and creates $dir . ./lib.sh new "Set up installdir $dir" new "Make DESTDIR install" (cd ..; make DESTDIR=$dir install) if [ $? -ne 0 ]; then err fi new "Check installed files" if [ ! -d $dir/usr ]; then err $dir/usr fi if [ ! -d $dir/www-data ]; then err $dir/www-data fi if [ ! -f $dir/usr/local/share/clixon/clixon-config* ]; then err $dir/usr/local/share/clixon/clixon-config* fi if [ ! -h $dir/usr/local/lib/libclixon.so ]; then err $dir/usr/local/lib/libclixon.so fi if [ ! -h $dir/usr/local/lib/libclixon_backend.so ]; then err $dir/usr/local/lib/libclixon_backend.so fi new "Make DESTDIR install include" (cd ..; make DESTDIR=$dir install-include) if [ $? -ne 0 ]; then err fi new "Check installed includes" if [ ! -f $dir/usr/local/include/clixon/clixon.h ]; then err $dir/usr/local/include/clixon/clixon.h fi new "Make DESTDIR uninstall" (cd ..; make DESTDIR=$dir uninstall) if [ $? -ne 0 ]; then err fi new "Check remaining files" f=$(find $dir -type f) if [ -n "$f" ]; then err "$f" fi new "Check remaining symlinks" l=$(find $dir -type l) if [ -n "$l" ]; then err "$l" fi
#!/bin/bash kubectl delete -f deploy
package co.infinum.goldfinger; /** * Legacy implementation for pre-Marshmallow devices. */ class LegacyGoldfinger implements Goldfinger { @Override public boolean hasFingerprintHardware() { return false; } @Override public boolean hasEnrolledFingerprint() { return false; } @Override public void authenticate(Callback callback) { } @Override public void decrypt(String keyName, String value, Callback callback) { } @Override public void encrypt(String keyName, String value, Callback callback) { } @Override public void cancel() { } }
<gh_stars>0 package uk.ac.glos.ct5057.assignment.s1609415.algorithms; import uk.ac.glos.ct5057.assignment.s1609415.map.MapGraph; import java.util.ArrayList; import java.util.HashMap; /** * This class searches for the shortest path between two points using Dijkstra's Algorithm * * @author <NAME> * @version 1.0 */ public class DijkstrasAlgorithm { public static ArrayList<Character> shortestRoute(MapGraph graph, Character startNode, Character endNode) { ArrayList<Character> searchedNodes = new ArrayList<>(); HashMap<Character, ArrayList<Integer>> allDistances = new HashMap<>(); ArrayList<Character> route; Character progressNode = startNode; if (progressNode != endNode) { while (progressNode != endNode) { searchedNodes.add(progressNode); // add current node to already searched nodes addDistances(allDistances, searchedNodes, progressNode, graph.getEdges(progressNode)); // updates distances based on current node progressNode = nearestUncheckedNode(allDistances, searchedNodes); // find the closest node if (progressNode == null) { route = new ArrayList<>(); return route; } } route = retraceRoute(allDistances, searchedNodes, startNode, endNode); } else { route = new ArrayList<>(); route.add(startNode); } return route; } private static void addDistances(HashMap<Character, ArrayList<Integer>> allDistances, ArrayList<Character> searchedNodes, Character progressNode, HashMap<Character, Integer> edges) { Integer progressMax; Integer nodeMax; ArrayList<Integer> progressDistances; ArrayList<Integer> nodeDistances; Integer newMax; if (allDistances.containsKey(progressNode)) { // if the node is already in the list progressDistances = allDistances.get( progressNode ); progressMax = progressDistances.get( progressDistances.size()-1 ); } else { progressMax = 0; } for (Character node: edges.keySet()) { if (!searchedNodes.contains(node)) { if (allDistances.containsKey(node)) { // if the node is already in the list nodeDistances = allDistances.get(node); nodeMax = nodeDistances.get( nodeDistances.size()-1 ); } else { allDistances.put(node, new ArrayList<>()); nodeMax = Integer.MAX_VALUE; // nodes default to infinity } // calculate distance value for node newMax = progressMax + edges.get(node); if (newMax > nodeMax) { newMax = nodeMax; } // each checked node is a unique index for all node distance arrays // for new node or node that has skipped an update add missing indexes nodeDistances = allDistances.get(node); for (int i = nodeDistances.size(); i < searchedNodes.indexOf(progressNode); i++) { nodeDistances.add(nodeMax); } allDistances.get(node).add( newMax ); } } } private static Character nearestUncheckedNode(HashMap<Character, ArrayList<Integer>> allDistances, ArrayList<Character> searchedNodes) { Integer nodeMax; ArrayList<Integer> nodeDistances; Integer shortest = null; Character nearest = null; boolean first = true; // find node with shortest distance that is not in the list of searched nodes for (Character node: allDistances.keySet()) { if (!searchedNodes.contains(node)) { nodeDistances = allDistances.get(node); nodeMax = nodeDistances.get( nodeDistances.size()-1 ); if (first) { shortest = nodeMax; nearest = node; first = false; } else if (shortest > nodeMax){ shortest = nodeMax; nearest = node; } } } return nearest; } private static ArrayList<Character> retraceRoute(HashMap<Character, ArrayList<Integer>> allDistances, ArrayList<Character> searchedNodes, Character startNode, Character endNode) { ArrayList<Character> route = new ArrayList<>(); Character progressNode; ArrayList<Integer> nodeDistances; Integer currentLength; Integer nextLength; int nextNode = 0; progressNode = endNode; route.add(endNode); while (progressNode != startNode) { nodeDistances = allDistances.get(progressNode); if (nodeDistances.size() > 1) { // for current node find that first index that had the current distance for (int i = nodeDistances.size() - 1; i > 0; i--) { currentLength = nodeDistances.get(i); nextLength = nodeDistances.get(i - 1); if (!nextLength.equals(currentLength)) { nextNode = i; break; } if (i == 1) { nextNode = 0; break; } } } else { nextNode = 0; } // find the node who's index matches the first index position progressNode = searchedNodes.get(nextNode); route.add(progressNode); } return route; } }
#coding:utf-8 import numpy as np b = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) print(b) print("="*40) #知识点:(1)修改shape属性和调用reshape()方法;(2)-1的使用;(3)共享内存 # # # 当某个轴为-1时,将根据数组元素的个数自动计算此轴的长度 b.shape = 2, -1 print(b) print(b.shape) print("="*40) # b.shape = 3, 4 print(b) print("="*40) # # # # 使用reshape方法,可以创建改变了尺寸的新数组,原数组的shape保持不变 c = b.reshape((4, -1)) print("b = \n", b) print('c = \n', c) print("="*40) # # # # 数组b和c共享内存,修改任意一个将影响另外一个 b[0][1] = 20 # print("b = \n", b) # print("c = \n", c)
package com.learning.Springboot.tutorial.controller; import java.util.List; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.learning.Springboot.tutorial.entity.Department; import com.learning.Springboot.tutorial.exceptions.DepartmentNotFoundException; import com.learning.Springboot.tutorial.service.DepartmentService; @RestController public class DepartmentController { @Autowired private DepartmentService deptService; //Logger concept starts here private static final Logger LOGGER = LoggerFactory.getLogger(DepartmentController.class); @PostMapping("/departments") public Department saveDepartment(@Valid @RequestBody Department department) { LOGGER.info("Inside save department method"); return deptService.saveDepartment(department); } @GetMapping("departments/{deptId}") public Department getDepartment(@PathVariable(value = "deptId") Long deptId) throws DepartmentNotFoundException { LOGGER.info("Inside get department by ID method"); return deptService.getDepartment(deptId); } @GetMapping("departments/all") public List<Department> getAllDepartments(){ LOGGER.info("Inside get all department method"); return deptService.getAllDepartments(); } @DeleteMapping("departments/{id}") public String deleteDepartment(@PathVariable(value="id") Long deptId) { return deptService.deleteDepartment(deptId); } @PutMapping("departments/{id}") public Department updateDepartment(@PathVariable(value="id") Long deptId, @RequestBody Department department) { return deptService.updateDepartment(deptId,department); } @GetMapping("departments/name/{name}") public Department getDepartmentByName(@PathVariable(value="name") String departmentName) { return deptService.getDepartmentByName(departmentName); } }
from django.utils import timezone from django.http import Http404 from django.shortcuts import get_object_or_404 from django.contrib.auth.models import User from django.db.models import Q from taggit.models import Tag from rest_framework.views import APIView from rest_framework.generics import ListAPIView from rest_framework.response import Response from rest_framework import status from assets.models import Asset, Application, Component, License from assets import serializers from assets.views.common import get_assets_query, get_simple_search_qry class AssetList(APIView): #queryset = Asset.objects.all() #serializer_class = serializers.AssetSerializer def get_queryset(self): appslug = self.kwargs.get('appslug', None) cslug = self.kwargs.get('cslug', None) tagslug = self.request.query_params.get('tag', None) author_name = self.request.query_params.get('author', None) version = self.request.query_params.get('appversion', None) qry, _t = get_assets_query(appslug=appslug, cslug=cslug, tslug=tagslug, verstring=version) if author_name is not None: author = get_object_or_404(User, username=author_name) qry = qry & Q(author=author) query = self.request.query_params.get('query', None) if query is not None: search = get_simple_search_qry(query) qry = qry & search return Asset.objects.filter(qry) # Retrieve a list of assets def get(self, request, appslug=None, cslug=None, format=None): assets = self.get_queryset() serializer = serializers.AssetSerializer(assets, many=True) return Response(serializer.data) # Create new asset def post(self, request, format=None): serializer = serializers.AssetSerializer(data=request.data) if serializer.is_valid(): serializer.save(author = self.request.user, pub_date=timezone.now()) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class SearchList(ListAPIView): serializer_class = serializers.AssetSerializer def get_queryset(self): query = self.request.query_params['query'] qry = get_simple_search_qry(query) return Asset.objects.filter(qry) class AssetDetail(APIView): queryset = Asset.objects.all() #serializer_class = AssetSerializer def get_object(self, pk): return get_object_or_404(Asset, pk=pk) # Get details for one asset def get(self, request, pk, format=None): asset = self.get_object(pk) serializer = serializers.AssetSerializer(asset) return Response(serializer.data) # Update one asset def put(self, request, pk, format=None): asset = self.get_object(pk) serializer = serializers.AssetSerializer(asset, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class ApplicationList(ListAPIView): serializer_class = serializers.ApplicationSerializer queryset = Application.objects.all() class ComponentList(ListAPIView): serializer_class = serializers.ComponentSerializer def get_queryset(self): appslug = self.kwargs.get('appslug', None) app = get_object_or_404(Application, slug=appslug) return app.component_set.all() class LicenseList(ListAPIView): serializer_class = serializers.LicenseSerializer queryset = License.objects.all() class TagList(ListAPIView): serializer_class = serializers.TagSerializer queryset = Tag.objects.all()
<filename>spec/models/parsers/edi/etf/policy_loop_spec.rb require 'spec_helper' describe Parsers::Edi::Etf::PolicyLoop do describe 'id' do let(:id) { '1234' } let(:raw_loop) { {"REFs" => [['', qualifier, id]]} } let(:policy_loop) { Parsers::Edi::Etf::PolicyLoop.new(raw_loop) } context 'qualified as carrier assigned policy ID' do let(:qualifier) { 'X9' } it 'returns the id in REF02' do expect(policy_loop.id).to eq id end end context 'not qualified as a carrier assigned policy ID' do let(:qualifier) { ' ' } it 'returns nil' do expect(policy_loop.id).to eq nil end end end describe 'coverage_start' do let(:date) { '19800101'} let(:raw_loop) { {"DTPs" => [['', qualifier, '', date]]} } let(:policy_loop) { Parsers::Edi::Etf::PolicyLoop.new(raw_loop) } context 'qualified as "Benefit Begin"' do let(:qualifier) { '348' } it 'returns the date from dtp03' do expect(policy_loop.coverage_start).to eq date end end context 'not qualified as "Benefit Begin"' do let(:qualifier) { ' ' } it 'returns nil' do expect(policy_loop.coverage_start).to eq nil end end end describe 'coverage_end' do let(:date) { '19800101'} let(:raw_loop) { {"DTPs" => [['', qualifier, '', date]]} } let(:policy_loop) { Parsers::Edi::Etf::PolicyLoop.new(raw_loop) } context 'qualified as "Benefit End"' do let(:qualifier) { '349' } it 'returns the date from dtp03' do expect(policy_loop.coverage_end).to eq date end end context 'not qualified as "Benefit End"' do let(:qualifier) { ' ' } it 'returns nil' do expect(policy_loop.coverage_end).to eq nil end end end describe 'action' do let(:raw_loop) { {"HD" => ['', type_code]} } let(:policy_loop) { Parsers::Edi::Etf::PolicyLoop.new(raw_loop) } context 'given Change type code' do let(:type_code) { '001' } it 'returns change symbol' do expect(policy_loop.action).to eq :change end end context 'given Stop type code' do let(:type_code) { '024' } it 'returns stop symbol' do expect(policy_loop.action).to eq :stop end end context 'given Audit type code' do let(:type_code) { '030' } it 'returns audit symbol' do expect(policy_loop.action).to eq :audit end end context 'given Reinstate type code' do let(:type_code) { '025' } it 'returns reinstate symbol' do expect(policy_loop.action).to eq :reinstate end end context 'given an undefined type code' do let(:type_code) { 'undefined' } it 'returns add symbol' do expect(policy_loop.action).to eq :add end end end describe '#eg_id' do let(:eg_id) { '1234' } let(:raw_loop) { { "REFs" => [['', '1L', eg_id]] } } let(:policy_loop) { Parsers::Edi::Etf::PolicyLoop.new(raw_loop) } it 'exposes the eg_id from the health coverage loop (2300)' do expect(policy_loop.eg_id).to eq eg_id end end describe '#hios_id' do let(:hios_id) { '1234' } let(:raw_loop) { { "REFs" => [['', 'CE', hios_id]] } } let(:policy_loop) { Parsers::Edi::Etf::PolicyLoop.new(raw_loop) } it 'exposes the hios_id from the health coverage loop (2300)' do expect(policy_loop.hios_id).to eq hios_id end end describe '#canceled?' do context 'when start and end date are equal' do let(:start_date) { '19800101'} let(:end_date) { start_date } let(:start_date_qualifier) { '348' } let(:end_date_qualifier) { '349' } let(:raw_loop) do { "DTPs" => [ ['', start_date_qualifier, '', start_date], ['', end_date_qualifier, '', end_date] ] } end let(:policy_loop) { Parsers::Edi::Etf::PolicyLoop.new(raw_loop) } it 'is a cancel' do expect(policy_loop.canceled?).to eq true end end end end
<filename>server/src/intercept/server/NoRouteException.java package intercept.server; import java.net.URI; public class NoRouteException extends RuntimeException { public NoRouteException(URI url) { super("No route available for " + url); } }
import sqlalchemy as sa from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship Base = declarative_base() class Category(Base): __tablename__ = 'category' id = sa.Column('id', sa.Integer, primary_key=True) class SubCategory(Base): __tablename__ = 'sub_category' id = sa.Column('id', sa.Integer, primary_key=True) category_id = sa.Column('category_id', sa.Integer, sa.ForeignKey('category.id')) products = relationship('Product', backref='sub_category') class Product(Base): __tablename__ = 'product' id = sa.Column('id', sa.Integer, primary_key=True) sub_category_id = sa.Column('sub_category_id', sa.Integer, sa.ForeignKey('sub_category.id')) sub_category = relationship('SubCategory', back_populates='products')
<reponame>hangmann/Temperature-Management-and-Prediction<filename>TMS_Host/TemperatureViewer/src/controller/C_HeaterControl.java package controller; import java.io.IOException; import model.M_TemperatureMeasurementSystem; import view.V_HeaterControl; public class C_HeaterControl { V_HeaterControl v_HC; C_TemperatureMeasurementSystem c_TMS; public C_HeaterControl(C_TemperatureMeasurementSystem c_TMS) { this.c_TMS = c_TMS; v_HC = new V_HeaterControl(c_TMS, this); } public void wait(int duration) { try { Thread.sleep(duration); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void startCalibration(){ setAllHeaters(M_TemperatureMeasurementSystem.HEATER_CALIBRATION_LEVEL ); c_TMS.getSerialCommunication().appendText("\nStarting Calibration...\n"); try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } startExperiment(); } public void stopCalibration(){ setAllHeaters(0); try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void stopHeaters(){ //controller.stopCalibration(); setAllHeaters(0); } public void sendMsg(String msg, boolean n) { try { if (n) msg = msg + "!"; for (int i=0; i<msg.getBytes().length;i++) { c_TMS.getModel().getOut_stream().write(msg.getBytes()[i]); } c_TMS.getModel().getOut_stream().flush(); c_TMS.getModel().getOut_stream().close(); c_TMS.renewOutputStream(); } catch (IOException e) { // System.out.println(e); } } public void setAllHeaters(int j){ sendMsg("setallheaters " + (j),true); } public void setHeater(int number, int intensity) { sendMsg("setheater " + number + " " + (intensity), true); } public void set5Heaters(int h0, int h1, int h2, int h3, int h4, int intensity) { sendMsg("set5heaters " + (h0) + " " +(h1) + " " + (h2) + " " + (h3) + " " + (h4) + " " + (intensity), true); } public void setTopHeaters(int intensity) { sendMsg("settopheaters " + (intensity), true); } public void setBottomHeaters(int intensity) { sendMsg("setbottomheaters " + (intensity), true); } public void setRightHeaters(int intensity) { sendMsg("setrightheaters " + (intensity), true); } public void setLeftHeaters(int intensity) { sendMsg("setleftheaters " + (intensity), true); } public void getHeater(int number) { sendMsg("getheater " + (number),true); } public void getTemperature() { sendMsg("gettemp",true); } public void getCounts() { sendMsg("getcounts",true); } public void getVCC() { sendMsg("getvcc",true); } public void stopExperiment() { sendMsg("stopex",true); } public void startExperiment() { sendMsg("startex",true); } public void toggleOutput() { sendMsg("toggleoutput",true); } public void setOutput(int parseInt) { sendMsg("setoutput " + (parseInt),true); } public String idToString(int id) { String si; if (id<10) si = "0"+id; else si=String.valueOf(id); return si; } }
#!/bin/sh cde chemdner prepare_tokens data/chemdner-1.0/evaluation.abstracts.txt --annotations data/chemdner-1.0/evaluation.annotations.txt --tout data/cde-ner/chemdner-evaluation-tag.txt --lout data/cde-ner/chemdner-evaluation-label.txt cde chemdner prepare_tokens data/chemdner-1.0/training.abstracts.txt --annotations data/chemdner-1.0/training.annotations.txt --tout data/cde-ner/chemdner-training-tag.txt --lout data/cde-ner/chemdner-training-label.txt cde chemdner prepare_tokens data/chemdner-1.0/development.abstracts.txt --annotations data/chemdner-1.0/development.annotations.txt --tout data/cde-ner/chemdner-development-tag.txt --lout data/cde-ner/chemdner-development-label.txt
SELECT department_name FROM employee WHERE id IN (SELECT MIN(id) FROM employee GROUP BY department_name)
#!/bin/sh mkdir -p ~/backup/test1 mkdir -p ~/backup/test2 mkdir -p ~/backup/test3 echo "store1" > ~/backup/test1/test1.txt echo "store2" > ~/backup/test1/test2.txt echo "store3" > ~/backup/test2/test3.txt echo "store4" > ~/backup/test2/test4.txt echo "store5" > ~/backup/test3/test5.txt echo "store6" > ~/backup/test3/test6.txt
<gh_stars>10-100 package io.jenkins.plugins.coverage.model; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.*; /** * Tests the class {@link CoverageMetric}. * * @author <NAME> */ class CoverageMetricTest { @Test void shouldSortMetrics() { List<CoverageMetric> all = new ArrayList<>(); all.add(CoverageMetric.MODULE); all.add(CoverageMetric.PACKAGE); all.add(CoverageMetric.FILE); all.add(CoverageMetric.CLASS); all.add(CoverageMetric.LINE); all.add(CoverageMetric.BRANCH); all.add(CoverageMetric.INSTRUCTION); Collections.sort(all); verifyOrder(all); Collections.reverse(all); assertThat(all).containsExactly( CoverageMetric.BRANCH, CoverageMetric.INSTRUCTION, CoverageMetric.LINE, CoverageMetric.CLASS, CoverageMetric.FILE, CoverageMetric.PACKAGE, CoverageMetric.MODULE); Collections.sort(all); verifyOrder(all); } private void verifyOrder(final List<CoverageMetric> all) { assertThat(all).containsExactly( CoverageMetric.MODULE, CoverageMetric.PACKAGE, CoverageMetric.FILE, CoverageMetric.CLASS, CoverageMetric.LINE, CoverageMetric.INSTRUCTION, CoverageMetric.BRANCH ); } }
import React, {useState, useEffect, useRef} from 'react'; import Axios from 'axios'; import * as am4core from '@amcharts/amcharts4/core'; import * as am4charts from '@amcharts/amcharts4/charts'; const PriceChart = () => { const chart = useRef(null); const [chartData, setChartData] = useState([]); useEffect(() => { async function getData () { Axios.get('data.csv').then(result => { let data = []; result.data.split("\n").forEach(row => { let values = row.split(','); data.push({timestamp: values[0], price: values[1]}); }); setChartData(data); }); } getData(); let chart = am4core.create('chartdiv', am4charts.XYChart); chart.data = chartData; // Create axes var dateAxis = chart.xAxes.push(new am4charts.DateAxis()); dateAxis.title.text = "Timestamp"; dateAxis.renderer.minGridDistance = 30; // Create value axis var valueAxis = chart.yAxes.push(new am4charts.ValueAxis()); valueAxis.title.text = "Price"; // Create series var series = chart.series.push(new am4charts.LineSeries()); series.dataFields.valueY = "price"; series.dataFields.dateX = "timestamp"; series.tooltipText = "{value}" series.strokeWidth = 2; series.minBulletDistance = 15; // Drop-shaped tooltips series.tooltip.background.cornerRadius = 20; series.tooltip.background.strokeOpacity = 0; series.tooltip.pointerOrientation = "vertical"; series.tooltip.label.minWidth = 40; series.tooltip.label.minHeight = 40; series.tooltip.label.textAlign = "middle"; series.tooltip.label.textValign = "middle"; // Make bullets grow on hover var bullet = series.bullets.push(new am4charts.CircleBullet()); bullet.circle.strokeWidth = 2; bullet.circle.radius = 4; bullet.circle.fill = am4core.color("#FFF"); var bullethover = bullet.states.create("hover"); bullethover.properties.scale = 1.3; // Make a panning cursor chart.cursor = new am4charts.XYCursor(); chart.cursor.behavior = "panXY"; chart.cursor.xAxis = dateAxis; chart.cursor.snapToSeries = series; // Create vertical scrollbar and place it before the value axis chart.scrollbarY = new am4core.Scrollbar(); chart.scrollbarY.parent = chart.leftAxesContainer; chart.scrollbarY.toBack(); // Create a horizontal scrollbar with preview and place it underneath the date axis chart.scrollbarX = new am4charts.XYChartScrollbar(); chart.scrollbarX.series.push(series); chart.scrollbarX.parent = chart.bottomAxesContainer; }, [chartData]); return <div id="chartdiv" style={{width: "100%", height: "500px"}} ref={chart} /> }; export default PriceChart;
function mockSendRequest(provider, expectedParams, expectedResponse) { const sendRequestSpy = jest.spyOn(provider, 'sendRequest'); return { verifySendRequest: (expectedParams) => { expect(sendRequestSpy).toHaveBeenCalled(); const params = sendRequestSpy.mock.calls[0][0]; expect(params).toMatchObject(expectedParams); }, setResponse: (response) => { sendRequestSpy.mockResolvedValue(response); } }; } // Example usage const provider = { sendRequest: jest.fn() }; const mock = mockSendRequest(provider, { headers: { 'X-API-KEY': 'test-client-id' } }, 'foo'); engine.send('eth_peerCount', []).then((value) => { mock.verifySendRequest({ headers: { 'X-API-KEY': 'test-client-id' } }); expect(value).toBe('foo'); done(); });
/* * Copyright 2017 - Swiss Data Science Center (SDSC) * A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and * Eidgenössische Technische Hochschule Zürich (ETHZ). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package models import java.time.Instant import play.api.libs.functional.syntax._ import play.api.libs.json.{ JsPath, JsValue, OFormat } case class Event( id: Option[Long], obj: JsValue, action: String, attr: JsValue, created: Instant ) object Event { def format: OFormat[Event] = ( ( JsPath \ "id" ).formatNullable[Long] and ( JsPath \ "obj" ).format[JsValue] and ( JsPath \ "action" ).format[String] and ( JsPath \ "attr" ).format[JsValue] and ( JsPath \ "created" ).format[Instant] )( read, write ) private[this] def read( id: Option[Long], obj: JsValue, action: String, attr: JsValue, created: Instant ): Event = { Event( id, obj, action, attr, created ) } private[this] def write( request: Event ): ( Option[Long], JsValue, String, JsValue, Instant ) = { ( request.id, request.obj, request.action, request.attr, request.created ) } }
<reponame>pezng/three<gh_stars>0 import { Material } from 'three'; export abstract class AbstractMaterial<T extends Material> { object!: T; }
// // Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.2 generiert // Siehe <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a> // Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren. // Generiert: 2020.03.13 um 12:48:52 PM CET // package net.opengis.fes._2; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java-Klasse für Extended_CapabilitiesType complex type. * * <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist. * * <pre> * &lt;complexType name="Extended_CapabilitiesType"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="AdditionalOperators" type="{http://www.opengis.net/fes/2.0}AdditionalOperatorsType" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Extended_CapabilitiesType", propOrder = { "additionalOperators" }) public class Extended_CapabilitiesType { @XmlElement(name = "AdditionalOperators") protected AdditionalOperatorsType additionalOperators; /** * Ruft den Wert der additionalOperators-Eigenschaft ab. * * @return * possible object is * {@link AdditionalOperatorsType } * */ public AdditionalOperatorsType getAdditionalOperators() { return additionalOperators; } /** * Legt den Wert der additionalOperators-Eigenschaft fest. * * @param value * allowed object is * {@link AdditionalOperatorsType } * */ public void setAdditionalOperators(AdditionalOperatorsType value) { this.additionalOperators = value; } public boolean isSetAdditionalOperators() { return (this.additionalOperators!= null); } }
#!/bin/bash #读取配置文件数据 for line in `cat conf/common.conf | grep -Ev '^$|#'` do eval "$line" done #hadoop上配置优先处理 hadoop_conf_path=/${hive_province}/conf/date.conf for line in `hadoop fs -cat ${hadoop_conf_path} | grep -Ev '^$|#'` do eval "$line" done modelType=$1 startDate=${startDate} endDate=${endDate} isUpdateDate=${isUpdateDate} if [ $isUpdateDate -eq 0 ];then echo "第一次无需修改,更新date.conf为isUpdateDate=1" isUpdateDate=1 else if [ -z "$modelType" ] || [ "$modelType" == "day" ];then startDate=$endDate endDate=`date -d "${endDate} +1 days" +%Y-%m-%d` elif [ "$modelType" == "week" ]; then startDate=$endDate endDate=`date -d "${startDate} +7 days" +%Y-%m-%d` elif [ "$modelType" == "month" ]; then startDate=$endDate endDate=`date -d "${startDate} +1 months" +%Y-%m-%d` elif "$modelType" == "quarter" ]; then startDate=$endDate endDate=`date -d "${startDate} +3 months" +%Y-%m-%d` fi fi mkdir -p tmp echo "" > tmp/date.conf echo "startDate=${startDate}" >> tmp/date.conf echo "endDate=${endDate}" >> tmp/date.conf echo "isUpdateDate=1" >> tmp/date.conf echo "" >> tmp/date.conf hadoop fs -copyFromLocal -f tmp/date.conf /${hive_province}/conf/ for line in `hadoop fs -cat ${hadoop_conf_path}` do echo "$line" done #重置队列文件 dateType=$modelType #配置yarn队列 yarn_queues=default,hive #如果yarn_queue_weight为空,表示随机获取 yarn_queue_weight=1 source ./tool/queue.sh init_yarn_queue
<reponame>zzApotheosis/Personal-Projects #include <stdlib.h> #include <stdio.h> #include "include/util.h" size_t util_strlen(char* s) { size_t l = (size_t) 0u; char* i = s; while (*i != '\0') { l++; i++; if (l >= UTIL_STR_MAX_LEN) return l; } return l; }
<gh_stars>0 package com.ramsaysmith.ultrame; import android.animation.ObjectAnimator; import android.app.Activity; import android.app.AppOpsManager; import android.app.usage.NetworkStats; import android.app.usage.NetworkStatsManager; import android.content.Context; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.app.Fragment; import android.preference.PreferenceManager; import android.telephony.TelephonyManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.DecelerateInterpolator; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import java.lang.ref.WeakReference; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Calendar; import java.util.List; import static android.app.AppOpsManager.OPSTR_GET_USAGE_STATS; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link DashboardFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link DashboardFragment#newInstance} factory method to * create an instance of this fragment. */ public class DashboardFragment extends Fragment { // TODO: Rename parameter arguments, choose names that match public DashboardFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment DashboardFragment. */ // TODO: Rename and change types and number of parameters public static DashboardFragment newInstance(String param1, String param2) { DashboardFragment fragment = new DashboardFragment(); Bundle args = new Bundle(); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void onPause() { super.onPause(); } @Override public void onResume() { super.onResume(); new RefreshAsyncTask(this.getView()).execute(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View content = inflater.inflate(R.layout.fragment_dashboard, container, false); new RefreshAsyncTask(content).execute(); return content; } @Override public void onDetach() { super.onDetach(); } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p/> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name } private static class RefreshAsyncTask extends AsyncTask<Void, Void, Integer> { private WeakReference<View> weakView; private Integer dataUsed, dataTotal, dataValue; private String dateString; public RefreshAsyncTask(View view) { weakView = new WeakReference<>(view); } private boolean isUsagePermissionGranted() { AppOpsManager appOps = (AppOpsManager) weakView.get().getContext().getSystemService(Context.APP_OPS_SERVICE); int mode = appOps.checkOpNoThrow(OPSTR_GET_USAGE_STATS, android.os.Process.myUid(), weakView.get().getContext().getPackageName()); return (mode == AppOpsManager.MODE_ALLOWED); } @Override protected void onPreExecute() { super.onPreExecute(); ProgressBar dataUsageCircle = weakView.get().findViewById(R.id.dataUsageCircle); dataValue = dataUsageCircle.getProgress(); dataUsageCircle.setProgress(0); } @Override protected Integer doInBackground(Void... params) { View view = weakView.get(); // Load cached information SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(view.getContext()); Long ticks = Calendar.getInstance().getTimeInMillis() - app_preferences.getLong("dataUpdate", Calendar.getInstance().getTimeInMillis()); if (ticks/1000 <= 60*1.5 || isUsagePermissionGranted()) { dateString = "Just now"; } // if less than one minute else if (ticks/1000 <= 60*60*1.5) { dateString = Math.round((float)ticks/1000/60) + " mins. ago"; } // if less than one hour else if (ticks/1000 <= 60*60*24*1.5) { dateString = Math.round((float)ticks/1000/60/60) + " hrs. ago"; } // if less than one day else { dateString = Math.round((float)ticks/1000/60/60/24) + " days ago"; } // Data usage circle dataUsed = app_preferences.getInt("dataUsed", 0); Integer available = app_preferences.getInt("dataAvailable", 100); dataTotal = dataUsed + available; if (isUsagePermissionGranted()) { // Add current system usage if allowed try { NetworkStatsManager networkStatsManager = (NetworkStatsManager) view.getContext().getSystemService(Context.NETWORK_STATS_SERVICE); TelephonyManager manager = (TelephonyManager) view.getContext().getSystemService(Context.TELEPHONY_SERVICE); String subscriberId = manager.getSubscriberId(); NetworkStats.Bucket bucket = networkStatsManager.querySummaryForDevice(ConnectivityManager.TYPE_MOBILE, subscriberId, app_preferences.getLong("dataUpdate", Calendar.getInstance().getTimeInMillis()), Calendar.getInstance().getTimeInMillis()); long extraData = (bucket.getRxBytes() + bucket.getTxBytes()) / (1024*1024); dataUsed += Integer.parseInt(String.valueOf(extraData)); Log.i("Ultra.me", "System indicated " + extraData + "MB extra data used since last system sync."); } catch (SecurityException e) { Log.e("Ultra.me", "Could not access subscriber id to get live data."); } catch (Exception e) { Log.e("Ultra.me", "Error occurred: " + e.getMessage()); } } return 1; } @Override protected void onPostExecute(Integer integer) { super.onPostExecute(integer); View view = weakView.get(); SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(view.getContext()); // Update date of update TextView lastUpdated = view.findViewById(R.id.timeStatusUpdated); lastUpdated.setText(dateString); // Update usage circle TextView usedData = view.findViewById(R.id.dataUsed); usedData.setText(String.valueOf(dataUsed)); TextView totalData = view.findViewById(R.id.dataTotal); if (dataTotal > 1000) { DecimalFormat decimalFormat = new DecimalFormat(".#"); totalData.setText("of " + decimalFormat.format(dataTotal / 1000) + " GB"); } else { totalData.setText("of " + String.valueOf(dataTotal) + " MB"); } ProgressBar dataUsageCircle = view.findViewById(R.id.dataUsageCircle); dataUsageCircle.setMax(dataTotal); dataUsageCircle.setSecondaryProgress(dataTotal); // Animate data circle if (Math.abs(dataValue - dataUsed) >= 5) { ObjectAnimator animation = ObjectAnimator.ofInt(dataUsageCircle, "progress", dataValue, dataUsed); animation.setDuration(dataUsed * 5000 / dataTotal); // in milliseconds animation.setInterpolator(new DecelerateInterpolator()); animation.setStartDelay(100); animation.start(); } else { dataUsageCircle.setProgress(dataUsed); } } } }
#!/bin/bash # run from wolfssl root # SECP256R1 openssl ecparam -name prime256v1 -genkey -noout -out certs/statickeys/ecc-secp256r1.pem openssl ec -inform pem -in certs/statickeys/ecc-secp256r1.pem -outform der -out certs/statickeys/ecc-secp256r1.der # DH 2048-bit (keySz = 29) # Using one generated and capture with wolfSSL using wc_DhGenerateKeyPair (openssl generates DH keys with 2048-bits... based on the DH "p" prime size) openssl genpkey -paramfile certs/statickeys/dh-ffdhe2048-params.pem -outform -out certs/statickeys/dh-ffdhe2048.pem openssl pkey -inform pem -in certs/statickeys/dh-ffdhe2048.pem -outform der -out certs/statickeys/dh-ffdhe2048.der # Export DH public key as DER and PEM openssl pkey -inform pem -in certs/statickeys/dh-ffdhe2048.pem -outform der -out certs/statickeys/dh-ffdhe2048-pub.der -pubout openssl pkey -inform pem -in certs/statickeys/dh-ffdhe2048.pem -outform pem -out certs/statickeys/dh-ffdhe2048-pub.pem -pubout # X25519 (Curve25519) openssl genpkey -algorithm x25519 -outform pem -out certs/statickeys/x25519.pem openssl pkey -inform pem -in certs/statickeys/x25519.pem -outform der -out certs/statickeys/x25519.der openssl pkey -inform pem -in certs/statickeys/x25519.pem -outform der -out certs/statickeys/x25519-pub.der -pubout openssl pkey -inform pem -in certs/statickeys/x25519.pem -outform pem -out certs/statickeys/x25519-pub.pem -pubout
import random def find_element(lower_limit, upper_limit, search_element): # generate a random array rand_arr = [random.randint(lower_limit, upper_limit) for _ in range(10)] # search for the first occurrence of the search_element for i in range(len(rand_arr)): if rand_arr[i] == search_element: return i return -1 result = find_element(lower_limit, upper_limit, search_element) print('First occurrence of ' + str(search_element) + ' is at index ' + str(result))
#!/bin/sh if ! test -d "$1" then exec echo Provide a directory to install to, e.g.: ./install.sh ../pokemon-online else install_to=$1 echo Installing to $install_to cp -f `pwd`/scripts.js ${install_to}/bin cp -f `pwd`/COPYING ${install_to}/bin/ZSCRIPTS_COPYING if test -h ${install_to}/bin/js_modules then rm ${install_to}/bin/js_modules else if test -d ${install_to}/bin/js_modules then echo wtf error exit fi fi ln -s `pwd`/js_modules ${install_to}/bin/js_modules if ! test -d ${install_to}/bin/js_databases then mkdir ${install_to}/bin/js_databases fi echo NOTE Symbolic linked js_modules fi
def sort_lexicographically(str1, str2): list1 = list(str1) list2 = list(str2) list1.sort() list2.sort() if list1 < list2: return str1 + str2 else: return str2 + str1 str1 = "hello" str2 = "world" sorted_string = sort_lexicographically(str1, str2) print(sorted_string)
package io.github.seniya2.bar; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; @RepositoryRestResource public interface BarRepositoryRestResource extends PagingAndSortingRepository<Bar, String>{ }
#bin/bash/'!¡ echo "" echo "" echo "Installing Packages" echo "===================" echo "By @certified_youtuber" echo "===================" echo "" apt update pkg install python -y apt upgrade pip install lolcat pkg install mpv -y pkg install figlet -y cp bash.bashrc $PREFIX/etc clear echo "" echo "" echo "Installed All Packages" |lolcat echo "=========================" echo "Ready To Go.........." |lolcat echo "=========================" echo "Done By @Certified_youtuber" |lolcat echo "=========================" echo "Restart Your Termux App" |lolcat echo "=========================" exit
package org.museautomation.ui.step.groups; import org.museautomation.core.*; import org.museautomation.core.step.descriptor.*; import java.util.*; /** * Finds/builds the available step type groups for the project. * * @author <NAME> (see LICENSE.txt for license details) */ public class StepTypeGroups { public static StepTypeGroup get(MuseProject project) { StepTypeGroup group = all_groups.get(project); if (group == null) { // lookup all types group = new StepTypeList("all"); for (StepDescriptor descriptor : project.getStepDescriptors().findAll()) group.add(descriptor, descriptor.getGroupName()); group.sortAll(); all_groups.put(project, group); } return group; } private static Map<MuseProject, StepTypeGroup> all_groups = new HashMap<>(); }
<gh_stars>0 module.exports = { display: { props: [ { name: 'height', type: 'number', default: 0, }, { name: 'lg', type: 'boolean', default: 'false', }, { name: 'lgAndDown', type: 'boolean', default: 'false', }, { name: 'lgAndUp', type: 'boolean', default: 'false', }, { name: 'md', type: 'boolean', default: 'false', }, { name: 'mdAndDown', type: 'boolean', default: 'false', }, { name: 'mdAndUp', type: 'boolean', default: 'false', }, { name: 'mobile', type: 'boolean', default: 'false', }, { name: 'mobileBreakpoint', type: 'number | string', default: 'md', }, { name: 'name', type: 'string', default: '', }, { name: 'platform', type: 'object', default: { android: false, ios: false, cordova: false, electron: false, edge: false, firefox: false, opera: false, win: false, mac: false, linux: false, touch: false, ssr: false, }, }, { name: 'sm', type: 'boolean', default: 'false', }, { name: 'smAndDown', type: 'boolean', default: 'false', }, { name: 'smAndUp', type: 'boolean', default: 'false', }, { name: 'thresholds', type: 'object', default: { xs: 0, sm: 600, md: 960, lg: 1280, xl: 1920, xxl: 2560, }, snippet: ` import { useDisplay } from 'vuetify' export default { mounted () { const display = useDisplay() // display thresholds are not reactive // and do not need to use .value console.log(display.thresholds.md) // 1280 } } `, }, { name: 'width', type: 'number', default: 0, }, { name: 'xl', type: 'boolean', default: 'false', }, { name: 'xlAndDown', type: 'boolean', default: 'false', }, { name: 'xlAndUp', type: 'boolean', default: 'false', }, { name: 'xs', type: 'boolean', default: 'false', }, { name: 'xxl', type: 'boolean', default: 'false', }, ], }, }
<filename>main.go<gh_stars>1-10 package main import ( "flag" "fmt" "os" "os/signal" "syscall" "time" "github.com/ajm188/go-mctop/memcap" "github.com/ajm188/go-mctop/ui" ) var ( flags = &flag.FlagSet{} iface = flags.String("interface", "", "interface to sniff") port = flags.Int("port", 11211, "port to sniff") t = flags.Duration("duration", time.Minute, "how long to sniff") ) func main() { flag.CommandLine = flags flag.Parse() mc, err := memcap.NewMemcap(*iface, *port, *t) if err != nil { panic(err) } quit := make(chan os.Signal, 1) done := make(chan bool, 1) doneSniffing := make(chan bool, 1) doneDrawing := make(chan bool, 1) signal.Notify(quit, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM) go func() { <-quit doneSniffing <- true doneDrawing <- true }() // TODO: more complex, but allow mctop to operate in two modes: // 1. report mode, which never renders a termui, but produces a detailed text report // 2. ui mode, which does all this drawing stuff. it's way more expensive to do, // mostly due to the constant sorting of an ever-growing list of key stats, so // mctop should let you get stats without forcing you to pay that cost. // // Thought: if you include a -duration flag, it runs in report mode for the specified // duration, but if you omit that flag it runs in ui mode indefinitely. if err := ui.Init(doneDrawing); err != nil { panic(err) } defer ui.Close() go func() { if err := mc.Run(doneSniffing); err != nil { fmt.Println(err) } done <- true }() go func() { // TODO: this interval should be configurable ticker := time.Tick(time.Second * 3) // TODO: make the initial wait time configurable // Wait for some data to arrive, then do an initial draw. time.Sleep(time.Millisecond * 100) draw(mc.GetStats()) for { select { case <-ticker: stats := mc.GetStats() draw(stats) case <-doneDrawing: done <- true return } } }() <-done } func draw(stats *memcap.Stats) { ui.UpdateCalls(stats) ui.UpdateKeys(stats) ui.Render() }
public class ShareLinkHandler { private readonly IRepository<ShareLinkPartRecord> _repository; private readonly IOrchardServices _orchardServices; private readonly IShareLinkService _sharelinkService; private readonly IEnumerable<IShareLinkPriorityProvider> _priorityProviders; public ShareLinkHandler( IRepository<ShareLinkPartRecord> repository, IOrchardServices orchardServices, IShareLinkService sharelinkService, IEnumerable<IShareLinkPriorityProvider> priorityProviders) { _repository = repository; _orchardServices = orchardServices; _sharelinkService = sharelinkService; _priorityProviders = priorityProviders; } public void ProcessShareLinks() { foreach (var priorityProvider in _priorityProviders) { var shareLinks = priorityProvider.GetShareLinks(); // Assuming a method GetShareLinks exists in IShareLinkPriorityProvider foreach (var shareLink in shareLinks) { // Process the share link using repository, orchardServices, and sharelinkService // Example: _sharelinkService.ProcessShareLink(shareLink); } } } }
import { format } from 'prettier/standalone'; import { getMemberObjectString } from '../../helpers/get-state-object-string'; import { MitosisContext } from '../../types/mitosis-context'; type ContextToReactOptions = { format?: boolean; }; export const contextToReact = (options: ContextToReactOptions = {}) => ({ context }: { context: MitosisContext }): string => { let str = ` import { createContext } from 'react'; export default createContext(${getMemberObjectString(context.value)}) `; if (options.format !== false) { try { str = format(str, { parser: 'typescript', plugins: [ require('prettier/parser-typescript'), // To support running in browsers ], }); } catch (err) { console.error('Format error for file:', str); throw err; } } return str; };
<gh_stars>0 package nl.probotix.helpers; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.util.ElapsedTime; import nl.probotix.RuckusHardware; /** * Copyright 2018 (c) ProBotiX */ public class AutoHelper { private RuckusHardware ruckusHardware; private LinearOpMode opMode; public AutoHelper(RuckusHardware ruckusHardware, LinearOpMode opMode) { this.ruckusHardware = ruckusHardware; this.opMode = opMode; } public void driveAndWait(double linearX, double linearY, double angularZ, double time, double timeout) { if(opMode.opModeIsActive()) { driveEncoded(linearX, linearY, angularZ, time); ElapsedTime runtime = new ElapsedTime(); runtime.reset(); while (opMode.opModeIsActive() && runtime.milliseconds() < timeout * 1000 && ruckusHardware.lfWheel.isBusy() && ruckusHardware.rfWheel.isBusy() && ruckusHardware.lrWheel.isBusy() && ruckusHardware.rrWheel.isBusy()) { ruckusHardware.telemetryData(opMode.telemetry, "DriveAndWait", "Encoders", "LF: " + ruckusHardware.lfWheel.getCurrentPosition() + " " + ruckusHardware.lfWheel.getTargetPosition() + "\n" + "RF: " + ruckusHardware.rfWheel.getCurrentPosition() + " " + ruckusHardware.rfWheel.getTargetPosition() + "\n" + "LR: " + ruckusHardware.lrWheel.getCurrentPosition() + " " + ruckusHardware.lrWheel.getTargetPosition() + "\n" + "RR: " + ruckusHardware.rrWheel.getCurrentPosition() + " " + ruckusHardware.rrWheel.getTargetPosition()); } ruckusHardware.setMotorPowers(0, 0, 0, 0); ruckusHardware.setDcMotorMode(DcMotor.RunMode.RUN_USING_ENCODER); } } public void driveEncoded(double linearX, double linearY, double angularZ, double time) { //Needed numbers double WHEEL_DIAMETER = 100; double WHEEL_SEPERATION_WIDTH = 384; double WHEEL_SEPARATION_LENGTH = 336; double GEAR_RATIO = 1.6; double COUNTS_PER_REV = 1478.4; double WHEEL_MAX_RPM = 125; double avwB = angularZ / 180 * Math.PI / time; double avwFL = (1 / (WHEEL_DIAMETER / 2)) * (linearX / time - linearY / time - (WHEEL_SEPERATION_WIDTH + WHEEL_SEPARATION_LENGTH) / 2 * avwB); double avwFR = (1 / (WHEEL_DIAMETER / 2)) * (linearX / time + linearY / time + (WHEEL_SEPERATION_WIDTH + WHEEL_SEPARATION_LENGTH) / 2 * avwB); double avwRL = (1 / (WHEEL_DIAMETER / 2)) * (linearX / time + linearY / time - (WHEEL_SEPERATION_WIDTH + WHEEL_SEPARATION_LENGTH) / 2 * avwB); double avwRR = (1 / (WHEEL_DIAMETER / 2)) * (linearX / time - linearY / time + (WHEEL_SEPERATION_WIDTH + WHEEL_SEPARATION_LENGTH) / 2 * avwB); double rpmFL = (avwFL * 30 / Math.PI) / GEAR_RATIO; double rpmFR = (avwFR * 30 / Math.PI) / GEAR_RATIO; double rpmRL = (avwRL * 30 / Math.PI) / GEAR_RATIO; double rpmRR = (avwRR * 30 / Math.PI) / GEAR_RATIO; Double ticksFLD = (rpmFL / 60 * COUNTS_PER_REV * time); Double ticksFRD = (rpmFR / 60 * COUNTS_PER_REV * time); Double ticksRLD = (rpmRL / 60 * COUNTS_PER_REV * time); Double ticksRRD = (rpmRR / 60 * COUNTS_PER_REV * time); int ticksFL = ticksFLD.intValue(); int ticksFR = ticksFRD.intValue(); int ticksRL = ticksRLD.intValue(); int ticksRR = ticksRRD.intValue(); ruckusHardware.setDcMotorMode(DcMotor.RunMode.RUN_TO_POSITION); ruckusHardware.addWheelTicks(ticksFL, ticksFR, ticksRL, ticksRR); ruckusHardware.setMotorPowers(rpmFL / WHEEL_MAX_RPM, rpmFR / WHEEL_MAX_RPM, rpmRL / WHEEL_MAX_RPM, rpmRR / WHEEL_MAX_RPM); } public void stopEncodedDrive() { ruckusHardware.setMotorPowers(0, 0, 0, 0); ruckusHardware.setDcMotorMode(DcMotor.RunMode.RUN_USING_ENCODER); } public void resetEncoders() { ruckusHardware.setDcMotorMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); ElapsedTime elapsedTime = new ElapsedTime(); elapsedTime.reset(); while(elapsedTime.milliseconds() < 100 && opMode.opModeIsActive()) { } ruckusHardware.setDcMotorMode(DcMotor.RunMode.RUN_USING_ENCODER); while(elapsedTime.milliseconds() < 200 && opMode.opModeIsActive()) { } } public double inchToCM(double inch) { return inch*2.54; } public double inchToMM(double inch) { return this.inchToCM(inch) * 0.1; } }
<filename>app/model/simulation/NumericResults.java package model.simulation; /** Created by chelen on 03/05/15. */ public class NumericResults { private double lcA; private double lcB; private double lc; private double la; private double lb; private double l; private double wcA; private double wcB; private double wc; private double wa; private double wb; private double w; private double ha; private double hb; private double h; private double porcentajeBInterrumpido; private double porcentajeBAbandono; private double porcentajeBNoIngresa; private int bCustomers; private int aCustomers; private float porcentajeBEnjaulado; private double canalOcupado; private double canalLibre; private double canalOcpuadoPorClienteB; private double canalOcpuadoPorClienteA; public double getCanalOcupado(){return canalOcupado;} public void setCanalOcupado(double time){this.canalOcupado=time;} public double getCanalLibre(){return canalLibre;} public void setCanalLibre(double time){this.canalLibre=time;} public double getLcA() { return lcA; } public void setLcA(double lcA) { this.lcA = lcA; } public double getLcB() { return lcB; } public void setLcB(double lcB) { this.lcB = lcB; } public double getLc() { return lc; } public void setLc(double lc) { this.lc = lc; } public double getLa() { return la; } public void setLa(double la) { this.la = la; } public double getLb() { return lb; } public void setLb(double lb) { this.lb = lb; } public double getL() { return l; } public void setL(double l) { this.l = l; } public double getWcA() { return wcA; } public void setWcA(double wcA) { this.wcA = wcA; } public double getWcB() { return wcB; } public void setWcB(double wcB) { this.wcB = wcB; } public double getWc() { return wc; } public void setWc(double wc) { this.wc = wc; } public double getWa() { return wa; } public void setWa(double wa) { this.wa = wa; } public double getWb() { return wb; } public void setWb(double wb) { this.wb = wb; } public double getW() { return w; } public void setW(double w) { this.w = w; } public double getHa() { return ha; } public void setHa(double ha) { this.ha = ha; } public double getHb() { return hb; } public void setHb(double hb) { this.hb = hb; } public double getH() { return h; } public void setH(double h) { this.h = h; } public double getPorcentajeBInterrumpido() { return porcentajeBInterrumpido; } public void setPorcentajeBInterrumpido(double porcentajeBInterrumpido) { this.porcentajeBInterrumpido = porcentajeBInterrumpido; } public double getPorcentajeBAbandono() { return porcentajeBAbandono; } public void setPorcentajeBAbandono(double porcentajeBAbandono) { this.porcentajeBAbandono = porcentajeBAbandono; } public double getPorcentajeBNoIngresa() { return porcentajeBNoIngresa; } public void setPorcentajeBNoIngresa(double porcentajeBNoIngresa) { this.porcentajeBNoIngresa = porcentajeBNoIngresa; } public void setBcustomers(int bcustomers) { bCustomers = bcustomers; } public int getBcustomers() { return bCustomers; } public void setAcustomers(int acustomers) { aCustomers = acustomers; } public int getAcustomers() { return aCustomers; } public void setPorcentajeBEnjaulado(float porcentajeBEnjaulado) { this.porcentajeBEnjaulado = porcentajeBEnjaulado; } public float getPorcentajeBEnjaulado() { return porcentajeBEnjaulado; } public void setCanalOcpuadoPorClienteB(double canalOcpuadoPorClienteB) { this.canalOcpuadoPorClienteB = canalOcpuadoPorClienteB; } public double getCanalOcpuadoPorClienteB() { return canalOcpuadoPorClienteB; } public void setCanalOcpuadoPorClienteA(double canalOcpuadoPorClienteA) { this.canalOcpuadoPorClienteA = canalOcpuadoPorClienteA; } public double getCanalOcpuadoPorClienteA() { return canalOcpuadoPorClienteA; } }
#!/usr/bin/env bash ${config.javaCommand} ${config.javaArgs} -jar ${mainJar.name} ${config.programArgs}
// Define the event listener interface public interface IFlagEntityEventAddedListener { void OnEventAdded(string eventName); } // Implement the FlagEntity class public class FlagEntity { private List<IFlagEntityEventAddedListener> eventListeners = new List<IFlagEntityEventAddedListener>(); // Method to register event listeners public void RegisterListener(IFlagEntityEventAddedListener listener) { eventListeners.Add(listener); } // Method to notify all registered listeners when an event occurs public void NotifyEventAdded(string eventName) { foreach (var listener in eventListeners) { listener.OnEventAdded(eventName); } } } // Example implementation of an event listener public class ExampleEventListener : IFlagEntityEventAddedListener { public void OnEventAdded(string eventName) { Console.WriteLine("Event added: " + eventName); } } // Example usage public class Program { public static void Main() { FlagEntity flagEntity = new FlagEntity(); ExampleEventListener listener1 = new ExampleEventListener(); ExampleEventListener listener2 = new ExampleEventListener(); flagEntity.RegisterListener(listener1); flagEntity.RegisterListener(listener2); flagEntity.NotifyEventAdded("Event1"); } }
<gh_stars>0 package modell.formel; /**Unterklasse des Bikonnektors. * Verknuepft seinen linken und rechten Formelnachbarn mit einem logischen EXOR beim Auswerten. * Seine String Repraesentation ist "x". * @author Flo * */ public class ExklusivOder extends BiKonnektor { /** Kostruktor. Setzt uebergebene Werte und seine String Rep. * @param rechts Die rechte Formel. * @param links Die linke Formel. */ public ExklusivOder(Formel links, Formel rechts) { this.rechts = rechts; this.links = links; this.rep = "\u2295"; this.bindungsstaerke = 3; this.zeichen = "x"; } @Override public boolean auswerten(boolean[] werte) { return links.auswerten(werte) ^ rechts.auswerten(werte); } }
# ---------------------------------------------------------------------------- # # Package : node-proper-lockfile # Version : v4.1.1 # Language : JavaScript # Source repo : https://github.com/moxystudio/node-proper-lockfile # Tested on : UBI 8.3 # Script License: MIT License # Maintainer : Varsha Aaynure <Varsha.Aaynure@ibm.com> # # Disclaimer: This script has been tested in root mode on given # ========== platform using the mentioned version of the package. # It may not work as expected with newer versions of the # package and/or distribution. In such case, please # contact "Maintainer" of this script. # # ---------------------------------------------------------------------------- #!/bin/bash #Variables PACKAGE_URL=https://github.com/moxystudio/node-proper-lockfile.git PACKAGE_VERSION="${1:-v4.1.1}" NODE_VERSION=v12.22.4 #Install required files yum install -y git #installing nvm curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash source ~/.bashrc nvm install $NODE_VERSION #Cloning Repo git clone $PACKAGE_URL cd node-proper-lockfile/ git checkout $PACKAGE_VERSION #Build package npm install npm audit fix npm audit fix --force npm install #Test pacakge npm test echo "Complete!"
<reponame>svenslaggare/texteditor<gh_stars>1-10 #pragma once #define GLEW_STATIC #include <GL/glew.h> #include <cstddef> #include <memory> #include <vector> struct GLUniform { std::size_t index; std::string name; GLint size; GLenum type; }; std::ostream& operator<<(std::ostream& stream, const GLUniform& uniform); /** * Contains helper functions for OpenGL */ namespace GLHelpers { /** * Creates a new vertex array object * @param vertices The vertices * @param verticesSize The size of all the vertices * @param elements The elements * @param elementsSize The size of all the elements * @param vao The vertex array object * @param vbo The vertex buffer object */ void createVertexArrayObject(GLfloat* vertices, std::size_t verticesSize, GLuint* elements, std::size_t elementsSize, GLuint& vao, GLuint& vbo); /** * Returns the uniforms in the given shader program * @param shaderProgram The shader program */ std::vector<GLUniform> getUniforms(GLuint shaderProgram); }
#!/usr/bin/env bash set -o errexit set -o nounset set -o pipefail IMAGE="artigraph/example-spend" VERSION="$(python3 -c 'from arti.internal import version; print(version)')" docker build --build-arg VERSION="${VERSION}" -t "${IMAGE}" . docker push "${IMAGE}"
class DealerUser { // ... other methods public function checkIntegrity() { // Verify that the dealer and approval status have been set correctly if ($this->dealer !== null && $this->approved === false) { return true; } else { return false; } } }
import { Body, Controller, Get, HttpCode, InternalServerErrorException, NotFoundException, Param, Post, Put, } from "@nestjs/common"; import { AddPlayer, ListPlayer, ListRegisterPlayer, PlayerUnknowException, RegisterPlayer, UpdatePlayer, } from "@cph-scorer/core"; import { RankingService } from "../ranking/ranking.service"; import { PlayerService } from "./player.service"; import { PlayerDTO } from "./DTO/player.dto"; import { ApiCreatedResponse, ApiNoContentResponse, ApiNotFoundResponse, ApiOkResponse, ApiTags, } from "@nestjs/swagger"; import { UpdateInsertPlayerDto } from "./DTO/update-insert-player.dto"; import { RegisterPlayerDto } from "./DTO/register-player.dto"; import { UUIDDTO } from "../util/uuid.dto"; @ApiTags("Player") @Controller("player") export class PlayerController { constructor( private readonly playerService: PlayerService, private readonly rankingService: RankingService ) {} @Get("/") @ApiOkResponse({ description: "List of all player", type: [PlayerDTO] }) async list(): Promise<PlayerDTO[]> { const useCase = new ListPlayer(this.playerService.dao); return await useCase.execute(); } @Get("/register") @ApiOkResponse({ description: "List of all registered player", type: PlayerDTO, }) async listRegister(): Promise<PlayerDTO[]> { const useCase = new ListRegisterPlayer(this.playerService.dao); return await useCase.execute(); } @Post("/") @HttpCode(201) @ApiCreatedResponse({ description: "Add new player", type: PlayerDTO }) async add(@Body() player: UpdateInsertPlayerDto): Promise<PlayerDTO> { const useCase = new AddPlayer(this.playerService.dao); return await useCase.execute(player); } @Put("/:id") @ApiOkResponse({ description: "Update one player", type: PlayerDTO }) @ApiNotFoundResponse({ description: "Player is unknow" }) async update( @Param() { id }: UUIDDTO, @Body() player: UpdateInsertPlayerDto ): Promise<PlayerDTO> { const useCase = new UpdatePlayer(this.playerService.dao); const res = await useCase.execute(id, player); if (res === null) { throw new NotFoundException("Invalid user"); } return res; } @Post("/register") @HttpCode(204) @ApiNoContentResponse({ description: "Player is registered" }) @ApiNotFoundResponse({ description: "Player is unknow" }) async registerPlayer(@Body() data: RegisterPlayerDto): Promise<void> { const useCase = new RegisterPlayer( this.playerService.dao, this.rankingService.dao ); try { await useCase.exec(data.id, data.type); } catch (e) { if (e instanceof PlayerUnknowException) { throw new NotFoundException("Invalid user"); } throw new InternalServerErrorException(e); } } }
#!/bin/bash # RESTful Interface Tool Sample Script for HPE iLO Products # # Copyright 2014, 2019 Hewlett Packard Enterprise Development LP # # Description: This is a sample bash script to retrieve the # # current security text message set in the iLO Login Banner. # # NOTE: You will need to replace the USER_LOGIN and PASSWORD # # values with values that are appropriate for your # # environment. # # Firmware support information for this script: # # iLO 5 - All versions # runLocal(){ ilorest get LoginSecurityBanner/SecurityMessage --selector=SecurityService. -u USER_LOGIN -p PASSWORD ilorest logout } runRemote(){ ilorest get LoginSecurityBanner/SecurityMessage --selector=SecurityService. --url=$1 --user $2 --password $3 ilorest logout } error(){ echo "Usage:" echo "remote: Get_Security_Msg.sh ^<iLO url^> ^<iLO username^> ^<iLO password^>" echo "local: Get_Security_Msg.sh" } if [ "$#" -eq "3" ] then runRemote "$1" "$2" "$3" elif [ "$#" -eq "0" ] then runLocal else error fi
<gh_stars>1-10 export { LoginCredentialQueryRepository } from "./query/LoginCredential" export { LoginSessionQueryRepository } from "./query/LoginSession" export { UserQueryRepository } from "./query/User" export { AuthenticityTokenQueryRepository } from "./query/AuthenticityToken" export { ChannelGroupQueryRepository } from "./query/ChannelGroup" export { ChannelQueryRepository } from "./query/Channel" export { MessageQueryRepository } from "./query/Message" export { ChannelGroupTimelineQueryRepository } from "./query/ChannelGroupTimeline" export { ChannelReadStateQueryRepository } from "./query/ChannelReadState" export { ChannelTimelineQueryRepository } from "./query/ChannelTimeline" export { LoginCredentialCommandRepository } from "./command/LoginCredential" export { LoginSessionCommandRepository } from "./command/LoginSession" export { UserCommandRepository } from "./command/User" export { AuthenticityTokenCommandRepository } from "./command/AuthenticityToken" export { ChannelGroupCommandRepository } from "./command/ChannelGroup" export { ChannelCommandRepository } from "./command/Channel" export { MessageCommandRepository } from "./command/Message" export { ChannelGroupTimelineCommandRepository } from "./command/ChannelGroupTimeline" export { ChannelReadStateCommandRepository } from "./command/ChannelReadState" export { TransactionRepository } from "./Transaction"
#!/bin/sh cd /home/pi/deimos DISPLAY=0:0; /usr/bin/python3 /home/pi/deimos/deimos.py
package com.haufelexware.gocd.service; import com.google.gson.Gson; import com.haufelexware.gocd.dto.GoPipelineHistory; import com.haufelexware.gocd.dto.GoPipelineInstance; import com.haufelexware.util.Streams; import com.thoughtworks.go.plugin.api.logging.Logger; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpGet; import java.io.IOException; import java.net.URLEncoder; import java.util.Collections; import java.util.List; /** * This class encapsulates the API call to get all pipeline instances of a Go pipeline. * This API service is available since Go Version 14.3.0 * @see <a href="https://api.gocd.org/current/#get-pipeline-history">Get Pipeline History</a> */ public class GoGetPipelineHistory { private static final Logger Log = Logger.getLoggerFor(GoGetPipelineHistory.class); private final GoApiClient goApiClient; public GoGetPipelineHistory(GoApiClient goApiClient) { this.goApiClient = goApiClient; } public List<GoPipelineInstance> get(final String pipelineName) { try { HttpResponse response = goApiClient.execute(new HttpGet("/go/api/pipelines/" + URLEncoder.encode(pipelineName, "UTF-8") + "/history")); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String content = Streams.readAsString(response.getEntity().getContent()); return new Gson().fromJson(content, GoPipelineHistory.class).getPipelines(); } else { Log.error("Request got HTTP-" + response.getStatusLine().getStatusCode()); } } catch (IOException e) { Log.error("Could not perform request", e); } return Collections.emptyList(); } }
import pytest from src.adapter import base from src.proxy import provider @pytest.mark.run(order=2) class TestBaseFetcher: def setup(self): self.obj = base.BaseFetcher( proxy_provider=provider.NoProxyProvier(), enable_fetch_price=True, enable_fetch_institutional_investors=True, enable_fetch_credit_transactions_securities=True, sleep_second=3, ) def test_headers(self): assert self.obj.HEADERS == { "User-agent": "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0", "Accept-Encoding": "gzip, deflate, compress", } def test_columns(self): assert self.obj.base_columns == [ "date", "category", ] assert self.obj.price_columns == [ "sid", "name", "open", "high", "low", "close", "capacity", "transaction", "turnover", ] assert self.obj.institutional_investors_columns == [ "foreign_dealers_buy", "foreign_dealers_sell", "foreign_dealers_total", "investment_trust_buy", "investment_trust_sell", "investment_trust_total", "dealer_buy", "dealer_sell", "dealer_total", "institutional_investors_total", ] assert self.obj.credit_transactions_securities_columns == [ "margin_purchase", "margin_sales", "margin_cash_redemption", "margin_today_balance", "margin_quota", "short_covering", "short_sale", "short_stock_redemption", "short_today_balance", "short_quota", "offsetting_margin_short", "note", ] def test_clean(self): assert self.obj.clean("-") == "-" assert self.obj.clean("--") is None assert self.obj.clean("---") is None assert self.obj.clean("----") is None assert self.obj.clean("1,000") == "1000" assert self.obj.clean("1,000,000") == "1000000" def test_combine(self): return NotImplemented
package driver; import fileIO.TextFile; public class LineCount { public static void main(String[] args){ TextFile tf=new TextFile(args[0], false, false); long lines=tf.countLines(); tf.close(); System.out.println(args[0]+" has "+lines+" non-blank lines."); } }
#!/bin/bash -x DATASET_NAME=${1} # has to be the same as the filename of DATASET_CONFIG DATASET_CONFIG="${DATASET_NAME}.py" GCP_PROJECT=kubric-xgcp GCS_BUCKET=gs://research-brain-kubric-xgcp REGION=us-central1 JOB_NAME=${2} MACHINE_TYPE="n1-highmem-16" NUM_WORKERS=20 if ! [[ $JOB_NAME =~ ^[a-zA-Z][-a-zA-Z0-9]*[a-zA-Z0-9]$ ]]; then echo "Invalid job_name ($JOB_NAME); the name must consist of only the characters [-a-z0-9], starting with a letter and ending with a letter or number" exit 1 fi # create a pseudo-package in a temporary directory to ship the dataset code to dataflow workers # https://beam.apache.org/documentation/sdks/python-pipeline-dependencies/ TEMP=$(mktemp -d) mkdir "$TEMP/$DATASET_NAME" cp "$DATASET_CONFIG" "$TEMP/$DATASET_NAME/__init__.py" echo "Dummy package to ship dataset code to worker nodes" > "$TEMP/README" cat > "$TEMP/setup.py" <<EOF import setuptools setuptools.setup( name='$DATASET_NAME', version='0.0.1', url="https://github.com/google-research/kubric", author="kubric authors", author_email="kubric@google.com", install_requires=['tensorflow_datasets', 'pypng', 'imageio', 'kubric'], packages=setuptools.find_packages(), ) EOF # install_requires=[ # 'tensorflow_datasets @ git+https://git@github.com/qwlouse/datasets@master#egg=tensorflow_datasets'], # tfds build $DATASET_CONFIG \ --data_dir=$GCS_BUCKET/tensorflow_datasets \ --beam_pipeline_options="runner=DataflowRunner,project=$GCP_PROJECT,job_name=$JOB_NAME,\ staging_location=$GCS_BUCKET/binaries,temp_location=$GCS_BUCKET/temp,region=$REGION,\ setup_file=$TEMP/setup.py,machine_type=$MACHINE_TYPE,num_workers=$NUM_WORKERS,experiments=upload_graph,experiments=use_unsupported_python_version" # clean-up: delete the pseudo-package rm -rf "$TEMP"
<?php $sentence = 'This is a test'; $words = explode(' ', $sentence); sort($words); print_r($words); ?>
<filename>src/modules/database/database-di.module.ts import { FactoryProvider, Module } from '@nestjs/common'; import { AddTelegramAccountAdapter } from './adapters/add-telegram-account.adapter'; import { AddTelegramAccountToDatabasePortSymbol } from '../../domains/ports/out/add-telegram-account-to-database.port'; import { DatabaseModule } from './database.module'; import { TelegramAccountsService } from './services/telegram-accounts.service'; import { GetChatIdByUsernamePortSymbol } from '../../domains/ports/out/get-chat-id-by-username.port'; import { GetChatIdByUsernameAdapter } from './adapters/get-chat-id-by-username.adapter'; const providers: FactoryProvider[] = [ { provide: AddTelegramAccountToDatabasePortSymbol, useFactory: (telegramAccountService: TelegramAccountsService) => { return new AddTelegramAccountAdapter(telegramAccountService); }, inject: [TelegramAccountsService], }, { provide: GetChatIdByUsernamePortSymbol, useFactory: (telegramAccountService: TelegramAccountsService) => { return new GetChatIdByUsernameAdapter(telegramAccountService); }, inject: [TelegramAccountsService], } ]; @Module({ imports: [DatabaseModule.forRoot()], providers, exports: [...providers], }) export class DatabaseDiModule { }
#!/usr/bin/env bash set -e # TODO: Set to URL of git repo. PROJECT_GIT_URL='https://github.com/rajiv-07/profiles-rest-api.git' PROJECT_BASE_PATH='/usr/local/apps/profiles-rest-api' echo "Installing dependencies..." apt-get update apt-get install -y python3-dev python3-venv sqlite python-pip supervisor nginx git # Create project directory mkdir -p $PROJECT_BASE_PATH git clone $PROJECT_GIT_URL $PROJECT_BASE_PATH # Create virtual environment mkdir -p $PROJECT_BASE_PATH/env python3 -m venv $PROJECT_BASE_PATH/env # Install python packages $PROJECT_BASE_PATH/env/bin/pip install -r $PROJECT_BASE_PATH/requirements.txt $PROJECT_BASE_PATH/env/bin/pip install uwsgi==2.0.18 # Run migrations and collectstatic cd $PROJECT_BASE_PATH $PROJECT_BASE_PATH/env/bin/python manage.py migrate $PROJECT_BASE_PATH/env/bin/python manage.py collectstatic --noinput # Configure supervisor cp $PROJECT_BASE_PATH/deploy/deploy/supervisor_profiles_api.conf /etc/supervisor/conf.d/profiles_api.conf supervisorctl reread supervisorctl update supervisorctl restart profiles_api # Configure nginx cp $PROJECT_BASE_PATH/deploy/deploy/nginx_profiles_api.conf /etc/nginx/sites-available/profiles_api.conf rm /etc/nginx/sites-enabled/default ln -s /etc/nginx/sites-available/profiles_api.conf /etc/nginx/sites-enabled/profiles_api.conf systemctl restart nginx.service echo "DONE! :)"
#!/usr/bin/env bash set -e source $SNAP/actions/common/utils.sh echo "Enabling default storage class" sudo mkdir -p ${SNAP_COMMON}/default-storage declare -A map map[\$SNAP_COMMON]="$SNAP_COMMON" use_manifest storage apply "$(declare -p map)" echo "Storage will be available soon" if [ -e ${SNAP_DATA}/var/lock/clustered.lock ] then echo "" echo "WARNING: The storage class enabled does not persist volumes across nodes" echo "" fi