language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
1,133
3
3
[ "Zlib" ]
permissive
package com.robototes.abomasnow; import edu.wpi.first.wpilibj.DigitalInput; /** * * @author sam */ public class LineSensorGroup { DigitalInput left; DigitalInput middle; DigitalInput right; LineSensorGroup(int l, int m, int r) { left = new DigitalInput(l); middle = new DigitalInput(m); right = new DigitalInput(r); } boolean[] get(){ boolean[] r = {left.get(), middle.get(), right.get()}; return r; } boolean getLeft() { return get()[0]; } boolean getMiddle() { return get()[1]; } boolean getRight() { return get()[2]; } int[] getNumbers() { int[] r = {left.get()?1:0,middle.get()?1:0,right.get()?1:0}; return r; } boolean allAreOff() { boolean r = false; r = (this.getLeft() == this.getMiddle() == this.getRight() == false) ? true : false; return r; } boolean allAreOn() { boolean r = false; r = (this.getLeft() == this.getMiddle() == this.getRight() == true) ? true : false; return r; } }
JavaScript
UTF-8
412
2.640625
3
[]
no_license
const index = require('./index'); const readline = require("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); const command = () => { rl.question("Enter command: ", function(values) { if (values === 'Q') { rl.close(); } else { index.runCommands(values); command(); } }); } command();
Go
UTF-8
1,961
4.0625
4
[ "MIT" ]
permissive
/* Vlad enjoys listening to music. He lives in Sam's Town. A few days ago he had a birthday, so his parents gave him a gift: MP3-player! Vlad was the happiest man in the world! Now he can listen his favorite songs whenever he wants! Vlad built up his own playlist. The playlist consists of N songs, each has a unique positive integer length. Vlad likes all the songs from his playlist, but there is a song, which he likes more than the others. It's named "Uncle Johny". After creation of the playlist, Vlad decided to sort the songs in increasing order of their lengths. For example, if the lengths of the songs in playlist was {1, 3, 5, 2, 4} after sorting it becomes {1, 2, 3, 4, 5}. Before the sorting, "Uncle Johny" was on K-th position (1-indexing is assumed for the playlist) in the playlist. Vlad needs your help! He gives you all the information of his playlist. Your task is to find the position of "Uncle Johny" in the sorted playlist. Input The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains one integer N denoting the number of songs in Vlad's playlist. The second line contains N space-separated integers A1, A2, ..., AN denoting the lenghts of Vlad's songs. The third line contains the only integer K - the position of "Uncle Johny" in the initial playlist. Output For each test case, output a single line containing the position of "Uncle Johny" in the sorted playlist.Constraints 1 ≤ T ≤ 1000 1 ≤ K ≤ N ≤ 100 1 ≤ Ai ≤ 10^9 */ package main import ( "sort" ) func main() { assert(johny([]int{1, 3, 4, 2}, 2) == 3) assert(johny([]int{1, 2, 3, 9, 4}, 5) == 4) assert(johny([]int{1, 2, 3, 9, 4}, 1) == 1) } func assert(x bool) { if !x { panic("assertion failed") } } func johny(a []int, k int) int { j := a[k-1] sort.Ints(a) i := sort.Search(len(a), func(i int) bool { return a[i] >= j }) return i + 1 }
Java
UTF-8
622
1.796875
2
[]
no_license
package nudt.web.repository; import nudt.web.entity.Permission; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import java.util.List; public interface PermissionRepository extends JpaRepository<Permission,Integer> { public List<Permission> findPermissionsByPid(Integer pid); // public Permission findPermissionById(Integer id); // public Permission findPermissionByName(String name); public void deletePermissionById(Integer id); }
Java
UTF-8
3,690
2.140625
2
[]
no_license
package dispositivos.moviles.karla.cuatro; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import com.squareup.picasso.Picasso; import dispositivos.moviles.karla.cuatro.AlbumAdapter2.AlbumAdapter2; /** * Created by ferKarly. * Clase-Programación de Dispositivos Moviles * Version -mil ocho mil */ public class EditAlbumActivity extends AppCompatActivity { private static final int NO_ID = -99; private static final String NO_WORD = "zzzzzzzzzzzzzzzzz"; private EditText editTituloView,editAlbumIdView,editIDView,editUrlView,editUrlThumbView; //for the intent reply. public static final String EXTRA_REPLY_T = "dispositivos.moviles.karla.cuatro.TITULO"; public static final String EXTRA_REPLY_A = "dispositivos.moviles.karla.cuatro.ALBUMID"; public static final String EXTRA_REPLY_I = "dispositivos.moviles.karla.cuatro.ID"; public static final String EXTRA_REPLY_U = "dispositivos.moviles.karla.cuatro.URL"; public static final String EXTRA_REPLY_Ut = "dispositivos.moviles.karla.cuatro.TURL"; private String url, turl; int mId = MainActivity.WORD_ADD; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_album); editTituloView = (EditText) findViewById(R.id.tituloEditView); editAlbumIdView = (EditText) findViewById(R.id.albumEditView); editIDView = (EditText) findViewById(R.id.idEditView); editUrlView = (EditText) findViewById(R.id.urlEditView); editUrlThumbView =(EditText) findViewById(R.id.thumbnailUrlEditView); Bundle extras = getIntent().getExtras(); if(extras != null) { mId = extras.getInt(AlbumAdapter2.EXTRA_ID, NO_ID); editTituloView.setHint(extras.getString(AlbumAdapter2.EXTRA_WORD, NO_WORD)); editAlbumIdView.setHint(extras.getString(AlbumAdapter2.EXTRA_AlbumId, NO_WORD)); editIDView.setHint(extras.getString(AlbumAdapter2.EXTRA_id, NO_WORD)); url = extras.getString(AlbumAdapter2.EXTRA_url, NO_WORD); turl = extras.getString(AlbumAdapter2.EXTRA_Turl, NO_WORD); editUrlView.setHint(url); editUrlThumbView.setHint(turl); Picasso.with(this).load(url).error(R.drawable.ic_info_black_24dp).into((ImageView) findViewById(R.id.imagenEditView)); Picasso.with(this).load(turl).error(R.drawable.ic_info_black_24dp).into((ImageView) findViewById(R.id.imagenEditView2)); } } public void returnReply(View view) { String word = editTituloView.getText().toString(); String albumIdA = editAlbumIdView.getText().toString(); String idA = editIDView.getText().toString(); String urlA = editUrlView.getText().toString(); String thumburlA = editUrlThumbView.getText().toString(); Intent replyIntent = new Intent(); replyIntent.putExtra(EXTRA_REPLY_T, word); replyIntent.putExtra(EXTRA_REPLY_A, albumIdA); replyIntent.putExtra(EXTRA_REPLY_I, idA); replyIntent.putExtra(EXTRA_REPLY_U, urlA); replyIntent.putExtra(EXTRA_REPLY_Ut, thumburlA); replyIntent.putExtra(AlbumAdapter2.EXTRA_ID, mId); setResult(RESULT_OK, replyIntent); finish(); } public void returnCancel(View view) { Intent replyIntent = new Intent(); replyIntent.putExtra(AlbumAdapter2.EXTRA_ID, mId); setResult(RESULT_CANCELED, replyIntent); finish(); } }
Python
UTF-8
642
3.203125
3
[]
no_license
import unittest import time """ 1.执行顺序是start-执行测试用例test01-end;test02也是如此 2.执行顺序是先执行setUp,然执行test*开头的用例,最后是后置tearDown 3.addtest没执行,说明只执行test开头的用例 """ class Test(unittest.TestCase): def setUp(self): print("start") def tearDown(self): time.sleep(1) print('end') def test02(self): print('执行测试用例test01') def test01(self): print('执行测试用例test02') def addtest(self): print('执行测试用例add方法') if __name__=='__main__': unittest.main()
Markdown
UTF-8
2,831
2.609375
3
[ "MIT" ]
permissive
--- layout: page label: portfolio title: "SKULLY Helmet AR-1" date: 2015-06-01 tags: - Industrial_Design - Mechanical_Eng - Creative_Direction - Player_Coach description: The flagship SKULLY AR-1 Helmet. image: /assets/img/skully_ar1_bg.jpg --- ### The SKULLY AR-1 helmet was the world's first augmented reality motorcycle helmet. Featuring a 180 degree rear view camera and a heads up display, it was a figher pilot helmet for motorcycle riders. I hired and led the Design Team at SKULLY and personally did hands on design work for everything needed for a complete experience from: physical helmet parts, in helmet UI, mobile companion applications and websites to shipping boxes and marketing collateral. I joined SKULLY as the VP of Design and expanded my role into VP of Product as we began planning multiple products and the larger SKULLY ecosystem. + **Role:** VP Product + **Team Size:** (5) 1 Industrial Designer, 1 Visual Designer, 3 Mechanical Engineers + **Company:** [SKULLY](https://en.wikipedia.org/wiki/Skully_(helmet)) + **Time Period:** Mid 2015 Big thanks on this project to the inimitable talents of designers [Jeff Broderick](http://brdrck.me/) and [Donald Burlock](http://www.theburlockgroup.com). Click the images to learn more. <a href="/assets/img/sk_ar1_img1.jpg" data-fancybox="gallery" data-caption="Early spec sheet showing off our features."> <img src="/assets/img/sk_ar1_img1.jpg" alt="" /> </a> <a href="/assets/img/sk_ar1_img4.jpg" data-fancybox="gallery" data-caption="Packaging concept art (all digital)."> <img src="/assets/img/sk_ar1_img4.jpg" alt="" /> </a> <a href="/assets/img/sk_ar1_img5.jpg" data-fancybox="gallery" data-caption="Sample of real cardboard packaging arriving at the office (you can see the coloring is incorrect)."> <img src="/assets/img/sk_ar1_img5.jpg" alt="" /> </a> <a href="/assets/img/sk_ar1_img6.jpg" data-fancybox="gallery" data-caption="Pelican case insert concept (digital)."> <img src="/assets/img/sk_ar1_img6.jpg" alt="" /> </a> <blockquote> Top 10 Invention of 2014 Truly Groundbreaking <cite>CNN</cite> </blockquote> <a href="/assets/img/sk_ar1_img2.jpg" data-fancybox="gallery" data-caption="Physical modeling to refine the fin shape for impact testing."> <img src="/assets/img/sk_ar1_img2.jpg" alt="" /> </a> <blockquote> The helmet for the digital age <cite>Popular Science</cite> </blockquote> <a href="/assets/img/sk_ar1_img3.jpg" data-fancybox="gallery" data-caption="First article inspection at the factory to ensure plastics and paint are up to our high standards."> <img src="/assets/img/sk_ar1_img3.jpg" alt="" /> </a> #### Watch this video for a quick overview of the SKULLY AR-1 Experience. #### <a data-fancybox href="https://www.youtube.com/embed/ZdcWd594lRw"> <img src="/assets/img/skullyVideo.jpg" alt=""> </a>
Markdown
UTF-8
970
2.546875
3
[]
no_license
# Учебный курс React JS. Полный Курс 2020 [React documentation](https://reactjs.org/). [React Hooks documentation](https://react-redux.js.org/api/hooks). На основании этого видео [![Основное видео](http://img.youtube.com/vi/9KJxaFHotqI/0.jpg)](http://www.youtube.com/watch?v=9KJxaFHotqI "Основное видео") ## Основные команды ### Создать новый проект ```bash npx create-react-app <имя проект> ``` Будет создана папка с именем проекта и установлены все зависимости. Вместо имени проекта можно использовать "." если мы находимся в текущей директории. ### `npm start` Запускает приложение в режиме разработки. ### `npm run build` Собирает приложение для релиза
Markdown
UTF-8
9,488
2.96875
3
[]
no_license
## Writeup Template ### You can use this file as a template for your writeup if you want to submit it as a markdown file, but feel free to use some other method and submit a pdf if you prefer. --- **Advanced Lane Finding Project** The goals / steps of this project are the following: * Compute the camera calibration matrix and distortion coefficients given a set of chessboard images. * Apply a distortion correction to raw images. * Use color transforms, gradients, etc., to create a thresholded binary image. * Apply a perspective transform to rectify binary image ("birds-eye view"). * Detect lane pixels and fit to find the lane boundary. * Determine the curvature of the lane and vehicle position with respect to center. * Warp the detected lane boundaries back onto the original image. * Output visual display of the lane boundaries and numerical estimation of lane curvature and vehicle position. [//]: # (Image References) [undistort]: ./output_images/undistort.png "Undistorted" [undistortroad]: ./output_images/undistortedroad.png "Road Transformed" [binary]: ./output_images/binary.png "Binary Example" [lanefit]: ./output_images/lanefit.png "Fit Visual" [annotated]: ./output_images/annotated.png "Output" [video1]: ./project_video.mp4 "Video" ## [Rubric](https://review.udacity.com/#!/rubrics/571/view) Points ### Here I will consider the rubric points individually and describe how I addressed each point in my implementation. --- ### Writeup / README #### 1. Provide a Writeup / README that includes all the rubric points and how you addressed each one. You can submit your writeup as markdown or pdf. [Here](https://github.com/udacity/CarND-Advanced-Lane-Lines/blob/master/writeup_template.md) is a template writeup for this project you can use as a guide and a starting point. You're reading it! ### Camera Calibration #### 1. Briefly state how you computed the camera matrix and distortion coefficients. Provide an example of a distortion corrected calibration image. The code for this step is contained in the second code cell of the IPython notebook located in "./camera_calibration.ipynb" I start by preparing "object points", which will be the (x, y, z) coordinates of the chessboard corners in the world. Here I am assuming the chessboard is fixed on the (x, y) plane at z=0, such that the object points are the same for each calibration image. Thus, `objp` is just a replicated array of coordinates, and `objpoints` will be appended with a copy of it every time I successfully detect all chessboard corners in a test image. `imgpoints` will be appended with the (x, y) pixel position of each of the corners in the image plane with each successful chessboard detection. I then used the output `objpoints` and `imgpoints` to compute the camera calibration and distortion coefficients using the `cv2.calibrateCamera()` function. I applied this distortion correction to the test image using the `cv2.undistort()` function and obtained this result: ![alt text][undistort] I take the transformation matrices and write them to a pickled file camera_cal.p for usage during lane detection. ### Pipeline (single images) #### 1. Provide an example of a distortion-corrected image. To demonstrate this step, I will describe how I apply the distortion correction to one of the test images like this one: ![alt text][undistortroad] I take the pickled calibration matrices and use the undistort #### 2. Describe how (and identify where in your code) you used color transforms, gradients or other methods to create a thresholded binary image. Provide an example of a binary image result. I used a combination of color and gradient thresholds to generate a binary image (thresholding steps at lines 216 through 248 in `laneutils.py`). Here's an example of my output for this step. The image was transformed into grayscale and HLS. I used the Sobel transform on the x dimension of the grayscaled image, Sobel x on the L channel, and value thresholding on the S channel. ![alt text][binary] #### 3. Describe how (and identify where in your code) you performed a perspective transform and provide an example of a transformed image. The code for my perspective transform is on lines 335 through 354 in the file `laneutils.py`. I chose the hardcode the source and destination points in the following manner: ```python slope = (680.-430.) / (265.-627.) ydes = 450 xdes = int((ydes-680.) / slope + 265.) slope2 = (430.-680.) / (655.-1049.) xdes2 = int((ydes-680.)/slope2 + 1045.) src = np.float32([[265, 680], [xdes, ydes], [xdes2, ydes], [1045, 680]]) dst = np.float32([[400, 700], [400, 100], [880, 100], [880, 700]]) ``` I pick points along straight lane lines to define the transformation trapezoid. I can slide up and down this trapezoid to define the far point of the transform using the variable ydes. This transforms to a fixed rectangular box in dst. I verified that my perspective transform was working as expected by drawing the `src` and `dst` points onto a test image and its warped counterpart to verify that the lines appear parallel in the warped image. ![alt text][binary] #### 4. Describe how (and identify where in your code) you identified lane-line pixels and fit their positions with a polynomial? `findLanes` function in laneutils.py starting line 55 uses the histogram method in a box to look for lane lines. I narrowed the box from the lecture to be 15% - 45% of the x dimension for the left lane and 55% to 85% for the right lane. Given my transformation points, I expect the lane to fall within this box and eliminate detection of other boundaries like railings. Then starting from the bottom successive boxes in the y dimension are used to select pixels for fitting the lane line polynomial. Each successive box is recentered around the mean x position of the thresholded pixels previous box. The box has a width of `margin=70` pixels. This cloud of x,y points that are presumably associated with the lane line is used with polyfit to find a best fit 2nd order polynomial to all these points. Once a polynomial is identified, subsequent frames use the polynomial from the previous detection to determine a window of `margin=70` pixels to select pixels for polynomial fitting for updating the lane lines. #### 5. Describe how (and identify where in your code) you calculated the radius of curvature of the lane and the position of the vehicle with respect to center. I did this in lines 399 through 417 in my code in `laneutils.py`. Using the formula provided in the lectures, the 2nd order polynomial coefficients determine the radius of curvature, using appropriate scalings between pixels to real world distance. The position of the lane lines relative to the video frame is computed by taking the bottom pixels of the left and right lane polynomial expansions, finding the midpoint, and subtracting from the middle of the frame. This is converted from pixels to meters using the same scale factors for curvature calculation. ![alt text][lanefit] #### 6. Provide an example image of your result plotted back down onto the road such that the lane area is identified clearly. I implemented this step in lines 365 through 382 in my code in `yet_another_file.py` in the function `map_lane()`. This takes the plotted lane lines, fills a polygon region, and warps it back to the lane perspective. I also annotated the image with radius of curvature and distance from center using cv2.putText. Here is an example of my result on a test image: ![alt text][annotated] --- ### Pipeline (video) #### 1. Provide a link to your final video output. Your pipeline should perform reasonably well on the entire project video (wobbly lines are ok but no catastrophic failures that would cause the car to drive off the road!). Here's the video on the segment of I-280 [![link to my video result](http://img.youtube.com/vi/5opxTJfPwwo/0.jpg)](https://youtu.be/5opxTJfPwwo) --- ### Discussion #### 1. Briefly discuss any problems / issues you faced in your implementation of this project. Where will your pipeline likely fail? What could you do to make it more robust? I followed the approach given in the lecture. 1. Undistort the image 2. Convert to HLS and grayscale, find appropriate thresholds to identify lanes on the channels 3. Transform the perspective to find a radius of curvature and identify distances I then smooth the detection results by 5 frames, and have sanity checks to make sure the updates do not diverge too much from the averages. It is difficult to find a robust set of thresholds given the variation of road surfaces. Color appearance can also be affected by lighting, such as night driving. A further improvement would be to spend more time on tuning the thresholds and make it adaptive to different road conditions. Another problem I notice is that when the vehicle goes over a bump, the suspension of the vehicle changes pitch or the camera mount wobbles. This skews the transformation and makes the assumptions for the perspective transformation incorrect. Also, going up or down a hill also violates the assumptions. The horizon is no longer where it is expected to be. To make this more robust, there needs to be 1. image stabilization 2. horizon detection 3. vehicle slope detection 4. automatic identification of features that can be used to transform the perspective, e.g. straight lane line detection, or something more sophisticated.
Java
UTF-8
7,064
2.671875
3
[]
no_license
import java.awt.Color; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ //package javaapplication1; /** * * @author User */ public class CustomGameFrame extends javax.swing.JFrame { /** * Creates new form CustomGameFrame */ public CustomGameFrame() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { //creating buttons/labels PlaceSudokuBoardHere = new javax.swing.JLabel(); backButton1 = new javax.swing.JButton(); CustomGameFrameTitle = new javax.swing.JLabel(); toNewGame = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); PlaceSudokuBoardHere.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N PlaceSudokuBoardHere.setText("SudokuBoardHere"); backButton1.setText("Back to Menu"); backButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { backButton1ActionPerformed(evt); } }); //set title CustomGameFrameTitle.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N CustomGameFrameTitle.setText("Create a Custom Game"); toNewGame.setText("Play this Board!"); toNewGame.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { toNewGameActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(backButton1) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGap(119, 119, 119) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(CustomGameFrameTitle, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(toNewGame, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap(139, Short.MAX_VALUE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(75, 75, 75) .addComponent(SudokuBoard.getInstance().getPanel(), javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(75, Short.MAX_VALUE))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(backButton1) .addGap(18, 18, 18) .addComponent(CustomGameFrameTitle) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 267, Short.MAX_VALUE) .addComponent(toNewGame) .addGap(52, 52, 52)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(75, 75, 75) .addComponent(SudokuBoard.getInstance().getPanel(), javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(75, Short.MAX_VALUE))) ); this.getContentPane().setBackground(Color.cyan); //set background colour pack(); }// </editor-fold> //backbutton action private void backButton1ActionPerformed(java.awt.event.ActionEvent evt) { this.setVisible(false); new MainFrameUI().setVisible(true); //Board.getInstance().clearBoard(); } //new game action private void toNewGameActionPerformed(java.awt.event.ActionEvent evt) { this.setVisible(false); new GameFrame().setVisible(true); SudokuBoard.getInstance().playCustomBoard(); //Board.getInstance().lockTheGrid(); } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(CustomGameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(CustomGameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(CustomGameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(CustomGameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new CustomGameFrame().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JLabel CustomGameFrameTitle; private javax.swing.JLabel PlaceSudokuBoardHere; private javax.swing.JButton backButton1; private javax.swing.JButton toNewGame; // End of variables declaration }
C#
UTF-8
1,345
2.734375
3
[]
no_license
using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using SchoolApi.Interfaces; using SchoolApi.Models; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; namespace SchoolApi.Controllers { [ApiController] [Route("api/[controller]")] public class TemperatureController : ControllerBase, IFetchDataByRoomNumber<HumidityTempSensor> { public TemperatureController(DbContext context) { Context = context; } private DbContext context; public DbContext Context { get { return context; } set { context = value; } } [HttpGet] public List<HumidityTempSensor> GetData(string roomNumber) { try { List<HumidityTempSensor> tempSensors = ((SchoolContext)Context).DataEntry .Where(x => x.RoomNumber.ToLower() == roomNumber.ToLower()) .Select(x => x.HumidityTempSensor).ToList(); return tempSensors; } catch (InvalidCastException) { //Log error return null; } } } }
C#
UTF-8
2,256
2.75
3
[]
no_license
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class ScoreController : MonoBehaviour { [Header("Score Attributes")] public List<ScoreInfo> highScores; [Space(10)] public float currentScore = 0f; public void ManageScore(float currentDepth, int rootCount) { float frameScore = ReturnCalculatedScore(currentDepth, rootCount); currentScore += frameScore; } public void RegisterScore() { CheckNewScore(currentScore); currentScore = 0f; } public void CheckNewScore(float newScore) { float convertedScore = Mathf.Abs(newScore); if (CheckIfNewHighScore(convertedScore)) { AddNewHighScore(convertedScore); } } private void AddNewHighScore(float newScore) { highScores.Add(new ScoreInfo(newScore)); } public float ReturnCalculatedScore(float currentDepth, int rootCount) { float convertedDepth = Mathf.Abs(currentDepth); return (currentDepth * rootCount) / 100; } public float ReturnScore() { return currentScore; } public float ReturnHighScore() { float highestScore = 0f; for (int i = 0; i < highScores.Count; i++) { if (highestScore < highScores[i].score) { highestScore = highScores[i].score; } } return highestScore; } private bool CheckIfNewHighScore(float newScore) { if (highScores.Count == 0) { return true; } for (int i = 0; i < highScores.Count; i++) { if (newScore > highScores[i].score) { return true; } } return false; } } [System.Serializable] public struct ScoreInfo { [Header("Score Info Attributes")] public float score; [Space(10)] public DateTime scoreTime; public ScoreInfo(float newScore) { this.score = newScore; this.scoreTime = DateTime.Now; } }
Java
UTF-8
1,745
2.296875
2
[]
no_license
package com.neusoft.book.entity; import java.util.Date; public class LenBook { // String sql="insert into lenbook(bid,mid,credate,retday,retstatus,creditno) values(?,?,?,?,?,?)"; private Integer leid; private Books books;//图书 private Member member;//用户 private Date credate;//借书起始时间 private Date retdate;//归还图书时间 private int retday;//借书天数 private int creditno;//不守信誉次数 private String remarks;//备注 public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } public int getCreditno() { return creditno; } public void setCreditno(int creditno) { this.creditno = creditno; } private String retstatus; public String getRetstatus() { return retstatus; } public void setRetstatus(String retstatus) { this.retstatus = retstatus; } public int getRetday() { return retday; } public void setRetday(int retday) { this.retday = retday; } @Override public String toString() { return "LenBook [leid=" + leid + ", books=" + books + ", member=" + member + ", credate=" + credate + ", retdate=" + retdate + ", retday=" + retday + ", retstatus=" + retstatus + "]"; } public Integer getLeid() { return leid; } public void setLeid(Integer leid) { this.leid = leid; } public Books getBooks() { return books; } public void setBooks(Books books) { this.books = books; } public Member getMember() { return member; } public void setMember(Member member) { this.member = member; } public Date getCredate() { return credate; } public void setCredate(Date credate) { this.credate = credate; } public Date getRetdate() { return retdate; } public void setRetdate(Date retdate) { this.retdate = retdate; } }
Java
UTF-8
591
2.171875
2
[]
no_license
package com.AssiaTanji; public class Livre { String titre,auteur,categorie; int idLivre; public String getTitre() { return titre; } public void setTitre(String titre) { this.titre = titre; } public String getAuteur() { return auteur; } public void setAuteur(String auteur) { this.auteur = auteur; } public String getCategorie() { return categorie; } public void setCategorie(String categorie) { this.categorie = categorie; } public int getIdLivre() { return idLivre; } public void setIdLivre(int idLivre) { this.idLivre = idLivre; } }
Java
UTF-8
492
1.96875
2
[]
no_license
package br.com.loja.util; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.inject.Named; import br.com.loja.controller.LoginController; import br.com.loja.entity.Cliente; @Named(value = "verificaLogado") @RequestScoped public class VerificaLogado { @Inject private LoginController loginController; public boolean estaLogado() { Cliente c = loginController.GetClienteSession(); if (c != null) { return true; } return false; } }
Markdown
UTF-8
10,268
2.90625
3
[]
no_license
ruby on rails 6.0 默认使用 Webpacker。 作为js打包的工具,webpack已经成为了现代js应用打包的事实标准。 Webpacker makes it easy to use the JavaScript pre-processor and bundler webpack 4.x.x+ to manage application-like JavaScript in Rails. It coexists with the asset pipeline, as the primary purpose for webpack is app-like JavaScript, not images, CSS, or even JavaScript Sprinkles (that all continues to live in app/assets). However, it is possible to use Webpacker for CSS, images and fonts assets as well, in which case you may not even need the asset pipeline. This is mostly relevant when exclusively using component-based JavaScript frameworks. Webpacker使它很容易用于JavaScript预处理和打包, webpack 4.x在Rails中处理重交互的JavaScript应用程序。它与asset pipeline共存,因为 webpack的主要目的是用于打包重交互的JavaScript应用程序,而不是图像、CSS,甚至页面JavaScript片段(它们都继续存在于app/asset路径中)。 但是,也可以将Webpacker用于CSS、图像和字体等静态资源,在这种情况下,您可能不需要 asset pipeline。这种情形在只使用基于组件的JavaScript框架时是有意义的。 如果基于组件化无论是多页还是单页的富应用重交互,只使用webpack是正确的。 但是如果是多页偏展示型网站如果想使用jquery(不使用GatsbyJS等基于组件框架的静态CMS生成框架),又想利用现代的ES语法,各种前端工具。 基本的分工就是gulp等同于asset pipeline,用于静态资源 images、CSS、字体的处理,而webpack用于JavaScript依赖打包。 这时候我们的构建系统需要实现的功能是 资源定位、文件指纹、源码预处理、压缩资源、CssSprite图片合并、CDN host替换、打包dist、非覆盖发布、开发环境文件监 听、浏览器自动刷新等。 这些需求在现代的开源工具下,都有完善实现的功能。现在开始,你需要做的就是配置他们。 1. 资源定位 截止到今天(2020年)前端标准很多都已经确定。 之前存在的很多模块化标准, CMD、AMD在浏览器环境都已经不再使用,目前使用es的模块语法是最佳实践。 webpack的思想是一切都可以分析依赖并进行打包,JavaScript优先,而样式表、字体、图片、图标等资源都需要手动引入,确定依赖才能被应用程序引用。这 样的处理-即只使用webpack处理一切资源,对于单页应用合适的,但是如果用于这篇文章目的(一个多页偏展示型网站的构建系统)来说,启动多个 HtmlWebpackPlugin,并通过链接跳转实现调试功能,就可能会造成很多页面处理时对内存占用过大,而且重交互不是当前的重点所以就显得得不偿失。 > 多页偏展示型网站如果有重交互组件应该怎么办,gitlab的源码可以参考,通过引用vue实现组件的复用。 相较于webpack,gulp也是流行的构建工具之一,虽然它没办法感知依赖,分割代码,但是对于常见的构建操作gulp都能满足。 既然不用webpack,那gulp什么怎么处理HTML、样式表、字体、图片、图标等资源的定位打包问题呢? 在前后端分离的情形下,html一般都是打包后单独部署在服务器上的静态资源而不是通过后端模板返回生成的动态页面。 此时gulp处理html应该有的能力是,html引用,资源引用。 常见的资源依赖有 HTML引用css js 图片,css中引用字体 背景图片。 常用gulp工具 gulp-inject、gulp-html-replace 指明 html 目标可以将声明的css、js地址标签替换掉html指定的标记代码,实现js、css的引入。 gulp-useref 在html明确引入js、css地址标签,在想要合并的开始和结束位置加入特定标记,插件就会找到地址中对应的js、css合并目标位置中的文件, 同时更新html中的标签地址。 gulp-rev 给所有经过这个插件的js、css通过hash计算更改文件名,并同时返回一个json文件mainfist,描述改名前后文件的对应关系。 gulp-rev-replace Rev重命名后替换html中源文件的名字。 gulp-htmlmin 压缩html中能够压缩的字符。 gulp-autoprefixer 自动添加厂商前缀 gulp-preprocess 通过配置对文件js html css 中的标记(标记可以比较可以进行简单的判断 引入 输出) 进行预处理 参考gitlab,打包过后的js放在 assets/webpack/,文件名为emoji.de2dcb00f0bc66cae573.chunk.js,由文件夹+.+文件名字 + 十四位hash 分割+chunk,源文件+bundle + .js。 很多gulp插件处理一个页面都是在示例代码中解释的比较清楚的,但是如果要延展到整个项目,就要定下代码文件放置的位置。约定大于配置,各种文件的位置都要 放在指定位置,如果想自定义,需要在特定位置配置文件中指明,这样gulp才能正确处理依赖。 所有不通过_开头的html都视为html页面,被gulp处理,所有_开头的都默认为引用模块忽略处理。Html中不明确指明css地址、js地址,相关地址通过html放置 猜测注入,之后通过mainfist文件替换为处理后的hash地址。 通过lodash模板配装成 html,随后根据当前html的路径找到对应放置的js,一个页面只有一个entry point。webpack对js进行处理,gulp根据页面路径猜测 插入js标签。 html 根据 ref 标记,合并 html 中的文件,然后通过 rev 压缩 html 中引用的css、img,之后通过 rev-replace替换掉文件中受影响的引用标记。 一个页面的css构成一般是页面css、公用代码css,js构成一般是页面代码(app)、公用代码(common\utils\vendor\polyfill)、页面统计代码(百度统计, 谷歌分析),代码监控代码(sentry)等。 样式需要 sass 转 css 一下,js 通过 webpack 处理一下(ES6转ES5转换,公用代码合并,分割,压缩等)。 css,js都要在开发环境配置sourceMap,通过浏览器调试代码成为可能。 用于拼装页面的gulp-template,默认使用lodash中的_.template()方法。 基本语法为_.template([string=''], [options={}]) string为模板 模板语法类似ejs有三种 <%= %> 输出 <%- %> 转义输出 <% %> 嵌入js语句 配置项options有 ``` [escape] (RegExp): "escape" 分隔符. [evaluate=] (RegExp): "evaluate" 分隔符. [imports] (Object): 导入对象到模板中作为自由变量。 [interpolate] (RegExp): "interpolate" 分隔符。 [sourceURL] (string): 模板编译的来源URL。 [variable] (string): 数据对象的变量名。 ``` gulp-template 模板插件虽然有最多的下载,只有这些简单的语法,不支持include,所以使用gulp-ejs。 gitlab打包后的js为 /assets/webpack/webpack_runtime.bf993a5b9d06faed3c70.bundle.js /assets/webpack/common.db159cd75479db13c6a5.bundle.js /assets/webpack/main.b9fa1bb4b84fda196c23.bundle.js /assets/webpack/pages.dashboard.activity.ed4eca0603e5e1c0c0cd.bundle.js 这是通过webpack4的optimization.splitChunks配置项拆分出来的模块。 chunk的拆分依据是webpack生成的依赖图分析,gitlab的相关配置项为 ``` optimization: { runtimeChunk: 'single', // 单独拆分webpack运行时 splitChunks: { maxInitialRequests: 4, // 初始化时最大并发请求 4 cacheGroups: { default: false, // 不适用默认的拆分配置(common、vector) common: () => ({ priority: 20, // 优先级 20 优先级高的 相同依赖优先拆入此文件,如果优先级相同,谁在谁权重高 name: 'main', // 拆分出的chunk名称 chunks: 'initial',// chunk的性质 是 初始化时引入的 还是通过import()按需引入的 minChunks: autoEntriesCount * 0.9, // 超过多少entrypoint共同引用时才要拆进此文件 }), vendors: { priority: 10, // 优先级 chunks: 'async', // chunk的性质 test: /[\\/](node_modules|vendor[\\/]assets[\\/]javascripts)[\\/]/, // 所有符合正则的路径下的依赖 }, commons: { chunks: 'all', // chunk的性质 minChunks: 2, // 超过多少entrypoint共同引用时才要拆进此文件 reuseExistingChunk: true, // 重用之前的chunk }, }, }, }, ``` 相对路径支持: 一般出现相对路径的情形为 ejs中相对路径 scss中相对路径,如果支持就不太好处理。 所以可以用一种简易的绝对路径来支持,比如默认替换一些引用路径。 public 为 /app/public 的缩写 stylessheet 为 /app/stylessheets的缩写 fonts icons 同理。 本地开发路径与打包结果对应关系为 ejs 转成 html 直接移动到 dist scss 转成 css 放到 asset/css 下,原stylesheets下的文件夹结构转化为 文件夹.文件名结构。 fonts icons images 同理。 在资源放到dist前一步,通过正则匹配 gulp-replace插件替换约定的标记值。之后再通过rev加版本。 错误处理分为两种情形: 1. 纯前端处理 html如果与静态文件一样同样使用nginx部署,就要配置ngnix配置文件指明404 422 500 502 503 等页面,同时调整html与静态资源不同的缓存策略。如果 部署在第三方托管网站上,则需要专门的适配第三方网站的规则。 2. 后端参与路由 这时候需要写错误处理的转发逻辑以及一些路由规则。 ------------ 1.使用Webpack打包时的“多页”实践[https://alisec-ued.github.io/2016/12/13/%E4%BD%BF%E7%94%A8Webpack%E6%89%93%E5%8C%85%E6% 97%B6%E7%9A%84%E2%80%9C%E5%A4%9A%E9%A1%B5%E2%80%9D%E5%AE%9E%E8%B7%B5/] 2.html-webpack-plugin[https://webpack.js.org/plugins/html-webpack-plugin/] 3.Rails Rails with Webpacker [https://ruby-china.org/topics/38949 , https://ruby-china.org/topics/38832 , https:// ruby-china.org/topics/38214 , https://ruby-china.org/topics/39025 , https://www.kutu66.com//GitHub/article_148193] 4.[https://www.npmjs.com/package/gulp-inject , ]
Python
UTF-8
934
3.140625
3
[]
no_license
import re import os import fnmatch def gen_file_list(base_path): for base, unused, filelist in os.walk(base_path): for name in filelist: yield os.path.join(base, name) def files_matching_regex(base_path, regex, ignore_case=False): try: if ignore_case: pat = re.compile(regex, re.IGNORECASE) else: pat = re.compile(regex) except re.error: raise StopIteration else: for filename in gen_file_list(base_path): if pat.search(filename) is not None: yield filename def files_matching_glob(base_path, glob): for filename in gen_file_list(base_path): if fnmatch.fnmatch(filename, glob): yield filename if __name__ == '__main__': print 'Unfiltered:' print '\n'.join([item for item in gen_file_list('/bin')]) print 'Filtered Regex' print '\n'.join([item for item in files_matching_regex('/bin', '/ch.+')]) print 'Filtered Glob' print '\n'.join([item for item in files_matching_glob('/bin', '*ch*')])
Markdown
UTF-8
1,891
2.5625
3
[]
no_license
# BA Node.js [![Slack Status](http://meetupjs.herokuapp.com/badge.svg)](http://meetupjs.herokuapp.com) ## Qué es y por qué BA Node.js intenta impulsar la comunidad Node.js en Buenos Aires. La idea nació en charlas entre miembros de la comunidad y por la necesidad de un enfoque descentralizado, dónde todos pueden participar. BA Node.js dispone de los recursos para que la propia comunidad genere contenido, lugares dónde hacer preguntas, recursos para quiénes quieran dar charlas y mucho más. Podés unirte tambien a nuestro [grupo en Meetup][1]. > Si le pedís a la comunidad que lo construya, se unirán. Mikeal Rogers ## BA Node.js es una comunidad OPEN Open Source. ¿Qué significa? Aquellas personas que realicen contribuciones significativas serán agregados cómo owners de la organización. Mirá [CONTRIBUTING.md][2] para más detalles. ## Este espacio es tuyo! Si te interesa ser miembro, abrí un [issue][9] con el título "Miembro" y uno de los organizadores te va a agregar al equipo. Todas las personas que soliciten ser miembros tendrán permisos de commit en este repositorio. [¡Unite al grupo de Slack!](http://meetupjs.herokuapp.com/) ## Otras comunidades en Buenos Aires - [BAFrontend][4] - [Meetup.js][5] - [MongoDB Argentina][6] - [Internet of Things Buenos Aires][7] - [Hack/HackersBA][8] - [Beer.js Buenos Aires][10] ## Código de Conducta Encontralo [acá][3]. [1]: http://www.meetup.com/BANode-Meetup/ [2]: https://github.com/banodejs/miembros/blob/master/CONTRIBUTING.md [3]: https://github.com/banodejs/miembros/blob/master/CONDUCT.md [4]: http://www.meetup.com/BAFrontend/ [5]: http://www.meetup.com/Meetup-js/ [6]: http://www.meetup.com/MongoDB-Argentina/ [7]: http://www.meetup.com/IoT-Buenos-Aires/ [8]: http://www.meetup.com/HacksHackersBA/ [9]: https://github.com/banodejs/miembros/issues/new [10]: http://www.meetup.com/Beer-js-Buenos-Aires
Markdown
UTF-8
2,925
2.984375
3
[ "BSD-2-Clause" ]
permissive
# browse.php Payload *[browse.php - Remote payload](https://github.com/bytecode-77/browse.php-payload), single file directory browser & downloader <https://bytecode77.com/hacking/payloads/browse>* **browse.php** is a PHP single-file script providing an HTML based directory browser. Once arbitrary write access is granted to a directory, deploying this file will yield comprehensive insights in the directory structure of the server. The script allows to... * ... browse the file system with the privileges of the executing user * ... download files using PHP's `readfile()` * ... dictionary traversal, i.e. attempting paths, like `"..\..\..\"` *(if possible)* ## Demonstration Let's have a look at some comprehensive screenshots. For demonstration purposes, I deployed this script on my own server, which I obviously *have* write access to. While taking the screenshots, I have picked a non-guessible name in order to avoid "accidents" in the time beeing. After I was finished, I deleted the file - **don't forget this if you test the script!** ### 1. Starting the script You have done 99% of the work by acquiring write access remotely. Congratulations, you are a genious! ;) Now, browse.php will list the current directory. From there, navigation is a simple & UI based task. ![](https://bytecode77.com/images/sites/hacking/payloads/browse/001.png) ### 2. View & download files You can view or download any file. Especially PHP files - and we all know which ones are particularly interesting. This is a lot more convenient than the `readfile("[...]\config.php")` code is that usually deployed in multiple trial and error attempts until the correct path is hit. ![](https://bytecode77.com/images/sites/hacking/payloads/browse/002.png) Any file you care about is accessible and can be downloaded. Note, that this is a simple and therefore deployable & compatible script, not a feature complete "remote cloud solution payload". ![](https://bytecode77.com/images/sites/hacking/payloads/browse/003.png) Directory traversal attacks, like `"..\..\..\..\file.txt"` are possible, as we can specify any path to the script. Here, I have deliberately weakened the server configuration to demonstrate how a user that is not jailed could cause you harm. Please note, that I'm using **my own** server for this demonstration. I really hope I didn't forget to delete the file afterwards... ![](https://bytecode77.com/images/sites/hacking/payloads/browse/004.png) ## Use cases I have actually developed this while testing suphp, Apache MPM and similar, not in an actual pentest. This helped me to debug through the web server implementation. However, the main purpose primarily suits pentesting. ## Project Page [![](https://bytecode77.com/images/shared/favicon16.png) bytecode77.com/hacking/payloads/browse](https://bytecode77.com/hacking/payloads/browse)
Python
UTF-8
1,626
4.21875
4
[]
no_license
""" Classe Retangulo: Crie uma classe que modele um retangulo: Atributos: LadoA, LadoB (ou Comprimento e Largura, ou Base e Altura, a escolher) Métodos: Mudar valor dos lados, Retornar valor dos lados, calcular Área e calcular Perímetro; Crie um programa que utilize esta classe. Ele deve pedir ao usuário que informe as medidades de um local. Depois, deve criar um objeto com as medidas e calcular a quantidade de pisos e de rodapés necessárias para o local. """ class Retangulo: def __init__(self,LadoA = 0, LadoB=0, lag = 0 , h = 0): self.base = LadoA self.altura = LadoB self.largura = lag self.h = h def mudarValoresLados(self): p = input('quer mudar o valor de algum lado[s/n]? ').upper().strip() if p == 'S': novo_ladoA= float(input('novo valor para lado A: ')) self.base = novo_ladoA novo_ladoB = float(input('novo valor para Lado B: ')) self.altura = novo_ladoB def mostrarValorLados(self): print(f'novo valor para cumprimento{self.base}') print(f'novo valor para altura {self.altura}') def calcularPerimentro(self): per = 2*(self.base) + 2*(self.altura) return per def calcularArea(self): A = self.base * self.altura return A def calcularAreaLocal(self): self.Al = self.largura*self.h return self.Al #def calculoPiso(self): #calc = self.Al/ if __name__ == '__main__': r = Retangulo(3,4) print(r.mudarValoresLados()) print(r.mostrarValorLados()) print(r.calcularArea()) print(r.calcularPerimentro())
Python
UTF-8
260
4
4
[]
no_license
a = int(input("Enter the first number: ")) b = int(input("Enter the second number: ")) d = input("Enter an action: + , - , * , / ") if d == "+": print(a + b) elif d == "-": print(a - b) elif d == "*": print(a * b) elif d == "/": print(a / b)
C
UTF-8
1,191
3.53125
4
[]
no_license
#include<stdio.h> #include<stdlib.h> typedef int datatype; void Swap(datatype array[],int x,int y){ int t=array[x]; array[x]=array[y]; array[y]=t; } int Partition_3(datatype array[],int left,int right){// xiabiao int d=left; for(int i=left;i<right;++i){ if(array[i]<=array[right]){ Swap(array,i,d); d++; } } } int Partition_2(datatype array[],int left,int right){// wakeng fa int begin=left; int end=right; int pivot=array[right]; while(begin<end){ while(begin<end&&array[begin]<=pivot){ begin++; } array[end]= array[begin]; while(begin<end&&array[end]>=pivot){ end--; } array[begin]=array[end]; } array[begin]=pivot; return begin; } int Partition_1(datatype array[],int left,int right){//hoare fa int begin=left; int end=right; int pivit=array[right]; while(begin<end){ while(begin<end&&array[begin]<=pivot){ begin++; } while(begin<end&&array[end]>=pivot){ end--; } Swap(array,begin,right); } Swap(array,begin,right); return begin; } void QuickSort(datatype array[],int left,int right){ if(left==right||left>right){ return ; } int d=Partition(array[],left,right); QuickSort(array,left,d-1); QuickSort(array,d+1,right); }
PHP
UTF-8
637
2.65625
3
[]
no_license
<?php if (isset($_POST["name"]) && isset($_POST["description"]) && isset($_POST["price"])) { echo $_POST["name"].$_POST["description"].$_POST["price"]; } require_once "inc/dbconn.inc.php"; $sql = "INSERT INTO Product(name, description, price) VALUES(?, ?, ?);"; $statement = mysqli_stmt_init($conn); mysqli_stmt_prepare($statement, $sql); mysqli_stmt_bind_param($statement, 'ssd', htmlspecialchars($_POST["name"]), htmlspecialchars($_POST["description"]), $_POST["price"]); if (mysqli_stmt_execute($statement)==true) { header("Location: index.php"); exit(); } else { mysqli_error($conn); } mysqli_close($conn); ?>
C++
GB18030
2,535
2.859375
3
[]
no_license
// ʹgrabCutкĤָ // ܽлָЧһ㣬ߡëδȥԲıԵ⻬ // ֶλ #include <iostream> #include <opencv2\core.hpp> #include <opencv2\imgproc.hpp> #include <opencv2\highgui.hpp> using namespace std; int main() { cv::Mat image = cv::imread("S6000S00.jpg"); if (!image.data)return 0; cv::namedWindow("Original Image"); cv::imshow("Original Image", image); cv::Rect rectangle1(image.cols / 2 - 200, image.rows / 2 - 200, 400, 400); cv::Rect rectangle2(image.cols / 2 - 85, image.rows / 2 - 85, 170, 170); cv::Mat bgModel1, fgModel1; cv::Mat bgModel2, fgModel2; cv::Mat result1; cv::Mat result2; // ---------- grabCutָԲ ---------- cv::grabCut(image, // ͼ result1, // ָ rectangle1, // ǰľ bgModel1, fgModel1, // ģ 1, // cv::GC_INIT_WITH_RECT); // ʹþ // ------------------------------------- // ---------- grabCutָԲ ---------- cv::grabCut(image, // ͼ result2, // ָ rectangle2, // ǰľ bgModel2, fgModel2, // ģ 1, // cv::GC_INIT_WITH_RECT); // ʹþ // ------------------------------------- cv::rectangle(image, rectangle1, cv::Scalar(255, 255, 255), 1); cv::namedWindow("Image With Rectangle"); cv::imshow("Image With Rectangle", image); // cv::GC_BGD ȷڱ // cv::GC_FGD ȷǰ // cv::GC_PR_BGD ڱ // cv::GC_PR_FGD ǰ // Բ cv::compare(result1, cv::GC_PR_FGD, result1, cv::CMP_EQ); cv::Mat object1(image.size(), CV_8UC3, cv::Scalar(255, 255, 255)); image.copyTo(object1, result1); cv::namedWindow("Object1"); cv::imshow("Object1", object1); // Բ cv::compare(result2, cv::GC_PR_FGD, result2, cv::CMP_EQ); cv::Mat object2(image.size(), CV_8UC3, cv::Scalar(255, 255, 255)); image.copyTo(object2, result2); cv::namedWindow("Object2"); cv::imshow("Object2", object2); // ĤԲּȥԲ cv::Mat dst = result1 - result2; cv::Mat object3(image.size(), CV_8UC3, cv::Scalar(255, 255, 255)); // һɫͼ image.copyTo(object3, dst); // Ʊ cv::namedWindow("Result"); cv::imshow("Result", object3); cv::waitKey(); return 0; }
Python
UTF-8
1,643
3.65625
4
[]
no_license
treeDraw = """ 1 / \\ 2 3 / \\ / \\ 4 56 7 / \\ 8 9 """ print(treeDraw) tree = [ (1, None), (2, 1), (3, 1), (4, 2), (5, 2), (6, 3), (7, 3), (8, 4), (9, 4), ] # de cualquier nodo a cualquier nodo mostrando el camino. def treesteps(init, end=1): node_lst = [] for ch, par in tree: if ch == init: if par is None: return ['root'] node_lst.append(par) for node in treesteps(par): node_lst.append(node) return node_lst # de cualquier nodo a cualquier nodo en cantidad def treedistance(init, end=1): for ch, par in tree: if ch == init: if par is None: return 0 return treedistance(par) + 1 # de cualquier nodo a cualquier nodo en cantidad def nodeToNode(init, end=1, avoid=int): # estudio si el punto actual esta al lado de la respuesta if init == end: return 0 for child, parent in tree: if parent == init and child == end: return 1 for child, parent in tree: if child == init and parent == end: return 1 # defino mis proximos puntos a analizar nextGoals = [] fobridden = [avoid, None] for child, parent in tree: if parent == init and child not in fobridden: nextGoals.append(child) elif child == init and parent not in fobridden: nextGoals.append(parent) # analizo estos puntos for node in nextGoals: return nodeToNode(node, end, init) + 1 print(nodeToNode(9, 8))
Markdown
UTF-8
2,369
2.5625
3
[ "MIT" ]
permissive
# Desenvolvimento local ## Configuração inicial Tentamos facilitar o desenvolvimento de novas funcionalidades por membros da comunidade, e todas as contribuições são bem-vindas. Para começar, é necessário um ambiente de desenvolvimento Java atualizado, com: * [git][GIT] * [git-crypt][GITCRYPT] * [GPG][GPG] * [JDK 8][JDK8] * Sua IDE favorita (nós preferimos [IntelliJ IDEA 14 CE][IDEA14CE]) Para começar, clone o repositório: ``` cd ~/projetos # ou o diretório de sua preferência git clone "https://github.com/servicosgovbr/guia-de-servicos.git" ``` A seguir, gere o arquivo de projeto do [IntelliJ IDEA][IDEA14CE]: ``` ./gradlew clean idea ``` Abra o arquivo `guia-de-servicos.ipr` no IntelliJ IDEA e você está pronto para navegar pelo código. Caso você não tenha desenvolvido utilizando o [Lombok] antes, a IDE marcará diversos arquivos com problemas de compilação. Será necessário instalar o plugin para que as coisas funcionem normalmente. Este plugin precisa ser manualmente instalado. Para o IntelliJ IDEA, procure nos repositórios de plugins pelo [Lombok IntelliJ Plugin][PLUGIN]. [Lombok]:http://projectlombok.org/ [GIT]:http://git-scm.org [GITCRYPT]:https://www.agwa.name/projects/git-crypt/ [GPG]:https://www.gnupg.org/ [JDK8]:http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html [IDEA14CE]:https://www.jetbrains.com/idea/download/ [VAGRANT]:http://vagrantup.com [PLUGIN]:https://github.com/mplushnikov/lombok-intellij-plugin [TOMCAT]:http://tomcat.apache.org/ [SPRINGBOOT]:http://projects.spring.io/spring-boot/ ## Execução da aplicação Para rodar a aplicação localmente, utilizamos um servidor web [Tomcat][TOMCAT], embutido pelo [Spring-Boot][SPRINGBOOT]: ``` ./gradlew bootRun ``` Após alguns segundos, o servidor estará disponível em [localhost:8080](http://localhost:8080/). Arquivos estáticos (html, js, css) alterados estarão disponíveis alguns segundos após alterações. ## ElasticSearch externo Para utilizar um servidor [ElasticSearch](./elasticsearch.md) configurado em `localhost:9300`, basta configurar a variável `SPRING_DATA_ELASTICSEARCH_CLUSTERNODES`: ``` SPRING_DATA_ELASTICSEARCH_CLUSTERNODES=127.0.0.1:9300 ./gradlew run ``` Para a inicialização funcionar desta forma, é necessário que o ElasticSearch já esteja executando antes de começar.
C++
UTF-8
550
2.65625
3
[]
no_license
#ifndef DUALQUATERNION_H #define DUALQUATERNION_H #include "glm::quaternion.h" class Dualglm::quat { Dualglm::quat(glm::quat q, glm::vec3 v) { ord = q; glm::vec3 quatvect = q.getVector(); dual.setA(quatvect.scaleProduct(v)*-0.5f); glm::vec3 dualvector = glm::vec3(0.5f * (v.x * q.getA() + v.y * quatvect.z - v.z * quatvect.y), 0.5f * (-v.x * quatvect.z + v.y * q.getA() + v.z * quatvect.x), 0.5f * (v.x * quatvect.y - v.y * quatvect.y + v.z * q.getA())); } private: glm::quat ord; glm::quat dual; }; #endif
JavaScript
UTF-8
528
4.125
4
[]
no_license
"use strict" /* Utilizando un bucle, mostrar la suma y la media de los números ingresados hasta introducir un número negativo y ahí mostrar el resultado */ var suma = 0; var contador = 0; do{ var numero = parseInt(prompt("Introduce algún número", 0)); if(isNaN(numero)){ numero = 0; } else if(numero >= 0){ suma = suma + numero; contador++; } }while(numero >= 0) alert("La suma total es: " + suma); alert("El promedio de los números ingresados es: " + (suma / contador))
Python
UTF-8
120
3.046875
3
[]
no_license
from collections import Counter as co arr = [2, 2, 1] arr = co(arr) for i in arr: if arr[i] == 1: print(i)
Go
UTF-8
975
2.703125
3
[]
no_license
package cmd import ( "github.com/spf13/cobra" ) var rootCmd = &cobra.Command{ Use: "blackjack", Short: "Blackjack Game", Long: "Starts a Blackjack Game", } func init() { startGameCmd.Flags().IntP("decks", "d", 1, "Number of decks to initialize with") startGameCmd.Flags().IntP("jokers", "j", 0, "Number of Jokers deck will be initialized with") startGameCmd.Flags().IntP("players", "p", 1, "Number of players in this game excluding the dealer") startGameCmd.Flags().BoolP("shuffle", "s", false, "Specify if deck should be shuffled") // startGameCmd.Flags().BoolP("shuffle", "s", true, "Specify if deck should be shuffled") startGameCmd.Flags().StringSliceP("omit-suits", "o", []string{}, "List of suits (H,D,S,C) to be omitted from the deck") startGameCmd.Flags().StringSliceP("omit-ranks", "r", []string{}, "List of ranks (A,1,2...,J,Q,K) to be omitted from the deck") } func Execute() error { rootCmd.AddCommand(startGameCmd) return rootCmd.Execute() }
C#
UTF-8
324
3.21875
3
[]
no_license
public void Draw(RenderWindow window) { var index = Math.Max(0, points.Count - 8); var offset = Math.Min(points.Count, 8); points.RemoveRange(index, offset); foreach (Point point in points) { point.Draw(window); } }
Java
UTF-8
466
2.234375
2
[]
no_license
package com.pwc.us.common.exception; /** * This exception is thrown when a user who is already registered in Guidewire * attempts to register again. * @author Roger Turnau - <roger.turnau@us.pwc.com> */ public class GwUserAlreadyRegisteredException extends Exception { public GwUserAlreadyRegisteredException(String message) { super(message); } public GwUserAlreadyRegisteredException(String message, Exception e) { super(message, e); } }
Markdown
UTF-8
1,352
2.578125
3
[ "MIT" ]
permissive
# InvoiceMe Simple invoice program ## Stage 1 ### UI design - Login form (Done) - MainMenu from (Done) - Contact form (Done) - Invoice form (Done) - Overview form (Done) - Print form (Done) ### Scripting - Loging form functions with DB (Done) - Contact form to add contacts to DB (Done) - Contacts form to edit existing contacts (Done) - Invoice form to add invoice to DB (Done) - Invoice form to edit existing invoices (Done) - Overview form to show Invoice table (Done) - Overview form to show Contact table (Done) - Print form to output invoice to print (Done) ### Feedback - Fonts changes to more readable font (Done) ## Stage 2 ### UI design - revise UI design - sort TAB functions on all forms ### Scripting - Print form to print Inovices (Done) - Add feature: incase of empty LoginTable create new Account - Set up Params file for Company - Change way Invoice Creation is done : Important (string needs to be "'unit' 'Description' @ 'UnitCost' = 'TotalCost'") - Checking on deletion of client there are no invoices stored with ID : Important - Workout if Client needs LatePaid field updated ## Stage 3 ### Features - Add Admin Field to Login Table - Admins to have access to Creation of new Accounts - Client LatePaid checks , Last invoice check is late, Add amount to bill based on terms and conditions
C#
UTF-8
3,208
2.84375
3
[]
no_license
using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using ProductCatalog.Models; using ProductCatalog.Repositories; namespace ProductCatalog.Controllers { [Route("api/[controller]")] [ApiController] public class CategoryController : Controller { private readonly CategoryRepository _repository; public CategoryController(CategoryRepository repository) { _repository = repository; } [HttpGet("")] [ResponseCache(Duration = 3600)] public async Task<ActionResult<List<Category>>> Get() { var categories = await _repository.Get(); return Ok(categories); } [HttpGet("{id:int}")] public async Task<ActionResult<Category>> Get(int id) { var categories = await _repository.Get(id); return Ok(categories); } [HttpGet("{id:int}/products")] [ResponseCache(Duration = 30)] public async Task<ActionResult<List<Product>>> GetProducts(int id) { var categories = await _repository.GetProducts(id); return Ok(categories); } [HttpPost("")] public async Task<ActionResult<Category>> Post([FromBody] Category category) { if (!ModelState.IsValid) { return BadRequest(ModelState); } try { await _repository.Save(category); return Ok(category); } catch (Exception) { return BadRequest(new { message = "Não foi possível criar a categoria" }); } } [HttpPut("{id:int}")] public async Task<ActionResult<Category>> Put([FromBody] Category category, int id) { if (id != category.Id) return NotFound(new { message = "Categoria não encontrada" }); if (!ModelState.IsValid) return BadRequest(ModelState); try { await _repository.Update(category); return Ok(category); } catch (DbUpdateConcurrencyException) { return BadRequest(new { message = "Este registro já foi atualizado" }); } catch (Exception) { return BadRequest(new { message = "Não foi possível atualizar a categoria" }); } } [HttpDelete("{id:int}")] public async Task<ActionResult<Category>> Delete(int id) { var searchCategory = await _repository.Get(id); if (searchCategory == null) { return NotFound(new { message = "Categoria não encontrada" }); } try { await _repository.Exclude(searchCategory); return Ok(searchCategory); } catch (Exception) { return BadRequest(new { message = "Não foi possível remover a categoria" }); } } } }
C++
UTF-8
2,408
3.140625
3
[ "MIT" ]
permissive
#include <iostream> #include <vector> #include <utility> using namespace std; class Solution{ private: string roll(vector<vector<int>> &maze, int ballRow, int ballCol, const vector<int> & hole, int dr, int dc, int dist, const string&path, pair<string, int>&res){ if (dist < res.second){ if (dr != 0 || dc != 0){ while (ballRow + dr >= 0 && ballCol + dc >= 0 && ballRow + dr < maze.size() && ballCol + dc < maze[0].size() && maze[ballRow + dr][ballCol + dc] != 1){ ballRow += dr; ballCol += dc; ++dist; if (ballRow == hole[0] && ballCol == hole[1] && dist < res.second) res = {path, dist}; } } if (maze[ballRow][ballCol] == 0 || dist + 2 < maze[ballRow][ballCol]){ maze[ballRow][ballCol] = dist + 2; if (dr == 0) roll(maze, ballRow, ballCol, hole, 1, 0, dist, path + "d", res); if (dc == 0) roll(maze, ballRow, ballCol, hole, 0, -1, dist, path + "l", res); if (dc == 0) roll(maze, ballRow, ballCol, hole, 0, 1, dist, path + "r", res); if (dr == 0) roll(maze, ballRow, ballCol, hole, -1, 0, dist, path + "u", res); } } return res.first; } public: string findShortestWay(vector<vector<int>> &maze, vector<int> &ball, vector<int> &hole){ return roll(maze, ball[0], ball[1], hole, 0, 0, 0, "", pair<string, int>() = {"impossible", INT_MAX}); } }; int main(){ vector<vector<int>> maze1 = {{0, 0, 0, 0, 0}, {1, 1, 0, 0, 1}, {0, 0, 0, 0, 0}, {0, 1, 0, 0, 1}, {0, 1, 0, 0, 0}}; vector<int> ball1 = {4, 3}; vector<int> hole1 = {3, 0}; vector<vector<int>> maze2 = {{0, 0, 0, 0, 0}, {1, 1, 0, 0, 1}, {0, 0, 0, 0, 0}, {0, 1, 0, 0, 1}, {0, 1, 0, 0, 0}}; vector<int> ball2 = {4, 3}; vector<int> hole2 = {0, 1}; vector<vector<int>> maze3 = {{0}, {1}}; vector<int> ball3 = {0, 0}; vector<int> hole3 = {1, 0}; Solution sol; cout << sol.findShortestWay(maze2, ball2, hole2) << endl; cout << sol.findShortestWay(maze1, ball1, hole1) << endl; cout << sol.findShortestWay(maze3, ball3, hole3) << endl; return 0; }
Java
UTF-8
1,296
2.53125
3
[]
no_license
package com.example.locuslabs.recommendedimplementation; /** * This class is for testing Proguard rules, it has no functional use. It should get obfuscated by Proguard, as described in the case below. * * Scenario: Proguard rules should not prevent obfuscation of customer's code * Given the RecommendedImplementation app * And the developer ran ./gradlew clean build * When the developer opens the file ./app/build/outputs/mapping/release/mapping.txt * Then the line starting "com.example.locuslabs.recommendedimplementation.ProguardTestClass ->" should say this class was renamed, for example to "com.example.locuslabs.recommendedimplementation.a" * And the file should not say "com.example.locuslabs.recommendedimplementation.ProguardTestClass -> com.example.locuslabs.recommendedimplementation.ProguardTestClass" * * For more information see https://android.maps.locuslabs.com/v2.0/docs/frequently-asked-questions#section-what-exceptions-does-locusmaps-android-sdk-require-for-proguard- * * LocusLabs internal source: https://app.asana.com/0/16049761259391/812529377090330/f */ public class ProguardTestClass { private int avar; public ProguardTestClass(int avar) { this.avar = avar; } public int incrementValue() { return ++avar; } }
JavaScript
UTF-8
3,346
2.984375
3
[]
no_license
window.AudioContext = window.AudioContext || window.webkitAudioContext; const audioContext = new AudioContext(); const drawAudio = url => { fetch(url) .then(response => response.arrayBuffer()) .then(arrayBuffer => audioContext.decodeAudioData(arrayBuffer)) .then(audioBuffer => draw(normalizeData(filterData(audioBuffer)))); }; const filterData = audioBuffer => { const rawData = audioBuffer.getChannelData(0); const samples = 700; const blockSize = Math.floor(rawData.length / samples); const filteredData = []; for (let i = 0; i < samples; i++) { let blockStart = blockSize * i; let sum = 0; for (let j = 0; j < blockSize; j++) { sum = sum + Math.abs(rawData[blockStart + j]); } filteredData.push(sum / blockSize); } return filteredData; }; const normalizeData = filteredData => { const multiplier = Math.pow(Math.max(...filteredData), -1); return filteredData.map(n => n * multiplier); } const draw = normalizedData => { const canvas = document.querySelector("canvas"); const dpr = window.devicePixelRatio || 1; const padding = 20; canvas.width = canvas.offsetWidth * dpr; canvas.height = (canvas.offsetHeight + padding * 2) * dpr; const ctx = canvas.getContext("2d"); ctx.scale(dpr, dpr); ctx.translate(0, canvas.offsetHeight / 2 + padding); const width = canvas.offsetWidth / normalizedData.length; for (let i = 0; i < normalizedData.length; i++) { const x = width * i; let height = normalizedData[i] * canvas.offsetHeight - padding; if (height < 0) { height = 0; } else if (height > canvas.offsetHeight / 2) { height = height > canvas.offsetHeight / 2; } drawLineSegment(ctx, x, height, width, (i + 1) % 2); } }; const drawLineSegment = (ctx, x, height, width, isEven) => { ctx.lineWidth = 2; ctx.strokeStyle = "#565656"; ctx.beginPath(); height = isEven ? height : -height; ctx.moveTo(x, 0); ctx.lineTo(x, height); ctx.arc(x + width / 4, height, width / 4, Math.PI, 0, isEven); ctx.lineTo(x + width, 0); ctx.stroke(); }; drawAudio('audio-file.mp3'); var myMusic= document.getElementById("music"); var seeker = document.getElementById("progress-bar"); var covered = document.getElementById("progress-seek"); var seeking; var counter = 0; function init(elem) { if (elem.classList.contains("fa-play-circle")) { play(elem); } else { pause(elem); } } function canvasPlay() { let elem = document.getElementById("btn-play"); init(elem); } function play(btn) { btn.classList.remove("fa-play-circle"); btn.classList.add("fa-pause-circle"); myMusic.play(); seeking = setInterval(function() { counter = counter + 0.47; seeker.style.left = counter+"px"; covered.style.width = counter+"px"; covered.style.left = "-"+(counter+2)+"px"; }, 1); } function pause(btn) { btn.classList.remove("fa-pause-circle"); btn.classList.add("fa-play-circle"); myMusic.pause(); clearInterval(seeking); } myMusic.addEventListener('ended', function() { this.currentTime = 0; counter = 0; seeker.style.left = "0px"; covered.style.width = "0px"; covered.style.left = "0px"; clearInterval(seeking); let btn = document.getElementById("btn-play"); btn.classList.remove("fa-pause-circle"); btn.classList.add("fa-play-circle"); })
Python
UTF-8
619
2.546875
3
[]
no_license
__author__ = 'xwffirilat' import MainRegistry from command.registry import CommandRegistry from internal.exception import CommandException class Interpreter: def __init__(self, GUI): MainRegistry.setInterpreter(self) self.GUI = GUI def interpret(self, string: str): command, *args = string.split(' ') try: cmd = CommandRegistry[command] r = cmd(*args) if r is None: return '' else: return r except CommandException as e: self.GUI.console.add(e.args[0]) return ''
C++
UTF-8
1,997
3.59375
4
[]
no_license
// // Non-overlappingIntervals.cpp // LeetCode-main // // Created by jackma on 2022/3/9. // Copyright © 2022 JackMa. All rights reserved. // #include "Non-overlappingIntervals.hpp" /** Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping. Input: intervals = [[1,2],[2,3],[3,4],[1,3]] Output: 1 Explanation: [1,3] can be removed and the rest of the intervals are non-overlapping. Input: intervals = [[1,2],[1,2],[1,2]] Output: 2 Explanation: You need to remove two [1,2] to make the rest of the intervals non-overlapping. */ int Solution::eraseOverlapIntervals(vector<vector<int>> &intervals) { sort(intervals.begin(), intervals.end(), [](auto &a, auto &b){ return (a[0] == b[0]) ? (a[1] > b[1]) : (a[0] < b[0]); }); int result = 0; int start = -INT_MAX, end = -INT_MAX; for (auto interval : intervals) { // three situation if (interval[0] >= end) { // next interval‘begin is bigger than end // have not overlap start = interval[0]; end = interval[1]; } else if (interval[1] <= end) { // next interval'end is smaller than end result++; // choose the minimum interval start = interval[0]; end = interval[1]; } else { // have overlap between interval with [start, end] // such as: [1, 4] [2, 5], push the back interval result++; } } return (int)result; } void testEraseOverlapIntervals() { // {{-52,31},{-73,-26},{82,97},{-65,-11},{-62,-49},{95,99},{58,95},{-31,49},{66,98},{-63,2},{30,47},{-40,-26}} vector<vector<int>> intervals = {{-52,31},{-73,-26},{82,97},{-65,-11},{-62,-49},{95,99},{58,95},{-31,49},{66,98},{-63,2},{30,47},{-40,-26}}; cout << Solution().eraseOverlapIntervals(intervals) << endl; }
C++
UTF-8
1,086
2.75
3
[ "MIT" ]
permissive
/** * @file DescriptorsRecognizer.cpp * @author Люнгрин Андрей aka prostoichelovek <iam.prostoi.chelovek@gmail.ru> * @date 01 Aug 2020 * @copyright MIT License */ #include "DescriptorsRecognizer.h" namespace faces { bool DescriptorsRecognizer::save(std::string const &dst) { return classifier->save(dst); } bool DescriptorsRecognizer::_checkOk() { _ok = classifier->isOk() && descriptor->isOk(); return _ok; } int DescriptorsRecognizer::_recognize(cv::Mat const &img) { if (!_checkOk()) return -2; std::vector<double> descriptors = descriptor->computeDescriptors(img); return classifier->classifyDescriptors(descriptors); } void DescriptorsRecognizer::train(std::map<int, cv::Mat &> const &samples) { if (!descriptor->isOk()) return; std::map<int, std::vector<double>> descriptorSamples; for (auto const &sample : samples) { descriptorSamples[sample.first] = descriptor->computeDescriptors(sample.second); } classifier->train(descriptorSamples); _checkOk(); } }
PHP
UTF-8
3,393
2.859375
3
[ "MIT" ]
permissive
<?php namespace SGT\HTTP\Navigation; use SGT\Traits\Config; class ButtonDropdown { use Config; use AddItem; public $type = 'button_dropdown'; protected $alignment = 'right'; protected $color = null; // Can be left or right protected $items = []; protected $size = null; public static function create() { return new ButtonDropdown(); } public function addButton($label) { return $this->addItem($label); } public function addDivider() { $item = new Divider(); $this->items[] = $item; return $item; } public function addItem($label) { $item = new Menu($label); $this->items[] = $item; return $item; } public function alignment($alignment = 'left') { $this->alignment = $alignment == 'left' ? 'left' : 'right'; return $this; } public function color($color) { $this->color = $color; return $this; } public function display() { $view = view($this->configFrontEnd('navigation.button.dropdown')); $divider = null; $item_count = 0; $items = []; foreach ($this->items as $item) { if ($item->canDisplay() == false) { continue; } if ($item->type == 'divider') { if ($divider) { continue; } # we flag having a divider, but don't add it yet because we don't know if there's a next item $divider = $item; continue; } if ($divider && count($items) > 0) { $items[] = $divider; $divider = null; } if ($item_count == 0) { $button = $this->makeButton($item); if ($this->color != null) { $button->color($this->color); } if ($this->size != null) { $button->size($this->size); } } else { $items[] = $item; $item->addClass('dropdown-item'); } $item_count++; } if ($item_count > 0) { $view->dropdown = $this; $view->items = $items; $view->button = $button; return $view->__toString(); } return ''; } public function dropdownMenuClasses() { $classes["dropdown-menu"] = "dropdown-menu"; if ($this->alignment == 'right') { $classes["dropdown-menu-right"] = "dropdown-menu-right"; } return implode(' ', $classes); } public function size($size) { $this->size = $size; return $this; } protected function makeButton($item) { $button = new Button(); $button->label($item->getLabel()); $button->link($item->gethRef()); $attributes = $item->attributes(); foreach ($attributes as $key => $value) { $button->attribute($key, $value); } return $button; } }
Java
UTF-8
1,654
2.765625
3
[ "Apache-2.0" ]
permissive
package com.robbendev.common.base; /** * <p> * 通用响应结果 * </p> * * @param <T> */ public class BaseResult<T> { // 返回信息-失败 public static final String APP_DEFINE_ERR = "参数错误或者操作未成功"; // 返回信息-成功 public static final String APP_DEFINE_SUC = "操作成功"; public static final String CODE_SUCCESS = "0"; public static final String CODE_ERROR = "500"; //返回状态码 private String code; //返回信息 private String message; // 返回数据 private T data; public BaseResult() { this.code = "200"; this.message = APP_DEFINE_SUC; } public BaseResult(boolean success) { if (success) { this.message = APP_DEFINE_SUC; } else { this.message = APP_DEFINE_ERR; } } public BaseResult(String message) { this.message = message; } public BaseResult(String message, T data) { this.message = message; this.data = data; } public BaseResult(String code, String message, T data) { this.code = code; this.message = message; this.data = data; } public static <T> BaseResult<T> success() { return new BaseResult<>(CODE_SUCCESS, APP_DEFINE_SUC, null); } public static <T> BaseResult<T> success(T data) { return new BaseResult<>(CODE_SUCCESS, APP_DEFINE_SUC, data); } public String getMessage() { return message; } public BaseResult<T> setMessage(String message) { this.message = message; return this; } public T getData() { return data; } public BaseResult<T> setData(T data) { this.data = data; return this; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } }
C
UTF-8
343
4.1875
4
[]
no_license
#include <stdio.h> int isPrime(int); int main() { int number; printf("Enter a number: "); scanf("%d", &number); if (isPrime(number)) printf("\nEntered number is prime!"); else printf("\nEntered number is not prime!"); } int isPrime(int x) { for (int i = 2; i < x; i++) if (x % i == 0) return 0; return 1; }
C++
UTF-8
1,819
2.8125
3
[]
no_license
#ifndef _cAStar_HG_ #define _cAStar_HG_ #include <Scene\sPathNode.h> #include <OpenGL\OpenGLHeaders.h> #include <vector> #include <deque> #include <list> class cAStar { public: cAStar(); ~cAStar(); // Set start and goal nodes of the path void SetStartNode(sPathNode* node); void SetStartNode(const glm::vec3& position); void SetGoalNode(sPathNode* node); void SetGoalNode(std::string nodeName); // Generate a new node and link them sPathNode* CreateNode(std::string nodeName, glm::vec3 nodePosition, int nodeDifficulty, bool isStartNode = false); // Get a node at the index sPathNode* GetNodeAt(int index); unsigned int GetNumNodes(); // Find all neighbours and calculate scores void InitializeNodes(int rows, int columns, bool findNeighbours); // Make the path bool CalculatePath(); bool MakePath(std::vector<sPathNode*>& path); bool MakePath(std::deque<sPathNode*>& path); bool DrawPath(class cDrawSystem* pDrawSystem, GLuint shaderProgramID); bool RemakePath(const std::vector<sPathNode*>& cameFrom, sPathNode* fromNode); std::string goalName; private: enum eDirections { TOP = 0, RIGHT = 1, BOTTOM = 2, LEFT = 3, TOPRIGHT = 4, BOTTOMRIGHT = 5, BOTTOMLEFT = 6, TOPLEFT = 7, INVALID = -1 }; void _ResetNodes(); void _CalculateScore(sPathNode* node); void _FindAllNeighbours(unsigned int index); sPathNode* _GetClosestOpenNode(); bool _IsNodeClosed(sPathNode* node); bool _IsNodeOpen(sPathNode* node); sPathNode* startNode; sPathNode* goalNode; int numRows; int numColumns; std::vector<std::pair<float/*score*/, sPathNode*/*node*/>> _vecNodes; cDrawSystem* _pDrawSystem; // Sets std::list<sPathNode*> openSet; std::list<sPathNode*> closedSet; std::vector<sPathNode*> _vecPath; std::deque<sPathNode*> _deqPath; }; #endif // !_cAStar_HG_
TypeScript
UTF-8
815
2.734375
3
[ "MIT" ]
permissive
export default FunctionWordsInKeyphraseAssessment; /** * Assessment to check whether the keyphrase only contains function words. */ declare class FunctionWordsInKeyphraseAssessment extends Assessment { /** * Sets the identifier and the config. * * @param {Object} [config] The configuration to use. * @param {number} [config.scores.onlyFunctionWords] The score to return if the keyphrase contains only function words. * @param {string} [config.urlTitle] The URL to the relevant KB article. * @param {string} [config.urlCallToAction] The URL to the call-to-action article. * * @returns {void} */ constructor(config?: any); identifier: string; _config: any; _functionWordsInKeyphrase: any; _keyword: any; } import Assessment from "../../assessment";
Java
UTF-8
3,961
2.25
2
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2009-2011 Mathias Doenitz * * 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.parboiled.parserunners; import org.parboiled.MatchHandler; import org.parboiled.MatcherContext; import org.parboiled.Rule; import org.parboiled.buffers.InputBuffer; import org.parboiled.errors.InvalidInputError; import org.parboiled.matchervisitors.IsSingleCharMatcherVisitor; import org.parboiled.support.MatcherPath; import org.parboiled.support.ParsingResult; import java.util.ArrayList; import java.util.List; import static org.parboiled.common.Preconditions.checkArgNotNull; /** * A {@link org.parboiled.parserunners.ParseRunner} implementation that creates an * {@link org.parboiled.errors.InvalidInputError} for the error at a known error location. * It never causes the parser to perform more than one parsing run and is rarely used directly. * Instead its functionality is relied upon by the {@link ReportingParseRunner} and {@link RecoveringParseRunner} classes. */ public class ErrorReportingParseRunner<V> extends AbstractParseRunner<V> implements MatchHandler { private final IsSingleCharMatcherVisitor isSingleCharMatcherVisitor = new IsSingleCharMatcherVisitor(); private final int errorIndex; private final MatchHandler inner; private final List<MatcherPath> failedMatchers = new ArrayList<MatcherPath>(); private boolean seeking; /** * Creates a new ErrorReportingParseRunner instance for the given rule and the given errorIndex. * * @param rule the parser rule * @param errorIndex the index of the error to report */ public ErrorReportingParseRunner(Rule rule, int errorIndex) { this(rule, errorIndex, null); } /** * Creates a new ErrorReportingParseRunner instance for the given rule and the given errorIndex. * The given MatchHandler is used as a delegate for the actual match handling. * * @param rule the parser rule * @param errorIndex the index of the error to report * @param inner another MatchHandler to delegate the actual match handling to, can be null */ public ErrorReportingParseRunner(Rule rule, int errorIndex, MatchHandler inner) { super(rule); this.errorIndex = errorIndex; this.inner = inner; } public ParsingResult<V> run(InputBuffer inputBuffer) { checkArgNotNull(inputBuffer, "inputBuffer"); resetValueStack(); failedMatchers.clear(); seeking = errorIndex > 0; // run without fast string matching to properly get to the error location MatcherContext<V> rootContext = createRootContext(inputBuffer, this, false); boolean matched = match(rootContext); if (!matched) { getParseErrors().add(new InvalidInputError(inputBuffer, errorIndex, failedMatchers, null)); } return createParsingResult(matched, rootContext); } public boolean match(MatcherContext<?> context) { boolean matched = inner == null && context.getMatcher().match(context) || inner != null && inner.match(context); if (context.getCurrentIndex() == errorIndex) { if (matched && seeking) { seeking = false; } if (!matched && !seeking && context.getMatcher().accept(isSingleCharMatcherVisitor)) { failedMatchers.add(context.getPath()); } } return matched; } }
JavaScript
UTF-8
5,922
3.1875
3
[]
no_license
var schedule = {} $(document).ready(function() { // listen for save button clicks schedule = JSON.parse(localStorage.getItem("schedule")) || {}; function setSchedule(schedule) { for (var time in schedule){ var hour = time.split("-")[1]; var textAreaClass = `.textarea${hour}`; var entry = schedule[time]; $(textAreaClass).val(entry); } } setSchedule(schedule); $(".saveBtn").on("click", function() { // get nearby values var value = $(this).siblings(".description").val(); var time = $(this).parent().attr("id"); console.log('value:', value); console.log('time:', time); // save the value in localStorage as time schedule[time] = value; localStorage.setItem("schedule", JSON.stringify(schedule)); console.log(localStorage); }); function hourUpdater() { // get current number of hours var currentHour = moment().hours(); console.log('current hour:', currentHour); // loop over time blocks $(".time-block").each(function() { var blockHour = parseInt($(this).attr("id").split("-")[1]); // check if we've moved past this time // if the current hour is greater than the block hour // then add class "past" // if they are equal // then remove class "past" and add class "present" // else // remove class "past", remove class "present", add class "future" //comparing currentHour to 9 if (currentHour > 9){ $(".textarea9").addClass("past") } else if (currentHour == 9){ $(".textarea9").removeClass("past"); $(".textarea9").addClass("present"); } else if (currentHour < 9){ $(".textarea9").removeClass("past"); $(".textarea9").removeClass("present"); $(".textarea9").addClass("future"); } //comparing currentHour to 10 if (currentHour > 10){ $(".textarea10").addClass("past") } else if (currentHour == 10){ $(".textarea10").removeClass("past"); $(".textarea10").addClass("present"); } else if (currentHour < 10){ $(".textarea10").removeClass("past"); $(".textarea10").removeClass("present"); $(".textarea10").addClass("future"); } //comparing currentHour to 11 if (currentHour > 11){ $(".textarea11").addClass("past") } else if (currentHour == 11){ $(".textarea11").removeClass("past"); $(".textarea11").addClass("present"); } else if (currentHour < 11){ $(".textarea11").removeClass("past"); $(".textarea11").removeClass("present"); $(".textarea11").addClass("future"); } //comparing currentHour to 12 if (currentHour > 12){ $(".textarea12").addClass("past") } else if (currentHour == 12){ $(".textarea12").removeClass("past"); $(".textarea12").addClass("present"); } else if (currentHour < 12){ $(".textarea12").removeClass("past"); $(".textarea12").removeClass("present"); $(".textarea12").addClass("future"); } //comparing currentHour to 1pm if (currentHour > 13){ $(".textarea13").addClass("past") } else if (currentHour == 13){ $(".textarea13").removeClass("past"); $(".textarea13").addClass("present"); } else if (currentHour < 13){ $(".textarea13").removeClass("past"); $(".textarea13").removeClass("present"); $(".textarea13").addClass("future"); } //comparing currentHour to 2pm if (currentHour > 14){ $(".textarea14").addClass("past") } else if (currentHour == 14){ $(".textarea14").removeClass("past"); $(".textarea14").addClass("present"); } else if (currentHour < 14){ $(".textarea14").removeClass("past"); $(".textarea14").removeClass("present"); $(".textarea14").addClass("future"); } //comparing currentHour to 3pm if (currentHour > 15){ $(".textarea15").addClass("past") } else if (currentHour == 15){ $(".textarea15").removeClass("past"); $(".textarea15").addClass("present"); } else if (currentHour < 15){ $(".textarea15").removeClass("past"); $(".textarea15").removeClass("present"); $(".textarea15").addClass("future"); } //comparing currentHour to 4pm if (currentHour > 16){ $(".textarea16").addClass("past") } else if (currentHour == 16){ $(".textarea16").removeClass("past"); $(".textarea16").addClass("present"); } else if (currentHour < 16){ $(".textarea16").removeClass("past"); $(".textarea16").removeClass("present"); $(".textarea16").addClass("future"); } //comparing currentHour to 5pm if (currentHour > 17){ $(".textarea17").addClass("past") } else if (currentHour == 17){ $(".textarea17").removeClass("past"); $(".textarea17").addClass("present"); } else if (currentHour < 17){ $(".textarea17").removeClass("past"); $(".textarea17").removeClass("present"); $(".textarea17").addClass("future"); } }); } // set up interval to check if current time needs to be updated // which means execute hourUpdater function every 15 seconds setInterval(hourUpdater(), 15000); // load any saved data from localStorage // for (const [key, value] of Object.entries(localStorage)) { // console.log(${key} | ${value}); // } console.log(Object.entries(localStorage)); // display current day on page $("#currentDay").text(moment().format("dddd, MMMM Do")); $("#currentTime").text("Current Time: " + moment().format('LT') ); });
Markdown
UTF-8
6,626
2.5625
3
[]
no_license
三四〇 一八一四年秋天,尼古拉和玛丽亚公爵小姐结了婚,尼古拉带着妻子、母亲和索尼娅迁到童山居住。 三年内,他没有变卖妻子的田产就还清了其余的债务。一个表姐去世后,他继承了一笔不大的遗产,把欠皮埃尔的债也还清了。 又过了三年,到一八二〇年,尼古拉已把他的财务整顿得有条不紊,更进一步在童山附近买了一处不大的庄园;此时他还在谈判买回父亲在奥特拉德诺耶的住宅——这可是他梦寐以求的一桩大事啊! 起初,他管理家业是出于需要,但不久就对经营庄园入了迷,几乎成为他独一无二的爱好了。尼古拉是个普通地主,不喜欢新办法,特别不喜欢当时流行的那套英国办法,他嘲笑经济理论著作,不喜欢办工厂,不喜欢价格高昂的产品,不喜欢种植其他贵重的农作物,也不单独经营农业的某一部门。他的目光总是盯着整个庄园,而不是庄园的某一部门,在庄园里,主要的东西不是存在于土壤和空气中的氮和氧,不是特别的犁和粪肥,而是使氮、氧、粪肥和犁发生作用的主要手段,也就是农业劳动者。当尼古拉着手管理庄园,深入了解它的各个方面的时候,尤其注重农民。他认为农民不仅是农业生产中的主要手段,而且是农业生产的最终目标和判断农业生产最后效益的主要裁判员。他先是观察农民,竭力了解他们的需要,了解他们对好坏的看法,他只是在表面上发号施令,而实际上是向农民学习他们的工作方法、语言,以及对好坏是非的判断。只有当他了解农民的爱好和愿望,学会用他们的语言说话,懂得他们话里潜在的意思,感到自己同他们已打成一片;只有在这个时候他才大胆地管理他们,也就是对农民尽他应尽的责任。尼古拉就是这样来经营他的农庄,于是在农业上他取得了最辉煌的成就。 尼古拉着手管理庄园的时候,凭着他那天赋的洞察力,立刻指定了合适的村长和工长(如果农民有权选举的话,也会选上这两个人的),而且再也不更换。他首先做的不是研究粪肥的化学成分,不是钻研借方和贷方(他爱说这种嘲笑的话),而是弄清农民牲口的头数,并千方百计使牲口增加。他支持农民维持大家庭,不赞成分家。他对懒汉、二流子和软弱无能的人一概不姑息,尽可能把他们从集体驱逐出去。 在播种、收割干草和作物上,他对自己的田地和对农民的田地一视同仁。像尼古拉这样播种和收割得又早又好、收入又这么好的地主很少。 他不爱管家奴的事,称他们为吃闲饭的人。然而大家却说他姑息家奴,把他们惯坏了。每当需要对某个家奴作出决定时,特别是作出处分时,他总是犹豫不决,要同家里所有的人商量。只有在可以用家奴代替农民去当兵的时候,他就会毫不犹豫地派家奴去当兵。在处理有关农民的问题上,他从来没有丝毫疑虑。他知道,他的每项决定都得到全体农民的拥护,最多只有一两个人持不同意见。 他不会只凭一时心血来潮找什么人的麻烦或者处分什么人,也不会凭个人的好恶宽恕人和奖赏人。他说不出什么事该做和什么事不该做,但两者的标准在他心里是明确不变的。 他对不顺利,或者乱七八糟的事,常常生气地说:“我们俄国老百姓真没办法。”他似乎觉得他无法容忍这样的农夫。 然而他却是用整个心灵爱“我们俄国老百姓”,爱他们的风俗习惯,正因为这样,他才能了解和采用最富有成效的、最适合俄罗斯农村特点的农村生产经营方法和方式。 玛丽亚伯爵夫人妒忌丈夫对事业的热爱,惋惜她不能分享这种感情,但她也不能理解他在那个对她来说是如此隔膜和生疏的世界里感受到的快乐和烦恼。她无法理解,他天一亮就起身,在田地里或打谷场上消磨整个早晨,在播种、割草或者收获后回家同她一起喝茶时,怎么总是那样兴高采烈,得意洋洋。当他赞赏地谈起富裕农户马特维·叶尔米什和他家里的人通宵搬运庄稼,别人还没有收割,可他已垛好禾捆的时候,她不能理解他讲这种事的时候怎么会这样兴致勃勃。当他看见温顺的细雨洒在干旱的燕麦苗上时,他从窗口走到阳台上,眨着眼,咧开留着胡髭的嘴唇,她无法明了他怎么会笑得那么开心。在割草或者收庄稼的时候,满天乌云被风吹散,他的脸晒得又红又黑汗水淋淋,身上带着一股苦艾和野菊的气味,从打谷场回来,这时,她不能理解为什么他总是高兴地搓着手说“再有一天,我们的粮食和农民的粮食都可以入仓了”。 她更不了解的是,这个心地善良、事事顺她意的人,一听到她替农妇式农夫求情免除他们的劳役时,为什么就会露出绝望的神情,为什么善心的尼古拉坚决拒绝她,他很气忿地叫她不要过问那与她无关的事。她觉得他有一个特殊的世界,他十分热爱那个世界,而她却不懂那个世界的某些规章制度。 她有时竭力想了解他,对他谈起他的功劳在于给农奴做了好事,他一听就恼了,他回答说:“根本不是这么回事,我从来没有这么想过,我也没有为他们谋福利。什么为他人谋幸福,全都是说得漂亮,全都是娘们的胡扯。我可不愿让我的孩子们上街去要饭,我活一天,就要理好我的家业,就是这样。为了做到这一点,就要立个好规矩,必须严格管理,就是这样。”他激动地握紧拳头说。“当然也要公平合理,”他又说,“因为,如果农民缺衣少食,家里只有一匹瘦马,那他既不能为他自己干好活,也不能给我干什么活了。” 也许,正因为尼古拉没有让自己想到他是在为别人做好事,是在乐善好施,于是他所做的一切都是那么富于成效,他的财富迅速增加,邻庄的农奴都来请求把他们买过去。就在他死后很久,农奴们还念念不忘他的治理才能。”“他是个好东家,……把农民的事放在前头,自己的事放在后头。可是他对人并不姑息。没说的——一个好东家。”
JavaScript
UTF-8
1,180
2.765625
3
[]
no_license
function timer() { var timer = { running: false, iv: 5000, timeout: false, cb : function(){}, start : function(cb,iv,sd){ var elm = this; clearInterval(this.timeout); this.running = true; if(cb) this.cb = cb; if(iv) this.iv = iv; if(sd) elm.execute(elm); else this.timeout = setTimeout(function(){elm.execute(elm)}, this.iv); }, execute : function(e){ if(!e.running) return false; e.cb(); e.start(); }, stop : function(){ this.running = false; }, set_interval : function(iv){ clearInterval(this.timeout); this.start(false, iv); } }; return timer; } //MINIFIED VERSION: function timer(){var t={running:!1,iv:5e3,timeout:!1,cb:function(){},start:function(t,i,n){var e=this;clearInterval(this.timeout),this.running=!0,t&&(this.cb=t),i&&(this.iv=i),n?e.execute(e):this.timeout=setTimeout(function(){e.execute(e)},this.iv)},execute:function(t){return t.running?(t.cb(),void t.start()):!1},stop:function(){this.running=!1},set_interval:function(t){clearInterval(this.timeout),this.start(!1,t)}};return t}
TypeScript
UTF-8
293
3.46875
3
[]
no_license
// interface Person { // name:string; // age:number; // } type Person = { name:string; age:number; } var a:Person = { name: 'ss', age: 27 } type s = string; var str:s = 'hhh'; type Todo = {id:string; title:string; done:boolean}; function getTodo(todo: Todo){ }
Python
UTF-8
2,892
3.3125
3
[]
no_license
''' start.py This is the file in which I began testing and development with the python requests library and API key author: awenstrup ''' #----------------Import statements--------------------- import requests from user import User #----------------Global Variable Definitions----------- #API Key Path api_key_file_path = '../api_key.txt' #URL fragments url_root = 'https://app.joinhandshake.com/api/v1' jobs_ext = '/jobs' users_ext = '/users' ext = users_ext #INPUT LINE #Request sections headers = {} params = {} #----------------Function definitions------------------ #Create HTTP headers def get_api_key(path): file = open(path, 'r') key = file.read().strip() return key def add_auth_header(key): headers['Authorization'] = 'Token token=\"' + key + '\"' # {Authorization: Token token=API_KEY_HERE} def add_content_type_header(): headers['Content-Type'] = 'application/json' # {Content-Type: appication/json} def add_cache_header(): headers['Cache-Control'] = 'no-cache' # {Cache-Control: no-cache} def init_headers(): k = get_api_key(api_key_file_path) add_auth_header(k) add_content_type_header() add_cache_header() #Set parameters def search_student_param(string): params['query'] = string def set_reponse_size(size): params['per_page'] = size def load_user(response): ''' Returns a User object (with username, first and last names, and class name), given a JSON object representing a user ''' uid = response['username'] email = response['email_address'] type = response['user_type'] first = response['first_name'] last = response['last_name'] class_name = response['school_year_name'] return User(uid, email, type, first, last, class_name) def load_users_from_year(users, year): ''' Returns all the users of a certain class year ''' out = {} for user in users: if user['user_type'] == 'Students' and user['school_year_name'] == year: out[user['username']] = load_user(user) for key in out: print(out[key]) return(out) #----------------Main---------------------------------- ''' Here is an example of a generic get request requests.get(url, headers=headers, data=data) ''' #Setup HTTP Request init_headers() #search_student_param('Senior') #INPUT LINE set_reponse_size(4000) #INPUT LINE, includes all users print(headers) print(params) print(url_root + ext) #Send HTTP Request #Request only users that match 'Wenstrup' r1 = requests.get(url_root + ext, headers=headers, params={'query': 'Wenstrup'}) #INPUT LINE #Request all users r2 = requests.get(url_root + ext, headers=headers, params=params) #INPUT LINE #Process returned data data1 = r1.json() alex = load_user(data1['users'][1]) print(alex) print() data2 = r2.json() #print(data2) users = load_users_from_year(data2['users'], 'Senior')
Java
UTF-8
873
2.03125
2
[]
no_license
package top.parak.config; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import javax.websocket.server.ServerEndpointConfig; /** * @author KHighness * @since 2021-04-05 */ public class CustomEndpointConfigure extends ServerEndpointConfig.Configurator implements ApplicationContextAware { private static volatile BeanFactory context; @Override public <T> T getEndpointInstance(Class<T> clazz) throws InstantiationException { return context.getBean(clazz); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { CustomEndpointConfigure.context = applicationContext; } }
PHP
UTF-8
1,048
2.640625
3
[]
no_license
<?php include_once('../config/security.php'); function get_token($context,$data) { global $ALLOWED_TOKEN_CONTEXTS; if(in_array($context,$ALLOWED_TOKEN_CONTEXTS)) { //check for duplicate token $query = "SELECT code FROM tokens WHERE context='$context' AND data='$data'"; $ret = mysql_query($query); if($ret && mysql_numrows($ret))//if it exists {//return the old one return mysql_result($ret,0); } else {//create new token $token = uniqid(); $query = "INSERT INTO tokens (code,context,data) VALUES ('$token','$context','$data')"; $ret = mysql_query($query); if($ret) return $token; } } return false; } function verify_token($token,$context) { $query = "SELECT data FROM tokens WHERE code='$token' AND context='$context'"; $ret = mysql_query($query); if($ret && mysql_numrows($ret)) { return true; } return false; } function delete_token($token) { $query = "DELETE FROM tokens WHERE code='$token'"; $ret = mysql_query($query); return $ret; } ?>
Shell
UTF-8
1,238
4
4
[ "BSD-3-Clause" ]
permissive
#!/usr/bin/env bash cd "$(dirname "$0")" CONFIG="configs.js" if [[ "$1" != "" ]]; then CONFIG="$1" fi if ! [[ -f "$CONFIG" ]]; then echo "File \"$CONFIG\" not found" 1>&2 exit 1; fi # The prefix for temporary files tmp_prefix=`./get_conf_field.js misc.tmp_prefix $CONFIG` next_prefix=`./get_conf_field.js run.next_prefix $CONFIG` next_prefix_len=${#next_prefix} # Получает первую комманду cmd=`./gen_cmd.js $CONFIG` while [ "${cmd:0:next_prefix_len}" == "$next_prefix" ]; do # Непосредственно выполняемая команда to_run=${cmd:next_prefix_len} # индекс команды в БД index="${to_run%%:*}" index_end_pos="${#index}" let "index_end_pos=index_end_pos+1" to_run=${to_run:index_end_pos} # Temporary files for output streams err_file="${tmp_prefix}_err_${index}" out_file="${tmp_prefix}_out_${index}" # run command echo "[$index] -> [$to_run]" $($to_run 1> "$out_file" 2> "$err_file") # Завершаем выполнение ./finish.js "$index" "$out_file" "$err_file" "$CONFIG" rm "$out_file" rm "$err_file" # get next command cmd=`./gen_cmd.js $CONFIG` done echo "DONE"
C++
UTF-8
1,055
3.6875
4
[]
no_license
/** \file * Contains declaration of Point class and PolarPoint structure */ #ifndef POINT_H_INCLUDED #define POINT_H_INCLUDED #include<iostream> namespace cg{ /** A point representing a location in (x,y) coordinate space, specified in double precision. It can be used to store a set of <x,y> points, create a new point from given x,y coordinates. */ class Point{ public: double x; //!< x coordinate of the point double y; //!< y coordinate of the point Point(); //!< An empty constructor. Defaults to (0.0,0.0) Point(const Point& p); //!< A constructor using another point Point(double x, double y); //!< A constructor using x and y coordinates Point& operator=(const Point& p); //!< Assignment operator overloaded for points }; std::ostream& operator<<(std::ostream&, const Point&); std::istream& operator>>(std::istream&, Point&); /** \brief A point representing a location in (r,Θ) coordinate space, specified in double precision. */ struct PolarPoint{ cg::Point point; double r,theta; }; } #endif
Python
UTF-8
2,154
2.796875
3
[ "MIT" ]
permissive
# # Copyright 2014-2018 Neueda Ltd. # from heliumdb import Heliumdb, HE_O_CREATE, HE_O_VOLUME_CREATE import unittest import os class TestInt(unittest.TestCase): def setUp(self): os.system('truncate -s 2g /tmp/test-int') flags = HE_O_CREATE | HE_O_VOLUME_CREATE self.hdb = Heliumdb(url="he://.//tmp/test-int", datastore='helium', key_type='i', val_type='i', flags=flags) def tearDown(self): self.hdb.cleanup() if os.path.exists('/tmp/test-int'): os.remove('/tmp/test-int') def test_subscript(self): self.hdb[1] = 163 self.hdb[2] = 164 self.assertEqual(self.hdb[1], 163) self.assertEqual(self.hdb[2], 164) def test_keys(self): exp = {} exp[1] = 163 exp[2] = 164 self.hdb[1] = 163 self.hdb[2] = 164 keys = [] for k in self.hdb.keys(): keys.append(k) self.assertEqual(self.hdb[k], exp[k]) self.assertEqual(len(keys), len(exp.keys())) def test_iter_keys(self): exp = {} exp[1] = 163 exp[2] = 164 self.hdb[1] = 163 self.hdb[2] = 164 keys = [] for k in self.hdb: keys.append(k) self.assertEqual(self.hdb[k], exp[k]) self.assertEqual(len(keys), len(exp.keys())) def test_iter_items(self): exp = {} exp[1] = 163 exp[2] = 164 self.hdb[1] = 163 self.hdb[2] = 164 keys = [] for k, v in self.hdb.items(): keys.append(k) self.assertEqual(v, exp[k]) self.assertEqual(len(keys), len(exp.keys())) def test_get(self): self.hdb[1] = 123 self.assertEqual(self.hdb.get(1), 123) self.assertEqual(self.hdb.get(2, 100), 100) def test_del(self): #put key 'x' self.hdb[1] = 60 self.assertEqual(self.hdb.get(1), 60) #deleting key 'x' del self.hdb[1] self.assertEqual(self.hdb.get(1, None), None)
Java
UTF-8
6,045
2.34375
2
[]
no_license
/* * Created on 27/02/2002 * Donated from Lindsay's private source library * * @author Lindsay Bradford * * * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package org.yawlfoundation.yawl.editor.swing; import java.text.*; import java.text.SimpleDateFormat; import java.util.*; import javax.swing.*; import javax.swing.text.*; public class JFormattedTimeField extends JFormattedSelectField { /** * */ private static final long serialVersionUID = 1L; protected Date dateValue; protected BoundVerifier verifier; public static final SimpleDateFormat TIMESTAMP_FORMAT = new SimpleDateFormat("hhmmss"); public JFormattedTimeField(String format, int columns) { super(getDateFormatter(format)); initialise(format, new Date(), columns); } public JFormattedTimeField(String format, Date date, int columns) { super(getDateFormatter(format)); initialise(format, date, columns); } private void initialise(String format, Date date, int columns) { assert isDateFormat(format) : "Format String parameter is not a date format"; verifier = new BoundVerifier(); setInputVerifier(verifier); setValue(date); setColumns(columns); } public Date getDate() { return (Date) getValue(); } public void setDate(Date date) { setValue(date); } public String getTimestamp() { return TIMESTAMP_FORMAT.format((Date) getValue()); } public void setDateViaTimestamp(String timestamp) { try { setValue(TIMESTAMP_FORMAT.parse(timestamp)); } catch (Exception e) {} } private static boolean isDateFormat(String format) { return true; } private static DateFormatter getDateFormatter(String format) { SimpleDateFormat dateFormat = new SimpleDateFormat(format); dateFormat.set2DigitYearStart(new Date(0)); StrictTimeFormatter timeFormatter = new StrictTimeFormatter(dateFormat); return timeFormatter; } public void setLowerBound(Date lowerBound) { verifier.setLowerBound(lowerBound); } public void setUpperBound(Date upperBound) { verifier.setUpperBound(upperBound); } public void setBounds(Date lowerBound, Date upperBound) { verifier.setBounds(lowerBound, upperBound); } class BoundVerifier extends InputVerifier { protected Date lowerBound; protected Date upperBound; public BoundVerifier() { super(); setBounds(new Date(Long.MIN_VALUE), new Date(Long.MAX_VALUE)); } public BoundVerifier(Date lowerBound, Date upperBound) { super(); setBounds(lowerBound, upperBound); } public boolean verify(JComponent component) { Date value; assert component instanceof JFormattedTimeField; JFormattedTimeField field = (JFormattedTimeField) component; String valueAsText; try { valueAsText = field.getText(); DateFormatter dateFormatter = (DateFormatter) field.getFormatter(); SimpleDateFormat dateFormat = (SimpleDateFormat) dateFormatter.getFormat(); value = dateFormat.parse(valueAsText); } catch (ParseException npe) { return false; } return verifyBounds(value); } protected boolean verifyBounds(Date date) { if (date.before(lowerBound)) { return false; } if (date.after(upperBound)) { return false; } return true; } public boolean shouldYieldFocus(JComponent component) { boolean isValid = verify(component); if (!isValid) { JFormattedTimeField field = (JFormattedTimeField) component; field.invalidEdit(); } return isValid; } public void setLowerBound(Date lowerBound) { this.lowerBound = lowerBound; } public void setUpperBound(Date upperBound) { this.upperBound = upperBound; } public void setBounds(Date lowerBound, Date upperBound) { setLowerBound(lowerBound); setUpperBound(upperBound); } } } class StrictTimeFormatter extends DateFormatter { /** * */ private static final long serialVersionUID = 1L; private static final TimeFilter filter = new TimeFilter(); public StrictTimeFormatter(SimpleDateFormat format) { super(format); } protected DocumentFilter getDocumentFilter() { return filter; } } class TimeFilter extends DocumentFilter { public void replace(DocumentFilter.FilterBypass bypass, int offset, int length, String text, AttributeSet attributes) throws BadLocationException { if (isValidText(text)) super.replace(bypass,offset,length,text,attributes); } protected boolean isValidText(String text) { return validateText("0123456789:AMP ", text); } protected boolean validateText(String validCharacters, String text) { // separated into another method so I can switch in a new one for differing // valid character sets. for (int i = 0; i < text.length(); i++) { if (validCharacters.indexOf(text.charAt(i)) == -1) { return false; } } return true; } }
Java
UTF-8
7,491
2.609375
3
[]
no_license
package com.flatrocktechnology.android.famousquotequiz.fragments; import android.app.Activity; import android.app.Fragment; import android.content.Context; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.flatrocktechnology.android.famousquotequiz.R; import com.flatrocktechnology.android.famousquotequiz.activities.MainActivity; import com.flatrocktechnology.android.famousquotequiz.model.QuizQuestionDao; import java.util.ArrayList; import java.util.Arrays; import java.util.Random; /* Fragment for showing question with three possible answers*/ public final class MultipleChoiceModeFragment extends Fragment { private static final String TAG = MultipleChoiceModeFragment.class.getSimpleName(); private OnAnswerClickListener mListener; private ArrayList<QuizQuestionDao> questionList; private int progressCount; private int correctAnswersCount; private TextView tvQuestion; private Button btnFirstAnswer; private Button btnSecondAnswer; private Button btnThirdAnswer; @Override public void onAttach(Context context) { super.onAttach(context); // This makes sure that the container activity has implemented // the callback interface. If not, it throws an exception try { mListener = (OnAnswerClickListener) context; } catch (ClassCastException e) { throw new ClassCastException(context.toString() + " must implement OnYesNoAnswerClickListener"); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); // This makes sure that the container activity has implemented // the callback interface. If not, it throws an exception try { mListener = (OnAnswerClickListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnYesNoAnswerClickListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { questionList = (ArrayList<QuizQuestionDao>) getArguments().getSerializable(MainActivity.QUESTIONS_BUNDLE_KEY); } catch (Exception e) { Log.d(TAG, "MultipleChoiceModeFragment exception " + questionList); // TODO Show error dialog } progressCount = 0; correctAnswersCount = 0; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_multiple_choise_mode, container, false); initializeLayout(rootView); showNextQuestionOnScreen(); setOnClickListeners(); return rootView; } private void initializeLayout(View rootView) { tvQuestion = (TextView) rootView.findViewById(R.id.tvQuestion); btnFirstAnswer = (Button) rootView.findViewById(R.id.btnAnswerA); btnSecondAnswer = (Button) rootView.findViewById(R.id.btnAnswerB); btnThirdAnswer = (Button) rootView.findViewById(R.id.btnAnswerC); } private void setOnClickListeners() { btnFirstAnswer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final String textOnButton = btnFirstAnswer.getText().toString(); handleUserButtonClick(textOnButton); } }); btnSecondAnswer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final String textOnButton = btnSecondAnswer.getText().toString(); handleUserButtonClick(textOnButton); } }); btnThirdAnswer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final String textOnButton = btnThirdAnswer.getText().toString(); handleUserButtonClick(textOnButton); } }); } /* This method check weather the selected button from user was the correct answer to the question, then inform him by showing dialog and after that load the next question on screen until the end of the quiz. */ private void handleUserButtonClick(String textOnButton) { String dialogTitle; QuizQuestionDao currentQuestion = questionList.get(progressCount); String correctAnswer = currentQuestion.getCorrAnswer(); // Compare weather the passed text is the correct answer to the question if (correctAnswer.equals(textOnButton)) { correctAnswersCount++; Log.d(TAG, "correctAnswersCount: " + correctAnswersCount); // Compose title for dialog; dialogTitle = getString(R.string.correct_answer) + " " + correctAnswer; } else { // Compose title for dialog dialogTitle = getString(R.string.wrong_answer) + " " + correctAnswer; } mListener.showDialog(dialogTitle); // Update the counter progressCount++; } /* Update screen with the question and the possible asnwers */ private void showNextQuestionOnScreen() { QuizQuestionDao dao = questionList.get(progressCount); tvQuestion.setText("\"" + dao.getQuestion() + "\""); // Put the answers in list to be randomized. ArrayList<String> list = new ArrayList<>(Arrays.asList(dao.getCorrAnswer(), dao.getFirstWrongAnswer(), dao.getSecondWrongAnswer())); randomizeElementsPosition(list); btnFirstAnswer.setText(list.get(0)); btnSecondAnswer.setText(list.get(1)); btnThirdAnswer.setText(list.get(2)); } private void randomizeElementsPosition(ArrayList<String> list) { // Swap first and second int max = 10; int middle = 5; Random random = new Random(); int rand = random.nextInt(max); if (rand < middle) { // used to randomly enter in the if String swap = list.get(1); list.set(1, list.get(0)); list.set(0, swap); } //Swap second and third word rand = random.nextInt(max); if (rand > middle) { // used to randomly enter in the if String swap = list.get(2); list.set(2, list.get(1)); list.set(1, swap); } } /* Call this method from outside the fragment to load and show the next question on screen. If we reached the end of the quiz show the PlayAgainFragment. */ public void loadNextQuestion() { Log.d(TAG, " loadNextQuestion progresscount: " + progressCount); if (progressCount < 10) { showNextQuestionOnScreen(); } else { // TODO check logic mListener.finishedQuiz(correctAnswersCount); progressCount = 0; } } public interface OnAnswerClickListener { void finishedQuiz(final int correctAnswers); void showDialog(String dialogTitle); } }
Python
UTF-8
781
3.59375
4
[]
no_license
def non_repeat(line): temp_longest, current_longest = '', '' for char in line: if char in temp_longest: current_longest = max(current_longest, temp_longest, key=lambda x: len(x)) index_of_repeating_symbol = temp_longest.index(char) + 1 temp_longest = temp_longest[index_of_repeating_symbol:] + char else: temp_longest += char return max(current_longest, temp_longest, key=lambda x: len(x)) if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing # assert non_repeat('aaaaa') == 'a', "First" assert non_repeat('abdjwawk') == 'abdjw', "Second" assert non_repeat('abcabcffab') == 'abcf', "Third" print('"Run" is good. How is "Check"?')
JavaScript
UTF-8
1,045
2.765625
3
[]
no_license
import React from 'react'; import PropTypes from 'prop-types'; class Addtodo extends React.Component{ state = { value:'' } textChange = (e) => this.setState({[e.target.name]:e.target.value}) onSubmit = (e) => { e.preventDefault()//The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form. Clicking on a link, prevent the link from following the URL this.props.addTodo(this.state.value) this.setState({value:''}) } render() { return ( <div> <form onSubmit={this.onSubmit}> <input type = "text" placeholder = "addtodo.." name = "value" value={this.state.value} onChange={this.textChange}></input> <input type ="submit" value="Submit"></input> </form> </div> ) } } export default Addtodo;
Markdown
UTF-8
3,886
3.421875
3
[]
no_license
# Problem 126: Word Ladder II > https://leetcode.com/problems/word-ladder-ii/\#/description ------ ## 思路 > https://discuss.leetcode.com/topic/27504/my-concise-java-solution-based-on-bfs-and-dfs 这个讲解不错! * 这道题是上一题的延伸,要寻找所有的最短梯子的解,而上一题只要得出最短的 length 长度就可以了。 * 可以用 bfs + dfs 的方式来得出所有的解。这里用 distance 记录所有的元素从 beginWord 出发的距离,这样,我们可以先用 bfs 找出最短长度,然后不断地找剩下的 word,根据 distance 来 match ---------------- ```java public class Solution { public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) { List<String> path = new ArrayList<>(); List<List<String>> rst = new ArrayList<>(); Set<String> dict = new HashSet<String>(wordList); Map<String, List<String>> nodeNeighbors = new HashMap<>(); Map<String, Integer> distance = new HashMap<>(); dict.add(beginWord); bfs(beginWord, endWord, dict, nodeNeighbors, distance); dfs(beginWord, endWord, dict, nodeNeighbors, distance, path, rst); return rst; } private void bfs(String beginWord, String endWord, Set<String>dict, Map<String, List<String>> nodeNeighbors, Map<String, Integer> distance) { for (String s : dict) { nodeNeighbors.put(s, new ArrayList<>()); } Queue<String> queue = new LinkedList<>(); queue.offer(beginWord); distance.put(beginWord, 0); while (!queue.isEmpty()) { int size = queue.size(); boolean isFinish = false; for (int i = 0; i < size; i++) { String word = queue.poll(); int curDistance = distance.get(word); List<String> neighbors = getNeighbors(word, dict); for (String neighbor : neighbors) { nodeNeighbors.get(word).add(neighbor); if (!distance.containsKey(neighbor)) { distance.put(neighbor, curDistance + 1); if (neighbor.equals(endWord)) { isFinish = true; } else { queue.offer(neighbor); } } } } if (isFinish) break; } } private void dfs(String currWord, String endWord, Set<String>dict, Map<String, List<String>> nodeNeighbors, Map<String, Integer> distance, List<String> path, List<List<String>> rst) { path.add(currWord); if (currWord.equals(endWord)) { rst.add(new ArrayList<String>(path)); } else { for (String nextWord : nodeNeighbors.get(currWord)) { if (distance.get(nextWord) == distance.get(currWord) + 1) { dfs(nextWord, endWord, dict, nodeNeighbors, distance, path, rst); } } } path.remove(path.size() - 1); } private List<String> getNeighbors(String word, Set<String> dict) { List<String> neighbors = new ArrayList<>(); for (int i = 0; i < word.length(); i++) { for (char c = 'a'; c <= 'z'; c++) { if (c == word.charAt(i)) continue; String neighbor = replace(word, i, c); if (dict.contains(neighbor)) { neighbors.add(neighbor); } } } return neighbors; } private String replace(String word, int index, char c) { char[] arr = word.toCharArray(); arr[index] = c; return new String(arr); } } ```
Python
UTF-8
659
3.171875
3
[]
no_license
#!/usr/bin/env python # coding: utf-8 # @File Name: 003.py # @Author: Joshua Liu # @Email: liuchaozhenyu@gmail.com # @Create Date: 2017-03-24 14:03:22 # @Last Modified: 2017-03-24 14:03:59 # @Description: import unittest def lengthOfLongestSubstring(s): res = 0 left = 0 d = {} for i, ch in enumerate(s): if ch in d and d[ch] >= left: left = d[ch] + 1 d[ch] = i res = max(res, i - left + 1) return res class mytest(unittest.TestCase): def testLengthOfLongestSubstring(self): max_len = lengthOfLongestSubstring('abcabcbb') self.assertEqual(max_len, 3) if __name__ == '__main__': unittest.main()
PHP
UTF-8
23,491
2.828125
3
[]
no_license
<?php /** * Holder for items in the shopping cart and interacting with them, as * well as rendering these items into an interface that allows editing * of items, * * @author morven * @package commerce */ class ShoppingCart extends Commerce_Controller { /** * URL Used to access this controller * * @var string * @config */ private static $url_segment = 'commerce/cart'; /** * Name of the current controller. Mostly used in templates. * * @var string * @config */ private static $class_name = "ShoppingCart"; private static $allowed_actions = array( "remove", "emptycart", "clear", "update", "usediscount", "CartForm", "PostageForm", "DiscountForm" ); /** * Determines if the shopping cart is currently enabled * * @var boolean * @config */ protected static $enabled = true; /** * Overwrite the default title for this controller which is taken * from the translation files. This is used for Title and MetaTitle * variables in templates. * * @var string * @config */ private static $title; /** * Track all items stored in the current shopping cart * * @var ArrayList */ protected $items; /** * Track a discount object placed against this cart * * @var ArrayList */ protected $discount; /** * Show the discount form on the shopping cart * * @var boolean * @config */ private static $show_discount_form = false; /** * Getters and setters * */ public function getClassName() { return self::config()->class_name; } public function getTitle() { return ($this->config()->title) ? $this->config()->title : _t("Commerce.CartName", "Shopping Cart"); } public function getMetaTitle() { return $this->getTitle(); } public function getShowDiscountForm() { return $this->config()->show_discount_form; } public function getItems() { return $this->items; } public function getDiscount() { return $this->discount; } public function setDiscount(Discount $discount) { $this->discount = $discount; } /** * Set postage that is available to the shopping cart based on the * country and zip code submitted * * @param $country 2 character country code * @param $code Zip or Postal code * @return ShoppingCart */ public function setAvailablePostage($country, $code) { // Set postage data from commerce_controller and save into a session $postage_areas = $this->getPostageAreas($country, $code); Session::set("Commerce.AvailablePostage", $postage_areas); return $this; } /** * find out if the shopping cart is enabled * * @return Boolean */ public static function isEnabled() { return self::config()->enabled; } /** * Shortcut for ShoppingCart::create, exists because create() * doesn't seem quite right. * * @return ShoppingCart */ public static function get() { return ShoppingCart::create(); } public function __construct() { // If items are stored in a session, get them now if(Session::get('Commerce.ShoppingCart.Items')) $this->items = unserialize(Session::get('Commerce.ShoppingCart.Items')); else $this->items = ArrayList::create(); // If discounts stored in a session, get them, else create new list if(Session::get('Commerce.ShoppingCart.Discount')) $this->discount = unserialize(Session::get('Commerce.ShoppingCart.Discount')); // If we don't have any discounts, a user is logged in and he has // access to discounts through a group, add the discount here if(!$this->discount && Member::currentUserID()) { $member = Member::currentUser(); $this->discount = $member->getDiscount(); Session::set('Commerce.ShoppingCart.Discount', serialize($this->discount)); } parent::__construct(); } /** * Actions for this controller */ /** * Default acton for the shopping cart */ public function index() { $this->extend("onBeforeIndex"); return $this->renderWith(array( 'ShoppingCart', 'Commerce', 'Page' )); } /** * Remove a product from ShoppingCart Via its ID. This action * expects an ID to be sent through the URL that matches a specific * key added to an item in the cart * * @return Redirect */ public function remove() { $key = $this->request->param('ID'); if(!empty($key)) { foreach($this->items as $item) { if($item->Key == $key) $this->items->remove($item); } $this->save(); } return $this->redirectBack(); } /** * Action that will clear shopping cart and associated sessions * */ public function emptycart() { $this->extend("onBeforeEmpty"); $this->removeAll(); $this->save(); return $this->redirectBack(); } /** * Action used to add a discount to the users session via a URL. * This is preferable to using the dicount form as disount code * forms seem to provide a less than perfect user experience * */ public function usediscount() { $this->extend("onBeforeUseDiscount"); $code_to_search = $this->request->param("ID"); $code = false; if(!$code_to_search) return $this->httpError(404, "Page not found"); // First check if the discount is already added (so we don't // query the DB if we don't have to). if(!$this->discount || ($this->discount && $this->discount->Code != $code_to_search)) { $codes = Discount::get() ->filter("Code", $code_to_search) ->exclude("Expires:LessThan", date("Y-m-d")); if($codes->exists()) { $code = $codes->first(); $this->discount = $code; $this->save(); } } elseif($this->discount && $this->discount->Code == $code_to_search) $code = $this->discount; return $this ->customise(array( "Discount" => $code ))->renderWith(array( 'ShoppingCart_discount', 'Commerce', 'Page' )); } /** * Add a product to the shopping cart via its ID number. * * @param Item Product Object you wish to add * @param Quantity number of this item to add * @param Customise array of custom options for this product, needs to be a * multi dimensional array with each item of format: * - "Title" => (str)"Item title" * - "Value" => (str)"Item Value" * - "ModifyPrice" => (float)"Modification to price" */ public function add(Product $add_item, $quantity = 1, $customise = array()) { $added = false; $config = SiteConfig::current_site_config(); // Make a string to match id's against ones already in the cart $product_key = ($customise) ? (int)$add_item->ID . ':' . base64_encode(serialize($customise)) : (int)$add_item->ID; // Check if the add call is trying to add an item already in the cart, // if so update the current quantity foreach($this->items as $item) { // If an instance of this is already in the shopping basket, increase if($item->Key == $product_key) { $this->update($item->Key, ($item->Quantity + $quantity)); $added = true; } } // If no update was sucessfull, update records if(!$added) { $custom_data = new ArrayList(); $price = $add_item->Price; (float)$tax_rate = $config->TaxRate; foreach($customise as $custom_item) { $custom_data->add(new ArrayData(array( 'Title' => ucwords(str_replace(array('-','_'), ' ', $custom_item["Title"])), 'Value' => $custom_item["Value"], 'ModifyPrice' => $custom_item['ModifyPrice'] ))); // If a customisation modifies price, adjust the price $price = (float)$price + (float)$custom_item['ModifyPrice']; } // Now, caclulate tax based on the new modified price and tax rate if($tax_rate > 0) (float)$tax = ($price / 100) * $tax_rate; // Get our tax amount from the price else (float)$tax = 0; $item_to_add = ArrayData::create(array( 'Key' => $product_key, 'ProductID' => $add_item->ID, 'Title' => $add_item->Title, 'SKU' => $add_item->SKU, 'Description' => $add_item->Description, 'Weight' => $add_item->Weight, 'Price' => number_format($price,2), 'Tax' => number_format($tax, 2), 'Customised' => $custom_data, 'Image' => $add_item->Images()->first(), 'Quantity' => $quantity )); $this->extend("onBeforeAdd", $item_to_add); $this->items->add($item_to_add); $this->extend("onAfterAdd"); } } /** * Find an existing item and update its quantity * * @param Item * @param Quantity */ public function update($item_key, $quantity) { foreach($this->items as $item) { if ($item->Key === $item_key) { $this->extend("onBeforeUpdate", $item); $item->Quantity = $quantity; $this->extend("onAfterUpdate", $item); return true; } } $this->save(); return false; } /** * Empty the shopping cart object of all items. * */ public function removeAll() { foreach($this->items as $item) { $this->items->remove($item); } } /** * Save the current products list and postage to a session. * */ public function save() { Session::clear("Commerce.PostageID"); // Save cart items Session::set( "Commerce.ShoppingCart.Items", serialize($this->items) ); // Save cart discounts Session::set( "Commerce.ShoppingCart.Discount", serialize($this->discount) ); // Update available postage if($data = Session::get("Form.Form_PostageForm.data")) { $country = $data["Country"]; $code = $data["ZipCode"]; $this->setAvailablePostage($country, $code); } } /** * Clear the shopping cart object and destroy the session. Different to * empty, as that retains the session. * */ public function clear() { Session::clear('Commerce.ShoppingCart.Items'); Session::clear('Commerce.ShoppingCart.Discount'); Session::clear("Commerce.PostageID"); } /** * Find the total weight of all items in the shopping cart * * @return Float */ public function TotalWeight() { $total = 0; foreach($this->items as $item) { $total = $total + ($item->Weight * $item->Quantity); } return $total; } /** * Find the total quantity of items in the shopping cart * * @return Int */ public function TotalItems() { $total = 0; foreach($this->items as $item) { $total = $total + $item->Quantity; } return $total; } /** * Find the cost of all items in the cart, without any tax. * * @return Float */ public function SubTotalCost() { $total = 0; foreach($this->items as $item) { $total = $total + ($item->Quantity * $item->Price); } return number_format($total,2); } /** * Get the cost of postage * */ public function PostageCost() { if($postage = PostageArea::get()->byID(Session::get("Commerce.PostageID"))) $cost = $postage->Cost; else $cost = 0; return number_format($cost,2); } /** * Find the total discount based on discount items added. * * @return Float */ public function DiscountAmount() { $total = 0; $subtotal = 0; $discount = $this->discount; if($discount) { // Are we using a whitelist $whitelist = $discount->WhiteList()->exists(); // Now get the total of any allowed items foreach($this->items as $item) { $allow = false; // If item is in our whitelist, then allow discount if($whitelist && $discount->WhiteList()->filter("ID", $item->ProductID)->first()) $allow = true; // If item is NOT in our blacklist, all adding discount if(!$whitelist && !$discount->BlackList()->filter("ID", $item->ProductID)->first()) $allow = true; if($allow) $subtotal = $subtotal + ($item->Quantity * $item->Price); } // If subtotal amount it greater than discount, use discount if($subtotal && $discount->Type == "Fixed") $total = ($subtotal > $discount->Amount) ? $discount->Amount : $subtotal; // Else, calculate a percentage elseif($subtotal && $discount->Type == "Percentage" && $discount->Amount) $total = (($discount->Amount / 100) * $subtotal); } return number_format($total,2); } /** * Find the total cost of tax for the items in the cart, as well as shipping * (if set) * * @return Float */ public function TaxCost() { // Add any tax that is needed for postage $config = SiteConfig::current_site_config(); $total = 0; if($config->TaxRate > 0) { $total = ($this->SubTotalCost() + $this->PostageCost()) - $this->DiscountAmount(); $total = ($total > 0) ? ((float)$total / 100) * $config->TaxRate : 0; } return number_format($total,2); } /** * Find the total cost of for all items in the cart, including tax and * shipping (if applicable) * * @return Float */ public function TotalCost() { $total = str_replace(",","",$this->SubTotalCost()); $discount = str_replace(",","",$this->DiscountAmount()); $postage = str_replace(",","",$this->PostageCost()); $tax = str_replace(",","",$this->TaxCost()); // If discount is less than 0, then set to 0 $total_with_discount = (((float)$total - (float)$discount) < 0) ? 0 : ((float)$total - (float)$discount); $total = $total_with_discount + (float)$postage + (float)$tax; return number_format($total,2); } /** * Form responsible for listing items in the shopping cart and * allowing management (such as addition, removal, etc) * * @return Form */ public function CartForm() { $fields = new FieldList(); $actions = new FieldList( FormAction::create('doUpdate', _t('Commerce.CartUpdate','Update Cart')) ->addExtraClass('btn') ->addExtraClass('btn-blue') ); $form = Form::create($this, "CartForm", $fields, $actions) ->addExtraClass("forms") ->setTemplate("ShoppingCartForm"); $this->extend("updateCartForm", $form); return $form; } /** * Form that allows you to add a discount code which then gets added * to the cart's list of discounts. * * @return Form */ public function DiscountForm() { $fields = new FieldList( TextField::create( "DiscountCode", _t("Commerce.DiscountCode", "Discount Code") )->setAttribute( "placeholder", _t("Commerce.EnterDiscountCode", "Enter a discount code") ) ); $actions = new FieldList( FormAction::create('doAddDiscount', _t('Commerce.Add','Add')) ->addExtraClass('btn') ->addExtraClass('btn-blue') ); $form = Form::create($this, "DiscountForm", $fields, $actions) ->addExtraClass("forms"); $this->extend("updateDiscountForm", $form); return $form; } /** * Form responsible for estimating shipping based on location and * postal code * * @return Form */ public function PostageForm() { $available_postage = Session::get("Commerce.AvailablePostage"); // Setup default postage fields $country_select = CompositeField::create( CountryDropdownField::create('Country',_t('Commerce.Country','Country')) ->setAttribute("class",'countrydropdown dropdown btn'), TextField::create("ZipCode",_t('Commerce.ZipCode',"Zip/Postal Code")) )->addExtraClass("size1of2") ->addExtraClass("unit") ->addExtraClass("unit-50"); // If we have stipulated a search, then see if we have any results // otherwise load empty fieldsets if($available_postage) { $search_text = _t('Commerce.Update',"Update"); // Loop through all postage areas and generate a new list $postage_array = array(); foreach($available_postage as $area) { $area_currency = new Currency("Cost"); $area_currency->setValue($area->Cost); $postage_array[$area->ID] = $area->Title . " (" . $area_currency->Nice() . ")"; } $postage_select = CompositeField::create( OptionsetField::create( "PostageID", _t('Commerce.SelectPostage',"Select Postage"), $postage_array ) )->addExtraClass("size1of2") ->addExtraClass("unit") ->addExtraClass("unit-50"); $confirm_action = CompositeField::create( FormAction::create("doSavePostage", _t('Commerce.Confirm',"Confirm")) ->addExtraClass('btn') ->addExtraClass('btn-green') )->addExtraClass("size1of2") ->addExtraClass("unit") ->addExtraClass("unit-50"); } else { $search_text = _t('Commerce.Search',"Search"); $postage_select = CompositeField::create() ->addExtraClass("size1of2") ->addExtraClass("unit") ->addExtraClass("unit-50"); $confirm_action = CompositeField::create() ->addExtraClass("size1of2") ->addExtraClass("unit") ->addExtraClass("unit-50"); } // Set search field $search_action = CompositeField::create( FormAction::create("doGetPostage", $search_text) ->addExtraClass('btn') )->addExtraClass("size1of2") ->addExtraClass("unit") ->addExtraClass("unit-50"); // Setup fields and actions $fields = new FieldList( CompositeField::create($country_select,$postage_select) ->addExtraClass("line") ->addExtraClass("units-row-end") ); $actions = new FieldList( CompositeField::create($search_action,$confirm_action) ->addExtraClass("line") ->addExtraClass("units-row-end") ); $required = RequiredFields::create(array( "Country", "ZipCode" )); $form = Form::create($this, 'PostageForm', $fields, $actions, $required) ->addExtraClass('forms') ->addExtraClass('forms-columnar'); // Check if the form has been re-posted and load data $data = Session::get("Form.{$form->FormName()}.data"); if(is_array($data)) $form->loadDataFrom($data); // Check if the postage area has been set, if so, Set Postage ID $data = array(); $data["PostageID"] = Session::get("Commerce.PostageID"); if(is_array($data)) $form->loadDataFrom($data); // Extension call $this->extend("updatePostageForm", $form); return $form; } /** * Action that will update cart * * @param type $data * @param type $form */ public function doUpdate($data, $form) { foreach($this->items as $cart_item) { foreach($data as $key => $value) { $sliced_key = explode("_", $key); if($sliced_key[0] == "Quantity") { if(isset($cart_item) && ($cart_item->Key == $sliced_key[1])) { if($value > 0) { $this->update($cart_item->Key, $value); } else $this->remove($cart_item->Key); } } } } $this->save(); return $this->redirectBack(); } /** * Action that will find a discount based on the code * * @param type $data * @param type $form */ public function doAddDiscount($data, $form) { $code_to_search = $data['DiscountCode']; // First check if the discount is already added (so we don't // query the DB if we don't have to). if(!$this->discount || ($this->discount && $this->discount->Code != $code_to_search)) { $code = Discount::get() ->filter("Code", $code_to_search) ->exclude("Expires:LessThan", date("Y-m-d")) ->first(); if($code) $this->discount = $code; } $this->save(); return $this->redirectBack(); } /** * Search and find applicable postage rates based on submitted data * * @param $data * @param $form */ public function doGetPostage($data, $form) { $country = $data["Country"]; $code = $data["ZipCode"]; $this->setAvailablePostage($country, $code); // Set the form pre-populate data before redirecting Session::set("Form.{$form->FormName()}.data", $data); $url = Controller::join_links($this->Link(),"#{$form->FormName()}"); return $this->redirect($url); } /** * Save applicable postage data to session * * @param $data * @param $form */ public function doSavePostage($data, $form) { Session::set("Commerce.PostageID", $data["PostageID"]); $url = Controller::join_links($this->Link(),"#{$form->FormName()}"); return $this->redirect($url); } }
C++
UTF-8
753
2.8125
3
[]
no_license
#include<iostream> #include<string> #include<map> using namespace std; map<char,char>mark; string line; int main() { mark['e']='q'; mark['r']='w'; mark['t']='e'; mark['y']='r'; mark['u']='t'; mark['i']='y'; mark['o']='u'; mark['p']='i'; mark['[']='o'; mark[']']='p'; mark['d']='a'; mark['f']='s'; mark['g']='d'; mark['h']='f'; mark['j']='g'; mark['k']='h'; mark['l']='j'; mark[';']='k'; mark['\'']='l'; mark['c']='z'; mark['v']='x'; mark['b']='c'; mark['n']='v'; mark['m']='b'; mark[',']='n'; mark['.']='m'; mark[' ']=' '; getline(cin,line); for(auto i:line) { cout<<mark[tolower(i)]; } cout<<endl; return 0; }
JavaScript
UTF-8
1,179
2.890625
3
[]
no_license
const {qCard, getDescription, getBasicEndPoint } = require('./Logic') // Sample Data var qCardSample = {"id":44,"name":"Relaxing","description":"restful, calming, peaceful"} test('Should hit endpoint without the database', () => { return getBasicEndPoint().then(res => { var data = res.data expect(typeof data).toBe('string') }) }) test('should return true if properly formed card object', () => { expect(qCard(qCardSample)).toBe(true); }) test('Should return a string for a card description', () => { return getDescription().then(res => { var data = res.data[0] expect(data).toHaveProperty('description') }) }) test('Should return only one card', () => { return getDescription().then(res => { var data = res.data expect(data).toHaveLength(1) }) }) test('Should return an object from axios', () => { return getDescription().then(res => { var data = res.data expect(typeof data).toBe('object') }) }) test('Should receive a string from our Description', () => { return getDescription().then(res => { var data = res.data[0] expect.any(Object) }) })
JavaScript
UTF-8
2,400
3.0625
3
[]
no_license
// authored by kyle simmons. this is the data provider for the news section import {getFriendArrayByUser} from '../friends/FriendProvider.js' let news = [] // gets the news from the api export const getNews= () =>{ return fetch("http://localhost:8088/articles?_expand=user") .then(response => response.json()) .then( parsedNews =>{ news = parsedNews } ) } // sorts news articles by date export const useNews = () => { const sortedByDate = news.sort( (currentPost, nextPost) => nextPost.timeOfArticlePost - currentPost.timeOfArticlePost ) return sortedByDate } // saves news articles export const saveNews = news => { return fetch('http://localhost:8088/articles', { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(news) }) .then(getNews) .then(dispatchStateChangeEvent) } // enables delete functionality export const deleteNews = newsId => { return fetch(`http://localhost:8088/articles/${newsId}`, { method: "DELETE" }) .then(getNews) } const eventHub = document.querySelector(".container") // change event for the news section const dispatchStateChangeEvent = () =>{ const newsStateChangedEvent = new CustomEvent("newsStateChanged") eventHub.dispatchEvent(newsStateChangedEvent) } // helper function created by devin. export const getNewsArrayByUser = user => { // Get a list of this user's friends. const friends = getFriendArrayByUser(user); if (typeof (user) === "number") { // Loop through all events return useNews().filter(ev => { // If the event's userId matches the user, return it if (user === ev.userId) { return true; } else { // Otherwise, loop through the friends of this user and see if any friends // match the ID of event's userId. return friends.find(fr => fr.followingId === ev.userId) } }) } } export const editNews = (article, articleId) =>{ return fetch (`http://localhost:8088/articles/${articleId}`,{ method: "Put", headers:{ "Content-Type": "application/json" }, body: JSON.stringify(article) }) .then(getNews) .then(dispatchStateChangeEvent) }
Java
UTF-8
7,344
2.25
2
[ "MIT" ]
permissive
/******************************************************************************* * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.debug.jdi.tests; import com.sun.jdi.Type; /** * Tests for JDI com.sun.jdi.Type. */ public class TypeTest extends AbstractJDITest { private Type fArrayType, fClassType, fInterfaceType, // primitive types fShortType, fByteType, fIntegerType, fLongType, fFloatType, fDoubleType, fCharType, fBooleanType, // One-dimensional primitive arrays fByteArrayType, fShortArrayType, fIntArrayType, fLongArrayType, fFloatArrayType, fDoubleArrayType, fCharArrayType, fBooleanArrayType, // Two-dimensional primitive arrays fByteDoubleArrayType, fShortDoubleArrayType, fIntDoubleArrayType, fLongDoubleArrayType, fFloatDoubleArrayType, fDoubleDoubleArrayType, fCharDoubleArrayType, fBooleanDoubleArrayType; /** * Creates a new test. */ public TypeTest() { super(); } /** * Init the fields that are used by this test only. */ @Override public void localSetUp() { // Get reference types fArrayType = getArrayType(); fClassType = getMainClass(); fInterfaceType = getInterfaceType(); // Get primitive types fBooleanType = (fVM.mirrorOf(true).type()); fByteType = (fVM.mirrorOf((byte) 1).type()); fCharType = (fVM.mirrorOf('a').type()); fDoubleType = (fVM.mirrorOf(12345.6789).type()); fFloatType = (fVM.mirrorOf(12345.6789f).type()); fIntegerType = (fVM.mirrorOf(12345).type()); fLongType = (fVM.mirrorOf(123456789l).type()); fShortType = (fVM.mirrorOf((short) 12345).type()); // Get one-dimensional primitive arrays fByteArrayType = getByteArrayType(); fShortArrayType = getShortArrayType(); fIntArrayType = getIntArrayType(); fLongArrayType = getLongArrayType(); fFloatArrayType = getFloatArrayType(); fDoubleArrayType = getDoubleArrayType(); fCharArrayType = getCharArrayType(); fBooleanArrayType = getBooleanArrayType(); // Get two-dimensional primitive arrays fByteDoubleArrayType = getByteDoubleArrayType(); fShortDoubleArrayType = getShortDoubleArrayType(); fIntDoubleArrayType = getIntDoubleArrayType(); fLongDoubleArrayType = getLongDoubleArrayType(); fFloatDoubleArrayType = getFloatDoubleArrayType(); fDoubleDoubleArrayType = getDoubleDoubleArrayType(); fCharDoubleArrayType = getCharDoubleArrayType(); fBooleanDoubleArrayType = getBooleanDoubleArrayType(); } /** * Run all tests and output to standard output. * @param args */ public static void main(java.lang.String[] args) { new TypeTest().runSuite(args); } /** * Gets the name of the test case. * @see junit.framework.TestCase#getName() */ @Override public String getName() { return "com.sun.jdi.Type"; } /** * Test JDI signature(). */ public void testJDISignature() { assertEquals("1", "[Ljava/lang/String;", fArrayType.signature()); assertEquals("2", "Lorg/eclipse/debug/jdi/tests/program/MainClass;", fClassType.signature()); assertEquals("3", "Lorg/eclipse/debug/jdi/tests/program/Printable;", fInterfaceType.signature()); // Primitive types assertEquals("4", "S", fShortType.signature()); assertEquals("5", "B", fByteType.signature()); assertEquals("6", "I", fIntegerType.signature()); assertEquals("7", "J", fLongType.signature()); assertEquals("8", "F", fFloatType.signature()); assertEquals("9", "D", fDoubleType.signature()); assertEquals("10", "C", fCharType.signature()); assertEquals("11", "Z", fBooleanType.signature()); // One-dimensional primitive arrays assertEquals("12", "[B", fByteArrayType.signature()); assertEquals("13", "[S", fShortArrayType.signature()); assertEquals("14", "[I", fIntArrayType.signature()); assertEquals("15", "[J", fLongArrayType.signature()); assertEquals("16", "[F", fFloatArrayType.signature()); assertEquals("17", "[D", fDoubleArrayType.signature()); assertEquals("18", "[C", fCharArrayType.signature()); assertEquals("19", "[Z", fBooleanArrayType.signature()); // Two-dimensional primitive arrays assertEquals("20", "[[B", fByteDoubleArrayType.signature()); assertEquals("21", "[[S", fShortDoubleArrayType.signature()); assertEquals("22", "[[I", fIntDoubleArrayType.signature()); assertEquals("23", "[[J", fLongDoubleArrayType.signature()); assertEquals("24", "[[F", fFloatDoubleArrayType.signature()); assertEquals("25", "[[D", fDoubleDoubleArrayType.signature()); assertEquals("26", "[[C", fCharDoubleArrayType.signature()); assertEquals("27", "[[Z", fBooleanDoubleArrayType.signature()); } /** * Test JDI typeName(). */ public void testJDITypeName() { assertEquals("1", "java.lang.String[]", fArrayType.name()); assertEquals("2", "org.eclipse.debug.jdi.tests.program.MainClass", fClassType.name()); assertEquals("3", "org.eclipse.debug.jdi.tests.program.Printable", fInterfaceType.name()); // Primitive types assertEquals("4", "byte", fByteType.name()); assertEquals("5", "short", fShortType.name()); assertEquals("6", "int", fIntegerType.name()); assertEquals("7", "long", fLongType.name()); assertEquals("8", "float", fFloatType.name()); assertEquals("9", "double", fDoubleType.name()); assertEquals("10", "char", fCharType.name()); assertEquals("11", "boolean", fBooleanType.name()); // One-dimensional primitive arrays assertEquals("12", "byte[]", fByteArrayType.name()); assertEquals("13", "short[]", fShortArrayType.name()); assertEquals("14", "int[]", fIntArrayType.name()); assertEquals("15", "long[]", fLongArrayType.name()); assertEquals("16", "float[]", fFloatArrayType.name()); assertEquals("17", "double[]", fDoubleArrayType.name()); assertEquals("18", "char[]", fCharArrayType.name()); assertEquals("19", "boolean[]", fBooleanArrayType.name()); // Two-dimensional primitive arrays assertEquals("20", "byte[][]", fByteDoubleArrayType.name()); assertEquals("21", "short[][]", fShortDoubleArrayType.name()); assertEquals("22", "int[][]", fIntDoubleArrayType.name()); assertEquals("23", "long[][]", fLongDoubleArrayType.name()); assertEquals("24", "float[][]", fFloatDoubleArrayType.name()); assertEquals("25", "double[][]", fDoubleDoubleArrayType.name()); assertEquals("26", "char[][]", fCharDoubleArrayType.name()); assertEquals("27", "boolean[][]", fBooleanDoubleArrayType.name()); } }
Markdown
UTF-8
3,699
2.96875
3
[]
no_license
# TwitterClone <p align="center"> <img src="Documentation/twitterclone-portfolio-mockup.png" width="650" title="Twittermenti App"> </p> ## Author Taylor Patterson ## Description What better way to test out your skills as a developer than to try and tackle one of the most iconic social media apps. As the app name states, TwitterClone is a replica of Twitter. I wanted to replicate Twitter to practice MVVM structural design, dive further with OOP, programmatically build every UIView, practice building a cloud database through Firebase, as well as direct messaging functionality through Firebase as well. ## Tools Used <p align="left"> <img src="https://firebase.google.com/images/brand-guidelines/logo-built_black.png" width="100" title="Twitter Developer Icon"> </p> **Firebase** - Google's answer to storing mobile data. **How I Used Twitter's API** - What can't be said already about Firebase that hasn't been stated yet? It's fast, easy to learn, and can be implemented with Apple's sign in functionality. I used Firebase's Cloud Firestore and Authentication capabilities to register new users, send and receive tweets and direct messages, as well as the link functionality. I chose Firebase because of its ease of use and how fast the cloud database is. For more info on **Firebase** click [here](https://firebase.google.com/) <p align="left"> <img src="https://devshive.tech/media/uploads/contents/1516823789563-design-patterns-for-cocoa-mvc-and-mvvm.png" width="100" title="Twitter Developer Icon"> </p> **MVVM** - A better approach to iOS Design Pattern. **How I used MVVM** - When I first started out learning iOS development, I learned all I could about MVC (the design pattern used by Apple). However, after research, discussions with another (paid) iOS developer, and just the shear realization how massive code can become in MVC or Massive View Conroller, I started to look for a better design approach to my coding architecture then came MVVM. I've wanted to use MVVM for a while now, but most of my projects have been small and MVC being fine for what I was doing. I chose to use MVVM for TwitterClone due to the size of the app and moving parts, and this way I could neatly keep each functionality separate thus resulting in cleaner and more readable code. This wasn't an easy task, and it took me a bit to get use to the design pattern, but I really like the way MVVM has made me think more about how my code looks as well as the functionality of it. Plus, it really makes you practice your OOP and POP programming fundamentals. For more info on **MVVM** click [here](https://www.raywenderlich.com/34-design-patterns-by-tutorials-mvvm) <p align="left"> <img src="https://www.rookieup.com/wp-content/uploads/2018/01/sketch-logo-light-transparent@2x.png" width="100" title="Twitter Developer Icon"> </p> **Sketch** - A dataset based on Sanders' tweet sentiment dataset. **How I used Sketch** - What I love about iOS development is you have fill the roll of a full stack developer. In one moment you're networking with APIs and creating backend functionality through CoreData or Firebase all the while keeping in mind to make the app look pretty with UI/UX elements for the user. For the "pretty" aspect, I wanted to learn a tool that was built for UI/UX design, used in the industry, and did not have a steep learning curve. Sketch has fit every need thus far. Every mockup picture on my portfolio was built with swift as well as many of the buttons, backgrounds, and screens used in my applications. Sketch is an invaluable tool that has made me look at iOS design with a much different eye. For more info on **Sketch** click [here](https://www.sketch.com/)
Shell
UTF-8
1,093
4.03125
4
[ "MIT" ]
permissive
#!/bin/sh # Checks requirements depends_on() { for i in $@; do hash $i >/dev/null 2>&1 || { echo >&2 "$i not installed. Aborting."; exit 1; } done } # Clones GitHub repo github_clone() { git clone https://github.com/$1.git $2 || exit 1; } # Clones configs clone_config() { # Checks whether ~/.vim exists if [ -d ~/.vim ]; then echo -e "The ~/.vim should be removed before installing. Aborting."; exit 1 fi # Cloning configs template and Vundle github_clone bcbcarl/ultra_vim ~/.vim github_clone gmarik/vundle ~/.vim/bundle/vundle } # Generates configs make_config() { # Installing bundles vim -u ~/.vim/vundle.vim +BundleInstall +qall 2>&1 # Backing up ~/.vimrc if [ -f ~/.vimrc ]; then TIMESTAMP=`date +%s` echo -e "~/.vimrc found." echo -e "Backing up to ~/.vimrc_$TIMESTAMP" mv ~/.vimrc ~/.vimrc_$TIMESTAMP fi # Generating ~/.vimrc cp ~/.vim/vimrc ~/.vimrc } # Installs configs and plugins install_config() { clone_config make_config echo "\nInstallation complete. Enjoy! ;-)\n" } depends_on vim git install_config
Java
UTF-8
4,688
2.703125
3
[]
no_license
package com.example.LBGManager.Model; import com.example.LBGManager.Channel; import java.util.ArrayList; import java.util.Date; import java.util.List; public class LBG { private static List<Event> events = new ArrayList<>(); private static List<Member> members = new ArrayList<>(); private static List<Task> tasks = new ArrayList<>(); private static AppMember app_user = AppMember.getInstance(); private static List<Channel> observers = new ArrayList<>(); public static void updateModel(Model model) { events = model.getEvents(); tasks = model.getTasks(); members = model.getMembers(); notifyObservers(); } public static List<Task> getUserTasks(String member_id) { List<Task> temp_tasks = new ArrayList<>(); for (Task task : tasks) { if (task.getResponsibles().contains(member_id)) { temp_tasks.add(task); } } tasks.add(new Task("AAA1","1","Courses","Aller acheter des courses au Colruyt",new Date(2020,10,31))); tasks.add(new Task("AAA2","1","Netoyage","Netoyer le local",new Date(2020,10,30))); tasks.add(new Task("AAA3","1","Netoyage","Netoyer le local",new Date(2020,10,30))); tasks.add(new Task("AAA4","1","Netoyage","Netoyer le local",new Date(2020,10,30))); tasks.add(new Task("AAA5","1","Netoyage","Netoyer le local",new Date(2020,10,30))); tasks.add(new Task("AAA6","1","Netoyage","Netoyer le local",new Date(2020,10,30))); tasks.add(new Task("AAA7","1","Netoyage","Netoyer le local",new Date(2020,10,30))); tasks.add(new Task("AAA8","1","Netoyage","Netoyer le local",new Date(2020,10,30))); tasks.add(new Task("AAA9","1","Netoyage","Netoyer le local",new Date(2020,10,30))); tasks.add(new Task("AAA10","1","Netoyage","Netoyer le local",new Date(2020,10,30))); tasks.add(new Task("AAA11","1","Netoyage","Netoyer le local",new Date(2020,10,30))); return tasks; /* List<Task> tasks = new ArrayList<>(); for (Event e : events) { tasks.addAll(e.getUserTasks(memeber_id)); } return tasks;*/ } public static Event getEventById(String id) { for (Event event : events) { if (event.getId().equals(id)) { return event; } } return null; } public static Task getTaskById(String id) { for (Task task : tasks) { if (task.getId().equals(id)) { return task; } } return null; } public static Member getMemberById(String id) { for (Member member : members) { if (member.getMember_Id().equals(id)) { return member; } } return null; } /** * Notifies every Channel objects that the state has changed */ public static void notifyObservers() { for (Channel channel : observers) { channel.stateChanged(); } } public static void addObserver(Channel channel) { observers.add(channel); } /** * This function will return every memeber id from the LBG, but the first elements are the organisers of the event * @param event_id The event identification number * @return A list containing all LBG memebers ids but the first elements are the organisers */ public static List<String> getAllMembersFromEventId(String event_id) { Event event = getEventById(event_id); List<String> members_ids = new ArrayList<>(); // First adds every member id from the event organisers members_ids.addAll(event.getOrganisers_ids()); // Then adds all the member id from the LBG for (Member member : members) { String id = member.getMember_Id(); if (!members_ids.contains(id)) { members_ids.add(id); } } return members_ids; } public static List<Event> getEvents() { List<Event> fake_temp_list = new ArrayList<>(); fake_temp_list.add(new Event("AA1","EBEC BENELUX", "Second phase", "dcouchar", new Date(21,10,2018), new Date(24, 10, 2018))); fake_temp_list.add(new Event("AA1","EBEC BENELUX", "Second phase", "dcouchar", new Date(21,10,2018), new Date(24, 10, 2018))); fake_temp_list.add(new Event("AA1","EBEC BENELUX", "Second phase", "dcouchar", new Date(21,10,2018), new Date(24, 10, 2018))); fake_temp_list.add(new Event("AA1","EBEC BENELUX", "Second phase", "dcouchar", new Date(21,10,2018), new Date(24, 10, 2018))); return fake_temp_list; } }
Markdown
UTF-8
2,733
2.703125
3
[]
no_license
# Wordpress and Magento 2 Docker setup for Google Cloud. This set of bash scripts creates the Dorel IO infrastructure which includes but is not limited to: - Docker - SQL - Storage buckets - Compute machines - Let's Encrypt - Wordpress - Magento Learn more about Google's infra: https://peering.google.com/#/infrastructure ## Core principle Within a Google project a sub-project is created which can be identified by the `dorel-io--projectname-*` prefix. All information about this setup is stored in the config storage bucket. _Note: You will have two types of projects: I. The Google Cloud project and (II) the sub-project id. You can create multiple sub-projects inside a Google Project._ _Note: This script is a tool to chain commands, not a cloud application, you need to always validate its output_ ## Getting started 1. Go to the Google Cloud console. 2. Open the terminal window. 3. Create a new machine to run the cloud tool: `$ gcloud compute --project "dorel-io-dev" instances create "gcloud-terminal" --zone "europe-west1-c" --machine-type "f1-micro" --subnet "default" --maintenance-policy "MIGRATE" --scopes default="https://www.googleapis.com/auth/cloud-platform" --tags "https-server" --image "/ubuntu-os-cloud/ubuntu-1604-xenial-v20161115" --boot-disk-size "10" --boot-disk-type "pd-standard" --boot-disk-device-name "gcloud-terminal"` 4. SSH into the new machine and go to the home dir `$ cd ~` 5. Run `$ sudo su` 6. Download the core bash file `$ wget https://raw.githubusercontent.com/dorel/google-cloud-container-setup/develop/dorelcloudtool.sh` 7. Set permissions `$ chmod +x ./dorelcloudtool.sh` 8. Run `$ ./dorelcloudtool.sh` 9. First `gcloud` will run, make sure to login with your Google Cloud credentials 10. When running for the first time on a new machine, make sure to run the Route 53 Authentication command! _Note I: to use the tool from another branche change 'master' into -for example- 'develop' in the download url_ _Note II: All debug info will be stored in: `/var/log/dorel/debug.log`_ ## Starting the software 1. Fill in the Google Cloud project id. 2. Select the Github branch that you want to work from (this is the installation bash, docker and config files repo). 3. Select what you want to do. After a process is done, the software will terminate. ## Creating a new Docker project (Option 5) When creating a new sub project (including general SQL and bucket setup) you need to run this command. 1. Select the instances you would like to generate the templates for. 2. Save the name of the project. This is always in the `xxx-yyy` format. 3. Enter the SQL root password. _Note: this is the only config setting which -for security reasons- is not saved in the config file_.
Python
UTF-8
3,046
3.296875
3
[]
no_license
import pandas import numpy as np '''def compute_error(thetaone, thetazero, points): error = 0 n = range(len(points)) thetaone = float(thetaone) thetazero = float(thetazero) for i in (0 ,n ): point = points[i] error += (point[1] - (thetaone * point[0] + thetazero)) ** 2 return error / ((float(len(points)))*2)''' def compute_error(theta1, theta0, data): total_error = 0 for i in range(0, len(data)): x = data[i, 0] y = data[i, 1] total_error = total_error + (y - ((theta1 * x) + theta0)) ** 2 return total_error/float(len(data)) '''def compute_erroris(thetaone, thetazero, points): error = 0 n = range(len(points)) thetaone = float(thetaone) thetazero = float(thetazero) for i in : point = points[i] error += (point[1] - (thetaone * point[0] + thetazero)) ** 2 return error / ((float(len(points)))*2)''' def main(): alpha = float(input('Enter alpha:')) thetazero = float(input('Enter theta zero :')) thetaone = float(input('Enter theta one :')) data = pandas.read_csv('pavan.csv',header=None) data2 = data.as_matrix() print(data2) trainingset = data2[0:3] print('trainingset',trainingset) #trainigsettarget = data2.target[0:3] testset = data2[3:5] print('testset',testset) #testsettarget = data2.target[4:] #Computing Initial Error initial_error = compute_error(thetaone,thetazero,trainingset) print('initial error=',initial_error) print('aaa',trainingset[0][0]) print('bbb',trainingset[1][0]) #Learning the model for i in range(len(trainingset)): thetaone_gradient = 0 thetazero_gradient = 0 n = (len(trainingset)) print('aaaaa',n) thetazero_sum = 0 thetaone_sum = 0 print('abc',type(thetazero_sum)) print(type(thetaone_sum)) for j in range(0,n): thetaone_sum += int((-1 * trainingset[j][0] * (trainingset[j][1] -(thetaone * trainingset[j][0] + thetazero)))) thetazero_sum += int((-1 * (trainingset[j][1] - (thetaone * trainingset[j][0] + thetazero)))) print(thetaone_sum) print(thetazero_sum) thetaone_gradient = ((2 / n) * thetaone_sum) thetazero_gradient = ((2 / n) * thetazero_sum) print('thetaone',thetaone_gradient) print('thetazero',thetazero_gradient) thetaone = ( thetaone - (alpha * thetaone_gradient)) thetazero = ( thetazero - (alpha * thetazero_gradient)) print( 'new value of thetaone = ',thetaone, ' and thetazero =', thetazero) #Computing Test Case print('aaa',testset[0][0]) print('bbb',testset[1][0]) final_error = compute_error(thetaone,thetazero,testset) a = final_error - initial_error print ('value of jtheta',a ) '''if(a>0.001): main() else: exit(0)''' print('Final Error = ',final_error ) main()
Shell
UTF-8
242
2.65625
3
[]
no_license
#!/bin/bash # First setup if [[ ! -e /data/db ]]; then mkdir -p /data/db fi if [[ ! -e /data/.alreadyrun ]]; then touch /data/.alreadyrun /scripts/firstRun.sh else # start by marathon after shutdown /scripts/runAsSlave.sh fi
Java
UTF-8
2,056
2.53125
3
[]
no_license
/* * Created on 22-mrt-2005 * */ package nl.fountain.xelem.ztest; import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import nl.fountain.xelem.Area; import nl.fountain.xelem.excel.Row; import nl.fountain.xelem.excel.Worksheet; import nl.fountain.xelem.lex.DefaultExcelReaderListener; import nl.fountain.xelem.lex.ExcelReader; import org.xml.sax.SAXException; /** * */ public class Test { public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException { new Test().listen(); } private void simple() throws ParserConfigurationException, IOException, SAXException { ExcelReader reader = new ExcelReader(); /*Workbook wb = */reader.getWorkbook("D:/test/big1879.xml"); } private void listen() throws ParserConfigurationException, SAXException, IOException { ExcelReader reader = new ExcelReader(); //reader.setReadArea(new Area("E11:M16")); reader.addExcelReaderListener(new DefaultExcelReaderListener() { public void setRow(int sheetIndex, String sheetName, Row row) { // process row and/or it's cells System.out.println(sheetIndex + " \t" + sheetName + " \t" + row.getIndex()); } }); reader.read("testsuitefiles/ReaderTest/reader.xml"); } class SwappingAreaListener extends DefaultExcelReaderListener { private ExcelReader reader; public SwappingAreaListener(ExcelReader reader) { this.reader = reader; } // override method in DefaultExcelReaderListener public void startWorksheet(int sheetIndex, Worksheet sheet) { switch (sheetIndex) { case 1: reader.setReadArea(new Area("A1:C6")); break; case 2: reader.setReadArea(new Area("G11:G11")); break; default: reader.clearReadArea(); } } } }
PHP
UTF-8
1,365
2.765625
3
[ "MIT" ]
permissive
<?php namespace Acme\LoginBundle\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity */ class Person { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue * * @var integer $id */ private $id; /** * @ORM\Column(type="datetime") * * @var DateTime $createdAt */ private $createdAt; /** * @ORM\Column(type="string") * * @var string username */ private $username; /** * Gets the id. * * @return string The id */ public function getId() { return $this->id; } /** * Gets an object representing the date and time the user was created. * * @return DateTime A DateTime object */ public function getCreatedAt() { return $this->createdAt; } /** * Gets the username. * * @return string The username. */ public function getUsername() { return $this->username; } /** * Sets the username. * * @param string $value The username. */ public function setUsername($value) { $this->username = $value; } /** * Constructs a new instance of User */ public function __construct() { $this->createdAt = new \DateTime(); } }
Markdown
UTF-8
2,294
2.71875
3
[ "Apache-2.0" ]
permissive
# CHANEGLOG ## v1.4.0 Some of the major upgrades/changes: * Update to React 16.3 and use of `Fragment` component for menu items. * Upgraded testing framework `enzyme` and fixed failing `Nav` tests. * Polished and reformatted code. The rest of changes can be found [here](https://github.com/DalerAsrorov/componofy/projects/8) ### v1.3.0 Some of the major features/changes are: * Loader message if no playlists found. * Fixed some UI responsiveness bugs and improved render time of DIalog. * Show suggested custom playlist based on user's preferences. * Upgraded Material UI to beta 38. To see the full list checkout [v1.3 Release Project Board](https://github.com/DalerAsrorov/componofy/projects/7). ### v1.2.0 * In this release experience for showing a particular playlist has been improved - the user can decide whether to expand the playlist tracklist fully or not. * Search and footer `sticky` position now works for Safari and other `webkit` type of browsers. * Number of playlist tracks indicated on the right. * Number of added tracks from playlist shows up to the left of the badge described above. View more in the [v1.2.0 release project board](https://github.com/DalerAsrorov/componofy/projects/6). ### v1.1.0 * Major feature: ability to reorder tracks in a playlist owned by the user. * Also includes fixes like: * Fetch all playlist tracks with no limit (before it was <= 100). * New search resets the offset properly. It means that on new search, the first 10 playlists will not be missed. * Show loader until all playlist tracks are fetched. * If playlists has a lot of playlists, the max height will be applied to not make the user scroll the page. * The rest of thea features/fixes can be found in [v1.1.0 Feature Board](https://github.com/DalerAsrorov/componofy/projects/5). ### v1.0.1 * Major feature: ability to merge public/private/personal playlists into an existing user's playlist. * The rest of the features can be found in [v1.0.1 Feature Board](https://github.com/DalerAsrorov/componofy/projects/3). ### v1.0.0 * The first complete build of the project. * Contains set of features implemented in [Project Alpha](https://github.com/DalerAsrorov/componofy/projects/1) and [Project Beta](https://github.com/DalerAsrorov/componofy/projects/2).
Python
UTF-8
739
2.734375
3
[]
no_license
import csv import json import pandas as pd # conteudo[i].municipio.id # features.properties.codearea malha = open('malha-dos-municipios-pi.json') municipios = open('id-municipios-pi.json') vacinados = open('vacinados.csv', 'rb') # 1 - Cria o arquivo f = open('p_vacinados.csv', 'w', newline='', encoding='utf-8') # 2. cria o objeto de gravação w = csv.writer(f) data_municipios = json.loads(municipios.read()) data_vacinados = pd.read_csv('vacinados.csv', delim_whitespace=True) w.writerow(['codarea', 'municipio']) # 3. grava as linhas for i in range(len(data_municipios)-1): w.writerow([data_municipios[i]['municipio']['id'], data_municipios[i]['municipio']['nome']]) malha.close() municipios.close() f.close()
PHP
UTF-8
11,612
2.546875
3
[]
no_license
<?php include 'connection.php'; # Checks if a value exists in a column function thereExists($to_be_checked,$table,$col){ $query = "SELECT ".$col." FROM ".$table.""; $run = mysqli_query($GLOBALS['link'],$query); for($i = 0 ; $row = mysqli_fetch_assoc($run) ; $i++){ if ( $to_be_checked == $row[$col] ) { return 1; } else continue; } return 0; } #Retirver function get($id,$what){ switch ($what) { case 'tutor': $r = mysqli_query($GLOBALS['link'],"SELECT * FROM `tutors` WHERE `id` = '".$id."'"); if (mysqli_num_rows($r) < 1) return -1; else return mysqli_fetch_assoc($r); break; case 'comment': $r = mysqli_query($GLOBALS['link'],"SELECT * FROM `comments` WHERE `id` = '".$id."'"); if (mysqli_num_rows($r) < 1) return -1; else return mysqli_fetch_assoc($r); break; case 'user': $q = "SELECT * FROM `users` WHERE `id` = '".$id."'"; $r = mysqli_query($GLOBALS['link'],$q); if (mysqli_num_rows($r) < 1) return -1; else return mysqli_fetch_assoc($r); break; case 'report': $r = mysqli_query($GLOBALS['link'],"SELECT * FROM `report` WHERE `id` = '".$id."'"); if (mysqli_num_rows($r) < 1) return -1; else return mysqli_fetch_assoc($r); break; default: return -1; break; } } # Displays the tutor card function displayCard($id,$name,$image,$gender,$price,$rating,$subs,$is_verified){ if ($is_verified){ echo ' <div class="col-md-3 tut-card"> <a href="detail.php?id='.$id.'" class="tut-link"> <div class="row no-gutters" style="padding: 1rem 0;"> <div class="img-cont"> <figure> <img style="height:200px;width:100%" src="'.$image.'" alt=""> <figcaption><center>'.$name.'</center></figcaption> </figure> <i class="fas fa-check-circle"></i> </div> <div class="col-md-12" style="outline: 1px solid #80808069;outline-offset: 5px;"> <div class="row justify-content-around gender-field no-gutters info-row"> <div class="col-6"> Gender </div> <div class="col-6"> '.$gender.' </div> </div> <div class="row justify-content-around price-field no-gutters info-row"> <div class="col-6"> Price </div> <div class="col-6"> '.$price.' </div> </div> <div class="row justify-content-around rating-field no-gutters info-row"> <div class="col-6"> Rating </div> <div class="col-6"> '.$rating.' </div> </div> <div class="row justify-content-around topic-field no-gutters "> <div class="col-4"> Tutors </div> <div class="col-8" style="text-overflow: ellipsis;overflow: hidden;white-space: nowrap;"> '.$subs.' </div> </div> </div> </div> </a> </div>';} else{ echo ' <div class="col-md-3 tut-card"> <a href="detail.php?id='.$id.'" class="tut-link"> <div class="row no-gutters" style="padding: 1rem 0;"> <div class="img-cont"> <figure> <img style="height:200px;width:100%" src="'.$image.'" alt=""> <figcaption><center>'.$name.'</center></figcaption> </figure> </div> <div class="col-md-12" style="outline: 1px solid #80808069;outline-offset: 5px;"> <div class="row justify-content-around gender-field no-gutters info-row"> <div class="col-6"> Gender </div> <div class="col-6"> '.$gender.' </div> </div> <div class="row justify-content-around price-field no-gutters info-row"> <div class="col-6"> Price </div> <div class="col-6"> '.$price.' </div> </div> <div class="row justify-content-around rating-field no-gutters info-row"> <div class="col-6"> Rating </div> <div class="col-6"> '.$rating.' </div> </div> <div class="row justify-content-around topic-field no-gutters "> <div class="col-4"> Tutors </div> <div class="col-8" style="text-overflow: ellipsis;overflow: hidden;white-space: nowrap;"> '.$subs.' </div> </div> </div> </div> </a> </div>'; } } # Display the tutor card by id function displayCard_by_id($id){ $tutor = mysqli_fetch_assoc(mysqli_query($GLOBALS['link'],"SELECT * FROM `tutors` WHERE `id` = '".$id."'")); if ( $tutor['gender'] ) { $tutor['gender'] = "Male"; } else { $tutor['gender'] = "Female"; } displayCard($tutor['id'],$tutor['name'],$tutor['photo'],$tutor['gender'],$tutor['price'],$tutor['rating'],mashedSubject($tutor['id']),$tutor['verified']); } # Mashes the subjects into one string function mashedSubject($id) { $stringed = ""; $r = mysqli_query($GLOBALS['link'],"SELECT * FROM subjects WHERE tutor_id = {$id}"); while($row = mysqli_fetch_assoc($r)){ $stringed = $stringed.$row['subject']."^"; } return str_replace("^"," ,",ucwords($stringed)); } # Checks if any cookies are set function is_a_cookie_set(){ if (count($_COOKIE) > 0){ return true; } else{ return false; } } # Uploader function Upload($name,$size,$temp){ $Target_dir = "../Uploads/"; $target_file = $Target_dir . $name; $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); if ( $size < 2000000 && $size != 0 ) { if ( getimagesize($temp) ) { if ($imageFileType == "png" || $imageFileType == "jpg" || $imageFileType == "jpeg" || $imageFileType == "ico"){ if(move_uploaded_file($temp,$target_file)){ $uploadok = true; } } else{ echo 'Unsupported file type.'; } } } else{ echo 'Size too large..'.$size / 100000 .'MB'; } if ($uploadok){ return true; } } # Suffixer function add_suffix($num) { if (!in_array(($num % 100),array(11,12,13))){ switch ($num % 10) { // Handle 1st, 2nd, 3rd case 1: return $num.'st'; case 2: return $num.'nd'; case 3: return $num.'rd'; } } return $num.'th'; } # Checks if subject exists function subjExists($sub,$id){ $r = mysqli_query($GLOBALS['link'],"SELECT * FROM `subjects` WHERE `tutor_id` = '".$id."' "); while($row = mysqli_fetch_assoc($r)){ if ( $row['subject'] == $sub) { return true; } else continue; } return false; } # Calculates the age function ageCalc($y){ $m = '01'; $d = '01'; $bday_string = $y.'-'.$m.'-'.$d; $bday = new Datetime(date(''.$bday_string)); $today = new Datetime(date('y-m-d')); $diff = date_diff($today,$bday); return $diff->y; } # Breaks strings up function frag($str){ $arr = explode("-",$str); return $arr; } # Remove all cookies function KillCookies(){ if (isset($_SERVER['HTTP_COOKIE'])) { $cookies = explode(';', $_SERVER['HTTP_COOKIE']); foreach($cookies as $cookie) { $parts = explode('=', $cookie); $name = trim($parts[0]); setcookie($name, '', time()-1000); setcookie($name, '', time()-1000, '/'); } } } # Cleans the url function CleanQuery($str){ $arr = explode('&',$str); unset($arr[ count($arr) - 1]); return implode('&',$arr); } # Trabslates age to date function AgetoDate($age){ $today = new Datetime(date('Y')); $today_int = intval($today->format('Y')); return $today_int - $age; } # Getting ip addresses function getUserIpAddr(){ if(!empty($_SERVER['HTTP_CLIENT_IP'])){ //ip from share internet $ip = $_SERVER['HTTP_CLIENT_IP']; }elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){ //ip pass from proxy $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; }else{ $ip = $_SERVER['REMOTE_ADDR']; } return $ip; } ?>
Java
UTF-8
5,068
2.140625
2
[]
no_license
package com.calculator.controller; import com.calculator.domain.PriceComponent; import com.calculator.domain.PurchaseOrder; import com.calculator.service.PriceEngineService; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.beans.BeanUtils; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.*; import static org.springframework.test.util.ReflectionTestUtils.setField; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.*; @ExtendWith(SpringExtension.class) public class PriceEngineControllerTest { private static final String PATH_PRICE_LIST = "/calculator/prices"; private static final String PATH_GENERATE = "/calculator/generate"; @Mock PriceEngineService priceEngineService; @InjectMocks PriceEngineController controller; private MockMvc mockMvc; private ObjectMapper objectMapper; @BeforeEach void setup() { objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter(); jackson2HttpMessageConverter.setObjectMapper(objectMapper); mockMvc = MockMvcBuilders.standaloneSetup(controller).setMessageConverters(jackson2HttpMessageConverter).build(); } @Test void testGetPriceList() throws Exception { final List<PriceComponent> priceList = new ArrayList<>(); priceList.add(new PriceComponent(1,1,2.0)); priceList.add(new PriceComponent(2,2,2.0)); priceList.add(new PriceComponent(3,3,3.0)); priceList.add(new PriceComponent(4,4,4.0)); when(priceEngineService.getPriceList(anyInt())).thenReturn(priceList); final MvcResult mvcResult = mockMvc .perform(get(PATH_PRICE_LIST).contentType(MediaType.APPLICATION_JSON_VALUE) .param("product_id", "1")) .andExpect(status().isOk()) .andReturn(); final String responseString = mvcResult.getResponse().getContentAsString(); verify(priceEngineService, times(1)).getPriceList(anyInt()); assertNotNull(responseString); } @Test void testGenerateFinalAmount() throws Exception { final String purchaseOrder = "{\n" + " \"productId\":2,\n" + " \"cartonOrder\":false,\n" + " \"units\":39\n" + "}"; when(priceEngineService.calculateAmount(any(PurchaseOrder.class))).thenReturn(2344.75); final MvcResult mvcResult = mockMvc .perform(post(PATH_GENERATE).contentType(MediaType.APPLICATION_JSON_VALUE) .content(purchaseOrder)) .andExpect(status().isOk()) .andReturn(); final String responseString = mvcResult.getResponse().getContentAsString(); verify(priceEngineService, times(1)).calculateAmount(any(PurchaseOrder.class)); assertNotNull(responseString); } @Test void testGenerateFinalAmountInvalidPurchaseOrder() throws Exception { final String purchaseOrder = "{\n" + " \"producctId\":2,\n" + " \"cartonOrder\":false,\n" + " \"units\":39\n" + "}"; when(priceEngineService.calculateAmount(any(PurchaseOrder.class))).thenReturn(2344.75); final MvcResult mvcResult = mockMvc .perform(post(PATH_GENERATE).contentType(MediaType.APPLICATION_JSON_VALUE) .content(purchaseOrder)) .andExpect(status().isBadRequest()) .andReturn(); } private PurchaseOrder mockPurchaseOrder(int productId, boolean cartonOrder, int units) { final PurchaseOrder purchaseOrder = BeanUtils.instantiateClass(PurchaseOrder.class); setField(purchaseOrder, "productId", productId); setField(purchaseOrder, "cartonOrder", cartonOrder); setField(purchaseOrder, "units", units); return purchaseOrder; } }
Java
UTF-8
3,289
2.265625
2
[ "MIT", "Apache-2.0" ]
permissive
/*- * #%L * anchor-plugin-image * %% * Copyright (C) 2010 - 2020 Owen Feehan, ETH Zurich, University of Zurich, Hoffmann-La Roche * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * #L% */ package org.anchoranalysis.plugin.image.bean.blur; import lombok.Getter; import lombok.Setter; import org.anchoranalysis.bean.AnchorBean; import org.anchoranalysis.bean.annotation.BeanField; import org.anchoranalysis.bean.annotation.Positive; import org.anchoranalysis.core.exception.OperationFailedException; import org.anchoranalysis.core.log.MessageLogger; import org.anchoranalysis.image.core.dimensions.Dimensions; import org.anchoranalysis.image.voxel.VoxelsUntyped; /** * A method for applying blurring to an image * * @author Owen Feehan */ public abstract class BlurStrategy extends AnchorBean<BlurStrategy> { // START BEAN PROPERTIES @BeanField @Positive @Getter @Setter private double sigma = 3; @BeanField @Getter @Setter private boolean sigmaInMeters = false; // Treats sigma if it's microns // END BEAN PROPERTIES public abstract void blur(VoxelsUntyped voxels, Dimensions dimensions, MessageLogger logger) throws OperationFailedException; protected double calculateSigma(Dimensions dimensions, MessageLogger logger) throws OperationFailedException { double sigmaToUse = sigma; if (sigmaInMeters) { if (dimensions.unitConvert().isPresent()) { // Then we reconcile our sigma in microns against the Pixel Size XY (Z is taken care // of // later) sigmaToUse = dimensions.unitConvert().get().fromPhysicalDistance(sigma); // NOSONAR logger.logFormatted("Converted sigmaInMeters=%f into sigma=%f", sigma, sigmaToUse); } else { throw new OperationFailedException( "Sigma is specified in meters, but no image-resolution is present"); } } if (sigmaToUse > dimensions.x() || sigmaToUse > dimensions.y()) { throw new OperationFailedException( "The calculated sigma is FAR TOO LARGE. It is larger than the entire channel it is applied to"); } return sigmaToUse; } }
Swift
UTF-8
562
2.671875
3
[]
no_license
// // URLSchemas.swift // Base-Project // // Created by Mojtaba Al Mousawi on 9/19/18. // Copyright © 2018 Tedmob. All rights reserved. // import Foundation struct URLSchemas{ enum Browsers : String{ case securedChrome = "googlechromes://" case notSecuredChrome = "googlechrome://" case securedFireFox = "firefox://open-url?url=https://" case notSecuredFireFox = "firefox://open-url?url=http://" case securedOpera = "opera://open-url?url=https://" case notSecuredOpera = "opera://open-url?url=http://" } }
Java
UTF-8
131
2.265625
2
[]
no_license
package com.book.JPRGerbertShildt.example.patterns.structural.composite.composite3; public interface Shape { void draw(); }
Python
UTF-8
1,264
2.765625
3
[ "Beerware" ]
permissive
import datetime import json import os class Recorder: def __init__(self, folder, name): self.folder = folder self.name = name self.paused = False self.f = None self.write_number = 0 self.new() def close_file(self): if self.f: self.f.seek(-1, os.SEEK_END) self.f.truncate() self.f.write(bytes('}}', 'utf8')) def write(self, datum): if not self.paused and self.f: dat = '\"' + str(self.write_number) + '\":' dat += json.dumps(datum) dat += ',' self.f.write(bytes(dat, 'utf8')) self.write_number += 1 # RPC Calls #def run(self, cmd): # return getattr(self, cmd)() def new(self): date = datetime.datetime.now() fid = date.strftime(self.folder + '%Y-%m-%d-%H-%M-%S') + \ '_' + self.name + '.json' self.f = open(fid, 'wb') self.f.write(bytes('{', 'utf8')) return 'File opened' #def start(self): # self.paused = False # return 'Recording started' #def pause(self): # self.paused = True # return 'Recording Paused' #def ping(self): # return 'Recorder ready.'
TypeScript
UTF-8
533
2.78125
3
[]
no_license
import {AbstractPackager} from "../AbstractPackager"; import {StringPackage} from "../package/StringPackage"; import {Packager} from "../context/annotations/Packager"; @Packager export class StringPackager extends AbstractPackager<string, StringPackage> { public unpack(pkg: StringPackage): string { return pkg.v; } public matchUnpacked(value: unknown): value is string { return typeof value === "string"; } public packageId(): number { return 2; } public toPackedValue(value: string): string { return value; } }
Java
UTF-8
1,528
2.234375
2
[]
no_license
package controle; import java.io.Serializable; import java.util.List; import javax.faces.view.ViewScoped; import javax.inject.Inject; import javax.inject.Named; import model.Cargo; import repository.Cargos; import util.jsf.FacesUtil; import filter.CargoFilter; @Named @ViewScoped public class PesquisaCargoBean implements Serializable { private static final long serialVersionUID = 1L; @Inject private Cargos cargos; private CargoFilter filtro; private List<Cargo> cargoFiltrados; private Cargo cargoSelecionado; public PesquisaCargoBean() { filtro = new CargoFilter(); }; public void pesquisar(){ cargoFiltrados = cargos.filtrados(filtro); System.out.println(" deposi de filtradas"); } public void excluir(){ cargos.remover(cargoSelecionado); cargoFiltrados.remove(cargoSelecionado); FacesUtil.addInfoMessage("Cargo " + cargoSelecionado.getCargo() + "excluido."); } public Cargos getCargos() { return cargos; } public void setCargos(Cargos cargos) { this.cargos = cargos; } public CargoFilter getFiltro() { return filtro; } public void setFiltro(CargoFilter filtro) { this.filtro = filtro; } public List<Cargo> getCargoFiltrados() { return cargoFiltrados; } public void setCargoFiltrados(List<Cargo> cargoFiltrados) { this.cargoFiltrados = cargoFiltrados; } public Cargo getCargoSelecionado() { return cargoSelecionado; } public void setCargoSelecionado(Cargo cargoSelecionado) { this.cargoSelecionado = cargoSelecionado; } }
Java
WINDOWS-1255
2,201
2.890625
3
[]
no_license
package geometries; import static primitives.Util.*; import primitives.*; import java.util.List; public class Plane extends Geometry { private Point3D p; private Vector vNormal; // ***************** Constructors ********************** // public Plane(Point3D p, Vector v) { this.p =new Point3D(p); this.vNormal = new Vector(v); } public Plane(Point3D p1,Point3D p2,Point3D p3) { this.p =new Point3D(p1); Vector v1=p1.subtract(p2); Vector v2=p1.subtract(p3); this.vNormal=v1.crossProduct(v2).normalize(); } public Plane(Color emissionLight, Material material, Point3D p1, Point3D p2, Point3D p3) { super(emissionLight, material); p = new Point3D(p1); Vector U = new Vector(p1.subtract(p2)); Vector V = new Vector(p1.subtract(p3)); Vector N = U.crossProduct(V); N.normalize(); vNormal = N; // _normal = N.scale(-1); } public Plane(Color emissionLight, Point3D p1, Point3D p2, Point3D p3) { this(emissionLight, new Material(0, 0, 0), p1, p2, p3); } // ***************** Getter********************** // public Point3D getP() { return p; } public Vector getNormal() { return vNormal; } // ***************** Administration ******************** // @Override public String toString() { return "Plane [point=" + p + ", Normal=" +vNormal + "]"; } public Vector getNormal (Point3D p) { return this.getNormal(); } @Override public List<GeoPoint> findIntsersections (Ray ray)// { Vector p0Q; try { p0Q = p.subtract(ray.get_Point()); } catch (IllegalArgumentException e) { return null; // ray starts from point Q - no intersections } double nv = vNormal.dotProduct(ray.get_direction()); if (isZero(nv)) // ray is parallel to the plane - no intersections return null; double t = alignZero(vNormal.dotProduct(p0Q) / nv); if (t <= 0) { return null; } GeoPoint geo = new GeoPoint(this, ray.getTargetPoint(t)); return List.of(geo); } }
PHP
UTF-8
8,230
2.515625
3
[]
no_license
<?php require_once "db/db_handle.php"; require_once "includes/layout2.php"; $location= urlencode($_SERVER['REQUEST_URI']); if (isset($_SESSION['id']) == false){ header ("Location: login.php?location=$location"); } ?> <title>My favourite</title> <?php if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; }; $start_from = ($page-1) * 6; $query3 = "SELECT i.*, m.*, f.*, count(*) AS num FROM offers i JOIN users m ON m.id = i.member_id JOIN favourite f ON i.id = f.offer_id WHERE f.member_id = :session_id"; $db -> query($query3, array('session_id' => $_SESSION['id'] )); $info3 = $db -> fetch(); if ($info3['num'] == '0'){ echo " <div class='container'> <div class='alert alert-danger'> <a href='#' class='close' data-dismiss='alert'>&times;</a> <strong>Sorry!</strong> No property has been added to your favourite list. </div> </div>"; } $sql = "SELECT i.*, m.*, f.*, i.id AS id_count, FORMAT(price, 0) AS price FROM offers i JOIN users m ON m.id = i.member_id JOIN favourite f ON i.id = f.offer_id WHERE f.member_id = :session_id ORDER BY f.offer_id ASC LIMIT $start_from, 6"; echo "<div class='row'> <div class='container'> <div class='col-xs-12 col-sm-12 col-md-12'> "; foreach ($db->query($sql, array('session_id' => $_SESSION['id'])) AS $result) { $newPrice = str_replace(".", ",", $result['price']); $view_photo = "SELECT i.*, p.* FROM offers i JOIN photos p ON i.id = p.photo_id WHERE i.id = :offer_id LIMIT 1 "; $myDate = date('F j, Y g:i a', strtotime($result['date'])); $rest = preg_replace('/\s+?(\S+)?$/', '', substr($result['description'], 0, 91)); if (isset($_SESSION['id']) != false){ $param_fav = array( 'session_id' => $_SESSION['id'], 'offer_id' => $result['id_count'] ); $sql_fav= "SELECT COUNT(*) AS num FROM favourite WHERE member_id= :session_id AND offer_id = :offer_id"; $db->query($sql_fav, $param_fav); $info_fav = $db->fetch(); if ($info_fav['num'] == '1') { // if the user is already a friend echo "<div class='hide' id='status'>Drop from fav</div>"; $follow_btn = "<span class='btn btn-success btn-sm following' data-clique_id='{$result['id_count']}' data-adder_id='{$_SESSION['id']}'>Drop from fav</span>"; }else { // if the user is NOT following, show follow button echo "<div class='hide' id='status'>Add to fav</div>"; $follow_btn = "<span class='btn btn-success btn-sm following' id='{$result['id_count']}'>Add to fav</span>"; } } echo " <div class='col-xs-12 col-sm-6 col-md-6' > <div class='myfav'> <div class='row'> <div class='col-md-4'> "; foreach ($db->query($view_photo, array( 'offer_id' => $result['id_count'])) AS $result2){ echo " <img src='properties/{$result2['photo']}' class='img-responsive' width = '300px' height ='' style=' '/>"; } echo" </div> <div class='col-md-8'> <div class='user_class col-md-12'> <span style=''> <i class='fa fa-university icon_color home_pad' style=''></i> {$result['school']}</br> <i class='fa fa-home icon_color home_pad_2' style=''></i> <span class='home_pad_3'>{$result['accommodation']}</span></br> "; if ($result['location'] != ''){ echo "<i class='fa fa-map-marker icon_color home_pad_4 style=''></i> {$result['location']}</br>"; } echo " <i class='fa fa-money icon_color home_pad_5' style=''></i> <strong>&#x20a6;$newPrice </strong></span> </div> <div class='user_class col-md-12'> <div class='row'> <div class='col-md-12'>"; if (isset($_SESSION['id']) != false){ echo $follow_btn; }else{ $follow_btn_1 = "<span class='btn btn-success following_2' data-toggle='modal' data-target='#{$result['id_count']}'>Add to Fav</span>"; echo $follow_btn_1; echo" <div class='modal fade' id='{$result['id_count']}' tabindex='-1' role='dialog' aria-labelledby='myModalLabel' aria-hidden='true'> <div class='modal-dialog'> <div class='modal-content'> <div class='modal-body'> <p class='text-center follow_btn_p'><a href='login.php?location=$location' class='follow_btn_a'>You must login to use this feature. Click to login</a></p> </div> <div class='modal-footer'> <button type='button' class='btn btn-danger' data-dismiss='modal'>Cancel</button> </div> </div> </div> </div>"; } echo " <div class='pull-right' ><a href='readmore.php?id={$result['id_count']}' class='btn btn-success btn-sm btn' style=''>Details </a></div> <!--Share property on social media- Facebook--> </br></br> <div class=''> <strong>Share this property on</strong>: </br> <a href='https://www.facebook.com/sharer/sharer.php?u=www.offcampus.com/readmore.php?id={$result['id_count']}' target='_blank' style='color:white;'><i class='fa fa-facebook' style='background-color: #4060A5; padding: .5em .50em;'></i></a> <a href='https://twitter.com/share?url=www.offcampus.com/readmore.php?id={$result['id_count']}' target='_blank' style='color:white;'><i class='fa fa-twitter' style='background-color: #55acee; padding: .5em .50em;'></i></a> <a href='whatsapp://send?text={$result['accommodation']} offcampus apartment at {$result['school']}. Click on the link for more details www.offcampus.com/readmore.php?id={$result['id_count']} or call 08063321043' style='color:white;' data-action='share/whatsapp/share'><i class='fa fa-whatsapp' style='background-color: #25D366; padding: .5em .50em;'></i></a> </div> <!--Sharing ends--> </div></div> </br> </div> </div> </div> </div> </div> "; } echo " </div></div></div>"; //Pagination continues $sql2 = "SELECT COUNT(id) FROM favourite WHERE member_id = :id"; $rs_result = $db-> query($sql2, array('id' => $_SESSION['id'])); $row = $rs_result->fetch(); $total_records = $row[0]; $total_pages = ceil($total_records / 6); echo " <div class='col-md-12 text-center'> <ul class='pagination pag'>"; if ($total_pages != 1){ for ($i=1; $i<=$total_pages; $i++) { if ($page == $i) echo "<li class='active' >"; else echo "<li>"; echo "<a href='myfav.php?page=$i' >$i</a></li>"; }; } echo "</ul></div>"; //Pagination stops ?>
Markdown
UTF-8
2,260
2.96875
3
[]
no_license
## The Naming Algorithm 1. Is the function a test? -> `test_<entity>_<behavior>`. 1. Does the function has a @property decorator? -> don’t use a verb in the function name. 1. Does the function use a disk or a network: 1. to store data? -> `save_to`, `send`, `write_to` 1. to receive data? -> fetch, load, read 1. Does the function output any data? -> `print`, `output` 1. Returns boolean value? -> `is_`, `has_/have_`, `can_`, `check_if_<entity>_<characteristic>` 1. Aggregates data? -> `calculate`, `extract`, `analyze` 1. Put data from one form to another: 1. Creates a single meaningful object? -> `create` 1. Fills an existing object with data? -> `initialize`, `configure` 1. Clean raw data? -> `clean` 1. Receive a string as input? -> `parse` 1. Return a string as output? -> `render` 1. Return an iterator as output? -> `iter` 1. Mutates its arguments or some global state? -> `update`, `mutate`, `add`, `remove`, `insert`, `set` 1. Return a list of errors? -> `validate` 1. Checks data items recursively? -> `walk` 1. Finds appropriate item in data? -> `find`, `search`, `match` 1. Transform data type? -> `<sth>_to_<sth_else>` 1. None of the above, but still works with data? -> Check one of those: `morph`, `compose`, `prepare`, `extract`, `generate`, `initialize`, `filter`, `map`, `aggregate`, `export`, `import`, `normalize`, `calculate`. ## Модели БД - Название модели пишется в единственном числе: User, UserAnswer - Название таблицы, если оно задается вручную, пишется во множественном числе в underscore: users, user_answers. - Поля модели и колонки в таблице пишутся в underscore: login, first_name. - Поля типа boolean начинаются с is_: is_admin, is_hidden. - Поля типов DATETIME заканчиваются на _at: created_at, updated_at. - Поля типов DATE заканчиваются на _date: connect_date, end_date. ### The Blacklist `get`, `run`, `process`, `make`, `handle`, `do`, `main`, `compare`. [Source](https://melevir.medium.com/python-functions-naming-the-algorithm-74320a18278d)
JavaScript
UTF-8
2,985
2.625
3
[ "MIT" ]
permissive
var sys = require("sys"), http = require("http"), url = require("url"), path = require("path"), fs = require("fs"), events = require("events"); function load_static(uri, response) { var filename = path.join(process.cwd(), uri); fs.exists(filename, function(exists) { if(!exists) { response.writeHead(404, {"Content-Type": "text/plain"}); response.write("404 Not Found\n"); response.end(); return; } fs.readFile(filename, "binary", function(err, file) { if(err) { response.writeHead(500, {"Content-Type": "text/plain"}); response.write(err + "\n"); response.end(); return; } response.writeHead(200); response.write(file, "binary"); response.end(); }); }); }; var tweet_emitter = new events.EventEmitter(); function get_tweets() { var options = { hostname: "api.twitter.com", path: "/1/statuses/user_timeline/thinkphp.json?count=10", method: "GET" }; var options2 = { hostname: "search.twitter.com", path: "/search.json?q=mootools", method: "GET" }; var req = http.request(options, function( response ){ response.setEncoding('binary'); var out = '' response.on("data", function( data ) { out += data }) response.on("end", function(){ var tweets = out if( tweets.length > 0) { tweet_emitter.emit("tweets", tweets) } }) }) req.on('error', function(e) { console.log('problem with request: ' + e.message); }); req.end(); }; setInterval(get_tweets, 5000); http.createServer(function(request, response){ var uri = url.parse(request.url).pathname; if(uri == '/stream') { var listener = tweet_emitter.addListener("tweets", function( tweets ){ response.writeHead("Access-Control-Allow-Origin", "*") response.writeHead(200, { "Content-Type" : "text/plain" }) response.write( JSON.stringify( tweets ) ) response.end() clearTimeout( timeout ) }) var timeout = setTimeout(function(){ response.writeHead("Access-Control-Allow-Origin", "*") response.writeHead(200, { "Content-Type" : "text/plain" }) response.write( JSON.stringify([]) ) response.end() tweet_emitter.removeListener( listener ) },10000) } else { load_static(uri, response) } }).listen(8080); sys.puts("Server running at http://localhost:8080")
Java
UTF-8
1,099
1.578125
2
[]
no_license
package com.grubhub.AppBaseLibrary.android.account; import android.support.v4.app.q; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.TextView; import android.widget.ViewSwitcher; class GHSAddressInfoFragment$22 implements View.OnClickListener { GHSAddressInfoFragment$22(GHSAddressInfoFragment paramGHSAddressInfoFragment) {} public void onClick(View paramView) { GHSAddressInfoFragment.A(a).setText(GHSAddressInfoFragment.B(a).getText().toString()); GHSAddressInfoFragment.A(a).setSelection(GHSAddressInfoFragment.A(a).getText().toString().length()); GHSAddressInfoFragment.z(a).setDisplayedChild(1); GHSAddressInfoFragment.A(a).requestFocus(); ((InputMethodManager)a.getActivity().getSystemService("input_method")).showSoftInput(GHSAddressInfoFragment.A(a), 1); } } /* Location: * Qualified Name: com.grubhub.AppBaseLibrary.android.account.GHSAddressInfoFragment.22 * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
Java
UTF-8
2,741
1.929688
2
[]
no_license
package com.saint.aoyangbuulid.mine.code; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.google.zxing.WriterException; import com.saint.aoyangbuulid.BaseActivity; import com.saint.aoyangbuulid.R; import com.saint.aoyangbuulid.login.Login_Activity; import com.saint.aoyangbuulid.mine.encoding.EncodingHandler; /** * Created by zzh on 15-12-17. */ public class MyCode_Activity extends BaseActivity { private ImageView image_code; private TextView text_name,text_phone; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mycode); SharedPreferences sp=getSharedPreferences(Login_Activity.PREFERENCE_NAME,Login_Activity.Mode); Intent intent=getIntent(); String id=intent.getStringExtra("id"); image_code= (ImageView) findViewById(R.id.image_code); text_name= (TextView) findViewById(R.id.code_text); text_phone= (TextView) findViewById(R.id.code_phone_text); //将id 生成二维码 try { // Bitmap bitmap= EncodingHandler.createQRCode(id, 400, BitmapFactory.decodeResource(getResources(), // Integer.parseInt(sp.getString("image_head", String.valueOf(R.mipmap.aoyang))))); // Bitmap bitmap=EncodingHandler.createQRCode(id,400, BitmapFactory.decodeResource(getResources(), R.mipmap.aoyang)); if (id.equals("")){ Toast.makeText(MyCode_Activity.this,"当前网络不稳定,请检查当前网络",Toast.LENGTH_SHORT).show(); }else { Bitmap bitmap=EncodingHandler.createQRCode(id,400,null); image_code.setImageBitmap(bitmap); } text_name.setText(sp.getString("nickname","")); text_phone.setText(sp.getString("phone","")); } catch (WriterException e) { e.printStackTrace(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater=getMenuInflater(); inflater.inflate(R.menu.menu,menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId()==android.R.id.home){ MyCode_Activity.this.finish(); } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { super.onBackPressed(); } }
Python
UTF-8
681
2.5625
3
[]
no_license
import os from watson_developer_cloud import DocumentConversionV1, WatsonException def get_doc_coversion(fp): document_conversion = DocumentConversionV1( username=os.environ['watson_dc_username'], password=os.environ['watson_dc_password'], version='2017-03-23') result = '' try: # Example of retrieving html or plain text # with open(fp, 'r') as document: config = { 'conversion_target': DocumentConversionV1.NORMALIZED_TEXT } result = document_conversion.convert_document( document=fp, config=config).content except WatsonException as e: print e return result
C#
UTF-8
1,361
2.578125
3
[]
no_license
using UnityEngine; using UnityEngine.UI; using Ai.Goap; namespace TeamZapocalypse { public class Shelter : MonoBehaviour, IStateful { public float shieldEnergy = 60f; public Text shieldEnergyText; public GameObject shield; private readonly State state = new State(); private const float energyDeplitionRate = 0.4f; private const float energyFromFuel = 8; private const float maxEnergy = 100; protected void Awake() { state["shieldEnergy"] = new StateValue(shieldEnergy); CheckShield(); } protected void Update() { shieldEnergy = Mathf.Max(0, shieldEnergy - Time.deltaTime * energyDeplitionRate); CheckShield(); } private void CheckShield() { state["shieldEnergy"].value = shieldEnergy; if (shieldEnergy > 10f) { shield.SetActive(true); shieldEnergyText.color = Color.blue; } else { shield.SetActive(false); shieldEnergyText.color = Color.red; } shieldEnergyText.text = "Shield Energy: " + new string('|', (int)shieldEnergy / 4); } public void AddFuel(int numOfTanks) { shieldEnergy += Mathf.Min(numOfTanks * energyFromFuel, maxEnergy); CheckShield(); } public State GetState() { // TODO: Add limited resources return state; } } }
Java
UTF-8
4,989
1.953125
2
[]
no_license
/******************************************************************************* * Copyright (c) 2005, 2007 Intel Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Intel Corporation - Initial API and implementation *******************************************************************************/ package org.eclipse.cdt.managedbuilder.envvar; import org.eclipse.cdt.core.envvar.IEnvironmentVariable; import org.eclipse.cdt.managedbuilder.core.IConfiguration; /** * * this interface represent the environment variable provider - the main entry-point * to be used for querying the build environment * * @since 3.0 */ public interface IEnvironmentVariableProvider{ /** * * * @return the reference to the IBuildEnvironmentVariable interface representing * the variable of a given name * @param variableName environment variable name * if environment variable names are case insensitive in the current OS, * the environment variable provider will query the getVariable method of suppliers always * passing it the uppercase variable name not depending on the case of the variableName * passed to the IEnvironmentVariableProvider.getVariable() method. This will prevent the * supplier from answering different values for the same variable given the names that differ * only by case. E.g. if the current OS does not support case sensitive variables both of the * calls below: * * provider.getVariable("FOO",level,includeParentContexts); * provider.getVariable("foo",level,includeParentContexts); * * will result in asking suppliers for the "FOO" variable * * @param level could be one of the following: * 1. IConfiguration to represent the configuration * 2. IManagedProject to represent the managed project * 3. IWorkspace to represent the workspace * 4. null to represent the system environment passed to eclipse * @deprecated use {@link IEnvironmentVariableProvider#getVariable(String, IConfiguration, boolean)} instead */ public IBuildEnvironmentVariable getVariable( String variableName, Object level, boolean includeParentLevels, boolean resolveMacros); public IEnvironmentVariable getVariable(String variableName, IConfiguration cfg, boolean resolveMacros); /** * * if environment variable names are case insensitive in the current OS, * the environment variable provider will remove the duplicates of the variables if their names * differ only by case * @deprecated use {@link IEnvironmentVariableProvider#getVariables(IConfiguration, boolean)} instead * * @return the array of IBuildEnvironmentVariable that represents the environment variables */ public IBuildEnvironmentVariable[] getVariables( Object level, boolean includeParentLevels, boolean resolveMacros); public IEnvironmentVariable[] getVariables( IConfiguration cfg, boolean resolveMacros); /** * * @return the String representing default system delimiter. That is the ":" for Unix-like * systems and the ";" for Win32 systems. This method will be used by the * tool-integrator provided variable supplier e.g. in order to concatenate the list of paths into the * environment variable, etc. */ public String getDefaultDelimiter(); /** * @return true if the OS supports case sensitive variables (Unix-like systems) or false * if it does not (Win32 systems) */ public boolean isVariableCaseSensitive(); /** * This method is defined to be used basically by the UI classes and should not be used by the * tool-integrator * @return the array of the provider-internal suppliers for the given level */ IEnvironmentVariableSupplier[] getSuppliers(Object level); /** * returns the array of String that holds the build paths of the specified type * @param configuration represent the configuration for which the paths were changed * @param buildPathType can be set to one of the IEnvVarBuildPath.BUILDPATH _xxx * (the IEnvVarBuildPath will represent the build environment variables, see also * the "Specifying the Includes and Library paths environment variables", * the "envVarBuildPath schema" and the "Expected CDT/MBS code changes" sections) */ String[] getBuildPaths(IConfiguration configuration, int buildPathType); /** * * adds the listener that will return notifications about the include and library paths changes. * The ManagedBuildManager will register the change listener and will notify all registered * Scanned Info Change Listeners about the include paths change. */ void subscribe( IEnvironmentBuildPathsChangeListener listener); /** * * removes the include and library paths change listener */ void unsubscribe( IEnvironmentBuildPathsChangeListener listener); }
Java
UTF-8
1,376
2.234375
2
[]
no_license
package com.fullgc.jbehave.steps; /** * Created by dani on 24/09/18. */ import com.fullgc.dispatcher.RequestDispatcher; import com.fullgc.jbehave.cache.CacheBean; import net.thucydides.junit.spring.SpringIntegration; import org.jbehave.core.annotations.Given; import org.jbehave.core.annotations.Named; import org.junit.Rule; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.test.context.ContextConfiguration; import java.io.IOException; @ContextConfiguration(locations = "/spring-context.xml") @Service public class GivenUserSteps { @Rule public SpringIntegration springIntegration = new SpringIntegration(); @Autowired CacheBean cache; @Given("$user is a Volcano enthusiast") public String user(@Named("user") String user) { return "let " + user + "be a volcano enthusiast"; } @Given("$user is logged in") public void logIn(@Named("user") String user) throws IOException { String session = RequestDispatcher.logIn(user, cache.getUsers().get(user)).getResponseBody(); assert session != null; cache.getToken().put(user, session); } @Given("$user has registered to Volcano") public void quickSignup(@Named("user") String user) { RequestDispatcher.createUser(user, "password"); } }
TypeScript
UTF-8
2,253
2.515625
3
[ "Apache-2.0" ]
permissive
/* * Copyright 2019 Red Hat, Inc. and/or its affiliates. * * 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. */ import { Action } from 'redux'; import { ThunkAction } from 'redux-thunk'; import RestServiceClient from './rest/RestServiceClient'; import { PersonList } from 'store/person/types'; import { AlertList } from './alert/types'; import { ResultViewHolder } from './assignments/types'; import { Configuration } from './config/types'; /** * ThunkCommand is a ThunkAction that has no result (it's typically something like * `Promise<ActionAfterDataFetched>`, but sending messages over WebSocket usually has no response * (with the exception of subscribe), so most of our operations are void). * * @template A Type of action(s) allowed to be dispatched. */ export type ThunkCommand<A extends Action> = ThunkAction<any, AppState, RestServiceClient, A>; /** * Factory method that takes a value and creates an @type {Action}. * * @template V value type * @template A action type */ export type ActionFactory<V, A extends Action> = V extends void ? // https://stackoverflow.com/questions/55646272/conditional-method-parameters-based-on-generic-type () => A : // nullary V extends boolean? (value: boolean) => A : // boolean unary (value: V) => A; // unary /** * Factory method that takes a value and creates a @type {ThunkCommand}. * * @template V value type * @template A action type */ export type ThunkCommandFactory<V, A extends Action> = V extends void ? () => ThunkCommand<A> : // nullary (value: V) => ThunkCommand<A>; // unary export interface AppState { readonly personList: PersonList; readonly alerts: AlertList; readonly assignments: ResultViewHolder; readonly config: Configuration; }
Markdown
UTF-8
863
2.8125
3
[]
no_license
#### A set of python projects dealing with exceptions **0-safe_print_list.py:** print x number of elements in a list inside try/except **1-safe_print_integer.py:** print an integer inside of try/except **2-safe_print_list_integers.py:** print a list of integers as integers, handle except **3-safe_print_division.py:** divide two numbers and catch divby0 **4-list_division.py:** divide elements from two lists up to a certain length **5-raise_exception.py:** function raises a type exception **6-raise_exception_message.py:** function raises an exception with a message **100-safe_print_integer_err.py:** print integer and handle exceptions **101-safe_function.py:** execute a function and handle exceptions **102-magic_calculation.py:** reverse engineer given python bytecode **103-python.c:** use cpython to output information about lists
Markdown
UTF-8
917
2.96875
3
[]
no_license
--- id: act1 title: Activity sidebar_label: Activity --- import useBaseUrl from '@docusaurus/useBaseUrl'; ## Dashboard Activity You can hover your mouse over the pie chart to view the number of tasks Overdue, In Progress and Completed. Click on the pie chart to bring you into the underlying detail. <img alt="Pie Chart" src={useBaseUrl('img/pie.png')}/> i.e. If you select ‘Overdue’, you are directed to the ‘Activity’ page where you can view the details of all tasks that are currently overdue, in our example we have 2 overdue tasks. You can action them on the right-hand side column. You can also use the filter function or search functionality to look for tasks within a project and their status. Actioning an overdue task Click on the edit icon for the task you want to action You will be presented with the full details of the selected task (Seen below) ![Activity](/static/img/activity.png)
Python
UTF-8
1,094
3.828125
4
[]
no_license
from typing import List class Node: def __init__(self, val=None, children=None): self.val = val self.children = children def preorder_recursive(root: Node) -> List[int]: res = [] def dfs(node: 'Node'): if node is None: return res.append(node.val) for child in node.children: dfs(child) dfs(root) return res def preorder_iterative(root: Node) -> List[int]: if root is None: return [] res = [] stack = [root] while stack: node = stack.pop() if node is None: continue res.append(node.val) # 因为栈是FILO的,但是希望靠左的儿子能优先被遍历,所以只好将儿子反转 for child in reversed(node.children): stack.append(child) return res def postorder_recursive(root: Node) -> List[int]: res = [] def dfs(node: 'Node'): if node is None: return for child in node.children: dfs(child) res.append(node.val) dfs(root) return res
Java
UTF-8
5,081
2.109375
2
[ "MIT" ]
permissive
package de.timherbst.wau.domain; import java.io.Serializable; import java.util.Date; import java.util.Vector; import com.thoughtworks.xstream.annotations.XStreamAlias; import de.timherbst.wau.domain.riege.EinzelRiege; import de.timherbst.wau.domain.riege.MannschaftsRiege; import de.timherbst.wau.domain.riege.Riege; import de.timherbst.wau.domain.wettkampf.EinzelWettkampf; import de.timherbst.wau.domain.wettkampf.MannschaftsWettkampf; import de.timherbst.wau.domain.wettkampf.Wettkampf; import de.timherbst.wau.events.Event; import de.timherbst.wau.events.EventDispatcher; import de.timherbst.wau.exceptions.HasWettkampfException; @XStreamAlias("WettkampfTag") public class WettkampfTag implements Serializable { private static final long serialVersionUID = 2524662626105936234L; private static WettkampfTag instance; private String name; private String ort; private Date datum; private Vector<Riege> riegen; private Vector<Wettkampf> wettkaempfe; private Vector<Mannschaft> mannschaften; private Vector<Turner> turner; private WettkampfTag() { name = "Wettkampf Tag"; ort = "Ort"; datum = new Date(); wettkaempfe = new Vector<Wettkampf>(); turner = new Vector<Turner>(); mannschaften = new Vector<Mannschaft>(); riegen = new Vector<Riege>(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getOrt() { return ort; } public void setOrt(String ort) { this.ort = ort; } public Date getDatum() { return datum; } public void setDatum(Date datum) { this.datum = datum; } public Vector<Wettkampf> getWettkaempfe() { return wettkaempfe; } public void addWettkampf(Wettkampf wettkampf) { wettkampf.setWkt(this); this.wettkaempfe.add(wettkampf); EventDispatcher.dispatchEvent(Event.WETTKAMPFTAG_CHANGED); } public Vector<Turner> getTurner() { return turner; } public void addTurner(Turner turner) { this.turner.add(turner); EventDispatcher.dispatchEvent(Event.WETTKAMPFTAG_CHANGED); } public Vector<Mannschaft> getMannschaften() { return mannschaften; } public void addMannschaft(Mannschaft mannschaft) { mannschaft.setWkt(this); this.mannschaften.add(mannschaft); EventDispatcher.dispatchEvent(Event.WETTKAMPFTAG_CHANGED); } public Vector<Riege> getRiegen() { return riegen; } public void addRiege(Riege riege) { riege.setWkt(this); this.riegen.add(riege); EventDispatcher.dispatchEvent(Event.WETTKAMPFTAG_CHANGED); } public static WettkampfTag get() { if (instance == null) instance = new WettkampfTag(); return instance; } public static void set(WettkampfTag wt) { instance = wt; EventDispatcher.dispatchEvent(Event.WETTKAMPFTAG_CHANGED); } @Override public String toString() { return getName(); } public static WettkampfTag newInstance() { return new WettkampfTag(); } public void removeWettkampf(Wettkampf w) { if (w instanceof EinzelWettkampf) { EinzelWettkampf ew = (EinzelWettkampf) w; for (Turner t : ew.getTurner()) { t.setWettkampf(null); } } if (w instanceof MannschaftsWettkampf) { MannschaftsWettkampf mw = (MannschaftsWettkampf) w; for (Mannschaft m : mw.getMannschaften()) { m.setWettkampf(null); } } getWettkaempfe().remove(w); EventDispatcher.dispatchEvent(Event.WETTKAMPFTAG_CHANGED); } public void removeRiege(Riege r) { if (r instanceof EinzelRiege) { EinzelRiege er = (EinzelRiege) r; for (Turner t : er.getTurner()) { t.setRiege(null); } } if (r instanceof MannschaftsRiege) { MannschaftsRiege mr = (MannschaftsRiege) r; for (Mannschaft m : mr.getMannschaften()) { m.setRiege(null); } } getRiegen().remove(r); EventDispatcher.dispatchEvent(Event.WETTKAMPFTAG_CHANGED); } public void removeTurner(Turner t) { if (t.getMannschaft() != null) t.getMannschaft().getTurner().remove(t); if (t.getRiege() != null && t.getRiege() instanceof EinzelRiege) ((EinzelRiege) t.getRiege()).getTurner().remove(t); if (t.getWettkampf() != null && t.getWettkampf() instanceof EinzelWettkampf) ((EinzelWettkampf) t.getWettkampf()).getTurner().remove(t); getTurner().remove(t); EventDispatcher.dispatchEvent(Event.WETTKAMPFTAG_CHANGED); } public void removeMannschaft(Mannschaft m) { for (Turner t : m.getTurner()) { t.setRiege(null); t.setWettkampf(null); try { t.setMannschaft(null); } catch (HasWettkampfException e) { // kann nicht passieren } } if (m.getRiege() != null && m.getRiege() instanceof MannschaftsRiege) ((MannschaftsRiege) m.getRiege()).getMannschaften().remove(m); if (m.getWettkampf() != null && m.getWettkampf() instanceof MannschaftsWettkampf) ((MannschaftsWettkampf) m.getWettkampf()).getMannschaften().remove(m); getMannschaften().remove(m); EventDispatcher.dispatchEvent(Event.WETTKAMPFTAG_CHANGED); } }