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
Ruby
UTF-8
1,059
3.65625
4
[]
no_license
=begin Makers. 04/11/20. Here I had to amend the Diary class in order to make it testable in isolation - using a double - from its dependency class Entry. Here is how I did it. 1) I deleted Entry.new(title, body) from the add method. 2) I placed a parameter in the initialize method, entry_class, which is by default the Entry class. But we can optionally make it a double. This is what ultimately allows us to then use a double to test Diary in an isolated manner. 3) Inside initialize, I set the @entry_class instance variable equal to the entry_class parameter. 4) In add, we create a new instance of the Entry class, or this can be stubbed in our test. =end class Diary def initialize(entry_class = Entry) @entries = [] @entry_class = entry_class end def add(title, body) @entries << @entry_class.new(title, body) end def index titles = @entries.map { |entry| entry.title } titles.join("\n") end end class Entry def initialize(title, body) @title = title @body = body end attr_reader :title, :body end
Java
UTF-8
4,289
2.4375
2
[ "Apache-2.0" ]
permissive
package com.cybernostics.lib.gui.windowcore; import com.cybernostics.lib.gui.ButtonFactory; import com.cybernostics.lib.gui.IconFactory; import com.cybernostics.lib.gui.IconFactory.StdButtonType; import com.cybernostics.lib.gui.declarative.events.WhenMadeVisible; import com.cybernostics.lib.gui.shapeeffects.ShapedPanel; import com.cybernostics.lib.media.SoundEffect; import java.awt.AWTEvent; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URL; import javax.swing.*; /** * * @author jasonw */ public class DialogPanel extends ShapedPanel implements SupportsTransition { private ActionListener getResponse = new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { response = (DialogResponses) ( (JComponent) e.getSource() ).getClientProperty( "response" ); firePropertyChange( "closeRequested", false, true ); } }; private JButton makeButton( String text, StdButtonType stdButtonType, DialogResponses answerType ) { JButton btn = ButtonFactory.getStdButton( stdButtonType, null ); btn.setName( text ); btn.putClientProperty( "response", answerType ); btn.addActionListener( getResponse ); return btn; } public enum DialogTypes { YES_NO, YES_NO_CANCEL, OK, OK_CANCEL } private DialogResponses response = null; public DialogResponses getResponse() { return response; } private SoundEffect audioQuery = null; public DialogPanel( String prompt, String Title, final URL audioQuestion, DialogTypes dialog_type ) { this( new JLabel( prompt ), Title, audioQuestion, dialog_type ); } public DialogPanel( JComponent prompt, String Title, final URL audioQuestion, DialogTypes diaog_type ) { setLayout( new BorderLayout() ); if (audioQuestion != null) { audioQuery = new SoundEffect( audioQuestion ); new WhenMadeVisible( this ) { @Override public void doThis( AWTEvent e ) { audioQuery.play(); } }; } prompt.setAlignmentX( 0.5f ); add( prompt, BorderLayout.CENTER ); JPanel buttons = new JPanel(); buttons.setOpaque( false ); BoxLayout bl = new BoxLayout( buttons, BoxLayout.X_AXIS ); buttons.setLayout( bl ); buttons.add( Box.createHorizontalGlue() ); switch (diaog_type) { case OK: buttons.add( makeButton( "OK", IconFactory.StdButtonType.YES, DialogResponses.OK_ANSWER ) ); break; case OK_CANCEL: buttons.add( makeButton( "OK", IconFactory.StdButtonType.YES, DialogResponses.OK_ANSWER ) ); buttons.add( Box.createHorizontalStrut( 10 ) ); buttons.add( makeButton( "Cancel", IconFactory.StdButtonType.CANCEL, DialogResponses.CANCEL_ANSWER ) ); break; case YES_NO: buttons.add( makeButton( "Yes", IconFactory.StdButtonType.YES, DialogResponses.YES_ANSWER ) ); buttons.add( Box.createHorizontalStrut( 10 ) ); buttons.add( makeButton( "No", IconFactory.StdButtonType.NO, DialogResponses.NO_ANSWER ) ); break; case YES_NO_CANCEL: buttons.add( makeButton( "Yes", IconFactory.StdButtonType.YES, DialogResponses.YES_ANSWER ) ); buttons.add( Box.createHorizontalStrut( 10 ) ); buttons.add( makeButton( "No", IconFactory.StdButtonType.NO, DialogResponses.NO_ANSWER ) ); buttons.add( Box.createHorizontalStrut( 10 ) ); buttons.add( makeButton( "Cancel", IconFactory.StdButtonType.CANCEL, DialogResponses.CANCEL_ANSWER ) ); break; } buttons.add( Box.createHorizontalGlue() ); buttons.setBorder( BorderFactory.createEmptyBorder( 10, 10, 10, 10 ) ); add( buttons, BorderLayout.SOUTH ); } @Override public void doWhenPushed( TransitionCompleteListener listener ) { setVisible( true ); if (listener != null) { listener.transitionComplete(); } } @Override public void doWhenPopped( TransitionCompleteListener listener ) { setVisible( false ); if (listener != null) { listener.transitionComplete(); } } @Override public void doWhenObscured( TransitionCompleteListener listener ) { } @Override public void doWhenRevealed( TransitionCompleteListener listener ) { } }
Python
UTF-8
2,230
3.75
4
[]
no_license
__author__ = 'Kalyan' import string notes = ''' Write your own implementation of converting a number to a given base. It is important to have a good logical and code understanding of this. Till now, we were glossing over error checking, for this function do proper error checking and raise exceptions as appropriate. Reading material: http://courses.cs.vt.edu/~cs1104/number_conversion/convexp.html ''' r=list(string.ascii_uppercase) r=dict(zip(range(10,36),r)) def convert(number, base): sign=0 """ Convert the given number into a string in the given base. valid base is 2 <= base <= 36 raise exceptions similar to how int("XX", YY) does (play in the console to find what errors it raises). Handle negative numbers just like bin and oct do. """ if number<0: sign=1 number=number*-1 l = [] y = 1 if base < 2 or base > 36: raise ValueError x = number while (x): y = x % base x = int(int(x) / int(base)) if y>9: l.append(r[y]) else: l.append(y) l = list(reversed(l)) if sign==1: s="-" else: s = "" for a in l: s = s + str(a) return s def test_convert(): assert "100" == convert(4,2) assert "FF" == convert(255,16) assert "377" == convert(255, 8) assert "JJ" == convert(399, 20) assert "-JJ" == convert(-399, 20) try: convert(10,1) assert False, "Invalid base <2 did not raise error" except ValueError as ve: print(ve) try: convert(10, 40) assert False, "Invalid base >36 did not raise error" except ValueError as ve: print(ve) try: convert("100", 10) assert False, "Invalid number did not raise error" except TypeError as te: print(te) try: convert(None, 10) assert False, "Invalid number did not raise error" except TypeError as te: print(te) try: convert(100, "10") assert False, "Invalid base did not raise error" except TypeError as te: print(te)
Python
UTF-8
331
3.15625
3
[]
no_license
import numpy as np import matplotlib.pyplot as plt def f(x): return x**4 - 8*x**3 - 35*x**2 + 450*x - 1001 x = np.linspace(0.0, 10.0, 1000) plt.clf() plt.plot(x, f(x)) plt.grid(True) plt.savefig("IMG_exe_5_10.pdf") x = np.linspace(4.0, 6.0, 1000) plt.clf() plt.plot(x, f(x)) plt.grid(True) plt.savefig("IMG_exe_5_10_v2.pdf")
Swift
UTF-8
1,934
2.859375
3
[]
no_license
// // LineGraphViewController.swift // ChartsDemo-Swift // // Created by Rupam Mitra on 01/08/16. // Copyright © 2016 Rupam Mitra. All rights reserved. // import UIKit class LineGraphViewController: BaseGraphViewController { override func viewDidLoad() { chartIdentifier = String(LineChartView) super.viewDidLoad() // Do any additional setup after loading the view. formChartData() chartView.setVisibleXRangeMaximum(5.0) chartView.animate(xAxisDuration: 0.5, easingOption: .Linear) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func formChartData() { var xVals = [String]() for obj in dataArray { xVals.append(obj["x"] as! String) } var yVals: [ChartDataEntry]! var dataSets = [LineChartDataSet]() var keys = Array(dataArray[0].keys) keys.sortInPlace() for (_, key) in keys.enumerate() { if key != "x" { yVals = [ChartDataEntry]() let color = UIColor.randomColor() var dataSet: LineChartDataSet! for (dataIndex, data) in dataArray.enumerate() { let markerString = " \(key.uppercaseString): \(data[key]!)" yVals.append(ChartDataEntry(value: data[key]!.doubleValue, xIndex: dataIndex, data: markerString)) } dataSet = CDSLineChartDataSet(yVals: yVals, label: key.uppercaseString, color: color, circleColor: color, circleRadius: 3.0, filledEnabled: filledEnabled, fillAlpha: 0.2, fillColor: color) dataSets.append(dataSet) } } chartView.data = CDSLineChartData(xVals: xVals, dataSets: dataSets, drawValues: false) } }
C
UTF-8
3,186
2.71875
3
[]
no_license
#include "monopoly.h" #include "game.h" #include <pthread.h> #include <stdio.h> #include <string.h> #include <time.h> #include <stdlib.h> float results[40] = {0}; void *play_monopoly(void *results_lock) { srand((unsigned) ((pthread_self() << 16) + time(NULL))); float tile_landings[40] = {0}; int game; for (game = 0; game < GAMES_PER_THREAD; game++) { struct player_t players[NUM_PLAYERS]; int i; for (i = 0; i < NUM_PLAYERS; i++) players[i] = new_player(); struct tile_t properties[40]; memcpy(properties, default_properties, sizeof(default_properties)); struct card_t chance[16]; memcpy(chance, default_chance, sizeof(default_chance)); struct card_t chest[16]; memcpy(chest, default_chest, sizeof(default_chest)); int round; for (round = 0; round < MAX_ROUNDS_PER_GAME; round++) { int player; for (player = 0; player < NUM_PLAYERS; player++) { struct dice_t roll; int doubles = 0; do { roll = roll_dice(); doubles += roll.doubles; if (doubles >= 3) { players[player].position = 10; tile_landings[10]++; break; } players[player].position = (players[player].position + roll.total) % 40; tile_landings[players[player].position]++; if (players[player].position == 30) { players[player].position = 10; tile_landings[10]++; break; } if (strcmp(properties[players[player].position].tile_name, "Chance") == 0) { int prev_position = players[player].position; struct card_t chance_card = draw_card(chance); chance_action(&players[player], chance_card); if (prev_position != players[player].position) { tile_landings[players[player].position]++; } } else if (strcmp(properties[players[player].position].tile_name, "Community Chest") == 0) { int prev_position = players[player].position; struct card_t chest_card = draw_card(chest); chest_action(&players[player], chest_card); if (prev_position != players[player].position) { tile_landings[players[player].position]++; } } } while (roll.doubles); } } } pthread_mutex_lock((pthread_mutex_t)results_lock); int i; for (i = 0; i < 40; i++){ tile_landings[i] /= GAMES_PER_THREAD; results[i] += tile_landings[i]; } threads_open--; pthread_mutex_unlock((pthread_mutex_t)results_lock); pthread_exit(NULL); return NULL; }
Java
UTF-8
10,700
1.9375
2
[]
no_license
package swipe.android.nearlings; import java.text.DateFormatSymbols; import java.text.NumberFormat; import java.util.Calendar; import java.util.HashMap; import java.util.List; import swipe.android.nearlings.googleplaces.GoogleParser; import swipe.android.nearlings.googleplaces.GoogleParser.PlacesTask; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.EditText; import android.widget.SimpleAdapter; import android.widget.TextView; import com.edbert.library.network.AsyncTaskCompleteListener; import com.fourmob.datetimepicker.date.DatePickerDialog; import com.fourmob.datetimepicker.date.DatePickerDialog.OnDateSetListener; import com.sleepbot.datetimepicker.time.RadialPickerLayout; import com.sleepbot.datetimepicker.time.TimePickerDialog; import de.metagear.android.view.ValidatingView; // reviewed public abstract class BaseFormAdapter extends ValidatingViewAdapter implements AsyncTaskCompleteListener, OnDateSetListener, TimePickerDialog.OnTimeSetListener { protected List<ValidatingView> validatingViews; private static final int MIN_LENGTH_OF_TEXT_VALUES = 0; boolean startTimeLastCalled = true; protected FragmentActivity ctx; public static final String DATEPICKER_START_TAG = "datepicker_start"; public static final String DATEPICKER_END_TAG = "datepicker_end"; public static final String TIMEPICKER_START_TAG = "timepicker_start"; public static final String TIMEPICKER_END_TAG = "timepicker_end"; // ListView listOfPlaces; String[] from = new String[] { "description" }; int[] to = new int[] { android.R.id.text1 }; Calendar calendar; TimePickerDialog timePickerDialog; PlacesTask placesTask; AutoCompleteTextView edt_input_place; Button start_date, start_time; SimpleAdapter adapterWithItems; SimpleAdapter adapterWithoutItems; final DatePickerDialog datePickerDialog; public BaseFormAdapter(FragmentActivity ctx, View rootView, Bundle savedInstanceState) { super(rootView); edt_input_place = (AutoCompleteTextView) rootView.findViewById(R.id.location); start_date = (Button) rootView.findViewById(R.id.start_date); start_time = (Button) rootView.findViewById(R.id.start_time); this.ctx = ctx; calendar = Calendar.getInstance(); datePickerDialog = DatePickerDialog.newInstance( this, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), false); timePickerDialog = TimePickerDialog.newInstance( this, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), false, false); if (savedInstanceState != null) { DatePickerDialog dpd = (DatePickerDialog) ctx.getSupportFragmentManager() .findFragmentByTag(DATEPICKER_START_TAG); if (dpd != null) { dpd.setOnDateSetListener(this); } TimePickerDialog tpd = (TimePickerDialog) ctx.getSupportFragmentManager() .findFragmentByTag(TIMEPICKER_START_TAG); if (tpd != null) { tpd.setOnTimeSetListener(this); } DatePickerDialog dpd2 = (DatePickerDialog) ctx.getSupportFragmentManager() .findFragmentByTag(DATEPICKER_END_TAG); if (dpd2 != null) { dpd2.setOnDateSetListener(this); } TimePickerDialog tpd2 = (TimePickerDialog) ctx.getSupportFragmentManager() .findFragmentByTag(TIMEPICKER_END_TAG); if (tpd2 != null) { tpd2.setOnTimeSetListener(this); } } this.setUpPlaces(edt_input_place); this.setUpTime(start_time); this.setUpDate(start_date); setUpTimeInitialize(start_date, start_time); } private void setUpTimeInitialize( TextView start_date, TextView start_time){ if(start_date == null || start_time == null){ return; } Calendar now = Calendar.getInstance(); int year = now.get(Calendar.YEAR); int month = now.get(Calendar.MONTH); // Note: zero based! int day = now.get(Calendar.DAY_OF_MONTH); int hour = now.get(Calendar.HOUR_OF_DAY); int minute = now.get(Calendar.MINUTE); String monthName = new DateFormatSymbols().getMonths()[month]; start_date.setText(monthName + " " + day + ", " + year); if (now.get(Calendar.AM_PM) == Calendar.PM) { start_time.setText(hour + ":" + String.format("%02d", minute)); } else { start_time.setText(hour + ":" + String.format("%02d", minute)); } } protected void setUpDate(Button start_date){ if(start_date == null){ return; } start_date.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { datePickerDialog.setVibrate(false); datePickerDialog.setYearRange(1985, 2028); datePickerDialog.show(ctx.getSupportFragmentManager(), DATEPICKER_START_TAG); } }); } protected void setUpTime(Button start_time){ if(start_time == null){ return; } start_time.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { timePickerDialog.setVibrate(false); startTimeLastCalled = true; timePickerDialog.show(ctx.getSupportFragmentManager(), TIMEPICKER_START_TAG); } }); } protected void setUpPlaces(final AutoCompleteTextView edt_input_place){ if(edt_input_place == null){ return; } edt_input_place.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before, int count) { GoogleParser outer = GoogleParser.getInstance(s.toString(), BaseFormAdapter.this); placesTask = outer.new PlacesTask(s.toString()); placesTask.execute(s.toString()); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void afterTextChanged(Editable s) { } }); edt_input_place.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { HashMap<String, String> description = (HashMap<String, String>) adapterWithItems .getItem(position); String s = description.get("description"); edt_input_place.setText(s); } }); } protected void setUpCategory(final Button category, int array_of_string) { final String[] items = ctx.getResources().getStringArray( array_of_string); category.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder( ctx); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { category.setText(items[item]); dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } }); category.setText(items[0]); } protected void setUpAgeRequirements(final Button age_inequality, final EditText age_value) { final String[] items = ctx.getResources().getStringArray( R.array.event_requirements_age_inequalities); age_inequality.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder( ctx); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { age_inequality.setText(items[item]); dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } }); age_inequality.setText(items[0]); age_value.setText("0"); } @Override public void onTaskComplete(Object result) { if (result instanceof List<?>) { List<HashMap<String, String>> resultOfGooglePlace = (List<HashMap<String, String>>) result; // Creating a SimpleAdapter for the AutoCompleteTextView adapterWithItems = new SimpleAdapter(ctx, resultOfGooglePlace, android.R.layout.simple_list_item_1, from, to); // Setting the adapter adapterWithItems.notifyDataSetChanged(); edt_input_place.setAdapter(adapterWithItems); adapterWithItems.notifyDataSetChanged(); // adapterWithItems.notifyDataSetChanged(); // edt_input_place.invalidate(); } } @Override public void onDateSet(DatePickerDialog datePickerDialog, int year, int month, int day) { String monthName = new DateFormatSymbols().getMonths()[month]; String total = monthName + " " + day + ", " + year; if (datePickerDialog.getTag().equals(DATEPICKER_START_TAG)) { start_date.setText(total); } else if (datePickerDialog.getTag().equals(DATEPICKER_END_TAG)) { // end_date.setText(total); } } @Override public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute) { String total = hourOfDay + ":" + String.format("%02d", minute); if (startTimeLastCalled) { start_time.setText(total); } else { // end_time.setText(total); } } protected OnClickListener dateOnClickListener = new OnClickListener(){ @Override public void onClick(View v) { datePickerDialog.setVibrate(false); datePickerDialog.setYearRange(1985, 2028); datePickerDialog.show(ctx.getSupportFragmentManager(), DATEPICKER_START_TAG); } }; protected OnClickListener timeOnClickListener = new OnClickListener(){ @Override public void onClick(View v) { timePickerDialog.setVibrate(false); startTimeLastCalled = true; timePickerDialog.show(ctx.getSupportFragmentManager(), TIMEPICKER_START_TAG); } }; protected void setUpPriceListener(final EditText price) { price.addTextChangedListener(new TextWatcher() { private String current = ""; @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (!s.toString().equals(current)) { price.removeTextChangedListener(this); String cleanString = s.toString().replaceAll("[$,.]", ""); cleanString = cleanString.replaceAll("[^0-9.]", ""); if(cleanString.equals("")){ cleanString = "0.00"; } double parsed = Double.parseDouble(cleanString); String formatted = NumberFormat.getCurrencyInstance() .format((parsed / 100)); current = formatted; price.setText(formatted); price.setSelection(formatted.length()); price.addTextChangedListener(this); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } }); price.setText("$0.00"); } }
C#
UTF-8
3,352
2.625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using log4net; using log4net.Config; using System.Configuration; using System.Collections.Specialized; namespace dk.gov.oiosi.logging { /// <summary> /// Log4Net creator /// </summary> public class Log4NetCreator : ILoggerCreator { /// <summary> /// The log 4 net creator /// </summary> public Log4NetCreator() { } /// <summary> /// Create a common logger, that can be used to log though log4net /// </summary> /// <returns>A class that can be used to log though log4net</returns> public ILogger Create() { return this.Create("dk.gov.oiosi.logging.Log4Net"); } /// <summary> /// Create a named logger, that can be used to log though log4net /// </summary> /// <param name="loggerName">The name of the logger</param> /// <returns>A class that can be used to log though log4net</returns> public ILogger Create(string loggerName) { return new Log4Net(LogManager.GetLogger(loggerName)); } /// <summary> /// Create a typed logger, that can be used to log though log4net /// </summary> /// <param name="type">The typed of the logger</param> /// <returns>A class that can be used to log though log4net</returns> public ILogger Create(Type type) { return new Log4Net(LogManager.GetLogger(type)); } /// <summary> /// Configurate the log4net logger creator /// </summary> public void Configurate() { // first we try to retrive the configuration file name from app.config string key = "log4Net4RaspConfigurationFile"; string log4NetConfigurationFile = ConfigurationManager.AppSettings[key]; if(string.IsNullOrEmpty(log4NetConfigurationFile)) { // the key did not exist in the default app.config // try the dk.gov.oiosi.logging.dll.config Configuration configuration = ConfigurationManager.OpenExeConfiguration(LoggingConstant.AppConfigName); AppSettingsSection section = configuration.AppSettings; KeyValueConfigurationCollection collection = section.Settings; KeyValueConfigurationElement element = collection[key]; if(element != null) { log4NetConfigurationFile = element.Value; } } if (string.IsNullOrEmpty(log4NetConfigurationFile)) { // configuration file still not identified. Trying default filename log4NetConfigurationFile = "log4net.xml"; } FileInfo fileInfo = new FileInfo(log4NetConfigurationFile); if (fileInfo.Exists) { XmlConfigurator.ConfigureAndWatch(fileInfo); } else { throw new LoggingException(" The configuration file '" + fileInfo.FullName + "' does not exist."); } } } }
Java
UTF-8
1,545
2.078125
2
[]
no_license
//package OTP_RECIEVER; // ///** // * Created by Mr singh on 2/3/2017. // */ // //import android.content.BroadcastReceiver; //import android.content.Context; //import android.content.Intent; //import android.os.Bundle; //import android.telephony.SmsManager; //import android.telephony.SmsMessage; //import android.util.Log; // //import in.co.mealman.mealman.Screen_03; // //public class otp_reciever extends BroadcastReceiver //{ // @Override // public void onReceive(Context context, Intent intent) // { // // final Bundle bundle = intent.getExtras(); // try { // // if (bundle != null) // { // // final Object[] pdusObj = (Object[]) bundle.get("pdus"); // for (int i = 0; i < pdusObj.length; i++) // { // // SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]); // String phoneNumber = currentMessage.getDisplayOriginatingAddress(); // String senderNum = phoneNumber ; // String message = currentMessage .getDisplayMessageBody(); // // try // { // // if (senderNum.equals("VK-MEALMN")) // { // // Screen_03 Sms = new Screen_03(); // Sms.recivedSms(message ); // } // } catch(Exception e){} // } // } // // } catch (Exception e) {} // } // //}
Java
UTF-8
4,287
2.265625
2
[]
no_license
package com.orangeteam.auc.models; import javax.persistence.*; import java.util.Date; import java.util.Set; @Entity @Table(name = "PRODUCT") public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID", nullable = false) private Long id; @Column(name = "NAME", nullable = false) private String name; @Column(name = "STAERTPRICE", nullable = false) private double startPrice; @Column(name = "STEP", nullable = false) private double step; @Column(name = "CURRPRICE", nullable = false) private double currPrice; @Column(name = "DESCRIPTION", nullable = false) private String description; @Column(name = "STATE", nullable = true) private int state; @Column(name = "DATEBEG", nullable = true) @Temporal(TemporalType.DATE) private Date dateBeg; @Column(name = "DATEEND", nullable = true) @Temporal(TemporalType.DATE) private Date dateEnd; @Column(name = "IMAGES", nullable = false) private String images; @ManyToMany(fetch = FetchType.LAZY) @JoinTable(name = "CATEGORY_PRODUCT", joinColumns = @JoinColumn(name = "PRODUCT_ID"), inverseJoinColumns = @JoinColumn(name = "CATEGORY_ID")) private Set<Category> categories; @OneToMany(fetch = FetchType.LAZY) @JoinColumn(name = "PRODUCT_ATTRIBUTE_VALUE_ID") private Set<Product_Attribute_Value> product_attribute_values; @OneToMany(fetch = FetchType.LAZY) @JoinColumn(name = "LISTS_ID") private Set<Lists> lists; public Product(String name, double startPrice, double step, double currPrice, String description, int state, Date dateBeg, Date dateEnd, String images, Set<Category> categories, Set<Product_Attribute_Value> product_attribute_values) { this.name = name; this.startPrice = startPrice; this.step = step; this.currPrice = currPrice; this.description = description; this.state = state; this.dateBeg = dateBeg; this.dateEnd = dateEnd; this.images = images; this.categories = categories; this.product_attribute_values = product_attribute_values; } public Product() { super(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getStartPrice() { return startPrice; } public void setStartPrice(double startPrice) { this.startPrice = startPrice; } public double getStep() { return step; } public void setStep(double step) { this.step = step; } public double getCurrPrice() { return currPrice; } public void setCurrPrice(double currPrice) { this.currPrice = currPrice; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getState() { return state; } public void setState(int state) { this.state = state; } public Date getDateBeg() { return dateBeg; } public void setDateBeg(Date dateBeg) { this.dateBeg = dateBeg; } public Date getDateEnd() { return dateEnd; } public void setDateEnd(Date dateEnd) { this.dateEnd = dateEnd; } public String getImages() { return images; } public void setImages(String images) { this.images = images; } public Set<Category> getCategories() { return categories; } public void setCategories(Set<Category> categories) { this.categories = categories; } public Set<Product_Attribute_Value> getProduct_attribute_values() { return product_attribute_values; } public void setProduct_attribute_values(Set<Product_Attribute_Value> product_attribute_values) { this.product_attribute_values = product_attribute_values; } public Set<Lists> getLists() { return lists; } public void setLists(Set<Lists> lists) { this.lists = lists; } }
Swift
UTF-8
867
2.71875
3
[]
no_license
// // CommonView.swift // Therapist // // Created by Astghik Hakopian on 5/2/20. // Copyright © 2020 Astghik Hakopian. All rights reserved. // import UIKit class CommonView: UIView { // MARK: - @IBInspectable @IBInspectable var cornerRadius: CGFloat = 0 { didSet { updateCornerRadius() } } @IBInspectable var borderWidth: CGFloat = 0 { didSet { updateBorder() } } @IBInspectable var borderColor: UIColor = .clear { didSet { updateBorder() } } // MARK: - Private Methods private func updateCornerRadius() { layer.cornerRadius = cornerRadius self.clipsToBounds = true } private func updateBorder() { layer.borderColor = borderColor.cgColor layer.borderWidth = borderWidth } }
Python
UTF-8
4,791
2.71875
3
[ "MIT" ]
permissive
""" GUI of image-resizer. """ import os import itertools import tkinter as tk import tkinter.filedialog as fd import image_resizer import async_util POS_X = 10 INPUT_FILE_TYPES = [ ('image file', '*.bmp;*.jpeg;*.jpg;*.png;*.ppm;*.gif;*.tiff') ] def on_select_files_button_click(): in_files = infile_text.get(1.0, 'end -1c') def get_ini_dir(in_paths: str): # get initial directory from inputted path head_path = in_paths.split()[0] return os.path.basename(head_path) if os.path.isdir(head_path) else os.path.dirname(head_path) ini_dir = get_ini_dir(in_files) if in_files else os.path.abspath(os.path.dirname(__file__)) file_names = fd.askopenfilenames(filetypes=INPUT_FILE_TYPES, initialdir=ini_dir) if file_names: # display selected files if in_files: infile_text.insert('end', ' ') infile_text.insert('end', file_names) def on_clear_files_button_click(): infile_text.delete(1.0, 'end') def on_select_dir_button_click(): # get initial directory from inputted path ini_dir = out_dir_text.get(1.0, 'end -1c') if not os.path.exists(ini_dir): ini_dir = os.path.abspath(os.path.dirname(__file__)) dir_name = fd.askdirectory(initialdir=ini_dir) if dir_name: # display selected directory out_dir_text.delete(1.0, 'end') out_dir_text.insert(1.0, dir_name) def on_resize_start_button_click(): # get parameters input_files_text = infile_text.get(1.0, 'end -1c') # get input files(ignore directories) input_files = list(filter(os.path.isfile, input_files_text.split())) if input_files_text else None if not input_files: status.set('Could not get input files') return # get optional params optional_params = get_optional_params() # define callback total = len(input_files) counter = itertools.count() def callback(): update_progress(total, next(counter)) # call callback once to initialize progress callback() # resize async_util.submit(lambda: image_resizer.resize_all(input_files, **optional_params, callback=callback)) def get_optional_params(): optional_params = {} out_dir = out_dir_text.get(1.0, 'end -1c') if out_dir: optional_params['out_dir'] = out_dir out_ext = out_ext_text.get(1.0, 'end -1c') if out_ext: optional_params['out_ext'] = out_ext width = width_text.get(1.0, 'end -1c') if width: optional_params['width'] = int(width) height = height_text.get(1.0, 'end -1c') if height: optional_params['height'] = int(height) return optional_params def update_progress(total: int, completed: int): status.set(f'{completed} / {total} completed') root = tk.Tk() root.title('image-resizer') root.geometry('500x440+0+0') infile_label = tk.Label(text='input file names') infile_label.place(x=POS_X, y=10) infile_text = tk.Text(width=50) infile_text.place(x=POS_X, y=30, height=50) infile_button = tk.Button(root, text='select files', width=15, height=30, command=on_select_files_button_click) infile_button.place(x=POS_X + 365, y=30, height=20) infile_clear_button = tk.Button(root, text='clear files', width=15, height=30, command=on_clear_files_button_click) infile_clear_button.place(x=POS_X + 365, y=60, height=20) out_dir_label = tk.Label(text='output directory (default = ./output/)') out_dir_label.place(x=POS_X, y=90) out_dir_text = tk.Text(width=50) out_dir_text.insert(1.0, os.path.join(os.path.abspath(os.path.dirname(__file__)), 'output')) out_dir_text.place(x=POS_X, y=110, height=50) out_dir_button = tk.Button(root, text='select directory', width=15, height=30, command=on_select_dir_button_click) out_dir_button.place(x=POS_X + 365, y=110, height=20) out_ext_label = tk.Label(text='output file extension (default = .png)') out_ext_label.place(x=POS_X, y=170) out_ext_text = tk.Text(width=10) out_ext_text.insert(1.0, '.png') out_ext_text.place(x=POS_X, y=190, height=20) width_label = tk.Label(text='width(px) (default = 1024)') width_label.place(x=POS_X, y=220) width_text = tk.Text(width=10) width_text.insert(1.0, '1024') width_text.place(x=POS_X, y=240, height=20) height_label = tk.Label(text='height(px) (default = 1024)') height_label.place(x=POS_X, y=270) height_text = tk.Text(width=10) height_text.insert(1.0, '1024') height_text.place(x=POS_X, y=300, height=20) resize_start_button = tk.Button(root, text='RESIZE START', width=50, height=3, command=on_resize_start_button_click) resize_start_button.place(x=POS_X, y=340) status = tk.StringVar() status_label = tk.Label(root, textvariable=status) status_label.place(x=POS_X, y=400) root.mainloop()
TypeScript
UTF-8
570
2.640625
3
[]
no_license
import { justTodoListSelector } from '../selectors/index'; // @ts-ignore export const observeTodoList = (store, cb) => { let prevState = justTodoListSelector(store.getState()); // Check against the initial store values if (prevState) { cb(prevState); } // This will trigger an update when the store data changes const handleStateChange = () => { const nextState = justTodoListSelector(store.getState()); if (prevState !== nextState) { prevState = nextState; cb(nextState); } }; return store.subscribe(handleStateChange); };
JavaScript
UTF-8
364
3.21875
3
[]
no_license
var readline = require("readline"); var leitor = readline.createInterface({ input: process.stdin, output: process.stdout }); let a = 0; let b = 0; leitor.question("", primeirovalor => { a = parseInt(primeirovalor); leitor.question("", segundovalor => { b = parseInt(segundovalor); console.log(`SOMA = ${a + b}`); leitor.close(); }); });
Java
UTF-8
398
1.921875
2
[]
no_license
package cn.lanca.plentyoffish.article.service; import cn.lanca.plentyoffish.article.model.Comment; /** * Description: 文章评论䞚务接口层 * <p> * Author: Hongliang.mei * Date: 2019/11/7 15:38 */ public interface ICommentService { /** * 新增/添加评论 * * @param comment 评论对象 * @return Long */ Long insertNewComment(Comment comment); }
C
UTF-8
229
3.46875
3
[]
no_license
#include <stdio.h> int main() { int x, polynomial; printf("enter value of x:"); scanf("%d", &x); polynomial = ((((3 * x + 2) * x - 5) * x - 1) * x + 7) * x - 6; printf("polynomial value:%d\n",polynomial); }
Python
UTF-8
533
3.125
3
[ "MIT" ]
permissive
from tqdm import tqdm import zipfile import sys wordlist = sys.argv[2] zip_file = sys.argv[1] zip_file = zipfile.ZipFile(zip_file) n_words = len(list(open(wordlist, "rb"))) print("Senhas:", n_words) with open(wordlist, "rb") as wordlist: for word in tqdm(wordlist, total=n_words, unit="word"): try: zip_file.extractall(pwd=word.strip()) except: continue else: print("[+] Senha encontrada:", word.decode().strip()) exit(0) print("[!] Não encontrado")
Java
UTF-8
852
3.078125
3
[]
no_license
package feuchtwanger.scrabble; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; public class ScrabbleDictionary { private static ScrabbleDictionary singleton; private final HashSet<String> dictionary; public ScrabbleDictionary() throws IOException { final BufferedReader in = new BufferedReader(new FileReader("./US.dic")); dictionary = new HashSet<String>(); String line; while ((line = in.readLine()) != null) { dictionary.add(line); } in.close(); } public boolean contains(String word) { word.toLowerCase(); return dictionary.contains(word); } //Typically called getInstance. Hides it. public static ScrabbleDictionary getInstance() throws IOException{ if(singleton == null){ singleton = new ScrabbleDictionary(); } return singleton; } }
Python
UTF-8
567
3.125
3
[]
no_license
import numpy from matplotlib import pyplot as plot from sklearn.metrics import r2_score # training & testing numpy.random.seed(2) x = numpy.random.normal(3, 1, 100) y = numpy.random.normal(150, 40, 100) / x # plot.scatter(x, y) # plot.show() train_x, train_y = x[:80], y[:80] test_x, test_y = x[80:], y[80:] mymodel = numpy.poly1d(numpy.polyfit(train_x, train_y, 4)) r2 = r2_score(test_y, mymodel(test_x)) print(r2) # myline = numpy.linspace(0, 6, 100) # plot.scatter(train_x, train_y) # plot.plot(myline, mymodel(myline)) # plot.show() print(mymodel(5.5))
Python
UTF-8
418
2.671875
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/python -u import sys, pickle def main(): if len(sys.argv) != 2: sys.stderr.write('Usage: %s input_file\n' % (sys.argv[0])) exit(1) with open(sys.argv[1], 'rb') as f: single_dict = pickle.load(f) sys.stderr.write('#single = ' + str(len(single_dict)) + '\n') print 'AuthorId,DuplicateAuthorIds' for authorId in single_dict: print authorId + ',' + authorId if __name__ == "__main__": main()
C++
UTF-8
650
3.234375
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: bool estimate(TreeNode* root, long long lower, long long upper) { if (root == nullptr) { return true; } if (root->val <= lower || root->val >= upper) { return false; } return estimate(root->left, lower, root->val) && estimate(root->right, root->val, upper); } bool isValidBST(TreeNode* root) { return estimate(root, LONG_MIN, LONG_MAX); } };
Python
UTF-8
1,356
2.609375
3
[]
no_license
# coding: utf8 # from __future__ import unicode_literals import core as cdc class Node_localvector(cdc.Dagnode): def getcomment(self): return 'this node extract current world translation of an object' def getdisplaytype(self): return 'math' def getinputplugs(self): return [ {'name': 'object', 'value': '', 'type': 'object','tip':'input 3D object'}, ] def getoutputplugs(self): return [ {'name': 'vector', 'value': '[0,0,0]', 'type': 'vector','tip':'output a vector with world translation of 3D object'}, {'name': 'x', 'value': '0', 'type': 'str','tip':'output x world translation of 3D object'}, {'name': 'y', 'value': '0', 'type': 'str','tip':'output y world translation of 3D object'}, {'name': 'z', 'value': '0', 'type': 'str','tip':'output z world translation of 3D object'} ] def evaluate(self): obj = self.getinputplugvalue('object') x=self.getnodelocalvector(obj,'0','0','0')+'[0]' y=self.getnodelocalvector(obj,'0','0','0')+'[1]' z=self.getnodelocalvector(obj,'0','0','0')+'[2]' self.setoutputplugvalue('vector', '['+x+','+y+','+z+']') self.setoutputplugvalue('x', x) self.setoutputplugvalue('y', y) self.setoutputplugvalue('z', z) return
JavaScript
UTF-8
947
2.78125
3
[]
no_license
'use strict'; const xhr = new XMLHttpRequest(); const submit = document.querySelector('#submit-button'); let title = document.querySelector('textarea'); let url = document.querySelector('input'); let form = document.querySelector('form'); const icon = document.querySelector('#icon'); icon.addEventListener('click', ()=>{ window.location.replace('/'); }); form.addEventListener('submit', () => { if(!title.value || !url.value){ alert('Please give a title and url!'); } else { event.preventDefault(); const body = { 'title': title.value, 'url' : url.value, 'timestamp': Math.floor(Date.now() / 1000) } xhr.open('POST', `/posts`); xhr.onload = () => { if (xhr.status === 200) { window.location.replace('/'); } } xhr.setRequestHeader('Accept', 'application/json'); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.send(JSON.stringify(body)); } });
Markdown
UTF-8
7,587
3.515625
4
[]
no_license
## 记莊页面 ### Money.tsx 的UI 完成 1. 根据讟计皿将TagsSection的结构先搞枅楚然后就匀始写HTML然后写css ``` <TagsSection> <ol> <li>è¡£</li> <li>食</li> <li>䜏</li> <li>行</li> </ol> <button>新增标筟</button> </TagsSection> const TagsSection = styled.section` background: #FFFFFF; padding: 12px 16px; > ol { margin: 0 -12px; > li{ background: #D9D9D9; border-radius: 18px; display:inline-block; padding: 3px 18px; font-size: 14px; margin: 8px 12px; } } > button{ background:none; border: none; padding: 2px 4px; border-bottom: 1px solid #333; color: #666; margin-top: 8px; } `; ``` 2. 由于ui䞻芁就是完成讟计皿的样匏就䞍甚䞀䞀叙述就自己看看源码就可以了重点讲讲需芁泚意或掌握的地方就可以。圚制䜜数字面板的时候需芁甚到浮劚䞺了枅楚浮劚我们需芁给浮劚元玠的父元玠加䞊clearfix,具䜓劂䞋 ``` .clearfix::after { content: ''; display: block; clear: both; } ``` 3. 写完组件的ui以后我们䌚发现䞀屏没有占满我们垌望将倚䜙的空闎党郜留给Tags 郚分那就需芁调敎css垃局需芁将layout的content郚分䞺flex垃局然后采甚flex-grow完成。可以这样做,䞍过这样写就䞍可以圚组件里面盎接写css了而是匕入䞀䞪css文件。 ``` function Money() { return { <Layout className='xxx'> 然后圚layout里面 const Layout = (props: any) => { return ( <Wrapper> <Main className={props.className}> {props.children} </Main> <Nav/> </Wrapper> ); }; ``` 方法二 ,styled components支持任䜕类型的组件也就意味着自定义的也可以代码改劚劂䞋。 ``` const MyLayout = styled(Layout)` display:flex; flex-direction: column; ` function Money() { return { <MyLayout> <TagsSection> <ol> <li>è¡£</li> ``` 4. ui基本完成由于尜量䞍芁䜿埗䞀䞪组件里面文件过倧我们需芁暡块化这䞪Money.tsx这䞪里面的各䞪暡块是埗成䞺独立的组件。 ### Money.tsx 的功胜实现 #### 完成标筟的选择和新增 䜿甚凜数创建组件`const TagsSection: React.FC = (props) => {}`,銖先我们需芁有标筟这䞪数据还埗有修改标筟和读取标筟这䞀䞪功胜然后圚䞀次记莊过皋䞭还埗需芁有选䞭标筟这䞪数据 ``` const [tags, setTags] = useState<string[]>(['è¡£', '食', '䜏', '行']); const [selectedTags, setSelectedTags] = useState<string[]>([]); const onAddTag = () => { const tagName = window.prompt('新标筟的名称䞺'); if (tagName !== null) { setTags([...tags, tagName]); } }; const onToggleTag = (tag: string) => { const index = selectedTags.indexOf(tag); if (index >= 0) { // 劂果 tag 已被选䞭就倍制所有没有被选䞭的 tag䜜䞺新的 selectedTag setSelectedTags(selectedTags.filter(t => t !== tag)); } else { setSelectedTags([...selectedTags, tag]); } }; const getClass = (tag: string) => selectedTags.indexOf(tag) >= 0 ? 'selected' : ''; return ( <Wrapper> <ol> {tags.map(tag => <li key={tag} onClick={ () => {onToggleTag(tag);} } className={getClass(tag)} >{tag}</li> )} </ol> <button onClick={onAddTag}>新增标筟</button> </Wrapper> ); ``` #### 完成倇泚的功胜 銖先䜿甚ref获取到这䞪input元玠然后对它事件监听 ``` const NoteSection: React.FC = () => { const [note, setNote] = useState(''); const refInput = useRef<HTMLInputElement>(null); const onBlur = () => { if (refInput.current !== null) { setNote(refInput.current.value); } }; return ( <Wrapper> <label> <span>倇泚</span> <input type="text" placeholder="圚这里添加倇泚" ref={refInput} defaultValue={note} onBlur={onBlur} /> </label> </Wrapper> ); }; ``` #### category 切换功胜实现 ``` const CategorySection: React.FC = () => { const categoryMap = {'-': '支出', '+': '收入'}; const [categoryList] = useState<('+' | '-')[]>(['-', '+']); const [category, setCategory] = useState('-'); return ( <Wrapper> <ul> {categoryList.map(c => <li className={category === c ? 'selected' : ''} onClick={() => {setCategory(c);}} >{categoryMap[c]} </li> )} </ul> </Wrapper> ); }; ``` #### numberPad 功胜实现 銖先埈确定圚面板星瀺的是字笊䞲而䞍䌚是数字因䞺数字䞍䌚出现'0.'这种状态。 ``` const NumberPadSection: React.FC = () => { const onClickButtonWrapper = (e: React.MouseEvent) => { const [output, _setOutput] = useState('0'); const setOutput = (output: string) => { if (output.length > 16) { output = output.slice(0, 16); } else if (output.length === 0) { output = '0'; } _setOutput(output); }; const text = (e.target as HTMLButtonElement).textContent; if (text === null) {return;} switch (text) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (output === '0') { setOutput(text); } else { setOutput(output + text); } break; case '.': if (output.indexOf('.') >= 0) {return;} setOutput(output + '.'); break; case '删陀': if (output.length === 1) { setOutput(''); } else { setOutput(output.slice(0, -1)); } break; case '枅空': setOutput(''); break; case 'OK': break; } }; return ( <Wrapper> <div className="output"> {output} </div> <div className="pad clearfix" onClick={onClickButtonWrapper}> <button>1</button> <button>2</button> <button>3</button> <button>删陀</button> <button>4</button> <button>5</button> <button>6</button> <button>枅空</button> <button>7</button> <button>8</button> <button>9</button> <button className="ok">OK</button> <button className="zero">0</button> <button className="dot">.</button> </div> </Wrapper> ); }; ``` #### 暡块化思想 由于这䞪文件内容倪倚代码䞍方䟿阅读所以将组件的样匏单独抜出来䞺䞀䞪文件倹再将蟓入面板的操䜜封装成䞀䞪单独的凜数 ``` const generateOutput = (text: string, output = '0') => { switch (text) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (output === '0') { return text; } else { return output + text; } case '.': if (output.indexOf('.') >= 0) {return output;} return output + '.'; case '删陀': if (output.length === 1) { return ''; } else { return output.slice(0, -1) || ''; } case '枅空': return ''; default: return ''; } }; export {generateOutput}; ``` 基本这䞪记莊的页面就奜了后续有䞀些问题慢慢发现慢慢修改。
C#
UTF-8
3,809
3.203125
3
[]
no_license
using NUnit.Framework; using System.Runtime.Serialization; using System.Collections.Generic; using System; using SFDCInjector.Utils; namespace SFDCInjector.Tests.Utils { /// <summary> /// Tests for SFDC Injector's SerializerDeserializer class. /// </summary> [TestFixture] public class SerializerDeserializerTest { /// <summary> /// A simple class used to test serialization methods. /// </summary> [DataContract] class Person { [DataMember(Name="name")] public string Name { get; set; } [DataMember(Name="age")] public int Age { get; set; } public override bool Equals(object obj) { bool isNull = Object.ReferenceEquals(null, obj), isItself = Object.ReferenceEquals(this, obj), isSameType = obj.GetType() == this.GetType(); if (isNull) { return false; } if (isItself || isSameType) { return true; } return IsEqual((Person) obj); } private bool IsEqual(Person person) { return (Name == person.Name && Age == person.Age); } public override int GetHashCode() { unchecked { // Choose large primes to avoid hashing collisions const int HashingBase = (int) 2166136261; const int HashingMultiplier = 16777619; int hash = HashingBase; hash = (hash * HashingMultiplier) ^ (!Object.ReferenceEquals(null, Name) ? Name.GetHashCode() : 0); hash = (hash * HashingMultiplier) ^ (!Object.ReferenceEquals(null, Age) ? Age.GetHashCode() : 0); return hash; } } } /// <summary> /// Maps a Person object to its corresponding JSON. /// </summary> private Dictionary<string, Person> _dict; [OneTimeSetUp] public void Init() { _dict = new Dictionary<string, Person>(); _dict.Add("{\"age\":-1,\"name\":\"John Doe\"}", new Person { Name = "John Doe", Age = -1 }); _dict.Add("{\"age\":0,\"name\":\"Jane Doe\"}", new Person { Name = "Jane Doe", Age = 0}); _dict.Add("{\"age\":1,\"name\":\"\"}", new Person { Name = "", Age = 1}); _dict.Add("{\"age\":100,\"name\":\" \"}", new Person { Name = " ", Age = 100}); _dict.Add("{\"age\":25,\"name\":null}", new Person { Name = null, Age = 25}); } /// <summary> /// Tests the SerializeTypeToJson method. /// </summary> [Test] public void SerializeTypeToJsonTest() { foreach(KeyValuePair<string, Person> kvp in _dict) { string expected = kvp.Key; string actual = SerializerDeserializer.SerializeTypeToJson<Person>(kvp.Value); Assert.That(expected, Is.EqualTo(actual)); } } /// <summary> /// Tests the DeserializeJsonToType method. /// </summary> [Test, Description("Tests the DeserializeJsonToType method.")] public void DeserializeJsonToTypeTest() { foreach(KeyValuePair<string, Person> kvp in _dict) { Person expected = kvp.Value; Person actual = SerializerDeserializer.DeserializeJsonToType<Person>(kvp.Key); Assert.That(expected, Is.EqualTo(actual)); } } } }
C++
UTF-8
617
2.703125
3
[ "MIT" ]
permissive
#include "opencvtypeconverter.h" OpencvTypeConverter::OpencvTypeConverter() { } cv::Rect OpencvTypeConverter::qrect2CvRect(QRectF rect) { return cv::Rect(rect.topLeft().x(),rect.topLeft().y(),rect.width(),rect.height()); } QRectF OpencvTypeConverter::qpoint2CvPoint(cv::Rect rect) { QPoint tl(rect.tl().x, rect.tl().y); QPoint br(rect.br().x, rect.br().y); QRectF ret(tl,br); return QRectF(tl,br); } cv::Point OpencvTypeConverter::qpoint2CvPoint(QPoint pt) { return cv::Point(pt.x(), pt.y()); } QPoint OpencvTypeConverter::cvpoint2QPoint(cv::Point pt) { return QPoint(pt.x, pt.y); }
TypeScript
UTF-8
1,298
3.0625
3
[]
no_license
// interfaces/types import type { StoryPhrases } from "../../../types/storyTypes"; // e.g. As a user, I can edit a text input in the middle, without the cursor going to the end export const STORY_REGEX = RegExp(/as (an?) (.*), I ([a-z]*) ([^,]*)(, .*)?/i); export const getStoryPhrases = (text: string): StoryPhrases => { const captureGroups = text.match(STORY_REGEX); if (!captureGroups) { return null; } else { const aOrAnCaptureGroup = captureGroups[1]; const roleCaptureGroup = captureGroups[2]; const storyAdverbCaptureGroup = captureGroups[3]; const storyActionPhraseCaptureGroup = captureGroups[4]; const rawReasonPhrase = captureGroups.length > 4 ? captureGroups[5] : null; const reasonPhrase = rawReasonPhrase?.length > 2 ? rawReasonPhrase.substr(2).trim() : null; const asText = text.substr(0, 2); const rolePhrase = `${asText} ${aOrAnCaptureGroup} ${roleCaptureGroup}`; const storyPhrase = `I ${storyAdverbCaptureGroup} ${storyActionPhraseCaptureGroup}`; return { rolePhrase, storyPhrase, reasonPhrase }; } }; export const isStoryPaste = (text: string) => { const storyPhrases = getStoryPhrases(text); return !!storyPhrases; };
Java
UTF-8
209
2.171875
2
[]
no_license
package subsequence; /** * Created by thiemann on 21.05.17. */ public class Main { public static PartialOrdering subsequenceCompare(String s1, String s2) { return PartialOrdering.LESS; } }
PHP
UTF-8
1,068
3.09375
3
[]
no_license
<?php namespace App\Classes; use App\Classes\Password; use App\Interfaces\InterfaceLogin; /** * */ class Login { private $email; private $password; /* Gerando os Setters. */ function setEmail($email) { $this->email = $email; } function setPassword($password) { $this->password = $password; } public function logar(interfaceLogin $interfaceLogin) { /* Pegando o Usuario com o Email digitado. */ $userEncontrado = $interfaceLogin->find('usu_login', $this->email); /* Se nao encontrar o usuario para por aqui. */ if(!$userEncontrado) { return false; } /* Instanciando a Classe password. */ $password = new Password; /* Checando a Password Digitada. */ if($password->verificarPassword($this->password, $userEncontrado->usu_password)) { /* Setando a sessao. */ $_SESSION['id'] = $userEncontrado->usu_id; $_SESSION['name'] = ucfirst($userEncontrado->usu_name_first); $_SESSION['level'] = $userEncontrado->usu_level_id; $_SESSION['logado'] = true; return true; }else { return false; } } }
Java
UTF-8
278
2.859375
3
[]
no_license
package HomeworkArray; public class Task3 { public static void main(String[] args) { //print to the console "foo bar" using two positions from this array: String[] s_r = new String[] {"foo ","hello","bar","world"}; System.out.println(s_r[0] + s_r[2]); } }
Ruby
UTF-8
876
4.28125
4
[]
no_license
=begin Write your code for the 'Series' exercise in this file. Make the tests in `series_test.rb` pass. To get started with TDD, see the `README.md` file in your `ruby/series` directory. =end # contiguous = sharing a border; adjacent class Series # start with a string of numbers def initialize(num_string) @num_string = num_string #('01234') end # Array.new(length) { "#{@num_string}" } def slices(pairings) array = @num_string.chars if pairings > array.length raise ArgumentError end new_array = [] array.each_cons(pairings) do |a| if pairings == 1 return array else new_array << a.join end end new_array # step though an array/list and do something with that end # ["01", "12", "23", "34"] # iterate over each digit # return a string of digits that can be n length # each digit had to have been adjacent to the other end
C++
UTF-8
625
2.84375
3
[]
no_license
#ifndef REGISTRO_H #define REGISTRO_H #include <iostream> class Registro { private: std::string estado; std::string data; int codigo; std::string cidade; int casos; int mortes; public: Registro(std::string data, std::string estado, std::string cidade, int codigo, int casos, int mortes); Registro(); std::string getData(){ return this->data; } std::string getCidade(){ return this->cidade; } int getId(){ return this->codigo; } int getCasos(){ return this->casos; } int getCode(){ return this->codigo;} }; #endif
Python
UTF-8
955
2.640625
3
[]
no_license
#much of the code is gotten from these websites: #www.voidspace.org.uk/python/articles/cookielib.shtml #stackoverflow.com/questions/189555/how-to-use-python-to-login-to-a-webpage-and-retrieve-cookies-for-later-usage import urllib import urllib2 import cookielib # handles passwords and cookies class URL: def __init__(self, baseurl, loginurl, theurl, email, password): passman = urllib2.HTTPPasswordMgrWithDefaultRealm() passman.add_password(None,loginurl,email,password) authhandler = urllib2.HTTPBasicAuthHandler(passman) cookiehandler = urllib2.HTTPCookieProcessor(cookielib.LWPCookieJar()) opener = urllib2.build_opener(cookiehandler, authhandler) login_data = urllib.urlencode({'email':email, 'passwd':password}) opener.open(loginurl, login_data) urllib2.install_opener(opener) self.url = urllib2.urlopen(theurl) def get(self): return self.url.read()
C#
UTF-8
598
2.734375
3
[]
no_license
using SOLIDPresentation.Open_Closed; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SOLIDPresentation.LiskovSubstitution { class Mammal : Animal { public override void Fly() { throw new Exception("Mammals can't fly."); } public override void Swim() { Console.WriteLine("Dive deep into the water."); } public override void MakeASound() { throw new Exception("Makes usual mammal sound."); } } }
Markdown
UTF-8
491
2.5625
3
[ "MIT" ]
permissive
# notebooks Our community notebooks used in our workshops and talks. Docker container with Anaconda and some scientific Python stuff. ## Usage You can download and run this image using the following commands: ```sh docker build -t joinvilleml/notebooks:latest . ``` And start the Jupyter Notebook server: ```sh docker run --rm -it -p 8888:8888 -v "$(pwd):/notebooks" joinvilleml/notebooks ``` You can then view the Jupyter Notebook by opening `http://localhost:8888` in your browser.
Java
UTF-8
775
1.796875
2
[]
no_license
package com.example.selim.h2h.utils; import android.app.Application; import com.parse.Parse; import com.parse.ParseACL; import com.parse.ParseInstallation; import com.parse.ParseObject; import com.parse.ParseUser; /** * Created by selim on 26/01/2016. */ public class MyApp extends Application { public ParseUser userPatient; public ParseObject parseObject; @Override public void onCreate() { super.onCreate(); Parse.initialize(this, "5MFXNBCly5I4Do6W0lQSk5ztXjJZWGNweVfIzfsM", "7ICppP0Hqno8Lue1F0f8jpxFBLK84j7ax2MMIQzb"); ParseACL defaultACL = new ParseACL(); defaultACL.setPublicReadAccess(true); ParseACL.setDefaultACL(defaultACL, true); ParseInstallation.getCurrentInstallation().saveInBackground(); } }
C#
UTF-8
1,179
3.4375
3
[ "MIT" ]
permissive
using System; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Collections.Generic; namespace Regex_Exercise_3_Camera_View { class Program { static void Main(string[] args) { int[] numbers = Console.ReadLine().Split(" ").Select(int.Parse).ToArray(); int first = numbers[0]; int second = numbers[1]; string camera = Console.ReadLine(); string pattern = @"\|<([\w]{" + first + @"})([\w]{0," + second + @"})"; // ОзпПлзваЌе кПМкатеМацОя за Ўа ЌПже Ўа сО прПчетеЌ чОслата за разЎеляМе // разЎеляМетП Ма групО МО пПзвПлява Ўа ОзбереЌ тазО част, кПятП ще ПтгПваря Ма услПвОята MatchCollection matches = Regex.Matches(camera, pattern); List<string> films = new List<string>(); foreach (Match film in matches) { films.Add(film.Groups[2].Value); } Console.WriteLine(string.Join(", ", films)); } } }
Python
UTF-8
7,150
3.421875
3
[]
no_license
# Import python 3.0 behaviour so division does not truncate reminder when dividing integers. from __future__ import division import matplotlib.pyplot as plt import csv import pickle from pylab import polyfit, poly1d def loadLabMT(path): """ Load labMT file into a dictionary. """ happiness = {} with open(path, "r") as f: reader = csv.reader(f, delimiter='\t') # Skip first lines that contain only column names and such. for _ in range(4): reader.next() for row in reader: happiness[row[0]] = float(row[2]) return happiness def getSentiment(text, labMT): """ Return sentiment of the text by calculating average happiness. Words are split on whitespace which might not work in some cases. text = string containing the text labMT = dictionary mapping words(lowercase) to happiness rating """ score, matches = 0, 0 for word in text.lower().split(): if word in labMT: score = score + labMT[word] matches += 1 return score / matches if matches > 0 else None def wholeTextSentiment(fileNames, years, labMTPath, outPath): """ Calculate sentiment in a given year. fileNames = a list of fileNames containing pickled reviews years = a sorted ascending list of years with len equal to that of fileNames outPath = path where pickled result will be saved """ print years sentiment = [] labMT = loadLabMT(labMTPath) for i in range(len(fileNames)): with open(fileNames[i], "rb") as f: reviews = pickle.load(f) wholeText = " ".join([entry[0] for entry in reviews]) sentiment += [getSentiment(wholeText, labMT)] with open(outPath, "wb") as f: pickle.dump((years, sentiment), f) def ratingFrequency(reviews, outPath): """ Calculate the total number of reviews for a given rating. reviews = list of review tuples outPath = path where pickled result will be saved. """ freq = {} for r in reviews: rating = r[1] freq[rating] = freq.get(rating, 0) + 1 data = zip(*freq.iteritems()) with open(outPath, "wb") as f: pickle.dump(data, f) def visualiseFrequency(picklePath, title= ""): """ Visualise the result of ratingFrequency function. """ with open(picklePath, "rb") as f: data = pickle.load(f) fig = plt.figure() p = fig.add_subplot(111) p.bar(data[0], data[1], align='center', color='red') plt.xlim([min(data[0])-1, max(data[0])+1]) plt.ylabel("Number of reviews") plt.xlabel("Rating") for e in ['bottom', 'top', 'left', 'right']: p.spines[e].set_color('gray') if title: plt.title(title) plt.show() def visualiseYears(picklePath, title=""): """ Visualise the result of wholeTextSentiment function. """ with open(picklePath, "rb") as f: data = pickle.load(f) fig = plt.figure() p = fig.add_subplot(111) p.plot(data[0], data[1], 'bo-', label="sentiment") p.legend(prop={'size': 10}, frameon=False) plt.ylabel("Average happiness") plt.xlabel("Year") for e in ['bottom', 'top', 'left', 'right']: p.spines[e].set_color('gray') if title: plt.title(title) plt.show() def sentimentRankingComparison(reviews, labMT): """ Return a tuple: ((ratings), (sentiment)) computed for over all reviews. Just plug into pyplot. reviews = a list of tuples: (review string, rating) labMT = dictionary mapping words(lowercase) to happiness rating """ sentimentSum = {} matches = {} for entry in reviews: sentiment = getSentiment(entry[0], labMT) if sentiment is None: continue rating = entry[1] matches[rating] = matches.get(rating, 0) + 1 sentimentSum[rating] = sentimentSum.get(rating, 0) + sentiment ratingAndSentiment = [(rating, sentSum / matches[rating]) for rating, sentSum in sentimentSum.iteritems()] # Keys might have been unsorted. sortedByRating = sorted(ratingAndSentiment, key= lambda (t): t[0]) # We have a list of (rating, sentiment) but for pyplot we want two lists - of ratings and of sentiment. return zip(*sortedByRating) def analyse(reviews, labMTPath, saveResultToPath): """ Analyse the sentiment vs ranking and save the result into fileName path. reviews = list of (review, ranking) tuples labMTPath = path to labMT file saveResultToPath = save the result to this file """ result = sentimentRankingComparison(reviews, loadLabMT(labMTPath)) with open(saveResultToPath, "wb") as f: pickle.dump(result, f) def visualise(fileName, title="", linearFit=False, polyFit=False): """ Draw graph representing the result. A bit verbose as that seem to be the only way to make borders gray. fileName = path and name of the pickled results """ with open(fileName, "rb") as f: data = pickle.load(f) fig = plt.figure() p = fig.add_subplot(111) if not linearFit and not polyfit: p.plot(data[0], data[1], 'bo-', label="sentiment") p.plot([data[0][0], data[0][-1]], [data[1][0], data[1][-1]], 'g', label="straight line through first and last point") elif linearFit: fit = polyfit(data[0], data[1], 1) fitFunc = poly1d(fit) p.plot(data[0], data[1], '-ro', label='sentiment') p.plot(data[0], fitFunc(data[0]), "--k", label="linear fit") elif polyFit: fit = polyfit(data[0], data[1], 2) f = [d*d*fit[0] + d*fit[1] + fit[2] for d in data[0]] p.plot(data[0], data[1], '-ro', label='sentiment') p.plot(data[0], f, "--k", label="polynomial fit") p.legend(prop={'size': 10}, frameon=False) plt.ylabel("Average happiness") plt.xlabel("Rating") for e in ['bottom', 'top', 'left', 'right']: p.spines[e].set_color('gray') if title: plt.title(title) plt.show() def visualiseCombined(fileNames, labels, title=""): """ Draw graph representing combined results. fileNames = list of paths to pickled results """ fig = plt.figure() p = fig.add_subplot(111) for i in range(len(fileNames)): data = normalizeDataFrom(fileNames[i]) p.plot(data[0], data[1], label=labels[i]) p.legend(prop={'size': 10}, frameon=False) plt.ylabel("Average happiness") plt.xlabel("Rating") for e in ['bottom', 'top', 'left', 'right']: p.spines[e].set_color('gray') if title: plt.title(title) plt.show() def normalizeDataFrom(fileName): with open(fileName, "rb") as f: data = pickle.load(f) newData = [] print data if len(data[0]) > 5: averages = [(data[1][i*2]+data[1][i*2+1])/2 for i in range(5)] newData = [range(1,6), averages] print newData else: newData = data return newData
Ruby
UTF-8
844
3
3
[]
no_license
require 'bundler' Bundler.require require_relative 'lib/player' require_relative 'lib/game' #require_relative 'lib/XXX' player1 = Player.new("Lulu la terreur") player2 = Player.new("Carlos le crado") puts " A ma droite nous avons #{player1.name}\n Et à ma gauche nous avons #{player2.name}" puts "\nvoici l'état de nos deux joueurs : " player1.show_state player2.show_state gets.chomp puts "\n\#####le combat va commencer !!!! #####" while player1.life_points != 0 && player2.life_points != 0 player1.attacks(player2) puts "\nvoici l'état de nos deux joueurs :" player1.show_state player2.show_state gets.chomp break if player2.life_points == 0 player2.attacks(player1) puts "\nvoici l'état de nos deux joueurs :" player1.show_state player2.show_state gets.chomp end puts "\n###fin du combat!###" #binding.pry
Java
UTF-8
590
1.664063
2
[]
no_license
package com.daking.sports.activity.personalset; import android.os.Bundle; import android.support.annotation.Nullable; import com.daking.sports.R; import com.daking.sports.base.NewBaseActivity; import butterknife.ButterKnife; /** * Description: * Data2018/4/11-14:18 * steven */ public class PersonActivity extends NewBaseActivity { @Override protected int getLayoutId() { return R.layout.activtiy_personset; } @Override protected void initData() { } @Override protected void initView(@Nullable Bundle savedInstanceState) { } }
Java
UTF-8
1,385
2.4375
2
[]
no_license
package fr.tangv.jeux2diso.objets; import java.util.HashMap; import java.util.Map; import java.util.UUID; import org.simpleyaml.configuration.serialization.ConfigurationSerializable; import fr.tangv.jeux2diso.entity.EntityLocation; public class Location implements ConfigurationSerializable { protected int x; protected int y; protected int z; protected UUID worldid; public EntityLocation toEntityLocation() { return new EntityLocation(x, y, z, World.getWorld(worldid)); } public Location copy() { return new Location(x, y, z, World.getWorld(worldid)); } public Location(int x, int y, int z, World world) { this.x = x; this.y = y; this.z = z; this.worldid = world.getUniqueId(); } public World getWorld() { return World.getWorld(worldid); } public int getX() { return x; } public int getY() { return y; } public int getZ() { return z; } @Override public Map<String, Object> serialize() { Map<String, Object> map = new HashMap<String, Object>(); map.put("x", x); map.put("y", y); map.put("z", z); map.put("worldid", worldid.toString()); return map; } public Location(Map<String, Object> map) { x = (int) map.get("x"); y = (int) map.get("y"); z = (int) map.get("z"); this.worldid = UUID.fromString((String) map.get("worldid")); } }
Java
UTF-8
4,678
2.546875
3
[]
no_license
package com.hjx.android.customviewset.widget; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.DashPathEffect; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.graphics.RectF; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.MotionEvent; import android.widget.ImageView; /** * Created by hjx on 2017/10/11. * You can make it better * * 拖劚选择囟片裁剪矩圢选䞭后选䞭区域䞍可点击选䞭后可以通过setClip讟眮䞍可再裁剪。 */ public class ClipImageView extends ImageView { // private int MIN_WIDTH = 50;//最小蟹长 private boolean isClip = true;//true = 可以拉矩圢裁剪 private boolean isOnClip; // 是吊圚裁剪䞭 private boolean isCustom = false; private float xProportion = 0.5f; private float yProportion = 0.5f; private float widthProportion = 0.3f; private Rect rect; private float downX; private float downY; private float moveX; private float moveY; private Paint paint; public ClipImageView(Context context) { this(context,null); } public ClipImageView(Context context, @Nullable AttributeSet attrs) { this(context, attrs,0); } public ClipImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); setClickable(true); paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColor(Color.RED); paint.setStyle(Paint.Style.STROKE); rect = new Rect(0,0,0,0); } @Override public boolean onTouchEvent(MotionEvent event) { moveX = event.getX(); moveY = event.getY(); switch (event.getAction()){ case MotionEvent.ACTION_DOWN: downY = event.getY(); downX = event.getX(); return !checkInRect(downX,downY,rect)&&isClip;//圚范囎内䞍拊截 case MotionEvent.ACTION_MOVE: // if(positionOk(downX,downY,moveX,moveY)){ isOnClip = true; invalidate(); // } break; case MotionEvent.ACTION_UP: if(isClip // && positionOk(downX,downY,moveX,moveY) ){ rect = sortRect(downX,downY,moveX,moveY); } isOnClip = false; invalidate(); break; default: break; } return isClip; } @Override protected void onDraw(Canvas canvas) { Path clipPath = new Path(); int width = getWidth(); int height = getHeight(); if(isCustom){ rect = new Rect((int)(xProportion*width),(int)(yProportion*height),(int)(xProportion*width+widthProportion*width),(int)(yProportion*height+widthProportion*height)); } clipPath.addRect(0, 0 ,width, rect.top, Path.Direction.CW); clipPath.addRect(0, 0 , rect.left,height, Path.Direction.CW); clipPath.addRect(rect.right, 0 ,width, height, Path.Direction.CW); clipPath.addRect(0, rect.bottom ,width,height, Path.Direction.CW); int save = canvas.save(); canvas.clipPath(clipPath); super.onDraw(canvas); canvas.restoreToCount(save); if(isOnClip){ Path path = new Path(); Rect pathRect = sortRect(downX, downY, moveX, moveY); path.addRect(new RectF(pathRect), Path.Direction.CW); paint.setPathEffect(new DashPathEffect(new float[]{5f,2f},0)); canvas.drawPath(path,paint); } } //重眮 public void reset(){ rect = new Rect(0,0,0,0); postInvalidate(); } // private boolean positionOk(float x,float y,float x1,float y1){ // return Math.abs(x1 - x) > MIN_WIDTH && Math.abs(y1 - y) > MIN_WIDTH; // } public void setClip(boolean clip) { isClip = clip; } private Rect sortRect(float x1, float y1, float x2, float y2){ Rect result = new Rect(0,0,0,0); result.left = (int) Math.max(Math.min(x1, x2),0); result.top = (int) Math.max(Math.min(y1, y2),0); result.right = (int) Math.min(Math.max(x1, x2),getWidth()); result.bottom = (int) Math.min(Math.max(y1, y2),getHeight()); return result; } public boolean checkInRect(float x,float y, Rect rect) { return (x>rect.left && x<rect.right) && (y>rect.top && y<rect.bottom); } }
Swift
UTF-8
709
2.5625
3
[]
no_license
// // TouchDownGestureRecognizer.swift // Treader // // Created by Derik Flanary on 3/7/16. // Copyright © 2016 Derik Flanary. All rights reserved. // import Foundation import UIKit import UIKit.UIGestureRecognizerSubclass class TouchDownGestureRecognizer: UIGestureRecognizer { override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent) { if self.state == .Possible { self.state = .Recognized } } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent) { self.state = .Failed } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent) { self.state = .Failed } }
PHP
UTF-8
802
2.9375
3
[]
no_license
<?php //$createEntry = true; $servername = "localhost"; $dbuser = 'root'; $dbpass = ''; $dbname = "nearbuy"; $connection = mysqli_connect($servername, $dbuser, $dbpass,$dbname); if (!$connection) { die("Connection failed: " . mysqli_connect_error()); } $createEntry = $_POST['prepareTable']; if($createEntry){ //creates a randomKey with which to encrypt //associates an ID with the user //extremely lazy $upperBound = pow(2, 20); $id = rand(1, $upperBound); $key = rand(1, $upperBound); //echo $id; //echo $key; $query = "INSERT INTO `user`(`id`, `encryptionKey`) VALUES ('$id' , '$key') " ; mysqli_query($connection, $query); $array = array($id, $key); //$array[0]=$id //$array[1]=$key mysqli_close($connection); echo json_encode($array); } else echo "ERROR"; ?>
Rust
UTF-8
90
2.6875
3
[]
no_license
extern crate add_two; #[test] fn it_adds_two() { assert_eq!(4, add_two::add_two(2)); }
Shell
UTF-8
256
2.609375
3
[]
no_license
#!/bin/bash #siitalgabskript echo -n "Mitu rida soovid: "; read rida for (( j = 1; j <= $rida; j++ )) do echo -n "$j." for (( a = ((rida-1)); a >= $j; a--)) do echo -n "O" done for (( i = 1; i <= $j; i++ )) do echo -n "*" done echo "" done
Java
UTF-8
7,728
2.953125
3
[]
no_license
package org.jyoshiriro.pocs.marsexplorer.model; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.jyoshiriro.pocs.marsexplorer.exception.BoundaryReachedException; import org.jyoshiriro.pocs.marsexplorer.exception.PlaneNotDefinedException; import static org.junit.jupiter.api.Assertions.*; class SpaceProbeTest { Plane plane5x5 = new Plane(5, 5); Coordinate coordinate2x2 = new Coordinate(2, 2); @Test void setPlaneShouldThrowExceptionForInvalidCoordinate() { int invalidX = 6; int invalidY = 6; Coordinate invalidCoordinate1 = new Coordinate(plane5x5.getWidth(), invalidY); Coordinate invalidCoordinate2 = new Coordinate(invalidX, plane5x5.getHeight()); Coordinate invalidCoordinate3 = new Coordinate(invalidX, invalidY); assertThrows(BoundaryReachedException.class, () -> new SpaceProbe(invalidCoordinate1, Direction.N).setPlane(plane5x5)); assertThrows(BoundaryReachedException.class, () -> new SpaceProbe(invalidCoordinate2, Direction.N).setPlane(plane5x5)); assertThrows(BoundaryReachedException.class, () -> new SpaceProbe(invalidCoordinate3, Direction.N).setPlane(plane5x5)); } @Test void moveShouldThrowExceptionForInvalidCoordinate() { SpaceProbe spaceProbeLowerLimit = new SpaceProbe(new Coordinate(0,0), Direction.W); spaceProbeLowerLimit.setPlane(plane5x5); assertThrows(BoundaryReachedException.class, () -> spaceProbeLowerLimit.move(Movement.M)); spaceProbeLowerLimit.move(Movement.L); assertThrows(BoundaryReachedException.class, () -> spaceProbeLowerLimit.move(Movement.M)); SpaceProbe spaceProbeGreatestLimit = new SpaceProbe(new Coordinate(5,5), Direction.N); spaceProbeGreatestLimit.setPlane(plane5x5); assertThrows(BoundaryReachedException.class, () -> spaceProbeGreatestLimit.move(Movement.M)); spaceProbeGreatestLimit.move(Movement.R); assertThrows(BoundaryReachedException.class, () -> spaceProbeGreatestLimit.move(Movement.M)); } @Test void setPlaneShouldWorkForValidCoordinate() { assertDoesNotThrow(() -> new SpaceProbe( new Coordinate(plane5x5.getWidth(), plane5x5.getHeight()), Direction.N).setPlane(plane5x5)); assertDoesNotThrow(() -> new SpaceProbe( new Coordinate(plane5x5.getWidth()-1, plane5x5.getHeight()), Direction.N).setPlane(plane5x5)); assertDoesNotThrow(() -> new SpaceProbe( new Coordinate(plane5x5.getWidth(), plane5x5.getHeight()-1), Direction.N).setPlane(plane5x5)); assertDoesNotThrow(() -> new SpaceProbe(new Coordinate(0, 0), Direction.N).setPlane(plane5x5)); } @Test void moveShouldThrowExceptionIfNoPlane() { for (Movement movement : Movement.values()) { assertThrows(PlaneNotDefinedException.class, () -> new SpaceProbe(coordinate2x2, Direction.N).move(movement)); } } @Test void moveShouldTurnRightCorrectly() { for (Direction direction : Direction.values()) { SpaceProbe spaceProbe = new SpaceProbe(coordinate2x2, direction); spaceProbe.setPlane(plane5x5); spaceProbe.move(Movement.R); assertEquals(direction.getToTheRight(), spaceProbe.getDirection()); } } @Test void moveShouldTurnLeftCorrectly() { for (Direction direction : Direction.values()) { SpaceProbe spaceProbe = new SpaceProbe(coordinate2x2, direction); spaceProbe.setPlane(plane5x5); spaceProbe.move(Movement.L); assertEquals(direction.getToTheLeft(), spaceProbe.getDirection()); } } @Test void movingShouldKeepDirectionAfterMoving() { for (Direction direction : Direction.values()) { SpaceProbe spaceProbe = new SpaceProbe(coordinate2x2, direction); spaceProbe.setPlane(plane5x5); spaceProbe.move(Movement.M); assertEquals(direction, spaceProbe.getDirection()); } } @Test @DisplayName("Space probe starting from 1,2 N on a 5x5 plane after LMLMLMLMM should stop at 1,3 N") void movingShouldMoveTakeToTheRightCoordinate_Scenario1() { SpaceProbe spaceProbe = new SpaceProbe(new Coordinate(1,2), Direction.N); spaceProbe.setPlane(plane5x5); spaceProbe.move(Movement.L); spaceProbe.move(Movement.M); assertEquals(0, spaceProbe.getCoordinate().getX()); assertEquals(2, spaceProbe.getCoordinate().getY()); assertEquals(Direction.W, spaceProbe.getDirection()); spaceProbe.move(Movement.L); spaceProbe.move(Movement.M); assertEquals(0, spaceProbe.getCoordinate().getX()); assertEquals(1, spaceProbe.getCoordinate().getY()); assertEquals(Direction.S, spaceProbe.getDirection()); spaceProbe.move(Movement.L); spaceProbe.move(Movement.M); assertEquals(1, spaceProbe.getCoordinate().getX()); assertEquals(1, spaceProbe.getCoordinate().getY()); assertEquals(Direction.E, spaceProbe.getDirection()); spaceProbe.move(Movement.L); spaceProbe.move(Movement.M); assertEquals(1, spaceProbe.getCoordinate().getX()); assertEquals(2, spaceProbe.getCoordinate().getY()); assertEquals(Direction.N, spaceProbe.getDirection()); spaceProbe.move(Movement.M); assertEquals(1, spaceProbe.getCoordinate().getX()); assertEquals(3, spaceProbe.getCoordinate().getY()); assertEquals(Direction.N, spaceProbe.getDirection()); } @Test @DisplayName("Space probe starting from 3,3 E on a 5x5 plane after MMRMMRMRRM should stop at 5,1 E") void movingShouldMoveTakeToTheRightCoordinate_Scenario2() { SpaceProbe spaceProbe = new SpaceProbe(new Coordinate(3, 3), Direction.E); spaceProbe.setPlane(plane5x5); spaceProbe.move(Movement.M); assertEquals(4, spaceProbe.getCoordinate().getX()); assertEquals(3, spaceProbe.getCoordinate().getY()); assertEquals(Direction.E, spaceProbe.getDirection()); spaceProbe.move(Movement.M); assertEquals(5, spaceProbe.getCoordinate().getX()); assertEquals(3, spaceProbe.getCoordinate().getY()); assertEquals(Direction.E, spaceProbe.getDirection()); spaceProbe.move(Movement.R); spaceProbe.move(Movement.M); assertEquals(5, spaceProbe.getCoordinate().getX()); assertEquals(2, spaceProbe.getCoordinate().getY()); assertEquals(Direction.S, spaceProbe.getDirection()); spaceProbe.move(Movement.M); assertEquals(5, spaceProbe.getCoordinate().getX()); assertEquals(1, spaceProbe.getCoordinate().getY()); assertEquals(Direction.S, spaceProbe.getDirection()); spaceProbe.move(Movement.R); spaceProbe.move(Movement.M); assertEquals(4, spaceProbe.getCoordinate().getX()); assertEquals(1, spaceProbe.getCoordinate().getY()); assertEquals(Direction.W, spaceProbe.getDirection()); spaceProbe.move(Movement.R); spaceProbe.move(Movement.R); spaceProbe.move(Movement.M); assertEquals(5, spaceProbe.getCoordinate().getX()); assertEquals(1, spaceProbe.getCoordinate().getY()); assertEquals(Direction.E, spaceProbe.getDirection()); } }
Java
UTF-8
712
2.03125
2
[]
no_license
package com.mmj.active.homeManagement.model; import java.util.List; public class WebMaketingEx { private List<WebMaketing> list; private Integer showId; private Integer maketingShow; public List<WebMaketing> getList() { return list; } public void setList(List<WebMaketing> list) { this.list = list; } public Integer getShowId() { return showId; } public void setShowId(Integer showId) { this.showId = showId; } public Integer getMaketingShow() { return maketingShow; } public void setMaketingShow(Integer maketingShow) { this.maketingShow = maketingShow; } }
Ruby
UTF-8
1,138
2.578125
3
[ "MIT" ]
permissive
require 'metriks' require 'rubypython' require 'pygments.rb' class Content module Code include Pygments # Heroku's cedar stack raises an "invalid ELF header" exception using the # latest version of python (2.7) on the system. python2.6 seems to work fine. RubyPython.configure :python_exe => 'python2.6' def self.highlight(code, lexer) Metriks.timer('viso.pygments').time { Pygments.highlight code, lexer: lexer, options: { encoding: 'utf-8' } } end def content return super unless code? return large_content if code_too_large? Code.highlight raw, lexer_name end def code? lexer_name && !%w( text postscript minid ).include?(lexer_name) end def lexer_name timer = Metriks.timer('viso.pygments.lexer_name').time @lexer_name ||= lexer_name_for :filename => @content_url rescue RubyPython::PythonError false ensure timer.stop end def code_too_large? raw.size >= 50_000 end def large_content %{<div class="highlight"><pre><code>#{ escaped_raw }</code></pre></div>} end end end
Java
UTF-8
1,019
2.515625
3
[]
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 citbyui.cit260.mountKabru.view; import byui.MountKabru.Control.GameControl; /** * * @author Moose */ public class LoadGameView extends View { public LoadGameView() { super("What is the name of the game you wish to load?"); } @Override public boolean doAction(String filePath) { try { //load a save game GameControl.getSavedGame(filePath); } catch (Exception ex) { ErrorView.display("MainMenuView", ex.getMessage()); return false; } this.console.println("Your game has lodded now get to work! you loaded: " + filePath); GameMenuView gameMenu = new GameMenuView(); gameMenu.display(); return true; } }
Java
UTF-8
3,795
3.09375
3
[]
no_license
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; public class P1 { public static int check(ArrayList<Character> word){ int dLeft = 0; int dRight = 0; int count = 0; while ( word.size() > 2 ){ //cat timp mai avem cel putin o litera facem verificari if ( word.get(0) == word.get ( word.size() - 1 ) ){ //daca cele 2 capete sunt egale: word.remove(0); //stergem capatul stanga word.remove( word.size() - 1 ); //stergem capatul drept continue; }else{ for(int i = 1 ; i < word.size() - 1 ; i++){ //daca nu sunt egale calculam distanta de la capatul stang pana la intalnirea carecterului din dreapta if ( word.get(i) == word.get ( word.size() - 1 ) ){ dLeft = i; //daca l-am gasit,memoram pozitia si ne oprim break; } dLeft = 10000; //daca nu,dam o valoarea foarte mare distantei(de preferat infinit) } for(int i = word.size() - 2 ; i >= 1 ; i--){ //calculam si distanta de la extrema dreapta pana la intalnirea unui caracter egal cu cel din stanga if ( word.get(i) == word.get(0) ){ dRight = word.size() - 1 - i; //memoram pozitia si iesim break; } dRight=10000; //daca nu,dam o valoarea foarte mare distantei(de preferat infinit) } if (dRight == 10000 && dLeft == 10000){ //daca nu s-au gasit niciunul din caractere inseamna ca avem 2 caractere diferite => cuvantul nu e palindrom count = -1; break; } if (dLeft <= dRight){ //verificam care distanta este mai mica,ca sa stim ce caracter il vom translata pana la cea mai apropiata extrema word.remove(dLeft); //stergem elementul,pt ca dupa permutari ar ajunge in dreapta,caz in care este acelasi cu extrema stanga=>stergere word.remove(word.size() - 1); //stergem extrema dreapta count += dLeft; }else{ word.remove(word.size() - 1 - dRight); //stergem elementul,pt ca dupa permutari ar ajunge in dreapta,caz in care este acelasi cu extrema stanga=>stergere word.remove(0); //stergem extrema stanga count += dRight; } } } return count; //nr de modificari } public static void main(String[] args) { // TODO Auto-generated method stub BufferedReader in = null; int numWords=0; String word; ArrayList<Integer> result=new ArrayList<Integer>(); try { in = new BufferedReader(new FileReader("joc.in")); numWords=Integer.parseInt(in.readLine()); //citim numarul de cuvinte //System.out.println(numWords); for(int i=0;i<numWords;i++){ ArrayList<Character> letters=new ArrayList<Character>(); //memoram literele intr-un ArrayList word=new String(in.readLine()); for(int j=0;j<word.length();j++){ letters.add(word.charAt(j)); //inseram fiecare litera din fiecare cuvant intr-o lista propie } result.add(check(letters)); //lista care pastreaza rezultatele pt fiecare cuvant } } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } PrintWriter out; try { out = new PrintWriter(new FileWriter("joc.out")); for (int i = 0; i < result.size(); i++) { //pt fiecare rezultat dupa prelucrarea cuvantului din lista out.println(result.get(i)); //scrie acest rezultat in fisier } out.close(); } catch (Exception e) { e.printStackTrace(); } } }
C#
UTF-8
3,945
2.875
3
[ "MS-PL", "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SimpleRX { public class LookupSubject<T, TKey> : BaseSubject<ILookup<TKey, T>> { private IObservable<T> source; private Func<T, TKey> keySelector; private IDisposable subscriped; private BaseSubject<T> subject; private Lookup<TKey, T> lookup = new Lookup<TKey, T>(); public LookupSubject(IObservable<T> source, Func<T, TKey> keySelector) { this.source = source; this.keySelector = keySelector; BaseSubject<T> subject = (BaseSubject<T>)source; this.subject = subject; var observer = new Observer<T>( value => InnerExecute(value), ex => NotifyErrorObservers(ex), () => NotifyCompleteObservers()); this.subscriped = subject.ColdSubscribe(observer); } private void InnerExecute(T value) { var selectorValue = keySelector(value); lookup.Add(selectorValue, value); } public override void Execute() { try { subject.Execute(); NotifyObservers(lookup); } catch (Exception exception) { NotifyErrorObservers(exception); } } } public class Lookup<TKey, TElement> : ILookup<TKey, TElement> { private Dictionary<TKey, List<TElement>> lookup = new Dictionary<TKey, List<TElement>>(); private List<TKey> keys; public bool Contains(TKey key) { return lookup.ContainsKey(key); } public void Add(TKey key, TElement element) { List<TElement> list = null; if(!lookup.TryGetValue(key, out list)) { list = new List<TElement>(); list.Add(element); lookup.Add(key, list); } list.Add(element); } public int Count { get { return lookup.Count(); } } public IEnumerable<TElement> this[TKey key] { get { List<TElement> list = null; if (!lookup.TryGetValue(key, out list)) { yield return default(TElement); } foreach (var item in list) { yield return item; } } } public IEnumerator<IGrouping<TKey, TElement>> GetEnumerator() { foreach (KeyValuePair<TKey, List<TElement>> item in lookup) { Grouping<TKey, TElement> grouping = new Grouping<TKey, TElement>(item.Key); foreach (var element in item.Value) { grouping.Add(element); } yield return grouping; } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class Grouping<TKey, TElement> : IGrouping<TKey, TElement> { private TKey key = default(TKey); private List<TElement> group = new List<TElement>(); public Grouping(TKey key) { this.key = key; } public void Add(TElement element) { group.Add(element); } public TKey Key { get { return key; } } public IEnumerator<TElement> GetEnumerator() { return group.Select(x => x).GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
Java
UTF-8
302
1.9375
2
[]
no_license
package com.blazers.jandan.model.event; import com.blazers.jandan.util.log.Log; /** * Created by blazers on 2016/12/8. */ public class FastScrollUpEvent { public int index; public FastScrollUpEvent(int index) { this.index = index; Log.i("ScrollUpEvent" + index); } }
Java
UTF-8
3,052
1.976563
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2015 Bubblegum Developers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.bubblegum.traceratops.sdk.client; public class TLog { static TLog sInstance; TLog() { } public static void v(String tag, String message, Object object) { if(sInstance!=null) { sInstance.vInternal(tag, message, object); } else { Traceratops.warnNotLogging(); } } public static void d(String tag, String message, Object object) { if(sInstance!=null) { sInstance.dInternal(tag, message, object); } else { Traceratops.warnNotLogging(); } } public static void w(String tag, String message, Object object) { if(sInstance!=null) { sInstance.wInternal(tag, message, object); } else { Traceratops.warnNotLogging(); } } public static void e(String tag, String message, Object object) { if(sInstance!=null) { sInstance.eInternal(tag, message, object); } else { Traceratops.warnNotLogging(); } } public static void i(String tag, String message, Object object) { if(sInstance!=null) { sInstance.iInternal(tag, message, object); } else { Traceratops.warnNotLogging(); } } public static void wtf(String tag, String message, Object object) { if(sInstance!=null) { sInstance.wtfInternal(tag, message, object); } else { Traceratops.warnNotLogging(); } } private void dInternal(String tag, String message, Object object) { Log.sInstance.logInternalAsync(tag, message, object, LogProxy.D); } private void eInternal(String tag, String message, Object object) { Log.sInstance.logInternalAsync(tag, message, object, LogProxy.E); } private void iInternal(String tag, String message, Object object) { Log.sInstance.logInternalAsync(tag, message, object, LogProxy.I); } private void vInternal(String tag, String message, Object object) { Log.sInstance.logInternalAsync(tag, message, object, LogProxy.V); } private void wInternal(String tag, String message, Object object) { Log.sInstance.logInternalAsync(tag, message, object, LogProxy.W); } private void wtfInternal(String tag, String message, Object object) { Log.sInstance.logInternalAsync(tag, message, object, LogProxy.WTF); } }
Python
UTF-8
1,774
2.84375
3
[]
no_license
import numpy as np import pandas as pd from collections import Counter from random import shuffle train_data = np.load('training_data.npy') df = pd.DataFrame(train_data) print(df.head()) print(Counter(df[1].apply(str))) forwards = [] lefts = [] rights = [] backs = [] forwardAndLefts = [] forwardAndRights = [] backAndLefts = [] backAndRights = [] noKeys = [] for data in train_data: img = data[0] choice = data[1] if(choice == [1,0,0,0,0,0,0,0,0]): forwards.append([img,choice]) elif(choice == [0,1,0,0,0,0,0,0,0]): lefts.append([img,choice]) elif(choice == [0,0,1,0,0,0,0,0,0]): rights.append([img,choice]) elif(choice == [0,0,0,1,0,0,0,0,0]): backs.append([img,choice]) elif(choice == [0,0,0,0,1,0,0,0,0]): forwardAndLefts.append([img,choice]) elif(choice == [0,0,0,0,0,1,0,0,0]): forwardAndRights.append([img,choice]) elif(choice == [0,0,0,0,0,0,1,0,0]): backAndLefts.append([img,choice]) elif(choice == [0,0,0,0,0,0,0,1,0]): backAndRights.append([img,choice]) elif(choice == [0,0,0,0,0,0,0,0,1]): noKeys.append([img,choice]) else: print("No key to match") forwards = forwards[:len(lefts)][:len(rights)] lefts = lefts[:len(forwards)] rights = rights[:len(forwards)] backs = backs[:len(forwards)] forwardAndLefts = forwardAndLefts[:len(forwards)] forwardAndRights = forwardAndRights[:len(forwards)] backAndLefts = backAndLefts[:len(forwards)] backAndRights = backAndRights[:len(forwards)] noKeys = noKeys[:len(forwards)] final_data = forwards + lefts + rights + backs + forwardAndLefts + forwardAndRights + backAndLefts + backAndRights + noKeys; shuffle(final_data) print(len(final_data)) dff = pd.DataFrame(final_data) print(dff.head()) print(Counter(dff[1].apply(str)))
Python
UTF-8
14,983
3.15625
3
[ "MIT" ]
permissive
import pandas as pd from datetime import datetime import math nan = float('nan') #Definindo primeira Linha iterável da planilha def get_begin_row(data,rows,begin_string): for row in rows: if(data.iloc[row][0] == begin_string): new_begin = int(row) #Primeiro indice não None pós matricula begin = new_begin +1 for i in range(begin,len(data.index)): try: if(not math.isnan(data.iloc[i][0])): return i except: return i #Definindo ultima Linha Iterável da Planilha def get_end_row(data,rows,end_string): rows.reverse() #Caso contenha total geral for row in rows: if(data.iloc[row][0] == end_string): return int(row) #Se não temos total geral for row in rows: #Lugar com o primeiro nome de pessoas try: if(not math.isnan(data.iloc[row][2])): return int(row) except: return int(row) return None #Define estratégia de leitura baseada na extensão do arquivo. def read_data(path,extension): if('ods' in extension): df_engine = 'odf' else: df_engine = 'xlrd' #Leitura de arquivo em disco. try: data = pd.read_excel(path,engine = df_engine) except Exception as excep: print(excep) return data #Definindo primeira Linha iterável da planilha para planilhas sem Indenizações def get_begin_row_notIn(data,rows,begin_string): for row in rows: if(data.iloc[row][0] == begin_string): new_begin = int(row) #Parser, convertendo os objetos para o formato exigido para empregados sem dados indenizatórios def employees(file_name,outputPath,year,month,file_type): #Definindo main Data extension = file_name.split('.') path = './/' + outputPath +'//' + file_name data = read_data(path,extension) rows = list(data.index.values) #Definindo linhas Iteráveis da planilha Principal begin_string = "Nome ou Matrícula" begin_row = get_begin_row(data,rows,begin_string) end_string = "TOTAL GERAL" end_row = get_end_row(data,rows,end_string) return all_employees_novi(data,begin_row,end_row,file_type) #Para empregados sem dados de verbas indenizatórias def all_employees_novi(data,begin_row,end_row,file_type): employees = [] for i in range(begin_row,end_row): employee = { 'reg' : data.iloc[i][0], 'name': data.iloc[i][0], 'role': data.iloc[i][3], 'type': file_type, 'workplace': data.iloc[i][13], 'active': True if ('Ativos' in file_type) else False, "income": #Income Details {'total' : format_string(data.iloc[i][25]), # ? Total Liquido ?? 'wage' : format_string(data.iloc[i][14]), 'perks' : #Perks Object { 'total' : format_string(data.iloc[i][27]), 'vacation_pecuniary':format_string(data.iloc[i][18]),#Férias }, 'other': { #Funds Object 'total': format_string(data.iloc[i][26]), 'trust_position' : format_string(data.iloc[i][16]), #Pericia e projeto 'gratification': format_string(data.iloc[i][17]), #Só existem dados da gratificação natalina 'others': format_string(data.iloc[i][15]) + format_string(data.iloc[i][19]), #Não encontrado } , } , 'discounts': { #Discounts Object 'total' : format_string(data.iloc[i][24]) * -1 if(format_string(data.iloc[i][24]) < 0) else format_string(data.iloc[i][24]), 'prev_contribution': format_string(data.iloc[i][21]) * -1 if(format_string(data.iloc[i][21]) < 0) else format_string(data.iloc[i][21]), 'ceil_retention': format_string(data.iloc[i][23]) * -1 if(format_string(data.iloc[i][24]) < 0) else format_string(data.iloc[i][23]), 'income_tax': format_string(data.iloc[i][22]) * - 1 if(format_string(data.iloc[i][22]) < 0) else format_string(data.iloc[i][22]), } } employees.append(employee) return (employees) #Para empregados no formato de mês com indenização mas sem match def all_employees(data,begin_row,end_row,file_type): employees = [] for i in range(begin_row,end_row): employee = { 'reg' : data.iloc[i][0], 'name': data.iloc[i][2], 'role': data.iloc[i][7], 'type': file_type, 'workplace': data.iloc[i][11], 'active': True if ('Ativos' in file_type) else False, "income": #Income Details {'total' : format_string(data.iloc[i][26]), # ? Total Liquido ?? 'wage' : format_string(data.iloc[i][12]), 'perks' : #Perks Object { 'total' : format_string(data.iloc[i][20]), 'compensatory_leave':format_string(data.iloc[i][19]), 'vacation_pecuniary':format_string(data.iloc[i][18]),#Férias }, 'other': { #Funds Object 'total': format_string(data.iloc[i][27]), 'trust_position' : format_string(data.iloc[i][14]), #Pericia e projeto 'gratification': format_string(data.iloc[i][17]), #Só existem dados da gratificação natalina 'others': format_string(data.iloc[i][13]), #Não encontrado } , } , 'discounts': { #Discounts Object 'total' : format_string(data.iloc[i][25]) * -1 if (format_string(data.iloc[i][25]) < 0) else format_string(data.iloc[i][25]), 'prev_contribution': format_string(data.iloc[i][22]) * -1 if(format_string(data.iloc[i][22]) < 0) else format_string(data.iloc[i][22]), 'ceil_retention': format_string(data.iloc[i][24]) * -1 if(format_string(data.iloc[i][24]) < 0) else format_string(data.iloc[i][24]), 'income_tax': format_string(data.iloc[i][23]) * - 1 if (format_string(data.iloc[i][23]) < 0) else format_string(data.iloc[i][23]), } } if(begin_row == end_row): return employee else: employees.append(employee) return (employees) #Parser, convertendo os objetos para o formato exigido para empregados com dados indenizatórios def employees_indemnity(file_name,indemnity_name,outputPath,year,month,file_type): #Definindo aspectos do main Data extension = file_name.split('.') path = './/' + outputPath + "//" + file_name data = read_data(path,extension) rows = list(data.index.values) #Definindo linhas Iteráveis da planilha Principal begin_string = "Matrícula" begin_row = get_begin_row(data,rows,begin_string) end_string = "TOTAL GERAL" end_row = get_end_row(data,rows,end_string) #Definindo aspectos dos dados indenizatórios indemnity_extension = indemnity_name.split('.') indemnity_path = './/' + outputPath + '//' + indemnity_name indemnity_data = read_data(indemnity_path,indemnity_extension) return all_employees_indemnity(data,begin_row,end_row,indemnity_data,file_type) # Encontra a linha que representa um funcionário na planilha de indenizações por meio do ID def match_line(id,indemnity_data): rows = list(indemnity_data.index.values) for row in rows: if(indemnity_data.iloc[row][0] == id): return row # Formata as Strings para o json, retirando os (R$) def format_string(string): if(isinstance(string, float)): return string elif(isinstance(string,int)): return float(string) aux = str(string) if(aux.find('(') != -1): aux = string[2:-1] aux = aux.replace(',','.') else: aux = string[2:] aux = aux.replace(',','.') return float(aux) #Função responsável por definir array com dados dos empregados + indenizações def all_employees_indemnity(data,begin_row,end_row,indemnity_data,file_type): employees = [] id = data.iloc[begin_row][0] match_row = match_line(id,indemnity_data) i = begin_row while(i <= end_row): #Por motivos desconhecidos alguns funcionários não estão na planilha indenizatória # --- mesmo estando na planilha comum ---# if(indemnity_data.iloc[match_row][0] == data.iloc[i][0]): #print("Data com indenização" + str(data.iloc[i][0])) employee = { 'reg' : data.iloc[i][0], 'name': data.iloc[i][2], 'role': data.iloc[i][7], 'type': file_type, 'workplace': data.iloc[i][11], 'active': True if ('Ativos' in file_type) else False, "income": #Income Details {'total' : data.iloc[i][26], # ? Total Liquido ?? 'wage' : data.iloc[i][12], 'perks' : #Perks Object { 'total' : format_string(indemnity_data.iloc[match_row][26]), 'food' : format_string(indemnity_data.iloc[match_row][16]), 'transportation': format_string(indemnity_data.iloc[match_row][19]), 'pre_school': format_string(indemnity_data.iloc[match_row][17]), 'birth_aid': format_string(indemnity_data.iloc[match_row][21]), 'housing_aid': format_string(indemnity_data.iloc[match_row][23]), 'subistence': format_string(indemnity_data.iloc[match_row][22]), 'compensatory_leave':format_string(indemnity_data.iloc[match_row][23]), 'pecuniary':format_string(indemnity_data.iloc[match_row][24]), 'vacation_pecuniary':format_string(indemnity_data.iloc[match_row][15]),#Férias 'furniture_transport':format_string(indemnity_data.iloc[match_row][20]), "premium_license_pecuniary": format_string(indemnity_data.iloc[match_row][25]), }, 'other': { #Funds Object 'total': format_string(indemnity_data.iloc[match_row][40]), 'eventual_benefits': format_string(indemnity_data.iloc[match_row][39]), #Férias 'trust_position' : format_string(data.iloc[i][14]), #Pericia e projeto 'gratification': format_string(indemnity_data.iloc[match_row][27]) + format_string(indemnity_data.iloc[match_row][28]) + format_string(indemnity_data.iloc[match_row][29]) + format_string(indemnity_data.iloc[match_row][30]) + format_string(indemnity_data.iloc[match_row][31]), 'others_total': format_string(indemnity_data.iloc[match_row][32]) + format_string(indemnity_data.iloc[match_row][33]) + format_string(indemnity_data.iloc[match_row][34]) + format_string(indemnity_data.iloc[match_row][35]) + format_string(indemnity_data.iloc[match_row][36]) + format_string(indemnity_data.iloc[match_row][37]) + format_string(indemnity_data.iloc[match_row][38]), 'others': format_string(data.iloc[i][13]), } , } , 'discounts': { #Discounts Object 'total' : (data.iloc[i][25]) * -1 if(format_string(data.iloc[i][25]) < 0) else format_string(data.iloc[i][25]), 'prev_contribution': data.iloc[i][22] * -1 if(format_string(data.iloc[i][22]) < 0) else format_string(data.iloc[i][22]), 'ceil_retention': data.iloc[i][24] * -1 if(format_string(data.iloc[i][24]) < 0) else format_string(data.iloc[i][24]), 'income_tax': (data.iloc[i][23] * - 1) if(format_string(data.iloc[i][23]) < 0) else format_string(data.iloc[i][23]), } } else: id = data.iloc[i][0] before_match = match_row match_row = match_line(id,indemnity_data) if(match_row == None): employee = all_employees(data,i,i,file_type) else: employee = all_employees(data,i,i,file_type) if(match_row == None): match_row = before_match i += 1 else: match_row += 1 i += 1 employees.append(employee) return (employees) #Função Auxiliar responsável pela tradução de um mês em um numero. def get_month_number(month): months = { 'Janeiro' : 1 , 'Fevereiro':2 , 'Março': 3, 'Abril': 4, 'Maio':5, 'Junho':6, 'Julho':7, 'Agosto':8, 'Setembro':9, 'Outubro':10, 'Novembro':11, 'Dezembro':12 } return months[month] #Função destinada a verificar se exisem os dados acerca de verbas indenizatórias #------ Apenas para querys pós julho de 2019 ------# def check_indemnity(year,month): valid_months2019 = ['Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'] if(int(year) < 2019): return False elif((int(year) == 2019) and (month not in valid_months2019)): return False else: return True #Processo de geração do objeto resultado do Crawler e Parser. def crawler_result(year,month,outputPath,file_names): #Ordem do tipo de arquivos file_order = ['Membros Ativos','Membros Inativos','Servidores Ativos','Servidores Inativos','Pensionistas','Colaboradores Ativos'] #Realizando o processo de parser em todas as planilhas employee = [] final_employees = [] if(check_indemnity(year,month)): indemnity_names = file_names.pop(-1) for i in range(len(file_names)): final_employees.append(employees_indemnity(file_names[i],indemnity_names[i],outputPath,year,month,file_order[i])) else: for i in range(len(file_names)): final_employees.append(employees(file_names[i],outputPath,year,month,file_order[i])) #Armazenando Todos os Empregados em lista unica for lista in final_employees: for employe in lista: employee.append(employe) month_number = get_month_number(month) now = datetime.now() return { 'agencyID' : 'MPF' , 'month' : month_number, 'year' : int(year), 'crawler': { #CrawlerObject 'crawlerID': 'mpf', 'crawlerVersion': 'Inicial' , }, 'files' : file_names, 'employees': employee, 'timestamp': now.strftime("%H:%M:%S"), 'procInfo' : '' }
Java
UTF-8
5,935
2.71875
3
[]
no_license
package org.ubimix.model; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.ubimix.commons.parser.json.utils.JavaObjectBuilder; import org.ubimix.commons.parser.json.utils.JavaObjectVisitor; /** * @author kotelnikov */ public class TreePresenter { @SuppressWarnings("unchecked") public static Map<Object, Object> copy(Map<Object, Object> map) { JavaObjectVisitor visitor = new JavaObjectVisitor(); JavaObjectBuilder builder = new JavaObjectBuilder(); visitor.visit(map, false, builder); return (Map<Object, Object>) builder.getTop(); } public static String toString(Object value) { return value != null ? value.toString() : null; } private String fFieldName; public TreePresenter(String fieldName) { fFieldName = fieldName; } public boolean addChild(Map<Object, Object> map, int pos, Object innerObject) { boolean result = false; if (pos < 0) { return result; } Object value = map.get(fFieldName); if (value == null) { map.put(fFieldName, innerObject); result = true; } else { if (value instanceof List<?>) { @SuppressWarnings("unchecked") List<Object> list = (List<Object>) value; if (pos >= 0 && pos <= list.size()) { list.add(pos, innerObject); result = true; } } else { if (pos == 0 || pos == 1) { List<Object> list = new ArrayList<Object>(); map.put(fFieldName, list); list.add(value); list.add(pos, innerObject); result = true; } } } return result; } public int getChildCount(Map<Object, Object> map) { Object value = map.get(fFieldName); int result = 0; if (value != null) { if (value instanceof List<?>) { result = ((List<?>) value).size(); } else { result = 1; } } return result; } public Object getChildObject(Map<Object, Object> map, int pos) { Object value = map.get(fFieldName); Object result = null; if (value != null) { if (value instanceof List<?>) { List<?> list = ((List<?>) value); result = pos >= 0 && pos < list.size() ? list.get(pos) : null; } else { result = pos == 0 ? value : null; } } return result; } public int getChildPosition(Map<Object, Object> map, Object nodeObject) { int result = -1; Object value = map.get(fFieldName); if (value != null) { if (value instanceof List<?>) { List<?> list = (List<?>) value; result = indexOf(list, nodeObject); } else if (nodeObject.equals(value)) { result = 0; } } return result; } public <W> List<W> getChildren( Map<Object, Object> map, IValueFactory<W> factory) { List<W> result = new ArrayList<W>(); Object value = map.get(fFieldName); if (value != null) { if (value instanceof List<?>) { List<?> list = (List<?>) value; for (Object c : list) { W child = factory.newValue(c); if (child != null) { result.add(child); } } } else { W child = factory.newValue(value); if (child != null) { result.add(child); } } } return result; } private int indexOf(List<?> list, Object nodeObject) { int idx = -1; if (!list.isEmpty()) { for (idx = 0; idx < list.size(); idx++) { if (same(nodeObject, list.get(idx))) { break; } } if (idx >= list.size()) { idx = -1; } } return idx; } public boolean removeChild(Map<Object, Object> map, int pos) { boolean result = false; if (pos < 0) { return result; } Object value = map.get(fFieldName); if (value != null) { if (value instanceof List<?>) { List<?> list = (List<?>) value; result = pos >= 0 && pos < list.size() && list.remove(pos) != null; if (list.isEmpty()) { map.remove(fFieldName); } else if (list.size() == 1) { map.put(fFieldName, list.get(0)); } } else if (pos == 0) { result = map.remove(fFieldName) != null; } } return result; } public boolean removeChild(Map<Object, Object> map, Object object) { Object value = map.get(fFieldName); boolean result = false; if (value != null) { if (value instanceof List<?>) { List<?> list = (List<?>) value; list.remove(object); if (list.isEmpty()) { map.remove(fFieldName); } else if (list.size() == 1) { map.put(fFieldName, list.get(0)); } } else if (value.equals(object)) { result = map.remove(fFieldName) != null; } } return result; } public void removeChildren(Map<Object, Object> map) { map.remove(fFieldName); } private boolean same(Object first, Object second) { return first == second; } }
C#
UTF-8
461
3.046875
3
[]
no_license
using System.Linq; namespace Dji.UI.Extensions { public static class StringExtensions { public static bool IsValidHexString(this string value) { string[] hexValues = value.Trim().Split(' '); return !(hexValues.Any(h => h.Length != 4) || hexValues.Any(h => h[1] != 'X' && h[1] != 'x') || hexValues.Any(h => h[0] != '0') || hexValues.Any(h => !h[2].IsHex() || !h[3].IsHex())); } } }
Java
UTF-8
684
3.25
3
[]
no_license
package src.Arrayprograms; public class Arraysort11 { public static void main(String[] args) { int temp; // int length; int []array= { 3,5,6,2 }; int length=array.length; for(int i=0;i<=length;i++) { for(int j=i+1;j<=length-1;j++) { if(array[i]>array[j]) { temp=array[i]; array[i]=array[j]; array[j]=temp; } } //System.out.println(array[i]); } System.out.print("Ascending Order:"); for (int i = 0; i < length - 1; i++) { System.out.print(array[i] + ","); } System.out.print(array[length - 1]); // System.out.println(array[i]); // for(int value:array) {System.out.println(array[value]);} } }
C#
UTF-8
2,616
2.890625
3
[ "MIT" ]
permissive
using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; namespace MauiDoctor { public class Util { public Util() { } public const string DoctorEnvironmentVariableNamePrefix = "MAUI_DOCTOR_"; public static void SetDoctorEnvironmentVariable(string name, string value) { Environment.SetEnvironmentVariable(name, value); } public static string GetDoctorEnvironmentVariable(string name) { foreach (DictionaryEntry ev in Environment.GetEnvironmentVariables()) { if (ev.Key.ToString().StartsWith(DoctorEnvironmentVariableNamePrefix, StringComparison.OrdinalIgnoreCase)) { var evName = ev.Key.ToString().Substring(DoctorEnvironmentVariableNamePrefix.Length); if (evName.Equals(name, StringComparison.OrdinalIgnoreCase)) return ev.Value?.ToString(); } } return null; } public static IEnumerable<KeyValuePair<string, string>> GetDoctorEnvironmentVariables() { foreach (DictionaryEntry ev in Environment.GetEnvironmentVariables()) { var key = ev.Key.ToString(); if (key?.StartsWith(DoctorEnvironmentVariableNamePrefix, StringComparison.OrdinalIgnoreCase) ?? false) { var v = ev.Value?.ToString(); if (!string.IsNullOrEmpty(v)) yield return new KeyValuePair<string, string>(key, v); } } } public static Platform Platform { get { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return Platform.Windows; if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) return Platform.OSX; if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD)) return Platform.Linux; return Platform.Windows; } } public static bool IsWindows => Platform == Platform.Windows; public static bool IsMac => Platform == Platform.OSX; [DllImport("libc")] #pragma warning disable IDE1006 // Naming Styles static extern uint getuid(); #pragma warning restore IDE1006 // Naming Styles public static bool IsAdmin() { try { if (IsWindows) { using (var identity = System.Security.Principal.WindowsIdentity.GetCurrent()) { var principal = new System.Security.Principal.WindowsPrincipal(identity); if (!principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator)) { return false; } } } else if (getuid() != 0) { return false; } } catch { return false; } return true; } } public enum Platform { Windows, OSX, Linux } }
Java
UTF-8
2,038
2.21875
2
[]
no_license
/* * RemoveFuncSigFileAction.java * * Created on December 18, 2005, 3:17 PM * * To change this template, choose Tools | Options and locate the template under * the Source Creation and Management node. Right-click the template and choose * Open. You can then make changes to the template in the Source Editor. */ package com.arexis.mugen.webapp.action.model; import com.arexis.form.FormDataManager; import com.arexis.mugen.MugenCaller; import com.arexis.mugen.MugenFormDataManagerFactory; import com.arexis.mugen.webapp.action.MugenAction; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; /** * * @author lami */ public class RemoveFuncSigFileAction extends MugenAction { /** Creates a new instance of RemoveFuncSigFileAction */ public RemoveFuncSigFileAction() { } /** * Returns the name of this action * @return The name of the action */ public String getName() { return "RemoveFuncSigFileAction"; } /** * Performs this action * @param request The http request object * @param context The servlet context * @return True if this action could be performed */ public boolean performAction(HttpServletRequest request, ServletContext context) { try { MugenCaller caller = (MugenCaller)request.getSession().getAttribute("caller"); FormDataManager formDataManager = getFormDataManager( MugenFormDataManagerFactory.EXPMODEL, MugenFormDataManagerFactory.WEB_FORM, request); String fsid = formDataManager.getValue("fsid"); modelManager.removeFunctionalSignificanceFile(Integer.parseInt(fsid), caller); GetFuncSigAction action = new GetFuncSigAction(); action.performAction(request, context); return true; } catch (Exception e) { e.printStackTrace(); } return false; } }
Python
UTF-8
452
3.6875
4
[]
no_license
import math def shellSort(alist): length = len(alist) gap = int(math.floor(length/2)) while gap > 0: for i in range(gap, length, 1): for j in range(i, -1, -gap): if j-gap >= 0 and alist[j-gap] > alist[j]: alist[j-gap], alist[j] = alist[j], alist[j-gap] else: break gap = int(math.floor(gap/2)) array = [121,65,12,2,1,6,56,3,54,4] shellSort(array) print array
Java
UTF-8
2,495
2.328125
2
[]
no_license
package cz.muni.fi.pv243.musiclib.dao.impl; import cz.muni.fi.pv243.musiclib.dao.SongDao; import cz.muni.fi.pv243.musiclib.dao.UserDao; import cz.muni.fi.pv243.musiclib.entity.Album; import cz.muni.fi.pv243.musiclib.entity.Artist; import cz.muni.fi.pv243.musiclib.entity.Genre; import cz.muni.fi.pv243.musiclib.entity.Song; import cz.muni.fi.pv243.musiclib.entity.User; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.persistence.Query; import javax.persistence.TypedQuery; import javax.transaction.Transactional; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.util.List; /** * @author <a href="mailto:martin.styk@gmail.com">Martin Styk</a> */ @ApplicationScoped @Transactional(value = Transactional.TxType.REQUIRED) public class SongDaoImpl extends GenericDaoImpl<Song, Long> implements SongDao, Serializable { public SongDaoImpl() { super(Song.class); } @Inject private UserDao userDao; @Override public List<Song> searchByTitle(@NotNull String titleFragment) { return em.createQuery("SELECT s FROM Song s WHERE UPPER(s.title) LIKE '%'||:titleFragment||'%'", Song.class) .setParameter("titleFragment", titleFragment.toUpperCase()) .getResultList(); } @Override public void remove(Long id) { //first remove all entries from music lib join table referencing this song Query query = em.createNativeQuery("DELETE FROM MusicLib lib WHERE lib.song_id = :songId", User.class).setParameter("songId", id); query.executeUpdate(); em.remove(this.em.getReference(Song.class, id)); } @Override public List<Song> searchByAlbum(@NotNull Album album) { TypedQuery<Song> q = em.createQuery("SELECT s FROM Song s WHERE s.album = :albumId", Song.class).setParameter("albumId", album); return q.getResultList(); } @Override public List<Song> searchByArtist(@NotNull Artist artist) { TypedQuery<Song> q = em.createQuery("SELECT s FROM Song s WHERE s.artist = :artistId", Song.class).setParameter("artistId", artist); return q.getResultList(); } @Override public List<Song> searchByGenre(@NotNull Genre genre) { TypedQuery<Song> q = em.createQuery("SELECT s FROM Song s WHERE s.genre = :genreId", Song.class).setParameter("genreId", genre); return q.getResultList(); } }
C#
UTF-8
1,717
3.46875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MatrixProblems { public class ValidTicTacToe { int[,] matrix; int size = 0; public ValidTicTacToe(int n) { matrix = new int[n,n]; size = n; } public int Move(int row, int col, int player) { matrix[row,col] = player; //check row bool win = true; for (int i = 0; i < size; i++) { if (matrix[row,i] != player) { win = false; break; } } if (win) return player; //check column win = true; for (int i = 0; i <size; i++) { if (matrix[i,col] != player) { win = false; break; } } if (win) return player; //check back diagonal win = true; for (int i = 0; i <size; i++) { if (matrix[i,i] != player) { win = false; break; } } if (win) return player; //check forward diagonal win = true; for (int i = 0; i < size; i++) { if (matrix[i,size - i - 1] != player) { win = false; break; } } if (win) return player; return 0; } } }
PHP
UTF-8
760
2.890625
3
[]
no_license
<?php $arr=array( 'student1'=>array("name"=>"Vishal", "age"=>"10", "fname"=>"Satish", "mobile"=>"3456", "city"=>"Delhi"), 'student2'=>array("name"=>"Amit", "age"=>"13", "fname"=>"ABC", "mobile"=>"444", "city"=>"Patna"), 'student3'=>array("name"=>"Submit", "age"=>"45", "fname"=>"FFGG", "mobile"=>"3333", "city"=>"Noida"), ); $heading=[]; foreach($arr as $list){ foreach($list as $key=>$val){ $heading[$key]=$key; } } ?> <table border="1"> <tr> <?php foreach($heading as $list){?> <td><?php echo $list?></td> <?php } ?> </tr> <?php foreach($arr AS $arrList){?> <tr> <?php foreach($arrList AS $list){?> <td><?php echo $list?></td> <?php }?> </tr> <?php }?> </table>
C#
UTF-8
712
3.390625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; namespace Adf.Test { public static class EnumerableExtensions { public static T PickOne<T>(this IEnumerable<T> e) { var one = e.Skip(new Random().Next(e.Count()) - 1).First(); Console.WriteLine("Picked {0}: {1}", typeof(T).Name, one); return one; } public static T PickOneOrDefault<T>(this IEnumerable<T> e, T defaultValue) where T : class { var one = e.Skip(new Random().Next(e.Count()) - 1).FirstOrDefault() ?? defaultValue; Console.WriteLine("Picked {0}: {1}", typeof(T).Name, one); return one; } } }
Markdown
UTF-8
2,421
2.65625
3
[ "MIT" ]
permissive
Customizable PHP Error Handler (custom-php-error-handler) ======================== <strong>Copyright (c) 2014-2023 Rich Morgan, rich@richmorgan.me</strong> Description ------------ This is a custom, flexible and configurable error handler useful for debugging. It writes the specified level of error messages to a log file and can be set to either bypass or not bypass the internal PHP error handler. Also can log backtraces of the function calls and the complete context of variables present at the time of the error. Installation ------------ Include this error handling script at the top of your own PHP scripts. For example: ```php include_once('MyErrHandler.php'); ``` Usage ----- 1. Set the error reporting to the level you want to capture. 2. Set the error handler to this custom function. 3. The filename parameter is optional and defaults to "php_errors.log" in the same directory. For example, if you want to capture all errors, notices, warnings: ```php error_reporting(E_ALL); ini_set('error_reporting', E_ALL); set_error_handler('MyErrHandler', E_ALL); ``` License ------ Released under the MIT License. <pre> The MIT License (MIT) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. </pre> Contributing ------------ All code contributions, bugfixes, enhancements, etc are welcome! Feel free to fork this project and submit pull requests. Version History --------------- <strong>Version 1.0.0:</strong><br />-Initial release 12/6/2014
Java
UTF-8
1,005
2.21875
2
[]
no_license
package com.hospital.Service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.hospital.Dao.*; import com.hospital.Interface.*; import com.hospital.Entity.*; @Service public class GioiThieuChiTietService implements GioiThieuChiTietInterface{ @Autowired GioiThieuChiTietDAO itemDAO = null; public List<GioiThieuChiTiet> getListGioiThieuChiTiet() { return itemDAO.getListGioiThieuChiTiet(); } public GioiThieuChiTiet getGioiThieuChiTiet(int id) { return itemDAO.getGioiThieuChiTiet(id); } public void addGioiThieuChiTiet(GioiThieuChiTiet item) { itemDAO.addGioiThieuChiTiet(item); } public void deleteGioiThieuChiTiet(GioiThieuChiTiet item) { itemDAO.deleteGioiThieuChiTiet(item); } public void updateGioiThieuChiTiet(GioiThieuChiTiet item) { itemDAO.updateGioiThieuChiTiet(item); } public long countAllGioiThieuChiTiet() { return itemDAO.countAllGioiThieuChiTiet(); } }
Java
UTF-8
782
3.171875
3
[]
no_license
/** * Creates an object with the player's history * @author Mehdi Himmiche * @date Apr 25, 2016 */ public class OperationHistory { private String operation; private String correctAnswer; private String selectAnswer; public OperationHistory(String operation, String correct, String selected) { this.operation = operation; this.correctAnswer = correct; this.selectAnswer = selected; } /** * Returns the operation saved * @return operation */ public String getOperation() { return operation; } /** * Returns the correct answer * @return correct answer */ public String getCorrectAnswer() { return correctAnswer; } /** * Returns the selected answer * @return selected answer */ public String getSelectedAnswer() { return selectAnswer; } }
Java
UTF-8
908
2.078125
2
[]
no_license
package zhuazhu.readhub.mvp.launcher; import android.Manifest; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.tbruyelle.rxpermissions2.RxPermissions; import java.util.concurrent.TimeUnit; import zhuazhu.readhub.R; import zhuazhu.readhub.mvp.main.MainActivity; public class LauncherActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_launcher); RxPermissions rxPermissions = new RxPermissions(this); rxPermissions.request(Manifest.permission.READ_PHONE_STATE,Manifest.permission.WRITE_EXTERNAL_STORAGE) .delay(3,TimeUnit.SECONDS) .subscribe(aBoolean -> { MainActivity.start(LauncherActivity.this); finish(); }); } }
Java
UTF-8
7,095
2.21875
2
[]
no_license
package com.catbattle.bean; public class CatInfo { private String catId; private String catName; private String category; private String defaultLevel; private String maxLevel; private String hp; private String kb; private String attack; private String attackRate; private String speed; private String attackAnimation; private String attackDistance; private String cooldown; private String attackType; private String cost; private String cd; private String skill; private String getCondition; private String alias; private String img; private String antiEnemy; private String skillType; private String categoryDescribe; private String antiEnemyDescribe; private String skillTypeDescribe; private Integer attackLevel; private Float attackBefore; private Float attackAfter; private Integer hpLevel; private Float hpBefore; private Float hpAfter; private Float basicAttack; private Float basicHp; public String getCatId() { return catId; } public void setCatId(String catId) { this.catId = catId == null ? null : catId.trim(); } public String getCatName() { return catName; } public void setCatName(String catName) { this.catName = catName == null ? null : catName.trim(); } public String getCategory() { return category; } public void setCategory(String category) { this.category = category == null ? null : category.trim(); } public String getDefaultLevel() { return defaultLevel; } public void setDefaultLevel(String defaultLevel) { this.defaultLevel = defaultLevel == null ? null : defaultLevel.trim(); } public String getMaxLevel() { return maxLevel; } public void setMaxLevel(String maxLevel) { this.maxLevel = maxLevel == null ? null : maxLevel.trim(); } public String getHp() { return hp; } public void setHp(String hp) { this.hp = hp == null ? null : hp.trim(); } public String getKb() { return kb; } public void setKb(String kb) { this.kb = kb == null ? null : kb.trim(); } public String getAttack() { return attack; } public void setAttack(String attack) { this.attack = attack == null ? null : attack.trim(); } public String getAttackRate() { return attackRate; } public void setAttackRate(String attackRate) { this.attackRate = attackRate == null ? null : attackRate.trim(); } public String getSpeed() { return speed; } public void setSpeed(String speed) { this.speed = speed == null ? null : speed.trim(); } public String getAttackAnimation() { return attackAnimation; } public void setAttackAnimation(String attackAnimation) { this.attackAnimation = attackAnimation == null ? null : attackAnimation.trim(); } public String getAttackDistance() { return attackDistance; } public void setAttackDistance(String attackDistance) { this.attackDistance = attackDistance == null ? null : attackDistance.trim(); } public String getCooldown() { return cooldown; } public void setCooldown(String cooldown) { this.cooldown = cooldown == null ? null : cooldown.trim(); } public String getAttackType() { return attackType; } public void setAttackType(String attackType) { this.attackType = attackType == null ? null : attackType.trim(); } public String getCost() { return cost; } public void setCost(String cost) { this.cost = cost == null ? null : cost.trim(); } public String getCd() { return cd; } public void setCd(String cd) { this.cd = cd == null ? null : cd.trim(); } public String getSkill() { return skill; } public void setSkill(String skill) { this.skill = skill == null ? null : skill.trim(); } public String getGetCondition() { return getCondition; } public void setGetCondition(String getCondition) { this.getCondition = getCondition == null ? null : getCondition.trim(); } public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias == null ? null : alias.trim(); } public String getImg() { return img; } public void setImg(String img) { this.img = img == null ? null : img.trim(); } public String getAntiEnemy() { return antiEnemy; } public void setAntiEnemy(String antiEnemy) { this.antiEnemy = antiEnemy == null ? null : antiEnemy.trim(); } public String getSkillType() { return skillType; } public void setSkillType(String skillType) { this.skillType = skillType == null ? null : skillType.trim(); } public String getCategoryDescribe() { return categoryDescribe; } public void setCategoryDescribe(String categoryDescribe) { this.categoryDescribe = categoryDescribe == null ? null : categoryDescribe.trim(); } public String getAntiEnemyDescribe() { return antiEnemyDescribe; } public void setAntiEnemyDescribe(String antiEnemyDescribe) { this.antiEnemyDescribe = antiEnemyDescribe == null ? null : antiEnemyDescribe.trim(); } public String getSkillTypeDescribe() { return skillTypeDescribe; } public void setSkillTypeDescribe(String skillTypeDescribe) { this.skillTypeDescribe = skillTypeDescribe == null ? null : skillTypeDescribe.trim(); } public Integer getAttackLevel() { return attackLevel; } public void setAttackLevel(Integer attackLevel) { this.attackLevel = attackLevel; } public Float getAttackBefore() { return attackBefore; } public void setAttackBefore(Float attackBefore) { this.attackBefore = attackBefore; } public Float getAttackAfter() { return attackAfter; } public void setAttackAfter(Float attackAfter) { this.attackAfter = attackAfter; } public Integer getHpLevel() { return hpLevel; } public void setHpLevel(Integer hpLevel) { this.hpLevel = hpLevel; } public Float getHpBefore() { return hpBefore; } public void setHpBefore(Float hpBefore) { this.hpBefore = hpBefore; } public Float getHpAfter() { return hpAfter; } public void setHpAfter(Float hpAfter) { this.hpAfter = hpAfter; } public Float getBasicAttack() { return basicAttack; } public void setBasicAttack(Float basicAttack) { this.basicAttack = basicAttack; } public Float getBasicHp() { return basicHp; } public void setBasicHp(Float basicHp) { this.basicHp = basicHp; } }
Markdown
UTF-8
583
2.609375
3
[]
no_license
--- permalink: /projects.html layout: default title: CLARIPHY Projects --- # Projects involving CLARIPHY collaborators We list here a number of small projects which are underway and which involve CLARIPHY collaborators. These are often larger projects with additional participants, which can be found on the linked project pages. <ul> {% assign sorted = site.pages | sort_natural: 'title' %} {% for mypage in sorted %} {% if mypage.layout == 'project' %} <li><a href="{{mypage.permalink}}">{{ mypage.title }}</a> - {{ mypage.description }} </li> {% endif %} {% endfor %} </ul>
Python
UTF-8
1,172
3.078125
3
[]
no_license
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm def graficar_3d(n): matriz=np.array(n, dtype='float').reshape(3,4) b=matriz[:,3] A=np.delete(matriz, 3, axis=1) print(A) print(b) solu=np.linalg.solve(A,b) print (solu) print(np.allclose(np.dot(A,solu), b)) x,y=np.linspace(0,10,10),np.linspace(0,10,10) X,Y=np.meshgrid(x,y) #Z1=(22-2*X-4*Y)/6 Z1=(float(n[3])-float(n[0])*X-float(n[1])*Y)/float(n[2]) #Z2=(27-3*X-8*Y)/5 Z2=(float(n[7])-float(n[4])*X-float(n[5])*Y)/float(n[6]) #Z3=(2+X-Y)/2 Z3=(float(n[11])-float(n[8])*X-float(n[9])*Y)/float(n[10]) fig=plt.figure() aux=fig.add_subplot(111,projection='3d') aux.plot_surface(X,Y,Z1,alpha=0.5,cmap=cm.Accent,rstride=100,cstride=100) aux.plot_surface(X,Y,Z2,alpha=0.5,cmap=cm.Paired,rstride=100,cstride=100) aux.plot_surface(X,Y,Z3,alpha=0.5,cmap=cm.Pastel1,rstride=100,cstride=100) aux.plot((solu[0],),(solu[1],),(solu[2]), lw=2,c='k',marker='X',markersize=7,markerfacecolor='black') aux.set_xlabel('X');aux.set_ylabel('Y');aux.set_zlabel('Z') plt.show()
Python
UTF-8
825
4.3125
4
[]
no_license
""" A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. """ ## maybe find a multiple of 3,4,5 such that they add up to 1000? # so # c(3+4+5) = 1000 => c(12) = 1000 # NOPE DOES NOT WORK def check_py_trip(a,b,c): return a**2 + b**2 == c**2 def find_py_trip_sum(n): """ return pythagorean triplet that adds up to n """ for a in range(1,n): for b in range(1,n): for c in range(1,n): if (check_py_trip(a,b,c) and (a+b+c == n)): return (a,b,c) return False n = 1000 a,b,c = find_py_trip_sum(n) print(a,b,c) prod = a * b * c print(prod)
Markdown
UTF-8
965
2.859375
3
[ "MIT" ]
permissive
# BubFusion The game consists of levels. The level is a grid field which can consists moving and stationary objects. There can initially be two types of balls on the level: full and empty. With the help of swipes, the player is able to move the balls. When touch begin, the same balls combine into one, which changes the type. For example, two full ones make an empty one and opposite. In addition to the balls, various obstacles will be placed on the level, such as spikes, walls, etc. The player's task is to fuse all the balls into one. https://user-images.githubusercontent.com/73526739/132767604-4bfb00a4-0af2-4f2e-a689-0c63d5765a46.mp4 Main menu & Level selection scene <img width="272" alt="image" src="https://user-images.githubusercontent.com/73526739/132766550-6490a84e-efc3-4100-8494-5f630d61928d.png"> <img width="272" alt="image" src="https://user-images.githubusercontent.com/73526739/132766973-5945cc93-3d82-4e90-87f2-b362a3f246dd.jpeg">
Java
UTF-8
958
3.8125
4
[]
no_license
/** * Title: Temperature Converter * Description: * Company: Heritage College * @author Philip * @version 1.0 */ import java.util.Scanner; public class TemperatureConverter { public static void main(String args[]) { Scanner keyboard = new Scanner (System.in); int celsiusTemperature; double fahrenheitTemperature; String yourName; System.out.print("What is your name? "); yourName = keyboard.next(); System.out.println("Hello " + yourName); System.out.print("What is the temperature in Celsius? "); celsiusTemperature = keyboard.nextInt(); fahrenheitTemperature = (celsiusTemperature/5 *9) +32; System.out.println("Celsius temperature is " + celsiusTemperature); System.out.println("Fahrenheit temperature is " + fahrenheitTemperature); } // main(String[]) } // TemperatureConverter class
Markdown
UTF-8
3,216
2.875
3
[]
no_license
--- title: Charlie Chawke ‘very’ interested in buying Newcastle United author: Kevin Doocey type: post date: 2009-07-12T11:33:38+00:00 url: /2009/07/12/charlie-chawke-very-interested-in-buying-newcastle-united/ dsq_thread_id: - "92802650" categories: - Charlie Chawke - Newcastle United News tags: - Charlie Chawke - Newcastle United Take Over - Newcatsle United Latest News - NUFC Blog --- ### Chawke - Interested in obtaining Newcastle United Breaking news today about the Newcastle United takeover. I was eating my breakfast and listening to national radio when I heard Newcastle mentioned. Thinking it was all about the friendly I listened half intently and then I heard some rather staggering news about a new runner for Newcastle United. Charlie Chawke was speaking to the radio channel in Ireland 'RTE Radio' and confirmed to radio host that he is interested in buying Newcastle United. For those of you that don't know who he is, he's the man that had a huge hand in bringing Sunderland to where they are now. He owned quite a bit of Sunderland but recently sold, for a profit, to Ellis Short. Speaking to the radio he said Newcastle was a far bigger 'pocket' and that such a city, with such supporters deserve to be in the Premier League. Chawke, was heavily involved with Niall Quinn and brought Sunderland back to the big stage, and stayed there. He'd be a very good owner, a very wise man, well known in Ireland for his ventures and said he would love the adventure of bringing Newcastle United back to the Premier League, where they belong. A pundit speaking after that advised Charlie to get a move on because the other consortia were 'well down the road' with the Newcastle United sale. Only problem is, it would take another good week for Charlie and his fellow men to make any progress in the sale. 'We're putting a syndicate hopefully together to do just that (bid for Newcastle). 'We had a great time in Sunderland. We got seven Irish people and one English person together with a syndicate and we succeeded in acquiring Sunderland. > 'We had three great years there but unfortunately we're gone now. It's sold out to an American and we're looking for options and Newcastle is a very viable option at the moment. > > 'It's on sale for about 100 million which is about 500 million less than what it was worth a year and a half or two years ago. > > 'We have to look at options other than Sunderland and Newcastle would fit very nicely into our portfolio.' > > 'What we're trying to do at the moment is put together a syndicate of people who are interested firstly in football and then investing with us in Newcastle United if possible.' > > 'We're thinking about possibly the same as we had in Sunderland, about eight people maybe, depending on what money we can get.' > > 'It's a great club, it houses 52,000 people. It's a great city, Newcastle. > > 'It's a bit like Dublin - vibrant, full of fun&#8230; all the best things in life are there. It makes perfect sense if I could just swing it.' So there it is, the sale takes another twist. A new interested party - Charlie Chawke heading a bid for Newcastle United amongst other rich individuals. Remember where you heard it first - Tyne Time 😀 Comments welcome 🙂
Java
UTF-8
1,586
2.609375
3
[ "MIT" ]
permissive
package pizzatech; import java.awt.Color; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; public class JanelaCadastrarProduto extends JFrame{ public class Linha{ JLabel l; JTextField t; } public JanelaCadastrarProduto(){ setTitle("Cadastrar Produtos"); setLocation(180, 180); setSize(380, 130); setResizable(true); setDefaultCloseOperation(EXIT_ON_CLOSE); getContentPane().setLayout(new FlowLayout()); JPanel p1 = new JPanel(); p1.setLayout(new GridLayout(3, 2)); String[] nomeDoLabel = {"Nome:", "Tipo:", "Preço:"}; ArrayList<Linha> vL = new ArrayList<Linha>(); for(int i = 0; i < 3; i++){ vL.add(new Linha()); vL.get(i).l = new JLabel(nomeDoLabel[i]); p1.add(vL.get(i).l); vL.get(i).t = new JTextField(15); p1.add(vL.get(i).t); } p1.setBounds(50, 50, 200, 100); add(p1); JButton bSalvar = new JButton("Salvar"); bSalvar.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String[] informacoes = new String[3]; for(int i = 0; i < 3; i++){ informacoes[i] = vL.get(i).t.getText(); System.out.println(informacoes[i]); vL.get(i).t.setText(""); } Dao.salvarCadastroDeProduto(informacoes); new JanelaDeOpcoes(); dispose(); } }); add(bSalvar); setVisible(true); } }
Java
UTF-8
8,060
1.84375
2
[]
no_license
package api.keyword.controller; import java.io.IOException; import java.util.List; import java.util.concurrent.TimeUnit; import javax.naming.directory.InvalidAttributesException; import org.apache.http.client.ClientProtocolException; import org.json.JSONException; import org.openqa.selenium.By; import api.keyword.KeywordEnum; import api.keyword.service.ApiKeywordService; import api.keyword.service.ApiNonKeywordService; import constants.FrameworkConstants; import testcase.RequestBase; import testcase.RequestData; import testcase.TestCase; import testcase.TestSuite; import ui.webdriver.Browser; import ui.webdriver.ObjectLocator; import ui.webdriver.action.CheckBox; import ui.webdriver.action.Click; import ui.webdriver.action.ComboBox; import ui.webdriver.action.InputLabel; import utility.StringUtilities; public class ApiKeywordController { public static final String BASIC_AUTHENTICATION_HEADER="basic"; static final String HEADER="header"; public void executeKeyword(TestSuite testCase, TestCase testStep, RequestBase requestBase, List<RequestData> requestDataList) throws ClientProtocolException, IOException, JSONException, InvalidAttributesException, NumberFormatException, InterruptedException { KeywordEnum keyword = KeywordEnum.getKeywordValue(testStep.getKeyword()); String[] objectKeyValue; switch(keyword) { case BASEURL: ApiKeywordService.setUrl(requestBase, testCase.getTestData().get(testStep.getParam1())); break; case SERVICE: ApiKeywordService.setServiceUrl(requestBase, testCase.getTestData().get(testStep.getParam1())); break; case REQUESTMETHOD: ApiKeywordService.setMethod(requestBase, testStep.getParam1(), testCase.getTestData().get(testStep.getParam1())); break; case REQUESTHEADER: if(testCase.getTestData().get(testStep.getParam1()).equalsIgnoreCase(BASIC_AUTHENTICATION_HEADER)) { requestBase.setAuthenticationType(BASIC_AUTHENTICATION_HEADER); requestBase.setAuthenicationUser(testCase.getTestData().get(testStep.getParam2())); requestBase.setAuthenicationPassword(testCase.getTestData().get(testStep.getParam3())); ApiKeywordService.setHeader(requestDataList, "username;;password", testCase.getTestData().get(testStep.getParam2())+";;"+testCase.getTestData().get(testStep.getParam3()),BASIC_AUTHENTICATION_HEADER); } else ApiKeywordService.setHeader(requestDataList, testStep.getParam1(), testCase.getTestData().get(testStep.getParam1()),HEADER); break; case REQUESTPARAMETER: ApiKeywordService.setParameter(requestDataList, testStep.getParam1(), testCase.getTestData().get(testStep.getParam1())); break; case REQUESTSUBMISSION: ApiKeywordService.requestSubmission(requestBase, requestDataList); break; case VERIFYSTATUS: ApiKeywordService.verifyResponseStatus(requestBase,testCase.getTestData().get(testStep.getParam1())); break; case VERIFYPARAMETERCOUNT: ApiKeywordService.verifyParamterCount(requestBase,testCase.getTestData().get(testStep.getParam1())); break; case VERIFYDATATYPE: ApiKeywordService.verifyDataType(testCase.getTestData().get(testStep.getParam1())); break; case VERIFYTEXT: if(testStep.getControlName()==null || testStep.getControlName().trim().equals("")) { if(testStep.getParam2()==null || testStep.getParam2().trim().equals("")) { ApiKeywordService.verifyText(RequestBase.responseParameters.get(testStep.getParam1()), testCase.getTestData().get(testStep.getParam1())); } else ApiKeywordService.verifyText(RequestBase.responseParameters.get(testStep.getParam2()), testCase.getTestData().get(testStep.getParam1())); } else { objectKeyValue = StringUtilities.splitObjectRepoValue(FrameworkConstants.ObjectRepository.get(testStep.getControlName())); if(ObjectLocator.getWebElement(objectKeyValue[0],objectKeyValue[1]).getText()==null || ObjectLocator.getWebElement(objectKeyValue[0],objectKeyValue[1]).getText().equals("")) { ApiKeywordService.verifyText(FrameworkConstants.SELENIUM_DRIVER.findElement(By.name("member(email)")).getAttribute("value").trim(), testCase.getTestData().get(testStep.getParam1())); } else ApiKeywordService.verifyText(ObjectLocator.getWebElement(objectKeyValue[0],objectKeyValue[1]).getText(), testCase.getTestData().get(testStep.getParam1())); } break; case VERIFYRESPONSETYPE: ApiKeywordService.verifyResponseContentType(requestBase,testCase.getTestData().get(testStep.getParam1())); break; case REQUEST_CONTENT: if(testCase.getTestData().get(testStep.getParam1()).contains("{")|| testCase.getTestData().get(testStep.getParam1()).contains("<")) { ApiKeywordService.setRequestMedia(requestDataList, testStep.getParam1(), testCase.getTestData().get(testStep.getParam1())); ApiNonKeywordService.identifyRequestContentType(testCase.getTestData().get(testStep.getParam1()), requestBase); } else ApiKeywordService.setRequestMediaFromFile(requestDataList, testStep.getParam1(), testCase.getTestData().get(testStep.getParam1()),requestBase); break; case OPENAPP: if(FrameworkConstants.SELENIUM_DRIVER==null) { Browser initiateWebDriver = new Browser(); initiateWebDriver.getWebDriver(); } FrameworkConstants.SELENIUM_DRIVER.get(testCase.getTestData().get(testStep.getParam1())); break; case INPUTTEXT: objectKeyValue = StringUtilities.splitObjectRepoValue(FrameworkConstants.ObjectRepository.get(testStep.getControlName())); InputLabel.enterText( ObjectLocator.getWebElement(objectKeyValue[0],objectKeyValue[1]), testCase.getTestData().get(testStep.getParam1())); break; case CLICK: objectKeyValue = StringUtilities.splitObjectRepoValue(FrameworkConstants.ObjectRepository.get(testStep.getControlName())); Click.click(ObjectLocator.getWebElement(objectKeyValue[0],objectKeyValue[1])); break; case SELECTFROMLIST: objectKeyValue = StringUtilities.splitObjectRepoValue(FrameworkConstants.ObjectRepository.get(testStep.getControlName())); ComboBox.selectFromDropDown(ObjectLocator.getWebElement(objectKeyValue[0],objectKeyValue[1]), testCase.getTestData().get(testStep.getParam1()),testCase.getTestData().get(testStep.getParam2())); break; case STORE: objectKeyValue = StringUtilities.splitObjectRepoValue(FrameworkConstants.ObjectRepository.get(testStep.getControlName())); if(ObjectLocator.getWebElement(objectKeyValue[0],objectKeyValue[1]).getText()==null || ObjectLocator.getWebElement(objectKeyValue[0],objectKeyValue[1]).getText().trim().equals("")) { testCase.setTestData(testStep.getParam1(), FrameworkConstants.SELENIUM_DRIVER.findElement(By.name("member(email)")).getAttribute("value").trim(),null); } else { testCase.setTestData(testStep.getParam1(), ObjectLocator.getWebElement(objectKeyValue[0],objectKeyValue[1]).getText().trim(),null); } break; case ALERTOK: FrameworkConstants.SELENIUM_DRIVER.switchTo().alert().accept(); break; case SELECTCHECKBOX: objectKeyValue = StringUtilities.splitObjectRepoValue(FrameworkConstants.ObjectRepository.get(testStep.getControlName())); CheckBox.selectDeSelectCheckBox(ObjectLocator.getWebElement(objectKeyValue[0],objectKeyValue[1]), true); break; case WAIT: TimeUnit.SECONDS.sleep(Integer.parseInt(testCase.getTestData().get(testStep.getParam1()))); break; case IFCLICK: objectKeyValue = StringUtilities.splitObjectRepoValue(FrameworkConstants.ObjectRepository.get(testStep.getControlName())); try { Click.click(ObjectLocator.getWebElement(objectKeyValue[0],objectKeyValue[1])); } catch(Exception E) { break; } break; default: break; } } }
C
UTF-8
335
3.25
3
[ "MIT" ]
permissive
#include <stdio.h> int zhishu(int a) {int i=2,s=0,n,m; while(i<a) {n=a%i; i=i+1; if(n==0) s=s+1;//䞍是莚数 else s=s;//是莚数 } if(s==0) m=0; //是莚数 else m=1; //䞍是莚数 return m; } int main() { int n,p=1; scanf("%d",&n); n=n+1; while(p!=0) {p=zhishu(n); n=n+1; } n=n-1; printf("%d",n); return 0; }
JavaScript
UTF-8
1,419
2.90625
3
[]
no_license
import { createTable } from "./table.js"; { const columns = [ { name: "date", valueFunc: (d) => d.slice(0, 10) }, { name: "name" }, { name: "points" }, { name: "bootcamp" }, { name: "energiser" }, { name: "category" }, ].map((o, i) => { o.headerFunc = (h) => h[0].toUpperCase() + h.slice(1); o.columnIndex = i; return o; }); const screen = document.querySelector("main.container"); const getSessions = async () => { const response = await fetch("/api/sessions"); const { payload: data } = await response.json(); screen.innerHTML = ""; screen.appendChild(createTable(data, columns)); }; // Add listener for search box. const input = document.querySelector("#search-by-energiser-name"); input.addEventListener("change", async (e) => { const partialEnergiserName = e.target.value.trim(); if (!partialEnergiserName) { // return; } screen.textContent = "Getting data, please wait..."; // It's inefficient to re-request the data each time from the server. // But can do it this way for now. const response = await fetch( `/api/sessions?energiser=${encodeURIComponent(partialEnergiserName)}` ); const { payload: data } = await response.json(); screen.innerHTML = ""; screen.appendChild(createTable(data, columns)); }); getSessions(); }
Java
UTF-8
661
3.375
3
[]
no_license
/** * * O(n^2) for all best, average and worst case, stable when using extra space * @author Tarun Gulati, tarun.gulati1988@gmail.com * */ package com.tarun.sort.selection; import java.util.Arrays; public class SelectionSort { private int numbers[]; private int size; public void sort( int[] arrayToSort ){ this.numbers = Arrays.copyOf( arrayToSort, arrayToSort.length ); int temp; for(int i = 0 ; i < numbers.length ; i++){ for(int j = i ; j < numbers.length ; j++){ if(numbers[i] > numbers[j]){ temp = numbers[j]; numbers[j] = numbers[i]; numbers[i] = temp; } } } /*for(int k : numbers){ System.out.print(" " + k); }*/ } }
C
UTF-8
2,020
3
3
[]
no_license
#include <stdio.h> #include <stdint.h> #include <stdbool.h> #include <stdlib.h> void cancelCatchException(void); void throwException(int); int catchException(void); #define INSUFFICIENT_MEMORY "malloc returned NULL in catchException\n" #define INVALID_EXCEPTION_NUMBER "throwException: Invalid exception number %d\n" #define UNHANDLED_EXCEPTION "unhandled exception %d\n" long saveRBP(); //long saveRIP(); long saveRBX(); long saveR12(); long saveR13(); long saveR14(); long saveR15(); //void setRBP(long); //void setRIP(long); void setRBX(long); void setR12(long); void setR13(long); void setR14(long); void setR15(long); void pareStack(long, int); static struct Snap *stack = 0; typedef struct Snap { long newRbp; long oldRbp; long rip; long rbx; long r12; long r13; long r14; long r15; struct Snap *next; } Snap; static struct Snap *stack; int catchException() { Snap *snap = malloc(sizeof(Snap)); if (snap == NULL){ fprintf(stderr, INSUFFICIENT_MEMORY); exit(-1); } snap->newRbp = saveRBP(); snap->oldRbp = *((long *)snap->newRbp); snap->rip = *(((long *)snap->newRbp) + 1); snap->rbx = saveRBX(); snap->r12 = saveR12(); snap->r13 = saveR13(); snap->r14 = saveR14(); snap->r15 = saveR15(); snap->next = stack; stack = snap; return 0; } void throwException(int exception) { if (stack == 0){ fprintf(stderr, UNHANDLED_EXCEPTION, exception); exit(-1); } if(exception<1){ fprintf(stderr, INVALID_EXCEPTION_NUMBER, exception); exit(-1); } Snap *snap = stack; stack = stack->next; *(long *)snap->newRbp = snap->oldRbp; *(((long *)snap->newRbp) + 1) = snap->rip; setRBX(snap->rbx); setR12(snap->r12); setR13(snap->r13); setR14(snap->r14); setR15(snap->r15); pareStack(snap->newRbp, exception); } void cancelCatchException() { if(stack !=0){ stack = stack->next; } } //
C++
UTF-8
223
3.484375
3
[]
no_license
// 參閱4-30頁 long fact(int n) { if (n == 0) return 1; else return n * fact(n - 1); } void setup() { Serial.begin(115200); long ans = fact(4); // 蚈算4的階局 Serial.print(ans); } void loop() {}
SQL
UTF-8
267
3.15625
3
[]
no_license
SELECT sen.name FROM SENSOR sen, SENSOR_TYPE st, COVERAGE_INFRASTRUCTURE ci WHERE sen.SENSOR_TYPE_ID=st.id AND st.name='Thermometer' AND sen.id=ci.SENSOR_ID AND ci.INFRASTRUCTURE_ID=ANY(array['2019','6213','1407','2221','6044','6019','4211','4202','4208','2232'])
Ruby
UTF-8
2,990
2.65625
3
[]
no_license
class Sighting < ActiveRecord::Base belongs_to :user # ALERT_MESSAGE = "Meter Maid is handing out TICKETS near by".freeze # def notify # @interest_locations = InterestLocation.all # @interest_locations.each do |interest_location| # dist = find_distance([self.latitude, self.longitude], [interest_location.latitude, interest_location.longitude]) # if interest_location.radius && interest_location.radius > dist # # send_message(interest_location.user.try(:phone_number), ALERT_MESSAGE) # send_message("+17049955069", ALERT_MESSAGE) # end # end # end def self.get_cordinates(arr) arr.map do |element| [element.latitude, element.longitude] end end def to_radians(degree) degree * Math::PI / 180 end def find_distance(last_post, user_settings) r = 6373 dlon = to_radians(user_settings[1] - last_post[1]) dlat = to_radians(user_settings[0] - last_post[0]) a = (Math.sin(dlat/2) * Math.sin(dlat/2)) + (Math.cos(to_radians(last_post[0])) * Math.cos(to_radians(user_settings[0])) * (Math.sin(dlon/2) * Math.sin(dlon/2))) c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)) d = r * c end def format_phone_number(arg) "+1" + arg.gsub(/[() -]/,"") end def send_email(array) puts "*********************************" array.each do |x| person = User.find(x) puts "Send an email to #{person.email}" end puts "USERS IS: #{array}" puts "*********************************" end # private # def send_message(phone_number, alert_message) # account_sid = ENV['TWILIO_ACCOUNT_SID'] # auth_token = ENV['TWILIO_AUTH_TOKEN'] # # set up a client to talk to the Twilio REST API # @client = Twilio::REST::Client.new account_sid, auth_token # @twilio_number = ENV['TWILIO_NUMBER'] # @client.account.messages.create({ # :from => @twilio_number, # :to => phone_number, # :body => alert_message # }); # end def alert_users(all_instances) user_ids = target_users([self.latitude, self.longitude], all_instances) send_sms(user_ids) end private def target_users(array1, all_instances) users = [] all_instances.each do |instance| distance = find_distance(array1, [instance.latitude, instance.longitude]) # 0.402 km equals 1/4 mile. # This will be the radius for now. # the circle on interest_locations map reflects that as it is set to 402 if distance < (0.402) users.push(instance.user_id) end end users.uniq end def send_sms(array) account_sid = ENV['TWILIO_API_KEY_SID'] auth_token = ENV['TWILIO_AUTH_TOKEN'] client = Twilio::REST::Client.new account_sid, auth_token from = "+13057056922" array.each do |user_id| recepient = User.find(user_id) if recepient.phone.length == 10 client.account.messages.create({ :from => from, :to => format_phone_number(recepient.phone), :body => "Hello from ParkNark. Ticket maid has been spotted near you. Happy Parking!" }) puts "Sent message to #{recepient.email}" end end end end
C#
UTF-8
10,235
2.59375
3
[]
no_license
using System; using System.Data; using System.Text; using System.Data.SqlClient; using ShowShop.IDAL.Product; using System.Collections.Generic; namespace ShowShop.SQLServerDAL.Product { public class Express:IExpress { #region "DataBase Operation" /// <summary> /// 增加䞀条数据 /// </summary> public int Add(ShowShop.Model.Product.Express model) { SqlParameter[] paras = (SqlParameter[])this.ValueParas(model); StringBuilder strSql = new StringBuilder(); strSql.Append("insert into yxs_express("); strSql.Append("name,fullname,address,phone,person,numstr,sort)"); strSql.Append(" values ("); strSql.Append("@name,@fullname,@address,@phone,@person,@numstr,@sort)"); strSql.Append(";select @@IDENTITY"); object obj = ChangeHope.DataBase.SQLServerHelper.GetSingle(strSql.ToString(), paras); if (obj == null) { return 0; } else { return Convert.ToInt32(obj); } } /// <summary> /// 曎新䞀条数据 /// </summary> public void Amend(ShowShop.Model.Product.Express model) { SqlParameter[] paras = (SqlParameter[])this.ValueParas(model); StringBuilder strSql = new StringBuilder(); strSql.Append("update yxs_express set "); strSql.Append("name=@name,"); strSql.Append("fullname=@fullname,"); strSql.Append("address=@address,"); strSql.Append("phone=@phone,"); strSql.Append("person=@person,"); strSql.Append("numstr=@numstr,"); strSql.Append("sort=@sort"); strSql.Append(" where id=@id "); ChangeHope.DataBase.SQLServerHelper.ExecuteSql(strSql.ToString(), paras); } /// <summary> /// 删陀䞀条数据 /// </summary> public void Delete(string id) { StringBuilder strSql = new StringBuilder(); strSql.Append("delete from yxs_express "); strSql.Append(" where [id] in (" + id + ") "); ChangeHope.DataBase.SQLServerHelper.ExecuteSql(strSql.ToString()); } /// <summary> /// 曎新䞀条数据 /// </summary> /// <param name="model"></param> /// <returns></returns> public int Amend(int id, string columnName, object value) { string sequel = "Update [yxs_express] set "; sequel = sequel + "[" + columnName + "] =@Value "; sequel = sequel + UpdateWhereSequel; SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@Value", value), new SqlParameter("@id", id) }; object obj = ChangeHope.DataBase.SQLServerHelper.GetSingle(sequel, paras); if (obj == null) { return 0; } else { return Convert.ToInt32(obj); } } #endregion #region "Data Load" /// <summary> /// 埗到䞀䞪对象实䜓 /// </summary> public ShowShop.Model.Product.Express GetModelByID(int id) { ShowShop.Model.Product.Express model = new ShowShop.Model.Product.Express(); StringBuilder strSql = new StringBuilder(); strSql.Append("select top 1 id,name,fullname,address,phone,person,numstr,sort from yxs_express "); strSql.Append(" where [id]=@id "); SqlParameter[] parameters = (SqlParameter[])this.ValueIDPara(id); using (SqlDataReader reader = ChangeHope.DataBase.SQLServerHelper.ExecuteReader(strSql.ToString(), parameters)) { if (reader.Read()) { model.ID = reader.GetInt32(0); model.Name = reader.GetString(1); model.FullName = reader.GetString(2); model.Address = reader.GetString(3); model.Person = reader.GetString(4); model.Phone = reader.GetString(5); model.Numstr = reader.GetString(6); model.Sort = reader.GetInt32(7); } } return model; } /// <summary> /// 所有数据集合 /// </summary> /// <returns></returns> public List<ShowShop.Model.Product.Express> GetAll() { List<ShowShop.Model.Product.Express> list = new List<ShowShop.Model.Product.Express>(); StringBuilder strSql = new StringBuilder(); strSql.Append("select id,name,fullname,address,phone,person,numstr,sort from yxs_express "); strSql.Append(" where 1=1"); strSql.Append(" order by sort asc"); using (SqlDataReader reader = ChangeHope.DataBase.SQLServerHelper.ExecuteReader(strSql.ToString())) { while (reader.Read()) { ShowShop.Model.Product.Express model = new ShowShop.Model.Product.Express(); model.ID = reader.GetInt32(0); model.Name = reader.GetString(1); model.FullName = reader.GetString(2); model.Address = reader.GetString(3); model.Person = reader.GetString(4); model.Phone = reader.GetString(5); model.Numstr = reader.GetString(6); model.Sort = reader.GetInt32(7); list.Add(model); } } return list; } /// <summary> /// 埗到指定条件的所有短消息 /// </summary> /// <param name="uid"></param> /// <returns></returns> public List<ShowShop.Model.Product.Express> GetAll(string strWhere) { List<ShowShop.Model.Product.Express> list = new List<ShowShop.Model.Product.Express>(); StringBuilder strSql = new StringBuilder(); strSql.Append("select id,name,fullname,address,phone,person,numstr,sort from yxs_express "); if (strWhere != null && strWhere != "") { strSql.Append("where " + strWhere + " "); } strSql.Append(" order by sort asc"); using (SqlDataReader reader = ChangeHope.DataBase.SQLServerHelper.ExecuteReader(strSql.ToString())) { while (reader.Read()) { ShowShop.Model.Product.Express model = new ShowShop.Model.Product.Express(); model.ID = reader.GetInt32(0); model.Name = reader.GetString(1); model.FullName = reader.GetString(2); model.Address = reader.GetString(3); model.Person = reader.GetString(4); model.Phone = reader.GetString(5); model.Numstr = reader.GetString(6); model.Sort = reader.GetInt32(7); list.Add(model); } } return list; } /// <summary> /// 埗到䞍同条件埗到列衚 /// </summary> /// <param name="strWhere"></param> /// <returns></returns> public ChangeHope.DataBase.DataByPage GetList(string strWhere) { ChangeHope.DataBase.DataByPage dataPage = new ChangeHope.DataBase.DataByPage(); dataPage.Sql = "[select] * [from] yxs_express [where] " + strWhere + " [order by] sort asc"; dataPage.GetRecordSetByPage(); return dataPage; } /// <summary> /// 分页列衚 /// </summary> /// <returns></returns> public ChangeHope.DataBase.DataByPage GetList() { ChangeHope.DataBase.DataByPage dataPage = new ChangeHope.DataBase.DataByPage(); dataPage.Sql = "[select] * [from] yxs_express [where] 1=1 [order by] sort asc"; dataPage.GetRecordSetByPage(); return dataPage; } #endregion #region "Other function" /// <summary> /// 曎新条件 /// </summary> protected string UpdateWhereSequel { get { return " Where [id] = @id"; } } /// <summary> /// 该数据访问对象的属性倌装蜜到数据库曎新参数数组 /// </summary> /// <remarks></remarks> public IDbDataParameter[] ValueParas(ShowShop.Model.Product.Express model) { SqlParameter[] paras = new SqlParameter[8]; paras[0] = new SqlParameter("@id", SqlDbType.Int, 4); paras[0].Value = model.ID; paras[1] = new SqlParameter("@name", SqlDbType.NVarChar, 20); paras[1].Value = model.Name; paras[2] = new SqlParameter("@fullname", SqlDbType.VarChar, 50); paras[2].Value = model.FullName; paras[3] = new SqlParameter("@address", SqlDbType.VarChar, 200); paras[3].Value = model.Address; paras[4] = new SqlParameter("@phone", SqlDbType.VarChar, 15); paras[4].Value = model.Phone; paras[5] = new SqlParameter("@person", SqlDbType.VarChar, 20); paras[5].Value = model.Person; paras[6] = new SqlParameter("@numstr", SqlDbType.VarChar, 200); paras[6].Value = model.Numstr; paras[7] = new SqlParameter("@sort", SqlDbType.Int,4); paras[7].Value = model.Sort; return paras; } /// <summary> /// 䞻键参数 /// </summary> /// <param name="id"></param> /// <returns></returns> public IDbDataParameter[] ValueIDPara(int id) { SqlParameter[] paras = new SqlParameter[1]; paras[0] = new SqlParameter("@id", id); paras[0].DbType = DbType.Int32; return paras; } #endregion } }
Java
UTF-8
1,092
1.914063
2
[ "LicenseRef-scancode-warranty-disclaimer", "ANTLR-PD", "CDDL-1.0", "bzip2-1.0.6", "Zlib", "BSD-3-Clause", "MIT", "EPL-1.0", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-jdbm-1.00", "Apache-2.0" ]
permissive
package com.sequenceiq.cloudbreak.converter.v4.stacks.cluster.filesystem; import org.springframework.stereotype.Component; import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.base.parameter.storage.AdlsCloudStorageV4Parameters; import com.sequenceiq.cloudbreak.converter.AbstractConversionServiceAwareConverter; import com.sequenceiq.cloudbreak.common.type.filesystem.AdlsFileSystem; @Component public class AdlsFileSystemToAdlsCloudStorageParametersV4Converter extends AbstractConversionServiceAwareConverter<AdlsFileSystem, AdlsCloudStorageV4Parameters> { @Override public AdlsCloudStorageV4Parameters convert(AdlsFileSystem source) { AdlsCloudStorageV4Parameters fileSystemConfigurations = new AdlsCloudStorageV4Parameters(); fileSystemConfigurations.setClientId(source.getClientId()); fileSystemConfigurations.setAccountName(source.getAccountName()); fileSystemConfigurations.setCredential(source.getCredential()); fileSystemConfigurations.setTenantId(source.getTenantId()); return fileSystemConfigurations; } }
Markdown
UTF-8
674
2.640625
3
[]
no_license
# Article L624-18 Peut être revendiqué le prix ou la partie du prix des biens visés à l'article L. 624-16 qui n'a été ni payé, ni réglé en valeur, ni compensé entre le débiteur et l'acheteur à la date du jugement ouvrant la procédure. Peut être revendiquée dans les mêmes conditions l'indemnité d'assurance subrogée au bien. **Liens relatifs à cet article** **Cité par**: - Décret n°2005-1677 du 28 décembre 2005 - art. 115 (Ab) - Code de commerce - art. R641-31 (V) - Code de commerce. - art. R624-16 (V) **Modifié par**: - Ordonnance n°2008-1345 du 18 décembre 2008 - art. 44 **Cite**: - Code de commerce - art. L624-16
PHP
UTF-8
13,544
2.59375
3
[]
no_license
<?php class Users extends Model { public function __construct($app) { parent::__construct($app); } public function getHome() { $us = $this->app->db->prepare("SELECT u.*, u.id AS id_users, ul.city, img.url FROM users u LEFT JOIN usersLocation ul ON u.id = ul.id_users LEFT JOIN usersImage img ON img.id_users = u.id AND img.isprofil = 1 WHERE u.gender = 'f' ORDER BY u.popularity DESC LIMIT 8"); $us->execute(); return $us->fetchAll(); } public function updatedLogin($id) { $date = date("d/m/Y H:i:s"); $us = $this->app->db->prepare("UPDATE users SET last_seen = ?, isConnected = ? WHERE id = ?"); $us->execute(array($date, 1, $id)); } public function setSaltForget($id) { $salt = uniqid(); $this->update($id, array('salt' => $salt)); return $salt; } public function getLocationById($id) { $loca = $this->app->db->prepare("SELECT * FROM usersLocation WHERE id_users = ?"); $loca->execute(array($id)); return $loca->fetch(); } public function getAllUser() { $pdo = $this->app->db->prepare("SELECT u.*, ui.url, ul.city, ul.longitude, ul.latitude FROM users u INNER JOIN usersImage ui ON ui.id_users = u.id AND ui.isprofil = 1 INNER JOIN usersLocation ul ON ul.id_users = u.id"); $pdo->execute(); return $pdo->fetchAll(); } public function checkPass($id, $old, $pass1, $pass2) { $user = $this->getUsers($id); if(hash('whirlpool', $old) != $user['passwd']) return -1; else if ($pass1 != $pass2) return -2; else $this->update($id, array('passwd' => hash('whirlpool', $pass1))); return 1; } public function changePass($id, $salt, $pass) { $user = $this->getUsers($id); if ($user['salt'] == $salt) { $this->update($id, array('passwd' => hash('whirlpool', $pass), 'salt' => uniqid())); return true; } return false; } public function isGoodSalt($mail, $salt) { $sal = $this->app->db->prepare("SELECT * FROM users WHERE salt = :salt AND mail = :mail"); $sal->execute(array('salt' => $salt, 'mail' => $mail)); if (empty($sal->fetch())) return false; return true; } public function setDisconnected($id) { $date = date("d/m/Y H:i:s"); $us = $this->app->db->prepare("UPDATE users SET last_seen = ?, isConnected = ? WHERE id = ?"); $us->execute(array($date, 0, $id)); } public function checkLog($val) { $pdo = $this->app->db->prepare("SELECT * FROM users WHERE mail = ? AND passwd = ?"); $pdo->execute(array($val['mail'], hash('whirlpool', $val['passwd']))); $us = $pdo->fetch(); if (empty($us)) return false; return $us; } public function getInterest($id) { $pdo = $this->app->db->prepare("SELECT * FROM users u INNER JOIN users_usersInterest uui ON uui.id_users = u.id INNER JOIN usersInterest ui ON uui.id_interest = ui.id WHERE u.id = ? "); $pdo->execute(array($id)); return $pdo->fetchAll(); } public function getUsers($id) { $pdo = $this->app->db->prepare("SELECT * FROM users u INNER JOIN usersLocation ul ON ul.id_users = u.id WHERE u.id = ?"); $pdo->execute(array($id)); return $pdo->fetch(); } public function getUsersByDate() { $date = new DateTime('-7 days'); $date = $date->format('d/m/Y'); $pdo = $this->app->db->prepare("SELECT SUBSTRING(created_at, 1, 10) as date, count(SUBSTRING(created_at, 1, 10)) as cpt FROM `users` WHERE created_at >= ? group by date"); $pdo->execute(array($date)); return $pdo->fetchAll(); } public function getAllUsers() { $user = $this->app->db->prepare("SELECT u.*, url, count(r.id_users_reported) as cptRe FROM users u LEFT JOIN usersImage ui ON u.id=ui.id_users AND ui.isprofil = 1 LEFT JOIN reported r ON r.id_users_reported = u.id AND r.id is not NULL GROUP by r.id_users_reported, IF(r.id_users_reported IS NULL, u.id, 0) "); $user->execute(); return $user->fetchAll(); } public function getStringInterest($id) { $pdo = $this->app->db->prepare("SELECT ui.interest FROM users u INNER JOIN users_usersInterest uui ON uui.id_users = u.id INNER JOIN usersInterest ui ON uui.id_interest = ui.id WHERE u.id = ? "); $pdo->execute(array($id)); foreach ($pdo->fetchAll() as $k => $v) $arr[] = $v['interest']; if (empty($arr)) return false; return implode(',', $arr); } public function deleteInfo($id) { $pdo = $this->app->db->prepare("DELETE FROM usersImage WHERE id_users = ?"); $pdo->execute(array($id)); $pdo = $this->app->db->prepare("DELETE FROM users_usersInterest WHERE id_users = ?"); $pdo->execute(array($id)); $pdo = $this->app->db->prepare("DELETE FROM usersLocation WHERE id_users = ?"); $pdo->execute(array($id)); $pdo = $this->app->db->prepare("DELETE FROM notification WHERE id_users = ? OR id_users_send = ?"); $pdo->execute(array($id, $id)); $pdo = $this->app->db->prepare("DELETE FROM likable WHERE id_users = ? OR id_users_like = ?"); $pdo->execute(array($id, $id)); $pdo = $this->app->db->prepare("DELETE FROM chat WHERE id_auteur = ? OR id_receiver = ?"); $pdo->execute(array($id, $id)); $pdo = $this->app->db->prepare("DELETE FROM history WHERE id_users = ? OR id_users_visited = ?"); $pdo->execute(array($id, $id)); $pdo = $this->app->db->prepare("DELETE FROM usersblocked WHERE id_users = ? OR id_users_block = ?"); $pdo->execute(array($id, $id)); $pdo = $this->app->db->prepare("DELETE FROM reported WHERE id_users = ? OR id_users_reported = ?"); $pdo->execute(array($id, $id)); $pdo = $this->app->db->prepare("DELETE FROM users WHERE id = ?"); $pdo->execute(array($id)); } public function getCountImage($id) { $pdo = $this->app->db->prepare("SELECT ui.url FROM users u INNER JOIN usersImage ui ON u.id = ui.id_users WHERE u.id = ? "); $pdo->execute(array($id)); return count($pdo->fetchAll()); } public function getImage($id) { $pdo = $this->app->db->prepare("SELECT ui.id, ui.url, ui.isprofil FROM users u INNER JOIN usersImage ui ON u.id = ui.id_users WHERE u.id = ? "); $pdo->execute(array($id)); return $pdo->fetchAll(); } public function isNotLoca($id) { $pdo = $this->app->db->prepare("SELECT * FROM usersLocation WHERE id_users = ?"); $pdo->execute(array($id)); return $pdo->fetch(); } public function getStatuts($id, $idUser) { if ($id == $idUser) return -1; $like = $this->app->db->prepare("SELECT * FROM likable WHERE (id_users = ? AND id_users_like = ?) OR (id_users = ? AND id_users_like = ?)"); $like->execute(array($idUser, $id, $id, $idUser)); if (count($like->fetchAll()) == 2) { return 2; } $like = $this->app->db->prepare("SELECT * FROM likable WHERE id_users = ? AND id_users_like = ?"); $like->execute(array($id, $idUser)); if (count($like->fetchAll()) == 1) { return 1; } return 0; } public function getImageProfil($id) { $pdo = $this->app->db->prepare("SELECT ui.url FROM users u INNER JOIN usersImage ui ON u.id = ui.id_users WHERE u.id = ? AND ui.isprofil = 1"); $pdo->execute(array($id)); return $pdo->fetch(); } public function getCity($id) { $pdo = $this->app->db->prepare("SELECT l.city FROM users u INNER JOIN usersLocation l ON l.id_users = u.id WHERE u.id = ?"); $pdo->execute(array($id)); return $pdo->fetch(); } /* * SUGGESTION */ public function isCompatible($user, $user2) { if ($user['orientation'] == "hetero") { if (($user['gender'] == $user2['gender']) || ($user['gender'] != $user2['gender'] && $user2['orientation'] == "homosexuel")) return false; } else if ($user['orientation'] == "homosexuel") { if ($user['gender'] != $user2['gender'] || ($user['gender'] == $user2['gender'] && $user2['orientation'] == "hetero")) return false; } else if ($user['orientation'] == "bisexuel") { if ($user['gender'] == $user2['gender'] && $user2['orientation'] == "hetero") return false; if ($user['gender'] != $user2['gender'] && $user2['orientation'] == "homosexuel") return false; } return true; } public function removeOrientation($listUsers, $users) { foreach ($listUsers as $key => $value) { if (!$this->isCompatible($users, $value)) { unset($listUsers[$key]); } } return $listUsers; } public function addInteretList($listUser) { foreach ($listUser as $key => $value) { $listUser[$key]['interestString'] = $this->getStringInterest($value['id_users']); } return $listUser; } public function findSuggest($id) { $pdo = $this->app->db; $block = new usersBlocked($this->app); $block = $block->getListBlock($id); $users = $this->getUsers($id); $orientation = $users['orientation']; $gender = $users['gender']; $lat = $users['latitude']; $long = $users['longitude']; $sql = "SELECT u.*, u.id AS id_users, ul.city, img.url, (ABS($ong - ul.longitude) + ABS($lat - ul.latitude)) AS distance,ul.latitude, ul.longitude, COUNT(up.id_interest) as commonInterest FROM users u LEFT JOIN users_usersInterest ui ON ui.id_users = u.id LEFT JOIN (SELECT id_interest FROM `users_usersInterest` WHERE id_users = $id) up on up.id_interest = ui.id_interest LEFT JOIN usersLocation ul ON ul.id_users = u.id LEFT JOIN usersImage img ON img.id_users = u.id AND img.isprofil = 1 WHERE u.gender LIKE (CASE '$gender' WHEN 'f' THEN ( CASE '$orientation' WHEN 'hetero' THEN 'm' WHEN 'homosexuel' THEN 'f' ELSE '%%' END) WHEN '$gender' THEN ( CASE '$orientation' WHEN 'hetero' THEN 'f' WHEN 'homosexuel' THEN 'm' ELSE '%%' END) END) AND u.id <> $id AND u.id NOT IN($block) GROUP BY u.id, ui.id_users, distance, img.id, ul.city ORDER BY distance ASC, commonInterest DESC, u.popularity DESC"; $usersL = $pdo->prepare($sql); $usersL->execute(); $listUsers = $usersL->fetchAll(); $listUsers = $this->removeOrientation($listUsers, $users); $listUsers = $this->addInteretList($listUsers); return $listUsers; } public function findSearch($string, $id) { $pdo = $this->app->db; $usersL = $pdo->prepare("SELECT u.*, u.id AS id_users, ul.city, img.url, COUNT(up.id_interest) as commonInterest FROM users u LEFT JOIN users_usersInterest ui ON ui.id_users = u.id LEFT JOIN (SELECT id_interest FROM `users_usersInterest` WHERE id_users = $id) up on up.id_interest = ui.id_interest LEFT JOIN usersLocation ul ON ul.id_users = u.id LEFT JOIN usersImage img ON img.id_users = u.id AND img.isprofil = 1 WHERE (u.nickname LIKE :terms OR u.name LIKE :terms OR u.lastname LIKE :terms) AND u.id != $id GROUP BY u.id, ui.id_users,img.id, ul.city"); $usersL->execute(array('terms' => '%' . $string . '%')); $usersL = $usersL->fetchAll(); $usersL = $this->addInteretList($usersL); return $usersL; } public function updatedLocation($id) { } public function getUsersByGender() { $pdo = $this->app->db->prepare("select count(case when gender='f' then 1 end) as malCpt, count(case when gender='m' then 1 end) as femCpt, count(*) as total_cnt from users"); $pdo->execute(); return $pdo->fetch(); } public function getUsersByOrien() { $pdo = $this->app->db->prepare("SELECT count(CASE WHEN orientation='bisexuel' then 1 end) as bi, count(CASE WHEN orientation='hetero' then 1 end) as he, count(CASE WHEN orientation='homosexuel' then 1 end) as ho FROM users"); $pdo->execute(); return $pdo->fetch(); } } ?>
Java
UTF-8
488
2.3125
2
[]
no_license
package test; import main.Application; import org.junit.Assert; import org.junit.Test; import java.util.List; /** * This test case verify the result when the sublist size is bigger then the origin list size * * @author Mouad Tahiri */ public class TestSizeParameter { @Test public void should_return_the_same_list_in_the_input() { List<List<?>> result= Application.partition(Application.list, 9); Assert.assertEquals(result.get(0),Application.list); } }
Markdown
UTF-8
1,443
2.59375
3
[]
no_license
### BeeGFS Tips The BeeGFS storage is spread across 3 nodes with SSD disks. The aggregate storage is 100TB. We don't enforce quotas here as some projects have large storage needs. However, you do need to be a good HPC citizen and respect the rights of others. Don't needlessly fill up this storage. We regularly **delete all data** here every 3-6 months. We only post warnings on the [slack channel](uwrc.slack.com/). If afteer 3 months the storage is not full and still performning well, we delay the wipe another 3 months. This storage is **not backed up** at all. It is on a raid array so if a hard drive fails your data is safe. However in the event of a more dramatic hardware failure, earthquakes or fire - your data is gone forever. If you accidentally delete something, it's gone forever. If an Admin misconfigures something, your data is gone (we try not to do this!). It is **your responsiblilty to backup your data** here - a good place is to use Digital Solutions Research Storage. BeeGFS should have better IO performance than the scratch storage - however it does depend what other users are doing. No filesystem likes small files, BeeGFS likes small files even less than scratch. Filesizes over 1MB are best. If you have a large amount of files you can improve performance by splitting your files accross many directories - the load balancing accross the metadata and storage servers is by directory, not file.
Java
UTF-8
1,291
2.765625
3
[]
no_license
package com.rhwayfun.sso.common; import java.net.URLEncoder; import java.util.UUID; /** * Created by rhwayfun on 16-3-23. */ public class StringUtil { private StringUtil(){} /** * 根据参数拌接url * @param originUrl * @param parameterName * @param parameterValue * @return * @throws Exception */ public static String appendUrlParameter(String originUrl,String parameterName,String parameterValue) throws Exception{ if (originUrl == null) return null; //刀断原来的url䞭是吊有连接笊 String bound = originUrl.contains("?") ? "&" : "?"; return originUrl + bound + parameterName + "=" + URLEncoder.encode(parameterValue,"utf-8"); } /** * 生成32䜍长床的随机字笊䞲䜜䞺key * @return * @throws Exception */ public static String uniqueKey() throws Exception{ return UUID.randomUUID().toString().replace("-","").toLowerCase(); } /** * 刀断字笊䞲是吊䞺空 * @param excludes * @return */ public static boolean isEmpty(String excludes) { if (excludes == null){ return true; } if (excludes.length() == 0){ return true; } return false; } }
JavaScript
UTF-8
2,189
4
4
[]
no_license
//a // const addTheWordCool = ["nice", "awesome", "geweldig"]; // //addTheWordCool.push("cool"); // console.log(addTheWordCool.push("cool")) const addTheWordCool = function (array) { array.push("cool"); return array; }; console.log("Add cool: " + addTheWordCool(["nice", "awesome", "geweldig"])); //b // const amountOfElementsInArray = ["appels", "peren", "citroenen"]; // console.log(amountOfElementsInArray.length); const amountOfElementsInArray = function (array) { return array.length; } console.log(amountOfElementsInArray(["appels", "peren", "citroenen"])); //c // const selectBelgiumFromBenelux = ["Belgie", "Nederland", "Luxemburg"]; // console.log(selectBelgiumFromBenelux[0]); const selectBelgiumFromBenelux = function (array) { return array[0]; } console.log(selectBelgiumFromBenelux(["Belgie", "Nederland", "Luxemburg"])); //d //const lastElementInArray = ["Haas", "Cavia", "Kip", "Schildpad"]; //console.log(lastElementInArray[lastElementInArray.length - 1]); const lastElementInArray = function (array) { return array[array.length - 1]; } console.log(lastElementInArray(["Haas", "Cavia", "Kip", "Schildpad"])); //e const presidents = ["Trump", "Obama", "Bush", "Clinton"]; const impeachTrumpSlice = function (array) { //zoals je hieronder ziet muteert .slice methode niet de bestaande array, maar retourneert een nieuwe die we opslaan in een nieuwe variabele/ const newArray = array.slice(1, 4); console.log("Nieuwe array: ", newArray, "De onaangetaste array", array); return newArray; }; const impeachTrumpSplice = function (array) { const removedElement = array.splice(0, 1); console.log( "removed element:", removedElement, "De mutated array, Trump is missing:", array ); return array; }; console.log(impeachTrumpSlice(presidents)); console.log(impeachTrumpSplice(presidents)); //f const stringsTogether = function (array) { return array.join(" "); }; console.log(stringsTogether(["Winc", "Academy", "is", "leuk", ";-}"])); //g const combineArrays = function (array1, array2) { return array1.concat(array2); }; console.log(combineArrays([1, 2, 3], [4, 5, 6]));
Markdown
UTF-8
16,972
2.921875
3
[ "MIT" ]
permissive
# チヌム開発の準備 チヌム開発に向けたGitの機胜を緎習したす。 ## ブランチ Gitはオヌプン゜ヌスプロゞェクトの開発を想定したツヌルです。リポゞトリヌを公開しお、垞に誰からアクセスされおも構わないようにしおおくのが基本です。 開発途䞭で䜜業時間が終わった堎合に、そのたたコミットずプッシュをするず、゚ラヌがでるような状態のプロゞェクトになっおしたいたす。これだずそのプロゞェクトを䜿っおみたい人にずっおは䞍䟿です。かずいっお、゚ラヌがでない状態になるたでプッシュができないずいうのも䞍䟿です。 そこで、バヌゞョン管理システムには**ブランチ**ずいうものが甚意されおいたす。日本語で **枝** のこずで、リポゞトリヌを枝分かれさせお、耇数の状態を同時に保存できるようにするものです。 最初に割り圓おられる**main** (以前は **master** )ブランチは、垞に動䜜可胜な状態にしおおくのが䞀般的です。開発をする時にはmainから開発甚のブランチを䜜成しお、その開発甚のブランチにコミットやプッシュをしたす。ブランチは独立しおいるのでmainブランチは動䜜する状態が維持されたす。 開発が䞀段萜しお問題なく動䜜するようになったら、開発甚ブランチをmainブランチに **マヌゞ(=merge 結合)** したす。これでmainブランチは垞に動䜜する状態に保぀こずができたす。開発を続行する時は、先の開発甚ブランチで再び䜜業をするか、新しい開発甚のブランチを䜜成しお䜜業したす。 理解を深めるために、実際に操䜜をしおみたしょう。 ### ブランチを䜜る 開発甚のブランチ`dev`を䜜成しおみたす。ブランチを切り替える操䜜をする際には、以䞋の2点に泚意しおください。 - ブランチの操䜜をする前に、倉曎䞭のファむルを0にしたす - ブランチの切り替え操䜜䞭は、Unityに切り替えないでください ![Changes](./images/img01.png) 倉曎䞭のファむルがある状態でブランチを切り替えるず状態の把握が難しくなりたす。䜜業䞭のファむルならコミット、倉曎を砎棄しお構わないならDiscardをしたしょう。 ここでは䜕も倉曎をしおいないはずなので、ChangesにファむルがあったらDiscard Allで倉曎を戻しおおいおください。 1. GitHub Desktopに切り替えお、Current branchをクリック > Filter 欄に`dev`ず入力 > Create New branch ボタンを抌したす ![ブランチ名の入力](./images/img02.png) 2. 続けお Create branch ボタンを抌したす これで開発甚のブランチ`dev`ができたした。少し倉曎を加えおみたす。 1. Unityに切り替えお、Projectりィンドりから GP2Sandbox > Scenes フォルダヌを開いお、 System シヌンをダブルクリックしお開きたす 1. Hierarchyりィンドりの + をクリックしお、3D Object > Sphereを遞んで球䜓を䜜りたす 1. Fileメニュヌから Save を遞択しお保存したす 1. GitHub Desktopに切り替えお、Summary欄に`Sphereを䜜成`などず入力しおコミットしたす ![球䜓の䜜成ずコミット](./images/img03.png) 以䞊でdevブランチに倉曎を加えおコミットしたした。それではmainブランチに切り替えおみたす。 1. GitHub DesktopのCurrent branchをクリックしお main を遞択したす ![mainブランチぞ](./images/img04.png) 2. Unityに切り替えおReloadをクリックしたす mainブランチはdevブランチを䜜成した時点の状態のたたなので、先ほど䜜成したSphereがなくなっお元の状態に戻ったこずが確認できたす。 ![Sphereが無くなっお元に戻っおいる](./images/img05.png) 同様の操䜜でdevブランチに戻しおみたしょう。 1. GitHub DesktopのCurrent branchをクリックしお dev を遞択したす 1. Unityに切り替えお、Reloadをクリックしたす Sphereが埩掻したす。 ![devに戻す](./images/img06.png) このようにブランチを利甚するず、プロゞェクトの様々な状態を同時に保存するこずができたす。**ファむルを倉曎したたたブランチを切り替えない限り**、マヌゞするたでは他のブランチを砎壊するこずはありたせん。 この性質を利甚しお、垞にリポゞトリヌのmainブランチを実行可胜な状態に保ったり、耇数のメンバヌが別々にプロゞェクトの開発を進めるこずができたす。 ## マヌゞ 開発が䞀段萜しお動䜜可胜な状態になったら、開発ブランチで行った䜜業をmainブランチに結合したす。これを **マヌゞ(Merge)** ず呌びたす。 devで远加したSphereを、mainブランチにも反映させおみたす。マヌゞは **マヌゞ先のブランチに切り替えお、マヌゞ元のブランチを指定** したす。 1. GitHub DesktopのCurrent branchを、**マヌゞ先**であるmainに切り替えたす 1. ブランチの切り替えが完了したら、Unityを遞択しおReloadしお倉曎を反映させたす 1. GitHub Desktopに切り替えお、Current branchをクリックしお、䞀番䞋の Choose a branch to merge into main をクリックしたす ![マヌゞ開始](./images/img07.png) 4. マヌゞ元のdevブランチをクリックしお遞択しお、 Merge dev into main をクリックしたす ![マヌゞ元のブランチの指定](./images/img08.png) 以䞊でマヌゞ完了です。Unityに切り替えおReloadをしおください。mainブランチにもSphereが远加されたす。Push origin すればGitHubにも曎新が反映したす。 䞀人で開発するなら、以䞊でmainを動䜜する状態に保ったたた開発が進められたす。 ## 簡易的なチヌム開発 ブランチの䜜成方法ずマヌゞの仕方が分かりたした。チヌムメンバヌを共同開発者にしお、メンバヌそれぞれが自分の䜜業甚のブランチを䜜っお、そこで䜜業しお、mainブランチにマヌゞをすれば共同開発ができそうです。詊しおみたしょう。 ### シナリオ 以䞋のようなシナリオを考えたす。 - AさんずBさんが同時に開発したす - Aさんは`dev`、Bさんは`devB`ブランチで䜜業をしたす - Aさんは、SphereをGameシヌンに移しお、配眮する䜜業を担圓したす - Bさんは、GameシヌンにCubeを䜜成しお、配眮する䜜業を担圓したす AさんずBさんの䞡圹になっお䜜業を進めおみたしょう。 ### 䜜業手順 䜜業を開始する前にBさん甚のブランチBを䜜成したす。 1. GitHub Desktopで main ブランチに切り替えたす 1. `dev`ブランチを䜜成したのず同様の手順で、`devB`ブランチを䜜成したす AさんずBさんが同じ状態から䜜業を開始する環境が敎いたした。たずはAさんの䜜業をしたす。 1. GitHub Desktopでdevブランチに切り替えたす 1. Unityに切り替えたす 1. Projectりィンドりの GP2Sandbox/Scenes フォルダヌから Game シヌンをHierarchyりィンドりにドラッグ&ドロップしたす 1. Hierarchyりィンドりで、Systemシヌンに䜜成したSphereをドラッグしお、Gameシヌンに移動したす ![SphereをGameシヌンぞ](./images/img09.png) 5. SphereをX=`2`, Y=`0`, Z=`2` あたりに移動したす(実際はどこでもいいです) ![Sphereを配眮](./images/img10.png) 6. FileメニュヌからSaveでシヌンを保存したす 1. GitHub Desktopに切り替えたす 1. Summaryに`Sphereを配眮`など入力しおコミットしたす ![Aさんの䜜業をコミット](./images/img11.png) 以䞊でAさんの担圓䜜業は完了です。ただマヌゞはしないでください。 次にBさん圹になっお䜜業を進めたす。 1. GitHub DesktopでdevBブランチに切り替えたす 1. Unityに切り替えお Reload 1. Hierarchyりィンドりの + をクリックしお 3D Object > Cubeを遞択しお Cube を生成したす 1. 先ほどのSphereの操䜜ず同様に、䜜成したCubeをドラッグしおGameシヌンでドロップしおGameシヌンぞ移動したす 1. CubeをX=`-2`, Y=`0`, Z=`-2`あたりに移動させおみたす ![Cubeを配眮](./images/img12.png) 6. FileメニュヌからSaveでシヌンを保存したす 以䞊で䜜業完了です。コミットしおおきたす。 7. GitHub Desktopに切り替えたす 1. Summaryに`Cubeを配眮`など入力しおコミットしたす 以䞊でAずB䞡者の䜜業が完了したした。mainにマヌゞしたす。 1. GitHub DesktopのCurrent branchを、**マヌゞ先**であるmainに切り替えたす 1. Current branchをクリックしお、䞀番䞋の Choose a branch to merge into main をクリックしたす ![マヌゞ開始](./images/img07.png) 3. マヌゞ元のdevブランチをクリックしお遞択しお、 Merge dev into main をクリックしたす ![マヌゞ元のブランチの指定](./images/img08.png) Unityに切り替えおReloadをしお、mainブランチにAさんの䜜業が反映されたこずを確認したす。続けおBさんの䜜業をマヌゞしたす。 4. GitHub Desktopに切り替えお、Current branchをクリックしお、䞀番䞋の Choose a branch to merge into main をクリックしたす 1. マヌゞ元のdevBブランチをクリックしお遞択しお、 Merge dev into main をクリックしたす 1. マヌゞが完了したら、Unityに切り替えおReloadしたす 以䞊で、䞡者の䜜業が結合できたした。毎回このようにスムヌズに進めばいいのですが、耇数メンバヌでルヌルを決めずにそれぞれが自由に開発するずマヌゞの時点で問題が起きるこずでしょう。 ## コンフリクト䜓隓 ではGitのハマりポむントである **コンフリクト(=Conflict 衝突)** を詊しおみたす。たずは`dev`ブランチず`devB`ブランチに`main`ブランチをマヌゞしお最新の状態に統䞀したす。 1. GitHub Desktopでdevブランチに切り替えたす 1. Current branchをクリックしお、Choose a branch to merge into dev をクリックしたす 1. mainを遞択しお、Merge main into dev をクリックしたす これでdevがmainず同じになりたした。devBも同様の手順でmainをマヌゞしおください。 それではコンフリクトを発生させたす。今はdevBブランチのはずなので、そこで以䞋の倉曎をしたす 1. Unityに切り替えたす 1. HierarchyりィンドりのSphereずCubeのX座暙を䞡方ずも`0`にしたす 1. FileメニュヌからSaveを遞択しお保存したす 1. `X座暙を0`などでコミットしたす ![devBのXを0に蚭定](./images/img13.png) 1. Current Branchをdevブランチに切り替えたす 1. Unityに切り替えおReloadしたす 1. HierarchyりィンドりのSphereのX座暙を`-2`、CubeのX座暙を`2`にしお巊右の堎所を入れ替えたす 1. FileメニュヌからSaveを遞択しお保存したす 1. GitHub Desktopに切り替えお`X座暙を反転`などでコミットしたす ![devのSphereずCubeのX䜍眮を反転](./images/img14.png) それでは先にやった手順でmainブランチに切り替えお、devずdevBブランチをmainにマヌゞしおみおください。`devB`ブランチをマヌゞしようずするず以䞋のような譊告が衚瀺されたす。 ![Conflictの譊告](./images/img17.png) これが **conflict** です。Merge devB into main をクリックしおマヌゞを詊したす。以䞋のようなダむアログが衚瀺されおマヌゞさせおくれたせん。 ![conflictの解決芁求](./images/img18.png) 赀い文字も出おいお危険な雰囲気です。そしお Commit merge が抌せないので無理やり先に進めるこずができたせん。これ以䞊はたずいず思ったら **Abort merge** を抌せばマヌゞをやめお匕き返すこずができたす。 今回のように同じ堎所が同時に倉曎されるず、どちらの曎新が正しいかを自動的に刀断するこずができたせん。プロゞェクトの責任者がどちらを採甚するかを決めるか、倉曎した圓人同士で話し合っおどちらの内容を残すか決めお、そのように線集する必芁がありたす。 ## コンフリクトの解決方法 チヌム制䜜では決めごずを守るこずでコンフリクトを避けるこずはできたす。しかし、Unityでは少しの油断でコンフリクトが起きる可胜性がありたす。たたもずもずオヌプン゜ヌスでは、誰が、い぀、どこを倉曎しおいるか分からないのでコンフリクトは垞に発生するこずが想定されたす。いざずいう時に備えお、コンフリクトの解決方法を知っおおきたしょう。先のりィンドりの続きから操䜜したす。 1. Open in Atomをクリックしたす ![Atomで開く](./images/img19.png) 2. Atom゚ディタヌで゜ヌスコヌドが開くので、スクロヌルをしお以䞋のように色が付いおいる郚分を探したす ![衝突箇所](./images/img20.png) コヌド内の`<<<<<<< HEAD`から`=======`たでの間の行が**マヌゞ先**、぀たり珟圚の手元のブランチの状態を衚したす。`========`から`>>>>>>> devB`の間の行が**マヌゞ元** なので **devB** ブランチの状態です。利甚したい方の**Use me**をクリックすればそちらの倉曎が採甚されたす。 今回はどちらが正解ずいうのはないので、ずりあえず倉曎元の倉曎である **their changes** の方を採甚しおみたしょう。 3. 青い郚分の巊の**Use me**をクリックしお、devBの方を採甚したす ![devBの倉曎を採甚する](./images/img21.png) 4. Ctrl + F キヌで怜玢ダむアログを出しお`=======`を怜玢したす 1. 衝突が芋぀かったら、再びどちらかの Use me をクリックしお衝突を解消 1. 怜玢を続けお、芋぀からなければこのファむルのコンフリクトは解決です。Ctrl + S キヌで保存したす 1. GitHub Desktopに切り替えたす 1. コンフリクトが党お解決されたらマヌゞが可胜になりたす。**Commit merge**をクリックしおマヌゞを実行したす ![コンフリクト解決](./images/img22.png) 以䞊でコンフリクト解決です。Unityに切り替えおReloadするず、devBで行った倉曎であるSphereずCubeのX座暙がどちらも0ずいう状態になりたす。 ![解決](./images/img13.png) ### 補足ファむルの差分衚蚘に぀いお `<<<<<<< HEAD`、`=======`、`>>>>>>> devB`ずいった蚘号でテキストファむルの差分を衚す方法はgit特有のものではなく、昔から䜿われおいるものです。専甚の゚ディタヌを䜿わなくおも、採甚する偎のコヌドだけ残しお䞍芁なコヌドず蚘号を削陀すれば**メモ垳のようなテキスト゚ディタヌでもコンフリクトの解決は可胜**です。 ## コンフリクトを避けるには コンフリクトの解決は手間がかかりたすし、Unityでは解消が難しくなるこずもあるので、決たったメンバヌで開発するのであればルヌルを決めおコンフリクトを避けるのが埗策です。以䞋にルヌルを挙げたす。 - mainブランチはマヌゞ専甚にしお、䜜業は開発甚のブランチを䜜成しおそこで行う - マヌゞの担圓者を決めお、他のメンバヌはマヌゞをしないようにしお、同時にマヌゞするこずによる衝突を避ける - シヌンやプレハブは䜜業担圓者を決めお、その担圓者のみが線集する - 䜜業をたずめるためのゲヌムオブゞェクトを䜜成しお、デヌタを受け枡すずきはそのゲヌムオブゞェクトをPrefabにしお、それを゚クスポヌトする - 他のメンバヌが担圓しおいるシヌンやプレハブ、ScriptableObject䞊で䜜業する必芁がある堎合は、それらを耇補したもので䜜業をする 以䞊を**チヌム党員で守れる堎合に限り**、Gitでのチヌム開発を行っおください。コンフリクトを解消できそうなメンバヌがいなかったり、䞊蚘の操䜜が難しいメンバヌがいる堎合は[Unityパッケヌゞによるチヌム開発](./unity_package_dev.md)を採甚しおください。
Markdown
UTF-8
1,273
2.875
3
[ "BSD-3-Clause" ]
permissive
# Components dev server This server serves up examples of the web components built within DevTools and provides a useful way to document various states of components. For more background, see the [initial proposal and design doc](https://docs.google.com/document/d/1P6qtACf4aryfT9OSHxNFI3okMKt9oUrtzOKCws5bOec/edit?pli=1). To add an example for your component: 1. Create `front_end/component_docs/DIR` where `DIR` is the name of your component. 2. Within the new `DIR`, add HTML files. Each one of these is a standalone example. You should name the HTML file based on what it's documenting, e.g. `basic.html` or `data-missing.html`. This file should import your component and render it with the data you need. 3. Update `front_end/component_docs/BUILD.gn` to add each of your `*.html` files to the `sources` array. You will also need to update the `deps` array to ensure the component examples depend on your component's source file. 4. Run `npm run components-server` to fire up a server on `localhost:8090`. You should now see your component listed and you can click on the link to view the examples. 5. **Note**: the server assumes your built target is `Default`. If not, run the server and pass the `--target` flag: `npm run components-server -- --target=Release`.
Java
UTF-8
754
2.34375
2
[]
no_license
package com.ssh.entity; public class Score { private String id; private Integer score; private String courseId; private String stuId; public String getId() { return id; } public void setId(String id) { this.id = id; } public Integer getScore() { return score; } public void setScore(Integer score) { this.score = score; } public String getCourseId() { return courseId; } public void setCourseId(String courseId) { this.courseId = courseId; } public String getStuId() { return stuId; } public void setStuId(String stuId) { this.stuId = stuId; } @Override public String toString() { return "Score [id=" + id + ", score=" + score + ", courseId=" + courseId + ", stuId=" + stuId + "]"; } }
PHP
UTF-8
2,007
2.71875
3
[ "MIT" ]
permissive
<?php namespace App\Repositories\Impl; use App\Models\Brand; use App\Repositories\BrandRepository as BradRepositoryInterface; use Illuminate\Database\Eloquent\Collection; use Illuminate\Pagination\LengthAwarePaginator; final class BrandRepository implements BradRepositoryInterface { /** * @var Brand */ private $brand; /** * BrandRepository constructor. * @param Brand $brand */ public function __construct( Brand $brand ) { $this->brand = $brand; } /** * @inheritDoc */ public function findAll(): Collection { return $this->brand->get(); } /** * @inheritDoc */ public function findAllWithPagination(): LengthAwarePaginator { return $this->brand->paginate(env('BRAND_PAGINATION')); } /** * @inheritDoc */ public function findByTerm(string $searchTerm): LengthAwarePaginator { $searchTermWildCard = '%' . $searchTerm . '%'; $fields = ['categories.name', 'brands.name']; return $this->brand->join('categories', 'brands.category_id', '=', 'categories.id') ->select('brands.name', 'brands.category_id') ->where(function($q) use($searchTerm, $fields, $searchTermWildCard) { foreach ($fields as $index => $field) { $q->orWhere($field, 'like', $searchTermWildCard); } })->paginate(env('BRAND_PAGINATION')); } /** * @inheritDoc */ public function create(int $categoryId, string $name): bool { return $this->brand->fill(['category_id' => $categoryId, 'name' => $name])->save(); } /** * @inheritDoc */ public function update(int $id, string $name): int { return $this->brand->whereId($id)->update(['name' => $name]); } /** * @inheritDoc */ public function delete(int $id): int { return $this->brand->whereId($id)->delete(); } }
C++
UTF-8
3,755
2.796875
3
[]
no_license
#include "ClassPacmen.h" ClassPacmen::ClassPacmen(Side SideFlag):MySide(SideFlag) { //ctor } ClassPacmen::ClassPacmen( int x , int y, Side SideFlag):MySide(SideFlag), PacmenMode(x, y), GhostMode(x, y) { //ctor } ClassPacmen::~ClassPacmen() { //dtor } void ClassPacmen::SetRegion() { PacmenMode.AssignRegion(); GhostMode.AssignRegion(); } void ClassPacmen::SetModeFlag() { SetRegion(); switch(MySide) { case SIDE_A: if(PacmenMode.GetCurrentRegion() == REGION_A || PacmenMode.GetCurrentRegion() == REGION_B) { ModeFlag = GHOSTMODE; break; } ModeFlag = PACMENMODE; break; case SIDE_B: if(PacmenMode.GetCurrentRegion() == REGION_C || PacmenMode.GetCurrentRegion() == REGION_D) { ModeFlag = GHOSTMODE; break; } ModeFlag = PACMENMODE; break; } } void ClassPacmen::PublishPacmenInformation(int PacmenNo) { GetPacmenData(PacmenData + PacmenNo); } void ClassPacmen::Render(SDL_Renderer *Renderer) { switch(ModeFlag) { case PACMENMODE: PacmenMode.Render(Renderer); break; case GHOSTMODE: GhostMode.Render(Renderer); break; } } Side ClassPacmen::Operate(SDL_Renderer * Renderer, int PacmenNo) { PublishPacmenInformation(PacmenNo - 1); if( CheckCollisionWithPacmen() ) { if(PacmenMode.GetCurrentRegion() == REGION_A || PacmenMode.GetCurrentRegion() == REGION_B) return SIDE_A; else return SIDE_B; } SetCollisionTargets(); SetModeFlag(); ProduceRegionConfinement(); PacmenMode.Move(); GhostMode.Move(); Render(Renderer); } void ClassPacmen::HandleEvent(MovementFlag Flag) { PacmenMode.HandleEvent(Flag); GhostMode.HandleEvent(Flag); } void ClassPacmen::Move() { PacmenMode.Move(); PacmenMode.Move(); } void ClassPacmen::SetCollisionTargets() { PacmenMode.SetCollisionTargets(); GhostMode.SetCollisionTargets(); } int ClassPacmen::CreateTexture(SDL_Renderer * Renderer, std::string path, Mode Flag) { //std::cout << endl<< path ; //std::cout << endl<< Flag ; int ReturnValue = 0; switch(Flag) { case PACMENMODE: ReturnValue += PacmenMode.CreateTexture(Renderer, path); break; case GHOSTMODE: ReturnValue += GhostMode.CreateTexture(Renderer , path); break; } return ReturnValue; } void ClassPacmen::ProduceRegionConfinement() { SDL_Rect Confinement[2] = {{0, 168, 16, 27}, {792, 168, 16, 27} }; for(int Looper = 0 ; Looper < 2 ; Looper++) { if(PacmenMode.CheckCollision(Confinement + Looper)) { switch(Looper) { case 0: PacmenMode.SetPositionX( 792-20); GhostMode.SetPositionX( 792-20); break; case 1: PacmenMode.SetPositionX( ORIGIN_XY + 20); GhostMode.SetPositionX( ORIGIN_XY + 20); break; } } } } void ClassPacmen::GetPacmenData(PacmenDetail *DetailPointer ) { DetailPointer->PacmenCollider = *PacmenMode.GetCollider(); DetailPointer->Allegiance = GetMySide(); } Side ClassPacmen::GetMySide() { return MySide; } bool ClassPacmen::CheckCollisionWithPacmen() { for(int PacmenNo = 0; PacmenNo < 2; PacmenNo++) { if( PacmenData[PacmenNo].Allegiance != MySide) { return GhostMode.CheckCollision( &PacmenData[PacmenNo].PacmenCollider ) ; break; } } return false; } PacmenDetail ClassPacmen::PacmenData[2];
Java
UTF-8
2,351
2.046875
2
[]
no_license
package com.tianjin.beichentiyu.bean; import java.util.List; public class FieldAppointListBean extends BaseRespBean{ /** * code : 99999 * list : [{"serialVersionUID":1,"logId":"157352589343886","timeSlot":"9:00-9:30","state":"0","gradeNum":1,"genTime":"2019-11-12 10:31:33","fId":1},{"serialVersionUID":1,"logId":"157352590833018","timeSlot":"8:00-8:30","state":"0","gradeNum":1,"genTime":"2019-11-12 10:31:48","fId":1}] */ private List<ListBean> list; public List<ListBean> getList() { return list; } public void setList(List<ListBean> list) { this.list = list; } public static class ListBean { /** * serialVersionUID : 1 * logId : 157352589343886 * timeSlot : 9:00-9:30 * state : 0 * gradeNum : 1 * genTime : 2019-11-12 10:31:33 * fId : 1 */ private int serialVersionUID; private String logId; private String timeSlot; private boolean subscribe; private int gradeNum; private String genTime; private int fId; public int getSerialVersionUID() { return serialVersionUID; } public void setSerialVersionUID(int serialVersionUID) { this.serialVersionUID = serialVersionUID; } public String getLogId() { return logId; } public void setLogId(String logId) { this.logId = logId; } public String getTimeSlot() { return timeSlot; } public void setTimeSlot(String timeSlot) { this.timeSlot = timeSlot; } public boolean isSubscribe() { return subscribe; } public void setSubscribe(boolean subscribe) { this.subscribe = subscribe; } public int getGradeNum() { return gradeNum; } public void setGradeNum(int gradeNum) { this.gradeNum = gradeNum; } public String getGenTime() { return genTime; } public void setGenTime(String genTime) { this.genTime = genTime; } public int getFId() { return fId; } public void setFId(int fId) { this.fId = fId; } } }