repo_name
stringlengths 6
115
| branch_name
stringclasses 301
values | path
stringlengths 2
728
| content
stringlengths 1
7.45M
|
|---|---|---|---|
CSWITH89/skillmatrix
|
refs/heads/master
|
/functions/index.js
|
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
exports.helloWorld = functions.https.onRequest((request, response) => {
response.send("Hello World");
});
exports.getSkills = functions.https.onRequest((req, res) => {
admin
.firestore()
.collection('skills')
.get()
.then((data) => {
let skills = [];
data.forEach((doc) => {
skills.push(doc.data());
});
return res.json(skills);
})
.catch((err) => console.error(err));
});
exports.createSkills = functions.https.onRequest((req, res) => {
const newSkill = {
skillName: req.body.skillName,
skillValue: req.body.skillValue,
username: req.body.username,
createdOn: admin.firestore.Timestamp.fromDate(new Date()),
};
admin.firestore('skills')
.collection
.add(newSkill)
.then(doc =>{
res.json({ message: `document ${doc.id} created successfully`});
})
.catch(err => {
res.status(500).json({error:'something went wrong'});
console.error(err);
});
});
|
leenismail/GPA-Calculator-
|
refs/heads/master
|
/cli/GPA.java
|
import java.util.Scanner;
public class GPA {
public static void main(String[] args) {
int course;
int grade;
int CourseSum=0;//Sum of all courses
double CmltivSum=0;//Cumulative grades sum
Scanner s = new Scanner(System.in);
System.out.println("Please enter number of semesters:");
int semester = s.nextInt();
for (int j = 0; j < semester; j++) {
double SmstrSum=0;//Sum of grades in each semester
System.out.println("For semester number "+(j+1)+":");
System.out.println(" Enter the number of passed courses:");
course = s.nextInt();
CourseSum=CourseSum+course;
for (int i = 0; i <course; i++) {
System.out.println(" Enter grade number" +(i+1)+ ":");
grade = s.nextInt();
if (grade>=35) {
CmltivSum=CmltivSum+grade;
SmstrSum=SmstrSum+grade;
}
else {
System.out.println(" Invalid Input!, Please enter a mark above 35.");
i=i-1;
}
}
double totalSem=(((SmstrSum/course)/100)*4);
System.out.println("\n Semester GPA: "+totalSem+"/4\n");
}
double totalCum=(((CmltivSum/CourseSum)/100)*4);
System.out.println(" Cumulative GPA: "+totalCum+"/4");
}
}
|
heshmatpour/tamrin2
|
refs/heads/master
|
/lcd.c
|
#include "lcd.h"
#include "stm32f4xx_hal.h"
#define D0_PIN_Start 1
#define LCD_DATA_MASK (LCD_D7|LCD_D6|LCD_D5|LCD_D4)
static GPIO_TypeDef* PORT_LCD;
static uint8_t state;
static uint16_t D[8];
static GPIO_TypeDef* port_EN;
static GPIO_TypeDef* port_RS;
static uint16_t PIN_RS, PIN_EN;
void lcd_init(lcd_t *lcd)
{
switch(mode)
{
case 1:
for(uint8_t i=0 ;i<8 ;i=i+1 )
{
D[i]= lcd.data_pins[i];
}
break;
default:
for(uint8_t i=0 ;i<4 ;i=i+1 )
{
D[i]= lcd.data_pins[i];
}
break;}
PIN_EN=lcd.en_pin;
PIN_RS=lcd.rs_pin;
state=mode;
}
void lcd_putchar(lcd_t *lcd, uint8_t character)
{
unsigned char temp=0;
unsigned int temp1=0;
temp=character;
temp=(temp>>4)&0x0F;
temp1=(temp<<20)&LCD_DATA_MASK;
delay(10);
}
void lcd_puts(lcd_t *lcd,char *str)
{
HAL_Delay(T);
while(*str != 0)
{
lcd_putchar(lcd , *str);
str++;
}
}
void lcd_clear (lcd_t *lcd)
{
HAL_Delay(T);
HAL_GPIO_WritePin(GPIOB,(1<<rs_pin),GPIO_PIN_SET);
HAL_GPIO_WritePin(GPIOD,(0xFF<<D0_PIN_Start),GPIO_PIN_RESET);
HAL_GPIO_WritePin(GPIOD,(0x01<<D0_PIN_Start),GPIO_PIN_SET);
HAL_GPIO_WritePin(GPIOB,(1<<en_pin),GPIO_PIN_SET);
HAL_GPIO_WritePin(GPIOB,(1<<en_pin),GPIO_PIN_RESET);
}
void lcd_set_curser(lcd_t *lcd, uint16_t row, uint16_t col)
{
uint16_t maskData;
maskData = (col-1)&0x0F;
if(row==1)
{
maskData |= (0x80);
write(lcd ,maskData);
}
else
{
maskData |= (0xc0);
write(lcd ,maskData);
}
}
|
ruanjiayu/githubFirstPush
|
refs/heads/master
|
/README.md
|
# githubFirstPush
第一次提交到github仓库的步骤以及遇到的问题
## 1. 当你本地已经存在代码的情况下,使用下面的方式来提交代码
1. 在本地使用git init
2. git remote add origin https://github.com/xxx
3. git pull origin master
4. git add .
5. git push -u origin master
## 2. 当你在github上提前先创建好了库
1. git clone https://github.com/xxx
## 3. 问题
### 3.1 git commit提交修改好的文件时候,提示`Changes not staged for commit`
- 使用`git status` 来查看本地修改好的文件是否已将放入暂存区
- 如果发现没有加入暂存区,那么你可以使用`git add .`或者 `git add fileName`来加入暂存区
- 最后你可以使用`git commit -m "xxxxx"`来提交暂存区的数据到本地库,当然你可以直接可以使用`git commit -am "xxxx""`来进行直接的提交
### 3.2 已经加入暂存区的文件如何撤回,保留工作区内的文件
- 使用`git rm --cached fileName` 可以撤回相对应的文件。
- 使用`git rm -r --cached .` 可以撤回所有的文件
### 3.3 删除工作区内的文件,并且进行提交上传。注意:要删除的文件是没有修改过的,就是说和当前版本库文件的内容相同
- 使用`git rm fileName`,可以删除工作区内的文件,并且加入到暂存
- 使用`git commit -m "xxxxxx"`将删除了的文件提交到暂存区
### 3.4 强制删除工作区和暂存区内对应的文件,并将删除好后的状态提交到暂存区
- 使用`git rm -f fileName`,可以删除工作区内的文件,并且加入到暂存区
|
ruanjiayu/githubFirstPush
|
refs/heads/master
|
/src/main/java/com/xian/demo/Hello.java
|
package com.xian.demo;
/**
* @Description:
* @Author: Xian
* @CreateDate: 2019/8/29 11:00
* @Version: 0.0.1-SHAPSHOT
*/
public class Hello {
public static void main(String[] args) {
System.out.println("hello world");
}
}
|
pablor0mero/Placester_Test_Pablo_Romero
|
refs/heads/master
|
/main.py
|
# For this solution I'm using TextBlob, using it's integration with WordNet.
from textblob import TextBlob
from textblob import Word
from textblob.wordnet import VERB
import nltk
import os
import sys
import re
import json
results = { "results" : [] }
#Override NLTK data path to use the one I uploaded in the folder
dir_path = os.path.dirname(os.path.realpath(__file__))
nltk_path = dir_path + os.path.sep + "nltk_data"
nltk.data.path= [nltk_path]
#Text to analyze
TEXT = """
Take this paragraph of text and return an alphabetized list of ALL unique words. A unique word is any form of a word often communicated
with essentially the same meaning. For example,
fish and fishes could be defined as a unique word by using their stem fish. For each unique word found in this entire paragraph,
determine the how many times the word appears in total.
Also, provide an analysis of what sentence index position or positions the word is found.
The following words should not be included in your analysis or result set: "a", "the", "and", "of", "in", "be", "also" and "as".
Your final result MUST be displayed in a readable console output in the same format as the JSON sample object shown below.
"""
TEXT = TEXT.lower()
WORDS_NOT_TO_CONSIDER = ["a", "the", "and", "of", "in", "be", "also", "as"]
nlpText= TextBlob(TEXT)
def getSentenceIndexesForWord(word, sentences):
sentenceIndexes = []
for index, sentence in enumerate(sentences):
count = sum(1 for _ in re.finditer(r'\b%s\b' % re.escape(word.lower()), sentence))
if count > 0:
sentenceIndexes.append(index)
return sentenceIndexes
#1: Get all words, excluding repetitions and all the sentences in the text
nlpTextWords = sorted(set(nlpText.words))
nlpTextSentences = nlpText.raw_sentences
#2 Get results
synonymsList = []
allreadyReadWords = []
for word in nlpTextWords:
if word not in WORDS_NOT_TO_CONSIDER and word not in allreadyReadWords:
timesInText = nlpText.word_counts[word]
#Get sentence indexes where the word can be found
sentenceIndexes = getSentenceIndexesForWord(word, nlpTextSentences)
#Check for synonyms
for word2 in nlpTextWords:
if word2 not in WORDS_NOT_TO_CONSIDER and ( word.lower() != word2.lower() and len(list(set(word.synsets) & set(word2.synsets))) > 0 ):
#If I find a synonym of the word I add it to the list of words allready read and add the times that synonym appeared in the text to the total
#count of the unique word and the corresponding sentence indexes
allreadyReadWords.append(word2)
timesInText = timesInText + nlpText.word_counts[word2]
sentenceIndexes += getSentenceIndexesForWord(word2,nlpTextSentences)
allreadyReadWords.append(word)
results["results"].append({"word" : word.lemmatize(), #I return the lemma of the word because TextBlob's stems seem to be wrong for certain words
"total-occurances": timesInText,
"sentence-indexes": sorted(set(sentenceIndexes))})
print(json.dumps(results, indent=4))
|
Ashutosh-Choubey/RBA-MobileApp
|
refs/heads/master
|
/android/app/src/main/kotlin/com/example/RBA/MainActivity.kt
|
package com.example.RBA
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
|
GabinCleaver/Auto_Discord_Bump
|
refs/heads/main
|
/README.md
|
# Auto Discord Bump
❗ Un auto bump pour discord totalement fait en Python par moi, et en français.
💖 Enjoy !
🎫 Mon Discord: Gabin#7955

