language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
C
UTF-8
4,153
2.90625
3
[]
no_license
#include "collision.h" const double AXIS_ROTATION_FROM_SIDE = M_PI / 2; typedef struct range { double min; double max; } range_t; typedef struct collis_deriv_info { collision_info_t info; double overlap; } collis_deriv_info_t; bool point_within_range(double point, range_t range) { return range.min <= point && point <= range.max; } double range_mag(range_t a) { return a.max - a.min; } bool range_a_intersects_b(range_t range_a, range_t range_b) { bool mincheck = point_within_range(range_a.min, range_b); bool maxcheck = point_within_range(range_a.max, range_b); return mincheck || maxcheck; } bool ranges_intersect(range_t range_a, range_t range_b) { bool acheck = range_a_intersects_b(range_a, range_b); bool bcheck = range_a_intersects_b(range_b, range_a); return acheck || bcheck; } double range_overlap(range_t a, range_t b) { if (!ranges_intersect(a, b)) { return 0; } return fabs(fmin(a.max, b.max) - fmax(a.min, b.min)); } double signed_projection_magnitude(vector_t axis, vector_t vertex) { vector_t proj = vec_project(axis, vertex); double proj_mag = vec_magnitude(proj); // Get unit vectors of projection and axis vector_t phat = vec_unit(proj); vector_t ahat = vec_unit(axis); vector_t diff = vec_subtract(phat, ahat); // If unit vectors are the same, then they are in the same direction double diff_mag = vec_magnitude(diff); // If the difference of unit vectors is closer to 2 than zero, "negative" // magnitude. double dist_to_zero = fabs(diff_mag); double dist_to_two = fabs(diff_mag - 2); if (dist_to_two < dist_to_zero) { proj_mag *= -1; } return proj_mag; } range_t axis_projection_range(list_t *polygon, vector_t axis) { double min; double max; size_t n = list_size(polygon); for (size_t i = 0; i < n; i++) { vector_t *vertex = (vector_t *)list_get(polygon, i); double proj_mag = signed_projection_magnitude(axis, *vertex); if (i == 0) { min = proj_mag; max = proj_mag; } else { min = fmin(proj_mag, min); max = fmax(proj_mag, max); } } return (range_t){ .min = min, .max = max, }; } collis_deriv_info_t side_overlap(list_t *shape_a, list_t *shape_b, size_t idx1, size_t idx2) { vector_t *a = (vector_t *)list_get(shape_a, idx1); vector_t *b = (vector_t *)list_get(shape_a, idx2); vector_t side = vec_subtract(*a, *b); vector_t axis = vec_rotate(side, AXIS_ROTATION_FROM_SIDE); range_t range_a = axis_projection_range(shape_a, axis); range_t range_b = axis_projection_range(shape_b, axis); double overlap = range_overlap(range_a, range_b); collision_info_t info = (collision_info_t){ .axis = axis, .collided = ranges_intersect(range_a, range_b), }; return (collis_deriv_info_t){.info = info, .overlap = overlap}; } collis_deriv_info_t best_collision_axis(collis_deriv_info_t a, collis_deriv_info_t b) { return a.overlap < b.overlap ? a : b; } collis_deriv_info_t axes_match_shape_a(list_t *shape_a, list_t *shape_b) { size_t n = list_size(shape_a); collis_deriv_info_t best; for (size_t idx1 = 0; idx1 < n; idx1++) { size_t idx2 = (idx1 + 1) % n; collis_deriv_info_t col = side_overlap(shape_a, shape_b, idx1, idx2); if (!col.info.collided) { return col; } best = idx1 == 0 ? col : best_collision_axis(best, col); } return best; } collision_info_t find_collision(list_t *shape1, list_t *shape2) { collis_deriv_info_t respect1 = axes_match_shape_a(shape1, shape2); collis_deriv_info_t respect2 = axes_match_shape_a(shape2, shape1); if (!(respect1.info.collided && respect2.info.collided)) { return (collision_info_t){.axis = VEC_ZERO, .collided = false}; } return best_collision_axis(respect1, respect2).info; // return (collision_info_t){ // .axis = vec_subtract(polygon_centroid(shape2), // polygon_centroid(shape1)), .collided = true}; // return (collision_info_t){ // .axis = vec_rotate(best_collision_axis(respect1, respect2).info.axis, // AXIS_ROTATION_FROM_SIDE), .collided = true}; }
C
UTF-8
3,123
2.984375
3
[]
no_license
;#include <stdio.h> ;#include <math.h> ;#include <stdlib.h> ; ;void calculate_e() ;{ ; int a; ; float b, c, e, z; ; a = 1; ; b = 1; ; c = 1; ; float y = 1.0; ; float e_6 = 2.718281; ; float prec = 0.00001; ; ; while (a <= 9) ; { ; printf("\n\nIteration number %d\n", a); ; c = c*a; ; z = b/c; ; a++; ; y=z+y; ; printf("Sum of fractions so far: %f\n", y); ; printf("Actual value of e: %f\n", e_6); ; e = e_6-y; ; printf("Difference: %f\n", e); ; printf("Precision value: %f\n", prec); ; } ;} ; ;void average_nums() ; ;{ ; ;} ; ;void matrix_mul() ;{ ; float matrix_1[4] = {0.4, 0.3, 0.2, 0.1}; ; float matrix_2[4] = {0.6, 0.7, 0.8, 0.9}; ; float temp_matrix[8] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; ; float end_matrix[4] = {0.0, 0.0, 0.0, 0.0}; ; ; printf("Matrix One:\n%lf %lf\n%lf %lf\n\n", matrix_1[0], matrix_1[1], matrix_1[2], matrix_1[3]); ; ; printf("Matrix Two:\n%lf %lf\n%lf %lf\n\n", matrix_2[0], matrix_2[1], matrix_2[2], matrix_2[3]); ; ; int a_counter=0, b_counter=0, c_counter=0, d_counter=0, counter=0; ; ; while (counter < 4) ; { ; temp_matrix[c_counter] = matrix_1[a_counter] * matrix_2[b_counter]; ; b_counter++; ; c_counter++; ; temp_matrix[c_counter] = matrix_1[a_counter] * matrix_2[b_counter]; ; a_counter++; ; b_counter++; ; c_counter++; ; if (b_counter==2) ; { ; b_counter = 0; ; } ; counter++; ; } ; ; counter = 0; ; c_counter = 0; ; d_counter = 0; ; ; while (counter < 4) ; { ; end_matrix[d_counter] = temp_matrix[c_counter] + temp_matrix[c_counter+2]; ; c_counter++; ; d_counter++; ; counter++; ; if (counter == 2) ; { ; c_counter = 4; ; } ; } ; ; printf("End Matrix:\n%lf %lf\n%lf %lf\n\n", end_matrix[0], end_matrix[1], end_matrix[2], end_matrix[3]); ;} ; ;void freq_table() ;{ ; int freq_tab[27] = {0}; ; char cm_str[7] = {"APP LE"}; ; int counter = 6; ; printf("String: %s\n", cm_str); ; int ft_counter = 0, thing = 0; ; float numletts = counter; ; float frq_val_max = 1/numletts; ; printf("Single letter frequency: %lf\n", frq_val_max); ; int start = 65; ; while (start > 64) ; { ; if (cm_str[ft_counter] == start) ; { ; printf("Letter: %c", cm_str[ft_counter]); ; freq_tab[thing] = freq_tab[thing] + frq_val_max; ; } ; ft_counter++; ; thing++; ; start++; ; if (start == 91) ; break; ; } ;} ; ;int main() ;{ ; int sel; ; do { ; printf("Welcome to Isaac Stallcup's Program 5.\n"); ; printf("Please select the function you wish to perform (1-4).\n"); ; printf("1 Approximate e\t\t\t2 Average numbers\n3 Float matrx multiplication\t4 Frequency Table\n"); ; scanf("%d", &sel); ; } while (sel > 5 && sel < 0); ; ; if (sel == 1) ; { ; calculate_e(); ; } ; ; if (sel == 2) ; { ; average_nums(); ; } ; ; if (sel == 3) ; { ; matrix_mul(); ; } ; ; if (sel == 4) ; { ; freq_table(); ; } ; ; return 0; ; ;} ; ; ; ; ; ; ; ; ; ;
Java
UTF-8
2,112
3.1875
3
[ "Apache-2.0" ]
permissive
package cz.net21.ttulka.ant; import org.apache.tools.ant.BuildException; import java.io.IOException; import java.nio.file.*; import java.util.ArrayList; import java.util.List; /** * Created by ttulka, 2017, http://blog.net21.cz * * Reads a directory and returns files with a name suffix (optional). * The actual file path is written in the @{file} attribute. * * Parameters: * - path * - suffix */ public class FetchFilesTask extends SequentialTask { /** * Attribute name. */ private static final String ATTR_NAME = "file"; private String path; private String suffix; public void setPath(String path) { this.path = path; } public void setSuffix(String suffix) { this.suffix = suffix; } @Override String getAttributeName() { return ATTR_NAME; } /** * Execution point of the task. */ @Override public void execute() { if (path == null || path.trim().isEmpty()) { throw new BuildException("Parameter 'path' must be specified."); } List<String> filesList = getFilesList(Paths.get(path), suffix); for (String file : filesList) { executeSequential(file.toString()); } } /** * Returns a list of files for the source path and the suffix. * @param sourcePath the path * @param suffix the suffix * @return the list of files */ List<String> getFilesList(Path sourcePath, String suffix) { final List<String> toReturn = new ArrayList<>(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(sourcePath)) { for (Path file: stream) { if (Files.isRegularFile(file)) { if (suffix == null || file.toString().endsWith(suffix)) { toReturn.add(file.toString()); } } } } catch (IOException | DirectoryIteratorException e) { throw new BuildException("Error by reading '" + sourcePath + "'.", e); } return toReturn; } }
Markdown
UTF-8
1,380
2.875
3
[ "MIT" ]
permissive
# Gulp integration Run this to set your project up with a simple Gulp config. ```sh ./bin/rails generate npm_pipeline:gulp ``` ## Manual setup If you don't want to use the generator, here's what it does. #### package.json > Set up `gulp`, `gulp-cli`, and some basic Gulp plugins. ```sh npm init --yes npm install --save-dev gulp gulp-cli gulp-concat ``` _See:_ [sample package.json](../lib/generators/npm_pipeline/gulp/package.json) #### gulpfile.js > Set it up to watch source files in `app/gulp`, then put built files into `vendor/assets`. _See:_ [sample gulpfile.js](../lib/generators/npm_pipeline/gulp/gulpfile.js) #### .gitignore > Set it up to ignore Gulp's built files. ``` /node_modules /vendor/assets/stylesheets/gulp /vendor/assets/javascripts/gulp ``` #### app/assets/stylesheets/application.css > Set it up to include Gulp's built files. This will load from `vendor/assets/stylesheets/gulp/app.css`, as built by Gulp. ```css /* *= require gulp/app */ ``` #### app/assets/javascripts/application.js > Set it up to include Gulp's built files. This will load from `vendor/assets/javascripts/gulp/app.js`, as built by Gulp. ```css //= require gulp/app ``` #### app/gulp/ > Put your source files into `app/gulp`. For instance: * `app/gulp/example.css` ```css * { color: blue } ``` * `app/gulp/example.js` ```js alert('it works!') ```
Java
UTF-8
637
1.914063
2
[]
no_license
package com.example.macrz.project; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { Button Boton1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Boton1=(Button)(findViewById(R.id.Boton1)); } public void Boton1(View v) { Intent segunda = new Intent (this, Main2Activity.class); startActivity(segunda); } }
Java
UTF-8
6,635
2.125
2
[ "Apache-2.0" ]
permissive
package us.ihmc.humanoidBehaviors.behaviors.complexBehaviors; import controller_msgs.msg.dds.ArmTrajectoryMessage; import controller_msgs.msg.dds.GoHomeMessage; import us.ihmc.euclid.referenceFrame.FramePoint3D; import us.ihmc.euclid.referenceFrame.FrameQuaternion; import us.ihmc.euclid.referenceFrame.ReferenceFrame; import us.ihmc.euclid.tuple3D.Point3D; import us.ihmc.humanoidBehaviors.behaviors.AbstractBehavior; import us.ihmc.humanoidBehaviors.behaviors.primitives.AtlasPrimitiveActions; import us.ihmc.humanoidBehaviors.behaviors.simpleBehaviors.BehaviorAction; import us.ihmc.humanoidBehaviors.taskExecutor.ArmTrajectoryTask; import us.ihmc.humanoidBehaviors.taskExecutor.GoHomeTask; import us.ihmc.humanoidBehaviors.taskExecutor.HandDesiredConfigurationTask; import us.ihmc.humanoidRobotics.communication.packets.HumanoidMessageTools; import us.ihmc.humanoidRobotics.communication.packets.dataobjects.HandConfiguration; import us.ihmc.humanoidRobotics.communication.packets.walking.HumanoidBodyPart; import us.ihmc.humanoidRobotics.frames.HumanoidReferenceFrames; import us.ihmc.robotics.robotSide.RobotSide; import us.ihmc.robotics.taskExecutor.PipeLine; import us.ihmc.ros2.ROS2Node; import us.ihmc.yoVariables.variable.YoDouble; public class PickObjectOffGroundBehavior extends AbstractBehavior { private final PipeLine<AbstractBehavior> pipeLine; private Point3D grabLocation = null; private double objectRadius = 0; private final AtlasPrimitiveActions atlasPrimitiveActions; public PickObjectOffGroundBehavior(String robotName, YoDouble yoTime, HumanoidReferenceFrames referenceFrames, ROS2Node ros2Node, AtlasPrimitiveActions atlasPrimitiveActions) { super(robotName, ros2Node); pipeLine = new PipeLine<>(yoTime); this.atlasPrimitiveActions = atlasPrimitiveActions; setupPipeline(); } private void setupPipeline() { HandDesiredConfigurationTask openHand = new HandDesiredConfigurationTask(RobotSide.LEFT, HandConfiguration.OPEN, atlasPrimitiveActions.leftHandDesiredConfigurationBehavior); HandDesiredConfigurationTask closeHand = new HandDesiredConfigurationTask(RobotSide.LEFT, HandConfiguration.CLOSE, atlasPrimitiveActions.leftHandDesiredConfigurationBehavior); double[] leftHandAfterGrabLocation = new double[] {-0.799566492522621, -0.8850712601496326, 1.1978163314288173, 0.9978871050058826, -0.22593401111949774, -0.2153318563363089, -1.2957848304397805}; ArmTrajectoryMessage leftHandAfterGrabMessage = HumanoidMessageTools.createArmTrajectoryMessage(RobotSide.LEFT, 2, leftHandAfterGrabLocation); ArmTrajectoryTask leftHandBeforeGrab = new ArmTrajectoryTask(leftHandAfterGrabMessage, atlasPrimitiveActions.leftArmTrajectoryBehavior); ArmTrajectoryTask leftHandAfterGrab = new ArmTrajectoryTask(leftHandAfterGrabMessage, atlasPrimitiveActions.leftArmTrajectoryBehavior); // GO TO INITIAL POICKUP LOCATION ******************************************* BehaviorAction goToPickUpBallInitialLocationTask = new BehaviorAction(atlasPrimitiveActions.wholeBodyBehavior) { @Override protected void setBehaviorInput() { publishTextToSpeech("Picking Up The Ball"); FramePoint3D point = new FramePoint3D(ReferenceFrame.getWorldFrame(), grabLocation.getX(), grabLocation.getY(), grabLocation.getZ() + objectRadius + 0.25); atlasPrimitiveActions.wholeBodyBehavior.setSolutionQualityThreshold(2.01); atlasPrimitiveActions.wholeBodyBehavior.setTrajectoryTime(3); FrameQuaternion tmpOr = new FrameQuaternion(point.getReferenceFrame(), Math.toRadians(45), Math.toRadians(90), 0); atlasPrimitiveActions.wholeBodyBehavior.setDesiredHandPose(RobotSide.LEFT, point, tmpOr); } }; //REACH FOR THE BALL ******************************************* BehaviorAction pickUpBallTask = new BehaviorAction(atlasPrimitiveActions.wholeBodyBehavior) { @Override protected void setBehaviorInput() { FramePoint3D point = new FramePoint3D(ReferenceFrame.getWorldFrame(), grabLocation.getX(), grabLocation.getY(), grabLocation.getZ() + objectRadius); atlasPrimitiveActions.wholeBodyBehavior.setSolutionQualityThreshold(2.01); atlasPrimitiveActions.wholeBodyBehavior.setTrajectoryTime(3); FrameQuaternion tmpOr = new FrameQuaternion(point.getReferenceFrame(), Math.toRadians(45), Math.toRadians(90), 0); atlasPrimitiveActions.wholeBodyBehavior.setDesiredHandPose(RobotSide.LEFT, point, tmpOr); } }; GoHomeMessage goHomeChestMessage = HumanoidMessageTools.createGoHomeMessage(HumanoidBodyPart.CHEST, 2); GoHomeTask goHomeChestTask = new GoHomeTask(goHomeChestMessage, atlasPrimitiveActions.chestGoHomeBehavior); GoHomeMessage goHomepelvisMessage = HumanoidMessageTools.createGoHomeMessage(HumanoidBodyPart.PELVIS, 2); GoHomeTask goHomePelvisTask = new GoHomeTask(goHomepelvisMessage, atlasPrimitiveActions.pelvisGoHomeBehavior); pipeLine.submitSingleTaskStage(leftHandBeforeGrab); pipeLine.requestNewStage(); pipeLine.submitTaskForPallelPipesStage(atlasPrimitiveActions.wholeBodyBehavior, goToPickUpBallInitialLocationTask); pipeLine.submitTaskForPallelPipesStage(atlasPrimitiveActions.wholeBodyBehavior, openHand); pipeLine.requestNewStage(); pipeLine.submitSingleTaskStage(pickUpBallTask); pipeLine.submitSingleTaskStage(closeHand); pipeLine.submitSingleTaskStage(leftHandAfterGrab); // pipeLine.submitSingleTaskStage(goHomeChestTask); pipeLine.submitSingleTaskStage(goHomePelvisTask); } public void setGrabLocation(Point3D grabLocation, double objectRadius) { this.grabLocation = grabLocation; this.objectRadius = objectRadius; } @Override public void onBehaviorExited() { grabLocation = null; } @Override public void doControl() { pipeLine.doControl(); } @Override public boolean isDone() { return pipeLine.isDone(); } @Override public void onBehaviorEntered() { } @Override public void onBehaviorAborted() { } @Override public void onBehaviorPaused() { } @Override public void onBehaviorResumed() { } }
C
UTF-8
316
3.046875
3
[ "BSD-2-Clause" ]
permissive
#include <stdio.h> void my_strcpy(char * dest, const char * src){ for(int i=0;src[i];i++){ dest[i]=src[i]; } } int main(int argc, const char *argv[]){ char buff[16]; int a=1; printf("hello world,a=%d\n",a); my_strcpy(buff,"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); return 0; }
JavaScript
UTF-8
2,390
3.0625
3
[]
no_license
const { RemindersStore } = require('../src/reminder/RemindersStore'); const Reminder = require('../src/reminder/Reminder'); const isStoredDataOk = data => { if (!data) { throw new Error('Restored data invalid.'); } if (!data['1']) { throw new Error('User not found.'); } if (!data['1'].reminders) { throw new Error('User has no reminders.'); } if (data['1'].reminders.length != 2) { throw new Error('User has invalid number of reminders.'); } if (!data['1'].reminders[0]) { throw new Error('User first reminder is invalid.'); } if (data['1'].reminders[0].id !== 1) { throw new Error('User first reminder has invalid id.'); } const testDate = new Date('2020-01-20T12:01:00+02:00'); if (data['1'].reminders[0].date.getTime() !== testDate.getTime()) { throw new Error('User first reminder has invalid date.'); } return true; } const userIdTest = '500'; const reminderTest = { id:100, text:'test text', date: '2020-01-20T13:01:00+02:00' } describe('ReminderStore Test', () => { const rStore = new RemindersStore( 'Test Store', { path: process.cwd() +'/tests/src/remindersTest.json' } ); test('is restore user successful', () => { expect(isStoredDataOk(rStore.data)).toBeTruthy(); }); const rwStore = new RemindersStore( 'Test Read Write Store', { path: process.cwd() +'/tests/src/remindersTempTest.json' } ); test('is hasUser return false if user not exist', () => { expect(!rwStore.hasUser('600')).toBeTruthy(); }); test('is createUser works fine', () => { rwStore.createUser(userIdTest); expect(rwStore.data[userIdTest]).toStrictEqual({ reminders:[] }); }); const rem = new Reminder(reminderTest) test('is addReminder works fine', () => { rwStore.addReminder(userIdTest, rem); expect(rwStore.data[userIdTest].reminders[0]).toStrictEqual(rem); }); test('is deleteReminder works fine', () => { rwStore.deleteReminder(userIdTest, rem.id); expect(rwStore.data[userIdTest].reminders.length).toBe(0); }); test('is deleteUser works fine', () => { rwStore.deleteUser(userIdTest); expect(rwStore.data[userIdTest] == null).toBeTruthy(); }); })
C++
UTF-8
1,398
4.1875
4
[]
no_license
#include<iostream> using namespace std; // declare a class class Wall{ private: double length; double height; public: //create parameterized constructor Wall(double len, double hgt) { //initialize private variables length=len; height=hgt; } Wall(double len) { length=len; height=5; } void display(){ cout<<"Values:\n"<<length <<"\t"<<height; } //copy constructor with a Wall object as parameter Wall(Wall &obj) { //initialize private variables length=obj.length; height=obj.height; } double calculateArea() { return length * height; } double getWall() { return length; return height; } }; int main() { //create object and initialize data members Wall wall1(10.5,8.6); wall1.display(); Wall wall2(42.5,5.8); wall2.display(); cout<<"\nArea of Wall 1:"<<wall1.getWall()<<endl; cout<<"Area of Wall 1: calculateArea :"<<wall1.calculateArea()<<endl; cout<<"Area of Wall 2:"<<wall2.getWall()<<endl; cout<<"Area of Wall 2: calculateArea :"<<wall2.calculateArea()<<endl; Wall wall3 = wall2; //copy contents of wall2 to another object wall3 cout<<"Area of Wall 3 :"<<wall3.calculateArea()<< endl; //print area of wall3 return 0; }
Python
UTF-8
282
3.046875
3
[]
no_license
i=1 k=False while k==False: num=sum(range(1,i+1)) numroot=int(num**0.5) divisor=0 for p in range(1,numroot): if num%p==0: divisor+=2 if num%numroot==0: divisor+=1 if divisor>=500: k=True else: i=i+1 print(num)
Java
UTF-8
438
1.734375
2
[]
no_license
package com.mvc.console.rpc.service; import com.mvc.api.vo.log.LogInfo; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @FeignClient("mvc-etherenum") public interface EthernumService { @RequestMapping(value="/api/log/save",method = RequestMethod.POST) public void saveLog(LogInfo info); }
C++
UTF-8
287
3.125
3
[]
no_license
#include <iostream> using namespace std; class Test { int i; // private by default public: int get_i() { return i; } void put_i(int j) { i = j; } }; int main() { Test s; s.put_i(10); cout << s.get_i(); system ("pause"); return 0; }
Java
UTF-8
12,077
2.421875
2
[]
no_license
package com.fcott.spadger.utils; import android.util.Log; import com.fcott.spadger.model.bean.ItemBean; import com.fcott.spadger.model.bean.MenuBean; import com.fcott.spadger.model.bean.NovelListBean; import com.fcott.spadger.model.bean.NovelListItemBean; import com.fcott.spadger.model.bean.PageControlBean; import com.fcott.spadger.model.bean.VedioListBean; import com.fcott.spadger.model.bean.VedioListItemBean; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.UnsupportedEncodingException; import java.util.ArrayList; /** * Created by Administrator on 2016/9/27. */ public class JsoupUtil { public static MenuBean parseYirenMenu(String response){ MenuBean menuBean = new MenuBean(); Document document = Jsoup.parse(response); Elements elements = document.select(".menu").select(".mt5"); for(Element element:elements){ Elements elements1 = element.select("a"); String type = elements1.get(0).text(); elements1.remove(0); if(type.equals("图片")){ for(Element ele:elements1){ menuBean.getPicList().add(new ItemBean( ele.text(),ele.attr("href"))); } }else if(type.equals("小说")){ for(Element ele:elements1){ menuBean.getNovelList().add(new ItemBean( ele.text(),ele.attr("href"))); } }else if(type.equals("电影")){ for(Element ele:elements1){ menuBean.getVedioList().add(new ItemBean( ele.text(),ele.attr("href"))); } } } return menuBean; } public static NovelListBean parseYirenList(String response){ NovelListBean novelListBean = new NovelListBean(); Document document = Jsoup.parse(response); Elements elements = document.getElementsByClass("textList").select("a"); for(Element element:elements){ novelListBean.getNovelList().add(new NovelListItemBean(element.attr("title"),element.attr("href"),"")); } Element pageElement = document.getElementsByClass("pages").get(0); String totalPage = pageElement.select("strong").get(0).text(); novelListBean.setPageControlBean(new PageControlBean(null, null, null, null, null, null,totalPage)); return novelListBean; } public static ArrayList<String> parseYirenPic(String response){ ArrayList<String> arrayList = new ArrayList<>(); Document document = Jsoup.parse(response); Elements elements = document.getElementsByClass("novelContent").select("img"); for(Element element:elements){ arrayList.add(element.attr("src")); } return arrayList; } public static String parseYirenNovelDetial(String response){ Document document = Jsoup.parse(response); Elements elements = document.getElementsByClass("novelContent").select("td"); return elements.get(0).text(); } public static VedioListBean parseYirenVideo(String response){ VedioListBean vedioListBean = new VedioListBean(); Document document = Jsoup.parse(response); Elements elements = document.getElementsByClass("movieList").select("li"); for(Element element:elements){ LogUtil.log(element.attr("href")+"--"+element.attr("title")+"--"+element.text()); vedioListBean.getVedioList().add(new VedioListItemBean(element.select("h3").text(),element.select("a").attr("href"),element.select("img").attr("src"),element.select("span").text())); } Elements pageElement = document.getElementsByClass("pages"); String totalPage; if(pageElement.size() == 0) totalPage = "1"; else totalPage = pageElement.get(0).select("strong").get(0).text(); vedioListBean.setPageControlBean(new PageControlBean(null, null, null, null, null, null,totalPage)); return vedioListBean; } public static String parseYirenVideoUrl(String response){ Document document = Jsoup.parse(response); // Element element = document.getElementById("videobox"); // LogUtil.log(element.attr("classid") +"--" +element.attr("xxid")); // String title = document.getElementsByTag("title").text(); String[] scripts = document.getElementsByTag("script").toString().split("http"); if(scripts == null || scripts.length < 2) return null; return "http"+scripts[1].split("mp4")[0]+"mp4"; } public static VedioListBean parseYirenSearch(String response){ VedioListBean vedioListBean = new VedioListBean(); Document document = Jsoup.parse(response); Elements elements = document.getElementsByClass("textList").select("li"); for(Element element:elements){ LogUtil.log(element.attr("href")+"--"+element.attr("title")+"--"+element.text()); vedioListBean.getVedioList().add(new VedioListItemBean(element.select("h3").text(),element.select("a").attr("href"),element.select("img").attr("src"),element.select("span").text())); } Elements pageElement = document.getElementsByClass("pages"); String totalPage; String jumpUrl = null; if(pageElement.size() == 0) totalPage = "1"; else{ totalPage = pageElement.get(0).select("strong").get(0).text(); jumpUrl = document.getElementsByClass("pageList").toString().split("searchid=")[1].split("\"")[0]; } vedioListBean.setPageControlBean(new PageControlBean(null, null, null, null, null, jumpUrl,totalPage)); return vedioListBean; } /** * 解析菜单(导航) * @param response */ public static MenuBean parseMenu(String response) { MenuBean menuBean = new MenuBean(); Document document = Jsoup.parse(response); Elements elementsTp = document.getElementsByClass("tp").get(0).select("li"); Elements elementsXs = document.getElementsByClass("xs").get(0).select("li"); Elements elementsDy = document.getElementsByClass("dy").get(0).select("li"); Elements newInfo = document.getElementsByClass("indexvod"); //最新信息 0:电影 1:图片 2:小说 for(int i = 0;i < newInfo.size();i++){ Elements e = newInfo.get(i).select("a"); switch (i){ case 0: for(Element element:e){ menuBean.getNewVedioList().add(new ItemBean(element.attr("title"),element.attr("href"))); } break; case 1: for(Element element:e){ menuBean.getNewpicList().add(new ItemBean(element.attr("title"),element.attr("href"))); } break; case 2: for(Element element:e){ menuBean.getNewNovelList().add(new ItemBean(element.attr("title"),element.attr("href"))); } break; } } //图片 for(Element e : elementsTp){ if(!e.select("a").attr("href").isEmpty() && !e.select("span").text().isEmpty()){ menuBean.getPicList().add(new ItemBean( e.select("span").text(),e.select("a").attr("href") )); } } //小说 for(Element e : elementsXs){ if(!e.select("a").attr("href").isEmpty() && !e.select("span").text().isEmpty()){ menuBean.getNovelList().add(new ItemBean( e.select("span").text(),e.select("a").attr("href") )); } } //电影 for(Element e : elementsDy){ if(!e.select("a").attr("href").isEmpty() && !e.select("span").text().isEmpty()){ menuBean.getVedioList().add(new ItemBean( e.select("span").text(),e.select("a").attr("href") )); } } return menuBean; } public static VedioListBean parseVideoList(String response){ VedioListBean vedioListBean = new VedioListBean(); Document document = Jsoup.parse(response); Elements elements = document.getElementsByClass("indexvod").select("li"); for(Element e:elements){ vedioListBean.getVedioList().add(new VedioListItemBean(e.select("a").attr("title"),e.select("a").attr("href") ,e.select("img").attr("src"),e.select("span").text())); } Element page = document.getElementsByClass("page").get(0); String s = page.select("input ").attr("onclick").replace("pagego('","").replace(")",""); String info[] = s.split("',"); vedioListBean.setPageControlBean(new PageControlBean(page.select("span").text(), page.getElementsContainingText("首页").attr("href"), page.getElementsContainingText("尾页").attr("href"), page.getElementsContainingText("下一页").attr("href"), page.getElementsContainingText("上一页").attr("href"), info[0],info[1])); return vedioListBean; } public static String parseVideoDetial(String response){ Log.w("aaa","begin"); Document document = Jsoup.parse(response); Elements elements = document.getElementsByClass("player").select("script"); String string = elements.get(0).data(); int index1 = string.indexOf("http"); int index2 = string.indexOf("m3u8"); String realUrl = ""; try { realUrl = ParseUtil.parseUrl(NativeUtil.ascii2Native(string.substring(index1,index2)+"m3u8").replace("\\","")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } LogUtil.log(realUrl); return realUrl; } public static NovelListBean parseNovelList(String response){ try { NovelListBean novelListBean = new NovelListBean(); Document document = Jsoup.parse(response); Elements elements = document.getElementsByClass("artlist").select("ul"); for(Element element:elements){ novelListBean.getNovelList().add(new NovelListItemBean(element.select("a").attr("title"),element.select("a").attr("href"),element.select("font").text())); } Element page = document.getElementsByClass("page").get(0); String s = page.select("input ").attr("onclick").replace("pagego('","").replace(")",""); String info[] = s.split("',"); novelListBean.setPageControlBean(new PageControlBean(page.select("span").text(), page.getElementsContainingText("首页").attr("href"), page.getElementsContainingText("尾页").attr("href"), page.getElementsContainingText("下一页").attr("href"), page.getElementsContainingText("上一页").attr("href"), info[0],info[1])); return novelListBean; }catch (Exception e){ return null; } } public static String parseNovelDetial(String response){ Document document = Jsoup.parse(response); Elements elements = document.getElementsByClass("cont"); return elements.text(); } public static ArrayList<String> parsePictureDetial(String response){ ArrayList<String> arrayList = new ArrayList<>(); Document document = Jsoup.parse(response); Elements elements = document.getElementById("postmessage").select("img"); for (Element element:elements){ arrayList.add(element.attr("src")); } return arrayList; } }
Java
UTF-8
11,020
2.015625
2
[]
no_license
package com.frostox.calculo.activities; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.firebase.client.DataSnapshot; import com.firebase.client.Firebase; import com.firebase.client.FirebaseError; import com.firebase.client.Query; import com.firebase.client.ValueEventListener; import com.firebase.ui.FirebaseRecyclerAdapter; import com.frostox.calculo.Nodes.Usermcq; import com.frostox.calculo.Nodes.Usertopics; import com.squareup.picasso.Picasso; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import calculo.frostox.com.calculo.R; public class Result extends AppCompatActivity { private FirebaseRecyclerAdapter recyclerAdapter, recyclerAdapter2; private Firebase usertopicref, usermcqref; private String userkey; private String[] topickey, mcqtopickey; private RecyclerView recyclerView, recyclerView2; private boolean topicmode = true; int counter, count1, count2; private Button clear; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_result); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); recyclerView = (RecyclerView) findViewById(R.id.rv); recyclerView2 = (RecyclerView) findViewById(R.id.rv2); clear = (Button)findViewById(R.id.clear); recyclerView.setVisibility(View.VISIBLE); final LinearLayoutManager llm2 = new LinearLayoutManager(this); llm2.setOrientation(LinearLayoutManager.VERTICAL); Intent intent = this.getIntent(); userkey = intent.getStringExtra("userkey"); usertopicref = new Firebase("https://extraclass.firebaseio.com/users/" + userkey + "/topics"); usermcqref = new Firebase("https://extraclass.firebaseio.com/users/" + userkey + "/mcqs"); getKey(usertopicref); checkmcqs(); // recyclerAdapter = new FirebaseRecyclerAdapter<Usertopics, DataObjectHolder>(Usertopics.class, R.layout.resulttopicitem, DataObjectHolder.class, usertopicref) { @Override public void populateViewHolder(DataObjectHolder dataObjectHolder, final Usertopics usertopics, final int position) { dataObjectHolder.label.setText(usertopics.getName()); dataObjectHolder.difficulty.setText("Difficulty: " + usertopics.getDifficulty()); dataObjectHolder.date.setText("Date: " + usertopics.getTimestamp()); dataObjectHolder.score.setText("Score: "+usertopics.getScore()); dataObjectHolder.ll.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { recyclerView2.setVisibility(View.VISIBLE); counter = 1; topicmode = false; Query query1 = usermcqref.orderByChild("topic").equalTo(topickey[position]); recyclerAdapter2 = new FirebaseRecyclerAdapter<Usermcq, MyViewHolder>(Usermcq.class, R.layout.navresultitem, MyViewHolder.class, query1) { @Override public void populateViewHolder(MyViewHolder myViewHolder, final Usermcq usermcq, final int position2) { myViewHolder.questionnumber.setText("Q." + (position2+1)); if (usermcq.getType().equals("text")) { myViewHolder.question.setText(usermcq.getQuestion()); myViewHolder.answer.setText(usermcq.getAnswer()); // Picasso.with(getBaseContext()).load("http://www.frostox.com/extraclass/uploads/"); // Picasso.with(getBaseContext()).load("http://www.frostox.com/extraclass/uploads/"); myViewHolder.imgquestion.setVisibility(View.GONE); myViewHolder.imganswer.setVisibility(View.GONE); } else if (usermcq.getType().equals("image")) { myViewHolder.question.setText(""); myViewHolder.answer.setText(""); myViewHolder.imgquestion.setVisibility(View.VISIBLE); myViewHolder.imganswer.setVisibility(View.VISIBLE); Picasso.with(getBaseContext()).load("http://www.frostox.com/extraclass/uploads/" + usermcq.getMcqid() + "quest").into(myViewHolder.imgquestion); String answer = usermcq.getState().substring(usermcq.getState().length() - 1); Picasso.with(getBaseContext()).load("http://www.frostox.com/extraclass/uploads/" + usermcq.getMcqid() + answer).into(myViewHolder.imganswer); } if (usermcq.getState().contains("Correct")) myViewHolder.ct.setImageResource(R.drawable.mark); else if (usermcq.getState().contains("Wrong")) myViewHolder.ct.setImageResource(R.drawable.cross); else if (usermcq.getState().contains("Skip")) myViewHolder.ct.setImageResource(R.drawable.skip); } }; notifyItemInserted(position); recyclerView2.setLayoutManager(llm2); recyclerView2.setAdapter(recyclerAdapter2); clear.setVisibility(View.GONE); recyclerView.setVisibility(View.GONE); } }); } }; LinearLayoutManager llm = new LinearLayoutManager(this); llm.setOrientation(LinearLayoutManager.VERTICAL); recyclerView.setLayoutManager(llm); recyclerView.setAdapter(recyclerAdapter); } private static class DataObjectHolder extends RecyclerView.ViewHolder { public TextView label; public TextView difficulty; public TextView date; public TextView score; public LinearLayout ll; public DataObjectHolder(View itemView) { super(itemView); label = (TextView) itemView.findViewById(R.id.recycler_view_item_text); difficulty = (TextView) itemView.findViewById(R.id.difficulty); date = (TextView) itemView.findViewById(R.id.date); score = (TextView) itemView.findViewById(R.id.score); ll = (LinearLayout) itemView.findViewById(R.id.ll); } } public static class MyViewHolder extends RecyclerView.ViewHolder { public ImageView imgquestion; public ImageView imganswer; public ImageView ct; public TextView questionnumber; public TextView answer; public TextView question; public MyViewHolder(View v) { super(v); ct = (ImageView) v.findViewById(R.id.ct); imganswer = (ImageView) v.findViewById(R.id.imganswer); imgquestion = (ImageView) v.findViewById(R.id.imgquestion); questionnumber = (TextView) v.findViewById(R.id.questionnumber); question = (TextView) v.findViewById(R.id.question); answer = (TextView) v.findViewById(R.id.answer); } } @Override public void onBackPressed() { // super.onBackPressed(); if (!topicmode) { Log.d("checking", "" + topicmode); recyclerView2.setVisibility(View.GONE); recyclerView.setAdapter(recyclerAdapter); clear.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.VISIBLE); topicmode = true; } else { finish(); return; } } @Override protected void onDestroy() { super.onDestroy(); recyclerAdapter.cleanup(); if (!topicmode) { recyclerAdapter2.cleanup(); } } public void Clear(View v) { // recyclerView.setVisibility(View.GONE); usermcqref.removeValue(); } public void getKey(Query query) { query.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { count1 = 0; int length = (int) dataSnapshot.getChildrenCount(); topickey = new String[length]; for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) { topickey[count1] = postSnapshot.getKey(); Usertopics usertopics = postSnapshot.getValue(Usertopics.class); Log.d("Checkingtopic", topickey[count1]); count1++; } } @Override public void onCancelled(FirebaseError firebaseError) { System.out.println("The read failed: " + firebaseError.getMessage()); } }); } public void checkmcqs() { usermcqref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { count2 = 0; int length = (int) dataSnapshot.getChildrenCount(); mcqtopickey = new String[length]; for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) { Usermcq usermcq = postSnapshot.getValue(Usermcq.class); mcqtopickey[count2] = usermcq.getTopic(); Log.d("Checkingmcqtopic", mcqtopickey[count2]); count2++; } Set<String> VALUES = new HashSet<String>(Arrays.asList(mcqtopickey)); for (int i = 0; i < count1; i++) { if (!VALUES.contains(topickey[i])) { usertopicref.child(topickey[i]).removeValue(); // Log.d("Checkingloop",""+i); } } getKey(usertopicref); } @Override public void onCancelled(FirebaseError firebaseError) { System.out.println("The read failed: " + firebaseError.getMessage()); } }); } }
TypeScript
UTF-8
912
2.578125
3
[]
no_license
import fs from "fs"; import fetch from 'node-fetch' import { Folders } from '../enums' const category: Folders = Folders.skinsCharacter test('resolver getSkins return the correct files URLs that are on the server', () => { const references: string[] = [] const images: string[] = fs.readdirSync(`public/skins/${category}/`) images.forEach((image: string) => { references.push(`http://localhost:4000/skins/${category}/${image}`) }) const query = ` { getSkins(category: skinsCharacter) } `; fetch(`http://localhost:4000/graphql`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', }, body: JSON.stringify({ query }) }).then(response => response.json()).then((json) => { expect(json.data.getSkins).toEqual(references) }) })
Markdown
UTF-8
14,624
3.890625
4
[]
no_license
## Chapter 3 线性方程组的解法 ### 3.1 基本概念 1、$n$元矩阵表示:$Ax=B$ 2、解:$x_1^*,\cdots,x^*_n$ 3、解法: - 直接法:用计算公式直接求出 - 迭代法:用迭代公式计算出满足精度要求近似解(逼近) ### 3.2 线性方程组的迭代解法 *类似非线性方程求根的简单迭代法,Jacobi迭代法、Seidel迭代法及Sor法等。* 基本思想:将线性方程组$Ax=B$等价变形为$x=Bx+g$,然后构造向量迭代公式: $x^{(k+1)}=Bx^{(k)}+g,k=0,1,2,\cdots$ 给定一个初始向量$x^{(0)}$,带入迭代公式计算$x^{(1)},x^{(2)},\cdots$ #### 3.2.1 迭代公式构造 1、Jacobi迭代公式构造 $\left\{\begin{array}{c} a_{11}x_1+a_{12}x_2+\cdots+a_{1n}x_n=b_1 \\ a_{21}x_1+a_{22}x_2+\cdots+a_{2n}x_n=b_2 \\ \vdots \\ a_{n1}x_1+a_{n2}x_2+\cdots+a_{nn}x_n=b_n \end{array} \right.\Leftrightarrow \left\{\begin{array}{c} x_1=\dfrac{1}{a_{11}}(b_1-a_{12}x_2-a_{13}x_3-\cdots-a_{1n}x_n)\\ x_2=\dfrac{1}{a_{22}}(b_2-a_{21}x_1-a_{23}x_3-\cdots-a_{2n}x_n)\\ \vdots \\ x_n=\dfrac{1}{a_{nn}}(b_n-a_{n1}x_1-a_{n2}x_2-\cdots-a_{nn-1}x_{n-1}) \end{array} \right.$ 写成Jacobi迭代格式: $\left\{\begin{array}{c} x_1^{(k+1)}=\dfrac{1}{a_{11}}(b_1-a_{12}x_2^{(k)}-a_{13}x_3^{(k)}-\cdots-a_{1n}x_n^{(k)})\\ x_2^{(k+1)}=\dfrac{1}{a_{22}}(b_2-a_{21}x_1^{(k)}-a_{23}x_3^{(k)}-\cdots-a_{2n}x_n^{(k)})\\ \cdots \\ x_n^{(k+1)}=\dfrac{1}{a_{nn}}(b_n-a_{n1}x_1^{(k)}-a_{n2}x_2^{(k)}-\cdots-a_{nn-1}x_{n-1}^{(k)}) \end{array} \right.$ 2、 Seidel迭代公式构造(Jacobi的改进,但不能取代) $\left\{\begin{array}{c} x_1^{(k+1)}=\dfrac{1}{a_{11}}(b_1-a_{12}x_2^{(k)}-a_{13}x_3^{(k)}-\cdots-a_{1n}x_n^{(k)})\\ x_2^{(k+1)}=\dfrac{1}{a_{22}}(b_2-a_{21}x_1^{(k+1)}-a_{23}x_3^{(k)}-\cdots-a_{2n}x_n^{(k)})\\ \cdots \\ x_n^{(k+1)}=\dfrac{1}{a_{nn}}(b_n-a_{n1}x_1^{(k+1)}-a_{n2}x_2^{(k+1)}-\cdots-a_{nn-1}x_{n-1}^{(k+1)}) \end{array} \right.$ 3、Sor迭代公式构造(Seidel的改进,*超松弛迭代法*) 用Seidel迭代格式算出的$x^{(k+1)}$记为$\tilde{x}^{(k+1)}$得到增量:$\Delta x=\tilde{x}^{(k+1)}-x^{(k)}$,做增量加速处理($\omega$松弛因子) $x^{(k+1)}=x^{(k)}+\omega\Delta x=(1-\omega)x^{(k)}+\omega\tilde{x}^{(k+1)}$ #### 3.2.2 向量迭代格式 1、Jacobi向量迭代格式 记:$L=\left[\begin{array}{cccc} 0&0&\cdots&0\\ -a_{21}&0&\cdots&0\\\vdots&\vdots&\ddots&\vdots\\-a_{n1}&-a_{n2}&\cdots&0\end{array}\right]$,$U=\left[\begin{array}{cccc} 0&-a_{12}&\cdots&-a_{2n}\\0&0&\cdots&-a_{2n}\\\vdots&\vdots&\ddots&\vdots\\0&0&\cdots&0\end{array}\right]$,$D=\left[\begin{array}{cccc} a_{11}\\&a_{22}\\&&\ddots\\&&&a_{nn}\end{array}\right]$,$x^{(k)}=\left[\begin{array}{c} x_{1}^{(k)}\\x_{2}^{(k)}\\\vdots\\x_{n}^{(k)}\end{array}\right]$,$b=\left[\begin{array}{c}b_1\\b_2\\\vdots\\b_n\end{array}\right]$ 有: $ \left[\begin{array}{c} x_{1}^{(k+1)}\\x_{2}^{(k+1)}\\\vdots\\x_{n}^{(k+1)}\end{array}\right]=\left[\begin{array}{cccc} a_{11}^{-1}\\&a_{22}^{-1}\\&&\ddots\\&&&a_{nn}^{-1}\end{array}\right]\left[\begin{array}{cccc} 0&-a_{12}&\cdots&-a_{1n}\\ -a_{21}&0&\cdots&-a_{2n}\\\vdots&\vdots&\ddots&\vdots\\-a_{n1}&-a_{n2}&\cdots&0\end{array}\right]\left[\begin{array}{c} x_{1}^{(k)}\\x_{2}^{(k)}\\\vdots\\x_{n}^{(k)}\end{array}\right]+\left[\begin{array}{c}b_1\\b_2\\\vdots\\b_n\end{array}\right] $ $x^{(k+1)}=D^{-1}(L+U)x^{(k)}+D^{(-1)}b\to x^{(k+1)}=B_Jx^{(k)}+g_J$,$B_J$称为Jacobi迭代矩阵。 2、Seidel向量迭代格式 $x^{(k+1)}=D^{-1}(Lx^{(k+1)}+Ux^{(k)}+b)\Rightarrow x^{(k+1)}=(D-L)^{-1}Ux^{(k)}+(D-L)^{-1}b\to x^{(k+1)}=B_Sx^{(k)}+g_S$,$B_S$称为Seidel迭代矩阵。 3、Sor向量迭代格式 $x^{(k+1)}=B_{\omega}x^{(k)}+g_{\omega}$ $B_{\omega}=(D-\omega L)^{-1}[(1-\omega)D+\omega U],g_{\omega}=\omega(D-\omega L)^{-1}b$ 上面三种向量迭代格式可统一写成: $x^{(k+1)}=Bx^{(k)}+g$,$B$为迭代矩阵。 #### 3.2.3 范数 *收敛的本质是距离趋于0,两个实数的距离是绝对值,向量的距离用**范数**描述。* 1、范数定义 设$L$是数域$K$上的一个线性空间,如果定义在$L$上的实值函数$P(x)$满足: 1)$\forall x\in L\Rightarrow P(x)\ge 0,P(x)=0\Leftrightarrow x=0$; 2)$\forall x\in L,\lambda \in K\Rightarrow P(\lambda x)=|\lambda|P(x)$; 3)$\forall x,y\in L\Rightarrow P(x+y)\le P(x)+P(y)$ 则称$P$是$L$的范数,$P(x)$为$x$的一个范数。记$P(x)=||x||_p=||x||$则 1)$||x||\ge 0$且$||x||=0\Leftrightarrow x=0$; 2)$||\lambda x||=|\lambda|\cdot||x||$; 3)$||x+y||\le||x||+||y||$ 2、数值分析中常用的线性空间 1)$n$维向量空间 $R^n$ 2)矩阵空间 $R^{m\times n}$ 3)连续函数空间 $C[a,b]=\{f(x)|f(x)在[a,b]连续\}$ 3、$R^{n\times n}$中范数矩阵定义 略 #### 3.2.4 数值分析中的范数 1、$R^n$中的向量范数 1)$||x||_1=\sum\limits_{k=1}^n|x_k|$ 2)$||x||_2=\sqrt{\sum^n\limits_{k=1}x_k^2}$ 3)$||x||_{\infty}=\max\limits_{1\le k\le n}|x_k|$ 式中向量$x=(x_1,\cdots,x_n)^T$ 2、矩阵算子范数 由范数相容性:$||Ax||\le ||A||||x||$, 矩阵$A$算子范数定义: $||A||_P=\max\limits_{x\in R^n\\x\neq0}\dfrac{||Ax||_P}{||x||_P}$,算子范数$\Rightarrow$矩阵范数,反向不可。 3、$R^{n\times n}$中的矩阵范数 1)列范数:$||A||_1=\max\limits_{1\le j\le n}\sum^n\limits_{i=1}|a_{ij}|$ 2)行范数:$||A||_\infty=\max\limits_{1\le i\le n}\sum^n\limits_{j=1}|a_{ij}|$ 3)$F$范数:$||A||_F=\sqrt{\sum^n\limits_{i,j=1}a^2_{ij}}$,不是算子范数 4)2范数:$||A||_2=\sqrt{\lambda_{\max}}$,$\lambda_{\max}$是$A^TA$的最大特征值 4、范数等价与向量极限 1)范数等价:$m||x||_p\le||x||_q\le M||x||_p,\forall x\in L$ $R^n$上所有范数等价。 2)$\lim\limits_{k\to\infty}x^{(k)}=x^*\Leftrightarrow \lim\limits_{k\to\infty}||x^{(k)}-x^*||=0$ #### 3.2.5 谱半径 1、定义:$A\in R^{n\times n},\lambda_k$是$A$的特征值,$k=1,2,\cdots,n$,称$\rho(A)=\max\limits_{1\le k\le n}|\lambda_k|$为矩阵$A$的谱半径。 2、谱半径与矩阵范数的关系 **定理1** $\rho(A)\le||A||$,$||\cdot||$是任意的矩阵范数。 3、一些关于谱半径的结论 1)$\rho(A^k)=[\rho(A)]^k$ 2)$\forall \varepsilon>0$,存在一种矩阵范数使得$||A||\le\rho(A)+\varepsilon$ 3)当矩阵$A$对称时,$\rho(A)=||A||_2$ 4)当矩阵$A$为方阵时有$\lim\limits_{k\to\infty}A^k=0\Leftrightarrow \rho(A)<1$ #### 3.2.6 迭代收敛定理 1、迭代收敛定理 **定理2** $x^{(k+1)}=Bx^{(k)}+g$对任意$x^{(0)}$都收敛$\Leftrightarrow \rho(B)<1$ 2、迭代收敛判别条件 **判别条件1** (充分条件)若存在迭代矩阵$B$的某种矩阵范数满足$||B||<1$,则$\forall x^{(0)}\in R^n,x^{(k+1)}=Bx^{(k)}+g$产生的迭代序列都收敛到其不动点$x^*$。 **判别条件2** 若$A$为严格对角占优矩阵,则线性方程组$Ax=B$的Jacobi和Seidel迭代对任何初值$x^{(0)}$都收敛。 严格行对角占优矩阵$A=(a_{ij})_{n\times n}$:$|a_{kk}|>\sum\limits^n_{j=1,j\neq k}|a_{kj}|,\forall k$ 严格列对角占优矩阵$A=(a_{ij})_{n\times n}$:$|a_{kk}|>\sum\limits^n_{i=1,i\neq k}|a_{ik}|,\forall k$ *定理:严格对角占优矩阵是非奇异的。* **判别条件3** 若$A$是正定矩阵,则$Ax=B$的Seidel迭代对任何初值$x^{(0)}$都收敛。 正定矩阵:$A$的$k$阶主子式$|.|_k>0,k=1,\cdots,n$ #### 3.2.7 收敛误差估计 **定理4** 设矩阵$B$的某种矩阵范数$||B||<1$,则有: 1、$||x^{(k)}-x^*||\le\dfrac{||B||}{1-||B||}||x^{(k)}-x^{(k-1)}||$ 2、$||x^{(k)}-x^*||\le\dfrac{||B||^k}{1-||B||}||x^{(1)}-x^{(0)}||$ [比较非线性方程求根误差定理](#2.3.5 误差估计) ### 3.3 线性方程组的直接解法 *有Gauss消元法(基础)、LU分解法等。* 三角方程组可以回代求解,一般方程组可用消元的方式华为三角方程组求解。 **基本思想** 先将线性方程组通过**消元方法**化为同解的上三角方程组,然后从该三角方程组中按第n个方程、n-1个方程、……**逐步回代**求出解。 #### 3.3.1 Gauss 消元法 1、Gauss消元法公式构造 记原方程组为:$\left\{\begin{array}{c} a_{11}^{(0)}x_1+a_{12}^{(0)}x_2+\cdots+a_{1n}^{(0)}x_n=b_1^{(0)} \\ a_{21}^{(0)} x_1+a_{22}^{(0)} x_2+\cdots+a_{2n}^{(0)}x_n=b_2^{(0)}\\ \vdots \\ a_{n1}^{(0)}x_1+a_{n2}^{(0)}x_2+\cdots+a_{nn}^{(0)}x_n=b_n^{(0)} \end{array} \right.$ (1)消元 顺序做了n-1次消元后,变为上三角方程组: $\left\{\begin{array}{} a_{11}^{(0)}x_1+a_{12}^{(0)}x_2+\cdots+a_{1n}^{(0)}x_n=b_1^{(0)} \\ a_{22}^{(1)} x_2+\cdots+a_{2n}^{(1)}x_n=b_2^{(1)}\\ \vdots \\ a_{nn}^{(n-1)}x_n=b_n^{(n-1)} \end{array} \right.$ (2)Gauss消元公式 略 #### 3.3.2 Gauss 消元法分析 1、Gauss消元法计算量 | 消元步 | 1 | 2 | … | n-1 | | :------: | :------: | :----------: | :--: | :--: | | 乘法次数 | $(n-1)n$ | $(n-1)(n-2)$ | … | 1×2 | | 除法次数 | $n-1$ | $n-2$ | … | 1 | $N_{消}=\sum\limits^{n-1}_{k=1}k(k+1)+\sum\limits^{n-1}_{k=1}k=\dfrac{n}{3}(n^2-1)+\dfrac{1}{2}n(n-1)$,$N_{回}=\dfrac{1}{2}n(n+1)$ 计算量:$N=\dfrac{n^3}{3}+n^2-\dfrac{n}{3}\approx\dfrac{n^3}{3}$. 2、Gauss消元法矩阵解释 是对$(A,b)$做初等行变换,每次对一个方程做一次消元时,对应的初等矩阵为: $M_{ik}=\left[\begin{array}{ccccccc} 1\\&\ddots\\&&1\\&&\vdots&\ddots\\&&m_{ik}&\cdots&1\\&&&&&\ddots\\&&&&&&1\end{array}\right]$ 3、Gauss消元法可使用的条件 **定理1** $a_{kk}^{(k-1)}\neq 0,\forall k\Leftrightarrow$矩阵$A$的所有顺序主子式$\neq 0$ **定理2** 矩阵$A$的所有顺序主子式$\neq 0$,则Gauss消元法可使用 4、Gauss消元法缺点 **缺点1** 要求$a_{kk}^{(k-1)}\neq 0(k=1,2,\cdots,n)$ **缺点2** 在使用Gauss消元法进行计算机求解时,有时求出的解是错的。 #### 3.3.3 主元消元法 *列主元消元法、全主元消元法* 比较: Gauss消元法:计算时间**最短**,精度**最差**; 全主元法:计算时间**最长**,精度**最高**; 实践表明:列主元法具有良好的数值稳定,且计算量远低于全主元法。 #### 3.3.4 LU 分解法 1、常用的矩阵三角分解 LU分解也成为了矩阵三角分解。常用的分解有三种: 1)Doolittle分解 $A=LU\quad L=\left[\begin{array}{ccc} 1\\l_{21}&1\\\vdots&&\ddots\\l_{n1}&l_{n2}&\cdots&1\end{array}\right],U=\left[\begin{array}{ccc} u_{11}&u_{12}&\cdots&u_{1n}\\&u_{22}&\cdots&u_{2n}\\&&\ddots&\vdots\\&&&u_{nn}\end{array}\right]$ 2)Grout分解 略 3)LDU分解 略 $A=LDU$ 2、基本思想 把一般线性方程组求解问题化为几个三角方程组来解。 $Ax=b\leftrightarrow LUx=b$ $Ax=b\leftrightarrow LDUx=b$ 3、Doolittle分解法公式构造 略 4、Dlittle分解算法 1)$u_{ij}=a_{ij}-\sum\limits^{i-1}_{k=1}l_{ik}u_{kj},i\le j\quad l_{ij}=(a_{ij}-\sum\limits^{j-1}_{k=1}l_{ik}u_{kj})/u_{jj},i>j$,计算出$L$、$U$矩阵 2)回代求解$Ly=b$,解得$y^*$ 3)回代求解$Ux=y^*$,得$Ax=b$的解$x$ 5、$A$可以进行Doolittle分解的条件 **定理1** 非奇异矩阵$A$的Doolittle分解是唯一的。 **定理2** 若$A$ 各阶顺序主子式不为0,则$A$有唯一的Doolittle分解。 *能进行Gauss消元法就能做Doolittle分解。* 6、Doolittle分解的紧凑格式 略 #### 3.3.5 追赶法 是求三对角线性方程组专用的方法。 1、三对角方程组:$\begin{pmatrix} b_1x_1 & c_1x_2& \cdots & \cdots&\cdots \\ \vdots & \ddots & \vdots &\cdots&\cdots\\ \cdots & a_ix_{i-1}& b_ix_{i} & b_{i+1}x_{i+1}&\cdots \\ \vdots & \vdots & \vdots& \ddots& \cdots \\ \cdots & \cdots & \cdots& a_{n}x_{n-1} & b_nx_n \end{pmatrix} =\begin{pmatrix} d_1 \\ \vdots \\ d_i \\ \vdots \\ d_n \end{pmatrix} (i=2,3\cdots n-1)$ 2、追赶法公式推导 3、追赶法求解公式 $q_1=b_1,y_1=d_1$ $\left\{\begin{array}{l}p_k=a_k/q_{k-1}\\ q_k=b_k-p_kc_{k-1}\quad(k=2,3,\cdots,n)\\ y_k=d_k-p_ky_{k-1}\end{array} \right.$ $x_n=y_n/q_n$ $x_k=(y_k-c_kx_{k+1})/q_k\quad (k=n-1,\cdots,1)$ 用追赶法来求解三对角线性方程组,计算量只有$5n-4$。 #### 3.3.6 特殊解法 特殊线性方程组:指系数矩阵有很多0元素或有特殊结构的方程组。 用LU分解法解该类方程组会产生较多无效的零元计算,损失计算效率。因此应构造能去掉其中**无效、重复计算部分**的内容的专用算法。 ### 3.4 线性方程组解对系数的敏感性 概念描述:指由于**系数的变化**(扰动),导致所求**解的变化**情况。 #### 3.4.1 系数敏感分析 设方程组$Ax=b$的解为$x^*$,系数扰动后对应的线性方程组为 $(A+\delta A)x=b+\delta b$ 又设扰动方程组的准确解为$x^*+\delta x$有 $Ax^*=b;\quad (A+\delta A)(x^*+\delta x)=b+\delta b$ 系数敏感对解的相对误差用$\dfrac{||\delta x||}{||x^*||}$的大小来描述。 1)考虑$\delta A=0$,即$Ax=b+\delta b$ 有$Ax^*=b,A(x^*+\delta x)=b+\delta b$ (过程略) $\dfrac{||\delta x||}{||x^*||}\le||A||\cdot||A^{-1}||\cdot\dfrac{||\delta b||}{||b||}$ 2)考虑$\delta b=0$,即$(A+\delta A)=b$ 可得:$\dfrac{||\delta x||}{||x^*||}\le\dfrac{||A||\cdot||A^{-1}||\cdot\dfrac{||\delta A||}{||A||}}{1-||A||\cdot||A^{-1}||\cdot\dfrac{||\delta A||}{||A||}}$ 3)一般情况$(A+\delta A)x=b+\delta b$ 可得:$\dfrac{||\delta x||}{||x^*||}\le\dfrac{||A||\cdot||A^{-1}||}{1-||A||\cdot||A^{-1}||\cdot\dfrac{||\delta A||}{||A||}}\left(\dfrac{||\delta A||}{||A||}+\dfrac{||\delta b||}{||b||}\right)$ 矩阵$A$的条件数:$Cond_p(A)=||A||_p\cdot||A^{-1}||_p,p=1,2,\infty$ 注: - $Cond_p(A)$的值与矩阵范数有关,但相对大小一致。 - 条件数值越大,解对系数越敏感,方程组越病态。 条件数性质: 1、$A$可逆$\Rightarrow Cond_p(A)\ge 1$ 2、$A$可逆$\Rightarrow Cond_p(\alpha A)=Cond_p(A),\forall \alpha\in R,\alpha\neq 0$ 3、$A$正交$\Rightarrow Cond_2(A)=1$ 病态矩阵特点: 1、行列式某些行、列近似相关; 2、元素间相差大数量级,且无规则; 3、主元消去过程中出现小主元; 4、特征值相差大数量级。 设$\overline{x}$是线性方程组$Ax=b$的近似解,称$r=A\overline{x}-b$为方程的**残向量**(或残量) 当矩阵$A$非病态时,残量可刻画近似解的准确程度。 $\dfrac{||\overline{x}-x^*||}{||x^*||}\le Cond(A)\dfrac{||r||}{||b||}$ ---
C
UTF-8
352
3.359375
3
[]
no_license
#include <stdio.h> #include <unistd.h> void printz() { sleep(1); } void bar() { sleep(1); printz(); sleep(1); } void foo() { sleep(1); bar(); sleep(1); } int main() { int a = 0; int b = 1; int c = 2; while (1) { printf("a=%d b=%d c=%d *c=%d=%08x\n",a,b,c,&c,&c); c++; bar(); foo(); sleep(1); } }
C#
UTF-8
3,965
2.890625
3
[ "MIT" ]
permissive
using ReverseRegex.Extensions; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; namespace ReverseRegex { class Program { static void Main(string[] args) { // FIXME: Console unicode support varies widely, do not use console Console.InputEncoding = Console.OutputEncoding = Encoding.Unicode; ConsoleHelper.Initialise(); string? regexStr = null; bool caseSensitive = true; for (int i = 0; i < args.Length; i++) { if(args[i].StartsWith("--")) { switch(args[i].Substring(2)) { case "file": { i++; if (i >= args.Length) { Console.Error.WriteLine("Expected a file path"); return; } var path = new StringBuilder(); for(; i < args.Length && !args[i].StartsWith("--"); i++) { if(path.Length > 0) { path.Append(' '); } path.Append(args[i]); } i--; try { regexStr = File.ReadAllText(path.ToString()); } catch (Exception e) { Console.Error.WriteLine(e.Message); return; } } break; case "case-insensitive": caseSensitive = false; break; case "regex": { var regexBuilder = new StringBuilder(); for (i++; i < args.Length; i++) { if (regexBuilder.Length > 0) { regexBuilder.Append(' '); } regexBuilder.Append(args[i]); } regexStr = regexBuilder.ToString(); } break; } } } if(regexStr is null) { Console.Write("Regex> "); regexStr = Console.ReadLine(); } Regex regex; try { regex = Regex.Build(regexStr, new RegexOptions { CaseSensitive = caseSensitive }); } catch (RegexParseException e) { e.Print(); return; } catch (Exception e) { Console.Error.WriteLine(e.Message); return; } var rng = new Random(); ConsoleKeyInfo response; do { Console.WriteLine($"Sample: {regex.GenerateSample(rng)}"); Console.Write("Generate another? (y/n) "); response = Console.ReadKey(); Console.WriteLine(); } while (response.KeyChar == 'y'); } } }
Go
UTF-8
343
3.28125
3
[]
no_license
package main import ( "math/rand" "time" ) func randomString(length int) string { rand.Seed(time.Now().UnixNano()) characters := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" returnString := "" for i := 0; i < length; i++ { returnString += string(characters[rand.Intn(len(characters))]) } return returnString }
Python
UTF-8
1,754
2.765625
3
[]
no_license
# -*- coding: utf-8 import pandas as pd import dask.dataframe as dd import fastparquet as fp import glob from pprint import pprint from dask import delayed pd.set_option('display.expand_frame_repr', False) def transform_one(series): """Takes a Series object representing a grouped dataframe row, and returns a string (serialized JSON). :return: dict """ data = series.to_dict() if not data: return pd.Series([], name='data') (customer, url, ts, _) = data.pop('index') page_views = data.pop('views') visitors = data.pop('visitors') data.update({ 'customer': customer, 'url': url, 'ts': ts.strftime('%Y-%m-%dT%H:%M:%S'), 'metrics': {'views': page_views, 'visitors': visitors} }) return pd.Series([data], name='data') if __name__ == '__main__': file_names = glob.glob('./events/*/*/*/*/*/part*.parquet') pf = fp.ParquetFile(file_names, root='./events') pf.cats = {'customer': pf.cats['customer']} dfs = (delayed(pf.read_row_group_file)(rg, pf.columns, pf.cats) for rg in pf.row_groups) df = dd.from_delayed(dfs) # round datetimes down to an hour df['ts'] = df['ts'].dt.floor('1H') # group on customer, timestamp (rounded) and url gb = df.groupby(['customer', 'url', 'ts']) df = gb.apply(lambda d: pd.DataFrame({ 'views': len(d), 'visitors': d.session_id.count(), 'referrers': [d.referrer.tolist()]}), meta={'views': int, 'visitors': int, 'referrers': int}) # I want index to be a part of dataframe, so it is passed # to the next .apply call. df['index'] = df.index df = df.apply(transform_one, axis=1, meta={'data': str}).to_bag() pprint(df.compute())
Java
UTF-8
398
2.234375
2
[]
no_license
package pathfind; import item.Inventory; import item.Item; import item.ItemTemplate; import java.util.ArrayList; import world.Block; import world.World; public class ConditionItem implements Condition { public String t; public ConditionItem(String t){ this.t = t; } @Override public boolean suits(Block b){ return World.getInstance().items.getInventory(b).suitsConditionFree(t); } }
C#
UTF-8
4,346
2.703125
3
[ "MIT" ]
permissive
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ModelImporter.cs" company="Helix Toolkit"> // Copyright (c) 2014 Helix Toolkit contributors // </copyright> // <summary> // Imports a model from a file. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace HelixToolkit.Wpf { using System; using System.IO; using System.Windows.Media.Media3D; using System.Windows.Threading; /// <summary> /// Imports a model from a file. /// </summary> public class ModelImporter { /// <summary> /// Initializes a new instance of the <see cref="ModelImporter"/> class. /// </summary> public ModelImporter() { this.DefaultMaterial = Materials.Blue; } /// <summary> /// Gets or sets the default material. /// </summary> /// <value> /// The default material. /// </value> public Material DefaultMaterial { get; set; } /// <summary> /// Loads a model from the specified path. /// </summary> /// <param name="path">The path.</param> /// <param name="dispatcher">The dispatcher used to create the model.</param> /// <param name="freeze">Freeze the model if set to <c>true</c>.</param> /// <returns>A model.</returns> /// <exception cref="System.InvalidOperationException">File format not supported.</exception> public Model3DGroup Load(string path, Dispatcher dispatcher = null, bool freeze = false) { if (path == null) { return null; } if (dispatcher == null) { dispatcher = Dispatcher.CurrentDispatcher; } Model3DGroup model; var ext = Path.GetExtension(path); if (ext != null) { ext = ext.ToLower(); } switch (ext) { case ".3ds": { var r = new StudioReader(dispatcher) { DefaultMaterial = this.DefaultMaterial, Freeze = freeze }; model = r.Read(path); break; } case ".lwo": { var r = new LwoReader(dispatcher) { DefaultMaterial = this.DefaultMaterial, Freeze = freeze }; model = r.Read(path); break; } case ".obj": { var r = new ObjReader(dispatcher) { DefaultMaterial = this.DefaultMaterial, Freeze = freeze }; model = r.Read(path); break; } case ".objz": { var r = new ObjReader(dispatcher) { DefaultMaterial = this.DefaultMaterial, Freeze = freeze }; model = r.ReadZ(path); break; } case ".stl": { var r = new StLReader(dispatcher) { DefaultMaterial = this.DefaultMaterial, Freeze = freeze }; model = r.Read(path); break; } case ".off": { var r = new OffReader(dispatcher) { DefaultMaterial = this.DefaultMaterial, Freeze = freeze }; model = r.Read(path); break; } case ".ply": { var r = new PlyReader(dispatcher) { DefaultMaterial = this.DefaultMaterial, Freeze = freeze }; model = r.Read(path); break; } default: throw new InvalidOperationException("File format not supported."); } //if (!freeze) //{ // dispatcher.Invoke(new Action(() => model.SetName(Path.GetFileName(path)))); //} return model; } } }
C++
UTF-8
1,841
2.953125
3
[ "MIT" ]
permissive
#pragma once #include "QuickModel/QuickItemBase.h" #include <QObject> class DeviceAddItem : public QuickItemBase { Q_OBJECT Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged) Q_PROPERTY(QString address READ address WRITE setAddress NOTIFY addressChanged) Q_PROPERTY(QString modelString READ modelString WRITE setModelString NOTIFY modelStringChanged) Q_PROPERTY(bool online READ online WRITE setOnline NOTIFY onlineChanged) public: explicit DeviceAddItem(QObject *parent = nullptr); const QString &name() const { return m_name; } const QString &address() const { return m_address; } const QString &modelString() const { return m_modelString; } bool online() const { return m_online; } public slots: void setName(const QString &name) { if (m_name == name) return; m_name = name; emit nameChanged(m_name); } void setAddress(const QString &address) { if (m_address == address) return; m_address = address; emit addressChanged(m_address); } void setModelString(const QString &modelString) { if (m_modelString == modelString) return; m_modelString = modelString; emit modelStringChanged(m_modelString); } void setOnline(bool online) { if (m_online == online) return; m_online = online; emit onlineChanged(m_online); } signals: void nameChanged(const QString &name); void addressChanged(const QString &address); void modelStringChanged(const QString &modelString); void onlineChanged(bool online); private: QString m_name; QString m_address; QString m_modelString; bool m_online; };
Swift
UTF-8
1,282
2.921875
3
[ "MIT" ]
permissive
// // PhotoPersistenceHelper.swift // PhotoJournal-Assignment // // Created by Pursuit on 10/3/19. // Copyright © 2019 Pursuit. All rights reserved. // import Foundation struct PhotoPersistenceHelper { private init() {} private let persistenceHelper = PersistenceHelper<Photo>(fileName: "photoJournals.plist") static let manager = PhotoPersistenceHelper() func save(newPhoto: Photo) throws { try persistenceHelper.save(newElement: newPhoto) } func getPhotos() throws -> [Photo] { return try persistenceHelper.getObjects() } func deletePhoto(specificID: Int) throws { do { let photos = try getPhotos() let newPhotos = photos.filter { $0.id != specificID} try persistenceHelper.replace(elements: newPhotos) } } func overwritePhoto(photo: Photo, id: Int) throws { let photos = try getPhotos() var oldIndex = Int() //get original photo index for (index, photo) in photos.enumerated() { if photo.id == id { oldIndex = index } } try persistenceHelper.saveAtIndex(newElement: photo, indexToSaveAt: oldIndex) try deletePhoto(specificID: id) } }
Java
UTF-8
1,490
3.609375
4
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ForkJoin; import java.util.Scanner; import java.util.concurrent.RecursiveTask; public class Fibonacci extends RecursiveTask<Long> { long n; boolean dividido; public Fibonacci(long n, boolean dividido) { this.n = n; this.dividido = dividido; } @Override protected Long compute() { if (dividido == true) { return this.fibo(n); } Fibonacci f1 = new Fibonacci(n - 1, true); Fibonacci f2 = new Fibonacci(n - 2, true); f1.fork(); f2.fork(); long f1R = f1.join(); long f2R = f2.join(); return f1R + f2R; } public long fibo(long n){ if (n <= 1) { return n; } return fibo(n-1) + fibo(n-2); } public static void main(String[] args) { long ms = System.currentTimeMillis(); System.out.println(Fibo.fibo(45)); System.out.println("Sem Fork: " + (System.currentTimeMillis() - ms)); ms = System.currentTimeMillis(); Fibonacci fibonacci = new Fibonacci(45, false); System.out.println(fibonacci.compute()); System.out.println("Com Fork: " + (System.currentTimeMillis() - ms)); } }
Java
UTF-8
1,004
1.992188
2
[]
no_license
package cn.bx.bframe.service; import java.io.Serializable; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import cn.bx.bframe.entity.BaseBean; import cn.bx.bframe.mapper.SqlMapper; public abstract class DefaultService<M extends SqlMapper<T>, T extends BaseBean> extends BaseService{ // spring4 泛型限定依赖注入 protected M sqlMapper; @Autowired public void setSqlMapper(M mapper) { this.sqlMapper = mapper; } public SqlMapper<T> getMapper() { return sqlMapper; } public List<T> list(Object parameter) { return getMapper().list(parameter); } public T get(Serializable id) { return getMapper().get(id); } public int add(T obj) { return getMapper().add(obj); } public int save(T obj) { return getMapper().save(obj); } public int remove(Serializable id) { return getMapper().remove(id); } public int removeList(String[] ids) { return getMapper().removeList(ids); } }
C++
UTF-8
4,660
2.765625
3
[ "Apache-2.0" ]
permissive
// Copyright 2020 The Pigweed Authors // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // https://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. #include "pw_allocator/block.h" namespace pw::allocator { Status Block::Init(const span<std::byte> region, Block** block) { // Ensure the region we're given is aligned and sized accordingly if (reinterpret_cast<uintptr_t>(region.data()) % alignof(Block) != 0) { return Status::INVALID_ARGUMENT; } if (region.size() < sizeof(Block)) { return Status::INVALID_ARGUMENT; } union { Block* block; std::byte* bytes; } aliased; aliased.bytes = region.data(); // Make "next" point just past the end of this block; forming a linked list // with the following storage. Since the space between this block and the // next are implicitly part of the raw data, size can be computed by // subtracting the pointers. aliased.block->next = reinterpret_cast<Block*>(region.end()); aliased.block->MarkLast(); aliased.block->prev = nullptr; *block = aliased.block; return Status::OK; } Status Block::Split(size_t head_block_inner_size, Block** new_block) { if (new_block == nullptr) { return Status::INVALID_ARGUMENT; } // Don't split used blocks. // TODO: Relax this restriction? Flag to enable/disable this check? if (Used()) { return Status::FAILED_PRECONDITION; } // First round the head_block_inner_size up to a alignof(Block) bounary. // This ensures that the next block header is aligned accordingly. // Alignment must be a power of two, hence align()-1 will return the // remainder. auto align_bit_mask = alignof(Block) - 1; size_t aligned_head_block_inner_size = head_block_inner_size; if ((head_block_inner_size & align_bit_mask) != 0) { aligned_head_block_inner_size = (head_block_inner_size & ~align_bit_mask) + alignof(Block); } // (1) Are we trying to allocate a head block larger than the current head // block? This may happen because of the alignment above. if (aligned_head_block_inner_size > InnerSize()) { return Status::OUT_OF_RANGE; } // (2) Does the resulting block have enough space to store the header? // TODO: What to do if the returned section is empty (i.e. remaining // size == sizeof(Block))? if (InnerSize() - aligned_head_block_inner_size < sizeof(Block)) { return Status::RESOURCE_EXHAUSTED; } // Create the new block inside the current one. Block* new_next = reinterpret_cast<Block*>( // From the current position... reinterpret_cast<intptr_t>(this) + // skip past the current header... sizeof(*this) + // into the usable bytes by the new inner size. aligned_head_block_inner_size); // If we're inserting in the middle, we need to update the current next // block to point to what we're inserting if (!Last()) { NextBlock()->prev = new_next; } // Copy next verbatim so the next block also gets the "last"-ness new_next->next = next; new_next->prev = this; // Update the current block to point to the new head. next = new_next; *new_block = next; return Status::OK; } Status Block::MergeNext() { // Anything to merge with? if (Last()) { return Status::OUT_OF_RANGE; } // Is this or the next block in use? if (Used() || NextBlock()->Used()) { return Status::FAILED_PRECONDITION; } // Simply enough, this block's next pointer becomes the next block's // next pointer. We then need to re-wire the "next next" block's prev // pointer to point back to us though. next = NextBlock()->next; // Copying the pointer also copies the "last" status, so this is safe. if (!Last()) { NextBlock()->prev = this; } return Status::OK; } Status Block::MergePrev() { // We can't merge if we have no previous. After that though, merging with // the previous block is just MergeNext from the previous block. if (prev == nullptr) { return Status::OUT_OF_RANGE; } // WARNING: This class instance will still exist, but technically be invalid // after this has been invoked. Be careful when doing anything with `this` // After doing the below. return prev->MergeNext(); } } // namespace pw::allocator
PHP
UTF-8
1,748
2.625
3
[]
no_license
<?php class Model_Empresa { protected $_table; public function getTable() { if(null ===$this->_table) { require_once APPLICATION_PATH.'/models/DbTable/Empresa.php'; $this->_table= new Model_DbTable_Empresa; } return $this->_table; } public function lista() { $tab=$this->getTable() ->fetchAll( $this->getTable()->select() ->setIntegrityCheck(false) ->from(array('f' => 'empresa')) )->toArray(); return $tab; } public function ver1($id1) { $table=$this->getTable(); $consulta=$table->select()-> where("id = ?", $id1); return $table->fetchRow($consulta)->toArray(); } public function inclui(array $dados,$img) { $table=$this->getTable(); if($img==NULL){unset ($dados['imagem_inicio']);} else { $dados['imagem_inicio']=$img;} $campos=$table->info(Zend_Db_Table_Abstract::COLS); foreach ($dados as $campo=> $value) { if(!in_array($campo, $campos)) { unset($dados[$campo]); } } return $table->insert($dados); } public function verMaior($id1) { $table=$this->getTable(); $consulta=$table->select()-> where("id > ?", $id1); return $table->fetchRow($consulta)->toArray(); } public function altera(array $dados, $id2, $img) { $table=$this->getTable(); if($img==NULL){unset ($dados['imagem_inicio']);} else { $dados['imagem_inicio']=$img;} $where = $table->getAdapter()->quoteInto('id = ?', $id2); $linhasatualizadas= $table->update($dados, $where); } public function exclui($dados1) { foreach ($dados1 as $valor=>$c) { $table=$this->getTable(); $where = $table->getAdapter()->quoteInto('id = ?', $c); $table->delete($where); } } }
C++
UTF-8
334
2.96875
3
[]
no_license
// Should be compiled with -ftemplate-depth=1000 #include <iostream> template<int N> struct SumMult3or5 { enum { sum = SumMult3or5<N-1>::sum + ((N % 3 == 0 || N % 5 == 0) ? N : 0) }; }; template<> struct SumMult3or5<0> { enum { sum = 0 }; }; int main() { std::cout << SumMult3or5<999>::sum << std::endl; }
Python
UTF-8
1,103
3.09375
3
[ "Apache-2.0" ]
permissive
from itertools import combinations, permutations # outer represents the nodes on the outer ring # inner represents the nodes on the inner ring # on the inner ring, middle represents the nodes in the middle of a line # on the inner ring, end_node represents the nodes on the end of a line lst = range(1, 11) numbers = [] for inner in combinations(lst, 5): total = 55 + sum(inner) if total % 5 == 0: line_sum = total / 5 outer = list(set(lst) - set(inner)) for middle in permutations(inner): end_node = [line_sum - mid - out for mid, out in zip(middle, outer)] if sorted(end_node) == sorted(middle) and all(e != m for e, m in zip(end_node, middle)): # no elements used more than twice and no elements used twice on a line table = zip(outer, middle, end_node) table.sort(reverse=True) table = table[-1:] + table[:-1] digits = ''.join(str(num) for line in table for num in line) if len(digits) == 16: numbers.append(int(digits)) print max(numbers)
Java
UTF-8
13,117
1.796875
2
[]
no_license
/* * Copyright 2013 WTFrobot. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ package wtfrobot.rosjava; import java.util.Date; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.Button; import android.widget.SeekBar; import android.widget.TextView; import android.widget.SeekBar.OnSeekBarChangeListener; import org.ros.address.InetAddressFactory; import org.ros.android.MessageCallable; import org.ros.android.RosActivity; import org.ros.android.view.RosTextView; import org.ros.node.NodeConfiguration; import org.ros.node.NodeMainExecutor; import wtfrobot.rosjava.IsrActivity; import wtfrobot.rosjava.RecognitionListener; import wtfrobot.rosjava.RecognizerTask; import wtfrobot.rosjava.TalkChnString; import wtfrobot.rosjava.TalkEnString; import wtfrobot.rosjava.TalkParam; import edu.cmu.pocketsphinx.demo.R; public class PocketSphinxROS extends RosActivity implements OnTouchListener, RecognitionListener { private RosTextView<std_msgs.String> rosTextView; private TalkParam talker; private TalkEnString talkerenstring; private TalkChnString talkerchnstring; private TalkServo talkerserver; private TalkObject talkerobject; public Button forward,back,right,left,stop,btn_isr_demo,revive; public static boolean send=false,sendenstring=false,sendchnstring=false,sendservo=true,sendobject=false; public Handler handler = new Handler(){}; //servo public TextView Value01,Value02; public static SeekBar servo1; public static SeekBar servo2; public PocketSphinxROS() { // The RosActivity constructor configures the notification title and ticker // messages. super("Pubsub Tutorial", "Pubsub Tutorial"); } //*pocketsphinx*************************************************************************************** static { System.loadLibrary("pocketsphinx_jni"); } /** * Recognizer task, which runs in a worker thread. */ RecognizerTask rec; /** * Thread in which the recognizer task runs. */ Thread rec_thread; /** * Time at which current recognition started. */ Date start_date; /** * Number of seconds of speech. */ float speech_dur; /** * Are we listening? */ boolean listening; /** * Progress dialog for final recognition. */ ProgressDialog rec_dialog; /** * Performance counter view. */ static TextView performance_text; /** * Editable text view. */ public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: start_date = new Date(); this.listening = true; this.rec.start(); break; case MotionEvent.ACTION_UP: if (this.listening) { Log.d(getClass().getName(), "Showing Dialog"); this.rec_dialog = ProgressDialog.show(this, "", "Recognizing speech...", true); this.rec_dialog.setCancelable(false); this.listening = false; } this.rec.stop(); break; default: ; } /* Let the button handle its own state */ return false; } //**************************************************************************************** @SuppressWarnings("unchecked") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); rosTextView = (RosTextView<std_msgs.String>) findViewById(R.id.text); rosTextView.setTopicName("recognizer/output"); rosTextView.setMessageType(std_msgs.String._TYPE); rosTextView.setMessageToStringCallable(new MessageCallable<String, std_msgs.String>() { @Override public String call(std_msgs.String message) { return message.getData(); } }); this.rec = new RecognizerTask(); this.rec_thread = new Thread(this.rec); this.listening = false; Button voice = (Button) findViewById(R.id.Voice); voice.setOnTouchListener(this); performance_text = (TextView) findViewById(R.id.PerformanceText); this.rec.setRecognitionListener(this); this.rec_thread.start(); forward = (Button)findViewById(R.id.forward); back = (Button)findViewById(R.id.back); right = (Button)findViewById(R.id.right); left = (Button)findViewById(R.id.left); stop = (Button)findViewById(R.id.stop); revive = (Button)findViewById(R.id.revive); btn_isr_demo=(Button)findViewById(R.id.btn_isr_demo); Value01 = (TextView)findViewById(R.id.value1); Value02 = (TextView)findViewById(R.id.value2); final SeekBar servo1 = (SeekBar)findViewById(R.id.servo1); //左右 final SeekBar servo2 = (SeekBar)findViewById(R.id.servo2); //上下 servo1.setMax(180); servo1.setProgress(73); servo2.setMax(150); servo2.setProgress(145); forward.setOnTouchListener(new OnTouchListener(){ @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { // Talker.tmpstring="FORWARD" ; dispose.control("forward"); send=true; } else if(event.getAction() == MotionEvent.ACTION_UP) { send=false; sendenstring=true; sendchnstring=true; } return false; } }); back.setOnTouchListener(new OnTouchListener(){ @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { dispose.control("back"); send=true; } else if(event.getAction() == MotionEvent.ACTION_UP) { send=false; sendenstring=true; sendchnstring=true; } return false; } }); left.setOnTouchListener(new OnTouchListener(){ @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { dispose.control("left"); send=true; } else if(event.getAction() == MotionEvent.ACTION_UP) { send=false; sendenstring=true; sendchnstring=true; } return false; } }); right.setOnTouchListener(new OnTouchListener(){ @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { dispose.control("right"); send=true; } else if(event.getAction() == MotionEvent.ACTION_UP) { send=false; sendenstring=true; sendchnstring=true; } return false; } }); stop.setOnTouchListener(new OnTouchListener(){ @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { dispose.control("stop"); send = false; } else if(event.getAction() == MotionEvent.ACTION_UP) { sendenstring=true; sendchnstring=true; } return false; } }); btn_isr_demo.setOnTouchListener(new OnTouchListener(){ @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { } else if(event.getAction() == MotionEvent.ACTION_UP) { Intent intent = new Intent(); intent.setClass(PocketSphinxROS.this,IsrActivity.class); startActivity(intent); } return false; } }); revive.setOnTouchListener(new OnTouchListener(){ @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { dispose.control("revive"); } else if(event.getAction() == MotionEvent.ACTION_UP) { send=false; servo1.setProgress(73); servo2.setProgress(145); } return false; } }); servo1.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){ @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if(progress > 150){ Value01.setText("当前角度:" + 0.6 ); TalkServo.pos[0]=0.6; } else{ Value01.setText("当前角度:" + ((float)(progress-90)/100 )); TalkServo.pos[0]=(float)(progress-90)/100; } sendservo=true; } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); servo2.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){ @Override public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) { Value02.setText("当前角度:" +((float)(progress-75)/100)); TalkServo.pos[1]=(float)(progress-75)/100; sendservo=true; } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); } //Voice Control /** Called when partial results are generated. */ public void onPartialResults(Bundle b) { final String hyp = b.getString("hyp"); handler.post(new Runnable() { public void run() { performance_text.setText(hyp); // Talker.tmpstring = hyp; } }); } /** Called with full results are generated. */ public void onResults(Bundle b) { final String hyp = b.getString("hyp"); final PocketSphinxROS that = this; handler.post(new Runnable() { public void run() { // Date end_date = new Date(); performance_text.setText(hyp); dispose.control(hyp); sendenstring=true; send=true; Log.d(getClass().getName(), "Hiding Dialog"); that.rec_dialog.dismiss(); } }); } public void onError(int err) { } @Override protected void init(NodeMainExecutor nodeMainExecutor) { // TODO Auto-generated method stub talker = new TalkParam(); talkerenstring = new TalkEnString(); talkerchnstring = new TalkChnString(); talkerserver = new TalkServo(); talkerobject = new TalkObject(); NodeConfiguration nodeConfiguration = NodeConfiguration.newPublic(InetAddressFactory.newNonLoopback().getHostAddress(), getMasterUri()); // 这里用户已经被提示输入master的URI来开始或启动本地master nodeConfiguration.setMasterUri(getMasterUri()); nodeMainExecutor.execute(talker, nodeConfiguration); nodeMainExecutor.execute(talkerenstring, nodeConfiguration); nodeMainExecutor.execute(talkerchnstring, nodeConfiguration); nodeMainExecutor.execute(talkerserver, nodeConfiguration); nodeMainExecutor.execute(talkerobject, nodeConfiguration); // RosTextView作为显示输入信息是必须存在的 nodeMainExecutor.execute(rosTextView, nodeConfiguration); } /*---------------------------------------------------------------------------------------------------------------------------------*/ }
JavaScript
UTF-8
466
3.640625
4
[ "MIT", "CC-BY-4.0", "LicenseRef-scancode-proprietary-license", "CC-BY-NC-4.0" ]
permissive
//Adapted from https://www.w3schools.com/howto/howto_js_copy_clipboard.asp function copyText(id, text) { /* Get the text field */ var copyText = document.getElementById(id); console.log(text) /* Select the text field */ copyText.select(); copyText.setSelectionRange(0, 99999); /*For mobile devices*/ /* Copy the text inside the text field */ document.execCommand("copy"); /* Alert the copied text */ alert(text.toString() + copyText.value); }
Python
UTF-8
1,203
3.625
4
[]
no_license
#!/usr/bin/env python3 class Holdings: ''' This class is built for containing a portfolio of stock shares. The default constructor receives an open file handle for a csv file. ''' def __init__(self, sharesfile): import csv self.holdings = [] with open(sharesfile,'r') as f: rows = csv.reader(f) header = next(rows) for row in rows: myholding = dict() myholding["name"] = row[0] myholding["date"] = row[1] myholding["shares"] = int(row[2]) myholding["price"] = float(row[3]) self.holdings.append(myholding) def total_assets_value(self): sum = 0 for holding in self.holdings: sum = sum + holding["shares"]*holding["price"] return sum def sell(self, sharename, numshares): import pandas as pd df = pd.DataFrame(self.holdings) if df.name == sharename: df.shares -= numshares ''' for holding in self.holdings: if holding["name"] == name: holding["shares"] -= numshares break '''
C++
UTF-8
2,228
2.96875
3
[ "MIT" ]
permissive
#include <cfloat> #include <cmath> #include <iostream> #include <sstream> #include <vector> using namespace std; double washup(double d) { if (fabs(d - (int)d) < FLT_EPSILON) return (int)(d); if (fabs(d - ((int)d + 1)) < FLT_EPSILON) return ((int)d + 1); if (fabs(d - ((int)d - 1)) < FLT_EPSILON) return ((int)d - 1); return d; } int main() { string str; vector<vector<double>> mat; int cptr = 0, rptr = 0, residual = 0; double temp; bool fail = false; // Input processing. while (getline(cin, str)) { stringstream xstr(str); mat.push_back(vector<double>()); while (xstr >> temp) mat.back().push_back(temp); } // Solve the linear system and print the results. while (cptr != mat.size() && rptr != mat.front().size()) { if (mat[cptr][rptr] == 0) { for (int t = cptr + 1; t != mat.size(); t++) if (mat[t][rptr] != 0) { swap(mat[cptr], mat[t]); continue; } rptr++; continue; } temp = 1.0 / mat[cptr][rptr]; for (int i = 0; i != mat[cptr].size(); i++) mat[cptr][i] = washup(mat[cptr][i] * temp); for (int i = 0; i < mat.size(); i++) { if (i == cptr) continue; temp = mat[i][rptr]; for (int j = 0; j < mat[i].size(); j++) mat[i][j] = washup(mat[i][j] - temp * mat[cptr][j]); } cptr++; rptr++; } for (int i = 0; i < mat.size(); i++) { for (int j = 0; j < mat[i].size() - 1; j++) { if (mat[i][j] != 0) { residual++; goto con; // outside for continue } } if (mat[i].back() != 0) { fail = true; break; } con:; } if (fail) { printf("No solution!"); } else if (residual < mat.front().size() - 1) { printf("No unique solution!"); } else { for (int i = 0; i < mat.size(); i++) { if (i) printf(" "); printf("%.3f", mat[i].back()); } } return 0; }
C++
UTF-8
1,311
3.359375
3
[]
no_license
// By Chandramani Kumar // Keep moving and must be simple bro!!!!! // Espérons le meilleur mais préparez-vous au pire 😎 /* Problem Statement : Given an m x n matrix board where each cell is a battleship 'X' or empty '.', return the number of the battleships on board. Battleships can only be placed horizontally or vertically on board. In other words, they can only be made of the shape 1 x k (1 row, k columns) or k x 1 (k rows, 1 column), where k can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships). Example 1: Input: board = [["X",".",".","X"],[".",".",".","X"],[".",".",".","X"]] Output: 2 Example 2: Input: board = [["."]] Output: 0 Constraints: m == board.length n == board[i].length 1 <= m, n <= 200 board[i][j] is either '.' or 'X'. */ Cpp code : class Solution { public: int countBattleships(vector<vector<char>>& board) { int n = board.size(); int m = board[0].size(); int res = 0; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if((i == 0 || board[i-1][j] != 'X') && (j == 0 || board[i][j-1] != 'X') && board[i][j] == 'X') res++; } } return res; } };
Java
UTF-8
6,574
2
2
[]
no_license
package com.uplink.carins.utils; import android.content.Context; import android.content.res.Resources; import android.view.View; import android.view.ViewGroup; import android.widget.GridView; import android.widget.ImageView; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.RadioButton; import android.widget.RadioGroup; import com.squareup.picasso.Callback; import com.squareup.picasso.Picasso; import com.uplink.carins.Own.AppCacheManager; import com.uplink.carins.Own.Config; import com.uplink.carins.R; import com.uplink.carins.model.api.UserBean; import com.uplink.carins.model.common.NineGridItemBean; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by chingment on 2017/12/18. */ public class CommonUtil { public static void loadImageFromUrl(Context context , final ImageView photoView, String imageUrl) { if (StringUtil.isEmptyNotNull(imageUrl)) { photoView.setBackgroundResource(R.drawable.default_image); } else //.centerCrop() Picasso.with(context).load(imageUrl) .placeholder(R.drawable.default_image).fit().centerInside() .into(photoView, new Callback() { @Override public void onSuccess() { photoView.setVisibility(View.VISIBLE); } @Override public void onError() { photoView.setBackgroundResource(R.drawable.default_image); } }); } public static void setListViewHeightBasedOnChildren(ListView listView) { // 获取ListView对应的Adapter ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) { return; } int totalHeight = 0; for (int i = 0; i < listAdapter.getCount(); i++) { // listAdapter.getCount()返回数据项的数目 View listItem = listAdapter.getView(i, null, listView); listItem.measure(0, 0); // 计算子项View 的宽高 totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度 } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); // listView.getDividerHeight()获取子项间分隔符占用的高度 // params.height最后得到整个ListView完整显示需要的高度 listView.setLayoutParams(params); } public static void setGridViewHeightBasedOnChildren(GridView gridview) { // 获取listview的adapter ListAdapter listAdapter = gridview.getAdapter(); if (listAdapter == null) { return; } // 固定列宽,有多少列 int col = 3;// listView.getNumColumns(); int totalHeight = 0; // i每次加4,相当于listAdapter.getCount()小于等于4时 循环一次,计算一次item的高度, // listAdapter.getCount()小于等于8时计算两次高度相加 for (int i = 0; i < listAdapter.getCount(); i += col) { // 获取listview的每一个item View listItem = listAdapter.getView(i, null, gridview); listItem.measure(0, 0); // 获取item的高度和 totalHeight += listItem.getMeasuredHeight(); } // 获取listview的布局参数 ViewGroup.LayoutParams params = gridview.getLayoutParams(); // 设置高度 params.height = totalHeight+60; // 设置margin ((ViewGroup.MarginLayoutParams) params).setMargins(0, 0, 0, 0); // 设置参数 gridview.setLayoutParams(params); } public static int px2dip(int pxValue) { final float scale = Resources.getSystem().getDisplayMetrics().density; return (int) (pxValue / scale + 0.5f); } public static float dip2px(float dipValue) { final float scale = Resources.getSystem().getDisplayMetrics().density; return (dipValue * scale + 0.5f); } public static void setRadioGroupCheckedByStringTag(RadioGroup testRadioGroup, String checkedtag ) { for (int i = 0; i < testRadioGroup.getChildCount(); i++) { RadioButton rb=(RadioButton)testRadioGroup.getChildAt(i); String tag= String.valueOf(rb.getTag()); if(tag.equals(checkedtag)) { rb.setChecked(true); } } } public static String getCurrentTime() { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date curDate = new Date(System.currentTimeMillis()); String str = formatter.format(curDate); return str; } public static boolean isDateOneBigger(String str1, String str2) { boolean isBigger = false; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date dt1 = null; Date dt2 = null; try { dt1 = sdf.parse(str1); dt2 = sdf.parse(str2); } catch (ParseException e) { e.printStackTrace(); } if (dt1.getTime() > dt2.getTime()) { isBigger = true; } else if (dt1.getTime() < dt2.getTime()) { isBigger = false; } return isBigger; } public static String getExtendedAppUrl(NineGridItemBean item) { //return item.getAction(); UserBean user= AppCacheManager.getUser(); String appId=item.getAppId()+""; String userId=""; String merchantId=""; String posMachineId=""; if(user!=null) { userId= user.getId()+""; merchantId=user.getMerchantId()+""; posMachineId=user.getPosMachineId()+""; } String url=Config.URL.extendedAppGoTo+"?userId="+userId+"&merchantId="+merchantId+"&posMachineId="+posMachineId+"&appId="+appId; return url; } public static String[] getPrice(String price) { String[] arr = new String[]{"0", ".00"}; String[] arrPrice = price.split("\\."); if (arrPrice.length == -1) { arr[0] = price; } else { if (arrPrice.length >= 2) { arr[0] = arrPrice[0]; arr[1] = "." + arrPrice[1]; } } return arr; } }
C++
UTF-8
8,126
2.6875
3
[ "Apache-2.0" ]
permissive
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "GameFramework/Actor.h" #include "LazerBossHand.generated.h" UENUM(BlueprintType) enum class EHandSlamState : uint8 { Idle,//Not Slamming Windup,//Moving back, winding up the slam PreSlam,//Delay before slamming down. Unwind,//Moving hand into slam position MoveDown,//Hand moving towards the ground PostSlam,//After the Slam has occured Reset//Reset back to the Idle Location/Rotation }; UENUM(BlueprintType) enum class EHandState : uint8 { Normal, Stunned }; UCLASS() class SNAKE_PROJECT_API ALazerBossHand : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties ALazerBossHand(); UPROPERTY(VisibleDefaultsOnly, Category = "Component") USceneComponent* RootSceneComponent; UPROPERTY(VisibleDefaultsOnly, Category = "Component") USceneComponent* HandRestComponent; UPROPERTY(VisibleDefaultsOnly, Category = "Component") USceneComponent* AttachmentComponent; UPROPERTY(VisibleDefaultsOnly, Category = "Component") UStaticMeshComponent* MeshComponent; UPROPERTY(VisibleDefaultsOnly, Category = "Component") UBoxComponent* HitBox; UPROPERTY(VisibleDefaultsOnly, Category = "Components") UAudioComponent* SlamAudioComponent; virtual void PostInitializeComponents() override; // Called every frame virtual void Tick( float DeltaSeconds ) override; public: /** Angle the Hand will reach when winding up */ UPROPERTY(EditAnywhere, Category = "Slam|Properties") FRotator WindupTarget; /** Time it takes for the hand to windup */ UPROPERTY(EditAnywhere, Category = "Slam|Properties") float WindupDuration; UPROPERTY(EditAnywhere, Category = "Slam|Properties") float PreSlamDuration; /** Time it takes for the hand to unwind */ UPROPERTY(EditAnywhere, Category = "Slam|Properties") float UnwindDuration; /** Time it takes to slam down */ UPROPERTY(EditAnywhere, Category = "Slam|Properties") float MoveDownDuration; UPROPERTY(EditAnywhere, Category = "Slam|Properties") float PostSlamDuration; UPROPERTY(EditAnywhere, Category = "Slam|Properties") float ResetDuration; /** Start the Slam Sequence */ UFUNCTION(BlueprintCallable, Category = "Slam|Control") void StartSlam(); /** Is the slam state not Idle? */ UFUNCTION(BlueprintPure, Category = "Slam|State") bool IsSlamInprogress() const; /** Is the slam state in a state >= then MoveDown? */ UFUNCTION(BlueprintPure, Category = "Slam|State") bool IsSlamDownInprogress() const; EHandSlamState GetSlamState() const; protected: EHandSlamState SlamState; /** Increment the State by one. If the index exceeds the max, reset to 0 */ UFUNCTION(BlueprintCallable, Category = "Slam|Control") void IncreaseSlamState(); UFUNCTION(BlueprintCallable, Category = "Slam|Control") void SetSlamState(EHandSlamState InState); /** Handle and set the varibles for the new state */ void HandleSlamState(); void InitializeSlamRotation(FRotator TargetRotation); float WindupProgress; float UnwindProgress; /** Get and Set the Correct Slam Progress floats. use the SlamState to determine which variable is modified/retrieved */ void SetSlamProgress(float DeltaTime); float GetSlamProgress(); /** Reset the Slam Progress for the current state. */ void ResetSlamProgress(); /** Get the Slam Duration. Uses SlamState to determine which variable is retrieved */ float GetSlamDuration(); /** Rotate the Hand during both Windup and Unwind state of slam. */ void RotateHandSlam(float DeltaTime); /** Rotation of the hand before windup state. */ UPROPERTY() FRotator InitialHandRotation; /** Initial Rotation for the QLerp */ FRotator InitialActorRotation; /** Target Rotation for the QLerp */ FRotator TargetActorRotation; /** Move the Hand to the TargetActorLocation @ Trigger Event - Event hack, if true trigger the OnSlamDown Event else ignore it */ void SlamDown(float DeltaTime, bool TriggerEvent); /** Blueprint Event triggered when the hand has finished its slam */ UFUNCTION(BlueprintImplementableEvent, Category = "LazerBossHand") void OnSlamDown(); float PreSlamProgress; float MoveDownProgress; float PostSlamProgress; float ResetProgress; /** Location before Movement Lerp */ FVector InitialActorLocation; /** Target Location for movement Lerp */ FVector TargetActorLocation; /** Down Line Trace to check for any blocking volumes. If none are found, use this to offset the current location to get the target */ UPROPERTY() int32 LineTraceHeight; void SlamTick(float DeltaTime); public: DECLARE_DELEGATE(FOnSequenceFinished); FOnSequenceFinished OnSequenceFinished; //DECLARE_DELEGATE_OneParam(FOnStunned, ALazerBossHand*); DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnStunned, ALazerBossHand*, Hand); UPROPERTY(BlueprintAssignable, Category = "Custom Event") FOnStunned OnStunned; DECLARE_DELEGATE_OneParam(FOnNormal, ALazerBossHand*); FOnNormal OnNormal; public: UFUNCTION(BlueprintCallable, Category = "Hand|State") void SetHandState(EHandState InState); /** Is the Hand in the Normal State? */ UFUNCTION(BlueprintPure, Category = "Hand|State") bool IsNormal() const; /** Is the Hand Stunned */ UFUNCTION(BlueprintPure, Category = "Hand|State") bool IsStunned() const; protected: EHandState HandState; public: UPROPERTY(EditAnywhere, Category = "Hand|Stats") FName DataTableRowName; protected: static const FString DataTableContext; UPROPERTY() UDataTable* StatDataTable; public: virtual float TakeDamage(float Damage, struct FDamageEvent const& DamageEvent, AController* EventInstigator, AActor* DamageCauser) override; /** Mark the hand as dead */ void Dead(); UFUNCTION() void OnBeginOverlap(AActor* Other, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& Hit); protected: /** Dead Flag. If true, this hand is dead. The hand should only be dead if called from the head. */ bool bDead; UPROPERTY() int32 MaxHealth; UPROPERTY() int32 Health; UFUNCTION() void SetHealth(int32 InHealth); UFUNCTION() void AddHealth(int32 InHealth); UFUNCTION() void ReduceHealth(int32 Value); public: UFUNCTION(BlueprintPure, Category = "Hand|Health") int32 GetHealth() const; UFUNCTION(BlueprintPure, Category = "Hand|Health") int32 GetMaxHealth() const; public: void SetBossState(uint8 InBossState); UFUNCTION(BlueprintPure, Category = "Hand|Animation") uint8 GetBossState(); UFUNCTION(BlueprintImplementableEvent, Category = "Hand|Animation") void OnStateChange(uint8 LastState, uint8 NewState); /** Trigger the Idle Animation */ UFUNCTION(BlueprintImplementableEvent, Category = "Hand|Animation") void TriggerIdle(); protected: uint8 BossState; public: UFUNCTION(BlueprintNativeEvent, Category = "Hand|Destroy") void HideAndDestroy(); virtual void HideAndDestroy_Implementation(); UPROPERTY(EditAnywhere, Category = "Hand|Destroy") float DestroyTime; UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Bot|Material") FName FractureColorName; /** Dissolve Blend Param Name */ UPROPERTY(EditAnywhere, Category = "Bot|Material|Dissolve") FName DissolveBlendName; /** Dissolve Outline Param Name */ UPROPERTY(EditAnywhere, Category = "Bot|Material|Dissolve") FName DissolveOutlineWidthName; UPROPERTY(EditAnywhere, Category = "Bot|Material|Dissolve") float DissolveOutlineWidth; /** Total time for the duration to complete from start to end */ UPROPERTY(EditAnywhere, Category = "Bot|Material|Dissolve") float DissolveDuration; /** Delay before the dissolve takes place */ UPROPERTY(EditAnywhere, Category = "Bot|Material|Dissolve") float DissolveStartDelay; protected: UPROPERTY(BlueprintReadWrite, Category = "Hand|Material") TArray<UMaterialInstanceDynamic*> DMI; /** if true, Dissolve is in progress */ bool bDissolveInprogress; /** Total time expired of the dissolve process */ float DissolveProgress; FTimerHandle DissolveDelay_TimerHandle; /** Start Dissolving the Hand */ UFUNCTION() void StartDissolve(); UFUNCTION() void SetDissolveBlend(); };
Markdown
UTF-8
980
2.75
3
[]
no_license
--- title: 不删除关联关系表引起的一点思考 date: 2018-03-19 22:13:12 categories: - MySQL tags: - MySQL --- ![image.png](https://upload-images.jianshu.io/upload_images/2875232-0f0cb9fd01d8877c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 三张表,其中一张c是另外两张a,b的关系表。如果仅仅考虑删除的情况,那么只要删除a就行了。不用去碰c表(coding的时候最好别这样做)。 a表相当于指向c表的指针,指针没有了,所指向的内容也就没有了价值。 #### 下面是几个小例子: 1. Windows上无论删除哪里的内容,只是删除了指针。内容还在那里,不增不减。所以,才有恢复数据一说。 2. 在同一个磁盘里剪切是很快的,只是复制了指针。原数据还在那里不动的。不同磁盘间的复制很慢,那是真的在复制东西。所以Linux上 `mv`命令很快。 写不下去了,操作系统知识了解的太少。
C#
UTF-8
27,027
2.78125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Data.SqlClient; using System.Globalization; using System.Reflection; using System.Diagnostics; //Contians problems that must be fixed before push to master [MASTER] //Contains problems that *SHOULD* be fixed before end of alpha phase [ALPHA] //Contains problems that would be nice to resolve [TODO] //Contains potential beta features [BETA] : fault talerance namespace ExperimentalProc.DataBase { public class Server : IDisposable { private string DataBaseConectionString = null; protected SqlConnection connection; public Server() { StreamReader config = new StreamReader(Path.GetDirectoryName(Uri.UnescapeDataString(new UriBuilder(Assembly.GetAssembly(typeof(Server)).CodeBase).Path)) + "/DataBaseConfig.txt"); while (!config.EndOfStream) {//load config functions string[] line = config.ReadLine().Split(':'); if (line[0] == "DataBase Conection String") { DataBaseConectionString = line[1]; }//database conection string //TODO add ADMIN config [ALPHA] } //DataBaseConectionString: Data Source=stusql;Initial Catalog=DanumCenter;Integrated Security=true; //config path: WebApp/Bin/DataBaseConfig.txt try { connection = new SqlConnection(); connection.ConnectionString = DataBaseConectionString; Debug.WriteLine("Connection Made"); Debug.WriteLine(DataBaseConectionString); } catch (SqlException excp) { Debug.WriteLine(DataBaseConectionString); Debug.WriteLine("Connection Failed: " + excp); } } //TODO: Alter this to work with new database [ALPHA] //generic insert into database statment public bool InsertRoomIntoDataBase(string Room_ID, string Room_Name) { SqlCommand cmd = new SqlCommand(); //Convert Room Logic int Room_IDParse; if (int.TryParse(Room_ID, out Room_IDParse)) { //Pre insert Room Logic Here: } else { Debug.WriteLine("Failed to Parse <STRING_ROOM_ID: " + Room_ID + "> too INT"); return false; } //Convert Month Logic string Room_NameParse; if (Room_Name.Length <= 20) { //Pre insert Month Logic Here: Room_NameParse = Room_Name; } else { Debug.WriteLine("Failed to Parse <STRING_ROOM_NAME: " + Room_Name + "> too VARCHAR(20)"); return false; } try { connection.Open(); cmd.Connection = connection; cmd.CommandText = "INSERT INTO Rooms (Room_ID,Room_Name) VALUES(" + Room_IDParse + "," + "'" + Room_NameParse + "'" + "); ";//alter this to be an insert statment cmd.ExecuteNonQuery(); } catch (SqlException excp) { Debug.WriteLine("Failed to run InsertIntoDataBase: " + excp); connection.Close(); return false; } connection.Close(); return true; } //TODO: Alter this to work with new database [ALPHA] //Generic insert Course item to database public bool InsertCourseIntoDataBase(string Class_ID, string Course, string Course_ID) { SqlCommand cmd = new SqlCommand(); //Convert Room Logic int Class_IDParse; if (int.TryParse(Class_ID, out Class_IDParse)) { //Pre insert Room Logic Here: } else { Debug.WriteLine("Failed to Parse <STRING_Class_ID: " + Class_ID + "> too INT"); return false; } //Convert Month Logic string CourseParse; if (Course.Length <= 20) { //Pre insert Month Logic Here: CourseParse = Course; } else { Debug.WriteLine("Failed to Parse <STRING_Course: " + Course + "> too INT"); return false; } //Convert Month Logic string Course_IDParse; if (Course_ID.Length <= 20) { //Pre insert Month Logic Here: Course_IDParse = Course; } else { Debug.WriteLine("Failed to Parse <STRING_MONTH: " + Course_ID + "> too INT"); return false; } try { connection.Open(); cmd.Connection = connection; cmd.CommandText = "INSERT INTO Classes(Class_ID,Class, Course) VALUES(" + (int)300 + "," + "'Gym'" + "," + "'15228'" + "); ";//alter this to insert passed params : CourseQueryString [ALPHA] cmd.ExecuteNonQuery(); } catch (SqlException excp) { Debug.WriteLine("Failed to run InsertIntoDataBase: " + excp); connection.Close(); return false; } connection.Close(); return true; } //!!! User Handle Code!!! //attempts to insert passed values into dataBase. returns false if failed public bool InsertUserIntoDataBase() { SqlCommand cmd = new SqlCommand(); try { connection.Open(); cmd.Connection = connection; cmd.CommandText = "INSERT INTO dbo.USER_REGISTRY(USER_NAME,USER_PASSWORD,USER_PRIVLAGE,USER_ONLINE) VALUES('testUser', '123test', '0', '0'); ";//alter this to insert passed params : CourseQueryString [ALPHA] cmd.ExecuteNonQuery(); } catch (SqlException excp) { Debug.WriteLine("Failed to run InsertIntoDataBase: " + excp); connection.Close(); return false; } connection.Close(); return true; } //Check if user is registered with password public bool RetriveUserFromDataBase(string userName, string password) { bool pass = false; SqlCommand cmd = new SqlCommand("SELECT USER_NAME FROM dbo.USER_REGISTRY WHERE USER_NAME = '" + userName + "' AND USER_PASSWORD = '" + password + "';", connection); try { connection.Open(); if(cmd.ExecuteScalar().ToString() == userName) { pass = true; } else { pass = false; } } catch (SqlException excp) { Debug.WriteLine("Failed to run InsertIntoDataBase: " + excp); connection.Close(); return false; } catch(NullReferenceException excp) { Debug.WriteLine("Failed to run InsertIntoDataBase: " + excp); connection.Close(); return false; } connection.Close(); return pass; } //Retrive UserID public bool RetriveUserID(string userName, out int UserID) { bool pass = false; UserID = 0; SqlCommand cmd = new SqlCommand("SELECT USER_ID FROM dbo.USER_REGISTRY WHERE USER_NAME = '" + userName + "';", connection); try { connection.Open(); UserID = (int) cmd.ExecuteScalar(); if (UserID != 0) { pass = true; } else { pass = false; } } catch (SqlException excp) { Debug.WriteLine("Failed to run RetriveUserID: " + excp); connection.Close(); return false; } connection.Close(); return pass; } //Retrive UserAccessRights public bool RetriveUserRights(int UserID, out int AccessRights) { AccessRights = -1; bool pass = false; SqlCommand cmd = new SqlCommand("SELECT USER_PRIVLAGE FROM dbo.USER_REGISTRY WHERE USER_ID = " + UserID + ";", connection); try { connection.Open(); AccessRights = (int)cmd.ExecuteScalar(); if (AccessRights != -1) { pass = true; } } catch (SqlException excp) { Debug.WriteLine("Failed to run RetriveUserAccessRights: " + excp); connection.Close(); return false; } connection.Close(); return pass; } //Update Session info public bool UpdateUserSession(int UserID, object Session) { SqlCommand cmd = new SqlCommand(); try { connection.Open(); cmd.Connection = connection; cmd.CommandText = "UPDATE dbo.USER_REGISTRY SET USER_SESSION = " + Session + " WHERE USER_ID = "+ UserID +";";//TODO: change this to insert Session as ByteArray cmd.ExecuteNonQuery(); } catch (SqlException excp) { Debug.WriteLine("Failed to run UpdateUserSession: " + excp); connection.Close(); return false; } connection.Close(); return true; } //!!! Calandar Handel Code !!! //retrives info from database and creates a string for inserting to web page public bool RetriveDayItem(int year,int dayID, out string dayItemInfo) { Calandar.CalanderFormater CF = new Calandar.CalanderFormater(year); dayItemInfo = "<label class=DayItem> <h3>" + CF.getMonthByDay(dayID).getDaysIntoMonth(dayID) + "</h3>"; //int valueDay = 1;//deadcode: removed because passed value (dayID) can be assumed to be equivilant int valueCourse = 404;//test value int valueRoom = 404; string valueStartTime = "08:00"; string valueEndTime = "12:00"; string queryString = "SELECT CLASS_ID, ROOM_ID, START_TIME, END_TIME FROM dbo.CALANDER_LIST WHERE LIST_YEAR = " + year + " AND LIST_DAY = " + dayID + ";"; SqlCommand cmd = new SqlCommand(queryString, connection); try { connection.Open(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { valueCourse = (int)reader.GetSqlInt32(0); valueRoom = (int) reader.GetSqlInt32(1); valueStartTime = (string) reader.GetSqlString(2); valueEndTime = (string)reader.GetSqlString(3); dayItemInfo += "<hr />" + valueCourse + " : Room " + valueRoom + " <br /> " + valueStartTime + " - " + valueEndTime + " </label>"; } reader.Close(); connection.Close(); } catch (SqlException excp) { dayItemInfo += "<hr /> failed to read on database"; Debug.WriteLine("failed on read day item" + excp); return false; } return true; } /* Attempts a brute force insert of all data considered valid by target parameters. Does not check against data inside database. If a target parameters are not valid within given context, function will imediantly terminate and no data will be inserted into database [returns false]. Parmeters(implicit): Target Database: Defined by [DataBase Connetion String] in [WebApp/Bin/DataBaseConfig.txt] Parmeters(defined): year(string): target year for upload into database. used by (Calander Logic) and [Calandar/CalanderFormater.cs] month(string): target month to upload target data. if left as (null) or (0) all months will be targeted week(string): target day of week to upload target data. if left as (null) or (0) all weeks will be targeted day(string): target day of target month(s) to upload target data. if left as (null) or (0) all days will be targeted room(string): roomID of target data to upload into database course(string): courseID of target data to upload into database startTime(string): time of day following 12 Clock formated to fit "XX:XX" as a 5 character string, defines begining target time of day for upload into dataBase endTime(string): time of day following 12 Clock formated to fit "XX:XX" as a 5 character string, defines ending target time of day for upload into dataBase */ public bool InsertSchedualItem(string year, string[] month, string[] week, string[] day, string room, string course, string startTime, string endTime) { //Convert Year Logic int yearParse; if (int.TryParse(year, out yearParse)) { //Pre insert Year Logic Here: } else { Debug.WriteLine("Failed to Parse <STRING_YEAR: " + year + "> too INT"); return false; } //Convert Month Logic int[] monthParse = new int[month.Length]; for (int i = 0; i < month.Length; i++) { if (int.TryParse(month[i], out monthParse[i])) { //Pre insert Month Logic Here: } else { Debug.WriteLine("Failed to Parse <STRING_MONTH: " + month[i] + "> too INT"); return false; } } //Convert Week Logic int[] weekParse = new int[week.Length]; for (int i = 0; i < week.Length; i++) { if (int.TryParse(week[i], out weekParse[i])) { //Pre insert Day Logic Here: } else { Debug.WriteLine("Failed to Parse <STRING_WEEK: " + week[i] + "> too INT"); return false; } } //Convert Day Logic int[] dayParse = new int[day.Length]; for (int i = 0; i < day.Length; i++) { if (int.TryParse(day[i], out dayParse[i])) { //Pre insert Day Logic Here: } else { Debug.WriteLine("Failed to Parse <STRING_DAY: " + day[i] + "> too INT"); return false; } } //Convert Room Logic int roomParse; if (int.TryParse(room, out roomParse)) { //Pre insert Room Logic Here: } else if (room == null)//Dan: roomID shouldn't be optional either, need to fix before push to master [MASTER] not-note: meh... { roomParse = 0; } else { Debug.WriteLine("Failed to Parse <STRING_ROOM: " + room + "> too INT"); return false; } //Convert Course Logic int courseParse; if (int.TryParse(course, out courseParse)) { //Pre insert Course Logic Here: } else if (course == null)//Dan: hold up... the course ID shouldn't be optional. this needs fixed before we can update master [MASTER] { courseParse = 0; } else { Debug.WriteLine("Failed to Parse <STRING_COURSE: " + course + "> too INT"); return false; } TimeItem startTimeParse; try { startTimeParse = new TimeItem(startTime); } catch (FormatException excpt) { Debug.WriteLine("Failed to Parse <STRING_START_TIME: " + startTime + "> too TIMEITEM \n" + excpt); return false; } TimeItem endTimeParse; try { endTimeParse = new TimeItem(endTime); } catch (FormatException excpt) { Debug.WriteLine("Failed to Parse <STRING_END_TIME: " + endTime + "> too TIMEITEM \n" + excpt); return false; } //Dan : Calandar logic Calandar.CalanderFormater CF = new Calandar.CalanderFormater(yearParse); SqlCommand cmd = new SqlCommand();//holds information for interacting with database //GregorianCalendar GC = new GregorianCalendar();//deadcode: replaced with CalanderFormater //Dan : find valid days logic for (int curDay = 1; curDay <= CF.GetDaysAmount(); curDay++)//begin for days in year { bool isValid = true; if (monthParse.Length != 0)//if month specified { for (int i = 0; i < monthParse.Length; i++) { if (CF.getMonthByDay(curDay).getMonthID() == monthParse[i])//looks to see if current day is in specified month { isValid = true;//makes invalid if it is break; } else { isValid = false; } } }//end if month specified if (weekParse.Length != 0 && isValid)//if week specified { for (int i = 0; i < weekParse.Length; i++) { if (CF.getDayOfWeek(curDay) == weekParse[i])//looks to see if current day is specified day of week { isValid = true; break; } else { isValid = false; } } }//end if week specified if (dayParse.Length != 0 && isValid)//if day specified { for (int i = 0; i < dayParse.Length; i++) { if (CF.getMonthByDay(curDay).getDayByMonth(dayParse[i]).getDayID() == curDay)//looks to see if current day is specified days into month { isValid = true; break; } else { isValid = false; } } }//end if day specified if (isValid)//if valid day { string[] badrows; string[] colDats = { null, null, null, null, null, null, CF[curDay].getDayID().ToString(), null, null }; if (!IsConflict("SELECT * FROM dbo.CALANDER_LIST WHERE LIST_YEAR IN (" + yearParse + ") AND ROOM_ID IN (" + roomParse + ");", colDats, out badrows))//checks for conflicting days of year { colDats = new string[] { null, null, null, null, null, null, null, startTimeParse.ToString(), endTimeParse.ToString() };//checks for conflicting rooms in days of year string[] rowGet; for (int i = 0; i < badrows.Length; i++) { if (IsConflictSingleRow("SELECT * FROM dbo.CALANDER_LIST WHERE LIST_ID IN (" + badrows[i] + ");", colDats, out rowGet)) { TimeItem gotStart = new TimeItem(rowGet[7]); TimeItem gotend = new TimeItem(rowGet[8]); if ((gotStart <= startTimeParse) && (gotend >= startTimeParse) || (gotend >= endTimeParse) && (gotStart <= endTimeParse))//check for time conflict { isValid = false; } }else { //TODO: check for fail to read on single row : fault talerance [BETA] } }//end for each conflict }//end if Conflict if (isValid) { cmd.CommandText += "INSERT INTO dbo.CALANDER_LIST(CLASS_ID,ROOM_ID,LIST_YEAR,LIST_MONTH,LIST_WEEK,LIST_DAY,START_TIME,END_TIME) VALUES(" + courseParse + "," + roomParse + "," + yearParse + "," + CF.getMonthByDay(curDay).getMonthID() + "," + CF.getDayOfWeek(curDay) + "," + curDay + ", '" + startTimeParse.ToString() + "', '" + endTimeParse.ToString() + "');\n"; } }//end if valid day }//end for days in year try { Debug.WriteLine(cmd.CommandText); connection.Open(); //SqlCommand cmd = new SqlCommand();//moved to : find valid days logic cmd.Connection = connection; //cmd.CommandText = null;//moved to : find valid days logic cmd.ExecuteNonQuery(); connection.Close(); } catch (SqlException excp) { Debug.WriteLine("Failed to run InsertIntoDataBase: " + excp); connection.Close(); return false; } return true; }//end InsertSchedualItem /* * (bool) IsConflict(string selectQuery, string[] collumDats, out string[] badRows) * takes a query string that selects a table and compares it too a string array containg a set of row data for that table * * Parameters(implicit): * Target Database: Defined by [DataBase Connetion String] in [WebApp/Bin/DataBaseConfig.txt] * * Parameters(defined): * selectQuery(string): a SQL select statment that must reuturn the primary key as the first element and all data must be returned * as the same element index as the value it is to be compared too in [collumDats] * collumDats(string[]): an array of string values that represent a row of data to compare against, any element index with its value as (null) * will not be checked for conflicts * * Parameters(return): * this method(bool): returns true if no conflicts detected, false if there are * badRows(string[]): creates a string array whose length is the number of rows with conflicting data and each element is the primary key of each row that had conflicting data */ private bool IsConflict(string selectQuery, string[] collumDats, out string[] badRows) { SqlCommand cmd = new SqlCommand(selectQuery, connection); List<string> tempBadRows = new List<string>(); try { connection.Open(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read())//runs for each row { for (int i = 0; i < collumDats.Length; i++)//runs for each given collumn { if (!(string.IsNullOrEmpty(collumDats[i]) || collumDats[i].Equals("0"))) { if (collumDats[i] == reader.GetValue(i).ToString()) tempBadRows.Add(reader.GetValue(0).ToString()); break; } }//end for collumn }//end while row reader.Close(); connection.Close(); } catch (SqlException excp)//currently dosen't warn do anything alert user if function didn't execute, or only partially execute probably want to fix that [TODO] { Debug.WriteLine("Failed on dataReader: " + excp); connection.Close(); } if (tempBadRows.Count == 0) { badRows = null; return true; } else { badRows = tempBadRows.ToArray(); return false; } } //functions like IsCOnflict but for single row, and returns all data in row as string array private bool IsConflictSingleRow(string selectQuery, string[] collumDats, out string[] rowDats) { rowDats = new string[collumDats.Length]; SqlCommand cmd = new SqlCommand(selectQuery, connection); try { connection.Open(); SqlDataReader reader = cmd.ExecuteReader(); reader.Read(); for (int i = 0; i < collumDats.Length; i++)//runs for each given collumn { if (!(string.IsNullOrEmpty(collumDats[i]) || collumDats[i].Equals("0"))) { rowDats[i] = reader.GetValue(i).ToString(); } }//end for collumn reader.Close(); connection.Close(); } catch (SqlException excp) { Debug.WriteLine("Failed on dataReader: " + excp); connection.Close(); return false; } return true; } public void Dispose() { //throw new NotImplementedException(); } } }
Go
UTF-8
1,579
2.765625
3
[]
no_license
package fcgi import ( "encoding/binary" "errors" "fmt" "io" "io/ioutil" ) // Request ... type Request struct { c *conn Stdout io.Writer Stderr io.Writer Stdin io.Reader } func writerOrDiscard(w io.Writer) io.Writer { if w != nil { return w } return ioutil.Discard } // StdoutPipe ... func (r *Request) StdoutPipe() io.Reader { pr, pw := io.Pipe() r.Stdout = pw return pr } // StderrPipe ... func (r *Request) StderrPipe() io.Reader { pr, pw := io.Pipe() r.Stderr = pw return pr } // Wait ... func (r *Request) Wait() error { defer r.c.Close() var h header stdout := writerOrDiscard(r.Stdout) stderr := writerOrDiscard(r.Stderr) go func() { var buf buffer buf.Reset() if err := writeStdin(r.c, &buf, requestID, r.Stdin); err != nil { // TODO(knorton): propagate the correct error as the return value. r.c.Close() } }() for { if err := binary.Read(r.c, binary.BigEndian, &h); err != nil { return err } if h.Version != fcgiVersion { return errors.New("invalid fcgi version") } if h.ID != 1 { return errors.New("invalid request id") } buf := make([]byte, int(h.ContentLength)+int(h.PaddingLength)) if _, err := io.ReadFull(r.c, buf); err != nil { return err } buf = buf[:h.ContentLength] switch h.Type { case typeStdout: if _, err := stdout.Write(buf); err != nil { return err } case typeStderr: if _, err := stderr.Write(buf); err != nil { return err } case typeEndRequest: return nil default: return fmt.Errorf("unexpected type: %d", h.Type) } } }
Java
UTF-8
1,858
3.40625
3
[]
no_license
package ua.privatbank.ilina.hw5; import java.util.Arrays; public class Library { public static void main(String[] args) { Book[] books = { new Book("Moydodir", "some author", 1973), new Book("Cheburashka", "some author", 1985), new Book("Tom&Jery", "some author", 1941), }; Reader[] readers = { new Reader("John Dou1", 1234, "faculty1", "05.12.1995", "+2423234234"), new Reader("John Dou2", 345234, "faculty2", "03.02.2005", "+242334234"), new Reader("John Dou3", 897765, "faculty3", "85.32.9995", "+4567865"), }; System.out.println("\n\n"); System.out.println(Arrays.toString(books)); System.out.println(Arrays.toString(readers)); System.out.println("\n\n"); readers[0].takeBook(books); readers[1].takeBook(5); readers[2].takeBook(new String[]{"Moydodir", "Cheburashka", "Tom&Jery"}); System.out.println("\n\n"); readers[0].returnBook(books); readers[1].returnBook(5); readers[2].returnBook(new String[]{"Moydodir", "Cheburashka", "Tom&Jery"}); } } // Класс Library используется как демонстрация работы классов Book и Reader. // Имеет метод main() в котором создается массивы объектов Book и Reader, по 3 или более элементов в каждом. // Выполняются такие действия: // - печатаются все книги. // - печатаются все читатели. // - демонстрируется работа всех вариантов методов takeBook() и returnBook().
C#
UTF-8
1,189
3.46875
3
[]
no_license
using System; using System.Collections.Generic; namespace BlackJack.Classes { public class Player { public List<Card> Cards; //pasakam, ka būs mainīgais - kāršu saraksts public Player() { Cards = new List<Card>(); //izveido jaunu tukšu sarakstu } public void GiveCard(Card card) { Console.WriteLine("Spēlētājs saņēma kārti " + card.Suit + card.Value); Cards.Add(card); } public int CountPoints() { int points = 0; int aceCount = 0; foreach(var c in Cards) // var - sameklē tipu augstāk, vai no vērtības nolasa { points += c.GetValue(); if(c.Value == "A") { aceCount++; } } while(points>21&& aceCount >0) { points -= 10; aceCount--; } return points; } public bool NeedAnotherCard() { var answer = Game.GetAnswer("Vai nepieciešana kārts"); return answer; } } }
Python
UTF-8
7,427
2.546875
3
[]
no_license
import sys import pathlib import os import numpy as np import librosa from scipy.io import wavfile import torch from art.estimators.speech_recognition.pytorch_deep_speech import PyTorchDeepSpeech from art.attacks.evasion.imperceptible_asr.imperceptible_asr_pytorch import ImperceptibleASRPyTorch class AsrAttack(): ''' This class controls all the configuration and parameters, including parameters for attack and inference. The attack used here is from `Trusted-AI/adversarial-robustness-toolbox`. Check their github page for more information. TODO: Use modified version of the attack module written specifically for audio captcha. ''' SAMPLE_RATE = 16000 def __init__(self, pretrained_model="librispeech", gpus="0", debug=False, **attack_kwargs): ''' Create a class `.AsrAttack` instance. Args: pretrained_model (str) : The choice of target model. Currently this attack supports 3 different pretrained models consisting of `an4`, `librispeech` and `tedlium`, representing which dataset the model was trained with. gpus (str) : assign specific gpu to use. Default is "0". If gpu is unavailable, use cpu instead. debug (bool) : whether to print the debug message attack_kwargs (dict) : arguments for attack parameters. Read the documentation below. Args for `attack_kwargs`: estimator (PyTorchDeepSpeech) : A trained estimator. initial_eps (float) : Initial maximum perturbation that the attacker can introduce. max_iter_1st_stage (int): The maximum number of iterations applied for the first stage of the optimization of the attack. max_iter_2nd_stage (int): The maximum number of iterations applied for the second stage of the optimization of the attack. learning_rate_1st_stage (float) : The initial learning rate applied for the first stage of the optimization of the attack. learning_rate_2nd_stage (float) : The initial learning rate applied for the second stage of the optimization of the attack. optimizer_1st_stage: The optimizer applied for the first stage of the optimization of the attack. If `None` attack will use `torch.optim.SGD`. optimizer_2nd_stage: The optimizer applied for the second stage of the optimization of the attack. If `None` attack will use `torch.optim.SGD`. global_max_length (int) : The length of the longest audio signal allowed by this attack. initial_rescale (float) : Initial rescale coefficient to speedup the decrease of the perturbation size during the first stage of the optimization of the attack. rescale_factor (float) : The factor to adjust the rescale coefficient during the first stage of the optimization of the attack. num_iter_adjust_rescale (int) : Number of iterations to adjust the rescale coefficient. initial_alpha (float) : The initial value of the alpha coefficient used in the second stage of the optimization of the attack. increase_factor_alpha (float) : The factor to increase the alpha coefficient used in the second stage of the optimization of the attack. num_iter_increase_alpha (int) : Number of iterations to increase alpha. decrease_factor_alpha (float) : The factor to decrease the alpha coefficient used in the second stage of the optimization of the attack. num_iter_decrease_alpha (int) : Number of iterations to decrease alpha. batch_size (int) : Size of the batch on which adversarial samples are generated. use_amp (bool) : Whether to use the automatic mixed precision tool to enable mixed precision training or gradient computation, e.g. with loss gradient computation. When set to True, this option is only triggered if there are GPUs available. opt_level (str) : Specify a pure or mixed precision optimization level. Used when use_amp is True. Accepted values are `O0`, `O1`, `O2`, and `O3`. ''' self.pretrained_model = pretrained_model self.gpus = gpus self.debug = debug self.attack_kwargs = attack_kwargs # set gpu device here if torch.cuda.is_available(): os.environ["CUDA_VISIBLE_DEVICES"] = self.gpus self.device_type = "gpu" else: self.device_type = "cpu" # TODO : Set up optimizer in `attack_kwargs` # initialize target asr model self.asr_model = PyTorchDeepSpeech(pretrained_model=self.pretrained_model, device_type=self.device_type) # attack! self.asr_attack = ImperceptibleASRPyTorch(estimator=self.asr_model, **self.attack_kwargs) def load_audio(self, path): ''' It's the same loader used by deepspeech-pytorch ''' sound, _ = librosa.load(path, sr=AsrAttack.SAMPLE_RATE) if len(sound.shape) > 1: sound = sound.mean(axis=1) # multiple channels, average return sound def save_audio(self, path, audio): ''' Save audio file. Will be rescaled in 16-bits integer. ''' wavfile.write(path, AsrAttack.SAMPLE_RATE, audio) def generate_adv_example(self, input_path, target, output_path): ''' Generate adversarial example. Args: input_path (str) : the path of audio being attacked. target (str) : target output in capital letter. Ex: "OPEN THE DOOR". output_path (str) : the path where targeted audio is stored. ''' audio = self.load_audio(input_path) prediction = self.asr_model.predict(np.array([audio]), batch_size=1, transcription_output=True) if self.debug: print('input path:', input_path) print('original prediction:', prediction) print('target:', target) # start generating adv example adv_audio = self.asr_attack.generate(np.array([audio]), np.array([target]), batch_size=1) # check the transcription of targeted audio adv_transcriptions = self.asr_model.predict(adv_audio, batch_size=1, transcription_output=True) print("Groundtruth transcriptions: ", prediction) print("Target transcriptions: ", target) print("Adversarial transcriptions: ", adv_transcriptions) # save adv audio self.save_audio(output_path, adv_audio[0]) if self.debug: print('Generated audio stored at:', output_path)
C
UTF-8
270
3.5
4
[]
no_license
#include<stdio.h> void main() { int i=0,j,t; char s[100],r[100]; printf("Enter the string \n"); scanf("%s",s); printf("%s\n",s); while(s[i]!='\0') { i++; } t=0; for(j=i-1;j>=0;j--) { r[t]=s[j]; t++; } printf("The reversed string is %s \n",r); }
Python
UTF-8
2,109
2.8125
3
[]
no_license
# import the necessary packages from keras.preprocessing.image import img_to_array from keras.models import load_model import numpy as np import argparse import cv2 import imutils import pickle import os from cv2 import * class ImgClassifier: path_model = "model4.h5" path_pickle = "lb.pickle3" @classmethod def transform_image(cls,image): image = cv2.resize(image, (32, 32)) image = image.astype("float") / 255.0 image = img_to_array(image) image = np.expand_dims(image, axis=0) return image @staticmethod def simple_msg(): print("main") @staticmethod def classify_img(path_img, path_model, path_pickle): image = cv2.imread(path_img) output = image.copy() image = ImgClassifier.transform_image(image) # load the trained convolutional neural network and the label # binarizer print("[INFO] loading network...") model = load_model(path_model) lb = pickle.loads(open(path_pickle, "rb").read()) # classify the input image print("[INFO] classifying image...") proba = model.predict(image)[0] print(proba) idx = np.argmax(proba) label = lb.classes_[idx] print(path_img) print(label) # filename = path_img.rsplit("\\", 2)[1] # print(filename) # correct = "correct" if filename.rfind(label) != -1 else "incorrect" # build the label and draw the label on the image label = "{}: {:.2f}% ({})".format(label, proba[idx] * 100, "") output = imutils.resize(output, width=400) cv2.putText(output, label, (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2) # show the output image print("[INFO] {}".format(label)) #cv2.imshow("Output", output) #cv2.waitKey(0) return label def main(): print("main") #main() #path_img2 = "C:\\Users\\Alexandru\\Desktop\\validation\\banana\\img3.jpg" #rez = path_img2 #ImgClassifier.classify_img(rez, ImgClassifier.path_model, ImgClassifier.path_pickle)
Java
UTF-8
1,500
2.296875
2
[]
no_license
package dealvector.lib; import io.restassured.response.Response; import io.restassured.response.ValidatableResponse; import io.restassured.specification.RequestSpecification; import java.util.HashMap; import java.util.NoSuchElementException; import static io.restassured.RestAssured.given; import static io.restassured.RestAssured.responseSpecification; /** * Created by UdayN on 28-07-2017. */ public class ApiBase { public enum MethodType{ GET ("get"), POST ("post"), DELETE ("delete"), PUT ("put"); private String _label; MethodType(String label) { _label = label; } public String toString() { return _label; } } protected ValidatableResponse json; protected String endpoint; protected Response response; protected RequestSpecification request; public RequestSpecification getRequest(){ return request; } public Response getResponse(){ return response; } private void createRequestFromParams(HashMap<String,Object> params){ request = given().params(params); } public void makeCall(MethodType type, HashMap params,String url){ createRequestFromParams(params); response = request.when().get(url); } public void isStatusCode(int code){ json = response.then().statusCode(code); } /*public void verifyIntField(){ json.body("totalItems",equals(0)); }*/ }
Markdown
UTF-8
754
3.203125
3
[]
no_license
# Countdown JS ## Setup Set the following IDs on their relevant elements in the HTML: ``` "cd-weeks" - for weeks, no maximum value "cd-days" - for days, up to 6 if weeks is defined "cd-hours" - for hours, up to 23 if days is defined "cd-minutes" - for minutes, up to 59 if hours is defined "cd-seconds" - for seconds, up to 59 if minutes is defined ``` Add all IDs up to the last one you need (if you don't need all of the values). ## How to run Run `new Countdown(dateToCountTo)` after the document is ready. `dateToCountTo` should be a valid date. Example "10/14/2017 12:36 PM". ## On End Listen for `cdOver` window event - triggered when the countdown is over (and do something). ---- Use countdown.html for reference.
JavaScript
UTF-8
1,001
2.703125
3
[ "MIT" ]
permissive
import './sass/main.scss'; import menuCardsTpl from './templates/menu-cards.hbs'; import menuData from './js/menu.json'; const Theme = { LIGHT: 'light-theme', DARK: 'dark-theme', }; const STORAGE_KEY = 'currentTheme'; const listRef = document.querySelector('.js-menu'); const inputRef = document.querySelector('#theme-switch-toggle'); const setUserTheme = savedTheme => { if (!savedTheme) { document.body.classList.add(Theme.LIGHT); } else { document.body.classList.add(savedTheme); if (savedTheme === Theme.DARK) { inputRef.checked = true; } } }; setUserTheme(localStorage.getItem(STORAGE_KEY)); listRef.innerHTML = menuCardsTpl(menuData); inputRef.addEventListener('change', event => { if (event.target.checked) { document.body.classList.replace(Theme.LIGHT, Theme.DARK); localStorage.setItem(STORAGE_KEY, Theme.DARK); } else { document.body.classList.replace(Theme.DARK, Theme.LIGHT); localStorage.setItem(STORAGE_KEY, Theme.LIGHT); } });
Markdown
UTF-8
1,334
2.578125
3
[ "MIT" ]
permissive
## About Ruleta - Este es un proyecto realizado con laravel version 8.23.1 y vueJs. ## Intalación en linux - Paso 1) Clonar el proyecto - Paso 2) Ubicarlo el la carpeta raiz de su servidor web Ej: /var/www/html/ruleta - Paso 3) Ejecutar composer install - Paso 4) Crear el archivo .env 4.1) Ejecutar touch .env para crear el archivo .env 4.2) Ejecutar cp .env.example .env - Paso 5) Configurar la base de datos mysql 5.1) En mi caso DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=ruleta DB_USERNAME=laravel1 DB_PASSWORD=laravel Dicha configuracion depende se su servidor mysql y el usuario. * La base esta nombrada como ruleta.sql - Paso 4) Ejecutar php artisan key:generate, laravel necesita una llave unica en nuestro proyecto ### Todos los pasos del 3 al 5 son explicados de una mejor forma en el siguiente post https://parzibyte.me/blog/2017/05/29/hacer-despues-clonar-proyecto-laravel/ -paso 5) Ejecuar servidor interno de laravel para ver nuestro projecto - php artisan serve Nota: si llega a tener algun problemas de permisos ver este video https://www.youtube.com/watch?v=m-EjyMPUhhY ## License The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT). # ruleta
Java
UTF-8
660
1.9375
2
[]
no_license
package com.banyechan.autocreatedatabase.configuration; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; @Slf4j @Component @Order(1) public class CommandLineRunnerTest implements CommandLineRunner { @Autowired private InitDatabaseAndTables initDatabaseAndTables; @Override public void run(String... args) throws Exception { log.info("====== CommandLineRunner 执行 ======="); initDatabaseAndTables.initTables(); } }
Java
UTF-8
1,954
2.109375
2
[]
no_license
package com.safely.batch.connector.components.external; import com.safely.batch.connector.JobContext; import com.safely.batch.connector.client.AuthorizationClient; import com.safely.batch.connector.entity.AuthenticationResponseToken; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; @Service public class LoadPmsAuthTokenService { private static final Logger log = LoggerFactory.getLogger(LoadPmsAuthTokenService.class); private final AuthorizationClient authorizationClient; public LoadPmsAuthTokenService(AuthorizationClient authorizationClient) { this.authorizationClient = authorizationClient; } public void execute(JobContext jobContext) throws Exception{ try { log.info("OrganizationId: {}. Retrieving Pms Token from RealTimeRental.", jobContext.getOrganizationId()); String username = jobContext.getOrganization().getOrganizationSourceCredentials().getAccountKey(); String password = jobContext.getOrganization().getOrganizationSourceCredentials().getAccountPrivateKey(); AuthenticationResponseToken token = authorizationClient.getPmsToken(username, password); if (token == null) { String msg = String.format("OrganizationId: %s. Error occurred while retrieving authentication from PMS.", jobContext.getOrganizationId()); log.error(msg); throw new Exception(msg); } jobContext.setToken(token.getAccessToken()); } catch (Exception ex) { String msg = String .format("OrganizationId: %s. Failed to retrieve an authentication token for the organization with name: %s. Error message: %s", jobContext.getOrganizationId(), jobContext.getOrganization().getName(), ex.getMessage()); log.error(msg, ex); throw ex; } } }
C#
UTF-8
1,656
3.078125
3
[]
no_license
using GameCampaign.Abstract; using GameCampaign.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GameCampaign.Consrete { class SaleManager : ISaleService { public void Order(Game game, Gamer gamer) { Console.WriteLine(" dear " + gamer.FirstName + " you can buy " + game.GameName + " for " + game.GamePrice); } public void OrderWithCampaign(Game game, Campaign campaign) { if (game.GamePrice > 400) { float finalprice = game.GamePrice - (game.GamePrice * campaign.DiscountRate / 100); Console.WriteLine("dear user you can buy " + " " + game.GameName + " game " + finalprice + " TL with " + campaign.CampaignName); } else { Console.WriteLine("Kampanya dışı"); } } public void OrderWithCampaign(List<Game> games, Campaign campaign) { foreach (var i in games) { if (i.GamePrice > 400) { float finalprice = i.GamePrice - (i.GamePrice * campaign.DiscountRate / 100); Console.WriteLine("dear user you can buy " + " " + i.GameName + " game " + finalprice + " TL with " + campaign.CampaignName); Console.WriteLine("............................................."); } else { Console.WriteLine("Kampanya dışı"); } } } } }
Markdown
UTF-8
720
2.703125
3
[]
no_license
# Deep Detect Drawing Deep detect Drawing is a app based on a CNN model, to recognize a few draw. You can check the model construction [here](https://github.com/leersmathieu/deep-detect-drawing/blob/master/modeling%20notebook/object_recognition_model.ipynb) # Training & accuracy ![train](assets/train.png) # Try it yourself ! On my serveur http://deepdrawing.tamikara.xyz/ OR With *docker* For try this app on your computer with docker, just enter this command in your terminal. It's magic. ```docker docker run -p 8501:8501 leersma/deep-detect-drawing:latest ``` just pay attention to the port used If you run it on port 8501 as in the example, you can easily access it like this: http://localhost:8501/.
Python
UTF-8
1,784
2.65625
3
[]
no_license
# coding: utf-8 """ 管理用户 Usage: --*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*-- from flask import Flask, request, redirect import login app = Flask(__name__) login.init(app, 'sign_in') @app.route('/') @login.login_required def index(): return 'Index!' def sign_up(): pass @app.route('/sign_in', methods=['GET', 'POST']) def sign_in(): if request.method == 'GET': return ''' <form action='sign_in' method='POST'> <input type='text' name='email' id='email' placeholder='email'/> <input type='password' name='password' id='password' placeholder='password'/> <input type='submit' name='submit'/> </form> ''' if request.form['email'] == '123': login.login('123') return redirect('/') return 'login error!' @app.route('/sign_out') def sign_out(): login.logout() return redirect('/') --*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*-- """ import flask_login from flask_login import login_required login_manager = flask_login.LoginManager() class User(flask_login.UserMixin): def __init__(self, user_id): self.id = user_id def init(app, login_view=None): """ :param app: from Flask(xxx) :param login_view: login_manager.login_view 用来显示登陆界面的函数 :return: None """ login_manager.init_app(app) login_manager.login_view = login_view @login_manager.user_loader def load_user(_id): return User(_id) def login(user_id): user = User(user_id) flask_login.login_user(user) @login_required def logout(): flask_login.logout_user() def get_cur_user_id(): return flask_login.current_user.id
PHP
UTF-8
791
2.515625
3
[ "MIT" ]
permissive
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateTariffsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('tariffs', function (Blueprint $table) { $table->increments('id'); $table->integer('room_id')->references('room')->on('id'); $table->integer('noofpersons'); $table->float('tariff',8,2); $table->float('extra_bad',8,2); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('tariffs'); } }
PHP
UTF-8
4,716
3.03125
3
[ "Apache-2.0" ]
permissive
<?php /** * Appfuel * Copyright (c) Robert Scott-Buccleuch <rsb.appfuel@gmail.com> * See LICENSE file at project root for details. */ namespace Appfuel\Filesystem; use SplFileInfo, LogicException, RunTimeException, InvalidArgumentException, RecursiveIteratorIterator, RecursiveDirectoryIterator; /** * Reads the contents of a file into memory */ class FileWriter implements FileWriterInterface { /** * @var FileFinderInterface */ protected $finder = null; /** * * @param FileFinderInterface * @return FileReader */ public function __construct(FileFinderInterface $finder = null) { if (null === $finder) { $finder = new FileFinder(); } $this->setFileFinder($finder); } /** * @return FileFinderInterface */ public function getFileFinder() { return $this->finder; } /** * @param FileFinderInterface $finder * @return FileReader */ public function setFileFinder(FileFinderInterface $finder) { $this->finder = $finder; return $this; } /** * @param string $data * @param string $path * @param int $flags * @return int */ public function putContent($data, $path, $flags = 0) { $finder = $this->getFileFinder(); $full = $finder->getPath($path); return file_put_contents($full, $data, $flags); } /** * @param string $src * @param string $dest * @return bool */ public function copy($src, $dest) { $finder = $this->getFileFinder(); $fullSrc = $finder->getPath($src); $fullDest = $finder->getPath($dest); return copy($fullSrc, $fullDest); } /** * @param string $path * @param int $mode * @param bool $isRecursive * @return */ public function mkdir($path, $mode = null, $recursive = null) { $isRecursive = false; if (true === $recursive) { $isRecursive = true; } $finder = $this->getFileFinder(); $full = $finder->getPath($path); return mkdir($full, $mode, $isRecursive); } /** * @param string $src * @param string $dest * @return bool */ public function copyTree($src, $dest) { $finder = $this->getFileFinder(); $src = $finder->getPath($src); $dest = $finder->getPath($dest); $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($src), RecursiveIteratorIterator::SELF_FIRST ); if (! is_dir($dest) && false === mkdir($dest)) { $err = "copy tree failed: could not create root directory -($dest)"; throw new RunTimeException($err); } foreach ($iterator as $node) { $srcPath =(string)$node; $destPath = str_replace($src, $dest, $srcPath); if ($node->isDir()) { if (! is_dir($destPath) && false === mkdir($destPath)) { $err = "copy tree failed: could not create directory at "; $err .= "-($destPath)"; throw new RunTimeException($err); } } else { if (false === copy($srcPath, $destPath)) { $err = "copy tree failed: could not copy -($srcPath) to "; $err .= "-($destPath)"; throw new RunTimeException($err); } } } return true; } /** * Recursively delete a directory and its contents * * @param $path * @return bool */ public function deleteTree($path, $leaveRoot = false) { $finder = $this->getFileFinder(); $target = $finder->getPath($path); if (DIRECTORY_SEPARATOR === $target) { $err = 'if you want to delete the root directory do it manually'; throw new logicexception($err); } if (! $finder->fileExists($target, false)) { return true; } $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($target), RecursiveIteratorIterator::CHILD_FIRST ); foreach ($iterator as $node) { $fullpath =(string)$node; if ($node->isDir()) { rmdir($fullpath); } else { unlink($fullpath); } } if (false === $leaveRoot) { rmdir($target); } return true; } }
Java
UTF-8
11,948
1.84375
2
[ "Apache-2.0" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * 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.apache.sshd.common.config.keys; import java.security.Key; import java.security.KeyPair; import java.security.PublicKey; import java.security.interfaces.DSAKey; import java.security.interfaces.DSAParams; import java.security.interfaces.DSAPublicKey; import java.security.interfaces.ECKey; import java.security.interfaces.ECPublicKey; import java.security.interfaces.RSAKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.ECParameterSpec; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.TreeMap; import org.apache.sshd.common.Digest; import org.apache.sshd.common.cipher.ECCurves; import org.apache.sshd.common.digest.BuiltinDigests; import org.apache.sshd.common.keyprovider.KeyPairProvider; import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.common.util.ValidateUtils; import org.apache.sshd.common.util.buffer.Buffer; import org.apache.sshd.common.util.buffer.BufferUtils; import org.apache.sshd.common.util.buffer.ByteArrayBuffer; /** * Utility class for keys * * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a> */ public class KeyUtils { private static final Map<String,PublicKeyEntryDecoder<? extends PublicKey>> byKeyTypeDecodersMap = new TreeMap<String, PublicKeyEntryDecoder<? extends PublicKey>>(String.CASE_INSENSITIVE_ORDER); private static final Map<Class<?>,PublicKeyEntryDecoder<? extends PublicKey>> byKeyClassDecodersMap = new HashMap<Class<?>, PublicKeyEntryDecoder<? extends PublicKey>>(); static { registerPublicKeyEntryDecoder(RSAPublicKeyDecoder.INSTANCE); registerPublicKeyEntryDecoder(DSSPublicKeyEntryDecoder.INSTANCE); registerPublicKeyEntryDecoder(ECDSAPublicKeyEntryDecoder.INSTANCE); } private KeyUtils() { throw new UnsupportedOperationException("No instance"); } public static void registerPublicKeyEntryDecoder(PublicKeyEntryDecoder<? extends PublicKey> decoder) { ValidateUtils.checkNotNull(decoder, "No decoder specified", GenericUtils.EMPTY_OBJECT_ARRAY); Class<?> keyType = ValidateUtils.checkNotNull(decoder.getKeyType(), "No key type declared", GenericUtils.EMPTY_OBJECT_ARRAY); synchronized(byKeyClassDecodersMap) { byKeyClassDecodersMap.put(keyType, decoder); } Collection<String> names = ValidateUtils.checkNotNullAndNotEmpty(decoder.getSupportedTypeNames(), "No supported key type", GenericUtils.EMPTY_OBJECT_ARRAY); synchronized(byKeyTypeDecodersMap) { for (String n : names) { PublicKeyEntryDecoder<? extends PublicKey> prev = byKeyTypeDecodersMap.put(n, decoder); if (prev != null) { continue; // debug breakpoint } } } } /** * @param keyType The {@code OpenSSH} key type string - ignored if {@code null}/empty * @return The registered {@link PublicKeyEntryDecoder} or {code null} if not found */ public static PublicKeyEntryDecoder<? extends PublicKey> getPublicKeyEntryDecoder(String keyType) { if (GenericUtils.isEmpty(keyType)) { return null; } synchronized(byKeyTypeDecodersMap) { return byKeyTypeDecodersMap.get(keyType); } } /** * @param key The {@link PublicKey} - ignored if {@code null} * @return The registered {@link PublicKeyEntryDecoder} for this key or {code null} if no match found * @see #getPublicKeyEntryDecoder(Class) */ public static PublicKeyEntryDecoder<? extends PublicKey> getPublicKeyEntryDecoder(PublicKey key) { if (key == null) { return null; } else { return getPublicKeyEntryDecoder(key.getClass()); } } /** * @param keyType The key {@link Class} - ignored if {@code null} or not a {@link PublicKey} * compatible type * @return The registered {@link PublicKeyEntryDecoder} or {code null} if no match found */ public static PublicKeyEntryDecoder<? extends PublicKey> getPublicKeyEntryDecoder(Class<?> keyType) { if ((keyType == null) || (!PublicKey.class.isAssignableFrom(keyType))) { return null; } synchronized(byKeyTypeDecodersMap) { { PublicKeyEntryDecoder<? extends PublicKey> decoder=byKeyTypeDecodersMap.get(keyType); if (decoder != null) { return decoder; } } // in case it is a derived class for (PublicKeyEntryDecoder<? extends PublicKey> decoder : byKeyTypeDecodersMap.values()) { Class<?> t = decoder.getKeyType(); if (t.isAssignableFrom(keyType)) { return decoder; } } } return null; } /** * Retrieve the public key fingerprint * * @param key the public key - ignored if {@code null} * @return the fingerprint or {@code null} if no key */ public static String getFingerPrint(PublicKey key) { if (key == null) { return null; } try { Buffer buffer = new ByteArrayBuffer(); buffer.putRawPublicKey(key); Digest md5 = BuiltinDigests.md5.create(); md5.init(); md5.update(buffer.array(), 0, buffer.wpos()); byte[] data = md5.digest(); return BufferUtils.printHex(data, 0, data.length, ':'); } catch(Exception e) { return "Unable to compute fingerprint"; } } /** * Retrieve the key type * * @param kp a key pair * @return the key type */ public static String getKeyType(KeyPair kp) { return getKeyType(kp.getPrivate() != null ? kp.getPrivate() : kp.getPublic()); } /** * Retrieve the key type * * @param key a public or private key * @return the key type */ public static String getKeyType(Key key) { if (key instanceof DSAKey) { return KeyPairProvider.SSH_DSS; } else if (key instanceof RSAKey) { return KeyPairProvider.SSH_RSA; } else if (key instanceof ECKey) { ECKey ecKey = (ECKey) key; ECParameterSpec ecSpec = ecKey.getParams(); return ECCurves.ECDSA_SHA2_PREFIX + ECCurves.getCurveName(ecSpec); } return null; } /** * @param key The {@link PublicKey} to be checked - ignored if {@code null} * @param keySet The keys to be searched - ignored if {@code null}/empty * @return The matching {@link PublicKey} from the keys or {@code null} if * no match found * @see #compareKeys(PublicKey, PublicKey) */ public static PublicKey findMatchingKey(PublicKey key, PublicKey ... keySet) { if ((key == null) || GenericUtils.isEmpty(keySet)) { return null; } else { return findMatchingKey(key, Arrays.asList(keySet)); } } /** * @param key The {@link PublicKey} to be checked - ignored if {@code null} * @param keySet The keys to be searched - ignored if {@code null}/empty * @return The matching {@link PublicKey} from the keys or {@code null} if * no match found * @see #compareKeys(PublicKey, PublicKey) */ public static PublicKey findMatchingKey(PublicKey key, Collection<? extends PublicKey> keySet) { if ((key == null) || GenericUtils.isEmpty(keySet)) { return null; } for (PublicKey k : keySet) { if (compareKeys(key, k)) { return k; } } return null; } public static boolean compareKeys(PublicKey k1, PublicKey k2) { if ((k1 instanceof RSAPublicKey) && (k2 instanceof RSAPublicKey)) { return compareRSAKeys(RSAPublicKey.class.cast(k1), RSAPublicKey.class.cast(k2)); } else if ((k1 instanceof DSAPublicKey) && (k2 instanceof DSAPublicKey)) { return compareDSAKeys(DSAPublicKey.class.cast(k1), DSAPublicKey.class.cast(k2)); } else if ((k1 instanceof ECPublicKey) && (k2 instanceof ECPublicKey)) { return compareECKeys(ECPublicKey.class.cast(k1), ECPublicKey.class.cast(k2)); } else { return false; // either key is null or not of same class } } public static boolean compareRSAKeys(RSAPublicKey k1, RSAPublicKey k2) { if (Objects.equals(k1, k2)) { return true; } else if ((k1 == null) || (k2 == null)) { return false; // both null is covered by Objects#equals } else if (Objects.equals(k1.getPublicExponent(), k2.getPublicExponent()) && Objects.equals(k1.getModulus(), k2.getModulus())) { return true; } else { return false; } } public static boolean compareDSAKeys(DSAPublicKey k1, DSAPublicKey k2) { if (Objects.equals(k1, k2)) { return true; } else if ((k1 == null) || (k2 == null)) { return false; // both null is covered by Objects#equals } else if (Objects.equals(k1.getY(), k2.getY()) && compareDSAParams(k1.getParams(), k2.getParams())) { return true; } else { return false; } } public static boolean compareDSAParams(DSAParams p1, DSAParams p2) { if (Objects.equals(p1, p2)) { return true; } else if ((p1 == null) || (p2 == null)) { return false; // both null is covered by Objects#equals } else if (Objects.equals(p1.getG(), p2.getG()) && Objects.equals(p1.getP(), p2.getP()) && Objects.equals(p1.getQ(), p2.getQ())) { return true; } else { return false; } } public static boolean compareECKeys(ECPublicKey k1, ECPublicKey k2) { if (Objects.equals(k1, k2)) { return true; } else if ((k1 == null) || (k2 == null)) { return false; // both null is covered by Objects#equals } else if (Objects.equals(k1.getW(), k2.getW()) && compareECParams(k1.getParams(), k2.getParams())) { return true; } else { return false; } } public static boolean compareECParams(ECParameterSpec s1, ECParameterSpec s2) { if (Objects.equals(s1, s2)) { return true; } else if ((s1 == null) || (s2 == null)) { return false; // both null is covered by Objects#equals } else if (Objects.equals(s1.getOrder(), s2.getOrder()) && (s1.getCofactor() == s2.getCofactor()) && Objects.equals(s1.getGenerator(), s2.getGenerator()) && Objects.equals(s1.getCurve(), s2.getCurve())) { return true; } else { return false; } } }
Java
UTF-8
7,665
2.34375
2
[]
no_license
package com.example.zapal.myapplication; import android.content.Intent; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import java.util.ArrayList; public class ListRecept extends ActionBarActivity { /* @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.list_recept); }*/ //ListView listView ; final String LOG_TAG = "myLogs"; //@Override /*protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.list_recept); // Get ListView object from xml listView = (ListView) findViewById(R.id.list); // Defined Array values to show in ListView String[] values = new String[] { "Автобус № 1", "Автобус № 2", "Автобус № 3", "Автобус № 4", "Автобус № 5", "Автобус № 6", "Автобус № 7", "Автобус № 8", "Автобус № 10", "Автобус № 11", "Автобус № 12", "Автобус № 13", "Автобус № 14", "Автобус № 15", "Автобус № 16", "Автобус № 17", "Автобус № 18", "Автобус № 19", "Автобус № 20", "Автобус № 21", "Автобус № 22", "Автобус № 23", "Автобус № 24", "Автобус № 25", "Автобус № 26", }; // Define a new Adapter // First parameter - Context // Second parameter - Layout for the row // Third parameter - ID of the TextView to which the data is written // Forth - the Array of data ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, values); // Assign adapter to ListView listView.setAdapter(adapter); // ListView Item Click Listener listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // ListView Clicked item index int itemPosition = position; // ListView Clicked item value String itemValue = (String) listView.getItemAtPosition(position); Intent myIntent = new Intent(ListRecept.this, DetailActivity.class); myIntent.putExtra("BUSN", itemValue); startActivity(myIntent); *//* // Show Alert Toast toast = new Toast(getApplicationContext()); toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); Toast.makeText(getApplicationContext(), "Position :"+itemPosition+" ListItem : " +itemValue , Toast.LENGTH_LONG) .show();*//* } }); }*/ private static final String DB_NAME = "bus.sql"; //Хорошей практикой является задание имен полей БД константами private static final String TABLE_NAME = "bus"; private static final String NUMBER = "NUMBER"; private static final String ROUTE = "ROUTE"; private SQLiteDatabase myDataBase; private ListView listView; private ArrayList bus; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //Наш ключевой хелпер //ExternalDbOpenHelper dbOpenHelper = new ExternalDbOpenHelper(this); // database = dbOpenHelper.openDataBase(); ExternalDbOpenHelper myDbHelper = new ExternalDbOpenHelper(this); myDbHelper = new ExternalDbOpenHelper(this); try { myDbHelper.createDataBase(); } catch (IOException ioe) { throw new Error("Unable to create database"); } try { myDbHelper.openDataBase(); }catch(SQLException sqle){ throw sqle; } //Все, база открыта! fillFreinds(); setUpList(); } private void setUpList() { ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, bus); // Assign adapter to ListView listView.setAdapter(adapter); //Подарим себе тост — для души listView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView parent, View view, int position,long id) { Toast.makeText(getApplicationContext(), ((TextView) view).getText() + " could be iDev's friend", Toast.LENGTH_SHORT).show(); } }); } //Извлечение элементов из базы данных private void fillFreinds() { bus = new ArrayList<String>(); Log.v(LOG_TAG, "test"); Cursor friendCursor = myDataBase.query("bus", null,null, null,null,null,null); friendCursor.moveToFirst(); if(!friendCursor.isAfterLast()) { do { String number = friendCursor.getString(1); Log.v(LOG_TAG, number); bus.add(number); } while (friendCursor.moveToNext()); } friendCursor.close(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_list_recept, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public boolean onPrepareOptionsMenu(Menu menu) { boolean result = super.onPrepareOptionsMenu(menu); menu.findItem(R.id.action_main).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { startActivity(new Intent(ListRecept.this, MainActivity.class)); return true; } }); return result; } }
PHP
UTF-8
440
2.859375
3
[ "MIT" ]
permissive
<?php namespace MoySklad\Exceptions; use \Exception; /** * Invalid key was passed in "create" method of Spec class * Class UnknownSpecException * @package MoySklad\Exceptions */ class UnknownSpecException extends Exception{ public function __construct($spec = '', $code = 0, Exception $previous = null) { parent::__construct( 'Unknown spec "'.$spec.'"', $code, $previous); } }
Python
UTF-8
1,863
3.578125
4
[]
no_license
from typing import Optional class XmasDecoder: def __init__(self, message_with_preamble: list[int], preamble_length: int): self.preamble_length = preamble_length self.message = message_with_preamble def is_valid_number(self, message_index: int) -> bool: if message_index < self.preamble_length: return True preamble = self.message[message_index-self.preamble_length:message_index] preamble_set = set(preamble) number = self.message[message_index] max_preamble = max(preamble) min_preamble = min(preamble) if number - max_preamble > max_preamble or number - min_preamble < min_preamble: return False for first in preamble: second = number - first if second != first and second in preamble_set: return True return False def get_invalid_numbers_in_message(self) -> list[int]: for i in range(len(self.message)): if not self.is_valid_number(i): yield self.message[i] def contiguous_sum(self, target_sum: int) -> Optional[tuple[int, int]]: for i in range(len(self.message)): for j in range(i, len(self.message)): subset = self.message[i:j] if sum(subset) == target_sum: return min(subset), max(subset) if __name__ == "__main__": preamble_size = 25 # Hard-coded for each example for now input_list: list[int] with open("input.txt") as input_file: input_list = list(map(int, input_file.readlines())) decoder = XmasDecoder(input_list, preamble_size) invalid_number = list(decoder.get_invalid_numbers_in_message())[0] print(invalid_number) result = decoder.contiguous_sum(invalid_number) print(result[0], result[1]) print(result[0] + result[1])
Java
UTF-8
2,162
2.265625
2
[]
no_license
package com.example.admin.safetyapp; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; import android.widget.Toast; /** * Created by admin on 10/26/2017. */ public class EmailSending extends Service implements ServerResponse { IBinder mBinder; int mStartMode; SendEmail f; int j=0; String latitude="",longitude=""; String username="",emailid="",password=""; String[] emergencyemailid=new String[10]; String[] emergencynames=new String[10]; int len=0; public EmailSending() { } @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return mBinder; } @Override public void onCreate() { } @Override public int onStartCommand(Intent intent, int flags, int startId) { latitude = intent.getStringExtra("latitude"); longitude = intent.getStringExtra("longitude"); emergencynames=intent.getStringArrayExtra("names"); emergencyemailid=intent.getStringArrayExtra("emailid"); len=intent.getIntExtra("count",5); username=intent.getStringExtra("username"); emailid=intent.getStringExtra("id"); password=intent.getStringExtra("password"); Log.d("Service","in service"); /*f=new SendEmail(latitude,longitude); f.delegate=this; f.execute(""); */ try { for(j=0;j<len;j++) { GMailSender sender = new GMailSender(emailid, password); sender.sendMail("Help Required", "This email has been sent by safety app on behalf of "+username+". He requires your help and his latitude is " + latitude + " and longitude is " + longitude, emergencyemailid[j], emergencyemailid[j]); } } catch (Exception e) { Log.e("SendMail", e.getMessage(), e); } return mStartMode; } public void ServerResponds(String result) { Toast.makeText(this,"msg sent",Toast.LENGTH_LONG).show(); } }
Markdown
UTF-8
1,369
3.03125
3
[]
no_license
Project 2 This app I built calls the studio ghibli API and lists every movie, person, location, and vehicle! you can even add your favorite movie to your profile for quicker access MVP goals I made four models You can favorite a movie to profile You can delete a movie from profile Each item (movie, person, etc.) has a unique page when clicked on from the show page. Stretch goals Wanted movie poster pictures to show on the "show" page Organize profile page with categories Be able to add/delete any of the model pages to/from profile Use a 2nd API for movie posters Routes Method Path Purpose GET / home page that lists all pages and an intro GET /profile gets profile page POST /profile deletes from profile GET /films lists all the films POST /films send the film to profile GET /people lists all the people GET /locations lists all the locations GET /vehicles lists all the vehicles GET /auth/login shows login page POST /auth/login posts info and logs in GET /auth/register show register page POST /auth/register posts register info to user and logs in Models film Attributes: title location Attributes: name person Attributes: name vehicle Attributes: name user Attributes: name, email, password Images from: https://studioghiblimovies.com/ API used: https://ghibliapi.herokuapp.com/
Rust
UTF-8
387
3.03125
3
[]
permissive
use nannou::prelude::*; pub struct Ball { pub position: Point2, color: Srgb<u8>, } impl Ball { pub fn new(color: Srgb<u8>) -> Self { let position = pt2(0.0, 0.0); Ball { position, color } } pub fn display(&self, draw: &Draw) { draw.ellipse() .xy(self.position) .radius(100.0) .color(self.color); } }
JavaScript
UTF-8
1,000
3.234375
3
[]
no_license
class Jugador { constructor (color,nombre){ this.color= color; this.nombre = nombre; this.turno = false; this.fichas = []; } getPosNombre (){ return this.posX; } setPosNombre (nombre){ this.nombre = nombre; } getColor (){ return this.color; } setColor (color){ this.color = color; } isHisTurn (){ return this.turno; } swichTurno (){ this.turno = !this.turno; } addFicha (ficha){ this.fichas.push(ficha); } getFichas (){ return this.fichas; } getFichaPointedInside(x,y){ let f = null; this.fichas.forEach(ficha =>{ if (ficha.isPointInside(x, y)){ f = ficha; } }) return f; } esSuFicha(ficha){ return this.fichas.includes(ficha); } drawFichas(){ this.fichas.forEach(ficha => ficha.dibujarse() ) } }
Python
UTF-8
516
3.75
4
[]
no_license
# 返回子字符串 str 在字符串中最后出现的位置,如果没有匹配的字符串会报异常 # str.rindex(str, beg=0 end=len(string)) # 参数 # str -- 查找的字符串 # beg -- 开始查找的位置,默认为0 # end -- 结束查找位置,默认为字符串的长度。 # 返回值:返回子字符串 str 在字符串中最后出现的位置,如果没有匹配的字符串会报异常。 # 与 rfind() 一样的示例代码 # 唯一不同找不到的时候报错
Java
UTF-8
227
1.914063
2
[]
no_license
package com.jk.algorithm.hackerrank.java.stringTokens; /** * string s 를 받아, !/@/,/./?/_ 를 구분자로 쪼개어 쪼개진 string 을 token이라 칭한다. 이후 token의 값 개수와 각 token을 출력하라 **/
PHP
UTF-8
1,088
2.90625
3
[]
no_license
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Classic Models</title> <meta name="description" content="Classic Models Admin Panel."> <link rel="stylesheet" href="cm.php"> <script src=""></script> </head> <body> <?php include 'header.php'; require_once 'cmconfig.php'; //<!----- Code adapted Web App Dev lecture notes and W3schools ----->// // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT productLine, textDescription, image FROM productlines"; $result = $conn->query($sql); if ($result->num_rows > 0) { echo "<table><tr><th>Product</th><th>Description</th></tr>"; // output data of each row while($row = $result->fetch_assoc()) { echo "<tr><td>" . $row["productLine"]. "</td><td>" . $row["textDescription"]. " " . $row["image"]. "</td></tr>"; } echo "</table>"; } else { echo "0 results"; } $conn->close(); include 'footer.php'; ?> </body> </html>
Shell
UTF-8
368
2.578125
3
[]
no_license
ZSH_DISABLE_COMPFIX=true if ! source "${HOME}/.zgen/init.zsh"; then # Load zgen source "${HOME}/.zgen.zsh" echo "Creating a zgen save" zgen load hlissner/zsh-autopair #zgen load zsh-users/zsh-syntax-highlighting # Save it to an init script zgen save fi # Completions fpath=(~/.zsh $fpath) # load built files source ~/.config/zsh/config.sh
SQL
UTF-8
555
4.15625
4
[ "MIT" ]
permissive
SELECT TOP(2) [s].[ShowGuid], [t0].[Title], [t0].[ModifiedDate] FROM [Show] AS [s] LEFT JOIN ( SELECT [t].[ShowId], [t].[Title], [t].[ModifiedDate] FROM ( SELECT [s0].[ModifiedDate], [s0].[ShowId], [s0].[Title], ROW_NUMBER() OVER( PARTITION BY [s0].[ShowId] ORDER BY [s0].[ModifiedDate] DESC) AS [row] FROM [ShowDescription] AS [s0] ) AS [t] WHERE [t].[row] <= 1 ) AS [t0] ON [s].[ShowId] = [t0].[ShowId] WHERE [s].[ShowGuid] = '471E3620-D24C-449D-8547-A84EF8EA40ED'
C#
UTF-8
505
2.921875
3
[]
no_license
namespace FactoryMethod { public class ChicagoStyleVeggiePizza : Pizza { public ChicagoStyleVeggiePizza() { Name = "Chicago Style Veggie Pizza"; Dough = "Crust"; Sauce = "Marinara Pizza Sauce"; Toppings.Add("Shredded Mozzarella"); Toppings.Add("Grated Parmesan"); Toppings.Add("Diced Onion"); Toppings.Add("Sliced Mushrooms"); Toppings.Add("Sliced Black Olives"); } } }
PHP
UTF-8
2,655
2.953125
3
[ "MIT" ]
permissive
<?php namespace MM\bot\components\sound; use Exception; use MM\bot\components\sound\types\AlisaSound; use MM\bot\components\sound\types\MarusiaSound; use MM\bot\components\sound\types\TelegramSound; use MM\bot\components\sound\types\TemplateSoundTypes; use MM\bot\components\sound\types\ViberSound; use MM\bot\components\sound\types\VkSound; use MM\bot\core\mmApp; /** * Класс отвечающий за обработку и корректное воспроизведение звуков, в зависимости от типа приложения. * Class Sound * @package bot\components\sound */ class Sound { /** * Массив звуков. * @var array $sounds */ public $sounds; /** * Использование стандартных звуков. * Если true - используются стандартные звуки. Актуально для Алисы и Маруси. По умолчанию true. * @var bool $isUsedStandardSound */ public $isUsedStandardSound; /** * Sound constructor. */ public function __construct() { $this->sounds = []; $this->isUsedStandardSound = true; } /** * Получение корректно поставленных звуков в текст. * * @param string $text Исходный текст. * @param TemplateSoundTypes|null $userSound Пользовательский класс для обработки звуков. * @return string|array * @throws Exception * @api */ public function getSounds(string $text, ?TemplateSoundTypes $userSound = null) { $sound = null; switch (mmApp::$appType) { case T_ALISA: $sound = new AlisaSound(); $sound->isUsedStandardSound = $this->isUsedStandardSound; break; case T_MARUSIA: $sound = new MarusiaSound(); $sound->isUsedStandardSound = $this->isUsedStandardSound; break; case T_VK: $sound = new VkSound(); break; case T_TELEGRAM: $sound = new TelegramSound(); break; case T_VIBER: $sound = new ViberSound(); break; case T_SMARTAPP: $sound = null; break; case T_USER_APP: $sound = $userSound; break; } if ($sound) { return $sound->getSounds($this->sounds, $text); } return $text; } }
C
UTF-8
294
2.71875
3
[]
no_license
#include "includes/addRoundKey.h" #include "includes/byte.h" #include "includes/constants.h" /** * AddRoundKey step: make state XOR roundKey */ void addRoundKey(byte state[], const byte roundKey[]) { for (int i = 0; i < KEY_BYTES_LENGTH; i++) { state[i] ^= roundKey[i]; } }
C++
UTF-8
535
3.375
3
[]
no_license
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void pusharr(TreeNode* node, vector<int> &a) { if (node == NULL) return; pusharr(node->left, a); a.push_back(node->val); pusharr(node->right, a); } vector<int> inorderTraversal(TreeNode* root) { vector<int> a; pusharr(root, a); return a; } };
PHP
UTF-8
578
2.578125
3
[]
no_license
<?php namespace App\Repositories\Eloquent; use App\Models\Notice as Model; use App\Repositories\Interfaces\Notice; class NoticeRepository extends EloquentRepository implements Notice { /** * Specify Model class name * * @return \Illuminate\Database\Eloquent\Model|string */ public function model() { return Model::class; } /** * @inheritdoc */ public function getEnabledNotices() { $results = $this->model->where('enabled', 1)->get(); $this->resetModel(); return $results; } }
Go
UTF-8
3,961
3.265625
3
[]
no_license
package main import ( "fmt" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/sha256" "crypto/x509" "encoding/base64" "encoding/json" "os" "bufio" "io/ioutil" "encoding/pem" ) //Defining a type that will be used to MarshalJSon in the main function. type jsonobj struct { Message string Signature string Pubkey string } //This function will check to see if a PrivateKey exists on the filesystem or will generate a new private key. //New or existing keys are stored on the filesystem as Pem Encoded X509 format in a txt file. func genKeys() (privateKey *ecdsa.PrivateKey){ //Check to see if a keyfile.txt exists on the file system. if _, err := os.Stat("keyfile.txt"); err == nil { fmt.Println("Using exists keys found on the filesystem! \n") //Read the existing PemEncoded private key from the txt file. keyfile, err := ioutil.ReadFile("keyfile.txt") if err != nil { fmt.Println(err) } //Use a decode function to decode the Pem Encoded x509 formatted private key. privateKey := decode(string(keyfile)) return privateKey } else { //Else Generate/return a new private key and store it on the filesystem for future use. fmt.Println("Keys not found on filesystem. Generating new keys! \n") privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { panic(err) } //x509 format and Pem encode the private key for easy filesystem storage/retrieval. privKeyPemEncoded := encode(privateKey) //write the new private key into a txt file file, err := os.OpenFile("keyfile.txt", os.O_WRONLY|os.O_CREATE, 0666) if err != nil { fmt.Println("File cannot be created") os.Exit(1) } defer file.Close() w := bufio.NewWriter(file) fmt.Fprintf(w,privKeyPemEncoded) w.Flush() return privateKey } } //This function will convert the Private Key into x509 format and then Pem encode it. func encode(privateKey *ecdsa.PrivateKey) (string) { x509Encoded, _ := x509.MarshalECPrivateKey(privateKey) pemEncoded := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: x509Encoded}) return string(pemEncoded) } //This function will decode the private key from a Pem encoded x509 format. func decode(pemEncoded string) (*ecdsa.PrivateKey) { block, _ := pem.Decode([]byte(pemEncoded)) x509Encoded := block.Bytes privateKey, _ := x509.ParseECPrivateKey(x509Encoded) return privateKey } func main() { //Check to see if a string input of less than 250 characters is provided by the user. if (len(os.Args) < 2 || len(os.Args[1]) > 250) { fmt.Println("Please enter a string (preferably email) between 1 and 250 characters") } else { input_var := os.Args[1] //Generate ECDSA private key. privateKey := genKeys() //Generate the Public key from the Private Key. pubz := privateKey.Public() //Generate sha256 hash of the user input. hash := sha256.Sum256([]byte(input_var)) //Generate signature of the sha256 hash of the input using the private key. r, s, err := ecdsa.Sign(rand.Reader, privateKey, hash[:]) if err != nil { panic(err) } //Base64 encode the signature in compliance with RFC4648. //The signature needs to be changed from type big_int to string in order to be Base64 encoded. r_bigstr := r.String() s_bigstr := s.String() str_64 := r_bigstr + ", " + s_bigstr encoded := base64.StdEncoding.EncodeToString([]byte(str_64)) //Converting the public key into type string pubz_bigstr := fmt.Sprint(pubz) //Pem encode the public key. block := &pem.Block{ Type: "Public Key", Bytes: []byte(pubz_bigstr), } blockencode := string(pem.EncodeToMemory(block)) //Use Json to output the user input, signature and public key. group := jsonobj { Message: input_var, Signature: encoded, Pubkey: blockencode, } bent, _:= json.MarshalIndent(group, " ", " ") os.Stdout.Write(bent) fmt.Println("\n") } }
Java
UTF-8
1,566
2.234375
2
[ "Apache-2.0", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package org.jclouds.elb; import org.jclouds.collect.PaginatedSet; import org.jclouds.collect.PaginatedSets; import org.jclouds.elb.domain.LoadBalancer; import org.jclouds.elb.features.LoadBalancerClient; import org.jclouds.elb.options.ListLoadBalancersOptions; import com.google.common.base.Function; /** * Utilities for using ELB. * * @author Adrian Cole */ public class ELB { /** * List loadBalancers based on the criteria in the {@link ListLoadBalancersOptions} passed in. * * @param loadBalancerClient * the {@link LoadBalancerClient} to use for the request * @param options * the {@link ListLoadBalancersOptions} describing the ListLoadBalancers request * * @return iterable of loadBalancers fitting the criteria */ public static Iterable<LoadBalancer> listLoadBalancers(final LoadBalancerClient loadBalancerClient, final ListLoadBalancersOptions options) { return PaginatedSets.lazyContinue(loadBalancerClient.list(options), new Function<String, PaginatedSet<LoadBalancer>>() { @Override public PaginatedSet<LoadBalancer> apply(String input) { return loadBalancerClient.list(options.clone().marker(input)); } @Override public String toString() { return "listLoadBalancers(" + options + ")"; } }); } public static Iterable<LoadBalancer> listLoadBalancers(LoadBalancerClient loadBalancerClient) { return listLoadBalancers(loadBalancerClient, new ListLoadBalancersOptions()); } }
TypeScript
UTF-8
6,275
2.90625
3
[ "MIT" ]
permissive
import { HotReloadService } from "./HotReloadService"; interface HotMethodOptions { //restartOnReload?: boolean; } const defaultHotMethodOptions: HotMethodOptions = { //restartOnReload: true }; /** * Marks a class as hot reloadable. * This marks each method with `@hotMethod` and tracks new methods. */ export function hotClass( module: NodeModule, options = defaultHotMethodOptions ) { return function(target: any) { if (!HotReloadService.instance) { return; } for (const key of Object.getOwnPropertyNames(target.prototype)) { const d = Object.getOwnPropertyDescriptor(target.prototype, key); if (d && typeof d.value === "function" && !d.value.isHot) { hotMethod(module, options)(target.prototype, key, d); Object.defineProperty(target.prototype, key, d); } } // Update existing only after all hot-wrappers have been installed. FunctionStore.instance.addPrototypeAndUpdateExisting( module, target.name, target.prototype ); }; } /** * Marks a method as hot reloadable. * If the method changes while it is executed, it will be restarted. * However, if an hot caller changes, it throws a `ModuleChangedError` exception. * This triggers the topmost changed caller to restart. * The decorator does nothing, if hot reloading has not been enabled. * Warning: This decorator might have an performance impact when hot reloading is enabled. */ export function hotMethod( module: NodeModule, options = defaultHotMethodOptions ) { return function( target: any, propertyKey: string, descriptor: PropertyDescriptor ) { if (!HotReloadService.instance) { return; } const func = descriptor.value; const className: string = target.constructor.name; FunctionStore.instance.setFunc(module, className, propertyKey, func); descriptor.value = getNewFunc(module, className, propertyKey); }; } export class ModuleChangedError { constructor(public readonly frameToRestart: HotStackFrame) {} } /** * Checks whether any hot method has been changed. * If so, throws a `ModuleChangedError` exception that triggers a restart. */ export function restartOnReload() { if (!HotStack.instance.current || !HotReloadService.instance) { return; } if ( HotReloadService.instance!.handleFileMightHaveChanged( HotStack.instance.current.module.filename ) ) { const b = HotStack.instance.findFrameToRestart(); if (b) { throw new ModuleChangedError(b.frameToRestart); } } } function getNewFunc(module: NodeModule, className: string, methodName: string) { const fnName = methodName === "constructor" ? `${className}` : `${methodName}@hot-wrapper`; const obj = { [fnName](this: any, ...args: any[]) { let result: any; while (true) { const entry = getMostRecentFuncAndPushOnStack( module, className, methodName ); try { restartOnReload(); result = entry.fn.apply(this, args); restartOnReload(); break; } catch (e) { if (handleError(e, args, entry).continue) { continue; } throw e; } finally { HotStack.instance.pop(); } } return result; }, }; (obj[fnName] as any).isHot = true; return obj[fnName]; } function handleError( e: Error, args: any[], entry: HotStackFrame ): { continue: boolean } { if (e instanceof ModuleChangedError) { if (e.frameToRestart === entry) { HotReloadService.instance!.log( `Restarting ${e.frameToRestart.className}::${e.frameToRestart.methodName}(${args}).`, args ); return { continue: true }; } else { HotReloadService.instance!.log( `Interrupting ${entry.className}::${entry.methodName}(${args}) because a caller changed.` ); } } return { continue: false }; } function getMostRecentFuncAndPushOnStack( module: NodeModule, className: string, methodName: string ): HotStackFrame { const mostRecentFunc = FunctionStore.instance.getFunc( module, className, methodName )!; const entry: HotStackFrame = { module, className, methodName, fn: mostRecentFunc, }; HotStack.instance.push(entry); return entry; } class FunctionStore { public static instance = new FunctionStore(); private readonly prototypes = new Map<string, any[]>(); private readonly map = new Map<string, Function>(); private getKey( module: NodeModule, className: string, methodName: string ): string { return JSON.stringify({ mod: module.filename, className, methodName }); } public addPrototypeAndUpdateExisting( module: NodeModule, className: string, newProto: any ) { const key = JSON.stringify({ mod: module.filename, className }); let oldProtos = this.prototypes.get(key); if (!oldProtos) { oldProtos = []; this.prototypes.set(key, oldProtos); } for (const oldProto of oldProtos) { for (const propName of Object.getOwnPropertyNames(newProto)) { if (!(propName in oldProto)) { oldProto[propName] = newProto[propName]; } } } oldProtos.push(newProto); } public setFunc( module: NodeModule, className: string, methodName: string, fn: Function ) { const key = this.getKey(module, className, methodName); this.map.set(key, fn); } public getFunc( module: NodeModule, className: string, methodName: string ): Function | undefined { const key = this.getKey(module, className, methodName); return this.map.get(key); } } interface HotStackFrame { module: NodeModule; className: string; methodName: string; fn: Function; } class HotStack { public static instance = new HotStack(); private readonly hotStack = new Array<HotStackFrame>(); public push(entry: HotStackFrame) { this.hotStack.push(entry); } public pop() { this.hotStack.pop(); } public get current(): HotStackFrame | undefined { if (this.hotStack.length === 0) { return undefined; } return this.hotStack[this.hotStack.length - 1]; } public findFrameToRestart(): { frameToRestart: HotStackFrame } | undefined { for (const entry of this.hotStack) { const newFn = FunctionStore.instance.getFunc( entry.module, entry.className, entry.methodName ); if (!newFn) { throw new Error("Cannot happen"); } if (newFn.toString() !== entry.fn.toString()) { return { frameToRestart: entry }; } } return undefined; } }
PHP
UTF-8
245
2.65625
3
[]
no_license
<?php /** * Created by PhpStorm. * User: asad.manzoor * Date: 7/14/16 * Time: 4:42 PM */ require_once "Fighter_Jet.php"; class Mashaak implements Fighter_Jet { public function purchased() { echo "Mashaak purchased"; } }
Swift
UTF-8
3,481
3.15625
3
[]
no_license
// // ViewController.swift // UITableViewSample // // Created by 박성은 on 2018. 2. 21.. // Copyright © 2018년 SE. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { let array = ["a", "b", "c", "d", "e"] let arrayDetail = ["aa", "bb", "cc", "dd", "ee"] override func viewDidLoad() { super.viewDidLoad() let tableView: UITableView = UITableView(frame: self.view.bounds, style: .grouped) tableView.dataSource = self tableView.delegate = self tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") // >> Custom 시 UITableViewCell.self -> CustomViewCell.self tableView.register(MyTableViewCell.self, forCellReuseIdentifier: "myCell") view.addSubview(tableView) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 0 { // >> Custom 시 as! CustomViewCell let cell: MyTableViewCell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as! MyTableViewCell cell.setSelected(true, animated: true) cell.backgroundColor = .gray cell.textLabel?.text = array[indexPath.row] cell.imageView?.image = #imageLiteral(resourceName: "images.jpg") cell.accessoryType = .checkmark cell.detailTextLabel?.text = arrayDetail[indexPath.row] return cell } else { // let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) let cell: UITableViewCell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell") cell.textLabel?.text = "\(indexPath.row)" cell.detailTextLabel?.text = "hmm" cell.backgroundColor = .yellow cell.accessoryType = .detailButton return cell } } func numberOfSections(in tableView: UITableView) -> Int { // print("numberOfSections") return 3 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return array.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.row == 0 { return 100 } return 30 } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section % 2 == 0 { return "짝수" } else { return "홀수" } } // 클릭하면 호출. 클릭한 셀의 indexPath를 가져올 수 있음. func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // 선택된 셀을 가져올 수 있음. let cell = tableView.cellForRow(at: indexPath) let title = cell?.textLabel?.text cell?.textLabel?.text = "선택" let title2 = array[indexPath.row] let nextVC = UIViewController() nextVC.view.backgroundColor = .blue present(nextVC, animated: true, completion: nil) nextVC.title = title } func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { tableView.backgroundColor = .clear } }
Java
UTF-8
1,439
2.859375
3
[]
no_license
package com.pss.chain; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.pss.service.MessageProcessor; /** * 责任链模式测试(chain) * * @author songsong.peng * */ public class ProcessorChain { private static final Logger LOGGER = LoggerFactory.getLogger(ProcessorChain.class); private String message; private List<MessageProcessor> processors = new ArrayList<MessageProcessor>(); /** * Add the processor to processors * * @param messageProcessor * @return the instance it self */ public ProcessorChain addProcessor(MessageProcessor messageProcessor) { processors.add(messageProcessor); return this; } /** * This method is to run each processor * * @param msg * @return string which is processored */ public String doProcessor() { LOGGER.info("Start to processor message {}", this.message); String dealMsg = this.message; for (MessageProcessor processor : processors) { dealMsg = processor.doProcessor(dealMsg); } LOGGER.info("End to processor message {}", this.message); return dealMsg; } public List<MessageProcessor> getProcessors() { return processors; } public void setProcessors(List<MessageProcessor> processors) { this.processors = processors; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
TypeScript
UTF-8
565
2.609375
3
[ "MIT" ]
permissive
import * as JWT from 'jsonwebtoken'; const TEN_MINUTES: string = '10m'; class JwtSignProcessor { static sign(payload: any, globalSecretKey: string): string { let signedToken: string = ''; let validationStatus = globalSecretKey && payload; if (!validationStatus) { throw new Error('Invalid Global Secret Key (or) Payload Specified!'); } signedToken = JWT.sign(payload, globalSecretKey, { expiresIn: TEN_MINUTES }); return signedToken; } } export default JwtSignProcessor;
C++
UTF-8
283
3.21875
3
[]
no_license
#include <cstdio> #include <functional> #include <string> class Person { public: std::string name; }; int main() { Person* p = new Person(); p->name = "Henry"; auto foo = [=](int value1, int value2) -> int { if (value1 > 0) { return value1 + value2; } }; return 0; }
Markdown
UTF-8
1,725
3.234375
3
[]
no_license
# Future Callable - Callable 接口 相比 Runnable 接口 ,可以抛出异常,获得返回值 - Future 对象 ,用来获取到 Callable 对象中的call方法的返回值 - 获取方法 - Future<V> f1 - f1.get() 获取到值(结果只能在计算完成后get‘进行检索,如有必要,阻塞,直到准备就绪) - - ``` package TestSychoronized; import java.util.concurrent.*; public class TestCallable { public static void main(String[] args) throws ExecutionException, InterruptedException { ExecutorService es = Executors.newCachedThreadPool(); Callable<Integer> task1 = new Callable<Integer>() { @Override public Integer call() throws Exception { int result = 0; for (int i = 1; i < 100; i+=2) { result += i; Thread.sleep(100); } return result; } }; Callable<Integer> task2 = new Callable<Integer>() { @Override public Integer call() throws Exception { int result = 0; for (int i = 2; i < 100; i+=2) { result += i; Thread.sleep(100); } return result; } }; Future<Integer> f1 = es.submit(task1); Future<Integer> f2 = es.submit(task2); System.out.println(""); int result = f1.get()+f2.get(); System.out.println(result); } } ```
Markdown
UTF-8
5,525
3.25
3
[]
no_license
# Rails API [Video](https://youtu.be/FjEJ2LLkxHk) ### Objectives - Understand WHY we want to use a Rails API - Understand how to get a Rails API up and running from scratch - Understand how to use a Rails API with your SPA ### Why a Rails API? - JSON is language agnostic. It is just a string that follows rules that our language of choice can parse into a datatype that pertains to that language (e.g. Ruby Hashes, JavaScript Objets). We can then take that information and turn them into custom objects. - So, we can now build a backend that can be used by MULTIPLE frontends! We can build a web app with JavaScript, a mobile app with Swift, Java, or React Native, and we can even let other developers use our backend to make their own sites!!! - We can get the great user expereience of a JS-based frontend while keeping our backend flexible. Do this with an existing rails app: ```ruby class UsersController < ApplicationController def index @users = User.all respond_to do |format| format.html { render :index } format.json { render json: @users } end end end ``` If we navigate to http://localhost:3000/users.html we’ll see html, if we navigate to http://localhost:3000/users.json we will see JSON. ### Rails API - How? We ONLY care about JSON now and will never want to return HTML Start by doing: `rails new my-app --api` How is this different?? - No layout view - Controller inherits from ActionController::API which is a lighter-weight version of the class. It does not have ActionView Now, let's generate a user: `rails g model user username password_digest name` Migrate `rails db:migrate` And test it in the console `User.create(name: "Micah", username: "micahshute")` Note we will leave password blank for now. Now, make the controller: `rails g controller api/v1/users` - Why do we version? - It allows you to change the api which may break the code of people using v1, giving them time to transition over. - How do we customize the JSON that is returned? - Show relationshiops - Hide data ### Serialization Go into rails console: ```ruby u = User.all.first u.to_json ``` - Let's see how to include relationships and hide other data. - Start by creating Tweet model which include content `rails g model tweet content user:belongs_to` Update models with has_many and belongs_to Make some tweets in the console. ***Refresher Q: How do I make tweets in rails c?*** A: ```ruby u = User.all.first u.tweets.build(content: "My tweet!") u.save ``` In the `users_controller.rb` file: ```ruby def index @users = User.all render json: @users end ``` See it in the browser. Now let's add the relationship and hide the password Go to the route, let them figure out why the error is there. (No route) ***Q: How do I set up my routes?*** A: ```ruby # config/routes.rb Rails.application.routes.draw do namespace :api do namespace :v1 do resources :users, only: [:index] end end end ``` ***Q: What route do I go to?*** A: /api/v1/users and I get: ```json [ { id: 1, username: "micahshute", password_digest: null, name: "Micah", created_at: "2019-11-12T19:45:39.873Z", updated_at: "2019-11-12T19:45:39.873Z" } ] ``` OK, I want to get related tweets and not show my password_digest: ```ruby #users_controller.rb def index @users = User.all render json: @users, only: [:id, :name], include: :tweets end ``` And now your password is hidden and you have your tweets coming through! ### Connect to the Front End Go to any website (besides localhost) and attempt a fetch request (expecting CORS error) ```js const url = 'http://localhost:3000/api/v1/users' fetch(url) .then(res => res.json()) .then(json => console.log(json)) ``` ERROR: ``` Access to fetch at 'http://localhost:3000/api/v1/users' from origin 'https://education.flatironschool.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. Cross-Origin Read Blocking (CORB) blocked cross-origin response http://localhost:3000/api/v1/users with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details. ``` ***Q: What does this mean??*** A: CORS has blocked us from making cross-site requests. It is important because it lets a website "whitelist" who is able to access it with fetch. CORS Resources: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS https://www.owasp.org/index.php/CORS_OriginHeaderScrutiny CORS is a rule that `fetch` follows that prevents making a request from one website to another website unless the target website allows it explicitly. So, let's tell our rails app to allow our frontend to get data from it! we will start by just letting our API accept all traffic. You can later update this to ONLY allow your front-end (and your mobile app!) ### Allow CORS 1. Uncomment out `rack-cors` in Gemfile 2. run `bundle install` 3. Open `app/config/initializers/cors.rb` and change it to: ```ruby Rails.application.config.middleware.insert_before 0, Rack::Cors do allow do origins '*' resource '*', headers: :any, methods: [:get, :post, :put, :patch, :delete, :options, :head] end end ``` (should just be able to uncomment it)
Python
UTF-8
546
4.875
5
[]
no_license
# Errors and Exceptions Exercise 4 # 0 puntos posibles (no calificados) # Write a program that asks the user for an input and tries to handle the error that may occur when you try to type cast the input to an int using the try ... except ... else clause. Your function should print the result if the operation is successful, if the operation is not successful your program should print 'Error' # # Main value = input("Enter the string for resolve error: ") try: value = int(value) except ValueError: print("Error") else: print(value)
Python
UTF-8
1,230
2.859375
3
[]
no_license
import pandas as pd from fpdf import FPDF import funconstructor as fc def newPDF(): pdf = FPDF('P', 'mm', 'A4') pdf.add_page() #Set Title pdf.set_font('Arial', 'B', 20) pdf.cell(0, 10, 'Social Media Report', 0, 1, 'C') #First row of data pdf.cell(0, 10, ' ', 0, 1, 'C') pdf.set_font('Arial', '', 14) volume, percentage = fc.volumeCategories('../output/predicted.csv') pdf.cell(95, 10, f'Total of tweets {volume}') pdf.set_font('Arial', '', 14) pdf.cell(95, 10, f'Percentage of tweets classificated {percentage}%', 0, 1, 'C') pdf.cell(0, 10, ' ', 0, 1, 'C') #Categories pdf.set_font('Arial', '', 14) pdf.cell(0, 10, 'Categories', 0, 1, 'C') pdf.image('../output/barcategories.png', 40, h=90) pdf.cell(0, 10, ' ', 0, 1, 'C') #Sentiment pdf.set_font('Arial', '', 14) pdf.cell(95, 10, 'Sentiment', 0, 0, 'C') pdf.image('../output/sentimentAnalysis.png', 5, 170, h=70) pdf.set_font('Arial', '', 14) pdf.cell(95, 10, 'Sentiment by Category', 0, 1, 'C') pdf.image('../output/sentimentcat.png', 100, 170, h=70) pdf.output('../output/report.pdf', 'F') print('Your PDF is ready')
JavaScript
UTF-8
3,686
2.734375
3
[]
no_license
/** * Created by Namita Malik on 26/5/15. */ (function (ng) { var eduStat = ng.module('eduStat', []); eduStat.controller('StudentController', ['StudentService',function (StudentService) { var studentController = this; studentController.students = StudentService.getStudentList(); function clearErrorMessage() { studentController.mandatoryErrorMessage = ""; studentController.rollErrorMessage = ""; studentController.scoreErrorMessage = ""; } studentController.showStudentModal = function () { studentController.rollNumbr = ""; studentController.name = ""; studentController.score = ""; clearErrorMessage(); ng.element('#studentModal').modal('show'); }; studentController.addStudent = function () { var tempObject = { roll_no: studentController.rollNumbr, name: studentController.name, score: parseInt(studentController.score) }; clearErrorMessage(); if ((studentController.rollNumbr && studentController.name && studentController.score)) { if (isNaN(studentController.rollNumbr) || studentController.rollNumbr<1) { studentController.rollErrorMessage = "Please enter a valid roll number." } else if (isNaN(studentController.score)||studentController.score<0) { studentController.scoreErrorMessage = "Please enter a valid score." } else { StudentService.saveStudent(tempObject); studentController.students.push(tempObject); ng.element('#studentModal').modal('hide'); } } else { studentController.mandatoryErrorMessage = "All the fields are mandatory"; } }; studentController.deleteStudent = function (toBeDeletedStudent) { angular.forEach(studentController.students, function (value, index) { if (value.roll_no == toBeDeletedStudent.roll_no && value.name == toBeDeletedStudent.name) { studentController.students.splice(index, 1); StudentService.deleteStudentList(index); } }); }; studentController.updateStudent = function(index) { StudentService.updateStudent(index, studentController.students[index]); }; }]); eduStat.filter('average', function () { return function (students) { var temp = 0; ng.forEach(students, function (value) { temp = temp + value.score; }); if(students.length==0){ return 0; } else { return parseInt((temp / students.length)); } } }); eduStat.filter('max', function () { return function (students) { var max = 0; ng.forEach(students, function (value) { if (max < value.score) { max = value.score; } }); return parseInt(max); } }); eduStat.filter('min', function () { return function (students) { var min = 0; ng.forEach(students, function (value, index) { if (index === 0) { min = value.score; } if (min > value.score) { min = value.score; } }); return parseInt(min); } }); })(angular);
C#
UTF-8
6,020
2.515625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SqlConnectionTest { struct RBFormat { public string code; public int tradeDate, naturalDate, tradeTime, tradeStatus; public double ask, bid, askv, bidv, lastPrice, highPrice, lowPrice,volume,turnover,openInterest,preOpenInterest,preClose,preSettle; } struct RBStatus { public int date,time; public double ask, bid, askv, bidv, lastPrice, deltaVolume, deltaTurnover, deltaOpenInterest, avgPrice; } /// <summary> /// 期权价格格式 /// </summary> struct optionFormat { public int code; public string type; public double strike; public int startDate, endDate; public int date, time; public double lastPrice; public optionPriceWithGreek[] ask, bid; public double preClose, preSettle; public double midDelta, midVolatility; public double openMargin; } /// <summary> /// 记录期权盘口价格变动的结构体。 /// </summary> struct optionPositionChange { public int lastTime,thisTime; public double lastPrice; public double midDelta, midVolatility; public List<optionPriceWithGreek> askChange, bidChange; public optionPositionChange(int lastTime,int thisTime,double lastPrice,double midDelta,double midVolatility) { this.lastTime = lastTime; this.thisTime = thisTime; this.lastPrice = lastPrice; this.midDelta = midDelta; this.midVolatility = midVolatility; askChange = new List<optionPriceWithGreek>(); bidChange = new List<optionPriceWithGreek>(); } } /// <summary> /// 期权带希腊值盘口价格的格式 /// </summary> struct optionPriceWithGreek { public double price, volume, volatility, delta; public optionPriceWithGreek(double price,double volume,double volatility,double delta) { this.price = price; this.volume = volume; this.volatility = volatility; this.delta = delta; } } /// <summary> /// 股票价格的格式 /// </summary> struct stockFormat { public int code; public int date, time; public double lastPrice; public stockPrice[] ask, bid; public double preClose; } /// <summary> /// 股票盘口价格的格式 /// </summary> struct stockPrice { public double price, volume; public stockPrice(double price,double volume) { this.price = price; this.volume = volume; } } /// <summary> /// 存储期权基本信息的结构体。 /// </summary> struct optionInfo { public int optionCode; public string optionName; public int startDate; public int endDate; public string optionType; public string executeType; public double strike; public string market; } /// <summary> /// 描述持仓仓位和成本的结构体 /// </summary> struct optionHold { public double position; public double cost; public optionHold(double cost,double position) { this.cost = cost; this.position = position; } } /// <summary> /// 描述资金情况的结构体 /// </summary> struct cashStatus { public double availableFunds; public double optionMargin; public double IHhold, IHprice, IHMargin,IHCost; public Dictionary<int, optionHold> optionList; public cashStatus(double availableFunds,double optionMargin=0,double IHhold=0,double IHprice=0,double IHMargin=0,double IHCost=0) { this.availableFunds = availableFunds; this.optionMargin = optionMargin; this.IHhold = IHhold; this.IHprice = IHprice; this.IHMargin = IHMargin; this.IHCost = IHCost; optionList = new Dictionary<int, optionHold>(); } } /// <summary> /// 跨期交易期权对 /// </summary> struct timeSpreadPair { public int frontCode; public int nextCode; } /// <summary> /// 记录期权具体的交易信息 /// </summary> struct optionTradeRecord { public int optionCode; public int date; public int time; public double strike; public double ETFPrice; public string type; public double price; public double volume; public double volatility; public double cost; public double holdVolume; public string remark; public optionTradeRecord(int optionCode,int date,int time,double price,double volume,double ETFPrice,double strike=0,string type="",double volatility=0,double cost=0,double holdVolume=0,string remark="") { this.optionCode = optionCode; this.date = date; this.time = time; this.ETFPrice = ETFPrice; this.strike = strike; this.type = type; this.price = price; this.volume = volume; this.volatility = volatility; this.cost = cost; this.holdVolume = holdVolume; this.remark = remark; } } /// <summary> /// 期权持仓的状态 /// </summary> struct optionStatus { public double presentValue; public double margin; public double delta; public double hold; public optionStatus(double PV,double margin,double delta,double hold) { this.presentValue = PV; this.margin = margin; this.delta = delta; this.hold = hold; } } }
JavaScript
UTF-8
2,723
2.59375
3
[ "ISC" ]
permissive
const https = require('https'); const http = require('http'); const url = require('url'); const log = require('./log.js'); var api = (function () { function request(method, href, headers, data, done) { var endpoint, options, request, requestContent; endpoint = url.parse(href); if (!headers) { headers = {}; } options = { method: method, hostname: endpoint.hostname, path: endpoint.path, port: endpoint.port, headers: headers }; if(method === 'POST') { requestContent = JSON.stringify(data || {}); options.headers['Content-Type'] = 'application/json'; options.headers['Content-Length'] = Buffer.byteLength(requestContent); } function apiRequestCallback(response) { var content, jsonContent; content = ''; response.on('data', function (chunk) { return content += chunk; }); response.on('end', function () { try { jsonContent = JSON.parse(content); log.info('Json content: %s', JSON.stringify(jsonContent)); } catch (e) { log.info('Non-json content: %s', content); } var statusCode = response.statusCode; if (statusCode / 100 != 2) { console.log('response is in error:', statusCode, response.req.method, response.req.path) } done(null, { status: statusCode, content: jsonContent || content }); }); request.on('error', function (err) { log.error('Error: %s', err); done(err); }); } log.info('Requesting: %s', url.format(endpoint)); if (endpoint.protocol === 'http:') { request = http.request(options, apiRequestCallback); } else if (endpoint.protocol === 'https:') { request = https.request(options, apiRequestCallback); } else { done('Unknown protocol:' + endpoint.protocol) } if(method === 'POST') { request.write(requestContent); } request.end(); } function get(href, headers, done) { request('GET', href, headers, null, done); } function post(href, headers, data, done) { request('POST', href, headers, data, done); } function del(href, headers, done) { request('DELETE', href, headers, null, done); } return { get: get, post: post, del: del }; })(); module.exports = api;
JavaScript
UTF-8
3,657
2.5625
3
[]
no_license
/*var ip = "192.168.1.43";//location.hostname; var robotPort = "4900"; var robotServer = 'http://'+ip+':'+robotPort; $('#robotDur').click(function() { $.post(robotServer+'/robot/dur,0,0'); }); $('#robotIleri').click(function() { var adimboyu = (parseFloat(35 * $('#AdimBoyu').val())).toString(); var adim = $('#Adim').val(); var hiz = $('#Hiz').val(); $.post(robotServer+'/robot/adim_boyu,' + adimboyu); $.post(robotServer+'/robot/ileri,' + adim + ',' + hiz); }); $('#robotGeri').click(function() { var adimboyu = (parseFloat(35 * $('#AdimBoyu').val())).toString(); var adim = $('#Adim').val(); var hiz = $('#Hiz').val(); $.post(robotServer+'/robot/adim_boyu,' + adimboyu); $.post(robotServer+'/robot/geri,' + adim + ',' + hiz); }); $('#robotSolDon').click(function() { var robotAci = $('#robotAci').val(); var AdimSayisi = parseInt(robotAci / 2.4); $.post(robotServer+'/robot/adim_boyu,1'); $.post(robotServer+'/robot/don,sol,' + AdimSayisi); }); $('#robotSagDon').click(function() { var robotAci = $('#robotAci').val(); var AdimSayisi = parseInt(robotAci / 2.5); $.post(robotServer+'/robot/adim_boyu,1'); $.post(robotServer+'/robot/don,sag,' + AdimSayisi); }); $('#camMerkez').click(function() { $.post(robotServer+'/robot/cam,sol,0'); $.post(robotServer+'/robot/cam,asagi,0'); }); $('#camYukari').click(function() { var robotAci = $('#camAci').val(); $.post(robotServer+'/robot/cam,yukari,' + robotAci); }); $('#camAsagi').click(function() { var robotAci = $('#camAci').val(); $.post(robotServer+'/robot/cam,asagi,' + robotAci); }); $('#camSol').click(function() { var robotAci = $('#camAci').val(); $.post(robotServer+'/robot/cam,sol,' + robotAci); }); $('#camSag').click(function() { var robotAci = $('#camAci').val(); $.post(robotServer+'/robot/cam,sag,' + robotAci); }); function initRobotMoveData() { document.getElementById("robotAci").value = "90" document.getElementById("AdimBoyu").value = "0.1" document.getElementById("TiltAci").value = "0" document.getElementById("PanAci").value = "0" document.getElementById("Hiz").value = "100" document.getElementById("InvisibleTilt").value = "0" document.getElementById("InvisiblePan").value = "0" document.getElementById("PanKonum").value = "Merkez" document.getElementById("TiltKonum").value = "Merkez" } */ function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } var ip = "192.168.1.43";//location.hostname; var robotPort = "4900"; var robotServer = 'http://'+ip+':'+robotPort; function ileri(adimboyu, adim, hiz){ $.post(robotServer+'/robot/adim_boyu,' + adimboyu); $.post(robotServer+'/robot/ileri,' + adim + ',' + hiz); } function geri(adimboyu, adim, hiz){ $.post(robotServer+'/robot/adim_boyu,' + adimboyu); $.post(robotServer+'/robot/geri,' + adim + ',' + hiz); } function sol(robotAci){ var AdimSayisi = parseInt(robotAci / 2.4); $.post(robotServer+'/robot/adim_boyu,1'); $.post(robotServer+'/robot/don,sol,' + AdimSayisi); } function sag(robotAci){ var AdimSayisi = parseInt(robotAci / 2.4); $.post(robotServer+'/robot/adim_boyu,1'); $.post(robotServer+'/robot/don,sag,' + AdimSayisi); } function kafamerkez(){ $.post(robotServer+'/robot/cam,sol,0'); $.post(robotServer+'/robot/cam,asagi,0'); } function kafayukari(robotAci) { $.post(robotServer+'/robot/cam,yukari,' + robotAci); } function kafaasagi(robotAci) { $.post(robotServer+'/robot/cam,asagi,' + robotAci); } function kafasol(robotAci) { $.post(robotServer+'/robot/cam,sol,' + robotAci); } function kafasag(robotAci) { $.post(robotServer+'/robot/cam,sag,' + robotAci); }
C
UTF-8
2,195
3.421875
3
[]
no_license
There are two singly linked lists in a system. By some programming error the end node of one of the linked list got linked into the second list, forming a inverted Y shaped list. Write a program to get the point where two linked lists merge. Y ShapedLinked List Above diagram shows an example with two linked list having 15 as intersection point. Expected time complexity is O(m + n) where m and n are lengths of two linked lists Input: You have to complete the method which takes two arguments as heads of two linked lists. Output: The function should return data value of a node where two linked lists merge. If linked list do not merge at any point, then it shoudl return -1. Constraints: 1 <=T<= 50 1 <=N<= 100 1 <=value<= 1000 Example: Input: 2 2 3 2 10 20 30 40 50 5 10 2 3 0 10 20 30 40 50 First line is number of test cases. Every test case has four lines. First line of every test case contains three numbers, x (number of nodes before merge point in 1st list), y(number of nodes before merge point in 11nd list) and z (number of nodes after merge point). Next three lines contain x, y and z values. Output: 5 -1 int intersectPoint(Node* head1, Node* head2) { Node *p,*q,*last,*lost; p=head1; q=head2; last=head1; lost=head2; if(head1==NULL || head2==NULL) return -1; while(last->next!=NULL) { last=last->next; } while(lost->next!=NULL) { lost=lost->next; } if(lost!=last) { return -1; } while(1) { head1=head1->next; p->next=NULL; head2= head2->next; q->next=NULL; p=head1; q=head2; if(head1==head2) return head1->data; if(head1==last) { while(head2->next!=NULL) { head2=head2->next; } return head2->data; } if(head2==last) { while(head1->next!=NULL) { head1=head1->next; } return head1->data; } if(head1->next==NULL) return head1->data; if(head2->next==NULL) return head2->data; } }
Markdown
UTF-8
2,163
2.9375
3
[]
no_license
--- title: "T3 JavaScript Framework for Large-scale Web Applications" description: "T3 is a client-side JavaScript framework for building large-scale web applications. T3 is different than most JavaScript frameworks. It’s meant to be a small piece of an overall architecture that allows you to build scalable client-side code. A T3 application is managed by the Application object, whose primary job is to manage modules, services, and behaviors. It’s the combination of these three types of objects that allow you to build a scalable JavaScript front-end." date: "2015-05-21T12:58:23.078Z" lastmod: "2015-05-21T12:58:23.078Z" slug: "t3-javascript-framework-for-large-scale-web-applications" categories: ["Web-Development", "Development"] tags: ["JavaScript"] thumbnail: "http://rs963.pbsrc.com/albums/ae120/Mirodil/WebSnippet/unnamed_1.jpg~c200" image: "http://i963.photobucket.com/albums/ae120/Mirodil/WebSnippet/unnamed_1.jpg" source: "http://t3js.org/" --- [T3](http://t3js.org/) is a client-side JavaScript framework for building large-scale web applications. T3 is different than most JavaScript frameworks. It’s meant to be a small piece of an overall architecture that allows you to build scalable client-side code. A T3 application is managed by the Application object, whose primary job is to manage modules, services, and behaviors. It’s the combination of these three types of objects that allow you to build a scalable JavaScript front-end. [T3](http://t3js.org/)’s design enforces best practices such as loose coupling by limiting how certain components can communicate with each other. Modules cannot interact directly with other modules but may communicate with them through an event bus. Modules may use services directly, but may only reference behaviors in a declarative way. These restrictions ensure that the various pieces remain loosely-coupled to make dependency management easy and maintenance self-contained. The loosely-coupled nature of [T3](http://t3js.org/) components means that creating tests is easy. Dependencies are injected into each component, making it trivial to substitute a mock object in place of real ones.
Python
UTF-8
9,524
2.546875
3
[ "Apache-2.0" ]
permissive
""" The script shows how to train Augmented SBERT (Domain-Transfer/Cross-Domain) strategy for STSb-QQP dataset. For our example below we consider STSb (source) and QQP (target) datasets respectively. Methodology: Three steps are followed for AugSBERT data-augmentation strategy with Domain Trasfer / Cross-Domain - 1. Cross-Encoder aka BERT is trained over STSb (source) dataset. 2. Cross-Encoder is used to label QQP training (target) dataset (Assume no labels/no annotations are provided). 3. Bi-encoder aka SBERT is trained over the labeled QQP (target) dataset. Citation: https://arxiv.org/abs/2010.08240 Usage: python train_sts_qqp_crossdomain.py OR python train_sts_qqp_crossdomain.py pretrained_transformer_model_name """ from torch.utils.data import DataLoader from sentence_transformers import models, losses, util, LoggingHandler, SentenceTransformer from sentence_transformers.cross_encoder import CrossEncoder from sentence_transformers.cross_encoder.evaluation import CECorrelationEvaluator from sentence_transformers.evaluation import EmbeddingSimilarityEvaluator, BinaryClassificationEvaluator from sentence_transformers.readers import InputExample from datetime import datetime from zipfile import ZipFile import logging import csv import sys import torch import math import gzip import os #### Just some code to print debug information to stdout logging.basicConfig(format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO, handlers=[LoggingHandler()]) #### /print debug information to stdout #You can specify any huggingface/transformers pre-trained model here, for example, bert-base-uncased, roberta-base, xlm-roberta-base model_name = sys.argv[1] if len(sys.argv) > 1 else 'bert-base-uncased' batch_size = 16 num_epochs = 1 max_seq_length = 128 use_cuda = torch.cuda.is_available() ###### Read Datasets ###### sts_dataset_path = 'datasets/stsbenchmark.tsv.gz' qqp_dataset_path = 'quora-IR-dataset' # Check if the STSb dataset exsist. If not, download and extract it if not os.path.exists(sts_dataset_path): util.http_get('https://sbert.net/datasets/stsbenchmark.tsv.gz', sts_dataset_path) # Check if the QQP dataset exists. If not, download and extract if not os.path.exists(qqp_dataset_path): logging.info("Dataset not found. Download") zip_save_path = 'quora-IR-dataset.zip' util.http_get(url='https://sbert.net/datasets/quora-IR-dataset.zip', path=zip_save_path) with ZipFile(zip_save_path, 'r') as zipIn: zipIn.extractall(qqp_dataset_path) cross_encoder_path = 'output/cross-encoder/stsb_indomain_'+model_name.replace("/", "-")+'-'+datetime.now().strftime("%Y-%m-%d_%H-%M-%S") bi_encoder_path = 'output/bi-encoder/qqp_cross_domain_'+model_name.replace("/", "-")+'-'+datetime.now().strftime("%Y-%m-%d_%H-%M-%S") ###### Cross-encoder (simpletransformers) ###### logging.info("Loading cross-encoder model: {}".format(model_name)) # Use Huggingface/transformers model (like BERT, RoBERTa, XLNet, XLM-R) for cross-encoder model cross_encoder = CrossEncoder(model_name, num_labels=1) ###### Bi-encoder (sentence-transformers) ###### logging.info("Loading bi-encoder model: {}".format(model_name)) # Use Huggingface/transformers model (like BERT, RoBERTa, XLNet, XLM-R) for mapping tokens to embeddings word_embedding_model = models.Transformer(model_name, max_seq_length=max_seq_length) # Apply mean pooling to get one fixed sized sentence vector pooling_model = models.Pooling(word_embedding_model.get_word_embedding_dimension(), pooling_mode_mean_tokens=True, pooling_mode_cls_token=False, pooling_mode_max_tokens=False) bi_encoder = SentenceTransformer(modules=[word_embedding_model, pooling_model]) ##################################################### # # Step 1: Train cross-encoder model with STSbenchmark # ##################################################### logging.info("Step 1: Train cross-encoder: {} with STSbenchmark (source dataset)".format(model_name)) gold_samples = [] dev_samples = [] test_samples = [] with gzip.open(sts_dataset_path, 'rt', encoding='utf8') as fIn: reader = csv.DictReader(fIn, delimiter='\t', quoting=csv.QUOTE_NONE) for row in reader: score = float(row['score']) / 5.0 # Normalize score to range 0 ... 1 if row['split'] == 'dev': dev_samples.append(InputExample(texts=[row['sentence1'], row['sentence2']], label=score)) elif row['split'] == 'test': test_samples.append(InputExample(texts=[row['sentence1'], row['sentence2']], label=score)) else: #As we want to get symmetric scores, i.e. CrossEncoder(A,B) = CrossEncoder(B,A), we pass both combinations to the train set gold_samples.append(InputExample(texts=[row['sentence1'], row['sentence2']], label=score)) gold_samples.append(InputExample(texts=[row['sentence2'], row['sentence1']], label=score)) # We wrap gold_samples (which is a List[InputExample]) into a pytorch DataLoader train_dataloader = DataLoader(gold_samples, shuffle=True, batch_size=batch_size) # We add an evaluator, which evaluates the performance during training evaluator = CECorrelationEvaluator.from_input_examples(dev_samples, name='sts-dev') # Configure the training warmup_steps = math.ceil(len(train_dataloader) * num_epochs * 0.1) #10% of train data for warm-up logging.info("Warmup-steps: {}".format(warmup_steps)) # Train the cross-encoder model cross_encoder.fit(train_dataloader=train_dataloader, evaluator=evaluator, epochs=num_epochs, evaluation_steps=1000, warmup_steps=warmup_steps, output_path=cross_encoder_path) ################################################################## # # Step 2: Label QQP train dataset using cross-encoder (BERT) model # ################################################################## logging.info("Step 2: Label QQP (target dataset) with cross-encoder: {}".format(model_name)) cross_encoder = CrossEncoder(cross_encoder_path) silver_data = [] with open(os.path.join(qqp_dataset_path, "classification/train_pairs.tsv"), encoding='utf8') as fIn: reader = csv.DictReader(fIn, delimiter='\t', quoting=csv.QUOTE_NONE) for row in reader: if row['is_duplicate'] == '1': silver_data.append([row['question1'], row['question2']]) silver_scores = cross_encoder.predict(silver_data) # All model predictions should be between [0,1] assert all(0.0 <= score <= 1.0 for score in silver_scores) binary_silver_scores = [1 if score >= 0.5 else 0 for score in silver_scores] ########################################################################### # # Step 3: Train bi-encoder (SBERT) model with QQP dataset - Augmented SBERT # ########################################################################### logging.info("Step 3: Train bi-encoder: {} over labeled QQP (target dataset)".format(model_name)) # Convert the dataset to a DataLoader ready for training logging.info("Loading BERT labeled QQP dataset") qqp_train_data = list(InputExample(texts=[data[0], data[1]], label=score) for (data, score) in zip(silver_data, binary_silver_scores)) train_dataloader = DataLoader(qqp_train_data, shuffle=True, batch_size=batch_size) train_loss = losses.MultipleNegativesRankingLoss(bi_encoder) ###### Classification ###### # Given (quesiton1, question2), is this a duplicate or not? # The evaluator will compute the embeddings for both questions and then compute # a cosine similarity. If the similarity is above a threshold, we have a duplicate. logging.info("Read QQP dev dataset") dev_sentences1 = [] dev_sentences2 = [] dev_labels = [] with open(os.path.join(qqp_dataset_path, "classification/dev_pairs.tsv"), encoding='utf8') as fIn: reader = csv.DictReader(fIn, delimiter='\t', quoting=csv.QUOTE_NONE) for row in reader: dev_sentences1.append(row['question1']) dev_sentences2.append(row['question2']) dev_labels.append(int(row['is_duplicate'])) evaluator = BinaryClassificationEvaluator(dev_sentences1, dev_sentences2, dev_labels) # Configure the training. warmup_steps = math.ceil(len(train_dataloader) * num_epochs * 0.1) #10% of train data for warm-up logging.info("Warmup-steps: {}".format(warmup_steps)) # Train the bi-encoder model bi_encoder.fit(train_objectives=[(train_dataloader, train_loss)], evaluator=evaluator, epochs=num_epochs, evaluation_steps=1000, warmup_steps=warmup_steps, output_path=bi_encoder_path ) ############################################################### # # Evaluate Augmented SBERT performance on QQP benchmark dataset # ############################################################### # Loading the augmented sbert model bi_encoder = SentenceTransformer(bi_encoder_path) logging.info("Read QQP test dataset") test_sentences1 = [] test_sentences2 = [] test_labels = [] with open(os.path.join(qqp_dataset_path, "classification/test_pairs.tsv"), encoding='utf8') as fIn: reader = csv.DictReader(fIn, delimiter='\t', quoting=csv.QUOTE_NONE) for row in reader: test_sentences1.append(row['question1']) test_sentences2.append(row['question2']) test_labels.append(int(row['is_duplicate'])) evaluator = BinaryClassificationEvaluator(test_sentences1, test_sentences2, test_labels) bi_encoder.evaluate(evaluator)
PHP
UTF-8
4,103
3.046875
3
[]
no_license
<?php class DBase { private $db_host; private $db_user; private $db_pass; private $db_driver; private $db_name; public $dbconn; function __construct() { // connet to db $this->handel_db_vars(); $this->connect(); } function __destruct() { // TODO: Implement __destruct() method. $this->close_connection(); } private function handel_db_vars(){ $this->db_host = env("DB_HOST"); $this->db_user = env("DB_USER"); $this->db_pass = env("DB_PASS"); $this->db_driver = env("DB_DRIV"); $this->db_name = env("DB_NAME"); } private function connect(){ $this->dbconn = new PDO($this->db_driver.':host='.$this->db_host.';dbname='.$this->db_name, $this->db_user, $this->db_pass); if($this->dbconn->errorCode()!=null){ return false; } $this->dbconn->exec("set names utf8 "); } private function close_connection(){ $this->dbconn = null; } public function DB_Query($sql){ $stmt = $this->dbconn->prepare($sql); return $stmt->execute(); } public function DB_Insert_With_Last_Id($sql){ $commit = $this->DB_Query($sql); if($commit) return $this->dbconn->lastInsertId(); return 0; } public function DB_Row_Count($sql){ $stmt = $this->dbconn->prepare($sql); $stmt->execute(); return $stmt->rowCount(); } public function DB_Login_Query_Via_Email($table, $email,$password){ $sql = "SELECT * FROM `{$table}` WHERE email = '{$email}'"; $resposne = []; $stmt = $this->dbconn->prepare($sql); $stmt->execute(); $stmt->setFetchMode(PDO::FETCH_ASSOC); $rowCount = $stmt->rowCount(); if($rowCount<=0){ $resposne["login"] = false; $resposne["message"] = "email not valid"; }else{ $data = $stmt->fetch(); $current_password = $data["password"]; if(password_verify($password,$current_password)){ $resposne["login"] = true; $resposne["data"] = $data; }else{ $resposne["login"] = false; $resposne["message"] = "password worng "; } } return $resposne; } public function DB_Delete($table,$val , $identy = "id" ){ $sql = "DELETE FROM $table WHERE `{$identy}` = '{$val}' "; $query = $this->DB_Query($sql); return $query; } public function DB_Fetch_Row($table,$val,$identy = "id", $colums = "*"){ $stmt = $this->dbconn->prepare("SELECT {$colums} FROM {$table} WHERE `{$identy}` = '{$val}'"); $stmt->execute(); $stmt->setFetchMode(PDO::FETCH_ASSOC); $resposne = []; if($stmt->rowCount()>=1){ $resposne = $stmt->fetch(); } return $resposne; } public function DB_Fetch_Grid($table = "users", $orderBy = ["clm"=>"id","case"=>"desc"], $colums = "*"){ $stmt = $this->dbconn->prepare("SELECT {$colums} FROM {$table} ORDER BY {$orderBy['clm']} {$orderBy['case']}"); $stmt->execute(); $stmt->setFetchMode(PDO::FETCH_ASSOC); $resposne = $stmt->fetchAll(); return $resposne; } public function DB_Fetch_Grid_With_Condition($table = "users", $where = ""){ $stmt = $this->dbconn->prepare("SELECT * FROM {$table} {$where} "); $stmt->execute(); $stmt->setFetchMode(PDO::FETCH_ASSOC); $resposne = $stmt->fetchAll(); return $resposne; } public function DB_Fetch_Grid_WHERE($table = "users", $where = "id",$ob = "=", $val = ""){ $stmt = $this->dbconn->prepare("SELECT * FROM {$table} WHERE {$where} {$ob} {$val} ORDER BY id DESC"); $stmt->execute(); $stmt->setFetchMode(PDO::FETCH_ASSOC); $resposne = $stmt->fetchAll(); return $resposne; } }
Python
UTF-8
1,643
2.53125
3
[]
no_license
# -*- coding: utf-8 -*- import requests from bs4 import BeautifulSoup from pandas import DataFrame import uuid,sys def scrapechart(soup) : blocks =[] taglist = soup.find('tbody',{"class" : "lister-list" }).findAll('tr') for t in taglist : movie_block={} try : movie_block['ImdbId']=t.find('td',{'class':'posterColumn'}).find('a')['href'].split('/')[2] ### img_url=t.find('td',{'class':'posterColumn'}).find('img')['src'] img_url = img_url.split(".") img_url = "https://m.media-amazon." + img_url[2]+"." movie_block['poster_url']=img_url ### movie_block['name']=t.find('td',{'class':'titleColumn'}).find('a').text.strip() movie_block['year']=t.find('span',{'class':'secondaryInfo'}).text.strip() movie_block['rating']=t.find('td',{'class':'ratingColumn'}).find('strong').text.strip() movie_block['rating-notes']=t.find('td',{'class':'ratingColumn'}).find('strong')['title'] except Exception as e: print(e) blocks.append(movie_block) unique_filename = str(uuid.uuid4()) with open('charts/'+unique_filename +'.json', 'w') as json_file: json.dump(blocks, json_file) def scrape(url) : r = requests.get(url) soup = BeautifulSoup(r.text, 'html.parser') scrapechart(soup) url="https://www.imdb.com/india/top-rated-indian-movies/?pf_rd_m=A2FGELUUNOQJNL&pf_rd_p=4da9d9a5-d299-43f2-9c53-f0efa18182cd&pf_rd_r=6K4T71CDNA8G26TF3J3S&pf_rd_s=right-4&pf_rd_t=15506&pf_rd_i=toptv&ref_=chttvtp_ql_7" scrape(url)
Python
UTF-8
14,659
2.75
3
[]
no_license
from matplotlib.backends.backend_agg import RendererAgg import streamlit as st import numpy as np import pandas as pd import seaborn as sns import matplotlib from matplotlib.figure import Figure import altair as alt import matplotlib.pyplot as plt import plotly.figure_factory as ff import plotly.express as px from models.process_data import tokyoData, veniceData, newYorkData st.set_page_config( page_title="Nimbus Solution ", page_icon=":globe_with_meridians:", layout="wide") matplotlib.use("agg") _lock = RendererAgg.lock sns.set_style('darkgrid') row0_spacer1, row0_1, row0_spacer2, row0_2, row0_spacer3 = st.beta_columns( (.1, 2, .2, 1, .1)) st.cache(persist=True) def load_data(): covid19 = pd.read_csv('data/covid.csv', encoding='ISO-8859-1',thousands='.', decimal=',', engine='python') covid19['date'] = pd.to_datetime(covid19['date'],format = '%Y-%m-%d') return covid19 data_load_state = st.text('Loading data, please wait...') covid19 = load_data() data_load_state.text('') def main(): row0_1.title('Looking At The Bigger Picture') with row0_2: st.write('') row0_2.subheader( 'Solution by the [Nimbus Team](https://github.com/bykevinyang/Nimbus)') row1_spacer1, row1_1, row1_spacer2 = st.beta_columns((.1, 3.2, .1)) with row1_1: st.markdown("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.") st.markdown("""---""") st.write('') row3_space1, row3_1, row3_space2, row3_2, row3_space3 = st.beta_columns( (.1, 1, .1, 1, .1)) # TOKYO COMPONENT with row3_1, _lock: st.header("Tokyo Data 🇯🇵 ") # Load Tokyo data. @st.cache(allow_output_mutation=True) def load_data(): return tokyoData() data_load_state = st.text('Loading Tokyo data...') chl_df_tokyo = load_data()[0] tsm_df_tokyo = load_data()[1] data_load_state.text('') st.dataframe(load_data()[2]) # year_to_filter = st.slider('Filter years', 2019, 2021, 2021, key='tokyo') # min: 0h, max: 23h, default: 17h st.markdown("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.") with row3_2, _lock: st.header("Plot of Tokyo's Data") chl_df_tokyo.sort_values(by='Time', ascending=True, inplace=True) chl_df_tokyo['time'] = pd.to_datetime(chl_df_tokyo.Time) # chl_df_tokyo = chl_df_tokyo[chl_df_tokyo['time'].dt.year == year_to_filter] fig = Figure() ax = fig.subplots() plt.figure(figsize=(15, 15)) ax.plot(chl_df_tokyo['Time'], chl_df_tokyo['Measurement Value'], color='darkorange', label='Chl Concentration') ax.legend() ax.tick_params(labelsize=7) ax.set_xlabel('Time (YY/MM)', fontsize=10) ax.set_ylabel('Measurement value (molarity)', fontsize=10) st.pyplot(fig) # fig=px.bar(chl_df_tokyo,x='Time',y='Measurement Value') # fig.update_layout(title_x=0.5, xaxis_rangeslider_visible=True, legend=dict(x=-.5, y=-2)) # fig.update_yaxes(title_text='Chlorophyll-A Concentration (Molarity)') # fig.update_xaxes(title_text='Date') # st.plotly_chart(fig) st.write('') row4_space1, row4_1, row4_space2, row4_2, row4_space3 = st.beta_columns( (.1, 1, .1, 1, .1)) with row4_2, _lock: st.header("Interesting dates for Japan") st.markdown('''The concentration of Chlorophyll-a is tested in lakes to determine how much algae is in the lake. Our solution shows the relationship between human activities and algae bloom, through out the COVID-19 pandemic human activities became decreasing and in result the concentration of Chl-a began decreasing to understand the dates below you must understand this first: \n Any decrease of the concentration of CHL was caused because of the high reported COVID-19 cases which meant less human activity in the past two months of the CHL decrease date. \n On the other hand, any increase of the concentration of CHL was caused because of the decrease of the reported COVID-19 cases which meant more human activity in the past two months of the CHL increase date. ''') expander_1 = st.beta_expander("The largest drop of concentration reported at 2020-08-22 in Japan.") expander_1.write('The largest drop of concentration was reported in 2020-08-22 with a decrease value of -87.3 in Tokyo, and if we look at the month before the date 2020-08-22 we can see the increase of COVID cases in Japan during the month of June and July of 2020:') button_1 = expander_1.button('Visualize', key='3') button_1_end = expander_1.button('Stop Visualizing', key='3') expander_2 = st.beta_expander("The largest increase of concentration reported at 2019-11-09 in Japan.") expander_2.write('''The largest increase in the CHL concentration was reported in 2019-11-09 with an increase value of +265.03 in Tokyo, and if we take a look at the months before June we can realize that the increase happened before the Pandemic. ''') with row4_1, _lock: country = 'Japan' st.header("Japan Covid Cases") if button_1: japan_covid_fig=px.bar(covid19[covid19["location"]==country],x='date',y='new_cases', color='tokyo_increase_color') japan_covid_fig.update_layout(title_x=0.5, xaxis_rangeslider_visible=True) japan_covid_fig.update_yaxes(title_text='New Cases') japan_covid_fig.update_xaxes(title_text='Date') st.plotly_chart(japan_covid_fig) elif button_1_end: japan_covid_fig=px.bar(covid19[covid19["location"]==country],x='date',y='new_cases') japan_covid_fig.update_layout(title_x=0.5, xaxis_rangeslider_visible=True) japan_covid_fig.update_yaxes(title_text='New Cases') japan_covid_fig.update_xaxes(title_text='Date') st.plotly_chart(japan_covid_fig) else: japan_covid_fig=px.bar(covid19[covid19["location"]==country],x='date',y='new_cases') japan_covid_fig.update_layout(title_x=0.5, xaxis_rangeslider_visible=True) japan_covid_fig.update_yaxes(title_text='New Cases') japan_covid_fig.update_xaxes(title_text='Date') st.plotly_chart(japan_covid_fig) #ITALY st.write('') st.markdown("""---""") row5_space1, row5_1, row5_space2, row5_2, row5_space3 = st.beta_columns( (.1, 1, .1, 1, .1)) with row5_1, _lock: st.header("Venice Data 🇮🇹") @st.cache(allow_output_mutation=True) def load_data(): return veniceData() data_load_state = st.text('Loading Venice data...') chl_df_venice = load_data()[0] tsm_df_venice = load_data()[1] data_load_state.text('') st.dataframe(load_data()[2]) # year_to_filter = st.slider('Filter years', 2019, 2021, 2021, key='venice') # min: 0h, max: 23h, default: 17h st.markdown("Note that the publication date on Goodreads is the **last** publication date, so Chl Concentration is altered for any book that has been republished by a publisher.") with row5_2, _lock: st.header("Plot of Venice's Data ") chl_df_venice.sort_values(by='Time', ascending=True, inplace=True) chl_df_venice['time'] = pd.to_datetime(chl_df_venice.Time) # chl_df_venice = chl_df_venice[chl_df_tokyo['time'].dt.year == year_to_filter] fig = Figure() ax = fig.subplots() ax.plot(chl_df_venice['Time'], chl_df_venice['Measurement Value'], color='darkorange', label='Chl Concentration') ax.legend() ax.tick_params(labelsize=7) ax.set_xlabel('Time (YY/MM)', fontsize=10) ax.set_ylabel('Measurement value (molarity)', fontsize=10) st.pyplot(fig) # fig=px.bar(chl_df_venice,x='Time',y='Measurement Value') # fig.update_layout(title_x=0.5, xaxis_rangeslider_visible=True, legend=dict(x=-.5, y=-2)) # fig.update_yaxes(title_text='Chlorophyll-A Concentration (Molarity)') # fig.update_xaxes(title_text='Date') # st.plotly_chart(fig) st.write('') row6_space1, row6_1, row6_space2, row6_2, row6_space3 = st.beta_columns( (.1, 1, .1, 1, .1)) with row6_2, _lock: st.header("Interesting dates for Italy") st.markdown('''The concentration of Chlorophyll-a is tested in lakes to determine how much algae is in the lake. Our solution shows the relationship between human activities and algae bloom, through out the COVID-19 pandemic human activities became decreasing and in result the concentration of Chl-a began decreasing to understand the dates below you must understand this first: \n Any decrease of the concentration of CHL was caused because of the high reported COVID-19 cases which meant less human activity in the past two months of the CHL decrease date. \n On the other hand, any increase of the concentration of CHL was caused because of the decrease of the reported COVID-19 cases which meant more human activity in the past two months of the CHL increase date. ''') expander_1 = st.beta_expander("The largest drop of concentration reported at 2020-08-22.") expander_1.write('The largest drop of Chl-a concentration was reported in 2021-03-06 with a decrease value of -79.630008 in Venice, and if we look at the months before the date 2021-03-06 we can see the increase of COVID cases in Italy during the months of January and February of 2021:') button_2 = expander_1.button('Visualize', key='12') button_2_end = expander_1.button('Stop Visualizing', key='11') expander_2 = st.beta_expander("The largest increase of concentration reported at 2019-11-09.") expander_2.write('''The largest increase in the CHL concentration was reported in 2019-06-13 with an increase value of +400.38177 in Venice, and if we take a look at the months before June we can realize that the increase happened before the Pandemic. ''') with row6_1, _lock: if button_2: country = 'Italy' st.header("Italy Covid Cases") italy_covid_fig=px.bar(covid19[covid19["location"]==country],x='date',y='new_cases', color='italy_increase_color') italy_covid_fig.update_layout(title_x=0.5, xaxis_rangeslider_visible=True) italy_covid_fig.update_yaxes(title_text='New Cases') italy_covid_fig.update_xaxes(title_text='Date') st.plotly_chart(italy_covid_fig) elif button_2_end: country = 'Italy' st.header("Italy Covid Cases") italy_covid_fig=px.bar(covid19[covid19["location"]==country],x='date',y='new_cases') italy_covid_fig.update_layout(title_x=0.5, xaxis_rangeslider_visible=True) italy_covid_fig.update_yaxes(title_text='New Cases') italy_covid_fig.update_xaxes(title_text='Date') st.plotly_chart(italy_covid_fig) else: country = 'Italy' st.header("Italy Covid Cases") italy_covid_fig=px.bar(covid19[covid19["location"]==country],x='date',y='new_cases') italy_covid_fig.update_layout(title_x=0.5, xaxis_rangeslider_visible=True) italy_covid_fig.update_yaxes(title_text='New Cases') italy_covid_fig.update_xaxes(title_text='Date') st.plotly_chart(italy_covid_fig) #UNITED STATES st.write('') st.markdown("""---""") row7_space1, row7_1, row7_space2, row7_2, row7_space3 = st.beta_columns( (.1, 1, .1, 1, .1)) with row7_1, _lock: st.header("New York Data 🇺🇸 ") @st.cache(allow_output_mutation=True) def load_data(): return newYorkData() data_load_state = st.text('Loading New York data...') chl_df_newyork = load_data()[0] tsm_df_newyork = load_data()[1] data_load_state.text('') st.dataframe(load_data()[2]) # year_to_filter = st.slider('Filter years', 2019, 2021, 2021, key='new-york') # min: 0h, max: 23h, default: 17h st.markdown("Note that the publication date on Goodreads is the **last** publication date, so Chl Concentration is altered for any book that has been republished by a publisher.") with row7_2, _lock: st.header("Plot of New-York's Data") chl_df_newyork.sort_values(by='Time', ascending=True, inplace=True) chl_df_newyork['time'] = pd.to_datetime(chl_df_newyork.Time) # chl_df_newyork = chl_df_newyork[chl_df_tokyo['time'].dt.year == year_to_filter] fig = Figure() ax = fig.subplots() # plt.figure(figsize=(15, 15)) ax.plot(chl_df_newyork['Time'], chl_df_newyork['Measurement Value'], color='darkorange', label='Chl Concentration') ax.legend() ax.tick_params(labelsize=7) ax.set_xlabel('Time (YY/MM)', fontsize=10) ax.set_ylabel('Measurement value (molarity)', fontsize=10) st.pyplot(fig) # fig=px.bar(chl_df_newyork,x='Time',y='Measurement Value') # fig.update_layout(title_x=0.5, xaxis_rangeslider_visible=True, legend=dict(x=-.5, y=-2)) # fig.update_yaxes(title_text='Chlorophyll-A Concentration (Molarity)') # fig.update_xaxes(title_text='Date') # st.plotly_chart(fig) st.write('') row8_space1, row8_1, row8_space2, row8_2, row8_space3 = st.beta_columns( (.1, 1, .1, 1, .1)) with row8_1, _lock: country = 'United States' st.header("United States Covid Cases") fig=px.bar(covid19[covid19["location"]==country],x='date',y='new_cases') fig.update_layout(title_x=0.5, xaxis_rangeslider_visible=True, legend=dict(x=-.5, y=-2)) fig.update_yaxes(title_text='New Cases') fig.update_xaxes(title_text='Date') st.plotly_chart(fig) with row8_2, _lock: st.header("Interesting dates for New York") st.markdown('Coming soon...') if __name__ == '__main__': main()
Java
UTF-8
220
2.90625
3
[]
no_license
package printer; public class PrinterImpl implements Printer { private String lastPrint = ""; public void print(String line) { lastPrint = line; } @Override public String toString() { return lastPrint; } }
Python
UTF-8
1,287
4.0625
4
[]
no_license
#1 '''def bubble_sort(lst=[7, 30, -8, 414, 9]): for i in range(len(lst)): for j in range(len(lst) - i - 1): if lst[j] > lst[j + 1]: lst[j], lst[j + 1] = [lst[j + 1], lst[j]] return lst print(bubble_sort([7, 30, -8, 414, 9]))''' #2 '''def mix_lists(lst1=[], lst2=[]): if len(lst1) == len(lst2): for i in range(0, len(lst1), 1): print(lst1[i] + lst2[i], end=' ') else: print("The number of members on your list isn't equal")''' #3 '''def each_item_to_its_square(lst=[]): new_lst = [] for each in lst: each = each ** 2 new_lst.append(each) return new_lst print(each_item_to_its_square([65, 41, 8, 9, 0]))''' #4 '''def sum_of_lists_members(lst=[1,2]): sum = 0 for each in lst: sum += each return sum''' #5 '''def remove_duplicates(lst=[]): new_lst = [] for i in lst: if i not in new_lst: new_lst.append(i) return new_lst print(remove_duplicates([ 111, 112 ]))''' #6 '''def unique_values(lst=[]): new_lst = [] for i in lst: if lst.count(i) == 1: new_lst.append(i) return new_lst print(unique_values([4, 11, 9, 33]))'''
Python
UTF-8
346
2.65625
3
[]
no_license
import numpy as np import cv2 class BackgroundSubstractClass: def __init__(self, height, width, alpha): self.height = height self.width = width self.alpha = alpha self.model = np.zeros((self.height, self.width, 3)) def updateModel(self, frame): self.model = (1 - self.alpha)*self.model + self.alpha*frame return self.model
Java
UTF-8
331
1.851563
2
[]
no_license
package com.restwebservices.prac.exception; import java.time.LocalDateTime; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class ExceptionReponse { private LocalDateTime timstamp; private String message; private String details; }