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
Java
UTF-8
381
1.726563
2
[ "Apache-2.0" ]
permissive
package com.ithxh.xhh.service; import java.util.List; import com.ithxh.baseCore.baseInterface.BaseService; import com.ithxh.xhh.entity.BookDic; import com.ithxh.xhh.vo.formbean.BookDicVo; public interface BookDicService extends BaseService<BookDic, BookDicVo>{ public List<BookDicVo> getListByType(String type); public List<BookDicVo> getListByFatherId(String fatherId); }
Python
UTF-8
12,383
3.046875
3
[]
no_license
# coding: utf-8 # In[2]: # Project # CS6375 Machine Learning # Created by: Xinyang Zhu, Ye Yao # Time: November 2018 #################################################################### # 0 Start # import libraries import numpy as np import pandas as pd #################################################################### # 1 Load Data # directory path dir_path = "./dataset/" # set the urls of dataset train_values_url = dir_path + "Warm_Up_Machine_Learning_with_a_Heart_-_Train_Values.csv" train_labels_url = dir_path + "Warm_Up_Machine_Learning_with_a_Heart_-_Train_Labels.csv" # load dataset values_df = pd.read_csv(train_values_url) labels_df = pd.read_csv(train_labels_url) # In[5]: #################################################################### # 1.2 Data Exploration import seaborn as sns values_df.head() # In[16]: values_df.dtypes # In[11]: labels_df.head() # In[17]: labels_df.dtypes # In[6]: labels_df.heart_disease_present.value_counts().plot.bar(title='Number with Heart Disease') # In[40]: features_to_show = [ 'age', 'sex', 'max_heart_rate_achieved', 'resting_blood_pressure', ] sns.set(style="darkgrid") sns.pairplot(values_df.join(labels_df['heart_disease_present']), hue='heart_disease_present', vars=values_df[features_to_show]) # In[16]: #################################################################### # 2 Pre-Process ## 2.1 # convert to ndarray values_nd = values_df.values labels_nd = labels_df.values # separate ids_nd = values_nd[:, 0] X_nd = values_nd[:, 1:] # ids_nd, X_nd = np.split(values_nd, [1], axis=1) y_nd = labels_nd[:, -1] # print(ids_nd) # print(type(ids_nd)) # print(X_nd) # print(type(X_nd)) # print(y_nd) # print(type(y_nd)) ################################## ## 2.2 encode from sklearn.compose import ColumnTransformer from sklearn.preprocessing import OneHotEncoder, Normalizer from sklearn.pipeline import Pipeline # one hot encoder for categoricalize # https://scikit-learn.org/stable/modules/generated/sklearn.compose.ColumnTransformer.html # https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html#sklearn.preprocessing.OneHotEncoder # https://stackoverflow.com/questions/43588679/issue-with-onehotencoder-for-categorical-features ct = ColumnTransformer( [('enc', OneHotEncoder(), [1])], remainder='passthrough' ) # normalizer # https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.Normalizer.html#sklearn.preprocessing.Normalizer norm = Normalizer() # build the preprocessing pipeline # https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html prep = Pipeline( [('ct', ct), ('norm', norm)] ) # fit the preprocessing pipeline prep.fit(X_nd) # transform on X_nd enc_X_nd = prep.transform(X_nd) # print("X_enc_nd:\n", X_enc_nd) ################################## ## 2.3 train-test split from sklearn.model_selection import train_test_split # split into train and test data X_train, X_test, y_train, y_test = train_test_split(enc_X_nd, y_nd, test_size=0.15) # print(X_train) # print(len(X_train)) # print(len(X_train[0])) # print() # print(X_test) # print(len(X_test)) # print() # print(y_train) # print(len(y_train)) # print() # print(y_test) # print(len(y_test)) # print() # In[17]: #################################################################### # 3 Train and Test Model ## 3.0 prepare # singular estimators from sklearn.tree import DecisionTreeClassifier as DTC from sklearn.linear_model import LogisticRegression as LR from sklearn.neural_network import MLPClassifier as MLPC from sklearn.svm import SVC from sklearn.naive_bayes import GaussianNB as NB from sklearn.neighbors import KNeighborsClassifier as KNNC # ensembling estimators from sklearn.ensemble import BaggingClassifier as BaggingC from sklearn.ensemble import RandomForestClassifier as RFC from sklearn.ensemble import AdaBoostClassifier as AdaBoostC from sklearn.ensemble import GradientBoostingClassifier as GBC from xgboost import XGBClassifier as XGB # command to install xgboost: # conda install -c conda-forge xgboost # metrics from sklearn.metrics import log_loss # grid search cross validation from sklearn.model_selection import GridSearchCV # ignore ConverenceWarning import warnings from sklearn.exceptions import ConvergenceWarning warnings.filterwarnings("ignore", category=ConvergenceWarning) ################################## ## 3.1 train and test models using GridSearchCV models = { 'DT': DTC(), 'LR': LR(), 'MLP': MLPC(), 'SVC': SVC(), 'NB': NB(), 'KNN': KNNC(), 'Bagging': BaggingC(), 'RF': RFC(), 'AdaBoost': AdaBoostC(), 'GB': GBC(), 'XGB': XGB(), } param_dict = { # 0.67 {'max_depth': 1, 'max_leaf_nodes': None, 'min_samples_leaf': 1, 'min_samples_split': 2} 'DT': { 'max_depth': [1,2,3,None], 'max_leaf_nodes': [4,6,8,10,None], 'min_samples_leaf': [1,2,3], 'min_samples_split': [2,4,6] }, # LR 0.64 {'C': 5.0, 'class_weight': None, 'fit_intercept': False, 'penalty': 'l2', 'solver': 'sag'} 'LR': { "solver": ['lbfgs', 'liblinear', 'sag', 'saga'], "penalty": ['l2'], "C": [1.0, 1.5, 2.0, 5.0, 10], "fit_intercept": [True, False], "class_weight": [None, 'balanced'] }, # MLP 0.63 {'activation': 'tanh', 'early_stopping': False, 'hidden_layer_sizes': (100, 100, 50), 'learning_rate': 'invscaling', 'max_iter': 1000} 'MLP': { "max_iter": [500, 1000, 2000], # "hidden_layer_sizes": [(100,100,50)], "hidden_layer_sizes": [ (40,20,10), (20,10,5), (10,5,5) ], "activation": ['tanh', 'relu'], "learning_rate": ['constant', 'invscaling', 'adaptive'], "early_stopping": [True, False], }, # SVC 0.64 {'coef0': 0.5, 'gamma': 'scale', 'kernel': 'poly', 'probability': True, 'shrinking': False} 'SVC': { "probability": [True], # "C": [5000, 10000, 20000, 30000], "kernel": ["poly", "rbf", "sigmoid"], "coef0": [0.0, 0.1, 0.2, 0.3, 0.5], "shrinking": [True, False], "gamma": ['scale', 'auto'] }, # NB 1.30 {} 'NB': { # Nothing can be tuned }, # KNN 0.71 {'algorithm': 'auto', 'n_neighbors': 7, 'p': 2, 'weights': 'uniform'} 'KNN': { "n_neighbors": [1, 2, 3, 5, 7], "weights": ['uniform', 'distance'], "algorithm": ['auto', 'ball_tree', 'kd_tree', 'brute'], "p": [1, 2, 3] }, # Bagging 0.56 {'max_features': 0.8, 'max_samples': 0.3, 'n_estimators': 100} 'Bagging': { "n_estimators": [10, 20, 50, 100, 200], "max_samples": [0.01, 0.1, 0.3, 0.5], "max_features": [0.5, 0.8, 1.0] }, # RF 0.58 {'criterion': 'gini', 'max_depth': 5, 'max_features': 'auto', 'n_estimators': 50} 'RF': { "n_estimators": [10, 20, 50, 100], "criterion": ["gini", "entropy"], "max_depth": [None, 5, 10, 20], "max_features": [None, "auto", "log2"] }, # GB 0.38 {'learning_rate': 0.05, 'max_depth': 5, 'max_features': 'log2', 'n_estimators': 50} 'GB': { "learning_rate": [0.005, 0.01, 0.05, 0.1], "n_estimators": [5, 10, 50, 100], "max_depth": [5, 10, 20], "max_features": [None, "auto", "log2"] }, # AdaBoost 0.63 {'algorithm': 'SAMME.R', 'learning_rate': 1, 'n_estimators': 5} 'AdaBoost': { "n_estimators": [5, 10, 20, 50, 100, 200], "learning_rate": [0.01, 0.1, 1], "algorithm": ["SAMME", "SAMME.R"], }, # XGB 0.55 {'booster': 'gbtree', 'learning_rate': 0.1, 'min_child_weight': 10, 'n_estimators': 100} 'XGB': { "learning_rate": [0.01, 0.1, 1], "n_estimators": [10, 100, 200, 500], "min_child_weight": [5, 10, 20], "booster": ['gbtree', 'gblinear', 'dart'] } } ################### # DEBUG # fast # selected_model_names = ['DT','SVC'] # mid # selected_model_names = ['DT','SVC','NB','KNN', # 'Bagging','RF','AdaBoost','GB','XGB'] # all selected_model_names = ['DT','MLP','SVC','NB','KNN', 'Bagging','RF','AdaBoost','GB','XGB'] ################### # function: grid search cross validation # argument: model name, e.g. 'DT' # return: trained GridSearchCV model def _gscv(model, params, X_train, y_train): gscv = GridSearchCV(model, params, iid=True, cv=3, scoring="neg_log_loss") gscv.fit(X_train, list(y_train)) return gscv # function: test gscv model on the test data # argument: trained gscv model # return: an array of predicted probabilities of a classification of 1 def _test(gscv, X_test, y_test): # test on test data y_pred = gscv.predict_proba(X_test) # print("y_pred:\n", y_pred) # get metrics (log loss) print(model_name,"%.2f" % log_loss(list(y_test), y_pred), gscv.best_params_) # We only need the second column y_pred = y_pred[:,-1] return y_pred # function: show the testing result # arguments: y_pred, y_label def _show_test_result(y_pred, y_label): df = pd.DataFrame() df['y_predict'] = y_pred df['y_label'] = y_label display(df) # function: draw ROC # arguments: y_pred, y_label def _draw_roc(y_pred, y_label): import matplotlib.pyplot as plt from sklearn.metrics import roc_curve, auc y_label = y_label.astype(int) # Compute ROC curve and ROC area for each class fpr, tpr, _ = roc_curve(y_label, y_pred) roc_auc = auc(fpr, tpr) # Draw ROC curve plt.figure() plt.plot(fpr, tpr, color='darkblue', lw=1.5, label='ROC curve (area = %0.2f)' % roc_auc) plt.plot([0, 1], [0, 1], color='grey', lw=1, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.legend(loc="lower right") plt.show() # train and test on models gscvs = {} preds = {} for i, model_name in enumerate(selected_model_names): print("#", i, model_name) # train model gscv = _gscv(models[model_name], param_dict[model_name], X_train, y_train) gscvs[model_name] = gscv # test model y_pred = _test(gscv, X_test, y_test) preds[model_name] = y_pred # show test results # _show_test_result(y_pred, y_test) # draw ROC _draw_roc(y_pred, y_test) print() # In[18]: #################################################################### # 4 Predict on evaluation test data ## 4.1 load evaluation test dataset test_values_url = dir_path + "Warm_Up_Machine_Learning_with_a_Heart_-_Test_Values.csv" test_df = pd.read_csv(test_values_url) ## 4.2 pre-process testset_ndarr = test_df.values test_ids, test_values = np.split(testset_ndarr, [1], axis=1) # print(test_values) # encode test data enc_test_values = prep.transform(test_values) # print(enc_test_values) # 4.3 predict preds = {} for model_name in gscvs: gscv = gscvs[model_name] preds[model_name] = gscv.predict_proba(enc_test_values) # print out predictions # for m_n in preds: # print(m_n) # print(preds[m]) # print() # In[19]: #################################################################### # 5 output # function: get current time in millis # return: timestamp in millisecond def _get_time_stamp(): import time millis = int(round(time.time() * 1000)) # print(millis) # print(type(millis)) return millis # function: export results to csv files # argument: model name, header, patient ids, prediction probabilities def _output(model_name, header, test_ids_list, pred): # export to DataFrame col_id_name = header[0] col_label_name = header[1] res_dict = {col_id_name: test_ids_list, col_label_name: pred[:,1]} res_df = pd.DataFrame.from_dict(res_dict) # write to csv file time_stamp = str(int(_get_time_stamp() / 1000)) output_path = "./" + time_stamp + "-" + model_name + ".csv" res_df.to_csv(output_path, index=False) # output predictions header = labels_df.columns test_ids_list = list(test_ids.flatten()) for model_name in preds: time_stamp = _get_time_stamp() _output(model_name, header, test_ids_list, preds[model_name])
Java
UTF-8
365
1.554688
2
[]
no_license
package com.xhh.myDecorate.dao; import lombok.Data; /** * @author xuhaihong * @create 2018-01-31 18:08 **/ @Data public class ProjectInstance { private Long id; private String title; private String content; private String url; private Long createTime; private Long updateTime; private Integer orders; private String status; }
Shell
UTF-8
2,489
3.234375
3
[]
no_license
#!/bin/bash PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin RETEVAL=0 # DB where data will be stored DATABASE="zarcillo" TABLE="nil_grants" DB_HOST="db1215.eqiad.wmnet" DB_USER="root" # DB from where to get the list of live hosts SOURCE_DB_HOST="db1215.eqiad.wmnet" SOURCE_DB="zarcillo" SOURCE_DB_TABLE="instances" # Timeout in seconds DB_TIMEOUT=5 MYSQL="`which db-mysql`" if [ ! -f "$MYSQL" ] then echo "db-mysql is not present" exit 1 fi case "$1" in "") echo "Usage: $0 --empty-password --unused-grants" RETVAL=1 ;; --empty-password) # Empty the table before start $MYSQL $DB_HOST $DATABASE -e " truncate table $TABLE;" $MYSQL $SOURCE_DB_HOST $SOURCE_DB -e "select server,port from $SOURCE_DB_TABLE;" -BN | while read server port do # The following IPs are whitelisted as they are proxies and we cannot remove haproxy or set a password for it see: T199061#4426646 $MYSQL $server:$port -e "select User,Host from mysql.user where password='' and plugin !='unix_socket' and user !='labsdbuser' and user !='research_role' and user !='mariadb.sys' and host NOT IN ('10.64.37.15','10.192.0.129','10.192.16.9','10.192.32.137','10.64.16.14','10.64.37.27','10.64.48.43', '10.64.32.180','10.64.32.179','10.192.48.47','10.64.0.15','10.64.32.10','10.64.16.7','10.64.48.33','10.64.130.15','10.64.134.16');" -BN | while read user host do echo "set session binlog_format=row; INSERT INTO $TABLE VALUES ('${server}','${port}','${user}','${host}',NOW()) ON DUPLICATE KEY UPDATE last_update = NOW();" | $MYSQL $DB_HOST -u $DB_USER $DATABASE done done # Check and report existing users # Not sending any kind of username/host on email to avoid any kind hint of over email USERS_COUNT=$($MYSQL $DB_HOST -u $DB_USER $DATABASE -e "select count(*) from nil_grants;" -BN) if [ $USERS_COUNT != 0 ] then echo "There are users with empty passwords. Please check $DATABASE.$TABLE table on $DB_HOST - this email address isn't monitored" | mail -s "Users with empty passwords detected" sre-data-persistence@wikimedia.org -aFrom:checkusers@wikimedia.org fi ;; --unused-grants) echo "unused-grants report" $MYSQL $SOURCE_DB_HOST $SOURCE_DB -e "select server,port from $SOURCE_DB_TABLE;" -BN | while read server port do echo "======$server:$port=======" $MYSQL $server:$port -e "select User,Host from mysql.user where host like '208.80.154.%' or host='208.80.152.161' or host='208.80.152.165' or user='globaldev' or user='prefetch' or user='test' or user='repl'" -BN done ;; esac exit $RETVAL
JavaScript
UTF-8
4,144
2.578125
3
[ "MIT" ]
permissive
// --------------------------------------------------------------------------- // // Datepicker // // --------------------------------------------------------------------------- define([ "jquery", "picker", "pickerDate", "pickerLegacy" ], function($) { "use strict"; var defaults = { callbacks: {}, dateFormat: "d mmm yyyy", dateFormatLabel: "yyyy/mm/dd", target: "#js-row--content", startSelector: "#js-av-start", endSelector: "#js-av-end", startLabelSelector: ".js-av-start-label", endLabelSelector: ".js-av-end-label" }; function Datepicker(args) { this.config = $.extend({}, defaults, args); this.target = $(this.config.target); this.target.length && this.init(); } Datepicker.prototype.init = function() { var config = this.config, options = this._getOptions(); this.inDate = this.target.find(config.startSelector); this.outDate = this.target.find(config.endSelector); this.inLabel = $(config.startLabelSelector); this.outLabel = $(config.endLabelSelector); this.firstTime = !!this.inDate.val(); this.day = 86400000; this.inDate.pickadate(options.inDate); this.outDate.pickadate(options.outDate); this.listen(); }; Datepicker.prototype.listen = function() { this.inDate.one("change", this._handleInDateChange.bind(this)); }; // ------------------------------------------------------------------------- // Private Functions // ------------------------------------------------------------------------- Datepicker.prototype._getOptions = function() { var _this = this, config = this.config, today = [], tomorrow = [], d = new Date(), inOpts, outOpts, pickFuture = config.pickFuture === true, pickPast = config.pickPast === true; today.push(d.getFullYear(), d.getMonth(), d.getDate()); tomorrow.push(d.getFullYear(), d.getMonth(), (d.getDate() + 1)); inOpts = { format: config.dateFormat, selectMonths: config.selectMonths, selectYears: config.selectYears, onSet: function() { _this._dateSelected( this.get("select", _this.config.dateFormatLabel), "start" ); } }; outOpts = { format: config.dateFormat, selectMonths: config.selectMonths, selectYears: config.selectYears, onSet: function() { _this._dateSelected( this.get("select", _this.config.dateFormatLabel), "end" ); } }; if (!pickFuture && pickPast) { inOpts.max = today; outOpts.max = today; } else if ((pickFuture && !pickPast) || (!pickFuture && !pickPast)) { inOpts.min = today; outOpts.min = tomorrow; } return { inDate: inOpts, outDate: outOpts }; }; Datepicker.prototype._handleInDateChange = function() { this.outDate.pickadate("picker").open(false); }; Datepicker.prototype._dateSelected = function(date, type) { var inDate = this.inDate.data("pickadate"), outDate = this.outDate.data("pickadate"); if (type === "start") { if (!this._isValidEndDate()) { outDate.set("select", new Date(date).getTime() + this.day); } this.inLabel.text(this.inDate.val()); } else if (type === "end") { if (!this._isValidEndDate() || this.firstTime) { inDate.set("select", new Date(date).getTime() - this.day); } this.outLabel.text(this.outDate.val()).removeClass("is-hidden"); } this.firstTime = false; if (this.config.callbacks.onDateSelect) { this.config.callbacks.onDateSelect(date, type); } }; Datepicker.prototype._inValue = function() { var inDate = this.inDate.data("pickadate"); return new Date(inDate.get("select", this.config.dateFormatLabel)); }; Datepicker.prototype._outValue = function() { var outDate = this.outDate.data("pickadate"); return new Date(outDate.get("select", this.config.dateFormatLabel)); }; Datepicker.prototype._isValidEndDate = function() { return this._inValue() < this._outValue(); }; return Datepicker; });
C++
UTF-8
589
3.0625
3
[]
no_license
class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<int> ans; for (int i = 0; i < numbers.size() - 1; i ++) { for (int j = i + 1; j < numbers.size(); j ++) { if (numbers[i] + numbers[j] == target) { ans.push_back(i + 1); ans.push_back(j + 1); return ans; } } } return ans; } };
Python
UTF-8
581
3.78125
4
[]
no_license
# Program to convert the decimal number to binary def dectobin(n): split_num = str(n).split('.') int_part = int(split_num[0]) decimal_part = '0.'+split_num[1] decimal_part=float(decimal_part) val1='' val2='' while(int_part!=0): rem=int_part%2 val1=str(rem)+val1 int_part=int_part//2 while(decimal_part<=1): res=decimal_part*2 val2=val2+str(int(res)) decimal_part=res print(val1+'.'+val2) def main(): n=float(input("Enter the number to convert binary")) # n=43.167 dectobin(n) main()
Java
UTF-8
358
2.609375
3
[]
no_license
package tests; import static org.junit.Assert.*; import org.junit.Test; import model.HorseshoeCrab; public class HorseshoeCrabTest { @Test public void moveTest() { HorseshoeCrab tester = new HorseshoeCrab(0, 0); int oldX = tester.getX(); int oldY = tester.getY(); tester.move(); assertTrue(tester.getX()!= oldX || tester.getY()!= oldY); } }
PHP
UTF-8
3,350
2.71875
3
[]
no_license
<?php #doc # classname: Googlestorage # scope: PUBLIC # #/doc class GoogleStorage extends RestfulService { # internal variables /** * @static * @var int $project_id */ static $project_id; /** * Set the type of Auth class the client should use. * @param int $projectid */ public function setProjectId($projectid) { self::$project_id = $projectid; } /** * Get the Project Id. * @return int $project_id */ public function getProjectId() { return self::$project_id; } # Constructor function __construct ($expiry = 0) { # code... # Populate the necessary headers $config = DataObject::get_one('SiteConfig',false); //Check expiry of last token $currenttime = time(); $isExpired = ($config->expiry < $currenttime) ? TRUE : FALSE; if ($isExpired) { # Token Expired. Refresh that bad boy. $client = new apiClient(); $client->refreshToken($config->refresh_token); $client->authenticate(); $newtoken = json_decode($client->getAccessToken()); $config->expiry = $currenttime + $newtoken->expires_in; $config->access_token = $newtoken->access_token; $config->write(); } //Set Auth Header self::httpHeader('Authorization: OAuth '.$config->access_token); //Set Date Header $date = date(DATE_RFC1123); self::httpHeader('Date: '.$date); //Set Host Header self::httpHeader('Host: commondatastorage.googleapis.com'); //Set the The Google Cloud Storage API version Header self::httpHeader('x-goog-api-version: 2'); //Other Required header is Content Length should be set at time of connect parent::__construct('commondatastorage.googleapis.com/', $expiry); } ### public function getBucket($name) { //List the objects in the given bucket $subUrl = $name; self::addAuthHeader(); //Set the Content Length Header self::httpHeader('Content-Length: 0','GET',null); $req = self::request($subUrl); return $req->getBody(); } public function putObject($bucketName,$targetfile,$data,$public="FALSE") { //Put new object or replace existing $subUrl = $bucketName.'/'.$targetfile; self::addAuthHeader(); //Set the Content Length Header $req = self::request($subUrl, $method = "PUT", $data); return $req; } public function getObject($bucketName,$targetfile) { //Put new object or replace existing $subUrl = $bucketName.'/'.$targetfile; self::addAuthHeader(); //Set the Content Length Header $req = self::request($subUrl, $method = "Get"); return $req; } private function addAuthHeader() { # Populate the necessary headers $config = DataObject::get_one('SiteConfig',false); //Check expiry of last token $currenttime = time(); $isExpired = ($config->expiry < $currenttime) ? TRUE : FALSE; if ($isExpired) { # Token Expired. Refresh that bad boy. $client = new apiClient(); $client->refreshToken($config->refresh_token); $client->authenticate(); $newtoken = json_decode($client->getAccessToken()); $config->expiry = $currenttime + $newtoken->expires_in; $config->access_token = $newtoken->access_token; $config->write(); } //Set Auth Header self::httpHeader('Authorization: OAuth '.$config->access_token); } } ###
JavaScript
UTF-8
1,140
2.546875
3
[]
no_license
import React, { Component } from 'react'; import api from '../../services/api'; import Menu from '../Menu/index'; import Promotions from '../Promotions/index'; class Wrapper extends Component { constructor(props){ super(props); this.state= { promotions: [], } } componentDidMount() { // serve para executar o metodo ou component assim que ele aparece this.loadApi(); } loadApi = async () => { const response = await api.get('/'); // o response ta recebendo o metodo get da api this.setState({ promotions: response.data }); // promotions recebendo os dados da response.date console.log(this.state.promotions); } thisNew = () => { const { promotions } = this.state; const newPromo = promotions.filter(item => { return item.onlyNewCustomers === true; }) console.log(newPromo); } render() { return ( <> <Menu handleClickNew={this.thisNew}/> <Promotions /> </> ) } } export default Wrapper;
C
UTF-8
1,015
2.71875
3
[]
no_license
void game() { int** fieldCurrent, ** fieldNext; int* arr; int len, flag; fieldCurrent = fieldNext = NULL; setup_terminal(); init(&fieldCurrent, &fieldNext, &flag, &arr, &len); if (flag) { gameCycle(fieldCurrent, fieldNext, arr, len); } reset_terminal(); free(arr); } void gameCycle(int** fieldCurrent, int** fieldNext, int* hashArr, int hashLen) { int freezeFlag, empltyFlag, keyFlag, sameFlag; keyFlag = 0, freezeFlag = 0, empltyFlag = 0, sameFlag = 0; mOutput(fieldCurrent); while (1) { getKey(&keyFlag); setup_terminal(); printf("\033[0d\033[2J"); reset_terminal(); if (keyFlag == 1) { nextState(fieldCurrent, fieldNext, &freezeFlag, &empltyFlag); mOutput(fieldNext); sameFlag = hashCheck(fieldNext, hashArr, &hashLen); swap(&fieldCurrent, &fieldNext); printf("\n"); } else { mOutput(fieldCurrent); } if (freezeFlag == 1 || empltyFlag == 1 || sameFlag == 1 || keyFlag == 2) break; } reset_terminal(); }
C#
UTF-8
815
3.71875
4
[]
no_license
using System; namespace Exercise2 { class Exercise2 { public void Execute() { var calculator = new Calculator(); // 演算方法を登録 calculator.AddOperator(Operator.Add, add); calculator.AddOperator(Operator.Sub, subtract); calculator.AddOperator(Operator.Mul, multiply); calculator.AddOperator(Operator.Div, divide); // 演算方法を指定して演算 Console.WriteLine(calculator.Calculate(Operator.Add, 12, 30)); // 出力 : 42 Console.WriteLine(calculator.Calculate(Operator.Div, 252, 6)); // 出力 : 42 } private int add(int a, int b) { return a + b; } private int subtract(int a, int b) { return a - b; } private int multiply(int a, int b) { return a * b; } private int divide(int a, int b) { return a / b; } } }
C++
UTF-8
4,644
3.21875
3
[]
no_license
/* *William Dunston *Michael De Long *COMP 350: Section 1 *November 15, 2020 *Final checkpoint: Commands can now be executed from batch files *This feature is determined at the execution time */ #include <bits/stdc++.h> #include<iostream> #include<unistd.h> #include<string.h> #include<fstream> #include<stdlib.h> using namespace std; char environmentPath[]="ASH=/bin";//Create path variable string prompt="ash"; void programErrors(){ cout<<"An error has occurred"<<endl; } //Prompts the user for a command and stores the command string getPrompt(){ char command[100];//Utilize char array to store 99 character commands cout<<prompt<<"> "; cin.getline(command,100); return command; } //Displays the exit prompt void printExit(){ cout<<"Exit William Dunston, Michael De Long."<<endl; exit(0); } bool correctChangeDirectory(string userCommand){//Method to confirm command format int size=userCommand.length(); bool result=true; for(int i=3;i<size;i++){ if(userCommand[i]==' '){ result=false; } } return result; } //Executed when change directory command is executed void changeDirectory(string userCommand){ string prefix="ash";//Store ash CLI prefix char destination[100];//Store the directory destination bool correctCommand=correctChangeDirectory(userCommand); if(userCommand==" "|userCommand.length()==0){//Change to home directory chdir("~"); getcwd(destination,100); } else if(correctCommand==false){//Error detected in change directory programErrors(); } else{//Change to a child directory chdir(userCommand.c_str()); getcwd(destination,100); } prompt=prefix+string(destination); } //FIX ME void changePath(){//Set empty path cout<<"Non-built in function are no longer available."<<endl; setenv("PATH"," ",1);//Prevent the use of non-built in functions } void changePath(string userCommand){//Set user specified path int pathPosition=0;//Keep track of path part setenv("PATH"," ",1);//Reset the path variable cout<<"Depending on your path, non-built in functions may be available."<<endl; stringstream paths(userCommand); string path; while(getline(paths, path,' ')){//Tokenize the string for paths by space if(pathPosition==0){ setenv("PATH",path.c_str(),1);//The first part of the path becomes the value } else{ string newPath=getenv("PATH")+':'+path;//If more paths added, concatenate and append setenv("PATH",newPath.c_str(),1); } pathPosition++; } } void nonBuiltInCommand(string userCommand){//Execvp non built in user commands //Convert command into execvp format char* commandPointer=new char[userCommand.length()+1]; strcpy(commandPointer,userCommand.c_str()); //Create a NULL terminated array of character pointers for execvp char* args[]={commandPointer,NULL}; //Execute non built in command execvp(args[0],args); } void readFromBatchFile(string fileName){ fstream batchFile; batchFile.open(fileName); string userCommand; while(getline(batchFile,userCommand)){ if(userCommand.substr(0,4)=="exit"){//Tell the loop when to break printExit(); } else if(userCommand.substr(0,2)=="cd"){//If change directory command entered changeDirectory(userCommand); } else if(userCommand.substr(0,4)=="path"){//Change the search path if(userCommand.length()==4){ changePath(); } else{ changePath(userCommand.substr(5)); } } else{//Handle non built in commands nonBuiltInCommand(userCommand); } } printExit();//Exit when the end of the file is reached } int main(int argc, char* argv[]){ putenv(environmentPath);//Initialize path to /bin if(argc==2){//Read commands from batch files string fileName=argv[1];//Get file name from command line cout<<"Reading commands from batch file: "<<fileName<<endl; readFromBatchFile(fileName); } else if(argc==1){//Interactive mode while(true){//Continuously displays the command prompt string userCommand=getPrompt();//Gets and stores the user's command if(userCommand.substr(0,4)=="exit"){//Tell the loop when to break printExit(); break; } else if(userCommand.substr(0,2)=="cd"){//If change directory command entered changeDirectory(userCommand.substr(3)); } else if(userCommand.substr(0,4)=="path"){//Change the search path if(userCommand.length()==4){ changePath(); } else{ changePath(userCommand.substr(5)); } } else{//Handle non built in commands nonBuiltInCommand(userCommand); } } } else{ programErrors(); } }
Java
UTF-8
1,186
2.109375
2
[]
no_license
package com.wetic.jersey.mapper; import com.wetic.jersey.domain.Facture; import com.wetic.jersey.service.dto.FactureDTO; import javax.annotation.Generated; import org.springframework.stereotype.Component; @Generated( value = "org.mapstruct.ap.MappingProcessor", date = "2019-08-23T14:55:31+0200", comments = "version: 1.3.0.Final, compiler: javac, environment: Java 1.8.0_121 (Oracle Corporation)" ) @Component public class FactureMapperImpl implements FactureMapper { @Override public FactureDTO toEntityDTO(Facture v) { if ( v == null ) { return null; } FactureDTO factureDTO = new FactureDTO(); if ( v.getId() != null ) { factureDTO.setId( v.getId() ); } factureDTO.setDateFacturation( v.getDateFacturation() ); return factureDTO; } @Override public Facture toEntity(FactureDTO t) { if ( t == null ) { return null; } Facture facture = new Facture(); facture.setId( t.getId() ); facture.setDateFacturation( t.getDateFacturation() ); return facture; } }
Java
UTF-8
826
2.9375
3
[]
no_license
package weeklytest; import java.math.BigDecimal; import java.math.BigInteger; /** * @author 彭康 * @create 2021-08-15 11:17 **/ public class No5844 { public int minNonZeroProduct(int p) { if (p == 1) { return 1; } // 注意bigInteger的用法 return BigInteger.valueOf((1L << p) - 2).modPow( BigInteger.valueOf((1L << (p - 1)) - 1), BigInteger.valueOf(1000000007)) .multiply(BigInteger.valueOf((1L << p) - 1)).mod(BigInteger.valueOf(1000000007)).intValue(); } public static void main(String[] args) { No5844 no5844 = new No5844(); for (int i = 1; i <= 60; i++) { int ans = no5844.minNonZeroProduct(i); System.out.println(i + "----" + ans); } String s = "age"; } }
Swift
UTF-8
655
2.765625
3
[ "MIT" ]
permissive
// // Pipe.swift // ManualLayoutUtility // // Created by Hoon H. on 2016/07/23. // Copyright © 2016 Eonil. All rights reserved. // import CoreGraphics func | <T>(a: T, b: T -> T) -> T { return b(a) } func atLeast(k: CGFloat) -> (CGFloat) -> (CGFloat) { return { Swift.max(k, $0) } } func atMost(k: CGFloat) -> (CGFloat) -> (CGFloat) { return { Swift.min(k, $0) } } func atLeast(k: CGSize) -> (CGSize) -> (CGSize) { return { max(k, $0) } } func atMost(k: CGSize) -> (CGSize) -> (CGSize) { return { min(k, $0) } } func and(a: Bool, b: Bool) -> Bool { return a && b } func or(a: Bool, b: Bool) -> Bool { return a || b }
JavaScript
UTF-8
1,408
2.734375
3
[]
no_license
/** * Created by yonghan on 2018/6/24. */ import * as THREE from 'three'; class Cube{ constructor (width, height, depth, color, x, y, z){ this.width = width; this.height = height; this.depth = depth; this.color = color; this.x = x; this.y = y; this.z = z; this.mesh = null; this.createMesh(); } createMesh(){ let geometry = new THREE.CubeGeometry(this.width, this.height, this.depth); let material = new THREE.MeshLambertMaterial({color: this.color}); this.mesh = new THREE.Mesh(geometry, material); this.mesh.position.set(this.x + this.width / 2, this.y + this.height / 2, this.z + this.depth / 2); this.mesh.castShadow = true; this.mesh.receiveShadow = true; } } class PhongCube extends Cube{ createMesh(){ let geometry = new THREE.CubeGeometry(this.width, this.height, this.depth); let material = new THREE.MeshPhongMaterial({ color: this.color, transparent: true, opacity: .6, specular: 0xffffff}); this.mesh = new THREE.Mesh(geometry, material); this.mesh.position.set(this.x + this.width / 2, this.y + this.height / 2, this.z + this.depth / 2); this.mesh.castShadow = true; this.mesh.receiveShadow = true; } } export default Cube export {PhongCube}
C++
UTF-8
2,198
3.359375
3
[]
no_license
/* Design a logger system that receives a stream of messages along with their timestamps. Each unique message should only be printed at most every 10 seconds (i.e. a message printed at timestamp t will prevent other identical messages from being printed until timestamp t + 10). All messages will come in chronological order. Several messages may arrive at the same timestamp. Implement the Logger class: Logger() Initializes the logger object. bool shouldPrintMessage(int timestamp, string message) Returns true if the message should be printed in the given timestamp, otherwise returns false. Example 1: Input ["Logger", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage"] [[], [1, "foo"], [2, "bar"], [3, "foo"], [8, "bar"], [10, "foo"], [11, "foo"]] Output [null, true, true, false, false, false, true] Explanation Logger logger = new Logger(); logger.shouldPrintMessage(1, "foo"); // return true, next allowed timestamp for "foo" is 1 + 10 = 11 logger.shouldPrintMessage(2, "bar"); // return true, next allowed timestamp for "bar" is 2 + 10 = 12 logger.shouldPrintMessage(3, "foo"); // 3 < 11, return false logger.shouldPrintMessage(8, "bar"); // 8 < 12, return false logger.shouldPrintMessage(10, "foo"); // 10 < 11, return false logger.shouldPrintMessage(11, "foo"); // 11 >= 11, return true, next allowed timestamp for "foo" is 11 + 10 = 21 */ #include <bits/stdc++.h> #define FOR(i,a,b) for(int i=a; i<b; i++) #define NFOR(i,a,b) for(int i=(a-1); i>=(b); i--) #define ll long long int #define ld long long double #define f first #define s second #define pb push_back #define mp make_pair #define max(x,y) (x>y)?x:y #define min(x,y) (x<y)?x:y const int INF = 1<<29; using namespace std; class Logger { public: Logger() {} map<string, int> ok; bool shouldPrintMessage(int timestamp, string message) { if (timestamp < ok[message]) return false; ok[message] = timestamp + 10; return true; } }; int main(){ return 0; }
Markdown
UTF-8
1,321
2.546875
3
[]
no_license
To run: 1) Clone repository from github 2) Create tomcat server as data source 3) Run resources/openhouse_exercise.sql 4) Connect to end points to alter or view data: Display all logs: GET /logs Display a single log: GET /logs/{id} Add log: POST /logs Add request body to add data Update log: PUT /logs Add request body to add data Delete log: DELETE /logs/{id} Display logs based on search criteria: GET /logs/search Add request body to add search criteria All documentation has been done using javadoc There is one small bug, which after several hours I was unable to fix. When data is sent to the POST endpoint, all the data is saved, but the foreign key for logs in the account table is not filled in. This results in some data for accounts not being retrieved properly. Also, in order to make this cloud-scalable, we would want to set up the storage so that it was stored as some sort of a tree, possibly an AVL tree. That way we could store the data in a sorted manner, and query all of that data in a much more efficient manner.
Java
UTF-8
645
2.109375
2
[]
no_license
package org.dayatang.security.domain; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; /** * Created by yyang on 15/7/27. */ @Entity @DiscriminatorValue("GLOBAL") public class GlobalAuthorityScope extends AuthorityScope { protected GlobalAuthorityScope() { super("GLOBAL"); } public static final GlobalAuthorityScope get() { GlobalAuthorityScope result = getRepository().createCriteriaQuery(GlobalAuthorityScope.class).singleResult(); if (result == null) { result = new GlobalAuthorityScope(); result.save(); } return result; } }
Java
UTF-8
2,667
2.3125
2
[]
no_license
package com.cypay.common.shiro; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.filter.mgt.FilterChainManager; import org.apache.shiro.web.filter.mgt.FilterChainResolver; import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver; import org.apache.shiro.web.mgt.WebSecurityManager; import org.apache.shiro.web.servlet.AbstractShiroFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.BeanInitializationException; public class MyShiroFilterFactoryBean extends ShiroFilterFactoryBean { private static transient final Logger log = LoggerFactory.getLogger(MyShiroFilterFactoryBean.class); @Override protected AbstractShiroFilter createInstance() throws Exception { log.debug("Creating Shiro Filter instance."); SecurityManager securityManager = getSecurityManager(); if (securityManager == null) { String msg = "SecurityManager property must be set."; throw new BeanInitializationException(msg); } if (!(securityManager instanceof WebSecurityManager)) { String msg = "The security manager does not implement the WebSecurityManager interface."; throw new BeanInitializationException(msg); } FilterChainManager manager = createFilterChainManager(); PathMatchingFilterChainResolver chainResolver = new PathMatchingFilterChainResolver(); chainResolver.setFilterChainManager(manager); return new SpringShiroFilter((WebSecurityManager) securityManager, chainResolver); } private static final class SpringShiroFilter extends AbstractShiroFilter { protected SpringShiroFilter(WebSecurityManager webSecurityManager, FilterChainResolver resolver) { super(); if (webSecurityManager == null) { throw new IllegalArgumentException("WebSecurityManager property cannot be null."); } setSecurityManager(webSecurityManager); if (resolver != null) { setFilterChainResolver(resolver); } } @Override protected ServletRequest wrapServletRequest(HttpServletRequest orig) { if (orig.getRequestURI().indexOf("/wechat/conn") == 0) { log.debug("【SSE】:The request({}) not wrap.", orig); return orig; } return super.wrapServletRequest(orig); } } }
Ruby
UTF-8
1,662
2.90625
3
[]
no_license
require "frozen_synapse/lazy_attributes" require "open-uri" require "json" module FrozenSynapse # @attr_reader [String] username # @attr_reader [Number] wins # @attr_reader [Number] losses # @attr_reader [Number] level # @attr_reader [Time] registered_at # @attr_reader [Float] rating The user's rating according to the Elo rating system # @attr_reader [Hash<Symbol<:daily, :streak, :global> => String>] rank The user's ranks class User include FrozenSynapse::LazyAttributes extend FrozenSynapse::LazyAttributes lazy_attr_reader :wins lazy_attr_reader :losses lazy_attr_reader :level lazy_attr_reader :registered_at lazy_attr_reader :rating # TODO ranks def initialize(username) @username = username @wins = @losses = @level = @registered_at = @rating = @rank = nil @populated = false end # Populate the user object with all attributes. Normally you don't # have to call this method directly, unless you are using # {FrozenSynapse::Rankings) # # @return [void] # @see FrozenSynapse::Rankings def populate(force = false) return if @populated == true && !force data = FrozenSynapse.make_request("user/#{@username}/profile") @wins = data["wins"] @losses = data["losses"] @level = data["level"] @rank = { :daily => data["daily_rank"], :streak => data["streak_rank"], :global => data["global_rank"], } @registered_at = Time.parse(data["date_full_registered"]) # TODO check if Time.parse is parsing correctly @rating = data["elo_rating"] @populated = true end end end
Java
UTF-8
3,371
2.953125
3
[]
no_license
package dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; public class AvatarDAO { private static final String TBLNAME = "avatar"; /* public static void main(String[] args){ AvatarDAO ad= new AvatarDAO(); System.out.println(ad.getAvatarName(2)); }*/ private void handleSQLException(SQLException ex, String sql, String... parameters) { String msg = "Unable to access data; SQL=" + sql + "\n"; for (String parameter : parameters) { msg += "," + parameter; } Logger.getLogger(StudentDAO.class.getName()).log(Level.SEVERE, msg, ex); throw new RuntimeException(msg, ex); } public void registerAvatar(String avatarName){ Connection conn = null; PreparedStatement stmt = null; String sql = ""; try { conn = ConnectionManager.getConnection(); sql = "insert into avatar (avatar_name, icon, avatar_qa_coin, avatar_thoughtfulness_score, section_id, is_bot) values (?,?,?,?,?,?)"; stmt = conn.prepareStatement(sql); stmt.setString(1, avatarName); stmt.setString(2,"");//icon stmt.setInt(3,0);//avatar_qa_coin stmt.setInt(4, 0); //avatar_thoughtfulness_score stmt.setString(5, ""); //section_id stmt.setInt(6, 0); //is_bot stmt.executeUpdate(); } catch (SQLException ex) { String msg = "An exception occurs during registration"; handleSQLException(ex, sql, "msg={" + msg + "}"); } finally { ConnectionManager.close(conn, stmt); } } public int lastAvatarID(){ Connection conn = null; PreparedStatement stmt = null; String sql = ""; int returnAvatarID = 0; ResultSet rs = null; try { conn = ConnectionManager.getConnection(); sql = "select MAX(avatar_id) FROM " + TBLNAME; stmt = conn.prepareStatement(sql); rs = stmt.executeQuery(); while (rs.next()) { returnAvatarID = rs.getInt(1); } } catch (SQLException ex) { handleSQLException(ex, sql, "avatar_id={" + returnAvatarID + "}"); } finally { ConnectionManager.close(conn, stmt, rs); } return returnAvatarID; } public String getAvatarName(int avatar_id){ Connection conn = null; PreparedStatement stmt = null; String sql = ""; String returnAvatarName = ""; ResultSet rs = null; try { conn = ConnectionManager.getConnection(); sql = "select avatar_name FROM " + TBLNAME +" WHERE avatar_id = ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, avatar_id); rs = stmt.executeQuery(); while (rs.next()) { returnAvatarName = rs.getString(1); } } catch (SQLException ex) { handleSQLException(ex, sql, "avatar_name={" + returnAvatarName + "}"); } finally { ConnectionManager.close(conn, stmt, rs); } return returnAvatarName; } }
Python
UTF-8
3,575
3.71875
4
[ "MIT", "Python-2.0" ]
permissive
# Opetetaan kilpikonna piirtämään tähtiä! import turtle t = turtle.Turtle() ##### INFO ##### # # Tutustuimme tähden piirtämiseen jo aikaisemmassa # tehtävässä. Komennot ovat alla muistin virkistykseksi. # # Tähden piirtäminen vaatii monta vaihetta. Entä jos haluamme # piirtää monta tähteä? Tarvitseeko kaikki vaiheet toistaa # uudelleen? Onneksi ei! Annamme tähden piirtävälle joukolle # komentoja nimen käytämme sitä uudelleen. # # Ohjelmoinnissa nimettyä joukkoa komentoja kutsutaan funktioksi. # Seuraava koodinpätkä määrittelee uuden funtion. # # "tahti()" on nimi jonka annamme funktiolle. Nimi voi olla # mitä vain kunhan se loppuu sulkuihin () def tahti(): # "tahti()" on lyhennetty muoto seuraaville komennoille. # Kaikki "def" avainsanan jälkeen sisennetty koodi on osa # funktiota. t.forward(50) t.left(160) t.forward(50) t.right(70) t.forward(50) t.left(160) t.forward(50) t.right(70) t.forward(50) t.left(160) t.forward(50) t.right(70) t.forward(50) t.left(160) t.forward(50) t.right(70) # Funktio ei itsessään tee vielä mitään. Funktion koodi ajetaan # vasta kun funtiota kutsutaan nimeltä. Voit testata että mitään # ei tapahdu kun painat run. ##### TEHTÄVÄ 1 ##### # # Voit nyt ajaa tähden piirtämiseen vaadittavat komennot # kutsumalla funktion nimeä. # Poista kommentti seuraavalta riviltä ja paina run # niin näet mitä funktio tekee. # tahti() ##### TEHTÄVÄ 2 ##### # # Piirretään tähtiä! "t.goto" siirtää kilpikonnaa uuteen # paikkaan ja "tahti()" piirtää tähden. Poista kommentit # seuraavilta riveiltä. # t.penup() # t.goto(80, -40) # t.pendown() # tahti() # Piirrä vielä kaksi tähteä lisää haluamaasi paikkaan käyttäen # edellistä kaavaa kilpikonnan liikutteluun. ##### # TEHTÄVÄ 3 ##### # # Tähän mennessä kaikki tähdet ovat ollet saman kokoisia, koska # tähden sivun pituus on määritelty olemaan 50 pikseliä kohdassa # "t.forward(50)" # # Entä jos haluamme pirtää erikokoisia tähtiä? Voimme korvata # sivunpituuden 50 muuttujalla ja antaa halutun pituuden funktiolle # sitä kutsuttaessa. # # Alla on uusi funktio. Se on muuten sama kuin tahti() -funktio, # mutta tähden sivun pituus on korvattu muuttujalla "koko". # Huomaa että muuttuja koko annetaan funktion sulkeiden sisällä. # Funktiolle annettavaa muuttujaa kututaan myös parametriksi. # Tämä tarkoittaa että muuttujan "koko" todellinen arvo # määritellään vasta funktiota kutsuttessa. def tahti_koolla(koko): t.forward(koko) t.left(160) t.forward(koko) t.right(70) t.forward(koko) t.left(160) t.forward(koko) t.right(70) t.forward(koko) t.left(160) t.forward(koko) t.right(70) t.forward(koko) t.left(160) t.forward(koko) t.right(70) # Funtiolle tahti_koolla annettaan muuttujan koko arvo parametrina # funktiota kutsuttaessa. Käytännössä tämä tapahtuu lisäämällä parametrin # koko arvo funktion kutsun sulkeiden sisään. # Esimerkiksi kutsu "tahti_koolla(10)" piirtää pienen tähden, koska # jokaisessa "t.forward(koko)" kutsussa koko korvataan nyt 10:llä. # Huomaa että nyt funktiolle on pakko antaa jokin arvo sulkeiden # sisällä. Muuten funtio ei tiedä mikä muuttujan koko arvo on ja # koodi aiheuttaa virheen. # Poista kommentit seuraavilta riveiltä piirtääksesi pienen tähden. # t.penup() # t.goto(-80, 100) # t.pendown() # tahti_koolla(20) # Piirrä seuraavaksi # pieni tähti (koko = 12), # keskikokoinen tähti (koko=25) # ja jättitähti (koko=100) # Haluamiisi paikkoihin
C
UTF-8
2,938
3.515625
4
[]
no_license
#include <stdio.h> #include <stdlib.h> #define STRSIZE 10000 #define DEBUG if(0) typedef struct{ char item; struct node* tail; struct node* next; }node; node* createList(){ return NULL; } int isEmpty(node *head){ return (head==NULL); } node* clearList(node *head){ node* aux = NULL; while (head->next != NULL){ aux = head; head = head->next; aux->next = NULL; free(aux); } return NULL; } node* addToHead(node *head, char item){ node *newNode; newNode = malloc(sizeof(node)); newNode->item = item; newNode->next = head; if (isEmpty(head)) newNode->tail = newNode; else newNode->tail = head->tail; return newNode; } node* addToTail(node *head, char item){ node *newNode; newNode = malloc(sizeof(node)); newNode->item = item; newNode->next = NULL; if (isEmpty(head)) return (addToHead(head, item)); node* tail = head->tail; tail->next = newNode; head->tail = newNode; return head; } node* removeByPointer(node *head, node *prev, node *current){ prev->next = current->next; free(current); return head; } node* search(node *head, char item){ while(head!=NULL){ if (head->item==item) return head; else head = head->next; } return NULL; } node* invertList(node *head){ int x; node *prev, *current; prev = head; current = head->next; while (current!=NULL){ x = current->item; head = removeByPointer(head, prev, current); head = addToHead(head, x); current = prev->next; } return head; } void printList(node *head){ if (isEmpty(head)) printf("List Underflow"); else while (!isEmpty(head)){ printf("%c ", head->item); head = head->next; } printf("\n"); return; } void tratamentoDaEntrada(node* lista){ char c, ant1, ant2; c = fgetc(stdin); ant1 = '.'; ant2 = '.'; while ((!((c=='\n')&&(ant1=='0')&&(ant2=='\n')))){ if (ant1 != '.'){ if (ant1!='\n') lista = addToTail(lista, ant1); else{ DEBUG{printList(lista);} maiorIntervalo(lista); lista = clearList(lista); DEBUG{printList(lista);} } } ant2 = ant1; ant1 = c; if ((c = fgetc(stdin))==EOF) break; } } void maiorIntervalo(node* head){ int a,b; int pos = 0; int max = 0; int maxPOS[2] = {0,0}; int atual = 0; a = pos; b = pos; while (head!=NULL){ DEBUG{printf("%c - ", head->item);} if (head->item == '0') { DEBUG{printf(" IF ");} atual++; DEBUG{printf("a = %d b = %d max = %d atual = %d\n", a,b,max,atual);} if (atual!=1) b++; if (atual>max){ max = atual; maxPOS[0] = a; maxPOS[1] = b; } }else{ DEBUG{printf(" ELSE ");} atual = 0; DEBUG{printf("a = %d b = %d max = %d atual = %d\n", a,b,max,atual);} if (atual>max){ max = atual; maxPOS[0] = a; maxPOS[1] = b; } a = pos + 1; b = a; } head = head->next; pos++; } a = maxPOS[0]; b = maxPOS[1]; printf("%d %d\n", a,b); } int main(){ node *lista; lista = createList(); tratamentoDaEntrada(lista); return 0; }
JavaScript
UTF-8
438
2.640625
3
[ "MIT" ]
permissive
const Command = require("../../core/Command"); const jokes = require("jokeslol"); class dadjoke extends Command { constructor(rice) { super(rice, { name: "dadjoke", category: "Fun", botPerms: ["sendMessages"], description: "Gets a funny Dad Joke", }); } async run(message, args) { jokes.DadJoke(function (joke) { return message.channel.send(joke); }); } } module.exports = dadjoke;
C++
UTF-8
518
2.765625
3
[]
no_license
/** * @file Variant.hpp * @author Gonzalo Perez Chamarro (Gonzalo1810 Github) * @brief Clase Variant, para el uso de variables no tipadas * @version 0.1 * @date 2019-05-24 * * @copyright Copyright (c) 2019 * */ #include "OpenGL.hpp" namespace example { struct Variant { enum Type { INT, FLOAT, UINT, VEC2, VEC3, VEC4, BOOL }type; union Value { GLint integer; GLuint uinteger; GLfloat f; GLfloat vec2[2]; GLfloat vec3[3]; GLfloat vec4[4]; }value; GLint id; }; }
Java
UTF-8
132
1.859375
2
[]
no_license
package randomgenerators; public interface Generator { public double generate(); public int generateS(); }
Markdown
UTF-8
1,818
3.1875
3
[]
no_license
# Javascript Embedding a JavaScript Service enables to use both the JavaScript language and Java methods by importing their classes. Let us rewrite the [_twice_ service example](https://github.com/jolie/docs/tree/f2682237d6cab2ca909d857f22b3e964ae8d11d8/technology-integration/getting-started/set_execution_modality/README.md) as a JavaScript embedded service. ```javascript importClass( java.lang.System ); importClass( java.lang.Integer ); function twice( request ) { var number = request.getFirstChild("number").intValue(); System.out.println( "Received a 'twice' request for number: " + number ); return Integer.parseInt(number + number); } ``` At Lines 1-2 we respectively import `java.lang.System` to use it for printing at console a message, and `java.lang.Integer` to send a proper response to the embedder. This is necessary because of JavaScript's single number type which, internally, represents any number as a 64-bit floating point number. At Line 6 the methods `getFirstChild` and `intValue`, belonging to `Value` class, are used to read the request's data. Finally at Line 8 we use the `parseInt` method of class `Integer` to return an `Integer` value to the invoker. ```jolie include "console.iol" type TwiceRequest:void { .number: int } interface TwiceInterface { RequestResponse: twice( TwiceRequest )( int ) } outputPort TwiceService { Interfaces: TwiceInterface } embedded { JavaScript: "TwiceService.js" in TwiceService } main { request.number = 5; twice@TwiceService( request )( response ); println@Console( "Javascript 'twice' Service response: " + response )() } ``` Like embedding Jolie Services, also JavaScript Services require the specification of the local file where the JavaScript Service is defined \(i.e., `TwiceService.js`, Line 18\).
JavaScript
UTF-8
5,609
2.90625
3
[]
no_license
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } var Comparison_Operator; (function (Comparison_Operator) { Comparison_Operator["Includes"] = "includes"; Comparison_Operator["Not_includes"] = "not_includes"; Comparison_Operator["Equal"] = "equal"; Comparison_Operator["Not_equal"] = "not_equal"; Comparison_Operator["Greater"] = "greater"; Comparison_Operator["Greater_or_equal"] = "greater_or_equal"; Comparison_Operator["Lower"] = "lower"; Comparison_Operator["Lower_or_equal"] = "lower_or_equal"; Comparison_Operator["Not"] = "not"; })(Comparison_Operator || (Comparison_Operator = {})); var Logical_Operator; (function (Logical_Operator) { Logical_Operator["Or"] = "or"; Logical_Operator["And"] = "and"; })(Logical_Operator || (Logical_Operator = {})); var Text_Type; (function (Text_Type) { Text_Type["Remaining"] = "remaining"; Text_Type["Number"] = "number"; })(Text_Type || (Text_Type = {})); var Token_Type = _objectSpread2({}, Comparison_Operator, {}, Logical_Operator, {}, Text_Type); function Tokenizer(input) { var tokens = []; var current = 0; function skip_break() { while (current < input.length && is_break(input[current])) { current++; } } function Read_Factory(checker) { return function () { var value = ''; while (current < input.length && checker(input[current])) { value += input[current]; current++; } return value; }; } var read_number = Read_Factory(is_number); var read_remaining = Read_Factory(is_remaining); var read_operator = Read_Factory(is_operator); function next_token() { var token = { value: '', type: Token_Type.Remaining }; if (is_number(input[current])) { token.value = read_number(); token.type = Token_Type.Number; return token; } if (is_operator(input[current])) { token.value = read_operator(); switch (token.value) { case '=': case '==': token.type = Token_Type.Equal; break; case '!=': token.type = Token_Type.Not_equal; break; case '||': token.type = Token_Type.Or; break; case '&&': token.type = Token_Type.And; break; case '!': token.type = Token_Type.Not; break; case '>': token.type = Token_Type.Greater; break; case '<': token.type = Token_Type.Lower; break; case '>=': token.type = Token_Type.Greater_or_equal; break; case '<=': token.type = Token_Type.Lower_or_equal; break; default: throw new TypeError("Unknown operator \"".concat(token.value, "\"")); } return token; } token.value = read_remaining(); switch (token.value.toLowerCase()) { case 'is': case 'equal': token.type = Token_Type.Equal; break; case 'includes': case 'contains': case 'has': case 'in': token.type = Token_Type.Includes; break; case 'greater': case 'more': case 'above': token.type = Token_Type.Greater; break; case 'lower': case 'less': case 'below': token.type = Token_Type.Lower; break; case 'or': token.type = Token_Type.Or; break; case 'and': token.type = Token_Type.And; break; case 'not': token.type = Token_Type.Not; break; default: token.type = Token_Type.Remaining; break; } return token; } while (current < input.length) { skip_break(); if (is_break(input[current])) break; tokens.push(next_token()); } return tokens; } var breaks = new Set([' ', '\n', '\r', '\t', undefined]); function is_break(char) { return breaks.has(char); } var numbers = new Set(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', ',', '_']); function is_number(char) { return numbers.has(char); } var operators = new Set(['=', '!', '|', '&', '>', '<']); function is_operator(char) { return operators.has(char); } function is_remaining(char) { return !(is_break(char) || is_operator(char)); } export { Comparison_Operator as C, Logical_Operator as L, Text_Type as T, _objectSpread2 as _, Token_Type as a, Tokenizer as b };
Markdown
UTF-8
723
3.09375
3
[]
no_license
# Lynx ![Statamic 2.0](https://img.shields.io/badge/statamic-2.0-blue.svg?style=flat-square) Shorten share links with Bit.ly This addon creates a modifier to shorten urls using the Bit.ly API ## Installation 1. Copy over the files into the `site` folder. 2. Add your [Bit.ly API key](http://dev.bitly.com/) in the `settings/addons/lynx.yaml` `api_key` parameter. 3. Shorten any url using the new `lynx` modifier! ## Branded Links It's best to generate branded links on your production server only to avoid hitting your limit of 500 branded Bitlinks per month. Configure the server you'd like Lynx to run on through the addons settings. ``` environments: - production ``` ## Example ``` {{ permalink | lynx }} ```
Java
UTF-8
4,086
2.40625
2
[]
no_license
package com.service; import java.util.List; import javax.naming.NameNotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.advice.IDNotFoundException; import com.advice.LogInNotFoundException; import com.model.Category; import com.model.Customer; import com.model.Item; import com.model.User; import com.repository.CategoryRepository; import com.repository.ItemRepository; @Service public class ItemService { @Autowired ItemRepository itemRepository; @Autowired CategoryRepository categoryRepository; public Item addItem(Item item, int categoryId,User user) throws Exception { if(user != null) { Category category = categoryRepository.findById(categoryId).orElseThrow(()-> new IDNotFoundException("Category Not Present")); item.setCategory(category); return itemRepository.save(item); } else { throw new LogInNotFoundException("You Can't Login.You Need To Login First"); } } public String deleteItem(int itemId, User user) throws Exception { if(user != null) { Item item = itemRepository.findById(itemId).orElseThrow(()-> new IDNotFoundException("Item ID Are Not Present")); itemRepository.delete(item); return "Delete Succesfuly "; } else { throw new LogInNotFoundException("You Can't Login.You Need To Login First"); } } // UPDATE ITEM public Item updateItem(Item item, int itemId,User user) throws Exception { if(user != null) { Item item2=itemRepository.findById(itemId).orElseThrow(()-> new IDNotFoundException("Item is Not Present You Enter Wrong Item ID")); item2.setPrice(item.getPrice()); item2.setUpdatedAt(item.getCreatedAt()); item2.setItemName(item.getItemName()); item2.setPrice(item.getPrice()); item2.setDescription(item.getDescription()); return itemRepository.save(item2); }else { throw new LogInNotFoundException("You Can't Login.You Need To Login First"); } } //LIST OF ITEM public List<Item> getItem(User user) throws Exception { if(user != null) { return itemRepository.findAll(); }else { throw new LogInNotFoundException("You Can't Login.You Need To Login First"); } } public Item viewItem(int itemId,User user) throws Exception { if(user != null) { return itemRepository.findById(itemId).orElseThrow(()-> new IDNotFoundException("Item Are Not Present")); } else { throw new LogInNotFoundException("You Can't Login.You Need To Login First"); } } public List<Item> getItemList(User user) throws Exception { if(user != null) { return itemRepository.findAll(); } else { throw new LogInNotFoundException("You Can't Login.You Need To Login First"); } } public Item getItemByName(String itemName,User user) throws Exception { if(user != null) { Item item = itemRepository.findByName(itemName); if(item != null) { return item; } else { throw new NameNotFoundException("Name Not Found"); } } else { throw new LogInNotFoundException("You Can't Login.You Need To Login First"); } } public List<Item> getItemByPrice(long price,User user) throws Exception { if(user != null) { List<Item> item = itemRepository.findByPrice(price); if(!item.isEmpty()) { return item; } else { throw new NameNotFoundException("Price Not Found"); } } else { throw new LogInNotFoundException("You Can't Login.You Need To Login First"); } } public List<Item> getItem(int categoryId,Customer customer) throws Exception { if(customer != null) { List<Item> itemList = itemRepository.findBycategoryId(categoryId); if(!itemList.isEmpty()) { return itemList; } else { throw new IDNotFoundException("Category ID is Empty"); } } else { throw new LogInNotFoundException("You Can't Login First Do You Login "); } } }
Python
UTF-8
1,005
2.640625
3
[]
no_license
from google.cloud import language from google.cloud.language import enums from google.cloud.language import types # gcs_uri = 'gs://cloud-samples-data/language/president.txt' gcs_uri = 'gs://nlp-text-1/president.txt' client = language.LanguageServiceClient() # Instantiates a plain text document. document = types.Document( gcs_content_uri=gcs_uri, type=enums.Document.Type.PLAIN_TEXT) # Detects sentiment in the document. You can also analyze HTML with: # document.type == enums.Document.Type.HTML entities = client.analyze_entities(document).entities for entity in entities: entity_type = enums.Entity.Type(entity.type) print('=' * 20) print(u'{:<16}: {}'.format('name', entity.name)) print(u'{:<16}: {}'.format('type', entity_type.name)) print(u'{:<16}: {}'.format('salience', entity.salience)) print(u'{:<16}: {}'.format('wikipedia_url', entity.metadata.get('wikipedia_url', '-'))) print(u'{:<16}: {}'.format('mid', entity.metadata.get('mid', '-')))
C#
UTF-8
586
2.5625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ByBothS { class ListItems { private int valueData; private string displayData; public ListItems(int valueData, string displayData) { this.valueData = valueData; this.displayData = displayData; } public string DisplayData { get {return displayData;} } public int ValueData { get { return valueData; } } } }
Python
UTF-8
745
2.75
3
[]
no_license
import cv2 import numpy as np filename = 'C:\\Users\\kaka\\Documents\\Programing\\Python\\OpenCV-Study\\lena.jpg' img = cv2.imread(filename, 1) hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # 取得する色の範囲を指定する [B,G,R] lower_color = np.array([20, 50, 50]) upper_color = np.array([255, 255, 255]) # 指定した色にも続いたマスク画像の生成 img_mask = cv2.inRange(hsv, lower_color, upper_color) # フレーム画像とま浮く画像の共通の領域を抽出する img_color = cv2.bitwise_and(img, img, mask=img_mask) image_path = 'C:\\Users\\kaka\\Documents\\Programing\\Python\\OpenCV-Study\\' cv2.imwrite(image_path+"02hsv.jpg", img_color) cv2.imshow('hsv.jpg', hsv) cv2.waitKey(0) cv2.destroyAllWindows()
JavaScript
UTF-8
1,517
2.8125
3
[]
no_license
import Models from "../models"; class ExampleRepository { table = ""; constructor(table) { this.table = table; } /** * Example Get Custom Data * @returns MySQL rows */ async exampleGetData() { return new Promise(async (resolve, reject) => { try { // const get = await Models.Examples.findAll(); // console.log(get); resolve({ example1: "value1", example2: "value2" }); } catch (error) { reject(error); } }); } /** * Example Post Custom Data * @returns MySQL rows */ async examplePostData(data) { return new Promise(async (resolve, reject) => { try { setTimeout(() => { resolve(data); }, 1000); } catch (error) { reject(error); } }); } /** * Example Update Custom Data * @returns MySQL rows */ async exampleUpdateData(data, id) { return new Promise(async (resolve, reject) => { try { if (id != 1) { resolve(false); } resolve(data); } catch (error) { reject(error); } }); } /** * Example Delete Custom Data * @returns MySQL rows */ async exampleDeleteData(id) { return new Promise(async (resolve, reject) => { try { if (id != 1) { resolve(false); } resolve(true); } catch (error) { reject(error); } }); } } export default new ExampleRepository("Examples");
C++
UTF-8
1,528
2.890625
3
[]
no_license
#include "stdafx.h" #include "ProgressBar.h" ProgressBar::ProgressBar() { } ProgressBar::~ProgressBar() { } HRESULT ProgressBar::Init(char * frontImage, char * backImage, float x, float y, int width, int height) { _x = x; _y = y; rectProgress = RectMake(x, y, width, height); progressBarFront = new Image; progressBarFront->Init(frontImage, x, y, width, height, true, RGB(255, 0, 255)); progressBarBack = new Image; progressBarBack->Init(backImage, x, y, width, height, true, RGB(255, 0, 255)); _width = progressBarFront->GetWidth(); return S_OK; } void ProgressBar::Release() { SAFE_DELETE(progressBarFront); SAFE_DELETE(progressBarBack); } void ProgressBar::Update() { rectProgress = RectMakeCenter(_x + progressBarBack->GetWidth() / 2, _y + progressBarBack->GetHeight() / 2, progressBarBack->GetWidth(), progressBarBack->GetHeight()); } void ProgressBar::Render(HDC hdc) { progressBarBack->Render(hdc, rectProgress.left, _y, 0, 0, progressBarBack->GetWidth(), progressBarBack->GetHeight()); progressBarFront->Render(hdc,rectProgress.left + 4, _y, 0, 0, _width, progressBarBack->GetHeight()); } void ProgressBar::Render(HDC hdc, float destX, float destY) { progressBarBack->Render(hdc, destX, destY, 0, 0, progressBarBack->GetWidth(), progressBarBack->GetHeight()); progressBarFront->Render(hdc, destX, destY, 0, 0, _width, progressBarBack->GetHeight()); } void ProgressBar::SetGauge(float currentGauge, float maxGauge) { _width = (currentGauge / maxGauge)* progressBarBack->GetWidth(); }
Java
UTF-8
1,459
4.09375
4
[]
no_license
public class PalindromeNumber { /** * 判断是否回文数:如121, 1221,1223221是回文数,-121就不是 * 解题的思路是根据数字翻转的思路,判断最后翻转后的数字是否和输入的数字相等即可(不是最优解) * @param n * @return */ public static boolean isPalindromeNumber(int n){ if(n < 0) { return false; } int rev = 0; int temp = n; while(n != 0){ int tail = n % 10; n = n / 10; if(n > Integer.MAX_VALUE || (rev == Integer.MAX_VALUE / 10 && tail > 7)){ throw new IllegalArgumentException("argument is error"); } rev = rev * 10 + tail; } return rev == temp; } /** * 与第一个方法相比,循环次数减半,判断对称的整数是否相等 * @param x * @return */ public static boolean isPalindromeNumber2(int x){ //先判断为负数或者末尾数为0的结果 if(x < 0 || (x % 10 == 0 && x != 0)){ return false; } int revNum = 0; while(x > revNum){ revNum = revNum * 10 + x % 10; x /= 10; } return x == revNum || x == revNum / 10; } public static void main(String[] args) { System.out.println(isPalindromeNumber2(1223221)); System.out.println(Integer.MAX_VALUE); } }
Markdown
UTF-8
634
2.71875
3
[ "MIT" ]
permissive
# how to solve conflict in git ## 提交时的错误信息 error: Your local changes to the following files would be overwritten by merge: readme.md Please, commit your changes or stash them before you can merge. ## 如果需要保留自己的修改,操作如下: ```bash git stash git pull git stash pop ``` ### 查看并修改差异 ```bash git diff -w +文件名 ``` ## 如果要完全覆盖本地修改的文件. 方法如下: ```bash git reset --hard git pull ``` 其中git reset是针对整个工程, ### 如果想针对文件回退本地修改,使用如下: ```bash git checkout HEAD file/to/restore ```
Shell
UTF-8
197
2.609375
3
[]
no_license
#!/bin/sh TMPFILE="${2}.tmp" grep -n 'in <a' $1 | sort -k 2 -t ':' | uniq -f 1 > "$TMPFILE" grep -nv 'in <a' $1 >> "$TMPFILE" sort -n -k 1 -t ':' "$TMPFILE" | cut -f2- -d ':' >> "$2" rm "$TMPFILE"
Python
UTF-8
662
4.0625
4
[]
no_license
class Solution: # @param nums: The integer array # @param target: Target number to find # @return the first å of target in nums, position start from 0 # @author Egbert Li def binarySearch(self, nums, target): if len(nums) == 0: return -1 start = 0 end = len(nums) - 1 while start + 1 < end: mid = int (start + (end - start) / 2) if target > nums[mid]: start = mid else: end = mid if target == nums[start]: return start elif target == nums[end]: return end else: return -1
Markdown
UTF-8
472
2.640625
3
[]
no_license
# CZ1115-Mini-Project Mini Project for CZ1115 Introduction to Data Science and Artificial Intelligence Dataset being used: https://www.kaggle.com/olistbr/brazilian-ecommerce # Setup Before starting, please download the Brazilian map [here](https://www.ibge.gov.br/#) and place it within `data` Ideas: - Sentiment analysis of reviews - Predict price of product based on category and reviews - Discover trends in Brazilian e-commerce, and how it evolves over the years
Java
UTF-8
5,416
2.46875
2
[]
no_license
package hhh.com.okhttpdemo; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import java.io.IOException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import static hhh.com.okhttpdemo.R.id.get_Asynchronous; import static hhh.com.okhttpdemo.R.id.get_Synchronization; import static hhh.com.okhttpdemo.R.id.post_Asynchronous; public class MainActivity extends Activity implements View.OnClickListener { // Executors.newFixedThreadPool(4); //线城池 private ExecutorService executorService= Executors.newFixedThreadPool(3); private Button get_synchronization; private Button post_Synchronization; private Button get_asynchronous; private Button post_asynchronous; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); get_synchronization = (Button) findViewById(get_Synchronization); post_Synchronization = (Button) findViewById(R.id.post_Synchronization); get_asynchronous = (Button) findViewById(get_Asynchronous); post_asynchronous = (Button) findViewById(post_Asynchronous); get_synchronization.setOnClickListener(this); post_Synchronization.setOnClickListener(this); get_asynchronous.setOnClickListener(this); post_asynchronous.setOnClickListener(this); //线程池 // private ExecutorService executorService = Executors.newFixedThreadPool(3); } @Override public void onClick(View view) { switch (view.getId()){ case get_Synchronization: get_Synchronization(); break; case get_Asynchronous: get_Asynchronous(); break; case R.id.post_Synchronization: post_Synchronization(); break; case post_Asynchronous: post_Asynchronous(); break; } } private void get_Synchronization() { executorService.execute(new Runnable() { @Override public void run() { try { OkHttpClient client = new OkHttpClient(); Request request=new Request.Builder().url("http://publicobject.com/helloworld.txt").build(); Response response = client.newCall(request).execute(); System.out.println("response =" + response.body().string()); } catch (IOException e) { e.printStackTrace(); } } }); } private void get_Asynchronous() { executorService.execute(new Runnable() { @Override public void run() { OkHttpClient client = new OkHttpClient(); Request request=new Request.Builder().url("http://publicobject.com/helloworld.txt").build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { System.out.println("response = " + response.body().string()); } }); } }); } String url="http://publicobject.com/helloworld.txt"; private void post_Synchronization() { executorService.execute(new Runnable() { @Override public void run() { try { OkHttpClient client = new OkHttpClient(); RequestBody formBody = new FormBody.Builder().add("username", "8541").add("password", "111111").add("postkey", "1503d").build(); Request request = new Request.Builder().url(url).post(formBody).build(); Response response = client.newCall(request).execute(); System.out.println("response = " + response.body().string()); } catch (IOException e) { e.printStackTrace(); } } }); } private void post_Asynchronous() { executorService.execute(new Runnable() { @Override public void run() { OkHttpClient client = new OkHttpClient(); RequestBody requestBody=new FormBody.Builder().add("username","8451").add("password","111111").add("postkey","1503d").build(); Request request = new Request.Builder().url(url).post(requestBody).build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { System.out.println("response = " + response.body().string()); } }); } }); } }
Swift
UTF-8
3,025
2.9375
3
[ "MIT" ]
permissive
// // UserDefaultsStore.swift // RYKit // // Created by Marc Steven on 2020/6/1. // Copyright © 2020 Rich and Young. All rights reserved. // import Foundation /// UseDefaults存储类,使用UserDefaults final public class UserDefaultsStore<T:Codable> { /// 存储时候所用的defaults private let storage:UserDefaults /// encoder private lazy var encoder = JSONEncoder() /// decoder private lazy var decoder = JSONDecoder() /// 通知的token private var notificationToken:NSObjectProtocol? /// key private let key:String /// 默认的值 private let defaultValue:T? /// 缓存的值在内存中 private var cachedValueInMemory:T? /// 是否应该缓存到内存中 private let shouldCacheValueInMemory:Bool /// 初始化方法 /// - Parameters: /// - key: 对应的key /// - defaultValue: 默认的值 /// - shouldCacheValueInMemory: 应该缓存到内存中 /// - storage: 对应的defaults public init(key:String, default defaultValue:T? = nil, shouldCacheValueInMemory:Bool = true, storage:UserDefaults = .standard) { self.key = key self.defaultValue = defaultValue self.shouldCacheValueInMemory = shouldCacheValueInMemory self.storage = storage } /// value public var value:T? { get { if let cachedValueInMemory = cachedValueInMemory { return cachedValueInMemory } guard let data = storage.object(forKey: key) as? Data, let value = try? decoder.decode(T.self, from: data) else { return defaultValue } if shouldCacheValueInMemory { cachedValueInMemory = value } return value } set { let data = newValue == nil ? nil : try? encoder.encode(newValue) storage.set(data, forKey: key) if shouldCacheValueInMemory { cachedValueInMemory = newValue } } } /// 安装application内存警告观察者 @available(iOS 11.0, *) private func setupApplicationMemoryWarningObserver() { notificationToken = NotificationCenter.on.applicationDidReceiveMemoryWarning { [weak self] in self?.cachedValueInMemory = nil } } deinit { } } //UserDefaultsStore conform to CustomStringConvertible extension UserDefaultsStore :CustomStringConvertible { public var description: String { guard let value = value as? CustomStringConvertible else { return String(describing: self.value) } return value.description } } //UserDefaults store conform to CustomDebugStringConvertible extension UserDefaultsStore:CustomDebugStringConvertible { public var debugDescription: String { return value.debugDescription } }
Markdown
UTF-8
1,615
2.84375
3
[]
no_license
# Git ## Instalación Para instalar Git tenemos que entrar en [Git](https://git-scm.com/) e instalarlo para nuestro SO. Normalmente en Ubuntu y OSX ya viene instalado de serie. Podemos comprobar si lo tenemos instalado ejecutando: ``` git --version ``` ## Introducción a git ### Ramas Un repositorio de git se divide en ramas. Normalmente, la rama principal se llama master y se sacan ramas a partir de ella para después mergearlas. Mergear una rama es añadir los cambios hechos en una rama a la rama destino. Esto nos permite hacer cambios sin alterar el código de la rama principal. Antes de mergear una rama se suele revisar por los demás integrantes del equipo para asegurar que todo está bien. ## Comandos más utilizados * Clonar un repositorio: ``` git clone https://github.com/user/repo.git ``` * Cambio de rama ``` git checkout nombre_de_rama ``` * Crear una rama nueva ``` git checkout -b nombre_de_rama_nueva ``` * Mirar en que rama estas: ``` git branch ``` * Añadir todos los ficheros a una rama: ``` git add . ``` * Añadir solo ciertos ficheros: ``` git add ruta_al_fichero/fichero.js ruta_al_fichero/fichero2.js ``` * Crear un commit: ``` git commit -m 'nombredelcommit' ``` * Push de los cambios al repositorio online ``` git push origin nombrerama ``` * Pull del repositorio ``` git pull ``` ## .gitignore El archivo .gitignore es un archivo que se encuentra en la raiz de nuestro repositorio y se utiliza para evitar subir ciertos archivos al repositorio (claves, librerías externas, etc...). Acepta expresiones regulares para poder excluir varios ficheros a la vez.
Java
UTF-8
3,065
3.125
3
[]
no_license
package com.nio.again; import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Iterator; public class NIOServer { private int index = 0; private int blockSize = 4096; private ByteBuffer sendBuffer = ByteBuffer.allocate(blockSize); private ByteBuffer receiveBuffer = ByteBuffer.allocate(blockSize); private Selector selector; NIOServer(int port) throws IOException{ ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.configureBlocking(false); ServerSocket serverSocket = serverSocketChannel.socket(); serverSocket.bind(new InetSocketAddress(port)); this.selector = Selector.open(); //服务管道注册到选择器上 serverSocketChannel.register(this.selector, SelectionKey.OP_ACCEPT); System.out.println("Server start ->" + port); } //监听 public void listen() throws Exception{ while(true){ this.selector.select(); Iterator<?> iterator = this.selector.selectedKeys().iterator(); while(iterator.hasNext()){ SelectionKey key = (SelectionKey) iterator.next(); //每次操作完之后删除,防止重复操作此key iterator.remove(); //业务逻辑 handleKey(key); } } } private void handleKey(SelectionKey key) throws IOException, Exception { ServerSocketChannel server = null; SocketChannel client = null; String receiveText; String sendText; int count = 0; if(key.isAcceptable()){ server = (ServerSocketChannel) key.channel(); client = server.accept(); client.configureBlocking(false); //可以给客户端发送消息 System.out.println("有连接进来了"); client.register(this.selector, SelectionKey.OP_READ); }else if(key.isReadable()){ client = (SocketChannel) key.channel(); count = client.read(receiveBuffer); if(count > 0){ receiveText = new String(receiveBuffer.array(),0,count); System.out.println("服务端接收到客户端的信息:"+receiveText); client.register(this.selector, SelectionKey.OP_WRITE); }else{ System.out.println("服务端接收到客户端的连接,但是没有信息"); } }else if(key.isWritable()){ try { Thread.sleep(3000); sendBuffer.clear(); client = (SocketChannel) key.channel(); sendText = "msg send to client"+index++ +"\r\n"; sendBuffer.put(sendText.getBytes()); sendBuffer.flip(); client.write(sendBuffer); System.out.println("客户端已经给服务端发送数据给客户端了" + index); } catch (Exception e) { e.printStackTrace(); key.cancel(); } } } public static void main(String[] args) throws Exception { int port = 7080; NIOServer nioServer = new NIOServer(port); nioServer.listen(); } }
Java
UTF-8
3,101
2.265625
2
[]
no_license
package com.bradley.gwt.user.client.ui; import com.bradley.gwt.user.client.resource.DialogClientBundle; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.user.client.Element; import com.google.gwt.user.client.ui.HasOneWidget; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.Widget; /** * Wrapper for a jquery dialog. */ public class Dialog implements HasOneWidget { protected Widget widget; protected boolean modal = false; protected String title; public Dialog(String title, boolean modal) { this(title, modal, (DialogClientBundle) GWT.create(DialogClientBundle.class)); } public Dialog(String title) { this(title, false); } public Dialog(String title, boolean modal, DialogClientBundle resources) { this.title = title; this.modal = modal; resources.getStyle().ensureInjected(); Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { setMinHeight(400); setMinWidth(600); } }); } @Override public void setWidget(IsWidget w) { setWidget(w.asWidget()); } @Override public Widget getWidget() { return widget; } @Override public void setWidget(Widget w) { this.widget = w; RootPanel.get().add(w); dialog(w.getElement(), title, modal); } /** * Show the dialog. */ public void show() { if (widget == null) { throw new IllegalArgumentException("Widget has not been initialized yet."); } callDialogMethod(widget.getElement(), "open"); } /** * Hide the dialog. */ public void hide() { if (widget == null) { throw new IllegalArgumentException("Widget has not been initialized yet."); } callDialogMethod(widget.getElement(), "close"); } /** * Set the minimum width of the Dialog window. The widget will not be able to resized * smaller than this width. * * @param pixelWidth The smallest width in pixels. */ public void setMinWidth(int pixelWidth) { setMinWidth(widget.getElement(), pixelWidth); } public void setMinHeight(int pixelHeight) { setMinHeight(widget.getElement(), pixelHeight); } public void setWidth(int pixelWidth) { setWidth(widget.getElement(), pixelWidth); } protected static native void setWidth(Element el, int pixelWidth)/*-{ $wnd.$(el).dialog("option", "width", pixelWidth); }-*/; protected static native void setMinHeight(Element el, int pixelHeight)/*-{ $wnd.$(el).dialog("option", "minHeight", pixelHeight); }-*/; protected static native void setMinWidth(Element el, int pixelWidth)/*-{ $wnd.$(el).dialog("option", "minWidth", pixelWidth); }-*/; protected static native void callDialogMethod(Element el, String method)/*-{ $wnd.$(el).dialog(method); }-*/; protected static native void dialog(Element el, String title, boolean modal)/*-{ $wnd.$(el).dialog({ autoOpen: false, modal: modal, title: title, resizable: false, zIndex: 2600 }); }-*/; }
Java
UTF-8
2,431
2.078125
2
[]
no_license
package com.yn.yntp.module.equipment.entity; import javax.persistence.Entity; import javax.persistence.Table; import com.yn.yntp.common.entity.BaseImageLibraryEntity; /** * * @Title: EquipmentEntity.java * @Package com.yn.yntp.module.equipment.entity * @Description: TODO(用一句话描述该文件做什么) * * @author liucc * @date 2015年1月19日 下午1:59:56 * @version V1.0 */ @Entity @Table(name = "biz_equipment") public class EquipmentEntity extends BaseImageLibraryEntity<Long> { private String name; // 类型 private Long type_id; private Double price; private String tel; private String address; // 状态,可租;正在出租中 private Integer status; private String equipment_abstract; private String equipment_description; // 租赁指南 private String equipment_buynotes; private Long business_id; public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Long getType_id() { return this.type_id; } public void setType_id(Long type_id) { this.type_id = type_id; } public Double getPrice() { return this.price; } public void setPrice(Double price) { this.price = price; } public String getTel() { return this.tel; } public void setTel(String tel) { this.tel = tel; } public String getAddress() { return this.address; } public void setAddress(String address) { this.address = address; } public Integer getStatus() { return this.status; } public void setStatus(Integer status) { this.status = status; } public String getEquipment_abstract() { return this.equipment_abstract; } public void setEquipment_abstract(String equipment_abstract) { this.equipment_abstract = equipment_abstract; } public String getEquipment_description() { return this.equipment_description; } public void setEquipment_description(String equipment_description) { this.equipment_description = equipment_description; } public String getEquipment_buynotes() { return this.equipment_buynotes; } public void setEquipment_buynotes(String equipment_buynotes) { this.equipment_buynotes = equipment_buynotes; } public Long getBusiness_id() { return this.business_id; } public void setBusiness_id(Long business_id) { this.business_id = business_id; } }
Python
UTF-8
1,283
3.03125
3
[]
no_license
import sys if __name__ == '__main__': file = sys.argv[1] memory = [0 for i in range(30000)] with open(file) as f: pointer = 0 index = 0 begin_index = None end_index = None code = f.read().replace('\n', '') while index < len(code): if code[index] == '>': pointer += 1 index += 1 elif code[index] == '<': pointer -= 1 index += 1 elif code[index] == '+': memory[pointer] += 1 index += 1 elif code[index] == '-': memory[pointer] -= 1 index += 1 elif code[index] == '.': print(chr(memory[pointer]), end='') index += 1 elif code[index] == '': memory[pointer] = input() index += 1 elif code[index] == '[': if memory[pointer] > 0: begin_index = index index += 1 else: index = end_index + 1 elif code[index] == ']' and begin_index: end_index = index index = begin_index else: index += 1
JavaScript
UTF-8
2,019
2.671875
3
[ "MIT" ]
permissive
const mocha = require('mocha'); const should = require('should'); const fs = require('fs'); const selectProp = require('../lib/'); describe('Selects a property from various objects', () => { it('Selects a prop', () => { const obj = { a: { b: { c: 'd' } } }; const selected = selectProp(obj, 'a.b.c'); selected.should.deepEqual('d'); }); it('Selects a prop from a random object with an array', () => { const obj = { a: { b: [{ c: 'd' }] } }; const selected = selectProp(obj, 'a.b.c'); selected.should.deepEqual(['d']); }); it('Selects a prop from a Reddit Listing', () => { const subreddit = require('./data/subreddit.json'); const titles = require('./data/subredditTitles.json'); const selected = selectProp(subreddit, 'data.children.data.title'); selected.should.deepEqual(titles); }); it('Selects the perf keys from lichess tournament data', () => { const tournaments = require('./data/lichess.json'); const selected = selectProp(tournaments, 'created.perf.key'); const unique = removeDuplicates(selected); const sorted = unique.sort((a, b) => a < b ? -1 : 1); const variants = [ 'antichess', 'atomic', 'blitz', 'bullet', 'chess960', 'crazyhouse', 'horde', 'kingOfTheHill', 'racingKings', 'rapid', 'threeCheck', 'ultraBullet' ]; sorted.should.deepEqual(variants); }) }) /// A function which removes duplicates from an array using a hash table function removeDuplicates(array) { const seen = {}; return array.filter((item) => { if (seen.hasOwnProperty(item)) return false; return seen[item] = true; }); }
PHP
UTF-8
2,562
2.640625
3
[]
no_license
<?php session_start(); $host = "localhost"; $username = "root"; $user_pass = ""; $database_in_use = "isp"; $mysqli = new mysqli($host, $username, $user_pass, $database_in_use); if(isset($_POST['login'])){ $username = $_POST['username']; $userpass = $_POST['password']; if(empty($username) or empty($userpass)){ print_r("Enter your information below"); } else{ $sql = "SELECT * FROM users WHERE username = '$username' AND userpass = '$userpass'"; $result = $mysqli->query($sql); if($result->num_rows > 0){ $_SESSION['username'] = $username; $_SESSION['success'] = "You are now logged in"; header('location: index.php'); } else{ print_r("No profiles match this information, please try again or create a new profile"); } } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="style.css"> <style> body { background: #2b5876; /* fallback for old browsers */ background: -webkit-linear-gradient(to right, #2b5876, #4e5376); /* For Chrome 10-25, Safari 5.1-6 */ background: linear-gradient(to right, #2b5876, #4e5376); } #form { width: 30%; margin: 25px auto; } </style> </head> <body> <div class="container"> <div class="row"> <div id="form"> <h1 style="text-align: center;">Login</h1> <form action="login.php" method="POST"> <div class="form-group"> <label>Username</label> <input class="form-control"type="text" name="username" placeholder="Username"> </div> <div class="form-group"> <label>Password</label> <input class="form-control"type="password" name="password" placeholder="Password"> </div> <div class="form-group"> <button name="login" class="btn btn-lg btn-default btn-block btn-primary" type="submit">Sign in</button> </div> </form> <a href="prj.html">Go Back</a> <p> Don't have a account? <a href="register.php"><button class="btn btn-sm btn-default btn-danger">Sign Up!</button></a> </p> </div> </div> </div> </body> </html>
Java
UTF-8
1,404
1.632813
2
[]
no_license
package co.moviired.register.properties; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import java.io.Serializable; @Data @ConfigurationProperties(prefix = "providers.mahindra") public final class MahindraProperties implements Serializable { // Service web private String url; private int connectionTimeout; private String specialCharacters; private int readTimeout; // REGISTRAR USUARIO private String userQueryInfoType; private String userQueryInfoProvider; private String type; private String provider; private String payid; private String npref; private String language1; private String ispincheckreq; private String doc1Name; // Change Password private String newPasswordType; private String newPasswordLanguage1; // Login private String loginType; private String loginSource; private String loginProvider; private String loginLanguage1; private String loginOtpReq; private String loginIsPinCheckReq; // Cash In private String rciReqType; private String rciReqMsisdn; private String rciReqPin; private String rciReqSndProvider; private String rciReqRcvProvider; private String rciReqSndInstrument; private String rciReqRcvInstrument; private String rciReqLanguage1; private String rciReqLanguage2; }
C++
UTF-8
1,081
2.5625
3
[ "MIT" ]
permissive
#pragma once #include "iPlayer.h" class cPlayer : public iPlayer { public: cPlayer(iUser* user, char playerID); virtual ~cPlayer(); virtual iUser* User(); virtual char PlayerID(); virtual bool IsReadyToPlay(); virtual bool IsBankrupty(); virtual bool CanBuy(int price); virtual int GetMoneyVariation(); virtual bool Deposit(int money); virtual bool Withdraw(int money); virtual void CurrentLocation(int location); virtual int CurrentLocation(); virtual bool UseChanceToThrowDice(); virtual void TakeChanceToThrowDice(); virtual int getEnjailCount(); virtual void SetEnjailCount(int numOfTurns); virtual bool getbCanThrowDice(); virtual void setbCanThrowDice(bool bChance); bool getbJustCameInJail(); void setbJustCameInJail(bool bFirstTime); virtual void GetPlayerInfo(sProtocolPlayerInfo& outInfo, int currentPlayerID); private: char m_playerID; int m_money; int m_previousMoney; int m_enjailedCount; int m_currentLocation; iUser* m_user; bool m_isReady; bool m_chanceToThrowDice; bool m_CanThrowDice; bool m_bJustCameInJail; };
C#
UTF-8
1,809
3.265625
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace b { class Program { static void Main(string[] args) { string[] str = Console.ReadLine().Split(' '); int n = int.Parse(str[0]); int q = int.Parse(str[1]); int[] uni = new int[n]; for (int i = 0; i < uni.Length; i++) { uni[i] = -1; } for (int i = 0; i < q; i++) { string[] que = Console.ReadLine().Split(' '); int x = int.Parse(que[0]) - 1; int y = int.Parse(que[1]) - 1; Connect(x, y, uni); } SortedSet<int> set = new SortedSet<int>(); for (int i = 0; i < n; i++) { set.Add(Root(i, uni)); } Console.WriteLine(set.Count - 1); } static int Root(int a, int[] uni) { if (uni[a] < 0) { return a; } else { return uni[a] = Root(uni[a], uni); } } static void Connect(int a, int b, int[] uni) { int ra = Root(a, uni); int rb = Root(b, uni); if (ra == rb) { return; } if (uni[ra] > uni[rb]) { uni[ra] = rb; } else { if (uni[ra] == uni[rb]) { uni[ra] -= 1; } uni[rb] = ra; } } static bool IsConnect(int a, int b, int[] uni) { return Root(a, uni) == Root(b, uni); } } }
Python
UTF-8
4,506
2.546875
3
[]
no_license
import facebook import operator from collections import Counter import time import datetime from operator import itemgetter import requests #activity fun ==================================================================================================== def fbdata(tok): graph = facebook.GraphAPI(access_token=tok, version='2.7') post = graph.get_connections(id='me', connection_name='posts',limit=500) d = post['data'] li =[] for i in d: li.append(i['id']) new = [] lin=0 stat=0 album=0 for i in li: ty = graph.get_object(id=i, fields='type') new.append(ty) if(ty['type']=='link'): lin=lin+1 if(ty['type']=='photo'): album=album+1 if(ty['type']=='status'): stat=stat+1 dic = [{'label':'status updates','value':stat}, {'label':'photo uploads','value':album}, {'label':'links shared','value':lin}, ] return dic #top frnds============================================================================================================ def topfrnd(tok): graph = facebook.GraphAPI(access_token=tok, version='2.7') post = graph.get_connections(id='me', connection_name='posts',limit=500) d = post['data'] li =[] for i in d: li.append(i['id']) new = [] for i in li: like = graph.get_connections(id=i, connection_name='likes',limit=500) new.append(like['data']) na = [] l=len(new) for i in range(0,l): for k in new[i]: na.append(k['name']) c = Counter(na) sor = sorted(c.items(), key=operator.itemgetter(1),reverse=True) zz= len(sor) if(zz>=5): zz=5 toplike = sor[0:zz] fr = [] for r in range(0,zz): for i in range(0,l): for k in new[i]: if(k['name']==toplike[r][0] and k['id'] not in fr): fr.append(k['id']) break sol= [] for z in range(0,zz): sol.append({'name':toplike[z][0],'id':fr[z], 'likes':toplike[z][1]}) tl = len(d) maxx=0 for i in range(0,l): if(len(new[i]) > maxx): maxx = len(new[i]) su=0 for i in range(0,l): su = su+len(new[i]) print("Data fetched :P") di = [{'value':tl,'label':'total activities'}, {'value':maxx,'label':'max likes on a post'}, {'value':su,'label':'total no of likes'} ] return sol,di #activity timeline =================================================================================================== def activity(tok): graph = facebook.GraphAPI(access_token=tok, version='2.7') post = graph.get_connections(id='me', connection_name='posts',limit=500) d = post['data'] li =[] for i in d: li.append(i['id']) new = [] tym = [] for i in li: t = graph.get_connections(id=i, connection_name='', date_format='U' , limit=500) tym.append(t['created_time']) mon = [] yr = [] ti =[] dti = [] for i in tym: t=time.strftime("%D %H:%M", time.localtime(int(i))) mon.append(t[0:2]+ t[5:8]) yr.append(t[6:8]) ti.append(t[9:11]) dti.append(t[0:8]) dayy = [] for dt in dti: month, day, year = (int(x) for x in dt.split('/')) ans = datetime.date(year, month, day) dayy.append(ans.strftime("%A")) print("Data fetched :P") yy = Counter(yr) tt = Counter(ti) mm = Counter(mon) dd = Counter(dayy) yyy=[] ttt=[] mmm=[] ddd=[] for i in yy.items(): yyy.append({'label': i[0], 'value': i[1]}) yyy= sorted(yyy, key=itemgetter('label'), reverse=False) for i in tt.items(): ttt.append({'label': i[0], 'value': i[1]}) ttt= sorted(ttt, key=itemgetter('label'), reverse=False) for i in mm.items(): mmm.append({'label': i[0], 'value': i[1]}) mmm= sorted(mmm, key=itemgetter('label'), reverse=False) for i in dd.items(): ddd.append({'label': i[0], 'value': i[1]}) ddd= sorted(ddd, key=itemgetter('label'), reverse=False) return (yyy, ttt ,mmm,ddd) def photo(tok,luv): ur = [] idd = [] for i in luv: idd.append(i['id']) for link in idd: url= 'https://graph.facebook.com/'+link+'?fields=picture&access_token=' + tok r= requests.get(url) re = r.json() ll = re['picture']['data']['url'] ur.append(ll) return ur
PHP
UTF-8
216
2.59375
3
[]
no_license
<?php error_reporting(0); //flag{1919810} if(md5($flag) === "25437c054698767f203c40ef1e058ea5"){ //爆破flag哦 echo "this is the true flag"; } else{ echo("You found me, but can you get the flag ???"); } ?>
Java
UTF-8
7,466
2.359375
2
[]
no_license
package com.example.cansis20; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * A simple {@link Fragment} subclass. * Use the {@link MarksDisplayFragment#newInstance} factory method to * create an instance of this fragment. */ public class MarksDisplayFragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private TextView semText; private List<String> subjectName = new ArrayList<>(); private List<Integer> maxMarks=new ArrayList<>(); private List<Integer> totalMarks=new ArrayList<>(); private List<String> grade = new ArrayList<>(); private RecyclerView recyclerView; private MarksAdapter marksAdapter; private ProgressDialog progressDialog; public MarksDisplayFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment MarksDisplayFragment. */ // TODO: Rename and change types and number of parameters public static MarksDisplayFragment newInstance(String param1, String param2) { MarksDisplayFragment fragment = new MarksDisplayFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } private void loadMarks() { progressDialog = new ProgressDialog(getContext()); progressDialog.setMessage("Loading Data..."); progressDialog.show(); final String sem = getArguments().getString("selectedSem"); final String cie = String.valueOf(getArguments().getInt("selectedCie")); StringRequest stringRequest = new StringRequest( Request.Method.POST, Constants.URL_MARKS, new Response.Listener<String>() { @Override public void onResponse(String response) { try { //converting the string to json array object JSONArray array = new JSONArray(response); if(array.length()<1){ progressDialog.dismiss(); Toast.makeText(getContext(),"Data Unavailable..",Toast.LENGTH_SHORT).show(); getFragmentManager().popBackStack(); } //traversing through all the object for (int i = 0; i < array.length(); i++) { //getting product object from json array JSONObject mark = array.getJSONObject(i); //adding the notification to notification list subjectName.add(mark.getString("subject_name")); if(cie.equals("5")){ grade.add(String.valueOf(mark.getInt("max_marks"))); }else { maxMarks.add(mark.getInt("max_marks")); } totalMarks.add(mark.getInt("total_marks")); } progressDialog.dismiss(); //creating adapter object and setting it to recyclerview if(cie.equals("5")) { marksAdapter = new MarksAdapter(getContext(), subjectName, grade, totalMarks,1); }else{ marksAdapter = new MarksAdapter(getContext(), subjectName, maxMarks, totalMarks); } GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 1, GridLayoutManager.VERTICAL, false); recyclerView.setLayoutManager(gridLayoutManager); recyclerView.setAdapter(marksAdapter); } catch (Exception e) { progressDialog.dismiss(); Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_LONG).show(); e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //progressDialog.dismiss(); Toast.makeText(getContext(), error.getMessage() + "Volley error", Toast.LENGTH_SHORT).show(); } } ) { @Override protected Map<String, String> getParams() throws AuthFailureError { //Toast.makeText(getApplicationContext(),"out",Toast.LENGTH_SHORT).show(); Map<String, String> params = new HashMap<>(); params.put("sem", sem); params.put("cie", cie); params.put("stud_id",SharedPrefManager.getInstance(getContext()).getStudentId()); return params; } }; RequestHandler.getInstance(getContext()).addToRequestQueue(stringRequest); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_marks_display, container, false); semText = view.findViewById(R.id.semCieText); int semNumber = getArguments().getInt("selectedCie"); String text = "| CIE-"+String.valueOf(semNumber)+" |"; if(semNumber == 4) { text = "| CIE-AVERAGE |"; } if(semNumber == 5){ text = "| SEE | "; } semText.setText(text); recyclerView = view.findViewById(R.id.marks_recyclerview); loadMarks(); return view; } }
Java
UTF-8
491
3.28125
3
[]
no_license
static boolean isAnagram(String a, String b) { a=a.toLowerCase(); b=b.toLowerCase(); int stringA = a.length(); int stringB = b.length(); if ( stringA != stringB ) {return false;} else { char[] s1array=a.toCharArray(); char[] s2array=b.toCharArray(); Arrays.sort(s1array); Arrays.sort(s2array); if (Arrays.equals(s1array,s2array)) {return false;} else return true;} }
Java
UTF-8
5,778
2.359375
2
[]
no_license
package kkellum.quizapp; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private TextView mTextView; private EditText mEditText; private LinearLayout mTrueFalseContainer; private LinearLayout mFillTheBlankContainer; private Button mTrueButton; private Button mFalseButton; private Button mNextButton; private Button mPrevious; private Button mCheckButton; private Button mCheatButton; private Question[] mQuestions; private int mIndex; private int mscore; private boolean mCheated = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTrueButton = (Button) findViewById(R.id.true_button); mFalseButton = (Button) findViewById(R.id.False_button); mNextButton = (Button) findViewById(R.id.next_button); mPrevious = (Button) findViewById(R.id.previous_button); mCheckButton =( Button) findViewById(R.id.check_button); mCheatButton = (Button) findViewById(R.id.cheat_button); mTrueFalseContainer = (LinearLayout) findViewById(R.id.true_false_container); mFillTheBlankContainer = (LinearLayout) findViewById(R.id.fill_the_blank_container); mEditText = (EditText) findViewById(R.id.edit_text); mTrueButton.setOnClickListener(this); mFalseButton.setOnClickListener(this); mNextButton.setOnClickListener(this); mPrevious.setOnClickListener(this); mCheckButton.setOnClickListener(this); mCheatButton.setOnClickListener(this); mTextView = (TextView) findViewById(R.id.text_view); // Initialize an array of questions. mQuestions = new Question[5]; mIndex = 0; // Initialize each slot in the array. mQuestions[0] = new TrueFalseQuestion(R.string.question_1,0, true); mQuestions[1] = new TrueFalseQuestion(R.string.question_2, 0, false); mQuestions[2] = new TrueFalseQuestion(R.string.question_3, 0, true); mQuestions[3] = new TrueFalseQuestion(R.string.question_4, 0, false); mQuestions[4] = new TrueFalseQuestion(R.string.question_5, 0, false); String[] q5Answers = getResources().getStringArray(R.array.question_6_answers); mQuestions[5] = new FillTheBlankQuestion(R.string.question_6, R.string.quesiton_6_hint, q5Answers); //setup the first question. setupQuestion(); } @Override public void onClick(View view) { if (view.getId() == R.id.true_button) { checkAnswer(true); } else if (view.getId() == R.id.False_button) { checkAnswer(false); } else if (view.getId() == R.id.check_button) { checkAnswer(mEditText.getText().toString()); } else if (view.getId() == R.id.next_button) { // change to the next question... //Increment the index by one. mIndex++; //do if statement here: // if the mIdex is greater than or equal to mQuestions.length // -set mIndex to 0 // - end the quiz //change text in view. mTextView.setText(mQuestions[mIndex].getTextResId()); } else if(view.getId() == R.id.previous_button) { //change to the previous question... //reduction the index by one mIndex--; //do if statement here: // -set mIndex to 0 //-after every question //change in text in view. setupQuestion(); } else if (view.getId() == R.id.cheat_button) { // TODO: Launch CheatActivity Intent cheatIntent = CheatActivity.newIntent(this); startActivity(cheatIntent); } } public void setupQuestion() { mTextView.setText(mQuestions[mIndex].getTextResId()); if (mQuestions[mIndex].isTrueFalseQuestion()) { mTrueFalseContainer.setVisibility(View.VISIBLE); mFillTheBlankContainer .setVisibility(View.GONE); } else if (mQuestions[mIndex].isFillTheBlankQuestion()) { mTrueFalseContainer.setVisibility(View.GONE); mFillTheBlankContainer .setVisibility(View.VISIBLE); } else if (mQuestions[mIndex].isMultipleChoiceQuestion()) { //TODO: hide and show relevance containers } } public boolean checkAnswer(boolean userInput) { if(mQuestions[mIndex].checkAnswer(userInput)) { Toast myToast = Toast.makeText(this, "you are correct", Toast.LENGTH_SHORT); myToast.show(); return true; } else { Toast myToast = Toast.makeText(this, "you are incorrect", Toast.LENGTH_SHORT); myToast.show(); return false; } } public boolean checkAnswer(String userInput) { if(mQuestions[mIndex].checkAnswer(userInput)) { Toast myToast = Toast.makeText(this, "you are correct", Toast.LENGTH_SHORT); myToast.show(); return true; } else { Toast myToast = Toast.makeText(this, "you are incorrect", Toast.LENGTH_SHORT); myToast.show(); return false; } } }
Java
UTF-8
1,380
3.0625
3
[]
no_license
package com.example.differential_equation_grapher.function; public class SquareRoot extends PredefinedFunction{ public static final String NAME = "sqrt"; private static final RealNumber powerValue = new RealNumber(0.5); public SquareRoot(Expression expression) { super(new ArgumentSingle(expression)); } public SquareRoot(Arguments arguments) { super(arguments); } @Override public String getName() { return NAME; } @Override public Expression specialSimplification() { /////todo: check for power to even return this; } @Override public String toDisplayString() { return "\u221A" + "(" + getFirstArg().toDisplayString() + ")"; } @Override public Expression getDerivative(Variable v) { return new Divide(getFirstArg().getDerivative(v),new Product(new RealNumber(2),this.copy())); } @Override public boolean argumentsAreCompatable(Arguments arguments) { return arguments.getNumberOfArguments()==1; } @Override public Operation getSubclassInstance(Arguments newArguments) { return new SquareRoot(newArguments); } @Override public Constant evaluate(Substitution substitution) { return ConstantMediator.power(getFirstArg().evaluate(substitution),powerValue); } }
Markdown
UTF-8
5,044
2.5625
3
[ "MIT" ]
permissive
# Portfolio for developers ** forked from @smakosh [![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/import/settings?s=https%3A%2F%2Fgithub.com%2FRajesh-Royal%2Fgatsby-developer-portfolio&c=1&env=GATSBY_PORTFOLIO_GITHUB_TOKEN%2CGATSBY_PORTFOLIO_FORMIK_ENDPOINT%2CGATSBY_PORTFOLIO_RECAPTCHA_KEY&envDescription=Required%20to%20fetch%20your%20repositories%20from%20GitHub&envLink=https://github.com/smakosh/gatsby-portfolio-dev&framework=nextjs) ## Theme [Gatsby-theme-portfolio](https://github.com/smakosh/gatsby-theme-portfolio) ## Features - Eslint/Prettier configured - Scores 100% on a11y / Performance / PWA / SEO - PWA (desktop & mobile) - Easy to customize - Nice project structure - Amazing illustrations by [Undraw.co](https://undraw.co) - Tablet & mobile friendly - Continuous deployment with [Vercel](https://vercel.com/?utm_source=smakosh) - Or with Netlify, check [Netlify branch](https://github.com/smakosh/gatsby-portfolio-dev/tree/netlify) - A contact form protected by Google Recaptcha - Can be deployed with one click - Functional components with ~~Recompose~~ React Hooks! ~~ready to migrate to React hooks!~~ - Fetches your Github pinned projects with most stars (You could customize this if you wish) - One click deployment to Vercel ## Design Project on [Behance](https://www.behance.net/gallery/74172961/Free-Gatsby-portfolio-for-developers) ## Structure ```bash . ├── data │ └── config # SEO related tags ├── src │ └── assets # Assets │ │ │── icons # icons │ │ │── illustrations # illustrations from (undraw.co) │ │ └── thumbnail # cover of your website when it's shared to social media │ ├── components # Components │ │ │── common # Common components │ │ │── landing # Components used on the landing page │ │ └── theme # Header & Footer │ └── pages # Pages └── static # favicon & Netlify redirects ``` ## Prerequisites ### Online 1. Create an account at [Formik](https://formik.com/?utm_source=smakosh) and grab your form endpoint url 2. Grab a Google recaptcha key from [Google Recaptcha](https://www.google.com/recaptcha/admin) 3. Grab your Github token from [GitHub](https://github.com/settings/tokens/new?scopes=repo&description=portfolio-dev) 4. Click [![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/import/settings?s=https%3A%2F%2Fgithub.com%2Fsmakosh%2Fgatsby-portfolio-dev&c=1&env=GATSBY_PORTFOLIO_GITHUB_TOKEN%2CGATSBY_PORTFOLIO_FORMIK_ENDPOINT%2CGATSBY_PORTFOLIO_RECAPTCHA_KEY&envDescription=Required%20to%20fetch%20your%20repositories%20from%20GitHub&envLink=https://github.com/smakosh/gatsby-portfolio-dev&framework=nextjs) and pass in your: - Formik form endpoint - Google recaptcha public key - Github token To Env variables section. ### Locally 1. Create an account at [Formik](https://formik.com/?utm_source=smakosh) 2. Install [Yarn](https://yarnpkg.com/en/) 3. Grab a Google recaptcha key from [Google Recaptcha](https://www.google.com/recaptcha/admin) 4. Grab your Github token from GitHub 5. Run `cp .env.development.template .env.development` 6. Run `yarn && yarn start` > You could run `vercel env pull` to get your env variables from Vercel. ### Deploying locally to Vercel I highly recommend that you push to GitHub/GitLab and deploy your repository to Vercel instead or just hit the Deploy button. ### Clean the cache This removes the `.cache/` & `public/` folders ```bash yarn reset ``` ## Built with - Adobe XD - Gatsby - React & GraphQL - Formik - Google recaptcha - VSCode - And these useful of JavaScript libraries & Gatsby plugins [package.json](package.json) ## License This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for more details ## Contributors - [Ajay NS](https://github.com/ajayns) https://github.com/smakosh/gatsby-portfolio-dev/pull/3 - [Ryan Lee](https://github.com/drdgvhbh) https://github.com/smakosh/gatsby-portfolio-dev/pull/6 - [David](https://github.com/davidavz) https://github.com/smakosh/gatsby-portfolio-dev/pull/8 - [Léu Almeida](https://github.com/LeuAlmeida) https://github.com/smakosh/gatsby-portfolio-dev/pull/21 - [Kudakwashe Mupeni](https://github.com/2wce) https://github.com/smakosh/gatsby-portfolio-dev/pull/20 - [sasannnn](https://github.com/sasannnn) https://github.com/smakosh/gatsby-portfolio-dev/pull/22 - [Michael Seifarth](https://github.com/Kageetai) https://github.com/smakosh/gatsby-portfolio-dev/pull/27 - [Hugo](https://github.com/Kronicom) https://github.com/smakosh/gatsby-portfolio-dev/pull/34 https://github.com/smakosh/gatsby-portfolio-dev/pull/35 - [manula thejan](https://github.com/manula2004) https://github.com/smakosh/gatsby-portfolio-dev/pull/38 - [Smakosh](https://smakosh.com) ## Support If you love this Gatsby template and want to support me, you can do so through my GitHub profile.
Python
UTF-8
228
2.8125
3
[]
no_license
from sys import stdin def main(): linea = stdin.readline().strip().split() while(linea): print((int(linea[0])*int(linea[1]))-1) linea = stdin.readline().strip().split() main()
Java
UTF-8
6,891
2.03125
2
[]
no_license
package com.moe.x4jdm.model; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import java.io.IOException; import com.alibaba.fastjson.JSONObject; import org.jsoup.select.Elements; import com.alibaba.fastjson.JSONArray; import java.util.Iterator; import org.jsoup.nodes.Element; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.util.Map; import java.util.LinkedHashMap; import java.net.URLEncoder; import java.io.UnsupportedEncodingException; import android.net.Uri; public class Indextldm extends Index { private static final String host="http://www.tldm.net/"; @Override public void clearCache() { } @Override public String getIndex(int page) { JSONArray index=new JSONArray(); try { Document doc= Jsoup.connect(host).get(); Elements tabs=doc.select("#naviin li"); if(tabs!=null){ JSONArray tab=new JSONArray(); tabs.remove(0); Iterator<Element> tabs_i=tabs.iterator(); while(tabs_i.hasNext()){ Element e=tabs_i.next().child(0); String href=e.absUrl("href"); if(!e.attr("href").startsWith("http")){ JSONObject tab_item=new JSONObject(); tab_item.put("href",href+"index%d.html"); tab_item.put("title",e.text()); tab.add(tab_item); } } index.add(tab); } Elements mains=doc.select(".page_content > .box720,.page_content > .home-top-new > dl.nobg"); if(mains!=null){ mains.remove(0); //JSONArray main=new JSONArray(); //index.put("main",main); for(Element e:mains){ JSONObject jo=new JSONObject(); index.add(jo); try{jo.put("title",e.selectFirst("em.dhp,em.topdhp").text());}catch(Exception ee){} //JSONArray items=new JSONArray(); //jo.put("item",items); Iterator<Element> main_i=e.select("ul > li > a,dl.fix > dd > a,dl.nobg > dd > a").iterator(); while(main_i.hasNext()){ Element a=main_i.next(); JSONObject item=new JSONObject(); item.put("href",a.absUrl("href")); try{ item.put("title",a.selectFirst("span").text()); }catch(NullPointerException ee){ item.put("title",a.ownText()); } try{item.put("desc",a.selectFirst("em").text());}catch(NullPointerException ee){ item.put("desc",a.parent().ownText()); } try{ item.put("src",a.selectFirst("img").absUrl("src")); item.put("title",a.selectFirst("img").attr("alt")); }catch(Exception ee){} index.add(item); } } } } catch (IOException e) {} return index.toJSONString(); } @Override public String getTime() { // TODO: Implement this method return null; } @Override public boolean hasTime() { return false; } @Override public String getList(String url) { if(url.endsWith("index1.html")) url=url.substring(0,url.length()-11); try { int index=url.indexOf("searchword="); if(index!=-1) { url =url.substring(0,index+11)+ URLEncoder.encode(url.substring(index+11), "GBK"); } } catch (UnsupportedEncodingException e) {} JSONObject list=new JSONObject(); try { Document doc=Jsoup.connect(url).ignoreContentType(true).postDataCharset("GBK").timeout(15000).get(); list.put("title",doc.selectFirst("#broodtitle").text()); String f=doc.selectFirst(".pages > span > span").text(); String[] page=f.substring(f.indexOf(":")+1,f.length()-1).split("/"); list.put("page",Integer.parseInt(page[0])); list.put("count",Integer.parseInt(page[1])); Elements lis=doc.select(".movie-chrList > ul > li"); if(lis!=null){ JSONArray items=new JSONArray(); Iterator<Element> lis_i=lis.iterator(); while(lis_i.hasNext()){ Element e=lis_i.next(); JSONObject item=new JSONObject(); item.put("href",e.selectFirst("a").absUrl("href")); item.put("src",e.selectFirst("img").absUrl("src")); item.put("title",e.selectFirst("img").attr("alt")); item.put("desc",e.selectFirst("abbr").text()); items.add(item); } list.put("item",items); } } catch (IOException e) {} return list.toJSONString(); } @Override public String getPost(String url) { JSONObject post=new JSONObject(); try { Document doc=Jsoup.connect(url).get(); post.put("title",doc.selectFirst(".mtext h1").text()); post.put("desc",doc.selectFirst(".mtext em").text()); post.put("profile",doc.selectFirst("div.m-intro").toString()); post.put("src",doc.selectFirst(".mimg > img").absUrl("src")); Elements play=doc.select(".playurl > .bfdz"); if(play!=null){ JSONArray video=new JSONArray(); Iterator<Element> play_i=play.iterator(); while(play_i.hasNext()){ Elements as=play_i.next().select("li > a"); if(as!=null){ JSONArray plays=new JSONArray(); Iterator<Element> as_i=as.iterator(); while(as_i.hasNext()){ JSONObject play_item=new JSONObject(); Element a=as_i.next(); play_item.put("title",a.text()); play_item.put("href",makeUrl(a.attr("href"))); plays.add(play_item); } video.add(plays); } } post.put("video",video); } } catch (IOException e) {} return post.toJSONString(); } @Override public Map<String,String> getVideoUrl(String url) { Map<String,String> urls=new LinkedHashMap<>(); try { String[] target=url.substring(url.lastIndexOf("?")+1).split("-"); Document doc=Jsoup.connect(url).get(); String href=doc.selectFirst("script[src^=/playdata]").absUrl("src"); String data=Jsoup.connect(href).ignoreContentType(true).execute().body(); JSONArray arr=JSONArray.parseArray(data.substring(data.indexOf("[["),data.lastIndexOf("]]")+2)).getJSONArray(Integer.parseInt(target[1])); JSONArray videos=arr.getJSONArray(1); String video_url=videos.getString(Integer.parseInt(target[2])); video_url=video_url.substring(video_url.indexOf("$")+1,video_url.lastIndexOf("$")); data=Jsoup.connect(video_url).ignoreContentType(true).execute().body(); Matcher matcher=Pattern.compile("url:\\s'(.*?)',",Pattern.MULTILINE).matcher(data); if(matcher.find()){ urls.put(matcher.group(1),matcher.group(1)); }else{ matcher=Pattern.compile("var\\shuiid\\s=\\s\\\"(.*?)\\\";",Pattern.MULTILINE).matcher(data); if(matcher.find()){ urls.put(matcher.group(1),matcher.group(1)); } } } catch (Exception e) {} return urls; } @Override public String search(String key) { return getHost() + "search.asp?page=%d&searchtype=-1&searchword=" +key; } @Override public String makeUrl(String url) { if(url.startsWith("//")){ return "http:"+url; } if(url.startsWith("/")) return getHost()+url.substring(1); return url; } @Override public String getHost() { // TODO: Implement this method return host; } @Override public String getGold() { // TODO: Implement this method return null; } }
PHP
UTF-8
6,344
2.765625
3
[ "Apache-2.0" ]
permissive
<?php namespace app\ad\controller; use think\Controller; // use app\base\model\User as Us; // use app\base\model\Record; // use app\base\model\Member; // use app\base\model\Conference; // use app\base\model\Config as Con; // use app\base\controller\Base as Bas; class Base extends Controller { /*前台基类默认执行方法*/ public function _initialize() { // 获取当前控制器 $request= \think\Request::instance(); if( $request->controller() != 'Log') { //判断是否有登录 if( session('id') === null ) { // 还没有登录系统,跳转到登录页面 return $this->redirect( 'log/login' ); } } } /** * 导出Excel表数据 * * @param $epl 需要导出的数据 * @param $type 导出数据的类型 * */ public function excelExport($epl, $type='records') { header("Content-type:text/html;charset=utf-8"); // 引入库文件 \think\Loader::import('Excel.PHPExcel'); \think\Loader::import('Excel.PHPExcel.IOFactory'); $letter_arr = 'ABCDEFGHIJKLMNOPKRSTUVWXYZ'; if($type == 'records') { $file_name = "预约记录"; $sheet_title = '预约记录'; $cell_value = ['访客姓名', '员工姓名', '来访人数', '约见开始时间', '约见截止时间', '记录类型', '约见事由', '车牌号码']; $cell_key = ['name', 'ename', 'number', 'start_time', 'end_time', 'visittype', 'reasons', 'car_num']; } else if($type == 'visitor'){ $file_name = "访客名单"; $sheet_title = '访客名单'; $cell_value = ['访客姓名', '联系方式', '身份证号(选填)']; $cell_key = ['name', 'phone', 'idcard']; } else if($type == 'employee'){ $file_name = "员工名单"; $sheet_title = '员工名单'; $cell_value = ['员工姓名', '联系方式', '员工地址', '部门(选填)', '身份证号(选填)','员工工号' ]; $cell_key = ['name', 'phone', 'address', 'department', 'idcard','code']; } // 拼接文件名 $file_name .= date("Ymd-His", time()) . ".xls"; $objExcel = new \PHPExcel(); // 创建一个处理对象实例 // 创建文件格式写入对象实例, uncomment $objWriter = new \PHPExcel_Writer_Excel5($objExcel); // 用于其他版本格式 //************************************* //设置文档基本属性 $objProps = $objExcel->getProperties(); $objProps->setCreator("Zeal Li"); $objProps->setLastModifiedBy("Zeal Li"); $objProps->setTitle("Office XLS Test Document"); $objProps->setSubject("Office XLS Test Document, Demo"); $objProps->setDescription("Test document, generated by PHPExcel."); $objProps->setKeywords("office excel PHPExcel"); $objProps->setCategory("Test"); //************************************* //设置当前的sheet索引,用于后续的内容操作。 //一般只有在使用多个sheet的时候才需要显示调用。 //缺省情况下,PHPExcel会自动创建第一个sheet被设置SheetIndex=0 $objExcel->setActiveSheetIndex(0); $objActSheet = $objExcel->getActiveSheet(); //设置当前活动sheet的名称 $objActSheet->setTitle($sheet_title); foreach ($cell_value as $key => $value) { // 设置首单元格内容 $objActSheet->setCellValue(substr($letter_arr, $key, 1) . '1', $value); // 设置单元格宽度 $objActSheet->getColumnDimension(substr($letter_arr, $key, 1))->setWidth(18.5); } // 遍历访客信息数组,将数据存入对应的excel文件的每个单元格 for($i = 0; $i < count($epl); $i++) { if(!isset($epl[$i]['name'])) continue; $epl[$i] = $epl[$i]->toArray(); $j = 0; foreach ($cell_value as $key => $value) { $objExcel->getActiveSheet()->setCellValueExplicit(substr($letter_arr, $j, 1) . ($i+2), $epl[$i][$cell_key[$key]]); $j++; } } //设置字体 $objStyleA = $objActSheet->getStyle('A'); $objStyleA = $objStyleA->getFont(); $objStyleA->setName('宋体'); $objStyleA->setSize(10); $objStyleA->setBold(true); $objStyleA->getColor()->setARGB('FF999999'); //************************************* //输出内容 // $output_file_name = $file_name; header("Content-Type: application/force-download"); header("Content-Type: application/octet-stream"); header("Content-Type: application/download"); header('Content-Disposition:attachment;filename="' . $output_file_name . '"');//兼容其他浏览器到文件 header('Content-Disposition:filename="' . $output_file_name . '"'); //兼容IE浏览器到文件 header('Content-Disposition:inline;filename="'.$output_file_name.'"'); //到浏览器 header("Content-Transfer-Encoding: binary"); header("Expires: 0"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Pragma: no-cache"); $objWriter->save('./excel/'.$output_file_name); return $output_file_name; } #curl http请求 整合get和post static public function getContents($url, $data='') { $header = array( 'Content-Type:application/json;charset=utf-8', // 'Content-Length: ' .strlen($data) ); $curl = curl_init(); curl_setopt($curl,CURLOPT_URL,$url); curl_setopt($curl,CURLOPT_HTTPHEADER,$header); curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,FALSE); curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,FALSE); if(!empty($data)) { curl_setopt($curl,1,1); curl_setopt($curl,CURLOPT_POSTFIELDS,$data); // curl_setopt($curl,1,$data); } // echo "444"; // print_r($data); // die; curl_setopt($curl,CURLOPT_RETURNTRANSFER,1); $output = curl_exec($curl); curl_close($curl); return $output; } }
JavaScript
UTF-8
861
4.34375
4
[]
no_license
/* Given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive). Input: low = 3, high = 7 Output: 3 Explanation: The odd numbers between 3 and 7 are [3,5,7]. Input: low = 8, high = 10 Output: 1 Explanation: The odd numbers between 8 and 10 are [9]. */ // Time Complexity: O(n) // Space Complexity: O(1) function countOdds(low, high) { let i = low; let count = 0; while (i <= high) { if (i % 2) { count++; i = i + 2; } else { i++; } } return count; }; // Time Complexity: O(1) // Space Complexity: O(1) function countOdds(low, high) { let diff = high - low; let count = 0; if (low % 2 == 0 && high % 2 == 0) { count = diff / 2; } else { count = Math.floor(diff / 2) + 1; } return count; };
C#
UTF-8
1,593
2.6875
3
[]
no_license
namespace GameOfLife { internal class SimkinGliderGun : Patterns { public override void Add(IGameOfLife game) { if (game.Width >= 36 && game.Height >= 22) { game.AddCell(3, 1); game.AddCell(3, 2); game.AddCell(4, 1); game.AddCell(4, 2); game.AddCell(7, 4); game.AddCell(8, 4); game.AddCell(7, 5); game.AddCell(8, 5); game.AddCell(10, 1); game.AddCell(10, 2); game.AddCell(11, 1); game.AddCell(11, 2); game.AddCell(23, 18); game.AddCell(23, 19); game.AddCell(24, 18); game.AddCell(24, 20); game.AddCell(25, 20); game.AddCell(26, 20); game.AddCell(26, 21); game.AddCell(24, 11); game.AddCell(24, 12); game.AddCell(24, 13); game.AddCell(25, 10); game.AddCell(26, 10); game.AddCell(25, 13); game.AddCell(26, 13); game.AddCell(28, 10); game.AddCell(29, 10); game.AddCell(30, 11); game.AddCell(31, 12); game.AddCell(30, 13); game.AddCell(29, 14); game.AddCell(34, 12); game.AddCell(35, 12); game.AddCell(34, 13); game.AddCell(35, 13); } } } }
Python
UTF-8
1,616
2.625
3
[]
no_license
# https://gist.github.com/Gerzer/347941cc813c1edc528b # coding utf-8 # A simple blog post auto-upload script for Pythonista Tools from stash import stash import os import console import sys import datetime console.show_activity('Initializing StaSh...') shell = stash.StaSh() console.hide_activity() console.show_activity('Pulling from GitHub...') shell('cd Pythonista-Tools') shell('git pull') console.hide_activity() console.show_activity('Switching to gh-pages...') shell('git checkout gh-pages') if not os.path.exists('_posts'): console.hide_activity() console.show_activity('Creating posts directory...') shell('mkdir _posts') shell('cd _posts') console.hide_activity() console.show_activity('Writing data to file...') now = datetime.datetime.now() file_name = str(now.year) + '-' + str(now.month) + '-' + str(now.day) + '-' + sys.argv[1] file_obj = open(file_name, 'w') file_obj.write(sys.argv[2]) file_obj.close() console.hide_activity() console.show_activity('Staging files...') shell('cd ..') shell('git add "_posts/' + file_name + '"') console.hide_activity() name = console.input_alert('Enter name to commit as') email = console.input_alert('Enter email to commit as') console.show_activity('Committing to gh-pages...') shell('git commit "Post ' + sys.argv[1] + ' to blog" ' + name + ' "' + email + '"') console.hide_activity() username, password = console.login_alert('Sign in to GitHub', 'Your credentials will NOT be saved.') console.show_activity('Pushing to GitHub...') shell('git push -u ' + username + ':' + password) console.hide_activity() console.hud_alert('Post successful!', 'success')
Java
UTF-8
1,691
2.34375
2
[ "Apache-2.0" ]
permissive
/** * * Copyright (c) 2015 Chutong Technologies All rights reserved. * */ /** * Version Control * * | version | date | author | description * 0.0.1 2015.11.30 TwoBirds 整理代码 * */ package com.twobirds.sdk.component.util; import android.util.SparseArray; import android.view.View; import android.view.ViewGroup; import android.widget.ListAdapter; import android.widget.ListView; /** * ListView工具类 * * @author TwoBirds * @version 0.0.1 */ public class ListViewUtil { public static void setListViewHeightBasedOnChildren(ListView listView) { ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) { return; } int totalHeight = 0; for (int i = 0; i < listAdapter.getCount(); i++) { View listItem = listAdapter.getView(i, null, listView); listItem.measure(0, 0); totalHeight += listItem.getMeasuredHeight(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); listView.setLayoutParams(params); } public static <T extends View> T getInItem(View view, int id) { SparseArray<View> viewHolder = (SparseArray<View>) view.getTag(); if (viewHolder == null) { viewHolder = new SparseArray<View>(); view.setTag(viewHolder); } View childView = viewHolder.get(id); if (childView == null) { childView = view.findViewById(id); viewHolder.put(id, childView); } return (T) childView; } }
Markdown
UTF-8
7,769
3.265625
3
[]
no_license
# Verkefni 4 Verkefni 4 snýst um að útfæra vefþjónustu fyrir verkefnalista. Verkefnið er tvíþætt, að útfæra virkni fyrir vefþjónustlista og að útbúa vefþjónustuskil ofan á þá virkni. ## Verkefnið keyrandi á vefnum Hér er hægt að skoða verkefnið mitt, það tekur smá stund fyrir verkefnið að byrja að keyra eftir að þið opnið linkinn Við mælum með að skoða verkefnið með forriti eins og Postman eða einhverjum JSON formatter þar sem þetta er vefþjónusta og öll gögn eru á JSON-formi. * https://bjorgvin-v4.herokuapp.com/ ## Virkni Útfæra skal virkni í `todos.js`, öll föll skjal skjala með [`jsdoc`](https://github.com/vefforritun/vef2-2019/blob/master/fyrirlestrar/02/02.1.modules.md#skj%C3%B6lun-eininga). Virkni skal leyfa að: * Sækja öll verkefni með `id, title, position, due, created, updated, completed` * Mögulegt skal vera að senda inn röðunargildi sem stýrir því hvort lista sé raðað eftir `position` í hækkandi (ascending) eða lækkandi röð (descending) * Mögulegt skal vera að senda inn að aðeins eigi að sýna verkefni sem er lokið (`completed = true`) * Sækja stakt verkefni eftir `id` með `id, title, position, due, created, updated, completed` * Útbúa verkefni með titli, loka dagsetningu og staðsetningu * Verkefni sem er búið til nýtt er alltaf með `completed = false` sem setja má með sjálfgefnu gildi í gagnagrunn * Sjá að neðan um staðfestingu gagna * Uppfæra verkefni eftir `id` með titli, loka dagsetningu, staðsetningu og hvort verkefni sé lokið eða ekki * Eyða verkefni eftir `id` ### Staðfesting gagna * Titill (`title`) skal alltaf senda með og verður hann að vera `[1, 128]` stafir * Ef titill er ekki gildur skal senda villuskilaboðin `Titill verður að vera strengur sem er 1 til 128 stafir` * Loka dagsetning (`due`) má vera tóm (`null`), en ef hún er það ekki, verður hún að vera [ISO 8601 dagsetning](https://en.wikipedia.org/wiki/ISO_8601) * Ef loka dagsetning er ekki gild skal senda villuskilaboðin `Dagsetning verður að vera gild ISO 8601 dagsetning` * Staðsetning (`position`) má vera tóm (`null`), en ef hún er það ekki, verður hún að vera tala, 0 eða stærri * Ef staðsetning er ekki gild skal senda villuskilaboðin `Staðsetning verður að vera heiltala stærri eða jöfn 0` * Hvort verkefni sé lokið (`completed`) verður að vera boolean gildi ef það er sent inn * Ef hvort verkefni sé lokið er ekki gilt skal senda villuskilaboðin `Lokið verður að vera boolean gildi` ## Vefþjónusta * `GET` á `\` skal skila fylki af öllum verkefnum * Ef query-string breyta `order=desc` er send með skal raða verkefnum eftir `position` í lækkandi röð, annars í hækkandi r-ð (ascending). T.d. `/?order=desc` * Ef query-string breyta `completed=true` er send skal aðeins birta verkefni sem er lokið, ef `completed=false` skal aðeins birta verkefni sem er ekki lokið. T.d. `/?completed=true` * Mögulegt á að vera að blanda saman þessum gildum, t.d. `/?completed=true&order=desc` * `POST` á `\` skal útbúa nýtt verkefni * Ef það er ólöglegt skal öllum villum skilað í fylki með skilaboðum að ofan og hvaða reitur var ólöglegur * Ef löglegt er verkefni skilað * `GET` á `\:id` skal skila hlut sem inniheldur verkefni með viðeigandi id * Ef verkefni er til er því skilað sem hlut * Ef verkefni er ekki til skal skila að verkefni sé ekki til * `PATCH` á `\:id` skal uppfæra verkefni með viðeigandi `id` * Ekki þarf að senda öll gögn—aðeins þau sem á að uppfæra * Sömu reglur gilda um gögn og þegar nýtt verkefni er búið til * Ef færsla er ekki til skal skila að verkefni sé ekki til * `DELETE` á `\:id`, eyðir verkefni með viðeigandi `id` * Ef verkefni er eytt skal engu skilað, upplýsingar um niðurstöðu skal gefa til kynna með HTTP status kóða * Ef verkefni er ekki til skal skila að verkefni sé ekki til Velja skal viðeigandi HTTP status kóða fyrir hvert tilvik um sig. ### Dæmi um verkefni ```json { "id": 1, "title": "Skrá í vefforritun 2", "position": 1, "due": null, "created": "2019-02-20T21:36:19.659Z", "updated": "2019-02-20T21:36:19.659Z", "completed": true } ``` ### Dæmi um villu ```json [ { "field": "title", "message": "Titill verður að vera strengur sem er 1 til 128 stafir" } ] ``` ### Dæmi ef verkefni finnst ekki ```json { "error": "Item not found" } ``` ## Gagnagrunnur Geyma skal gögn í postgres gagnagrunni með eftirtalda dálka: * `id`, tölulegt auðkenni * `title`, strengur að hámarki 128 stafir, ekki tómur * `due`, timestamp með tímabelti, má vera tómt * `position`, heiltala, sjálfgefið 0 * `completed`, boolean gildi, sjálfgefið `false` * `created`, timestamp með tímabelti, sjálfgefið _núna_ * `updated`, timestamp með tímabelti, sjálfgefið _núna_ ### Prufugögn Þegar `npm run setup` er keyrt skal setja upp gagnagrunn (g.r.f. að `DATABASE_URL` sé sett) með eftirtöldum prufugögnum: Titill | Staðsetning | Lokið | Ljúka fyrir -------|-------------|-------|--------- Skrá í vefforritun 2 | 1 | true | null Sækja verkefni 4 á github | 2 | false | null Klára verkefni 4 | 3 | false | null Setja verkefni 4 upp á Heroku | 4 | false | null Skila verkefni 4 | 5 | false | 2019-03-08 23:59:59 ## Heroku Verkefnið skal keyra á Heroku með allri þeirri virkni sem hér er lýst ásamt prufugögnum. ## Annað Engu ætti að þurfa að breyta í `app.js`. Öll gögn skulu vera á json formi, bæði sem send eru inn í vefþjónustu og þær sem vefþjónusta skilar. Passa þarf upp á SQL injection og XSS í gögnum sem koma frá notanda. Öll dependency skulu skráð í `package.json`. `npm start` skal keyra upp vefþjón á localhost porti 3000. ## Git og GitHub Verkefni þetta er sett fyrir á GitHub og almennt ætti að skila því úr einka (private) repo nemanda. Nemendur geta fengið gjaldfrjálsan aðgang að einkarepos á meðan námi stendur, sjá https://education.github.com/. Til að byrja er hægt að afrita þetta repo og bæta við á sínu eigin: ```bash > git clone https://github.com/vefforritun/vef2-2019-v4.git > cd vef2-2019-v4 > git remote remove origin # fjarlægja remote sem verkefni er í > git remote add origin <slóð á repo> # bæta við í þínu repo > git push -u origin master # ýta á nýtt origin og tracka branch ``` ## Mat * 10% – Snyrtilegur kóði, engar villur þegar `npm test` er keyrt * 20% – Verkefni sett upp á Heroku * 30% - Vefþjónustuskil * 40% – Virkni verkefnalista ## Sett fyrir Verkefni sett fyrir í fyrirlestri fimmtudaginn 21. febrúar 2019. ## Skil Skila skal undir „Verkefni og hlutaprófa“ á Uglu í seinasta lagi fyrir lok dags föstudaginn 8. mars 2019. Skilaboð skulu innihalda: * Slóð á GitHub repo fyrir verkefni, og dæmatímakennurum skal hafa verið boðið í repo (sjá leiðbeiningar). Notendanöfn þeirra eru `freyrdanielsson`, `gunkol`, `kth130` * Slóð á verkefni keyrandi á Heroku ## Einkunn Sett verða fyrir sex minni verkefni þar sem fimm bestu gilda 6% hvert, samtals 30% af lokaeinkunn. Sett verða fyrir tvö hópverkefni þar sem hvort um sig gildir 15%, samtals 30% af lokaeinkunn. Verkefnahluti gildir 60% og lokapróf gildir 40%. Ná verður *bæði* verkefnahluta og lokaprófi með lágmarkseinkunn 5. --- > Útgáfa 0.2 | Útgáfa | Lýsing | |--------|-------------------------------------------| | 0.1 | Fyrsta útgáfa | | 0.2 | Bæta við um query-string fyrir GET /, lagfæra lýsingu á því sem senda þarf inn |
TypeScript
UTF-8
4,174
2.515625
3
[ "MIT", "BSD-3-Clause", "Apache-2.0" ]
permissive
import resolveFrom from 'resolve-from'; const debug = require('debug')('expo:metro:import'); // These resolvers enable us to test the CLI in older projects. // We may be able to get rid of this in the future. // TODO: Maybe combine with AsyncResolver? class MetroImportError extends Error { constructor(projectRoot: string, moduleId: string) { super( `Missing package "${moduleId}" in the project at: ${projectRoot}\n` + 'This usually means "react-native" is not installed. ' + 'Please verify that dependencies in package.json include "react-native" ' + 'and run `yarn` or `npm install`.' ); } } function resolveFromProject(projectRoot: string, moduleId: string) { const resolvedPath = resolveFrom.silent(projectRoot, moduleId); if (!resolvedPath) { throw new MetroImportError(projectRoot, moduleId); } return resolvedPath; } function importFromProject(projectRoot: string, moduleId: string) { return require(resolveFromProject(projectRoot, moduleId)); } /** Import `metro` from the project. */ export function importMetroFromProject(projectRoot: string): typeof import('metro') { return importFromProject(projectRoot, 'metro'); } export function importMetroCreateWebsocketServerFromProject( projectRoot: string ): typeof import('metro/src/lib/createWebsocketServer').createWebsocketServer { return importFromProject(projectRoot, 'metro/src/lib/createWebsocketServer'); } export function importMetroHmrServerFromProject( projectRoot: string ): typeof import('metro/src/HmrServer').MetroHmrServer { return importFromProject(projectRoot, 'metro/src/HmrServer'); } export function importExpoMetroConfig(projectRoot: string) { return importFromProjectOrFallback<typeof import('@expo/metro-config')>( projectRoot, '@expo/metro-config' ); } /** * Attempt to use the local version of a module or fallback on the CLI version. * This should only ever happen when testing Expo CLI in development. */ export function importFromProjectOrFallback<TModule>( projectRoot: string, moduleId: string ): TModule { const resolvedPath = resolveFrom.silent(projectRoot, moduleId); if (!resolvedPath) { debug(`requiring "${moduleId}" relative to the CLI`); return require(require.resolve(moduleId)); } debug(`requiring "${moduleId}" from the project:`, resolvedPath); return require(resolvedPath); } /** Import `metro-resolver` from the project. */ export function importMetroResolverFromProject( projectRoot: string ): typeof import('metro-resolver') { return importFromProject(projectRoot, 'metro-resolver'); } /** Import `metro-inspector-proxy` from the project. */ export function importMetroInspectorProxyFromProject( projectRoot: string ): typeof import('metro-inspector-proxy') { return importFromProject(projectRoot, 'metro-inspector-proxy'); } /** Import `metro-inspector-proxy/src/Device` from the project. */ export function importMetroInspectorDeviceFromProject( projectRoot: string ): typeof import('metro-inspector-proxy/src/Device') { return importFromProject(projectRoot, 'metro-inspector-proxy/src/Device'); } /** * Import the internal `saveAssets()` function from `react-native` for the purpose * of saving production assets as-is instead of converting them to a hash. */ export function importCliSaveAssetsFromProject( projectRoot: string ): typeof import('@react-native-community/cli-plugin-metro/build/commands/bundle/saveAssets').default { return importFromProject( projectRoot, '@react-native-community/cli-plugin-metro/build/commands/bundle/saveAssets' ).default; } export function importCliBuildBundleWithConfigFromProject( projectRoot: string ): typeof import('@react-native-community/cli-plugin-metro/build/commands/bundle/buildBundle').buildBundleWithConfig { return importFromProject( projectRoot, '@react-native-community/cli-plugin-metro/build/commands/bundle/buildBundle' ).buildBundleWithConfig; } /** Resolve the installed Metro version from project */ export function resolveMetroVersionFromProject(projectRoot: string): string { return importFromProject(projectRoot, 'metro/package.json').version; }
Java
UTF-8
208
1.59375
2
[]
no_license
package com.mytest.dao; import com.mytest.domain.Student; import org.springframework.data.mongodb.repository.MongoRepository; public interface StudentRepository extends MongoRepository<Student, String> { }
Markdown
UTF-8
2,371
2.671875
3
[]
no_license
# HTML 17-02-19 Wifi: 2182299978 #### HTML Es un lenguaje de etiqueta de hipertexto(Maquetar y etiquetar) 'No tiene nada de programacion' El navegador necesita cierta estructura: - header, body, footer. - El atributo lang indica el idioma Visual estudio es mas rápido, estable, cuenta con diversos pluggins y es fácil. > WAKA TIME - Siempre abrir y cerrar las etiquetas, por buena practica y productividad. - Lo que esta en body es lo que vera el usuario. - Patallas de retina tienen buena resolucion por ello es recomendable tenerla al doble el ancho de pixelaje pues el navegador comprime las imagenes. - Es mejor utilizar el ancho en diseño responsivo. #### Listas - El atributo *_blank* hace que se abra en una nueva pestaña, recomendable para UX. - El atributo *_self* hace que se abra en nuestra pestaña actual. > Dentro de las listas podemos poner mas etiquetas, esto es ideal para una seccion de preguntas y respuestas. - Dentro de una UL puede vivir una OL y viceversa, esto es ideal para una receta de cocina o un temario de algun curso. #### Formulario - Label es unicamente para formularios. - El atributo name es vital en un formulario ya que identifica los campos en el envio de formularios. - El for asocia el id del input con el label, para posicionar el cursor. - Usar los type de los input ayuda a validar la información. - Para garantizar la calidad de la informacion utilizar el atributo type correctamente. - Atributo accept ayuda a limitar los tipos de archivo que se subiran. - required ayuda a que el formulario no sea enviado sin informacion. - acction indica a que servidor sera enviado, es un atributo va en el form. ##### TextArea - El atributo rols y cols sirve para el tamaño que ocupara el textarea mediante la cantidad de caracteres. ##### Select - Lista de valores definidos - disabled deshabilita la opción que contiene lo contiene. - selected genera una opcion por default - Value es el valor que tendra la opcion elegida ##### Radio - Sirve para una seleccion. ##### Checkbox - Sirve para seleccion multiple. - checked sirve para seleccion un checkbox por default. ### RECOMENDACION PARA SEO - El title no debe llevar mas de 55 caracteres. - Siempre en el header va menu de navegación. - Carpeta de imagenes debe llamarse img o images. - Solo poner un h1 y no rebasar el h5 por compatibilidad en navegadores.
Python
UTF-8
4,733
2.65625
3
[]
no_license
import numpy as np import pandas as pd from sklearn.model_selection import KFold from sklearn.metrics import log_loss, r2_score from sklearn.base import BaseEstimator, TransformerMixin class BlendingClassifier(): def __init__(self, clfs, n_class, folds=5, verbose=0): self.clfs = clfs self.kfold = KFold(folds) self.verbose = verbose self.n_class = n_class def __fit_one_fold(self, X, y): for clf in self.clfs: clf.fit(X, y) def __predict_one_fold(self, X): res = np.ones((X.shape[0], 1)) * (-1) for clf in self.clfs: res = np.column_stack((res, clf.predict_proba(X))) return np.array(res[:, 1:]) def fit_transform_train(self, X, y): res = np.ones((X.shape[0], len(self.clfs) * self.n_class)) * (-1) X_train = X # k-fold for training set for (tr_idx, cv_idx) in self.kfold.split(X_train, y): X_tr, y_tr = X_train[tr_idx], y[tr_idx] X_cv, y_cv = X_train[cv_idx], y[cv_idx] self.__fit_one_fold(X_tr, y_tr) res[cv_idx, :] = self.__predict_one_fold(X_cv) if self.verbose > 0: print("Fold results (cv error):") # TODO - add different metrics for (idx, clf) in enumerate(self.clfs): print( "clf {:2d}: {:06.4f}". format(idx, log_loss(y_cv, clf.predict_proba(X_cv)))) return res def fit_transform_test(self, Xtr, ytr, Xts): # Xtr = Xtr.todense() # Xts = Xts.todense() self.__fit_one_fold(Xtr, ytr) return self.__predict_one_fold(Xts) class BlendingRegressorTransformer(): def __init__(self, base_models=None, n_splits=5, verbose=0, scoring=r2_score): self.base_models = [[m for m in base_models] for s in n_splits] self.n_splits = n_splits self.folds = None self.verbose = verbose self.hash = None self.target = None self.isTrainFit = False self.scoring = scoring def fit_one_fold_(self, X, y): for rgr in self.base_models: rgr.fit(X, y) def predict_one_fold_(self, X): res = np.zeros((X.shape[0], 1)) for rgr in self.base_models: res = np.column_stack((res, rgr.predict(X))) return np.array(res[:, 1:]) def fit(self, X, y): self.hash = hash(X.data.tobytes()) self.isTrainFit = True self.folds = list(KFold(n_splits=self.n_splits).split(X, y)) for i, rgr in enumerate(self.base_models): for j, (train_idx, test_idx) in enumerate(self.folds): X_train = X[train_idx] y_train = y[train_idx] X_holdout = X[test_idx] y_holdout = y[test_idx] self.base_models[i, j].fit(X_train, y_train) y_pred = self.base_models[i, j].predict(X_holdout)[:] print ("Model %d fold %d score %f" % (i, j, r2_score(y_holdout, y_pred))) return self def transform_train_(self, X): X_result = np.zeros((X.shape[0], len(self.base_models))) for i, rgr in enumerate(self.base_models): for j, (train_idx, test_idx) in enumerate(self.folds): X_holdout = X[test_idx] y_pred = self.base_models[i, j].predict(X_holdout)[:] X_result[test_idx, i] = y_pred return X_result def transform_test_(self, X): X_result = np.zeros((X.shape[0], len(self.base_models))) for i, rgr in enumerate(self.base_models): X_result_i = np.zeros((X.shape[0], self.n_splits)) for j, (train_idx, test_idx) in enumerate(self.folds): X_result_i[:, j] = self.base_models[i, j].predict(X)[:] X_result[:, i] = X_result_i.mean(axis=1) return X_result def transform(self, X): if hash(X.data.tobytes()) == self.hash: return self.transform_train_(X) else: return self.transform_test_(X) def fit_transform(self, X, y): self.hash = hash(X.data.tobytes()) self.fit(X, y) self.isTrainFit = True return self.transform_train_(X, y) class PipeExtractor(BaseEstimator, TransformerMixin): def __init__(self, fields): self.fields = fields def fit(self, X, y=None): return self def transform(self, X): return X[self.fields] class PipeShape(BaseEstimator, TransformerMixin): def fit(self, X, y=None): return self def transform(self, X): print("Pipeline output shape: ", X.shape) return X
C++
UTF-8
2,614
2.734375
3
[ "MIT" ]
permissive
#pragma once // class wrappong a memmapped object #include <sys/mman.h> #include <stdio.h> #include <unistd.h> #include <stdint.h> #include <algorithm> #ifdef __ANDROID_API__ extern "C" void* __mmap2(void*, size_t, int, int, int, size_t); #define mymmap __mmap2 #define mmapoffset(x) (x>>12) #else #define mymmap mmap #define mmapoffset(x) (x) #endif /* * NOTE: problem on macosx: you can't mmap a block or char device. * * see https://stackoverflow.com/questions/24520474/mmap-a-block-device-on-mac-os-x * * the problem is in the mmap kernel driver: https://opensource.apple.com/source/xnu/xnu-2422.1.72/bsd/kern/kern_mman.c if (vp->v_type != VREG && vp->v_type != VCHR) { (void)vnode_put(vp); error = EINVAL; goto bad; } ... if (vp->v_type == VCHR || vp->v_type == VSTR) { (void)vnode_put(vp); error = ENODEV; goto bad; } */ // class for creating a memory mapped file. struct mappedmem { uint8_t *pmem; uint64_t phys_length; uint64_t dataofs; uint64_t length; static uint64_t round_up(uint64_t ofs, uint64_t base) { return ((ofs-1)|(base-1))+1; } static uint64_t round_down(uint64_t ofs, uint64_t base) { return ofs & ~(base-1); } mappedmem(mappedmem&& mm) { pmem= mm.pmem; phys_length= mm.phys_length; dataofs= mm.dataofs; mm.pmem= nullptr; } mappedmem(int f, uint64_t start, uint64_t end, int mmapmode= PROT_READ|PROT_WRITE) { uint64_t pagesize= std::max(0x1000, (int)sysconf(_SC_PAGE_SIZE)); uint64_t phys_start= round_down(start, pagesize); uint64_t phys_end= round_up(end, pagesize); phys_length= phys_end - phys_start; length = end - start; pmem= (uint8_t*)mymmap(NULL, phys_length, mmapmode, MAP_SHARED, f, mmapoffset(phys_start)); if (pmem==MAP_FAILED) { //printf("l=%llx, mm=%x, s=%llx\n", phys_length, mmapmode, phys_start); //printf("start=%llx -> %llx, end=%llx -> %llx\n", start, phys_start, end, phys_end); throw std::system_error(errno, std::generic_category(), "mmap"); } dataofs= start - phys_start; } // todo: add madvise support ~mappedmem() { if (!pmem) return; if (munmap(pmem, phys_length)) perror("munmap"); } uint8_t *ptr() { return pmem+dataofs; } uint8_t *begin() { return ptr(); } uint8_t *end() { return ptr() + length; } size_t size() { return length; } };
Java
UTF-8
746
3.703125
4
[]
no_license
package com.windknew.unit2; /* * (驾驶费用)编写一个程序,提示用户输入驾驶的距离、以每加仑多少英里的汽车燃油性能,以及每加仑的价格,然后显示旅程的费用。 * * */ import java.util.Scanner; public class Exercise2_23 { public static void main(String[] args){ Scanner in = new Scanner(System.in); System.out.print("Enter the driving distance : "); double distance = in.nextDouble(); System.out.print("Enter miles per gallon: "); double miles = in.nextDouble(); System.out.print("Enter price per gallon"); double price = in.nextDouble(); System.out.println("The cost of driving is: " + distance / miles * price); } }
Ruby
UTF-8
180
3.328125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def prime?(number) if number > 1 for divider in 2..(number - 1) if (number % divider) == 0 return false end end true else false end end
C
UTF-8
1,739
2.921875
3
[]
no_license
// // pass2.h // Assembler // // Created by Giancarlo Anemone and Caitlin Braun on 5/12/13. // Copyright (c) 2013 Giancarlo Anemone and Caitlin Braun. All rights reserved. // #ifndef Assembler_pass2_h #define Assembler_pass2_h /*getBinary function determines the unsigned binary value of a particular decimal number for a given number of bits *parameters include the decimal nubmer and the number of bits the binary result will be expressed in *returns a pointer to the string containing the binary representation */ char* getBinary(int dec, int range); /* getRegisterCode determines the binary representation of each register *paramaters include the pointer to the register name */ char* getRegisterCode(char * regName); /* getNetToken finds the next token in the line using delimeters of ',', '(', ')', ':', or '\0' * Parameters include the pointer to the register, the token beginning and the token end */ int getNextToken(char **reg,char **tokBegin,char **tokEnd); /* getNameInfo determines all of the information about the instruction that can be determined by the name of the instruction *Paramters include the pointer to the name of the instruction and the pointer to the array containing the information for each instruction */ int getNameInfo(char * name, char ** info); /*getRegisters assigns the source register, the shift amount, the destination register, and the address to the instruction *Paramaters include two source registers, destination register, shift amount, address, token begin and token end. When one of the parameters is null the register will not be assigned as it is not needed for the instruction */ int getRegisters(char** rs, char** rt, char** rd, char** shamt, char** address, char* tokBegin, char* tokEnd); #endif
Markdown
UTF-8
2,420
2.9375
3
[]
no_license
# Youtube Watchmen ## Overview An app to get the latest videos on predefined search query. This app provides an API for the latest videos sorted in reverse chronological order of their publishing date-time from YouTube for a given tag/search query in a paginated response. ### Features - Paginated API response - Async YT Data fetch with the help of celery and redis - API Key rotation in case of quota exhaustion - UI to display all the videos ### Screenshots ![alt screenshot](.github/images/ytw-ss1.png) ### API endpoints - `GET /api/videos/` - This endpoint returns a list of all videos in the database in a paginated resposne. ## Build Guide ### Create Virtual Environment Create a virtual environment and activate it ```shell python3 -m venv env source env/bin/active ``` Now move inside the project folder ```shell cd YoutubeWatchmen ``` ### Install dependencies Install python dependencies ```shell pip install -r requirements.txt ``` For the async API fecth function to work, you need to install redis and start a celery worker. Steps to install redis are as follows: 1. For ubuntu server `sudo apt install redis-server` 2. `sudo nano /etc/redis/redis.conf` 3. Inside the file find the `supervised` directive and change it to `systemd`. It should be set to `no` by default. ``` ... supervised systemd ... ``` 4. `sudo systemctl restart redis.service` 5. Add `redis://localhost:6379` in the `CELERY_BROKER_URL` part of the `.env` file you have in your locally cloned repository. To check if redis is working correctly or not: 1. Type in `redis-cli` 2. Type `ping` 3. If it returns `PONG`, then your redis-broker server is running fine. ### Configuration This project uses `python-decouple` for dotenv files ```shell cp .env.example .env ``` Then `.env` according to the needs *For the ease of configuration, I have kept defaults in all configurations, so it will work even if you ignore this step* ### Run the app Steps to follow to run the app ```shell python manage.py migrate python manage.py runserver ``` Open a another terminal, activate the virtual environment and start celery by ```shell celery -A YoutubeWatchmen worker -B -E -l INFO ``` ### For Production uses - Nginx as reverse proxy - Gunicorn as WSGI server - PostgreSQL as DB - Services (gunicorn, celery, nginx) can be managed by systemctl units. - Multiple workers for can be used with celery for scaling
JavaScript
UTF-8
3,352
3.015625
3
[ "ISC" ]
permissive
import regeneratorRuntime from 'regenerator-runtime'; import { join } from 'path'; import { asyncMap } from './async'; import { lStat, readDir, stat } from './fs'; /** * File */ export default class File { /** * Create an instance of File * * @param {string} path Path to a file, directory, or symlink * @param {boolean} isDirectory Whether the file is a directory or not. Symbolic links to * directories are not considered directories. * @param {boolean} isSymbolicLink Whether the file is a symbolic link. */ constructor(path, isDirectory, isSymbolicLink) { this.path = path; this.isDirectory = isDirectory; this.isSymbolicLink = isSymbolicLink; } /** * @returns {string} A string representation of the file. */ toString() { return this.path; } /** * Generate children of the file. * * @async * @generator * @returns {AsynchronousGenerator<File>} Generates one instance of File per child. */ async *getChildren() { if (!this.isDirectory) { throw new Error(`File is not a directory: ${this}`); } yield* this.constructor.readDir(this.path); } /** * Resolve symbolic link. * * @returns {Promise<File>} A new File instance if the current file is a symbolic link and has not * been resolved yet. Otherwise, returns this file. */ async followSymbolicLink() { if (this.isSymbolicLink && this.isDirectory === undefined) { return this.constructor.fromPath(this.path, true); } return this; } /** * Create an instance of File from a `fs.Dirent` object of a file. * * @param {string} directory Parent directory of the file. * @param {fs.Dirent} dirent Dirent object of the file. * @returns {File} An instance of File representing the file. * @see {@link https://nodejs.org/api/fs.html#fs_class_fs_dirent|fs.Dirent} */ static fromDirent(directory, dirent) { const path = join(directory, dirent.name); return new this( path, dirent.isSymbolicLink() ? undefined : dirent.isDirectory(), dirent.isSymbolicLink(), ); } /** * Create an instance of File from a file path. * * @async * @param {string} path Path to the file. * @returns {Promise<File>} An instance of File representing the file. */ static async fromPath(path, followSymbolicLink = false) { const stats = await (followSymbolicLink ? stat : lStat)(path); return new this( path, stats.isSymbolicLink() ? undefined : stats.isDirectory(), stats.isSymbolicLink(), ); } /** * Generate instances of File from multiple paths. * * @async * @generator * @param {string[]} paths Paths of the file. * @returns {AsyncGenenerator<File>} One instance of File per path. */ static fromPaths(paths) { return asyncMap(paths, this.fromPath.bind(this)); } /** * Create instance of files from a directory path. * * @param {string} directory Directory path. * @returns {AsyncGenenerator<File>} An asynchronous generator of files. */ static async *readDir(directory) { yield* asyncMap(await readDir(directory, { withFileTypes: true }), child => typeof child === 'string' ? this.fromPath(join(directory, child)) // withFileTypes requires Node 10+ : this.fromDirent(directory, child), ); } }
Go
UTF-8
10,707
2.71875
3
[]
no_license
package server import ( "encoding/json" "io/ioutil" "net/http" "github.com/bavaz1/go-pubg/database" "github.com/go-chi/chi" "github.com/gorilla/mux" ) type Server struct { Client *http.Client Address string Storage database.Storage } func (s *Server) Listen() { r := chi.NewRouter() r.Route("/api/v1", func(r chi.Router) { r.Route("/players", func(r chi.Router) { r.Get("/", s.getPlayers) r.Post("/", s.createPlayer) r.Get("/{id}", s.getPlayer) r.Put("/{id}", s.putPlayer) r.Delete("/{id}", s.deletePlayer) r.Route("/{playerId}/matches", func(r chi.Router) { r.Get("/", s.getPlayerMatches) r.Post("/", s.createPlayerMatch) r.Get("/{id}", s.getPlayerMatch) r.Put("/{id}", s.putPlayerMatch) r.Delete("/{id}", s.deletePlayerMatch) }) }) r.Route("/match", func(r chi.Router) { r.Get("/", s.getMatches) r.Post("/", s.createMatch) r.Get("/{id}", s.getMatch) r.Put("/{id}", s.putMatch) r.Delete("/{id}", s.deleteMatch) }) r.Route("/cups", func(r chi.Router) { r.Get("/", s.getCups) r.Post("/", s.createCup) r.Get("/{id}", s.getCup) r.Put("/{id}", s.putCup) r.Delete("/{id}", s.deleteCup) r.Route("/{cupId}/matches", func(r chi.Router) { r.Get("/", s.getCupMatches) r.Post("/", s.createCupMatch) r.Get("/{id}", s.getCupMatch) r.Put("/{id}", s.putCupMatch) r.Delete("/{id}", s.deleteCupMatch) }) }) }) http.ListenAndServe(s.Address, r) } func (s *Server) getPlayers(w http.ResponseWriter, r *http.Request) { p := s.Storage.GetPlayers() response, err := json.Marshal(p) if err != nil { panic(err) } w.WriteHeader(http.StatusCreated) w.Write(response) } func (s *Server) createPlayer(w http.ResponseWriter, r *http.Request) { b, err := ioutil.ReadAll(r.Body) if err != nil { panic(err) } defer r.Body.Close() var player database.Player err = json.Unmarshal(b, &player) if err != nil { panic(err) } p := s.Storage.CreatePlayer(player) response, err := json.Marshal(p) if err != nil { panic(err) } w.WriteHeader(http.StatusCreated) w.Write(response) } func (s *Server) getPlayer(w http.ResponseWriter, r *http.Request) { var player database.Player params := mux.Vars(r) player.ID = params["id"] p := s.Storage.GetPlayer(player) response, err := json.Marshal(p) if err != nil { panic(err) } w.WriteHeader(http.StatusCreated) w.Write(response) } func (s *Server) putPlayer(w http.ResponseWriter, r *http.Request) { var player database.Player params := mux.Vars(r) player.ID = params["id"] b, err := ioutil.ReadAll(r.Body) if err != nil { panic(err) } defer r.Body.Close() err = json.Unmarshal(b, &player) if err != nil { panic(err) } p := s.Storage.UpdatePlayer(player) response, err := json.Marshal(p) if err != nil { panic(err) } w.WriteHeader(http.StatusCreated) w.Write(response) } func (s *Server) deletePlayer(w http.ResponseWriter, r *http.Request) { var player database.Player params := mux.Vars(r) player.ID = params["id"] p := s.Storage.DeletePlayer(player) response, err := json.Marshal(p) if err != nil { panic(err) } w.WriteHeader(http.StatusCreated) w.Write(response) } func (s *Server) getMatches(w http.ResponseWriter, r *http.Request) { m := s.Storage.GetMatches() response, err := json.Marshal(m) if err != nil { panic(err) } w.WriteHeader(http.StatusCreated) w.Write(response) } func (s *Server) createMatch(w http.ResponseWriter, r *http.Request) { b, err := ioutil.ReadAll(r.Body) if err != nil { panic(err) } defer r.Body.Close() var match database.Match err = json.Unmarshal(b, &match) if err != nil { panic(err) } m := s.Storage.CreateMatch(match) response, err := json.Marshal(m) if err != nil { panic(err) } w.WriteHeader(http.StatusCreated) w.Write(response) } func (s *Server) getMatch(w http.ResponseWriter, r *http.Request) { var match database.Match params := mux.Vars(r) match.ID = params["id"] m := s.Storage.GetMatch(match) response, err := json.Marshal(m) if err != nil { panic(err) } w.WriteHeader(http.StatusCreated) w.Write(response) } func (s *Server) putMatch(w http.ResponseWriter, r *http.Request) { var match database.Match params := mux.Vars(r) match.ID = params["id"] b, err := ioutil.ReadAll(r.Body) if err != nil { panic(err) } defer r.Body.Close() err = json.Unmarshal(b, &match) if err != nil { panic(err) } m := s.Storage.UpdateMatch(match) response, err := json.Marshal(m) if err != nil { panic(err) } w.WriteHeader(http.StatusCreated) w.Write(response) } func (s *Server) deleteMatch(w http.ResponseWriter, r *http.Request) { var match database.Match params := mux.Vars(r) match.ID = params["id"] m := s.Storage.DeleteMatch(match) response, err := json.Marshal(m) if err != nil { panic(err) } w.WriteHeader(http.StatusCreated) w.Write(response) } func (s *Server) getCups(w http.ResponseWriter, r *http.Request) { c := s.Storage.GetCups() response, err := json.Marshal(c) if err != nil { panic(err) } w.WriteHeader(http.StatusCreated) w.Write(response) } func (s *Server) createCup(w http.ResponseWriter, r *http.Request) { b, err := ioutil.ReadAll(r.Body) if err != nil { panic(err) } defer r.Body.Close() var cup database.Cup err = json.Unmarshal(b, &cup) if err != nil { panic(err) } c := s.Storage.CreateCup(cup) response, err := json.Marshal(c) if err != nil { panic(err) } w.WriteHeader(http.StatusCreated) w.Write(response) } func (s *Server) getCup(w http.ResponseWriter, r *http.Request) { var cup database.Cup params := mux.Vars(r) cup.ID = params["id"] c := s.Storage.GetCup(cup) response, err := json.Marshal(c) if err != nil { panic(err) } w.WriteHeader(http.StatusCreated) w.Write(response) } func (s *Server) putCup(w http.ResponseWriter, r *http.Request) { var cup database.Cup params := mux.Vars(r) cup.ID = params["id"] b, err := ioutil.ReadAll(r.Body) if err != nil { panic(err) } defer r.Body.Close() err = json.Unmarshal(b, &cup) if err != nil { panic(err) } c := s.Storage.UpdateCup(cup) response, err := json.Marshal(c) if err != nil { panic(err) } w.WriteHeader(http.StatusCreated) w.Write(response) } func (s *Server) deleteCup(w http.ResponseWriter, r *http.Request) { var cup database.Cup params := mux.Vars(r) cup.ID = params["id"] c := s.Storage.DeleteCup(cup) response, err := json.Marshal(c) if err != nil { panic(err) } w.WriteHeader(http.StatusCreated) w.Write(response) } func (s *Server) getPlayerMatches(w http.ResponseWriter, r *http.Request) { var playerMatch database.PlayerMatch params := mux.Vars(r) playerMatch.PlayerID = params["playerId"] p := s.Storage.GetPlayerMatches(playerMatch) response, err := json.Marshal(p) if err != nil { panic(err) } w.WriteHeader(http.StatusCreated) w.Write(response) } func (s *Server) createPlayerMatch(w http.ResponseWriter, r *http.Request) { b, err := ioutil.ReadAll(r.Body) if err != nil { panic(err) } defer r.Body.Close() var playerMatch database.PlayerMatch err = json.Unmarshal(b, &playerMatch) if err != nil { panic(err) } p := s.Storage.CreatePlayerMatch(playerMatch) response, err := json.Marshal(p) if err != nil { panic(err) } w.WriteHeader(http.StatusCreated) w.Write(response) } func (s *Server) getPlayerMatch(w http.ResponseWriter, r *http.Request) { var playerMatch database.PlayerMatch params := mux.Vars(r) playerMatch.MatchID = params["id"] playerMatch.PlayerID = params["playerId"] p := s.Storage.GetPlayerMatch(playerMatch) response, err := json.Marshal(p) if err != nil { panic(err) } w.WriteHeader(http.StatusCreated) w.Write(response) } func (s *Server) putPlayerMatch(w http.ResponseWriter, r *http.Request) { var playerMatch database.PlayerMatch params := mux.Vars(r) playerMatch.MatchID = params["id"] playerMatch.PlayerID = params["playerId"] b, err := ioutil.ReadAll(r.Body) if err != nil { panic(err) } defer r.Body.Close() err = json.Unmarshal(b, &playerMatch) if err != nil { panic(err) } p := s.Storage.UpdatePlayerMatch(playerMatch) response, err := json.Marshal(p) if err != nil { panic(err) } w.WriteHeader(http.StatusCreated) w.Write(response) } func (s *Server) deletePlayerMatch(w http.ResponseWriter, r *http.Request) { var playerMatch database.PlayerMatch params := mux.Vars(r) playerMatch.MatchID = params["id"] playerMatch.PlayerID = params["playerId"] p := s.Storage.DeletePlayerMatch(playerMatch) response, err := json.Marshal(p) if err != nil { panic(err) } w.WriteHeader(http.StatusCreated) w.Write(response) } func (s *Server) getCupMatches(w http.ResponseWriter, r *http.Request) { var cupMatch database.CupMatch params := mux.Vars(r) cupMatch.CupID = params["cupId"] c := s.Storage.GetCupMatches(cupMatch) response, err := json.Marshal(c) if err != nil { panic(err) } w.WriteHeader(http.StatusCreated) w.Write(response) } func (s *Server) createCupMatch(w http.ResponseWriter, r *http.Request) { b, err := ioutil.ReadAll(r.Body) if err != nil { panic(err) } defer r.Body.Close() var cupMatch database.CupMatch err = json.Unmarshal(b, &cupMatch) if err != nil { panic(err) } c := s.Storage.CreateCupMatch(cupMatch) response, err := json.Marshal(c) if err != nil { panic(err) } w.WriteHeader(http.StatusCreated) w.Write(response) } func (s *Server) getCupMatch(w http.ResponseWriter, r *http.Request) { var cupMatch database.CupMatch params := mux.Vars(r) cupMatch.CupID = params["cupId"] cupMatch.MatchID = params["id"] c := s.Storage.GetCupMatch(cupMatch) response, err := json.Marshal(c) if err != nil { panic(err) } w.WriteHeader(http.StatusCreated) w.Write(response) } func (s *Server) putCupMatch(w http.ResponseWriter, r *http.Request) { var cupMatch database.CupMatch params := mux.Vars(r) cupMatch.CupID = params["cupId"] cupMatch.MatchID = params["id"] b, err := ioutil.ReadAll(r.Body) if err != nil { panic(err) } defer r.Body.Close() err = json.Unmarshal(b, &cupMatch) if err != nil { panic(err) } c := s.Storage.UpdateCupMatch(cupMatch) response, err := json.Marshal(c) if err != nil { panic(err) } w.WriteHeader(http.StatusCreated) w.Write(response) } func (s *Server) deleteCupMatch(w http.ResponseWriter, r *http.Request) { var cupMatch database.CupMatch params := mux.Vars(r) cupMatch.CupID = params["cupId"] cupMatch.MatchID = params["id"] c := s.Storage.DeleteCupMatch(cupMatch) response, err := json.Marshal(c) if err != nil { panic(err) } w.WriteHeader(http.StatusCreated) w.Write(response) }
C++
UTF-8
2,164
3.125
3
[ "MIT" ]
permissive
#include "problemes.h" #include "arithmetique.h" #include "racine.h" typedef unsigned long long nombre; typedef std::vector<nombre> vecteur; namespace { struct Point { long double x; long double y; Point(long double _x, long double _y) : x(_x), y(_y) {} bool operator<(const Point &p) const { if (std::abs(x - p.x) < std::numeric_limits<long double>::epsilon()) return x < p.x; return y < p.y; } }; } ENREGISTRER_PROBLEME(184, "Triangles containing the origin") { // Consider the set Ir of points (x,y) with integer co-ordinates in the interior of the circle with radius r, // centered at the origin, i.e. x2 + y2 < r2. // // For a radius of 2, I2 contains the nine points (0,0), (1,0), (1,1), (0,1), (-1,1), (-1,0), (-1,-1), (0,-1) and // (1,-1). There are eight triangles having all three vertices in I2 which contain the origin in the interior. Two // of them are shown below, the others are obtained from these by rotation. // // For a radius of 3, there are 360 triangles containing the origin in the interior and having all vertices in I3 // and for I5 the number is 10600. // // How many triangles are there containing the origin in the interior and having all three vertices in I105? nombre limite = 105; std::vector<std::pair<Point, nombre>> points; for (nombre x = 0; x < limite; ++x) for (nombre y = 1; y < limite; ++y) { nombre r2 = x * x + y * y; if (r2 > 0 && r2 < limite * limite && arithmetique::PGCD(x, y) == 1) points.emplace_back(Point(x, y), racine::racine_carre((limite * limite - 1) / r2)); } std::sort(points.begin(), points.end()); nombre resultat = 0; size_t longueur = points.size(); for (size_t i = 0; i < longueur; ++i) { nombre compteur = 0; for (size_t j = i + 1; j < i + 2 * longueur; ++j) { resultat += points[i].second * points[j % longueur].second * compteur; compteur += points[j % longueur].second; } } return std::to_string(resultat * 4 / 3); }
Java
UTF-8
4,552
2.171875
2
[]
no_license
package com.example.codelabs.moviestage; import android.os.Parcel; import android.os.Parcelable; import android.util.Log; import com.example.codelabs.moviestage.Utils.MovieUtils; import java.util.List; /** * Created by varshaa on 23-11-2017. */ public class Movie implements Parcelable { //Parcel creator public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public Movie createFromParcel(Parcel in) { return new Movie(in); } public Movie[] newArray(int size) { return new Movie[size]; } }; private String mImageUrl; private String mOriginalTitle; private String mOverview; private String mReleaseDate; private String mVoteAverage; private String mId; private String mTrailerUrl; private String mReviewUrl; private int mByteArraySize; //private boolean offlineFlag; public byte[] getmRawImage() { return mRawImage; } private byte[] mRawImage; private List<Trailer> mTrailer; private List<Review> mReview; //public boolean isOfflineFlag() { //return offlineFlag; //} public Movie(String mImageUrl, String mOriginalTitle, String mOverview, String mReleaseDate, String mVoteAverage, String mId, int mByteArraySize, byte[] mRawImage /*boolean offlineFlag*/) { this.mImageUrl = mImageUrl; this.mOriginalTitle = mOriginalTitle; this.mOverview = mOverview; this.mReleaseDate = mReleaseDate; this.mVoteAverage = mVoteAverage; this.mId = mId; this.mByteArraySize = mByteArraySize; this.mRawImage = mRawImage; //this.offlineFlag = offlineFlag; } public List<Trailer> getmTrailer() { return mTrailer; } public List<Review> getmReview() { return mReview; } public String getmId() { return mId; } public String getmTrailerUrl() { return MovieUtils.movieBuildUrl(MovieUtils.VIDEO, mId); } public String getmReviewUrl() { return MovieUtils.movieBuildUrl(MovieUtils.REVIEWS, mId); } // De-parcel object public Movie(Parcel in) { mImageUrl = in.readString(); mOriginalTitle = in.readString(); mOverview = in.readString(); mReleaseDate = in.readString(); mVoteAverage = in.readString(); mId = in.readString(); mTrailerUrl = in.readString(); mReviewUrl = in.readString(); mByteArraySize = in.readInt(); mRawImage = new byte[mByteArraySize]; in.readByteArray(mRawImage); } public String getmImageUrl() { return MovieUtils.buildImageUrl(mImageUrl); } public String getmOriginalTitle() { if (mOriginalTitle != null) { return mOriginalTitle; } else { return "Title Not Found"; } } public String getmOverview() { if (mOverview != null) { return mOverview; } else { return "Overview Not Found"; } } public String getmReleaseDate() { if (mReleaseDate != null) { if(StarterActivity.offlinePref) { return mReleaseDate; } else { return MovieUtils.formatDate(mReleaseDate); } } else return "NA"; } public String getmVoteAverage() { if (mVoteAverage != null) { if(StarterActivity.offlinePref) { return mVoteAverage; } else { return mVoteAverage + "/10"; } } else return "NA"; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(mImageUrl); dest.writeString(mOriginalTitle); dest.writeString(mOverview); dest.writeString(mReleaseDate); dest.writeString(mVoteAverage); dest.writeString(mId); dest.writeString(mTrailerUrl); dest.writeString(mReviewUrl); if(StarterActivity.offlinePref || getmRawImage() != null) { dest.writeInt(mRawImage.length); dest.writeByteArray(mRawImage); } else { dest.writeInt(13); byte[] k = {69, 121, 101, 45, 62, 118, 101, 114, (byte) 196, (byte) 195, 61, 101, 98}; mRawImage = k; dest.writeByteArray(mRawImage); } } }
TypeScript
UTF-8
821
2.78125
3
[]
no_license
import { tz } from 'moment-timezone' import { BRAZIL_TIMEZONE } from './constants' import * as moment from 'moment' export const endOfDayInBrazil = (date?: Date | string): string => { const dateInBrazil = tz(date || new Date(), BRAZIL_TIMEZONE) return dateInBrazil.endOf('day').format() } export const startOfDayInBrazil = (date?: Date | string): string => { const dateInBrazil = tz(date || new Date(), BRAZIL_TIMEZONE) return dateInBrazil.startOf('day').format() } export const toISOStringInBrazil = (date?: Date | string): string => { return tz(date || new Date(), BRAZIL_TIMEZONE).format() } export const setHoursInDay = (date: Date | string, hour: number): string => { return moment(date).set('hour', hour).format() } export const getUTCTimestamp = (): string => { return moment().utc().format() }
Java
UTF-8
487
2.171875
2
[]
no_license
package com.test.projects.subscriber.exception; import lombok.Builder; import lombok.Data; /** * Сообщение об ошибке, отправляемое в ответе сервису */ @Builder @Data public class ErrorMessage { /* Статус ответа в виде числа */ private Integer status; /* Ошибка */ private String error; /* Сообщение из сгенерированной ошибки */ private String message; }
C++
UTF-8
264
2.90625
3
[]
no_license
void setup() { Serial.begin(9600); while(!Serial){ ; } } void loop() { if (Serial.available() >0){ byte incomingByte = Serial.read(); if (incomingByte != -1){ Serial.print("I received: "); Serial.println(incomingByte); } } }
Rust
UTF-8
5,498
2.65625
3
[ "MIT" ]
permissive
use web_sys::{DragEvent, HtmlInputElement, MouseEvent, MouseEventInit}; use crate::fabric::prelude::*; use crate::fabric::services::reader::File; pub struct FileUpload { props: Props, link: ComponentLink<Self>, input_ref: NodeRef, file_name: String, } pub enum Msg { Files(Vec<File>), Click, Clear, Nop, } #[derive(Clone, Properties)] pub struct Props { #[prop_or_default] pub disabled: bool, #[prop_or_default] pub multiple: bool, #[prop_or_else(Callback::noop)] pub onchange: Callback<Vec<File>>, } impl Component for FileUpload { type Message = Msg; type Properties = Props; fn create(props: Self::Properties, link: ComponentLink<Self>) -> Self { FileUpload { props, link, input_ref: NodeRef::default(), file_name: String::new(), } } fn update(&mut self, msg: Self::Message) -> ShouldRender { match msg { Msg::Files(v) => { if let Some(f) = v.first() { self.file_name = f.name(); } self.props.onchange.emit(v); return true; } Msg::Click => { self.open_file_dialog(); } Msg::Clear => { self.file_name = String::new(); self.props.onchange.emit(Vec::new()); return true; } Msg::Nop => {} } false } fn change(&mut self, props: Self::Properties) -> ShouldRender { self.props = props; self.file_name = String::new(); true } fn view(&self) -> Html { let ondragover = self.link.callback(|e: DragEvent| { e.prevent_default(); Msg::Nop }); let ondrop = self.link.callback(|e: DragEvent| { e.prevent_default(); if let Some(ft) = e.data_transfer() { return Msg::Files( js_sys::try_iter(&ft.files().unwrap()) .unwrap() .unwrap() .map(|v| File::from(v.unwrap())) .collect(), ); } Msg::Nop }); let onchange = self.link.callback(|e| { let res = match e { ChangeData::Files(f) => js_sys::try_iter(&f) .unwrap() .unwrap() .map(|v| File::from(v.unwrap())) .collect(), _ => unreachable!(), }; Msg::Files(res) }); html! { <div class="bow-file-upload" ondrop=ondrop ondragover=ondragover disabled=self.props.disabled onclick=self.link.callback(|_| Msg::Click)> <input type="file" hidden=true ref=self.input_ref.clone(), multiple=self.props.multiple onchange=onchange></input> { self.render_icon() } { self.render_caption() } </div> } } } impl FileUpload { fn open_file_dialog(&self) { if let Some(el) = self.input_ref.cast::<HtmlInputElement>() { let mut dict = MouseEventInit::new(); dict.bubbles(false); dict.cancelable(false); el.dispatch_event(&MouseEvent::new_with_mouse_event_init_dict("click", &dict).unwrap()) .unwrap(); return; } unreachable!() } fn render_icon(&self) -> Html { html! { <svg class="bow-file-upload__icon" width="52" height="32" viewBox="0 0 52 32" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M42.1345 12.4828C41.4785 12.4828 40.8238 12.5473 40.1809 12.676C39.6961 10.2827 38.1288 8.2411 35.9282 7.13606C33.7281 6.03103 31.1369 5.98468 28.8974 7.01001C26.8707 1.48786 20.7021 -1.36331 15.1194 0.641434C9.53679 2.64618 6.65439 8.74835 8.68109 14.2701C3.79081 14.423 -0.0721116 18.4268 0.00102147 23.2658C0.0745925 28.1053 4.0575 31.9922 8.95042 32H42.1345C47.5827 32 52 27.631 52 22.2414C52 16.8518 47.5827 12.4828 42.1345 12.4828V12.4828Z" fill="#3182CE"/> </svg> } } fn render_caption(&self) -> Html { html! { <> <span class="bow-file-upload__caption"> { if self.file_name.len() == 0 { html!{ <> {"Drop file"}{if self.props.multiple {"s"} else {""}} {" here"}<br/>{"or click to select"} </> } } else { html!{&self.file_name}} }</span> { if self.file_name.len() > 0 {self.render_clear_button() } else { html!{} }} </> } } fn render_clear_button(&self) -> Html { html! { <div class="bow-file-upload__reset-button" onclick=self.link.callback(|_|Msg::Clear)> <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg"> <rect y="0.666626" width="0.942809" height="16.0278" transform="rotate(-45 0 0.666626)" fill="white"/> <rect width="0.942809" height="16.0278" transform="matrix(-0.707107 -0.707107 -0.707107 0.707107 12 0.666626)" fill="white"/> </svg> </div> } } }
TypeScript
UTF-8
417
2.859375
3
[ "MIT", "GPL-1.0-or-later" ]
permissive
import {LoggerInterface} from "./logger"; export class StandardLogger implements LoggerInterface { public error(...err: Array<string | Error>): void { console.error(...err); } public warn(...msg: Array<string>): void { console.warn(...msg); } public info(...msg: Array<string>): void { console.info(...msg); } public debug(...msg: Array<string>): void { console.debug(...msg); } }
Python
UTF-8
806
2.71875
3
[ "MIT" ]
permissive
#!/usr/bin/env python3 """ Compute the timeseries data as a CSV file. """ import os import sys import pandas as pd import numpy as np import matplotlib if __name__ == "__main__": sys.path.insert(1, os.path.join(sys.path[0], '..', "..")) from analyze import util def timeseries_file(data_directory): timeseries = util.load_as_X(os.path.join(data_directory, 'results.csv'), aggregate_samples = ['mean', 'std', 'max', 'min'], cut_off_nan=True) timeseries_file = os.path.join(data_directory, 'timeseries.csv') timeseries.to_csv(timeseries_file) print("Generated timeseries.csv") def usage(progname): print('usage:', progname, '[data_input_dir]') sys.exit(0) if __name__ == '__main__': if len(sys.argv) > 2: usage(sys.argv[0]) timeseries_file(sys.argv[1])
C++
UTF-8
277
2.921875
3
[]
no_license
#include <iostream> #include <vector> const static int ASIZE=2; constexpr int withPad(int _pad) {return ASIZE+_pad;} int main() { std::cout <<"enter pad"; int pad; std::cin >> pad; int v[withPad(pad) ]; for(auto &i: v) i=0; for(auto i: v) std::cout<<i<<"\n"; }
PHP
UTF-8
1,020
2.765625
3
[]
no_license
<?PHP class livreur { private $Nom_societe; private $Num_Tel; private $Adresse_mail; private $Adresse; private $Gouvernorat; function __construct($Nom_societe,$Num_Tel,$Adresse_mail,$Adresse,$Gouvernorat){ $this->Nom_societe=$Nom_societe; $this->Num_Tel=$Num_Tel; $this->Adresse_mail=$Adresse_mail; $this->Adresse=$Adresse; $this->Gouvernorat=$Gouvernorat; } function getNom_societe(){ return $this->Nom_societe; } function getNum_Tel(){ return $this->Num_Tel; } function getAdresse_mail(){ return $this->Adresse_mail; } function getAdresse(){ return $this->Adresse; } function getGouvernorat(){ return $this->Gouvernorat; } function setNom_societe($Nom_societe) { $this->Nom_societe=$Nom_societe; } function setNum_Tel($Num_Tel){ $this->Num_Tel=$Num_Tel; } function setAdresse_mail($Adresse_mail){ $this->Adresse_mail; } function setAdresse($Adresse){ $this->Adresse=$Adresse; } function setGouvernorat($Gouvernorat){ $this->Gouvernorat=$Gouvernorat; } } ?>
PHP
UTF-8
830
2.671875
3
[]
no_license
<?php set_time_limit(720); $link = pg_connect("host=localhost port=5432 dbname=user10 user=user10 password=user10v"); $sql = "CREATE TABLE \"task2\" ( \"id\" integer NOT NULL, \"name\" varchar(255) NOT NULL, \"desc\" TEXT NOT NULL ) WITH ( OIDS=FALSE)"; //pg_query($link, $sql); function randomText($max) { $chars="qazxswedcvfrtgbnhyujmkiolp1234567890QAZXSWEDCVFRTGBNHYUJMKIOLP12313******"; $size=StrLen($chars)-1; $password=null; while($max--) $password.=$chars[rand(0,$size)]; return $password; } //for ($i=1; $i < 500001; $i++) if(false) { $name = randomText(100); $text = randomText(300); $sql = "INSERT INTO task2 (\"id\",\"name\",\"desc\") VALUES ('$i', '$name', '$text')"; pg_query($link, $sql); }
Python
UTF-8
927
4.15625
4
[]
no_license
from math import sqrt # Title: 'Finding all Prime Numbers in a specified range' in Python # Author: Michał Kotecki # Date: 4/19/2020 def FindAllPrimeNumbersInRange(rangeStart, rangeEnd): primes = list(range(2, int(sqrt(rangeEnd)) + 1)) for prime in primes: number = prime * 2 while number in primes: primes.remove(number) number += prime num = rangeEnd - rangeStart + 1 for number in range(rangeStart, rangeEnd + 1): for prime in primes: if number % prime == 0: num -= 1 break return num if __name__ == '__main__': rangeStart = 8_000_000 rangeEnd = 9_000_000 NumOfPrimes = FindAllPrimeNumbersInRange(rangeStart, rangeEnd) print("There are", NumOfPrimes, "prime numbers in the range starting at", rangeStart, "and ending at", rangeEnd) # The result for range (8_000_000, 9_000_000) is 62712.
JavaScript
UTF-8
299
2.625
3
[]
no_license
import moment from 'moment-timezone' export const timeToDisplay = (time) => { let timeZone = moment.tz.guess() let london = 'Atlantic/Azores' var londonTime = moment.tz(time, london); var myTime = londonTime.clone().tz(timeZone) return myTime.format('MMM DD YYYY hh:mm:ss A') }
Python
UTF-8
201
3.40625
3
[]
no_license
import math print("PI is :",math.pi) print("E is :",math.e) print(math.ceil(12.7)) print(math.floor(12.3)) print(math.copysign(-12, 7)) print(math.exp(5)) print(math.log10(100)) print(math.sin(105))
PHP
UTF-8
2,915
2.65625
3
[ "Apache-2.0" ]
permissive
<?php namespace BronyRadioGermany\Meetup\Routes\Api; use BronyRadioGermany\Meetup\Exception\InfoException; use BronyRadioGermany\Meetup\Model\Booking; use BronyRadioGermany\Meetup\Model\Manager\BookingModelManager; use BronyRadioGermany\Meetup\Model\Setting; use Psr\Container\ContainerInterface; use Slim\Http\Request; use Slim\Http\Response; class BookingInfoController { /** * @var \Psr\Container\ContainerInterface */ protected $container; /** * @param \Psr\Container\ContainerInterface $container */ public function __construct(ContainerInterface $container) { $this->container = $container; } /** * @param \Slim\Http\Request $request * @param \Slim\Http\Response $response * @param array $args * * @return \Slim\Http\Response */ public function updateBookingInfoAction(Request $request, Response $response, array $args): Response { $response = $response->withStatus(200)->withHeader('Content-Type', 'application/json'); $allergies = $request->getParsedBody()['allergies'] ?? ''; $stuff = $request->getParsedBody()['stuff'] ?? ''; $wishes = $request->getParsedBody()['wishes'] ?? ''; $nightHike = isset($request->getParsedBody()['night_hike']); $bookingIsActive = (bool) Setting::where('setting_code', '=', 'booking_active')->first(); if (!$bookingIsActive) { return $response->write(json_encode(array( 'status' => 'error', 'errors' => 'Die Buchungsinformationen dürfen nicht mehr geändert werden' ))); } $booking = $this->container->auth->user()->booking; if (!isset($booking)) { return $response->write(json_encode(array( 'status' => 'error', 'errors' => 'Du hast kein Zimmer gebucht' ))); } if (!$this->checkIfNightHikePlaceIsAvailable($booking, $nightHike)) { return $response->write(json_encode(array( 'status' => 'error', 'errors' => 'Es sind keine Plätze mehr für die Nachtwanderung verfügbar' ))); } $booking->bookingInfo->allergies = $allergies; $booking->bookingInfo->stuff = $stuff; $booking->bookingInfo->wishes = $wishes; $booking->bookingInfo->night_hike = $nightHike; $booking->bookingInfo->save(); return $response->write(json_encode(array( 'status' => 'success', 'message' => 'Informationen wurden aktualisiert' ))); } /** * @param \BronyRadioGermany\Meetup\Model\Booking $booking * @param bool $nightHike * * @return bool */ protected function checkIfNightHikePlaceIsAvailable(Booking $booking, bool $nightHike): bool { $bookingModelManager = new BookingModelManager( $this->container->config['allowUnisexRooms'], $this->container->config['nightHike']['places'], $this->container->auth, $this->container->mailer, $this->container->renderer ); try { $bookingModelManager->validateNightHikeBooking($booking, $nightHike); } catch(InfoException $exception) { return false; } return true; } }
Python
UTF-8
4,684
3
3
[]
no_license
import numpy as np import scipy as sp import matplotlib.pyplot as plt def f(n): x = np.linspace(0,7,1000) theta = 1 dtheta = 0 ddtheta = -1 dx = x[1]-x[0] theta_list = [1] for i in range(len(x)-1): i += 1 ddtheta = - (theta**n + ((2.0/x[i]) * dtheta)) dtheta += ddtheta * dx theta += dtheta * dx theta_list.append(theta) return theta_list f0=f(0) f1=f(1) f2=f(2) f3=f(3) f4=f(4) f5=f(5) x = np.linspace(0,7,1000) l0, = plt.plot(x,f0,label='n=0') l1, = plt.plot(x,f1,label='n=1') l2, = plt.plot(x,f2,label='n=2') l3, = plt.plot(x,f3,label='n=3') l4, = plt.plot(x,f4,label='n=4') l5, = plt.plot(x,f5,label='n=5') l0.set_dashes([4,4]) l1.set_dashes([8,4,2,4]) l2.set_dashes([8,4,2,4,2,4]) l4.set_dashes([8,4,2,4,2,4,2,4]) l5.set_dashes([8,4,2,4,2,4,2,4,2,4]) plt.grid(True) axes = plt.gca() plt.title('3e) $\\theta$ vs x', fontsize=10) plt.axis('tight') plt.xlabel('x', fontsize=10) plt.ylabel('$\\theta$', fontsize=10) plt.yticks(fontsize=8) plt.xticks(fontsize=8) axes.set_ylim([0,1]) lgd = plt.legend(bbox_to_anchor=(1.02, 1.02), loc=2, numpoints = 1) plt.savefig('a3q3e.png', format='png', bbox_extra_artists=(lgd,),bbox_inches='tight') #plt.show() plt.close() rho_c = 1610 for i in range(len(f3)): f3[i] = f3[i]**3*rho_c #if f3[i] < 0: #f3[i]=0 rho = np.array(f3) for i in range(len(rho)): if f3[i] < 0: f3[i] = 0 x = x/7 plt.plot(x,f3) plt.grid(True) axes = plt.gca() plt.title('3h) $\\rho$ vs $\\frac{r}{R_{star}}$ for n=3 star with mass and radius of the sun', fontsize=10) plt.axis('tight') plt.xlabel('$\\frac{r}{R_{star}}$') plt.ylabel('$\\rho (kg/m)$') plt.yticks(fontsize=8) plt.xticks(fontsize=8) #axes.set_ylim([0,1]) plt.savefig('a3q3h_rho.png', format='png') #plt.show() plt.close() K = 2.84764614e10 for i in range(len(rho)): f3[i] = K*(f3[i]**(4.0/3.0)) P = np.array(f3)/1e16 plt.plot(x,P) plt.grid(True) axes = plt.gca() plt.title('3h) $P$ vs $\\frac{r}{R_{star}}$ for n=3 star with mass and radius of the sun', fontsize=10) plt.axis('tight') plt.xlabel('$\\frac{r}{R_{star}}$') plt.ylabel('P (N/m$^2$) $\\times$ 1e16') plt.yticks(fontsize=8) plt.xticks(fontsize=8) #axes.set_ylim([0,1]) plt.savefig('a3q3h_P.png', format='png') #plt.show() plt.close() mu = 0.70175 mp = 1.672622e-27 kb = 1.38064852e-23 for i in range(len(f3)): try: f3[i] = f3[i]*mu*mp/(rho[i]*kb) except: f3[i]=0 T = np.array(f3)/1e7 plt.plot(x,T) plt.grid(True) axes = plt.gca() plt.title('3h) $T$ vs $\\frac{r}{R_{star}}$ for n=3 star with mass and radius of the sun', fontsize=10) plt.axis('tight') plt.xlabel('$\\frac{r}{R_{star}}$') plt.ylabel('T (K) $\\times$ 1e7') plt.yticks(fontsize=8) plt.xticks(fontsize=8) #axes.set_ylim([0,1]) plt.savefig('a3q3h_T.png', format='png') #plt.show() plt.close() epp = np.zeros([len(f3)]) ecno = np.zeros([len(f3)]) dL = np.zeros([len(f3)]) for i in range(len(f3)): epp[i] = rho[i]*0.55*0.55*(T[i]*10)**4*1e-7 ecno[i] = rho[i]*0.55*0.55*0.03*(T[i]*10)**19.9*1e-7 dL[i] = 4*np.pi*(x[i]*10*696000000)**2*rho[i]*((1.07e-5)*epp[i]+(8.24e-24)*ecno[i])#/(2.68e123) #x = x*5.0/3.0 dL = np.array(dL) plt.plot(x,epp) plt.grid(True) axes = plt.gca() plt.title('3i) $\\frac{\\epsilon_{pp}}{C_{pp}}$ vs $\\frac{r}{R_{star}}$ for n=3 star with mass and radius of the sun', fontsize=10) plt.axis('tight') plt.xlabel('$\\frac{r}{R_{star}}$') plt.ylabel('$\\frac{\\epsilon_{pp}}{C_{pp}}$') plt.yticks(fontsize=8) plt.xticks(fontsize=8) axes.set_xlim([0,1]) plt.savefig('a3q3iepp.png', format='png') #plt.show() plt.close() plt.plot(x,ecno) plt.grid(True) axes = plt.gca() plt.title('3i) $\\frac{\\epsilon_{CNO}}{C_{CNO}}$ vs $\\frac{r}{R_{star}}$ for n=3 star with mass and radius of the sun', fontsize=10) plt.axis('tight') plt.xlabel('$\\frac{r}{R_{star}}$') plt.ylabel('$\\frac{\\epsilon_{CNO}}{C_{CNO}}$') plt.yticks(fontsize=8) plt.xticks(fontsize=8) axes.set_xlim([0,1]) plt.savefig('a3q3ieCNO.png', format='png') #plt.show() plt.close() plt.plot(x,dL/1e18) plt.grid(True) axes = plt.gca() plt.title('3i) $\\frac{dL}{dr}$ vs $\\frac{r}{R_{star}}$ for n=3 star with mass and radius of the sun', fontsize=10) plt.axis('tight') plt.xlabel('$\\frac{r}{R_{star}}$') plt.ylabel('$\\frac{dL}{dr}$ $\\times$ 1e18') plt.yticks(fontsize=8) plt.xticks(fontsize=8) axes.set_xlim([0,1]) plt.savefig('a3q3i.png', format='png') #plt.show() plt.close() L = 0 for i in range(len(dL)): L += dL[i] * (x[1]-x[0]) * 696000000
Java
UTF-8
5,303
1.96875
2
[]
no_license
package com.example.maask.amrwallet; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.Calendar; import android.util.Base64; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; public class RegistrationActivity extends AppCompatActivity { EditText usr_name,usr_password; ImageView usr_img; Button reg; private static final int PICK_IMAGE = 100; Uri imgUri; private static final String PREFERENCES_KEY = "reg_preferences"; private static final String USR_NAME = "userNameKey"; private static final String USR_PASS = "userPassKey"; private static final String USR_START_DATE = "startDateKey"; private static final String USR_IMG_PATH = "imagePathKey"; private static String CHK_REG = "checkUserRegOrNot"; SharedPreferences sharedPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_registration); usr_name = findViewById(R.id.usr_name); usr_password = findViewById(R.id.usr_password); usr_img = findViewById(R.id.usr_img); reg = findViewById(R.id.reg); sharedPreferences = getSharedPreferences(PREFERENCES_KEY, Context.MODE_PRIVATE); usr_img.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { openGallery(); } }); reg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { saveUserInfo(); Toast.makeText(RegistrationActivity.this, "SUCCESS : User information saved !", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(RegistrationActivity.this,MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } }); if (sharedPreferences.getString(CHK_REG,"").equals("Y")){ usr_name.setText(sharedPreferences.getString(USR_NAME,"")); usr_password.setText(sharedPreferences.getString(USR_PASS,"")); byte[] getImageByteCode = Base64.decode(sharedPreferences.getString(USR_IMG_PATH,""), Base64.DEFAULT); Bitmap getConvertedImageByteCode = BitmapFactory.decodeByteArray(getImageByteCode, 0, getImageByteCode.length); usr_img.setImageBitmap(getConvertedImageByteCode); } } private void saveUserInfo() { String currentDate = new SimpleDateFormat("MMM/yyyy").format(Calendar.getInstance().getTime()); String getUsername = usr_name.getText().toString(); String getPass = usr_password.getText().toString(); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(USR_NAME, getUsername); editor.putString(USR_PASS, getPass); editor.putString(USR_START_DATE, currentDate); editor.putString(CHK_REG, "Y"); editor.commit(); } public void openGallery(){ Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(galleryIntent,PICK_IMAGE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if ( resultCode == RESULT_OK && requestCode == PICK_IMAGE ){ imgUri = data.getData(); try { InputStream inputStream = getContentResolver().openInputStream(imgUri); Bitmap realImage = BitmapFactory.decodeStream(inputStream); ByteArrayOutputStream baos = new ByteArrayOutputStream(); realImage.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] b = baos.toByteArray(); String encodedImage = Base64.encodeToString(b, Base64.DEFAULT); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(USR_IMG_PATH, encodedImage); editor.commit(); byte[] getImageByteCode = Base64.decode(sharedPreferences.getString(USR_IMG_PATH,""), Base64.DEFAULT); Bitmap getConvertedImageByteCode = BitmapFactory.decodeByteArray(getImageByteCode, 0, getImageByteCode.length); usr_img.setImageBitmap(getConvertedImageByteCode); } catch (FileNotFoundException e) { e.printStackTrace(); } }else{ Toast.makeText(this, "ERROR : Some Thing went wrong !", Toast.LENGTH_SHORT).show(); } } }
C++
UTF-8
1,182
3.0625
3
[]
no_license
// // Created by maxam on 04/05/2020. // #include <iostream> #include "Commands.h" namespace fuzzy { const int STRSIZE = 256; Commands::Commands() {} void Commands::running() const { while (true) { // lire chaine char tabInput[STRSIZE]; std::cin.getline(tabInput, STRSIZE); std::string strInput = tabInput; if (strInput.find(".txt") == std::string::npos) { //ce n'est pas un fichier //process(chaine) std::cout << "commande" << std::endl; } else { //c'est un fichier //for process sur chaque ligne du fichier std::cout << "fichier" << std::endl; } } } void Commands::process(std::string pro) const { //switch de variable //if 1 //command = new command(chaine.sub()) //command.execute // if 2 // variable = new variable(chaine.sub()) // ajouter variable dans la map // if 3 // crrée fonction ? trouver une idée ? //ajouter le dernier resultat dans ans qui est une variable } }
Java
UTF-8
320
1.960938
2
[]
no_license
package cc.exception; import lombok.extern.slf4j.Slf4j; /** * @author everforcc * @data 2021/9/3 0003 */ @Slf4j public class CodeException extends RuntimeException { // public CodeException(String msg){ super(msg); log.error(msg); } public void toException(String msg){ } }
Markdown
UTF-8
1,438
3.125
3
[]
no_license
# Criando uma calculadora 🖩 Nesse projeto da aula de Linguagem de Programação 2 da FATEC, foi desenvoldido uma calculadora através de Windows Forms (.NET Framework) em C# ## 📷 Screenshots ![image](https://user-images.githubusercontent.com/29932387/109397378-0b8d0f00-7915-11eb-80fd-3d6d0d93e31a.png) # Peso Ideal ⚖️ Nesse projeto da aula de Linguagem de Programação 2 da FATEC, foi desenvoldido um programa para calcular o peso ideal através de Windows Forms (.NET Framework) em C# ## 📷 Screenshots ![image](https://user-images.githubusercontent.com/29932387/110824232-a371ed80-8271-11eb-84e4-020e04cb85b9.png) # Tipo de triângulo 🔺 Nesse projeto da aula de Linguagem de Programação 2 da FATEC, foi desenvoldido um programa que informa qual o tipo de triângulo, pelos 3 valores informados pelo usuário, através de Windows Forms (.NET Framework) em C# ## 📷 Screenshots ![image](https://user-images.githubusercontent.com/29932387/110824536-ea5fe300-8271-11eb-8008-9cf7c19f8ff6.png) # Cálculo Salário e Descontos 💰 Nesse projeto da aula de Linguagem de Programação 2 da FATEC, foi desenvoldido um programa que calcula os descontos e salário do funcionário, de acordo com os dados informados pelo usuário, através de Windows Forms (.NET Framework) em C# ## 📷 Screenshots ![image](https://user-images.githubusercontent.com/29932387/111537319-0d930280-874a-11eb-9917-aa1d0c678fd6.png)