language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
2,236
3.21875
3
[]
no_license
import java.math.BigDecimal; /** * Created by jarockja on 24.01.2017. */ public class DecimalTestClass { public static void main(String[] argv){ // octal int int intValue = 034; // 28 in decimal int six = 06; // Equal to decimal 6 int seven = 07; // Equal to decimal 7 int eight = 010; // Equal to decimal 8 int nine = 011; // Equal to decimal 9 // hex int int hex10 = 0x10; int hex16 = 0x16; int hex20 = 0x20; int hex32 = 0x32; int hex33 = 0x33; int hexFF = 0xFF; System.out.println(new Value("034", intValue)); System.out.println(new Value("06", six)); System.out.println(new Value("07", seven)); System.out.println(new Value("010", eight)); System.out.println(new Value("011", nine)); System.out.println(new Value("0x10", hex10)); System.out.println(new Value("0x16", hex16)); System.out.println(new Value("0x20", hex20)); System.out.println(new Value("0x32", hex32)); System.out.println(new Value("0x33", hex33)); System.out.println(new Value("0xFF", hexFF)); System.out.println(String.format("Kein %s-Objekt fuer Liegenschaftsnummer %d gefunden!", "SA727", 123456789L)); System.out.println(String.format("Kein %s-Objekt fuer Liegenschaftsnummer %s gefunden!", "SA727", "123456789")); System.out.println(String.format("%d%02d", 201L, 1L)); System.out.println(String.format("%d%02d", 201L, 11L)); System.out.println(String.format("%04d/%d", 1L, 0L)); System.out.println(String.format("%04d/%d", 1L, 1L)); System.out.println(String.format("Scale: %f=%d", 12.0, BigDecimal.valueOf(12.12).scale())); System.out.println(String.format("Scale: %f=%d", 12.12, BigDecimal.valueOf(12.12).scale())); System.out.println(String.format("Scale: %f=%d", 12.12988776463, BigDecimal.valueOf(12.12988776463).scale())); } } class Value { private String strVal; private int intVal; public Value(String strVal, int intVal) { this.strVal = strVal; this.intVal = intVal; } @Override public String toString() { return "Value{" + "strVal='" + strVal + '\'' + ", intVal=" + intVal + '}'; } }
Java
UTF-8
385
2.046875
2
[]
no_license
package be.matthieu.mybasicsyncadapter.contracts; /** * Created by Matthieu on 10/02/2016. */ public class BaseContract { /*Definition des requets de base*/ protected static final String DEFAULT = " DEFAULT"; protected static final String TEXT_TYPE = " TEXT"; protected static final String INT_TYPE = " INTEGER"; protected static final String COMMA_SEP = ","; }
TypeScript
UTF-8
354
2.609375
3
[]
no_license
import styled from "styled-components"; import { number } from "prop-types"; interface TextProps { weight?: number; size?: number; } function getTextSize({ size = 16 }: TextProps) { return `${size}px`; } export const Text = styled.p<TextProps>` margin: 0; padding: 0; font-size: ${getTextSize}; font-weight: ${props => props.weight}; `;
JavaScript
UTF-8
411
4.125
4
[]
no_license
let array1 = Array.of(5, 3, 5, 6, 8); let array2 = [5, 3, 5, 6, 8]; console.log(array1, array2, array1 == array2); let newArray = Array.from(array2, val => val * 2); console.log(newArray); let array3 = Array(10); array3.fill(100); console.log(array3); let array4 = Array(10); array4.fill(100, 3, 8); console.log(array4); console.log(array2.find(val => val >= 6)); // gives back first matching element
SQL
UTF-8
1,297
4.25
4
[]
no_license
--Age CREATE PROCEDURE EmployeeAge AS BEGIN SELECT name, count(*) AS value FROM ( select case WHEN datediff(YY,DateOfBirth,getdate())<20 THEN 'Below 20' WHEN datediff(YY,DateOfBirth,getdate())<20 THEN 'Below 20' WHEN datediff(YY,DateOfBirth,getdate()) BETWEEN 20 AND 30 THEN '20+' WHEN datediff(YY,DateOfBirth,getdate()) BETWEEN 30 AND 40 THEN '30+' WHEN datediff(YY,DateOfBirth,getdate()) BETWEEN 40 AND 50 THEN '40+' WHEN datediff(YY,DateOfBirth,getdate()) BETWEEN 50 AND 60 THEN '50+' WHEN datediff(YY,DateOfBirth,getdate())>60 THEN '60+' END as name FROM Employee ) t group by name END --EXEC EmployeeAge --Gender CREATE PROCEDURE EmployeeGender AS BEGIN SELECT Gender AS name,COUNT(Gender) AS value FROM Employee GROUP BY Gender; END --EXEC EmployeeGender --DEPARTMENT CREATE PROCEDURE EmployeeDept AS BEGIN SELECT DName AS name, COUNT(DName) as value FROM Employee AS e INNER JOIN JobTitle AS j ON e.Code = j.Code INNER JOIN DepartmentDetail AS d ON j.DId = d.DId GROUP BY DName END --EXEC EmployeeDept --POSITION CREATE PROCEDURE EmployeePosition AS BEGIN SELECT Title AS name, COUNT(Title) as value FROM Employee AS e INNER JOIN JobTitle AS j ON e.Code = j.Code GROUP BY Title END --EXEC EmployeePosition
PHP
UTF-8
2,986
2.609375
3
[]
no_license
<?php $ename=$_POST ['ename']; $ecode=$_POST ['ecode']; $loc=$_POST ['loc']; $dep=$_POST ['dep']; $rh=$_POST ['rh']; $hd=$_POST ['hd']; $nd=$_POST ['nd']; $ph=$_POST ['ph']; $gs=$rh*$hd*$nd; $tax=$gs*0.1; $healthIns=$gs*0.05; $EPF=1800; $Total_Deduction=$tax+$healthIns+$EPF; $ns=$gs-$Total_Deduction; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title><?php echo $ename; ?>'s Slary Receipt</title> </head> <style> body { background-image: url(1.jpg); } .footer { position: fixed; text-align: center; bottom: 0px; width: 100%; } table input[type="submit"] { display: block; margin: 0 auto; } label { color: black; } </style> <body text="white"> <h2 ALIGN="CENTER"><?php echo $ename; ?>'s Slary Receipt</h2> <div align="center"> <fieldset> <table align="center" cellpadding="5"> <tr> <td> <label> <b>Employee ID:</b> </label> <?php echo $ecode; ?> </td> <td> <label color="black"> <b>Tax@10 percent:</b> </label> <?php echo $tax; ?> </td> </tr> <p></p> <tr> <td> <label><b>Gross Salary: </b></label> <?php echo $gs; ?> </td> <td> <label><b>Health Insurance@ 5%: </b></label> <?php echo $healthIns; ?> </td> </tr> <tr> <td> <label><b>Deduction: </b></label> <?php echo $Total_Deduction; ?> </td> <td> <label><b>EPF in Rs: </b></label> <?php echo $EPF; ?> </td> </tr> <tr> <td> <label><b>Net Salary: </b></label> <?php echo $ns; ?> </td> <td> <label><b>Total Deduction: </b></label> <?php echo $Total_Deduction; ?> </td> </tr> </table> </fieldset> </div> <div class="footer">Designed By Edula Vinay Kumar Reddy</div> <br> </body> </html>
Shell
UTF-8
7,935
3.65625
4
[]
no_license
#!/bin/bash # # Program : EvoCyclone LCD Service # : RESISTANCECOVID.COM # : https://github.com/libre/resistancecovid/evocyclo/ # Author : Deraoui Said <said.deraoui@gmail.com> # Purpose : # Parameters : --help # : --version # # Notes : See --help for details #============:============================================================== #set -x PROGNAME=`basename $0` PROGPATH=`echo $0 | /bin/sed -e 's,[\\/][^\\/][^\\/]*$,,'` REVISION=`echo '$Revision: 0.0.1.4 $' | sed -e 's/[^0-9.]//g'` datelog=`date "+%F_%H-%M-%S"` PID_LCD='/tmp/lcd.pid' PIDMSG_LCD='/tmp/lcd_msg.pid' PID_MENU='/tmp/evo-menu.pid' PATHLCD='/opt/evocyclone/lcd' SLEEPDEBUG=0 print_usage() { echo "Usage: $PROGNAME [--log /var/log/evo-motordrive.log] [--debug 0|1]" echo "" echo "$PROGNAME --log Log path file /var/log/evo-motordrive.log (default)" echo "$PROGNAME --debug 0 (default) silent, 1 = log in file" } print_help() { echo "$PROGNAME $REVISION" echo "" echo "LCD Service for EvoCyclo" echo "Appliance Respirator" echo "" print_usage echo "" echo "EVO-CYCLO Suite. Resistancecovid.com 2020" echo "" exit 0 # support } # Check mounting processing check() { # Test is running if [ -a $PID_LCD ]; then TESTPID=`ps ax | awk '{ print $7 }' | grep LCD | wc -l` if [ $TESTPID -lt 1 ]; then echo "$datelog Service running !!!! [STOPED]" exit 1 fi echo "$datelog File lock present ... [Unlocking]" rm -rf $PID_LCD fi # Check Debug status if [ -z "${DEBUGSTATUS}" ]; then DEBUGSTATUS=0 fi # Debug 0 if [ "${DEBUGSTATUS}" = "0" ]; then LOGFILE = "/dev/null" echo "$datelog Starting log webservice DEBUG = 0 [OK]" >> $LOGFILE fi # Debug 1 if [ "${DEBUGSTATUS}" = "1" ]; then # Check logfile default value if [ "${LOGFILE}" = "" ]; then LOGFILE="/tmp/evo-motordrive.log" fi echo "$datelog Starting log webservice DEBUG = 1 [OK]" >> $LOGFILE fi # Check PID MENU Service is started if [ -a $PID_MENU ]; then MENU_ORDRE = $PID_MENU echo "$datelog Pid Menu Process Detected [OK]" >> $LOGFILE else MENU_ORDRE = '/dev/null' echo "$datelog Pid MENU Process Not Detected [WARNING]" >> $LOGFILE fi echo "STARTING_LCD" > $PID_LCD echo "$datelog Service starting [Wait]" starting } # Starting Deamon Server Process. starting() { while true; do TTRUE=`cat $PID_LCD` if [ $TTRUE == "STARTING_LCD" ]; then cd $PATHLCD screen -dmS LCD sh -c "python $PATHLCD/stop.py" echo "$datelog Service LCD running !!!! [OK]" >> $LOGFILE echo "LCD_START" > $PID_LCD fi TESTPID=`ps ax | awk '{ print $7 }' | grep LCD | wc -l` if [ $TESTPID -lt 1 ]; then echo "$datelog Service not running !!!! [ERROR]" echo "$datelog Service not running !!!! [ERROR]" >> $LOGFILE rm -rf $PID_LCD exit 1 fi T4TRUE=`cat $PID_LCD` if [ $T4TRUE == "LCD_RUNNING" ]; then screen -X -S LCD kill screen -dmS LCD sh -c "python $PATHLCD/running.py" echo "LCD_START" > $PID_LCD echo "$datelog PID Order LCD Running [RUNNING]" >> $LOGFILE fi T4TRUE=`cat $PID_LCD` if [ $T4TRUE == "LCD_CYCLE" ]; then data=`cat $PIDMSG_LCD` screen -X -S LCD kill screen -dmS LCD sh -c "python $PATHLCD/runningcycle.py -m ${data}" echo "$datelog PID Order LCD Error code $data [OK]" >> $LOGFILE echo "LCD_ERROROK" > $PID_LCD fi T5TRUE=`cat $PID_LCD` if [ $T5TRUE == "LCD_ERROR" ]; then data=`cat $PIDMSG_LCD` screen -X -S LCD kill screen -dmS LCD sh -c "python $PATHLCD/error.py -m ${data}" echo "$datelog PID Order LCD Error code $data [OK]" >> $LOGFILE sleep 1 echo "LCD_ERROROK" > $PID_LCD fi T6TRUE=`cat $PID_LCD` if [ $T6TRUE == "LCD_STOP" ]; then screen -X -S LCD kill screen -dmS LCD sh -c "python $PATHLCD/stop.py" echo "$datelog PID Order LCD Status stop [OK]" >> $LOGFILE echo "LCD_STOPED" > $PID_LCD fi T7TRUE=`cat $PID_LCD` if [ $T7TRUE == "STOP" ]; then echo "$datelog PID Order stop service [STOPING]" >> $LOGFILE stopping fi T7TRUE=`cat $PID_LCD` if [ $T7TRUE == "RELOAD" ]; then echo "$datelog PID Order reload service [RELOADING]" >> $LOGFILE reload fi ### Integration Menu Interaction # MENUCHECK=`cat $PID_LCD` if [ $MENUCHECK == "LCD_MENU_MASTER_1" ]; then screen -X -S LCD kill screen -dmS LCD sh -c "python $PATHLCD/menu_master_1.py" echo "$datelog PID Order LCD Menu Master 1 [OK]" >> $LOGFILE echo "LCD_MENUOK" > $PID_LCD fi MENUCHECK=`cat $PID_LCD` if [ $MENUCHECK == "LCD_MENU_MASTER_2" ]; then screen -X -S LCD kill screen -dmS LCD sh -c "python $PATHLCD/menu_master_2.py" echo "$datelog PID Order LCD Menu Master 2 [OK]" >> $LOGFILE echo "LCD_MENUOK" > $PID_LCD fi MENUCHECK=`cat $PID_LCD` if [ $MENUCHECK == "LCD_MENU_MASTER_3" ]; then screen -X -S LCD kill screen -dmS LCD sh -c "python $PATHLCD/menu_master_3.py" echo "$datelog PID Order LCD Menu Master 3 [OK]" >> $LOGFILE echo "LCD_MENUOK" > $PID_LCD fi MENUCHECK=`cat $PID_LCD` if [ $MENUCHECK == "LCD_MENU_STATUS_1" ]; then screen -X -S LCD kill screen -dmS LCD sh -c "python $PATHLCD/menu_status_1.py" echo "$datelog PID Order LCD Menu Status 1 [OK]" >> $LOGFILE echo "LCD_MENUOK" > $PID_LCD fi MENUCHECK=`cat $PID_LCD` if [ $MENUCHECK == "LCD_MENU_STATUS_2" ]; then screen -X -S LCD kill screen -dmS LCD sh -c "python $PATHLCD/menu_status_2.py" echo "$datelog PID Order LCD Menu Status 2 [OK]" >> $LOGFILE echo "LCD_MENUOK" > $PID_LCD fi MENUCHECK=`cat $PID_LCD` if [ $MENUCHECK == "LCD_MENU_STATUS_3" ]; then screen -X -S LCD kill screen -dmS LCD sh -c "python $PATHLCD/menu_status_3.py" echo "$datelog PID Order LCD Menu Status 3 [OK]" >> $LOGFILE echo "LCD_MENUOK" > $PID_LCD fi MENUCHECK=`cat $PID_LCD` if [ $MENUCHECK == "LCD_MENU_SPEED_1" ]; then screen -X -S LCD kill screen -dmS LCD sh -c "python $PATHLCD/menu_speed_1.py" echo "$datelog PID Order LCD Menu Speed 1 [OK]" >> $LOGFILE echo "LCD_MENUOK" > $PID_LCD fi MENUCHECK=`cat $PID_LCD` if [ $MENUCHECK == "LCD_MENU_SPEED_2" ]; then screen -X -S LCD kill screen -dmS LCD sh -c "python $PATHLCD/menu_speed_2.py" echo "$datelog PID Order LCD Menu Speed 2 [OK]" >> $LOGFILE echo "LCD_MENUOK" > $PID_LCD fi MENUCHECK=`cat $PID_LCD` if [ $MENUCHECK == "LCD_MENU_SPEED_3" ]; then screen -X -S LCD kill screen -dmS LCD sh -c "python $PATHLCD/menu_speed_3.py" echo "$datelog PID Order LCD Menu Speed 3 [OK]" >> $LOGFILE echo "LCD_MENUOK" > $PID_LCD fi sleep $SLEEPDEBUG done } # Stoping Deamon Server Process. stopping() { screen -X -S LCD kill rm -rf $LOGFILE rm -rf $PIDMSG_LCD echo "$datelog Stoped LCD service [STOP]" exit 0 } # Stoping Deamon Server Process. reload() { screen -X -S LCD kill rm -rf $LOGFILE rm -rf $PIDMSG_LCD check starting echo "$datelog Service LCD reloaded !" exit 0 } while test -n "$1"; do case "$1" in -H|-h|--help) print_help exit 0 ;; -V|-v|--version) print_revision $PROGNAME $REVISION exit 0 ;; --device) DEVICE=$2; shift; ;; --port) PORT=$2; shift; ;; --log) LOGFILE=$2; shift; ;; --debug) DEBUGSTATUS=$2; shift; ;; *) echo "Unknown argument: $1" print_usage exit 2 ;; esac shift done check echo "Unknow Error Phase running" exit 1
Java
UTF-8
997
2.484375
2
[]
no_license
package nhn.cistory.util; import java.util.ArrayList; import java.util.HashMap; import nhn.cistory.vo.Qobtr; public class CalcScore { public CalcScore(){} public int calculate(ArrayList<Qobtr> list){ int score = 0; Qobtr qt = null; for(int i = 0 ; i < list.size() ; i ++){ qt = new Qobtr(); qt = list.get(i); if(qt.getUser_sol()== qt.getOb_sol()){ score += qt.getPoint(); } } return score; } public ArrayList<Integer> wrongList(ArrayList<Qobtr> list) { ArrayList<Integer> wrongList = new ArrayList<Integer>(); Qobtr qt = null; for(int i = 0 ; i < list.size() ; i ++){ qt = new Qobtr(); qt = list.get(i); System.out.println("내가푼답"+qt.getUser_sol()); System.out.println("정답"+qt.getOb_sol()); if(qt.getUser_sol()!= qt.getOb_sol()){ wrongList.add(qt.getQ_num()); } } return wrongList; } public HashMap<String, Integer> wrongType(ArrayList<Qobtr> userList) { // TODO Auto-generated method stub return null; } }
Java
UTF-8
4,552
2.1875
2
[]
no_license
package adam.mathandnumbers; import android.app.FragmentTransaction; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import java.io.File; import java.util.HashMap; import java.util.Map; import adam.mathandnumbers.QuestionFragment.QuestionFragCommunicator; import adam.mathandnumbers.ButtonPanelFragment.ButtonPanelFragCommunicator; /** * Created by adam on 2016-01-08. */ public class QuestionActivity extends AppCompatActivity implements QuestionFragCommunicator, ButtonPanelFragCommunicator, CustomDialogFragment.CustomDialogListener { //private static final String QUES_FRAG_TAG = "ques_frag_tag"; //private static final String BUTTON_PANE_TAG = "button_pane_tag"; private QuestionBank questionBank; private String answer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_question); SharedPreferences pref = getSharedPreferences(MainActivity.DEFAULT_PREFERENCES, MODE_PRIVATE); File f = new File("/data/data/" + getPackageName() + "/shared_prefs/" + MainActivity.DEFAULT_PREFERENCES + ".xml"); if (!f.exists()) { SharedPreferences.Editor editor = pref.edit(); editor.putBoolean(QuestionBank.QuestionType.ADDITION.toString(), true); editor.putBoolean(QuestionBank.QuestionType.SUBTRACTION.toString(), true); editor.commit(); } questionBank = new QuestionBank(this, pref); if (savedInstanceState == null) { FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.question_act_ques_frag_container, new QuestionFragment());//, QUES_FRAG_TAG); ft.replace(R.id.question_act_button_panel_frag_container, new ButtonPanelFragment());//, BUTTON_PANE_TAG); ft.commit(); } } @Override public Question getNextQuestion() { return questionBank.getNextQuestion(); } @Override public Question restoreQuestion(int ordinal) { return questionBank.restoreQuestion(ordinal); } @Override public void showCheckDialog(boolean correct, String answer) { this.answer = answer; Map<CustomDialogFragment.DialogKeys, String> mapBundle = new HashMap<>(); mapBundle.put(CustomDialogFragment.DialogKeys.POS_BUTTON, getString(R.string.dialog_button_close)); if (correct) { mapBundle.put(CustomDialogFragment.DialogKeys.TITLE, getString(R.string.dialog_correct_title)); mapBundle.put(CustomDialogFragment.DialogKeys.NEG_BUTTON, getString(R.string.dialog_button_next_question)); CustomDialogFragment dialogFrag = CustomDialogFragment.newInstance(mapBundle); dialogFrag.show(getFragmentManager(), "Answer Correct Dialog"); } else { mapBundle.put(CustomDialogFragment.DialogKeys.TITLE, getString(R.string.dialog_incorrect_title)); mapBundle.put(CustomDialogFragment.DialogKeys.NEG_BUTTON, getString(R.string.dialog_button_show_answer)); CustomDialogFragment dialogFrag = CustomDialogFragment.newInstance(mapBundle); dialogFrag.show(getFragmentManager(), "Answer Incorrect Dialog"); } } @Override public void checkAnswer() { QuestionFragment qFrag = (QuestionFragment) getFragmentManager().findFragmentById(R.id.question_act_ques_frag_container); qFrag.checkAnswer(); } @Override public void showNextQuestion() { QuestionFragment qFrag = (QuestionFragment) getFragmentManager().findFragmentById(R.id.question_act_ques_frag_container); qFrag.showNextQuestion(); } @Override public void doNegClick(String negButton) { if (negButton.equals(getString(R.string.dialog_button_next_question))) showNextQuestion(); else if (negButton.equals(getString(R.string.dialog_button_show_answer))) { Map<CustomDialogFragment.DialogKeys, String> mapBundle = new HashMap<>(); mapBundle.put(CustomDialogFragment.DialogKeys.TITLE, getString(R.string.dialog_show_answer_title)); mapBundle.put(CustomDialogFragment.DialogKeys.MESSAGE, answer); mapBundle.put(CustomDialogFragment.DialogKeys.NEG_BUTTON, getString(R.string.dialog_button_next_question)); mapBundle.put(CustomDialogFragment.DialogKeys.POS_BUTTON, getString(R.string.dialog_button_close)); CustomDialogFragment dialogFrag = CustomDialogFragment.newInstance(mapBundle); dialogFrag.show(getFragmentManager(), "Show Answer Dialog"); } } }
C#
UTF-8
3,186
3.265625
3
[ "MIT" ]
permissive
using System; using System.ComponentModel; using System.Globalization; namespace sabatex.Extensions.ClassExtensions { public static class DateTimeExtension { public static DateTime BeginOfDay(this DateTime dt) { return new DateTime(dt.Year, dt.Month, dt.Day, 0, 0, 0); } public static DateTime EndOfDay(this DateTime dt) { return new DateTime(dt.Year, dt.Month, dt.Day, 23, 59, 59); } public static DateTime BeginOfWeek(this DateTime dt) { return BeginOfDay(dt.AddDays(1 - (int)(dt.DayOfWeek))); } public static DateTime EndOfWeek(this DateTime dt) { return EndOfDay(dt.AddDays(7 - (int)(dt.DayOfWeek))); } public static DateTime BeginOfMonth(this DateTime dt) { return new DateTime(dt.Year, dt.Month, 1, 0, 0, 0); } public static DateTime EndOfMonth(this DateTime dt) { return new DateTime(dt.Year, dt.Month, DateTime.DaysInMonth(dt.Year, dt.Month), 23, 59, 59); } public static DateTime BeginOfYear(this DateTime dt) { return new DateTime(dt.Year, 1, 1, 0, 0, 0); } public static DateTime EndOfYear(this DateTime dt) { return new DateTime(dt.Year, 12, 31, 23, 59, 59); } public static int Quarter(this DateTime dt) { switch (dt.Month) { case 1: case 2: case 3: return 1; case 4: case 5: case 6: return 2; case 7: case 8: case 9: return 3; default: return 4; } } public static DateTime BeginOfQuarter(this DateTime dt) { switch (dt.Quarter()) { case 1: return new DateTime(dt.Year, 1, 1, 0, 0, 0); case 2: return new DateTime(dt.Year, 4, 1, 0, 0, 0); case 3: return new DateTime(dt.Year, 7, 1, 0, 0, 0); default: return new DateTime(dt.Year, 10, 1, 0, 0, 0); } } public static DateTime EndOfQuarter(this DateTime dt) { switch (dt.Quarter()) { case 1: return new DateTime(dt.Year, 3, 31, 23, 59, 49); case 2: return new DateTime(dt.Year, 6, 30, 23, 59, 49); case 3: return new DateTime(dt.Year, 9, 30, 23, 59, 49); default: return new DateTime(dt.Year, 12, 31, 23, 59, 49); } } public static int WeekOfYear(this DateTime dt) { Calendar cl = CultureInfo.InvariantCulture.Calendar; return cl.GetWeekOfYear(dt, DateTimeFormatInfo.CurrentInfo.CalendarWeekRule, DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek); } } }
JavaScript
UTF-8
1,348
3.8125
4
[]
no_license
/* Team BigFish - Jeffrey Wu and Dennis Chen SoftDev1 pd6 K29 -- Sequential Progression II: Electric Boogaloo... 2018-12-19*/ var fibonacci = function(n) { var sum = [0,1] for (var i = 2; i <= n; i++) { sum.push(sum[i-2] + sum[i-1]); } return sum[sum.length - 1] }; var gcd = function(a,b) { if (a > b) { for (i = b; i > 0; i--) { if ((a%i==0) && (b%i==0)) { return i } } } else { for (i = a; i > 0; i--) { if ((a%i==0) && (b%i==0)) { return i } } } }; var students = ['joe','bob','mary','addison','dennis','andrew','tyler','jessica','karen','vincent','allen'] var randomStudent = function(){ return students[parseInt(Math.random() * students.length)] }; f = document.getElementById('fibb') g = document.getElementById('gcd') r = document.getElementById('randomS') f.addEventListener('click',function(){ console.log(fibonacci(13)); document.getElementById("message").innerHTML = 'Fibonnacci of 13 is ' + fibonacci(13); }); r.addEventListener('click',function(){ var ranStu = randomStudent(); console.log(ranStu); document.getElementById("message").innerHTML = 'Random student is ' + ranStu; }); g.addEventListener('click',function(){ console.log(gcd(2019,3365)); document.getElementById("message").innerHTML = 'The GCD of 2019 and 3365 is ' + gcd(2019,3365); });
JavaScript
UTF-8
1,998
3.0625
3
[]
no_license
// browser-sync start --server --directory --files "**/*" let mediator = ( function () { const subscribe = function( channel, fn ) { if ( typeof mediator.channels[ channel ] === 'undefined' ){ mediator.channels[ channel ] = []; } mediator.channels[ channel ].push({ context: this, callback: fn }); console.log( fn, 'fn this' ); return this; }, publish = function( channel ) { if ( !mediator.channels[channel] ) return false; let args = [ ...arguments ].slice( 1 ); // Sandbox - это фасад со своим собственным имененем, обратным выховом и контекстом. // Контекстом явлюяется объект, подписанный на изменение let sandbox = mediator.channels[ channel ]; for ( let i = 0, l = sandbox.length; i < l; i++ ) { console.log('sandbox', sandbox); let subscription = sandbox[ i ]; console.log('subscription', subscription); // Метод текущего модуля, применяется к контексту медиатора. subscription.callback.apply( subscription.context, args ); } return this; }; return { channels: {}, publish: publish, subscribe: subscribe, installTo: obj => { obj.subscribe = subscribe; obj.publish = publish; } }; })(); const test = function( arg ) { console.log( `First arg: ${arg}` ); console.log( arguments ); console.log( [ ...arguments ] ); console.log( Object.keys( arguments ) ); } mediator.name = 'tim'; mediator.subscribe('nameChange', function(arg) { console.log('Name before:', this.name); this.name = arg; console.log('Name after:', this.name); }); mediator.publish('nameChange', 'default'); let obj = { name: 'sam' }; mediator.installTo( obj ); obj.subscribe('nameChange', function(arg) { console.log('Name before:', this.name); this.name = arg; console.log('Name after:', this.name); }); obj.publish('nameChange', 'john'); //sam, john
Java
UTF-8
493
2.0625
2
[]
no_license
package com.syndhacathon.awsomecoders.repository; import com.syndhacathon.awsomecoders.entity.Agent; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; @Repository public interface AgentRepository extends JpaRepository<Agent,Integer> { @Query(value = "SELECT * FROM agent WHERE email = ?1",nativeQuery = true) public Agent getAgentByEmail(String email); }
TypeScript
UTF-8
197
2.96875
3
[]
no_license
function clone<T>(data:T):T { //声明 T 类型(自定义),传入T类型则返回也是T类型 ;三者必须相同 return JSON.parse(JSON.stringify(data)) } export default clone;
Shell
UTF-8
11,831
3.671875
4
[]
no_license
#!/bin/bash banner() { echo "+------------------------------------------+" printf "| %-40s |\n" "`date`" echo "| |" printf "|`tput bold` %-40s `tput sgr0`|\n" "$@" echo "+------------------------------------------+" } #--- apache --- banner "Installing Apache2" sudo apt-get update sudo apt-get install -y apache2 sudo systemctl start apache2 sudo systemctl enable apache2 echo "<h1>Deployed via Terraform</h1>" | sudo tee /var/www/html/index.html #--- NGINX --- #sudo apt-get update #sudo apt-get install nginx #sudo systemctl start nginx #sudo systemctl enable nginx #--- curl and jq --- banner "Installing curl, wget, jq, nano, pwgen" sudo apt-get -y install curl unzip sudo apt-get -y install jq #--- Chrome --- #sudo wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb #sudo apt-get -y install ./google-chrome-stable_current_amd64.deb #--- Remote Desktop --- #sudo apt-get -y install xrdp #sudo systemctl enable --now xrdp #sudo ufw allow from any to any port 3389 proto tcp #--- Add a new user for Remote Desktop --- #Make sure you run "passwd" to set a new password to this account #The username and password will be located in $HOME/rdpcreds.txt USERNAME=teddy sudo adduser $USERNAME --quiet --disabled-password --gecos "" sudo usermod -aG sudo $USERNAME sudo apt -y install pwgen sudo grep $USERNAME /etc/passwd >> $HOME/usercreds.txt PASSWORD=$(pwgen -ys 15 1) banner "Creating user:$USERNAME pass:$PASSWORD for rdp" sudo echo $USERNAME:$PASSWORD | sudo chpasswd sudo echo "Username:"$USERNAME, "Password:"$PASSWORD >> $HOME/rdpcreds.txt sudo echo "Home:"$HOME,"Username:"$USERNAME, "Password:"$PASSWORD WHOIAM=$(whoami) sudo echo "WHO I AM:"$WHOIAM #--- Armor Agent --- banner "Installing the Armor Agent" sudo curl -sSL https://agent.armor.com/latest/armor_agent.sh | sudo bash /dev/stdin -l XXXXX-XXXXX-XXXXX-XXXXX-XXXXX -r us-west-armor -f #--- Metadata and index.html files --- banner "Generating webserver metadata" PRETTYpretty=$(cat /etc/os-release | awk -F '=' '/^PRETTY_NAME/{print $2}' | tr -d '"') #GET distro type and CREATE default index.html file sudo echo "Linux Distribution :"$PRETTYpretty WORKINGDIRECTORY=$(pwd) sudo echo "WORKING DIR:"$WORKINGDIRECTORY case "$PRETTYpretty" in *Ubuntu*) wget -N https://armorscripts.s3.amazonaws.com/BASHscripts/ansiart/ascii-art-ubuntu.ans -O /var/www/html/ascii-art-ubuntu.ans 2>/dev/null wget -N https://armorscripts.s3.amazonaws.com/BASHscripts/ansiart/ascii-art-ubuntu.html -O /var/www/html/index.html 2>/dev/null wget -N https://armorscripts.s3.amazonaws.com/BASHscripts/bashrc.txt -O /bashrc_append.txt 2>/dev/null cat /bashrc_append.txt >> /home/ubuntu/.bashrc wget -N https://armorscripts.s3.amazonaws.com/BASHscripts/bashrc.txt -O /root/.bashrc 2>/dev/null cat /var/www/html/ascii-art-ubuntu.ans ;; *Amazon*) wget -N https://armorscripts.s3.amazonaws.com/BASHscripts/ansiart/ascii-art-AWSLinux.ans -O /var/www/html/ascii-art-AWSLinux.ans 2>/dev/null wget -N https://armorscripts.s3.amazonaws.com/BASHscripts/ansiart/ascii-art-AWSLinux.html -O /var/www/html/index.html 2>/dev/null wget -N https://armorscripts.s3.amazonaws.com/BASHscripts/bashrc.txt -O /bashrc_append.txt 2>/dev/null cat /bashrc_append.txt >> /home/ec2-user/.bashrc wget -N https://armorscripts.s3.amazonaws.com/BASHscripts/bashrc.txt -O /root/.bashrc 2>/dev/null sudo cat /var/www/html/ascii-art-AWSLinux.ans ;; *CentOS*) wget -N https://armorscripts.s3.amazonaws.com/BASHscripts/ansiart/ascii-art-centos1.ans -O /var/www/html/ascii-art-centos1.ans 2>/dev/null wget -N https://armorscripts.s3.amazonaws.com/BASHscripts/ansiart/ascii-art-centos1.html -O /var/www/html/index.html 2>/dev/null wget -N https://armorscripts.s3.amazonaws.com/BASHscripts/bashrc.txt -O /bashrc_append.txt 2>/dev/null cat /bashrc_append.txt >> /home/centos/.bashrc wget -N https://armorscripts.s3.amazonaws.com/BASHscripts/bashrc.txt -O /root/.bashrc 2>/dev/null sudo cat /var/www/html/ascii-art-centos1.ans ;; *Debian*) wget -N https://armorscripts.s3.amazonaws.com/BASHscripts/ansiart/ascii-art-debian.ans -O /var/www/html/ascii-art-debian.ans 2>/dev/null wget -N https://armorscripts.s3.amazonaws.com/BASHscripts/ansiart/ascii-art-debian.html -O /var/www/html/index.html 2>/dev/null wget -N https://armorscripts.s3.amazonaws.com/BASHscripts/bashrc.txt -O /bashrc_append.txt 2>/dev/null cat /bashrc_append.txt >> /home/admin/.bashrc wget -N https://armorscripts.s3.amazonaws.com/BASHscripts/bashrc.txt -O /root/.bashrc 2>/dev/null sudo cat /var/www/html/ascii-art-debian.ans ;; *'Red Hat'*) wget -N https://armorscripts.s3.amazonaws.com/BASHscripts/ansiart/ascii-art-RHEL.ans -O /var/www/html/ascii-art-RHEL.ans 2>/dev/null wget -N https://armorscripts.s3.amazonaws.com/BASHscripts/ansiart/ascii-art-RHEL.html -O /var/www/html/index.html 2>/dev/null wget -N https://armorscripts.s3.amazonaws.com/BASHscripts/bashrc.txt -O /bashrc_append.txt 2>/dev/null cat /bashrc_append.txt >> /home/ec2-user/.bashrc wget -N https://armorscripts.s3.amazonaws.com/BASHscripts/bashrc.txt -O /root/.bashrc 2>/dev/null sudo cat /var/www/html/ascii-art-RHEL.ans ;; *SUSE*) wget -N https://armorscripts.s3.amazonaws.com/BASHscripts/ansiart/ascii-art-suse2.ans -O /srv/www/htdocs/ascii-art-suse2.ans 2>/dev/null wget -N https://armorscripts.s3.amazonaws.com/BASHscripts/ansiart/ascii-art-suse2.html -O /srv/www/htdocs/index.html 2>/dev/null wget -N https://armorscripts.s3.amazonaws.com/BASHscripts/bashrc.txt -O /bashrc_append.txt 2>/dev/null cat /bashrc_append.txt >> /home/ec2-user/.bashrc wget -N https://armorscripts.s3.amazonaws.com/BASHscripts/bashrc.txt -O /root/.bashrc 2>/dev/null sudo cat /srv/www/htdocs/ascii-art-suse2.ans ;; *Fedora*) wget -N https://armorscripts.s3.amazonaws.com/BASHscripts/ansiart/ascii-art-fedora.ans -O /var/www/html/ascii-art-fedora.ans 2>/dev/null wget -N https://armorscripts.s3.amazonaws.com/BASHscripts/ansiart/ascii-art-fedora.html -O /var/www/html/index.html 2>/dev/null wget -N https://armorscripts.s3.amazonaws.com/BASHscripts/bashrc.txt -O /bashrc_append.txt 2>/dev/null cat /bashrc_append.txt >> /home/ec2-user/.bashrc wget -N https://armorscripts.s3.amazonaws.com/BASHscripts/bashrc.txt -O /root/.bashrc 2>/dev/null sudo cat /var/www/html/ascii-art-fedora.ans ;; *) printf '%s\n\n' "This is some other version of linux" ;; esac chmod +x /var/www/html/index.html #GET ec2 localhost meta-data INSTANCE_ID=$(TOKEN=`curl -sS -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` 2>/dev/null && curl -sS -H "X-aws-ec2-metadata-token: $TOKEN" -v http://169.254.169.254/latest/meta-data/instance-id 2>/dev/null) HOSTNAME=$(TOKEN=`curl -sS -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` 2>/dev/null && curl -sS -H "X-aws-ec2-metadata-token: $TOKEN" -v http://169.254.169.254/latest/meta-data/hostname 2>/dev/null) REGION=$(TOKEN=`curl -sS -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` 2>/dev/null && curl -sS -H "X-aws-ec2-metadata-token: $TOKEN" -v http://169.254.169.254/latest/meta-data/placement/region 2>/dev/null) AVAIL_ZONE=$(TOKEN=`curl -sS -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` 2>/dev/null && curl -sS -H "X-aws-ec2-metadata-token: $TOKEN" -v http://169.254.169.254/latest/meta-data/placement/availability-zone 2>/dev/null) PRIVATE_IP=$(TOKEN=`curl -sS -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` 2>/dev/null && curl -sS -H "X-aws-ec2-metadata-token: $TOKEN" -v http://169.254.169.254/latest/meta-data/local-ipv4 2>/dev/null) PUBLIC_IP=$(TOKEN=`curl -sS -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` 2>/dev/null && curl -sS -H "X-aws-ec2-metadata-token: $TOKEN" -v http://169.254.169.254/latest/meta-data/public-ipv4 2>/dev/null) PUBLIC_HOSTNAME=$(TOKEN=`curl -sS -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` 2>/dev/null && curl -sS -H "X-aws-ec2-metadata-token: $TOKEN" -v http://169.254.169.254/latest/meta-data/public-hostname 2>/dev/null) #CREATE and set new HOSTNAME, /etc/hosts file, /etc/sysconfig/network file NEWprivatehostname="Ubuntu-$PRIVATE_IP-$AVAIL_ZONE-$PRETTYpretty-$INSTANCE_ID" NEWpublichostname="Ubuntu-$PUBLIC_IP-$AVAIL_ZONE-$PRETTYpretty-$INSTANCE_ID" #VarPUB="$(echo "$NEWpublichostname" | tr -d ' ')" #VarPRI="$(echo "$NEWprivatehostname" | tr -d ' ')" #VarPUB="$(echo "$NEWpublichostname" | cut -d ' ')" #VarPUB="$( cut -d ' ' -f 1 <<< "$NEWpublichostname" )"-"$INSTANCE_ID"; echo "$VarPUB" #VarPRI="$( cut -d ' ' -f 1 <<< "$NEWprivatehostname" )"-"$INSTANCE_ID"; echo "$VarPRI" VarPRI="UBUNTU-$PRIVATE_IP-$AVAIL_ZONE"-"$INSTANCE_ID" VarPUB="UBUNTU-$PUBLIC_IP-$AVAIL_ZONE"-"$INSTANCE_ID" echo "NEW Private hostname:"$NEWprivatehostname echo "NEW Public hostname:"$NEWpublichostname echo "VarPUB:"$VarPUB echo "VarPRI:"$VarPRI hostnamectl set-hostname $VarPUB #HOST=$Var #PRIVATE_HOST= #echo "HOST:"$HOST #PUBSTR=$Var PUBSUBSTR=$(echo $VarPUB | cut -d'-' -f 1) #PUBSTR=$Var PRISUBSTR=$(echo $VarPRI | cut -d'-' -f 1) echo "PUB Str:"$PUBSUBSTR echo "PRI Str:"$PRISUBSTR PUBLIC_DNS="$PUBSUBSTR-public" PRIVATE_DNS="$PRISUBSTR-private" echo "PUBLIC DNS:"$PUBLIC_DNS echo "PRIVATE DNS:"$PRIVATE_DNS #configLine [searchPattern] [replaceLine] [filePath] configLine () { local OLD_LINE_PATTERN=$1; shift local NEW_LINE=$1; shift local FILE=$1 local NEW=$(echo "${NEW_LINE}" | sed 's/\//\\\//g') touch "${FILE}" sed -i '/'"${OLD_LINE_PATTERN}"'/{s/.*/'"${NEW}"'/;h};${x;/./{x;q100};x}' "${FILE}" if [[ $? -ne 100 ]] && [[ ${NEW_LINE} != '' ]] then echo "${NEW_LINE}" >> "${FILE}" fi } #configLine HOSTNAME "HOSTNAME=$VarPUB" /etc/sysconfig/network configLine "$PUBLIC_IP $VarPUB" "$PUBLIC_IP $VarPUB $PUBLIC_DNS" /etc/hosts configLine "$PRIVATE_IP $VarPRI" "$PRIVATE_IP $VarPRI $PRIVATE_DNS" /etc/hosts #ADD meta-data to default index.html file printf '%s\n\n' printf "%20s%b\n" "PRETTY Linux Name : " "$PRETTYpretty" | tee /var/www/html/file.txt printf "%20s%b\n" "INSTANCE ID : " "$INSTANCE_ID" | tee -a /var/www/html/file.txt printf "%20s%b\n" "PUBLIC HOSTNAME : " "$PUBLIC_HOSTNAME" | tee -a /var/www/html/file.txt printf "%20s%b\n" "PRIVATE HOSTNAME : " "$HOSTNAME" | tee -a /var/www/html/file.txt printf "%20s%b\n" "LOCAL HOSTNAME : " "$VarPRI" | tee -a /var/www/html/file.txt printf "%20s%b\n" "REGION : " "$REGION" | tee -a /var/www/html/file.txt printf "%20s%b\n" "AVAILABILITY ZONE : " "$AVAIL_ZONE" | tee -a /var/www/html/file.txt printf "%20s%b\n" "PRIVATE IP : " "$PRIVATE_IP" | tee -a /var/www/html/file.txt printf "%20s%b\n" "PUBLIC IP : " "$PUBLIC_IP" | tee -a /var/www/html/file.txt printf '%s\n\n' set -o allexport PS1_DATE="\D{%Y-%m-%d %H:%M:%S %Z}" LOCATION=' `pwd | sed "s#\(/[^/]\{1,\}/[^/]\{1,\}/[^/]\{1,\}/\).*\(/[^/]\{1,\}/[^/]\{1,\}\)/\{0,1\}#\1_\2#g"`' color_prompt=yes # Color mapping grey='\[\033[1;30m\]' #bold dark GREY='\[\033[0;30m\]' #dark red='\[\033[0;31m\]' RED='\[\033[1;31m\]' green='\[\033[0;32m\]' GREEN='\[\033[1;32m\]' yellow='\[\033[0;33m\]' YELLOW='\[\033[1;33m\]' purple='\[\033[0;35m\]' PURPLE='\[\033[1;35m\]' white='\[\033[0;37m\]' WHITE='\[\033[1;37m\]' blue='\[\033[0;34m\]' BLUE='\[\033[1;34m\]' cyan='\[\033[0;36m\]' CYAN='\[\033[1;36m\]' NC='\[\033[0m\]' if [ "$color_prompt" = yes ]; then PS1="$PURPLE $PS1_DATE $GREEN\u@\h$NC:$BLUE$LOCATION$NC\$" else PS1="$NC$PS1_DATE \u@\h $LOCATION\$" fi
Python
UTF-8
6,306
3.890625
4
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- import math class MathOperations: """Различные математические операции""" @staticmethod def sma(points: list, cur_position: int, diff: int) -> float: """SMA: Простое скользящее среднее Это тоже самое, что и среднее арифметическое :param points: все точки (median prices) :param cur_position: текущая позиция (обычно последняя) :param diff: за сколько временных интервалов рассчитываем""" result = 0 # diff вычитаем 1 т/к у него # нет нулевого индекса count = cur_position - (diff-1) if count < 0: return None # Нужно считать включительно # последний пункт i = cur_position while i >= count: result += points[i] i -= 1 result = result/diff return result @staticmethod def std_dev(points: list, cur_position: int, diff: int) -> float: """Стандартное отклонение (standard deviation) :param points: все точки (median prices) :param cur_position: текущая позиция (обычно последняя) :param diff: за сколько временных интервалов рассчитываем Пример нахождения стандартного отклонения от 10 до 70 с шагом 10 10 20, 30, 40, 50, 60, 70 40 40, 40, 40, 40, 40, 40 - находим среднее -30, -20, -10, 0, 10, 20, 30 - находим разницу между значением и средним 10-40, 20-40... возводим разницу в квадрат -30*-30 = 900 900, 400, 100, 0, 100, 400, 900 суммируем квадраты 2800(900+900+400+400+100+100) делим на кол-во элементов выборки минус 1 2800/(7-1) = 467 Вычислаем квадратный корень sqrt(467) = 21,6 diff вычитаем 1 т/к у него нет нулевого индекса""" count = cur_position - (diff-1) if count < 0: return None # Среднее middle = MathOperations.sma(points, cur_position, diff) # Находим разницы между позицией и средним # Сразу возводим их в квадрат diffs = [] i = cur_position while i >= count: cur_diff = points[i] - middle diffs.append(pow(cur_diff, 2)) i -= 1 # Суммируем квадраты разниц squares_summ = 0 for item in diffs: squares_summ += item # Делим на кол-во элементов выборки минус 1 square = squares_summ / (diff-1) return math.sqrt(square) @staticmethod def bollinger_bands(points: list, cur_position: int, diff: int, D: int): """Bollinger Bands :param points: все точки (median prices) :param cur_position: текущая позиция (обычно последняя) :param diff: за сколько временных интервалов рассчитываем :param D: число стандартных отклонений ML = sma(points, cur_position, diff) TL(top_line) = ML(middle_line) + D * std_dev BL(bottom_line) = ML(middle_line) - D * std_dev D = число стандартных отклонений diff вычитаем 1 т/к у него нет нулевого индекса""" count = cur_position - (diff-1) if count < 0: return [None, None, None] ml = MathOperations.sma(points, cur_position, diff) standard_deviation = MathOperations.std_dev(points, cur_position, diff) bl = ml + D * standard_deviation tl = ml - D * standard_deviation return [round(tl, 4), round(ml, 4), round(bl, 4)] @staticmethod def martingail(digit: int, step: int, multiply: int = 2) -> float: """Стратегия Мартингейла У нас есть число digit, нам надо каждый шаг step удваивать это число :param digit: сумма ставки :param step: текущий шаг проигрышей подряд :param multiply: во сколько раз увеличиваем 0.35 ставка, выплата 0.66 35 = 66 (66-35=31 сколько это % от 35?) 35 100% 31 ?% 88% => 12% комиссия 0.7 ставка, выплата 1.36 70 = 136 (136-70=66 сколько это % от 70?) 70 100% 66 ?% 94% => 6% комиссия 1.4 ставка, выплата 2.72 140 = 272 (272-140=132 сколько это % от 140?) 140 = 100% 132 = ?% 94% => 6% комиссия 2.8 ставка, выплата 5.44 280 = 544 (544-280=264 сколько это % от 280?) 280 = 100% 264 = ?% 94% => 6% комиссия multiply => множитель, по умолчанию 2, с множителем в 1,5 можно 6 повторов сделать""" summa = 0 percent = 6 for i in range(step): if i == 0: summa += digit else: # От удваемого числа нужно плюсануть 6% # на первом шаге 12%, согласно расчетам if i == 1: percent = 12 six_percents = summa / 100 * percent summa = summa * multiply + six_percents return summa
Go
UTF-8
6,390
3.15625
3
[]
no_license
package claquete import ( "errors" "fmt" "math/rand" "regexp" "strconv" "strings" "time" "github.com/PuerkitoBio/goquery" "github.com/dsbezerra/claqueteapi/util" "github.com/gocolly/colly" ) // SearchFilterFlag is used to filter search results type SearchFilterFlag uint8 const ( // SearchFilterCinema restrict to Cinema results only SearchFilterCinema SearchFilterFlag = 1 << iota // SearchFilterMovie restrict to Movie results only SearchFilterMovie // SearchFilterNews restrict to News results only SearchFilterNews ) const ( // SearchTypeCinema indicates search result type is Cinema SearchTypeCinema = "cinema" // SearchTypeMovie indicates search result type is Movie SearchTypeMovie = "movie" // SearchTypeNews indicates search result type is News SearchTypeNews = "news" // DefaultSearchFilterFlags is the default behavior for search requests in Claquete's website. DefaultSearchFilterFlags = SearchFilterCinema | SearchFilterMovie | SearchFilterNews // MinQueryLength is used to avoid searching with a short query. // The website doesn't seem to have a pagination system and that makes // it retrieves all data in a single request. MinQueryLength = 2 ) var ( // Months is an array of month names (pt-BR) Months = []string{ "janeiro", "fevereiro", "março", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro", } ) type ( // SearchResults represents the search operation results. SearchResults struct { FilterFlags SearchFilterFlag `json:"-"` Query string `json:"query"` Filtered bool `json:"filtered"` TotalCount int `json:"total_count"` Results []SearchResult `json:"results"` } // SearchResult represents one row returned from search operation. SearchResult struct { Date time.Time `json:"date,omitempty"` Year int `json:"year,omitempty"` Title string `json:"title"` Type string `json:"type"` Page string `json:"page"` } ) // ShouldIncludeType checks if the result type match the filter. func (s *SearchResults) ShouldIncludeType(t string) bool { var f SearchFilterFlag switch t { case SearchTypeCinema: f = SearchFilterCinema case SearchTypeMovie: f = SearchFilterMovie case SearchTypeNews: f = SearchFilterNews } return s.FilterFlags&f != 0 } // Search performs a search operation without filtering results. func Search(query string) (*SearchResults, error) { return search(query, DefaultSearchFilterFlags) } // SearchCinemas performs a search operation filtering results to Cinema only. func SearchCinemas(query string) (*SearchResults, error) { return search(query, SearchFilterCinema) } // SearchMovies performs a search operation filtering results to Movie only. func SearchMovies(query string) (*SearchResults, error) { return search(query, SearchFilterMovie) } // SearchNews performs a search operation filtering results to News only. func SearchNews(query string) (*SearchResults, error) { return search(query, SearchFilterNews) } // SearchFiltered performs a search operation and applies a filter to its results. // filterFlags is used to specify what it should return. func SearchFiltered(query string, filterFlags SearchFilterFlag) (*SearchResults, error) { return search(query, filterFlags) } // Search searches in Claquete's website. func search(query string, filterFlags SearchFilterFlag) (*SearchResults, error) { if len(query) < MinQueryLength { return nil, errors.New("query length must be at least 2") } result := &SearchResults{ FilterFlags: filterFlags, Query: query, } c := NewClaquete() c.collector.OnHTML("#busca_ajax", func(e *colly.HTMLElement) { totalCountRE := regexp.MustCompile("(\\d+)\\sresultados") var sr SearchResult e.DOM.Children().Each(func(i int, s *goquery.Selection) { // Parse found results count if s.Is("h3") && result.TotalCount == 0 { r := totalCountRE.FindStringSubmatch(strings.ToLower(s.Text())) if len(r) == 2 { totalCount, err := strconv.Atoi(r[1]) if err != nil { fmt.Printf("couldn't find total count in text: %s\n", r[1]) } else { result.TotalCount = totalCount } } else { fmt.Printf("expected size 2, got: %d\n", len(r)) } } else if s.Is("div") && s.AttrOr("class", "") == "ttsubn" { t := getSearchType(s.Text()) if result.ShouldIncludeType(t) { sr = SearchResult{ Type: getSearchType(s.Text()), } } } else if s.Is("span") && sr.Type != "" { // If is a span and we have a result, parse the date/year information str := strings.TrimSpace(s.Text()) if sr.Type == SearchTypeNews { d, _, err := util.CreateDate(str, " de ") if err != nil { // TODO: proper error handling fmt.Println(err) } else { sr.Date = d } } else if sr.Type == SearchTypeMovie && sr.Type != "" { year, err := strconv.Atoi(str) if err != nil { // TODO: proper error handling fmt.Printf("couldn't convert text %s to year\n", str) } else { sr.Year = year } } else if sr.Type == SearchTypeCinema && sr.Type != "" { // Do nothing. } } else if s.Is("h2") && sr.Type != "" { // If is a h2 and we have a result, get title and page information sr.Title = s.Text() sr.Page = s.Find("a").AttrOr("href", "") result.Results = append(result.Results, sr) } }) // Update totalCount to match filtered results if result.FilterFlags != DefaultSearchFilterFlags { result.TotalCount = len(result.Results) result.Filtered = true } }) // NOTE(diego): // Claquete website sends x, y positions of mouse // at the time search button was clicked. // // Request works without them, but let's send it anyway. searchBtnWidth := 30 searchBtnHeight := 31 err := c.collector.Post(BaseURL+"/busca.html", map[string]string{ "query": query, "x": strconv.Itoa(rand.Intn(searchBtnWidth)), "y": strconv.Itoa(rand.Intn(searchBtnHeight)), }) return result, err } // getSearchType retrieves the search type for a given string. func getSearchType(str string) string { result := "" str = strings.TrimSpace(str) switch strings.ToLower(str) { case "cinema": result = SearchTypeCinema case "filme": result = SearchTypeMovie case "notícias": result = SearchTypeNews } return result }
C#
UTF-8
3,500
2.515625
3
[]
no_license
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using System.Web; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Filters; using System.Web.Mvc; // https://chsakell.com/2015/06/07/web-api-file-uploading-desktop-and-web-client/ namespace ApiS.Controllers { public class FileController : ApiController { [System.Web.Http.HttpGet] public string GetMessage() { return "Hello From FileController"; } [System.Web.Http.HttpPost] [MimeMultipart] public async Task<string> PostFile() { var uploadPath = HttpContext.Current.Server.MapPath("~/Uploads"); var multipartFormDataStreamProvider = new UploadMultipartFormProvider(uploadPath); // Read the MIME multipart asynchronously await Request.Content.ReadAsMultipartAsync(multipartFormDataStreamProvider); string _localFileName = multipartFormDataStreamProvider .FileData.Select(multiPartData => multiPartData.LocalFileName).FirstOrDefault(); // Create response return "OK!"; } [System.Web.Http.HttpPost] [MimeMultipart] public async Task<FileUploadResult> PostFile1() { var uploadPath = HttpContext.Current.Server.MapPath("~/Uploads"); var multipartFormDataStreamProvider = new UploadMultipartFormProvider(uploadPath); // Read the MIME multipart asynchronously await Request.Content.ReadAsMultipartAsync(multipartFormDataStreamProvider); string _localFileName = multipartFormDataStreamProvider .FileData.Select(multiPartData => multiPartData.LocalFileName).FirstOrDefault(); // Create response return new FileUploadResult() { LocalFilePath = uploadPath, FileName = _localFileName, FileLength = new FileInfo(_localFileName).Length }; } } public class FileUploadResult { public string LocalFilePath { get; set; } public string FileName { get; set; } public long FileLength { get; set; } } public class UploadMultipartFormProvider : MultipartFormDataStreamProvider { public UploadMultipartFormProvider(string rootPath) : base(rootPath) { } public override string GetLocalFileName(HttpContentHeaders headers) { if (headers != null && headers.ContentDisposition != null) { return headers .ContentDisposition .FileName.TrimEnd('"').TrimStart('"'); } return base.GetLocalFileName(headers); } } public class MimeMultipart : System.Web.Http.Filters.ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { if (!actionContext.Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException( new HttpResponseMessage( HttpStatusCode.UnsupportedMediaType) ); } } public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { } } }
Python
UTF-8
1,765
2.859375
3
[ "BSD-3-Clause" ]
permissive
# -*- coding: utf-8 -*- '''Helper utilities and decorators.''' import time from flask import flash def flash_errors(form, category="warning"): '''Flash all errors for a form.''' for field, errors in form.errors.items(): for error in errors: flash("{0} - {1}" .format(getattr(form, field).label.text, error), category) def pretty_date(dt, default=None): """ Returns string representing "time since" e.g. 3 days ago, 5 hours ago etc. Ref: https://bitbucket.org/danjac/newsmeme/src/a281babb9ca3/newsmeme/ """ if default is None: default = 'just now' now = datetime.utcnow() diff = now - dt periods = ( (diff.days / 365, 'year', 'years'), (diff.days / 30, 'month', 'months'), (diff.days / 7, 'week', 'weeks'), (diff.days, 'day', 'days'), (diff.seconds / 3600, 'hour', 'hours'), (diff.seconds / 60, 'minute', 'minutes'), (diff.seconds, 'second', 'seconds'), ) for period, singular, plural in periods: if not period: continue if period == 1: return u'%d %s ago' % (period, singular) else: return u'%d %s ago' % (period, plural) return default def pretty_seconds_to_hhmmss(seconds): if not seconds: return None m, s = divmod(seconds, 60) h, m = divmod(m, 60) return "%d h %d m %s s" % (h, m, s) def pretty_seconds_to_hhmm(seconds): if not seconds: return None m, s = divmod(seconds, 60) h, m = divmod(m, 60) return "%d h %d m" % (h, m) def pretty_seconds_to_hh(seconds): if not seconds: return None m, s = divmod(seconds, 60) h, m = divmod(m, 60) return "%d h" % (h)
JavaScript
UTF-8
2,978
4.375
4
[]
no_license
// Tableau Array // - Une variable povant avoir simultanément en ensemble de valeurs // // - Le premier indice du tableau est 0 function fun() { var tab = [2, 3, 4, 5]; // // Recuperer la taille du tableau console.log(tab.length) // //Afficher 1er élément du tableau console.log(tab[0]) // //Affiche le tableau console.log(tab) // //Parcourir et afficher un tableau for (i = 0; i < tab.length; i++) { console.log(tab[i]) } for (elt of tab) { console.log(elt) } } fun(); // Opérations sur les tableaux // - push () ajoute un élément // - pop () supprime dernier élément // - shift () supprime le premier élément // - reverse () inverse l'ordre // - sort () trie le tableau // - splice () permet d'extraire, ajouter ou supprimer un ou plusieurs élément // - slice () permet d extraire un sous tableau a partir tu tableau f'origine // - include () renvoie true si la valeur passé en parametre existe dans le tableau // - indexof () retourne la position de l'élément passer en parametre // - fill () permet d'initialiser ou modifier valaeur d'un array // splice var sports = ["foot", "boxe", "tennis", "petanque", 'rugby']; var tab2 = sports.splice(2, 1, "basket"); for (elt of tab2) { console.log(elt) } // slice var tab = sports.slice(0, 4); for (elt of tab) { console.log(elt) } //fill var tab = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] tab.fill(9, 2, 5) console.log(tab) // exo calculer la somme et le produits d'un tableau d'entier tab1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]; sum = 0; products = 1; for (i = 0; i < tab1.length; i++) { sum += tab1[i]; products *= tab1[i] } console.log(products); console.log(sum); for (elt of tab1) { sum += elt products += elt } // .forEach () parcourir un tableau // . map() appliquer une fonction a un tableau // .filter () filtre les éléments d'un tableau selon un critère sous la forme d'une fonction anonyme // .reduce () réduis tous les élément d'un tableau en un seul selon une régle définie sous la forme d'une fonction fléché ou anonyme var tab = [2, 3, 5]; tab.map(x => x + 3) .filter(x => x > 5) .forEach( function (a) { console.log(a - 3) } ); var somme = tab .map(x => x + 3) .filter(x => x > 5) .reduce(function (sum, elt) { return sum + elt }); console.log(somme) // ECMA 5 function somme(a, b) { return a + b } somme(1,3) // ECMA 6 const addition= (a,b) => a +b; var res= addition(1,3); console.log(res) //autre function somme(a, b) { return a + b } var res = somme(1, 3) console.log(somme) let somme2 = new Function("a","b", "return a+b") let resultat= somme2(1,5); console.log(resultat) // exo ecrire une fonction en ecma5 et ecma6 qui récupére la valeur des tableaux et renvoie le premier élément tab3= [1, 2, 3, 4, 5, 6, 7, 8, 9] function exo3(tab3){ return tab3[0] } const f2 = (arr) => arr[0]
Java
UTF-8
956
1.78125
2
[]
no_license
package com.zhss.eshop.promotion.service.Impl; import com.zhss.eshop.promotion.domain.dto.CouponDTO; import com.zhss.eshop.promotion.domain.dto.PromotionActivityDTO; import com.zhss.eshop.promotion.service.PromotionService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.util.List; /** * 促销中心service组件 * @author zhonghuashishan * */ @Service public class PromotionServiceImpl implements PromotionService { private static final Logger logger = LoggerFactory.getLogger(PromotionServiceImpl.class); @Override public List<PromotionActivityDTO> listByGoodsId(Long goodsId) { return null; } @Override public PromotionActivityDTO getById(Long id) { return null; } @Override public List<CouponDTO> listValidByUserAccountId(Long userAccountId) { return null; } @Override public Boolean useCoupon(Long couponId, Long userAccountId) { return null; } }
Java
ISO-8859-1
6,220
2.515625
3
[ "MIT" ]
permissive
package presentacion.vistas.menu; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import presentacion.contexto.Contexto; import presentacion.controlador.appController.Controller; import presentacion.eventos.EventosMenu; import presentacion.vistas.gui.VistaPrincipal; /** * The Class VistaMenu. */ public class VistaMenu extends JFrame implements VistaPrincipal { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** The factura boton. */ private JButton menuBoton, clienteBoton, editorialBoton, libroBoton, facturaBoton; /** * Instantiates a new vista menu. */ public VistaMenu() { vista(); } /* * (non-Javadoc) * * @see * presentacion.vistas.gui.VistaPrincipal#actualizar(presentacion.contexto. * Contexto) */ @Override public void actualizar(final Contexto contexto) { } /** * Botones. * * @param Path * the path * @param color * the color * @return the j button */ public JButton botones(final String Path, final Color color) { final JButton boton = new JButton(); boton.setPreferredSize(new Dimension(190, 120)); // 200, 125 boton.setBackground(color); boton.setBorder(null); boton.setFocusPainted(false); boton.setIcon(new ImageIcon(Path)); return boton; } /** * Botones menu. * * @param nombre * the nombre * @return the j button */ public JButton botonesMenu(final String nombre) { final JButton boton = new JButton(nombre); boton.setFocusPainted(false); boton.setBorderPainted(false); boton.setFont(new Font("Arial", Font.PLAIN, 18)); boton.setBackground(new Color(255, 255, 255)); boton.setMaximumSize(new Dimension(170, 50)); return boton; } /** * Boton exit. * * @return the j button */ public JButton botonExit() { final JButton boton = new JButton("X"); boton.setFocusPainted(false); boton.setBorder(null); boton.setContentAreaFilled(false); boton.setBorderPainted(false); boton.setPreferredSize(new Dimension(30, 30)); boton.setFont(new Font("Corbel", Font.BOLD, 20)); boton.setForeground(new Color(255, 255, 255)); boton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final int confirmacion = JOptionPane.showConfirmDialog(null, "Desea cerrar el programa?", "Salir", JOptionPane.YES_NO_OPTION); if (confirmacion == JOptionPane.YES_OPTION) { System.exit(0); } } }); return boton; } /** * Vista. */ private void vista() { setSize(1080, 720); setLocationRelativeTo(null); setResizable(false); setUndecorated(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); final JPanel fondo = new JPanel(); final JPanel barra = new JPanel(); final JPanel panelMenuBoton = new JPanel(); final JPanel panelSalir = new JPanel(); barra.setBackground(new Color(66, 86, 98)); panelMenuBoton.setBackground(new Color(66, 86, 98)); panelSalir.setBackground(new Color(66, 86, 98)); fondo.setBackground(new Color(225, 225, 225)); barra.setLayout(new BorderLayout()); fondo.setLayout(new FlowLayout(FlowLayout.CENTER, 20, 250)); menuBoton = botonesMenu("MEN"); menuBoton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { dispose(); final Contexto contexto = new Contexto(EventosMenu.MOSTRAR_MENU_VISTA, null); Controller.getInstance().handleRequest(contexto); ; } }); final JButton salir = botonExit(); panelMenuBoton.add(menuBoton); panelSalir.add(salir); barra.add(panelMenuBoton, BorderLayout.WEST); barra.add(panelSalir, BorderLayout.EAST); clienteBoton = botones(getClass().getClassLoader().getResource("iconos/menu/clientes.png").getPath(), new Color(255, 255, 255)); clienteBoton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { dispose(); final Contexto contexto = new Contexto(EventosMenu.MOSTRAR_CLIENTE_VISTA, null); Controller.getInstance().handleRequest(contexto); } }); fondo.add(clienteBoton); editorialBoton = botones(getClass().getClassLoader().getResource("iconos/menu/editorial.png").getPath(), new Color(255, 255, 255)); editorialBoton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { dispose(); final Contexto contexto = new Contexto(EventosMenu.MOSTRAR_EDITORIAL_VISTA, null); Controller.getInstance().handleRequest(contexto); } }); fondo.add(editorialBoton); libroBoton = botones(getClass().getClassLoader().getResource("iconos/menu/libro.png").getPath(), new Color(255, 255, 255)); libroBoton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { dispose(); final Contexto contexto = new Contexto(EventosMenu.MOSTRAR_LIBRO_VISTA, null); Controller.getInstance().handleRequest(contexto); } }); fondo.add(libroBoton); facturaBoton = botones(getClass().getClassLoader().getResource("iconos/menu/factura.png").getPath(), new Color(255, 255, 255)); facturaBoton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { dispose(); final Contexto contexto = new Contexto(EventosMenu.MOSTRAR_FACTURA_VISTA, null); Controller.getInstance().handleRequest(contexto); } }); fondo.add(facturaBoton); add(barra, BorderLayout.NORTH); add(fondo, BorderLayout.CENTER); setVisible(true); } }
JavaScript
UTF-8
165
2.640625
3
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
var n = 0; (function() { function o() { while(i()); } var c; function i() { c && c[n++]; } i((c = 1)); })(); console.log(n);
Java
UTF-8
2,040
2.484375
2
[]
no_license
package objects; import java.util.LinkedList; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.utils.Pool.Poolable; import framework.Assets; import framework.Handler; import framework.ObjectId; import framework.NewGame; public class Block extends GameObject implements Poolable { public boolean flipX; public Sprite sprite; public Block(float x, float y, int type, Handler handler, ObjectId id) { super(x, y, handler, id); sprite = new Sprite(Assets.findRegion("MiddlePink")); sprite.setPosition(x, y); sprite.setOrigin(x, y); boundingRectangle = new Rectangle(sprite.getX(), sprite.getY(), sprite.getWidth() * scaleValue, sprite.getHeight() * scaleValue); } public void tick(LinkedList<GameObject> object) { boundingRectangle = new Rectangle(sprite.getX(), sprite.getY(), sprite.getWidth() * scaleValue, sprite.getHeight() * scaleValue); if(sprite.getX() < handler.gameCam.position.x - NewGame.V_WIDTH / 2 - sprite.getWidth()) { handler.disposeList.add(this); } } public void draw(SpriteBatch batch) { sprite.setFlip(flipX, true); // if(sprite.getX() < handler.gameCam.position.x + NewGame.V_WIDTH / 2 + sprite.getWidth() && sprite.getY() > handler.gameCam.position.y - NewGame.V_HEIGHT / 2 - sprite.getHeight()) { drawSprite(batch); // } } public void drawSprite(SpriteBatch batch) { batch.draw(sprite, sprite.getX(), sprite.getY(), sprite.getWidth() * scaleValue, sprite.getHeight() * scaleValue); boundingRectangle = new Rectangle(sprite.getX(), sprite.getY(), sprite.getWidth() * scaleValue, sprite.getHeight() * scaleValue); } @Override public void reset() { // resetting old block. Add paramter that changes the skin } public void drawSprite1(SpriteBatch batch) { batch.draw(sprite, x, y, width, height); boundingRectangle = new Rectangle(x, y, width, height); // Swapped out old calculations that multiplied original image size by the width and height } }
PHP
UTF-8
773
2.765625
3
[]
no_license
<?php ini_set('error_reporting', E_ALL ^ E_NOTICE); define(RUTA, __DIR__ . DIRECTORY_SEPARATOR); $idHotel = 1; //vendrá via POST $fecha = '2017-03-21'; //vendrá via POST $reserva = 3; $doc = new DOMDocument(); $doc->load(RUTA . 'datos.xml'); $xpath = new DOMXPath($doc); $guardar = false; if ($result = $xpath->query("//oferta[@id='$idHotel']/fecha[@dia='$fecha']/plazas")) { if ($reserva > (int) $result->item(0)->nodeValue) { echo " imposible reservar ..." . PHP_EOL; } else { $result->item(0)->nodeValue = (int) $result->item(0)->nodeValue - $reserva; echo " Reservar efectuada ... de $reserva plazas" . PHP_EOL; $guardar = true; } } if ($guardar) { $doc->save(RUTA . 'datos.xml'); }
C#
UTF-8
2,034
2.953125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using StateLib.Infrastructure.State; namespace StateLib.Infrastructure { public class ClockSetup { private IClockSetup yearState; private IClockSetup monthState; private IClockSetup dayState; private IClockSetup currentState; private IClockSetup finishedState; public ClockSetup() { this.finishedState = new FinishedState(this); this.currentState = this.finishedState; } public IClockSetup State { set { this.currentState = value; } } public IClockSetup YearState { get { return yearState; } set { yearState = value; } } public IClockSetup MonthState { get { return monthState; } set { monthState = value; } } public IClockSetup DayState { get { return dayState; } set { dayState = value; } } public IClockSetup FinishedState { get { return finishedState; } } public virtual void PushKnob() { currentState.SelectValue(); } public virtual void RotateRight() { currentState.NextValue(); } public virtual void RotateLeft() { currentState.PreviousValue(); } public virtual DateTime GetSelectedDate() { return new DateTime(this.yearState.SelectedValue, this.monthState.SelectedValue, this.dayState.SelectedValue, 0, 0, 0); } } }
C++
UTF-8
1,684
3.296875
3
[]
no_license
#include <iostream> using namespace std; // kelompok 8 : // Program pengisian data nilai-nilai // mahasiswa lengkap dari nilai absen, kuis, uts, // uas, dan akumulasi nilai dalam bentuk angka dan // pengelompokkan nilai berdasarkan huruf int main() { char nilai_huruf; int nilai_uas[10], absen[10], kuis[10], uts[10], nilai_akhir[10]; cout << "Program menghitung pengisian " << endl; for (int i = 0; i < 10; i++) { cout << "Masukkan nilai UAS ke -" << i + 1 << " : "; cin >> nilai_uas[i]; cout << endl; cout << "Masukkan nilai absen -" << i + 1 << " : "; cin >> absen[i]; cout << endl; cout << "Masukkan nilai ke Kuis -" << i + 1 << " : "; cin >> kuis[i]; cout << "Masukkan nilai ke Uts -" << i + 1 << " : "; cout << endl; cin >> uts[i]; cout << endl; nilai_akhir[i] = (nilai_uas[i] + absen[i] + uts[i] + kuis[i]) / 4; } for (int i = 0; i < 10; i++) { int nilai_akhir_mahasiswa = nilai_akhir[i]; if (nilai_akhir_mahasiswa >= 80) { nilai_huruf = 'A'; } else if (nilai_akhir_mahasiswa <= 80 && nilai_akhir_mahasiswa >= 70) { nilai_huruf = 'B'; } else if (nilai_akhir_mahasiswa <= 70 && nilai_akhir_mahasiswa >= 60) { nilai_huruf = 'C'; } else if (nilai_akhir_mahasiswa <= 60 && nilai_akhir_mahasiswa >= 0) { nilai_huruf = 'D'; } else { nilai_huruf = 'E'; } cout << "Nilai mahasiswa ke-" << i << " : " << nilai_huruf; cout << endl; } }
C
UTF-8
264
2.65625
3
[]
no_license
#include <string.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int var = 15; void func(int *p) { p = &b; printf("inside : %d adress %d\n", *p, p); } int main() { int b = 100, *ptr = &b; func(ptr); printf("%d %d ", *ptr, ptr); }
Python
UTF-8
1,442
3.34375
3
[ "CC-BY-4.0", "MIT" ]
permissive
import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set() # Specify Parameters n_gen = 16 # Chance of having beneficial mutation r = 1e-5 # Total Number of Cells n_cells = 2**(n_gen-1) ai_samples = np.random.binomial(n_cells,r,size=100000) # print('AI mean:',np.mean(ai_samples)) # print('AI std:',np.std(ai_samples)) # print('Fano factor: ',np.var(ai_samples) / np.mean(ai_samples)) # # plt.plot(np.bincount(ai_samples) / len(ai_samples), marker='.', markersize=10, # linestyle='None') # # plt.xlabel('Number of survivors') # plt.ylabel('Probability') # plt.xticks(np.arange(ai_samples.max()+1)); # plt.margins(0.02) # plt.show() def draw_random_mutation(n_gen,r): """Draw sample under random mutation hypothesis""" n_mut = 0 for g in range(n_gen): n_mut = 2*n_mut + np.random.binomial(2**g-2*n_mut,r) return n_mut def sample_random_mutation(n_gen, r, n_samples): """Sample out of the Luria-Delbruck distribution""" # Initialize samples samples = np.empty(n_samples) # Draw the samples for i in range(n_samples): samples[i] = draw_random_mutation(n_gen, r) return samples def print_stats(data,desc): print(desc,' mean:',np.mean(data)) print(desc,' std:',np.std(data)) print('Fano factor: ',np.var(data) / np.mean(data)) rm_samples = sample_random_mutation(n_gen, r, 100000).astype(int) print_stats(rm_samples,desc='rm')
Markdown
UTF-8
2,763
2.640625
3
[]
no_license
# El mito de la alimentación “natural” Tal como afirmaba el maestro de la nutrición en nuestro país, el Profesor Grande Covián_,_ la adición del adjetivo _natural_ al nombre de un producto basta para convertirlo automáticamente en un alimento dotado de extraordinarias propiedades nutritivas, de las que el mismo producto carece cuando no es objeto de tal calificación. La primera dificultad va a consistir, precisamente, en definir qué se entiende por alimento natural. En sentido estricto, natural sólo es aplicable a aquello que se produce espontáneamente, sin intervención de la mano del hombre, por lo que es **prácticamente imposible encontrar en el mundo actual alimentos que merezcan esta calificación**. Así, desde el comienzo de la agricultura y la domesticación de los animales, hace aproximadamente diez mil años, las especies vegetales y animales de las que derivamos nuestro sustento diario han sido seleccionadas y sometidas a distintos métodos de cultivo y crianza, con objeto de aumentar la productividad y hacerlas más apetecibles. Gracias a ello, precisamente, nuestros antepasados pudieron comenzar a disfrutar de un suministro relativamente estable, se pudo abandonar la vida nómada y comenzar el proceso de lo que llamamos civilización. Por tanto, no puede pensarse seriamente que la humanidad vuelva a alimentarse, en estos momentos, de las plantas que crecen espontáneamente y de los animales salvajes. ¿Cuál sería la producción mundial de alimentos, si llevados por la creencia de la alimentación natural abandonáramos los métodos modernos de producción agrícola y ganadera?. Cuando de alimentos se trata, el calificativo natural se emplea con frecuencia sin tener en cuenta el sujeto a quien el alimento se destina. En este sentido, muchos de nuestra propia especie atribuyen un buen estado de salud a la alimentación con los llamados productos naturales, tales como la leche de vaca y los huevos de gallina. La cuestión que se plantea es si son o no naturales para el hombre: admitamos que la leche de vaca es el alimento específicamente diseñado por la naturaleza para servir de alimento al ternero durante la primera época de su vida, y que el huevo de gallina es el alimento diseñado por la naturaleza para servir de alimento al embrión de pollo. Sin embargo, es más difícil admitir que la leche de vaca y el huevo de gallina han sido diseñados por la naturaleza para servir de alimento a una persona que, evidentemente, no es ni un ternero ni un embrión de pollo, por lo que debe dudarse que puedan calificarse de alimentos naturales para el hombre. Esto no quiere decir, evidentemente, que tanto la leche de vaca como el huevo de gallina no sean alimentos excelentes para el hombre.
Swift
UTF-8
2,546
2.78125
3
[]
no_license
// // HomeTrips.swift // HomeTrips // // Created by Ronan Furuta on 8/29/21. // import SwiftUI import ArrivalUI import ArrivalCore struct HomeTrips: View { @ObservedObject var appState: AppState @State var timeDisplayMode = TimeDisplayType.etd var body: some View { VStack { if (self.appState.trainsLoading) { List() { ForEach(0..<5) {i in TrainCard(train: MockUpData().train, timeDisplayMode: self.$timeDisplayMode, redacted: true).redacted(reason: .placeholder).listRowSeparator(.hidden).listRowInsets(EdgeInsets()).padding(.vertical, 5) } }.listStyle(.plain) } else { if (self.appState.trips.count > 0) { List() { ForEach(self.appState.trips) {trip in //Text("test") Button(action: { print("displaying from click") self.appState.diplayTripModal = true self.appState.tripDisplay = trip }) { TrainCard(train: trip.legs.first!.trainData, timeDisplayMode: self.$timeDisplayMode, eta: trip.destinationTime) }.contentShape(Rectangle()).listRowSeparator(.hidden).listRowInsets(EdgeInsets()).padding(.vertical, 5).buttonStyle(PlainButtonStyle()) }.edgesIgnoringSafeArea(.bottom) }.listStyle(.plain).refreshable { Task(priority: .userInitiated) { await self.appState.cycle() await self.appState.refreshAlerts() } }.edgesIgnoringSafeArea(.bottom) } else { VStack { Spacer() Text("No Trips in this direction") Spacer() } } } }.padding().edgesIgnoringSafeArea(.bottom).sheet(isPresented: .init(get: { return self.appState.diplayTripModal }, set: { self.appState.diplayTripModal = $0 })) { TripDetailsView(appState: appState) } } } struct HomeTrips_Previews: PreviewProvider { static var previews: some View { HomeTrips(appState: AppState()) } }
Python
UTF-8
19,194
2.515625
3
[]
no_license
import data_distributions as data_dist import DateFunctions.date_functions as dates import data_dist_database as db analytics_file_path = '\\\\filer01\\public\\Data_Analytics\\Data_Distributions\\temporary_files\\in_files\\' #Find the most recent sunday. This is for the week by week data pulls #since the weeks end on sunday most_recent_sunday = dates.DateFunctions().find_most_recent_sunday() most_recent_sunday = dates.DateFunctions().datetime_to_string_y_m_d(most_recent_sunday, "-") def find_weekly_query_start_date(table): last_run_date = db.DatabaseWork().pull_most_recent_date_value(table) + 1 last_run_date = str(last_run_date) year = last_run_date[:4] month = last_run_date[4:6] day = last_run_date[6:8] return year + "-" + month + "-" + day def find_monthly_query_start_date(table): last_run_date = str(db.DatabaseWork().pull_most_recent_date_value(table)) year = int(last_run_date[:4]) month = int(last_run_date[4:6]) + 1 if month == 13: month = 1 year += 1 month = str(month) if len(month) == 1: month = "0" + month return str(year) + "-" + month + "-" + "01" def run_weekly_queries(): """ Run all the pre-planned weekly analysis tool queries """ '''All Active Profiles''' active_start = find_weekly_query_start_date('active_profiles') data_dist.DataDistributions().post_analysis_tool_query("localhost", "Ryan Data Dist Week by Week All Actives", active_start, most_recent_sunday, "", "Profile Age Measure", "Count", "&& ALL", "Date Ranges Weeks 2010 to 2016") """Total Profiles""" total_start = find_weekly_query_start_date("overall_profiles") data_dist.DataDistributions().post_analysis_tool_query("psbuilder02a", "Ryan Data Dist Week by Week Total Profiles", total_start, most_recent_sunday, "", "Profile Age Measure", "Count", "&& ALL", "Date Ranges Weeks 2010 to 2016") """ '''Combined Salary''' salary_start = find_weekly_query_start_date("combined_salary_weekly") data_dist.DataDistributions().post_analysis_tool_query("localhost", "Ryan Data Dist Week by Week Combined Salary", "Ryan Data Dist Week by Week Combined Salary", salary_start, most_recent_sunday, "", "Combined Salary Measure", "Medians", "&& ALL", "Date Ranges Weeks 2010 to 2016") '''EAC Medians''' eac_start = find_weekly_query_start_date("eac_weekly") data_dist.DataDistributions().post_analysis_tool_query("localhost", "Ryan Data Dist Week by Week EAC Medians", "Ryan Data Dist Week by Week EAC Medians", eac_start, most_recent_sunday, "", "EAC Measure", "Medians", "&& ALL", "Date Ranges Weeks 2010 to 2016") """ #Find the first day of the current month (in case this is being ran on the 2nd or 3rd) #This is for the monthly queries first_of_month = dates.DateFunctions().return_ymd_first_of_the_current_month("-") def run_monthly_queries(): """ Run the monthly pre-planned analysis tool queries. These bad boys will take a while since they're going to output all of the data via months as dimension files. These should be running at night. """ '''Rollups''' rollup_start = find_monthly_query_start_date('rollups') data_dist.DataDistributions().post_analysis_tool_query("localhost", "Ryan Data Dist Rollups", rollup_start, first_of_month, "", "Profile Age Measure", "Count", "Date Ranges Months 2010 to 2017", "&& ALL", dimension="Job Rollup Dimension") over_rollup_start = find_monthly_query_start_date('rollups_overall') data_dist.DataDistributions().post_analysis_tool_query("psbuilder02a", "Ryan Data Dist Rollups Overall", over_rollup_start, first_of_month, "", "Profile Age Measure", "Count", "Date Ranges Months 2010 to 2017", "&& ALL", dimension="Job Rollup Dimension") '''ONET''' onet_start = find_monthly_query_start_date('onet_forty') data_dist.DataDistributions().post_analysis_tool_query("localhost", "Ryan Data Dist ONET 40", onet_start, first_of_month, "", "Profile Age Measure", "Count", "Date Ranges Months 2010 to 2017", "&& ALL", dimension="ONET 40 Dimension") over_onet_start = find_monthly_query_start_date('onet_forty') data_dist.DataDistributions().post_analysis_tool_query("psbuilder02a", "Ryan Data Dist ONET 40 Overall", over_onet_start, first_of_month, "", "Profile Age Measure", "Count", "Date Ranges Months 2010 to 2017", "&& ALL", dimension="ONET 40 Dimension") '''NAICS''' naics_start = find_monthly_query_start_date('naics_codes') data_dist.DataDistributions().post_analysis_tool_query("localhost", "Ryan Data Dist Month by Month NAICS 40", naics_start, first_of_month, "", "Profile Age Measure", "Count", "Date Ranges Months 2010 to 2017", "&& ALL", dimension="Industry 40 Dimension") over_naics_start = find_monthly_query_start_date('naics_codes_overall') data_dist.DataDistributions().post_analysis_tool_query("psbuilder02a", "Ryan Data Dist Month by Month NAICS 40 Overall", over_naics_start, first_of_month, "", "Profile Age Measure", "Count", "Date Ranges Months 2010 to 2017", "&& ALL", dimension="Industry 40 Dimension") '''Metros''' metro_start = find_monthly_query_start_date('metro_main') data_dist.DataDistributions().post_analysis_tool_query("localhost", "Ryan Data Dist Metros", metro_start, first_of_month, "", "Profile Age Measure", "Count", "Date Ranges Months 2010 to 2017", "&& ALL", dimension="Metro Dimension") over_metro_start = find_monthly_query_start_date('metro_main_overall') data_dist.DataDistributions().post_analysis_tool_query("psbuilder02a", "Ryan Data Dist Metros Overall", over_metro_start, first_of_month, "", "Profile Age Measure", "Count", "Date Ranges Months 2010 to 2017", "&& ALL", dimension="Metro Dimension") '''Degree Affinties''' degree_start = find_monthly_query_start_date('degree_affinities') data_dist.DataDistributions().post_analysis_tool_query("localhost", "Ryan Data Dist Degree Affinities", degree_start, first_of_month, "", "Profile Age Measure", "Count", "Date Ranges Months 2010 to 2017", "&& ALL", dimension="Degree Affinity Dimension") over_degree_start = find_monthly_query_start_date('degree_affinities_overall') data_dist.DataDistributions().post_analysis_tool_query("psbuilder02a", "Ryan Data Dist Degree Affinities Overall", "Ryan Data Dist Degree Affinities Overall", over_degree_start, first_of_month, "", "Profile Age Measure", "Count", "Date Ranges Months 2010 to 2017", "&& ALL", dimension="Degree Affinity Dimension") '''Company Size''' company_start = find_monthly_query_start_date('company_size') data_dist.DataDistributions().post_analysis_tool_query("localhost", "Ryan Data Dist Company Sizes", company_start, first_of_month, "", "Profile Age Measure", "Count", "Date Ranges Months 2010 to 2017", "&& ALL", dimension="Number Employees Dimension") over_company_start = find_monthly_query_start_date('company_size_overall') data_dist.DataDistributions().post_analysis_tool_query("psbuilder02a", "Ryan Data Dist Company Sizes Overall", over_company_start, first_of_month, "", "Profile Age Measure", "Count", "Date Ranges Months 2010 to 2017", "&& ALL", dimension="Number Employees Dimension") '''AGE''' age_start = find_monthly_query_start_date('age_ranges') data_dist.DataDistributions().post_analysis_tool_query("localhost", "Ryan Data Dist Age Buckets", age_start, first_of_month, "", "Profile Age Measure", "Count", "Date Ranges Months 2010 to 2017", "&& ALL", dimension="Age Dimension", ranges="Dynamic") over_age_start = find_monthly_query_start_date('age_ranges_overall') data_dist.DataDistributions().post_analysis_tool_query("psbuilder02a", "Ryan Data Dist Age Buckets Overall", over_age_start, first_of_month, "", "Profile Age Measure", "Count", "Date Ranges Months 2010 to 2017", "&& ALL", dimension="Age Dimension", ranges="Dynamic") '''YE''' ye_start = find_monthly_query_start_date('years_experience') data_dist.DataDistributions().post_analysis_tool_query("localhost", "Ryan Data Dist YE", ye_start, first_of_month, "", "Profile Age Measure", "Count", "Date Ranges Months 2010 to 2017", "&& ALL", dimension="Experience Dimension") over_ye_start = find_monthly_query_start_date('years_experience_overall') data_dist.DataDistributions().post_analysis_tool_query("psbuilder02a", "Ryan Data Dist YE Overall", over_ye_start, first_of_month, "", "Profile Age Measure", "Count", "Date Ranges Months 2010 to 2017", "&& ALL", dimension="Experience Dimension")
C
UTF-8
6,103
3.046875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <semaphore.h> #include "fifo.h" #include <signal.h> //#define SEMAPHORE 1 //Konstanten #define ALPHABET_LAENGE 26 #define SLEEP_CONSUMER 2 #define SLEEP_PRODUCER 3 //Mutex für den Zugriff auf den FIFO Puffer static pthread_mutex_t fifo_mutex = PTHREAD_MUTEX_INITIALIZER; //Mutex Variablen für Producer und Consumer Threads static pthread_mutex_t producer1_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t producer2_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t consumer_mutex = PTHREAD_MUTEX_INITIALIZER; static int producer1_isRunning; static int producer2_isRunning; static int consumer1_isRunning; //threadvariablen pthread_t producer_1_t; pthread_t producer_2_t; pthread_t consumer_t; pthread_t control_t; //wenn semaphore an dann: #ifdef SEMAPHORE sem_t puffer_input; sem_t puffer_output; #else //conditional variables //cv fürs produzieren pthread_cond_t cond_p = PTHREAD_COND_INITIALIZER; //cv fürs consumen pthread_cond_t cond_c = PTHREAD_COND_INITIALIZER; #endif /* * Funktion die alle 3 Sekunden einen char in den Puffer schreibt */ void produce(char*buchstaben, pthread_mutex_t* producer_mutex, int *producer_isRunning){ //Zeiger auf den aktuellen Buchstaben int charZeiger = 0; while(*producer_isRunning){ pthread_mutex_lock(producer_mutex); pthread_mutex_unlock(producer_mutex); pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);//for die if #ifdef SEMAPHORE sem_wait(&puffer_input); //check ob der puffer frei ist //beginn kritischer Abschnitt pthread_mutex_lock(&fifo_mutex); fifo_push(buchstaben[charZeiger]); pthread_mutex_unlock(&fifo_mutex); sem_post(&puffer_output); #else //beginn kritischer Abschnitt pthread_mutex_lock(&fifo_mutex); while(fifo_getLength() == PUFFER_SIZE) pthread_cond_wait(&cond_p, &fifo_mutex); fifo_push(buchstaben[charZeiger]); pthread_cond_signal(&cond_c); pthread_mutex_unlock(&fifo_mutex); #endif pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); sleep(SLEEP_PRODUCER); charZeiger++; if(charZeiger == ALPHABET_LAENGE) { charZeiger = 0; } } } void *producer1_function(void *notUsed){ char* alphabetKlein = "abcdefghijklmopqrstuvwxyz"; produce(alphabetKlein, &producer1_mutex, &producer1_isRunning); return NULL; } void *producer2_function(void *notUsed){ char* alphabetGross = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; produce(alphabetGross, &producer2_mutex, &producer2_isRunning); return NULL; } //fertig void *consumer_function(void *a){ printf("Consumer gestartet...\n"); while(1){ pthread_mutex_lock(&consumer_mutex); pthread_mutex_unlock(&consumer_mutex); pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL); #ifdef SEMAPHORE sem_wait(&puffer_output);//check ob der puffer leer ist pthread_mutex_lock(&fifo_mutex); fifo_pop(); pthread_mutex_unlock(&fifo_mutex); sem_post(&puffer_input); #else pthread_mutex_lock(&fifo_mutex); while(fifo_getLength() == 0) pthread_cond_wait(&cond_c, &fifo_mutex); fifo_pop(); pthread_cond_signal(&cond_p); //vor unlock gesetzt pthread_mutex_unlock(&fifo_mutex); #endif pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); sleep(SLEEP_CONSUMER); } return NULL; } void *control_Function(void *notUsed){ char eingabe = 0; int producer1_blocked = 0; int producer2_blocked = 0; int consumer_blocked = 0; while(1){ eingabe = getchar(); switch(eingabe){ case '1': if(producer1_blocked == 0){ pthread_mutex_lock(&producer1_mutex); printf("Producer 1 blockiert...\n"); producer1_blocked = 1; }else{ pthread_mutex_unlock(&producer1_mutex); printf("Producer 1 gestartet...\n"); producer1_blocked = 0; } break; case '2': if(producer2_blocked == 0){ pthread_mutex_lock(&producer2_mutex); printf("Producer 2 blockiert...\n"); producer2_blocked = 1; }else{ pthread_mutex_unlock(&producer2_mutex); printf("Producer 1 gestartet...\n"); producer2_blocked = 0; } break; case 'c' : case 'C': if(consumer_blocked == 0){ pthread_mutex_lock(&consumer_mutex); printf("Consumer blockiert...\n"); consumer_blocked = 1; }else { pthread_mutex_unlock(&consumer_mutex); printf("Consumer gestartet...\n"); consumer_blocked = 0; } break; case 'q' : case 'Q': if(consumer_blocked){ pthread_mutex_unlock(&consumer_mutex); } if(producer1_blocked){ pthread_mutex_unlock(&producer1_mutex); } if(producer2_blocked){ pthread_mutex_unlock(&producer2_mutex); } pthread_mutex_unlock(&fifo_mutex); pthread_cancel(producer_1_t); pthread_cancel(producer_2_t); pthread_cancel(consumer_t); pthread_exit(0); break; } } } int main(){ printf("Das Programm wurde gestartet...\n"); #ifdef SEMAPHORE printf("SEMAPHORE VARIANTE!\n"); #else printf("CV VARIANTE!\n"); #endif fifo_init(); producer1_isRunning = 1; producer2_isRunning = 1; consumer1_isRunning = 1; #ifdef SEMAPHORE sem_init(&puffer_input, 0, PUFFER_SIZE); sem_init(&puffer_output, 0, 0); #endif pthread_create(&control_t, NULL, control_Function, NULL); pthread_create(&producer_1_t, NULL, producer1_function, NULL); pthread_create(&producer_2_t, NULL, producer2_function, NULL); pthread_create(&consumer_t, NULL, consumer_function, NULL); pthread_join(control_t, NULL); pthread_join(producer_1_t, NULL); pthread_join(producer_2_t, NULL); pthread_join(consumer_t, NULL); #ifdef SEMAPHORE sem_destroy(&puffer_input); sem_destroy(&puffer_output); #else pthread_cond_destroy(&cond_c); pthread_cond_destroy(&cond_p); #endif pthread_mutex_destroy(&producer1_mutex); pthread_mutex_destroy(&producer2_mutex); pthread_mutex_destroy(&consumer_mutex); pthread_mutex_destroy(&fifo_mutex); printf("\nDas Program wurde beendet!"); return 0; }
Java
UTF-8
2,245
3.25
3
[]
no_license
package contest.contest102; import java.util.HashSet; import java.util.Set; public class Problem906_3 { private static final Set<Integer> set = new HashSet<>(); private boolean isPalindrome(long num) { long right = 0; while (num > right) { right = right * 10 + num % 10; num /= 10; } return num == right || num == right / 10; } /** * 获取数字的[反转数字, 数字长度pow] */ private int[] getReverseNumAndPow(int num) { int reverseNum = 0; int pow10 = 1; while (num > 0) { reverseNum = reverseNum * 10 + num % 10; num /= 10; pow10 *= 10; } return new int[]{reverseNum, pow10}; } private void rec(int i, int value) { if (i == 4) { int[] reverseNumAndPow = getReverseNumAndPow(value); // 中间加一个数的情况 int pow10 = reverseNumAndPow[1]; int tmpValue = value * pow10 * 10 + reverseNumAndPow[0]; for (int j = 0; j <= 9; j++) { int num = tmpValue + j * pow10; long square = (long) num * num; if (isPalindrome(square)) { set.add(num); } } // 中间不加一个数的情况 int num = value * reverseNumAndPow[1] + reverseNumAndPow[0]; long square = (long) num * num; if (isPalindrome(square)) { set.add(num); } return; } int oldValue = value; for (int j = 0; j <= 9; j++) { value = value * 10 + j; rec(i + 1, value); value = oldValue; } } public int superpalindromesInRange(String left, String right) { long l = Long.parseLong(left); long r = Long.parseLong(right); if (set.isEmpty()) { rec(0, 0); } int rCount = 0; int lCount = 0; for (long num : set) { if (num * num <= r) { rCount++; } if (num * num < l) { lCount++; } } return rCount - lCount; } }
JavaScript
UTF-8
3,877
3.46875
3
[]
no_license
//Функция обновления содержимого массива function UpdatePanel() { //Сначала очищается содержимое панели let panel = document.getElementById("conveyor_panel"); panel.innerHTML = ""; //Запрос, на получение нового содержимого var xhr = new XMLHttpRequest(); xhr.open('POST', "https://localhost:44367/main/state", true); //При загрузке данных xhr.onload = function () { //Если не удачно, выброс ошибки if (xhr.status != 200) { ShowError(xhr.responseText); return; } //Добавление новых элементов //Получение массива значений var products = JSON.parse(xhr.responseText); //Получение отдельных продуктов for (index = 0; index < products.length; index++) { //Получение и добавление продукта panel.appendChild(GetNewProdyct(products[index])); } } xhr.send(); } //Метод для вывода ошибки пользователю function ShowError(errorText) { alert(errorText); } //Запрос на добавление новой продукции в конвеер function addButtonClick() { //Получение типа продукта, который надо добавить let typeProd = ""; let good = document.getElementById("goodradio"); let defective = document.getElementById("defectiveradio") if (good.checked) typeProd = "good"; if (defective.checked) typeProd = "defective"; //Формирование тела запроса let date = new FormData(); date.append('type', typeProd); let xhr = new XMLHttpRequest(); xhr.open('POST', "https://localhost:44367/main/AddProduct", true); xhr.onload = function () { if (xhr.status != 200) { let error_text = "Не удалось добавить продукт: "; error_text += xhr.responseText; ShowError(error_text); } //Обновление страницы UpdatePanel(); } xhr.send(date); } //Запрос на извлечение конвеера с ленты function pushButtonClick() { let Addr = "https://localhost:44367/main/pushproduct"; let xhr = new XMLHttpRequest(); xhr.open("POST", Addr, true); xhr.onload = function () { if (xhr.status != 200) { let error_text = "Не удалось извлечь продукт: "; error_text += xhr.responseText; ShowError(error_text); } //Обновление страницы UpdatePanel(); } xhr.send(); } //Функция возвращает новый продукт //Зависящий от типа function GetNewProdyct(type) { //Создание нового продукта let product = document.createElement('div'); //Указание класса в зависимости от типа let product_class = "conveyor-product"; if (type == "good") product_class += " " + "conveyor-product-good"; else if (type == "defective") product_class += " " + "conveyor-product-defective"; else { //Если ни один из типов не подходит, выбросить ошибку alert("Непредведенный тип!"); } //Указние стиля product.className = product_class; //Возвращение объекта return product; } //Функция, инициализирующая страницу function LoadPage() { //Заполнение панели UpdatePanel(); }
C#
UTF-8
339
2.578125
3
[]
no_license
using System; using MicrosoftDI.Contracts; namespace MicrosoftDI { public class GameMovement : IMovement { private ILogger logger; public GameMovement(ILogger logger) { this.logger = logger; } public void Move() { logger.Log("Moving"); } } }
C#
UTF-8
6,269
2.90625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Console2048 { /// <summary> /// 游戏核心类,负责处理游戏核心算法,与界面无关 /// </summary> class GameCore { //字段 属性 构造函数 private int[,] map; private int[] mergeArray; private int[] removeZeroArray; private int[,] originalMap; /// <summary> /// 地图是否发生改变 /// </summary> public bool IsChange { get; set; } public int[,] Map { get { return this.map; } } public GameCore() { map = new int[4, 4]; mergeArray = new int[4]; removeZeroArray = new int[4]; emptyLocationList = new List<Location>(16); random = new Random(); originalMap = new int[4,4]; } #region 数据合并 private void RemoveZero() { //每次去零操作,都先清空去零数组元素 Array.Clear(removeZeroArray, 0, 4); int index = 0; for (int i = 0; i < mergeArray.Length; i++) { if (mergeArray[i] != 0) removeZeroArray[index++] = mergeArray[i]; } removeZeroArray.CopyTo(mergeArray,0); } private void Merge() { RemoveZero(); for (int i = 0; i < mergeArray.Length - 1; i++) { if (mergeArray[i] != 0 && mergeArray[i] == mergeArray[i + 1]) { mergeArray[i] += mergeArray[i + 1]; mergeArray[i + 1] = 0; //积分 } } RemoveZero(); } #endregion #region 移动 private void MoveUp() { for (int c = 0; c < map.GetLength(1); c++) { for (int r = 0; r < map.GetLength(0); r++) { mergeArray[r] = map[r, c]; } Merge(); for (int r = 0; r < map.GetLength(0); r++) { map[r, c] = mergeArray[r]; } } } private void MoveDown() { for (int c = 0; c < map.GetLength(1); c++) { for (int r = map.GetLength(0) - 1; r >= 0; r--) { mergeArray[3 - r] = map[r, c]; } Merge(); for (int r = map.GetLength(0) - 1; r >= 0; r--) { map[r, c] = mergeArray[3 - r]; } } } private void MoveLeft() { //00 01 02 03 for(int r = 0; r < map.GetLength(0); r++) { for (int c = 0; c < map.GetLength(1); c++) mergeArray[c] = map[r, c]; Merge(); for (int c = 0; c < map.GetLength(1); c++) map[r, c] = mergeArray[c]; } } private void MoveRight() { for (int r = 0; r < map.GetLength(0); r++) { for (int c = map.GetLength(1) - 1; c >=0; c--) mergeArray[3 - c] = map[r, c]; Merge(); for (int c = map.GetLength(1) - 1; c >= 0; c--) map[r, c] = mergeArray[3 - c]; } } public void Move(MoveDirection direction) { //移动之前记录map ->originalMap Array.Copy(map, originalMap, map.Length); IsChange = false; switch (direction) { case MoveDirection.Up: MoveUp(); break; case MoveDirection.Down: MoveDown(); break; case MoveDirection.Left: MoveLeft(); break; case MoveDirection.Right: MoveRight(); break; } //移动完毕对比map for (int r = 0; r < map.GetLength(0); r++) { for (int c = 0; c < map.GetLength(1); c++) { if (map[r, c] != originalMap[r, c]) { IsChange = true; return; } } } } #endregion #region 生成数字 //生成数字 //需求:在空白位置,随机产生一个2(90%)或者4(10). //分析:先计算所有空白位置 // 在随机选择一个位置 // 随机2,4, private List<Location> emptyLocationList; private void CalculateEmpty() { //每次统计空位置前,先清空列表 emptyLocationList.Clear(); for(int r = 0; r < map.GetLength(0); r++) { for(int c = 0; c < map.GetLength(1); c++) { if (map[r, c] == 0) { //记录r c,一个空位置 //类[数据类型] 类数据成员[多个类型] //将多个基本数据类型,封装为1个复合数据类型(自定义类型) emptyLocationList.Add(new Location(r, c)); } } } } private Random random; public void GenerateNumber() { CalculateEmpty(); if (emptyLocationList.Count > 0) { int randomIndex = random.Next(0, emptyLocationList.Count); Location loc = emptyLocationList[randomIndex]; map[loc.Rlndex, loc.Clndex] = random.Next(0, 10) == 1 ? 4 : 2; } } #endregion #region 游戏结束 //没有空位置 //不能合并 #endregion } }
Java
UTF-8
696
2.234375
2
[]
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 semestralnipracedbs; /** * * @author linvo */ public class Table { public static class DataRequest { String text; Object type; public DataRequest(String text, Object type) { this.text = text; this.type = type; } } String name; DataRequest[] dataRequest; public Table(String name, DataRequest[] dataRequest) { this.name = name; this.dataRequest = dataRequest; } }
C#
UTF-8
8,282
2.765625
3
[]
no_license
using MVVMSample.Infrastructure.Interfaces; using MVVMSample.Infrastructure.Wizard; using MVVMSample.Model; using MVVMSample.Model.Interfaces; using Products = MVVMSample.Model.Products; namespace MVVMSample.ViewModels.Wizards.Product { /// <summary> /// Parent Wizard that handles adding the steps and coordinating interactions between them /// </summary> public class ProductWizardViewModel : WizardBaseViewModel { //inject this dependency: private IProductRepository _productRepository; /// Simplify access to specific steps with properties that use the GetStep<T> helper method: public ProductTypeStepViewModel ProductTypeStepViewModel { get { return GetStep<ProductTypeStepViewModel>(); } } public ProductRequiredStepViewModel ProductRequiredStepViewModel { get { return GetStep<ProductRequiredStepViewModel>(); } } public ProductOptionalStepViewModel ProductOptionalStepViewModel { get { return GetStep<ProductOptionalStepViewModel>(); } } public SummaryStepViewModel SummaryStepViewModel { get { return GetStep<SummaryStepViewModel>(); } } public ProductWizardViewModel(IProductRepository productRepository, ILocalizationService localizationService) : base(localizationService) { _productRepository = productRepository; Steps.Add(new ProductTypeStepViewModel(localizationService)); Steps.Add(new ProductRequiredStepViewModel(localizationService)); Steps.Add(new ProductOptionalStepViewModel(localizationService)); //SummaryStepViewModel is shared between customer and product wizards: Steps.Add(new SummaryStepViewModel(localizationService)); } /// <summary> /// This method is called on back or next click and allows the parent wizard to show /// dialogs/progress messages and configure the next step based on the current step's properties /// </summary> /// <param name="eventArgs">Navigation EventArgs with info on Navigation Direction, Action, and current and new steps</param> protected override void OnNavigating(WizardNavigationEventArgs eventArgs) { if (eventArgs.NavigationType == WizardNavigationType.Next) { //figure out what step we're moving to: if (eventArgs.NewStep is ProductRequiredStepViewModel) SetRequiredFieldsViewModel(); else if (eventArgs.NewStep is ProductOptionalStepViewModel) SetOptionalFieldsViewModel(); else if (eventArgs.NewStep is SummaryStepViewModel) { //pause could be used to show a confirmation dialog or show a busymessage to run an async operation //you must call ContinueNavigation or CancelNavigation after calling pause! eventArgs.NavigationAction = WizardNavigationAction.Pause; CreateProduct(); } } } /// <summary> /// Set RequiredFieldsViewModel type based on selected product type /// </summary> private void SetRequiredFieldsViewModel() { if (ProductTypeStepViewModel.SelectedProductType == typeof (Products.Boat) && //second check is necessary so we don't always reset and clear user's previous textbox values //(They could've clicked back, made a change without modifying product type, and then clicked Next again) !(ProductRequiredStepViewModel.RequiredFieldsViewModel is RequiredBoatFieldsViewModel)) { ProductRequiredStepViewModel.RequiredFieldsViewModel = new RequiredBoatFieldsViewModel(LocalizationService); } else if (ProductTypeStepViewModel.SelectedProductType == typeof (Products.Car) && !(ProductRequiredStepViewModel.RequiredFieldsViewModel is RequiredCarFieldsViewModel)) { ProductRequiredStepViewModel.RequiredFieldsViewModel = new RequiredCarFieldsViewModel(LocalizationService); } } /// <summary> /// Set OptionalFieldsViewModel based on selected product type (exact same pattern as required step) /// </summary> private void SetOptionalFieldsViewModel() { if (ProductTypeStepViewModel.SelectedProductType == typeof(Products.Boat) && !(ProductOptionalStepViewModel.OptionalFieldsViewModel is OptionalBoatFieldsViewModel)) { ProductOptionalStepViewModel.OptionalFieldsViewModel = new OptionalBoatFieldsViewModel(LocalizationService); } else if (ProductTypeStepViewModel.SelectedProductType == typeof(Products.Car) && !(ProductOptionalStepViewModel.OptionalFieldsViewModel is OptionalCarFieldsViewModel)) { ProductOptionalStepViewModel.OptionalFieldsViewModel = new OptionalCarFieldsViewModel(LocalizationService); } } private void CreateProduct() { //tell the UI to show that an operation is running: IsBusy = true; BusyMessage = LocalizationService.GetLocalizedString("CreatingProduct"); Products.Product product = null; if (ProductTypeStepViewModel.SelectedProductType == typeof(Products.Car)) product = ConstructCar(); else if (ProductTypeStepViewModel.SelectedProductType == typeof(Products.Boat)) product = ConstructBoat(); //repository simulates long running async process and takes a callback: _productRepository.CreateProduct(product, ProductCreatedCallback); } /// <summary> /// Build the Car object from the step viewmodel properties if selected product type was car /// </summary> private Products.Car ConstructCar() { RequiredCarFieldsViewModel requiredFields = (RequiredCarFieldsViewModel)ProductRequiredStepViewModel.RequiredFieldsViewModel; OptionalCarFieldsViewModel optionalFields = (OptionalCarFieldsViewModel)ProductOptionalStepViewModel.OptionalFieldsViewModel; return new Products.Car(ProductTypeStepViewModel.Name, requiredFields.Make, requiredFields.Model, requiredFields.Year.Value, requiredFields.Color) { Description = ProductTypeStepViewModel.Description, HasGPS = optionalFields.HasGPS, HasSunroof = optionalFields.HasSunroof }; } /// <summary> /// Build the Product object from the step viewmodel properties if selected product type was Boat /// </summary> private Products.Boat ConstructBoat() { RequiredBoatFieldsViewModel requiredFields = (RequiredBoatFieldsViewModel)ProductRequiredStepViewModel.RequiredFieldsViewModel; OptionalBoatFieldsViewModel optionalFields = (OptionalBoatFieldsViewModel) ProductOptionalStepViewModel.OptionalFieldsViewModel; return new Products.Boat(ProductTypeStepViewModel.Name, requiredFields.EngineType, requiredFields.Length.Value) { Description = ProductTypeStepViewModel.Description, HasDTS = optionalFields.HasDTS, HasJoystick = optionalFields.HasJoystick }; } /// <summary> /// Invoked from ProductRepository when async process of creation completes /// </summary> /// <param name="response"></param> private void ProductCreatedCallback(ResponseCode response) { //tell UI the operation finished: IsBusy = false; //set the response on the summary step: SummaryStepViewModel.Response = response; //we are currently paused so we can show the progress in the UI. Call this to continue on to the summary step: ContinueNavigation(); } } }
Java
UTF-8
1,120
2.03125
2
[]
no_license
package com.rxjava.nan.rxjava_demo01.network; import com.rxjava.nan.rxjava_demo01.request.UserBaseInfoResponse; import com.rxjava.nan.rxjava_demo01.request.UserExtraInfoResponse; import com.rxjava.nan.rxjava_demo01.response.LoginResponse; import com.rxjava.nan.rxjava_demo01.response.RegisterResponse; import java.util.Map; import io.reactivex.Observable; import okhttp3.ResponseBody; import retrofit2.Response; import retrofit2.http.GET; import retrofit2.http.Query; import retrofit2.http.QueryMap; /** * Api接口 * Created by Nan on 2017/5/4. */ public interface Api { @GET("/") Observable<LoginResponse> login(@QueryMap Map<String, String> content); @GET("/") Observable<RegisterResponse> register(@QueryMap Map<String, String> content); @GET("/") Observable<UserBaseInfoResponse> getUserBaseInfo(@QueryMap Map<String, String> content); @GET("/") Observable<UserExtraInfoResponse> getUserExtraInfo(@QueryMap Map<String, String> content); @GET("v2/movie/top250") Observable<Response<ResponseBody>> getTop250(@Query("start") int start, @Query("count") int count); }
C++
UTF-8
1,805
2.859375
3
[]
no_license
#include <ArduinoRS485.h> #define LEDpinA 13 //PB5 #define LEDpinB 12 //PB4 #define LEDpinC 11 //PB3 #define LEDpinD 10 //PB2 boolean LEDpinA_state; boolean LEDpinB_state; boolean LEDpinC_state; boolean LEDpinD_state; int key = 0; int temp; int sensor = 0; void setup() { Serial.begin(9600); while (!Serial); RS485.begin(9600); // enable reception, can be disabled with: RS485.noReceive(); RS485.receive(); DDRB |= 0B00111110; //port PB5,4,3,2 output } void loop() { sensor = analogRead(A0); Serial.println(sensor); while (RS485.available()) { sensor = analogRead(A0); Serial.println(sensor); key = RS485.read(); Serial.write(key); if (key == 'A'){ PORTB = PORTB ^B00100000; // Remember LED state, lit or unlit. } else if (key == 'B'){ PORTB = PORTB ^B00010000; // Remember LED state, lit or unlit. } else if (key == 'C'){ PORTB = PORTB ^B00001000; // Remember LED state, lit or unlit. } else if (key == 'D'){ PORTB = PORTB ^B00000100; // Remember LED state, lit or unlit. } else if (key == '#'){ int count = 1; temp = PORTB; while (count<=5){ PORTB = 0B00111100; delay(175); PORTB = PORTB ^0B00111100; delay(75); count++; } PORTB = temp; } else if (key == '*'){ int count = 1; temp = PORTB; while (count<=5){ PORTB = 0B00100000; delay(50); PORTB = PORTB ^0B00110000; delay(50); PORTB = PORTB ^0B00011000; delay(50); PORTB = PORTB ^0B00001100; delay(50); PORTB = PORTB ^0B00000100; delay(50); count++; } tone(9, 6000, 500); // 20-24 microseconds delay(1000); PORTB = temp; } } }
C#
UTF-8
810
3.09375
3
[ "MIT" ]
permissive
using System; using EPubLibraryContracts; namespace EPubLibrary.PathUtils { public class PathElement : IPathElement { private readonly PathType _pathType; private readonly string _name; public PathElement(string name, PathType type) { if (string.IsNullOrEmpty(name) && type != PathType.Root) { throw new ArgumentException("Can't have empty name for non root path element"); } _pathType = type; _name = name; } public PathType Type { get { return _pathType; } } public string Name { get { return _name; } } public object Clone() { return MemberwiseClone(); } } }
Markdown
UTF-8
5,476
2.703125
3
[]
no_license
## Global Temperature Anomaly: Time Series Modeling #### Lucas Dwyer ##### https://github.com/AuraSinis/global_temperature_anomaly_forecasting ## Executive Summary #### Problem Statement - The potential impacts of climate change affect many facets of our everyday lives. - One important metric one can use to keep track of exactly how severely the climate has changed is the Global Temperature Anomaly (GTA), which is the rise in the global average temperature over the past few decades. - Forecasting the GTA years in advance is necessary in order to give prompt insight to policy makers regarding timetables for green climate policy changes. ##### Objective - Forecasting the annual global temperature anomaly and change in annual global temperature anomaly. ##### Data - The data was free to download from government and educational entitites. <br> <br> [Global Temperature Anomalies Dataset (NOAA)](https://www.ncdc.noaa.gov/cag/global/time-series/globe/land_ocean/ytd/12/1880-2020/data.csv)<br> <br> [World Methane Emissions Dataset (World Bank)](http://api.worldbank.org/v2/en/indicator/EN.ATM.METH.KT.CE?downloadformat=csv)<br> <br> [Global Annual Carbon ppm Historical Dataset (IAC)](ftp://data.iac.ethz.ch/CMIP6/input4MIPs/UoM/GHGConc/CMIP/yr/atmos/UoM-CMIP-1-1-0/GHGConc/gr3-GMNHSH/v20160701/mole_fraction_of_carbon_dioxide_in_air_input4MIPs_GHGConcentrations_CMIP_UoM-CMIP-1-1-0_gr3-GMNHSH_0000-2014.csv) <br> ##### Data Dictionary <br> - This is the data dictionary (once the data has been aggregated in the $aggr$ dataframe.) <br> | Feature | Feature | Data Type | Description | | |---------------------------------|----------------------|-----------|-------------------------------------------------------------------------------------------------------------------------------|---| | Temporal Anomaly | temp_anom | float64 | Global Average Temporal Anomaly (Annual) ($ºC$) | | | Temporal Anomaly 1st Difference | temp_a_diff_1 | float64 | Yearly Change in Global Average Temporal Anomaly (Annual) ($ºC/year$) | | | Temporal Anomaly 2nd Difference | temp_a_diff_2 | float64 | Yearly Change in the Yearly Change in Global Average Temporal Anomaly (Annual) ($ºC/(year^2)$) | | | World Methane | world_methane | float64 | Global Methane emissions in equivalence to kilotons of CO2 (Annual) ($kt$) | | | World Methane 1st Difference | world_methane_diff_1 | float64 | Yearly Change in the Global Methane emissions in equivalence to kilotons of CO2 (Annual) ($kt/year$) | | | World Methane 2nd Difference | world_methane_diff_2 | float64 | Yearly Change in the Yearly Change in the Global Methane emissions in equivalence to kilotons of CO2 (Annual) ($kt/(year^2)$) | | | World Carbon | world_carbon | float64 | Global Carbon levels in parts per million (Annual) ($ppm$) | | | World Carbon 1st Difference | world_carbon_diff_1 | float64 | Yearly Change in the Global Carbon levels in equivalence to kilotons of CO2 (Annual) ($ppm/year$) | | | World Carbon 2nd Difference | world_carbon_diff_2 | float64 | Yearly Change in the Yearly Change in the Global Carbon levels in equivalence to kilotons of CO2 (Annual) ($ppm/(year^2)$) | | | Target | target | float64 | The Temporal Anomaly 1st Difference, shifted once (to be predicted). (For example, 2002 has 2003's _temp_a_diff_1_ as it's _target_. | | ##### Performance Metrics<br> Mean Squared Error (MSE) is the primary metric considered for model benchmarking. <br> ##### Results<br> A simple ridge regression model on some engineered dataset did well in predicting the change in annual global temperature anomaly, as well as annual global temperature anomaly itself.<br> ##### Limitations<br> The model, while performing well, is fairly overfit.<br> #### Technical Pertinents<br> Jupyter Labs, statsmodels, and sklearn were the primary libraries used for the implementation. Models were evaluated by comparing their MSE scores against each other, and the R^2 values of each model on the testing and training data sets were used to examine for over/under fitting. There are limited _novel_ inferential deductions to be made; the correlation between methane and carbon emissions, and global temperature anomalies, are well documented. The first and second differences were taken of the three original features (global temperature anomaly, methane emissions, and carbon levels), and the target feature was taken as the shifted first difference of the global temporal anomaly (how much the global temporal anomaly will change between one year and the year after). The ridge model was finally selected as it out-performed all the other models (although realistically it tied with the non-PCA implemented LASSO model). Hyperparameters were tuned manually and through GridSearch().
Python
UTF-8
707
3.375
3
[]
no_license
# encoding: utf-8 """ @project:data_structure_and_algorithm @author: Jiang Hui @language:Python 3.7.2 [GCC 7.3.0] :: Anaconda, Inc. on linux @time: 2019/8/6 20:30 @desc: """ class Solution(object): def printMinNumber(self, nums): """ :type nums: List[int] :rtype: str """ if not nums: return '' nums = [str(x) for x in nums] from functools import cmp_to_key nums = sorted(nums, key=cmp_to_key(lambda x, y: int(x + y) - int(y + x))) return ''.join(nums).lstrip('0') or '0' # 去除输入中可能存在的0,如果只有'0',则返回'0' if __name__ == '__main__': print(Solution().printMinNumber([0, 12]))
Java
UTF-8
2,284
3.6875
4
[]
no_license
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class Hop { public static void main(String[] args) { if (0 < args.length) { String filename = args[0]; File file = new File(filename); ArrayList<Integer> nums = readNumbers(file); // Convert the list to an array int[] list = new int[nums.size()]; for (int i = 0; i < nums.size(); i++) { list[i] = nums.get(i); } //ArrayList<Integer> chosen = new ArrayList<Integer>(); //System.out.println(minJumps(list, 0, list.length, chosen)); //System.out.println(chosen); jumper(list); // Go get the shortest hops } else { System.out.println("Failure: File not found!"); } } /* * Read the passed file and return a list of numbers stored in * that file. */ public static ArrayList<Integer> readNumbers(File file) { ArrayList<Integer> nums = new ArrayList<Integer>(); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); String line = null; while((line = reader.readLine()) != null) { nums.add(Integer.parseInt(line)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { } } return nums; } public static void jumper(int[] list) { List<Integer> chosen = new ArrayList<Integer>(); jumper(list, 0, list.length, chosen); } private static void jumper(int[] a, int start, int end, List<Integer> chosen) { if (a[start] == 0) { // Value is 0, cannot move forward return; } else if (start == end) { // start and end indices same. return; } else { int val = a[start]; // value at the index // Build an array of all possible "hops" in descending order int[] hops = new int[val]; for (int i = 1; i <= val; i++) { hops[i - 1] = i; } // explore these hops in descending order for (int i = hops.length - 1; i > -1; i--) { chosen.add(hops[i]); jumper(a, start + 1, a[start] + a[i], chosen); //chosen.remove(chosen.size() - 1); } } } }
Python
UTF-8
439
3.34375
3
[]
no_license
from tkinter import* import random tk = Tk() canvas = Canvas(tk, width=400, height=400) canvas.pack() def rectangulo_aleatorio(ancho,alto, relleno): x1 = random.randrange(ancho) y1 = random.randrange(alto) x2 = x1 + random.randrange(ancho) y2 = y1 + random.randrange(alto) canvas.create_rectangle(x1,y1,x2,y2, fill=relleno) def escribiendo(): canvas.create_text(150,100,text='estoy escribiendo e tkinter')
JavaScript
UTF-8
313
2.859375
3
[]
no_license
function treeHeight(root) { if ( !root ) return -1; if ( !root.left && !root.right ) return 0; let left = 0; let right = 0; if (root.left) left = treeHeight(root.left) + 1; if (root.right) right = treeHeight(root.right) + 1; return Math.max(left, right); } module.exports = { treeHeight };
C#
UTF-8
4,004
3.46875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using TrainingModel.Models; namespace TrainingSolution { class Program { static void Main(string[] args) { Console.WriteLine("************** Course Name [Course ID]************************"); var courses = new Course(); courses.AddCourse(1,"Python Course" ); courses.AddCourse(2, "Full Stack"); courses.AddCourse(3, "Architecture Program"); //foreach (var course in courseLst) //{ // Console.WriteLine(""+ course.CourseId + ". "+course.CourseName+""); //} Console.WriteLine("************** Training ************************"); var training = new Trainings(); //Basic Python Training, WebDevelopment, Design Principle //Basic Python Training = new List<Trainings>(); training.AddTraining(new Course(){ CourseId = 1, CourseName = "Python Course" },"BasicPythonTraining", "hr1", 100); training.AddTraining(new Course() { CourseId = 1, CourseName = "Python Course" }, "WebDevelopment", "hr2", 200); training.AddTraining(new Course() { CourseId = 1, CourseName = "Python Course" }, "DesignPrinciple", "hr3", 300); Console.WriteLine("[CourseId] [TrainingName] [HR] [Cost]"); training.DisplayTrainings(); Console.WriteLine("\n\nSelect the Course to add training or enter 0 to exit"); courses.DisplayCourses(); int courseId = Convert.ToInt32(Console.ReadLine()); while (courseId!=0) { switch (courseId) { case 1: Console.WriteLine("\nAdd new training to Python Course"); Console.WriteLine("Enter the Name,Hr,Cost separated by comma"); string[] values = Console.ReadLine()?.Split(','); training.AddTraining(new Course() {CourseId = courseId, CourseName = "Python Course"}, values[0], values[1], Convert.ToInt32(values[2])); break; case 2: Console.WriteLine("\nAdd new training to Full Stack"); Console.WriteLine("Enter the Name,Hr,Cost separated by comma"); string[] values1 = Console.ReadLine()?.Split(','); training.AddTraining(new Course() {CourseId = courseId, CourseName = "Full Stack"}, values1[0], values1[1], Convert.ToInt32(values1[2])); break; case 3: Console.WriteLine("\nAdd new training to Architecture Program"); Console.WriteLine("Enter the Name,Hr,Cost separated by comma"); string[] values2 = Console.ReadLine()?.Split(','); training.AddTraining(new Course() {CourseId = courseId, CourseName = "Architecture Program"}, values2[0], values2[1], Convert.ToInt32(values2[2])); break; default: Console.WriteLine("Select a valid course"); break; } Console.WriteLine("Training Added Successfully..!!!!!\n\n"); Console.WriteLine("[CourseId] [TrainingName] [HR] [Cost]"); foreach (var trainings in training.trainings.ToList()) { Console.WriteLine(" " + trainings.CourseDetails.CourseId + " " + trainings.Name + " " + trainings.TrainingHR + " " + trainings.Cost + ""); } Console.WriteLine("\n\nSelect the Course to add training or enter 0 to exit"); courses.DisplayCourses(); courseId = Convert.ToInt32(Console.ReadLine()); } } } }
SQL
UTF-8
1,946
3.359375
3
[]
no_license
CREATE TABLE purchase ( pur_num NUMERIC(8,0), sup_id VARCHAR(8), complete_date VARCHAR(8), item_num NUMERIC(8,0), quantity NUMERIC(8,0), unit_cost NUMERIC(8,0), note VARCHAR(20), PRIMARY KEY (pur_num, complete_date) ); CREATE TABLE factory ( fac_id VARCHAR(8), fac_name VARCHAR(15), address VARCHAR(34), zip_code VARCHAR(5), phone VARCHAR(12), manager VARCHAR(8), PRIMARY KEY (fac_id) ); CREATE TABLE skill ( sk_code VARCHAR(8), sk_title VARCHAR(21), sk_description VARCHAR(30), sk_level VARCHAR(12) CHECK(sk_level IN ('beginner', 'intermediate', 'advanced')), PRIMARY KEY (sk_code) ); CREATE TABLE person ( per_id VARCHAR(8), last_name VARCHAR(20), first_name VARCHAR(20), address VARCHAR(31), zip_code VARCHAR(5), email VARCHAR(24), gender VARCHAR(6), PRIMARY KEY (per_id) ); CREATE TABLE position ( pos_code VARCHAR(8), pos_title VARCHAR(34), description VARCHAR(122), pay_range_high NUMERIC(8,0), pay_range_low NUMERIC(8,0), PRIMARY KEY (pos_code) ); CREATE TABLE job ( job_code VARCHAR(8), j_title VARCHAR(22), fac_id VARCHAR(8), pos_code VARCHAR(8), per_id VARCHAR(8), emp_mode VARCHAR(9), pay_rate NUMERIC(8,0), pay_type VARCHAR(9), cate_code VARCHAR(8), company VARCHAR(9), PRIMARY KEY (job_code), FOREIGN KEY (per_id) REFERENCES person ON DELETE SET NULL, FOREIGN KEY (pos_code) REFERENCES position ON DELETE SET NULL, FOREIGN KEY (fac_id) REFERENCES factory ON DELETE SET NULL ); CREATE TABLE requires ( sk_code VARCHAR(8), pos_code VARCHAR(8), PRIMARY KEY (pos_code, sk_code), FOREIGN KEY (sk_code) REFERENCES skill ON DELETE CASCADE, FOREIGN KEY (pos_code) REFERENCES position ON DELETE CASCADE ); CREATE TABLE has_skill ( per_id VARCHAR(8), sk_code VARCHAR(8), PRIMARY KEY (per_id, sk_code), FOREIGN KEY (per_id) REFERENCES person ON DELETE CASCADE, FOREIGN KEY (sk_code) REFERENCES skill ON DELETE CASCADE );
Rust
UTF-8
2,638
2.96875
3
[ "MIT" ]
permissive
use std::marker::PhantomData; use macroquad::prelude::{is_key_down, KeyCode, Vec2}; use rand::{rngs::ThreadRng, Rng}; use crate::entity::creature::Creature; use crate::entity::{Object, Physics}; pub trait Controller<A> { /// Update the controller /// # Arguments /// `object` - The object to control /// `secs` - The time elapsed sinced last update fn update(&mut self, _object: &mut A, _secs: f32) {} } pub struct NoneController<A>(PhantomData<A>); impl<A: Object> NoneController<A> { pub fn new() -> NoneController<A> { Self(PhantomData) } } impl<A: Object> Controller<A> for NoneController<A> { // Just use default trait implementations } /// A controller that controls objects using the keyboard pub struct KeyboardController; impl KeyboardController { pub fn new() -> KeyboardController { KeyboardController } } impl Controller<Creature> for KeyboardController { fn update(&mut self, object: &mut Creature, _: f32) { let move_accel = object.move_accel; let x_accel = if is_key_down(KeyCode::Left) { -move_accel * if object.is_on_ground() { 1.0 } else { 0.6 } } else if is_key_down(KeyCode::Right) { move_accel * if object.is_on_ground() { 1.0 } else { 0.6 } } else { 0.0 }; let new_accel = Vec2::new(x_accel, object.acceleration().y); object.set_acceleration(new_accel); let jump_accel = object.jump_accel; if object.is_on_ground() && is_key_down(KeyCode::Up) { let new_velocity = object.velocity() + Vec2::new(0.0, -jump_accel); object.set_velocity(new_velocity); } } } /// A controller that controls objects using randomness pub struct RandomController { rng: ThreadRng, move_time: f32, wait_time: f32, } impl RandomController { pub fn new(move_time: f32) -> RandomController { RandomController { rng: rand::thread_rng(), move_time, wait_time: 0.0 } } } impl Controller<Creature> for RandomController { fn update(&mut self, object: &mut Creature, secs: f32) { self.wait_time += secs; if self.wait_time > self.move_time { let move_accel = object.move_accel; let x_accel = match self.rng.gen::<f32>() { dir if dir < 0.5 => 0.0, dir if dir < 0.75 => move_accel, _ => -move_accel, }; let new_accel = Vec2::new(x_accel, object.acceleration().y); object.set_acceleration(new_accel); self.wait_time -= self.move_time; } } }
Java
UTF-8
586
1.882813
2
[]
no_license
package com.example.after; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * Created by after on 2020/5/29. */ @RestController public class ConfigController { @Value("${server.port}") private int serverPort; @Value("${spring.application.name}") private String applicationName; @RequestMapping(value = "/test") public String getProperties() { return "result:" + applicationName + "," + serverPort; } }
JavaScript
UTF-8
2,593
3.734375
4
[]
no_license
// Soldier function Soldier(health, strength) { this.health = health; this.strength = strength; this.attack = function() { return this.strength; } this.receiveDamage = function(demage) { this.health -= demage; } } // Viking function Viking(name, health, strength) { this.name = name; Soldier.call(this, health, strength); this.attack = function() { return this.strength; } this.receiveDamage = function(demage) { this.health -= demage; if(this.health > 0) { return this.name + ' has received ' + demage + ' points of damage'; } else { return this.name + ' has died in act of combat'; } } this.battleCry = function(){ return 'Odin Owns You All!'; } } Viking.prototype = Object.create(Soldier.prototype); // Saxon function Saxon(health, strength){ Soldier.call(this, health, strength); this.receiveDamage = function(demage){ this.health -= demage; if(this.health > 0) { return 'A Saxon has received ' + demage + ' points of damage'; } else { return 'A Saxon has died in combat'; } } } Saxon.prototype = Object.create(Soldier.prototype); // War function War() { this.vikingArmy=[]; this.saxonArmy =[]; this.addViking = function (viking) { this.vikingArmy.push(viking); }; this.addSaxon = function (saxon) { this.saxonArmy.push(saxon); }; this.vikingAttack = function(){ var index = Math.floor(Math.random() * this.vikingArmy.length); this.saxon = this.saxonArmy[Math.floor(Math.random() * this.saxonArmy.length)]; this.viking = this.vikingArmy[index]; var result = this.saxon.receiveDamage(this.viking.strength); if( this.saxon.health <= 0){ this.saxonArmy.splice(index, 1); } return result; }; this.saxonAttack = function() { var index = Math.floor(Math.random() * this.vikingArmy.length); this.viking = this.vikingArmy[index]; this.saxon = this.saxonArmy[Math.floor(Math.random() * this.saxonArmy.length)]; var result = this.viking.receiveDamage(this.saxon.strength); if( this.viking.health <= 0){ this.vikingArmy.splice(index, 1); } return result; }; this.showStatus = function() { if(this.saxonArmy.length === 0){ return "Vikings have won the war of the century!"; } if(this.vikingArmy.length === 0){ return "Saxons have fought for their lives and survive another day..."; } if((this.vikingArmy.length >= 1) && (this.saxonArmy.length >=1)){ return "Vikings and Saxons are still in the thick of battle." } }; }
Ruby
UTF-8
235
3.1875
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby # This is only a sample file used in the tests. class Sample attr_reader :x, :y def initialize @x = 1 @y = 2 end def inspection x.inspect y.inspect end end s = Sample.new s.inspection
Shell
UTF-8
616
3.375
3
[]
no_license
#! /bin/bash prepare_list_grobner() { cat tmp/grobner-$d1-$d2-$d3-$d4-$d \ | grep -v Coefficient \ | grep -v Allocate \ > tmp/list_grobner } run_gp() { cat tmp/list_grobner | while read lijn do naam=$(echo "$lijn" | sed "s/ /-/g") gp -f -q tmp/$d1-$d2-$d3-$d4-$d/$naam do_it.gp >> tmp/$d1-$d2-$d3-$d4-$d/$naam done } cat tmp/list | while read line do arr=($line) d1=${arr[0]} d2=${arr[1]} d3=${arr[2]} d4=${arr[3]} d=${arr[4]} grep -q "$d1 $d2 $d3 $d4 $d" tmp/list_done if [ $? == 0 ]; then echo "This case: $d1 $d2 $d3 $d4 $d already done" exit 1 fi prepare_list_grobner run_gp done
JavaScript
UTF-8
832
3.078125
3
[ "Apache-2.0" ]
permissive
const BUFFER_SIZE = 4096; function createWhiteNoiseNode(audioContext, level = 0.1) { const inputChannels = 1; const outputChannels = 1; const node = audioContext .createScriptProcessor(BUFFER_SIZE, inputChannels, outputChannels); node.addEventListener('audioprocess', (e) => { for (let channelIndex = 0; channelIndex < e.outputBuffer.numberOfChannels; channelIndex++) { const output = e.outputBuffer.getChannelData(channelIndex); for (let bufferIndex = 0; bufferIndex < BUFFER_SIZE; bufferIndex++) { output[bufferIndex] = _whiteNoiseSample(); } } }); const gainNode = audioContext.createGain(); gainNode.gain.value = level; node.connect(gainNode); return gainNode; } function _whiteNoiseSample() { return (Math.random() * 2) - 1 } export { createWhiteNoiseNode, };
Markdown
UTF-8
61,964
2.5625
3
[ "Apache-2.0" ]
permissive
--- title: Maintaining high availability during network partitions for virtual machines stored on distributed object-based storage abstract: Techniques are disclosed for maintaining high availability (HA) for virtual machines (VMs) running on host systems of a host cluster, where each host system executes a HA module in a plurality of HA modules and a storage module in a plurality of storage modules, where the host cluster aggregates, via the plurality of storage modules, locally-attached storage resources of the host systems to provide an object store, where persistent data for the VMs is stored as per-VM storage objects across the locally-attached storage resources comprising the object store, and where a failure causes the plurality of storage modules to observe a network partition in the host cluster that the plurality of HA modules do not. In one embodiment, a host system in the host cluster executing a first HA module invokes an API exposed by the plurality of storage modules for persisting metadata for a VM to the object store. If the API is not processed successfully, the host system: (1) identifies a subset of second HA modules in the plurality of HA modules; (2) issues an accessibility query for the VM to the subset of second HA modules in parallel, the accessibility query being configured to determine whether the VM is accessible to the respective host systems of the subset of second HA modules; and (3) if at least one second HA module in the subset indicates that the VM is accessible to its respective host system, transmits a command to the at least one second HA module to invoke the API on its respective host system. url: http://patft.uspto.gov/netacgi/nph-Parser?Sect1=PTO2&Sect2=HITOFF&p=1&u=%2Fnetahtml%2FPTO%2Fsearch-adv.htm&r=1&f=G&l=50&d=PALL&S1=09513946&OS=09513946&RS=09513946 owner: VMware, Inc. number: 09513946 owner_city: Palo Alto owner_country: US publication_date: 20140627 --- Virtual machine high availability referred to herein simply as high availability or HA and hypervisor converged object based HC OB storage are two emerging technologies in the field of computer virtualization. HA is designed to minimize virtual machine VM downtime by monitoring the availability of host systems and VMs in a host cluster. If an outage such as a host or network failure causes one or more VMs to stop executing HA detects the outage and automatically restarts the affected VMs on active host systems in the cluster. In this way HA ensures that guest applications running within the VMs continue to remain operational throughout the outage. One exemplary HA implementation is described in commonly assigned U.S. Patent Application Publication No. 2012 0278801 published Nov. 1 2012 entitled Maintaining High Availability of a Group of Virtual Machines Using Heartbeat Messages. HC OB storage is a distributed software based storage technology that leverages the local or direct attached storage resources e.g. solid state disks spinning hard disks etc. of host systems in a host cluster by aggregating these locally attached resources into a single logical storage pool. Thus this technology effectively re purposes the host cluster to also act as a distributed storage cluster. A hypervisor based storage system layer referred to herein generically as a VSAN layer comprising VSAN modules manages the logical storage pool and enables interactions between the logical storage pool and storage clients such as VMs running on host systems in the cluster. For example the VSAN layer allows the VMs to access the logical storage pool during VM runtime in order to store and retrieve persistent VM data e.g. virtual disk data . The qualifier object based in hypervisor converged object based storage refers to the manner in which VMs are maintained within HC OB storage in particular the state of each VM is organized as a hierarchical collection of distinct storage objects or simply objects . For example the files that hold the metadata configuration of a VM may reside in a file system that is created within a namespace object also known as a file system object the virtual disks of the VM may reside in virtual disk objects and so on. Each of these storage objects may be composed of multiple component objects. The VSAN layer provisions manages and monitors each of these storage objects individually. For instance in order to meet a particular storage policy for a particular virtual disk VMDK the VSAN layer may determine that the component storage objects that make up the virtual disk object corresponding to VMDK should be striped across the locally attached storage of three different host systems. Through these and other mechanisms HC OB storage can provide improved ease of management scalability and resource utilization over traditional storage solutions. One exemplary implementation of an HC OB storage system is described in commonly assigned U.S. patent application Ser. No. 14 010 293 filed Aug. 26 2013 entitled Scalable Distributed Storage Architecture. Unlike non object based storage systems the state of a VM is not contained within a larger coarse storage container e.g. a LUN . Having such storage containers provide a couple of benefits. First a coarse storage container provides a convenient location to store information common to all VMs that use the container. For example it is possible to create a file system on top of a LUN create a directory within the file system for each VM whose state is stored on the underlying storage device s and then create a directory at the root to store shared information. Second for a given class of failures one can reason about the availability accessibility of all of the VM data stored within a storage container by reasoning about the availability accessibility of the container itself. For instance one can determine whether a network failure impacts the accessibility of the VM data by determining if the container is accessible. As a result there is no need to track the accessibility of each individual VM stored in a single storage container instead it is sufficient to track the accessibility of the container itself. The lack of coarse storage containers raises unique challenges when attempting to use HC OB storage and HA concurrently in the same virtualized compute environment. As one example existing HA implementations typically maintain information known as HA protection state that identifies the VMs in a host cluster that should be failed over restarted in the event of a failure. The master HA module in the cluster i.e. the HA module that is responsible for detecting failures and orchestrating VM failovers restarts manages this HA protection state by persisting it to a centralized file or set of files on the storage tier. If there is an outage that affects a subset of host systems in the cluster one or more new master HA modules may be elected. Each newly elected master HA module may then retrieve the file from the storage tier to determine which VMs are HA protected. This approach works well if the storage tier is implemented using dedicated shared storage since the HA protection file can be placed in the storage container storing the configurations for the protected VMs. On the other hand if the storage tier is implemented using HC OB storage there is no convenient location to store such information that is shared across VMs. As another example in existing HA implementations when a master HA module detects a failure that requires one or more VMs to be failed over restarted the master HA module executes a conventional failover workflow that involves 1 identifying active host systems for placing the VMs that can meet the VMs resource needs and 2 initiating VM restarts on the identified host systems. If the VMs are stored on dedicated shared storage these two steps are generally sufficient for successfully completing the failover. However if the VMs are stored on HC OB storage there may be cases where a VM cannot be restarted because one or more of its storage objects are not yet accessible to the host system executing on the master HA module and or to the host system on which the restart is being attempted . This situation cannot be uncovered using conventional coarse grained storage accessibility checks. This in turn can cause the conventional failover workflow to break down or result in multiple continuous restart attempts which can increase the load on the affected host systems. As yet another example there are certain types of network partitions that can further complicate the HA protection state persistence and VM failover restart workflows noted above. As one example if there is a failure that causes the VSAN modules to observe a partition while the HA modules do not there may be instances where the host system on which the master HA module is running does not have access visibility to a particular VM and thus cannot update retrieve HA protection state information for the VM or determine its accessibility for failover purposes while the host systems of other slave HA modules do have such access visibility. Accordingly it would be desirable to have techniques for integrating HA with distributed object based storage systems like HC OB storage that overcome these and other similar issues. The present disclosure describes techniques that allow high availability HA to be provided for VMs that are stored on distributed object based storage. In one set of embodiments the techniques can include persisting by a master HA module HA protection state for VMs in a host cluster on a per VM basis rather than in a centralized file in the logical storage pool of the distributed object based storage system. For example in a particular embodiment the master HA module can persist HA protection state for a given VM as metadata for the VM s namespace object. With this approach the master HA module can avoid scenarios where it can access the VM itself but cannot access the VM s protection state or vice versa . This approach also provides performance benefits when a newly elected master HA module needs to retrieve the persisted protection state information. In another set of embodiments the techniques can include modifying the conventional failover restart workflow performed by the master HA module to account for potential VM inaccessibility at the time of failover. With these modifications the master HA module can more gracefully deal with situations where a VM has been identified as a failover candidate but some critical subset of the VM s storage objects remains unavailable. In yet another set of embodiments the techniques can include enhancements to both the HA protection state persistence and restart failover workflows mentioned above so that they can operate more effectively in specific network partition scenarios. In the sections that follow numerous examples and details are set forth in order to provide a thorough understanding of various embodiments. It should be appreciated however that certain embodiments can be practiced without some of these details or can be practiced with modifications or equivalents thereof. For instance although examples are provided for integrating HA with HC OB storage in particular the techniques of the present disclosure may also be used to integrate HA functionality with other types of storage systems that exhibit characteristics similar to HC OB systems e.g. distributed object based storage systems that expose multiple distinct ingress access points to storage clients . Further although certain embodiments are discussed in the context of a HA system that relies on a master slave model comprising at least one master HA module and multiple slave HA modules the present techniques are applicable to any distributed high availability system designed to monitor the liveliness of VMs and failover such VMs in the case of failures regardless of the manner in which the HA modules interoperate e.g. master slave peer to peer etc. . For example in a peer to peer HA implementation the functions attributed to the master HA module in the sections below may be performed by one or more peer HA modules. One of ordinary skill in the art will recognize many variations modifications and alternatives. For purposes of this disclosure a VM is said to be stored on distributed object based e.g. HC OB storage if the VM s configuration e.g. vmx file is maintained within the storage system s logical storage pool sometimes referred to herein as the object store . Other state information for the VM e.g. virtual disk data may also be maintained within the HC OB storage pool or may be stored on traditional shared storage. Further a VM is said to be accessible by to a host system or a module thereof such as a HA module running on the host system if all of its storage objects can be accessed by the host system. The VM is inaccessible if these requirements are not met. Alternatively in some embodiments a VM may be considered accessible if some user defined subset of required storage objects can be accessed by the host system. One exemplary object structure for a VM which can include e.g. a namespace object one or more virtual disk objects and so on is described in Section 1.1 below. To provide context for the techniques described herein depicts a virtualized compute environment that implements both HC OB storage and HA according to an embodiment. As shown environment includes a host cluster comprising host systems M a virtualization management platform and a conceptual HC OB storage component . Host cluster and constituent host systems M provide virtualized compute resources within environment . For example each host system M includes a virtualization layer or hypervisor M through which the host system can execute one or more VMs M . As part of its responsibilities each hypervisor can manage the physical hardware M of its respective host system e.g. CPU memory etc. to make these hardware resources available in appropriate amounts to running VMs. Virtualization management platform is an entity that allows users to perform administrative and management tasks with respect to host cluster such as configuring and managing the lifecycles of VMs M running on host systems M . Virtualization management platform can also interact with host systems M to enable facilitate certain inter host features such as VM migrations distributed resource scheduling and so on. HC OB storage is a conceptual representation of a distributed software based storage tier that provides storage services to host cluster . For instance HC OB storage can be used to store the persistent state of VMs M running on host systems M . As shown in HC OB storage comprises a logical storage pool i.e. object store that is an aggregation of local storage resources M that are locally attached i.e. housed in or attached via a point to point link to host systems M . These local storage resources may include e.g. commodity SSDs commodity spinning hard disks and other types of non volatile memory. Since object store of HC OB storage is composed entirely of aggregated host side storage there is no physical distinction between the storage tier of environment represented by HC OB storage and the compute tier of environment represented by host cluster . They are from a physical perspective one and the same. Per its designation as an object based storage component HC OB storage stores data such as VM state in the form of distinct storage objects. As noted in the Background section these storage objects can be provisioned managed and monitored on an individual basis. Thus unlike non object based storage systems that typically group together the states for multiple VMs into a coarse storage container e.g. a LUN or file system container HC OB storage can provide granular performance isolation per VM or per virtual disk quality of service and other features that are beneficial in virtualized compute environments like environment . To manage and provide access to HC OB storage hypervisors M of host systems M include a software based storage management i.e. VSAN layer comprising VSAN modules M . As shown VSAN modules M are interconnected via a management network . Although a comprehensive discussion of the operation of VSAN modules M is beyond the scope of this disclosure VSAN modules M are responsible for among other things enabling interactions between the storage tier represented by HC OB storage and storage clients or other external entities. For example in one set of embodiments VSAN modules M can automate the creation of storage objects in object store for new VMs and or virtual disks that are provisioned by e.g. administrators via virtualized management platform . In another set of embodiments VSAN modules M can process VM I O requests that are directed to e.g. virtual disks swap space etc. on object store such that those I O requests are properly routed to the host systems in cluster that house the local storage resources backing the storage objects associated with the requested virtual disk data. In yet another set of embodiments VSAN modules M can expose APIs that allow other entities modules to e.g. modify storage object metadata query information regarding the status or accessibility of certain storage objects or groups of objects and more. To clarify how VSAN modules M may create a storage object representation of a newly provisioned VM in object store depicts an example object structure for a VM running on host system according to an embodiment. As shown object structure includes a top level namespace object that is one of multiple namespace objects in object store . Namespace object corresponds to a representation of a file system such as VMFS NFS etc. that is used to store the files of VM that represent part of the VM s state. In the specific embodiment of namespace object includes a configuration file for VM identified by the path vsan fs vm.vmx and a virtual disk descriptor file for a virtual disk used by VM identified by the path vsan fs disk.vmdk . The virtual disk descriptor file within namespace object includes in turn a pointer to a composite virtual disk object distinct from namespace object that conceptually represents virtual disk . Object includes metadata that describes a storage organization or configuration for virtual disk referred to as an object blueprint . In one embodiment VSAN modules M may create this object blueprint at the time virtual disk is provisioned based on one or more storage profiles for the virtual disk that are specified by e.g. an administrator. Object also includes references to a number of component objects . Component objects hold the actual data for virtual disk in accordance with the storage configuration identified in object blueprint . For example in component objects correspond to data stripes in a RAID 1 RAID 0 configuration per object blueprint . Finally as shown via the lines interconnecting component objects with host systems and these component objects map to specific storage locations on the local storage resources of host systems respectively that back the data stripes represented by the objects. Like object blueprint VSAN modules M may determine these mappings in a way that satisfies one more storage profiles defined for virtual disk . It should be appreciated that object structure of is illustrative and not intended to limit the embodiments described herein. Generally speaking object structure may include objects corresponding to any type of storage entity that VM may consume use such as swap objects memory checkpoint objects file shares which are themselves contained within objects and so on. One of ordinary skill in the art will recognize many variations modifications and alternatives. As part of the process of creating object structure within object store and at potentially other times VSAN modules M can cache in an in memory database that is synchronized and replicated on every host system detailed information regarding object structure such as what composite and component objects are included in the structure the relationships between objects metadata associated with each object and the mapping of objects to physical storage locations. In this way each VSAN module M can have this information readily available for e.g. recovery or I O request processing purposes without needing to access object store . VSAN modules M may also use in memory database to cache other types of information that are relevant to their management of HC OB storage such a physical inventory of the local storage resources in host cluster the performance characteristics of each local storage resource quality of service requirements cluster topology health and more. In addition to VSAN modules M each hypervisor M of host cluster includes a HA module M . In the embodiment of HA modules M are communicatively coupled via a management network that is separate from management network interconnecting VSAN modules M . However in alternative embodiments HA modules M and VSAN modules M may share the same management network. Collectively HA modules M allow for high availability of VMs M running within host cluster . For example according to a typical HA implementation when HA is first turned on via e.g. virtualization management platform HA modules M can communicate with each other to elect a master HA module. The master HA module is generally responsible for e.g. monitoring the health of hosts and VMs in the cluster orchestrating VM failovers restarts in case of a failure reporting cluster state and failover actions to virtualization management platform and managing HA protection state. This last function involves managing information regarding which VMs in host cluster should be protected for HA purposes. In existing HA implementations the master HA module typically persists this HA protection state information to a centralized file on the storage tier discussed in greater detail in Section 2 below . The remaining non master modules can configure themselves to act as slave HA modules. Each slave HA module is generally responsible for e.g. monitoring and forwarding local host VM state changes to the master HA module locally restarting VMs on its host system when directed by the master HA module and participating in master election. When the master HA module detects a host VM network outage by e.g. determining that it is no longer in communication with one or more slave HA modules the master HA module can execute a failover restart workflow for automatically restarting the VMs that are rendered inoperable by the failure. At a high level this workflow can include identifying the VMs to be restarted placing those VMs on active host systems in cluster that have available capacity and then transmitting commands to the slave HA modules on the respective host systems to initiate the restart process for each VM. In this manner the master HA module together with the slave HA modules can ensure that the guest applications running within the affected VMs remain operational throughout the outage. In addition whenever one or more of HA modules M are no longer in contact with a master HA module those modules can perform a re election to elect a new master. This may occur if e.g. a failure in management network causes some subset of HA modules M to become partitioned from another subset including the current master HA module or if the host system running the master HA module fails or becomes network isolated. In these situations the cluster may comprise multiple master HA modules one master per partition . This will remain the case until the failure s causing the network partition s are resolved at which point all but one master HA module will abdicate. For purposes of illustration depicts an exemplary HA module comprising various functional components according to an embodiment. These functional components generally map to the host VM monitoring failover orchestration HA protection state management local restart and master election functions attributed to HA modules M in the description above. Depending on the HA implementation HA module can also include other components or sub components that are not specifically shown. or exclude one or more of the existing components. For instance some HA implementations may not use a master slave model and instead implement group messaging among HA modules in virtual synchrony. In these and similar embodiments there would be no need for e.g. master election component . One of ordinary skill in the art will recognize many variations modifications and alternatives. As mentioned previously in existing HA implementations the master HA module of a host cluster generally saves HA protection state for the VMs running within the cluster to one or more centralized files on persistent storage. This arises out of the need for newly elected master HA modules to determine at the time they are elected which VMs should be protected for HA purposes. Without persisting this information in some way the newly elected masters have no way of knowing which VMs they should monitor and failover restart in the case of a failure since the original master HA module that previously maintained this information may have failed or become network isolated or partitioned . By way of example depicts an exemplary flowchart that may be performed by a master HA module for persisting HA protection state to a centralized file according to an existing HA implementation. In particular illustrates HA protection state processing that occurs when a VM is first powered in the master HA module s host cluster. At block a user issues a power on command for a given VM. At block the host system on which the VM is registered performs a power on operation and reports the powered on status of the VM to the virtualization management platform for the cluster. In response the virtualization management platform informs the master HA module that the VM should be HA protected block . At block the protection state management component of the master HA module stores the HA protection state for the VM in memory so that it can be quickly retrieved by the master HA module on demand . Finally at block the protection state management component writes the HA protection state for the VM to a centralized protection file on the storage tier of the cluster so that it can be retrieved by other newly elected master HA modules in the case that the current master goes down or becomes unavailable . While the approach for persisting HA protection state shown in works well in environments where the storage tier is implemented using dedicated shared storage e.g. a SAN or NAS based storage array it can be problematic for environments where the storage tier is implemented using distributed object based storage like HC OB storage of . This is due to the varying and potentially asymmetric nature of object accessibility in such distributed storage systems if the HA protection state is maintained in a centralized file in HC OB storage which in turn would be persisted as one or more storage objects across the HC OB object store there may be cases where a master HA module cannot access the file even if the master HA module can access the VMs themselves. For example assume that the centralized HA protection file is stored as two storage objects across hosts H and H of a host cluster comprising hosts H H H H and H. If a failure causes H and H to be partitioned from H H and H a master HA module in the H H H partition will not be able to restart any VMs because it will not have access to the HA protection file in the H H partition. This would remain true even if all of the VMs in the cluster were maintained within and thus accessible from the H H H partition. Further after a network partition is resolved merging updates to the HA protection file that are performed during the partition can be complicated or may not be possible at all . To address the foregoing and other similar issues in certain embodiments each master HA module can persist the HA protection state for a VM within one or more storage objects of the VM on the HC OB storage tier rather than in a centralized file. Stated another way each master HA module can co locate the HA protection state for a VM with the persistent configuration of that specific VM. With this approach if a host master HA module can access the VM s configuration information on HC OB storage the host master HA module can also access the VM s protection state information and thus the master HA module can make an attempt to failover restart the VM as needed . This also ensures that when a VM is powered on the master HA module in the cluster partition where the VM is registered will always be able to persist the HA protection state for the VM. There are a number of different ways in which HA protection state can be co located with VM state in HC OB storage e.g. as a distinct file the VM s file system as object metadata etc. . According to a particular embodiment each master HA module can store the HA protection state for a given VM as part of the metadata of the VM s namespace object in the HC OB object store. This embodiment can be advantageous in certain scenarios. For example recall that each VSAN module caches in a synchronized in memory database i.e. database of information about the storage objects in the object store. As part of this process in some embodiments each VSAN module can automatically cache the metadata for each VM namespace object and potentially other storage objects in the in memory database. Thus in these embodiments when a newly elected master HA module needs to retrieve the HA protection state for all VMs in a cluster partition e.g. following a failure or at other times the newly elected HA module can query the VSAN layer which in turn can quickly retrieve the HA protection state from the in memory database rather than from HC OB storage . This can significantly speed up the protection state retrieval process which is important since any lag between the time a master HA module is elected and the time at which it knows which VMs to protect can potentially result in unhandled failures. If the HA protection state for each VM were stored as a separate file within each VM s file system the VSAN layer or some other component would need to discover all of the file locations enumerate the files and then open read close each file which can be a very time consuming process. At block master HA module X can receive a list of one or more VMs to be HA protected from e.g. virtualization management platform . This may occur when one or more VMs are powered on as in flowchart of or at other times. In one embodiment the list of VMs identifies the VMs as well as the host systems on which the VMs are registered for execution. At block master HA module X can enter a loop for each VM. Within the loop protection state management component of master HA module X can first store HA protection state for the VM in memory. The HA protection state can be embodied in various ways such as a protected flag or some other value. Protection state management component can then invoke e.g. a SET API exposed by the VSAN layer for persisting the VM s HA protection state as metadata for the VM s namespace object in HC OB object store block . In a particular embodiment this API can be a generic metadata SET API that can be used to update any metadata field of the namespace object. In this embodiment the generic SET API can take as input a key value pair that identifies the metadata field to be populated and the corresponding value. The generic SET API can also optionally take as input a service identifier that identifies the service component or layer that is performing the metadata update in this case HA . In other embodiments the SET API can be specifically tailored to set HA protection state within the namespace object. Upon receiving the invocation of the SET API the VSAN layer in particular the VSAN module of the host system on which the master HA module is located in concert with potentially other VSAN modules on other host systems can cause the HA protection state for the VM to be added to the VM s namespace object metadata in object store block . As noted above the HA protection state can be stored as e.g. a protected flag or some similar indicator value. The VSAN layer can subsequently cache the HA protection state in in memory database and return a completion message to master HA module X . In response master HA module X can reach the end of the VM loop block and iterate though blocks until all of the VMs have been processed. It should be noted that although flowchart and certain other subsequent flowcharts illustrate VMs as being processed serially in a loop in alternative embodiments these steps can be carried out on multiple VMs at the same time e.g. via batching . Further in cases where the host system on which master HA module X is running cannot access HC OB storage master HA module X can cause the SET API described above to be executed via a slave HA module. For example master HA module X can send a message to the slave HA module to invoke the API or can directly invoke the API via a remote procedure call. This embodiment is described in further detail in Section 4.2 below. At block protection state management component of master HA module Y can invoke a VSAN GET API for retrieving the HA protection state for the VMs in host cluster from object store . Like the SET API discussed with respect to block of this GET API can be a generic API that can be used to retrieve the value s of any metadata field of any namespace object or group of namespace objects or a non generic API that is specifically designed for retrieving HA protection state. At block the VSAN layer can receive the API invocation and can consult in memory database to retrieve and return the requested HA protection state to master HA module Y . This step can comprise e.g. accessing the cached namespace object metadata for each VM in database . As mentioned previously since the VSAN layer does not need to hit physical storage in order to perform this retrieval operation master HA module Y can more quickly determine which VMs it needs to protect when compared to other persistence techniques. Finally at block protection state management component of master HA module Y can determine the currently known set of HA protected VMs based on the information returned by the VSAN layer at block . In certain embodiments the API invocation at block of flowchart will only return the HA protection state information that the VSAN layer can access from HC OB storage at that time. Due to failures it is possible some HA protection state information is not accessible. To account for this situation in one embodiment not shown master HA module Y can re invoke the GET API after the VSAN layer informs the master HA module of a change in accessibility of any storage objects. This re invocation may cause the master HA module to determine that additional VMs are in fact HA protected. It should be appreciated that the embodiments described above are illustrative and that other approaches are also possible for persisting managing HA protection state for VMs stored on HC OB storage. For example according to one alternative approach the VSAN layer itself may be modified to support the storage of a file that can be concurrently accessed by host systems in different network partitions. With this approach HA protection state can remain within a centralized file as in current HA implementations since all master HA modules would be able to read it regardless of how the cluster is partitioned . One implementation of this approach may for simplicity allow only one master HA module to write to the centralized file at a time. This write enabled master may be selected via e.g. a third party witness. Another implementation may allow multiple concurrent writers with the host system of each master HA module owning a segment of the file for write purposes. In addition to protection state management another aspect of HA that is affected by the use of a HC OB storage system for VM data storage is the VM restart failover workflow orchestrated by master HA modules in the event of a failure. As discussed in Section 1.2 above a conventional version of this workflow comprises 1 identifying the VMs to be restarted 2 placing those VMs on active host systems that have available capacity and which can access the VM s devices including storage and 3 transmitting commands to the slave HA modules on the respective host systems to initiate the restart process for each VM. Unfortunately this conventional version fails to take into account the fact that when a VM is stored on HC OB storage the accessibility of the VM s objects cannot be determined via a storage container check and hence there may be cases where the VM cannot be restarted because one or more of its storage objects are not yet accessible to the host system executing on the master HA module and or to the host system on which the restart is being attempted . This in turn can result in multiple continuous VM restart attempts which can increase the load on the affected host systems and can delay the restart of other VMs. To address this depict a modified HA failover restart workflow comprising flowcharts and respectively that can be performed by a master HA module e.g. X of according to an embodiment. At a high level this modified workflow can check whether a given VM is accessible by the host system on which the master HA module is located before the master HA module attempts to restart it thereby reducing the total number of unsuccessful VM restart attempts and thus the load on the system . Starting with flowchart of at block host VM monitoring component of master HA module X can detect a failure within host cluster that necessitates the failover of one or more VMs. At block failover orchestration component of master HA module X can identify the VM s to be failed over restarted in response to the failure. For example in one embodiment failover orchestration component can identify these VMs based on the HA protection state information discussed with respect to Section 2 above. At block failover orchestration component can enter a loop for each VM identified at block . Within the loop failover orchestration component can first determine whether the VM is a VSAN VM i.e. a VM whose state is stored on HC OB storage block . If not failover orchestration component can add the VM to a restart list of VMs to be immediately placed and restarted block . As discussed with respect to flowchart of below another thread process of failover orchestration component can asynchronously process this restart list to place and restart the listed VMs. The VM loop can then end block and failover orchestration component can return to block to iterate through the loop again if needed to handle additional VMs. If failover orchestration component determines that the VM is not a VSAN VM at block component can move on to checking whether the VM is accessible block . For example in one embodiment block can comprise determining whether all of the VM s storage objects can be accessed by the host system of master HA module X from HC OB storage . In a particular embodiment this check can be carried out by invoking an appropriate query API exposed by the VSAN layer. If the VM is accessible failover orchestration component can add the VM to the restart list as described above block . On the other hand if the VM is inaccessible failover orchestration component can add the VM to a wait list of VMs waiting for an accessibility change block . As discussed with respect to flowchart of below another thread process of failover orchestration component can asynchronously process this wait list to wait for the accessibility of the VMs on the list to change before restarts for those VMs are attempted. The VM loop can then end block and failover orchestration component can return to block to iterate through the loop again if needed to handle additional VMs. Turning now to flowchart depicts a sub flow that can be performed by an independent thread process of failover orchestration component of master HA module X for processing the restart list noted at block of according to an embodiment. In the embodiment of flowchart is performed in the context of a particular VM on the restart list and thus should be repeated for all other VMs on the list . At block failover orchestration component can first attempt to find a place for restarting the current VM. In other words failover orchestration component can attempt to find an active host system within host cluster that is suitable for hosting execution of the VM. In one embodiment this placement step may take into account the available compute e.g. CPU memory etc. capacity of each active host system and or other factors. If failover orchestration component cannot find a place for the VM block component can wait for a host capacity change block and can subsequently return to block . If a place for the VM can be found at block failover orchestration component can initiate the VM restart process on the identified host system not shown . Failover orchestration component can then check whether the restart was successful block . If so flowchart and the overall restart workflow for this VM can end. If the restart was unsuccessful failover orchestration component can check whether the restart failed due to insufficient capacity at the selected host system block . If so component can wait for a host capacity change as noted above block and can return to block . However if the restart did not fail due to insufficient host capacity failover orchestration component can perform a series of steps to determine whether the failed restart was caused by a VM object accessibility issue. In particular at block failover orchestration component can check whether the VM is a VSAN VM. If not failover orchestration component can conclude that the failed restart was due to some transient issue on the target host system and thus can wait for a delay period before re attempting the restart process block . On the other hand if the VM is VSAN VM failover orchestration component can check whether the restart failed because the VM was inaccessible and whether the VM is still currently inaccessible. In one embodiment component can perform this check by e.g. invoking the same query API used at block of block . This second accessibility check is useful because in certain embodiments the accessibility of the VM may change between the first check performed at block and the actual restart of the VM at block . If the VM is accessible at block failover orchestration component can wait for a delay period block and subsequently return to block . Otherwise failover orchestration component can remove the VM from the restart list and add it to the wait list blocks and . In this way failover orchestration component can put off any further restart attempts for this VM until its stored objects are accessible. Turning now to flowchart depicts a sub flow that can be performed by an independent thread process of failover orchestration component of master HA module X for processing the wait list noted at block of and block of according to an embodiment. In the embodiment of flowchart is performed in the context of a particular VM on the wait list and thus should be repeated for all other VMs on the list . At block failover orchestration component can check whether the accessibility of the current VM has changed. Such a change may occur due to e.g. a resolution event that causes the VM and potentially other VMs in the cluster to become available again. In one set of embodiments failover orchestration component can perform this check by waiting for a notification from the VSAN layer that the VM s accessibility has changed. In these embodiments failover orchestration component can register for the notification by e.g. registering for a callback exposed by the VSAN layer. It should be noted that in some cases where a resolution event occurs the VSAN layer may not become aware that the storage objects of all VMs affected by the event have become accessible at exactly the same moment. Rather it may take some time for the VSAN layer to determine the accessibility of VM the accessibility of VM and so on. Accordingly in certain embodiments the VSAN layer may be configured to issue multiple accessibility changed notifications in response to a resolution event. For instance each successive notification can report the VMs whose storage objects have become accessible since the last notification. The notifications can be issued on a fixed time interval e.g. one every minute or as objects VMs become accessible. With this approach the average time needed to restart VSAN VMs can be reduced. If failover orchestration component determines that the current VM is not yet accessible at block component can continue to wait for an accessibility change block and return to block . However if the VM becomes accessible at block failover orchestration component can remove the VM from the wait list and add it to the restart list blocks and . As a result component can subsequently place and restart the VM whose stored state is now fully accessible per the processing of flowchart of . It should be appreciated that the embodiments described above for modifying the conventional HA failover restart workflow are illustrative and numerous variations and alternatives are possible. For example in some embodiments as part of the accessibility changed notification step described at block of the VSAN layer may not be able to notify master HA module X when a particular VM has become accessible rather the VSAN layer may only be able to notify master HA module X when one or more storage objects of any VM in the cluster have become accessible. To account for this when failover orchestration component of master HA module X receives the notification component can re invoke the accessibility query API for each VM in the wait list in order to identify the specific VM whose storage object s have become accessible. In addition in some embodiments the accessibility query API exposed by the VSAN layer may not be able to return a definite answer as to whether a VM is accessible instead the API may only be able to indicate whether a VM s namespace object is accessible. In these scenarios the same failover restart workflow shown in may be used but master HA module X may need to attempt more VM restarts since the restart for a given VM will fail if a full copy of the VM s persistent data such as its virtual disks is not accessible . When a failure splits the host systems in a host cluster into two or more network partitions the HA and VSAN modules in the cluster may or may not observe the same partitions. For example if the HA and VSAN modules share the same management network they will generally observe the same partitions since a failure in the management network will split both groups of modules in the same manner . However if the HA and VSAN modules do not share the same management network as in environment of there may be cases where a network failure splits one group of modules but not the other or splits the two groups of modules in non identical ways. There are generally four partition scenarios to consider Some of the scenarios above may require enhancements to the HA protection state persistence and HA failover restart techniques described in Sections 2 and 3 so that those techniques can operate efficiently. These enhancements are detailed in the sub sections that follow. In this scenario the HA modules observe a partition but the VSAN modules do not. With respect to environment of this may occur if e.g. there is a failure in management network interconnecting HA modules M but there is no failure in management network interconnecting VSAN modules M . If scenario 1 occurs the group of HA modules in each partition will elect a master HA module such that there are multiple master HA modules one per partition . The master HA module in each partition will be able to read and write the HA protection state for all VMs in the host cluster because the VSAN layer has full visibility of the entire HC OB object store. Accordingly no changes are needed for the HA protection state persistence retrieval flows described in Section 2 to accommodate this scenario. In terms of HA failover restart each master HA module will in parallel attempt to restart each VM within the master module s partition. In certain embodiments no mechanism may be provided to prevent concurrent VM restart attempts by different master HA modules in different partitions. Nevertheless generally speaking only one instance of each VM will actually power on because VM power on requires in one embodiment an exclusive lock to be held on one of the VM s files and thus only one master HA module will obtain this lock and successfully power on the VM . This means that changes are also not needed for the failover restart workflow described in Section 3 to accommodate this scenario. In this scenario the VSAN modules observe a partition but the HA modules do not. One example of this scenario is illustrated in which depicts a host cluster of six host systems in which there is a failure in management network interconnecting VSAN modules that splits the cluster into two partitions and but there is no failure in management network interconnecting HA modules . Thus master HA module on host system identified by the M designation is able to communicate with slave HA modules on host systems while the VSAN modules can only communicate with the other VSAN modules in their particular partition. For issues A and B above at least three solutions are possible 1 the master HA module queries each slave HA module to learn whether that slave HA module can access a particular VM 2 the VSAN module or some other component on each host system publishes the set of VMs that are accessible from that host and this set is forwarded to the master HA module by each slave HA module and 3 the master HA module uses trial and error when attempting to update the metadata of a VM or when trying to restart it. For issue C above the master HA module can inform the slave HA modules of the VMs that the master is interested in tracking for accessibility change purposes. The slave HA modules can then report back to the master when a given VM becomes accessible to the respective host systems of the slaves. For issue D above the master HA module can periodically ask each slave HA module to call the GET API to retrieve the HA protection state information for accessible VMs. The master HA module can subsequently compare the information received from the slave HA modules with what it had previously obtained. Based on this comparison if there are any new VMs that are not currently running the master HA module can attempt to restart those VMs. Starting with block protection state management component of master HA module can attempt to invoke the VSAN SET API on host system for persisting the protection state of a VM e.g. VM in HC OB object store . If this invocation completes successfully at block meaning that host system has access to the VM s namespace object flowchart can end block . On the other hand if the invocation of the VSAN SET API does not complete successfully at block protection state management component can identify a subset of slave HA modules and can issue a VM accessibility query to the subset in parallel blocks and . This subset could be determined for example by querying the VSAN layer for the hosts that the current host can access over the management network and then excluding these from the subset queried in block . This VM accessibility query can effectively ask the target HA module whether the host system on which it is running has access to the VM. If a particular slave HA module in the subset sends a response message indicating that its host system can access the VM block protection state management component of master HA module can transmit a command to that slave HA module with instructions to invoke the VSAN SET API from its respective host system block . If this remote invocation is successful block flowchart can end. However if no slave HA module in the subset indicates that its host system can access the VM at block or if the remote invocation at block is unsuccessful protection state management component of master HA module can check whether all of the slave HA modules have been queried. If not component can select a new subset at block and repeat the subsequent steps of flowchart . Finally if protection state component determines that all slave HA modules have been queried at block component can add the VM to the wait for accessibility change list described with respect to block and can subsequently return to block . At block failover orchestration component of master HA module can transmit a list of VMs to be placed and restarted to slave HA modules for the purpose of inquiring about the accessibility of the VMs from their respective host systems. At block failover orchestration component can receive the requested accessibility information from the slave HA modules. Failover orchestration component can then match the VMs to certain host systems based on the received accessibility information block . At block failover orchestration component of master HA module can notify slave HA modules of the wait list of VMs on which master HA module is waiting for an accessibility change notification. In response each slave HA module can query via the accessibility query API discussed with respect to its respective VSAN module for accessibility of the VMs on the list block . Finally at block each slave HA module can report back to master HA module when a VM on the list has become accessible or is already accessible . It should be appreciated that are illustrative and various modifications alternatives are possible. For example in the master HA module may not need to attempt to execute the VSAN SET API on the host of each slave HA module. Rather when an attempt fails on a host X the VSAN module of host X can return the IDs of the hosts that the VSAN module can communicate with over VSAN network . The master HA module can then use this information to make only one attempt per partition rather than one attempt per host. In this scenario the HA and VSAN modules observe identical partitions. With respect to environment of this may occur if e.g. there are failures at identical points in management networks and respectively. Alternatively this scenario may occur if the HA and VSAN modules share the same management network and there is a failure on that shared network. Scenario 3 is similar to scenario 1 in that the group of HA modules in each partition will elect a master HA module such that there are multiple master HA modules one per partition . The master HA modules in each partition will only be able to read and write the HA protection state for the VMs that are accessible from within the master s partition however each VM should be accessible to one master HA module. Accordingly no changes are needed for the HA protection state persistence retrieval flows described in Section 2 to accommodate this scenario. In terms of HA failover restart each master HA module will attempt to restart its accessible VMs within its partition. To accomplish this the master HA modules can follow the failover restart workflow described in Section 3 without any specific changes or enhancements. In this scenario the HA and VSAN modules observe non identical partitions. An example of this scenario is illustrated in which depicts a host cluster of six host systems in which there is a first failure in management network interconnecting VSAN modules that splits the cluster into two partitions and and there is a second failure in management network interconnecting HA modules that splits the cluster into two different partitions and . If scenario 4 occurs a master HA module that knows whether a given VM is protected may not know whether the VM is accessible within the master s partition. Conversely a master HA module that knows whether a VM is accessible within its partition may not know whether the VM is protected. To process HA protection state updates and restart failed VMs quickly in this scenario the master HA module that is responding to the protection request or knows a VM is protected should retry such operations repeatedly until they succeed. The embodiments described herein can employ various computer implemented operations involving data stored in computer systems. For example these operations can require physical manipulation of physical quantities usually though not necessarily these quantities take the form of electrical or magnetic signals where they or representations of them are capable of being stored transferred combined compared or otherwise manipulated. Such manipulations are often referred to in terms such as producing identifying determining comparing etc. Any operations described herein that form part of one or more embodiments can be useful machine operations. Further one or more embodiments can relate to a device or an apparatus for performing the foregoing operations. The apparatus can be specially constructed for specific required purposes or it can be a general purpose computer system selectively activated or configured by program code stored in the computer system. In particular various general purpose machines may be used with computer programs written in accordance with the teachings herein or it may be more convenient to construct a more specialized apparatus to perform the required operations. The various embodiments described herein can be practiced with other computer system configurations including handheld devices microprocessor systems microprocessor based or programmable consumer electronics minicomputers mainframe computers and the like. Yet further one or more embodiments can be implemented as one or more computer programs or as one or more computer program modules embodied in one or more non transitory computer readable storage media. The term non transitory computer readable storage medium refers to any data storage device that can store data which can thereafter be input to a computer system. The non transitory computer readable media may be based on any existing or subsequently developed technology for embodying computer programs in a manner that enables them to be read by a computer system. Examples of non transitory computer readable media include a hard drive network attached storage NAS read only memory random access memory e.g. a flash memory device a CD Compact Disc e.g. CD ROM CD R CD RW etc. a DVD Digital Versatile Disc a magnetic tape and other optical and non optical data storage devices. The non transitory computer readable media can also be distributed over a network coupled computer system so that the computer readable code is stored and executed in a distributed fashion. In addition while described virtualization methods have generally assumed that virtual machines present interfaces consistent with a particular hardware system persons of ordinary skill in the art will recognize that the methods described can be used in conjunction with virtualizations that do not correspond directly to any particular hardware system. Virtualization systems in accordance with the various embodiments implemented as hosted embodiments non hosted embodiments or as embodiments that tend to blur distinctions between the two are all envisioned. Furthermore certain virtualization operations can be wholly or partially implemented in hardware. Many variations modifications additions and improvements are possible regardless the degree of virtualization. The virtualization software can therefore include components of a host console or guest operating system that performs virtualization functions. Plural instances can be provided for components operations or structures described herein as a single instance. Finally boundaries between various components operations and data stores are somewhat arbitrary and particular operations are illustrated in the context of specific illustrative configurations. Other allocations of functionality are envisioned and may fall within the scope of the invention s . In general structures and functionality presented as separate components in exemplary configurations can be implemented as a combined structure or component. Similarly structures and functionality presented as a single component can be implemented as separate components. As used in the description herein and throughout the claims that follow a an and the includes plural references unless the context clearly dictates otherwise. Also as used in the description herein and throughout the claims that follow the meaning of in includes in and on unless the context clearly dictates otherwise. The above description illustrates various embodiments along with examples of how aspects of particular embodiments may be implemented. These examples and embodiments should not be deemed to be the only embodiments and are presented to illustrate the flexibility and advantages of particular embodiments as defined by the following claims. Other arrangements embodiments implementations and equivalents can be employed without departing from the scope hereof as defined by the claims.
Markdown
UTF-8
751
2.53125
3
[]
no_license
--- date: w01d03 duration: 60 maintainer: RobertoReif order: 1 title: Presentation Guide --- # Sample Lesson Plan * (60m) [Presentation Tips](PresentationGuide.pptx) # Learning Objectives At the end of this lecture the students should: * Understand how to create and deliver effective presentations * Have a clear understanding of what information should go on the main slides versus the appendix # Depends On None # Instructor Notes The goal of this slide deck is to walk students through some tips on what should be included in their presentations and how to effectively create slides. It covers topics such as images, animations, text, etc. Use the PowerPoint deck (not a pdf) so the animations can be presented. # Additional Resources
Markdown
UTF-8
2,457
3.3125
3
[]
no_license
# GettingAndCleaningData This file explains all the variables, features, calculations performed as part of the Week4 Assignment of the Getting and Cleaning Data assignment There are two sets of data: training and test data. We can see that the main data captured from devices are under InertialSignals folder. This folder contains three sets of raw data - X, Y and Z 1. acceleration signals in gravity units 2. acceleration signals subtracting the gravity 3. angular velocity in radians/second For our assignment we take the two main files : X_train.txt and X_test.txt. This contains 561 columns. Each of the column is one of the below calculation: mean(): Mean value std(): Standard deviation mad(): Median absolute deviation max(): Largest value in array min(): Smallest value in array sma(): Signal magnitude area energy(): Energy measure. Sum of the squares divided by the number of values. iqr(): Interquartile range entropy(): Signal entropy arCoeff(): Autorregresion coefficients with Burg order equal to 4 correlation(): correlation coefficient between two signals maxInds(): index of the frequency component with largest magnitude meanFreq(): Weighted average of the frequency components to obtain a mean frequency skewness(): skewness of the frequency domain signal kurtosis(): kurtosis of the frequency domain signal bandsEnergy(): Energy of a frequency interval within the 64 bins of the FFT of each window. angle(): Angle between to vectors. So the process followed for completing this assignment is as below: 1. The X_train and X_test seemed clean i.e. all columns were populated, there were no NAs or badly formated data 2. It was safe to merge the two tables to form one single data set 3. Similarly the y_train and y_test that contains the activity labels also had the same number of rows as the X_train and X_test and so the two 'y*' files were merged to form a common file 4. Next step was to merge the activities with the measurements. This enabled to create a view of the various values per activity 5. Further as per requirements all the mean and standard deviation values were extracted to form a separate data table 6. Now all that was left is to perform a three way join with the measurements, activity and subject 7. Finally as the last step we can calculate the mean of each measurement by using the aggregate function that performs aggregation in groups. In our assignment we need to group by activity and then by subject.
Markdown
UTF-8
917
3.296875
3
[]
no_license
<!-- https://developers.weixin.qq.com/miniprogram/dev/api/canvas/scale.html --> canvasContext.scale =================== ### 定义 在调用`scale`方法后,之后创建的路径其横纵坐标会被缩放。多次调用`scale`,倍数会相乘。 ### 参数 参数 | 类型 | 说明 ----------------|-----------|-------------------------------------------- scaleWidth | Number |横坐标缩放的倍数 (1 = 100%,0.5 = 50%,2 = 200%) scaleHeight | Number |纵坐标轴缩放的倍数 (1 = 100%,0.5 = 50%,2 = 200%) ### 例子 const ctx = wx.createCanvasContext('myCanvas') ctx.strokeRect(10, 10, 25, 15) ctx.scale(2, 2) ctx.strokeRect(10, 10, 25, 15) ctx.scale(2, 2) ctx.strokeRect(10, 10, 25, 15) ctx.draw() ![](https://developers.weixin.qq.com/miniprogram/dev/image/canvas/scale.png)
Python
UTF-8
663
4.03125
4
[]
no_license
#!/usr/bin/python # demo function passing parameters by name and returning values def print_total(customer_name, items): print "Total for {0}:".format(customer_name) total = 0 for item in items: total = total + item print "${0}".format(total) print_total(items=[5.0, 5.5, 5.0], customer_name="Alfred") def get_square_and_cube(number): square = number * 2 cube = number * 3 return square,cube # python will return a tuple that contains all the values returned by the function result = get_square_and_cube(5) print result square, cube = get_square_and_cube(5) # the values are assign to my own vars print square print cube
Ruby
UTF-8
753
3.203125
3
[]
no_license
class TestObserver attr_reader :values, :errors def initialize @values = [] @errors = [] @complete = false end def do_on_next(value) @values << value end def do_on_complete @complete = true end def do_on_error(error) @errors << error end def empty? @values.empty? end def complete? @complete end def has_values?(*values) @values == values end def has_error?(error_class) @errors.any? { |error| error.class == error_class } end def expect_to_have_values(*values) raise "Expected values #{values.inspect}, actual: #{to_s}" unless has_values?(*values) end def to_s "[values: #{@values.inspect}, errors: #{@errors.inspect}, complete: #{@complete}]" end end
C++
UTF-8
6,167
2.71875
3
[ "BSD-2-Clause", "LicenseRef-scancode-free-unknown", "MIT" ]
permissive
#include "driver.h" #include "assert.h" #include "mm.h" #include "mp.h" #include "object.h" #include "log.h" #include <cinttypes> namespace driver::common { static driver_initialize_fn driver_initialize_; static driver_destroy_fn driver_destroy_; static object_t<mm::system_memory_allocator> system_memory_allocator_object_; static object_t<mm::hypervisor_memory_allocator> hypervisor_memory_allocator_object_; static bool has_default_hypervisor_allocator_ = false; static void* hypervisor_allocator_base_address_ = nullptr; static size_t hypervisor_allocator_capacity_ = 0; size_t hypervisor_allocator_capacity__ = 0; // read from registry auto initialize( driver_initialize_fn driver_initialize, driver_destroy_fn driver_destroy ) noexcept -> error_code_t { // // Either both must be set or both must be nullptr, // nothing else. // hvpp_assert(!(!!driver_initialize ^ !!driver_destroy)); driver_initialize_ = driver_initialize; driver_destroy_ = driver_destroy; // // Initialize logger and memory manager. // if (auto err = logger::initialize()) { return err; } if (auto err = mm::initialize()) { return err; } // // Print memory information to the debugger. // mm::mtrr_descriptor().dump(); mm::physical_memory_descriptor().dump(); mm::paging_descriptor().dump(); // // Initialize default system allocator. // if (auto err = system_allocator_default_initialize()) { return err; } // // If driver doesn't have initialize() function, we're finished. // if (!driver_initialize_) { return {}; } // // ...otherwise, call the provided initialize() function. // if (auto err = driver_initialize_()) { return err; } // // Check if hypervisor allocator has been set. // if (mm::hypervisor_allocator()) { return {}; } // // ...if not, create default hypervisor allocator. // if (auto err = hypervisor_allocator_default_initialize()) { return err; } return {}; } void destroy() noexcept { // // Call driver's destroy() function, if provided. // if (driver_destroy_) { driver_destroy_(); } // // Destroy memory manager and logger. // mm::destroy(); logger::destroy(); // // Destroy default hypervisor allocator (if constructed). // if (has_default_hypervisor_allocator_) { hypervisor_allocator_default_destroy(); } // // At last, destroy default system allocator. // system_allocator_default_destroy(); } auto system_allocator_default_initialize() noexcept -> error_code_t { // // Construct and assign system allocator object. // system_memory_allocator_object_.initialize(); mm::system_allocator(&*system_memory_allocator_object_); return {}; } void system_allocator_default_destroy() noexcept { // // Unassign system allocator and destroy the object. // mm::system_allocator(nullptr); system_memory_allocator_object_.destroy(); } auto hypervisor_allocator_default_initialize() noexcept -> error_code_t { hvpp_assert(hypervisor_allocator_base_address_ == nullptr); hvpp_assert(hypervisor_allocator_capacity_ == 0); // // Construct hypervisor allocator object. // hypervisor_memory_allocator_object_.initialize(); hypervisor_allocator_capacity_ = hypervisor_allocator_recommended_capacity(); hvpp_info("Number of processors: %u", mp::cpu_count()); hvpp_info("Reserved memory: %" PRIu64 " MB", hypervisor_allocator_capacity_ / 1024 / 1024); // // Allocate memory. // hypervisor_allocator_base_address_ = mm::system_allocator()->allocate(hypervisor_allocator_capacity_); if (!hypervisor_allocator_base_address_) { return make_error_code_t(std::errc::not_enough_memory); } // // Attach allocated memory. // if (auto err = hypervisor_memory_allocator_object_->attach(hypervisor_allocator_base_address_, hypervisor_allocator_capacity_)) { return err; } // // Assign allocator. // mm::hypervisor_allocator(&*hypervisor_memory_allocator_object_); has_default_hypervisor_allocator_ = true; return {}; } void hypervisor_allocator_default_destroy() noexcept { if (!hypervisor_allocator_base_address_) { return; } if (!mm::hypervisor_allocator()) { return; } // // Unassign allocator. // mm::hypervisor_allocator(nullptr); // // Detach allocated memory. // hypervisor_memory_allocator_object_->detach(); // // Destroy object. // hypervisor_memory_allocator_object_.destroy(); // // Return allocated memory back to the system. // mm::system_allocator()->free(hypervisor_allocator_base_address_); hypervisor_allocator_base_address_ = nullptr; hypervisor_allocator_capacity_ = 0; } auto hypervisor_allocator_recommended_capacity() noexcept -> size_t { // // If allocator capacity was set in the registry, prefer that value. // if (hypervisor_allocator_capacity__ > 0) { return hypervisor_allocator_capacity__; } // // Estimate required memory size. // If hypervisor begins to run out of memory, required_memory_size // is the right variable to adjust. // // Default required memory size is 34MB per CPU. // const auto recommended_memory_size = ( // // Estimated EPT size: // Make space for 2MB EPT entries for 512 GB of the physical // memory. Each EPT entry has 8 bytes. // 512GB / 2MB * 8 = 256kb * 8 = 2MB per CPU. // ((512ull * 1024 * 1024 * 1024) / (2ull * 1024 * 1024) * 8) + // // Additional 32MB per CPU. // (32ull * 1024 * 1024) ) * mp::cpu_count(); // // Round up to page boundary. // return ia32::round_to_pages(recommended_memory_size); } }
Python
UTF-8
4,460
3.234375
3
[]
no_license
# -*- coding:utf-8 -*- import json import shlex import copy import re from collections import OrderedDict class Control(object): def __init__(self, root): self.stack = [root] self.root = root self.path = [] def push(self, name): self.stack.append(self.stack[-1][name]) self.path.append(name) def pop(self): self.stack.pop() self.path.pop() def refresh(self): self.stack = [self.root] self.path = [] def nodes_from_path(self, path): return [(int(x) if x.isdigit() else x) for x in path.strip().split("/")] def access(self, nodes): if not nodes: return self.stack[-1] stack = self.stack[:] if nodes[0] == "": stack = [self.root] for name in non_empty_iterator(nodes): if name == ".": continue elif name == "..": stack.pop() else: stack.append(stack[-1][name]) return stack[-1] @property def current(self): return self.stack[-1] def non_empty_iterator(itertaor): for x in itertaor: if not x: continue yield x class SelfishList(list): def __setitem__(self, i, v): try: super(SelfishList, self).__setitem__(i, v) except IndexError: if len(self) == i: self.append(v) else: raise class JSONMaker(object): def __init__(self): self.list = SelfishList self.dict = OrderedDict def mkobject(self, c, *paths): for path in non_empty_iterator(paths): nodes = c.nodes_from_path(path) target = c.access(nodes[:-1]) if nodes[-1] not in target: target[nodes[-1]] = self.dict() def mkarray(self, c, *paths): for path in non_empty_iterator(paths): nodes = c.nodes_from_path(path) target = c.access(nodes[:-1]) if nodes[-1] not in target: target[nodes[-1]] = self.list() def cp(self, c, src, dst): srcobj = c.access(c.nodes_from_path(src)) nodes = c.nodes_from_path(dst) target = c.access(nodes[:-1]) target[nodes[-1]] = copy.deepcopy(srcobj) def rm(self, c, *paths): for path in non_empty_iterator(paths): nodes = c.nodes_from_path(path) target = c.access(nodes[:-1]) target.pop(nodes[-1], None) def put(self, c, path, v): nodes = c.nodes_from_path(path) target = c.access(nodes[:-1]) target[nodes[-1]] = v def append(self, c, path, v): nodes = c.nodes_from_path(path) target = c.access(nodes) target.append(v) def cd(self, c, v): if not v: return elif v.startswith("/"): self.refresh() self.cd(c, v[1:]) elif v.startswith("./"): self.cd(c, v[2:]) else: for name in non_empty_iterator(c.nodes_from_path(v)): if name == "..": c.pop() else: c.push(name) def eval(self, cmd, splitter=re.compile("[;\n]", re.MULTILINE).split): c = Control(self.dict()) actions = splitter(cmd) for action in actions: if not action: continue name, *args = shlex.split(action) getattr(self, name)(c, *args) return c.root def pwd(self, c): print(c.path) v = JSONMaker().eval(""" mkobject address phoneNumber cd address put ./streetAddress "21 2nd Street" put city "New York" cd ../phoneNumber put location home put code 44 mkarray ../favorites append ../favorites a append /favorites b """) print(json.dumps(v, indent=2)) """ { "address": { "streetAddress": "21 2nd Street", "city": "New York" }, "phoneNumber": { "code": "44", "location": "home" }, "favorites": [ "a", "b" ] } """ print(json.dumps(JSONMaker().eval(""" mkobject foo cd foo; put name "foo"; put age 20 cd ../ mkarray members cp foo members/0 cp foo members/1 put members/1/name "bar" rm foo """), indent=2)) print(json.dumps(JSONMaker().eval(""" mkobject address phoneNumber cd address put ./streetAddress "21 2nd Street" put city "New York" put ../phoneNumber/location home put /phoneNumber/code 44 """), indent=2))
Markdown
UTF-8
8,617
3.03125
3
[]
no_license
# Redux w/ ReactJS Tutorial `Redux` provides a predictable state container for JavScript applications. The app state is centralized. `react-redux` is the official React binding for Redux. ## Installing `redux` and `react-redux` ```bash npm install --save redux react-redux ``` > `--save` to include 'redux' and 'react-redux' within `dependencies` For Redux DevTools (chrome extension), add following code to source file e.g. `App.js` ```jsx const global_store = createStore( reducer_object, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__() ); ``` ## Basic Directory Tree <pre> main-app/ ├── node_modules/ ├── public/ ├── ... ├── src/ │ ├── actions/ │ ├── reducers/ │ ├── App.js │ ├── index.js │ └── ... ├── package.json └── ... </pre> ## Reducers Reducers are `functions` that return a new `state` depending on the current `state` and `action` passed. <br> `(state, action) => newState` Some guidelines on reducers: 1. By concept, `state` is immutable 2. Handling `undefined` behaviour: * Handle `undefined` state arguments provided to the reducer function. <br> e.g. `const reducer = (initial_state = 0, action) => {...}` <br> Here, if passed `state` is undefined, * And try not to return any `undefined` states. ### Files and directories Convention: `./src/reducers/<reducerFileName>.js`. Include `./src/reducers/index.js` for a main reducer file. > note: assuming we are in the react-app's root directory A typical reducer JS file: ```jsx const counter_reducer = (initial_state = 0, action) => { switch (action.type) { /* Convention: action = { type: '...', payload: '...' } */ case 'ADD': return initial_state + action.payload; case 'SUB': return initial_state - action.payload; default: return initial_state; // better to run some checks on 'action.payload' // e.g. datatypes(string or number) etc. } } export default counter_reducer; ``` ### Combining multiple reducers Why? To reduce complexity from having multiple reducers. Afterall, `createStore` takes a single reducer funtion. Import required: `import { combineReducers } from 'redux';` Combining several reducers to a single `index.js` file: ```jsx import <reducerName> from './<reducerFileName>'; import counter_reducer from './counterReducer.js'; //assuming within same dir // import other reducers from their respective reducer files import { combineReducers } from 'redux'; const allReducers = combineReducers({ <keyName>: <reducerName>, // syntax counter: counter_reducer, // example 1 username: username_reducer // example 2 //... }); export default allReducers; ``` ## Global State (`store`) and `Provider` ### `store` `createStore()` is used to create a storage/state object (import required from `redux`). Syntax:<br> ```jsx import allReducers from './reducers/index.js'; // or simply './reducers', index.js is implied import { createStore } from 'redux'; const store = createStore(allReducers); ``` ### `Provider` `Provider` is used to link/connect our global state/`store` object to our app. <br> From 'react-redux' api webpage: > The `<Provider>` component makes the Redux `store` available to any nested components that need to access the Redux store.<br> ... <br> The `Hooks` and `connect` APIs can then access the provided store instance via React's Context mechanism. Import statement: ```jsx // app-root's 'index.js' file import { Provider } from 'react-redux'; // ... const global_store = createStore(...); ReactDOM.render( <Provider store={global_store}> <App /> </Provider>, document.getElementById('root') ); ``` ## Using redux `store` ### For function-based Components `Hooks` are used to access the redux `store` object. <br> `useSelector` function from `react-redux` is required. Its basic syntax: ```jsx const result: any = useSelector(selector: Function, equalityFn?: Function) ``` ```jsx import { useSelector } from 'react-redux'; function CustomComponent() { const redux_state = useSelector(state => state); // OR const _username = useSelector(state => state.username); return ( <div> Username: {_username} </div> ); } export default CustomComponent; ``` ### For Class-based Components `connect` function from `react-redux` is used for accessing redux `store` object within class-based components. 1. First, ```jsx import { connect } from 'react-redux'; // Also import all the `action` functions we need. import { <actionName> } from '../actions'; // syntax import { userName } from '../actions'; // example ``` 2. Create a `mapStateToProps` function object. ```jsx const mapStateToProps = (state) => { return { // syntax <newPropName>: state.<reducerName>, // example usernameAsProp: state.username // as declared in our combined-reducer }; }; ``` > `<reducerName>` references to the keyName within our combined-reducer > `<newPropName>` can be used as `this.props.newPropName` within our connected-component 3. Display redux `state` ```jsx class CustomComponent extends React.Component { render() { return ( {/* syntax */} <h1> { this.props.<newPropName> } </h1> {/* example */} <h1> { this.props.usernameAsProp } </h1> ); }; } ``` ## `action` objects `action` describes what happens within app; it could be events and can trigger updates to `state`. ### Creating `action` Convention: Create `<appRootDir>/src/actions` directory. Within the directory, create action JS files, e.g. `index.js` ```jsx // index.js contents export const adder = () => { return { type: 'ADD', payload: ... }; }; // OR export const adder = (num_to_add) => { return { type: 'ADD', payload: num_to_add }; }; ``` ### Using `action` ```jsx import { <actionName> } from './actions/index.js'; // or simply import { <actionName> } from './actions'; ``` To use `action` objects to update `state`, we use concept of `dispatch` method within the `store` object. ## Dispatch From 'redux.js.org/tutorials' page: <br> > The Redux `store` has a method called `dispatch`. The only way to update the state is to call `store.dispatch()` and pass in an `action` object. The `store` will run its `reducer` function and save the `new` state value inside, and we can call `getState()` to retrieve the updated value: ```jsx store.dispatch({ type: <type> }) ``` > You can think of dispatching actions as "triggering an event" in the application. Something happened, and we want the store to know about it. Reducers act like event listeners, and when they hear an action they are interested in, they update the state in response. ### for function-based Components Using `useDispatch()` ```jsx import { useDispatch } from 'react-redux'; import { adder } from './actions'; // ... function CustomComponent() { const dispatch = useDispatch(); return ( <div> <button onClick={ () => dispatch(adder()) }> Add (w/o arg)</button> <button onClick={ () => dispatch(adder(100)) }> Add (w/ arg) </button> </div> ); } ``` ### for class-based Components 1. Create a `mapDispatchToProps` function object ```jsx import { adder } from './actions'; // ... const mapDispatchToProps = () => { return { // syntax <actionName>: actionFunction, // example adder: adder, }; }; ``` > `actionFunction` that we imported from `../actions/index.js` 2. Add event to Component ```jsx import { adder } from './actions'; // ... const mapDispatchToProps = () => { ... }; // ... class CustomComponent extends React.Component { render() { return ( {/* syntax */} <button onClick={() => this.props.<actionName>()}> Press me </button> {/* example */} <button onClick={() => this.props.adder(10)}> Add 10 </button> ); } } ``` 3. `connect` mapper functions From `react-redux.js.org/api/connect` page: > The `connect()` function connects a React component to a Redux `store`. <br> > It provides its connected component with the pieces of the data it needs from the `store`, and the functions it can use to dispatch actions to the `store`. <br> > It does not modify the component class passed to it; instead, it returns a new, connected component class that wraps the component you passed in. <br> ```jsx import { connect } from 'react-redux'; // ... const mapStateToProps = (state) => { ... }; const mapDispatchToProps = (state) => { ... }; class CustomComponent extends React.Component { ... } export default connect( mapStateToProps, mapDispatchToProps() )(CustomComponent); ``` > note: we have to call `connect(...)` function obj by `connect(...)(Component)`
Markdown
UTF-8
844
2.875
3
[ "MIT" ]
permissive
# Orientation <div class="aside"> <h3>To-Do List</h3> <ul> <li><b>Sign Up</b> for a free Cloudinary Account.</li> <li><b>Configure</b> your environment.</li> </ul> </div> There are few things to do before we can really get started. ## Sign Up Go to [cloudinary.com/signup](https://cloudinary.com/signup) to register for a free account. This free account gives you 25 credits per month that will be far more than enough for this adventure and any other experimenting that you would like to do. ## Configure Once you've signed up, go the Cloudinary [Dashboard](https://cloudinary.com/console) to get your: * Cloud Name * API Key * API Secret You will need these to complete this objective and configure access to Cloudinary account. Enter the information into the form on the right and click _HACK_ to verify and save this information.
JavaScript
UTF-8
3,201
2.53125
3
[]
no_license
"use strict" import React, {Component} from 'react'; import {render} from 'react-dom'; import ApiService from './apiService'; import CatalogBooks from './catalog-books'; import Header from './header'; import Footer from './footer'; import styles from './register-book.css'; class RegisterBook extends Component { constructor(props){ super(props); this.saved = this.saved.bind(this); this.search = this.search.bind(this); this.clear = this.clear.bind(this); this.handleChange = this.handleChange.bind(this); this.api = new ApiService(); this.state = { books:[], title: '', description:'' } } clear(){ this.refs.title.value = ''; this.refs.description.value = ''; this.setState({title:''}); } componentDidMount(){ componentHandler.upgradeDom(); } componentDidUpdate(){ componentHandler.upgradeDom(); } handleChange(e) { this.setState({title: e.target.value}); } render() { return ( <div> <Header /> <div className={styles.marginHeader}> <div className="mdl-grid"> <div className="mdl-layout-spacer"></div> <div className="mdl-textfield mdl-js-textfield mdl-textfield--floating-label"> <div className="mdl-layout-spacer"></div> <input className="mdl-textfield__input" type="text" id="title" ref="title" name="title" onChange={this.handleChange}/> <label className="mdl-textfield__label" htmlFor="title">Título</label> <div className="mdl-layout-spacer"></div> </div> <div className="mdl-layout-spacer"></div> </div> <div className="mdl-grid"> <div className="mdl-layout-spacer"></div> <div className="mdl-textfield mdl-js-textfield mdl-textfield--floating-label"> <input className="mdl-textfield__input" type="text" id="description" ref="description" name="description" /> <label className="mdl-textfield__label" htmlFor="description">Sinopse</label> </div> <div className="mdl-layout-spacer"></div> </div> <div className="mdl-grid"> <div className="mdl-layout-spacer"></div> <button className="mdl-button mdl-js-button mdl-button--raised" onClick={this.saved} disabled={!this.state.title}> Salvar </button> <button className="mdl-button mdl-js-button mdl-button--raised" onClick={this.search}> Pesquisar </button> <div className="mdl-layout-spacer"></div> </div> <CatalogBooks data={this.state.books}/> </div> <Footer /> </div> ); } saved(){ let title = this.refs.title.value; let description = this.refs.description.value; this.api.post('/book/save', JSON.stringify({title:title, description:description})); this.clear(); this.search(); } search(){ var a = this; this.api.get('/book/all').then(function(response){ for(var i=0;i<response.length;i++){ a.setState({books:response}); } }); } } export default RegisterBook;
Python
UTF-8
1,443
2.890625
3
[]
no_license
import pandas as pd import cPickle as pkl import numpy as np f = open('pkl_files/train_df_1.pkl','rb') train_df = pkl.load(f) f.close() image_date = pd.read_csv("input/listing_image_time.csv") # rename columns so you can join tables later on image_date.columns = ["listing_id", "time_stamp"] # reassign the only one timestamp from April, all others from Oct/Nov image_date.loc[80240,"time_stamp"] = 1478129766 image_date["img_date"] = pd.to_datetime(image_date["time_stamp"], unit="s") image_date["img_days_passed"] = (image_date["img_date"].max() - image_date["img_date"]).astype("timedelta64[D]").astype(int) image_date["img_date_month"] = image_date["img_date"].dt.month image_date["img_date_week"] = image_date["img_date"].dt.week image_date["img_date_day"] = image_date["img_date"].dt.day image_date["img_date_dayofweek"] = image_date["img_date"].dt.dayofweek image_date["img_date_dayofyear"] = image_date["img_date"].dt.dayofyear image_date["img_date_hour"] = image_date["img_date"].dt.hour image_date["img_date_monthBeginMidEnd"] = image_date["img_date_day"].apply(lambda x: 1 if x<10 else 2 if x<20 else 3) train_df = pd.merge(train_df, image_date, on="listing_id", how="left") info = train_df.columns importance = np.loadtxt('feature_importance.csv') # print info # print importance for i in range(250): print info[i],importance[i]
Java
UTF-8
656
3.390625
3
[]
no_license
import javax.swing.*; public class InputCharacterInfo { public static void main(String[] args) { char aChar; String input; input = JOptionPane.showInputDialog("Please enter a character0."); aChar = input.charAt(0); if (Character.isUpperCase(aChar)){ System.out.println(aChar + "is uppercase."); } else { System.out.println(aChar + "is not uppercase."); } if (Character.isLowerCase(aChar)){ System.out.println(aChar + "is lowercase."); } else { System.out.println(aChar + "is not lowercase."); } } }
JavaScript
UTF-8
2,421
3.203125
3
[]
no_license
const singlePost = document.querySelector(".singlePostResult"); const queryString = document.location.search; const params = new URLSearchParams(queryString); const id = params.get("id"); const url = "https://project-exam1-cms.svanevik.one/wp-json/wc/store/products/" + id; // Calling the API async function fetchSinglePost() { try { const fetchResponse = await fetch(url); const fetchResult = await fetchResponse.json(); singlePost.innerHTML = ""; createHTML(fetchResult); } catch(error) { console.log(error); } } fetchSinglePost(); // Creates the html fetched from the API function createHTML(sPost) { singlePost.innerHTML = `<div class="post_card"> <img class="post_img" id="image_modal" src="${sPost.images[0].src}" alt="${sPost.images[0].alt}"> <div id="modal_container" class="modal"> <img class="modal_image" id="img1"> <span class="close_modal"><i class="fas fa-times"></i></span> </div> <div class="text_container"> <h2 class="post_name">${sPost.name}</h2> ${sPost.short_description} ${sPost.description} </div>`; // Modal for all images on the single blog page var modal_container = document.getElementById("modal_container"); var open_image = document.getElementById("image_modal"); var modal_image = document.getElementById("img1"); open_image.onclick = function () { modal_container.style.display = "block"; modal_image.src = this.src; }; // Closes the modal opened on all single blog pages var span = document.getElementsByClassName("close_modal")[0]; span.onclick = function () { modal_container.style.display = "none"; }; window.onclick = function(event) { if (event.target == modal_container) { modal_container.style.display = "none" } }; // Change the title of each post document.title = "Eple's Blog" + " " + "|" + " " + sPost.name; // Change the innerHTML of the single blogpage document.getElementById("sp_h1").innerHTML = "Welcome to the" + " " + sPost.name + " " + "post"; }
C#
UTF-8
1,070
2.65625
3
[ "BSD-3-Clause" ]
permissive
using System; using System.Collections.Generic; using System.Text; namespace SteamCondenser.Steam.Packets { public class ServerRulesResponsePacket : SteamPacket { public ServerRule[] ServerRules { get; protected set; } public ServerRulesResponsePacket(ServerRule[] rules) : base(SteamPacketTypes.S2A_RULES) { ServerRules = rules; } public ServerRulesResponsePacket(byte[] data) : base(SteamPacketTypes.S2A_RULES, data) { if (reader.Length == 0) { throw new Exception("Wrong formatted S2A_RULES response packet."); } short numRules = reader.ReadShort(); ServerRules = new ServerRule[(int)numRules]; for (short i = 0; i < numRules; i++) { string cvar = reader.ReadString(); string value = reader.ReadString(); ServerRules[i] = new ServerRule(cvar, value); } } public override void Serialize(PacketWriter writer, bool prefix) { writer.WriteShort((short)ServerRules.Length); foreach (var rule in ServerRules) { writer.WriteString(rule.CVar); writer.WriteString(rule.Value); } } } }
Python
UTF-8
347
2.609375
3
[]
no_license
from unittest import TestCase from src.DeliveryProblem.AverageWeight import average from src.DeliveryProblem.Utils import DeliveryUtils class TestDaysToWinCash(TestCase): def test_average_weight(self): graph = DeliveryUtils.get_graph([(178, 212), (287, 131), (98, 156)]) self.assertEqual(424.1000397032701, average(graph))
Java
UTF-8
1,114
2.796875
3
[]
no_license
public class LogicaVenda { private Custo iv = new ImpostoSobreVenda(); private Custo seguro; public Custo getSeguro() { return seguro; } public void setSeguro(Custo seguro) { this.seguro = seguro; } public double calcularTotal(Venda venda) { venda.setTotal(0.0); for (ItemVenda item: venda.getItens()) { if (item != null) { venda.setTotal(venda.getTotal() + item.getSubTotal()); } } if ( this.iv != null) { venda.setTotal(venda.getTotal() + this.iv.calcularCusto(venda)); } if ( this.seguro != null) { venda.setTotal(venda.getTotal() + this.seguro.calcularCusto(venda)); } return venda.getTotal(); } public double lucroVenda (Venda venda){ double lucro = 0.0; for (ItemVenda item: venda.getItens()){ if(item != null){ lucro += item.getPrecoVenda()-item.getProduto().getPrecoReferencia(); } } return lucro; } }
Java
UTF-8
1,783
2.25
2
[]
no_license
/** * */ package ar.com.tellapic.sumi.treetable; import javax.swing.AbstractAction; /** * Copyright (c) 2010 Sebastián Treu. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * @author * Sebastian Treu * sebastian.treu(at)gmail.com * */ public class DefaultTellapicNodeActionCombo extends DefaultAbstractTellapicNodeAction { private Object[] data; /** * * @param node * @param action */ public DefaultTellapicNodeActionCombo(TellapicNode node, AbstractAction action, Object[] data) { super(node, action, TellapicTreeTable.DEFAULT_COMBO_EDITOR_KEY, TellapicTreeTable.DEFAULT_COMBO_RENDERER_KEY, true); initData(data); } /** * * @param action */ public DefaultTellapicNodeActionCombo(AbstractAction action, Object[] data) { this(null, action, data); } /** * */ public DefaultTellapicNodeActionCombo(String name, Object[] data) { super(name, TellapicTreeTable.DEFAULT_COMBO_EDITOR_KEY, TellapicTreeTable.DEFAULT_COMBO_RENDERER_KEY, true); initData(data); } /* (non-Javadoc) * @see ar.com.tellapic.gumi.treetable.TellapicNodeAction#getData() */ @Override public Object getData() { return data; } private void initData(Object[] data) { if (data == null) throw new IllegalArgumentException("data must not be null"); this.data = data; if (data.length > 0) setValue(data[0]); } }
C#
UTF-8
2,684
3.15625
3
[ "MIT" ]
permissive
using System.Collections; using System.Collections.Generic; namespace PortableTestApp.Test { static class FlowControlAndEnumerators { public static bool RunTest() { var valuesList = new List<int>(); valuesList.Add(4); valuesList.Add(5); valuesList.Add(6); var values = new int[3] { 1, 2, 3 }; valuesList.AddRange(values); var valuesFromList = valuesList.ToArray(); var values2 = new int[3]; values2[0] = 3; values2[1] = 2; values2[2] = 1; foreach (int value in values) foreach (int value2 in values2) foreach (int value3 in valuesFromList) { if (value == 0 || value2 == 0 || value3 == 0) return false; } for (int i = 0, i2 = 2; i != values.Length; ++i, --i2) { if (values[i] != values2[i2]) return false; } int l = 0; while (l != 3) { l++; } do { l -= 1; } while (l != 0); if (l == 0) { switch (l) { case 5 + 0: case 6: return false; case 0: l = 4; break; default: { return false; } } } else if (l == -1) { return false; } else { return false; } var myEnumerable = new MyEnumerable<int>(); myEnumerable.Set(40, 0); myEnumerable.Set(41, 1); myEnumerable.Set(42, 2); foreach (int e in myEnumerable) { if (e == 0) return false; } return true; } } // MyEnumerable<T> should be a class class MyEnumerable<T> : IEnumerable<T> { private MyEnumerator<T> e = new MyEnumerator<T>(new T[3]); public void Set(T value, int index) { e.Set(value, index); } public MyEnumerator<T> GetEnumerator() { return e; } // Will be ignored by CS2X #pragma warning disable CS0626 extern IEnumerator<T> IEnumerable<T>.GetEnumerator(); extern IEnumerator IEnumerable.GetEnumerator(); #pragma warning restore CS0626 } // MyEnumerator should be a struct struct MyEnumerator<T> : IEnumerator<T> { private int i; private T[] collection; public MyEnumerator(T[] collection) { i = -1; this.collection = collection; } public T Current { get { return collection[i]; } } // Will be ignored by CS2X #pragma warning disable CS0626 extern object IEnumerator.Current { get; } #pragma warning restore CS0626 public bool MoveNext() { ++i; return i < collection.Length; } public void Reset() { i = -1; } public void Set(T value, int index) { collection[index] = value; } } }
C#
UTF-8
1,113
2.984375
3
[]
no_license
using System.Text; namespace Buttercup.Control.Common.IO { public class Utility { #region Methods (1)  /// <summary> /// Converts the given wildcard to a regex string. Used by In Memory directory implementation. /// </summary> /// <param name="wildcard">The wildcard expression.</param> /// <returns>The wildcard as a regular expression.</returns> public static string WildcardToRegex(string wildcard) { if(wildcard == null) { return null; } StringBuilder buffer = new StringBuilder(); buffer.Append("^"); char[] chars = wildcard.ToCharArray(); for(int i = 0; i < chars.Length; ++i) { if(chars[i] == '*') { buffer.Append(".*"); } else if(chars[i] == '?') { buffer.Append("."); } else if("+()^$.{}[]|\\".IndexOf(chars[i]) != -1) { buffer.Append('\\').Append(chars[i]); // prefix all metacharacters with backslash } else { buffer.Append(chars[i]); } } buffer.Append("$"); return buffer.ToString(); } #endregion Methods  } }
Markdown
UTF-8
3,169
2.71875
3
[]
no_license
# NLP ### Setup As usual, you'll need to sign up. It's free. And you'll need a Google/Gmail account. - Click "Sign up for Free" - Log in with Google - Choose "Create Agent" (an agent is like a dialogflow bot) - Name it "Blank agent" - In the sidebar, chose "Prebuilt Agents" - Then in the main area, find the logo for the "Small Talk" prebuilt agent (Note, this is _not_ the "Small Talk" option in the left-side menu) - Just leave the "Link to Google Project" line empty and hit OK - Wait and then click "Proceed to Agent" - This is tricky ... now in the _drop-down_ menu, chose "Small-Talk." Again, not the "Small Talk" item that's always in the sidebar. Look for the hyphen in `Small-Talk`. That's the right one. - Now, to end this craziness, let's rename it. Click the gear next to `Small-Talk` (with the hyphen) - Call it "My-Workshop-Bot" - Click "Save" ### Play a little Find the "Try it now" box at the top and try typing some random phrases that might constitute small talk. What happens? Pay close attention to the "Intent" and "Action" areas. Also try things that might be casual synonyms for "yes" and "no." ## Update your Dexter bot ``` + * % do you like dogs $ GET https://api.api.ai/v1/query?v=20150910&query=<call>encode_uri <star></call>&lang=en&sessionId=<_platformId> {"headers":{"Content-Type":"application/json", "Authorization": "<bot apiai>"}} * ${{result.action}} == smalltalk.confirmation.yes => <set dogvar=yes> Do you like cats? * ${{result.action}} == smalltalk.confirmation.no => <set dogvar=no> Do you like cats? + * % do you like cats $ GET https://api.api.ai/v1/query?v=20150910&query=<call>encode_uri <star></call>&lang=en&sessionId=<_platformId> {"headers":{"Content-Type":"application/json", "Authorization": "<bot apiai>"}} * ${{result.action}} == smalltalk.confirmation.yes => <set catvar=yes> {@ answered <get dogvar> <get catvar>} * ${{result.action}} == smalltalk.confirmation.no => <set catvar=no> {@ answered <get dogvar> <get catvar>} + * $ GET https://api.api.ai/v1/query?v=20150910&query=<call>encode_uri <star></call>&lang=en&sessionId=<_platformId> {"headers":{"Content-Type":"application/json", "Authorization": "<bot apiai>"}} * ${{result.fulfillment.speech}} != "" => ${{result.fulfillment.speech}} - Sorry, I have no idea what you just said. > object encode_uri javascript return encodeURIComponent(args[0]) < object ! var apiai = Bearer putyourapikeyhere ``` Update the yes/no handler to: ``` + handle yesno * * <star> == smalltalk.confirmation.yes => <set openended-answer=yes> {@ openended reset and route} * <star> == smalltalk.confirmation.no => <set openended-answer=no> {@ openended reset and route} - Is that a yes or a no? ^buttons("Yes!", "No!") ``` ## Connect your bot to API.ai Finally, we wire up the NLP ... - Back at the API.ai settings page, copy the "Client Access Token" - Switch to your Dexter bot - Paste the "Client Access Token" at the very top of your bot script. - In front of the token, add `! var apiai = Bearer ` so it looks something this: Walk through changes in the [cat-dog-nlp](./cat-dog-nlp.rs) script. ``` ! var apiai = Bearer ab12cd34ef56ab78cd90ef12 ```
C++
UTF-8
525
2.734375
3
[]
no_license
class Solution { public: int uniquePaths(int m, int n) { vector<vector<int> > ans; ans.resize(m); for (int i=0;i<m;i++) { ans[i].resize(n); } for (int i=0;i<m;i++) { ans[i][0]=1; } for (int i=0;i<n;i++) { ans[0][i]=1; } for (int i=1;i<m;i++) { for (int j=1;j<n;j++) { ans[i][j]=ans[i-1][j]+ans[i][j-1]; } } return ans[m-1][n-1]; } };
C++
WINDOWS-1251
744
2.9375
3
[]
no_license
#include "FieldCommandArgument.h" #include "../../exceptions/BadBookFieldException.h" FieldCommandArgument::FieldCommandArgument() { name = "field"; description = " (author, title, publisher, year, storePlace)"; regexString = "author|title|publisher|year|storePlace"; } Book::field FieldCommandArgument::toBookEnumField() { if (value == "author") { return Book::AUTHOR; } else if (value == "title") { return Book::TITLE; } else if (value == "publisher") { return Book::PUBLISHER; } else if (value == "year") { return Book::YEAR; } else if (value == "storePlace") { return Book::STORE_PLACE; } throw BadBookFieldException(); }
Java
UTF-8
1,375
2.6875
3
[]
no_license
package com.recsys.similarity; import java.util.Iterator; import java.util.List; import com.recsys.recommendation.Mathematics; public class AdjustedCosineSimilarity<Double> extends NumbersSimilarityMeasure<java.lang.Double> { public java.lang.Double measureSimilarity(List<java.lang.Double> activeRatings,List<java.lang.Double> otherUserRatings) { double simPears = 0d; double numerateur = 0d; double denumerateurUser = 0d; double denumerateurActive = 0d; if (!activeRatings.isEmpty() && otherUserRatings.size() > 1) { double userMeanRatings = Mathematics.average(otherUserRatings); double activeMeanRatings = Mathematics.average(activeRatings); Iterator<java.lang.Double> i1 = activeRatings.iterator(); Iterator<java.lang.Double> i2 = otherUserRatings.iterator(); while(i1.hasNext()){ double double1 = i1.next(); double double2 = i2.next(); numerateur += (double1 - activeMeanRatings) * (double2 - userMeanRatings); denumerateurUser += Math.pow((double1 - activeMeanRatings),2); denumerateurActive += Math.pow((double2 - userMeanRatings),2); } simPears = numerateur/(Math.sqrt(denumerateurActive*denumerateurUser)); } //System.out.println("SPPPPPPPPPPPPPPPP = "+simPears); return simPears; } @Override public Boolean isSimilarity() { return true; } }
C#
UTF-8
898
2.71875
3
[]
no_license
using System; using System.Linq; using System.Security.Claims; namespace Ayatta.Web.Extensions { public static class ClaimsPrincipalExtensions { public static Identity AsIdentity(this ClaimsPrincipal principal) { if (principal != null && principal.Identity.IsAuthenticated) { var id = 0; string guid, name; if (!string.IsNullOrEmpty(principal.Identity.Name)) { id = Convert.ToInt32(principal.Identity.Name); } guid = principal.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Hash).Value; name = principal.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value; return new Identity(id,guid, name); } return new Identity(0); } } }
Python
UTF-8
1,576
3.90625
4
[]
no_license
# 3-11. Intentional Error: If you haven’t received an index error in one of your programs yet, try to make one happen. Change an index in one of your programs to produce an index error. Make sure you correct the error before closing the program. # Exercise 3-10 presidents = ["Lula", "Bolsonaro", "Putin"] print("hey "+ presidents[0] + ", i am making dinner, pleae come?") print("hey "+ presidents[1] + ", i am making dinner, pleae come?") print("hey "+ presidents[2] + ", i am making dinner, pleae come?") print("Hey " + presidents[2] + " can't make it.") presidents.remove(presidents[2]) presidents.insert(2,"Temer") print("Hey " + presidents[0] + " i am making dinner, please come!") print("Hey " + presidents[1] + " i am making dinner, please come!") print("Hey " + presidents[2] + " i am making dinner, please come!") print("I found a bigger table") presidents.insert(0,"FHC") presidents.insert(1,"Dilma") presidents.append("Collor") print("Hey " + presidents[0] + " i am making dinner, please come!") print("Hey " + presidents[1] + " i am making dinner, please come!") print("Hey " + presidents[2] + " i am making dinner, please come!") print("Hey " + presidents[3] + " i am making dinner, please come!") print("Hey " + presidents[4] + " i am making dinner, please come!") print("Hey " + presidents[5] + " i am making dinner, please come!") print(sorted(presidents)) presidents.sort(reverse=True) print(presidents) print(sorted(presidents,reverse=True)) presidents.reverse() print(presidents) print("The number of people i am inviting is " + str(len(presidents)))
Java
UTF-8
2,245
2.359375
2
[]
no_license
package com.geekyants.ads.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.ObjectUtils; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.geekyants.ads.dto.ResponseDto; import com.geekyants.ads.dto.SlotRequestDto; import com.geekyants.ads.dto.SlotResponseDto; import com.geekyants.ads.exception.InvalidDataException; import com.geekyants.ads.service.SlotService; @RestController @CrossOrigin(allowedHeaders = { "*", "*/" }, origins = { "*", "*/" }) public class SlotController { @Autowired private SlotService slotService; /** * @author Karthika T * * Method is used to Book the Slot * * @param planId , SlotRequestDto * @return ResponseDto Displays the status * code and message */ @PostMapping("/plans/{planId}/slots") public ResponseEntity<ResponseDto> bookSlot(@PathVariable Long planId,@RequestBody SlotRequestDto slotRequest){ if((ObjectUtils.isEmpty(planId))&&(ObjectUtils.isEmpty(slotRequest))){ throw new InvalidDataException("Invalid Request"); } ResponseDto slotResponse=slotService.bookSlot(planId, slotRequest); return new ResponseEntity<ResponseDto>(slotResponse, HttpStatus.OK); } /** * @author Karthika T * * Method is used to get the Slot * * @param planId * @return SlotResponseDto Displays the SlotDetails * code and message */ @GetMapping("/plans/{planId}/slots") public ResponseEntity<SlotResponseDto> getSlots(@PathVariable Long planId){ if((ObjectUtils.isEmpty(planId))){ throw new InvalidDataException("Invalid Request"); } SlotResponseDto slotResponse=slotService.getSlot(planId); return new ResponseEntity<SlotResponseDto>(slotResponse, HttpStatus.OK); } }
JavaScript
UTF-8
1,613
4.25
4
[]
no_license
/* 给定一个二叉树,返回它的 前序 遍历。  示例: 输入: [1,null,2,3] 1 \ 2 / 3 输出: [1,2,3] 进阶: 递归算法很简单,你可以通过迭代算法完成吗? */ /** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @return {number[]} */ var preorderTraversal = function(root) { // 方法1:迭代法 /* 从根节点开始,每次迭代弹出当前栈顶元素,并将其孩子节点压入栈中,先压右孩子再压左孩子。 在这个算法中,输出到最终结果的顺序按照 Top->Bottom 和 Left->Right,符合前序遍历的顺序 */ let stack = [] let output = [] if (root === null) return output // 推入根节点 stack.push(root) while (stack.length) { // 弹出栈顶元素, 并推入output let node = stack.pop() output.push(node.val) // 先考察弹出的元素是否有右节点,再考察是否有左节点,先推右节点后推左节点, // 保证推入后,左节点在右节点上面,保证先弹出左节点,后弹出右节点--故为前序遍历 if (node.right !== null) { // 有右节点,推入 stack.push(node.right) } if (node.left !== null) { // 有左节点,推入 stack.push(node.left) } } return output };
C#
UTF-8
1,450
2.5625
3
[]
no_license
using FontAwesome.Sharp; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace CrewmanSystem { public class CrewPantalla { IconButton _boton; CrewPantalla _padre; Panel _panel; Color _color; BTNtipo _tipo; Form _formulario; bool _n, _a, _e, _b, _f; public CrewPantalla() { } public CrewPantalla(IconButton boton, CrewPantalla padre, Panel panel, Color color, Form formulario, BTNtipo tipo) { Boton = boton; Padre = padre; Panel = panel; Color = color; Formulario = formulario; Tipo = tipo; } public void SetCabecera(bool n, bool a, bool e, bool b, bool f) { N = n; A = a; E = e; B = b; F = f; } public IconButton Boton { get => _boton; set => _boton = value; } public CrewPantalla Padre { get => _padre; set => _padre = value; } public Panel Panel { get => _panel; set => _panel = value; } public Color Color { get => _color; set => _color = value; } public Form Formulario { get => _formulario; set => _formulario = value; } public BTNtipo Tipo { get => _tipo; set => _tipo = value; } public bool N { get => _n; set => _n = value; } public bool A { get => _a; set => _a = value; } public bool E { get => _e; set => _e = value; } public bool B { get => _b; set => _b = value; } public bool F { get => _f; set => _f = value; } } }
Python
UTF-8
373
2.9375
3
[]
no_license
#Tempo: O(n) #Memória: O(n). from typing import List class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: hash_nums = {} for i in range(len(nums)): complement = target - nums[i] if hash_nums.get(complement) != None: return [hash_nums.get(complement), i] hash_nums[nums[i]] = i
Java
UTF-8
3,496
2.109375
2
[]
no_license
package com.caipiao.game.cacher.match; import java.io.File; import java.util.Arrays; import java.util.HashMap; import com.mina.rbc.thread.RbcAbstractThread; import com.mina.rbc.util.CheckUtil; import com.mina.rbc.util.xml.JXmlWapper; public class MatchCacheEngine extends RbcAbstractThread { private String jcpath ; private String bdpath ; private String lqpath; private String mcpath; private MatchCacheManager mcm = MatchCacheManager.getMatchCacheManager(); private HashMap<String,Long> maps = new HashMap<String,Long>(); private final static String[] bdgames = {"85","86","87","88","89","84"}; private final static String[] bddescs = {"spf","cbf","bqc","sxp","jqs","sfgg"}; private final static String[] lqgames = {"lq"}; private final static String[] lqdescs = {"hh"}; private final static String[] jcgames = {"jc"}; private final static String[] jcdescs = {"hh"}; private final static String[] mcgames = {"gj","gyj"}; private final static String[] mcdescs = {"gj","gyj"}; @Override public void thread_init(JXmlWapper elmConfig) { jcpath = elmConfig.getStringValue("@jcpath","") ; lqpath = elmConfig.getStringValue("@lqpath","") ; bdpath = elmConfig.getStringValue("@bdpath","") ; mcpath = elmConfig.getStringValue("@mcpath",""); } @Override public void thread_func() { try { String fileName = ""; if ( !CheckUtil.isNullString(jcpath)) { for (int j=0;j<jcgames.length;j++) { fileName = jcpath + File.separator + "jczq_" + jcdescs[j] + ".xml"; if ( haveChange(fileName)) { cacheFileContext(jcgames[j],fileName); } } } if ( !CheckUtil.isNullString(lqpath)) { for (int j=0;j<lqgames.length;j++) { fileName = lqpath + File.separator + "jclq_" + lqdescs[j] + ".xml"; if ( haveChange(fileName)) { cacheFileContext(lqgames[j],fileName); } } } if ( !CheckUtil.isNullString(bdpath)) { File bdir = new File(bdpath); if ( bdir.exists() ) { String[] ss = bdir.list(); Arrays.sort(ss); int st = ss.length - 20 > 0 ? ss.length - 20:0; for (int i=0;i<st;i++) { for (int j=0;j<bdgames.length;j++) { mcm.removeCache(ss[i] + "_" + bdgames[j]); } } for (int i=st;i<ss.length;i++) { for (int j=0;j<bdgames.length;j++) { fileName = bdpath + File.separator + ss[i] + File.separator + bddescs[j] + ".xml"; if ( haveChange(fileName)) { cacheFileContext(ss[i] + "_" + bdgames[j],fileName); } } } } } if ( !CheckUtil.isNullString(mcpath)) { for (int j=0;j<mcgames.length;j++) { fileName = mcpath + File.separator + mcdescs[j] + ".xml"; if ( haveChange(fileName)) { cacheFileContext(mcgames[j],fileName); } } } } catch (Exception e) { } } private boolean haveChange(String fileName) { boolean bln = false ; File file = new File(fileName); if ( file.exists() ) { Long lold = maps.get(fileName); if ( lold == null || lold.longValue() != file.lastModified() ) { maps.put(fileName, file.lastModified()); bln = true ; } } return bln ; } private void cacheFileContext(String key,String fileName) { try { JXmlWapper xml = JXmlWapper.parse(new File(fileName)); mcm.putCache(key, xml); } catch (Exception e) { maps.clear(); } } }
C++
UTF-8
359
2.96875
3
[]
no_license
#include <iostream> #include <string.h> using std::cin; using std::cout; using std::endl; using std::string; int main() { string input; string total; while (cin >> input) { if (total.empty() == false) total = total + ' ' + input; else total = input; } cout << total << endl; return 0; }
PHP
UTF-8
5,207
2.53125
3
[]
no_license
<?php App::uses('AppModel', 'Model'); /** * Job Model * * @property User $User * @property Account $Account * @property Customer $Customer */ class Job extends AppModel { /** * Validation rules * * @var array */ public $contain=array( 'User'=>array( 'fields'=>array( 'first_name', 'last_name', 'id' ) ), 'Customer'=>array( 'fields'=>array( 'first_name', 'last_name', 'id' ) ) ); public $validate = array( 'id' => array( 'naturalnumber' => array( 'rule' => array('naturalnumber'), ), ), 'description' => array( 'notempty' => array( 'rule' => array('notempty'), ), ), ); /**Purpose: get all job information * created on:8 july 2014 * created by:Abhishek Tripathi */ public function get_all($id=null) { $condition=array(); if(isset($id)){ $condition=array('AND'=>array( 'Job.customer_id'=>$id, )); } $this->recursive=2; $jobs=$this->find('all',array('conditions'=>$condition,'fields'=>array('id','subject','description','created'),'contain'=>$this->contain,'order' => array( 'Job.created' => 'desc' ))); return $jobs; } /**Purpose: get all job information on filter * created on:8 july 2014 * created by:Abhishek Tripathi */ public function get_data_filter($keyword=null) { $conditions=array(); if(isset($keyword)) { append_condition($conditions, 'Job.subject', 'any_like', $keyword); append_condition($conditions, 'Job.description', 'any_like', $keyword); } //debug($conditions);exit; $jobs=$this->find('all',array('conditions'=>array('OR'=>$conditions),'fields'=>array('id','subject','description','created'),'contain'=>$this->contain,'order' => array( 'Job.created' => 'desc'))); return $jobs; } public function get_detail($id=null) { $condition=array(); if(isset($id)){ $condition=array( 'Job.id'=>$id ); } $this->recursive=2; $jobs=$this->find('all',array('conditions'=>$condition,'fields'=>array('id','subject','description','created'),'contain'=>$this->contain,'order' => array( 'Job.created' => 'desc'))); return $jobs; } public function get_all_task(){ $condition=array(); $condition=array('AND'=>array( 'Job.task '=>1, 'Job.cost '=>0 )); $this->recursive=2; $jobs=$this->find('all',array('conditions'=>$condition,'fields'=>array('id','subject','description','created'),'contain'=>$this->contain,'order' => array( 'Job.created' => 'desc' ))); return $jobs; } // aftersave function for manage event log----------------------- public function afterSave($created,$options = array()){ $obj = ClassRegistry::init('Event'); $customer = ClassRegistry::init('Customer'); $customer_detail=$this->Customer->find('first',array('conditions'=>array('Customer.id'=>$this->data['Job']['customer_id']),'fields'=>array('first_name','last_name'))); $event=array('Event'=>array( 'event_type'=>($this->data['Job']['cost']==0)?"Add Task":"Add Job", 'customer_id'=>$this->data['Job']['customer_id'], 'customer_name'=>$customer_detail['Customer']['first_name'].' '.$customer_detail['Customer']['last_name'], 'description'=>$this->data['Job']['subject'], 'job_id'=>$this->getLastInsertID() )); $obj->save($event); //debug($this->data['Job']['round_id']);exit; if(!empty($this->data['Job']['round_id'])){ $schedule=ClassRegistry::init('Schedule'); $data=array('Schedule'=>array( 'round_id'=>$this->data['Job']['round_id'], 'job_id'=>$this->getLastInsertID(), 'round_position'=>$this->data['Job']['round_position'] )); $schedule->save($data); } } // beforedelete function for manage event log--------------------- public function beforeDelete($cascade = true){ $job=$this->find('first',array('conditions'=>array('Job.id'=>$this->id))); $customer = ClassRegistry::init('Customer'); $customer_detail=$this->Customer->find('first',array('conditions'=>array('Customer.id'=>$job['Job']['customer_id']),'fields'=>array('first_name','last_name'))); $obj = ClassRegistry::init('Event'); $event=array('Event'=>array( 'event_type'=>($job['Job']['cost']==0)?"Delete Task":"Delete Job", 'customer_id'=>$job['Job']['customer_id'], 'user_id'=>$job['Job']['user_id'], 'description'=>$job['Job']['subject'], 'customer_name'=>$customer_detail['Customer']['first_name'].' '.$customer_detail['Customer']['last_name'], )); $obj->save($event); } //The Associations below have been created with all possible keys, those that are not needed can be removed /** * belongsTo associations * * @var array */ public $belongsTo = array( 'User' => array( 'className' => 'User', 'foreignKey' => 'user_id', ), 'Customer' => array( 'className' => 'Customer', 'foreignKey' => 'customer_id', ) ); /** * hasMany associations * * @var array */ public $hasMany = array( 'Account' => array( 'className' => 'Account', 'foreignKey' => 'job_id', 'dependent' => true, ), 'Schedule' => array( 'className' => 'Schedule', 'foreignKey' => 'job_id', 'dependent' => true, ) ); }
Java
UTF-8
11,602
2.078125
2
[]
no_license
package com.hzaihua.jfoenix.entity; import com.jfoenix.controls.datamodels.treetable.RecursiveTreeObject; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; public class AWAServerInstruct extends RecursiveTreeObject<AWAServerInstruct> { private StringProperty instructId; //服务器指令编号 private StringProperty measureName; //测点名称 private StringProperty subTree; //测点编码信息 private StringProperty deviceType; //测点设备的型号 private SimpleDoubleProperty longitude; //测点经度 private SimpleDoubleProperty latitude; //测点纬度 private SimpleDoubleProperty userLongitude; //用户指定测点经度 private SimpleDoubleProperty userLatitude; //用户指定测点纬度 private StringProperty functionCode; //功能区代码 private StringProperty measureAddress; //测点地址 private StringProperty deviceAWAID; //测点设备的机号或编号 private SimpleIntegerProperty isAutoAdjust; //自动校准时钟 private SimpleIntegerProperty isReadMin; //分钟历史数据 private SimpleIntegerProperty isReadHour; //小时历史数据 private SimpleIntegerProperty isReadDay; //天历史数据 private SimpleIntegerProperty isReadLp; //Lp的历史数据 private SimpleIntegerProperty isReadLeq1s; //Leq1S的历史数据 private SimpleIntegerProperty isReadOct; //频谱历史数据 private SimpleIntegerProperty isReadWea; //气象历史数据 private SimpleIntegerProperty isReadCar; //交通历史数据 private SimpleIntegerProperty isReadDust; //空气历史数据 private SimpleIntegerProperty isReadEvent; //时间上传 private SimpleIntegerProperty isOpenVoice; //实时语音 @Override public String toString() { return "AWAServerInstruct{" + "instructId=" + instructId + ", measureName=" + measureName + ", subTree=" + subTree + ", deviceType=" + deviceType + ", longitude=" + longitude + ", latitude=" + latitude + ", userLongitude=" + userLongitude + ", userLatitude=" + userLatitude + ", functionCode=" + functionCode + ", measureAddress=" + measureAddress + ", deviceAWAID=" + deviceAWAID + ", isAutoAdjust=" + isAutoAdjust + ", isReadMin=" + isReadMin + ", isReadHour=" + isReadHour + ", isReadDay=" + isReadDay + ", isReadLp=" + isReadLp + ", isReadLeq1s=" + isReadLeq1s + ", isReadOct=" + isReadOct + ", isReadWea=" + isReadWea + ", isReadCar=" + isReadCar + ", isReadDust=" + isReadDust + ", isReadEvent=" + isReadEvent + ", isOpenVoice=" + isOpenVoice + '}'; } public String getInstructId() { return instructId.get(); } public StringProperty instructIdProperty() { return instructId; } public void setInstructId(String instructId) { this.instructId = new SimpleStringProperty(instructId); } public String getMeasureName() { return measureName.get(); } public StringProperty measureNameProperty() { return measureName; } public void setMeasureName(String measureName) { this.measureName = new SimpleStringProperty(measureName); } public String getSubTree() { return subTree.get(); } public StringProperty subTreeProperty() { return subTree; } public void setSubTree(String subTree) { this.subTree = new SimpleStringProperty(subTree); } public String getDeviceType() { return deviceType.get(); } public StringProperty deviceTypeProperty() { return deviceType; } public void setDeviceType(String deviceType) { this.deviceType = new SimpleStringProperty(deviceType); } public double getLongitude() { return longitude.get(); } public SimpleDoubleProperty longitudeProperty() { return longitude; } public void setLongitude(double longitude) { this.longitude = new SimpleDoubleProperty(longitude); } public double getLatitude() { return latitude.get(); } public SimpleDoubleProperty latitudeProperty() { return latitude; } public void setLatitude(double latitude) { this.latitude = new SimpleDoubleProperty(latitude); } public double getUserLongitude() { return userLongitude.get(); } public SimpleDoubleProperty userLongitudeProperty() { return userLongitude; } public void setUserLongitude(double userLongitude) { this.userLongitude = new SimpleDoubleProperty(userLongitude); } public double getUserLatitude() { return userLatitude.get(); } public SimpleDoubleProperty userLatitudeProperty() { return userLatitude; } public void setUserLatitude(double userLatitude) { this.userLatitude = new SimpleDoubleProperty(userLatitude); } public String getFunctionCode() { return functionCode.get(); } public StringProperty functionCodeProperty() { return functionCode; } public void setFunctionCode(String functionCode) { this.functionCode = new SimpleStringProperty(functionCode); } public String getMeasureAddress() { return measureAddress.get(); } public StringProperty measureAddressProperty() { return measureAddress; } public void setMeasureAddress(String measureAddress) { this.measureAddress = new SimpleStringProperty(measureAddress); } public String getDeviceAWAID() { return deviceAWAID.get(); } public StringProperty deviceAWAIDProperty() { return deviceAWAID; } public void setDeviceAWAID(String deviceAWAID) { this.deviceAWAID = new SimpleStringProperty(deviceAWAID); } public int getIsAutoAdjust() { return isAutoAdjust.get(); } public SimpleIntegerProperty isAutoAdjustProperty() { return isAutoAdjust; } public void setIsAutoAdjust(int isAutoAdjust) { this.isAutoAdjust = new SimpleIntegerProperty(isAutoAdjust); } public int getIsReadMin() { return isReadMin.get(); } public SimpleIntegerProperty isReadMinProperty() { return isReadMin; } public void setIsReadMin(int isReadMin) { this.isReadMin = new SimpleIntegerProperty(isReadMin); } public int getIsReadHour() { return isReadHour.get(); } public SimpleIntegerProperty isReadHourProperty() { return isReadHour; } public void setIsReadHour(int isReadHour) { this.isReadHour = new SimpleIntegerProperty(isReadHour); } public int getIsReadDay() { return isReadDay.get(); } public SimpleIntegerProperty isReadDayProperty() { return isReadDay; } public void setIsReadDay(int isReadDay) { this.isReadDay = new SimpleIntegerProperty(isReadDay); } public int getIsReadLp() { return isReadLp.get(); } public SimpleIntegerProperty isReadLpProperty() { return isReadLp; } public void setIsReadLp(int isReadLp) { this.isReadLp = new SimpleIntegerProperty(isReadLp); } public int getIsReadLeq1s() { return isReadLeq1s.get(); } public SimpleIntegerProperty isReadLeq1sProperty() { return isReadLeq1s; } public void setIsReadLeq1s(int isReadLeq1s) { this.isReadLeq1s = new SimpleIntegerProperty(isReadLeq1s); } public int getIsReadOct() { return isReadOct.get(); } public SimpleIntegerProperty isReadOctProperty() { return isReadOct; } public void setIsReadOct(int isReadOct) { this.isReadOct = new SimpleIntegerProperty(isReadOct); } public int getIsReadWea() { return isReadWea.get(); } public SimpleIntegerProperty isReadWeaProperty() { return isReadWea; } public void setIsReadWea(int isReadWea) { this.isReadWea = new SimpleIntegerProperty(isReadWea); } public int getIsReadCar() { return isReadCar.get(); } public SimpleIntegerProperty isReadCarProperty() { return isReadCar; } public void setIsReadCar(int isReadCar) { this.isReadCar = new SimpleIntegerProperty(isReadCar); } public int getIsReadDust() { return isReadDust.get(); } public SimpleIntegerProperty isReadDustProperty() { return isReadDust; } public void setIsReadDust(int isReadDust) { this.isReadDust = new SimpleIntegerProperty(isReadDust); } public int getIsReadEvent() { return isReadEvent.get(); } public SimpleIntegerProperty isReadEventProperty() { return isReadEvent; } public void setIsReadEvent(int isReadEvent) { this.isReadEvent = new SimpleIntegerProperty(isReadEvent); } public int getIsOpenVoice() { return isOpenVoice.get(); } public SimpleIntegerProperty isOpenVoiceProperty() { return isOpenVoice; } public void setIsOpenVoice(int isOpenVoice) { this.isOpenVoice = new SimpleIntegerProperty(isOpenVoice); } public AWAServerInstruct(String instructId, String measureName, String subTree, String deviceType, double longitude, double latitude, double userLongitude, double userLatitude, String functionCode, String measureAddress, String deviceAWAID, int isAutoAdjust, int isReadMin, int isReadHour, int isReadDay, int isReadLp, int isReadLeq1s, int isReadOct, int isReadWea, int isReadCar, int isReadDust, int isReadEvent, int isOpenVoice) { this.instructId = new SimpleStringProperty(instructId); this.measureName = new SimpleStringProperty(measureName); this.subTree = new SimpleStringProperty(subTree); this.deviceType = new SimpleStringProperty(deviceType); this.longitude = new SimpleDoubleProperty(longitude); this.latitude = new SimpleDoubleProperty(latitude); this.userLongitude = new SimpleDoubleProperty(userLongitude); this.userLatitude = new SimpleDoubleProperty(userLatitude); this.functionCode = new SimpleStringProperty(functionCode); this.measureAddress = new SimpleStringProperty(measureAddress); this.deviceAWAID = new SimpleStringProperty(deviceAWAID); this.isAutoAdjust = new SimpleIntegerProperty(isAutoAdjust); this.isReadMin = new SimpleIntegerProperty(isReadMin); this.isReadHour = new SimpleIntegerProperty(isReadHour); this.isReadDay = new SimpleIntegerProperty(isReadDay); this.isReadLp = new SimpleIntegerProperty(isReadLp); this.isReadLeq1s = new SimpleIntegerProperty(isReadLeq1s); this.isReadOct = new SimpleIntegerProperty(isReadOct); this.isReadWea = new SimpleIntegerProperty(isReadWea); this.isReadCar = new SimpleIntegerProperty(isReadCar); this.isReadDust = new SimpleIntegerProperty(isReadDust); this.isReadEvent = new SimpleIntegerProperty(isReadEvent); this.isOpenVoice = new SimpleIntegerProperty(isOpenVoice); } public AWAServerInstruct() { } }
Java
UTF-8
834
2.140625
2
[]
no_license
package com.buzz.jwtdemo.service; import java.util.HashMap; import com.buzz.jwtdemo.common.JwtMessageKey; import com.buzz.jwtdemo.common.MessageUtil; import com.buzz.jwtdemo.common.ResponseConstants; /**************************************************************************************************** * Service Layer 의 공통 로직 구현 ****************************************************************************************************/ public class JwtBaseService { protected HashMap<String,Object> makeResultMap() { HashMap<String,Object> resultMap = new HashMap<String,Object>(); resultMap.put(ResponseConstants.STATUS, ResponseConstants.RESULT_SUCCESS); resultMap.put(ResponseConstants.MESSAGE,MessageUtil.getMessage(JwtMessageKey.MSG_KEY_OK ) ); return resultMap; } }
C#
UTF-8
449
2.671875
3
[]
no_license
using System; using System.Collections.Generic; using System.Text; namespace TDDMicroExercises.TirePressureMonitoringSystem { class SensorMock : ISensor { Queue<double> _queue =new Queue<double>(); public void PushNextPressurePsiValue(double value) { _queue.Enqueue(value); } public double PopNextPressurePsiValue() { return _queue.Dequeue(); } } }
JavaScript
UTF-8
21,768
2.875
3
[]
no_license
// ================================================================================================ // // wayfarer.js // // Author: Thomas Norman (with thanks to Isabel Broome-Nicholson!) // Created: 10/08/2013 // // This is the entry point for the Wayfarer web service. // // Uses: // - Express: A web application framework for node.js // - Mongoose: Mongodb object modelling for node.js // // ================================================================================================ // ------------------------------------------------------------------------------------------------ // Server setup // ------------------------------------------------------------------------------------------------ // Express is a framework for node.js, we need it var express = require("express"); // Get the appropriate port or default to 5000. var port = process.env.PORT || 5000; // Set up the application, using the express framework var app = express(); app.use(express.logger()); app.use(express.limit('200kb')); app.use(express.bodyParser()); // allows the app to read JSON from body app.set('title', 'Wayfarer'); // Commence listening! app.listen(port, function() { console.log("Listening on " + port); }); // ------------------------------------------------------------------------------------------------ // Database setup // ------------------------------------------------------------------------------------------------ // Mongoose provides mongodb object modelling for node.js, we need it var mongoose = require ("mongoose"); // Determine database URI to connect to. Uses local host if none found. var dbURI = process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || 'mongodb://localhost/wayfarer'; // Connect to the database mongoose.connect(dbURI, function (err, res) { if (err) { console.log ('DB: ERROR connecting to ' + dbURI + '. ' + err); } else { console.log ('DB: Connected to ' + dbURI); } }); // Get the mongoose models var models = require('./mongooseModels'); var userModel, subjectModel; models.defineModels(mongoose, function() { userModel = mongoose.model('User'); subjectModel = mongoose.model('Subject'); }) // ------------------------------------------------------------------------------------------------ // Other application stuffs setup // ------------------------------------------------------------------------------------------------ // Load datapool var datapool; fs = require('fs'); fs.readFile('datapool.dat', function(err, data) { if (err) { console.log ('ERROR: Unable to load datapool.dat file!'); process.exit(1); } datapool = JSON.parse(data); }); // Set up the Basic Authentication function. // When authentication fails for any reason, 401 is automatically returned. var authenticate = express.basicAuth(function(email, password, callback) { // Find the user by email (which is unique) userModel.findOne({'email':email}, function(err, user){ // Pass errors on to the callback function instead of failing immediately. if (!err){ // User not found? if (!user){ console.log('authenticate: No user exists with that email address'); err = new Error('No user exists with that email address.'); // User found: authenticate them by comparing their password. // Creates a new error if they don't match, which will automatically throw a 401. } else if (!user.authenticate(password)){ err = new Error('Email and password do not match.'); } } // Callback with any errors that have arisen, and the user's profile. callback(err, user); }); }); // ------------------------------------------------------------------------------------------------ // API end point setup // ------------------------------------------------------------------------------------------------ // Root app.get('/', function(request, response){ response.send('See README.md in Wayfarer-Server git for API details.'); }); // GET '/users' // Requires authentication. // Returns the authenticated user. app.get('/users', authenticate, function(request, response){ var user = request.user.returnType; response.send(200, JSON.stringify(user, undefined, 2)); }); // PUT '/users' // { // "email": "bigmomma69@gmail.com", // "password": "password", // "name": "Lady Sass" // } // Creates a user. app.put('/users', function(request, response){ // Validate JSON fields exist if (!request.body || !request.body.email || !request.body.name || !request.body.password){ console.log("PUT /users: Body missing required information."); response.send(400, "Body missing required information."); return; } // Tidy up input request.body.email = request.body.email.trim().toLowerCase(); request.body.name = request.body.name.trim().capitalize(); // Find any users with the same email userModel.find({'email':request.body.email}, function (err, existingUsers) { if (err) { internalError(err, response); return; } // Email exists: bad! They must be unique if (existingUsers.length != 0) { console.log('PUT /users: An account already exists for that email.'); console.log(JSON.stringify(existingUsers, undefined, 2)); response.send(403, 'An account already exists for that email.'); return; } // Create the user var newUser = new userModel(request.body); newUser.setPassword(request.body.password); // Save user in db newUser.save(function(err){ if (err) { internalError(err, response); return; } // Send 'created' response including user console.log('PUT /users: New user created: ' + JSON.stringify(newUser, undefined, 2)); response.send(201, newUser.returnType); }); }); }); // POST '/users/{id}' // { // "name": "Prince" // } // Updates a given user app.post('/users', authenticate, function(request, response){ // Validate JSON fields exist if (!request.body){ console.log("POST /users Body missing or missing required information."); response.send(400, "Body missing required information."); return; } // If subjectId, make sure that subject exists if (request.body.subjectId) { subjectModel.findOne({ _id: request.body.subjectId }, function(err, subject) { if (err) { internalError(err, response); return; } if (!subject){ response.send(404, 'That subject could not be found.'); return; } }); } // If email, make sure it is unique userModel.find({'email':request.body.email}, function (err, existingUsers) { if (err) { internalError(err, response); return; } if (existingUsers.length != 0) { console.log('POST /users: An account already exists with that email.'); console.log(JSON.stringify(existingUsers, undefined, 2)); response.send(403, 'An account already exists with that email address.'); return; } }); // "password" as it exists in the database is different to the json body, so it needs // to be removed before updating the user... if it exists. var password; if (request.body.password) { password = request.body.password; delete request.body.password; } // Find and update the user. userModel.findByIdAndUpdate(request.user.returnType.id, request.body, function(err, user) { if (err) { internalError(err, response); return; } if (!user){ response.send(404, 'That user could not be found: '+request.params.id); return; } // Also manually update password if supplied, in order to encrypt it. // There is a more 'automatic' method but in the interests of mental brevity this will be fine if (password) { user.setPassword(password); user.save(function(err){ if (err) { internalError(err, response); return; } }); } console.log('POST /users/{id}: Updated user with id "'+request.user.returnType.id+'"'); response.send(200, JSON.stringify(user.returnType, undefined, 2)); }); }); // DELETE '/users' // Deletes the authenticated user app.delete('/users', authenticate, function(request, response){ // Find the user in database var query = userModel.remove({ _id: request.user.returnType.id }, function(err, user) { if (err) { internalError(err, response); return; } if (!user){ response.send(404, 'That user could not be found.'); return; } response.send(200, "User deleted"); }); }); // PUT '/subjects' // { // "name": "Moe" // } // Creates a subject and returns its information and the datapool. // Also sets the authenticated user's subjectId to the new subject's id. app.put('/subjects', authenticate, function(request, response){ // Validate JSON fields exist if (!request.body || !request.body.name){ console.log("PUT /subjects: Body missing or missing required information."); response.send(400, "Body missing required information."); return; } // Create the subject request.body.name = request.body.name.trim().capitalize(); var newSubject = new subjectModel(request.body); // Save subject in db newSubject.save(function(err){ if (err) { internalError(err, response); return; } }); // TODO if time: // if user has a subjectId already // Query database for users with subjectId = subjectId // if no user found // delete subject from database // Save subjectId in user userModel.findByIdAndUpdate(request.user.returnType.id, { $set: { subjectId: newSubject.returnType.id }}, function(err, user) { if (err) { internalError(err, response); return; } if (!user){ // should never happen response.send(500, 'That user could not be found: '+request.params.id); return; } }); // Send datapool back with response var toReturn = newSubject.returnType; toReturn.datapool = datapool; console.log('PUT /subjects: New subject created: ' + JSON.stringify(newSubject, undefined, 2)); response.send(201, toReturn); }); // GET '/subjects' // Returns the subject watched by the authenticated user. app.get('/subjects', authenticate, function(request, response){ // Find the subject in database var query = subjectModel.findOne({ _id: request.user.returnType.subjectId }, function(err, subject) { if (err) { internalError(err, response); return; } if (!subject){ response.send(404, 'That subject could not be found.'); return; } response.send(JSON.stringify(subject.returnType, undefined, 2)); }); }); // POST '/subjects // { // "state": {"blah":"blah"} // } // Updates the subject watched by the authenticated user. app.post('/subjects', authenticate, function(request, response){ // Validate JSON fields exist if (!request.body){ console.log("POST /subjects: Body missing or missing required information."); response.send(400, "Body missing required information."); return; } // Update the subject in database subjectModel.findByIdAndUpdate(request.user.returnType.subjectId, request.body, function(err, subject) { if (err) { internalError(err, response); return; } if (!subject){ response.send(404, 'That subject could not be found.'); return; } console.log('POST /subjects: Updated subject "'+request.user.returnType.subjectId+'"'); response.send(200, JSON.stringify(subject.returnType, undefined, 2)); }); }); // ------------------------------------------------------------------------------------------------ // Administration end points // TODO: use admin authentication // ------------------------------------------------------------------------------------------------ // Gets the datapool app.get('/datapool', function(request, response){ response.send(200, JSON.stringify(datapool, undefined, 2)); }); // Updates the datapool app.post('/datapool', function(request, response){ // Validate JSON fields exist if (!request.body){ console.log("POST /datapool: Body missing or missing required information."); response.send(400, "Body missing required information."); return; } // Update datapool field datapool = request.body; // Write datapool back to file fs.writeFile("datapool.dat", JSON.stringify(datapool, undefined, 2), function(err) { if(err) { console.log(err); } else { console.log("POST /datapool: Datapool updated"); } }); response.send(200); }); // ------------------------------------------------------------------------------------------------ // Older end points that I'm not ready to retire // ------------------------------------------------------------------------------------------------ // GET '/allUsers' // Returns all users. TEMPORARY DEV THING. app.get('/allUsers', function(request, response){ // Find all users in database var query = userModel.find( function(err, users) { if (err) { internalError(err, response); return; } // Send users. response.send(JSON.stringify(users, undefined, 2)); }); }); // GET '/users/{id}' // Returns the user with the given id. app.get('/users/:id', function(request, response){ // Find the user in database var query = userModel.findById(request.params.id, function(err, user) { if (err) { internalError(err, response); return; } // User not found if (!user){ response.send(404, 'That user could not be found.'); return; } // User found; send them back. response.send(JSON.stringify(user.returnType, undefined, 2)); }); }); // POST '/users/{id}' // { // "name": "Prince" // } // Updates a given user app.post('/users/:id', function(request, response){ // Validate JSON fields exist if (!request.body){ console.log("POST /users/{id}: Body missing or missing required information."); response.send(400, "Body missing required information."); return; } // If subjectId, make sure that subject exists if (request.body.subjectId) { subjectModel.findOne({ _id: request.body.subjectId }, function(err, subject) { if (err) { internalError(err, response); return; } if (!subject){ response.send(404, 'That subject could not be found.'); return; } }); } // "password" as it exists in the database is different to the json body, so it needs // to be removed before updating the user... if it exists. var password; if (request.body.password) { password = request.body.password; delete request.body.password; } // Find and update the user. userModel.findByIdAndUpdate(request.params.id, request.body, function(err, user) { if (err) { internalError(err, response); return; } if (!user){ response.send(404, 'That user could not be found: '+request.params.id); return; } // Also manually update password if supplied, in order to encrypt it. // There is a more 'automatic' method but in the interests of mental brevity this will be fine if (password) { user.setPassword(password); user.save(function(err){ if (err) { internalError(err, response); return; } }); } console.log('POST /users/{id}: Updated user with id "'+request.params.id+'"'); response.send(200, JSON.stringify(user.returnType, undefined, 2)); }); }); // DELETE '/users/{id}' // Deletes the user with the given id. app.delete('/users/:id', function(request, response){ // Find the user in database var query = userModel.remove({ _id: request.params.id }, function(err, user) { if (err) { internalError(err, response); return; } if (!user){ response.send(404, 'That user could not be found.'); return; } response.send(200, "User deleted"); }); }); // GET '/subjects' // Returns all subjects. TEMPORARY DEV THING. app.get('/allSubjects', function(request, response){ var query = subjectModel.find( function(err, subjects) { if (err) { internalError(err, response); return; } response.send(JSON.stringify(subjects, undefined, 2)); }); }); // PUT '/subjects' // { // "name": "Moe" // } // Creates a subject and returns its information and the datapool. app.put('/subjects', function(request, response){ // Validate JSON fields exist if (!request.body || !request.body.name){ console.log("PUT /subjects: Body missing or missing required information."); response.send(400, "Body missing required information."); return; } // Create the subject request.body.name = request.body.name.trim().capitalize(); var newSubject = new subjectModel(request.body); // Save user in db newSubject.save(function(err){ if (err) { internalError(err, response); return; } // Send datapool back with response var toReturn = newSubject.returnType; toReturn.datapool = datapool; console.log('PUT /subjects: New subject created: ' + JSON.stringify(newSubject, undefined, 2)); response.send(201, toReturn); }); }); // GET '/subjects' // Returns all subjects. TEMPORARY DEV THING. app.get('/subjects', function(request, response){ var query = subjectModel.find( function(err, subjects) { if (err) { internalError(err, response); return; } response.send(JSON.stringify(subjects, undefined, 2)); }); }); // GET '/subjects/{id}' // Returns the subject with the given id. app.get('/subjects/:id', function(request, response){ // Find the subject in database var query = subjectModel.findOne({ _id: request.params.id }, function(err, subject) { if (err) { internalError(err, response); return; } if (!subject){ response.send(404, 'That subject could not be found.'); return; } response.send(JSON.stringify(subject.returnType, undefined, 2)); }); }); // POST '/subjects/{id}' // { // "state": "blah" // } // Updates a given subject app.post('/subjects/:id', function(request, response){ // Validate JSON fields exist if (!request.body){ console.log("POST /subjects/{id}: Body missing or missing required information."); response.send(400, "Body missing required information."); return; } // Find the subject in database subjectModel.update({ _id: request.params.id }, request.body, function(err, numberAffected, raw) { if (err) { internalError(err, response); return; } if (numberAffected == 0){ response.send(404, 'That subject could not be found.'); return; } console.log('POST /subjects/{id}: Updated subject "'+request.params.id+'"'); response.send(200); }); }); // DELETE '/subjects/{id}' // Deletes the subject with the given id. app.delete('/subjects/:id', function(request, response){ // Find the subject in database var query = subjectModel.remove({ _id: request.params.id }, function(err, user) { if (err) { internalError(err, response); return; } if (!user){ response.send(404, 'That subject could not be found.'); return; } response.send(200, "Subject deleted"); }); }); // GET '/steps' // Returns a list of all steps. TEMP DEV THING app.get('/steps', function(request, response){ var jsonTest = [ { id:1, title:'Check for possible weapons', description:'If you believe your friend may have weapons, ask them directly about it. Convince them to give up the weapon. Act like an authority figure.' }, { id:2, title:'Don’t leave them alone', description:'It can be dangerous to leave a suicidal individual alone, even for a few minutes. If you have to go, make sure there is someone else to take care of them.' }, { id:3, title:'Listen to them', description:'Listen carefully to whatever they say. If they are your friend they will likely be honest with you about how close they are to suicide.' }, { id:4, title:'Offer them support', description:'Remind the person that you will support them no matter how bad things get. They are unlikely to commit suicide while you are around.' }, { id:5, title:'Ask questions', description:'Asking them in more detail about why they are depressed is a good idea to share the burden. Don’t worry about depressing them further by talking about it.' }, { id:6, title:'Get them help', description:'The individual is not likely to seek help on their own. Asking them if they would accept expert help is likely the only way they will get it.' } ]; var jsonString = JSON.stringify(jsonTest, undefined, 2); response.send(200, jsonString); }); // GET '/steps/{id}' // Returns the informations pertaining to the step with the given id TEMP DEV THING app.get('/steps/:id', function(request, response){ response.send(500, "Not yet implemented"); }); // Get test TEMP DEV THING app.get('/getTest', function(request, response){ var jsonTest = { name:'Thomas Danger Norman', age:28, sex:'yes please' }; var jsonString = JSON.stringify(jsonTest, undefined, 2); response.send(200, jsonString); }); // Post test TEMP DEV THING app.post('/postTest', function(request, response){ response.send(200, 'Post test success.'); }); // ------------------------------------------------------------------------------------------------ // Helper methods // ------------------------------------------------------------------------------------------------ function internalError(err, response) { console.log(err); response.send(500, err); } function isValidJSON(json) { try { JSON.parse(json); return true; } catch (e) { return false; } } String.prototype.capitalize = function() { return this.charAt(0).toUpperCase() + this.substr(1).toLowerCase(); }; String.prototype.toTitleCase = function() { return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}); }
Python
UTF-8
2,057
2.546875
3
[ "WTFPL" ]
permissive
#!/usr/bin/env python # coding:utf-8 import urllib from bs4 import BeautifulSoup import re import json import os import functools def cache(func): """cache the value in memory """ table = func.cache = {} @functools.wraps(func) def wrapper(*args, **kwargs): key = '{0}{1}'.format(args, kwargs) if key not in table: table[key] = func(*args, **kwargs) return table[key] return wrapper @cache def _get_pm25_data(city): """get pm2.5 data per hour for every city """ html_doc = urllib.urlopen('http://m.cnpm25.cn/pm/%s.html' % (city, )).read().decode('utf-8') soup = BeautifulSoup(html_doc) tempdata = [] alldata = {} try: if "url" in soup.html.head.prettify(): urllib.urlopen(soup.html.head.meta['content'].split(";")[1][4:]) html_doc = urllib.urlopen('http://m.cnpm25.cn/pm/%s.html' % (city, )).read().decode('utf-8') soup = BeautifulSoup(html_doc) except: pass for x in soup.find_all('div', 'dl1'): try: x.img.extract() except: pass tempdata.append(x.string) alldata[tempdata[0]] = [] alldata[tempdata[1]] = [] alldata[tempdata[2]] = [] for i in range(3, len(tempdata[3:]), 3): alldata[tempdata[0]].append(tempdata[i]) alldata[tempdata[1]].append(tempdata[i + 1]) alldata[tempdata[2]].append(tempdata[i + 2]) tempdata = [] for x in soup.find_all('div', 'dl2'): try: x.img.extract() except: pass tempdata.append(x.string) alldata[tempdata[0]] = tempdata[1:] twothings = soup.find_all('div', 'main_aqi') twothings[0].div.span.extract() alldata['now'] = twothings[0].div.string twothings[1].font.script.extract() alldata['time'] = twothings[1].font.string return alldata def get(city): if city: try: return _get_pm25_data(city) except: return '错误: 请检查您是否拼错城市'
SQL
UTF-8
2,605
4.125
4
[]
no_license
CREATE TABLE room ( room_id int PRIMARY KEY, rate numeric(5,2), bed_type varchar(15), bed_qty int ); CREATE TABLE guest ( guest_id int PRIMARY KEY, first_name varchar(35), last_name varchar(35), phone_number varchar(10), email varchar(62) ); CREATE TABLE booking ( room_id int REFERENCES room(room_id), guest_id int REFERENCES guest(guest_id), check_in_date date, check_out_date date ); INSERT INTO room (room_id, rate, bed_type, bed_qty) VALUES (101, 99.99, 'full', 1), (102, 99.99, 'full', 1), (103, 119.99, 'full', 2), (104, 119.99, 'full', 2), (105, 109.99, 'queen', 1), (106, 109.99, 'queen', 1), (107, 149.99, 'queen', 2), (108, 149.99, 'queen', 2), (109, 139.99, 'king', 1), (110, 139.99, 'king', 1); INSERT INTO guest (guest_id, first_name, last_name, phone_number, email) VALUES (100001, 'Tory', 'Herman', '6515551234', 'tory.herman12@gmail.com'), (100002, 'Eric', 'Northman', '5045550001', 'eric@fangtasia.com'), (100003, 'Sam', 'Merlotte', '3185551111', 'sam@merlottes.com'), (100004, 'Sookie', 'Stackhouse', '3185555309', 'sookie@merlottes.com'), (100005, 'Andy', 'Bellefleur', '3375555050', 'sheriff.bellefleur@renardpd.gov'); INSERT INTO booking (room_id, guest_id, check_in_date, check_out_date) VALUES (101, 100001, '2017-09-22', '2017-09-24'), (103, 100001, '2017-09-22', '2017-09-24'), (101, 100005, '2017-09-24', '2017-09-30'), (104, 100003, '2017-10-31', '2017-11-03'), (110, 100001, '2018-01-05', '2018-01-08'), (106, 100002, '2017-09-18', '2017-09-19'), (107, 100005, '2017-10-14', '2017-10-21'), (104, 100003, '2017-12-24', '2017-12-27'); /* find a guest who exists in the db who has not booked a room */ SELECT CONCAT(g.first_name, ' ', g.last_name) AS name FROM guest g LEFT OUTER JOIN booking b ON g.guest_id = b.guest_id WHERE b.room_id IS NULL; /* find bookings for a guest who has booked two rooms for the same dates */ SELECT CONCAT(g.first_name, ' ', g.last_name) AS name, b.check_in_date, b.check_out_date, COUNT(*) AS rooms_booked FROM guest g JOIN booking b ON g.guest_id = b.guest_id GROUP BY b.check_in_date, b.check_out_date, g.guest_id HAVING COUNT(*) > 1; /* find books for a guest who has booked one room several times */ SELECT CONCAT(g.first_name, ' ', g.last_name) AS name, r.room_id, COUNT(*) AS bookings FROM booking b JOIN guest g ON b.guest_id = g.guest_id JOIN room r ON b.room_id = r.room_id GROUP BY g.guest_id, r.room_id HAVING COUNT(*) > 1; /* find number of unique guests who have booked the same room */ SELECT r.room_id, COUNT(DISTINCT(r.room_id, g.guest_id)) AS unique_guests FROM booking b JOIN room r ON b.room_id = r.room_id JOIN guest g ON b.guest_id = g.guest_id GROUP BY r.room_id;
Markdown
UTF-8
1,465
2.65625
3
[]
no_license
# xrope [![Build Status](https://travis-ci.org/wasabiz/xrope.png)](https://travis-ci.org/wasabiz/xrope) rope data structre ## Usage Just include "xrope.h" anywhere you want to use xrope! ## API ```c typedef struct xrope xrope; /** * | name | frees buffer? | end with NULL? | complexity | misc * | ---- | ---- | ---- | ---- | --- * | xr_new_cstr | no | yes | O(1) | xr_new(_lit) * | xr_new_imbed | no | no | O(1) | * | xr_new_move | yes | yes | O(1) | * | xr_new_copy | yes | no | O(n) | */ #define xr_new(cstr) xr_new_cstr(cstr, strlen(cstr)) #define xr_new_lit(cstr) xr_new_cstr(cstr, sizeof(cstr) - 1) static inline xrope *xr_new_cstr(const char *, size_t); static inline xrope *xr_new_imbed(const char *, size_t); static inline xrope *xr_new_move(const char *, size_t); static inline xrope *xr_new_copy(const char *, size_t); static inline void XROPE_INCREF(xrope *); static inline void XROPE_DECREF(xrope *); static inline size_t xr_len(xrope *); static inline char xr_at(xrope *, size_t); static inline xrope *xr_cat(xrope *, xrope *); static inline xrope *xr_sub(xrope *, size_t, size_t); static inline const char *xr_cstr(xrope *); /* returns NULL-terminated string */ ``` ## TODO - self-balancing - unicode support? - custom allocator - more test cases ## Author Yuichi Nishiwaki (yuichi@idylls.jp)
Markdown
UTF-8
6,966
3.296875
3
[]
no_license
--- layout: post title: "How-to-debug-mobile-web-app" date: 2018-04-22 1:38:28 +0800 categories: jekyll update --- Today Mobile Web Hybrid Apps are popular and the fornt end develpers are facing the difficult problems. The mobile web app needs more careful looking care of. The adaptive, the code debugging etc. The article will explore some key points for beginners. <B>The first: Adaptive, `rem`:</B> It's a wonderful and perfect solution to mobile adaptive. In the past we use Media Query tech to solve mobile adaptive problems. You have to code different style files to meet the demand of different ratio of mobile device. Now you just code a single style which will be just the same in all kinds of devices. https://developer.mozilla.org/en-US/docs/Web/CSS/font-size `rem values were invented in order to sidestep the compounding problem. rem values are relative to the root html element, not the parent element. In other words, it lets you specify a font size in a relative fashion without being affected by the size of the parent` demo code: {% highlight css %} html { font-size: 62.5%; /* font-size 1em = 10px on default browser settings */ } span { font-size: 1.6rem; } {% endhighlight %} But before exploring the `rem` unit we firstly need think what's the meaning of the unit on earth that is traced back to philosophy. In the dark age or religious era we needn't know about the nature because God knows everything create everything and we only obeyed the rule of his. But after the era we began to know about nature or things. When I see a physics objects what I've seen. The fact I see its properties including width, height, weigh, taste, dense etc. But how I eliminate all of those? The concepts of human is about kinds or types that is ideal. To agreement we invent `Units` to measure all the things. Now we have SEVEN basic Units those're `The International System of Units (SI) defines seven units of measure as a basic set from which all other SI units can be derived. The SI base units and their physical quantities are the metre for measurement of length, the kilogram for mass, the second for time, the ampere for electric current, the kelvin for temperature, the candela for luminous intensity, and the mole for amount of substance.` We can code a test suit to describe the above units: {% highlight typescript %} describe(`https://en.wikipedia.org/wiki/SI_base_unit`, () => { it(`Seven SI base units`, () => { const SI = [{ "Name": "metre", "Symbol": "m", "Measure": "length", "DimensionSymbol": "L" }, { "Name": "kilogram", "Symbol": "kg", "Measure": "mass", "DimensionSymbol": "M" }, { "Name": "second", "Symbol": "s", "Measure": "time", "DimensionSymbol": "T" }, { "Name": "ampere", "Symbol": "A", "Measure": "electric current", "DimensionSymbol": "I" }, { "Name": "kelvin", "Symbol": "K", "Measure": "thermodynamic temperature", "DimensionSymbol": "Θ" }, { "Name": "mole", "Symbol": "mol", "Measure": "amount of substance", "DimensionSymbol": "N" }, { "Name": "candela", "Symbol": "cd", "Measure": "luminous intensity", "DimensionSymbol": "J" }]; expect(SI.length).toBe(7) }); it(`"The metre is the length of the path travelled by light in vacuum during a time interval of 1 / 299792458 of a second."`, () => { const metreUnit = 1, LightSpeed = metreUnit * 299792458, threeHundredThounsandMetres = 30 * 1e5 * 1e3; expect(LightSpeed).toBeLessThan(threeHundredThounsandMetres) }); }); {% endhighlight %} What's the meaning? Metre(l) is the basic unit of Length. It's akin to the pixel(px) in physical measurement of DOM elements that is called `Absolute length units`. Of course there're seveal units like px e.g. cm, mm, ... We code a test unit to describe that: {% highlight typescript %} describe(`Absolute length units represent a physical measurement when the physical properties of the output medium are known, such as for print layout.`, () => { it(`1px = 1/96th of 1in,One inch. 1in = 2.54cm = 96px`, () => { const metre = 1 const cm = 1e-2 * metre const px = 2.54 * cm / 96; expect((px).toFixed(5)).toBe("0.00026") }); }); {% endhighlight %} What does the test tell us? `px` is not the basic unit of everything. It can be evaluated by METRE through the bridge of INCH. So we know we need a length measuement when developing front-end page. We set all kinds of absolute length units for web development. Those length units derived from the ultimate length unit METRE. p.s. Why does metre is constant? It's measured by the speed of light. Light speed in vacuum is absolute and unchangable. The statement is important for the modern science. We know Einstain's Relative Theory is based on the light speed exeriments. Einstain doesn't know why the light speed is constant but he is the first human knowing what it'll lead to. From then the ideal of human in the macro world is changed for ever. Next question: Why the `rem` unit introduced into web development? `rem Represents the font-size of the root element (typically <html>). When used within the root element font-size, it represents its initial value (a common browser default is 16px, but user-defined preferences may modify this).` This means that 1rem equals the font size of the html element (which for most browsers has a default value of 16px). Because the two aspect relation is ratio relation that identify the page layout keeps constant in different metrics devices. But because it's a ratio relation that leads to the actual rem not intuitional. So we can use a trick called '62.5%' such as: {% highlight typescript %} body { font-size:62.5%; } /* =10px */ h1 { font-size: 2.4em; } /* =24px */ p { font-size: 1.4em; } /* =14px */ li { font-size: 1.4em; } /* =14px */ {% endhighlight %} <B>The second: Remote Debugging:</B> Remote debug live content on an Android device from your Windows, Mac, or Linux computer. Android: https://developers.google.com/web/tools/chrome-devtools/remote-debugging/ iOS: It's akin to Android but you have to use Mac's safari to debug the browser or hybrid app embedded browser. So you should have a mac and install safari and Chrome/Canary to debug iOS and Android respectively. Tips: If your country block some google services you maybe open blank page when debugging. If so you have to use VPN service to connect the google server and debug the pages. <B>Performance:</B> The mobile performance is important and you need remember the problem. If page freezes you can use Performance panel of devtools in Chrome/Canary to detect the situation and which function callback. Or you can use Audits panel which integrated into Lighthouse tool to see what need optimize. Now you know the most important problems about mobile development. Moreover if you want to simulate App actions and UI effects you need use some UI library. Best luck to you! Thank you reading my blog.
TypeScript
UTF-8
1,537
2.703125
3
[]
no_license
import md5 from "md5"; import Admin, { IAdmin, IAdminCreation } from "../modules/Admin"; function filter(result: any) { let data: any = null; if (result) { const { id, loginId } = result; data = { id, loginId, }; } return data; } export default class AdminService { static async addAdmin(adminObj: IAdminCreation) { adminObj.loginPwd = md5(adminObj.loginPwd); const result = await Admin.create(adminObj); return filter(result.toJSON()); } static async deleteAdmin(id: string) { const result = await Admin.destroy({ where: { id, }, }); return result; } static async updateAdmin(id: number, adminObj: Partial<IAdmin>) { if (adminObj.loginPwd) { adminObj.loginPwd = md5(adminObj.loginPwd); } const result = await Admin.update(adminObj, { where: { id, }, }); return result; } static async getAdminById(id: number) { const result = await Admin.findByPk(id); if (result) { return filter(result.toJSON()); } return null; } static async getAdmins() { const result = await Admin.findAll(); return JSON.parse(JSON.stringify(result)); } static async login(loginId: string, loginPwd: string) { loginPwd = md5(loginPwd); const result = await Admin.findOne({ where: { loginId, loginPwd, }, }); console.log(result); if (result && result.loginId === loginId) { return filter(result.toJSON()); } return null; } }
Java
UTF-8
675
2
2
[]
no_license
package com.guru99.banking.webelements; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.Select; public class Ministatement { WebDriver driver; By ministatement=By.linkText("Mini Statement"); By accountno=By.name("accountno"); By submit=By.name("AccSubmit"); public Ministatement(WebDriver x) { this.driver=x; } public void selectstatement() { driver.findElement(ministatement).click(); } public void selectaccount() { Select s=new Select(driver.findElement(accountno)); s.selectByVisibleText("3308"); } public void submit() { driver.findElement(submit).click(); } }
Java
UTF-8
904
2.234375
2
[]
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 OmarEntite; /** * * @author user */ public class enfantETactivite { private int id_e; private int id_ac; private int id; public enfantETactivite() { } public enfantETactivite(int id_e, int id_ac) { this.id_e = id_e; this.id_ac = id_ac; } public int getId() { return id; } public int getId_ac() { return id_ac; } public int getId_e() { return id_e; } public void setId(int id) { this.id = id; } public void setId_ac(int id_ac) { this.id_ac = id_ac; } public void setId_e(int id_e) { this.id_e = id_e; } }
C
UTF-8
1,533
3.546875
4
[]
no_license
#include <stdio.h> #include <stdlib.h> typedef struct Node Node; struct Node{ long long key; int cnt; Node *leftChild, *rightChild; }; Node* createNode(long long key){ Node* ret = (Node*) malloc(sizeof(Node)); ret->key = key; ret->cnt = 1; ret->leftChild = ret->rightChild = NULL; return ret; } int maxAns = 0; Node* insertNode(Node* root, long long key){ if(!root) return createNode(key); // printf("\n------%lld------\n", root->key); if(key < root->key) root->leftChild = insertNode(root->leftChild, key); else if(key > root->key) root->rightChild = insertNode(root->rightChild, key); else if(key == root->key){ root->cnt++; if(root->cnt > maxAns) maxAns = root->cnt; } return root; } long long minTeleNum = -1; int nSame = 0; void inOrder(Node* root){ if(!root) return; inOrder(root->leftChild); if(root->cnt == maxAns){ if(root->cnt == maxAns) nSame++; if(minTeleNum == -1) minTeleNum = root->key; } inOrder(root->rightChild); } int main(){ Node* root = NULL; int nRecord; scanf("%d", &nRecord); while(nRecord--){ long long key; scanf("%lld", &key); root = insertNode(root, key); scanf("%lld", &key); root = insertNode(root, key); } // printf("%d", maxAns); inOrder(root); printf("%lld %d", minTeleNum, maxAns); if(nSame != 1) printf(" %d", nSame); return 0; }