|
GabinCleaver/Auto_Discord_Bump
|
refs/heads/main
|
/autobump.py
|
import requests
import time
token = "TOKEN"
headers = {
'User-Agent' : 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.12) Gecko/20050915 Firefox/1.0.7',
'Authorization' : token
}
id = input(f"[?] Salon ID: ")
print("")
while True:
requests.post(
f"https://discord.com/api/channels/{id}/messages",
headers = headers,
json = {"content" : "!d bump"}
)
print("[+] Serveur Bumpé")
time.sleep(121 * 60)
|
josemiche11/reversebycondition
|
refs/heads/master
|
/reversebycondition.py
|
'''
Input- zoho123
Output- ohoz123
'''
char= input("Enter the string: ")
char2= list(char)
num= "1234567890"
list1= [0]*len(char)
list2=[]
for i in range(len(char)):
if char2[i] not in num:
list2.append( char2.index( char2[i]))
char2[i]= "*"
list2.reverse()
k=0
for j in range( len(char) ):
if j in list2:
list1[j]= char[list2[k]]
k= k+1
else:
list1[j]= char[j]
ch=""
for l in range(len(list1)):
ch= ch+ list1[l]
print(ch)
|
Mucheap/Autoinsta
|
refs/heads/main
|
/config.php
|
<?php
/*
By @Mucheap
GitHub : https://github.com/Mucheap/Autoinsta.git
Email : appscomposer@gmail.com
*/
$username = 'INSTAGRAM_USERNAME';
$password = 'INSTAGRAM_PASSWORD';
$image_description = 'Your Description Here ...';
$imgurl = 'https://picsum.photos/700/?random';
$photoFilename = "img/rand.jpg";
|
MoisesWillianCorreia/calculadora
|
refs/heads/main
|
/atividade 02/parte.01.html/01.js
|
var div = document.getElementById("q1");
var input = document.createElement("input");
var input2 = document.createElement("input");
var buttom = document.createElement("buttom");
var p = document.createElement("p");
input.setAttribute("id","valorMinimo");
input.setAttribute("type","number");
input2.setAttribute("id","valorMaximo");
input2.setAttribute("type","number");
buttom.setAttribute("id","buttom");
buttom.setAttribute("content","clique aqui");
p.setAttribute("id","resultado");
div.appendChild(input);
div.appendChild(input2);
div.appendChild(buttom);
div.appendChild(p);
buttom.addEventListener("click",multiplicar);
function multiplicar()
{
console.log("entrou")
// var imputMinimo = document.getElementById("valorMinimo");
// var imputMaximo = document.getElementById("valorMaximo");
var valorMinimo = document.getElementById("valorMinimo").value;
var valorMaximo = document.getElementById("valorMaximo").value;
var n1 = parseInt(valorMinimo)
var n2 = parseInt(valorMaximo)
console.log(n1);
console.log(n2);
for (let index = n1; index <= n2; index++) {
if (index %2 == 0 && index %3 == 0 ) {
console.log(index + " e multiplo de 2 e 3")
}
}
}
function sortear()
{
var min= imputMinimo.getElementById("minimo").value;
var max= imputMaximo.getElementById("maximo").value;
var sorteio = Math.floor(Math.random() * (max - min) + min);
document.getElementById("resultado").innerHTML = sorteio;
}
|
fruitsamples/iGetKeys
|
refs/heads/master
|
/iGKTest.c
|
/*
File: MLTEUserPane.c
Description:
This file contains the main application program for the MLTEUserPane
example. This application creates a dialog window and installs a scrolling
text user pane in the dialog. You will notice that since the implementation
of these scrolling text fields is based on the user pane control manager
api, this program makes very few calls for maintaining the edit
fields. those calls are made by the control manager.
Routines in this file are responsible for handling events directed
at the application.
Where calls are explicitly made to routines defined in the
file mUPControl.h, I have added comments beginning with
the phrase:
Call to mUPControl.h
Copyright:
Copyright 2000 Apple Computer, Inc. All rights reserved.
Disclaimer:
IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc.
("Apple") in consideration of your agreement to the following terms, and your
use, installation, modification or redistribution of this Apple software
constitutes acceptance of these terms. If you do not agree with these terms,
please do not use, install, modify or redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and subject
to these terms, Apple grants you a personal, non-exclusive license, under Apples
copyrights in this original Apple software (the "Apple Software"), to use,
reproduce, modify and redistribute the Apple Software, with or without
modifications, in source and/or binary forms; provided that if you redistribute
the Apple Software in its entirety and without modifications, you must retain
this notice and the following text and disclaimers in all such redistributions of
the Apple Software. Neither the name, trademarks, service marks or logos of
Apple Computer, Inc. may be used to endorse or promote products derived from the
Apple Software without specific prior written permission from Apple. Except as
expressly stated in this notice, no other rights or licenses, express or implied,
are granted by Apple herein, including but not limited to any patent rights that
may be infringed by your derivative works or by other works in which the Apple
Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION
OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT
(INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Change History (most recent first):
Fri, Jan 28, 2000 -- created
*/
#ifdef __APPLE_CC__
#include <Carbon/Carbon.h>
#else
#include <Carbon.h>
#endif
#include "iGKTest.h"
#include "iGetKeys.h"
#include "MapDialog.h"
Boolean gRunning = true;
Boolean gTesting = false;
typedef struct {
short itemNo;
short keycode;
short state;
ControlHandle itemControl;
char* name;
short namelen;
} ItemKeyCode;
ItemKeyCode gItemKeyCheckboxes[] = {
{ 4, kVirtualCapsLockKey, 0, NULL, "Caps Lock", 9},
{ 5, kVirtualShiftKey, 0, NULL, "Shift", 5},
{ 6, kVirtualControlKey, 0, NULL, "Control", 7},
{ 7, kVirtualOptionKey, 0, NULL, "Option", 6},
{ 8, kVirtualCommandKey, 0, NULL, "Command", 7},
{ 9, kVirtualHelpKey, 0, NULL, "Help", 4},
{ 10, kVirtualDeleteKey, 0, NULL, "Delete", 6},
{ 11, kVirtualTabKey, 0, NULL, "Tab", 3},
{ 12, kVirtualEnterKey, 0, NULL, "Enter", 5},
{ 13, kVirtualReturnKey, 0, NULL, "Return", 6},
{ 14, kVirtualEscapeKey, 0, NULL, "Escape", 6},
{ 15, kVirtualForwardDeleteKey, 0, NULL, "FwdDelete", 6},
{ 16, kVirtualHomeKey, 0, NULL, "Home", 4},
{ 17, kVirtualEndKey, 0, NULL, "End", 3},
{ 18, kVirtualPageUpKey, 0, NULL, "Page Up", 7},
{ 19, kVirtualPageDownKey, 0, NULL, "Page Down", 9},
{ 20, kVirtualLeftArrowKey, 0, NULL, "Arrow Left", 10},
{ 21, kVirtualRightArrowKey, 0, NULL, "Arrow Right", 11},
{ 22, kVirtualUpArrowKey, 0, NULL, "Arrow Up", 8},
{ 23, kVirtualDownArrowKey, 0, NULL, "Arrow Down", 10}
};
enum {
kGKCharacterListItem = 3,
kNumCheckBoxes = (sizeof(gItemKeyCheckboxes)/sizeof(ItemKeyCode))
};
DialogPtr gGKDialog = NULL;
DialogMapRecPtr gItemMap = NULL;
enum {
kTestDialogID = 130,
kCancelTestItem = 1,
kTestListItem = 2
};
DialogPtr gTestDialog = NULL;
DialogMapRecPtr gTestMap = NULL;
void ProcessNextEvent(void);
typedef struct {
Boolean asciiEntry;
Boolean state;
short code;
} KeyEntryTable;
static void BeginTestingSequence(void) {
ItemKeyCode *itemp;
short itemt, i;
Handle itemh;
Rect itemb;
Str255 s;
Size outActualSize;
ControlHandle listbox;
Ascii2KeyCodeTable ttable;
Cell theCell;
ListHandle gTestList = NULL;
Boolean isDown, product, changed, tableChanged;
KeyEntryTable keyTable[64], *entryp;
short keyTableSize;
/* get the test dialog, separate the list control */
gTestDialog = GetNewDialog(kTestDialogID, NULL, (WindowPtr)(-1));
NewDialogItemMap(gTestDialog, &gTestMap);
GetDialogItemAsControl(gTestDialog, kTestListItem, &listbox);
GetControlData(listbox, kControlEntireControl, kControlListBoxListHandleTag, sizeof(gTestList), &gTestList, &outActualSize);
SetListSelectionFlags(gTestList, 0);
/* list of ascii codes to test */
GetDialogItem( gGKDialog, kGKCharacterListItem, &itemt, &itemh, &itemb );
GetDialogItemText( itemh, s );
/* set up the ascii translation table */
InitAscii2KeyCodeTable( &ttable );
/* set up our local translation table */
keyTableSize = 0;
entryp = keyTable;
/* gather letters typed in table */
for (i=0; i<s[0]; i++) {
/* display in list */
SetPt(&theCell, 0, LAddRow(1, 3000, gTestList));
LSetCell(&s[i+1], 1, theCell, gTestList);
/* add new key table entry */
entryp->asciiEntry = true;
entryp->code = s[i+1];
entryp->state = false;
keyTableSize++;
entryp++;
}
/* gather checkboxes into table */
for (i=0, itemp=gItemKeyCheckboxes; i<kNumCheckBoxes; itemp++, i++)
if (itemp->state) {
/* display in list */
SetPt(&theCell, 0, LAddRow(1, 3000, gTestList));
LSetCell(itemp->name, itemp->namelen, theCell, gTestList);
/* add new key table entry */
entryp->asciiEntry = false;
entryp->code = itemp->keycode;
entryp->state = false;
keyTableSize++;
entryp++;
}
/* display the window */
ShowWindow(GetDialogWindow(gTestDialog));
/* while the window is visible, re-display the keys */
gTesting = true;
while (gTesting) {
/* validate the ascii translation table */
ValidateAscii2KeyCodeTable( &ttable, &tableChanged);
/* set the drawing environment */
SetPortWindowPort(GetDialogWindow(gTestDialog));
product = true;
changed = false;
for (i = 0, entryp=keyTable; i < keyTableSize; entryp++, i++) {
/* search the table for key transitions */
if (entryp->asciiEntry)
isDown = TestForAsciiKeyDown( &ttable, entryp->code );
else isDown = TestForKeyDown(entryp->code);
if (isDown != entryp->state) {
entryp->state = isDown;
SetPt(&theCell, 0, i);
LSetSelect(isDown, theCell, gTestList);
changed = true;
}
if ( ! isDown ) product = false;
}
/* redraw the list if it changed */
if (changed) Draw1Control(listbox);
/* beep and exit if all the keys are down */
if ( product ) {
SysBeep(1);
gTesting = false;
}
/* process the next event */
ProcessNextEvent();
}
/* close and return to the caller */
DisposeDialog(gTestDialog);
gTestDialog = NULL;
gTestList = NULL;
}
static void GKKeyTestDialog(EventRecord *ev, DialogPtr theDialog, short itemHit) {
if (itemHit == kCancelTestItem)
gTesting = false;
}
static void GKConfigDialog(EventRecord *ev, DialogPtr theDialog, short itemHit) {
long i;
ItemKeyCode *itemp;
/* check box clicks handled first */
for (i=0, itemp=gItemKeyCheckboxes; i<kNumCheckBoxes; itemp++, i++)
if (itemp->itemNo == itemHit) {
itemp->state = ( (itemp->state + 1) & 1 );
SetControlValue(itemp->itemControl, itemp->state);
return;
}
/* button clicks */
if (itemHit == 1) {
gRunning = false;
} else if (itemHit == 2) {
BeginTestingSequence();
}
}
/* QuitAppleEventHandler is our quit Apple event handler. this routine
is called when a quit Apple event is sent to our application. Here,
we set the gRunning flag to false. NOTE: it is not appropriate to
call ExitToShell here. Instead, by setting the flag to false we
fall through the bottom of our main event loop. */
static pascal OSErr QuitAppleEventHandler(const AppleEvent *appleEvt, AppleEvent* reply, long refcon) {
gRunning = false;
return noErr;
}
void ProcessNextEvent(void) {
EventRecord ev;
DialogPtr theDialog;
WindowPtr theWindow;
short itemHit, partCode;
/* get the next event */
if ( ! WaitNextEvent(everyEvent, &ev, GetCaretTime(), NULL) )
ev.what = nullEvent;
/* mouse events */
if ( ev.what == mouseDown ) {
partCode = FindWindow(ev.where, &theWindow);
switch (partCode) {
case inGrow:
if (theWindow == GetDialogWindow(gGKDialog)) {
GrowMappedDialog(ev.where, gGKDialog, gItemMap);
} else if (theWindow == GetDialogWindow(gTestDialog)) {
GrowMappedDialog(ev.where, gTestDialog, gTestMap);
}
break;
case inGoAway:
if (theWindow == GetDialogWindow(gGKDialog)) {
if (TrackGoAway(theWindow, ev.where))
gRunning = false;
}
break;
case inDrag:
{ Rect boundsRect = {0,0, 32000, 32000};
DragWindow(theWindow, ev.where, &boundsRect);
}
break;
}
if (partCode == inGrow || partCode == inGoAway || partCode == inDrag)
ev.what = nullEvent;
}
/* apple events */
if ( ev.what == kHighLevelEvent ) {
AEProcessAppleEvent(&ev);
ev.what = nullEvent;
}
/* key downs during testing... */
if (gTesting && (ev.what == keyDown || ev.what == autoKey))
ev.what = nullEvent;
/* handle dialog events */
if (IsDialogEvent(&ev))
if ( DialogSelect(&ev, &theDialog, &itemHit))
if (theDialog == gGKDialog)
GKConfigDialog(&ev, theDialog, itemHit);
else if (theDialog == gTestDialog)
GKKeyTestDialog(&ev, theDialog, itemHit);
}
/* the main program */
int main(void) {
long i;
ItemKeyCode *itemp;
/* set up */
InitCursor();
AEInstallEventHandler(kCoreEventClass, kAEQuitApplication, NewAEEventHandlerUPP(QuitAppleEventHandler), 0, false);
/* set up the menu bar */
SetMenuBar(GetNewMBar(kMenuBarID));
DrawMenuBar();
/* open the dialog window */
gGKDialog = GetNewDialog(kMainDialogBox, NULL, (WindowPtr)(-1));
NewDialogItemMap(gGKDialog, &gItemMap);
for (i=0, itemp=gItemKeyCheckboxes; i<kNumCheckBoxes; itemp++, i++) {
GetDialogItemAsControl(gGKDialog, itemp->itemNo, &itemp->itemControl);
}
ShowWindow(GetDialogWindow(gGKDialog));
/* loop processing events until.... */
while ( gRunning )
ProcessNextEvent();
/* close the dialog. */
DisposeDialog(gGKDialog);
DeleteDialogItemMap(gItemMap);
/* done */
ExitToShell();
return 0;
}
|
fruitsamples/iGetKeys
|
refs/heads/master
|
/MapDialog.h
|
/*
File: MapDialog.h
Description:
MapDialog provides an easily accessable set of routines that allow your
application to resize dialog windows reposition their contents to similarily
located positions in the window after it has been resized.
Copyright:
Copyright 2001 Apple Computer, Inc. All rights reserved.
Disclaimer:
IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc.
("Apple") in consideration of your agreement to the following terms, and your
use, installation, modification or redistribution of this Apple software
constitutes acceptance of these terms. If you do not agree with these terms,
please do not use, install, modify or redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and subject
to these terms, Apple grants you a personal, non-exclusive license, under Apples
copyrights in this original Apple software (the "Apple Software"), to use,
reproduce, modify and redistribute the Apple Software, with or without
modifications, in source and/or binary forms; provided that if you redistribute
the Apple Software in its entirety and without modifications, you must retain
this notice and the following text and disclaimers in all such redistributions of
the Apple Software. Neither the name, trademarks, service marks or logos of
Apple Computer, Inc. may be used to endorse or promote products derived from the
Apple Software without specific prior written permission from Apple. Except as
expressly stated in this notice, no other rights or licenses, express or implied,
are granted by Apple herein, including but not limited to any patent rights that
may be infringed by your derivative works or by other works in which the Apple
Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION
OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT
(INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Change History (most recent first):
Mon, Jan 15, 2001 -- created
*/
#ifndef __MAPDIALOG__
#define __MAPDIALOG__
#ifdef __APPLE_CC__
#include <Carbon/Carbon.h>
#else
#include <Carbon.h>
#endif
/* the position of each item in the dialog is recorded inside of a
DialogMapItem record. It is assumed that the dialog was created
using a control heirarchy, so every item has a control associated
with it. The control handle is cached here, along with the item's
coordinates */
typedef struct {
ControlHandle theItem; /* handle to the control */
Rect bounds; /* the control's bounds */
Rect ibounds; /* the dialog item's bounds */
} DialogMapItem;
/* DialogMapRecord contains a list of DialogMapItem records
together with the original coordinates of the dialog window. If the
dialog is ever resized, the items are remapped from the dialog's original
boundary into the new window boundary. */
typedef struct {
Rect bounds; /* the dialog's window bounds */
long count; /* the number of items in the dialog */
DialogMapItem itemb[1]; /* a list of items */
} DialogMapRecord, *DialogMapRecPtr;
/* NewDialogItemMap creates a new DialogMapRecord for all of the
items in the dialog. This DialogMapRecord can later be passed to RemapDialog
to reposition the dialog items after the dialog window has been resized. */
OSStatus NewDialogItemMap(DialogPtr theDialog, DialogMapRecPtr *theItems);
/* DeleteDialogItemMap disposes of a DialogMapRecord allocated by
NewDialogItemMap. */
void DeleteDialogItemMap(DialogMapRecPtr theItems);
/* RemapDialog repositions all of the items in the dialog according
proportionately to the new dialog size. */
OSStatus RemapDialog(DialogPtr theDialog, DialogMapRecPtr theItems);
/* GrowMappedDialog calls grow-window and tracks the mouse movement
and then calls RemapDialog to reposition all of the items if the size of the
window changes. */
void GrowMappedDialog(Point globalWhere, DialogPtr theDialog, DialogMapRecPtr theItems);
#ifdef __cplusplus
}
#endif
#endif
|
fruitsamples/iGetKeys
|
refs/heads/master
|
/MapDialog.c
|
/*
File: iGetKeys.c
Description:
Internationally Savy GetKeys test type routines for your entertainment
and enjoyment.
Copyright:
Copyright 2001 Apple Computer, Inc. All rights reserved.
Disclaimer:
IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc.
("Apple") in consideration of your agreement to the following terms, and your
use, installation, modification or redistribution of this Apple software
constitutes acceptance of these terms. If you do not agree with these terms,
please do not use, install, modify or redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and subject
to these terms, Apple grants you a personal, non-exclusive license, under Apples
copyrights in this original Apple software (the "Apple Software"), to use,
reproduce, modify and redistribute the Apple Software, with or without
modifications, in source and/or binary forms; provided that if you redistribute
the Apple Software in its entirety and without modifications, you must retain
this notice and the following text and disclaimers in all such redistributions of
the Apple Software. Neither the name, trademarks, service marks or logos of
Apple Computer, Inc. may be used to endorse or promote products derived from the
Apple Software without specific prior written permission from Apple. Except as
expressly stated in this notice, no other rights or licenses, express or implied,
are granted by Apple herein, including but not limited to any patent rights that
may be infringed by your derivative works or by other works in which the Apple
Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION
OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT
(INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Change History (most recent first):
Mon, Jan 15, 2001 -- created
*/
#ifdef __APPLE_CC__
#include <Carbon/Carbon.h>
#else
#include <Carbon.h>
#include <stddef.h>
#endif
#include "MapDialog.h"
OSStatus NewDialogItemMap(DialogPtr theDialog, DialogMapRecPtr *theItems) {
long i, n;
DialogMapRecPtr items;
DialogMapItem *itemip;
OSStatus err;
short itemt;
Handle itemh;
/* known state */
items = NULL;
SetPortWindowPort(GetDialogWindow(theDialog));
/* allocate our list */
n = CountDITL(theDialog);
items = (DialogMapRecPtr) NewPtr(offsetof(DialogMapRecord, itemb) + sizeof(DialogMapItem) * n);
if (items == NULL) { err = memFullErr; goto bail; }
/* bounds */
GetPortBounds(GetWindowPort(GetDialogWindow(theDialog)), &items->bounds);
/* count */
items->count = n;
/* items */
for (i=1, itemip = items->itemb; i<=n; itemip++, i++) {
err = GetDialogItemAsControl( theDialog, i, &itemip->theItem);
if (err != noErr) goto bail;
GetControlBounds(itemip->theItem, &itemip->bounds);
GetDialogItem( theDialog, i, &itemt, &itemh, &itemip->ibounds);
}
/* save result */
*theItems = items;
return noErr;
bail:
if (items != NULL) DisposePtr((Ptr) items);
return err;
}
void DeleteDialogItemMap(DialogMapRecPtr theItems) {
DisposePtr((Ptr) theItems);
}
OSStatus RemapDialog(DialogPtr theDialog, DialogMapRecPtr theItems) {
long i;
DialogMapItem *itemip;
short itemt;
Handle itemh;
Rect newbounds, temp, theemptyrect = {0, 0, 0, 0};
RgnHandle clipSave;
/* set the port and get the map-to bounds */
SetPortWindowPort(GetDialogWindow(theDialog));
GetPortBounds(GetWindowPort(GetDialogWindow(theDialog)), &newbounds);
/* turn off drawing until we're done shuffling items */
GetClip((clipSave = NewRgn()));
ClipRect(&theemptyrect);
/* items */
for (i=1, itemip = theItems->itemb; i <= theItems->count; itemip++, i++) {
/* adjust control rectangle */
temp = itemip->bounds;
MapRect(&temp, &theItems->bounds, &newbounds);
MoveControl(itemip->theItem, temp.left, temp.top);
SizeControl(itemip->theItem, temp.right - temp.left, temp.bottom - temp.top);
/* adjust item rectangle */
GetDialogItem( theDialog, i, &itemt, &itemh, &temp);
temp = itemip->ibounds;
MapRect(&temp, &theItems->bounds, &newbounds);
SetDialogItem( theDialog, i, itemt, itemh, &temp);
}
/* restore drawing */
SetClip(clipSave);
DisposeRgn(clipSave);
/* clear the old contents */
SetPortWindowPort(GetDialogWindow(theDialog));
EraseRect(&newbounds);
DrawDialog(theDialog);
ValidWindowRect(GetDialogWindow(theDialog), &newbounds);
//InvalWindowRect(GetDialogWindow(theDialog), &newbounds);
/* done */
return noErr;
}
void GrowMappedDialog(Point globalWhere, DialogPtr theDialog, DialogMapRecPtr theItems) {
Rect sizerect;
long grow_result;
WindowPtr theWindow;
theWindow = GetDialogWindow(theDialog);
SetRect(&sizerect, theItems->bounds.right, theItems->bounds.bottom, 32767, 32767);
grow_result = GrowWindow(theWindow, globalWhere, &sizerect);
if (grow_result != 0) {
SizeWindow(theWindow, LoWord(grow_result), HiWord(grow_result), true);
RemapDialog(theDialog, theItems);
}
}
|
bdhillon23/Cucumber_First
|
refs/heads/master
|
/Cucumber/src/test/java/com/dhillon/Cucumber/steps/Login2.java
|
package com.dhillon.Cucumber.steps;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class Login2 {
@Given("^User(\\d+) navigate to the stackoverflow website on the login page$")
public void user2_navigate_to_the_stackoverflow_website_on_the_login_page(int arg1) throws Throwable {
System.out.println("User 2 navigate to the stackoverflow website on the login page");
}
@When("^user(\\d+) clicks on the login button$")
public void user2_clicks_on_the_login_button(int arg1) throws Throwable {
System.out.println("User 2 navigate to the stackoverflow website on the login page");
}
@When("^user(\\d+) enters valid username ,password$")
public void user2_enters_valid_username_password(int arg1) throws Throwable {
System.out.println("User 2 navigate to the stackoverflow website on the login page");
}
@When("^clicks(\\d+) on the login page\\.$")
public void clicks2_on_the_login_page(int arg1) throws Throwable {
System.out.println("User 2 navigate to the stackoverflow website on the login page");
}
@Then("^System(\\d+) should allow user to login successfully\\.$")
public void system2_should_allow_user_to_login_successfully(int arg1) throws Throwable {
System.out.println("User 2 navigate to the stackoverflow website on the login page");
}
}
|
bdhillon23/Cucumber_First
|
refs/heads/master
|
/Cucumber/src/test/java/com/dhillon/Cucumber/runner/MainRunner.java
|
package com.dhillon.Cucumber.runner;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
@RunWith(Cucumber.class)
@CucumberOptions(
features = {"C:\\Users\\balwinder\\git\\Cucumber\\Cucumber\\src\\test\\java\\com\\dhillon\\Cucumber\\features\\Login.feature","C:\\Users\\balwinder\\git\\Cucumber\\Cucumber\\src\\test\\java\\com\\dhillon\\Cucumber\\features\\Login2.feature"},
glue = {"com.dhillon.Cucumber.steps"},
monochrome =true,
tags={},
plugin={"pretty" , "html:target/cucumber","json:target/cucumber.json","com.cucumber.listener.ExtentCucumberFormatter:target/report.html"}
)
public class MainRunner {
}
|
sanjar8855/cactuscorp
|
refs/heads/master
|
/result.html
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>CactusJobs.uz</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<header>
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html"><img src="images/logo-cactus-4.png" id="logo"></a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li><a href="#">Подработки</a></li>
<li><a href="#">Предложения работы в IT сфере</a></li>
<li><a href="#">Профили работодателей</a></li>
<li><a href="#">Создатель резюме</a></li>
<li><a href="#">Заработок</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="#">Войти в систему</a></li>
<li><a href="#" id="acc">Завести аккаунт</a></li>
<li><a href="#" id="for-com">Для компаний</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
</header>
<div class="result container">
<div class="row">
<div class="poisk col-lg-12">
<form class="form-inline">
<div class="form-group col-lg-6">
<label for="exampleInputName2">ПОИСК</label>
<input type="text" class="form-control" id="exampleInputName2" placeholder="Должность, компания, ключевое слово">
</div>
<div class="form-group col-lg-4">
<input type="email" class="form-control" id="exampleInputEmail2" placeholder="Город">
</div>
<button type="submit" class="btn btn-default"> <span class="glyphicon glyphicon-search"> Искать</span></button>
</form>
</div>
</div>
<!-- -->
<div class="vakansiyalar row">
<div class="col-lg-3">
<h1>Показывать вакансии</h1>
<select class="form-control">
<option>За все время</option>
<option>За день</option>
</select>
</div>
<div class="col-lg-9">
<h1>Работа для студентов</h1>
<p>Найдено: 2329</p>
</div>
</div>
<br>
<!-- -->
<div class="filtr row">
<div class="col-lg-3">
<div class="head">
<h1>Текущие фильтры</h1>
</div>
<div class="content">
<div>
<h1>Город</h1>
<ul>
<li><a href="#">Ташкент</a></li>
<li><a href="#">Фергана</a></li>
<li><a href="#">Ургенч</a></li>
<li><a href="#">Самарканд</a></li>
<li><a href="#">Наманган</a></li>
<li><a href="#">Андижан</a></li>
<li><a href="#">Показать все</a></li>
</ul>
</div>
<div>
<h1>Зарплата</h1>
<ul>
<li><a href="#">От 500 000 сум</a></li>
<li><a href="#">От 1 000 000 сум</a></li>
<li><a href="#">От 1 500 000 сум</a></li>
<li><a href="#">От 2 000 000 сум</a></li>
<li><a href="#">От 2 500 000 сум</a></li>
<li><a href="#">От 3 000 000 сум</a></li>
<li><a href="#">От 4 000 000 сум</a></li>
<li><a href="#">От 5 000 000 сум</a></li>
</ul>
</div>
<div>
<h1>График работы</h1>
<ul>
<li><a href="#">Гибкий</a></li>
<li><a href="#">Фиксированный</a></li>
<li><a href="#">Сменный</a></li>
</ul>
</div>
<div>
<h1>Занятость</h1>
<ul>
<li><a href="#">Полная</a></li>
<li><a href="#">Частичная</a></li>
<li><a href="#">Разовая</a></li>
</ul>
</div>
<div>
<h1>Характер работы</h1>
<ul>
<li><a href="#">На территории работодателя</a></li>
<li><a href="#">Разьездной</a></li>
<li><a href="#">Работу на дому</a></li>
</ul>
</div>
</div>
</div>
<!-- -->
<div class="headtext col-lg-6">
<div class="col-lg-12">
<h1><a href="vakansiya.html">Андроид разработчик</a></h1>
<h2>3 400 000 сум.+</h2>
<p>Фергана | 16 ноябрь 2020, 15:00</p>
<a href="#">Откликнуться</a>
<a href="#">Посмотреть контакты</a>
</div>
<div class="col-lg-12">
<h1><a href="vakansiya.html">Андроид разработчик</a></h1>
<h2>3 400 000 сум.+</h2>
<p>Фергана | 16 ноябрь 2020, 15:00</p>
<a href="#">Откликнуться</a>
<a href="#">Посмотреть контакты</a>
</div>
<div class="col-lg-12">
<h1><a href="vakansiya.html">Андроид разработчик</a></h1>
<h2>3 400 000 сум.+</h2>
<p>Фергана | 16 ноябрь 2020, 15:00</p>
<a href="#">Откликнуться</a>
<a href="#">Посмотреть контакты</a>
</div>
<div class="col-lg-12">
<h1><a href="vakansiya.html">Андроид разработчик</a></h1>
<h2>3 400 000 сум.+</h2>
<p>Фергана | 16 ноябрь 2020, 15:00</p>
<a href="#">Откликнуться</a>
<a href="#">Посмотреть контакты</a>
</div>
<div class="col-lg-12">
<h1><a href="vakansiya.html">Андроид разработчик</a></h1>
<h2>3 400 000 сум.+</h2>
<p>Фергана | 16 ноябрь 2020, 15:00</p>
<a href="#">Откликнуться</a>
<a href="#">Посмотреть контакты</a>
</div>
<div class="col-lg-12">
<h1><a href="vakansiya.html">Андроид разработчик</a></h1>
<h2>3 400 000 сум.+</h2>
<p>Фергана | 16 ноябрь 2020, 15:00</p>
<a href="#">Откликнуться</a>
<a href="#">Посмотреть контакты</a>
</div>
<div class="col-lg-12">
<h1><a href="vakansiya.html">Андроид разработчик</a></h1>
<h2>3 400 000 сум.+</h2>
<p>Фергана | 16 ноябрь 2020, 15:00</p>
<a href="#">Откликнуться</a>
<a href="#">Посмотреть контакты</a>
</div>
<div class="col-lg-12">
<h1><a href="vakansiya.html">Андроид разработчик</a></h1>
<h2>3 400 000 сум.+</h2>
<p>Фергана | 16 ноябрь 2020, 15:00</p>
<a href="#">Откликнуться</a>
<a href="#">Посмотреть контакты</a>
</div>
<div class="col-lg-12">
<h1><a href="vakansiya.html">Андроид разработчик</a></h1>
<h2>3 400 000 сум.+</h2>
<p>Фергана | 16 ноябрь 2020, 15:00</p>
<a href="#">Откликнуться</a>
<a href="#">Посмотреть контакты</a>
</div>
<div class="col-lg-12">
<h1><a href="vakansiya.html">Андроид разработчик</a></h1>
<h2>3 400 000 сум.+</h2>
<p>Фергана | 16 ноябрь 2020, 15:00</p>
<a href="#">Откликнуться</a>
<a href="#">Посмотреть контакты</a>
</div>
<nav>
<ul class="pagination">
<li>
<a href="#" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
<li class="active"><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
<li><a href="#">5</a></li>
<li>
<a href="#" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</ul>
</nav>
</div>
<!-- -->
<div class="col-lg-3">
<p>В данном разделе предложения о
работе в Ташкенте, Фергане, Ургенче
или в любом другом городе Узбекистана
найдут выпускники, студенты и тд.
Если вы еще учитесь и ищите подработку
работу в выходные дни или удаленную
работу - этот раздел для вас! На партале
есть удобные инструменты поиска: расширенный
поиск и пазличные фильтры благодаря которым
можно сформировать точный запрос? Укажите
тип занятости, график, желаемый размер заработной
платы, образование и специальность. </p>
</div>
</div>
<!-- -->
</div>
<footer class="col-lg-12">
<div class="container">
<div class="row">
<div class="col-lg-3">
<h1>Для компаний</h1>
<ul>
<li><a href="#">Добавить обьявления</a></li>
<li><a href="#">Помощь компаниям</a></li>
</ul>
</div>
<div class="col-lg-3">
<h1>CactusJobs.</h1>
<ul>
<li><a href="#">О нас</a></li>
<li><a href="#">Реклама</a></li>
<li><a href="#">Партнеры</a></li>
<li><a href="#">Архив предложений</a></li>
</ul>
</div>
<div class="col-lg-3">
<h1>Информация</h1>
<ul>
<li><a href="#">Политика конфиденциальности</a></li>
<li><a href="#">Политика использования файлов cookie</a></li>
<li><a href="#">Настройка файлов cookie</a></li>
</ul>
</div>
<div class="col-lg-3">
<h1>Скачать приложение</h1>
<ul>
<li><a href="#"><img src="images/apk-ios.jpg"></a></li>
<!-- <li><a href="#"><img src="images/appstore.png"></a></li> -->
</ul>
</div>
</div>
</div>
</footer>
<script src="js/jQuery.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>
</html>
|
sanjar8855/cactuscorp
|
refs/heads/master
|
/telegram.php
|
<?php
/* https://api.telegram.org/bot1430206287:AAGHi-PVElHdLIBhzNhAlv0nkivxnvH8jnM/getUpdates*/
$tel_nomer=$_POST['number']
$token = "1430206287:AAGHi-PVElHdLIBhzNhAlv0nkivxnvH8jnM";
$chat_id = "49394018";
$arr= array(
'Vakansiya ID: ' => '156',
'Фирма: ' => 'Raqamli Texnologiyalar Markazi',
'Нужен: ' => 'Андроид разработчик',
'Telefon №: ' => $tel_nomer,
);
foreach($arr as $key => $value){
$txt .= "<b>".$key."</b>".$value."%0A";
};
$sendToTelegram = fopen("https://api.telegram.org/bot{$token}/sendMessage?chat_id={$chat_id}&parse_mode=html&text={$txt}", "r");
if($sendToTelegram){
header('Location: vakansiya.html');
} else {
echo "Error";
}
?>
|
kaedelulu/U10316015_HW4_11_10
|
refs/heads/master
|
/TestStack.java
|
/**
* Name : 呂芝瑩
* ID : U10316015
* EX : 11.10
*/
import java.util.Scanner;
public class TestStack {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
MyStack stack = new MyStack(); //invoke stack
for ( int i = 0 ; i < 5 ; i++ ){
stack.push( input.nextLine() );
}
System.out.println(stack.getSize() + " strings are: ");
while (!stack.isEmpty())
System.out.println(stack.pop());
}
}
|
MissAle17/dsc-1-05-06-selecting-data-lab-online-ds-sp-000
|
refs/heads/master
|
/insert.sql
|
INSERT INTO planets (name, color, num_of_moons, mass, rings)
VALUES ('Mercury', 'gray',0,0.55,1),
('Venus', 'yellow',0,0.82,1),
('Earth','blue',1,1.00,1),
('Mars','red',2,0.11,1),
('Jupiter','orange',53,317.90,1),
('Saturn','hazel',62,95.19,0),
('Uranus','light blue',27,14.54,0),
('Neptune','dark blue',14,17.15,0),
('Pluto','brown',5,0.003,1);
|
phu-bui/Nhan_dien_bien_bao_giao_thong
|
refs/heads/master
|
/main.py
|
import tkinter as tk
from tkinter import filedialog
from tkinter import *
from PIL import Image, ImageTk
import numpy
from keras.models import load_model
model = load_model('BienBao.h5')
class_name = {
1:'Speed limit (20km/h)',
2:'Speed limit (30km/h)',
3:'Speed limit (50km/h)',
4:'Speed limit (60km/h)',
5:'Speed limit (70km/h)',
6:'Speed limit (80km/h)',
7:'End of speed limit (80km/h)',
8:'Speed limit (100km/h)',
9:'Speed limit (120km/h)',
10:'No passing',
11:'No passing veh over 3.5 tons',
12:'Right-of-way at intersection',
13:'Priority road',
14:'Yield',
15:'Stop',
16:'No vehicles',
17:'Veh > 3.5 tons prohibited',
18:'No entry',
19:'General caution',
20:'Dangerous curve left',
21:'Dangerous curve right',
22:'Double curve',
23:'Bumpy road',
24:'Slippery road',
25:'Road narrows on the right',
26:'Road work',
27:'Traffic signals',
28:'Pedestrians',
29:'Children crossing',
30:'Bicycles crossing',
31:'Beware of ice/snow',
32:'Wild animals crossing',
33:'End speed + passing limits',
34:'Turn right ahead',
35:'Turn left ahead',
36:'Ahead only',
37:'Go straight or right',
38:'Go straight or left',
39:'Keep right',
40:'Keep left',
41:'Roundabout mandatory',
42:'End of no passing',
43:'End no passing veh > 3.5 tons'
}
top=tk.Tk()
top.geometry('800x600')
top.title('Phan loai bien bao giao thong')
top.configure(background='#CDCDCD')
label = Label(top, background = '#CDCDCD', font=('arial',15,'bold'))
label.place(x=0, y=0, relwidth = 1, relheight = 1)
sign_image = Label(top)
def classify(file_path):
global label_packed
image = Image.open(file_path)
image = image.resize((30, 30))
image = numpy.expand_dims(image, axis=0)
image = numpy.array(image)
print(image.shape)
pred = model.predict_classes([image])[0]
sign = class_name[pred+1]
print(sign)
label.configure(foreground = '#011638', text = sign)
def show_classify_button(file_path):
classify_button = Button(top,text='Phan loai', command = lambda : classify(file_path), padx=10, pady=5)
classify_button.configure(background='GREEN', foreground = 'white', font = ('arial', 10, 'bold'))
classify_button.place(relx = 0.79, rely = 0.46)
def upload_image():
try:
file_path = filedialog.askopenfilename()
uploaded = Image.open(file_path)
uploaded.thumbnail(((top.winfo_width()/2.25),
(top.winfo_height()/2.25)))
im = ImageTk.PhotoImage(uploaded)
sign_image.configure(image= im)
sign_image.image = im
label.configure(text='')
show_classify_button(file_path)
except:
pass
upload = Button(top, text='Upload an image', command=upload_image, padx = 10, pady = 5)
upload.configure(background='#364156', foreground = 'white', font = ('arial', 10, 'bold'))
upload.pack(side = BOTTOM, pady = 50)
sign_image.pack(side=BOTTOM, expand = True)
label.pack(side = BOTTOM, expand = True)
heading = Label(top, text = 'Bien bao giao thong cua ban', pady = 20, font = ('arial', 20, 'bold'))
heading.configure(background = '#CDCDCD', foreground = '#364156')
heading.pack()
top.mainloop()
|
arun8785/ArunkumarAlgorithmsAssignmentSolution
|
refs/heads/main
|
/arunkumarAlgorithmsAssignmentSolution/src/com/stockers/model/StockDetails.java
|
package com.stockers.model;
import java.util.Scanner;
public class StockDetails {
private int noOfCompanies;
public double[] shrPrice;
public boolean[] shrGrowth;
public StockDetails(int noOfCompanies) {
this.noOfCompanies = noOfCompanies;
}
public double getnoOfCompanies() {
return noOfCompanies;
}
public void noOfCompanies(int noOfCompanies) {
this.noOfCompanies = noOfCompanies;
}
public void AddShareDetails() {
double[] shrPrice;
boolean[] shrGrowth;
shrPrice = new double[noOfCompanies];
shrGrowth = new boolean[noOfCompanies];
@SuppressWarnings("resource")
Scanner sr = new Scanner(System.in);
for(int i=0;i<noOfCompanies;i++) {
int j=i+1;
System.out.println("Enter current stock price of the company " + j);
shrPrice[i] = sr.nextDouble();
System.out.println("Whether company's stock price rose today compare to yesterday?");
shrGrowth[i] = sr.nextBoolean();
}
this.shrPrice = shrPrice;
this.shrGrowth = shrGrowth;
}
}
|
hsk/xterm.js
|
refs/heads/master
|
/src/xterm.ts
|
/**
* xterm.js: xterm, in the browser
* Originally forked from (with the author's permission):
* Fabrice Bellard's javascript vt100 for jslinux:
* http://bellard.org/jslinux/
* Copyright (c) 2011 Fabrice Bellard
* The original design remains. The terminal itself
* has been extended to include xterm CSI codes, among
* other features.
* @license MIT
*/
import { CompositionHelper } from './CompositionHelper';
import { EventEmitter } from './EventEmitter';
import { Viewport } from './Viewport';
import { rightClickHandler, pasteHandler, copyHandler } from './handlers/Clipboard';
import { CircularList } from './utils/CircularList';
import { C0 } from './EscapeSequences';
import { InputHandler } from './InputHandler';
import { Parser } from './Parser';
import { Renderer } from './Renderer';
import { Linkifier } from './Linkifier';
import { CharMeasure } from './utils/CharMeasure';
import * as Browser from './utils/Browser';
import { CHARSETS } from './Charsets';
import { IBrowser, IInputHandler, ITerminal, ICircularList, LinkMatcherOptions } from './Interfaces';
import { LinkMatcherHandler } from './Types';
declare var define: any;
declare var require: (id:string|string[],callback?:(...params:any[])=>any)=>any;
/**
* Terminal Emulation References:
* http://vt100.net/
* http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt
* http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
* http://invisible-island.net/vttest/
* http://www.inwap.com/pdp10/ansicode.txt
* http://linux.die.net/man/4/console_codes
* http://linux.die.net/man/7/urxvt
*/
// Let it work inside Node.js for automated testing purposes.
var document = (typeof window != 'undefined') ? window.document : null;
/**
* The amount of write requests to queue before sending an XOFF signal to the
* pty process. This number must be small in order for ^C and similar sequences
* to be responsive.
*/
var WRITE_BUFFER_PAUSE_THRESHOLD = 5;
/**
* The number of writes to perform in a single batch before allowing the
* renderer to catch up with a 0ms setTimeout.
*/
var WRITE_BATCH_SIZE = 300;
/**
* Terminal
*/
class Terminal extends EventEmitter implements ITerminal {
public colors:string[];
public options:any;
public parent:HTMLElement;
public geometry:number[];
public convertEol:boolean;
public queue:string;
public scrollTop:number;
public scrollBottom:number;
public customKeydownHandler:(string)=>any;
// modes
public applicationKeypad:boolean;
public applicationCursor:boolean;
public originMode:boolean;
public insertMode:boolean;
public wraparoundMode:boolean; // defaults: xterm - true, vt100 - false
public normal:boolean;
// misc
public refreshStart:number;
public refreshEnd:number;
public savedX:number;
public savedY:number;
//public savedCols:number;
// charset
public charset:string;
public gcharset:string;
public glevel:number;
public charsets:string[];
// mouse properties
public decLocator:boolean;
public x10Mouse:boolean;
public vt200Mouse:boolean;
public vt300Mouse:boolean;
public normalMouse:boolean;
public mouseEvents:boolean;
public sendFocus:boolean;
public utfMouse:boolean;
public sgrMouse:boolean;
public urxvtMouse:boolean;
// stream
public readable:boolean;
public writable:boolean;
public curAttr:number;
public params:any[];
public currentParam:number;
public prefix:string;
public postfix:string;
public inputHandler:IInputHandler;
public parser:Parser;
// Reuse renderer if the Terminal is being recreated via a Terminal.reset call.
public renderer:Renderer;
public linkifier:Linkifier;
// user input states
public writeInProgress:boolean;
public xoffSentToCatchUp:boolean;
// Whether writing has been stopped as a result of XOFF
public writeStopped:boolean;
// leftover surrogate high from previous write invocation
public surrogate_high:string;
public tabs:object;
scrollback:number;
// Store if user went browsing history in scrollback
public userScrolling: boolean;
element: HTMLElement;
rowContainer: HTMLElement;
textarea: HTMLTextAreaElement;
ybase: number;
ydisp: number;
lines: ICircularList<any>;
rows: number;
cols: number;
browser: IBrowser;
writeBuffer: string[];
children: HTMLElement[];
cursorHidden: boolean;
cursorState: number;
x: number;
y: number;
defAttr: number;
cancel:(ev: Event, force?: boolean)=>any;
public viewport:Viewport;
public context:any;
public document:HTMLDocument;
public body:HTMLElement;
public theme:string;
public viewportElement:HTMLElement;
public viewportScrollArea:HTMLElement;
public helperContainer:HTMLElement;
public compositionView:HTMLElement;
public compositionHelper:CompositionHelper;
public charSizeStyleElement:HTMLElement;
public charMeasure:CharMeasure;
public visualBell:string;
public popOnBell:string;
public debug:boolean;
public termName:string;
static cancelEvents:boolean;
/**
* Creates a new `Terminal` object.
*
* @param {object} options An object containing a set of options, the available options are:
* - `cursorBlink` (boolean): Whether the terminal cursor blinks
* - `cols` (number): The number of columns of the terminal (horizontal size)
* - `rows` (number): The number of rows of the terminal (vertical size)
*
* @public
* @class Xterm Xterm
* @alias module:xterm/src/xterm
*/
constructor(options:any) {
super();
var self = this;
/*
if (!(this instanceof Terminal)) {
return new Terminal(arguments[0], arguments[1], arguments[2]);
}
*/
self.browser = Browser;
self.cancel = Terminal.cancel;
EventEmitter.call(this);
if (typeof options === 'number') {
options = {
cols: arguments[0],
rows: arguments[1],
handler: arguments[2]
};
}
options = options || {};
Object.keys(Terminal.defaults).forEach(function(key) {
if (options[key] == null) {
options[key] = Terminal.options[key];
if (Terminal[key] !== Terminal.defaults[key]) {
options[key] = Terminal[key];
}
}
self[key] = options[key];
});
if (options.colors.length === 8) {
options.colors = options.colors.concat(Terminal._colors.slice(8));
} else if (options.colors.length === 16) {
options.colors = options.colors.concat(Terminal._colors.slice(16));
} else if (options.colors.length === 10) {
options.colors = options.colors.slice(0, -2).concat(
Terminal._colors.slice(8, -2), options.colors.slice(-2));
} else if (options.colors.length === 18) {
options.colors = options.colors.concat(
Terminal._colors.slice(16, -2), options.colors.slice(-2));
}
this.colors = options.colors;
this.options = options;
// this.context = options.context || window;
// this.document = options.document || document;
this.parent = options.body || options.parent || (
document ? document.getElementsByTagName('body')[0] : null
);
this.cols = options.cols || options.geometry[0];
this.rows = options.rows || options.geometry[1];
this.geometry = [this.cols, this.rows];
if (options.handler) {
this.on('data', options.handler);
}
/**
* The scroll position of the y cursor, ie. ybase + y = the y position within the entire
* buffer
*/
this.ybase = 0;
/**
* The scroll position of the viewport
*/
this.ydisp = 0;
/**
* The cursor's x position after ybase
*/
this.x = 0;
/**
* The cursor's y position after ybase
*/
this.y = 0;
this.cursorState = 0;
this.cursorHidden = false;
this.queue = '';
this.scrollTop = 0;
this.scrollBottom = this.rows - 1;
this.customKeydownHandler = null;
// modes
this.applicationKeypad = false;
this.applicationCursor = false;
this.originMode = false;
this.insertMode = false;
this.wraparoundMode = true; // defaults: xterm - true, vt100 - false
this.normal = null;
// charset
this.charset = null;
this.gcharset = null;
this.glevel = 0;
this.charsets = [null];
// stream
this.readable = true;
this.writable = true;
this.defAttr = (0 << 18) | (257 << 9) | (256 << 0);
this.curAttr = this.defAttr;
this.params = [];
this.currentParam = 0;
this.prefix = '';
this.postfix = '';
this.inputHandler = new InputHandler(this);
this.parser = new Parser(this.inputHandler, this);
// Reuse renderer if the Terminal is being recreated via a Terminal.reset call.
this.renderer = this.renderer || null;
this.linkifier = this.linkifier || null;;
// user input states
this.writeBuffer = [];
this.writeInProgress = false;
/**
* Whether _xterm.js_ sent XOFF in order to catch up with the pty process.
* This is a distinct state from writeStopped so that if the user requested
* XOFF via ^S that it will not automatically resume when the writeBuffer goes
* below threshold.
*/
this.xoffSentToCatchUp = false;
/** Whether writing has been stopped as a result of XOFF */
this.writeStopped = false;
// leftover surrogate high from previous write invocation
this.surrogate_high = '';
/**
* An array of all lines in the entire buffer, including the prompt. The lines are array of
* characters which are 2-length arrays where [0] is an attribute and [1] is the character.
*/
this.lines = new CircularList(this.scrollback);
var i = this.rows;
while (i--) {
this.lines.push(this.blankLine());
}
this.setupStops();
// Store if user went browsing history in scrollback
this.userScrolling = false;
}
/**
* back_color_erase feature for xterm.
*/
eraseAttr():number {
// if (this.is('screen')) return this.defAttr;
return (this.defAttr & ~0x1ff) | (this.curAttr & 0x1ff);
}
/**
* Colors
*/
// Colors 0-15
static tangoColors:string[] = [
// dark:
'#2e3436',
'#cc0000',
'#4e9a06',
'#c4a000',
'#3465a4',
'#75507b',
'#06989a',
'#d3d7cf',
// bright:
'#555753',
'#ef2929',
'#8ae234',
'#fce94f',
'#729fcf',
'#ad7fa8',
'#34e2e2',
'#eeeeec'
];
// Colors 0-15 + 16-255
// Much thanks to TooTallNate for writing this.
static colors:string[] = (function() {
var colors = Terminal.tangoColors.slice()
, r = [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]
, i
, k;
// 16-231
i = 0;
for (; i < 216; i++) {
out(r[(i / 36) % 6 | 0], r[(i / 6) % 6 | 0], r[i % 6]);
}
// 232-255 (grey)
i = 0;
for (; i < 24; i++) {
k = 8 + i * 10;
out(k, k, k);
}
function out(r, g, b) {
colors.push('#' + hex(r) + hex(g) + hex(b));
}
function hex(c) {
c = c.toString(16);
return c.length < 2 ? '0' + c : c;
}
return colors;
})();
static _colors:string[] = Terminal.colors.slice();
static vcolors:string[] = (function() {
var out = []
, colors = Terminal.colors
, i = 0
, color;
for (; i < 256; i++) {
color = parseInt(colors[i].substring(1), 16);
out.push([
(color >> 16) & 0xff,
(color >> 8) & 0xff,
color & 0xff
]);
}
return out;
})();
/**
* Options
*/
static defaults = {
colors: Terminal.colors,
theme: 'default',
convertEol: false,
termName: 'xterm',
geometry: [80, 24],
cursorBlink: false,
cursorStyle: 'block',
visualBell: false,
popOnBell: false,
scrollback: 1000,
screenKeys: false,
debug: false,
cancelEvents: false,
disableStdin: false,
useFlowControl: false,
tabStopWidth: 8
// programFeatures: false,
// focusKeys: false,
};
static options:any = {};
static focus:Terminal = null;
/**
* Focus the terminal. Delegates focus handling to the terminal's DOM element.
*/
focus(): void {
return this.textarea.focus();
}
/**
* Retrieves an option's value from the terminal.
* @param {string} key The option key.
*/
getOption(key:string):any {
if (!(key in Terminal.defaults)) {
throw new Error('No option with key "' + key + '"');
}
if (typeof this.options[key] !== 'undefined') {
return this.options[key];
}
return this[key];
}
/**
* Sets an option on the terminal.
* @param {string} key The option key.
* @param {string} value The option value.
*/
setOption(key:string, value:any):void {
if (!(key in Terminal.defaults)) {
throw new Error('No option with key "' + key + '"');
}
switch (key) {
case 'scrollback':
if (this.options[key] !== value) {
if (this.lines.length > value) {
const amountToTrim = this.lines.length - value;
const needsRefresh = (this.ydisp - amountToTrim < 0);
this.lines.trimStart(amountToTrim);
this.ybase = Math.max(this.ybase - amountToTrim, 0);
this.ydisp = Math.max(this.ydisp - amountToTrim, 0);
if (needsRefresh) {
this.refresh(0, this.rows - 1);
}
}
this.lines.maxLength = value;
this.viewport.syncScrollArea();
}
break;
}
this[key] = value;
this.options[key] = value;
switch (key) {
case 'cursorBlink': this.element.classList.toggle('xterm-cursor-blink', value); break;
case 'cursorStyle':
// Style 'block' applies with no class
this.element.classList.toggle(`xterm-cursor-style-underline`, value === 'underline');
this.element.classList.toggle(`xterm-cursor-style-bar`, value === 'bar');
break;
case 'tabStopWidth': this.setupStops(); break;
}
};
/**
* Binds the desired focus behavior on a given terminal object.
*
* @static
*/
static bindFocus(term:Terminal):void {
on(term.textarea, 'focus', function (ev) {
if (term.sendFocus) {
term.send(C0.ESC + '[I');
}
term.element.classList.add('focus');
term.showCursor();
Terminal.focus = term;
term.emit('focus', {terminal: term});
});
};
/**
* Blur the terminal. Delegates blur handling to the terminal's DOM element.
*/
blur():void {
return this.textarea.blur();
};
/**
* Binds the desired blur behavior on a given terminal object.
*
* @static
*/
static bindBlur(term:Terminal):void {
on(term.textarea, 'blur', function (ev) {
term.refresh(term.y, term.y);
if (term.sendFocus) {
term.send(C0.ESC + '[O');
}
term.element.classList.remove('focus');
Terminal.focus = null;
term.emit('blur', {terminal: term});
});
};
/**
* Initialize default behavior
*/
initGlobal():void {
var term = this;
Terminal.bindKeys(this);
Terminal.bindFocus(this);
Terminal.bindBlur(this);
// Bind clipboard functionality
on(this.element, 'copy', function (ev) {
copyHandler.call(this, ev, term);
});
on(this.textarea, 'paste', function (ev) {
pasteHandler.call(this, ev, term);
});
on(this.element, 'paste', function (ev) {
pasteHandler.call(this, ev, term);
});
function rightClickHandlerWrapper (ev) {
rightClickHandler.call(this, ev, term);
}
if (term.browser.isFirefox) {
on(this.element, 'mousedown', function (ev) {
if (ev.button == 2) {
rightClickHandlerWrapper(ev);
}
});
} else {
on(this.element, 'contextmenu', rightClickHandlerWrapper);
}
}
/**
* Apply key handling to the terminal
*/
static bindKeys(term:Terminal):void {
on(term.element, 'keydown', function(ev) {
if (document.activeElement != this) {
return;
}
term.keyDown(ev);
}, true);
on(term.element, 'keypress', function(ev) {
if (document.activeElement != this) {
return;
}
term.keyPress(ev);
}, true);
on(term.element, 'keyup', function(ev) {
function wasMondifierKeyOnlyEvent(ev:KeyboardEvent):boolean {
return ev.keyCode === 16 || // Shift
ev.keyCode === 17 || // Ctrl
ev.keyCode === 18; // Alt
}
if (!wasMondifierKeyOnlyEvent(ev)) {
term.focus();
}
}, true);
on(term.textarea, 'keydown', function(ev) {
term.keyDown(ev);
}, true);
on(term.textarea, 'keypress', function(ev) {
term.keyPress(ev);
// Truncate the textarea's value, since it is not needed
this.value = '';
}, true);
on(term.textarea, 'compositionstart', term.compositionHelper.compositionstart.bind(term.compositionHelper));
on(term.textarea, 'compositionupdate', term.compositionHelper.compositionupdate.bind(term.compositionHelper));
on(term.textarea, 'compositionend', term.compositionHelper.compositionend.bind(term.compositionHelper));
term.on('refresh', term.compositionHelper.updateCompositionElements.bind(term.compositionHelper));
term.on('refresh', function (data) {
term.queueLinkification(data.start, data.end)
});
}
/**
* Insert the given row to the terminal or produce a new one
* if no row argument is passed. Return the inserted row.
* @param {HTMLElement} row (optional) The row to append to the terminal.
*/
insertRow(row?:HTMLElement):HTMLElement {
if (typeof row != 'object') {
row = document.createElement('div');
}
this.rowContainer.appendChild(row);
this.children.push(row);
return row;
};
/**
* Opens the terminal within an element.
*
* @param {HTMLElement} parent The element to create the terminal within.
*/
open(parent:HTMLElement):void {
var self=this, i=0, div;
this.parent = parent || this.parent;
if (!this.parent) {
throw new Error('Terminal requires a parent element.');
}
// Grab global elements
this.context = this.parent.ownerDocument.defaultView;
this.document = this.parent.ownerDocument;
this.body = this.document.getElementsByTagName('body')[0];
//Create main element container
this.element = this.document.createElement('div');
this.element.classList.add('terminal');
this.element.classList.add('xterm');
this.element.classList.add('xterm-theme-' + this.theme);
this.element.classList.toggle('xterm-cursor-blink', this.options.cursorBlink);
this.element.style.height
this.element.setAttribute('tabindex', '0');
this.viewportElement = document.createElement('div');
this.viewportElement.classList.add('xterm-viewport');
this.element.appendChild(this.viewportElement);
this.viewportScrollArea = document.createElement('div');
this.viewportScrollArea.classList.add('xterm-scroll-area');
this.viewportElement.appendChild(this.viewportScrollArea);
// Create the container that will hold the lines of the terminal and then
// produce the lines the lines.
this.rowContainer = document.createElement('div');
this.rowContainer.classList.add('xterm-rows');
this.element.appendChild(this.rowContainer);
this.children = [];
this.linkifier = new Linkifier(document, this.children);
// Create the container that will hold helpers like the textarea for
// capturing DOM Events. Then produce the helpers.
this.helperContainer = document.createElement('div');
this.helperContainer.classList.add('xterm-helpers');
// TODO: This should probably be inserted once it's filled to prevent an additional layout
this.element.appendChild(this.helperContainer);
this.textarea = document.createElement('textarea');
this.textarea.classList.add('xterm-helper-textarea');
this.textarea.setAttribute('autocorrect', 'off');
this.textarea.setAttribute('autocapitalize', 'off');
this.textarea.setAttribute('spellcheck', 'false');
this.textarea.tabIndex = 0;
this.textarea.addEventListener('focus', function() {
self.emit('focus', {terminal: self});
});
this.textarea.addEventListener('blur', function() {
self.emit('blur', {terminal: self});
});
this.helperContainer.appendChild(this.textarea);
this.compositionView = document.createElement('div');
this.compositionView.classList.add('composition-view');
this.compositionHelper = new CompositionHelper(this.textarea, this.compositionView, this);
this.helperContainer.appendChild(this.compositionView);
this.charSizeStyleElement = document.createElement('style');
this.helperContainer.appendChild(this.charSizeStyleElement);
for (; i < this.rows; i++) {
this.insertRow();
}
this.parent.appendChild(this.element);
this.charMeasure = new CharMeasure(document, this.helperContainer);
this.charMeasure.on('charsizechanged', function () {
self.updateCharSizeCSS();
});
this.charMeasure.measure();
this.viewport = new Viewport(this, this.viewportElement, this.viewportScrollArea, this.charMeasure);
this.renderer = new Renderer(this);
// Setup loop that draws to screen
this.refresh(0, this.rows - 1);
// Initialize global actions that
// need to be taken on the document.
this.initGlobal();
// Ensure there is a Terminal.focus.
this.focus();
on(this.element, 'click', function() {
var selection = document.getSelection(),
collapsed = selection.isCollapsed,
isRange = typeof collapsed == 'boolean' ? !collapsed : selection.type == 'Range';
if (!isRange) {
self.focus();
}
});
// Listen for mouse events and translate
// them into terminal mouse protocols.
this.bindMouse();
/**
* This event is emitted when terminal has completed opening.
*
* @event open
*/
this.emit('open');
};
/**
* Attempts to load an add-on using CommonJS or RequireJS (whichever is available).
* @param {string} addon The name of the addon to load
* @static
*/
static loadAddon(addon:string, callback?:(...params:any[])=>any):any {
if (typeof exports === 'object' && typeof module === 'object') {
// CommonJS
return require('./addons/' + addon + '/' + addon);
} else if (typeof define == 'function') {
// RequireJS
return require(['./addons/' + addon + '/' + addon], callback);
} else {
console.error('Cannot load a module without a CommonJS or RequireJS environment.');
return false;
}
};
/**
* Updates the helper CSS class with any changes necessary after the terminal's
* character width has been changed.
*/
updateCharSizeCSS(): void {
this.charSizeStyleElement.textContent = '.xterm-wide-char{width:' + (this.charMeasure.width * 2) + 'px;}';
}
/**
* XTerm mouse events
* http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
* To better understand these
* the xterm code is very helpful:
* Relevant files:
* button.c, charproc.c, misc.c
* Relevant functions in xterm/button.c:
* BtnCode, EmitButtonCode, EditorButton, SendMousePosition
*/
bindMouse():void {
var el = this.element, self = this, pressed = 32;
// mouseup, mousedown, wheel
// left click: ^[[M 3<^[[M#3<
// wheel up: ^[[M`3>
function sendButton(ev) {
var button
, pos;
// get the xterm-style button
button = getButton(ev);
// get mouse coordinates
pos = getCoords(ev);
if (!pos) return;
sendEvent(button, pos);
switch (ev.overrideType || ev.type) {
case 'mousedown':
pressed = button;
break;
case 'mouseup':
// keep it at the left
// button, just in case.
pressed = 32;
break;
case 'wheel':
// nothing. don't
// interfere with
// `pressed`.
break;
}
}
// motion example of a left click:
// ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7<
function sendMove(ev) {
var button = pressed
, pos;
pos = getCoords(ev);
if (!pos) return;
// buttons marked as motions
// are incremented by 32
button += 32;
sendEvent(button, pos);
}
// encode button and
// position to characters
function encode(data, ch) {
if (!self.utfMouse) {
if (ch === 255) return data.push(0);
if (ch > 127) ch = 127;
data.push(ch);
} else {
if (ch === 2047) return data.push(0);
if (ch < 127) {
data.push(ch);
} else {
if (ch > 2047) ch = 2047;
data.push(0xC0 | (ch >> 6));
data.push(0x80 | (ch & 0x3F));
}
}
}
// send a mouse event:
// regular/utf8: ^[[M Cb Cx Cy
// urxvt: ^[[ Cb ; Cx ; Cy M
// sgr: ^[[ Cb ; Cx ; Cy M/m
// vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r
// locator: CSI P e ; P b ; P r ; P c ; P p & w
function sendEvent(button, pos) {
// self.emit('mouse', {
// x: pos.x - 32,
// y: pos.x - 32,
// button: button
// });
if (self.vt300Mouse) {
// NOTE: Unstable.
// http://www.vt100.net/docs/vt3xx-gp/chapter15.html
button &= 3;
pos.x -= 32;
pos.y -= 32;
var data = C0.ESC + '[24';
if (button === 0) data += '1';
else if (button === 1) data += '3';
else if (button === 2) data += '5';
else if (button === 3) return;
else data += '0';
data += '~[' + pos.x + ',' + pos.y + ']\r';
self.send(data);
return;
}
if (self.decLocator) {
// NOTE: Unstable.
button &= 3;
pos.x -= 32;
pos.y -= 32;
if (button === 0) button = 2;
else if (button === 1) button = 4;
else if (button === 2) button = 6;
else if (button === 3) button = 3;
self.send(C0.ESC + '['
+ button
+ ';'
+ (button === 3 ? 4 : 0)
+ ';'
+ pos.y
+ ';'
+ pos.x
+ ';'
+ (pos.page || 0)
+ '&w');
return;
}
if (self.urxvtMouse) {
pos.x -= 32;
pos.y -= 32;
pos.x++;
pos.y++;
self.send(C0.ESC + '[' + button + ';' + pos.x + ';' + pos.y + 'M');
return;
}
if (self.sgrMouse) {
pos.x -= 32;
pos.y -= 32;
self.send(C0.ESC + '[<'
+ (((button & 3) === 3 ? button & ~3 : button) - 32)
+ ';'
+ pos.x
+ ';'
+ pos.y
+ ((button & 3) === 3 ? 'm' : 'M'));
return;
}
var dt = [];
encode(dt, button);
encode(dt, pos.x);
encode(dt, pos.y);
self.send(C0.ESC + '[M' + String.fromCharCode.apply(String, dt));
}
function getButton(ev) {
var button
, shift
, meta
, ctrl
, mod;
// two low bits:
// 0 = left
// 1 = middle
// 2 = right
// 3 = release
// wheel up/down:
// 1, and 2 - with 64 added
switch (ev.overrideType || ev.type) {
case 'mousedown':
button = ev.button != null
? +ev.button
: ev.which != null
? ev.which - 1
: null;
if (self.browser.isMSIE) {
button = button === 1 ? 0 : button === 4 ? 1 : button;
}
break;
case 'mouseup':
button = 3;
break;
case 'DOMMouseScroll':
button = ev.detail < 0
? 64
: 65;
break;
case 'wheel':
button = ev.wheelDeltaY > 0
? 64
: 65;
break;
}
// next three bits are the modifiers:
// 4 = shift, 8 = meta, 16 = control
shift = ev.shiftKey ? 4 : 0;
meta = ev.metaKey ? 8 : 0;
ctrl = ev.ctrlKey ? 16 : 0;
mod = shift | meta | ctrl;
// no mods
if (self.vt200Mouse) {
// ctrl only
mod &= ctrl;
} else if (!self.normalMouse) {
mod = 0;
}
// increment to SP
button = (32 + (mod << 2)) + button;
return button;
}
// mouse coordinates measured in cols/rows
function getCoords(ev) {
var x, y, w, h, el;
// ignore browsers without pageX for now
if (ev.pageX == null) return;
x = ev.pageX;
y = ev.pageY;
el = self.element;
// should probably check offsetParent
// but this is more portable
while (el && el !== self.document.documentElement) {
x -= el.offsetLeft;
y -= el.offsetTop;
el = 'offsetParent' in el
? el.offsetParent
: el.parentNode;
}
// convert to cols/rows
x = Math.ceil(x / self.charMeasure.width);
y = Math.ceil(y / self.charMeasure.height);
// be sure to avoid sending
// bad positions to the program
if (x < 0) x = 0;
if (x > self.cols) x = self.cols;
if (y < 0) y = 0;
if (y > self.rows) y = self.rows;
// xterm sends raw bytes and
// starts at 32 (SP) for each.
x += 32;
y += 32;
return {
x: x,
y: y,
type: 'wheel'
};
}
on(el, 'mousedown', function(ev) {
if (!self.mouseEvents) return;
// send the button
sendButton(ev);
// ensure focus
self.focus();
// fix for odd bug
//if (self.vt200Mouse && !self.normalMouse) {
if (self.vt200Mouse) {
ev.overrideType = 'mouseup';
sendButton(ev);
return self.cancel(ev);
}
// bind events
if (self.normalMouse) on(self.document, 'mousemove', sendMove);
// x10 compatibility mode can't send button releases
if (!self.x10Mouse) {
on(self.document, 'mouseup', function up(ev) {
sendButton(ev);
if (self.normalMouse) off(self.document, 'mousemove', sendMove);
off(self.document, 'mouseup', up);
return self.cancel(ev);
});
}
return self.cancel(ev);
});
//if (self.normalMouse) {
// on(self.document, 'mousemove', sendMove);
//}
on(el, 'wheel', function(ev) {
if (!self.mouseEvents) return;
if (self.x10Mouse
|| self.vt300Mouse
|| self.decLocator) return;
sendButton(ev);
return self.cancel(ev);
});
// allow wheel scrolling in
// the shell for example
on(el, 'wheel', function(ev) {
if (self.mouseEvents) return;
self.viewport.onWheel(ev);
return self.cancel(ev);
});
}
/**
* Destroys the terminal.
*/
destroy():void {
this.readable = false;
this.writable = false;
this._events = {};
this.handler = function() {};
this.write = function() {};
if (this.element && this.element.parentNode) {
this.element.parentNode.removeChild(this.element);
}
//this.emit('close');
};
/**
* Tells the renderer to refresh terminal content between two rows (inclusive) at the next
* opportunity.
* @param {number} start The row to start from (between 0 and this.rows - 1).
* @param {number} end The row to end at (between start and this.rows - 1).
*/
refresh(start:number, end:number):void {
if (this.renderer) {
this.renderer.queueRefresh(start, end);
}
};
/**
* Queues linkification for the specified rows.
* @param {number} start The row to start from (between 0 and this.rows - 1).
* @param {number} end The row to end at (between start and this.rows - 1).
*/
queueLinkification(start:number, end:number):void {
if (this.linkifier) {
for (let i = start; i <= end; i++) {
this.linkifier.linkifyRow(i);
}
}
}
/**
* Display the cursor element
*/
showCursor():void {
if (!this.cursorState) {
this.cursorState = 1;
this.refresh(this.y, this.y);
}
}
/**
* Scroll the terminal down 1 row, creating a blank line.
*/
scroll():void {
var row;
// Make room for the new row in lines
if (this.lines.length === this.lines.maxLength) {
this.lines.trimStart(1);
this.ybase--;
if (this.ydisp !== 0) {
this.ydisp--;
}
}
this.ybase++;
// TODO: Why is this done twice?
if (!this.userScrolling) {
this.ydisp = this.ybase;
}
// last line
row = this.ybase + this.rows - 1;
// subtract the bottom scroll region
row -= this.rows - 1 - this.scrollBottom;
if (row === this.lines.length) {
// Optimization: pushing is faster than splicing when they amount to the same behavior
this.lines.push(this.blankLine());
} else {
// add our new line
this.lines.splice(row, 0, this.blankLine());
}
if (this.scrollTop !== 0) {
if (this.ybase !== 0) {
this.ybase--;
if (!this.userScrolling) {
this.ydisp = this.ybase;
}
}
this.lines.splice(this.ybase + this.scrollTop, 1);
}
// this.maxRange();
this.updateRange(this.scrollTop);
this.updateRange(this.scrollBottom);
/**
* This event is emitted whenever the terminal is scrolled.
* The one parameter passed is the new y display position.
*
* @event scroll
*/
this.emit('scroll', this.ydisp);
}
/**
* Scroll the display of the terminal
* @param {number} disp The number of lines to scroll down (negatives scroll up).
* @param {boolean} suppressScrollEvent Don't emit the scroll event as scrollDisp. This is used
* to avoid unwanted events being handled by the veiwport when the event was triggered from the
* viewport originally.
*/
scrollDisp(disp:number, suppressScrollEvent?:boolean):void {
if (disp < 0) {
this.userScrolling = true;
} else if (disp + this.ydisp >= this.ybase) {
this.userScrolling = false;
}
this.ydisp += disp;
if (this.ydisp > this.ybase) {
this.ydisp = this.ybase;
} else if (this.ydisp < 0) {
this.ydisp = 0;
}
if (!suppressScrollEvent) {
this.emit('scroll', this.ydisp);
}
this.refresh(0, this.rows - 1);
}
/**
* Scroll the display of the terminal by a number of pages.
* @param {number} pageCount The number of pages to scroll (negative scrolls up).
*/
scrollPages(pageCount:number):void {
this.scrollDisp(pageCount * (this.rows - 1));
}
/**
* Scrolls the display of the terminal to the top.
*/
scrollToTop():void {
this.scrollDisp(-this.ydisp);
}
/**
* Scrolls the display of the terminal to the bottom.
*/
scrollToBottom():void {
this.scrollDisp(this.ybase - this.ydisp);
}
/**
* Writes text to the terminal.
* @param {string} text The text to write to the terminal.
*/
write(data:string):void {
this.writeBuffer.push(data);
// Send XOFF to pause the pty process if the write buffer becomes too large so
// xterm.js can catch up before more data is sent. This is necessary in order
// to keep signals such as ^C responsive.
if (this.options.useFlowControl && !this.xoffSentToCatchUp && this.writeBuffer.length >= WRITE_BUFFER_PAUSE_THRESHOLD) {
// XOFF - stop pty pipe
// XON will be triggered by emulator before processing data chunk
this.send(C0.DC3);
this.xoffSentToCatchUp = true;
}
if (!this.writeInProgress && this.writeBuffer.length > 0) {
// Kick off a write which will write all data in sequence recursively
this.writeInProgress = true;
// Kick off an async innerWrite so more writes can come in while processing data
var self = this;
setTimeout(function () {
self.innerWrite();
});
}
}
innerWrite():void {
var writeBatch = this.writeBuffer.splice(0, WRITE_BATCH_SIZE);
while (writeBatch.length > 0) {
var data = writeBatch.shift();
var l = data.length, i = 0, j, cs, ch, code, low, ch_width, row;
// If XOFF was sent in order to catch up with the pty process, resume it if
// the writeBuffer is empty to allow more data to come in.
if (this.xoffSentToCatchUp && writeBatch.length === 0 && this.writeBuffer.length === 0) {
this.send(C0.DC1);
this.xoffSentToCatchUp = false;
}
this.refreshStart = this.y;
this.refreshEnd = this.y;
this.parser.parse(data);
this.updateRange(this.y);
this.refresh(this.refreshStart, this.refreshEnd);
}
if (this.writeBuffer.length > 0) {
// Allow renderer to catch up before processing the next batch
var self = this;
setTimeout(function () {
self.innerWrite();
}, 0);
} else {
this.writeInProgress = false;
}
}
/**
* Writes text to the terminal, followed by a break line character (\n).
* @param {string} text The text to write to the terminal.
*/
writeln(data:string):void {
this.write(data + '\r\n');
}
/**
* Attaches a custom keydown handler which is run before keys are processed, giving consumers of
* xterm.js ultimate control as to what keys should be processed by the terminal and what keys
* should not.
* @param {function} customKeydownHandler The custom KeyboardEvent handler to attach. This is a
* function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
* the default action. The function returns whether the event should be processed by xterm.js.
*/
attachCustomKeydownHandler(customKeydownHandler:(string)=>any):void {
this.customKeydownHandler = customKeydownHandler;
}
/**
* Attaches a http(s) link handler, forcing web links to behave differently to
* regular <a> tags. This will trigger a refresh as links potentially need to be
* reconstructed. Calling this with null will remove the handler.
* @param {LinkHandler} handler The handler callback function.
*/
attachHypertextLinkHandler(handler:LinkMatcherHandler):void {
if (!this.linkifier) {
throw new Error('Cannot attach a hypertext link handler before Terminal.open is called');
}
this.linkifier.attachHypertextLinkHandler(handler);
// Refresh to force links to refresh
this.refresh(0, this.rows - 1);
}
/**
* Registers a link matcher, allowing custom link patterns to be matched and
* handled.
* @param {RegExp} regex The regular expression to search for, specifically
* this searches the textContent of the rows. You will want to use \s to match
* a space ' ' character for example.
* @param {LinkHandler} handler The callback when the link is called.
* @param {LinkMatcherOptions} [options] Options for the link matcher.
* @return {number} The ID of the new matcher, this can be used to deregister.
*/
registerLinkMatcher(regex: RegExp, handler: LinkMatcherHandler, options?:LinkMatcherOptions): number {
if (this.linkifier) {
var matcherId = this.linkifier.registerLinkMatcher(regex, handler, options);
this.refresh(0, this.rows - 1);
return matcherId;
}
}
/**
* Deregisters a link matcher if it has been registered.
* @param {number} matcherId The link matcher's ID (returned after register)
*/
deregisterLinkMatcher(matcherId:number):void {
if (this.linkifier) {
if (this.linkifier.deregisterLinkMatcher(matcherId)) {
this.refresh(0, this.rows - 1);
}
}
}
/**
* Handle a keydown event
* Key Resources:
* - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
* @param {KeyboardEvent} ev The keydown event to be handled.
*/
keyDown(ev:KeyboardEvent):boolean {
if (this.customKeydownHandler && this.customKeydownHandler(ev) === false) {
return false;
}
if (!this.compositionHelper.keydown.bind(this.compositionHelper)(ev)) {
if (this.ybase !== this.ydisp) {
this.scrollToBottom();
}
return false;
}
var self = this;
var result = this.evaluateKeyEscapeSequence(ev);
if (result.key === C0.DC3) { // XOFF
this.writeStopped = true;
} else if (result.key === C0.DC1) { // XON
this.writeStopped = false;
}
if (result.scrollDisp) {
this.scrollDisp(result.scrollDisp);
return this.cancel(ev, true);
}
if (isThirdLevelShift(this, ev)) {
return true;
}
if (result.cancel) {
// The event is canceled at the end already, is this necessary?
this.cancel(ev, true);
}
if (!result.key) {
return true;
}
this.emit('keydown', ev);
this.emit('key', result.key, ev);
this.showCursor();
this.handler(result.key);
return this.cancel(ev, true);
}
/**
* Returns an object that determines how a KeyboardEvent should be handled. The key of the
* returned value is the new key code to pass to the PTY.
*
* Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
* @param {KeyboardEvent} ev The keyboard event to be translated to key escape sequence.
*/
evaluateKeyEscapeSequence(ev:any):{cancel:boolean,key:string,scrollDisp:number} {
var result = {
// Whether to cancel event propogation (NOTE: this may not be needed since the event is
// canceled at the end of keyDown
cancel: false,
// The new key even to emit
key: undefined,
// The number of characters to scroll, if this is defined it will cancel the event
scrollDisp: undefined
};
var modifiers = ev.shiftKey << 0 | ev.altKey << 1 | ev.ctrlKey << 2 | ev.metaKey << 3;
switch (ev.keyCode) {
case 8:
// backspace
if (ev.shiftKey) {
result.key = C0.BS; // ^H
break;
}
result.key = C0.DEL; // ^?
break;
case 9:
// tab
if (ev.shiftKey) {
result.key = C0.ESC + '[Z';
break;
}
result.key = C0.HT;
result.cancel = true;
break;
case 13:
// return/enter
result.key = C0.CR;
result.cancel = true;
break;
case 27:
// escape
result.key = C0.ESC;
result.cancel = true;
break;
case 37:
// left-arrow
if (modifiers) {
result.key = C0.ESC + '[1;' + (modifiers + 1) + 'D';
// HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
// http://unix.stackexchange.com/a/108106
// macOS uses different escape sequences than linux
if (result.key == C0.ESC + '[1;3D') {
result.key = (this.browser.isMac) ? C0.ESC + 'b' : C0.ESC + '[1;5D';
}
} else if (this.applicationCursor) {
result.key = C0.ESC + 'OD';
} else {
result.key = C0.ESC + '[D';
}
break;
case 39:
// right-arrow
if (modifiers) {
result.key = C0.ESC + '[1;' + (modifiers + 1) + 'C';
// HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
// http://unix.stackexchange.com/a/108106
// macOS uses different escape sequences than linux
if (result.key == C0.ESC + '[1;3C') {
result.key = (this.browser.isMac) ? C0.ESC + 'f' : C0.ESC + '[1;5C';
}
} else if (this.applicationCursor) {
result.key = C0.ESC + 'OC';
} else {
result.key = C0.ESC + '[C';
}
break;
case 38:
// up-arrow
if (modifiers) {
result.key = C0.ESC + '[1;' + (modifiers + 1) + 'A';
// HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
// http://unix.stackexchange.com/a/108106
if (result.key == C0.ESC + '[1;3A') {
result.key = C0.ESC + '[1;5A';
}
} else if (this.applicationCursor) {
result.key = C0.ESC + 'OA';
} else {
result.key = C0.ESC + '[A';
}
break;
case 40:
// down-arrow
if (modifiers) {
result.key = C0.ESC + '[1;' + (modifiers + 1) + 'B';
// HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
// http://unix.stackexchange.com/a/108106
if (result.key == C0.ESC + '[1;3B') {
result.key = C0.ESC + '[1;5B';
}
} else if (this.applicationCursor) {
result.key = C0.ESC + 'OB';
} else {
result.key = C0.ESC + '[B';
}
break;
case 45:
// insert
if (!ev.shiftKey && !ev.ctrlKey) {
// <Ctrl> or <Shift> + <Insert> are used to
// copy-paste on some systems.
result.key = C0.ESC + '[2~';
}
break;
case 46:
// delete
if (modifiers) {
result.key = C0.ESC + '[3;' + (modifiers + 1) + '~';
} else {
result.key = C0.ESC + '[3~';
}
break;
case 36:
// home
if (modifiers)
result.key = C0.ESC + '[1;' + (modifiers + 1) + 'H';
else if (this.applicationCursor)
result.key = C0.ESC + 'OH';
else
result.key = C0.ESC + '[H';
break;
case 35:
// end
if (modifiers)
result.key = C0.ESC + '[1;' + (modifiers + 1) + 'F';
else if (this.applicationCursor)
result.key = C0.ESC + 'OF';
else
result.key = C0.ESC + '[F';
break;
case 33:
// page up
if (ev.shiftKey) {
result.scrollDisp = -(this.rows - 1);
} else {
result.key = C0.ESC + '[5~';
}
break;
case 34:
// page down
if (ev.shiftKey) {
result.scrollDisp = this.rows - 1;
} else {
result.key = C0.ESC + '[6~';
}
break;
case 112:
// F1-F12
if (modifiers) {
result.key = C0.ESC + '[1;' + (modifiers + 1) + 'P';
} else {
result.key = C0.ESC + 'OP';
}
break;
case 113:
if (modifiers) {
result.key = C0.ESC + '[1;' + (modifiers + 1) + 'Q';
} else {
result.key = C0.ESC + 'OQ';
}
break;
case 114:
if (modifiers) {
result.key = C0.ESC + '[1;' + (modifiers + 1) + 'R';
} else {
result.key = C0.ESC + 'OR';
}
break;
case 115:
if (modifiers) {
result.key = C0.ESC + '[1;' + (modifiers + 1) + 'S';
} else {
result.key = C0.ESC + 'OS';
}
break;
case 116:
if (modifiers) {
result.key = C0.ESC + '[15;' + (modifiers + 1) + '~';
} else {
result.key = C0.ESC + '[15~';
}
break;
case 117:
if (modifiers) {
result.key = C0.ESC + '[17;' + (modifiers + 1) + '~';
} else {
result.key = C0.ESC + '[17~';
}
break;
case 118:
if (modifiers) {
result.key = C0.ESC + '[18;' + (modifiers + 1) + '~';
} else {
result.key = C0.ESC + '[18~';
}
break;
case 119:
if (modifiers) {
result.key = C0.ESC + '[19;' + (modifiers + 1) + '~';
} else {
result.key = C0.ESC + '[19~';
}
break;
case 120:
if (modifiers) {
result.key = C0.ESC + '[20;' + (modifiers + 1) + '~';
} else {
result.key = C0.ESC + '[20~';
}
break;
case 121:
if (modifiers) {
result.key = C0.ESC + '[21;' + (modifiers + 1) + '~';
} else {
result.key = C0.ESC + '[21~';
}
break;
case 122:
if (modifiers) {
result.key = C0.ESC + '[23;' + (modifiers + 1) + '~';
} else {
result.key = C0.ESC + '[23~';
}
break;
case 123:
if (modifiers) {
result.key = C0.ESC + '[24;' + (modifiers + 1) + '~';
} else {
result.key = C0.ESC + '[24~';
}
break;
default:
// a-z and space
if (ev.ctrlKey && !ev.shiftKey && !ev.altKey && !ev.metaKey) {
if (ev.keyCode >= 65 && ev.keyCode <= 90) {
result.key = String.fromCharCode(ev.keyCode - 64);
} else if (ev.keyCode === 32) {
// NUL
result.key = String.fromCharCode(0);
} else if (ev.keyCode >= 51 && ev.keyCode <= 55) {
// escape, file sep, group sep, record sep, unit sep
result.key = String.fromCharCode(ev.keyCode - 51 + 27);
} else if (ev.keyCode === 56) {
// delete
result.key = String.fromCharCode(127);
} else if (ev.keyCode === 219) {
// ^[ - Control Sequence Introducer (CSI)
result.key = String.fromCharCode(27);
} else if (ev.keyCode === 220) {
// ^\ - String Terminator (ST)
result.key = String.fromCharCode(28);
} else if (ev.keyCode === 221) {
// ^] - Operating System Command (OSC)
result.key = String.fromCharCode(29);
}
} else if (!this.browser.isMac && ev.altKey && !ev.ctrlKey && !ev.metaKey) {
// On Mac this is a third level shift. Use <Esc> instead.
if (ev.keyCode >= 65 && ev.keyCode <= 90) {
result.key = C0.ESC + String.fromCharCode(ev.keyCode + 32);
} else if (ev.keyCode === 192) {
result.key = C0.ESC + '`';
} else if (ev.keyCode >= 48 && ev.keyCode <= 57) {
result.key = C0.ESC + (ev.keyCode - 48);
}
}
break;
}
return result;
};
/**
* Set the G level of the terminal
* @param g
*/
setgLevel(g:number):void {
this.glevel = g;
this.charset = this.charsets[g];
};
/**
* Set the charset for the given G level of the terminal
* @param g
* @param charset
*/
setgCharset(g:number, charset:string):void {
this.charsets[g] = charset;
if (this.glevel === g) {
this.charset = charset;
}
};
/**
* Handle a keypress event.
* Key Resources:
* - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
* @param {KeyboardEvent} ev The keypress event to be handled.
*/
keyPress(ev:KeyboardEvent):boolean {
var key;
this.cancel(ev);
if (ev.charCode) {
key = ev.charCode;
} else if (ev.which == null) {
key = ev.keyCode;
} else if (ev.which !== 0 && ev.charCode !== 0) {
key = ev.which;
} else {
return false;
}
if (!key || (
(ev.altKey || ev.ctrlKey || ev.metaKey) && !isThirdLevelShift(this, ev)
)) {
return false;
}
key = String.fromCharCode(key);
this.emit('keypress', key, ev);
this.emit('key', key, ev);
this.showCursor();
this.handler(key);
return false;
};
/**
* Send data for handling to the terminal
* @param {string} data
*/
send(data:string):void {
var self = this;
if (!this.queue) {
setTimeout(function() {
self.handler(self.queue);
self.queue = '';
}, 1);
}
this.queue += data;
};
/**
* Ring the bell.
* Note: We could do sweet things with webaudio here
*/
bell():void {
if (!this.visualBell) return;
var self = this;
this.element.style.borderColor = 'white';
setTimeout(function() {
self.element.style.borderColor = '';
}, 10);
if (this.popOnBell) this.focus();
};
/**
* Log the current state to the console.
*/
log():void {
if (!this.debug) return;
if (!this.context.console || !this.context.console.log) return;
var args = Array.prototype.slice.call(arguments);
this.context.console.log.apply(this.context.console, args);
};
/**
* Log the current state as error to the console.
*/
error():void {
if (!this.debug) return;
if (!this.context.console || !this.context.console.error) return;
var args = Array.prototype.slice.call(arguments);
this.context.console.error.apply(this.context.console, args);
};
/**
* Resizes the terminal.
*
* @param {number} x The number of columns to resize to.
* @param {number} y The number of rows to resize to.
*/
resize(x:number, y:number):void {
if (isNaN(x) || isNaN(y)) {
return;
}
var line
, el
, i
, j
, ch
, addToY;
if (x === this.cols && y === this.rows) {
return;
}
if (x < 1) x = 1;
if (y < 1) y = 1;
// resize cols
j = this.cols;
if (j < x) {
ch = [this.defAttr, ' ', 1]; // does xterm use the default attr?
i = this.lines.length;
while (i--) {
while (this.lines.get(i).length < x) {
this.lines.get(i).push(ch);
}
}
} else { // (j > x)
i = this.lines.length;
while (i--) {
while (this.lines.get(i).length > x) {
this.lines.get(i).pop();
}
}
}
this.cols = x;
this.setupStops(this.cols);
// resize rows
j = this.rows;
addToY = 0;
if (j < y) {
el = this.element;
while (j++ < y) {
// y is rows, not this.y
if (this.lines.length < y + this.ybase) {
if (this.ybase > 0 && this.lines.length <= this.ybase + this.y + addToY + 1) {
// There is room above the buffer and there are no empty elements below the line,
// scroll up
this.ybase--;
addToY++
if (this.ydisp > 0) {
// Viewport is at the top of the buffer, must increase downwards
this.ydisp--;
}
} else {
// Add a blank line if there is no buffer left at the top to scroll to, or if there
// are blank lines after the cursor
this.lines.push(this.blankLine());
}
}
if (this.children.length < y) {
this.insertRow();
}
}
} else { // (j > y)
while (j-- > y) {
if (this.lines.length > y + this.ybase) {
if (this.lines.length > this.ybase + this.y + 1) {
// The line is a blank line below the cursor, remove it
this.lines.pop();
} else {
// The line is the cursor, scroll down
this.ybase++;
this.ydisp++;
}
}
if (this.children.length > y) {
el = this.children.shift();
if (!el) continue;
el.parentNode.removeChild(el);
}
}
}
this.rows = y;
// Make sure that the cursor stays on screen
if (this.y >= y) {
this.y = y - 1;
}
if (addToY) {
this.y += addToY;
}
if (this.x >= x) {
this.x = x - 1;
}
this.scrollTop = 0;
this.scrollBottom = y - 1;
this.charMeasure.measure();
this.refresh(0, this.rows - 1);
this.normal = null;
this.geometry = [this.cols, this.rows];
this.emit('resize', {terminal: this, cols: x, rows: y});
};
/**
* Updates the range of rows to refresh
* @param {number} y The number of rows to refresh next.
*/
updateRange(y:number):void {
if (y < this.refreshStart) this.refreshStart = y;
if (y > this.refreshEnd) this.refreshEnd = y;
// if (y > this.refreshEnd) {
// this.refreshEnd = y;
// if (y > this.rows - 1) {
// this.refreshEnd = this.rows - 1;
// }
// }
};
/**
* Set the range of refreshing to the maximum value
*/
maxRange():void {
this.refreshStart = 0;
this.refreshEnd = this.rows - 1;
};
/**
* Setup the tab stops.
* @param {number} i
*/
setupStops(i?:number):void {
if (i != null) {
if (!this.tabs[i]) {
i = this.prevStop(i);
}
} else {
this.tabs = {};
i = 0;
}
for (; i < this.cols; i += this.getOption('tabStopWidth')) {
this.tabs[i] = true;
}
};
/**
* Move the cursor to the previous tab stop from the given position (default is current).
* @param {number} x The position to move the cursor to the previous tab stop.
*/
prevStop(x?:number):number {
if (x == null) x = this.x;
while (!this.tabs[--x] && x > 0);
return x >= this.cols
? this.cols - 1
: x < 0 ? 0 : x;
};
/**
* Move the cursor one tab stop forward from the given position (default is current).
* @param {number} x The position to move the cursor one tab stop forward.
*/
nextStop(x?:number):number {
if (x == null) x = this.x;
while (!this.tabs[++x] && x < this.cols);
return x >= this.cols
? this.cols - 1
: x < 0 ? 0 : x;
};
/**
* Erase in the identified line everything from "x" to the end of the line (right).
* @param {number} x The column from which to start erasing to the end of the line.
* @param {number} y The line in which to operate.
*/
eraseRight(x:number, y:number):void {
var line = this.lines.get(this.ybase + y);
if (!line) {
return;
}
var ch = [this.eraseAttr(), ' ', 1]; // xterm
for (; x < this.cols; x++) {
line[x] = ch;
}
this.updateRange(y);
}
/**
* Erase in the identified line everything from "x" to the start of the line (left).
* @param {number} x The column from which to start erasing to the start of the line.
* @param {number} y The line in which to operate.
*/
eraseLeft(x:number, y:number):void {
var line = this.lines.get(this.ybase + y);
if (!line) {
return;
}
var ch = [this.eraseAttr(), ' ', 1]; // xterm
x++;
while (x--) {
line[x] = ch;
}
this.updateRange(y);
}
/**
* Clears the entire buffer, making the prompt line the new first line.
*/
clear():void {
if (this.ybase === 0 && this.y === 0) {
// Don't clear if it's already clear
return;
}
this.lines.set(0, this.lines.get(this.ybase + this.y));
this.lines.length = 1;
this.ydisp = 0;
this.ybase = 0;
this.y = 0;
for (var i = 1; i < this.rows; i++) {
this.lines.push(this.blankLine());
}
this.refresh(0, this.rows - 1);
this.emit('scroll', this.ydisp);
};
/**
* Erase all content in the given line
* @param {number} y The line to erase all of its contents.
*/
eraseLine(y:number):void {
this.eraseRight(0, y);
};
/**
* Return the data array of a blank line
* @param {number} cur First bunch of data for each "blank" character.
*/
blankLine(cur?:boolean):any[][] {
var attr = cur
? this.eraseAttr()
: this.defAttr;
var ch = [attr, ' ', 1] // width defaults to 1 halfwidth character
, line = []
, i = 0;
for (; i < this.cols; i++) {
line[i] = ch;
}
return line;
};
/**
* If cur return the back color xterm feature attribute. Else return defAttr.
* @param {object} cur
*/
ch(cur:object):[number,string,number] {
return cur
? [this.eraseAttr(), ' ', 1]
: [this.defAttr, ' ', 1];
};
/**
* Evaluate if the current erminal is the given argument.
* @param {object} term The terminal to evaluate
*/
is(term:string):boolean {
var name = this.termName;
return (name + '').indexOf(term) === 0;
};
/**
* Emit the 'data' event and populate the given data.
* @param {string} data The data to populate in the event.
*/
handler(data:string):void {
// Prevents all events to pty process if stdin is disabled
if (this.options.disableStdin) {
return;
}
// Input is being sent to the terminal, the terminal should focus the prompt.
if (this.ybase !== this.ydisp) {
this.scrollToBottom();
}
this.emit('data', data);
}
/**
* Emit the 'title' event and populate the given title.
* @param {string} title The title to populate in the event.
*/
handleTitle(title:string):void {
/**
* This event is emitted when the title of the terminal is changed
* from inside the terminal. The parameter is the new title.
*
* @event title
*/
this.emit('title', title);
}
/**
* ESC
*/
/**
* ESC D Index (IND is 0x84).
*/
index():void {
this.y++;
if (this.y > this.scrollBottom) {
this.y--;
this.scroll();
}
// If the end of the line is hit, prevent this action from wrapping around to the next line.
if (this.x >= this.cols) {
this.x--;
}
}
/**
* ESC M Reverse Index (RI is 0x8d).
*
* Move the cursor up one row, inserting a new blank line if necessary.
*/
reverseIndex():void {
var j;
if (this.y === this.scrollTop) {
// possibly move the code below to term.reverseScroll();
// test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
// blankLine(true) is xterm/linux behavior
this.lines.shiftElements(this.y + this.ybase, this.rows - 1, 1);
this.lines.set(this.y + this.ybase, this.blankLine(true));
this.updateRange(this.scrollTop);
this.updateRange(this.scrollBottom);
} else {
this.y--;
}
}
/**
* ESC c Full Reset (RIS).
*/
reset():void {
this.options.rows = this.rows;
this.options.cols = this.cols;
var customKeydownHandler = this.customKeydownHandler;
Terminal.call(this, this.options);
this.customKeydownHandler = customKeydownHandler;
this.refresh(0, this.rows - 1);
this.viewport.syncScrollArea();
}
/**
* ESC H Tab Set (HTS is 0x88).
*/
tabSet():void {
this.tabs[this.x] = true;
}
/**
* Helpers
*/
static on(el:EventTarget|EventTarget[], type:string, handler:(...args:any[])=>any, capture?:boolean):void {
var els:EventTarget[] = Array.isArray(el) ? el : [el];
els.forEach(function (element) {
element.addEventListener(type, handler, capture || false);
});
}
static off(el:EventTarget, type:string, handler:(...args:any[])=>any, capture?:boolean):void {
el.removeEventListener(type, handler, capture || false);
}
static cancel(ev:Event, force?:boolean):boolean {
if (!this.cancelEvents && !force) {
return;
}
ev.preventDefault();
ev.stopPropagation();
return false;
}
static EventEmitter = EventEmitter;
static inherits(child:any, parent:any):void {
function f() {
this.constructor = child;
}
f.prototype = parent.prototype;
child.prototype = new f;
}
static matchColor_cache:object = {};
matchColor(r1:number, g1:number, b1:number):number {
// http://stackoverflow.com/questions/1633828
function distance(r1, g1, b1, r2, g2, b2) {
return Math.pow(30 * (r1 - r2), 2)
+ Math.pow(59 * (g1 - g2), 2)
+ Math.pow(11 * (b1 - b2), 2);
};
var hash = (r1 << 16) | (g1 << 8) | b1;
if (Terminal.matchColor_cache[hash] != null) {
return Terminal.matchColor_cache[hash];
}
var ldiff = Infinity
, li = -1
, i = 0
, c
, r2
, g2
, b2
, diff;
for (; i < Terminal.vcolors.length; i++) {
c = Terminal.vcolors[i];
r2 = c[0];
g2 = c[1];
b2 = c[2];
diff = distance(r1, g1, b1, r2, g2, b2);
if (diff === 0) {
li = i;
break;
}
if (diff < ldiff) {
ldiff = diff;
li = i;
}
}
return Terminal.matchColor_cache[hash] = li;
}
}
Object.keys(Terminal.defaults).forEach(function(key:string):void {
Terminal[key] = Terminal.defaults[key];
Terminal.options[key] = Terminal.defaults[key];
});
function isThirdLevelShift(term:Terminal, ev:KeyboardEvent):boolean {
var thirdLevelKey =
(term.browser.isMac && ev.altKey && !ev.ctrlKey && !ev.metaKey) ||
(term.browser.isMSWindows && ev.altKey && ev.ctrlKey && !ev.metaKey);
if (ev.type == 'keypress') {
return thirdLevelKey;
}
// Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
return thirdLevelKey && (!ev.keyCode || ev.keyCode > 47);
}
/**
* Adds an event listener to the terminal.
*
* @param {string} event The name of the event. TODO: Document all event types
* @param {function} callback The function to call when the event is triggered.
*/
var on = Terminal.on;
var off = Terminal.off;
var cancel = Terminal.cancel;
module.exports = Terminal;
|
adamwiguna/tugas1
|
refs/heads/master
|
/tugas.js
|
window.onload = function (event) {
var wrapIcon = document.querySelector("#wrapicon");
var page = 1;
var limit = 3;
var url = "https://jsonplaceholder.typicode.com/posts";
var serverUrl = url + '?_page=' + page + '&_limit=' + limit;
fetch(serverUrl)
.then(
function (resp) {
return resp.json();
}
)
.then(
function (data) {
//console.log(data);
data.forEach(function (val, index) {
//console.log(val);
var div = document.createElement('div');
div.className = "icon-item";
var blogTitle = document.createElement('h3');
var detail = document.createElement('a');
detail.href = 'detail.html';
detail.innerHTML = 'Detail';
var blogBody = document.createElement('p');
blogTitle.name = "title";
blogTitle.innerHTML = val.title;
blogTitle.style.height = "100px";
blogBody.innerText = val.body;
div.appendChild(blogTitle);
div.appendChild(blogBody);
wrapIcon.appendChild(div);
});
});
function getBlogs(url, page = 1, limit = 3) {
console.log('ambil data...')
var serverUrl = url + '?_page=' + page + '&_limit=' + limit;
fetch(serverUrl)
.then(
function (resp) {
return resp.json();
}
)
.then(
function (data) {
//console.log(data);
data.forEach(function (val, index) {
//console.log(val);
var blogTitle = document.createElement('h3');
var detail = document.createElement('a');
detail.href = 'detail.html';
detail.innerHTML = 'Detail';
var blogBody = document.createElement('p');
blogTitle.name = "title";
blogTitle.innerHTML = '<a href="detail.html?id=' + val.id + '">' + val.title + '</a>';
blogBody.innerText = val.body;
wrapper.appendChild(blogTitle);
wrapper.appendChild(blogBody);
});
//display load more
loadmore.style.display = 'block';
});
//display load more
loadmore.style.display = 'block';
}
function getDetail() {
}
var contactForm = document.querySelector('#contactform')
contactForm.addEventListener("submit", function (event) {
console.log('form submitted');
event.preventDefault();
var formName = document.querySelector('#form-name');
var formEmail = document.querySelector('#form-email');
var formMessage = document.querySelector('#form-message');
var formData = {
name: formName.value,
email: formEmail.value,
message: formMessage.value,
}
//console.log(formName.value);
fetch('http://localhost:3000/contacts', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
})
.then(function (resp) {
return resp.json();
})
.then(function (data) {
//succesfully submitted
console.log(data);
})
.catch(function (error) {
//something error happened
console.error(error);
});
});
console.log('selesai');
}
|
drenovac/superail
|
refs/heads/main
|
/config/routes.rb
|
Rails.application.routes.draw do
root 'static_public#landing_page'
# get 'static_public/landing_page' # this is the generic form
# get 'static_public/privacy' # convert this to more sensible looking paths
get 'privacy', to: 'static_public#privacy'
# get 'static_public/terms'
get 'terms', to: 'static_public#terms'
end
|
goodshitman/warframe-status
|
refs/heads/master
|
/lib/caches/cache.js
|
'use strict';
const EventEmitter = require('events');
const http = require('http');
const https = require('https');
class Cache extends EventEmitter {
constructor(url, timeout, {
parser, promiseLib = Promise, logger, delayStart = true, opts, maxListeners = 45,
} = {}) {
super();
this.url = url;
this.protocol = this.url.startsWith('https') ? https : http;
this.timeout = timeout;
this.currentData = null;
this.updating = null;
this.Promise = promiseLib;
this.parser = parser;
this.hash = null;
this.logger = logger;
this.delayStart = delayStart;
this.opts = opts;
if (!delayStart) {
this.startUpdating();
}
this.setMaxListeners(maxListeners);
}
getData() {
if (this.delayStart) {
this.startUpdating();
}
if (this.updating) {
return this.updating;
}
return this.Promise.resolve(this.currentData);
}
startUpdating() {
this.updateInterval = setInterval(() => this.update(), this.timeout);
this.update();
}
stopUpdating() {
clearInterval(this.updateInterval);
}
update() {
this.updating = this.httpGet().then(async (data) => {
this.currentData = this.parser(data, this.opts);
setTimeout(async () => this.emit('update', await this.currentData), 2000);
this.updating = null;
return this.currentData;
}).catch((err) => {
this.updating = null;
throw err;
});
}
httpGet() {
return new this.Promise((resolve, reject) => {
const request = this.protocol.get(this.url, (response) => {
if (response.statusCode < 200 || response.statusCode > 299) {
reject(new Error(`Failed to load page, status code: ${response.statusCode}`));
}
const body = [];
response.on('data', chunk => body.push(chunk));
response.on('end', () => resolve(body.join('')));
});
request.on('error', err => reject(err));
});
}
}
module.exports = Cache;
|
homka506/digitalproducts
|
refs/heads/master
|
/src/assets/js/app.js
|
import $ from 'jquery';
import 'what-input';
// Foundation JS relies on a global varaible. In ES6, all imports are hoisted
// to the top of the file so if we used`import` to import Foundation,
// it would execute earlier than we have assigned the global variable.
// This is why we have to use CommonJS require() here since it doesn't
// have the hoisting behavior.
window.jQuery = $;
// require('foundation-sites');
// If you want to pick and choose which modules to include, comment out the above and uncomment
// the line below
import './lib/foundation-explicit-pieces';
import './lib/slick.min.js';
let worksSlider = $(".ba-slider__works");
worksSlider.slick({
ainfinite: false,
dots: true,
arrows:true,
prevArrow: worksSlider.find('[data-prev]'),
nextArrow: worksSlider.find('[data-next]')
});
$(document).foundation();
function baMap() {
//create map and asign it to the baMap var
let mapCenter = {
lat: 40.678177,
lng: -73.944160
};
let baMap = new google.maps.Map(document.getElementById('ba-map'), {
center: mapCenter,
zoom: 12,
icon: 'img/marker.svg'
});
// The marker, positioned in mapcenter
let cities = {
rome: {
lat: 41.902782,
lng: 12.496365
},
paris: {
lat: 48.856613,
lng: 2.352222
},
madrid: {
lat: 40.416775,
lng: -3.703790
},
}
let mapMarkers = [];
for (let key in cities) {
var marker = new google.maps.Marker({
position: mapCenter,
map: baMap,
icon: 'img/marker.svg'
});
mapMarkers[key] = marker; //save markers in object
}
//on select city
$('#city-select').on('change', function (e) {
baMap.panTo(cities[this.value]);
});
} // function ba-map
$(document).ready(function (e) {
baMap();
})();
let teamSlider = $('.ba-team-slider');
teamSlider.slick({
centerPadding: '60px',
slidesToShow: 1,
ainfinite: false,
dots: true,
prevArrow: teamSlider.find('[data-prev]'),
nextArrow: teamSlider.find('[data-next]'),
responsive: [
{
breakpoint: 768,
settings: {
arrows: true,
centerMode: true,
centerPadding: '40px',
slidesToShow: 3
}
},
{
breakpoint: 480,
settings: {
arrows: true,
centerMode: true,
centerPadding: '40px',
slidesToShow: 1
}
}
]
});
|
baltorius89/NF3-PAC02-PHP-i-MySQL
|
refs/heads/master
|
/N3P206JavierComments.php.php
|
<?php
echo "<p>\n";
echo "\t<ul>
\t<li>Me parece util la manera en que guardas la creacion de tablas e inserts dentro de variables</li>
\t<li>Puedo utilizar las variables para ahorrarme el tener que implementar el codigo siempre</li>
\t<li>La relacion entre tablas me parece mas simple que en MYSQL</li>
\t<li>La conexion de la base de datos y autentificacion me parece muy util</li>
\t<li>Puedes mezclar html y php en el mismo fichero</li>
\t<li>La manera de concatenar variables y texto es bastante simple</li>
\t<li>Con el get puedo coger cualquier tipo de dato</li>
\t<li>Me parece util la manera de meter los inserts</li>
\t<li>Me ha parecido util la manera en la que se usa la paginacion</li>
\t<li>Puedo imprimir las querys con las variables muy facilmente</li>
</ul>\n";
echo "</p>\n";
echo "<p>Mi puntuacion al documento es de un 0 y la puntuacion de la explicacion del profesor un 7";
echo "</p>\n";
echo "<p>Me daria la puntuacion de un 5";
echo "</p>\n";
echo "<p>Mi profesor me ha ayudado bastante, y me ha motivado, pero en lo que respecta al documento habia muchissimos errores de sintaxis";
echo "</p>";
?>
|
baltorius89/NF3-PAC02-PHP-i-MySQL
|
refs/heads/master
|
/PaginaConsultaMySQL (1).php
|
<?php
$db = mysqli_connect('localhost', 'root') or
die ('Unable to connect. Check your connection parameters.');
mysqli_select_db($db,'animesite') or die(mysqli_error($db));
// select the movie titles and their genre after 1990
$query = 'select anime_id, anime_name, anime_year, anime_type, animetype_label, caracter_fullname
from anime, animetype, caracter
where (anime_type=animetype_id) and (anime_director=caracter_id)';
$result = mysqli_query($db, $query) or die(mysqli_error($db));
// show the results
while ($row = mysqli_fetch_assoc($result)) {
extract($row);
echo $anime_id . ' - ' . $anime_name . ' - ' . $anime_year . ' - ' . $anime_type . ' - ' . $animetype_label . ' - ' . $caracter_fullname . '</br>';
}
?>
<?php
$noRegistros = 1; //Registros por página
$pagina = 1; //Por defecto pagina = 1
if($_GET['pagina'])
$pagina = $_GET['pagina']; //Si hay pagina, lo asigna
$buskr=$_GET['searchs']; //Palabra a buscar
//Utilizo el comando LIMIT para seleccionar un rango de registros
$sSQL = "SELECT * FROM anime WHERE anime_name LIKE '%$buskr%' LIMIT " . ($pagina - 1) * $noRegistros . ",$noRegistros";
$result = mysqli_query($db,$sSQL) or die(mysqli_error($db));
//Exploracion de registros
echo "<table>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td height=80 align=center>$row[anime_id]<br>";
echo "</td><td align=center>$row[anime_name]</td>";
echo "</td><td align=center>$row[anime_year]</td>";
echo "</tr>";
}
//Imprimiendo paginacion
$sSQL = "SELECT count(*) FROM anime WHERE anime_name LIKE '%$buskr%'";
//Cuento el total de registros
$result = mysqli_query($db,$sSQL);
$row = mysqli_fetch_array($result);
$totalRegistros = $row["count(*)"]; //Almaceno el total
$noPaginas = $totalRegistros/$noRegistros; //Determino la cantidad de paginas
?>
<tr>
<td colspan="2" align="center"><?php echo "<strong>Total registros: </strong>".$totalRegistros.";" ?></td>
<td colspan="2" align="center"><?php echo "<strong>Pagina: </strong>".$pagina.";" ?></td>
</tr>
<tr bgcolor="f3f4f1">
<td colspan="4" align="right"><strong>Pagina:
<?php
for($i=1; $i<$noPaginas+1; $i++) { //Imprimo las paginas
if($i == $pagina)
echo "<font color=red>".$i."</font>"; //No link
else
echo "<a href=\"?pagina=".$i."&searchs=".$buskr."\" style=color:#000;> ".$i."</a>";
}
?>
|
kesamercy/diving-Competition-project
|
refs/heads/master
|
/README.md
|
# diving-Competition-project
Program to calculate score for a diver based on 7 judges
Problem Statement
Create a class that describes one dive in a competition in the sport of diving.
A dive has a competitor name and a competitor number associated with it.
The dive also has a degree of difficulty and a score from each of the seven judges.
Each score awarded is between 0 and 10, where each score may be a floating-point value.
The highest and lowest scores are thrown out and the remaining scores are added together.
The sum is then multiplied by the degree of difficulty for that dive.
The degree of difficulty ranges from 1.2 to 3.8 points.
The total is then multiplied by 0.6 to determine the diver’s score.
The class must include the appropriate methods to support object oriented programming as well as the following problem specific methods:
• Class for diving competition.
• Declare Attributes
• Initialize using a Constructor
• Use Methods
• Set methods
• Get methods
• Print data
• Method for Competitor name and competitor number
• The Degree of difficulty is 1.2 – 3.8
• Score from judges is 0 and 10 double
• Take out the highest score
• Take out the lowest score
• Add the rest
• Multiply the sum by the degree of difficulty
• Total is multipled by 0.6 to determine divers score
• A method name inputValidScore that inputs one valid score for one judge for one diver.
• A method named inputAllScores that creates an array to store the scores for all judges for the diver. This method will fill the array with a valid score from each judge.
• A method named inputValidDegreeOfDifficulty that inputs a valid degree of difficulty for the dive.
• A method named calculateScore that will calculate the score for the diver based on the scores from all judges and the degree of difficulty.
• A method that will input the diver information including the name and the competition number.
• A method that prints out all attributes in the class.
• INPUT DIVER INFORMATION as a method no return statement so it is void
Create a main method that is in a separate class including no attributes and no other methods besides main. A main method that creates a Dive object, inputs all information about the dive, and then prints out all information for the dive.
• Input all information basically call the class
• Print out all information of the class
Additional Directions
• You must not use any Array class or Array method included in the Java libraries to solve this problem
• Console input and output must be used to solve this problem.
• When you are satisfied that your solution works then use the following input values to run your program to create your output file.
Diver Name Use your actual name
Diver Number 327
Degree of difficulty 2.7
Judge #1 score 7.5
Judge #2 score 9.5
Judge #3 score 5.7
Judge #4 score 8.25
Judge #5 score 6.72
Judge #6 score 10.0
Judge #7 score 3.46
• Part I. Program Design
o Rewrite the problem statement in your own words using short bulleted phrases
o Create a class skeleton for this problem – show your attribute declarations and appropriate comment descriptions. Also show comment header blocks for your methods. You do not include the code for the methods at this point Note you do not have to include MyUtilityClass and its methods in the design work.
o Post your completed design work for this problem in Blackboard before class begins on the due date listed in the syllabus.
• Part II. Completed Program
o You must complete all of the code for this program and run the program using the specific input values defined in these instructions to generate an output file.
o Print out a copy of your output file and also your source code in all classes except for MyUtilityClass to turn in for this homework on the due date listed in the syllabus.
|
kesamercy/diving-Competition-project
|
refs/heads/master
|
/OneDiveClass.java
|
//
// OneDive
// The purpose of this class is to describe one class
//
// Author: Nekesa Mercy
// Date: 11/02/16
//
package divingCompetitionPackage;
public class OneDiveClass {
//declare attributes
private String name; // the name of the diver
private int competitonNum; // the competition number for the diver
private double[ ]allScores; // all the scores for one diver from all the judges
private double degreeOfDifficulty; // the degree of difficulty for the dive
private double finalScore; // the final score for the diver
private double oneScore; // one score for the diver from the judge
private double maxScore; // the maximum score the diver
private double minScore; // the minimum score for the diver
//declare constants here
private double MAXIMUMSCORE = 10.0;
private double MINIMUMSCORE = 0.0;
private double MAXIMUMDEGDIFFICULTY = 3.8;
private double MINIMUMDEGREEDIFFICULTY = 1.2;
private double NUMTOMULTIPLY = 0.6;
private int NUMJUDGES = 7;
// OneDive
// the purpose of this method is to initialize all attributes
// Input: none
// Return: none
//
public OneDiveClass( ){
int cntr;
name = "none yet";
competitonNum = 0;
degreeOfDifficulty = 0.0;
finalScore = 0.0;
maxScore = 0.0;
minScore = 0.0;
oneScore = 0.0;
//create space for the array
allScores = new double[NUMJUDGES];
for(cntr = 0; cntr < allScores.length; ++cntr){
allScores[cntr] = 0;
}// end for
}// end OneDive
//
// OneDive
// the purpose of this method is to initialize all new attributes
//
// Input: nme // the name
// compNum // the competetion number
// sc // scores
// allSc // array for all the scores for one person
// degDiff // the degree of difficulty
// finSc // the final score
// Return: none
//
public void OneDive(String nme, int compNum, double[]allsc, double degDiff, double finSc ){
int cntr;
name = nme;
competitonNum = compNum;
degreeOfDifficulty = degDiff;
finalScore = finSc;
allScores = new double[NUMJUDGES];
for(cntr = 0; cntr < allScores.length; ++cntr){
allScores[cntr] = allsc[cntr];
}// end for
}// end OneDive
//
// setName
// The purpose of this method is to set a new name for the diver
//
// input: nme // the new name
// return: none
//
public void setName(String nme){
name = nme;
}// end setName
//
// setCompetitionNum
// The purpose of this method is to set a new value for the competition number for the diver
//
// input: compNum // the new competition number
// return:none
//
public void setCompetitionNum(int compNum){
competitonNum = compNum;
}// end competitionNum
//
// setDegreeOfDIfficulty
// The purpose of this method is to set new values for the degree of difficulty
//
// input: degreeOfDifficulty // the array for the new value for the degree of difficulty
// return: none
//
public void setDegreeOfDifficulty(double degDiff){
degreeOfDifficulty = degDiff;
}// end setDegreeOfDifficulty
//
// getName
// The purpose of this method is to return the name
//
// input: none
// return: name // the name
//
public String getName( ){
return(name);
}// end getName
//
// getCompetitionNum
// The purpose of this method is to return the competition number
//
// input: none
// return: competitionNum // the competition number
//
public int getCompetitionNum( ){
return(competitonNum);
}// end getCompetitionNum
//
// getAllScores
// The purpose of this method is to return the array for all the scores for one diver
//
// input: none
// return: allScores // all the scores for one diver
//
public double[] getAllScore( ){
return(allScores);
}// end getAllSocres
//
// getDegreeOfDifficulty
// The purpose of this method is to return the value for the degree of difficulty
//
// input: none
// return: degreeOfDifficulty // the value for the degree of difficulty
//
public double getDegreeOfDifficulty( ){
return(degreeOfDifficulty);
}// end getDegreeOfDifficulty
//
// getFinalScore
// The purpose of this method is to return the final score for the diver
//
// input: none
// return: finalScore // the final score for the diver
//
public double getFinalScore( ){
return(finalScore);
}// end getFinalScore
//
// printData
// The purpose of this method is to print out all the attributes of the class
//
// Input: none
// return: none
public void printData(){
int cntr;
System.out.println("The name of the diver is " + name);
System.out.println("The competition number for the diver is " + competitonNum);
for(cntr = 0; cntr < allScores.length; ++cntr){
System.out.println("The scores for the diver are " + allScores[cntr]);
}// end for
System.out.println("The degree of difficulty is " + degreeOfDifficulty);
System.out.println("The final score for the diver is " + finalScore);
}// end printData
//
// inputDiverinfo
// The purpose of this method is to input the diver's information
//
// input: none
// return: none
public void inputDiverInfo( ){
//input the name of the diver
name = MyUtilityClass.inputString("Enter the name of the diver");
//input the competition number of the diver
competitonNum = MyUtilityClass.inputInteger("Enter the competition number of the diver");
}// end inputDiverInfo
//
// inputAllScores
// The purpose of this method is to input all scores for all the judges for the diver
//
// Input: none
// return : none
//
public void inputAllScores( ){
int cntr;
for(cntr = 0; cntr < allScores.length; ++cntr){
do{
if((allScores[cntr] >= MINIMUMSCORE) ||(allScores[cntr] <= MAXIMUMSCORE)){
allScores[cntr] = MyUtilityClass.inputDouble("Enter the score for the diver ");
}// end if
else{
System.out.println("Error, invalid socre " + allScores[cntr]);
}// end else
}while((allScores[cntr] < MINIMUMSCORE) ||(allScores[cntr] > MAXIMUMSCORE) );
}// end for
}// end inputAllScores
//
// inputValidDegreeOfDificulty
// The purpose of this method is to input a valid degree of difficulty for the dive
//
// Input: none
// return : none
//
public void inputValidDegreeOfDifficulty( ){
do{
if((degreeOfDifficulty >= MINIMUMDEGREEDIFFICULTY)||(degreeOfDifficulty <= MAXIMUMDEGDIFFICULTY )){
degreeOfDifficulty = MyUtilityClass.inputDouble("Enter the degree of difficulty for the diver ");
}// end if
else{
System.out.println("Error, invalid number for degree of difficulty " + degreeOfDifficulty);
}// end else
}while((degreeOfDifficulty < MINIMUMDEGREEDIFFICULTY)||(degreeOfDifficulty > MAXIMUMDEGDIFFICULTY ));
}// end inputValidDegreeOfDifficulty
//
// findMaxScoreOneDive
//
// The purpose of this method is to find the highest score for one diver
//
// Input: allScores // array that holds all scores for one diver
//
// REturn: maxScore // highest score for that bowler
//
public double findMaxScoreOneDive(double[] allScores){
int cntr;
for (cntr = 0; cntr < allScores.length; ++cntr)
{
if (allScores[cntr] > maxScore)
{
maxScore = allScores[cntr];
}// end if
}// end for
return(maxScore);
}// end findMaxScoreOneDive
//
// findMinScoreOneDive
//
// The purpose of this method is to find the lowest score for one diver
//
// Input: allScores // array that holds all scores for one diver
//
// REturn: minScore // lowest score for one diver
//
public double findMinScoreOneDive(double[]allScores){
int cntr;
for (cntr = 0; cntr < allScores.length;++cntr)
{
if (allScores[cntr] < minScore)
{
minScore = allScores[cntr];
}// end if
}// end for
return(minScore);
}// end findMinScoreOneDive
// calculateScore
// The purpose of this method is to calculate the score of the diver based on the scores from the judges and the degree of difficulty
//
// Input: allScores // all the scores from all the judges from one diver
// degreeOfDifficulty // the value for the level of difficulty for the dive
// maxScore // the maximum score
// minScore // the minimum score
// return : finalScore // over all score for the diver based on the scores from the judges
//
public double calculateFinalScore( ){
//declare variables
double sumExtremes;
double totalFinal;
double firstTotal;
double total;
int cntr;
//initialize variables
sumExtremes = 0.0;
totalFinal = 0.0;
firstTotal = 0.0;
total = 0;
//calculate the sum of the minimum and maximum
sumExtremes = maxScore + minScore;
//find the total score for all the scores
for(cntr = 0; cntr < allScores.length; cntr++ ){
total += allScores[cntr];
}// end for
//subtract the sum of the max and min from the total score
firstTotal = total - sumExtremes;
//multiply the new total by the degree of difficulty
totalFinal = firstTotal * degreeOfDifficulty;
//multiply that score by the generic number to multiply the total
finalScore = totalFinal * NUMTOMULTIPLY;
return(finalScore);
}// end calculateScore
//
// runOneDiveClass
// The purpose of this method is to run the one dive class
//
// Input : none
// Return: none
//
public void runOneDiveClass( ){
int cntr;
//input diver information
inputDiverInfo();
//input the degree of difficulty
inputValidDegreeOfDifficulty( );
//input the scores from the judges
inputAllScores( );
//calculate the score
calculateFinalScore( );
//print data
printData( );
}// end runOneDiveClass
}// end OneDiveClass
|
giogonzo/react-intl
|
refs/heads/master
|
/src/components/useIntl.ts
|
import {useContext} from 'react'
import {Context} from './injectIntl'
import {invariantIntlContext} from '../utils'
import {IntlShape} from '../types'
export default function useIntl(): IntlShape {
const intl = useContext(Context)
invariantIntlContext(intl)
return intl
}
|
giogonzo/react-intl
|
refs/heads/master
|
/src/error.ts
|
import {MessageDescriptor} from './types'
export const enum ReactIntlErrorCode {
FORMAT_ERROR = 'FORMAT_ERROR',
UNSUPPORTED_FORMATTER = 'UNSUPPORTED_FORMATTER',
INVALID_CONFIG = 'INVALID_CONFIG',
MISSING_DATA = 'MISSING_DATA',
MISSING_TRANSLATION = 'MISSING_TRANSLATION',
}
export class ReactIntlError extends Error {
public readonly code: ReactIntlErrorCode
public readonly descriptor?: MessageDescriptor
constructor(
code: ReactIntlErrorCode,
message: string,
descriptor?: MessageDescriptor,
exception?: Error
) {
super(
`[React Intl Error ${code}] ${message} ${
exception ? `\n${exception.stack}` : ''
}`
)
this.code = code
this.descriptor = descriptor
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, ReactIntlError)
}
}
}
|
nhanh2/WebMyPham
|
refs/heads/main
|
/js/main.js
|
$(document).ready(function () {
var cart_count = 0 ;
console.log("ready!");
$(".card").click(function () {
window.location.href = "productdetail.html";
});
$("#shopping-card").click(function () {
window.location.href = ' ShoppingCardDetail.html';
});
});
|
smellycats/SX-CarRecgServer
|
refs/heads/master
|
/run.py
|
from car_recg import app
from car_recg.recg_ser import RecgServer
from ini_conf import MyIni
if __name__ == '__main__':
rs = RecgServer()
rs.main()
my_ini = MyIni()
sys_ini = my_ini.get_sys_conf()
app.config['THREADS'] = sys_ini['threads']
app.config['MAXSIZE'] = sys_ini['threads'] * 16
app.run(host='0.0.0.0', port=sys_ini['port'], threaded=True)
del rs
del my_ini
|
smellycats/SX-CarRecgServer
|
refs/heads/master
|
/car_recg/config.py
|
# -*- coding: utf-8 -*-
import Queue
class Config(object):
# 密码 string
SECRET_KEY = 'hellokitty'
# 服务器名称 string
HEADER_SERVER = 'SX-CarRecgServer'
# 加密次数 int
ROUNDS = 123456
# token生存周期,默认1小时 int
EXPIRES = 7200
# 数据库连接 string
SQLALCHEMY_DATABASE_URI = 'mysql://root:root@127.0.0.1/hbc_store'
# 数据库连接绑定 dict
SQLALCHEMY_BINDS = {}
# 用户权限范围 dict
SCOPE_USER = {}
# 白名单启用 bool
WHITE_LIST_OPEN = True
# 白名单列表 set
WHITE_LIST = set()
# 处理线程数 int
THREADS = 4
# 允许最大数队列为线程数16倍 int
MAXSIZE = THREADS * 16
# 图片下载文件夹 string
IMG_PATH = 'img'
# 图片截取文件夹 string
CROP_PATH = 'crop'
# 超时 int
TIMEOUT = 5
# 识别优先队列 object
RECGQUE = Queue.PriorityQueue()
# 退出标记 bool
IS_QUIT = False
# 用户字典 dict
USER = {}
# 上传文件保存路径 string
UPLOAD_PATH = 'upload'
class Develop(Config):
DEBUG = True
class Production(Config):
DEBUG = False
class Testing(Config):
TESTING = True
|
smellycats/SX-CarRecgServer
|
refs/heads/master
|
/car_recg/views.py
|
# -*- coding: utf-8 -*-
import os
import Queue
import random
from functools import wraps
import arrow
from flask import g, request
from flask_restful import reqparse, Resource
from passlib.hash import sha256_crypt
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from car_recg import app, db, api, auth, limiter, logger, access_logger
from models import Users, Scope
import helper
def verify_addr(f):
"""IP地址白名单"""
@wraps(f)
def decorated_function(*args, **kwargs):
if not app.config['WHITE_LIST_OPEN'] or request.remote_addr == '127.0.0.1' or request.remote_addr in app.config['WHITE_LIST']:
pass
else:
return {'status': '403.6',
'message': u'禁止访问:客户端的 IP 地址被拒绝'}, 403
return f(*args, **kwargs)
return decorated_function
@auth.verify_password
def verify_password(username, password):
if username.lower() == 'admin':
user = Users.query.filter_by(username='admin').first()
else:
return False
if user:
return sha256_crypt.verify(password, user.password)
return False
def verify_token(f):
"""token验证装饰器"""
@wraps(f)
def decorated_function(*args, **kwargs):
if not request.headers.get('Access-Token'):
return {'status': '401.6', 'message': 'missing token header'}, 401
token_result = verify_auth_token(request.headers['Access-Token'],
app.config['SECRET_KEY'])
if not token_result:
return {'status': '401.7', 'message': 'invalid token'}, 401
elif token_result == 'expired':
return {'status': '401.8', 'message': 'token expired'}, 401
g.uid = token_result['uid']
g.scope = set(token_result['scope'])
return f(*args, **kwargs)
return decorated_function
def verify_scope(scope):
def scope(f):
"""权限范围验证装饰器"""
@wraps(f)
def decorated_function(*args, **kwargs):
if 'all' in g.scope or scope in g.scope:
return f(*args, **kwargs)
else:
return {}, 405
return decorated_function
return scope
class Index(Resource):
def get(self):
return {
'user_url': '%suser{/user_id}' % (request.url_root),
'scope_url': '%suser/scope' % (request.url_root),
'token_url': '%stoken' % (request.url_root),
'recg_url': '%sv1/recg' % (request.url_root),
'uploadrecg_url': '%sv1/uploadrecg' % (request.url_root),
'state_url': '%sv1/state' % (request.url_root)
}, 200, {'Cache-Control': 'public, max-age=60, s-maxage=60'}
class RecgListApiV1(Resource):
def post(self):
parser = reqparse.RequestParser()
parser.add_argument('imgurl', type=unicode, required=True,
help='A jpg url is require', location='json')
parser.add_argument('coord', type=list, required=True,
help='A coordinates array is require',
location='json')
args = parser.parse_args()
# 回调用的消息队列
que = Queue.Queue()
if app.config['RECGQUE'].qsize() > app.config['MAXSIZE']:
return {'message': 'Server Is Busy'}, 449
imgname = '%32x' % random.getrandbits(128)
imgpath = os.path.join(app.config['IMG_PATH'], '%s.jpg' % imgname)
try:
helper.get_url_img(request.json['imgurl'], imgpath)
except Exception as e:
logger.error('Error url: %s' % request.json['imgurl'])
return {'message': 'URL Error'}, 400
app.config['RECGQUE'].put((10, request.json, que, imgpath))
try:
recginfo = que.get(timeout=15)
os.remove(imgpath)
except Queue.Empty:
return {'message': 'Timeout'}, 408
except Exception as e:
logger.error(e)
else:
return {
'imgurl': request.json['imgurl'],
'coord': request.json['coord'],
'recginfo': recginfo
}, 201
class StateListApiV1(Resource):
def get(self):
return {
'threads': app.config['THREADS'],
'qsize': app.config['RECGQUE'].qsize()
}
class UploadRecgListApiV1(Resource):
def post(self):
# 文件夹路径 string
filepath = os.path.join(app.config['UPLOAD_PATH'],
arrow.now().format('YYYYMMDD'))
if not os.path.exists(filepath):
os.makedirs(filepath)
try:
# 上传文件命名 随机32位16进制字符 string
imgname = '%32x' % random.getrandbits(128)
# 文件绝对路径 string
imgpath = os.path.join(filepath, '%s.jpg' % imgname)
f = request.files['file']
f.save(imgpath)
except Exception as e:
logger.error(e)
return {'message': 'File error'}, 400
# 回调用的消息队列 object
que = Queue.Queue()
# 识别参数字典 dict
r = {'coord': []}
app.config['RECGQUE'].put((9, r, que, imgpath))
try:
recginfo = que.get(timeout=app.config['TIMEOUT'])
except Queue.Empty:
return {'message': 'Timeout'}, 408
except Exception as e:
logger.error(e)
else:
return {'coord': r['coord'], 'recginfo': recginfo}, 201
api.add_resource(Index, '/')
api.add_resource(RecgListApiV1, '/v1/recg')
api.add_resource(StateListApiV1, '/v1/state')
api.add_resource(UploadRecgListApiV1, '/v1/uploadrecg')
|
francois-blanchard/Memo_project_flash
|
refs/heads/master
|
/README.md
|
Memo_project_flash
==================
Jeu de Memo
|
francois-blanchard/Memo_project_flash
|
refs/heads/master
|
/js/script.js
|
function TestAs(s,n){
alert("test: "+s+" : "+n);
}
|
jamesspwalker/week_07_day_2_hw_musical
|
refs/heads/master
|
/src/views/instrument_info_view.js
|
const PubSub = require('../helpers/pub_sub.js');
const InstrumentInfoView = function(container){
this.container = container;
};
InstrumentInfoView.prototype.bindEvents = function(){
PubSub.subscribe('InstrumentFamilies:selected-instrument-ready', (evt) => {
const instrument = evt.detail;
this.render(instrument);
});
};
InstrumentInfoView.prototype.render = function(family){
const infoParagraph = document.createElement('p');
infoParagraph.textContent = `${family.description}`;
this.container.innerHTML = '';
this.container.appendChild(infoParagraph);
};
module.exports = InstrumentInfoView;
|
cindy01/sandbox
|
refs/heads/master
|
/index.php
|
<?php
/*class BankAccount{
public $balance = 10.5;
public function DisplayBalance(){
return 'Balance: '. $this->balance;
}
public function Withdraw($amount){
if($this->balance < $amount){
echo ' Not enough money!';
}else{
$this->balance = $this->balance-$amount;
}
}
}
$alex = new BankAccount;
$alex ->Withdraw(15);
echo $alex ->DisplayBalance();
*/
/*class BankAccount{
//protected $balance = 3500;
protected $_balance = 3500;
public $balance = 2500;
public function DisplayBalance(){
return $this->_balance;
}
}
$cindy = new BankAccount;
echo $cindy->DisplayBalance();
echo $cindy->balance;*/
/*class Circle {
const pi = 3.141;
public function Area($radius){
//return self::pi * ($radius * $radius);
return $this::pi * ($radius * $radius);
}
}
$cindy = new Circle;
echo $cindy->Area(5);
echo $cindy::pi;
*/
/*class Test{
public function __construct($something){
$this->SaySomething($something);
}
public function SaySomething($something){
echo $something;
}
}
$test= new Test('Some text here');
//$test->SaySomething();*/
/*
class BankAccount{
public $balance = 0;
public $type = '';
public function DisplayBalance(){
return 'Balance: '. $this->balance;
}
public function SetType($input){
$this->type = $input;
}
public function Withdraw($amount){
if($this->balance < $amount){
echo ' Not enough money!<br>';
}else{
$this->balance = $this->balance-$amount;
}
}
public function Deposit($amount){
$this->balance = $this->balance + $amount;
}
}
class SavingAccount extends BankAccount{
public $type = '18-25';
}
$billy = new BankAccount;
$billy->SetType('18-25');
echo $billy->type;
*/
/*$ben = new SavingAccount;
$ben->Deposit(3000);
echo $ben->type.'<br>';
echo $ben->DisplayBalance();
$cindy = new BankAccount;
$cindy->Deposit(1000);
$cindy->Withdraw(240);
$cindy->Withdraw(140);
$billy = new BankAccount;
$billy->Deposit(2000);
$billy->Withdraw(240);
$billy->Withdraw(140);
$cindy->Withdraw(140);
$billy->Deposit(4000);
$billy_saving = new SavingAccount;
$billy->Withdraw(14000);
echo $billy_saving->type;
echo 'Cindy '.$cindy->DisplayBalance().'<br>';
echo 'Billy '.$billy->DisplayBalance();*/
/*class DatabaseConnect {
public function __construct($db_host,$db_username,$db_password){
echo 'Attemting connection<br>';
//echo $db_host.'<br>'.$db_username.'<br>'.$db_password;
if(!@$this->Connect($db_host,$db_username,$db_password)){
echo 'Connection failed';
}else if($this->Connect($db_host,$db_username,$db_password)){
echo 'Connected to '. $db_host;
}
}
public function Connect($db_host,$db_username,$db_password){
if (!mysqli_connect($db_host,$db_username,$db_password)){
return false;
}else{
return true;
}
}
}
$connection = new DatabaseConnect('localhost','root','');*/
//require_once('myclass.php');
//require_once('math.php');
//$cindy = new Myclass('Cindy','Park');
//$John = new Myclass('John','Lock');
//var_dump($cindy);
//var_dump($John);
//$John->dosomething();
//$ben = new Math;
//echo $ben->add(5,10,12,13);
//
//echo Math::add(2,3)
include('myclass.php');
//$class1 = new Myclass;
//print_r(MyClass::checkImage('envato.jpg'));
//MyClass::checkImage('envato.jpg');
//MyClass::checkImage('envato.jpg');
//MyClass::checkImage('envato.jpg');
//print_r(MyClass::checkImage('envato.jpg'));
//echo Myclass::getNumUploaded()."<br>";
//
//$instance = new Myclass();
//echo Myclass::getNumUploaded();
//
//echo Myclass::getNumUploaded();
?>
|
jdamatopoulos/photoncloudfunction
|
refs/heads/master
|
/PhotonCloudFunction.ino
|
int red = D5;
int blue = D4;
int yellow = D3;
int changeColour(String colour);
void setup() {
pinMode(red, OUTPUT);
pinMode(blue, OUTPUT);
pinMode(yellow, OUTPUT);
bool success = Particle.function("changeColour", changeColour);
}
void loop() {
}
int changeColour(String colour)
{
if(colour == "red")
{
digitalWrite(red, HIGH);
delay(2000);
digitalWrite(red, LOW);
return 1;
}
if(colour == "blue")
{
digitalWrite(blue, HIGH);
delay(2000);
digitalWrite(blue, LOW);
return 1;
}
if(colour == "yellow")
{
digitalWrite(yellow, HIGH);
delay(2000);
digitalWrite(yellow, LOW);
return 1;
}
}
|
whaid/FPS-Player
|
refs/heads/master
|
/Script/RaycastShoot.cs
|
using UnityEngine;
using System.Collections;
public class RaycastShoot : MonoBehaviour
{
public int weaponDamage = 1;
public int weaponRange = 100;
public float fireRate = 0.1f;
private float nextFire = 0;
private Ray ray;
private RaycastHit hit;
private WaitForSeconds shotDuration = new WaitForSeconds(0.07f);
private AudioSource gunAudio;
void Start()
{
gunAudio = GetComponent<AudioSource>();
}
void Update()
{
if (Input.GetButtonDown("Fire1") && Time.time > nextFire)
{
nextFire = Time.time + fireRate;
StartCoroutine(ShotEffect());
Vector2 screenCenterPoint = new Vector2(Screen.width / 2, Screen.height / 2);
ray = Camera.main.ScreenPointToRay(screenCenterPoint);
if (Physics.Raycast(ray, out hit, weaponRange))
{
Debug.Log("Hit!");
ShootableRobot health = hit.collider.GetComponent<ShootableRobot>();
if (health != null)
{
health.Damage(weaponDamage);
}
}
}
}
private IEnumerator ShotEffect()
{
Debug.Log("shot!");
gunAudio.Play();
yield return shotDuration;
}
}
|
whaid/FPS-Player
|
refs/heads/master
|
/Script/AnimationPlayer.cs
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AnimationPlayer : MonoBehaviour {
private Animator anim;
private AudioSource soundReload;
// Use this for initialization
void Start ()
{
anim = GetComponent<Animator>();
soundReload = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update ()
{
anim.SetBool("isWalking", false);
if (Input.GetButton("Vertical") || Input.GetButton("Horizontal"))
{
anim.SetBool("isWalking", true);
}
if (anim.GetBool("isWalking") && Input.GetButtonDown("Fire3"))
{
anim.SetBool("isWalking", false);
anim.SetBool("isRunning", true);
}
if(anim.GetBool("isRunning") && Input.GetButtonUp("Fire3"))
{
anim.SetBool("isRunning", false);
}
}
}
|
ariksu/pyhfss_parser
|
refs/heads/master
|
/setup.py
|
from setuptools import setup
setup(
name='pyhfss_parser',
version='0.0.0',
packages=['', 'venv.Lib.site-packages.py', 'venv.Lib.site-packages.py._io', 'venv.Lib.site-packages.py._log',
'venv.Lib.site-packages.py._code', 'venv.Lib.site-packages.py._path',
'venv.Lib.site-packages.py._process', 'venv.Lib.site-packages.py._vendored_packages',
'venv.Lib.site-packages.pip', 'venv.Lib.site-packages.pip._vendor',
'venv.Lib.site-packages.pip._vendor.idna', 'venv.Lib.site-packages.pip._vendor.pytoml',
'venv.Lib.site-packages.pip._vendor.certifi', 'venv.Lib.site-packages.pip._vendor.chardet',
'venv.Lib.site-packages.pip._vendor.chardet.cli', 'venv.Lib.site-packages.pip._vendor.distlib',
'venv.Lib.site-packages.pip._vendor.distlib._backport', 'venv.Lib.site-packages.pip._vendor.msgpack',
'venv.Lib.site-packages.pip._vendor.urllib3', 'venv.Lib.site-packages.pip._vendor.urllib3.util',
'venv.Lib.site-packages.pip._vendor.urllib3.contrib',
'venv.Lib.site-packages.pip._vendor.urllib3.contrib._securetransport',
'venv.Lib.site-packages.pip._vendor.urllib3.packages',
'venv.Lib.site-packages.pip._vendor.urllib3.packages.backports',
'venv.Lib.site-packages.pip._vendor.urllib3.packages.ssl_match_hostname',
'venv.Lib.site-packages.pip._vendor.colorama', 'venv.Lib.site-packages.pip._vendor.html5lib',
'venv.Lib.site-packages.pip._vendor.html5lib._trie',
'venv.Lib.site-packages.pip._vendor.html5lib.filters',
'venv.Lib.site-packages.pip._vendor.html5lib.treewalkers',
'venv.Lib.site-packages.pip._vendor.html5lib.treeadapters',
'venv.Lib.site-packages.pip._vendor.html5lib.treebuilders', 'venv.Lib.site-packages.pip._vendor.lockfile',
'venv.Lib.site-packages.pip._vendor.progress', 'venv.Lib.site-packages.pip._vendor.requests',
'venv.Lib.site-packages.pip._vendor.packaging', 'venv.Lib.site-packages.pip._vendor.cachecontrol',
'venv.Lib.site-packages.pip._vendor.cachecontrol.caches',
'venv.Lib.site-packages.pip._vendor.webencodings', 'venv.Lib.site-packages.pip._vendor.pkg_resources',
'venv.Lib.site-packages.pip._internal', 'venv.Lib.site-packages.pip._internal.req',
'venv.Lib.site-packages.pip._internal.vcs', 'venv.Lib.site-packages.pip._internal.utils',
'venv.Lib.site-packages.pip._internal.models', 'venv.Lib.site-packages.pip._internal.commands',
'venv.Lib.site-packages.pip._internal.operations', 'venv.Lib.site-packages.attr',
'venv.Lib.site-packages.pluggy', 'venv.Lib.site-packages._pytest', 'venv.Lib.site-packages._pytest.mark',
'venv.Lib.site-packages._pytest._code', 'venv.Lib.site-packages._pytest.config',
'venv.Lib.site-packages._pytest.assertion', 'venv.Lib.site-packages.colorama',
'venv.Lib.site-packages.atomicwrites', 'venv.Lib.site-packages.parsimonious',
'venv.Lib.site-packages.parsimonious.tests', 'venv.Lib.site-packages.more_itertools',
'venv.Lib.site-packages.more_itertools.tests', 'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip.req',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip.vcs',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip.utils',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip.compat',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip.models',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.distlib',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.distlib._backport',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.colorama',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.html5lib',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.html5lib._trie',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.html5lib.filters',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.html5lib.treewalkers',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.html5lib.treeadapters',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.html5lib.treebuilders',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.lockfile',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.progress',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.requests',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.requests.packages',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.requests.packages.chardet',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.requests.packages.urllib3',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.requests.packages.urllib3.util',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.requests.packages.urllib3.contrib',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.requests.packages.urllib3.packages',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.requests.packages.urllib3.packages.ssl_match_hostname',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.packaging',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.cachecontrol',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.cachecontrol.caches',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.webencodings',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.pkg_resources',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip.commands',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip.operations'],
url='',
license='MIT',
author='Ariksu',
author_email='ariksu@gmail.com',
description='Attempt to write peg-parser for .hfss'
)
|
veralindstrom/clara
|
refs/heads/master
|
/clara.js
|
$('#login').click(function() {
window.location.href='clara2.html';
});
var username = document.getElementById("username");
localStorage.setItem("username", username);
// Retrieve
document.getElementById("valkommen").innerHTML = "Vlkommen " + username;
|
Lasyin/batch-resize
|
refs/heads/master
|
/batch_resize.py
|
import os
import sys
import argparse
from PIL import Image # From Pillow (pip install Pillow)
def resize_photos(dir, new_x, new_y, scale):
if(not os.path.exists(dir)):
# if not in full path format (/usrers/user/....)
# check if path is in local format (folder is in current working directory)
if(not os.path.exists(os.path.join(os.getcwd(), dir))):
print(dir + " does not exist.")
exit()
else:
# path is not a full path, but folder exists in current working directory
# convert path to full path
dir = os.path.join(os.getcwd(), dir)
i = 1 # image counter for print statements
for f in os.listdir(dir):
if(not f.startswith('.') and '.' in f):
# accepted image types. add more types if you need to support them!
accepted_types = ["jpg", "png", "bmp"]
if(f[-3:].lower() in accepted_types):
# checks last 3 letters of file name to check file type (png, jpg, bmp...)
# TODO: need to handle filetypes of more than 3 letters (for example, jpeg)
path = os.path.join(dir, f)
img = Image.open(path)
if(scale > 0):
w, h = img.size
newIm = img.resize((w*scale, h*scale))
else:
newIm = img.resize((new_x, new_y))
newIm.save(path)
print("Image #" + str(i) + " finsihed resizing: " + path)
i=i+1
else:
print(f + " of type: " + f[-3:].lower() + " is not an accepted file type. Skipping.")
print("ALL DONE :) Resized: " + str(i) + " photos")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-d", "-directory", help="(String) Specify the folder path of images to resize")
parser.add_argument("-s", "-size", help="(Integer) New pixel value of both width and height. To specify width and height seperately, use -x and -y.")
parser.add_argument("-x", "-width", help="(Integer) New pixel value of width")
parser.add_argument("-y", "-height", help="(Integer) New pixel value of height")
parser.add_argument("-t", "-scale", help="(Integer) Scales pixel sizes.")
args = parser.parse_args()
if(not args.d or ((not args.s) and (not args.x and not args.y) and (not args.t))):
print("You have error(s)...\n")
if(not args.d):
print("+ DIRECTORY value missing Please provide a path to the folder of images using the argument '-d'\n")
if((not args.s) and (not args.x or not args.y) and (not args.t)):
print("+ SIZE value(s) missing! Please provide a new pixel size. Do this by specifying -s (width and height) OR -x (width) and -y (height) values OR -t (scale) value")
exit()
x = 0
y = 0
scale = 0
if(args.s):
x = int(args.s)
y = int(args.s)
elif(args.x and args.y):
x = int(args.x)
y = int(args.y)
elif(args.t):
scale = int(args.t)
print("Resizing all photos in: " + args.d + " to size: " + str(x)+"px,"+str(y)+"px")
resize_photos(args.d, x, y, scale)
|
Lasyin/batch-resize
|
refs/heads/master
|
/README.md
|
# batch-resize
Python script to resize every image in a folder to a specified size.
# Arguments
<pre>
-h or -help
- List arguments and their meanings
-s or -size
- New pixel value of both width and height.
-x or -width
- New pixel value of width
-y or -height
- New pixel value of height
-t or -scale
- Scales pixel sizes
</pre>
<hr/>
# Example Usage
<pre>
python batch_resize.py -d folder_name -s 128
-> Resizes all images in 'folder_name' to 128x128px
python batch_resize.py -d full/path/to/image_folder -x 128 -y 256
-> Resizes all images in 'image_folder' (listed as a full path, do this if you're not in the current working directory) to 128x256px
python batch_resize.py -d folder_name -t 2
-> Resizes all images in 'folder_name' to twice their original size
</pre>
<hr />
## Accepted Image Types:
<pre>
- Jpg, Png, Bmp (more can easily be added by editing the 'accepted_types' list in the python file)
</pre>
<hr />
# Dependencies
<pre>
- Pillow, a fork of PIL.
- Download from pip:
- pip install Pillow
- Link to their Github:
- https://github.com/python-pillow/Pillow
</pre>
|
Phalanxia/recs
|
refs/heads/master
|
/src/BuiltInPlugins/init.lua
|
return {
CollectionService = require(script.CollectionService),
ComponentChangedEvent = require(script.ComponentChangedEvent),
}
|
Phalanxia/recs
|
refs/heads/master
|
/rotriever.toml
|
name = "RECS"
author = "AmaranthineCodices <git@amaranthinecodices.me>"
license = "MIT"
content_root = "src"
version = "1.0.0"
[dependencies]
TestEZ = { git = "https://github.com/Roblox/testez", rev = "master" }
t = { git = "https://github.com/osyrisrblx/t", rev = "master" }
|
Phalanxia/recs
|
refs/heads/master
|
/README.md
|
# RECS
A work-in-progress successor to [RobloxComponentSystem](https://github.com/tiffany352/RobloxComponentSystem). Primary differences:
* Systems exist as a formalized concept
* Components have very little attached behavior
* Singleton components exist
|
kswgit/ctfs
|
refs/heads/master
|
/0ctf2017/pages.py
|
from pwn import *
import time
context.update(arch='x86', bits=64)
iteration = 0x1000
cache_cycle = 0x10000000
shellcode = asm('''
_start:
mov rdi, 0x200000000
mov rsi, 0x300000000
mov rbp, 0
loop_start:
rdtsc
shl rdx, 32
or rax, rdx
push rax
mov rax, rdi
mov rdx, %d
a:
mov rcx, 0x1000
a2:
prefetcht1 [rax+rcx]
loop a2
dec edx
cmp edx, 0
ja a
b:
rdtsc
shl rdx, 32
or rax, rdx
pop rbx
sub rax, rbx
cmp rax, %d
jb exists
mov byte ptr [rsi], 1
jmp next
exists:
mov byte ptr [rsi], 0
next:
inc rsi
inc rbp
add rdi, 0x2000
cmp rbp, 64
jne loop_start
end:
int3
''' % (iteration, cache_cycle))
HOST, PORT = '0.0.0.0', 31337
HOST, PORT = '202.120.7.198', 13579
r = remote(HOST, PORT)
p = time.time()
r.send(p32(len(shellcode)) + shellcode)
print r.recvall()
print time.time() - p
|
dtkeijser/ChapAppFirebase
|
refs/heads/master
|
/app/src/main/java/com/example/chapapp/registerlogin/LoginActivity.kt
|
package com.example.chapapp.registerlogin
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.example.chapapp.R
import com.google.firebase.auth.FirebaseAuth
import kotlinx.android.synthetic.main.activity_login.*
class LoginActivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
btn_login.setOnClickListener{
val email = tv_email_login.text.toString()
val password = tv_password_login.text.toString()
Log.d( "Login", "Attempt login with email/pw: $email/***")
FirebaseAuth.getInstance().signInWithEmailAndPassword(email, password)
//make new intent to go to new activity
.addOnCompleteListener { finish() }
// .addOnFailureListener { }
}
tv_back_reg.setOnClickListener {
finish()
}
}
}
|
dtkeijser/ChapAppFirebase
|
refs/heads/master
|
/app/src/main/java/com/example/chapapp/messages/ChatLogActivity.kt
|
package com.example.chapapp.messages
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.example.chapapp.NewMessageActivity
import com.example.chapapp.R
import com.example.chapapp.models.ChatMessage
import com.example.chapapp.models.User
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.ChildEventListener
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.squareup.picasso.Picasso
import com.xwray.groupie.GroupAdapter
import com.xwray.groupie.Item
import com.xwray.groupie.ViewHolder
import kotlinx.android.synthetic.main.activity_chat_log.*
import kotlinx.android.synthetic.main.chat_from_row_left.view.*
import kotlinx.android.synthetic.main.chat_to_row_right.view.*
class ChatLogActivity : AppCompatActivity() {
companion object {
val TAG = "ChatLogActivity"
}
val adapter = GroupAdapter<ViewHolder>()
var toUser: User? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_chat_log)
rv_chat_log.adapter = adapter
toUser = intent.getParcelableExtra<User>(NewMessageActivity.USER_KEY)
supportActionBar?.title = toUser?.username
// setupDummyData()
ListenForMessages()
btn_send_chat_log.setOnClickListener {
Log.d(TAG, "Attempt to send message")
performSendMessage()
}
}
private fun ListenForMessages() {
val fromId = FirebaseAuth.getInstance().uid
val toId = toUser?.uid
val ref = FirebaseDatabase.getInstance().getReference("/user-messages/$fromId/$toId")
ref.addChildEventListener(object : ChildEventListener {
override fun onChildAdded(snapshot: DataSnapshot, previousChildName: String?) {
val chatMessage = snapshot.getValue(ChatMessage::class.java)
if (chatMessage != null) {
Log.d(TAG, chatMessage.text)
if (chatMessage.fromId == FirebaseAuth.getInstance().uid) {
val currentUser = LatestMessagesActivity.currentUser ?: return
adapter.add(ChatFromItem(chatMessage.text, currentUser))
} else {
//val toUser = intent.getParcelableExtra<User>(NewMessageActivity.USER_KEY)
adapter.add(ChatToItem(chatMessage.text, toUser!!))
}
}
rv_chat_log.scrollToPosition(adapter.itemCount -1)
}
override fun onChildChanged(snapshot: DataSnapshot, previousChildName: String?) {
}
override fun onChildRemoved(snapshot: DataSnapshot) {
}
override fun onChildMoved(snapshot: DataSnapshot, previousChildName: String?) {
}
override fun onCancelled(error: DatabaseError) {
}
})
}
private fun performSendMessage() {
val text = et_chat_log.text.toString()
// Pushes to messages
// val reference = FirebaseDatabase.getInstance().getReference("/messages").push()
val fromId = FirebaseAuth.getInstance().uid
val user = intent.getParcelableExtra<User>(NewMessageActivity.USER_KEY)
val toId = user!!.uid
val reference = FirebaseDatabase.getInstance().getReference("/user-messages/$fromId/$toId").push()
val toReference = FirebaseDatabase.getInstance().getReference("/user-messages/$toId/$fromId").push()
if (fromId == null) return
val chatMessage =
ChatMessage(reference.key!!, text, fromId, toId, System.currentTimeMillis() / 1000)
reference.setValue(chatMessage)
.addOnSuccessListener {
Log.d(TAG, "Saved our chat message: ${reference.key}")
et_chat_log.text.clear()
rv_chat_log.scrollToPosition(adapter.itemCount -1)
}
toReference.setValue(chatMessage)
val latestMessageRef = FirebaseDatabase.getInstance().getReference("/latest-messages/$fromId/$toId")
latestMessageRef.setValue(chatMessage)
val latestMessageToRef = FirebaseDatabase.getInstance().getReference("/latest-messages/$toId/$fromId")
latestMessageToRef.setValue(chatMessage)
}
// private fun setupDummyData() {
// val adapter = GroupAdapter<ViewHolder>()
// adapter.add(ChatFromItem("from MESSAGES"))
// adapter.add(ChatToItem("TO MESSAGE"))
// adapter.add(ChatFromItem("YEAHHHHHHHHH"))
// adapter.add(ChatToItem("HELLOOOO"))
// adapter.add(ChatFromItem("BOOOOOOOOOOOOOOOOOOOOOOOOOOOOO"))
//
//
// rv_chat_log.adapter = adapter
// }
}
class ChatFromItem(val text: String, val user: User) : Item<ViewHolder>() {
override fun bind(viewHolder: ViewHolder, position: Int) {
viewHolder.itemView.tv_chat_from_row_right.text = text
//load image into chat
val uri = user.profileImageUrL
val targetImageView = viewHolder.itemView.iv_chat_from_row_left
Picasso.get().load(uri).into(targetImageView)
}
override fun getLayout(): Int {
return R.layout.chat_from_row_left
}
}
class ChatToItem(val text: String, val user: User) : Item<ViewHolder>() {
override fun bind(viewHolder: ViewHolder, position: Int) {
viewHolder.itemView.tv_chat_to_row_right.text = text
val uri = user.profileImageUrL
val targetImageView = viewHolder.itemView.iv_chat_to_row_right
Picasso.get().load(uri).into(targetImageView)
}
override fun getLayout(): Int {
return R.layout.chat_to_row_right
}
}
|
dtkeijser/ChapAppFirebase
|
refs/heads/master
|
/settings.gradle
|
include ':app'
rootProject.name = "ChapApp"
|
altopalido/yelp_python
|
refs/heads/master
|
/README.md
|
# yelp_python
Web Application development with python and SQLite. Using www.yelp.com user reviews Database.
|
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 2