blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
3
236
src_encoding
stringclasses
29 values
length_bytes
int64
8
7.94M
score
float64
2.52
5.72
int_score
int64
3
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
8
7.94M
download_success
bool
1 class
dbb88b541895623a81e7f9bd7a8df0b943c9fbb0
JavaScript
rhaws87/Alien_Heroku
/static/js/app3.js
UTF-8
5,950
2.65625
3
[]
no_license
// UFO Data --> standalone file // Perform a GET request to the query URL // var URL = "../static/js/GeoJsonNew.json"; // Perform a GET request to the query URL d3.json("../static/js/GeoJsonNew.json", function(data_MiB) { // Once we get a response, send the data.features object to the createFeatures function console.log(data_MiB); createFeatures(data_MiB); }); var geojsonMarkerOptions_MiB = { radius: 20, fillColor: "#5bff00", color: "#000", weight: 1, opacity: 1, fillOpacity: 0.8 }; // // // Create function to create circular features function createFeatures(UFOPlots) { console.log("-----------"); console.log(UFOPlots.features[20]["geometry"].properties.index); curindx =UFOPlots.features[20]["geometry"].properties.index urlcall ="/api_getUFOText_v1.1 <" + curindx + ">" console.log(getText(urlcall)) console.log(UFOPlots.features[20]["geometry"].properties.Date_Time); console.log(UFOPlots.features[20]["geometry"].properties.Shape); console.log(UFOPlots.features[20]["geometry"].properties.Duration); console.log(UFOPlots.features[20]["geometry"].coordinates[0]); console.log(UFOPlots.features[20]["geometry"].coordinates[1]); let plot = []; let plot2 =[]; var test=[]; // let features = UFOPlots.features; // features.forEach(f => { // coords = f.geometry.coordinates; // plot.push([coords[1]['latitude'], coords[0]['longitude']]) // }); let features = UFOPlots["features"]; console.log("Point 20:",features[20]['geometry'].coordinates[0] ,features[20]['geometry'].coordinates[1] ); for (let i = 0; i < UFOPlots["features"].length; i++){ let test = [features[i]['geometry'].coordinates[0] , features[i]['geometry'].coordinates[1]] let lng =features[i]['geometry'].coordinates[0]//['longitude'] let lat =features[i]['geometry'].coordinates[1]//['latitude'] plot.push([lng,lat]) plot2.push([lat,lng]) //plot.push(test); } console.log("here"); // console.log(plot); var MiB2 = L.geoJson(plot,{ pointToLayer: function (features, plot) { return L.circleMarker(plot, geojsonMarkerOptions_MiB) .bindPopup("<h3>" + "Base: " + features.properties[2] + "</h3><hr><p>" + "Military Branch: " + features.properties[2] + "<br>" + "State: " + features.properties[2] + "</p>"); } }); // createMap(MiB,true); //if you used the heat map with the for loop above, this will work var MiB2 = L.heatLayer(plot, { radius: 10, blur: 1 }); console.log("here after"); // Sending our UFO layer to the createMap function createMap(MiB2,true); } function createMap(MiB2,initialize) { // Define base layer if (initialize=true) { var lightmap = L.tileLayer("https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}", { attribution: "Map data &copy; <a href=\"https://www.openstreetmap.org/\">OpenStreetMap</a> contributors, <a href=\"https://creativecommons.org/licenses/by-sa/2.0/\">CC-BY-SA</a>, Imagery © <a href=\"https://www.mapbox.com/\">Mapbox</a>", maxZoom: 15, id: "mapbox.light", accessToken: API_Key }) //GET NEW DARKMAP LAYER FROM MAPBOX var darkmap = L.tileLayer("https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}", { attribution: "Map data &copy; <a href=\"https://www.openstreetmap.org/\">OpenStreetMap</a> contributors, <a href=\"https://creativecommons.org/licenses/by-sa/2.0/\">CC-BY-SA</a>, Imagery © <a href=\"https://www.mapbox.com/\">Mapbox</a>", maxZoom: 15, id: "mapbox.dark", accessToken: API_Key }) // Define a baseMaps object to hold our base layers var baseMaps = { "Light": lightmap, "Dark": darkmap }; // // Create overlay object to hold our overlay layer var overlayMaps = { MiB: MiB2 }; // Create our map var myMap = L.map("map", { center: [37.6872, -97.3301], zoom: 5, layers: [darkmap, MiB2] }); } //end if initalize //console.log(myMap); // Create a layer control // Pass in our baseMaps and overlayMaps // Add the layer control to the map L.control.layers(baseMaps, overlayMaps, { collapsed: false }).addTo(MiB2); // //Add legend to myMap // legend.addTo(myMap); } let listofsounds=[ 'silence','sound','buzz','crackle','silent','soundless','quiet','quietly','loud','thunderous','boom','noise','sound'] let listofcolors=['red','green','blue','white','yellow','purple','bright','dim','dark','black','silouette','shadow','yellow','gold','glimmering','silver','aluminum','shiny','dull','brilliant','flash','pulsing','metallic','blinking'] let listoffeelings=['scared','scary','terrified','terrifying','frightened','frightening','amazed','amazing','excited','exciting','surprising','surprised','happy','sad','horrified','mortified','confused'] let listofspeeds=["slow","fast","instantly","just gone","disappeared","rapidly",'poof','great speed','really fast','quickly'] let listofmotion=["straight line",'right angle','perpendicular','ninty degree', '90 deg','reappear','break up','disappear','appear','was gone','divided','jumped'] let listofsize=['colossal','large','small','distant','close','huge','tiny','giant'] let listofencounter=['contact','abducted','saw','missing time','taken away'] function highlight(text) { var inputText = document.getElementById("innerText"); var innerHTML = inputText.innerHTML; var index = innerHTML.indexOf(text); if (index >= 0) { innerHTML = innerHTML.substring(0,index) + "<span class='highlight'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length); inputText.innerHTML = innerHTML; } } function Scanlists(listofwords){ listofwords.forEach(f => { highlight(f) }); } var defurl = "/api_getUFOText_v1.1 <1>"; function getText(url) { // d3.text(url).then(function(response) { // console.log(response); // highlight(response) // return response // }); return "This is returned from getText" var block = document.getElementById("innerText") = "" block.innerHTML="This is returned from getText" }
true
a4ad01fc01b54a74ea77f6f8b0e359962c75227d
JavaScript
eric-wang/dojo-todo-app
/views/utils/utils.js
UTF-8
1,023
2.65625
3
[ "BSD-3-Clause", "AFL-2.1" ]
permissive
define(["dojo/dom", "dojo/_base/connect", "dijit/registry"], function(dom, connect, registry){ var _getListItemByIndex = function(widget, index){ var children = widget.domNode.children; var list = []; //get all list items for (var i = 0; i < children.length; i++) { var child = children[i]; if (child.nodeName == "LI" || children.nodeName == "li") { list.push(child); } } if (index >= 0 && index < list.length) { return registry.byNode(list[index]); } return null; }; var _getIndexByListItem = function(widget, item){ var children = widget.domNode.children; var list = []; //get all list items for (var i = 0; i < children.length; i++) { var child = children[i]; if (child.nodeName == "LI" || children.nodeName == "li") { list.push(child); } } for (var i = 0; i < list.length; i++) { if (list[i] == item.domNode) { return i; } } return 0; }; return { getListItemByIndex: _getListItemByIndex, getIndexByListItem: _getIndexByListItem } });
true
b64bd242c6c10106f76c2e0d09d2e9c8db5b75c4
JavaScript
wiss1php2014/wiss1
/app/webroot/js/front/invtrust/description/invTrustCalendarCom.js
UTF-8
746
3
3
[]
no_license
// カレンダー生成処理メソッド function calendarInit() { // 表示対象の年 var year = $('[name=registerYear]').val(); // 休日データ(JSON形式)の格納先を取得 var $dateInput = $('#jsonDate'); // JSON形式のデータからJavaScriptオブジェクトに変換 var dateMap = parseJson($dateInput.val()); // 入力種別の読み込み var inputType = $('#inputType').val(); // 休日データが更新された時の処理 var updateDataFunc = function(json) { $dateInput.val(json); }; // 入力用カレンダー生成 createDatePicker("#holidayCalendar", getInputDatePickerOption(year, dateMap, inputType, updateDataFunc)); } // 画面読み込み完了時の初期化処理 $(calendarInit);
true
bc9e2db19a688d6bf785e0bf0637c13032a910a0
JavaScript
bohandley/vending-machine-js
/coin.js
UTF-8
229
2.75
3
[ "MIT" ]
permissive
var Coin = function(args) { this.name = args.name; this.size = args.name.length; this.weight = args.name.split('').map(function(x) { return x.charCodeAt(); }).reduce(function(a,b) { return a+b; }); this.value = ''; };
true
cdb733a24ba6b848c369bda97d84d8ad009ff878
JavaScript
ccjoness/CG_StudentWork
/Juan/Exercises/Week6/roll_dice/js/main.js
UTF-8
2,306
4.53125
5
[]
no_license
/* I will need: - An event listener to detect a button click - A function that generates an array of random numbers - A function that creates an html element for each random number */ // input validator function validator(num_rolls) { // check to make sure input can be interpreted as a positive integer if (parseInt(num_rolls) > 0) { // everything is OK return(false); } else { alert('Please enter a postive number.'); return(true); } } // random number generator, one roll function gen_roll() { var roll = Math.floor(Math.random() * 6) + 1; return(roll); } // number array generator function gen_array(num_rolls) { // initialize empty array var rolls = [], i; // roll once for each time we've been asked to roll for (i = 0; i < num_rolls; i++) { rolls.push(gen_roll()); } // return array of all rolls return(rolls); } // generate html elements based on an array function gen_elements(rolls) { // initialize variables for use in loop var i, // cache dice area for use in function dice_area = document.getElementById('dice_area'); // clear the roll area to make way for new dice dice_area.innerHTML = ""; // loop through roll array for(i = 0; i < rolls.length; i++) { // create a div containing nothing var newdiv = document.createElement('div'); newdiv.classList.add('die'); // create an image for the corresponding number var newimg = document.createElement('img'); newimg.src = rolls[i] + '.png'; // add image to div newdiv.appendChild(newimg); // add div to .dice_area div dice_area.appendChild(newdiv); } } // event handler for click on "roll" button function roll_it(event) { // initialize variables! var roll_results, // pull required number of rolls from the document, convert to int num_rolls = parseInt(document.getElementById('num_dice').value); // check to make sure input is valid if (validator(num_rolls)) { return; } // pass those rolls to the roller function and save result roll_results = gen_array(num_rolls); // pass roll results to the element generator function gen_elements(roll_results); } // BEHOLD THE GREAT AND POWERFUL EVENT LISTENER window.onload = function () { document.getElementById('roll').onclick = roll_it; };
true
e0fd6915902425e0fe3b9985dbb6866f2aa56461
JavaScript
achuth10/achuth10.github.io
/src/app.js
UTF-8
313
3
3
[]
no_license
console.log("App.js is running"); const incCount = ()=> {count+=1;console.log(count)} let count = 0; let template = ( <div> <p>{count} </p> <button onClick = {incCount}>Click me now!</button> </div> ); let appRoot = document.getElementById("app") ReactDOM.render(template, appRoot);
true
77ddba4ad40fcfe3a6e6e547e2211d01970d9444
JavaScript
chriskelsey/employee-directory
/src/components/EmployeeContainer/index.js
UTF-8
2,359
2.75
3
[]
no_license
import React, { Component } from 'react'; import API from '../../utils/API.js'; import Table from '../Table'; import Searchbox from '../Searchbox'; class EmployeeContainer extends Component{ state = { employees:[], result: "", } componentDidMount(){ this.getEmployees(); } handleSearchInput = event =>{ let value = event.target.value; const name = event.target.name; console.log(event.target); this.setState({ [name]:value }); } getEmployees = ()=>{ API.search() .then(res => { this.setState({employees:res.data.results}) }) .catch(err => console.log(err)) } /* formatDate = params =>{ var d = new Date(params); return `${d.getDate}-${d.getDay}-${d.getFullYear}`; } */ getFormattedDate = (params) =>{ const d = new Date(params); const getMonthOfYear = (d.getMonth() <=9)?'0' + (d.getMonth()+1):d.getMonth()+1; const getDayOfMonth = (d.getDate() <=9)?'0' + d.getDate():d.getDate(); return `${getMonthOfYear}-${getDayOfMonth}-${d.getFullYear()}`; } logData = ()=>{ if(this.state.employees.length <= 0){ console.log('not yet'); } else { console.log(this.state.employees[0]); } } render() { if(this.state.employees.length <= 0){ return <div>Waiting!</div>; } return( <div> <Searchbox handleSearchInput={this.handleSearchInput} /> <Table> {this.state.employees.map(emps => ( <tr key={emps.login.uuid}> <td><img src={emps.picture.thumbnail} alt={`${emps.name.first} ${emps.name.last}`} /></td> <td>{`${emps.name.first} ${emps.name.last}`} </td> <td>{emps.phone}</td> <td>{emps.email}</td> {/* <td>{this.formatDate=emps.dob.date}</td> */} <td>{this.getFormattedDate(emps.dob.date)}</td> </tr> ))} </Table> </div> ) } } export default EmployeeContainer;
true
50c9bc939b8e0e35ac3ae58fe45269a935c8dfa6
JavaScript
JBeard1981/webfund
/Old Assignments/Expressions_Personal/js/script.js
UTF-8
2,347
4.15625
4
[]
no_license
// Jonathan Beard, Expressions assignment part 1 "Personal" date completed Thursday, January 16, 2014 // This section lets pops up an allert to let you know what is going on in this portion of the assignment // alert ("In this portion of the assignment we are to use javascrypt to create \nsomething that relates specifically to us. Therefor i decided to create \na short program to see how your age relates to my own. \nPlease press enter or click the ok button to continue.") // the variable userAge is a prompt to get your age in order to determine weather or not you are older than me. var userAge = prompt("Lets see if you are younger or older than me. \nPlease input your age."); // the variable myAge is a constant that shows how old I am in order to determine weather you are older than me or not. var myAge = 32; // if else statement is being used to calculate then display the proper message depending on weather you are older than me younger than me or the same age. if (userAge<myAge) { // var diff is being used to calculate the difference in my age and the user's age. // In this instance since my age is greater than the user age it is subtracting myAge from the user age var diff = myAge - userAge; // alert here is being used to display that the user age is less than mine and by how much alert("You are younger than me by " + diff + " years."); // console.log is printing the same information as the above alert to the console console.log("You are younger than me by " + diff + " years."); } else if (userAge>myAge) { // var diff is being used to calculate the difference in my age and the user's age. // In this instance since my age is less than the user age it is subtracting the user age from mine var diff = userAge - myAge // alert here is being used to display that the user age is less than mine and by how much alert("You are older than me by " + diff + " years."); // console.log is printing the same information as the above alert to the console console.log("You are older than me by " + diff + " years."); } else { // alert here is being used to display that both I and the user are the same age alert("We are the same age.") // console.log is printing the same information as the above alert to the console console.log("We are the same age.") }
true
4e564c58a286197ff2ba96974dfca38c60b32737
JavaScript
phamphanbang/RGT-webbase
/JS/ProductPageController.js
UTF-8
3,628
2.6875
3
[]
no_license
var item = {}; var id = sessionStorage.getItem("curent-id"); let renderProduct = () => { fetch('http://localhost:3000/product') .then(response => { if(!response.ok){ throw Error('ERROR'); } return response.json(); }) .then(data => { console.log(data); //let id = sessionStorage.getItem("curent-id") item = data.find(i => i.id==id); console.log(item); $(".dptr-title").after('<h3>'+item.product_name+'</h3>') $(".price").append('<i class="fas fa-euro-sign"></i>'+item.product_price); $(".price-detail").append('<p>Product code : '+item.id +'<br>Availability : In Stock </p>') $(".to").text(item.product_name); const subHtml = data.slice(0,3).map(item => { return ` <div class="product-item" > <div class="product-img"> <img src="https://picsum.photos/300/340" alt="" class="figure-img img-fluid "> </div> <div class="product-description"> <p>${item.product_name}</p> <div class="product-price"> $${item.product_price} </div> </div> <div class="item-hover" id="${item.id}"> <a href="./productPage.html" class="btn go-to-detail" role="button" > Detail </a> <button class="btn add-to-cart" > Add to cart </button> </div> </div> ` }).join(""); $("#also-like").append(subHtml); const subHtml2 = data.slice(-3).map(item => { return ` <div class="product-item" > <div class="product-img"> <img src="https://picsum.photos/300/340" alt="" class="figure-img img-fluid "> </div> <div class="product-description"> <p>${item.product_name}</p> <div class="product-price"> $${item.product_price} </div> </div> <div class="item-hover" id="${item.id}"> <a href="./productPage.html" class="btn go-to-detail" role="button" > Detail </a> <button class="btn add-to-cart" > Add to cart </button> </div> </div> ` }).join(""); $("#recently-viewed").append(subHtml2); }) .then(()=>{ $(".add-to-cart").click(function () { var cart = JSON.parse(localStorage.getItem("cart")); if(cart == null) cart = []; let temp = cart.find(i => i.id == id); if(!temp){ var addToCart = { "id" : item.id, "product_name" : item.product_name, "product_price" : item.product_price, "count" : 1 } cart.push(addToCart); } else { cart.map(i => i.id==id?i.count++:i); } console.log(cart); localStorage.setItem("cart",JSON.stringify(cart)); alert("Product added !") }); $(".go-to-detail").click(function () { let id = $(this).closest('.item-hover').attr('id'); sessionStorage.setItem("curent-id",id); }) }) } renderProduct(); $(document).ready(function () { console.log('doc ready'); });
true
7fc6d3843fa594e9512bc0398d085709f2ed6816
JavaScript
jiangshuai/xingguapp
/src/libs/fileUpload.js
UTF-8
3,832
2.6875
3
[ "MIT" ]
permissive
window.fileUpload = (function() { function fileUpload(option) { var uploadUrl; if (option && option.url && option.url != "") { uploadUrl = option.url } else { console.error("upload url undefined"); return } var FileList = []; if (option.FileList && option.FileList.length > 0) { FileList = option.FileList } else { console.log("no FileList"); return } //上传方式 var method; if (option.method && option.method != '') { method = option.method; } else { method = 'PUT'; } //FormData 对象 key var formName = option.formName || 'fileToUpload'; var i = 0; var xhr; function Upload(file) { // console.log(file); //1.准备FormData var fd = new FormData(); var fileName = file.name == undefined ? new Date() * 1 + "." + file.type.split("/")[1].toLowerCase() : file.name fd.append(formName, file, fileName); // 2.创建xhr对象 if (!xhr) { xhr = new XMLHttpRequest(); } // 监听状态,实时响应 // xhr 和 xhr.upload 都有progress事件,xhr.progress是下载进度,xhr.upload.progress是上传进度 //这里监听上传进度事件,文件在上次的过程中,会多次触发该事件,返回一个event事件对象 xhr.upload.onprogress = function(event) { if (event.lengthComputable) { //返回一个 长度可计算的属性,文件特别小时,监听不到,返回false //四舍五入 var percent = Math.round(event.loaded * 100 / event.total); //event.loaded:表示当前已经传输完成的字节数。 //event.total:当前要传输的一个总的大小.通过传输完成的除以总的,就得到一个传输比率 event["percent"] = percent option && option.onprogress && option.onprogress(event); } }; // 传输开始事件 xhr.onloadstart = function(event) { option && option.onloadstart && option.onloadstart(event); }; // xhr.abort();//调用该方法停止ajax上传,停止当前的网络请求 //每个文件上传成功 xhr.onload = function(event) { option && option.onload && option.onload(JSON.parse(event.target.response)); i++ if (i < FileList.length) { setTimeout(function() { Upload(FileList[i]); }, 200); } }; // ajax过程发生错误事件 xhr.onerror = function(event) { option && option.onerror && option.onerror(event); }; // ajax被取消,文件上传被取消,说明调用了 xhr.abort(); 方法,所触发的事件 xhr.onabort = function(event) { option && option.onabort && option.onabort(event); }; // loadend传输结束,不管成功失败都会被触发 xhr.onloadend = function(event) { option && option.onloadend && option.onloadend(event); }; // 发起ajax请求传送数据 xhr.open(method, uploadUrl, true); xhr.send(fd); //发送文件 } Upload(FileList[i]); return { abort: function() { xhr.abort(); } }; } return fileUpload; })() try { module.exports = window.fileUpload } catch (error) { }
true
11f641115d80a3c196992eb44fa395fe4238aebc
JavaScript
withKumar/backend
/main.js
UTF-8
1,606
3.015625
3
[]
no_license
$(document).ready(()=> { console.log('Document Loaded'); //Way 1 -> to binding an Event using Selecctor $('#mid_div').bind("click", function(e) { console.log(e); var value = $('#input1').val(); console.log(value); }) var user; var pass; $('#auth').bind('click', () => { user = $('#user').val(); pass = $('#pass').val(); console.log(`User : ${user} password : ${pass}`); }) /** * USING XMLHttpRequest making GET request * The Flow Below like : * 1. Creating an Interface of XMLHttpRequest * 2. Sending GET request to the server link XHR.Open * 3. Responding in OnLoad method after checking xhr readystate, status * 4. in myData we are storing the JSON edition of the received data */ var xhr = new XMLHttpRequest; xhr.open('GET', 'http://localhost:3000/', true); xhr.onload = function () { // if(xhr.readyState == 4 && xhr.status == 200) { // var mydata = JSON.parse(this.responseText); // var foods = mydata[1].favFood; // foods.forEach(element => { // console.log(element); // }); // } } xhr.send() setTimeout(() => { xhr.abort(); console.log('Waited A Little and closed'); }, 1500); // $.ajax({ // method : 'POST', // url : 'http://localhost:3000', // data : { name : user , password : pass } // }) // .done(function(msg) { // alert('data Transferred' + msg); // }) })
true
bbd3d96f3a9b4f83b42baed01493c4c0f85f747f
JavaScript
Bizoguc/final
/js/manageActivity.js
UTF-8
1,059
2.609375
3
[ "MIT" ]
permissive
$(document).ready(function () { $("#activity").change(function () { var id = $(this).val(); console.log('Activity', id); $.ajax({ url: "getActivity.php", type: 'POST', data: { activityId: id } //activityId ชื่อค่า : id value ค่า }).done(function(result) { console.log(result); activity = (JSON.parse(result)); $("#room").val(""); $("#activity_quan").val(activity.Activity_Quantity); $("#activity_date").val(activity.Activity_Date); $('#startActivity').val(activity.Activity_StartTime); $('#endActivity').val(activity.Activity_StartTime); // console.log(activity.Activity_Hour + activity.Activity_StartTime) var hour = parseInt($('#endActivity').val()) + parseInt(activity.Activity_Hour) $('#endActivity').val(hour); console.log(hour); }).error(function(){ console.log("ERROR"); }); }); });
true
4a029e1162757f1ab7c7221b768414893ae9d41e
JavaScript
joshuahamlet/whatdoyouwannaread
/src/contexts/authContext.js
UTF-8
597
2.546875
3
[]
no_license
import React, {createContext, useEffect, useState} from 'react' export const AuthContext = createContext() const AuthContextProvider = (props) => { const localData = localStorage.getItem('accessToken') const [authState, setAuthState] = useState(localData) useEffect(() => { localStorage.setItem('accessToken', authState) console.log("AUTHSTATE", authState) }, [authState]) return( <AuthContext.Provider value={{authState, setAuthState}}> {props.children} </AuthContext.Provider> ) } export default AuthContextProvider
true
cfc97e873359b999352bf833dc267f423a7c68b7
JavaScript
laurenthiasherly/1950-final
/scripts/menu.js
UTF-8
1,735
2.625
3
[]
no_license
$(document).ready(function(){ $( "#hamburger" ).click(function() { $( "nav" ).toggle(); }); $( window ).resize(function() { if($( window ).width() > 768 || $( document ).width() > 768){ $( "nav" ).css("display", "block"); } else{ $( "nav" ).css("display", "none"); } }); $("#scrolltop").click(function(){ window.scrollTo(0, 0); }); $("#close").click(function(){ $("#popup").css("display", "none"); }); const pattern = new RegExp("^(a|A)[0-9]{8}$"); $("#submit").click(function(e){ let isValid = true; if($.trim($("#firstname").val()) !== "" && $("#firstname").val() !== null && $("#firstname").val() !== "" && $("#lastname").val() !== "" && $("#lastname").val() !== "" && $("#lastname").val() !== null){ if(pattern.test($("#studentno").val()) === true){ console.log("student no ok") $("#popup").css("display", "block"); $("#reminder2").css("display", "none"); $('#firstname').empty(); $('#firstname').attr('value', ''); $('form :input').val(''); $('form :checked').removeAttr('checked'); $('#submit').val('Submit'); $("#whichstudent").attr("checked", "checked"); } else{ $("#reminder2").css("display", "block"); isValid = false; } $("#reminder").css("display", "none"); } else{ if(pattern.test($("#studentno").val()) === true){ console.log("student no ok"); $("#reminder2").css("display", "none"); } else{ $("#reminder2").css("display", "block"); } $("#reminder").css("display", "block"); isValid = false; } console.log(pattern.test($("#studentno").val())); e.preventDefault(); }); });
true
e29b8b9311add9da1edd730f054affd60e68dd00
JavaScript
DannyLeiton/MongoDBx-Class
/3 - Node REST APIs with Express/3-examples/test.js
UTF-8
3,991
3.359375
3
[]
no_license
var app = require('./server'); var assert = require('assert'); var superagent = require('superagent'); describe('server', function() { var server; beforeEach(function() { server = app().listen(3005); }); afterEach(function() { server.close(); }); it('prints out "Hello, world" when user goes to /', function(done) { superagent.get('http://localhost:3005/', function(error, res) { assert.ifError(error); assert.equal(res.status, 200); assert.equal(res.text, "Hello, world!"); done(); }); }); }); /* In addition to node.js' great testing and workflow tools, the asynchronous nature of node.js makes testing very easy. In this course, you will learn to take advantage of node.js to get fast feedback on your development process. In particular, in this lesson, you will learn to write tests that interact with your rest API, in the same way your AngularJS and ionic code will in later chapters. This is the same server.js file that you saw in the express HTTP server lesson. It exports a function that returns an express app. Thanks to node.js' asynchronous IO, you can use this function to start a server in your Mocha test code, and make HTTP requests against your live server. Here's the actual Mocha test code. Now, this may seem counter-intuitive if your background is in a language like C++ or Java, but the nature of event driven IO makes it possible to start an HTTP server, and make HTTP requests to that same server in the same thread. So this superagent module is a popular node.js HTTP client. You can use superagent to make HTTP requests. For instance superagent exposes this nice dot get function. You could use the dot get function to make an HTTP request with the verb get to localhost: 3000 and get the response back in this nice little res parameter. Now in this particular example, what this test does is, before the test starts you create a new server using the call to your server.js file. Once you have the server, you listen on port 3,000, and then your test makes an HTTP request to localhost:3000. The same server that you started here. Once it gets the response back, it asserts that you got back the text hello world. This test also asserts on the HTTP response status. HTTP responses include a numeric status that describe the high level semantics of the response. For instance, if the response succeeded or failed. You may have heard of the HTTP status 404, which means not found. In this case the HTTP status 200, means that the response was processed successfully. Express returns HTTP status 200 by default. Finally, one last detail. See this function done right here? Since JavaScript is asynchronous, Mocha supports asynchronous tests. Mocha inspects the parameters of the function you pass to the it function. If the function takes an argument, Mocha assumes that this test is asynchronous, and calling done is how you tell Mocha that your test is in fact completed. Now in case you have doubts, let's run this test and see that it really works. As you can see all the tests pass. Now let's tweak the server so the tests fail. Let's make it so that the server prints out hola mundo rather than hello world, and rerun the tests. So here's the new slash route. And when you rerun the tests, you get back this nice handy output that says that you expected the server to return hello world, and it gave you back hola mundo. So now thanks to the power of event driven IO, you have the ability to start an HTTP server, as well as test it. Later in this chapter, you will use this paradigm with Gulp to write tests for your rest API. So why is testing your rest API so important? Besides the obvious reason that we want to make sure this course's code examples work, testing is an important investment in your code base's future. A single test eliminates the possibility of one or more bugs creeping into your system. A thorough suite of tests can ensure that your code doesn't break in any obvious ways. */
true
dcc09cb16bd3fabd0b2dbf70f97025ca9d5f95da
JavaScript
rodrigodata/iforgot
/app/controllers/servico/Servico.js
UTF-8
622
2.8125
3
[]
no_license
/* Importação de dependencias */ const Mongoose = require("mongoose"); /* Importação Models */ const Servico = Mongoose.model("Servico"); /* Controller responsável pela criação de novos serviços em que possa ser gerado um */ exports.criar = function(req, res, next) { let body = req.body; if (!body.nome) return res.status(400).json({ errors: { nome: "Valor não pode ser em branco ou nulo." } }); let servico = new Servico(); servico.nome = body.nome; servico .save() .then(() => { return res.status(201).send({ ...req.body }); }) .catch(next); };
true
91ef599e596d99c1779e8098dde5d066ad3068ad
JavaScript
chunkzer/hook-fiesta
/src/components/StateTester.jsx
UTF-8
1,426
2.953125
3
[]
no_license
import React, { useState } from 'react'; const initialTodos = [ { id: 'a', task: 'Learn React', complete: true, }, { id: 'b', task: 'Learn Firebase', complete: true, }, { id: 'c', task: 'Learn GraphQL', complete: false, }, ]; const StateTester = () => { const [inputValue, setInputValue] = useState(''); const [todos, setTodo] = useState(initialTodos); const _addTodo = (todo) => { const complexTodo = { id: Math.random(), task: todo, complete: false, }; setTodo([...todos, complexTodo]); }; const _removeTodo = (id) => { const newTodos = todos.filter(todo => todo.id !== id); return setTodo(newTodos); }; return ( <div style={styles.container}> <ul> {todos.map(todo => ( <li key={todo.id}> <span style={{ marginRight: 3 }}>{todo.task}</span> <span onClick={() => _removeTodo(todo.id)}>❌</span> </li> ))} </ul> <div> <span>New Todo: </span> <input type="text" value={inputValue} onChange={e => setInputValue(e.target.value)} /> <span onClick={() => _addTodo(inputValue)}>✅</span> </div> </div> ); }; const styles = { container: { display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', alignSelf: 'stretch', }, }; export { StateTester };
true
742f156f1aba0d54b9ae6eb1c5bf2ddfc30a5d53
JavaScript
CallMeSahu/build-exercises
/strings.js
UTF-8
4,925
4.28125
4
[]
no_license
/*//Convert to UpperCase var str = "siddhartha"; str = str.toUpperCase(); console.log(str);*/ //Join two strings function joinStrings(str1, str2){ return str1.concat(str2); } //Count number of characters function countCharacters(str){ var count = 0; for(var i=0; i<str.length; i++){ if(str.charAt(i) != " "){ count++; } } return count; } //Convert String to integer function convertNum(str){ return parseInt(str); } //Remove Vowels function removeVowels(str){ var result = ""; for(var i=0; i<str.length; i++){ if(str[i] != "a" && str[i] != "e" && str[i] != "i" && str[i] != "o" && str[i] != "u"){ result += str[i]; } } return result; } //Alphanumeric Check function isAlphaNumeric(str){ str = str.toUpperCase(); for(var i=0; i<str.length; i++){ var code = str.charCodeAt(i); if( !(code>=48 && code<=57)//Numeric check && !(code>=65 && code<=90)//Uppercase check ){ return false; } } return true; } //Print longest and shortest function compareString(str1, str2, str3){ var len1 = str1.length; var len2 = str2.length; var len3 = str3.length; //Print longest if(len1>len2){ if(len1>len3){ //str1 is longest console.log("Longest:", str1); } else{ //str3 is longest console.log("Longest:", str3); } } else{ if(len2>len3){ //str2 is longest console.log("Longest:", str2); } else{ //str 3 is longest console.log("Longest:", str3); } } //Print shortest if(len1<len2){ if(len1<len3){ //str1 is shortest console.log("Shortest:", str1); } else{ //str3 is shortest console.log("Shortest:", str3); } } else{ if(len2<len3){ //str2 is shortest console.log("Shortest:", str2); } else{ //str 3 is shortest console.log("Shortest:", str3); } } } //Number of vowels and consonents function countCharacterType(str){ str = str.toLowerCase(); var vowels=0, cons=0; for(var i=0; i<str.length; i++){ if(str[i] == "a" || str[i] == "e" || str[i] == "i" || str[i] == "o" || str[i] == "u"){ vowels++; } else if(str[i] == " "){ } else{ cons++; } } console.log("Vowels:", vowels, "Consonents:", cons); } //Check string length function checkStringLength(str){ var strlen = 0; str = str + "\0"; for(var i=0; str[i] != "\0"; ++i){ strlen++; console.log(strlen); } if(strlen > 7){ return true; } return false; } //Copy smaller string into bigger string function stringCompare(str1, str2){ var len1 = str1.length; var len2 = str2.length; var result = ""; if(len1>len2){ result = str1.concat(str2); } else{ result = str2.concat(str1); } return result; } //Palindromic string function checkPalindrome(str){ var strev = str.split("").reverse().join(""); if(strev == str){ return true; } return false; } //Mask characters function maskChar(str){ var stres = ""; for(var i=0; i<str.length; i++){ if(i<str.length-4) stres += "#" else stres += str[i]; } return stres; } // First six capital case function firstSix(str){ var result="" var charCount = 0; for(var i=0; i<str.length; i++){ if(str[i] != " "){ charCount++; } if(charCount <= 6){ result += str[i].toUpperCase(); } else{ result += str[i]; } } return result; } //Replace character in string function replaceChar(str, c1, c2){ var stres = ""; for(var i=0; i<str.length; i++){ if(str[i] == c1){ stres += c2; } else{ stres += str[i]; } } return stres; } // Remove spaces function removeSpace(str){ var strnew = ""; for(var i=0; i<str.length; i++){ if(str[i] != " "){ strnew += str[i]; } } return strnew; } //Reverse String wordwise function reverseWordWise(str){ var splitString = str.split(" "); var reverseArray = splitString.reverse(); var joinArray = reverseArray.join(" "); return joinArray; } //Toggle Case characters function toggleCase(str){ var newString = ""; for(var i=0; i<str.length; i++){ if(i%2 == 0){ newString += str[i].toUpperCase(); } else{ newString += str[i]; } } return newString; } //Remove specific word function removeWord(str, word){ var splitString = str.split(" "); var newArray = []; for(var i=0; i<splitString.length; i++){ if(splitString[i] != word){ newArray.push(splitString[i]); } } var newString = newArray.join(" "); return newString; } //Max repeating character function maxChar(str){ var maxKey = str[0]; var maxCount = 0; for(var i=0; i<str.length; i++){ var key = str[i]; var count = 0; for(var j=0; j<str.length; j++){ if(str[j] == key){ count++; } } if(count > maxCount){ maxCount = count; maxKey = key; } } return maxKey; }
true
e9966ef9b397304cdcef7ab2cc205eb0c8b12cb0
JavaScript
TheNewbieCO/primerSketch
/script.js
UTF-8
992
2.890625
3
[]
no_license
//animation const card = document.querySelector('.card'); const container = document.querySelector('.container'); const butt = document.querySelector('.comprabtn'); const bridge = document.querySelector('.bridge img'); const title = document.querySelector('.info h1'); //evento: movimiento de mouse container.addEventListener("mousemove", (e) => { let xaxis = ((window.innerWidth / 2 - e.pageX) / 25); let yaxis = ((window.innerHeight / 2 - e.pageY) / 25); card.style.transform = `rotateY(${xaxis}deg) rotateX(${yaxis}deg)`; }); container.addEventListener("mouseenter", (e) => { card.style.transition = 'all 0.2s ease'; bridge.style.transform = "translateZ(80px)"; title.style.transform = "translateZ(70px)"; }); container.addEventListener("mouseleave", (e) => { card.style.transition = 'all 0.8s ease'; card.style.transform = `rotateY(0deg) rotateX(0deg)`; }); butt.addEventListener('click', (e) => { alert("Creeme, si la hice para ti. att. Gian") });
true
6df518e907db17f0b458a7c547d0056d712e399c
JavaScript
joshthecoder/firmata-http
/firmata-http.js
UTF-8
4,075
2.984375
3
[ "MIT" ]
permissive
var events = require('events'), util = require('util'); var express = require('express'), firmata = require('firmata'); var app = express(); app.configure(function(){ app.set('port', process.env.PORT || 8080); }); // -- Channels -- // Channels provide a way for clients // to consume pin data on a dedicated "data" // connection which provides a streaming response. // Multiple pins can feed data into a channel. function Channel() { events.EventEmitter.call(this); } util.inherits(Channel, events.EventEmitter); Channel.prototype.addFeed = function(pinNumber) { var self = this; console.log('Feed added for pin ' + pinNumber); return function(newValue) { self.emit('data', pinNumber, newValue); } } var channels = { }; // --- Endpoints --- // Query the version of the board. // // GET /version/board // -> {"major": 1, "minor": 0} app.get('/version/board', function(req, res) { board.reportVersion(function() { res.json(200, { major: board.version.major, minor: board.version.minor }); }); }); // Query firmware version of the board. // // GET /version/firmware // -> {"major": 1, "minor": 2, "name": "awesome"} app.get('/version/firmware', function(req, res) { board.queryFirmware(function() { res.json(200, { major: board.firmware.version.major, minor: board.firmware.version.minor, name: board.firmware.name }); }); }); // Write digital or analog data to a pin. // // POST /pins/:num/write?type=digital&value=1 app.post('/pins/:num/write', function(req, res) { var pinNumber = req.params.num, value = parseInt(req.query.value), dataType = req.query.type; if (Number.isNaN(value)) { res.send(400, 'Invalid value. Must be a number.'); return; } if (dataType == 'digital') { board.digitalWrite(pinNumber, value); } else if (dataType == 'analog') { board.analogWrite(pinNumber, value); } else { res.send(400, 'Invalid type. Must be digital or analog.'); return; } res.send(200); }); // Read digital or analog pin data. // Pin data is delivered to a channel as it arrives. // // GET /pins/2/read?type=digital&channel=1 app.get('/pins/:num/read', function(req, res) { var pinNumber = req.params.num, dataType = req.query.type, channelID = req.query.channel; if (typeof(channelID) == 'undefined') { res.send(400, 'Must provide a channel ID.'); return; } var channel = channels[channelID]; if (typeof(channel) == 'undefined') { channel = channels[channelID] = new Channel; } var dataCallback = channel.addFeed(pinNumber); if (dataType == 'digital') { board.digitalRead(pinNumber, dataCallback); } else if (dataType == 'analog') { board.analogRead(pinNumber, dataCallback); } else { res.send(400, 'Invalid type. Must be digital or analog.'); return; } res.send(200); }); // Connect to channel and start receiving data. // This endpoint provides a streaming response // of JSON objects delimited by a newline character. // // GET /channels/1 // -> {pin: 2, value: 0}\n // -> {pin: 4, value: 128}\n // ... app.get('/channels/:id', function(req, res) { var id = req.params.id; if (typeof(id) == 'undefined') { res.send(400, 'Must provide a channel ID.'); return; } var channel = channels[id]; if (typeof(channel) == 'undefined') { // Create the channel if it does not exist yet. // The client might want to connect first before // subscribing to a pin's data. channel = channels[id] = new Channel; } function onData(pinNumber, value) { res.write(JSON.stringify({pin: pinNumber, value: value}) + '\n'); } res.on('close', function() { console.log('Channel client disconnected.'); channel.removeListener('data', onData); }); channel.on('data', onData); }); // Usage: node firmata-http.js <serialPortPath> var serialPortPath = process.argv[2]; var board = new firmata.Board(serialPortPath, function() { app.listen(app.get('port')); console.log('Connected to board. HTTP server running.'); });
true
a10226ef88169c0844a0dd82dab3b8cb50013cb8
JavaScript
Aliszl/Sprint-Challenge-Advanced-React
/womens-world-cup/src/components/Worldcupdata.jsx
UTF-8
1,942
2.859375
3
[]
no_license
import React, { useState, useEffect } from "react"; import axios from "axios"; import styled from "styled-components"; // import Card from "./Card"; const DivStyled = styled.div` border: 1px solid red; margin: 20px 20px; padding: 20px 20px; .list { margin: 10px; } `; export default class WorldcupData extends React.Component { state = { players: [] }; componentDidMount() { axios.get("http://localhost:5000/api/players").then(response => { console.log(response); console.log(response.data); this.setState({ players: response.data }); }); } render() { return ( <DivStyled className="players"> {this.state.players.map(player => ( <ul> <li className="list" key={player.id}> {player.name} <br /> Country: {player.country} <br /> Google Popularity by no. searches: {player.searches} <br /> </li> </ul> ))} </DivStyled> ); } } // Functional component with state and hooks // export default function WorldcupData() { // const [players, fetchPlayers] = useState([]); // useEffect(() => { // console.log("WorldcupData component mounted"); // axios // .get("http://localhost:5000/api/players") // .then(response => { // console.log(response); // console.log(response.data); // fetchPlayers(response.data); // }) // .catch(error => { // console.log("the data was not returned", error); // }); // }, []); // return ( // <div> // {players.map(player => { // return ( // <div> // <li key={player.id}> // Player:{player.name} Country: // {player.country} Searches:{player.searches} ID: {player.id} // </li> // </div> // ); // })} // </div> // ); // }
true
cd5333f37ededafd18714811f27f3c8553ed293f
JavaScript
sacken0923/team_c_57
/app/assets/javascripts/select_2.js
UTF-8
271
2.53125
3
[]
no_license
$(function(){ $("#delivery").on("change",function(){ $("#shipping_method").removeClass("method"); var deliveryselect = document.getElementById("item_delivery").value; if (deliveryselect === '') $("#shipping_method").addClass("method"); }); });
true
f2cf683dcb7cee94bf8fc227e8fcb9349c969788
JavaScript
Yatoom/yatoom.github.io
/yawl-viewer/js/drawer.js
UTF-8
1,192
2.5625
3
[]
no_license
var drawer = new function drawer() { this.draw = function(net, canvas) { net = $(net) var bounds = _getBounds(net) console.log(bounds) } this.createCanvas = function(net, target) { var $target = $(target) var bounds = _getBounds(net) var canvas = sprintf("<canvas width='%(w)dpx' height='%(h)dpx'></canvas>", bounds) return $target.html(canvas) } this.getVertices = function (net) { net = $(net) var vertices = net.find("vertex") console.log(vertices) } this.getTasks = function(processControlElements) { return $(processControlElements).find("task") } this.getConditions = function(processControlElements) { return $(processControlElements).find("condition") } function _drawSquare(x, y, size, canvas) { var context = canvas.getContext("2d") context.beginPath(); context.rect(x, y, size, size); context.stroke(); } function _drawCircle(x, y, size, canvas) { var context = canvas.getContext("2d") context.beginPath() context.arc(x, y, size, 0, 2 * Math.PI) context.stroke() } function _getBounds(net) { var bounds = net.child("bounds").attributes return { w: +bounds.w.value, h: +bounds.h.value, } } }
true
f4045db8acef1571f37f5afff532599513b04331
JavaScript
MrTrick/connect4
/lib/game.js
UTF-8
2,496
3.53125
4
[ "MIT" ]
permissive
//Represents and encapsulates the game itself - the players and the board state 'use strict'; const assert = require('assert').strict; const EventEmitter = require('events'); const State = require('./state'); const Player = require('./player'); /** * Game Controller * * Contains: * - The game state * - The players (and current player) * - The highlighted columns * - The current player's thoughts * * Implements Action: * - Play (next move) * * Generates/Relays events on: * - Change of state * - Change of highlighted columns * - Change of player's thoughts */ class Game extends EventEmitter { /** * @param {State} start_state * @param {Player} player1 * @param {Player} player2 */ constructor(start_state, player1, player2) { super(); assert(start_state instanceof State); assert(player1 instanceof Player); assert(player2 instanceof Player); this.state = start_state; this.player1 = player1; this.player2 = player2; this.thoughts = []; this.highlight = []; //Chain Player events to Game events const onThinking = (msg, player) => { if (player !== this.nextPlayer) return; this.thoughts.push(msg); this.emit('thinking', msg, player); }; const onHighlight = (highlight, player) => { if (player !== this.nextPlayer) return; this.highlight = highlight; this.emit('highlight', highlight, player); }; player1.on('thinking', msg=>onThinking(msg, player1)); player2.on('thinking', msg=>onThinking(msg, player2)); player1.on('highlight', highlight=>onHighlight(highlight, player1)); player2.on('highlight', highlight=>onHighlight(highlight, player2)); } /** * Accessor for the next player to make a move. * Based off the * @return {Player} */ get nextPlayer() { const piece = this.state.nextPiece(); return (piece === 1) ? this.player1 : this.player2; } /** * Play the next step of the game. * Delegate to the current player to choose where to place the piece. * Delegate to state to generate the next state. * @returns {Promise()} */ play() { assert(!this.state.gameover, 'Game continuing'); //Fetch the play from the player whose turn is next const play = this.nextPlayer.getPlay(this.state); //When a play is chosen, update the board. return play.then(pos => { const next = this.state.play(pos); this.highlight = []; this.thoughts = []; this.state = next; this.emit('state', this.state); return next; }); } } module.exports = Game;
true
c1ce1aaeafa8f489046dce8cd6605712dc5ac082
JavaScript
msd495/React-Topic-wise
/src/useCustomHook.jsx
UTF-8
219
2.53125
3
[]
no_license
import React from 'react'; const useCustomHook = (count) => { React.useEffect(()=> { alert('I am clicked'); document.title = `you clicked me ${count} times`; }) } export default useCustomHook;
true
dab83ae2690569d8710f1a27a3bda522c6b3b253
JavaScript
AbhishekNairOfficial/northstar
/src/components/goalListingComponents/goalTemplate.js
UTF-8
3,128
2.609375
3
[]
no_license
import React, { Component } from 'react'; import { Text, View, TouchableOpacity, Image } from 'react-native'; import ProgressCircle from 'react-native-progress-circle'; import moment from 'moment'; import FilledIcon from "../../../images/filled.png"; import HighImpactIcon from "../../../images/highImpact.png"; class GoalListing extends Component { setColor(item) { if (item.percentage ==100){ return 'green'; } else if (item.percentage < 100 && moment(item.dueOn).isBefore(moment())){ return 'red'; } else if (item.percentage < 100){ return 'purple'; } } setContent(item) { if (item.percentage === 100){ return (<Text style={{ color: this.setColor(item)}}> Completed on {moment.utc(item.dueOn).format('MMM DD')}</Text>); } else if (item.percentage < 100) { return (<Text style={{ color: this.setColor(item) }}> Expired On {moment.utc(item.dueOn).format('MMM DD')}</Text>); } else { return (<Text style={{ color: this.setColor(item) }}> Complete By {moment.utc(item.dueOn).format('MMM DD')}</Text>); } } renderHighImpactIcon(data) { if (data.isHighImpact) { return (<Image style={{ width: 25, height: 25 }} source= {FilledIcon} />); }else { return (<Image style={{ width: 25, height : 25 }} source= {HighImpactIcon} />); } } render(){ const { navigation}=this.props; if(this.props.data.length < 1) return(<View></View>); return ( <TouchableOpacity style={styles.goalTemplateStyle} onPress={() => navigation.navigate('GoalLandingDetail', { itemId: this.props.data._id })}> <View style = {{flexDirection:'row' , alignItems:'center'}}> {this.renderHighImpactIcon(this.props.data)} <View style={styles.contaierStyle}> <Text style={styles.taskName}>{this.props.data.name}</Text> <View style={styles.statusStyle}> <Text style = {{color:this.setColor(this.props.data)}}>{this.props.data.percentage} % |</Text> {this.setContent(this.props.data)} </View> </View> </View> <View> <ProgressCircle percent={this.props.data.percentage} radius={20} borderWidth={8} color={this.setColor(this.props.data)} shadowColor='#fafafa' bgColor="#fff"></ProgressCircle> </View> </TouchableOpacity> ); } } const styles = { goalTemplateStyle: { flexDirection: 'row', justifyContent: 'space-between', margin: 20, }, contaierStyle: { flexDirection: 'column', marginLeft: 5 }, statusStyle: { flexDirection: 'row', justifyContent: 'flex-start' }, taskName: { textTransform: 'capitalize', letterSpacing: -0.5, // fontWeight: 600, width: '100%', } }; export default GoalListing;
true
7f0c1eb8cfe29babd367f6dd85c5f1021e83d8b8
JavaScript
jshbrntt/sierpinski
/src/core/services/index.js
UTF-8
362
2.640625
3
[]
no_license
export default class Services { static provide (name, service) { if (!this._services) { this._services = new Map() } this._services.set(name, service) } static locate (name) { if (this._services.has(name)) { return this._services.get(name) } else { throw new ReferenceError(`Service '${name}' not found.`) } } }
true
8491be2e55ae61881acdd1c8e44438b037bffbd2
JavaScript
meeksfred/random-practice-problems
/min-max.js
UTF-8
640
4.125
4
[]
no_license
'use strict'; // Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers. let exampleArray = [4, 2, 34, 22, 12]; function minMax(arr) { let sorted = arr.sort(function(a, b) { return a - b; }); let min = sorted.slice(0, 4).reduce(function(x, y) { return Number(x) + Number(y); }, 0); let max = sorted.slice(1, 5).reduce(function(x, y) { return Number(x) + Number(y); }, 0); console.log(min, max); } minMax(exampleArray);
true
50f1b4fefe552866b69a796236cf73d34b0b090e
JavaScript
togetherworks/iKBS
/WebRoot/scripts/menuExpandable.js
UTF-8
2,503
2.796875
3
[]
no_license
/* * menuExpandable2.js - implements an expandable menu based on a HTML list * Author: Dave Lindquist ([email protected]) */ if (!document.getElementById) document.getElementById = function() { return null; } function isExpanded(menuId) { var cookieName = window.location.pathname + "="; var returnvalue = ""; if (document.cookie.length > 0) { offset = document.cookie.indexOf(cookieName) // if cookie exists if (offset != -1) { offset += cookieName.length // set index of beginning of value end = document.cookie.indexOf(";", offset); // set index of end of cookie value if (end == -1) end = document.cookie.length; returnvalue = unescape(document.cookie.substring(offset, end)) } } if (returnvalue!="") { if (returnvalue.indexOf(menuId) != -1) return true; } return false; } function initializeMenu(menuId, actuatorId) { var menu = document.getElementById(menuId); var actuator = document.getElementById(actuatorId); if (menu == null || actuator == null) return; if (window.opera) return; // I'm too tired actuator.parentNode.style.backgroundImage = "url(../images/plus.gif)"; actuator.onclick = function() { var display = menu.style.display; if (display == "block") { this.parentNode.style.backgroundImage = "url(../images/plus.gif)"; menu.style.display = "none"; } else { this.parentNode.style.backgroundImage = "url(../images/minus.gif)"; menu.style.display = "block"; } return false; } // expand if necessary if (isExpanded(menuId)) { menu.style.display = "block"; menu.parentNode.style.backgroundImage = "url(../images/minus.gif)"; } // remove if there are no child nodes if (actuator.parentNode.children(1).children.length == 0) { actuator.parentNode.removeNode(true); } } function saveCookie() { var cookieName = window.location.pathname + "="; var saveList = ""; for (i=0; i<document.getElementsByTagName("UL").length; i++){ currUL = document.getElementsByTagName("UL")[i]; if ((currUL.className=="menu") && (currUL.style.display=="block")) { saveList += currUL.id; } } document.cookie = cookieName+saveList; } window.onunload = saveCookie;
true
3dfdc38307462124da7c09c94c75e8bdc11fb917
JavaScript
dheerajaraj/foodDeliveryApp
/appeng/src/AppPart1.js
UTF-8
2,842
2.515625
3
[]
no_license
import React, { useState, useEffect } from "react"; import ReactDOM from "react-dom"; import axios from "axios"; import "./index.css"; import loginService from "./service/loginService"; import LoginForm from "./components/LoginForm"; import BlogForm from "./components/BlogForm"; import TogglableButton from "./components/TogglableButton"; import communicationService from "./components/CommunicationNotes"; const AppPart1 = () => { const [errorMessage, setErrorMessage] = useState(""); const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const [user, setUser] = useState(null); const [loginVisible, setLoginVisible] = useState(false); useEffect(() => { const loggedUserJson = window.localStorage.getItem("loggedBlogAppUser"); if (loggedUserJson) { const user = JSON.parse(loggedUserJson); setUser(user); communicationService.setToken(user.token); } }, []); const handleLogout = event => { window.localStorage.removeItem("loggedBlogAppUser"); setUser(null); }; const handleLoginUsername = ({ target }) => setUsername(target.value); const handleLoginPassword = ({ target }) => setPassword(target.value); const handleLogin = async event => { event.preventDefault(); try { const user = await loginService.login({ username, password }); window.localStorage.setItem("loggedBlogAppUser", JSON.stringify(user)); communicationService.setToken(user.token); setUser(user); setUsername(""); setPassword(""); } catch (exception) { setErrorMessage("Wrong credentials"); setTimeout(() => { setErrorMessage(null); }, 5000); } }; const ErrorMessage = () => { if (errorMessage === "") return <div></div>; return ( <div className="error"> <p>{errorMessage}</p> </div> ); }; const blogForm = () => { return ( <div> <p> {user.username} has logged in{" "} <input type="button" value="Logout" onClick={handleLogout} /> </p> <br /> <BlogForm errorMessage={ErrorMessage} setErrorMessage={setErrorMessage} username={username} /> <br /> </div> ); }; const mainForm = () => { if (user === null) { return ( <div> <LoginForm handleLoginUsername={handleLoginUsername} handleLoginPassword={handleLoginPassword} handleLogin={handleLogin} username={username} password={password} /> </div> ); } else { return <div>{blogForm()}</div>; } }; return ( <div> <h1>Phonebook</h1> <ErrorMessage /> {mainForm()} </div> ); }; export default AppPart1;
true
b6d681b8add254f9b1b49f72694386a4a0770d1e
JavaScript
rado08271/isitkeyword
/src/App.js
UTF-8
1,557
2.515625
3
[]
no_license
import React, { Component } from 'react'; import './App.css'; import SearchBar from './components/SearchBar'; import './components/faLib'; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import './components/faLib' class App extends Component { constructor(props){ super(props); this.state = { clicked: false }; this.hoverHandler = this.hoverHandler.bind(this); } //TODO decide whether onClick or on hover...if on click toggle it through javaScript hoverHandler = (event) => { this.setState({clicked: !this.state.clicked}); console.log(this.state); }; render() { return ( <div className={"container"}> <div className={"in-center"}> <h1>Is it Keyword<FontAwesomeIcon icon={['fas', 'question']} className={"question-icon"} onClick={this.hoverHandler}/></h1> <SearchBar/> {/*{console.log(value)}*/} </div> {this.state.clicked ? toolTip : ""} </div> ) } } const toolTip = <div className={"tooltip"}> <p>Write a keyword you think of. If it is a keyword, specific language will be shown. In case of case sensitive language, it will be shown in orange otherwise in green... Bear in mind it's just development build! Still in progress...feel free to cantact me <a className={"contact"} href={"meilto:[email protected]"}>[email protected]</a></p> </div> export default App;
true
8ce4f36c59ee2a6e624a6762307908976cb3a086
JavaScript
shamlisampla/webproject
/FinalProjectWebDev/js/slideShow.js
UTF-8
1,894
2.8125
3
[]
no_license
document.getElementById("app").innerHTML = ` <div class='wrapper'> <div class='view'> <div class='left'><</div> <div class='right'>></div> </div> <div class='buttons'> </div> </div> `; const images = [ "https://images.all-free-download.com/images/graphiclarge/canoe_water_nature_221611.jpg", "https://images.all-free-download.com/images/graphiclarge/tree_meadow_nature_220408.jpg", "https://images.all-free-download.com/images/graphicthumb/stones_pebble_nature_215149.jpg", "https://images.all-free-download.com/images/graphicthumb/beautiful_natural_scenery_02_hd_picture_166231.jpg" ]; const qs = document.querySelector.bind(document); const Wrapper = qs(".wrapper"); const Views = qs(".view"); const Buttons = qs(".buttons"); const Left = qs(".left"); const Right = qs(".right"); let active = 0; const Circles = []; function focus() { document.querySelectorAll(".circle").forEach((ele) => { ele.classList.remove("highlight"); }); Circles[active].classList.add("highlight"); Views.style.backgroundImage = `url(${Circles[active].dataset.link})`; } Left.onclick = function () { active--; if (active < 0) active += Circles.length; focus(); }; Right.onclick = function () { active++; active %= Circles.length; focus(); }; images.forEach((link, i) => { let circle = document.createElement("div"); circle.dataset.link = link; Circles.push(circle); circle.classList.add("circle"); if (!i) circle.classList.add("highlight"); circle.onclick = function () { Views.style.backgroundImage = `url(${link})`; document.querySelectorAll(".circle").forEach((ele) => { ele.classList.remove("highlight"); }); this.classList.add("highlight"); console.log(Views); }; Buttons.appendChild(circle); }); Views.style.backgroundImage = `url(${images[0]})`;
true
281820cebce0054e6ec5976f9f52dfb8d658bb2e
JavaScript
eliasjames/load_test
/test_spec.js
UTF-8
755
2.765625
3
[]
no_license
var loadTester = require('./loadTester'); var config = require('./config'); // solves error caused by self-signed https cert process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; var user_name_num = 0; function oneUserCycle(user_name_num) { var user_name_num_padded = padWithZeroes(user_name_num, 4); //console.log(user_name_num_padded); var lt = loadTester(config.password, user_name_num_padded, 23, 2); lt.runCycle(); } function padWithZeroes (some_num, len) { var padded = String(some_num); while (padded.length < len) { padded = "0" + padded; } return padded; } function tenUsers (which_ten) { for (var i=1; i<10; i++){ if (which_ten === 0 && i === 0) i++; oneUserCycle(which_ten + i); } } tenUsers(config.which_ten);
true
4b3f153190d529d719dea9f3c22070d3e8f2df44
JavaScript
alastairkitchen/studio-ghibli-react-app
/src/js/components/full-info-panel/full-info-panel.js
UTF-8
1,177
2.609375
3
[]
no_license
import React from "react"; // Owned imports import FilmPanelContent from "./film-panel-content"; import PersonPanelContent from "./person-panel-content"; class FullInfoPanel extends React.Component { constructor(props) { super(props); this.characterNumberText = this.characterNumberText.bind(this); this.noCharactersMessage = this.noCharactersMessage.bind(this); } characterNumberText(people) { if (people && Array.isArray(people)) { return `(${people.length})`; } } noCharactersMessage(people) { if (people && Array.isArray(people)) { if (people.length === 0) { return <p>No character data had been added to this film yet</p>; } } } generatePanelContent(panelType) { if(panelType === "film") { return <FilmPanelContent {...this.props} composeBlurbCards={this.props.composeBlurbCards}/> } if (panelType === "person") { return <PersonPanelContent {...this.props} composeBlurbCards={this.props.composeBlurbCards}/> } } render() { return ( <div> {this.generatePanelContent(this.props.panelType)} </div> ); } } export default FullInfoPanel;
true
0cf55113822f248668377541f36df3e4bafc68c8
JavaScript
adriansilisque/js-largest-prime-factor
/scripts/LPFCalculator.js
UTF-8
780
3.234375
3
[]
no_license
function largestPrimeFactor(n) { if (n % 2 == 0){ var lastFactor = 2; n=n/2; while (n % 2 == 0){ n=n/2; } }else{ lastFactor =1;} factor = 3; maxFactor = Math.sqrt(n); while ((n > 1) && (factor<=maxFactor)){ if (n % factor == 0){ n=n/factor lastFactor=factor while (n % factor == 0){ n = n / factor} maxFactor= Math.sqrt(n) } factor += 2; } if (n == 1){ return lastFactor; }else{ return n; } } function ValidateResult(origText, result){ var index, total = 1; for(index = 0; index < result.length; index++){ total = total * result[index];} return (origText === total.toString()) ? result : "Error: Factoring did not validate"; };
true
d154302100ca0dcd60658d844b4ac9abf84e6404
JavaScript
sebascrosta/curso
/React/exchange/app/index_exchange.js
UTF-8
1,951
2.84375
3
[]
no_license
import React, {Component, PropTypes} from 'react'; import ReactDOM from 'react-dom'; const node = document.getElementById('content'); class SimpleApp extends Component { constructor(props) { super(props) this.state = { rates: [], error: '', isLoading: true } } componentDidMount() { fetch("http://api.fixer.io/latest?base=USD").then((response) => { return response.json() }).then((values) => { // console.log(values) this.setState({rates: values.rates, isLoading: false, error: ''}) console.log(this.state.rates) }).catch((error) => { this.setState({rates: {}, isLoading: false, error: 'ERROR'}) }) // var xmlhttp = new XMLHttpRequest(); // // xmlhttp.onreadystatechange = () => { // if (xmlhttp.readyState == XMLHttpRequest.DONE ) { // if (xmlhttp.status === 200) { // console.log(values) // } else if (xmlhttp.status === 400) { // console.error('ERROR :('); // } else { // console.error('Unknown error'); // } // } // }; // // xmlhttp.open("GET", "http://api.fixer.io/latest?base=USD", true); // xmlhttp.send(); } render() { let ratesToShow = [] let rate for (rate in this.state.rates) { ratesToShow.push( <div key={rate}> {rate} -- {this.state.rates[rate]} </div> ) } if (this.state.isLoading){ return <div>Está cargando...</div> }else if (this.state.error !== ''){ return <div>{this.state.error}</div> }else{ return <div><ul>{ratesToShow}</ul></div> } } } ReactDOM.render( <SimpleApp/>, node);
true
ff08254441bff25dd41a691ba37c7545c43e6723
JavaScript
akira86071/Y
/my-app/src/App.js
UTF-8
1,128
2.59375
3
[]
no_license
import React from 'react'; import logo from './logo.svg'; import './App.css'; import { render } from 'react-dom'; function App() { let a = Promise.resolve(getdata()); return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <p> Edit <code>src/App.js</code> and save to reload. </p> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > Learn React HIHI test {() => getdata()} </a> </header> </div> ); } async function getdata(){ var newheader = new Headers(); let callback = []; const ans = await fetch("http://localhost:7001/hihi",{ method: 'GET', headers: newheader, mode: 'cors', cache: 'default' }).then(function(response){ return response.json(); }).then(function(result){ console.log(result); return result.content.toString(); }).then(function(test){ console.log(test); }); return ans; } export default App;
true
e8f3d5b0f263b738bc7bc061c31a6f82c383e393
JavaScript
yifoo/Node
/Demo-core/demo00_http.js
UTF-8
1,538
2.890625
3
[]
no_license
const http=require('http'); const fs=require('fs'); let server=http.createServer(function(req,res){ res.writeHead(200, {'Content-Type':'text/html;charset=UTF-8'}); if(req.url=='/index'){ res.write('<h1>这是首页</h1>') }else if(req.url=='/user/login'){ res.write('<h1>这是登录页</h1>') }else if(req.url=='/user/register'){ res.write('<h1>这是注册页</h1>') } res.end('欢迎来到NodeJs'); }) server.listen(3000); console.log('开始监听3000端口') //监听3000端口 /* fs.stat('data.txt', (err, stats) => { if (err) { console.log(err); throw err; } console.log(stats); }); fs.realpath('./data.txt',function(err,path){ //如果转换失败,则err中有值,否则为null if(err){ console.error(err); }else{ console.log(path); } }) fs.readFile('data.txt', (err, data) => { if (err) throw err; console.log(data); }); fs.writeFile('data.txt', 'Hello Node.js', (err) => { if (err) throw err; console.log('The file has been saved!'); }); */ // var rs=fs.createReadStream('./data.txt'); // var temp=""; // rs.on('data',function(chunk){ //每读取64kb执行data方法 // console.log(chunk); // //看字符串 // // console.log(chunk.toString()); // temp+=chunk;//拼接所有的数据 // }) // //读取流完毕后执行end // rs.on('end',function(){ // console.log(temp); // }) // var rs=fs.createReadStream('./data.txt'); // var ws=fs.createWriteStream('./data_bak.txt'); // rs.on('data',function(chunk){ // ws.write(chunk); // }) // rs.pipe(ws)
true
705df7da23611aed4b265727b73e2f6b3b500289
JavaScript
HarolG/komatsu
/js/informe.js
UTF-8
3,774
2.921875
3
[]
no_license
$(document).ready(function () { lista_informe() function lista_informe(){ $.get("../php/informe.php", function (response) { const tasks = JSON.parse(response) let template = ''; let template2 = ''; tasks.forEach(informe => { template += ` <tr id_turno = "${informe.id_turno}" recomendacion="${informe.reco_trabajador}"> <td>${informe.documento}</td> <td>${informe.nombre} ${informe.apellido}</td> <td>${informe.hora_total} horas</td> <td class="reco">${informe.reco_trabajador}</td> <td> <button class="btn btn-success btn-sm">Efectuar</button> <button class="btn btn-danger btn-sm">Aplazar</button> </td> </tr> ` template2 += ` <tr id_turno = "${informe.id_turno}" recomendacion="${informe.reco_maquina}"> <td>${informe.id_maquina}</td> <td>${informe.modelo_maquina}</td> <td>${informe.hora_total} horas</td> <td>${informe.reco_maquina}</td> <td> <button class="btn btn-success btn-sm">Efectuar</button> <button class="btn btn-danger btn-sm">Aplazar</button> </td> </tr> ` }); $('#tabla_trabajador').html(template); $('#tabla_maquina').html(template2); } ); } $(document).on('click', '.btn-success', (e) => { if (confirm('¿Estás seguro de esto?')) { const element = $(this)[0].activeElement.parentElement.parentElement; const id = $(element).attr('id_turno'); const recomendacion = $(element).attr('recomendacion'); const postData = { id_turno: id, recomendacion: recomendacion } $.post("../php/informe_success.php", postData, function (response) { if(response == "Realizado correctamente") { alert(response) lista_informe() } else { alert(response) } } ); } }); $(document).on('click', '.btn-danger', (e) => { if (confirm('¿Estás seguro de esto?')) { const element = $(this)[0].activeElement.parentElement.parentElement; const id = $(element).attr('id_turno'); const recomendacion = $(element).attr('recomendacion'); const postData = { id_turno: id, recomendacion: recomendacion } $.post("../php/informe_aplazar.php", postData, function (response) { if(response == "Aplazado correctamente") { alert(response) lista_informe() } else { alert(response) } } ); } }); });
true
9bc68795a11f68a1006c9002307532d6d1a097ea
JavaScript
ruk-na-Ziddi/XYZ
/practice1/guess.js
UTF-8
2,307
3.421875
3
[]
no_license
var min=0; var max=1000; var attempts=8; var valueOfButton=function(id){ var input= document.getElementById('itsInput'); input.value=input.value+id; } var getRandomInt=function(){ var num=Math.floor(Math.random()*(max-min))+min; return num; } var generatedNum=getRandomInt(); var reload=function(){ document.getElementById('itsInput').value=''; document.getElementById('message').value=''; document.getElementById('instruction').value=''; document.getElementById('attempt').value=9; location.reload(); }; var smaller=function(){ var input=document.getElementById('itsInput'); var message=document.getElementById('message'); if(input.value<generatedNum){ --attempts; message.value=input.value+' is smaller than Expected Number'; input.value=''; return true; }; }; var bigger=function(){ var input=document.getElementById('itsInput'); var message=document.getElementById('message'); if(input.value>generatedNum && input.value<=max){ --attempts; message.value=input.value+' is bigger than Expected Number'; input.value=''; return true; }; }; var gotIt=function(){ var input=document.getElementById('itsInput'); var message=document.getElementById('message'); if(input.value==generatedNum){ message.value='Got IT'; alert('Hey....... You did it.It was '+generatedNum); reload(); }; }; var moreThanMax=function(){ var input=document.getElementById('itsInput'); var message=document.getElementById('message'); if(input.value>max){ --attempts; message.value="Click on 'GetInstrunction' Please!!!!"; input.value=''; return true; }; }; var noInput=function(){ var input=document.getElementById('itsInput'); var message=document.getElementById('message'); if(input.value==''){ --attempts; message.value='Please give a number as Input'; return true; }; }; var maxAttemptsDone=function(){ if(attempts==0 && !gotIt()){ alert("Unfortunately You couldn't win, Number is==>"+generatedNum) reload(); }; }; var getInstrunction=function(){ var instruct=document.getElementById('instruction'); instruct.value='Type a number between '+min+' and '+max; }; var lockIt=function(){ var attempt=document.getElementById('attempt'); attempt.value=attempts; maxAttemptsDone() || noInput() || moreThanMax() || smaller() || bigger() || gotIt() };
true
9509beccb1ef0a76c6d5c8ac69d303f45a32835b
JavaScript
jessmcdonald/currency-converter
/src/App.js
UTF-8
708
2.546875
3
[]
no_license
import React from "react"; import "./App.css"; import Converter from "./components/converter/Converter"; import History from "./components/history/History"; class App extends React.Component { constructor(props) { super(props); this.state = { history: [], }; } addItemToHistory = (newitem) => { let updatedHistory = this.state.history; updatedHistory.unshift(newitem); this.setState({ history: updatedHistory }); console.log(this.state.history); }; render() { return ( <div className="App"> <Converter addItemToHistory={this.addItemToHistory} /> <History history={this.state.history} /> </div> ); } } export default App;
true
ed83b7401312b42c295648b7fa1e515757862999
JavaScript
pizza-is-life/todo-list
/assets/js/scripts.js
UTF-8
867
3.046875
3
[]
no_license
$(document).ready(function() { // Check off specific todos by clicking li $("ul").on("click", "li", function() { $(this).toggleClass("completed"); }); // Delete todos by clicking X $("ul").on("click", "span", function(event) { $(this).parent().fadeOut(500, function() { $(this).remove(); }); event.stopPropagation(); }); // Add new todo through input $("input[type='text']").on("keypress", function(event){ if(event.which === 13) { let todoText = ($(this).val()); $("ul").append("<li><span><i class='fas fa-trash-alt'></i></span> " + todoText + "</li>"); $(this).val(""); } }); // Toggle between showing and hiding the input field $("input").hide(); $("h1").on("click", "i", function(){ $("input[type='text']").fadeToggle(300, "swing"); $("h1 i").toggleClass("fa-plus"); }); });
true
a2e2dbdaf329651721278cde4eb250d4431c05be
JavaScript
KBerndt10/kyle-berndt-prework
/JavaScript_Basics_Assessment/activity-1.js
UTF-8
392
3.40625
3
[]
no_license
const product = 9 * 9; const quotient = 56 / 12; const remainder = 281 % 9; const inf = 18 / 0; const concat = '56' + '92'; const falseBool = 42 >= 52; console.log(`9 * 9 = ${product}`); console.log(`56 / 12 = ${quotient}`); console.log(`281 % 9 = ${remainder}`); console.log(`18 / 0 = ${inf}`); console.log(`\'56\' + \'92\' = ${concat}`); console.log(`42 >= 52 = ${falseBool}`);
true
7268b69df972f74afe291b5f6272e043ea381f53
JavaScript
luyongzhao/reframe
/utils/wxWrapper.js
UTF-8
3,065
2.65625
3
[]
no_license
function showToast(errMsg) { wx.showToast({ title: errMsg, icon: 'none', duration: 3000 }) } function get(url, data, succ, error){ //加载等待 wx.showLoading({ title: '加载中...', mask: true }) //网络请求 var requestTask = wx.request({ url: baseUrl+url, data: data, method: "get", header: { 'Content-Type': 'application/x-www-form-urlencoded', 'cookie': wx.getStorageSync("sessionid")//读取cookie }, success: function(res){ //console.log(JSON.stringify(res)); //登录请求回来之后,读取res的header的cookie //持久化sessionId if (res.header["Set-Cookie"] != null) { wx.setStorageSync("sessionid", res.header["Set-Cookie"]); } if (succ) { succ(res.data); } }, fail: function(e){ if (error) { error(e); }else{ //console.log(JSON.stringify(e)); showToast("服务器暂时不可用!"); } }, complete: function(e){ //无论成功失败,都需要关闭等待 wx.hideLoading(); } }) //返回请求,便于终止请求 return requestTask; } function post(url,data,succ,error){ //加载等待 wx.showLoading({ title: '加载中...', mask: true }) //网络请求 var requestTask = wx.request({ url: baseUrl + url, data: data, method: "post", header: { 'Content-Type': 'application/x-www-form-urlencoded', 'cookie': query("sessionid")//读取cookie }, success: function (res) { //console.log(JSON.stringify(res)); //登录请求回来之后,读取res的header的cookie //持久化sessionId if (res.header["Set-Cookie"]!=null) { upsert("sessionid", res.header["Set-Cookie"]); //wx.setStorageSync("sessionid", res.header["Set-Cookie"]); } if (succ) { succ(res.data); } }, fail: function (e) { if (error) { error(e); } }, complete: function (e) { //无论成功失败,都需要关闭等待 wx.hideLoading(); } }) //返回请求,便于终止请求 return requestTask; } function wxPromisify(fn) { return function (obj = {}) { return new Promise((resolve, reject) => { obj.success = function (res) { resolve(res) } obj.fail = function (res) { reject(res) } fn(obj) }) } } function upsert(k,v){ let value = wx.getStorageSync(k); if (value != null) { wx.removeStorageSync(k); } console.log("save in database,k="+k+",v="+v); wx.setStorageSync(k, v); } function query(k){ let v = wx.getStorageSync(k); console.log("query in database,k=" +k+",v="+v); return v; } function del(k){ wx.removeStorageSync(k); } module.exports.get = get; module.exports.post = post; module.exports.showToast = showToast; module.exports.wxPromisify = wxPromisify; module.exports.upsert = upsert; module.exports.query = query; module.exports.del = del;
true
7eb27196c2767bec61c30304ead9f9730f0daf14
JavaScript
konarssuresh/burger_react
/src/store/reducers/order.js
UTF-8
1,218
2.59375
3
[]
no_license
import * as actionTypes from '../actions/actionTypes'; const initialValue={ orders:[], loading:false, purchased:false } export const reducer=(state=initialValue,action)=>{ switch(action.type){ case actionTypes.FETCH_ORDER_START: return{ ...state, loading:true, } case actionTypes.FETCH_ORDER_SUCCESS: return { ...state, orders:action.orders, loading:false } case actionTypes.PURCHASE_INIT: return { ...state, purchased:false, } case actionTypes.PURCHASE_BURGER_SUCCESS: const orderObj={ ...action.orderData, id:action.orderId } return { ...state, orders:state.orders.concat(orderObj), loading:false, purchased:true } case actionTypes.PURCHASE_BURGER_FAILURE: return { ...state, loading:false } default: return state } } export default reducer
true
c36acc355240e5d6e64f9fa870dd9a2db536de0f
JavaScript
tbris/tic-tac-toe
/js/dom.js
UTF-8
4,384
2.53125
3
[ "MIT" ]
permissive
"use strict" const dom = (function(doc) { let container = doc.querySelector("#current"); let grid = doc.querySelector(".grid"); let turn = doc.querySelector("#turn"); let msgCont = doc.querySelector("#msg"); let autoMode = false; let darkMode = false; let finished = true; let currentPlayer = "O"; let botCoords = [null, null]; let returnCode; let msg; let preferences; // Start game const beginGame = (target) => { finished = false; _resetGrid(); target.remove(); _setCurrentMark(); pubSub.publish("start game") }; const _resetGrid = () => { for (let i = 0; i < grid.childElementCount; i++) { grid.children[i].textContent = null; } }; const _setCurrentMark = () => { turn.textContent = `"${currentPlayer}"`; }; // Mark cell const markCell = (target) => { let coord = target.dataset.coord.split(""); let currentMark = currentPlayer; pubSub.publish("mark", coord); if (Number.isInteger(returnCode)) { if (returnCode >= 3) target.textContent = currentMark; return _code(); } target.textContent = currentMark; if (autoMode) return _operateBot(coord) _setCurrentMark(); }; const _code = () => { switch (returnCode) { case 1: msg = "Please start the game"; break; case 2: msg = "That cell is not empty"; break; case 3: msg = `"${currentPlayer}" won!`; break; case 4: msg = "Game Over"; break; } if (returnCode >= 3) _finishGame(); returnCode = null; _activateMsg(msg); }; const _operateBot = (coord) => { if (!(coord[0] == botCoords[0] && coord[1] == botCoords[1])) { pubSub.publish("start bot"); return markCell(doc.querySelector(`[data-coord="${botCoords.join("")}"]`)); } } const _activateMsg = (msg) => { let strtBtn = doc.querySelector("#current > .btn"); let disappeared = []; let elements = [strtBtn, turn]; elements.forEach(element => { if (!element) return; element.classList.add("display-none"); disappeared.push(element); }); msgCont.textContent = msg; setTimeout(_disappearMsg.bind(this, disappeared), 2000); }; const _disappearMsg = (elements) => { msgCont.textContent = null; elements.forEach(element => element.classList.remove("display-none")); }; // Finish game const _finishGame = () => { _resetProperties(); turn.textContent = null; container.append(_createStartBtn()); pubSub.publish("finish game"); }; const _resetProperties = () => { finished = true; currentPlayer = "O"; botCoords = [null, null]; } const _createStartBtn = () => { let btn = doc.createElement("div"); btn.classList.add("btn"); btn.id = "start"; btn.tabIndex = 0; btn.textContent = "start"; return btn; }; // Change theme const changeTheme = () => { if (autoMode) _swapAutoTheme(); doc.body.classList.toggle("dark"); darkMode = !darkMode; pubSub.publish("set dark mode", darkMode); }; const _swapAutoTheme = () => { let [rClass, aClass] = darkMode ? ["dark", "light"] : ["light", "dark"]; doc.body.classList.remove("robot-" + rClass); doc.body.classList.add("robot-" + aClass); }; // Automatic mode const automaticMode = () => { if (!finished) return _activateMsg("You can't do that"); doc.body.classList.toggle("robot-" + (darkMode ? "dark" : "light")); autoMode = !autoMode; _activateMsg("Automatic mode: " + (autoMode ? "ON" : "OFF")) pubSub.publish("set auto mode", autoMode); }; // DOM storage const restoreProfile = () => { pubSub.publish("request pref keys"); if (preferences.includes("dark")) dom.changeTheme(); if (preferences.includes("auto")) dom.automaticMode(); }; // Events const _setCurrPlayer = (token) => currentPlayer = token; const _setRetCode = (code) => returnCode = code; const _setBotCoords = (coords) => botCoords = coords; const _setPreferences = (keys) => preferences = keys; pubSub.subscribe("change player", _setCurrPlayer); pubSub.subscribe("change return code", _setRetCode); pubSub.subscribe("change bot coords", _setBotCoords); pubSub.subscribe("get preferences", _setPreferences); return { beginGame, markCell, changeTheme, automaticMode, restoreProfile }; })(document);
true
c5967667aaa2948451042bbef853b13324df4f92
JavaScript
jmneutel/wexler-questions
/Quiz-program/public/assets/javascript/logic.js
UTF-8
10,725
3.046875
3
[]
no_license
var counter = 0; var database = firebase.database(); // Append text to the DOM function append_text(txt) { var docbody=document.getElementsByTagName("body")[0]; docbody.appendChild(document.createTextNode(txt)); docbody.appendChild(document.createElement("br")); } // Append row data to a row function append_td(row,txt) { var tdata=document.createElement("td"); tdata.appendChild(document.createTextNode(txt)); //console.log(txt); var text = txt; if (text === undefined) { text = "undefined"; } //console.log(text); if (text != "Scale" && text != "Scale Description" && text != "Raw Score" && text != "K Score" && text != "T Score" && text != "% Answered" && text != "Question" && text != "Answer" && text !="Question Text") { database.ref('entry').push(text); } row.appendChild(tdata); } // Append a row of data to a table function append_tr(table) { var trow=document.createElement("tr"); for(var i=1;i< arguments.length;++i) { append_td(trow,arguments[i]); } table.appendChild(trow); } // Append a table to the DOM and return a reference to it // Arguments are table headings (variable length) function make_table() { var docbody,table,thead,tbody,trow,i; docbody=document.getElementsByTagName("body")[0]; table=document.createElement("table"); table.setAttribute("class", "results-table"); table.setAttribute("border","5"); thead=document.createElement("thead"); table.appendChild(thead); tbody=document.createElement("tbody"); table.appendChild(tbody); docbody.appendChild(table); jared = table; //console.log(table); //console.log(tbody); trow=document.createElement("tr"); for(i=0;i< arguments.length;++i) { append_td(trow,arguments[i]); } thead.appendChild(trow); return tbody; } longform=true; // All questions or first 370 gender=0; // 0==male, 1==female ans=[]; // Answers to questions: [T,F,?] var profile; // Score the test function score() { // Change mouse pointer to wait indicator // This does not seem to work because JavaScript blocks the UI message pump :( document.body.style.cursor="wait"; // Variable declarations var i,j,tscale,q,n,s,rp; var k,rawscore,kscore,tscore,percent; var t_cnt,f_cnt,cs_cnt,pe; // Make the scale and critical item tables var scale_table=make_table("Scale","Scale Description","Raw Score","K Score","T Score","% Answered"); var ci_table=make_table("Scale","Scale Description","Question","Answer","Question Text"); // Count the number of True, False, and Can't Say answers n=longform?questions.length:371; t_cnt=0; f_cnt=0; cs_cnt=0; for(q=1;q< n;++q) { switch(ans[q]) { case "T": ++t_cnt; break; case "F": ++f_cnt; break; default: ++cs_cnt; break; } } --q; // Add T/F/? stats to scale table append_tr(scale_table,"True"," ",t_cnt," "," ",(t_cnt*100/q).toPrecision(3)); append_tr(scale_table,"False"," ",f_cnt," "," ",(f_cnt*100/q).toPrecision(3)); append_tr(scale_table,"?"," ",cs_cnt," "," ",(cs_cnt*100/q).toPrecision(3)); // Score the TRIN/VRIN scales // Iterate the *RIN scales for(i=0;i< rin.length;++i) { // Start with default score rawscore=rin[i][0][2]; // Iterate all the answer pairs for(j=0;j< rin[i][1].length;++j) { // Get reference to answer pair rp=rin[i][1][j]; // If answers match, update the raw score if(ans[rp[0]]===rp[1] && ans[rp[2]]===rp[3]) { rawscore+=rp[4]; } } // Append results to scale table append_tr(scale_table,rin[i][0][0],rin[i][0][1],rawscore," ",rin[i][2+gender][rawscore]," "); } // Score the scales and critical items k=0; pe=0; // Iterate all the scales for(i=0;i< scales.length;++i) { n=0; rawscore=0; // Get the T score table, critcal items will not have this (undefined) tscale=scales[i][3+gender]; // Iterate the True question list for(j=0;j< scales[i][1].length;++j) { // Get the question number q=scales[i][1][j]; // Act upon the answer to that question switch(ans[q]) { // True case "T": // Increment the answer count ++n; // Increment raw score only if True ++rawscore; // If this is a critcal item, add it to the critical items table if(tscale===undefined) { append_tr(ci_table,scales[i][0][1],scales[i][0][2],q,"True",questions[q]); } break; case "F": // Increment the answer count ++n; break; } } // Iterate the False question list (same procedure as True above) for(j=0;j< scales[i][2].length;++j) { q=scales[i][2][j]; switch(ans[q]) { case "F": ++n; ++rawscore; if(tscale===undefined) { append_tr(ci_table,scales[i][0][1],scales[i][0][2],q,"False",questions[q]); } break; case "T": ++n; break; } } // Add scale results to scale table // T score table must be defined, otherwise this is a critical item if(tscale!==undefined) { // Capture K for future use if(scales[i][0][0]==="K") { k=rawscore; } // If there is a K correction, use it if(tscale[0]) { // Adjust with K kscore=k*tscale[0]+rawscore; // Round off and make integer kscore=Math.floor(kscore+0.5); // T score lookup of corrected score tscore=tscale[kscore+1]; // No K correction } else { // K score is undefinded kscore=undefined; // T score lookup of raw score tscore=tscale[rawscore+1]; } // Calculate percent answered percent=n*100/(scales[i][1].length+j); // Append results to score table append_tr(scale_table,scales[i][0][1],scales[i][0][2],rawscore,kscore===undefined?" ":kscore,tscore,percent.toPrecision(3)); // Update profile elevation for the 8 scales switch(scales[i][0][1]) { case "Hs": case "D": case "Hy": case "Pd": case "Pa": case "Pt": case "Sc": case "Ma": pe+=tscore; break; } } } // Convert profile elevation sum to average (divide by number of scales) pe/=8; // Show profile elevation in page //append_text("Profile Elevation: "+pe.toPrecision(3)); profile = "Profile Elevation: "+pe.toPrecision(3); console.log(profile); database.ref('entry').push(profile); // Show an answer summary to allow for copy & paste of answers //append_text("Answer Summary"); s=""; for(q=1;q< questions.length;++q) { s+=ans[q]; if(s.length>=75) { //append_text(s); s=""; } } console.log(testing); database.ref('entry').push(testing); //if(s.length) { append_text(s);} //console.log(scale_table); setTimeout(function(){ post("/results"); }, 5000); // Restore mouse pointer document.body.style.cursor="auto"; } // Read status of radio button group and return value of selected button function radio_value(rb) { if(!rb) { return; } for(var i=0;i< rb.length;i++) { if(rb[i].checked===true) { return rb[i].value; } } } // Fill the answer array with radio button state and score var testing = []; testing.push('Answer Summary: '); function score_rb(form) { database.ref('entry').remove(); ans=[undefined]; for(var i=1;i< questions.length;++i) { var rbv=radio_value(form.elements["Q"+i]); if(rbv) { ans.push(rbv); testing.push(rbv); } else { ans.push("?"); testing.push("?"); } } score(); } // Fill the answer array from text and score function score_text(anstext) { //alert("Score Text: "+anstext.length); ans=[undefined]; var n=1; // Check each character of text for(var i=0;i< anstext.length;++i) { // Ignore control characters (0 to 31) and space (32) if(anstext.charCodeAt(i)>32) { // Convert character to 'T','F' or '?' var a; switch(anstext.charAt(i)) { case "T": case "t": case "Y": case "y": case "X": case "x": a="T"; break; case "F": case "f": case "N": case "n": case "O": case "o": a="F"; break; case "?": case "-": a="?"; break; default: a=undefined; break; } // Save valid answer in answer array if(a) { ans.push(a); ++n; } } } //alert((n-1)+" answers entered"); // If too few valid characters where processed, fill the remaining answers with '?' for(;n< questions.length;++n) { ans.push("?"); } // Score it score(); } // Set the test gender - called by onclick() event in the form function set_gender(g) { gender=g; //alert("gender: "+g); } // Set the test length - called by onclick() event in the form function use_long_form(lf) { longform=lf; //longformdiv.style.visibility=longform?"visible":"hidden"; longformdiv.style.display=longform?"inline":"none"; //alert("longform: "+longform); } // Write a single question to the HTML page function doc_write_question(name,text) { document.write('<ul class="list-group">'); document.write('<li class="list-group-item">'); document.write('<div class="btn-group" data-toggle="buttons"><label class="btn btn-primary"><input type="radio" name="'+name+'" autocomplete="off" value="T">True</label><label class="btn btn-primary"><input type="radio" name="'+name+'" autocomplete="off" value="F">False</label></div>'); document.write("&nbsp;&nbsp;"+text+"<br>"); document.write('</li>'); document.write('</ul>'); //document.write("<input type=\"radio\" name="+name+" value=\"F\">False&nbsp;"); // document.write("<input type=\"radio\" name="+name+" value=\"T\">True&nbsp;"); } // Write all question radio buttons and text to the HTML page - called from the HTML function doc_write_all_questions() { for(var i=1; i < questions.length; ++i) { doc_write_question("Q"+i,i+". "+questions[i]); if(i===370) { document.write("<div id=\"longformdiv\">"); } } if(i>370) { document.write("<\/div>"); } } function post(path, params, method) { method = method || "post"; // Set method to post by default if not specified. // The rest of this code assumes you are not using a library. // It can be made less wordy if you use one. var form = document.createElement("form"); form.setAttribute("method", method); form.setAttribute("action", path); for(var key in params) { if(params.hasOwnProperty(key)) { var hiddenField = document.createElement("input"); hiddenField.setAttribute("type", "hidden"); hiddenField.setAttribute("name", key); hiddenField.setAttribute("value", params[key]); form.appendChild(hiddenField); } } document.body.appendChild(form); form.submit(); }
true
d3373aa935be7fae358ad6dc39eb08c24db0c4b7
JavaScript
qaz734913414/Speech-Nodes
/speech/read-file.js
UTF-8
963
2.75
3
[]
no_license
/* *本节点用于测试语音识别和语音合成节点 *语音数据通过my_msg.audio_len和my_msg.audio_data传递给语音识别节点 *文本数据通过my_msg.text传递给语音合成节点 */ module.exports = function(RED) { var fs = require('fs'); var file_name = 'text_to_speech_result.pcm';//需要读取的音频文件 var my_msg = new Object(); var node function ReadFile(config) { RED.nodes.createNode(this,config); node = this; this.on('input', function(msg) { read(); this.send(msg); }); } function read(){ fs.readFile(file_name , function(err, data) { if(err) { console.error(err); } else{ my_msg.audio_len = data.length;//将读取音频文件的长度传入my_msg my_msg.audio_data = data;//将音频文件数据传入my_msg my_msg.text = "春眠不觉晓";// node.send(my_msg); } }); } RED.nodes.registerType("read-file",ReadFile); }
true
742d985a17cc6a8ec4c0acfccdc2c2538cda9bd2
JavaScript
battez/d3a
/scripts/main.js
UTF-8
11,449
2.953125
3
[]
no_license
/* JL Barker 1: wrote a D3 program that consumes the feed 2: draws a map of the UK 3: Plots the towns form the feed on the map 4: You can use any details in the feed to enhance the map. */ var debugMode = (window.location.hash !== "#debug") ? false : true; var amount = debugMode ? 20 : document.getElementById('slide').value; var feedUrl = function (amount) { //debug with local script if remote not working: //return 'scripts/20.json'; // Feed url: //return 'http://ac51041-1.cloudapp.net:8080/Circles/Towns/' + parseInt(amount); // alt feed URL: return 'http://ac32007.cloudapp.net:8080/Circles/Towns/' + parseInt(amount); } // var url = feedUrl(amount); var url = 'https://raw.githubusercontent.com/battez/d3a/master/scripts/20.json' /* ** Load remote JSON: */ // set up a global which will be our dataset: var dataset; // asynchronously load in the JSON from the remote feed: d3.json(url, function(error, json) { if (error) return console.warn(error); // set this JSON data to the global we made earlier: dataset = json; showD3(); // display our plot now the JSON has had a chance to load: //console.log('dataset loaded now, should be plotted.') // // unpause the slider again to allow input: document.getElementById('slide').disabled = false; }); // Meanwhile, set up the SVG container for our map, and its projection etc: var w = 1105; var h = 1296; var xOffset = 300; var yOffset = 250; // global SVG var svg = d3.select("body") .append("svg") .attr("width", w) .attr("height", h); var currentTowns; // credit: edited and previewed on mapstarter.com var mapFile = 'uk-map-topo-mci.json'; // d3 map projection setup: from 3D to 2D! var projection = d3.geo.mercator() .scale(2250) .center([-5.960072394999926,55.76000251037824]) //projection center .translate([w/2 - xOffset, h/2 - yOffset]) //translate to shift the map // "path" encapsulates the geographic features for us // then we reference the custom projection from earlier var path = d3.geo.path().projection(projection); // group for UK map var features = svg.append("g") .attr("class","features"); // load local copy of UK geodata and display the map d3.json(mapFile, function(error,geodata) { if (error) return console.log(error); //Create a separate path for each map feature in our geodata (countries) features.selectAll("path") .data(topojson.feature(geodata,geodata.objects.subunits).features) //generate features from TopoJSON .enter() .append("path") .attr("d", path) .attr("title", function (d) { return d.id; }) .attr("class", function (d) { return "subunit " + d.id; }) features.selectAll(".subunit-label") .data(topojson.feature(geodata,geodata.objects.subunits).features) .enter() .append("text") .attr("class", function(d) { return "subunit-label " + d.id; }) .attr("transform", function(d) { return "translate(" + path.centroid(d) + ")"; }) .attr("dy", "1em") .attr("dx", "0.25em") .text(function(d) { return d.properties.name; }); }); /* this is our visualise data wrapper, ** that gets called once JSON loads from "url" **/ var showD3 = function(updating) { updating = updating || false; if(updating) { // remove all current d3.select('svg').select('g.towns').selectAll('circle').remove(); d3.select('svg').select('g.towns').remove(); d3.select('svg').selectAll('g.legend-entry').remove(); } // make a sqrt scale for our circles as this will represent the area better for // differing populations var rScale = d3.scale.sqrt() .domain([0, d3.max(dataset, function(d) { return d.Population; })]) .rangeRound([2, 16]); // colorbrewer2.org palette in green. // circle color will belong to one bin var colorScale = d3.scale.quantize() .domain([ 0, d3.max(dataset, function(d) { return Math.ceil(d.Population / 1000) * 1000; }) ]) .range(['#edf8e9','#c7e9c0','#a1d99b','#74c476','#31a354','#006d2c']); // // we set a scale for radius by population and also // color scale - slotting the circle into a bucket/bin range // currentTowns = svg.append('g').attr("class","towns") .selectAll('circle') .data(dataset) .enter() .append('circle') .attr("id",function(d, i){return "town" + d.Population;}) .attr('cx', function(d){ return projection([d.lng, d.lat])[0]; }) .attr('cy', function(d){ return projection([d.lng, d.lat])[1]; }) .attr('r', function(d){ return rScale(d.Population); }) .attr('fill', function(d){ return colorScale(d.Population); }) .append('svg:title').text(function(d) { return d.Town + ", "+ d.Population; }); // Display a visual legend for colorScale of towns population: var legend = svg.selectAll('g.legend-entry') .data(colorScale.range()) .enter() .append('g').attr('class', 'legend-entry'); legend .append('rect') .attr("x", 10) .attr("y", function(d, i) { return 200 + i * 20; }) .attr("width", 20) .attr("height", 20) .style("fill", function(d){return d;}); legend.append('text') .attr("x", 35) .attr("y", function(d, i) { return 205 + i * 20; }) .attr("dy", "8px") .text(function(d,i) { var extent = colorScale.invertExtent(d); //extent will be a two-element array, format it however you want: var format = d3.format("f"); return format(+extent[0]) + " to " + format(+extent[1]) + ' inhabitants'; }); svg.select('g.legend-entry').append('text').attr('text-anchor','start') .attr('transform', 'translate(10,190)') .text('Colour / Population: '); // HORIZ. BAR CHART OF TOWNS; top-right: datasetSorted = dataset.sort(function(a,b) { return b.Population - a.Population; }), function(d) { return d.Population; }; var barH = 8; // set line height var verticalOffset = 20; var xScale = d3.scale.linear() .domain([0, d3.max(dataset, function(d){ return d.Population; })]) .range([0, 399]); // Draw the bars in the bar chart: var bars = svg.select('g.towns').selectAll("rect") .data(datasetSorted) .enter() .append("rect") .attr("x", 700) .attr("y", function(d, i) { return verticalOffset + (i * (barH + 0.5)); }) .attr("width", function(d) { return xScale(d.Population); }) .attr("height", barH); var barLabels = svg.select('g.towns').selectAll("text") .data(datasetSorted) .enter() .append("text") .text(function (d) { return d.Town.trim() + ' ' + zeroFill(d.Population, 6); }) .attr("class", 'label') .attr('text-anchor', 'end') .attr("x", 729) .attr("y", function(d, i) { return verticalOffset + 7 + (i * (barH + 0.5)); }) .attr("id", function(d){ return "own" + d.Population; // add a hook to this element }) .attr("width", 300) .attr("height", barH) .on( "click", function(){ var search = "t" + this.id; // first, remove earlier highlights: d3.select('g.towns') .selectAll('text.selected') .attr('class', 'label'); d3.select('g.towns') .selectAll('circle') .attr('style',''); d3.selectAll('.highlight') .remove(); // highlight the town with a big circle and label it: this.setAttribute("class", "label selected"); var showing = d3.select('circle#'+search) .style('fill','#ff0000') .style('stroke-width','75px') .style('stroke', '#dd9999'); if(!showing.empty()) { d3.select('g.towns').append('text').attr('class', 'highlight') .attr('x', showing.attr('cx')).attr('y', showing.attr('cy')) .text(showing.data()[0]['Town']); } }); // draw an axis (just once!) if (d3.select('g.axes').empty()) { var xAxis = d3.svg.axis() .scale(xScale) .orient('top') .ticks(4); svg.append('g') .attr('class', 'axes') .attr("transform", "translate(" + 701 + ", 20)") .call(xAxis); svg.select('g.axes').append('text').attr('text-anchor','end') .attr('transform', 'translate(-10,-10)') .text('Town/Inhabitants '); } }; // end showD3() // FIXME: County Layer // county centroids: list of CSV format Lat/Long centroids by UK county // credit: http://www.nearby.org.uk/counties/ // N Ire is wrong, so Londonderry, Derry, Antrim, Armagh, Fermanagh, Down, Tyrone // must be mapped to that // also some others wrong :( if no towns for that county just hide. // - counties - group // var counties = []; d3.csv('uk-county-centroids-no-eire.csv', function(csvData){ svg.append('g').attr("class","counties") .selectAll('circle') .data(csvData) .enter() .append('circle') .attr('id', function(d, i){ return 'county' + i; }) .attr('cx', function(d){ return projection([d.wgs84_long, d.wgs84_lat])[0]; }) .attr('cy', function(d){ return projection([d.wgs84_long, d.wgs84_lat])[1]; }) .attr('r', 15) .on( "click", function(){ var search = "text-" + this.id; // first, remove earlier highlights: d3.select('g.counties') .selectAll('text').attr('style',''); // highlight the town with a big circle and label it: var showing = d3.select('text#'+search) .style('opacity','1'); }); // label counties: svg.select('g.counties') .selectAll('text') .data(csvData) .enter() .append('text') .text( function(d){ return d.name; }) .attr('id', function(d, i){ counties[i] = d.name; return 'text-county'+i; }) .attr('text-anchor', 'start') .attr('x', function(d){ return projection([d.wgs84_long, d.wgs84_lat])[0]; }) .attr('y', function(d){ return projection([d.wgs84_long, d.wgs84_lat])[1]; }) .attr('transform', 'translate(45 -30) rotate(5)') .attr('class', 'county-label'); }); /* ** ** misc .js for events etc ** */ /* event handler for a html5 range control to set data feed amount */ var slide = document.getElementById('slide'), sliderDiv = document.getElementById('amount'); // adjust and ReLoad data slide.onchange = function() { sliderDiv.innerHTML = this.value; url = feedUrl(this.value); // pause this until the new data has loaded: this.disabled = true; // asynchronously load in the JSON from the remote feed: d3.json(url, function(error, json) { if (error) return console.warn(error); // set this JSON data to the global we made earlier: dataset = json; showD3(true); // display our plot now the JSON has had a chance to load: // console.log('dataset loaded now, should be plotted.') // unpause: document.getElementById('slide').disabled = false; }); } sliderDiv.innerHTML = slide.value; // initialise this value /* event handler for a checkbox */ function handleClick(cb) { toggleVisibility('counties'); } function toggleVisibility(className) { elements = document.getElementsByClassName(className); for (var i = 0; i < elements.length; i++) { elements[i].style.display = elements[i].style.display == 'inline' ? 'none' : 'inline'; } } function htmlEntities(str) { return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;'); } function zeroFill(number, width) { width -= number.toString().length; if ( width > 0 ) { return new Array( width + (/\./.test( number ) ? 2 : 1) ).join( '0' ) + number; } return number + ""; // returns a string }
true
8a24a782f4b9168b7f8e8abcfbfadf7029c206e9
JavaScript
MrKaKaluote/study
/excess/javascript/leetcode/连续的子数组和/index.js
UTF-8
1,298
3.375
3
[]
no_license
/* * @Description: https://leetcode-cn.com/problems/continuous-subarray-sum/ * @Autor: ruyun * @Date: 2021-06-03 10:17:10 * @LastEditors: ruyun * @LastEditTime: 2021-06-03 10:20:19 */ /** * @param {number[]} nums * @param {number} k * @return {boolean} */ var checkSubarraySum = function(nums, k) { let map = new Map(),remd = 0 map.set(0, -1) for(let i = 0; i < nums.length; i++) { remd += nums[i] let tt = remd % k if (map.has(tt)) { if (i - map.get(tt) >=2) { return true } } else { map.set(tt, i) } } return false }; // /** // * @param {number[]} nums // * @param {number} k // * @return {boolean} // */ // var checkSubarraySum = function(nums, k) { // var map = new Map() // map.set(0, -1); // var sum = 0 // for(var i = 0 ; i < nums.length; i++){ // sum+= nums[i] // if(k != 0){ // sum = sum % k // 先取余再加一个数=两数相加取余(23%6 + 2) % 6 === (23+2)% 6 // } // if(map.has(sum)){ // if(i - map.get(sum) > 1){ // return true // } // }else { // map.set(sum, i) // } // } // return false // };
true
926361425ce0daaed5f209ea5bb4db38a2b2270b
JavaScript
TeamHowler/altitude-apparel
/client/ProductOverview/Size.jsx
UTF-8
2,075
2.546875
3
[]
no_license
/* eslint-disable guard-for-in */ import React, {useContext} from 'react'; import {ProductContext} from '../context.js'; import {Col, Row} from 'react-bootstrap'; function Size() { const {currentStyle, currentSize, updateSize} = useContext(ProductContext); const skuArr = []; const quantArr = []; if (currentStyle === undefined) { return <center><div className="spinner-border" role="status"> <span className="sr-only">Loading...</span> </div></center>; } else if (currentStyle.skus) { for (const keys in currentStyle.skus) { const newObj = {}; newObj.sku = keys; newObj.size = currentStyle.skus[keys].size; newObj.quantity = currentStyle.skus[keys].quantity; if (skuArr.indexOf(newObj.size) < 0) { skuArr.push(newObj); }; }; if (currentStyle.skus[currentSize]) { const tempQuant = currentStyle.skus[currentSize].quantity; for (let i = 1; i < tempQuant; i++) { quantArr.push(i); } } return ( <Row className='mb-3'> <Col> <style type="text/css"> {` #customDrop { background-color: #f3f7f0; border-color: transparent; color: black; height: 2rem } `} </style> <select id='customDrop' onChange={(e) => { e.preventDefault(); updateSize(e.target.value); }}> <option>Select A Size</option> {skuArr.map((item) => { return <option key={item.sku} value={item.sku}>{item.size} </option>; })} </select> </Col> <Col> <select id="customDrop"> <option>Select A Quantity</option> {currentSize ? quantArr.map((quant) => { return (<option key={quant}>{quant}</option>); }) : <option>choose a size first</option> } </select> </Col> </Row> ); } } export default Size;
true
d58734ad1c7589bc054ee33b30fd71a7fe6f0f24
JavaScript
aparna0003/aparna0003
/sketches/p5/p5/webcam.js
UTF-8
441
2.78125
3
[]
no_license
let video; let button; function takesnap() { image(video,0,0); ellipse(5,10,10,10) } function setup() { createCanvas(200, 200); background(51); video= createCapture(VIDEO); video.size(200,200); fill(120,70,30); button = createButton('SNAP'); button.mousePressed(takesnap); // ellipse(5,10,10,10) } // function takesnap() // { // image(video,0,0); // ellipse(5,10,10,10) // } function draw() { //background(220); }
true
2f5c1e3b4b18c44c38d53b0825c8dfa1cd245b1b
JavaScript
duchuytran943/note-ECMAScript-Advanced-Example
/method-overriding.js
UTF-8
398
3.5
4
[]
no_license
/** * methods-overriding */ class CoffeeMachine { makeCoffee() { console.log("making coffee..."); } } class SpecialCoffeeMachine extends CoffeeMachine { makeCoffee(cbFunc) { console.log("making spectial coffee and do somethings..."); cbFunc(); } } const coffeeMachine = new SpecialCoffeeMachine(); coffeeMachine.makeCoffee(function() { console.log("Call the boss..."); });
true
84c28685f551c28c4c43fd49d9d131fedb49779a
JavaScript
celelstine/codingProblemSolutions
/CDS_65_print_matrix_clockwise.js
UTF-8
2,012
4.3125
4
[ "MIT" ]
permissive
function popRow(matrix, rowIndex, start_column, end_column, direction = 1) { if (direction === 1) { for (var i = start_column; i <= end_column; i++) { console.log(matrix[rowIndex][i]); } } else { for (var i = start_column; i >= end_column; i--) { console.log(matrix[rowIndex][i]); } } matrix.splice(rowIndex, 1); return matrix; } function popColumn(matrix, columnIndex, startRow, endRow, direction = 1) { if (direction === 1) { for (var i = startRow; i <= endRow; i++) { console.log(matrix[i][columnIndex]); matrix[i].splice(columnIndex, 1); } } else { for (var i = startRow; i >= endRow; i--) { console.log(matrix[i][columnIndex]); matrix[i].splice(columnIndex, 1); } } return matrix; } function printMatrix_clockWise(matrix) { let problemDescription = ` This problem was asked by Amazon. Given a N by M matrix of numbers, print out the matrix in a clockwise spiral. For example, given the following matrix: [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]] You should print out the following: 1 2 3 4 5 10 15 20 19 18 17 16 11 6 7 8 9 14 13 12 `; console.log(`Problem Description \n${problemDescription}`); let matrix_copy = matrix; try { matrix_copy = popRow(matrix_copy, 0, 0, matrix_copy[0].length - 1); matrix_copy = popColumn(matrix_copy, matrix_copy[0].length - 1, 0, matrix_copy.length - 1) matrix_copy = popRow(matrix_copy, matrix_copy.length - 1,matrix_copy[matrix_copy.length - 1].length - 1, 0, -1); matrix_copy = popColumn(matrix_copy, 0, matrix_copy.length - 1, 0, -1) } catch (ex) { return; } } let test = [ [1, 2, 4 ,5 ,6, 'a'], [7, 8, 9 ,10, 11, 'b'], [12, 13, 14, 15, 16, 'c'], [17, 18, 19, 20, 21, 'd'], ]; printMatrix_clockWise(test); // test.splice(0,1) // console.log(test);
true
55ddca62cac0b31acfbda08bcf4f08d54e87c839
JavaScript
timurkalimullin/basic-js
/src/extended-repeater.js
UTF-8
742
3.125
3
[ "MIT" ]
permissive
module.exports = function repeater(str,{repeatTimes, separator = "+", addition, additionRepeatTimes, additionSeparator = "|"}){ let addBlock = [], finalBlock = []; if (String(addition).length>0) { if (additionRepeatTimes>0) { while (additionRepeatTimes) { addBlock.push(addition===null?"null":String(addition)); additionRepeatTimes--; } } else { addBlock.push(addition)} } str = String(str) + addBlock.join(additionSeparator); if (repeatTimes>0) { while (repeatTimes) { finalBlock.push(str); repeatTimes--; } } else {finalBlock.push(str)}; return finalBlock.join(separator) };
true
5177b3b254a8625d0066e5b00feb55a4f5cc5031
JavaScript
felipandrade/launchbase
/1.challenges/1.introduction-to-web/challenge-1.3/2.search-for-technology.js
UTF-8
594
3.40625
3
[ "MIT" ]
permissive
const users = [ { name: "Carlos", technologies: ["HTML", "CSS"] }, { name: "Jasmine", technologies: ["JavaScript", "CSS"] }, { name: "Tuane", technologies: ["HTML", "Node.js"] } ]; function checkUserUseCss(user) { for( let technologie of user.technologies ) { const userUseCss = technologie === 'CSS' if (userUseCss) { return true; } } return false; } for (let user of users) { const userWorksWithCss = checkUserUseCss(user); if (userWorksWithCss) { console.log(`The user ${user.name} works with CSS`); } }
true
25c783273f8143236a9d32fe6a6ed154c7dd084d
JavaScript
thatkaiguy/AppAcademy
/Week6/w6d1/Asteroids/lib/gameView.js
UTF-8
834
2.8125
3
[]
no_license
(function() { var Asteroids = window.Asteroids = window.Asteroids || {}; var GameView = Asteroids.GameView = function(game, ctx) { this.game = game; this.ctx = ctx.getContext("2d"); }; GameView.prototype.start = function () { var game = this.game; var ctx = this.ctx; this.bindKeyHandlers(); var interval = window.setInterval(function(){ game.step(); game.draw(ctx); }, 20); }; GameView.prototype.bindKeyHandlers = function() { var game = this.game; key('w', function() {game.ship.power([0,-1])} ); key('a', function() {game.ship.power([-1,0])} ); key('s', function() {game.ship.power([0,1])} ); key('d', function() {game.ship.power([1,0])} ); key('space', function() {game.ship.fireBullet()}); }; })();
true
547a8929c83327acdae37a6cfc6f8c707d85899e
JavaScript
khan4019/advJSDebug
/scripts/promiseDemo.js
UTF-8
2,984
3.234375
3
[ "MIT" ]
permissive
var fakeSlowNetwork; (function() { var lsKey = 'fake-slow-network'; var networkFakeDiv = document.querySelector('.network-fake'); var checkbox = networkFakeDiv.querySelector('input'); fakeSlowNetwork = Number(localStorage.getItem(lsKey)) || 1; networkFakeDiv.style.display = 'block'; checkbox.checked = !!fakeSlowNetwork; checkbox.addEventListener('change', function() { localStorage.setItem(lsKey, Number(checkbox.checked)); location.reload(); }); }()); function spawn(generatorFunc) { function continuer(verb, arg) { var result; try { result = generator[verb](arg); } catch (err) { return Promise.reject(err); } if (result.done) { return result.value; } else { return Promise.resolve(result.value).then(callback, errback); } } var generator = generatorFunc(); var callback = continuer.bind(continuer, "next"); var errback = continuer.bind(continuer, "throw"); return callback(); } function wait(ms) { return new Promise(function(resolve) { setTimeout(resolve, ms); }); } function get(url) { // Return a new promise. // We do all the work within the constructor callback. var fakeNetworkWait = wait(3000 * Math.random() * fakeSlowNetwork); var requestPromise = new Promise(function(resolve, reject) { // Do the usual XHR stuff var req = new XMLHttpRequest(); req.open('get', url); req.onload = function() { // 'load' triggers for 404s etc // so check the status if (req.status == 200) { // Resolve the promise with the response text resolve(req.response); } else { // Otherwise reject with the status text reject(Error(req.statusText)); } }; // Handle network errors req.onerror = function() { reject(Error("Network Error")); }; // Make the request req.send(); }); return Promise.all([fakeNetworkWait, requestPromise]).then(function(results) { return results[1]; }); } function getJson(url) { return get(url).then(JSON.parse); } function getSync(url) { var startTime = Date.now(); var waitTime = 3000 * Math.random() * fakeSlowNetwork; var req = new XMLHttpRequest(); req.open('get', url, false); req.send(); while (waitTime > Date.now() - startTime); if (req.status == 200) { return req.response; } else { throw Error(req.statusText || "Request failed"); } } function getJsonSync(url) { return JSON.parse(getSync(url)); } function getJsonCallback(url, callback) { getJson(url).then(function(response) { callback(undefined, response); }, function(err) { callback(err); }); } var storyDiv = document.querySelector('.story'); function addHtmlToPage(content) { var div = document.createElement('div'); div.innerHTML = content; storyDiv.appendChild(div); } function addTextToPage(content) { var p = document.createElement('p'); p.textContent = content; storyDiv.appendChild(p); }
true
36929e90b658ec414d69f2892e9e2d441dec98f5
JavaScript
jtefera/node_learning_examples
/06_files/appendData.js
UTF-8
469
3.53125
4
[]
no_license
//appendData.js //Cada vez que se llama a este archivo, //añade al final del texto la fecha a la que se hizo //Modulo fs para tratar con archivos var fs = require("fs"); var filepath = "appending.txt"; //Tiempo actual más salto de linea var textToAppend = Date() + "\r\n"; //appendFile, añade textToAppend al final del archivo filepath fs.appendFile(filepath, textToAppend, function(err) { if(err) return console.log(err); console.log("Fecha Añadida!"); });
true
0ffc20d224469b81092250c9406a8119d1ce95a7
JavaScript
brandonsargent/brandonsargent.github.io
/js/main.js
UTF-8
259
2.5625
3
[]
no_license
var teaser = false; $("document").ready(function(){ if (teaser == true) { // open teaser website window.open("templates/teaser.html", "_self"); } else { // open regular website window.open("templates/home.html", "_self"); } });
true
a4f416367246e0d5fef5756c5757802adeedf9dd
JavaScript
Vinit453/schoolbackend2
/services/schoolService.js
UTF-8
2,703
2.640625
3
[]
no_license
var appRoot = require('app-root-path'); var con = require(appRoot + '/services/connectionService'); exports.getSchools = function (queryString, callback) { var sql = "select * from tbl_school"; con.query(sql, function (err, result) { if (err) { callback(null, err); return; } else { callback(null, result); return; } }); } exports.getSchoolById = function (id, callback) { var sql = "select * from tbl_school where id='" + id + "'"; con.query(sql, function (err, result) { if (err) { callback(null, err); return; } else { callback(null, result); return; } }); } exports.postSchool = function (school, callback) { var setString = ""; var keyString=""; var valueString=""; let schoolbjectLeng = Object.keys(school).length; var i = 1; for (var key in school) { if (i != schoolbjectLeng) { keyString=keyString+key+','; valueString=valueString+"'"+school[key]+"',"; } else { keyString=keyString+key; valueString=valueString+"'"+school[key]+"'"; } i++; } var sql = "INSERT INTO tbl_school ("+keyString+") VALUES (" +valueString+")"; con.query(sql, function (err, result) { if (err) { callback(null, err); return; } else { callback(null, result); return; } }); } exports.patchSchool = function (id, school, callback) { var setString = ""; let schoolbjectLeng = Object.keys(school).length; var i = 1; for (var key in school) { console.log(key + " " + school[key]); // here is your column name you are looking for if (i != schoolbjectLeng) setString = setString + key + "='" + school[key] + "',"; else setString = setString + key + "='" + school[key] + "'"; i++; } var sql = "UPDATE tbl_school SET " + setString + "WHERE id = '" + id + "'"; console.log("Final Update query =\n" + sql); con.query(sql, function (err, result) { if (err) { callback(null, err); return; } else { callback("User Updated"); } console.log(result.affectedRows + " record(s) updated"); }) } exports.deleteSchool = function (id, callback) { var sql = "DELETE from tbl_school where id='" + id + "'"; con.query(sql, function (err, result) { if (err) { callback(null, err); return; } else { callback(null, result); return; } }); }
true
7ee925e213b317af4bc3acb47aa639cc238c58ae
JavaScript
mitchelkuijpers/ajxr
/test/ajxrTest.js
UTF-8
1,995
2.53125
3
[ "MIT" ]
permissive
describe('ajxr', function() { // Fix Sinon bug when using 'FakeXMLHttpRequest' in Node // https://github.com/cjohansen/Sinon.JS/issues/319 if (navigator.userAgent.indexOf('PhantomJS') !== -1){ window.ProgressEvent = function (type, params) { params = params || {}; this.lengthComputable = params.lengthComputable || false; this.loaded = params.loaded || 0; this.total = params.total || 0; }; } beforeEach(function(){ this.xhr = sinon.useFakeXMLHttpRequest(); var requests = this.requests = []; this.xhr.onCreate = function (xhr) { requests.push(xhr); }; }); afterEach(function(){ this.xhr.restore(); }); describe('Get', function(){ it('should do an AJAX request', function(done){ ajxr.get('/users').then(function(response){ response.should.have.lengthOf(1); response[0].should.have.property('username', 'tomtheun'); done(); }).done(); this.requests[0].respond(200, {}, '[{ "username": "tomtheun"}]'); }); it('should reject promise when AJAX request returns a 404', function(done){ ajxr.get('/users/non-existing-user').fail(function(response){ response.should.have.property('message', 'Status code was 404'); done(); }).done(); this.requests[0].respond(404); }); }); describe('Post', function(){ it('should do an AJAX request', function(done){ ajxr.post('/users', {'username': 'tomtheun'}).then(function(response){ response.should.have.property('username', 'tomtheun'); done(); }).done(); this.requests[0].respond(201, {}, '{ "username": "tomtheun"}'); }); it('should reject promise when AJAX request returns a 400', function(done) { ajxr.post('/users', {'usrname': 'tomtheun'}).fail(function(response) { response.should.have.property('message', 'Status code was 400'); done(); }); this.requests[0].respond(400); }); }); });
true
3879677b6f2b30f4fc0f2d90bbe863b0316be0a4
JavaScript
GaianiMagali/Photogram-Backend
/server/src/middleware/auth.js
UTF-8
705
2.546875
3
[]
no_license
const jwt = require("jsonwebtoken"); module.exports = (req, res, next) => { const authHeader = req.headers.authorization; if (!authHeader) return res.status(401).send({ error: "No autorizado" }); const parts = authHeader.split(" "); if (parts.length !== 2) return res.status(401).send({ error: "Token error" }); const [scheme, token] = parts; if (!/^Bearer$/i.test(scheme)) return res.status(401).send({ error: "Token malformateado" }); jwt.verify(token, process.env.SIGNATURE_TOKEN, (error, decode) => { if (error) return res.status(401).send({ error: "Token invalido" }); req.userId = decode.id; return next(); }); };
true
4290ec338298b26b7b93f2bd53beb9a4f6f25e6c
JavaScript
kapil125/rps
/app.js
UTF-8
3,500
3.75
4
[]
no_license
const playerImg = document.getElementById("plyr-img"); const computerImg = document.getElementById("comp-img"); const rockSelected = document.getElementById("rock"); const paperSelected = document.getElementById("paper"); const scissorsSelected = document.getElementById("scissors"); const won = document.getElementById("won"); const loose = document.getElementById("loose"); const tie = document.getElementById("tie"); const changeBestOfBtn = document.getElementById("bestof"); const bestOfText = document.getElementById("best"); const resultText = document.getElementById("result"); const ROCK = "ROCK"; const PAPER = "PAPER"; const SCISSORS = "SCISSORS"; let wonNumber = 0; let looseNumber = 0; let tieNumber = 0; let choosenBestOf = 3; let runCheck = 0; const computerChoice = () => { const computer = Math.trunc(Math.random() * 100); if (computer < 34) { return ROCK; } else if (computer < 67) { return PAPER; } else { return SCISSORS; } }; //Resets Everything const reset = (bestof = 3) => { wonNumber = 0; looseNumber = 0; tieNumber = 0; choosenBestOf = bestof; runCheck = 0; won.textContent = wonNumber; loose.textContent = looseNumber; tie.textContent = tieNumber; bestOfText.textContent = choosenBestOf; resultText.textContent = " "; computerImg.src = "images/crock.png"; playerImg.src = "images/prock.png"; }; const winnerManager = (userSelText, userSel) => { runCheck += 1; const compSel = computerChoice(); playerImg.src = userSel; if (compSel === ROCK) { computerImg.src = "images/crock.png"; } else if (compSel === PAPER) { computerImg.src = "images/cpaper.png"; } else if (compSel === SCISSORS) { computerImg.src = "images/cscissors.png"; } //checking winner if ( (userSelText === ROCK && compSel === SCISSORS) || (userSelText === PAPER && compSel === ROCK) || (userSelText === SCISSORS && compSel === PAPER) ) { wonNumber += 1; won.textContent = wonNumber; } else if ( (compSel === ROCK && userSelText === SCISSORS) || (compSel === PAPER && userSelText === ROCK) || (compSel === SCISSORS && userSelText === PAPER) ) { looseNumber += 1; loose.textContent = looseNumber; } else if (userSelText === compSel) { tieNumber += 1; tie.textContent = tieNumber; } //checking best of and setting result if (runCheck === choosenBestOf) { if (wonNumber > looseNumber) { resultText.textContent = "You Won"; console.log("You Won"); } else if (wonNumber === looseNumber) { console.log("Game Was Tie"); resultText.textContent = "It's A Tie"; } else { console.log("You Loose"); resultText.textContent = "You Loose"; } setTimeout(reset, 3000); } }; rockSelected.addEventListener( "click", winnerManager.bind(null, ROCK, "images/prock.png") ); paperSelected.addEventListener( "click", winnerManager.bind(null, PAPER, "images/ppaper.png") ); scissorsSelected.addEventListener( "click", winnerManager.bind(null, SCISSORS, "images/pscissors.png") ); changeBestOfBtn.addEventListener("click", () => { let bestOfValue = parseInt(prompt("Enter any number", "3")); isNaN(bestOfValue) || bestOfValue < 3 ? alert("It's Not A Number or you have choosen less than 3") : (choosenBestOf = bestOfValue); bestOfText.textContent = choosenBestOf; reset(choosenBestOf); });
true
1d70b97ff4fc6f22a5b6d19bc903cc67e7fa9c06
JavaScript
palak-sethi/CodeDecode
/js/main.js
UTF-8
2,274
3.390625
3
[]
no_license
function showCode() { document.getElementById('code').style.display = "block"; document.getElementById('codeBtn').style.display = "none"; } function showDecode() { document.getElementById('decode').style.display = "block"; document.getElementById('decodeBtn').style.display = "none"; } function code1() { var str = document.getElementById("codeMessage").value; var rev = str.split("").reverse().join(""); document.getElementById("codedMessage").innerHTML = rev; } function decode1() { var str = document.getElementById("decodeMessage").value; var rev = str.split("").reverse().join(""); document.getElementById("decodedMessage").innerHTML = rev; } function code2() { var str = document.getElementById("codeMessage").value; var n = str.length; var s = str.split(""); var coded = ""; for(var i=0; i<n; i++) { var c = str.charCodeAt(i); if((c >= 97 && c <= 109) || (c >= 65 && c <= 77)) { c = c+13; } else if((c >= 110 && c <= 122) || (c >= 78 && c <= 90)) { c = c-13; } else if((c >= 48 && c <= 52)) { c = c + 5; } else if((c >= 53 && c <= 57)) { c = c - 5; } else { continue; } s[i] = String.fromCharCode(c); } var coded = s.join(""); document.getElementById("codedMessage").innerHTML = coded; } function decode2() { var str = document.getElementById("decodeMessage").value; var n = str.length; var s = str.split(""); var coded = ""; for(var i=0; i<n; i++) { var c = str.charCodeAt(i); if((c >= 97 && c <= 109) || (c >= 65 && c <= 77)) { c = c+13; } else if((c >= 110 && c <= 122) || (c >= 78 && c <= 90)) { c = c-13; } else if((c >= 48 && c <= 52)) { c = c + 5; } else if((c >= 53 && c <= 57)) { c = c - 5; } else { continue; } s[i] = String.fromCharCode(c); } var decoded = s.join(""); document.getElementById("decodedMessage").innerHTML = decoded; }
true
423df7c7d548a3f3f93d349b19ca2bd9372ff501
JavaScript
remusao/pbot
/content_scripts/find_candidates.js
UTF-8
2,262
2.703125
3
[]
no_license
const { parse } = require('tldjs'); // cached regex case insensitive (crci) const KEYWORDS = [ new RegExp('privacy', 'i'), new RegExp('datenschutz', 'i'), new RegExp('Конфиденциальность', 'i'), new RegExp('Приватность', 'i'), new RegExp('тайность', 'i'), new RegExp('隐私', 'i'), new RegExp('隱私', 'i'), new RegExp('プライバシー', 'i'), new RegExp('confidential', 'i'), new RegExp('mentions-legales', 'i'), new RegExp('conditions-generales', 'i'), new RegExp('mentions légales', 'i'), new RegExp('conditions générales', 'i'), new RegExp('termini-e-condizioni', 'i') ]; function matchKeyword(url) { for (let i = 0, len = KEYWORDS.length; i < len; i++) { if (KEYWORDS[i].test(url)) { return true; } } } // Finds all urls in a page that match the keywords function candidateUrls(htmlDoc) { const links = htmlDoc.getElementsByTagName('a'); const candidates = []; const uniqueUrls = {}; for (let i = 0, len = links.length; i < len; i++) { if ((matchKeyword(links[i].href) || matchKeyword(links[i].innerText)) && !(links[i].href in uniqueUrls)) { uniqueUrls[links[i].href] = true; candidates.push({ 'domain': parse(location).domain, 'text': links[i].innerText, 'url': links[i].href }); } } return candidates; }; // Communicating with background.js function handleResponse(message) { console.log(`backround.js: ${message.response}`); } function handleError(error) { console.log(`Error: ${error}`); } function notifyBackgroundPage(e) { let candidates = JSON.stringify(candidateUrls(document)); // send candidate urls to bakcgound.js let sending = browser.runtime.sendMessage({ candidates: candidates }); sending.then(handleResponse, handleError); } // Not sure I like this, but at least it triggers, // and updates the icon bage text ['DOMContentLoaded', 'load', 'ontouchstart', 'scroll'].forEach( evt => window.addEventListener(evt, notifyBackgroundPage, { once: true, passive: true, capture: true } ) );
true
373a15a55a2dfe8fb8c1ba6ee4127a53a162f2df
JavaScript
pauladarias/users_API
/user.js
UTF-8
5,947
2.953125
3
[]
no_license
// function fetchData() { // fetch("http://35.178.207.61:8080/pubmate/api/0.1/user/1") // .then(response => { // console.log(response) // if (!response.ok) { // throw Error("ERROR") // } // return response.json() // }).then(data => { // console.log(data.username) // // mapping over (if array of users) each user // //const html = data.users.map(user =>{ // // return `<p>Name: ${user.name}</p> // //}) // document.querySelector("#app").innerHTML = // ` // <h1>USERS</h1> // <div class="user"> // <h1>${data.id}</h1> // <p>User Name: ${data.username}</p> // <p>User Email: ${data.email}</p> // </div> // ` // }).catch(err =>{ // console.log(err) // }) // } // fetchData(); // function postData() { // fetch("http://35.178.207.61:8080/pubmate/api/0.1/user", { // method: "POST", // headers: { // "Content-Type" : "application/json" // }, // body: JSON.stringify({ // username: "Paula", // email: "[email protected]" // }) // }) // .then(response => { // console.log(response) // if (!response.ok) { // throw Error("ERROR") // } // return response.json() // }).then(data => { // console.log(data) // }).catch(err =>{ // console.log(err) // }) // } // postData(); // ---------------------- const usersList = document.querySelector(".users-list"); const addUserForm = document.querySelector(".add-user-form"); const usernameValue = document.getElementById("username-value"); const emailValue = document.getElementById("email-value"); const btnSubmit = document.querySelector(".btn") let output = ""; //const renderUsers = (users) => { // data.forEach(user => { // output += ` // <div class="card mt-4 col-md-6 bg-light" style="width: 18rem;"> // <img src="./user_profile_pic.png" class="card-img-top" alt="..."> // <div class="card-body"> // <h5 class="card-title">Card title</h5> // <h6 class="card-subtitle mb-2 text-muted">Card subtitle</h6> // <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> // <a href="#" class="card-link">Edit</a> // <a href="#" class="card-link">Delete</a> // </div> // </div> // ` // }); //friendsList.innerHTML = output; //} const url = "http://35.178.207.61:8080/pubmate/api/0.1/user/1"; fetch(url) .then(response => response.json()) .then(data => { //.then(data => renderUsers(data)) usersList.innerHTML = ` <div class="card mt-4 col-md-6 bg-light" style="width: 18rem;"> <img src="./user_profile_pic.png" class="card-img-top" alt="..."> <div class="card-body" data-id=${data.id}> <h5 class="card-username">${data.username}</h5> <h6 class="card-email mb-2 text-muted">${data.email}</h6> <small class="card-subtitle mb-2 text-muted">${data.timestamp}</small> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="card-link" id="edit-user">Edit</a> <a href="#" class="card-link" id="delete-user">Delete</a> <a href="http://127.0.0.1:5500/userFriends/userFriends.html" class="card-link">Friends</a> </div> </div> ` usersList.addEventListener("click", (e) =>{ e.preventDefault(); let editButtonIsPressed = e.target.id == "edit-user" let deleteButtonIsPressed = e.target.id == "delete-user" let id = (e.target.parentElement.dataset.id) //DELETE EXISTING USER if(deleteButtonIsPressed) { fetch("http://35.178.207.61:8080/pubmate/api/0.1/user/" + `${id}`, { method: "DELETE", }) .then(res => res.json()) .then(() => location.reload()) } if(editButtonIsPressed) { const parent = e.target.parentElement; let usernameContent = parent.querySelector(".card-username").textContent let emailContent = parent.querySelector(".card-email").textContent usernameValue.value = usernameContent; emailValue.value = emailContent; } // UPDATE THE EXISTING USER btnSubmit.addEventListener("click", () => { fetch("http://35.178.207.61:8080/pubmate/api/0.1/user/" + `${id}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username: usernameValue.value, email: emailValue.value }) .then(res => res.json()) .then(() => location.reload) }) }) }) }) // POST METHOD ADD USER - input value - NOT WORKING ----------- // addUserForm.addEventListener("submit", (e) => { // e.preventDefault(); // console.log(usernameValue.value) // fetch("http://35.178.207.61:8080/pubmate/api/0.1/user", { // method: "POST", // headers: { // "Content-Type" : "application/json" // }, // body: JSON.stringify({ // username: usernameValue.value, // email: emailValue.value // }) // }) // .then(response => response.text()) // console.log(response) // .then(text => { // console.log(text) // // const dataArr = []; // // dataArr.push(data); // //renderUsers(dataArr) // }) // }) function postData() { fetch("http://35.178.207.61:8080/pubmate/api/0.1/user", { method: "POST", headers: { "Content-Type" : "application/json" }, body: JSON.stringify({ id: "6", username: 'Paula', email: '[email protected]' }) }) .then(response => { console.log(response) if (!response.ok) { throw Error("ERROR") } return response.text() }).then(text => { console.log(text) }) } postData();
true
f76c9a0eb6775f098285aaf13c63d3381bde1020
JavaScript
brandon1011/vaxx-pass-web
/src/components/User/index.js
UTF-8
2,065
2.5625
3
[]
no_license
import React, { useState, useEffect, useRef } from 'react'; import QRCode from 'qrcode'; import './style.css'; import VerifiedImage from '../../assets/images/verified.png'; import UnverifiedImage from '../../assets/images/unverified.png'; export default function User(props) { const [user, setUser] = useState(null); const canvasContainerRef = useRef(); useEffect(() => { if (user) { QRCode.toCanvas(user.user_id, { errorCorrectionLevel: "H", width: 180, color: {dark: "#003766", light: "#fff"} }, (err, canvas) => { if (err) throw err; canvasContainerRef.current.appendChild(canvas); }); } else { const url = "https://vaxx-pass-server.herokuapp.com/api/users/12111111"; fetch(url) .then(res => res.json()) .then(data => setUser(data)) .catch(err => console.log(err)); } }); function renderName() { if (user) { return user.first_name + " " + user.last_name; } else { return ""; } } function renderImage() { if (user) { return ( <div class="status_container"> <span>{user.vaccine_verified ? "Vaccine verified" : "Not verified"}</span> <img id="verify_image" src={user.vaccine_verified ? VerifiedImage : UnverifiedImage} /> </div> ); } else { return ""; } } return ( <div class="account_container"> <div id="nav_top"> <span class="sign_out_button">Sign Out</span> <div id="user_info_container"> <span id="user_full_name">{renderName()}</span> <span id="user_location">Toronto, ON, CA</span> </div> <span class="settings_button">&#x2699;</span> </div> <div ref={canvasContainerRef} id="canvas_container"></div> {renderImage()} </div> ); }
true
73db3ebec9e368228be795363528a7dccae04d86
JavaScript
givedirectly/Google-Partnership
/docs/import/manage_disaster_add_delete.js
UTF-8
7,013
2.546875
3
[ "MIT" ]
permissive
import {eeLegacyPathPrefix, legacyStateDir} from '../ee_paths.js'; import {showError} from '../error.js'; import {disasterCollectionReference} from '../firestore_document.js'; import {createDisasterData} from './create_disaster_lib.js'; import {setStatus} from './create_score_asset.js'; import {createOptionFrom} from './manage_common.js'; import {disasterData} from './manage_disaster_base.js'; export {addDisaster, deleteDisaster, setUpAddDelete, toggleState}; // For testing. export {writeNewDisaster}; /** Adds handlers to manage_disaster page. Called when Firestore is ready. */ function setUpAddDelete() { // enable add disaster button. const addDisasterButton = $('#add-disaster-button'); addDisasterButton.prop('disabled', false); addDisasterButton.on('click', addDisaster); // Enable delete button. const deleteButton = $('#delete'); deleteButton.prop('disabled', false); deleteButton.on('click', deleteDisaster); } /** * Deletes a disaster from firestore. Confirms first. Returns when deletion is * complete (or instantly if deletion doesn't actually happen). * * TODO(janakr): If a slow write from {@link updateDataInFirestore} happens to * lose to this delete, the doc will be recreated, which isn't great. Could * maybe track all pending write promises and chain this one off of them, or * disable delete button until all pending writes were done (might be good to * give user an indication like that). * @return {Promise<void>} */ function deleteDisaster() { const disasterPicker = $('#disaster-dropdown'); const disasterId = disasterPicker.val(); if (confirm('Delete ' + disasterId + '? This action cannot be undone')) { disasterData.delete(disasterId); // Don't know how to get a select element's "options" field in jQuery. disasterPicker[0].remove(disasterPicker[0].selectedIndex); const newOption = disasterPicker.children().eq(0); disasterPicker.val(newOption.val()).trigger('change'); return disasterCollectionReference().doc(disasterId).delete(); } return Promise.resolve(); } /** * Onclick function for submitting the new disaster form. Writes new disaster * to firestore, local disasters map and disaster picker. Doesn't allow name, * year or states to be empty fields. * @return {Promise<boolean>} resolves true if new disaster was successfully * written. */ function addDisaster() { const year = $('#year').val(); const name = $('#name').val(); let states = $('#states').val(); if (!year || !name) { setStatus('Error: Disaster name and year are required.'); return Promise.resolve(false); } if ($('#disaster-type-flexible').is(':checked')) { states = null; } else if (!states) { setStatus('Error: states are required for Census-based disaster.'); return Promise.resolve(false); } if (isNaN(year)) { setStatus('Error: Year must be a number.'); return Promise.resolve(false); } if (notAllLowercase(name)) { setStatus( 'Error: disaster name must be comprised of only lowercase letters'); return Promise.resolve(false); } const disasterId = year + '-' + name; return writeNewDisaster(disasterId, states); } /** * Writes the given details to a new disaster entry in firestore. Fails if * there is an existing disaster with the same details or there are errors * writing to EarthEngine or Firestore. Tells the user in all failure cases. * * @param {string} disasterId of the form <year>-<name> * @param {?Array<string>} states array of states (abbreviations) or null if * this is not a state-based disaster * @return {Promise<boolean>} Returns true if EarthEngine folders created * successfully and Firestore write was successful */ async function writeNewDisaster(disasterId, states) { if (disasterData.has(disasterId)) { setStatus('Error: disaster with that name and year already exists.'); return false; } setStatus(''); const eeFolderPromises = [getCreateFolderPromise(eeLegacyPathPrefix + disasterId)]; if (states) { states.forEach( (state) => eeFolderPromises.push( getCreateFolderPromise(legacyStateDir + '/' + state))); } const tailError = '" You can try refreshing the page'; // Wait on EE folder creation to do the Firestore write, since if folder // creation fails we don't want to have to undo the write. try { await Promise.all(eeFolderPromises); } catch (err) { showError('Error creating EarthEngine folders: "' + err + tailError); return false; } const currentData = createDisasterData(states); try { await disasterCollectionReference().doc(disasterId).set(currentData); } catch (err) { const message = err.message ? err.message : err; showError('Error writing to Firestore: "' + message + tailError); return false; } disasterData.set(disasterId, currentData); const disasterPicker = $('#disaster-dropdown'); let added = false; // We expect this recently created disaster to go near the top of the list, so // do a linear scan down. // Note: let's hope this tool isn't being used in the year 10000. // Comment needed to quiet eslint. disasterPicker.children().each(/* @this HTMLElement */ function() { if ($(this).val() < disasterId) { createOptionFrom(disasterId).insertBefore($(this)); added = true; return false; } }); if (!added) disasterPicker.append(createOptionFrom(disasterId)); toggleState(true); disasterPicker.val(disasterId).trigger('change'); return true; } /** * Returns a promise that resolves on the creation of the given folder. * TODO: add status bar for when this is finished. * * @param {string} dir asset path of folder to create * @return {Promise<void>} resolves when after the directory is created and * set to world readable. */ function getCreateFolderPromise(dir) { return new Promise( (resolve, reject) => ee.data.createFolder(dir, false, (result, failure) => { if (failure && !failure.startsWith('Cannot overwrite asset ')) { reject(failure); return; } ee.data.setAssetAcl( dir, {all_users_can_read: true}, (result, failure) => { if (failure) { reject(failure); return; } resolve(result); }); })); } /** * Returns true if the given string is *not* all lowercase letters. * @param {string} val * @return {boolean} */ function notAllLowercase(val) { return !/^[a-z]+$/.test(val); } /** * Changes page state between looking at a known disaster and adding a new one. * @param {boolean} known */ function toggleState(known) { if (known) { $('#create-new-disaster').show(); $('#new-disaster').hide(); $('#current-disaster-interaction').show(); } else { $('#create-new-disaster').hide(); $('#new-disaster').show(); $('#current-disaster-interaction').hide(); } }
true
d6732e9e054479ef999ea4678b8be79aa93a0f18
JavaScript
zhangjianhaoww/blog
/target/myblog/resources/js/adminindex.js
UTF-8
1,691
2.546875
3
[]
no_license
$(function () { var url = "/myblog/admin/admininitinfo"; var articlePage = 1; var articleType = null; var pageCount = 1; $("#buttonfull").click(); getAdminInitInfo(articlePage, articleType); function getAdminInitInfo(articlePage, articleType) { $.getJSON(url, { articlePage:articlePage, articleType:articleType }, function (data) { if(data.success){ setAtricleInfo(data.articles); } }) } function setAtricleInfo(data) { var html = ''; data.map(function (item, index) { html += '<tr>' +'<td>'+ item.articleId + '</td>' +'<td><a href="/myblog/article/articledetails?articleId=' + item.articleId +'">' + item.articleName + '</a></td>' +'<td>' + item.articleId +'</td>' //item.articleType +'<td class="am-hide-sm-only">' + item.articleId +'</td>' //item.articleOwner.userName +' <td class="am-hide-sm-only">' + item.articleLastEditTime +'</td>' +'<td>' +'<div class="am-btn-toolbar">' +'<div class="am-btn-group am-btn-group-xs">' +'<a class="am-btn am-btn-default am-btn-xs am-text-secondary"><span class="am-icon-pencil-square-o"></span> 编辑</a>' +'<a class="am-btn am-btn-default am-btn-xs am-text-danger am-hide-sm-only"><span class="am-icon-trash-o"></span> 删除</a>' +'</div>' +'</div>' +' </td>' +'</tr>' }) $("#articleInfo").html(html); } })
true
085a25db36de640040b06187b683335026570044
JavaScript
joewickes/playstore-practice-express
/app.js
UTF-8
2,156
3.125
3
[]
no_license
const express = require('express'); const morgan = require('morgan'); // Data from Thinkful const apps = require('./apps.json'); const app = express(); app.use(morgan('dev')); app.get('/apps', (req, res) => { // Sort the list by either rating or app, any other value results in an error, if no value provided do not perform a sort. // one of ['Action', 'Puzzle', 'Strategy', 'Casual', 'Arcade', 'Card']If present the value must be one of the list otherwise an error is returned. Filter the list by the given value. // Sort & genres destructured from request query object const { sort, genres } = req.query; // Spread apps array into results const results = [...apps]; // if a genres parameter was passed, filter it appropriately if (genres) { // make genres case insensitive const genresLC = genres.toLowerCase(); // Make sure it includes a valid genre classification if ( genresLC === 'action' || genresLC === 'puzzle' || genresLC === 'strategy' || genresLC === 'casual' || genresLC === 'arcade' || genresLC === 'card' ) { // filter by lowercased genre return res.json(results.filter(result => { return result.Genres.toLowerCase().includes(genresLC); })); } else { return res.status(404).send( 'Make sure to filter by Action, Puzzle, Strategy, Casual, Arcade, or Card.' ); } } if (sort) { if (sort !== 'rating' && sort !== 'app') { return res.status(404).send('Make sure to sort by either rating or app.'); } else if (sort === 'app') { return res.json(results.sort((a, b) => { if (a.App.toLowerCase() > b.App.toLowerCase()) { return 1; } else if (b.App.toLowerCase() > a.App.toLowerCase()) { return -1; } else { return 0; } })); } else if (sort === 'rating') { return res.json(results.sort((a, b) => { if (a.Rating > a.Rating) { return 1; } else if (b.Rating < a.Rating) { return -1; } else { return 0; } })); } } return res.send(results); }); module.exports = app;
true
feb711d273682f35d689f2de52ef2b68fe3edc0d
JavaScript
szolotukhin-language/js-webpack
/server.js
UTF-8
357
2.609375
3
[]
no_license
const express = require("express") const app = express() app.get('/api/users', (req, res) => // res.send("HELLO FROM EXPRESS 22") res.json([ {username: 'Serhij Zolotukhin 1'}, {username: 'Serhij Zolotukhin 2'}, {username: 'Serhij Zolotukhin 3'} ] ) ); app.listen(8082, () => console.log("Example app listening on port 3000!") );
true
10b9b7266a8cffd3f7e6714c9972c79d93389759
JavaScript
haiitk14/react_online_shop
/src/reducers/categorys.js
UTF-8
1,734
2.796875
3
[]
no_license
import * as Types from './../constants/ActionTypes'; var initialState = []; const categorys = (state = initialState, action) => { var { categorys, category } = action; switch (action.type) { case Types.GET_CATEGORYS: state = categorys; return [...state]; case Types.POST_CATEGORY: state.push(action.category); return [...state]; case Types.DELETE_CATEGORY: let indexDel = findIndex(state, category.id); state.splice(indexDel, 1); return [...state]; case Types.UPDATE_CATEGORY: let indexUp = findIndex(state, category.id); state[indexUp] = { ...state[indexUp], name: category.name, code: category.code, description: category.description, order: category.order, isPublic: category.isPublic, titleSeo: category.titleSeo, keywordsSeo: category.keywordsSeo, descriptionSeo: category.descriptionSeo, updatedDate: category.updatedDate }; return [...state]; case Types.UPDATE_STATUS: let indexUpStatus = findIndex(state, category.id); state[indexUpStatus] = { ...state[indexUpStatus], isPublic: state[indexUpStatus].isPublic } return [...state]; default: return [...state]; } }; var findIndex = (categorys, id) => { var result = -1; categorys.forEach((categogy, index) => { if (categogy.id === id) { result = index; } }); return result; } export default categorys;
true
76aab89743a9bda930876c327eb3ebe51b0d363b
JavaScript
MikeMurrayDev/react100-change-calculator
/src/js/app.jsx
UTF-8
9,432
2.890625
3
[]
no_license
import React, { Component } from 'react'; import { render } from 'react-dom'; class App extends Component { constructor(props) { super(props); this.state = { amountDue: '0', amountReceived: '0', twenties: '0', tens: '0', fives: '0', ones: '0', quarters: '0', dimes: '0', nickels: '0', pennies: '0', changeDue: 'No change due at this time.', }; this.handleChange = this.handleChange.bind(this); this.calculate = this.calculate.bind(this); } handleChange(event){ this.setState({ [event.target.name]: event.target.value}); } calculate() { var change = this.state.amountReceived - this.state.amountDue; var change = change.toFixed(2); this.setState({ changeDue: `The total change due is $${change}` }); const twenties = Math.floor(change / 20); this.setState({ twenties: twenties }); var remainder = change % 20; const tens = Math.floor(remainder / 10); this.setState({ tens: tens }); var remainder = remainder % 10; const fives = Math.floor(remainder / 5); this.setState({ fives: fives }); var remainder = remainder % 5; const ones = Math.floor(remainder / 1); this.setState({ ones: ones }); var remainder = remainder % 1; const quarters = Math.floor(remainder / .25); this.setState({ quarters: quarters }); var remainder = remainder % .25; const dimes = Math.floor(remainder.toFixed(2) / .10); this.setState({ dimes: dimes }); var remainder = remainder % .10; const nickels = Math.floor(remainder.toFixed(2) / .05); this.setState({ nickels: nickels }); var remainder = remainder % .05; const pennies = Math.floor(remainder.toFixed(2) / .01); this.setState({ pennies: pennies }); var remainder = remainder % .01; } render() { return ( <div> <div className='container-fluid' style={{width: '90%'}}> <h1 style={{ color: 'white', paddingTop: '1.25em', marginBottom: '0.5em' }}>Change Calculator</h1> <hr style={{ backgroundColor: 'white', height: '0.0625em' }}/> <div className='container' style={{padding: '0em'}}> <div className='row'> <div className='col-sm-4' style={{ marginBottom: '1em'}}> <div className='card'> <h6 className='card-header'> Enter Information </h6> <div className='card-body'> <div className='form-group'> <div style={{ fontWeight: 'bold', marginBottom: '8px' }}> How much is due? </div> <input className='form-control' name='amountDue' type='number' placeholder='0' step='0.01' style={{ width: '100%', margin: 'auto'}} value={this.state.amountDue} onChange={this.handleChange} pattern="^-?[0-9]\d*\.?\d*$"/> </div> <div className='form-group'> <div style={{ fontWeight: 'bold', marginBottom: '8px' }}> How much was received? </div> <input className='form-control' name='amountReceived' type='number' placeholder='0' step='0.01' style={{ width: '100%', margin: 'auto'}} value={this.state.amountReceived} onChange={this.handleChange} pattern="^-?[0-9]\d*\.?\d*$"/> </div> </div> <div className='card-footer'> <button className='btn btn-primary' name='calculate' style={{ backgroundColor: '#337AB7', color: 'white', width: '100%', margin: 'auto'}} onClick={this.calculate}>Calculate</button> </div> </div> </div> <div className='col-sm-8'> <div className='card' style={{margin: 'auto'}}> <div className='card-body'> <div className='row' style={{margin: 'auto auto 1em'}}> <div className='card' style={{ backgroundColor: '#DFF0D8', color: '#69A080', height: '20%', width: '100%', margin: 'auto', borderRadius: '.25rem', display: 'block'}}> <div className='card-body'> <div style={{display: 'flex', justifyContent: 'center'}} value={this.state.changeDue}>{this.state.changeDue}</div> </div> </div> </div> <div className='row'> <div className='col-md'> <div className='card'> <div className='card-body' style={{ backgroundColor: '#F5F5F5', width: '100%'}}> <div style={{textAlign: 'center', fontWeight: 'bold'}}> Twenties </div> <div style={{textAlign: 'center'}} value={this.state.twenties}>{this.state.twenties}</div> </div> </div> </div> <div className='col-md'> <div className='card'> <div className='card-body' style={{ backgroundColor: '#F5F5F5'}}> <div style={{textAlign: 'center', fontWeight: 'bold'}}> Tens </div> <div style={{textAlign: 'center'}} value={this.state.tens}>{this.state.tens}</div> </div> </div> </div> <div className='col-md'> <div className='card'> <div className='card-body' style={{ backgroundColor: '#F5F5F5'}}> <div style={{textAlign: 'center', fontWeight: 'bold'}}> Fives </div> <div style={{textAlign: 'center'}} value={this.state.fives}>{this.state.fives}</div> </div> </div> </div> <div className='col-md'> <div className='card'> <div className='card-body' style={{ backgroundColor: '#F5F5F5'}}> <div style={{textAlign: 'center', fontWeight: 'bold'}}> Ones </div> <div style={{textAlign: 'center'}} value={this.state.ones}>{this.state.ones}</div> </div> </div> </div> </div> <div className='row' style={{marginTop: '1em'}}> <div className='col-sm'> <div className='card'> <div className='card-body' style={{ backgroundColor: '#F5F5F5', width: '100%'}}> <div style={{textAlign: 'center', fontWeight: 'bold'}}> Quarters </div> <div style={{textAlign: 'center'}} value={this.state.quarters}>{this.state.quarters}</div> </div> </div> </div> <div className='col-sm'> <div className='card'> <div className='card-body' style={{ backgroundColor: '#F5F5F5'}}> <div style={{textAlign: 'center', fontWeight: 'bold'}}> Dimes </div> <div style={{textAlign: 'center'}} value={this.state.dimes}>{this.state.dimes}</div> </div> </div> </div> <div className='col-sm'> <div className='card'> <div className='card-body' style={{ backgroundColor: '#F5F5F5'}}> <div style={{textAlign: 'center', fontWeight: 'bold'}}> Nickels </div> <div style={{textAlign: 'center'}} value={this.state.nickels}>{this.state.nickels}</div> </div> </div> </div> <div className='col-sm'> <div className='card'> <div className='card-body' style={{ backgroundColor: '#F5F5F5'}}> <div style={{textAlign: 'center', fontWeight: 'bold'}}> Pennies </div> <div style={{textAlign: 'center'}} value={this.state.pennies}>{this.state.pennies}</div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> ) } } render(<App />, document.getElementById('root')); export default App;
true
879bf1283472d9be98362a7afb4b7e78c49007a4
JavaScript
Codezainab/myjava
/film.js
UTF-8
522
3.171875
3
[]
no_license
let film = ("kung fu hustle"); let films = ["inglorious Bastards", "matilda", "pulpfiction", "her",] console.log("My third favourite film is " + films[2]) console.log("My second favourite film is " +films[1]) let book = ("Harry Potter"); let books = ["The Perks Of Being A Wallflower", "Lord Of The Rings", "Charlie and The Chocolate Factory"] console.log("My favourite book is " + books[2] + " and my favourite film is " + films[0]) console.log("My favourite film is " + films[1] + "and my favourite book is " + books[1])
true
e52686c33d76a633a3e68f4b9d8be8b63cfa8688
JavaScript
crappy-coder/astrid
/src/Thread.js
UTF-8
575
2.90625
3
[]
no_license
class Thread { constructor(callback) { this.threadCallback = callback; this.threadTarget = null; this.threadArgs = null; } getCallback() { return this.threadCallback; } setCallback(value) { this.threadCallback = value; } start(target) { this.threadTarget = target; // remove the target from the arguments if (arguments.length > 1) { this.threadArgs = $A(arguments).slice(1); } return window.setTimeout((function () { return this.threadCallback.apply(this.threadTarget, this.threadArgs); }).bind(this), 0); } } export default Thread;
true
1ecae89ae969df259a61cfb02ae2be02a197fdaf
JavaScript
lwd6666/school
/好酷音乐网站/js/1.js
UTF-8
318
2.515625
3
[]
no_license
var t=demo.scrollWidth demo1.innerHTML+=demo1.innerHTML function doMarquee() { demo.scrollLeft=demo.scrollLeft<demo.scrollWidth-demo.offsetWidth?demo.scrollLeft+1:t-demo.offsetWidth } function doscroll() { sc=setInterval(doMarquee,20) } function stopscroll() { clearInterval(sc) } doscroll() ;
true
297cc538bdf1e751b204f0b0afdd10ef09176809
JavaScript
Q-Jones92/Week-4-Homework
/setInterval.js
UTF-8
159
2.8125
3
[]
no_license
var count = 0 var time = 1000 var intervalId = setInterval(function(){ console.log(count); count++ if(count == 900){ clearInterval(intervalId) } },time)
true
bcd0c6ef8da7194ee6e96a3298ec42abcfd2e0b8
JavaScript
iskonplus/js-course
/hometasks/lesson5/lesson5-app/src/App.js
UTF-8
2,811
2.625
3
[]
no_license
import React from 'react'; import { LoginForm } from './components/LoginForm' import './App.css'; // const compose = (...fns) => { // return value => { // let result = value; // for (let fn of fns) { // result = fn(result) // } // return result; // } // } // const withValidation = (validationFn, errorMessage) => BaseComponent => { // return class WithValidation extends React.Component { // render() { // if (this.props.error) { // return <BaseComponent {...this.props} /> // } // const isError = validationFn(this.props.value) // return ( // <BaseComponent // {...this.props} // error={isError ? errorMessage : null} // /> // ) // } // } // } // const emailValidationFn = value => { // const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; // return value ? !re.test(String(value).toLowerCase()) : false // } // const requiredValidationFn = value => !value // const withEmailValidation = withValidation(emailValidationFn, 'Invalid Email') // const withRequiredValidation = withValidation(requiredValidationFn, 'Required') // function debounce(f, ms) { // let isCooldown = false // return function() { // if (isCooldown) return; // f.apply(this, arguments) // isCooldown = true; // setTimeout(() => isCooldown = false, ms); // } // } // const withDebounce = timeout => BaseComponent => { // return class WithDebounce extends React.Component { // state = { // onChange: null, // } // static getDerivedStateFromProps(nextProps, state) { // if (nextProps.onChange !== state.onChange) { // const debouncedOnChange = debounce(nextProps.onChange, timeout) // return { // debouncedOnChange, // onChange: nextProps.onChange // } // } // return null // } // handleChange = event => { // return debounce(this.props.onChange, timeout) // } // render() { // return <BaseComponent // {...this.props} // onChange={this.state.debouncedOnChange} // /> // } // } // } // const withTextFieldValidation = compose( // withEmailValidation, // withRequiredValidation, // ) // const withField = compose( // withDirty, // withTextFieldValidation, // ) // const EnhancedTextField = withField(TextField) class App extends React.Component { state = { search: 'qweqe', } handleSearch = event => { console.log(event.target.value) } render() { return ( <div> <input defaultValue={this.state.search} onChange={this.handleSearch} /> </div> ) } } export default App;
true
e1c1faba0969f6a4a58ab2ea2d12d27dd4cdeddc
JavaScript
swtpumpkin/JavascriptAlgorithm
/Exercise/alphaString46.js
UTF-8
897
4.5625
5
[]
no_license
//alphaString46 함수는 문자열 s를 매개변수로 입력받는다. s의 길이가 4 ~ 6이고, 숫자로만 구성되어 있는지 확인하는 함수를 완성하라. function alphaString46(s) { /* 문자열을 배열의 형태로 바꿔 4자리 이상 6자리 이하인지 확인한다. 확인 후 true이면 정규표현식을 사용하여 문자열이 숫자형인지 확인 후 맞으면 true 문자열이 숫자 이외의 다른 문자가 있으면 false를 반환한다. if문에서 3항연산자로 변환하였다. */ return (s.split('').length<= 6 && s.split('').length>= 4)? /^\d+$/.test(s) : false; } console.log(alphaString46('123456')) //true console.log(alphaString46('39472')) //true console.log(alphaString46('1234567')) //false console.log(alphaString46('a1234')) //false console.log(alphaString46('ab')) //false console.log(alphaString46('123')) //false
true
73080bc6d32b7a64717e385648a4f96a8bbe1a76
JavaScript
relf/XDSMjs
/src/graph.js
UTF-8
8,756
2.578125
3
[ "Apache-2.0" ]
permissive
var UID = "_U_"; var MULTI_TYPE = "_multi"; function Node(id, name, type) { if (typeof (name) === 'undefined') { name = id; } if (typeof (type) === 'undefined') { type = 'analysis'; } this.id = id; this.name = name; this.isMulti = (type.search(/_multi$/) >= 0); this.type = this.isMulti ? type.substr(0, type.length - MULTI_TYPE.length) : type; } Node.prototype.isMdo = function() { return this.type === "mdo"; }; Node.prototype.getScenarioId = function() { if (this.isMdo()) { var idxscn = this.name.indexOf("_scn-"); if (idxscn === -1) { console.log("Warning: MDO Scenario not found. " + "Bad type or name for node: " + JSON.stringify(this)); return null; } return this.name.substr(idxscn + 1); } return null; }; function Edge(from, to, name, row, col, isMulti) { this.id = "link_" + from + "_" + to; this.name = name; this.row = row; this.col = col; this.iotype = row < col ? "in" : "out"; this.io = { fromU: (from === UID), toU: (to === UID) }; this.isMulti = isMulti; } Edge.prototype.isIO = function() { return this.io.fromU || this.io.toU; }; function Graph(mdo, refname) { this.nodes = [new Node(UID, UID, "user")]; this.edges = []; this.chains = []; this.refname = refname || ""; this._newNodeCount = 0; var numbering = Graph.number(mdo.workflow); var numPrefixes = numbering.toNum; this.nodesByStep = numbering.toNode; mdo.nodes.forEach(function(item) { var num = numPrefixes[item.id]; this.nodes.push(new Node(item.id, num ? num + ":" + item.name : item.name, item.type)); }, this); mdo.edges.forEach(function(item) { var idA = this.idxOf(item.from); var idB = this.idxOf(item.to); var isMulti = this.nodes[idA].isMulti || this.nodes[idB].isMulti; this.edges.push(new Edge(item.from, item.to, item.name, idA, idB, isMulti)); }, this); var echain = Graph.expand(mdo.workflow); echain.forEach(function(leafChain) { if (leafChain.length < 2) { throw new Error("Bad process chain (" + leafChain.length + "elt)"); } else { this.chains.push([]); var ids = this.nodes.map(function(elt) { return elt.id; }); leafChain.forEach(function(item, j) { if (j !== 0) { var idA = ids.indexOf(leafChain[j - 1]); if (idA < 0) { throw new Error("Process chain element (" + leafChain[j - 1] + ") not found"); } var idB = ids.indexOf(leafChain[j]); if (idB < 0) { throw new Error("Process chain element (" + leafChain[j] + ") not found"); } if (idA !== idB) { this.chains[this.chains.length - 1].push([idA, idB]); } } }, this); } }, this); } Graph.prototype.idxOf = function(nodeId) { return this.nodes.map(function(elt) { return elt.id; }).indexOf(nodeId); }; Graph.prototype.getNode = function(nodeId) { var theNode; this.nodes.forEach(function(node) { if (node.id === nodeId) { theNode = node; } }, this); return theNode; }; Graph.prototype.addNode = function(nodeName) { this._newNodeCount += 1; this.nodes.push( new Node("NewNode" + this._newNodeCount, nodeName, "analysis")); }; Graph.prototype.removeNode = function(index) { var self = this; // Update edges var edges = this.findEdgesOf(index); edges.toRemove.forEach(function(edge) { var idx = self.edges.indexOf(edge); if (idx > -1) { self.edges.splice(idx, 1); } }, this); edges.toShift.forEach(function(edge) { if (edge.row > 1) { edge.row -= 1; } if (edge.col > 1) { edge.col -= 1; } }, this); // Update nodes this.nodes.splice(index, 1); }; Graph.prototype.findEdgesOf = function(nodeIdx) { var toRemove = []; var toShift = []; this.edges.forEach(function(edge) { if ((edge.row === nodeIdx) || (edge.col === nodeIdx)) { toRemove.push(edge); } else if ((edge.row > nodeIdx) || (edge.col > nodeIdx)) { toShift.push(edge); } }, this); return {toRemove: toRemove, toShift: toShift}; }; function _expand(workflow) { var ret = []; var prev; workflow.forEach(function(item) { if (item instanceof Array) { if (item[0].hasOwnProperty('parallel')) { if (prev) { ret = ret.slice(0, ret.length - 1).concat(item[0].parallel.map( function(elt) { return [prev].concat(_expand([elt]), prev); })); } else { throw new Error("Bad workflow structure : " + "cannot parallel loop without previous starting point."); } } else if (prev) { ret = ret.concat(_expand(item), prev); } else { ret = ret.concat(_expand(item)); } prev = ret[ret.length - 1]; } else if (item.hasOwnProperty('parallel')) { if (prev) { ret = ret.slice(0, ret.length - 1).concat( item.parallel.map(function(elt) { return [prev].concat(_expand([elt])); })); } else { ret = ret.concat(item.parallel.map( function(elt) { return _expand([elt]); })); } prev = undefined; } else { var i = ret.length - 1; var flagParallel = false; while (i >= 0 && (ret[i] instanceof Array)) { ret[i] = ret[i].concat(item); i -= 1; flagParallel = true; } if (!flagParallel) { ret.push(item); } prev = item; } }, this); return ret; } Graph._isPatchNeeded = function(toBePatched) { var lastElts = toBePatched.map(function(arr) { return arr[arr.length - 1]; }); var lastElt = lastElts[0]; for (var i = 0; i < lastElts.length; i++) { if (lastElts[i] !== lastElt) { return true; } } return false; }; Graph._patchParallel = function(expanded) { var toBePatched = []; expanded.forEach(function(elt) { if (elt instanceof Array) { toBePatched.push(elt); } else if (Graph._isPatchNeeded(toBePatched)) { toBePatched.forEach(function(arr) { arr.push(elt); }, this); } }, this); }; Graph.expand = function(item) { var expanded = _expand(item); var result = []; var current = []; // first pass to add missing 'end link' in case of parallel branches at the end of a loop // [a, [b, d], [b, c], a] -> [a, [b, d, a], [b, c, a], a] Graph._patchParallel(expanded); // [a, aa, [b, c], d] -> [[a, aa, b], [b,c], [c, d]] expanded.forEach(function(elt) { if (elt instanceof Array) { if (current.length > 0) { current.push(elt[0]); result.push(current); current = []; } result.push(elt); } else { if (result.length > 0 && current.length === 0) { var lastChain = result[result.length - 1]; var lastElt = lastChain[lastChain.length - 1]; current.push(lastElt); } current.push(elt); } }, this); if (current.length > 0) { result.push(current); } return result; }; Graph.number = function(workflow, num) { num = (typeof num === 'undefined') ? 0 : num; var toNum = {}; var toNode = []; function setStep(step, nodeId) { if (step in toNode) { toNode[step].push(nodeId); } else { toNode[step] = [nodeId]; } } function setNum(nodeId, beg, end) { if (end === undefined) { num = String(beg); setStep(beg, nodeId); } else { num = end + "-" + beg; setStep(end, nodeId); } if (nodeId in toNum) { toNum[nodeId] += "," + num; } else { toNum[nodeId] = num; } } function _number(wks, num) { var ret = 0; if (wks instanceof Array) { if (wks.length === 0) { ret = num; } else if (wks.length === 1) { ret = _number(wks[0], num); } else { var head = wks[0]; var tail = wks.slice(1); var beg = _number(head, num); if (tail[0] instanceof Array) { var end = _number(tail[0], beg); setNum(head, beg, end); beg = end + 1; tail.shift(); } ret = _number(tail, beg); } } else if ((wks instanceof Object) && 'parallel' in wks) { var nums = wks.parallel.map(function(branch) { return _number(branch, num); }); ret = Math.max.apply(null, nums); } else { setNum(wks, num); ret = num + 1; } return ret; } _number(workflow, num); // console.log('toNodes=', JSON.stringify(toNode)); // console.log('toNum=',JSON.stringify(toNum)); return {toNum: toNum, toNode: toNode}; }; module.exports = Graph;
true
85f177b6bfe985ce132b2d6921e4aa6ab8dd7b1e
JavaScript
sarahsponda902/volunteervoice
/public/javascripts/pagination.js
UTF-8
392
2.546875
3
[]
no_license
$( function(){ //constantly looks for click changes to dom $(".pagination a").live("click",function() { $(".pagination").html("Page is loading...")//loading message $.get(this.href, null, null, "script");// says that any script returned by ajax request should be executed return false; // so that the actual link will not be triggered }); });
true
3bf154a9847a554104c3528f976979240cfc9ee8
JavaScript
ecodolphin/i8254-Emulator
/Sources/JS/main.js
UTF-8
1,702
2.75
3
[]
no_license
$(document).ready(function() { init(); welcome(); //test(); }); // Interaction. var rwl = []; var dbf = []; var cwr = []; // Channels. var channels = []; var generator = []; // Features. var assemblerer = []; var tasker = []; function init() { rwl = new RWL(); dbf = new DBF(); cwr = new CWR(); channels.push(new Channel(0, '#channel0')); channels.push(new Channel(1, '#channel1')); channels.push(new Channel(2, '#channel2')); generator = new Generator(); tasker = new Tasker(); assemblerer = new Assemblerer(); } function welcome() { alert(makeGreeting()); } function makeGreeting() { var greeting = ""; greeting += "Добро пожаловать!\r\n"; greeting += "Для комфортной работы, перейдите в полноэкранный режим (F11).\r\n"; return greeting; } function test() { channels[0].setChannelStatus(new ChannelStatus("00010101")); channels[0].setByte("01000100"); channels[1].setChannelStatus(new ChannelStatus("01010011")); channels[1].setByte("10010100"); channels[2].setChannelStatus(new ChannelStatus("10011010")); channels[2].setByte("00100101"); generator.setPeriod(1000); setupAssProgram(); } function setupAssProgram() { var assProgram = ""; assProgram += "mov bl, 00010001b\r\n"; assProgram += "mov al, bl\r\n"; assProgram += "out 43h, al\r\n"; assProgram += "mov cx, AF45h\r\n"; assProgram += "mov ax, cx\r\n"; assProgram += "out 40h, al\r\n"; assProgram += "mov dh, 194\r\n"; assProgram += "mov al, dh\r\n"; assProgram += "out 43h, al\r\n"; assProgram += "in al, 40h"; assemblerer.setLines(assProgram); }
true
a3879f7f51ada7d590b4e27893a5b3c9b245c434
JavaScript
estebandh/misy350-s18-exercises
/4-5-18/my-code.js
UTF-8
198
2.984375
3
[ "MIT" ]
permissive
blist = ["end of semester", "blah blah", "blah blah blah"]; console.log(blist.length); blist.push("more blahs"); console.log(blist); for (i = 0; i < blist.length; i++) { console.log(blist[i]); }
true
fa5ea9bed203d5ca0889aae7cd5b2f23ef202597
JavaScript
sandeep2007/floating-emoji
/app.js
UTF-8
270
2.71875
3
[]
no_license
emojiArray = ['😀', '🥳', '😜', '❤️']; function pushEmoji() { $('.em-container').append(`<span class="em-node-${(Math.floor(Math.random() * 5) + 1)}">${emojiArray[(Math.floor(Math.random() * 3) + 1)]}</span>`) } setInterval(() => { pushEmoji() }, 200);
true
cec4ec4f40c6045b1cc8939c384a8165dc27db94
JavaScript
5ervant/usamadaniyalxen.github.io
/envato/themeforest/aline/javascript/infiniteSlider.js
UTF-8
13,950
2.515625
3
[]
no_license
/* //////////////////////////////////////////////////////////////////////////// // // Infinite Slider // V 1.0 // Alexandra Nantel // Last Update 01/11/2012 10:22 // /////////////////////////////////////////////////////////////////////////// */ function InfiniteSlider(wrapper, speed, duration, mode, easing, hover, animation) { var _infiniteSlider = this; // If true : running this.animated = false; // Autorotation this.hover = hover; this.autorotation = animation; this.running = true; this.t; // Setting the container and controller this.wrapper = $(wrapper); this.container = $('.slider', this.wrapper); this.arrows = $('.slider-arrows', this.wrapper); this.count = $('.count .numbers', this.arrows); this.controls = $('.slider-controls', this.wrapper); this.infos = $('.slider-infos', this.wrapper); this.speed = speed; this.duration = duration; this.mode = mode; // slide - slidev - fade - demask this.easing = easing; this.width = this.container.width(); this.height = this.container.height(); // Setting index : slide ordered index || indexSlide : slide real index this.index = 0; this.indexSlide = 0; // Number of elements this.length = $('li', this.container).length - 1; /* Initialize //////////////////////////////////////////////////////////////////////// */ // Identify each slide and control with initial order $('> ul > li', this.container).each(function() { $(this).attr('data-slide', $(this).index() + 1); if ($(this).index() == 0) { $(this).addClass('active'); $(_infiniteSlider.controls).append('<li class="active" data-slide="' + ($(this).index() + 1) + '"><a href="">Slide ' + ($(this).index() + 1) + '</a></li>'); } else { $(this).addClass('inactive'); $(_infiniteSlider.controls).append('<li class="inactive" data-slide="' + ($(this).index() + 1) + '"><a href="">Slide ' + ($(this).index() + 1) + '</a></li>'); } }); $('li', this.controls).each(function() { $(this).attr('data-slide', $(this).index() + 1); if ($(this).index() == 0) $(this).addClass('active'); else $(this).addClass('inactive'); }); // Fill Count values if (this.index < 10) $(this.count).html('0' + (this.index + 1) + ' / ' + (this.length + 1)); else $(this.count).html((this.index + 1) + ' / ' + (this.length + 1)); // Fill First Infos if ($('> ul > li:eq(0)', this.container).attr('data-infos') != '') $(this.infos).html($('> ul > li:eq(0)', this.container).attr('data-infos')); // Disable if just one slide if (this.length == 0) { $(this.controls).hide(); this.autorotation = false; } // Initiate Positioning this.reset(_infiniteSlider); // Bind if (this.hover) { $(this.wrapper).mouseenter(function() { _infiniteSlider.stop(_infiniteSlider); }); $(this.wrapper).mouseleave(function() { _infiniteSlider.start(_infiniteSlider); }); } $('li a', this.controls).click(function() { _infiniteSlider.controlsClick($(this), _infiniteSlider); return false; }); $('li a', this.arrows).click(function() { _infiniteSlider.arrowsClick($(this), _infiniteSlider); return false; }); $(window).resize(function() { _infiniteSlider.reset(_infiniteSlider); }); // Start Autorotation if (this.running) this.autoRotation(_infiniteSlider); if (_infiniteSlider.mode == 'slidev') _infiniteSlider.container.height($('> ul > li', _infiniteSlider.container).eq(0).height()); } /* //////////////////////////////////////////////////////////////////////////// // // Autorotation // /////////////////////////////////////////////////////////////////////////// */ InfiniteSlider.prototype.autoRotation = function(_infiniteSlider) { clearTimeout(_infiniteSlider.t); if ($('li', _infiniteSlider.controls).length > 1 && _infiniteSlider.autorotation) { if (_infiniteSlider.running) { _infiniteSlider.t = setTimeout(function() { _infiniteSlider.changeSlide(_infiniteSlider.indexSlide, _infiniteSlider.indexSlide + 1, _infiniteSlider) }, _infiniteSlider.duration); } } } /* //////////////////////////////////////////////////////////////////////////// // // External Functions // /////////////////////////////////////////////////////////////////////////// */ InfiniteSlider.prototype.start = function(_infiniteSlider) { _infiniteSlider.running = true; _infiniteSlider.autoRotation(_infiniteSlider); return false; } InfiniteSlider.prototype.stop = function(_infiniteSlider) { clearTimeout(_infiniteSlider.t); _infiniteSlider.running = false; return false; } InfiniteSlider.prototype.arrowsClick = function(object, _infiniteSlider) { if (!_infiniteSlider.animated) { _infiniteSlider.autorotation = false; // Stop timer clearTimeout(_infiniteSlider.t); if ($(object).parent().hasClass('next')) var clicked = _infiniteSlider.indexSlide + 1; else var clicked = _infiniteSlider.indexSlide - 1; _infiniteSlider.changeSlide(_infiniteSlider.indexSlide, clicked, _infiniteSlider); } return false; } InfiniteSlider.prototype.controlsClick = function(object, _infiniteSlider) { if (!_infiniteSlider.animated && $(object).parent().hasClass('active') == false) { _infiniteSlider.autorotation = false; // Stop timer clearTimeout(_infiniteSlider.t); var clicked = $(object).parent().index(); $('> ul > li', _infiniteSlider.container).each(function() { if ($(this).attr('data-slide') == clicked + 1) { _infiniteSlider.changeSlide(_infiniteSlider.indexSlide, $(this).index(), _infiniteSlider); } }); } return false; } InfiniteSlider.prototype.reset = function(_infiniteSlider) { if (!_infiniteSlider.animated) { _infiniteSlider.stop(_infiniteSlider); _infiniteSlider.width = _infiniteSlider.container.width(); _infiniteSlider.height = _infiniteSlider.container.height(); $(_infiniteSlider.infos).css('top', ($(_infiniteSlider.container).height() / 2 - $(_infiniteSlider.infos).height() / 2) + 'px'); if (_infiniteSlider.mode == 'slidev') _infiniteSlider.container.height($('> ul > li', _infiniteSlider.container).eq(_infiniteSlider.indexSlide).height()); _infiniteSlider.start(_infiniteSlider); } } /* //////////////////////////////////////////////////////////////////////////// // // Change slide // /////////////////////////////////////////////////////////////////////////// */ InfiniteSlider.prototype.changeSlide = function(current, clicked, _infiniteSlider) { _infiniteSlider.animated = true; var direction = 'next'; if (clicked < current) direction = 'previous'; // Check limits if (clicked > _infiniteSlider.length) { clicked = 0; } else if (clicked < 0) { clicked = _infiniteSlider.length; } // Redefine active slide $('> ul > li', _infiniteSlider.container).removeClass('active').addClass('inactive'); $('> ul > li', _infiniteSlider.container).eq(clicked).removeClass('inactive').addClass('active'); if (_infiniteSlider.mode == 'slidev') _infiniteSlider.container.height($('> ul > li', _infiniteSlider.container).eq(clicked).height()); _infiniteSlider.index = parseInt($('> ul > li.active', _infiniteSlider.container).attr('data-slide')) - 1; _infiniteSlider.indexSlide = $('> ul > li.active', _infiniteSlider.container).index(); // Redefine active control $('li', _infiniteSlider.controls).removeClass('active'); $('li', _infiniteSlider.controls).eq(_infiniteSlider.index).addClass('active'); // Change Count if (_infiniteSlider.index < 9) $(_infiniteSlider.count).html('0' + (_infiniteSlider.index + 1) + ' / ' + (_infiniteSlider.length + 1)); else $(_infiniteSlider.count).html((_infiniteSlider.index + 1) + ' / ' + (_infiniteSlider.length + 1)); // Animate Infos if (_infiniteSlider.wrapper.attr('id') == 'slider-container-slide' && $('#slider-container-slide .animation').length > 0) animationsRows[clicked][1].reset(); $(_infiniteSlider.infos).fadeOut(_infiniteSlider.speed / 2, function() { $('> li', _infiniteSlider.infos).hide(); $('> li', _infiniteSlider.infos).eq(clicked).show(); $(this).show().css('opacity', '0'); _infiniteSlider.reset(_infiniteSlider); $(this).animate({ opacity: 1 }, _infiniteSlider.speed / 2, function() { if (_infiniteSlider.wrapper.attr('id') == 'slider-container-slide' && $('#slider-container-slide .animation').length > 0) animationsRows[clicked][1].start(parseInt($('#' + animationsRows[clicked][0]).attr('data-nb-frames')) - 1); }); }); // Animate Slides if (_infiniteSlider.mode == 'slide') { // Place new slide AFTER if (direction == 'next') { $('> ul > li', _infiniteSlider.container).eq(clicked) .css('left', _infiniteSlider.width + 'px') .show(); // Animate slides $('> ul > li', _infiniteSlider.container).animate({ left: '-=' + _infiniteSlider.width }, { 'duration': _infiniteSlider.speed, easing: _infiniteSlider.easing, 'complete': function() { _infiniteSlider.animated = false; $('> ul > li.inactive', _infiniteSlider.container).hide(); if (_infiniteSlider.running) _infiniteSlider.autoRotation(_infiniteSlider); } }); } // Place new slide BEFORE else { $('> ul > li', _infiniteSlider.container).eq(clicked) .css('left', -_infiniteSlider.width + 'px') .show(); // Animate slides $('> ul > li', _infiniteSlider.container).animate({ left: '+=' + _infiniteSlider.width }, { 'duration': _infiniteSlider.speed, easing: _infiniteSlider.easing, 'complete': function() { _infiniteSlider.animated = false; $('> ul > li.inactive', _infiniteSlider.container).hide(); if (_infiniteSlider.running) _infiniteSlider.autoRotation(_infiniteSlider); } }); } } else if (_infiniteSlider.mode == 'slidev') { // Place new slide AFTER if (direction == 'next') { $('> ul > li', _infiniteSlider.container).eq(clicked) .css('top', '150%'); // Animate slides $('> ul > li', _infiniteSlider.container).eq(current).animate({ top: '-150%' }, { 'duration': _infiniteSlider.speed, easing: _infiniteSlider.easing, 'complete': function() { _infiniteSlider.animated = false; if (_infiniteSlider.running) _infiniteSlider.autoRotation(_infiniteSlider); } }); $('> ul > li', _infiniteSlider.container).eq(clicked).animate({ top: 0 }, { 'duration': _infiniteSlider.speed, easing: _infiniteSlider.easing }); } // Place new slide BEFORE else { $('> ul > li', _infiniteSlider.container).eq(clicked) .css('top', '-150%'); // Animate slides $('> ul > li', _infiniteSlider.container).eq(current).animate({ top: '150%' }, { 'duration': _infiniteSlider.speed, easing: _infiniteSlider.easing, 'complete': function() { _infiniteSlider.animated = false; if (_infiniteSlider.running) _infiniteSlider.autoRotation(_infiniteSlider); } }); $('> ul > li', _infiniteSlider.container).eq(clicked).animate({ top: 0 }, { 'duration': _infiniteSlider.speed, easing: _infiniteSlider.easing }); } } else if (_infiniteSlider.mode == 'fade') { // Animate Slides $('> ul > li.active', _infiniteSlider.container).fadeIn(_infiniteSlider.speed, function() { $('> ul > li', _infiniteSlider.container).eq(current).hide(); _infiniteSlider.animated = false; if (_infiniteSlider.running) _infiniteSlider.autoRotation(_infiniteSlider); }); } else if (_infiniteSlider.mode == 'demask') { $('> ul > li.active', _infiniteSlider.container).animate({ width: _infiniteSlider.width }, _infiniteSlider.speed, _infiniteSlider.easing, function() { $('> ul > li.inactive', _infiniteSlider.container).width(0); _infiniteSlider.animated = false; if (_infiniteSlider.running) _infiniteSlider.autoRotation(_infiniteSlider); }); } else if (_infiniteSlider.mode == 'columns') { $('> ul > li', _infiniteSlider.container).eq(clicked).css('left', '0'); $('> ul > li', _infiniteSlider.container).eq(current).find('.columns > li > div').animate({ width: 0 }, _infiniteSlider.speed, _infiniteSlider.easing, function() { $('> ul > li', _infiniteSlider.container).eq(current).css('left', '100%'); $('> ul > li', _infiniteSlider.container).eq(current).find('.columns > li > div').width('100%'); _infiniteSlider.animated = false; if (_infiniteSlider.running) _infiniteSlider.autoRotation(_infiniteSlider); }); } }
true
7d0d2cc898d5ee76c70cd032389789945171d9cd
JavaScript
silverjosh90/airController
/js/logic.js
UTF-8
946
3.375
3
[]
no_license
var cost = 0; function finalCost() { cityVal(); seatVal(); wifiVal(); bagVal(); discountVal(); total.innerHTML = '\$' + cost; cost = 0 } function cityVal() { var cityChoice = Number(departures.value) + Number(arrivals.value) switch (cityChoice) { case 3.0: cost += 250; break; case 3.1: cost += 545 case 2.5: cost += 350 break; } } function seatVal() { switch (Number(seating.value)) { case 1: cost += 200 break; case 2: cost += 500 break; } } function wifiVal() { if (wifi.checked == true) { cost += 12 } } function bagVal() { var bagFee = Number(bags.value) * 25 cost += bagFee } function discountVal() { var discountCode = (discount.value) switch (discountCode) { case 'g18': cost -= 100 break; case 'g15': cost += 5000 } } function formReset() { cost = 0; total.innerHTML = '\$' + cost; }
true
a4f64c3b9d48f3d71191cb854b7607e2296f9a31
JavaScript
kunalbhoria/quick-notes.github.io
/app2.js
UTF-8
10,365
2.921875
3
[]
no_license
// let newBtn = document.querySelector('#newbtn'); // let saveBtn = document.querySelector('#savebtn'); // let deleteBtn = document.querySelector('#deletebtn'); // let textBox = document.querySelector('#textBox'); // let noteBox = document.querySelector('#noteBox'); // let h = document.querySelectorAll('h4') // let aside = document.querySelector('aside') // let activeNote=0; // const files =[] // let k ={ // title : `file${files.length + 1}`, // notes : "", // isSave:false, // id: `${files.length + 1}`, // isnotes:false, // isNew:true, // selected:true // } // files.unshift(k); // let hf=document.createElement('h4'); // hf.innerText = files[files.length-1].title // hf.id=files[files.length-1].title // let fileList = [] // fileList.push(hf) // function fileUpdate(){ // for(let k of fileList){ // aside.append(k) // } // } // function newh4(){ // let hf=document.createElement('h4'); // hf.innerText = files[files.length-1].title // hf.id=files[files.length-1].title // fileList.unshift(hf) // } // let save =(num)=>{ // let n = noteBox.innerText // files[num].isnotes = checkIsNote(n); // if(files[num].isNew){ // if(files[num].isnotes){ // files[num].notes = noteBox.innerText; // files[num].isSave= true; // files[num].isNew= false; // } // else{ // alert("you have not written any note !") // }} // else{ // files[num].notes = noteBox.innerText; // files[num].isSave= true;} // } // function checkIsNote(n){ // let m = n.trim(); // let char = m.length; // if(char==0){ // return false; // } // else{ // return true; // } // } // fileUpdate(); // saveBtn.addEventListener('click',function(){ // save(activeNote); // updateclass() // }) // textBox.addEventListener('input',function(){ // noteBox.innerText= textBox.value ; // files[activeNote].isSave=false; // // fileList[0].notes=noteBox.innerText; // }) // function updateclass(){ // let h = document.querySelectorAll('h4') // for(let h4btn of h){ // h4btn.addEventListener('click',function(){ // h4btn.classList.add("selected") // let activeh = h4btn.innerText; // active(activeh); // textBox.value=files[activeNote].notes // }) // } // } // updateclass() // // new file // newBtn.addEventListener('click',function(){ // if(files[files.length-1].isSave){ // let nk = { // title : `file${files.length + 1}`, // notes : "", // isSave:false, // id: `${files.length + 1}`, // isnotes:false, // isNew:true, // selected:true } // activeNote=files.length; // files.push(nk) // newh4(); // fileUpdate(); // updateclass() // textBox.value=""; // noteBox.innerText=""; // } // }) // function active(j){ // for(let k of files){ // if(k.title==j){ // activeNote=files.indexOf(k); // } // } // } let newBtn = document.querySelector('#newbtn'); let saveBtn = document.querySelector('#savebtn'); let deleteBtn = document.querySelector('#deletebtn'); let textBox = document.querySelector('#textBox'); let noteBox = document.querySelector('#noteBox'); let h = document.querySelectorAll('h4') let asideDiv = document.querySelector('aside div') let nameInput = document.querySelector('#nameinput') let nameBtn = document.querySelector('#namebtn') let modeBtn = document.querySelector('#mode') let headingBtn = document.querySelector('#headingbtn') let deleteAll = document.querySelector('#deleteall') let activeNote=0; let hlBtn = document.querySelector('.btnclickeffect') let color = document.querySelector('#color') let files =[] let fileList = [] let isLocalStorage = localStorage.getItem("isLocalStorage"); let selectedList; function defaults() { createFile(); createH4(); listUpdate(); updateClass(); } if(isLocalStorage){ retriveDataFromLS(); } else{ defaults(); selectedList = fileList.length-1; newFileStyle() } selectedList = fileList.length-1; headingBtn.addEventListener('click',function(){ noteBox.innerHTML= noteBox.innerHTML +`<h2 style="text-align: center;">Heading</h2>` }) deleteAll.addEventListener('click',function(){ fileList=[] files=[] listUpdate(); localStorage.clear() }) function createFile(){ let k ={ title : `Note ${files.length + 1}`, notes : "", isSave:false, id: `Note ${files.length + 1}`, isNotes:false, isNew:true, isDeleted:false, rename:`Note ${files.length + 1}` } activeNote=files.length; files.push(k); saveToLS("files",files) } hlBtn.addEventListener('click',function(){ let m = window.getSelection() let k= m.toString(); let j = `<span style="background-color:${color.value};">${k}</span>` noteBox.innerHTML = noteBox.innerHTML.replace(m,j) }) function createH4(){ let hf=document.createElement('h4'); hf.innerText = files[files.length-1].title hf.id=files[files.length-1].id fileList.unshift(hf) } let keytime =1 noteBox.onkeyup = function(e){ if(e.keyCode == 32){ if(keytime==2){ console.log("working") noteBox.innerHTML= noteBox.innerHTML+ '&nbsp;&nbsp; ' }else{ keytime++; } setTimeout(function(){ keytime = 1 }, 200); // console.log(e) } } function listUpdate(){ asideDiv.innerHTML="" for(let file of fileList){ asideDiv.append(file) } } const save = (num)=>{ let n = noteBox.innerText files[num].isNotes = checkIsNote(n); if(files[num].isNew){ if(files[num].isNotes){ files[num].notes = noteBox.innerHTML; files[num].isSave= true; files[num].isNew= false; } else{ alert("you have not written any note !") }} else{ files[num].notes = noteBox.innerHTML; files[num].isSave= true;} } function checkIsNote(str){ let m = str.trim(); let char = m.length; if(char==0){ return false; } else{ return true; } } saveBtn.addEventListener('click',function(){ save(activeNote); updateClass() saveToLS("files",files) }) // textBox.addEventListener('input',function(){ // noteBox.innerText= textBox.value ; // files[activeNote].isSave=false; // // fileList[0].notes=noteBox.innerText; // }) function updateClass(){ h = document.querySelectorAll('h4') for(let h4btn of h){ h4btn.addEventListener('click',function(){ for(let hbtn of h){ hbtn.classList.remove("selected") } h4btn.classList.add("selected") let activeh = h4btn.id; active(activeh); //textBox.value=files[activeNote].notes noteBox.innerHTML=files[activeNote].notes selectedFile(); nameInput.value=fileList[selectedList].innerText }) } } function newFileStyle(){ // selectedFile(); //errror for(let hbtn of h){ hbtn.classList.remove("selected") } fileList[0].classList.add("selected") nameInput.value=fileList[0].innerText let a = fileList[selectedList].id active(a) //textBox.value=files[activeNote].notes noteBox.innerHTML=files[activeNote].notes } function selectedFile(){ selectedList = fileList.length - (activeNote + 1) } // delete -------------------------------------------------------------------- deleteBtn.addEventListener('click',deletes); function deletes(){ selectedFile(); fileList.splice(selectedList,1); files[activeNote].isSave=true files[activeNote].isDeleted = true listUpdate(); selectedList=0 newFileStyle(); saveToLS("files",files) } // new file newBtn.addEventListener('click',function(){ if(files.length==0){ defaults(); selectedList = fileList.length-1; newFileStyle() }else{ if(files[files.length-1].isSave){ createFile(); createH4(); listUpdate(); updateClass(); newFileStyle(); textBox.value=""; noteBox.innerText=""; } else{ alert(`You have not saved ${fileList[0].innerText} yet !!!`) } } }) function active(j){ for(let k of files){ if(k.id==j){ activeNote=files.indexOf(k); } } } // rename ----------- rename nameBtn.addEventListener('click',function(){ fileList[selectedList].innerText=nameInput.value; files[activeNote].rename=nameInput.value; }) // modeBtn.addEventListener('click',function(){ // //textBox.style.display="none" // textBox.classList.toggle("hidden") // noteBox.classList.toggle("pSize") // let c = textBox.className // if(c=="hidden"){ // modeBtn.innerText="Edit mode" // } // else{ // modeBtn.innerText="Read only mode" // } // }) function saveToLS(fileName , fileData){ let s = JSON.stringify(fileData) localStorage.setItem(fileName,s) localStorage.setItem("isLocalStorage",true) } function retriveDataFromLS(){ let unparsefiles = localStorage.getItem("files") files = JSON.parse(unparsefiles) makeFileList(); listUpdate(); updateClass(); selectedList = fileList.length-1; newFileStyle(); activeNote=files.length-1; noteBox.innerHTML=files[activeNote].notes; } function makeFileList(){ for(let f of files){ k = f.isDeleted; if(!k){ let hf=document.createElement('h4'); hf.innerText = f.rename; hf.id=f.id fileList.unshift(hf) } } }
true
2c28e6328792c96fc7b878f45992088caa99e7f2
JavaScript
chaitanyaGitHub1/The-Roar
/index.js
UTF-8
5,200
2.515625
3
[]
no_license
// Importing required node modules var http = require('http'); const request = require('request'); const cheerio = require('cheerio'); const path = require('path'); var fs = require('fs'); const shell = require('shelljs'); const https = require('https'); var cron = require('node-cron'); const express = require('express'); require('dotenv').config(); // const mongoose = require('mongoose'); // const { exec } = require("child_process"); const app = express(); const port = process.env.PORT; const api_key = process.env.API_KEY; const mobile_numbers = process.env.MOBILE_NUMBERS console.log(mobile_numbers); app.listen(port, () => console.log(`Example app listening on port ${port}!`)) // Running temp file manually // Writing to Temp file only once // tempFile(); // function tempFile() { // f = "tempF.txt"; // deleteFile(f); // scrape(f); // } // diff(); // getFinalLinks(); // swapFile(); // Run the application for every 5 minutes cron.schedule('*/2 * * * *', () => { var time = Date.now(); console.log(time); console.log('running a task every 2 minutes'); mainFile(); }); // // Writing to main file // mainFile(); function mainFile() { f = "mainF.txt" deleteFile(f); // scrape(f); // diff(); // getFinalLinks(); // swapFile(); } // delete the file function deleteFile(f) { try { if (fs.existsSync('mainF.txt')) { console.log("The file exists."); file = f; console.log(f); filePath = path.join(__dirname + "/mainF.txt"); console.log(filePath); fs.unlink(filePath, function (err) { if (err) return console.log(err); else scrape(f); console.log('file deleted successfully'); }); } else { console.log('The file does not exist.'); scrape(f); } } catch (err) { console.error(err); } } // emptyMainF(); // // Swap the file main to temp // function emptyMainF() { // shell.exec('bash ./emptyMainF.sh'); // } // Function to scrape the urls from sitemap function scrape(f) { request('https://www.theroar.com.au/sitemap-posttype-video.xml', (error, response, html) => { if (!error && response.statusCode == 200) { const $ = cheerio.load(html); const url = $('url'); // console.log(url); url.each((i, el) => { var game = "cricket"; const item = $(el).text(); if (i = item.match(game)) { // console.log(item) const loc = $(el).children('loc').text() + '\r\n'; // const lastMod = $(el).children('lastMod').text(); // console.log("URL: ", loc," Time stamp: ",lastMod); fs.appendFile( path.join(__dirname, '/', f), loc, err => { if (err) throw err; else shell.exec('bash ./diff.sh'); } ); } }); console.log('File written to...'); getFinalLinks(); } }); } // compare two files // function diff() { // shell.exec('bash ./diff.sh'); // } // Get the links from the diff.txt function getFinalLinks() { var fs = require('fs'); fs.readFile(process.cwd() + "/diff.txt", function (err, data) { if (err) console.log(err) else console.log(data.toString()); var links = data.toString(); sendNotification(links); }); } function sendNotification(links) { console.log("The Final links : " + links); if (links !== "") { var arr = links.split("\n"); var f_links = []; for (let i = 0; i < (arr.length - 1); i++) { var n = i+1; f_links.push(" link " + n + ": "+ arr[i] + "\n"); } // console.log("f_links : ", f_links); https.get(`https://manage.ibulksms.in/api/sendhttp.php?authkey=${api_key}&mobiles=${mobile_numbers}&message=${f_links}&sender=CRICSL&route=4&country=91`, (resp) => { let data = ''; // A chunk of data has been received. resp.on('data', (chunk) => { data += chunk; }); // The whole response has been received. Print out the result. resp.on('end', () => { console.log(data); shell.exec('bash ./swap.sh'); }); }).on("error", (err) => { console.log("Error: " + err.message); }); } else { console.log("No new links found"); } } // Swap the file main to temp // function swapFile() { // shell.exec('bash ./swap.sh'); // } // Semi-Swap process // Delete all the content in the temp file - [ Empty the Temp file ] // Move the contents from the main file to temp file // Delete all the contents from the main file - [ Empty the Main file ] // Never put the tempF file empty // always check empty mainF.txt is placed in the directory
true
2c77bb439456ae2b964dbb8b54c44b15fc3c4dac
JavaScript
bonbj/30DayChallengeJavaScript.github.io
/18-ReduceWithDiv/script.js
UTF-8
806
3.265625
3
[]
no_license
//data time of videos let timeNodes = Array.from(document.querySelectorAll("[data-time]")); //total time const seconds = timeNodes .map(node => node.dataset.time) .map(timeCode => { const [mins, secs] = timeCode.split(":").map(parseFloat); return mins * 60 + secs; }) .reduce((total, vidSeconds) => total + vidSeconds); //hours let secondsLeft = seconds; const hours = Math.floor(secondsLeft / 3600); secondsLeft = secondsLeft % 3600; //minutes const mins = Math.floor(secondsLeft / 60); //seconds secondsLeft = secondsLeft % 60; //show total time on screen const videos = document.querySelector('.videos'); videos.innerHTML = `<li>total time : ${hours}:${mins}:${secondsLeft}</li>`; //show time and div in console console.log(hours, mins, secondsLeft); console.table(timeNodes);
true
ec5e6bfa8e1d2a19ff4a9e3b7129d8b1c7df6f0f
JavaScript
Grumlen/Exercises-Java
/Eloquent/Ch10/months.js
UTF-8
396
4.0625
4
[]
no_license
// Your code here. var month = function () { var months = ["January","February","March","April","May","June","July","August","September","October","November","December"]; return { name: function (number) {return months[number];}, number: function (name) {return months.indexOf(name);} } }(); console.log(month.name(2)); // → March console.log(month.number("November")); // → 10
true
d0cd381ba3d3732627c2159199691fb96819a925
JavaScript
CarmenGarduno09/expedientes
/assets/js/comparar_val_jur.js
UTF-8
6,772
2.78125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
//Comparación 1 function obtener_informacion_mes(selectobject){ var mes = selectobject.value; //alert ('estoy en info mes '); var id_expediente= $.trim($('#id_exp').val()); var anio = $.trim($("#year").val()); if(anio.length == ""){ alert ('por favor elije un año y después el mes.'); }else{ //alert (mes + id_expediente); //alert ('Ha elegido un año'); traer_planes(mes,id_expediente); traer_acuerdos(mes,id_expediente); traer_personas(mes,id_expediente); } } function traer_planes(mes,id_expediente){ //alert(mes+id_expediente); //alert('estoy trayendo planes'); var anio = $.trim($("#year").val()); //alert(anio); $.ajax({ type:"POST", url : base_url+'Proyecto/traerplanes', data:({mes_tx:mes,id:id_expediente,anio:anio}), cache:false, dataType:"json", success:mostrarPlanes, error:function(){ alert('No puedo traer datos'); } }); function mostrarPlanes(data){ //alert('estoy eN funcion mostar planes'); $("#plan").empty(); $("#plan").append('<ul >'); $(data).each(function(index,data){ if(data.estado=="success"){ $("#plan").append('<li class="list-group-item">'+data.v2+'</li>'); } }); $("#plan").append('</ul>'); $("#plan").trigger('create'); } }//Fin de función traer planes function traer_acuerdos(mes,id_expediente){ var anio = $.trim($("#year").val()); //alert('estoy en acuerdos'+mes+id_expediente); $.ajax({ type:"POST", url : base_url+'Proyecto/traeracuerdos', data:({mes_tx:mes,id_tx:id_expediente,anio:anio}), cache:false, dataType:"json", success:mostrarAcuerdos, error:function(){ alert('No se pudieron traer los datos'); } }); function mostrarAcuerdos(data){ //alert('estoy e funcion mostar acuerdos'); $("#acuerdo").empty(); $("#acuerdo").append('<ul>'); $(data).each(function(index,data){ if(data.estado=="success"){ $("#acuerdo").append('<li class="list-group-item">'+data.v2+'</li>'); } }); $("#acuerdo").append('</ul>'); $("#acuerdo").trigger('create'); } }//Fin de función traer acuerdos. function traer_personas(mes,id_expediente){ var anio = $.trim($("#year").val()); //alert('estoy en acuerdos'+mes+id_expediente); $.ajax({ type:"POST", url : base_url+'Proyecto/traerpersonas', data:({mes_tx:mes,id_tx:id_expediente,anio:anio}), cache:false, dataType:"json", success:mostrarPersonas, error:function(){ alert('No se pudieron traer los datos'); } }); function mostrarPersonas(data){ //alert('estoy e funcion mostar acuerdos'); $("#persona").empty(); $("#persona").append('<ul>'); $(data).each(function(index,data){ if(data.estado=="success"){ $("#persona").append('<li class="list-group-item">'+data.v2+'</li>'); } }); $("#persona").append('</ul>'); $("#persona").trigger('create'); } }//Fin de función traer personas. //Carga de datos 2 //Comparación 1 function obtener_informacion_mes2(selectobject){ var mes = selectobject.value; var anio = $.trim($("#year").val()); //alert (mes); var id_expediente= $.trim($('#id_exp').val()); //alert (mes + id_expediente); if(anio.length == ""){ alert ('por favor elije un año y después el mes.'); }else{ //alert ('Si traigo año .'); traer_planes2(mes,id_expediente); traer_acuerdos2(mes,id_expediente); traer_personas2(mes,id_expediente); } } function traer_planes2(mes,id_expediente){ var anio = $.trim($("#year").val()); //alert(mes+id_expediente); //alert(anio); $.ajax({ type:"POST", url : base_url+'Proyecto/traerplanes', data:({mes_tx:mes,id:id_expediente,anio:anio}), cache:false, dataType:"json", success:mostrarPlanes2, error:function(){ alert('Vale madre hubo un error'); } }); function mostrarPlanes2(data){ //alert('estoy e funcion mostar planes 2'); $("#plan2").empty(); $("#plan2").append('<ul>'); $(data).each(function(index,data){ if(data.estado=="success"){ $("#plan2").append('<li class="list-group-item">'+data.v2+'</li>'); } }); $("#plan2").append('</ul>'); $("#plan2").trigger('create'); } }//Fin de función traer planes function traer_acuerdos2(mes,id_expediente){ var anio = $.trim($("#year").val()); //alert('estoy en acuerdos'+mes+id_expediente); $.ajax({ type:"POST", url : base_url+'Proyecto/traeracuerdos', data:({mes_tx:mes,id_tx:id_expediente,anio:anio}), cache:false, dataType:"json", success:mostrarAcuerdos2, error:function(){ alert('Vale madre hubo un error'); } }); function mostrarAcuerdos2(data){ //alert('estoy e funcion mostar acuerdos'); $("#acuerdo2").empty(); $("#acuerdo2").append('<ul>'); $(data).each(function(index,data){ if(data.estado=="success"){ $("#acuerdo2").append('<li class="list-group-item">'+data.v2+'</li>'); } }); $("#acuerdo2").append('</ul>'); $("#acuerdo2").trigger('create'); } }//Fin de función traer acuerdos. function traer_personas2(mes,id_expediente){ var anio = $.trim($("#year").val()); //alert('estoy en acuerdos'+mes+id_expediente); $.ajax({ type:"POST", url : base_url+'Proyecto/traerpersonas', data:({mes_tx:mes,id_tx:id_expediente,anio:anio}), cache:false, dataType:"json", success:mostrarPersonas2, error:function(){ alert('Vale madre hubo un error'); } }); function mostrarPersonas2(data){ //alert('estoy e funcion mostar acuerdos'); $("#persona2").empty(); $("#persona2").append('<ul>'); $(data).each(function(index,data){ if(data.estado=="success"){ $("#persona2").append('<li class="list-group-item">'+data.v2+'</li>'); } }); $("#persona2").append('</ul>'); $("#persona2").trigger('create'); } }//Fin de función traer personas.
true
1779a3ea802b4fae000d6f200b7536434d1488d7
JavaScript
JesusWhite97/LabSoft_Ingexis
/Interfaz/js/validaciones.js
UTF-8
4,632
3.265625
3
[]
no_license
//====================================================================================================== //Función para validar una CURP La entrada tiene que ser toda en mayusculas function curpValida(curp) { var re = /^([A-Z][AEIOUX][A-Z]{2}\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])[HM](?:AS|B[CS]|C[CLMSH]|D[FG]|G[TR]|HG|JC|M[CNS]|N[ETL]|OC|PL|Q[TR]|S[PLR]|T[CSL]|VZ|YN|ZS)[B-DF-HJ-NP-TV-Z]{3}[A-Z\d])(\d)$/, validado = curp.toUpperCase().match(re); if (!validado) //Coincide con el formato general? return false; //Validar que coincida el dígito verificador function digitoVerificador(curp17) { //Fuente https://consultas.curp.gob.mx/CurpSP/ var diccionario = "0123456789ABCDEFGHIJKLMNÑOPQRSTUVWXYZ", lngSuma = 0.0, lngDigito = 0.0; for(var i=0; i<17; i++) lngSuma = lngSuma + diccionario.indexOf(curp17.charAt(i)) * (18 - i); lngDigito = 10 - lngSuma % 10; if (lngDigito == 10) return 0; return lngDigito; } if (validado[2] != digitoVerificador(validado[1])) return false; return true; //Validado } //====================================================================================================== //Función para validar una RFC La entrada tiene que ser toda en mayusculas function validateRFC(rfc) { var patternPM = "^(([A-ZÑ&]{3})([0-9]{2})([0][13578]|[1][02])(([0][1-9]|[12][\\d])|[3][01])([A-Z0-9]{3}))|" + "(([A-ZÑ&]{3})([0-9]{2})([0][13456789]|[1][012])(([0][1-9]|[12][\\d])|[3][0])([A-Z0-9]{3}))|" + "(([A-ZÑ&]{3})([02468][048]|[13579][26])[0][2]([0][1-9]|[12][\\d])([A-Z0-9]{3}))|" + "(([A-ZÑ&]{3})([0-9]{2})[0][2]([0][1-9]|[1][0-9]|[2][0-8])([A-Z0-9]{3}))$"; var patternPF = "^(([A-ZÑ&]{4})([0-9]{2})([0][13578]|[1][02])(([0][1-9]|[12][\\d])|[3][01])([A-Z0-9]{3}))|" + "(([A-ZÑ&]{4})([0-9]{2})([0][13456789]|[1][012])(([0][1-9]|[12][\\d])|[3][0])([A-Z0-9]{3}))|" + "(([A-ZÑ&]{4})([02468][048]|[13579][26])[0][2]([0][1-9]|[12][\\d])([A-Z0-9]{3}))|" + "(([A-ZÑ&]{4})([0-9]{2})[0][2]([0][1-9]|[1][0-9]|[2][0-8])([A-Z0-9]{3}))$"; if (rfc.toUpperCase().match(patternPM) || rfc.toUpperCase().match(patternPF)) { return true; } else { // alert("La estructura de la clave de RFC es incorrecta."); return false; } } //====================================================================================================== function validaCorreoValido(correo){ emailRegex = /^[-\w.%+]{1,64}@(?:[A-Z0-9-]{1,63}\.){1,125}[A-Z]{2,63}$/i; //Se muestra un texto a modo de ejemplo, luego va a ser un icono if (emailRegex.test(correo)) { return true; } else { return false; } } //====================================================================================================== function validaContraFormat(Contra){ if(Contra != "" || Contra != null){ var regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])([A-Za-z\d$@$!%*?&]|[^ ]){8,16}$/; //Se muestra un texto a modo de ejemplo, luego va a ser un icono if (Contra.match(regex)) { return true; } else { return false; } } } //====================================================================================================== function camposRequeridos(){ var ok = true; var requireds = document.getElementsByClassName("required"); for(var i = 0; i < requireds.length; i++){ if(requireds[i].value == "" || requireds == null){ ok = false; requireds[i].style.border = "1px solid #8B0000"; }else{ requireds[i].style.border = "0px"; requireds[i].style["border-bottom"]= "2px solid rgba(255, 255, 255, 0.5)"; } } return ok; } //====================================================================================================== function isNumberKey(evt){ var charCode = (evt.which) ? evt.which : evt.keyCode; if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) return false; return true; } //====================================================================================================== function validaCoincideContra(contra1, contra2){ if(contra1 == contra2){ return true; }else{ return false; } } //====================================================================================================== //======================================================================================================
true
6abd987978b35683d507df2717f52556f662fadc
JavaScript
kornofilo/portafolio-S9
/Codigos/bubbleSort.js
UTF-8
809
3.890625
4
[ "MIT" ]
permissive
var arreglo = [2, 7, 4, 1, 5, 3]; function bubbleSort(arreglo) { var swapped; do { swapped = false; for (var i = 0; i < arreglo.length - 1; i++) { if (arreglo[i] > arreglo[i + 1]) { var temp = arreglo[i]; arreglo[i] = arreglo[i + 1]; arreglo[i + 1] = temp; swapped = true; } } } while (swapped); } switch (prompt("A para asendente, D para descendente?")) { case "A": bubbleSort(arreglo); console.log(arreglo); break; case "D": bubbleSort(arreglo); let inverso = arreglo; console.log(inverso.reverse()); break; default: console.log("no!"); break; }
true
3645b791a6be8b2a593fc354b121d2ab4b635987
JavaScript
anadoh/react_meal_finder
/src/helpers/helpers.js
UTF-8
526
2.609375
3
[]
no_license
export async function searchMealFromApi(term) { const response = await fetch( `https://www.themealdb.com/api/json/v1/1/search.php?s=${term}` ); if (response.status === 200) { return response.json(); } else { throw new Error(response); } } export async function getRandomMeal() { const response = await fetch( `https://www.themealdb.com/api/json/v1/1/random.php` ); if (response.status === 200) { return response.json(); } else { throw new Error(response); } }
true
5cb7fa2b62129ead1aab0d636f8ca0909973556f
JavaScript
moguejiofor/grape-electron
/app/src/app/ensureFocus.js
UTF-8
258
2.5625
3
[]
no_license
import state from './state' /** * Makes sure window is in focus. * Maximizes window if needed. */ export default function ensureFocus(win = state.mainWindow) { if (!win) return false if (win.isMinimized()) win.restore() win.focus() return true }
true
2843bca41b10495f5add7ec2286776cbc1cf3335
JavaScript
ShakoHo/moztrap-new-ui
/js/parser.js
UTF-8
3,176
2.578125
3
[]
no_license
//TODO: replace this with jison generated parser function tokenize(query) { // separate qeury with space var re_tokenize = /([^\s"']+"([^"]*)"|[^\s]+)/g; var results = query.match(re_tokenize); var resultList = results.map(function(result) { var keyVal = result.split(":"); if (keyVal.length < 2) { return {key:"", value:keyVal[0]}; } else { return {key:keyVal[0], value:keyVal[1]}; } }); return resultList; } function caseversionCodegen(tokens) { var toRESTQuery = { '': 'name__icontains=', 'name': 'name__icontains=', 'tag': 'tags__name__in=', 'suite': 'case__suites__name__icontains=', 'product': 'productversion__product__name__icontains=', 'ver': 'productversion__version__icontains=', 'status': 'status=', 'orderby': 'order_by=', }; var re_replace = /["']/g; return tokens.map(function(token){ token.value = token.value.replace(re_replace, ""); //tirm the \" if (typeof toRESTQuery[token.key] === "undefined") { return ''; } else { return toRESTQuery[token.key] + encodeURI(token.value); } }); } function caseselectionCodegen(tokens) { var toRESTQuery = { '': 'name__icontains=', 'name': 'name__icontains=', 'tag': 'tags__name__in=', 'suite': 'case__suites__name__icontains=', 'product': 'productversion__product__name__icontains=', 'status': 'status=', 'orderby': 'order_by=', }; var re_replace = /["']/g; //TODO:exact match? return tokens.map(function(token){ token.value = token.value.replace(re_replace, ""); //tirm the \" if (typeof toRESTQuery[token.key] === "undefined") { return ''; } else { return toRESTQuery[token.key] + encodeURI(token.value); } }); } function suiteCodegen(tokens) { var toRESTQuery = { '': 'name__icontains=', 'name': 'name__icontains=', 'product': 'product__name__icontains=', 'status': 'status=', 'orderby': 'order_by=', }; var re_replace = /["']/g; //TODO:exact match? return tokens.map(function(token){ token.value = token.value.replace(re_replace, ""); //tirm the \" if (typeof toRESTQuery[token.key] === "undefined") { return ''; } else { return toRESTQuery[token.key] + encodeURI(token.value); } }); } /* function urlCodegen(tokens) { return tokens.map(function(token){ token.value = token.value.replace('"', '', 'g'); //tirm the \" return token.key + "=" + encodeURI(token.value); }); } */ function buildQueryUrl(url, query, codegen) { //TODO: parse and transform query to tastypie filters var queryUrl = url + "?"; //var queryUrl = url; //console.log(query) var tokens = tokenize(query); //console.log(tokens) if (!tokens.map(function(tok){return tok['key']}) .some(function(key){return key == 'orderby'})){ tokens.push({'key':'orderby', 'value':'-modified_on'}); //FIXME: use default search term instead? } //console.log(tokens) var queryStrings = codegen(tokens); queryStrings.map(function(qs){queryUrl += ("&" + qs);}); //var queryUrl = url + "?order_by=modified_on" //console.log(queryUrl); return queryUrl; }
true
f663fac2916372d4a800aba7fa8c5498dfafd25e
JavaScript
CahylA1/Kixclusive
/src/components/Main.js
UTF-8
1,267
2.8125
3
[]
no_license
import { useState, useEffect } from 'react' import { Route, Switch } from 'react-router-dom' import Index from '../pages/Index' import Show from '../pages/Show' function Main(props) { console.log("MAIN PROPS", props) const [sneaker, setSneaker ] = useState(null); const BASE_URL = 'http://localhost:3001/kixclusive/'; // helper functions for getting and creating sneeakers const getSneaker = async () => { const response = await fetch(BASE_URL) const data = await response.json(); setSneaker(data); } const createSneaker = async (shoe) => { await fetch(BASE_URL,{ method: 'POST', headers: { 'Content-type': 'Application/json' }, body: JSON.stringify(shoe) }) getSneaker() // get Sneaker and update state after creating a sneaker } // get sneakers when application loads useEffect(() => getSneaker(), []) // runs once on page load // BE SURE TO Proof read * return ( <main> <Switch> <Route exact path="/"> <Index sneaker={sneaker} createSneaker={createSneaker}/> </Route> <Route path="/kixclusive/:id" render={(rp) => ( <Show {...rp} sneaker={sneaker} /> )} /> </Switch> </main> ) } export default Main;
true
e7f2379cda9220b98ece6bf634bf6263d791c09b
JavaScript
jstiehl/training-plan
/app/src/libs/utils.js
UTF-8
1,079
3.03125
3
[]
no_license
export const dayMap = day => { switch(day) { case 1: return "Monday" case 2: return "Tuesday" case 3: return "Wednesday" case 4: return "Thursday" case 5: return "Friday" case 6: return "Saturday" case 0: default: return "Sunday" } } export const getAccessToken = () => { let token try { token = JSON.parse(window.localStorage.getItem('tpaccess')) } catch (e) { console.log("no token available") throw(e) } return token } export const getRefreshToken = () => { let token try { token = JSON.parse(window.localStorage.getItem('tprefresh')) } catch (e) { console.log("no refresh token available") throw(e) } return token } export const deleteTokens = () => { window.localStorage.removeItem("tpaccess") window.localStorage.removeItem("tprefresh") } export const setTokens = tokens => { window.localStorage.setItem("tpaccess", JSON.stringify(tokens.accessToken)) window.localStorage.setItem("tprefresh", JSON.stringify(tokens.refreshToken)) }
true
a0ad25f249bd6a2a490f72560c4deaa83f1ca7fa
JavaScript
Edisonsan/typescript
/Typescript002_Decorators_Clase.js
UTF-8
2,463
2.921875
3
[]
no_license
var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; //Definimos la funcion como Init, la cual extendera Target que es una clase function init(target) { return /** @class */ (function (_super) { __extends(class_1, _super); function class_1() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.marca = 'Hyundai'; _this.model = _super.prototype.getModel.call(_this); _this.color = 'Azul'; return _this; } class_1.prototype.getModel = function () { return this.marca + " " + this.model + " " + this.color; }; return class_1; }(target)); } //Definimos la clase con el Decorador var NuevoVehiculo = /** @class */ (function () { function NuevoVehiculo(model) { this.model = model; } //Empleamos el decorador Historial para la funcion getModel, por lo que cada //vez que se ejecute este metodo se va ejecutar el decorador. NuevoVehiculo.prototype.getModel = function () { console.log(this.model); return this.model; }; NuevoVehiculo = __decorate([ init ], NuevoVehiculo); return NuevoVehiculo; }()); //Creamos un Objeto con la clase Vehiculo, y llamamos el metodo getModel var NuevoCarro = new NuevoVehiculo('Tucson'); NuevoCarro.getModel();
true