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
C++
UTF-8
3,360
3.09375
3
[]
no_license
/************************************************************************* > File Name: thread_pool.h > Author: > Mail: > Created Time: 2017年05月13日 星期六 12时22分24秒 ************************************************************************/ #ifndef _THREAD_POOL_H #define _THREAD_POOL_H #include <stdio.h> #include <assert.h> #include <stdlib.h> #include <deque> #include <pthread.h> #include <functional>// for std::function, std::bind class ThreadPool{ public: typedef std::function<void()> Task; ThreadPool(int threadNum = 10); ~ThreadPool(); size_t addTask(const Task& task); void stop(); int size(); Task take(); private: int createThreads(); static void* threadFunc(void * threadData);//这里threadFun是静态的 ThreadPool& operator=(const ThreadPool&); ThreadPool(const ThreadPool&); private: volatile bool isRunning_; int threadsNum_; pthread_t* threads_; std::deque<Task> taskQueue_; pthread_mutex_t mutex_; pthread_cond_t condition_; }; //构造函数,创建一定数量的线程,要调用create函数 ThreadPool::ThreadPool(int threadNum){ isRunning_ = true; threadsNum_ = threadNum; createThreads(); } ThreadPool::~ThreadPool(){ stop(); } //创建线程 int ThreadPool::createThreads(){ pthread_mutex_init(&mutex_, NULL); pthread_cond_init(&condition_, NULL); threads_ = (pthread_t*) malloc(sizeof(pthread_t) * threadsNum_); for (int i = 0; i < threadsNum_; i++){ pthread_create(&threads_[i], NULL, threadFunc, this); } return 0; } //往线程队列里添加线程 size_t ThreadPool::addTask(const Task& task){ pthread_mutex_lock(&mutex_); taskQueue_.push_back(task); int size = taskQueue_.size(); pthread_mutex_unlock(&mutex_); pthread_cond_signal(&condition_); return size; } //停止所有的线程 //释放资源 void ThreadPool::stop(){ if (!isRunning_){ return; } isRunning_ = false; pthread_cond_broadcast(&condition_); for (int i = 0; i < threadsNum_; i++){ pthread_join(threads_[i], NULL);//等待其他线程退出 } free(threads_); threads_ = NULL; pthread_mutex_destroy(&mutex_); pthread_cond_destroy(&condition_); } //任务队列的大小 int ThreadPool::size(){ pthread_mutex_lock(&mutex_); int size = taskQueue_.size(); pthread_mutex_unlock(&mutex_); return size; } //从任务队列中拿出一个任务 ThreadPool::Task ThreadPool::take(){ Task task = NULL; pthread_mutex_lock(&mutex_); while (taskQueue_.empty() && isRunning_){ pthread_cond_wait(&condition_, &mutex_); } if (!isRunning_){ pthread_mutex_unlock(&mutex_); return task; } assert(!taskQueue_.empty()); task = taskQueue_.front(); taskQueue_.pop_front(); pthread_mutex_unlock(&mutex_); return task; } //创建线程时的驱动函数,如果有task就运行它 void* ThreadPool::threadFunc(void* arg){ pthread_t tid = pthread_self(); ThreadPool* pool = static_cast<ThreadPool*>(arg); while (pool->isRunning_){ ThreadPool::Task task = pool->take(); if (!task){ printf("thread %lu will exit\n", tid); break; } assert(task); task(); } return 0; } #endif
C#
UTF-8
1,211
2.859375
3
[]
no_license
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _04数据库创建和填充种子数据及LINQ操作 { //public class Context : DbContext //{ // public Context() : base("name=FirstCodeFirstApp") // { // //无论什么时候创建上下文类,Database.SetInitializer方法都会调用,并且将数据库初始化策略设置为DropCreateDataIfModelChanges // Database.SetInitializer<Context>(new DropCreateDatabaseIfModelChanges<Context>()); // //如果处于生产环境,那么我们肯定不想丢失已存在的数据。这时我们需要关闭该初始化器,只需要将null传给Database.SetInitializer方法 // //Database.SetInitializer<Context>(null); // } //} #region SeedingDbContext public class SeedingDataContext : DbContext { public SeedingDataContext() : base("name=FirstCodeFirstApp") { Database.SetInitializer<SeedingDataContext>(new SeedingDataInitializer()); } public virtual DbSet<Employer> Employers { get; set; } } #endregion }
Java
UTF-8
1,358
1.796875
2
[]
no_license
/******************************************************************************* * Copyright (c) 2010 - 2013 webXcerpt Software GmbH. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * webXcerpt Software GmbH - initial creator * www.webxcerpt.com ******************************************************************************/ package org.vclipse.configscan.views.actions; import org.vclipse.base.ui.util.ClasspathAwareImageHelper; import org.vclipse.configscan.ConfigScanPlugin; import org.vclipse.configscan.IConfigScanImages; import org.vclipse.configscan.views.ConfigScanView; public final class ExpandTreeAction extends SimpleTreeViewerAction { public static final String ID = ConfigScanPlugin.ID + "." + ExpandTreeAction.class.getSimpleName(); public ExpandTreeAction(ConfigScanView view, ClasspathAwareImageHelper imageHelper) { super(view, imageHelper); setText("Expand all"); setToolTipText("Expand all"); setImageDescriptor(imageHelper.getImageDescriptor(IConfigScanImages.EXPAND_ALL)); setId(ID); } @Override public void run() { treeViewer.expandAll(); } }
Markdown
UTF-8
450
2.75
3
[]
no_license
# dht22-hygrometer-script <h2>DHT22 Hygrometer</h2> DHT22 Hygrometer script for accepting and sending temperature and humitity values <h2>Configuration</h2> Three things should be configured before uploading it to chip: <ul> <li>Provide Wi-Fi SSID and Password so it can connect to internet</li> <li>Configure "String url" to the url that is accepting the values</li> <li>Configure "YOUR_URL_TO_ACCEPT_VALUES" to the url you wish</li> </ul>
Ruby
UTF-8
2,041
2.578125
3
[]
no_license
class Notifier::UserBase < Notifier::Base def initialize(user:, body:, notifiable_user:) super user: user, body: body @notifiable_user = notifiable_user end def full_bio @notifiable_user.profile_blurb end def truncated_bio full_bio.present? ? full_bio&.truncate(260, seperator: /\s/) : '' end def bio_truncated? full_bio.present? ? full_bio.length != truncated_bio.length : false end def distance_with_units distance + ' miles' end def distance_with_units_short distance + ' mi' end def ages @notifiable_user.child_ages_in_months end def distance return '' if @user.place.nil? || @notifiable_user.place.nil? @user.place.distance_to(@notifiable_user.place).round(1).to_s end def kids_ages_sentence_string if ages.empty? 'no kids' elsif ages.length == 1 'kid is ' + display_age(ages[0], 'month') else 'kids are ' + and_join_ages end end def kids_ages_count_string if ages.empty? 'no kids' elsif ages.length == 1 '1 kid age ' + display_age(ages[0], 'month') else and_join_ages = display_ages.slice(0, display_ages.length - 1).join(', ') + ' and ' + display_ages[-1] ages.count.to_s + ' kids ages ' + and_join_ages end end def display_ages ages.map { |age| display_age(age, 'mo') } end def kids_ages_standalone_string if ages.empty? 'no kids' elsif ages.length == 1 'Kid age ' + display_age(ages[0], 'mo') else 'Kids age ' + and_join_ages end end def and_join_ages display_ages.slice(0, display_ages.length - 1).join(', ') + ' and ' + display_ages[-1] end def link ENV['LINK_HOST'] + '/users/' + @notifiable_user.id.to_s end def chat_link ENV['LINK_HOST'] + '/chat/' + @notifiable_user.id.to_s end def display_age(age_in_months, month_unit) if age_in_months < 24 age_in_months.to_s + ' ' + month_unit + (age_in_months > 1 ? 's' : '') else (age_in_months / 12).to_s end end end
Python
UTF-8
787
3.578125
4
[]
no_license
def reduce_polymer(polymer): temp_string = "" for char in polymer: next_char = "" if not temp_string else temp_string[-1] if should_remove_characters(char, next_char): temp_string = temp_string[:-1] else: temp_string += char return len(temp_string) def remove_unit_from_polymer(polymer): chars = find_all_characters(polymer) return min(reduce_polymer(polymer.replace(c.lower(), "").replace(c.upper(), "")) for c in chars) def should_remove_characters(a, b): return a.lower() == b.lower() and a.isupper() != b.isupper() def find_all_characters(polymer): chars = set() for i in range(len(polymer)): if polymer[i].lower() not in chars: chars.add(polymer[i].lower()) return chars
JavaScript
UTF-8
3,471
2.609375
3
[]
no_license
import React, { useState } from "react"; import "./App.css"; import { useSelector } from "react-redux"; import { selectLoggedinUser } from "./store/selectors"; import ResourcesSection from "./components/ResourcesSection"; import AddResourceForm from "./components/AddResourceForm"; const selectDevs = (state) => { return state.developers; }; const selectRecources = (state) => { return state.resources; }; const selectDevelopersWithFavorite = (favoriteId) => { return (state) => { return state.developers.filter((dev) => dev.favorites.includes(favoriteId)); }; }; const selectDevelopersFavoritesResources = (developerId) => { return (state) => { return state.developers .find((dev) => dev.id === developerId) .favorites.map((favId) => state.resources.find((resource) => resource.id === favId) ); }; }; function App() { const developers = useSelector(selectDevs); // const numDevelopers = useSelector(state => state.developers.length); const resources = useSelector(selectRecources); const [favoriteId, setFavoriteId] = useState(2); const [developerId, setDeveloperId] = useState(1); // console.log("favoriteId:", favoriteId); // console.log("developerId:", developerId); const developersWithThisFavorite = useSelector( selectDevelopersWithFavorite(favoriteId) ); // console.log("developers lenghth", developers.length); // console.log("resources", resources.length); const renderFavorites = resources.map((resource) => { const { id, name } = resource; return ( <option key={id} value={id}> {name} </option> ); }); // console.log("developersWithThisFavorite", developersWithThisFavorite); const renderDevsPerFavorite = developersWithThisFavorite.map((dev) => { const { id, name } = dev; return <li key={id}>{name}</li>; }); const favOptHandler = (e) => { // console.log("e.target.value", e.target.value); setFavoriteId(parseInt(e.target.value)); }; const devOptHandler = (e) => { // console.log("e.target.value", e.target.value); setDeveloperId(parseInt(e.target.value)); }; const optionsDevs = developers.map((dev) => { const { id, name } = dev; return ( <option key={id} value={id}> {name} </option> ); }); const developersFavoritesResources = useSelector( selectDevelopersFavoritesResources(developerId) ); const renderFavoritesPerDev = developersFavoritesResources.map((resource) => { const { id, name } = resource; return <li key={id}>{name}</li>; }); const loggedinUser = useSelector(selectLoggedinUser); // console.log("loggedinUser", loggedinUser.name); return ( <div className="App"> <div className="welcome"> Welcome back, <strong>{loggedinUser.name}</strong>! </div> <h3>Web development resources</h3> <p>Developers: {developers.length}</p> <p>Resources: {resources.length}</p> <h3> Who likes:{" "} <select value={favoriteId} onChange={favOptHandler}> {renderFavorites} </select>{" "} ? </h3> <ul>{renderDevsPerFavorite}</ul> <h3> What are{" "} <select value={developerId} onChange={devOptHandler}> {optionsDevs} </select>{" "} 's favourites? </h3> <ul>{renderFavoritesPerDev}</ul> <ResourcesSection /> <AddResourceForm /> </div> ); } export default App;
Shell
UTF-8
466
3.453125
3
[]
no_license
#!/bin/bash # Написать скрипт, который переименовывает все файлы # с именами, начинающиеся на «b». (команда mv) # Ищем в текущем каталоге файлы с префиксом "b". # При отсутствии выводится ошибка files=`ls b* 2>/dev/null` if [[ -z $files ]]; then echo Files dont exist ; exit; fi for i in $files do mv $i B$i done echo Done
Python
UTF-8
2,572
4.875
5
[]
no_license
"""Problem : Given a position, return node at that position Solution : a. Iterative Solution: 1. Initialize count = 0 2. Traverse through list unitl count == index 3. Return index 4. If list ended, Return NOT FOUND b. RECURSIVE SOLUTION: 1. Set function with parameter curr, count, index 2. Base condition :if count == index -> Retun curr 3. elif curr has reached None -> Return NOT FOUND 4. Else Recursively call function itself, with parameter curr.next, count+1, index """ # Node class class Node: # function to initialize Node object def __init__(self, data): self.data = data # Linked List Class class LinkedList: # function to initialize LinkedList object def __init__(self): self.head = None # function to push node to linked list def push(self, data): newNode = Node(data) newNode.next = self.head self.head = newNode # function to display/ traverse node in linked list def display(self, curr): # Base condition if curr is None: return "None" return str(curr.data)+' -> '+self.display(curr.next) # function to get node at index ITERATIVE METHOD -- O(n) def iter_get_at(self, index): # index is 0- based count = 0 curr = self.head while curr is not None: if count == index: # At this point curr points node print('Node at index :',index,' is :',curr.data) return curr = curr.next # update curr node count +=1 # if curr reached to last node it means node not found print('Node NOT FOUND for index, ',index) return -1 # function to get node at index RECURSIVE METHOD --O(n) def recur_get_at(self, curr, count, index): # index is 0- based # Base condition if curr is None: print(f'NODE NOT FOUND, at index:{index}') return elif count == index: print(f'Node :{curr.data} found for index {index}') return # recursively call function return self.recur_get_at(curr.next, count+1, index) # Code Begins Here if __name__ == "__main__": # initialize linked list llist = LinkedList() print(llist.display(llist.head)) # push node llist.push(5) llist.push(4) llist.push(3) llist.push(2) llist.push(1) print(llist.display(llist.head)) # find node at index print('Itetative way :') llist.iter_get_at(0) llist.iter_get_at(4) llist.iter_get_at(2) llist.iter_get_at(5) llist.iter_get_at(-1) print('REcursibe way :') llist.recur_get_at(llist.head, 0, 0) llist.recur_get_at(llist.head, 0, 4) llist.recur_get_at(llist.head, 0, 2) llist.recur_get_at(llist.head, 0, 5) llist.recur_get_at(llist.head, 0, -1)
Swift
UTF-8
401
2.71875
3
[]
no_license
// // Shapes.swift // Shapes // // Created by Rodrigo Labronici on 13/04/16. // Copyright © 2016 Rodrigo Labronici. All rights reserved. // import SpriteKit protocol Shapes { var initialPoint: CGPoint {get set} var lastPoint:CGPoint {get set} var inicialPointLandscape: CGPoint {get set} var lastPointLandscape: CGPoint {get set} func getTipe() -> Shapes func isBlocked() -> Bool }
Python
UTF-8
1,181
2.625
3
[]
no_license
""" nitter module """ from datetime import datetime import logging from typing import List import requests from lxml import etree from nitter.types import Twitt class FetchException(Exception): """ FetchException """ def fetch_feed(instance_urls: str, followings: List[str], logger: logging.Logger) -> List[Twitt]: """ fetch nitter rss :param username: :return: """ url = f"{instance_urls}/{','.join(followings)}/rss" logger.info("Request on %s", url) resp = requests.get(url) if resp.status_code != 200: raise FetchException(f"Fail to fetch status: {resp.status_code} {followings}") root = etree.fromstring(resp.text.encode()) # pylint: disable=c-extension-no-member return [Twitt(**{"title": item.find("title").text, "description": item.find("description").text, "guid": item.find("guid").text, "link": item.find("link").text, "pub_date": datetime.strptime(item.find("pubDate").text, "%a, %d %b %Y %H:%M:%S %Z")}) for item in root.xpath("/rss/channel/item")]
Java
UTF-8
312
1.851563
2
[]
no_license
package com.syl.androidart.fragment; import android.view.View; import com.syl.androidart.base.BaseFragment; /** * Created by Bright on 2017/8/7. * @Describe Retrofit * @Called */ public class RetrofitFragment extends BaseFragment { @Override public View initView() { return null; } }
Markdown
UTF-8
1,559
3.5
4
[]
no_license
# Chapter 1 What is functional programming? ## Summary - Functional programming is based on a simple premise. We use pure functions to construct programs. - Pure functions are functions that have no side effect. - Pure functions are easier to reason about. - We call functions that have side effects procedures, functions have no side effects. - If we have to have side effects, it's best to make them *unobservable* by other parts of the code. e.g. writing to a local variable or writing to a file as long as no other enclosing function can *observe* it. - Referential transparency: An expression is RT if it can be replaced by its evaluated value in a program and not change the meaning of the program. A function is pure if calling it with RT parameters is RT. - We can use substitution model with (pure) functions. We can replace expressions with their values and vice versa. This makes it easier to reason about the code because we don't need to keep track of the state of the program. This is called local reasoning. - A function can be treated as a black box. This results in more composable components and easier reuse. The functional programs are more modular in the sense that the meaning of the whole depends on the meaning of the constituent components and rules of composition. Not any (observable) state. ## Discussion points - Functional programing makes testing, reuse and parallelization simpler. Compared to what and why? - What are the downsides? - The example is kind of useless. It erases the question instead of answering it.
Java
UTF-8
965
2.15625
2
[]
no_license
package com.retailstore.billing; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import com.retailstore.dto.request.BillRequestDto; /** * @author pankajsamadhiya * */ @RunWith(SpringRunner.class) @SpringBootTest public class GroceryDiscountStrategyTest { @Mock private DiscountStrategy discountStrategy; @Mock private BillRequestDto billDto; Billing billing; @InjectMocks GroceryDiscountStrategy groceryDiscountStrategy; @Before public void setUp(){ billing = new Billing(discountStrategy,billDto); } @Test public void testCalculateFinalBillAmount(){ when(billDto.getBillAmount()).thenReturn(200.0); groceryDiscountStrategy.calculateFinalBillAmount(billing); } }
C#
UTF-8
1,550
3.125
3
[]
no_license
using System; namespace Alistirmalar { class Program { static void Main(string[] args) { string[] dersler = new string[] { "Matematik","Türkçe","Yeni Ders Geometri","Coğrafya","Biyoloji","Yeni bir ders daha" }; Console.WriteLine("----------------FOR------------------"); for (int i = 0; i < dersler.Length; i++) { Console.WriteLine(dersler[i]); } Console.WriteLine("----------------FOREACH------------------"); foreach (string ders in dersler) { Console.WriteLine(ders); } Kitap kitap1 = new Kitap(); kitap1.KitapAdi = "Aşkın Gözyaşları"; kitap1.YazarAdi = "Sinan Yağmur"; kitap1.StokAdedi = 150; kitap1.Fiyat = 25; Kitap kitap2 = new Kitap(); kitap2.KitapAdi = "Aşk"; kitap2.YazarAdi = "Elif Şafak"; kitap2.StokAdedi = 200; kitap2.Fiyat = 30; Kitap[] kitaps = new Kitap[] { kitap1, kitap2 }; foreach (Kitap kitap in kitaps) { Console.WriteLine(kitap.KitapAdi + " " + kitap.YazarAdi + " " + kitap.StokAdedi + " " + kitap.Fiyat); } } } class Kitap { public string YazarAdi { get; set; } public string KitapAdi { get; set; } public decimal Fiyat { get; set; } public int StokAdedi { get; set; } } }
Python
UTF-8
214
3.28125
3
[]
no_license
# open: megnyit egy file-t és visszaad egy streamet file = open('./temp.txt') print(file) lines = file.readlines() print(lines) nums = [] for line in lines: nums.append(int(line)) file.close() print(nums)
C#
UTF-8
1,633
3.171875
3
[]
no_license
using UnityEngine; using UnityEngine.UI; using System.Collections; public class TextController : MonoBehaviour { public Text display; public InputField input; int intRandomNumber; int intGuessedNumber; // Use this for initialization void Start () { InitializeGame(); input.onEndEdit.AddListener(CheckAnswer); } // Update is called once per frame void Update () { // Hitting the spacebar always restarts the game if (Input.GetKeyDown(KeyCode.Space)) { InitializeGame(); } } private void CheckAnswer(string arg) { // Reset input field input.text = ""; // Compare input to random number if (int.TryParse(arg, out intGuessedNumber)) { if (intRandomNumber > intGuessedNumber) { display.text = string.Format("You guessed {0}. You are too low", intGuessedNumber); } if (intRandomNumber < intGuessedNumber) { display.text = string.Format("You guessed {0}. You are too high", intGuessedNumber); } if (intRandomNumber == intGuessedNumber) { display.text = string.Format("You guessed {0}.\nYou are correct!\n(press spacebar to continue)", intGuessedNumber); } } } private void InitializeGame() { // Pick a random number intRandomNumber = Random.Range(1, 100); Debug.Log(intRandomNumber); // Set the text to start the game display.text = "Geuss a number between 1 and 100"; } }
Markdown
UTF-8
6,273
3.265625
3
[]
no_license
**Chapter 4 Functions** <!-- vim-markdown-toc GFM --> * [Procedures](#procedures) * [Functions with Empty Parentheses](#functions-with-empty-parentheses) * [Function Invocation with Expression Blocks](#function-invocation-with-expression-blocks) * [Recursive Functions](#recursive-functions) * [Nested Functions](#nested-functions) * [Calling Functions with Named Parameters](#calling-functions-with-named-parameters) * [Parameters with Default Values](#parameters-with-default-values) * [Vararg Parameters](#vararg-parameters) * [Parameter Groups](#parameter-groups) * [Type Parameters](#type-parameters) * [Methods and Operators](#methods-and-operators) * [Writing Readable Functions](#writing-readable-functions) * [Summary](#summary) * [Exercises](#exercises) <!-- vim-markdown-toc --> Syntax: Defining an Input-less Function ``` def <identifier> = <expression> ``` ```scala scala> def hi = "hi" hi: String scala> hi res0: String = hi ``` Syntax: Defining a Function with a Return Type ``` def <identifier>: <type> = <expression> ``` ```scala scala> def hi:String="hi" hi: String ``` Syntax: Defining a Function ``` def <identifier>(<identifier>: <type>[, ... ]): <type> = <expression> ``` ```scala scala> def multiplier(x:Int,y:Int):Int={x * y} multiplier: (x: Int, y: Int)Int scala> multiplier(6,7) res3: Int = 42 scala> def safeTrims(s:String):String = { | if (s == null) return null | s.trim() | } safeTrims: (s: String)String ``` # Procedures ```scala scala> def log(d: Double) = println(f"Got value $d%.2f") log: (d: Double)Unit scala> def log(d: Double): Unit = println(f"Got value $d%.2f") log: (d: Double)Unit scala> log(2.23535) Got value 2.24 ``` # Functions with Empty Parentheses Syntax: Defining a Function with Empty Parentheses ``` def <identifier>()[: <type>] = <expression> ``` ```scala scala> def hi(): String = "hi" hi: ()String scala> hi() res11: String = hi scala> hi res12: String = hi ``` # Function Invocation with Expression Blocks Syntax: Invoking a Function with an Expression Block ``` <function identifier> <expression block> ``` ```scala scala> def formatEuro(amt: Double) = f"€$amt%.2f" formatEuro: (amt: Double)String scala> formatEuro(3.4645) res14: String = €3.46 scala> formatEuro { val rate = 1.32; 0.235 + 0.7123 + rate * 5.32 } res15: String = €7.97 ``` # Recursive Functions ```scala scala> def power(x:Int,n:Int):Long = { | if (n<1) 1 | else x * power(x, n - 1) | } power: (x: Int, n: Int)Long scala> power(2, 8) res16: Long = 256 scala> power(2, 1) res17: Long = 2 scala> power(2, 0) res18: Long = 1 ``` ```scala scala> @annotation.tailrec | def power(x: Int, n: Int): Long = { | if (n >= 1) x * power(x, n-1) | else 1 | } if (n >= 1) x * power(x, n-1) ^ On line 3: error: could not optimize @tailrec annotated method power: it contains a recursive call not in tail position scala> @annotation.tailrec | def power(x: Int, n: Int): Long = { | if (n < 1) 1 | else x * power(x, n-1) | } else x * power(x, n-1) ^ On line 4: error: could not optimize @tailrec annotated method power: it contains a recursive call not in tail position scala> @annotation.tailrec | def power(x: Int, n: Int, t: Int = 1): Int = { | if (n < 1 ) t | else power(x, n-1, x * t) | } power: (x: Int, n: Int, t: Int)Int scala> power(2, 8) res19: Int = 256 ``` # Nested Functions ```scala scala> def max(a: Int, b: Int, c: Int) = { | def max(x: Int,y:Int) = if(x>y) x else y | max(a, max(b, c)) | } max: (a: Int, b: Int, c: Int)Int scala> max(42, 181, 19) res27: Int = 181 ``` # Calling Functions with Named Parameters Syntax: Specifying a Parameter by Name ``` <function name>(<parameter> = <value>) ``` ```scala scala> def greet(prefix: String, name: String) = s"$prefix $name" greet: (prefix: String, name: String)String scala> val greeting1 = greet("Ms", "Brown") greeting1: String = Ms Brown scala> val greeting2 = greet(name = "Brown", prefix = "Mr") greeting2: String = Mr Brown ``` # Parameters with Default Values Syntax: Specifying a Default Value for a Function Parameter ``` def <identifier>(<identifier>: <type> = <value>): <type> ``` ```scala scala> def greet(prefix: String = "", name: String) = s"$prefix$name" greet: (prefix: String, name: String)String scala> val greeting1 = greet(name = "Paul") greeting1: String = Paul scala> def greet(name: String, prefix: String = "") = s"$prefix$name" greet: (name: String, prefix: String)String scala> val greeting2 = greet("Ola") greeting2: String = Ola ``` # Vararg Parameters ```scala scala> def sum(item: Int*):Int = { | var total = 0 | for ( i <- item ) { | total += i | } | total | } sum: (item: Int*)Int scala> sum(10, 20, 30) res29: Int = 60 scala> sum() res30: Int = 0 ``` # Parameter Groups ```scala scala> def max(x: Int)(y: Int) = if (x > y) x else y max: (x: Int)(y: Int)Int scala> val larger = max(20)(39) larger: Int = 39 ``` # Type Parameters Syntax: Defining a Function’s Type Parameters ``` def <function-name>[type-name](parameter-name>: <type-name>): <type-name>... ``` ```scala scala> def identity(s: String): String = s identity: (s: String)String scala> def identity(i: Int): Int = i identity: (i: Int)Int scala> def identity(a: Any): Any = a identity: (a: Any)Any scala> val s: String = identity("Hello") ^ error: type mismatch; found : Any required: String ``` ```scala scala> def identity[A](a:A):A = a identity: [A](a: A)A scala> val s:String = identity[String]("Hello") s: String = Hello scala> val d:Double = identity[Double](2.717) d: Double = 2.717 ``` # Methods and Operators ```scala scala> val s = "vacation.jpg" s: String = vacation.jpg scala> val isJPEG = s.endsWith(".jpg") isJPEG: Boolean = true scala> val d = 65.642 d: Double = 65.642 scala> d.round res31: Long = 66 scala> d.floor res32: Double = 65.0 scala> d.compare(18.0) res33: Int = 1 scala> d.+(2.721) res34: Double = 68.363 scala> d compare 18.0 res36: Int = 1 scala> d + 2.721 res37: Double = 68.363 ``` # Writing Readable Functions # Summary # Exercises
JavaScript
UTF-8
5,455
3.359375
3
[]
no_license
let elList = []; let CONTROLS = { buttons: { }, sliders: { }, sorting: { } } window.addEventListener('load', function() { // slider display elements const elementTarget = document.querySelector('.value__elements'); const speedTarget = document.querySelector('.value__speed'); // sorting elements CONTROLS.sorting = { type: document.getElementById('sorting__type'), order: document.getElementById('sorting__order') }; // slider control elements CONTROLS.sliders = { elements: document.getElementById('elements'), speed: document.getElementById('speed') }; // button elements CONTROLS.buttons = { sort: document.querySelector('.btn__sort'), pause: document.querySelector('.btn__pause'), shuffle: document.querySelector('.btn__shuffle') }; // show slider values elementTarget.innerHTML = CONTROLS.sliders.elements.value; speedTarget.innerHTML = CONTROLS.sliders.speed.value; // display elements elList = createElements(CONTROLS.sliders.elements.value); CONTROLS.sliders.elements.addEventListener('input', () => { const value = CONTROLS.sliders.elements.value; elementTarget.innerHTML = value; elList = createElements(value); }); CONTROLS.sliders.speed.addEventListener('input', () => { speedTarget.innerHTML = CONTROLS.sliders.speed.value; }); // add button click events addClickEvent(CONTROLS.buttons.shuffle, () => { const container = document.getElementById('element-box'); shuffle(elList, container); resetControls(); }); addClickEvent(CONTROLS.buttons.sort, () => { start(); disable(CONTROLS.buttons.sort, ...Object.values(CONTROLS.sliders), ...Object.values(CONTROLS.sorting)); enable(CONTROLS.buttons.pause); }); addClickEvent(CONTROLS.buttons.pause, () => { pause(); resetControls(); }); }); window.addEventListener('resize', debounce(updateElementDimensions, 150)); function getElementValue(id) { return document.getElementById(id).value; } function addClickEvent(button, func) { button.addEventListener('click', func); } function enable(...elements) { elements.forEach(b => { b.disabled = false; }) } function disable(...elements) { elements.forEach(b => { b.disabled = true; }) } function createElements(number) { const container = document.getElementById('element-box'); const width = container.offsetWidth / number; const showValue = width <= 30 ? false : true; const r = (18 - 57) / number; const g = (231 - 172) / number; const b = (58 - 211) / number; const bars = []; for (i = 0; i < number; i++) { const height = Math.round(container.offsetHeight / number * (i + 1)) * 0.9; const color = `rgb( ${Math.floor(57 + r * i)}, ${Math.floor(172 + g * i)}, ${Math.floor(211 + b * i)} )`; const el = createBarElement(height, width, color, showValue); bars.push(el); } shuffle(bars, container); return bars; } function createBarElement(height, width, color, showValue = false) { const el = document.createElement('div'); el.classList.add('element'); el.style.width = `${width}px`; el.style.height = `${height}px`; el.style.background = color; if (showValue) { const value = document.createElement('span'); value.innerHTML = Math.round(height + 0.1 * height); // get full height el.appendChild(value); } return el; } function resetControls() { enable(CONTROLS.buttons.sort, ...Object.values(CONTROLS.sliders), ...Object.values(CONTROLS.sorting)); disable(CONTROLS.buttons.pause); } function pause() { play = false; resetControls(); } function start() { const container = document.getElementById('element-box'); const ascending = getElementValue('sorting__order') == 'ascending'; play = true; setSpeed(getElementValue('speed')); switch (getElementValue('sorting__type')) { case 'quick': Algorithms.quick(container.children, ascending); break; case 'heap': Algorithms.heap(container.children, ascending); break; case 'bubble': Algorithms.bubble(container.children, ascending); break; case 'insertion': Algorithms.insertion(container.children, ascending); break; case 'selection': Algorithms.selection(container.children, ascending); break; case 'merge': Algorithms.merge(container.children, ascending); break; default: return; } } function shuffle(elements, container) { pause(); container.innerHTML = ''; // remove children elements.sort(() => 0.5 - Math.random()); elements.forEach((item, i) => { const width = parseFloat(item.style.width); item.style.left = `${width * i}px`; container.appendChild(item); }) } function debounce(func, time = 100){ var timer; return function(event) { if (timer) { clearTimeout(timer); } timer = setTimeout(func, time, event); }; } function updateElementDimensions() { elList = createElements(elList.length); }
JavaScript
UTF-8
1,508
3.03125
3
[]
no_license
import {createStore, combineReducers} from 'redux'; import {ACTION_UPDATE_USER_PROFILE} from './actions'; /** * A "Reducer" which is capable to turn the current application status received into * a new application status. * * @param {*} state During "Redux Store" initialization this parameter is undefined * and the ES6 default parameter is taken to initialize the store value instead. * Later executions of this function will contain the current application status before * the "Action" has happened. * @param {*} action The "Action" which contains information about the application status change. * An "Action" contains at least a type property. In addition each "Action" can have its own payload * that contains information about the application status change. */ function updateUserProfileReducer(state = {firstname: '', lastname: ''}, action) { switch(action.type) { case ACTION_UPDATE_USER_PROFILE: return action.userProfile; default: //If a "Reducer" is not responsible for an "Action" received it must //return the current application status like we do in this default block. return state; } } /** * "Redux Store" initialization. * While initialization the "Redux Store" can be split into specific * application status regions. For each region a specific "Reducer" can be assigned. */ const store = createStore(combineReducers({ userProfile: updateUserProfileReducer })); export default store;
C#
UTF-8
1,778
2.75
3
[]
no_license
using NUnit.Framework; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Firefox; using OpenQA.Selenium.Support.UI; using System; namespace TestAutomation.Page { public class CheckYourBrowserPage : BasePage { public static IWebElement text => Driver.FindElement(By.CssSelector(".simple-major")); public CheckYourBrowserPage(IWebDriver webdriver) : base(webdriver) { } //konstruktorius public void TestResult(string result, IWebDriver webdriver) { WaitForElementToBeDisplayed(text); Assert.IsTrue(text.Text.Contains(result), "Browser name is not displayed correctly"); ClosePage(webdriver); } public static IWebDriver SelectBrowser(string browser) { if ("chrome".Equals(browser)) Driver = new ChromeDriver(); else if ("firefox".Equals(browser)) Driver = new FirefoxDriver(); else throw new Exception("Browser is not supported"); return Driver; } public void GoToPage(IWebDriver webdriver) { webdriver.Url = "https://developers.whatismybrowser.com/useragents/parse/?analyse-my-user-agent=yes#parse-useragent"; webdriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10); webdriver.Manage().Window.Maximize(); } private static void ClosePage(IWebDriver webdriver) { webdriver.Quit(); } private static void WaitForElementToBeDisplayed(IWebElement webElement) { WebDriverWait wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(10)); wait.Until(webdriver => webElement.Displayed); } } }
Java
UTF-8
3,655
2.046875
2
[]
no_license
package combit.ListLabel23.DataProviders;import Common.Activation;import static Common.Helper.Convert;import static Common.Helper.getGetObjectName;import static Common.Helper.getReturnObjectName;import static Common.Helper.ConvertToConcreteInterfaceImplementation;import Common.Helper;import com.javonet.Javonet; import com.javonet.JavonetException; import com.javonet.JavonetFramework; import com.javonet.api.NObject; import com.javonet.api.NEnum; import com.javonet.api.keywords.NRef; import com.javonet.api.keywords.NOut; import com.javonet.api.NControlContainer;import java.util.concurrent.atomic.AtomicReference;import jio.System.*; import combit.ListLabel23.DataProviders.*; import combit.ListLabel23.*;public class TranslateFilterSyntaxEventArgs extends EventArgs {protected NObject javonetHandle; /** * GetProperty */ public LlExpressionPart getPart (){ try { return LlExpressionPart.valueOf(((NEnum) javonetHandle.<NObject>get("Part")).getValueName());} catch (JavonetException _javonetException) { _javonetException.printStackTrace(); return null;} }/** * GetProperty */ public java.lang.Integer getArgumentCount (){ try { return javonetHandle.get("ArgumentCount");} catch (JavonetException _javonetException) { _javonetException.printStackTrace(); return 0;} }/** * GetProperty */ public NObject getName (){ try { return (NObject) javonetHandle.<NObject>get("Name");} catch (JavonetException _javonetException) { _javonetException.printStackTrace(); return null;} }/** * GetProperty */ public NObject[] getArguments (){ try { return Helper.ConvertNObjectToDestinationType((NObject[])javonetHandle.<NObject>get("Arguments"),NObject[].class);} catch (JavonetException _javonetException) { _javonetException.printStackTrace(); return null;} }/** * SetProperty */ public void setResult (NObject value){ try { javonetHandle.set("Result",value);} catch (JavonetException _javonetException) { _javonetException.printStackTrace(); } }/** * GetProperty */ public NObject getResult (){ try { return (NObject) javonetHandle.<NObject>get("Result");} catch (JavonetException _javonetException) { _javonetException.printStackTrace(); return null;} }/** * SetProperty */ public void setHandled (java.lang.Boolean value){ try { javonetHandle.set("Handled",value);} catch (JavonetException _javonetException) { _javonetException.printStackTrace(); } }/** * GetProperty */ public java.lang.Boolean getHandled (){ try { return javonetHandle.get("Handled");} catch (JavonetException _javonetException) { _javonetException.printStackTrace(); return false;} }public TranslateFilterSyntaxEventArgs (LlExpressionPart part,java.lang.Integer argumentCount,NObject name,NObject[] arguments,NObject result){ super((NObject) null); try { javonetHandle = Javonet.New("TranslateFilterSyntaxEventArgs",NEnum.fromJavaEnum(part),argumentCount,name,new Object[] {arguments},result); super.setJavonetHandle(javonetHandle); } catch (JavonetException _javonetException) { _javonetException.printStackTrace(); } }public TranslateFilterSyntaxEventArgs(NObject handle) {super(handle);this.javonetHandle=handle;}public void setJavonetHandle(NObject handle) { this.javonetHandle = handle; } static { try { Activation.initializeJavonet(); } catch (java.lang.Exception e) { e.printStackTrace(); } }}
Java
UTF-8
9,389
3.140625
3
[]
no_license
import java.util.*; import java.net.*; import java.io.*; /** * Servidor que processa e armazena os dados dos arquivos. * * @author Lucas Gutierrez * @author Marcos Balatka */ public class Servidor extends IOException { private final String arquivoOriginal = "sample.csv"; private final String arquivoFormatado = "sample.pra"; private final String arquivoIndice = "indice.pra"; private final int colunaChave = 2; private final int porta = 12345; private TreeMap tm; private Set set; private Iterator ite; private final ManipuladorArquivo ma = new ManipuladorArquivo(); private final ManipuladorIndice mi = new ManipuladorIndice(); private ServerSocket servidor; private final int limite; private Socket cliente; private final ArrayList<Integer> indices; /** * Construtor formata os arquivos, carrega a TreeMap e abre o servidor * * @throws IOException Erros de IO. */ public Servidor() throws IOException { limite = 0; ma.formataArquivo(arquivoOriginal, arquivoFormatado); indices = mi.carregaIndice(arquivoIndice, arquivoFormatado, ma.getMaiores(), colunaChave); //nome do arquivo do indice, nome do arquivo formatado, vetor de maiores, numero da coluna com campo chave carregaArvore(); abreServidor(); } /** * Método que cria uma thread que recebe entradas do servidor a fim de * atualizar o arquivo de índice * * @throws IOException Erros de IO. */ public void atualizarArquivo() throws IOException { new Thread(() -> { Scanner teclado = new Scanner(System.in); String cmd; while (true) { cmd = teclado.nextLine(); if (cmd.equals("Atualizar")) { synchronized (this) { try { mi.atualizaIndice(indices); System.out.println("Arquivo atualizado"); } catch (Exception e) { System.out.println("Problemas na atualização"); } } } } }).start(); } /** * Abre o servidor de dados e começa a espera por clientes. * * @throws IOException Erros de IO. */ private void abreServidor() throws IOException { servidor = new ServerSocket(porta); System.out.println("Porta " + porta + " aberta!"); } /** * Cria a TreeMap usando o arquivo de índices devidamente criado. * * @throws IOException Erros de IO. */ private void carregaArvore() throws IOException { tm = mi.criaArvore(); set = tm.entrySet(); ite = set.iterator(); } /** * Cria-se a Thread que espera entradas de teclado do servidor e em seguida * entra-se em um loop de espera de cliente; Ao chegar um novo cliente, * cria-se uma thread que espera solicitações do referido cliente. * * @throws IOException Erros de IO. */ public void loopEspera() throws IOException { atualizarArquivo(); while (true) { cliente = servidor.accept(); new Thread(() -> { Socket c = cliente; System.out.println("Nova conexão com o cliente " + c.getInetAddress().getHostAddress()); try { Scanner s = new Scanner(c.getInputStream()); PrintStream saida = new PrintStream(c.getOutputStream()); int nReg, menu; String resultado; String linha; while (s.hasNextLine()) { menu = Integer.parseInt(s.nextLine()); if (menu == 1) { saida.println("Número do registro: "); nReg = Integer.parseInt(s.nextLine()); try { resultado = buscaRegistro(nReg); saida.println(resultado); System.out.println(c.getInetAddress().getHostAddress() + " realizou busca"); } catch (Exception e) { } } else if (menu == 2) { saida.println("Número do registro: "); nReg = Integer.parseInt(s.nextLine()); try { resultado = removeRegistro(nReg); saida.println(resultado); System.out.println(c.getInetAddress().getHostAddress() + " realizou remoção"); } catch (Exception e) { } } else if (menu == 3) { saida.println("Digite as informações a serem inseridas:"); linha = s.nextLine(); try { resultado = insereRegistro(linha); saida.println(resultado); System.out.println(c.getInetAddress().getHostAddress() + " realizou inserção"); } catch (Exception e) { } } else if (menu == 4) { saida.println("Nome do arquivo a ser usado:"); linha = s.nextLine(); try { while (!linha.equals("EOF")) { resultado = insereRegistro(linha); saida.println(resultado); System.out.println(c.getInetAddress().getHostAddress() + " realizou inserção"); linha = s.nextLine(); } } catch (Exception e) { } } else if (menu == -1) { break; } else { saida.println("Valor inválido!"); } } System.out.println("Conexão " + c.getInetAddress().getHostAddress() + " encerrada"); mi.atualizaIndice(indices); } catch (IOException e) { } }).start(); } } /** * Método que recebe um id e retorna o registro correspondente ao id ao * cliente que solicitou. * * @param nReg Id do registro desejado. * * @return Linha respectiva, ou mensagem de erro. * * @throws IOException Erros de IO. */ private String buscaRegistro(int nReg) throws IOException { if (tm.get(nReg) != null) { String resultBusca; int linhaRegistro = Integer.parseInt(tm.get(nReg).toString()); resultBusca = ma.buscaLinha(linhaRegistro); return resultBusca; } return "Resultado não encontrado!"; } /** * Dado um id lançado pelo usuário, o método exclui o registro respectivo; A * exclusão acontece apenas no arquivo de índices inicialmente e, ou * solicitado pelo servidor, ou ao ter um usuário desconectado os arquivos * são devidamente atualizados; O método garante exclusividade de execução. * * @param nReg Id do registro desejado. * * @return Mensagem de execução. * * @throws IOException Erro de IO. */ private synchronized String removeRegistro(int nReg) throws IOException { if (tm.get(nReg) != null) { String resultBusca; int linhaRegistro = Integer.parseInt(tm.get(nReg).toString()); System.out.println("Linha Registro:" + linhaRegistro); tm.remove(nReg); indices.set(linhaRegistro, -1); resultBusca = "Registro Excluido!!!"; System.out.println(resultBusca); return resultBusca; } return "Registro nao encontrado"; } /** * Dado um id lançado pelo usuário, o método adiciona o registro respectivo; * O método garante exclusividade de execução. * * @param novoRegistro Linha a ser inserida. * * @return Mensagem de execução. * * @throws IOException Erro de IO. */ private synchronized String insereRegistro(String novoRegistro) throws IOException { String regFormatado = ma.separaLinha(novoRegistro); System.out.println(regFormatado); int novoID = mi.recuperaID(regFormatado); if (tm.get(novoID) != null) { return "Nao foi possivel adicionar o novo registro pois ja existe um registro com esse ID"; } indices.add(novoID); tm.put(novoID, indices.size() - 1); ma.insereLinha(regFormatado); ma.insereLinhaArqOriginal(novoRegistro); return "O registro foi inserido com sucesso"; } }
C
UTF-8
442
3.234375
3
[]
no_license
#include<stdio.h> #include<string.h> #include<stdlib.h> int main(void) { // your code goes here int *arr,shift,size,index; scanf("%d %d",&size,&shift); arr=(int*)malloc(size*sizeof(int)); while(shift>=size) { shift-=size; } for(index=0;index<size;index++) scanf("%d ",&arr[index]); for(index=size-shift;index<size;index++) printf("%d ",arr[index]); for(index=0;index<size-shift;index++) printf("%d ",arr[index]); return 0; }
C#
UTF-8
1,290
2.71875
3
[ "MIT" ]
permissive
using Essenbee.Bot.Core.Games.Adventure.Interfaces; using System.Collections.Generic; namespace Essenbee.Bot.Core.Games.Adventure.Locations.AllAlikeMaze { public class BrinkOfPit : AdventureLocation { public BrinkOfPit(IReadonlyAdventureGame game) : base(game) { LocationId = Location.BrinkOfPit; Name = "Brink of Pit"; ShortDescription = "on the brink of a pit"; LongDescription = "standing on the brink of a thirty foot pit with a massive orange column down one wall." + "You could climb down here but you could not get back up. The maze continues at this level."; IsDark = true; Level = 1; Items = new List<IAdventureItem>(); ValidMoves = new List<IPlayerMove> { new PlayerMove("You enter the pit, and squeeze yourself through an impossibly narrow crack...", Location.BirdChamber, "down"), new PlayerMove("", Location.AllAlike13, "north", "n"), // Dead end? new PlayerMove("", Location.AllAlike5, "south", "s"), new PlayerMove("", Location.AllAlike14, "east", "e"), new PlayerMove("", Location.AllAlike12, "west", "w"), }; } } }
TypeScript
UTF-8
1,068
3.4375
3
[ "MIT" ]
permissive
import { Record } from 'immutable'; /** * 组件位置 * left(左)|right(右)|top(上)|bottom(下) * 绝对定位: left, top 对应 Position: absoult | relative * 相对定位:对应 margin */ export interface IPosition { top: number; left: number; } const defaultRecord: IPosition = { top: 0, left: 0 }; export const PositionStateRecord: Record.Class = Record(defaultRecord); /** * 构建组件位置State */ export class PositionState extends PositionStateRecord { /** * 初始化一个空的PositionState */ static createEmpty(): PositionState { return PositionState.create({ top: 0, left: 0 }); } /** * 通过传入位置参数初始化PositionState * @param position IPosition类型的对象(eg:{left: 10, right: 10, top: 10, bottom: 10}) */ static create(position: IPosition): PositionState { return new PositionState(position); } getTop(): number { return this.get('top'); } getLeft(): number { return this.get('left'); } }
Shell
UTF-8
203
2.890625
3
[]
no_license
#!/bin/bash for i in {1..5}; do echo "Error test $i" g++ -DERRTEST=$i test.cpp 2>/dev/null if [[ $? == 0 ]]; then echo "Fail, it worked!" >&2 exit 1 fi done echo Success
Markdown
UTF-8
686
3.203125
3
[]
no_license
# Monthly programming challenges for the study.py group ## [Beginner] Formatting output Printing output with color or styles can be very useful in debugging and logging. **Problem:** Design and implement your own markup language for example: ``` $ ./markup.py "<bold blue>What a wonderful world" ``` would print out "What a wonderfule world" in bold blue text. Of course that is just an example. you should design your own markup language that you find to be intuitive and easy to read. **Bonus:** 1. Try to make your code take in an entire file written in your markup language and output using your defined rules. ## [Web-Scraping] Cryptocurrencies ## [Data] Crime Rates
Ruby
UTF-8
1,544
4.125
4
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'pry' def spicy_foods [ { name: 'Green Curry', cuisine: 'Thai', heat_level: 9 }, { name: 'Buffalo Wings', cuisine: 'American', heat_level: 3 }, { name: 'Mapo Tofu', cuisine: 'Sichuan', heat_level: 6 } ] end def get_names(spicy_foods) spicy_foods.map do |dish| dish[:name] end end def spiciest_foods(spicy_foods) spicy_foods.filter do |heat| heat[:heat_level] >= 5 end end def print_spicy_foods(spicy_foods) spicy_foods.each do |food| puts "#{food[:name]} (#{food[:cuisine]}) | Heat Level: #{'🌶' * food[:heat_level]}" end end #learned you can * things by emojois def get_spicy_food_by_cuisine(spicy_foods, cuisine) spicy_foods.each do |food| food[:cuisine] == cuisine end #dont really get how this one works^^^^^^^ def sort_by_heat(spicy_foods) spicy_foods.sort_by do |food| food[:heat_level] end end # given an array of spicy foods, output to the terminal ONLY # the spicy foods that have a heat level greater than 5, in the following format: # Buffalo Wings (American) | Heat Level: 🌶🌶🌶 # HINT: Try to use methods you've already written to solve this! def print_spiciest_foods(spicy_foods) spiciest = spiciest_foods(spicy_foods) print_spicy_foods(spiciest) end # given an array of spicy foods, return an integer representing # the average heat level of all the spicy foods in the array def average_heat_level(spicy_foods) total_heat_level = spicy_foods.sum do|food| food[:heat_level] end total_heat_level / spicy_foods.length end
Markdown
UTF-8
1,363
2.921875
3
[ "MIT" ]
permissive
#Agenda: 1. HackerRank fundamentals in Obj C and Swift 2. Problem solving strategies for programming challenges (using HR and english) 3. Break into groups of 3 ppl and do HR challenges together in 15 minute chunks per problem 4. Back into a big group to discuss Cracking the Coding interview as a resource, and teach a bit of Java for understanding the solutions Slides available here: https://docs.google.com/presentation/d/1ihyKo347WrlKHyw9K-eqydDQvgf8DMqdIqM0lvZu3hw/edit?usp=sharing ### 1. HackerRank fundamentals Solve me first: https://www.hackerrank.com/challenges/solve-me-first Solve me second: https://www.hackerrank.com/challenges/simple-array-sum ### 2. Problem solving strategies: USE ENGLISH! Let's try trees: https://www.hackerrank.com/challenges/tree-huffman-decoding Let's try graphs: https://www.hackerrank.com/challenges/bfsshortreach ### 3. Groups for HackerRank exercises 5. Basic Problem solving: https://www.hackerrank.com/challenges/angry-professor 1. Height of a binary tree: https://www.hackerrank.com/challenges/tree-height-of-a-binary-tree 2. Find squares in range: https://www.hackerrank.com/challenges/sherlock-and-squares 3. Balanced Parentheses: https://www.hackerrank.com/challenges/balanced-parentheses 4. Array Sums: https://www.hackerrank.com/challenges/sherlock-and-array ### 4. Cracking the Coding Interview
Swift
UTF-8
4,144
2.609375
3
[]
no_license
// // ShiftImportViewModel.swift // Shifree // // Created by 岩見建汰 on 2018/06/23. // Copyright © 2018年 Kenta Iwami. All rights reserved. // import Foundation protocol ShiftImportViewModelDelegate: class { func initializeUI() func successImport() func successImportButExistUnknown(unknown: [Unknown]) func faildImportBecauseUnRegisteredShift(unRegisteredShift: [String]) func faildAPI(title: String, msg: String) } class ShiftImportViewModel { weak var delegate: ShiftImportViewModelDelegate? private let api = API() private(set) var sameLineTH:Float = 0.0 private(set) var usernameTH:Float = 0.0 private(set) var joinTH:Float = 0.0 private(set) var dayShiftTH:Float = 0.0 private(set) var filePath:URL = URL(fileURLWithPath: "") fileprivate let utility = Utility() func setThreshold() { api.getThreshold().done { (json) in self.sameLineTH = json["same_line_threshold"].floatValue self.usernameTH = json["username_threshold"].floatValue self.joinTH = json["join_threshold"].floatValue self.dayShiftTH = json["day_shift_threshold"].floatValue self.delegate?.initializeUI() } .catch { (err) in let tmp_err = err as NSError let title = "Error(" + String(tmp_err.code) + ")" self.delegate?.faildAPI(title: title, msg: tmp_err.domain) } } func setfilePaht(path: URL) { filePath = path } func importShift(formValues: [String:Any?]) { let start = utility.getFormatterStringFromDate(format: "yyyy-MM-dd", date: formValues["start"] as! Date) let end = utility.getFormatterStringFromDate(format: "yyyy-MM-dd", date: formValues["end"] as! Date) let number = formValues["number"] as! String let title = formValues["title"] as! String let sameLine = formValues["sameLine"] as! Float let username = formValues["username"] as! Float let join = formValues["join"] as! Float let dayShift = formValues["dayShift"] as! Float api.importShift(number: number, start: start, end: end, title: title, sameLine: String(sameLine), username: String(username), join: String(join), dayShift: String(dayShift), file: filePath).done { (json) in if json["param"].arrayValue.count == 0 { if json["results"]["unknown"].dictionaryValue == [:] { self.delegate?.successImport() }else { // 取り込みには成功したが、unknownとしてシフトを仮登録したユーザがいる場合 var unknownList:[Unknown] = [] let unknownDict = json["results"]["unknown"].dictionaryValue for userCode in unknownDict.keys { let userDict = unknownDict[userCode]?.dictionaryValue let date = userDict!["date"]?.arrayValue.map({$0.stringValue}) let name = userDict!["name"]?.stringValue let order = userDict!["order"]?.intValue unknownList.append(Unknown( userCode: userCode, date: date!, username: name!, order: order! )) } self.delegate?.successImportButExistUnknown(unknown: unknownList) } }else { // 未登録のシフトがあって取り込みは成功していない場合 let unRegisteredShift = json["param"].arrayValue.map({$0.stringValue}) self.delegate?.faildImportBecauseUnRegisteredShift(unRegisteredShift: unRegisteredShift) } } .catch { (err) in let tmp_err = err as NSError let title = "Error(" + String(tmp_err.code) + ")" self.delegate?.faildAPI(title: title, msg: tmp_err.domain) } } }
Ruby
UTF-8
1,446
2.515625
3
[]
no_license
require 'sinatra/base' require 'sinatra/flash' require './lib/bookmark' class BookmarkManager < Sinatra::Base enable :sessions register Sinatra::Flash get '/' do 'Bookmark Manager' end get '/bookmarks' do @bookmarks = Bookmark.all #flash[:keys] = "Helloo" erb(:'bookmarks/index') end post '/bookmarks/add' do @new_url = params[:new_url] @new_title = params[:new_title] if !Bookmark.check_url(@new_url) flash[:notice] = "Please enter a valid url" flash[:alert] = "danger" elsif !Bookmark.check_title(@new_title) flash[:notice] = "Please enter a title" flash[:alert] = "danger" else Bookmark.create(@new_url, @new_title) end redirect '/bookmarks' end get '/bookmarks/edit/:id' do @id = params[:id] erb(:'bookmarks/edit') end post '/bookmarks/edit/:id' do @id = params[:id] @title = params[:edit_title] @url = params[:edit_url] if !Bookmark.check_url(@url) flash[:notice] = "Please enter a valid url" flash[:alert] = "danger" elsif !Bookmark.check_title(@title) flash[:notice] = "Please enter a title" flash[:alert] = "danger" else Bookmark.edit(@url, @title, @id) redirect '/bookmarks' end redirect "/bookmarks/edit/#{@id}" end post '/bookmarks/delete/:id' do Bookmark.remove(params[:id]) redirect '/bookmarks' end run! if app_file == $0 end
Markdown
UTF-8
2,006
3.046875
3
[]
no_license
# Installation ### First install mongodb driver: `npm i mongodb` ### Then install wrapper: `npm i basic-mongo-wrapper` # Using #### This package is promise based. It means you must use `await` or `.then` to get results ## Starting #### Declare package ```JS const Interface = require("basic-mongo-wrapper"); ``` #### Creating instance of ```JS let database = new Interface(url, dbname); ``` ##### Where url: connection string, dbname: database name #### Getting information from database ```JS const Interface = require("basic-mongo-wrapper"); let database = new Interface(url, dbname); await database.findOne("users", { name: 'Fox', status: 'Premium' }).then((data) => { console.log(data); return; }); ``` # Functions ##### Find - return promise with array of all results ```JS database.find(collectionname, params); ``` ##### findOne - return promise with object ```JS database.findOne(collectionname, params); ``` ##### findOneAndUpdate - return promise with updated object ```JS database.findOneAndUpdate(collectionname, paramsfind, paramsupdate); ``` ##### updateOne - return promise with updated object ```JS database.updateOne(collectionname, paramsfind, paramsupdate); ``` ##### updateMany - return promise with all updated objects ```JS database.updateMany(collectionname, paramsfind, paramsupdate); ``` ##### insertOne - return promise with inserted object ```JS database.insertOne(collectionname, data); ``` ##### insertMany - return promise with all inserted objects ```JS database.insertMany(collectionname, dataArray); ``` ##### deleteOne - return promise with deleted object ```JS database.deleteOne(collectionname, paramsfind); ``` ##### deleteMany - return promise with all deleted objects ```JS database.deleteMany(collectionname, paramsfind); ``` ##### drop - delete all data in collection ```JS database.drop(collectionname); ``` ##### createCollection - create collection in database ```JS database.createCollection(collectionname, data); ```
Java
UTF-8
12,636
2.96875
3
[]
no_license
package assignment; import java.io.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; /** * Database class to get data from Text File or Database * Method to read people.txt written by Natalie Sy * Modification to the same method done by Vishesh Jain * Other methods for DB Connection, relationData() by Vishesh Jain * getData() method and handling in Driver Class done by Vishesh Jain * @version 2.0 21 May 2018 * @author Vishesh Jain, Natalie Sy */ public abstract class Database { private static HashMap<Integer, Profile> list = new HashMap<Integer, Profile>(); public static HashMap<Integer, Profile> getData() throws IOException{ int count=0; try { peopleData(); } catch (IOException e) { System.err.println(e.getMessage()); count++; } try { relationData(); } catch (NotToBeFriendsException | NoParentException | NotToBeChildException | NoAvailableException | NotToBeColleaguesException | NotToBeClassmatesException | IOException e) { System.err.println(e.getMessage()); count++; } if(count!=0) { connectDatabase(); createData(); insertData(); viewData(); } return list; } public static void peopleData() throws IOException { try { BufferedReader br = new BufferedReader(new FileReader("people.txt")); int id = 0; String name = ""; int age = 0; String status = ""; String[] lineSplit; Profile person = null; String line = br.readLine(); while (line != null) { lineSplit = line.split(","); id = Integer.parseInt(lineSplit[0]); name = lineSplit[1]; age = Integer.parseInt(lineSplit[2]); status = lineSplit[3]; /** * Modified by Vishesh Jain */ if(age>16) { person = new Adult(name, age, status); } else if(age<16 && age>2) { person = new Child(name,age,status, new ArrayList<String>()); } else if(age<2 && age>0) { person = new YoungChild(name,age,status,new ArrayList<String>()); } /** * Modification End */ list.put(id, person); System.out.println(" Id: "+id+ " Name: " +name + " Age: " +age + " Status: " +status); line = br.readLine(); } br.close(); } catch(FileNotFoundException e) { System.err.println("File is missgin from Compilation Folder !"); } } /** * All below methods created by Vishesh Jain */ public static void relationData() throws NotToBeFriendsException, NoParentException, NotToBeChildException, NoAvailableException, NotToBeColleaguesException, NotToBeClassmatesException, IOException { BufferedReader br = new BufferedReader(new FileReader("relation.txt")); String name = ""; String[] lineSplit; String name2 = ""; String relation = ""; Profile person1 = null; Profile person2 = null; String line = br.readLine(); while (line != null) { lineSplit = line.split(","); name = lineSplit[0].toLowerCase(); name2 = lineSplit[1].toLowerCase(); relation = lineSplit[2].toLowerCase(); for(int i: list.keySet()) { if((list.get(i).getName().contains(name))){ person1 = list.get(i); } if((list.get(i).getName().contains(name2))) { person2 = list.get(i); } } switch(relation) { case "friend": try { person1.addFriend(person2); System.out.println(person2.getName()+" added as a Friend"); person2.addFriend(person1); } catch(NotToBeFriendsException e) { System.err.println(e.getMessage()); throw new NotToBeFriendsException(e.getMessage()); } break; case "parent": try { person1.addParent(person2); System.out.println(person2.getName()+" added as a Parent"); person2.addChild(person1); } catch(NoParentException e) { System.err.println(e.getMessage()); throw new NoParentException(e.getMessage()); } break; case "child": try { person1.addChild(person2); System.out.println(person2.getName()+" added as a Child"); person2.addParent(person1); } catch(NotToBeChildException e) { System.err.println(e.getMessage()); throw new NotToBeChildException(e.getMessage()); } break; case "couple": try { person1.addCouple(person2); System.out.println(person2.getName()+" added as a Spouse"); person2.addCouple(person1); } catch(NoAvailableException e) { System.err.println(e.getMessage()); throw new NoAvailableException(e.getMessage()); } break; case "colleague": try { person1.addColleague(person2); System.out.println(person2.getName()+" added as a Colleague"); person2.addColleague(person1); } catch(NotToBeColleaguesException e) { System.err.println(e.getMessage()); throw new NotToBeColleaguesException(e.getMessage()); } break; case "classmate": try { person1.addClassmate(person2); System.out.println(person2.getName()+" added as a Classmate"); person2.addClassmate(person1); } catch(NotToBeClassmatesException e) { System.err.println(e.getMessage()); throw new NotToBeClassmatesException(e.getMessage()); } break; default: System.out.println("Invalid Relation Found !"); break; } System.out.println("Name: "+name+" Second Name: "+name2+" Relation: "+relation); line = br.readLine(); } br.close(); } public static void connectDatabase() { Connection con = null; try { //Registering the HSQLDB JDBC driver Class.forName("org.hsqldb.jdbc.JDBCDriver"); con = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/testdb", "SA", ""); if (con!= null){ System.out.println("Connection created successfully"); }else{ System.out.println("Problem with creating connection"); } } catch (Exception e) { e.printStackTrace(System.out); } } public static void createData() { connectDatabase(); Connection con = null; Statement stmt = null; int result1 = 0; int result2 = 0; try { //Registering the HSQLDB JDBC driver Class.forName("org.hsqldb.jdbc.JDBCDriver"); con = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/testdb", "SA", ""); stmt = con.createStatement(); result1 = stmt.executeUpdate("CREATE TABLE MiniNet_people " + "(id INT NOT NULL, name VARCHAR(50) NOT NULL,age INT NOT NULL, " + "status VARCHAR(50) NOT NULL,PRIMARY KEY (id));"); result2 = stmt.executeUpdate("CREATE TABLE MiniNet_relation " + "(name VARCHAR(50) NOT NULL,name2 VARCHAR(50) NOT NULL, " + "relation VARCHAR(50) NOT NULL,PRIMARY KEY (name,name2,relation));"); } catch (Exception e) { e.printStackTrace(System.out); } } public static void insertData() { Connection con = null; createData(); Statement stmt = null; int result1 = 0; int result2 = 0; try { Class.forName("org.hsqldb.jdbc.JDBCDriver"); con = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/testdb", "SA", ""); stmt = con.createStatement(); result1 = stmt.executeUpdate("INSERT INTO MiniNet_people VALUES " + "(1001,'john nash',30,'Mathematician')," + "(1002,'eleanor stier',30,'Nurse')," + "(1003,'david stier',10,' ')," + "(1004,'alan turing',42,'Computer Scientist')," + "(1005,'joan clarke',37,'Cryptanalyst')," + "(1006,'paul jobs',44,'United States Coastguard')," + "(1007,'clara hagopian',42,'Armenian')," + "(1008,'steve jobs',13,'Future Innovator')"); result2 = stmt.executeUpdate("INSERT INTO MiniNet_relation VALUES " + "('david stier','john nash','parent')," + "('david stier','eleanor stier','parent')," + "('john nash','eleanor stier','couple')," + "('alan turing','joan clarke','couple')," + "('alan turing','john nash','colleague')," + "('paul jobs','clara hagopian','couple')," + "('paul jobs','steve jobs','child')," + "('steve jobs','clara hagopian','parent')," + "('paul jobs','john nash','friend')," + "('david stier','steve jobs','classmate')"); con.commit(); } catch (Exception e) { e.printStackTrace(System.out); } System.out.println(result1 + " rows effected"); System.out.println("Rows inserted successfully"); } public static void viewData() { Connection con = null; Statement stmt = null; ResultSet result1 = null; ResultSet result2 = null; String name=null; int age = 0; int id = 0; String status=null; String name2=null; String name3 = null; String relation=null; try { Class.forName("org.hsqldb.jdbc.JDBCDriver"); con = DriverManager.getConnection( "jdbc:hsqldb:hsql://localhost/testdb", "SA", ""); stmt = con.createStatement(); result1 = stmt.executeQuery("SELECT * FROM MiniNet_people"); result1 = stmt.executeQuery("SELECT * FROM MiniNet_relation"); while(result1.next()){ id = result1.getInt("id"); name = result1.getString("name"); age = result1.getInt("age"); status = result1.getString("status"); addPeopleData(id,name,age,status); } while(result2.next()){ name2 = result2.getString("name"); name3 = result2.getString("name2"); relation = result2.getString("relation"); addRelationData(name2,name3,relation); } } catch (Exception e) { e.printStackTrace(System.out); } } public static void addPeopleData(int id, String name, int age, String status) { Profile person = null; if(age>16) { person = new Adult(name, age, status); } else if(age<16 && age>2) { person = new Child(name,age,status, new ArrayList<String>()); } else if(age<2 && age>0) { person = new YoungChild(name,age,status,new ArrayList<String>()); } list.put(id, person); } public static void addRelationData(String name, String name2, String relation) throws NotToBeFriendsException, NoParentException, NotToBeChildException, NoAvailableException, NotToBeColleaguesException, NotToBeClassmatesException { Profile person1=null; Profile person2=null; for(int i: list.keySet()) { if((list.get(i).getName().contains(name))){ person1 = list.get(i); } if((list.get(i).getName().contains(name2))) { person2 = list.get(i); } } switch(relation) { case "friend": try { person1.addFriend(person2); System.out.println(person2.getName()+" added as a Friend"); person2.addFriend(person1); } catch(NotToBeFriendsException e) { System.err.println(e.getMessage()); throw new NotToBeFriendsException(e.getMessage()); } break; case "parent": try { person1.addParent(person2); System.out.println(person2.getName()+" added as a Parent"); person2.addChild(person1); } catch(NoParentException e) { System.err.println(e.getMessage()); throw new NoParentException(e.getMessage()); } break; case "child": try { person1.addChild(person2); System.out.println(person2.getName()+" added as a Child"); person2.addParent(person1); } catch(NotToBeChildException e) { System.err.println(e.getMessage()); throw new NotToBeChildException(e.getMessage()); } break; case "couple": try { person1.addCouple(person2); System.out.println(person2.getName()+" added as a Spouse"); person2.addCouple(person1); } catch(NoAvailableException e) { System.err.println(e.getMessage()); throw new NoAvailableException(e.getMessage()); } break; case "colleague": try { person1.addColleague(person2); System.out.println(person2.getName()+" added as a Colleague"); person2.addColleague(person1); } catch(NotToBeColleaguesException e) { System.err.println(e.getMessage()); throw new NotToBeColleaguesException(e.getMessage()); } break; case "classmate": try { person1.addClassmate(person2); System.out.println(person2.getName()+" added as a Classmate"); person2.addClassmate(person1); } catch(NotToBeClassmatesException e) { System.err.println(e.getMessage()); throw new NotToBeClassmatesException(e.getMessage()); } break; default: System.out.println("Invalid Relation Found !"); break; } } }
Python
UTF-8
793
2.96875
3
[]
no_license
import glob listText = [] def getTexts(inputUser) : #inputUser = input("Enter the name of the folder you want to search in: ") #print(inputUser) mypath = "DataSet/Train/" + inputUser + "/*.txt" #print(mypath) listText = glob.glob(mypath) count = 0 for text in listText : textSplit = text.split("/") listText[count] = textSplit[3] count += 1 return listText, inputUser def getTextsTest() : #inputUser = input("Enter the name of the folder you want to search in: ") #print(inputUser) mypath = "DataSet/Test/*.txt" #print(mypath) listText = glob.glob(mypath) count = 0 for text in listText : textSplit = text.split("/") listText[count] = textSplit[2] count += 1 return listText
Markdown
UTF-8
13,654
2.609375
3
[]
no_license
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' /> ##Overeenkomst inzake de uitwisseling van stagiaires tussen Nederland en Finland ####Accord relatif à l'échange de stagiaires entre les Pays-Bas et la Finlande Le Gouvernement de Sa Majesté la Reine des Pays-Bas et Le Gouvernement de la République de Finlande,désireux de favoriser l'échange de stagiaires entre leurs pays ont arrêté d'un commun accord, les dispositions suivantes: ### Article 1er Le présent accord s'applique aux „stagiaires”, c'est-à-dire aux ressortissants de l'un des deux pays qui se rendent dans l'autre pays pour une période délimitée, afin de perfectionner leurs connaissances linguistiques et professionnelles, tout en occupant un emploi.Les stagiaires seront autorisés à occuper un emploi dans les conditions fixées par les articles ci-après, sans que la situation du marché du travail dans leur profession puisse être prise en considération. ### Article 2 Les stagiaires peuvent être de l'un ou de l'autre sexe. En règle générale, ils ne doivent pas être âgés de plus de 30 ans. ### Article 3 L'autorisation est donnée en principe pour une année. Elle pourra exceptionnellement être prolongée pour six mois. ### Article 4 Le nombre de stagiaires pouvant être admis dans chacun des deux Etats ne devra pas dépasser 50 par an.Cette limite ne s'applique pas aux stagiaires de l'un des deux Etats résidant déjà sur le territoire de l'autre Etat. Elle pourra être atteinte quelle que soit la durée pour laquelle les autorisations délivrées au cours d'une année auront été accordées et pendant laquelle elles auront été utilisées.Si ce contingent de 50 autorisations n'était pas atteint au cours d'une année par les stagiaires de l'un des deux Etats, celui-ci ne pourrait pas réduire le nombre des autorisations données aux stagiaires de l'autre Etat, ni reporter sur l'année suivante le reliquat inutilisé de son contingent.Ce contingent de 50 stagiaires est valable pour l'année du 1er janvier au 31 décembre. Il pourra être modifié ultérieurement en vertu d'un accord qui devra intervenir, sur la proposition de l'un des deux Etats, le 1er décembre au plus tard pour l'année suivante. ### Article 5 Les stagiaires ne pourront être admis par les autorités compétentes que si les employeurs qui les occupent s'engagent, envers ces autorités, dès que ces stagiaires rendront des services normaux, à les rémunérer, là où il existe des dispositions réglementaires ou des conventions collectives, d'après les tarifs fixés par ces dispositions ou conventions, là où il n'en existe point, d'après les taux normaux et courants de la profession et de la région.Dans les autres cas, les employeurs devront s'engager à leur donner une rémunération correspondant à la valeur de leurs services et qui doit au moins leur permettre de subvenir à leurs besoins essentiels.Les stagiaires ne peuvent obtenir en Finlande et aux Pays-Bas un permis de travail que si les autorités compétentes sont convaincues par une enquête entreprise par elles-mêmes, que les conditions convenues entre les employeurs et les stagiaires et définies au paragraphe précédent seront respectées. ### Article 6 (a). Les stagiaires jouissent de l'égalité de traitement avec les ressortissants du pays du lieu de travail pour tout ce qui concerne l'application des lois, règlements et usages régissant la sécurité, l'hygiène et les conditions de travail. (b). Les stagiaires et leurs employeurs sont tenus de se conformer aux prescriptions en vigueur en matière de sécurité sociale. ### Article 7 Les stagiaires qui désireront bénéficier des dispositions du présent accord devront en faire la demande à l'autorité chargée, dans leur pays, de l'échange de stagiaires. Ils devront donner, dans leur demande, toutes les indications nécessaires et faire connaître notamment l'établissement dans lequel ils devront être employés. Ils devront en même temps produire les documents suivants: 1.l'engagement visé à l'article 5 du présent accord; 2.un certificat officiel de bonne vie et moeurs; 3.une déclaration aux termes de laquelle ils s'engagent à ne pas rester dans le pays où leur stage a été effectué dans le dessin d'y occuper un emploi.Il appartiendra à l'autorité mentionnée plus haut d'examiner s'il y a lieu, de transmettre la demande à l'autorité correspondante de l'autre État, en tenant compte du contingent annuel auquel elle a droit et de la transmettre, le cas échéant, aux autorités compétentes de l'autre Etat.Les autorités compétentes des deux Etats feront tout leur possible pour assurer l'instruction des demandes dans le plus court délai. ### Article 8 Les autorités compétentes feront tous leurs efforts pour que les décisions des autorités administratives concernant l'entrée et le séjour des stagiaires admis interviennent d'urgence. Elles s'efforceront également d'aplanir avec la plus grande rapidité les difficultés qui pourraient surgir à propos de l'entrée ou du séjour des stagiaires. ### Article 9 Chaque Gouvernement s'efforcera de faciliter le placement des stagiaires de l'autre Etat. ### Article 10 L'Office National du Travail aux Pays-Bas et le Ministère des Affaires Sociales en Finlande sont chargés de l'application du présent accord. ### Article 11 (a). Des arrangements entre les autorités compétentes fixeront, le cas échéant, les mesures nécessaires à l'application du présent accord. (b). Tout différend venant à s'élever concernant l'interprétation ou l'application du présent accord, sera résolu par voie de négociation directe. (c). Si ce différend ne peut être résolu dans un délai de trois mois à dater du début de la négociation, il sera soumis à l'arbitrage d'un organisme dont la composition sera déterminée d'un commun accord. La procédure à suivre sera établie dans les mêmes conditions. (d). La décision de l'organisme arbitral sera prise conformément à l'esprit du présent accord; elle sera obligatoire et sans appel. ### Article 12 Le présent accord entrera en vigueur à partir de la date de signature et restera en vigueur jusqu'au 31 décembre 1951.Il sera prorogé ensuite par tacite reconduction et chaque fois pour une nouvelle année, à moins qu'il ne soit dénoncé par l'une des parties contractantes, avant le 1er octobre pour la fin de l'année.Toutefois, en cas de dénonciation, les autorisations accordées en vertu du présent accord resteront valables pour la durée pour laquelle elles auront été accordées. EN FOI DE QUOI, les soussignés, dûment autorisés à cet effet, ont signé le présent accord.Fait à Helsinki, en deux exemplaires, en langue française, le 11 juillet 1951.A. J. TH. VAN DER VLUGT.ÅKE GARTZ. ####Overeenkomst inzake de uitwisseling van stagiaires tussen Nederland en Finland De Regering van Hare Majesteit de Koningin der Nederlanden en De Regering van de Republiek Finland,Verlangende de uitwisseling van stagiaires tussen haar landen te bevorderen, komen als volgt overeen: ### Artikel 1 Deze Overeenkomst is van toepassing op „stagiaires”, dat is op onderdanen van een van beide landen, die zich voor een bepaalde tijd naar het andere land begeven ten einde hun kennis te vervolmaken wat de taal of hun beroep betreft, terwijl zij een betrekking vervullen.Het is de stagiaires vergund een betrekking te vervullen overeenkomstig de voorwaarden bij de artikelen hieronder bepaald, zonder dat de toestand van de arbeidsmarkt in overweging zal worden genomen. ### Artikel 2 Stagiaires kunnen van het manlijk of van het vrouwelijk geslacht zijn. In het algemeen mogen zij niet ouder zijn dan 30 jaar. ### Artikel 3 In beginsel wordt de vergunning verleend voor de tijd van een jaar. Bij uitzondering kan deze termijn voor zes maanden worden verlengd. ### Artikel 4 Het aantal stagiaires die in elk van beide Staten kunnen worden toegelaten mag ten hoogste jaarlijks 50 bedragen.Deze grens geldt niet voor stagiaires van een van beide Staten, die reeds in het gebied van de andere Staat verblijven. Zij mag bereikt worden ongeacht de duur van de tijd voor welke vergunningen, in de loop van een jaar afgegeven, zijn verleend en gedurende welke van deze vergunningen gebruik is gemaakt.Indien het contingent van 50 stagiaires van een van beide Staten in de loop van een jaar niet wordt bereikt, mag deze het aantal vergunningen, aan de stagiaires van de andere Staat verleend, niet verminderen; evenmin mag hij het niet gebruikte restant van zijn contingent voegen bij dat van het volgend jaar.Het contingent van 50 stagiaires geldt voor het jaar lopend van 1 Januari tot 31 December. Het kan later worden gewijzigd krachtens een overeenkomst welke, op een daartoe door een van beide Staten gedaan voorstel, uiterlijk 1 December met betrekking tot het volgend jaar gesloten moet worden. ### Artikel 5 Stagiaires worden door de bevoegde instanties slechts toegelaten, indien de werkgevers die hen in dienstbetrekking nemen, zich tegenover deze instanties verplichten hun, zodra zij normale arbeid verrichten, een loon uit te betalen, hetzij overeenkomstig de bij collectieve arbeidsovereenkomsten vastgestelde tarieven, hetzij, bij gebreke van zodanige overeenkomsten, overeenkomstig de voor het beroep en in de streek normale gangbare loonschalen.In alle andere gevallen verbinden de werkgevers zich, hun een beloning te geven welke overeenkomt met hun diensten en welke hen tenminste in staat moet stellen te voorzien in hun noodzakelijke levensbehoeften.Stagiaires kunnen in Nederland en in Finland slechts een werkvergunning krijgen als de bevoegde instanties zich door een door haar zelf ingesteld onderzoek ervan overtuigd hebben, dat de tussen werkgevers en stagiaires overeengekomen en in het voorgaande lid vastgestelde voorwaarden worden nageleefd. ### Artikel 6 (a). Stagiaires genieten dezelfde behandeling als de onderdanen van het land, waar zij werken, met betrekking tot de toepassing van de wetten, reglementen en gebruiken inzake veiligheid, hygiëne en arbeidsvoorwaarden. (b). Zowel de stagiaires als hun werkgevers zijn verplicht de op het gebied van sociale zekerheid geldende wetten en voorschriften in acht te nemen. ### Artikel 7 Stagiaires, die gebruik wensen te maken van het bij deze overeenkomst bepaalde, moeten het verzoek daartoe richten tot de instantie welke, in hun land, belast is met de uitwisseling van stagiaires. Zij moeten in dit verzoek alle nodige aanwijzingen geven en in het bijzonder aangeven in welke inrichting zij wensen te werk gesteld te worden. Zij moeten tegelijk de volgende bescheiden overleggen: 1.het contract, bedoeld in artikel 5 van deze Overeenkomst; 2.een officieel bewijs van goed gedrag; 3.een verklaring waarbij zij zich verbinden om niet in het land waar hun leertijd is doorgebracht, te blijven met de bedoeling er een betrekking te vervullen.De bovenbedoelde instantie onderzoekt of er aanleiding is, de aanvraag aan de overeenkomstige instantie van de andere Staat te doen toekomen, met inachtneming van het jaarlijks contingent waarop zij recht heeft; in voorkomende gevallen geeft zij deze door aan de bevoegde instanties van de andere Staat.De bevoegde instanties van beide Staten zullen zich beijveren de aanvragen binnen de kortst mogelijke tijd te doen onderzoeken. ### Artikel 8 De bevoegde instanties zullen zich beijveren, de beslissingen van de administratieve instanties inzake binnenkomst en verblijf van de stagiaires met spoed te doen nemen.Zij zullen zich eveneens beijveren, met de meeste spoed alle moeilijkheden uit de weg te ruimen welke zich met betrekking tot het binnenkomen en het verblijf van de stagiaires kunnen voordoen. ### Artikel 9 Iedere Regering zal zich beijveren, de plaatsing van stagiaires van de andere Staat te bevorderen. ### Artikel 10 Het Rijksarbeidsbureau in Nederland en het Ministerie van Sociale Zaken in Finland zijn belast met de toepassing van deze Overeenkomst. ### Artikel 11 (a). De bevoegde instanties zullen in voorkomende gevallen door onderlinge regelingen de nodige maatregelen treffen voor de toepassing van deze Overeenkomst. (b). Elk geschil, dat zich mocht voordoen met betrekking tot de interpretatie of de toepassing van deze Overeenkomst, zal door onderhandelingen tot oplossing worden gebracht. (c). Indien het geschil niet binnen drie maanden na de aanvang van de onderhandelingen is bijgelegd, zal het worden onderworpen aan de scheidsrechterlijke uitspraak van een orgaan, waarvan de samenstelling in gemeen overleg zal worden vastgesteld. De te volgen procedure zal op dezelfde wijze worden vastgesteld. (d). De beslissing van het scheidsrechterlijk orgaan zal worden genomen in overeenstemming met de geest van deze Overeenkomst; zij is bindend en niet voor beroep vatbaar. ### Artikel 12 Deze Overeenkomst treedt in werking op de dag van ondertekening en blijft van kracht tot 31 December 1951.Zij zal stilzwijgend worden verlengd, telkens voor de tijd van een jaar, tenzij zij door een van de Overeenkomstsluitende Partijen wordt opgezegd voor de 1ste October tegen het einde van dat jaar.Ingeval van opzegging blijven desniettemin de vergunningen, welke krachtens deze Overeenkomst zijn verleend, geldig gedurende de tijd waarvoor zij zijn verleend. TEN BLIJKE WAARVAN de ondergetekenden, te dien einde behoorlijk gemachtigd, deze Overeenkomst hebben ondertekend.Gedaan te Helsinki, de 11de Juli 1951,in tweevoud, in de Franse taal.A. J. TH. VAN DER VLUGT.ÅKE GARTZ.
Shell
UTF-8
473
3.4375
3
[ "MIT" ]
permissive
#!/bin/bash # # This example shows how to store and read a value from a file. # # * examples/02_base.rb reads a file twice. Once where the file name # is known, and once where it is unknown until set via an # environment variable. examples="$(cd "$(dirname "$BASH_SOURCE")" && pwd)" # Alter a value via the system environment. export EXAMPLES_FILE_NAME='02_value' bundle exec levels \ --output json \ --level "Base" \ --system \ $examples/02_base.rb
Java
UTF-8
2,143
2.171875
2
[]
no_license
// PROJECT : RemoteQuartzScheduler // CLASS : JobDatas.java // // ************************************************************************************************ // // This copy of the Source Code is a property of Ravindu Eranga Abayawardena. No // part of this file may be reproduced or distributed in any form or by any // means without the written approval of Ravindu Eranga Abayawardena. // // ************************************************************************************************* // // REVISIONS: // Author : Ravindu Eranga Abayawardena // Date : May 19, 2015 // Version : version 1.0 // // ************************************************************************************************* package com.rqs.model; /** * * @author Ravindu Eranga Abaywardena */ public class EmailJobData { /* * Email Address of sender */ String to; /* * Email Address of receiver */ String from; /* * Host */ String host; /* * Subject of the email */ String subject; /* * Content of the email */ String body; /** * @return the to */ public String getTo() { return to; } /** * @param to the to to set */ public void setTo(String to) { this.to = to; } /** * @return the from */ public String getFrom() { return from; } /** * @param from the from to set */ public void setFrom(String from) { this.from = from; } /** * @return the host */ public String getHost() { return host; } /** * @param host the host to set */ public void setHost(String host) { this.host = host; } /** * @return the subject */ public String getSubject() { return subject; } /** * @param subject the subject to set */ public void setSubject(String subject) { this.subject = subject; } /** * @return the body */ public String getBody() { return body; } /** * @param body the body to set */ public void setBody(String body) { this.body = body; } }
Java
UTF-8
204
2.078125
2
[]
no_license
package org.sheehan.algorithm.thread; import org.junit.Test; public class ThreadLocalExampleTest { @Test public void testMain() throws Exception { ThreadLocalExample.main(null); } }
Rust
UTF-8
1,943
3.015625
3
[ "MIT", "Apache-2.0" ]
permissive
use std::collections::HashMap; use std::fs::{read_to_string, write}; use serde_derive::{Deserialize, Serialize}; use crate::config::stats_path; // solitaire statistics #[derive(Clone, Serialize, Deserialize)] pub(crate) struct GameStat { pub(crate) played: u64, pub(crate) won: u64, } impl Default for GameStat { fn default() -> GameStat { GameStat { played: 0, won: 0 } } } // all solitaires statistics #[derive(Serialize, Deserialize)] pub(crate) struct Stats { pub(crate) games: HashMap<String, GameStat>, } impl Stats { fn new() -> Self { Stats { games: HashMap::new() } } pub(crate) fn load() -> Self { let path = stats_path(); if !path.exists() { return Stats::new(); } let data = match read_to_string(path) { Ok(s) => s, Err(e) => { eprintln!("Failed to load statistics: {:?}", e); return Stats::new(); } }; let stats: Stats = match toml::from_str(&data) { Ok(s) => s, Err(e) => { eprintln!("Failed to read TOML statistics: {:?}", e); Stats::new() } }; stats } pub(crate) fn update_stat(&mut self, name: &str, won: bool) { let stat = self.games.entry(name.to_string()).or_insert_with(Default::default); stat.played += 1; if won { stat.won += 1; } } pub(crate) fn game_stat(&self, name: &str) -> GameStat { match self.games.get(name) { None => GameStat::default(), Some(st) => st.clone(), } } pub(crate) fn save(&self) { let tml = toml::to_string(&self).expect("failed to serialize statistics"); let path = stats_path(); if let Err(e) = write(path, tml) { eprintln!("Failed to save statistics: {:?}", e); } } }
JavaScript
UTF-8
1,456
4.1875
4
[]
no_license
"use strict"; var user = { name: "Cristian", age: 17, adress: { city: "Joinville", state: "SC" } }; /** * A primeira e mais fácil forma de extrair algum dado do objeto declarado * anteriormente, é: * * The first way to extract some object values is: */ // const name = user.name; // const age = user.age; // const city = user.adress.city; // console.log(name, age, city); /** * Porém, com isso gasta-se mais espaço e o processo se torna mais cansativo, * tendo assim outra maneira de realizar este processo, usando assim a * "desestruturação", por exemplo: * * But, with "desestruturation", all the process becomes more easy. * For example: */ /** * Já que "city" é uma propriedade de endereço, a instanciação tem que ser * assim, como se fosse um objeto dentro do outro. Todo esse esquema funciona * mais ou menos como o "extract()" lá do PHP. * * Because "city" is a property of adress object, the instantiation must to * happen like the example, as an object inside another one. All this scheme * works more or less like PHP "extract()". */ var name = user.name, age = user.age, city = user.adress.city; console.log(name, age, city); /** * É possível também usar esse processo no parâmetro de uma função: * * It's also possible use this process in the function parameter: */ function getNome(_ref) { var name = _ref.name; return name; } console.log(getNome(user));
Java
UTF-8
1,419
2.421875
2
[]
no_license
package action; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dao.EntidadeDAO; import entidades.Entidade; import entidades.Usuario; public class CadastrarEntidadeAction implements ActionProcess { @Override public void process(HttpServletRequest request, HttpServletResponse response) throws IOException { // TODO Auto-generated method stub try{ Integer resp; Usuario u = (Usuario) request.getSession().getAttribute("usuario"); Entidade e = new Entidade(); EntidadeDAO eDAO = new EntidadeDAO(u.getUsu_ds_subdominio()); e.setEnt_nm_entidade(request.getParameter("ENT_NM_ENTIDADE")); e.setEnt_cd_usuario(u.getUsu_cd_usuario()); resp = eDAO.inserirRegistro(e); if (resp == null){ request.getSession().setAttribute("msg_erro", "Erro ao cadastrar entidade... entre em contato com o suporte"); response.sendRedirect("processoErroMsg.jsp"); }else{ request.getSession().setAttribute("msg_cadastro", "Cadastro efetuado com sucesso!"); CarregaCadastroEntidadeAction carregaCadastroEndidade = new CarregaCadastroEntidadeAction(); carregaCadastroEndidade.process(request, response); }; }catch(Exception e){ request.getSession().setAttribute("msg_erro", "Erro ao cadastrar entidade... entre em contato com o suporte"); response.sendRedirect("processoErroMsg.jsp"); } } }
Java
UTF-8
3,730
2.9375
3
[]
no_license
package indi.ycl.util; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.RandomAccessFile; import java.util.ArrayList; public class FileOperation { public static boolean createFile(File fileName) throws Exception { boolean flag = false; try { if (!fileName.exists()) { fileName.createNewFile(); flag = true; } } catch (Exception e) { e.printStackTrace(); } return flag; } /** * ��TXT�ļ����� * * @param fileName * @return */ public static String readTxtFile(File fileName) throws Exception { String result = null; FileReader fileReader = null; BufferedReader bufferedReader = null; try { fileReader = new FileReader(fileName); bufferedReader = new BufferedReader(fileReader); try { String read = null; while ((read = bufferedReader.readLine()) != null) { result = result + read + "\r\n"; } } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } finally { if (bufferedReader != null) { bufferedReader.close(); } if (fileReader != null) { fileReader.close(); } } return result; } public static boolean writeTxtFile(String content, File fileName) throws Exception { RandomAccessFile mm = null; boolean flag = false; FileOutputStream o = null; try { o = new FileOutputStream(fileName); o.write(content.getBytes("UTF-8")); o.write("\r\n".getBytes()); o.close(); // mm=new RandomAccessFile(fileName,"rw"); // mm.writeBytes(content); flag = true; } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } finally { if (mm != null) { mm.close(); } } return flag; } public static void contentToTxt(String filePath, String content) { String str = new String(); // ԭ��txt���� String s1 = new String();// ���ݸ��� try { File f = new File(filePath); if (f.exists()) { System.out.print("�ļ�����"); } else { System.out.print("�ļ�������"); f.createNewFile();// �������򴴽� } BufferedReader input = new BufferedReader(new FileReader(f)); while ((str = input.readLine()) != null) { s1 += str + "\n"; } System.out.println(s1); input.close(); s1 += content; BufferedWriter output = new BufferedWriter(new FileWriter(f)); output.write(s1); output.close(); } catch (Exception e) { e.printStackTrace(); } } public static ArrayList<String> readFileByLine(File filepath){ ArrayList<String> content=new ArrayList<>(); try { //����1 FileInputStream file = new FileInputStream(filepath); InputStreamReader inputFileReader = new InputStreamReader(file, "utf-8"); BufferedReader reader = new BufferedReader(inputFileReader); String tempString; // һ�ζ���һ�У�ֱ������nullΪ�ļ����� while ((tempString = reader.readLine()) != null) { content.add(tempString); // System.out.println(tempString); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return content; } public static void main(String[] args){ File tmp=new File("D:/luceneSpace/file/1.txt"); FileOperation.readFileByLine(tmp); } }
C++
UTF-8
575
3.21875
3
[]
no_license
// // Created by 郭磊 on 2021/1/13. // #include <iostream> #include "Person.h" using namespace std; int main1(int argc, char *argv[]) { Person p1(28, 98); Person p2(27, 56); Person p3 = operator+(p1, p2); p3 = p1 + p2; cout << "person:age:" << p3.getAge() << ",score:" << p3.getScore() << endl; } // 全局函数运算符重载需要将成员函数注释掉,否则会报错 Person operator+(Person &p1, Person &p2) { Person temp; temp.setAge(p1.getAge() + p2.getAge()); temp.setScore(p1.getScore() + p2.getScore()); return temp; }
Markdown
UTF-8
806
2.671875
3
[]
no_license
--- ID: 285 post_title: Jim and the Orders, JavaScript Solution author: slbarnes post_excerpt: "" layout: page permalink: > http://localhost/index.php/jim-and-the-orders/jim-and-the-orders-javascript/ published: true post_date: 2018-09-04 08:42:32 --- ### Functions: ##### jimOrders I create an array servings and calculate the serving time ( *serveTime*) for each customer. For each customer in the orders array, a servings array entry is created with with customer number and the *serveTime*, resulting in a new two dimensional array. I then sort this array by serving time. Note the use of a comparitor in the sort, necessary for correct sorting of numbers in JavaScript. The resulting new order is used to push customer numbers into an array of customer numbers in the required order (*returnArr*).
Java
UTF-8
1,101
2.296875
2
[]
no_license
package com.udacity.gradle.builditbigger; import android.content.Context; import android.support.v4.util.Pair; import android.test.AndroidTestCase; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; public class EndpointAsyncTaskTest extends AndroidTestCase { CountDownLatch signal; String mResult; @Override protected void setUp() throws Exception { super.setUp(); signal = new CountDownLatch(1); } public void testEndpointTask() throws Throwable { EndpointsAsyncTask endpointsAsyncTask = new EndpointsAsyncTask() { @Override public void onPostExecute(String result) { mResult = result; signal.countDown(); } }; endpointsAsyncTask.execute(new Pair<Context, String>(getContext(), "")); signal.await(30, TimeUnit.SECONDS); assertNotNull(mResult); assertFalse(mResult.isEmpty()); } @Override protected void tearDown() throws Exception { super.tearDown(); signal.countDown(); } }
Python
UTF-8
691
4.15625
4
[ "Apache-2.0" ]
permissive
""" 斐波拉契问题:F(0)=0,F(1)=1,F(n) = F(n-1)+ F(n-2) (n>2,n∈N*) 一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶。求该青蛙跳上一个n级台阶总共有多少种跳法。 """ def moeo(func): cache = {} def wrap(*args): if args not in cache: cache[args] = func(*args) return cache[args] return wrap @moeo def fib(n): if n <= 0: return 0 elif n == 1: return 1 else: return fib(n-1) + fib(n-2) print(fib(10)) # fib2 = lambda n: n if n <= 2 else fib(n-1) + fib(n-2) def fib2(n): a, b = 0, 1 for _ in range(n): a, b = b, a + b return b print(fib2(10))
Java
UTF-8
931
2.734375
3
[]
no_license
package org.rendersnake.jquery; public class JQueryCanvasFactory { /** * Create a new JQueryCanvas to compose expressions. * @param selector , A string containing a selector expression * @see {@link http://api.jquery.com/jQuery/} * @return a new JQueryCanvas */ public static JQueryCanvas $(String selector) { return new JQueryCanvas().jQuery(selector); } /** * Create a new JQueryCanvas to compose expressions. * @param selector , A string containing a selector expression * @param context , A DOM Element, Document, or jQuery to use as context * @see {@link http://api.jquery.com/jQuery/} * @return a new JQueryCanvas */ public static JQueryCanvas $(String selector, String context) { return new JQueryCanvas().jQuery(selector,context); } public static JQueryCanvas $() { return new JQueryCanvas().jQuery(); } }
Python
UTF-8
1,283
3.046875
3
[]
no_license
from colorsys import rgb_to_hsv from PIL import Image, ImageDraw def rgb2int(r, g, b): return int('{:02x}{:02x}{:02x}'.format(r, g, b), 16) def get_first_not_white_y(x, y, pixels, w, h, white_value): # expected 2314 if y < h: while rgb2int(*pixels[x + y * w]) > white_value: y += 1 if y >= h: return -1 return y def get_next_white_y(x, y, pixels, w, h, white_value): y += 1 if y < h: while rgb2int(*pixels[x + y * w]) < white_value: y += 1 if y >= h: return h - 1 return y - 1 def get_first_not_black_y(x, y, pixels, w, h, black_value): if y < h: while rgb2int(*pixels[x + y * w]) < black_value: y += 1 if y >= h: return -1 return y def get_next_black_y(x, y, pixels, w, h, black_value): y += 1 if y < h: while rgb2int(*pixels[x + y * w]) > black_value: y += 1 if y >= h: return -1 return y - 1 white_value = 0x39A2C0 black_value = 0xbdc00 img = Image.open('fuzzed.jpg') pixels = list(img.getdata()) w, h = img.size for i in range(h): print(get_next_black_y(i, 0, pixels, w, h, black_value)) # expected 2314 # -5144191
Python
UTF-8
2,429
3.09375
3
[]
no_license
#----------- ARCHIVOS TXT ----------------- print("\n***CLAVES***") claves = open("claves.txt", "rt", encoding="utf8") datos_claves = claves.read() print(datos_claves) print("\n***CoDIGOS***") codigo = open("codigo.txt", "rt", encoding="utf8") datos_codigo = codigo.read() print(datos_codigo) print("\n***NOMBRES***") nombre = open("nombre.txt", "rt", encoding="utf8") datos_nombre = nombre.read() print(datos_nombre) print("\n***PRECIOS***") precio = open("precio.txt", "rt", encoding="utf8") datos_precio = precio.read() print(datos_precio) print("\n***USUARIOS***") usuarios = open("usuarios.txt", "rt", encoding="utf8") datos_usuarios = usuarios.read() print(datos_usuarios) #-----------CREACIÓN DE BD ----------------- import sqlite3 conexion = sqlite3.connect("ventas.db") conexion.close() #-----------CREACIÓN DE TABLAS EN BD ----------------- conexion = sqlite3.connect("ventas.db") cursor = conexion.cursor() tabla_usuario = ("""CREATE TABLE USUARIO( IDUSUARIO INTEGER PRIMARY KEY AUTOINCREMENT, USUARIO TEXT UNIQUE, CLAVE TEXT)""") tabla_producto = ("""CREATE TABLE PRODUCTO( IDPRODUCTO INTEGER PRIMARY KEY AUTOINCREMENT, NOMBRE TEXT, CODIGO TEXT, PRECIO NUMBER )""") cursor = conexion.cursor() cursor.execute(tabla_usuario) cursor.execute(tabla_producto) conexion.close() #-----------LEER E INSERTAR TABLA 01 ----------------- conexion = sqlite3.connect("ventas.db") cursor = conexion.cursor() lista_usuario = datos_usuarios.split('\n') lista_clave = datos_claves.split('\n') for indice,valor in enumerate(zip(lista_usuario,lista_clave)): print(valor[0],valor[1]) cursor.execute("INSERT INTO USUARIO(USUARIO,CLAVE)VALUES('"+valor[0]+"','"+valor[1]+"')") #CONFIRMAR CAMBIOS CON COMMIT conexion.commit() conexion.close() #-----------LEER E INSERTAR TABLA 02 ----------------- conexion = sqlite3.connect("ventas.db") cursor = conexion.cursor() lista_nombre = datos_nombre.split('\n') lista_codigo = datos_codigo.split('\n') lista_precio = datos_precio.split('\n') for indice,valor in enumerate(zip(lista_nombre,lista_codigo,lista_precio)): print(valor[0],valor[1]) cursor.execute("INSERT INTO PRODUCTO(NOMBRE,CODIGO,PRECIO)VALUES('"+valor[0]+"','"+valor[1]+"','"+valor[2]+"')") conexion.commit() conexion.close()
C++
UTF-8
937
2.515625
3
[]
no_license
// In the name of **** God **** /* Copyright (C) JadedBeast Morocco created : 03/11/2019 */ #include <bits/stdc++.h> using namespace std; #define ll long long const ll mod= 1e9+7; const int MAX=1e5+5; #define debug(x) cout<<"Mayday Mayday : "<<x<<endl; inline void JadedBeast() { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); } int main() { JadedBeast(); int a ,b,x; cin >> a >> b ; if(a==b){ cout <<"infinity"; return 0; } x=a-b; int counter=0,rcn=sqrt(x); for(int i=1;i<=rcn;i++) if(x%i==0){ if(x/i==i && i>b) counter++; else{ if((x/i)>b) counter++; if(i>b) counter++; } } cout <<counter; return 0; }
PHP
UTF-8
2,194
2.78125
3
[ "MIT" ]
permissive
<?php namespace MultilineQM\Log; use MultilineQM\Config\LogConfig; use MultilineQM\Config\ProcessConfig; use MultilineQM\Log\Driver\LogDriverInterface; use MultilineQM\OutPut\OutPut; use MultilineQM\Serialize\JsonSerialize; /** * Log type * @method static debug(string $message, array $context = []); debugging information * @method static info(string $message, array $context = []); information * @method static notice(string $message, array $context = []); notice * @method static warning(string $message, array $context = []); warning * @method static error(string $message, array $context = []); general error * @method static critical(string $message, array $context = []); dangerous error * @method static alert(string $message, array $context = []); alert error * @method static emergency(string $message, array $context = []); emergency error * * @see LogDriverInterface * @package MultilineQM\Log */ class Log { private static $driver; private static $levelOut=[ 'debug'=>'info', 'info'=>'normal', 'notice'=>'warning', 'warning'=>'warning', 'error'=>'error', 'critical'=>'error', 'alert'=>'error', 'emergency'=>'error' ]; /** * Get the log driver * @return LogDriverInterface */ public static function getDriver(): LogDriverInterface { if(!self::$driver){ self::$driver = LogConfig::driver(); } return self::$driver; } public static function __callStatic($name, $arguments) { $arguments[0] ='['.ProcessConfig::queue().':'.ProcessConfig::getType().':'.getmypid().']'.$arguments[0]; if(call_user_func_array([self::getDriver(),$name],$arguments) && !ProcessConfig::daemon()){ //If the record is successful and not running in the background, the corresponding information will be printed to the screen OutPut::{self::$levelOut[$name]}( (new \DateTimeImmutable())->format('Y-m-d\TH:i:s.v') ."【{$name}】".$arguments[0] .(!empty($arguments[1])?JsonSerialize::serialize($arguments[1]):'') ."\n"); } } }
Java
UTF-8
35,550
2.6875
3
[ "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 courseenrollmentsystem; import java.io.FileOutputStream; // importing java libraries import java.io.OutputStream; // importing java libraries import java.sql.Connection; // importing java libraries import java.sql.DriverManager; // importing java libraries import java.sql.PreparedStatement; // importing java libraries import java.sql.ResultSet; // importing java libraries import java.util.ArrayList; // importing java libraries import java.util.Calendar; // importing java libraries /** * * @author Sono */ public class StudentDBOperations { String url = "jdbc:mysql://localhost:3306/nsbm_database"; // url to connect database String username = "root"; // username to access database String password = ""; // password to access database Connection con = null; // connection variable to create connection PreparedStatement pst = null; // variable to store preapared query /** * method to add undergraduate student * */ boolean addUndergraduate(Undergraduate und) { try { con = (Connection) DriverManager.getConnection(url, username, password); // trying to connect with the database String query = "INSERT INTO undergraduate_student VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"; // sql query to access mydql String queryEx = "INSERT INTO students VALUES (?,?,?)"; // query two pst = (PreparedStatement) con.prepareStatement(query); //make query as a statement PreparedStatement pstEx = con.prepareStatement(queryEx); pst.setString(1, und.getRegNum()); // configer frontend data with the query statement pst.setString(2, und.getFullName()); // configer frontend data with the query statement pst.setString(3, und.getNic()); // configer frontend data with the query statement pst.setString(4, und.getAddress()); // configer frontend data with the query statement pst.setInt(5, und.getPhoneNumber()); // configer frontend data with the query statement pst.setString(6, und.getDob()); // configer frontend data with the query statement pst.setString(7, und.getEmail()); // configer frontend data with the query statement pst.setString(8, und.getPassword()); // configer frontend data with the query statement pst.setInt(9, und.getIndexNumber()); // configer frontend data with the query statement pst.setString(10, und.getStream()); // configer frontend data with the query statement pst.setString(11, und.getStream()); // configer frontend data with the query statement pst.setInt(12, und.getIslandRank()); // configer frontend data with the query statement pst.setString(13, und.getFacultyName()); // configer frontend data with the query statement pstEx.setString(1, und.getRegNum()); pstEx.setString(2, und.getFacultyName()); pstEx.setString(3, und.getEmail()); pst.executeUpdate(); //execute the query and insert the data into the database pstEx.executeUpdate(); } catch (Exception e) { System.out.println(e); } finally { try { if (pst != null) { pst.close(); } if (con != null) { con.close(); } } catch (Exception e) { } } return true; } /** * method to add postgraduate student * */ boolean addPostgrasuate(Postgraduate pgs) { try { con = (Connection) DriverManager.getConnection(url, username, password); // trying to connect with the database String query = "INSERT INTO postgraduate_student VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"; // sql query to access mydql String queryEx = "INSERT INTO students VALUES (?,?,?)"; pst = (PreparedStatement) con.prepareStatement(query); //make the query as a statement PreparedStatement pstEx = con.prepareStatement(queryEx); pst.setString(1, pgs.getRegNum()); // configer frontend data with the query statement pst.setString(2, pgs.getFullName()); // configer frontend data with the query statement pst.setString(3, pgs.getNic()); // configer frontend data with the query statement pst.setString(4, pgs.getAddress()); // configer frontend data with the query statement pst.setInt(5, pgs.getPhoneNumber()); // configer frontend data with the query statement pst.setString(6, pgs.getDob()); // configer frontend data with the query statement pst.setString(7, pgs.getEmail()); // configer frontend data with the query statement pst.setString(8, pgs.getPassword()); // configer frontend data with the query statement pst.setString(9, pgs.getInstitute()); // configer frontend data with the query statement pst.setInt(10, pgs.getYoc()); // configer frontend data with the query statement pst.setString(11, pgs.getQualification()); // configer frontend data with the query statement pst.setString(12, pgs.getFacultyName()); // configer frontend data with the query statement pst.setString(13, pgs.getDegreeType()); // configer frontend data with the query statement pstEx.setString(1, pgs.getRegNum()); pstEx.setString(2, pgs.getFacultyName()); pstEx.setString(3, pgs.getEmail()); pst.executeUpdate(); // execute the query pstEx.executeUpdate(); } catch (Exception e) { } return true; } /** * method to get assignment details * */ ArrayList<Assignment> getAssignmentList(String facultyName, String year) { ArrayList<Assignment> lst = new ArrayList<Assignment>(); try { con = (Connection) DriverManager.getConnection(url, username, password); String query = "SELECT * FROM assignments WHERE subject_name IN (SELECT name FROM subjects WHERE course ='" + facultyName + "' AND yos = '" + year + "')"; pst = (PreparedStatement) con.prepareStatement(query); ResultSet rs = pst.executeQuery(); while (rs.next()) { Assignment asg = new Assignment(); asg.setAssignmentID(rs.getInt(1)); asg.setSubjetcName(rs.getString(2)); asg.setDate(rs.getString(3)); asg.setPosterID(rs.getString(4)); asg.setPlace(rs.getString(5)); lst.add(asg); } return lst; } catch (Exception e) { System.out.println(e); return null; } finally { try { if (con != null) { con.close(); } if (pst != null) { pst.close(); } } catch (Exception e) { } } } /** * method to get lab session details * */ ArrayList<LabSession> getLabSessionDetails(String facultyName, String year) { ArrayList<LabSession> lbSessions = new ArrayList<LabSession>(); try { con = (Connection) DriverManager.getConnection(url, username, password); String query = "SELECT * FROM lab_sessions WHERE subject_name IN (SELECT name FROM subjects WHERE course ='" + facultyName + "' AND yos = '" + year + "')"; pst = (PreparedStatement) con.prepareStatement(query); ResultSet rs = pst.executeQuery(); while (rs.next()) { LabSession lbs = new LabSession(); lbs.setSubjectName(rs.getString(1)); lbs.setPlace(rs.getString(2)); lbs.setDate(rs.getString(3)); lbs.setPosterID(rs.getString(4)); lbSessions.add(lbs); } return lbSessions; } catch (Exception e) { return null; } finally { try { if (con != null) { con.close(); } if (pst != null) { pst.close(); } } catch (Exception e) { } } } /** * method to insert semester details * */ boolean insertSemesterSubjects(String[] subjects, String regNumber, String yos) { try { con = (Connection) DriverManager.getConnection(url, username, password); String query1 = "INSERT INTO semester_1_subjects VALUES (?,?,?,?,?,?,?)"; String query2 = "INSERT INTO semester_2_subjects VALUES (?,?,?,?,?,?,?)"; PreparedStatement pst2 = (PreparedStatement) con.prepareStatement(query2); pst = (PreparedStatement) con.prepareStatement(query1); pst.setString(1, regNumber); pst.setInt(2, 1); pst.setString(3, subjects[0]); pst.setString(4, subjects[1]); pst.setString(5, subjects[2]); pst.setString(6, subjects[3]); pst.setString(7, yos); pst2.setString(1, regNumber); pst2.setInt(2, 2); pst2.setString(3, subjects[4]); pst2.setString(4, subjects[5]); pst2.setString(5, subjects[6]); pst2.setString(6, subjects[7]); pst2.setString(7, yos); pst.executeUpdate(); pst2.executeUpdate(); return true; } catch (Exception e) { System.out.println(e); return false; } finally { try { if (con != null) { con.close(); } if (pst != null) { pst.close(); } } catch (Exception e) { } } } /** * method to get subject details * */ ArrayList<Subject> getSubjectDetails(String regNum, String facultyName, String year) { ArrayList<Subject> sbjList = new ArrayList<Subject>(); try { con = (Connection) DriverManager.getConnection(url, username, password); String query = ""; if (regNum.charAt(1) == 'U') { query = "SELECT * FROM subjects WHERE course ='" + facultyName + "' AND yos = '" + year + "' AND degree_type='BSc'"; } else { query = "SELECT * FROM subjects WHERE course ='" + facultyName + "' AND yos = '" + year + "' AND degree_type='Msc'"; } pst = (PreparedStatement) con.prepareStatement(query); ResultSet rs = pst.executeQuery(); while (rs.next()) { Subject sbj = new Subject(); sbj.setSubCode(rs.getString(1)); sbj.setName(rs.getString(2)); sbj.setSemester(rs.getInt(3)); sbj.setCredits(rs.getInt(4)); sbj.setCourseFee(rs.getInt(6)); sbj.setCompulsoraTag(rs.getString(7)); sbj.setYear(rs.getString(8)); sbjList.add(sbj); } return sbjList; } catch (Exception e) { System.out.println(e); return null; } finally { try { if (con != null) { con.close(); } if (pst != null) { pst.close(); } } catch (Exception e) { } } } /** * method to authenticate undergraduate login * */ boolean undergraduateStudentVerification(Undergraduate und) { try { con = (Connection) DriverManager.getConnection(url, username, password); String query = "SELECT reg_number,password FROM undergraduate_student"; pst = (PreparedStatement) con.prepareStatement(query); ResultSet rs = pst.executeQuery(); String tempPasswordHolder = ""; while (rs.next()) { if (rs.getString(1).equals(und.getRegNum())) { tempPasswordHolder = rs.getString(2); } } if (tempPasswordHolder.equals(und.getPassword())) { return true; } else { return false; } } catch (Exception e) { return false; } finally { try { if (con != null) { con.close(); } if (pst != null) { pst.close(); } } catch (Exception e) { } } } /** * method to authenticate postgraduate login * */ boolean postgraduateStudentVerification(Postgraduate pgs) { try { con = (Connection) DriverManager.getConnection(url, username, password); String query = "SELECT reg_number,password FROM postgraduate_student"; pst = (PreparedStatement) con.prepareStatement(query); ResultSet rs = pst.executeQuery(); String tempPasswordHolder = ""; while (rs.next()) { if (rs.getString(1).equals(pgs.getRegNum())) { tempPasswordHolder = rs.getString(2); } } if (tempPasswordHolder.equals(pgs.getPassword())) { return true; } else { return false; } } catch (Exception e) { return false; } finally { try { if (con != null) { con.close(); } if (pst != null) { pst.close(); } } catch (Exception e) { } } } /** * method to get payment details * */ ArrayList<Payment> getPaymentDetails(String regNumber) { ArrayList<Payment> plst = new ArrayList<>(); try { con = (Connection) DriverManager.getConnection(url, username, password); String query = "SELECT * FROM payments WHERE reg_number='" + regNumber + "'"; pst = (PreparedStatement) con.prepareStatement(query); ResultSet rs = pst.executeQuery(); while (rs.next()) { Payment pay = new Payment(); pay.setPayID(rs.getInt(1)); pay.setAmount(rs.getString(2)); pay.setSemester(rs.getInt(3)); pay.setCourse(rs.getString(4)); pay.setRegNumber(regNumber); plst.add(pay); } return plst; } catch (Exception e) { return null; } finally { try { if (con != null) { con.close(); } if (pst != null) { pst.close(); } } catch (Exception e) { } } } /** * method to insert payment details * */ boolean insertPayments(Payment pay) { try { con = (Connection) DriverManager.getConnection(url, username, password); String query = "INSERT INTO payments VALUES (?,?,?,?,?,?)"; pst = (PreparedStatement) con.prepareStatement(query); pst.setInt(1, pay.getPayID()); pst.setString(2, pay.getAmount()); pst.setInt(3, pay.getSemester()); pst.setString(4, pay.getCourse()); pst.setString(5, pay.getRegNumber()); pst.setString(6, pay.getYear()); pst.executeUpdate(); return true; } catch (Exception e) { System.out.println(e); return false; } finally { try { if (con != null) { con.close(); } if (pst != null) { pst.close(); } } catch (Exception e) { } } } /** * method to get first semester payment details * */ int getFirstSemesterAmountToPay(String regNumber, String yos) { try { int total = 0; con = (Connection) DriverManager.getConnection(url, username, password); String query1 = "SELECT course_fee FROM subjects WHERE name IN (SELECT first FROM semester_1_subjects WHERE reg_number ='" + regNumber + "' AND yos = '" + yos + "' AND semester='1')"; String query2 = "SELECT course_fee FROM subjects WHERE name IN (SELECT second FROM semester_1_subjects WHERE reg_number ='" + regNumber + "' AND yos = '" + yos + "' AND semester='1')"; String query3 = "SELECT course_fee FROM subjects WHERE name IN (SELECT third FROM semester_1_subjects WHERE reg_number ='" + regNumber + "' AND yos = '" + yos + "' AND semester='1')"; String query4 = "SELECT course_fee FROM subjects WHERE name IN (SELECT fourth FROM semester_1_subjects WHERE reg_number ='" + regNumber + "' AND yos = '" + yos + "' AND semester='1')"; pst = (PreparedStatement) con.prepareStatement(query1); PreparedStatement pst2 = (PreparedStatement) con.prepareStatement(query2); PreparedStatement pst3 = (PreparedStatement) con.prepareStatement(query3); PreparedStatement pst4 = (PreparedStatement) con.prepareStatement(query4); ResultSet rs1 = pst.executeQuery(); rs1.next(); ResultSet rs2 = pst2.executeQuery(); rs2.next(); ResultSet rs3 = pst3.executeQuery(); rs3.next(); ResultSet rs4 = pst4.executeQuery(); rs4.next(); total = rs1.getInt(1) + rs2.getInt(1) + rs3.getInt(1) + rs4.getInt(1); return total; } catch (Exception e) { System.out.println(e); return 0; } finally { try { if (con != null) { con.close(); } if (pst != null) { pst.close(); } } catch (Exception e) { } } } /** * method to get second semester payment details * */ int getSecondSemesterAmountToPay(String regNumber, String yos) { try { int total = 0; con = (Connection) DriverManager.getConnection(url, username, password); String query1 = "SELECT course_fee FROM subjects WHERE name IN (SELECT first FROM semester_2_subjects WHERE reg_number ='" + regNumber + "' AND yos = '" + yos + "' AND semester='2')"; String query2 = "SELECT course_fee FROM subjects WHERE name IN (SELECT second FROM semester_2_subjects WHERE reg_number ='" + regNumber + "' AND yos = '" + yos + "' AND semester='2')"; String query3 = "SELECT course_fee FROM subjects WHERE name IN (SELECT third FROM semester_2_subjects WHERE reg_number ='" + regNumber + "' AND yos = '" + yos + "' AND semester='2')"; String query4 = "SELECT course_fee FROM subjects WHERE name IN (SELECT fourth FROM semester_2_subjects WHERE reg_number ='" + regNumber + "' AND yos = '" + yos + "' AND semester='2')"; pst = (PreparedStatement) con.prepareStatement(query1); PreparedStatement pst2 = (PreparedStatement) con.prepareStatement(query2); PreparedStatement pst3 = (PreparedStatement) con.prepareStatement(query3); PreparedStatement pst4 = (PreparedStatement) con.prepareStatement(query4); ResultSet rs1 = pst.executeQuery(); rs1.next(); ResultSet rs2 = pst2.executeQuery(); rs2.next(); ResultSet rs3 = pst3.executeQuery(); rs3.next(); ResultSet rs4 = pst4.executeQuery(); rs4.next(); total = rs1.getInt(1) + rs2.getInt(1) + rs3.getInt(1) + rs4.getInt(1); return total; } catch (Exception e) { return 0; } finally { try { if (con != null) { con.close(); } if (pst != null) { pst.close(); } } catch (Exception e) { } } } /** * method to get faculty details * */ Student getFacultyName(String regNumber) { Student st = new Student(); try { con = (Connection) DriverManager.getConnection(url, username, password); String query = ""; if (regNumber.charAt(1) == 'U') { query = "SELECT faculty FROM undergraduate_student WHERE reg_number ='" + regNumber + "'"; } else if (regNumber.charAt(1) == 'P') { query = "SELECT faculty FROM postgraduate_student WHERE reg_number ='" + regNumber + "'"; } pst = (PreparedStatement) con.prepareStatement(query); ResultSet rs = pst.executeQuery(); while (rs.next()) { st.setFacultyName(rs.getString("faculty")); } return st; } catch (Exception e) { System.out.println(e); return null; } finally { try { if (con != null) { con.close(); } if (pst != null) { pst.close(); } } catch (Exception e) { } } } /** * method to get first semester subject details * */ boolean updateFirstSemesterSubjects(String sjdet[], int sem, String yos) { try { con = (Connection) DriverManager.getConnection(url, username, password); String query = ""; int month = Calendar.getInstance().get(Calendar.MONTH) + 1; if (month == 2) { query = "UPDATE semester_1_subjects SET first = '" + sjdet[1] + "', second ='" + sjdet[2] + "', third = '" + sjdet[3] + "', fourth = '" + sjdet[4] + "' WHERE reg_number ='" + sjdet[0] + "' AND semester ='" + sem + "' AND yos = '" + yos + "'"; } else { return false; } pst = (PreparedStatement) con.prepareStatement(query); pst.executeUpdate(); return true; } catch (Exception e) { System.out.println(e); return false; } finally { try { if (con != null) { con.close(); } if (pst != null) { pst.close(); } } catch (Exception e) { } } } /** * method to get second semester subject details * */ boolean updateSecondSemesterSubjects(String sjdet[], int sem, String yos) { try { con = (Connection) DriverManager.getConnection(url, username, password); String query = ""; int month = Calendar.getInstance().get(Calendar.MONTH) + 1; if (month == 7 || month == 2) { query = "UPDATE semester_2_subjects SET first = '" + sjdet[1] + "', second ='" + sjdet[2] + "', third = '" + sjdet[3] + "', fourth = '" + sjdet[4] + "' WHERE reg_number ='" + sjdet[0] + "' AND semester ='" + sem + "' AND yos = '" + yos + "'"; } else { return false; } pst = (PreparedStatement) con.prepareStatement(query); pst.executeUpdate(); return true; } catch (Exception e) { System.out.println(e); return false; } finally { try { if (con != null) { con.close(); } if (pst != null) { pst.close(); } } catch (Exception e) { } } } /** * method to get current gpa details * */ FourthYears getSemesterGPA(String regNumber, int sem) { FourthYears f = new FourthYears(); try { con = (Connection) DriverManager.getConnection(url, username, password); String query = "SELECT * FROM ranking WHERE reg_number='" + regNumber + "' AND semester ='" + sem + "'"; pst = (PreparedStatement) con.prepareStatement(query); ResultSet rs = pst.executeQuery(); while (rs.next()) { f.setGpa(rs.getString(2)); f.setSub1(rs.getString(4)); f.setSub2(rs.getString(6)); f.setSub3(rs.getString(8)); f.setSub4(rs.getString(10)); f.setSub5(rs.getString(12)); f.setSub6(rs.getString(14)); f.setSub7(rs.getString(16)); f.setSub8(rs.getString(18)); f.setRes1(rs.getString(5)); f.setRes2(rs.getString(7)); f.setRes3(rs.getString(9)); f.setRes4(rs.getString(11)); f.setRes5(rs.getString(13)); f.setRes6(rs.getString(15)); f.setRes7(rs.getString(17)); f.setRes8(rs.getString(19)); } return f; } catch (Exception e) { System.out.println(e); return null; } finally { try { if (con != null) { con.close(); } if (pst != null) { pst.close(); } } catch (Exception e) { } } } /** * method to get result details * */ ArrayList<Results> getResultDetails() { ArrayList<Results> res = new ArrayList<Results>(); byte[] fileBytes; try { con = (Connection) DriverManager.getConnection(url, username, password); String query = "SELECT * FROM results"; pst = (PreparedStatement) con.prepareStatement(query); ResultSet rs = pst.executeQuery(); while (rs.next()) { Results r = new Results(); r.setSubjectName(rs.getString(1)); // fileBytes = rs.getBytes(4); // OutputStream targetFile = new FileOutputStream(rs.getString(4)); // targetFile.write(fileBytes); // targetFile.close(); r.setName(rs.getString(4)); res.add(r); } return res; } catch (Exception e) { System.out.println(e); return null; } finally { try { if (con != null) { con.close(); } if (pst != null) { pst.close(); } } catch (Exception e) { } } } /** * method to download exam pdf files * */ boolean donwloadFile(String fileName) { byte[] fileBytes; try { con = (Connection) DriverManager.getConnection(url, username, password); String query = "SELECT * FROM results WHERE file_name='" + fileName + "'"; pst = (PreparedStatement) con.prepareStatement(query); ResultSet rs = pst.executeQuery(); while (rs.next()) { fileBytes = rs.getBytes(3); OutputStream targetFile = new FileOutputStream("C:\\Users\\Public\\Documents\\" + rs.getString(4)); targetFile.write(fileBytes); targetFile.close(); } return true; } catch (Exception e) { System.out.println(e); return false; } finally { try { if (con != null) { con.close(); } if (pst != null) { pst.close(); } } catch (Exception e) { } } } ArrayList<LecturerNotes> getLecturerNotes() { ArrayList<LecturerNotes> lecNotes = new ArrayList<LecturerNotes>(); try { con = (Connection) DriverManager.getConnection(url, username, password); String query = "SELECT * FROM lec_notes"; pst = (PreparedStatement) con.prepareStatement(query); ResultSet rs = pst.executeQuery(); while (rs.next()) { LecturerNotes note = new LecturerNotes(); note.setNoteID(rs.getInt(1)); note.setFileName(rs.getString(2)); note.setSubjectID(rs.getString(6)); lecNotes.add(note); } return lecNotes; } catch (Exception e) { return null; } finally { try { if (con != null) { con.close(); } if (pst != null) { pst.close(); } } catch (Exception e) { } } } boolean downloadLecturerNotes(LecturerNotes ln) { byte[] fileBytes; try { con = (Connection) DriverManager.getConnection(url, username, password); String query = "SELECT * FROM lec_notes WHERE file_name='" + ln.getFileName() + "'"; pst = (PreparedStatement) con.prepareStatement(query); ResultSet rs = pst.executeQuery(); while (rs.next()) { fileBytes = rs.getBytes(4); OutputStream targetFile = new FileOutputStream("C:\\Users\\Public\\Documents\\" + rs.getString(2)); targetFile.write(fileBytes); targetFile.close(); } return true; } catch (Exception e) { System.out.println(e); return false; } finally { try { if (con != null) { con.close(); } if (pst != null) { pst.close(); } } catch (Exception e) { } } } String getCurrentGPA(String regNumber) { String gpa = ""; try { con = (Connection) DriverManager.getConnection(url, username, password); String query = "SELECT gpa FROM ranking WHERE reg_number='" + regNumber + "'"; pst = (PreparedStatement) con.prepareStatement(query); ResultSet rs = pst.executeQuery(); double tmp = 0; int count = 1; while (rs.next()) { tmp += rs.getDouble(1); count++; } if (tmp > 0) { gpa = Double.toString(tmp / count); } return gpa; } catch (Exception e) { return null; } finally { try { if (con != null) { con.close(); } if (pst != null) { pst.close(); } } catch (Exception e) { } } } }
C++
UTF-8
706
3.4375
3
[]
no_license
#include <iostream> using namespace std; class myclass{ public: int size; int *p; public: myclass(myclass&my ){ this->size=my.size; //Copy constructor ile dizi kopyalama this->p=new int[size]; for(int i=0;i<size;i++){ this->p[i]=my.p[i]; } } myclass(int sz){ p=new int[sz]; if(!p) exit(1); size=sz; for(int i=0;i<size;i++){ p[i]=2*i; } } ~myclass(){ delete [] p; } int* get(int i){return &p[i]; } int getSize(){return size; } }; void show(myclass& a){ cout<<"array : "; for(int i=0;i<a.getSize();i++)cout<<a.get(i)<<" ";cout<<endl;} int main(){ myclass obj1(5); show(obj1); myclass obj2=obj1; show(obj2); }
JavaScript
UTF-8
273
2.859375
3
[]
no_license
export const personReducer = (currentPersons, action) => { switch (action.type) { case 'add': return [...currentPersons, action.value]; case 'remove': return currentPersons.filter(p => p !== action.value); default: return currentPersons; } }
Python
UTF-8
379
2.96875
3
[]
no_license
# encoding=utf-8 __author__ = 'xiaowang' __date__ = '18/2/16' class Singleton(object): _state = {} def __new__(cls, *args, **kwargs): ob = super(Singleton, cls).__new__(cls, *args, **kwargs) ob.__dict__ = cls._state print(ob) return ob # class MyClass(Singleton): # a = 1 # # # a1 = MyClass() # a2 = MyClass() # print(a1 is a2)
Python
UTF-8
519
3.203125
3
[]
no_license
shopping_items = [ "jajka", "bułka", "ser feta", "masło", "pomidor" ] forgotten_items = [ "chusteczki", "papier toaletowy" ] def shopping(items): shopping_cart = "Koszyk zawiera: " for item in items: shopping_cart += item + '\n' return shopping_cart def x_shopping(items): x_cart = "Jesce dokupic: " for item in items: x_cart += item +'\n' return x_cart basket = shopping(shopping_items) x_basket = x_shopping(forgotten_items) print(basket, x_basket)
JavaScript
UTF-8
608
4.09375
4
[]
no_license
class Student { constructor(firstName, lastName){ this.firstName = firstName this.lastName = lastName } getFullName(){ return this.firstName + ' '+ this.lastName } } let student = new Student("Scott", "Desatnick") console.log(student.firstName) console.log(student.lastName) console.log(student.getFullName()) class Vehicle { constructor (name, type) { this.name = name; this.type = type; } } class Car extends Vehicle { constructor(name, type){ super(name, type) } } let car = new Car('Tesla', 'Car'); console.log(car)
Markdown
UTF-8
8,880
2.71875
3
[ "MIT" ]
permissive
[![Ember Observer Score](http://emberobserver.com/badges/ember-power-timepicker.svg)](http://emberobserver.com/addons/ember-power-timepicker) # Ember-Power-Timepicker This is an Ember addon that uses the wonderful [ember-power-select](https://github.com/cibernox/ember-power-select) component for the singular purpose of allowing the user to select a time of day from a picklist. ## IMPORTANT **This project is no longer being worked on** other than for security related issues. If you are interested in taking over this project please create an issue and I'll work out the details of transfering the project with you. See #13 for more information. ## Installation Ember Time Picker has the same requirements as ember-power-select namely Ember **2.3.1+** This is an ember-cli addon so this will install the addon: ``` ember install ember-power-timepicker ``` ## Properties **Ember Power Select (pass-through) Properties** These properties behave the same as [documented](http://www.ember-power-select.com/docs/api-reference) in ember-power-select: ```javascript /** * The component rendered after the list of options. It is empty by default in both single and multiple selects * @property {string | null} * @public */ afterOptionsComponent: null /** * When true the time can be cleared by clicking [x]. * @property {boolean} * @public */ allowClear: true /** * The component rendered before the list of options defaults to the searchbox. * @property {string | undefined} * @public */ beforeOptionsComponent: undefined /** * The CSS class of the power-select component. * @property {string | null} * @public */ class: null /** * Defaults to true. When false, the component won't be closed after the user chooses an option, either with the * mouse/keyboard or using the `choose` action in the publicAPI. * @property {boolean} * @public */ closeOnSelect: true /** * Id of the element used as target for the dropdown's content, when not rendered in place. * @property {string | undefined} * @public */ destination: undefined /** * Indicates if the component is disabled or not. * @property {boolean} * @public */ disabled: false /** * CSS class applied to the dropdown only. * @property {string | null} * @public */ dropdownClass: null /** * When true the component is rendered initially in the open state. * @property {boolean} * @public */ initiallyOpened: false /** * Message shown in the list of times while the times are still not resolved, typically after a search... * @property {string} * @public */ loadingMessage: 'Loading times...' /** * When enabled (and it's enabled by default) the dropdown with match the width of the trigger. * @property {boolean} * @public */ matchTriggerWidth: true /** * The default message displayed when searching for a time and the search has no match * in the times array. * @property {string} * @public */ noMatchesMessage: "No matching time found" /** * Text to show when no time has been selected. * @property {string} * @public */ placeholder: "" /** * When truthy, the list of options will be rendered in place instead of being attached to the root of the body and * positioned with javascript.Enabling this option also adds a wrapper div around the trigger and the content with * class .ember-power-select. * @property {boolean} * @public */ renderInPlace: false /** * Indicates if the search box is enabled. * @property {boolean} * @public */ searchEnabled: true /** * Class to be applied to the trigger only * @property {string | undefined} * @public */ triggerClass: undefined /** * Component to be rendered as placeholder. It can be used along with placeholder and has access to it. * @property {string} * @public */ placeholderComponent: 'power-select/placeholder' /** * The component to render instead of the default one inside the trigger. * @property {string} * @public */ triggerComponent: 'power-select/trigger' /** * The id to be applied to the trigger. * Useful link the select to a <label> tag. * @property {string} * @public */ triggerId: '' ``` **Ember Time Picker Properties** ```javascript /** * List of times to choose from (corresponds to the options property in power-select). * If not set a default times[] array is used. * @property {string[] | null} * @public */ times: null /** * The currently selected time (if not null it should be set to an element in the times[] property). * This corresponds to Ember Power Select property: selected. * @property {string | null} * @public */ selectedTime: null /** * Component to render for each time element. * @property {string} * @public */ timeComponent: 'time-element' /** * Component to render for the selected time (corresponds to the selectedItemComponent in power-select) * @property {string} * @public */ selectedTimeComponent: 'selected-time' /** * If selectedTime === null and defaultTimeToNow is true then the current clock time will be used. * defaultTimeToNow is ignored if selectedTime !==null * @property {boolean} * @public */ defaultTimeToNow: true /** * When set to true then military time format will be used (Only applies if the times[] array is generated). * @property {boolean} * @public */ military: false /** * Indicates the number of minute intervals. If not specified 30 will be used. * @property {int | null} * @public * @default 30 */ increment: null /** * Indicates the beginning hour in the picklist. If not set then 1 will be used. * @property {int | null} * @public * @default 1 */ startTimeHour: null /** * Indicates the ending hour in the picklist. If not set the 24 is the default. * @property {int | null} * @public * @default 24 */ endTimeHour: null ``` **Actions** All actions are pass-through actions to the Ember Power Select component: ```javascript /** * Invoked when component or any of its subitems looses the focus. * The last argument is the FocusEvent, that can be used to disambiguate what gained the focus. * @param select * @param e */ onblur(select, e) /** * Invoked when the user selects/changes a time. * Two-way binding is established by setting the selectedTime property when a new selection is made. * @param {string | null} timeString The time string of the selected time (can be null if no time selected, or cleared). * @param {int | null} hours The hours from the time string as an integer. * @param {int | null} minutes The minutes from the time string as an integer. */ onchange(timeString, hours, minutes) /** * Invoked when the component is closed. * @param select * @param e */ onclose(select, e) /** * Invoked when the component gets focus. * @param select * @param e */ onfocus(select, e) /** * Invoked when the user changes the text in any any search input of the component. * If the function returns false the default behaviour (filter/search) is prevented. * @param select * @param e */ oninput(select, e) /** * Invoked when the user presses a key being the component or the inputs inside it focused. * @param dropdown * @param e */ onkeydown(dropdown, e) /** * Invoked when the component is opened. * @param select * @param e */ onopen(select, e) ``` ## Simple Example ```handlebars <p>Calculated Times Selection</p> <div style="text-align: right; clear: both; float: left; margin-right: 15px;"> Time: </div> <div style="width: 220px;"> {{time-picker selectedTime=timeSelected onchange=(action "onChange") increment=5 }} </div> <br/> <p>timeSelected property: {{timeSelected}}</p> <p>Time from Action.onChange(): {{time}} </p> ``` ```javascript import Controller from '@ember/controller'; export default Controller.extend( { timeSelected: null, time: null, actions: { onChange(value) { this.set('time', value); } } }); ``` ## Running Dummy Website * `ember serve` * Visit [http://localhost:4200](http://localhost:4200). ![Example](https://github.com/ryannerd/ember-power-timepicker/blob/screenshots/screenshots/example-2.png) ![Example](https://github.com/ryannerd/ember-power-timepicker/blob/screenshots/screenshots/example-1.png) ## Running Tests * `ember serve` * Visit [http://localhost:4200/tests](http://localhost:4200/tests).
C
UTF-8
1,928
3.1875
3
[]
no_license
#ifndef SORT_H_ #define SORT_H_ #define ElementType int /* 冒泡排序 Bubble_Sort 时间复杂度 O(N^2) */ void Bubble_Sort(ElementType A[], int N); /* 插入排序 Insertion_Sort 时间复杂度 O(N^2) 若一个数组基本有序,则插入排序算法简单高效 */ void Insertion_Sort(ElementType A[], int N); /* 希尔排序 Shell_Sort 希尔排序可以看作是插入排序的扩展 时间复杂度 最坏情况O(N^2) 希尔排序时间复杂度不稳定! */ // 原始希尔排序 void Shell_Sort(ElementType A[], int N); // Hibbard 增量序列 希尔排序 void Hibbard_Shell_Sort(ElementType A[], int N); // Sedgewick增量序列哈希排序 void Sedgewick_Shell_Sort(ElementType A[], int N); /* 选择排序 Selection_Sort 时间复杂度 O(N^2) */ void Selection_Sort(ElementType A[], int N); /* 堆排序 Heap_Sort 时间复杂度 最坏情况O(NlogN) 堆排序的时间复杂度不稳定 */ void Heap_Sort(ElementType A[], int N); /* 归并排序 Merge_Sort 时间复杂度 O(NlogN) 归并排序非常稳定 */ // 递归实现 void Merge_Sort_Recursive(ElementType A[], int N); // 非递归实现 void Merge_Sort_NonRecursive(ElementType A[], int N); /* 快速排序 Quick_Sort 时间复杂度 最坏 O(N^2) 平均 O(NlogN) 不稳定 */ // 递归实现 void Quick_Sort(ElementType A[], int N); // 调用库函数 qsort void Quick_Sort_Stdlib(ElementType A[], int N); /* 桶排序 Bucket_Sort 时间复杂度 O(M+N) 稳定 适用于整形序列,且范围是 0~M M是序列的最大值,N是序列的长度 当M与N接近时,适合用桶排序 */ void Bucket_Sort(int A[], int N); /* 基数排序 Radix_Sort 时间复杂度 O(P(N+B)) P是整数的最大位数 N是序列个数 B是进制 稳定 适用于整数排序 适用于P较少的情况 低位优先 LSD */ int GetDigit(int X, int D); void PrintArr(int A[], int N); #endif // SORT_H_
Markdown
UTF-8
425
2.5625
3
[]
no_license
--- layout: post title: 'Training' categories: training tags: squat bench deadlift chinup --- Squat : 205x5x3 Bench : 175x5x3 Deadlift : 285x5 Chinup : 35x5x3 ### Notes Stomach issue over the weekend, so barely ate. Held weight constant. Squats okay, thought definitely uneven in the hole at times. Bench okay, touching chest more controlled now ("glass"). Deads easy still, "head back".
PHP
UTF-8
2,817
2.53125
3
[ "MIT" ]
permissive
<?php namespace Tastetag\MainBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Comments * @ORM\Entity(repositoryClass="Tastetag\MainBundle\Entity\CommentsRepository") */ class Comments { /** * @var \DateTime */ private $createdAt; /** * @var string */ private $content; protected $recipeId; private $userId; /** * @var integer */ private $id; protected $recipe; /** * var user * @ORM\ManyToOne(targetEntity="Tastetag\MainBundle\Entity\User", inversedBy="comments") * @ORM\JoinColumn(name="user_id", referencedColumnName="id") **/ protected $user; public function __construct() { $this->setCreatedAt(new \DateTime()); } /** * Set createdAt * * @param \DateTime $createdAt * @return Comments */ public function setCreatedAt($createdAt) { $this->createdAt = $createdAt; return $this; } /** * Get createdAt * * @return \DateTime */ public function getCreatedAt() { return $this->createdAt; } /** * Set content * * @param string $content * @return Comments */ public function setContent($content) { $this->content = $content; return $this; } /** * Get content * * @return string */ public function getContent() { return $this->content; } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set recipe * * @param Tastetag\MainBundle\Entity\Recipe $recipe */ public function setRecipe(\Tastetag\MainBundle\Entity\Recipes $recipe) { $this->recipe = $recipe; $this->recipe->addComment($this); } /** * Get recipe * * @return Tastetag\MainBundle\Entity\Recipe */ public function getRecipe() { return $this->recipe; } public function setRecipeId($recipe_id) { $this->recipeId = $recipe_id; return $this; } public function getRecipeId() { return $this->recipeId; } /** * Set user * * @param Tastetag\MainBundle\Entity\User $user */ public function setUser(\Tastetag\MainBundle\Entity\User $user) { $this->user = $user; $this->user->addComment($this); } /** * Get user * * @return Tastetag\MainBundle\Entity\User */ public function getUser() { return $this->user; } public function setUserId($user_id) { $this->userId = $user_id; return $this; } public function getUserId() { return $this->userId; } }
Java
UTF-8
2,903
3.15625
3
[]
no_license
package versionvegaterminal; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.InetSocketAddress; import java.net.Socket; import versionvegaterminal.util.IOUtil; public class VersionVegaTerminal { private static final String BOXHOST = "127.0.0.1"; private static final int BOXPORT = 15099; public static void main(String[] args) throws Throwable { String host = (args.length > 0) ? args[0] : BOXHOST; int port = (args.length > 1) ? Integer.parseInt(args[1]) : BOXPORT; System.out.println("Connecting... "); Socket socket = new Socket(); socket.connect(new InetSocketAddress(host, port)); BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(socket.getInputStream())); PrintWriter writer = new java.io.PrintWriter(socket.getOutputStream(),true); System.out.println("GO or EXIT?"); System.out.print("> "); BufferedReader keyboardReader = new BufferedReader(new InputStreamReader(System.in)); String line = keyboardReader.readLine(); if ("GO".equals(line)) { writer.println(line); writer.flush(); line = reader.readLine(); if (! line.equals("OK")) throw new RuntimeException("No OK:" + line); } else if ("EXIT".equals(line)) { writer.println(line); writer.flush(); reader.close(); writer.close(); socket.close(); return; } else { reader.close(); writer.close(); socket.close(); return; } System.out.println("Talking to @versionvega at " + host + ":" + Integer.toString(port) + "."); while (true) { System.out.print("> "); System.out.flush(); line = keyboardReader.readLine(); if (line == null) break; String[] parts = line.split(" "); if (parts.length < 2) { System.out.println("Syntax: <object> <method> <arg1> <arg2> ..."); System.out.println("with <object> being one of orion, vega, sirius, polaris."); System.out.println("with <method> being the command to be invoked, e.g. connect."); System.out.println("with <argX> being the arguments to the command (must match the expected number)"); continue; } String object = parts[0]; String method = parts[1]; writer.println(object + " " + method + " " + (parts.length - 2)); for (int i=2; i<parts.length; i++) if (parts[i].toLowerCase().equals("null")) parts[i] = null; for (int i=2; i<parts.length; i++) writer.println(IOUtil.writeArg(parts[i])); Object ret = IOUtil.readRet(reader.readLine()); if (ret instanceof String[]) { for (String str : (String[]) ret) System.out.println(">>> " + str); } else if (ret instanceof String) { System.out.println(">>> " + (String) ret); } else { System.out.println(">>> " + ret); } } reader.close(); writer.close(); socket.close(); } }
Java
UTF-8
938
1.851563
2
[]
no_license
package mx.com.nok.componente.dao; import java.util.List; import mx.com.nok.componente.model.dto.ComponenteDTO; import mx.com.nok.componente.model.dto.ComponentePerfilDTO; public interface ComponenteDAO { public List<?> infoComponente(ComponenteDTO dto) throws Exception; public ComponenteDTO insertComponente(ComponenteDTO dto) throws Exception; public ComponenteDTO updateComponente(ComponenteDTO dto)throws Exception; public boolean deleteComponente(ComponenteDTO dto) throws Exception; public ComponenteDTO updateEstatusComponente(ComponenteDTO dto)throws Exception; public List<?> infoComponentePerfil(ComponentePerfilDTO dto) throws Exception; public ComponentePerfilDTO insertComponentePerfil(ComponentePerfilDTO dto) throws Exception; public ComponentePerfilDTO updateComponentePerfil(ComponentePerfilDTO dto)throws Exception; public boolean deleteComponentePerfil(ComponentePerfilDTO dto) throws Exception; }
JavaScript
UTF-8
222
3.265625
3
[]
no_license
function add(num1,num2){ // option 1 // num2 = num2 || 0; // option 2 if (num2 == undefined ){ num2 = 0; } const total = num1 + num2 return total; } const result = add(15); console.log(result);
C++
WINDOWS-1252
6,807
2.625
3
[ "MIT" ]
permissive
/*=========================================================================== ; DVServercommon.cpp ;---------------------------------------------------------------------------- ; * Copyright 2020 Intel Corporation ; SPDX-License-Identifier: MIT ; ; File Description: ; This file defines the DVServer common helper functions ;--------------------------------------------------------------------------*/ #include "Driver.h" #include "DVServercommon.h" #include "DVServererror.h" extern WDFDEVICE g_idd_device; static char log_buff[BUFSIZ] = { 0 }; /*--------------------------------------------------------------------------- ; Helper function to open the IDD registry key ;--------------------------------------------------------------------------*/ static NTSTATUS open_idd_registry(WDFKEY *key) { NTSTATUS status = STATUS_SUCCESS; if (!key) { return STATUS_UNSUCCESSFUL; } status = WdfDeviceOpenRegistryKey( g_idd_device, PLUGPLAY_REGKEY_DRIVER | WDF_REGKEY_DRIVER_SUBKEY, KEY_READ | KEY_SET_VALUE, WDF_NO_OBJECT_ATTRIBUTES, key); sprintf_s(log_buff, BUFSIZ, "%s, status: %x", __FUNCTION__, status); WriteToLog(log_buff); return status; } /*--------------------------------------------------------------------------- ; Helper function to close the IDD registry key ;--------------------------------------------------------------------------*/ static void close_idd_registry(WDFKEY key) { WdfRegistryClose(key); } /*--------------------------------------------------------------------------- ; Internal API to read a UINT32 value from the registry ;--------------------------------------------------------------------------*/ int idd_read_registry_dword(PCWSTR name, ULONG *value) { NTSTATUS status = STATUS_SUCCESS; WDFKEY key_idd; UNICODE_STRING uc_name; if (!name || !value) { return IDD_FAILURE; } status = open_idd_registry(&key_idd); if (NT_SUCCESS(status)) { RtlInitUnicodeString(&uc_name, name); status = WdfRegistryQueryULong( key_idd, &uc_name, (PULONG)value); sprintf_s(log_buff, BUFSIZ, "%s, status: %x", __FUNCTION__, status); WriteToLog(log_buff); close_idd_registry(key_idd); return IDD_SUCCESS; } return IDD_FAILURE; } /*--------------------------------------------------------------------------- ; Internal API to write a UNIT32 value to the registry ; If the registry value not present, create it and assign the value ;--------------------------------------------------------------------------*/ int idd_write_registry_dword(PCWSTR name, ULONG value) { NTSTATUS status = STATUS_SUCCESS; WDFKEY key_idd; UNICODE_STRING uc_name; if (!name) { return IDD_FAILURE; } status = open_idd_registry(&key_idd); if (NT_SUCCESS(status)) { RtlInitUnicodeString(&uc_name, name); status = WdfRegistryAssignULong( key_idd, &uc_name, value); sprintf_s(log_buff, BUFSIZ, "%s, status: %x", __FUNCTION__, status); WriteToLog(log_buff); close_idd_registry(key_idd); return IDD_SUCCESS; } return IDD_FAILURE; } /*--------------------------------------------------------------------------- ; Internal API to read binary data from registry into a buffer ; [in] *size : read buffer size ; [out] *size : byte count read from the registry ;--------------------------------------------------------------------------*/ int idd_read_registry_binary(PCWSTR name, BYTE *buffer, ULONG *size) { NTSTATUS status = STATUS_SUCCESS; WDFKEY key_idd; UNICODE_STRING uc_name; ULONG value_len, value_type = REG_BINARY; if (!name || !buffer || !size) { return IDD_FAILURE; } status = open_idd_registry(&key_idd); if (NT_SUCCESS(status)) { RtlInitUnicodeString(&uc_name, name); status = WdfRegistryQueryValue( key_idd, &uc_name, *size, buffer, &value_len, &value_type); sprintf_s(log_buff, BUFSIZ, "%s, status: %x, read length: %d", __FUNCTION__, status, value_len); WriteToLog(log_buff); close_idd_registry(key_idd); if (NT_SUCCESS(status)) { *size = value_len; return IDD_SUCCESS; } } return IDD_FAILURE; } /*--------------------------------------------------------------------------- ; Internal API to write binary data from a buffer into registry ;--------------------------------------------------------------------------*/ int idd_write_registry_binary(PCWSTR name, BYTE *buffer, ULONG size) { NTSTATUS status = STATUS_SUCCESS; WDFKEY key_idd; UNICODE_STRING uc_name; ULONG value_type = REG_BINARY; if (!name || !buffer || !size) { return IDD_FAILURE; } status = open_idd_registry(&key_idd); if (NT_SUCCESS(status)) { RtlInitUnicodeString(&uc_name, name); status = WdfRegistryAssignValue( key_idd, &uc_name, value_type, size, buffer); sprintf_s(log_buff, BUFSIZ, "%s, status: %x", __FUNCTION__, status); WriteToLog(log_buff); close_idd_registry(key_idd); if (NT_SUCCESS(status)) { return IDD_SUCCESS; } } return IDD_FAILURE; } /*--------------------------------------------------------------------------- ; Internal API to read WCHAR string from registry into a buffer ;--------------------------------------------------------------------------*/ int idd_read_registry_string(PCWSTR name, WCHAR *buffer, ULONG size) { NTSTATUS status = STATUS_SUCCESS; WDFKEY key_idd; UNICODE_STRING uc_name; ULONG value_len, value_type = REG_SZ; if (!name || !buffer || !size) { return IDD_FAILURE; } status = open_idd_registry(&key_idd); if (NT_SUCCESS(status)) { RtlInitUnicodeString(&uc_name, name); status = WdfRegistryQueryValue( key_idd, &uc_name, size, buffer, &value_len, &value_type); sprintf_s(log_buff, BUFSIZ, "%s, status: %x", __FUNCTION__, status); WriteToLog(log_buff); close_idd_registry(key_idd); if (NT_SUCCESS(status) && size >= value_len) { return IDD_SUCCESS; } } return IDD_FAILURE; } /*--------------------------------------------------------------------------- ; Internal API to write a WCHAR string buffer into the registry ;--------------------------------------------------------------------------*/ int idd_write_registry_string(PCWSTR name, WCHAR *buffer, ULONG size) { NTSTATUS status = STATUS_SUCCESS; WDFKEY key_idd; UNICODE_STRING uc_name; ULONG value_type = REG_SZ; if (!name || !buffer || !size) { return IDD_FAILURE; } status = open_idd_registry(&key_idd); if (NT_SUCCESS(status)) { RtlInitUnicodeString(&uc_name, name); status = WdfRegistryAssignValue( key_idd, &uc_name, value_type, size, buffer); sprintf_s(log_buff, BUFSIZ, "%s, status: %x", __FUNCTION__, status); WriteToLog(log_buff); close_idd_registry(key_idd); if (NT_SUCCESS(status)) { return IDD_SUCCESS; } } return IDD_FAILURE; }
Python
UTF-8
6,321
2.578125
3
[]
no_license
import numpy as np import pandas as pd import PMF_Thesis as Pmf import time # To change all the data into tuples (col, row, value) def change_into_tuple(data_file): data_list = [] for each_row_tuple_index in range(0, len(data_file)): for each_col_index in range(0, len(data_file[each_row_tuple_index])): if ~np.isnan(data_file[each_row_tuple_index][each_col_index]): data_list.append([each_row_tuple_index,each_col_index,data_file[each_row_tuple_index][each_col_index]]) return data_list # to select only distinct values def select_distinct(data_array): a = np.ascontiguousarray(data_array) unique_a = np.unique(a.view([('', a.dtype)] * a.shape[1])) return unique_a.view(a.dtype).reshape((unique_a.shape[0], a.shape[1])) # Evaluation function. # Calculate root mean squared error. Ignoring missing values in the test data. def rmse(test_data, predicted): I = ~np.isnan(test_data) # indicator for missing values N = I.sum() # number of non-missing values diff = test_data - predicted sqerror1 = abs(diff) #RMSE sqerror2 = diff / (test_data) avarage = sqerror2[I].sum() / N sqerror = sqerror1 ** 2 #RMSE mse = sqerror[I].sum() / N #RMSE return np.sqrt(mse), np.max(sqerror2[I]), np.min(sqerror2[I]), avarage # RMSE, max, min, avg def build_matrix_from_tuple(columns_data, rows_data, matrix_R): matrix = np.ones((columns_data, rows_data)) * np.nan for item_id in xrange(rows_data): data = matrix_R[matrix_R[:, 1] == item_id] if data.shape[0] > 0: matrix[(data[:, 0]).astype(int), int(item_id)] = data[:, 2] return matrix def accuracy_percent_pmf(test_data_l, predicted_l): I = ~np.isnan(test_data_l) # indicator for missing values N = I.sum() # number of non-missing values substract_d = np.array(test_data_l).astype(float) - np.array(predicted_l).astype(float) sub_only_target1 = substract_d[I] # print len(sub_only_target1), N total_number = len(sub_only_target1) sub_only_target2 = sub_only_target1[sub_only_target1<=0.1] total_number1 = len(sub_only_target2) range_exact_percent = float((total_number1 *100)/total_number) sub_only_target3 = sub_only_target1[sub_only_target1<=0.2] total_number2 = len(sub_only_target3) range_five_percent = float((total_number2 * 100)/total_number) sub_only_target4 = sub_only_target1[sub_only_target1<=0.3] total_number3 = len(sub_only_target4) range_thirty_percent = float((total_number3 * 100)/total_number) return range_exact_percent, range_five_percent, range_thirty_percent if __name__ == "__main__": all_rmse = [] all_rmse_acc = [] time_list = [] auroRes = [] for ind in range(3,9):#range(3,21): # change it into 21 k = ind for index in range(1, k+1): data = pd.read_csv('eachSensors/Merged_data/k_'+str(k)+'/k_'+str(k)+'_cluster_'+str(index)+ '_norm_without_empty_column.csv', sep=",") print "K : ", k, " Index: ", index, " Data amount: ", data.shape if len(data) > 100: d = data[1:5001].astype(float) unique_data = select_distinct(d) col_num, row_num = unique_data.shape all_data_tuple = change_into_tuple(unique_data) np.random.shuffle(all_data_tuple) # shuffle_data # set feature numbers num_feature = int(row_num/2) # set max_iterations max_iter = 10000 # split data to training & testing train_pct = 0.9 train_size = int(train_pct * len(all_data_tuple)) train = np.array(all_data_tuple[:train_size]) validation = np.array(all_data_tuple[train_size:]) all_data_array = np.array(all_data_tuple) # models start_time=time.time() rec = Pmf.Pmf.BayesianMatrixFactorization(col_num, row_num, num_feature, all_data_array, train, validation, max_matrix_R=1, min_matrix_R=0, show_log=False) elapsed_time_train=time.time()-start_time start_time2 = time.time() rec.estimate(max_iter) elapsed_time_estimate=time.time()-start_time2 # validation R_hat = np.dot(rec.matrix_u_features, rec.matrix_v_features.T) # print R_hat.shape rmse_data, max_error, min_error, ave_error = rmse(build_matrix_from_tuple(col_num, row_num,validation), R_hat) all_rmse.append([k, index, rec.validation_errors[-1], rmse_data, max_error, min_error, ave_error]) exact_acc, five_acc, thirty_acc = accuracy_percent_pmf(build_matrix_from_tuple(col_num, row_num, validation), R_hat) all_rmse_acc.append([k, index, exact_acc, five_acc, thirty_acc]) time_list.append([k, index, elapsed_time_train,len(train), elapsed_time_estimate, len(validation)]) realM = build_matrix_from_tuple(col_num, row_num, validation) predictedM = R_hat predicted = predictedM[~np.isnan(realM)] real= realM[~np.isnan(realM)] MAPE = sum((abs(real-predicted))/len(real))*100 RMSE = np.sqrt(np.mean((real - predicted)**2)); CVRMSE = RMSE/np.mean(real)*100 auroRes.append([MAPE,RMSE,CVRMSE]) print "Done with index = ", index if len(all_rmse) > 0: lst_rmse = pd.DataFrame(np.array(all_rmse).T) lst_rmse.to_csv('data_other/June_13/All_Result_PMF_True_RMSE.csv', index=False) if len(all_rmse_acc) > 0: lst_acc = pd.DataFrame(np.array(all_rmse_acc).T) lst_acc.to_csv('data_other/June_13/All_Result_PMF_True_Acc.csv', index=False) if len(time_list) > 0: lst_time = pd.DataFrame(np.array(time_list).T) lst_time.to_csv('data_other/June_13/All_Result_PMF_True_elapsed_time.csv', index=False) print "All done!!!" auroRes
Java
UTF-8
5,281
1.828125
2
[]
no_license
package com.leyijf.view.activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.Toast; import com.leyijf.R; import com.leyijf.adapter.SelectoeBankAdapter; import com.leyijf.base.BaseActivity; import com.leyijf.bean.SelectorBank; import com.leyijf.bean.UserInfo; import com.leyijf.util.OkHttpUtil; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; /** * 银行列表页面 */ public class BanlListActivity extends BaseActivity { private ImageView zhuce_back; private ListView limt_list; private List<SelectorBank> list; @Override protected void initData() { } @Override protected void initId() { initView(); toRequestBankList(); } private void toRequestBankList() { Map<String,String> map=new HashMap<>(); map.put("act","uc_add_bank"); map.put("email", UserInfo.getInstance().getUserPhone()); map.put("pwd",UserInfo.getInstance().getUserPwd()); OkHttpUtil.getInstance().doHttp(map, new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { String string = response.body().string(); Log.e("---uc_recharge_app--",string+""); // JSONObject jsonObject= null; try { jsonObject = new JSONObject(string); int response_code = jsonObject.getInt("response_code"); if(response_code==1){ JSONArray jsonArray = jsonObject.getJSONObject("objects").getJSONArray("item"); list = new ArrayList<SelectorBank>(); for (int i = 0; i < jsonArray.length(); i++) { SelectorBank selectorBank=new SelectorBank(jsonArray.getJSONObject(i).getString("id"),jsonArray.getJSONObject(i).getString("name"),jsonArray.getJSONObject(i).getString("is_rec") ,jsonArray.getJSONObject(i).getString("day"),jsonArray.getJSONObject(i).getString("sort"),jsonArray.getJSONObject(i).getString("icon"),jsonArray.getJSONObject(i).getString("code")); list.add(selectorBank); } runOnUiThread(new Runnable() { @Override public void run() { SelectoeBankAdapter selectoeBankAdapter=new SelectoeBankAdapter(BanlListActivity.this,list); limt_list.setAdapter(selectoeBankAdapter); selectoeBankAdapter.notifyDataSetChanged(); limt_list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ImageView imageView=view.findViewById(R.id.biaozhi); imageView.setVisibility(View.VISIBLE); Intent intent=new Intent(); Bundle bundle=new Bundle(); bundle.putString("name",list.get(position).getName()); bundle.putString("id",list.get(position).getId()); intent.putExtras(bundle); setResult(1234,intent); finish(); } }); } }); }else { final String show_err = jsonObject.getString("show_err"); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(BanlListActivity.this, show_err+"", Toast.LENGTH_SHORT).show(); } }); } } catch (JSONException e) { e.printStackTrace(); } } }); } @Override protected int getContentViewId() { withColor(); return R.layout.activity_banl_list; } private void initView() { zhuce_back = (ImageView) findViewById(R.id.zhuce_back); limt_list = (ListView) findViewById(R.id.limt_list); } }
C#
UTF-8
1,841
3.203125
3
[]
no_license
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Modelowanie_GUI { class Grid { public int cellSize { get; set; } public Grid(int panelWidth, int panelHeight, int numberOfXCells, int numberOfYCells) { int tmpX = panelWidth / numberOfXCells; int tmpY = panelHeight / numberOfYCells; this.cellSize = tmpX < tmpY ? tmpX : tmpY; } public Grid(int cellSize) { this.cellSize = cellSize; } public Grid(int panelWidth, int numberOfCells) { this.cellSize = panelWidth / numberOfCells; } public void draw(int panelWidth, int panelHeight, Graphics canva, Pen pen) { int realHeight = (panelHeight / cellSize)*cellSize; int realWidth = (panelWidth / cellSize)* cellSize; for (int it = 0; it < panelWidth; it += cellSize) canva.DrawLine(pen, it, 0, it, realHeight); for (int it = 0; it < panelHeight; it += cellSize) canva.DrawLine(pen, 0, it, realWidth, it); } public void drawSpecificNumberOfCells(int numberOfXCells, int numberOfYCells, Graphics canva, Pen pen) { int realHeight = cellSize * numberOfYCells; int realWidth = cellSize * numberOfXCells; for (int it = 0, cord = 0; it <= numberOfXCells; it++, cord += cellSize) canva.DrawLine(pen, cord, 0, cord, realHeight); for (int it = 0, cord = 0; it <= numberOfYCells; it++, cord += cellSize) canva.DrawLine(pen, 0, cord, realWidth, cord); } } }
Markdown
UTF-8
1,136
2.578125
3
[ "MIT" ]
permissive
- [Chinese](readme.md) - [English](readme_en.md) When coding projects, we often search for basic data(Such as code of nations, currencies, etc.) because we lack them. However, the data collected temporarily is often not complete enough, disordered and even the names and codings are wrong, you need to reorganize and correct it yourself. Therefore, I have push the baisc data collected and collated by myself. You can download them, and welcome to share the basic data collected and organized. This project provides three formats: CSV, JSON, and SQLite. It can be downloaded and used directly. It can also be edited, filtered, and used. CSV files can be opened in Excel, and SQLite (.db) files can be opened with Navicat, SQLite Expert, or SQLiteStudio. [**Click to browse Table of Content**](coding) For binary files (such as `.db`) or larger text files, you can click download to download. ![](img/download_1.png) For smaller text files (such as `.csv` and `.json`), you can click Raw to download, or you can right-click Raw and download directly by tools or copy the address into the download tools. ![](img/download_2.png)
Java
UTF-8
4,428
2.1875
2
[]
no_license
package com.five.amung.qna.controller; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.five.amung.qna.dto.QnaCommentDto; import com.five.amung.qna.dto.QnaDto; import com.five.amung.qna.service.QnaService; import com.five.amung.review.dto.ReviewDto; @Controller public class QnaController { @Autowired private QnaService qnaService; //목록 보기 @RequestMapping("/qna/qna_list") public ModelAndView getList(HttpServletRequest request, ModelAndView mView) { qnaService.getList(request); mView.setViewName("qna/qna_list"); return mView; } //내용 하나 자세히 보기 @RequestMapping("/qna/content") public ModelAndView detail(HttpServletRequest request, ModelAndView mView) { qnaService.getDetail(request); mView.setViewName("qna/content"); return mView; } //글 작성하기 폼 @RequestMapping("/qna/private/insertform") public ModelAndView insertForm(ModelAndView mView) { mView.setViewName("qna/insertform"); return mView; } //글 작성하기 @RequestMapping(value = "/qna/private/insert", method=RequestMethod.POST) public ModelAndView insert(QnaDto dto, ModelAndView mView, HttpSession session) { //dto 에 글 작성자 담기 String id = (String)session.getAttribute("id"); dto.setWriter(id); qnaService.saveContent(dto); mView.setViewName("qna/insert"); return mView; } //글 수정하기 폼 @RequestMapping("/qna/updateform") public ModelAndView updateform(HttpServletRequest request, ModelAndView mView) { qnaService.getDetail(request); mView.setViewName("qna/updateform"); return mView; } //글 수정 @RequestMapping(value="/qna/update", method=RequestMethod.POST) public ModelAndView update(QnaDto dto, ModelAndView mView) { qnaService.updateContent(dto); mView.setViewName("qna/update"); return mView; } //글 삭제 @RequestMapping("/qna/delete") public ModelAndView delete(int num, HttpServletRequest request, ModelAndView mView) { qnaService.deleteContent(num, request); mView.setViewName("redirect:/qna/qna_list.do"); return mView; } //내 글 목록보기 //자기 글 목록 보기 @RequestMapping("/qna/myqna") public ModelAndView getMyList(HttpServletRequest request, ModelAndView mView, QnaDto dto) { qnaService.getMyList(request); mView.setViewName("qna/myqna"); return mView; } //댓글작성 @RequestMapping(value = "/qna/private/comment_insert", method=RequestMethod.POST) public ModelAndView commentInsert(HttpServletRequest request, ModelAndView mView, @RequestParam int ref_group) { //새 댓글을 저장하고 qnaService.saveComment(request); //보고 있던 글 자세히 보기로 다시 리다일렉트 이동 시킨다. mView.setViewName("redirect:/qna/content.do?num="+ref_group); return mView; } //댓글 삭제 @RequestMapping("/qna/private/comment_delete") public ModelAndView commentDelete(HttpServletRequest request, ModelAndView mView, @RequestParam int ref_group) { qnaService.deleteComment(request); mView.setViewName("redirect:/qna/content.do?num="+ref_group); return mView; } //댓글 수정 ajax 요청에 대한 요청 처리 @RequestMapping(value = "/qna/private/comment_update", method=RequestMethod.POST) @ResponseBody public Map<String, Object> commentUpdate(QnaCommentDto dto){ //댓글을 수정 반영하고 qnaService.updateComment(dto); //JSON 문자열을 클라이언트에게 응답한다. Map<String, Object> map=new HashMap<>(); map.put("num", dto.getNum()); map.put("content", dto.getContent()); return map; } //비밀글 //글 작성하기 폼 @RequestMapping("/qna/secret_content") public ModelAndView secretContent(ModelAndView mView) { mView.setViewName("qna/secret_content"); return mView; } }
JavaScript
UTF-8
917
2.59375
3
[]
no_license
var page = require('webpage').create(); var system = require('system'); var count = system.args[1] || 1; var URL = 'https://github.com/Chiara-yen/startLearningNodejs'; page.onConsoleMessage = function(msg) { for (var i = 0; i < count; i++) { console.log(msg); } }; page.open(URL, function(status) { if (status !== 'success') { return console.log('Unable to access network'); } page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js', function() { var OUTER_VARIABLE = { a: 1, b: 2, c: 3 }; page.evaluate(function(outer) { console.log('outer variable:'); console.log(outer.a); console.log(outer.b); console.log(outer.c); console.log(window.$('.author a span').text() + '/' + window.$('.js-current-repository').text()); }, OUTER_VARIABLE); page.render('github.png'); phantom.exit(); }); });
Java
UTF-8
598
2.390625
2
[]
no_license
package com.example.android.bookrentalsystemforcsumblibrary.helperobjects; /** * Created by atomi on 12/8/2016. */ public class LibraryUser { private String userName; private String userPassword; private boolean isAdmin; public LibraryUser(String userName, String userPassword, int isAdmin){ this.userName = userName; this.userPassword = userPassword; this.isAdmin = isAdmin == 1; } public String getUserName(){return userName;} public String getUserPassword(){return userPassword;} public int getIsAdmin(){return isAdmin ? 1:0;} }
PHP
UTF-8
1,735
2.6875
3
[]
no_license
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>アドレス登録</title> </head> <body> <?php $link = mysqli_connect("localhost", "root", "root"); if (!$link) { exit('データベースに接続できませんでした。'); } $result = mysqli_select_db($link, "999sample"); if (!$result) { exit('データベースを選択できませんでした。'); } $result = mysqli_query($link,'SET NAMES utf8'); if (!$result) { exit('文字コードを指定できませんでした。'); echo '<a href="index.php">戻る</a> '; } $userID = $_REQUEST['userID']; $date = $_REQUEST['date']; $start = $_REQUEST['start']; $finish = $_REQUEST['finish']; //$worktime = $finish - $start; //仕事を開始したときに名前と仕事開始時間を記録・デフォルトの出勤アクションにより対処 $result = mysqli_query($link , "INSERT INTO worktime(userID, start, finish) VALUES('$userID', '$start', '$finish')"); if (!$result) { exit('データを登録できませんでした。'); } //作業した日の情報を作成 $tmp = new DateTime($date.$start); //仕事を終了したときに終了時刻を追加・条件分け先 $result = mysqli_query($link , "UPDATE worktime set finish = $finish where userID = $userID"; if (!$result) { exit('データを更新できませんでした。'); } //作業時間を計算 $date1 = new DateTime(SELECT start $start); $date2 = new DateTime($finish); $diff = $date1->diff($date2); $con = mysql_close($link); if (!$link) { exit('データベースとの接続を閉じられませんでした。'); } ?> <p>登録が完了しました。<br /><a href="index.html">戻る</a></p> </body> </html>
Java
UTF-8
13,166
1.757813
2
[]
no_license
package com.example.akshay.akshay5; /** * Created by AKSHAY on 25-01-2018. */ import android.Manifest; import android.app.ProgressDialog; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.util.Base64; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import com.twitter.sdk.android.core.TwitterCore; import com.twitter.sdk.android.core.TwitterSession; import com.twitter.sdk.android.tweetcomposer.ComposerActivity; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import javax.net.ssl.HttpsURLConnection; public class DashboardActivity extends AppCompatActivity { public static final int RequestPermissionCode = 1; public static EditText tweetText; Button CaptureImageFromCamera, UploadImageToServer, GoToProfile; ImageView ImageViewHolder; EditText imageName; ProgressDialog progressDialog; Intent intent; Bitmap bitmap; boolean check = true; String GetImageNameFromEditText; String GetTweetDataFromEditText; String ImageNameFieldOnServer = "image_name"; String ImagePathFieldOnServer = "image_path"; String ImageUploadPathOnSever = "https://arty-crafty-radiato.000webhostapp.com/AndroidApp/capture_img_upload_to_server.php"; String username; //FT Button click; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dashboard); CaptureImageFromCamera = findViewById(R.id.button); ImageViewHolder = findViewById(R.id.imageView); UploadImageToServer = findViewById(R.id.button2); imageName = findViewById(R.id.editText); tweetText = findViewById(R.id.editText3); //twitter username fetching username = getIntent().getStringExtra("username"); EnableRuntimePermissionToAccessCamera(); OnClickButtonListener(); CaptureImageFromCamera.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, 7); } }); UploadImageToServer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { GetImageNameFromEditText = imageName.getText().toString(); ImageUploadToServerFunction(); } }); //FT click = findViewById(R.id.button5); click.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { FetchDataActivity process = new FetchDataActivity(); process.execute(); // Setting image as transparent after done uploading. ImageViewHolder.setImageResource(android.R.color.transparent); imageName.setText(""); } }); } public void OnClickButtonListener() { GoToProfile = findViewById(R.id.button4); GoToProfile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent("com.example.akshay.akshay5.ProfileActivity"); intent.putExtra("username", username); startActivity(intent); // tweetText.setText(""); } }); } public void shareUsingTwitterNativeComposer(View view) { GetTweetDataFromEditText = tweetText.getText().toString(); /* TweetComposer.Builder builder = new TweetComposer.Builder(this).text(GetTweetDataFromEditText); builder.show(); */ final TwitterSession session = TwitterCore.getInstance().getSessionManager() .getActiveSession(); final Intent intent = new ComposerActivity.Builder(DashboardActivity.this) .session(session) .image(filePath) .text(GetTweetDataFromEditText) .hashtags("#twitter") .createIntent(); startActivity(intent); Toast.makeText(DashboardActivity.this, "Click On Tweet", Toast.LENGTH_LONG).show(); } private Uri createFileFromBitmap(Bitmap bitmap) throws IOException { String name = "image:"; File f = new File(getCacheDir(), name + System.currentTimeMillis()+ ".jpg"); f.createNewFile(); //Convert bitmap to byte array ByteArrayOutputStream bos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos); byte[] bitmapdata = bos.toByteArray(); //write the bytes in file FileOutputStream fos = new FileOutputStream(f); fos.write(bitmapdata); fos.flush(); fos.close(); return Uri.fromFile(f); } Uri filePath; @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); /* filePath = data.getData(); try { Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath); ImageViewHolder.setImageBitmap(bitmap); } catch (IOException e) { e.printStackTrace(); } */ if (requestCode == 7 && resultCode == RESULT_OK) { filePath = data.getData(); Bundle extras = data.getExtras(); Bitmap imageBitmap = (Bitmap) extras.get("data"); ImageViewHolder.setImageBitmap(imageBitmap); // Create a file n then get Object of URI try { filePath= createFileFromBitmap(imageBitmap); } catch (IOException e) { e.printStackTrace(); filePath=null; Log.e(getClass().getName(), "onActivityResult: some problem occur to getting URI "+e.getMessage()); } } } // Requesting runtime permission to access camera. public void EnableRuntimePermissionToAccessCamera() { if (ActivityCompat.shouldShowRequestPermissionRationale(DashboardActivity.this, Manifest.permission.CAMERA)) { // Printing toast message after enabling runtime permission. Toast.makeText(DashboardActivity.this, "CAMERA permission allows us to Access CAMERA app", Toast.LENGTH_LONG).show(); } else { ActivityCompat.requestPermissions(DashboardActivity.this, new String[]{Manifest.permission.CAMERA}, RequestPermissionCode); } } // Upload captured image online on server function. public void ImageUploadToServerFunction() { // Locate the image in res > drawable-hdpi bitmap = ((BitmapDrawable) ImageViewHolder.getDrawable()).getBitmap(); ByteArrayOutputStream byteArrayOutputStreamObject; byteArrayOutputStreamObject = new ByteArrayOutputStream(); // Converting bitmap image to jpeg format, so by default image will upload in jpeg format. bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStreamObject); byte[] byteArrayVar = byteArrayOutputStreamObject.toByteArray(); final String ConvertImage = Base64.encodeToString(byteArrayVar, Base64.DEFAULT); class AsyncTaskUploadClass extends AsyncTask<Void, Void, String> { @Override protected void onPreExecute() { super.onPreExecute(); // Showing progress dialog at image upload time. progressDialog = ProgressDialog.show(DashboardActivity.this, "Image is Uploading", "Please Wait", false, false); } @Override protected void onPostExecute(String string1) { super.onPostExecute(string1); // Dismiss the progress dialog after done uploading. progressDialog.dismiss(); // Printing uploading success message coming from server on android app. Toast.makeText(DashboardActivity.this, string1, Toast.LENGTH_LONG).show(); } @Override protected String doInBackground(Void... params) { ImageProcessClass imageProcessClass = new ImageProcessClass(); HashMap<String, String> HashMapParams = new HashMap<String, String>(); HashMapParams.put(ImageNameFieldOnServer, GetImageNameFromEditText); HashMapParams.put(ImagePathFieldOnServer, ConvertImage); String FinalData = imageProcessClass.ImageHttpRequest(ImageUploadPathOnSever, HashMapParams); return FinalData; } } AsyncTaskUploadClass AsyncTaskUploadClassOBJ = new AsyncTaskUploadClass(); AsyncTaskUploadClassOBJ.execute(); } @Override public void onRequestPermissionsResult(int RC, String per[], int[] PResult) { switch (RC) { case RequestPermissionCode: if (PResult.length > 0 && PResult[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(DashboardActivity.this, "Permission Granted, Now your application can access CAMERA.", Toast.LENGTH_LONG).show(); } else { Toast.makeText(DashboardActivity.this, "Permission Canceled, Now your application cannot access CAMERA.", Toast.LENGTH_LONG).show(); } break; } } public class ImageProcessClass { public String ImageHttpRequest(String requestURL, HashMap<String, String> PData) { StringBuilder stringBuilder = new StringBuilder(); try { URL url; HttpURLConnection httpURLConnectionObject; OutputStream OutPutStream; BufferedWriter bufferedWriterObject; BufferedReader bufferedReaderObject; int RC; url = new URL(requestURL); httpURLConnectionObject = (HttpURLConnection) url.openConnection(); httpURLConnectionObject.setReadTimeout(19000); httpURLConnectionObject.setConnectTimeout(19000); httpURLConnectionObject.setRequestMethod("POST"); httpURLConnectionObject.setDoInput(true); httpURLConnectionObject.setDoOutput(true); OutPutStream = httpURLConnectionObject.getOutputStream(); bufferedWriterObject = new BufferedWriter( new OutputStreamWriter(OutPutStream, "UTF-8")); bufferedWriterObject.write(bufferedWriterDataFN(PData)); bufferedWriterObject.flush(); bufferedWriterObject.close(); OutPutStream.close(); RC = httpURLConnectionObject.getResponseCode(); if (RC == HttpsURLConnection.HTTP_OK) { bufferedReaderObject = new BufferedReader(new InputStreamReader(httpURLConnectionObject.getInputStream())); stringBuilder = new StringBuilder(); String RC2; while ((RC2 = bufferedReaderObject.readLine()) != null) { stringBuilder.append(RC2); } } } catch (Exception e) { e.printStackTrace(); } return stringBuilder.toString(); } private String bufferedWriterDataFN(HashMap<String, String> HashMapParams) throws UnsupportedEncodingException { StringBuilder stringBuilderObject; stringBuilderObject = new StringBuilder(); for (Map.Entry<String, String> KEY : HashMapParams.entrySet()) { if (check) check = false; else stringBuilderObject.append("&"); stringBuilderObject.append(URLEncoder.encode(KEY.getKey(), "UTF-8")); stringBuilderObject.append("="); stringBuilderObject.append(URLEncoder.encode(KEY.getValue(), "UTF-8")); } return stringBuilderObject.toString(); } } }
C++
UTF-8
1,016
2.8125
3
[]
no_license
/* * 有一个整数数组nums,和一个查询数组requests,其中requests[i]=[starti,endi] * 第i个查询求nums[starti] + nums[starti + 1] + ... + nums[endi] 的结果 ,starti * 和 endi 数组索引都是 从 0 开始 的。你可以任意排列 nums * 中的数字,请你返回所有查询结果之和的最大值。由于答案可能会很大,请你将它对 * 109 + 7 取余 后返回。 */ #include "Header.h" #define MOD 1000000007 using LL = long long; class Solution { public: int maxSumRangeQuery(vector<int>& nums, vector<vector<int>>& requests) { int size = nums.size(); vector<int> freq(size + 1); for (auto v : requests) { freq[v[0]]++; freq[v[1] + 1]--; } for (int i = 1; i <= size; i++) freq[i] += freq[i - 1]; sort(freq.begin(), freq.begin() + size); sort(nums.begin(), nums.end()); LL ans = 0; for (int i = size - 1; i >= 0; i--) ans = (ans + (LL)nums[i] * freq[i]) % MOD; return ans; } }; // 596658136
Markdown
UTF-8
2,249
2.71875
3
[]
no_license
# angular-commit-complete fish complete for they `<type>` part of angular commit message, that is, in the format of > `<type>(<scope>): <short summary>` 👉 Read more for the [angular commit message format](https://github.com/angular/angular/blob/master/CONTRIBUTING.md#type). ## Motivation While the convention of angular commit message format is good but I find it's hard to remember or determine which `<type>` in every single commit. If there's a hint or complete that list all the types available, it's much better. While this is possible in fish shell with the `complete` command. Although it's not perfect at present, it's just works, which, I mean, it does list all the types when you do a commit. When I say it's not perfect, I mean the fish `complete` cannot completes arguments with quotation marks, so, instead of `git commit -m "build`, what we get after choosing a candidate is `git commit -m build`. ## Installing ```sh curl https://raw.githubusercontent.com/wayou/angular-commit-complete/master/git.fish > ~/.config/fish/completions/git.fish ``` ## Usage Restart the terminal session or `source ~/.config/fish/completions/git.fish` to make the complete take palces. Commit as usually and using <kbd>TAB</kbd> to trigger the complete. ``` $ git commit -m <tab> # or $ git commit --message <tab> test (Adding missing tests or correcting existing tests) refactor (A code change that neither fixes a bug nor adds a feature) perf (A code change that improves performance) fix (A bug fix) feat (A new feature) docs (Documentation only changes) ci (Changes to our CI configuration files and scripts (example scopes: Circle, BrowserStack, SauceLabs)) build (Changes that affect the build system or \r\ntexternal dependencies (example scopes: gulp, broccoli…) ``` ## Preview ![preview](./preview.gif)
C++
UTF-8
337
3.359375
3
[]
no_license
#include <iostream> #include <cmath> using namespace std; int GetFactors(int num) { int count = 0; for(int i = 1; i <= sqrt(num) ; i ++) { if(num % i == 0) count += 2; } return count; } int main() { int n = 500; int TriNum = 1; int i = 2; while (GetFactors(TriNum) < n) { TriNum += i; i ++; } cout<<TriNum<<endl; }
Markdown
UTF-8
12,669
2.875
3
[]
no_license
# 天下为公:TCP堵塞控制 - 算法与数学之美 - CSDN博客 2017年10月27日 00:00:00[算法与数学之美](https://me.csdn.net/FnqTyr45)阅读数:169 在 TCP 协议中,我们使用连接记录 TCP 两端的状态,使用编号和分段实现了 TCP 传输的有序,使用广播窗口来实现了发送方和接收方处理能力的匹配,还使用重复发送机制来实现 TCP 传输的可靠性。最初的 TCP 协议就是由上述的几个方面构成。1980 年代,TCP 协议又引入了流量控制机制。 ****令人头痛的堵车**** 从 1980 年代开始,网络变得繁忙。许多网络中出现了大量的堵塞(congestion)。堵塞类似于现实中的堵车。网络被称为“信息高速公路”。许多 IP 包在网络中行驶,并经过一个一个像十字路口一样的路由器,直到到达目的地。一个路由器如果过度繁忙,会丢弃一些 IP 包。UDP 协议不保证传输的可靠性,所以丢失就丢失了。而 TCP 协议需要保证传输的可靠性,当包含有 TCP 片段的 IP 包丢失时,TCP 协议会重复发送 TCP 片段。于是,更多的“汽车”进入到公路中,原本繁忙的路由器变得更加繁忙,更多的 IP 包丢失。这样就构成了一个恶性循环。这样的情况被称为堵塞崩溃(congestion collapse)。每个发送方为了保证自己的发送质量而乱发车,是造成堵塞崩溃的主要原因。当时的网络中高达 90%的传输资源可能被堵塞崩溃所浪费。 为了弥补这一缺陷,从 1980 年代开始,TCP 协议中开始加入堵塞控制(congestion control)的功能,以避免堵塞崩溃的出现。多个算法被提出并实施,大大改善了网络的交通状况。流量控制类似于生活中的真实交通。现实中,当我们遇到堵车,可能就会希望兴建立交桥和高架,或者希望有一位交警来疏导交通。而 TCP 协议的堵塞控制是通过约束自己实现的。当 TCP 的发送方探测到网络交通拥堵时,会控制自己发送片段的速率,以缓解网络的交通状况,避免堵塞崩溃。简言之,TCP 协议规定了发送方需要遵守的“公德”。 我们先来说明堵塞是如何探测的。在 TCP 重新发送中,我们已经总结了两种推测 TCP 片段丢失的方法:ACK 超时和重复 ACK。一旦发送方认为 TCP 片段丢失,则认为网络中出现堵塞。另一方面,TCP 发送方是如何控制发送速率呢?TCP 协议通过控制滑窗大小来控制发送速率。在 TCP 滑窗管理中,我们已经见到了一个窗口限制,就是广播窗口大小,以实现 TCP 流量控制。TCP 还会维护一个阻塞窗口大小,以根据网络状况来调整滑窗大小。真实滑窗大小取这两个滑窗限制的最小值,从而同时满足流量控制和堵塞控制的限制。我们下面就来看一看阻塞窗口。 **阻塞窗口** 阻塞窗口总是处于两种状态的一个。这两种状态是慢起动(slow start)和堵塞避免(congestion avoidance)。下面是它们的示意图: ![0?wx_fmt=png](https://ss.csdn.net/p?http://mmbiz.qpic.cn/mmbiz_png/951TjTgiabkxywDlVox1xHvZKHUgONBZEdmhtytNME5MsbS3UzgPIZJFI176iaeVM23pM5icY0ucWFjHlDUuXpqeA/0?wx_fmt=png) 上图是概念性的。实际的实施要比上图复杂,而且根据算法不同会有不同的版本。cwnd 代表阻塞窗口大小(congestion window size)。我们以片段的个数为单位,来表示阻塞窗口大小 。实际应用中会以字节为单位,但并不影响这里的讲解。 阻塞窗口从慢启动状态开始。慢启动的特点是初始速率低,但速率不断倍增。每次进入到慢启动状态时,阻塞窗口大小都需要重置为初始值 1。发送方每接收到一个正确的 ACK,就会将阻塞窗口大小增加 1,从而实现速率的倍增。需要注意的是,由于累计 ACK,速率增长可能会小于倍增。 当阻塞窗口大小达到阈值(图中 ssthresh)时,阻塞窗口进入到阻塞避免状态。发送速率会继续增长。发送方在每个窗户所有片段成功传输后,将窗口尺寸增加 1,等效于每个往返时间增加 1。所以在阻塞避免模式下,阻塞窗口大小线性增长,增长速率慢。如果在阻塞避免下有片段丢失,重新回到慢启动状态,并将阈值更新为阻塞窗口大小的一半。 我们看到,触及阈值是从慢启动到 c 阻塞避免的切换点。而片段丢失是阻塞避免到慢启动的切换点。一开始阈值一般比较大,所以慢启动可能在切换成阻塞避免之前就丢失片段。这种情况下,慢启动会重新开始,而阈值更新为阻塞窗口大小的一半。 总的来说,发送速率总是在增长。如果片段丢失,则重置速率为 1,并快速增长。增长到一定程度,则进入到慢性增长。快速增长和慢性增长的切换点会随着网络状况更新。通过上面的机制,让发送速率处于动态平衡,不断的尝试更大值。初始时增长块,而接近饱和时增长慢。但一旦尝试过度,则迅速重置,以免造成网络负担。阻塞控制有效的提高了互联网的利用率,但依然不完善。一个常见的问题是阻塞窗口小在接近饱和时线性增长,因此对新增的网络带宽不敏感。 ****TCP 实践**** TCP 协议利用流量控制机制来实现整个网络的总体效率。到现在为止,已经讲解了 TCP 的几大模块:分段与流,滑窗,连接,流量控制,重新发送,堵塞控制。现在,我们可以在编程中实际利用一下 TCP 协议。 在 Python 中,我们可以用标准库中的 socket 包来建立 TCP 连接。这个包已经用于 UDP 协议的套接字编程,它同样可以用于 TCP 协议的套接字编程。我们需要写两个程序,分别用于 TCP 连接的服务器端和客户端。一旦连接建立,双方可以相互通信。下面是服务器端的程序。我们用 bind()方法来赋予套接字以固定的地址和端口,用 listen()方法来被动的监听该端口。当有客户尝试用 connect()方法连接的时候,服务器使用 accept()接受连接,从而建立一个 TCP 连接: > # Written by Vamei # Server side import socket # Address HOST = '' PORT = 8000 reply = 'Yes' # Configure socket s      = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) # passively wait, 3: maximum number of connections in the queue s.listen(3) # accept and establish connection conn, addr = s.accept() # receive message request    = conn.recv(1024) print 'request is: ',request print 'Connected by', addr # send message conn.sendall(reply) # close connection conn.close() 上面的程序中,socket.socket()创建一个 socket 对象,并说明 socket 使用的是 IPv4(AF_INET,IP version 4)和 TCP 协议(SOCK_STREAM)。服务器写好了,下面是客户。在客户的程序中,我们主动使用 connect()方法来搜索服务器端的 IP 地址和端口,以便客户可以找到服务器,并建立连接: > # Written by Vamei # Client side import socket # Address HOST = '172.20.202.155' PORT = 8000 request = 'can you hear me?' # configure socket s       = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) # send message s.sendall(request) # receive message reply   = s.recv(1024) print 'reply is: ',reply # close connection s.close() TCP 协议是双向的。因此,我们在连接两端都可以调用 recv()方法来接收信息,调用 sendall()方法来发送信息。这样,我们就可以在分处于两台计算机的两个进程间进行通信了。当通信结束的时候,我们使用 close()方法来关闭 TCP 连接。为了展示网络通信,上面程序最好运行于两台电脑。但如果没有两台计算机做实验,也可以将客户端的 IP 改为 127.0.0.1。这是个特殊的 IP 地址,指向主机自身。这样,我们在同一台电脑上建立了 TCP 连接。 ****总结**** 流量控制要求参与 TCP 通信的各方守公德,从而提高了 TCP 通信的整体效率。这一篇的最后,还有一个实际建立 TCP 连接的例子,用 Python 语言实现。到了这里,TCP 协议的介绍就可以告一段落了。下一章我们将进入应用层。 ☞  [哈尔莫斯:怎样做数学研究](http://mp.weixin.qq.com/s?__biz=MzA5ODUxOTA5Mg==&mid=2652554187&idx=1&sn=35143b89b06fe4f5273f210b2d6a7c91&chksm=8b7e3290bc09bb86f7bb3f158d993df3f019a7e9ce3bc8897e164e35a2ebe5a4e0bdcc111089&scene=21#wechat_redirect) ☞  [扎克伯格2017年哈佛大学毕业演讲](http://mp.weixin.qq.com/s?__biz=MzA5ODUxOTA5Mg==&mid=2652554187&idx=2&sn=c75293463823e4d6769638e54b64f3ec&chksm=8b7e3290bc09bb86dc1e3f8e78d0b6de8811d75f3dcb092766fcb8ba0bab1cd9ba1ddfcef3b9&scene=21#wechat_redirect) ☞  [线性代数在组合数学中的应用](http://mp.weixin.qq.com/s?__biz=MzA5ODUxOTA5Mg==&mid=2652554141&idx=1&sn=74a74c4e4d08eba0dd734528aa0b08e7&chksm=8b7e32c6bc09bbd073b34c22004ac6e4d99c8a0caa64c7d3dbaa8fd55e6ef1fc87ed545b8b7e&scene=21#wechat_redirect) ☞  [你见过真的菲利普曲线吗?](http://mp.weixin.qq.com/s?__biz=MzA5ODUxOTA5Mg==&mid=2652554105&idx=1&sn=224ab0d38fb57facea70081385360d58&chksm=8b7e3222bc09bb34d3b6df665087e64b233778ed427598d08e809f96261e898c1c0de6188bbc&scene=21#wechat_redirect) ☞  [支持向量机(SVM)的故事是这样子的](http://mp.weixin.qq.com/s?__biz=MzA5ODUxOTA5Mg==&mid=2652554096&idx=1&sn=46783e6ace661a3ccbd8a6e00fb17bf9&chksm=8b7e322bbc09bb3d73dc240f2280bddf2ef8b7824a459a24bd7f6eeadd60edb96e690d467f6e&scene=21#wechat_redirect) ☞  [深度神经网络中的数学,对你来说会不会太难?](http://mp.weixin.qq.com/s?__biz=MzA5ODUxOTA5Mg==&mid=2652554077&idx=2&sn=3ecd63f2205fd59df8c360c97c943ef6&chksm=8b7e3206bc09bb10a36b09547efe0c54f41423b180622c1fdc7f14747ccc8f8fecee3a12e2cd&scene=21#wechat_redirect) ☞  [编程需要知道多少数学知识?](http://mp.weixin.qq.com/s?__biz=MzA5ODUxOTA5Mg==&mid=2652554062&idx=1&sn=17f0a88d5e15d1adfc29c690a0b1b89b&chksm=8b7e3215bc09bb038c6caa59d0f49cedd929f9be1104beea3411186cf4c81de69efc71a17883&scene=21#wechat_redirect) ☞  [陈省身——什么是几何学](http://mp.weixin.qq.com/s?__biz=MzA5ODUxOTA5Mg==&mid=2652553994&idx=2&sn=74f67a1a3ac5c705f51f2ba619b717f6&chksm=8b7e3251bc09bb47dce73319948780081efe0333ffae99ea04a9eeabbcfcb38a29b4b73fb7c1&scene=21#wechat_redirect) ☞  [模式识别研究的回顾与展望](http://mp.weixin.qq.com/s?__biz=MzA5ODUxOTA5Mg==&mid=2652553949&idx=2&sn=d171680964df774397efd9db81c00347&chksm=8b7e3386bc09ba90bf0f6e1cabf82ba86ff94630cb5ee2e0f14ff9455db52be32ddbc289d237&scene=21#wechat_redirect) ☞  [曲面论](http://mp.weixin.qq.com/s?__biz=MzA5ODUxOTA5Mg==&mid=2652553747&idx=1&sn=e25f866d510cf2338b6d9e1b32bafb62&chksm=8b7e3348bc09ba5ea1caaf2a7bfcd80a7e7559b1983e473eda2206e56df7f38ef3cecf2f77c7&scene=21#wechat_redirect) ☞  [自然底数e的意义是什么?](http://mp.weixin.qq.com/s?__biz=MzA5ODUxOTA5Mg==&mid=2652553811&idx=1&sn=000305074471c3d4c681c9cfd4e4bc93&chksm=8b7e3308bc09ba1e3043f5568a3a75a045285a1de97e4da36918bac68e7c6d579ad5d8cc25ab&scene=21#wechat_redirect) ☞  [如何向5岁小孩解释什么是支持向量机(SVM)?](http://mp.weixin.qq.com/s?__biz=MzA5ODUxOTA5Mg==&mid=2652553670&idx=1&sn=ea75a448c016f7229e4cb298f6017614&chksm=8b7e309dbc09b98bc622acdf1223c7c2f743609d0a577dd43c9e9d98ab4da4314be7c1002bd5&scene=21#wechat_redirect) ☞  [华裔天才数学家陶哲轩自述](http://mp.weixin.qq.com/s?__biz=MzA5ODUxOTA5Mg==&mid=2652553646&idx=2&sn=bbf8f1be1ca1c66ad3f3270babea6885&chksm=8b7e30f5bc09b9e3e1a4fa735412e2fcb20df9e78f2f346bf578018ceab77de6326095d1bf71&scene=21#wechat_redirect) ☞  [代数,分析,几何与拓扑,现代数学的三大方法论](http://mp.weixin.qq.com/s?__biz=MzA5ODUxOTA5Mg==&mid=2652553596&idx=1&sn=bc5064e871831f862db6d19c3de6327e&chksm=8b7e3027bc09b93194fa09b25e2df400421c062927bb9120912875f8aaf0bb25553fc8f51e3b&scene=21#wechat_redirect) ![0?wx_fmt=gif](https://ss.csdn.net/p?http://mmbiz.qpic.cn/mmbiz_gif/951TjTgiabkwJ4BpvBcQhGAbtWZZvV69s7GickZGibsKgYkTQkiaZfLYOmGS9iaaoibadibGJhT18OVZkfeJmCSUSD0zw/0?wx_fmt=gif) 算法数学之美微信公众号欢迎赐稿 稿件涉及数学、物理、算法、计算机、编程等相关领域。 稿件一经采用,我们将奉上稿酬。 投稿邮箱:math_alg@163.com 商务合作:微信号hengzi5809 ![0?wx_fmt=gif](https://ss.csdn.net/p?http://mmbiz.qpic.cn/mmbiz_gif/951TjTgiabkxN5SJPzhu6icTXrIpMZqSdFzG0y6ib1c9enWGK3GxfHTRIN7ich2kzqepNvMHfktp4Ir88ibolsDBuhQ/0?wx_fmt=gif)
Markdown
UTF-8
5,860
2.6875
3
[]
no_license
# CnsOpenapiRubyClient::CorporationsApi All URIs are relative to *https://api.houjin-bangou.nta.go.jp/4* | Method | HTTP request | Description | | ------ | ------------ | ----------- | | [**get_corporations**](CorporationsApi.md#get_corporations) | **GET** /name | 法人名を指定しリクエストすることで、指定した法人名の基本3情報及び付随する情報を取得することができます。 | ## get_corporations > <ResponseWrapper> get_corporations(name, type, opts) 法人名を指定しリクエストすることで、指定した法人名の基本3情報及び付随する情報を取得することができます。 法人名による法人情報の取得 ### Examples ```ruby require 'time' require 'cns_openapi_ruby_client' # setup authorization CnsOpenapiRubyClient.configure do |config| # Configure API key authorization: id config.api_key['id'] = 'YOUR API KEY' # Uncomment the following line to set a prefix for the API key, e.g. 'Bearer' (defaults to nil) # config.api_key_prefix['id'] = 'Bearer' end api_instance = CnsOpenapiRubyClient::CorporationsApi.new name = 'name_example' # String | 取得の対象とする法人名を URL エンコード(UTF-8)した値をセットします。 type = '12' # String | リクエストに対して応答するデータのファイル形式と文字コードを指定します。 opts = { mode: 1, # Integer | 検索方式を指定できます。 指定しない場合は、「1」(前方一致検索)で処理します。 target: 1, # Integer | 検索対象を指定できます。 指定しない場合は、「1」(JIS 第一・第二水準)で処理します。 address: 'address_example', # String | 国内所在地の都道府県コード又は 都道府県コードと市区町村コードを組み合わせたコードのいずれかを指定できます。 市区町村コードのみではエラー(エラーコード 051)となります。 kind: '01', # String | 法人種別を指定できます。 change: 0, # Integer | 法人名や所在地の変更があった法人等に ついて過去の情報を含めて検索するかどうかを指定できます。 close: 0, # Integer | 登記記録の閉鎖等があった法人等の情報を取得するかどうかを指定できます。 from: 'from_example', # String | 取得の対象とする法人番号指定年月日の開始日を指定できます。 to: 'to_example', # String | 取得の対象とする法人番号指定年月日の終了日を指定できます。 divide: 56 # Integer | 分割番号を指定できます。 指定しない場合は、「1」で処理します。 } begin # 法人名を指定しリクエストすることで、指定した法人名の基本3情報及び付随する情報を取得することができます。 result = api_instance.get_corporations(name, type, opts) p result rescue CnsOpenapiRubyClient::ApiError => e puts "Error when calling CorporationsApi->get_corporations: #{e}" end ``` #### Using the get_corporations_with_http_info variant This returns an Array which contains the response data, status code and headers. > <Array(<ResponseWrapper>, Integer, Hash)> get_corporations_with_http_info(name, type, opts) ```ruby begin # 法人名を指定しリクエストすることで、指定した法人名の基本3情報及び付随する情報を取得することができます。 data, status_code, headers = api_instance.get_corporations_with_http_info(name, type, opts) p status_code # => 2xx p headers # => { ... } p data # => <ResponseWrapper> rescue CnsOpenapiRubyClient::ApiError => e puts "Error when calling CorporationsApi->get_corporations_with_http_info: #{e}" end ``` ### Parameters | Name | Type | Description | Notes | | ---- | ---- | ----------- | ----- | | **name** | **String** | 取得の対象とする法人名を URL エンコード(UTF-8)した値をセットします。 | | | **type** | **String** | リクエストに対して応答するデータのファイル形式と文字コードを指定します。 | [default to &#39;12&#39;] | | **mode** | **Integer** | 検索方式を指定できます。 指定しない場合は、「1」(前方一致検索)で処理します。 | [optional][default to 1] | | **target** | **Integer** | 検索対象を指定できます。 指定しない場合は、「1」(JIS 第一・第二水準)で処理します。 | [optional][default to 1] | | **address** | **String** | 国内所在地の都道府県コード又は 都道府県コードと市区町村コードを組み合わせたコードのいずれかを指定できます。 市区町村コードのみではエラー(エラーコード 051)となります。 | [optional] | | **kind** | **String** | 法人種別を指定できます。 | [optional] | | **change** | **Integer** | 法人名や所在地の変更があった法人等に ついて過去の情報を含めて検索するかどうかを指定できます。 | [optional][default to 0] | | **close** | **Integer** | 登記記録の閉鎖等があった法人等の情報を取得するかどうかを指定できます。 | [optional][default to 1] | | **from** | **String** | 取得の対象とする法人番号指定年月日の開始日を指定できます。 | [optional] | | **to** | **String** | 取得の対象とする法人番号指定年月日の終了日を指定できます。 | [optional] | | **divide** | **Integer** | 分割番号を指定できます。 指定しない場合は、「1」で処理します。 | [optional] | ### Return type [**ResponseWrapper**](ResponseWrapper.md) ### Authorization [id](../README.md#id) ### HTTP request headers - **Content-Type**: Not defined - **Accept**: application/xml, application/json
Java
UTF-8
2,398
2.3125
2
[]
no_license
package com.yalantis.ucrop.task; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; public class Converter extends AsyncTask<Void, Void, Void> { private static final String TAG = "FFMpeg"; private String cmd[] = null; private Process p = null; private Context context; private String path, output; public Converter(String path, String output, Context context) { this.path = path; this.output = output; this.context = context; } @Override protected void onPreExecute() { super.onPreExecute(); Context m_context = context; //First get the absolute path to the file File folder = m_context.getFilesDir(); String fullpath = ""; String filefolder = null; try { filefolder = folder.getCanonicalPath(); if (!filefolder.endsWith("/")) filefolder += "/"; fullpath = filefolder + "ffmpeg"; String cmd[] = new String[]{fullpath, "-i", path, "-vcodec", "libx264", "-b:v", "1000k", "-profile:v", "BaseLine", "-level", "3.0", "-acodec", "copy", "-f", "mp4", "-preset", "ultrafast", "-tune", "film", "-r", "30", "-threads", "20", "-strict", "experimental", "-vsync", "2", output}; p = Runtime.getRuntime().exec(cmd); } catch (IOException e) { e.printStackTrace(); } } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); } @Override protected Void doInBackground(Void... params) { String line; StringBuilder log = new StringBuilder(); BufferedReader in = new BufferedReader( new InputStreamReader(p.getErrorStream()) ); try { p.waitFor(); while ((line = in.readLine()) != null) { log.append(line).append("\n"); Log.d(TAG, "onActivityResult: " + log.toString()); } in.close(); Log.d(TAG, "onActivityResult: " + log.toString()); } catch (IOException | InterruptedException e) { e.printStackTrace(); } return null; } }
Markdown
UTF-8
12,328
3.265625
3
[ "MIT" ]
permissive
**1. Unsupervised Learning cheatsheet** &#10230; Pense-bête d'apprentissage non-supervisé <br> **2. Introduction to Unsupervised Learning** &#10230; Introduction à l'apprentissage non-supervisé <br> **3. Motivation ― The goal of unsupervised learning is to find hidden patterns in unlabeled data {x(1),...,x(m)}.** &#10230; Motivation ― Le but de l'apprentissage non-supervisé est de trouver des formes cachées dans un jeu de données non-labelées {x(1),...,x(m)}. <br> **4. Jensen's inequality ― Let f be a convex function and X a random variable. We have the following inequality:** &#10230; Inégalité de Jensen ― Soit f une fonction convexe et X une variable aléatoire. On a l'inégalité suivante : <br> **5. Clustering** &#10230; Partitionnement <br> **6. Expectation-Maximization** &#10230; Espérance-Maximisation <br> **7. Latent variables ― Latent variables are hidden/unobserved variables that make estimation problems difficult, and are often denoted z. Here are the most common settings where there are latent variables:** &#10230; Variables latentes ― Les variables latentes sont des variables cachées/non-observées qui posent des difficultés aux problèmes d'estimation, et sont souvent notées z. Voici les cadres dans lesquelles les variables latentes sont le plus fréquemment utilisées : <br> **8. [Setting, Latent variable z, Comments]** &#10230; [Cadre, Variable latente z, Commentaires] <br> **9. [Mixture of k Gaussians, Factor analysis]** &#10230; [Mixture de k gaussiennes, Analyse factorielle] <br> **10. Algorithm ― The Expectation-Maximization (EM) algorithm gives an efficient method at estimating the parameter θ through maximum likelihood estimation by repeatedly constructing a lower-bound on the likelihood (E-step) and optimizing that lower bound (M-step) as follows:** &#10230; Algorithme ― L'algorithme d'espérance-maximisation (EM) est une méthode efficace pour estimer le paramètre θ. Elle passe par le maximum de vraisemblance en construisant un borne inférieure sur la vraisemblance (E-step) et optimisant cette borne inférieure (M-step) de manière successive : <br> **11. E-step: Evaluate the posterior probability Qi(z(i)) that each data point x(i) came from a particular cluster z(i) as follows:** &#10230; E-step : Évaluer la probabilité postérieure Qi(z(i)) que chaque point x(i) provienne d'une partition particulière z(i) de la manière suivante : <br> **12. M-step: Use the posterior probabilities Qi(z(i)) as cluster specific weights on data points x(i) to separately re-estimate each cluster model as follows:** &#10230; M-step : Utiliser les probabilités postérieures Qi(z(i)) en tant que coefficients propres aux partitions sur les points x(i) pour ré-estimer séparemment chaque modèle de partition de la manière suivante : <br> **13. [Gaussians initialization, Expectation step, Maximization step, Convergence]** &#10230; [Initialisation de gaussiennes, Étape d'espérance, Étape de maximisation, Convergence] <br> **14. k-means clustering** &#10230; Partitionnement k-means <br> **15. We note c(i) the cluster of data point i and μj the center of cluster j.** &#10230; On note c(i) la partition du point i et μj le centre de la partition j. <br> **16. Algorithm ― After randomly initializing the cluster centroids μ1,μ2,...,μk∈Rn, the k-means algorithm repeats the following step until convergence:** &#10230; Algorithme ― Après avoir aléatoirement initialisé les centroïdes de partitions μ1,μ2,...,μk∈Rn, l'algorithme k-means répète l'étape suivante jusqu'à convergence : <br> **17. [Means initialization, Cluster assignment, Means update, Convergence]** &#10230; [Initialisation des moyennes, Assignation de la partition, Mise à jour des moyennes, Convergence] <br> **18. Distortion function ― In order to see if the algorithm converges, we look at the distortion function defined as follows:** &#10230; Fonction de distortion ― Pour voir si l'algorithme converge, on regarde la fonction de distortion définie de la manière suivante : <br> **19. Hierarchical clustering** &#10230; Regroupement hiérarchique <br> **20. Algorithm ― It is a clustering algorithm with an agglomerative hierarchical approach that build nested clusters in a successive manner.** &#10230; Algorithme ― C'est un algorithme de partitionnement avec une approche hiérarchique qui construit des partitions intriqués de manière successive. <br> **21. Types ― There are different sorts of hierarchical clustering algorithms that aims at optimizing different objective functions, which is summed up in the table below:** &#10230; Types ― Il y a différents types d'algorithme de regroupement hiérarchique qui ont pour but d'optimiser différents fonctions objectif, récapitulés dans le tableau ci-dessous : <br> **22. [Ward linkage, Average linkage, Complete linkage]** &#10230; [Ward linkage, Average linkage, Complete linkage] <br> **23. [Minimize within cluster distance, Minimize average distance between cluster pairs, Minimize maximum distance of between cluster pairs]** &#10230; [Minimiser la distance au sein d'une partition, Minimiser la distance moyenne entre chaque paire de partitions, Minimiser la distance maximale entre les paires de partition] <br> **24. Clustering assessment metrics** &#10230; Indicateurs d'évaluation de clustering <br> **25. In an unsupervised learning setting, it is often hard to assess the performance of a model since we don't have the ground truth labels as was the case in the supervised learning setting.** &#10230; Dans le cadre de l'apprentissage non-supervisé, il est souvent difficile d'évaluer la performance d'un modèle vu que les vrais labels ne sont pas connus (contrairement à l'apprentissage supervisé). <br> **26. Silhouette coefficient ― By noting a and b the mean distance between a sample and all other points in the same class, and between a sample and all other points in the next nearest cluster, the silhouette coefficient s for a single sample is defined as follows:** &#10230; Coefficient silhouette ― En notant a et b la distance moyenne entre un échantillon et tous les autres points d'une même classe, et entre un échantillon et tous les autres points de la prochaine partition la plus proche, le coefficient silhouette s d'un échantillon donné est défini de la manière suivante : <br> **27. Calinski-Harabaz index ― By noting k the number of clusters, Bk and Wk the between and within-clustering dispersion matrices respectively defined as** &#10230; Index de Calinski-Harabaz ― En notant k le nombre de partitions, Bk et Wk les matrices de dispersion entre-partitions et au sein d'une même partition sont définis respectivement par : <br> **28. the Calinski-Harabaz index s(k) indicates how well a clustering model defines its clusters, such that the higher the score, the more dense and well separated the clusters are. It is defined as follows:** &#10230; l'index de Calinski-Harabaz s(k) renseigne sur la qualité des partitions, de sorte à ce qu'un score plus élevé indique des partitions plus denses et mieux séparées entre elles. Il est défini par : <br> **29. Dimension reduction** &#10230; Réduction de dimension <br> **30. Principal component analysis** &#10230; Analyse des composantes principales <br> **31. It is a dimension reduction technique that finds the variance maximizing directions onto which to project the data.** &#10230; C'est une technique de réduction de dimension qui trouve les directions maximisant la variance, vers lesquelles les données sont projetées. <br> **32. Eigenvalue, eigenvector ― Given a matrix A∈Rn×n, λ is said to be an eigenvalue of A if there exists a vector z∈Rn∖{0}, called eigenvector, such that we have:** &#10230; Valeur propre, vecteur propre ― Soit une matrice A∈Rn×n, λ est dit être une valeur propre de A s'il existe un vecteur z∈Rn∖{0}, appelé vecteur propre, tel que l'on a : <br> **33. Spectral theorem ― Let A∈Rn×n. If A is symmetric, then A is diagonalizable by a real orthogonal matrix U∈Rn×n. By noting Λ=diag(λ1,...,λn), we have:** &#10230; Théorème spectral ― Soit A∈Rn×n. Si A est symmétrique, alors A est diagonalisable par une matrice réelle orthogonale U∈Rn×n. En notant Λ=diag(λ1,...,λn), on a : <br> **34. diagonal** &#10230; diagonal <br> **35. Remark: the eigenvector associated with the largest eigenvalue is called principal eigenvector of matrix A.** &#10230; Remarque : le vecteur propre associé à la plus grande valeur propre est appelé le vecteur propre principal de la matrice A. <br> **36. Algorithm ― The Principal Component Analysis (PCA) procedure is a dimension reduction technique that projects the data on k dimensions by maximizing the variance of the data as follows:** &#10230; Algorithme ― La procédure d'analyse des composantes principales (en anglais *PCA - Principal Component Analysis*) est une technique de réduction de dimension qui projette les données sur k dimensions en maximisant la variance des données de la manière suivante : <br> **37. Step 1: Normalize the data to have a mean of 0 and standard deviation of 1.** &#10230; Étape 1 : Normaliser les données pour avoir une moyenne de 0 et un écart-type de 1. <br> **38. Step 2: Compute Σ=1mm∑i=1x(i)x(i)T∈Rn×n, which is symmetric with real eigenvalues.** &#10230; Étape 2 : Calculer Σ=1mm∑i=1x(i)x(i)T∈Rn×n, qui est symmétrique et aux valeurs propres réelles. <br> **39. Step 3: Compute u1,...,uk∈Rn the k orthogonal principal eigenvectors of Σ, i.e. the orthogonal eigenvectors of the k largest eigenvalues.** &#10230; Étape 3 : Calculer u1,...,uk∈Rn les k valeurs propres principales orthogonales de Σ, i.e. les vecteurs propres orthogonaux des k valeurs propres les plus grandes. <br> **40. Step 4: Project the data on spanR(u1,...,uk).** &#10230; Étape 4 : Projeter les données sur spanR(u1,...,uk). <br> **41. This procedure maximizes the variance among all k-dimensional spaces.** &#10230; Cette procédure maximise la variance sur tous les espaces à k dimensions. <br> **42. [Data in feature space, Find principal components, Data in principal components space]** &#10230; [Données dans l'espace initial, Trouver les composantes principales, Données dans l'espace des composantes principales] <br> **43. Independent component analysis** &#10230; Analyse en composantes indépendantes <br> **44. It is a technique meant to find the underlying generating sources.** &#10230; C'est une technique qui vise à trouver les sources génératrices sous-jacentes. <br> **45. Assumptions ― We assume that our data x has been generated by the n-dimensional source vector s=(s1,...,sn), where si are independent random variables, via a mixing and non-singular matrix A as follows:** &#10230; Hypothèses ― On suppose que nos données x ont été générées par un vecteur source à n dimensions s=(s1,...,sn), où les si sont des variables aléatoires indépendantes, par le biais d'une matrice de mélange et inversible A de la manière suivante : <br> **46. The goal is to find the unmixing matrix W=A−1.** &#10230; Le but est de trouver la matrice de démélange W=A−1. <br> **47. Bell and Sejnowski ICA algorithm ― This algorithm finds the unmixing matrix W by following the steps below:** &#10230; Algorithme d'ICA de Bell and Sejnowski ― Cet algorithme trouve la matrice de démélange W en suivant les étapes ci-dessous : <br> **48. Write the probability of x=As=W−1s as:** &#10230; Écrire la probabilité de x=As=W−1s par : <br> **49. Write the log likelihood given our training data {x(i),i∈[[1,m]]} and by noting g the sigmoid function as:** &#10230; Écrire la log vraisemblance de notre ensemble d'apprentissage {x(i),i∈[[1,m]]} et en notant g la fonction sigmoïde par : <br> **50. Therefore, the stochastic gradient ascent learning rule is such that for each training example x(i), we update W as follows:** &#10230; Par conséquent, l'algorithme du gradient stochastique est tel que pour chaque example de ensemble d'apprentissage x(i), on met à jour W de la manière suivante :
Python
UTF-8
5,167
3.5
4
[]
no_license
# Imports JSON library import json # Imports ZIP library from zipfile import ZipFile # Imports the remove function from os import remove class Document(object): def __init__(self): # Flag to state whether data is loaded or not self.is_loaded = False # Initializes the source attribute self.source = None # Initializes the url attribute self.url = None # Initializes the language attribute self.lang = None # Initializes the date attribute self.date = None # Initializes the author attribute self.author = None # Initializes the keyword attribute self.keyword = None # Initializes the title attribute self.title = None # Initializes the text attribute self.text = None # Initializes the ID attribute self.id = None def load_from_json(self, path): """ Initializes attributes from JSON file. Args: path (str): path to JSON file with document information. Raises: IOError: if the file does not exists or can not be opened. JSONDecodeError: if the file is not a valid JSON file. """ # Checks if file is zipped or not if path.endswith(".zip"): # Opens the ZIP file archive = ZipFile(path, "r") # Gets the filename from file filename = archive.infolist()[0].filename # Reads the file archive = archive.read(filename) # Loads the archive as JSON input_data = json.loads(archive) elif path.endswith(".json"): # Opens the file in read mode input_file = open(path, "r") # Reads the file as JSON format input_data = json.load(input_file) # Sets the source attribute self.source = input_data["source"] # Sets URL attribute self.url = input_data["url"] # Sets the language attribute self.lang = input_data["lang"] # Sets the date attribute self.date = input_data["date"] # Sets the author attribute self.author = input_data["author"] # Sets the keyword attribute self.keyword = input_data["keyword"] # Sets the title attribute self.title = input_data["title"] # Sets the text attribute self.text = input_data["text"] # Sets the ID attribute self.id = input_data["id"] # Sets loaded flag on True self.is_loaded = True def load_from_dict(self, parameters): """ Initializes attributes from dictionary. """ # Sets the set attribute self.source = parameters["source"] # Sets the URL attribute self.url = parameters["url"] # Sets the language attribute self.lang = parameters["lang"] # Sets the date attribute self.date = parameters["date"] # Sets the author attribtue self.author = parameters["author"] # Sets the keyword attribtue self.keyword = parameters["keyword"] # Sets the title attribute self.title = parameters["title"] # Sets the text attribute self.text = parameters["text"] # Sets the ID attribute self.id = parameters["id"] def dump_to_json(self, path): """ Saves the object attributes into a JSON file. Args: path (str): path for the new JSON file. If the file exists it will be replaced with a new file. """ # Creates the attributes dictionary attributes_dict = { "source": self.source, "url": self.url, "lang": self.lang, "date": self.date, "author": self.author, "keyword": self.keyword, "title": self.title, "text": self.text, "id": self.id } # Defines the JSON path json_path = path + ".json" # Defines the ZIP file zip_path = path + ".zip" # Opens the output file with open(json_path, "w") as output_file: # Dumps attribute dictionary into a JSON file json_string = json.dump(attributes_dict, output_file, indent=4) # Zips the output file ZipFile(zip_path, mode="w").write(json_path) # Removes the original file remove(json_path) def __eq__(self, other): """ Checks if another object is equal to current. Performs the comparison between two objects that might be from the same class and equal. The comparison starts by checking that both objects are form the Document class. Then it checks that the 'id' attribute is equal between both objects. Args: other (Document): object that will be compared to current instance of Document class. Returns: bool: True if both objects are equal. False otherwise. Raises: Exception: if the other object is not an instance of the Document class. Exception: if either the current or the other instance data was not loaded before performing the comparison. """ # Checks if other is instance of Document class if not isinstance(other, Document): raise Exception("Other object is not instance of Document class.") # Checks if instace was loaded if not self.is_loaded: raise Exception("Current instance data was not loaded.") # Checks if other object data is loaded if not other.is_loaded: raise Exception("Other instance data was not loaded.") # Checks if ID is equal between objects elif self.id == other.id: # Returns true if both IDs are equal return True else: # Returns false if IDs are different return False def __str__(self): """ Prints string representation of Document object. """ return self.id
Java
UTF-8
1,627
2.1875
2
[]
no_license
package com.juran.quote.resource.v1; import com.juran.core.log.contants.LoggerName; import com.juran.core.log.eventlog.aop.RestLog; import com.juran.quote.bean.exception.QuoteException; import com.juran.quote.bean.response.CommonRespBean; import com.juran.quote.service.QuoteService; import io.swagger.annotations.*; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @Api(value = "第三方对接服务") @RestLog @Component @Path("/v1/thirdparty") @Produces(MediaType.APPLICATION_JSON) public class ThirdPartyResource { protected final Logger logger = LoggerFactory.getLogger(LoggerName.INFO); @Autowired private QuoteService quoteService; @ApiOperation(value = "报价结果接口", notes = "报价结果接口获取报价详情") @GET @Path("/quote/{designId}") public Response getCaseQuotationInfo(@ApiParam(value = "案例id") @PathParam("designId") String designId) { try { CommonRespBean quoteSummary = quoteService.getCaseQuotation(designId); return Response.status(Response.Status.OK).entity(quoteSummary).build(); } catch (QuoteException e) { CommonRespBean resp = new CommonRespBean(new CommonRespBean.Status(CommonRespBean.Status.EXCEPTION, e.getErrorMsg())); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(resp).build(); } } }
SQL
UTF-8
1,644
4.21875
4
[]
no_license
--ejercicio1 select employee_id,first_name , last_name from employees where department_id in (select department_id from employees where job_id in (select job_id from jobs where job_title like '%Clerk%')); select * from employees; select * from jobs; --Ejercicio 2 select e.first_name,e.salary,d.department_id from employees e full join departments d on e.department_id= d.department_id; select department_id, avg(salary) from employees group by department_id; SELECT E.FIRST_NAME NOMBRE,E.LAST_NAME APELLIDO,E.SALARY SALARIO,D.DEPARTMENT_ID, M.prom FROM (select department_id, avg(salary) as prom from employees group by department_id) M ,EMPLOYEES E inner join departments d on e.department_id=d.department_id WHERE e.salary>m.prom group BY E.FIRST_NAME,E.LAST_NAME,E.SALARY,D.DEPARTMENT_ID, M.prom ; SELECT FIRST_NAME AS NOMBRE,LAST_NAME AS APELLIDO,SALARY AS SALARIO,M.DEPARTMENT_ID, M.MINIMO_SALARIO FROM EMPLOYEES E, (SELECT DEPARTMENT_ID,MIN(SALARY) AS MINIMO_SALARIO FROM EMPLOYEES GROUP BY DEPARTMENT_ID) M WHERE E.DEPARTMENT_ID=M.DEPARTMENT_ID ORDER BY E.DEPARTMENT_ID; --Ejercicio 3 select first_name,last_name, salary,min(salary) from employees inner join departments on employees.department_id= departments.department_id group by first_name,last_name,salary; --Ejercicio 4 select department_id from employees group by department_id having max(salary)>10000; 100,30,90,20,110,80 max 90,110 avg
C
UTF-8
247
3.15625
3
[]
no_license
#include<stdio.h> int main() { unsigned long int a, b; while(scanf("%lu %lu", &a, &b) == 2) { if(a > b) printf("%lu", a - b); else printf("%lu", b - a); printf("\n"); } return 0; }
Java
UTF-8
1,782
2.171875
2
[]
no_license
/* * Copyright 2013 Worldpay * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations under the License. */ package com.worldpay.sdk.util; import com.worldpay.gateway.clearwater.client.core.exception.WorldpayException; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; public class HttpUrlConnection { public static HttpURLConnection getConnection(String fullUri) { HttpURLConnection httpURLConnection; URL url; try { url = new URL(fullUri); httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setDoOutput(true); httpURLConnection.setDoInput(true); httpURLConnection.setConnectTimeout(WorldpayLibraryConstants.CONNECTION_TIMEOUT); httpURLConnection.setReadTimeout(WorldpayLibraryConstants.SOCKET_TIMEOUT); httpURLConnection .setRequestProperty(WorldpayLibraryConstants.ACCEPT, WorldpayLibraryConstants.APPLICATION_JSON); httpURLConnection .setRequestProperty(WorldpayLibraryConstants.CONTENT_TYPE, WorldpayLibraryConstants.APPLICATION_JSON); } catch (IOException e) { throw new WorldpayException(e.getMessage()); } return httpURLConnection; } }
Java
GB18030
13,794
2.234375
2
[]
no_license
package com.non.packer; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Utils { public static final String AM_XML = "tmp/out/AndroidManifest.xml"; public static final String OUT_DIR = "tmp\\out"; public static final String TMP_DIR = "tmp"; public static final String OUTPUT_APK_DIR = "tmp\\t.apk"; private static String SIGNED_APK; public static final String TMP_APK_DIR = "tmp\\out.apk"; private static final String APP_NAME = "APPLICATION_CLASS_NAME"; private static final String APP_VALUE = "com.reinforce.app.MShellApplication"; /** * byte,ʱûʵ */ public static byte[] encrypt(byte[] bytes) { return bytes; } /** * ļжȡbytes */ public static byte[] readbytes(String filedir) throws IOException { FileInputStream fis = new FileInputStream(new File(filedir)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] cache = new byte[1024]; int len = 0; while ((len = fis.read(cache)) != -1) { baos.write(cache, 0, len);// Ϊһһreadװcache,ַʽȷὫcacheĩβд } fis.close(); baos.close(); return baos.toByteArray(); } /** * byteдļ * * @param dstdex * Ҫдbytes * @param clsdex * 洢ļ */ public static void write2file(byte[] dstdex, String clsdex) throws Exception { File file = new File(clsdex); if (file.exists()) { file.delete(); } file.createNewFile(); FileOutputStream fos = new FileOutputStream(file); fos.write(dstdex); fos.flush(); fos.close(); } /** * apkļ */ public static void disassmApk(String apkpath) throws Exception { File f = new File(OUT_DIR); if (f.exists()) deleteAll(f);// Ŀ¼,ɾ String cmd = "java -jar -Duser.language=en lib\\apktool.jar d " + apkpath + " -o " + OUT_DIR;// javaִapktool.jarapkļ Runtime run = Runtime.getRuntime(); Process process = run.exec(cmd); process.waitFor(); savelog("---------------------------------------------\n" + "disassembling apk...\n"); savelog(process); process.destroy(); } /** * شĿ¼Ϊapkļ */ public static void compileApk() throws Exception { String cmd = "java -jar -Duser.language=en lib\\apktool.jar b " + OUT_DIR + " -o " + OUTPUT_APK_DIR;// javaִapktool.jarش Runtime run = Runtime.getRuntime(); Process process = run.exec(cmd); process.waitFor(); savelog("---------------------------------------------\n" + "compiling apk...\n"); savelog(process); process.destroy(); } public static void savelog(Process process) throws Exception { BufferedInputStream bis = new BufferedInputStream( process.getInputStream()); BufferedInputStream error = new BufferedInputStream( process.getErrorStream()); // شĵϢļ,Ա鿴־ File f = new File("log.txt"); FileOutputStream fos = new FileOutputStream(f, true); copy(bis, fos); copy(error, fos); bis.close(); error.close(); fos.close(); } public static void savelog(String str) throws Exception { // Ϣļ,Ա鿴־ File f = new File("log.txt"); FileOutputStream fos = new FileOutputStream(f, true); fos.write(str.getBytes("utf-8")); fos.flush(); fos.close(); } /** * */ public static void copy(InputStream is, OutputStream os) throws IOException { int len = 0; byte[] cache = new byte[8192]; while ((len = is.read(cache)) > 0) { os.write(cache, 0, len); } os.flush(); } /** * ļ */ public static void copy(String src, String dst) throws IOException { System.out.println("copy file from " + src + " to " + dst); BufferedInputStream bis = new BufferedInputStream(new FileInputStream( new File(src)));// BufferedInputStreamĿΪ߶дٶ(ȽļBufferedInputStreamĻ,Ĭ8192,ٽд) FileOutputStream fos = new FileOutputStream(new File(dst)); int len = 0; byte[] cache = new byte[8192]; while ((len = bis.read(cache)) > 0) { fos.write(cache, 0, len); } bis.close(); fos.flush(); fos.close(); System.out.println("copy file finished."); } /** * Ӹapkжȡclasses.dex,Ϊorigin.dex */ public static void readDex(String apkpath, String filename) throws Exception { savelog("---------------------------------------------\n" + "reading dex...\n"); SIGNED_APK = "packed-" + apkpath;// յapkļ File file = new File(apkpath); ZipInputStream zis = new ZipInputStream(new BufferedInputStream( new FileInputStream(file))); String name;// zipѹеļ // ѹвclasses.dex,ҵ˾ͼһ do { ZipEntry entry = zis.getNextEntry(); name = entry.getName(); } while (!name.equals(filename)); // ½origin.dexļ,classes.dexļ File originfile = new File(MergeDexs.ORIGIN_DEX); if (!originfile.getParentFile().exists()) { System.out.println(originfile.getParentFile() + " not exist"); originfile.getParentFile().mkdirs(); } if (originfile.exists()) { originfile.delete(); } System.out.println(originfile.getAbsolutePath()); originfile.createNewFile(); // ѹжȡclasses.dexļ,浽origin.dex FileOutputStream fos = new FileOutputStream(originfile); int len = 0; byte[] cache = new byte[4096]; while ((len = zis.read(cache)) > 0) { fos.write(cache, 0, len); } fos.flush(); fos.close(); System.out.println(name + " extract success"); zis.closeEntry(); zis.close(); } /** * ļǩ */ public static void signapk(String file) throws Exception { savelog("---------------------------------------------\n" + "signing apk...\n"); System.out.println("sign apk " + file); String cmd = "java -jar lib\\signapk.jar lib\\testkey.x509.pem lib\\testkey.pk8 " + file + " " + SIGNED_APK;// javaִsignapk.jarapkǩ Runtime run = Runtime.getRuntime(); Process process = run.exec(cmd); process.waitFor(); process.destroy(); } /** * ļzip,Ҫʵaddbyte2zip */ public static void addfile2zip(String srcfile, String srczip, String showname) throws Exception { savelog("---------------------------------------------\n" + "adding file...\n"); addbytes2zip(readbytes(srcfile), srczip, showname); System.out.println("add file done"); } /** * byteszip,Ҫʵ:zipеļһzipļ,вļΪҪӵļ, * zipеļbytesĿzip * * @param srczip * Ҫzip * @param bytes * Ҫbytes * @param showname * byteszipʾ·ļ */ private static void addbytes2zip(byte[] bytes, String srczip, String showname) throws Exception { System.out.println("src zip:" + srczip); System.out.println("dst zip:" + TMP_APK_DIR); System.out.println("display name in zip:" + showname); String outdir = TMP_APK_DIR.substring(0, TMP_APK_DIR.lastIndexOf('\\')); File szip = new File(srczip); if (!szip.exists()) { return; } File outpath = new File(outdir); if (!outpath.exists()) { outpath.mkdirs(); } File dzip = new File(TMP_APK_DIR); if (dzip.exists()) { dzip.delete(); } ZipOutputStream zipos = new ZipOutputStream(new FileOutputStream(dzip)); ZipFile szipfile = new ZipFile(szip); @SuppressWarnings("unchecked") Enumeration<ZipEntry> emu = (Enumeration<ZipEntry>) szipfile.entries();// zipļеĿ while (emu.hasMoreElements()) { // Ŀ,ļΪҪļ,,򿽱Ŀzip ZipEntry entry = (ZipEntry) emu.nextElement(); if (showname.equals(entry.getName())) { System.out.println("not copy " + entry.getName()); } else { zipos.putNextEntry(entry); // ļ,ļ if (!entry.isDirectory()) { System.out.println("copy file " + entry.getName()); copy(szipfile.getInputStream(entry), zipos); } zipos.closeEntry(); } } System.out.println("add file to zip"); // zipļ ZipEntry zEntry = new ZipEntry(showname); zipos.putNextEntry(zEntry); zipos.write(bytes); zipos.closeEntry(); szipfile.close(); zipos.close(); } /** * ޸manifestļ */ public static void fixManifest() throws Exception { savelog("---------------------------------------------\n" + "fixing manifest...\n"); String filename = AM_XML; File amxml = new File(filename); DocumentBuilder builder = DocumentBuilderFactory.newInstance() .newDocumentBuilder(); Document document = builder.parse(amxml);// xmlļн Node app = document.getElementsByTagName("application").item(0);// õapplicationǩ(manifestֻ1applicationǩ,item(0)һ) // ޸applicationǩеandroid:namevalueֵ,ؾɵvalueֵ(Ҫɵֵmeta-data) String old = setNodeAttr(app, new String[] { "android:name", APP_VALUE }); // ɵvalueֵ.MyApplicationʽ, Ҫǰϰ if (old.startsWith(".")) { Node manifest = document.getElementsByTagName("manifest").item(0); String packagename = setNodeAttr(manifest, new String[] { "package" });// ȡmanifestǩеpackageֵ old = packagename + old; } // ȡapplicationǩӱǩ,meta-dataǩ,޸meta-datanamevalueֵ,meta-dataǩ NodeList nodelist = app.getChildNodes(); int pos = -1; if ((pos = isExist(nodelist, "meta-data")) != -1) { setNodeAttr(nodelist.item(pos), new String[] { "android:name", APP_NAME }); setNodeAttr(nodelist.item(pos), new String[] { "android:value", old }); } else { // mete-data,meta-dataǩ Element node = document.createElement("meta-data"); node.setAttribute("android:name", APP_NAME); node.setAttribute("android:value", old); app.appendChild(node); } Transformer tf = TransformerFactory.newInstance().newTransformer(); tf.transform(new DOMSource(document), new StreamResult(filename));// ޸ĺdocument浽ļ } /** * ñǩ,Բ,.(ÿһǩΪһNode,ǩеÿ<name,value>ҲΪһNode) * * @param n * Ҫ޸ĵıǩ * @param attr * Ҫ޸ĵԼֵ, Ϊɱ,Ϊ1ʾȡԵֵ,Ϊ2ʾ޸ĸԵֵ * @return ؾɵֵ */ private static String setNodeAttr(Node n, String... attr) { NamedNodeMap nnmap = n.getAttributes();// ȡñǩȫԽڵ,ÿһڵΪ<name,value>ֵ int len = nnmap.getLength(); int i = 0; while (i < len) { Node node = nnmap.item(i); // жϵǰǷҪ޸ĵ if (attr[0].equals(node.getNodeName())) { String old = node.getNodeValue();// ɵֵ if (attr.length == 2) { node.setNodeValue(attr[1]);// attrΪ2,޸Ϊµֵ } return old; } i++; } // Բ,attrΪ2, if (attr.length == 2) { ((Element) n).setAttribute(attr[0], attr[1]); } return ""; } /** * жϱǩбǷӱǩ,򷵻ӱǩλ */ private static int isExist(NodeList list, String nodename) { int len = list.getLength(); for (int i = 0; i < len; i++) { if (nodename.equals(list.item(i).getNodeName())) { return i; } } return -1; } /** * ɾļмļ */ public static void deleteAll(File dir) { if (dir.isFile()) { System.out.println("delete " + dir); dir.delete(); return; } if (dir.isDirectory()) { File[] files = dir.listFiles(); for (File f : files) { deleteAll(f); } System.out.println("delete " + dir); dir.delete(); } } }
JavaScript
UTF-8
2,912
2.625
3
[]
no_license
// Namespace this.GC = this.GC || {}; (function ($) { "use strict"; function Preloader() { var _this = this; this.cubeFaceEnum = { FRONT:1, BACK:2, LEFT:3, RIGHT:4, TOP:5, BOTTOM:6 }; this.assetsLoaded = 0; this.assetsToLoad = 0; this.refreshRate = 500; this.videoLoader = null; this.assetCollection = [ // bgSuperCell videoGame { face:this.cubeFaceEnum.FRONT, type:"video", id:"videoFront", mute:true, sources:[ {src:"bgSuperCell.mp4", type:"video/mp4"}, {src:"bgSuperCell.ogv", type:"video/ogg"} ] }, { face:this.cubeFaceEnum.BACK, type:"video", id:"videoBack", mute:true, sources:[ {src:"bgSuperCell.mp4", type:"video/mp4"}, {src:"bgSuperCell.ogv", type:"video/ogg"} ] }, { face:this.cubeFaceEnum.LEFT, type:"video", id:"videoLeft", mute:true, sources:[ {src:"bgSuperCell.mp4", type:"video/mp4"}, {src:"bgSuperCell.ogv", type:"video/ogg"} ] }, { face:this.cubeFaceEnum.RIGHT, type:"video", id:"videoRight", mute:true, sources:[ {src:"bgSuperCell.mp4", type:"video/mp4"}, {src:"bgSuperCell.ogv", type:"video/ogg"} ] }, { face:this.cubeFaceEnum.TOP, type:"video", id:"videoTop", mute:true, sources:[ {src:"bgSuperCell.mp4", type:"video/mp4"}, {src:"bgSuperCell.ogv", type:"video/ogg"} ] }, { face:this.cubeFaceEnum.BOTTOM, type:"video", id:"videoBottom", mute:true, sources:[ {src:"bgSuperCell.mp4", type:"video/mp4"}, {src:"bgSuperCell.ogv", type:"video/ogg"} ] } ]; this.videos = []; this.init = function() { this.assetsLoaded = 0; this.assetsToLoad = this.assetCollection.length; for (var i=0; i<this.assetsToLoad; i++) { var v = createVideo(this.assetCollection[i]); v.load(); this.videos.push(v); } this.videoLoader = setInterval(pollLoader.bind(_this), this.refreshRate); // this was changing context } this.allVideosLoaded = function() { return this.assetsLoaded == this.assetsToLoad; } function pollLoader() { for (var i=0; i<this.assetsToLoad; i++) { var video = this.videos[i]; if (video.readyState) { var buffered = video.buffered.end(0).toFixed(2); var duration = video.duration.toFixed(2); if (buffered >= duration) { ++this.assetsLoaded; console.log("Videos loaded: "+this.assetsLoaded); if (this.allVideosLoaded()) { clearInterval(this.videoLoader); console.log("All videos loaded"); } } } } } function createVideo(elem) { var vid = document.createElement('video'); vid.id = elem.id; vid.preload = true; vid.face = elem.face; vid.style.display = "none"; vid.muted = elem.mute; for (var i=0; i<elem.sources.length; i++) { var s = document.createElement('source'); s.src = elem.sources[i].src; s.type = elem.sources[i].type; vid.appendChild(s); } document.body.appendChild(vid); return vid; } } GC.Preloader = Preloader; })(jQuery);
Java
UTF-8
230
1.671875
2
[]
no_license
package com.mstream.rulesengine.core; import java.util.List; import java.util.Map; import java.util.Set; public interface Rule { String getName(); List<String> getActions(); Map<String, Boolean> getCondition(); }
PHP
UTF-8
203
3.140625
3
[]
no_license
<?php class Posts{ function __call($name, $arguments){ echo $name . "<br>"; var_dump($arguments); } } $post1 = new Posts(); $post1->createPosts("this is a test", 10); ?>
C++
UTF-8
995
2.796875
3
[]
no_license
// // triangle.cpp // RayTracer // // Created by Uriana on 3/30/14. // Copyright (c) 2014 Uriana. All rights reserved. // #include "triangle.h" triangle::triangle(Vector3D theP0, Vector3D theP1, Vector3D theP2, Vector3D then0, Vector3D then1, Vector3D then2) { P0 = theP0; P1 = theP1; P2 = theP2; nAt0 = then0; nAt1 = then1; nAt2 = then2; n2 = ((nAt0 + nAt1 + nAt2)/3.0).Normalize(); n0 = (P0 - P1).Normalize(); n1 = Cross(n2, n0).Normalize(); } Vector3D triangle::getP0(void){ return P0; } Vector3D triangle::getP1(void){ return P1; } Vector3D triangle::getP2(void){ return P2; } Vector3D triangle::getn0(void){ return n0; } Vector3D triangle::getn1(void){ return n1; } Vector3D triangle::getn2(void){ return n2; } Vector3D triangle::getnAt0(void){ return nAt0; } Vector3D triangle::getnAt1(void){ return nAt1; } Vector3D triangle::getnAt2(void){ return nAt2; } int triangle::objectType(){ return 2; }
PHP
UTF-8
22,699
3.078125
3
[ "MIT" ]
permissive
<?php /** * O2System * * An open source application development framework for PHP 5.4+ * * This content is released under the MIT License (MIT) * * Copyright (c) 2015, . * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @package O2System * @author Circle Creative Dev Team * @copyright Copyright (c) 2005 - 2015, . * @license http://circle-creative.com/products/o2system-codeigniter/license.html * @license http://opensource.org/licenses/MIT MIT License * @link http://circle-creative.com/products/o2system-codeigniter.html * @since Version 2.0 * @filesource */ // ------------------------------------------------------------------------ defined( 'ROOTPATH' ) OR exit( 'No direct script access allowed' ); // ------------------------------------------------------------------------ /** * String Helpers * * @package O2System * @subpackage helpers * @category Helpers * @author Circle Creative Dev Team * @link http://circle-creative.com/products/o2system-codeigniter/user-guide/helpers/string.html */ // ------------------------------------------------------------------------ if ( ! function_exists( 'str_capitalize' ) ) { /** * String Capitalize * * Capitalize a string * * @param string $string Source String * @param bool $first_word First Word Only * * @return string */ function str_capitalize( $string, $first_word = FALSE ) { if ( ! empty( $string ) ) { if ( $first_word ) { return ucfirst( $string ); } else { $string = explode( ' ', $string ); $strings = array_map( function ( $string ) { return ucfirst( $string ); }, $string ); return implode( ' ', $strings ); } } return NULL; } } // ------------------------------------------------------------------------ if ( ! function_exists( 'is_default_str' ) ) { /** * Is Default String * * Check if value is (not) the same as the default value * * @param string $string Source String * @param int $default Default Value * * @return string */ function is_default_str( $string, $default ) { return ( $string == $default ) ? TRUE : FALSE; } } // ------------------------------------------------------------------------ if ( ! function_exists( 'is_html' ) ) { /** * Determine if string is HTML * * @param $string * * @return bool */ function is_html( $string ) { return $string != strip_tags( $string ) ? TRUE : FALSE; } } if ( ! function_exists( 'str_echo' ) ) { /** * Show string or a formatted string with the value in it when the value exists * * @access public * * @param string * @param integer number of repeats * * @return string */ function str_echo( $value, $start_string = '', $end_string = '', $type = 'text' ) { if ( ! empty( $value ) && $value !== '' ) { switch ( $type ) { default : case 'text' : echo $start_string . $value . $end_string; break; case 'email' : echo $start_string . safe_mailto( $value, $value ) . $end_string; break; case 'url' : if ( preg_match( '[http://]', $value ) or preg_match( '[https://]', $value ) ) { $url = $value; } else { $url = 'http://' . $value; } echo $start_string . '<a href="' . $url . '" target="_blank">' . $value . '</a>' . $end_string; break; case 'yahoo_messenger' : echo $start_string . '<a href="ymsgr:sendim?' . $value . '">' . $value . '</a>' . $end_string; break; case 'msn_messenger' : echo $start_string . '<a href="msnim:chat?contact=' . $value . '">' . $value . '</a>' . $end_string; break; case 'gtalk_messenger' : echo $start_string . '<a href="googletalk:chat?jid=' . $value . '">' . $value . '</a>' . $end_string; break; case 'skype_messenger' : echo $start_string . '<a href="skype:' . $value . '?chat">' . $value . '</a>' . $end_string; break; } } } } // ------------------------------------------------------------------------ if ( ! function_exists( 'str_email' ) ) { /** * Save display email * * @access public * * @param string * @param integer number of repeats * * @return string */ function str_email( $string ) { if ( ! empty( $string ) or $string != '' ) { return str_replace( [ '.', '@', ], [ ' [dot] ', ' [at] ', ], trim( $string ) ); } return $string; } } // ------------------------------------------------------------------------ if ( ! function_exists( 'str_alphanumeric' ) ) { /** * Remove Non AlphaNumeric Characters * * @access public * * @param string * @param integer number of repeats * * @return string */ function str_alphanumeric( $string ) { if ( ! empty( $string ) or $string != '' ) { $string = preg_replace( "/[^a-zA-Z0-9\s]/", "", $string ); } return trim( $string ); } } // ------------------------------------------------------------------------ if ( ! function_exists( 'str_numeric' ) ) { /** * Remove Non Numeric Characters * * @access public * * @param string * @param integer number of repeats * * @return string */ function str_numeric( $string ) { if ( ! empty( $string ) or $string != '' ) { $string = preg_replace( "/[^0-9\s]/", "", $string ); } return trim( $string ); } } // ------------------------------------------------------------------------ if ( ! function_exists( 'str_alias' ) ) { /** * Create Alias From String * * @access public * * @param string * @param integer number of repeats * * @return string */ function str_alias( $string, $delimiter = '-' ) { if ( ! empty( $string ) || $string != '' ) { $string = strtolower( trim( $string ) ); $string = preg_replace( "/[^A-Za-z0-9 ]/", '', $string ); if ( $delimiter === '-' ) { return preg_replace( '/[ _]+/', '-', $string ); } elseif ( $delimiter === '_' ) { return preg_replace( '/[ -]+/', '_', $string ); } } return $string; } } // ------------------------------------------------------------------------ if ( ! function_exists( 'str_readable' ) ) { /** * Normalize Alias Into a Capitalize String * * @access public * * @param string * @param integer number of repeats * * @return string */ function str_readable( $string, $capitalize = FALSE ) { if ( ! empty( $string ) or $string != '' ) { $string = str_replace( '-', ' ', $string ); $string = str_replace( '_', ' ', $string ); if ( $capitalize == TRUE ) { return ucwords( $string ); } return $string; } return $string; } } // ------------------------------------------------------------------------ if ( ! function_exists( 'str_truncate' ) ) { /** * Truncates a string to a certain length * * @param string $string * @param int $limit * @param string $ending * * @return string */ function str_truncate( $string, $limit = 25, $ending = '' ) { if ( strlen( $string ) > $limit ) { $string = strip_tags( $string ); $string = substr( $string, 0, $limit ); $string = substr( $string, 0, -( strlen( strrchr( $string, ' ' ) ) ) ); $string = $string . $ending; } return $string; } } // ------------------------------------------------------------------------ if ( ! function_exists( 'str_shorten' ) ) { /** * If a string is too long, shorten it in the middle * * @param string $string * @param int $limit * * @return string */ function str_shorten( $string, $limit = 25 ) { if ( strlen( $string ) > $limit ) { $pre = substr( $string, 0, ( $limit / 2 ) ); $suf = substr( $string, -( $limit / 2 ) ); $string = $pre . ' ... ' . $suf; } return $string; } } // ------------------------------------------------------------------------ if ( ! function_exists( 'str_obfuscate' ) ) { /** * Scrambles the source of a string * * @param string $string * * @return string */ function str_obfuscate( $string ) { $length = strlen( $string ); $scrambled = ''; for ( $i = 0; $i < $length; ++$i ) { $scrambled .= '&#' . ord( substr( $string, $i, 1 ) ) . ';'; } return $scrambled; } } // ------------------------------------------------------------------------ if ( ! function_exists( 'symbols_to_entities' ) ) { /** * Converts high-character symbols into their respective html entities. * * @return string * * @param string $string */ function symbols_to_entities( $string ) { static $symbols = [ '‚', 'ƒ', '"', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', "'", "'", '"', '"', '•', '–', '—', '˜', '™', 'š', '›', 'œ', 'Ÿ', '€', 'Æ', 'Á', 'Â', 'À', 'Å', 'Ã', 'Ä', 'Ç', 'Ð', 'É', 'Ê', 'È', 'Ë', 'Í', 'Î', 'Ì', 'Ï', 'Ñ', 'Ó', 'Ô', 'Ò', 'Ø', 'Õ', 'Ö', 'Þ', 'Ú', 'Û', 'Ù', 'Ü', 'Ý', 'á', 'â', 'æ', 'à', 'å', 'ã', 'ä', 'ç', 'é', 'ê', 'è', 'ð', 'ë', 'í', 'î', 'ì', 'ï', 'ñ', 'ó', 'ô', 'ò', 'ø', 'õ', 'ö', 'ß', 'þ', 'ú', 'û', 'ù', 'ü', 'ý', 'ÿ', '¡', '£', '¤', '¥', '¦', '§', '¨', '©', 'ª', '«', '¬', '­', '®', '¯', '°', '±', '²', '³', '´', 'µ', '¶', '·', '¸', '¹', 'º', '»', '¼', '½', '¾', '¿', '×', '÷', '¢', '…', 'µ', ]; static $entities = [ '&#8218;', '&#402;', '&#8222;', '&#8230;', '&#8224;', '&#8225;', '&#710;', '&#8240;', '&#352;', '&#8249;', '&#338;', '&#8216;', '&#8217;', '&#8220;', '&#8221;', '&#8226;', '&#8211;', '&#8212;', '&#732;', '&#8482;', '&#353;', '&#8250;', '&#339;', '&#376;', '&#8364;', '&aelig;', '&aacute;', '&acirc;', '&agrave;', '&aring;', '&atilde;', '&auml;', '&ccedil;', '&eth;', '&eacute;', '&ecirc;', '&egrave;', '&euml;', '&iacute;', '&icirc;', '&igrave;', '&iuml;', '&ntilde;', '&oacute;', '&ocirc;', '&ograve;', '&oslash;', '&otilde;', '&ouml;', '&thorn;', '&uacute;', '&ucirc;', '&ugrave;', '&uuml;', '&yacute;', '&aacute;', '&acirc;', '&aelig;', '&agrave;', '&aring;', '&atilde;', '&auml;', '&ccedil;', '&eacute;', '&ecirc;', '&egrave;', '&eth;', '&euml;', '&iacute;', '&icirc;', '&igrave;', '&iuml;', '&ntilde;', '&oacute;', '&ocirc;', '&ograve;', '&oslash;', '&otilde;', '&ouml;', '&szlig;', '&thorn;', '&uacute;', '&ucirc;', '&ugrave;', '&uuml;', '&yacute;', '&yuml;', '&iexcl;', '&pound;', '&curren;', '&yen;', '&brvbar;', '&sect;', '&uml;', '&copy;', '&ordf;', '&laquo;', '&not;', '&shy;', '&reg;', '&macr;', '&deg;', '&plusmn;', '&sup2;', '&sup3;', '&acute;', '&micro;', '&para;', '&middot;', '&cedil;', '&sup1;', '&ordm;', '&raquo;', '&frac14;', '&frac12;', '&frac34;', '&iquest;', '&times;', '&divide;', '&cent;', '...', '&micro;', ]; return str_replace( $symbols, $entities, $string ); } } // ------------------------------------------------------------------------ if ( ! function_exists( 'is_parse_string' ) ) { /** * Is Parse String * * @return string * * @params string $string */ function is_parse_string( $string ) { if ( preg_match( '[=]', $string ) ) { return TRUE; } return FALSE; } } // ------------------------------------------------------------------------ if ( ! function_exists( 'parse_string' ) ) { /** * Is Parse String * * @return string * * @params string $string */ function parse_string( $string ) { if ( preg_match( '[=]', $string ) ) { parse_str( html_entity_decode( $string ), $string ); } return $string; } } // ------------------------------------------------------------------------ if ( ! function_exists( 'mb_stripos_all' ) ) { /** * mb_stripos all occurences * based on http://www.php.net/manual/en/function.strpos.php#87061 * * Find all occurrences of a needle in a haystack * * @param string $haystack * @param string $needle * * @return array or false */ function mb_stripos_all( $haystack, $needle ) { $s = 0; $i = 0; while ( is_integer( $i ) ) { $i = mb_stripos( $haystack, $needle, $s ); if ( is_integer( $i ) ) { $aStrPos[] = $i; $s = $i + mb_strlen( $needle ); } } if ( isset( $aStrPos ) ) { return $aStrPos; } else { return FALSE; } } } // ------------------------------------------------------------------------ if ( ! function_exists( 'is_serialized' ) ) { /** * Is Serialized * * Check is the string is serialized array * * @param string $string Source string * * @return bool */ function is_serialized( $string ) { if ( ! is_string( $string ) ) { return FALSE; } if ( trim( $string ) == '' ) { return FALSE; } if ( preg_match( "/^(i|s|a|o|d)(.*);/si", $string ) ) { $is_valid = @unserialize( $string ); if ( empty( $is_valid ) ) { return FALSE; } return TRUE; } return FALSE; } } // ------------------------------------------------------------------------ if ( ! function_exists( 'is_json' ) ) { /** * Is JSON * * Check is the string is json array or object * * @item string or array * @return boolean (true or false) */ function is_json( $string ) { // make sure provided input is of type string if ( ! is_string( $string ) ) { return FALSE; } // trim white spaces $string = trim( $string ); // get first character $first_char = substr( $string, 0, 1 ); // get last character $last_char = substr( $string, -1 ); // check if there is a first and last character if ( ! $first_char || ! $last_char ) { return FALSE; } // make sure first character is either { or [ if ( $first_char !== '{' && $first_char !== '[' ) { return FALSE; } // make sure last character is either } or ] if ( $last_char !== '}' && $last_char !== ']' ) { return FALSE; } // let's leave the rest to PHP. // try to decode string json_decode( $string ); // check if error occurred $is_valid = json_last_error() === JSON_ERROR_NONE; return $is_valid; } } /** * CodeIgniter * * An open source application development framework for PHP * * This content is released under the MIT License (MIT) * * Copyright (c) 2014 - 2015, British Columbia Institute of Technology * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @package CodeIgniter * @author EllisLab Dev Team * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) * @copyright Copyright (c) 2014 - 2015, British Columbia Institute of Technology (http://bcit.ca/) * @license http://opensource.org/licenses/MIT MIT License * @link http://codeigniter.com * @since Version 1.0.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter String Helpers * * @package CodeIgniter * @subpackage Helpers * @category Helpers * @author EllisLab Dev Team * @link http://codeigniter.com/user_guide/helpers/string_helper.html */ // ------------------------------------------------------------------------ if ( ! function_exists( 'strip_slashes' ) ) { /** * Strip Slashes * * Removes slashes contained in a string or in an array * * @param mixed string or array * * @return mixed string or array */ function strip_slashes( $str ) { if ( ! is_array( $str ) ) { return stripslashes( $str ); } foreach ( $str as $key => $val ) { $str[ $key ] = strip_slashes( $val ); } return $str; } } // ------------------------------------------------------------------------ if ( ! function_exists( 'strip_quotes' ) ) { /** * Strip Quotes * * Removes single and double quotes from a string * * @param string * * @return string */ function strip_quotes( $str ) { return str_replace( [ '"', "'" ], '', $str ); } } // ------------------------------------------------------------------------ if ( ! function_exists( 'quotes_to_entities' ) ) { /** * Quotes to Entities * * Converts single and double quotes to entities * * @param string * * @return string */ function quotes_to_entities( $str ) { return str_replace( [ "\'", "\"", "'", '"' ], [ "&#39;", "&quot;", "&#39;", "&quot;" ], $str ); } } // ------------------------------------------------------------------------ if ( ! function_exists( 'reduce_double_slashes' ) ) { /** * Reduce Double Slashes * * Converts double slashes in a string to a single slash, * except those found in http:// * * http://www.some-site.com//index.php * * becomes: * * http://www.some-site.com/index.php * * @param string * * @return string */ function reduce_double_slashes( $str ) { return preg_replace( '#(^|[^:])//+#', '\\1/', $str ); } } // ------------------------------------------------------------------------ if ( ! function_exists( 'reduce_multiples' ) ) { /** * Reduce Multiples * * Reduces multiple instances of a particular character. Example: * * Fred, Bill,, Joe, Jimmy * * becomes: * * Fred, Bill, Joe, Jimmy * * @param string * @param string the character you wish to reduce * @param bool TRUE/FALSE - whether to trim the character from the beginning/end * * @return string */ function reduce_multiples( $str, $character = ',', $trim = FALSE ) { $str = preg_replace( '#' . preg_quote( $character, '#' ) . '{2,}#', $character, $str ); return ( $trim === TRUE ) ? trim( $str, $character ) : $str; } } // ------------------------------------------------------------------------ if ( ! function_exists( 'random_string' ) ) { /** * Create a Random String * * Useful for generating passwords or hashes. * * @param string type of random string. basic, alpha, alnum, numeric, nozero, unique, md5, encrypt and sha1 * @param int number of characters * * @return string */ function random_string( $type = 'alnum', $len = 8 ) { switch ( $type ) { case 'basic': return mt_rand(); case 'alnum': case 'numeric': case 'nozero': case 'alpha': switch ( $type ) { case 'alpha': $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; break; case 'alnum': $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; break; case 'numeric': $pool = '0123456789'; break; case 'nozero': $pool = '123456789'; break; } return substr( str_shuffle( str_repeat( $pool, ceil( $len / strlen( $pool ) ) ) ), 0, $len ); case 'unique': // todo: remove in 3.1+ case 'md5': return md5( uniqid( mt_rand() ) ); case 'encrypt': // todo: remove in 3.1+ case 'sha1': return sha1( uniqid( mt_rand(), TRUE ) ); } } } // ------------------------------------------------------------------------ if ( ! function_exists( 'increment_string' ) ) { /** * Add's _1 to a string or increment the ending number to allow _2, _3, etc * * @param string required * @param string What should the duplicate number be appended with * @param string Which number should be used for the first dupe increment * * @return string */ function increment_string( $str, $separator = '_', $first = 1 ) { preg_match( '/(.+)' . $separator . '([0-9]+)$/', $str, $match ); return isset( $match[ 2 ] ) ? $match[ 1 ] . $separator . ( $match[ 2 ] + 1 ) : $str . $separator . $first; } } // ------------------------------------------------------------------------ if ( ! function_exists( 'alternator' ) ) { /** * Alternator * * Allows strings to be alternated. See docs... * * @param string (as many parameters as needed) * * @return string */ function alternator( $args ) { static $i; if ( func_num_args() === 0 ) { $i = 0; return ''; } $args = func_get_args(); return $args[ ( $i++ % count( $args ) ) ]; } }
C#
UTF-8
2,998
2.796875
3
[]
no_license
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Data; using ExcelLibrary.SpreadSheet; using Newtonsoft.Json; using System.Text.RegularExpressions; namespace Online.Registration.Web.Helper { public class ExcelHelper { public static string Export(string jsonTable) { jsonTable = Regex.Replace(jsonTable.Replace(@"\n", " "), @"\s+", " "); string excelFileName = Guid.NewGuid().ToString() + ".xls"; string excelFilePath = HttpContext.Current.Server.MapPath("~/Temp/" + excelFileName); var result = Deserialize(jsonTable, typeof(DataTable)); DataTable da = result as DataTable; //// Create an Excel object and add workbook... Workbook workbook = new Workbook(); Worksheet worksheet = new Worksheet("Sheet1"); if (da == null) return string.Empty; //add blank rows to data set because of ms excel unable to open the file if file size is less than 10kb int totalRows = da.Rows.Count; if (totalRows < 50) { int count = 50 - totalRows; for (int i = 0; i <= count; i++) { da.Rows.Add(da.NewRow()); } } if (da.Columns.Contains("Action")) { da.Columns.Remove("Action"); } // Add column headings... int iCol = 0; foreach (DataColumn c in da.Columns) { worksheet.Cells[0, iCol] = new Cell(c.ColumnName); iCol++; } // for each row of data... int iRow = 0; foreach (DataRow r in da.Rows) { // add each row's cell data... iCol = 0; foreach (DataColumn c in da.Columns) { worksheet.Cells[iRow + 1, iCol] = new Cell(r[c.ColumnName].ToString()); iCol++; } iRow++; } workbook.Worksheets.Add(worksheet); workbook.Save(excelFilePath); return excelFileName; } private static object Deserialize(string jsonText, Type valueType) { JsonSerializer json = new JsonSerializer { NullValueHandling = NullValueHandling.Ignore, ObjectCreationHandling = ObjectCreationHandling.Replace, MissingMemberHandling = MissingMemberHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Ignore }; StringReader sr = new StringReader(jsonText); JsonTextReader reader = new JsonTextReader(sr); object result = json.Deserialize(reader, valueType); reader.Close(); return result; } } }
Java
UTF-8
1,532
3.046875
3
[]
no_license
/* * 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 paquete2; import paquete5.Persona; /** * * @author reroes */ public class Prestamo{ protected Persona beneficiario; protected double tiempoPrestamoMeses; protected String ciudadPrestamo; public Prestamo(Persona b, double tPM, String cP){ beneficiario = b; tiempoPrestamoMeses = tPM; ciudadPrestamo = cP; } public void establecerBeneficiario(Persona b){ beneficiario = b; } public void establecerTiempoDePrestamoEnMeses(double tPM){ tiempoPrestamoMeses = tPM; } public void establecerCiudadPrestamo(String cP){ ciudadPrestamo = cP; } public Persona obtenerBeneficiario(){ return beneficiario; } public double obtenerTiempoDePrestamoEnMeses(){ return tiempoPrestamoMeses; } public String obtenerCiudadPrestamo(){ return ciudadPrestamo; } @Override public String toString(){ String cadena; cadena = String.format("Beneficiarios\n\tNombre: %s\n\tApellido: %s\n" + "Tiempo de prestamo en meses: %.2f\nCiudad del prestamo: %s\n", beneficiario.obtenerNombre(), beneficiario.obtenerApellido(), obtenerTiempoDePrestamoEnMeses(), obtenerCiudadPrestamo()); return cadena; } }
Python
UTF-8
776
3.40625
3
[]
no_license
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param {integer} n # @return {TreeNode[]} def dfs(self, start, end): if start > end: return [None] result = [] for i in range(start, end + 1): subLeft = self.dfs(start, i - 1) subRight = self.dfs(i + 1, end) for rootLeft in subLeft: for rootRight in subRight: root = TreeNode(i) root.left = rootLeft root.right = rootRight result.append(root) return result def generateTrees(self, n): return self.dfs(1, n)
Markdown
UTF-8
430
2.734375
3
[]
no_license
# React - Videos React application that consumes data from the YouTube API providing the user with a video search field and returns as a result a total of five videos with the searched theme. The application is also composed of a featured video and a list of videos related to the search, which when clicking on one of these, it updates the state of the component and changes the clicked video to the state of highlighted video.
JavaScript
UTF-8
136
2.8125
3
[]
no_license
class Hello { run() { document.querySelector("#hello").innerHTML = "ES6_Hello_World"; } } var hello = new Hello(); hello.run();
PHP
UTF-8
4,299
2.609375
3
[ "MIT" ]
permissive
<?php namespace App\Sharp; use App\Models\Project; use App\Models\Tag; use Code16\Sharp\Form\Eloquent\Uploads\Transformers\SharpUploadModelFormAttributeTransformer; use Code16\Sharp\Form\Eloquent\WithSharpFormEloquentUpdater; use Code16\Sharp\Form\Fields\SharpFormCheckField; use Code16\Sharp\Form\Fields\SharpFormDateField; use Code16\Sharp\Form\Fields\SharpFormListField; use Code16\Sharp\Form\Fields\SharpFormSelectField; use Code16\Sharp\Form\Fields\SharpFormTagsField; use Code16\Sharp\Form\Fields\SharpFormTextareaField; use Code16\Sharp\Form\Fields\SharpFormTextField; use Code16\Sharp\Form\Fields\SharpFormUploadField; use Code16\Sharp\Form\Layout\FormLayoutColumn; use Code16\Sharp\Form\SharpForm; class ProjectForm extends SharpForm { use WithSharpFormEloquentUpdater; /** * Retrieve a Model for the form and pack all its data as JSON. * * @param $id * @return array */ public function find($id): array { return $this ->setCustomTransformer( "cover", new SharpUploadModelFormAttributeTransformer() ) ->transform( Project::with('tags', 'links', 'cover')->findOrFail($id) ); } /** * @param $id * @param array $data * @return mixed the instance id */ public function update($id, array $data) { $project = $id ? Project::findOrFail($id) : new Project; $this->save($project, $data); } /** * @param $id */ public function delete($id) { Project::findOrFail($id)->find($id)->delete(); } /** * Build form fields using ->addField() * * @return void */ public function buildFormFields() { $this->addField( SharpFormTextField::make('name') ->setLabel('Название') ) ->addField( SharpFormTextField::make('code') ->setLabel('Код страницы') ) ->addField( SharpFormCheckField::make('published', 'Опубликовано') ->setText('Опубликовано') ) ->addField( SharpFormTextareaField::make('description') ->setLabel('Описание') ->setRowCount(4) )->addField( SharpFormTagsField::make('tags', Tag::pluck("name", "id")->all()) ->setLabel('Теги') ->setCreatable(true) ->setCreateText('Создать новый тег') ->setCreateAttribute('name') ) ->addField( SharpFormUploadField::make("cover") ->setLabel("Обложка") ->setFileFilterImages() ->setStorageDisk("local") ->setStorageBasePath("data/project/cover") ) ->addField( SharpFormListField::make('links') ->setLabel('Ссылки') ->setAddable() ->setRemovable() ->addItemField( SharpFormTextField::make("link") ->setLabel("Ссылка") ) ->addItemField( SharpFormTextField::make("type") ->setLabel("Тип ссылки") ) ); } /** * Build form layout using ->addTab() or ->addColumn() * * @return void */ public function buildFormLayout() { $this->addColumn(6, function (FormLayoutColumn $column) { $column ->withSingleField('name') ->withSingleField('code') ->withSingleField('published') ->withSingleField('cover') ->withSingleField('description') ->withSingleField('tags') ->withSingleField('links', function (FormLayoutColumn $listItem) { $listItem->withSingleField("link"); $listItem->withSingleField("type"); }); }); } }
Python
UTF-8
524
3.1875
3
[]
no_license
import re respecchar = ['?', '*', '+', '{', '}', '.', '\\', '^', '$', '[', ']'] def regexstrip(string, _strip): if _strip == '' or _strip == ' ': _strip = r'\s' elif _strip in respecchar: _strip = r'\'+_strip' print(_strip) #just for troubleshooting re_strip = re.compile('^'+_strip+'*(.+?)'+_strip+'*$') print(re_strip) #just for troubleshooting mstring = re_strip.search(string) print(mstring) #just for troubleshooting stripped = mstring.group(1) print(stripped)