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
Markdown
UTF-8
23,487
3.03125
3
[]
no_license
# Manuel utilisateur FEAT++ - Professeurs Ce manuel est destiné à être utilisé par les professeurs qui souhaiteraient utiliser le framework FEAT++. Il explique comment installer le framework sur une machine, comment utiliser les différentes commandes que FEAT++ propose et comment configurer les fichiers nécessaires au bon fonctionnement du framework. #### Table des matières I. [Installation du framework](#installation) II. [Commandes](#commandes) A. [Créer un nouveau projet vierge](#startup) B. [Configurer un projet](#setup) C. [Vérifier ses propres scripts de tests](#runtests) D. [Récupérer le travail sur demande d'un élève](#mill) E. [Lancer un cycle de tests](#cycle_teacher) F. [Obtenir un aperçu de l'avancée globale des étudiants](#progress) III. [Documents utiles](#documents) A. [Fichier de configuration : config.py](#config) B. [Fichiers relatifs aux scripts de tests](#script) C. [Fichier de modalités : modalites.txt](#modalites) D. [Fichier d'avancée globale : avancee_globale_[DATE].txt](#avancee) E. [Fichiers de retour : synthese.txt et details.txt](#retour) ## I. Installation du framework <a id='installation'></a> ### Prérequis Les seuls prérequis sont au niveau de Python. Pour le bon fonctionnement des programmes, il faut avoir une version de Python 3 ou supérieure, avec la majorité des modules classiques (os, sys, etc.) importés via Anaconda, par exemple. On précise toutefois ici que seule une machine Linux pourra accéder à la fonctionnalité "isolate" qui permet d'exécuter des codes inconnus en toute sécurité. Le reste de l'application fonctionne sur tous les systèmes d'exploitation. ### Comment installer FEAT++ ? * Pour télécharger le code source, et donc l'application, il suffit de rentrer la commande suivante, en vous plaçant dans un répertoire vierge qui deviendra FEAT++. ```bash git init git pull https://github.com/geoffreyakb/featpp.git ``` ## II. Commandes <a id='commandes'></a> Il vous faudra configurer l'environnement de FEAT++. L'application a besoin de connaître plusieurs chemins : - Celui d'un dossier où tous vos projets seront créés, stockés puis depuis lequel ils seront envoyés - Ceux des copies locales des dépôts SVN pour chaque liste d'élèves Pour cela, vous avez deux options. Premièrement, vous pouvez configurer le fichier "variables.json" situé au chemin "./featpp/src/main/variables.json", de la manière suivante : ```json { "repository_path": { "1A_prepa" : "/home/cours/svn_eleves/1A_prepa", "2A_prepa" : "home/cours/svn_eleves/2A_INP" }, "projects_path" : "home/cours/projets/" } ``` Attention : - il ne faut pas modifier les noms "repository_path" et "projects_path", cela engendrerait des erreurs - lorsque vous appellerez les commandes FEAT++, elles prendront en argument les keys des paths correspondants, pas le nom du repository. Par exemple : ```bash featpp send tp1 2A_prepa ``` et non : ```bash featpp send tp1 2A_INP ``` Il est donc conseillé de synchroniser les deux. #### A. Créer l'environnement de travail <a id='setup'></a> Ensuite, il ne reste plus qu'à l'enseignant d'appeler la commande suivante : ```bash featpp setup ``` Deuxièmement, vous pouvez insérer le path vers votre propre fichier .json, à condition qu'il est rigoureusement la même syntaxe que le template ci-dessus. ```bash featpp setup <json_file> ``` * json_file : Il s'agit du path vers votre fichier json. Dans les deux cas, cette commande créera les dossiers dont vous avez renseigné les path si ce n'est pas déjà fait, et le logiciel enregistrera les chemins en mémoire. Si les dépôts SVN n'existaient pas, FEAT++ créera un fichier au format `.csv` qui contiendra la liste des élèves de la promo. Il vous suffit de le remplir au format suivant : ```txt Students student1 student2 student3 ``` #### B. Créer un nouveau projet vierge <a id='startup'></a> Afin de créer un nouveau projet, l'enseignant peut utiliser la commande suivante : ```bash featpp start <nom_projet> ``` Argument : * nom_projet : Il s'agit du nom du dossier qui sera créé et qui contiendra l'arborescence par défaut d'un nouveau projet sous FEAT++. Cette commande va générer une arborescence par défaut d'un projet sous FEAT++ : ```txt Projet ├── config.py ├── public │   ├── retours │   └── sources │   └── HelloWorld.java ├── scriptsTests └── testsProject ``` Cette arborescence contient les éléments suivants : * __config.py__ est le fichier de configuration du projet. C'est dans ce dernier qu'il est possible de définir des scénarios de tests qui pourront être joués sur le code d'un étudiant. Ces scénarios sont écrits en langage python et des informations plus détaillées sur la configuration de ce fichier peuvent être trouvés en section [Documents utiles](#config). * __public__ est un dossier contenant tous les fichiers que l'élève devrait pouvoir récupérer sur son dépôt. Il contient : * __sources__ qui est un dossier qui devrait contenir les sources fournies par l'enseignant pour le projet. * __retours__ qui est un dossier qui contiendra les retours fournis par le framework sur le code de l'élève vis-à-vis du fichier de configuration. * __scriptsTests__ est un dossier contenant des fichiers rédigés par l'enseignant qui serviront d'entrée pour les outils de tests (Ex : classes de tests JUnit, paramètres checkstyle, ...) * __testsProject__ est un dossier qui contiendra des tests que l'enseignant pourra réaliser sur le code qu'il fournit pour faire des vérifications. Vous trouverez plus d'informations sur ce point dans la section [Vérifier ses propres scripts de tests](#runtests). ### C. Vérifier ses propres scripts de tests <a id='runtests'></a> Pour configurer les tests d'un projet, il faut modifier le fichier `testsProject/tests_runner.py`, et optionnellement ajouter des scénarios de test dans le fichier `config.py`. Vous trouverez plus d'informations sur la manière de configurer tous ces documents dans la section [Documents utiles](#documents). Une fois que la configuration a été effectuée, il est possible de la mettre en pratique en utilisant la commande suivante : ```bash featpp runtests <nom_projet> ``` Argument : * nom_projet : Il s'agit du nom du projet dans lequel se trouve le fichier de configuration `config.py` relatif au projet pour lequel le professeur souhaite exercer ses tests. ### D. Envoyer un projet <a id='send'></a> Pour configurer un projet, il faut modifier le fichier `config.py`, éventuellement fournir des fichiers utiles pour les tests, éventuellement fournir des fichiers pour tester les sources qu'il fournit. Vous trouverez plus d'informations sur la manière de configurer tous ces documents dans la section [Documents utiles](#documents). Une fois que la configuration a été effectuée, il est possible de la mettre en pratique en utilisant la commande suivante : ```bash featpp send <nom_projet> <promo_1> <promo_2> <promo_3> ... ``` Arguments : * dossier_projet : Il s'agit du nom du projet dans lequel se trouvent le fichier de configuration `config.py` et la base de donnée `database_test.db` relatifs au projet pour lequel le professeur souhaite obtenir l'avancée globale des étudiants. * promo_i : Le nom des promos auxquelles vous voulez envoyer ce projet. Vous pouvez en renseigner une infinité. Cette commande va générer deux nouveaux fichiers : * __modalites.txt__ : Il s'agit du fichier qui va permettre à l'étudiant de définir les scénarios de tests qu'il veut jouer. Plus d'informations disponibles [ici](#modalites). Ce fichier est généré dans le dossier __public__. * __database_test.db__ : Il s'agit de la base de données propre au projet et au fichier de configuration fourni. C'est une base créée avec `sqlite3` qui contient une table par scénario de tests et des informations importantes comme le nombre de tentatives effectuées, le nombre de tentatives restantes, la dernière date d'exécution du scénario, le score et les pénalités obtenus pour un étudiant. <!-- ### D. Récupérer le travail sur demande d'un élève <a id='mill'></a> Une fois que tout a été configuré, l'utilisateur n'a plus qu'à lancer la commande suivante pour activer la détection automatique des demandes d'évaluation : ```bash featpp mill <racine_depot> <dossier_projets> ``` Arguments : * racine_depot : Le chemin vers le dossier contenant les dépôts Subversion de tout les élèves. * dossiers_projets : Le chemin vers le racine contenant tout les TPs et projets créés par l'enseignant. Dans les faits, cette commande va régulièrement effectuer les commandes **svn update** et **svn info** afin de mettre à jour les dépôts, puis de vérifier si le fichier de modalités a été modifié depuis le dernier cycle de tests, auquel cas un cycle de tests est lancé. Le délai d'attente entre deux vérifications des sources des élèves est de 5 secondes par défaut. Celui-ci peut être changé depuis la variable **WAIT_TIME** dans le fichier `main_mill.py`. En théorie, mill n'a pas besoin d'être relancé après la création de chaque nouveau TP ou projet car il effectue une vérification à partir des dossiers présents dans le dépôt de chaque élève. Toutefois, cette fonctionnalité n'a pas été complètement testée et il est recommandé à l'utilisateur de stopper puis relancer le mill quand un nouveau travail est ajouté. --> ### E. Lancer un cycle de tests <a id='evaluate'></a> Il est possible pour le professeur de lancer un cycle de test pour un élève sans tenir compte de ses contraintes afin de vérifier ce que l'élève a produit à la main. Pour cela il faut utiliser la commande suivante : ```bash featpp evaluate <nom_projet> <promo> <etudiant> <scenario1> <scenario2> ... ``` Arguments : * nom_projet : Il s'agit du nom du dossier dans lequel se trouve le fichier de configuration `config.py` concernant le projet que le professeur souhaite tester chez l'élève. * promo : Le nom de la promo auquel appartient l'étudiant * etudiant : le nom du dépôt SVN de l'étudiant (en général son login) * une liste de noms de scenario que le professeur souhaite voir testé chez l'élève. ### F. Obtenir un aperçu de l'avancée globale des étudiants <a id='progress'></a> Plutôt que d'observer un à un chaque dossier d'un élève pour voir où ils en sont, il est possible de générer un fichier texte contenant une synthèse de la progression des élèves en utilisant la commande suivante : ```bash featpp progress <nom_projet> <promo_1> <promo_2> <promo_3> ... ``` Arguments : * nom_projet : Il s'agit du nom du dossier dans lequel se trouvent le fichier de configuration `config.py` et la base de donnée `database_test.db` relatifs au projet pour lequel le professeur souhaite obtenir l'avancée globale des étudiants. * promo_i : Les noms des promos pour lesquelles vous voulez obtenir l'avancement. Un fichier nommé `avancee_globale_[DATE].txt` est alors généré pour chaque promo entrée dans le dossier du projet avec __[DATE]__ écrit au format `%Y-%m-%d_%Hh%Mm%Ss`. Pour avoir un aperçu de ce fichier, vous pouvez vous rendre [ici](#avancee). ## III. Documents utiles <a id='documents'></a> ### A. Fichier de configuration : config.py <a id='config'></a> Le fichier de configuration d'un projet est la principale interface entre FEAT++ et le professeur. Il s'agit d'un fichier python config.py dont un exemple est donné lors de l'initialisation du projet. Il commence par les importations nécessaires à son bon fonctionnement. A noter que _from tools import *_ permet d'importer tous les outils disponibles grâce à FEAT++. ``` from Scenario import Scenario from tools import * from Text import Text ``` Puis il faut instancier les outils qui vont servir pour le projet, par exemple : ``` javaCompiler = JavaCompiler() blackBox = Blackbox() ``` Puis le professeur doit définir des scénarios de test. Pour cela il doit créer une fonction python par scénario. Cette fonction permet de définir concrètement quel test exécute le scénario et dans quel ordre. Le professeur est libre d'utiliser la syntaxe python pour y mettre des conditionnels par exemple. En voici un exemple : ``` def scenario_example(project_env): results = [ run = javaCompiler.run(project_env, ["HelloWorld.java"]) if run.result == "ERROR" : result.append(Penalty("Pénalité : 1 point perdu", 1)) else results.append(blackBox.run(project_env, "helloWorld")) return results ``` Le professeur peut ajouter des pénalités selon les résultats des différents tests comme on peut le voir dans l'exemple précédent. Afin d'être le plus flexible possible, le professeur peut se renseigner sur les différents attributs des différents objets dans le `README_DEV.md` Après avoir défini l'ensemble de ces fonctions, le professeur doit créer les scénarios à proprement parler et les ajouter dans une liste à la fin du fichier de configuration. Pour créer un scénario, il y a plusieurs paramètres : * **_run**, une fonction (celle définie préalablement) qui correspond à ce que fait concrètement le scénario. * **_nb_attempts**, un entier correspondant au nombre de fois maximum qu'un élève peut demander à exécuter ce scénario. Par défaut fixé à l'infini. * **_delay**, un entier correspondant au nombre de secondes définissant la limite de fréquence de demande d'exécution de ce scénario. Par défaut fixé à une variable globale DELAY = 5. * **_visible**, un booléen indiquant si le scénario sera ou non visible pour l'étudiant. Cela peut être utile pour des tests particuliers, d'évaluation par exemple. Par défaut fixé à vrai. * **_mark**, un entier indiquant combien de points au total représente le scénario, utile si le professeur décide d'utiliser des pénalités. Par défaut fixé à 0. Ainsi, à la fin du fichier de configuration, on trouve deux listes : La première correspond aux scenarios qui vont réellement faire partie du projet : ``` SCENARIOS = [ Scenario(scenario1), Scenario(scenario2), Scenario(scenario_example, _visible = false, _mark = 5) ] ``` La seconde correspond aux scenarios utilisés par le professeur pour tester ses propres fichiers en interne avec la commande **runtests** : ``` SCENARIOS_TESTS = SCENARIOS + [ Scenario(scenario_test), Scenario(bad_scenario_test), ] ``` #### Note concernant la sécurité de la machine lors de l'exécution du code d'un étudiant Cette section n'a d'intérêt que lorsque le besoin de redéfinir ponctuellement la fonction `run()` d'un outil se présente (ce qui devrait ne se produire que peu). Hors de ce cas de figure, cette section peut être ignorée. Cette section relève plus du développement que de l'utilisation, mais présente des problèmes pouvant être rencontrés par les enseignants. Afin d'assurer la sécurité des machines des enseignants, tout code auquel on ne peut pas faire confiance (notamment celui des étudiants) doit être exécuté dans un environnement isolé. Ainsi, si la fonction `run()` d'un outil exécutant un code auquel on ne fait pas confiance est redéfinie, les appels d'exécution de ce code doivent se faire avec la fonction `isolate_run(id, options, prog)` définie dans le fichier `isolate.py`, `id` étant accessible depuis l'attribut `ProjectEnv.isolate_id`, `options` permettant de contrôler les restrictions appliquées sur le code exécuté (cf. http://www.ucw.cz/moe/isolate.1.html), et `prog` contenant un appel en ligne de commande de syntaxe similaire à celui de `SubProcess.run()`. À noter cependant que toutes les sources et les fichiers avec lesquels le code doit interagir au cours de son exécution doivent avoir été déplacés dans le dossier correspondant à l'environnement isolé avant l'exécution. L'intégralité du dossier source de l'étudiant est déplacée au début du cycle de tests, cependant tout fichier nécessaire et extérieur au dossier source de l'étudiant doit être déplacé à l'aide de la fonction `isolate_mv(isolated_dir, files)`, `isolated_dir` étant accessible depuis l'attribut `ProjectEnv.path_to_isolate_env`, et `files` étant une liste de chemins (absolus ou relatifs à l'environnement d'exécution de FEAT++) vers les fichiers/dossiers à déplacer. À noter également que les appels de commandes externes à l'environnement isolé (par exemple `sh` ou `java`) par la fonction `isolate_run(id, options, prog)` doivent être fait avec le chemin absolu de l'exécutable (par exemple : `/usr/bin/sh` ou `/usr/bin/java`), et que les chemins vers des fichiers dans l'environnement isolé dans la commande passée dans le paramètre `prog` doivent être relatifs à la racine de l'environnement isolé (par exemple : "src/TP_java/HelloWorld.java"). Un problème peut survenir dans le cas où le chemin absolu donné pour un exécutable est en réalité un lien symbolique. Le problème peut être contourné en utilisant la commande `realpath` ou `readlink` (par exemple : `$(/usr/bin/realpath /usr/bin/java)`), ou en remplaçant le chemin par le contenu d'une variable d'environnement dans laquelle le chemin réel a été enregistré au préalable (par exemple : `PATHTOJAVA=$(realpath $(which java))`). ### B. Fichiers relatifs aux scripts de tests <a id='script'></a> #### B.1 Les fichiers du dossier ScriptsTests <a id='ScriptsTests'></a> Ce dossier contient tous les fichiers qui vont devoir être appelé par les outils et qui ne seront pas chez l'étudiant. Par exemple pour les tests en boîte noire, on trouvera ici les fichiers qui permettront de comparer le résultat et qui doivent se terminer par `.expected` et les fichiers qui permettent de décrire ce que doit executer le test en boite noire, ceux-ci doivent se terminer par `.run`. En voici deux exemples : __exempleConfiantTricheurSujet.run__ ```bash #!/bin/bash /usr/lib/jvm/java-11-openjdk-amd64/bin/java allumettes.Partie -confiant Ordinateur@rapide Tricheur@tricheur << EOF EOF ``` Pour l'instant, il faut mettre le chemin complet pour appeler des logiciels. __exempleConfiantTricheurSujet.expected__ ``` Nombre d'allumettes restantes : 13 Au tour de Ordinateur. Ordinateur prend 3 allumettes. Nombre d'allumettes restantes : 10 Au tour de Tricheur. Tricheur prend 1 allumette. Nombre d'allumettes restantes : 1 Au tour de Ordinateur. Ordinateur prend 1 allumette. Ordinateur a perdu ! Tricheur a gagné ! ``` #### B.2 Les fichiers du dossier TestsProject <a id='TestsProject'></a> Le but de ce dossier est de permettre l'utilisation de la commande **runtests**. Le fichier le plus important de ce dossier est `tests_runner.py`. Celui-ci contient un dictionnaire python qui permet de préciser quel scenario de quel dossier doit bien s'exécuter ou doit mal s'exécuter. En effet, pour vérifier le bon fonctionnement de son projet, le professeur peut simuler le code des élèves de telle sorte que les résultats des scénarios de tests doivent être positifs ou négatifs. Ce fichier est en directe corrélation avec la liste __SCENARIOS_TESTS__ définie dans le fichier config.py. Le professeur a connaissance des scénarios qu'il a placés dans cette liste pour ses tests personnels. Ce dictionnaire est écrit comme suit : ``` TESTS = { "ExampleTestOK" : True, "ExampleTestKO" : { "scenario2" : True, "scenario_test" : False, "bad_scenario_test" : False }, } ``` __ExampleTestOk__ est un dossier qui contient une simulation de fichier source d'un élève tel que tous les tests de __SCENARIOS_TESTS__ doivent bien s'exécuter. __ExampleTestKO__ est un dossier qui contient une simulation de fichier source d'un élève tel que le scenario2 doit bien s'exécuter tandis qu'il doit y avoir au moins une erreur en exécutant les deux autres. ### C. Fichier de modalités : modalites.txt <a id='modalites'></a> Le fichier `modalites.txt` est généré lors de la [configuration d'un projet](#config). Le fichier de modalités est le support que les étudiants utilisent pour demander une évaluation de leur code. Ce fichier contient plusieurs blocs de textes, chacun relatif à un scénario de tests écrit par un professeur. Chaque bloc de texte contient le nom du scénario, la dernière date d'utilisation de ce scénario, la prochaine date à laquelle il pourra être relancé et enfin le nombre de tentatives restantes et déjà effectuées. Pour identifier les scénarios qu'un étudiant veut jouer, il suffit que ce dernier remplace le terme "non" écrit à côté du nom du scénario par "oui". Il est aussi possible de jouer tous les scénarios en remplaçant "non" par "oui" sur la première ligne du fichier de modalités, ainsi que de ne jouer que les scénario sans restriction du nombre de tentatives en remplaçant "non" par "oui" sur la deuxième ligne du fichier. Voici un exemple de fichier de modalités : ```txt Voulez-vous jouer tous les tests ? non Voulez-vous jouer tous les tests qui n'ont pas de restriction de tentatives (infini) ? non scenario1 : non nombre de tentatives infini, vous avez joue ce test 3 fois derniere tentative = 2021-03-03 15:52:16.828228 prochaine tentative possible = 2021-03-03 15:52:21.828228 scenario2 : non nombre de tentatives restantes = 10 derniere tentative = 2021-03-03 15:52:16.828228 prochaine tentative possible = 2021-03-03 15:52:21.828228 ``` Si jamais un étudiant modifie et compromet ce fichier en supprimant ou ajoutant une ligne ou s'il écrit autre chose que "oui" ou "non", alors ce dernier est prévenu de la compromission, aucun scénario n'est joué et le fichier de modalité est réinitialisé. ### D. Fichier d'avancée globale : avancee_globale_[DATE].txt <a id='avancee'></a> Pour générer un fichier `avancee_globale_[DATE].txt`, référez-vous à [cette partie](#progress). Un fichier d'avancée globale contient la progression des étudiants vis-à-vis du score obtenu par scénario. Cette progression est exprimée scénario par scénario et enfin pour la totalité des scénarios dans l'ordre de résultats croissants. De plus, il est possible d'observer le nombre de tentatives effectuées pour chaque scénario pour chaque élève. Voici un exemple de fichier d'avancée globale : ```txt Date d'execution : 2021-03-03_15h52m25s scenario1 ------------------------------------------- Eleve1 : 2/5 (40.0%) 3 tentatives ------------------------------------------- Eleve2 : 3/5 (60.0%) 5 tentatives ------------------------------------------- Eleve3 : 5/5 (100.0%) 2 tentatives ------------------------------------------- scenario2 ------------------------------------------- Eleve1 : 3/5 (60.0%) 3 tentatives ------------------------------------------- Eleve2 : 0/5 (0.0%) 0 tentative ------------------------------------------- Eleve3 : 4/5 (80.0%) 1 tentative ------------------------------------------- Score total obtenu par les etudiants : ------------------------------------------- Eleve2 : 3/10 (30.0%) ------------------------------------------- Eleve1 : 5/10 (50.0%) ------------------------------------------- Eleve3 : 9/10 (90.0%) ------------------------------------------- ``` ### E. Fichiers de retour : synthese.txt et details.txt <a id='retour'></a>
Java
UTF-8
1,802
1.992188
2
[ "MIT" ]
permissive
package com.google.android.gms.internal; import android.util.Log; import com.google.ads.AdRequest; @C1507ey /* renamed from: com.google.android.gms.internal.gr */ public final class C1607gr { /* renamed from: S */ public static void m4705S(String str) { if (m4714v(3)) { Log.d(AdRequest.LOGTAG, str); } } /* renamed from: T */ public static void m4706T(String str) { if (m4714v(6)) { Log.e(AdRequest.LOGTAG, str); } } /* renamed from: U */ public static void m4707U(String str) { if (m4714v(4)) { Log.i(AdRequest.LOGTAG, str); } } /* renamed from: V */ public static void m4708V(String str) { if (m4714v(2)) { Log.v(AdRequest.LOGTAG, str); } } /* renamed from: W */ public static void m4709W(String str) { if (m4714v(5)) { Log.w(AdRequest.LOGTAG, str); } } /* renamed from: a */ public static void m4710a(String str, Throwable th) { if (m4714v(3)) { Log.d(AdRequest.LOGTAG, str, th); } } /* renamed from: b */ public static void m4711b(String str, Throwable th) { if (m4714v(6)) { Log.e(AdRequest.LOGTAG, str, th); } } /* renamed from: c */ public static void m4712c(String str, Throwable th) { if (m4714v(4)) { Log.i(AdRequest.LOGTAG, str, th); } } /* renamed from: d */ public static void m4713d(String str, Throwable th) { if (m4714v(5)) { Log.w(AdRequest.LOGTAG, str, th); } } /* renamed from: v */ public static boolean m4714v(int i) { return (i >= 5 || Log.isLoggable(AdRequest.LOGTAG, i)) && i != 2; } }
C++
UTF-8
1,122
2.796875
3
[]
no_license
/************************************************************************* > File Name: colleage.h > Author: Duke-wei > Mail: 13540639584@163.com > Created Time: 2017年01月10日 星期二 10时27分49秒 ************************************************************************/ #ifndef _COLLEAGE_H_ #define _COLLEAGE_H_ #include<string> using namespace std; class Mediator; class Colleage{ public: virtual ~Colleage(); virtual void Action()=0; virtual void SetState(const string& sdt) = 0; virtual string GetState()=0; protected: Colleage(); Colleage(Mediator* mdt); Mediator* _mdt; private: }; class ConcreteColleageA:public Colleage{ public: ConcreteColleageA(); ConcreteColleageA(Mediator* mdt); ~ConcreteColleageA(); void Action(); void SetState(const string& sdt); string GetState(); protected: private: string _sdt; }; class ConcreteColleageB:public Colleage{ public: ConcreteColleageB(); ConcreteColleageB(Mediator* mdt); ~ConcreteColleageB(); void Action(); void SetState(const string& sdt); string GetState(); protected: private: string _sdt; }; #endif
Markdown
UTF-8
4,828
2.625
3
[]
no_license
--- layout: post permalink: /bookreview-habit2/ title: '2.무엇이 우리를 지속하게 하는가: 책 <해빗>' date: 2020-02-09 00:01:00 +09:00 feature: '/img/posts/002/blog2-thumbnail.jpg' background: '/img/posts/002/blog2-background.jpg' content_id: 'id002' categories: - bookreview tags: - Book review - 책리뷰 - 습관 - 해빗 description: '무엇이 우리를 지속하게 하는가. 습관은 목표에 집착하지 않는다. 습관은 애쓰지 않는다.' --- ## 무엇이 우리를 지속하게 하는가 1. 습관은 목표에 집착하지 않는다 뇌 과학적으로 봤을 때 무언가를 반복하는 일은 무언가를 시작하는 일과 전혀 다른 영역의 행위이며, 같은 방식으로 여러 번 반복하면 그것은 완전히 다른 무어나로 변할 수 있다. 이렇게 변한 '무언가'는 보상 따위와는 아무런 상관없이 매우 강력한 지속력을 얻게 된다. 많은 사람들이 행동의 동기는 보상을 얻기 위함이라고 생각하기 쉽다. 하지만 사람들은 목적이나 결과에 따른 보상이 없더라도 그저 습관에 따라 행동한다고 한다. '나는 지금 냉장고 앞에 서있어. 그러니 냉장고 문을 열어야지.' 뇌 깊은 곳에 이런 추론 과정이 무언가를 먹어야 한다는 의식적인 결정이 아니라 단순한 습관일 뿐이라는 것이다. 습관의 정체는 동기와 의지에 연연하지 않고 스스로 작동한다는 사실을 알게 되었다. 습관의 지배력이 강해질수록 인간은 행동의 목표와 보상에 점점 둔감해진다. 무언가를 시작하는데 동기와 목표는 분명 중요하지만, 적절한 보상은 우리에게 좋은 습관이 형성되는데 많은 도움이 되기는 하지만, 무언가를 반복하는 일은 완전히 다른 영역에 놓여있다. 습관을 형성하는 핵심 요소는 '상황'이다. 습관의 가장 중요한 특징은 힘들이지 않아도 된다는 것이며 그저 특정한 상황이 닥치면 정해진 반응이 튀어나온다. 의식적으로 손가락을 들지 않아도 일이 처리 되는 기쁨을 누릴 수 있다. 베테랑의 소방관들과 미식축구 선수들, 이들의 사고과정은 놀랍도록 유사하다. 반복적인 훈련을 거듭한 끝에 극심한 혼란이나 연기, 혹은 130킬로그램이 넘는 수비수의 돌진 속에서도 자신이 해야 할 일이 무엇인지 놓치지 않았다. 겉으로는 별 것 아닌 것 처럼 보이지만 습관의 매커니즘이 현실에서 발휘하는 힘은 이처럼 확실하다. 습관은 목표에 집착하느라 쓸데 없이 시간을 낭비하지 않는다. 2. 습관은 애쓰지 않는다 무언가를 시작할 때(학습)의 뇌와 무언가를 반복할 때(습관)의 뇌가 전혀 다르게 작동한다는 점만 기억하라. 그리고 각각의 영역은 자극을 많이 받으면 받을 수록 더 발달한다. 당신의 행동이 뇌를 재설계할 수 있다는 사실이다. 다른 사람의 눈에는 당신이 처음 그 행동을 배웠을 때(학습)와 늘 똑같은 일을 하고 있는 것처럼 보이지만, 그 일을 반복할 수록(습관) 당신의 뇌 속에서는 새로운 신경 시스템이 계속해서 재구축되는 것이다. 바로 이러한 뇌의 재설계 덕분에 과거에 우리가 학습했던 것을 반복하면 그 다음에는 좀 더 수행하기가 쉬워진다. 뇌가 그에 맞춰 조금씩 변하기 때문이다. 소금을 얼마나 더 넣어야 하는지, 면은 언제 꺼내야 하는지, 스파게티 소스가 어디에 있는지 고민할 필요가 없다. 이렇게 습관히 형성된다. 그렇다면 우리 삶에서 순수하게 학습의 영역과 습관의 영역을 분리할 수 있을까? 바로 이 점이 습관의 과학을 연구하는 데 가장 큰 걸림돌이 된다. '목표'에 집중하는 신경 시스템(학습)과 '상황'에 더 민감하게 반응하는 신경 시스템(습관)은 서로 긴밀하게 연결되어 있는 한편 함께 작동할 때가 많기 때문이다. 우리는 의식적으로 대부분의 시간을 자동조종 모드로 보낸다. 물론 당장 적군의 측면 공격이 임박한 상황이 아니라면 말이다. 아군이 적에 몰살당할지도 모르는 상황에 처하면 어떻게 해서든 기병대를 불러야 한다. 그러나 미국인들은 충분한 채소 섭취와 같은 사소한 일에 대해선 굳이 돌격신호를 낭비할 필요가 없다고 여겼다. 우리는 모든 시간에 기병대를 투입할 수 없다. 실행제어 기능이 처리할 수 없는 임무에 대해서는 다른 영역의 힘을 빌려야 한다. 바로 습관 말이다. 그리고 습관은 아무런 비용이 들지 않는다.
SQL
UTF-8
13,897
4.0625
4
[]
no_license
WITH report_vars AS ( SELECT ('[[Username]]') AS "USERNAME", ('[[From=date]]') AS "REPORT_START", ('[[To=date]]') AS "REPORT_END" FROM sysibm.sysdummy1 ), timetable_structure AS ( SELECT term.timetable_id, term.term_id, cycle_day.cycle_day_id, cycle_day.cycle_id, cycle_day.day_index FROM term INNER JOIN term_group ON term_group.term_id = term.term_id INNER JOIN cycle_day ON cycle_day.cycle_id = term_group.cycle_id WHERE start_date <= (SELECT report_start FROM report_vars) AND end_date >= (SELECT report_start FROM report_vars) AND term.timetable_id NOT IN (SELECT timetable_id FROM timetable WHERE LOWER(timetable) LIKE '%detention%') ), teacher_timetable AS ( SELECT timetable_structure.timetable_id, timetable_structure.term_id, timetable_structure.cycle_day_id, timetable_structure.cycle_id, timetable_structure.day_index, period_cycle_day.period_cycle_day_id, period_cycle_day.period_id, period.period, period_class.class_id, class.class, period_class.effective_start, period_class.effective_end, perd_cls_teacher.is_primary, perd_cls_teacher.teacher_id, room.code AS "ROOM" FROM timetable_structure -- Join all periods LEFT JOIN period_cycle_day ON period_cycle_day.cycle_day_id = timetable_structure.cycle_day_id LEFT JOIN period ON period.period_id = period_cycle_day.period_id -- Join all timetabled classes on all periods LEFT JOIN period_class ON period_class.timetable_id = timetable_structure.timetable_id AND period_class.period_cycle_day_id = period_cycle_day.period_cycle_day_id AND period_class.effective_start <= (SELECT report_start FROM report_vars) AND period_class.effective_end >= (SELECT report_start FROM report_vars) LEFT JOIN class ON class.class_id = period_class.class_id -- Join all teachers on all periods LEFT JOIN perd_cls_teacher ON perd_cls_teacher.period_class_id = period_class.period_class_id LEFT JOIN teacher ON teacher.teacher_id = perd_cls_teacher.teacher_id -- Join room information INNER JOIN room ON room.room_id = period_class.room_id -- Only show data for specific teacher WHERE perd_cls_teacher.teacher_id = (SELECT teacher_id FROM teacher WHERE contact_id = (SELECT contact_id FROM sys_user WHERE username = (SELECT username FROM report_vars))) AND (class.class NOT LIKE ('12 Study%') AND class.class NOT LIKE ('11 Study%') AND class.class NOT LIKE ('%Distance Education%') AND class.class NOT LIKE ('%Saturday%') AND class.class NOT LIKE ('%Work in the Community%')) ORDER BY timetable_structure.timetable_id, timetable_structure.term_id, timetable_structure.cycle_id, timetable_structure.day_index, period.start_time ), raw_traffic AS ( SELECT * FROM TABLE(DB2INST1.get_period_network_traffic( (SELECT username FROM report_vars), (SELECT report_start FROM report_vars), (SELECT report_end FROM report_vars) )) ), active_term AS ( SELECT term_id, start_date, end_date, cycle_start_day, timetable_id FROM term WHERE timetable_id = ( SELECT timetable_id FROM timetable WHERE academic_year_id = ( SELECT academic_year_id FROM academic_year WHERE academic_year = YEAR(current date) ) AND default_flag = 1 ) AND (SELECT report_start FROM report_vars) BETWEEN start_date AND end_date ), active_timetable AS ( SELECT * FROM TABLE(edumate.get_timetable_cycle_day_date((SELECT report_start FROM report_vars), (SELECT report_end FROM report_vars))) WHERE timetable_id = (SELECT timetable_id FROM active_term) ), traffic_and_day_index AS ( SELECT raw_traffic.username, raw_traffic.start_date, raw_traffic.end_date, active_timetable.day_index, raw_traffic.start_time, raw_traffic.end_time, raw_traffic.data_in, raw_traffic.data_out FROM raw_traffic INNER JOIN active_timetable ON active_timetable.date_on = raw_traffic.start_date ), timetable_skeleton AS ( SELECT cycle_day.day_index, period.period_id, period.period, period.short_name, period.start_time, period.end_time FROM cycle_day INNER JOIN period_cycle_day pcd ON pcd.cycle_day_id = cycle_day.cycle_day_id INNER JOIN period ON period.period_id = pcd.period_id WHERE cycle_id = 25 ORDER BY cycle_day.day_index, period.start_time ), traffic_by_period AS ( SELECT traffic_and_day_index.username, traffic_and_day_index.start_date, traffic_and_day_index.day_index, timetable_skeleton.period_id, traffic_and_day_index.data_in, traffic_and_day_index.data_out FROM traffic_and_day_index INNER JOIN timetable_skeleton ON timetable_skeleton.day_index = traffic_and_day_index.day_index AND traffic_and_day_index.start_time BETWEEN timetable_skeleton.start_time AND timetable_skeleton.end_time ), period_totals AS ( SELECT day_index, period_id, SUM(BIGINT(data_in)) AS "DATA_IN_TOTAL", SUM(BIGINT(data_out)) AS "DATA_OUT_TOTAL" FROM traffic_by_period GROUP BY day_index, period_id ), teacher_timetable_aggregate AS ( SELECT period_id, LISTAGG(class, ', ') WITHIN GROUP(ORDER BY period_id) AS "CLASS", (CASE WHEN ROW_NUMBER() OVER (PARTITION BY period_id) = 1 THEN room ELSE null END) AS "ROOM" --LISTAGG(room, ', ') WITHIN GROUP(ORDER BY period_id) AS "ROOM" FROM teacher_timetable GROUP BY period_id, room ), timetable_and_totals AS ( SELECT DISTINCT timetable_skeleton.day_index, timetable_skeleton.period_id, timetable_skeleton.period, timetable_skeleton.short_name, timetable_skeleton.start_time, teacher_timetable_aggregate.class, (CASE WHEN teacher_timetable_aggregate.room IS null THEN '' ELSE teacher_timetable_aggregate.room END) AS ROOM, --timetable_skeleton.end_time, (CASE WHEN FLOAT(period_totals.data_in_total) / 1024 < 100 THEN 0 ELSE (BIGINT(period_totals.data_in_total) / 1024) END) AS "DOWNLOADED", (CASE WHEN FLOAT(period_totals.data_out_total) / 1024 < 100 THEN 0 ELSE (BIGINT(period_totals.data_out_total) / 1024) END) AS "UPLOADED" FROM timetable_skeleton LEFT JOIN teacher_timetable ON teacher_timetable.day_index = timetable_skeleton.day_index AND teacher_timetable.period_id = timetable_skeleton.period_id LEFT JOIN teacher_timetable_aggregate ON teacher_timetable_aggregate.period_id = timetable_skeleton.period_id LEFT JOIN period_totals ON period_totals.day_index = timetable_skeleton.day_index AND period_totals.period_id = timetable_skeleton.period_id --ORDER BY timetable_skeleton.day_index, timetable_skeleton.start_time ), day_one_totals AS ( SELECT period, short_name, LISTAGG(class || ' (' || room || ')', ', ') WITHIN GROUP(ORDER BY class) AS class, start_time, (CASE WHEN VARCHAR(downloaded) = '0' THEN '< 100' ELSE VARCHAR(downloaded) END) AS "DAY_1_DOWNLOADED", (CASE WHEN VARCHAR(uploaded) = '0' THEN '< 100' ELSE VARCHAR(uploaded) END) AS "DAY_1_UPLOADED" FROM timetable_and_totals WHERE day_index = 1 GROUP BY period, short_name, start_time, downloaded, uploaded ), day_two_totals AS ( SELECT period, LISTAGG(class || ' (' || room || ')', ', ') WITHIN GROUP(ORDER BY class) AS class, (CASE WHEN VARCHAR(downloaded) = '0' THEN '< 100' ELSE VARCHAR(downloaded) END) AS "DAY_2_DOWNLOADED", (CASE WHEN VARCHAR(uploaded) = '0' THEN '< 100' ELSE VARCHAR(uploaded) END) AS "DAY_2_UPLOADED" FROM timetable_and_totals WHERE day_index = 2 GROUP BY period, downloaded, uploaded ), day_three_totals AS ( SELECT period, LISTAGG(class || ' (' || room || ')', ', ') WITHIN GROUP(ORDER BY class) AS class, (CASE WHEN VARCHAR(downloaded) = '0' THEN '< 100' ELSE VARCHAR(downloaded) END) AS "DAY_3_DOWNLOADED", (CASE WHEN VARCHAR(uploaded) = '0' THEN '< 100' ELSE VARCHAR(uploaded) END) AS "DAY_3_UPLOADED" FROM timetable_and_totals WHERE day_index = 3 GROUP BY period, downloaded, uploaded ), day_four_totals AS ( SELECT period, LISTAGG(class || ' (' || room || ')', ', ') WITHIN GROUP(ORDER BY class) AS class, (CASE WHEN VARCHAR(downloaded) = '0' THEN '< 100' ELSE VARCHAR(downloaded) END) AS "DAY_4_DOWNLOADED", (CASE WHEN VARCHAR(uploaded) = '0' THEN '< 100' ELSE VARCHAR(uploaded) END) AS "DAY_4_UPLOADED" FROM timetable_and_totals WHERE day_index = 4 GROUP BY period, downloaded, uploaded ), day_five_totals AS ( SELECT period, LISTAGG(class || ' (' || room || ')', ', ') WITHIN GROUP(ORDER BY class) AS class, (CASE WHEN VARCHAR(downloaded) = '0' THEN '< 100' ELSE VARCHAR(downloaded) END) AS "DAY_5_DOWNLOADED", (CASE WHEN VARCHAR(uploaded) = '0' THEN '< 100' ELSE VARCHAR(uploaded) END) AS "DAY_5_UPLOADED" FROM timetable_and_totals WHERE day_index = 5 GROUP BY period, downloaded, uploaded ), day_six_totals AS ( SELECT period, LISTAGG(class || ' (' || room || ')', ', ') WITHIN GROUP(ORDER BY class) AS class, (CASE WHEN VARCHAR(downloaded) = '0' THEN '< 100' ELSE VARCHAR(downloaded) END) AS "DAY_6_DOWNLOADED", (CASE WHEN VARCHAR(uploaded) = '0' THEN '< 100' ELSE VARCHAR(uploaded) END) AS "DAY_6_UPLOADED" FROM timetable_and_totals WHERE day_index = 6 GROUP BY period, downloaded, uploaded ), day_seven_totals AS ( SELECT period, LISTAGG(class || ' (' || room || ')', ', ') WITHIN GROUP(ORDER BY class) AS class, (CASE WHEN VARCHAR(downloaded) = '0' THEN '< 100' ELSE VARCHAR(downloaded) END) AS "DAY_7_DOWNLOADED", (CASE WHEN VARCHAR(uploaded) = '0' THEN '< 100' ELSE VARCHAR(uploaded) END) AS "DAY_7_UPLOADED" FROM timetable_and_totals WHERE day_index = 7 -- AND room IS NOT null GROUP BY period, downloaded, uploaded ), day_eight_totals AS ( SELECT period, LISTAGG(class || ' (' || room || ')', ', ') WITHIN GROUP(ORDER BY class) AS class, (CASE WHEN VARCHAR(downloaded) = '0' THEN '< 100' ELSE VARCHAR(downloaded) END) AS "DAY_8_DOWNLOADED", (CASE WHEN VARCHAR(uploaded) = '0' THEN '< 100' ELSE VARCHAR(uploaded) END) AS "DAY_8_UPLOADED" FROM timetable_and_totals WHERE day_index = 8 GROUP BY period, downloaded, uploaded ), day_nine_totals AS ( SELECT period, LISTAGG(class || ' (' || room || ')', ', ') WITHIN GROUP(ORDER BY class) AS class, (CASE WHEN VARCHAR(downloaded) = '0' THEN '< 100' ELSE VARCHAR(downloaded) END) AS "DAY_9_DOWNLOADED", (CASE WHEN VARCHAR(uploaded) = '0' THEN '< 100' ELSE VARCHAR(uploaded) END) AS "DAY_9_UPLOADED" FROM timetable_and_totals WHERE day_index = 9 GROUP BY period, downloaded, uploaded ), day_ten_totals AS ( SELECT period, LISTAGG(class || ' (' || room || ')', ', ') WITHIN GROUP(ORDER BY class) AS class, (CASE WHEN VARCHAR(downloaded) = '0' THEN '< 100' ELSE VARCHAR(downloaded) END) AS "DAY_10_DOWNLOADED", (CASE WHEN VARCHAR(uploaded) = '0' THEN '< 100' ELSE VARCHAR(uploaded) END) AS "DAY_10_UPLOADED" FROM timetable_and_totals WHERE day_index = 10 GROUP BY period, downloaded, uploaded ) -- Final query SELECT (SELECT username FROM report_vars) AS "REPORT_USERNAME", TO_CHAR((SELECT report_start FROM report_vars), 'DD Month') AS "REPORTING_FROM", TO_CHAR((SELECT report_end FROM report_vars), 'DD Month YYYY') AS "REPORTING_TO", ((SELECT * FROM TABLE(DB2INST1.BUSINESS_DAYS_COUNT((SELECT report_start FROM report_vars), (SELECT report_end FROM report_vars)))) / 10) AS "FN_COUNT", day_one_totals.period, day_one_totals.short_name, day_one_totals.class AS "DAY_ONE_TT", day_one_totals.day_1_downloaded || ' KB down, ' || day_one_totals.day_1_uploaded || ' KB up' AS "DAY_ONE_DATA", day_two_totals.class AS "DAY_TWO_TT", day_two_totals.day_2_downloaded || ' KB down, ' || day_two_totals.day_2_uploaded || ' KB up' AS "DAY_TWO_DATA", day_three_totals.class AS "DAY_THREE_TT", day_three_totals.day_3_downloaded || ' KB down, ' || day_three_totals.day_3_uploaded || ' KB up' AS "DAY_THREE_DATA", day_four_totals.class AS "DAY_FOUR_TT", day_four_totals.day_4_downloaded || ' KB down, ' || day_four_totals.day_4_uploaded || ' KB up' AS "DAY_FOUR_DATA", day_five_totals.class AS "DAY_FIVE_TT", day_five_totals.day_5_downloaded || ' KB down, ' || day_five_totals.day_5_uploaded || ' KB up' AS "DAY_FIVE_DATA", day_six_totals.class AS "DAY_SIX_TT", day_six_totals.day_6_downloaded || ' KB down, ' || day_six_totals.day_6_uploaded || ' KB up' AS "DAY_SIX_DATA", day_seven_totals.class AS "DAY_SEVEN_TT", day_seven_totals.day_7_downloaded || ' KB down, ' || day_seven_totals.day_7_uploaded || ' KB up' AS "DAY_SEVEN_DATA", day_eight_totals.class AS "DAY_EIGHT_TT", day_eight_totals.day_8_downloaded || ' KB down, ' || day_eight_totals.day_8_uploaded || ' KB up' AS "DAY_EIGHT_DATA", day_nine_totals.class AS "DAY_NINE_TT", day_nine_totals.day_9_downloaded || ' KB down, ' || day_nine_totals.day_9_uploaded || ' KB up' AS "DAY_NINE_DATA", day_ten_totals.class AS "DAY_TEN_TT", day_ten_totals.day_10_downloaded || ' KB down, ' || day_ten_totals.day_10_uploaded || ' KB up' AS "DAY_TEN_DATA" FROM day_one_totals LEFT JOIN day_two_totals ON day_two_totals.period = day_one_totals.period LEFT JOIN day_three_totals ON day_three_totals.period = day_one_totals.period LEFT JOIN day_four_totals ON day_four_totals.period = day_one_totals.period LEFT JOIN day_five_totals ON day_five_totals.period = day_one_totals.period LEFT JOIN day_six_totals ON day_six_totals.period = day_one_totals.period LEFT JOIN day_seven_totals ON day_seven_totals.period = day_one_totals.period LEFT JOIN day_eight_totals ON day_eight_totals.period = day_one_totals.period LEFT JOIN day_nine_totals ON day_nine_totals.period = day_one_totals.period LEFT JOIN day_ten_totals ON day_ten_totals.period = day_one_totals.period ORDER BY day_one_totals.start_time
Java
UTF-8
2,634
2.125
2
[ "BSD-3-Clause" ]
permissive
/** * Copyright (c) 2008-2018, Massachusetts Institute of Technology (MIT) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package edu.mit.ll.nics.nicsdao.mappers; import edu.mit.ll.nics.common.entity.TaskAssign; import edu.mit.ll.jdbc.JoinRowMapper; import edu.mit.ll.nics.common.entity.Form; import edu.mit.ll.nics.common.constants.TaskingConstants; import java.sql.ResultSet; import java.sql.SQLException; public class TaskAssignRowMapper extends JoinRowMapper<TaskAssign> { public TaskAssignRowMapper() { super("task_assign"); } @Override public TaskAssign createRowObject(ResultSet rs, int rowNum) throws SQLException { TaskAssign taskAssign = new TaskAssign(); taskAssign.setId(rs.getLong("id")); taskAssign.setCompleted(rs.getBoolean("completed")); // TODO: Not proper way to do this... need to query/join actual form Form form = new Form(); form.setFormId(rs.getInt("form_id")); taskAssign.setForm(form); return taskAssign; } public String getKey(ResultSet rs) throws SQLException{ return rs.getString("id"); } }
Markdown
UTF-8
1,010
2.640625
3
[ "Apache-2.0" ]
permissive
Goadd: Add Folder To Gopath™ ========================== ![image](https://farm5.staticflickr.com/4317/35198386374_1939af3de6_k_d.jpg) ## Requirements - Go development environment: >= **go1.2** ### Install from source code go get -u github.com/apple-han/goadd The executable will be produced under `$GOPATH/bin` in your file system; for global use purpose, we recommend you to add this path into your `PATH` environment variable. ## Features - Add folder to gopath. - Easy to find files under gopath ``` $ goadd NAME: Goadd - Add Folder To GoPath USAGE: Goadd [arguments...] VERSION: 0.0.1 Beta COMMANDS: run add a new folder, and add to gopath list list all files of gopath help, h Shows a list of commands or help for one command GLOBAL OPTIONS: --help, -h show help --version, -v print the version ``` ## License This project is under the Apache License, Version 2.0. See the [LICENSE](LICENSE) file for the full license text.
PHP
UTF-8
1,189
2.546875
3
[]
no_license
<?php class APP { private static $instance = null; public static function getInstance () { if(!self::$instance) { self::$instance = new self(); } return self::$instance; } public function run (){ require_once 'controllers/GroupsController.php'; require_once 'controllers/StudentsController.php'; $appLocales = include 'locales/en/modules.php'; $model = $_GET['model']; $action = $_GET['action'] ?: "index"; $controllerName = ucfirst($model) . "Controller"; $methodName = "action" . ucfirst($action); $controllerObject = new $controllerName(); $data = $controllerObject->$methodName(); $viewPath = "views/{$model}/{$action}.php"; if( empty($model) || !method_exists($controllerObject, $methodName) || !file_exists($viewPath) ) { $viewPath = "views/errors/e404.php"; } ob_start(); $pageTitle = $appLocales[$model]['title']; include $viewPath; $pageContent = ob_get_contents(); ob_end_clean(); include 'layouts/main.php'; } }
Java
UTF-8
2,828
1.710938
2
[ "BSD-3-Clause", "Classpath-exception-2.0", "GPL-2.0-only", "Apache-2.0", "MIT", "CDDL-1.1" ]
permissive
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ads.googleads.codegen; import com.google.ads.googleads.lib.stubs.annotations.VersionDescriptor; import com.google.ads.googleads.lib.stubs.exceptions.BaseGoogleAdsException; import com.google.api.gax.rpc.ApiException; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.Message; import com.squareup.javapoet.JavaFile; import io.grpc.Metadata; import java.io.IOException; import java.util.Set; import org.junit.Test; /** Test cases for {@link GeneratedCatalogCodeGenerator} . */ public class GeneratedCatalogCodeGeneratorTest extends AbstractGeneratorTest { private Set<Integer> versions = ImmutableSet.of(1); private int latestVersion = 1; /** Ensures the the generated code matches a base case. */ @Test public void baseCaseCodeMatches() throws IOException { // Executes the test case. assertGeneratedCodeMatches( "/com/google/ads/googleads/codegen/GeneratedCatalog.java.expected"); } /** * Implements the abstract method to invoke generator. * * @return */ @Override protected JavaFile invokeCodeGenClass() { return new GeneratedCatalogCodeGenerator( versions, latestVersion, ImmutableMap.of( MockVersion.class.getAnnotation(VersionDescriptor.class), MockVersion.class), temporaryFolder.getRoot()) .generate(); } @VersionDescriptor(versionName = "v1", googleAdsExceptionFactory = MockExceptionFactory.class) static class MockVersion {} static class MockExceptionFactory extends BaseGoogleAdsException.Factory { @Override protected BaseGoogleAdsException createException( ApiException source, byte[] protoData, Metadata metadata) throws InvalidProtocolBufferException { return null; } @Override public Metadata.Key<byte[]> getTrailerKey() { return null; } @Override public Message createGoogleAdsFailure() { return null; } @Override public Message createGoogleAdsFailure(byte[] serializedBytes) throws InvalidProtocolBufferException { return null; } } }
Markdown
UTF-8
1,355
2.59375
3
[]
no_license
# Introduction ## Autorun Manager Autorun Manager (formerly Autorun Killer) lets you decide what apps you want to let automatically start up. It sports two modes: Basic mode lets you decide which startup apps should be killed right after they start during system boot process. Applications are usually autostarting because of a reason, so only disable one if you know exactly what it is doing and you definitely don't need it. Advanced mode lists all your applications which are registered for system wide events (aka. [intents](https://developer.android.com/intl/fr/reference/android/content/Intent.html) like an incoming call, low battery or boot finished) and gives you the control to enable or disable these -so called- receivers. Using this mode recommends above average knowledge about how your device works. **Please be very careful.** If you encounter errors with your disabled apps please re-enable them. <img src="images/ark1.png" alt="shot 1" /> <img src="images/ark2.png" alt="shot 2" /> [![Get it on Google Play](../img/google-play-badge.png)](https://play.google.com/store/apps/details?id=com.rs.autokiller) ## Go PRO If you like my work please consider buying the PRO version, this will support further development. [![Get it on Google Play](../img/google-play-badge.png)](https://play.google.com/store/apps/details?id=com.rs.autorun.pro)
Java
UTF-8
1,241
3.671875
4
[]
no_license
/** * Handles setting walls around the GameScreen. * @author andreirichkov * retrieved from https://github.com/andreirichkov/console-snake */ public class Wall extends GameObject { /** * Default constructor. Sets symbol to '#' */ public Wall() { setSymbol('#'); } /** * Constructor for Wall * @param symbol Character used to represent the wall */ public Wall(char symbol) { setSymbol(symbol); } /** * Adds horizontal line of walls to GameScreen * @param screen GameScreen to draw Wall on * @param wall Wall to draw on GameScreen * @param rowNumber Row on gamescreen to draw wall to */ public void addWallsRow(GameScreen screen, Wall wall, int rowNumber) { for (int i = 0; i < screen.getScreenWidth(); i++) { screen.setObjectOnLocation(wall, i, rowNumber); } } /** * Adds vertical line of wall to GameScreen * @param screen GameScreen to draw Wall on * @param wall Wall to draw on GameScreen * @param columnNumber Column on gamescreen to draw wall to */ public void addWallsColumn(GameScreen screen, Wall wall, int columnNumber) { for (int i = 0; i < screen.getScreenHeight(); i++) { screen.setObjectOnLocation(wall, columnNumber, i); } } }
Shell
UTF-8
1,083
3.96875
4
[]
no_license
#!/bin/bash # This script clears the terminal then performs an interactive checkout # if run from the src directory with RCS nested below src (src/RCS). # All .h files, all .c files, the README and the Makefile are checked out. checkout(){ cd ./RCS co -l * mv -f ./*.h ../ mv -f ./*.c ../ mv -f ./README ../ mv -f ./Makefile ../ echo "Check out complete." cd ../ rm FILES_ARE_CHECKED_IN touch FILES_ARE_CHECKED_OUT pwd ls -la exit } leave(){ echo "No checkout performed." echo "Current working file set remains unchanged:" pwd ls -la exit } tryagain(){ echo "Invalid choice. Read carefully." echo "I clearly asked y or n." echo "You can reply Y or N if you want to be difficult, but you didn't even do that." } clear echo "Checking project out from src/RCS ..." echo "This will check the project out from RCS and overwrite any" echo "existing files in this directory with the checked out files." while true do read -r -p "Are you sure you want to check out the project (y/n)? " choice case "$choice" in n|N) leave;; y|Y) checkout;; *) tryagain;; esac done
Go
UTF-8
291
3.109375
3
[]
no_license
package str func RemoveOuterParentheses(S string) string { L, R := 1, 0 resp := []byte("") for i := 1; i < len(S); i++ { cur := S[i] if cur == '(' { L++ } else { R++ } if L != R { resp = append(resp, cur) } else { i++ L, R = 1, 0 } } return string(resp) }
C
UTF-8
1,744
3.4375
3
[]
no_license
/*http://moss.cs.iit.edu/cs351/assets/slides-processmgmt-1.pdf*/ /* * In this program we are taking output from a chlid process to the parent process * If we just want to send data manually, it can be done like in t1.c but Sometime we need to redirect output to stdout hence we use * dup */ #include <stdio.h> #include <unistd.h> #include <errno.h> int main() { pid_t id; int fds[2]; if(pipe(fds)==-1) { perror("pipe"); return 1; } id=fork(); if(id==0) { printf("This is child with pid:%d and ppid:%d\n",getpid(),getppid()); close(fds[0]);//Close stdin as child is only going to write close(1);//Close stdout dup(fds[1]);//Change stdout to fds out execlp("/usr/bin/ls","ls",NULL);//I cannot see the output of this command, so I need pipes to communicate between parent and child perror("execl"); close(fds[1]); } else { close(fds[1]); close(0); dup(fds[0]); printf("This is parent with pid:%d and ppid:%d\n",getpid(),getppid()); char buffer[256]; while(1) { int bytes=read(fds[0],buffer,sizeof(buffer)); if(bytes==-1) { if(errno=EINTR)//Interrupt continue; else perror("read"); } else if(bytes==0) break; else { printf("%s",buffer); } } //sleep(10); //Either that exit or this sleep creates a zombie process because child finishes before parent //child becomes zombie beause the entry remains in process table and pid cannot be used again. //This is handled in 2 ways, either use wait in parent or handle SIGCHLD signal //If there is no wait in parent then init takes over that zombie after the parent terminates and performs a wait to remove it. } printf("Exiting pid:%d and ppid:%d\n",getpid(),getppid()); wait(); return 0; }
Python
UTF-8
7,774
2.578125
3
[]
no_license
paper_direct={'A':['C','D'],'B':0,'C':0,'D':['B']}# 论文与其他论文的直接引用关系 paper_all={} messageuser = { 'Tsai-ing': {'password':'12345', 'first_name': 'Tsai', 'last_name': 'Ingwen', 'Phone_number': '886-22311-3731', 'relationship': {'Winnie': 0, 'Trump': 1},'paper':{}}, 'Trump': {'password':'12345', 'first_name': 'Donald', 'last_name': 'Trump', 'Phone_number': '1234567', 'relationship': {'Winnie': 1, 'Tsai-ing': 1},'paper':{}}, 'Winnie': {'password':'12345', 'first_name': 'abc', 'last_name': 'def', 'Phone_number': '1234567890', 'relationship': {'Winnie': 1, 'Tsai-ing': 0},'paper':{}}} # username:{'password':'12345','first_name':'Tsai','last_name':'Ingwen'...与别人的关系:{}}三重列表!!最外层列表是用户名,第二层列表是用户个人信息,第三重是与别人关系 messageadmin = {'dennis LIU': {'password': '123456'}} ''' def isFriend(X, Y): def IsDirectSource(A, b): def isSource(A, B): def Anchor(A): def DirectReport(A): def Report(A): def NicePrientU(X): def NicePrintA(A): def GetU(X): def GetA(A): ''' def admin(name): # admin function print('Hello',name) print(""" |---------Welcome to admin interface-----| |--- :N/n ---| |---- Login user Account:S/s ---------| |--- Create a new admin account:W/w---| |----- Login admin Account:E/e -------| |---------- Log out:Q/q --------------| """) def user(name): # user function print('Hello',name) while True: print(""" |--- Welcome to admin interfac------| |--- Submit Paper:N/n -------------| |--- Make friends: S/s--------------| |--- Back to main interface: Q/q----| """) while True: #上传paper chose = 0 while not chose: print('\n') order = input("Enter:") if order not in 'NnSsWw': print("Wrong input, please choose again!") else: chose = 1 if order=='N' or order=='n':# Submit paper paper_index=input('Please enter your paper index:') while True: if paper_index in paper_direct: print('This index has been taken, try a new index.') else: break aa=input('Please submit your paper content (Just paste here):') messageuser[name]['paper'][paper_index]=aa print('') if order=='S' or order=='s': # Make friends for i in messageuser: print(i,end='') print('') print("Enter your friend's username one by one:") while True: a1=input("Enter your friend's username(If no more, enter 'No' exit):") if a1=='No': break elif a1 in messageuser: messageuser[name]['relationship'][a1]=1 messageuser[a1]['relationship'][name]=1 else: print() if order=='Q' or order=='q': main() def user_register(): print('User register interface') name = input("Please enter your username:") while True: if name in messageuser: # temp = "This username has been taken, try another username:" continue else: # 没有此人的信息 break pw = input("Please enter your password:") messageuser[name]={} messageuser[name]['relationship']={} messageuser[name]['paper']={} messageuser[name]['password'] = pw p1 = input('Please enter your first name:') messageuser[name]['first_name']=p1 p2 = input('Please enter your last name:') messageuser[name]['last_name']=p2 print(""" |------Add auxiliary information one by one-----| |--- Date-of-birth:N/n ---| |---- Phone number:S/s ---------| """) while True: pp=input('How many type of information are you going to add:') if pp.isdigit(): break else: print('Are you serious?') chose = 0 while chose <int(pp): print('\n') order = input("Enter the type of information you would like to enter:") if order not in 'NnSs': print("Wrong input, please choose again!") else: chose +=1 if order=='N' or order=='n': k1=input('Please enter your data of birth:') messageuser[name]['Date-of-birth']=k1 if order=='S' or order=='s': k2 = input('Please enter your phone number:') messageuser[name]['Phone_number']=k2 print("Successfully register!") main() def user_login(): print('User login interface') temp = "Please enter your username:" while True: name = input(temp) if name not in messageuser: temp = "Username Wrong, try again:" continue else: break pw = str(input("Please enter your password:")) password = messageuser[name]['password'] if pw == password: print("Log in successfully") user(name) # 转到用户功能 else: print("Wrong Password") def admin_register(): print('Admin register interface') name = input("Please enter your admin name") while True: if name in messageadmin: # temp = "This username has been taken, try another username" continue else: # 没有此人的信息 break pw = input("Please enter your password") messageadmin[name] = pw print("Successfully register!") main() def admin_login(): print('Admin login interface') temp = "Please enter your admin name:" while True: name = input(temp) if name not in messageadmin: temp = "Username Wrong, try again:" continue else: break pw = input("Please enter your password:") password = messageadmin[name]['password'] if pw == password: print("Log in successfully") admin(name) # 转到管理功能 else: print("Wrong Password") def main(): while True: print('*'*20) print(""" |---------Welcome to system------------| |--- Create a new user account:N/n ---| |---- Login user Account:S/s ---------| |--- Create a new admin account:W/w---| |----- Login admin Account:E/e -------| """) print('*'*20) while True: chose = 0 while not chose: print('\n') order = input("Enter:") if order not in 'QqNnSsWwEe': print("Wrong input, please choose again!") else: chose = 1 if order == 'N' or order == 'n': user_register() if order == 'S' or order == 's': user_login() if order == 'E' or order == 'e': admin_login() if order == 'W' or order == 'E': admin_register() main()
Java
UTF-8
4,359
1.96875
2
[]
no_license
package com.example.progtablet; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONObject; import android.app.ActionBar; import android.app.Activity; import android.app.ListActivity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.StrictMode; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.InputMethodManager; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ListView; import android.widget.RadioButton; import android.widget.Spinner; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Toast; import com.example.progtablet.R; public class AddPrestitiActivity extends ListActivity implements OnClickListener{ Button salva; Spinner oggetto; EditText descrizione; ListView listasalvati; String oggettonuovo; IP ip = new IP(); int myid; String controllo = "false"; List<String> listoggetto = new ArrayList<String>(); /** Items entered by the user is stored in this ArrayList variable */ ArrayList<String> list = new ArrayList<String>(); /** Declaring an ArrayAdapter to set items to ListView */ ArrayAdapter<String> adapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_addprestiti); Bundle bundle = getIntent().getExtras(); myid = bundle.getInt("id"); descrizione = (EditText) findViewById(R.id.txtInserisciPrestito); listasalvati = (ListView) findViewById(android.R.id.list); oggetto = (Spinner) findViewById(R.id.InserisciOggetto); addItemsOnSpinner(); salva = (Button) findViewById(R.id.salvaprestiti); /** Defining the ArrayAdapter to set items to ListView */ adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list); /** Setting the adapter to the ListView */ setListAdapter(adapter); salva.setOnClickListener(this); } private void addItemsOnSpinner() { listoggetto.add("Casse"); listoggetto.add("Console"); listoggetto.add("Microfono"); listoggetto.add("Altro"); ArrayAdapter<String> dataAdapteroggetto = new ArrayAdapter<String>( this, android.R.layout.simple_spinner_item, listoggetto); dataAdapteroggetto .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); oggetto.setAdapter(dataAdapteroggetto); } @Override public void onClick(View arg0) { modifica(); adapter.notifyDataSetChanged(); } public void modifica() { oggettonuovo = oggetto.getSelectedItem().toString(); String descrizione1 = descrizione.getText().toString(); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() .permitAll().build(); StrictMode.setThreadPolicy(policy); try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost( ip.getindirizzo()+"InserisciOggetto?idutente=" + myid + "&nome=" + oggettonuovo + "&descrizione=" + descrizione1); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); if (entity != null) { String risposta = EntityUtils.toString(entity); JSONObject json = new JSONObject(risposta); controllo = json.optString("inseriscioggetto"); } Log.d("json", controllo); } catch (Exception e) { Log.e("TEST", "Errore nella connessione http " + e.toString()); } if (controllo.equals("true")) { int obj = oggetto.getSelectedItemPosition(); list.add(listoggetto.get(obj).toString()); } else { Toast toast6 = Toast.makeText(this, "Errore nell inserimento dell oggetto", Toast.LENGTH_LONG); toast6.show(); } } }
PHP
UTF-8
1,198
3.65625
4
[]
no_license
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Regular Expression</title> <style type="text/css"> p{margin: 0;} </style> </head> <body> <?php $search = "Now is the time"; print("<p>Test string is: '$search'</p>"); if(preg_match("/Now/", $search)){ print("<p>'Now' was found.</p>"); } if(preg_match("/^Now/", $search)){ print("<p>'Now' found at the beginning of the line.</p>"); } if(!preg_match("/Now$/", $search)){ print("<p>'Now' was not found at the end of the line.</p>"); } if(preg_match("/\b([a-zA-Z]*ow)\b/i", $search, $match)){ print("<p>Word found ending in 'ow': ".$match[1]."</p>"); } print("<p>Words beginning with 't' is found: "); while(preg_match("/\b(t[[:alpha:]]+)\b/", $search, $match)){ print($match[1]." "); $search = preg_replace("/".$match[1]."/","",$search); } print("</p>"); ?><!--end PHP script--> </body> </html>
Java
UTF-8
352
3.09375
3
[]
no_license
package ArrayAssignmentPrograms; public class LargestElement9 { public static void main(String[] args) { int a[] = {12,8,78,14,2}; int large= a[0]; for (int i=0;i<a.length;i++) { if(a[i] > large) large=a[i]; } System.out.println("Large Element: " + large); } }
SQL
UTF-8
4,580
3.09375
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.8.5 -- https://www.phpmyadmin.net/ -- -- Хост: 127.0.0.1:3306 -- Время создания: Июл 23 2019 г., 00:57 -- Версия сервера: 5.6.43 -- Версия PHP: 7.2.10 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 */; -- -- База данных: `task_wic` -- -- -------------------------------------------------------- -- -- Структура таблицы `countries` -- CREATE TABLE `countries` ( `country_id` int(6) NOT NULL, `country` varchar(30) NOT NULL, `country_code` varchar(2) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Дамп данных таблицы `countries` -- INSERT INTO `countries` (`country_id`, `country`, `country_code`) VALUES (1, 'Andorra', 'AD'), (2, 'Argentina', 'AR'), (3, 'American Samoa', 'AS'), (4, 'Bulgaria', 'BG'), (5, 'Brazil', 'BR'), (6, 'Canada', 'CA'), (7, 'Spain', 'ES'), (8, 'India', 'IN'), (9, 'Italy', 'IT'), (10, 'Monaco', 'MC'); -- -------------------------------------------------------- -- -- Структура таблицы `places` -- CREATE TABLE `places` ( `id` int(6) NOT NULL, `places` text NOT NULL, `country_id` int(6) DEFAULT NULL, `postcode_id` int(6) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Дамп данных таблицы `places` -- INSERT INTO `places` (`id`, `places`, `country_id`, `postcode_id`) VALUES (1, 'aaaaaaa', 1, 2), (3, '[{\"place name\":\"Canillo\",\"longitude\":\"1.6667\",\"state\":\"\",\"state abbreviation\":\"\",\"latitude\":\"42.5833\"}]', 1, 32), (4, '[{\"place name\":\"Escaldes-Engordany\",\"longitude\":\"1.5667\",\"state\":\"\",\"state abbreviation\":\"\",\"latitude\":\"42.5\"}]', 1, 33), (5, '[{\"place name\":\"Encamp\",\"longitude\":\"1.6333\",\"state\":\"\",\"state abbreviation\":\"\",\"latitude\":\"42.5333\"}]', 1, 34), (6, '[{\"place name\":\"Ordino\",\"longitude\":\"1.55\",\"state\":\"\",\"state abbreviation\":\"\",\"latitude\":\"42.6\"}]', 1, 35), (13, '[{\"place name\":\"Andorra la Vella\",\"longitude\":\"1.5\",\"state\":\"\",\"state abbreviation\":\"\",\"latitude\":\"42.5\"}]', 1, 42); -- -------------------------------------------------------- -- -- Структура таблицы `postcodes` -- CREATE TABLE `postcodes` ( `postcode_id` int(6) NOT NULL, `postcode` varchar(30) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Дамп данных таблицы `postcodes` -- INSERT INTO `postcodes` (`postcode_id`, `postcode`) VALUES (1, 'A0A'), (2, '1601'), (3, '96799'), (4, '01000-000'), (5, '110001'), (6, '00010'), (7, 'L-1009'), (8, '101000'), (30, 'AD100'), (31, 'AD100'), (32, 'AD100'), (33, 'AD700'), (34, 'AD200'), (35, 'AD300'), (42, 'AD500'); -- -- Индексы сохранённых таблиц -- -- -- Индексы таблицы `countries` -- ALTER TABLE `countries` ADD PRIMARY KEY (`country_id`); -- -- Индексы таблицы `places` -- ALTER TABLE `places` ADD PRIMARY KEY (`id`), ADD KEY `country_id` (`country_id`), ADD KEY `postcode_id` (`postcode_id`); -- -- Индексы таблицы `postcodes` -- ALTER TABLE `postcodes` ADD PRIMARY KEY (`postcode_id`); -- -- AUTO_INCREMENT для сохранённых таблиц -- -- -- AUTO_INCREMENT для таблицы `countries` -- ALTER TABLE `countries` MODIFY `country_id` int(6) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11; -- -- AUTO_INCREMENT для таблицы `places` -- ALTER TABLE `places` MODIFY `id` int(6) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14; -- -- AUTO_INCREMENT для таблицы `postcodes` -- ALTER TABLE `postcodes` MODIFY `postcode_id` int(6) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=43; -- -- Ограничения внешнего ключа сохраненных таблиц -- -- -- Ограничения внешнего ключа таблицы `places` -- ALTER TABLE `places` ADD CONSTRAINT `places_ibfk_1` FOREIGN KEY (`country_id`) REFERENCES `countries` (`country_id`), ADD CONSTRAINT `places_ibfk_2` FOREIGN KEY (`postcode_id`) REFERENCES `postcodes` (`postcode_id`); 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
623
1.796875
2
[]
no_license
package com.eqsian.tictactoe; import android.os.Bundle; import android.preference.PreferenceActivity; import android.preference.PreferenceFragment; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; /** * Created by Андрей on 10.11.2017. */ public class SettingsActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); // getFragmentManager().beginTransaction() .replace(android.R.id.content, new PrefFragment()).commit(); } }
Python
UTF-8
3,388
4.25
4
[]
no_license
import random lowercase = "abcdefghijklmnopqrstuvwxyz" uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" numbers = "0123456789" special_characters = "!@#$%^&*" three_char_words = ["shy","pop","hog","pig","cap","dog","cat","act","owl","lot"] four_char_words = ["book","bone","fish","dark","moon","ship","wild","wood","chef","duke"] five_char_words = ["ariel","bacon","camel","campy","comfy","shoes","rupee", "mango","phone","pizza"] weak_word_lists = [three_char_words, four_char_words, five_char_words] def int_input(message): """ Converts string input into 'int' type. """ answer = input(message) return int(answer) def bool_input(question, option_1, option_2): """ Returns True or False based on user-response to a two-answer question. The response being equal to the first option will return True, the second option will return false. If the user enters a response that is neither one of the options, a ValueError is raised. --- EXAMPLE --- A "Yes/No" question is a two-option question. "Yes" could be set to option_1 and "No" could be set to option_2. If the user were to enter "Yes" in response to the question, this function would return "True" while it would return "False" if the user entered "No" to the question. --------------- """ answer = input(question) if answer.upper() == option_1: return True elif answer.upper() == option_2: return False else: raise ValueError(f'Invalid input. Please enter either {option_1} or {option_2}.') def create_password(is_strong, has_numbers, has_special_chars): """ Creates a customized password based on provided parameters. """ password = "" features = [lowercase, uppercase] if has_numbers: features.append(numbers) if has_special_chars: features.append(special_characters) if is_strong: print("For a strong password, your password will be a minimum of 8 characters in length.") length = int_input("How many total characters do you want in you password?") if length < 8: raise ValueError(f'Invalid input. Please enter a greater than or equal to 8.') for x in range(0, length): current_char = random.choice(random.choice(features)) password += current_char else: print("For a weak password, your password will contain a word 3-5 characters in length.") length = int_input("How many characters do you want in your password's word?") if length >= 3 or length <=5: word_list = weak_word_lists[length-3] password += random.choice(word_list) else: raise ValueError(f'Invalid input. Please enter a value betweem 3 and 5 inclusive.') for feature in features: password += random.choice(feature) return password if __name__ == "__main__": is_strong = bool_input("Do you want a strong or weak password? (STRONG/WEAK)", option_1="STRONG", option_2="WEAK") has_numbers = bool_input("Would you like numbers in your password? (Y/N)", option_1="Y", option_2="N") has_special_chars = bool_input("Would you like special characters in your password? (Y/N)", option_1="Y", option_2="N") new_password = create_password(is_strong, has_numbers, has_special_chars) print(new_password)
C++
UTF-8
5,030
3.3125
3
[]
no_license
/* * main.cpp * * Created on: Oct 20, 2018 * Author: Anton Dogadaev */ #include <iostream> #include <iomanip> #include <map> #include <set> #include <string> #include <sstream> #include <regex> using namespace std; class Date { public: Date() : mYear(0), mMonth(0), mDay(0) {} Date(string str) { int year, month, day; const char delim = '-'; char c; checkStrFormat(str); stringstream ss(str); if (ss >> year && (ss >> c && c == delim) && ss >> month && (ss >> c && c == delim) && ss >> day) { mYear = year; checkMonthFormat(month); mMonth = month; checkDayFormat(day); mDay = day; } else { throw invalid_argument("Wrong date format: " + str); } } int GetYear() const { return mYear; } int GetMonth() const { return mMonth; } int GetDay() const { return mDay; } private: int mYear; int mMonth; int mDay; void checkStrFormat(string str) { int nums_registered = 0; const char delim = '-'; bool neg_sign_detected = false; bool recording_digits = false; for (size_t i = 0; i < str.length(); i++) { if (str[i] == delim && neg_sign_detected == false && recording_digits == false) { neg_sign_detected = true; } else if (isdigit(str[i]) != 0 && recording_digits == false) { recording_digits = true; } else if (str[i] == delim && recording_digits == true) { neg_sign_detected = false; recording_digits = false; nums_registered++; } else if (isdigit(str[i]) == 0) { throw invalid_argument("Wrong date format: " + str); } } if (nums_registered != 2 || recording_digits == false) { throw invalid_argument("Wrong date format: " + str); } } void checkMonthFormat(int month) { if (month < 1 || month > 12) { throw invalid_argument("Month value is invalid: " + to_string(month)); } } void checkDayFormat(int day) { if (day < 1 || day > 31) { throw invalid_argument("Day value is invalid: " + to_string(day)); } } }; bool operator<(const Date& lhs, const Date& rhs) { if (lhs.GetYear() < rhs.GetYear()) { return true; } else if (lhs.GetYear() == rhs.GetYear() && lhs.GetMonth() < rhs.GetMonth()) { return true; } else if (lhs.GetYear() == rhs.GetYear() && lhs.GetMonth() == rhs.GetMonth() && lhs.GetDay() < rhs.GetDay()) { return true; } return false; } class Database { public: void AddEvent(const Date& date, const string& event) { mDb[date].insert(event); } bool DeleteEvent(const Date& date, const string& event) { if (mDb.count(date) > 0 && mDb.at(date).count(event) > 0) { mDb.at(date).erase(event); if (mDb.at(date).size() == 0) { mDb.erase(date); } return true; } return false; } int DeleteDate(const Date& date) { int events = 0; if (mDb.count(date) > 0) { events = mDb.at(date).size(); } mDb.erase(date); return events; } set<string> Find(const Date& date) const { if (mDb.count(date) > 0) { return mDb.at(date); } else { return {}; } } void Print() const { if (mDb.size() != 0) { for (const auto& EventsInDay : mDb) { for (const auto& event : EventsInDay.second) { cout << setw(4) << setfill('0') << EventsInDay.first.GetYear() << '-'; cout << setw(2) << setfill('0') << EventsInDay.first.GetMonth() << '-'; cout << setw(2) << setfill('0') << EventsInDay.first.GetDay() << ' '; cout << event << endl; } } } else { cout << endl; } } private: map<Date, set<string>> mDb; }; int main() { Database db; string command; while (getline(cin, command)) { // Считайте команды с потока ввода и обработайте каждую stringstream ss(command); string command_name; string sDate; string sEvent; if (ss >> command_name) { if (command_name == "Add") { if (ss >> sDate && ss >> sEvent) { try { Date date(sDate); db.AddEvent(date, sEvent); } catch (invalid_argument& e) { cout << e.what() << endl; } } } else if (command_name == "Del") { if (ss >> sDate) { try { Date date(sDate); if (ss >> sEvent) { bool deleted = db.DeleteEvent(date, sEvent); if (deleted == true) { cout << "Deleted successfully" << endl; } else { cout << "Event not found" << endl; } } else { int deletedEvents = db.DeleteDate(date); cout << "Deleted " << deletedEvents << " events" << endl; } } catch (invalid_argument& e) { cout << e.what() << endl; } } } else if (command_name == "Find") { if (ss >> sDate) { try { Date date(sDate); set<string> events = db.Find(date); if (events.size() == 0) { cout << endl; } else { for (const string& ev : events) { cout << ev << endl; } } } catch (invalid_argument& e) { cout << e.what() << endl; } } } else if (command_name == "Print") { db.Print(); } else { cout << "Unknown command: " << command_name << endl; } } } return 0; }
Markdown
UTF-8
9,231
3
3
[ "CC0-1.0" ]
permissive
# Action Research <standard name="Action Research"> *Empirical research that investigates how an intervention, like the introduction of a method or tool, affects a real-life context* ## Application This standard applies to empirical research that meets the following conditions. - investigates a primarily social phenomenon within its real-life, organizational context - intervenes in the real-life context (otherwise see the **Case Study Standard**) - the change and its observation are an integral part of addressing the research question and contribute to research If the intervention primarily alters social phenomena (e.g. the organization's processes, culture, way of working or group dynamics), use this standard. If the intervention is a new technology or technique (e.g. a testing tool, a coding standard, a modeling grammar), especially if it lacks a social dimension, consider the **Engineering Research Standard**. If the research involves creating a technology and an organizational intervention with a social dimension, consider both standards. ## Specific Attributes ### Essential Attributes <checklist name="Essential"> <intro> <method> - [ ] justifies the selection of the site(s) that was(were) studied - [ ] describes the site(s) in rich detail - [ ] describes the relationship between the researcher and the host organization<sup>[3](#myfootnote1)</sup> - [ ] describes the intervention(s) in detail - [ ] describes how interventions were determined (e.g. by management, researchers, or a participative/co-determination process) - [ ] explains how the interventions are evaluated<sup>[4](#myfootnote3)</sup> - [ ] describes the longitudinal dimension of the research design (including the length of the study) - [ ] describes the interactions between researcher(s) and host organization(s)<sup>[1](#myfootnote1)</sup> - [ ] explains research cycles or phases, if any, and their relationship to the intervention(s)<sup>[2](#myfootnote2)</sup> <results> - [ ] presents a clear chain of evidence from observations to findings - [ ] reports participant or stakeholder reactions to interventions <discussion> - [ ] reports lessons learned by the organization - [ ] researchers reflect on their own possible biases <other> </checklist> ### Desirable Attributes <checklist name="Desirable"> - [ ] provides supplemental materials such as interview guide(s), coding schemes, coding examples, decision rules, or extended chain-of-evidence tables - [ ] uses direct quotations extensively - [ ] validates results using member checking, dialogical interviewing<sup>[5](#myfootnote1)</sup>, feedback from non-participant practitioners or research audits of coding by advisors or other researchers - [ ] findings plausibly transferable to other contexts - [ ] triangulation across quantitative and qualitative data </checklist> ### Extraordinary Attributes <checklist name="Extraordinary"> - [ ] research team with triangulation across researchers (to mitigate researcher bias) </checklist> ## General Quality Criteria Example criteria include reflexivity, credibility, resonance, usefulness and transferability (see **Glossary**). Positivist quality criteria such as internal validity, construct validity, generalizability and reliability typically do not apply. ## Examples of Acceptable Deviations - In a study of deviations from organizational standards, detailed description of circumstances and direct quotations are omitted to protect participants. - The article reports a negative outcome of an intervention and e.g. investigates why a certain method was not applicable. ## Antipatterns - Forcing interventions that are not acceptable to participants or the host organization. - Losing professional distance and impartiality; getting too involved with the community under study. - Over-selling a tool or method without regard for participants' problems, practices or values. - Avoiding systematic evaluation; downplaying problems; simply reporting participants views of the intervention. ## Invalid Criticisms - The findings and insights are not valid because the research intervened in the context. Though reflexivity is crucial, the whole point of action research is to introduce a change and observe how participants react. - This is merely consultancy or an experience report. Systematic observation and reflection should not be dismissed as consultancy or experience reports. Inversely, consultancy or experiences should not be falsely presented as action research. - Lack of quantitative data; causal analysis; objectivity, internal validity, reliability, or generalizability. - Sample not representative; lack of generalizability; generalizing from one organization. - Lack of replicability or reproducibility; not releasing transcripts. - Lack of control group or experimental protocols. An action research study is not an experiment. ## Suggested Readings Richard Baskerville and A. Trevor Wood-Harper. 1996. A critical perspective on action research as a method for information systems research.\" *Journal of information Technology* 11.3, 235–246. Peter Checkland and Sue Holwell. 1998. Action Research: Its Nature and Validity. *Systematic Practice and Action Research.* (Oct. 1997), 9–21. Yvonne Dittrich. 2002. Doing Empirical Research on Software Development: Finding a Path between Understanding, Intervention, and Method Development. In *Social thinking---Software practice*. 243–262 Yvonne Dittrich, Kari Rönkkö, Jeanette Eriksson, Christina Hansson and Olle Lindeberg. 2008. Cooperative method development. *Empirical Software Engineering.* 13, 3, 231-260. DOI: 10.1007/s10664-007-9057-1 Kurt Lewin. 1947. Frontiers in Group Dynamics. *Human Relations* 1, 2 (1947), 143--153. DOI: 10.1177/001872674700100201 Lars Mathiassen. 1998. Reflective systems development. *Scandinavian Journal of Information Systems* 10, 1 (1998), 67–118 Lars Mathiassen. 2002. Collaborative practice research. *Information, Technology & People.* 15,4 (2002), 321–345 Lars Mathiassen, Mike Chiasson, and Matt Germonprez. 2012. Style Composition in Action Research Publication. *MIS quarterly. JSTOR* 36, 2 (2012), 347-363 Miroslaw Staron. Action research in software engineering: Metrics' research perspective. *International Conference on Current Trends in Theory and Practice of Informatics.* (2019), 39-49 Maung K. Sein, Ola Henfridsson, Sandeep Purao, Matti Rossi and Rikard Lindgren. 2011. Action design research. *MIS quarterly*. (2011), 37-56. DOI: 10.2307/23043488 ## Exemplars Yvonne Dittrich, Kari Rönkkö, Jeanette Eriksson, Christina Hansson and Olle Lindeberg. 2008. Cooperative method development. *Empirical Software Engineering*. 13, 3 (Dec. 2007), 231-260. DOI: 10.1007/s10664-007-9057-1 Helle Damborg Frederiksen, Lars Mathiassen. 2005. Information-centric assessment of software metrics practices. IEEE Transactions on Engineering Eanagement. 52, 3 (2005), 350-362. DOI: 10.1109/TEM.2005.850737 Jakob Iversen and Lars Mathiassen. 2003. Cultivation and engineering of a software metrics program. Information Systems Journal. 13, 1 (2006), 3--19 Jakob Iversen. 1998. Problem diagnosis software process improvement. Larsen TJ, Levine L, DeGross JI (eds) Information systems: current issues and future changes. Martin Kalenda, Petr Hyna, Bruno Rossi. *Scaling agile in large organizations: Practices, challenges, and success factors*. Journal of Software: Evolution and Process. Wiley Online Library 30, 10 (Oct. 2018), 1954 pages. Miroslaw Ochodek, Regina Hebig, Wilhem Meding, Gert Frost, Miroslaw Staron. Recognizing lines of code violating company-specific coding guidelines using machine learning. *Empirical Software Engineering*. 25, 1 (Jan. 2020), 220-65. Kari Rönkkö, Brita Kilander, Mats Hellman, Yvonne Dittrich. 2004. Personas is not applicable: local remedies interpreted in a wider context. In *Proceedings of the eighth conference on Participatory design: Artful integration: interweaving media, materials and practices-Volume 1, Toronto, ON*, 112--120. Thatiany Lima De Sousa, Elaine Venson, Rejane Maria da Costa Figueired, Ricardo Ajax Kosloski, and Luiz Carlos Miyadaira Ribeiro. Using Scrum in Outsourced Government projects: An Action Research. 2016. In *2016 49th Hawaii International Conference on System Sciences (HICSS)*, January 5, 2016, 5447-5456. Hataichanok Unphon, Yvonne Dittrich. 2008. Organisation matters: how the organisation of software development influences the introduction of a product line architecture. In *Proc. IASTED Int. Conf. on Software Engineering*. 2008, 178-183. --- <footnote><sup>[1](#myfootnote1)</sup> i.e. who intervened and with which part of the organization? </footnote><br> <footnote><sup>[2](#myfootnote2)</sup> Action research projects are structured in interventions often described as action research cycles, which are often structured in distinct phases. It is a flexible methodology, where subsequent cycles are based on their predecessors.</footnote><br> <footnote><sup>[3](#myfootnote1)</sup> E.g. project financing, potential conflicts of interest, professional relationship leading to access.</footnote><br> <footnote><sup>[4](#myfootnote3)</sup> Can include quantitative evaluation in addition to qualitative evaluation.</footnote><br> <footnote><sup>[5](#myfootnote1)</sup> L. Harvey. 2015. Beyond member-checking: A dialogic approach to the research interview, International Journal of Research & Method in Education, 38, 1, 23–38.</footnote><br> </standard>
Markdown
UTF-8
929
2.625
3
[]
no_license
# Exercism A containerized coding practice environment for: [exercism.io](https://exercism.io/my/tracks) ## Build ``` docker build -t psollars/exercism . ``` Alternatively, you can provide this argument to the build to specify the exercism executable that you'd like to use. The artifact should be located in `./artifacts`. ``` --build-arg artifact=exercism.tar.gz ``` ## Run **On the Windows machine** ``` docker run --rm -it \ --env-file .env \ -v /mnt/f/Projects/psollars/exercism/files:/home/exercism \ -v /mnt/f/Projects/psollars/exercism/bash/.bash_history:/root/.bash_history \ psollars/exercism ``` **On the Mac** ``` docker run --rm -it \ --env-file .env \ -v ~/dev/exercism/files:/home/exercism \ -v ~/dev/exercism/bash/.bash_history:/root/.bash_history \ psollars/exercism ```
Python
UTF-8
2,031
2.5625
3
[ "MIT" ]
permissive
''' Developer: M. Kokshoorn Date: 22/02/2015 Set of Python fucntions/wrappers for "cec-client", developped for use on a Rasberry Pi to control/detect HDMI connected devices. More about cec-client ultilit and installation instructions at: https://github.com/Pulse-Eight/libcec ''' import subprocess def get_power_status(dev=0): cmd='echo "pow %i" | cec-client -d 1 -s "standby 0" RPI'%dev p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,shell=True) out, err = p.communicate() return 'on' in out.split(' ')[-1] def set_power_status(set_value,dev=0): if(set_value): cmd='echo "on %i" | cec-client -d 1 -s "standby 0" RPI'%dev p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,shell=True) out, err = p.communicate() else: cmd='echo "standby %i" | cec-client -d 1 -s "standby 0" RPI'%dev p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,shell=True) out, err = p.communicate() def set_active(): cmd='echo "as" | cec-client -d 1 -s "standby 0" RPI' p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,shell=True) out, err = p.communicate() def get_devices(): cmd='echo "scan" | cec-client -d 1 -s "standby 0" RPI' p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,shell=True) out, err = p.communicate() return out def get_ps4_power(): out= get_devices() out_lines=out.split('\n') try: index=out_lines.index('osd string: PlayStation 4') line=out_lines[index-4] num_1=line.index('#')+1 num_2=line.index(':') dev_num=line[num_1:num_2] return get_power_status(dev=int(dev_num)) except: print "No PS4 found!" def set_ps4_power(set_value): out= get_devices() out_lines=out.split('\n') try: index=out_lines.index('osd string: PlayStation 4') line=out_lines[index-4] num_1=line.index('#')+1 num_2=line.index(':') dev_num=line[num_1:num_2] print "Ps4 found on dev "+dev set_power_status(set_value,dev=int(dev_num)) except: print "No PS4 found!"
Ruby
UTF-8
1,482
2.703125
3
[]
no_license
$:.unshift File.join(File.dirname(__FILE__),'..','lib') require 'test/unit' require 'mincoverage/input_reader' class NewInputReaderTest < Test::Unit::TestCase def test_get_instances InputFaker.with_fake_input([2, '', 1, "-1 0", "-5 -3", "2 5", "0 0", '', 1, "-1 0", "0 1", "0 0"]) { instances = MinCoverage::InputReader.get_instances assert_equal(2, instances.size) assert_equal(1, instances[0].m) assert_equal(-1, instances[0].segment_list[0].left) assert_equal(1, instances[1].m) assert_equal(1, instances[1].segment_list[1].right) } end def test_instance_count_error InputFaker.with_fake_input([0, '', 1, "-1 0", "-5 -3", "2 5", "0 0", '', 1, "-1 0", "0 1", "0 0"]) { assert_raise(MinCoverage::InputReader::InputFormatError) { MinCoverage::InputReader.get_instances } } end def test_blank_line_error InputFaker.with_fake_input([2, 'xxx', 1, "-1 0", "-5 -3", "2 5", "0 0", '', 1, "-1 0", "0 1", "0 0"]) { assert_raise(MinCoverage::InputReader::InputFormatError) { MinCoverage::InputReader.get_instances } } end end class InputFaker def initialize(strings) @strings = strings end def gets next_string = @strings.shift # Uncomment the following line if you'd like to see the faked $stdin#gets #p "(DEBUG) Faking #gets with: #{next_string}" next_string end def self.with_fake_input(strings) $stdin = new(strings) yield ensure $stdin = STDIN end end
C++
UTF-8
4,357
2.859375
3
[]
no_license
#include <cstdio> #include <cmath> #include <limits>//This library is used to get the double max value. #include "point.h" #include "rays.h" #include "world.h" #define F_INFINITY std::numeric_limits<double>::infinity() inline double square( double num ){ return num*num; } inline double dist3DSq( Point p1, Point p2 ){//returns the square of the distance between 2 3D points return square(p2.x-p1.x) + square(p2.y-p1.y) + square(p2.z-p1.z); } inline double dist3D( Point p1, Point p2 ){ return sqrt( dist3DSq( p1, p2 ) ); } Ray::Ray( Point setP1, Point setP2 ){ p1 = setP1; p2 = setP2; //length = dist3D(x1, y1, z1, x2, y2, z2); } bool Ray::pointsAt( Point point ){//Make sure point is in fromt of ray (on each axis, from ray p1 to ray p2 is the same direction as ray p1 to point) return ( ( p2.x >= p1.x ) == ( point.x >= p1.x ) ) && ( ( p2.y >= p1.y ) == ( point.y >= p1.y ) ) && ( ( p2.z >= p1.z ) == ( point.z >= p1.z ) ) && dist3DSq( p1, point ) > INTERSECT_ERR; } bool Ray::inRange( Point point ){ return ( ( point.x >= p1.x ) == ( point.x <= p2.x ) ) && ( ( point.y >= p1.y ) == ( point.y <= p2.y ) ) && ( ( point.z >= p1.z ) == ( point.z <= p2.z ) ) && dist3DSq( p2, point ) > INTERSECT_ERR; } double Ray::getLength(){ return dist3D( p1, p2 ); } Ray& Ray::normalize(){ double length = dist3D( p1, p2 ); p2.x = ( p2.x - p1.x ) / length + p1.x; p2.y = ( p2.y - p1.y ) / length + p1.y; p2.x = ( p2.z - p1.z ) / length + p1.z; return *this; } double Ray::cosAngleToUVec( Point normalRay ){ return dot( ( p2 - p1 ) /= getLength(), normalRay ); } double cosAngleBetween( Ray ray1, Ray ray2 ){ return dot( ( ray1.p2 - ray1.p1 ) / ray1.getLength(), ( ray2.p2 - ray2.p1 ) / ray2.getLength() ); } CRay::CRay( Ray setRay ){ ray = setRay; //length = dist3D(x1, y1, z1, x2, y2, z2); color.r = 0; color.g = 0; color.b = 0; colorMixLeft = 65535; currentIOR = 1; nextIOR = 1; hitPos.x = F_INFINITY; hitPos.y = F_INFINITY; hitPos.z = F_INFINITY; hitDist = F_INFINITY; escape = true; bounceCount = 0; } bool CRay::intersect( Object* object, Color toSet, Point hit, double dist, Point objNormalVec ){ if( dist <= hitDist ){ objLastHit = object; normalVec = objNormalVec; hitDist = dist; hitPos = hit; castColor = toSet; escape = false; return true; } return false; } /*void CRay::addLight( FloatColor addLightColor ){ lightColor.r += addLightColor.r; lightColor.g += addLightColor.g; lightColor.b += addLightColor.b; }*/ /*void CRay::castBackground( Color backgroundColor ){ if( escape ){//hitDist >= F_INFINITY objLastHit = nullptr; normalVec.x = 0; normalVec.y = 0; normalVec.z = 0; setCastColor = backgroundColor; setCastColor.a = 65535; } }*/ void CRay::addColor( Color addColor, uint16_t addColorAlpha, FloatColor addLightColor ){ //if( addLightColor.r < 0 ){ addLightColor.r = 0; }//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<INEFFICIENT!! //if( addLightColor.g < 0 ){ addLightColor.g = 0; } //if( addLightColor.b < 0 ){ addLightColor.b = 0; } double temp = (uint64_t)addColor.r * addColorAlpha * colorMixLeft / 4294836225 * addLightColor.r + color.r; if( temp >= 65535 ){ color.r = 65535; } else{ color.r = (uint16_t)temp; } temp = (uint64_t)addColor.g * addColorAlpha * colorMixLeft / 4294836225 * addLightColor.g + color.g; if( temp >= 65535 ){ color.g = 65535; } else{ color.g = (uint16_t)temp; } temp = (uint64_t)addColor.b * addColorAlpha * colorMixLeft / 4294836225 * addLightColor.b + color.b; if( temp >= 65535 ){ color.b = 65535; } else{ color.b = (uint16_t)temp; } //color.r += (uint16_t)( (uint64_t)addColor.r * addColor.a * colorMixLeft / 4294836225 * lightColor.r ); //color.g += (uint16_t)( (uint64_t)addColor.g * addColor.a * colorMixLeft / 4294836225 * lightColor.g ); //color.b += (uint16_t)( (uint64_t)addColor.b * addColor.a * colorMixLeft / 4294836225 * lightColor.b ); colorMixLeft = (uint32_t)colorMixLeft * (65535 - addColorAlpha) / 65535; } //void CRay::finishCast( bool doSetPos, bool doSetColor ){ // if( doSetPos ){ // ray.p2 = hitPos; // } // if( doSetColor ){ // addColor( setCastColor, setCastColorAlpha, lightColor ); // } // // //if( hitDist < F_INFINITY ){ escape = false; } //}
Java
UTF-8
1,164
2.375
2
[]
no_license
package it.portalECI.DTO; public class RispostaFormulaQuestionarioDTO extends RispostaQuestionario { private String valore1; private String valore2; private String operatore; private String risultato; public RispostaFormulaQuestionarioDTO() { } public String getValore1() { return valore1; } public void setValore1(String valore1) { this.valore1 = valore1; } public String getValore2() { return valore2; } public void setValore2(String valore2) { this.valore2 = valore2; } public String getOperatore() { return operatore; } public String getSimboloOperatore() { switch (operatore) { case "Somma": return "+"; case "Sottrazione": return "-"; case "Moltiplicazione": return "x"; case "Divisione": return ":"; case "Potenza": return "^"; default: return ""; } } public void setOperatore(String operatore) { this.operatore = operatore; } public String getRisultato() { return risultato; } public void setRisultato(String risultato) { this.risultato = risultato; } }
Java
UTF-8
3,032
2.453125
2
[]
no_license
package com.sy.filter; import com.auth0.jwt.interfaces.DecodedJWT; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; import com.netflix.zuul.exception.ZuulException; import com.sy.utils.JWTUtils; import javax.servlet.http.HttpServletRequest; public class PreFilter extends ZuulFilter { @Override public String filterType() { // 过滤器类型,可选值有 pre、route、post、error。 return "pre"; } @Override public int filterOrder() { // 过滤器的执行顺序,数值越小,优先级越高。 return 1; } @Override public boolean shouldFilter() { // 是否执行该过滤器,true 为执行,false 为不执行,这个也可以利用配置中心来实现,达到动态的开启和关闭过滤器。 // RequestContext.getCurrentContext();获取请求的上下文信息对象 // 再使用.getRequest()获取 HttpServletRequest 对象 // 再通过.getRequestURI() 方法可获取到请求路径 RequestContext requestContext = RequestContext.getCurrentContext(); HttpServletRequest request = requestContext.getRequest(); System.out.println("============================================"+request.getRequestURI()); if("/client/Accountclient/userAccount".equals(request.getRequestURI())) { return false; } else if ("/client/Accountclient/adminAccount".equals(request.getRequestURI())) { return false; }else if ("/client/Userclient/save".equals(request.getRequestURI())) { return false; } else { return true; } } @Override public Object run() throws ZuulException { // RequestContext.getCurrentContext();获取请求的上下文信息对象 // 再使用.getRequest()获取 HttpServletRequest 对象 // 再通过.getRequestURI() 方法可获取到请求路径 RequestContext requestContext = RequestContext.getCurrentContext(); HttpServletRequest request = requestContext.getRequest(); //获取请求头中的token对象 String token = request.getHeader("Authorization"); System.out.println("=========================================="+token); if(JWTUtils.verify(token)==null) { // 如果未通过验证,则终止该请求进行路由,并设置返回状态码为401 requestContext.setSendZuulResponse(false); requestContext.setResponseStatusCode(401); } else { DecodedJWT decodedJWT = JWTUtils.verify(token); System.out.println("============================"+decodedJWT.getExpiresAt()); // 如果通过验证,则对该请求进行路由,并设置返回状态码为200 requestContext.setSendZuulResponse(true); requestContext.setResponseStatusCode(200); } return null; } }
C#
UTF-8
4,407
2.515625
3
[]
no_license
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Web.UI; using Spinit.Extensions; using Spinit.Wpc.Synologen.OPQ.Business; using Spinit.Wpc.Synologen.OPQ.Core; namespace Spinit.Wpc.Synologen.OPQ.Presentation { public class OpqUtility { /// <summary> /// Checks a filepath for allowed extensions /// </summary> /// <param name="filePath">The current filepath</param> /// <returns>true/false if the extension is allowed or not</returns> static public bool IsAllowedExtension(string filePath) { if (filePath.IsNullOrEmpty()) return false; if (Configuration.UploadAllowedExtensions.IsNullOrEmpty()) return false; if (!Path.HasExtension(filePath)) return false; string[] allowedExtensions = Configuration.UploadAllowedExtensions.Split(','); foreach (var extension in allowedExtensions) { if (Path.GetExtension(filePath).ToLower().Equals(string.Concat('.',extension.ToLower()))) { return true; } } return false; } /// <summary> /// Encodes a string to avoid forbidden chars in url /// </summary> /// <param name="value"></param> /// <returns></returns> static public string EncodeStringToUrl(string value) { value = value.ToLower(); value = value.Replace('å', 'a'); value = value.Replace('ä', 'a'); value = value.Replace('ö', 'o'); value = value.Replace(' ', '-'); value = Regex.Replace(value, "[^a-z0-9-]", ""); value = Regex.Replace(value, "[-]+", "-"); return value; } public static string GetSessionValue(string sessionName, string defaultValue) { try { return HttpContext.Current.Session[sessionName].ToString(); } catch { return defaultValue; } } public static int GetSessionValue(string sessionName, int defaultValue) { try { int returnValue; return Int32.TryParse(HttpContext.Current.Session[sessionName].ToString(), out returnValue) ? returnValue : defaultValue; } catch { return defaultValue; } } public static bool GetSessionValue(string sessionName, bool defaultValue) { try { return (bool)(HttpContext.Current.Session[sessionName]); } catch { return defaultValue; } } public static DateTime GetSessionValue(string sessionName, DateTime defaultValue) { try { return (DateTime)(HttpContext.Current.Session[sessionName]); } catch { return defaultValue; } } public static void SetSessionValue(string sessionName, object value) { HttpContext.Current.Session[sessionName] = value; } public static object GetSessionValue(string sessionName) { try { object list = HttpContext.Current.Session[sessionName]; return list ?? new object(); } catch { return new object(); } } public static List<int> GetSessionIntList(string sessionName) { try { var list = (List<int>)HttpContext.Current.Session[sessionName]; return list ?? new List<int>(); } catch { return new List<int>(); } } /// <summary> /// Finds a Control recursively. /// Note finds the first match and exists /// </summary> /// <param name="root">The container to start looking</param> /// <param name="id">Id to find</param> /// <returns></returns> public static Control FindControlRecursive(Control root, string id) { if (root.ID == id) return root; foreach (Control ctl in root.Controls) { Control foundCtl = FindControlRecursive(ctl, id); if (foundCtl != null) return foundCtl; } return null; } /// <summary> /// Builds a path from root to current node separated with delimiter /// </summary> /// <param name="nodeId">Id of current node</param> /// <param name="delimiter">The delimiter to use</param> /// <returns></returns> public static string GetNodePathFromId(int nodeId, string delimiter) { var path = new StringBuilder(); var bNode = new BNode(SessionContext.CurrentOpq); var node = bNode.GetNode(nodeId, false); path = path.Insert(0, node.Name); while (node.Parent != null) { node = bNode.GetNode((int) node.Parent, false); path = path.Insert(0, delimiter); path = path.Insert(0, node.Name); } return path.ToString(); } } }
C++
UTF-8
1,524
2.765625
3
[ "MIT" ]
permissive
#ifndef __BITCRAF_STATEMACHINE_TOKEN_H__ #define __BITCRAF_STATEMACHINE_TOKEN_H__ namespace Bitcraft { namespace StateMachine { /// <summary> /// Represents a uniquely identifiable entity. /// </summary> class Token { friend class StateBase; private: unsigned long long _id; const wchar_t* _name; static unsigned long long _globalId; private: void Initialization(const wchar_t* name); protected: /// <summary> /// Initializes the Token instance. /// </summary> Token(); /// <summary> /// Initializes the Token instance. /// </summary> /// <param name="name">Name of the token.</param> Token(const wchar_t* name); public: /// <summary> /// Provides a string representation of the token. /// </summary> /// <returns>Returns the string representation of the token.</returns> const wchar_t* ToString(); /// <summary> /// Checks whether the current token is the same as another one. /// </summary> /// <param name="other">The other token to check equality upon.</param> /// <returns>Returns true if both tokens are the same, false otherwise.</returns> bool Equals(Token* other); }; } } #endif // __BITCRAF_STATEMACHINE_TOKEN_H__
Markdown
UTF-8
2,488
2.828125
3
[]
no_license
**Your Business Unit** page allows your customers to select company user account they are logged in. To open **Your Business Unit** page, go to Customer Account → **Your Business Unit**. ## Graphic User Interface @(Info)()(Hover your mouse over the numbers to view their description.) <div class="mapster-container"> <img class="mapster-image" src="https://spryker.s3.eu-central-1.amazonaws.com/docs/User+Guides/Shop+User+Guides/Business+on+Behalf/business-on-behalf-ui.png" usemap="#Map" data-mapster-config="" /> <map class="mapster-map" name="Map" id="Map"> <area alt="" id="id1" href="#" shape="rect" coords="247,130,286,170" data-static-state="false" data-key="id1" data-tool-tip="A menu for managing customer information, viewing orders." /> <area alt="" id="id2" href="#" shape="rect" coords="365,259,406,300" data-static-state="false" data-key="id2" data-tool-tip="A drop-down to select the company user account you are operating in. The accounts are displayed in the format [COMPANY NAME / BUSINESS UNIT NAME]. No Business Unit value in the drop-down means that user isn't yet logged into any company accounts." /> <area alt="" id="id3" href="#" shape="rect" coords="360,352,401,393" data-static-state="false" data-key="id3" data-tool-tip="A checkbox to make company user account selection as a default one." /> <area alt="" id="id4" href="#" shape="rect" coords="358,427,398,469" data-static-state="false" data-key="id4" data-tool-tip="Saves changes." /> </map> </div> ## Selecting Another Company User to Log in on Behalf To log in to a different business unit, do the following: 1. On the *Your Business Unit* page select the required company account from the drop-down: ![Select another company user](https://spryker.s3.eu-central-1.amazonaws.com/docs/User+Guides/Shop+User+Guides/Business+on+Behalf/select-another-company-user.png){height="" width=""} 2. (Optionally) Check **Remember Choice** option if you would like to make this account your default one on login. 3. Click **Submit** to save the changes. After a successful change, you will be able to see [COMPANY NAME / BUSINESS UNIT NAME] instead of Your Business Unit menu item: ![Business unit](https://spryker.s3.eu-central-1.amazonaws.com/docs/User+Guides/Shop+User+Guides/Business+on+Behalf/business-unit-changed.png){height="" width=""} <!-- Last review date: Mar 06, 2019 by Oksana Karasyova -->
Markdown
UTF-8
877
3.890625
4
[]
no_license
[1108.defanging-an-ip-address](https://leetcode.com/problems/defanging-an-ip-address/) Given a valid (IPv4) IP `address`, return a defanged version of that IP address. A _defanged IP address_ replaces every period `"."` with `"[.]"`. **Example 1:** **Input:** address = "1.1.1.1" **Output:** "1\[.\]1\[.\]1\[.\]1" **Example 2:** **Input:** address = "255.100.50.0" **Output:** "255\[.\]100\[.\]50\[.\]0" **Constraints:** * The given `address` is a valid IPv4 address. **Solution:** ```cpp class Solution { public: string defangIPaddr(string address) { string ans; for(auto c : address) { if( c == '.') { ans.push_back('['); ans.push_back(c); ans.push_back(']'); }else ans.push_back(c); } return ans; } }; ```
Go
UTF-8
4,271
2.828125
3
[]
no_license
package fyne import ( "context" "fyne.io/fyne" "fyne.io/fyne/app" "fyne.io/fyne/layout" "fyne.io/fyne/widget" godcrApp "github.com/raedahgroup/godcr/app" "github.com/raedahgroup/godcr/fyne/log" "github.com/raedahgroup/godcr/fyne/pages" "github.com/raedahgroup/godcr/fyne/widgets" ) const ( menuSectionWidth = 200 menuSectionPageSectionSeparation = 20 ) type fyneApp struct { fyne.App ctx context.Context walletMiddleware godcrApp.WalletMiddleware mainWindow fyne.Window mainWindowContent fyne.CanvasObject menuSectionOnLeft *fyne.Container menuButtons []*widget.Button pageSectionOnRight *widget.Box pageTitle *widget.Label pageContent fyne.CanvasObject } func LaunchApp(ctx context.Context, walletMiddleware godcrApp.WalletMiddleware) error { this := &fyneApp{ App: app.New(), ctx: ctx, walletMiddleware: walletMiddleware, } this.prepareNavSectionOnLeft() this.preparePageSectionOnRight() // create main window content holder and add menu and page sections, separated with space this.mainWindowContent = fyne.NewContainerWithLayout( layout.NewHBoxLayout(), this.menuSectionOnLeft, widgets.NewHSpacer(menuSectionPageSectionSeparation/2), this.pageSectionOnRight, ) this.mainWindow = this.NewWindow(godcrApp.DisplayName) // todo: main.go now requires that the user select a wallet or create one before launching interfaces, so need for this check // if there's no wallet, show create wallet window and trigger the sync operation after a wallet is created //walletExists, err := walletMiddleware.WalletExists() //if err != nil { // return err //} //if !walletExists { // this.showCreateWalletWindow() //} else { // // begin sync, main window content will be displayed after sync completes // this.showSyncWindow() //} // begin sync, main window content will be displayed after sync completes this.showSyncWindow() this.listenForWindowResizeEvents() // fyneApp.Run() blocks until the app is exited, before returning nil error to the caller of this LaunchApp function this.Run() return nil } func (app *fyneApp) prepareNavSectionOnLeft() { menuGroup := widget.NewGroup("Menu") for _, page := range pages.NavPages() { menuButton := widget.NewButton(page.Title, app.displayPageFunc(page)) menuGroup.Append(menuButton) app.menuButtons = append(app.menuButtons, menuButton) } // add exit menu option menuGroup.Append(widget.NewButton("Exit", app.Quit)) // layout menu using FixedGridLayout to ensure that the provided `menuSectionWidth` is used in rendering the menu group menuSectionSize := fyne.NewSize(menuSectionWidth, menuGroup.MinSize().Height) app.menuSectionOnLeft = fyne.NewContainerWithLayout(layout.NewFixedGridLayout(menuSectionSize), menuGroup) } func (app *fyneApp) preparePageSectionOnRight() { // page section contents app.pageTitle = widget.NewLabelWithStyle("", fyne.TextAlignLeading, fyne.TextStyle{Italic: true, Bold: true}) // put page title and scrollable content area in v-box app.pageSectionOnRight = widget.NewVBox(app.pageTitle) } // displayPageFunc returns the function that will be triggered to display a page func (app *fyneApp) displayPageFunc(page *pages.Page) func() { return func() { app.pageTitle.SetText(page.Title) app.highlightCurrentPageMenuButton(page.Title) if simplePageLoader, ok := page.PageLoader.(pages.SimplePageLoader); ok { simplePageLoader.Load(app.updatePageFunc) } else if walletPageLoader, ok := page.PageLoader.(pages.WalletPageLoader); ok { walletPageLoader.Load(app.ctx, app.walletMiddleware, app.updatePageFunc) } else { log.PrintError("Page not properly set up: ", page.Title) } } } func (app *fyneApp) highlightCurrentPageMenuButton(currentPage string) { for _, menuButton := range app.menuButtons { if menuButton.Text == currentPage { menuButton.Style = widget.PrimaryButton } else { menuButton.Style = widget.DefaultButton } } // refresh menu section so the changes made in this function reflects app.mainWindow.Canvas().Refresh(app.menuSectionOnLeft) } func (app *fyneApp) updatePageFunc(pageContent fyne.CanvasObject) { app.pageContent = pageContent app.resizeScrollableContainer() }
Ruby
UTF-8
3,443
3.109375
3
[]
no_license
require "json" require "csv" # csv_file_path = "eva_csv/ase.csv" def eva_return(hash) return "なし" if hash["evaluation_method"].nil? return "なし" if hash["evaluation_method"].empty? hash["evaluation_method"] end def insert_element(hash, term, i, j) # i = 通年かどうかで決まる 基本的に0のみ # j = その期で授業コマ文だけ回すため campus = hash["campus"] != "" ? hash["campus"] : "なし" day = !hash["metadata"][0].empty? ? hash["metadata"][i][j]["day"] : "なし" period = !hash["metadata"][0].empty? ? hash["metadata"][i][j]["period"] : "なし" classroom = !hash["metadata"][0].empty? ? hash["metadata"][i][j]["classroom"] : "なし" evaluation_method = eva_return(hash) [].push( hash["year"] , hash["place"] , hash["name"] , hash["professor"] , hash["time"] , hash["category"] , hash["target_grade"] , hash["credit"] , hash["classroom"] , campus, hash["language"] , hash["field_large"] , hash["field_middle"] , hash["field_small"] , hash["level"] , hash["form"] , hash["open_course"] , hash["full_od"] , term , day , period , classroom, hash["textbook"] || "なし", evaluation_method ) end def json_format(csv , json_file_path, count = 0) JSON.parse(File.open(json_file_path).read).each do |hash| #open json to parse count = count + 1 if hash["metadata"][0].empty? # たまにある授業時間割がない場合 csv << insert_element(hash, hash["term"], 0, 0) elsif hash["term"].include?("通年") k = 0 l = 0 hash["metadata"][0].map do csv << insert_element(hash, "春学期", 0, k) puts "通年0 #{insert_element(hash, "春学期", 0, k)}" k = k + 1 end hash["metadata"][1].map do csv << insert_element(hash, "秋学期", 1, l) puts "通年1 #{insert_element(hash, "秋学期", 1, l)}" l = l + 1 end elsif hash["metadata"][0].length > 1 # 通年以外(春か秋かのみ) かつ 2コマ以上 の場合 ※ただし、微積などの場合は通年であり かつ 半期ごとに2コマ以上あるのでその場合は、注意する。 next if hash["term"].include?("通年") j = 0 hash["metadata"][0].map do puts "通年以外(春か秋かのみ) かつ 2コマ以上 の場合" csv << insert_element(hash, hash["term"], 0, j) j = j + 1 end else next if hash["term"].include?("通年") || hash["metadata"][0].length > 1 csv << insert_element(hash, hash["term"], 0, 0) end puts "#{count}\n" end end csv_dir = Dir::entries("csv") csv_dir.shift(2) puts "csv_dir : #{csv_dir}" # ["cse.csv", "sils.csv", "ase.csv", "hum.csv", "fse.csv", "cms.csv", "sps.csv", "hss.csv", "sss.csv", "edu.csv", "pse.csv"] csv_dir.each do |csv_name| csv_file_path = "eva_csv/".concat(csv_name) dir_length = Dir::entries("json/".concat(csv_name.sub(/.csv/,""))).length - 2 json_dir = Dir::entries("json/".concat(csv_name.sub(/.csv/,""))) json_dir.shift(2) CSV.open(csv_file_path, "w") do |csv| #open new file for write json_dir.each do |value| json_format(csv, "json/#{csv_name.sub(/.csv/,"")}/#{value}") end end end
Java
UTF-8
1,676
1.84375
2
[]
no_license
/******************************************************************************* * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3, 29 June 2007; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.gnu.org/licenses/lgpl-3.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package no.sintef.bvr.tool.primitive.impl; import org.eclipse.emf.ecore.EObject; import no.sintef.bvr.tool.primitive.VisitableSymbolEObject; import no.sintef.bvr.tool.primitive.SymbolTableEObject; import no.sintef.bvr.tool.visitor.NodeVisitor; import bvr.CompoundNode; import bvr.NamedElement; public class SymbolCompoundNode extends VisitableSymbolEObject { CompoundNode node; SymbolTableCompoundNode table; public SymbolCompoundNode(CompoundNode element) { node = element; } @Override public NamedElement getSymbol() { return (NamedElement) node; } @Override public void setSymbolTable(SymbolTableEObject stable) { table = (SymbolTableCompoundNode) stable; } @Override public SymbolTableEObject getSymbolTable() { return table; } @Override public void setSymbol(EObject element) { node = (CompoundNode) element; } @Override public void accept(NodeVisitor visitor) { visitor.visitNamedElement(this); } }
C++
UTF-8
10,155
3.4375
3
[]
no_license
#include <iostream> // подключение библиотек ввода-вывода #include <ctime> // подключение библиотек для работы с текущим временем (необходимы для генерации случайных чисел) #include <string> // подключение библиотек для работы со строками #include <windows.h> // подключение библиотек для использования кириллицы в консоли using namespace std; // использование пространства имен std #define LIMIT 10000 // верхняя граница генерации числа /* Функция возведения числа n в степень p по модулю mod * https://ru.wikipedia.org/wiki/Алгоритмы_быстрого_возведения_в_степень_по_модулю * Модификация метода повторяющихся возведения в квадрат и умножения */ int modulo(int n, int p, int mod) { int result = 1; // результат вычисления for (; p; p >>= 1) // в цикле p = p / 2 { // если p нечетное, то n перемножается с результатом вычисления функции if (p & 1) result = (1LL * result * n) % mod; // теперь p четное: n = (1LL * n * n) % mod; } return result; } /* Тест Миллера-Рабина для проверки простоты числа n * https://ru.wikipedia.org/wiki/Тест_Миллера_—_Рабина */ bool millerTest(int n, int d) { // выбрать случайное число в диапазоне [2..n-2], n > 4 int a = 2 + rand() % (n - 4); // вычислить a^d % n int x = modulo(a, d, n); if (x == 1 || x == n - 1) return true; // продолжать возводить в квадрат x, пока не выполнится одно из следующих условий: // 1) d достигнет n-1 // 2) (x^2) % n не 1 // 3) (x^2) % n не n-1 while (d != n - 1) { x = (x * x) % n; d *= 2; if (x == 1) return false; if (x == n - 1) return true; } // вернуть "составное" return false; } /* Функция проверки простоты числа n за k раундов * Возвращает false, если n составное; возвращает true, если n возможно простое * Переменная k - входной параметр, который влияет на точность проверки. */ bool isPrime(int n, int k) { if (n <= 1 || n == 4) return false; if (n <= 3) return true; // Найти r такое, что n = 2^d * r + 1 для некоторого r >= 1 int d = n - 1; while (d % 2 == 0) d /= 2; // Проверить число вероятностным тестом простоты k раз for (int i = 0; i < k; i++) if (!millerTest(n, d)) return false; return true; } /* Функция генерации простого числа */ int generate_prime() { int generated = rand() % LIMIT; // сгенерировать число while (!isPrime(generated, log(generated))) // генерировать еще, пока оно не окажется простым generated = rand() % LIMIT; return generated; // вернуть простое число } /* Алгоритм Евклида (https://ru.wikipedia.org/wiki/Алгоритм_Евклида) * Алгоритм для нахождения наибольшего общего делителя двух целых чисел. * Используется для проверки чисел на взаимную простоту */ int gcd(int a, int b) { while (b) { int r = a % b; a = b; b = r; } return a; } /* Функция генерации числа, взаимно простого с числом n */ int generate_coprime(int n) { int generated = rand() % LIMIT; // сгенерировать число while (gcd(n, generated) != 1) // генерировать еще, пока оно не окажется взаимно простым с n generated = rand() % LIMIT; return generated; // вернуть взаимно простое с n число } /* Расширенный алгоритм Евклида (см. там же, где и обычный алгоритм) * или (http://e-maxx.ru/algo/export_extended_euclid_algorithm) * Возвращает пару y, x: a * x + b * y = gcd(a, b) */ pair<int, int> euclid_extended(int a, int b) { if (!b) // если b = 0, то x = 0, y = 1 - база рекурсии return { 1, 0 }; // иначе рекурсивный пересчет коэффициентов auto result = euclid_extended(b, a % b); return { result.second, result.first - (a / b) * result.second }; } /* Модулярная инверсия. * Ищет такое x, что a * x ≡ 1 (mod m) * 1) Чтобы найти x, необходимо положить b = m в формуле расширенного алгоритма Евклида ax + by = gcd(a, b). * Поскольку известно, что a и m взаимно просты, можно положить значение gcd как 1: ax + my = 1 * 2) Если взять по модулю m с обеих сторон, то получится ax + my ≡ 1 (mod m) * 3) Можно удалить второй член слева, так как my (mod m) всегда будет равно нулю для целого числа y: ax ≡ 1 (mod m) * Таким образом, используя расширенный алгоритм Евклида, можно найти x */ int modular_inverse(int a, int m) { int x = euclid_extended(a, m).first; // m добавляется в случае отрицательного x: while (x < 0) x += m; return x; } typedef pair<int, int> PublicKey; // пара (e, n) - открытый ключ typedef pair<int, int> PrivateKey; // пара (d, n) - закрытый ключ /* Структура Ключи – открытый и закрытый */ struct Keys { PublicKey public_key; PrivateKey private_key; }; /* Функция генерации ключей */ Keys generate_keys() { Keys result; // возвращаемое значение int p, q; // два случайных простых числа // Сгенерировать их: p = generate_prime(); q = generate_prime(); // Вычислить модуль - произведение сгенерированных простых чисел: int n = p * q; // Найти phi - значение функции Эйлера от числа n: int phi = (p - 1) * (q - 1); // Выбрать число e, взаимно простое с числом phi: int e = generate_coprime(phi); // Выбрать пару (e, n) в качестве открытого ключа: result.public_key = make_pair(e, n); // Найти d - мультипликативно обратное к числу e мо модулю phi: int d = modular_inverse(e, phi); // Выбрать пару (d, n) в качестве закрытого ключа: result.private_key = make_pair(d, n); return result; // вернуть результат } /* Функция шифрования */ int encrypt(PublicKey key, int value) { return modulo(value, key.first, key.second); } /* Функция дешифрования */ int decrypt(PrivateKey key, int value) { return modulo(value, key.first, key.second); } int main() { srand(time(NULL)); // инициализация генератора случайных чисел // Установка ввода-вывода кириллицы в консоли: SetConsoleCP(1251); SetConsoleOutputCP(1251); Keys keys = generate_keys(); // генерация ключей keys // Вывод сгенерированных ключей: cout << "Сгенерированный открытый ключ: (" << keys.public_key.first << ", " << keys.public_key.second << ")" << endl;; cout << "Сгенерированный закрытый ключ: (" << keys.private_key.first << ", " << keys.private_key.second << ")" << endl; // Чтение строки с пробелами и нахождение ее длины: string s; cout << endl << "Введите строку: "; getline(cin, s); int len = s.length(); // Вывод исходной строки и кодов ее символов: cout << "Исходная строка: " << s << endl; cout << endl << "Коды символов исходной строки: " << endl; for (int i = 0; i < len; i++) cout << (int)s[i] << " "; cout << endl; // Объявление двух целочисленных массивов для хранения кодов шифртекста и расшифрованного текста и заполнение их нулями: int enc[100] = { 0 }; int dec[100] = { 0 }; // Посимвольное шифрование строки: for (int i = 0; i < len; i++) enc[i] = encrypt(keys.public_key, s[i]); // Вывод кодов символов шифртекста: cout << endl << "Коды символов шифртекста: " << endl; for (int i = 0; i < len; i++) cout << enc[i] << " "; cout << endl; // Посимвольное дешифрование строки: for (int i = 0; i < len; i++) dec[i] = decrypt(keys.private_key, enc[i]); // Вывод кодов символов дешифрованного текста: cout << endl << "Дешифрованные коды: " << endl; for (int i = 0; i < len; i++) cout << dec[i] << " "; cout << endl; // Вывод символов дешифрованной строки: cout << endl << "Дешифрованная строка: " << endl; for (int i = 0; i < len; i++) cout << (char)dec[i]; cout << endl << endl; system("pause"); return 0; }
Java
UTF-8
8,077
1.867188
2
[]
no_license
package com.yt.fragments; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.ConnectivityManager; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.EditText; import android.widget.GridView; import android.widget.LinearLayout; import android.widget.TextView; import com.yt.activities.YTSDKUtils; import com.yt.activities.adapters.SearchListAdapter; import com.yt.common.constants.Constants; import com.yt.common.utils.ConnectionChecker; import com.yt.common.utils.GData; import com.yt.common.utils.MyLog; import com.yt.common.utils.Utils; import com.yt.item.VideoItem; import com.ytsdk.testapp.stp.R; public class SearchListFragment extends Fragment { private static final String KEY_CONTENT = "ItemListFragment:Items"; private static final String KEY_FILE_NAME = "ItemListFragment:fileName"; private final String SEARCH_URL_1 = "https://www.googleapis.com/youtube/v3/search?order=viewCount&q="; private final String SEARCH_URL_2 = "&type=video&maxResults=20&part=snippet&fields=items(id/videoId,snippet/title,snippet/thumbnails)&key=" + Constants.YOUTUBE_API_KEY; private GridView mGridView; LinearLayout progressBar; SearchListAdapter mListAdapter; ArrayList<VideoItem> item = new ArrayList<VideoItem>(); private static SearchListFragment thisPointer; private int position; private EditText mEditText; private LinearLayout mSearchButton; public static SearchListFragment getInstance(int position) { // if (gridFragent == null) { thisPointer = new SearchListFragment(); // } Bundle args = new Bundle(); args.putInt("position", position); thisPointer.setArguments(args); return thisPointer; } @Override public void onCreate(Bundle savedInstanceState) { restoreData(savedInstanceState); Bundle bundle = this.getArguments(); if (bundle != null) { this.position = bundle.getInt("position"); } super.onCreate(savedInstanceState); Utils.loadFullScreenAd(getActivity()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.layout_search_video, container, false); progressBar = (LinearLayout) view.findViewById(R.id.loadingPanel); mGridView = (GridView) view.findViewById(R.id.list); mEditText = (EditText) view.findViewById(R.id.edit_seach); mEditText .setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEARCH) { performSearch(); return true; } return false; } }); mSearchButton = (LinearLayout) view .findViewById(R.id.searchButtonLayout); mSearchButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { performSearch(); } }); return view; } private void performSearch() { Utils.showFullScreenAd(getActivity()); String searchText = mEditText.getText().toString(); if (searchText == null || searchText.length() == 0) { return; } closeKeyboard(); if (!isConnectivityPresent()) { return; } Pattern pattern = Pattern.compile("\\s+"); Matcher matcher = pattern.matcher(searchText); String decodedSearchStr = matcher.replaceAll("%20"); String searchUrl = SEARCH_URL_1 + decodedSearchStr + SEARCH_URL_2; new GetVideoListFromYouTube().execute(searchUrl); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public void onPause() { super.onPause(); closeKeyboard(); } private void closeKeyboard() { if (SearchListFragment.this == null) { return; } try { InputMethodManager imm = (InputMethodManager) getActivity() .getSystemService(getActivity().INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0); } catch (Exception e) { // TODO: handle exception } } public void onListItemClick(GridView g, View v, int position, long id) { YTSDKUtils.getYTSDK().showCustomDialog(getActivity(), true, false); YTSDKUtils.getYTSDK().download(getActivity(), item.get(position).getVideoId()); } private void restoreData(Bundle savedInstanceState) { if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) { item = (ArrayList<VideoItem>) savedInstanceState.get(KEY_CONTENT); position = savedInstanceState.getInt(KEY_FILE_NAME); } } private class GetVideoListFromYouTube extends AsyncTask<String, Void, ArrayList<VideoItem>> { @Override protected void onPreExecute() { super.onPreExecute(); progressBar.setVisibility(View.VISIBLE); mGridView.setVisibility(View.GONE); } @Override protected ArrayList<VideoItem> doInBackground(String... params) { ArrayList<VideoItem> videoList = null; String searchUrl = params[0]; if (searchUrl != null && searchUrl.length() > 0) { videoList = GData.getGData(searchUrl); } return videoList; } @Override protected void onPostExecute(ArrayList<VideoItem> result) { super.onPostExecute(result); // Cancel the Loading Dialog progressBar.setVisibility(View.GONE); addVideoList(result); } } private void addVideoList(ArrayList<VideoItem> videoList) { if (videoList == null || videoList.size() == 0) { if (!progressBar.isShown()) { } return; } // mErrorTextView.setVisibility(View.GONE); item = videoList; mListAdapter = new SearchListAdapter(getActivity(), item, position, R.layout.grid_item); if (mGridView != null) { mGridView.setAdapter(mListAdapter); } mGridView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView parent, View view, int position, long id) { onListItemClick((GridView) parent, view, position, id); } }); // } // This has to run only at fist time from next the on scroll down will // run if (!item.isEmpty()) { mGridView.setVisibility(View.VISIBLE); progressBar.setVisibility(View.GONE); } } private boolean isConnectivityPresent() { ConnectivityManager cm = (ConnectivityManager) getActivity() .getSystemService(Context.CONNECTIVITY_SERVICE); ConnectionChecker connectionChecker = new ConnectionChecker( getActivity(), cm, getActivity()); if (MyLog.disableConnectionCheckForDebug) { return true; } if (connectionChecker.isOnline()) { return true; } else { showConnectivityErrorDialog(); return false; } } private void showConnectivityErrorDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setCancelable(true); builder.setIcon(null); builder.setTitle(null); builder.setMessage(getActivity().getString(R.string.enablewifiMsg)); builder.setInverseBackgroundForced(true); builder.setPositiveButton("Settings", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent settingPage = new Intent( android.provider.Settings.ACTION_SETTINGS); getActivity().startActivityForResult(settingPage, 0); dialog.dismiss(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog alert = builder.create(); alert.show(); } }
SQL
UTF-8
2,194
4
4
[]
no_license
create table tabela_pessoa(id serial primary key,nome varchar) create table tabela_evento(id serial primary key,evento varchar,pessoa_id int, foreign key (pessoa_id) references tabela_pessoa(id) ON DELETE CASCADE); insert into tabela_pessoa(nome) values('John Doe'); insert into tabela_pessoa(nome) values('Jane Doe'); insert into tabela_pessoa(nome) values('Alice Jones '); insert into tabela_pessoa(nome) values('Bobby Louis'); insert into tabela_pessoa(nome) values('Lisa Romero'); select * from tabela_pessoa; insert into tabela_evento(evento,pessoa_id) values('Evento A',2); insert into tabela_evento(evento,pessoa_id) values('Evento B',3); insert into tabela_evento(evento,pessoa_id) values('Evento C',2); insert into tabela_evento(evento,pessoa_id) values('Evento D',null); select * from tabela_evento; --2.1 select p.nome,e.evento from tabela_pessoa p join tabela_evento e on(p.id = e.pessoa_id); --2.2 select nome from tabela_pessoa where nome like '%Doe'; --2.3 insert into tabela_evento(evento,pessoa_id) values ('Evento E',5); --2.4 update tabela_evento set pessoa_id = 1 where evento ='Evento D'; --2.5 delete from tabela_evento where evento = 'Evento B'; --2.6 delete from tabela_pessoa p where not EXISTS (select 1 from tabela_evento where pessoa_id = p.id); --2.7 alter table tabela_pessoa add column idade int; --2.8 create table tabela_telefone(id int primary key,telefone varchar(200),pessoa_id int,foreign key (pessoa_id) references tabela_pessoa(id) ON DELETE CASCADE); --2.9 alter table tabela_telefone add constraint restricao unique(telefone); --2.10 drop table tabela_telefone; '''+----+--------------+ | tabela_pessoa | +----+--------------+ | id | nome | +----+--------------+ | 1 | John Doe | | 2 | Jane Doe | | 3 | Alice Jones | | 4 | Bobby Louis | | 5 | Lisa Romero | +----+--------------+ +----+----------------+-----------+ | tabela_evento | +----+----------------+-----------+ | id | evento | pessoa_id | +----+----------------+-----------+ | 1 | Evento A | 2 | | 2 | Evento B | 3 | | 3 | Evento C | 2 | | 4 | Evento D | NULL | +----+----------------+-----------+'''
Java
UTF-8
1,268
3.71875
4
[]
no_license
package Lista4Puc; import java.util.Scanner; public class Lista4Att3 { public static void main(String[] args) {//METODO PRINCIPAL DO PROGRAMA float A,B,C;//LADOS DO TRIANGULO Scanner ler = new Scanner(System.in);//COMANDO PARA RECEBER ENTRADA DE UMA LEITURA DE VARIAVEIS System.out.println("descubra se é tringulo obtusângulo, retângulo ou acutângulo ");//TITULO System.out.print("Informe o lado A do trângulo:");//LEITURA DO LADO A A = ler.nextFloat(); System.out.print("Informe o lado B do trângulo:");//LEITURA DO LADO B B = ler.nextFloat(); System.out.print("Informe o lado C do trângulo:");//LEITURA DO LADO C C = ler.nextFloat(); if (Math.pow(A,2) == Math.pow(B,2) + Math.pow(C,2)){//SE A^2=B^2+C^2 TRIANGULO RETANGULO System.out.print("TRIANGULO RETANGULO\n"); } else if (Math.pow(A,2) > Math.pow(B,2) + Math.pow(C,2)){//SE A^2>B^2+C^2 TRIANGULO OBTUSANGULO System.out.print("TRIANGULO OBTUSANGULO\n"); } else if (Math.pow(A,2) < Math.pow(B,2) + Math.pow(C,2)){////SE A^2<B^2+C^2 TRIANGULO OBTUSANGULO System.out.print("TRIANGULO ACUTANGULO\n"); } } }
Python
UTF-8
374
2.921875
3
[]
no_license
import json from pprint import pprint #filename = input("Input filename: ") filename = "lab3-4.json" with open(filename) as f: data = json.load(f) pprint(data) arp_dict = {} arp_entries = data["ipV4Neighbors"] for entry in arp_entries: ip_addr = entry["address"] mac_addr = entry["hwAddress"] arp_dict[ip_addr] = mac_addr print() pprint(arp_dict) print()
TypeScript
UTF-8
2,929
3.1875
3
[]
no_license
const CHORD_BASES = [ 'A', 'B♭', 'B', 'C', 'C#', 'D', 'E♭', 'E', 'F', 'F#', 'G', 'G#', ] const CHORD_BASE_INDEX: any = { 'A': 0, 'B♭': 1, 'A#': 1, 'B': 2, 'C': 3, 'C#': 4, 'D♭': 4, 'D': 5, 'E♭': 6, 'D#': 6, 'E': 7, 'F': 8, 'F#': 9, 'G♭': 9, 'G': 10, 'G#': 11, 'A♭': 11, } export enum ChordType { major = '', minor = 'm', empty = 'empty', other = 'other', repeat = 'repeat', } export class Chord { base: number; type: string; label: string = ''; isEmpty: boolean; inScale: boolean; resetLabel() { this.label = this.isEmpty ? '' : `${CHORD_BASES[this.base]}${this.type}`; } constructor(base: number, type: string, inScale: boolean = false) { this.base = base; this.type = type; this.isEmpty = type === ChordType.empty; this.inScale = inScale; this.resetLabel(); } static init() { return new Chord(0, ChordType.empty); } copyFrom(other: Chord) { this.base = other.base; this.type = other.type; this.label = other.label; this.isEmpty = other.isEmpty; } transpose(up: boolean = true) { if (this.isEmpty || this.type === ChordType.repeat) { return this; } else { const offset = up ? 1 : -1; const b = (this.base + offset + CHORD_BASES.length) % CHORD_BASES.length; return new Chord(b, this.type); } } updateFromString(label: string) { label = label.trim(); if (label.length < 1) { this.isEmpty = true; return; } if (label === '%') { this.label = label; this.type = ChordType.repeat; this.isEmpty = false; return; } const base1 = label[0].toUpperCase(); if (base1 > 'G' || base1 < 'A') { this.isEmpty = true; return; } let base = base1; if (label.length > 1) { if (label[1] === '♭' || label[1] === '#') { base += label[1]; } } this.base = CHORD_BASE_INDEX[base]; this.type = label.slice(base.length); this.label = base + this.type this.isEmpty = false; } equals(other: Chord) { return this.isEmpty === other.isEmpty || (this.base === other.base && this.type === other.type); } static fromJson(data: any) { const c = Chord.init(); c.base = data.base; c.type = data.type; c.isEmpty = data.isEmpty; c.label = data.label; return c; } toJson() { return { base: this.base, type: this.type, label: this.label, isEmpty: this.isEmpty, }; } } export const createAllChords = () => { const chords: Chord[] = []; for (let b = 0; b < CHORD_BASES.length; ++b) { chords.push(new Chord(b, ChordType.major, true)); chords.push(new Chord(b, ChordType.minor)); } chords.push(new Chord(0, ChordType.empty)); chords.sort((a, b) => { if (a.inScale && b.inScale) return 0 if (a.inScale && !b.inScale) return -1 return 1 }) return chords; }
JavaScript
UTF-8
967
3.53125
4
[]
no_license
/* * Discrete Fourier transform (JavaScript) * by Project Nayuki, 2022. Public domain. * https://www.nayuki.io/page/how-to-implement-the-discrete-fourier-transform */ "use strict"; /* * Computes the discrete Fourier transform (DFT) of the given complex vector. * 'inreal' and 'inimag' are each an array of n floating-point numbers. * Returns an array of two arrays - outreal and outimag, each of length n. */ function computeDft(inreal, inimag) { const n = inreal.length; let outreal = new Array(n); let outimag = new Array(n); for (let k = 0; k < n; k++) { // For each output element let sumreal = 0; let sumimag = 0; for (let t = 0; t < n; t++) { // For each input element const angle = 2 * Math.PI * t * k / n; sumreal += inreal[t] * Math.cos(angle) + inimag[t] * Math.sin(angle); sumimag += -inreal[t] * Math.sin(angle) + inimag[t] * Math.cos(angle); } outreal[k] = sumreal; outimag[k] = sumimag; } return [outreal, outimag]; }
Shell
UTF-8
5,265
2.84375
3
[ "Apache-2.0" ]
permissive
#!/bin/sh - # # Copyright (c) 1991 The Regents of the University of California. # All rights reserved. # # This code is derived from software contributed to Berkeley by # Kenneth Almquist. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. All advertising materials mentioning features or use of this software # must display the following acknowledgement: # This product includes software developed by the University of # California, Berkeley and its contributors. # 4. Neither the name of the University nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # # @(#)nodetypes 5.1 (Berkeley) 3/7/91 # # /b/source/CVS/src/bin/sh/nodetypes,v 1.3 1993/03/23 00:28:58 cgd Exp # This file describes the nodes used in parse trees. Unindented lines # contain a node type followed by a structure tag. Subsequent indented # lines specify the fields of the structure. Several node types can share # the same structure, in which case the fields of the structure should be # specified only once. # # A field of a structure is described by the name of the field followed # by a type. The currently implemented types are: # nodeptr - a pointer to a node # nodelist - a pointer to a list of nodes # string - a pointer to a nul terminated string # int - an integer # other - any type that can be copied by assignment # temp - a field that doesn't have to be copied when the node is copied # The last two types should be followed by the text of a C declaration for # the field. NSEMI nbinary # two commands separated by a semicolon type int ch1 nodeptr # the first child ch2 nodeptr # the second child NCMD ncmd # a simple command type int backgnd int # set to run command in background args nodeptr # the arguments redirect nodeptr # list of file redirections NPIPE npipe # a pipeline type int backgnd int # set to run pipeline in background cmdlist nodelist # the commands in the pipeline NREDIR nredir # redirection (of a compex command) type int n nodeptr # the command redirect nodeptr # list of file redirections NBACKGND nredir # run command in background NSUBSHELL nredir # run command in a subshell NAND nbinary # the && operator NOR nbinary # the || operator NIF nif # the if statement. Elif clauses are handled type int # using multiple if nodes. test nodeptr # if test ifpart nodeptr # then ifpart elsepart nodeptr # else elsepart NWHILE nbinary # the while statement. First child is the test NUNTIL nbinary # the until statement NFOR nfor # the for statement type int args nodeptr # for var in args body nodeptr # do body; done var string # the for variable NCASE ncase # a case statement type int expr nodeptr # the word to switch on cases nodeptr # the list of cases (NCLIST nodes) NCLIST nclist # a case type int next nodeptr # the next case in list pattern nodeptr # list of patterns for this case body nodeptr # code to execute for this case NDEFUN narg # define a function. The "next" field contains # the body of the function. NARG narg # represents a word type int next nodeptr # next word in list text string # the text of the word backquote nodelist # list of commands in back quotes NTO nfile # fd> fname NFROM nfile # fd< fname NAPPEND nfile # fd>> fname type int next nodeptr # next redirection in list fd int # file descriptor being redirected fname nodeptr # file name, in a NARG node expfname temp char *expfname # actual file name NTOFD ndup # fd<&dupfd NFROMFD ndup # fd>&dupfd type int next nodeptr # next redirection in list fd int # file descriptor being redirected dupfd int # file descriptor to duplicate NHERE nhere # fd<<\! NXHERE nhere # fd<<! type int next nodeptr # next redirection in list fd int # file descriptor being redirected doc nodeptr # input to command (NARG node)
Java
UTF-8
355
2.1875
2
[]
no_license
package homework.base; import org.openqa.selenium.WebDriver; import org.testng.annotations.BeforeSuite; import static java.lang.System.setProperty; public abstract class TestBase { protected WebDriver driver; @BeforeSuite(alwaysRun = true) public void setUp() { setProperty("webdriver.chrome.driver", "chromedriver.exe"); } }
Markdown
UTF-8
5,667
3.546875
4
[ "MIT" ]
permissive
# alexa-utterances generate expanded Amazon Alexa utterances from a template string When building apps for Alexa or Echo, it's important to declare many permutations of text, in order to improve the voice recognition rate. Manually generating these combinations is tedious. This module allows you to generate many (hundreds or even thousands) of sample utterances using just a few samples that get auto-expanded. Any number of sample utterances may be passed in the utterances array. Below are some sample utterances macros and what they will be expanded to. ### Usage installation: ``` npm install alexa-utterances ``` running tests: ``` npm test ``` ### API ```javascript var result = utterances(template, slots, dictionary, exhaustiveUtterances); ``` **template** a string to generate utterances from **slots** a hash of slots to fill for the given utterance **dictionary** a hash of lookup values to expand **exhaustiveUtterances** if true, builds a full cartesian product of all shortcut values and slot sample values; if false, builds a smaller list of utterances that has the full cartesian product of all shortcut values, with slot sample values filled in; default = false **result** an array of strings built from the template #### Example In the following examples, the Alexa Skill Interactin Model is used to input the LIST_OF_MOVIES. This list will be used when the Echo interprets the utterances for the intent. ```javascript var dictionary = { }; var slots = { Movie: "LIST_OF_MOVIES" }; var template = "(The best|My favorite|A great) movie is {Movie}"; var result = utterances(template, slots, dictionary); // result: // [ "My best movie is {Movie}", "My favorite movie is {Movie}", "A great movie is {Movie}" ] ``` #### Slots The slots object is a simple Name:Type mapping. The type must be one of Amazon's [built-in slot types](https://developer.amazon.com/appsandservices/solutions/alexa/alexa-skills-kit/docs/defining-the-voice-interface#h2_speech_input) or it can be a [custom slot type](#custom-slot-types). * `AMAZON.DATE` – converts words that indicate dates (“today”, “tomorrow”, or “july”) into a date format (such as “2015-07-00T9”). * `AMAZON.DURATION` – converts words that indicate durations (“five minutes”) into a numeric duration (“PT5M”). * `AMAZON.FOUR_DIGIT_NUMBER` - Provides recognition for four-digit numbers, such as years. * `AMAZON.NUMBER` – converts numeric words (“five”) into digits (such as “5”). * `AMAZON.TIME` – converts words that indicate time (“four in the morning”, “two p m”) into a time value (“04:00”, “14:00”). * `AMAZON.US_CITY` - provides recognition for major cities in the United States. All cities with a population over 100,000 are included. You can extend the type to include more cities if necessary. * `AMAZON.US_FIRST_NAME` - provides recognition for thousands of popular first names, based on census and social security data. You can extend the type to include more names if necessary. * `AMAZON.US_STATE` - provides recognition for US states, territories, and the District of Columbia. You can extend this type to include more states if necessary. #### Generate Multiple Versions of Static Text This lets you define multiple ways to say a phrase, but combined into a single sample utterance using parentheses to group the phrases. ```javascript "(what is|what's|check) the status" => "what is the status" "what's the status" "check the status" ``` #### Auto-Generated Number Ranges When capturing a numeric slot value, it's helpful to generate many sample utterances with different number values. ```javascript "buy (2-5) items" => "buy two items" "buy three items" "buy four items" "buy five items" ``` Number ranges can also increment in steps. ```javascript "buy (5-20 by 5) items" => "buy five items" "buy ten items" "buy fifteen items" "buy twenty items" ``` #### Optional Words ```javascript "what is your (favorite |)color" => "what is your color" "what is your favorite color" ``` #### Custom Slot Types <a name="custom-slot-types"></a> You may want to work with [Custom Slot Types](https://developer.amazon.com/appsandservices/solutions/alexa/alexa-skills-kit/docs/defining-the-voice-interface#h2_speech_input) registered in your interaction model. To reference the slot name in the template, use the name enclosed in curly braces. For example, if you have defined in your skill a `FRUIT_TYPE` with the values `Apple`, `Orange` and `Lemon` for the slot `Fruit`, you can keep `Fruit` a curly-braced literal as follows. ```javascript "(my|your) (favorite|least favorite) snack is {Fruit}" => "my favorite snack is {Fruit}" "your favorite snack is {Fruit}" "my least favorite snack is {Fruit}" "your least favorite snack is {Fruit}" ``` #### Using a Dictionary Several intents may use the same list of possible values, so you want to define them in one place, not in each intent schema. Use the app's dictionary. ```javascript var dictionary = { "colors": [ "red", "green", "blue" ] }; ... "I like {colors|COLOR}" ``` #### Multiple Options mapped to a Slot It is [recommended to use Custom Slot Types](https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/migrating-to-the-improved-built-in-and-custom-slot-types) instead of this approach when constructing utterances. Migrating to a custom slot type is recommended, as it is easier to define the sample utterances and achieve better accuracy. ```javascript "my favorite color is {red|green|blue|NAME}" => "my favorite color is {red|NAME}" "my favorite color is {green|NAME}" "my favorite color is {blue|NAME}" ```
Ruby
UTF-8
883
3.15625
3
[]
no_license
require_relative 'todolist.rb' # Creates a new todo list mylist = TodoList.new("Things to complete") # Add four new items mylist.add_item("Alarm ring") mylist.add_item("Wake up") mylist.add_item("Bath") mylist.add_item("Ready to office") # Print the list mylist.print_list # Delete the first item mylist.remove_item(1) # Print the list mylist.print_list # Delete the second item mylist.remove_item(2) # Print the list mylist.print_list # Update the completion status of the first item to complete mylist.update_status(1,true) # Print the list mylist.print_list # Update the title of the list mylist.update_title("New Things to learn") # Print the list mylist.print_list #New features #Get items that are in completed status mylist.completed_status ##Add due date , times for each item mylist.update_due_date("Wake up","03/12/2016") # Print the list mylist.print_list
Java
UTF-8
535
2.40625
2
[]
no_license
package com.javashitang.medium._416; import org.junit.Test; import static org.junit.Assert.*; public class SolutionTest { @Test public void canPartition() { Solution solution = new Solution(); int[] nums = {1, 5, 11, 5}; boolean flag = solution.canPartition(nums); assertTrue(flag); } @Test public void test1() { Solution solution = new Solution(); int[] nums = {1, 2, 3, 5}; boolean flag = solution.canPartition(nums); assertFalse(flag); } }
SQL
UTF-8
402
3.0625
3
[ "MIT" ]
permissive
CREATE TABLE users ( id BIGINT PRIMARY KEY NOT NULL, created TIMESTAMP NOT NULL, modified TIMESTAMP NOT NULL, version INTEGER NOT NULL, email VARCHAR(255), enabled BOOLEAN NOT NULL DEFAULT FALSE, first_name VARCHAR(255), last_name VARCHAR(255), password VARCHAR(255) ); CREATE UNIQUE INDEX uk_email ON users (email);
JavaScript
UTF-8
4,459
2.609375
3
[]
no_license
var express = require('express'); var mongoose = require('mongoose'); var router = express.Router(); var Species = require('../../models/species'); var Genus = require('../../models/genus'); var Family = require('../../models/family'); var Order = require('../../models/order'); var Class = require('../../models/class'); var Phylum = require('../../models/phylum'); var Domain = require('../../models/domain'); var columnOrder = ["domain", "phylum", "class", "order", "family", "genus"]; var columnJSONList = { DOMAIN : Domain, PHYLUM : Phylum, CLASS : Class, ORDER : Order, FAMILY : Family, GENUS : Genus, SPECIES : Species } //Column is either Species, Genus, Family, Order, Phylum or Domain //finds the element and number var findElement = function(element, Column) { Column.findOne({ ename: element.ename }, function(err, item) { if (err) return console.log(err); return item; }); } //This will find the element, see if it exists, and then save it. var saveElementPC = function(elementChildModel, elementParent, ColumnParent, callback) { console.log(elementParent.ename); ColumnParent.findOne({ ename: elementParent.ename }, function(err, item) { if (err) return console.log(err); var cparent = item; //If item exist, push the current object id to the member of the above if (cparent) { cparent.members.push(elementChildModel._id); //saveElement(cparent); elementChildModel.cparent = cparent._id; cparent.save(function(err, savedParent) { if (err) return console.log(err); elementChildModel.save(function(err, savedParent) { if (err) return console.log(err); callback(null); }) }); //saveElement(elementChildModel); //found match } else { var saveParent = new ColumnParent(elementParent); saveParent.members.push(elementChildModel._id); saveParent.save(function(err, savedParent) { if (err) return console.log(err); elementChildModel.cparent = savedParent._id; elementChildModel.save(function(err,savedChild) { if (err) return console.log(err); callback(savedParent); }); }); } }); } var addSpecieRecursion = function(row, savedChildModel) { if (row.columnsToBeFilled.length > 0) { var columnName = row.columnsToBeFilled.pop(); var elementParent = { ename: row[columnName] } var Column = columnJSONList[columnName.toUpperCase()]; saveElementPC(savedChildModel, elementParent, Column, function( savedChildModel) { if (savedChildModel === null) return; else addSpecieRecursion(row, savedChildModel); }); } } //Pass in a JSON object with every paramater, simplifies it for the front end //We deal with the rest, easier to maintain. //It'll break if you dont passs in the right column paramaters for the row //Easy fix, we'd simply check the prototpes so no one fucks with our DB. //CBA right now to do it. var addSpecie = function(req, res, next) { var row = {}; row.species = req.body.species; row.strain = req.body.strain; row.genome = req.body.genome; row.JSONCreate = req.body.JSONCreate; row.domain = req.body.domain; row.phylum = req.body.phylum; row.class = req.body.class; row.order = req.body.order; row.family = req.body.family; row.genus = req.body.genus; var specie = new Species({ ename: row['species'], strain: row['strain'], misc: row['misc'], genome: row['genome'], JSONCreated: row['JSONCreated'] }); row.columnsToBeFilled = columnOrder; specie.save(function(err, savedSpecie) { addSpecieRecursion(row, savedSpecie); res.send('Successfully saved ' + req.body.species + '\n'); }); } router.post('/create/specie',addSpecie) module.exports = router;
Java
UTF-8
504
1.695313
2
[]
no_license
package com.its.fppbkk.service; import java.util.List; import com.its.fppbkk.entity.Menu; import com.its.fppbkk.entity.Restoran; import com.its.fppbkk.entity.Tag; public interface RestoranService { public List<Restoran> getRestoran(); public void saveRestoran(Restoran resto); public Restoran getRestoranByID(int restoID); public void deleteRestoran(int restoID); public List<Tag> getTagRestoran(int restoID); public List<Restoran> getRestoranByBudget(int budget, String location); }
Java
UTF-8
22,737
1.640625
2
[]
no_license
/******************************************************************************* * Copyright (c) 2009 LuaJ. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ package org.luaj.lib; import org.luaj.vm.CallInfo; import org.luaj.vm.LClosure; import org.luaj.vm.LFunction; import org.luaj.vm.LInteger; import org.luaj.vm.LNil; import org.luaj.vm.LPrototype; import org.luaj.vm.LString; import org.luaj.vm.LTable; import org.luaj.vm.LValue; import org.luaj.vm.LoadState; import org.luaj.vm.Lua; import org.luaj.vm.LuaErrorException; import org.luaj.vm.LuaState; public class DebugLib extends LFunction { private static final String[] NAMES = { "debuglib", "debug", "getfenv", "gethook", "getinfo", "getlocal", "getmetatable", "getregistry", "getupvalue", "setfenv", "sethook", "setlocal", "setmetatable", "setupvalue", "traceback", }; private static final int INSTALL = 0; private static final int DEBUG = 1; private static final int GETFENV = 2; private static final int GETHOOK = 3; private static final int GETINFO = 4; private static final int GETLOCAL = 5; private static final int GETMETATABLE = 6; private static final int GETREGISTRY = 7; private static final int GETUPVALUE = 8; private static final int SETFENV = 9; private static final int SETHOOK = 10; private static final int SETLOCAL = 11; private static final int SETMETATABLE = 12; private static final int SETUPVALUE = 13; private static final int TRACEBACK = 14; /* maximum stack for a Lua function */ private static final int MAXSTACK = 250; private static final LString LUA = new LString("Lua"); private static final LString JAVA = new LString("Java"); private static final LString JAVASRC = new LString("[Java]"); private static final LString QMARK = new LString("?"); private static final LString GLOBAL = new LString("global"); private static final LString LOCAL = new LString("local"); private static final LString METHOD = new LString("method"); private static final LString UPVALUE = new LString("upvalue"); private static final LString FIELD = new LString("field"); private static final LString NOSTRING = new LString(""); public static void install( LuaState vm ) { LTable debug = new LTable(); for (int i = 1; i < NAMES.length; i++) debug.put(NAMES[i], new DebugLib(i)); vm._G.put("debug", debug); PackageLib.setIsLoaded("debug", debug); } private final int id; public DebugLib() { this.id = INSTALL; } private DebugLib( int id ) { this.id = id; } public String toString() { return NAMES[id]+"()"; } public int invoke( LuaState vm ) { switch ( id ) { case INSTALL: install(vm); return 0; case DEBUG: return debug(vm); case GETFENV: return getfenv(vm); case GETHOOK: return gethook(vm); case GETINFO: return getinfo(vm); case GETLOCAL: return getlocal(vm); case GETMETATABLE: return getmetatable(vm); case GETREGISTRY: return getregistry(vm); case GETUPVALUE: return getupvalue(vm); case SETFENV: return setfenv(vm); case SETHOOK: return sethook(vm); case SETLOCAL: return setlocal(vm); case SETMETATABLE: return setmetatable(vm); case SETUPVALUE: return setupvalue(vm); case TRACEBACK: return traceback(vm); default: LuaState.vmerror( "bad package id" ); return 0; } } // j2se subclass may wish to override and provide actual console here. // j2me platform has not System.in to provide console. protected int debug(LuaState vm) { return 0; } protected int gethook(LuaState vm) { LuaState threadVm = vm; if ( vm.gettop() >= 2 ) threadVm = vm.checkthread(1).vm; vm.pushlvalue(threadVm.gethook()); vm.pushinteger(threadVm.gethookmask()); vm.pushinteger(threadVm.gethookcount()); return 3; } protected LuaState optthreadvm(LuaState vm, int index) { if ( ! vm.isthread(index) ) return vm; LuaState threadVm = vm.checkthread(index).vm; vm.remove(index); return threadVm; } protected int sethook(LuaState vm) { LuaState threadVm = optthreadvm(vm, 1); LFunction func = vm.isnoneornil(1)? null: vm.checkfunction(2); String str = vm.optstring(2,""); int count = vm.optint(3,0); int mask = 0; for ( int i=0; i<str.length(); i++ ) switch ( str.charAt(i) ) { case 'c': mask |= LuaState.LUA_MASKCALL; break; case 'l': mask |= LuaState.LUA_MASKLINE; break; case 'r': mask |= LuaState.LUA_MASKRET; break; } threadVm.sethook(func, mask, count); return 0; } protected int getfenv(LuaState vm) { LValue object = vm.topointer(1); LValue env = object.luaGetEnv(null); vm.pushlvalue(env!=null? env: LNil.NIL); return 1; } protected int setfenv(LuaState vm) { LValue object = vm.topointer(1); LTable table = vm.checktable(2); object.luaSetEnv(table); vm.settop(1); return 1; } protected int getinfo(LuaState vm) { LuaState threadVm = optthreadvm(vm, 1); String what = vm.optstring(2, "nSluf"); // find the stack info StackInfo si; if ( vm.isnumber(1) ) { int level = vm.tointeger(1); si = getstackinfo(threadVm, level, 1)[0]; if ( si == null ) { return 0; } } else { LFunction func = vm.checkfunction(1); si = findstackinfo(threadVm, func); } // look up info LTable info = new LTable(); vm.pushlvalue(info); LClosure c = si.closure(); for (int i = 0, n = what.length(); i < n; i++) { switch (what.charAt(i)) { case 'S': { if ( c != null ) { LPrototype p = c.p; info.put("what", LUA); info.put("source", p.source); info.put("short_src", new LString(p.sourceshort())); info.put("linedefined", p.linedefined); info.put("lastlinedefined", p.lastlinedefined); } else { info.put("what", JAVA); info.put("source", JAVASRC); info.put("short_src", JAVASRC); info.put("linedefined", -1); info.put("lastlinedefined", -1); } break; } case 'l': { int line = si.currentline(); info.put( "currentline", line ); break; } case 'u': { info.put("nups", (c!=null? c.p.nups: 0)); break; } case 'n': { LString[] kind = si.getfunckind(); info.put("name", kind!=null? kind[0]: QMARK); info.put("namewhat", kind!=null? kind[1]: NOSTRING); break; } case 'f': { info.put( "func", si.func ); break; } case 'L': { LTable lines = new LTable(); info.put("activelines", lines); if ( si.luainfo != null ) { int line = si.luainfo.currentline(); if ( line >= 0 ) lines.put(1, LInteger.valueOf(line)); } break; } } } return 1; } protected int getlocal(LuaState vm) { LuaState threadVm = optthreadvm(vm, 1); int level = vm.checkint(1); int local = vm.checkint(2); StackInfo si = getstackinfo(threadVm, level, 1)[0]; CallInfo ci = (si!=null? si.luainfo: null); LPrototype p = (ci!=null? ci.closure.p: null); LString name = (p!=null? p.getlocalname(local, ci.pc>0? ci.pc-1: 0): null); if ( name != null ) { LValue value = threadVm.stack[ci.base+(local-1)]; vm.pushlvalue( name ); vm.pushlvalue( value ); return 2; } else { vm.pushnil(); return 1; } } protected int setlocal(LuaState vm) { LuaState threadVm = optthreadvm(vm, 1); int level = vm.checkint(1); int local = vm.checkint(2); LValue value = vm.topointer(3); StackInfo si = getstackinfo(threadVm, level, 1)[0]; CallInfo ci = (si!=null? si.luainfo: null); LPrototype p = (ci!=null? ci.closure.p: null); LString name = (p!=null? p.getlocalname(local, ci.pc>0? ci.pc-1: 0): null); if ( name != null ) { threadVm.stack[ci.base+(local-1)] = value; vm.pushlvalue(name); } else { vm.pushnil(); } return 1; } protected int getmetatable(LuaState vm) { LValue object = vm.topointer(1); LValue mt = object.luaGetMetatable(); if ( mt != null ) vm.pushlvalue( object.luaGetMetatable() ); else vm.pushnil(); return 1; } protected int setmetatable(LuaState vm) { LValue object = vm.topointer(1); try { if ( ! vm.isnoneornil(2) ) object.luaSetMetatable(vm.checktable(3)); else object.luaSetMetatable(null); vm.pushboolean(true); return 1; } catch ( LuaErrorException e ) { vm.pushboolean(false); vm.pushstring(e.toString()); return 2; } } protected int getregistry(LuaState vm) { vm.pushlvalue( new LTable() ); return 1; } private LString findupvalue(LClosure c, int up) { if ( c.upVals != null && up > 0 && up <= c.upVals.length ) { if ( c.p.upvalues != null && up <= c.p.upvalues.length ) return c.p.upvalues[up-1]; else return new LString( "."+up+"" ); } return null; } protected int getupvalue(LuaState vm) { LFunction func = vm.checkfunction(1); int up = vm.checkint(2); vm.resettop(); if ( func instanceof LClosure ) { LClosure c = (LClosure) func; LString name = findupvalue(c, up); if ( name != null ) { vm.pushlstring(name); vm.pushlvalue(c.upVals[up-1].getValue()); return 2; } } vm.pushnil(); return 1; } protected int setupvalue(LuaState vm) { LFunction func = vm.checkfunction(1); int up = vm.checkint(2); LValue value = vm.topointer(3); vm.resettop(); if ( func instanceof LClosure ) { LClosure c = (LClosure) func; LString name = findupvalue(c, up); if ( name != null ) { c.upVals[up-1].setValue(value); vm.pushlstring(name); return 1; } } vm.pushnil(); return 1; } protected int traceback(LuaState vm) { LuaState threadVm = optthreadvm(vm, 1); String message = ""; int level = vm.optint(2,1); if ( ! vm.isnoneornil(1) ) message = vm.checkstring(1)+"\n"; StackInfo[] s = getstackinfo(threadVm, level, 10); StringBuffer sb = new StringBuffer("stack traceback:"); for ( int i=0; i<s.length; i++ ) { StackInfo si = s[i]; if ( si != null ) { sb.append( "\n\t" ); sb.append( si.sourceline() ); sb.append( ": in " ); sb.append( si.tracename() ); } } vm.pushstring(message+sb); return 1; } // ======================================================= private static void lua_assert(boolean x) { if (!x) throw new RuntimeException("lua_assert failed"); } private static class StackInfo { private LuaState vm; private CallInfo caller; // or null if first item on stack private int stackpos; // offset into stack private CallInfo luainfo; // or null if a java function private LValue func; // or null if a lua call public StackInfo(LuaState vm, CallInfo caller, int stackpos, CallInfo luainfo, LFunction func) { this.vm = vm; this.caller = caller; this.stackpos = stackpos; this.luainfo = luainfo; this.func = func!=null? func: luainfo!=null? luainfo.closure: null; } public LClosure closure() { return luainfo!=null? luainfo.closure: func!=null&&func.isClosure()? (LClosure)func: null; } public String sourceline() { if ( luainfo != null ) { String s = luainfo.closure.p.source.toJavaString(); int line = currentline(); return (s.startsWith("@")||s.startsWith("=")? s.substring(1): s) + ":" + line; } else { return "[Java]"; } } public LString[] getfunckind() { return (caller!=null && stackpos>=0? getobjname(vm, caller, stackpos): null); } public int currentline() { return luainfo!=null? luainfo.currentline(): -1; } public String tracename() { if ( caller == null ) return "main chunk"; if ( func != null ) return func.toString(); LString[] kind = getfunckind(); if ( kind == null ) return "function ?"; return "function "+kind[0].toJavaString(); } } /** * @param level first level to report * @return array StackInfo with countlevels items, some may be null! */ private static StackInfo[] getstackinfo(LuaState vm, int level, int countlevels) { StackInfo[] si = new StackInfo[countlevels]; int i = 0; LClosure prevclosure = null; for (int j=vm.cc; j>=0; --j) { CallInfo ci = vm.calls[j]; LFunction f = ci.currentfunc(vm); // java, or tailcall? if ( f != null && (! f.isClosure() || f!=prevclosure) ) { if ( (level--) <= 0 ) { si[i++] = new StackInfo( vm, ci, ci.currentfunca(vm), null, f); if ( i >= countlevels ) return si; } } // add the lua closure if ( (level--) <= 0 ) { if (j>0 && vm.calls[j-1].currentfunc(vm) == ci.closure) { CallInfo caller = vm.calls[j-1]; int callera = caller.currentfunca(vm); si[i++] = new StackInfo( vm, caller, callera, ci, ci.closure); } else { si[i++] = new StackInfo( vm, null, -1, ci, ci.closure); } if ( i >= countlevels ) return si; } prevclosure = ci.closure; } return si; } // look up a function in the stack, if it exists private static StackInfo findstackinfo(LuaState vm, LFunction func) { for (int j=vm.cc; j>=0; --j) { CallInfo ci = vm.calls[j]; int instr = ci.closure.p.code[ci.pc>0? ci.pc-1: 0]; if ( Lua.GET_OPCODE(instr) == Lua.OP_CALL ) { int a = Lua.GETARG_A(instr); if ( func == vm.stack[ci.base + a] ) return new StackInfo(vm, ci, a, null, func); if ( func == ci.closure ) return new StackInfo(vm, (j>0? vm.calls[j-1]: null), 0, ci, null); } } return new StackInfo(vm, null, -1, null, func); } // return LString[] { name, namewhat } if found, null if not private static LString[] getobjname(LuaState L, CallInfo ci, int stackpos) { LString name; if (ci.isLua()) { /* a Lua function? */ LPrototype p = ci.closure.p; int pc = (ci.pc > 0 ? ci.pc - 1 : 0); // currentpc(L, ci); int i;// Instruction i; name = p.getlocalname(stackpos + 1, pc); if (name != null) /* is a local? */ return new LString[] { name, LOCAL }; i = symbexec(p, pc, stackpos); /* try symbolic execution */ lua_assert(pc != -1); switch (Lua.GET_OPCODE(i)) { case Lua.OP_GETGLOBAL: { int g = Lua.GETARG_Bx(i); /* global index */ // lua_assert(p.k[g].isString()); return new LString[] { p.k[g].luaAsString(), GLOBAL }; } case Lua.OP_MOVE: { int a = Lua.GETARG_A(i); int b = Lua.GETARG_B(i); /* move from `b' to `a' */ if (b < a) return getobjname(L, ci, b); /* get name for `b' */ break; } case Lua.OP_GETTABLE: { int k = Lua.GETARG_C(i); /* key index */ name = kname(p, k); return new LString[] { name, FIELD }; } case Lua.OP_GETUPVAL: { int u = Lua.GETARG_B(i); /* upvalue index */ name = u < p.upvalues.length ? p.upvalues[u] : QMARK; return new LString[] { name, UPVALUE }; } case Lua.OP_SELF: { int k = Lua.GETARG_C(i); /* key index */ name = kname(p, k); return new LString[] { name, METHOD }; } default: break; } } return null; /* no useful name found */ } private static LString kname(LPrototype p, int c) { if (Lua.ISK(c) && p.k[Lua.INDEXK(c)].isString()) return p.k[Lua.INDEXK(c)].luaAsString(); else return QMARK; } private static boolean checkreg(LPrototype pt,int reg) { return (reg < pt.maxstacksize); } private static boolean precheck(LPrototype pt) { if (!(pt.maxstacksize <= MAXSTACK)) return false; lua_assert(pt.numparams + (pt.is_vararg & Lua.VARARG_HASARG) <= pt.maxstacksize); lua_assert((pt.is_vararg & Lua.VARARG_NEEDSARG) == 0 || (pt.is_vararg & Lua.VARARG_HASARG) != 0); if (!(pt.upvalues.length <= pt.nups)) return false; if (!(pt.lineinfo.length == pt.code.length || pt.lineinfo.length == 0)) return false; if (!(Lua.GET_OPCODE(pt.code[pt.code.length - 1]) == Lua.OP_RETURN)) return false; return true; } private static boolean checkopenop(LPrototype pt,int pc) { int i = pt.code[(pc)+1]; switch (Lua.GET_OPCODE(i)) { case Lua.OP_CALL: case Lua.OP_TAILCALL: case Lua.OP_RETURN: case Lua.OP_SETLIST: { if (!(Lua.GETARG_B(i) == 0)) return false; return true; } default: return false; /* invalid instruction after an open call */ } } //static int checkArgMode (LPrototype pt, int r, enum OpArgMask mode) { private static boolean checkArgMode (LPrototype pt, int r, int mode) { switch (mode) { case Lua.OpArgN: if (!(r == 0)) return false; break; case Lua.OpArgU: break; case Lua.OpArgR: checkreg(pt, r); break; case Lua.OpArgK: if (!(Lua.ISK(r) ? Lua.INDEXK(r) < pt.k.length : r < pt.maxstacksize)) return false; break; } return true; } // return last instruction, or 0 if error private static int symbexec(LPrototype pt, int lastpc, int reg) { int pc; int last; /* stores position of last instruction that changed `reg' */ last = pt.code.length - 1; /* * points to final return (a `neutral' * instruction) */ if (!(precheck(pt))) return 0; for (pc = 0; pc < lastpc; pc++) { int i = pt.code[pc]; int op = Lua.GET_OPCODE(i); int a = Lua.GETARG_A(i); int b = 0; int c = 0; if (!(op < Lua.NUM_OPCODES)) return 0; if (!checkreg(pt, a)) return 0; switch (Lua.getOpMode(op)) { case Lua.iABC: { b = Lua.GETARG_B(i); c = Lua.GETARG_C(i); if (!(checkArgMode(pt, b, Lua.getBMode(op)))) return 0; if (!(checkArgMode(pt, c, Lua.getCMode(op)))) return 0; break; } case Lua.iABx: { b = Lua.GETARG_Bx(i); if (Lua.getBMode(op) == Lua.OpArgK) if (!(b < pt.k.length)) return 0; break; } case Lua.iAsBx: { b = Lua.GETARG_sBx(i); if (Lua.getBMode(op) == Lua.OpArgR) { int dest = pc + 1 + b; if (!(0 <= dest && dest < pt.code.length)) return 0; if (dest > 0) { /* cannot jump to a setlist count */ int d = pt.code[dest - 1]; if ((Lua.GET_OPCODE(d) == Lua.OP_SETLIST && Lua.GETARG_C(d) == 0)) return 0; } } break; } } if (Lua.testAMode(op)) { if (a == reg) last = pc; /* change register `a' */ } if (Lua.testTMode(op)) { if (!(pc + 2 < pt.code.length)) return 0; /* check skip */ if (!(Lua.GET_OPCODE(pt.code[pc + 1]) == Lua.OP_JMP)) return 0; } switch (op) { case Lua.OP_LOADBOOL: { if (!(c == 0 || pc + 2 < pt.code.length)) return 0; /* check its jump */ break; } case Lua.OP_LOADNIL: { if (a <= reg && reg <= b) last = pc; /* set registers from `a' to `b' */ break; } case Lua.OP_GETUPVAL: case Lua.OP_SETUPVAL: { if (!(b < pt.nups)) return 0; break; } case Lua.OP_GETGLOBAL: case Lua.OP_SETGLOBAL: { if (!(pt.k[b].isString())) return 0; break; } case Lua.OP_SELF: { if (!checkreg(pt, a + 1)) return 0; if (reg == a + 1) last = pc; break; } case Lua.OP_CONCAT: { if (!(b < c)) return 0; /* at least two operands */ break; } case Lua.OP_TFORLOOP: { if (!(c >= 1)) return 0; /* at least one result (control variable) */ if (!checkreg(pt, a + 2 + c)) return 0; /* space for results */ if (reg >= a + 2) last = pc; /* affect all regs above its base */ break; } case Lua.OP_FORLOOP: case Lua.OP_FORPREP: if (!checkreg(pt, a + 3)) return 0; /* go through */ case Lua.OP_JMP: { int dest = pc + 1 + b; /* not full check and jump is forward and do not skip `lastpc'? */ if (reg != Lua.NO_REG && pc < dest && dest <= lastpc) pc += b; /* do the jump */ break; } case Lua.OP_CALL: case Lua.OP_TAILCALL: { if (b != 0) { if (!checkreg(pt, a + b - 1)) return 0; } c--; /* c = num. returns */ if (c == Lua.LUA_MULTRET) { if (!(checkopenop(pt, pc))) return 0; } else if (c != 0) if (!checkreg(pt, a + c - 1)) return 0; if (reg >= a) last = pc; /* affect all registers above base */ break; } case Lua.OP_RETURN: { b--; /* b = num. returns */ if (b > 0) if (!checkreg(pt, a + b - 1)) return 0; break; } case Lua.OP_SETLIST: { if (b > 0) if (!checkreg(pt, a + b)) return 0; if (c == 0) pc++; break; } case Lua.OP_CLOSURE: { int nup, j; if (!(b < pt.p.length)) return 0; nup = pt.p[b].nups; if (!(pc + nup < pt.code.length)) return 0; for (j = 1; j <= nup; j++) { int op1 = Lua.GET_OPCODE(pt.code[pc + j]); if (!(op1 == Lua.OP_GETUPVAL || op1 == Lua.OP_MOVE)) return 0; } if (reg != Lua.NO_REG) /* tracing? */ pc += nup; /* do not 'execute' these pseudo-instructions */ break; } case Lua.OP_VARARG: { if (!((pt.is_vararg & Lua.VARARG_ISVARARG) != 0 && (pt.is_vararg & Lua.VARARG_NEEDSARG) == 0)) return 0; b--; if (b == Lua.LUA_MULTRET) if (!(checkopenop(pt, pc))) return 0; if (!checkreg(pt, a + b - 1)) return 0; break; } default: break; } } return pt.code[last]; } }
Java
UTF-8
2,410
2.328125
2
[]
no_license
package pl.cyfronet.indigo.security; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.ToString; import org.codehaus.jackson.annotate.JsonCreator; import org.codehaus.jackson.annotate.JsonProperty; import pl.cyfronet.indigo.bean.Role; import pl.cyfronet.indigo.bean.User; @Data @Builder @AllArgsConstructor @ToString public class UserInfo { private Long id; private String email; private String name; private Boolean confirmedRegistration; private String organisation_name; private String unityPersistentIdentity; private boolean operator; public UserInfo() { } @JsonCreator public UserInfo(@JsonProperty("email")String email, @JsonProperty("name")String name, @JsonProperty("email_verified")Boolean confirmedRegistration, @JsonProperty("persistent")String persistent, @JsonProperty("organisation_name")String organisationName ) { this.email = email; this.name = name; this.confirmedRegistration = confirmedRegistration; this.unityPersistentIdentity = persistent; this.organisation_name = organisationName; } public User.UserBuilder toUserPrototype() { return User.builder() .email(email) .name(name) .organisationName(organisation_name) .confirmedRegistration(confirmedRegistration) .unityPersistentIdentity(unityPersistentIdentity); } public static UserInfo fromUser(User user) { if (user == null) { return null; } UserInfoBuilder builder = UserInfo.builder() .id(user.getId()) .email(user.getEmail()) .name(user.getName()) .organisation_name(user.getOrganisationName()) .confirmedRegistration(user.getConfirmedRegistration()) .unityPersistentIdentity(user.getUnityPersistentIdentity()); /* * TODO fix role assignment below */ for(Role role: user.getRoles()) { if (role.getName().equals("operator") || role.getName().equals("admin")) { builder.operator(true); } } return builder.build() ; } }
Python
UTF-8
1,332
3.40625
3
[ "MIT" ]
permissive
def recursiveSolution(string1, string2): if not string1 and string2: return len(string2) elif not string2 and string1: return len(string1) elif not(string1 or string2): return 0 if string1[-1] == string2[-1]: return recursiveSolution(string1[:-1], string2[:-1]) else: return 1 + min(recursiveSolution(string1, string2[:-1]), recursiveSolution(string1[:-1], string2[:-1]), recursiveSolution(string1[:-1], string2)) def dpSolution(string1, string2): matrix = [[0 for _ in range(len(string1)+1)] for _ in range(len(string2)+1)] for i in range(len(matrix)): # i = current row = current substring in string 2 for j in range(len(matrix[0])): # j = current column = current substring in string 1 if i == 0: matrix[i][j] = j elif j == 0: matrix[i][j] = i elif string2[i-1] == string1[j-1]: matrix[i][j] = matrix[i - 1][j - 1] else: matrix[i][j] = 1 + min(matrix[i - 1][j], matrix[i][j - 1], matrix[i - 1][j - 1]) return matrix[len(string2) - 1][len(string1) - 1] def main(): assert dpSolution("kitten", "sitting") == 3 assert recursiveSolution("kitten", "sitting") == 3 if __name__ == '__main__': main()
JavaScript
UTF-8
4,651
2.640625
3
[ "Apache-2.0" ]
permissive
var page = require('webpage').create(), system = require('system'), username, password; var isFirstTimeEnterRunning = true; var isTurningOn = false; var isReloadPage = false; if (system.args.length < 2) { console.log('Usage: koding.js <username> <password>'); phantom.exit(); } else { username = system.args[1]; password = system.args[2]; } page.viewportSize = { width: 800, height: 600 }; //method functions function checkVMStatus() { setTimeout(function() { var isDialogDisplayed = page.evaluateJavaScript(function() { return document.getElementsByClassName('kdmodal-shadow').length > 0; }); var isLoadingStatus = page.evaluateJavaScript(function() { if (document.getElementsByClassName('content-container').length > 0) { return document.getElementsByClassName('content-container')[0].firstElementChild.textContent.indexOf('turned off') < 0; } else { return false; } }); var vmStatus = 'checking'; if (isDialogDisplayed) { if (!isLoadingStatus) { vmStatus = 'off'; } } else { vmStatus = 'on'; } if (vmStatus === 'off') { isTurningOn = true; console.log('[INFO] Turn it on now!!!'); page.evaluateJavaScript(function() { document.getElementsByClassName('content-container')[0].children[1].click(); }); } else if (vmStatus === 'on') { isTurningOn = false; if (isFirstTimeEnterRunning) { isFirstTimeEnterRunning = false; console.log('[INFO] Running!!!'); console.log('[INFO] Terminate old sessions and create a new session...'); // close all sessions, and create a new session page.evaluateJavaScript(function() { setTimeout(function() { document.getElementsByClassName('plus')[0].click(); setTimeout(function() { var sessionMenu = document.getElementsByClassName('new-terminal')[0].nextElementSibling; sessionMenu.className = sessionMenu.className.replace('hidden', ''); if (document.getElementsByClassName('terminate-all').length > 0) { document.getElementsByClassName('terminate-all')[0].click(); setTimeout(function() { document.getElementsByClassName('plus')[0].click(); setTimeout(function() { var newSessionMenu = document.getElementsByClassName('new-terminal')[0].nextElementSibling; newSessionMenu.className = newSessionMenu.className.replace('hidden', ''); setTimeout(function() { document.getElementsByClassName('new-session')[0].click(); }, 1000); }, 1000); }, 5000); } else { document.getElementsByClassName('new-session')[0].click(); } }, 1000); }, 5000); }); setTimeout(function() { console.log('[INFO] ' + new Date()); console.log('\r\n'); phantom.exit(); }, 15000); } else { console.log('[WARN] Check running again.'); } } else { checkVMStatus(); } }, 500); }; // page functions page.onLoadStarted = function() { if (isReloadPage) { isReloadPage = false; } else { var currentUrl = page.evaluate(function() { return window.location.href; }); console.log('[INFO] Current page ' + currentUrl + ' will gone...'); console.log('[INFO] Now loading a new page...'); } }; page.onLoadFinished = function(status) { if (status !== 'success') { isReloadPage = true; page.reload(); } else { var currentUrl = page.evaluate(function() { return window.location.href; }); console.log('[INFO] Page ' + currentUrl + ' loaded...'); if (currentUrl == 'https://koding.com/Login') { console.log('[INFO] Login now!!!'); page.evaluate(function(username, password) { document.querySelector('input[testpath="login-form-username"]').value = username; document.querySelector('input[testpath="login-form-password"]').value = password; document.querySelector('button[testpath="login-button"]').click(); }, username, password); } else if (currentUrl == 'https://koding.com/IDE/koding-vm-0/my-workspace') { checkVMStatus(); } } }; // start program console.log('[INFO] ' + new Date()); page.open('https://koding.com/Login', function(status) { if (status !== 'success') { isReloadPage = true; page.reload(); } }); // force kill this phantomJS thread if it's still alive after 3 mins // wait for 1 more min if it's turning on setTimeout(function() { if (isTurningOn) { setTimeout(function() { console.log('[WARN] Force killed!!!'); console.log('[INFO] ' + new Date()); console.log('\r\n'); phantom.exit(); }, 60000); } else { console.log('[WARN] Force killed!!!'); console.log('[INFO] ' + new Date()); console.log('\r\n'); phantom.exit(); } }, 180000);
Java
UTF-8
7,028
1.8125
2
[]
no_license
package com.mystihgreeh.mareu; import android.text.format.DateFormat; import android.widget.DatePicker; import androidx.test.espresso.contrib.PickerActions; import androidx.test.espresso.contrib.RecyclerViewActions; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.rule.ActivityTestRule; import com.mystihgreeh.mareu.DI.Injection; import com.mystihgreeh.mareu.controler.ReunionList; import com.mystihgreeh.mareu.service.ReunionApiService; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static androidx.test.espresso.Espresso.onView; import static androidx.test.espresso.action.ViewActions.click; import static androidx.test.espresso.action.ViewActions.closeSoftKeyboard; import static androidx.test.espresso.action.ViewActions.replaceText; import static androidx.test.espresso.action.ViewActions.scrollTo; import static androidx.test.espresso.assertion.ViewAssertions.matches; import static androidx.test.espresso.contrib.RecyclerViewActions.actionOnItemAtPosition; import static androidx.test.espresso.matcher.ViewMatchers.assertThat; import static androidx.test.espresso.matcher.ViewMatchers.hasMinimumChildCount; import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed; import static androidx.test.espresso.matcher.ViewMatchers.withClassName; import static androidx.test.espresso.matcher.ViewMatchers.withId; import static androidx.test.espresso.matcher.ViewMatchers.withText; import static com.mystihgreeh.mareu.RecyclerViewItemCountAssertion.withItemCount; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.notNullValue; @RunWith(AndroidJUnit4.class) public class ReunionListTest { // This is fixed private static int ITEMS_COUNT_ONE = 5; private static int ITEMS_COUNT_TWO = 4; private int positionTest = 0; private String roomName = "Mario"; // Can be any other room name private ReunionApiService service = Injection.getNewInstanceApiService(); @Rule public ActivityTestRule<ReunionList> mActivityRule = new ActivityTestRule<>(ReunionList.class); @Before public void setUp() { service = Injection.getNewInstanceApiService(); ReunionList activity = mActivityRule.getActivity(); assertThat(activity, notNullValue()); } /**Test that the recyclerview display at least one item in the list * */ @Test public void ReunionListShouldNotBeEmpty() { onView(allOf(withId(R.id.recyclerView), isDisplayed())).check(matches(hasMinimumChildCount(1))); } /** When we click on the reunion, the reunion details display */ @Test public void reunionProfileDisplayOnClick() { onView(allOf(withId(R.id.recyclerView),isDisplayed())).perform(actionOnItemAtPosition(0, click())); onView(withId(R.id.reunion_details)).check(matches(isDisplayed())); } @Test public void newReunionIsCreated() { onView(allOf(withId(R.id.recyclerView), isDisplayed())).check(withItemCount(ITEMS_COUNT_TWO)); onView(withId(R.id.addButton)).perform(click()); onView(withId(R.id.reunion_object)).check(matches(isDisplayed())); onView(withId(R.id.date)).perform(click()); onView(withText("OK")).perform(click()); onView(withId(R.id.time)).perform(click()); onView(withText("OK")).perform(click()); onView(withId(R.id.reunion_object)).perform(scrollTo(), replaceText("Reunion Z"), closeSoftKeyboard()); onView(withId(R.id.emails)).perform(scrollTo(), replaceText("charlotte@lamzone.fr"), closeSoftKeyboard()); onView(withId(R.id.save)).perform(click()); onView(allOf(withId(R.id.recyclerView), isDisplayed())).check(withItemCount(ITEMS_COUNT_TWO + 1)); } /** When we delete an item, the item is no more shown */ @Test public void ReunionListDeleteAction() { // Given : we remove the element at position 2 onView(allOf(withId(R.id.recyclerView), isDisplayed())).check(withItemCount(ITEMS_COUNT_ONE)); //When perform a click on the delete icon onView(allOf(withId(R.id.recyclerView), isDisplayed())).perform(RecyclerViewActions.actionOnItemAtPosition(1, new DeleteViewAction())); //Then the number of element is now 3 onView(allOf(withId(R.id.recyclerView), isDisplayed())).check(withItemCount(ITEMS_COUNT_ONE - 1)); } /** When we click on the room filter, the reunions are filtered by room */ //Filter by location @Test public void MeetingList_onLocationFilterClick_shouldFilterList() { // Filter a room onView(withId(R.id.filter_menu)).perform(click()); onView(withText("Filter by room")).perform(click()); onView(withText(roomName)).perform(click()); onView(withText("OK")).perform(click()); //Only the reunion with the same room as the one filtered is displayed onView(withId(R.id.recyclerView)).check(withItemCount(0)); } /** When we click on the date filter, the reunions are filtered by date */ @Test public void MeetingList_onDateFilterClick_shouldFilterList() { // Filter a date onView(withId(R.id.filter_menu)).perform(click()); onView(withText("Filter by date")).perform(click()); onView(withClassName(Matchers.equalTo(DatePicker.class.getName()))).perform(PickerActions.setDate(2020, 9, 6)); onView(withText("OK")).perform(click()); // Count the number of reunion with the same date int filterCount = 0; for (int i = 0; i< service.getReunions().size(); i++ ){ String meetingDate = (String) DateFormat.format("yyyy/MM/dd", service.getReunions().get(i).getDate()); if (meetingDate.equals("2020/09/06")) filterCount++; } // Only the reunion with the same date as the one filtered is displayed onView(withId(R.id.recyclerView)).check(withItemCount(filterCount)); } /** * When we click on the reset filter, all the filters are reset */ @Test public void MeetingList_onClearFilterClick_shouldFilterList() { // Filtering a room onView(withId(R.id.filter_menu)).perform(click()); onView(withText("Filter by room")).perform(click()); onView(withText(roomName)).perform(click()); onView(withText("OK")).perform(click()); // Filtering a date onView(withId(R.id.filter_menu)).perform(click()); onView(withText("Filter by date")).perform(click()); onView(withClassName(Matchers.equalTo(DatePicker.class.getName()))).perform(PickerActions.setDate(2020, 9, 6)); onView(withText("OK")).perform(click()); // Cleaning filters onView(withId(R.id.filter_menu)).perform(click()); onView(withText("Reset filters")).perform(click()); // All the meeting display again onView(withId(R.id.recyclerView)).check(withItemCount(4)); } }
PHP
UTF-8
2,379
3.15625
3
[ "MIT" ]
permissive
<?php /** * Created by PhpStorm. * User: Admin * Date: 2016-02-09 * Time: 00:48 */ namespace App\Services; use App\Services\vertex; class VertexCalculatorService { public function testVertex() { $v0 = new vertex(0); $v1 = new vertex(1); $v2 = new vertex(2); $v3 = new vertex(3); $v4 = new vertex(4); $v5 = new vertex(5); $list0 = new SplDoublyLinkedList(); $list0->push($v1); $list0->push($v3); $list0->rewind(); $list1 = new SplDoublyLinkedList(); $list1->push($v0); $list1->push($v2); $list1->rewind(); $list2 = new SplDoublyLinkedList(); $list2->push($v1); $list2->push($v3); $list2->push($v4); $list2->rewind(); $list3 = new SplDoublyLinkedList(); $list3->push($v1); $list3->push($v2); $list3->rewind(); $list4 = new SplDoublyLinkedList(); $list4->push($v2); $list4->push($v5); $list4->rewind(); $list5 = new SplDoublyLinkedList(); $list5->push($v4); $list5->rewind(); $adjacencyList = array( $list0, $list1, $list2, $list3, $list4, $list5, ); calcDistances($v0, $adjacencyList); print_r($adjacencyList); } public function calcDistances(vertex $start, &$adjLists) { // define an empty queue $q = array(); // push the starting vertex into the queue array_push($q, $start); // color it gray $start->color = 'gray'; // mark the distance to it 0 $start->distance = 0; while ($q) { // 1. pop from the queue $t = array_pop($q); // 2. foreach poped item find it's adjacent white vertices $l = $adjLists[$t->key]; while ($l->valid()) { // 3. mark them gray, increment their length with one from their parent if ($l->current()->color == 'white') { $l->current()->color = 'gray'; $l->current()->distance = $t->distance + 1; // 4. push them to the queue array_push($q, $l->current()); } $l->next(); } } } }
Python
UTF-8
608
3.359375
3
[]
no_license
from tkinter import * root=Tk() canvas_width=800 canvas_height=400 root.geometry(f"{canvas_width}x{canvas_height}") root.title("KV's GUI") can_widget= Canvas(root,width=canvas_width,height=canvas_height) can_widget.pack() #line (x1,x2,y1,y2) can_widget.create_line(0,0,800,400,fill="red") can_widget.create_line(0,400,800,0,fill="red") # Order=coordinates of top left & coordinates of bottom right can_widget.create_rectangle(3,5,700,300,fill="green") can_widget.create_text(200,200,text="Python") #we give coordinates of a rectangle for oval can_widget.create_oval(344,233,244,355) root.mainloop()
Java
UTF-8
3,358
2.15625
2
[]
no_license
package com.huashu.monitor.controller; import com.huashu.monitor.common.ServerResponse; import com.huashu.monitor.pojo.User; import com.huashu.monitor.service.UserService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authz.annotation.RequiresRoles; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; /** * @Description * @auther supermao * @create 2021-03-26 13:49 */ @Api(tags = "用户管理模块") @RestController @RequestMapping("/user/") @Slf4j public class UserController { @Autowired private UserService userService; /** * 用户注册 * * @param user * @return */ @GetMapping("register") @ApiOperation(value = "用户注册", notes = "参数: ") public ServerResponse<String> register(User user) { userService.register(user); return ServerResponse.createBySuccessMessage("注册成功"); } /** * 退出登录 * * @return */ @GetMapping("logout") @ApiOperation(value = "用户登出", notes = "参数: ") public ServerResponse<String> logout() { SecurityUtils.getSubject().logout(); return ServerResponse.createBySuccessMessage("退出登录成功"); } /** * 登录 * * @param username * @param password * @return */ @GetMapping("login") @ApiOperation(value = "用户登录", notes = "参数: ") public ServerResponse<String> login(String username, String password) { Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(username, password); token.setRememberMe(true); subject.login(token); return ServerResponse.createBySuccess("登录成功", "data"); } @ApiOperation(value = "更新用户信息", notes = "参数:") @RequiresRoles("user") @GetMapping(value = "update_user_info") public ServerResponse updateUserInfo() { return null; } @ApiOperation(value = "获取当前登录用户信息", notes = "参数:") @RequiresRoles("user") @GetMapping(value = "get_user_info") public ServerResponse getUserInfo() { return null; } @ApiOperation(value = "按类型分页查询用户列表", notes = "参数:") @RequiresRoles("admin") @GetMapping(value = "get_user_list") public ServerResponse getUserList() { return null; } @ApiOperation(value = "批量添加用户", notes = "参数:") @RequiresRoles("admin") @GetMapping(value = "batch_insert_user") public ServerResponse batchInsertUser() { return null; } @ApiOperation(value = "添加用户", notes = "参数:") @RequiresRoles("admin") @GetMapping(value = "insert_user") public ServerResponse insertUser() { return null; } // @GetMapping("index") // @RequiresRoles("admin") // @ApiOperation(value = "测试用户权限", notes = "参数: null") // public ServerResponse<String> testUserRoles() { // return ServerResponse.createBySuccess("有权限", "data"); // } }
JavaScript
UTF-8
1,369
2.8125
3
[]
no_license
import m from 'mithril' var todo = {} todo.Todo = function (data) { this.description = m.prop(data.description) this.done = m.prop(false) } todo.TodoList = Array // define the view-model todo.vm = { init: function () { todo.vm.list = new todo.TodoList() todo.vm.description = m.prop('') todo.vm.add = function () { if (todo.vm.description()) { todo.vm.list.push(new todo.Todo({description: todo.vm.description()})) todo.vm.description('') } } } } todo.vm.init() todo.vm.description('Write code') todo.vm.add(todo.vm.description) console.log('Todos: ' + todo.vm.list.length) // define controller todo.controller = function () { todo.vm.init() } // create the view todo.view = function () { return [ m('input', {onchange: m.withAttr('value', todo.vm.description), value: todo.vm.description()}), m('button', {onclick: todo.vm.add}, 'Add'), m('table', [ todo.vm.list.map(function (task, index) { return m('tr', [ m('td', [ m('input[type=checkbox]', {onclick: m.withAttr('checked', task.done), checked: task.done()}) ]), m('td', {style: {textDecoration: task.done() ? 'line-through' : 'none'}}, task.description()) ]) }) ]) ] } // m.mount(document.getElementById('app'), {controller: todo.controller, view: todo.view})
Java
UTF-8
8,282
2.390625
2
[]
no_license
package ffm.geok.com.uitls; import android.content.Context; import android.os.Environment; import android.text.format.DateUtils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonIOException; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.google.gson.JsonSyntaxException; import com.google.gson.stream.JsonReader; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.lang.reflect.Type; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:16/9/28 * 描 述: * 修订历史: * ================================================ */ public class Convert { private static Gson create() { return GsonHolder.gson; } private static Gson createFormat() { return GsonFormatHolder.gson; } private static class GsonHolder { private static Gson gson = new Gson(); } private static class GsonFormatHolder { private static Gson gson = new GsonBuilder() .setDateFormat(ffm.geok.com.uitls.DateUtils.pattern_full) .registerTypeAdapter(Integer.class, new IntegerDefault0Adapter()) .registerTypeAdapter(int.class, new IntegerDefault0Adapter()) .registerTypeAdapter(Double.class, new DoubleDefault0Adapter()) .registerTypeAdapter(double.class, new DoubleDefault0Adapter()) .registerTypeAdapter(Long.class, new LongDefault0Adapter()) .registerTypeAdapter(long.class, new LongDefault0Adapter()) .create(); } public static <T> T fromJson(String json, Class<T> type) throws JsonIOException, JsonSyntaxException { return create().fromJson(json, type); } public static <T> T fromJson(String json, Type type) { return create().fromJson(json, type); } public static <T> T fromJsonFormat(String json, Type type) { return createFormat().fromJson(json, type); } public static <T> T fromJson(JsonReader reader, Type typeOfT) throws JsonIOException, JsonSyntaxException { return create().fromJson(reader, typeOfT); } public static <T> T fromJson(Reader json, Class<T> classOfT) throws JsonSyntaxException, JsonIOException { return create().fromJson(json, classOfT); } public static <T> T fromJson(Reader json, Type typeOfT) throws JsonIOException, JsonSyntaxException { return create().fromJson(json, typeOfT); } public static String toJson(Object src) { return create().toJson(src); } public static String toJson(Object src, Type typeOfSrc) { return create().toJson(src, typeOfSrc); } /** * 解析json 文件 * @param context * @param jsonFile * @return */ public static String parseJsonFile(Context context, String jsonFile) { String result = null; try { InputStreamReader inputStreamReader = new InputStreamReader(context.getAssets().open(jsonFile), "utf-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String line; StringBuilder stringBuilder = new StringBuilder(); while((line = bufferedReader.readLine()) != null) { stringBuilder.append(line); } bufferedReader.close(); inputStreamReader.close(); result = stringBuilder.toString(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } result = result.replaceAll("\\\\", ""); return result ; } /*异常处理int*/ public static class IntegerDefault0Adapter implements JsonSerializer<Integer>, JsonDeserializer<Integer> { @Override public Integer deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { try { if (json.getAsString().equals("") || json.getAsString().equals("null")) {//定义为int类型,如果后台返回""或者null,则返回0 return 0; } } catch (Exception ignore) { } try { return json.getAsInt(); } catch (NumberFormatException e) { throw new JsonSyntaxException(e); } } @Override public JsonElement serialize(Integer src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src); } } /*异常处理long*/ public static class LongDefault0Adapter implements JsonSerializer<Long>, JsonDeserializer<Long> { @Override public Long deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { try { if (json.getAsString().equals("") || json.getAsString().equals("null")) {//定义为long类型,如果后台返回""或者null,则返回0 return 0l; } } catch (Exception ignore) { } try { return json.getAsLong(); } catch (NumberFormatException e) { throw new JsonSyntaxException(e); } } @Override public JsonElement serialize(Long src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src); } } /*异常处理double*/ static class DoubleDefault0Adapter implements JsonSerializer<Double>, JsonDeserializer<Double> { @Override public Double deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { try { if (json.getAsString().equals("") || json.getAsString().equals("null")) {//定义为double类型,如果后台返回""或者null,则返回0.00 return 0.00; } } catch (Exception ignore) { } try { return json.getAsDouble(); } catch (NumberFormatException e) { throw new JsonSyntaxException(e); } } @Override public JsonElement serialize(Double src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src); } } /** * 保存json到本地 * @param filename * @param content */ public static boolean saveToSDCard(String path,String filename, String content) { boolean result = false; try { boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); //判断sd卡是否存在 File foder = null; if (sdCardExist) { foder = new File(Environment.getExternalStorageDirectory(), path); } else { foder = new File(Environment.getDownloadCacheDirectory(), path); } if (!foder.exists()) { foder.mkdirs(); } File saveFile = new File(foder, filename); L.d("saveFile = " + saveFile.getAbsolutePath()); if (!saveFile.exists()) { saveFile.createNewFile(); } OutputStream out = new FileOutputStream(saveFile); out.write(content.getBytes()); out.close(); result = true; L.d("json文件保存成功"); } catch (IOException e) { e.printStackTrace(); L.e("json文件保存失败"); result = false; } return result; } }
C
UTF-8
1,001
3.109375
3
[ "BSD-3-Clause" ]
permissive
#include <stdio.h> #include <string.h> #include "ziplist.h" /*列表键和哈希键的应用*/ int main(int argc, char const *argv[]) { unsigned char *zl = ziplistNew(); unsigned char*str = (unsigned char*)"b"; ziplistPush(zl,str,strlen((char*)str),0); unsigned char*str2 = (unsigned char*)"c"; ziplistPush(zl,str2,strlen((char*)str2),1); unsigned char*str3 = (unsigned char*)"de"; ziplistPush(zl,str3,strlen((char*)str3),1); unsigned char*str4 = (unsigned char*)"f"; ziplistPush(zl,str4,strlen((char*)str4),1); unsigned int len = ziplistLen(zl); printf("%d\n",len); unsigned char *s = zl;int i = 0; for (i = 0 ; s[i] != 0xff; i++) { printf("%x ",s[i]); } printf("length:%d\n",i); return 0; } /* <zlbytes> <zltail> <zllen> <entry> <entry> ... <entry> <zlend> */ /* |zlbytes| |<zltail>| |<zllen>| |--b--| |--c--| |---de---| |--f--| |zlend| 18 0 0 0 14 0 0 0 4 0 0 1 62 3 1 63 3 2 64 65 4 1 66 0xff */
Python
UTF-8
231
3.4375
3
[]
no_license
def missingNumbers(arr): nums = set(arr) missing = [] for num in range(0, len(arr)+1): if num not in nums: missing.append(num) return missing print(missingNumbers([1, 2, 8, 3, 4, 5, 3, 3]))
C++
UTF-8
2,772
3.078125
3
[ "MIT" ]
permissive
/*793 - Network Connections*/ #include <bits/stdc++.h> using namespace std; void makeSet(vector <int>& padre, vector <int>& rango, int tam); bool sameArbol(vector <int>& padre, int x, int y); void unionByRank(vector <int>& padre, vector <int>& rango, int x, int y); int find(vector <int>& padre, int x); int totalArboles(vector <int>& padre, int tam); int totalVertices(vector <int>& padre, int root, int tam); int arbolesConMasDeUnVertice(vector <int>& padre, int tam); int main(){ int cases; int k = 1; cin>>cases; while(cases--){ if(k>1) cout<<'\n'; int computers; cin>>computers; string line; cin.ignore(); int good = 0; int bad = 0; vector <int> padre; vector <int> rango; for (int i = 0; i < computers; ++i) { padre.push_back(i); rango.push_back(0); } while(getline(cin, line) and line.size() > 0){ istringstream in(line); char letra; int x, y; in>>letra>>x>>y; x--; y--; if(letra == 'c') if(x != y){ unionByRank(padre, rango, x, y); } if(letra == 'q'){ if(find(padre, x) == find(padre, y)) good++; else bad++; } } padre.clear(); rango.clear(); cout<<good<<','<<bad<<'\n'; k++; } return 0; } void makeSet(vector <int>& padre, vector <int>& rango, int tam){ for (int i = 0; i < tam; ++i) { padre[i] = i; rango[i]= i; } } int find(vector <int>& padre, int x){ if( x == padre[x]) return x; else return padre[x] = find(padre, padre[x]); } bool sameArbol(vector <int>& padre, int x, int y){ if(find(padre, x) == find(padre, y)) return true; else return false; } void unionByRank(vector <int>& padre, vector<int>& rango, int x, int y){ int rootX = find(padre, x); int rootY = find(padre, y); if(rango[rootX] > rango[rootY]){ padre[rootY] = rootX; } else{ padre[rootY] = rootX; if(rango[rootX] == rango[rootY]) rango[rootX]++; } } int totalArboles(vector <int>& padre, int tam){ int numArb = 0; for (int i = 0; i < tam; ++i) { if(padre[i] == i) numArb++; } return numArb; } int arbolesConMasDeUnVertice(vector <int>& padre, int tam){ int numArb = 0; for (int i = 0; i < tam; ++i) { if(padre[i] == i){ if(totalVertices(padre, i, tam) > 1){ numArb++; } } } return numArb; } /* original, modifiqué la de arriba para que solo diera arboles con mas de un vertice */ /*regresa el total de nodos de una raiz específica*/ int totalVertices(vector <int>& padre, int root, int tam){ int tot; for (int i = 0; i < tam; ++i) { if(find(padre, padre[i]) == root) tot++; } return tot; }
TypeScript
UTF-8
6,068
2.65625
3
[]
no_license
/** * Cordova Plugins Abstract * npm i @types/cordova -D */ // import 'cordova'; import {TypeInfo} from '../Core/TypeInfo'; import {EAbort} from '../Core/Exception'; declare var window: any; declare var navigator: any; export type TSuccessfulCallback = (msg?: any) => void; export type TFailureCallback = (msg?: any) => void; export type TPluginFunction = (...argv: any[]) => void; export class ECordovaPlugin extends EAbort { constructor(msg?: string) { if (TypeInfo.Assigned(msg)) super(msg); else super('e_cordova_plugin'); } } export class ECordovaPluginNotInstalled extends ECordovaPlugin { constructor() { super('e_cordova_plugin_not_installed'); } } export class TCordovaPlugin { static readonly Name: string = ''; static readonly Repository?: string; static get IsPluginInstalled(): boolean { return TypeInfo.Assigned(this.Instance); } static get Instance(): any { if (this.Name === '') { console.error(this.name.toString() + ' has no Name defined.'); return undefined; } if (! TypeInfo.Assigned(this._Instance)) { this._Instance = this._GetInstance(this.Name); if (! TypeInfo.Assigned(this._Instance)) { if (TypeInfo.Assigned(this.Repository)) console.error(this.Repository + ' is not installed.'); else console.error('cordova plugin: ' + this.Name + ' is not installed.'); } else this.OnCreateInstance(this._Instance); } return this._Instance; } static async InstancePromise(): Promise<any> { const Instance = this.Instance; if (! TypeInfo.Assigned(Instance)) throw new ECordovaPluginNotInstalled(); else return Instance; } static GetProperty<T>(propname: string): T { const Instance = this.Instance; if (TypeInfo.Assigned(Instance)) return Instance[propname]; else return undefined; } static CallFunction<T>(func: string, ...argv: any[]): T { const Instance = this.Instance; if (TypeInfo.Assigned(Instance)) { const PluginFunction: Function = Instance[func]; return PluginFunction.call(Instance, ...argv); } } static async CallbackToPromise<T>(func: string): Promise<T> { const Instance = await this.InstancePromise(); return new Promise<T>((resolve, reject) => { const PluginFunction: Function = Instance[func]; PluginFunction.call(this, succ, err); function succ(msg: any): void { resolve(msg); } function err(msg: any): void { if (TypeInfo.IsString(msg)) { console.warn('cordova plugin error: ' + msg); reject(new ECordovaPlugin(msg)); } else if (msg instanceof Error) { console.warn('cordova plugin error: ' + msg.message + ' error class: ' + typeof msg); reject(msg); } } }); } static async CallbackToPromise_RightParam<T>(func: string, ...argv: any[]): Promise<T> { const Instance = await this.InstancePromise(); return new Promise<T>((resolve, reject) => { argv = [succ, err].concat(argv); const PluginFunction: Function = Instance[func]; PluginFunction.call(this, ...argv); function succ(msg: any): void { resolve(msg); } function err(msg: any): void { if (TypeInfo.IsString(msg)) { console.warn('cordova plugin error: ' + msg); reject(new ECordovaPlugin(msg)); } else if (msg instanceof Error) { console.warn('cordova plugin error: ' + msg.message + ' error class: ' + typeof msg); reject(msg); } } }); } static async CallbackToPromise_LeftParam<T>(func: string, ...argv: any[]): Promise<T> { const Instance = await this.InstancePromise(); const PluginFunction: Function = Instance[func]; return new Promise<T>((resolve, reject) => { argv.push(succ, err); PluginFunction.call(this, ...argv); function succ(msg: any): void { resolve(msg); } function err(msg: any): void { if (TypeInfo.IsString(msg)) { console.warn('cordova plugin error: ' + msg); reject(new ECordovaPlugin(msg)); } else if (msg instanceof Error) { console.warn('cordova plugin error: ' + msg.message + ' error class: ' + typeof msg); reject(msg); } } }); } protected static _GetInstance(PluginName: string): any { if (! TypeInfo.Assigned(window.cordova)) return undefined; let Plugin = undefined; if (TypeInfo.Assigned(window.cordova.plugins)) Plugin = window.cordova.plugins[PluginName]; if (! TypeInfo.Assigned(Plugin)) Plugin = window.cordova[PluginName]; if (! TypeInfo.Assigned(Plugin)) Plugin = window[PluginName]; if (! TypeInfo.Assigned(Plugin)) Plugin = navigator[PluginName]; return Plugin; } protected static OnCreateInstance(Instance: any): void { } private static _Instance: any = undefined; protected constructor() { } }
Swift
UTF-8
1,857
2.734375
3
[]
no_license
// // ViewController.swift // DieuHuongManHinh // // Created by Quynh on 3/24/20. // Copyright © 2020 Quynh. All rights reserved. // import UIKit class ViewController: UIViewController, UIAdaptivePresentationControllerDelegate { let name : String = "" override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let screen2 = segue.destination as! Screen2ViewController // screen2.presentationController?.delegate = self screen2.isModalInPresentation = true screen2.text = "Hello Screen 2" } @IBAction func unWindToVC(_ sender: UIStoryboardSegue){ print("abc") if sender.source is Screen2ViewController { if let sen = sender.source as? Screen2ViewController { print(sen.name) } } } // func presentationControllerDidAttemptToDismiss(UIPresentationController) // Function này khi user cố gắng swipe để dismiss Present ViewController // func presentationControllerDidDismiss(UIPresentationController) // Func này được gọi khi Present ViewController đã dismiss // func presentationControllerShouldDismiss(UIPresentationController) -> Bool // Function này để chúng ta có thể set điều kiện để dismiss Present ViewController // func presentationControllerWillDismiss(UIPresentationController) // Func này được gọi trước khi Present ViewController được dismiss func presentationControllerDidAttemptToDismiss(_ presentationController: UIPresentationController) { print("abc") } func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { print("Đã dismiss") } }
Python
UTF-8
662
3.109375
3
[]
no_license
import time import multiprocessing def deposit(balance,lock): for i in range(1000): lock.acquire() val = balance.value val += 1 time.sleep(.01) balance.value = val lock.release() def withdraw(balance,lock): for i in range(1000): lock.acquire() val2 = balance.value val2 -= 1 time.sleep(.01) balance.value = val2 lock.release() if __name__ == '__main__': balance = multiprocessing.Value('i', 200) lock = multiprocessing.Lock() d = multiprocessing.Process(target=deposit, args=(balance,lock)) w = multiprocessing.Process(target=withdraw, args=(balance,lock)) d.start() w.start() d.join() w.join() print(balance.value)
Shell
UTF-8
4,335
3.75
4
[ "MIT" ]
permissive
#!/bin/bash function heketi:init_instance_id() { HEKETI_INSTANCE=$1 } function heketi:get_config_file() { local instance_id=$1 local target=$2 info "heketi" "Downloading the default heketi json config..." gcloud compute scp $instance_id:/etc/heketi/heketi.json $target } function heketi:put_config_file() { local instance_id=$1 local target=$2 info "heketi" "Uploading heketi json config..." gcloud compute scp "$target" $instance_id:./heketi.json gcloud compute ssh $instance_id --command "sudo cp -v $HEKETI_KEY_DIR/heketi.json{,bak} \ && sudo cp -v heketi.json $HEKETI_KEY_DIR/heketi.json \ && sudo chown heketi: $HEKETI_KEY_DIR/heketi.json" info "heketi" "Restarting heketi server..." heketi:start_on "$instance_id" } function heketi:patch_config_file() { local target=$1 local patch_file=$(mktemp /tmp/heketi-json-patch.XXXXXX) info "heketi" "Generating json patch file..." cat <<PATCH > $patch_file [ { "op": "replace", "path": "/glusterfs/sshexec/keyfile", "value": "$HEKETI_KEY_DIR/id_rsa" }, { "op": "replace", "path": "/glusterfs/sshexec/user", "value": "root" }, { "op": "replace", "path": "/glusterfs/sshexec/port", "value": "22" }, { "op": "replace", "path": "/glusterfs/sshexec/fstab", "value": "/etc/fstab" }, { "op": "replace", "path": "/glusterfs/executor", "value": "ssh" }, { "op": "replace", "path": "/glusterfs/loglevel", "value": "debug" }, { "op": "replace", "path": "/glusterfs/db", "value": "/var/lib/heketi/heketi.db" }, { "op": "replace", "path": "/jwt/user/key", "value": "$HEKETI_JWT_USER_SECRET" }, { "op": "replace", "path": "/jwt/admin/key", "value": "$HEKETI_JWT_ADMIN_SECRET" } ] PATCH info "heketi" "Patching heketi json config..." local tmp_config_file=$(mktemp /tmp/heketi-json.XXXXX) cat $target | json-patch -p "$patch_file" \ | json_pp > $tmp_config_file mv $tmp_config_file $target } function heketi:selfcheck() { local instance_id=$1 info "heketi" "Checking heketi service..." gcloud compute ssh $instance_id --command "curl -s $instance_id:8080/hello" } function heketi_get_external_ip() { local instance_id=$1 info "heketi" "Getting external IP from the NAT network interface" local ip=$(gcloud:instance_info "$instance_id" | jq --raw-output '.networkInterfaces[0].accessConfigs[0].natIP') echo $ip } function heketi:start_on() { local instance_id=$1 info "$instance_id: Starting heketi..." gcloud:ssh_command "$instance_id" "[[ -f /etc/heketi/container_id ]] \ && sudo docker stop heketi5 \$(/etc/heketi/container_id) \ && sudo docker rm heketi5 \$(/etc/heketi/container_id) \ || true" gcloud:ssh_command "$instance_id" "\ sudo mkdir -p /var/lib/heketi /etc/heketi \ && sudo docker run --detach --publish 8080:8080 \ --name heketi5 \ --restart=always \ --privileged \ --volume /etc/heketi:/etc/heketi \ --volume /var/lib/heketi:/var/lib/heketi \ heketi/heketi:5 | sudo tee /etc/heketi/container_id" } function heketi:install_on() { local instance_id=$1 local heketi_version=v5.0.1 local heketi_arch=amd64 local heketi_os=linux local heketi_tarfile=heketi-${heketi_version}.${heketi_os}.${heketi_arch}.tar.gz info "$instance_id: Installing docker..." gcloud:ssh_command "$instance_id" "sudo yum update -y && sudo yum install -y --quiet docker && sudo systemctl start docker" info "$instance_id: Installing heketi..." gcloud:ssh_command "$instance_id" "([[ ! -f $heketi_tarfile ]] && curl -L -O https://github.com/heketi/heketi/releases/download/${heketi_version}/heketi-${heketi_version}.${heketi_os}.${heketi_arch}.tar.gz || true) \ && tar xvzf heketi-${heketi_version}.${heketi_os}.${heketi_arch}.tar.gz \ && sudo rsync -av heketi/ /etc/heketi/" # we can't install heketi via yum now... # gcloud:ssh_command "$instance_id" "sudo yum update -y && sudo yum -y --quiet install heketi heketi-client" } function gcloud:instance_add_tag() { local instance_id=$1 shift info "$instance_id" "Adding tags {$*}..." gcloud compute instances add-tags "$instance_id" --tags "$*" --zone "$ZONE" }
Markdown
UTF-8
1,252
3.359375
3
[]
no_license
# COP-mastermind Mastermind or Master Mind is a code-breaking game for two players. The modern game with pegs was invented in 1970 by Mordecai Meirowitz, an Israeli postmaster and telecommunications expert. It resembles an earlier pencil and paper game called Bulls and Cows that may date back a century or more. (Source Wikipedia) ## Rules 1. The first player will select 4 letters from A to F. Letters can not be duplicated but there will always be exactly 4. 2. The second player has to guess the code. 2. The Mastermind will return the following feedback: - Number of pins that are both the right letter and position - Number of pins that are correct in letter but in the wrong position ## Example 1 Secret ABCD and guess ABCD must be evaluated to: rightPosition = 4, wrongPosition = 0. All letters are guessed correctly in respect to their positions. ## Example 2 Secret ABCD and guess CDBA must be evaluated to: rightPosition = 0, wrongPosition = 4. All letters are guessed correctly, but none has the right position. ## Example 3 Secret ABCD and guess ABDC must be evaluated to: rightPosition = 2, wrongPosition = 2. A and B letters and their positions are guessed correctly. C and D letters are guessed correctly, but their positions are wrong.
PHP
UTF-8
1,737
3.4375
3
[]
no_license
<?php echo "Veuillez entrer au moins 2 lettres séparées par un espace: ".PHP_EOL; $input = readline(); $pattern = '/[[a-zA-Z]{1}\s]*/'; if(!empty(trim($input))){ //echo $input; $result = preg_grep($pattern, explode("\n", trim($input))); // print_r($result); if(!empty($result)){ // echo 'yesssssssss'; $choixLettres = explode(" ", $result[0]); $countLetters = array_count_values($choixLettres); foreach($choixLettres as $index=>$item){ if($countLetters[$item] >=2 || is_numeric($item) || (is_string($item) && strlen($item) > 1)){ echo "Erreur:: N'accepte que des lettres et pas de lettre répétée"; exit; } } print_r($choixLettres); $nbLettres = $compteur = count($choixLettres); $nbPossibilites = 1; while($compteur >=1){ $nbPossibilites *= $compteur; $compteur--; } echo "---------------------------------- $nbLettres lettres donnent $nbPossibilites possibilités ----------------------------------".PHP_EOL; $combinaison = strval(implode("", $choixLettres)); $listCombinaisons[] = $combinaison; while(count($listCombinaisons) < $nbPossibilites){ $combinaison = str_shuffle($combinaison); if(!in_array($combinaison, $listCombinaisons)){ //echo '- '.$combinaison.PHP_EOL; $listCombinaisons[] = $combinaison; } } sort($listCombinaisons); echo "<pre>"; print_r($listCombinaisons); echo"</pre>"; }else{echo "Erreur:: Veuillez entrer que des lettres séparés par un espace: ".PHP_EOL;} }
Go
UTF-8
1,337
2.703125
3
[]
no_license
package main import ( //"crypto/tls" "log" "net" "runtime" flag "github.com/spf13/pflag" ) var bindAddr string var backendAddr string var certFile string var keyFile string func init() { flag.StringVar(&bindAddr, "l", ":443", "bind address") flag.StringVar(&backendAddr, "b", ":8082", "backend address") flag.StringVar(&certFile, "c", "cert.pem", "TLS certificate path") flag.StringVar(&keyFile, "k", "key.pem", "TLS key path") } func main() { flag.Parse() runtime.GOMAXPROCS(runtime.NumCPU()) log.Printf("Handling connections on %s", bindAddr) log.Printf("Proxying connections to %s", backendAddr) // bind a port to handle TLS connections l, err := net.Listen("tcp", bindAddr) if err != nil { log.Printf("Failed to bind on address %s: %s", bindAddr, err) } log.Printf("Serving connections on %v", l.Addr()) for { // accept next connection to this frontend conn, err := l.Accept() if err != nil { log.Printf("Failed to accept new connection for %v", conn.RemoteAddr()) if e, ok := err.(net.Error); ok { if e.Temporary() { continue } } log.Printf("cannot continue here, terminating due to error: %s", err) panic(err) } log.Printf("Accepted new connection from %v", conn.RemoteAddr()) // proxy the connection to an backend go proxyConnection(conn, backendAddr) } }
C#
UTF-8
1,927
3.65625
4
[]
no_license
//p.482 delegate/Landa; 변수처럼 사용하는 method다. /* 1. products.Sort(SortWithPrice); private static int SortWithPrice(Product x, Product y){ return x.Price.CompareTo(y.Price); } 2.delegate p.484 products.Sort(delegate(Product x, Product y){ return x.Price.CompareTo(y.Price); } 3.Landa- p.486 products.Sort((x, y) => x.Price.CompareTo(y.Price)); */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DElegateRand { class Product { public string Name { get; set; } public int Price { get; set; } public Product(string name, int price) { Name = name; Price = price; } public override string ToString() //자동 ToString 호출 되도록 { return Name + " : " + Price; } } class Program { static void Main(string[] args) { List<Product> products = new List<Product>(); products.Add(new Product("감자", 500)); products.Add(new Product("사과", 700)); products.Add(new Product("고구마", 400)); products.Add(new Product("배추", 600)); products.Add(new Product("상추", 300)); // products.Sort(SortWithPrice); //변수?? -- ???함수호출;SortWithPrice()??? //무명 delegate p.486 products.Sort((x, y) => x.Price.CompareTo(y.Price)); foreach (var item in products) { Console.WriteLine( item ); //자동 ToString 호출 되도록 } } /* private static int SortWithPrice(Product x, Product y) //변수 { return x.Price.CompareTo(y.Price); //오른자순 } */ } }
C
UTF-8
962
3.46875
3
[]
no_license
#include<stdio.h> #include<math.h> /*一步一步来,先筛选出最大值作比较,用count来进行最终判断*/ int main() { int a[7]; int count = 0,max=0,boom_num=0; for (int i = 1; i < 7; i++) { /* code */ scanf("%d",&a[i]); } max = a[1]; for (int i = 1; i < 5; i++) { /* code */ if (a[i] > max) { /* code */ max = a[i]; } } for (int i = 1; i < 5; i++) { /* code */ if ((max - a[i]) > a[6] || a[i]<a[5]) { /* code */ count++; boom_num = i; } } if (count==0) { printf("Normal"); } else if (count == 1) { /* code */ printf("Warning: please check #%d!",boom_num); } else if (count >= 2) { /* code */ printf("Warning: please check all the tires!"); } return 0; }
Java
UTF-8
438
1.828125
2
[]
no_license
package com.knowledge.point.rabbitmq; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class RabbitController { @Autowired private RabbitMqSender rabbitMqSender; @RequestMapping("/rabbit") public void TestRabbitMQ(){ rabbitMqSender.send(); } }
Python
UTF-8
1,992
3.796875
4
[ "MIT" ]
permissive
#!/usr/bin/env python3 """ Author : schackartk Date : 2019-02-21 Purpose: Grad HW 5, find the winner """ import argparse import sys # -------------------------------------------------- def get_args(): """get command-line arguments""" parser = argparse.ArgumentParser( description='Tic-Tac-Toe board', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( 'positional', metavar='STATE', help='State of the board') return parser.parse_args() # -------------------------------------------------- def warn(msg): """Print a message to STDERR""" print(msg, file=sys.stderr) # -------------------------------------------------- def die(msg='Something bad happened'): """warn() and exit with error""" warn(msg) sys.exit(1) # -------------------------------------------------- def main(): """Make a jazz noise here""" args = get_args() state = args.positional cells = [0,1,2,3,4,5,6,7,8,9] acc_char = {i:0 for i in '.-XO'} count = 0 for i, char in enumerate(state): if char in acc_char: count += 1 if char == '.': char = '-' if char != '-': cells[i+1] = char if count != 9 or len(state) != 9: print('State "{}" must be 9 characters of only ., X, O'.format(state)) sys.exit(1) winner = '' for p in 'XO': for i in range(1,8,3): if cells[i] == cells[i+1] == cells[i+2] == p: winner = p for l in range(1,4): if cells[l] == cells[l+3] == cells[l+6] == p: winner = p if cells[1] == cells[5] == cells[9] == p or cells[3] == cells[5] == cells[7] == p: winner = p if winner == '': print('No winner') else: print('{} has won'.format(winner)) # -------------------------------------------------- if __name__ == '__main__': main()
Java
UTF-8
4,157
2.65625
3
[ "MIT" ]
permissive
// NadaMillas (c) 2019 Baltasar MIT License <baltasarq@gmail.com> package com.devbaltasarq.nadamillas.core.storage; import android.content.ContentValues; import android.database.Cursor; import android.util.JsonReader; import android.util.JsonWriter; import com.devbaltasarq.nadamillas.core.YearInfo; import java.io.IOException; /** Represents a YearInfo in storage. */ public class YearInfoStorage { public static final String FIELD_YEAR = "_id"; public static final String FIELD_TARGET = "target"; public static final String FIELD_TOTAL = "total"; public static final String FIELD_TOTAL_POOL = "total_pool"; /** Creates a new wrapper. * @param yinfo the object YearInfo being wrapped. */ public YearInfoStorage(YearInfo yinfo) { this.yearInfo = yinfo; } /** @return the YearInfo object begin wrapped. */ public YearInfo getYearInfo() { return this.yearInfo; } /** @return a corresponding ContentValues object. */ public ContentValues toValues() { final ContentValues toret = new ContentValues(); toret.put( FIELD_YEAR, this.getYearInfo().getYear() ); toret.put( FIELD_TOTAL, this.getYearInfo().getTotal() ); toret.put( FIELD_TARGET, this.getYearInfo().getTarget() ); toret.put( FIELD_TOTAL_POOL, this.getYearInfo().getTotalPool() ); return toret; } /** Stores the info in JSON. * @param jsonWriter the stream to write to. * @throws IOException if something goes really wrong. */ public void toJSON(JsonWriter jsonWriter) throws IOException { jsonWriter.beginObject(); jsonWriter.name( FIELD_YEAR ).value( this.getYearInfo().getYear() ); jsonWriter.name( FIELD_TOTAL ).value( this.getYearInfo().getTotal() ); jsonWriter.name( FIELD_TARGET ).value( this.getYearInfo().getTarget() ); jsonWriter.name( FIELD_TOTAL_POOL ).value( this.getYearInfo().getTotalPool() ); jsonWriter.endObject(); } /** Reads a YearInfo object from JSON. * @param jsonReader the stream to read from. * @return a YearInfo object reflecting the data. * @throws IOException if something goes really wrong. */ public static YearInfo createFrom(JsonReader jsonReader) throws IOException { int year = -1; int target = -1; int total = -1; int poolTotal = -1; jsonReader.beginObject(); while( jsonReader.hasNext() ) { final String NAME = jsonReader.nextName(); if ( NAME.equals( FIELD_YEAR ) ) { year = jsonReader.nextInt(); } else if ( NAME.equals( FIELD_TARGET ) ) { target = jsonReader.nextInt(); } else if ( NAME.equals( FIELD_TOTAL ) ) { total = jsonReader.nextInt(); } else if ( NAME.equals( FIELD_TOTAL_POOL ) ) { poolTotal = jsonReader.nextInt(); } else { jsonReader.skipValue(); } } jsonReader.endObject(); if ( year == -1 || target == -1 || total == -1 || poolTotal == -1 ) { throw new IOException( "reading YearInfo from JSON: missing data" ); } return new YearInfo( year, target, total, poolTotal ); } /** Creates a new YearInfo object from the info stored in the Cursor. * @param cursor the database cursor object. * @return a new YearInfo object. */ public static YearInfo createFrom(Cursor cursor) { int year = cursor.getInt( cursor.getColumnIndexOrThrow( YearInfoStorage.FIELD_YEAR ) ); int target = cursor.getInt( cursor.getColumnIndexOrThrow( YearInfoStorage.FIELD_TARGET ) ); int total = cursor.getInt( cursor.getColumnIndexOrThrow( YearInfoStorage.FIELD_TOTAL ) ); int totalPool = cursor.getInt( cursor.getColumnIndexOrThrow( YearInfoStorage.FIELD_TOTAL_POOL ) ); return new YearInfo( year, target, total, totalPool ); } private YearInfo yearInfo; }
Markdown
UTF-8
2,816
2.703125
3
[ "Apache-2.0" ]
permissive
### Transporter #### 1 简介 > 名称:传输器/传输者,和Exchanger是对应的,里面也是两个方法一个bind,一个connect。 ``` @SPI("netty") public interface Transporter { /** * Bind a server. * * @param url server url * @param handler * @return server * @throws RemotingException * @see org.apache.dubbo.remoting.Transporters#bind(URL, ChannelHandler...) */ @Adaptive({Constants.SERVER_KEY, Constants.TRANSPORTER_KEY}) Server bind(URL url, ChannelHandler handler) throws RemotingException; /** * Connect to a server. * * @param url server url * @param handler * @return client * @throws RemotingException * @see org.apache.dubbo.remoting.Transporters#connect(URL, ChannelHandler...) */ @Adaptive({Constants.CLIENT_KEY, Constants.TRANSPORTER_KEY}) Client connect(URL url, ChannelHandler handler) throws RemotingException; } ``` #### 2 类关系 > 以为几个子类,不同的传入者,其中默认使用的NettyTransporter(netty4包下的)。 ``` NettyTransporter (org.apache.dubbo.remoting.transport.netty4) GrizzlyTransporter (org.apache.dubbo.remoting.transport.grizzly) NettyTransporter (org.apache.dubbo.remoting.transport.netty) Transporter (com.alibaba.dubbo.remoting) MinaTransporter (org.apache.dubbo.remoting.transport.mina) ``` #### 3 Transporters#bind > 上一篇,代码跟踪到这里 ``` // Transporters#bind public static Server bind(URL url, ChannelHandler... handlers) throws RemotingException { if (url == null) { throw new IllegalArgumentException("url == null"); } if (handlers == null || handlers.length == 0) { throw new IllegalArgumentException("handlers == null"); } ChannelHandler handler; if (handlers.length == 1) { handler = handlers[0]; } else { handler = new ChannelHandlerDispatcher(handlers); } // 获得Transporter,并调用bind方法 // debug可以看到这里返回的是netty4包下的NettyTransporter return getTransporter().bind(url, handler); } public static Transporter getTransporter() { return ExtensionLoader.getExtensionLoader(Transporter.class).getAdaptiveExtension(); } ``` ##### 3.1 NettyTransporter#bind > netty传输器 ``` public class NettyTransporter implements Transporter { public static final String NAME = "netty"; @Override public Server bind(URL url, ChannelHandler listener) throws RemotingException { // 创建netty服务器 return new NettyServer(url, listener); } @Override public Client connect(URL url, ChannelHandler listener) throws RemotingException { // 创建netty客户端 return new NettyClient(url, listener); } } ```
Shell
UTF-8
484
3.453125
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env bash if [ "$UID" -ne 0 ] then >&2 echo "This script requires superuser priviledges." exit 1 fi # Target version COMMITISH="build-v1.1" # Make sure the folder exists INSTALL_DIR="/opt/harmonics-explorer" mkdir -p "$INSTALL_DIR" cd "$INSTALL_DIR" git init git remote remove origin &> /dev/null || true git remote add origin https://github.com/IMAGINARY/harmonics-explorer.git git fetch --tags origin git reset --hard origin/gh-pages git checkout "$COMMITISH"
Python
UTF-8
606
3.640625
4
[]
no_license
class Solution: def strangeGrid(self, h: int, w: int) -> list: lis=[[None]*w for i in range(h)] c='A' for j in range(w): # reservamos a j para columnas y a i para filas como siempre for i in range(h): # print(c,end=' ') # saldran en el orden deseado if j%2!=0: lis[h-i-1][j] = c c=chr(ord(c)+1) # ord convierte a c en un integer Unicode code point value else: lis[i][j] = c c=chr(ord(c)+1) # chr es la inversa lo vuelve a como estaba pero ahora modificado return lis s=Solution() h = int(input()) w = int(input()) print(s.strangeGrid(h, w))
Python
UTF-8
2,126
2.625
3
[]
no_license
from strategy_monitor_server import order_msg from strategy_monitor_server import log_msg import json #策略字典 strategys = {} #创建策略信息 def new_strategy_info(name): strategy = strategys.get(name,StrategyInfo()) strategys.setdefault(name,strategy) return strategy #策略信息 class StrategyInfo: def __init__(self): self._name = "" self._profile = 0 self._positions = {} #更新持仓信息 def update_position(self,instrument_id,direction,date_type,vol): position = self._positions.get(instrument_id,PositionInfo()) if direction == Direction.LONG: if date_type == DateType.TD: position._td_long = vol else: position._yd_long = vol else: if date_type == DateType.TD: position._td_short = vol else: position._yd_short = vol self._positions.setdefault(instrument_id,position) #增加或更新订单消息 def add_or_update_order(self,order_id,instrument_id,direction,open_close,qty,leave_qty,status): order = order_msg.OrderMsg() order._strategy_name = self._name order._order_id = order_id order._instrument_id = instrument_id order._direction = direction order._open_close = open_close order._qty = qty order._status = status order_msg.orders.append(order) #增加日志 def add_log(self,log): info = log_msg.LogMsg() info._strategy_name = self._name info._content = log log_msg.logs.append(info) #查询策略 def query_strategys(json_str): return json.dumps(strategys) #持仓信息 class PositionInfo: def __init__(self): self._strategy_name = "" self._instrument_id = "" self._td_long = 0 self._td_short = 0 self._yd_long = 0 self._yd_short = 0 #持仓方向 class Direction: LONG="多" SHORT="空" #开平 class OpenClose: OPEN="开" CLOSE="平" #持仓类型 class DateType: YD="今" TD="昨"
JavaScript
UTF-8
2,968
3.140625
3
[]
no_license
import { findById, getUser } from '../common/utilities.js'; import { hpArray, expArray } from '../data/final-result.js'; import { hasCompleted } from './has-completed.js'; export const renderResult = () => { // grabs the HTML elements to be rendered const questTitle = document.getElementById('quest-title'); const questResult = document.getElementById('result-message'); // grabs the user profile and choices from local storage const questInfo = localStorage.getItem('CHOICE'); const parsedQuestInfo = JSON.parse(questInfo); const userData = getUser(); const completed = hasCompleted(userData); if (completed === false) { const currentQuest = parsedQuestInfo[0]; const userChoice = parsedQuestInfo[1]; const result = findById(userChoice, currentQuest.choices); const resultMessage = result.result; userData.hp += result.hp; userData.exp += result.experience; userData.completed[`${currentQuest.id}`] = true; questTitle.textContent = currentQuest.title; questResult.textContent = resultMessage; } const updatedUserData = JSON.stringify(userData); localStorage.setItem('USER', updatedUserData); const emptyArray = []; const stringyEmptyArray = JSON.stringify(emptyArray); localStorage.setItem('CHOICE', stringyEmptyArray); }; export const renderLose = () => { // grabs the HTML elements to be rendered const questTitle = document.getElementById('quest-title'); const questResult = document.getElementById('result-message'); const resultMessage = `You battled as hard as you could, but you couldn't make it to the League! Remember, every Pokemon has strengths and weaknesses. Study up, and you'll be able to make it to the league next time!`; questTitle.textContent = 'Too Bad!'; questResult.textContent = resultMessage; }; export const renderFinal = () => { const questTitle = document.getElementById('quest-title'); const questResult = document.getElementById('result-message'); const user = getUser(); const finalHp = user.hp; const finalExp = user.exp; let hpMessageIndex; let expMessageIndex; if (finalHp > 67) { hpMessageIndex = 0; } else if (finalHp < 67 && finalHp > 33) { hpMessageIndex = 1; } else { hpMessageIndex = 2; } if (finalExp > 67) { expMessageIndex = 2; } else if (finalExp < 67 && finalExp > 33) { expMessageIndex = 1; } else { expMessageIndex = 0; } const resultMessage = `${user.name}, congratulations for making it to the Pokemon League! Only a select few trainers can say they made it this far, so you've already cemented your place in history! ${hpArray[hpMessageIndex].message} After the Champion arrives, ${expArray[expMessageIndex].message}.`; questTitle.textContent = 'Indigo Plateau'; questResult.textContent = resultMessage; };
Java
UTF-8
945
2.171875
2
[ "MIT" ]
permissive
package com.algorand.algosdk.v2.client.model; import java.util.HashMap; import java.util.Objects; import com.algorand.algosdk.v2.client.common.PathResponse; import com.fasterxml.jackson.annotation.JsonProperty; /** * Encoded block object. */ public class BlockResponse extends PathResponse { /** * Block header data. */ @JsonProperty("block") public HashMap<String,Object> block; /** * Optional certificate object. This is only included when the format is set to * message pack. */ @JsonProperty("cert") public HashMap<String,Object> cert; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null) return false; BlockResponse other = (BlockResponse) o; if (!Objects.deepEquals(this.block, other.block)) return false; if (!Objects.deepEquals(this.cert, other.cert)) return false; return true; } }
PHP
UTF-8
1,150
2.796875
3
[]
no_license
<?php // création de la classe TYPE_CLIENT class TYPE_CLIENT { Private $id_typeclient; Private $lib_typeclient; Private $idcat; //constructeur de la classe TYPE_CLIENT Public TYPE_CLIENT ($idtypcli, $libtypcli, $c) { $this -> id_typeclient = $idtypcli; $this -> lib_typeclient = $libtypcli; $this -> idcat = $c; } // getter de la classe TYPE_CLIENT Public function get_id_typeclient(): int { Return $this -> id_typeclient; } Public function get_lib_typeclient(): varchar { Return $this -> lib_typeclient; } Public function get_idcat(): int { Return $this -> idcat; } // setter de la classe TYPE_CLIENT Public void set_lib_typeclient($libtypcli) { $this -> lib_typeclient = $libtypcli; } }
Shell
UTF-8
361
2.921875
3
[]
no_license
#!/bin/sh cd "$(dirname "$0")" || exit # The kernel does send a RST packet when it receives something to an # unknown socket destination which is the case with raw sockets. To # prevent this we simply block all outgoing RST packets. if ! iptables -C OUTPUT -p tcp --tcp-flags RST RST -j DROP; then iptables -A OUTPUT -p tcp --tcp-flags RST RST -j DROP fi
Shell
UTF-8
1,183
3.046875
3
[]
no_license
#!/bin/bash #autor : Esteban #mueve a las carpetas correspondientes #archivos de log son creados durante la instalacion previos a la creacion #de la estructura. son movidos a la carpeta definitiva definida por #DIRLOG. la carpeta donde se guardaban es dirconf q es palabra reservada comando="mover_Archivos_utiles.sh" . funcion_mover.sh emitir.sh -t $comando "Instalando Programas y Funciones" "" #moviendo archivos de log que se hayan creado durante la instalacion que estaban en carpeta #temporal, ya que si el usuario cambio el nombre se evalua if [ "${DIRLOG}" != "log" ] then if [ -d "${GRUPO}/log" ] then origen=$(ls ${GRUPO}/log/*.log) #varios casos se contemplan destino="${GRUPO}/$DIRLOG" Movep "$origen" "$destino" "$comando" fi fi #--------------------------------------------------- emitir.sh -t $comando "Instalando Archivos Maestros y tablas" "INFO" #se modifica la carpeta agrupados los archivos mae en una subcarpeta origen=$(ls ${GRUPO}/datos/*.csv) destino="${GRUPO}/$DIRMAE" Movep "$origen" "$destino" "$0" #nota:no expande con entrecomillado origen=$(ls ${GRUPO}/*.sh) destino="${GRUPO}/$DIRBIN" Movep "$origen" "$destino" "$comando"
C++
UTF-8
1,076
3.296875
3
[]
no_license
#pragma once #include <iostream> #include<cstring> // Да се дефинира клас Location, който има член-данни указател към първия елемент на динамичен масив //от символи за име (символен низ с произволна дължина) на локацията и две числа от тип double за //координати. Класа трябва да съдържа голяма четворка, сетъри и гетъри и член-функция print. class Location { private: char* name; double coordX; double coordY; void copy(const Location& other_location); void erase(); public: Location(); Location& operator=(const Location& other_location); Location(const Location& other_location); ~Location(); void setName(const char* _name); void setCoordX(double _coordX); void setCoordY(double _coordY); const char* getName() const; double getCoordX() const; double getCoordY() const; void print() const; };
Python
UTF-8
1,129
3.59375
4
[]
no_license
from tkinter import * import random root=Tk() root.title("TESTING RANDOM FUNCTION") root.geometry("500x500") input_password = Entry(root) guessed_passward_label = Label(root) generated_passward_label= Label(root) array_3d = [[["I","J","K","L","M","N","O","P"],["King","Queen"],["!","@","#","$","%","^","&","*"]]] print(array_3d[0][2][3]) def new_password(): guessed_passward_label["text"] = "Guessed Password: " + input_password.get() r1 = random.randint(0,5) r2 = random.randint(0,1) r3 = random.randint(0,7) letter1 = array_3d[0][0][r1] letter2 = array_3d[0][1][r2] letter3 = array_3d[0][2][r3] generated_passward_label["text"] = "Generated Password: " + letter1 + "" + letter2 + "" + letter3 input_password.place(relx = 0.5, rely =0.3, anchor = CENTER) guessed_passward_label.place(relx = 0.5, rely =0.4, anchor = CENTER) btn = Button(root, text= "new password", command = new_password) btn.place(relx = 0.5, rely =0.5, anchor = CENTER) generated_passward_label.place(relx = 0.5, rely =0.6, anchor = CENTER) root.mainloop()
C++
UTF-8
1,009
2.921875
3
[]
no_license
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { vector<int> res(2,-1); if(nums.empty()) return res; int low=0,size=nums.size(),high=nums.size()-1,mid=0; while(low<high){ mid=low+(high-low)/2; if(nums[mid]>target) high=mid-1; else if(nums[mid]==target) high=mid; else low=mid+1; } if(nums[low]==target) res[0]=low; low=0,size=nums.size(),high=size-1,mid=0; while(low+1<high){ mid=low+(high-low)/2; if(nums[mid]<target) low=mid+1; else if(nums[mid]==target) low=mid; else high=mid-1; } if(nums[low+1]==target&&size>1) res[1]=low+1; else if(nums[low]==target) res[1]=low; else res[1]=-1; return res; } };
C++
UTF-8
1,047
2.828125
3
[ "BSD-3-Clause" ]
permissive
// Purpose: Debug callbacks with Eigen::Ref<> arguments. #include <cstddef> #include <cmath> #include <sstream> #include <string> #include <iostream> #include <Eigen/Dense> #include <pybind11/eigen.h> #include <pybind11/embed.h> #include <pybind11/eval.h> #include <pybind11/functional.h> #include <pybind11/pybind11.h> namespace py = pybind11; using namespace py::literals; using namespace std; using Callback = std::function<Eigen::VectorXd (const Eigen::Ref<const Eigen::VectorXd>& x)>; void call_thing(const Callback& func) { Eigen::VectorXd x(4); x << 10, 20, 30, 40; Eigen::VectorXd y = func(x); cout << y.transpose() << endl; } int main(int argc, char* argv[]) { py::scoped_interpreter guard{}; py::module m("test_callback_eigen_ref"); m.def("call_thing", &call_thing); py::dict globals = py::globals(); globals["m"] = m; py::exec(R"""( def my_func(x): print("Python callback: {}".format(x)) return 2 * x m.call_thing(my_func) )"""); cout << "[ Done ]" << endl; return 0; }
Markdown
UTF-8
2,345
3.40625
3
[ "MIT" ]
permissive
--- title: Friendship date: 21/04/2019 --- **This is Easy Reading Edition of the Sabbath School. For the regular Adult version with Teacher comments and EGW notes please open the top lesson on the main screen** `What basic idea is Ecclesiastes 4:9–12 talking about? What important rule about life do these verses teach us?` Very few of us can live with no friends. But what about people who like being alone most of the time? Even they need people too. Sooner or later, we want to spend time with someone else. We may even need to. We need friends to do things with us that we both enjoy. People who have close families should be very thankful. Family members can give them support and love when they need it most. Not everyone has a family or feels close to their family. There are people who need help. Sadly, they do not know anyone who can help them. They have no one to talk to. You may not know that these people are everywhere around you. They are in church. They are at work. They live next door. You may meet one of these people sometimes. We can feel lonely at any time. One man who was not married said that he felt lonely on Sunday more than any other day. During the week people were all around him at work. On Sabbath, he saw people at church. “But on Sunday I am alone,” he said. `What important rules can we learn from John 16:32, 33 and Philippians 4:11–13? How can these rules help us when we are feeling lonely?` As Christians, we know that God is real. He is our Friend too. So, we can feel happy knowing that God wants us to feel close to Him. But we must remember something. Yes, Adam was close to God in Eden. But that did not stop God from making Adam a wife. God said, “ ‘I see that it is not good for the man to be alone’ ” (Genesis 2:18, ERV). God saw that Adam needed a human to be close to. That was true in Eden. It is true for us now, even more so. Why? Because we live on an earth hurt by sin. But we must be careful. Do not make the mistake of thinking that people are not lonely just because there are many people around them. Some very lonely people live in big cities. They meet many people all the time. But they feel alone anyway because they do not feel close to anyone. `It is not easy to know who feels lonely. What can you do as a friend to help the lonely people around you?`
TypeScript
UTF-8
1,066
2.96875
3
[ "MIT" ]
permissive
import { parseEmojis } from '../src/Utils' /** * Gerar html da uma imagem genérica para teste. * @async * @param {Object} props Valores recebidos no query string da solicitação. * @returns {Promise<string>} Template a ser renderizado. */ export default async (props: any): Promise<string> => { // Valores padrões const { title = "Olá mundo!", emoji = "🤙🌎" } = props return ` <style> body { background: #eee; width: 720px; word-break: break-word; margin: 0; } .container { padding: 80px; display: flex; flex-direction: column; justify-content: center; align-items: center; text-align: center; } .emoji { display: flex; flex-wrap: nowrap; } h1 { font-size: 62px; margin: 50px 0 0; } </style> <div class="container"> <div class="emoji"> ${parseEmojis(emoji).replace(/png\/32\//gm, 'png/128/')} </div> <h1>${title}</h1> </div> ` }
Java
UTF-8
131
1.945313
2
[]
no_license
package com.example.basic.socket.netty3; public interface IMessageFactory { public abstract IMessage getMessage(String type); }
Java
UTF-8
1,069
2.28125
2
[]
no_license
package org.finartz.homework.web.dto; /** * @author Mert * */ public class SearchDTO { private String query; private String type; private Integer limit; private Integer offSet; private String accessToken; public String getQuery() { return query; } public void setQuery(String query) { this.query = query; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Integer getLimit() { return limit; } public void setLimit(Integer limit) { this.limit = limit; } public Integer getOffSet() { return offSet; } public void setOffSet(Integer offSet) { this.offSet = offSet; } public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } @Override public String toString() { return "SearchDTO [query=" + query + ", type=" + type + ", limit=" + limit + ", offSet=" + offSet + ", accessToken=" + accessToken + "]"; } }
Java
UTF-8
2,818
2.46875
2
[]
no_license
package in.webxstudio.rest.quiz.api.truefalse; import java.util.ArrayList; import java.util.List; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import in.webxstudio.rest.quiz.api.connector.GetBoolean; import in.webxstudio.rest.quiz.api.models.SingleAnswer; @Path("boolean") public class TrueFalse { @GET @Produces(MediaType.TEXT_HTML) public String questionBase() { String index="<h3>You're in Multiple Choice Home Select Your Subject</h3> " + " <br>For Science <a href='/webapi/boolean/science'>Click here</a>" + " <br>For History <a href='/webapi/boolean/history'>Click here</a>" + " <br>For Geography <a href='/webapi/boolean/geography'>Click here</a>" + " <br>For Computer Science <a href='/webapi/boolean/computers'>Click here</a>" + " <br>For Mythology <a href='/webapi/boolean/mythology'>Click here</a>" + " <br>For Sports <a href='/webapi/boolean/sports'>Click here</a>" + " <br>For Films <a href='/webapi/boolean/films'>Click here</a>"; return index; } @Path("science") @GET @Produces(MediaType.APPLICATION_JSON) public List<SingleAnswer> science() { GetBoolean single=new GetBoolean(); List<SingleAnswer> data=new ArrayList<>(); data=single.getBoolean("science_boolean"); return data; } @Path("history") @GET @Produces(MediaType.APPLICATION_JSON) public List<SingleAnswer> history() { GetBoolean single=new GetBoolean(); List<SingleAnswer> data=new ArrayList<>(); data=single.getBoolean("history_boolean"); return data; } @Path("geography") @GET @Produces(MediaType.APPLICATION_JSON) public List<SingleAnswer> geography() { GetBoolean single=new GetBoolean(); List<SingleAnswer> data=new ArrayList<>(); data=single.getBoolean("geography_boolean"); return data; } @Path("computers") @GET @Produces(MediaType.APPLICATION_JSON) public List<SingleAnswer> computerScience() { GetBoolean single=new GetBoolean(); List<SingleAnswer> data=new ArrayList<>(); data=single.getBoolean("computers_boolean"); return data; } @Path("films") @GET @Produces(MediaType.APPLICATION_JSON) public List<SingleAnswer> films() { GetBoolean single=new GetBoolean(); List<SingleAnswer> data=new ArrayList<>(); data=single.getBoolean("films_boolean"); return data; } @Path("mythology") @GET @Produces(MediaType.APPLICATION_JSON) public List<SingleAnswer> mythology() { GetBoolean single=new GetBoolean(); List<SingleAnswer> data=new ArrayList<>(); data=single.getBoolean("mythology_boolean"); return data; } @Path("sports") @GET @Produces(MediaType.APPLICATION_JSON) public List<SingleAnswer> sports() { GetBoolean single=new GetBoolean(); List<SingleAnswer> data=new ArrayList<>(); data=single.getBoolean("sports_boolean"); return data; } }
PHP
UTF-8
1,971
2.5625
3
[ "MIT" ]
permissive
<?php namespace App\Repositories; use App\Models\Comment; use App\Repositories\Contracts\BusinessCommentRepository; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; class BusinessCommentRepositoryImpl implements BusinessCommentRepository { private $businessComment; public function __construct(Comment $businessComment,) { $this->businessComment = $businessComment; } public function createComment(array $payload) { $id = $this->businessComment->insertGetId([ 'userId' => $payload['userId'], 'businessId' => $payload['businessId'], 'comment' => filter_var($payload['comment'], FILTER_SANITIZE_STRING), ]); // $userId = Auth::id(); $data = DB::table('comments')->where('CommentId', '=', $id)->select('comments.created_at', 'comments.commentId', 'comments.comment', 'users.name',)->leftJoin('users', 'comments.userId', '=', 'users.id')->get(); return $data; } public function getAllComment($id) { $userid = Auth::user()->id; $data = DB::table('comments')->where('comments.businessId', '=', $id)->select('comments.businessId as bId', 'comments.commentId as cId', 'comments.comment', 'users.name', 'comments.userId as commentByUserID')->addSelect(DB::raw("(select COUNT(comment_like_dislikes.likeDislikeId) from comment_like_dislikes WHERE comment_like_dislikes.likeDislike = '1' AND comment_like_dislikes.businessId = bId AND comment_like_dislikes.userId = $userid AND comment_like_dislikes.commentId = cId) as liked"))->addSelect(DB::raw("(select COUNT(comment_like_dislikes.likeDislikeId) from comment_like_dislikes WHERE comment_like_dislikes.likeDislike = '0' AND comment_like_dislikes.businessId = bId AND comment_like_dislikes.userId = $userid AND comment_like_dislikes.commentId = cId) as disliked"))->leftJoin('users', 'comments.userId', '=', 'users.id')->get(); return $data; } }
Markdown
UTF-8
4,204
3.015625
3
[]
no_license
# DataBootcampFinalProject Segment1 Deliverable **This is the Segment1 Deliverable for the Data Analytics Bootcamp Final Project.** ## Overview - **Topic**: Our team will create a NN to determine the 'rating' of chocolate from this kaggle dataset. - **Reason**: Because we love chocolate. The scientific name is *Theobroma cacao* (Theobroma means "Food of the gods") - **Data Sources**: - [Kaggle Chocolate Bar Ratings](https://www.kaggle.com/rtatman/chocolate-bar-ratings) - [Flavors of Cacao](http://flavorsofcacao.com/chocolate_database.html) - [Kaggle Countries and States Lat Lon](https://www.kaggle.com/paultimothymooney/latitude-and-longitude-for-every-country-and-state) - **Questions we want to answer**: 1. Can we predict which chocolate bars will be rated in the top 15% (i.e. Rating >= 3.75, one Standard Deviation above the Mean), based on: + Review date: How recent was the review? + Cocoa Percent: Ranges from 42% to 100% + Bean Type: Criollo, Trinitario, or Forastero + Broad Bean Origin: Country where the cocoa beans were grown 2. Where are the best cocoa beans grown? 3. Which countries product the hightest-rated bars? 4. What's the relationship between cocoa solids percentage and rating? - References: + [Cacao Varieties - Willie's cacao](https://www.williescacao.com/world-cacao/different-cacao-varieties/) + [Cocoa Bean - Wikipedia](https://en.wikipedia.org/wiki/Cocoa_bean) Table 1 - Team Roles for this Project | Deliverable | Role | Member | | :-- | :-- | :-- | | Presentation | X? | Travis | | GitHub | Square | Bruce | | ML Model | Triangle | Tahereh / Bruce | | Database | Circle | Yan | | Dashboard | X? | Travis | ## Results Table 2 - Rubric for Segment 1 | Segment | Item | Details |Points | | :-- | :-- | :-- | --: | | 1 | [Presentation](https://github.com/jilek/DataBootcampFinalProject/blob/main/Segment1_Deliverable/Chocolate%20Bar%20Ratings%20Predictor.pdf) | | 30 | | | Selected topic | Done: (see Overview above) | | | | Reason for topic | Done: (see Overview above) | | | | Desc. of data source | Done: (see Overview above) | | | | Questions we want to answer | Done: (see Overview above) | | | 1 | GitHub | | 10 | | | Main branch includes a README.md | Done: this file | | | | README.md includes communication protocols | Done: Slack | | | | At least one branch for each team member | Done | | | | Each member has at least 4 commits. | Done | | | 1 | [ML model](https://github.com/jilek/DataBootcampFinalProject/blob/main/Segment1_Deliverable/ChocolateBarRatings.ipynb) | | 35 | | | Takes in data from the provisional database | Done: CSV for now | | | | Outputs label(s) for input data | Done: we predict 'Rating' | | | 1 | Database | | 25 | | | Sample data the mimics the expected final DB schema | Done: ERD and SQL now | | | | Draft machine learning module is connected to the provional DB | Done: CSV for now | | | 1 | Dashboard | | 0 | | | n/a for segment 1 | | | | 1 | **Total** | | 100 | Figure 1 - Entity Relationship Diagram (ERD) for the provisional Database ![ERD](Images/erd_diagram.png) ## Summary **To be completed in future segments**
Java
UTF-8
7,714
3.828125
4
[]
no_license
package ga.lab; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { String charString; double summedDoubles; int middleValue; //Problem 1: stringLengthOrValue("I said"); stringLengthOrValue("hey"); stringLengthOrValue("whats up?"); stringLengthOrValue("hello!"); //Problem 2: reversedOrder(); //Problem 3: maxValue(new int[]{2, 52, 7, 91, 10, 12}); maxValue(new int[]{12, 1, 11}); maxValue(new int[]{0, 14}); maxValue(new int[]{100, 23, 29, 101, 1}); // //Problem 4: summedDoubles = sumOfValues(new double[]{12.1, 13.9, 7.0}); System.out.println(summedDoubles); summedDoubles = sumOfValues(new double[]{1.23, 2.09, 9.2}); System.out.println(summedDoubles); summedDoubles = sumOfValues(new double[]{1.01, 15.1, 22.27, 19.99}); System.out.println(summedDoubles); summedDoubles = sumOfValues(new double[]{3.08, 4.1, 7.2, 3.0}); System.out.println(summedDoubles); //Problem 5: charString = charsToString(new char[]{'h', 'e', 'l', 'l', 'o'}); System.out.println(charString); charString = charsToString(new char[]{'t', 'h', 'e', 'r', 'e', '!'}); System.out.println(charString); charString = charsToString(new char[]{'I', ' ', 'a', 'm', ' '}); System.out.println(charString); charString = charsToString(new char[]{'A', ' ', 'S', 't', 'r', 'i', 'n', 'g', '.'}); System.out.println(charString); // //Problem 6: // //Put your code for problem 6 here // //Create a List of type String with the variable name myStringList. At least 5 String values to the list. (You can put any 5 String values you want). List<String> myStringList = new ArrayList<>(); myStringList.add("red"); myStringList.add("orange"); myStringList.add("yellow"); myStringList.add("green"); myStringList.add("blue"); // //Problem 7: // reversedStringOrder(/*use the List you created in problem 6*/); reversedStringOrder(myStringList); // //Problem 8: // printOrAdd(/*use the List you created in problem 6*/); printOrAdd(myStringList); // //Problem 9: // //Create an int array of an odd size, with the variable name 'oddSizedArray' // //Make sure the size is at least 5. // //Problem 10: // findMiddle(/*use the array you created in problem 9*/); // //how do we print a variable to the command line middleValue = findMiddle(new int[]{2,7,9,12,15}); System.out.println(middleValue); middleValue = findMiddle(new int[]{13, 91, 27, 99, 14, 36, 10}); System.out.println(middleValue); middleValue = findMiddle(new int[]{100, 1, 45, 1092, 76, 12, 34, 11, 145}); System.out.println(middleValue); } //declare your functions //Write a function stringLengthOrValue that accepts one String parameter. This function should print the value of the String parameter to the command line if the length of the String is greater than 5. If the length of the String is less than 5, print the length of the String parameter. public static void stringLengthOrValue(String a) { if (a.length() > 5) { System.out.println(a); } else if (a.length() < 5) { System.out.println(a.length()); } } //Write a function reversedOrder that accepts no parameters. This function should create an int array of size 10 and assign values 0-9 to each index in the array by using a for loop. It should then print out the values in reverse order using a separate for loop inside the function. public static void reversedOrder() { int[] anIntArray = new int[10]; for (int i = 0; i < anIntArray.length; i++) { anIntArray[i] = i; } for (int i = 9; i >= 0; i--) { System.out.println(anIntArray[i]); } } //Write a function maxValue that accepts one int array parameter. This function should loop through the array to return the max value in that array. If the array is of size 1, the max value is the only item in the array. If the array is of size 10, how do we keep a record of the current max value when looping through the array? public static void maxValue(int[] a) { int max = 0; for (int i = 0; i < a.length; i++) { if (a[i] > max) { max = a[i]; } } System.out.println(max); } //Write a function sumOfValues that accepts a double array parameter. This function should loop through the array and ADD all the values in the array. It should then return the sum of the values. The sum must then be assigned to the variable summedDoubles and the value of the variable should then be printed to the command line. public static double sumOfValues(double[] a) { double sum = 0; for (int i = 0; i < a.length; i++) { sum = sum + a[i]; } return sum; } //Write a function charsToString that takes in a char array parameter. This function should loop through the array and concatenate each char value into a String. It should then return the String that was created. The String must then be assigned to the variable charString and the value of the variable should then be printed to the command line. public static String charsToString(char[] a) { String word = (""); for (int i = 0; i < a.length; i++) { word = word + a[i]; } return word; } //Write a function reversedStringOrder that accepts a List parameter of type String. The function should loop through the List and print each String in reverse order to the command line (last String first). Use the List you created in problem 6 as the parameter you give to the function. public static void reversedStringOrder(List<String> b) { String words = ""; for (int i = b.size() - 1; i > -1; i--) { words = b.get(i); System.out.println(words); } } //Write in a function printOrAdd that accepts a List parameter of type String. The function should print all values in the list if the size of the List is equal to 10. If the size of the list is less than 10, add a String value to the list that consists of the word "Java" concatenated with the current size of the list. Use the List you created in problem 6. public static void printOrAdd(List<String> c) { if (c.size() == 10) { for (int i = 0; i < c.size(); i++) { System.out.println(c.get(i)); } } else { c.add(("Java " + c.size())); for (int i = 0; i < c.size(); i++) { System.out.println(c.get(i)); } } } //Create an int array of an odd size with the variable name oddSizedArray. Make sure the size is at least 5. int[] oddSizedArray = new int[7]; ///Write a function findMiddle that accepts a int array parameter. The function should access the value of the item at the middle of the array. The function should then return that value and assign it to the int variable middleValue. Print the value of middleValue to the command line. Use the array you created in problem 9 for one of the examples. public static int findMiddle (int[] m) { int mid = 0; for (int i = 0; i > m.length; i++) { mid = m.length % 2; System.out.println(mid); } return mid; } }
Markdown
UTF-8
559
2.953125
3
[]
no_license
# Grow-A-Caterpillar > Simple caterpillar game ## Getting Started Just start pressing buttons to watch the caterpillar grow and change! ## Features This project makes it easy to: * Teach children the life cycle of a butterfly * Help children practice computer skills and dexterity, while also engaging in life science. ## Deployment Play the game [here](https://github.com/nlee728/Grow-A-Caterpillar) ## Built With * HTML/CSS * jQuery/Javascript ## Authors * **Nutishia Lee** - [nlee728](https://github.com/nlee728) ## License Copyright 2018 - Nutishia Lee
JavaScript
UTF-8
2,877
2.890625
3
[]
no_license
//SelectView Object constructor var SelectView = function (container,model) { // Get all the relevant elements of the view (ones that show data // and/or ones that responded to interaction) this.numberOfGuests = container.find(".pplNbr"); this.plusButton = container.find(".plusButton"); this.minusButton = container.find(".minusButton"); this.menuList = container.find(".menuList"); this.filter = container.find("#filter"); this.confirmDinnerBtn = container.find(".confirmDinnerBtn"); this.dishFilter = container.find("#filter"); // this.model = model; this.dishList = container.find("#dishList"); this.allDishes = model.getAllDishes(); model.addObserver(this); this.filterDishesByType = function(){ var dishType = this.dishFilter.find("option:selected").val(); this.dishList.empty(); if(dishType !== "all") this.allDishes = model.getAllDishesByType(dishType); else this.allDishes = model.getAllDishes(); // Generating the dishes list html for (var i = 0; i < this.allDishes.length; i++) { dishHtml = ""; dishHtml += '<li id="' + this.allDishes[i].id + '">'; dishHtml += '<img src="images/'+ this.allDishes[i].image+'" alt="' + this.allDishes[i].name + '" >'; dishHtml += '<div class="dishName">'+ this.allDishes[i].name +'</div></li>'; //dishHtml += '<div class="dishDesc">'+ allDishes[i].type +'</div></li>'; this.dishList.append(dishHtml); }; } this.update = function(param){ // ingnoring the update of selected dish if(param == "selectedDish") return; //=== updating the number of guests value var nbPpl = model.getNumberOfGuests(); this.numberOfGuests.val(nbPpl); //====================== //========== Updating the menu List (at left) var fullMenu = model.getFullMenu(); // generating the list of items in the menu var menuBodyHtml = ""; for (var i = 0; i < fullMenu.length; i++) { var dish = fullMenu[i]; menuBodyHtml += "<tr>"; menuBodyHtml += "<td>" + fullMenu[i].name + "</td>"; menuBodyHtml += '<td class="aRigh">' + model.getDishPrice(dish) * nbPpl + "</td>"; menuBodyHtml += "</tr>"; }; this.menuList.find("tbody").empty(); this.menuList.find("tbody").html(menuBodyHtml); // generating the total var menuTotalHtml = ""; menuTotalHtml += "<tr>"; menuTotalHtml += "<td>SEK</td>"; menuTotalHtml += "<td>"; menuTotalHtml += model.getTotalMenuPrice() * nbPpl ; menuTotalHtml += "</td>"; menuTotalHtml += "</tr>"; this.menuList.find("tfoot").empty(); this.menuList.find("tfoot").html(menuTotalHtml); //===================================== // if the list of dishes needs to be updated if(param!== "guestsNbr" && param!="menu") { // updating the list of dishes this.filterDishesByType("all"); } } this.update(); }
C++
UTF-8
2,193
3.03125
3
[ "MIT" ]
permissive
#ifndef TEXTURE_H #define TEXTURE_H #include "Image.h" #include "Rect.h" #include "Graphics.h" #include "Utility.h" class Texture : public Renderable { public: Texture( PtrS<Renderer> renderer ) : renderer( renderer ) {} Texture( PtrS<Renderer> renderer, std::string filename ) : renderer( renderer ) { Image image( filename ); createFromImage( image ); if ( !texture ) { std::cout << "Failed to create Texture of '" << image.getFilename() << "' image.\n"; return; } } Texture( PtrS<Renderer> renderer, Image& image ) : renderer( renderer ) { createFromImage( image ); if ( !texture ) { std::cout << "Failed to create Texture of '" << image.getFilename() << "' image.\n"; return; } } ~Texture() { SDL_DestroyTexture( texture ); } bool createFromImage( Image& image ) { return createFromImageData( image.getData() ); } void draw( int x, int y) { SDL_Rect rect{ x, y, clip.w, clip.h }; SDL_RenderCopy( renderer.lock().get(), texture, (const SDL_Rect*)&clip, &rect ); } void draw( Rect rect ) { SDL_RenderCopy( renderer.lock().get(), texture, (const SDL_Rect*)&clip, (const SDL_Rect*)&rect ); } void draw( Renderer& renderer ) { } void draw( RenderTarget& render ) { } void setClip( Rect rect ) { clip = rect; } Rect getClip() const { return clip; } void setAlpha( double alpha ) { unsigned char alpha8 = (alpha * 255); SDL_SetTextureAlphaMod( texture, alpha8 ); } double getAlpha() const { unsigned char alpha; SDL_GetTextureAlphaMod( texture, &alpha ); return (alpha / 255); } SDL_Texture* getData() { return texture; } bool createFromImageData( SDL_Surface* image ) { if ( !image ) { return false; } if ( texture ) { SDL_DestroyTexture( texture ); texture = nullptr; clip = Rect(); } texture = SDL_CreateTextureFromSurface( renderer.lock().get(), image ); if ( !texture ) { return false; } SDL_QueryTexture( texture, nullptr, nullptr, &clip.w, &clip.h ); return true; } private: PtrW<Renderer> renderer; // This should be a shared pointer. SDL_Texture* texture = nullptr; Rect clip = Rect(); }; #endif //TEXTURE_H