language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
JavaScript
UTF-8
806
2.71875
3
[]
no_license
(function(birdmin){ function HistoryController() { var page = 0; var state = function(n) { return {page:n}; }; this.popped = false; /** * Push a URL into the history. * @param url string * @returns {Object} */ this.push = function(url) { if (url !== location.pathname+(location.query ? "" : "?"+location.query)) { this.popped = true; } page++; history.pushState(state(page), url, url); return history.state; }; this.pull = function(ajax) { ajax.get(location.href).then(ajax.link(false), ajax.error); }; } birdmin.history = new HistoryController(); })(birdmin);
Java
UTF-8
647
3.5
4
[]
no_license
package java02; public class ja02_12_ASCII코드 { public static void main(String[] args) { int x = '4'; //문자가 숫자로 변환됨, ASCII:52 int y = '5'; //문자가 숫자로 변환됨, ASCII:53 int res = 0; res = x + y; System.out.println(res); res = x - y; System.out.println(res); res = x * y; System.out.println(res); res = x / y; System.out.println(res); res = x % y; System.out.println(res); } }
Python
UTF-8
62
3.140625
3
[]
no_license
def multiply(num): x = num * num print x multiply(100)
Java
UTF-8
1,139
3.65625
4
[]
no_license
package collectionFramework.maps; import java.util.*; import java.util.HashSet; class marker{ int price; String colour; public marker(int x,String s) { price = x; colour =s; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((colour == null) ? 0 : colour.hashCode()); result = prime * result + price; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; marker other = (marker) obj; if (colour == null) { if (other.colour != null) return false; } else if (!colour.equals(other.colour)) return false; if (price != other.price) return false; return true; } } public class HashcodeEqualsPart_2 { public static void main(String[] args) { marker m1= new marker(10,"blue"); marker m2=new marker (10,"blue"); Set<marker> markers =new HashSet<>(); markers.add(m2); markers.add(m1); System.out.println("m1 = "+m1); System.out.println("m2 = "+m2); System.out.println("m1==m2 : "+(m1==m2)); System.out.println(markers); } }
Ruby
UTF-8
1,477
2.984375
3
[ "MIT" ]
permissive
# frozen_string_literal: true module Chatrix class Bot module Plugins # Plugin to query various information about the bot. class Info < Plugin TIME_MULTS = [24, 60, 60, 1].freeze register_command 'info', nil, 'Provides info about the bot', handler: :info register_command 'uptime', nil, 'Tells how long the bot has been running for', handler: :uptime def initialize(bot) super @info = "I am chatrix-bot v#{Chatrix::Bot::VERSION}, " \ "using chatrix v#{Chatrix::VERSION}." end def info(room, _sender, _command, _data) room.messaging.send_notice @info end def uptime(room, _sender, _command, _data) duration = pretty_duration @bot.uptime room.messaging.send_notice "Current uptime: #{duration}" end private def pretty_duration(seconds) values = get_values(seconds) format '%03d' + ':%02d' * (values.size - 1), *values end def get_values(remain, index = 0, acc = []) return acc if index == TIME_MULTS.count mult = time_mult index acc.push remain / mult get_values remain - acc.last * mult, index + 1, acc end def time_mult(index) TIME_MULTS[index..-1].reduce { |a, e| a * e } end end end end end
C#
UTF-8
241
2.734375
3
[]
no_license
foreach (DataGridViewCell selectedCell in dataGridView1.SelectedCells) { foreach (DataGridViewCell cell in selectedCell.OwningRow.Cells) { if (cell.ColumnIndex > selectedCell.ColumnIndex) cell.Value = selectedCell.Value; } }
C++
UTF-8
1,077
3.4375
3
[]
no_license
#include <iostream> #include "nodei.h" using namespace std; int main() { int choice,n,m,position,i; NodeImplementation obj; while(1) { cout<<endl<<"1. Create List"<<endl; cout<<"2. EnQueue"<<endl; cout<<"3. DeQueue"<<endl; cout<<"4. Display"<<endl; cout<<"5. ShowSize"<<endl; cout<<"6. PEEK"<<endl; cout<<"Enter ur choice : "; cin>>choice; switch(choice) { case 1: cout<<"How many nodes u want:"<<endl; cin>>n; for(i=0;i<n;i++) { cout<<"Enter the element"<<endl; cin>>m; obj.createQueue(m); } break; case 2: { cout<<"Enter the element"<<endl; cin>>m; obj.enQueue(m); break; } case 3: { cout<<"This : "<<obj.deQueue()<<" came out from Queue"<<endl; break; } case 4: { obj.display(); break; } case 5: { cout<<"List Size : "<<obj.getSize(); break; } case 6: { cout<<endl<<"This is On the Head : "<<obj.peek()<<endl; break; } default: cout<<"Wrong choice"<<endl; } } return 0; }
Python
UTF-8
970
2.796875
3
[]
no_license
import speech_recognition as sr from gtts import gTTS from translation import evaluate from SentimentAnalysis import predict import os from time import sleep import pyglet from sarcasm import predict_text import playsound import numpy as np def translate(): r = sr.Recognizer() with sr.Microphone() as source: r.adjust_for_ambient_noise(source) audio = r.listen(source) # import pdb; pdb.set_trace() text = r.recognize_google(audio) sentiment = predict(text) translation = evaluate(text)[0][:-6] sarcasm = predict_text(text) tts = gTTS(text=translation, lang='fr') filename = f'temp{text[0]}{np.random.randn()}.mp3' tts.save(filename) playsound.playsound(filename, True) os.remove(filename) #remove temperory file print(f"English: {text}, French: {translation}, Sentiment:{sentiment}, Sarcasm:{sarcasm}") return {"English": text, "French": translation, "Sentiment": sentiment, "Sarcasm": sarcasm}
Java
UTF-8
1,379
2.515625
3
[]
no_license
package db; import java.sql.Connection; import java.sql.PreparedStatement; public class DBassignproject { public String insert(int fname,int lname) { try{ Connection con= DBConnect.getConnect(); String query="update add_employee set application_id=?,status=? where employee_id=?"; PreparedStatement pstmt=con.prepareStatement(query); pstmt.setInt(1,fname); pstmt.setString(2,"assigned"); pstmt.setInt(3,lname); pstmt.executeUpdate(); con.setAutoCommit(true); String query1="insert into status_employee(Employee_id,Application_id,Status,Bill_status)values(?,?,?,?)"; PreparedStatement pstmt1=con.prepareStatement(query1); pstmt1.setInt(1,lname); pstmt1.setInt(2,fname); pstmt1.setString(3,"assigned"); pstmt1.setString(4,"onprocess"); pstmt1.executeUpdate(); con.setAutoCommit(true); String query2="update add_application set Status=? where Application_id=?"; PreparedStatement pstmt2=con.prepareStatement(query2); pstmt2.setString(1,"assigned"); pstmt2.setInt(2,fname); pstmt2.executeUpdate(); con.setAutoCommit(true); con.close(); return "Inserted"; } catch(Exception ex){ return "Exception------------------------> "+ex; } } }
JavaScript
UTF-8
3,490
3.265625
3
[]
no_license
/* global $, boardDetails */ 'use strict'; const playMechanics = (function(){ // initial state of gamePlay const state = { seqArr: [], respArr: [], strictMode: false, count: 0, inPlay: false }; //render function // -- checks for strict mode // -- check status of seqArr vs respArr --> separate function // increase counter // end game (disable clicks) // adds one to seqArr and plays (disable clicks) // -- checks for end of game // -- updated counter const strictGameCheck = function(){ console.log('strict'); }; const gameCheck = function(){ let j = state.count-1; if (state.seqArr.length === 0){ state.seqArr.push(boardDetails.randomQ()); playSeqArr(); } else if (state.respArr.length < state.seqArr.length){ for(let k=0; k<state.respArr.length; k++){ if (state.respArr[k] !== state.seqArr[k]){ setTimeout(function() { alert('Mistake! Try Again.'); }, 750); setTimeout(playSeqArr, 750); state.respArr = []; } } } else if (state.respArr[j] === state.seqArr[j]){ if(j<19){ state.seqArr.push(boardDetails.randomQ()); setTimeout(playSeqArr, 750); state.respArr = []; } else{ alert('Congratulations! You won!'); state.inPlay = false; render(); } } else { setTimeout(function() { alert('Mistake! Try Again.'); }, 750); setTimeout(playSeqArr, 750); state.respArr = []; } }; const render = function(){ if(state.inPlay){ if (state.strictMode){ strictGameCheck(); }else { gameCheck(); } } else{ state.seqArr = []; } state.count = state.seqArr.length; $('#counter').html(`${state.count}`); }; // function to play through seqArr // -- enables clicks after it's done and renders let i = 0; const loopThroughSeqArr = function(){ if (i < state.seqArr.length){ setTimeout(function(){ boardDetails.playRightQ(state.seqArr[i]); i++; loopThroughSeqArr(); }, 750); } }; const playSeqArr = function(){ i = 0; loopThroughSeqArr(); }; // event listeners for clicks on quarters // -- calls boardDetails.playRightQ(qx) // -- calls render const quarterClick = function(event){ const id = $(event.target)[0].id; boardDetails.playRightQ(id); if(state.inPlay){ state.respArr.push(id); render(); } console.log(state.seqArr, state.respArr); }; const handleQuarterClicked = function() { $('.quarter').on('click', quarterClick); }; // event listener on Start // -- enables clicks // -- resets seqArr and respArr // -- calls render const handleStartClicked = function(){ $('#start-button').on('click', function(event){ console.log('start button clicked!'); state.inPlay = true; state.seqArr = []; state.respArr = []; setTimeout(render(), 750); }); }; // event listener on Strict // -- toggles strictMode const handleStrictClicked = function(){ $('#strict-button').on('click', function(event){ console.log('strict button clicked'); state.inPlay = false; render(); }); }; const bindEventListeners = function(){ handleStartClicked(); handleQuarterClicked(); handleStrictClicked(); }; return { bindEventListeners, render }; })();
Java
UTF-8
5,810
1.664063
2
[ "Apache-2.0" ]
permissive
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you 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. */ end_comment begin_package DECL|package|org.elasticsearch.plugins package|package name|org operator|. name|elasticsearch operator|. name|plugins package|; end_package begin_import import|import name|joptsimple operator|. name|OptionSet import|; end_import begin_import import|import name|org operator|. name|elasticsearch operator|. name|cli operator|. name|EnvironmentAwareCommand import|; end_import begin_import import|import name|org operator|. name|elasticsearch operator|. name|cli operator|. name|Terminal import|; end_import begin_import import|import name|org operator|. name|elasticsearch operator|. name|env operator|. name|Environment import|; end_import begin_import import|import name|java operator|. name|io operator|. name|IOException import|; end_import begin_import import|import name|java operator|. name|nio operator|. name|file operator|. name|DirectoryStream import|; end_import begin_import import|import name|java operator|. name|nio operator|. name|file operator|. name|Files import|; end_import begin_import import|import name|java operator|. name|nio operator|. name|file operator|. name|Path import|; end_import begin_import import|import name|java operator|. name|util operator|. name|ArrayList import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Collections import|; end_import begin_import import|import name|java operator|. name|util operator|. name|List import|; end_import begin_comment comment|/** * A command for the plugin cli to list plugins installed in elasticsearch. */ end_comment begin_class DECL|class|ListPluginsCommand class|class name|ListPluginsCommand extends|extends name|EnvironmentAwareCommand block|{ DECL|method|ListPluginsCommand name|ListPluginsCommand parameter_list|() block|{ name|super argument_list|( literal|"Lists installed elasticsearch plugins" argument_list|) expr_stmt|; block|} annotation|@ name|Override DECL|method|execute specifier|protected name|void name|execute parameter_list|( name|Terminal name|terminal parameter_list|, name|OptionSet name|options parameter_list|, name|Environment name|env parameter_list|) throws|throws name|Exception block|{ if|if condition|( name|Files operator|. name|exists argument_list|( name|env operator|. name|pluginsFile argument_list|() argument_list|) operator|== literal|false condition|) block|{ throw|throw operator|new name|IOException argument_list|( literal|"Plugins directory missing: " operator|+ name|env operator|. name|pluginsFile argument_list|() argument_list|) throw|; block|} name|terminal operator|. name|println argument_list|( name|Terminal operator|. name|Verbosity operator|. name|VERBOSE argument_list|, literal|"Plugins directory: " operator|+ name|env operator|. name|pluginsFile argument_list|() argument_list|) expr_stmt|; specifier|final name|List argument_list|< name|Path argument_list|> name|plugins init|= operator|new name|ArrayList argument_list|<> argument_list|() decl_stmt|; try|try init|( name|DirectoryStream argument_list|< name|Path argument_list|> name|paths init|= name|Files operator|. name|newDirectoryStream argument_list|( name|env operator|. name|pluginsFile argument_list|() argument_list|) init|) block|{ for|for control|( name|Path name|plugin range|: name|paths control|) block|{ name|plugins operator|. name|add argument_list|( name|plugin argument_list|) expr_stmt|; block|} block|} name|Collections operator|. name|sort argument_list|( name|plugins argument_list|) expr_stmt|; for|for control|( specifier|final name|Path name|plugin range|: name|plugins control|) block|{ name|terminal operator|. name|println argument_list|( name|Terminal operator|. name|Verbosity operator|. name|SILENT argument_list|, name|plugin operator|. name|getFileName argument_list|() operator|. name|toString argument_list|() argument_list|) expr_stmt|; try|try block|{ name|PluginInfo name|info init|= name|PluginInfo operator|. name|readFromProperties argument_list|( name|env operator|. name|pluginsFile argument_list|() operator|. name|resolve argument_list|( name|plugin operator|. name|toAbsolutePath argument_list|() argument_list|) argument_list|) decl_stmt|; name|terminal operator|. name|println argument_list|( name|Terminal operator|. name|Verbosity operator|. name|VERBOSE argument_list|, name|info operator|. name|toString argument_list|() argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|IllegalArgumentException name|e parameter_list|) block|{ if|if condition|( name|e operator|. name|getMessage argument_list|() operator|. name|contains argument_list|( literal|"incompatible with version" argument_list|) condition|) block|{ name|terminal operator|. name|println argument_list|( literal|"WARNING: " operator|+ name|e operator|. name|getMessage argument_list|() argument_list|) expr_stmt|; block|} else|else block|{ throw|throw name|e throw|; block|} block|} block|} block|} block|} end_class end_unit
Java
UTF-8
940
2.359375
2
[]
no_license
package servicio; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import model.Contacto; @Service public class ServicioContactosImpl implements ServicioContactos { @Autowired RestTemplate rt; @Override public void alta(Contacto c) { String url = "http://localhost:8080/07_contactos_rest/accion"; String resultado = rt.postForObject(url,c,String.class); System.out.println("El resultado ha sido " + resultado); } @Override public Contacto[] obtenerContactos() { String url = "http://localhost:8080/07_contactos_rest/busqueda"; Contacto[] contactos = rt.getForObject(url,Contacto[].class); return contactos; } @Override public void eliminar(int idContacto) { String url = "http://localhost:8080/07_contactos_rest/accion"; rt.delete(url+"/"+idContacto); } }
Java
UTF-8
699
1.859375
2
[]
no_license
package android.text.method; public class Touch { Touch() { throw new RuntimeException("Stub!"); } public static void scrollTo(android.widget.TextView widget, android.text.Layout layout, int x, int y) { throw new RuntimeException("Stub!"); } public static boolean onTouchEvent(android.widget.TextView widget, android.text.Spannable buffer, android.view.MotionEvent event) { throw new RuntimeException("Stub!"); } public static int getInitialScrollX(android.widget.TextView widget, android.text.Spannable buffer) { throw new RuntimeException("Stub!"); } public static int getInitialScrollY(android.widget.TextView widget, android.text.Spannable buffer) { throw new RuntimeException("Stub!"); } }
Python
UTF-8
1,128
3.234375
3
[]
no_license
from typing import ItemsView def validIPAddress(string): ipAddressesFound = [] for i in range(1, min(len(string), 4)): print(len(string)) currentIPAddress = ["","","",""] currentIPAddress[0] = string[:i] if not isValid(currentIPAddress[0]): continue for j in range(i + 1, i + min(len(string) - i, 4)): print(len(string)) currentIPAddress[1] = string[i:j] if not isValid(currentIPAddress[1]): continue for k in range(j + 1, j + min(len(string) - j, 4)): print(len(string)) currentIPAddress[2] = string[j:k] currentIPAddress[3] = string[k:] if isValid(currentIPAddress[2]) and isValid(currentIPAddress[3]): ipAddressesFound.append(".".join(currentIPAddress)) return ipAddressesFound def isValid(string): stringAsInt = int(string) if stringAsInt > 255: return False return len(string) == len(str(stringAsInt)) #checks for leading 0's string = "1921680" print(validIPAddress(string))
Markdown
UTF-8
1,164
3.046875
3
[ "MIT" ]
permissive
# Component_pin_net_mapping A small script that takes a netlist created in Orcad and creates a pin-net mapping for components, connectors and testpoints. In order for this to work, the following naming conventions need to be set: * Components need to have the letter "U". * Connectors need to have the letter "J". * Testpoints need to have the letter "TP". ## How to "install" program * Clone the repo from GitHub * Install python through "anaconda Download" * Create an environment variable called %CONDA_PATH% for the path to where anaconda is installed. * Create an environment variable called %COMPONENT_MAPPING% for the path to where the downloaded files is located. ## How to run progam * A netlist needs to be generated prior to running this script. * In order to generate the file called "pstxnet.dat" * The program is ran by running the script called "Component_net_table.bat" * A dialog will show up * Navigate to the folder where the netlist is located. * The folder needs to have a file called "pstxnet.dat" * Then three excel documents is created in the folder chosen. * Components.xls * Connectors.xls * Testpoints.xls.
Java
UTF-8
1,704
3.25
3
[ "Apache-2.0" ]
permissive
package org.seasar.doma; import org.seasar.doma.internal.util.StringUtil; /** * Defines naming convention rules for the keys contained in a {@code Map<Object, String>} object. * * <p>The key name is resolved from a column name by applying this convention. */ public enum MapKeyNamingType { /** Does nothing. */ NONE { @Override public String apply(String text) { if (text == null) { throw new DomaNullPointerException("text"); } return text; } }, /** * Converts an underscore separated string to a camel case string. * * <p>For example, {@code AAA_BBB} is converted to {@code aaaBbb}. */ CAMEL_CASE { @Override public String apply(String text) { if (text == null) { throw new DomaNullPointerException("text"); } return StringUtil.fromSnakeCaseToCamelCase(text); } }, /** * Converts a string to an upper case string. * * <p>For example、{@code aaaBbb} is converted to {@code AAABBB}. */ UPPER_CASE { @Override public String apply(String text) { if (text == null) { throw new DomaNullPointerException("text"); } return text.toUpperCase(); } }, /** * Converts a string to an lower case string. * * <p>For example, {@code aaaBbb} is converted to {@code aaabbb}. */ LOWER_CASE { @Override public String apply(String text) { if (text == null) { throw new DomaNullPointerException("text"); } return text.toLowerCase(); } }; /** * Applies this naming conversion. * * @param text the text * @return the converted text */ public abstract String apply(String text); }
TypeScript
UTF-8
1,125
2.703125
3
[]
no_license
import { Interruptions } from "./interruptions" export class Observer { subscriber: any[] = [] subscribe(who: any, what: any, cb: any) { if (!this.subscriber[what]) { this.subscriber[what] = []; } for (var i = 0; i < this.subscriber[what].length; i++) { var o = this.subscriber[what][i]; if (o.item == who && o.callback == cb) { return; } } this.subscriber[what].push({ item: who, callback: cb }); } unsubscribe(who: any, what: any) { if (!this.subscriber[what]) return; for (var i = 0; i < this.subscriber[what].length; i++) { var o = this.subscriber[what][i]; if (o.item == who) { this.subscriber[what].splice(i, 1); return; } } } send(who: any, what: any, ...data: any) { if (!this.subscriber[what]) return; for (var i = 0; i < this.subscriber[what].length; i++) { var o = this.subscriber[what][i]; o.callback.bind(o.item)(who, data) } } }
C
UTF-8
1,472
3.59375
4
[]
no_license
#include <stdio.h> #include "bmi.h" void calculate_bmi_imperial() { UserInfo user_info; float ft, in; printf("---\n"); printf("Enter your weight (lbs): "); scanf(" %f", &user_info.weight); printf("Enter your height:\n"); printf(" Feet: "); scanf(" %f", &ft); printf(" Inches: "); scanf(" %f", &in); user_info.height = convert_ft_to_in(ft, in); // calculate BMI user_info.bmi = 703 * (user_info.weight / (user_info. height * user_info.height)); printf("\n"); print_result(user_info.bmi); } void calculate_bmi_metric() { UserInfo user_info; printf("---\n"); printf("Enter your weight (kg): "); scanf(" %f", &user_info.weight); printf("Enter your height (m): "); scanf(" %f", &user_info.height); // calculate BMI user_info.bmi = user_info.weight / (user_info.height * user_info.height); print_result(user_info.bmi); } char * get_bmi_status(float bmi) { char *status; if(bmi < 18.5) status = "UNDERWEIGHT"; else if (bmi >= 18.5 && bmi <= 24.9) status = "HEALTHY"; else if (bmi > 24.9 && bmi < 29.9) status = "OVERWEIGHT"; else if (bmi > 30.0) status = "OBESITY"; return status; } float convert_ft_to_in(float ft, float in) { return (ft * 12) + in; } void print_result(float bmi) { printf("\n"); printf("Your BMI is %.2f\n", bmi); printf("Your are in \"%s\" range\n", get_bmi_status(bmi)); }
C++
UTF-8
110
2.515625
3
[]
no_license
#include<iostream> using namespace std; int main() { int x[5]={0,1,2,3,4}; string y = char(x); cout<<y; }
Rust
UTF-8
681
2.765625
3
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
//! Unix-specific extensions. use heim_common::prelude::BoxFuture; use crate::ProcessResult; mod signal; pub use self::signal::Signal; /// Unix-specific extension to [Process]. /// /// [Process]: ../../struct.Process.html pub trait ProcessExt { /// Send the signal to process. /// /// Since `-> impl Trait` is not allowed yet in the trait methods, /// this method returns boxed `Future`. This behavior will change later. fn signal(&self, signal: Signal) -> BoxFuture<ProcessResult<()>>; } #[cfg(unix)] impl ProcessExt for crate::Process { fn signal(&self, signal: Signal) -> BoxFuture<ProcessResult<()>> { self.as_ref().signal(signal) } }
Java
UTF-8
2,351
2.6875
3
[ "Apache-2.0", "WTFPL" ]
permissive
package eu.ha3.matmos.editor; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.util.ArrayList; import java.util.Map; import javax.swing.AbstractListModel; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ListSelectionModel; import javax.swing.ScrollPaneConstants; import javax.swing.SwingConstants; import eu.ha3.matmos.editor.interfaces.ILister; public abstract class ListerPanel extends JPanel implements ILister { private static final long serialVersionUID = 1L; private JLabel titleLabel; private JList<String> list; private JPanel panel; private JButton create; private JPanel panel_1; public ListerPanel() { setLayout(new BorderLayout(0, 0)); JScrollPane scrollPane = new JScrollPane(); scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); add(scrollPane, BorderLayout.CENTER); list = new JList<>(); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list.setModel(new AbstractListModel<String>() { /** * */ private static final long serialVersionUID = 1L; String[] values = new String[] {}; @Override public int getSize() { return values.length; } @Override public String getElementAt(int index) { return values[index]; } }); scrollPane.setViewportView(list); panel = new JPanel(); add(panel, BorderLayout.SOUTH); panel.setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 5)); create = new JButton("Create new"); panel.add(create); panel_1 = new JPanel(); add(panel_1, BorderLayout.NORTH); titleLabel = new JLabel("no label"); panel_1.add(titleLabel); titleLabel.setHorizontalAlignment(SwingConstants.CENTER); } @Override public void setTitle(String title) { titleLabel.setText(title); } protected void updateWith(Map<String, ?> listing) { list.removeAll(); list.setListData(new ArrayList<>(listing.keySet()).toArray(new String[listing.keySet().size()])); } }
Python
UTF-8
241
3.09375
3
[]
no_license
# https://codeforces.com/problemset/problem/888/A n = int(input()) a = tuple(map(int, input().split())) ans = 0 for i in range(1, n-1): if a[i] < a[i+1] and a[i] < a[i-1] or a[i] > a[i+1] and a[i] > a[i-1]: ans += 1 print(ans)
Shell
UTF-8
8,453
2.875
3
[]
no_license
#!/usr/bin/haserl <% # This program is copyright © 2008-2013 Eric Bishop and is distributed under the terms of the GNU GPL # version 2.0 with a special clarification/exception that permits adapting the program to # configure proprietary "back end" software provided that all modifications to the web interface # itself remain covered by the GPL. # See http://gargoyle-router.com/faq.html#qfoss for more information eval $( gargoyle_session_validator -c "$COOKIE_hash" -e "$COOKIE_exp" -a "$HTTP_USER_AGENT" -i "$REMOTE_ADDR" -r "login.sh" -t $(uci get gargoyle.global.session_timeout) -b "$COOKIE_browser_time" ) gargoyle_header_footer -h -s "system" -p "usb_storage" -c "internal.css" -j "table.js usb_storage.js" -z "usb_storage.js" gargoyle network firewall nfsd samba vsftpd share_users %> <script> <!-- <% echo "var driveSizes = [];" echo "var storageDrives = [];" awk '{ print "storageDrives.push([\""$1"\",\""$2"\",\""$3"\",\""$4"\", \""$5"\", \""$7"\"]);" }' /tmp/mounted_usb_storage.tab 2>/dev/null echo "var physicalDrives = [];" #note that drivesWithNoMounts, refers to drives # with no mounts on the OS, not lack of network mounts echo "var drivesWithNoMounts = [];" #ugly one-liner #unmounted_drives=$( drives=$(cat /tmp/drives_found.txt | grep "dev" | sed 's/[0-9]:.*$//g' | uniq) ; for d in $drives ; do mounted=$(cat /proc/mounts | awk '$1 ~ /dev/ { print $1 }' | uniq | grep "$d") ; if [ -z "$mounted" ] ; then echo "$d" ; fi ; done ) drives="$(awk -F':' '$1 ~ /^\/dev\// { sub(/[0-9]+$/, "", $1); arr[$1]; } END { for (x in arr) { print x; } }' /tmp/drives_found.txt)" for d in ${drives}; do if awk -v devpath="^${d}[0-9]+" '$1 ~ devpath { is_mounted = "yes"} END { if (is_mounted == "yes") { exit 1; } }' /proc/mounts; then size=$(( 1024 * $(fdisk -s "$d") )) DRIVE=$(echo ${d##/*/}) if [ -e "/sys/class/block/$DRIVE/device/model" ]; then V=$(cat /sys/class/block/$DRIVE/device/vendor | xargs) P=$(cat /sys/class/block/$DRIVE/device/model | xargs) DRIVE="$V $P" else DRIVE=$d fi echo "drivesWithNoMounts.push( [ \"$d\", \"$size\", \"$DRIVE\" ] );" fi done echo "var extroot_enabled=\""$(mount | grep "/dev/sd.*on /overlay" | wc -l)"\";" echo "var extroot_drive=\""$(mount | awk '/\/dev\/sd.*on \/overlay/ {print $1}')"\";" %> //--> </script> <fieldset id="no_disks" style="display:none;"> <legend class="sectionheader"><%~ usb_storage.SDisk %></legend> <em><span class="nocolumn"><%~ Nomdsk %></span></em> </fieldset> <fieldset id="shared_disks"> <legend class="sectionheader"><%~ SDisk %></legend> <div id='ftp_wan_access_container' > <span class="nocolumn"> <input class="aligned_check" type='checkbox' id='ftp_wan_access' onclick='updateWanFtpVisibility()' />&nbsp; <label class="aligned_check_label" id='ftp_wan_access_label' for='ftp_wan_access'><%~ WFTP %></label> </span> </div> <div id='ftp_pasv_container' class="indent" > <span class="nocolumn"> <input class="aligned_check" type='checkbox' id='ftp_wan_pasv' onclick='updateWanFtpVisibility()' />&nbsp; <label class="aligned_check_label" id='ftp_wan_access_label' for='ftp_wan_pasv'><%~ WpFTP %></label>&nbsp; <input type="text" size='7' maxLength='5' onkeyup='proofreadPort(this)' id='pasv_min_port'>&nbsp;-&nbsp;<input type="text" size='7' maxLength='5' onkeyup='proofreadPort(this)' id='pasv_max_port'> </span> </div> <div id="ftp_wan_spacer" style="height:15px;"></div> <div id="cifs_workgroup_container" style="margin-bottom:20px;" > <label id="cifs_workgroup_label" class="leftcolumn" for="cifs_workgroup"><%~ CFWkg %>:</label> <input id="cifs_workgroup" class="rightcolumn" type="text" size='30'/> </div> <div id="user_container"> <label id="cifs_user_label" class="leftcolumn"><%~ CFUsr %>:</label> <span class="rightcolumnonly" id="user_container"> <label id="user_label" for="new_user" style="float:left;width:120px;"><%~ NewU %>:</label> <input id="new_user" type="text" /> </span> </div> <div class="rightcolumnonly" id="user_pass_container"> <label id="user_pass_label" for="user_pass" style="float:left;width:120px;"><%~ Pasw %>:</label> <input id="user_pass" type="password" /> </div> <div class="rightcolumnonly" id="user_pass_confirm_container"> <label id="user_pass_confirm_label" for="user_pass_confirm" style="float:left;width:120px;"><%~ CfPass %>:</label> <input id="user_pass_confirm" type="password" /> </div> <div class="rightcolumnonly" id="user_pass_container"> <input id="add_user" type="button" class="default_button" value="<%~ AddU %>" onclick="addUser()" style="margin-left:0px;" /> </div> <div class="rightcolumnonly" style="margin-bottom:20px;" id="user_table_container"> </div> <div id="sharing_add_heading_container"> <span class="nocolumn" style="text-decoration:underline;"><%~ ADir %>:</span> </div> <div id="sharing_add_controls_container" class="indent"> <%in templates/usb_storage_template %> <div> <input type="button" id="add_share_button" class="default_button" value="<%~ ADsk %>" onclick="addNewShare()" /> </div> </div> <div class="internal_divider"></div> <div id="sharing_current_heading_container"> <span class="nocolumn" style="text-decoration:underline;"><%~ CShare %>:</span> </div> <div id="sharing_mount_table_container"> </div> <div class="internal_divider"></div> <input type='button' value='<%~ SaveChanges %>' id="save_button" class="bottom_button" onclick='saveChanges()' /> <input type='button' value='<%~ Reset %>' id="reset_button" class="bottom_button" onclick='resetData()'/> </fieldset> <fieldset id="disk_unmount"> <legend class="sectionheader"><%~ Umnt %></legend> <div> <span class="leftcolumn" style="margin-bottom:60px;margin-left:0px;"><input type='button' value="<%~ UmntB %>" id="unmount_usb_button" class="default_button" onclick="unmountAllUsb()"></span> <span class="rightcolumn"><em><%~ UmntWarn %></em></span> </div> </fieldset> <fieldset id="disk_format"> <legend class="sectionheader"><%~ FDisk %></legend> <div id="no_unmounted_drives"> <em><span class="nocolumn"><%~ NoUmntDev %></span></em> </div> <div id="format_warning"> <em><span class="nocolumn"><%~ FmtWarn %></span></em> </div> <div id="format_disk_select_container"> <label id="format_disk_select_label" class="leftcolumn" for="format_disk_select"><%~ DskForm %>:</label> <select class="rightcolumn" id="format_disk_select" ></select> <br/> <span id="format_warning" class="right_column_only"></span> </div> <div id="swap_percent_container"> <label class="leftcolumn" id="swap_percent_label" for="swap_percent" ><%~ PSwap %>:</label> <span class="rightcolumn"><input id="swap_percent" type="text" onkeyup="updateFormatPercentages(this.id)" /></span>%&nbsp;&nbsp;<em><span id="swap_size"></span></em> </div> <div id="storage_percent_container"> <label class="leftcolumn" id="storage_percent_label" for="storage_percent" ><%~ PStor %>:</label> <span class="rightcolumn"><input id="storage_percent" type="text" onkeyup="updateFormatPercentages(this.id)" /></span>%&nbsp;&nbsp;<em><span id="storage_size"></span></em> </div> <div id="extroot_container"> <span class="rightcolumnonly"> <input type="checkbox" id="extroot" name="extroot" style="padding:0;margin:0px;vertical-align:middle;overflow:hidden;" /> <label id="extroot_label" for="extroot" style="vertical-align:middle"><%~ MExtr %></label> </span> <div class="rightcolumnonly"> <em><%~ ExtrWarn %></em> </div> </div> <div id="usb_format_button_container"> <span class="leftcolumn" style="margin-left:0px;" ><input type="button" value="<%~ FmtNow %>" id="usb_format_button" class="default_button" onclick="formatDiskRequested()" /></span> </div> </fieldset> <fieldset id="extroot_fieldset" style="display:none;"> <legend class="sectionheader"><%~ ExtrS %></legend> <span class="leftcolumn" style="margin-left:0px;"><input type="button" value="<%~ ExtrOff %>" id="extroot_button" class="default_button" onclick="disableExtroot();" /></span> <span class="rightcolumn"><em><%~ ExtDt %> <b><span id="extroot_drive"></span></b>.</em></span> </fieldset> <iframe id="reboot_test" onload="reloadPage()" style="display:none" ></iframe> <!-- <br /><textarea style="margin-left:20px;" rows=30 cols=60 id='output'></textarea> --> <script> <!-- resetData(); //--> </script> <% gargoyle_header_footer -f -s "system" -p "usb_storage" %>
Markdown
UTF-8
897
3.265625
3
[]
no_license
# Angular Dynamic Overflow Menu [**Read the full post about this menu on my blog**](https://jcs.wtf/angular-dynamic-overflow-menu/) > An "angular" approach to a very DRY dynamic overflow menu using [@angular/cdk](https://github.com/angular/components)s awesome portals. **Problem:** You need to develop a hotizontal toolbar for a responsive web app and you have no control over how wide your users pull the window. You face an overflow problem if the window gets too small. **Assumption:** There is no space for traditional, css-based responsiveness and horizontal scrolling is not an option because it sucks on desktop and no one would get it. **Solution:** Define breakpoints and move the actual components into an overlay menu using cdk portals. **Final Product:** ![dynamic overlay GIF](./dynamic-overflow-menu.gif) # Run it yourself 1. Clone the repo 2. `npm install` 3. `npm start`
Python
UTF-8
1,057
3.03125
3
[ "MIT" ]
permissive
from abc import ABC, abstractmethod class MAB(ABC): """ Abstract class that represents a multi-armed bandit (MAB) """ @abstractmethod def play(self, tround, context): """ Play a round Arguments ========= tround : int positive integer identifying the round context : 1D float array, shape (self.ndims * self.narms), optional context given to the arms Returns ======= arm : int the positive integer arm id for this round """ @abstractmethod def update(self, arm, reward, context): """ Updates the internal state of the MAB after a play Arguments ========= arm : int a positive integer arm id in {1, ..., self.narms} reward : float reward received from arm context : 1D float array, shape (self.ndims * self.narms), optional context given to arms """
Java
UTF-8
737
3.625
4
[]
no_license
package DataStructure; import java.util.LinkedHashMap; import java.util.Map; public class FirstNonRepeatingElement { public static void main(String[] args) { FirstNonRepeatingElement obj = new FirstNonRepeatingElement(); System.out.println(obj.methodFirstNonRepeating("Inzamamul")); } public Character methodFirstNonRepeating(String str) { char[] ch = str.toCharArray(); LinkedHashMap<Character, Integer> lhm = new LinkedHashMap<Character, Integer>(); for (char i : ch) { if (!lhm.containsKey(i)) { lhm.put(i, 1); } else { lhm.put(i, lhm.get(i) + 1); } } for (Map.Entry<Character, Integer> j : lhm.entrySet()) { if (j.getValue() == 1) { return j.getKey(); } } return null; } }
Markdown
UTF-8
698
2.65625
3
[]
no_license
# mustBeFile **Filetype:** _MATLAB&reg; function_ **Synopsis:** _Validate value is a filename (or set of filenames) on the path_ MUSTBEFILE is a validation function which wraps to isfile() and issues an error if the input argument is not comprised solely of existing files on the path. (The input can be a string array, character array, or cell array of character vectors (aka "cell-string") of any size.) ### Usage ### [] = MUSTBEFILE( A ) ### References ### See also <https://www.mathworks.com/help/matlab/ref/isfile.html isfile> <https://www.mathworks.com/help/matlab/matlab_prog/argument-validation-functions.html validation functions> ### Attributes - nInputs : 1 - nOutputs : 0
Java
UTF-8
875
2.5
2
[ "Apache-2.0" ]
permissive
package com.example.nekonekocats; import android.app.Activity; import android.content.res.Configuration; import androidx.appcompat.app.AppCompatDelegate; public class AppColorTheme { // Toggle the color theme of this app public static void toggle(Activity activity) { int currentNightMode = activity.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK; switch (currentNightMode) { case Configuration.UI_MODE_NIGHT_YES: // Change to light theme AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); break; case Configuration.UI_MODE_NIGHT_NO: default: // Change to night theme AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); break; } } }
JavaScript
UTF-8
442
4.0625
4
[]
no_license
Math.floor(Math.random() * 11); // [0 ,11[ // 1) Crear arreglo 5 elementos const arreglo = []; const arreglo2 = []; // 2) Cada elemento 1 o 0 for (let indice = 0; indice < 10; indice++) { arreglo[indice] = Math.floor(Math.random() * 2); } console.log(arreglo); for (let i = 0; i < 10; i++) { arreglo.push(Math.floor(Math.random() * 2)); } console.log(arreglo2); // [0 ,2[ // Ej: [0, 0, 1, 1, 0] // 3) Existe al menos un elementos = 1
PHP
UTF-8
1,474
2.546875
3
[]
no_license
<?php $sitegroup = ''; $env = ''; $sites = array( ); $backup_location = '/tmp/dumps'; $data = date('YmdHi'); // Create the backup directory. create_dir($backup_location); foreach ($sites as $uri) { $db_name = vget('gardens_db_name'); // Archive the themes and files to the backup directory. $files_dir = "/var/www/html/${sitegroup}.${env}/docroot/sites/g/files/${db_name}"; foreach (array('themes', 'files') as $type) { create_archive("${files_dir}/${type}", "${dump_dir}/${uri}.${date}.${type}.gz"); } // Dump the database to the backup directory. dump_database($uri, "@${sitegroup}.${env}" "${backup_location}/${uri}.${date}.sql.gz"); } function create_dir($dirname) { if (!file_exists($dirname)) { if (!mkdir($dirname)) { return drush_log("Could not create directory $dirname", 'error'); } } } function vget($name) { $value = variable_get($name); if (is_null($value)) { return drush_log("Could not find variable $name", 'error'); } } function create_archive($source, $target) { execute_command("tar czf $target -C $source ."); } function dump_database($uri, $drush_alias, $target) { execute_command("drush5 $drush_alias -l $uri sql-dump | gzip -9 > $target"); } function execute_command($command) { drush_print("Executing: $command"); $return = shell_exec($command); if (is_null($return)) { return drush_log('Command execution failed. Processing has been aborted.', 'error'); } return $return; }
Java
UTF-8
377
1.8125
2
[]
no_license
package com.john.cloud.provider.repositories; import com.john.cloud.provider.model.Good; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.jpa.repository.JpaRepository; /** * Created by cjl20 on 2017/5/16. */ public interface GoodRepository extends JpaRepository<Good, Long> { @Cacheable Good findByGoodUrl(String goodUrl); }
C#
UTF-8
2,921
2.84375
3
[]
no_license
using InternetBankingApp.Interfaces; using InternetBankingApp.Models; using InternetBankingApp.Utilities; using Microsoft.Data.SqlClient; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InternetBankingApp.Managers { public class CustomerManagerProxy : ICustomerManager { private readonly string _connectionString; private CustomerManager _customerManager; public List<Customer> Customers { get; } public CustomerManagerProxy(string connectionString) { _connectionString = connectionString; using var connection = _connectionString.CreateConnection(); SqlCommand command = connection.CreateCommand(); command.CommandText = "select * from Customer"; var accountManager = new AccountManager(_connectionString); Customers = command.GetDataTableAsync().Result.Select().Select(x => new Customer { CustomerID = (int)x["CustomerID"], Name = (string)x["Name"], Address = Convert.IsDBNull(x["Address"]) ? null : (string)x["Address"], City = Convert.IsDBNull(x["City"]) ? null : (string)x["City"], PostCode = Convert.IsDBNull(x["PostCode"]) ? null : (string)x["PostCode"], Accounts = accountManager.GetAccounts((int)x["CustomerID"]) }).ToList(); } public Customer GetCustomer(int customerID) { var customer = Customers.FirstOrDefault(x => x.CustomerID == customerID); if(customer is null) { _customerManager = new CustomerManager(_connectionString); customer = _customerManager.GetCustomer(customerID); } return customer; } public async Task InsertCustomerAsync(Customer customer) { if (Customers.Any()) { return; } using var connection = _connectionString.CreateConnection(); connection.Open(); var cmd = connection.CreateCommand(); cmd.CommandText = "insert into Customer (CustomerID, Name, Address, City, PostCode) values (@customerID, @name, @address, @city, @postCode)"; cmd.Parameters.AddWithValue("customerID", customer.CustomerID); cmd.Parameters.AddWithValue("name", customer.Name); cmd.Parameters.AddWithValue("address", customer.Address ?? (object)DBNull.Value); cmd.Parameters.AddWithValue("city", customer.City ?? (object)DBNull.Value); cmd.Parameters.AddWithValue("postCode", customer.PostCode ?? (object)DBNull.Value); await cmd.ExecuteNonQueryAsync(); } public List<Customer> GetAllCustomers() { return Customers; } } }
Markdown
UTF-8
2,713
2.75
3
[]
no_license
# Express application using ES6 ## 1. Pre Requisites ```sh 1. Install Node JS 2. Install NPM (Node Package Manager) ``` ## 2. Scaffolding ```sh npm init -y touch README.md touch .gitignore touch .flowconfig touch gulpfile.config.js touch .babelrc mkdir src mkdir dist ``` ## 3. Development #### 3.1 Install Gulp ```sh npm install -g gulp-cli npm install --save-dev gulp ``` #### 3.2 Install Lint (ESLINT) ```sh npm install --save-dev gulp-eslint npm install -g install-peerdeps install-peerdeps --dev eslint-config-airbnb ``` #### 3.3 Install Sass ```sh npm install --save-dev gulp-sass npm install --save-dev gulp-sourcemaps npm install --save-dev gulp-autoprefixer ``` ```javascript var gulp = require('gulp'); var sass = require('gulp-sass'); var sourcemaps = require('gulp-sourcemaps'); var autoprefixer = require('gulp-autoprefixer'); // ... variables var autoprefixerOptions = { browsers: ['last 2 versions', '> 5%', 'Firefox ESR'] }; gulp.task('sass', function () { return gulp .src(input) .pipe(sourcemaps.init()) .pipe(sass(sassOptions).on('error', sass.logError)) .pipe(sourcemaps.write()) .pipe(autoprefixer(autoprefixerOptions)) .pipe(gulp.dest(output)); }); ``` #### 3.4 Install Babel ```sh npm install --save-dev babel-register npm install --save-dev babel-preset-2015 npm install --save-dev babel-preset-stage-0 ``` _.babelrc_ ```json { "presets": ["es2015","stage-0"] } ``` #### 3.3 Install Gulp Plugins ```sh npm install --save-dev gulp-load-plugins npm install --save-dev gulp-babel npm install --save-dev gulp-util npm install --save-dev gulp-pug npm install --save-dev gulp-newer npm install --save-dev del ``` #### 3.4 Install Express & Middlewares ```sh npm install --save express npm install --save body-parser ``` #### 4 Build Gulp Config File ```javascript import gulp from 'gulp' import gulpLoadPlugins from 'gulp-load-plugins' // <== Load all the plugins without imports import del from 'del' import path from 'path' const plugins = gulpLoadPlugins() const bases = { src: 'src/', dist: 'dist/' } const sources = { env: ['./package.json','./.gitignore','./.env'], templates: ['templates/**/*.pug'], styles: ['sass/**/*.scss'], scripts: ['scripts/**/*.js'] } // Clean Task gulp.task('clean', () => { del.sync(['dist/**','dist/.*', '!dist']) }) // Copy Task gulp.task('copy-env', () => { gulp.src(sources.env) .pipe(plugins.newer(bases.dist)) .pipe(gulp.dest(bases.dist)) }) // HTML Task gulp.task('html', () => { gulp.src(sources.templates, {cwd: bases.src}) .pipe(pug()) .pipe(plugins.newer(bases.dist)) .pipe(gulp.dest(bases.dist)) }) gulp.task('default',['clean','copy-env','html']) ```
PHP
UTF-8
239
2.859375
3
[]
no_license
<?php namespace DesignPattern\Structural\DependencyInjection; class Feed { private $feed; public function __construct(FeedInterface $feed) { $this->feed = $feed; } public function get(){ return $this->feed->getMessages(); } }
Java
UTF-8
1,818
3.21875
3
[]
no_license
package fileIO; import java.io.IOException; import java.util.Scanner; public class SignUpService { //1.Get username and check it is exist or not (to prevent the user re-sign-up with registered credentials) //2.Get password and re-writing of password //3.After success message of sign-up redirect user to sign-in page private static Scanner scanner; public SignUpService() throws IOException { System.out.println("*************************"); System.out.println("* SIGN-UP *"); System.out.println("*************************"); scanner = new Scanner(System.in); getCredentials(); } public static void getCredentials() throws IOException { String userName = getUsername(); String password; if (!checkUserIsExist(userName)) { password = getPassword(); FileService.createUser(new Person(userName, password)); } else { System.out.println("You are re-directing to the Sign-in page..."); new SignInService(); //Run SignInService Constructor } } public static String getUsername() { System.out.println("Please enter your Username : "); String userName = scanner.nextLine(); return userName; } public static String getPassword() { System.out.println("Please enter your Password : "); String password = scanner.nextLine(); String reWritePassword = ""; while (!password.equals(reWritePassword)) { System.out.println("Please re-write you Password"); reWritePassword = scanner.nextLine(); } return password; } public static boolean checkUserIsExist(String userName) { return FileService.checkFileIsExist(userName); } }
Java
UTF-8
3,111
2.78125
3
[]
no_license
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import javax.swing.*; import org.json.*; public class CollegeMain { private static JFrame new_frame; public static void main(String[] args) throws IOException { // TODO Auto-generated method stub new_frame = new CollegeGUI(); new_frame.setVisible(true); } public static List<String> getCollegeData(String[] colleges) throws IOException { List<String> collegeFeedback = new ArrayList<>(); for (int i = 0; i < colleges.length; i++) { StringBuilder result = new StringBuilder(); String[] collegeNames = colleges[i].split(" "); String queryString = "https://api.data.gov/ed/collegescorecard/v1/schools?" + "school.name="; for (int j = 0; j < collegeNames.length; j++) { if (collegeNames.length > 1) { queryString += collegeNames[j] + "%20"; } else { queryString += collegeNames[j]; } } queryString += "&school.degrees_awarded.predominant=2,3&_fields=id,school.name,2016.student.size,school.degree_urbanization,2016.admissions.admission_rate.overall,2016.admissions.sat_scores.average.overall&api_key=sYfXIxxImmXyrrjZhjordCAOP7gtRQiACcnFpq0Z"; URL url = new URL(queryString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoOutput(true); conn.connect(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { result.append(line); } rd.close(); collegeFeedback.add(result.toString()); } return collegeFeedback; } public static void createText() throws IOException { String[] collegeArray = new String[1]; collegeArray[0] = ((CollegeGUI) new_frame).getInput(); List<String> testOutput = getCollegeData(collegeArray); // Change the conditional statement to apply to the output quantity (size) for (int i = 0; i < 1; i++) { // This needs to be figured out because with multiple school, you would // need to find the proper indices (not zero) JSONObject obj = new JSONObject(testOutput.get(i)); JSONArray pageName = obj.getJSONArray("results"); JSONObject schoolFields = pageName.getJSONObject(0); String schoolName = schoolFields.getString("school.name"); double acceptanceRate = (schoolFields.getDouble("2016.admissions.admission_rate.overall")) * 100; int studentBody = schoolFields.getInt("2016.student.size"); JPanel currentPanel = ((CollegeGUI) new_frame).getPanel(); currentPanel.add(new JLabel(schoolName + ": (2016)")); currentPanel.add(new JLabel(String.valueOf(acceptanceRate + "% Acceptance Rate"))); currentPanel.add(new JLabel(String.valueOf(studentBody + " Students"))); new_frame.pack(); } } }
Java
UTF-8
4,020
1.835938
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2010-2012 by PHP-maven.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.phpmaven.mojos.test; import java.io.File; import java.io.StringReader; import org.apache.maven.execution.MavenSession; import org.apache.maven.monitor.logging.DefaultLog; import org.codehaus.plexus.logging.console.ConsoleLogger; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.codehaus.plexus.util.xml.Xpp3DomBuilder; import org.junit.Assert; import org.junit.Test; import org.phpmaven.core.IComponentFactory; import org.phpmaven.phar.IPharPackagerConfiguration; import org.phpmaven.plugin.phar.ConvertPharMojo; import org.phpmaven.test.AbstractTestCase; /** * Testing the phar support with dependency extraction. * * @author <a href="mailto:Martin.Eisengardt@googlemail.com">Martin Eisengardt</a> * @author <a href="mailto:s.schulz@slothsoft.de">Stef Schulz</a> * @since 2.0.0 */ public class ConvertPharTest extends AbstractTestCase { /** * tests the goal "convert-phar" * * @throws Exception */ @Test public void testGoal() throws Exception { final MavenSession session = this.createSimpleSession("mojos-phar/convert-phar"); final File phar = new File(session.getCurrentProject().getBasedir(), "phar-with-dep1-folders-0.0.1.phar"); final File phar2 = new File(session.getCurrentProject().getBasedir(), "phar-with-dep1-folders-0.0.1-2.phar"); final File zip = new File(session.getCurrentProject().getBasedir(), "phar-with-dep1-folders-0.0.1.zip"); final File jar = new File(session.getCurrentProject().getBasedir(), "phar-with-dep1-folders-0.0.1.jar"); Assert.assertTrue(phar.exists()); Assert.assertFalse(phar2.exists()); Assert.assertFalse(zip.exists()); Assert.assertFalse(jar.exists()); Xpp3Dom config = Xpp3DomBuilder.build(new StringReader( "<configuration>" + "<from>"+phar.getAbsolutePath()+"</from>" + "<to>"+zip.getAbsolutePath()+"</to>" + "</configuration>")); ConvertPharMojo convertMojo = createCurrentConfiguredMojo( ConvertPharMojo.class, session, "convert-phar", config); convertMojo.execute(); config = Xpp3DomBuilder.build(new StringReader( "<configuration>" + "<from>"+zip.getAbsolutePath()+"</from>" + "<to>"+jar.getAbsolutePath()+"</to>" + "</configuration>")); convertMojo = createCurrentConfiguredMojo( ConvertPharMojo.class, session, "convert-phar", config); convertMojo.execute(); Assert.assertTrue(jar.exists()); config = Xpp3DomBuilder.build(new StringReader( "<configuration>" + "<from>"+jar.getAbsolutePath()+"</from>" + "<to>"+phar2.getAbsolutePath()+"</to>" + "</configuration>")); convertMojo = createCurrentConfiguredMojo( ConvertPharMojo.class, session, "convert-phar", config); convertMojo.execute(); Assert.assertTrue(phar2.exists()); // list files final IPharPackagerConfiguration pharConfig = lookup(IComponentFactory.class).lookup( IPharPackagerConfiguration.class, IComponentFactory.EMPTY_CONFIG, session); final Iterable<String> files = pharConfig.getPharPackager().listFiles(phar2, new DefaultLog(new ConsoleLogger())); assertIterableCount(files, 3); assertIterableContains(files, File.separatorChar + "folderA" + File.separatorChar + "MyClassA.php"); assertIterableContains(files, File.separatorChar + "folderB" + File.separatorChar + "MyClassB.php"); assertIterableContains(files, File.separatorChar + "META-INF" + File.separatorChar + "MANIFEST.MF"); } }
Python
UTF-8
1,161
3.65625
4
[]
no_license
""" You are given a **list of binary integers** and `k`, the **number of flips** allowed. Write a function that returns the indices of zeroes of which, when flipped, return the **longest contiguous sequence of ones**. ### Examples zero_indices([1, 0, 1, 1, 0, 0, 0, 1], 1) ➞ [1] zero_indices([1, 0, 0, 0, 0, 1], 1) ➞ [1] zero_indices([1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0], 3) ➞ [6, 7, 9] zero_indices([1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0], 3) ➞ [7, 8, 9] ### Notes If multiple combinations of indices tie for longest one sequence, return the indices which occur **first** (see examples #2, #3). """ def zero_indices(lst, k): start_point, index, maximum = 0, [], 0 for num in range(start_point, len(lst)): temp_list = [x for x in lst] for change in range(k): try: temp_list[temp_list.index(0, num)] = 1 except ValueError: break temp_list2 = "".join([str(x) for x in temp_list]).split("0") if max([len(x) for x in temp_list2]) > maximum: maximum = max([len(x) for x in temp_list2]) index = [x for x in range(len(lst)) if str(lst[x]) != str(temp_list[x])] return index
Markdown
UTF-8
4,188
3
3
[ "MIT" ]
permissive
# tqdm-ruby [![Build Status](https://github.com/powerpak/tqdm-ruby/actions/workflows/ruby-ci.yml/badge.svg?branch=master&event=push)](https://github.com/powerpak/tqdm-ruby/actions/workflows/ruby-ci.yml?query=event%3Apush+branch%3Amaster) [![Gem Version](https://badge.fury.io/rb/tqdm.svg?version=0.4.1)](https://badge.fury.io/rb/tqdm) tqdm-ruby allows you to add a progress indicator to your loops with minimal effort. It is a port of the excellent [tqdm library][tqdm] for python. tqdm (read taqadum, تقدّم) means "progress" in Arabic. Calling `#tqdm` (or `#with_progress`) on any `Enumerable` returns an enhanced clone that animates a meter during iteration. ```ruby require 'tqdm' (0...1000).tqdm.each { |x| sleep 0.01 } ``` The default output is sent to `$stderr` and looks like this: ![|####------| 492/1000 49% [elapsed: 00:05 left: 00:05, 88.81 iters/sec]](http://i.imgur.com/6y0t7XS.gif) It works equally well from within irb, [pry](http://pryrepl.org/), and [iRuby notebooks](https://github.com/SciRuby/iruby) as seen here: ![iRuby notebook screencap](http://i.imgur.com/DilrHuX.gif) *Why not progressbar, ruby-progressbar, powerbar, or any of the [other gems][]?* These typically have a bucketload of formatting options and you have to manually send updates to the progressbar object to use them. tqdm pleasantly encourages the laziest usage scenario, in that you "set it and forget it". [tqdm]: https://github.com/tqdm/tqdm [other gems]: https://www.ruby-toolbox.com/categories/CLI_Progress_Bars ## Install Install it globally from [Rubygems](https://rubygems.org/gems/tqdm): $ gem install tqdm # (might need sudo for a system ruby) *or* add this line to your application's Gemfile: gem 'tqdm' And then execute: $ bundle ## Usage All `Enumerable` objects gain access to the `#with_progress` method (aliased as `#tqdm`), which returns an enhanced object wherein any iteration (by calling `#each` or any of its relatives: `#each_with_index`, `#map`, `#select`, etc.) produces an animated progress bar on `$stderr`. ```ruby require 'tqdm' num = 1629241972611353 (2..Math.sqrt(num)).with_progress.reject { |x| num % x > 0 }.map { |x| [x, num/x] } # ... Animates a progress bar while calculating... # => [[32599913, 49976881]] ``` Options can be provided as a hash, e.g., `.with_progress(desc: "copying", leave: true)`. The following options are available: - `desc`: Short string, describing the progress, added to the beginning of the line - `total`: Expected number of iterations, if not given, `self.size || self.count` is used - `file`: A file-like object to output the progress message to, by default, `$stderr` - `leave`: A boolean (default `false`). Should the progress bar should stay on screen after it's done? - `min_interval`: Default is `0.5`. If less than `min_interval` seconds or `min_iters` iterations have passed since the last progress meter update, it is not re-printed (decreasing IO thrashing). - `min_iters`: Default is `1`. See previous. [Sequel](http://sequel.jeremyevans.net/) is an amazing database library for Ruby. tqdm can enhance its [`Dataset`](http://sequel.jeremyevans.net/rdoc/classes/Sequel/Dataset.html) objects to show progress while iterating (same options as above): ```ruby require 'tqdm/sequel' # Automatically requires tqdm and sequel # In-memory database for demonstration purposes DB = Sequel.sqlite DB.create_table :items do primary_key :id Float :price end # Show progress during big inserts (this isn't new) (0..100000).with_progress.each { DB[:items].insert(price: rand * 100) } # Show progress during long SELECT queries DB[:items].where{ price > 10 }.with_progress.each { |row| "do some processing here" } ``` ## TODO 1. Performance improvements 2. Add benchmark suite, expand test coverage 3. Add smoothing for speed estimates 4. Support unicode output (smooth blocks) 5. By default, resize to the apparent width of the output terminal ## Contributing 1. Fork it 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create new Pull Request
C++
UTF-8
746
3.234375
3
[]
no_license
#include <iostream> #include <cmath> float original(float x); //float mejor(float x); float mejor2(float x); float a = 0.01; int main(void) { std::cout.precision(8); std::cout.setf(std::ios::scientific); std::cout << "Grupo:\n"; std::cout << "Jorge Palmar Velasco\n"; std::cout << "Jorge Palmar Velasco\n"; for(int i = 0; i <= 100; ++i){ float x1 = i*a; float f1 = original(x1); float f2 = mejor2(x1); std::cout << x1 << "\t" << f1 << "\t" << f2 << "\n"; } return 0; } float original(float x) { return 5 - std::sqrt( 25 + x*x); } float mejor2(float x) { return -1.0*x*x/( 5 + std::sqrt( 25 + x*x)); } //float mejor(float x) //{ //x = 5 - std::sqrt( std::pow((x+5),2)-10*x); //return x; //}
Markdown
UTF-8
856
2.515625
3
[]
no_license
Strangelove is a creative agency based in Amsterdam for the "always on" world. By using their business acumen they aim to provide solutions that are relevant, human-friendly, memorable and above all, simple. Working as a full-stack developer my first order of business was to give the company website a much-needed makeover. I worked closely with the motion-graphics designer and experimented a lot with parallax-effects. While building this website I even created a library called [kubrick][kubrick] ([get it?][strangelove]) which made it easier to set up such pages. After that, my work shifted towards building a CMS that could eliminate a lot of the repetitive work setting up new client websites while still allowing for customisation. [kubrick]: https://github.com/strangelove/kubrick [strangelove]: https://en.wikipedia.org/wiki/Dr._Strangelove
Java
ISO-8859-1
497
3.796875
4
[]
no_license
package cynthia_urbano.laboratorio4; import java.util.Scanner; //Escribir un programa para comprobar si el nmero ingresado por el usuario es positivo o negativo public class NumeroPositivoNegativo { public static void main(String[] args) { Scanner sc = new Scanner (System.in); int num; System.out.println("Ingrese un nmero: "); num= sc.nextInt(); if(num>0) { System.out.println("El nmero es positivo"); }else System.out.println("El nmero es negativo"); } }
C
UTF-8
548
3.015625
3
[ "MIT" ]
permissive
/* Inspired by the same problem under: * https://github.com/tiny656/PAT */ #include <stdio.h> int fav[201], dp[201]; int main() { int n, m, l, x; scanf("%d\n%d", &n, &m); for (int i = 1; i <= m; i++) scanf("%d", &fav[i]); scanf("%d", &l); for (int i = 0; i < l; i++) { scanf("%d", &x); for (int j = 1; j <= m; j++) { if (dp[j - 1] > dp[j]) dp[j] = dp[j - 1]; if (x == fav[j]) dp[j]++; } } printf("%d\n", dp[m]); return 0; }
Shell
UTF-8
1,617
3.5625
4
[ "MIT" ]
permissive
#!/bin/bash # GENERATE AND WRITE ROOT PW #=============================================================================== function f_set_root_pw() { # remove root from shadow file awk '{ if($1 !~ /root/) print }' /mnt/etc/shadow > /mnt/etc/new_shadow # generate and add root pasword to the new shadow file openssl passwd -1 -salt xyz $ROOTPASSWORD > /tmp/root_pw echo "root:$(</tmp/root_pw):17393::::::" >> /mnt/etc/new_shadow rm /tmp/root_pw # replace shadow with new shadow file mv /mnt/etc/new_shadow /mnt/etc/shadow } #=============================================================================== # CREATE NEW USER #=============================================================================== function f_create_new_user() { arch-chroot /mnt /bin/bash -c "useradd -m -g users -G wheel,storage,power,network,video,audio -s /usr/bin/fish '$USERNAME'" f_set_user_pw echo "%wheel ALL=(ALL) ALL" >> /mnt/etc/sudoers.back } #=============================================================================== # GENERATE AND WRITE USER PW #=============================================================================== function f_set_user_pw() { # Clear User Password awk '{ if($1 !~ /'$USERNAME'/) print }' /mnt/etc/shadow > /mnt/etc/new_shadow # Set new User Password openssl passwd -1 -salt xyz $USERPASSWORD > /tmp/user_pw echo "$USERNAME:$(</tmp/user_pw):17393:0:99999:7:::" >> /mnt/etc/new_shadow rm /tmp/user_pw # replace shadow with new shadow file mv /mnt/etc/new_shadow /mnt/etc/shadow } #===============================================================================
JavaScript
UTF-8
709
3.203125
3
[]
no_license
/* This tests file contains sample demonstrating custom commands and its usage. */ /* Adding a custom command to the browser instance */ browser.addCommand("getPageTitleAndUrl", function (){ return { url: browser.getUrl(), title : browser.getTitle() }; }); /* Usage of custom command */ describe("Usage of custom command which returns the url and title of the page", function (){ it("Shows the usage of a custom command getPageTitelAndUrl", function (){ browser.url("http://ToolsQA.com"); var result = browser.getPageTitleAndUrl(); console.log("Page url is " + result.url); console.log("Page title is " + result.title); }); }); /* Real life usage of custom commands */
Swift
UTF-8
989
2.640625
3
[]
no_license
// // PersonTableViewCell.swift // Test1 // // Created by eCOM-arjun.tp on 15/09/21. // import UIKit class PersonTableViewCell: UITableViewCell { @IBOutlet weak var name: UILabel! @IBOutlet weak var age: UILabel! @IBOutlet weak var termDate: UILabel! @IBOutlet weak var termFee: UILabel! var abc = 0.0 override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func setProdCell(obj:Person){ name.text = obj.name age.text = String(Int32(obj.age)) termDate.text = obj.termDate termFee.text = String(Double(obj.fee)) } func setHeader() { name.text = "Name" age.text = "Age" termDate.text = "Term Date" termFee.text = "Term Fee" } }
Python
UTF-8
367
3.21875
3
[]
no_license
# A palindromic number reads the same both ways. # The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 c397 99. # Find the largest palindrome made from the product of two 3-digit numbers. from decorators import * import numpy as np import math def v1(): print() @timer def main(): v1() if __name__ == '__main__': main()
Java
UTF-8
12,610
1.820313
2
[]
no_license
package com.dayal.xmpptest2; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.annotation.TargetApi; import android.app.ActivityManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.os.Build; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.EditorInfo; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.dayal.xmpptest2.utils.Util; import org.jivesoftware.smack.SmackException; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.tcp.XMPPTCPConnection; import org.jivesoftware.smackx.iqregister.AccountManager; import org.jivesoftware.smackx.search.ReportedData; import org.jivesoftware.smackx.search.UserSearchManager; import org.jivesoftware.smackx.xdata.Form; import org.jxmpp.jid.parts.Localpart; import org.jxmpp.stringprep.XmppStringprepException; import java.io.IOException; import butterknife.ButterKnife; import butterknife.OnClick; import static android.Manifest.permission.READ_CONTACTS; /** * A login screen that offers login via email/password. */ public class LoginActivity extends AppCompatActivity { private static final String TAG="LoginActivity"; /** * Id to identity READ_CONTACTS permission request. */ private static final int REQUEST_READ_CONTACTS = 0; // UI references. private AutoCompleteTextView mJidView; private EditText mPasswordView; private View mProgressView; private View mLoginFormView; private BroadcastReceiver mBroadcastReceiver; private Context mContext; private static String email; private XmppConnection mConnection; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); ButterKnife.bind(this); //Show // Set up the login form. mJidView = (AutoCompleteTextView) findViewById(R.id.email); populateAutoComplete(); mPasswordView = (EditText) findViewById(R.id.password); // check if user is already logged in TODO change logic if (XmppConnectService.sConnectionState == XmppConnection.ConnectionState.AUTHENTICATED) { startActivity(new Intent(LoginActivity.this, TabbedActivity.class)); finish(); } mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) { if (id == 100 || id == EditorInfo.IME_NULL) { attemptLogin(); return true; } return false; } }); mLoginFormView = findViewById(R.id.login_form); mProgressView = findViewById(R.id.login_progress); mContext = this; } @OnClick(R.id.email_sign_in_button) public void onSignInBtnClick(){ Log.d(TAG,"attempting login on click"); attemptLogin(); } // only checks if user registered on current PHONE before @OnClick(R.id.email_sign_up_button) public void onSignUpBtnClick() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); if(prefs.contains("xmpp_registerState") && prefs.getString("xmpp_registerState",Util.UNREGISTERED) == Util.REGISTERED ){ prefs.edit().putString("xmpp_registerState",Util.REGISTERED).apply(); //TODO snack bar to ask for register again Toast.makeText(mContext, "A user is already registered", Toast.LENGTH_SHORT).show(); }else{ prefs.edit().putString("xmpp_registerState",Util.UNREGISTERED).apply(); } } //Login User // public void loginUser(Context objContext, XmppConnection objXmpptcpConnection, String strUsername, String strPassword) throws XmppStringprepException { // // // // // // // } @Override protected void onPause() { super.onPause(); this.unregisterReceiver(mBroadcastReceiver); } @Override protected void onResume() { super.onResume(); mBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); switch (action) { case XmppConnectService.UI_AUTHENTICATED: Log.d(TAG,"Got a broadcast to show the main app window"); //Show the main app window showProgress(false); Intent i2 = new Intent(mContext,TabbedActivity.class); startActivity(i2); finish(); break; } } }; IntentFilter filter = new IntentFilter(XmppConnectService.UI_AUTHENTICATED); this.registerReceiver(mBroadcastReceiver, filter); } private void populateAutoComplete() { if (!mayRequestPermissions()) { return; } //getLoaderManager().initLoader(0, null, this); } private boolean mayRequestPermissions() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { return true; } if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) { return true; } if (shouldShowRequestPermissionRationale(READ_CONTACTS)) { Snackbar.make(mJidView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE) .setAction(android.R.string.ok, new View.OnClickListener() { @Override @TargetApi(Build.VERSION_CODES.M) public void onClick(View v) { requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS); } }); } else { requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS); } return false; } /** * Callback received when a permissions request has been completed. */ @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == REQUEST_READ_CONTACTS) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { populateAutoComplete(); } } } /** * Attempts to sign in or register the account specified by the login form. * If there are form errors (invalid email, missing fields, etc.), the * errors are presented and no actual login attempt is made. */ private void attemptLogin() { // Reset errors. mJidView.setError(null); mPasswordView.setError(null); // Store values at the time of the login attempt. email = mJidView.getText().toString(); String password = mPasswordView.getText().toString(); // Intent intentCurrUserID = new Intent(LoginActivity.this, MessageListActivity.class); // intentCurrUserID.putExtra("CURRENT_USER_ID",email); boolean cancel = false; View focusView = null; // Check for a valid password, if the user entered one. if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) { mPasswordView.setError(getString(R.string.error_invalid_password)); focusView = mPasswordView; cancel = true; } // Check for a valid email address. if (TextUtils.isEmpty(email)) { mJidView.setError(getString(R.string.error_field_required)); focusView = mJidView; cancel = true; } else if (!isEmailValid(email)) { mJidView.setError(getString(R.string.error_invalid_jid)); focusView = mJidView; cancel = true; } if (cancel) { // There was an error; don't attempt login and focus the first // form field with an error. focusView.requestFocus(); } else { // Show a progress spinner, and kick off a background task to // perform the user login attempt. //showProgress(true); //This is where the login login is fired up. // Log.d(TAG,"Jid and password are valid ,proceeding with login."); // startActivity(new Intent(this,ContactListActivity.class)); //Save the credentials and login saveCredentialsAndLogin(); } } private void saveCredentialsAndLogin() { Log.d(TAG,"saveCredentialsAndLogin() called."); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor editor = prefs.edit(); editor.putString("xmpp_jid", mJidView.getText().toString()) .putString("xmpp_password", mPasswordView.getText().toString()) .putBoolean("xmpp_logged_in",true) .putString("xmpp_registerState", Util.REGISTERED) .apply(); Log.d(TAG,"xmpp_jid:" + mJidView.getText()); //Start the service Intent i1 = new Intent(this,XmppConnectService.class); startService(i1); } private boolean isEmailValid(String email) { //TODO: Replace this with your own logic return email.contains("@"); } private boolean isPasswordValid(String password) { //TODO: Replace this with your own logic return password.length() > 4; } /** * Shows the progress UI and hides the login form. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) private void showProgress(final boolean show) { // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow // for very easy animations. If available, use these APIs to fade-in // the progress spinner. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime); mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); mLoginFormView.animate().setDuration(shortAnimTime).alpha( show ? 0 : 1).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); } }); mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); mProgressView.animate().setDuration(shortAnimTime).alpha( show ? 1 : 0).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); } }); } else { // The ViewPropertyAnimator APIs are not available, so simply show // and hide the relevant UI components. mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); } } //Check if service is running. private boolean isServiceRunning(Class<?> serviceClass) { ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.getName().equals(service.service.getClassName())) { return true; } } return false; } }
PHP
UTF-8
1,369
2.609375
3
[ "BSD-3-Clause" ]
permissive
<?php namespace app\modules\admin\models; use Yii; /** * This is the model class for table "userstable". * * @property int $id * @property string $login * @property string $f_name * @property string $l_name * @property string $m_name * @property string $password * @property int $type * * @property Results[] $results */ class Users extends \yii\db\ActiveRecord { /** * {@inheritdoc} */ public static function tableName() { return 'userstable'; } /** * {@inheritdoc} */ public function rules() { return [ [['login', 'f_name', 'l_name', 'm_name', 'password'], 'string'], [['login', 'f_name', 'l_name', 'm_name', 'password'], 'required'], [['type'], 'integer'], [['login'], 'unique'], ]; } /** * {@inheritdoc} */ public function attributeLabels() { return [ 'id' => 'ID', 'login' => 'Логин', 'f_name' => 'Имя', 'l_name' => 'Фамилия', 'm_name' => 'Отчество', 'password' => 'Пароль', 'type' => 'Type', ]; } /** * @return \yii\db\ActiveQuery */ public function getResults() { return $this->hasMany(Results::className(), ['userid' => 'id']); } }
JavaScript
UTF-8
416
3.421875
3
[]
no_license
const body = document.querySelector('body'); const colorName = document.querySelector('.color'); const button = document.querySelector('.change-color'); button.addEventListener('click', () => { const newColor = getRandomHexColor(); body.style.backgroundColor = newColor; colorName.textContent = newColor; }); function getRandomHexColor() { return `#${Math.floor(Math.random() * 16777215).toString(16)}`; }
Java
UTF-8
373
1.851563
2
[]
no_license
package com.gopawpaw.erp.hibernate.p; /** * PlMstrId entity. @author MyEclipse Persistence Tools */ public class PlMstrId extends AbstractPlMstrId implements java.io.Serializable { // Constructors /** default constructor */ public PlMstrId() { } /** full constructor */ public PlMstrId(String plDomain, String plProdLine) { super(plDomain, plProdLine); } }
Markdown
UTF-8
1,875
4.03125
4
[ "MIT" ]
permissive
# Recipe 14.11, Filtering a Map ## Mutable maps Use `filterInPlace`: ```scala val x = collection.mutable.Map( 1 -> 100, 2 -> 200, 3 -> 300 ) x.filterInPlace((k,v) => k > 1) // x: HashMap(2 -> b, 3 -> c) x.filterInPlace((k,v) => v > 200) // x: HashMap(3 -> 300) ``` ## Mutable and immutable maps Use a predicate with `filterKeys` (and a view): ```scala val x = Map( 1 -> "a", 2 -> "b", 3 -> "c" ) val y = x.view.filterKeys(_ > 2).toMap // y: Map(3 -> c) ``` If you don’t call `toMap` at the end, you’ll see this result: ```scala val y = x.view.filterKeys(_ > 2) // result: // val y: scala.collection.MapView[Int, String] = MapView(<not computed>) ``` If your algorithm is longer, you can define a function (or method), and then pass it to `filterKeys`: ```scala def only1(i: Int) = if i == 1 then true else false ``` Pass the method to `filterKeys`: ```scala val x = Map(1 -> "a", 2 -> "b", 3 -> "c") val y = x.view.filterKeys(only1).toMap // y: Map(1 -> a) ``` Can also use a `Set` with `filterKeys`: ```scala val x = Map(1 -> "a", 2 -> "b", 3 -> "c") val y = x.view.filterKeys(Set(2,3)).toMap // y: Map[Int, String] = Map(2 -> b, 3 -> c) ``` ## Discussion `filter` on a map: ```scala // an immutable map val a = Map(1 -> "a", 2 -> "b", 3 -> "c") // filter by the key val b = a.filter((k,v) => k > 1) // b: Map(2 -> b, 3 -> c) // filter by the value val c = a.filter((k,v) => v != "b") // c: Map(1 -> a, 3 -> c) ``` `filter` can also use a tuple: ```scala // filter by the key (t._1) val b = a.filter((t) => t._1 > 1) // b: Map(2 -> b, 3 -> c) // filter by the value (t._2) val b = a.filter((t) => t._2 != "b") // b: Map(1 -> a, 3 -> c) ``` `take` lets you keep the first N elements from the map: ```scala val b = a.take(2) // b: Map(1 -> a, 2 -> b) ```
Python
UTF-8
1,464
2.96875
3
[]
no_license
""" This module contains tests for the Region class """ from unittest import TestCase from mock import MagicMock, patch from doboto import Region class TestRegion(TestCase): """ This class implements unittests for the Region class """ def setUp(self): """ Define resources usable by all unit tests """ self.test_url = "http://abc.example.com" self.test_uri = "{}/regions".format(self.test_url) self.test_do = "do" self.test_token = "abc123" self.test_agent = "Unit" self.instantiate_args = (self.test_do, self.test_token, self.test_url, self.test_agent) self.klass_name = "Region" self.klass = getattr(Region, self.klass_name) def test_class_exists(self): """ Region class is defined """ self.assertTrue(hasattr(Region, self.klass_name)) def test_can_instantiate(self): """ Region class can be instantiated """ exc_thrown = False try: self.klass(*self.instantiate_args) except Exception: exc_thrown = True self.assertFalse(exc_thrown) @patch('doboto.Region.Region.pages') def test_list_happy(self, mock_pages): """ list works with happy path """ region = self.klass(*self.instantiate_args) result = region.list() mock_pages.assert_called_with(self.test_uri, "regions")
C++
UTF-8
755
2.828125
3
[]
no_license
// Problem link: https://leetcode.com/problems/unique-paths-ii/ class Solution { public: int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { int m = obstacleGrid.size(); int n = obstacleGrid[0].size(); vector<vector<long long>> dp(m); for (int i=0; i<m; i++) { dp[i].resize(n, 0); } dp[0][0] = 1LL; for (int i=0; i<m; i++) { for (int j=0; j<n; j++) { if (obstacleGrid[i][j]) { dp[i][j] = 0; continue; } if (i > 0) dp[i][j] += dp[i-1][j]; if (j > 0) dp[i][j] += dp[i][j-1]; } } return dp[m-1][n-1]; } };
Java
UTF-8
823
2.546875
3
[]
no_license
package com.wiseassblog.androidcleanguiarchitecture; public interface IViewContract { enum UpdateViewEvent { UPDATE_LEFT_TEXT_LABEL, UPDATE_RIGHT_TEXT_LABEL, UPDATE_LEFT_SWITCH, UPDATE_RIGHT_SWITCH, UPDATE_LEFT_PROGRESS_BAR, UPDATE_RIGHT_PROGRESS_BAR } interface View{ } /** * We may only give the ViewModel String, int, bool */ interface ViewModel { public void setSubscriber(Subscriber<UpdateViewEvent> sub); public void clear(); public void setLeftTextLabel(String s); public void setRightTextLabel(String s); public void setLeftSwitch(boolean b); public void setRightSwitch(boolean b); public void setLeftProgress(int i); public void setRightProgress(int i); } }
PHP
UTF-8
1,839
2.53125
3
[ "MIT" ]
permissive
<?php namespace Tests\Feature\Queries; use Tests\TestCase; class UsersTest extends TestCase { /** * @var \App\User */ private $user; public function setUp(): void { parent::setUp(); $this->user = factory(\App\User::class)->create([ 'name' => 'test1', 'email' => 'test@mail.com', 'password' => 'asdzxc' ]); } public function testQueryUsersGet(): void { /** @var \Illuminate\Foundation\Testing\TestResponse $response */ $response = $this->graphQL(/** @lang GraphQL */ ' { users(orderBy: [ {field: "name", order: DESC} ], first: 51) { data { id, name } } } '); $names = $response->json('data.*.data.*.name'); $this->assertContains('test1', $names); } public function testQueryUserGet(): void { /** @var \Illuminate\Foundation\Testing\TestResponse $response */ $response = $this->graphQL(/** @lang GraphQL */ ' { user(id: ' . $this->user->id . ') { id, name } } '); $user = $response->json('data.user'); $this->assertEquals('test1', $user['name']); } public function testQueryUserGetError(): void { /** @var \Illuminate\Foundation\Testing\TestResponse $response */ $response = $this->graphQL(/** @lang GraphQL */ ' { user(id: ' . ($this->user->id + 1) . ') { id, name } } '); $user = $response->json('data.user'); $this->assertNull($user); } }
TypeScript
UTF-8
3,600
2.671875
3
[]
no_license
/// <reference path="../../typings/node/node.d.ts"/> // Configuration: // None // // Commands: // hubot brb and I'm back - move cards to in development list or paused // // Author: // Juan Jose Guevara, Aida Martinez <juanjose@acklenavenue.com, > var httpClient = require('request-promise'); var key = "797802d631d9baf29d186424fe55c3c3"; var token = "259861bea77d82e20ddb7bcbfde81cb49c7f04ec4dd62f361a8c35099471c8bb"; var in_development_list_id = "5531389b43906b56da8a6fe2"; var paused_list_id = "553143820a7dd8fa71f33793"; function TrelloBRB(robot: any) { robot.respond(/brb?(.*)/i, (msg: any) => { moveCardsToPausedList(msg); }); robot.respond(/I'm off for the day?(.*)/i, (msg: any) => { moveCardsToPausedList(msg); }); function moveCardsToPausedList(msg: any) { var username = msg.match[1].trim(); var options = { uri: "https://api.trello.com/1/lists/" + in_development_list_id + "/cards?key=" + key + "&token=" + token + "&members=true", method: "GET" }; httpClient(options).then((cards) => { var parsed_cards = JSON.parse(cards); var card_to_move = []; msg.send("Looking for your cards"); for(var i = 0; i < parsed_cards.length; i++){ for(var j = 0; j < parsed_cards[i].members.length; j++){ if(parsed_cards[i].members[j].username === username){ card_to_move.push(parsed_cards[i]); } } } if(card_to_move.length === 0){ msg.send("you don't have any card on development"); }else{ msg.send("moving cards to Paused list"); for(var i = 0; i < card_to_move.length; i++){ msg.send("moving card: " + card_to_move[i].name); httpClient({ uri: "https://api.trello.com/1/cards/" + card_to_move[i].id + "/idList?value=" + paused_list_id + "&key=" + key + "&token=" + token, method: "PUT" }).then((response) => { var card_moved = JSON.parse(response); msg.send("card " + card_moved.name + " moved!"); }).catch((error) => { msg.send("error: " + error); }); } } }).catch((error) => { msg.send("error while loading cards on development list"); }); }; robot.respond(/I'm back?(.*)/i, (msg: any) => { moveCardsToInDevelopmentList(msg); }); robot.respond(/I'm ready for work?(.*)/i, (msg: any) => { moveCardsToInDevelopmentList(msg); }); function moveCardsToInDevelopmentList(msg: any) { var username = msg.match[1].trim(); httpClient({ uri: "https://api.trello.com/1/lists/" + paused_list_id + "/cards?key=" + key + "&token=" + token + "&members=true", method: "GET" }).then((response) => { var cards = JSON.parse(response); var card_to_move = []; msg.send("Looking for your cards"); for(var i = 0; i < cards.length; i++){ for(var j = 0; j < cards[i].members.length; j++){ if(cards[i].members[j].username === username){ msg.send("cards found"); card_to_move.push(cards[i]); } } } if(card_to_move.length === 0){ msg.send("you don't have any card on paused"); }else{ msg.send("moving cards back to In Development list"); for(var i = 0; i < card_to_move.length; i++){ msg.send("moving card: " + card_to_move[i].name); httpClient({ uri: "https://api.trello.com/1/cards/" + card_to_move[i].id + "/idList?value=" + in_development_list_id + "&key=" + key + "&token=" + token, method: "PUT" }).then((response) => { var card_moved = JSON.parse(response); msg.send("card " + card_moved.name + " moved!"); }).catch((error) => { msg.send("error: " + error); }); } } }).catch((error) => { msg.send("error while loading cards on paused list"); }); }; } export = TrelloBRB;
Python
UTF-8
1,380
2.5625
3
[ "MIT" ]
permissive
from django.test import TestCase from rest_framework.reverse import reverse class SeriesTestCase(TestCase): fixtures = ['series.json'] def test_series_list(self): resp = self.client.get(reverse('api:v1:series-list')) self.assertEqual(resp.status_code, 200) self.assertIsInstance(resp.data, list) def test_series_detail(self): resp = self.client.get(reverse('api:v1:series-detail', kwargs=dict(pk=1))) self.assertEqual(resp.status_code, 200) self.assertIsInstance(resp.data, dict) self.assertIn('id', resp.data) self.assertEqual(resp.data['id'], 1) self.assertIn('name', resp.data) self.assertEqual(resp.data['name'], 'Mighty Morphin Power Rangers') self.assertIn('seasons', resp.data) self.assertIsInstance(resp.data['seasons'], list) self.assertGreaterEqual(len(resp.data['seasons']), 1) season = resp.data['seasons'][0] self.assertIn('id', season) self.assertEqual(season['id'], 2) self.assertIn('number', season) self.assertEqual(season['number'], 1) self.assertIn('year', season) self.assertEqual(season['year'], 1993) def test_series_not_found(self): resp = self.client.get(reverse('api:v1:series-detail', kwargs=dict(pk=9999))) self.assertEqual(resp.status_code, 404)
Java
UTF-8
6,031
2.375
2
[ "MIT" ]
permissive
/* * 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 assignmentone_magazine; import java.util.HashMap; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author becky */ public class InvoiceTest { public InvoiceTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of SetInvoiceID method, of class Invoice. */ @Test public void testSetInvoiceID() { System.out.println("SetInvoiceID"); String inputID = ""; Invoice instance = null; instance.SetInvoiceID(inputID); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of GetInvoiceID method, of class Invoice. */ @Test public void testGetInvoiceID() { System.out.println("GetInvoiceID"); Invoice instance = null; String expResult = ""; String result = instance.GetInvoiceID(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of SetPatronEmail method, of class Invoice. */ @Test public void testSetPatronEmail() { System.out.println("SetPatronEmail"); String inputEmail = ""; Invoice instance = null; instance.SetPatronEmail(inputEmail); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of GetPatronEmail method, of class Invoice. */ @Test public void testGetPatronEmail() { System.out.println("GetPatronEmail"); Invoice instance = null; String expResult = ""; String result = instance.GetPatronEmail(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of SetCustomer method, of class Invoice. */ @Test public void testSetCustomer() { System.out.println("SetCustomer"); Customer inputCustomer = null; Invoice instance = null; instance.SetCustomer(inputCustomer); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of GetCustomer method, of class Invoice. */ @Test public void testGetCustomer() { System.out.println("GetCustomer"); Invoice instance = null; Customer expResult = null; Customer result = instance.GetCustomer(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of SetSubscriptions method, of class Invoice. */ @Test public void testSetSubscriptions() { System.out.println("SetSubscriptions"); HashMap<String, Subscription> inputSubscription = null; Invoice instance = null; instance.SetSubscriptions(inputSubscription); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of GetSubscriptions method, of class Invoice. */ @Test public void testGetSubscriptions() { System.out.println("GetSubscriptions"); Invoice instance = null; HashMap<String, Subscription> expResult = null; HashMap<String, Subscription> result = instance.GetSubscriptions(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of SetInvoiceDate method, of class Invoice. */ @Test public void testSetInvoiceDate() { System.out.println("SetInvoiceDate"); Datum inputDate = null; Invoice instance = null; instance.SetInvoiceDate(inputDate); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of GetInvoiceDate method, of class Invoice. */ @Test public void testGetInvoiceDate() { System.out.println("GetInvoiceDate"); Invoice instance = null; Datum expResult = null; Datum result = instance.GetInvoiceDate(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of PrintInvoice method, of class Invoice. */ @Test public void testPrintInvoice() { System.out.println("PrintInvoice"); Invoice instance = null; instance.PrintInvoice(); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of GetTotalInvoice method, of class Invoice. */ @Test public void testGetTotalInvoice() { System.out.println("GetTotalInvoice"); Invoice instance = null; float expResult = 0.0F; float result = instance.GetTotalInvoice(); assertEquals(expResult, result, 0.0); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } }
JavaScript
UTF-8
278
2.65625
3
[]
no_license
// JavaScript Document /* * 打印机效果 * Copyright (c) 2013 某年某月 * Date: 2013-05-20 * */ function PrintWord() { if (count <= str.length) { obj.innerHTML = str.substring(0, count); count++; } else { clearInterval(time); } }
Python
UTF-8
1,707
3.203125
3
[]
no_license
import pandas as pd import matplotlib.pyplot as plt from matplotlib.lines import Line2D from matplotlib.patches import Patch # read csv X = pd.read_csv("congress-terms.csv", thousands=',') # form data frame from csv df = pd.DataFrame(X) # only for the state of Wyoming df = df.loc[df['state'] == 'WY'] # make smaller data frames from the original, one for each type of marker df_D = df.loc[df['party'] == 'D'] df_R = df.loc[df['party'] == 'R'] df_O = df.loc[df['party'] != 'D'].loc[df['party'] != 'R'] df_list = [df_D, df_R, df_O] markers = ['*', '^', '.'] # make scatter plot (each data frame with its corresponding marker) fig, ax = plt.subplots() for d, m in zip(df_list, markers): # determine color based on dictionary color = d['chamber'].replace({'house': 'b', 'senate': 'r'}) ax.scatter(d['congress'], d['age'], c=color, marker=m) # title and labels ax.set_title('Congress Terms') ax.set_xlabel('nth Congress') ax.set_ylabel('Age') # make legend for different markers and colors legend_elements = [Line2D([0], [0], marker='*', color='w', label='Democrats', markerfacecolor='k', markersize=15), Line2D([0], [0], marker='^', color='w', label='Republicans', markerfacecolor='k', markersize=15), Line2D([0], [0], marker='.', color='w', label='Other Party', markerfacecolor='k', markersize=15), Patch(facecolor='blue', edgecolor='k', label='House'), Patch(facecolor='red', edgecolor='k', label='Senate')] ax.legend(handles=legend_elements, loc='best') plt.tight_layout() plt.show()
Java
UTF-8
191
2.78125
3
[]
no_license
package Threads; public class SecondThread implements Runnable { @Override public void run() { System.out.println("Second thread is Running by Runnable interface"); } }
C++
UTF-8
657
2.734375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <iostream> #include <vector> #include <algorithm> #include <set> #include <queue> using namespace std; int main() { int fact[15]; fact[0] = 1; for(int i = 1; i < 15; ++i) fact[i] = i * fact[i - 1]; string v = "0123456789"; string res = ""; int indx = 1000000-1; while(v.size()) { int i = v.size() - 1; int p = indx / fact[i]; indx %= fact[i]; res.push_back(v[p]); v.erase(v.begin() + p); //cout << indx << " " << fact[i] << endl; } cout << res << endl; return 0; }
Markdown
UTF-8
929
3.5
4
[]
no_license
# 元素垂直居中的几种实现方式 - 单行文本垂直居中 - line-height - 利用 vertical-align 设置父级元素为 table-cell 以及 vertical-align:middle - 通过新增元素来实现垂直居中(after 也行) ```css .parent { height: 300px; font-size: 0px; } .child { font-size: 14px; display: inline-block; vertical-align: middle; } .childAdd { display: inline-block; vertical-align: middle; height: 100%; width: 0px; } ``` ```html <div class="parent"> <div class="child"> 我是垂直居中的,多点字可以变成多行文本我是垂直居中的 </div> <label class="childAdd"></label> </div> ``` - 通过绝对定位来实现垂直居中 position: absolute; top: 50%; transform: translateY(-50%); - margin-top:50vh; transform:translateY(-50%); (vh 是一个类似百分比的概念,50vh 就是 50%) - 使用弹性盒模型 flex 实现垂直居中 align-items: center
C#
UTF-8
693
3.125
3
[]
no_license
// See https://aka.ms/new-console-template for more information using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Running; Console.WriteLine("Hello, World!"); BenchmarkRunner.Run<HoistingAggregation>(); [MemoryDiagnoser] public class HoistingAggregation { [Benchmark] [Arguments(100, 10)] public int? A(int? x, int? y) { int? sum = 0; for (int i = 0; i < 1000; i++) sum += x + y; return sum.Value; } [Benchmark] [Arguments(100, 10)] public int? B(int? x, int? y) { int? sum = 0; var h = x + y; for (int i = 0; i < 1000; i++) sum += h; return sum.Value; } }
C
UTF-8
324
3.484375
3
[]
no_license
#include<stdio.h> void reverse(int *arr, int n){ int temp; for (int i = 0; i < n/2; i++){ temp = arr[i]; arr [n-i+1] = temp; } } int main(); int arr[] = {1,2,3,4,5,6,7}; reverse(arr, 7); for (int i = 0; i < 7; i++){ printf ("the value of %d element is: %d/n" , i, arr [i); } return 0; }
Java
UTF-8
20,048
1.53125
2
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
/* * Copyright (c) 2005-2010 Grameen Foundation USA * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * * See also http://www.apache.org/licenses/LICENSE-2.0.html for an * explanation of the license and how it is applied. */ package org.mifos.config.struts.action; import junit.framework.Assert; import org.mifos.accounts.loan.struts.action.MultipleLoanAccountsCreationAction; import org.mifos.application.util.helpers.ActionForwards; import org.mifos.application.util.helpers.Methods; import org.mifos.config.struts.actionform.LabelConfigurationActionForm; import org.mifos.framework.MifosMockStrutsTestCase; import org.mifos.framework.components.mifosmenu.MenuRepository; import org.mifos.framework.hibernate.helper.StaticHibernateUtil; import org.mifos.framework.persistence.TestDatabase; import org.mifos.framework.util.helpers.Constants; import org.mifos.framework.util.helpers.TestObjectFactory; import org.mifos.security.util.UserContext; public class LabelConfigurationActionStrutsTest extends MifosMockStrutsTestCase { public LabelConfigurationActionStrutsTest() throws Exception { super(); } private UserContext userContext; private String flowKey; @Override protected void tearDown() throws Exception { StaticHibernateUtil.closeSession(); super.tearDown(); } @Override protected void setUp() throws Exception { super.setUp(); userContext = TestObjectFactory.getContext(); request.getSession().setAttribute(Constants.USERCONTEXT, userContext); addRequestParameter("recordLoanOfficerId", "1"); addRequestParameter("recordOfficeId", "1"); request.getSession(false).setAttribute("ActivityContext", TestObjectFactory.getActivityContext()); flowKey = createFlow(request, MultipleLoanAccountsCreationAction.class); } public void testUpdateWithOutData() { request.setAttribute(Constants.CURRENTFLOWKEY, flowKey); setRequestPathInfo("/labelconfigurationaction.do"); addRequestParameter("method", "update"); addRequestParameter(Constants.CURRENTFLOWKEY, (String) request.getAttribute(Constants.CURRENTFLOWKEY)); actionPerform(); verifyActionErrors(new String[] { "Please specify Head office.", "Please specify Regional office.", "Please specify Sub regional office.", "Please specify Area office.", "Please specify Branch office.", "Please specify Client.", "Please specify Group.", "Please specify Center.", "Please specify Loans.", "Please specify Savings.", "Please specify State.", "Please specify Postal code.", "Please specify Ethnicity.", "Please specify Citizenship.", "Please specify Handicapped.", "Please specify Government ID.", "Please specify Address 1.", "Please specify Address 2.", "Please specify Address 3.", "Please specify Partial Application.", "Please specify Pending Approval.", "Please specify Approved.", "Please specify Cancel.", "Please specify Closed.", "Please specify On hold.", "Please specify Active.", "Please specify Inactive.", "Please specify Active in good standing.", "Please specify Active in bad standing.", "Please specify Closed-obligation met.", "Please specify Closed-rescheduled.", "Please specify Closed-written off.", "Please specify None.", "Please specify Grace on all repayments.", "Please specify Principal only grace.", "Please specify Interest.", "Please specify External ID.", "Please specify Bulk entry." }); verifyInputForward(); } public void testUpdate() throws Exception { try { request.setAttribute(Constants.CURRENTFLOWKEY, flowKey); setRequestPathInfo("/labelconfigurationaction.do"); addRequestParameter("method", "update"); addRequestParameter(Constants.CURRENTFLOWKEY, (String) request.getAttribute(Constants.CURRENTFLOWKEY)); addRequestParameter("headOffice", "Head Office-Changed"); addRequestParameter("regionalOffice", "Regional Office-Changed"); addRequestParameter("subRegionalOffice", "Divisional Office-Changed"); addRequestParameter("areaOffice", "Area Office-Changed"); addRequestParameter("branchOffice", "Branch Office-Changed"); addRequestParameter("client", "Member-Changed"); addRequestParameter("group", "Group-Changed"); addRequestParameter("center", "Kendra-Changed"); addRequestParameter("loans", "Loan-Changed"); addRequestParameter("savings", "Margin Money-Changed"); addRequestParameter("state", "State-Changed"); addRequestParameter("postalCode", "Postal Code-Changed"); addRequestParameter("ethnicity", "Caste-Changed"); addRequestParameter("citizenship", "Religion-Changed"); addRequestParameter("handicapped", "Handicapped-Changed"); addRequestParameter("govtId", "Government ID-Changed"); addRequestParameter("address1", "Address1-Changed"); addRequestParameter("address2", "Address2-Changed"); addRequestParameter("address3", "Village-Changed"); addRequestParameter("partialApplication", "Partial Application-Changed"); addRequestParameter("pendingApproval", "Application Pending Approval-Changed"); addRequestParameter("approved", "Application Approved-Changed"); addRequestParameter("cancel", "Cancel-Changed"); addRequestParameter("closed", "Closed-Changed"); addRequestParameter("onhold", "On Hold-Changed"); addRequestParameter("active", "Active-Changed"); addRequestParameter("inActive", "Inactive-Changed"); addRequestParameter("activeInGoodStanding", "Active in Good Standing-Changed"); addRequestParameter("activeInBadStanding", "Active in Bad Standing-Changed"); addRequestParameter("closedObligationMet", "Closed- Obligation met-Changed"); addRequestParameter("closedRescheduled", "Closed- Rescheduled-Changed"); addRequestParameter("closedWrittenOff", "Closed- Written Off-Changed"); addRequestParameter("none", "None-Changed"); addRequestParameter("graceOnAllRepayments", "Grace on all repayments-Changed"); addRequestParameter("principalOnlyGrace", "Principal only grace-Changed"); addRequestParameter("interest", "Service Charge-Changed"); addRequestParameter("externalId", "External Id-Changed"); addRequestParameter("bulkEntry", "Bulk entry-Changed"); actionPerform(); verifyNoActionErrors(); verifyNoActionMessages(); Assert.assertFalse(MenuRepository.getInstance().isMenuForLocale(userContext.getPreferredLocale())); setRequestPathInfo("/labelconfigurationaction.do"); addRequestParameter("method", "load"); actionPerform(); LabelConfigurationActionForm labelConfigurationActionForm = (LabelConfigurationActionForm) request.getSession() .getAttribute("labelconfigurationactionform"); Assert.assertEquals("Head Office-Changed", labelConfigurationActionForm.getHeadOffice()); Assert.assertEquals("Regional Office-Changed", labelConfigurationActionForm.getRegionalOffice()); Assert.assertEquals("Divisional Office-Changed", labelConfigurationActionForm.getSubRegionalOffice()); Assert.assertEquals("Area Office-Changed", labelConfigurationActionForm.getAreaOffice()); Assert.assertEquals("Branch Office-Changed", labelConfigurationActionForm.getBranchOffice()); Assert.assertEquals("Member-Changed", labelConfigurationActionForm.getClient()); Assert.assertEquals("Group-Changed", labelConfigurationActionForm.getGroup()); Assert.assertEquals("Kendra-Changed", labelConfigurationActionForm.getCenter()); Assert.assertEquals("Loan-Changed", labelConfigurationActionForm.getLoans()); Assert.assertEquals("Margin Money-Changed", labelConfigurationActionForm.getSavings()); Assert.assertEquals("State-Changed", labelConfigurationActionForm.getState()); Assert.assertEquals("Postal Code-Changed", labelConfigurationActionForm.getPostalCode()); Assert.assertEquals("Caste-Changed", labelConfigurationActionForm.getEthnicity()); Assert.assertEquals("Religion-Changed", labelConfigurationActionForm.getCitizenship()); Assert.assertEquals("Handicapped-Changed", labelConfigurationActionForm.getHandicapped()); Assert.assertEquals("Government ID-Changed", labelConfigurationActionForm.getGovtId()); Assert.assertEquals("Address1-Changed", labelConfigurationActionForm.getAddress1()); Assert.assertEquals("Address2-Changed", labelConfigurationActionForm.getAddress2()); Assert.assertEquals("Village-Changed", labelConfigurationActionForm.getAddress3()); Assert.assertEquals("Partial Application-Changed", labelConfigurationActionForm.getPartialApplication()); Assert.assertEquals("Application Pending Approval-Changed", labelConfigurationActionForm.getPendingApproval()); Assert.assertEquals("Application Approved-Changed", labelConfigurationActionForm.getApproved()); Assert.assertEquals("Cancel-Changed", labelConfigurationActionForm.getCancel()); Assert.assertEquals("Closed-Changed", labelConfigurationActionForm.getClosed()); Assert.assertEquals("On Hold-Changed", labelConfigurationActionForm.getOnhold()); Assert.assertEquals("Active-Changed", labelConfigurationActionForm.getActive()); Assert.assertEquals("Inactive-Changed", labelConfigurationActionForm.getInActive()); Assert.assertEquals("Active in Good Standing-Changed", labelConfigurationActionForm.getActiveInGoodStanding()); Assert.assertEquals("Active in Bad Standing-Changed", labelConfigurationActionForm.getActiveInBadStanding()); Assert.assertEquals("Closed- Obligation met-Changed", labelConfigurationActionForm.getClosedObligationMet()); Assert.assertEquals("Closed- Rescheduled-Changed", labelConfigurationActionForm.getClosedRescheduled()); Assert.assertEquals("Closed- Written Off-Changed", labelConfigurationActionForm.getClosedWrittenOff()); Assert.assertEquals("None-Changed", labelConfigurationActionForm.getNone()); Assert.assertEquals("Grace on all repayments-Changed", labelConfigurationActionForm.getGraceOnAllRepayments()); Assert.assertEquals("Principal only grace-Changed", labelConfigurationActionForm.getPrincipalOnlyGrace()); Assert.assertEquals("Service Charge-Changed", labelConfigurationActionForm.getInterest()); Assert.assertEquals("External Id-Changed", labelConfigurationActionForm.getExternalId()); Assert.assertEquals("Bulk entry-Changed", labelConfigurationActionForm.getBulkEntry()); setRequestPathInfo("/labelconfigurationaction.do"); addRequestParameter("method", "update"); addRequestParameter(Constants.CURRENTFLOWKEY, (String) request.getAttribute(Constants.CURRENTFLOWKEY)); addRequestParameter("headOffice", "Head Office"); addRequestParameter("regionalOffice", "Regional Office"); addRequestParameter("subRegionalOffice", "Divisional Office"); addRequestParameter("areaOffice", "Area Office"); addRequestParameter("branchOffice", "Branch Office"); addRequestParameter("client", "Member"); addRequestParameter("group", "Group"); addRequestParameter("center", "Kendra"); addRequestParameter("loans", "Loan"); addRequestParameter("savings", "Savings"); addRequestParameter("state", "State"); addRequestParameter("postalCode", "Postal Code"); addRequestParameter("ethnicity", "Caste"); addRequestParameter("citizenship", "Religion"); addRequestParameter("handicapped", "Handicapped"); addRequestParameter("govtId", "Government ID"); addRequestParameter("address1", "Address1"); addRequestParameter("address2", "Address2"); addRequestParameter("address3", "Village"); addRequestParameter("partialApplication", "Partial Application"); addRequestParameter("pendingApproval", "Application Pending Approval"); addRequestParameter("approved", "Application Approved"); addRequestParameter("cancel", "Cancel"); addRequestParameter("closed", "Closed"); addRequestParameter("onhold", "On Hold"); addRequestParameter("active", "Active"); addRequestParameter("inActive", "Inactive"); addRequestParameter("activeInGoodStanding", "Active in Good Standing"); addRequestParameter("activeInBadStanding", "Active in Bad Standing"); addRequestParameter("closedObligationMet", "Closed- Obligation met"); addRequestParameter("closedRescheduled", "Closed- Rescheduled"); addRequestParameter("closedWrittenOff", "Closed- Written Off"); addRequestParameter("none", "None"); addRequestParameter("graceOnAllRepayments", "Grace on all repayments"); addRequestParameter("principalOnlyGrace", "Principal only grace"); addRequestParameter("interest", "Service Charge"); addRequestParameter("externalId", "External Id"); addRequestParameter("bulkEntry", "Bulk entry"); actionPerform(); verifyNoActionErrors(); } finally { // this test leaves updated data in the database, so clear it out TestDatabase.resetMySQLDatabase(); } } public void testCancel() { request.setAttribute(Constants.CURRENTFLOWKEY, flowKey); setRequestPathInfo("/labelconfigurationaction.do"); addRequestParameter("method", "cancel"); addRequestParameter(Constants.CURRENTFLOWKEY, (String) request.getAttribute(Constants.CURRENTFLOWKEY)); actionPerform(); verifyNoActionErrors(); verifyNoActionMessages(); verifyForward(ActionForwards.cancel_success.toString()); } public void testValidate() throws Exception { setRequestPathInfo("/labelconfigurationaction.do"); addRequestParameter("method", "validate"); addRequestParameter(Constants.CURRENTFLOWKEY, flowKey); actionPerform(); verifyNoActionErrors(); verifyNoActionMessages(); verifyForward(ActionForwards.load_failure.toString()); } public void testValidateForUpdate() throws Exception { setRequestPathInfo("/labelconfigurationaction.do"); addRequestParameter("method", "validate"); addRequestParameter(Constants.CURRENTFLOWKEY, flowKey); request.setAttribute("methodCalled", Methods.update.toString()); actionPerform(); verifyNoActionErrors(); verifyNoActionMessages(); verifyForward(ActionForwards.update_failure.toString()); } /** * FIXME: This test passes at independent (with clean database), But its * failing with the surefire *Test semantic. * */ public void xtestLoad() throws Exception { setRequestPathInfo("/labelconfigurationaction.do"); addRequestParameter("method", "load"); performNoErrors(); verifyForward(ActionForwards.load_success.toString()); LabelConfigurationActionForm labelConfigurationActionForm = (LabelConfigurationActionForm) request.getSession() .getAttribute("labelconfigurationactionform"); Assert.assertEquals("Head Office", labelConfigurationActionForm.getHeadOffice()); Assert.assertEquals("Regional Office", labelConfigurationActionForm.getRegionalOffice()); Assert.assertEquals("Divisional Office", labelConfigurationActionForm.getSubRegionalOffice()); Assert.assertEquals("Area Office", labelConfigurationActionForm.getAreaOffice()); Assert.assertEquals("Branch Office", labelConfigurationActionForm.getBranchOffice()); Assert.assertEquals("Member", labelConfigurationActionForm.getClient()); Assert.assertEquals("Group", labelConfigurationActionForm.getGroup()); Assert.assertEquals("Kendra", labelConfigurationActionForm.getCenter()); Assert.assertEquals("Loan", labelConfigurationActionForm.getLoans()); Assert.assertEquals("Savings", labelConfigurationActionForm.getSavings()); Assert.assertEquals("State", labelConfigurationActionForm.getState()); Assert.assertEquals("Postal Code", labelConfigurationActionForm.getPostalCode()); Assert.assertEquals("Caste", labelConfigurationActionForm.getEthnicity()); Assert.assertEquals("Religion", labelConfigurationActionForm.getCitizenship()); Assert.assertEquals("Handicapped", labelConfigurationActionForm.getHandicapped()); Assert.assertEquals("Government ID", labelConfigurationActionForm.getGovtId()); Assert.assertEquals("Address1", labelConfigurationActionForm.getAddress1()); Assert.assertEquals("Address2", labelConfigurationActionForm.getAddress2()); Assert.assertEquals("Village", labelConfigurationActionForm.getAddress3()); Assert.assertEquals("Partial Application", labelConfigurationActionForm.getPartialApplication()); Assert.assertEquals("Application Pending Approval", labelConfigurationActionForm.getPendingApproval()); Assert.assertEquals("Application Approved", labelConfigurationActionForm.getApproved()); Assert.assertEquals("Cancel", labelConfigurationActionForm.getCancel()); Assert.assertEquals("Closed", labelConfigurationActionForm.getClosed()); Assert.assertEquals("On Hold", labelConfigurationActionForm.getOnhold()); Assert.assertEquals("Active", labelConfigurationActionForm.getActive()); Assert.assertEquals("Inactive", labelConfigurationActionForm.getInActive()); Assert.assertEquals("Active in Good Standing", labelConfigurationActionForm.getActiveInGoodStanding()); Assert.assertEquals("Active in Bad Standing", labelConfigurationActionForm.getActiveInBadStanding()); Assert.assertEquals("Closed- Obligation met", labelConfigurationActionForm.getClosedObligationMet()); Assert.assertEquals("Closed- Rescheduled", labelConfigurationActionForm.getClosedRescheduled()); Assert.assertEquals("Closed- Written Off", labelConfigurationActionForm.getClosedWrittenOff()); Assert.assertEquals("None", labelConfigurationActionForm.getNone()); Assert.assertEquals("Grace on all repayments", labelConfigurationActionForm.getGraceOnAllRepayments()); Assert.assertEquals("Principal only grace", labelConfigurationActionForm.getPrincipalOnlyGrace()); Assert.assertEquals("Service Charge", labelConfigurationActionForm.getInterest()); Assert.assertEquals("External Id", labelConfigurationActionForm.getExternalId()); Assert.assertEquals("Bulk entry", labelConfigurationActionForm.getBulkEntry()); } }
Python
UTF-8
157
3.03125
3
[]
no_license
a = [10, 20] b = [a, 30] a.append(b) print(a) from copy import deepcopy c = deepcopy(a) print(c) print(c[2]) print(c[2][0]) print(c[2][0][2]) d = c[2][0][2]
Python
UTF-8
3,599
2.671875
3
[ "MIT" ]
permissive
#!/bin/env python import unittest from datetime import date, timedelta from dateutil.relativedelta import relativedelta import context from cash_flow.transaction import Transaction from cash_flow.transaction_store import TransactionStore from cash_flow.cash_flow import CashFlow from cash_flow.money import Money class TestConstructor(unittest.TestCase): def test_contructor_float_balance(self): sd = date.today() sb = 100.00 ts = TransactionStore() cf = CashFlow(sd, sb, ts) self.assertIsInstance(cf.start_date, date) self.assertEqual(cf.start_date, sd) self.assertIsInstance(cf.start_balance, Money) self.assertEqual(cf.start_balance, Money(sb)) self.assertIsInstance(cf.transaction_store, TransactionStore) self.assertEqual(len(cf.transaction_store.getTransactions()), 0) self.assertIsInstance(cf.current_date, date) self.assertEqual(cf.current_date, sd) self.assertIsInstance(cf.current_balance, Money) self.assertEqual(cf.current_balance, Money(sb)) def test_contructor_string_balance(self): sd = date.today() sb = '100.00' ts = TransactionStore() cf = CashFlow(sd, sb, ts) self.assertIsInstance(cf.start_date, date) self.assertEqual(cf.start_date, sd) self.assertIsInstance(cf.start_balance, Money) self.assertEqual(cf.start_balance, Money(sb)) self.assertIsInstance(cf.transaction_store, TransactionStore) self.assertEqual(len(cf.transaction_store.getTransactions()), 0) self.assertIsInstance(cf.current_date, date) self.assertEqual(cf.current_date, sd) self.assertIsInstance(cf.current_balance, Money) self.assertEqual(cf.current_balance, Money(sb)) class TestGenerator(unittest.TestCase): def setUp(self): sd = date.today() sb = 100.00 ts = TransactionStore() self.cf = CashFlow(sd, sb, ts) def assertTransactionsEqual(self, t1, t2): self.assertEqual(t1.start, t2.start) self.assertEqual(t1.original_start, t2.original_start) self.assertEqual(t1.end, t2.end) self.assertEqual(t1.description, t2.description) self.assertEqual(t1.amount, t2.amount) self.assertEqual(t1.frequency, t2.frequency) self.assertEqual(t1.skip.symmetric_difference(t2.skip), set()) self.assertEqual(t1.scheduled, t2.scheduled) self.assertEqual(t1.cleared, t2.cleared) def test_generate_from_nonrecurring_today(self): st = Transaction( start=date.today(), description="Once, today", amount=1.00, frequency=Transaction.ONCE) self.cf.transaction_store.addTransactions(st) day = self.cf.getTodaysTransactions() (d, bal, t_list) = next(day) self.assertEqual(d, self.cf.start_date) self.assertEqual(d, self.cf.current_date) self.assertEqual(bal, self.cf.current_balance) self.assertEqual(len(t_list), 1) t = t_list[0] self.assertTransactionsEqual(t, st) self.assertEqual(bal, self.cf.start_balance + st.amount) for i in range(1, 100): (d, bal, t_list) = next(day) self.assertEqual(d, self.cf.current_date) self.assertEqual(d, self.cf.start_date + timedelta(days=i)) self.assertEqual(bal, self.cf.current_balance) self.assertEqual(len(t_list), 0) self.assertEqual(bal, self.cf.start_balance + st.amount) if __name__ == '__main__': unittest.main()
C++
UTF-8
1,924
3.5
4
[]
no_license
/* You are given N jobs where every job is represented as: 1.Start Time 2.Finish Time 3.Profit Associated Find the maximum profit subset of jobs such that no two jobs in the subset overlap. Input The first line of input contains one integer denoting N. Next N lines contains three space separated integers denoting the start time, finish time and the profit associated with the ith job. Output Output one integer, the maximum profit that can be achieved. Constraints 1 <= N <= 10^6 1 <= ai, di, p <= 10^6 Sample Input 4 3 10 20 1 2 50 6 19 100 2 100 200 Sample Output 250 */ #include<bits/stdc++.h> using namespace std; struct Job{ int st; int end; int profit; }; bool compare(Job j1 , Job j2){ return j1.end<j2.end; } int index(Job arr[] , int i){ int start = 0; int end = i-1; int j = -1; while(start <= end){ int mid = (start+end)/2; if(arr[mid].end == arr[i].st){ j = mid; start = mid+1; } if(arr[mid].end > arr[i].st){ end = mid-1; } else{ j = mid; start = mid+1; } } return j; } int main(){ int n; cin >> n; Job arr[n]; for(int i = 0 ; i < n ; i++){ cin >> arr[i].st >> arr[i].end >> arr[i].profit; } // sort on basis of end time of the job sort(arr , arr + n , compare); // to find maximum profit either by excluding or including int dp[n]; dp[0] = arr[0].profit; for(int i = 1 ; i < n ; i++){ dp[i] = dp[i-1]; int j = index(arr , i); // cout<<j<<endl; if(j != -1){ dp[i] = max(dp[i] , dp[j] + arr[i].profit); } else{ dp[i] = max(dp[i] , arr[i].profit); } } cout<<dp[n-1]<<endl; }
PHP
UTF-8
5,364
2.75
3
[]
no_license
<?php class Api { const ERROR_NO_IMAGE_FOLDER = 'no_image_folder'; private $imageFolder; private $metaFile; private $rootFolder; public function __construct( string $imageFolder = DEFAULT_IMAGEFOLDER, string $metaFile = DEFAULT_METAFILE, string $rootFolder = ROOT_FOLDER ) { $this->imageFolder = $imageFolder; $this->metaFile = $metaFile; $this->rootFolder = $rootFolder; } /** * Upload operation handle * @param array $files * @return void */ public function upload(array $files = []) { try { $meta = textFileToArray($this->metaFile); $imagesdir = $this->imageFolder; if (!$imagesdir) { throw new Exception(self::ERROR_NO_IMAGE_FOLDER, 1); } $data = array(); foreach ($files as $file) { $filename = save_file($file, $file['name'], $this->imageFolder); $data[] = array( 'name' => $filename, 'type' => $file['type'], 'extension' => pathinfo($file['name'], PATHINFO_EXTENSION) ); } json_response('ok', 200, $data); return; } catch (Exception $e) { json_response($e->getMessage(), 400); return; } } /** * Save data to files * @param array|null $data * @return void */ public function save(array $data = null) { if (!$data || !count($data)) { json_response('Bad query', 400); return; } try { $meta = textFileToArray($this->metaFile); $result = array(); foreach ($data as $key => $value) { if ($key !== 'images' && !is_array($value)) { if (array_key_exists($key, $meta)) { $meta[$key] = trim($value); $result[$key] = $meta[$key]; } else { // adding new entries $meta[$key] = trim($value); $result[$key] = $meta[$key]; } } } array_to_file($meta); if (array_key_exists('images', $data)) { $result['images'] = $this->delete_all_files_except($data['images']); $result['images'] = $this->update_filenames($data['images']); } json_response('ok', 200, $result); return; } catch (Exception $e) { json_response($e->getMessage(), 500); } } /** * Delete all files except provided list * @param array|null $data exceptions * @return array deleted images filenames list * @throws Exception */ private function delete_all_files_except(array $data = null) { try { $meta = textFileToArray($this->metaFile); if (!$data || !count($data)) { return array(); } if (!$this->imageFolder) { throw new Exception(self::ERROR_NO_IMAGE_FOLDER, 1); return; } $images = getImagesInFolder($this->imageFolder); $result = array(); foreach ($images as $image) { if (!array_key_exists_in_array_of_arrays($image, 'filename', $data)) { @unlink($this->imageFolder . DS . $image); } else { $result[] = array('src' => url(str_replace(ROOT_FOLDER, '', $this->imageFolder) . DS . $image), 'filename' => $image); } } return $result; } catch (Exception $e) { throw new Exception($e->getMessage(), $e->getCode()); } } /** * Update filenames for given images list * @param array|null $images * @return array modified images filenames list */ private function update_filenames(array $images = null) { try { $meta = textFileToArray($this->metaFile); if (!$images || !count($images)) { return array(); } if (!$this->imageFolder) { throw new Exception(self::ERROR_NO_IMAGE_FOLDER, 1); return; } $existingImages = getImagesInFolder($this->imageFolder); $result = array(); foreach ($images as $image) { if (array_key_exists('filename', $image) && array_key_exists('newfilename', $image)) { if (in_array($image['filename'], $existingImages)) { $filename = update_filename($this->imageFolder . DS . $image['filename'], $image['newfilename']); $result[] = array( 'src' => url(str_replace(ROOT_FOLDER, '', $this->imageFolder) . DS . pathinfo($filename, PATHINFO_FILENAME) . '.' . pathinfo($filename, PATHINFO_EXTENSION)), 'filename' => pathinfo($filename, PATHINFO_FILENAME) . '.' . pathinfo($filename, PATHINFO_EXTENSION) ); } } } return $result; } catch (Exception $e) { throw new Exception($e->getMessage(), $e->getCode()); } } }
Java
UTF-8
1,572
1.9375
2
[]
no_license
package com.winterframework.firefrog.game.service.impl; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.winterframework.firefrog.common.util.GameContext; import com.winterframework.firefrog.game.dao.IGameTrendIssueDao; import com.winterframework.firefrog.game.dao.vo.GameSlip; import com.winterframework.firefrog.game.dao.vo.GameSlipDetail; import com.winterframework.firefrog.game.dao.vo.GameTrendIssue; import com.winterframework.firefrog.game.service.IGameTrendIssueService; /** * 走势图奖期服务实现类 * @ClassName * @Description * @author ibm * 2014年10月23日 */ @Service("gameTrendIssueServiceImpl") @Transactional public class GameTrendIssueServiceImpl implements IGameTrendIssueService { @Resource(name="gameTrendIssueDaoImpl") private IGameTrendIssueDao gameTrendIssueDao; @Override public int save(GameContext ctx, GameTrendIssue trendIssue) throws Exception { if(trendIssue==null) return 0; if(trendIssue.getId()!=null){ this.gameTrendIssueDao.update(trendIssue); }else{ this.gameTrendIssueDao.insert(trendIssue); } return 1; } @Override public int remove(GameContext ctx, Long id) throws Exception { return this.gameTrendIssueDao.delete(id); } @Override public GameTrendIssue getByLotteryIdAndIssueCode(GameContext ctx, Long lotteryId, Long issueCode) throws Exception { return this.gameTrendIssueDao.getByLotteryIdAndIssueCode(lotteryId, issueCode); } }
Java
UTF-8
6,035
2.578125
3
[ "MIT" ]
permissive
package im.djm.coin.tx; import java.util.ArrayList; import java.util.List; import com.google.common.primitives.Longs; import im.djm.blockchain.BlockUtil; import im.djm.coin.txhash.TxHash; import im.djm.coin.txhash.TxSignature; import im.djm.wallet.WalletAddress; /** * @author djm.im */ public class Tx { private TxHash txId; private List<Input> inputs; private List<Output> outputs; private boolean coinbase; private long timestamp; private TxSignature txSignature; public Tx() { this.inputs = new ArrayList<>(); this.outputs = new ArrayList<>(); this.coinbase = false; this.timestamp = timeNow(); // this.txSignature = null; -- txSignature is later setup } public Tx(WalletAddress minerAddress, long coinValue) { this.coinbase = true; // TOOD // Create NullArrayList this.inputs = new ArrayList<>(); this.outputs = new ArrayList<>(); this.timestamp = timeNow(); this.addOutput(minerAddress, coinValue); } private Tx(List<Input> inputs, List<Output> outputs, TxSignature txSignature) { this.coinbase = false; this.inputs = new ArrayList<>(inputs); this.txSignature = new TxSignature(txSignature.getBytes()); this.outputs = new ArrayList<>(outputs); this.timestamp = timeNow(); } public static class TxBuilder { private List<Input> inputs; private List<Output> outputs; private TxSignature txSignature; public Tx build() { this.validate(); return new Tx(this.inputs, this.outputs, this.txSignature); } private void validate() { if (this.inputs == null && this.outputs == null) { throw new TxException("Tx is not complited. Inputs and Outputs are null."); } if (this.inputs == null) { throw new TxException("Tx in not completed. Inputs are null."); } if (this.outputs == null) { throw new TxException("Tx in not completed. Outputs are null."); } if (this.txSignature == null) { throw new TxException("Tx in not completed. Signature is null."); } } public TxBuilder addInputs(List<Input> inputs) { if (inputs == null) { throw new TxException("Error: Inputs cannot be null."); } if (this.inputs != null) { throw new TxException("Error: Inputs are already added."); } this.inputs = new ArrayList<>(inputs); return this; } public TxBuilder addOutputs(List<Output> outputs) { if (outputs == null) { throw new TxException("Error: Outputs cannot be null."); } if (this.outputs != null) { throw new TxException("Error: Outputs are already added."); } this.outputs = new ArrayList<>(outputs); return this; } public TxBuilder addSignature(TxSignature signature) { if (signature == null) { throw new TxException("Error: Signature cannot be null."); } if (this.txSignature != null) { throw new TxException("Error: Signature is already added."); } this.txSignature = new TxSignature(signature.getBytes()); return this; } public List<Input> getInputsForSignature() { return this.inputs; } } private long timeNow() { return System.currentTimeMillis() / 1000; } public void addOutput(WalletAddress address, long coinAmount) { Output output = new Output(address, coinAmount); this.outputs.add(output); // byte[] txRawHash = // ByteArrayUtil.calculateRawHash(this.getRawDataForSignature()); // this.txId = new TxHash(txRawHash); this.txId = TxHash.hash(this.getRawDataForSignature()); } public boolean isCoinbase() { return this.coinbase; } public void addInput(TxHash prevTxHash, int outputIndexd) { Input input = new Input(prevTxHash, outputIndexd); this.inputs.add(input); } public byte[] getRawDataForSignature() { byte[] inputRawByte = getInputRawBytes(); byte[] outputRawByte = getOutputRawBytes(); byte[] timestampRawWyte = Longs.toByteArray(this.timestamp); return BlockUtil.concatenateArrays(inputRawByte, outputRawByte, timestampRawWyte); } private byte[] getInputRawBytes() { byte[] txInputRaw = new byte[0]; // TODO // replace with reduce method for (Input input : this.inputs) { txInputRaw = BlockUtil.concatenateArrays(txInputRaw, input.getRawData()); } return txInputRaw; } private byte[] getOutputRawBytes() { byte[] txOutputRaw = new byte[0]; for (Output output : this.outputs) { txOutputRaw = BlockUtil.concatenateArrays(txOutputRaw, output.getRawData()); } return txOutputRaw; } public void addSignature(byte[] signature) { this.txSignature = new TxSignature(signature); } public TxHash getTxId() { return this.txId; } public List<Input> getInputs() { return this.inputs; } // TODO ??? // delete this method public Input getInput(int index) { if (0 > index || index > this.inputs.size()) { throw new TxInputException("Index out of range: " + index); } // TODO // return a copy of element return this.inputs.get(index); } // TODO??? // remove the method public int getInputSize() { return this.inputs.size(); } // TODO ??? // remove the method public List<Output> getOutputs() { // TODO // return (immutable) array copy return this.outputs; } public Output getOutput(int index) { if (index < 0 || index > this.outputs.size()) { throw new TxOutputException("Index out of range: " + index); } // TODO // return a copy of element return this.outputs.get(index); } public int getOutputSize() { return this.outputs.size(); } public TxSignature getSignature() { return this.txSignature; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("\t{\n"); sb.append("\t\tTxId : ").append(this.txId).append("\n"); sb.append("\t\tTime : ").append(this.timestamp).append("\n"); sb.append("\t\tCoinbase: ").append(this.coinbase).append("\n"); sb.append("\t\tInputs : ").append(this.inputs).append("\n"); sb.append("\t\tOutputs : ").append(this.outputs).append("\n"); sb.append("\t\tSignarur: ").append(this.txSignature).append("\n"); sb.append("\t}\n"); return sb.toString(); } }
C++
UTF-8
2,561
3.21875
3
[]
no_license
#include "florp/graphics/Mesh.h" namespace florp { namespace graphics { Mesh::Mesh(void* vertices, size_t numVerts, const BufferLayout& layout, uint32_t* indices, size_t numIndices) { myIndexCount = numIndices; myVertexCount = numVerts; // Cache the layout myLayout = layout; // Create and bind our vertex array glCreateVertexArrays(1, &myRendererID); glBindVertexArray(myRendererID); // Create 2 buffers, 1 for vertices and the other for indices glCreateBuffers(2, myBuffers); // Bind and buffer our vertex data glBindBuffer(GL_ARRAY_BUFFER, myBuffers[0]); glBufferData(GL_ARRAY_BUFFER, numVerts * layout.GetStride(), vertices, GL_STATIC_DRAW); // Bind and buffer our index data glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, myBuffers[1]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, numIndices * sizeof(uint32_t), indices, GL_STATIC_DRAW); // Our elements will be sequential in the shaders (so attrib 0, 1, 2 ...) uint32_t index = 0; // Iterate over all elements for (const BufferElement& element : layout) { // Enable the attribute glEnableVertexAttribArray(index); // Set up the vertex attribute glVertexAttribPointer(index, element.GetComponentCount(), // Number of components in the attribute ToGLElementType(GetShaderDataTypeCode(element.Type)), // The data type of the attribute element.IsNormalized, // Whether or not the element is normalized layout.GetStride(), (const void*)element.Offset); index++; } // Unbind our VAO glBindVertexArray(0); } void* Mesh::ExtractVertices(size_t& outSize) const { outSize = myLayout.GetStride() * myVertexCount; void* result = malloc(outSize); glGetNamedBufferSubData(myBuffers[0], 0, outSize, result); return result; } uint32_t* Mesh::ExtractIndices(size_t& outSize) const { outSize = sizeof(uint32_t) * myIndexCount; void* data = malloc(outSize); glGetNamedBufferSubData(myBuffers[1], 0, outSize, data); return (uint32_t*)data; } Mesh::~Mesh() { LOG_INFO("Deleting mesh with ID: {}", myRendererID); // Clean up our buffers glDeleteBuffers(2, myBuffers); // Clean up our VAO glDeleteVertexArrays(1, &myRendererID); } void Mesh::Draw() { // Bind the mesh glBindVertexArray(myRendererID); if (myIndexCount > 0) // Draw all of our vertices as triangles, our indexes are unsigned ints (uint32_t) glDrawElements(GL_TRIANGLES, myIndexCount, GL_UNSIGNED_INT, nullptr); else glDrawArrays(GL_TRIANGLES, 0, myVertexCount); } } }
Markdown
UTF-8
2,341
3.640625
4
[]
no_license
# LeetCode # Stick to practice coding of algorithmic problems everyday and you would be a good algorithm engineer someday! ## 062_(不同路径)Unique Paths ## 1 问题描述、输入输出与样例 ### 1.1 问题描述 一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。<br> 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。<br> 问总共有多少条不同的路径?(图可以参见[62 不同路径](https://leetcode-cn.com/problems/unique-paths/))<br> __说明__:m 和 n 的值均不超过 100。 ### 1.2 输入与输出 输入: * int m: 网格的行数 * int n: 网格的列数 输出: * int: 从“Start”到“Finish”的路径总数 ### 1.3 样例 #### 1.3.1 样例1 输入: m = 3, n = 2<br> 输出: 3<br> 解释:<br> 从左上角开始,总共有 3 条路径可以到达右下角。 1. 向右 -> 向右 -> 向下 2. 向右 -> 向下 -> 向右 3. 向下 -> 向右 -> 向右 #### 1.3.2 样例2 输入: m = 7, n = 3<br> 输出: 28 ## 2 思路描述与代码 ### 2.1 思路描述(动态规划方法) dp[i][j] 代表从左上角(1, 1)到网格(i + 1, j + 1)的路径总数;<br> 到点(i, j)的路只有经过(i - 1, j)和(i, j - 1)的两条路,所以有 dp[i][j] = dp[i - 1][j] + dp[i][j - 1]。 ### 2.2 代码 ```cpp int uniquePaths(int m, int n) { vector<vector<int>> dp(m, vector<int>(n, 0)); //边界 for( int i = 0; i < m; i++ ) dp[i][0] = 1; for( int j = 0; j < n; j++ ) dp[0][j] = 1; //迭代 for( int i = 1; i < m; i++ ){ for(int j = 1; j < n; j++ ){ //上方往下的路和左方往右的路 dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; } } return dp[m - 1][n - 1]; } ``` ## 3 思考与拓展 ### 3.1 思考 #### 3.1.1 其他方法 无。 #### 3.1.2 复杂度分析 方法|空间复杂度|时间复杂度 --- | --- | --- 动态规划|O(mn)|O(mn) #### 3.1.3 难点分析 1. 找到DP递推表达式,这题递推表达式较为简单; 2. 边界初始化。 ### 3.2 拓展 如果给你的网格是有障碍的呢?快尝试下[不同路径 II](https://leetcode-cn.com/problems/unique-paths-ii/)。 ## 我一定要在这一年每天至少刷一道题,坚持不懈,持之以恒,我一定行!
C++
UTF-8
848
3.96875
4
[]
no_license
// function to reverse a doubly linked list // in groups of given size Node* revListInGroupOfGivenSize(Node* head, int k) { Node *current = head; Node* next = NULL; Node* newHead = NULL; int count = 0; // reversing the current group of k // or less than k nodes by adding // them at the beginning of list // 'newHead' while (current != NULL && count < k) { next = current->next; push(&newHead, current); current = next; count++; } // if next group exists then making the desired // adjustments in the link if (next != NULL) { head->next = revListInGroupOfGivenSize(next, k); head->next->prev = head; } // pointer to the new head of the // reversed group return newHead; }
SQL
UTF-8
1,006
3.9375
4
[]
no_license
WITH X AS (SELECT f.con_id, MAX(t.termination_letter_created ) AS cfw_create_termination_letter, count( DISTINCT f.cfw_nu_num_installment ) AS total_cfw_dt_installment, MIN(f.cfw_nu_num_installment ) AS cfw_nu_num_installment FROM td_contract c INNER JOIN td_cashflow f ON c.con_id = f.con_id INNER JOIN td_collection col ON c.con_id = col.con_id LEFT JOIN td_termination_letter_tracking t ON f.con_id = t.con_id AND t.cfw_nu_num_installment = f.cfw_nu_num_installment WHERE c.wkf_sta_id NOT IN (200, 213, 203, 500, 208, 206, 207) AND f.cfw_typ_id IN (5,2) AND f.cfw_bl_cancel IS FALSE AND f.cfw_bl_paid IS FALSE AND to_timestamp( 1526868592236 / 1000) > f.cfw_dt_installment GROUP BY f.con_id ORDER BY f.con_id ) SELECT con_id, cfw_create_termination_letter FROM X WHERE cfw_create_termination_letter IS NULL AND total_cfw_dt_installment > 2
Markdown
UTF-8
607
3.015625
3
[]
no_license
# App purpose Payments signature app User inputs payments, these are signed with a random 10 x 10 alphabetic matrix and local time, stored, and ready to be sent to an API. # Modules App is very small - one module can fit all the functionality (App Module) # Pages Generator page Payments page # Services Signature generator service: Generates a new 2D matrix and 2 digit code (signature) every 2 sec. Matrix data is a 1D array of chars Signature is the matrix + code Payments service: Remembers payments made, along with each's signature. Payment is the name, amount, and signature
Java
UTF-8
2,205
4.09375
4
[]
no_license
package array; /** * 给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。 示例 1: 输入: [1,2,3,4,5,6,7] 和 k = 3 输出: [5,6,7,1,2,3,4] 解释: 向右旋转 1 步: [7,1,2,3,4,5,6] 向右旋转 2 步: [6,7,1,2,3,4,5] 向右旋转 3 步: [5,6,7,1,2,3,4] 示例 2: 输入: [-1,-100,3,99] 和 k = 2 输出: [3,99,-1,-100] 解释: 向右旋转 1 步: [99,-1,-100,3] 向右旋转 2 步: [3,99,-1,-100] * */ public class RotatedArray { // public void rotate(int[] nums, int k) { // //k 必须小于 nums.length,否则会越界。如果相等则直接退出 // k = k % nums.length; // if ( k == nums.length ) // { // return; // } // // int[] temps = new int[k]; // int len = temps.length-1; // //将需要旋转的元素存放在临时数组中 // for ( int i=0; i<k; i++ ) // { // temps[i] = nums[nums.length-k+i]; // } // // //开始向右移动数组 // for ( int i=nums.length-1; i>=0; i--) // { // //将 nums[] 索引小于(nums.length-k-1)的元素,移至最右边 // if ( i>=k ) // { // nums[i] = nums[i-k]; // } // // 将 temp[] 放到nums[]剩下的元素中 // else // { // nums[i] = temps[len--]; // } // } // } //LeetCode代码 public void rotate(int[] nums, int k) { int n = nums.length; //求余,防止k大于n k %= n; reverse(nums, 0, n-1); reverse(nums, 0, k-1); reverse(nums, k, n-1); } //将nums[] 中的 strart~end的元素的值翻转 public void reverse(int[] nums, int start, int end){ while(start < end){ int temp = nums[start]; nums[start++] = nums[end]; nums[end--] = temp; } } public static void main(String[] args) { int[] nums = {1,2,3,4,5,6,7}; RotatedArray ra = new RotatedArray(); ra.rotate(nums, 29); for ( int i=0; i<nums.length; i++ ) { System.out.print(nums[i]+" "); } } }
JavaScript
UTF-8
1,104
2.734375
3
[]
no_license
import axios from 'axios' const fetchPopularShows = async (page) => { try { // const {data: {tv_shows}} = await axios.get('https://www.episodate.com/api/most-popular?page=1') let url = `https://www.episodate.com/api/most-popular?page=${page}` const {data: {tv_shows}} = await axios.get(url) const shows = tv_shows.map((tv)=>({ imagePath : tv.image_thumbnail_path, showName: tv.name, network: tv.network, id: tv.id })) return(shows) }catch (err) { console.log(err) } } const returnCount = async()=>{ try{ let url = `https://www.episodate.com/api/most-popular?page=1` const {data: {pages, total}} = await axios.get(url) return([pages, total]) }catch (err){ console.log(err) } } const searchShow = async function(name){ console.log('yay') let url = `https://www.episodate.com/api/search?q=${name}` const {data: {tv_shows}} = await axios.get(url) return tv_shows } export {fetchPopularShows, returnCount, searchShow};
PHP
UTF-8
1,337
2.53125
3
[]
no_license
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Data modification</title> <link rel="stylesheet" type="text/css" href="css_modify_page_two.css"> </head> <body> <h1>Data modification</h1> <?php $conexion=mysqli_connect("localhost", "c0230365_6to2020", "pozo62moRA", "c0230365_6to2020") or die("Problems with the conection"); $registros=mysqli_query($conexion,"select * from Cordisco_Table where email='$_REQUEST[email]'") or die("Problems with the select:".mysqli_error($conexion)); if($reg=mysqli_fetch_array($registros)) { ?> <div> <form action = "modify.php" method = "post"> Enter new E-Mail: <br> <input class = "input" type = "text" name ="newemail" value = "<?php echo $reg['email'] ?>"><br> <input type = "hidden" name = "oldemail" value = "<?php echo $reg['email'] ?>"><br><br> <input class = "button" type = "submit" value ="Modify"> </form> </div> <?php } else echo "There is not user with that E-mail."; ?> <form action="home_page.php"> <input class="form" type="submit" value="Home"> </form><br> <form action="modify_page.php"> <input class="form" type="submit" value="Back"> </form><br> <h4>Copyright © 2020 Cordisco's Company. All rights reserved. Contact: tom.cordisco2002@gmail.com</h4> </body> </html>
Java
UTF-8
1,334
2.125
2
[]
no_license
package com.rz.httpapi.bean; import java.io.Serializable; /** * Created by Administrator on 2017/9/18 0018. */ public class DataStatisticsBean implements Serializable { private String custId; private int articleNum; //文章数量 private int coterieNum; //私圈数量 private int offerNum; //悬赏数量 private String score; //积分 private String custLevel; //等级 public String getCustId() { return custId; } public void setCustId(String custId) { this.custId = custId; } public int getArticleNum() { return articleNum; } public void setArticleNum(int articleNum) { this.articleNum = articleNum; } public int getCoterieNum() { return coterieNum; } public void setCoterieNum(int coterieNum) { this.coterieNum = coterieNum; } public int getOfferNum() { return offerNum; } public void setOfferNum(int offerNum) { this.offerNum = offerNum; } public String getScore() { return score; } public void setScore(String score) { this.score = score; } public String getCustLevel() { return custLevel; } public void setCustLevel(String custLevel) { this.custLevel = custLevel; } }
PHP
UTF-8
234
2.6875
3
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
<?php declare(strict_types=1); namespace Edde\Api\Protocol\Event; interface IListener { /** * return/generate list of listeners for EventBus * * @return \Traversable|array */ public function getListenerList(); }
Java
UTF-8
234
1.914063
2
[]
no_license
//package frc.team852.lib.callbacks; // //import frc.team852.DeepSpaceRobot.GaffeTape; // //public abstract class GaffeListener extends GenericListener<GaffeTape> { // public GaffeListener() { // super(GaffeTape.class); // } //}
C++
UTF-8
6,959
3.265625
3
[]
no_license
#include "position.h" #include <map> #include <iostream> using namespace std; const std::map<Direction, Direction> OPPOSITE_DIRECTIONS = { { Direction::N, Direction::S }, { Direction::S, Direction::N }, { Direction::W, Direction::E }, { Direction::E, Direction::W }, { Direction::NW, Direction::SE }, { Direction::SE, Direction::NW }, { Direction::NE, Direction::SW }, { Direction::SW, Direction::NE } }; const std::map<Direction, std::vector<Direction>> FORWARD_DIAGONALS = { { Direction::N, { Direction::NW, Direction::NE } }, { Direction::S, { Direction::SW, Direction::SE } }, { Direction::W, { Direction::NW, Direction::SW } }, { Direction::E, { Direction::NE, Direction::SE } } }; Position::Position( int row, int col ) : row{ row }, col{ col } {} int Position::getRow() const { return row; } int Position::getCol() const { return col; } int Position::getRowDiff( const Position &other ) const { return row - other.row; } int Position::getColDiff( const Position &other ) const { return col - other.col; } int Position::getABSRowDiff( const Position &other ) const { return std::abs( getRowDiff( other ) ); } int Position::getABSColDiff( const Position &other ) const { return std::abs( getColDiff( other ) ); } Direction Position::getDirection( const Position &other ) const { int r = row; int c = col; int otherR = other.getRow(); int otherC = other.getCol(); if (otherR < r) { if (otherC < c) { return Direction::NW; } else if (otherC == c) { return Direction::N; } else { // otherC > c return Direction::NE; } } else if (otherR == r) { if (otherC < c) { return Direction::W; } else { // (otherC >= c) return Direction::E; } } else { // otherR > r if (otherC < c) { return Direction::SW; } else if (otherC == c) { return Direction::S; } else { // otherC > c return Direction::SE; } } } int getDeltaR( Direction direction, int n ) { if ( direction == Direction::NW || direction == Direction::N || direction == Direction::NE ) { return -1 * n; } else if ( direction == Direction::SW || direction == Direction::S || direction == Direction::SE ) { return n; } else { return 0; } } int getDeltaC( Direction direction, int n ) { if ( direction == Direction::NW || direction == Direction::W || direction == Direction::SW ) { return -1 * n; } else if ( direction == Direction::NE || direction == Direction::E || direction == Direction::SE ) { return n; } else { return 0; } } Position Position::getNSquaresForward( Direction direction, int n ) const { return { row + getDeltaR( direction, n ), col + getDeltaC( direction, n ) }; /* if ( direction == Direction::NW ) { return { row - n, col - n }; } else if ( direction == Direction::N ) { return { row - n, col }; } else if ( direction == Direction::NE ) { return { row - n, col + n }; } else if ( direction == Direction::W ) { return { row, col - n }; } else if ( direction == Direction::E ) { return { row, col + n }; } else if ( direction == Direction::SW ) { return { row + n, col - n }; } else if ( direction == Direction::S ) { return { row + n, col }; } else { // direction == Direction::SE return { row + n, col + n }; } */ } Position Position::getNSquaresBackward( Direction direction, int n ) const { return getNSquaresForward( OPPOSITE_DIRECTIONS.at( direction ), n ); } std::vector<Position> Position::getLine( Direction direction, int endRow, int endCol ) const { std::vector<Position> line; int r = row; int c = col; int deltaR = getDeltaR( direction, 1 ); int deltaC = getDeltaC( direction, 1 ); /* cout << "r" << r << " c " << c << endl; cout << "dr" << deltaR << " dc " << deltaC << endl; cout << "End row " << endRow << " end col " << endCol; cout << "Position" << Position{ r + deltaR, c + deltaC } << endl; */ for ( Position position = { r + deltaR, c + deltaC }; position.getRow() < endRow && position.getCol() < endCol; position = { position.getRow() + deltaR, position.getCol() + deltaC } ) { line.emplace_back( position ); } return line; } std::vector<Position> Position::getInBetween( const Position &other ) const { std::vector<Position> line; int startRow = row; int startCol = col; int endRow = other.getRow(); int endCol = other.getCol(); Direction direction = getDirection( other ); int deltaR = getDeltaR( direction, 1 ); int deltaC = getDeltaC( direction, 1 ); /* cout << "endRow" << endRow << "endCol" << endCol << endl; cout << "path start" << Position{ startRow + deltaR, startCol + deltaC } << endl;*/ for ( Position position = { startRow + deltaR, startCol + deltaC }; position.getRow() != endRow || position.getCol() != endCol; position = { position.getRow() + deltaR, position.getCol() + deltaC } ) { // cout << "Position" << position << endl; line.emplace_back( position ); } return line; // return getLine( getDirection( other ), // other.getRow(), other.getCol() ); } std::vector<Position> Position::getLineSegment ( const Position &other ) const { std::vector<Position> line = getInBetween( other ); line.insert( line.begin(), *this ); line.emplace_back( other ); return line; } bool Position::isNSquaresForwardTo( const Position &other, Direction direction, int n ) const { return (*this) == Position{ other.getRow() + getDeltaR( direction, n ), other.getCol() + getDeltaC( direction, n ) }; } bool Position::isNSquaresDiagForwardTo( const Position &other, Direction direction, int n ) const { std::vector<Direction> forwardDiagonals = FORWARD_DIAGONALS.at( direction ); for ( const auto &forwardDiagonal : forwardDiagonals ) { if ( isNSquaresForwardTo( other, forwardDiagonal, n ) ) { return true; } } return false; } bool Position::operator==( const Position &other ) const { return row == other.row && col == other.col; } bool Position::operator!=( const Position &other ) const { return !( *this == other ); } std::ostream &operator<<(std::ostream &out, const Position &position) { return out << "( " << position.getRow() << ", " << position.getCol() << " )"; }
C
UTF-8
729
2.75
3
[]
no_license
#ifndef SOFTWAREPROJECT2_OTHELLOLIB_H #define SOFTWAREPROJECT2_OTHELLOLIB_H #include <stdbool.h> #define MAX_STR_LEN 20 typedef struct { char colour; //'B' and 'W' for placing their tokens on board char team[6]; //"Black" for player1 and "White" for player2 int score; char name[MAX_STR_LEN+1]; }player; typedef struct { char board[8][8]; //holds the state of every tile on board player* currentPlayer; //points to current player player *nextPlayer; //points to next player }game; void printBoard(game*); bool isValid(game*, int, int, char[3]); bool validMoves(game*); void move(game*, int, int); void playerSwap(game*); void endReport(player*, player*); #endif //SOFTWAREPROJECT2_OTHELLOLIB_H
C++
UTF-8
564
2.71875
3
[]
no_license
/* * Player.cpp * * Created on: Aug 29, 2016 * Author: lenz */ #include "Player.h" #include "../Session.h" using namespace std; Player::Player(int i,Session* mySess) { this->position = i; this->mySession = mySess; } Player::Player() { } Player::~Player() { // TODO Auto-generated destructor stub } void Player::whereAmI(){ vector<Player*> players; players = mySession->getPlayers(); int pos = 0; for(vector<Player*>::iterator it = players.begin(); it != players.end(); it++){ if(this == *it){ break; } pos++; } position = pos; }
C#
UTF-8
1,146
2.625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EntitiesLib { public class Contact { private int id; private int id_personne; private Personne personne; public Contact() { } public Contact(int id_personne) { this.id_personne = id_personne; } public Contact(int id, int id_personne) { this.id = id; this.id_personne = id_personne; } public Contact(int id, int id_personne, Personne personne) { this.id = id; this.id_personne = id_personne; this.personne = personne; } public int Id { get { return id; } set { id = value; } } public int Id_personne { get { return id_personne; } set { id_personne = value; } } } }
JavaScript
UTF-8
4,010
3.078125
3
[ "MIT" ]
permissive
function Index() { 'use strict'; this.invertedIndex = {}; this.createIndex = function(filepath) { /* createIndex method reads the contents of a file whose path is passed as an argument in the method. The method returns a promise. */ return fetch(filepath).then(function(response) { return response.text(); }).then(function(data) { var jsonObject = JSON.parse(data); return jsonObject; }); }; this.formatContent = function(content) { /* This method removes stop words and punctuation marks and returns an array of words. Stop words from http://www.ranks.nl/stopwords */ var stopWords = ['a', 'about', 'above', 'after', 'again', 'against', 'all', 'am', 'an', 'and', 'any', 'are', 'aren\'t', 'as', 'at', 'be', 'because', 'been', 'before', 'being', 'below', 'between', 'both', 'but', 'by', 'can\'t', 'cannot', 'could', 'couldn\'t', 'did', 'didn\'t', 'do', 'does', 'doesn\'t', 'doing', 'don\'t', 'down', 'during', 'each', 'few', 'for', 'from', 'further', 'had', 'hadn\'t', 'has', 'hasn\'t', 'have', 'haven\'t', 'having', 'he', 'he\'d', 'he\'ll', 'he\'s', 'her', 'here', 'here\'s', 'hers', 'herself', 'him', 'himself', 'his', 'how', 'how\'s', 'i', 'i\'d', 'i\'ll', 'i\'m', 'i\'ve', 'if', 'in', 'into', 'is', 'isn\'t', 'it', 'it\'s', 'its', 'itself', 'let\'s', 'me', 'more', 'most', 'mustn\'t', 'my', 'myself', 'no', 'nor', 'not', 'of', 'off', 'on', 'once', 'only', 'or', 'other', 'ought', 'our', 'ours', 'ourselves', 'out', 'over', 'own', 'same', 'shan\'t', 'she', 'she\'d', 'she\'ll', 'she\'s', 'should', 'shouldn\'t', 'so', 'some', 'such', 'than', 'that', 'that\'s', 'the', 'their', 'theirs', 'them', 'themselves', 'then', 'there', 'there\'s', 'these', 'they', 'they\'d', 'they\'ll', 'they\'re', 'they\'ve', 'this', 'those', 'through', 'to', 'too', 'under', 'until', 'up', 'very', 'was', 'wasn\'t', 'we', 'we\'d', 'we\'ll', 'we\'re', 'we\'ve', 'were', 'weren\'t', 'what', 'what\'s', 'when', 'when\'s', 'where', 'where\'s', 'which', 'while', 'who', 'who\'s', 'whom', 'why', 'why\'s', 'with', 'won\'t', 'would', 'wouldn\'t', 'you', 'you\'d', 'you\'ll', 'you\'re', 'you\'ve', 'your', 'yours', 'yourself', 'yourselves' ]; var stopString = '\\b' + stopWords.toString() .replace(/\,/gi, '\\b|\\b') + '\\b'; var re = new RegExp(stopString, 'gi'); /* Replaces punctuaion marks and the regExp containing stopwords with a single space and splits the string by spaces returning an array of words. */ var doc = content.replace(/\W+/gi, ' ').replace(re, ' ') .trim().toLowerCase().split(' '); return doc; }; this.getIndex = function() { function getValues(obj) { var str = ''; Object.keys(obj).map(function(key) { str += ' ' + obj[key]; }); return str; } var indexObj = this.invertedIndex; for (var index = 0; index < this.arr.length; index++) { var fileContents = getValues(this.arr[index]); var doc = this.formatContent(fileContents); for (var i = 0; i < doc.length; i++) { var exist = indexObj.hasOwnProperty(doc[i]); if (!exist) { indexObj[doc[i]] = [index]; } if (exist && !indexObj[doc[i]].includes(index)) { indexObj[doc[i]].push(index); } } } return indexObj; }; this.searchIndex = function(searchItems) { /* When a search item is passed into the method it returns an array of that identifies the document in which the words are contained or lack thereof. */ var results = []; var terms = []; if (!Array.isArray(searchItems) && typeof searchItems !== 'string') { return 'Invalid Input'; } if (!Array.isArray(searchItems)) { for (var key in arguments) { terms.push(arguments[key]); } } else { terms = searchItems; } for (var i = 0; i < terms.length; i++) { if (!this.invertedIndex.hasOwnProperty(terms[i])) { results.push([-1]); } else { results.push(this.invertedIndex[terms[i]]); } } return results; }; }
Python
UTF-8
684
4.9375
5
[]
no_license
# Write a function which takes a list as an input from the user [using the input() # command] and returns the highest and the second highest elements of a list. # Ex: # Input 1: # 1 2 3 4 # Output 1: # 3 4 # Input 2: # 1 2 3 8 7 # Output 2: # 7 8 def list_pro(): a = input("Enter the list as space separated numbers: ") lis = a.split(" ") print("List that we have", lis) b = [] for i in lis: b.append(int(i)) print("Converted list we have", b) first_largest_int = max(b) b.remove(first_largest_int) second_largest_int = max(b) print("First Highest : ", first_largest_int) print("Second Highest : ", second_largest_int) list_pro()
Markdown
UTF-8
681
2.578125
3
[]
no_license
# Installation of Backend Instructions ## Notes Please note that this is subject to change, as we may need more stuff to be installed on the backend later ## Instructions 1. Navigate to the Backend folder 2. run npm install babel-cli@6.26.0 3. run npm install babel-preset-env@1.7.0 4. run npm install babel-watch@2.0.7 5. run npm install express@4.16.3 6. run npm install cors@2.8.4 - This is where the tutorial installed mongoose, which I did not, as I did not see the reason. As we are not using a database at the current time. - As a reference, the command for that would be npm install mongoose 7. run npm run dev This should start the backend server on localhost:4000
Java
UTF-8
2,357
2.265625
2
[]
no_license
package com.couchbase.day.web; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.couchbase.day.model.Error; import com.couchbase.day.model.IValue; import com.couchbase.day.service.AirportService; @RestController @RequestMapping("/api/airports") public class AirportControllerImpl { private static final Logger LOGGER = LoggerFactory.getLogger(AirportControllerImpl.class); private final AirportService airportService; @Autowired public AirportControllerImpl(AirportService airportService) { this.airportService = airportService; } @RequestMapping(value="/airport/{id}/", method=RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<? extends IValue> findAirportById(@PathVariable("id") String id) { try { return ResponseEntity.ok(airportService.findAirportById(id)); } catch (Exception e) { return ResponseEntity.badRequest().body(new Error(e.getMessage())); } } @RequestMapping(value="/airport/name/{name}/", method=RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<? extends IValue> findAirportByState(@PathVariable("name") String name) { try { return ResponseEntity.ok(airportService.findAirportByName(name)); } catch (Exception e) { return ResponseEntity.badRequest().body(new Error(e.getMessage())); } } @RequestMapping(value="/flypath/{from}/{to}/", method=RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<? extends IValue> findAirportFlighPaths(@PathVariable("from") String from, @PathVariable("to") String to) { try { return ResponseEntity.ok(airportService.findFlighPaths(from, to)); } catch (Exception e) { return ResponseEntity.badRequest().body(new Error(e.getMessage())); } } }
Python
UTF-8
167
3.53125
4
[]
no_license
srtroka = input('Введите предложение\n') itog = '' for s in srtroka: if s == 'о': itog += "а" else: itog += s print(itog)
C++
UTF-8
311
3.03125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int powerK(int n, int k){ if(k == 1) return n; int num; if(k%2 ==0){ num = powerK(n, k/2); } else{ num = powerK(n. k/1) } return num*num; } int main(){ int n; cin >> n; int k; cin>>k; cout << powerK(n, k); }
Java
UTF-8
831
2.09375
2
[]
no_license
package com.android.project.view.wall.di; import com.android.project.api.RequestService; import com.android.project.database.DatabaseManager; import com.android.project.view.wall.WallPresenter; import com.android.project.view.wall.WallPresenterImpl; import dagger.Module; import dagger.Provides; /** * Created by Lobster on 05.11.16. */ @Module public class WallModule { private WallPresenter.View mView; public WallModule(WallPresenter.View view) { mView = view; } @Provides public WallPresenter.View provideView() { return mView; } @Provides public WallPresenter.ActionListener providePresenter(RequestService requestService, DatabaseManager databaseManager, WallPresenter.View view) { return new WallPresenterImpl(requestService, databaseManager, view); } }
JavaScript
UTF-8
1,036
2.8125
3
[]
no_license
import React from "react"; import "./App.css"; import { CardList } from "./components/card-list/card-list.componenets"; import { SearchBox } from "./components/search-box/search-box.component"; class App extends React.Component { constructor() { super(); this.state = { locals: [], searchField: " ", }; } componentDidMount() { fetch("https://jsonplaceholder.typicode.com/users") .then((response) => response.json()) .then((users) => this.setState({ locals: users })); } render() { const { locals, searchField } = this.state; const filteredUsers = locals.filter((localUser) => localUser.name.toLowerCase().includes(searchField.toLocaleLowerCase()) ); return ( <div className="App"> <h1>Search Users</h1> <SearchBox placeholder = 'Search Users' handleChange = {e => this.setState({searchField : e.target.value})}/> <CardList users={filteredUsers}></CardList> </div> ); } } export default App;
TypeScript
UTF-8
1,120
3.234375
3
[ "MIT" ]
permissive
import { Atributo } from "./Atributo"; export enum Etiqueta { UNICA, DOBLE, HEADER } export class Objeto { identificador: string; texto: string; listaAtributos: Array<Atributo>; listaObjetos: Array<Objeto>; linea: number; columna: number; etiqueta: Etiqueta; textWithoutSpecial: string; constructor(id: string, texto: string, linea: number, columna: number, listaAtributos: Array<Atributo>, listaO: Array<Objeto>, etiqueta:Etiqueta) { this.identificador = id; this.texto = texto; this.linea = linea; this.columna = columna; this.listaAtributos = listaAtributos; this.listaObjetos = listaO this.etiqueta = etiqueta; this.textWithoutSpecial = this.setCaracteresEspeciales(texto); } setCaracteresEspeciales(valor: string) { let value = valor.split("&lt;").join("<"); value = value.split("&gt;").join(">"); value = value.split("&amp;").join("&"); value = value.split("&apos;").join("'"); value = value.split("&quot;").join('"'); return value; } }
Python
UTF-8
1,172
3.125
3
[]
no_license
import pygame class Settings(): """A class to store all settings for alien invasion.""" def __init__(self): """Initialize the game's settings""" self.screen_width = 1200 self.screen_height = 800 self.image = pygame.image.load('images/night.jpg') self.alien_image = pygame.image.load('images/alien.bmp') self.board_color = (38, 38, 38) self.ship_limit = 1 self.bullets_allowed = 5 self.alien_number = 5 self.initialize_dynamic_settings() def initialize_dynamic_settings(self): """initialize settings that change throughout the game""" self.ship_speed_factor = 20 self.alien_speed_factor = 12 self.bullet_speed_factor = 16 #scoring self.alien_points = 10 self.bonus_points = 30 def increase_level(self, stats): """increase level settings.""" stats.level += 1 if stats.level == 2: self.image = pygame.image.load('images/space.jpg') self.alien_image = pygame.image.load('images/ufo.png') self.alien_number = 7 elif stats.level == 3: pass
Java
UTF-8
271
2.21875
2
[]
no_license
package com.src; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; class AccountTest2 { @Test void testwithdraw() { Account a=new Account("hello",456789123,5000); boolean b=a.withdraw(2000, 100); assertEquals(b,true); } }
C#
UTF-8
3,352
2.625
3
[]
no_license
using HRMserver.Model; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Configuration; using System.Data; using System.ComponentModel; using System.Drawing; namespace HRMserver.DAL { public class DictionaryServer { public static List<DictionaryField> GetListOfDictionary() // 获取字典中的字段 { string sql = "select * from Dictionary"; List<DictionaryField> Res = new List<DictionaryField>(); using (SqlDataReader sdr = SqlHelper.ExecuteReader(sql)) { while (sdr.Read()) { DictionaryField df = new DictionaryField(); df.Id = (Guid)sdr["Id"]; df.Name = sdr["Name"].ToString(); df.Category = sdr["Category"].ToString(); Res.Add(df); } } return Res; } public static int AddDictionary(string Category,string Name) // 增加字典字段 { string sql = "insert into Dictionary values(@Id,@Name,@Category)"; SqlParameter[] p = { new SqlParameter("@Id",Guid.NewGuid()), new SqlParameter("@Name",Name), new SqlParameter("@Category",Category) }; return SqlHelper.ExecuteNonQuery(sql, p); } public static int EraseDictionary(string Category, string Name) // 删除字典字段 { string sql = "delete from Dictionary where Name=@Name and Category=@Category"; SqlParameter[] p = { new SqlParameter("@Name",Name.Trim()), new SqlParameter("@Category",Category.Trim()) }; return SqlHelper.ExecuteNonQuery(sql, p); } public static int UpdateDictionary(string Category, string Name,string ToName) // 修改字典字段 { string sql = "update Dictionary set Name=@ToName where Name=@Name and Category=@Category"; SqlParameter[] p = { new SqlParameter("@Name",Name), new SqlParameter("@Category",Category), new SqlParameter("@ToName",ToName) }; return SqlHelper.ExecuteNonQuery(sql, p); } public static List<DictionaryField> SelectDictionary(string Category) // 某分类的字段列表 { string sql = "select * From Dictionary where Category=@Category)"; SqlParameter[] p = { new SqlParameter("@Category",Category) }; List<DictionaryField> list = new List<DictionaryField>(); using (SqlDataReader sdr = SqlHelper.ExecuteReader(sql, p)) { while (sdr.Read()) { DictionaryField df = new DictionaryField(); df.Category = Category; df.Id = (Guid)sdr["Id"]; df.Name = sdr["Id"].ToString(); list.Add(df); } } return list; } } }