language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
C++
UTF-8
1,353
3.484375
3
[ "MIT" ]
permissive
#ifndef ISSTRPERMUTATION_HPP_ #define ISSTRPERMUTATION_HPP_ // Given two strings, write a method to decide if one is a permutation of the // other #include <string> #include <algorithm> #include <map> namespace Algo::DS::String { bool IsPermutationSort(const std::string& first, const std::string& second) { if (first.empty() && second.empty()) { return true; } if (first.size() != second.size()) { return false; } std::string firstStr = first, secondStr = second; std::sort(firstStr.begin(), firstStr.end()); std::sort(secondStr.begin(), secondStr.end()); return firstStr == secondStr; } bool IsPermutationCount(const std::string& first, const std::string& second) { if (first.empty() && second.empty()) { return true; } if (first.size() != second.size()) { return false; } std::map<char, int> stat; for (size_t i = 0; i < first.size(); ++i) { if (stat.end() == stat.find(first[i])) { stat.insert({first[i], 0}); } ++stat[first[i]]; } for (size_t i = 0; i < second.size(); ++i) { if (stat.end() == stat.find(second[i])) { return false; } if (--stat[second[i]] < 0) { return false; } } return true; } } #endif /* ISSTRPERMUTATION_HPP_ */
JavaScript
UTF-8
1,304
2.640625
3
[]
no_license
var express = require('express'); var router = express.Router(); var User = require('../models/db-user'); /* GET users listing. */ router.get('/', function(req, res, next) { res.send('respond with a resource'); }); router.post('/', (req, res)=>{ var user = { name : "Nhat", email : "email@gmail.com", password : "Nhat123" } User.create(user,(err, user)=>{ if (err) return res.status(500).send("Lỗi "); res.status(200).send(user); }) }) router.get('/:id', function (req, res) { User.findById(req.params.id, function (err, user) { if (err) return res.status(500).send("Lỗi"); if (!user) return res.status(404).send("Không tìm thấy user."); res.status(200).send(user); }); }); router.delete('/:id', function (req, res) { User.findByIdAndRemove(req.params.id, function (err, user) { if (err) return res.status(500).send("Lỗi."); res.status(200).send("User "+ user.name +" đã được xóa."); }); }); router.put('/:id', function (req, res) { User.findByIdAndUpdate(req.params.id, {$set:{name:"Bon"}}, {new: true}, (err, user) =>{ if (err) return res.status(500).send("There was a problem updating the user."); res.status(200).send(user); }); }); module.exports = router;
Python
UTF-8
798
2.8125
3
[]
no_license
import requests from bs4 import BeautifulSoup def get_imdb_movie_ids(count): try: url = 'http://www.imdb.com/chart/top' res = requests.get(url, verify=False) movies_chart = BeautifulSoup(res.text, 'html.parser') movies_list = movies_chart.body.find("tbody", {"class": "lister-list"}) movies_list_items = movies_list.find_all('tr') movie_ids = [] for i, chart_row in enumerate(movies_list_items): while i < count: movie_id = chart_row.find("div", {"class": "seen-widget"})['data-titleid'] movie_ids.append(movie_id) break return movie_ids except Exception as err: print(err) if __name__ == '__main__': print('Main page')
Java
UTF-8
224
1.515625
2
[]
no_license
package org.openelis.portal.client.resources; public interface IconCSS extends org.openelis.ui.resources.IconCSS { String helpImage(); String reportImage(); String emailImage(); String spreadsheetImage(); }
PHP
UTF-8
1,315
3.15625
3
[]
permissive
<?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ $naziv = 'Algebra'; if ($naziv == 'PHP') { echo 'Varijabla ima vrijednost PHP'; echo 'Varijabla ima neku drugu vrijednost'; } echo '<hr>'; $a = 1; if ($a <= 2) { echo 'Varijabla a je manja ili jednaka broju 2'; $a++; } else { echo 'Varijabla a je veća od broja 2'; $a = 1; } echo '<hr>'; $naziv = 'Algebra'; if (strlen($naziv) > 10) { echo 'Naziv ima više od 10 znakova'; } echo '<br> nizanje uvjeta && || <br>'; echo 'true && true = true <br>'; echo 'true && false =false <br>'; echo 'false && true =false <br>'; echo 'false $$ false = false <br>'; echo '1 && 1 = 1 <br>'; echo '1 && 0 = 0 <br>'; echo '0 $$ 1 = 0 <br>'; echo '0 && 0 = 0 <br>'; echo 'ili <br>'; echo '1 || 1 = 1 <br>'; echo '1 || 0 = 0 <br>'; echo '0 || 1 = 0 <br>'; echo '0 || 0 = 0 <br>'; echo 'not !<br>'; echo '!1=0<br>'; echo '!0=1<br>'; echo '<hr>'; $naziv = 'AlgebraXXX'; if (strlen($naziv) < 5 || strlen($naziv) >= 11) { echo 'lozinka mora imati najmanje 6 znakova i strogo manje od 11'; echo '<br>lozinka '.$naziv.' ima '.strlen($naziv).' znakova!'; } else { echo 'lozinka je ispravna'; }
Markdown
UTF-8
1,478
2.703125
3
[ "MIT" ]
permissive
I am ZnBase64Encoder. Base64 encoding is a technique to encode binary data as a string of characters that can be safely transported over various protocols. Basically, every 3 bytes are encoded using 4 characters from an alphabet of 64. Each encoded character represents 6 bits. The most commonly used alphabet is 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'. One or two equal signs (= or ==) are used for padding. ZnBase64Encoder new encode: #[0 1 2 3 4 5]. ZnBase64Encoder new encode: #[10 20] ZnBase64Encoder new decode: 'BQQDAgEA'. ZnBase64Encoder new decode: 'FAo='. The encoded data can optionally be broken into lines. Characters not part of the alphabet are considered as white space and are ignored when inbetween groups of 4 characters. My #encode: method works from ByteArray to String, while my #decode: method works from String to ByteArray. Note that to encode a String as Base64, you first have to encode the characters as bytes using a character encoder. See also http://en.wikipedia.org/wiki/Base64 I can be configured with - a custom alphabet (#alphabet: #standardAlphabetWith:and:) - optional line breaking (#breakLines #breakLinesAt:) - the line end convention to use when breaking lines (#lineEndConvention:) - custom padding character or no padding (#padding: #noPadding) - optional enforcing of padding on input (#beStrict #beLenient) - what kind of whitespace I accept (#whitespace:) Part of Zinc HTTP Components.
Java
UTF-8
3,087
2.140625
2
[]
no_license
package com.index.medidor.activities; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.index.medidor.R; import com.index.medidor.utils.CustomProgressDialog; public class RegistroActivity extends AppCompatActivity { private String url = null ; private int valor; private CustomProgressDialog mCustomProgressDialog; private EditText etEmail, etNombres, etApellidos, etPassword, etIdDispositivo; private Button btnRegistrar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_registro); mCustomProgressDialog = new CustomProgressDialog(this); mCustomProgressDialog.setCanceledOnTouchOutside(false); mCustomProgressDialog.setCancelable(false); etEmail = findViewById(R.id.etEmail); etNombres = findViewById(R.id.etNombres); etApellidos = findViewById(R.id.etApellidos); etPassword = findViewById(R.id.etPassword); etIdDispositivo = findViewById(R.id.etIdDispositivo); btnRegistrar = findViewById(R.id.btnRegistrar); btnRegistrar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mCustomProgressDialog.show(""); valor = 0; String email = etEmail.getText().toString().toLowerCase(); String nombres = etNombres.getText().toString(); String apellidos = etApellidos.getText().toString(); String password = etPassword.getText().toString(); String id_dispositivo = etIdDispositivo.getText().toString(); url = "https://www.inndextechnology.com/inndex/app/registarUsuario.php?email="+email+"&nombres="+nombres+"&apellidos="+apellidos+"&password="+password+"&id_dispositivo="+id_dispositivo; if (!email.isEmpty() && !password.isEmpty() && !nombres.isEmpty() && !apellidos.isEmpty() && !id_dispositivo.isEmpty()){ ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); if (networkInfo !=null && networkInfo.isConnected()){ //new Registro().execute(); }else{ Toast.makeText(getBaseContext(),"No hay conexion a internet",Toast.LENGTH_LONG).show(); mCustomProgressDialog.dismiss(""); } }else{ Toast.makeText(getBaseContext(),"No ha llenado todos los datos",Toast.LENGTH_LONG).show(); mCustomProgressDialog.dismiss(""); } } }); } }
Python
UTF-8
2,717
3.015625
3
[]
no_license
import matplotlib.pyplot as plt import os import random from sklearn.tree import DecisionTreeRegressor dataset_file = os.path.join(os.getcwd(), '../../datasets/winequality-red.csv') x_list = [] labels = [] names = [] header = True with open(dataset_file, 'r') as f: if header: names = f.readline().strip().split(';') for line in f.readlines(): row = line.strip().split(';') labels.append(float(row[-1])) row.pop() float_row = [float(num) for num in row] x_list.append(float_row) # Normalize columns in x and labels n_rows = len(x_list) n_cols = len(x_list[0]) # Take fixed test set 30% of sample n_sample = int(n_rows * 0.30) idx_test = random.sample(range(n_rows), n_sample) idx_test.sort() idx_train = [i for i in range(n_rows) and i not in idx_test] # Define test and training attribute and label sets x_train = [x_list[r] for r in idx_train] x_test = [x_list[r] for r in idx_test] y_train = [labels[r] for r in idx_train] y_test = [labels[r] for r in idx_test] # Train a series of models on random subsets of the training data # collect the models in a list and check error of composite as list grows # maximum number of models to generate num_tree_max = 100 # tree_depth - typically at the high end tree_depth = 5 # initialize a list to hold models model_list = [] pred_list = [] # number of samples to draw for stochastic bagging bag_fract = 0.5 n_bag_samples = int(len(x_train) * bag_fract) for i_trees in range(num_tree_max): idx_bag = [] for i in range(n_bag_samples): idx_bag.append(random.choice(range(len(x_train)))) x_train_bag = [x_train[i] for i in idx_bag] y_train_bag = [y_train[i] for i in idx_bag] model_list.append(DecisionTreeRegressor(max_depth=tree_depth)) model_list[-1].fit(x_train_bag, y_train_bag) # Make prediction with latest model and add to list of predictions latest_pred = model_list[-1].predict(x_test) pred_list.append(list(latest_pred)) # build cumulative prediction from first "n" models mse = [] all_pred = [] for i_models in range(len(model_list)): # Average first "i_models" of the predictions pred = [] for i_pred in range(len(x_test)): pred.append(sum([pred_list[i][i_pred] for i in range(y_test)]) / ( i_models+1)) all_pred.append(pred) errors = [(y_test[i]-pred[i]) for i in range(len(y_test))] mse.append(sum([e*e for e in errors])/len(y_test)) n_models = [i+1 for i in range(len(model_list))] plt.plot(n_models, mse) plt.axis('tight') plt.xlabel('Number of models in Ensemble') plt.ylabel('Mean squared error') plt.ylim((0.0, max(mse))) plt.show() print('Minimum MSE: ', min(mse))
Markdown
UTF-8
10,004
2.796875
3
[]
no_license
--- layout: layouts/post.njk title: > VoV 040: Fonts with Miriam Suzanne date: 2018-12-04 11:00:51 episode_number: 040 duration: 51:15 audio_url: https://media.devchat.tv/viewsonvue/VoV_040_Fonts%20with%20Miriam_Suzanne.mp3 podcast: views-on-vue tags: - views_on_vue - podcast --- **Panel:** - Joe Eames - John Papa - Erik Hatchett - Charles Max Wood **Special Guest:** [Miriam Suzanne](https://twitter.com/mirisuzanne?lang=en) In this episode, the panel talks with [Miriam Suzanne](https://twitter.com/mirisuzanne?lang=en) who is an author, performer, musician, designer, and web developer who works with [OddBird](https://oddbird.net/authors/miriam/), Teacup, Gorilla, Grapefruit Lab, and CSS Tricks. She’s the author of Riding SideSaddle and the Post-Obsolete Book, co-author of Jump Start Sass, and creator of the Susy and True Open-Source toolkits. The panel and the guest talk about Fonts! **Show Topics:** 0:00 [– Advertisement – Kendo UI](https://www.telerik.com/kendo-ui) 0:53 – Guest: Hello! 1:01 – Guest: I am a designer and a developer and started a business with my brother. We are two college dropouts. 2:00 – Panel: Is that’s why it’s called [OddBird?](https://oddbird.net/authors/miriam/) 2:05 – Guest: Started with Vue and have been talking at conferences. 2:31 – Chuck: Chris invited you and he’s not here today – go figure! 2:47 – Panel: You are big in the CSS world. 2:58 – Guest: That’s where I’ve made my name. I made a grid system that was popular at one moment in time. 3:17 – Panel. 3:27 – Panel: Grid Systems are... 3:36 – _Guest talks about her grid system and how it looked._ 4:20 – Panel. 4:24 – _Panel goes back-and-forth!_ 5:24 – Chuck. 5:27 – Guest: That’s why grid systems came out in the first place b/c layout was such a nightmare. When I built Susy... 6:02 – How much easier is design today on modern browsers compared to ten years ago when you created Susy? 6:14 – Guest: It can look daunting but there are great guides out there! 7:04 – _Panel asks a question._ 7:11 – Guest: We recommend a stack to our clients. We had been using backbone Marinette for a while and we wanted to start messing with others. Looking at other frameworks. Looking at design, I like that Vue doesn’t hide it from me and I can see what I need. 8:41 – Panel: I love that about Vue. I knew this guy named, Hue. 8:54 – Guest: I have been friends with [Sarah Drasner.](https://twitter.com/sarah_edo?ref_src=twsrc%255Egoogle%257Ctwcamp%255Eserp%257Ctwgr%255Eauthor) 9:07 – Panel: [Sarah](https://twitter.com/sarah_edo?ref_src=twsrc%255Egoogle%257Ctwcamp%255Eserp%257Ctwgr%255Eauthor) is great she’s on my team. 9:39 – Guest: I had been diving into JavaScript over the summer. I hadn’t done a lot of JS in the past before the summer. I was learning Vanilla JavaScript. 10:21 – Guest: I don’t like how it mixes it all together (in reference to the [JSX](https://reactjs.org/docs/introducing-jsx.html)). 10:44 – _Panel mentions Python and other things. Panelist asks a question._ 10:54 – Guest: That would be a question for someone who writes that. 11:30 – Panel: I am going to change topics here for a second. Can you talk about your talk? And what is a design system? 11:48 – _Guest answers the question._ 13:26 – _Panel follows-up with another question._ 13:35 – _Guest talks about component libraries._ 15:30 – Chuck: Do people assume that the component that they have has all the accessibility baked-in b/c everything else does – and turns out it doesn’t? 15:48 – _Guest answers._ Guest: Hopefully it’s marked into the documentation. 16:25 – Panel. 16:36 – Guest: If you don’t document it – it doesn’t exist. 17:01 – Panel. 17:22 – Guest: “How do we sell clients on this?” We don’t – we let them come back and say, “we had to do less upkeep.” If they are following our patterns then... 17:57 – Panel: We’ve had where guides are handed off and it erodes slowly over time. Then people are doing it 10 different ways and not doing it the way it was designed. 18:31 – Guest: Yes, it should be baked-into the design and it shouldn’t be added to the style guide. 19:02 – Chuck: I really love Sass – and CSS – how do you write SASS or CSS with Vue? 19:12 – _Guest answers the question._ 19:23 – Chuck: You made my life better! 19:31 – Guest: If you have global files...you can have those imported among other things. 20:11 – Panel: What’s the best way to go about that? 20:24 – _The guest talks about CSS, global designs, among other things._ 21:15 – The guest mentions [inverted triangles CSS!](https://medium.freecodecamp.org/managing-large-s-css-projects-using-the-inverted-triangle-architecture-3c03e4b1e6df) 22:12 – Guest: The deeper we get the narrower we get! 22:49 – _Guest mentions scope styles._ 23:12 – Panel: That makes total sense! We are using scope everywhere. 23:30 – Guest. 23:36 – Panel: How would you approach this? I start with scope and then I take them out of scope and then usually promote them to import for mix-ins. I wonder where is that border? 24:30 [– Advertisement – Get A Coder Job!](https://devchat.tv/get-a-coder-job/) 25:09 – _Guest answers the question._ 25:53 – Panel: It sounds easy at first but when you are designing it you say: I know that isn’t right! 26:13 – Guest: I try to go through a design proposal. 26:27 – _Guest defines the term:_ _reused._ 27:04 – Panel. 27:10 – Guest. 27:30 – Panel: We used to have this problem where we got the question of the following: splitting up the CSS bundles. 28:27 – Guest: That is the nice thing of having CSS in components. 28:49 – _Panel asks Miriam a question._ 29:02 – Guest: That’s often when someone wants a redesign. 29:54 – Panel: How do you decide on how many fonts to deliver so they don’t take over the size of the browser? 30:09 – Guest: The usual design rule is no more than 2-3 fonts works out well for performance. Try to keep that rule in mind, but you have to consider every unique project. What is more important for THAT project? 31:46 – Panel. 32:21 – _Guest gives recommendations with fonts and font files._ 33:37 – Chuck: What are you working on now with Vue? 33:45 – _Guest answers the question._ _The guest talks about collaborative writing._ 34:10 – _Miriam continues._ 34:55 – Chuck: What was the trickiest part? 35:00 – _Guest answers the question._ 36:03 – Guest: It’s called Vue Finder and it’s through open source. 36:39 – Chuck: Any recent talks coming up for you? 36:49 – Guest: I have one tonight and later one in California! 37:02 – Guest: There were several Vue conferences this year that I was sad to have missed. 37:40 – Guest: Are you doing it again? 37:49 – Panel: How many do you attend? 37:57 – Guest: Normally I do 8-10 conferences and then a variety of Meetups. 38:33 – Chuck: Picks! How do people find you? 38:41 – Guest: [OddBird.net](https://oddbird.net) and [Twitter!](https://twitter.com/mirisuzanne?lang=en) 38:58 –[Advertisement – Fresh Books! DEVCHAT code. 30-day trial.](https://www.freshbooks.com/?ref=ppc-na-fb&camp=US%2528SEM%2529Branded%257CEXM&ag=%255Bfreshbooks%255D&kw=freshbooks&campaignid=717543354&adgroupid=51893696397&kwid=kwd-298507762065&dv=c&ntwk=g&crid=284659279616&source=GOOGLE&gclid=EAIaIQobChMI1uiA0Jas3gIVirrACh04fwTjEAAYASAAEgJxqvD_BwE&gclsrc=aw.ds) **Links:** - [Vue](https://vuejs.org) - [React](https://reactjs.org) - [JavaScript](https://www.javascript.com) - [C#](https://www.tutorialspoint.com/csharp/) - [C++](https://www.cplusplus.com) - [C++ Programming / Memory Management](https://en.wikibooks.org/wiki/C%252B%252B_Programming/Memory_Management) - [Angular](https://angular.io) - [Blazor](https://github.com/aspnet/Blazor) - [JavaScript](https://www.javascript.com) - [DevChat TV](https://devchat.tv) - [JSX](https://reactjs.org/docs/introducing-jsx.html) - [VueConf US 2018](https://www.vuemastery.com/conferences/vueconf-us-2018/agile-design-systems-in-vue-miriam-suzanne/) - [CSS Tricks – By Sarah Drasner](https://css-tricks.com/how-to-import-a-sass-file-into-every-vue-component-in-an-app/#more-277641) - [Real Talk JavaScript](https://realtalkjavascript.simplecast.fm) - [FX](https://www.fxnetworks.com/shows/pose) - [Miriam’s Twitter](https://twitter.com/mirisuzanne?lang=en) - [Miriam’s Website](https://www.miriamsuzanne.com) - [OddBird](https://oddbird.net) **Sponsors:** - [Fresh Books](https://www.freshbooks.com/?ref=ppc-na-fb&camp=US%2528SEM%2529Branded%257CEXM&ag=%255Bfreshbooks%255D&kw=freshbooks&campaignid=717543354&adgroupid=51893696397&kwid=kwd-298507762065&dv=c&ntwk=g&crid=284659279616&source=GOOGLE&gclid=EAIaIQobChMI6NHV7MSb3gIVh7bACh0hhAD5EAAYASAAEgI9K_D_BwE&gclsrc=aw.ds&dclid=COL6yu3Em94CFRi8TwodLnkP0A) - [Cache Fly](https://www.cachefly.com) - [Kendo UI](https://www.telerik.com/kendo-angular-ui/?utm_medium=cpm&utm_source=adventuresinng&utm_campaign=dt-kendo-ang2-nov16&utm_content=audio) - [Get A Coder Job!](https://devchat.tv/get-a-coder-job/) **Picks:** Joe - Indoor Rock Climbing - Getting back into what you enjoy - [RoboTech](https://en.wikipedia.org/wiki/Robotech_(TV_series)) - [History of Robotech](https://www.youtube.com/watch?v=CrIm5lYSdTQ) - [Vue.JS In Action](https://www.amazon.com/Vue-js-Action-Eric-Hanchett/dp/1617294624) John Papa - [How To Import a SASS file into every Vue Component in an App](https://css-tricks.com/how-to-import-a-sass-file-into-every-vue-component-in-an-app/) - [Real Talk JS Podcast](https://www.realtalkjs.com/) Erik - [AWS Amplify](https://aws-amplify.github.io) - [Doctor Who](https://www.bbcamerica.com/shows/doctor-who) Charles - Dungeons and Dragons Stuff - [Extreme Ownership](https://www.amazon.com/Extreme-Ownership-U-S-Navy-SEALs-ebook/dp/B00VE4Y0Z2) Miriam - [Pose](https://www.fxnetworks.com/shows/pose) - New DND Game - Test Version ### Transcript
Java
UTF-8
541
2.03125
2
[ "Apache-2.0" ]
permissive
package com.italankin.placard.colorpicker; import android.view.LayoutInflater; import android.view.ViewGroup; import androidx.annotation.ColorInt; import androidx.annotation.Nullable; interface ColorModelController { void init(ViewGroup root, LayoutInflater inflater); void destroy(); void setColor(@ColorInt int color); @ColorInt int getColor(); void setListener(@Nullable OnColorChangedListener listener); interface OnColorChangedListener { void onColorChanged(@ColorInt int newColor); } }
JavaScript
UTF-8
4,067
4.15625
4
[ "MIT" ]
permissive
// Código del cuadrado console.group("Cuadrados"); // const ladoCuadrado = 5; // console.log("Los lados del cuadrado miden: " + ladoCuadrado + "cm"); function perimetroCuadrado(lado) { return lado * 4; } // console.log("El perímetro del cuadrado es: " + perimetroCuadrado + "cm"); function areaCuadrado(lado) { return lado * lado; } // console.log("El área del cuadrado es: " + areaCuadrado + "cmˆ2"); console.groupEnd(); // Código del triángulo console.group("Triángulos"); // const ladoTriangulo1 = 6; // const ladoTriangulo2 = 6; // const baseTriangulo = 4; // console.log( // "Los lados del triángulo miden: " // + ladoTriangulo1 // + "cm, " // + ladoTriangulo2 // + "cm, " // + baseTriangulo // + "cm" // ); // const alturaTriangulo = 5.5; // console.log("La altura del triángulo es de: " + alturaTriangulo + "cm"); function perimetroTriangulo(lado1, lado2, base) { return lado1 + lado2 + base; } // console.log("El perímetro del triángulo es: " + perimetroTriangulo + "cm"); function areaTriangulo(base, altura) { return (base * altura) / 2; } console.log("El área del triángulo es: " + areaTriangulo + "cmˆ2"); console.groupEnd(); // Código del círculo console.group("Círculos"); // Radio // const radioCirculo = 4; // console.log("El radio del círculo es: " + radioCirculo + "cm"); // Diámetro function diametroCirculo(radio) { return radio * 2; } // PI const PI = Math.PI; console.log("PI es: " + PI); // Circunferencia function perimetroCirculo(radio) { const diametro = diametroCirculo(radio); return diametro * PI; } // Área function areaCirculo(radio) { return (radio * radio) * PI; } console.groupEnd(); console.group("isosceles"); function alturaIsosceles(lado1,lado2,base){ if(lado1==lado2){ if(lado1>base){ alert("si es un isosceles"); altura=Math.sqrt((lado1*lado1)-((base*base)/4)); return altura; } }else{ alert("no es un triangulo isosceles"); } } console.groupEnd; // Aquí interactuamos con el HTML function calcularPerimetroCuadrado() { const input = document.getElementById("InputCuadrado"); const value = input.value; const perimetro = perimetroCuadrado(value); alert(perimetro); } function calcularAreaCuadrado() { const input = document.getElementById("InputCuadrado"); const value = input.value; const area = areaCuadrado(value); alert(area); } function CalcularPerimetroTriangulo(){ const input1 = document.getElementById("lado1"); const plado = input1.value; const input2 = document.getElementById("lado2"); const slado = input2.value; const input3 = document.getElementById("base"); const pbase = input3.value; n1=Number(plado); n2=Number(slado); n3=Number(pbase); const perimetro=perimetroTriangulo(n1,n2,n3); alert(perimetro); } function CalcularAreaTriangulo(){ const input1 = document.getElementById("baset"); const baset = input1.value; const input2 = document.getElementById("altura"); const altura = input2.value; const area = areaTriangulo(baset,altura); alert(area); } function CalcularDiametroCirculo(){ const input = document.getElementById("radio"); const radio = input.value; const diametro = diametroCirculo(radio); alert(diametro); } function CalcularPerimetroCirculo(){ const input = document.getElementById("radio"); const radio = input.value; const perimetro = perimetroCirculo(radio); alert(perimetro); } function CalcularAreaCirculo(){ const input = document.getElementById("radio"); const radio = input.value; const area = areaCirculo(radio); alert(area); } function CalcularAlturaIsosceles(){ const input1 = document.getElementById("ladoi1"); const ladoi1 = input1.value; const input2 = document.getElementById("ladoi2"); const ladoi2 = input2.value; const input3 = document.getElementById("basei"); const basei = input3.value; const altura = alturaIsosceles(ladoi1,ladoi2,basei); alert(altura); }
JavaScript
UTF-8
783
3.859375
4
[]
no_license
const maxSubarraySum = (array, n) => { if (n > array.length){ return null; } let maxSum = 0; let tempSum = 0; for (let i = 0; i< n; i++){ maxSum += array[i]; } tempSum=maxSum; for (let i = n; i < array.length; i++){ tempSum = tempSum - array[i-n] + array[i]; maxSum = Math.max(maxSum, tempSum); } return maxSum; } // function getRandomIntInclusive(min, max) { // min = Math.ceil(min); // max = Math.floor(max); // return Math.floor(Math.random() * (max - min + 1)) + min; //The maximum is inclusive and the minimum is inclusive // } // const exampleArray = new Array(100); // for (let i=0; i<exampleArray.length; i++){ // exampleArray[i]=getRandomIntInclusive(1,10); // } // console.log(exampleArray); module.exports = maxSubarraySum;
TypeScript
UTF-8
550
3.125
3
[ "MIT" ]
permissive
async function* limiter(rps: number) { while(true) { let count: number = yield await new Promise(resolve => setTimeout(resolve, 1000 / rps * (count || 1))) } } interface LimiterFactory { new(rps: number): AsyncGenerator<any, void, number> (rps: number): AsyncGenerator<any, void, number> } interface Exports extends LimiterFactory { limiter: typeof limiter default: LimiterFactory } const Limiter = function Limiter(rps: number) { return limiter(rps) } as Exports Limiter.limiter = limiter Limiter.default = Limiter export = Limiter
Java
UTF-8
642
3.3125
3
[]
no_license
package array; /** * 描述:1207. 独一无二的出现次数 * * @author zy * @date 2019/10/14 8:55 */ public class UniqueOccurrences { public boolean uniqueOccurrences(int[] arr) { int[] nums = new int[2001]; for (int i = 0; i < arr.length; i++) { nums[arr[i] + 1000]++; } int[] rs = new int[2001]; for (int i = 0; i < nums.length; i++) { if (nums[i] > 0) { if (rs[nums[i]] > 0) { return false; } else { rs[nums[i]] = 1; } } } return true; } }
C++
UTF-8
4,766
2.796875
3
[ "MIT" ]
permissive
#include "Camera.h" #include <iostream> #include "../Transform.h" //must be less than 90 to avoid gimbal lock const float Camera::s_maxVerticalAngle = 85.0f; const float Camera::s_minFov = 0.1f; const float Camera::s_maxFov = 179.0f; Camera::Camera() : m_position(0.0f, 0.0f, 1.0f) , m_viewMatrix(1.0f) , m_projectionMatrix(1.0f) , m_forward(0.0f) , m_up(0.0f) , m_right(0.0f) , m_horizontalAngle(180.0f) , m_verticalAngle(0.0f) { m_frustum = BoundingFrustum(m_viewMatrix); } void Camera::Update(float deltaTime) { if (m_isInterpolating) { m_interpolationCurrentTime += deltaTime; if (m_interpolationCurrentTime <= m_interpolationTime) { float progress = m_interpolationCurrentTime / m_interpolationTime; CameraSnapshot transition = CameraSnapshotInterpolator::Interpolate(m_CSFrom, m_CSTo, progress); m_params.m_fov = transition.fov; m_horizontalAngle = transition.horizontalRotation; m_verticalAngle = transition.verticalRotation; m_position = transition.position; } else { m_isInterpolating = false; } } m_forward = glm::vec3( cos(glm::radians(m_verticalAngle)) * sin(glm::radians(m_horizontalAngle)), sin(glm::radians(m_verticalAngle)), cos(glm::radians(m_verticalAngle)) * cos(glm::radians(m_horizontalAngle)) ); m_right = glm::vec3( sin(glm::radians(m_horizontalAngle) - 3.14f * 0.5f), 0.0f, cos(glm::radians(m_horizontalAngle) - 3.14f * 0.5f) ); m_up = glm::cross(m_right, m_forward); /* * Possible Solution for Matrix based camera. * https://stackoverflow.com/questions/42263325/3d-camera-has-unintended-roll */ const float hSize = m_params.m_orthoSize * 0.5f; const float wSize = m_params.m_orthoSize * 0.5f * m_params.m_aspectRatio; m_viewMatrix = glm::lookAt(m_position, m_position + m_forward, m_up); m_projectionMatrix = glm::perspective( glm::radians(m_params.m_fov), m_params.m_aspectRatio, m_params.m_nearPlane, m_params.m_farPlane ); m_orthographicMatrix = glm::ortho(-wSize, wSize, -hSize, hSize, m_params.m_nearPlane, m_params.m_farPlane); m_frustum.UpdateViewProjectionMatrix(m_projectionMatrix * m_viewMatrix); } void Camera::UpdateFov(float delta) { m_params.m_fov += delta; if (m_params.m_fov < s_minFov) { m_params.m_fov = s_minFov; } else if (m_params.m_fov > s_maxFov) { m_params.m_fov = s_maxFov; } } void Camera::UpdateLookAt(const glm::vec2& mouseMovement) { m_horizontalAngle -= mouseMovement.x; m_verticalAngle -= mouseMovement.y; NormalizeAngles(); } void Camera::Move(const glm::vec3& movement) { m_position += movement; } void Camera::SetFov(float fov) { if (fov < s_minFov) { fov = s_minFov; } else if (fov > s_maxFov) { fov = s_maxFov; } m_params.m_fov = fov; } void Camera::SetNearFarPlane(float nearPlane, float farPlane) { m_params.m_nearPlane = nearPlane; m_params.m_farPlane = farPlane; } void Camera::SetAspectRatio(float ratio) { m_params.m_aspectRatio = ratio; } bool Camera::IsInFieldOfView(const glm::vec3& position) const { const glm::vec3 camToObj = position - m_position; const float distSq = static_cast<float>(camToObj.length() * camToObj.length()); if (distSq > m_params.m_farPlane * m_params.m_farPlane) { return false; } if (distSq < m_params.m_nearPlane * m_params.m_nearPlane) { return false; } const glm::vec3 camToObjDir = glm::normalize(camToObj); const float dot = glm::dot(camToObjDir, m_forward); if (dot > 0) { const float angle = glm::degrees(acosf(dot)); return angle <= m_params.m_fov; } return false; } void Camera::ToggleOrthographicCamera() { m_params.m_isOrtho = !m_params.m_isOrtho; } void Camera::LookAt(const glm::vec3& position) { glm::vec3 direction = glm::normalize(position - m_position); m_horizontalAngle = -glm::radians(atan2f(-direction.x, -direction.z)); m_verticalAngle = glm::radians(asinf(-direction.y)); NormalizeAngles(); } void Camera::NormalizeAngles() { while (m_horizontalAngle < 0.0f) { m_horizontalAngle += 360.0f; } while (m_horizontalAngle > 360.0f) { m_horizontalAngle -= 360.0f; } if (m_verticalAngle > s_maxVerticalAngle) { m_verticalAngle = s_maxVerticalAngle; } else if (m_verticalAngle < -s_maxVerticalAngle) { m_verticalAngle = -s_maxVerticalAngle; } } void Camera::SetParams(const Params & params) { if (m_params != params) { m_params = params; } } CameraSnapshot Camera::SaveCameraSnapshot() { CameraSnapshot now; now.fov = m_params.m_fov; now.horizontalRotation = m_horizontalAngle; now.verticalRotation = m_verticalAngle; now.position = m_position; return now; } void Camera::InterpolateTo(CameraSnapshot b, float time) { m_CSFrom = SaveCameraSnapshot(); m_CSTo = b; m_interpolationTime = time; m_interpolationCurrentTime = 0.0f; m_isInterpolating = true; }
Java
UTF-8
1,015
2.546875
3
[]
no_license
package main; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.scene.control.Alert.AlertType; import javafx.stage.Stage; public class Main extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage stage) throws Exception{ Parent root = FXMLLoader.load(getClass().getResource("MainStage.fxml")); stage.setTitle("Type Master"); stage.setScene(new Scene(root)); stage.setResizable(false); stage.show(); stage.setOnCloseRequest(e -> { if(MyController.getTimeline() != null) MyController.getTimeline().stop(); try { MyController.saveGame(); } catch (Exception e1) {} new Alert(AlertType.NONE, "GAME SAVED!!", ButtonType.OK).showAndWait(); }); } }
C++
UTF-8
8,389
3.6875
4
[]
no_license
#include <Rcpp.h> #include <vector> // [[Rcpp::export]] std::vector<int> NextPerm(std::vector<int> x, int n) { // Compute the next permutation to x with maximum number at n // // Args: // x : integer vector // n : integer of the maximum x can have // // Returns: // integer vector, same size as x // // Assumes: // x has no duplicate values // size of x is positive // Note: // if x has reached the 'end', the value does not change // Strategy: // Starting from the end of the vector x, // find the first element that has a larger, unused by the elements to the left // and no greater than n. // replace this element by the smallest such number. // then, fill the elements to the right from the smallest unused values. // Example: // x = 1 2 3 5, n = 5 // 5 does not have larger unused. 3 has one. replace it by 4. // then fill the last element by 3, which is the smallest // result = 1 2 4 3 // // x = 4 5 3 2, n = 5 // 2, 3, 5 does not have larger replacement. 4 is replaced by 5. // then fill the right from the smallest // result = 5 1 2 3 int k = x.size(); if (k > n) Rcpp::stop("k must be no greater than n"); if (k <= 0 || n <= 0) Rcpp::stop("n and k must be positive"); // is there next? bool end = true; for (int i = 0; i < k; i++) { if (x[i] != n-i) { end = false; break; } } if (end) return x; // used keeps which numbers are taken // careful with the difference in the indexing base std::vector<bool> used(n, false); // number of true counted, must equal k int used_count = 0; for (int i = 0; i < k; i++) { used[x[i]-1] = true; used_count++; } if (used_count != k) Rcpp::stop("x must not have duplicate"); for (int i = k-1; i >= 0; i--) { int cur = x[i]; used[cur-1] = false; for (int nex = cur+1; nex <= n; nex++) { if (!used[nex-1]) { x[i] = nex; used[cur-1] = false; used[nex-1] = true; // if this is the last element, done if (i >= k-1) return x; // fill the values to the right int m = i + 1; for (int j = 0; j < n; j++) { if (!used[j]) { x[m] = j+1; used[j] = true; m++; if (m >= k) return x; } } Rcpp::stop("could not fill vectors"); } } } // no way to reach here, though Rcpp::stop("x has no next"); return x; } // [[Rcpp::export]] std::vector<int> PrevPerm(std::vector<int> x, int n) { // Compute the previous permutation to x with maximum number at n // // See NextPerm for details int k = x.size(); if (k > n) Rcpp::stop("k must be no greater than n"); if (k <= 0 || n <= 0) Rcpp::stop("n and k must be positive"); // is there next? bool end = true; for (int i = 0; i < k; i++) { if (x[i] != i+1) { end = false; break; } } if (end) return x; // used keeps which numbers are taken // careful with the difference in the indexing base std::vector<bool> used(n, false); // number of true counted, must equal k int used_count = 0; for (int i = 0; i < k; i++) { used[x[i]-1] = true; used_count++; } if (used_count != k) Rcpp::stop("x must not have duplicate"); for (int i = k-1; i >= 0; i--) { int cur = x[i]; used[cur-1] = false; for (int nex = cur-1; nex >= 1; nex--) { if (!used[nex-1]) { x[i] = nex; used[cur-1] = false; used[nex-1] = true; // if this is the last element, done if (i >= k-1) return x; // fill the values to the right int m = i + 1; for (int j = n-1; j >= 0; j--) { if (!used[j]) { x[m] = j+1; used[j] = true; m++; if (m >= k) return x; } } Rcpp::stop("could not fill vectors"); } } } // no way to reach here, though Rcpp::stop("x has no next"); return x; } /*** R x <- 1:3 n <- 5 ct <- 0 while (TRUE) { ct <- ct + 1 cat(sprintf("%3d : %s\n", ct, paste0(x, collapse = " "))) y <- combiter:::NextPerm(x, n) if (all(x == y)) break x <- y } # NextPerm and PrevPerm are the inverse function for each other x <- 1:3 n <- 5 ct <- 1 while (TRUE) { cat(sprintf("%3d : %s\n", k, paste0(x, collapse = " "))) y <- combiter:::NextPerm(x, n) if (all(x == y)) break z <- combiter:::PrevPerm(y, n) stopifnot(all(x == z)) x <- y ct <- ct + 1 } */ // // [[Rcpp::export]] // std::vector<int> NextPerm(std::vector<int> x) { // // Compute the next permutation to x // // // // Args: // // x : integer vector // // // // Returns: // // integer vector, same size as x // // // // Assumes: // // x has no duplicate values // // size of x is positive // // Note: // // if x has reached the 'end', the value does not change // // // Quick input validation // if (x.size() == 0) Rcpp::stop("x must have positive size"); // // // Strategy: // // Starting from the end of the vector x, // // find the first decreasing adjacent values. // // If find one, then swap that samller value with the // // next larger value on the right, then // // reverse the numbers on the right. // // Example: // // x = 1 2 3 4 // // 3 is the first decreased value, swap that with 4. // // On the right is just one element 3, so the reversing // // does not affect. // // result = 1 2 4 3 // // // // x = 2 4 3 1 // // 2 is the first decreased value, which is swapped with 3. // // On the right is 4 2 1, reversed to 1 2 4 // // result = 3 1 2 4 // for (int i = x.size()-1; i > 0; i--) // { // if (x[i-1] < x[i]) { // for (int j = x.size()-1; j >= i; j--) // { // // Note: I could use binary search here // // but the total runtime would be still O(n) // if (x[i-1] < x[j]) { // std::swap(x[i-1], x[j]); // std::reverse(x.begin()+i, x.end()); // break; // } // } // break; // } // } // return x; // } // // // // // [[Rcpp::export]] // std::vector<int> PrevPerm(std::vector<int> x) { // // Compute the previous permutation to x // // // // Args: // // x : integer vector // // // // Returns: // // integer vector, same size as x // // // // Assumes: // // x has no duplicate values // // size of x is positive // // Note: // // If x has reached the 'end', then no change is made // // // Quick input validation // if (x.size() == 0) Rcpp::stop("x must have positive size"); // // // Same algorithm as NextPerm, except for the direction of inequality // for (int i = x.size()-1; i > 0; i--) // { // if (x[i-1] > x[i]) { // for (int j = x.size()-1; j >= i; j--) // { // // Note: I could use binary search here // // but the total runtime would be still O(n) // // And practically n won't be so big // if (x[i-1] > x[j]) { // std::swap(x[i-1], x[j]); // std::reverse(x.begin()+i, x.end()); // break; // } // } // break; // } // } // return x; // } // // [[Rcpp::export]] // std::vector<int> PrevPerm(std::vector<int> x) { // // Compute the previous permutation to x // // // // Args: // // x : integer vector // // // // Returns: // // integer vector, same size as x // // // // Assumes: // // x has no duplicate values // // size of x is positive // // Note: // // If x has reached the 'end', then no change is made // // // Quick input validation // if (x.size() == 0) Rcpp::stop("x must have positive size"); // // // Same algorithm as NextPerm, except for the direction of inequality // for (int i = x.size()-1; i > 0; i--) // { // if (x[i-1] > x[i]) { // for (int j = x.size()-1; j >= i; j--) // { // // Note: I could use binary search here // // but the total runtime would be still O(n) // // And practically n won't be so big // if (x[i-1] > x[j]) { // std::swap(x[i-1], x[j]); // std::reverse(x.begin()+i, x.end()); // break; // } // } // break; // } // } // return x; // }
Python
UTF-8
1,471
2.859375
3
[]
no_license
from collections import defaultdict from itertools import combinations from sys import api_version from typing import final username = ["joe","joe","joe","james","james","james","james","mary","mary","mary"] timestamp = [1,2,3,4,5,6,7,8,9,10] website = ["home","about","career","home","cart","maps","home","home","about","career"] userDetails=[] analyse=defaultdict(list) for i in range(len(timestamp)): userDetails.append([username[i],timestamp[i],website[i]]) for name,timeStamp,website in userDetails: analyse[name].append(website) combinationsValue=[] resultant=[] for keys,values in analyse.items(): if len(values)>3: for i in range(len(values)-2): for j in range(i+1,len(values)-1): for k in range(j+1,len(values)):#This Code Also gives Same 3 Value Pairs combinationsValue.append((values[i],values[j],values[k])) resultant.append((values[i],values[j],values[k])) analyse[keys]=combinationsValue else: values=tuple(values) resultant.append(values) #analyse[keys]=list(combinations(values,3)) finalDictionary={} for i in range(len(resultant)): if resultant[i] not in finalDictionary: finalDictionary[resultant[i]]=1 else: finalDictionary[resultant[i]]+=1 sortedValue=sorted(finalDictionary.values(),reverse=True) for key,val in finalDictionary.items(): if sortedValue[0]==val: print(list(key))
PHP
UTF-8
2,979
2.65625
3
[]
no_license
<?php function koneksi() { $conn = mysqli_connect("localhost", "root", ""); mysqli_select_db($conn, "tubes_193040043"); return $conn; } function query($sql) { $conn = koneksi(); $result = mysqli_query($conn, "$sql"); $books = []; while ($book = mysqli_fetch_assoc($result)) { $books[] = $book; } return $books; } function tambah($data) { $conn = koneksi(); $cover = htmlspecialchars($data['cover']); $judul_buku = htmlspecialchars($data['judul_buku']); $pengarang = htmlspecialchars($data['pengarang']); $tahun_terbit = htmlspecialchars($data['tahun_terbit']); $harga = htmlspecialchars($data['harga']); $query = "INSERT INTO buku VALUES ('','$cover' , '$judul_buku' , '$pengarang' , '$tahun_terbit' , '$harga') "; mysqli_query($conn, $query); return mysqli_affected_rows($conn); } function hapus($id) { $conn = koneksi(); mysqli_query($conn, "DELETE FROM buku WHERE id_buku = $id"); return mysqli_affected_rows($conn); } function ubah($data) { $conn = koneksi(); $id_buku = htmlspecialchars($data['id_buku']); $cover = htmlspecialchars($data['cover']); $judul_buku = htmlspecialchars($data['judul_buku']); $pengarang = htmlspecialchars($data['pengarang']); $tahun_terbit = htmlspecialchars($data['tahun_terbit']); $harga = htmlspecialchars($data['harga']); $queryubah = "UPDATE buku SET cover = '$cover', judul_buku = '$judul_buku', pengarang = '$pengarang', tahun_terbit = '$tahun_terbit', harga = '$harga' WHERE id_buku = '$id_buku' "; mysqli_query($conn, $queryubah); return mysqli_affected_rows($conn); } function registrasi($data) { $conn = koneksi(); $username = htmlspecialchars($data['username']); $password = htmlspecialchars($data['password']); $email = htmlspecialchars($data['email']); $result = mysqli_query($conn, "SELECT * FROM user WHERE username = '$username'"); if (mysqli_fetch_assoc($result)) { echo "<script> alert('Username sudah digunakan !'); </script>"; return false; } $password = password_hash($password, PASSWORD_DEFAULT); $query = "INSERT INTO user VALUES ('','$username' , '$password' , '$email')"; mysqli_query($conn, $query); return mysqli_affected_rows($conn); } function cari($keyword) { $conn = koneksi(); $query = ("SELECT * FROM buku WHERE judul_buku LIKE '%$keyword%' OR pengarang LIKE '%$keyword%' OR tahun_terbit LIKE '%$keyword%'"); $result = mysqli_query($conn, $query); $rows = []; while ($row = mysqli_fetch_assoc($result)) { $rows[] = $row; } return $rows; }
JavaScript
UTF-8
5,033
2.921875
3
[]
no_license
var API = require('./api'), Post = require('./Post'), _ = require('lodash'); var ViewController = function(model) { this.model = model; this.postCollection = []; this.actions = []; this.undoButton = document.getElementById('blog-undo-button'); var postTemplate = document.getElementById('blog-post-template'); this.template = _.template(postTemplate.textContent.trim()); this.initialize(); }; ViewController.prototype.initialize = function() { this.establishHandlers(); this.fetchPosts(); var elements = this.generatePostDOMElements(this.postCollection); this.renderPosts(elements); }; ViewController.prototype.establishHandlers = function() { var that = this; document.getElementsByClassName('blog-body__form-section__form__submit')[0] .addEventListener('click', function(e) { e.preventDefault(); var title = document.getElementsByClassName('blog-body__form-section__form__title')[0].value; var body = document.getElementsByClassName('blog-body__form-section__form__body')[0].value; that.handleSubmit({ title: title, body: body }); }); document.getElementById('blog-undo-button') .addEventListener('click', function(e) { e.preventDefault(); that.handleUndo(); }); }; ViewController.prototype.establishPostHandlers = function(postDOMElement) { var that = this; postDOMElement.getElementsByClassName('blog-post__delete-section__button')[0] .addEventListener('click', function(e) { e.preventDefault(); var postId = parseInt(this.dataset.postid); that.handleDelete({ id: postId }); }); }; ViewController.prototype.fetchPosts = function() { var response = API.get(); if (response.status === 200) { this.postCollection = response.body.map(function(post) { return new Post(JSON.parse(post)); }).reverse(); } }; ViewController.prototype.generatePostDOMElements = function(posts) { var that = this; return posts.map(function(post) { var html = that.template(post.attributes); var wrapperDiv = document.createElement('div'); wrapperDiv.innerHTML = html; that.establishPostHandlers(wrapperDiv.firstChild); return wrapperDiv.firstChild; }); }; ViewController.prototype.renderPosts = function(postDOMElements) { var that = this; var bodyContent = document.getElementsByClassName('blog-body__content')[0]; postDOMElements.forEach(function(element) { bodyContent.appendChild(element); }); }; ViewController.prototype.renderPost = function(postDOMElement) { var parent = document.getElementsByClassName('blog-body__content')[0]; parent.insertBefore(postDOMElement, parent.firstChild); }; ViewController.prototype.handleSubmit = function(data) { var response = this.addPost(data); if(response.status === 200){ this.addAction({ actionType: 'add', id: response.data.id }); } }; ViewController.prototype.handleDelete = function(data) { var response = this.deletePost(data); if(response.status === 200){ this.addAction({ actionType: 'delete', id: response.data.id }); } }; ViewController.prototype.handleUndo = function() { this.undo(); }; ViewController.prototype.addAction = function(data) { this.actions.unshift(data); this.showUndo(); }; ViewController.prototype.showUndo = function() { this.undoButton.classList.remove('hide'); }; ViewController.prototype.hideUndo = function() { this.undoButton.classList.add('hide'); }; ViewController.prototype.undo = function() { var action = this.actions.shift(); if(action){ var postModel = this.getPost(action.id); var isAdd = action.actionType === "add"; postModel.update({ deleted: isAdd }); if(isAdd) { this.deletePostFromView(postModel); } else { this.addPostToView(postModel); } } if(this.actions.length === 0){ this.hideUndo(); } }; ViewController.prototype.getPost = function(postId) { return _.find(this.postCollection, function(post){ return post.attributes.id === postId; }); }; ViewController.prototype.addPost = function(data) { var postModel = new Post(data); var response = postModel.save(); if (response.status === 200) { response.data = postModel.attributes; this.postCollection.push(postModel); this.addPostToView(postModel); } return response; }; ViewController.prototype.addPostToView = function(postModel) { var elements = this.generatePostDOMElements([postModel]); this.renderPost(elements[0]); }; ViewController.prototype.deletePost = function(data) { var postModel = this.getPost(data.id); var response = postModel.delete(); if(response.status === 200){ response.data = postModel.attributes; this.deletePostFromView(postModel); } return response; }; ViewController.prototype.deletePostFromView = function(postModel) { var postDOMElement = document.getElementById('blog-post-' + postModel.attributes.id); postDOMElement.parentNode.removeChild(postDOMElement); }; module.exports = ViewController;
TypeScript
UTF-8
153
2.875
3
[ "MIT" ]
permissive
export default function isUndefined<T>(value?: T | undefined): value is undefined { if (value === undefined) { return true; } return false; }
SQL
UTF-8
1,905
3.6875
4
[]
no_license
-- etaty, pracownicy, zespoly select min(placa_pod), max(placa_pod), max(placa_pod) - min(placa_pod) from pracownicy; select etat, avg(placa_pod) as srednia from pracownicy group by etat order by srednia desc; select count(*) as profesorowie from pracownicy group by etat having etat = 'PROFESOR'; select id_zesp, sum(placa_pod) + sum(placa_dod) as sumaryczne from pracownicy group by id_zesp order by id_zesp; select max(sum(placa_pod) + sum(placa_dod)) as max_sum_placa from pracownicy group by id_zesp; select id_szefa, min(placa_pod) as minimalna from pracownicy group by id_szefa order by id_szefa; select id_zesp, count(*) as ilu_pracuje from pracownicy group by id_zesp order by ilu_pracuje desc; select id_zesp, count(*) as ilu_pracuje from pracownicy group by id_zesp having count(*) > 3 order by ilu_pracuje desc; select id_prac, count(*) as duplikaty from pracownicy group by id_prac having count(*) > 1; select etat, avg(placa_pod) as srednia, count(*) as liczba from pracownicy where extract(year from zatrudniony) <= 1990 group by etat order by etat; select id_zesp, etat, avg(placa_pod + placa_dod) as srednia, max(placa_pod + placa_dod) from pracownicy where etat in ('PROFESOR', 'ASYSTENT') group by id_zesp, etat order by id_zesp, etat; select extract(year from zatrudniony) as rok, count(*) as ilu_pracownikow from pracownicy group by extract(year from zatrudniony) order by rok; select length(nazwisko) as ile_liter, count(*) as w_ilu from pracownicy group by length(nazwisko) order by ile_liter; select count(case when instr(nazwisko, 'A', 1, 1) > 0 then 1 else null end) as ile_a, count(case when instr(nazwisko, 'E', 1, 1) > 0 then 1 else null end) as ile_b from pracownicy; select id_zesp, sum(placa_pod) as suma_plac, listagg(nazwisko || ':' || placa_pod, ',') within group (order by nazwisko) as pracownicy from pracownicy group by id_zesp order by id_zesp;
Python
UTF-8
3,065
3.859375
4
[]
no_license
# (19)****************************Logistic Regression practical in machine learning***************** # ----The formula which we use the Logistic Regression----y=1/1+e**-x-----y=1/1+e**-thita**T*X # ----The formula which we use the Regression Line----y=Thita**T * X # -----this is the formula to find out the probability---- p^=sigmoid(Thita**T . X) # -----What is Logistic Regression # *A Regression Algorithm which does classification # *Calculates probability of belonging to a particular class # *if p>50% -->> 1 # *if p<50% -->> 0 # -----How does Logistic Regression Work? # *It takes your feartures and labels [Training Data] # *Fits a linear model (Weights and baises) # *And instead of giving you the result, it gives you the logistic of the result. # *Why logistic? # ******Training a Logistic Regression Model? # *We need values of parameters in theta # *We need high values of probabilities near 1 for positive instances # *We also want low values of probabilities near 0 for negative instances # ----Cost for single training instance # cost(thita)={-log(p^) if y=1 and -log(i-p^) if y=0} # ----C(thita)=-[y log(p^)+ (1-y)log(i-p^)] # ----We use cost function to predict the correct values and to avoid the errors # ----when -log t is very high then t->0 and this is the correct # ----Total training instance # ---J(thita)=-1/m [i=1**Sigma**m y**i log(p^**(i))+ (1-y**i)log(1-p^**i)] # ----bad news----we didnot calculate minimize in this equation # ----Good News---We use Gradient Decent function and approch the minima of the Training values # ----Starting practical # ----import libraries from numpy.core.defchararray import mod from sklearn import datasets from sklearn.linear_model import LogisticRegression import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import tensorflow as tf # ---importing dataset iris=datasets.load_iris() # ----Now checking the keys of irus dataset # print(list(iris.keys())) # ---Now abstracting the data of irus dataset # print(iris['data']) # ---Now abstracting the target of the irus dataset # print(iris['target']) # ---Now abstracting the Description of iris dataset # print(iris['DESCR']) # ----checking the shape of the iris datasets # print(iris['data'].shape) # -------Question----train a logistic regression classifier to predict whether a flower is iris virginica or not # ---Now training the iris dataset # ---we train the data using just one colum X=iris['data'][:,3:] # print(X) y=(iris['target']==2).astype(np.int) # print(y ) # ----Now we train a Logistic Regression classsifier model=LogisticRegression() # ---Now fit the values of Logistic Regression model.fit(X,y) # ---Now predicted the values using pridict function example=model.predict(([[1.6]])) example=model.predict(([[2.6]])) # print(example) # ----Using matplotlib to plot the visualization X_new=np.linspace(0,3,1000).reshape(-1,1) # print(X_new) y_prob=model.predict_proba(X_new) # ---plotting the graph plt.plot(X_new,y_prob[:,1],'g--',label='virginica') plt.show( )
Markdown
UTF-8
8,877
3.203125
3
[ "Apache-2.0" ]
permissive
# A more HTTP-like CouchDB client for Ruby This client library is designed to be more familiar to those used to CouchDB's HTTP interface, as well as being a safe and efficient method of interacting with CouchDB for those just getting started. It's based on the idea of _templates_ rather than _method calls_. Instead of calling a method with arguments, one makes a request by filling in a template and getting the client to make the request. Often there's not even anything to fill in: ```ruby require 'rubycouch' client = CouchClient.new(URI.parse('http://localhost:5984')) response = client.make_request(AllDbs.new) response.json # => ["_replicator","_users","animaldb",...] ``` This is intended to make the calls being made over the network more explicit, but also has the side-effect of being a bit like SQL, where one composes a query and then makes it. Features: - Simple one-to-one mapping between HTTP requests and library calls. - Almost all methods support streaming response data, either raw data or individual results for requests like views, using a simple block mechanism: ```ruby f = open('sample.flv') begin req = GetAttachment.new('elephant', 'sample.flv') database.make_request(req) do |segment| f.write(segment) end ensure f.close() end ``` ## Installing Right now, I guess it's copy the code into your application. I should learn how to publish gems; bear with me a while. ## Incompleteness Right now the library has fairly incomplete API support, though should be enough for simple uses: - Document: `GET` (including streaming), `PUT` (including streaming), `DELETE`. - Attachment: `GET` (including streaming), `PUT` (including streaming), `DELETE`. - Views: Query via `GET`, including streaming response rows. - Databases: Create, Delete, Get info, List documents. - Instance: Get info, List databases. Most of these don't have much in the way of query string parameter support, but do support adding parameters via `merge_query_items` which makes most things work fine. However, one aim of the template-based approach is to make adding support for new requests quite simple, and I think most of the patterns for any request are in place now. If you want to try out the library, I more than welcome PRs to fill in the gaps if the idea of the library intrigues you and you want to use it for your own projects. ## Benefits There are a bunch of benefits to the template approach. Firstly, as intimated, it makes the requests to the database crystal-clear. One thing I've noticed when supporting people using client libraries for different systems is that, often, it's a struggle to work out what's going on under the hood. Why is such-and-such call taking so long? Often it turns out that one method call actually equates to several HTTP requests. Secondly, taking this approach makes it very simple to take HTTP docs and translate them to the library, or to transfer knowledge from making raw HTTP calls to being a little helped by a library: ```ruby get_document = GetDocument.new('aardvark') get_document.rev_id = '1-asdfsfd' # ?rev_id=1-asdfsfd client.database('animaldb').make_request(get_document).json # => {"_id"=>"aardvark", "min_weight"=>40, "_rev"=>... } put_document = PutDocument.new('test-doc-1') put_document.body = '{"hello": "world"}' put_document.rev_id = '1-asdfsfd' # ?rev_id=1-asdfsfd client.database('animaldb').make_request(put_document).json ``` As a developer there are some further benefits. It makes things easier to test, because one can test that a set of calls create the right description of a HTTP request separately from testing that the description is executed correctly. It also means that code naturally falls into small chunks. Normally, a client object would have dozens of methods. In this library, all the client does is maintain high-level connection parameters, such as the root of the CouchDB instance and the credentials to use over HTTP Basic Authentication. At some point, this will hopefully make it simpler to use different HTTP libraries, but for now it's just `Net:HTTP`. ## The API I'll document the full API at some point, but for now, check the source code in the `lib/rubycouch/operations` folder for a list of the operations you can do. Most operations don't actually have a full method compliment for the query parameters they accept. Instead, use `merge_query_params` on the operation, for example, `merge_query_params({:include_docs=>true})`. Some things deserve a couple more notes. ### Request return values All calls to `make_request` return an object of the following form: ```ruby Class.new do attr_reader :code # HTTP status code, as string attr_reader :raw # response body (aside from when streaming) attr_reader :success # whether the request succeeded attr_reader :content_type # content type for `raw` def json if content_type.downcase.eql? 'application/json' JSON.parse(raw) else raise "Non-JSON content type in response; cannot convert." end end end ``` Broadly speaking, it'll only be attachments that return non-JSON responses, though if your CouchDB instance is behind a proxy, it might send back something funny in error cases (e.g., HAProxy's default "503: no backend" error if your instance is down is HTML I think). Where `raw` says "aside from when streaming", most request types provide the facility to stream response data to a block passed to `make_request`. Passing the block causes the response handling code to discard the body after passing it to the block, so `raw` doesn't have any content; the data is already consumed and discarded. Some request types, such as views, have special handling for the block passed to `make_request` where such handling makes more sense than passing back raw stream data. ### Streaming data #### Download The standard behaviour of passing a block to make_request streams the data to the block. For small documents, this probably isn't at all necessary but for large documents and particularly attachments this might be sensible: ```ruby doc = '' database.make_request(GetDocument.new('elephant')) do |segment| doc += segment end puts sprintf("\nStreamed return value: %s", JSON.parse(doc)) # => {"id"=>"kookaburra",...} ``` Of course, it's probably wiser to save the data to a file for later processing or whatever: ```ruby f = open('sample.flv') begin req = GetAttachment.new('elephant', 'sample.flv') database.make_request(req) do |segment| f.write(segment) end ensure f.close() end ``` #### Upload To stream data when uploading, assign something responding to `read` to the `body_stream` attribute of a `PutDocument` or `PutAttachment` call: ```ruby put_document = PutAttachment.new('test-doc-1', 'large_attachment.mp3') put_document.body_stream = File.open("/path/to/large/file") put_document.rev_id = '1-asdfsfd' # ?rev_id=1-asdfsfd client.database('animaldb').make_request(put_document).json ``` Only one of `body` and `body_stream` should be assigned. The values assigned to these attributes are passed directly to `Net::HTTP::Put/Post`. ### Views Views can be called in either a simple or streaming manner. Use streaming for retrieving larger result sets, as the code avoids buffering the response in memory. The simple way gives you back a response with all the data inside it: ```ruby client.database('animaldb') .make_request(GetView.new('views101', 'latin_name')) .json # => # {"total_rows"=>5, "offset"=>0, "rows"=>[ # {"id"=>"kookaburra", "key"=>"Dacelo novaeguineae", "value"=>19}, # {"id"=>"snipe", "key"=>"Gallinago gallinago", "value"=>19}, # {"id"=>"llama", "key"=>"Lama glama", "value"=>10}, # {"id"=>"badger", "key"=>"Meles meles", "value"=>11}, # {"id"=>"aardvark", "key"=>"Orycteropus afer", "value"=>16}]} ``` In the streaming version, one provides a block taking a result row and an index to `make_request`. The block is called for every row in the result set. This consumes each row, so by the time you get the result of the `make_request` call, the `rows` field is empty: ```ruby get_view = GetView.new('views101', 'latin_name') client.database('animaldb').make_request(get_view) do |row, idx| puts sprintf(" %d: %s", idx, row) # => 0: {"id"=>"kookaburra", "key"=>"Dacelo novaeguineae", "value"=>19} # and so on. `row` is always decoded JSON. end.json # => {"total_rows"=>5, "offset"=>0,"rows"=>[]} ``` ### Custom Query Parameters To add your own query parameters, use `merge_query_params`: ```ruby all_docs = AllDocs.new all_docs.merge_query_params({ :include_docs=>true, :descending=>true, :foo=>'bar' }) ``` ### Custom Headers To add headers, use `merge_header_items`: ```ruby all_dbs = AllDbs.new all_dbs.merge_header_items({ 'X-Cloudant-User'=>'mikerhodes', 'Another-Header'=>'Another Value' }) ```
Markdown
UTF-8
1,889
3.09375
3
[]
no_license
# README This readme covers what you need to do to get hasura playing nicely with a simple rails api. The goal is to make it easy to use hasura in development and commit your changes to hasura metadata. 1. We will use rails for schema changes because Hasura's migrations are so messy and the rails meta migration language is quite convenient after all these years. 2. We will run hasura locally in dev mode with a simple docker script 3. We will use Hasura CLI tools to export hasura metadata into version control 4. We will try to use a hook to import this metadata into production when deployed. To start the hasura docker container run the hasura_docker.sh script in application root. Useful commands from within the hasura directory: % hasura metadata export (exports hasura metadata into hasura/metadata) % hasura metadata reload (reloads the existing metadata) % hasura metadata apply (removes and re-applies metadata) For local development: Run hasura via the docker-run.sh script in this folder; Docker hasura container will run on localhost:8080 Set hasura db vars in .env (see .env.example for what you need) To kill the docker container do "docker ps" to see the container id then "docker kill <id>" Use Hasura CLI tools to export hasura metadata into version control so they can be imported by other developers. ## To bring your local hasura up to date with the current metadata: % hasura metadata apply ## To export your local hasura's metadata (configuration) into version control: % hasura metadata export ## To export hasura metadata to staging or production (necessary for deployment) % hasura metadata apply --endpoint "https://staging_url" --admin-secret "<admin secret>" ## A convenient script to apply hasura metadata to staging: % apply-metadata-to-staging.sh But it depends on your setting up .env.deployment_secrets (see example)
C#
UTF-8
674
2.515625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
using UnityEngine; namespace Unity.VisualScripting { /// <summary> /// Returns the component-wise quotient of two 4D vectors. /// </summary> [UnitCategory("Math/Vector 4")] [UnitTitle("Divide")] public sealed class Vector4Divide : Divide<Vector4> { protected override Vector4 defaultDividend => Vector4.zero; protected override Vector4 defaultDivisor => Vector4.zero; public override Vector4 Operation(Vector4 a, Vector4 b) { return new Vector4 ( a.x / b.x, a.y / b.y, a.z / b.z, a.w / b.w ); } } }
Shell
UTF-8
233
2.578125
3
[]
no_license
#!/usr/bin/env sh # Terminate already running picom instances killall -q picom # Wait until the processes have been shut down while pgrep -u $UID -x picom >/dev/null; do sleep 1; done # Start picom picom --experimental-backends &
C#
UTF-8
10,044
2.734375
3
[]
no_license
using System; using System.Collections.Generic; using System.IO; namespace DevToolsAndReferenceAnalyzer.TfsBindingCleanerClasses { /// <summary> /// Class that implements the TFS Migration Cleaner feature functionality. /// </summary> public sealed class TfsMigrationMethods { /// <summary> /// Initializes a new instance of the <see cref="TfsMigrationMethods"/> class. /// </summary> public TfsMigrationMethods() { SeriousIssues = string.Empty; } public string SeriousIssues { get; set; } /// <summary> /// Deletes the TFS related files for a Solution and related Projects. /// </summary> /// <param name="solutionFilePath">The solution file path.</param> /// <returns>A status string listing which files were removed.</returns> /// <exception cref="System.IO.FileNotFoundException">File Not Found Exception</exception> public string DeleteTfsRelatedFilesForSolutionAndRelatedProjects(string solutionFilePath) { #region Preconditions if (!File.Exists(solutionFilePath)) { throw new FileNotFoundException(solutionFilePath); } #endregion string fullSolutionPath = Path.GetFullPath(solutionFilePath); string solutionPath = Path.GetDirectoryName(fullSolutionPath); string solutionFileNameWithoutExtension = Path.GetFileNameWithoutExtension(fullSolutionPath); string results = "Deleting Tfs Related Files for Solution: " + solutionFilePath + Environment.NewLine; results += "--------------------------------------------------------" + Environment.NewLine + Environment.NewLine; Environment.CurrentDirectory = solutionPath; results += DeleteTfsSolutionOrProjectFiles(solutionFileNameWithoutExtension, "."); Solution solution = new Solution(solutionFilePath); foreach (SolutionProject project in solution.Projects) { results += DeleteTfsSolutionOrProjectFiles(project.ProjectName, project.RelativePath); } return results + Environment.NewLine; } /// <summary> /// Removes the TFS project entries for all Project files in a Solution. /// </summary> /// <param name="solutionFilePath">The solution file path.</param> /// <returns>A status string listing which Project files were cleaned.</returns> /// <exception cref="System.IO.FileNotFoundException">File Not Found exception</exception> public string RemoveTfsProjectEntriesForAllProjectsInSolution(string solutionFilePath) { #region Preconditions if (!File.Exists(solutionFilePath)) { throw new FileNotFoundException(solutionFilePath); } #endregion string results = "Removing Tfs Related Project Entries for the Solution: " + solutionFilePath + Environment.NewLine; results += "--------------------------------------------------------" + Environment.NewLine + Environment.NewLine; string fullSolutionPath = Path.GetFullPath(solutionFilePath); string solutionPath = Path.GetDirectoryName(fullSolutionPath); string solutionFileNameWithoutExtension = Path.GetFileNameWithoutExtension(fullSolutionPath); Environment.CurrentDirectory = solutionPath; Solution solution = new Solution(fullSolutionPath); foreach (SolutionProject project in solution.Projects) { results += RemoveTfsRelatedEntriesForProjectFile(project.RelativePath); } return results + Environment.NewLine; } /// <summary> /// Removes the TFS entries for a Solution file. /// </summary> /// <param name="solutionFilePath">The solution file path.</param> /// <returns>A status string noting that the Solution file has been cleaned.</returns> /// <exception cref="System.IO.FileNotFoundException">File Not Found exception.</exception> public string RemoveTfsEntriesForSolution(string solutionFilePath) { string solutionTfsVersionControlMatchStartString = "GlobalSection(TeamFoundationVersionControl) = preSolution"; string solutionTfsVersionControlMatchEndString = "EndGlobalSection"; #region Preconditions if (!File.Exists(solutionFilePath)) { throw new FileNotFoundException(solutionFilePath); } #endregion string results = "Removing Tfs Entries from Solution: " + solutionFilePath + Environment.NewLine + Environment.NewLine; string fullSolutionPath = Path.GetFullPath(solutionFilePath); Environment.CurrentDirectory = Path.GetDirectoryName(fullSolutionPath); UtilityMethods.MakeFileWritable(fullSolutionPath); UtilityMethods.BackupFile(fullSolutionPath); TextReader reader = File.OpenText(fullSolutionPath); string line = reader.ReadLine(); string newSolutionContents = string.Empty; bool insideTargetGlobalSection = false; while (line != null) { if (!insideTargetGlobalSection && line.Contains(solutionTfsVersionControlMatchStartString)) { insideTargetGlobalSection = true; } else if (insideTargetGlobalSection && line.Contains(solutionTfsVersionControlMatchEndString)) { insideTargetGlobalSection = false; } else if (!insideTargetGlobalSection) { newSolutionContents += line + Environment.NewLine; } line = reader.ReadLine(); } reader.Dispose(); File.Delete(solutionFilePath); File.WriteAllText(solutionFilePath, newSolutionContents); return results; } /// <summary> /// Removes the TFS related entries for a specific Project file. /// </summary> /// <param name="relativePathWithFileName">Name of the relative path with file.</param> /// <returns>Status string noting that the Project file has been cleaned.</returns> private string RemoveTfsRelatedEntriesForProjectFile(string relativePathWithFileName) { string results = "Removing Tfs Related Entries in Project File: " + relativePathWithFileName + Environment.NewLine; List<string> tfsEntryNames = new List<string>() { "SccProjectName", "SccLocalPath", "SccAuxPath", "SccProvider" }; string projectFilePath = Path.GetFullPath(relativePathWithFileName); if (!File.Exists(projectFilePath)) { SeriousIssues += " - PROJECT FILE COULD NOT BE FOUND, COULD BE AN EXTERNAL LIBRARY: " + projectFilePath + Environment.NewLine; return string.Empty; } UtilityMethods.MakeFileWritable(projectFilePath); TextReader reader = File.OpenText(projectFilePath); string newContents = string.Empty; string line = reader.ReadLine(); while (line != null) { bool skipLine = false; foreach (string tfsEntry in tfsEntryNames) { if (line.Contains(tfsEntry)) { skipLine = true; break; } } if (!skipLine) { newContents += line + Environment.NewLine; } line = reader.ReadLine(); } reader.Dispose(); UtilityMethods.BackupFile(projectFilePath); File.Delete(projectFilePath); File.WriteAllText(projectFilePath, newContents); return results; } /// <summary> /// Deletes the TFS related files from a Solution or Project directory. /// </summary> /// <param name="solutionOrProjectNameWithoutExtension">The solution or project name without extension.</param> /// <param name="relativePath">The relative path.</param> /// <returns>Status string noting that the files in a Solution or Project's directory have been deleted.</returns> private string DeleteTfsSolutionOrProjectFiles(string solutionOrProjectNameWithoutExtension, string relativePath) { string fullPath = Path.Combine(Environment.CurrentDirectory, relativePath); //string workingFolderPath = Path.GetDirectoryName(Path.GetFullPath(relativePath)); string workingFolderPath = Path.GetDirectoryName(fullPath); string results = "Deleting TFS files for Solution/Project " + solutionOrProjectNameWithoutExtension + Environment.NewLine; results += "-------------------------------------------" + Environment.NewLine; List<string> tfsRelatedFiles = new List<string>() { "mssccprj.scc", ".vssscc", "vssver.scc", ".vbproj.vspscc", ".csproj.vspscc" }; foreach (string relatedFileName in tfsRelatedFiles) { string fullRelatedFileName = relatedFileName; if (fullRelatedFileName.IndexOf('.') == 0) { fullRelatedFileName = solutionOrProjectNameWithoutExtension + fullRelatedFileName; } string fullFilePath = Path.Combine(workingFolderPath, fullRelatedFileName); if (File.Exists(fullFilePath)) { UtilityMethods.MakeFileWritable(fullFilePath); File.Delete(fullFilePath); results += "Deleted File: " + fullFilePath + Environment.NewLine; } } return results + Environment.NewLine; } } }
C#
UTF-8
1,555
2.96875
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace MT { public class Task : INotifyPropertyChanged { public DateTime CreationDate { get; set; } = DateTime.Now; private string _name; private string _description; private bool _isDone = false; public string Name { get { return _name; } set { if (_name == value) return; _name = value; OnPropertyChanged("Name"); } } public string Description { get { return _description; } set { if (_description == value) { return; } _description = value; OnPropertyChanged("Description"); } } public bool IsDone { get { return _isDone; } set { if (_isDone == value) return; _isDone = value; OnPropertyChanged("IsDone"); } } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
Java
UTF-8
2,210
2.125
2
[]
no_license
package at.rueckgr.chatbox.database.model; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Index; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import javax.validation.constraints.NotNull; /** * @author paulchen */ @Entity @Table(name = "shout_smilies", uniqueConstraints = { @UniqueConstraint(columnNames = { "shout", "smiley" }) }, indexes = { @Index(name = "shout_smilies_shout_idx", columnList = "shout"), @Index(name = "shout_smilies_smiley_idx", columnList = "smiley"), } ) @NamedQueries( @NamedQuery(name = ShoutSmileys.QRY_FIND_BY_SHOUT, query = "SELECT sm FROM ShoutSmileys sm WHERE sm.shout = :shout") ) @Getter @Setter @EqualsAndHashCode(exclude = { "shout", "smiley", "count" }) public class ShoutSmileys implements ChatboxEntity { private static final long serialVersionUID = -3741930808788765544L; public static final String QRY_FIND_BY_SHOUT = "ShoutSmileys.findByShout"; @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "shout_smilies_id_seq") @SequenceGenerator(name = "shout_smilies_id_seq", sequenceName = "shout_smilies_id_seq") @Column(name = "id", nullable = false) private Integer id; @NotNull @ManyToOne(optional = false) @JoinColumn(name = "shout", nullable = false) private Shout shout; @NotNull @ManyToOne @JoinColumn(name = "smiley", nullable = false) private Smiley smiley; @NotNull @Column(name = "count", nullable = false) private int count; public ShoutSmileys() { } public ShoutSmileys(Shout shout, Smiley smiley, int count) { this.shout = shout; this.smiley = smiley; this.count = count; } }
Java
UTF-8
718
2.34375
2
[]
no_license
package org.objectscape.wilco; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; /** * Created by Nutzer on 25.05.2015. */ public class AsyncTaskTest extends AbstractTest { @Test public void execute() throws InterruptedException { AtomicBoolean executed = new AtomicBoolean(false); CountDownLatch latch = new CountDownLatch(1); wilco.execute(()-> { executed.compareAndSet(false, true); latch.countDown(); }); boolean noTimeout = latch.await(1, TimeUnit.SECONDS); Assert.assertTrue(noTimeout); } }
Python
UTF-8
1,252
3.140625
3
[ "MIT" ]
permissive
import hashlib def Repr(obj): return '\n'.join(['%s: %s' % (key, value) for key, value in sorted(obj.__dict__.items())]) def HashKey(obj): if hasattr(obj, 'HashKey'): return obj.HashKey() elif hasattr(obj, '__dict__'): return HashKey(obj.__dict__) elif isinstance(obj, (list, tuple)): m = hashlib.md5() for item in obj: m.update(HashKey(item).encode('utf-8')) return m.hexdigest() elif isinstance(obj, set): m = hashlib.md5() for item in sorted(obj): m.update(HashKey(item).encode('utf-8')) return m.hexdigest() elif isinstance(obj, dict): m = hashlib.md5() for key, value in sorted(obj.items()): m.update(HashKey(key).encode('utf-8')) m.update(HashKey(value).encode('utf-8')) return m.hexdigest() else: m = hashlib.md5() m.update(repr(obj).encode('utf-8')) return m.hexdigest() class AbstractObject(object): def __str__(self): return Repr(self) def __repr__(self): return Repr(self) def __eq__(self, other): if other is None: return False return self.__dict__ == other.__dict__ def __hash__(self): return int(HashKey(self.__dict__), 16) def HashKey(self): return HashKey(self.__dict__)
Java
UTF-8
2,589
3.953125
4
[]
no_license
package binarytree; public class BinarySearchTree { private BinaryTreeNode root; // insert public void insert(int value) { if (root == null) { // first time insertion root = new BinaryTreeNode(value, null, null); } else { insertNodeRecursively(value, root); } } private void insertNodeRecursively(int value, BinaryTreeNode node) { if (value <= node.getValue()) { // no node exist on left if (node.getLeft() == null) { BinaryTreeNode newNode = new BinaryTreeNode(value, null, null); node.setLeft(newNode); } else { insertNodeRecursively(value, node.getLeft()); } } else { // greater than case if (node.getRight() == null) { BinaryTreeNode newNode = new BinaryTreeNode(value, null, null); node.setRight(newNode); } else { insertNodeRecursively(value, node.getRight()); } } } public void traverseInOrder() { if (root == null) { throw new RuntimeException("tree is empty"); } traerseInOrderRecursively(root); } private void traerseInOrderRecursively(BinaryTreeNode node) { if (node == null) { return; } traerseInOrderRecursively(node.getLeft()); System.out.println("node value found " + node.getValue()); traerseInOrderRecursively(node.getRight()); } public BinaryTreeNode searchNode(int value) { if (root == null) { throw new RuntimeException("tree is empty"); } return searchNodeRecursively(root, value); } private BinaryTreeNode searchNodeRecursively(BinaryTreeNode node, int value) { if (node.getValue() == value) { return node; } if (value <= node.getValue()) { if (node.getLeft() == null) { return null; } else { return searchNodeRecursively(node.getLeft(), value); } } else if (value > node.getValue()) { if (node.getRight() == null) { return null; } else { return searchNodeRecursively(node.getRight(), value); } } return null; } public void deleteTree() { root = null; } public int height() { if (root == null) { return 0; } return heightRecursively(root, 1); } private int heightRecursively(BinaryTreeNode root, int iteration) { // both are null if (root.getLeft() == null && root.getRight() == null) { return iteration; } // height of left int leftHeight = 0; if (root.getLeft() != null) { leftHeight = heightRecursively(root.getLeft(), iteration+1); } // height of right // height of left int rightHeight = 0; if (root.getRight() != null) { rightHeight = heightRecursively(root.getRight(), iteration+1); } return Math.max(leftHeight, rightHeight); } }
TypeScript
UTF-8
2,505
2.640625
3
[ "MIT" ]
permissive
import {AvaPwar} from './ava-pwar.js'; import {define} from 'xtal-element/define.js'; /** * `ava-pwar-simple` * Simple view of PWA Manifest * * @customElement * @polymer * @demo demo/index.html */ export class AvaPwarSimple extends AvaPwar{ static get is(){return 'ava-pwar-simple';} set manifest(val){ super.manifest = val; this.render(); } render(){ const input = this._manifest; const $ = this.$; if(!input.icons) return; let oneNineTwoIcon = input.icons.find(icon => (icon.sizes.indexOf('192') > -1)); if(!oneNineTwoIcon) oneNineTwoIcon = input.icons[input.icons.length - 1]; let imagePath = oneNineTwoIcon.src; if(imagePath.startsWith('/')) imagePath = imagePath.substring(1); const imgURL = imagePath.startsWith('http') ? imagePath : input.url + imagePath; const inverseColor = this.invertColor(input.background_color); this.innerHTML = /* html */` <div class="simple" style="background-color:${input.background_color};color:${inverseColor}"> <div class="iconLabel">Icon:</div> <div class="icon"><img height="192" width="192" src="${imgURL}"/></div> <div class="nameLabel">Name:</div> <div class="name">${$(input.name)}</div> <div class="shortNameLabel">Short Name:</div> <div class="shortName">${$(input.short_name)}</div> <a class="url" target="_blank" href="${input.url}">${$(input.url)}</a> </div> `; } $(str: string){ return str.replace(/(<([^>]+)>)/ig, ''); } invertColor(hex) { if (hex.indexOf('#') === 0) { hex = hex.slice(1); } // convert 3-digit hex to 6-digits. if (hex.length === 3) { hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]; } if (hex.length !== 6) { throw new Error('Invalid HEX color.'); } // invert color components var r = (255 - parseInt(hex.slice(0, 2), 16)).toString(16), g = (255 - parseInt(hex.slice(2, 4), 16)).toString(16), b = (255 - parseInt(hex.slice(4, 6), 16)).toString(16); // pad each with zeros and return return '#' + this.padZero(r) + this.padZero(g) + this.padZero(b); } padZero(str, len?) { len = len || 2; var zeros = new Array(len).join('0'); return (zeros + str).slice(-len); } } define(AvaPwarSimple)
Python
UTF-8
1,249
3.453125
3
[]
no_license
from sys import stdin from collections import deque # stdin = open('./input.txt', 'r') def BFS(graph, v, visited): # 큐 생성 queue = deque([v]) visited[v] = True while queue: # 큐에서 하나의 원소를 꺼낸 후 v = queue.popleft() print(v, end = " ") # graph에 v와 인접한 노드 중 방문되지 않는 노드를 queue에 append for i in graph[v]: if visited[i] == False: queue.append(i) visited[i] = True def DFS(graph, v, visited): # 탐색 노드 방문 처리 visited[v] = True print(v, end = " ") print(visited) for i in graph[v]: if not visited[i]: DFS(graph, i, visited) # 노드의 개수, 간선의 개수, 시작 노드 n, e, s = map(int, stdin.readline().rstrip().split()) graph = [[0] for _ in range(n + 1)] DFS_visited = [False] * (n + 1) BFS_visited = [False] * (n + 1) DFS_visited[0] = True BFS_visited[0] = True for _ in range(e): a, b = map(int, stdin.readline().rstrip().split()) graph[a].append(b) graph[b].append(a) for i in graph: i.sort() DFS(graph, s , DFS_visited) print() BFS(graph, s, BFS_visited)
C
UTF-8
5,601
2.71875
3
[]
no_license
#include <stdint.h> #include <stdio.h> #include <stdlib.h> #include "LT_SPI.h" #include "LTC6803.h" // Function that writes configuration of LTC6803-2/-3 void LTC6803_wrcfg(uint8_t total_ic,uint8_t config[][6]) { uint8_t BYTES_IN_REG = 6; uint8_t CMD_LEN = 4+7; uint8_t *cmd; uint16_t cfg_pec; uint8_t cmd_index; //command counter cmd = (uint8_t *)malloc(CMD_LEN*sizeof(uint8_t)); for (uint8_t current_ic = 0; current_ic < total_ic; current_ic++) { cmd[0] = 0x80 + current_ic; cmd[1] = pec8_calc(1,cmd); cmd[2] = 0x01; cmd[3] = 0xc7; cmd_index = 4; for (uint8_t current_byte = 0; current_byte < BYTES_IN_REG; current_byte++) { cmd[cmd_index] = config[current_ic][current_byte]; cmd_index = cmd_index + 1; } cfg_pec = pec8_calc(BYTES_IN_REG, &config[current_ic][0]); // calculating the PEC for each ICs configuration register data cmd[cmd_index ] = (uint8_t)cfg_pec; cmd_index = cmd_index + 1; cs_low(); spi_write_array(CMD_LEN, cmd); cs_high(); } free(cmd); } //!Function that reads configuration of LTC6803-2/-3 int8_t LTC6803_rdcfg(uint8_t total_ic, //Number of ICs in the system uint8_t r_config[][7] //A two dimensional array that the function stores the read configuration data. ) { uint8_t BYTES_IN_REG = 7; uint8_t cmd[4]; uint8_t *rx_data; int8_t pec_error = 0; uint8_t data_pec; uint8_t received_pec; rx_data = (uint8_t *) malloc((BYTES_IN_REG*total_ic)*sizeof(uint8_t)); for (uint8_t current_ic = 0; current_ic < total_ic; current_ic++) //executes for each LTC6803 in the daisy chain and packs the data { //into the r_config array as well as check the received Config data //for any bit errors cmd[0] = 0x80 + current_ic; cmd[1] = pec8_calc(1,cmd); cmd[2] = 0x02; cmd[3] = 0xCE; cs_low(); spi_write_read(cmd, 4, rx_data, (BYTES_IN_REG*total_ic)); cs_high(); for (uint8_t current_byte = 0; current_byte < BYTES_IN_REG; current_byte++) { r_config[current_ic][current_byte] = rx_data[current_byte]; } received_pec = r_config[current_ic][6]; data_pec = pec8_calc(6, &r_config[current_ic][0]); if (received_pec != data_pec) { pec_error = -1; } } free(rx_data); return(pec_error); } //!Function that starts Cell Voltage measurement void LTC6803_stcvad() { cs_low(); spi_write(0x10); spi_write(0xB0); cs_high(); } //! Function that Temp channel voltage measurement void LTC6803_sttmpad() { cs_low(); spi_write(0x30); spi_write(0x50); cs_high(); } //!Function that reads Temp Voltage registers int8_t LTC6803_rdtmp(uint8_t total_ic, uint16_t temp_codes[][3]) { int data_counter = 0; int pec_error = 0; uint8_t data_pec = 0; uint8_t received_pec = 0; uint8_t cmd[4]; uint8_t *rx_data; rx_data = (uint8_t *) malloc((7)*sizeof(uint8_t)); for (int i=0; i<total_ic; i++) { cmd[0] = 0x80 + i; cmd[1] = pec8_calc(1,cmd); cmd[2] = 0x0E; cmd[3] = 0xEA; cs_low(); spi_write_read(cmd, 4,rx_data,6); cs_high(); received_pec = rx_data[5]; data_pec = pec8_calc(5, &rx_data[0]); if (received_pec != data_pec) { pec_error = -1; } //int cell_counter = 0; data_counter = 0; int temp,temp2; temp = rx_data[data_counter++]; temp2 = (rx_data[data_counter]& 0x0F)<<8; temp_codes[i][0] = temp + temp2 -512; temp2 = (rx_data[data_counter++])>>4; temp = (rx_data[data_counter++])<<4; temp_codes[i][1] = temp+temp2 -512; temp2 = (rx_data[data_counter++]); temp = (rx_data[data_counter++]& 0x0F)<<8; temp_codes[i][2] = temp+temp2 -512; } free(rx_data); return(pec_error); } //! Function that reads Cell Voltage registers uint8_t LTC6803_rdcv( uint8_t total_ic, uint16_t cell_codes[][12]) { int data_counter =0; int pec_error = 0; uint8_t data_pec = 0; uint8_t received_pec = 0; uint8_t *rx_data; uint8_t cmd[4]; rx_data = (uint8_t *) malloc((19)*sizeof(uint8_t)); for (int i=0; i<total_ic; i++) { cmd[0] = 0x80 + i; cmd[1] = pec8_calc(1,cmd); cmd[2] = 0x04; cmd[3] = 0xDC; cs_low(); spi_write_read(cmd, 4,rx_data,19); cs_high(); received_pec = rx_data[18]; data_pec = pec8_calc(18, &rx_data[0]); if (received_pec != data_pec) { pec_error = -1; } //int cell_counter = 0; data_counter = 0; uint16_t temp,temp2; for (int k = 0; k<12; k=k+2) { temp = rx_data[data_counter++]; temp2 = (uint16_t)(rx_data[data_counter]&0x0F)<<8; cell_codes[i][k] = temp + temp2 - 512; temp2 = (rx_data[data_counter++])>>4; temp = (rx_data[data_counter++])<<4; cell_codes[i][k+1] = temp+temp2 - 512; } } free(rx_data); return(pec_error); } //!Function that calculates PEC byte uint8_t pec8_calc(uint8_t len, uint8_t *data) { uint8_t remainder = 0x41;//PEC_SEED; /* * Perform modulo-2 division, a byte at a time. */ for (int byte = 0; byte < len; ++byte) { /* * Bring the next byte into the remainder. */ remainder ^= data[byte]; /* * Perform modulo-2 division, a bit at a time. */ for (uint8_t bit = 8; bit > 0; --bit) { /* * Try to divide the current data bit. */ if (remainder & 128) { remainder = (remainder << 1) ^ PEC_POLY; } else { remainder = (remainder << 1); } } } /* * The final remainder is the CRC result. */ return (remainder); }
PHP
UTF-8
6,566
2.53125
3
[ "MIT" ]
permissive
<?php class CompTags{ public static function resolve($html){ $html = self::suite($html); $html = self::condition($html); $html = self::http($html); $html = self::breadcrumb($html); $html = self::app($html); return $html; } public function render($html = null){ $html = self::suite($html); $html = self::condition($html); $html = self::http($html); $html = self::breadcrumb($html); $html = self::suite($html); $html = self::app($html); return $html; } public static function app($html){ /* $app = Suite_globals::get('app'); echo '<pre>'; print_r($app); echo '</pre>'; */ $appFunction = create_function('$matches',' $value0 = isset($matches[0])?$matches[0]:null; $value1 = isset($matches[1])?$matches[1]:null; $value2 = isset($matches[2])?$matches[2]:null; $value1 = substr($value1, 1); $result = ""; if($value1==null){ $result = Suite_globals::get("app/".$value2); }else{ $result = (Suite_globals::get("app/".$value1."/".$value2)); } return $result; '); $html = preg_replace_callback('/\[app(.*?):(.*?)\]/is',$appFunction,$html); return $html; } public static function http($html = null){ $menuFunction = create_function('$matches',' $value0 = isset($matches[0])?$matches[0]:null; $value1 = isset($matches[1])?$matches[1]:null; $value2 = isset($matches[2])?$matches[2]:null; $value3 = isset($matches[3])?$matches[3]:null; $value4 = isset($matches[4])?$matches[4]:null; $value5 = isset($matches[5])?$matches[5]:null; $result = ""; $result = Suite_globals::get("http/".$value1); return $result; '); $html = preg_replace_callback('/\[http:(.*?)?\]/is',$menuFunction,$html); return $html; } public static function breadcrumb($html){ $domain = Suite_globals::get('http/domain/url'); $appDir = Suite_globals::get('app/dir'); $modulesDir = $appDir . '_modules/'; $prefix = Suite_globals::get('http/prefix'); $action = Suite_globals::get('http/target'); $actionArray = explode('/', $action); $actionArray = array_filter($actionArray); if($actionArray[0] == $prefix){ unset($actionArray[0]); $actionArray = array_values($actionArray); $target = implode('/', $actionArray); } $breadcrumb_html = '<ol itemscope itemtype="http://schema.org/BreadcrumbList">'; $join = ''; foreach ($actionArray as $key => $value) { $join .= $value.'/'; $title = $value; $optionsFile = $modulesDir . $join . 'options.json'; if(file_exists($optionsFile)){ $optionsJson = file_get_contents($optionsFile); $options = json_decode($optionsJson,true); $title = isset($options['menu']['title'])?$options['menu']['title']:$title; } $link = $domain.$join; $image = ''; $breadcrumb_html .= '<li itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem">'; $breadcrumb_html .= '<a itemscope itemtype="http://schema.org/Thing" itemprop="item" href="'.$link.'">'; $breadcrumb_html .= '<span itemprop="name">'.$title.'</span>'; // $breadcrumb_html .= '<img itemprop="image" src="'.$image.'" alt="'.$title.'"/>'; $breadcrumb_html .= '</a>'; $breadcrumb_html .= '<meta itemprop="position" content="'.$key.'">'; $breadcrumb_html .= '</li>'; if($key < count($actionArray)-1) $breadcrumb_html .= '›'; } $breadcrumb_html .= '</ol>'; $html = str_replace('[breadcrumb]', $breadcrumb_html, $html); return $html; } public static function suite($html = null){ $menuFunction = create_function('$matches',' $value0 = isset($matches[0])?$matches[0]:null; $value1 = isset($matches[1])?$matches[1]:null; $value2 = isset($matches[2])?$matches[2]:null; $value3 = isset($matches[3])?$matches[3]:null; $value4 = isset($matches[4])?$matches[4]:null; $value5 = isset($matches[5])?$matches[5]:null; $value2 = substr($value2, 1); $result = ""; if($value1 == "view"){ if($value2 == "_CURRENT_"){ return Suite_view::view(); }else{ return Suite_view::content($value2); } }if($value1 == "app-get"){ $appDir = Suite_globals::get("app/dir"); $htmlDir = $appDir.$value2; if(file_exists($htmlDir)){ $result = Suite_libs::run("Http/Request/includes",$htmlDir); } }if($value1 == "globals"){ $result = Suite_globals::get($value2); if(is_array($result)){ $result = print_r($result,true); } return $result; } return $result; '); $html = preg_replace_callback('/\[suite:(.*?)?(:.*?)?\]/is',$menuFunction,$html); if(strpos($html, '[suite')!=false){ $html = self::suite($html); } return $html; } public static function condition($html){ // procura pela tag [contition] e verifica a condição para exibir o conteúdo $conditionFunction = create_function('$matches',' $value0 = isset($matches[0])?$matches[0]:null; $termo1 = isset($matches[1])?$matches[1]:null; $operator = isset($matches[2])?$matches[2]:null; $termo2 = isset($matches[3])?$matches[3]:null; $retult1 = isset($matches[4])?$matches[4]:null; $retult2 = isset($matches[6])?$matches[6]:null; if(strtolower($operator) == "like"){ $cond = eval("return strpos($termo1,$termo2) ;"); }else{ $cond = eval("return $termo1 $operator $termo2 ;"); } if($cond) $result = $retult1; else $result = ($retult2 != null)?$retult2:""; return $result; '); $html = preg_replace_callback('/\[condition:(.*?)(==|===|!=|!==|>=|<=|>|<|like)(.*?)\](.*?)(\[condition-else\](.*?))?\[\/condition\]/is',$conditionFunction,$html); return $html; } }
Ruby
UTF-8
2,468
3.484375
3
[]
no_license
class Defusal def initialize @running = true end def run puts ' - Desarmar a bomba 💣 - ' puts "\n" puts "\n" while @running display_instructions defusal_sequence = gets.chomp print `clear` parsed_sequence = sequence_parser(defusal_sequence) action(parsed_sequence) end end private def action(parsed_sequence) # stop app return stop if parsed_sequence.one? && parsed_sequence[0] == 'sair' available_colors = %w[branco vermelho preto laranja verde roxo] # check errors in unput sequence parsed_sequence.each do |color| next if available_colors.include? color return puts "#{color} não é uma cor válida. \n \n" end defusal(parsed_sequence) end def defusal(sequence) return puts 'Bomba desarmada' if sequence.one? # check if next wire meets conditions case sequence[0] when 'branco' %w[preto branco].include? sequence[1] ? failure : next_wire(sequence) when 'vermelho' sequence[1] == 'verde' ? next_wire(sequence) : failure when 'preto' %w[branco verde laranja].include? sequence[1] ? failure : next_wire(sequence) when 'laranja' %w[vermelho preto].include? sequence[1] ? next_wire(sequence) : failure when 'verde' %w[branco laranja].include? sequence[1] ? next_wire(sequence) : failure when 'roxo' %w[vermelho preto].include? sequence[1] ? next_wire(sequence) : failure end end def next_wire(sequence) # move to the next wire remaining_wires = sequence.drop(1) defusal(remaining_wires) end def failure puts "\n" puts 'Bomba explodiu' puts "\n" end def sucess puts "\n" puts 'Bomba desarmada' puts "\n" puts '---------------' end def sequence_parser(defusal_sequence) # split the string, remove whitespace and downcase defusal_sequence.split(',').map { |sequence| sequence.gsub(/\s+/, '').downcase } end def stop @running = false end def display_instructions puts 'Introduza a sequência de cores dos fios, separadas por virgula e' puts 'com o seguinte formato: "cor, cor, cor"' puts 'cores disponíveis:' puts ' branco, preto, vermelho, laranja, verde, roxo ' puts ' ' puts 'Para terminar a aplicação digite "sair"' puts "\n" end end
Java
UTF-8
384
2.765625
3
[]
no_license
package com.Logic.Constructor; import com.world.obstacle.Obstacle; import com.world.obstacle.Square; import com.world.obstacle.TriangleObstacle; public class SquareObstacleFactory extends ObstacleFactory{ public Obstacle getObstacle(String obstacleType){ if(obstacleType.equals("SQUARE1")){ return new Square(); } else return null; } }
PHP
UTF-8
604
2.75
3
[]
no_license
<?php function counting_rating($product_id,$c_id,$conn){ $output = 0; $rate = mysqli_query($conn,"SELECT AVG(rating) AS prod_rate FROM rating WHERE product_fk = '$product_id'"); $result = mysqli_num_rows($rate); $row = mysqli_fetch_assoc($rate); if ($result > 0) { foreach ($row as $value) { $output = round($value["prod_rate"]); } } return $output; } function counting_row($product_id,$c_id,$conn){ $output = 0; $rate = mysqli_query($conn,"SELECT * FROM rating WHERE product_fk = '$product_id'"); return mysqli_num_rows($rate); } ?>
Java
UTF-8
1,613
2.484375
2
[]
no_license
package com.trainings.rest_paging.dto; import java.util.HashSet; import java.util.Set; /** * @author jlising - 4/8/16. */ public class StudentInfo{ private String id; private String student_no; private String first_name; private String middle_name; private String last_name; private AddressInfo address; Set<CourseInfo> courses = new HashSet<CourseInfo>(0); public AddressInfo getAddress() { return address; } public void setAddress(AddressInfo address) { this.address = address; } public Set<CourseInfo> getCourses() { return courses; } public void setCourses(Set<CourseInfo> courses) { this.courses = courses; } public String getFirst_name() { return first_name; } public void setFirst_name(String first_name) { this.first_name = first_name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getLast_name() { return last_name; } public void setLast_name(String last_name) { this.last_name = last_name; } public String getMiddle_name() { return middle_name; } public void setMiddle_name(String middle_name) { this.middle_name = middle_name; } public String getStudent_no() { return student_no; } public void setStudent_no(String student_no) { this.student_no = student_no; } //Constructor for ConstructExpression.create public StudentInfo(String id) { this.id = id; } }
Shell
UTF-8
97
2.609375
3
[]
no_license
#!/bin/bash for file in *.txt; do mkdir -- "${file%.txt}"; mv -- "$file" "${file%.txt}"; done
C#
UTF-8
2,865
3.5625
4
[ "MIT" ]
permissive
using System; using System.Collections.Generic; // nice Авторско Решение using System.Linq; // 100/100 using System.Text; class AnonymousThreat { static void Main() { List<string> sensitiveData = Console.ReadLine().Split().ToList(); string inputLine = string.Empty; while ((inputLine = Console.ReadLine()) != "3:1") { string[] inputParameters = inputLine.Split(); string command = inputParameters[0]; if (command == "merge") { int startIndex = int.Parse(inputParameters[1]); int endIndex = int.Parse(inputParameters[2]); sensitiveData = Merge(sensitiveData, startIndex, endIndex); } else if (command == "divide") { int index = int.Parse(inputParameters[1]); int partitions = int.Parse(inputParameters[2]); sensitiveData = Divide(sensitiveData, index, partitions); } } Console.WriteLine(string.Join(" ", sensitiveData)); } private static int ChangeIndex(int index, int maxLength) { if (index < 0) { index = 0; } if (index >= maxLength) { index = maxLength - 1; } return index; } private static List<string> Merge(List<string> sensitiveData, int startIndex, int endIndex) { startIndex = ChangeIndex(startIndex, sensitiveData.Count); endIndex = ChangeIndex(endIndex, sensitiveData.Count); List<string> newList = new List<string>(); for (int i = 0; i < startIndex; i++) { newList.Add(sensitiveData[i]); } StringBuilder result = new StringBuilder(); for (int i = startIndex; i <= endIndex; i++) { result.Append(sensitiveData[i]); } newList.Add(result.ToString()); for (int i = endIndex + 1; i < sensitiveData.Count; i++) { newList.Add(sensitiveData[i]); } return newList; } private static List<string> Divide(List<string> sensitiveData, int index, int partitions) { string element = sensitiveData[index]; int partitionLength = element.Length / partitions; List<string> dividedPartitions = new List<string>(); for (int i = 0; i < partitions; i++) { if (i == partitions - 1) { dividedPartitions.Add(element.Substring(i * partitionLength)); } else { dividedPartitions.Add(element.Substring(i * partitionLength, partitionLength)); } } sensitiveData.RemoveAt(index); sensitiveData.InsertRange(index, dividedPartitions); return sensitiveData; } }
Java
UTF-8
2,039
2
2
[]
no_license
package a.m.restaurant_automation; import android.os.Bundle; import android.view.MenuItem; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.navigation.NavController; import androidx.navigation.Navigation; import androidx.navigation.ui.NavigationUI; import com.google.android.material.bottomnavigation.BottomNavigationView; public class ChefActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener { public BottomNavigationView bottomNavigationView; public NavController navController; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chef); setUpNavigation(); } public void setUpNavigation() { bottomNavigationView= findViewById(R.id.BottomnavigateMenuChef); navController= Navigation.findNavController(this,R.id.chefHostFragment); NavigationUI.setupWithNavController(bottomNavigationView,navController); NavigationUI.setupActionBarWithNavController(this,navController); NavigationUI.setupWithNavController(bottomNavigationView,navController); bottomNavigationView.setOnNavigationItemSelectedListener(this); } @Override public void onBackPressed() { super.onBackPressed(); } @Override public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { // Fragment fragment=null; menuItem.setCheckable(true); int id = menuItem.getItemId(); switch (id){ case R.id.Dashboard: navController.navigate(R.id.chefDashboard); return true; case R.id.OrderHistory: navController.navigate(R.id.chefOrderHistoryFragment); return true; case R.id.Moremenu: navController.navigate(R.id.chefMoreItemsFragment); return true; } return false; } }
C++
UTF-8
491
3.234375
3
[ "MIT" ]
permissive
#include <iostream> using namespace std; int maxabsinlst(int[], int); int main() { int lst[] = { -19, -3, 20, -1, 5, -25 }, size = 0; size = sizeof(lst) / sizeof(int); printf("%i", maxabsinlst(lst, size)); return 0; } int maxabsinlst(int lst[], int size) { int maximum = 0, tmpAbs = 0; for(int i = 0; i < size; i++) { tmpAbs = (lst[i] * (-1)); if(tmpAbs > maximum) { maximum = tmpAbs; } } return maximum; }
JavaScript
UTF-8
2,112
2.671875
3
[ "MIT" ]
permissive
var target_actual = {}; // SELECT $(document).on("mousedown",".select .head_select", function(){ target_actual = $(this).parent(); var elemento = $(this); var target = elemento.parent().find('.opciones'); console.log(target); if (target.hasClass('slider_down')) { target.hide(); target.removeClass('slider_down'); }else{ target.show(); target.addClass('slider_down'); } }); $(document).on("click",".select .opciones .opcion", function(){ var elemento = $(this); var data_elemento = $(this).find('span').html(); var select = $(this).closest('.select'); var target = select.find('.opciones'); var data_select = $(this).closest('.select').attr('data'); target.removeClass('slider_down'); if (data_elemento != data_select) { select.attr('data',data_elemento); select.find('.head_select').find('.nombre_select').html(data_elemento); select.find('input[type="hidden"]').val(data_elemento); console.log(select.find('input[type="hidden"]')); if (elemento.hasClass('default')){ select.find('input[type="hidden"]').val(''); } } if (elemento.hasClass('t_submit')) { elemento.closest('form').submit(); } $(this).parent().hide(); }); function data_select(){ $(".select").each(function(index,value){ var select = $(this); var data = select.attr('data'); if (data.length > 0){ select.find('.head_select').find('.nombre_select').html(data); select.find('input[type="hidden"]').val(data); } }); } data_select(); function selected(){ $(".select .opciones .opcion").each(function(index,value){ var select = $(this).closest('.select'); var elemento = $(this); if (elemento.attr('selected') == 'selected'){ var data = elemento.find('span').html(); select.attr('data',data); select.find('.head_select').find('.nombre_select').html(data); select.find('input[type="hidden"]').val(data); } }); } selected();
Java
UTF-8
336
1.867188
2
[]
no_license
package com.lcz.blog.service; import com.lcz.blog.bean.PermissionBean; import java.util.List; /** * Created by luchunzhou on 15/12/9. */ public interface PermissionService { /** * 获取用户权限 * @param id * @return * @throws Exception */ List<PermissionBean> queryPermByUserId(Integer id); }
Markdown
UTF-8
1,331
3.703125
4
[ "MIT" ]
permissive
### Java foreach原理 1. 常规写法 for(int i=0; i<list.size; i++){ //..... } 2. 简单写法 List<String> list = new ArrayList<String>(); for(String e : list){ // } 3. foreach原理 1. 对于list集合 List<String> a = new ArrayList<String>(); a.add("1"); a.add("2"); a.add("3"); for(String temp : a){ System.out.print(temp); } 反编译: List a = new ArrayList(); a.add("1"); a.add("2"); a.add("3"); String temp; for(Iterator i$ = a.iterator(); i$.hasNext(); System.out.print(temp)){ temp = (String)i$.next(); } 2. 遍历数组 String[] arr = {"1","2"}; for(String e : arr){ System.out.println(e); } 反编译后代码: String arr[] = { "1", "2" }; String arr$[] = arr; int len$ = arr$.length; for(int i$ = 0; i$ < len$; i$++) { String e = arr$[i$]; System.out.println(e); } 总结,遍历集合是对应的集合必须实现Iterator接口,遍历数组直接转成for i的形式
Java
UTF-8
793
2.09375
2
[ "Apache-2.0" ]
permissive
package io.github.brandonjmitchell.amblur.dispatcher; import java.lang.reflect.InvocationTargetException; import javax.xml.stream.XMLStreamException; import io.github.brandonjmitchell.amblur.event.ParserEvent; import io.github.brandonjmitchell.amblur.exception.DispatcherException; import io.github.brandonjmitchell.amblur.exception.ParserException; import io.github.brandonjmitchell.amblur.handler.ParsingHandler; public interface ParsingDispatcher { public <E extends ParserEvent> void register(int eventType, ParsingHandler<E> handler) throws DispatcherException; public <E extends ParserEvent> void dispatch(E event) throws DispatcherException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, ParserException, XMLStreamException; }
PHP
UTF-8
1,370
3.25
3
[]
no_license
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <?php // 1 Od niza zadatih reči, napraviti niz čiji će svaki element predstavljati span. Svaki span će imati klasu "crveni", "zeleni" u zavisnosti od toga da li je reč kraća ili duža od 5 slova. Prikazati dobijeni niz. $nizz = ['Sto','Stolica','Kauc','Televizor','Racunar']; foreach($nizz as $ind=>$element){ if(strlen($nizz[$ind]) > 5){ echo "<span style='color:red'>".$element."</span>"; } elseif(strlen($nizz[$ind]) < 5){ echo "<span style='color:green'>".$element."</span>"; } } // 2 Napraviti niz od svih brojeva koji su veći od aritmetičke sredine niza (prosečne vrednosti). $nizzz = [5,15,6,8,9,10,33,4]; $y =[]; $zbir = 0; $brojac = 0; for($i=0; $i<count($nizzz); $i++){ $zbir += $nizzz[$i]; $brojac++; } $as = $zbir / $brojac; for($i=0; $i<count($nizzz); $i++){ if($nizzz[$i] > $as){ array_push($y, $nizzz[$i]); } } echo "y:".join(",", $y)."<br/>"; ?> </body> </html>
Python
UTF-8
2,751
3.015625
3
[]
no_license
import streamlit as st import torch from htbuilder import HtmlElement, div, ul, li, br, hr, a, p, img, styles, classes, fonts from htbuilder.units import percent, px import torch.nn as nn import torch.nn.functional as F import torchvision from PIL import Image import numpy as np import pandas as pd from model import CNN st.set_option('deprecation.showfileUploaderEncoding', False) st.title('Applying Machine Learning to Diagnose\ Lung Disease using Chest X-rays') st.header('SEM-6 Mini Project') st.subheader('KJ Somaiya College of Engineering') st.markdown("This Model is a CNN model that, when provided an chest X-ray can predict with an 90+% accuray if the patient has pneumonia and if yes then its type ") def layout(*args): style = """ <style> # MainMenu {visibility: hidden;} footer {visibility: hidden;} .stApp { bottom: 105px; } </style> """ style_div = styles(position="fixed", left=0, bottom=0, margin=px(0, 0, 0, 0), width=percent(100), color="white", text_align="center", height=percent(3.8), opacity=1) style_hr = styles(display="block", margin=px(0, 0, 0, 0), border_style="inset", border_width=px(2)) body = p() foot = div( style=style_div )( hr( style=style_hr ), body ) st.markdown(style, unsafe_allow_html=True) for arg in args: if isinstance(arg, str): body(arg) elif isinstance(arg, HtmlElement): body(arg) st.markdown(str(foot), unsafe_allow_html=True) def footer(): myargs = [ "Made by Nimit Dave " ] layout(*myargs) footer() def img_to_torch(pil_image): img = pil_image.convert('L') x = torchvision.transforms.functional.to_tensor(img) x = torchvision.transforms.functional.resize(x, [150, 150]) x.unsqueeze_(0) return x def predict(image, model): x = img_to_torch(image) pred = model(x) pred = pred.detach().numpy() df = pd.DataFrame(data=pred[0], index=['Bacterial', 'Normal', 'Viral'], columns=['confidence']) st.write(f'''### Bacterial Probability : **{np.round(pred[0][0]*100, 3)}%**''') st.write(f'''### Viral Probability : **{np.round(pred[0][2]*100, 3)}%**''') st.write(f'''### Normal Probability: **{np.round(pred[0][1]*100, 3)}%**''') st.write('') st.bar_chart(df) PATH_TO_MODEL = './0.906_loss0.081.pt' model = torch.load(PATH_TO_MODEL) model.eval() uploaded_file = st.file_uploader('Upload X-ray image to be Diagnosed ', type=['jpeg', 'jpg', 'png']) if uploaded_file is not None: image = Image.open(uploaded_file) st.image(image, use_column_width=True) if st.button('Run Analysis'): predict(image, model)
PHP
UTF-8
5,393
2.796875
3
[ "MIT" ]
permissive
<?php /* * Copyright (c) 2015 Mihai Stancu <stancu.t.mihai@gmail.com> * * This source file is subject to the license that is bundled with this source * code in the LICENSE.md file. */ namespace MS\RpcBundle\Service; /** * The ProxyGenerator takes an interface or a class as an input and generates a * Proxy class which implements all of the public abstract methods from the * supplied interface or class. */ class ProxyGenerator { /** * @var string */ protected $directory; /** * @var string */ protected $namespace; /** * @var */ protected $trait; /** * @var string */ protected $classTemplate = '<?php namespace {$namespace}; class {$name} {$keyword} {$base} { {$trait} {$methods} } '; /** * @var string */ protected $methodTemplate = ' public function {$name}({$parameters}) { return $this->call(__FUNCTION__, func_get_args()); } '; protected $parameterTemplate = '{$type} {$name} {$default}'; /** * @param string $directory * @param string $namespace * @param string $baseTrait */ public function __construct($directory, $namespace, $baseTrait) { $this->directory = $directory; $this->namespace = trim($namespace, '\\'); $this->trait = $baseTrait; } /** * @param string $class * * @return string */ public function generateProxyClass($class) { $definition = $this->getClassDefinition($class); if (empty($definition)) { return $class; } $file = $this->directory.str_replace('\\', '/', $class).'.php'; $directory = dirname($file); if (!is_dir($directory)) { mkdir($directory, 0755, true); } file_put_contents($file, $definition); return $this->getProxyClassName($class); } /** * @param string $class * * @return string */ protected function getProxyClassName($class) { return $this->namespace.'\\'.$class; } /** * @param string $interfaceOrClass * * @return string|null */ protected function getClassDefinition($interfaceOrClass) { $reflectionClass = new \ReflectionClass($interfaceOrClass); if ($reflectionClass->isFinal() or $reflectionClass->isTrait()) { return; } $namespace = $this->namespace.'\\'.$reflectionClass->getNamespaceName(); $name = $reflectionClass->getShortName(); $trait = ''; if (!array_key_exists($this->trait, $reflectionClass->getTraits())) { $trait = 'use \\'.$this->trait.';'; } $keyword = $reflectionClass->isInterface() ? 'implements' : 'extends'; $base = '\\'.$reflectionClass->getName(); $methods = []; foreach ($reflectionClass->getMethods() as $reflectionMethod) { $methods[] = $this->getMethodDefinition($reflectionMethod); } if (empty($methods)) { return; } $methods = array_filter($methods); $methods = implode("\n", $methods); $replace = [ '{$namespace}' => $namespace, '{$name}' => $name, '{$trait}' => $trait, '{$keyword}' => $keyword, '{$base}' => $base, '{$methods}' => $methods, ]; $template = $this->classTemplate; $definition = str_replace(array_keys($replace), array_values($replace), $template); return $definition; } /** * @param \ReflectionMethod $reflectionMethod * * @return string|null */ protected function getMethodDefinition(\ReflectionMethod $reflectionMethod) { if (!$reflectionMethod->isPublic() or !$reflectionMethod->isAbstract() or $reflectionMethod->isFinal() or $reflectionMethod->isStatic()) { return; } $name = $reflectionMethod->getName(); $parameters = []; foreach ($reflectionMethod->getParameters() as $reflectionParameter) { $parameters[] = $this->getParameterDefinition($reflectionParameter); } $parameters = array_filter($parameters); $parameters = implode(', ', $parameters); $replace = [ '{$name}' => $name, '{$parameters}' => $parameters, ]; $template = $this->methodTemplate; $definition = str_replace(array_keys($replace), array_values($replace), $template); return $definition; } /** * @param \ReflectionParameter $r * * @return string */ protected function getParameterDefinition(\ReflectionParameter $r) { $type = ''; if ($r->isArray()) { $type = 'array'; } elseif ($r->isCallable()) { $type = 'callable'; } elseif ($r->getClass()) { $type = '\\'.$r->getClass()->getName(); } $name = $r->getName(); $default = ''; if ($r->isDefaultValueAvailable() and $r->isDefaultValueConstant()) { $default = ' = \\'.$r->getDefaultValueConstantName(); } elseif ($r->isDefaultValueAvailable()) { $default = ' = '.var_export($r->getDefaultValue(), true); } $definition = trim($type.' $'.$name.$default); return $definition; } }
Markdown
UTF-8
2,715
2.890625
3
[ "ISC" ]
permissive
## Customizing this release. Currently, there are two basic ways of customizing epoch: * Updating the official `sys.config` file * Specifying your own config file at startup Both methods require complying with the format of Erlang/OTP config files, which will be briefly described by example below. ### The official `sys.config` file The location of the `sys.config`, relative to the directory where `epoch` is installed, is `releases/0.2.0/sys.config`. ### Specifying your own config Normally, you would start epoch calling `bin/epoch start`. You can add a config file by calling ``` ERL_FLAGS="-config <full_path_to_config>" bin/epoch start ``` (Use a fully qualified name to avoid confusion) The file name must end with `.config`. The extension can be specified or left out in `<full_path_to_config>` above. ### Things you can configure The main things you may want to configure are: * The port number used for the HTTP service end point (default: `3013`) * The list of peers to contact at startup (default: none) While some other things are configurable in theory, please leave them alone unless you fully understand what you're doing. The following example sets the port to `9900` and adds two peer URIs: ```erlang [ {aecore, [ {peers, ["http://somehost.net:4000/", "http://someotherhost.net:5000/"]} ]}, {aehttp, [ {swagger_port_external, 9900} ]} ]. ``` Note that whitespace and indentation are ignored by Erlang, but it's picky about delimiters. The format is one of: ```erlang [ App1, ..., Appn ]. ``` (Be sure to remember the period (`'.'`) at the end.) where `aecore` and `aehttp` above are application names. Each application config is on the form: ```erlang { AppName, [ Var1, ..., Varn ] } ``` where a Var is a `{ Key, Value }` pair. note that there is no trailing comma after the last element. For clarity, specifying only the peers would look like this: ```erlang [ {aecore, [ {peers, ["http://somehost.net:4000/", "http://someotherhost.net:5000/"]} ]} ]. ``` (Never a trailing comma directly before a closing `}` or `]`.) ### Manually connecting to a peer It is possible to instruct a running `epoch` node to connect to another peer, even if it didn't know about it before. Using one of the example peers above: ``` bin/epoch rpc aec_sync connect_peer http://somehost.net:4000/ ``` If the connected peer knows of other peers, it will share them in the handshake, and your node will try to connect to them as well. If you want to check if something is happening when you do this, you may follow the output in `log/epoch.log`. It may appear noisy unless you're used to Erlang logs, but at least there will be activity.
Ruby
UTF-8
2,555
3.59375
4
[]
no_license
def combine_anagrams(words) # <YOUR CODE HERE> #~ puts "Original" #~ puts #~ puts words #~ puts words.size #sort the letters into a sorted array sorted = Array.new x = String.new y = String.new for i in 0..words.size-1 x = words[i].to_str y = x.downcase #~ puts y #~ abort("yup") #~ y = x.downcase #~ x.downcase #~ puts y sorted.push(y.unpack("c*").sort.pack("c*")) end #~ puts "---------" #~ puts "Sorted" #~ puts #~ puts sorted #~ puts sorted.size #~ puts "*****************************************" #now generate a new array anagram = Array.new while words.size > 0 #initialise the new group group = Array.new group.push(words[0]) #~ puts "---------" #~ puts "New Group" #~ puts group.inspect #what it is when sorted x = words[0].to_str y = x.downcase sortval = y.unpack("c*").sort.pack("c*") #~ puts "sorted as " + sortval #copy for j in 1..words.size-1 if sorted[j]==sortval group.push(words[j]) #~ puts "---------" #~ puts "Building the Group" #~ puts group.inspect end end anagram.push(group) #~ puts "---------" #~ puts "Anagram" #~ puts #~ puts anagram.inspect #~ puts anagram.size #~ puts "______________" #clean #~ counter = 0 j = 0 while j<words.size #~ puts "J is now ", j #~ puts "sorted = " ,sorted[j] if sorted[j]==sortval #~ puts "-to delete" #~ puts words[j] #~ puts "-----" words.delete_at(j) sorted.delete_at(j) #~ words.delete_at(j-counter) #~ sorted.delete_at(j-counter) #~ puts "new" #~ puts words.inspect #~ puts "______________" j = j - 1 end j = j + 1 #~ puts "J is now ", j #~ puts "***********************" end #~ puts "---------" #~ puts "Left over words" #~ puts #~ puts words.inspect #~ puts words.size #~ test = test + 1 end #~ puts "---------" #~ puts "Anagram" #~ puts #~ puts anagram.inspect #~ puts anagram.size return anagram end words = ['cars', 'for', 'potatoes', 'racs', 'four','scar', 'creams', 'scream'] puts words.inspect puts combine_anagrams(words).inspect words = ['fat','mumma'] puts words.inspect puts combine_anagrams(words).inspect words = [] puts words.inspect puts combine_anagrams(words).inspect words = ['cat','dog','cAt'] puts words.inspect puts combine_anagrams(words).inspect words = ['a','A'] puts words.inspect puts combine_anagrams(words).inspect
C#
UTF-8
1,324
3
3
[]
no_license
using DAL.DataContext; using DAL.Interfaces; using System; using System.Collections.Generic; using System.Linq; namespace DAL.Repository { public class BaseRepository<T> : IRepository<T> where T : class { RCContext db; public BaseRepository(RCContext context) { db = context; } public void Add(T item) { db.Set<T>().Add(item); db.SaveChanges(); } public List<T> GetAllItems() { return db.Set<T>().ToList(); } public T GetItem(Guid Id) { return db.Set<T>().Find(Id); } public void Remove(Guid Id) { db.Set<T>().Remove(db.Set<T>().Find(Id)); db.SaveChanges(); } public void Update(T item) { db.Set<T>().Update(item); db.SaveChanges(); } private bool disposed = false; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public void Dispose(bool disposing) { if (!disposed) { if (disposing) { db.Dispose(); } disposed = true; } } } }
Java
UTF-8
807
2.265625
2
[]
no_license
package com.example.demo.core.applicationServices; import com.example.demo.core.domainEntities.RfidCard; import com.example.demo.core.domainEntities.RfidCard.State; import com.example.demo.core.domainServices.IRfidCardRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class RfidCardService { private IRfidCardRepository cardRepository; @Autowired public RfidCardService(IRfidCardRepository cardRepository) { this.cardRepository = cardRepository; } public RfidCard activateRfidCard(String cardId) { var card = this.cardRepository.getRfidCardById(cardId); card.setLifeCycleState(State.ACTIVE); this.cardRepository.saveRfidCard(card); return card; } }
C#
UTF-8
1,908
3
3
[ "MIT" ]
permissive
using System.Collections.Generic; namespace PiaSharp.Core.Objects { /** * A superpixel is the individual pixel of the output image. * It is represented by a SINGLE position and SINGLE color at its core. */ public class Superpixel { // Location of the superpixel public PixelLocation Location { get; set; } // The key that can be used to reference back to the global palette // to obtain the superpixel's palette color public int PaletteColorKey { get; set; } // The computed average color of the group of input pixels // which are associated with this superpixel. public LabColor Color { get; set; } // Internal mappings of the input image pixels public List<PixelLocation> Pixels { get; set; } // The uniform probability of this superpixel. Default 1 / N public double Probability { get; set; } // Every single superpixel has an associated probability to some color // within the global color palette. The key is the palette color key, and // the value represents the probability to that palette color public Dictionary<int, double> PaletteProbabilityMap; private Superpixel() { Pixels = new List<PixelLocation>(); Color = new LabColor(0, 0, 0); PaletteColorKey = 0; Location = new PixelLocation(0, 0); PaletteProbabilityMap = new Dictionary<int , double>(); Probability = 1; } public Superpixel(int paletteColorKey, PixelLocation location) { Color = new LabColor(0, 0, 0); Location = location; PaletteColorKey = paletteColorKey; PaletteProbabilityMap = new Dictionary<int, double>(); Pixels = new List<PixelLocation>(); Probability = 1; } } }
Python
UTF-8
7,558
2.90625
3
[ "MIT" ]
permissive
#!/usr/bin/env python """Script used to generate a cuboid dataset with cubes and rectangles under various shapes, rotations, translations following the general format of ShapeNet. """ import argparse import random import os from string import ascii_letters, digits import sys import numpy as np from progress.bar import Bar from pyquaternion import Quaternion from .shapes import Shape, Cuboid, Ellipsoid from learnable_primitives.mesh import MeshFromOBJ def get_single_cube(minimum, maximum): minimum = minimum[0] maximum = maximum[0] r = minimum + np.random.rand() * (maximum-minimum) return Cuboid(-r, r, -r, r, -r, r) def get_single_rectangle(minimum, maximum): minimum = np.array(minimum) maximum = np.array(maximum) rs = minimum + np.random.rand(3) * (maximum - minimum) return Cuboid(-rs[0], rs[0], -rs[1], rs[1], -rs[2], rs[2]) def adjacent_cubes(R): x_max1, y_max1, z_max1 = tuple(np.random.rand(3)) x_max2, y_max2, z_max2 = tuple(np.random.rand(3)) c1 = Cuboid(-x_max1, x_max1, -y_max1, y_max1, -z_max1, z_max1) c2 = Cuboid(-x_max2, x_max2, -y_max2, y_max2, -z_max2, z_max2) t1 = np.array([ [0.0, y_max2 + y_max1, 0.0], [x_max2 + x_max1, 0.0, 0.0], [0.0, 0.0, z_max2 + z_max1] ]) t = t1[np.random.choice(np.arange(3))].reshape(3, 1) c2.translate(t) c1.rotate(R) c2.rotate(R) return c1, c2 def multiple_cubes(R1, R2, t): x_max1, y_max1, z_max1 = tuple(np.random.rand(3)) x_max2, y_max2, z_max2 = tuple(np.random.rand(3)) c1 = Cuboid(-x_max1, x_max1, -y_max1, y_max1, -z_max1, z_max1) c2 = Cuboid(-x_max2, x_max2, -y_max2, y_max2, -z_max2, z_max2) c1.rotate(R1) c2.translate(t) c2.rotate(R2) #c2.translate(R2.dot(t)) return c1, c2 def main(argv): parser = argparse.ArgumentParser( description="Generate a cuboid dataset" ) parser.add_argument( "output_directory", help="Save the dataset in this directory" ) parser.add_argument( "--n_samples", type=int, default=10, help="Number of training samples to be generated" ) parser.add_argument( "--shapes_type", default="cubes", choices=[ "cubes", "cubes_translated", "cubes_rotated_translated", "cubes_rotated", "rectangles", "rectangles_translated", "rectangles_rotated", "rectangles_rotated_translated", "ellipsoid", "random" ], help="The type of the shapes in every sample" ) parser.add_argument( "--n_shapes_per_samples", type=int, default=1, help="Number of shapes per sample" ) parser.add_argument( "--maximum", type=lambda x: tuple(map(float, x.split(","))), default="0.5,0.5,0.5", help="Maximum size along every axis" ) parser.add_argument( "--minimum", type=lambda x: tuple(map(float, x.split(","))), default="0.13,0.13,0.13", help="Maximum size along every axis" ) args = parser.parse_args(argv) # Check if output directory exists and if it doesn't create it if not os.path.exists(args.output_directory): os.makedirs(args.output_directory) # Create a directory based on the type of the shapes inside the output # directory output_directory = os.path.join( args.output_directory, args.shapes_type ) ranges = None if "cubes" in args.shapes_type: # Make sure that the maximum and minimum range are equal along each # axis assert args.maximum[0] == args.maximum[1] assert args.maximum[1] == args.maximum[2] assert args.minimum[0] == args.minimum[1] assert args.minimum[1] == args.minimum[2] ranges = np.linspace( args.minimum[0], args.maximum[0], 10, endpoint=False ) # elif "rectangles" in args.shapes_type: else: ranges = [ np.linspace(args.minimum[0], args.maximum[0], 10, endpoint=False), np.linspace(args.minimum[1], args.maximum[1], 10, endpoint=False), np.linspace(args.minimum[2], args.maximum[2], 10, endpoint=False), ] bar = Bar("Generating %d cuboids" % (args.n_samples,), max=args.n_samples) c = None for i in range(args.n_samples): if "cubes" in args.shapes_type: c = get_single_cube(args.minimum, args.maximum) if "rectangles" in args.shapes_type: c = get_single_rectangle(args.minimum, args.maximum) if "translated" in args.shapes_type: t = 0.3*np.random.random((3, 1)) c.translate(t) if "rotated" in args.shapes_type: q = Quaternion.random() R = q.rotation_matrix c.rotate(R) if "ellipsoid" in args.shapes_type: abc = np.random.random((3, 1)) c1 = Ellipsoid(abc[0], abc[1], abc[2]) c2 = Ellipsoid(abc[0], abc[1], abc[2]) c3 = Ellipsoid(abc[0], abc[1], abc[2]) q = Quaternion.random() R = q.rotation_matrix c2.rotate(R) q = Quaternion.random() R = q.rotation_matrix c3.rotate(R) # t = 0.3*np.random.random((3, 1)) # c1.translate(t) c = Shape.from_shapes([c1, c2, c3]) if "random" in args.shapes_type: #if random.choice((True, False)): #if True: # q = Quaternion.random() # c1, c2 = adjacent_cubes(q.rotation_matrix) #else: if True: q1 = Quaternion.random() q2 = Quaternion.random() c1, c2 = multiple_cubes( q1.rotation_matrix, q2.rotation_matrix, 3.5*np.random.random((3, 1)) ) # q = Quaternion.random() # c1, c2 = adjacent_cubes(q.rotation_matrix) # q1 = Quaternion.random() # x_max1, y_max1, z_max1 = tuple(np.random.rand(3)) # c3 = Cuboid(-x_max1, x_max1, -y_max1, y_max1, -z_max1, z_max1) # c3.rotate(q1.rotation_matrix) # c3.translate(np.random.random((3,1)).reshape(3, -1)) c = Shape.from_shapes([c1, c2]) # Create subdirectory to save the sample folder_name = ''.join([ random.choice(ascii_letters + digits) for n in range(32) ]) base_dir = os.path.join(output_directory, folder_name, "models") if not os.path.exists(base_dir): os.makedirs(base_dir) # print base_dir # Save as obj file c.save_as_mesh(os.path.join(base_dir, "model_normalized.obj"), "obj") c.save_as_mesh(os.path.join(base_dir, "model_normalized.ply"), "ply") c.save_as_pointcloud( os.path.join(base_dir, "model_normalized_pcl.obj"), "obj" ) if "translated" in args.shapes_type: print(os.path.join(base_dir, "model_normalized_pcl.obj"), t.T) if "rotated" in args.shapes_type: print(os.path.join(base_dir, "model_normalized_pcl.obj"), q) next(bar) for i in os.listdir(output_directory): x = os.path.join(output_directory, i, "models/model_normalized.obj") m = MeshFromOBJ(x) print(x, m.points.max(-1)) if __name__ == "__main__": main(sys.argv[1:])
Markdown
UTF-8
3,082
2.609375
3
[]
no_license
# Dockerized Shibboleth Service Provider ## Included - Apache as Webserver - Shibboleth Service Provider 2.6 - Ilias Version 5.2 - MySQL database ## Preconditions For the host system, I recommend using a virtual machine with Debian Jessy. In addition you will need **Docker**, **Docker Compose** and **Git** on your host system. Therefor you can use the [Docker Installation Guide](https://docs.docker.com/engine/installation/linux/debian/), the [Compose Installation Guide](https://docs.docker.com/compose/install/) and this [How To Install Git on Debian 8 Guide](https://www.digitalocean.com/community/tutorials/how-to-install-git-on-debian-8). <br><br> ## Getting Started 1. Open the console and clone the repository on your host system: `git clone https://github.com/larry1337/shibboleth-sp.git` <br> 2. Navigate into the directory. There you can build the docker-image with the command: `docker-compose build`<br> Do not worry, it will take a few minutes :wink:. <br> 3. If the image has been built successfully, the following script must be executed once: `./init.sh`<br> It is ok if some directories were not found. <br> 4. Now you can start the docker container on the previously built image: `docker-compose up`<br> You will see some messages. That's fine. <br> 5. Afterwards navigate to the following address in your browser: **yourdomain/setup/setup.php** <br> <sub>(Note: You have to trust the self-signed certificate)</sub> <br> 6. Log into Ilias with the master-password: "homer"<br> <br> 7. You will see the Ilias setup page with the List of Clients. Now we need a new client. Therefore press the blue button "Create New Client" and follow the setup steps: - **Step 1 - Database selection:** <br> MySQL 5.5x or higher (InnoDB engine)<br> - **Step 2 - Basic Data:** <br> Client ID: "ilias"<br> Database Host: "mysql-db"<br> Database Name: "ilias"<br> Database User: "root"<br> Database Password: "root"<br> - **Step 3 - Database:**<br> Activate the "Create Database" checkbox<br> - **Step 4 - Languages:**<br> Choose your desired language<br> - **Step 5 - Contact Information:**<br> Fill up the required fields<br> - **Step 6 - Proxy:**<br> If you have a proxy, you can setup the Proxy configuration here.<br> - **Step 7 - Registration:**<br> Skip the registration<br> - **Step 8 - Finish Setup:**<br> You're done with the setup! :sunglasses:<br> <br> 8. Log into Ilias with the root account, password: "homer". Make sure to change the password after installation. <br> 9. Navigate to **_Administration > Authentication and Registration_** and activate Shibboleth as default authentication mode. Save it. <br> 10. Now go to the **_Shibboleth_** tab and make the following settings: - Enable Shibboleth support<br> - Allow Local Authentication if you want to support the default Ilias login<br> - Unique Shibboleth attribute: HTTP_SHIB_UID<br> - Attribute for first name: HTTP_SHIB_FIRSTNAME<br> - Attribute for lastname: HTTP_SHIB_LASTNAME<br> - Attribute for e-mail address: HTTP_SHIB_EMAIL<br>
Java
UTF-8
6,812
1.898438
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * Copyright 2002-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.servlet.mvc.annotation; /** * @author Mark Fisher */ import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.BeanInstantiationException; import org.springframework.beans.BeanUtils; import org.springframework.util.ClassUtils; import org.springframework.util.ReflectionUtils; import org.springframework.util.ReflectionUtils.MethodCallback; import org.springframework.validation.BindException; import org.springframework.validation.BindingResult; import org.springframework.validation.Errors; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException; public class GenericAnnotationController extends AbstractController { private final Map<String, Method> getMethodMappings = new ConcurrentHashMap<String, Method>(); private final Map<String, Method> postMethodMappings = new ConcurrentHashMap<String, Method>(); private final Map<Class<?>, Method> validateMethodMappings = new ConcurrentHashMap<Class<?>, Method>(); private boolean bindOnGet = false; public GenericAnnotationController() { initMethodMappings(); } public void setBindOnGet(boolean bindOnGet) { this.bindOnGet = bindOnGet; } private void initMethodMappings() { ReflectionUtils.doWithMethods(getClass(), new MethodCallback() { public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { Annotation[] annotations = method.getAnnotations(); for (Annotation annotation : annotations) { Class<? extends Annotation> annotationType = annotation.annotationType(); String[] paths = null; if (annotationType.equals(Post.class)) { paths = ((Post) annotation).value(); if (paths != null) { for (String path : paths) { if (postMethodMappings.get(path) != null) { throw new IllegalStateException( "only one POST method may be mapped to path: '" + path + "'"); } postMethodMappings.put(path, method); } } } else if (annotationType.equals(Get.class)) { paths = ((Get) annotation).value(); if (paths != null) { for (String path : paths) { if (getMethodMappings.get(path) != null) { throw new IllegalStateException( "only one GET method may be mapped to path: '" + path + "'"); } getMethodMappings.put(path, method); } } } else if (annotationType.equals(Validate.class)) { Class[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length != 2 || !parameterTypes[1].equals(Errors.class)) { throw new IllegalStateException( "validation method must have two parameters with second of type [" + Errors.class.getName() + "]"); } Class targetType = parameterTypes[0]; if (validateMethodMappings.get(targetType) != null) { throw new IllegalStateException( "only one validation method may be mapped to type [" + targetType.getName() + "]"); } validateMethodMappings.put(targetType, method); } } } }); } protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { String path = request.getContextPath(); String requestMethod = request.getMethod(); Method method = null; if ("POST".equals(requestMethod)) { method = this.postMethodMappings.get(path); } else if ("GET".equals(requestMethod)) { method = this.getMethodMappings.get(path); } return this.invokeMethod(method, path, request, response); } protected final ModelAndView invokeMethod(Method method, String path, HttpServletRequest request, HttpServletResponse response) throws Exception { if (method == null) { throw new NoSuchRequestHandlingMethodException(method.getName(), getClass()); } Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length > 3) { throw new IllegalStateException("handler methods accept at most 3 parameters"); } Object[] parameterValues = new Object[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { Class<?> type = parameterTypes[i]; if (HttpServletRequest.class.isAssignableFrom(type)) { parameterValues[i] = request; } else if (HttpServletResponse.class.isAssignableFrom(type)) { parameterValues[i] = response; } else { try { Object target = createCommandObject(type); boolean isPost = "POST".equals(request.getMethod()); BindingResult result = null; if (isPost || this.bindOnGet) { ServletRequestDataBinder binder = new ServletRequestDataBinder(target); binder.bind(request); result = binder.getBindingResult(); } if (isPost) { Method validateMethod = validateMethodMappings.get(type); if (validateMethod != null) { if (result == null) { result = new BindException(target, ClassUtils.getShortNameAsProperty(type)); } validateMethod.invoke(this, target, result); } } if (result != null && result.hasErrors()) { return new ModelAndView(path, result.getModel()); } parameterValues[i] = target; } catch (BeanInstantiationException e) { throw new IllegalStateException("unable to create object for binding", e); } } } Object returnValue = method.invoke(this, parameterValues); if (method.getReturnType().equals(void.class)) { return new ModelAndView(path); } if (returnValue instanceof ModelAndView) { return (ModelAndView) returnValue; } if (returnValue instanceof Map) { return new ModelAndView(path, (Map) returnValue); } return new ModelAndView(path).addObject(returnValue); } protected Object createCommandObject(Class type) { return BeanUtils.instantiateClass(type); } }
C++
UTF-8
1,210
3.09375
3
[]
no_license
#ifndef CAT_H #define CAT_H #include <QString> #include <QChar> #define MAX_SIZE_OF_NAME 22 //размер имени котика из БД #define MAX_SIZE_OF_BREED 61 //размер породы котика из БД #define CAT_SIZE 86 //размер одного котика для записи class Cat { QString name; //имя котика QString breed; //порода unsigned short age; //возраст QChar gender; //пол public: // Cat(); Cat(QString name="", QString breed="", unsigned short age=0, QChar gender='m'); friend QDataStream& operator << (QDataStream& stream, Cat &cat); friend QDataStream& operator >> (QDataStream& stream, Cat &cat); void print() const; //напечатать котика unsigned short getAge() const { return age; } QString getName() const { return name; } QString getBreed() const { return breed; } QChar getGender() const { return gender; } bool operator == (const Cat &c); }; #endif // CAT_H
JavaScript
UTF-8
2,676
2.96875
3
[]
no_license
$(function(){ /*Основные переменные*/ var btn = $('#btn'); var modal = $('.modal'); var docHeight = $(document).height();//Высота документа /*Создаем обработчик события клик - вызов модального окна*/ btn.click(function(e){ e.preventDefault();//Отменяем стандартное событие sWrapper();//Затемнить страницу(контент недоступен) showModal();//Показать модальное окно btnClose();//Вызвать событие закрытия модального окна }); /*Функция затемнения основного контента(подложка)*/ function sWrapper(){ /*Создаем блок с классом*/ var shadow = $('<div>') .addClass('shadow') $('body').append(shadow);//Добавляем на страницу } /*Функция показа модального окна*/ function showModal(){ modal.fadeIn('slow');//Показать окно /* Далее происходят интересные вычисления По умолчанию модальное окно находится по середине горизонтальной линии, а вот по вертикали сверху Поэтому для полного центрирования мы меняем значение "top" на половину высоты документа минус половина высоты модального окна Тем самым мы дабиваемся полного центрирования блока вне зависимо от разрешения экрана и высоты модального окна */ modal.css({ top: docHeight/2 - modal.find('.modal-content').height()/2 + 'px' }); }; /*Функция закрытия модального окна*/ function btnClose(){ /*Кнопки*/ var btnClose = $('.btn-close'); /*Создаем обработчик события клик - для кнопок*/ btnClose.click(function(e){ e.preventDefault();//Отменяем стандартное событие modal.fadeOut('fast');//Прячем модальное окно $('.shadow').fadeOut('slow');//Прячем "подложку", чтобы контент стал доступным }); } });
Markdown
UTF-8
1,067
2.984375
3
[ "MIT" ]
permissive
# PHP Crypt A PHP implementation of crypt methods like SHA1, SHA256, MD5 and etc. for Information Systems Bachelor (UNASP-HP) ## Hash strategy The hash strategy that we decided to use was a mix of some algorithms: sha1, md5, and sha256. Basically, we generate a random MD5 salt that is used to concatenate with the user password, and with this two informations the algorithms sha256, md5 and sha1 are applied to generate the final password. The unique way to achieve the final password is using the unique hash + the right algorithms on the sequence. ## Run Locally Clone the project ```bash https://github.com/thiscosta/php_project_cript.git ``` Go to the project directory ```bash cd php_project_cript ``` Start docker containers ```bash docker-compose up -d ``` Run the initial script (init.sql) on the started MySQL instance and access localhost on port 80 or 443 ## Authors - [@thiscosta](https://www.github.com/thiscosta) - [@thaleszago](https://github.com/ThalesZago) ## License [MIT](https://choosealicense.com/licenses/mit/)
JavaScript
UTF-8
610
2.75
3
[ "MIT" ]
permissive
import { escapeHtml } from './escapeHtml.js' describe('escapeHtml()', () => { it('should escape quotes, ampersands, and smaller/greater than signs', () => { expect(escapeHtml('<div id="me, myself & i"/>')) .toBe('&lt;div id=&quot;me, myself &amp; i&quot;/&gt;') }) it('should return an empty string if nothing can be processed', () => { expect(escapeHtml()).toBe('') expect(escapeHtml(null)).toBe('') expect(escapeHtml('')).toBe('') }) it('should handle falsy values correctly', () => { expect(escapeHtml(0)).toBe('0') expect(escapeHtml(false)).toBe('false') }) })
Python
UTF-8
4,657
3.703125
4
[]
no_license
# -*- coding: utf-8 -*- """ ----------------------------------------------------------------------------- Spark with Python Copyright : V2 Maestros @2016 Code Demo : Spark Machine Learning - Linear Regression Problem Statement ***************** The input data set contains data about details of various car models. Based on the information provided, the goal is to come up with a model to predict Miles-per-gallon of a given model. Techniques Used: 1. Linear Regression ( multi-variate) 2. Data Imputation - replacing non-numeric data with numeric ones 3. Variable Reduction - picking up only relevant features ----------------------------------------------------------------------------- """ #import os #os.chdir("C:/Users/kumaran/Dropbox/V2Maestros/Courses/Spark n X - Do Big Data Analytics and ML/Python") #os.curdir """-------------------------------------------------------------------------- Load Data -------------------------------------------------------------------------""" #Load the CSV file into a RDD autoData = SpContext.textFile("auto-miles-per-gallon.csv") autoData.cache() autoData.take(5) #Remove the first line (contains headers) dataLines = autoData.filter(lambda x: "CYLINDERS" not in x) dataLines.count() """-------------------------------------------------------------------------- Cleanup Data -------------------------------------------------------------------------""" from pyspark.sql import Row #Use default for average HP avgHP =SpContext.broadcast(80.0) #Function to cleanup Data def CleanupData( inputStr) : global avgHP attList=inputStr.split(",") #Replace ? values with a normal value hpValue = attList[3] if hpValue == "?": hpValue=avgHP.value #Create a row with cleaned up and converted data values= Row( MPG=float(attList[0]),\ CYLINDERS=float(attList[1]), \ DISPLACEMENT=float(attList[2]), HORSEPOWER=float(hpValue),\ WEIGHT=float(attList[4]), \ ACCELERATION=float(attList[5]), \ MODELYEAR=float(attList[6]),\ NAME=attList[7] ) return values #Run map for cleanup autoMap = dataLines.map(CleanupData) autoMap.cache() autoMap.take(5) #Create a Data Frame with the data. autoDf = SpSession.createDataFrame(autoMap) """-------------------------------------------------------------------------- Perform Data Analytics -------------------------------------------------------------------------""" #See descriptive analytics. autoDf.select("MPG","CYLINDERS").describe().show() #Find correlation between predictors and target for i in autoDf.columns: if not( isinstance(autoDf.select(i).take(1)[0][0], unicode)) : print( "Correlation to MPG for ", i, autoDf.stat.corr('MPG',i)) """-------------------------------------------------------------------------- Prepare data for ML -------------------------------------------------------------------------""" #Transform to a Data Frame for input to Machine Learing #Drop columns that are not required (low correlation) from pyspark.ml.linalg import Vectors def transformToLabeledPoint(row) : lp = ( row["MPG"], Vectors.dense([row["ACCELERATION"],\ row["DISPLACEMENT"], \ row["WEIGHT"]])) return lp autoLp = autoMap.map(transformToLabeledPoint) autoDF = SpSession.createDataFrame(autoLp,["label", "features"]) autoDF.select("label","features").show(10) """-------------------------------------------------------------------------- Perform Machine Learning -------------------------------------------------------------------------""" #Split into training and testing data (trainingData, testData) = autoDF.randomSplit([0.9, 0.1]) trainingData.count() testData.count() #Build the model on training data from pyspark.ml.regression import LinearRegression lr = LinearRegression(maxIter=10) lrModel = lr.fit(trainingData) #Print the metrics print("Coefficients: " + str(lrModel.coefficients)) print("Intercept: " + str(lrModel.intercept)) #Predict on the test data predictions = lrModel.transform(testData) predictions.select("prediction","label","features").show() #Find R2 for Linear Regression from pyspark.ml.evaluation import RegressionEvaluator evaluator = RegressionEvaluator(predictionCol="prediction", \ labelCol="label",metricName="r2") evaluator.evaluate(predictions)
Python
UTF-8
544
2.84375
3
[]
no_license
import csv import branchboundsearch as bb import sys data = {} start = goal = str() with open(sys.argv[1]) as f: reader = csv.reader(f, delimiter=' ') target = next(reader) start = target[0] goal = target[1] headers = next(reader) for row,header,i in zip(reader,headers,range(len(headers))): data[header] = {headers[i]:int(x) for x,i in zip(row,range(len(row))) if headers[i] != header and int(x) != -1 } result = bb.search(data, start, goal) print('cost: {}, path: {}'.format(result['cost'],result['path']))
Shell
UTF-8
722
3.875
4
[ "BSD-3-Clause" ]
permissive
#!/bin/bash -eu DIST=$(find deploy -name 'image*lite.zip' | head -1) if [ -z "$DIST" ] then echo "No distribution found. Exiting." exit 1 fi echo echo "Currently mounted disks:" diskutil list external | grep -A 2 external DISK=$(diskutil list external | grep "/dev/disk" | head -1 | awk '{print $1}') if [ -z "$DISK" ] then echo "No external disk found. Exiting." exit 1 fi echo echo "Unmounting $DISK" diskutil unmountDisk $DISK RDISK=$(echo $DISK | sed 's/disk/rdisk/') echo echo "About to flash to raw $RDISK using:" COMMAND="unzip -p $DIST | sudo dd of=$RDISK bs=4m" echo " " $COMMAND echo read -p "Are you sure? (press y to confirm)" -n 1 -r if [[ $REPLY =~ ^[Yy]$ ]]; then echo eval "$COMMAND" fi
Markdown
UTF-8
2,159
2.828125
3
[]
no_license
--- directions: Mossley Community Centre title: Mr Pickles Visits St John's year: 1926 teaser: Mr. Pickles flew over Mossley looking at the queues of people outside the employment exchange. lat: 53.52355 lon: -2.03838 --- {% include intro.html %} Mr Pickles flew over Mossley looking at the queues of people outside the employment exchange. Work had been drying up in the town as the machinery in the mills started to grow old and out of date. Now the General Strike had made things even worse. ![Illustration by children of Milton St John's School](/images/stops/crow/Trail_Crow_4.png) _Illustration by children of Milton St John's School_ {% include body.html %} When Mr Pickles felt sad and needed to think, he went to rest on one of his favourite perches. It was a cross set in to a large boulder. The cross was a memorial to soldiers who had died in the war and because of that and because men also left Mossley to find work, there were less and less young men around. Mr Pickles preferred to think about the boulder, which the Vicar of St John's often talked about. It had been found by some St John's school boys digging in the garden before the school had merged with Milton and the pupils had moved there. It was a glacial boulder from the Ice Age, before Mossley had even existed. The stone mason who had cut the hole for the cross said it was the hardest stone he had ever worked on. Mr Pickles sat on the granite boulder and looked across the sloping roof and factory chimneys. He took comfort in the thought that despite all the changes the little valley of Mossley had seen with the coming of industry and the Great War, it was a fraction of time compared to the thousands of years it took to make the valley in the first place. {% include fact.html %} ![Cross](/images/stops/crow/Trail_Crow_4b.png) The school here opened in 1865 and was originally called Roughtown School. it was badly damaged by fire in 1912 and eventually merged with Milton School in 1979. The best known teacher at St John's School was Alfred Holt, the Head for many years before his death in 1932. His 1926 publication 'The Story of Mossley' remains an informative and popular read.
Java
UTF-8
2,396
2.21875
2
[ "Apache-2.0" ]
permissive
package org.cache2k.core; /* * #%L * cache2k implementation * %% * Copyright (C) 2000 - 2020 headissue GmbH, Munich * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import org.cache2k.Weigher; /** * @author Jens Wilke */ public class RandomEviction extends AbstractEviction { private int evictionIndex = 0; private long size = 0; private Entry head = new Entry().shortCircuit(); public RandomEviction(final HeapCache _heapCache, final HeapCacheListener _listener, final long _maxSize, final Weigher _weigher, final long _maxWeight) { super(_heapCache, _listener, _maxSize, _weigher, _maxWeight, false); } @Override public void updateWeight(final Entry e) { } @Override protected void removeFromReplacementList(Entry e) { Entry.removeFromList(e); } @Override protected void insertIntoReplacementList(Entry e) { size++; Entry.insertInList(head, e); } @Override protected Entry findEvictionCandidate(Entry _previous) { Entry[] h0 = heapCache.hash.getEntries(); int idx = evictionIndex % (h0.length); Entry e; while ((e = h0[idx]) == null) { idx++; if (idx >= h0.length) { idx = 0; } } evictionIndex += e.hashCode; if (evictionIndex < 0) { evictionIndex = -evictionIndex; } return e; } @Override public void checkIntegrity(final IntegrityState _integrityState) { } @Override public long removeAll() { long _count = 0; Entry _head = head; Entry e = head.prev; while (e != _head) { Entry _next = e.prev; e.removedFromList(); _count++; e = _next; } return _count; } @Override public String getExtraStatistics() { return ""; } @Override public long getHitCount() { return 0; } @Override public long getSize() { return size; } }
C++
UTF-8
764
2.703125
3
[ "MIT" ]
permissive
//============================================ // Larduino w/ 328D // DAC0 output demo // DACO output ==> D4 on board //============================================ #define SAMPLES 255 byte table[SAMPLES]; void setup() { // put your setup code here, to run once: for (int i = 0; i < SAMPLES; i++) { table[i] = sin((float)i * TWO_PI / SAMPLES) * 255; } analogReference(DEFAULT); // 5v // analogReference(EXTERNAL); // REF PIN Voltage // analogReference(INTERNAL4V096); // 4.096V // analogReference(INTERNAL2V048); // 2.048v // analogReference(INTERNAL1V048); // 1.024v pinMode(DAC0, ANALOG); } void loop() { // put your main code here, to run repeatedly: for (byte i = 0; i <= SAMPLES; i++) { analogWrite(DAC0, table[i]); } }
C#
UTF-8
746
2.625
3
[]
no_license
using Microsoft.AspNetCore.Mvc; using System.Reflection; namespace SwaggerApp.Controllers { [Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { /// <summary> /// Get current Assembly name /// </summary> /// <remarks> /// Sample request: /// GET /// { /// "id": 1 /// } /// </remarks> /// <returns>Name of current Assembly</returns> /// <response code="200">Success</response> /// <response code="404">Not found</response> [HttpGet] public ActionResult<string> Get() { return Assembly.GetExecutingAssembly().GetName().Name; } } }
PHP
UTF-8
1,826
2.640625
3
[ "MIT" ]
permissive
<?php namespace Microsoft\Graph\Beta\Generated\Financials\Companies\Item\SalesOrderLines\Item; use Microsoft\Kiota\Abstractions\BaseRequestConfiguration; use Microsoft\Kiota\Abstractions\RequestOption; /** * Configuration for the request such as headers, query parameters, and middleware options. */ class SalesOrderLineItemRequestBuilderGetRequestConfiguration extends BaseRequestConfiguration { /** * @var SalesOrderLineItemRequestBuilderGetQueryParameters|null $queryParameters Request query parameters */ public ?SalesOrderLineItemRequestBuilderGetQueryParameters $queryParameters = null; /** * Instantiates a new SalesOrderLineItemRequestBuilderGetRequestConfiguration and sets the default values. * @param array<string, array<string>|string>|null $headers Request headers * @param array<RequestOption>|null $options Request options * @param SalesOrderLineItemRequestBuilderGetQueryParameters|null $queryParameters Request query parameters */ public function __construct(?array $headers = null, ?array $options = null, ?SalesOrderLineItemRequestBuilderGetQueryParameters $queryParameters = null) { parent::__construct($headers ?? [], $options ?? []); $this->queryParameters = $queryParameters; } /** * Instantiates a new SalesOrderLineItemRequestBuilderGetQueryParameters. * @param array<string>|null $expand Expand related entities * @param array<string>|null $select Select properties to be returned * @return SalesOrderLineItemRequestBuilderGetQueryParameters */ public static function createQueryParameters(?array $expand = null, ?array $select = null): SalesOrderLineItemRequestBuilderGetQueryParameters { return new SalesOrderLineItemRequestBuilderGetQueryParameters($expand, $select); } }
Java
UTF-8
168
1.976563
2
[ "Apache-2.0" ]
permissive
package com.daedafusion.sf; /** * Created by mphilpot on 7/2/14. */ public interface Base64Encoder { String encode(byte[] bytes); byte[] decode(String s); }
Java
UTF-8
1,185
1.945313
2
[]
no_license
package fr.univrouen.cv21.model; import java.util.Date; import org.springframework.data.mongodb.core.mapping.Document; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.JsonProperty.Access; @JsonIgnoreProperties(ignoreUnknown = true) public class Expe { private String datedeb; private String datefin; private String titre; public Expe() { super(); // TODO Auto-generated constructor stub } public Expe(String datedeb, String datefin, String titre) { this.datedeb = datedeb; this.datefin = datefin; this.titre = titre; } public String getDatedeb() { return datedeb; } public void setDatedeb(String datedeb) { this.datedeb = datedeb; } public String getDatefin() { return datefin; } public void setDatefin(String datefin) { this.datefin = datefin; } public String getTitre() { return titre; } public void setTitre(String titre) { this.titre = titre; } }
Markdown
UTF-8
2,854
3.59375
4
[ "MIT" ]
permissive
#Blitz-DB Blitzdb (or simply blitz) is a document-oriented database for Python. It can be used either as a **stand-alone, flat-file database** or in conjunction with another database backend such as **MongoDB** or **MySQL**. ##Features * multiple database backends (flat files, Mongo, ...) * database transactions & operation caching * automatic object references * flexible querying syntax * deep-key indexing ##Use Cases Blitz can be used as a standalone document store for client application. Originally blitz was designed for use with the checkmate Python code analysis toolkit, where it stores statistical data. Since blitz stores all documents as single JSON files, it is possible to put the whole database under version-control. ##Examples To get an idea of what you can do with Blitz, here are some examples. ###Creating objects ```python from blitzdb import Document class Movie(Document): pass class Actor(Document): pass the_godfather = Movie({'name': 'The Godfather','year':1972,'pk':1L}) marlon_brando = Actor({'name':'Marlon Brando','pk':1L}) al_pacino = Actor({'name' : 'Al Pacino','pk':1L}) ``` ###Storing objects in the database: ```python from blitzdb import FileBackend backend = FileBackend("/path/to/my/db") the_godfather.save(backend) marlon_brando.save(backend) al_pacino.save(backend) ``` ###Retrieving objects from the database: ```python the_godfather = backend.get(Movie,{'pk':1L}) #or... the_godfather = backend.get(Movie,{'name' : 'The Godfather'}) ``` ###Filtering objects ```python movies_from_1972 = backend.filter(Movie,{'year' : 1972}) ``` ###Working with transactions ```python backend.begin() the_godfather.director = 'Roland Emmerich' #oops... the_godfather.save() backend.rollback() #undo the changes... ``` ###Creating nested object references ```python the_godfather.cast = {'Don Vito Corleone' : marlon_brando, 'Michael Corleone' : al_pacino} #Documents stored within other objects will be automatically converted to database references. marlon_brando.performances = [the_godfather] al_pacino.performances = [the_godfather] marlon_brando.save(backend) al_pacino.save(backend) the_godfather.save(backend) #Will store references to the movies within the documents in the DB ``` ###Creation of database indexes and advanced querying ```python backend.create_index(Actor,'performances') #Will create an index on the 'performances' field, for fast querying godfather_cast = backend.filter(Actor,{'movies' : the_godfather}) #Will return 'Al Pacino' and 'Marlon Brando' ``` ###Arbitrary filter expressions ```python star_wars_iv = Movie({'name' : 'Star Wars - Episode IV: A New Hope','year': 1977}) star_wars_iv.save() movies_from_the_seventies = backend.filter(Movie,{'year': lambda year : True if year >= 1970 and year < 1980 else False}) #Will return Star Wars & The Godfather (man, what a decade!) ```
PHP
UTF-8
1,611
3.234375
3
[ "MIT" ]
permissive
<?php /* * RunTimer * Фабрика таймеров, должна быть вызвана, чтобы потом сработал деструктор */ include 'Timer.php'; final class RunTimer { private $_nameGeneralTimer; private static $_listTimers = array(); public function __construct($name = 'TOTAL_TIMER') { $this->_nameGeneralTimer = $name; self::addTimer($this->_nameGeneralTimer); self::addPoint($this->_nameGeneralTimer); } function __destruct() { self::endPoint($this->_nameGeneralTimer); $title = 'Timers:'; $descr = ''; foreach (self::$_listTimers as $key => $value) { $descr .= '"' . $key . '": ' . TFormat::timer($value->getAllTime(true)) . "\n"; } Log::info($title, $descr, true); } //задать точку для таймера public static function addPoint($nameTimer) { self::$_listTimers[$nameTimer]->addPoint(); } //возвратить отработанное время от точки до точки public static function endPoint($nameTimer){ return TFormat::timer(self::$_listTimers[$nameTimer]->endPoint()); } /** * @param string $name Название нового таймера */ public static function addTimer($name) { if (isset(self::$_listTimers[$name])) { Log::notice('Таймер ' . $nameTimer . ' уже существует'); return false; } else { self::$_listTimers[$name] = new Timer(); return true; } } }
JavaScript
UTF-8
1,037
3.90625
4
[]
no_license
let button = document.getElementById("btn"); let hex = document.getElementById("hex"); let main = document.getElementById("mainDiv"); button.onclick = function() { //Generate random color let color = getRandomHex(); //set maindiv to random colour main.style.backgroundColor = color; //set hex content to random color as it's generated hex.innerHTML = color; //set button color // button.style.backgroundColor = getButtonColor(); } // Function to get random 6 letter hexcode function getRandomHex() { let values = '0123456789ABCDEF'; let hex = '#'; for (var i = 0; i <= 5; i++){ hex += values[Math.floor(Math.random() * 16)]; } return hex; } /* Function to generate button color based on random hex color */ // function getButtonColor() { // let color = getRandomHex(); // let btnColor = "#"; // let j = 1; // for (let i = 1; i <= 3; i++){ // btnColor += color[j] + "F"; // j += 2; // } // return btnColor; // }
Python
UTF-8
139
3.703125
4
[]
no_license
a=float(input('Radius? ')) print('area =',round(3.14*a,2)) b=float(input('enter the temperature ')) print(a,'C = ',round(1.8*b+32,2),'F')
Java
UTF-8
656
1.921875
2
[]
no_license
package com.vika.way.srpc.constants; /** * @author chenwei.tjw * @date 2022/5/12 */ public class Constants { public static final String DEFAULT_HOST = "127.0.0.1"; public static final int DEFAULT_PORT = 8080; /** * init method name */ public static String INIT_METHOD = "init"; /** * 生产者线程池线程数量 */ public static final int PROVIDER_THREAD_POOL_NUM = 256; /** * 生产者线程池工作队列长度 */ public static final int PROVIDER_THREAD_POOL_QUEUE_LEN = 1024; /** * 注册中心root节点名 */ public static final String BASE_PATH = "/rpc"; }
Shell
UTF-8
2,489
3.5
4
[ "Apache-2.0", "CC-BY-4.0" ]
permissive
#!/bin/bash # # Copyright (c) 2016-2017 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. INSTALL_NSB_BIN="/opt/nsb_bin" cd $INSTALL_NSB_BIN if [ "$(whoami)" != "root" ]; then echo "Must be root to run $0" exit 1; fi echo "Install required libraries to run collectd..." pkg=(git flex bison build-essential pkg-config automake autotools-dev libltdl-dev librabbitmq-dev rabbitmq-server) for i in "${pkg[@]}"; do dpkg-query -W --showformat='${Status}\n' "${i}"|grep "install ok installed" if [ "$?" -eq "1" ]; then apt-get -y install "${i}"; fi done echo "Done" ldconfig -p | grep libpqos >/dev/null if [ $? -eq 0 ] then echo "Intel RDT library already installed. Done" else pushd . echo "Get intel_rdt repo and install..." rm -rf intel-cmt-cat >/dev/null git clone https://github.com/01org/intel-cmt-cat.git pushd intel-cmt-cat git checkout tags/v1.5 -b v1.5 make install PREFIX=/usr popd popd echo "Done." fi which /opt/nsb_bin/collectd/collectd >/dev/null if [ $? -eq 0 ] then echo "Collectd already installed. Done" else pushd . echo "Get collectd from repository and install..." rm -rf collectd >/dev/null git clone https://github.com/collectd/collectd.git pushd collectd git stash git checkout -b collectd 43a4db3b3209f497a0ba408aebf8aee385c6262d ./build.sh ./configure --with-libpqos=/usr/ make install > /dev/null popd echo "Done." popd fi modprobe msr cp $INSTALL_NSB_BIN/collectd.conf /opt/collectd/etc/ echo "Check if admin user already created" rabbitmqctl list_users | grep '^admin$' > /dev/null if [ $? -eq 0 ]; then echo "'admin' user already created..." else echo "Creating 'admin' user for collectd data export..." rabbitmqctl delete_user guest rabbitmqctl add_user admin admin rabbitmqctl authenticate_user admin admin rabbitmqctl set_permissions -p / admin ".*" ".*" ".*" echo "Done" fi
Python
UTF-8
627
4.28125
4
[]
no_license
#6. take a string from the user and check contains only alphabets or not import re user_string = raw_input("Enter String:") print "Without Regular Expressions" for i in user_string: if not i.isalpha(): flag = 0 break else: flag = 1 if flag == 1: print "\nString contains only Alphabets" else: print "\nNot a Aplhabet Only String" user_string1 = raw_input("\nEnter String:") print "With Regular Expressions" # checking only for chars in string not for digits res = re.match('[A-Za-z].', user_string1) if res: print "\nContains only Alphabets" else: print "\nNot a Alphabet Only String"
Java
UTF-8
1,905
1.984375
2
[]
no_license
package com.aichu.admin.vo.request; import com.aichu.common.util.api.BasePageOrder; import io.swagger.annotations.ApiModelProperty; /** * @program: ai-chu * @description * @author: Yuan.shuai * @create: 2020-02-17 15:35 **/ public class AcOrderBaseRefundQueryRequest extends BasePageOrder { @ApiModelProperty(name = "name", value = "关键词",hidden = false) private String name; @ApiModelProperty(name = "refundStatus", value = "退款状态(0-退款中,1-已拒绝,2-已通过, 3-退款失败)",hidden = false) private Integer refundStatus; @ApiModelProperty(name = "consumeType", value = "消费类型(0-充值,1-提现,2-优惠卡,3-直播打赏,4-直播付费, 5-代理提成)",hidden = false) private Integer consumeType; @ApiModelProperty(name = "startCreateTime", value = "交易开始时间",hidden = false) private String startCreateTime; @ApiModelProperty(name = "endCreateTime", value = "交易截止时间",hidden = false) private String endCreateTime; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getRefundStatus() { return refundStatus; } public void setRefundStatus(Integer refundStatus) { this.refundStatus = refundStatus; } public String getStartCreateTime() { return startCreateTime; } public void setStartCreateTime(String startCreateTime) { this.startCreateTime = startCreateTime; } public String getEndCreateTime() { return endCreateTime; } public void setEndCreateTime(String endCreateTime) { this.endCreateTime = endCreateTime; } public Integer getConsumeType() { return consumeType; } public void setConsumeType(Integer consumeType) { this.consumeType = consumeType; } }
Markdown
UTF-8
1,318
3.140625
3
[]
no_license
# Production Problem 09: Usability Checklists ## The Problem Usability checklists are typical, and sometimes mindless, tools/magic tricks used to find usability problems in web and other digital projects. What you are going to do for this Production Problem is to locate at least 2 different usability checklists of at least 25 items (use Google, but challenge yourself to go beyond the first page of results). From those lists, create your own, condensed list of exactly ten items. Share with your group for Project 3 to help yourselves create your own master usability checklist. ## Deliverables * URLs for the usability checklists you've found: 1. https://stayintech.com/info/UX 2. https://medium.com/the-mvp/the-usability-checklist-for-visual-design-9ca1ea44dc83#.b6ev8zal1 * Your own condensed, ten-item must-have usability checklist: 1. Homepage - Create a positive first impression 2. Logged in user's name is displayed on the site 3. Appropriate color usage 4. Consistency in colors, fonts, element sizes, spacings, and navigation 5. Meaningful images and videos 6. Links, buttons, and checkboxes are easily clickable 7. Important content is displayed first 8. Site is responsive - works with different screen sizes 9. Related information is grouped together clearly 10. Site works in various browsers
JavaScript
UTF-8
308
2.578125
3
[]
no_license
import React, { useEffect, useState } from "react"; const Add = () => { const [num, setNum] = useState(0); useEffect(()=>{ alert("i am clicked") }) return ( <button onClick={() => { setNum(num + 1); }} > click me {num} </button> ); }; export default Add;
JavaScript
UTF-8
485
3.78125
4
[]
no_license
function speedOmeter(speed) { speed = Number(speed); let result = ""; if (speed <= 10) { result = "slow"; } else if ((10 < speed) & (speed <= 50)) { result = "average"; } else if ((50 < speed) & (speed <= 150)) { result = "fast"; } else if ((150 < speed) & (speed <= 1000)) { result = "ultra fast"; } else if (speed > 1000) { result = "extremely fast"; } console.log(result) } speedOmeter("8")
Swift
UTF-8
701
3.28125
3
[]
no_license
// // ingredients.swift // Bootcamp_Recipe // // Created by Bakiza Zhanbatyrova on 2017-03-16. // Copyright (c) 2017 Zavier Patrick David Aguila. All rights reserved. // import Foundation class Ingredients{ init(food_quantity: Float, name: String, calories: Int){ self.food_quantity = food_quantity self.name = name self.calories = calories } private(set)var food_quantity: Float private(set)var name: String private(set)var calories: Int func add(amount: Float) { food_quantity = food_quantity + amount } func subtract(amount: Float) { food_quantity = food_quantity - amount } func isempty() -> (Bool) { return (food_quantity == 0) } }
PHP
UTF-8
1,273
3.390625
3
[]
no_license
<?php // $handle = fopen('sampleInput.txt', 'r'); $handle = fopen('input.txt', 'r'); $twosCount = 0; $threesCount = 0; while (($line = fgets($handle, 4096)) !== false) { // TODO remove newline? don't need to, only one per line, won't be dupes of it // echo "raw line: $line"; $lineArray = str_split($line); sort($lineArray); // echo "sorted line: " . json_encode($lineArray) . "\n"; unset($currentChar); $lineArray[] = "end"; // this is cheesy but it ensures our last character doesn't match any previous (because it's 3 chars), gives us an end step $currentCount = 0; $hasTwo = false; $hasThree = false; foreach ($lineArray as $char) { if(!isset($currentChar)) { $currentChar = $char; } if ($currentChar === $char) { $currentCount++; } else { if($currentCount === 2) { $hasTwo = true; } else if($currentCount === 3) { $hasThree = true; } $currentChar = $char; $currentCount = 1; } } if ($hasTwo === true) { $twosCount++; } if ($hasThree === true) { $threesCount++; } // echo "Processed " . json_encode($lineArray) . " new twosCount is $twosCount and threes is $threesCount\n"; } $checksum = $twosCount * $threesCount; echo "checksum: $checksum\n";
Python
UTF-8
1,011
2.53125
3
[ "BSD-3-Clause" ]
permissive
#!/usr/bin/python import os import sys import time import termios import fcntl from Adafruit_PWM_Servo_Driver import PWM # Terminal init stuff found on stackoverflow (SlashV) fd = sys.stdin.fileno() oldterm = termios.tcgetattr(fd) newattr = termios.tcgetattr(fd) newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO termios.tcsetattr(fd, termios.TCSANOW, newattr) oldflags = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK) # Init PWM pwm = PWM(0x40, debug=True) pwm.setPWMFreq(60) # min/max found by trial and error: servoMin = 130 servoMax = 610 pos = servoMin try: while (True): try: c = sys.stdin.read(1) except IOError: c = '' if c == "-": pos -= 10 elif c == "+": pos += 10 sys.stdout.write("\r%d" % pos) sys.stdout.flush() pwm.setPWM(0, 0, pos) #time.sleep(.1) except: pass finally: # Reset terminal termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
Java
UTF-8
18,476
2.234375
2
[ "Apache-2.0", "MIT", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tubemq.server.common.offsetstorage.zookeeper; import java.io.IOException; import java.util.ArrayList; import org.apache.commons.codec.binary.StringUtils; import org.apache.tubemq.corebase.TBaseConstants; import org.apache.tubemq.server.common.fileconfig.ZKConfig; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.KeeperException.NoNodeException; import org.apache.zookeeper.KeeperException.NodeExistsException; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooDefs.Ids; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Internal utility class for ZooKeeper. * <p> * <p>Contains only static methods and constants. * <p> * <p>Methods all throw {@link KeeperException} if there is an unexpected * zookeeper exception, so callers of these methods must handle appropriately. * If ZK is required for the operation, the server will need to be aborted. * * Copied from <a href="http://hbase.apache.org">Apache HBase Project</a> */ public class ZKUtil { private static final Logger logger = LoggerFactory.getLogger(ZKUtil.class); private static final int RETRY_TIMES = 3; private static final int RETRY_INTERVAL = 1000; private static final int SOCKET_RETRY_WAIT_MS = 200; private static final int DEFAULT_ZOOKEEPER_CLIENT_PORT = 2181; // Replace this with ZooKeeper constant when ZOOKEEPER-277 is resolved. private static final char ZNODE_PATH_SEPARATOR = '/'; /** * Creates a new connection to ZooKeeper, pulling settings and ensemble config from the * specified configuration object using methods from {@link ZKConfig} . * <p/> * Sets the connection status monitoring watcher to the specified watcher. * <p/> * configuration to pull ensemble and other settings from * * @param watcher watcher to monitor connection changes * @return connection to zookeeper * @throws IOException if unable to connect to zk or config problem */ public static RecoverableZooKeeper connect(ZKConfig zkConfig, Watcher watcher) throws IOException { if (zkConfig.getZkServerAddr() == null) { throw new IOException("Unable to determine ZooKeeper Server Address String"); } return new RecoverableZooKeeper(zkConfig.getZkServerAddr(), zkConfig.getZkSessionTimeoutMs(), watcher, RETRY_TIMES, RETRY_INTERVAL); } // // Helper methods // /** * Join the prefix znode name with the suffix znode name to generate a proper full znode name. * <p/> * Assumes prefix does not end with slash and suffix does not begin with it. * * @param prefix beginning of znode name * @param suffix ending of znode name * @return result of properly joining prefix with suffix */ public static String joinZNode(String prefix, String suffix) { return prefix + ZNODE_PATH_SEPARATOR + suffix; } /** * Returns the full path of the immediate parent of the specified node. * * @param node path to get parent of * @return parent of path, null if passed the root node or an invalid node */ public static String getParent(String node) { int idx = node.lastIndexOf(ZNODE_PATH_SEPARATOR); return idx <= 0 ? null : node.substring(0, idx); } /** * Check if the specified node exists. Sets no watches. * <p/> * Returns true if node exists, false if not. Returns an exception if there is an unexpected * zookeeper exception. * * @param zkw zk reference * @param znode path of node to watch * @return version of the node if it exists, -1 if does not exist * @throws KeeperException if unexpected zookeeper exception */ public static int checkExists(ZooKeeperWatcher zkw, String znode) throws KeeperException { try { Stat s = zkw.getRecoverableZooKeeper().exists(znode, null); return s != null ? s.getVersion() : -1; } catch (KeeperException e) { logger.warn(zkw.prefix("Unable to set watcher on znode (" + znode + ")"), e); zkw.keeperException(e); return -1; } catch (InterruptedException e) { logger.warn(zkw.prefix("Unable to set watcher on znode (" + znode + ")"), e); zkw.interruptedException(e); return -1; } } /** * Get the data at the specified znode and set a watch. * <p/> * Returns the data and sets a watch if the node exists. Returns null and no watch is set if the * node does not exist or there is an exception. * * @param zkw zk reference * @param znode path of node * @return data of the specified znode, or null * @throws KeeperException if unexpected zookeeper exception */ public static byte[] getDataAndWatch(ZooKeeperWatcher zkw, String znode) throws KeeperException { return getDataInternal(zkw, znode, null, true); } private static byte[] getDataInternal(ZooKeeperWatcher zkw, String znode, Stat stat, boolean watcherSet) throws KeeperException { try { byte[] data = zkw.getRecoverableZooKeeper().getData(znode, zkw, stat); logRetrievedMsg(zkw, znode, data, watcherSet); return data; } catch (KeeperException.NoNodeException e) { if (logger.isDebugEnabled()) { logger.debug(zkw.prefix("Unable to get data of znode " + znode + " " + "because node does not exist (not an error)")); } return null; } catch (KeeperException e) { logger.warn(zkw.prefix("Unable to get data of znode " + znode), e); zkw.keeperException(e); return null; } catch (InterruptedException e) { logger.warn(zkw.prefix("Unable to get data of znode " + znode), e); zkw.interruptedException(e); return null; } } /** * Sets the data of the existing znode to be the specified data. Ensures that the current data * has the specified expected version. * <p/> * <p/> * If the node does not exist, a {@link NoNodeException} will be thrown. * <p/> * <p/> * If their is a version mismatch, method returns null. * <p/> * <p/> * No watches are set but setting data will trigger other watchers of this node. * <p/> * <p/> * If there is another problem, a KeeperException will be thrown. * * @param zkw zk reference * @param znode path of node * @param data data to set for node * @param expectedVersion version expected when setting data * @return true if data set, false if version mismatch * @throws KeeperException if unexpected zookeeper exception */ public static boolean setData(ZooKeeperWatcher zkw, String znode, byte[] data, int expectedVersion) throws KeeperException, KeeperException.NoNodeException { try { return zkw.getRecoverableZooKeeper().setData(znode, data, expectedVersion) != null; } catch (InterruptedException e) { zkw.interruptedException(e); return false; } } /** * Sets the data of the existing znode to be the specified data. The node must exist but no * checks are done on the existing data or version. * <p/> * <p/> * If the node does not exist, a {@link NoNodeException} will be thrown. * <p/> * <p/> * No watches are set but setting data will trigger other watchers of this node. * <p/> * <p/> * If there is another problem, a KeeperException will be thrown. * * @param zkw zk reference * @param znode path of node * @param data data to set for node * @throws KeeperException if unexpected zookeeper exception */ public static void setData(ZooKeeperWatcher zkw, String znode, byte[] data) throws KeeperException { setData(zkw, znode, data, -1); } // // Data setting // /** * Set data into node creating node if it doesn't yet exist. Does not set watch. * * @param zkw zk reference * @param znode path of node * @param data data to set for node */ public static void createSetData(final ZooKeeperWatcher zkw, final String znode, final byte[] data) throws KeeperException { if (checkExists(zkw, znode) == -1) { createWithParents(zkw, znode); } setData(zkw, znode, data); } public static boolean isSecureZooKeeper() { return (System.getProperty("java.security.auth.login.config") != null && System.getProperty("zookeeper.sasl.clientconfig") != null); } private static ArrayList<ACL> createACL(ZooKeeperWatcher zkw, String node) { if (isSecureZooKeeper()) { if (node.equals(zkw.getBaseZNode())) { return ZooKeeperWatcher.CREATOR_ALL_AND_WORLD_READABLE; } return Ids.CREATOR_ALL_ACL; } else { return Ids.OPEN_ACL_UNSAFE; } } public static void waitForZKConnectionIfAuthenticating(ZooKeeperWatcher zkw) throws InterruptedException { if (isSecureZooKeeper()) { if (logger.isDebugEnabled()) { logger.debug("Waiting for ZooKeeperWatcher to authenticate"); } zkw.saslLatchAwait(); if (logger.isDebugEnabled()) { logger.debug("Done waiting."); } } } /** * Creates the specified node with the specified data and watches it. * <p/> * <p/> * Throws an exception if the node already exists. * <p/> * <p/> * The node created is persistent and open access. * <p/> * <p/> * Returns the version number of the created node if successful. * * @param zkw zk reference * @param znode path of node to create * @param data data of node to create * @return version of node created * @throws KeeperException if unexpected zookeeper exception * @throws KeeperException.NodeExistsException if node already exists */ public static int createAndWatch(ZooKeeperWatcher zkw, String znode, byte[] data) throws KeeperException, KeeperException.NodeExistsException { try { waitForZKConnectionIfAuthenticating(zkw); zkw.getRecoverableZooKeeper().create(znode, data, createACL(zkw, znode), CreateMode.PERSISTENT); Stat stat = zkw.getRecoverableZooKeeper().exists(znode, zkw); if (stat == null) { return -1; } return stat.getVersion(); } catch (InterruptedException e) { zkw.interruptedException(e); return -1; } } /** * Creates the specified node, if the node does not exist. Does not set a watch and fails * silently if the node already exists. * <p/> * The node created is persistent and open access. * * @param zkw zk reference * @param znode path of node * @throws KeeperException if unexpected zookeeper exception */ public static void createAndFailSilent(ZooKeeperWatcher zkw, String znode) throws KeeperException { try { RecoverableZooKeeper zk = zkw.getRecoverableZooKeeper(); waitForZKConnectionIfAuthenticating(zkw); if (zk.exists(znode, false) == null) { zk.create(znode, new byte[0], createACL(zkw, znode), CreateMode.PERSISTENT); } } catch (KeeperException.NodeExistsException nee) { // } catch (KeeperException.NoAuthException nee) { try { if (null == zkw.getRecoverableZooKeeper().exists(znode, false)) { // If we failed to create the file and it does not already // exist. throw (nee); } } catch (InterruptedException ie) { zkw.interruptedException(ie); } } catch (InterruptedException ie) { zkw.interruptedException(ie); } } /** * Creates the specified node and all parent nodes required for it to exist. * <p/> * No watches are set and no errors are thrown if the node already exists. * <p/> * The nodes created are persistent and open access. * * @param zkw zk reference * @param znode path of node * @throws KeeperException if unexpected zookeeper exception */ public static void createWithParents(ZooKeeperWatcher zkw, String znode) throws KeeperException { try { if (znode == null) { return; } waitForZKConnectionIfAuthenticating(zkw); zkw.getRecoverableZooKeeper().create(znode, new byte[0], createACL(zkw, znode), CreateMode.PERSISTENT); } catch (KeeperException.NodeExistsException nee) { return; } catch (KeeperException.NoNodeException nne) { createWithParents(zkw, getParent(znode)); createWithParents(zkw, znode); } catch (InterruptedException ie) { zkw.interruptedException(ie); } } private static void logRetrievedMsg(final ZooKeeperWatcher zkw, final String znode, final byte[] data, final boolean watcherSet) { if (!logger.isDebugEnabled()) { return; } logger.debug(zkw.prefix("Retrieved " + ((data == null) ? 0 : data.length) + " byte(s) of data from znode " + znode + (watcherSet ? " and set watcher; " : "; data=") + (data == null ? "null" : data.length == 0 ? "empty" : new String(data)))); } /** * Create a persistent node. * * @param createParents if true all parent dirs are created as well and no {@link * NodeExistsException} is thrown in case the path already exists * @throws InterruptedException if operation was interrupted, or a required reconnection got * interrupted * @throws IllegalArgumentException if called from anything except the ZooKeeper event thread * @throws KeeperException if any ZooKeeper exception occurred * @throws RuntimeException if any other exception occurs */ public static void createPersistent(ZooKeeperWatcher zkw, String path, boolean createParents) throws KeeperException { try { ZKUtil.createAndWatch(zkw, path, null); } catch (NodeExistsException e) { if (!createParents) { throw e; } } catch (NoNodeException e) { if (!createParents) { throw e; } String parentDir = path.substring(0, path.lastIndexOf('/')); createPersistent(zkw, parentDir, createParents); createPersistent(zkw, path, createParents); } } // TODO: Double check the replacement /*---------------------------------------------------------*/ /*---------------------------------------------------------*/ /* Following APIs added by Denny */ /* The APIs are nearly compatible with old tube */ /*---------------------------------------------------------*/ /*---------------------------------------------------------*/ /** * create the parent path */ public static void createParentPath(final ZooKeeperWatcher zkw, final String path) throws Exception { final String parentDir = path.substring(0, path.lastIndexOf('/')); if (parentDir.length() != 0) { ZKUtil.createPersistent(zkw, parentDir, true); } } /** * Update the value of a persistent node with the given path and data. create parent directory * if necessary. Never throw NodeExistException. */ public static void updatePersistentPath(final ZooKeeperWatcher zkw, final String path, final String data) throws Exception { byte[] bytes = (data == null ? null : StringUtils.getBytesUtf8(data)); try { ZKUtil.setData(zkw, path, bytes); } catch (final NoNodeException e) { createParentPath(zkw, path); ZKUtil.createAndWatch(zkw, path, bytes); } catch (final Exception e) { throw e; } } public static String readData(final ZooKeeperWatcher zkw, final String path) throws KeeperException { byte[] bytes = ZKUtil.getDataAndWatch(zkw, path); if (bytes == null) { return null; } try { return new String(bytes, TBaseConstants.META_DEFAULT_CHARSET_NAME); } catch (Throwable e) { logger.error("readData from " + path + " error! bytes is " + new String(bytes), e); } return null; } public static String readDataMaybeNull(final ZooKeeperWatcher zkw, final String path) throws KeeperException { try { return readData(zkw, path); } catch (NoNodeException e) { return null; } } }
Java
UTF-8
380
1.859375
2
[]
no_license
package mapper; import domain.ItemsCustom; import domain.ItemsQueryVo; import java.util.List; public interface ItemsMapperCustom { // 商品查询列表 List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception; ItemsCustom findItemsById(Integer id) throws Exception; void updateItems(ItemsCustom itemsCustom) throws Exception; }
Shell
UTF-8
1,182
3.09375
3
[ "Apache-2.0" ]
permissive
#!/bin/bash # set -x if [ $# -ne 3 ]; then echo "usage: ./self scheduler_node mpi.conf dir_of_mpi_node_sh" exit -1; fi # support mpich and openmpi # try mpirun -n 1 env to get all available environment if [ ! -z ${PMI_RANK} ]; then my_rank=${PMI_RANK} elif [ ! -z ${OMPI_COMM_WORLD_RANK} ]; then my_rank=${OMPI_COMM_WORLD_RANK} else echo "failed to get my rank id" exit -1 fi if [ ! -z ${PMI_SIZE} ]; then rank_size=${PMI_SIZE} elif [ ! -z ${OMPI_COMM_WORLD_SIZE} ]; then rank_size=${OMPI_COMM_WORLD_SIZE} else echo "failed to get the rank size" exit -1 fi # echo "$my_rank $rank_size" source ${2} if (( ${rank_size} < ${num_workers} + ${num_servers} + 1 )); then echo "too small rank size ${rank_size}" exit -1 fi mkdir -p ${3}/../output ${3}/ps \ -num_servers ${num_servers} \ -num_workers ${num_workers} \ -num_threads ${num_threads} \ -scheduler ${1} \ -my_rank ${my_rank} \ -app ${3}/${app_conf} \ -report_interval ${report_interval} \ ${verbose} \ ${log_to_file} \ ${log_instant} \ ${print_van} \ ${shuffle_fea_id} \ || { echo "rank:${my_rank} launch failed"; exit -1; }
C++
UTF-8
981
3.65625
4
[]
no_license
#include "max_heap.h" max_heap::max_heap(int n) { data = new int[n]; node = 1; length = 0; } void max_heap::shift_up(int index) { if(index > 1) { int temp = data[index]; data[index] = data[index/2]; data[index/2] = temp; } } void max_heap::insert(int element) { data[node] = element; int index = node; node++; length++; while (element > data[index/2] && index > 1) { shift_up(index); index /= 2; } } int max_heap::peek() { if(length>0) return data[1]; return 0; } void max_heap::delete_max(int index) { if(length>0 && index < node) { int index_to_push = (data[2*index] > data[2*index + 1] ? 2*index : 2*index + 1); shift_up(index_to_push); delete_max(index_to_push); node--; length--; } } int max_heap::extract_max() { int ret = data[0]; delete_max(); return ret; } int *max_heap::ret_array() { int *ret = new int[1]; for (int i=0; i < length; i++) ret[i] = data[i+1]; return ret; } int max_heap::size() { return length; }
Python
UTF-8
1,437
4.5
4
[]
no_license
#Creating a mapping of state to abbreviation states = { #Create a dict for states 'Oregon': 'OR', 'Florida': 'FL', 'California': 'CA', 'New York': 'NY', 'Michigan': 'MI' } #create a basic set of states and some cities in them cities = { #create a dict for cities 'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville' } #add some more cities cities['NY'] = 'New York' cities['OR'] = 'Portland' # print out some cities print('-' * 10) print("NY State has: ", cities['NY']) print("OR State has: ", cities['OR']) #print some states print('-' * 10) print("Michigan's abbreviation is: ", states['Michigan']) print("Florida's abbreviation is : ",states['Florida']) #do it by using the state then cities dict print('-' * 10) print("Michigan has: ", cities[states['Michigan']]) print("Florida has: ", cities[states['Florida']]) #print every state abbreviation print('-' * 10) for abbrev, city in list(cities.items()): # cities.items() return key and value as a list #list funct not necessary print(f"{states} state is abbreviated {abbrev}") print(f"and has cuty {cities[abbrev]}") print("-" * 10) #safely get a abbreviation by state that might nit be in there state = states.get('Texas') if not state: print("Sorry, no Texas.") # get a citty with a deafdault value city = cities.get('TX', 'Does not exist') print(f"The cuty for state 'TX' is: {city}")
Python
UTF-8
1,220
2.625
3
[]
no_license
import pymysql from constants import * def getQuery(tableName, tgtCol = 'evalCol'): return 'SELECT * FROM ' + tableName + ' AS t1 INNER JOIN (SELECT max(' + tgtCol + ') as evalColMax FROM ' + tableName + ') AS t2 ON t1.' + tgtCol + ' = t2.evalColMax' inputFileAttrs = open('data/dictOfAttributesFile.txt', 'r') dictOfAttrs = eval(inputFileAttrs.read()) inputFileCategories = open('data/listOfCategoriesFile.txt', 'r') listOfCategories = eval(inputFileCategories.read()) for category in listOfCategories: con = pymysql.connect(HOST_NAME, USER_NAME, USER_PASSWORD, DB_NAME, cursorclass=pymysql.cursors.DictCursor) cur = con.cursor() cur.execute(getQuery('positions_with_category_ext_' + category)) for uniqueAnswer in cur.fetchall(): print('В категории \"' + uniqueAnswer['CategoryName'] + '\" товар \"' + uniqueAnswer['ProductPositionName'] + '\" уникален по следующим характеристикам: ') for key in uniqueAnswer: if key[:8] != 'attr_id_' or uniqueAnswer[key] == None: continue print('\t' + dictOfAttrs[key] + ': ' + uniqueAnswer[key]) print('=============================') con.close()
Java
UTF-8
3,429
2.25
2
[]
no_license
package com.MavenGitEclipse; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.HashMap; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; import com.MavenGitEclipse.pojo.Datanova; import com.fasterxml.jackson.databind.ObjectMapper; public class WebServices { private static String retrieve(String URI) { StringBuilder output = new StringBuilder(); try { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); // Create all-trusting host name verifier HostnameVerifier allHostsValid = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; // Install the all-trusting host verifier HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); URL url = new URL(URI); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader( (conn.getInputStream()))); String test; while ((test = br.readLine()) != null){ output.append(test); } br.close(); conn.disconnect(); } catch (IOException | NoSuchAlgorithmException | KeyManagementException e){ e.printStackTrace(); } return output.substring(0); } public static Datanova getDatas(String rows) { String json = retrieve("http://datanova.legroupe.laposte.fr/api/records/1.0/search/?dataset=laposte_hexasmal&rows="+rows); System.out.println("le json : "+json); ObjectMapper mapper = new ObjectMapper(); Datanova data = null; try { data = mapper.readValue(json, Datanova.class); } catch (IOException e) { e.printStackTrace(); } return data; } }
C++
UTF-8
3,712
2.640625
3
[ "MIT" ]
permissive
/*! * util.cc (https://github.com/SamsungDForum/NativePlayer) * Copyright 2016, Samsung Electronics Co., Ltd * Licensed under the MIT license * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @author Adam Bujalski * @author Tomasz Borkowski */ #include <string> #include <vector> #include "util.h" #include "segment_base_sequence.h" #include "segment_list_sequence.h" #include "segment_template_sequence.h" namespace { template <typename T> std::unique_ptr<MediaSegmentSequence> MakeSequence( const RepresentationDescription& representation, uint32_t bandwidth) { return std::unique_ptr<MediaSegmentSequence>{ new T(representation, bandwidth)}; } } RepresentationDescription MakeEmptyRepresentation() { RepresentationDescription representation; representation.segment_base = nullptr; representation.segment_list = nullptr; representation.segment_template = nullptr; return representation; } std::unique_ptr<MediaSegmentSequence> CreateSequence( const RepresentationDescription& representation, uint32_t bandwidth) { if (representation.segment_base) return MakeSequence<SegmentBaseSequence>(representation, bandwidth); if (representation.segment_list) return MakeSequence<SegmentListSequence>(representation, bandwidth); if (representation.segment_template) return MakeSequence<SegmentTemplateSequence>(representation, bandwidth); return {}; } double ParseDurationToSeconds(const std::string& duration_str) { // We don't support negative duration, years and months. if (duration_str.empty() || duration_str[0] != 'P') // 'P' is obligatory. return kInvalidDuration; double duration_in_seconds = 0; uint32_t digits_in_a_row = 0; const double kSecondsInMinute = 60; const double kSecondsInHour = 60 * kSecondsInMinute; const double kSecondsInDay = 24 * kSecondsInHour; bool time_flag_occured = false; // begin from 1, because first character has been checked already for (uint32_t i = 1; i < duration_str.length(); ++i) { if (isdigit(duration_str[i]) || duration_str[i] == '.') { ++digits_in_a_row; continue; } double multiplier = 0; switch (duration_str[i]) { // we don't support years and months case 'D': multiplier = kSecondsInDay; break; case 'T': time_flag_occured = true; break; case 'H': multiplier = kSecondsInHour; break; case 'M': // 'M' means months or if there was a 'T' flag - minutes if (time_flag_occured) multiplier = kSecondsInMinute; else return kInvalidDuration; break; case 'S': multiplier = 1; break; default: return kInvalidDuration; } if (digits_in_a_row > 0) { double value = std::atof( duration_str.substr(i - digits_in_a_row, digits_in_a_row).c_str()); duration_in_seconds += value * multiplier; digits_in_a_row = 0; } } return duration_in_seconds; }
Java
UTF-8
5,917
2.046875
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2019 sulzbachr. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.clownfish.clownfish.dbrepository; import io.clownfish.clownfish.daointerface.CfAssetDAO; import io.clownfish.clownfish.dbentities.CfAsset; import java.math.BigInteger; import java.util.List; import javax.persistence.TypedQuery; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; /** * * @author sulzbachr */ @Repository public class CfAssetDAOImpl implements CfAssetDAO { private final SessionFactory sessionFactory; @Autowired public CfAssetDAOImpl(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Override public CfAsset findById(Long id) { Session session = this.sessionFactory.getCurrentSession(); TypedQuery query = (TypedQuery) session.getNamedQuery("CfAsset.findById"); query.setParameter("id", id); try { CfAsset cfasset = (CfAsset) query.getSingleResult(); if (!cfasset.isScrapped()) { return cfasset; } else { return null; } } catch (Exception ex) { System.out.println("Asset-ID not found: " + id); return null; } } @Override public CfAsset create(CfAsset entity) { Session session = this.sessionFactory.getCurrentSession(); session.persist(entity); return entity; } @Override public boolean delete(CfAsset entity) { Session session = this.sessionFactory.getCurrentSession(); session.delete(entity); return true; } @Override public CfAsset edit(CfAsset entity) { Session session = this.sessionFactory.getCurrentSession(); session.merge(entity); return entity; } @Override public List<CfAsset> findAll() { Session session = this.sessionFactory.getCurrentSession(); TypedQuery query = (TypedQuery) session.getNamedQuery("CfAsset.findAll"); List<CfAsset> cfassetlist = query.getResultList(); return cfassetlist; } @Override public CfAsset findByName(String name) { Session session = this.sessionFactory.getCurrentSession(); TypedQuery query = (TypedQuery) session.getNamedQuery("CfAsset.findByName"); query.setParameter("name", name); CfAsset cfasset = (CfAsset) query.getSingleResult(); return cfasset; } @Override public List<CfAsset> findByIndexed(boolean indexed) { Session session = this.sessionFactory.getCurrentSession(); TypedQuery query = (TypedQuery) session.getNamedQuery("CfAsset.findByIndexed"); query.setParameter("indexed", indexed); List<CfAsset> cfassetlist = query.getResultList(); return cfassetlist; } @Override public List<CfAsset> findByScrapped(boolean scrapped) { Session session = this.sessionFactory.getCurrentSession(); TypedQuery query = (TypedQuery) session.getNamedQuery("CfAsset.findByScrapped"); query.setParameter("scrapped", scrapped); List<CfAsset> cfassetlist = query.getResultList(); return cfassetlist; } @Override public List<CfAsset> findByPublicuse(boolean publicuse) { Session session = this.sessionFactory.getCurrentSession(); TypedQuery query = (TypedQuery) session.getNamedQuery("CfAsset.findByPublicuse"); query.setParameter("publicuse", publicuse); List<CfAsset> cfassetlist = query.getResultList(); return cfassetlist; } @Override public List<CfAsset> findByFilesize(long filesize) { Session session = this.sessionFactory.getCurrentSession(); TypedQuery query = (TypedQuery) session.getNamedQuery("CfAsset.findByFilesize"); query.setParameter("filesize", filesize); List<CfAsset> cfassetlist = query.getResultList(); return cfassetlist; } @Override public List<CfAsset> findByAvatars() { Session session = this.sessionFactory.getCurrentSession(); TypedQuery query = (TypedQuery) session.getNamedQuery("CfAsset.findByAvatars"); List<CfAsset> cfassetlist = query.getResultList(); return cfassetlist; } @Override public List<CfAsset> findByPublicuseAndScrapped(boolean publicuse, boolean scrapped) { Session session = this.sessionFactory.getCurrentSession(); TypedQuery query = (TypedQuery) session.getNamedQuery("CfAsset.findByPublicuseAndScrapped"); query.setParameter("publicuse", publicuse); query.setParameter("scrapped", scrapped); List<CfAsset> cfassetlist = query.getResultList(); return cfassetlist; } @Override public List<CfAsset> findByPublicuseAndScrappedNotInList(boolean publicuse, boolean scrapped, BigInteger ref) { Session session = this.sessionFactory.getCurrentSession(); TypedQuery query = (TypedQuery) session.getNamedQuery("CfAsset.findByPublicuseAndScrappedNotInList"); query.setParameter("publicuse", publicuse); query.setParameter("scrapped", scrapped); query.setParameter("refclasscontent", ref); List<CfAsset> cfassetlist = query.getResultList(); return cfassetlist; } }
Python
UTF-8
1,213
3.296875
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Oct 13 20:37:59 2018 @author: paulhuynh """ import os import docx2txt import pandas as pd #set working directory os.chdir('/Users/christophrico/documents/msds_453/corpus') #function to retreive and turn document into text def retrieve_DSI(file_name): file_name=str(file_name) text = docx2txt.process(file_name) return text #Lists to store file name and body of text file_name=[] text=[] #for loop to iterate through documents in working directory for file in os.listdir('.'): #if statment to not attempt to open non word documents if file.endswith('.docx'): text_name=file #call function to obtain the text text_body=retrieve_DSI(file) #apped the file names and text to list file_name.append(text_name) text.append(text_body) #removed the variables used in the for loop del text_name, text_body, file #create dictionary for corpus corpus={'DSI_Title':file_name, 'Text': text} #output a CSV with containing the class corpus along with titles of corpus. #file saved in working directory. pd.DataFrame(corpus).to_csv('Class Corpus.csv', index=file_name)
PHP
UTF-8
1,070
2.640625
3
[]
no_license
<?php session_start(); include('../connect.php'); $a = $_POST['caption']; $b = $_POST['desc']; // query $vid = $_FILES["file"] ["name"]; $type = $_FILES["file"] ["type"]; $size = $_FILES["file"] ["size"]; $temp = $_FILES["file"] ["tmp_name"]; $error = $_FILES["file"] ["error"]; if ($error > 0){ die("Error uploading file! Code $error.");} else { if($size > 3000000000000) //conditions for the file { die("Format is not allowed or file size is too big!"); } else { move_uploaded_file($temp,"../videos/".$vid); //do your write to the database filename and other details $sql = "INSERT INTO books (video_title,video_detail,file,date) VALUES (:a,:b,:c, NOW())"; $q = $db->prepare($sql); $q->execute(array(':a'=>$a,':b'=>$b,':c'=>$vid)); if($q){ header("location:add-video.php?success=true"); }else{ header("location:add-video.php?failed=true"); } } } ?>
Swift
UTF-8
1,297
2.921875
3
[]
no_license
// // Chat.swift // RideAlong // // Created by Erin Flynn on 4/25/17. // // import Foundation import Firebase class Chat { private var chatsRef: FIRDatabaseReference! private var _name: String? private var _otherID: String? private var _chatID: String? private var _Key: String? var chatID: String { return _chatID! } var name: String { return _name! } var otherID: String { return _otherID! } var key: String { return _Key! } // Initialize the new Joke init(key: String, dictionary: Dictionary<String, AnyObject>) { self._Key = key // Within the Joke, or Key, the following properties are children if let id = dictionary["otherID"] as? String { self._otherID = id } if let n = dictionary["name"] as? String { self._name = n } if let c = dictionary["chatID"] as? String { self._chatID = c } // The above properties are assigned to their key. let uid = FIRAuth.auth()?.currentUser!.uid self.chatsRef = FIRDatabase.database().reference().child("MyChats").child(uid!).child(self._Key!) } }