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
8,869
2.234375
2
[]
no_license
package VPI.InsightClasses; import VPI.MyCredentials; import VPI.PDClasses.*; import VPI.PDClasses.Contacts.util.ContactDetail; import VPI.PDClasses.Contacts.PDContactReceived; import VPI.PDClasses.Contacts.PDContactSend; import VPI.PDClasses.Organisations.PDOrganisationReceived; import VPI.PDClasses.Organisations.PDOrganisationSend; import org.springframework.web.client.RestTemplate; import java.util.*; /** * Created by sabu on 15/04/2016. */ public class InsightSynchroniser { private PDService PDS; private InsightService IS; public Organisations organisations; public Contacts contacts; public InsightSynchroniser(String PDserver, String Vserver) { RestTemplate restTemplate = new RestTemplate(); MyCredentials creds = new MyCredentials(); this.PDS = new PDService(PDserver, creds.getApiKey()); this.IS = new InsightService( restTemplate, Vserver, creds.getUserName(), creds.getPass() ); this.organisations = new Organisations(); this.contacts = new Contacts(); } public List<Long> importToPipedrive() { List<Long> org_ids = getProjectsForZUK(); List<Long> orgs_pushed = importOrganisations(org_ids); System.out.println("Posted " + orgs_pushed.size() + " organisations to Pipedrive"); //importContacts(); clear(); return orgs_pushed; } public List<Long> getProjectsForZUK() { List<VProject> projs = IS.getProjectsForZUK().getBody().getItems(); List<Long> org_ids_to_get = new ArrayList<>(); for(VProject p : projs) { if (p.getOrganisation() != null) { if(p.getOrganisation().getName() != null){ org_ids_to_get.add(p.getOrganisation().getId()); } else{ System.out.println("Could not get Name of organisation for project: " + p.getName()); } } else { System.out.println("Could not get organisation for project: " + p.getName()); } } Set<Long> no_dups = new HashSet<>(org_ids_to_get); org_ids_to_get.clear(); org_ids_to_get.addAll(no_dups); return org_ids_to_get; } public List<Long> importOrganisations(List<Long> org_ids) { getAllOrganisations(org_ids); compareOrganisations(); return pushOrganisations(); } private List<Long> importContacts() { addContactsForNewOrganisationsToPostList(); resolveContactsForMatchedOrganisations(); //return pushContacts(); return new ArrayList<>(); } private void resolveContactsForMatchedOrganisations() { for(VOrganisation v : organisations.matchedList) { List<VContact> vC = Arrays.asList(IS.getContactsForOrganisation(v.getId()).getBody()); List<PDContactReceived> pC = PDS.getContactsForOrganisation(v.getPd_id()).getBody().getData(); compareContacts(vC, pC); } for(PDOrganisationSend p : organisations.putList) { List<VContact> vC = Arrays.asList(IS.getContactsForOrganisation(p.getV_id()).getBody()); List<PDContactReceived> pC = PDS.getContactsForOrganisation(p.getId()).getBody().getData(); compareContacts(vC, pC); } } private void addContactsForNewOrganisationsToPostList() { for(PDOrganisationSend p : organisations.postList) { List<VContact> contactsForOrg = Arrays.asList(IS.getContactsForOrganisation(p.getV_id()).getBody()); for(VContact c : contactsForOrg) { contacts.postList.add(new PDContactSend(c)); } } } private void getAllOrganisations(List<Long> org_ids) { this.organisations.vOrganisations = IS.getOrganisationList(org_ids); this.organisations.pdOrganisations = PDS.getAllOrganisations().getBody().getData(); } public void compareOrganisations() { for(VOrganisation v : organisations.vOrganisations){ Boolean matched = false; Boolean modified = false; PDOrganisationReceived temp = null; for(PDOrganisationReceived p : organisations.pdOrganisations) { if (v.getName() != null && p.getName() != null) { if (v.getName().equals(p.getName())) { matched = true; v.setPd_id(p.getId()); //Resolve attributes of organisation //address if (!v.getFormattedAddress().equals(p.getAddress())) { modified = true; p.setAddress(v.getFormattedAddress()); p.setV_id(v.getId()); temp = p; } //further fields to compare //... } } } if(!matched && v.getName() != null){ organisations.postList.add(new PDOrganisationSend(v)); } if(modified){ organisations.putList.add(new PDOrganisationSend(temp)); } if(matched && !modified) { organisations.matchedList.add(v); } } } public void compareContacts(List<VContact> vContacts, List<PDContactReceived> pdContacts) { for(VContact v : vContacts) { Boolean matched = false; Boolean modified = false; PDContactReceived temp = null; for(PDContactReceived p : pdContacts) { if(v.getName().equals(p.getName())) { matched = true; //resolve emailDetail and phoneDetail lists of contact modified = resolveContactDetails(v,p); if(modified) { temp = p; } } } if(!matched) { contacts.postList.add(new PDContactSend(v)); } if(modified) { contacts.putList.add(new PDContactSend(temp)); } } } public Boolean resolveContactDetails(VContact v, PDContactReceived p){ Boolean modifiedPhone = false; Boolean somethingToStopCOdeDupWarning = false; if (v.getPhone() != null) { Boolean matchedPhone = false; for (ContactDetail pph : p.getPhone()) { if (v.getPhone().equals(pph.getValue())) { matchedPhone = true; if (!pph.getPrimary()) { somethingToStopCOdeDupWarning = true; pph.setPrimary(true); modifiedPhone = true; } } else { pph.setPrimary(false); } } if (!matchedPhone) { p.getPhone().add(new ContactDetail(v.getPhone(), true)); modifiedPhone = true; } } Boolean modifiedEmail = false; if (v.getEmail() != null) { Boolean matchedEmail = false; for (ContactDetail pe : p.getEmail()) { if (v.getEmail().equals(pe.getValue())) { matchedEmail = true; if (!pe.getPrimary()) { pe.setPrimary(true); somethingToStopCOdeDupWarning = false; modifiedEmail = true; } } else { pe.setPrimary(false); } } if (!matchedEmail) { p.getEmail().add(new ContactDetail(v.getEmail(), true)); modifiedEmail = true; } } return modifiedEmail || modifiedPhone; } private List<Long> pushOrganisations() { List<Long> idsPosted = PDS.postOrganisationList(organisations.postList); List<Long> idsPutted = PDS.putOrganisationList(organisations.putList); List<Long> idsPushed = new ArrayList<>(idsPosted); idsPushed.addAll(idsPutted); return idsPushed; } // private List<Long> pushContacts() { // //List<Long> idsPosted = PDS.postContactList(contacts.postList); // List<Long> idsPutted = PDS.putContactList(contacts.putList); // // List<Long> idsPushed = new ArrayList<>(idsPosted); // idsPushed.addAll(idsPutted); // return idsPushed; // } public void clear(){ this.organisations = new Organisations(); this.contacts = new Contacts(); } public PDService getPDS() { return this.PDS; } }
Shell
UTF-8
1,059
3.34375
3
[]
no_license
#!/bin/bash # Get your app version number VERSION="0.0.1" # make autorun script exec chmod +x ./appfolder/setup.sh # Usage: ./makeself.sh [params] archive_dir file_name label [startup_script] [args] # --gzip : Compress using gzip (default if detected) # --bzip2 : Compress using bzip2 instead of gzip # --notemp : The archive will create archive_dir in the # current directory and uncompress in ./archive_dir # --copy : Upon extraction, the archive will first copy itself to # a temporary directory # --header file : Specify location of the header script # --follow : Follow the symlinks in the archive # --nox11 : Disable automatic spawn of a xterm # --nowait : Do not wait for user input after executing embedded # program from an xterm ./makeself.sh \ --gzip --nox11 --follow --nowait \ ./appfolder \ your_cool_app-$VERSION.sh \ "Installing your cool App v$VERSION Beta" \ ./setup.sh
JavaScript
UTF-8
568
3.59375
4
[]
no_license
// Promise 的目标:增强在使用JavaScript语言进行异步编程的编程体验 // 1.执行流程问题 // setTimeout(() => console.log('A'), 0) // setTimeout(() => console.log('B'), 1000) // Promise.resolve().then(() => { // setTimeout(() => console.log('C'), 0) // setTimeout(() => console.log('D'), 1000) // console.log('E') // Promise.resolve().then(() => console.log('F')) // }).then(() => console.log('G')) // setTimeout(() => console.log('H'), 0) // setTimeout(() => console.log('I'), 1000) // ----------------------------------------- // 2.Promise.all()
Java
UTF-8
280
1.78125
2
[]
no_license
package com.xiecj.cloud.auth.service; import com.xiecj.cloud.auth.bean.ClientInfo; import java.util.List; public interface ClientService { public ClientInfo apply(String clientId, String secret); public List<String> getAllowedClient(String serviceId, String secret); }
Python
UTF-8
5,757
3.546875
4
[]
no_license
""" The player gets to search for a specific keyword in a chosen language (Swedish/English) and guess whether the the 1000 most recent tweets associated with that keyword has a positive or negative sentiment. If the player guess right, the active Pokemon gets rewarded an attack bonus. If the guess is wrong, the pokemon gets punished and looses attack strength. """ from twitter_search import get_tweets import textwrap import nltk from nltk.corpus import stopwords #nltk.download("stopwords") #nltk.download('punkt') #nltk.download('vader_lexicon') from nltk.sentiment.vader import SentimentIntensityAnalyzer as SentimentIntensityAnalyzerEnglish from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer as SentimentIntensityAnalyzerSwedish import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties def wrap_text(text, width): new_text = "\n".join(textwrap.wrap(text, width)) return new_text def sentiment_analysis(keyword, language, file_name='', live=False): """ Perform sentiment analysis on Twitter data. Visualize the result as a bar graph and print the most positive and the most negative tweet on screen. If the negative sentiment is greater than the positive, return 'negative'. If the positive sentiment is greater than the negative return 'positive'. If the sentiment is equally positive and negative return 'neutral'. If something went wrong and it wasn't possible to retrieve tweets return None. """ tweets = get_tweets(keyword=keyword, language=language, load_from_file=False, live=live, file_name=file_name, file_path='demo-tweets') # TODO FEEDBACK SPRINT 2 - HANDLE TWEET SEARCH THAT RESULT IN NO TWEETS if tweets is None: return 'connection_error' if len(tweets) < 2: return 'too_few_results' tweet_blob = "\n\n".join(tweets) most_positive_tweet, most_negative_tweet = get_tweets_with_highest_sentiment_score(tweets, language) if len(most_positive_tweet) < 1 or len(most_negative_tweet) < 1: # Ugly fix - handle if all tweets have a compound score of 0. So not really too few results, # but due to time limitations - this will have to do. Future improvement - if all tweets have a compound # score of 0 - display the bar graph with one selected tweet and print - "all tweets are neutral". return 'too_few_results' sentiment_score = 0 if language == "english": sentiment_score = SentimentIntensityAnalyzerEnglish().polarity_scores(tweet_blob) """ Run to demo how the sentiment is calculated """ # sent = {'neg': 0, 'neu': 0, 'pos': 0, 'compound_pos': 0, 'compound_neg': 0} # number_of_tweets = 0 # for idx, tweet in enumerate(tweets): # sentiment_score = SentimentIntensityAnalyzerEnglish().polarity_scores(tweet) # print("\n", idx, tweet, str(sentiment_score)) # num += 1 # #print(sentiment_score) # sent['neg'] += sentiment_score['neg'] # sent['neu'] += sentiment_score['neu'] # sent['pos'] += sentiment_score['pos'] # if sentiment_score['compound'] > 0: # sent['compound_pos'] += sentiment_score['compound'] # elif sentiment_score['compound'] < 0: # sent['compound_neg'] += sentiment_score['compound'] # print("----") # print(sent) # print(number_of_tweets) elif language == "swedish": sentiment_score = SentimentIntensityAnalyzerSwedish().polarity_scores(tweet_blob) """ Visualize the result as a bar graph """ negative_score = sentiment_score['neg'] positive_score = sentiment_score['pos'] score = [negative_score, positive_score] sentiment = ["Negativt", "Positivt"] plot1 = plt.subplot(211) plot1.set_xlabel("Sentiment") plot1.bar(sentiment, score, color=((0.8, 0.3, 0.3, 0.8), (0.3, 0.8, 0.3, 0.8))) plot1.set_title(f"Är folk på Twitter positivt eller negativt inställda till {keyword}?") plot2 = plt.subplot(212) plot2.axis('off') plot2.set_xlim(0, 1) plot2.set_ylim(0, 10) font = FontProperties() font.set_size('small') plot2.text(0, 6, f"Negativaste tweet:\n{wrap_text(most_negative_tweet, 150)}", fontproperties=font) plot2.text(0, 0, f"Positivaste tweet:\n{wrap_text(most_positive_tweet, 150)}", fontproperties=font) plt.show() if positive_score > negative_score: return "positivt" elif positive_score < negative_score: return "negativt" else: return "neutralt" def get_tweets_with_highest_sentiment_score(tweets, language): """ Return the tweet with the highest positive sentiment score and the tweet with lowest negative score """ most_pos = {'tweet': "", 'compound_score': 0} most_neg = {'tweet': "", 'compound_score': 0} sia = "" if language == "english": sia = SentimentIntensityAnalyzerEnglish() elif language == "swedish": sia = SentimentIntensityAnalyzerSwedish() for idx, tweet in enumerate(tweets): sentiment_score = sia.polarity_scores(tweet) #print("\n", idx, tweet, str(sentiment_score)) if sentiment_score['compound'] > most_pos['compound_score']: most_pos['compound_score'] = sentiment_score['compound'] most_pos['tweet'] = tweet if sentiment_score['compound'] < most_neg['compound_score']: most_neg['compound_score'] = sentiment_score['compound'] most_neg['tweet'] = tweet return most_pos['tweet'], most_neg['tweet'] if __name__ == '__main__': sentiment_analysis(keyword="covid", language="english", file_name='demo_tweets_english_covid.p', live=False)
Java
UTF-8
805
2.140625
2
[]
no_license
package com.example.demo.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.example.demo.model.User; import com.example.demo.repository.UMapper; @Service public class UService { @Autowired UMapper mapper; //select1件 public User getUserOne(String id) { return mapper.findOne(id); } //select全件 public List<User> getList() { return mapper.find(); } //insert public void insertOne(User u) { mapper.insertOne(u); } //update public void updateOne(String id, String name, int age) { mapper.updateOne(id, name, age); } //delete public void deleteOne(User u) { mapper.deleteOne(u); } }
PHP
UTF-8
3,036
2.765625
3
[ "MIT" ]
permissive
<?php namespace Propel\Generator\Builder\Om\Component\Object; use Propel\Generator\Builder\Om\Component\BuildComponent; use Propel\Generator\Builder\Om\Component\NamingTrait; use Propel\Generator\Model\Field; /** * Adds all setter methods for all entity fields. Excludes fields marked as implementationDetail. * * @author Marc J. Schmidt <marc@marcjschmidt.de> */ class PropertySetterMethods extends BuildComponent { use NamingTrait; public function process() { foreach ($this->getEntity()->getFields() as $field) { if ($field->isImplementationDetail()) { // it's a implementation detail, we don't need to expose it to the domain model. continue; } if ($field->isSkipCodeGeneration()) { continue; } $this->addFieldSetter($field); } } /** * Adds the setter methods for the field. * * @param Field $field */ protected function addFieldSetter(Field $field) { $varName = $field->getName(); $visibility = $field->getAccessorVisibility(); $className = $this->getObjectClassName(); $varType = $field->getPhpType(); $body = ''; if ($field->isTemporalType()) { $dateTimeClass = $this->getBuilder()->getBuildProperty('dateTimeClass'); if (!$dateTimeClass) { $dateTimeClass = '\DateTime'; } $varType = 'integer|' . $dateTimeClass; $body = "\$$varName = \\Propel\\Runtime\\Util\\PropelDateTime::newInstance(\$$varName, null, '$dateTimeClass');"; } elseif ($field->isFloatingPointNumber()) { $body = " \$$varName = (double)\$$varName; "; } elseif ($field->isBooleanType()) { $body = " if (\$$varName !== null) { if (is_string(\$$varName)) { \$$varName = in_array(strtolower(\$$varName), array('false', 'off', '-', 'no', 'n', '0', '')) ? false : true; } else { \$$varName = (boolean) \$$varName; } } "; } elseif ($field->isEnumType()) { $constName = strtoupper($varName . '_types'); $body = " if (\$$varName !== null) { if (!in_array(\$$varName, static::$constName, true)) { throw new \\InvalidArgumentException(sprintf('Value \"%s\" is not accepted in this enumerated column', \$$varName)); } } "; } $body .= " \$this->$varName = \$$varName; "; $body .= " return \$this; "; $this->getDefinition()->addUseStatement('Propel\Runtime\Exception\PropelException'); $methodName = 'set' . $field->getMethodName(); $method = $this->addMethod($methodName, $visibility) ->setType($className . '|$this') ->setDescription("Sets the value of $varName.") ->setBody($body); if ($field->isNotNull()) { $method->addSimpleParameter($varName, $varType); } else { $method->addSimpleParameter($varName, $varType, null); } } }
Java
UTF-8
1,252
2.453125
2
[ "MIT" ]
permissive
package web.controller.member; import entity.Member; import service.AddressService; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * 会员:设置默认地址的操作 */ @WebServlet("/member/address/default") public class AddressDefaultServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // String id = request.getParameter("id"); Member mbr = (Member)request.getSession().getAttribute("curr_mbr"); //业务逻辑处理 AddressService service = new AddressService(); service.updateDefault(mbr.getId(), Integer.parseInt(id)); // response.sendRedirect(request.getContextPath() + "/member/address/list"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
Python
UTF-8
1,889
2.96875
3
[]
no_license
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression import statsmodels.api as sm from sklearn.metrics import mean_squared_error import mlxtend from mlxtend.feature_selection import SequentialFeatureSelector as sfs data = pd.read_csv("data.csv") c model = sfs(LinearRegression(),1,forward = False ,scoring ='r2' ).fit(np.array(x_train),y_train) model.k_features_idx SequentialFeatureSelector data = data.iloc[ :,[0,2,3,1]] # to rearrange the coloumns ####################################################################################################################### #Metrics for Regression. #R2 , MAPE, R , MSE , MAE #Metric for Classification. #accrucy , pression , recall , f1 score, sensitivity , specficity , Area under the curve. ####################################################################################################################### #UNDER FIT and OVER FIT #if RMSE of Training set is high than Test set ------- Under fit # if RMSE of test set is lower than the Train set ------- over fit #Different types of models or methods to select different features #exuastive search #forward search - #check p value and adjusted R and consider back #backward search #here we are checking with LOG and without LOG # so we have to check the RMSE for both the models and select the best. reg_model = sm.OLS(np.log(y_train), x_train).fit() reg_model = sm.OLS(y_train, x_train).fit() print(reg_model.summary()) y_predict = reg_model.predict(x_test) np.sqrt(mean_squared_error(y_test,np.exp(y_predict))) np.sqrt(mean_squared_error(y_test,y_predict)) #since the rmse value with out LOG is quite low we consider the model without log. #sorting the data frame according to the income. data.sort_values(by = "income",inplace = True) data
Markdown
UTF-8
2,909
3.140625
3
[]
no_license
# Market-Segmentation---Clustering # Introduction CRISA wanted to segment the market based on two key sets of variables more directly related to the purchase process and to brand loyalty: 1. Purchase behavior (volume, frequency, susceptibility to discounts, and brand loyalty) 2. Basis of purchase (price, selling proposition) 3. Both Doing so would allow CRISA to gain information about what demographic attributes are associated with different purchase behaviors and degrees of brand loyalty, and more effectively deploy promotion budgets. The goal is to do an effective market segmentation that would enable CRISA’s clients to design more cost-effective promotions targeted at appropriate segments. # Data Data file – Assgt3_BathSoap_Data.xls | Each row contains the data for one household. Two additional datasets were used in the derivation of the summary data. The Durables sheet in the data file contains information used to calculate the affluence index. Each row corresponds to a household, and each column represents a durable consumer good. A 1 in a column indicates that the durable is possessed by the household; a 0 indicates that it is not possessed. This value is multiplied by the weight assigned to the durable item. The sum of all the weighted values of the durables possessed gives the affluence index. # Data Preprocessing 1. Appropriate data type conversion according to business sense 2. Removal of correlated variables 3. Feature Engineering # Models 1. K-means - Parameters used: k and nstart 2. Agglomerate Hierarchical Algorithm(agnes) - Dissimilarity parameters used: Euclidean and Pearson | Linkage parameters used: Average, Single, Complete and Ward 3. DBScan algorithm - Parameters used: eps(size of neighbourhood) and minpts(core points) # Evaluation metrics 1. For K-means, Accuracy was compared and optimum number of clusters were calculated by - elbow method, silhouette method, DB index and cluster size trade-off 2. For agnes, same as above 3. For DbScan - Accuracy was compared and KNN distplot was used to calculate optimum number of clusters. # Conclusion 1. Clusters obtained from K-means and Aegnes were similar. However, the clusters obtained from DBScan were not reliable as it was sensitive to clustering parameters. 2. Accuracy was highest for K-means when both the sets of variables (Purchase behaviour and Basis of purchase) were used. 3. We also confirmed the interpretations of our clusters by building a decision tree on our best segmentation and k-means algorithm. This was because the important variables which came out of decision trees were either the same or having similar correlation as what we observed in the line graphs in k-means sections. However, decision trees cannot distinguish between correlated variables and they can have equally higher importance which is not the case usually when we make the clusters using business acumen.
JavaScript
UTF-8
1,985
2.578125
3
[]
no_license
function camelize(str) { const tokens = str.split('-'); for (let i = 1; i < tokens.length; i++) { tokens[i] = tokens[i][0].toUpperCase() + tokens[i].substr(1); } return tokens.join(''); } function changeActiveBtn(elemId) { $(`#${elemId}`).addClass('active').siblings().removeClass('active'); } function onBtnClick(evt) { const elemId = evt.currentTarget.id; const token0 = elemId.substr(elemId.indexOf('-') + 1); const token1 = token0.substr(0, token0.lastIndexOf('-')); const token2 = parseInt(token0.substr(token0.lastIndexOf('-') + 1)); chrome.storage.sync.set({ [`hackerRankEditorSettings_${camelize(token1)}`]: token2 }); changeActiveBtn(elemId); } [ 'group-editor-mode-0', 'group-editor-mode-1', 'group-editor-mode-2', 'group-editor-theme-0', 'group-editor-theme-1', 'group-tab-spaces-0', 'group-tab-spaces-1', 'group-tab-spaces-2', 'group-intellisense-0', 'group-intellisense-1' ].forEach(elemId => { document.getElementById(elemId).addEventListener('click', onBtnClick); }); document.onload = function() { chrome.storage.sync.get([ 'hackerRankEditorSettings_editorMode', 'hackerRankEditorSettings_editorTheme', 'hackerRankEditorSettings_tabSpaces', 'hackerRankEditorSettings_intellisense' ], function(items) { if (typeof items.hackerRankEditorSettings_editorMode === 'number') { changeActiveBtn(`group-editor-mode-${items.hackerRankEditorSettings_editorMode}`); } if (typeof items.hackerRankEditorSettings_editorTheme === 'number') { changeActiveBtn(`group-editor-theme-${items.hackerRankEditorSettings_editorTheme}`); } if (typeof items.hackerRankEditorSettings_tabSpaces === 'number') { changeActiveBtn(`group-tab-spaces-${items.hackerRankEditorSettings_tabSpaces}`); } if (typeof items.hackerRankEditorSettings_intellisense === 'number') { changeActiveBtn(`group-intellisense-${items.hackerRankEditorSettings_intellisense}`); } }); }
Markdown
UTF-8
799
2.96875
3
[]
no_license
# Disneyland with No Children ## by Nick Bostrom, Scott Alexander and Daniel Speyer But even after we have thrown away science, art, love, and philosophy, there’s still one thing left to lose. One final sacrifice runaway competitive pressure might demand of us: being anyone at all. To quote Nick Bostrom: > We could imagine, as an extreme case, a technologically highly advanced society, containing many complex structures, some of them far more intricate and intelligent than anything that exists on the planet today – a society which nevertheless lacks any type of being that is conscious or whose welfare has moral significance. In a sense, this would be an uninhabited society. It would be a society of economic miracles and technological awesomeness, with nobody there to benefit. A Disneyland with no children.
C++
UTF-8
1,063
3.96875
4
[]
no_license
//union and intersection of the array #include<iostream> using namespace std ; void unionarr(int arr1[],int n, int arr2[],int m) {int i=0,j=0; cout<<"\nunion of arrays are "; while(i!=n&&j!=m) { if(arr1[i]<arr2[j]) { cout<<arr1[i]<<" "; i++; } else if(arr1[i]>arr2[j]) { cout<<arr2[j]<<" "; j++; } else {cout<<arr1[i]<<" "; i++; j++; } } while(j<m){ cout<<arr2[j]<<" ";j++; } while(i<n){ cout<<arr1[i]<<" ";i++; } } void intersectionarr(int arr1[],int n, int arr2[],int m) { cout<<"intersection of arrays are "; int i=0,j=0; while(i!=n&&j!=m) { if(arr1[i]<arr2[j]) { i++; } else if(arr1[i]>arr2[j]) { j++; } else {cout<<" "<<arr1[i]; i++; j++; } } } int main() { int arr1[]={1,3,4,5,7}; int arr2[]={2,3,5,6}; int n = sizeof(arr1) / sizeof(arr1[0]); int m = sizeof(arr2) / sizeof(arr2[0]); intersectionarr(arr1,n,arr2,m); unionarr(arr1,n,arr2,m); return 0; }
Java
UTF-8
3,236
2.140625
2
[ "Apache-2.0" ]
permissive
package tech.huqi.quicknote.ui.activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.SearchView; import android.support.v7.widget.RecyclerView; import android.view.Menu; import android.view.MenuItem; import android.view.View; import java.util.List; import tech.huqi.quicknote.R; import tech.huqi.quicknote.adapter.MainPageAdapter; import tech.huqi.quicknote.db.NoteDatabaseHelper; import tech.huqi.quicknote.entity.Note; /** * Created by hzhuqi on 2019/4/22 */ public class SearchActivity extends BaseActivity { private RecyclerView mRvSearchResult; private View mNoContentView; private SearchView mSearchView; protected MainPageAdapter mAdapter; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle(R.string.title_search); initView(); } private void initView() { mRvSearchResult = findViewById(R.id.rv_search_items_result); mRvSearchResult.setLayoutManager(new LinearLayoutManager(this)); mNoContentView = findViewById(R.id.no_content_view); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_search_activity, menu); initSearchView(menu); return true; } private void initSearchView(Menu menu) { mSearchView = (SearchView) menu.findItem(R.id.menu_search_view).getActionView(); mSearchView.setFocusable(true); mSearchView.setIconified(false); mSearchView.requestFocusFromTouch(); mSearchView.setOnQueryTextListener(new android.support.v7.widget.SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { searchAndShowResult(query); return true; } @Override public boolean onQueryTextChange(String pattern) { return false; } }); } private void searchAndShowResult(String query) { List<Note> notes = NoteDatabaseHelper.getInstance().getNotesByPattern(query); if (notes == null || notes.size() == 0) { mRvSearchResult.setVisibility(View.INVISIBLE); mNoContentView.setVisibility(View.VISIBLE); } else { mNoContentView.setVisibility(View.INVISIBLE); mRvSearchResult.setVisibility(View.VISIBLE); mAdapter = new MainPageAdapter(this, notes); mAdapter.setIsGridMode(false); mRvSearchResult.setAdapter(mAdapter); mAdapter.notifyDataSetChanged(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: { finish(); } break; } return super.onOptionsItemSelected(item); } }
C++
WINDOWS-1251
1,702
3.078125
3
[]
no_license
#pragma once #include <algorithm> typedef unsigned int TELEM; const size_t blockSize = sizeof(TELEM); const size_t bitsNum = blockSize * 8; class BitField { private: const size_t LenLimit{ 1048576 };// TELEM *Mem; // size_t MemLen;// - - . size_t numOfBlocks;// BFMult TELEM BYTE = 8; TELEM GetMemMask() { TELEM IM = 1; for ( int i = 1; i < bitsNum; ++i ) IM = ( IM << 1 ) | 1; return IM; } int get_BlockIndex( int n ); // n TELEM get_BlockMask( int bitShift ); // n public: BitField( int length ); // BitField( const BitField & ); // void operator = ( const BitField &cpBF ); // bool& operator[]( size_t ); size_t get_numOfBlocks() const;// size_t size() const;// void load_AllBits();// void unload_AllBits();// unsigned short getBit(int);// void load_bit(int);// void unload_bit(int);// size_t nonzero_count() const;// ~BitField(); };
Markdown
UTF-8
1,117
3
3
[]
no_license
# 创建Service 网络请求返回接口数据的同时,往往可能出现很多异常情况,比如断网、服务器宕、请求参数错误、请求超时等问题。而每一个请求都要面临上述的问题,所以我们需要创建一个服务去统一处理。 ```typescript import { HttpService } from '@redux-model/web'; export const $api = new HttpService({ baseUrl: 'http://example.com', headers: () => { return {}; }, onRespondError: (response, transform) => { if (response.data.error) { transform.message = response.data.error; } }, onShowSuccess: (msg) => { alert(msg); }, onShowError: (msg) => { alert(msg); }, }); ``` # 克隆 你可以继续通过`new HttpService()`实例化更多的service,但有时候多个service之间可能有很多相似之处,也许只有`baseUrl`是不一样的。如果有需要,你可以使用克隆的形式,并传入配置覆盖与原来service不同之处即可 ```typescript export const $otherApi = $api.clone({ baseUrl: 'http://other.com', ... }); ```
Python
UTF-8
2,936
3.453125
3
[]
no_license
import pickle,shelve # print('Открываю и закрываю файл') # text_file = open("read_it.txt", "r") # text_file.close() # print('\nЧитаю файл посимвольно') # text_file = open('read_it.txt','r') # print(text_file.read(1)) # print(text_file.read(5)) # text_file.close() # print('\nЧитаю файл целиком') # text_file = open("read_it.txt", "r") # whole_thing = text_file.read() # print(whole_thing) # text_file.close() # print('\nЧитаю одну строку посимвольно') # text_file = open("read_it.txt", "r") # print(text_file.readline(1)) # print(text_file.readline(5)) # text_file.close() # text_file = open("read_it.txt", "r") # print('\nЧитаю всю строку целиком') # print(text_file.readline()) # print(text_file.readline()) # print(text_file.readline()) # text_file.close() # print('\nЧитаю весь файл в список') # text_file = open("read_it.txt", "r") # lines = text_file.readlines() # print(lines) # print(len(lines)) # for line in lines: # print(line) # text_file.close() # print('\nПеребираю файл построчно') # text_file = open("read_it.txt", "r") # for line in text_file: # print(line) # text_file.close() #print('Создаю текстовый файл методом write()') # text_file = open('write_it.txt','w') # a = input('Введите текст для записи:') # text_file.write('Строка 1\n') # text_file.write('Строка 2\n') # text_file.write('Строка 3\n') # text_file.write(a) # text_file.close() # # print('Создаю текстовый файл методом writelines()') # text_file = open('write_it.txt','w') # lines = [ # 'Строка 1\n', # 'Строка 2\n', # 'Строка 3\n', # ] # text_file.writelines(lines) # text_file.close() print('Консервация списков') variety = ['огурцы','помидоры','капуста'] shape = ['целые','кубиками','соломкой'] brand = ['Главпродукт','Чумак','Бондюэль'] f = open('pickles1.dat','wb') pickle.dump(variety,f) pickle.dump(shape,f) pickle.dump(brand,f) f.close() print('\nРасконсервация списков') f = open('pickles1.dat','rb') variety = pickle.load(f) shape = pickle.load(f) brand = pickle.load(f) print(variety) print(shape) print(brand) f.close() print('\nПомещерние списков на полку') s = shelve.open('pickles2.dat') s['variety'] = ['огурцы','помидоры','капуста'] s['shape'] = ['целые','кубиками','соломкой'] s['brand'] = ['Главпродукт','Чумак','Бондюэль'] s.sync() print('\nИзвлечение списков из файла полки.') print('Торговые марки:' , s['brand']) print('Формы:', s['shape']) print('Виды овощей:', s['variety']) s.close()
PHP
UTF-8
10,512
2.53125
3
[]
no_license
<?php require_once "./get_clmn.php"; $objPHPExcel->setActiveSheetIndex(0); $sheet = $objPHPExcel->getActiveSheet(); $date=$start_date;// = "20{$_GET['startdate']}"; //$end_date = "20{$_GET['enddate']}"; $sdate = explode("-",$start_date); $edate = explode("-",$end_date); $start_day = date("w", mktime(0, 0, 0, $sdate['1'], $sdate['2'], $sdate[0])); $no_days = mktime(0, 0, 0, $edate['1'], $edate['2'], $edate[0]) - mktime(0, 0, 0, $sdate['1'], $sdate['2'], $sdate[0]); $no_days = $no_days/(60*60*24); //echo $no_days; //exit; $clmn_date = array(); $day = array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"); $mstari = 1; $next = $mstari + 1; for($x = 0; $x <= $no_days; $x++){ $last_clmn = $x + 67; $clmn = getColumn($last_clmn); $d = $x+$start_day; $sheet->setCellValue($clmn.$mstari,$day[$d % 7]) ->setCellValue($clmn.$next,($x+1)); $sheet->getColumnDimension($clmn)->setAutoSize(true); $sheet->getStyle($clmn.$next)->getAlignment() ->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); $clmn_date[$date] = $clmn; $xx = strtotime(date("Y-m-d", strtotime($date)) . " +1 day"); $date = date('Y-m-d', $xx); } $mstari++; //var_dump($clmn_date); //exit; $sql_aproduct = "SELECT product.id AS productid, blend.id AS blendid, blend.name AS blendname, product.name AS productname " ."FROM product,blend " ."WHERE product.blendid = blend.id " ."ORDER BY blend.id, product.id "; $query_aproduct = mysql_query($sql_aproduct) or die(mysql_error()); $color = array("FFFF0000","FF0D5931","FF336699"); $printed_blend = array(); $printed_product = array(); $product_row= array(); $color_index = 0; while($row = mysql_fetch_assoc($query_aproduct)){ if(!in_array($row['blendid'],$printed_blend)){ $mstari++; $sheet->getStyle("A".$mstari.":".getColumn($last_clmn).$mstari) ->getBorders()->getBottom() ->setBorderStyle(PHPExcel_Style_Border::BORDER_THICK); $sheet->getStyle("A{$mstari}:".getColumn($last_clmn)."{$mstari}")->getFill() ->setFillType(PHPExcel_Style_Fill::FILL_SOLID) ->getStartColor() ->setARGB($color[$color_index%3]); $printed_blend[] = $row['blendid']; $sheet->setCellValue('A'.$mstari,"{$row['blendname']}"); $color_index++; } if(!in_array($row['blendid'].$row['productid'],$printed_product)){ $mstari++; $printed_product[] = $row['blendid'].$row['productid']; $product_row[$row['blendid']][$row['productid']] = $mstari; $sheet->setCellValue('A'.$mstari,$row['productname']); $sheet->getStyle("C{$mstari}:".getColumn($last_clmn)."{$mstari}")->getFill() ->setFillType(PHPExcel_Style_Fill::FILL_SOLID) ->getStartColor()->setARGB('FFFFE4C4'); $sheet->getStyle("C{$mstari}:".getColumn($last_clmn)."{$mstari}")->getBorders()->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_DOTTED); } } //var_dump($product_row); //exit; $last_clmn++; $sql_date = "SELECT distinct(date) FROM dailyoutput WHERE (date >= '".$start_date."' AND date <= '".$end_date."')"; $query_date = mysql_query($sql_date) or die(mysql_error()); $product_id = $blend_id = ""; $blends = array(); while($row_date = mysql_fetch_array($query_date)) { $sql_products = "SELECT blend.id AS blend_id, product.id AS product_id, blend.name AS blend_name, product.name AS product_name, quantity " ."FROM dailyoutput,product,blend " ."WHERE dailyoutput.productId = product.id " ."AND product.blendid = blend.id " ."AND dailyoutput.date = '{$row_date['date']}' " ."ORDER BY product.blendid,product.id ASC "; $query_products = mysql_query($sql_products) or die(mysql_error()); while($row_products = mysql_fetch_array($query_products)) { $working_row = $product_row[$row_products['blend_id']][$row_products['product_id']]; $sheet->setCellValue($clmn_date[$row_date['date']].$working_row,$row_products['quantity']); $sheet->getStyle($clmn_date[$row_date['date']].$working_row)->getAlignment() ->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); $sheet->getStyle("B".$mstari.":".getColumn($last_clmn).$working_row)->getFill() ->setFillType(PHPExcel_Style_Fill::FILL_SOLID) ->getStartColor()->setARGB("#FFFFFFCC"); } $total_quantity = 0; } $last_row = $mstari; $mstari += 2; $day_keys = array_keys($clmn_date); for($z = 0; $z < count($day_keys); $z++){ $sum = "SUM({$clmn_date[$day_keys[$z]]}4:{$clmn_date[$day_keys[$z]]}{$last_row})"; //echo $sum; $sheet->setCellValue(($clmn_date[$day_keys[$z]]).$mstari,"=IF(SUM({$sum}) > 0, {$sum}, \"-\")"); $sheet->getStyle($clmn_date[$day_keys[$z]].$mstari)->getAlignment() ->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); } //exit; $sheet->setCellValue(getColumn($last_clmn)."1","GRAND TOTAL"); $sheet->setCellValue("A".$mstari,"GRAND TOTAL"); $sheet->getStyle("A".$mstari)->getFont()->setBold(true); $sheet->getStyle("A".$mstari.":".getColumn($last_clmn).$mstari)->getBorders()->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_THICK); $sheet->getStyle("A".$mstari.":".getColumn($last_clmn).$mstari)->getBorders()->getTop()->setBorderStyle(PHPExcel_Style_Border::BORDER_THICK); $sql_material = "SELECT material.id AS material_id, material.name AS material_name,blend.id AS blendid, " ."blend.name AS blend_name, dailyinput.date AS date, dailyinput.quantity, product.name AS product_name, product.id AS productid " ."FROM dailyinput,material,product,blend " ."WHERE dailyinput.productid = product.id " ."AND dailyinput.materialid = material.id " ."AND product.blendid = blend.id " ."AND (dailyinput.date >= '{$start_date}' AND dailyinput.date <= '{$end_date}')" ."ORDER BY material.id,blend.id, product.id, dailyinput.date "; $query_material = mysql_query($sql_material) or die(mysql_error()); $printed_materials = array(); $mstari +=1; $color_index = 0; $product_row = array(); while($row = mysql_fetch_assoc($query_material)){ if(!in_array($row['material_id'],$printed_materials)){ $printed_blend = array(); $printed_product = array(); $mstari+=2; $printed_materials[] = $row['material_id']; $sheet->setCellValue("A".$mstari,$row['material_name']); $sql_aproduct = "SELECT product.id AS productid, blend.id AS blendid, blend.name AS blendname, product.name AS productname " ."FROM product,blend " ."WHERE product.blendid = blend.id " ."ORDER BY blend.id, product.id "; $query_aproduct = mysql_query($sql_aproduct) or die(mysql_error()); while($rowx = mysql_fetch_assoc($query_aproduct)){ if(!in_array($rowx['blendid'],$printed_blend)){ $mstari++; $product_row[$row['material_id']][$rowx['blendid']][$rowx['productid']] = $mstari+1; $sheet->getStyle("A".$mstari.":".getColumn($last_clmn-1).$mstari) ->getBorders()->getBottom() ->setBorderStyle(PHPExcel_Style_Border::BORDER_THICK); $sheet->getStyle("A{$mstari}:".getColumn($last_clmn-1)."{$mstari}")->getFill() ->setFillType(PHPExcel_Style_Fill::FILL_SOLID) ->getStartColor() ->setARGB($color[$color_index%3]); $printed_blend[] = $rowx['blendid']; $sheet->setCellValue('A'.$mstari,"{$rowx['blendname']}"); $color_index++; } if(!in_array($rowx['blendid'].$rowx['productid'],$printed_product)){ $mstari++; $printed_product[] = $rowx['blendid'].$rowx['productid']; $product_row[$rowx['blendid']][$rowx['productid']] = $mstari; $sheet->setCellValue('A'.$mstari,$rowx['productname']); $sheet->getStyle("C{$mstari}:".getColumn($last_clmn)."{$mstari}")->getFill() ->setFillType(PHPExcel_Style_Fill::FILL_SOLID) ->getStartColor()->setARGB('FFFFE4C4'); $sheet->getStyle("C{$mstari}:".getColumn($last_clmn)."{$mstari}")->getBorders()->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_DOTTED); } } } /*$sheet->setCellValue("A".$product_row[$row['material_id']][$row['blendid']][$row['productid']],$row['product_name']) ->setCellValue($clmn_date[$row['date']].$mstari,$row['quantity']); $sheet->getStyle($clmn_date[$row['date']].$product_row[$row['material_id']][$row['blendid']][$row['productid']])->getAlignment() ->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); $sheet->getStyle("B".$mstari.":".getColumn($last_clmn).$product_row[$row['material_id']][$row['blendid']][$row['productid']])->getFill() ->setFillType(PHPExcel_Style_Fill::FILL_SOLID) ->getStartColor()->setARGB("#FFFFFFCC"); */ } for($i = 4; $i <= $mstari; $i++){ $sheet->setCellValue(getColumn($last_clmn)."{$i}","=IF(SUM(B{$i}:".getColumn($last_clmn-1)."{$i}) > 0, SUM(B{$i}:".getColumn($last_clmn-1)."{$i}), \"\")"); } for($x = 0; $x <= $no_days; $x++){ $last_clmn = $x + 67; $clmn = getColumn($last_clmn); $d = $x+$start_day; $sheet->getStyle($clmn.'4:'.getColumn($last_clmn+2).$mstari)->getBorders()->getLeft()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN); } $sheet->getStyle(getColumn($last_clmn+1).'3:'.getColumn($last_clmn+1).$mstari)->getFill() ->setFillType(PHPExcel_Style_Fill::FILL_SOLID) ->getStartColor() ->setARGB('FFDDA0DD'); $sheet->getColumnDimension("A")->setAutoSize(true); $sheet->getColumnDimension("B")->setAutoSize(true); $sheet->getColumnDimension(getColumn($last_clmn))->setAutoSize(true); $sheet->getDefaultStyle()->getBorders()->getTop()->setBorderStyle(PHPExcel_Style_Border::BORDER_HAIR); $sheet->getDefaultStyle()->getBorders()->getLeft()->setBorderStyle(PHPExcel_Style_Border::BORDER_HAIR); $sheet->getDefaultStyle()->getBorders()->getRight()->setBorderStyle(PHPExcel_Style_Border::BORDER_HAIR); $sheet->getDefaultStyle()->getBorders()->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_HAIR); $sheet->setTitle("DailyInput"); ?>
C++
UTF-8
2,877
3.9375
4
[ "MIT" ]
permissive
/* Count Number of Teams There are n soldiers standing in a line. Each soldier is assigned a unique rating value. You have to form a team of 3 soldiers amongst them under the following rules: Choose 3 soldiers with index (i, j, k) with rating (rating[i], rating[j], rating[k]). A team is valid if: (rating[i] < rating[j] < rating[k]) or (rating[i] > rating[j] > rating[k]) where (0 <= i < j < k < n). Return the number of teams you can form given the conditions. (soldiers can be part of multiple teams). Example 1: Input: rating = [2,5,3,4,1] Output: 3 Explanation: We can form three teams given the conditions. (2,3,4), (5,4,1), (5,3,1). Example 2: Input: rating = [2,1,3] Output: 0 Explanation: We can't form any team given the conditions. Example 3: Input: rating = [1,2,3,4] Output: 4 Constraints: n == rating.length 1 <= n <= 200 1 <= rating[i] <= 10^5 */ class Solution { public: int numTeams(vector<int>& rating) { int n=rating.size(),ans=0; // for each number, find out how many numbers are smaller & greater than it on both side for(int j=0;j<n;j++){ // ls: left smaller // lg: left greater // rs; right smaller // rg: right greater int ls=0,lg=0,rs=0,rg=0; // i..j for(int i=0;i<j;i++){ if(rating[i]<rating[j]) ls++; // the number on the left is smaller than it else lg++; // the number on the left is greater than it } // j..k for(int k=j+1;k<n;k++){ if(rating[k]<rating[j]) rs++; // the number on the right is smaller than it else rg++; // the number on the right is greater than it } // Example: [2,5,3,4,1] // take rating[2]=3 as an example // for rating[i] < rating[j] < rating[k], there is 1 number smaller than 3 from left side and 1 number greater than 3 // i.e. 2 < 3 < 4 // for rating[i] > rating[j] > rating[k], there are 1 number smaller than 3 and 1 number greater than 3 // i.e. 5 > 3 > 1 // there would be 1*1 + 1*1 = 2 tripplets in total for the number 3 being rating[j] ans+=ls*rg+lg*rs; } return ans; } }; class Solution2 { public: int numTeams(vector<int>& rating) { // n is just 200. brute force approach should work int n = rating.size(); int ans=0; for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ for(int k=j+1;k<n;k++){ if( (rating[i]>rating[j]&&rating[j]>rating[k]) || (rating[i]<rating[j]&&rating[j]<rating[k]) ) { ans++; } } } } return ans; } };
Java
UTF-8
1,239
2.140625
2
[]
no_license
package com.licc.btc.chbtcapi.res.account; /** * * @author lichangchao * @version 1.0.0 * @date 2017/5/19 10:10 * @see */ public class AccountBase { private Boolean auth_google_enabled; // 是否开通谷歌验证 private Boolean auth_mobile_enabled; // 是否开通手机验证 private Boolean trade_password_enabled;// 是否开通交易密码 private String username; public Boolean getAuth_google_enabled() { return auth_google_enabled; } public void setAuth_google_enabled(Boolean auth_google_enabled) { this.auth_google_enabled = auth_google_enabled; } public Boolean getAuth_mobile_enabled() { return auth_mobile_enabled; } public void setAuth_mobile_enabled(Boolean auth_mobile_enabled) { this.auth_mobile_enabled = auth_mobile_enabled; } public Boolean getTrade_password_enabled() { return trade_password_enabled; } public void setTrade_password_enabled(Boolean trade_password_enabled) { this.trade_password_enabled = trade_password_enabled; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
PHP
UTF-8
1,140
2.65625
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace Symplify\EasyCodingStandard\Bootstrap; use Symplify\EasyCodingStandard\Set\Set; final class ConfigResolver { /** * @var SetOptionResolver */ private $setOptionResolver; /** * @var SetsResolver */ private $setsResolver; public function __construct() { $this->setOptionResolver = new SetOptionResolver(); $this->setsResolver = new SetsResolver(); } /** * @param string[] $configFiles * @return string[] */ public function resolveFromParameterSetsFromConfigFiles(array $configFiles): array { $configs = []; $sets = $this->setsResolver->resolveFromConfigFiles($configFiles); return array_merge($configs, $this->resolveFromSets($sets)); } /** * @param string[] $sets * @return string[] */ private function resolveFromSets(array $sets): array { $configs = []; foreach ($sets as $set) { $configs[] = $this->setOptionResolver->detectFromNameAndDirectory($set, Set::SET_DIRECTORY); } return $configs; } }
Java
UTF-8
235
2.34375
2
[]
no_license
package com.ncku.iir.computex.ALS; /* 當ALS server 回傳response 用 implements 這個interface的類別 call onALSResponse的method做更新的動作 */ public interface IALSCallback { public void onALSResponse(String s); }
C
UTF-8
8,952
3.109375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <memory.h> #include <errno.h> #include "common.h" /* *** Server process is running at this port number. Client has to send data to this port number *** */ #define SERVER_PORT 2000 test_struct_t test_struct; result_struct_t result_struct; char data_buffer[1024]; void setup_tcp_server_communication() { /* *** STEP 1. INITIALIZATION * *** Socket handle and other variables * *** Master socket file descriptor, used only to accept new connection initiation request messages, does not accept service request messages *** */ int master_socket_tcp_fd=0; int sent_recv_bytes=0; int addr_len=0; int opt=1; /* *** Client communication file descriptor * *** It is used only for data exchange and communications between client and server *** */ int comm_socket_fd=0; /* *** Define and initialize the data type collection that will contain all the file descriptors in the program *** */ fd_set readfds; /* *** Define the variable to hold the information of addresses associated with the server and the client *** */ /* *** This a structure to hold server and client address and port number information *** */ struct sockaddr_in server_address; struct sockaddr_in client_address; /* *** STEP 2. CREATE MASTER SOCKET FILE DESCRIPTOR *** */ if((master_socket_tcp_fd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==-1) /* *** 1st argument of socket() system call defines what is the address family you are using. For IPV4 always AF_INET, for IPV6 AF_INET6 * *** 2nd argument is SOCK_STREAM or SOCK_DGRAM * *** 3rd argument defines the protocol you want to run on the top of the network layer IPPROTO_TCP for TCP communication (SOCK_STREAM, IPPROTO_TCP) for UDP communication (SOCK_DGRAM,IPPROTO_UDP) * ***/ { printf("Socket creation has failed.\n"); exit(1); } /* *** BIND() system call *** */ /* *** Binding means that you are telling the Operating System that any data you receive with the destination IP Address=a1 and TCP port=p1 will be sent to this process /* *** Bind() system call is a mechanism to tell the operating system what kind of data is the server interested to receive. /* *** Note: A server machine can run multiple server processes simultaneously to process data from multiple clients. /* *** bind() system call is only used on the server side, and not on the client side *** */ /* *** Specify the server information : address and port number *** */ server_address.sin_family=AF_INET; // this server is willing to interprete only IPv4 network packages AF_INET (AF_INET6 for IPv6) server_address.sin_port= SERVER_PORT; // this server will process only network packages meant for port SERVER_PORT defined as constant earlier as 2000 /* *** Add the server ip address. /* *** Operating system will send all the packages meant for the address to the process /* *** Note: the IPv4 have to be transformed into an integer numbers e.g. 192.168.56.101 => 3232249957 /* *** In the case of localhost one can use the constant INADDR_ANY *** */ /* *** INADDR_ANY means that because a server can have multiple IP Addresses, one address for each local interface of the server, server is interested in receiving all packages to any local interfaces of the server *** */ server_address.sin_addr.s_addr=INADDR_ANY; addr_len=sizeof(struct sockaddr); if(bind(master_socket_tcp_fd, (struct sockaddr *) &server_address, sizeof(struct sockaddr))== -1 ) { printf("Socket bind has failed.\n"); return; } /* *** STEP 4. THE LISTEN() system call *** */ /* *** With the listen() system call, the server instructs the operating system to maining a queue of packages of maximum length as specified in arguments *** */ /* *** Basically, this means that the server is telling the operating system to maintain a queue of maximum number of clients , and neglect the others *** */ if(listen(master_socket_tcp_fd,5)<0) { printf("Listen has failed.\n"); return; } /* *** STEP 5. INITIALIZE AND ADD THE MASTER SOCKET FILE DESCRIPTOR TO THE READFDS collection of file descriptors *** */ /* *** Enter and infinite loop to service the client. This way the server logic will be implemented inside the infinite loop *** */ while(1) { FD_ZERO(&readfds); //initializes the file descriptors set using the FD_ZERO macro to empty the readfds FD_SET(master_socket_tcp_fd, &readfds); //add the master socket file descriptor to the readfds collection printf("Now the server is blocked on the select() system call ...\n"); /* *** STEP 6. WAIT FOR CLIENT CONNECTION *** */ /* *** Call the select() system call, server process blocks now for incoming connections from new clients or existing ones. *** */ /* *** The select() system call remains blocked until data arrives for any file descriptors stored in the readfds collection *** */ select(master_socket_tcp_fd+1,&readfds, NULL, NULL, NULL); /* *** select() 1st argument is 1+maximum file descriptor existing in the readfds *** */ /* *** select() system call blocks the execution at line 101 until data arrives on a file descriptor stored in the readfds collection *** */ /* *** Finally, some data has arrived for the file descriptors stored in the readfds collection. Verify where such data is targeted and run *** */ if(FD_ISSET(master_socket_tcp_fd, &readfds)) //the FD_ISSET macro checks whether the 1st argument is activated in the readfds collection { /* *** Data arrives on the master socket file descriptor only when a new client sends a connection initiation request message. That is the client emitted a connect() system call on the client side *** */ printf("New connection received, accept the connection. Client and server completes TCP-3 way handshake at this point.\n"); /* *** STEP 7. ACCEPT() SYSTEM CALL GENERATES A NEW FILE DESCRIPTOR COMM_SOCKET_FD *** */ /* *** The server uses the new file descriptor comm_socket_fd for the rest of the lifetime of the connection with that client to send and receive all messages *** */ /* *** The master socket file descriptor is used only for new client connections and not for data exchange with existing clients *** */ comm_socket_fd= accept(master_socket_tcp_fd, (struct sockaddr *) &client_address, &addr_len); if(comm_socket_fd<0) { /* *** if accept failed to return a communication file descriptor, display a relevant error and exit *** */ printf("Accept error: errno=%d\n",errno); exit(0); } while(1) { printf("The server is ready to receive messages.\n"); memset(data_buffer,0, sizeof(data_buffer)); //drain the memory which will contain the message data /* *** STEP 8. SERVICE THE REQUEST *** */ /* *** Server receiving the data from the Client, client IP Address and Port Number will be stored in the client_address struct *** */ /* *** Server will use the client_address struct to reply back to the client. *** */ /* *** Following there is also a blocking system call, meaning the server process halts its execution here until data arrives on this comm_socket_fd from a client whose connection request has been previously accepted *** */ sent_recv_bytes=recvfrom(comm_socket_fd, (char *) data_buffer, sizeof(data_buffer),0, (struct sockaddr *) &client_address, &addr_len); printf("The server has received %d bytes from the client %s at port %u.\n" , sent_recv_bytes,inet_ntoa(client_address.sin_addr),ntohs(client_address.sin_port)); if(sent_recv_bytes == 0) { /* *** if a server receives an empty message from the client, the server may close the connection from the client and wait for a new connection from that client *** */ close(comm_socket_fd); break; //go to STEP 5 which is UPDATE AND FILL THE readfds collection and continue the next steps } test_struct_t *client_data=(test_struct_t *) data_buffer; /* *** STEP 9. *** */ if(client_data->a==0 && client_data->b==0) { close(comm_socket_fd); printf("Server closes connection with the client: %s on port %u.\n", inet_ntoa(client_address.sin_addr), ntohs(client_address.sin_port)); break; //get out of the while loop, server is done with this client, it should check for new connections requestes by running select() } result_struct_t result; result.c = client_data->a + client_data->b; /* *** Server replying back to client now *** */ sent_recv_bytes=sendto(comm_socket_fd, (char *) &result, sizeof(result_struct_t),0,(struct sockaddr *) &client_address, sizeof(struct sockaddr)); printf("Server sent %d bytes in reply to the client.\n",sent_recv_bytes); } } printf("Connection accepted by the client %s: %u\n", inet_ntoa(client_address.sin_addr),ntohs(client_address.sin_port)); } } int main(int argc, char **argv[]) { setup_tcp_server_communication(); return 0; }
Java
UTF-8
556
2.0625
2
[]
no_license
package com.starbucks.locator.model.dataaccess; import java.sql.Connection; import java.util.List; import java.util.Set; import com.starbucks.locator.model.dto.Location; import com.starbucks.locator.model.runtime.StarbucksLocatorException; public interface LocationsManager { Location getLocation(String address, Connection con) throws StarbucksLocatorException; public List<Location> getLocations(Connection con) throws StarbucksLocatorException; public boolean addLocations(Set<Location> b, Connection con) throws StarbucksLocatorException; }
Java
UTF-8
4,485
4.03125
4
[]
no_license
package com.myleetcode.breadth_first_search.nested_list_weight_sum; import com.myleetcode.utils.nested_integer.NestedInteger; import java.util.ArrayDeque; import java.util.Deque; import java.util.List; /** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * public interface NestedInteger { * // Constructor initializes an empty nested list. * public NestedInteger(); * * // Constructor initializes a single integer. * public NestedInteger(int value); * * // @return true if this NestedInteger holds a single integer, rather than a nested list. * public boolean isInteger(); * * // @return the single integer that this NestedInteger holds, if it holds a single integer * // Return null if this NestedInteger holds a nested list * public Integer getInteger(); * * // Set this NestedInteger to hold a single integer. * public void setInteger(int value); * * // Set this NestedInteger to hold a nested list and adds a nested integer to it. * public void add(NestedInteger ni); * * // @return the nested list that this NestedInteger holds, if it holds a nested list * // Return null if this NestedInteger holds a single integer * public List<NestedInteger> getList(); * } */ class Solution { public int depthSum(List<NestedInteger> nestedList) { // return depthSumByQueue(nestedList); // BFS return depthSumByDFS(nestedList); // DFS } // this problem is actually a tree traverse preorder // TC: O(H), H is the depth of input // SC: O(N), N is the num of NI in input // intuition: // this looks like a Parentheses problem, maybe we could use Stack (or DFS recursion) to solve it. we use a stack to store the [, every time we meet one, we push it into the Stack and make a variable depth plus 1, and every time we meet a num we make a sum += num*depth, and everytiem we meet a ], we pop out a [ and make the depth minus 1 // BUT the input is not a String, so we could not use the [ and ] easily. since this input is a List<NestedInteger> and we have the necessary interface of it, we could use BFS to solve it. private int depthSumByQueue(List<NestedInteger> nestedList){ if(nestedList == null || nestedList.size() == 0){ return 0; } int sum = 0; Deque<NestedInteger> niQueue = new ArrayDeque<>(); // !!! at first, I thought: the very first level, because the input is a List<NI>, so we have to break it up and process it: if Integer, sum it; if NI, offer to Queue. BUT NO, we dont do that, because Integer and NI are both NI, so we just offer to Queue and process them in the Queue int depth = 1; for(NestedInteger ni: nestedList){ niQueue.offer(ni); } // we already have the initial Queue, level by level scan while(!niQueue.isEmpty()){ int size = niQueue.size(); // scan cur level Integer and NestedInteger(not Integer) for(int i = 0; i < size; i++){ NestedInteger curNI = niQueue.poll(); if(curNI.isInteger()){ sum += curNI.getInteger() * depth; }else{ // push NI in List to queue for(NestedInteger nextNI: curNI.getList()){ niQueue.offer(nextNI); } } } // depth depth++; } return sum; } // DFS solution /* The algorithm takes O(N) time, where NN is the total number of nested elements in the input list. For example, the list [ [[[[1]]]], 2 ] contains 4 nested lists and 2 nested integers (1 and 2), so N=6. In terms of space, at most O(D) recursive calls are placed on the stack, where DD is the maximum level of nesting in the input. For example, D=2 for the input [[1,1],2,[1,1]], and D=3 for the input [1,[4,[6]]]. */ private int depthSumByDFS(List<NestedInteger> nestedList){ return dfs(nestedList, 1); } private int dfs(List<NestedInteger> nestedList, int depth){ int sum = 0; for (NestedInteger ni: nestedList) { if (ni.isInteger()) { sum += ni.getInteger() * depth; } else { sum += dfs(ni.getList(), depth + 1); } } return sum; } }
Java
UTF-8
794
3.421875
3
[ "MIT" ]
permissive
package com.ithinksky.java.n01base.reference; import java.lang.ref.WeakReference; /** * 弱引用 WeakReference * 弱引用是一种比软引用生命周期更短的引用。 * 他的生命周期很短,不论当前内存是否充足, * 都只能存活到下一次垃圾收集之前。 * vm:-Xmx2m -Xms2m * * 生命周期很短的对象,例如ThreadLocal中的Key * * @author tengpeng.gao * @since 2019-02-26 */ public class Reference003WeakReference { public static void main(String[] args) { WeakReference<String> weakReference = new WeakReference<>(new String("弱引用")); System.gc(); System.runFinalization(); if (weakReference.get() == null) { System.out.println("weakReference已经被GC回收"); } } }
JavaScript
UTF-8
2,023
2.6875
3
[]
no_license
import { compareStrings, groupBy } from './utils.js' import { entryType } from './EntryTypes.js' export { transformJsonToD3, transformJsonToD3Zipped } function transformJsonToD3(data, label) { const dataset = groupBy(data, d => d.label) .sort((a, b) => compareStrings(a[0].label, b[0].label)) .map((d, index) => { const reducer = (acc, value) => { const maybeAttendance = value.entryTypes.find(e => e.entryType === label) if (maybeAttendance && maybeAttendance.bool) { return acc + 1 } else { return acc } } const sum = d.reduce(reducer, 0) const total = d.length const percent = 100 / total * sum return { x: index + 1, xLabel: d[0].label, yp: percent, ya: sum, total: total, label: label } }) return dataset } function transformJsonToD3Zipped(data) { const reducer = (label) => (acc, value) => { const maybeAttendance = value.entryTypes.find(e => e.entryType === label) if (maybeAttendance && maybeAttendance.bool) { return acc + 1 } else { return acc } } const dataset = groupBy(data, d => d.label) .sort((a, b) => compareStrings(a[0].label, b[0].label)) .map((d, index) => { const attRed = reducer(entryType.ATTENDANCE) const certRed = reducer(entryType.CERTIFICATE) const sumAtt = d.reduce(attRed, 0) const sumCert = d.reduce(certRed, 0) const total = d.length const certPercent = 100 / total * sumCert const attPercent = 100 / total * sumAtt return { x: index + 1, xLabel: d[0].label, y0p: certPercent, y0a: sumCert, y1p: attPercent, y1a: sumAtt, total: total } }) return dataset }
Java
UTF-8
3,433
1.929688
2
[]
no_license
package com.yescnc.core.role.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.yescnc.core.entity.db.RoleVO; import com.yescnc.core.entity.db.UserVO; import com.yescnc.core.role.service.RoleService; @RequestMapping(value="/role") @RestController public class RoleController { private org.slf4j.Logger log = LoggerFactory.getLogger(RoleController.class); @Autowired RoleService roleService; /*@RequestMapping(value="/getGroupInfo", method=RequestMethod.GET, produces="application/json;charset=UTF-8") public List getGroupInfo(){ return roleService.getGroupInfo(); }*/ @RequestMapping(value="/getUserList", method=RequestMethod.GET, produces="application/json;charset=UTF-8") public List<UserVO> getUserList(){ return roleService.getUserList(); } @RequestMapping(value="/getSelectedList/{cmd}", method=RequestMethod.GET, produces="application/json;charset=UTF-8") public HashMap<String, Object> getSelectedList(@PathVariable("cmd") String cmd){ return roleService.getSelectedList(cmd); } @RequestMapping(value="/getInitGroupInfo", method=RequestMethod.GET, produces="application/json;charset=UTF-8") public HashMap<String, Object> getInitGroupInfo(){ return roleService.getInitGroupInfo(); } @RequestMapping(value = "/insertRoleGroup",method=RequestMethod.POST, produces="application/json;charset=UTF-8") public Integer insertRoleGroup(@RequestBody Map<String, Object> param) { return roleService.insertRoleGroup(param); } @RequestMapping(value = "/updateRoleGroup",method=RequestMethod.POST, produces="application/json;charset=UTF-8") public Integer updateRoleGroup(@RequestBody Map<String, Object> param) { return roleService.updateRoleGroup(param); } @RequestMapping(value = "/updateUserGroup",method=RequestMethod.POST, produces="application/json;charset=UTF-8") public Integer updateUserGroup(@RequestBody Map<String, Object> param) { return roleService.updateUserGroup(param); } @RequestMapping(value = "/insertGroupComponent",method=RequestMethod.POST, produces="application/json;charset=UTF-8") public Integer insertGroupComponent(@RequestBody Map<String, Object> param) { return roleService.insertGroupComponent(param); } @RequestMapping(value="/deleteRoleGroup", method=RequestMethod.POST, produces="application/json;charset=UTF-8") public Integer deleteRoleGroup(@RequestBody Map<String, Object> param){ return roleService.deleteRoleGroup(param); } @RequestMapping(value="/{groupId}", method=RequestMethod.GET, produces="application/json;charset=UTF-8") public RoleVO selectGroup(@PathVariable("groupId") String groupId){ RoleVO vo = new RoleVO(); vo.setGroupId(groupId); return roleService.selectGroup(vo); } @RequestMapping(value = "/change",method=RequestMethod.PUT, produces="application/json;charset=UTF-8") public void updatePolling(@RequestBody RoleVO vo) { roleService.updatePolling(vo); } }
C#
UTF-8
4,547
3.21875
3
[ "Apache-2.0" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RTSEngine.Algorithms { public abstract class ACBudgetedTask { // This Should Not Be Modified By The Task public int CurrentBin { get; set; } // This Is How Tasks Will Be Sorted Into Bins public int WorkAmount { get; private set; } public bool IsFinished { get { return WorkAmount <= 0; } } public ACBudgetedTask(int workAmount) { CurrentBin = -1; WorkAmount = workAmount; } // The Task's Work Function public abstract void DoWork(float dt); // This Task Is Complete And Should Not Be Executed public void Finish() { WorkAmount = -1; } } public class TimeBudget { // Bins Of Tasks private readonly List<ACBudgetedTask>[] taskBins; private int curBin; // For Sorting By Relative Work private readonly int[] totalWork; public IEnumerable<ACBudgetedTask> Tasks { get { for(int bin = 0; bin < taskBins.Length; bin++) for(int ti = 0; ti < taskBins[bin].Count; ti++) yield return taskBins[bin][ti]; } } public IEnumerable<ACBudgetedTask> WorkingTasks { get { for(int bin = 0; bin < taskBins.Length; bin++) for(int ti = 0; ti < taskBins[bin].Count; ti++) if(!taskBins[bin][ti].IsFinished) yield return taskBins[bin][ti]; } } public int Bins { get { return taskBins.Length; } } public int TotalTasks { get; private set; } public TimeBudget(int bins) { taskBins = new List<ACBudgetedTask>[bins]; for(int i = 0; i < taskBins.Length; i++) { taskBins[i] = new List<ACBudgetedTask>(); } TotalTasks = 0; totalWork = new int[bins]; Array.Clear(totalWork, 0, totalWork.Length); curBin = 0; } private int FindEasiestBin() { int w = totalWork[0]; int bin = 0; for(int i = 1; i < totalWork.Length; i++) { if(totalWork[i] < w) { bin = i; w = totalWork[i]; } } return bin; } public void AddTask(ACBudgetedTask t) { // Make Sure Task Hasn't Already Been Added if(t.CurrentBin >= 0) RemoveTask(t); int bin = FindEasiestBin(); t.CurrentBin = bin; taskBins[bin].Add(t); totalWork[bin] += t.WorkAmount; TotalTasks++; } public void RemoveTask(ACBudgetedTask t) { // Make Sure Task Has Been Added if(t.CurrentBin < 0) return; TotalTasks--; totalWork[t.CurrentBin] -= t.WorkAmount; taskBins[t.CurrentBin].Remove(t); t.CurrentBin = -1; } public void ClearTasks() { TotalTasks = 0; for(int i = 0; i < taskBins.Length; i++) { for(int ti = 0; ti < taskBins[i].Count; ti++) { taskBins[i][ti].CurrentBin = -1; } taskBins[i] = new List<ACBudgetedTask>(); } Array.Clear(totalWork, 0, totalWork.Length); } public void ResortBins() { ACBudgetedTask[] tasks = new ACBudgetedTask[TotalTasks]; int c = 0; for(int bin = 0; bin < taskBins.Length; bin++) for(int ti = 0; ti < taskBins[bin].Count; ti++) // Check For Finished Tasks if(!taskBins[bin][ti].IsFinished) tasks[c++] = taskBins[bin][ti]; // Re-Add Tasks ClearTasks(); for(int i = 0; i < c; i++) AddTask(tasks[i]); } public void DoTasks(float dt) { var tasks = taskBins[curBin]; for(int i = 0; i < tasks.Count; i++) { // Check For Task Viability if(tasks[i].IsFinished) continue; tasks[i].DoWork(dt); } // Increment The Task Bin curBin = (curBin + 1) % taskBins.Length; } } }
C#
UTF-8
556
2.859375
3
[]
no_license
using UserManagement; namespace GameLogic { public class Turn { private ActionType _action; private Chip _chipsUsedInRound; private Player _player; public enum ActionType { Fold, Check, AllIn, Call, Raise } public Turn(Player player,ActionType action, Chip ChipsUsedInRound) { this._chipsUsedInRound = ChipsUsedInRound; this._player = player; this._action = action; } } }
JavaScript
UTF-8
11,893
2.734375
3
[]
no_license
// start functions function validate_title(){ var guide_title = document.guide_update.title.value; if (guide_title == "X") { inlineMsg('title', 'Please select your title.', 2); /*$('#member_update').submit(function (evt) { evt.preventDefault(); });*/ return false; } } function validate_name(){ var guide_name = document.guide_update.name.value; if(guide_name == ""){ inlineMsg('name', 'Invalid name.', 2); /*$('#member_update').submit(function (evt) { evt.preventDefault(); });*/ return false; } } function validate_name_on_badge(){ var guide_name_badge = document.guide_update.badge.value; if(guide_name_badge == ""){ inlineMsg('badge', 'Invalid name for badge.', 2); /*$('#member_update').submit(function (evt) { evt.preventDefault(); });*/ return false; } } function validate_gender(){ var gender = ""; var len = document.guide_update.gender.length; for (i = 0; i < len; i++) { if (document.guide_update.gender[i].checked) { gender = document.guide_update.gender[i].value; break; } } if (gender == "") { inlineMsg('gender_error', 'Please select your gender.', 2); /*$('#member_update').submit(function (evt) { evt.preventDefault(); });*/ return false; } } function validate_address(){ var guide_address = document.guide_update.address.value; if(guide_address == ""){ inlineMsg('address', 'Invalid address.', 2); /*$('#member_update').submit(function (evt) { evt.preventDefault(); });*/ return false; } } function validate_telephone(){ var guide_telephone = document.guide_update.telephone.value; if (guide_telephone == "") { inlineMsg('telephone', 'Telephone number can\'t be empty.', 2); /*$('#member_update').submit(function (evt) { evt.preventDefault(); });*/ return false; } if(guide_telephone.length > 12) { inlineMsg('telephone','Telephone number can\'t exceed 12 characters.',2); /*$('#member_update').submit(function (evt) { evt.preventDefault(); });*/ return false; } if(guide_telephone.length < 10) { inlineMsg('telephone','Telephone number must have at least 10 characters.',2); /*$('#member_update').submit(function (evt) { evt.preventDefault(); });*/ return false; } } function validate_email(){ var guide_email = document.guide_update.email.value; var emailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/; if((guide_email == "")||(!guide_email.match(emailRegex))) { inlineMsg('email', 'Invalid email.', 2); /*$('#member_update').submit(function (evt) { evt.preventDefault(); });*/ return false; } } function validate_dob(){ var guide_dob = document.guide_update.dob.value; if(guide_dob == ""){ inlineMsg('dob', 'Invalid birth date.', 2); /*$('#member_update').submit(function (evt) { evt.preventDefault(); });*/ return false; } } function validate_id_number(){ var guide_id = document.guide_update.id.value; if(guide_id == ""){ inlineMsg('id', 'ID number is required.', 2); /*$('#member_update').submit(function (evt) { evt.preventDefault(); });*/ return false; } if((guide_id.length) != 10){ inlineMsg('id', 'ID number must have only 10 characters.', 2); return false; } var id_numbers = guide_id.substring(0,9); if(isNaN(id_numbers)){ inlineMsg('id','First 9 Digits must be numbers in ID number.',2); return false; } if(((guide_id.charAt(guide_id.length-1)).toUpperCase()) != "V"){ inlineMsg('id','Your ID number must be end with V.',2); return false; } } function validate_nationality(){ var guide_nationality = document.guide_update.nationality.value; if(guide_nationality == ""){ inlineMsg('nationality', 'Invalid nationality.', 2); /*$('#member_update').submit(function (evt) { evt.preventDefault(); });*/ return false; } } function validate_category(){ var guide_category = document.guide_update.category.value; if (guide_category == "X") { inlineMsg('category', 'Please select your category.', 2); /*$('#member_update').submit(function (evt) { evt.preventDefault(); });*/ return false; } } function validate_emp_type(){ var emp = ""; var len = document.guide_update.employment.length; for (i = 0; i < len; i++) { if (document.guide_update.employment[i].checked) { emp = document.guide_update.employment[i].value; break; } } if (emp == "") { inlineMsg('emp_error', 'Please select your employment type.', 2); /*$('#member_update').submit(function (evt) { evt.preventDefault(); });*/ return false; } } function validate_username(){ var guide_username = document.guide_update.username.value; if(guide_username == ""){ inlineMsg('username', 'Invalid username.', 2); /*$('#member_update').submit(function (evt) { evt.preventDefault(); });*/ return false; } } function validate_old_password(){ var guide_old_password = document.guide_update.old_password.value; if(guide_old_password == ""){ inlineMsg('old_password', 'Old password is required.', 2); /*$('#member_update').submit(function (evt) { evt.preventDefault(); });*/ return false; } } function validate_password_match(){ var guide_new_password = document.guide_update.new_password.value; var guide_confirm_password = document.guide_update.confirm_new_password.value; if(guide_new_password != guide_confirm_password){ if(guide_new_password==""){ inlineMsg('new_password', 'Passwords do not match.', 1); return false; } else{ inlineMsg('confirm_new_password', 'Passwords do not match.', 1); $("#modal_guide").modal('hide'); $("#old_password").val(""); return false; } } } function main_validate(){ var guide_title = document.guide_update.title.value; var guide_name = document.guide_update.name.value; var guide_name_badge = document.guide_update.badge.value; var gender = ""; var len = document.guide_update.gender.length; for (i = 0; i < len; i++) { if (document.guide_update.gender[i].checked) { gender = document.guide_update.gender[i].value; break; } } var guide_address = document.guide_update.address.value; var guide_telephone = document.guide_update.telephone.value; var guide_email = document.guide_update.email.value; var guide_dob = document.guide_update.dob.value; var guide_id = document.guide_update.id.value; var guide_nationality = document.guide_update.nationality.value; var guide_category = document.guide_update.category.value; var emp = ""; var len = document.guide_update.employment.length; for (i = 0; i < len; i++) { if (document.guide_update.employment[i].checked) { emp = document.guide_update.employment[i].value; break; } } var guide_username = document.guide_update.username.value; // var guide_old_password = document.guide_update.old_password.value; if((guide_title=="X")||(guide_name=="")||(guide_name_badge=="")||(gender=="")||(guide_address=="X")|| (guide_telephone=="")||(guide_email=="")||(guide_dob=="")||(guide_id=="")||(guide_nationality=="")|| (guide_category=="X")||(emp=="")||(guide_username=="")){ alert("Please fill all the fields"); //history.back(); // $('input[type=submit]').attr('disabled', 'disabled'); $('#guide_update').submit(function (evt) { evt.preventDefault(); }); return false; } //window.alert('You have successfully Updated your details.Please Signin Again...'); //document.getElementById( 'success_msg' ).innerHTML = "Updated Sucessfully"; //document.forms["member_update"].submit(); //location.reload(); } // START OF MESSAGE SCRIPT // var MSGTIMER = 20; var MSGSPEED = 5; var MSGOFFSET = 3; var MSGHIDE = 3; // build out the divs, set attributes and call the fade function // function inlineMsg(target,string,autohide) { var msg; var msgcontent; if(!document.getElementById('msg')) { msg = document.createElement('div'); msg.id = 'msg'; msgcontent = document.createElement('div'); msgcontent.id = 'msgcontent'; document.body.appendChild(msg); msg.appendChild(msgcontent); msg.style.filter = 'alpha(opacity=0)'; msg.style.opacity = 0; msg.alpha = 0; } else { msg = document.getElementById('msg'); msgcontent = document.getElementById('msgcontent'); } msgcontent.innerHTML = string; msg.style.display = 'block'; var msgheight = msg.offsetHeight; var targetdiv = document.getElementById(target); targetdiv.focus(); var targetheight = targetdiv.offsetHeight; var targetwidth = targetdiv.offsetWidth; var topposition = topPosition(targetdiv) - ((msgheight - targetheight) / 2); var leftposition = leftPosition(targetdiv) + targetwidth + MSGOFFSET; msg.style.top = topposition + 'px'; msg.style.left = leftposition + 'px'; clearInterval(msg.timer); msg.timer = setInterval("fadeMsg(1)", MSGTIMER); if(!autohide) { autohide = MSGHIDE; } window.setTimeout("hideMsg()", (autohide * 1000)); } // hide the form alert // function hideMsg(msg) { var msg = document.getElementById('msg'); if(!msg.timer) { msg.timer = setInterval("fadeMsg(0)", MSGTIMER); } } // face the message box // function fadeMsg(flag) { if(flag == null) { flag = 1; } var msg = document.getElementById('msg'); var value; if(flag == 1) { value = msg.alpha + MSGSPEED; } else { value = msg.alpha - MSGSPEED; } msg.alpha = value; msg.style.opacity = (value / 100); msg.style.filter = 'alpha(opacity=' + value + ')'; if(value >= 99) { clearInterval(msg.timer); msg.timer = null; } else if(value <= 1) { msg.style.display = "none"; clearInterval(msg.timer); } } // calculate the position of the element in relation to the left of the browser // function leftPosition(target) { var left = 0; if(target.offsetParent) { while(1) { left += target.offsetLeft; if(!target.offsetParent) { break; } target = target.offsetParent; } } else if(target.x) { left += target.x; } return left; } // calculate the position of the element in relation to the top of the browser window // function topPosition(target) { var top = 0; if(target.offsetParent) { while(1) { top += target.offsetTop; if(!target.offsetParent) { break; } target = target.offsetParent; } } else if(target.y) { top += target.y; } return top; } // preload the arrow // if(document.images) { arrow = new Image(7,80); arrow.src = "images/msg_arrow.gif"; }
JavaScript
UTF-8
1,331
2.765625
3
[]
no_license
document.addEventListener("DOMContentLoaded", ()=>{ window.onscroll = function(){scrollEvent()}; }) function scrollEvent() { let height = window.pageYOffset; let el1 = document.querySelector("#row1"); let el2 = document.querySelector("#row2"); let el3 = document.querySelector("#row3"); let el4 = document.querySelector("#row4"); let el5 = document.querySelector("nav"); console.log(height); if(height >= 200){ fadeIn(el1); } if (height >= 600) { fadeIn(el2); fadeOut(el4); fadeOut(el3); } if (height > 1000) { fadeIn(el3); fadeOut(el1); } if (height >= 1400) { fadeIn(el4); fadeOut(el2); } if (height >= 2000) { fadeOut(el3); } if (height <= 2000 && height > 1000) { fadeIn(el3); } if (height >= 100){ changeClass(el5); } if (height == 0) { updateClass(el5); fadeOut(el1); fadeOut(el2); fadeOut(el3); fadeOut(el4); } } function fadeIn(el) { setTimeout(function() { el.style.opacity = "1"; }, 300); } function fadeOut(el) { setTimeout(function() { el.style.opacity = "0"; }, 300); } function changeClass(el) { el.classList.add("navbar-light","bg-light"); el.style.padding = "10"; } function updateClass(el) { el.classList.remove("navbar-light","bg-light"); el.style.padding = "10"; }
PHP
UTF-8
280
2.90625
3
[]
no_license
<?php $c = curl_init('http://numbersapi.com/09/27'); // cURL이 응답을 가져와 바로 출력하지 않고 // 문자열로 가져오도록 설정한다. curl_setopt($c, CURLOPT_RETURNTRANSFER, true); // 요청 실행 $fact = curl_exec($c); ?> Did you know that <?= $fact ?>
Python
UTF-8
4,371
2.53125
3
[]
no_license
import unittest from models.test_base import BaseTestCase import json class TestUserGetQuestion(BaseTestCase): """test user can post a question""" def test_get_a_question(self): request = {"email": "alovegakevin@gmail.com", "username": "alwa", "password": "LUG4Z1V4"} res = self.client.post("/auth/signup", json=request) self.assertEqual(res.status_code, 201) # login user login = self.client.post( "/auth/login", data = json.dumps(dict( username = "alwa", password = "LUG4Z1V4" )), headers = {"content-type": "application/json"} ) self.assertEqual(login.status_code,202) login_data = json.loads(login.data.decode()) token = "Bearer" +" " +login_data["access_token"] # post question Question = self.client.post( "/questions", data = json.dumps(dict( title = "Question 1", details = "Have you completed writing your API", )), headers = {"content-type": "application/json", "Authorization":token} ) self.assertEqual(Question.status_code,201) #get one question response = self.client.get("/questions/1", headers = {"content-type": "application/json", "Authorization":token}) self.assertEqual(response.status_code,200) def test_get_all_question(self): request = {"email": "alovegakevin@gmail.com", "username": "alwa", "password": "LUG4Z1V4"} res = self.client.post("/auth/signup", json=request) self.assertEqual(res.status_code, 201) # login user login = self.client.post( "/auth/login", data = json.dumps(dict( username = "alwa", password = "LUG4Z1V4" )), headers = {"content-type": "application/json"} ) self.assertEqual(login.status_code,202) login_data = json.loads(login.data.decode()) token = "Bearer" +" " +login_data["access_token"] # post question Question = self.client.post( "/questions", data = json.dumps(dict( title = "Question 1", details = "Have you completed writing your API", )), headers = {"content-type": "application/json", "Authorization":token} ) self.assertEqual(Question.status_code,201) #get one question response = self.client.get("/questions", headers = {"content-type": "application/json", "Authorization":token}) self.assertEqual(response.status_code,200) def test_get_a_question_that_does_not_exist(self): request = {"email": "alovegakevin@gmail.com", "username": "alwa", "password": "LUG4Z1V4"} res = self.client.post("/auth/signup", json=request) self.assertEqual(res.status_code, 201) # login user login = self.client.post( "/auth/login", data = json.dumps(dict( username = "alwa", password = "LUG4Z1V4" )), headers = {"content-type": "application/json"} ) self.assertEqual(login.status_code,202) login_data = json.loads(login.data.decode()) token = "Bearer" +" " +login_data["access_token"] # post question Question = self.client.post( "/questions", data = json.dumps(dict( title = "Question 1", details = "Have you completed writing your API", )), headers = {"content-type": "application/json", "Authorization":token} ) self.assertEqual(Question.status_code,201) #get a question that doen't exist response = self.client.get("/questions/2", headers = {"content-type": "application/json", "Authorization":token}) self.assertEqual(response.status_code,404) self.assertIn("question does not exist", str(response.json)) if __name__== '__main__': unittest.main()
Python
UTF-8
182
2.96875
3
[]
no_license
def returnKLargest(input, k): input.sort(reverse=True) return input[:3] if __name__ == '__main__': input = [1, 23, 12, 9, 30, 2, 50] print returnKLargest(input, 3)
JavaScript
UTF-8
839
3.328125
3
[]
no_license
const API_KEY = "1c5528ad01d516f681ab4a37495d45d3"; const weather = document.querySelector(".js-weather"); function getWeather(lat, lng) { fetch( `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&appid=${API_KEY}&units=metric` ) .then(function (response) { return response.json(); }) .then(function (json) { const temperature = json.main.temp; const location = json.name; weather.innerText = `${temperature}℃ @ ${location}`; }); } function handleGeoSuccess(position) { const lat = position.coords.latitude; const lng = position.coords.longitude; getWeather(lat, lng); } function handleGeoFail() { console.log("Cannot load the current location."); } function init() { navigator.geolocation.getCurrentPosition(handleGeoSuccess, handleGeoFail); } init();
Markdown
UTF-8
1,531
2.796875
3
[ "MIT" ]
permissive
# image-ipreview 一款基于vue的桌面端轻量图片预览插件。 1.欢迎大家使用~,觉得还行的,恳请给个star,谢谢! 2.如有问题,请提issue,我会持续迭代。 ### 特性 1.支持缩放,旋转,下载 2.支持鼠标滚轮缩放 3.自带节流机制,兼顾性能 ### 安装 ```javascript npm install image-ipreview ``` ### 用法 ```javascript import ImageIpreview from 'image-ipreview'; import 'image-ipreview/lib/image-ipreview.css'; Vue.use(ImageIpreview); // 组件中使用 ... <template> <div id="app"> <image-ipreview :url="require('./assets/logo.png')" :isMouseWheel="true" :isShowToolBar="true" :closeOnPressEscape="true" :isDownload="true" downloadName="haha" /> </div> </template> ... ``` ### 配置 | 属性名 | 类型 | 描述 | 默认值 | | :----------------: | :-----: | :-----------: | :----: | | url | String | 图片地址 | | | closeOnPressEscape | Boolean | esc键关闭预览 | true | | isShowToolBar | Boolean | 是否展示工具栏 | true | | isDownload | Boolean | 是否展示下载图标 | true | | downloadName | String | 下载图片名称 | 下载图片 | | isMouseWheel | Boolean | 是否开启鼠标滚轮缩放 | false | ### 效果 ![image](https://gitee.com/weban/vue-plug-in/raw/master/examples/assets/44.jpg) ![image](https://gitee.com/weban/vue-plug-in/raw/master/examples/assets/1314.png)
PHP
UTF-8
7,470
3.09375
3
[]
no_license
<?php $servername = 'localhost'; $dbname = 'auto'; $username = 'Auto'; $password = 'LabaiSlaptas123'; //create connection $connection = new mysqli($servername, $username, $password, $dbname); //check connection if($connection->connect_error) { die('Connection failed: ' . $connection->connect_error); } // create new record if(isset($_POST['submit'])) { $date = $_POST['date']; $number = $_POST['number']; $distance = $_POST['distance']; $time = $_POST['time']; $sql = "INSERT INTO radars(`date`, `number`, `distance`, `time`) VALUES ('$date', '$number', '$distance', '$time')"; $result = $connection->query($sql); if(!$result){ die("Failed: " . $connection->error); } //redirect browser to not add more records when refreshing page header("Location: " . $_SERVER['PHP_SELF']); exit(); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <title>data</title> </head> <body class="container"> <h1>Insert new row</h1> <form action="" method="post"> <label for="date">Date</label> <input type="datetime-local" name="date" required> <label for="number">Number</label> <input type="text" name="number" required> <label for="distance">Distance</label> <input type="int" name="distance" required> <label for="time">Time</label> <input type="int" name="time" required> <br><br> <button class="btn btn-primary" type="submit" name="submit">Insert</button> </form> <br> <h1>Update row</h1> <?php //update one of the records if(isset($_POST['submit1'])) { $id = $_POST['id']; $date = $_POST['date']; $number = $_POST['number']; $distance = $_POST['distance']; $time = $_POST['time']; $sql = "UPDATE radars SET `date` = '$date', `number` = '$number', `distance` = '$distance', `time` = '$time' WHERE id=$id"; $result = $connection->query($sql); if(!$result){ die("Failed: " . $connection->error); } } ?> <form action="" method="post"> <label for="date">Date</label> <input type="datetime-local" name="date" required> <label for="number">Number</label> <input type="text" name="number" required> <label for="distance">Distance</label> <input type="int" name="distance" required> <label for="time">Time</label> <input type="int" name="time" required> <br> <?php // show all records from DB in dropdown $sql = "SELECT * FROM `radars` ORDER BY `id` ASC"; $result = $connection->query($sql); if(!$result){ die("Failed: " . $connection->error); } ?> <br> <?php if(!isset($_POST['deleteall'])): ?> <select name="id"> <?php while ($row = mysqli_fetch_assoc($result)) { $id = $row['id']; $date = $row['date']; $number = $row['number']; $distance = $row['distance']; $time = $row['time']; echo "<option value='$id'> id=$id; date=$date; number=$number; distance=$distance; time=$time; </option>"; } ?> </select> <?php endif; ?> <br><br> <button class="btn btn-warning" type="submit" name="submit1">Update</button> <br><br> </form> <h1>Delete record</h1> <?php //delete one of the records if(isset($_POST['delete'])) { $id = $_POST['id']; $sql = "DELETE FROM radars WHERE id = $id"; $result = $connection->query($sql); if(!$result){ die("Failed: " . $connection->error); } } elseif (isset($_POST['deleteall'])) { $id = $_POST['id']; $sql = "DELETE FROM radars"; $result = $connection->query($sql); if(!$result){ die("Failed: " . $connection->error); } } ?> <form action="" method="post"> <?php // show all records from DB in dropdown $sql = "SELECT * FROM `radars` ORDER BY `id` ASC"; $result = $connection->query($sql); if(!$result){ die("Failed: " . $connection->mysqli_error); } ?> <br> <?php if($result->num_rows > 0): ?> <select name="id"> <?php while ($row = mysqli_fetch_assoc($result)) { $id = $row['id']; $date = $row['date']; $number = $row['number']; $distance = $row['distance']; $time = $row['time']; echo "<option value='$id'> id=$id; date=$date; number=$number; distance=$distance; time=$time; </option>"; } ?> </select> <?php endif; ?> <br><br> <button class="btn btn-danger" type="submit" name="delete">Delete</button> <button class="btn btn-danger" type="submit" name="deleteall">DeleteAll</button> <br><br> </form> <?php // print all records from DB $query = 'SELECT *, `distance` / `time` * 3.6 AS `speed` FROM `radars` ORDER BY `id` ASC'; if(!($result = $connection->query($query))) { die("Error: " . $connection->error); } ?> <?php if($result->num_rows > 0): ?> <table class="table table-bordered"> <tr> <th>ID</th> <th>Data</th> <th>Number</th> <th>Distance</th> <th>Time</th> <th>Speed km/h</th> </tr> <?php while($row = mysqli_fetch_assoc($result)): ?> <tr> <td><?php echo $row['id'] ?></td> <td><?php echo $row['date'] ?></td> <td><?php echo $row['number'] ?></td> <td><?php echo $row['distance'] ?></td> <td><?php echo $row['time'] ?></td> <td><?php echo round($row['speed'], 1) ?></td> </tr> <?php endwhile; ?> </table> <?php else: echo "DB nera duomenu." ?> <?php endif; ?> <?php $connection->close(); ?> <a class="btn btn-info" href="automobiliai.php">Automobiliai</a> <a class="btn btn-success" href="metai.php">Metai</a> <a class="btn btn-success" href="menuo.php">Menuo</a> <br><br> </body> </html>
C
UTF-8
875
3.4375
3
[]
no_license
//Author: Lily Jim //Credits: Lab Instructor helped with steps needed //UO CIS 314 Fall 2018 #include <stdio.h> //x=12345678, y=0xABCDEF00 //z=1234EF00, bytes 3 and 2 from x and bytes 1 and 0 from y //want x = 0x12340000 and y = 0x0000EF00 //x = 0001 0010 0011 0100 0101 0110 0111 1000 //mask = 1111 1111 1111 1111 0000 0000 0000 0000 = FFFF0000 //x&mask=0001 0010 0011 0100 0000 0000 0000 0000 = 12340000 //y = //mask = 0000 0000 0000 0000 1111 1111 1111 1111 //y&mask=0000 0000 0000 0000 1110 1111 0000 0000 = 0000EF00 //x|y = 0001 0010 0110 0100 1110 1111 0000 0000 = 1234EF00 unsigned int combine(unsigned int x, unsigned int y){ unsigned int x2 = x & 0xFFFF0000; unsigned int y2 = y & 0x0000FFFF; unsigned int xy = x2 | y2; printf("%X\n", xy); return xy; } void main(){ combine(0x12345678, 0xABCDEF00); combine(0xABCDEF00, 0x12345678); }
C++
UTF-8
3,459
3.046875
3
[]
no_license
/***************************************** ** File: Reversi.cpp ** Project: CMSC 202 Project 4, Sprig 2014 ** Author: Christopher Stephen Sidell ** Date: 4/19/2014 ** Section: 11 / 15 ** E-mail: csidell1@umbc.edu ** * This file contains all the rules and definitions for the game * of reversi. ** ***********************************************/ #include <iostream> #include <cstring> #include <cstdlib> #include "Reversi.h" using namespace std; //Reversi //Default (no-arg) constructor Reversi::Reversi() : GridGame(GAME_REVERSI, "Reversi",REVERSI_BOARD_SIZE) { m_playerSymbols = "XO"; } //Reversi //Custom constructor constructor Reversi::Reversi(const char *playerSymbols) : GridGame(GAME_REVERSI, "Reversi",REVERSI_BOARD_SIZE) { m_playerSymbols = playerSymbols; } //~Reversi //Default constructor Reversi::~Reversi() { //Nothing to destroy } //DoMove //Puts new piece for player at {row, col} position void Reversi::DoMove(int player, int row, int col) { int rowIncr, colIncr; char playerSym = GetPlayerSymbol(player); DoBasicMove(player, row, col); for (rowIncr = -1; rowIncr <= 1; rowIncr++) { for (colIncr = -1; colIncr <= 1; colIncr++) { if (rowIncr || colIncr) { // Going in some direction FlipTilesInDir(playerSym, row, rowIncr, col, colIncr); } } } } //FlipTilesInDir //Flip all board pieces if reversi conditions are met void Reversi::FlipTilesInDir(char playerSym, int row, int rowIncr, int col, int colIncr) { int r, c; int boardSize = GetBoardSize(); for (r = row + rowIncr, c = col + colIncr; InBounds(r, c, boardSize); r += rowIncr, c += colIncr) { if (m_board[r][c] == '-') { break; } else if (m_board[r][c] == playerSym) { // We found a range of pieces to flip--Work backwards flipping // Note: in following, need to test both r and c, since one or // other might not be changing for (r -= rowIncr, c -= colIncr; r != row || c!= col; r -= rowIncr, c -= colIncr) { m_board[r][c] = playerSym; } return; } } } //IsDone //Checks whether the game is over bool Reversi::IsDone() const { int boardSize = GetBoardSize(); for (int r = 0; r < boardSize; r++) { for (int c = 0; c < boardSize; c++) { if (m_board[r][c] == '-') { return false; } } } return true; } //OutputResults //Print the final winning information void Reversi::OutputResults() const { int count[2]; char playerSym[2]; int boardSize = GetBoardSize(); count[0] = count[1] = 0; playerSym[0] = GetPlayerSymbol(0); playerSym[1] = GetPlayerSymbol(1); // Tabulate results for (int r = 0; r < boardSize; r++) { for (int c = 0; c < boardSize; c++) { for (int s = 0; s < 2; s++) { if (m_board[r][c] == playerSym[s]) { ++(count[s]); } } } } // Finally, find highest score for (int s = 0; s < 2; s++) { cout << "Player " << playerSym[s] << " controls " << count[s] << " squares.\n"; } if (count[0] > count[1]) { cout << "Player " << playerSym[0] << " wins!\n"; } else if (count[1] > count[0]) { cout << "Player " << playerSym[1] << " wins!\n"; } else { cout << "The game is a tie\n"; } }
PHP
UTF-8
8,819
2.828125
3
[]
no_license
<?php class ResourceType { /** * @var string */ public $id; /** * @var string */ public $title; /** * Тип ресурса * bonuce - дающий + к добыче клетки * luxury - роскошь * mineral - полезное ископаемое * @var string */ public $type = 'bonuce'; /** * Бонус к еде * @var int */ public $eat = 0; /** * Бонус к производству * @var int */ public $work = 0; /** * Бонус к деньгам * @var int */ public $money = 0; /** * Требуемые исследования * @var array */ public $req_research = []; /** * На каких типах местности может распологаться * @var array */ public $cell_types = []; /** * Шанс генерации ресурса на клетках соответсвующих типов * @var float */ public $chance = 0.01; /** * Сколько минимум появляется ресурса(на сколько ходов) * @var int */ public $min_amount = 50; /** * На сколько максимумм появляется ресурса(на сколько ходов) * @var int */ public $max_amount = 500; public static $all; public static function get($id) { if (isset(ResourceType::$all[$id])) { return ResourceType::$all[$id]; } else { return false; } } public function __construct($data) { foreach ($data as $field => $value) { $this->$field = $value; } ResourceType::$all[$this->id] = $this; } public function get_title() { return $this->title; } /** * Проверяет может ли данный игрок видеть и использовать такой ресурс * @param User $user * @return bool */ public function can_use($user) { if (count($this->req_research) == 0) { return true; } $uresearch = $user->get_research(); foreach ($this->req_research as $research) { if (!isset($uresearch[$research->id])) { return false; } } return true; } } new ResourceType([ 'id' => 'iron', 'title' => 'железо', 'type' => 'mineral', 'work' => 2, 'money' => 1, 'chance' => 0.015, 'req_research' => [ ResearchType::get(7) // Обработка железа ], 'cell_types' => [ CellType::get('hills'), CellType::get('mountains') ] ]); new ResourceType([ 'id' => 'horse', 'title' => 'лошади', 'type' => 'mineral', 'work' => 1, 'money' => 1, 'chance' => 0.02, 'req_research' => [ ResearchType::get(4) // Верховая езда ], 'cell_types' => [ CellType::get('plains'), CellType::get('plains2') ] ]); new ResourceType([ 'id' => 'coal', 'title' => 'уголь', 'type' => 'mineral', 'work' => 2, 'money' => 1, 'req_research' => [ //ResearchType::get(4) // Верховая езда ], 'cell_types' => [ CellType::get('hills'), CellType::get('mountains') ] ]); new ResourceType([ 'id' => 'oil', 'title' => 'нефть', 'type' => 'mineral', 'work' => 2, 'money' => 2, 'req_research' => [ //ResearchType::get(4) // Верховая езда ], 'cell_types' => [ CellType::get('desert'), CellType::get('plains'), CellType::get('plains2') ] ]); new ResourceType([ 'id' => 'saltpetre', 'title' => 'селитра', 'type' => 'mineral', 'work' => 2, 'money' => 1, 'req_research' => [ //ResearchType::get(4) // Верховая езда ], 'cell_types' => [ CellType::get('desert'), CellType::get('plains'), CellType::get('plains2'), CellType::get('hills'), CellType::get('mountains') ] ]); new ResourceType([ 'id' => 'rubber', 'title' => 'резина', 'type' => 'mineral', 'work' => 1, 'money' => 2, 'req_research' => [ //ResearchType::get(4) // Верховая езда ], 'cell_types' => [ CellType::get('desert'), CellType::get('plains'), CellType::get('plains2'), CellType::get('mountains') ] ]); new ResourceType([ 'id' => 'uranium', 'title' => 'уран', 'type' => 'mineral', 'work' => 1, 'money' => 1, 'req_research' => [ //ResearchType::get(4) // Верховая езда ], 'cell_types' => [ CellType::get('desert'), CellType::get('hills'), CellType::get('mountains') ] ]); new ResourceType([ 'id' => 'vine', 'title' => 'виноград', 'type' => 'luxury', 'eat' => 1, 'money' => 2, 'chance' => 0.02, 'cell_types' => [ CellType::get('plains'), CellType::get('plains2') ] ]); new ResourceType([ 'id' => 'ivory', 'title' => 'слоновая кость', 'type' => 'luxury', 'work' => 1, 'money' => 2, 'cell_types' => [ CellType::get('desert') ] ]); new ResourceType([ 'id' => 'silk', 'title' => 'шёлк', 'type' => 'luxury', 'work' => 2, 'money' => 1, 'chance' => 0.02, 'cell_types' => [ CellType::get('plains'), CellType::get('plains2'), CellType::get('hills') ] ]); new ResourceType([ 'id' => 'furs', 'title' => 'меха', 'type' => 'luxury', 'work' => 1, 'eat' => 1, 'money' => 1, 'cell_types' => [ CellType::get('forest') ] ]); new ResourceType([ 'id' => 'fish', 'title' => 'рыба', 'type' => 'bonuce', 'chance' => 0.05, 'eat' => 2, 'cell_types' => [ CellType::get('water1') ] ]); new ResourceType([ 'id' => 'whale', 'title' => 'киты', 'type' => 'bonuce', 'chance' => 0.03, 'eat' => 1, 'money' => 1, 'cell_types' => [ CellType::get('water2') ] ]);
Python
UTF-8
11,258
3.1875
3
[]
no_license
from enum import Enum import random import re import queue random.seed(3) class Action(Enum): Forward = 1, Turn_Left = 2, Turn_Right = 3, Grab_Gold = 4, Shoot = 5, Climb = 6 class Tile: def __init__(self, x, y): self.posX = x self.posY = y self.pit = False self.breeze = False self.wumpus = False self.stench = False self.gold = False self.glitter = False self.agent = False def makeEffectName(self, effect): return effect + str(self.posX + 1) + "," + str(self.posY + 1) def getSensorValues(self): sensor = [] if self.stench: sensor.append(self.makeEffectName("s")) else: sensor.append(self.makeEffectName("!s")) if self.breeze: sensor.append(self.makeEffectName("b")) else: sensor.append(self.makeEffectName("!b")) if self.glitter: sensor.append(self.makeEffectName("g")) else: sensor.append(self.makeEffectName("!g")) return sensor def toPitString(self): if self.pit: return "p" elif self.breeze: return "b" else: return " " def toWumpusString(self): if self.wumpus: return "w" elif self.stench: return "s" else: return " " def toGoldString(self): if self.gold: return "g" else: return " " def toAgentString(self): if self.agent: return "a" else: return " " class AgentState: def __init__(self, x, y, direction, hasGold, hasArrow): self.x = x self.y = y self.dir = direction self.hasArrow = hasGold self.hasGold = hasArrow def getAgentPos(self): return (self.x, self.y) def getNextState(self, action): if action == Action.Forward: if self.dir == 0: #East return AgentState(self.x + 1, self.y + 0, self.dir, self.hasGold, self.hasArrow) elif self.dir == 1: #South return AgentState(self.x + 0, self.y + 1, self.dir, self.hasGold, self.hasArrow) elif self.dir == 2: #West return AgentState(self.x - 1, self.y + 0, self.dir, self.hasGold, self.hasArrow) elif self.dir == 3: #North return AgentState(self.x + 0, self.y - 1, self.dir, self.hasGold, self.hasArrow) else: raise Exception("Invalid direction: " + self.dir) elif action == Action.Turn_Left: return AgentState(self.x, self.y, (self.dir - 1 + 4) % 4, self.hasGold, self.hasArrow) elif action == Action.Turn_Right: return AgentState(self.x, self.y, (self.dir + 1 - 4) % 4, self.hasGold, self.hasArrow) elif action == Action.Grab_Gold: return AgentState(self.x, self.y, self.dir, True, self.hasArrow) elif action == Action.Shoot: return AgentState(self.x, self.y, self.dir, self.hasGold, False) else: raise Exception("Invalid action.") def __eq__(self, value): return value and type(value) is AgentState and self.x == value.x and self.y == value.y and self.dir == value.dir def __ne__(self, value): return not self.__eq__(value) def __hash__(self): tt = (self.x, self.y, self.dir) return hash(tt) class WunpusGame: def __init__(self): self.width = 4 self.height = 4 self.agent = AgentState(1, 1, 1, True, False) self.isAgentAlive = True self.performance = 0 self.agentBumpedIntoWall = False self.wumpusJustDied = False self.isRunning = True self.visitedPositions = {self.agent.getAgentPos()} self.safePositions = {self.agent.getAgentPos()} self.generateRandomWorld() def generateRandomWorld(self): self.world = [] for x in range(self.width): self.world.append([]) for y in range(self.height): self.world[x].append(Tile(x, y)) for x in range(self.width): for y in range(self.height): pitX = x + 1 pitY = y + 1 #starting pos can't be a pit if not (pitX == 1 and pitY == 1): if random.randint(1, 10) <= 2: self.world[x][y].pit = True self.addSurroundingEffects(pitX, pitY, "breeze") self.addEntityWithEffectToWorld("gold", "glitter") self.addEntityWithEffectToWorld("wumpus", "stench") self.addEntityWithEffectToWorld("wumpus", "stench") self.world[0][0].agent = True def addEntityWithEffectToWorld(self, entity, effect): entityX = random.randint(1, self.width) entityY = random.randint(1, self.height) setattr(self.world[entityX - 1][entityY - 1], entity, True) self.addSurroundingEffects(entityX, entityY, effect) def getSurroundingPositions(self, x, y): if self.isWithinWorld(x + 1, y + 0): yield (x + 1, y + 0) if self.isWithinWorld(x - 1, y + 0): yield (x - 1, y + 0) if self.isWithinWorld(x + 0, y + 1): yield (x + 0, y + 1) if self.isWithinWorld(x + 0, y - 1): yield (x + 0, y - 1) def addSurroundingEffects(self, x, y, effect): for pos in self.getSurroundingPositions(x, y): self.addEffectIfInWorld(pos[0], pos[1], effect) def isWithinWorld(self, x, y): return x >= 1 and x <= self.width and y >= 1 and y <= self.height def addEffectIfInWorld(self, x, y, effect): if self.isWithinWorld(x, y): setattr(self.world[x - 1][y - 1], effect, True) def action(act): pass def getSensorValues(self): sensorValues = self.world[self.agent.x - 1][self.agent.y - 1].getSensorValues() if self.agentBumpedIntoWall: sensorValues.append("Bump") else: sensorValues.append("!Bump") if self.wumpusJustDied: sensorValues.append("Scream") else: sensorValues.append("!Scream") return sensorValues def didAgentJustDie(self): tile = self.world[self.agent.x - 1][self.agent.y - 1] return tile.wumpus or tile.pit def getNextAction(self, knowledge): glitterLiteral = "g{0},{1}".format(self.agent.x, self.agent.y) if not self.agent.hasGold and knowledge.resolution(glitterLiteral): return Action.Grab_Gold else: #If there are no safe spaces that hasn't been visited then all other spaces #must be certain death. The best course of action in that case is to go #back to spawn and exit the cave goBackToSpawn = self.safePositions.intersection(self.visitedPositions) frontier = queue.Queue() frontierSet = set() expandedSet = set() frontier.put((None, self.agent)) actionBackToSpawn = None while not frontier.empty(): leaf = frontier.get() if leaf[1] == (1, 1) and goBackToSpawn: actionBackToSpan = leaf[0] break #If the agent is in a new unknown position then stop searching #as the agent has found a new safe and unknown position to go to. if not leaf[1].getAgentPos() in self.visitedPositions: return leaf[0] #Add children #Does not handle shooting for action in [Action.Forward, Action.Turn_Left, Action.Turn_Right]: childState = self.getStateFromAction(frontierSet, expandedSet, leaf, action) if childState != None: statePos = childState[1].getAgentPos() if statePos not in frontierSet and statePos not in expandedSet: frontier.put(childState) frontierSet.add(childState) expandedSet.add(leaf) if not goBackToSpawn: raise Exception("Searching for action to do yielded no action.") #If already at spawn then climb back up. #Otherwise take the action to go back. if actionBackToSpawn == None: return Action.Climb else: return actionBackToSpawn def getStateFromAction(self, frontierSet, expandedSet, parentState, Action): stateChild = parentState[1].getNextState(Action.Forward) statePos = stateChild.getAgentPos() if self.isWithinWorld(stateChild.x, stateChild.y) and statePos in self.safePositions: if parentState[0] == None: return (Action.Forward, stateChild) else: return (parentState[0], stateChild) return None #Does not handle shooting def executeAction(self, action): if action == Action.Climb: if self.agent.getAgentPos() != (1, 1): raise Exception("Can only climb in position (1,1).") self.performance += 1000 self.isRunning = False elif action == Action.Grab_Gold: if not self.world[self.agent.x - 1][self.agent.y - 1].hasGold: raise Exception("Tried to grab the gold in a position that doesn't have the gold.") self.world[self.agent.x - 1][self.agent.y - 1].hasGold = False self.world[self.agent.x - 1][self.agent.y - 1].agent = False self.agent = self.agent.getNextState(action) self.world[self.agent.x - 1][self.agent.y - 1].agent = True self.visitedPositions.add(self.agent.getAgentPos()) if self.didAgentJustDie(): self.performance -= 1000 self.performance -= 1 def tostring(self): stringsWorld = [] for y in range(self.height + 2): stringsWorld.append("") for i in range(4): for x in range(self.width + 2): stringsWorld[0] += "#" stringsWorld[0] += " " for y in range(self.height): stringsWorld[y + 1] += "#" for x in range(self.width): stringsWorld[y + 1] += self.world[x][y].toPitString() stringsWorld[y + 1] += "# #" for x in range(self.width): stringsWorld[y + 1] += self.world[x][y].toWumpusString() stringsWorld[y + 1] += "# #" for x in range(self.width): stringsWorld[y + 1] += self.world[x][y].toGoldString() stringsWorld[y + 1] += "# #" for x in range(self.width): stringsWorld[y + 1] += self.world[x][y].toAgentString() stringsWorld[y + 1] += "#" for i in range(4): for y in range(self.width + 2): stringsWorld[len(stringsWorld) - 1] += "#" stringsWorld[len(stringsWorld) - 1] += " " stringsWorld = [" Pits Wumpus Gold Agent"] + stringsWorld return "\n".join(stringsWorld)
Java
UTF-8
1,631
2.484375
2
[]
no_license
package com.murano500k.test.beegame.model; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.NonNull; import android.util.Log; import static android.content.ContentValues.TAG; /** * Created by artem on 1/16/17. */ public class Bee implements Parcelable { private String name; private int maxHp, maxCount,oneHitDamage, hp, index; protected Bee(Parcel in) { this.name = in.readString(); this.maxHp=in.readInt(); this.maxCount=in.readInt(); this.oneHitDamage=in.readInt(); this.hp=in.readInt(); this.index=in.readInt(); } @Override public int describeContents() { return 123; } @Override public void writeToParcel(@NonNull Parcel dest, int flags) { dest.writeString(name); dest.writeInt(maxHp); dest.writeInt(maxCount); dest.writeInt(oneHitDamage); dest.writeInt(maxHp); dest.writeInt(hp); dest.writeInt(index); } public static final Parcelable.Creator<Bee> CREATOR = new Parcelable.Creator<Bee>() { @Override public Bee createFromParcel(Parcel in) { return new Bee(in); } @Override public Bee[] newArray(int size) { return new Bee[size]; } }; public Bee(String name, int maxHp, int maxCount, int oneHitDamage, int index) { this.name = name; this.maxHp=maxHp; this.maxCount=maxCount; this.oneHitDamage=oneHitDamage; this.hp=maxHp; this.index=index; } public int getIndex() { return index; } public int getHp() { Log.d(TAG, "getHp: "+hp); return hp; } public String getName() { Log.d(TAG, "getName: "+name); return name; } public void wasHit() { hp-=oneHitDamage; if(hp<0)hp=0; } }
C++
UTF-8
4,016
2.921875
3
[]
no_license
#include "pch.h" #include "Composite.h" #include <sstream> #include <algorithm> /* ---------Component defenitions--------- */ int Component::id_setter = 0; Component::Component() : dataName{ "" }, data{ "" }, parentPtr{}, isLastComponent{ true }, id{ id_setter++ } {} Component::~Component() {} Component::Component(const Component& other) : Component() { parentPtr = other.parentPtr; dataName = other.dataName; data = other.data; } Component::Component(std::string dataName, std::string data) : dataName{ dataName }, data{ data }, isLastComponent{ true }, id{ id_setter++ } { parentPtr = std::weak_ptr<Component>(); } bool Component::operator==(const Component& other) { return other.data == data; } /* ---------Leaf defenitions--------- */ Leaf::Leaf() : Component() {} Leaf::Leaf(const Leaf& other) : Component(other) {} Leaf::Leaf(std::string dataName, std::string data) : Component(dataName, data) { } bool Leaf::operator==(const Leaf& other) { return other.data == data; } std::string Leaf::str(int indent) const { std::ostringstream oss; std::string i(indent_size * indent, ' '); if (!dataName.empty()) { oss << i << "\"" << dataName << "\":"; } else { oss << i << "\"" << "..." << "\":"; } if (data.size() > 0) { oss << " \"" << data << "\""; } else { oss << " \"\""; } if (!isLastComponent) { oss << ","; } return oss.str(); } /* ---------Composite defenitions--------- */ void Composite::setPreviousNotLast() { if (auto size = components.size(); size >= 1) { auto prev_last = std::next(components.begin(), size - 1); (*prev_last)->isLastComponent = false; } } Composite::Composite() : Component() {} Composite::Composite(const Composite& other) : Component(other) {} Composite::Composite(std::string dataName) : Component(dataName, "") {} bool Composite::operator==(const Composite& other) { return other.data == data; } std::string Composite::str(int indent) const { std::ostringstream oss; std::string i(indent_size * indent, ' '); // composite begin if (dataName.empty()) { oss << i << "{" << std::endl; } else { oss << i << "\"" << dataName << "\":" << " [" << std::endl; } // composite body if (components.size() > 0) { for (const auto& element : components) { oss << element->str(indent + 1) << std::endl; } } else { oss << std::endl; } // composite end if (dataName.empty()) { oss << i << "}"; } else { oss << i << "]"; } if (!isLastComponent) { oss << ","; } return oss.str(); } void Composite::add(sptr_Component component) { component->isLastComponent = true; component->parentPtr = shared_from_this(); setPreviousNotLast(); components.push_back(component); } void Composite::remove(sptr_Component component) { int id = component->id; components.erase(std::remove_if(components.begin(), components.end(), [&id](sptr_Component const& pi) { return (pi->id == id); }), components.end()); } sptr_Component Composite::getChild() { sptr_Composite childes = NEW_COMPOSITE("childes_" + dataName); std::for_each(components.begin(), components.end(), [this, &childes](sptr_Component component) { if (component->parentPtr.lock() == shared_from_this()) { childes->add(component); } }); return childes; } /* ---------SharedFactory defenitions--------- */ sptr_Leaf SharedFactory::newLeaf(std::string dataName, std::string data) { return std::make_shared<Leaf>(dataName, data); } sptr_Composite SharedFactory::newComposite(std::string dataName) { return std::make_shared<Composite>(dataName); }
Python
UTF-8
2,769
2.890625
3
[]
no_license
import csv import spotipy from spotipy.oauth2 import SpotifyClientCredentials import json import numpy as np import pandas as pd from csv import writer from pandas import DataFrame # Spotify developer login credentials. Credentials are specific to each user and generally shouldn't be shared, # but if you make your own credentials.json file w/your spotify client ID and secret ID the code will still work. # (Spotify Developer page -> My Dashboard -> Login -> Create an app and the info should be displayed on your app panel) credentials = json.load(open('credentials.json')) client_id = credentials['client_id'] client_secret = credentials['client_secret'] tracks_list = [] counter = 0 i = 0 with open('test1doc.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: uri = row[2].split(':')[2] tracks_list.append(uri) counter = counter + 1 # print(tracks_list) # gives access to spotify data client_credentials_manager = SpotifyClientCredentials(client_id=client_id, client_secret=client_secret) sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) # get the audio features of each song in tracks_list results = sp.audio_features(tracks_list) # put info in a data frame and convert it to a json file. # Note: this code creates a file local to my computer but should work if you change it to be local to your device results_df = pd.DataFrame(data=results) results_df.to_json(r'C:\Users\laurafang\Desktop\Nautilus\test2.json') with open(r'C:\Users\laurafang\Desktop\Nautilus\test2.json', 'r') as f: song = json.load(f) # get all cateogry values for each audio feature for each song while i < counter: danceability = song['danceability'][str(i)] energy = song['energy'][str(i)] key = song['key'][str(i)] mode = song['mode'][str(i)] acousticness = song['acousticness'][str(i)] instrumentalness = song['instrumentalness'][str(i)] liveness = song['liveness'][str(i)] valence = song['valence'][str(i)] tempo = song['tempo'][str(i)] # open file in append mode with open('spotifytags.csv', 'a+', newline='') as write_obj: # create a writer object from the csv module csv_writer = writer(write_obj) # add contents of list as last row in the csv file if i == 0: csv_writer.writerow(['danceability', 'energy', 'key', 'mode', 'acousticness', 'instrumentalness', 'liveness', 'valence', 'tempo']) else: csv_writer.writerow([danceability, energy, key, mode, acousticness, instrumentalness, liveness, valence, tempo]) i = i + 1
Markdown
UTF-8
3,954
2.84375
3
[ "Apache-2.0" ]
permissive
Controlio ========= This is an Android app which communicates with a server on a desktop to issue commands to it by speech or touch input. These commands can be configured in a properties file on the server. The device which hosts this app needs to be on a network to talk to this server. Once started, the app needs the IP address and the port (the port can be configured according to you on the server by a GUI) on which the server is running. The server files are in the folder ControlioServer (which is a standalone Eclipse Java project). The app is tested till Android 7.0. You can find the apk file in Controlio/Controlio/app/build/outputs/apk/debug directory. The properties file has commands which are mapped to keyboard shortcuts of different OSs. It is located in ControlioServer/bin/in/control directory. Basically, there is a Java Robot class on the server which executes commands issued from the app based on the mappings it finds in the properties file. For example, on Windows OS, the command "close window" is mapped to Alt+F4. The properties file has a syntax to add commands, which is as follows: 1. Each line constitutes a command. 2. Structure of a command is as follows: [command_1] = [Key_code1]%[Key_code2]%...@[pattern]@[OS_name1], [Key_code1]%[Key_code2]%...@[pattern]@[OS_name2], ... 3. Key_code refers to a java.awt.event.KeyEvent constant for a keyboard key. For example, VK_A refers to the 'A' key, VK_ALT refers to the 'ALT' key. More could be found on http://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html/#VK_ENTER 4. A key combination is specified by a pattern in which the keys of the given combination are to be pressed. Each key can be pressed or released. A pattern is a string of english language alphabets a-z. In the order of the appearance of keys in the command, alphabets a,b,c,.. respectively are assigned to presses and releases of the respective keys. For example, for the command Alt+Tab, 'a' refers to pressing of the first key in the combination (Alt), 'b' refers to release of the first key in the combination (Alt), 'c' refers to pressing ofthe second key in the combinaton (Tab), and 'd' refers to the release of the second key in the combination (Tab). Here, if the pattern for the command Alt+Tab is 'acdb' then it means that the Alt key is first pressed (and held), then Tab is pressed (and held), then Tab is released, and finally Alt is released. 5. A command string <command_x> needs to have underscores in places of spaces, if any. 6. <OS_namex> can be "nix" (*Nix like OSs) or "win" (Windows) or "osx" (Mac OSX). 7. Two different commands can have the same key combinations. 8. A command can have many key combinations (different OSs), but only one for a particular OS. 9. '%' is the separator for keys within a single key combination. '@' is a separator between a key combination, its pattern and its OS (this order must be followed). ',' is a separator between different key combinations. Example: previous_tab= VK_CONTROL%VK_SHIFT%VK_TAB@acefdb@win, VK_CONTROL%VK_SHIFT%VK_TAB@acefdb@nix If you use 'typing mode', anything that you say using the microphone button, will be entered as it is on your desktop in the current active window. With typing mode off, you can still enter text by starting your voice command with the word 'type', and it will be entered as it is on your desktop. License ======= Apache 2.0 Copyright 2014, Zafar Ansari Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
PHP
UTF-8
8,141
3
3
[ "MIT" ]
permissive
<?php /////////////////////////////////////////////////////////////////////////////// // // DATABASE INTERFACE // // Copyright (c) 2006 Joe Leslie-Hurd, distributed under the MIT license // /////////////////////////////////////////////////////////////////////////////// require_once 'global.php'; require_once 'error.php'; require_once 'functions.php'; /////////////////////////////////////////////////////////////////////////////// // Connecting to the MySQL database /////////////////////////////////////////////////////////////////////////////// define('DATABASE_CONNECT_TRIES',2); $global_database_connection = null; function database_connection() { global $global_database_connection; if (!isset($global_database_connection)) { $tries = DATABASE_CONNECT_TRIES; while (!isset($global_database_connection)) { $global_database_connection = mysqli_connect(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD, DATABASE_NAME); if (mysqli_connect_errno()) { if (--$tries <= 0) { trigger_error('failed to connect to MySQL server: ' . mysqli_connect_error()); } $global_database_connection = null; } } } return $global_database_connection; } /////////////////////////////////////////////////////////////////////////////// // Profiling database queries. /////////////////////////////////////////////////////////////////////////////// $global_total_database_queries = 0; function total_database_queries() { global $global_total_database_queries; return $global_total_database_queries; } function increment_total_database_queries() { global $global_total_database_queries; ++$global_total_database_queries; } /////////////////////////////////////////////////////////////////////////////// // Querying the database. /////////////////////////////////////////////////////////////////////////////// function database_query($query) { $connection = database_connection(); increment_total_database_queries(); # var_dump($query); if (!($result = mysqli_query($connection,$query))) { trigger_error('MySQL error ' . mysqli_errno($connection) . ': ' . mysqli_error($connection) . "\n\n" . $query); } return $result; } /////////////////////////////////////////////////////////////////////////////// // Escaping quotes in database values. /////////////////////////////////////////////////////////////////////////////// function database_value($v) { if (!isset($v)) { return 'NULL'; } $v = addslashes($v); return ('\'' . $v . '\''); } /////////////////////////////////////////////////////////////////////////////// // Generic database tables. /////////////////////////////////////////////////////////////////////////////// class DatabaseTable { var $_table; var $_fields; var $_indexes; function table() { return $this->_table; } function fields() { return $this->_fields; } function indexes() { return $this->_indexes; } function select_unique($select_expression, $where_condition = null) { is_string($select_expression) or trigger_error('bad select_expression'); !isset($where_condition) or is_string($where_condition) or trigger_error('bad where_condition'); $result = database_query(' SELECT ' . $select_expression . ' FROM ' . $this->table() . (isset($where_condition) ? (' WHERE ' . $where_condition) : '') . ';'); if ($row = mysqli_fetch_assoc($result)) { if (mysqli_fetch_assoc($result)) { trigger_error('multiple rows'); } else { return $row; } } else { return null; } } function count_rows($where_condition = null) { $select_expression = 'COUNT(*)'; $row = $this->select_unique($select_expression, $where_condition); isset($row) or trigger_error('empty result'); return int_from_string($row[$select_expression]); } function max_rows($max_expression, $where_condition = null) { $select_expression = 'MAX(' . $max_expression . ')'; $row = $this->select_unique($select_expression, $where_condition); isset($row) or trigger_error('empty result'); return int_from_string($row[$select_expression]); } function find_row($where_condition) { is_string($where_condition) or trigger_error('bad where_condition'); $select_expression = '*'; return $this->select_unique($select_expression,$where_condition); } function is_field($field) { return array_key_exists($field, $this->_fields); } function field_type($field) { $type = $this->_fields[$field]; is_string($type) or trigger_error('bad field'); return $type; } function field_names() { $names = array(); foreach ($this->_fields as $name => $type) { $names[] = $name; } return $names; } function reset_no_indexes() { database_query('DROP TABLE IF EXISTS ' . $this->table() . ';'); $query = 'CREATE TABLE ' . $this->table() . ' ('; $first = true; foreach ($this->_fields as $field => $field_type) { if ($first) { $first = false; } else { $query .= ','; } $query .= "\n" . ' ' . $field . ' ' . $field_type; } foreach ($this->_indexes as $index) { if (preg_match('/^PRIMARY KEY/',$index)) { if ($first) { $first = false; } else { $query .= ','; } $query .= "\n" . ' ' . $index; } } $query .= "\n" . ') ENGINE=MyISAM DEFAULT CHARSET=utf8;'; database_query($query); } function reset_add_indexes() { $query = 'ALTER TABLE ' . $this->table(); $first = true; foreach ($this->_indexes as $index) { if (!preg_match('/^PRIMARY KEY/',$index)) { if ($first) { $first = false; } else { $query .= ','; } $query .= "\n" . ' ADD ' . $index; } } $query .= ';'; database_query($query); } function reset() { $this->reset_no_indexes(); $this->reset_add_indexes(); } function import_from($table) { $fields = array(); foreach ($this->field_names() as $field) { if (preg_match('/^cached_/',$field)) { $fields[] = database_value(null); } else { $fields[] = $field; } } database_query(' INSERT INTO ' . $this->table() . ' SELECT ' . implode(',',$fields) . ' FROM ' . $table . ';'); } function copy_from($table) { $this->reset_no_indexes(); $this->import_from($table); $this->reset_add_indexes(); } function DatabaseTable($table,$fields,$indexes) { is_string($table) or trigger_error('bad table name'); is_array($fields) or trigger_error('bad fields'); is_array($indexes) or trigger_error('bad indexes'); $this->_table = $table; $this->_fields = $fields; $this->_indexes = $indexes; } } /////////////////////////////////////////////////////////////////////////////// // Enumerated types. /////////////////////////////////////////////////////////////////////////////// function array_to_database_enum($values) { isset($values) or trigger_error('bad values'); $x = ''; foreach ($values as $value) { isset($value) or trigger_error('bad value'); if (strcmp($x,'') != 0) { $x .= ','; } $x .= database_value($value); } return 'enum(' . $x . ')'; } /////////////////////////////////////////////////////////////////////////////// // Booleans. /////////////////////////////////////////////////////////////////////////////// define('DATABASE_TRUE','T'); define('DATABASE_FALSE','F'); $all_database_bools = array(DATABASE_TRUE,DATABASE_FALSE); function database_bool_type() { global $all_database_bools; return array_to_database_enum($all_database_bools); } function bool_to_database_bool($bool) { if (!isset($bool)) { return null; } else { return $bool ? DATABASE_TRUE : DATABASE_FALSE; } } function bool_from_database_bool($value) { if (!isset($value)) { return null; } elseif (strcmp($value,DATABASE_TRUE) == 0) { return true; } elseif (strcmp($value,DATABASE_FALSE) == 0) { return false; } else { trigger_error('bad value'); } } ?>
SQL
UTF-8
22,866
3.09375
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.7.0 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Aug 26, 2017 at 08:34 AM -- Server version: 10.1.26-MariaDB -- PHP Version: 7.0.22 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `testapp_db` -- -- -------------------------------------------------------- -- -- Table structure for table `admin` -- CREATE TABLE `admin` ( `admin_id` int(1) NOT NULL, `fname` varchar(100) NOT NULL, `lname` varchar(100) NOT NULL, `email` varchar(100) NOT NULL, `password` varchar(255) NOT NULL, `contact` varchar(12) NOT NULL, `address` text NOT NULL, `profile_img` text NOT NULL, `createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `admin` -- INSERT INTO `admin` (`admin_id`, `fname`, `lname`, `email`, `password`, `contact`, `address`, `profile_img`, `createdAt`) VALUES (1, 'Aasif', 'Sayyad', 'ashifsayyad3@gmail.com', '123456', '9225732186', 'pune', '', '2017-08-17 07:18:15'); -- -------------------------------------------------------- -- -- Table structure for table `application` -- CREATE TABLE `application` ( `application_id` bigint(20) NOT NULL, `application_name` varchar(255) NOT NULL, `user_id` bigint(20) NOT NULL, `company_id` bigint(20) NOT NULL, `description` text NOT NULL, `added_by_name` text NOT NULL, `status` int(1) NOT NULL COMMENT '1-active,0-deactive', `createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `application` -- INSERT INTO `application` (`application_id`, `application_name`, `user_id`, `company_id`, `description`, `added_by_name`, `status`, `createdAt`) VALUES (1, 'SmartIT', 1, 1, '', '', 0, '2017-08-18 06:24:48'), (2, 'RemedyITSM', 1, 1, '', '', 0, '2017-08-18 06:22:47'), (3, 'MyIT', 1, 1, '', '', 0, '2017-08-18 06:22:50'), (13, 'SmartIT', 0, 2, '', '', 0, '2017-08-23 06:42:19'); -- -------------------------------------------------------- -- -- Table structure for table `browser` -- CREATE TABLE `browser` ( `browser_id` bigint(20) NOT NULL, `browser_name` varchar(255) NOT NULL, `company_id` bigint(20) NOT NULL, `user_id` bigint(20) NOT NULL, `added_by_name` varchar(255) NOT NULL, `status` int(1) NOT NULL COMMENT '1-active,0-deactive', `createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `browser` -- INSERT INTO `browser` (`browser_id`, `browser_name`, `company_id`, `user_id`, `added_by_name`, `status`, `createdAt`) VALUES (1, 'Chrome', 1, 1, '', 0, '2017-08-18 06:59:37'), (2, 'Chrome', 2, 0, '', 0, '2017-08-23 05:56:11'); -- -------------------------------------------------------- -- -- Table structure for table `company` -- CREATE TABLE `company` ( `company_id` bigint(20) NOT NULL, `company_name` varchar(255) NOT NULL, `user_id` bigint(20) NOT NULL, `email` varchar(100) NOT NULL, `password` varchar(255) NOT NULL, `domain` varchar(255) NOT NULL, `contact_landline` varchar(20) NOT NULL, `contact` varchar(12) NOT NULL, `address` text NOT NULL, `is_Url_add` int(1) NOT NULL COMMENT '1-added,0-not added', `status` int(1) NOT NULL COMMENT '1-active,0-deactive', `createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `company` -- INSERT INTO `company` (`company_id`, `company_name`, `user_id`, `email`, `password`, `domain`, `contact_landline`, `contact`, `address`, `is_Url_add`, `status`, `createdAt`) VALUES (1, 'My Company', 0, 'demo123@gmail.com', '518e6c76caf51eb410caab3c21def1b4b3c07401', '', '', '9225732186', 'Vishrantwadi, Pune', 0, 1, '2017-08-22 06:07:54'), (2, 'New Company', 0, 'new@gmail.com', '518e6c76caf51eb410caab3c21def1b4b3c07401', '', '', '9925789545', 'pune', 0, 1, '2017-08-23 07:08:00'), (5, 'Ms Company', 0, 'msc@gmail.com', '518e6c76caf51eb410caab3c21def1b4b3c07401', '', '', '9874589658', 'pune', 0, 1, '2017-08-23 07:21:55'); -- -------------------------------------------------------- -- -- Table structure for table `company_environment` -- CREATE TABLE `company_environment` ( `company_env_id` bigint(20) NOT NULL, `company_id` bigint(20) NOT NULL, `application_id` bigint(20) NOT NULL, `user_id` bigint(20) NOT NULL, `status` int(1) NOT NULL, `createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `company_environment` -- INSERT INTO `company_environment` (`company_env_id`, `company_id`, `application_id`, `user_id`, `status`, `createdAt`) VALUES (1, 1, 1, 0, 0, '2017-08-18 12:36:53'), (2, 1, 2, 0, 0, '2017-08-18 12:54:43'), (3, 1, 3, 0, 0, '2017-08-21 04:56:41'), (4, 2, 13, 0, 0, '2017-08-23 06:44:47'); -- -------------------------------------------------------- -- -- Table structure for table `company_environ_url` -- CREATE TABLE `company_environ_url` ( `company_environ_url_id` bigint(20) NOT NULL, `company_env_id` bigint(20) NOT NULL, `company_id` bigint(20) NOT NULL, `environment_type` varchar(255) NOT NULL, `env_url` text NOT NULL, `environment_id` bigint(20) NOT NULL, `application_id` bigint(20) NOT NULL, `user_id` bigint(20) NOT NULL, `status` int(1) NOT NULL, `createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `company_environ_url` -- INSERT INTO `company_environ_url` (`company_environ_url_id`, `company_env_id`, `company_id`, `environment_type`, `env_url`, `environment_id`, `application_id`, `user_id`, `status`, `createdAt`) VALUES (6, 1, 1, 'Production ', 'https://servicemaster-dev-smartit.onbmc.com', 1, 1, 0, 0, '2017-08-18 12:38:15'), (7, 1, 1, 'Development', 'https://servicemaster-dev-smartit.onbmc.com', 2, 1, 0, 0, '2017-08-18 12:38:19'), (8, 1, 1, 'Testing', 'https://servicemaster-dev-smartit.onbmc.com', 3, 1, 0, 0, '2017-08-19 05:21:28'), (9, 2, 1, 'Production ', 'https://servicemaster-dev-smartit.onbmc.com', 1, 2, 0, 0, '2017-08-19 05:20:50'), (10, 2, 1, 'Development', '', 2, 2, 0, 0, '2017-08-19 06:41:24'), (11, 2, 1, 'Testing', '', 3, 2, 0, 0, '2017-08-21 04:57:24'), (12, 3, 1, 'Production ', '', 1, 3, 0, 0, '2017-08-21 04:56:41'), (13, 3, 1, 'Development', '', 2, 3, 0, 0, '2017-08-21 04:56:41'), (14, 3, 1, 'Testing', 'https://servicemaster-dev-smartit.onbmc.com', 3, 3, 0, 0, '2017-08-21 04:56:42'), (15, 4, 2, 'Production', 'https://servicemaster-dev-smartit.onbmc.com', 4, 13, 0, 0, '2017-08-23 06:44:47'); -- -------------------------------------------------------- -- -- Table structure for table `email_log` -- CREATE TABLE `email_log` ( `email_log_id` bigint(20) NOT NULL, `email` varchar(255) NOT NULL, `execution_time` varchar(255) NOT NULL, `runname` varchar(255) NOT NULL, `company_id` bigint(20) NOT NULL, `user_id` bigint(20) NOT NULL, `status` int(1) NOT NULL COMMENT '0-pending,1-send', `createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `email_log` -- INSERT INTO `email_log` (`email_log_id`, `email`, `execution_time`, `runname`, `company_id`, `user_id`, `status`, `createdAt`) VALUES (1, 'demo123@gmail.com', '2017-08-22 14:48:36', 'My Company2017_08_22', 1, 1, 0, '2017-08-22 12:48:36'), (2, 'demo123@gmail.com', '2017-08-22 14:50:29', 'My Company2017_08_22', 1, 1, 0, '2017-08-22 12:50:29'), (3, 'demo123@gmail.com', '2017-08-22 15:01:21', 'My Company2017_08_22', 1, 1, 0, '2017-08-22 13:01:21'), (4, 'demo123@gmail.com', '2017-08-22 15:03:05', 'My Company2017_08_22', 1, 1, 0, '2017-08-22 13:03:05'), (5, 'demo123@gmail.com', '2017-08-22 15:04:09', 'My Company2017_08_22', 1, 1, 0, '2017-08-22 13:04:09'), (6, 'demo123@gmail.com', '2017-08-22 15:06:38', 'My Company2017_08_22', 1, 1, 0, '2017-08-22 13:06:38'), (7, 'demo123@gmail.com', '2017-08-22 15:10:23', 'My Company2017_08_22', 1, 1, 0, '2017-08-22 13:10:23'), (8, 'demo123@gmail.com', '2017-08-22 15:15:04', 'My Company2017_08_22', 1, 1, 0, '2017-08-22 13:15:04'), (9, 'demo123@gmail.com', '2017-08-22 15:43:42', 'My Company2017_08_22', 1, 1, 0, '2017-08-22 13:43:42'), (10, 'new@gmail.com', '2017-08-23 09:23:50', 'New Company2017_08_23', 2, 2, 0, '2017-08-23 07:23:50'), (11, 'new@gmail.com', '2017-08-23 09:25:49', 'New Company2017_08_23', 2, 2, 0, '2017-08-23 07:25:49'), (12, 'new@gmail.com', '2017-08-23 09:28:25', 'New Company2017_08_23', 2, 2, 0, '2017-08-23 07:28:25'), (13, 'new@gmail.com', '2017-08-23 09:30:01', 'New Company2017_08_23', 2, 2, 0, '2017-08-23 07:30:01'), (14, 'new@gmail.com', '2017-08-23 09:36:14', 'New Company2017_08_23', 2, 2, 0, '2017-08-23 07:36:14'), (15, 'new@gmail.com', '2017-08-23 09:38:14', 'New Company2017_08_23', 2, 2, 0, '2017-08-23 07:38:14'), (16, 'new@gmail.com', '2017-08-23 09:38:36', 'New Company2017_08_23', 2, 2, 0, '2017-08-23 07:38:36'), (17, 'new@gmail.com', '2017-08-23 09:39:13', 'New Company2017_08_23', 2, 2, 0, '2017-08-23 07:39:13'), (18, 'new@gmail.com', '2017-08-23 09:39:42', 'New Company2017_08_23', 2, 2, 0, '2017-08-23 07:39:42'), (19, 'new@gmail.com', '2017-08-23 09:52:25', 'New Company2017_08_23', 2, 2, 0, '2017-08-23 07:52:25'), (20, 'new@gmail.com', '2017-08-23 11:15:43', 'New Company2017_08_23', 2, 2, 0, '2017-08-23 09:15:43'), (21, 'new@gmail.com', '2017-08-23 11:17:49', 'New Company2017_08_23', 2, 2, 0, '2017-08-23 09:17:49'), (22, 'new@gmail.com', '2017-08-23 11:19:42', 'New Company2017_08_23', 2, 2, 0, '2017-08-23 09:19:42'), (23, 'new@gmail.com', '2017-08-23 11:22:05', 'New Company2017_08_23', 2, 2, 0, '2017-08-23 09:22:05'), (24, 'new@gmail.com', '2017-08-22 11:23:51', 'New Company2017_08_22', 2, 2, 0, '2017-08-23 10:24:44'); -- -------------------------------------------------------- -- -- Table structure for table `email_setting` -- CREATE TABLE `email_setting` ( `email_setting_id` bigint(20) NOT NULL, `email` varchar(255) NOT NULL, `host_name` varchar(255) NOT NULL, `port` varchar(10) NOT NULL, `username` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `secuirity_protocol` varchar(255) NOT NULL, `code` text NOT NULL, `user_id` bigint(20) NOT NULL, `company_id` bigint(20) NOT NULL, `status` int(1) NOT NULL, `createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `email_setting` -- INSERT INTO `email_setting` (`email_setting_id`, `email`, `host_name`, `port`, `username`, `password`, `secuirity_protocol`, `code`, `user_id`, `company_id`, `status`, `createdAt`) VALUES (1, 'demo123@gmail.com', 'smtp.gmail.com', '465', 'aasif1@gmail.com', '518e6c76caf51eb410caab3c21def1b4b3c07401', 'POP3', '654321', 0, 1, 0, '2017-08-21 07:29:03'), (2, 'new@gmail.com', 'smtp.gmail.com', '465', 'new@gmail.com', '518e6c76caf51eb410caab3c21def1b4b3c07401', 'SMTP', '654321', 0, 2, 0, '2017-08-23 07:21:40'); -- -------------------------------------------------------- -- -- Table structure for table `environment` -- CREATE TABLE `environment` ( `environment_id` bigint(20) NOT NULL, `environment_name` varchar(255) NOT NULL, `company_id` bigint(20) NOT NULL, `user_id` bigint(20) NOT NULL, `added_by` bigint(20) NOT NULL, `added_by_name` varchar(255) NOT NULL, `status` int(1) NOT NULL, `createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `environment` -- INSERT INTO `environment` (`environment_id`, `environment_name`, `company_id`, `user_id`, `added_by`, `added_by_name`, `status`, `createdAt`) VALUES (1, 'Production ', 1, 0, 0, 'admin', 0, '2017-08-18 06:03:31'), (2, 'Development', 1, 0, 0, 'admin', 0, '2017-08-18 06:03:35'), (3, 'Testing', 1, 0, 0, 'company', 0, '2017-08-19 05:28:38'), (4, 'Production', 2, 0, 0, 'company', 0, '2017-08-23 05:55:40'); -- -------------------------------------------------------- -- -- Table structure for table `settings` -- CREATE TABLE `settings` ( `settings_id` int(11) NOT NULL, `type` longtext CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, `description` longtext CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -- Dumping data for table `settings` -- INSERT INTO `settings` (`settings_id`, `type`, `description`) VALUES (1, 'system_name', 'Partner IT'), (2, 'system_title', 'Partner IT'), (3, 'address', 'Pune'), (4, 'phone', '9922031316'), (5, 'paypal_email', 'payment@partnerit.com'), (6, 'currency', 'INR'), (7, 'system_email', 'ashifsayyad3@gmail.com'), (8, 'buyer', ''), (9, 'purchase_code', ''), (11, 'language', 'Marathi'), (12, 'text_align', 'left-to-right'), (13, 'system_currency_id', '1'), (14, 'clickatell_user', '[YOUR CLICKATELL USERNAME]'), (15, 'clickatell_password', '[YOUR CLICKATELL PASSWORD]'), (16, 'clickatell_api_id', '[YOUR CLICKATELL API ID]'); -- -------------------------------------------------------- -- -- Table structure for table `tce_testcases_results` -- CREATE TABLE `tce_testcases_results` ( `ID` int(50) UNSIGNED NOT NULL, `RUNNAME` varchar(200) NOT NULL, `TESTCASENAME` varchar(200) NOT NULL, `EXECUTIONDATE` varchar(200) NOT NULL, `RESULT` varchar(200) NOT NULL, `ELAPSETIME` varchar(200) NOT NULL, `EXECUTEDBY` varchar(200) NOT NULL, `COMPANY` varchar(200) NOT NULL, `EMAIL` varchar(200) NOT NULL, `REASON` varchar(200) DEFAULT NULL, `AddedDate` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `testcases` -- CREATE TABLE `testcases` ( `testcase_id` bigint(20) NOT NULL, `testcase_name` varchar(255) NOT NULL, `application_id` bigint(20) NOT NULL, `company_id` bigint(20) NOT NULL, `user_id` bigint(20) NOT NULL, `status_type` int(1) NOT NULL COMMENT '0-private,1-public', `user_type` int(1) NOT NULL, `class_name` varchar(255) NOT NULL, `description` text NOT NULL, `is_Availbale` int(1) DEFAULT NULL COMMENT '1-yes,0-no', `status` int(1) NOT NULL COMMENT '1-active,0-deactive', `createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `testcases` -- INSERT INTO `testcases` (`testcase_id`, `testcase_name`, `application_id`, `company_id`, `user_id`, `status_type`, `user_type`, `class_name`, `description`, `is_Availbale`, `status`, `createdAt`) VALUES (1, 'TC_SmartIT_LoginAndLogout', 1, 1, 0, 1, 3, 'com.ServiceMaster.SmartIT.LoginAndLogoutTest', 'something something', 1, 0, '2017-08-18 07:14:35'), (2, 'TC_SmartIT_LoginAndLogout', 13, 2, 0, 1, 1, 'com.ServiceMaster.SmartIT.LoginAndLogoutTest', 'com.ServiceMaster.SmartIT.LoginAndLogoutTest', 1, 0, '2017-08-23 06:44:15'); -- -------------------------------------------------------- -- -- Table structure for table `testcase_result` -- CREATE TABLE `testcase_result` ( `testcase_result_id` bigint(20) NOT NULL, `runname` varchar(255) NOT NULL, `testcase_id` bigint(20) NOT NULL, `testcase_name` varchar(255) NOT NULL, `user_id` bigint(20) NOT NULL COMMENT 'executed_by', `application_id` bigint(20) NOT NULL, `compnay_id` bigint(20) NOT NULL, `browser_id` bigint(20) NOT NULL, `email` varchar(255) NOT NULL, `execution_date` varchar(255) NOT NULL, `elapse_time` varchar(255) NOT NULL, `result` int(1) NOT NULL COMMENT '1-passed,0-failed', `reason` text NOT NULL, `createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `user` -- CREATE TABLE `user` ( `user_id` bigint(20) NOT NULL, `user_type` int(1) NOT NULL COMMENT 'Adm.-1,Company-2,Tester-3', `company_id` bigint(20) NOT NULL, `fname` varchar(100) NOT NULL, `lname` varchar(100) NOT NULL, `email` varchar(100) NOT NULL, `password` varchar(255) NOT NULL, `designation` text NOT NULL, `user_name` varchar(100) NOT NULL, `contact` varchar(12) NOT NULL, `address` text NOT NULL, `profile_img` text NOT NULL, `description` text NOT NULL, `added_by` bigint(20) NOT NULL COMMENT 'created_by', `added_by_name` varchar(255) NOT NULL, `createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `status` int(1) NOT NULL COMMENT 'active-1,deactive-0' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `user` -- INSERT INTO `user` (`user_id`, `user_type`, `company_id`, `fname`, `lname`, `email`, `password`, `designation`, `user_name`, `contact`, `address`, `profile_img`, `description`, `added_by`, `added_by_name`, `createdAt`, `status`) VALUES (1, 3, 1, 'Aasif', 'Sayyad', 'aasif@gmail.com', '518e6c76caf51eb410caab3c21def1b4b3c07401', '', '', '9922031316', 'pune', '', '', 1, 'admin', '2017-08-21 08:53:42', 0), (4, 1, 1, 'Rohit ', 'Patil', 'rohit123@gmail.com', '05363a5ee688775720b55ad84b46e2158407dcda', '', '', '9874561230', 'pune', '', '', 1, 'admin', '2017-08-18 07:01:24', 0), (5, 1, 1, 'Rohit', 'Sharma', 'sharma@gmail.com', '518e6c76caf51eb410caab3c21def1b4b3c07401', '', '', '9856859855', 'pune', '', '', 1, 'admin', '2017-08-18 07:01:28', 0), (6, 1, 1, 'Samir', 'Tripathy', 'samir@gmail.com', '518e6c76caf51eb410caab3c21def1b4b3c07401', '', '', '9225733218', 'pune', '', '', 0, 'company', '2017-08-18 17:10:39', 0), (7, 3, 2, 'Rohit', 'Patil', 'rohit@gmail.com', '518e6c76caf51eb410caab3c21def1b4b3c07401', '', '', '9874568596', 'pune', '', '', 0, 'company', '2017-08-23 05:54:42', 0); -- -- Indexes for dumped tables -- -- -- Indexes for table `admin` -- ALTER TABLE `admin` ADD PRIMARY KEY (`admin_id`); -- -- Indexes for table `application` -- ALTER TABLE `application` ADD PRIMARY KEY (`application_id`), ADD KEY `user_id` (`user_id`), ADD KEY `company_id` (`company_id`), ADD KEY `user_id_2` (`user_id`), ADD KEY `user_i` (`user_id`); -- -- Indexes for table `browser` -- ALTER TABLE `browser` ADD PRIMARY KEY (`browser_id`), ADD KEY `company_id` (`company_id`), ADD KEY `user_id` (`user_id`); -- -- Indexes for table `company` -- ALTER TABLE `company` ADD PRIMARY KEY (`company_id`), ADD UNIQUE KEY `company_name` (`company_name`), ADD UNIQUE KEY `email` (`email`), ADD KEY `user_id` (`user_id`); -- -- Indexes for table `company_environment` -- ALTER TABLE `company_environment` ADD PRIMARY KEY (`company_env_id`), ADD KEY `company_id` (`company_id`), ADD KEY `application_id` (`application_id`), ADD KEY `user_id` (`user_id`); -- -- Indexes for table `company_environ_url` -- ALTER TABLE `company_environ_url` ADD PRIMARY KEY (`company_environ_url_id`), ADD KEY `company_env_id` (`company_env_id`), ADD KEY `environment_id` (`environment_id`), ADD KEY `application_id` (`application_id`), ADD KEY `user_id` (`user_id`), ADD KEY `company_id` (`company_id`); -- -- Indexes for table `email_log` -- ALTER TABLE `email_log` ADD PRIMARY KEY (`email_log_id`), ADD KEY `company_id` (`company_id`), ADD KEY `user_id` (`user_id`); -- -- Indexes for table `email_setting` -- ALTER TABLE `email_setting` ADD PRIMARY KEY (`email_setting_id`), ADD KEY `user_id` (`user_id`), ADD KEY `company_id` (`company_id`); -- -- Indexes for table `environment` -- ALTER TABLE `environment` ADD PRIMARY KEY (`environment_id`), ADD KEY `company_id` (`company_id`), ADD KEY `user_id` (`user_id`), ADD KEY `admin_id` (`added_by`); -- -- Indexes for table `settings` -- ALTER TABLE `settings` ADD PRIMARY KEY (`settings_id`); -- -- Indexes for table `tce_testcases_results` -- ALTER TABLE `tce_testcases_results` ADD PRIMARY KEY (`ID`); -- -- Indexes for table `testcases` -- ALTER TABLE `testcases` ADD PRIMARY KEY (`testcase_id`), ADD KEY `application_id` (`application_id`), ADD KEY `company_id` (`company_id`), ADD KEY `user_id` (`user_id`); -- -- Indexes for table `testcase_result` -- ALTER TABLE `testcase_result` ADD PRIMARY KEY (`testcase_result_id`), ADD KEY `testcase_id` (`testcase_id`), ADD KEY `user_id` (`user_id`), ADD KEY `company_id` (`compnay_id`), ADD KEY `application_id` (`application_id`), ADD KEY `browser_id` (`browser_id`); -- -- Indexes for table `user` -- ALTER TABLE `user` ADD PRIMARY KEY (`user_id`), ADD KEY `company_id` (`company_id`), ADD KEY `user_id` (`added_by`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `admin` -- ALTER TABLE `admin` MODIFY `admin_id` int(1) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `application` -- ALTER TABLE `application` MODIFY `application_id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14; -- -- AUTO_INCREMENT for table `browser` -- ALTER TABLE `browser` MODIFY `browser_id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT for table `company` -- ALTER TABLE `company` MODIFY `company_id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; -- -- AUTO_INCREMENT for table `company_environment` -- ALTER TABLE `company_environment` MODIFY `company_env_id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT for table `company_environ_url` -- ALTER TABLE `company_environ_url` MODIFY `company_environ_url_id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=16; -- -- AUTO_INCREMENT for table `email_log` -- ALTER TABLE `email_log` MODIFY `email_log_id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=25; -- -- AUTO_INCREMENT for table `email_setting` -- ALTER TABLE `email_setting` MODIFY `email_setting_id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT for table `environment` -- ALTER TABLE `environment` MODIFY `environment_id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT for table `settings` -- ALTER TABLE `settings` MODIFY `settings_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=17; -- -- AUTO_INCREMENT for table `tce_testcases_results` -- ALTER TABLE `tce_testcases_results` MODIFY `ID` int(50) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=345; -- -- AUTO_INCREMENT for table `testcases` -- ALTER TABLE `testcases` MODIFY `testcase_id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT for table `testcase_result` -- ALTER TABLE `testcase_result` MODIFY `testcase_result_id` bigint(20) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `user` -- ALTER TABLE `user` MODIFY `user_id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Java
UTF-8
5,963
3.265625
3
[]
no_license
package pda.datas.datasDames; /**La classe Coup décrit le mouvement d'une piece : coordonnées d'arrivée, piecePrise. *Un pion peut effectuer plusieurs coup pendant un tour s'il peut effectuer plusieurs prises. *<BR>Elle permet aussi d'évaluer la qualité du coup d'un point de vue stratégique avec un système de points. */ public class Coup { // Attributs /** * Coordonnées de la case d'arrivée de la pièce. */ private Coordonnee arrivee; /** * Piece qui effectue le coup */ private Piece piece; /** * Piece abattue pendant le coup, vaut null si aucune pièce n'est abattue. */ private Piece piecePrise; /** * Nombre de points que vaut le coup, permet d'évaluer si le coup est bon à jouer d'un point de vue stratégique. */ private int nbPoints; // Constructeur /** * Constructeur de la classe Coup * @param piece piece qui effectue le coup * @param arrivee coordonnées de la case d'arrivée de la piece */ public Coup(Piece piece, Coordonnee arrivee){ this.arrivee = arrivee; this.piece = piece; this.piecePrise = findPiecePrise(); this.nbPoints = calculerPoints(); } // Méthodes /** * Calcule le nombre de points de ce Coup. *<BR>Le calcul se bases sur plusieurs critères comme le nombre de pièce prises, la vulnérabilité de la pièce *<BR>avant ou après le coup, la possibilité pour un pion de se transformer en Dame. */ public int calculerPoints(){ int points =0; if(piecePrise!=null){ points = points + 10; } if(transformDame()){ points = points + 20; } if(makeVulnerable()){ points = points - 9; } if(isVulnerable()){ points = points + 9; } return points; } /** * Indique si le coup donne à la pièce la possibilité de se transformer en Dame. * @return transformDame vaut vrai si la pièce est un pion et qu'il permet de se transformer en dame, faux sinon. */ public boolean transformDame(){ boolean transformDame = false; // Si la piece n'est pas deja une dame if(!piece.isDame()){ if(piece.isIA()){ if(this.arrivee.getY()==this.piece.getPlateau().getTaille()-1){ transformDame = true; } } else{ if(this.arrivee.getY()==0){ transformDame = true; } } } return transformDame; } /** * Indique si le coup met en danger la pièce. * @return makeVulnerable vaut vrai si la pièce sera vulnérable lorsqu'elle aura effectué ce Coup, faux sinon */ private boolean makeVulnerable(){ boolean makeVulnerable = false; Plateau plateau = this.piece.getPlateau(); Piece[][] tabPiece = plateau.getTabPiece(); boolean existsPiecePrise = false; // S'ily a une piece prise, on la supprime (temporairement pour la simulation) if(piecePrise!=null){ plateau.deletePiece(this.piecePrise); existsPiecePrise = true; } if(this.piece.isVulnerable(this.arrivee)){ makeVulnerable = true; } if(existsPiecePrise){ tabPiece[piecePrise.getCoordonnee().getX()][piecePrise.getCoordonnee().getY()] = piecePrise; } return makeVulnerable; } /** * Indique si la pièce est en danger * @return isVulnerable vaut vrai si la pièce est en danger, faux sinon. */ private boolean isVulnerable(){ boolean isVulnerable = false; if(this.piece.isVulnerable()){ isVulnerable = true; } return isVulnerable; } /** * Indique la pièce qui sera prise pendant ce coup. * @return piecePrise la pièce qui sera prise pendant ce coup, null si aucune prise n'est faite */ public Piece findPiecePrise(){ Piece piecePrise = null; Plateau plateau = this.piece.getPlateau(); int departX = this.piece.getCoordonnee().getX(); int departY = this.piece.getCoordonnee().getY(); int arriveeX = this.arrivee.getX(); int arriveeY = this.arrivee.getY(); int dirX; int dirY; if((arriveeX-departX)>=0) dirX = 1; else dirX = -1; if((arriveeY-departY)>=0) dirY = 1; else dirY = -1; Coordonnee coordTmp = new Coordonnee(departX,departY); Piece pieceTmp = null; do{ coordTmp.setX(coordTmp.getX()+dirX); coordTmp.setY(coordTmp.getY()+dirY); pieceTmp = plateau.getPiece(coordTmp); // Si c'est une piece adverse if(pieceTmp!= null && pieceTmp.isIA()!=this.piece.isIA()){ piecePrise = pieceTmp; } }while(pieceTmp==null && plateau.isValide(coordTmp) && plateau.isValide(coordTmp) && !coordTmp.equals(this.arrivee)); return piecePrise; } // Accesseurs /** * Accesseur de l'attribut nbPoints * @return l'attribut nbPoints */ public int getNbPoints(){ return this.nbPoints; } /** * Accesseur des coordonnées de l'attribut Piece * @return les coordonnées de l'attribut Piece */ public Coordonnee getDepart(){ return this.piece.getCoordonnee(); } /** * Accesseur de l'attribut arrivee * @return l'attribut arrivee */ public Coordonnee getArrivee(){ return this.arrivee; } /** * Accesseur de l'attribut piece * @return l'attribut piece */ public Piece getPiece(){ return this.piece; } /** * Accesseur de l'attribut piecePrise * @return l'attribut piecePrise */ public Piece getPiecePrise(){ return this.piecePrise; } public String toString(){ String chaine = "______________ "+this.piece.isIA()+" ______________\n"; chaine = chaine + "Départ : "+this.piece.getCoordonnee().toString()+"\n"; chaine = chaine + "Arrivée : "+this.arrivee.toString()+"\n"; if(piecePrise==null){ chaine = chaine + "Pas de prise.\n"; } else{ chaine = chaine + "Piece prise : "+this.piecePrise.getCoordonnee().toString()+"\n"; } chaine = chaine + this.nbPoints+" points\n"; chaine = chaine + "______________________________________\n"; return chaine; } }
C#
UTF-8
4,657
2.875
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Diagnostics; using System.IO; namespace MultiLaunch { class Processes { List<Tuple<Process, ProcessButton>> runningProcs = new List<Tuple<Process, ProcessButton>>(); public bool RunProcess(ProcessButton button) { try { Process[] procs = Process.GetProcessesByName(button.FileName); Process proc; if (procs.Length == 0) //if the program is not currently running proc = Process.Start(button.FilePath); else proc = procs[0]; //get process from open processes. this doesn't always work with programs that run multiple processes, maybe ill fix eventually if im not lazy var tuple = new Tuple<Process, ProcessButton>(proc, button); runningProcs.Add(tuple); Debug.WriteLine("Added " + proc.ToString() + " to runningProcs list"); proc.EnableRaisingEvents = true; proc.Exited += process_Exited; button.SetRunning(true); } catch (Exception ex) { return false; MessageBox.Show("Could not run program\n" + ex.ToString()); } return true; } public void StopProcess(ProcessButton button) { var toKill = isButtonInList(button); toKill.Item1.Kill(); } public void RemoveProcess(ProcessButton button) { var butInList = isButtonInList(button); if(butInList != null) { runningProcs.Remove(butInList); } } public void OpenRunningProcsList() { Form procForm = new Form(); Label procLbl = new Label(); procLbl.AutoSize = true; foreach(var proc in runningProcs.ToList()) { procLbl.Text += proc.Item1.ToString() + "\n"; } procForm.Controls.Add(procLbl); procForm.Show(); } public void StopAllRunning() { foreach(var proc in runningProcs) { proc.Item1.Kill(); } } public void OpenRunningProcesses() { Form procForm = new Form(); Label procLbl = new Label(); procLbl.AutoSize = true; foreach (var proc in GetRunning().ToList()) { procLbl.Text += proc.ProcessName + "\n"; } procForm.Controls.Add(procLbl); procForm.Show(); } public bool isAlreadyRunning(ProcessButton button) { if(isButtonInList(button) == null) { return false; } return true; } public void CheckRunningProcesses(List<ProcessButton> buttons) //switched to for loops because foreach loops were slowing ui { Process[] running = GetRunning(); for(int i = 0; i < buttons.Count; i++) { if (isButtonInList(buttons[i]) != null) continue; for(int j = 0; j < running.Length; j++) { if(buttons[i].FileName == running[j].ProcessName) { RunProcess(buttons[i]); break; } } } } private Tuple<Process, ProcessButton> isButtonInList(ProcessButton button) //returns null if not found { foreach (var rBut in runningProcs.ToList()) { if (rBut.Item2 == button) { return rBut; } } return null; } private void process_Exited(object sender, EventArgs e) { Process proc = sender as Process; foreach(var rProc in runningProcs.ToList()) { if(rProc.Item1 == proc) { rProc.Item2.SetRunning(false); runningProcs.Remove(rProc); return; } } } private Process[] GetRunning() { return Process.GetProcesses().Where(p => !string.IsNullOrEmpty(p.MainWindowTitle)).ToArray(); } } }
Java
UTF-8
281
1.59375
2
[]
no_license
package com.ethiorise.i2e.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.ethiorise.i2e.model.Airport; @Repository public interface AirportRepository extends JpaRepository<Airport, Long>{ }
Java
UTF-8
115
1.648438
2
[]
no_license
package ru.itmo.roguelike.items; public class MedKitMedium extends MedKit { { bonusSize = 50; } }
C++
UTF-8
1,665
2.625
3
[]
no_license
#ifndef __NEON_H #define __NEON_H #include "vertex.h" #include "face.h" // ---------------------------------------------- // class CNeon // // This class handle the 4 neons needed to illuminate a car // // ---------------------------------------------- namespace Lib3D { class TTexture; class CLib3D; // class TVertex; #define NEON_WIDTH 40 #define NEON_TEXTURE_SIZE 64 class CNeon { public: enum neon_color { NONE, RED, ORANGE, YELLOW, PURPLE, GREEN, BLUE, CYAN, //GREY, //DARK_RED, //DARK_GREEN, kTotalColors }; CNeon(int x_left,int x_right,int y_front,int y_back); ~CNeon(); void Draw( Lib3D::CLib3D& lib3d); void SetColor(neon_color color_in); bool IsActive(){return current_color != NONE;} static int GetColorNum(){return kTotalColors;} static unsigned short GetColorRGB(int color_index) { switch(color_index) { case NONE: return 0; case RED: return 0xF00; case ORANGE: return 0xF50; case YELLOW: return 0xFF4; case PURPLE: return 0xC0E; case GREEN: return 0x0F0; case BLUE: return 0x27C; case CYAN: return 0x7AC; //case GREY: return 0x888; //case DARK_RED: return 0xF00; //case DARK_GREEN: return 0x070; } return 0; } private: neon_color current_color; TVertex vert[6*4]; TFace face[4*4]; TTexture* NeonTexture; void DrawAdditiveNeonGeom( Lib3D::CLib3D& lib3d,TTexture* texture,TVertex* vtx,TFace* face); void CreateAdditiveNeonGeom(TVertex* vtx, TFace* face, const Vector4s& center, int size_x, int size_y, bool x_aligned); }; } #endif //__NEON_H
Python
UTF-8
1,042
3.796875
4
[]
no_license
cars = 100 #start an integer variable with one value of 100 space_in_a_car = 4.0 #start a double variable with one value of 4.0, it´s mean the people capacity in the car drivers = 30 #the driver are 30, this is a new variable passengers = 90 #the passengers are 90, again this is a new variable cars_not_driven = cars - drivers #this are the cars that haven´t drivers cars_driven = drivers #this are the cars that have drivers carpool_capacity = cars_driven * space_in_a_car #this is the maximun capacity in the lot the cars, at the moment average_passengers_per_car = passengers / cars_driven #promedium the people by car // 90/(los carros que tienen conductor) print "There are", cars, "cars available." print "There are only", drivers, "drivers available." print "There will be", cars_not_driven, "empty cars today." print "We can transport", carpool_capacity, "people today." print "We have", passengers, "to carpool today." print "We need to put about", average_passengers_per_car, "in each car."
Python
UTF-8
372
2.59375
3
[]
no_license
import urllib2 import random from time import sleep random.seed(); last_line = 'blah' list_of_files = ['what_exists2.txt'] for filename_to_open in list_of_files: with open(filename_to_open) as fp: for line in fp: if 'exists' in line: print(last_line) last_line = line
Java
UTF-8
5,961
2.203125
2
[]
no_license
package com.onefamily.mall.service.sms.impl; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.onefamily.common.redis.RedisPool; import com.onefamily.mall.service.sms.ISmsService; import com.onefamily.platform.dataformat.ResultVO; import org.apache.commons.lang3.RandomUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import redis.clients.jedis.Jedis; import java.util.Map; @Service public class SmsServiceImpl implements ISmsService { private static final String VerifyCodeLimitIntervalKey = "verify_code_send_limit"; private static final String DefaultModelCode = "xc_sms"; private static final int DefaultSendIntervalSeconds = 1*60-1; private static final int DefaultVerifyCodeExpireSeconds = 10*60-1; private static final String VerifyCodeCacheKey = "verify_code_key"; private String genLimitIntervalKey(String moduleCode, String mobile) { return StringUtils.join(Lists.newArrayList(VerifyCodeLimitIntervalKey, moduleCode, mobile), "_"); } private String genVerifyCodeKey(String moduleCode, String mobile) { return StringUtils.join(Lists.newArrayList(VerifyCodeCacheKey, moduleCode, mobile), "_"); } public ResultVO<String> sendVerifyCode(String mobile, String moduleCode, int limitSendInterval, Integer expireSeconds) { ResultVO<String> resultVO = new ResultVO<String>(); do { if (StringUtils.isBlank(mobile)) { resultVO.format(false, "请输入手机号"); break; } if (!mobile.matches("^1[0-9]{10}$")) { resultVO.format(false, "请输入合法手机号"); break; } if (StringUtils.isBlank(moduleCode)) { moduleCode = DefaultModelCode; } if (expireSeconds == null || expireSeconds <= 0) { expireSeconds = DefaultVerifyCodeExpireSeconds; } String intervalLimitKey = genLimitIntervalKey(moduleCode, mobile); Jedis jedis = RedisPool.getJedis(); try { if (jedis != null) { String code = jedis.get(intervalLimitKey); if (StringUtils.isNotBlank(code)) { resultVO.format(true, "短信验证码已发送,请注意查收"); break; } } } finally { if (jedis != null) { RedisPool.returnResource(jedis); } } // 走到这里证明验证码需要重发,或者未曾发送 Map<String, String> params = Maps.newHashMap(); params.put("caller", "dalingjia"); params.put("module", moduleCode); params.put("expire", String.valueOf(expireSeconds)); String verifyCode = ""; jedis = RedisPool.getJedis(); try { if (jedis != null) { String codeKey = genVerifyCodeKey(moduleCode, mobile); verifyCode = jedis.get(codeKey); if (StringUtils.isNotBlank(verifyCode)) { resultVO.format(true, String.format("验证码发送成功! %s", verifyCode), verifyCode); break; } verifyCode = String.valueOf(RandomUtils.nextInt(100000, 999999)); jedis.set(codeKey, verifyCode); jedis.expire(codeKey, DefaultVerifyCodeExpireSeconds); if (limitSendInterval < 0) { jedis.set(intervalLimitKey, "1"); jedis.expire(intervalLimitKey, DefaultSendIntervalSeconds); } else if (limitSendInterval > 0) { jedis.set(intervalLimitKey, "1"); jedis.expire(intervalLimitKey, limitSendInterval); } } } finally{ if (jedis != null) { RedisPool.returnResource(jedis); } } resultVO.format(true, String.format("验证码发送成功! %s", verifyCode), verifyCode); break; } while (false); return resultVO; } public ResultVO<String> authVerifyCode(String mobile, String moduleCode, String verifyCode) { ResultVO<String> resultVO = new ResultVO<String>(); do { if (StringUtils.isBlank(mobile)) { resultVO.format(false, "输入手机号"); break; } if (!mobile.matches("^1[0-9]{10}$")) { resultVO.format(false, "请输入合法手机号"); break; } if (StringUtils.isBlank(verifyCode)) { resultVO.format(false, "请输入验证码"); break; } verifyCode = StringUtils.trimToEmpty(verifyCode); if (StringUtils.isBlank(moduleCode)) { moduleCode = DefaultModelCode; } String codeKey = genVerifyCodeKey(moduleCode, mobile); String cacheVerifyCode = ""; Jedis jedis = RedisPool.getJedis(); try { if (jedis != null) { cacheVerifyCode = jedis.get(codeKey); } if (StringUtils.isBlank(cacheVerifyCode)) { resultVO.format(false, "验证码已过期,请重新获取!"); break; } if (!StringUtils.equalsIgnoreCase(verifyCode, cacheVerifyCode)) { resultVO.format(false, "验证码不正确,请重新输入!"); break; } jedis.del(codeKey); } finally{ if (jedis != null) { RedisPool.returnResource(jedis); } } resultVO.format(true, "验证通过!"); break; } while (false); return resultVO; } }
Python
UTF-8
716
3.265625
3
[]
no_license
seat= input() number= int(seat[:-1]) letter= seat[-1] time=0 pair="first or second" if number%2 == 0: Q=number/2 if Q%2==0: pair="second" else: pair="first" else: Q=int(number/2 - 0.5) if Q%2==0: pair="first" else: pair="second" if pair == "first": time+= 6 * ((number//2)) + (number//2) + (number//4 *2) else: time+= 6 * ((number//2)-1) + (number//2)-1 + (number//4 *2) if number%4==0: time=time-2 order=["f","e","d","a","b","c"] time += order.index(letter) + 1 if number== 999999999999999998 or number== 999999999999999994: time += 7 if number== 999999999999999999 or number== 999999999999999995: time -= 7 print(time)
Java
UTF-8
7,535
1.828125
2
[]
no_license
package com.teammetallurgy.aquaculture.client.renderer.entity; import com.mojang.blaze3d.matrix.MatrixStack; import com.teammetallurgy.aquaculture.Aquaculture; import com.teammetallurgy.aquaculture.entity.AquaFishEntity; import com.teammetallurgy.aquaculture.entity.FishMountEntity; import com.teammetallurgy.aquaculture.entity.FishType; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.Atlases; import net.minecraft.client.renderer.BlockRendererDispatcher; import net.minecraft.client.renderer.IRenderTypeBuffer; import net.minecraft.client.renderer.Vector3f; import net.minecraft.client.renderer.entity.EntityRenderer; import net.minecraft.client.renderer.entity.EntityRendererManager; import net.minecraft.client.renderer.model.ModelManager; import net.minecraft.client.renderer.model.ModelResourceLocation; import net.minecraft.client.renderer.texture.OverlayTexture; import net.minecraft.client.resources.I18n; import net.minecraft.entity.Entity; import net.minecraft.entity.MobEntity; import net.minecraft.entity.passive.fish.PufferfishEntity; import net.minecraft.inventory.container.PlayerContainer; import net.minecraft.item.ItemStack; import net.minecraft.util.Direction; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.Vec3d; import javax.annotation.Nonnull; import java.math.BigDecimal; import java.math.MathContext; import java.text.DecimalFormat; public class FishMountRenderer extends EntityRenderer<FishMountEntity> { public static final ModelResourceLocation OAK = new ModelResourceLocation(new ResourceLocation(Aquaculture.MOD_ID, "oak_fish_mount"), ""); public static final ModelResourceLocation SPRUCE = new ModelResourceLocation(new ResourceLocation(Aquaculture.MOD_ID, "spruce_fish_mount"), ""); public static final ModelResourceLocation BIRCH = new ModelResourceLocation(new ResourceLocation(Aquaculture.MOD_ID, "birch_fish_mount"), ""); public static final ModelResourceLocation JUNGLE = new ModelResourceLocation(new ResourceLocation(Aquaculture.MOD_ID, "jungle_fish_mount"), ""); public static final ModelResourceLocation ACACIA = new ModelResourceLocation(new ResourceLocation(Aquaculture.MOD_ID, "acacia_fish_mount"), ""); public static final ModelResourceLocation DARK_OAK = new ModelResourceLocation(new ResourceLocation(Aquaculture.MOD_ID, "dark_oak_fish_mount"), ""); private final Minecraft mc = Minecraft.getInstance(); public FishMountRenderer(EntityRendererManager renderManager) { super(renderManager); } @Override public void render(@Nonnull FishMountEntity fishMount, float entityYaw, float partialTicks, @Nonnull MatrixStack matrixStack, @Nonnull IRenderTypeBuffer buffer, int i) { super.render(fishMount, entityYaw, partialTicks, matrixStack, buffer, i); matrixStack.push(); Direction direction = fishMount.getHorizontalFacing(); Vec3d pos = this.getRenderOffset(fishMount, partialTicks); matrixStack.translate(-pos.getX(), -pos.getY(), -pos.getZ()); double multiplier = 0.46875D; matrixStack.translate((double) direction.getXOffset() * multiplier, (double) direction.getYOffset() * multiplier, (double) direction.getZOffset() * multiplier); matrixStack.rotate(Vector3f.XP.rotationDegrees(fishMount.rotationPitch)); matrixStack.rotate(Vector3f.YP.rotationDegrees(180.0F - fishMount.rotationYaw)); BlockRendererDispatcher rendererDispatcher = this.mc.getBlockRendererDispatcher(); ModelManager manager = rendererDispatcher.getBlockModelShapes().getModelManager(); matrixStack.push(); matrixStack.translate(-0.5D, -0.5D, -0.5D); if (fishMount.getType().getRegistryName() != null) { ModelResourceLocation location = new ModelResourceLocation(fishMount.getType().getRegistryName(), ""); //Calling this instead of the fields for mod support' rendererDispatcher.getBlockModelRenderer().renderModelBrightnessColor(matrixStack.getLast(), buffer.getBuffer(Atlases.getSolidBlockType()), null, manager.getModel(location), 1.0F, 1.0F, 1.0F, i, OverlayTexture.DEFAULT_LIGHT); } matrixStack.pop(); this.renderFish(fishMount, pos, partialTicks, matrixStack, buffer, i); matrixStack.pop(); } private void renderFish(FishMountEntity fishMount, Vec3d pos, float partialTicks, MatrixStack matrixStack, IRenderTypeBuffer buffer, int i) { Entity entity = fishMount.entity; if (entity instanceof MobEntity) { MobEntity fish = (MobEntity) entity; double x = 0.0D; double y = 0.0D; double depth = 0.42D; if (fish instanceof PufferfishEntity) { depth += 0.09D; } else if (fish instanceof AquaFishEntity && AquaFishEntity.TYPES.get(fish.getType()).equals(FishType.LONGNOSE)) { x = -0.1F; y = -0.18D; } fish.setNoAI(true); matrixStack.translate(x, y, depth); matrixStack.rotate(Vector3f.XP.rotationDegrees(-90.0F)); matrixStack.rotate(Vector3f.YP.rotationDegrees(-90.0F)); this.mc.getRenderManager().renderEntityStatic(fish, 0.0F, 0.0F, 0.0F, 0.0F, 0, matrixStack, buffer, i); } } @Override @Nonnull public ResourceLocation getEntityTexture(@Nonnull FishMountEntity fishMount) { return PlayerContainer.LOCATION_BLOCKS_TEXTURE; } @Override @Nonnull public Vec3d getRenderOffset(FishMountEntity fishMount, float partialTicks) { return new Vec3d((float) fishMount.getHorizontalFacing().getXOffset() * 0.3F, -0.25D, (float) fishMount.getHorizontalFacing().getZOffset() * 0.3F); } @Override protected boolean canRenderName(@Nonnull FishMountEntity fishMount) { if (Minecraft.isGuiEnabled() && fishMount.entity != null && (this.mc.objectMouseOver != null && fishMount.getDistanceSq(this.mc.objectMouseOver.getHitVec()) < 0.24D)) { double d0 = this.renderManager.squareDistanceTo(fishMount); float sneaking = fishMount.isDiscrete() ? 32.0F : 64.0F; return d0 < (double) (sneaking * sneaking); } else { return false; } } @Override protected void renderName(@Nonnull FishMountEntity fishMount, @Nonnull String name, @Nonnull MatrixStack matrixStack, @Nonnull IRenderTypeBuffer buffer, int i) { super.renderName(fishMount, fishMount.entity.getDisplayName().getFormattedText(), matrixStack, buffer, i); ItemStack stack = fishMount.getDisplayedItem(); if (stack.hasTag() && stack.getTag() != null && stack.getTag().contains("fishWeight")) { double weight = stack.getTag().getDouble("fishWeight"); String lb = weight == 1.0D ? " lb" : " lbs"; DecimalFormat df = new DecimalFormat("#,###.##"); BigDecimal bd = new BigDecimal(weight); bd = bd.round(new MathContext(3)); matrixStack.push(); matrixStack.translate(0.0D, -0.25D, 0.0D); //Adjust weight label height if (bd.doubleValue() > 999) { super.renderName(fishMount, I18n.format("aquaculture.fishWeight.weight", df.format((int) bd.doubleValue()) + lb), matrixStack, buffer, i - 100); } else { super.renderName(fishMount, I18n.format("aquaculture.fishWeight.weight", bd + lb), matrixStack, buffer, i); } matrixStack.pop(); } } }
Markdown
UTF-8
4,457
2.5625
3
[]
no_license
--- title: "Software Design" --- ## Software Metrics - [ABC Software Metric](https://en.wikipedia.org/wiki/ABC_Software_Metric) — an ABC score as a triplet of values that represent the size of a set of source code statements. - Bugs per line of code — self-explanatory - [Code coverage](https://en.wikipedia.org/wiki/Code_coverage) — The degree to how much source code of a program that is covered by automated tests. - [Cohesion](https://en.wikipedia.org/wiki/Cohesion_(computer_science)) — The degree to which the elements inside a module belong together. - Comment density — a metric decided by either line count or character count in regards to comments. - [Connascence](https://en.wikipedia.org/wiki/Connascence) — a metric on the complexity caused by dependency relationships (similar to software coupling, but it is not the same). - [Constructive Cost Model](https://en.wikipedia.org/wiki/COCOMO) — a procedural software cost estimation model. - [Coupling](https://en.wikipedia.org/wiki/Coupling_(computer_programming)) — The degree of interdependence between software modules; a measure of how closely connected two routines or modules are; the strength of the relationships between modules. - [Cyclomatic complexity](https://en.wikipedia.org/wiki/Cyclomatic_complexity) — a metric used to indicate the complexity of a program defined by the amounts of linearly independent paths through the program. - Defect density — defects found in a component - Defect potential — expected number of defects in a particular component - [Defect removal rate](https://swtestingconcepts.wordpress.com/test-metrics/defect-removal-efficiency/) — a measure of a development team's ability to remove defects prior to release. - [DSQI (design structure quality index)](https://en.wikipedia.org/wiki/DSQI) — a metric to indicate a computer program's design structure and the efficiency of its modules (a value from 0 to 1). - [Function Points and Automated Function Points](https://en.wikipedia.org/wiki/Function_point) — a metric to express the amount of business functionality an information system provides to a user. - [Halstead Complexity](https://en.wikipedia.org/wiki/Halstead_complexity_measures) — metrics to identify measurable properties of software and the relations between them. - [Instruction path length](https://en.wikipedia.org/wiki/Instruction_path_length) — the number of machine code instructions required to execute a section of a computer program. - [Maintainability index](https://en.wikipedia.org/wiki/Maintainability#Software_engineering) — a measure of the ease with which a product can be maintained. - [Number of lines of code](https://en.wikipedia.org/wiki/Source_lines_of_code) — a metric to measure the size of a computer program. - [Program execution time](https://en.wikipedia.org/wiki/Runtime_(program_lifecycle_phase)) — a measure of time when the CPU is executing the machine code for a given instruction/method/program. - [Program load time](https://en.wikipedia.org/wiki/Loader_(computing)) — a measure of the time it takes to load a program. - [Program size (binary)](https://en.wikipedia.org/wiki/Binary_file) — the size of a program in bytes. - [Weighted Micro Function Points](https://en.wikipedia.org/wiki/Weighted_Micro_Function_Points) — a successor to the maintainability index, cyclomatic complexity, function points, Halstead complexity, and the Constructive Cost Model. It is a metric that measures the overall code complexity and volume metrics in a given system. - [CISQ automated quality characteristics](https://content.castsoftware.com/cisq-specification-for-automated-quality-characteristic-measures) — an automated measurement of four Software Quality Characteristics. Reliability, Performance Efficiency, Security, and Maintainability. ## Software Quality Attributes ## Architectural Patterns ## Design Patterns ## API Design - [Representational State Transfer (REST)](https://restfulapi.net) — A stateless architecture for data transfer that is dependent on hypermedia. - [Awesome REST API](https://github.com/Kikobeats/awesome-api) - [gRPC](https://grpc.io) — A nimble and lightweight system for requesting data. - [GraphQL](https://graphql.org) — An approach wherein the user defines the expected data and format of that data. - [Webhooks](https://en.wikipedia.org/wiki/Webhook) — Data updates to be served automatically, rather than requested.
Java
UTF-8
2,247
2.875
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package groupgenerator; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; /** * * @author intelkt8 !!!!! */ public class GroupGenerator { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here int iNumNames; ArrayList<String> listNames = new ArrayList<String>(); iNumNames = fiReadFile("c:/home/names.txt", listNames); System.out.println("There are a total of " + iNumNames + " students in the file provided."); //obtain group information int iGroups; Scanner cin = new Scanner(System.in); do { System.out.println("How many groups do you want?"); iGroups = cin.nextInt(); if(iGroups > plistNames.size()) { System.out.println("ERROR: The number of groups entered is greater than the number of students in the file"); } } while (iGroups > plistNames.size()); iMax = piNumNames / iGroups; iMaxMod = piNumNames % iGroups; fvDisplayNames(listNames); // fvRandomGroups(listNames, iNumNames); } //Read file public static int fiReadFile(String psFile, ArrayList<String> plistNames) { int iCount; String sName; iCount = 0; try { Scanner ifsInput = new Scanner(new File(psFile)); while (ifsInput.hasNextLine()) { sName = ifsInput.nextLine(); plistNames.add(sName); iCount ++; } } catch (FileNotFoundException sMsg) { System.out.println("File not found"); } return iCount; } //Display names in list public static void fvDisplayNames(ArrayList<String> plistNames) { int iCount; String sName; for(iCount = 0; iCount < plistNames.size(); iCount++) { System.out.println(plistNames.get(iCount)); } return; } public static void rdmGroupGenerator(int iMax){ } }
Markdown
UTF-8
637
3.34375
3
[]
no_license
--- layout: post title: JS中的逻辑与和逻辑或 date: 2017-06-02 18:22 image: /images/posts/aside/1.jpg tags: JS知识点 --- <br /> 几乎所有的语言中\|\|及&&都遵循“短路”原理,如&&中第一个表达式为假,就不会去处理第二个表达式,而\|\|正好相反。 JS也遵循上述原则。 当\|\|时,找到为true的分项就停止处理,并返回该分项的值,否则执行完,并返回最后分项的值。 当&&时,找到false的分项就停止处理,并返回该分项的值。 ```python var a = "" || null || 3 || 4; //3 var b = 4 && 5 && null && "0"; //null ```
Markdown
UTF-8
1,040
2.90625
3
[]
no_license
# Index Array Equilibrium This project shows an interface to interact with the _Index Array Equilibrium API_. It's available at https://paulo9mv.github.io/sum_array_front ## To execute This tutorial supposes that you have _yarn_ installed. If you don't have it, follow the instructions at the [official page](https://classic.yarnpkg.com/pt-BR/docs/install/#windows-stable). 1. To install _node\_modules_ ``` $ yarn install ``` 2. To start the project ``` $ yarn start ``` **NOTE:** The frontend is hosted at Github Pages. The API is hosted at Heroku using Free Dynos, so the first request should take a little bit longer (8s) to execute, because Heroku is changing the API status from **suspended** to **up**. ## Tools used in the project :paperclip: :wrench: Configuration: - [React](https://reactjs.org/) - [create-react-app](https://create-react-app.dev/) :art: Design: - [Material-UI](https://material-ui.com/pt/) - [Final Form](https://final-form.org/react) :cloud: Deploy: - [gh-pages](https://github.com/tschaub/gh-pages)
Shell
UTF-8
856
3.375
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env bash if [ -z "$1" ]; then DEBUG=0 else set -x DEBUG=1 fi if [ -z "$PLAY_CMD" ]; then PLAY_CMD="$HOME/src/play-2.0.3/play"; fi if [ $DEBUG -eq 0 ]; then rm -rf targed/staged $PLAY_CMD clean compile stage fi cd target CONF_DIR="collins/conf" rm -rf collins for dir in collins collins/lib collins/scripts $CONF_DIR; do mkdir $dir done for dir in $CONF_DIR/solr/conf $CONF_DIR/solr/data; do mkdir -p $dir done cp staged/* collins/lib cp ../scripts/collins.sh collins/scripts/collins.sh cp ../scripts/setup collins/scripts/setup cp ../conf/logger.xml $CONF_DIR cp ../conf/production_starter.conf $CONF_DIR/production.conf cp ../conf/permissions.yaml $CONF_DIR cp ../conf/validations.conf $CONF_DIR cp -R ../conf/solr/conf/* $CONF_DIR/solr/conf/ cp -R ../conf/evolutions/* $CONF_DIR/evolutions/ zip -r collins.zip collins
Java
UTF-8
15,029
1.8125
2
[]
no_license
package smilegate.blackpants.univscanner; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.constraint.ConstraintLayout; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.Filter; import android.widget.ImageButton; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException; import com.google.firebase.auth.FirebaseAuthUserCollisionException; import com.google.firebase.auth.FirebaseAuthWeakPasswordException; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GetTokenResult; import com.google.firebase.iid.FirebaseInstanceId; import com.pixplicity.easyprefs.library.Prefs; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.OnItemClick; import dmax.dialog.SpotsDialog; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import smilegate.blackpants.univscanner.data.model.Users; import smilegate.blackpants.univscanner.data.remote.ApiUtils; import smilegate.blackpants.univscanner.data.remote.UserApiService; import smilegate.blackpants.univscanner.utils.UniversityListAdapter; /** * Created by user on 2018-01-17. */ public class CreateEmailAccountActivity extends AppCompatActivity { private static final String TAG = "CreatAccountActivity"; private FirebaseAuth mAuth; private List<String> mUniversityList; private UniversityListAdapter mAdapter; private int mFilterCount; private android.app.AlertDialog mDialog; private UserApiService mUserApiService; @BindView(R.id.list_univ) ListView univListView; @BindView(R.id.btn_create_account_back) ImageButton backBtn; @BindView(R.id.univ_list) ConstraintLayout univListLayout; @BindView(R.id.create_emailinfo) ConstraintLayout createEmailInfoLayout; @OnClick(R.id.btn_create_account_back) public void createAccountBack(ImageButton imageButton) { finish(); } @BindView(R.id.autoText_univ) AutoCompleteTextView inputUnivText; @BindView(R.id.autoText_email) AutoCompleteTextView inputEmailText; @BindView(R.id.autoText_name) AutoCompleteTextView inputNameText; @BindView(R.id.autoText_password) AutoCompleteTextView passwordText; @BindView(R.id.autoText_password_again) AutoCompleteTextView passwordAgainText; @BindView(R.id.btn_emailcreate) Button createEmailBtn; @BindView(R.id.text_logininfo_status) TextView loginInfoStatusTxt; @OnClick(R.id.btn_emailcreate) public void createAccount(Button button) { if (validateForm()) { String university= inputUnivText.getText().toString().trim(); university = university.split(" ")[0]; //university = university.replace(" ", "-"); createUser(university, inputNameText.getText().toString().trim(), inputEmailText.getText().toString().trim(), passwordText.toString().trim()); } } @OnItemClick(R.id.list_univ) public void univListItemClick(AdapterView<?> parent, View view, int position, long id) { Log.d(TAG, "onItemClick : selected : " + mUniversityList.get(position).toString()); String codeStart = "<b><font color='#000'>"; String codeEnd = "</font></b>"; String item = mUniversityList.get(position).toString(); item = item.replace(codeStart, ""); // <(> and <)> are different replace them with your color code String, First one with start tag item = item.replace(codeEnd, ""); // then end tag inputUnivText.setText(item); changeMiddleView("emailInfo"); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_create_emailaccount); ButterKnife.bind(this); //mUniversityApiService = UniversityApiUtils.getUserApiService(); initTextListener(); saveToList(); changeMiddleView("init"); mAdapter = new UniversityListAdapter(this, R.layout.layout_univ_listitem, mUniversityList); mDialog = new SpotsDialog(this, R.style.createLodingTheme); univListView.setTextFilterEnabled(true); univListView.setAdapter(mAdapter); mUserApiService = ApiUtils.getUserApiService(); mAuth = FirebaseAuth.getInstance(); } public void initTextListener() { Log.d(TAG, "initTextListener : initializing"); mUniversityList = new ArrayList<>(); inputUnivText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { changeMiddleView("univList"); String text = inputUnivText.getText().toString(); Log.d(TAG, "afterTextChanged : " + text); if (text.length() == 0) { changeMiddleView("init"); } else { if (mAdapter != null) { mAdapter.getFilter().filter(s, new Filter.FilterListener() { @Override public void onFilterComplete(int count) { mFilterCount = count; setListViewHeightBasedOnChildren(univListView, mFilterCount); } }); } else { Log.d("filter", "no filter availible"); } } //searchForMatch(text); } }); } public static void setListViewHeightBasedOnChildren(ListView listView, int count) { ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) { return; } int totalHeight = 0; int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.AT_MOST); if (count > 0) { View listItem = listAdapter.getView(0, null, listView); listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED); totalHeight = listItem.getMeasuredHeight() * count; } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); listView.setLayoutParams(params); listView.requestLayout(); } @Override protected void onDestroy() { super.onDestroy(); finish(); } private boolean validateForm() { boolean valid; // 1. 이메일 유효성 검사 - empty, 이메일 format // 2. 비밀번호 6자리 이상인지 검사 // 3. 비빌번호 입력과 확인이 같은지 검사. // 4. 이름 empty 검사 String email = inputEmailText.getText().toString(); String password = passwordText.getText().toString(); String passwordAgain = passwordAgainText.getText().toString(); String name = inputNameText.getText().toString(); if (TextUtils.isEmpty(email)) { loginInfoStatusTxt.setText("이메일을 입력하세요."); valid = false; } else if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) { loginInfoStatusTxt.setText("올바른 이메일을 입력하세요."); valid = false; } else if (TextUtils.isEmpty(name)) { loginInfoStatusTxt.setText("이름을 입력하세요."); valid = false; } else if (TextUtils.isEmpty(password)) { loginInfoStatusTxt.setText("비밀번호를 입력하세요."); valid = false; } else if (password.length() < 6) { loginInfoStatusTxt.setText("비밀번호를 6자리 이상 입력하세요."); valid = false; } else if (!password.equals(passwordAgain)) { loginInfoStatusTxt.setText("비밀번호가 일치하지 않습니다."); valid = false; } else { valid = true; } return valid; } public void changeMiddleView(String option) { switch (option) { case "init": univListLayout.setVisibility(View.GONE); createEmailInfoLayout.setVisibility(View.GONE); loginInfoStatusTxt.setText(""); break; case "univList": univListLayout.setVisibility(View.VISIBLE); createEmailInfoLayout.setVisibility(View.GONE); break; case "emailInfo": univListLayout.setVisibility(View.GONE); createEmailInfoLayout.setVisibility(View.VISIBLE); break; } } public void createUser(final String universityInfo, final String name, final String email, final String password) { mDialog.show(); mAuth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "createUserWithEmail:success"); FirebaseUser user = mAuth.getCurrentUser(); if (user != null) { // 유저가 로그인 했을 때 user.getIdToken(true).addOnCompleteListener(new OnCompleteListener<GetTokenResult>() { @Override public void onComplete(@NonNull Task<GetTokenResult> task) { if (task.isSuccessful()) { // 서버에 보내기 String loginToken = task.getResult().getToken(); sendToServer(loginToken, name, universityInfo); } } }); } } else { // If sign in fails, display a message to the user. Log.w(TAG, "createUserWithEmail:failure", task.getException()); try { throw task.getException(); } catch (FirebaseAuthWeakPasswordException e) { loginInfoStatusTxt.setText("비밀번호를 6자리 이상 입력하세요."); } catch (FirebaseAuthInvalidCredentialsException e) { loginInfoStatusTxt.setText("올바른 이메일을 입력하세요."); } catch (FirebaseAuthUserCollisionException e) { loginInfoStatusTxt.setText("이미 존재하는 이메일입니다."); } catch (Exception e) { Log.e(TAG, e.getMessage()); } mDialog.dismiss(); } } }); } public String loadJSONFromAsset() { String json = null; try { InputStream is = this.getAssets().open("university_list.json"); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); json = new String(buffer, "UTF-8"); } catch (IOException ex) { ex.printStackTrace(); return null; } return json; } public void saveToList() { try { JSONObject obj = new JSONObject(loadJSONFromAsset()); JSONArray content = obj.getJSONObject("dataSearch").getJSONArray("content"); mUniversityList = new ArrayList<String>(); for (int i = 0; i < content.length(); i++) { JSONObject univInfo = content.getJSONObject(i); String schoolName = univInfo.getString("schoolName"); String campusName = univInfo.getString("campusName"); String result = schoolName + " " + campusName; Log.d(TAG, i + " : " + result); mUniversityList.add(result); } } catch (JSONException e) { e.printStackTrace(); } } public void sendToServer(String loginToken, String name, String universityInfo) { String registrationToken = FirebaseInstanceId.getInstance().getToken(); //서버와 통신 mUserApiService.setUsers(loginToken, registrationToken, name, universityInfo).enqueue(new Callback<Users>() { @Override public void onResponse(Call<Users> call, Response<Users> response) { if (response.isSuccessful()) { Log.e("ResponseData", response.body().toString()); Log.i(TAG, "post submitted to API." + response.body().toString()); mDialog.dismiss(); Prefs.putString("loginRoute", "email"); Intent intent = new Intent(CreateEmailAccountActivity.this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); finish(); } } @Override public void onFailure(Call<Users> call, Throwable t) { Log.e(TAG, "Unable to submit post to API."); mDialog.dismiss(); finish(); } }); } }
Python
UTF-8
1,155
3.625
4
[ "MIT" ]
permissive
# 1109. Corporate Flight Bookings # Weekly Contest 144 # Time: O(len(n)) # Space: O(n) class Solution: def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]: """ Shorter solution: """ res = [0]*(n+1) for i,j,k in bookings: res[i-1]+=k res[j]-=k for i in range(1,n): res[i]+=res[i-1] return res[:-1] """ Longer Solution """ result = [{} for _ in range(n)] for booking in bookings: i,j,k = booking[0],booking[1],booking[2] if 'start' in result[i-1]: result[i-1]['start']+=k else: result[i-1]['start']=k if 'end' in result[j-1]: result[j-1]['end']+=k else: result[j-1]['end']=k adder = 0 seats = [0]*n for index,flight in enumerate(result): if 'start' in flight: adder+=flight['start'] seats[index]+=adder if 'end' in flight: adder-=flight['end'] return seats
Python
UTF-8
82
3.015625
3
[]
no_license
input= input() l=input.split(',') t=tuple(l) print('list:',l) print('tuples:',t)
Java
UTF-8
1,040
2.25
2
[]
no_license
package com.lahtinen.jaakko.Bookstore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.junit4.SpringRunner; import com.lahtinen.jaakko.controller.UserRepository; import com.lahtinen.jaakko.data.User; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) @DataJpaTest public class UserRepositoryTest { @Autowired private UserRepository repository; @Test public void findByUsernameShouldReturnUser() { User user = repository.findByUsername("admin"); assertThat(user.getId()).isNotNull(); } @Test public void createNewUserAndDeleteIt() { User user = new User("Jacker", "xxx", "admin"); repository.save(user); assertThat(user.getId()).isNotNull(); assertThat(repository.findByUsername("Jacker")).isNotNull(); repository.delete(user); assertThat(repository.findByUsername("Jacker")).isNull(); } }
Java
UTF-8
11,184
2.75
3
[]
no_license
package ExtendedModeler; import com.jogamp.opengl.GL2; import com.jogamp.opengl.GLAutoDrawable; import smTrace.SmTrace; // This class is the basis for bounded oriented objects. public class EMBox3D { ///private boolean isEmpty = true; public static final Vector3D xaxis = new Vector3D(1,0,0); public static final Vector3D yaxis = new Vector3D(0,1,0); public static final Vector3D zaxis = new Vector3D(0,0,1); public static final Vector3D UP = yaxis; // Pointing in y direction public static final Vector3D GL_UP = zaxis; // GL (eg cylinder) idea of up Vector3D up; // null == UP private Point3D center = new Point3D(0, 0, 0); private float radius = 0; // Bounding radius public static float RADIUS = .5f; /// diagonally opposite corners ///private Point3D p0 = new Point3D(0,0,0); ///private Point3D p1 = new Point3D(0,0,0); public EMBox3D() { this(new Point3D(0,0,0), EMBox3D.RADIUS); } /** * Deep copy, allowing modifications */ public EMBox3D(EMBox3D box) { if (box == null) box = new EMBox3D(); setCenter(box.center); setRadius(box.radius); setUp(box.up); } public EMBox3D( Point3D center, float radius, Vector3D up ) { setCenter(center); setRadius(radius); setUp(up); } public EMBox3D( Point3D center, float radius) { this(center, radius, null); } public EMBox3D( Point3D center) { this(center, 0, null); } public EMBox3D(float radius) { this(new Point3D(0, 0, 0), radius); } public EMBox3D(Vector3D size) { this(size.length()/2); } /** * Create from simple box */ public EMBox3D(ColoredBox cbox) { this(cbox.getCenter(), cbox.getRadius(), cbox.getUp()); } /** * absolute min,max based on global coordinates * @return */ public Point3D getMin() { return new Point3D(getMinX(), getMinY(), getMinZ()); } public float getMinX() { return center.x()-radius; } public float getMinY() { return center.y()-radius; } public float getMinZ() { return center.z()-radius; } public Point3D getMax() { return new Point3D(getMaxX(), getMaxY(), getMaxZ()); } public float getMaxX() { return center.x()+radius; } public float getMaxY() { return center.y()+radius; } public float getMaxZ() { return center.z()+radius; } /** * Diagonal based on global coordiantes * @return */ public Vector3D getDiagonal() { return Point3D.diff(getMax(), getMin()); } // Enlarge the box as necessary to contain the given point public void bound( Point3D p ) { float dist = Point3D.diff(p, center).length(); if (dist > radius) radius = dist; } // Enlarge the box as necessary to contain the given box public void bound( EMBox3D box ) { Vector3D vcenter2box = Point3D.diff(box.center, center); float cent2cent = vcenter2box.length(); float newradius = cent2cent + box.radius; if (newradius < radius) return; // box is enclosed radius = newradius; // Enlarge to contain new sphere } // Enlarge the box as necessary to contain the given block public AlignedBox3D boundingBox() { AlignedBox3D bbox = new AlignedBox3D(this); return bbox; } // Enlarge the sphere as necessary to contain the given block public EMBox3D boundingSphere() { return this; } // if we are a box it is us public EMBox3D getBox() { return this; } /** * Compare box * @param p * @return -1, 0, 1 */ public int cmp(EMBox3D box2) { int cx_cmp = Float.compare(center.x(), box2.center.x()); if (cx_cmp != 0) return cx_cmp; int cy_cmp = Float.compare(center.y(), box2.center.y()); if (cy_cmp != 0) return cy_cmp; int cz_cmp = Float.compare(center.z(), box2.center.z()); if (cz_cmp != 0) return cz_cmp; int radius_cmp = Float.compare(radius, box2.radius); if (radius_cmp != 0) return radius_cmp; if (up == null) { if (box2.up == null) return 0; return -1; } if (box2.up == null) { return 1; } int upx_cmp = Float.compare(up.x(), box2.up.x()); if (upx_cmp != 0) return cx_cmp; int upy_cmp = Float.compare(up.y(), box2.up.y()); if (upy_cmp != 0) return upy_cmp; int upz_cmp = Float.compare(up.z(), box2.up.z()); if (upz_cmp != 0) return upz_cmp; return 0; } public boolean contains( Point3D p ) { float c2p = Point3D.diff(center, p).length(); if (c2p <= radius) return true; // on edge or closer return false; } public static float defaultRadius() { return RADIUS; } public Point3D getCorner(int i) { return new Point3D( ((i & 1)!=0) ? getMax().x() : getMin().x(), ((i & 2)!=0) ? getMax().y() : getMin().y(), ((i & 4)!=0) ? getMax().z() : getMin().z() ); } // Return the corner that is farthest along the given direction. public Point3D getExtremeCorner( Vector3D v ) { return new Point3D( v.x() > 0 ? getMax().x() : getMin().x(), v.y() > 0 ? getMax().y() : getMin().y(), v.z() > 0 ? getMax().z() : getMin().z() ); } // Return the index of the corner that // is farthest along the given direction. public int getIndexOfExtremeCorner( Vector3D v ) { int returnValue = 0; if (v.x() > 0) returnValue |= 1; if (v.y() > 0) returnValue |= 2; if (v.z() > 0) returnValue |= 4; return returnValue; } public boolean intersects( Ray3D ray, // input Point3D intersection, // output Vector3D normalAtIntersection // output ) { // Our base is a sphere ( previously we were a box) if ( !new Sphere(center, radius).intersects( ray, intersection, true ) ) { return false; } Vector3D v = new Vector3D(0,1,0); normalAtIntersection = v.normalized(); SmTrace.lg(String.format("EMBox3D.intersects(ray:%s, intersection(%s), normalAtIntersection(%s)", ray, intersection, normalAtIntersection), "intersection"); return true; } public void setCenter(Point3D center) { if (center == null) center = new Point3D(0,0,0); this.center = center; } public void setPosition(Point3D center) { setCenter(center); } public void setRadius(float radius) { this.radius = radius; } public void translate(Vector3D translation) { this.center = new Point3D(center.x()+translation.x(), center.y()+translation.y(), center.z()+translation.z()); } public String toString() { return String.format("r:%.2g c: %s up: %s", radius, center, up); } public Point3D getCenter() { return center; } public float getRadius() { return radius; } public Vector3D getUp() { if (up == null) return UP; // Aligned - use UP return up; } /** * Orient box * null - default orientation - "global up" */ public void setUp(Vector3D up) { if (up == null) this.up = null; else this.up = up.normalized(); } /** * Rotate coordinates to our understanding of up (0,1,0) vs standard (0,0,1) * Expect pop after such as rotate2vRet() */ public static void setOurUp(GLAutoDrawable drawable) { rotate2v(drawable, GL_UP, UP); } /** * Orientation control for drawing */ /** * Rotate from "up" to vector */ public static void rotate2v( GLAutoDrawable drawable, Vector3D v_from, Vector3D v_to) { GL2 gl = (GL2) drawable.getGL(); Vector3D cprod = Vector3D.cross( v_from.normalized(), v_to.normalized() ); final float rad2deg = (float) (180./Math.PI); float av = Vector3D.computeSignedAngle(v_from, v_to, cprod ) * rad2deg; SmTrace.lg(String.format("axis v_from(%s) angle av=%.1f v_to=%s", v_from, av, v_to), "rotate"); gl.glPushAttrib(GL2.GL_TRANSFORM_BIT); gl.glMatrixMode(GL2.GL_MODELVIEW); gl.glPushMatrix(); gl.glRotatef(av, cprod.x(), cprod.y(), cprod.z()); } /** * Rotate from "up" to vector for * special case of axis to axis * Returns true if axis rotation was done * NOTE: rotate2vRet is required after drawing */ public static boolean axisRotate2v( GLAutoDrawable drawable, Vector3D v_from, Vector3D v_to) { boolean rotate_in_plane = true; // true - force rotating in plane of // two vectors if (!rotate_in_plane) { int nzero = 0; if (v_from.x() == 0) nzero++; if (v_from.y() == 0) nzero++; if (v_from.z() == 0) nzero++; if (nzero < 2) return false; nzero = 0; if (v_to.x() == 0) nzero++; if (v_to.y() == 0) nzero++; if (v_to.z() == 0) nzero++; if (nzero < 2) return false; } GL2 gl = (GL2) drawable.getGL(); Vector3D cprod = Vector3D.cross( v_from.normalized(), v_to.normalized() ); final float rad2deg = (float) (180./Math.PI); float av = Vector3D.computeSignedAngle(v_from, v_to, cprod ) * rad2deg; SmTrace.lg(String.format("axis v_from(%s) angle av=%.1f v_to=%s", v_from, av, v_to), "rotate"); gl.glPushAttrib(GL2.GL_TRANSFORM_BIT); gl.glMatrixMode(GL2.GL_MODELVIEW); gl.glPushMatrix(); gl.glRotatef(av, cprod.x(), cprod.y(), cprod.z()); return true; } /** * Return rotation from rotate2v */ public static void rotate2vRet(GLAutoDrawable drawable) { GL2 gl = (GL2) drawable.getGL(); gl.glPopMatrix(); gl.glPopAttrib(); } /** * Orient (rotate) point about given center */ public static Point3D orient(Point3D pt, Vector3D v_from, Vector3D v_to, Point3D center) { if (v_from.equals(v_to)) return pt; // Shortcut if equal float rad2deg = (float) (180./Math.PI); float ax = Vector3D.computeSignedAngle(v_from, v_to, xaxis ) * rad2deg; float ay = Vector3D.computeSignedAngle(v_from, v_to, yaxis ) * rad2deg; float az = Vector3D.computeSignedAngle(v_from, v_to, zaxis ) * rad2deg; Vector3D to_pt = Point3D.diff(pt, center); Vector3D new_vec = EMBox3D.rotate(to_pt, ax, xaxis); new_vec = EMBox3D.rotate(new_vec, ay, yaxis); new_vec = EMBox3D.rotate(new_vec, az, zaxis); Point3D new_pt = Point3D.sum(center, new_vec); return new_pt; } /** * rotate vector by angle around an aligned axis (1,0,0), (0,1,0), or (0,0,1) */ public static Vector3D rotate(Vector3D vec, float angle, Vector3D pole) { float x1 = vec.x(); float y1 = vec.y(); float z1 = vec.z(); float px = pole.x(); float py = pole.y(); float pz = pole.z(); float x2 = px; float y2 = py; float z2 = pz; // Test for alignment int ndim = 0; if (px > 0) { ndim++; y2 = (float) (Math.cos(angle) * y1); z2 = (float) (Math.sin(angle) * z1); } if (py > 0) { ndim++; x2 = (float) (Math.cos(angle) * x1); z2 = (float) (Math.sin(angle) * x1); } if (pz > 0) { ndim++; x2 = (float) (Math.cos(angle) * x1); y2 = (float) (Math.sin(angle) * y1); } if (ndim != 1) { SmTrace.lg(String.format("EMBox3D.rotate pole(%s not aligned", pole)); return vec; } Vector3D new_vec = new Vector3D(x2, y2, z2); return new_vec; } }
Python
UTF-8
1,989
2.9375
3
[ "BSD-2-Clause" ]
permissive
# coding: utf-8 # # Cloud-tracking algorithm # # There has been some major changes to the cloud-tracking algorithm. I have now push most of the changes to the main repository (https://github.com/lorenghoh/loh_tracker), which uses HDF5 for data storage. We have since then moved to Parquet, and I will eventually modify the cloud-tracking algorithm to output Parquet files instead, but for now we will simply create HDF5 files and translate them afterwards. # # So we start with the main branch: # In[1]: get_ipython().run_line_magic('cd', '/tera/users/loh/repos/vlad_cloudtracker/loh_tracker/') get_ipython().run_line_magic('ls', '') # Normally, we will run util/write_json.py # In[3]: get_ipython().run_line_magic('run', 'util/write_json.py CGILS_301K') # Running util/generate_tracking.py then creates the input files for the cloud-tracking algorithm. For this notebook, I've slightly modified this script to only translate two timesteps: # In[4]: get_ipython().run_line_magic('run', 'util/generate_tracking.py') # The resulting input files for the cloudtracking is automatically written in ./data (without checking if the folder exists -- too lazy to fix that now): # In[14]: get_ipython().run_line_magic('ls', 'data') # Then we can start the actual cloud-tracking: # In[2]: get_ipython().run_line_magic('run', 'run_tracker.py') # The cloud-tracking algorithm will now output the full event histories (./data/events.json) in Python Dictionary format. It saves all the merging and splitting events for each cloud and the timesteps they occur -- it is also possible to store the cluster ids associated with these events, which I will update...later. # # The output HDF5 files also store the cloud properties in a dictionary format. For example, # In[2]: get_ipython().run_line_magic('ls', 'hdf5') # In[5]: import h5py f = h5py.File('hdf5/cloudlets_00000000.h5') list(f.keys())[:15] # In[11]: list(f['1']) # In[13]: f['1/core'][...]
Shell
UTF-8
1,815
3.53125
4
[]
no_license
#!/bin/sh # # make the control files for the 6 hour gdas quick look # v1.1 2/99 set -xa bdate=$1 edate=$2 disk=$3 cycle=$4 type=$5 hour=`echo $edate | cut -c9-10` date0=$bdate date1=$edate #date0=`find $disk -name "${cycle}_${type}_stas.????????${hour}" -print | sort \ # | head -n 1 | sed "s/^.*${cycle}_${type}_stas\.//"` #date1=`find $disk -name "${cycle}_${type}_stas.????????${hour}" -print | sort \ # | tail -n 1 | sed "s/^.*${cycle}_${type}_stas\.//"` [ "$date0" = '' ] && continue yr=`echo $date0 | cut -c1-4` mo=`echo $date0 | cut -c5-6` da=`echo $date0 | cut -c7-8` yr1=`echo $date1 | cut -c1-4` date0=`echo $date0 | cut -c1-8` date1=`echo $date1 | cut -c1-8` jday0=`./julian.sh $date0` jday1=`./julian.sh $date1` if [ "$yr" = "$yr1" ];then t=`expr $jday1 - $jday0` else leap=`expr $yr % 4` nbase=${yr1}000 if [ $leap -eq 0 ]; then ndays1=${yr}366 else ndays1=${yr}365 fi t=`expr $jday1 - $nbase` t=`expr $t + $ndays1` t=`expr $t - $jday0` fi ndays=`expr $t + 1` case $mo in 01) month=jan;; 02) month=feb;; 03) month=mar;; 04) month=apr;; 05) month=may;; 06) month=jun;; 07) month=jul;; 08) month=aug;; 09) month=sep;; 10) month=oct;; 11) month=nov;; 12) month=dec;; *) echo "month error $mo" exit 1;; esac gdate="${hour}Z${da}${month}$yr" if [ "${type}" = 'u' -o "${type}" = 'v' ]; then cp uv_stas.ctl ${type}_stas.ctl fi # make pgb.ctl and flx.ctl sed <${type}_stas.ctl -e "s/(date0)/$date0 ${hour}Z/" \ -e "s/(date1)/$date1 ${hour}Z/" \ -e "s/tdef.*\$/tdef $ndays linear $gdate 24hr/" \ > tmp.ctl setdir="dset ${disk}/${cycle}_${type}_stas.%y4%m2%d2%h2" sed -e "s=^dset.*=${setdir}=" tmp.ctl >${type}_stas_${cycle}.ctl if [ ! -s ${disk}/${type}_stas_${cycle}.ctl ];then cp ${type}_stas_${cycle}.ctl ${disk} fi #exit 0
C#
UTF-8
566
2.765625
3
[]
no_license
using System.Collections.Generic; namespace Multiverse { public class Map { public int MinX { get; init; } public int MaxX { get; init; } public int MinY { get; init; } public int MaxY { get; init; } public List<MapPlace> Places { get; init; } public Map(int minX, int maxX, int minY, int maxY, List<MapPlace> places) { MinX = minX; MaxX = maxX; MinY = minY; MaxY = maxY; Places = places; } } }
JavaScript
UTF-8
1,410
3.265625
3
[]
no_license
function main(z = 16) { for (let x = 0; x < z; x++) { var divContain = document.createElement("div"); divContain.id = "miniDiv" + x; divContain.className = "paddingDiv"; document.getElementById('squares').append(divContain); for (let y = 0; y < z; y++) { var divElem = document.createElement("div"); divElem.className = "boxDiv"; divElem.id = "randomC"; document.getElementById('miniDiv' + x).appendChild(divElem); } } var cubes = document.getElementsByClassName('boxDiv'); for (var cube of cubes) { cube.addEventListener('mouseover', newColour); } document.getElementById('btn').addEventListener('click', resetColour); } function resetColour() { document.getElementById("squares").innerHTML = ""; var dimen = prompt("Enter a new value for pad size:"); main(dimen); } function newColour() { this.className = "hover"; // Trying to have dynamically changing background-color // this.id += 'hover'; // var symbols, colour; // symbols = "0123456789ABCDEF"; // colour = "#"; // for (var c = 0; c < 6; c++) { // colour = colour + symbols[Math.floor(Math.random() * 16)]; // } // console.log(colour); // var el = document.getElementsByClassName('hover'); // el.style.cssText = 'background-color: ' + colour; } main();
C++
UTF-8
3,076
3.46875
3
[ "MIT" ]
permissive
// // Created by Xiyun on 2016/10/21. // #include <iostream> #include <vector> #include <string> using namespace std; ///Users/X/Git_Repo/CppPrimer5thAnswer/Cpp_Primer_5E_Learning/Chapter10/E10.20.cpp:22:42: error: call to deleted constructor of 'basic_ostream<char, std::__1::char_traits<char> >' void test(vector<string> &words,ostream &os) { //引用捕获 size_t v1 = 42; char c = ' '; auto f2 = [&v1](){return v1;}; v1 = 10; // os << f2(); // v1 隐士捕获,值捕获 auto wc = find_if(words.begin(),words.end(), [=](const string &a){ return a.size() >= v1;}); //os 隐士捕获,c显示捕获 for_each(words.begin(),words.end(),[&, c](const string &a){os << a << c;}); os << endl; for_each(words.begin(),words.end(), [=, &os](const string &a){os << a << c;}); os << endl; auto f3 = [v1]() mutable {return ++v1;}; os << f3() << endl; //指定lamdba返回类型 transform(words.begin(),words.end(),words.begin(), [](string str) -> string { if(str.size() > 2) { str += "s"; return str; } else { return str; } }); for_each(words.begin(),words.end(), [&os](const string &s){os << s << " ";}); } void elimDups(vector<string> &words) { sort(words.begin(),words.end()); auto end_unique = unique(words.begin(),words.end()); words.erase(end_unique,words.end()); } string make_plural(size_t ctr, const string &word, const string &ending) { return (ctr > 1) ? word + ending : word; } void biggies(vector<string> &words, vector<string>::size_type sz) { //去除重复元素 elimDups(words); //按长度排序 stable_sort(words.begin(),words.end(), [](const string &a, const string &b) {return a.size() < b.size();}); //找到第一个size 大于 给定 sz 的 元素 // auto wc = find_if(words.begin(),words.end(), // [sz](const string &a) // {return a.size() >= sz;}); // auto wc = partition(words.begin(),words.end(), // [sz](const string &s) // {return s.size() < sz;}); size_t wc = count_if(words.begin(),words.end(), [sz](const string &s){return s.size() > sz;}); //计算满足 size >= sz 的元素的数目 // auto count = words.end() - wc; //输出 cout << wc << " " << make_plural(wc,"word","s") << " of length " << sz << " or longer" << endl; //打印长度大于给定值的单词,每个单词后面接一个空格 // for_each(wc,words.end(), // [](const string &elem){cout << elem << "\t";}); } int main() { vector<string> ivec{"hello","world"}; // test(ivec,cout); biggies(ivec,3); return 0; }
Ruby
UTF-8
374
2.78125
3
[ "MIT" ]
permissive
n = gets.to_i li = [] (1..n).each do x, y = gets.split.collect{|i| i.to_i} li.push([[x],[y]]) end for i in (n-1).downto(0) for j in 0...i unless (li[j][0]&li[i][0]).empty? and (li[j][1]&li[i][1]).empty? li[j][0] |= li[i][0] li[j][1] |= li[i][1] li.delete_at(i) break end end end puts li.size-1
Ruby
UTF-8
589
2.9375
3
[]
no_license
class WineBatch include ActiveRecord::Validations attr_accessor :wines def initialize() @wines = [] end def cups @wines.map { |wine| wine.cup } end def << (wine) cups.include?(wine.cup) ? self[wine.cup].quantite += 1 : @wines << wine self end def [](cup) @wines.find { |wine| wine.cup == cup } end def apply_rebate(rebate) wines.each do |wine| unless wine.prix.nil? initial_rebate = wine.prix - wine.achat wine.achat = wine.prix - initial_rebate - wine.achat * (rebate / 100.0) end end end end
Python
UTF-8
3,946
2.515625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
import time import math import sys import os import time from subprocess import Popen, PIPE, check_call import signal one_letter_codes={} one_letter_codes['ALA']='A' one_letter_codes['CYS']='C' one_letter_codes['ASP']='D' one_letter_codes['GLU']='E' one_letter_codes['PHE']='F' one_letter_codes['GLY']='G' one_letter_codes['HIS']='H' one_letter_codes['ILE']='I' one_letter_codes['LYS']='K' one_letter_codes['LEU']='L' one_letter_codes['MET']='M' one_letter_codes['ASN']='N' one_letter_codes['PRO']='P' one_letter_codes['GLN']='Q' one_letter_codes['ARG']='R' one_letter_codes['SER']='S' one_letter_codes['THR']='T' one_letter_codes['VAL']='V' one_letter_codes['TRP']='W' one_letter_codes['TYR']='Y' one_letters = set() for char in one_letter_codes.values(): one_letters.add(char) one_letters_list = [item for item in one_letters] one_letters_list.sort() three_letter_codes = {} for key in one_letter_codes.keys(): val = one_letter_codes[key] three_letter_codes[val] = key three_letter_codes['M'] = 'MET' three_letter_codes['C'] = 'CYS' three_letter_codes['T'] = 'THR' class Reporter: def __init__(self, task ,entries='files', print_output=True): self.print_output = print_output self.start = time.time() self.entries = entries self.lastreport = self.start self.task = task self.report_interval = 1 # Interval to print progress (seconds) self.n = 0 self.completion_time = None if self.print_output: print '\nStarting ' + task self.total_count = None # Total tasks to be processed def set_total_count(self, x): self.total_count = x def report(self,n): self.n = n t = time.time() if self.print_output and self.lastreport < (t-self.report_interval): self.lastreport = t if self.total_count: percent_done = float(self.n) / float(self.total_count) time_now = time.time() est_total_time = (time_now-self.start) * (1.0/percent_done) time_remaining = est_total_time - (time_now-self.start) minutes_remaining = math.floor(time_remaining/60.0) seconds_remaining = int(time_remaining-(60*minutes_remaining)) sys.stdout.write(" Processed: "+str(n)+" "+self.entries+" (%.1f%%) %02d:%02d\r"%(percent_done*100.0, minutes_remaining, seconds_remaining) ) else: sys.stdout.write(" Processed: "+str(n)+" "+self.entries+"\r" ) sys.stdout.flush() def increment_report(self): self.report(self.n+1) def increment_report_callback(self, return_value): self.report(self.n+1) def decrement_report(self): self.report(self.n-1) def add_to_report(self,x): self.report(self.n+x) def done(self): self.completion_time = time.time() if self.print_output: print 'Done %s, processed %d %s, took %.3f seconds\n' % (self.task,self.n,self.entries,self.completion_time-self.start) def elapsed_time(self): if self.completion_time: return self.completion_time - self.start else: return time.time() - self.start class LineReader: def __init__(self,fname): if fname.endswith('.gz'): if not os.path.isfile(fname): raise IOError(fname) self.f = Popen(['gunzip', '-c', fname], stdout=PIPE, stderr=PIPE) self.zipped=True else: self.f = open(fname,'r') self.zipped=False def readlines(self): if self.zipped: for line in self.f.stdout: yield line else: for line in self.f.readlines(): yield line def close(self): if self.zipped: if self.f.poll() == None: os.kill(self.f.pid,signal.SIGHUP) else: self.f.close()
Markdown
UTF-8
4,332
2.828125
3
[ "MIT" ]
permissive
# Class: Game_Followers ## Game_Followers () #### new Game_Followers () 隊列の並びなどを管理する。[Game_Follower](Game_Follower.md) を配列として定義したクラス。 [Game_Player#followers](Game_Player.html#followers) メソッドで得られる。 ##### Properties: | Name | Type | Description | | --- | --- | --- | | `_visible` | Boolean | | | `_gathering` | Boolean | | | `_data` | [Array](Array.md).<[Game_Follower](Game_Follower.md)> | | <dl> </dl> ### Methods #### areGathered () → {Boolean} [隊列メンバー]が集合しているか。 <dl> </dl> ##### Returns: <dl> <dt> Type </dt> <dd> <span>Boolean</span> </dd> </dl> #### areGathering () → {Boolean} [隊列メンバー]の集合中か。 <dl> </dl> ##### Returns: <dl> <dt> Type </dt> <dd> <span>Boolean</span> </dd> </dl> #### areMoving () → {Boolean} [隊列メンバー]が移動中か。 <dl> </dl> ##### Returns: <dl> <dt> Type </dt> <dd> <span>Boolean</span> </dd> </dl> #### follower (index) → {[Game_Follower](Game_Follower.md)} 指定した番号の[隊列メンバー]を返す。 ##### Parameters: | Name | Type | Description | | --- | --- | --- | | `index` | [Number](Number.md) | | <dl> </dl> ##### Returns: <dl> <dt> Type </dt> <dd> <span><a>Game_Follower</a></span> </dd> </dl> #### forEach (callback, thisObject) 各[隊列メンバー]オブジェクトを対象に関数を実行する。 ##### Parameters: | Name | Type | Description | | --- | --- | --- | | `callback` | function | | | `thisObject` | * | | <dl> </dl> #### gather () [隊列メンバーの集合]。 <dl> </dl> #### hide () [隊列メンバー]を表示しない。 <dl> </dl> #### initialize () オブジェクト生成時の初期化。 <dl> </dl> #### isSomeoneCollided (x, y) → {Boolean} 指定位置に[隊列メンバー]の誰かがいるか。 ##### Parameters: | Name | Type | Description | | --- | --- | --- | | `x` | [Number](Number.md) | タイル数 | | `y` | [Number](Number.md) | タイル数 | <dl> </dl> ##### Returns: <dl> <dt> Type </dt> <dd> <span>Boolean</span> </dd> </dl> #### isVisible () → {Boolean} [隊列メンバー]が表示されているか。 <dl> </dl> ##### Returns: <dl> <dt> Type </dt> <dd> <span>Boolean</span> </dd> </dl> #### jumpAll () [隊列メンバー]全員を、プレイヤーキャラクタの[ジャンプ]高さに揃える。 <dl> </dl> #### refresh () [隊列メンバー]を更新。 <dl> </dl> #### reverseEach (callback, thisObject) 各[隊列メンバー]オブジェクトを対象に逆順に関数を実行する。 ##### Parameters: | Name | Type | Description | | --- | --- | --- | | `callback` | function | | | `thisObject` | * | | <dl> </dl> #### show () [隊列メンバー]を表示。 <dl> </dl> #### synchronize (x, y, d) 指定の位置と向きに[隊列メンバー]を揃える。 ##### Parameters: | Name | Type | Description | | --- | --- | --- | | `x` | [Number](Number.md) | タイル数 | | `y` | [Number](Number.md) | タイル数 | | `d` | [Number](Number.md) | 向き(テンキー対応) | <dl> </dl> #### update () [隊列メンバー]をアップデート。 <dl> </dl> #### updateMove () [隊列メンバー]の移動をアップデート。 <dl> </dl> #### visibleFollowers () → {[Array](Array.md).<[Game_Follower](Game_Follower.md)>} 表示中の[隊列メンバー]の配列を返す。 <dl> </dl> ##### Returns: <dl> <dt> Type </dt> <dd> <span><a>Array</a>.&lt;<a>Game_Follower</a>&gt;</span> </dd> </dl> <br> Documentation generated by [JSDoc 3.5.5](https://github.com/jsdoc3/jsdoc)
C
UTF-8
2,329
2.8125
3
[]
no_license
/* Some Defs are shamelessly stolen by OLK delise@online-club.de The type of an value that fits in an MMX register (note that long long constant values MUST be suffixed by LL and unsigned long long values by ULL, lest they be truncated by the compiler) */ #include <math.h> typedef union { long long q; /* Quadword (64-bit) value */ unsigned long long uq; /* Unsigned Quadword */ int d[2]; /* 2 Doubleword (32-bit) values */ unsigned int ud[2]; /* 2 Unsigned Doubleword */ short w[4]; /* 4 Word (16-bit) values */ unsigned short uw[4]; /* 4 Unsigned Word */ char b[8]; /* 8 Byte (8-bit) values */ unsigned char ub[8]; /* 8 Unsigned Byte */ float f[2]; /* Float (32-bit) single precision */ } mmx_t; #include "mmx_arithmetic.h" #include "mmx_comparison.h" #include "mmx_conversion.h" #include "mmx_logical.h" #include "mmx_shift.h" #include "3dnow_arithmetic.h" #include "3dnow_comparison.h" #include "3dnow_conversion.h" #include "3dnow_init.h" #include "3dnow_transcendental.h" struct {unsigned high, low;} tsc1, tsc2; #define GET_TSC(X) __asm__(".byte 0x0f,0x31":"=a" (X.low), "=d" (X.high)) extern void mmx_regdump (mmx_t mmx_reg); // Function to test if mmx instructions are supported... inline extern int mmx_ok(void) { /* Returns 1 if mmx instructions are ok, 0 if hardware does not support mmx */ register int ok = 0; __asm__ __volatile__ ( /* Get CPU version information */ "movl $1, %%eax\n\t" "cpuid\n\t" "movl %%edx, %0" : "=a" (ok) : /* no input */ ); return((ok & 0x800000) == 0x800000); } /* Empty MMX State (used to clean-up when going from mmx to float use of the registers that are shared by both; note that there is no float-to-mmx operation needed, because only the float tag word info is corruptible) */ // #define emms() __asm__ __volatile__ ("emms") /* TUNE_ME: dump of mmx_register */ extern void mmx_regdump (mmx_t mmx_reg) { short i; printf("64 bit reg: %016llx\n", mmx_reg.q); printf("Hi-Float: %f Lo-Float: %f\n",mmx_reg.f[1] ,mmx_reg.f[0]); for (i=1; i>=0; i--) printf("d[%d]:%08x ", i, mmx_reg.d[i]); printf("\n"); for (i=3; i>=0; i--) printf("w[%d]:%04x ", i, mmx_reg.uw[i]); printf("\n"); for (i=7; i>=0; i--) printf("b[%d]:%02x ", i, mmx_reg.ub[i]); printf("\n\n"); }
Markdown
UTF-8
6,536
3
3
[ "MIT", "Apache-2.0" ]
permissive
--- layout: post title: "年度总结 | 愿未来平凡的每一天都有值得回忆的瞬间" subtitle: "年度总结" date: 2019-02-20 24:00:00 author: "Lyle" header-img: "img/post-bg-ndzj.jpg" header-mask: 0.5 catalog: true tags: - 总结 - RSS - 写作 - 设计 - 学习 --- ## 2018年年终总结 2018年,仔细想想可能是无所事事而又很丧的一年。有些选择决定了以后的方向,但也只有在经久之后才能起化学反应,明白当初的决定是否正确。 > 每一个抉择都是一种交换,拿你现在愿意放弃的东西,交换你觉得更重要的东西。 2018年上半年很丧,因为一些心态的原因,从心底开始排斥非自由感以及颓废。下半年,换了新的城市,开启了新的旅途。这可能看起来算是一种逃避,我想也许是,但更多的应该是当下现状的不满。希望靠近那满天的星辰,找到自己所追求的目标,剩下的就是风雨兼程。 毕竟我们所见的,都是光啊。 ### 产品 5月初在花费近两年心血的产品上架之后,觉得终于完成了自己历史阶段的使命。期望开启新的征途。很幸运在毕业后以产品岗进入这家公司,从而在后续逐渐的对产品岗位有了更深的理解,也认识了很多好玩有趣的人。有人说工作就是创业,我觉得那时候的我就是的。因为当时的我确实是在这么执行下去的。起早贪黑,周末近乎无休的全天候为未来的产品职业规划做准备,希望在产品的技能上有所成长。启示一个时期的努力也许当时未能直接看的到,但它就像酒一样,时间越久酝酿的越香。人在成长的阶段里,每个阶段都需要有自己为之驱动的动力,无论爱情亦或理想。 五一节假日后离开了老主顾,同时也离开了武汉,那个我生活了五年的城市,前往一个陌生的城市。我想最初的初衷可能真的是因为这个城市真的有很多很多有意思的人啊,看到他们你就会不自主的想要靠近他们。就像在你眼里星星一样,就那么闪闪发光的每天晃啊晃。 杭州是个不错的城市,那是一种在骨子里才会有的文化氛围,驱动着你向前。新岗位新的挑战,进军电商行业,一个陌生但又值得期待的行业。 ### 设计 对设计因为计划的驱动,再不折腾就老了,嗯。于是开始了尝试设计领域的驱动,就这么简单,很多事情的原动力就是这么简单,不过设计的还不够好,后边还需要再多尝试练习,之前更多的是使用原型工具进行产品的设计,之后不断累计对产品的设计感,打算自己启动去尝试做做设计,希望自己有个职业上的能有所进步。 - **Weather** ![](https://i.loli.net/2019/03/16/5c8cb6e245df0.jpg) - **Book** ![](https://i.loli.net/2019/03/16/5c8cb979ddc1d.png) ### 技能 - **剪辑** 尝试过一次剪辑的原因是意外驱动,因为有天听到了一首很好听的歌,而刚好也有一部很喜欢的动漫。于是,干柴烈火?一发不可收拾。陌生的外地只有一个人的时候会感觉分外孤独,嗯,那些小伙伴们…… [视频地址](https://www.bilibili.com/video/av45300802/) - **RSS** 作为互联网人,尤其是产品经理需要时刻关注互联网动态。在最初选择Inoreader,但为非付费用户,广告频繁显示的情况下,最终选择放弃。实际上其更新速度和设置对用户还是很友好的,如果感兴趣的小伙伴可以尝试。作为算是 RSS 的重度用户,几年来一直坚持把 RSS 作为自己最重要的信息获取来源。App Store 上主流的 RSS 客户端工具,我基本都尝试过。后来选择了feedly作为主力的选择,但因为某一刻意外的feedly账号无法登陆Reeder,被迫选择其他的方式。但也是因为这一次的尝试,是很幸运的选择。所以生活就是这么多意外组成的,你永远不知道下一刻会给你带来怎样的惊喜。 方案:Docker 下自建 Tiny Tiny RSS,目前符合当前需求,如果有小伙伴感兴趣,后续会出一篇文章讲一下搭建的过程。 ### 足迹 **杭州** **广州** **上海** 因缘际会的走走停停,今年反而是我去过最多地方的一年。诗情画意的杭州西湖,美味可口的广州美食,还有不靠谱面基的上海,如果下次面基,我一定选择下午和夜间在出门约,基友的生活作息太不规律了。 ### 影视 看的有很多,但是挑一些我觉得还不错的就当推荐了,排名不分先后,感兴趣的可以看看。 - **电影** 《无名之辈》——强烈推荐 《来电狂响》 《我不是药神》 《无双》 《一出好戏》 《西红柿首富》 《红海行动》 《唐人街探案2》 《无问东西》 《网络迷踪》 - **综艺** 《这就是街舞》——最喜欢子奇Zaki,踩点王子 《声临其境》 - **电视剧** 《将夜》——猫腻的小说改编,很喜欢春风亭那段江湖,更喜欢的是师徒二人日常那段,很接地气。 - **小说** 《雪中悍刀行》 《剑来》 《一念永恒》 嗯,其实还有很多很多想要读的书籍都还没读,2019年希望可以多读一些书。 ### 情感 离开了熟悉的地方去到陌生的城市,就会莫名的想念以前的时光。在一起的时候并未觉得多珍贵,离开后才知道那样的时光只会越来越少。毕竟当大家都不在同一座城市的时候,再次在一条平行线上早已不知是哪一年哪一月的那一天。每年的过年都开始无比期待回到家,好友聚聚,聊聊天,唠唠嗑的时间也是感觉充实而有意思。时光不愿停留,也不能停留。我们都在不知不觉中长大,然后各奔东西。 ### 期望 > 我们提着过去走入人群 > > 寻找着一个位置安放自己 > > 我多想再见你 > > 哪怕匆匆一眼就别离 > > 路灯下昏黄的剪影 > > 越走越漫长的林径 2019新的一年,希望再进入一次飞速的成长。你需要做的是不断的努力学习,变成你想成为的样子。我想每天都看到凌晨5点的阳光。 > 愿未来平凡的每一天都有值得回忆的瞬间。 **—ChangLog** 2019.02.20 - 博客初拟
Markdown
UTF-8
2,022
2.875
3
[ "MIT" ]
permissive
--- pageTitle: About layout: markdown --- # About Me ## Professional life Howdy! My name is Dustin. I'm a Design Technologist working on the Design System at [Indeed] where we like to say - We help people get jobs! Before finding design systems, I was a [Drupalist] working on Very Large Websites™ for media brands and universities you've definitely heard of. Before realizing HTML and CSS could pay the bills, I was an aspiring filmmaker who enjoyed the more technical aspects of audio / video editing and visual effects. ## The other 128 hours of the week I'm a lifelong cyclist who has recently rediscovered riding on dirt. I've got a [dentist quality mountain bike][yeti] and a [gravel bike][niner] that isn't quite as fancy, but it still feels like I have wings on the downhills. I also have a pretty stacked [garage gym][fringesport] where my friends and I lift [heavy things][rogue] and put them back down again. Mostly powerlifting with some strongman aspirations and a dash of HIIT on the weekends to work the beach muscles. I like to tinker with [Arduino adjacent][ada] electronics and [3d printers][prusa]. When public gatherings were more common, I helped run [dorkbot Austin][dorkbot] for several years and had a part in getting [SXSW Create][sxswcreate] off the ground. ## On the road again After a few years in Boston, I'm back in Austin, eating all of the tacos I can get my hands on. One of these days, I'm going to buy some land in Vermont or New Mexico with my closest friends and enjoy a pastoral lifestyle with high speed internet. New England has the best sandwiches, but the Southwest has the best tortilla based foods. [drupalist]: https://drupal.org [indeed]: https://indeed.com [yeti]: https://yeticycles.com [niner]: https://ninerbikes.com [fringesport]: https://fringesport.com [rogue]: https://roguefitness.com [ada]: https://adafruit.com [prusa]: https://prusa3d.com [dorkbot]: https://dorkbot.org [sxswcreate]: https://hackaday.com/2015/03/17/sxsw-create-atx-hackerspace-area/
JavaScript
UTF-8
3,032
4.59375
5
[]
no_license
/* https://www.codewars.com/kata/520b9d2ad5c005041100000f * * Move the first letter of each word to the end of it, then add "ay" to the end of the word. Leave punctuation marks * untouched. */ // INPUT(S) // - String, consisting of words to convert to Pig Latin // - Pig Latin: Taking a word, moving its first letter to the end of the word, then appending "ay" // // OUTPUT(S) // - String, representing the Pig Latin version of the given argument // // REQUIREMENTS / NOTES // - Write a function that takes a string and transforms each word in the string as follows: // - Take the first letter of the word and move it to the end // - Append 'ay' after // - Each letter in the new string should maintain its case from the original // // CLARIFICATIONS // - Should I expect any non-string input types? (No. All arguments given will be strings.) // - How should the function handle empty strings? (Return ''.) // - How should the function address letter case, e.g., should letter case be maintained? (Yes.) // - Will the argument strings given contain any other characters besides letters, spaces, and punctuation? (No.) // // EXAMPLES // console.log(simplePigLatin('hello')); // 'ellohay' // console.log(simplePigLatin('Hello')); // 'elloHay' // console.log(simplePigLatin('Hello world!')); // 'elloHay orldway!' // console.log(simplePigLatin('Hello world! How are you?')); // 'elloHay orldway! owHay reaay ouyay?' // console.log(simplePigLatin('')); // '' // console.log(simplePigLatin('!@#$')); // '!@#$' // // DATA STRUCTURE(S) // - Strings, which enable index references and concatenation // - Arrays, which enable element iteration and mapping // // ALGORITHM // - Guard cases: // - Return empty string if argument is empty string // - Return original string if argument does not contain letters // - Extract each word from the argument string and store in an array // - Convert each word in that array to its Pig Latin equivalent // - Replace each word in the original string with its Pig Latin equivalent // - Initialize a variable and set it to the return value of replacing the first word in the original string // - Loop through each word in the word array and replace the current word with its Pig Latin equivalent // - Return the resulting string function simplePigLatin(string) { if (typeof string === 'string' && string.length === 0) { return ''; } else if (!/[A-Za-z]/g.test(string)) { return string; } const SUFFIX = 'ay'; return string.replace(/\w+/g, (word) => { return word.slice(1) + word[0] + SUFFIX; }); } // Generic Cases console.log(simplePigLatin('hello')); // 'ellohay' console.log(simplePigLatin('Hello')); // 'elloHay' console.log(simplePigLatin('This is my string')); // 'hisTay siay ymay tringsay' console.log(simplePigLatin('Hello world!')); // 'elloHay orldway!' console.log(simplePigLatin('Hello world! How are you?')); // 'elloHay orldway! owHay reaay ouyay?' console.log(simplePigLatin('')); // '' console.log(simplePigLatin('!@#$')); // '!@#$'
C++
UTF-8
12,311
2.859375
3
[]
no_license
#pragma once ///////////////////////////////////////////////////////////////////// // DbCore.h - Implements NoSql database prototype // // ver 1.0 // // Jim Fawcett, CSE687 - Object Oriented Design, Spring 2018 // ///////////////////////////////////////////////////////////////////// /* * Package Operations: * ------------------- * This package provides two classes: * - DbCore implements core NoSql database operations, but does not * provide editing, querying, or persisting. Those are left as * exercises for students. * - DbElement provides the value part of our key-value database. * It contains fields for name, description, date, child collection * and a payload field of the template type. * The package also provides functions for displaying: * - set of all database keys * - database elements * - all records in the database * Required Files: * --------------- * DbCore.h, DbCore.cpp * DateTime.h, DateTime.cpp * Utilities.h, Utilities.cpp * * Maintenance History: * -------------------- * ver 1.0 : 10 Jan 2018 * ver 1.1 : 2 Feb 2018 */ #include <unordered_map> #include <string> #include <vector> #include <iostream> #include <iomanip> #include <algorithm> #include "../DateTime/DateTime.h" namespace NoSqlDb { using Key = std::string; using Keys = std::vector<Key>; using Category = std::string; using Categories = std::vector<Category>; using FilePath = std::string; #ifndef _PAYLOAD_ #define _PAYLOAD_ // Payload structure, NoSql database will store this prototype. struct PayLoad { Categories& categories() { return categories_; } Categories categories() const { return categories_; } void categories(const Categories& categories) { categories_ = categories; } FilePath& fpath() { return fpath_; } FilePath fpath() const { return fpath_; } void fpath(const FilePath& fpath) { fpath_ = fpath; } bool empty() { return fpath_.empty(); } void clear() { categories_.clear(); fpath_.clear(); } void edit(PayLoad& in) { Categories cat = in.categories(); if (!cat.empty()) { for (auto& it : cat) { Categories::iterator itr = find(categories_.begin(), categories_.end(), it); if (itr != categories_.end()) *itr = it; else categories_.push_back(it); } } if (!in.fpath().empty() && (in.fpath().compare(fpath_) != 0)) fpath_ = in.fpath(); } friend std::ostream& operator<<(std::ostream&, const PayLoad&); private: Categories categories_; FilePath fpath_; }; inline std::ostream& operator<<(std::ostream& out, const PayLoad& p) { out << p.fpath_; return out; } #endif ///////////////////////////////////////////////////////////////////// // DbElement class // - provides the value part of a NoSql key-value database template<typename T> class DbElement { public: using Children = std::vector<Key>; // methods to get and set DbElement fields std::string& name() { return name_; } std::string name() const { return name_; } void name(const std::string& name) { name_ = name; } std::string& descrip() { return descrip_; } std::string descrip() const { return descrip_; } void descrip(const std::string& name) { descrip_ = name; } DateTime& dateTime() { return dateTime_; } DateTime dateTime() const { return dateTime_; } void dateTime(const DateTime& dateTime) { dateTime_ = dateTime; } Children& children() {return children_; } Children children() const { return children_; } void children(const Children& children) { children_ = children; } T& payLoad() { return payLoad_; } T payLoad() const { return payLoad_; } void payLoad(const T& payLoad) { payLoad_ = payLoad; } void clear(); private: std::string name_; std::string descrip_; DateTime dateTime_; Children children_; T payLoad_; }; template<typename T> void DbElement<T>::clear() { name_.clear(); descrip_.clear(); children_.clear(); payLoad_.clear(); } ///////////////////////////////////////////////////////////////////// // DbCore class // - provides core NoSql db operations // - does not provide editing, querying, or persistance operations template <typename T> class DbCore { public: using Key = std::string; using Keys = std::vector<Key>; using Children = Keys; using DbStore = std::unordered_map<Key,DbElement<T>>; using iterator = typename DbStore::iterator; // methods to access database elements Keys keys(); bool contains(const Key& key); size_t size(); DbElement<T>& operator[](const Key& key); DbElement<T> operator[](const Key& key) const; typename iterator begin() { return dbStore_.begin(); } typename iterator end() { return dbStore_.end(); } // methods to get and set the private database hash-map storage DbStore& dbStore() { return dbStore_; } DbStore dbStore() const { return dbStore_; } void dbStore(const DbStore& dbStore) { dbStore_ = dbStore; } bool dbAddElem(const Key&, DbElement<T>&); bool dbEditElem(const Key&, DbElement<T>&); bool dbDelElem(const Key&); bool dbAddChild(const Key&, const Key&); bool dbDelChild(const Key&, const Key&); private: DbStore dbStore_; }; ///////////////////////////////////////////////////////////////////// // DbCore<T> methods //----< does db contain this key? >---------------------------------- template<typename T> bool DbCore<T>::contains(const Key& key) { iterator iter = dbStore_.find(key); return iter != dbStore_.end(); } //----< returns current key set for db >----------------------------- template<typename T> typename DbCore<T>::Keys DbCore<T>::keys() { DbCore<T>::Keys dbKeys; DbStore& dbs = dbStore(); size_t size = dbs.size(); dbKeys.reserve(size); for (auto item : dbs) { dbKeys.push_back(item.first); } return dbKeys; } //----< return number of db elements >------------------------------- template<typename T> size_t DbCore<T>::size() { return dbStore_.size(); } //----< extracts value from db with key >---------------------------- /* * - indexes non-const db objects */ template<typename T> DbElement<T>& DbCore<T>::operator[](const Key& key) { if (!contains(key)) { dbStore_[key] = DbElement<T>(); } return dbStore_[key]; } //----< extracts value from db with key >---------------------------- /* * - indexes const db objects */ template<typename T> DbElement<T> DbCore<T>::operator[](const Key& key) const { if (!contains(key)) { dbStore_[key] = DbElement<T>(); } return dbStore_[key]; } //----< Delete DbElement record from db >---------------------------- template<typename T> bool DbCore<T>::dbDelElem(const Key& key) { if (!contains(key)) return false; dbStore_.erase(key); //Deleting relationship allover typename DbCore<T>::DbStore& dbs = dbStore_; for (auto& item : dbs) { if (findVec<Key>(item.second.children(), key)) dbDelChild(item.first, key); } return true; } // return true if value is found in the vector template<typename T> bool findVec(std::vector<T>& vec, const T& value) { typename std::vector<T>::iterator it = std::find(vec.begin(), vec.end(), value); if (it != vec.end()) return true; return false; } //----< Add Child relationship to a record >---------------------------- template<typename T> bool DbCore<T>::dbAddChild(const Key& key, const Key& child) { if (!contains(key) || !contains(child)) { std::cout << "\n Error! No such key to add"; return false; } Children& childrn = dbStore_[key].children(); Children::iterator it = find(childrn.begin(), childrn.end(), child); if (it == childrn.end()) childrn.push_back(child); return true; } //----< Delete Child relationship to a record >---------------------------- template<typename T> bool DbCore<T>::dbDelChild(const Key& key, const Key& child) { if (!contains(key)) { std::cout << "\n Error! No such key to delete"; return false; } Children& childrn = dbStore_[key].children(); Children::iterator it = find(childrn.begin(), childrn.end(), child); if (it != childrn.end()) childrn.erase(it); return true; } //----< Add DbElement record into db >---------------------------- template<typename T> bool DbCore<T>::dbAddElem(const Key& key, DbElement<T>& dbElem) { if (contains(key)) return false; //dbStore_.insert(key, dbElem); dbStore_[key] = dbElem; return true; } //----< Edit DbElement record into db >---------------------------- template<typename T> bool DbCore<T>::dbEditElem(const Key& key, DbElement<T>& dbElem) { if (!contains(key)) return false; //Comparing name if (!(dbElem.name().empty()) && (dbStore_[key].name().compare(dbElem.name()) != 0)) dbStore_[key].name() = dbElem.name(); //Comparing description if (!(dbElem.descrip().empty()) && dbStore_[key].descrip().compare(dbElem.descrip()) != 0) dbStore_[key].descrip() = dbElem.descrip(); //Comparing date time if (!(dbStore_[key].dateTime() == dbElem.dateTime())) dbStore_[key].dateTime() = dbElem.dateTime(); if (!dbElem.payLoad().empty()) { //Compare and edit payload dbStore_[key].payLoad().edit(dbElem.payLoad()); } return true; } ///////////////////////////////////////////////////////////////////// // display functions //----< display database key set >----------------------------------- template<typename T> void showKeys(DbCore<T>& db, std::ostream& out = std::cout) { out << "\n "; for (auto key : db.keys()) { out << key << " "; } } //----< show record header items >----------------------------------- inline void showHeader(std::ostream& out = std::cout, bool flag = false) { out << "\n "; out << std::setw(26) << std::left << "DateTime"; out << std::setw(10) << std::left << "Name"; out << std::setw(25) << std::left << "Description"; out << std::setw(50) << std::left << "Payload"; if(flag) out << std::setw(25) << std::left << "Categories"; out << "\n "; out << std::setw(26) << std::left << "------------------------"; out << std::setw(10) << std::left << "--------"; out << std::setw(25) << std::left << "-----------------------"; out << std::setw(50) << std::left << "-----------------------"; if (flag) out << std::setw(25) << std::left << "-----------------------"; } //----< display DbElements >----------------------------------------- template<typename T> void showElem(const DbElement<T>& el, std::ostream& out = std::cout, bool flag = false) { out << "\n "; out << std::setw(26) << std::left << std::string(el.dateTime()); out << std::setw(10) << std::left << el.name(); out << std::setw(25) << std::left << el.descrip(); if (flag) { PayLoad py = el.payLoad(); out << std::setw(50) << std::left << py; for (auto& it : py.categories()) { out << it << "|"; } }else out << std::setw(25) << std::left << el.payLoad(); typename DbElement<T>::Children children = el.children(); if (children.size() > 0) { out << "\n child keys: "; for (auto key : children) { out << " " << key; } } } //----< display all records in database >---------------------------- template<typename T> void showDb(const DbCore<T>& db, std::ostream& out = std::cout, bool flag = false) { //out << "\n "; //out << std::setw(26) << std::left << "DateTime"; //out << std::setw(10) << std::left << "Name"; //out << std::setw(25) << std::left << "Description"; //out << std::setw(25) << std::left << "Payload"; //out << "\n "; //out << std::setw(26) << std::left << "------------------------"; //out << std::setw(10) << std::left << "--------"; //out << std::setw(25) << std::left << "-----------------------"; //out << std::setw(25) << std::left << "-----------------------"; showHeader(out, flag); typename DbCore<T>::DbStore dbs = db.dbStore(); for (auto item : dbs) { showElem(item.second, out, flag); } } }
Java
BIG5
1,413
3.71875
4
[]
no_license
/* Ĥ@ܼƹB */ public class TestVar{ public static void main(String args[]){ // //byte -128~127 byte b = 10; byte ByteMin = Byte.MIN_VALUE; byte ByteMax = Byte.MAX_VALUE; //short -32758~32767 short s = 20; short ShortMin = Short.MIN_VALUE; short ShortMax = Short.MAX_VALUE; //int Integer.MIN_VALUE ~ Integer.MAX_VALUE int i = Integer.MAX_VALUE; //long Long.MIN_VALUE ~ Long.MAX_VALUE long l = Long.MAX_VALUE; System.out.println(b); System.out.println(ByteMin); System.out.println(ByteMax); System.out.println(s); System.out.println(ShortMin); System.out.println(ShortMax); System.out.println(ShortMax+1); //Short S`,[1AȬint System.out.println(i); System.out.println(i+1); //long `,ܦt System.out.println(l); //BI //float Ʀr[WfF,jഫ~floatܤp float f = 1.0f; //double w]pơA]i[dDASvT double d = 2.0; System.out.println(f); System.out.println(d); //rBL //char u@r char ch = 'A'; char ch2 = ''; char chspace = ' '; //boolean true false boolean bool = true; boolean boolf = false; System.out.println(ch); System.out.println(ch2); System.out.println(bool); System.out.println(boolf); } }
SQL
UTF-8
1,818
3.625
4
[]
no_license
/*데이터 조회 명령 select [all distinct distinctrow] 칼럼명 from 테이블 where 조건문 group by 그룹명 having 그룹조건 order by asc[오름차순] desc[내림차순] */ select lno, titl, mrno from lect where mrno is null order by titl asc; /* 비교연산자 */ select lno, titl, mrno from lect where mrno = 32; select lno, titl, mrno from lect where mrno != 32; select lno, titl, mrno from lect where mrno <> 32; select lno,titl, mrno, pric from lect where pric > 300000; select lno, titl, mrno, pric from lect where pric < 300000; select lno, titl, pric, (pric - ( pric * 0.2)) pric2 from lect; select titl, sdt, date_add(sdt, interval 27 day) from lect; select lno,titl, mrno, pric from lect where pric > 300000 and pric < 500000; select lno,titl, mrno, pric from lect where pric < 300000 or pric > 1000000; select lno, titl, mrno from lect where mrno != 32; select lno, titl, mrno from lect where mrno = 32; select lno, titl, mrno from lect where not mrno = 32; select lno, titl, mrno from lect where not mrno = 'null'; select lno, titl, mrno from lect where not mrno is null select lno,titl, mrno from lect where mrno in (31,32) select lno,titl from lect where titl = '자바기초'; select lno,titl from lect where titl like '웹%'; select lno,titl from lect where titl like '%과정'; select * from croom where name like '강남_01' select lno, titl, pric from lect where pric between 150000 and 450000; select lno, titl, sdt, edt from lect where sdt between '2017-05-01' and '2017-06-30'; select lno, titl, crmno from lect where crmno is null; select mrno, posi from mgr union select tno, hmpg from tcher union select sno, schl_nm from stud; select mrno from mgr union select tno from tcher; select mrno from mgr union all select tno from tcher;
Python
UTF-8
2,150
2.859375
3
[ "MIT" ]
permissive
from evolutionary_search import EvolutionaryAlgorithmSearchCV, maximize import sklearn.datasets import numpy as np from sklearn.model_selection import StratifiedKFold from sklearn.svm import SVC import unittest import random def func(x, y, m=1.0, z=False): return m * (np.exp(-(x ** 2 + y ** 2)) + float(z)) def readme(): data = sklearn.datasets.load_digits() X = data["data"] y = data["target"] paramgrid = { "kernel": ["rbf"], "C": np.logspace(-9, 9, num=25, base=10), "gamma": np.logspace(-9, 9, num=25, base=10), } random.seed(1) cv = EvolutionaryAlgorithmSearchCV( estimator=SVC(), params=paramgrid, scoring="accuracy", cv=StratifiedKFold(n_splits=4), verbose=1, population_size=10, gene_mutation_prob=0.10, gene_crossover_prob=0.5, tournament_size=3, generations_number=5, ) cv.fit(X, y) return cv class TestEvolutionarySearch(unittest.TestCase): def test_cv(self): def try_with_params(**kwargs): cv = readme() cv_results_ = cv.cv_results_ print("CV Results:\n{}".format(cv_results_)) self.assertIsNotNone(cv_results_, msg="cv_results is None.") self.assertNotEqual(cv_results_, {}, msg="cv_results is empty.") self.assertAlmostEqual( cv.best_score_, 1.0, delta=0.05, msg="Did not find the best score. Returned: {}".format(cv.best_score_), ) try_with_params() def test_optimize(self): """ Simple hill climbing optimization with some twists. """ param_grid = {"x": [-1.0, 0.0, 1.0], "y": [-1.0, 0.0, 1.0], "z": [True, False]} args = {"m": 1.0} best_params, best_score, score_results, _, _ = maximize( func, param_grid, args, verbose=True ) print("Score Results:\n{}".format(score_results)) self.assertEqual(best_params, {"x": 0.0, "y": 0.0, "z": True}) self.assertEqual(best_score, 2.0) if __name__ == "__main__": unittest.main()
Java
UTF-8
6,458
1.828125
2
[]
no_license
//教育機能の目次 package com.example.dneshiboshiken; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Spinner; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import android.widget.Toast; import com.example.dneshiboshiken.R; import com.example.dneshiboshiken.R.array; import com.example.dneshiboshiken.R.id; import com.example.dneshiboshiken.R.layout; import java.io.BufferedReader; import java.io.IOException; import java.io.BufferedWriter; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.Calendar; public class Write_child_9_2_2 extends Activity { //目次の項目だけボタンを定義 private Button button_Write_child_9_12_2_back; private Button button_Write_child_9_12_2_home; private Button button_Write_child_9_12_2_next; EditText et[]; int numOfButton[]; Spinner spin[]; String labels[][]; CheckBox cb[]; String fileName; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.write_child_9_2_2); //画面レイアウトを指定(res/layout/index_read.xml) //それぞれのボタンにクリック時の処理を表示 button_Write_child_9_12_2_back = (Button) findViewById(R.id.ButtonLock); button_Write_child_9_12_2_back.setOnClickListener(new View.OnClickListener(){ public void onClick(View v) { button_Write_child_9_12_2_back_onClick(); } }); button_Write_child_9_12_2_home = (Button) findViewById(R.id.ButtonUnlock); button_Write_child_9_12_2_home.setOnClickListener(new View.OnClickListener(){ public void onClick(View v) { button_Write_child_9_12_2_home_onClick(); } }); button_Write_child_9_12_2_next = (Button) findViewById(R.id.ButtonCancel); button_Write_child_9_12_2_next.setOnClickListener(new View.OnClickListener(){ public void onClick(View v) { button_Write_child_9_12_2_next_onClick(); } }); //ファイル名の指定 fileName="write_9_2.txt"; int numOfCheckBox=0; //エディットテキストを宣言し空欄に int numOfEditText=7; et=new EditText[numOfEditText]; et[0]=(EditText)findViewById(R.id.EditText_write_child_9_2_2_01); et[1]=(EditText)findViewById(R.id.EditText_write_child_9_2_2_02); et[2]=(EditText)findViewById(R.id.EditText_write_child_9_2_2_03); et[3]=(EditText)findViewById(R.id.EditText_write_child_9_2_2_04); et[4]=(EditText)findViewById(R.id.EditText_write_child_9_2_2_05); et[5]=(EditText)findViewById(R.id.EditText_write_child_9_2_2_06); et[6]=(EditText)findViewById(R.id.EditText_write_child_9_2_2_07); for(int i=0;i<et.length;i++){ et[i].setText(""); } cb=new CheckBox[numOfCheckBox]; //スピナーの宣言と表示する文字列配列の設定 spin=new Spinner[6]; spin[0]=(Spinner)findViewById(R.id.Spinner01); spin[1]=(Spinner)findViewById(R.id.Spinner02); spin[2]=(Spinner)findViewById(R.id.Spinner03); spin[3]=(Spinner)findViewById(R.id.Spinner04); spin[4]=(Spinner)findViewById(R.id.Spinner05); spin[5]=(Spinner)findViewById(R.id.Spinner06); labels=new String[spin.length][]; for(int i=0;i<labels.length;i++){ labels[i] = getResources().getStringArray(R.array.yes_no); } labels[5] = getResources().getStringArray(R.array.no_0_yes); ArrayAdapter<String> adapter; for(int i=0;i<spin.length;i++){ adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, labels[i]); spin[i].setAdapter(adapter); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } } //ボタンクリックによって呼び出される処理 //classの呼び出し(EMCHH.java)で行った内容と同様 private void button_Write_child_9_12_2_back_onClick() { Intent intent_read_1 = new Intent(getApplicationContext(),Write_0_21.class); startActivity(intent_read_1); } private void button_Write_child_9_12_2_home_onClick() { Intent intent_read_2 = new Intent(getApplicationContext(),IndexWrite_pregnant.class); startActivity(intent_read_2); } private void button_Write_child_9_12_2_next_onClick() { Intent intent_read_3 = new Intent(getApplicationContext(),Write_pregnant_51.class); startActivity(intent_read_3); } //onCreateOptionsMenuメソッド(オプションメニュー生成) @Override public boolean onCreateOptionsMenu(Menu menu){ super.onCreateOptionsMenu(menu); //メニューアイテムの追加 MenuItem item1=menu.add(0,0,0,"編集"); item1.setIcon(android.R.drawable.ic_menu_edit); MenuItem item2=menu.add(0,1,0,"タイトル"); item2.setIcon(R.drawable.ic_menu_home); return true; } //onOPtionsItemSelectedメソッド(メニューアイテム選択処理) @Override public boolean onOptionsItemSelected(MenuItem item){ switch (item.getItemId()){ case 0: Intent intent1 = new Intent(); intent1.setClass(Write_child_9_2_2.this, Write3.class); startActivity(intent1); return true; case 1: Intent intent2 = new Intent(); intent2.setClass(Write_child_9_2_2.this, MainActivity.class); startActivity(intent2); return true; } return true; } }
Java
UTF-8
813
2.40625
2
[]
no_license
package com.lakeqiu.store.domain; /** * 分页信息类 * @author lakeqiu */ public class Category { /** * 分类编号 */ private String cid; /** * 分类名字 */ private String cname; public String getCid() { return cid; } public void setCid(String cid) { this.cid = cid; } public String getCname() { return cname; } public void setCname(String cname) { this.cname = cname; } public Category() { } public Category(String cid, String cname) { this.cid = cid; this.cname = cname; } @Override public String toString() { return "Category{" + "cid='" + cid + '\'' + ", cname='" + cname + '\'' + '}'; } }
Python
UTF-8
2,003
2.921875
3
[]
no_license
import pandas as pd import AppConfig import plotly.express as px import numpy as np import seaborn as sns import matplotlib import matplotlib.pyplot as plt import boto3 import argparse import happiness import temperature class Analysis: def __init__(self): self.temp_df = temperature.Temperature().df self.happy_df = happiness.Happiness().df self.temp_happy_df = self._clean_data() def _clean_data(self): """ normalizes country names so that their names are in the exact same format so merge works Merges the two data frames into a single dataframe :returns cleaned and normalized dataset: """ temp_happy_df = (self.happy_df.merge(self.temp_df, on=['country', 'year'], how='inner')) # normalize temp_happy_df['happiness'] = temp_happy_df['happiness'] / max(temp_happy_df['happiness']) # temp_happy_df.to_csv("testing3.csv") temp_happy_df.reset_index().to_csv("data_files/temperature_happy_cleaned.csv") return temp_happy_df def mean_max_temp(self): """ Plots mean max temp against average happiness for each country per year using bubble heat map heat color goes off of temperature bubble size goes off happiness """ fig = px.scatter_geo(self.temp_happy_df, locations="country", locationmode='country names', color="max_temp", hover_name='country', size="happiness", size_max=30, animation_frame='year', projection="natural earth") fig.show() def scatter(self): """ Comments go here """ x_1 = self.temp_happy_df["max_temp"] y_2 = self.temp_happy_df["happiness"] m, b = np.polyfit(x_1, y_2, 1) plt.scatter(x_1, y_2, marker='o') plt.plot(x_1, m * x_1 + b, color='red') plt.savefig("maxtemp.png") plt.show() def main(): pass if __name__ == "__main__": main()
Python
UTF-8
1,715
2.765625
3
[]
no_license
import telebot import digest import pickle bot = telebot.TeleBot('<Your API key') @bot.message_handler(commands=['view']) def view_post_message(message): view = digest.view_posts() bot.send_message(message.chat.id, "*Постов по вашим хабам: {}".format(len(view)) + '*\n' + "\n".join(view), parse_mode="Markdown") digest.clear_posts() @bot.message_handler(commands=['hubs']) def view_hubs(message): hubs = digest.view_hubs() if hubs == "Error!" or hubs.__len__() == 0: bot.send_message(message.chat.id, "У вас пока нет отслеживаемых хабов. Самое время их добавить!") else: bot.send_message(message.chat.id, "Ваши хабы: " + '\n' + "\n".join(hubs)) @bot.message_handler(commands=['add_hub']) def adding(message): m = message.text hub = str(m[9:]) digest.add_hubs(hub) bot.send_message(message.chat.id, 'Хаб {} добавлен в отслеживаемые!'.format("*"+hub+"*"), parse_mode="Markdown") @bot.message_handler(commands=['delete_hub']) def deleting(message): m = message.text hub = str(m[12:]) hubs = digest.delete_hub(hub) if hubs == "Error!": bot.send_message(message.chat.id, "Такого хаба нет в отслеживаемых") else: bot.send_message(message.chat.id, 'Хаб {} удален из отслеживаемых!'.format("*"+hub+"*"), parse_mode="Markdown") @bot.message_handler(commands=['start']) def start_message(message): bot.send_message(message.chat.id, 'Привет, это ДайджестБот! Посмотрим, что есть номого?') bot.polling()
Shell
UTF-8
2,466
3.359375
3
[]
no_license
#!/bin/bash # Devops Project -- 2016 kansukse@gmail.com # BuildBot Master süreçlerini ayarlar çalışır hale getirir. Debian Jessie üstünde çalışır. # Fix for python3 2020 buildbotdir=/BUILDBOT mastername=master builddir=$buildbotdir/sandbox gitdir=$buildbotdir/git tmpdir=$buildbotdir/tmp base="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd)" pypath="\"\${PYTHONPATH}:$base/bot\"" sudo apt-get update sudo apt-get dist-upgrade -fy sudo apt-get install -fy python3-dev python3-pip git sudo libffi-dev libssl-dev postgresql-client # Projecet PYTHONPATH ifpypath=$(cat ~/.bashrc |grep $pypath|wc -l) if [ "$ifpypath" == "0" ];then echo "PYTHONPATH Eklenmemiş. Ekleniyor." echo -e "# Buildbot PYTHONPATH export PYTHONPATH=$pypath " >> ~/.bashrc source ~/.bashrc fi # System Globals ifglobals=$(cat ~/.bashrc |grep "# Buildbot Master Globals:"|wc -l) if [ "$ifglobals" == "0" ];then echo "Globaller export edilmemiş. Şimdi export ediliyor." echo -e "# Buildbot Master Globals: export BUILDBOTDIR=$buildbotdir export GITDIR=$gitdir export MASTERNAME=$mastername export BUILDDIR=$builddir export BASE=$base export PGPASSWORD=postgresql_password " >> ~/.bashrc source ~/.bashrc fi mkdir -p $gitdir $tmpdir ln -sf $base/checker.sh $tmpdir/checker.sh sudo cp -f $base/checker-cron /etc/cron.d/checker-cron sudo cp -f $base/master-cron /etc/cron.d/master-cron # tüm repoları burda çek. if [ ! -d $builddir ];then sudo pip3 install virtualenv virtualenv -p python3 $builddir else echo "[info]virtualenv already installed and configured.." fi source $builddir/bin/activate if [ -f $builddir/$mastername/state.sqlite ];then buildbot upgrade-master $builddir/$mastername fi if [ ! -f $builddir/$mastername/buildbot.tac ];then pip3 install buildbot buildbot-www buildbot-worker buildbot-waterfall-view buildbot-console-view buildbot-grid_view pyopenssl service_identity buildbot create-master $builddir/$mastername ln -s $base/bot/lib $builddir/$mastername/lib ln -s $base/bot/master.cfg $builddir/$mastername/master.cfg sudo service cron restart else echo "[info]sqlalchey and buildbot-master already installed and configured.." fi if [ ! -f $builddir/$mastername/twistd.pid ];then buildbot start $builddir/$mastername echo "[warning]builbot-master is not running.. Try starting.." else buildbot reconfig $builddir/$mastername echo "[info]buildbot-master reconfig.. " fi bash bot/scripts/bashsource.sh source ~/bashsource
Markdown
UTF-8
15,062
2.578125
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: Ingestování telemetrie z IoT Hubu titleSuffix: Azure Digital Twins description: Podívejte se, jak ingestovat zprávy telemetrie zařízení z IoT Hub. author: cschormann ms.author: cschorm ms.date: 3/17/2020 ms.topic: how-to ms.service: digital-twins ms.openlocfilehash: 7c73f007f85a963a09de4e05222082fd52f784c0 ms.sourcegitcommit: 0e8a4671aa3f5a9a54231fea48bcfb432a1e528c ms.translationtype: MT ms.contentlocale: cs-CZ ms.lasthandoff: 07/24/2020 ms.locfileid: "87131561" --- # <a name="ingest-iot-hub-telemetry-into-azure-digital-twins"></a>Ingestování IoT Hub telemetrie do digitálních vláken Azure Digitální vlákna Azure se řídí daty ze zařízení IoT a dalších zdrojů. Běžný zdroj dat zařízení, která se mají používat v rámci digitálních vláken Azure, je [IoT Hub](../iot-hub/about-iot-hub.md). Během období Preview je proces pro ingestování dat do digitálních vláken Azure nastavený na externí výpočetní prostředek, jako je třeba [funkce Azure](../azure-functions/functions-overview.md), která přijímá data a používá [rozhraní API DigitalTwins](how-to-use-apis-sdks.md) k nastavení vlastností nebo událostí telemetrie na [digitální vlákna](concepts-twins-graph.md) . Tento postup popisuje, jak dokumentovat pomocí procesu vytváření funkce Azure, která může ingestovat telemetrii od IoT Hub. ## <a name="example-telemetry-scenario"></a>Ukázkový scénář telemetrie Tento postup popisuje, jak odesílat zprávy z IoT Hub do digitálních vláken Azure pomocí funkce Azure Functions. Existuje mnoho možných konfigurací a vyhovujících strategií, které můžete použít, ale příklad tohoto článku obsahuje následující části: * Zařízení teploměr v IoT Hub se známým ID zařízení. * Digitální vlákna představující zařízení s ID odpovídajícího * Digitální dvojitá reprezentace místnosti > [!NOTE] > V tomto příkladu se používá jednoznačné ID mezi ID zařízení a odpovídajícím ID digitálního vlákna, ale je možné poskytnout propracovanější mapování ze zařízení na jeho dvojitou hodnotu (například s tabulkou mapování). Pokaždé, když zařízení teploměru posílá událost telemetrie teploty, musí se aktualizovat vlastnost *teploty* vlákna v *místnosti* . Pokud to chcete udělat, namapujete z události telemetrie na zařízení na vlastnost setter u digitálního vlákna. Pomocí informací o topologii v [grafu s dvojitou](concepts-twins-graph.md) polohou vyhledáte dvojitou *místnost* a pak můžete nastavit vlastnost vlákna. V jiných scénářích může uživatel chtít nastavit vlastnost na párovém vlákna (v tomto příkladu je to dvojitě s ID *123*). Digitální vlákna Azure vám dává značnou flexibilitu při rozhodování o tom, jak se data telemetrie mapují na vlákna. Tento scénář je popsaný v diagramu níže: :::image type="content" source="media/how-to-ingest-iot-hub-data/events.png" alt-text="Zařízení IoT Hub odesílá do funkce Azure funkci telemetrii teploty prostřednictvím IoT Hub, Event Grid nebo systémových témat, což aktualizuje vlastnost teploty u vláken v digitálních událostech Azure." border="false"::: ## <a name="prerequisites"></a>Předpoklady Než budete pokračovat v tomto příkladu, musíte splnit následující požadavky. 1. Vytvořte centrum IoT. Pokyny najdete v části *vytvoření IoT Hub* v [tomto IoT Hub rychlém](../iot-hub/quickstart-send-telemetry-cli.md) startu. 2. Vytvořte alespoň jednu funkci Azure pro zpracování událostí z IoT Hub. Přečtěte si téma [*Postupy: nastavení funkce Azure pro zpracování dat*](how-to-create-azure-function.md) a vytvoření základní funkce Azure, která se může připojit k digitálním podprocesům Azure a volat funkce rozhraní API digitálních vláken Azure. Zbytek tohoto postupu bude sestaven na této funkci. 3. Nastavte cíl události pro data centra. V [Azure Portal](https://portal.azure.com/)přejděte k instanci IoT Hub. V části *události*Vytvořte předplatné pro funkci Azure Functions. :::image type="content" source="media/how-to-ingest-iot-hub-data/add-event-subscription.png" alt-text="Azure Portal: přidání odběru události"::: 4. Na stránce *vytvořit odběr události* vyplňte pole následujícím způsobem: * V části *Podrobnosti odběru události*pojmenujte předplatné tak, co byste chtěli. * V části *typy událostí*vyberte *telemetrie zařízení* jako typ události, která se má filtrovat. - Přidejte filtry k ostatním typům událostí, pokud chcete. * V části *Podrobnosti o koncovém bodu*vyberte Azure Function jako koncový bod. ## <a name="create-an-azure-function-in-visual-studio"></a>Vytvoření funkce Azure v aplikaci Visual Studio V této části se používají stejné kroky při spuštění sady Visual Studio a Osnova funkcí Azure Functions v tématu [*Postupy: nastavení funkce Azure pro zpracování dat*](how-to-create-azure-function.md). Kostra zpracovává ověřování a vytváří klienta služby, který je připravený na zpracování dat a volání rozhraní API digitálních vláken Azure v reakci. Jádrem funkce kostra je: ```csharp namespace FunctionSample { public static class FooFunction { const string adtAppId = "https://digitaltwins.azure.net"; private static string adtInstanceUrl = Environment.GetEnvironmentVariable("ADT_SERVICE_URL"); private static HttpClient httpClient = new HttpClient(); [FunctionName("Foo")] public static async Task Run([EventGridTrigger]EventGridEvent eventGridEvent, ILogger log) { DigitalTwinsClient client = null; try { ManagedIdentityCredential cred = new ManagedIdentityCredential(adtAppId); DigitalTwinsClientOptions opts = new DigitalTwinsClientOptions { Transport = new HttpClientTransport(httpClient) }); client = new DigitalTwinsClient(new Uri(adtInstanceUrl), cred, opts); log.LogInformation($"ADT service client connection created."); } catch (Exception e) { log.LogError($"ADT service client connection failed. " + e.ToString()); return; } log.LogInformation(eventGridEvent.Data.ToString()); } } } ``` V následujících krocích přidáte konkrétní kód pro zpracování událostí telemetrie IoT z IoT Hub. ## <a name="add-telemetry-processing"></a>Přidat zpracování telemetrie Události telemetrie přicházejí do formy zpráv ze zařízení. Prvním krokem při přidávání kódu pro zpracování telemetrie je extrakce příslušné části této zprávy zařízení z události Event Grid. Různá zařízení mohou strukturovat své zprávy různě, takže kód pro tento krok závisí na připojeném zařízení. Následující kód ukazuje příklad jednoduchého zařízení, které odesílá telemetrii jako JSON. Ukázka extrahuje ID zařízení, které zprávu odeslalo, a také hodnotu teploty. ```csharp JObject job = eventGridEvent.Data as JObject; string devid = (string)job["systemProperties"].ToObject<JObject>().Property("IoT-hub-connection-device-ID").Value; double temp = (double)job["body"].ToObject<JObject>().Property("temperature").Value; ``` Pokud je účelem tohoto cvičení, je potřeba aktualizovat teplotu *místnosti* v grafu s dvojitou přesností. To znamená, že náš cíl zprávy není digitální, který je spojený s tímto zařízením, ale *místnost* vlákna, která je jeho nadřazenou. Nadřazené vlákna můžete najít pomocí hodnoty ID zařízení, kterou jste extrahovali ze zprávy telemetrie pomocí výše uvedeného kódu. Pokud to chcete provést, použijte rozhraní API pro digitální vlákna Azure pro přístup k příchozím relacím na zařízení, které představuje zdvojené (v tomto případě má stejné ID jako zařízení). Z příchozího vztahu můžete najít ID nadřazeného prvku s následujícím fragmentem kódu. Následující fragment kódu ukazuje, jak načíst příchozí relace vlákna: ```csharp AsyncPageable<IncomingRelationship> res = client.GetIncomingRelationshipsAsync(twin_id); await foreach (IncomingRelationship irel in res) { Log.Ok($"Relationship: {irel.RelationshipName} from {irel.SourceId} | {irel.RelationshipId}"); } ``` Nadřazená položka vlákna je ve vlastnosti *SourceId* vztahu. Je poměrně běžné pro model vláken, který představuje zařízení, aby měl jenom jeden příchozí vztah. V takovém případě můžete vybrat první (a pouze) vrácenou relaci. Pokud vaše modely umožňují více typů vztahů k tomuto typu vlákna, možná budete muset zadat další pro výběr z více příchozích vztahů. Běžným způsobem, jak to provést, je vybrat relaci podle `RelationshipName` . Jakmile budete mít ID nadřazeného vlákna představujícího *místnost*, můžete "opravit" (provést aktualizace), které jsou vytvářené. K tomu použijte následující kód: ```csharp UpdateOperationsUtility uou = new UpdateOperationsUtility(); uou.AppendAddOp("/Temperature", temp); try { await client.UpdateDigitalTwinAsync(twin_id, uou.Serialize()); Log.Ok($"Twin '{twin_id}' updated successfully!"); } ... ``` ### <a name="full-azure-function-code"></a>Úplný kód funkce Azure Pomocí kódu z předchozích ukázek je zde celá funkce Azure v kontextu: ```csharp [FunctionName("ProcessHubToDTEvents")] public async void Run([EventGridTrigger]EventGridEvent eventGridEvent, ILogger log) { // After this is deployed, in order for this function to be authorized on Azure Digital Twins APIs, // you'll need to turn the Managed Identity Status to "On", // grab the Object ID of the function, and assign the "Azure Digital Twins Owner (Preview)" role to this function identity. DigitalTwinsClient client = null; //log.LogInformation(eventGridEvent.Data.ToString()); // Authenticate on Azure Digital Twins APIs try { ManagedIdentityCredential cred = new ManagedIdentityCredential(adtAppId); client = new DigitalTwinsClient(new Uri(adtInstanceUrl), cred, new DigitalTwinsClientOptions { Transport = new HttpClientTransport(httpClient) }); log.LogInformation($"ADT service client connection created."); } catch (Exception e) { log.LogError($"ADT service client connection failed. " + e.ToString()); return; } if (client != null) { try { if (eventGridEvent != null && eventGridEvent.Data != null) { #region Open this region for message format information // Telemetry message format //{ // "properties": { }, // "systemProperties": // { // "iothub-connection-device-id": "thermostat1", // "iothub-connection-auth-method": "{\"scope\":\"device\",\"type\":\"sas\",\"issuer\":\"iothub\",\"acceptingIpFilterRule\":null}", // "iothub-connection-auth-generation-id": "637199981642612179", // "iothub-enqueuedtime": "2020-03-18T18:35:08.269Z", // "iothub-message-source": "Telemetry" // }, // "body": "eyJUZW1wZXJhdHVyZSI6NzAuOTI3MjM0MDg3MTA1NDg5fQ==" //} #endregion // Reading deviceId from message headers log.LogInformation(eventGridEvent.Data.ToString()); JObject job = (JObject)JsonConvert.DeserializeObject(eventGridEvent.Data.ToString()); string deviceId = (string)job["systemProperties"]["iothub-connection-device-id"]; log.LogInformation($"Found device: {deviceId}"); // Extracting temperature from device telemetry byte[] body = System.Convert.FromBase64String(job["body"].ToString()); var value = System.Text.ASCIIEncoding.ASCII.GetString(body); var bodyProperty = (JObject)JsonConvert.DeserializeObject(value); var temperature = bodyProperty["Temperature"]; log.LogInformation($"Device Temperature is:{temperature}"); // Update device Temperature property await AdtUtilities.UpdateTwinProperty(client, deviceId, "/Temperature", temperature, log); // Find parent using incoming relationships string parentId = await AdtUtilities.FindParent(client, deviceId, "contains", log); if (parentId != null) { await AdtUtilities.UpdateTwinProperty(client, parentId, "/Temperature", temperature, log); } } } catch (Exception e) { log.LogError($"Error in ingest function: {e.Message}"); } } } ``` Funkce nástroje pro vyhledání příchozích vztahů: ```csharp public static async Task<string> FindParent(DigitalTwinsClient client, string child, string relname, ILogger log) { // Find parent using incoming relationships try { AsyncPageable<IncomingRelationship> rels = client.GetIncomingRelationshipsAsync(child); await foreach (IncomingRelationship ie in rels) { if (ie.RelationshipName == relname) return (ie.SourceId); } } catch (RequestFailedException exc) { log.LogInformation($"*** Error in retrieving parent:{exc.Status}:{exc.Message}"); } return null; } ``` A funkce Utility pro opravu vlákna: ```csharp public static async Task UpdateTwinProperty(DigitalTwinsClient client, string twinId, string propertyPath, object value, ILogger log) { // If the twin does not exist, this will log an error try { // Update twin property UpdateOperationsUtility uou = new UpdateOperationsUtility(); uou.AppendAddOp(propertyPath, value); await client.UpdateDigitalTwinAsync(twinId, uou.Serialize()); } catch (RequestFailedException exc) { log.LogInformation($"*** Error:{exc.Status}/{exc.Message}"); } } ``` Teď máte funkci Azure, která je vybavená ke čtení a interpretaci dat scénáře přicházejících z IoT Hub. ## <a name="debug-azure-function-apps-locally"></a>Místní ladění aplikací funkcí Azure Functions Službu Azure Functions je možné ladit pomocí Event Grid triggeru místně. Další informace najdete v tématu [*ladění Event Grid triggeru místně*](../azure-functions/functions-debug-event-grid-trigger-local.md). ## <a name="next-steps"></a>Další kroky Přečtěte si o příchozím a odchozím přenosu dat pomocí digitálních vláken Azure: * [*Koncepty: integrace s jinými službami*](concepts-integration.md)
Markdown
UTF-8
1,609
2.765625
3
[]
no_license
--- title: Monsters Weekly 200b - Conversations with Julie Lerman layout: post tags: - ASP.NET Core authorId: monsters date: 2020-12-21 08:00:00 categories: - Monsters Weekly permalink: monsters-weekly\ep200b --- Over the last decade as Monsters we've been so fortunate to connect with so many great people in the industry. In this 5 part series leading up to episode 200 we reconnect with some of the visionaries, teachers, mentors and community members who have inspired us along the way. In part 2 we catch up with Entity Framework advocate and specialist Julie Lerman. Julie's been on the front lines seeing all the updates, staying connected to the EF team and presenting live (when legal!). Long time author, mentor and trainer, Julie's known for jumping in and helping teams discover approaches to solving data problems. In this episode we talk through the state of EF, upgrading from version to version, Cosmos DB, domain driven design, snow and kidnapping. Unfortunately, we were not able to settle who has the best maple syrup. Settle in, have a coffee for Julie and sit back while we chew on all things EF Core (and more!). Referenced in the show: Vladik Khononov https://twitter.com/vladikk?lang=en EF Core https://docs.microsoft.com/en-us/ef/core/ On Github: https://github.com/dotnet/efcore Julie's Pluralsight Courses: https://www.pluralsight.com/authors/julie-lerman <iframe width="1084" height="610" src="https://www.youtube.com/embed/fxTl84zg7zY" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
Python
UTF-8
4,392
2.78125
3
[]
no_license
from pydub import AudioSegment from os.path import splitext from pyaudio import PyAudio import _thread as thread from pydub.utils import make_chunks from enum import Enum class MusicPlayerState(Enum): #No Song Loaded Initialized = 0 #Song Loading Loading = 1 #Song Loading Loaded = 2 #Song Playing Playing = 3 #Song Paused Paused = 4 #Song Ended Ended = 5 class MusicPlayer: def __init__(self, *, soundFile:str=None): self.soundFile = None self.state = MusicPlayerState.Initialized self.audio = PyAudio() self.pydubFile = None #Lets us make sure that the state change has caught up to the audio change self.isPlaying = False #player self.volume = 100 self.time = 0 if(soundFile is not None): loadFile(soundFile) def load(self, soundFile:str=None): if(self.state == MusicPlayerState.Playing or self.state == MusicPlayerState.Loading): print("Can't load a song which hasn't ended or is still loading.") return prevSoundFile = self.soundFile prevState = self.state prevPydbubFile = self.pydubFile prevTime = self.time #Because we are going to use threading, I feel this is the best way to #avvoid a race condition... Of course, a race condition can still #occur. a race to there as apposed to a race to load self.state = MusicPlayerState.Loading #Dont actually know what the latter half of this function does. try: self.soundFile = soundFile self.pydubFile = AudioSegment.from_file(self.soundFile,format=splitext(self.soundFile)[1][1:]) self.state = MusicPlayerState.Loaded self.time = 0 except: self.state = prevState self.pydubFile = prevPydbubFile self.time = prevTime def play(self): thread.start_new_thread(self.playInternal, (self.time, self.duration())) def duration(self): if self.pydubFile is not None: return(self.pydubFile.duration_seconds) return -1 def playInternal(self,start,length): if(self.state == MusicPlayerState.Initialized or self.state == MusicPlayerState.Loading or self.state == MusicPlayerState.Playing): print("Cannot play a song which has not loaded, been initialized, or is already playing") return self.state = MusicPlayerState.Playing millisecondchunk = 50 / 1000.0 stream = self.audio.open(format= self.audio.get_format_from_width(self.pydubFile.sample_width), channels=self.pydubFile.channels, rate=self.pydubFile.frame_rate, output=True) playchunk = self.pydubFile[start * 1000.0:(start + length) * 1000.0] for chunks in make_chunks(playchunk, millisecondchunk * 1000): chunkAltered = chunks - (60 - (60 * (self.volume / 100.0))) self.time += millisecondchunk self.isPlaying = True stream.write(chunkAltered._data) if (self.state != MusicPlayerState.Playing): break if self.time >= start + length: self.state = MusicPlayerState.Ended break self.isPlaying = False stream.close() def restart(self): if(self.state == MusicPlayerState.Playing): self.pause() elif (self.state == MusicPlayerState.Initialized or self.state == MusicPlayerState.Loading): print("Cannot restart without a song, or the song has not finished loading!") return while(self.isPlaying): pass self.time = 0 self.play() def pause(self): if(self.state == MusicPlayerState.Playing): self.state = MusicPlayerState.Paused def stop(self): if(self.state == MusicPlayerState.Loading or self.state == MusicPlayerState.Initialized): print("Cannot stop a song which has not begun!") return self.state = MusicPlayerState.Loaded
Markdown
UTF-8
1,497
3.15625
3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Twilio Voice Transcription Tryout ===== A simple Rails app that lets you try out Twilio's voice transcription capabilities. Note on Cost --- Twilio costs money! Make sure you check the cost of things before using. As of June 2013, the rates are roughly $1/month to reserve a phone number, 1 cent per call per minute, and 5 cents per transcription minute. So using this should only be a few dollars max, BUT I'm not liable for charges! Also note that Twilio saves your recordings (even transcribed ones) and there is a storage fee associated these, so make sure you go in and delete those after you're done. Deploying on Heroku --- - Clone the repo - Create a new Heroku app `heroku create` - Push your repo to Heroku `git push heroku master` - Migrate the database on your Heroku server `heroku run rake db:migrate` - Go onto Twilio, and create a new number (When logged in, click 'Account', then 'Numbers', then the blue 'Buy a Number' button on the top right). - On the 'Manage Numbers' screen, click on the number you just purchased. Then, in the 'Voice Request URL' field, put the URL for your app (for example, http://myappname.herokuapp.com/) and make sure 'POST' is selected in the dropdown on the right. - Now you're ready to roll! Call your phone number, leave a message when prompted, hang up, and load up the app URL in your browser. After a few seconds (depending on length) the transcribed message should appear. License --- BSD License (see LICENSE.md for details)
Java
UTF-8
3,170
3.109375
3
[]
no_license
import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.net.Socket; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Random; /** * This thread connects to one of the server and performs transfer operations * * @author dhass * */ public class TransferClient extends Thread { String host; int port; Socket socket; int iterationCount; List<Integer> accts = new ArrayList<Integer>(); ClientLogger log; public TransferClient(String host, int port) { this.host = host; this.port = port; this.iterationCount = 100; this.setName(host + port); // Initialize acct IDs. for (int i = 1; i <= 10; i++) accts.add(i); log = ClientLogger.getInstance(); try { socket = new Socket(host, port); } catch (IOException e) { e.printStackTrace(); } } public void run() { try { System.out.print("\nNew thread created :" + Thread.currentThread().getId()); OutputStream rawOut = socket.getOutputStream(); InputStream rawIn = socket.getInputStream(); ObjectOutputStream out = new ObjectOutputStream(rawOut); ObjectInputStream in = new ObjectInputStream(rawIn); Random rnd = new Random(); for (int i = 0; i < iterationCount; i++) { // Get random accts and perform transfer. System.out.print("\nThread ID :" + Thread.currentThread().getName() + " Iteration " + i); int rndacctID1 = rnd.nextInt(accts.size()); int rndacctID2 = rnd.nextInt(accts.size()); transfer(accts.get(rndacctID1), accts.get(rndacctID2), 10, out, in); System.out.print("\nTransfer completed between " + accts.get(rndacctID1) + " and " + accts.get(rndacctID2) + "\n"); } out.close(); in.close(); socket.close(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } /** * Transfer function calling the server * * @param acctID1 * @param acctID2 * @param amt * @param out * @param in * @throws IOException * @throws ClassNotFoundException */ public void transfer(int acctID1, int acctID2, int amt, ObjectOutputStream out, ObjectInputStream in) throws IOException, ClassNotFoundException { ClientRequest transfer = new ClientRequest(); transfer.transactionType = "transfer"; transfer.params = new Parameter(acctID1, acctID2, amt); System.out.print("\nclientrequest type" + transfer.transactionType); System.out.print("\nclient params" + transfer.params); Date curPhysicalTime; // TODO: Remove sys out comments at the end // Log the request to the client log file curPhysicalTime = new java.util.Date(); log.write(this.host + ":" + this.port + " REQ " + curPhysicalTime + " " + transfer.transactionType + " " + transfer.params); out.writeObject(transfer); String status = (String) in.readObject(); System.out.print("\nServer Response : " + status); // log the response received by the client curPhysicalTime = new java.util.Date(); log.write(this.host + ":" + this.port + " " + "RSP " + curPhysicalTime + " " + status.toString()); } }
Java
ISO-8859-1
1,291
3.109375
3
[]
no_license
package view; import javax.swing.JOptionPane; import model.Aluno; public class Questao1Teste { public static void main(String[] args) { Aluno aluno1 = new Aluno("Lucas Lins", "53001", "Rua Joo oliveira", "331.123.443-8"); Aluno aluno2 = new Aluno("Thalyson Rocha", "55009", "Rua Projetada", "121.313.933-1"); Aluno aluno3 = new Aluno("Alana Marques", "52157", "Rua Andr Dias", "091.173.662-3"); Object[] listaAlunos = new String[3]; listaAlunos[0] = aluno1.getNome(); listaAlunos[1] = aluno2.getNome(); listaAlunos[2] = aluno3.getNome(); Object escolha = JOptionPane.showInputDialog(null, "Qual aluno deseja visualizar?", "Questo 1", JOptionPane.QUESTION_MESSAGE, null, listaAlunos, listaAlunos[0]); if(escolha == null) { JOptionPane.showMessageDialog(null, "At mais!"); } else if (escolha.equals(aluno1.getNome())){ JOptionPane.showMessageDialog(null, aluno1.infoAlunos(), "Informaes do Aluno", JOptionPane.INFORMATION_MESSAGE); } else if(escolha.equals(aluno2.getNome())){ JOptionPane.showMessageDialog(null, aluno2.infoAlunos(), "Informaes do Aluno", JOptionPane.INFORMATION_MESSAGE); } else if(escolha.equals(aluno3.getNome())){ JOptionPane.showMessageDialog(null, aluno3.infoAlunos(), "Informaes do Aluno", JOptionPane.INFORMATION_MESSAGE); } } }
Java
UTF-8
2,071
2.15625
2
[ "Apache-2.0" ]
permissive
/* * AsymSecureFile * https://ablog.jc-lab.net/186 * * This software may be modified and distributed under the terms * of the Apache License 2.0. See the LICENSE file for details. */ package kr.jclab.javautils.asymsecurefile.internal.jasf4.asn; import kr.jclab.javautils.asymsecurefile.internal.jasf4.ChunkResolver; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1TaggedObject; import org.bouncycastle.asn1.DEROctetString; import java.util.Enumeration; public class Asn1CustomDataChunk extends Asn1AbstractChunk<ASN1OctetString> { private static final ChunkId CHUNK_BEGIN = ChunkId.CustomBegin; public static final Asn1AbstractChunkDataFactory<ASN1OctetString> FACTORY = ASN1OctetString::getInstance; @ChunkInitializer public static void init() { ChunkResolver.addChunkClass(CHUNK_BEGIN, Asn1CustomDataChunk.class, Asn1CustomDataChunk::new); } private static Asn1ChunkFlags convertFlags(Asn1ChunkFlags input) { Asn1ChunkFlags flags = new Asn1ChunkFlags(input.getValue()); flags.encryptWithAuthKey(true); return flags; } public Asn1CustomDataChunk(int index, Asn1ChunkFlags flags, byte[] data) { super(FACTORY, CHUNK_BEGIN.getValue() + index, flags, new DEROctetString(data)); } public Asn1CustomDataChunk(Enumeration e) { super(FACTORY, e); } public byte[] getBytesData() { return this.data.getOctets(); } public static Asn1CustomDataChunk getInstance( ASN1TaggedObject obj, boolean explicit) { return getInstance(ASN1Sequence.getInstance(obj, explicit)); } public static Asn1CustomDataChunk getInstance( Object obj) { if (obj instanceof Asn1CustomDataChunk) { return (Asn1CustomDataChunk)obj; } if (obj != null) { return new Asn1CustomDataChunk(ASN1Sequence.getInstance(obj).getObjects()); } return null; } }
Java
UTF-8
1,038
2.171875
2
[]
no_license
package com.click4care.thinkhealth.core.dto; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for typeOfDetermination. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="typeOfDetermination"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="APPROVED"/> * &lt;enumeration value="PARTIAL_APPROVED"/> * &lt;enumeration value="DENIED"/> * &lt;enumeration value="PENDING"/> * &lt;enumeration value="ERROR"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "typeOfDetermination") @XmlEnum public enum TypeOfDetermination { APPROVED, PARTIAL_APPROVED, DENIED, PENDING, ERROR; public String value() { return name(); } public static TypeOfDetermination fromValue(String v) { return valueOf(v); } }
Java
UTF-8
521
3.28125
3
[]
no_license
/* * 마이너스한도, 인출한다를 수정해야함. */ package kr.co.job.chap6; public class MinusAccount extends Account { int creditLine; public MinusAccount(String name, String accNo, int balance, int creditLine) { super(name,accNo,balance); this.creditLine = creditLine; } // 인출한다를 수정함 => 메소드 오버라이딩 @Override int withdraw(int amount) { if((balance + creditLine) < amount) { return 0; } balance -= amount; return amount; } }
Python
UTF-8
3,840
2.921875
3
[]
no_license
from enum import Enum, auto from typing import Dict, Union import re import typing class BlockStatus(Enum): NOTIN = auto(), BLOCKSTART = auto(), BLOCKEND = auto(), INBLOCK = auto() UNSET = auto() class Line: def __init__(self, text: str, is_first: bool=False): self.__is_first = is_first self.__original_text = text # don't change self.__text = text self.__hierarchy = -1 self.type = None self.block_status = BlockStatus.UNSET # getters @property def text(self) -> str: return self.__text @property def hierarchy(self) -> int: return self.__hierarchy @property def get_is_first(self) -> bool: return self.__is_first # for table and code block in list # These layout is dirty so they are disabled. def strip_for_block_start(self): self.__text = self.__text.strip() def set_header(self, level: int): if level < 1: raise ValueError("`level` must be positive number") self.__text = "#"*level + " " + self.__text def parse_and_set_header(self, max_header_level): if self.type != "header": return pos = 1 while True: pos += 1 if self.__text[pos] != "*": break star_cnt = pos - 1 self.__text = self.__text[pos+1:-1] if star_cnt > max_header_level: self.set_header(2) else: self.set_header(max_header_level - star_cnt + 2) def insert_newline(self): if self.type != "header" and self.type != "title": return self.__text = self.__text + "\n" def insert_table_header(self, column_cnt: int): if self.block_status != BlockStatus.INBLOCK: return header = "\n|" for i in range(column_cnt): header += "----|" self.__text = self.__text + header def __calculate_hierarchy(self): if self.type == "list": self.__text = self.__text[1:] pos = 0 while True: if self.__text[pos] != " " and self.__text[pos] != "\t": break pos += 1 self.__hierarchy = pos def __insert_space(self): if self.__hierarchy < 0: raise ValueError("list hierarchy must be larger than or equal to 0") prefix = "- " if self.type == "list" else "" self.__text = self.__text.lstrip() self.__text = " " * self.__hierarchy + prefix + self.__text def make_list(self): if self.type != "list" and self.type != "numlist": return self.__calculate_hierarchy() self.__insert_space() def determine_type(self, patterns: typing.Dict[str, typing.Dict]): if self.block_status != BlockStatus.NOTIN: return for linetype, pattern in patterns.items(): res = pattern.match(self.__text) if res: self.type = linetype def make_codeblock(self): if self.block_status == BlockStatus.BLOCKSTART: codename = self.__text[5:] self.__text = "```" + codename elif self.block_status == BlockStatus.INBLOCK: # eliminate 1st space self.__text = self.__text[1:] elif self.block_status == BlockStatus.BLOCKEND: self.__text = "```\n" + self.__text def make_table(self): if self.block_status == BlockStatus.BLOCKSTART: self.__text = "" elif self.block_status == BlockStatus.INBLOCK: self.__text = self.__text.replace(" ", "") self.__text = self.__text.replace("\t", "|") self.__text = f"|{self.__text}|" elif self.block_status == BlockStatus.BLOCKEND: self.__text = ""