blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ddbe4ffcea4cf6b4e6bae42db991abeb3b4207a6 | b68711e23199155cf55a4c169955e625a576e5b6 | /lanco_gui/app_module.cpp | 30b2e3d3ec439e12274075dd5cf807abae03adaf | [] | no_license | jian828/lanco_gui | 62cd17b372ef77feda0b0676fb7468feb95fae1b | e8357951d2c3670f984d7b3c391925c31613cbab | refs/heads/master | 2020-03-19T07:22:30.783167 | 2018-06-04T13:04:53 | 2018-06-04T13:04:53 | 136,108,324 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 22,436 | cpp | app_module.cpp |
#include "inc/app_def.h"
unsigned long next;
unsigned short myrand( void )
{
unsigned short tmp1;
unsigned short tmp2;
next = next * 1103515245 + 12345;
tmp1 = (unsigned short)(next/65536) % 32768;
tmp2 = (tmp1 / 10);
tmp2 = tmp2 * 10;
return( tmp1 - tmp2); // numbers 0 to 9
//return(unsigned short)(next/65536) % 32768;
}
unsigned char mu_enter_pin( char * sPin )
{
unsigned char nret=0;
unsigned long st_tick = app_get_tick_count();
char cmd_buf[128];
memset(cmd_buf,0,sizeof(cmd_buf));
appsys.flag_got_458=0;
send_android_command(andr_build_448_input_simpin(cmd_buf,sPin));
while(get_duration_tick(st_tick) < 1000)
{
if(appsys.flag_got_458 >0)
{
if(appsys.byte_pinret_state == '1')
{
if(1 == appsys.flag_genie_trace)DebugPrintf("mu_enter_pin, succeed \r\n");
nret =1;
}
else
{
if(1 == appsys.flag_genie_trace)DebugPrintf("mu_enter_pin, faled01 \r\n");
}
break;
}
delay_ms(100);
}
if(1 == appsys.flag_genie_trace)DebugPrintf("mu_enter_pin ,failed02! \r\n");
return nret;
}
unsigned char mu_is_pin_active( void )
{
unsigned long st_tick = app_get_tick_count();
char cmd_buf[128];
memset(cmd_buf,0,sizeof(cmd_buf));
appsys.flag_got_458=0;
send_android_command(andr_build_448_query_simpin_enabled(cmd_buf));
while(get_duration_tick(st_tick) < 1000)
{
if(appsys.flag_got_458 >0)
{
if(appsys.byte_pinret_state == '1')
{
if(1 == appsys.flag_genie_trace)DebugPrintf("mu_is_pin_active, enabled \r\n");
return 1;
}
else
{
if(1 == appsys.flag_genie_trace)DebugPrintf("mu_is_pin_active, disabled\r\n");
return 0;
}
break;
}
delay_ms(100);
}
if(1 == appsys.flag_genie_trace)DebugPrintf("mu_is_pin_active ,failed! \r\n");
return 0;
}
unsigned char mu_change_pin( char *sOld,char *sNew )
{
unsigned long st_tick = app_get_tick_count();
char cmd_buf[128];
memset(cmd_buf,0,sizeof(cmd_buf));
appsys.flag_got_458=0;
send_android_command(andr_build_448_change_pin(cmd_buf,sOld,sNew));
while(get_duration_tick(st_tick) < 1000)
{
if(appsys.flag_got_458 >0)
{
if(appsys.byte_pinret_state == '1')
{
if(1 == appsys.flag_genie_trace)DebugPrintf("mu_change_pin, succeed \r\n");
return 1;
}
else
{
if(1 == appsys.flag_genie_trace)DebugPrintf("mu_change_pin, failed01 \r\n");
}
break;
}
delay_ms(100);
}
if(1 == appsys.flag_genie_trace)DebugPrintf("mu_change_pin ,failed02 \r\n");
return 0;
}
unsigned char mu_user_enter_pin( char * pin_out )
{
unsigned char i=0;
char tmp_buf[10];
memset(tmp_buf,0,10);
for(i=0;i<3;i++)
{
if (1 == wnd_input_password(tmp_buf, get_multi_string((char * *)text_input_simpin), 8))
{
msg(get_multi_string((char * *) text_please_wait));
if(1 == mu_enter_pin(tmp_buf))
{
msgok(get_multi_string((char * *) text_pin_code_pass));
delay_ms(1500);
if(NULL !=pin_out )
{
strcpy(pin_out, tmp_buf);
}
return 1;
}
}
else
{
break;
}
}
return 0;
}
unsigned char mu_enter_puk( char *sPuk, char *sPin ) //输入PUK码,和新的pin?
{
unsigned char nret=0;
unsigned long st_tick = app_get_tick_count();
char cmd_buf[128];
memset(cmd_buf,0,sizeof(cmd_buf));
appsys.flag_got_458=0;
send_android_command(andr_build_448_input_simpuk(cmd_buf, sPuk, sPin));
while(get_duration_tick(st_tick) < 1000)
{
if(appsys.flag_got_458 >0)
{
if(appsys.byte_pinret_state == '1')
{
if(1 == appsys.flag_genie_trace)DebugPrintf("mu_enter_puk, succeed \r\n");
nret =1;
}
else
{
if(1 == appsys.flag_genie_trace)DebugPrintf("mu_enter_puk, faled01 \r\n");
}
break;
}
delay_ms(100);
}
if(1 == appsys.flag_genie_trace)DebugPrintf("mu_enter_puk ,failed02! \r\n");
return nret;
}
unsigned char mu_active_pin( char *sPin )
{
unsigned long st_tick = app_get_tick_count();
char cmd_buf[128];
memset(cmd_buf,0,sizeof(cmd_buf));
appsys.flag_got_458=0;
send_android_command(andr_build_448_setup_simpin_enabled(cmd_buf,sPin,1));
while(get_duration_tick(st_tick) < 1000)
{
if(appsys.flag_got_458 >0)
{
if(appsys.byte_pinret_state == '1')
{
if(1 == appsys.flag_genie_trace)DebugPrintf("mu_active_pin, enabled \r\n");
mu_is_pin_active();
return 1;
}
else
{
if(1 == appsys.flag_genie_trace)DebugPrintf("mu_active_pin, disabled\r\n");
}
break;
}
delay_ms(100);
}
if(1 == appsys.flag_genie_trace)DebugPrintf("mu_active_pin ,failed! \r\n");
return 0;
}
unsigned char mu_cancel_pin( char *sPin )
{
unsigned long st_tick = app_get_tick_count();
char cmd_buf[128];
memset(cmd_buf,0,sizeof(cmd_buf));
appsys.flag_got_458=0;
send_android_command(andr_build_448_setup_simpin_enabled(cmd_buf,sPin,0));
while(get_duration_tick(st_tick) < 1000)
{
if(appsys.flag_got_458 >0)
{
if(appsys.byte_pinret_state == '1')
{
if(1 == appsys.flag_genie_trace)DebugPrintf("mu_cancel_pin, enabled \r\n");
mu_is_pin_active();
return 1;
}
else
{
if(1 == appsys.flag_genie_trace)DebugPrintf("mu_cancel_pin, disabled\r\n");
}
break;
}
delay_ms(100);
}
if(1 == appsys.flag_genie_trace)DebugPrintf("mu_cancel_pin ,failed! \r\n");
return 0;
}
unsigned char mu_user_active_pin( char * spin ,int length)
{
memset(spin,0,length);
if (0== wnd_input_password(spin, get_multi_string((char * *) text_please_enter_pin), length))
{
return 0;
}
msg(get_multi_string((char * *) text_please_wait));
if(1 == mu_active_pin(spin))
{
msgok(get_multi_string((char * *)text_pin_protect_actived));
delay_ms(1500);
return 1;
}
else
{
msg_warn(get_multi_string((char * *)text_pin_code_error));
delay_ms(1500);
}
return 0;
}
unsigned char mu_user_cancel_pin( void )
{
char temp_pin[10];
memset(temp_pin,0,10);
if (0== wnd_input_password(temp_pin, get_multi_string((char * *)text_please_enter_pin), 8))
{
return 0;
}
msg(get_multi_string((char * *) text_please_wait));
if ( mu_cancel_pin(temp_pin) )
{
msgok(get_multi_string((char * *)text_pin_protect_has_been_canceled));
delay_ms(2000);
return 1;
}
else
{
msg_warn(get_multi_string((char * *)text_failed));
delay_ms(2000);
}
return 0;
}
unsigned char mu_user_enter_puk( void )
{
char spuk[10];
char spin[10];
char spin2[10];
memset(spuk,0,10);
memset(spin,0,10);
memset(spin2,0,10);
ENTER_PUK_AGAIN:
if (0 == wnd_input_password(spuk, get_multi_string((char * *)text_input_puk), 8))
{
return 0;
}
if (0 == wnd_input_password(spin, get_multi_string((char * *)text_enter_new_pin), 8))
{
return 0;
}
if (0 == wnd_input_password(spin2, get_multi_string((char * *)text_enter_new_again), 8))
{
return 0;
}
if ( strncmp(spin,spin2,8)!=0 )
{
msg_warn(get_multi_string((char * *)text_pin_disaccord_please_input_again));
delay_ms(2000);
goto ENTER_PUK_AGAIN;
}
msg(get_multi_string((char * *) text_please_wait));
if (1 == mu_enter_puk(spuk,spin) )
{
msg(get_multi_string((char * *)text_succeed_keep_your_pin));
delay_ms(2000);
return 1;
}
else
{
msg_warn(get_multi_string((char * *)text_unlock_puk_failed));
delay_ms(2000);
return 0;
}
}
unsigned char mu_check_lockcard( void )
{
if ( 1 == mu_user_enter_pin(NULL) )
{
return 1;
}
return 0;
}
unsigned char mu_get_cimi( char *str_cimi, unsigned char cimi_len ) //ESN?
{
return 0;
}
unsigned char mu_check_sim_valid(int wait_ms)
{
if(1 == appsys.flag_genie_trace) DebugPrintf("start check simcard\r\n");
msg(get_combined_string(get_multi_string((char * *)text_checking_simcard), "\n", get_multi_string((char * *)text_please_wait)));
if(1 == app_wait_simcard_ready(wait_ms))
{
switch(appsys.byte_simcard_state)
{
//0 提示SIM状态未知
case '0':
//1 提示没有SIM卡
case '1':
{
app_show_no_simcard();
appsys.flag_nouim_emergency_call=1;
}
break;
//2 提示开机需要用户输入PIN码
case '2':
if(mu_check_lockcard())
{
return 1;
}
break;
//3 提示开机需要用户输入PUK码
case '3':
{
msg_warn(get_multi_string((char * *)text_simcard_locked_puk_needed));
delay_ms(2000);
if(1 == mu_user_enter_puk())
{
return 1;
}
}
break;
//4 提示开机需要网络PIN码
case '4':
break;
//5 提示SIM卡就绪
case '5':
{
return 1;
}
break;
default:
break;
}
}
if(1 == appsys.flag_genie_trace) DebugPrintf("check simcard failed!!!!\r\n");
return 0;
}
unsigned char mu_get_csq( void )
{
char tmp_cmd[128];
memset(tmp_cmd,0,sizeof(tmp_cmd));
send_android_command(andr_build_44E_get_csq(tmp_cmd));
return 1;
}
int get_smsinfo_from_simcard()
{
unsigned long st_tick= app_get_tick_count();
char tmp_cmd[128];
memset(tmp_cmd,0,sizeof(tmp_cmd));
msg(get_multi_string((char * *)text_please_wait));
appsys.flag_got_455=0;
send_android_command(andr_build_445_read_simsms_count(tmp_cmd));
while(get_duration_tick(st_tick) <1000)
{
if(appsys.flag_got_455 >0)
{
return appsys.byte_simcard_sms_cnt;
}
else
{
delay_ms(100);
}
}
return 0;
}
int get_bookinfo_from_simcard()
{
unsigned long st_tick= app_get_tick_count();
char tmp_cmd[128];
memset(tmp_cmd,0,sizeof(tmp_cmd));
msg(get_multi_string((char * *)text_please_wait));
appsys.flag_got_454=0;
send_android_command(andr_build_444_read_simbook_count(tmp_cmd));
while(get_duration_tick(st_tick) <1000)
{
if(appsys.flag_got_454 >0)
{
return appsys.byte_simcard_book_cnt;
}
else
{
delay_ms(100);
}
}
return 0;
}
void wait_for_android_response(int wait_ms)
{
unsigned long st_tick= app_get_tick_count();
if(1 == appsys.flag_genie_trace) DebugPrintf("start wait 1st response.\r\n");
while(get_duration_tick(st_tick) <wait_ms)
{
if(appsys.flag_got_andr_message>0)
{
break;
}
else
{
delay_ms(100);
}
}
if(1 == appsys.flag_genie_trace) DebugPrintf("wait 1st response finished.\r\n");
}
unsigned char mu_registering()
{
lcd_goto_xy(0, 0);
show_bitmap(BMP_REGISTERING_BIN);
appsys.byte_sysrun_state=1;
app_query_hw_info(200);
appsys.flag_enable_handfree=1;
appsys.byte_sysrun_state=0xFF;
appsys.flag_sms_full =(app_get_record_used(TABLEINFO_SMS_INBOX) == g_table_info[TABLEINFO_SMS_INBOX].tb_info.rec_max_cnt)?1:0;
appsys.dword_last_input_tick = app_get_tick_count();
return 1;
}
unsigned char mu_reg_changed( void )
{
if(appsys.flag_got_422 >0)
{
appsys.flag_got_422=0;
return 1;
}
return 0;
}
void mu_set_spk_gain( unsigned char level )
{
if(level <MAX_VOLUM_LEVEL)
{
app_set_voice_volumn(VOCTYPE_TALKING, speech_volume [level]);
}
}
void mu_set_ring_gain( unsigned char level )
{
if(level <MAX_VOLUM_LEVEL)
{
app_set_voice_volumn(VOCTYPE_INCOMING_CALL, music_volume [level]);
}
}
void mu_set_date_time(DATE * p_date, TIME * p_time)
{
char tmp_buf[32];
memset(tmp_buf,0,sizeof(tmp_buf));
//date -s "yyyymmdd.hhmmss"
sprintf(tmp_buf,"date -s \"%.4d%.2d%.2d.%.2d%.2d%.2d\"", p_date->year,p_date->mon,p_date->day, p_time->hour,p_time->min,p_time->sec);
if(1 == appsys.flag_genie_trace)DebugPrintf("mu_set_date_time :%s",tmp_buf);
system(tmp_buf);
}
void mu_dial_dtmf( char dtmf )
{
char cmd_buf[128];
memset(cmd_buf,0,sizeof(cmd_buf));
send_android_command(andr_build_437_talking_ctrl(cmd_buf, "3", dtmf));
}
unsigned char mu_dial_dtmf_str( char * dtmf_str )
{
char str_dial[24];
char cmd_buf[128];
unsigned char flag_succeed =0;
unsigned long st_tick = app_get_tick_count();
memset(cmd_buf,0,sizeof(cmd_buf));
appsys.flag_handfree_pressed=0;
appsys.flag_sending_numbers=1;
memset(str_dial, 0, sizeof(str_dial));
strcpy(appsys.str_dialed_numbers, dtmf_str);
strcpy(str_dial, dtmf_str);
appsys.flag_got_423=0;
send_android_command(andr_build_431_callout(cmd_buf, str_dial));
while(get_duration_tick( st_tick) < 1500)
{
if(appsys.flag_got_423 >0)
{
if(appsys.byte_tlk_state == '3')
{
flag_succeed =1;
}
appsys.flag_got_423 =0;
if(1 == appsys.flag_genie_trace)DebugPrintf("mu_dial_dtmf_str , dialing out...\r\n");
}
else
{
delay_ms(100);
}
}
appsys.flag_sending_numbers=0;
if(HOOK_STATE_OFFHOOK == appsys.flag_hook_state )
{
appsys.flag_hand_free=0;
set_handfree_led(0);
}
else
{
if( 0 == appsys.flag_hand_free || 1== appsys.flag_handfree_pressed)
{
flag_succeed=0;
set_handfree_led(0);
}
}
appsys.flag_handfree_pressed=0;
return flag_succeed;
}
void mu_hook_on( void )
{
char cmd_buf[128];
memset(cmd_buf,0,sizeof(cmd_buf));
send_android_command(andr_build_432_hook_onoff(cmd_buf, 0));
}
void mu_answer_call( void )
{
char cmd_buf[128];
memset(cmd_buf,0,sizeof(cmd_buf));
send_android_command(andr_build_432_hook_onoff(cmd_buf, 1));
}
unsigned char mu_set_voice_path( unsigned char voc_path )
{ //SPEAKER AND MIC PATH 1=handset, 0= handfree
char tmp_cmd[128];
memset(tmp_cmd,0,sizeof(tmp_cmd));
if(1 ==appsys.flag_genie_trace)DebugPrintf("set voice path to %s\r\n" , (VOICE_PATH_HANDSET== voc_path)? "handset" : "handfree");
appsys.byte_delay_cnt_handfree=0;
app_disable_speaker();
if (VOICE_PATH_HANDSET== voc_path )
{
send_android_command(andr_build_438_voc_path(tmp_cmd, '1'));
}
else
{
send_android_command(andr_build_438_voc_path(tmp_cmd, '2'));
}
if(VOICE_PATH_HANDFREE== voc_path )
{
app_enable_speaker(); //防止挂机的时候拨号音从喇叭放出;
}
appsys.flag_voice_path =voc_path;
return 1;
}
void mu_generate_beep( void )
{
char tmp_cmd[128];
memset(tmp_cmd,0,sizeof(tmp_cmd));
app_enable_speaker();
if(1 ==appsys.flag_genie_trace)DebugPrintf("))))) play beep ))))\r\n");
send_android_command( andr_build_43C_play(tmp_cmd, 'K'));
}
void mu_generate_dtmf( char dtmf )
{
char tmp_cmd[128];
memset(tmp_cmd,0,sizeof(tmp_cmd));
app_enable_speaker();
if(1 ==appsys.flag_genie_trace)DebugPrintf("~~~~~ play dtmf =%c ~~~~~\r\n",dtmf);
send_android_command( andr_build_43C_play(tmp_cmd, dtmf));
}
void mu_play_dialtone( void )
{
appsys.flag_playing_tone=1;
appsys.dword_dialtone_st=app_get_tick_count();
app_play_dial_tone(DIAL_TONE_ASIA, 45);
if(0== appsys.flag_hand_free && HOOK_STATE_OFFHOOK == appsys.flag_hook_state)
{
app_disable_speaker();
}
}
void mu_stop_dialtone( void )
{
appsys.flag_playing_tone=0;
app_stop_music();
}
unsigned char mu_list_calls( T_CALL_STATE *call_state )
{
return 0;
}
void mu_shift_waiting_call( void )
{
}
void mu_terminate_call( unsigned char id )
{
}
void mu_active_holded_call( unsigned char id )
{
}
unsigned char mu_mute_mic( )
{
char cmd_buf[128];
memset(cmd_buf,0,sizeof(cmd_buf));
send_android_command(andr_build_437_talking_ctrl(cmd_buf, "1", '1'));
appsys.flag_muted=1;
return 1;
}
unsigned char mu_cancel_mute_mic( )
{
char cmd_buf[128];
memset(cmd_buf,0,sizeof(cmd_buf));
send_android_command(andr_build_437_talking_ctrl(cmd_buf, "1", '0'));
appsys.flag_muted=0;
return 1;
}
void mu_delete_message( unsigned char sm_index )
{
}
unsigned char mu_send_sms( char * numbers,char * context )
{
char tmp_cmd[512];
unsigned long st_tick =app_get_tick_count();
memset(tmp_cmd,0,sizeof(tmp_cmd));
appsys.flag_got_426=0;
send_android_command(andr_build_434_sendsms(tmp_cmd, numbers, context));
while( get_duration_tick(st_tick) <5000)
{
if(appsys.flag_got_426 >0)
{
return appsys.byte_smsret_state=='1'?1:0;
}
else
{
delay_ms(200);
}
}
return 0;
}
unsigned char mu_query_callwait_status( void )
{
char tmp_cmd[128];
unsigned long st_tick= app_get_tick_count();
memset(tmp_cmd,0,sizeof(tmp_cmd));
msg(get_multi_string((char * *)text_please_wait));
appsys.flag_got_456=0;
send_android_command(andr_build_446_query_call_waiting(tmp_cmd));
while(get_duration_tick(st_tick) < 10000)
{
if( appsys.flag_got_456 >0)
{
return appsys.byte_callwaitret_state=='1'?1:0;
}
else
{
delay_ms(300);
}
}
return 0;
}
unsigned char mu_set_callwait( unsigned char on_off )
{
char tmp_cmd[128];
unsigned long st_tick= app_get_tick_count();
memset(tmp_cmd,0,sizeof(tmp_cmd));
msg(get_multi_string((char * *)text_please_wait));
appsys.flag_got_456=0;
send_android_command(andr_build_446_setup_call_waiting(tmp_cmd,on_off));
while(get_duration_tick(st_tick) < 10000)
{
if( appsys.flag_got_456 >0)
{
return appsys.byte_callwaitret_state=='1'?1:0;
}
else
{
delay_ms(300);
}
}
return 0;
}
unsigned char check_ccfc_state(unsigned char * pcmd, T_CALL_DIVERT_STATUS * divert_status)
{
return 0;
}
unsigned char mu_query_calldivert_status( )
{
char tmp_cmd[128];
unsigned long st_tick= app_get_tick_count();
memset(tmp_cmd,0,sizeof(tmp_cmd));
msg(get_multi_string((char * *)text_please_wait));
appsys.flag_got_457=0;
memset(appsys.DIVT_LIST,0,sizeof(appsys.DIVT_LIST));
send_android_command(andr_build_447_query_call_divert(tmp_cmd));
while(get_duration_tick(st_tick) < 10000)
{
if( appsys.flag_got_457 >0)
{
return 1;
}
else
{
delay_ms(300);
}
}
return 0;
}
unsigned char mu_active_calldivert( unsigned char divert_mode,char *num )
{
char tmp_cmd[128];
unsigned long st_tick= app_get_tick_count();
memset(tmp_cmd,0,sizeof(tmp_cmd));
msg(get_multi_string((char * *)text_please_wait));
appsys.flag_got_457=0;
send_android_command(andr_build_447_setup_call_divert(tmp_cmd, divert_mode+0x30, 1, num));
while(get_duration_tick(st_tick) < 10000)
{
if( appsys.flag_got_457 >0)
{
return appsys.byte_divtret_state=='1'?1:0;
}
else
{
delay_ms(300);
}
}
return 0;
}
unsigned char mu_dactive_calldivert( unsigned char divert_mode )
{
char tmp_cmd[128];
unsigned long st_tick= app_get_tick_count();
memset(tmp_cmd,0,sizeof(tmp_cmd));
msg(get_multi_string((char * *)text_please_wait));
appsys.flag_got_457=0;
send_android_command(andr_build_447_setup_call_divert(tmp_cmd, divert_mode+0x30, 0, "0"));
while(get_duration_tick(st_tick) < 10000)
{
if( appsys.flag_got_457 >0)
{
return appsys.byte_divtret_state=='1'?1:0;
}
else
{
delay_ms(300);
}
}
return 0;
}
unsigned char mu_list_operator( T_NETWORKS *networks )
{
return 0;
}
unsigned char mu_select_operator( unsigned char mode,char * name )
{
return 0;
}
unsigned char mu_get_cgsn( char * str_cgsn,unsigned char datelen )
{
return 0;
}
unsigned short get_ucs2_value(char * pdata)
{
unsigned short ret_val=0;
ret_val += hex_to_byte(pdata[0]);
ret_val <<=4;
ret_val += hex_to_byte(pdata[1]);
ret_val <<=4;
ret_val += hex_to_byte(pdata[2]);
ret_val <<=4;
ret_val += hex_to_byte(pdata[3]);
return ret_val;
}
void ucs2_to_ascii_my(char * pdata ,unsigned short data_len ,char * pout, unsigned char out_len )
{
unsigned short i=0;
for(i=0;i<data_len;i+=4)
{
if(i/4 < out_len)
{
pout[i/4]= get_ucs2_value(&pdata[i]);
}
else
{
break;
}
}
}
unsigned short find_char_pos(char *src, const char c, unsigned short tms)
{
unsigned short i,cnt;
unsigned short len = strlen(src);
i=cnt=0;
if(len >0)
{
if(tms !=0xFFFF)
{
while ( src[i] )
{
if ( c ==src[i] )
{
if(++cnt == tms)
{
return i;
}
}
i++;
}
}
else
{
i=len;
while(i >0)
{
i--;
if(src[i] == c)
{
return i;
}
}
}
}
return 0xffff;
}
unsigned char mu_getsimcard_sms(unsigned char sms_idx, T_SMS_RECORD * psms_record)
{
unsigned long st_tick= app_get_tick_count();
char tmp_cmd[128];
char str_idx[6];
memset(tmp_cmd,0,sizeof(tmp_cmd));
memset(str_idx,0,sizeof(str_idx));
sprintf(str_idx,"%d", sms_idx);
appsys.flag_got_455=0;
send_android_command(andr_build_445_read_simbook_user(tmp_cmd, str_idx));
while(get_duration_tick(st_tick) <1000)
{
if(appsys.flag_got_455 >0)
{
memcpy(psms_record,&appsys.tp_sms, sizeof(T_SMS_RECORD));
return 1;
}
else
{
delay_ms(100);
}
}
return 0;
}
unsigned char mu_getsimcard_book(unsigned char book_idx, T_BOOK_ENTRY* pbook_entry)
{
unsigned long st_tick= app_get_tick_count();
char tmp_cmd[128];
char str_idx[6];
memset(tmp_cmd,0,sizeof(tmp_cmd));
memset(str_idx,0,sizeof(str_idx));
sprintf(str_idx,"%d", book_idx);
appsys.flag_got_454=0;
send_android_command(andr_build_444_read_simbook_user(tmp_cmd, str_idx));
while(get_duration_tick(st_tick) <1000)
{
if(appsys.flag_got_454 >0)
{
memcpy(pbook_entry,&appsys.tp_book, sizeof(T_BOOK_ENTRY));
return 1;
}
else
{
delay_ms(100);
}
}
return 0;
}
|
9851e77bdc392182e1a7401a384892bb8509b1ac | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/bc/23e9c7c609d898/main.cpp | df92acd4c88afaffe606ae7f149263e7d214d932 | [] | no_license | WhiZTiM/coliru | 3a6c4c0bdac566d1aa1c21818118ba70479b0f40 | 2c72c048846c082f943e6c7f9fa8d94aee76979f | refs/heads/master | 2021-01-01T05:10:33.812560 | 2015-08-24T19:09:22 | 2015-08-24T19:09:22 | 56,789,706 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 856 | cpp | main.cpp | #include <vector>
#include <stdexcept>
#include <iostream>
#include <assert.h>
template<typename T>
struct Allocator : std::allocator<T>
{
using std::allocator<T>::allocator;
};
namespace std
{
template<typename T>
class vector<T, std::allocator<T>> : public vector<T, Allocator<T>>
{
public:
using vector<T, Allocator<T>>::vector;
void push_back(T&& n)
{
if (this->size() == this->capacity())
{
throw std::logic_error("Realloc triggered! Your code is slow!");
}
vector<T, Allocator<T>>::push_back(std::move(n));
}
};
}
int main()
{
std::vector<int> vec;
vec.reserve(5);
for (int i = 0; i != 10; ++i)
{
std::cout << vec.size() << "/" << vec.capacity() << std::endl;
vec.push_back(1);
}
}
|
b8e24dba4cfef2c78106582f747cb5ac72eedb58 | e937fe5a30ec0f7d7f468dde952d263b096fbc78 | /Remote_Backup_Client/FileToUpload.h | 979d7e9a07970d72a75e097bf2009264dd73f6ec | [] | no_license | palumbamboo/pds2020_remote_backup_service | 616c816c579bb168a99e7ba07ffebc3ff9b08208 | 17832789be8a39d56c142e42de0e3a6437eb2987 | refs/heads/master | 2022-12-26T03:24:42.473106 | 2020-10-01T13:46:48 | 2020-10-01T13:46:48 | 286,785,682 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,345 | h | FileToUpload.h | //
// Created by daniele on 19/09/20.
//
#ifndef REMOTE_BACKUP_CLIENT_FILETOUPLOAD_H
#define REMOTE_BACKUP_CLIENT_FILETOUPLOAD_H
#include <filesystem>
#include <fstream>
#include <boost/uuid/detail/md5.hpp>
#include <boost/algorithm/hex.hpp>
#include <utility>
#include <iostream>
class FileToUpload {
private:
std::string folderToWatch;
std::filesystem::path path;
size_t fileSize;
std::string hash;
public:
FileToUpload() : fileSize(0) {}
FileToUpload(std::string _folderToWatch, std::filesystem::path _path) :
folderToWatch(std::move(_folderToWatch)),
path(std::move(_path)),
fileSize(0) {}
FileToUpload(std::string _folderToWatch, std::filesystem::path _path, size_t _filesize) :
folderToWatch(std::move(_folderToWatch)),
path(std::move(_path)),
fileSize(_filesize) {}
~FileToUpload()=default;
std::filesystem::path getPath() { return path; }
std::filesystem::path getPathToUpload();
std::string getPathName() { return path.filename().string(); }
std::string fileHash();
size_t getFileSize() const { return fileSize; }
std::string getFileStoredHash() { return hash; }
void setPath(const std::filesystem::path &path);
void setFileSize(size_t fileSize);
};
#endif //REMOTE_BACKUP_CLIENT_FILETOUPLOAD_H
|
71e1e03fa74888bba717d1748c67c388b3692fac | de0db32066d76b9c326b6187d33bd17f12249322 | /kimi_no_monogatari/client/GameHall/src/GameHallWindow.cpp | 07770d581e842ad14e1ef203f396f21a2c2956d5 | [] | no_license | feraligatr/wolf2d | f04fb3a7e0efc01c06a2f1ed8782a9db7d39880c | b8c6d6533615255e1546f8d91248d998653797c9 | refs/heads/master | 2021-01-19T11:16:24.288765 | 2011-11-26T06:22:11 | 2011-11-26T06:22:11 | 2,313,794 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 601 | cpp | GameHallWindow.cpp | #include "pch.h"
#include <QtGui>
#include "GameHallWindow.h"
#include "GameHallApplication.h"
GameHallWindow::GameHallWindow()
{
m_centralWidget = new QWidget(this);
setCentralWidget(m_centralWidget);
resize(1024, 768);
}
void GameHallWindow::setDisplayWindow(QWidget* window)
{
if (!window)
{
return;
}
int x = (width() - window->frameGeometry().width()) / 2;
int y = (height() - window->frameGeometry().height()) / 2;
window->setParent(m_centralWidget);
window->move(x, y);
window->show();
}
void GameHallWindow::resizeEvent(QResizeEvent * event)
{
g_app->onResizeEvent(event);
}
|
ff2ca84e065f79895e72704d0cd94eca1061e7f0 | 9cb42d00153b1154a6efd915ab3fb731167c5894 | /wndzone.cpp | 4d4badf1b224ebac111eec576511d1f9240c4a6e | [] | no_license | corra72/mudeditor | 45f9bfeb8b80e20cc00e5f1d694973d0cc27a701 | 7cca359cc1b8c32ad678d0dd5717e629011919fc | refs/heads/master | 2020-05-20T04:07:28.076528 | 2019-06-17T10:18:04 | 2019-06-17T10:18:04 | 185,375,884 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,163 | cpp | wndzone.cpp | #include "wndzone.h"
#include <QTreeWidget>
#include <QLineEdit>
#include <QGroupBox>
#include <QCheckBox>
#include <QPushButton>
#include <QMessageBox>
#include <QMenu>
#include <QLabel>
#include <QCloseEvent>
#include <QCursor>
#include <QHeaderView>
#include <QApplication>
#include <QRegExp>
#include "wndzonecommand.h"
#include "validator.h"
#include "config.h"
#include "constantname.h"
#include "selectobject.h"
#include "guiutils.h"
#include "kreatorsettings.h"
using namespace ts;
WndZone::WndZone(Area& ref_area, const Zone& ref_zone, QWidget* parent)
: QDialog(parent), Ui::GuiZone(),
m_area(ref_area),
m_zone(ref_zone),
m_zoneCommands(m_zone.commandList()),
m_lastLineSelected(0),
m_commandGroupCopied()
{
#if defined( KREATOR_DEBUG )
qDebug("WndZone::WndZone( const Area&, const Zone&, QWidget* ) called.");
#endif
init();
loadData();
mp_leName->setFocus();
setModal(true);
}
WndZone::~WndZone()
{
#if defined( KREATOR_DEBUG )
qDebug("WndZone::~WndZone() called.");
#endif
}
void WndZone::init()
{
#if defined( KREATOR_DEBUG )
qDebug("WndZone::init() called.");
#endif
setupUi(this);
KreatorSettings::instance().loadGuiStatus("ZoneWindow", this);
mp_tbFlags->setIcon(TS::GetEditIcon());
mp_leVNumber->setValidator(Validator::vnumber());
mp_twZoneCommands->header()->hide();
mp_comboRepopMode->clear();
for (int i = 0; i < ZONE_REPOP_MODE_END; i++)
mp_comboRepopMode->insertItem(i, ConstantName::zoneRepopMode(i).toLower());
mp_bgFilters = new MyQt::ButtonGroup(this);
mp_bgFilters->addButton(mp_cbGroup, 0);
mp_bgFilters->addButton(mp_cbMobs, 1);
mp_bgFilters->addButton(mp_cbItems, 2);
mp_bgFilters->addButton(mp_cbDoors, 3);
mp_bgFilters->addButton(mp_cbComments, 4);
mp_bgFilters->addButton(mp_cbSpaces, 5);
mp_bgFilters->addButton(mp_cbExpand, 6);
KreatorSettings::instance().loadButtonGroupStatus("ZoneCommandFilters", mp_bgFilters);
connect(mp_pbSave, SIGNAL(clicked()), this, SLOT(saveData()));
connect(mp_pbRestore, SIGNAL(clicked()), this, SLOT(restoreData()));
connect(mp_pbOk, SIGNAL(clicked()), this, SLOT(saveAndClose()));
connect(mp_pbCancel, SIGNAL(clicked()), this, SLOT(close()));
connect(mp_leVNumber, SIGNAL(textChanged(const QString&)), this, SLOT(somethingChanged()));
connect(mp_leMaxVNumber, SIGNAL(textChanged(const QString&)), this, SLOT(somethingChanged()));
connect(mp_leRepopInterval, SIGNAL(textChanged(const QString&)), this, SLOT(somethingChanged()));
connect(mp_leName, SIGNAL(textChanged(const QString&)), this, SLOT(somethingChanged()));
connect(mp_comboRepopMode, SIGNAL(activated(int)), this, SLOT(somethingChanged()));
connect(mp_lePwpLevel, SIGNAL(textChanged(const QString&)), this, SLOT(somethingChanged()));
connect(mp_bgFilters, SIGNAL(buttonClicked(int)), this, SLOT(refreshView()));
connect(mp_tbFlags, SIGNAL(clicked()), this, SLOT(editFlags()));
connect(mp_leFilter, SIGNAL(textEdited(const QString&)), this, SLOT(refreshView()));
connect(mp_leFilter, SIGNAL(returnPressed()), this, SLOT(refreshView()));
mp_leMaxVNumber->setValidator(Validator::vnumber());
mp_leRepopInterval->setValidator(Validator::integer());
mp_lePwpLevel->setValidator(Validator::integer());
mp_popupMenu = new QMenu(this);
mp_popupMenu->addAction(QIcon(":/images/edit.png"), trUtf8("Modifica..."), this, SLOT(editCommandLine()));
mp_popupMenu->addSeparator();
mp_actUpdateMaxInits = mp_popupMenu->addAction(QIcon(":/images/max.png"), trUtf8("Aggiorna maxaggi"), this, SLOT(updateMaxInits()));
mp_actUpdateMaxInits->setEnabled(false);
mp_popupMenu->addSeparator();
mp_popupMenu->addAction(QIcon(":/images/add.png"), trUtf8("Inserisci una linea vuota"), this, SLOT(addNewEmptyLine()));
mp_popupMenu->addAction(QIcon(":/images/cut.png"), trUtf8("Taglia"), this, SLOT(cutCommandLine()));
mp_popupMenu->addAction(QIcon(":/images/copy.png"), trUtf8("Copia"), this, SLOT(copyCommandLine()));
mp_actPaste = mp_popupMenu->addAction(QIcon(":/images/paste.png"), trUtf8("Incolla"), this, SLOT(pasteCommandLine()));
mp_actPaste->setEnabled(false);
mp_popupMenu->addSeparator();
mp_popupMenu->addAction(QIcon(":/images/remove.png"), trUtf8("Elimina"), this, SLOT(removeCommandLine()));
mp_twZoneCommands->setMenu(mp_popupMenu);
connect(mp_twZoneCommands, SIGNAL(itemSelectionChanged()), this, SLOT(lineSelected()));
connect(mp_twZoneCommands, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)),
this, SLOT(editCommandLine()));
}
void WndZone::refreshPanel()
{
#if defined( KREATOR_DEBUG )
qDebug("WndZone::refreshPanel() called.");
#endif
mp_leVNumber->setText(QString::number(m_zone.vnumber()));
mp_leName->setText(m_zone.name());
mp_leMinVNumber->setText(QString::number(m_zone.minVNumber()));
mp_leMaxVNumber->setText(QString::number(m_zone.maxVNumber()));
mp_comboRepopMode->setCurrentIndex(m_zone.repopMode());
mp_leRepopInterval->setText(QString::number(m_zone.repopInterval()));
mp_lePwpLevel->setText(QString::number(m_zone.pwpLevel()));
}
void WndZone::refreshView()
{
#if defined( KREATOR_DEBUG )
qDebug("WndZone::refreshView() called.");
#endif
QApplication::setOverrideCursor(Qt::WaitCursor);
qApp->processEvents();
mp_twZoneCommands->clear();
mp_twZoneCommands->setAlternatingRowColors(mp_cbGroup->isChecked());
ZoneCommandList::const_iterator it = m_zoneCommands.begin();
QTreeWidgetItem* last_item = 0;
QTreeWidgetItem* item = 0;
QTreeWidgetItem* selected_item = 0;
QTreeWidgetItem* selected_parent_item = 0;
bool has_regexp_filter = !mp_leFilter->text().trimmed().isEmpty();
QRegExp reg_exp(mp_leFilter->text().toLower().trimmed());
QString sTxt = "";
bool regexp_filter_accepted = true;
while (it != m_zoneCommands.end()) {
sTxt = (*it).toString(true);
regexp_filter_accepted = (!has_regexp_filter || sTxt.toLower().contains(reg_exp) || sTxt.toLower().isEmpty());
if (regexp_filter_accepted) {
if ((mp_cbMobs->isChecked() && (*it).isMobCommand())
|| (mp_cbItems->isChecked() && (*it).isItemCommand())
|| (mp_cbDoors->isChecked() && (*it).isDoorInit())) {
if (mp_cbGroup->isChecked()) {
if ((*it).hasParent()) {
if (last_item)
item = new QTreeWidgetItem(last_item);
else
item = new QTreeWidgetItem(mp_twZoneCommands);
} else {
item = new QTreeWidgetItem(mp_twZoneCommands);
if (last_item && mp_cbExpand->isChecked())
mp_twZoneCommands->expandItem(last_item);
last_item = item;
}
} else
item = new QTreeWidgetItem(mp_twZoneCommands);
} else if ((*it).isOnlyComment() && (*it).comment().isEmpty() && mp_cbSpaces->isChecked())
item = new QTreeWidgetItem(mp_twZoneCommands);
else if ((*it).isOnlyComment() && !(*it).comment().isEmpty() && mp_cbComments->isChecked())
item = new QTreeWidgetItem(mp_twZoneCommands);
}
if (item) {
item->setText(0, Utils::vnumber2string((*it).id(), 6));
item->setText(1, sTxt);
if ((*it).id() == m_lastLineSelected) {
selected_item = item;
if ((*it).hasParent() && mp_cbGroup->isChecked())
selected_parent_item = last_item;
}
item = 0;
}
++it;
}
if (selected_item) {
if (selected_parent_item)
mp_twZoneCommands->expandItem(selected_parent_item);
mp_twZoneCommands->clearSelection();
mp_twZoneCommands->setItemSelected(selected_item, true);
mp_twZoneCommands->scrollToItem(selected_item);
}
QApplication::restoreOverrideCursor();
qApp->processEvents();
}
void WndZone::refreshTitle()
{
#if defined( KREATOR_DEBUG )
qDebug("WndZone::refreshTitle() called.");
#endif
QString sTitle = "";
sTitle.sprintf("Zona #%ld - %s", m_zone.vnumber(), m_zone.name().toUtf8().data());
if (mp_pbSave->isEnabled())
sTitle.append(QString(" [modificata]"));
setWindowTitle(sTitle);
}
void WndZone::somethingChanged()
{
#if defined( KREATOR_DEBUG )
qDebug("WndZone::somethingChanged() called.");
#endif
mp_pbSave->setEnabled(true);
refreshTitle();
}
void WndZone::restoreData()
{
#if defined( KREATOR_DEBUG )
qDebug("WndZone::restoreData() called.");
#endif
if (m_area.hasZone(m_zone.vnumber())) {
m_zone = m_area.zone(m_zone.vnumber());
m_zoneCommands = m_zone.commandList();
loadData();
} else
QMessageBox::warning(this, TS::MESSAGE_BOX_WARNING,
TS::MESSAGE_WARNING_NO_VNUMBER.arg(m_zone.vnumber()));
}
void WndZone::loadData()
{
#if defined( KREATOR_DEBUG )
qDebug("WndZone::loadData() called.");
#endif
refreshPanel();
refreshView();
refreshFlags();
mp_pbSave->setEnabled(false);
refreshTitle();
mp_leName->setFocus();
}
void WndZone::saveData()
{
#if defined( KREATOR_DEBUG )
qDebug("WndZone::saveData() called.");
#endif
VNumber old_vnum = m_zone.vnumber();
VNumber new_vnum = mp_leVNumber->text().toLong();
if (old_vnum != new_vnum) {
if (m_area.hasZone(new_vnum)
&& QMessageBox::question(this, TS::MESSAGE_BOX_QUESTION,
TS::MESSAGE_ASK_OVERWRITE_VNUMBER.arg(new_vnum),
trUtf8("Si"), trUtf8("No"), QString(), 1, 1)
)
return;
if (!QMessageBox::question(this, TS::MESSAGE_BOX_QUESTION,
TS::MESSAGE_ASK_UPDATE_REFERENCES.arg(old_vnum).arg(new_vnum),
trUtf8("Si"), trUtf8("No"), QString(), 0, 1)
)
m_area.changeZoneVNumber(old_vnum, new_vnum);
}
m_zone.setVNumber(new_vnum);
m_zone.setName(mp_leName->text());
m_zone.setMaxVNumber(mp_leMaxVNumber->text().toLong());
m_zone.setRepopMode(mp_comboRepopMode->currentIndex());
m_zone.setRepopInterval(mp_leRepopInterval->text().toLong());
bool ok;
m_zone.setPwpLevel(mp_lePwpLevel->text().toInt(&ok, 10));
m_zone.setCommandList(m_zoneCommands);
m_area.addZone(m_zone);
m_area.setZonesChanged();
m_area.sortZones();
refreshPanel();
mp_pbSave->setEnabled(false);
refreshTitle();
emit(dataSaved());
}
void WndZone::saveAndClose()
{
#if defined( KREATOR_DEBUG )
qDebug("WndZone::saveAndClose() called.");
#endif
if (mp_pbSave->isEnabled())
saveData();
close();
}
void WndZone::closeEvent(QCloseEvent* e)
{
#if defined( KREATOR_DEBUG )
qDebug("WndZone::closeEvent( QCloseEvent* ) called.");
#endif
if (mp_pbSave->isEnabled()) {
if (KreatorSettings::instance().applyWithoutAsking()) {
saveData();
e->accept();
} else {
switch (QMessageBox::question(this, TS::MESSAGE_BOX_QUESTION, TS::MESSAGE_ASK_SAVE,
trUtf8("Si"), trUtf8("No"), trUtf8("Annulla"), 1, 2)) {
case 0:
saveData();
e->accept();
break;
case 1:
e->accept();
break;
default:
e->ignore();
break;
}
}
} else
e->accept();
if (e->isAccepted()) {
KreatorSettings::instance().saveGuiStatus("ZoneWindow", this);
KreatorSettings::instance().saveButtonGroupStatus("ZoneCommandFilters", mp_bgFilters);
}
}
QTreeWidgetItem* WndZone::selectedItem()
{
#if defined( KREATOR_DEBUG )
qDebug("WndZone::selectedItem() called.");
#endif
QList<QTreeWidgetItem*> wiList = mp_twZoneCommands->selectedItems();
return wiList.empty() ? 0 : wiList.first();
}
void WndZone::addNewEmptyLine()
{
#if defined( KREATOR_DEBUG )
qDebug("WndZone::addNewCommandLine() called.");
#endif
QTreeWidgetItem* item = selectedItem();
if (!item) {
QMessageBox::warning(this, TS::MESSAGE_BOX_WARNING,
trUtf8("E' necessario selezionare una linea.\nIl nuovo comando sara' inserito prima della linea selezionata."));
return;
}
int iLine = Utils::string2vnumber(item->text(0));
m_zoneCommands.addCommand(iLine);
refreshView();
somethingChanged();
}
void WndZone::removeCommandLine()
{
#if defined( KREATOR_DEBUG )
qDebug("WndZone::removeCommandLine() called.");
#endif
QTreeWidgetItem* item = selectedItem();
if (!item) {
QMessageBox::warning(this, TS::MESSAGE_BOX_WARNING,
trUtf8("E' necessario selezionare la linea che si vuole eliminare."));
return;
}
int iLine = Utils::string2vnumber(item->text(0));
m_zoneCommands.removeCommand(iLine);
refreshView();
somethingChanged();
}
void WndZone::editCommandLine()
{
#if defined( KREATOR_DEBUG )
qDebug("WndZone::editCommandLine() called.");
#endif
QTreeWidgetItem* item = selectedItem();
if (!item) {
QMessageBox::warning(this, TS::MESSAGE_BOX_WARNING,
trUtf8("E' necessario selezionare prima una linea per modificare."));
return;
}
int iLine = Utils::string2vnumber(item->text(0));
if (!m_zoneCommands.hasCommand(iLine)) {
QMessageBox::warning(this, TS::MESSAGE_BOX_WARNING,
trUtf8("Alla linea selezionata non e' piu' associato un comando di zona."));
return;
}
WndZoneCommand *pWndZoneCommand = new WndZoneCommand(m_area, m_zoneCommands, m_zoneCommands.command(iLine), this);
connect(pWndZoneCommand, SIGNAL(dataSaved()), this, SLOT(somethingChanged()));
pWndZoneCommand->show();
pWndZoneCommand->setFixedSize(pWndZoneCommand->size());
pWndZoneCommand->exec();
disconnect(pWndZoneCommand, SIGNAL(dataSaved()), this, SLOT(somethingChanged()));
delete pWndZoneCommand;
item->setText(1, m_zoneCommands.command(iLine).toString(true));
}
void WndZone::lineSelected()
{
#if defined( KREATOR_DEBUG )
qDebug("WndZone::lineSelected( QListViewItem* ) called.");
#endif
QTreeWidgetItem* item = selectedItem();
if (!item)
return;
m_lastLineSelected = Utils::string2vnumber(item->text(0));
if (!m_zoneCommands.hasCommand(m_lastLineSelected)) {
qWarning("Alla linea selezionata non e' piu' associato un comando di zona.");
return;
}
ZoneCommand zc = m_zoneCommands.command(m_lastLineSelected);
mp_actUpdateMaxInits->setEnabled(zc.hasMaxField());
}
void WndZone::editFlags()
{
#if defined( KREATOR_DEBUG )
qDebug("WndZone::editFlags( int ) called.");
#endif
BitVector vFlags = m_zone.newFlags();
BitVector vRetFlags = SelectObject::zoneFlags(vFlags, this);
if (vRetFlags == vFlags)
return;
m_zone.setNewFlags(vRetFlags);
refreshFlags();
somethingChanged();
}
void WndZone::refreshFlags()
{
#if defined( KREATOR_DEBUG )
qDebug("WndZone::refreshFlags() called.");
#endif
mp_leFlags->setText(Utils::bitvector2string(m_zone.newFlags(), Eleuconf::getAllFlagsCaption(Eleuconf::zoneFlags)).toLower());
}
void WndZone::keyPressEvent(QKeyEvent* e)
{
#if defined( KREATOR_DEBUG )
qDebug("WndZone::keyPressEvent( QKeyEvent* ) called.");
#endif
if (mp_leFilter->hasFocus() && (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return))
e->ignore();
else
QDialog::keyPressEvent(e);
}
void WndZone::copyCommandLine()
{
#if defined( KREATOR_DEBUG )
qDebug("WndZone::copyCommandLine() called.");
#endif
QTreeWidgetItem* item = selectedItem();
if (!item)
return;
int iLine = Utils::string2vnumber(item->text(0));
if (!m_zoneCommands.hasCommand(iLine)) {
QMessageBox::warning(this, TS::MESSAGE_BOX_WARNING,
trUtf8("Alla linea selezionata non e' piu' associato un comando di zona."));
return;
}
ZoneCommandGroup zcg;
zcg.setParent(m_zoneCommands.command(iLine));
for (int i = 0; i < item->childCount(); i++) {
int son_line = Utils::string2vnumber(item->child(i)->text(0));
if (m_zoneCommands.hasCommand(son_line))
zcg.addSon(m_zoneCommands.command(son_line));
}
m_commandGroupCopied = zcg;
mp_actPaste->setEnabled(true);
}
void WndZone::pasteCommandLine()
{
#if defined( KREATOR_DEBUG )
qDebug("WndZone::pasteCommandLine() called.");
#endif
if (m_commandGroupCopied.isNull())
return;
QTreeWidgetItem* item = selectedItem();
if (!item)
return;
int iLine = Utils::string2vnumber(item->text(0));
ZoneCommandGroup zcg = m_commandGroupCopied;
ZoneCommand zc = m_commandGroupCopied.parent();
zc.setId(iLine);
zcg.setParent(zc);
m_zoneCommands.addCommandGroup(zcg);
refreshView();
somethingChanged();
}
void WndZone::cutCommandLine()
{
#if defined( KREATOR_DEBUG )
qDebug("WndZone::cutCommandLine() called.");
#endif
copyCommandLine();
removeCommandLine();
}
void WndZone::updateMaxInits()
{
#if defined( KREATOR_DEBUG )
qDebug("WndZone::updateMaxInits() called.");
#endif
QTreeWidgetItem* item = selectedItem();
if (!item)
return;
int iLine = Utils::string2vnumber(item->text(0));
if (!m_zoneCommands.hasCommand(iLine)) {
QMessageBox::warning(this, TS::MESSAGE_BOX_WARNING,
trUtf8("Alla linea selezionata non e' piu' associato un comando di zona."));
return;
}
ZoneCommand zc = m_zoneCommands.command(iLine);
if (!zc.hasMaxField()) {
QMessageBox::warning(this, TS::MESSAGE_BOX_WARNING,
trUtf8("Alla linea selezionata non e' piu' associato un comando con il campo per il maxaggio."));
return;
}
QString sName = "";
int iCountInits = 0;
int iUpdate = 0;
if (zc.hasMobField()) {
sName = m_area.mobName(zc.argument(ZoneCommand::Argument1));
iCountInits = m_zoneCommands.countMobs(zc.argument(ZoneCommand::Argument1));
} else {
sName = m_area.itemName(zc.argument(ZoneCommand::Argument1));
iCountInits = m_zoneCommands.countItems(zc.argument(ZoneCommand::Argument1));
}
QString sTxt = "";
sTxt.sprintf("Si vuole aggiornare tutti i maxaggi per l'entita' #%ld (%s)?\n"
"%ld = maxaggio del comando selezionato\n"
"%d = numero totale inizializzazioni",
zc.argument(ZoneCommand::Argument1), qPrintable(sName),
zc.argument(ZoneCommand::Argument2), iCountInits);
switch (QMessageBox::question(this, TS::MESSAGE_BOX_QUESTION, sTxt,
QString("Aggiorna a %1").arg(zc.argument(ZoneCommand::Argument2)),
QString("Aggiorna a %1").arg(iCountInits), QString(trUtf8("Annulla")),
2, 2)) {
case 0:
iUpdate = zc.argument(ZoneCommand::Argument2);
break;
case 1:
iUpdate = iCountInits;
break;
default:
iUpdate = -1;
}
if (iUpdate > 0) {
int iUpdateCount = 0;
if (zc.hasMobField())
iUpdateCount = m_zoneCommands.setMaxMobs(zc.argument(ZoneCommand::Argument1), iUpdate);
else
iUpdateCount = m_zoneCommands.setMaxItems(zc.argument(ZoneCommand::Argument1), iUpdate);
QMessageBox::information(this, TS::MESSAGE_BOX_INFORMATION,
trUtf8("Sono stati Aggiornati %1 riferimenti.").arg(iUpdateCount));
refreshView();
somethingChanged();
}
}
|
304ac0276a35ba0063f725d50f24f9dd175e95e3 | a5a99f646e371b45974a6fb6ccc06b0a674818f2 | /CondTools/DT/test/validate/DTLVStatusValidateDBRead.h | a3c70065492bd18d9b941890e4e0c8c2cffd4ca3 | [
"Apache-2.0"
] | permissive | cms-sw/cmssw | 4ecd2c1105d59c66d385551230542c6615b9ab58 | 19c178740257eb48367778593da55dcad08b7a4f | refs/heads/master | 2023-08-23T21:57:42.491143 | 2023-08-22T20:22:40 | 2023-08-22T20:22:40 | 10,969,551 | 1,006 | 3,696 | Apache-2.0 | 2023-09-14T19:14:28 | 2013-06-26T14:09:07 | C++ | UTF-8 | C++ | false | false | 903 | h | DTLVStatusValidateDBRead.h |
/*----------------------------------------------------------------------
Toy EDAnalyzer for testing purposes only.
----------------------------------------------------------------------*/
#include "FWCore/Framework/interface/one/EDAnalyzer.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
class DTLVStatus;
class DTLVStatusRcd;
class DTLVStatusValidateDBRead : public edm::one::EDAnalyzer<> {
public:
explicit DTLVStatusValidateDBRead(edm::ParameterSet const& p);
explicit DTLVStatusValidateDBRead(int i);
~DTLVStatusValidateDBRead() override = default;
void analyze(const edm::Event& e, const edm::EventSetup& c) override;
void endJob() override;
private:
std::string dataFileName;
std::string elogFileName;
edm::ESGetToken<DTLVStatus, DTLVStatusRcd> dtlvstatusToken_;
};
|
486191bdda18cdc367d2a920daf3da9c710f9c1c | b1c9b5601a79b6ef33f454e0aa50356e4fa6cb0b | /PriorityQueue.h | 9037d5960e6daa2fd65a4263a200631b67c10e4f | [] | no_license | wetzelc22/cs375-prog-2 | 4a853ba7699e19370b6cac669d370eebbe8d210d | 8090b13ba7ef5590a9fa06d0002eac22ca9c812a | refs/heads/master | 2022-04-14T20:21:39.334873 | 2020-04-15T00:01:01 | 2020-04-15T00:01:01 | 254,746,392 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 464 | h | PriorityQueue.h | #ifndef CW_PRIORITYQUEUE
#define CW_PRIORITYQUEUE
#include "Node.h"
#include <vector>
class PriorityQueue{
private:
std::vector<Node *> queue;
public:
PriorityQueue();
void Heapify(std::vector<Node *>);
void siftdown(std::vector<Node *>&, int);
int left(unsigned int, std::vector<Node *>);
int right(unsigned int, std::vector<Node *>);
void addElement(Node *);
Node * getPriority();
bool empty();
unsigned long size(){return queue.size();};
};
#endif
|
13f792d0849d5c0a6dc6617a9494d4463a40c4fd | 319c4e17b51b68e2eac9d365a70d53553318c097 | /cpp04/ex03/inc/MateriaSource.hpp | 226a68d30f889dc370f2e8907f2f5ffc408e133a | [] | no_license | PracticeofEno/CPP | 079ea33273d461da1bbba9514bd49bc9f8e59600 | 192c6febcf79d497702cd95fbe52fb0a3dcd97ba | refs/heads/main | 2023-08-22T04:38:38.914669 | 2021-10-10T03:43:43 | 2021-10-10T03:43:43 | 395,391,236 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 470 | hpp | MateriaSource.hpp | #ifndef MATERIASOURCE_HPP
#define MATERIASOURCE_HPP
#include "AMateria.hpp"
#include "IMateriaSource.hpp"
class MateriaSource : public IMateriaSource {
public:
MateriaSource();
~MateriaSource();
MateriaSource(MateriaSource& tmp);
MateriaSource& operator=(MateriaSource& tmp);
void learnMateria(AMateria*);
AMateria* createMateria(const std::string& type);
int mIndex;
int tmp2Index;
AMateria* materias[4];
AMateria* tmp[4];
AMateria* tmp2[4];
};
#endif |
1ca242268d362701abba55ce766196dffa26c839 | 3acb4d7ee67b86305bd264a187d7fd97049d8843 | /CipherAlgorithms/main.cpp | 2c9858658c7c38463a2067e9a4e8a649c1633381 | [] | no_license | jesusHasRyzen/CipherAlgorithms | 1d7fa5656362b3d144471876eddf4380d0b2421d | d9bf9ec9485a91ca48245bc860e9b72c72b21dad | refs/heads/master | 2022-12-24T09:17:48.638174 | 2020-10-01T19:55:04 | 2020-10-01T19:55:04 | 300,408,676 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,734 | cpp | main.cpp | //
// main.cpp
// CipherAlgorithms
//
// Created by Jesus Ponce on 9/28/20.
// Copyright © 2020 Jesus Ponce. All rights reserved.
//
#include <iostream>
#include <string>
#include <vector>
#include <string.h>
#include <stdio.h>
#include <cstring>
//terative Rotation Cipher (IRC)
//The encode method will receive two arguments — a positive integer n and a string value.
//
//The decode method will receive one argument — a string value.
//Output
//
//Each method will return a string value.
//How It Works
//Encoding and decoding are done by performing a series of character and substring rotations on a string input.
//
//Encoding: The number of rotations is determined by the value of n. The sequence of rotations is applied in the following order:
// Step 1: remove all spaces in the string (but remember their positions)
// Step 2: shift the order of characters in the new string to the right by n characters
// Step 3: put the spaces back in their original positions
// Step 4: shift the characters of each substring (separated by one or more consecutive spaces) to the right by n
//Repeat this process until it has been completed n times in total.
//The value n is then prepended to the resulting string with a space.
//Decoding: Decoding simply reverses the encoding process.
std::string encode(int n, std::string str);
std::string insertSpacesByPosition(std::string, std::vector<int> spaces);
std::string moveCharsInStringRightNumberOfXTimes(int n,std::string str);
std::string decode(std::string str);
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
std::string intro ="If you wish to make an apple pie from scratch, you must first invent the universe.";
std::cout << encode(10, intro)<<std::endl;
std::cout <<encode(14,"True evil is a mundane bureaucracy.")<<std::endl;
return 0;
}
std::string encode(int n, std::string str)
{
std::vector <int> spacePositions;
int j =0, num =n;
std::string tempCode;
for(auto i: str)
{
if(i == ' ')
{
spacePositions.push_back(j);
}
else
{
tempCode+=i;
}
j++;
}
// tempCode = tempCode.substr((tempCode.length()-n),tempCode.length()) + tempCode.substr(0,(tempCode.length()-n));
while(num > 0){
tempCode = moveCharsInStringRightNumberOfXTimes(n, tempCode);
// for(int i: spacePositions)
// tempCode.insert(i, " ");
tempCode = insertSpacesByPosition(tempCode, spacePositions);
//making string into c-string to be able tokenize
char * cstr = new char [tempCode.length()+1];
std::strcpy (cstr, tempCode.c_str());
tempCode.clear();
//tokenizing the string passed
char * p = strtok(cstr, " ");
while(p != 0)
{
tempCode += moveCharsInStringRightNumberOfXTimes(n, p);
p = strtok(NULL, " ");
}
num--;
}
tempCode = insertSpacesByPosition(tempCode, spacePositions);
std::string m = std::to_string(n) + " ";
tempCode.insert(0,m);
return tempCode;
}
std::string insertSpacesByPosition(std::string str, std::vector<int> spaces)
{
for(int i: spaces)
str.insert(i, " ");
return str;
}
std::string moveCharsInStringRightNumberOfXTimes(int n,std::string str)
{
std::string tempCode;
if(str.length()>n)
{
tempCode = str.substr((str.length()-n),str.length()) + str.substr(0,(str.length()-n));
}
else
{
int remainder = n%str.length();
tempCode = str.substr((str.length()-remainder),str.length()) + str.substr(0,(str.length()-remainder));
}
return tempCode;
}
std::string decode(std::string str)
{
return "";
}
|
1a92edf94c7ba8b6a2fc63a2608987a771aed40d | c280ced86726a014064f40ee13aa9e9b3c59f962 | /Canadian Computing Olympiad/2005/The_Great_Spamway_Strike.cpp | 84b4be08b4ac02c3e96622f7702ec68ba19378b4 | [] | no_license | lfeng99/Competitive-Programming | 9379ce07a421f3bfe9ef3c6f5f390794b9c8595a | 5de75295522725047adb0e99ae7f637d8fc64ba3 | refs/heads/master | 2021-08-30T12:05:24.717850 | 2017-12-18T02:21:48 | 2017-12-18T02:21:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,025 | cpp | The_Great_Spamway_Strike.cpp | #include <bits/stdc++.h>
using namespace std;
int graph[110][110], sleep[110];
int main()
{
// freopen("CCO.txt","r",stdin);
cin.sync_with_stdio(0); cin.tie(0);
for (int i=0; i<110; ++i)
for (int j=0; j<110; ++j)
graph[i][j] = 1e9;
int N;
cin >> N;
for (int i=0; i<=N; ++i){
int M;
cin >> sleep[i] >> M;
for (int j=0; j<M; ++j){
int z; cin >> z;
graph[i][z] = graph[z][i] = 10;
}
}
for (int i=0; i<=N; ++i)
for (int j=0; j<=N; ++j)
if (graph[i][j] == 10)
graph[i][j] += sleep[j];
for (int j=0; j<=N; ++j)
for (int i=0; i<=N; ++i)
for (int k=0; k<=N; ++k){
if (graph[i][j] != 1e9 && graph[j][k] != 1e9){
graph[i][k] = min(graph[i][k], graph[i][j] + graph[j][k]);
}
}
int best = 0;
for (int i=1; i<=N; ++i)
if (graph[0][i]!=1e9)
best = max(best, graph[0][i] + graph[i][0]);
cout << best;
return 0;
}
|
eb7880aa827c3ad97d650a20ce06d5e648d344f3 | 7b963e1b8dd6f7288eaca2fe11233ed918ff139e | /FileReader.h | 8cba55bed0b84b0ed332bf82380ef1bc5983b904 | [] | no_license | m1ndless/BalayProject | b3281331fcc1a8a9f1c0dba19615b3a95252fdf3 | 0490b1e6a59655bff7a854ffa8f9c206d6764bfb | refs/heads/master | 2021-01-18T21:20:39.882492 | 2015-06-01T15:58:49 | 2015-06-01T15:58:49 | 32,573,093 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,373 | h | FileReader.h | //
// FileReader.h
// BalayProject
//
// Created by Denis Genalitskiy on 03.03.15.
// Copyright (c) 2015 Denis Genalitskiy. All rights reserved.
//
#ifndef __BalayProject__FileReader__
#define __BalayProject__FileReader__
#include <stdio.h>
#include <fstream>
#include "BitsBuffer.h"
class FileReader {
private:
size_t size;
const char* path;
std::ifstream ifs;
//in bytes
void filesize() {
ifs.seekg(0, ifs.end);
this->size = this->ifs.tellg();
ifs.seekg(0, ifs.beg);
}
public:
FileReader(const char* path) {
this->path = path;
this->ifs = std::ifstream(path, std::ifstream::binary);
filesize();
}
BitsBuffer* readNext(bool& isNext) {
// char buf[256];
// return new BitsBuffer(buf);
//если размер файла больше 50 мегабайт(ов?), делим файл на 10 кусков
if (this->size > 52428800)
{
return nullptr;
}
//читаем весь файл целиком
else {
isNext = false;
unsigned char *buf = new unsigned char[this->size];
ifs.read((char*)buf, this->size);
return new BitsBuffer(buf, this->size);
}
}
};
#endif /* defined(__BalayProject__FileReader__) */
|
3a920725a172ed30a206e7d686f399e0e4749667 | 7a92a764a05c06940853dd3793a6122a29a62c49 | /code/vertex_shader.cpp | 8786f97edff58d1967859eb9ec09d97db8808acb | [] | no_license | DmiAS/bmstu_CG_CP | c2f8831c3a48e3077812c940c95288153184f0ad | 4e2e980f6a64e790691c07e99f58ba72d332e4b2 | refs/heads/main | 2023-03-17T09:16:21.558445 | 2021-03-05T08:35:37 | 2021-03-05T08:35:37 | 338,559,053 | 0 | 0 | null | 2021-03-05T08:02:28 | 2021-02-13T11:26:51 | C++ | UTF-8 | C++ | false | false | 634 | cpp | vertex_shader.cpp | #include "vertex_shader.h"
Vertex VertexShader::shade(const Vertex &a, const Mat4x4f& rotMatrix, const Mat4x4f& objToWorld, const Camera& cam){
Vec4f res(a.pos);
res = res * objToWorld;
Vertex output = a;
output.pos = Vec3f(res.x, res.y, res.z);
auto normal = Vec4f(a.normal) * rotMatrix;
output.normal = Vec3f(normal.x, normal.y, normal.z).normalize();
auto diffuse = light_color * std::max(0.f, Vec3f::dot(output.normal.normalize(), -cam.direction.normalize())) * intensity;
auto c = (diffuse + ambient).saturate();
output.color = output.color.hadamard(c).saturate();
return output;
}
|
d5045c88091e3f761df49e97f0ee5677e00fb753 | 813d9380b3fbf66a0d344937a6be52f408b54078 | /runtime/regiontemplates/examples/PipelineRTFS-NS-Diff-AH-PRO-Yi/DiffMaskComp.cpp | 9389adcedfcb882e1a2d394a87b5802607913767 | [] | no_license | SBU-BMI/region-templates | 6b63fab2809ac281e458053069d26782d04cd1e5 | ab311b70eaeee3353ae09e1b8ba694e29d4d982d | refs/heads/master | 2023-03-05T03:26:03.580106 | 2017-07-13T03:02:35 | 2017-07-13T03:02:35 | 35,566,013 | 5 | 6 | null | 2017-04-17T20:04:58 | 2015-05-13T18:10:24 | C++ | UTF-8 | C++ | false | false | 1,733 | cpp | DiffMaskComp.cpp |
#include "DiffMaskComp.h"
#include <regiontemplates/comparativeanalysis/pixelcompare/PixelCompare.h>
DiffMaskComp::DiffMaskComp() {
this->setComponentName("DiffMaskComp");
this->addInputOutputDataRegion("tile", "MASK", RTPipelineComponentBase::INPUT);
}
DiffMaskComp::~DiffMaskComp() {
}
int DiffMaskComp::run()
{
int parameterSegId = ((ArgumentInt*)this->getArgument(0))->getArgValue();
RegionTemplate * inputRt = this->getRegionTemplateInstance("tile");
float *diffPixels = (float *) malloc(2 * sizeof(float));
diffPixels[0] = 0;
diffPixels[1] = 0;
this->setResultData((char *) diffPixels, 2 * sizeof(float));
if(inputRt != NULL){
// Mask computed in segmentation using specific application parameter set
DenseDataRegion2D *computed_mask = dynamic_cast<DenseDataRegion2D*>(inputRt->getDataRegion("MASK", "", 0, parameterSegId));
// Mask used as a reference
DenseDataRegion2D *reference_mask = dynamic_cast<DenseDataRegion2D*>(inputRt->getDataRegion("REF_MASK"));
if(computed_mask != NULL && reference_mask != NULL){
// gambiarra
diffPixels[0] = this->getId();
// Create processing task
TaskDiffMask *tDiffMask = new PixelCompare(computed_mask, reference_mask, diffPixels);
this->executeTask(tDiffMask);
}else{
std::cout << "DiffMaskComp: did not find data regions: " << std::endl;
inputRt->print();
}
}else{
std::cout << "\tTASK diff mask: Did not find RT named tile"<< std::endl;
}
return 0;
}
// Create the component factory
PipelineComponentBase* componentFactoryDF() {
return new DiffMaskComp();
}
// register factory with the runtime system
bool registeredDF = PipelineComponentBase::ComponentFactory::componentRegister("DiffMaskComp", &componentFactoryDF);
|
8b5ada3fe1f8b37a1934e45d45f98749dc43d634 | 0f36bb4e7e04b2c7eccaed79200a9d8629b05495 | /Source/UnlimRealms/Sys/Canvas.h | 282f07d0a64bcc47d1c15401a5aadb572fa8f3c9 | [] | no_license | AntekX/UnlimRealms | 1c43920ac31d15fa9b14757e2b7cfb5ce3ee4478 | 00604446e9c1d7b71c2816e0a3afb79ee791c42e | refs/heads/master | 2023-02-07T13:28:08.648864 | 2023-01-31T23:17:35 | 2023-01-31T23:17:35 | 72,669,246 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,256 | h | Canvas.h | ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// UnlimRealms
// Author: Anatole Kuzub
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "Realm/Realm.h"
namespace UnlimRealms
{
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Base system canvas
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class UR_DECL Canvas : public RealmEntity
{
public:
Canvas(Realm &realm);
virtual ~Canvas();
Result Initialize(const RectI &bound);
Result SetBound(const RectI &bound);
inline void SetPos(ur_int x, ur_int y);
inline void SetSize(ur_int width, ur_int height);
inline const RectI& GetBound() const;
inline const RectI& GetClientBound() const;
protected:
virtual Result OnInitialize(const RectI &bound);
virtual Result OnSetBound(const RectI &bound);
protected:
RectI clientBound;
private:
RectI bound;
};
} // end namespace UnlimRealms
#include "Sys/Canvas.inline.h" |
110edd844e18f1ddd1ce4ecba33d291ec5927db7 | 713c87d18d89579f42b1dad7e0ad5bc7abb7b285 | /GPLT团体程序设计天梯赛-练习集/L2-010.排座位_mutimap.cpp | e24992d4225a1a4c5a51c3251cd458a703f913fc | [] | no_license | spencercjh/PAT_Cpp | 452c84d70df4ba32aa8337f5bec32048e415770c | 3d4c829b9d144970b938230ae4d5d5e8d76b4217 | refs/heads/master | 2021-05-06T12:58:41.093406 | 2017-12-05T16:37:01 | 2017-12-05T16:37:01 | 113,205,622 | 2 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,718 | cpp | L2-010.排座位_mutimap.cpp | /*
Name: L2-010. 排座位
Author: spencercjh
Date: 2017年10月22日 12:11:23
Description:团体程序设计天梯赛-练习集 GPLT
https://www.patest.cn/contests/gplt/L2-010
ref:http://blog.csdn.net/lhrsdl/article/details/38119577
http://www.cplusplus.com/reference/map/multimap/find/
http://www.cnblogs.com/dongsheng/archive/2013/09/10/3311594.html
http://www.cplusplus.com/reference/map/multimap/equal_range/
*/
#include<iostream>
#include<cmath>
#include<string>
#include<cstring>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<numeric>
#include<stack>
using namespace::std;
int main()
{
int N,M,K;
scanf("%d %d %d",&N,&M,&K);
multimap<int,int> Friend;
multimap<int,int> Enemy;
for(int i=1; i<=N; i++) //初始化mutimap
{
Friend.insert(pair<int,int>(i,i));
Enemy.insert(pair<int,int>(i,i));
}
auto j=Friend.begin(),k=Friend.begin(),p=Enemy.begin(),q=Enemy.begin();
for(int i=0; i<M; i++)
{
int a,b,c;
scanf("%d %d %d",&a,&b,&c);
if(c==1)
{
j=Friend.find(a);
k=Friend.find(b);
if(j->first!=k->first)
{
Friend.insert(pair<int,int>(a,b));
Friend.insert(pair<int,int>(b,a));
}
}
else if(c==-1)
{
p=Enemy.find(a);
q=Enemy.find(b);
if(p->first!=q->first)
{
Enemy.insert(pair<int,int>(a,b));
Enemy.insert(pair<int,int>(b,a));
}
}
}
for(int i=0; i<K; i++)
{
int a,b;
scanf("%d %d",&a,&b);
bool friendflag=false,enemyflag=false,commonfriend=false;
auto Friendbeg=Friend.lower_bound(a),Friendend=Friend.upper_bound(a);
while(Friendbeg!=Friendend)
{
if(Friendbeg->second==b)
{
friendflag=true;
break;
}
Friendbeg++;
}
auto Enemybeg=Enemy.lower_bound(a),Enemyend=Enemy.upper_bound(a);
while(Enemybeg!=Enemyend)
{
if(Enemybeg->second==b)
{
enemyflag=true;
break;
}
Enemybeg++;
}
auto commonbeg=Friend.lower_bound(b),commonend=Friend.upper_bound(b);
if(enemyflag) //双方有敌对关系,寻找双方的共同朋友
{
Friendbeg=Friend.lower_bound(a); //之前Friendbeg已经经历过一个循环,在此规整
while(Friendbeg!=Friendend)
{
commonbeg=Friend.lower_bound(b); //之前commonbeg已经经历过一个循环,在此规整
while(commonbeg!=commonend)
{
if(Friendbeg->second==commonbeg->second)
{
commonfriend=true;
break;
}
commonbeg++;
}
Friendbeg++;
}
}
if(friendflag)
printf("No problem\n");
else if(enemyflag)
{
if(commonfriend)
printf("OK but...\n");
else
printf("No way\n");
}
else
printf("OK\n");
}
}
|
2f9401a7d10b856ddf28df97f2e68e55ae7a6881 | 1894685e4beaf304d0351b7cbb29f8421b597050 | /src/datasourcewindow.cpp | 4f40bb20bd7a4ecae482f60c155185d04d51927d | [] | no_license | maxavadallat/maxdesigner | f9d9f9568d633fc0b1ede609894630a2e0ac0eba | cf13dd5927be0a9aa8c45826f3cac213fb0578be | refs/heads/master | 2021-01-22T07:48:40.904807 | 2017-11-22T13:15:24 | 2017-11-22T13:15:24 | 81,853,498 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,726 | cpp | datasourcewindow.cpp | #include <QDebug>
#include "datasourcewindow.h"
#include "ui_datasourcewindow.h"
#include "settingscontroller.h"
#include "livewindow.h"
#include "projectmodel.h"
#include "constants.h"
//==============================================================================
// Constructor
//==============================================================================
DataSourceWindow::DataSourceWindow(LiveWindow* aLiveWindow, ProjectModel* aProjectModel, QWidget* aParent)
: QMainWindow(aParent)
, ui(new Ui::DataSourceWindow)
, mLiveWindow(aLiveWindow)
, mProject(aProjectModel)
, mSettings(SettingsController::getInstance())
{
// Setup UI
ui->setupUi(this);
// Init
init();
}
//==============================================================================
// Init
//==============================================================================
void DataSourceWindow::init()
{
// Restore UI
restoreUI();
}
//==============================================================================
// Restore UI
//==============================================================================
void DataSourceWindow::restoreUI()
{
}
//==============================================================================
// Shut Down
//==============================================================================
void DataSourceWindow::shutDown()
{
// Release Settings
mSettings->release();
// ...
}
//==============================================================================
// Add DataSource To Control
//==============================================================================
void DataSourceWindow::addDataSource(const QString& aName)
{
// Check Name
if (!aName.isEmpty()) {
}
}
//==============================================================================
// Remove Data Source From Controleld Data Sources
//==============================================================================
void DataSourceWindow::removeDataSource(const int& aIndex)
{
// Check Index
if (aIndex >= 0 && aIndex < mDataSources.count()) {
}
}
//==============================================================================
// Clear Controlled Data Sources
//==============================================================================
void DataSourceWindow::clearDataSources()
{
}
//==============================================================================
// Destructor
//==============================================================================
DataSourceWindow::~DataSourceWindow()
{
// Shut Down
shutDown();
// Delete Data Source Window Quick Widget
delete ui->dataSourceQuickWidget;
// Delte UI
delete ui;
}
|
cd7f01c5e742337d348e794cdd3ba6b820676563 | 74b9e30adec8a55d7afff2db5c9c25b91ec8667a | /Sivo-fuzzer/src/solutions.cpp | cc2990c9b81c5cd9587522b39aefcd0ea4e68f9f | [] | no_license | blu3sh0rk/SivoFuzzer-1 | 5812c42edad7b3200cf6fa1951805de9ad15127f | 4b7867c669132a9fb4a10aaea3e1fede68fcf533 | refs/heads/main | 2023-06-16T16:09:19.919751 | 2021-07-11T02:27:34 | 2021-07-11T02:27:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,047 | cpp | solutions.cpp | /*
Copyright (c) 2021, Ivica Nikolic <cube444@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "solutions.h"
#include "files_etc.h"
#include "executions.h"
#include "fork_servers.h"
#include "minimizer.h"
#include "testcases.h"
//
//
// Solutions are actually seeds. This keeps track of correctly naming them,
// i.e. assigning the right ID, and naming the seed files according to the
// fuzzer that was used to find them. Processing seeds that lead to
// timeouts and crashes is also partially defined here.
//
//
int solution_id=0;
set <uint32_t> crash_line;
int hang_id = 0;
int solutions_on_timeout = 0;
double tot_sol_add_time = 0;
map < int , int > solution_types;
map < int , set<uint32_t> > solution_types_iter;
map < int , int > solution_first;
map < pair<int, int>,int> true_coverage;
extern uint32_t *branches_instrument;
extern uint32_t *__new_branch_index;
string create_id(string temp_input, bool external_tc, int sol_type, string add_info )
{
if ( ! file_exists(temp_input) ){
printf( KERR "(create_id)Input file does not exist: %s\n" KNRM , temp_input.c_str() );
return "";
}
string solution_folder = OUTPUT_FOLDER+'/'+FUZZER_OUTPUT_FOLDER_NAME+"/queue/";
// true covearge
float ACTUAL_TIMEOUT_EXECUTION = TIMEOUT_EXECUTION;
TIMEOUT_EXECUTION = MAX_EXTERNAL_TC_TIMEOUT_EXEC;
int good_run_this = run_one_fork( RUN_GETTER );
TIMEOUT_EXECUTION = ACTUAL_TIMEOUT_EXECUTION;
bool real_update = false;
int found_new = false;
if( good_run_this ){
map < pair<int, int>,int> counters;
for( int i=1; i<__new_branch_index[0]; i++ ){
pair<int, int> p = make_pair( branches_trace[i-1], branches_trace[i] );
auto zz = counters.find(p);
if( zz == counters.end() )
counters.insert( { p , 1 } );
else
zz->second ++;
}
for( auto zz=counters.begin(); zz!= counters.end(); zz++){
auto edge = zz->first; // edge
auto count = zz->second; // count
int compressed_bit = count >=256 ? 128 : ectb[count];
auto it = true_coverage.find( edge );
if( it == true_coverage.end() ){
found_new = real_update = true;
true_coverage.insert( {edge, 0} );
it = true_coverage.find( edge );
}
real_update = real_update || (it->second | compressed_bit) != it->second;
it->second |= compressed_bit;
}
if( !real_update &&
!external_tc &&
(2!=glob_found_different) &&
!RE_INIT_USE
){
printf( KINFO "Not a real update: %d %ld \n" KNRM,
__new_branch_index[0], counters.size()
);
return "";
}
}
char reinit_info[1024];
if( RE_INIT_USE ) sprintf(reinit_info, "reinit-%02d-", RE_CURR_REPEATS );
else sprintf(reinit_info,"%s","");
char cdest_file[1024];
if (external_tc ){
// if external, it must increase the coverage to be accepted
// Give more time to external
prepare_tmp_input(temp_input);
float ACTUAL_TIMEOUT_EXECUTION = TIMEOUT_EXECUTION;
TIMEOUT_EXECUTION = MAX_EXTERNAL_TC_TIMEOUT_EXEC;
int good_run = run_one_fork( RUN_TRACER );
TIMEOUT_EXECUTION = ACTUAL_TIMEOUT_EXECUTION;
if( !good_run || !execution_edge_coverage_update() ){
printf( "Cannot properly execute (%d) or file %s does not increase coverage\n", good_run, temp_input.c_str() );
return "";
}
sprintf(cdest_file,"%s%sid:%06d,src:external%s",solution_folder.c_str(),reinit_info, solution_id,
(2==glob_found_different) ? "," SUFFIX_COV:"");
}
else
sprintf(cdest_file,"%s%sid:%06d,src:%06d,type:%s,fuzz:%s%s%s",
solution_folder.c_str(),
reinit_info,
solution_id,
current_testcase->my_id,
fuzzer_type ? "dataflow" : "vanillla",
get_solution_name(sol_type).c_str(),
add_info.c_str(),
(2==glob_found_different) ? "," SUFFIX_COV:""
);
string dest_file = string(cdest_file);
if( PRINT_FOUND_TESTCASES ){
printf( KGRN "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n");
printf( "New testcase %s\n", dest_file.c_str() );
printf( "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" KNRM);
}
interim_testcase ite;
ite.depth = (current_testcase != NULL) ? (current_testcase->depth + 1) : 0;
ite.is_new_cover = 2==glob_found_different;
ite.my_id = solution_id;
itest.insert( {dest_file, ite});
copy_binary_file( temp_input, dest_file );
solution_id ++;
if( good_run_this &&
2==glob_found_different &&
!RE_INIT_USE &&
!found_new &&
(__new_branch_index[0] < MAX_BRANCHES_INSTRUMENTED - 1)
){
printf( KINFO "No real new coverage found: %d %d %d : %s \n" KNRM,
glob_found_different, RE_INIT_USE, found_new,
cdest_file );
printf("#edges: %ld\n", true_coverage.size() );
int noz =0;
for( int j=0; j<1<<16; j++)
noz += showmap[j] > 0 ;
printf("#afledges: %d\n", noz );
}
// keep the full (un-minimized file) as well
/*
string dest_file_full=dest_file;
string squ = "/queue/", nsqu = "/queue_full/";
size_t pos = dest_file_full.find(squ);
if( pos >= 0){
dest_file_full.replace(pos, squ.length(), nsqu);
//simple_exec("cp "+temp_input + " "+dest_file_full);
copy_binary_file( temp_input, dest_file_full );
}
*/
if( !external_tc)
minimize_testcase(dest_file);
return dest_file;
}
void count_true_coverage( uint32_t cttc[2] )
{
cttc[0] = true_coverage.size();
cttc[1] = 0;
for( auto it= true_coverage.begin(); it!= true_coverage.end(); it++)
{
for( int i=0; i<8; i++)
cttc[1] += (it->second >> i) & 1;
}
}
void solution_add_found_types( int CURRENT_SOLUTION_TYPE )
{
// solution type (for logging purposes only)
if( solution_types.find( CURRENT_SOLUTION_TYPE ) == solution_types.end() )
solution_types.insert( {CURRENT_SOLUTION_TYPE,0});
solution_types.find( CURRENT_SOLUTION_TYPE )->second ++;
// solution type (with iteration number)
if( solution_types_iter.find( CURRENT_SOLUTION_TYPE ) == solution_types_iter.end() )
solution_types_iter.insert( {CURRENT_SOLUTION_TYPE , set<uint32_t>()} );
solution_types_iter.find( CURRENT_SOLUTION_TYPE )->second.insert(glob_iter);
// which type results in completely new edges
if( solution_first.find( CURRENT_SOLUTION_TYPE ) == solution_first.end() )
solution_first.insert( {CURRENT_SOLUTION_TYPE , 0} );
if( 2 == glob_found_different)
{
solution_first.find( CURRENT_SOLUTION_TYPE )->second ++;
}
}
void check_and_add_solution( string tmp_input_file, int CURRENT_SOLUTION_TYPE, string add_info )
{
if( last_crashed ) return;
if( last_is_timeout_max )
solutions_on_timeout ++;
START_TIMER(start_add_sol_time);
//# create a new testcase file and place it in the queue folder
string dest_file = create_id( tmp_input_file, false , CURRENT_SOLUTION_TYPE, add_info );
if (dest_file.size() != 0){
// add type
solution_add_found_types( CURRENT_SOLUTION_TYPE );
// add to the queue of testcases
get_testcases_from_folder(OUTPUT_FOLDER+"/"+FUZZER_OUTPUT_FOLDER_NAME +"/queue", false);
}
tot_sol_add_time += TIME_DIFFERENCE_SECONDS( start_add_sol_time );
return ;
}
void create_lookup_for_sol_id_to_string()
{
sol_type_id_to_str.insert( { SOL_TYPE_IMPORTED , "imported" } ) ;
sol_type_id_to_str.insert( { SOL_TYPE_BRANCH_GA , "branch-ga" } ) ;
sol_type_id_to_str.insert( { SOL_TYPE_SOLVER_A , "solverA" } ) ;
sol_type_id_to_str.insert( { SOL_TYPE_SOLVER_B , "solverB" } ) ;
sol_type_id_to_str.insert( { SOL_TYPE_BRANCH_PRIMARY , "branch-primary" } ) ;
sol_type_id_to_str.insert( { SOL_TYPE_BRANCH_SECOND , "branch-second" } ) ;
sol_type_id_to_str.insert( { SOL_TYPE_MINGLER , "mingler" } ) ;
sol_type_id_to_str.insert( { SOL_TYPE_MINGLER_DUMB , "minglerD" } ) ;
sol_type_id_to_str.insert( { SOL_TYPE_MINGLER_SMART , "minglerS" } ) ;
sol_type_id_to_str.insert( { SOL_TYPE_MUTATE_KNOWN , "mutate-known" } ) ;
sol_type_id_to_str.insert( { SOL_TYPE_MUTATE_RAND , "mutate-rand-ga" } ) ;
sol_type_id_to_str.insert( { SOL_TYPE_MUTATE_RAND1 , "mutate-rand-1" } ) ;
sol_type_id_to_str.insert( { SOL_TYPE_COPREM_RAND , "copyrem-rand" } ) ;
sol_type_id_to_str.insert( { SOL_TYPE_COPREM_REAL , "copyrem-real" } ) ;
sol_type_id_to_str.insert( { SOL_TYPE_COPREM_RE_DIVS , "copyrem-learn" } ) ;
sol_type_id_to_str.insert( { SOL_TYPE_COPREM_RE_PREV , "copyrem-prev" } ) ;
sol_type_id_to_str.insert( { SOL_TYPE_COMBINER , "combiner" } ) ;
sol_type_id_to_str.insert( { SOL_TYPE_COMBINERSMART , "combiner-learn" } ) ;
}
string get_solution_name( int stype )
{
auto it = sol_type_id_to_str.find( stype );
if( it == sol_type_id_to_str.end() ) return "unknown"+to_string(stype);
return it->second;
}
uint32_t count_current_important_tc()
{
return solution_id + crash_uniq;
}
void process_crash( int status )
{
crash_id++;
uint32_t last_bb = 0;
//if( STORE_CRASHES && execution_showmap_crashes_new() )
if( STORE_CRASHES )
{
if( 0 == __new_branch_index[0] ){
processing_crash = true;
run_one_fork( RUN_GETTER );
processing_crash == false;
}
if( __new_branch_index[0] > 0 ){
last_bb = branches_trace[ __new_branch_index[0] - 1 ];
if( crash_line.find( last_bb ) == crash_line.end() ){
crash_uniq++;
crash_line.insert( last_bb );
// add type
solution_add_found_types( fuzzer_current_main );
string crashes_folder = OUTPUT_FOLDER+"/"+FUZZER_OUTPUT_FOLDER_NAME+"/crashes/";
string fuz_type = get_solution_name(fuzzer_current_main);
char ccrash_file[1024];
sprintf(ccrash_file, "%scrash-uid:%06d,totnum:%06d,status:%02d,bb:%08x,type:%s,fuzz:%s,src:%06d",
crashes_folder.c_str(), crash_uniq, crash_id, status, last_bb,
fuzzer_type ? "dataflow" : "vanillla", fuz_type.c_str(),
current_testcase->my_id );
string crash_file = string( ccrash_file );
copy_binary_file( TMP_INPUT, crash_file );
current_testcase->found_crash = true;
}
}
}
}
void store_timeout_testcase()
{
hang_id++;
if(!STORE_TIMEOUTS ) return;
string hangs_folder = OUTPUT_FOLDER+"/"+FUZZER_OUTPUT_FOLDER_NAME+"/hangs/";
string fuz_type = get_solution_name(fuzzer_current_main);
char chang_file[1024];
sprintf(chang_file, "%shang-id:%06d,type:%s,fuzz:%s",
hangs_folder.c_str(), hang_id,
fuzzer_type ? "dataflow" : "vanillla",
fuz_type.c_str() );
string hang_file = string( chang_file );
copy_binary_file( TMP_INPUT, hang_file );
}
void process_timeout( int type_of_run ,
uint64_t &res_runs, uint64_t &res_timo,
int QTS, uint8_t queue_timeouts[],
uint32_t ×_successfull_used_temp_timeout, uint32_t ×_used_temp_timeout )
{
// if increases coverage then assign MAX_TIMEOUT_EXECUTION and re-run
if( STORE_TIMEOUTS && execution_showmap_timeout_new() ){
float ACTUAL_TIMEOUT_EXECUTION = TIMEOUT_EXECUTION;
TIMEOUT_EXECUTION = MAX_TIMEOUT_EXECUTION;
processing_timeout_max = true;
run_one_fork( type_of_run );
processing_timeout_max = false;
TIMEOUT_EXECUTION = ACTUAL_TIMEOUT_EXECUTION;
return;
}
// ONLY if the final run among the last FACTOR_INCREASE_TIMEOUT runs timeout
// then repeat the execution with timeout increased by a factor of FACTOR_INCREASE_TIMEOUT
queue_timeouts[ res_runs % int(FACTOR_INCREASE_TIMEOUT) ] = 1;
int s = 0;
for( int i=0; i< int(FACTOR_INCREASE_TIMEOUT) ; i++) s += queue_timeouts[i];
if( s <= 1 ){
// If certain percentage of runs with already increased execution time (by FACTOR_INCREASE_TIMEOUT)
// still timeouts, then increase the FACTOR_INCREASE_TIMEOUT
float prz = times_used_temp_timeout > 0 ? 100.0 * times_successfull_used_temp_timeout /times_used_temp_timeout : 0.0;
if( times_used_temp_timeout > 5 &&
prz < 50.0 &&
int(FACTOR_INCREASE_TIMEOUT) < QTS
)
FACTOR_INCREASE_TIMEOUT = mmin( QTS, 1.5 * FACTOR_INCREASE_TIMEOUT);
printf( KINFO "Repeating execution with larger timeout: %5.1f : %5d %5d : %.1f : %.3f x %.1f -> %.3f \n" KNRM,
prz,
times_successfull_used_temp_timeout, times_used_temp_timeout,
100.0 * res_timo/res_runs,
TIMEOUT_EXECUTION, FACTOR_INCREASE_TIMEOUT, mmin( MAX_TIMEOUT_EXECUTION, TIMEOUT_EXECUTION * FACTOR_INCREASE_TIMEOUT ) );
fflush(stdout);
processing_temp_timeout = true;
times_used_temp_timeout ++;
run_one_fork( type_of_run );
}
} |
005570b8f1c79cdfe4793c2823f83195174594ee | 43db097127c291414f1dabb858a822daa63e32e4 | /include/Cfg/AdamoGeneric.h | 82a97c7db1fc8cb61768a0d86e35cd1b4c168d7a | [] | no_license | Spritutu/AdamoIDE | c7e0188b72846c154192692e77a123727f5d7865 | d6f6e785a56526f22dc8a86e53abf56b180e808d | refs/heads/master | 2023-02-05T09:57:59.621114 | 2020-12-29T10:44:38 | 2020-12-29T10:44:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 654 | h | AdamoGeneric.h | /*
** AdamoGeneric.h
*/
#if !defined(AFX_DGTIN_H__EF3C3325_4AAB_434E_91C9_E235F8A61635__INCLUDED_)
#define AFX_DGTIN_H__EF3C3325_4AAB_434E_91C9_E235F8A61635__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CAdamoGenericCan : public CAdamoBase
{
DECLARE_SERIAL(CAdamoGenericCan)
public:
CAdamoGenericCan();
virtual ~CAdamoGenericCan();
virtual void Serialize(CArchive &ar);
virtual void Serialize(stAdamoParametri *pAdamoParametri, CStdioFile *pFile);
virtual enDispositivi GetType() {
return enGenericCan;
}
};
#endif // !defined(AFX_DGTIN_H__EF3C3325_4AAB_434E_91C9_E235F8A61635__INCLUDED_)
|
8d00aca5f4014bcafa989955da41acbb7e19f6a6 | 2d7b655a43669f291dbab4975e243ceb6947ee9b | /A4/GeometryNode.cpp | fb590054e7de355cf413c9ce547ca8a1ca682965 | [] | no_license | chinux23/CS488-Ray-Tracer | 555c879584126df2cd2851910559bd614c2d3a52 | 895a95d2c0389ce47fc41271551d77865f5de244 | refs/heads/master | 2021-01-17T17:11:53.086140 | 2019-08-24T05:56:03 | 2019-08-24T05:56:03 | 49,350,195 | 3 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 2,552 | cpp | GeometryNode.cpp | #include "GeometryNode.hpp"
//---------------------------------------------------------------------------------------
GeometryNode::GeometryNode(
const std::string & name, Primitive *prim, Material *mat )
: SceneNode( name )
, m_material( mat )
, m_primitive( prim )
, m_texture( nullptr )
{
m_nodeType = NodeType::GeometryNode;
}
void GeometryNode::setMaterial( Material *mat )
{
// Obviously, there's a potential memory leak here. A good solution
// would be to use some kind of reference counting, as in the
// C++ shared_ptr. But I'm going to punt on that problem here.
// Why? Two reasons:
// (a) In practice we expect the scene to be constructed exactly
// once. There's no reason to believe that materials will be
// repeatedly overwritten in a GeometryNode.
// (b) A ray tracer is a program in which you compute once, and
// throw away all your data. A memory leak won't build up and
// crash the program.
m_material = mat;
}
Intersection GeometryNode::intersect(const Ray & ray)
{
auto origin = invtrans * ray.origin;
auto dir = invtrans * ray.direction;
Ray new_ray(origin, dir);
Intersection i = m_primitive->intersect(ray);
if (i.hit) {
// update material at the point of the hit
i.material = (PhongMaterial *)m_material;
i.node = this;
}
return i;
}
Intersection GeometryNode::intersect(const Ray & ray, std::list<glm::mat4> transformations)
{
auto origin = invtrans * ray.origin;
auto dir = invtrans * ray.direction;
Ray new_ray(origin, dir);
Intersection i = m_primitive->intersect(new_ray);
if (i.hit) {
// get the materials as usual
i.material = (PhongMaterial *)m_material;
i.node = this;
}
// Test with all remaning child, and return the closet intersection point.
for (auto child : children) {
Intersection child_i = child->intersect(new_ray, transformations);
if (child_i.hit) {
if (!i.hit || child_i.t < i.t) {
i = child_i;
}
}
}
if (i.hit) {
// Once hit, transform normal and incoming ray back to the world coordinates.
auto normal = glm::dvec3(i.normal);
auto invtrans3 = glm::dmat3(invtrans);
i.normal = glm::dvec4(glm::transpose(invtrans3) * normal, 0);
// i.normal = glm::transpose(invtrans) * i.normal;
i.normal = glm::normalize(i.normal);
i.incoming_ray.origin = trans * i.incoming_ray.origin;
i.incoming_ray.direction = trans * i.incoming_ray.direction;
i.fromMaterial = ray.material;
}
return i;
}
bool GeometryNode::isOpticsEnabled()
{
return m_primitive->isOpticsEnabled();
}
|
991979d25ae12030fc352048524308d2f4a6b7ea | a6094c9c6d19a0878eb379bb8f8b09243072ba73 | /lmm-p3540-Accepted-s915303.cpp | e6ed5e16c007007fb213b603db192177a44b1067 | [] | no_license | pedris11s/coj-solutions | c6b0c806a560d1058f32edb77bc702d575b355c3 | e26da6887109697afa4703f900dc38a301c94835 | refs/heads/master | 2020-09-26T07:25:40.728954 | 2019-12-05T22:51:07 | 2019-12-05T22:51:07 | 226,202,753 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,126 | cpp | lmm-p3540-Accepted-s915303.cpp | #include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ULL;
const int NB = 4;
const int MAXN = 1e3 + 1;
const ULL PB[NB] = {17, 23, 31, 41};
#define V(c) ((c) - 'a' + 1)
int K, N;
string S;
ULL P[MAXN];
ULL H[MAXN];
ULL BASE;
map<ULL, int> F;
void precalc(){
BASE = PB[NB - 1]; //randomize if WA
P[0] = 1ULL;
for (int i = 1 ; i <= N ; i++){
P[i] = P[i - 1] * BASE;
H[i] = H[i - 1] * BASE + V(S[i]);
}
}
ULL h(int a, int b){
ULL r = H[b] - H[a - 1] * P[b - a + 1];
return r;
}
int main()
{
cin >> K;
cin >> S;
N = S.size();
S = " " + S;
precalc();
int sol = -1;
for (int L = 1 ; L <= N ; L++){
F.clear();
for (int j = L ; j <= N ; j++){
ULL x = h(j - L + 1, j);
if (F.find(x) == F.end())
F[x] = 1;
else
F[x]++;
}
map<ULL, int> :: iterator it;
for (it = F.begin() ; it != F.end() ; it++){
int f = (*it).second;
if (f == K)
sol = L;
}
}
cout << sol;
return 0;
}
|
7e05c80c045bcfa9f1932a3b12c727d4dcc66514 | ad23f1909778c33ef1144678ab97de6c3dfff531 | /main.cpp | f48e32164e87ace0e12664c0791752ebcf498e5c | [] | no_license | Lxnoob/parking_sys | 5fc8854ee9a7ee03fecddcc30d1661783d22e826 | 830c28fbfa4c626abb5557e2c5513eb8547c65a7 | refs/heads/master | 2021-01-20T00:29:01.246191 | 2017-04-29T14:30:01 | 2017-04-29T14:30:01 | 89,139,581 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 298 | cpp | main.cpp | #include "login.h"
#include "parking.h"
#include "carport.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// Widget w;
// Parking w;
// carport w;
// w.show();
Parking *p = Parking::TheInstance();
p->show();
return a.exec();
}
|
10995a73dc61bb15723296e88dcbb03eec033cd0 | 902faa8e9b9808a19cd76d27e3caa6899a171289 | /terrain/chunk_terrain.cpp | 0a7bc6a8a988c42c99e3b2e6ae140938b931c78d | [] | no_license | JoseETeixeira/Chunk_Terrain_Godot | ef569a7a737adfcbcc5d6b1826f0526f290320c9 | 2d6f76179be9c57c5f3ce475515ef58884da1dce | refs/heads/main | 2023-06-22T18:18:50.588562 | 2021-07-26T12:13:13 | 2021-07-26T12:13:13 | 386,690,993 | 5 | 0 | null | 2021-07-21T22:50:38 | 2021-07-16T15:55:19 | C++ | UTF-8 | C++ | false | false | 11,766 | cpp | chunk_terrain.cpp | /* chunk_terrain.cpp */
/*
Copyright (c) 2021 José Eduardo da Silva Teixeira Junior
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "chunk_terrain.h"
#include "../generator/chunk_generator.h"
#include <core/core_string_names.h>
#include <core/array.h>
template <typename T>
std::vector<String> get_keys(std::map<String,T> dictionary){
std::vector<String> mapString;
for(auto const& imap: dictionary)
mapString.push_back(imap.first);
return mapString;
}
ChunkTerrain::ChunkTerrain(){
set_x(0);
set_z(0);
set_chunk_size(32);
set_chunk_amount(16);
should_generate = true;
should_generate_water = true;
should_generate_grass = true;
pool = ThreadPool::get_singleton();
set_process(true);
}
ChunkTerrain::~ChunkTerrain(){
std::vector<String> chunk_keys = get_keys(chunks);
for (uint32_t it =0; it<chunk_keys.size(); it++){
ChunkGenerator *chunk = chunks[chunk_keys[it]];
if(chunk!= NULL){
memdelete(chunk);
}
}
chunks.clear();
unready_chunks.clear();
}
void ChunkTerrain::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_PROCESS:
_process(get_process_delta_time());
break;
}
}
void ChunkTerrain::set_x(int x){
_x = x;
}
void ChunkTerrain::set_z(int z){
_z = z;
}
int ChunkTerrain::get_x(){
return _x;
}
int ChunkTerrain::get_z(){
return _z;
}
void ChunkTerrain::set_chunk_size(int size){
_chunk_size = size;
}
int ChunkTerrain::get_chunk_size(){
return _chunk_size;
}
void ChunkTerrain::set_chunk_amount(int amount){
_chunk_amount = amount;
}
int ChunkTerrain::get_chunk_amount(){
return _chunk_amount;
}
void ChunkTerrain::_process(float delta){
if(_noise!=NULL && _surface_material!=nullptr){
update_chunks();
clean_up_chunks();
reset_chunks();
}
}
void ChunkTerrain::set_noise(Ref<OpenSimplexNoise> noise) {
if (_noise == noise) {
return;
}
_noise = noise;
}
Ref<OpenSimplexNoise> ChunkTerrain::get_noise() {
return _noise;
}
void ChunkTerrain::set_surface_material(Ref<ShaderMaterial> surface_material) {
if (_surface_material == surface_material) {
return;
}
_surface_material = surface_material;
}
Ref<ShaderMaterial> ChunkTerrain::get_surface_material() {
return _surface_material;
}
void ChunkTerrain::set_water_material(Ref<ShaderMaterial> water_material) {
if (_water_material == water_material) {
return;
}
_water_material = water_material;
}
Ref<ShaderMaterial> ChunkTerrain::get_water_material() {
return _water_material;
}
void ChunkTerrain::set_grass_material(Ref<ShaderMaterial> grass_material) {
if (_grass_material == grass_material) {
return;
}
_grass_material = grass_material;
}
Ref<ShaderMaterial> ChunkTerrain::get_grass_material() {
return _grass_material;
}
template <typename T>
std::string NumberToString ( T Number )
{
std::ostringstream ss;
ss << Number;
return ss.str();
}
void ChunkTerrain::add_chunk(int x_local, int z_local){
String xx = NumberToString(x_local).c_str();
String zz = NumberToString(z_local).c_str();
String key = xx + "," + zz;
if (chunks.find(key)!=chunks.end() || unready_chunks.find(key)!=unready_chunks.end()){
return;
}
Array arr;
arr.push_back(x_local);
arr.push_back(z_local);
arr.push_back(_chunk_size);
pool->create_execute_job(this, "load_chunk", arr);
unready_chunks[key] = 1;
}
void ChunkTerrain::load_chunk(Array arr){
int x_local = arr.pop_front();
int z_local = arr.pop_front();
int chunk_size = arr.pop_front();
ChunkGenerator *chunk = memnew(ChunkGenerator(x_local,z_local));
chunk->set_x(x_local * chunk_size);
chunk->set_z(z_local * chunk_size);
chunk->set_chunk_size(chunk_size);
chunk->set_translation(Vector3(x_local*chunk_size,0,z_local*chunk_size));
load_done(chunk);
//call_deferred("load_done",chunk);
}
void ChunkTerrain::load_done(Variant variant){
ChunkGenerator *chunk = Object::cast_to<ChunkGenerator>(variant);
if(chunk!=NULL){
mtx.lock();
add_child(chunk);
String xx = NumberToString(chunk->get_x()/get_chunk_size()).c_str();
String zz = NumberToString(chunk->get_z()/get_chunk_size()).c_str();
String key = xx + "," + zz;
chunks[key] = chunk;
unready_chunks.erase(key);
mtx.unlock();
}
call_deferred("_on_load_done",chunk);
//mtx.unlock();
//thread.wait_to_finish();
}
void ChunkTerrain::_on_load_done(Variant variant){
ChunkGenerator *chunk = Object::cast_to<ChunkGenerator>(variant);
if(chunk!=NULL){
print_line(String("Chunk Loaded {{0}, {1}}").format(varray(chunk->get_x(), chunk->get_z())));
}
}
ChunkGenerator* ChunkTerrain::get_chunk(int x_local, int z_local){
String xx = NumberToString(x_local).c_str();
String zz = NumberToString(z_local).c_str();
String key = xx + "," + zz;
if(chunks.find(key)!=chunks.end()){
return chunks[key];
}
return NULL;
}
void ChunkTerrain::update_chunks(){
Node *player = get_node(player_path);
if (player!=NULL && player->is_inside_tree() == true){
Spatial *s_player = Object::cast_to<Spatial>(player);
if(s_player != NULL){
set_x(s_player->get_translation().x);
set_z(s_player->get_translation().z);
}
}
Vector3 player_translation = Vector3(get_x(),0,get_z());
int p_x = int(player_translation.x) / _chunk_size;
int p_z = int(player_translation.z) / _chunk_size;
for (int i = (p_x - _chunk_amount * 0.5); i< (p_x + _chunk_amount * 0.5); i++){
for (int j = (p_z - _chunk_amount * 0.5);j< (p_z + _chunk_amount * 0.5); j++){
add_chunk(i, j);
ChunkGenerator *chunk = get_chunk(i,j);
if (chunk != NULL){
chunk->set_should_remove(false);
}
}
}
}
void ChunkTerrain::clean_up_chunks(){
std::vector<String> chunk_keys = get_keys(chunks);
for (uint32_t it =0; it<chunk_keys.size(); it++){
ChunkGenerator* chunk = chunks[chunk_keys[it]];
if(chunk!=NULL){
if(chunk->get_should_remove() == true){
memdelete(chunk);
chunks.erase(chunk_keys[it]);
}
}
}
}
void ChunkTerrain::reset_chunks(){
std::vector<String> chunk_keys = get_keys(chunks);
for (uint32_t it =0; it<chunk_keys.size(); it++){
ChunkGenerator* chunk = chunks[chunk_keys[it]];
if(chunk!=NULL){
chunk->set_should_remove(true);
}
}
}
void ChunkTerrain::set_player_path(NodePath path){
player_path = path;
}
NodePath ChunkTerrain::get_player_path(){
return player_path;
}
void ChunkTerrain::set_should_generate_water(bool generate_water){
should_generate_water = generate_water;
}
bool ChunkTerrain::get_should_generate_water(){
return should_generate_water;
}
void ChunkTerrain::set_grass_mesh(Ref<Mesh> mesh){
grass_mesh = mesh;
}
Ref<Mesh> ChunkTerrain::get_grass_mesh(){
return grass_mesh;
}
void ChunkTerrain::set_should_generate_grass(bool generate_grass){
should_generate_grass = generate_grass;
}
bool ChunkTerrain::get_should_generate_grass(){
return should_generate_grass;
}
void ChunkTerrain::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_x", "x"), &ChunkTerrain::set_x);
ClassDB::bind_method(D_METHOD("get_x"), &ChunkTerrain::get_x);
ClassDB::bind_method(D_METHOD("set_z", "z"), &ChunkTerrain::set_z);
ClassDB::bind_method(D_METHOD("get_z"), &ChunkTerrain::get_z);
ClassDB::bind_method(D_METHOD("set_chunk_size", "size"), &ChunkTerrain::set_chunk_size);
ClassDB::bind_method(D_METHOD("get_chunk_size"), &ChunkTerrain::get_chunk_size);
ClassDB::bind_method(D_METHOD("set_chunk_amount", "amount"), &ChunkTerrain::set_chunk_amount);
ClassDB::bind_method(D_METHOD("get_chunk_amount"), &ChunkTerrain::get_chunk_amount);
ClassDB::bind_method(D_METHOD("set_noise", "noise"), &ChunkTerrain::set_noise);
ClassDB::bind_method(D_METHOD("get_noise"), &ChunkTerrain::get_noise);
ClassDB::bind_method(D_METHOD("set_player_path", "path"), &ChunkTerrain::set_player_path);
ClassDB::bind_method(D_METHOD("get_player_path"), &ChunkTerrain::get_player_path);
ClassDB::bind_method(D_METHOD("add_chunk", "x","y"), &ChunkTerrain::add_chunk);
ClassDB::bind_method(D_METHOD("load_chunk", "arr"), &ChunkTerrain::load_chunk);
ClassDB::bind_method(D_METHOD("load_done", "var"), &ChunkTerrain::load_done);
ClassDB::bind_method(D_METHOD("_on_load_done","chunk"), &ChunkTerrain::_on_load_done);
ClassDB::bind_method(D_METHOD("set_surface_material", "surface_material"), &ChunkTerrain::set_surface_material);
ClassDB::bind_method(D_METHOD("get_surface_material"), &ChunkTerrain::get_surface_material);
ClassDB::bind_method(D_METHOD("set_water_material", "water_material"), &ChunkTerrain::set_water_material);
ClassDB::bind_method(D_METHOD("get_water_material"), &ChunkTerrain::get_water_material);
ClassDB::bind_method(D_METHOD("set_grass_mesh", "grass_mesh"), &ChunkTerrain::set_grass_mesh);
ClassDB::bind_method(D_METHOD("get_grass_mesh"), &ChunkTerrain::get_grass_mesh);
ClassDB::bind_method(D_METHOD("set_should_generate_water", "generate_water"), &ChunkTerrain::set_should_generate_water);
ClassDB::bind_method(D_METHOD("get_should_generate_water"), &ChunkTerrain::get_should_generate_water);
ClassDB::bind_method(D_METHOD("set_should_generate_grass", "generate_grass"), &ChunkTerrain::set_should_generate_grass);
ClassDB::bind_method(D_METHOD("get_should_generate_grass"), &ChunkTerrain::get_should_generate_grass);
ClassDB::bind_method(D_METHOD("set_grass_material", "grass_material"), &ChunkTerrain::set_grass_material);
ClassDB::bind_method(D_METHOD("get_grass_material"), &ChunkTerrain::get_grass_material);
ADD_GROUP("Terrain", "");
ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "player", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Spatial"), "set_player_path", "get_player_path");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "noise", PROPERTY_HINT_RESOURCE_TYPE, "OpenSimplexNoise"), "set_noise", "get_noise");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "surface_material", PROPERTY_HINT_RESOURCE_TYPE, "ShaderMaterial"), "set_surface_material", "get_surface_material");
ADD_PROPERTY(PropertyInfo(Variant::INT, "chunk_size"), "set_chunk_size", "get_chunk_size");
ADD_PROPERTY(PropertyInfo(Variant::INT, "chunk_amount"), "set_chunk_amount", "get_chunk_amount");
ADD_GROUP("Water", "");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "water_material", PROPERTY_HINT_RESOURCE_TYPE, "ShaderMaterial"), "set_water_material", "get_water_material");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "should_generate_water"), "set_should_generate_water", "get_should_generate_water");
ADD_GROUP("Grass", "");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "grass_mesh", PROPERTY_HINT_RESOURCE_TYPE, "Mesh"), "set_grass_mesh", "get_grass_mesh");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "grass_material", PROPERTY_HINT_RESOURCE_TYPE, "ShaderMaterial"), "set_grass_material", "get_grass_material");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "should_generate_grass"), "set_should_generate_grass", "get_should_generate_grass");
}
|
375e6357900637f54cd996fc0ce9d58ecf3edf95 | b5317b08ddec6620382bdd85b791000752766760 | /modules/vis/processors/advoptimizedraycaster.h | d911e6a8e4a1c571d370af75f3deae16176634ea | [
"Apache-2.0"
] | permissive | hmsgit/campvis | 49379dedfb0143e086183c7b89de6efaa6f0dfed | d97de6a86323866d6a8f81d2a641e3e0443a6b39 | refs/heads/master | 2021-04-26T13:16:05.224811 | 2016-02-10T13:56:18 | 2016-02-10T13:56:18 | 121,310,766 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,558 | h | advoptimizedraycaster.h | // ================================================================================================
//
// This file is part of the CAMPVis Software Framework.
//
// If not explicitly stated otherwise: Copyright (C) 2012-2015, all rights reserved,
// Christian Schulte zu Berge <christian.szb@in.tum.de>
// Chair for Computer Aided Medical Procedures
// Technische Universitaet Muenchen
// Boltzmannstr. 3, 85748 Garching b. Muenchen, Germany
//
// For a full list of authors and contributors, please refer to the file "AUTHORS.txt".
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
//
// ================================================================================================
#ifndef AdvOptimizedRaycaster_H__
#define AdvOptimizedRaycaster_H__
#include "core/pipeline/raycastingprocessor.h"
#include "core/properties/floatingpointproperty.h"
#include "core/properties/genericproperty.h"
#include "core/properties/transferfunctionproperty.h"
#include "modules/modulesapi.h"
#include "modules/vis/tools/voxelhierarchymapper.h"
#include <string>
namespace cgt {
class Shader;
}
namespace campvis {
/**
* Performs ray casting using acceleration data structure. Also, the number of control instructions which is used is reduced to increase the execution performance on the gpu.
* The method is similar to [THGM11] paper. First, the data to be rendered is voxelized and stored in a 2D texture (each element of the texture is a 32-bit int. So, each element of the texture
* can store 32 ). Then, a hierarchy is generated to increase the ray-rendering
* [THGM11] Sinje Thiedemann, Niklas Henrich, Thorsten Grosch, and Stefan Müller. 2011. Voxel-based global illumination. In Symposium on Interactive 3D Graphics and Games (I3D '11). ACM, New York, NY, USA, 103-110. DOI=10.1145/1944745.1944763 http://doi.acm.org/10.1145/1944745.1944763
*/
class CAMPVIS_MODULES_API AdvOptimizedRaycaster : public RaycastingProcessor {
public:
enum AdditionalInvalidationLevels {
INVALID_BBV = AbstractProcessor::FIRST_FREE_TO_USE_INVALIDATION_LEVEL
};
/**
* Constructs a new AdvOptimizedRaycaster Processor
**/
explicit AdvOptimizedRaycaster(IVec2Property* viewportSizeProp);
/**
* Destructor
**/
virtual ~AdvOptimizedRaycaster();
/**
* To be used in ProcessorFactory static methods
*/
static const std::string getId() { return "AdvOptimizedRaycaster"; };
/// \see AbstractProcessor::getName()
virtual const std::string getName() const { return getId(); };
/// \see AbstractProcessor::getDescription()
virtual const std::string getDescription() const { return "Performs advanced ray casting to render sparse and big volumes faster."; };
/// \see AbstractProcessor::getAuthor()
virtual const std::string getAuthor() const { return "Morteza Mostajab <mostajab@in.tum.de>"; };
/// \see AbstractProcessor::getProcessorState()
virtual ProcessorState getProcessorState() const { return AbstractProcessor::EXPERIMENTAL; };
/// \see AbstractProcessor::init
virtual void init();
/// \see AbstractProcessor::deinit
virtual void deinit();
BoolProperty p_enableShading; ///< Flag whether to enable shading
DataNameProperty p_lightId; ///< Name/ID for the LightSource to use
protected:
/// \see RaycastingProcessor::processImpl()
virtual void processImpl(DataContainer& data, ImageRepresentationGL::ScopedRepresentation& image);
/// \see RaycastingProcessor::updateProperties
virtual void updateProperties(DataContainer& dataContainer);
/// \see RaycastingProcessor::generateHeader()
virtual std::string generateHeader() const;
VoxelHierarchyMapper* _vhm;
static const std::string loggerCat_;
};
}
#endif // AdvOptimizedRaycaster_H__
|
5e635b437a81eccb8b092847465a128aaf2e014a | 666fc810542ad3703214952d459b4dd0d165b18c | /zot.cpp | 4ecb6e31b084504629e9ff72e1d62fa89d079da4 | [] | no_license | drdanz/test_template_explicit_instantiation | e35618a1d7f34d709e74cc9f6cb7dadbd12f2cc0 | 360f5a3cf31e8470f580e57452a1092e79e4b3a1 | refs/heads/master | 2020-12-19T01:23:49.669756 | 2020-01-22T16:42:32 | 2020-01-22T16:42:32 | 235,577,800 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 117 | cpp | zot.cpp | #include "zot.h"
Zot::Zot([[maybe_unused]] int n) {}
int Zot::zot1() { return {}; }
int Zot::zot2() { return {}; }
|
5a5dfb70b5b4278e6fc0c0308a9e8a40de3df0a7 | 47a4b9901faf9742273b02ba14444d8d555b65a4 | /Codeforces/831Eredux.cpp | 06f8e17cabb00cce963185c9187196fca81126e7 | [] | no_license | Aulene/Competitive-Programming-Solutions | a028b7b96e024d8547e2ff66801e5377d7fb76cd | 81d2705263313755399f2e3b6e01e029d40f61a6 | refs/heads/master | 2021-06-27T20:03:53.657351 | 2019-04-25T19:48:29 | 2019-04-25T19:48:29 | 101,798,734 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,372 | cpp | 831Eredux.cpp | #include<iostream>
#include<fstream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<climits>
#include<algorithm>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#include<set>
#include<list>
using namespace std;
#define int long long int
#define mod 1000000007
#define pb push_back
#define mp make_pair
#define f first
#define s second
int n, m, a[100007];
int val1[100007], val2[100007];
int mapx[100007], tree[100007];
bool taken[100007];
vector <int> vs;
int summation(int id)
{
int sum = 0;
while(id)
{
sum += tree[id];
id -= (id & -id);
}
return sum;
}
void update(int id, int v)
{
while(id < 100007)
{
tree[id] += v;
id += (id & -id);
}
}
int nextid(int x)
{
int prev = upper_bound(vs.begin(), vs.end(), x) - vs.begin();
if(prev == vs.size())
return 0;
return vs[prev];
}
signed main()
{
int i, v, prev, u, newv, ans;
cin >> n;
for(i = 1; i <= n; i++)
{
cin >> a[i];
vs.pb(a[i]);
}
sort(vs.begin(), vs.end());
m = unique(vs.begin(), vs.end()) - vs.begin();
for(i = n; i >= 1; i--)
{
update(i, 1);
v = a[i];
u = nextid(v);
if(mapx[v])
val1[i] = mapx[v];
else if(mapx[u])
val2[i] = mapx[u];
mapx[v] = i;
}
for(i = 1; i <= n; i++)
{
v = a[i], u = nextid(v);
if(!val1[i])
val1[i] = mapx[v];
if(!val2[i] && u)
val2[i] = mapx[u];
}
// for(i = 1; i <= n; i++)
// cout << i << " " << val1[i] << " " << val2[i] << endl;
prev = ans = 0;
for(i = 1; i <= n; i++)
if(a[i] == vs[0])
{
prev = i;
ans += i;
update(i, -1);
taken[i] = 1;
break;
}
taken[0] = 1;
while(1)
{
newv = val1[prev];
if(newv == prev || taken[newv])
newv = val2[prev];
if(taken[newv])
break;
if(newv > prev)
ans = ans + summation(newv) - summation(prev);
else
ans = ans + summation(n) - summation(prev) + summation(newv);
prev = newv;
update(prev, -1);
taken[prev] = 1;
}
cout << ans << endl;
}
|
67db10434313edcc659c1780a71a22a873c3ad14 | 7776f88bc3bdb0342930dde82fb4edb4f0862818 | /entity/order_entity.cpp | 227e16f2d45971102bf7e9db271af89976af0f3e | [] | no_license | LYuanZhuo/orderSystem | 93858c65d7cf62ee7adb9b9b76e3eb3bda133ad3 | 03c4feac0ee32997d7bae1865d745cd28660c11d | refs/heads/master | 2021-08-07T11:01:21.218987 | 2020-05-11T09:34:02 | 2020-05-11T09:34:02 | 174,059,369 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,426 | cpp | order_entity.cpp | #include "order_entity.h"
Order_entity::Order_entity()
{
}
int Order_entity::getId(){
return this->id;
}
void Order_entity::setId(int id){
this->id = id;
}
int Order_entity::getTableId(){
return this->tableId;
}
void Order_entity::setTableId(int tableId){
this->tableId = tableId;
}
int Order_entity::getShopId(){
return this->shopId;
}
void Order_entity::setShopId(int shopId){
this->shopId = shopId;
}
int Order_entity::getPersonNum(){
return this->personNum;
}
void Order_entity::setPersonNum(int personNum){
this->personNum = personNum;
}
QString Order_entity::getOrderNum(){
return this->orderNum;
}
void Order_entity::setOrderNum(QString orderNum){
this->orderNum = orderNum;
}
bool Order_entity::getIsPay(){
return this->isPay;
}
void Order_entity::setIsPay(bool isPay){
this->isPay = isPay;
}
double Order_entity::getPrice(){
return this->price;
}
void Order_entity::setPrice(double price){
this->price = price;
}
QString Order_entity::getTime(){
return this->time;
}
void Order_entity::setTime(QString time){
this->time = time;
}
QString Order_entity::getPayTime(){
return this->payTime;
}
void Order_entity::setPayTime(QString payTime){
this->payTime = payTime;
}
QString Order_entity::getTableName(){
return this->tableName;
}
void Order_entity::setTableName(QString tableName){
this->tableName = tableName;
}
|
e5a37002cfafbb2432ab0b0bca23ec46ae997816 | 8bed1844554ed247bf90309789cbe18e0369b0f8 | /MainMenu.cpp | 35fe5378f437ba6790164607d09026f3c5fd1eee | [] | no_license | Anstow/oxen | 59cf316cf1de331abea1e67be9bd5bcb82a7cb00 | 7126740943ed9264102722e613edfb06b513be33 | refs/heads/master | 2020-05-18T21:42:19.437635 | 2013-07-17T19:48:33 | 2013-07-17T19:48:33 | 7,719,746 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,794 | cpp | MainMenu.cpp | #include <CEGUIEvent.h>
#include "MainMenu.h"
////////////////////////////////////////////////////////////////////////////////
MainMenu::MainMenu() {
m_bQuit = false;
m_FrameEvent = Ogre::FrameEvent();
try {
m_pMenu = CEGUI::WindowManager::getSingleton().loadWindowLayout("MainMenu.layout");
if (m_pMenu->isChild("Main/Exit")) {
m_pMenu->getChild("Main/Exit")->subscribeEvent(CEGUI::Window::EventMouseButtonUp,
CEGUI::Event::Subscriber(&MainMenu::onExit, this));
} else {
Framework::getSingletonPtr()->m_pLog->logMessage("Error, loading MainMenu no exit button found");
}
if (m_pMenu->isChild("Main/Game")) {
m_pMenu->getChild("Main/Game")->subscribeEvent(CEGUI::Window::EventMouseButtonUp,
CEGUI::Event::Subscriber(&MainMenu::playGame, this));
} else {
Framework::getSingletonPtr()->m_pLog->logMessage("Warning, loading MainMenu no Game button found");
}
} catch (CEGUI::Exception &e) {
OGRE_EXCEPT(Ogre::Exception::ERR_INTERNAL_ERROR, e.getMessage().c_str(), "Error Parsing Menu");
shutdown();
}
}
void MainMenu::createScene() {
if (m_pMenu) {
pushMenu(m_pMenu);
}
}
////////////////////////////////////////////////////////////////////////////////
void MainMenu::enter() {
Framework::getSingletonPtr()->m_pLog->logMessage("Entering MainMenu...");
m_bQuit = false;
// Create the SceneManager
m_pSceneMgr = Framework::getSingletonPtr()->m_pRoot->createSceneManager(Ogre::ST_GENERIC, "MenuSceneMgr");
m_pSceneMgr->setAmbientLight(Ogre::ColourValue(0.7f, 0.7f, 0.7f));
// Create the camera
m_pCamera = m_pSceneMgr->createCamera("MenuCamera");
m_pCamera->setPosition(Ogre::Vector3(0, 25, -50));
m_pCamera->lookAt(Ogre::Vector3(0, 0, 0));
m_pCamera->setNearClipDistance(1);
m_pCamera->setAspectRatio(Ogre::Real(Framework::getSingletonPtr()->m_pViewport->getActualWidth()) / Ogre::Real(Framework::getSingletonPtr()->m_pViewport->getActualHeight()));
Framework::getSingletonPtr()->m_pViewport->setCamera(m_pCamera);
Framework::getSingletonPtr()->m_pTrayMgr->destroyAllWidgets();
Framework::getSingletonPtr()->m_pTrayMgr->showFrameStats(OgreBites::TL_BOTTOMLEFT);
Framework::getSingletonPtr()->m_pTrayMgr->showLogo(OgreBites::TL_BOTTOMRIGHT);
createScene();
}
void MainMenu::exit() {
Framework::getSingletonPtr()->m_pLog->logMessage("Leaving MainMenu...");
// Remove the camera
m_pSceneMgr->destroyCamera(m_pCamera);
if (m_pSceneMgr) {
Framework::getSingletonPtr()->m_pRoot->destroySceneManager(m_pSceneMgr);
}
popMenu(m_pMenu);
// Remove tray data
Framework::getSingletonPtr()->m_pTrayMgr->clearAllTrays();
Framework::getSingletonPtr()->m_pTrayMgr->destroyAllWidgets();
Framework::getSingletonPtr()->m_pTrayMgr->setListener(0);
}
bool MainMenu::pause() {
m_pMenu->disable();
return true;
}
void MainMenu::resume() {
m_pMenu->enable();
}
void MainMenu::update(double timeSinceLastFrame) {
m_FrameEvent.timeSinceLastFrame = timeSinceLastFrame;
Framework::getSingletonPtr()->m_pTrayMgr->frameRenderingQueued(m_FrameEvent);
if(m_bQuit == true)
{
shutdown();
return;
}
}
////////////////////////////////////////////////////////////////////////////////
bool MainMenu::keyPressed(const OIS::KeyEvent &keyEventRef) {
if (Framework::getSingletonPtr()->m_pKeyboard->isKeyDown(OIS::KC_ESCAPE)) {
m_bQuit = true;
return true;
}
Framework::getSingletonPtr()->keyPressed(keyEventRef);
return true;
}
bool MainMenu::keyReleased(const OIS::KeyEvent &keyEventRef) {
Framework::getSingletonPtr()->keyReleased(keyEventRef);
return true;
}
bool MainMenu::mouseMoved(const OIS::MouseEvent &evt) {
if(Framework::getSingletonPtr()->m_pMenuMgr->InjectOISMouseMove(evt)) {
return true;
} else if (Framework::getSingletonPtr()->m_pTrayMgr->injectMouseMove(evt)) {
return true;
}
return true;
}
bool MainMenu::mousePressed(const OIS::MouseEvent &evt, OIS::MouseButtonID id) {
if(Framework::getSingletonPtr()->m_pMenuMgr->InjectOISMouseButtonDown(evt, id)) {
return true;
} else if(Framework::getSingletonPtr()->m_pTrayMgr->injectMouseDown(evt, id)) {
return true;
}
return true;
}
bool MainMenu::mouseReleased(const OIS::MouseEvent &evt, OIS::MouseButtonID id) {
if(Framework::getSingletonPtr()->m_pMenuMgr->InjectOISMouseButtonUp(evt, id)) {
return true;
} else if(Framework::getSingletonPtr()->m_pTrayMgr->injectMouseUp(evt, id)) {
return true;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
bool MainMenu::onExit(const CEGUI::EventArgs& e) {
m_bQuit = true;
return true;
}
bool MainMenu::playGame(const CEGUI::EventArgs& e) {
popAllAndPushAppState(m_pParent->findByName("GameState"));
Framework::getSingletonPtr()->m_pLog->logMessage("Transfer to game state");
return true;
}
|
577a627323dff1da9cff36a78482c57f5f8433ac | e9cc0edad84629928acb8f1cf11ae8aac8a54d2a | /code/Object/object.cpp | ee947f7a458f84360360f7640bcb6e901834174f | [] | no_license | mince22/NothingWorld | 914d41a286543f251f80f4570b8735433b092ab0 | 546422d561bee0ef94eabcdc273931646ef9705a | refs/heads/master | 2022-04-05T10:44:57.759351 | 2020-02-21T10:32:49 | 2020-02-21T10:32:49 | 234,732,609 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 509 | cpp | object.cpp | #pragma once
#include "object.hpp"
#include "../Interface/i_execute.hpp"
Object::Object(wstring name)
{
create();
Execute::add_object_pool(this);
}
void Object::create()
{
}
void Object::destroy()
{
for (auto component : components)
component.second->destroy();
}
void Object::add_object_pool()
{
}
const Object_ID Object::get_id() const
{
return id;
}
void Object::add_child(const Object & child) const
{
Object_ID child_id = child.get_id();
}
void Object::delete_child(Object & child)
{
}
|
9a2bf3c019b541bfd97600ecd51e1ae7e4998955 | 8ac6a26e0120598dc253efc3307c48a38c86fc85 | /include/RegistrationI.h | 138262ddd3a9ef6a3cfd2cbfc3c2620b6ab43276 | [] | no_license | systematic-chaos/cardroid-server-plus-plus | 3e997f0756989403b04a3d1a3eb24bc6fbc03b8f | e8872f3099fb3d869c9d42f03a7f5ec34279fa67 | refs/heads/master | 2021-01-10T03:15:10.721889 | 2016-01-03T22:37:01 | 2016-01-03T22:37:01 | 48,963,110 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 707 | h | RegistrationI.h | #ifndef REGISTRATIONI_H_
#define REGISTRATIONI_H_
#include <string>
#include "Registration.h"
#include "Util.h"
using namespace std;
namespace Cardroid {
namespace Network {
namespace Server {
class RegistrationI: public cardroid::network::zerocice::Registration {
public:
RegistrationI(
Cardroid::occi::StatelessConnectionPoolHolder* connectionPool);
bool registerNewUser(const cardroid::data::zerocice::UserTypPtr& newUser,
const std::string& password, const ::Ice::Current& = ::Ice::Current()) override;
private:
Cardroid::occi::StatelessConnectionPoolHolder* _connectionPool;
static const long long int serialVersionUID = 3502112289481155093L;
};
}
}
}
#endif /* REGISTRATIONI_H_ */
|
b9bc74219b7ac084318e8cb659e1733f31cfcb5d | 4b83840f50cc9a35d0c149a18bc5a214c568f53a | /SumanthKongani/week_3/ViralAdvertising.cpp | 8855610a1349cf6aedea48fd739c9f1309e8b307 | [
"MIT"
] | permissive | niteshbharti005101/Competitive-Coding | fd861a6fa5b3ca063da5d36384cf2b028f72846f | e58664096e7ed60652319a46677eb556ce072db6 | refs/heads/master | 2020-06-26T01:18:46.236385 | 2020-03-24T17:23:10 | 2020-03-24T17:23:10 | 199,478,594 | 1 | 8 | null | 2020-03-24T17:23:12 | 2019-07-29T15:24:50 | HTML | UTF-8 | C++ | false | false | 411 | cpp | ViralAdvertising.cpp | #include <bits/stdc++.h>
using namespace std;
int viralAdvertising(int n) {
int shared=5;
int liked;
int cumulative=0;
for(int i=0;i<n;++i){
liked=shared/2;
cumulative=cumulative+liked;
shared=liked*3;
}
cout<<"the number of people who liked the advertisement during the first "<<n<<" days:"<<cumulative;
return 0;
}
int main(){
int n;
cout<<"Enter number of days :";
cin>>n;
viralAdvertising(n);
return 0;
}
|
2b8145e63ed9c03a683f5cd816645cf960b829b7 | c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64 | /Engine/Plugins/Online/IOS/OnlineSubsystemIOS/Source/Private/TurnBasedEventListener.cpp | db6fc16dbde78a33a60b3e6c751674b227d91609 | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | windystrife/UnrealEngine_NVIDIAGameWorks | c3c7863083653caf1bc67d3ef104fb4b9f302e2a | b50e6338a7c5b26374d66306ebc7807541ff815e | refs/heads/4.18-GameWorks | 2023-03-11T02:50:08.471040 | 2022-01-13T20:50:29 | 2022-01-13T20:50:29 | 124,100,479 | 262 | 179 | MIT | 2022-12-16T05:36:38 | 2018-03-06T15:44:09 | C++ | UTF-8 | C++ | false | false | 2,583 | cpp | TurnBasedEventListener.cpp | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "OnlineSubsystemIOSPrivatePCH.h"
#include "TurnBasedEventListener.h"
@interface FTurnBasedEventListenerIOS()
{
FTurnBasedEventDelegate* _owner;
}
@end
@implementation FTurnBasedEventListenerIOS
- (id)initWithOwner:(FTurnBasedEventDelegate&)owner
{
if (self = [super init]) {
_owner = &owner;
#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
if ([GKLocalPlayer instancesRespondToSelector : @selector(registerListener:)] == YES)
#endif
{
[[GKLocalPlayer localPlayer] registerListener:self];
}
}
return self;
}
- (void)dealloc
{
#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
if ([GKLocalPlayer instancesRespondToSelector : @selector(unregisterListener:)] == YES)
#endif
{
[[GKLocalPlayer localPlayer] unregisterListener:self];
}
[super dealloc];
}
// GKChallengeListener
- (void)player:(GKPlayer *)player didCompleteChallenge:(GKChallenge *)challenge issuedByFriend:(GKPlayer *)friendPlayer {}
- (void)player:(GKPlayer *)player didReceiveChallenge:(GKChallenge *)challenge {}
- (void)player:(GKPlayer *)player issuedChallengeWasCompleted:(GKChallenge *)challenge byFriend:(GKPlayer *)friendPlayer {}
- (void)player:(GKPlayer *)player wantsToPlayChallenge:(GKChallenge *)challenge {}
// GKInviteEventListener
- (void)player:(GKPlayer *)player didAcceptInvite:(GKInvite *)invite {}
// GKInviteEventListener and GKTurnBasedEventListener
- (void)player:(GKPlayer *)player didRequestMatchWithPlayers:(NSArray *)playerIDsToInvite {}
// GKTurnBasedEventListener
- (void)player:(GKPlayer *)player matchEnded:(GKTurnBasedMatch *)match
{
if (_owner) {
_owner->OnMatchEnded([self getMatchIDFromMatch:match]);
}
}
- (void)player:(GKPlayer *)player receivedExchangeCancellation:(GKTurnBasedExchange *)exchange forMatch:(GKTurnBasedMatch *)match {}
- (void)player:(GKPlayer *)player receivedExchangeReplies:(NSArray *)replies forCompletedExchange:(GKTurnBasedExchange *)exchange forMatch:(GKTurnBasedMatch *)match {}
- (void)player:(GKPlayer *)player receivedExchangeRequest:(GKTurnBasedExchange *)exchange forMatch:(GKTurnBasedMatch *)match {}
- (void)player:(GKPlayer *)player receivedTurnEventForMatch:(GKTurnBasedMatch *)match didBecomeActive:(BOOL)didBecomeActive
{
if (_owner) {
_owner->OnMatchReceivedTurnEvent([self getMatchIDFromMatch:match], didBecomeActive, match);
}
}
- (FString)getMatchIDFromMatch:(GKTurnBasedMatch *)match
{
return FString::Printf(TEXT("%s"), UTF8_TO_TCHAR(match.matchID.UTF8String));
}
@end
|
d4bc9f69cb8db6b5f74131f4027a4dad8c058453 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5765824346324992_1/C++/smarterthanu1234/haircut.cpp | 8d8e916ec224821f2a2962a1d26aa64938ff92ea | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,999 | cpp | haircut.cpp | #include<iostream>
#include<algorithm>
#include<cstdio>
#include<string.h>
#include<climits>
using namespace std;
#define FOR(i,n) for(i=0;i<n;i++)
#define sint(i) scanf("%d",&i)
#define ss(s) scanf("%s",s)
#define pii pair<int,int>
#define ll long long
#define MAX 1000000000
#define MOD 1000000007
int main()
{
// freopen("test.in", "r", stdin);
//freopen("file.out", "w", stdout);
freopen("test.in", "r", stdin);
freopen("file.out", "w", stdout);
int test;
sint(test);
int n,b,i;
for(int t=1;t<=test;t++)
{
cout<<"Case #"<<t<<": ";
sint(b);
ll m[b];
ll n;
ll count1;
ll maxi=0;
scanf("%lld",&n);
FOR(i,b)
{
scanf("%lld",&m[i]);
maxi=max(maxi,m[i]);
}
if(n<=b)
cout<<n<<"\n";
else
{
n=n-b;
ll low=1;
ll high=n*maxi;
ll mid;
while(high>=low)
{
// cout<<high<<" "<<low<<"\n";
ll x=0,y=0;
mid=(high+low)/2;
FOR(i,b)
{
if(mid%m[i]==0)
{
y++;
x=x+(mid/m[i])-1;
}
else
x=x+(mid/m[i]);
}
if(x>=n)
{
high=mid-1;
}
else if((x+y)<n)
{
low=mid+1;
}
else
{
count1=0;
n=n-x;
FOR(i,b)
{
if(mid%m[i]==0)
{
count1++;
}
if(count1==n)
{
cout<<i+1<<"\n";
goto out;
}
}
}
}
}
out:
;
}
return 0;
}
|
11fc9c604a22e1f1b6bf6dbaa8419e7f1f904c1c | 2cc63e61904c0b821b88687cbc7c20f4ffeb28cb | /1140 - Flores Florescem da França.cpp | 40a26e0c86959ee1b5a5e6b5064ec5f30e3d300a | [] | no_license | lawrencesilva/URI | 47557fbb007ccbfb00150d2cd503e8ab9bd0973a | 1db51a14e7072099351e205abb691b191fb7d681 | refs/heads/master | 2020-03-24T02:08:58.630761 | 2018-07-26T11:12:00 | 2018-07-26T11:12:00 | 142,364,470 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 697 | cpp | 1140 - Flores Florescem da França.cpp | #include <iostream>
#include <cstdio>
#include <string>
#include <ctype.h>
using namespace std;
int main() {
string frase;
char letra;
bool falso = false;
getline(cin, frase);
while(frase != "*") {
for(int i = 0; frase[i] != '\0'; i++) {
if(i == 0)
letra = toupper(frase[i]);
else if(frase[i] == ' ') {
frase[i + 1] = toupper(frase[i + 1]);
if(frase[i + 1] != letra) {
falso = true;
break;
}
}
}
if(falso)
cout << "N" << endl;
else
cout << "Y" << endl;
falso = false;
getline(cin, frase);
}
return 0;
} |
b3b43f3003fdfaf9f6d191d5f43af624c4f9f63f | 0bcd128368e2de959ca648960ffd7944067fcf27 | /src/core/SkRecorder.h | b11c2a2714e577a05a8e37411bfc49a0eed061b6 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | google/skia | ac6e39179cd33cf0c8a46d29c1a70bf78b4d74ee | bf6b239838d3eb56562fffd0856f4047867ae771 | refs/heads/main | 2023-08-31T21:03:04.620734 | 2023-08-31T18:24:15 | 2023-08-31T20:20:26 | 15,773,229 | 8,064 | 1,487 | BSD-3-Clause | 2023-09-11T13:42:07 | 2014-01-09T17:09:57 | C++ | UTF-8 | C++ | false | false | 6,367 | h | SkRecorder.h | /*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkRecorder_DEFINED
#define SkRecorder_DEFINED
#include "include/core/SkCanvasVirtualEnforcer.h"
#include "include/core/SkColor.h"
#include "include/core/SkM44.h"
#include "include/core/SkRefCnt.h"
#include "include/core/SkSamplingOptions.h"
#include "include/core/SkScalar.h"
#include "include/core/SkTypes.h"
#include "include/private/base/SkNoncopyable.h"
#include "include/private/base/SkTDArray.h"
#include "include/utils/SkNoDrawCanvas.h"
#include "src/core/SkBigPicture.h"
#include <cstddef>
#include <memory>
#include <utility>
class SkBlender;
class SkData;
class SkDrawable;
class SkImage;
class SkMatrix;
class SkMesh;
class SkPaint;
class SkPath;
class SkPicture;
class SkRRect;
class SkRecord;
class SkRegion;
class SkShader;
class SkSurface;
class SkSurfaceProps;
class SkTextBlob;
class SkVertices;
enum class SkBlendMode;
enum class SkClipOp;
struct SkDrawShadowRec;
struct SkImageInfo;
struct SkPoint;
struct SkRSXform;
struct SkRect;
namespace sktext {
class GlyphRunList;
namespace gpu { class Slug; }
}
class SkDrawableList : SkNoncopyable {
public:
SkDrawableList() {}
~SkDrawableList();
int count() const { return fArray.size(); }
SkDrawable* const* begin() const { return fArray.begin(); }
SkDrawable* const* end() const { return fArray.end(); }
void append(SkDrawable* drawable);
// Return a new or ref'd array of pictures that were snapped from our drawables.
SkBigPicture::SnapshotArray* newDrawableSnapshot();
private:
SkTDArray<SkDrawable*> fArray;
};
// SkRecorder provides an SkCanvas interface for recording into an SkRecord.
class SkRecorder final : public SkCanvasVirtualEnforcer<SkNoDrawCanvas> {
public:
// Does not take ownership of the SkRecord.
SkRecorder(SkRecord*, int width, int height); // TODO: remove
SkRecorder(SkRecord*, const SkRect& bounds);
void reset(SkRecord*, const SkRect& bounds);
size_t approxBytesUsedBySubPictures() const { return fApproxBytesUsedBySubPictures; }
SkDrawableList* getDrawableList() const { return fDrawableList.get(); }
std::unique_ptr<SkDrawableList> detachDrawableList() { return std::move(fDrawableList); }
// Make SkRecorder forget entirely about its SkRecord*; all calls to SkRecorder will fail.
void forgetRecord();
void willSave() override;
SaveLayerStrategy getSaveLayerStrategy(const SaveLayerRec&) override;
bool onDoSaveBehind(const SkRect*) override;
void willRestore() override {}
void didRestore() override;
void didConcat44(const SkM44&) override;
void didSetM44(const SkM44&) override;
void didScale(SkScalar, SkScalar) override;
void didTranslate(SkScalar, SkScalar) override;
void onDrawDRRect(const SkRRect&, const SkRRect&, const SkPaint&) override;
void onDrawDrawable(SkDrawable*, const SkMatrix*) override;
void onDrawTextBlob(const SkTextBlob* blob,
SkScalar x,
SkScalar y,
const SkPaint& paint) override;
void onDrawSlug(const sktext::gpu::Slug* slug) override;
void onDrawGlyphRunList(
const sktext::GlyphRunList& glyphRunList, const SkPaint& paint) override;
void onDrawPatch(const SkPoint cubics[12], const SkColor colors[4],
const SkPoint texCoords[4], SkBlendMode,
const SkPaint& paint) override;
void onDrawPaint(const SkPaint&) override;
void onDrawBehind(const SkPaint&) override;
void onDrawPoints(PointMode, size_t count, const SkPoint pts[], const SkPaint&) override;
void onDrawRect(const SkRect&, const SkPaint&) override;
void onDrawRegion(const SkRegion&, const SkPaint&) override;
void onDrawOval(const SkRect&, const SkPaint&) override;
void onDrawArc(const SkRect&, SkScalar, SkScalar, bool, const SkPaint&) override;
void onDrawRRect(const SkRRect&, const SkPaint&) override;
void onDrawPath(const SkPath&, const SkPaint&) override;
void onDrawImage2(const SkImage*, SkScalar, SkScalar, const SkSamplingOptions&,
const SkPaint*) override;
void onDrawImageRect2(const SkImage*, const SkRect&, const SkRect&, const SkSamplingOptions&,
const SkPaint*, SrcRectConstraint) override;
void onDrawImageLattice2(const SkImage*, const Lattice&, const SkRect&, SkFilterMode,
const SkPaint*) override;
void onDrawAtlas2(const SkImage*, const SkRSXform[], const SkRect[], const SkColor[], int,
SkBlendMode, const SkSamplingOptions&, const SkRect*, const SkPaint*) override;
void onDrawVerticesObject(const SkVertices*, SkBlendMode, const SkPaint&) override;
void onDrawMesh(const SkMesh&, sk_sp<SkBlender>, const SkPaint&) override;
void onDrawShadowRec(const SkPath&, const SkDrawShadowRec&) override;
void onClipRect(const SkRect& rect, SkClipOp, ClipEdgeStyle) override;
void onClipRRect(const SkRRect& rrect, SkClipOp, ClipEdgeStyle) override;
void onClipPath(const SkPath& path, SkClipOp, ClipEdgeStyle) override;
void onClipShader(sk_sp<SkShader>, SkClipOp) override;
void onClipRegion(const SkRegion& deviceRgn, SkClipOp) override;
void onResetClip() override;
void onDrawPicture(const SkPicture*, const SkMatrix*, const SkPaint*) override;
void onDrawAnnotation(const SkRect&, const char[], SkData*) override;
void onDrawEdgeAAQuad(const SkRect&, const SkPoint[4], QuadAAFlags, const SkColor4f&,
SkBlendMode) override;
void onDrawEdgeAAImageSet2(const ImageSetEntry[], int count, const SkPoint[], const SkMatrix[],
const SkSamplingOptions&, const SkPaint*,
SrcRectConstraint) override;
sk_sp<SkSurface> onNewSurface(const SkImageInfo&, const SkSurfaceProps&) override;
private:
template <typename T>
T* copy(const T*);
template <typename T>
T* copy(const T[], size_t count);
template<typename T, typename... Args>
void append(Args&&...);
size_t fApproxBytesUsedBySubPictures;
SkRecord* fRecord;
std::unique_ptr<SkDrawableList> fDrawableList;
};
#endif//SkRecorder_DEFINED
|
01d1b70b8a41626aa12b6537fee53ed1663b2a06 | bb38c44037a99d0a12a12d92059678f2faebbc80 | /src/common/backend/pgxc_single/locator/locator.cpp | 088e4f73774ddfe57158d814dfed26c0c3e5d29b | [
"LicenseRef-scancode-mulanpsl-2.0-en",
"LicenseRef-scancode-unknown-license-reference",
"PostgreSQL",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"LicenseRef-scancode-unicode",
"LicenseRef-scancode-warranty-disclaimer",
"curl",
"GPL-1.0-or-later",
"LGPL-2.1-or-later",
"LGPL-2.1-only",
"CC-BY-4.0",
"LicenseRef-scancode-protobuf",
"OpenSSL",
"LicenseRef-scancode-generic-export-compliance",
"X11-distribute-modifications-variant",
"LicenseRef-scancode-other-permissive",
"MIT",
"NCSA",
"Python-2.0",
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-ssleay-windows",
"CC-BY-3.0",
"LicenseRef-scancode-other-copyleft",
"GPL-2.0-only",
"BSL-1.0",
"Apache-2.0",
"LGPL-2.0-only",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"Zlib"
] | permissive | opengauss-mirror/openGauss-server | a9c5a62908643492347830826c56da49f0942796 | 310e84631c68c8bf37b004148b66f94064f701e4 | refs/heads/master | 2023-07-26T19:29:12.495484 | 2023-07-17T12:23:32 | 2023-07-17T12:23:32 | 276,117,477 | 591 | 208 | MulanPSL-2.0 | 2023-04-28T12:30:18 | 2020-06-30T14:08:59 | C++ | UTF-8 | C++ | false | false | 46,021 | cpp | locator.cpp | /* -------------------------------------------------------------------------
*
* locator.c
* Functions that help manage table location information such as
* partitioning and replication information.
*
*
*
* Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
* Portions Copyright (c) 2010-2012 Postgres-XC Development Group
*
*
* IDENTIFICATION
* $$
*
* -------------------------------------------------------------------------
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "postgres.h"
#include "knl/knl_variable.h"
#include "access/skey.h"
#include "access/gtm.h"
#include "access/tableam.h"
#include "access/relscan.h"
#include "catalog/indexing.h"
#include "catalog/pg_type.h"
#include "miscadmin.h"
#include "nodes/pg_list.h"
#include "nodes/nodeFuncs.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
#include "utils/fmgroids.h"
#include "utils/lsyscache.h"
#include "utils/rel.h"
#include "utils/rel_gs.h"
#include "utils/relcache.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
#include "nodes/nodes.h"
#include "optimizer/clauses.h"
#include "parser/parse_coerce.h"
#include "postmaster/autovacuum.h"
#include "pgxc/nodemgr.h"
#include "pgxc/locator.h"
#include "pgxc/pgxc.h"
#include "pgxc/pgxcnode.h"
#include "catalog/pgxc_group.h"
#include "catalog/pgxc_class.h"
#include "catalog/pgxc_node.h"
#include "catalog/pgxc_slice.h"
#include "catalog/namespace.h"
#include "catalog/pg_namespace.h"
#include "access/hash.h"
#include "optimizer/streamplan.h"
#include "optimizer/prep.h"
#include "pgxc/poolmgr.h"
#include "pgxc/poolutils.h"
#include "utils/elog.h"
#pragma GCC diagnostic ignored "-Wunused-function"
static uint2* tryGetBucketMap(const char* groupname, char* relname, bool isOtherTempNamespace, int *bucketlen);
extern Const* makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid);
static const unsigned int xc_mod_m[] = {0x00000000,
0x55555555,
0x33333333,
0xc71c71c7,
0x0f0f0f0f,
0xc1f07c1f,
0x3f03f03f,
0xf01fc07f,
0x00ff00ff,
0x07fc01ff,
0x3ff003ff,
0xffc007ff,
0xff000fff,
0xfc001fff,
0xf0003fff,
0xc0007fff,
0x0000ffff,
0x0001ffff,
0x0003ffff,
0x0007ffff,
0x000fffff,
0x001fffff,
0x003fffff,
0x007fffff,
0x00ffffff,
0x01ffffff,
0x03ffffff,
0x07ffffff,
0x0fffffff,
0x1fffffff,
0x3fffffff,
0x7fffffff};
static const unsigned int xc_mod_q[][6] = {{0, 0, 0, 0, 0, 0},
{16, 8, 4, 2, 1, 1},
{16, 8, 4, 2, 2, 2},
{15, 6, 3, 3, 3, 3},
{16, 8, 4, 4, 4, 4},
{15, 5, 5, 5, 5, 5},
{12, 6, 6, 6, 6, 6},
{14, 7, 7, 7, 7, 7},
{16, 8, 8, 8, 8, 8},
{9, 9, 9, 9, 9, 9},
{10, 10, 10, 10, 10, 10},
{11, 11, 11, 11, 11, 11},
{12, 12, 12, 12, 12, 12},
{13, 13, 13, 13, 13, 13},
{14, 14, 14, 14, 14, 14},
{15, 15, 15, 15, 15, 15},
{16, 16, 16, 16, 16, 16},
{17, 17, 17, 17, 17, 17},
{18, 18, 18, 18, 18, 18},
{19, 19, 19, 19, 19, 19},
{20, 20, 20, 20, 20, 20},
{21, 21, 21, 21, 21, 21},
{22, 22, 22, 22, 22, 22},
{23, 23, 23, 23, 23, 23},
{24, 24, 24, 24, 24, 24},
{25, 25, 25, 25, 25, 25},
{26, 26, 26, 26, 26, 26},
{27, 27, 27, 27, 27, 27},
{28, 28, 28, 28, 28, 28},
{29, 29, 29, 29, 29, 29},
{30, 30, 30, 30, 30, 30},
{31, 31, 31, 31, 31, 31}};
static const unsigned int xc_mod_r[][6] = {{0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000},
{0x0000ffff, 0x000000ff, 0x0000000f, 0x00000003, 0x00000001, 0x00000001},
{0x0000ffff, 0x000000ff, 0x0000000f, 0x00000003, 0x00000003, 0x00000003},
{0x00007fff, 0x0000003f, 0x00000007, 0x00000007, 0x00000007, 0x00000007},
{0x0000ffff, 0x000000ff, 0x0000000f, 0x0000000f, 0x0000000f, 0x0000000f},
{0x00007fff, 0x0000001f, 0x0000001f, 0x0000001f, 0x0000001f, 0x0000001f},
{0x00000fff, 0x0000003f, 0x0000003f, 0x0000003f, 0x0000003f, 0x0000003f},
{0x00003fff, 0x0000007f, 0x0000007f, 0x0000007f, 0x0000007f, 0x0000007f},
{0x0000ffff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff},
{0x000001ff, 0x000001ff, 0x000001ff, 0x000001ff, 0x000001ff, 0x000001ff},
{0x000003ff, 0x000003ff, 0x000003ff, 0x000003ff, 0x000003ff, 0x000003ff},
{0x000007ff, 0x000007ff, 0x000007ff, 0x000007ff, 0x000007ff, 0x000007ff},
{0x00000fff, 0x00000fff, 0x00000fff, 0x00000fff, 0x00000fff, 0x00000fff},
{0x00001fff, 0x00001fff, 0x00001fff, 0x00001fff, 0x00001fff, 0x00001fff},
{0x00003fff, 0x00003fff, 0x00003fff, 0x00003fff, 0x00003fff, 0x00003fff},
{0x00007fff, 0x00007fff, 0x00007fff, 0x00007fff, 0x00007fff, 0x00007fff},
{0x0000ffff, 0x0000ffff, 0x0000ffff, 0x0000ffff, 0x0000ffff, 0x0000ffff},
{0x0001ffff, 0x0001ffff, 0x0001ffff, 0x0001ffff, 0x0001ffff, 0x0001ffff},
{0x0003ffff, 0x0003ffff, 0x0003ffff, 0x0003ffff, 0x0003ffff, 0x0003ffff},
{0x0007ffff, 0x0007ffff, 0x0007ffff, 0x0007ffff, 0x0007ffff, 0x0007ffff},
{0x000fffff, 0x000fffff, 0x000fffff, 0x000fffff, 0x000fffff, 0x000fffff},
{0x001fffff, 0x001fffff, 0x001fffff, 0x001fffff, 0x001fffff, 0x001fffff},
{0x003fffff, 0x003fffff, 0x003fffff, 0x003fffff, 0x003fffff, 0x003fffff},
{0x007fffff, 0x007fffff, 0x007fffff, 0x007fffff, 0x007fffff, 0x007fffff},
{0x00ffffff, 0x00ffffff, 0x00ffffff, 0x00ffffff, 0x00ffffff, 0x00ffffff},
{0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff},
{0x03ffffff, 0x03ffffff, 0x03ffffff, 0x03ffffff, 0x03ffffff, 0x03ffffff},
{0x07ffffff, 0x07ffffff, 0x07ffffff, 0x07ffffff, 0x07ffffff, 0x07ffffff},
{0x0fffffff, 0x0fffffff, 0x0fffffff, 0x0fffffff, 0x0fffffff, 0x0fffffff},
{0x1fffffff, 0x1fffffff, 0x1fffffff, 0x1fffffff, 0x1fffffff, 0x1fffffff},
{0x3fffffff, 0x3fffffff, 0x3fffffff, 0x3fffffff, 0x3fffffff, 0x3fffffff},
{0x7fffffff, 0x7fffffff, 0x7fffffff, 0x7fffffff, 0x7fffffff, 0x7fffffff}};
/*
* GetPreferredReplicationNode
* Pick any Datanode from given list, however fetch a preferred node first.
*/
List* GetPreferredReplicationNode(List* relNodes)
{
#ifndef ENABLE_MULTIPLE_NODES
Assert(false);
DISTRIBUTED_FEATURE_NOT_SUPPORTED();
return NIL;
#else
ListCell* item = NULL;
int nodeid = -1;
if (list_length(relNodes) <= 0)
elog(ERROR, "a list of nodes should have at least one node");
foreach (item, relNodes) {
int cnt_nodes;
for (cnt_nodes = 0; cnt_nodes < num_preferred_data_nodes && nodeid < 0; cnt_nodes++) {
if (PGXCNodeGetNodeId(preferred_data_node[cnt_nodes], PGXC_NODE_DATANODE) == lfirst_int(item))
nodeid = lfirst_int(item);
}
if (nodeid >= 0)
break;
}
if (nodeid < 0)
return list_make1_int(linitial_int(relNodes));
return list_make1_int(nodeid);
#endif
}
bool IsFunctionShippable(Oid foid) {
DISTRIBUTED_FEATURE_NOT_SUPPORTED();
return false;
}
/*
* compute_modulo
* This function performs modulo in an optimized way
* It optimizes modulo of any positive number by
* 1,2,3,4,7,8,15,16,31,32,63,64 and so on
* for the rest of the denominators it uses % operator
* The optimized algos have been taken from
* http://www-graphics.stanford.edu/~seander/bithacks.html
*/
int compute_modulo(unsigned int numerator, unsigned int denominator)
{
#ifndef ENABLE_MULTIPLE_NODES
DISTRIBUTED_FEATURE_NOT_SUPPORTED();
return 0;
#else
unsigned int d;
unsigned int m;
unsigned int s;
unsigned int mask;
int k;
unsigned int q, r;
if (numerator == 0)
return 0;
/* Check if denominator is a power of 2 */
if ((denominator & (denominator - 1)) == 0)
return numerator & (denominator - 1);
/* Check if (denominator+1) is a power of 2 */
d = denominator + 1;
if ((d & (d - 1)) == 0) {
/* Which power of 2 is this number */
s = 0;
mask = 0x01;
for (k = 0; k < 32; k++) {
if ((d & mask) == mask)
break;
s++;
mask = mask << 1;
}
m = (numerator & xc_mod_m[s]) + ((numerator >> s) & xc_mod_m[s]);
for (q = 0, r = 0; m > denominator; q++, r++)
m = (m >> xc_mod_q[s][q]) + (m & xc_mod_r[s][r]);
m = (m == denominator) ? 0 : m;
return m;
}
return numerator % denominator;
#endif
}
/*
* get_node_from_modulo - determine node based on modulo
*
* compute_modulo
*/
int get_node_from_modulo(int modulo, List* nodeList)
{
if (nodeList == NIL || modulo >= list_length(nodeList) || modulo < 0) {
Assert(0);
ereport(ERROR,
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
errmsg("Modulo value: %d out of range %d.\n", modulo, list_length(nodeList))));
}
return list_nth_int(nodeList, modulo);
}
/*
* GetRelationDistribColumn
* Return hash column name for relation or NULL if relation is not distributed.
*/
List* GetRelationDistribColumn(RelationLocInfo* locInfo)
{
#ifndef ENABLE_MULTIPLE_NODES
Assert(false);
DISTRIBUTED_FEATURE_NOT_SUPPORTED();
return NIL;
#else
#error You SHOULD call the same name function in distribute directory.
#endif
}
/*
* IsDistribColumn
* Return whether column for relation is used for distribution or not.
*/
bool IsDistribColumn(Oid relid, AttrNumber attNum)
{
#ifndef ENABLE_MULTIPLE_NODES
Assert(false);
DISTRIBUTED_FEATURE_NOT_SUPPORTED();
return false;
#else
RelationLocInfo* locInfo = GetRelationLocInfo(relid);
/* No locator info, so leave */
if (!locInfo)
return false;
/* No distribution column if relation is not distributed with a key */
if (!IsRelationDistributedByValue(locInfo))
return false;
/* Finally check if attribute is distributed */
return locInfo->partAttrNum == attNum;
#endif
}
/*
* IsTypeDistributable
* Returns whether the data type is distributable using a column value.
*/
bool IsTypeDistributable(Oid col_type)
{
/*
* all the distributable types here should be matched with a "bucketXXXX" function
* in hashfunc.cpp and the functions should be registered in pg_proc.h too.
*/
if (col_type == INT8OID || col_type == INT1OID || col_type == INT2OID || col_type == INT4OID ||
col_type == NUMERICOID || col_type == CHAROID || col_type == BPCHAROID || col_type == VARCHAROID ||
col_type == NVARCHAR2OID || col_type == DATEOID || col_type == TIMEOID || col_type == TIMESTAMPOID ||
col_type == TIMESTAMPTZOID || col_type == INTERVALOID || col_type == TIMETZOID ||
col_type == SMALLDATETIMEOID || col_type == TEXTOID || col_type == CLOBOID || col_type == UUIDOID)
return true;
// following types are not allowed as distribution column
// seldom used, non-standard, imprecise or large data types
if (g_instance.attr.attr_common.support_extended_features && (col_type == OIDOID || col_type == ABSTIMEOID ||
col_type == RELTIMEOID || col_type == CASHOID || col_type == BYTEAOID || col_type == RAWOID ||
col_type == BOOLOID || col_type == NAMEOID || col_type == INT2VECTOROID || col_type == OIDVECTOROID ||
col_type == FLOAT4OID || col_type == FLOAT8OID || col_type == BYTEAWITHOUTORDERWITHEQUALCOLOID))
return true;
return false;
}
bool IsTypeDistributableForSlice(Oid colType)
{
switch (colType) {
case INT2OID:
case INT4OID:
case INT8OID:
case NUMERICOID:
return true;
case CHAROID:
case BPCHAROID:
case VARCHAROID:
case NVARCHAR2OID:
case TEXTOID:
return true;
case DATEOID:
case TIMESTAMPOID:
case TIMESTAMPTZOID:
return true;
default:
return false;
}
}
/*
* GetRoundRobinNode
* Update the round robin node for the relation.
* PGXC - may not want to bother with locking here, we could track
* these in the session memory context instead...
*/
int GetRoundRobinNode(Oid relid)
{
int ret_node;
Relation rel = relation_open(relid, AccessShareLock);
Assert(rel->rd_locator_info->locatorType == LOCATOR_TYPE_REPLICATED ||
rel->rd_locator_info->locatorType == LOCATOR_TYPE_RROBIN);
ret_node = lfirst_int(rel->rd_locator_info->roundRobinNode);
/* Move round robin indicator to next node */
if (rel->rd_locator_info->roundRobinNode->next != NULL)
rel->rd_locator_info->roundRobinNode = rel->rd_locator_info->roundRobinNode->next;
else
/* reset to first one */
rel->rd_locator_info->roundRobinNode = rel->rd_locator_info->nodeList->head;
relation_close(rel, AccessShareLock);
return ret_node;
}
/*
* IsTableDistOnPrimary
* Does the table distribution list include the primary node?
*/
bool IsTableDistOnPrimary(RelationLocInfo* rel_loc_info)
{
ListCell* item = NULL;
if (!OidIsValid(u_sess->pgxc_cxt.primary_data_node) || rel_loc_info == NULL ||
list_length(rel_loc_info->nodeList) == 0)
return false;
foreach (item, rel_loc_info->nodeList) {
if (PGXCNodeGetNodeId(u_sess->pgxc_cxt.primary_data_node, PGXC_NODE_DATANODE) == lfirst_int(item))
return true;
}
return false;
}
/*
* IsLocatorInfoEqual
* Check equality of given locator information
*/
bool IsLocatorInfoEqual(RelationLocInfo* locInfo1, RelationLocInfo* locInfo2)
{
#ifndef ENABLE_MULTIPLE_NODES
Assert(false);
DISTRIBUTED_FEATURE_NOT_SUPPORTED();
return false;
#else
List* nodeList1 = NULL;
List* nodeList2 = NULL;
Assert(locInfo1 && locInfo2);
nodeList1 = locInfo1->nodeList;
nodeList2 = locInfo2->nodeList;
/* Same relation? */
if (locInfo1->relid != locInfo2->relid)
return false;
/* Same locator type? */
if (locInfo1->locatorType != locInfo2->locatorType)
return false;
/* Same attribute number? */
if (locInfo1->partAttrNum != locInfo2->partAttrNum)
return false;
/* Same node list? */
if (list_difference_int(nodeList1, nodeList2) != NIL || list_difference_int(nodeList2, nodeList1) != NIL)
return false;
/* Everything is equal */
return true;
#endif
}
bool IsSliceInfoEqualByOid(Oid tabOid1, Oid tabOid2)
{
Assert(false);
DISTRIBUTED_FEATURE_NOT_SUPPORTED();
return false;
}
/*
* InitBuckets
*
* Set buckets_ptr of RelationLocInfo
*/
void InitBuckets(RelationLocInfo* rel_loc_info, Relation relation)
{
Relation rel = relation;
if (rel == NULL) {
rel = relation_open(rel_loc_info->relid, AccessShareLock);
}
if (rel->rd_rel->relpersistence == RELPERSISTENCE_TEMP) {
rel_loc_info->buckets_ptr = tryGetBucketMap(NameStr(rel_loc_info->gname),
NameStr(rel->rd_rel->relname),
isOtherTempNamespace(rel->rd_rel->relnamespace),
&rel_loc_info->buckets_cnt);
} else {
rel_loc_info->buckets_ptr = BucketMapCacheGetBucketmap(NameStr(rel_loc_info->gname),
&rel_loc_info->buckets_cnt);
}
if (relation == NULL) {
relation_close(rel, AccessShareLock);
}
}
/*
* GetRelationNodes
*
* Get list of relation nodes
* If the table is replicated and we are reading, we can just pick one.
* If the table is partitioned, we apply partitioning column value, if possible.
*
* If the relation is partitioned, partValue will be applied if present
* (indicating a value appears for partitioning column), otherwise it
* is ignored.
*
* preferredNodes is only used when for replicated tables. If set, it will
* use one of the nodes specified if the table is replicated on it.
* This helps optimize for avoiding introducing additional nodes into the
* transaction.
*
* The returned List is a copy, so it should be freed when finished.
*/
ExecNodes* GetRelationNodes(RelationLocInfo* rel_loc_info, Datum* values, const bool* nulls, Oid* attr,
List* idx_dist_by_col, RelationAccessType accessType, bool needDistribution, bool use_bucketmap)
{
#ifndef ENABLE_MULTIPLE_NODES
Assert(false);
DISTRIBUTED_FEATURE_NOT_SUPPORTED();
return NULL;
#else
ExecNodes* exec_nodes = NULL;
long hashValue;
int modulo;
int nodeIndex;
if (rel_loc_info == NULL)
return NULL;
exec_nodes = makeNode(ExecNodes);
exec_nodes->baselocatortype = rel_loc_info->locatorType;
exec_nodes->accesstype = accessType;
exec_nodes->bucketid = INVALID_BUCKET_ID;
switch (rel_loc_info->locatorType) {
case LOCATOR_TYPE_REPLICATED:
/*
* When intention is to read from replicated table, return all the
* nodes so that planner can choose one depending upon the rest of
* the JOIN tree. But while reading with update lock, we need to
* read from the primary node (if exists) so as to avoid the
* deadlock.
* For write access set primary node (if exists).
*/
exec_nodes->nodeList = list_copy(rel_loc_info->nodeList);
if (accessType == RELATION_ACCESS_UPDATE || accessType == RELATION_ACCESS_INSERT) {
/* we need to write to all synchronously */
/*
* Write to primary node first, to reduce chance of a deadlock
* on replicated tables. If -1, do not use primary copy.
*/
if (IsTableDistOnPrimary(rel_loc_info) && exec_nodes->nodeList &&
list_length(exec_nodes->nodeList) > 1) /* make sure more than 1 */
{
exec_nodes->primarynodelist =
list_make1_int(PGXCNodeGetNodeId(primary_data_node, PGXC_NODE_DATANODE));
exec_nodes->nodeList =
list_delete_int(exec_nodes->nodeList, PGXCNodeGetNodeId(primary_data_node, PGXC_NODE_DATANODE));
}
} else if (accessType == RELATION_ACCESS_READ_FOR_UPDATE && IsTableDistOnPrimary(rel_loc_info)) {
/*
* We should ensure row is locked on the primary node to
* avoid distributed deadlock if updating the same row
* concurrently
*/
exec_nodes->nodeList = list_make1_int(PGXCNodeGetNodeId(primary_data_node, PGXC_NODE_DATANODE));
}
break;
case LOCATOR_TYPE_HASH:
case LOCATOR_TYPE_MODULO:
if (!isValueNull) {
hashValue = compute_hash(typeOfValueForDistCol, valueForDistCol, rel_loc_info->locatorType);
modulo = compute_modulo(abs(hashValue), list_length(rel_loc_info->nodeList));
nodeIndex = get_node_from_modulo(modulo, rel_loc_info->nodeList);
exec_nodes->nodeList = list_make1_int(nodeIndex);
exec_nodes->bucketid = compute_modulo(abs((int)hashValue), BUCKETDATALEN);
} else {
if (accessType == RELATION_ACCESS_INSERT)
/* Insert NULL to first node */
exec_nodes->nodeList = list_make1_int(linitial_int(rel_loc_info->nodeList));
else
exec_nodes->nodeList = list_copy(rel_loc_info->nodeList);
}
break;
case LOCATOR_TYPE_RROBIN:
/*
* round robin, get next one in case of insert. If not insert, all
* node needed
*/
if (accessType == RELATION_ACCESS_INSERT)
exec_nodes->nodeList = list_make1_int(GetRoundRobinNode(rel_loc_info->relid));
else
exec_nodes->nodeList = list_copy(rel_loc_info->nodeList);
break;
default:
ereport(ERROR, (errmsg("Error: no such supported locator type: %c\n", rel_loc_info->locatorType)));
break;
}
return exec_nodes;
#endif
}
/*
* GetRelationNodesByQuals
* A wrapper around GetRelationNodes to reduce the node list by looking at the
* quals. varno is assumed to be the varno of reloid inside the quals. No check
* is made to see if that's correct.
*/
ExecNodes* GetRelationNodesByQuals(void* query_arg, Oid reloid, Index varno, Node* quals, RelationAccessType relaccess,
ParamListInfo boundParams, bool useDynamicReduce)
{
Query* query = (Query*)query_arg;
RelationLocInfo* rel_loc_info = GetRelationLocInfo(reloid);
Expr* distcol_expr = NULL;
Expr* distcol_expr_original = NULL;
ExecNodes* exec_nodes = NULL;
ListCell* cell = NULL;
AttrNumber attnum;
Datum* distcol_value = NULL;
bool* distcol_isnull = NULL;
Oid* distcol_type = NULL;
List* idx_dist = NULL;
/* datanodes reduction where there are params */
List* distcol_expr_list = NULL;
List* bucket_expr_list = NULL;
bool needDynamicReduce = false;
int len = 0;
int i = 0;
if (rel_loc_info == NULL)
return NULL;
/*
* If the table distributed by value, check if we can reduce the Datanodes
* by looking at the qualifiers for this relation
*/
if (IsRelationDistributedByValue(rel_loc_info)) {
len = list_length(rel_loc_info->partAttrNum);
distcol_value = (Datum*)palloc(len * sizeof(Datum));
distcol_isnull = (bool*)palloc(len * sizeof(bool));
distcol_type = (Oid*)palloc(len * sizeof(Oid));
foreach (cell, rel_loc_info->partAttrNum) {
attnum = lfirst_int(cell);
Oid disttype = get_atttype(reloid, attnum);
int32 disttypmod = get_atttypmod(reloid, attnum);
distcol_expr_original = distcol_expr = pgxc_find_distcol_expr(query, varno, attnum, quals);
/*
* If the type of expression used to find the Datanode, is not same as
* the distribution column type, try casting it. This is same as what
* will happen in case of inserting that type of expression value as the
* distribution column value.
*/
if (distcol_expr != NULL) {
Oid exprtype = exprType((Node*)distcol_expr);
/*
* To variable length data type, here need not consider it's typmode because hash value of the same
* value must be the same.
*
* If consider typmode that may lead to ERROR rather than return 0 row result.
*
* For example:
* create table test(a numeric(19, 18));
* select * from test where 10 = a;
*
* '10' can not be converted to numeric(19, 18), that will lead to ERROR.
* So we add this branch to handle this problem.
*
*/
if (disttype == NUMERICOID || disttype == BPCHAROID || disttype == VARCHAROID) {
if (can_coerce_type(1, &exprtype, &disttype, COERCION_ASSIGNMENT)) {
distcol_expr = (Expr*)coerce_type(NULL,
(Node*)distcol_expr,
exprtype,
disttype,
disttypmod,
COERCION_ASSIGNMENT,
COERCE_IMPLICIT_CAST,
-1);
} else {
distcol_expr = NULL;
}
} else {
distcol_expr = (Expr*)coerce_to_target_type(NULL,
(Node*)distcol_expr,
exprtype,
disttype,
disttypmod,
COERCION_ASSIGNMENT,
COERCE_IMPLICIT_CAST,
-1);
}
/*
* PGXC_FQS: We should set the bound parameters here, but we don't have
* PlannerInfo struct and we don't handle them right now.
* Even if constant expression mutator changes the expression, it will
* only simplify it, keeping the semantics same
*/
if (boundParams) {
distcol_expr = (Expr*)eval_const_expressions_params(NULL, (Node*)distcol_expr, boundParams);
} else {
distcol_expr = (Expr*)eval_const_expressions(NULL, (Node*)distcol_expr);
}
}
if (distcol_expr != NULL) {
/*
* If all distcol_expr are const, no need to do node reduction, which is the same as before.
* If there is extern params with the form '$n', we can do dynamic datanode reduction.
*/
if (IsA(distcol_expr, Const)) {
/* If all const for now, do the same as before; else there is no need to do these */
if (!needDynamicReduce) {
Const* const_expr = (Const*)distcol_expr;
distcol_value[i] = const_expr->constvalue;
distcol_isnull[i] = const_expr->constisnull;
distcol_type[i] = const_expr->consttype;
idx_dist = lappend_int(idx_dist, i);
i++;
}
}
/* node reduction when there are param but no boundParams, i.e. generate a generic plan */
else if (useDynamicReduce && IsA(distcol_expr_original, Param) && boundParams == NULL) {
Param* param_expr = (Param*)distcol_expr_original;
/* node reduction only for PARAM_EXTERN params with the form '$n' */
if (param_expr->paramkind != PARAM_EXTERN) {
break;
}
needDynamicReduce = true;
} else {
if (IsA(distcol_expr_original, Param) && boundParams == NULL) {
Param* param_expr = (Param*)distcol_expr_original;
/* node reduction only for PARAM_EXTERN params with the form '$n' */
if (param_expr->paramkind != PARAM_EXTERN) {
break;
}
}
break;
}
distcol_expr_list = lappend(distcol_expr_list, copyObject(distcol_expr));
bucket_expr_list = lappend(bucket_expr_list, copyObject(distcol_expr));
} else {
break;
}
}
/* If needDynamicReduce, we also do cleaning like before */
if (cell != NULL || needDynamicReduce) {
for (int j = 0; j < len; j++) {
distcol_value[j] = 0;
distcol_isnull[j] = true;
distcol_type[j] = InvalidOid;
}
list_free(idx_dist);
idx_dist = NULL;
}
/* mark that datanodes can be reduced */
if (cell != NULL && needDynamicReduce) {
needDynamicReduce = false;
}
}
exec_nodes = GetRelationNodes(rel_loc_info, distcol_value, distcol_isnull, distcol_type, idx_dist, relaccess);
/*
* If 'needDynamicReduce' and 'canReduce', we will use 'distcol_expr_list' to get the
* correct connection during execution.
* There are two cases: pure param; param and const mixed.
* Also, we will discard and release the node lists we just got,
* and append the relation oid to exec nodes.
*/
if (needDynamicReduce && exec_nodes != NULL) {
exec_nodes->en_expr = distcol_expr_list;
list_free(exec_nodes->primarynodelist);
exec_nodes->primarynodelist = NIL;
list_free(exec_nodes->nodeList);
exec_nodes->nodeList = NIL;
exec_nodes->en_relid = rel_loc_info->relid;
exec_nodes->nodelist_is_nil = true;
}
if (exec_nodes != NULL && list_length(rel_loc_info->partAttrNum) == list_length(bucket_expr_list)) {
exec_nodes->bucketexpr = bucket_expr_list;
exec_nodes->bucketrelid = rel_loc_info->relid;
}
return exec_nodes;
}
void PruningDatanode(ExecNodes* execNodes, ParamListInfo boundParams)
{
Assert(false);
DISTRIBUTED_FEATURE_NOT_SUPPORTED();
}
void ConstructSliceBoundary(ExecNodes* en)
{
Assert(false);
DISTRIBUTED_FEATURE_NOT_SUPPORTED();
}
/*
* GetLocatorType
* Returns the locator type of the table.
*/
char GetLocatorType(Oid relid)
{
char ret = LOCATOR_TYPE_NONE;
if (relid == InvalidOid)
return ret;
RelationLocInfo* locInfo = GetRelationLocInfo(relid);
if (locInfo != NULL) {
ret = locInfo->locatorType;
FreeRelationLocInfo(locInfo);
}
#ifdef STREAMPLAN
else {
if (is_sys_table(relid))
ret = LOCATOR_TYPE_REPLICATED;
}
#endif
return ret;
}
/*
* GetAllDataNodes
* Return a list of all Datanodes.
* We assume all tables use all nodes in the prototype, so just return a list
* from first one.
*/
List* GetAllDataNodes(void)
{
if (IS_STREAM) {
/* single node only has one node */
return lappend_int(NIL, 0);
} else {
return NIL;
}
}
/*
* GetNodeGroupNodeList
* Look at the data cached for handles and return datanode list
* Reload pooler when find node failed.
*/
List* GetNodeGroupNodeList(Oid* members, int nmembers)
{
Assert(false);
DISTRIBUTED_FEATURE_NOT_SUPPORTED();
return NIL;
}
List* SearchSliceEntryCopy(char parttype, Oid relid)
{
Assert(false);
DISTRIBUTED_FEATURE_NOT_SUPPORTED();
return NIL;
}
HeapTuple SearchTableEntryCopy(char parttype, Oid relid)
{
Assert(false);
DISTRIBUTED_FEATURE_NOT_SUPPORTED();
return NULL;
}
/*
* GetAllCoordNodes
* Return a list of all Coordinators
* This is used to send DDL to all nodes and to clean up pooler connections.
* Do not put in the list the local Coordinator where this function is launched.
*/
List* GetAllCoordNodes(void)
{
int i;
List* nodeList = NIL;
for (i = 0; i < u_sess->pgxc_cxt.NumCoords; i++) {
/*
* Do not put in list the Coordinator we are on,
* it doesn't make sense to connect to the local Coordinator.
*/
if (i != u_sess->pgxc_cxt.PGXCNodeId - 1)
nodeList = lappend_int(nodeList, i);
}
return nodeList;
}
/*
* @Description: temp table does not do redistribute when cluster resizing, so it will
* still on old node group after redistributing. when the old node group is dropped,
* so GetBucketMap will encounter "cache lookup failed" error. This function is for
* giving human readable messages..
* @in groupname - the node group to be used.
* @in relname - the relation name which the bucketmap is for.
* @in isOtherTempNamespace -- If it's our own temp table or other session's temp table,
to determin report an error or warning
* @return: uint2* - the bucket map of the giving relation.
*/
static uint2* tryGetBucketMap(const char* groupname, char* relname, bool isOtherTempNamespace, int *bucketlen)
{
Relation rel;
HeapTuple htup;
int len;
rel = heap_open(PgxcGroupRelationId, ShareLock);
len = BUCKETDATALEN * sizeof(uint2);
htup = SearchSysCache1(PGXCGROUPNAME, CStringGetDatum(groupname));
if (!HeapTupleIsValid(htup)) {
if (!isOtherTempNamespace) {
heap_close(rel, ShareLock);
ereport(ERROR,
(errcode(ERRCODE_SYSTEM_ERROR),
errmsg("The relation %s is invalid because of cluster resize, "
"please quit current session and it will be "
"automaticly dropped.",
relname)));
} else {
heap_close(rel, ShareLock);
return NULL;
}
}
ReleaseSysCache(htup);
heap_close(rel, ShareLock);
return (uint2*)BucketMapCacheGetBucketmap(groupname, bucketlen);
}
/*
* RelationBuildLocator
* Build locator information associated with the specified relation.
*/
void RelationBuildLocator(Relation rel)
{
#ifndef ENABLE_MULTIPLE_NODES
Assert(false);
DISTRIBUTED_FEATURE_NOT_SUPPORTED();
return;
#else
Relation pcrel;
ScanKeyData skey;
SysScanDesc pcscan;
HeapTuple htup;
MemoryContext oldContext;
RelationLocInfo* relationLocInfo = NULL;
int j;
Form_pgxc_class pgxc_class;
ScanKeyInit(
&skey, Anum_pgxc_class_pcrelid, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(RelationGetRelid(rel)));
pcrel = heap_open(PgxcClassRelationId, AccessShareLock);
pcscan = systable_beginscan(pcrel, PgxcClassPgxcRelIdIndexId, true, NULL, 1, &skey);
htup = systable_getnext(pcscan);
if (!HeapTupleIsValid(htup)) {
/* Assume local relation only */
rel->rd_locator_info = NULL;
systable_endscan(pcscan);
heap_close(pcrel, AccessShareLock);
return;
}
pgxc_class = (Form_pgxc_class)GETSTRUCT(htup);
oldContext = MemoryContextSwitchTo(CacheMemoryContext);
relationLocInfo = (RelationLocInfo*)palloc(sizeof(RelationLocInfo));
rel->rd_locator_info = relationLocInfo;
relationLocInfo->relid = RelationGetRelid(rel);
relationLocInfo->locatorType = pgxc_class->pclocatortype;
relationLocInfo->partAttrNum = pgxc_class->pcattnum;
relationLocInfo->nodeList = NIL;
for (j = 0; j < pgxc_class->nodeoids.dim1; j++)
relationLocInfo->nodeList = lappend_int(
relationLocInfo->nodeList, PGXCNodeGetNodeId(pgxc_class->nodeoids.values[j], PGXC_NODE_DATANODE));
/*
* If the locator type is round robin, we set a node to
* use next time. In addition, if it is replicated,
* we choose a node to use for balancing reads.
*/
if (relationLocInfo->locatorType == LOCATOR_TYPE_RROBIN ||
relationLocInfo->locatorType == LOCATOR_TYPE_REPLICATED) {
int offset;
/*
* pick a random one to start with,
* since each process will do this independently
*/
offset = compute_modulo(abs(rand()), list_length(relationLocInfo->nodeList));
srand(time(NULL));
relationLocInfo->roundRobinNode = relationLocInfo->nodeList->head; /* initialize */
for (j = 0; j < offset && relationLocInfo->roundRobinNode->next != NULL; j++)
relationLocInfo->roundRobinNode = relationLocInfo->roundRobinNode->next;
}
systable_endscan(pcscan);
heap_close(pcrel, AccessShareLock);
MemoryContextSwitchTo(oldContext);
#endif
}
/*
* GetLocatorRelationInfo
* Returns the locator information for relation,
* in a copy of the RelationLocatorInfo struct in relcache
*/
RelationLocInfo* GetRelationLocInfo(Oid relid)
{
RelationLocInfo* ret_loc_info = NULL;
Relation rel = relation_open(relid, AccessShareLock);
/* Relation needs to be valid */
Assert(rel->rd_isvalid);
if (rel->rd_locator_info)
ret_loc_info = CopyRelationLocInfo(rel->rd_locator_info);
/*
* NodeGroup --dynamic computation elastic
*
* When new datanodes added into cluster, we need invoke SQL function pgxc_pool_reload()
* to do handler update so that optimizer can do correct planning based on new cluster
* scale, however pgxc_pool_reload() won't invalidate rel_loc in relcache, so we have to
* rebuild rel_loc here anyway.
*
* It may not be the most efficient solution, the idea way is to invalidate all relcache
* in pgxc_pool_reload(), -- will improve later.
*/
if (ret_loc_info && (RELKIND_FOREIGN_TABLE == rel->rd_rel->relkind
|| RELKIND_STREAM == rel->rd_rel->relkind)) {
ExecNodes* exec_nodes = RelidGetExecNodes(relid, false);
if (NIL != exec_nodes->nodeList) {
ret_loc_info->nodeList = list_copy(exec_nodes->nodeList);
list_free(exec_nodes->nodeList);
bms_free(exec_nodes->distribution.bms_data_nodeids);
}
pfree(exec_nodes);
}
relation_close(rel, AccessShareLock);
return ret_loc_info;
}
/*
* GetLocatorRelationInfoDN
* Returns the locator information for hashbucket relation
* only relid and partAttrNum is valid, other fields are dummy
*/
RelationLocInfo* GetRelationLocInfoDN(Oid reloid)
{
RelationLocInfo* ret_loc_info = NULL;
Relation relation = heap_open(reloid, NoLock);
if (!REALTION_BUCKETKEY_VALID(relation)) {
heap_close(relation, NoLock);
return NULL;
}
ret_loc_info = (RelationLocInfo*)palloc0(sizeof(RelationLocInfo));
ret_loc_info->relid = reloid;
ret_loc_info->locatorType = LOCATOR_TYPE_HASH;
ret_loc_info->nodeList = lappend_int(ret_loc_info->nodeList, u_sess->pgxc_cxt.PGXCNodeId);
int2vector* colids = relation->rd_bucketkey->bucketKey;
for (int i = 0; i< colids->dim1; i++) {
ret_loc_info->partAttrNum = lappend_int(ret_loc_info->partAttrNum, colids->values[i]);
}
heap_close(relation, NoLock);
return ret_loc_info;
}
/*
* CopyRelationLocInfo
* Copy the RelationLocInfo struct
*/
RelationLocInfo* CopyRelationLocInfo(RelationLocInfo* srcInfo)
{
#ifndef ENABLE_MULTIPLE_NODES
Assert(false);
DISTRIBUTED_FEATURE_NOT_SUPPORTED();
return NULL;
#else
RelationLocInfo* destInfo = NULL;
Assert(srcInfo);
destInfo = (RelationLocInfo*)palloc0(sizeof(RelationLocInfo));
destInfo->relid = srcInfo->relid;
destInfo->locatorType = srcInfo->locatorType;
destInfo->partAttrNum = srcInfo->partAttrNum;
if (srcInfo->nodeList)
destInfo->nodeList = list_copy(srcInfo->nodeList);
/* Note: for roundrobin, we use the relcache entry */
return destInfo;
#endif
}
/*
* FreeRelationLocInfo
* Free RelationLocInfo struct
*/
void FreeRelationLocInfo(RelationLocInfo* relationLocInfo)
{
#ifndef ENABLE_MULTIPLE_NODES
Assert(false);
DISTRIBUTED_FEATURE_NOT_SUPPORTED();
return;
#else
if (relationLocInfo)
pfree(relationLocInfo);
#endif
}
Distribution* NewDistribution()
{
Distribution* distribution = (Distribution*)palloc0(sizeof(Distribution));
if (distribution == NULL) {
ereport(ERROR, (errcode(ERRCODE_SYSTEM_ERROR), errmsg("Could not alloc new memory.")));
}
return distribution;
}
void DestroyDistribution(Distribution* distribution)
{
if (distribution != NULL) {
bms_free(distribution->bms_data_nodeids);
pfree(distribution);
}
}
/*
* FreeExecNodes
* Free the contents of the ExecNodes expression
*/
void FreeExecNodes(ExecNodes** exec_nodes)
{
ExecNodes* tmp_en = *exec_nodes;
/* Nothing to do */
if (tmp_en == NULL)
return;
list_free(tmp_en->primarynodelist);
list_free(tmp_en->nodeList);
pfree(tmp_en);
*exec_nodes = NULL;
}
/*
* pgxc_find_distcol_expr
* Search through the quals provided and find out an expression which will give
* us value of distribution column if exists in the quals. Say for a table
* tab1 (val int, val2 int) distributed by hash(val), a query "SELECT * FROM
* tab1 WHERE val = fn(x, y, z) and val2 = 3", fn(x,y,z) is the expression which
* decides the distribution column value in the rows qualified by this query.
* Hence return fn(x, y, z). But for a query "SELECT * FROM tab1 WHERE val =
* fn(x, y, z) || val2 = 3", there is no expression which decides the values
* distribution column val can take in the qualified rows. So, in such cases
* this function returns NULL.
*/
Expr* pgxc_find_distcol_expr(void* query_arg, Index varno, AttrNumber attrNum, Node* quals)
{
List* lquals = NULL;
ListCell* qual_cell = NULL;
Query* query = (Query*)query_arg;
/* If no quals, no distribution column expression */
if (quals == NULL)
return NULL;
/* Convert the qualification into List if it's not already so */
if (!IsA(quals, List))
lquals = make_ands_implicit((Expr*)quals);
else
lquals = (List*)quals;
/*
* For every ANDed expression, check if that expression is of the form
* <distribution_col> = <expr>. If so return expr.
*/
foreach (qual_cell, lquals) {
Expr* qual_expr = (Expr*)lfirst(qual_cell);
OpExpr* op = NULL;
Expr* lexpr = NULL;
Expr* rexpr = NULL;
Var* var_expr = NULL;
Expr* distcol_expr = NULL;
/* if it is 'is null' */
if (IsA(qual_expr, NullTest)) {
NullTest* nt = (NullTest*)qual_expr;
if (nt->nulltesttype == IS_NULL && IsA(nt->arg, Var)) {
var_expr = (Var*)(nt->arg);
/*
* If Var found is not the distribution column of required relation,
* check next qual
*/
if (var_expr->varno != varno || var_expr->varattno != attrNum)
continue;
/* Make NullConst */
distcol_expr = (Expr*)makeNullConst(var_expr->vartype, var_expr->vartypmod, var_expr->varcollid);
/* Found the distribution column expression return it */
return distcol_expr;
}
continue;
}
if (!IsA(qual_expr, OpExpr))
continue;
op = (OpExpr*)qual_expr;
/* If not a binary operator, it can not be '='. */
if (list_length(op->args) != 2)
continue;
lexpr = (Expr*)linitial(op->args);
rexpr = (Expr*)lsecond(op->args);
/*
* If either of the operands is a RelabelType, extract the Var in the RelabelType.
* A RelabelType represents a "dummy" type coercion between two binary compatible datatypes.
* If we do not handle these then our optimization does not work in case of varchar
* For example if col is of type varchar and is the dist key then
* select * from vc_tab where col = 'abcdefghijklmnopqrstuvwxyz';
* should be shipped to one of the nodes only
*/
if (IsA(lexpr, RelabelType))
lexpr = ((RelabelType*)lexpr)->arg;
if (IsA(rexpr, RelabelType))
rexpr = ((RelabelType*)rexpr)->arg;
/*
* If either of the operands is a Var expression, assume the other
* one is distribution column expression. If none is Var check next
* qual.
*/
if (IsA(lexpr, Var)) {
var_expr = (Var*)lexpr;
distcol_expr = rexpr;
} else if (IsA(rexpr, Var)) {
var_expr = (Var*)rexpr;
distcol_expr = lexpr;
} else
continue;
Var baserel_var = *var_expr;
/* currently we only handle this level vars */
if (var_expr->varlevelsup == 0) {
/* find the base relation for a join var */
(void)get_real_rte_varno_attno(query, &(baserel_var.varno), &(baserel_var.varattno));
/* use baserel_var now */
var_expr = &baserel_var;
}
/*
* If Var found is not the distribution column of required relation,
* check next qual
*/
if (var_expr->varno != varno || var_expr->varattno != attrNum)
continue;
/*
* If the operator is not an assignment operator, check next
* constraint. An operator is an assignment operator if it's
* mergejoinable or hashjoinable. Beware that not every assignment
* operator is mergejoinable or hashjoinable, so we might leave some
* oportunity. But then we have to rely on the opname which may not
* be something we know to be equality operator as well.
*/
if (!op_mergejoinable(op->opno, exprType((Node*)lexpr)) && !op_hashjoinable(op->opno, exprType((Node*)lexpr)))
continue;
/* Found the distribution column expression return it */
return distcol_expr;
}
/* Exhausted all quals, but no distribution column expression */
return NULL;
}
/*
* @Description : check whether the OpExpr contain value of distribution column.
* Say for a table tab1 (val int, val2 int) distributed by hash(val), a query
* "SELECT * FROM tab1 WHERE val = fn(x, y, z)", fn(x,y,z) is the expression
* which decides the distribute column value in the rows qualified by this query.
* Hence return fn(x, y, z).
*
* @in varno : index of the var_expr's relation in the range.
* @in attrNum : attribute number of this var_expr.
* @in opexpr : the opexpr in function statement need be check.
* @return : true when we get the right opexpr.
*/
Expr* pgxc_check_distcol_opexpr(Index varno, AttrNumber attrNum, OpExpr* opexpr)
{
Assert(false);
DISTRIBUTED_FEATURE_NOT_SUPPORTED();
return NULL;
}
/*
* @Description: Get min dn number from pgxc_group.
* @return - return min dn num.
*/
int GetMinDnNum()
{
int dataNodeNum = u_sess->pgxc_cxt.NumDataNodes;
Relation rel = NULL;
TableScanDesc scan;
HeapTuple tuple;
bool isNull = false;
rel = heap_open(PgxcGroupRelationId, ShareLock);
scan = tableam_scan_begin(rel, SnapshotNow, 0, NULL);
while ((tuple = (HeapTuple) tableam_scan_getnexttuple(scan, ForwardScanDirection)) != NULL) {
Datum group_members_datum = heap_getattr(tuple, Anum_pgxc_group_members, RelationGetDescr(rel), &isNull);
/* Should not happend */
if (isNull) {
ereport(ERROR, (errcode(ERRCODE_SYSTEM_ERROR), errmsg("Can't get group member")));
}
oidvector* group_members = (oidvector*)PG_DETOAST_DATUM(group_members_datum);
if (group_members->dim1 < dataNodeNum) {
dataNodeNum = group_members->dim1;
}
if (group_members != (oidvector*)DatumGetPointer(group_members_datum)) {
pfree_ext(group_members);
}
}
tableam_scan_end(scan);
heap_close(rel, ShareLock);
return dataNodeNum;
}
|
a1ba20a18bc32e61c5cee4fdc4240c1f9ce824c9 | 62bcd3fa83bce8a59fd81707dca0801bf2065c8a | /src/main.cpp | 8c936b08a3520c25fa51dc2b3821334d5a9124fe | [] | no_license | jisshin/CS143 | 692e41d9e885c1430b5b079cd002ab4ea0f3cd21 | cf91f8b0c2b4aff769f91ea009bf7237103bff12 | refs/heads/master | 2021-05-30T03:43:36.405884 | 2015-12-09T10:26:22 | 2015-12-09T10:26:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 393 | cpp | main.cpp | /**
* Checks the functionality of retrieving network info.
*/
#include "../include/retrieve_network_info.hpp"
#include <cstdlib>
#include <iostream>
int main(int argc, char* argv[]) {
if (argc != 2) {
std::cout << "enter json file name" << std::endl;
return 0;
}
RetrieveNetworkInfo retrieve;
if (retrieve.setNetworkInfo(argv[1])) {
retrieve.createNetwork();
}
return 0;
}
|
90c95c759d34a2d29dde322acbf86bf1e1135e14 | a53ef594315692d14ab9a1633f29e3ad05c20771 | /csplane3d.cpp | 6b95099ae27e33c4f3c4a421bda13aa0f4937745 | [] | no_license | grischnack/CSVision | 0f780a4ebfe945a665d89833971db0e003f98c31 | 76582b099c9acd276fa61691437df5f385d07551 | refs/heads/master | 2021-01-12T10:40:13.162105 | 2018-01-20T11:58:06 | 2018-01-20T11:58:06 | 81,724,461 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,995 | cpp | csplane3d.cpp | #include "csplane3d.h"
CsPlane3D::CsPlane3D(QVector3D norm, float dist, CsShape2D shap, CsPoint3D cent){
normal = norm;
distance = dist;
shape = shap;
center = cent;
}
CsPlane3D::CsPlane3D(){
normal = QVector3D(0,0,1);
distance = 0.0f;
shape = CsShape2D(3, 100, CsPoint2D(0,0));
center = CsPoint3D(0,0,0);
}
CsPoint3D CsPlane3D::intersection2(const CsLine3D *lin) const{
}
CsPoint3D CsPlane3D::intersection(const CsLine3D *lin) const{
CsPoint3D intersp;
QVector3D plancent = QVector3D(center.x, center.y, center.z);
plancent = plancent +(normal*distance);
QVector3D lincent = QVector3D(lin->center.x, lin->center.y, lin->center.z);
QVector3D linNorm = lin->norm();
linNorm *= lin->distance;
lincent = lincent + linNorm;
float length;
float dotNumerator;
float dotDenominator;
dotNumerator = QVector3D::dotProduct(( plancent - lincent), normal);
dotDenominator = QVector3D::dotProduct(lin->direction(), normal);
QVector3D vector = QVector3D(0,0,0);
if(dotDenominator != 0.0f){
length = dotNumerator / dotDenominator;
if(abs(length)<lin->length/2){
vector = lin->direction();
vector *= length;
QVector3D intersection = lincent + vector;
intersp = CsPoint3D(intersection.x(), intersection.y(), intersection.z());
}
}
return intersp;
}
float CsPlane3D::calculatePointsDist( CsPoint3D const *point1, CsPoint3D const *point2) const{
return sqrt(pow( (point1->x-point2->x), 2)
+pow((point1->y-point2->y),2)
+pow((point1->z-point2->z),2));
}
//Returns line with same center as this plane.
CsLine3D CsPlane3D::intersection(const CsPlane3D *plan) const{
QVector3D linedir = QVector3D::crossProduct(normal,plan->normal);
linedir = linedir.normalized();
QVector3D dirFromPointOnThisPlaneToClosestPointOfIntersection = QVector3D::crossProduct(-normal, linedir);
QVector3D dirFromPointOnOtherPlaneToClosestPointOfIntersection = QVector3D::crossProduct(plan->normal, linedir);
CsLine3D helperline = CsLine3D(QQuaternion::fromDirection(dirFromPointOnThisPlaneToClosestPointOfIntersection, normal),
distance, INFINITY, center);
CsPoint3D closestpoint = plan->intersection(&helperline);
float linedist = calculatePointsDist(¢er, &closestpoint);
QVector3D centerv = QVector3D(center.x, center.y, center.z);
QVector3D pointonplanv = centerv + (normal*distance);
CsPoint3D pointonplan = CsPoint3D(pointonplanv.x(), pointonplanv.y(), pointonplanv.z());
//dirvector is linedir
//upvector is following:
float x = distance;
float y = calculatePointsDist(&pointonplan, &closestpoint);
float z = 0;
QVector3D up = QVector3D(x, y, z);
up = up.normalized();
CsLine3D result = CsLine3D(QQuaternion::fromDirection(linedir, up), linedist, INFINITY, center);
return result;
//TODO: test
}
|
e0e686b94970293ccf19908fb4bb4a9c9f541eb9 | 6bf77f419745da07aaa5088b1e7b129392fa2bac | /src/Graphics/Graphics.cpp | 76ca129ffc88ec6fe60e543cf562c35eddb06b6c | [] | no_license | 0----0/danmaku | 4508066d5301eecd8e48fce19638e37399fcaa2a | 9aad5f230d1d072f9fe501b437db03fb885c15ef | refs/heads/master | 2021-01-10T21:15:29.074040 | 2014-12-28T03:09:53 | 2014-12-28T03:09:53 | 28,552,216 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,174 | cpp | Graphics.cpp | #include "Graphics.hpp"
const std::array<vertex,4> quad = {{
{{0.5f, -0.5f, 0.f}, {1.f, 1.f}},
{{-0.5f, -0.5f, 0.f}, {0.f, 1.f}},
{{-0.5f, 0.5f, 0.f}, {0.f, 0.f}},
{{0.5f, 0.5f, 0.f}, {1.f, 0.f}}
}};
void Graphics::setTransform(const std::array<float, 2> position, const std::array<float, 2> scale) {
const float matrix[4][4] = {
{scale[0], 0.f, 0.f, 0.f},
{0.f, scale[1], 0.f, 0.f},
{0.f, 0.f, 1.f, 0.f},
{position[0], position[1], 0.f, 1.f}
};
glUniformMatrix4fv(program.modelview_matrix_uniform, 1, 0, &matrix[0][0]);
}
void init() {
glfwSwapInterval(0);
glClearColor(1.f, 1.f, 1.f, 1.f);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
bool Graphics::processWindow() {
glfwSwapBuffers(*window);
glfwPollEvents();
return !glfwWindowShouldClose(*window);
}
void Graphics::draw() {
glDrawArrays(GL_QUADS, 0, 4);
}
void Graphics::clear() {
glClear(GL_COLOR_BUFFER_BIT);
}
Graphics::Graphics():
vertexBuffer(quad, program) {
init();
}
|
31ea014a9db0443f6657f497509548ff68bbfb1b | 5cca59a3f310cb6b33813f8290c537596286e2f7 | /5.8.cpp | ad4ad2017d5a355b68c0bc32ba196ea5fc3014e4 | [] | no_license | kacpersyn7/C-Primer-Plus.-Stephen-Prata | 719e3feb20b4813ea233ec54dac6fd17b1dc297d | e588e1b010743ed57ae696b800832f85c4cbe4bd | refs/heads/master | 2021-01-22T03:08:54.378788 | 2017-04-15T21:52:06 | 2017-04-15T21:52:06 | 81,102,787 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 371 | cpp | 5.8.cpp | #include <iostream>
#include <cstring>
const int ROZMIAR = 20;
int main()
{
using namespace std;
char worlds[ROZMIAR];
int i = 0;
cout<<"Podawaj slowa (kiedy skonczysz, napisz \"gotowe\") \n";
do
{
cin>>worlds;
i++;
}
while(strcmp(worlds,"gotowe"));
cout<<"Podano "<<i-1<<" slow\n";
return 0;
}
|
3a1048666e292af4f1e582bc9335611446b52c27 | 205cf7bd410b10881ec744a43f10aaf7b69dffcf | /src/places/retirement_home.cpp | d720a0de6af22d6f834e2acf46c7c108a0b8a415 | [
"MIT"
] | permissive | Dynamical-Systems-Laboratory/ABM-COVID-DSL | 13e873d3fec584eaa12fef6c48591f4aecfad082 | bf1fcbbd7ae161f2a026335fa830cd21ccdf48f0 | refs/heads/main | 2023-05-12T10:06:44.698601 | 2021-05-27T23:28:03 | 2021-05-27T23:28:03 | 309,719,867 | 3 | 3 | MIT | 2021-01-12T15:00:15 | 2020-11-03T14:56:13 | C++ | UTF-8 | C++ | false | false | 486 | cpp | retirement_home.cpp | #include "../../include/places/retirement_home.h"
/*****************************************************
* class: RetirementHome
*
* Defines and stores attributes of a single
* retirement home
*
*****************************************************/
//
// I/O
//
// Save information about a RetirementHome object
void RetirementHome::print_basic(std::ostream& where) const
{
Place::print_basic(where);
where << " " << beta_emp << " " << beta_ih << " " << psi_emp;
}
|
9da40c61f8d62677785236f07652c9fd0ad2a265 | 674bcb4bf88b5359ea9710c864481af61f5867d3 | /src/plugins/playback/adplug/adplug_lib/src/herad.cpp | 67b01ec47ad62ea50e107718361789ece4636452 | [
"GPL-1.0-or-later",
"LGPL-2.0-or-later",
"LGPL-2.1-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-2.0-only",
"LGPL-2.1-only",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | HippoPlayer/HippoPlayer | a1da46743507c866c5e614f36122348794229b05 | a3145f9797a5ef7dd1b79ee8ccd3476c8c5310a6 | refs/heads/master | 2023-04-19T13:05:36.210552 | 2021-05-08T06:48:18 | 2021-05-08T06:48:18 | 2,195,999 | 44 | 5 | Apache-2.0 | 2022-10-19T15:45:21 | 2011-08-12T08:12:25 | C | UTF-8 | C++ | false | false | 28,506 | cpp | herad.cpp | /*
* Adplug - Replayer for many OPL2/OPL3 audio file formats.
* Copyright (C) 1999 - 2008 Simon Peter <dn.tlp@gmx.net>, et al.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* herad.cpp - Herbulot AdLib Player by Stas'M <binarymaster@mail.ru>
*
* Thanks goes to co-workers:
* -=CHE@TER=- (SQX decompression)
* SynaMax (general documentation, reverse-engineering, testing)
* Jepael (timer code sample, DOS driver shell)
* Daniël van de Burgt "thatdutchguy" (pitch slides code sample)
*
* REFERENCES:
* http://www.vgmpf.com/Wiki/index.php/HERAD
*
* TODO:
* - Fix strange AGD sound
* - Fix splash sound in Gorbi (at 0:23)
* - Fix hiss sound in NewSan (at beginning)
*/
#include <cstring>
#include <stdio.h>
#include "herad.h"
#include "load_helper.h"
#ifdef DEBUG
#include "debug.h"
#endif
const uint8_t CheradPlayer::slot_offset[HERAD_NUM_VOICES] = {
0, 1, 2, 8, 9, 10, 16, 17, 18
};
const uint16_t CheradPlayer::FNum[HERAD_NUM_NOTES] = {
343, 364, 385, 408, 433, 459, 486, 515, 546, 579, 614, 650
};
const uint8_t CheradPlayer::fine_bend[HERAD_NUM_NOTES + 1] = {
19, 21, 21, 23, 25, 26, 27, 29, 31, 33, 35, 36, 37
};
const uint8_t CheradPlayer::coarse_bend[10] = {
0, 5, 10, 15, 20,
0, 6, 12, 18, 24
};
CPlayer *CheradPlayer::factory(Copl *newopl)
{
return new CheradPlayer(newopl);
}
std::string CheradPlayer::gettype()
{
char scomp[12 + 1] = "";
if (comp > HERAD_COMP_NONE)
sprintf(scomp, ", %s packed", (comp == HERAD_COMP_HSQ ? "HSQ" : "SQX"));
char type[40 + 1];
sprintf(type, "HERAD System %s (version %d%s)", (AGD ? "AGD" : "SDB"), (v2 ? 2 : 1), scomp);
return std::string(type);
}
bool isHSQ(uint8_t * data, int size)
{
// data[0] - word DecompSize
// data[1]
// data[2] - byte Null = 0
// data[3] - word CompSize
// data[4]
// data[5] - byte Checksum
if ( data[2] != 0 )
{
#ifdef DEBUG
AdPlug_LogWrite("HERAD: Is not HSQ, wrong check byte.\n");
#endif
return false;
}
const uint16_t temp_size = u16_unaligned(data + 3);
if ( temp_size != size )
{
#ifdef DEBUG
AdPlug_LogWrite("HERAD: Is not HSQ, wrong compressed size.\n");
#endif
return false;
}
uint8_t checksum = 0;
for (int i = 0; i < HERAD_MIN_SIZE; i++)
{
checksum += data[i];
}
if ( checksum != 0xAB )
{
#ifdef DEBUG
AdPlug_LogWrite("HERAD: Is not HSQ, wrong checksum.\n");
#endif
return false;
}
return true;
}
bool isSQX(uint8_t * data)
{
// data[0] - word OutbufInit
// data[1]
// data[2] - byte SQX flag #1
// data[3] - byte SQX flag #2
// data[4] - byte SQX flag #3
// data[5] - byte CntOffPart
if ( data[2] > 2 || data[3] > 2 || data[4] > 2 )
{
#ifdef DEBUG
AdPlug_LogWrite("HERAD: Is not SQX, wrong flags.\n");
#endif
return false;
}
if ( data[5] == 0 || data[5] > 15 )
{
#ifdef DEBUG
AdPlug_LogWrite("HERAD: Is not SQX, wrong bit count.\n");
#endif
return false;
}
return true;
}
uint16_t HSQ_decompress(uint8_t * data, int size, uint8_t * out)
{
uint32_t queue = 1;
int8_t bit;
int16_t offset;
uint16_t count, out_size = *(uint16_t *)data;
uint8_t * src = data;
uint8_t * dst = out;
src += 6;
while (true)
{
// get next bit of the queue
if (queue == 1)
{
queue = u16_unaligned(src) | 0x10000;
src += 2;
}
bit = queue & 1;
queue >>= 1;
// if bit is non-zero
if (bit)
{
// copy next byte of the input to the output
*dst++ = *src++;
}
else
{
// get next bit of the queue
if (queue == 1)
{
queue = u16_unaligned(src) | 0x10000;
src += 2;
}
bit = queue & 1;
queue >>= 1;
// if bit is non-zero
if (bit)
{
// count = next 3 bits of the input
// offset = next 13 bits of the input minus 8192
count = u16_unaligned(src);
offset = (count >> 3) - 8192;
count &= 7;
src += 2;
// if count is zero
if (!count)
{
// count = next 8 bits of the input
count = *(uint8_t *)src;
src++;
}
// if count is zero
if (!count)
break; // finish the unpacking
}
else
{
// count = next bit of the queue * 2 + next bit of the queue
if (queue == 1)
{
queue = u16_unaligned(src) | 0x10000;
src += 2;
}
bit = queue & 1;
queue >>= 1;
count = bit << 1;
if (queue == 1)
{
queue = u16_unaligned(src) | 0x10000;
src += 2;
}
bit = queue & 1;
queue >>= 1;
count += bit;
// offset = next 8 bits of the input minus 256
offset = *(uint8_t *)src;
offset -= 256;
src++;
}
count += 2;
// copy count bytes at (output + offset) to the output
while (count--)
{
*dst = *(dst + offset);
dst++;
}
}
}
return out_size;
}
uint16_t SQX_decompress(uint8_t * data, int size, uint8_t * out)
{
int16_t offset;
uint16_t count;
uint8_t * src = data;
uint8_t * dst = out;
bool done = false;
std::memcpy(dst, src, sizeof(uint16_t));
src += 6;
uint16_t queue = 1;
uint8_t bit, bit_p;
while (true)
{
bit = queue & 1;
queue >>= 1;
if (queue == 0)
{
queue = u16_unaligned(src);
src += 2;
bit_p = bit;
bit = queue & 1;
queue >>= 1;
if (bit_p)
queue |= 0x8000;
}
if (bit == 0)
{
switch (data[2])
{
case 0:
*dst++ = *src++;
break;
case 1:
count = 0;
bit = queue & 1;
queue >>= 1;
if (queue == 0)
{
queue = u16_unaligned(src);
src += 2;
bit_p = bit;
bit = queue & 1;
queue >>= 1;
if (bit_p)
queue |= 0x8000;
count = bit;
bit = queue & 1;
queue >>= 1;
}
else
{
count = bit;
bit = queue & 1;
queue >>= 1;
if (queue == 0)
{
queue = u16_unaligned(src);
src += 2;
bit_p = bit;
bit = queue & 1;
queue >>= 1;
if (bit_p)
queue |= 0x8000;
}
}
count = (count << 1) | bit;
offset = *(uint8_t *)src;
offset -= 256;
src++;
count += 2;
while (count--)
{
*dst = *(dst + offset);
dst++;
}
break;
case 2:
count = u16_unaligned(src);
offset = (count >> data[5]) - (1 << (16 - data[5]));
count &= (1 << data[5]) - 1;
src += 2;
if (!count)
{
count = *(uint8_t *)src;
src++;
}
if (!count)
{
done = true;
break;
}
count += 2;
while (count--)
{
*dst = *(dst + offset);
dst++;
}
break;
}
if (done)
break;
continue;
}
else
{
bit = queue & 1;
queue >>= 1;
if (queue == 0)
{
queue = u16_unaligned(src);
src += 2;
bit_p = bit;
bit = queue & 1;
queue >>= 1;
if (bit_p)
queue |= 0x8000;
}
if (bit == 0)
{
switch (data[3])
{
case 0:
*dst++ = *src++;
break;
case 1:
count = 0;
bit = queue & 1;
queue >>= 1;
if (queue == 0)
{
queue = u16_unaligned(src);
src += 2;
bit_p = bit;
bit = queue & 1;
queue >>= 1;
if (bit_p)
queue |= 0x8000;
count = bit;
bit = queue & 1;
queue >>= 1;
}
else
{
count = bit;
bit = queue & 1;
queue >>= 1;
if (queue == 0)
{
queue = u16_unaligned(src);
src += 2;
bit_p = bit;
bit = queue & 1;
queue >>= 1;
if (bit_p)
queue |= 0x8000;
}
}
count = (count << 1) | bit;
offset = *(uint8_t *)src;
offset -= 256;
src++;
count += 2;
while (count--)
{
*dst = *(dst + offset);
dst++;
}
break;
case 2:
count = u16_unaligned(src);
offset = (count >> data[5]) - (1 << (16 - data[5]));
count &= (1 << data[5]) - 1;
src += 2;
if (!count)
{
count = *(uint8_t *)src;
src++;
}
if (!count)
{
done = true;
break;
}
count += 2;
while (count--)
{
*dst = *(dst + offset);
dst++;
}
break;
}
if (done)
break;
continue;
}
else
{
switch (data[4])
{
case 0:
*dst++ = *src++;
break;
case 1:
count = 0;
bit = queue & 1;
queue >>= 1;
if (queue == 0)
{
queue = u16_unaligned(src);
src += 2;
bit_p = bit;
bit = queue & 1;
queue >>= 1;
if (bit_p)
queue |= 0x8000;
count = bit;
bit = queue & 1;
queue >>= 1;
}
else
{
count = bit;
bit = queue & 1;
queue >>= 1;
if (queue == 0)
{
queue = u16_unaligned(src);
src += 2;
bit_p = bit;
bit = queue & 1;
queue >>= 1;
if (bit_p)
queue |= 0x8000;
}
}
count = (count << 1) | bit;
offset = *(uint8_t *)src;
offset -= 256;
src++;
count += 2;
while (count--)
{
*dst = *(dst + offset);
dst++;
}
break;
case 2:
count = u16_unaligned(src);
offset = (count >> data[5]) - (1 << (16 - data[5]));
count &= (1 << data[5]) - 1;
src += 2;
if (!count)
{
count = *(uint8_t *)src;
src++;
}
if (!count)
{
done = true;
break;
}
count += 2;
while (count--)
{
*dst = *(dst + offset);
dst++;
}
break;
}
if (done)
break;
continue;
}
}
}
return dst - out;
}
bool CheradPlayer::load(const std::string &filename, const CFileProvider &fp)
{
binistream *f = fp.open(filename); if(!f) return false;
// file validation
if (!fp.extension(filename, ".hsq") &&
!fp.extension(filename, ".sqx") &&
!fp.extension(filename, ".sdb") &&
!fp.extension(filename, ".agd") &&
!fp.extension(filename, ".ha2"))
{
#ifdef DEBUG
AdPlug_LogWrite("HERAD: Unsupported file extension.\n");
#endif
fp.close(f);
return false;
}
int size = fp.filesize(f);
if (size < HERAD_MIN_SIZE)
{
#ifdef DEBUG
AdPlug_LogWrite("HERAD: File size is too small.\n");
#endif
fp.close(f);
return false;
}
if (size > HERAD_MAX_SIZE)
{
#ifdef DEBUG
AdPlug_LogWrite("HERAD: File size is too big.\n");
#endif
fp.close(f);
return false;
}
// Read entire file into memory
uint8_t * data = new uint8_t[size];
f->readString((char *)data, size);
fp.close(f);
// Detect compression
if (isHSQ(data, size))
{
comp = HERAD_COMP_HSQ;
uint8_t * out = new uint8_t[HERAD_MAX_SIZE];
memset(out, 0, HERAD_MAX_SIZE);
size = HSQ_decompress(data, size, out);
delete[] data;
data = new uint8_t[size];
memcpy(data, out, size);
delete[] out;
}
else if (isSQX(data))
{
comp = HERAD_COMP_SQX;
uint8_t * out = new uint8_t[HERAD_MAX_SIZE];
memset(out, 0, HERAD_MAX_SIZE);
size = SQX_decompress(data, size, out);
delete[] data;
data = new uint8_t[size];
memcpy(data, out, size);
delete[] out;
}
else
{
comp = HERAD_COMP_NONE;
}
// Process file header
uint16_t offset;
if (size < HERAD_HEAD_SIZE)
{
#ifdef DEBUG
AdPlug_LogWrite("HERAD: File size is too small.\n");
#endif
goto failure;
}
if ( size < *(uint16_t *)data )
{
#ifdef DEBUG
AdPlug_LogWrite("HERAD: Incorrect offset / file size.\n");
#endif
goto failure;
}
nInsts = (size - *(uint16_t *)data) / HERAD_INST_SIZE;
if ( nInsts == 0 )
{
#ifdef DEBUG
AdPlug_LogWrite("HERAD: M32 files are not supported.\n");
#endif
goto failure;
}
offset = *(uint16_t *)(data + 2);
if ( offset != 0x32 && offset != 0x52 )
{
#ifdef DEBUG
AdPlug_LogWrite("HERAD: Wrong first track offset.\n");
#endif
goto failure;
}
AGD = offset == 0x52;
wLoopStart = *(uint16_t *)(data + 0x2C);
wLoopEnd = *(uint16_t *)(data + 0x2E);
wLoopCount = *(uint16_t *)(data + 0x30);
wSpeed = *(uint16_t *)(data + 0x32);
if (wSpeed == 0)
{
#ifdef DEBUG
AdPlug_LogWrite("HERAD: Speed is not defined.\n");
#endif
goto failure;
}
nTracks = 0;
for (int i = 0; i < HERAD_MAX_TRACKS; i++)
{
if ( *(uint16_t *)(data + 2 + i * 2) == 0 )
break;
nTracks++;
}
track = new herad_trk[nTracks];
chn = new herad_chn[nTracks];
for (int i = 0; i < nTracks; i++)
{
offset = *(uint16_t *)(data + 2 + i * 2) + 2;
uint16_t next = (i < HERAD_MAX_TRACKS - 1 ? *(uint16_t *)(data + 2 + (i + 1) * 2) + 2 : *(uint16_t *)data);
if (next <= 2) next = *(uint16_t *)data;
track[i].size = next - offset;
track[i].data = new uint8_t[track[i].size];
memcpy(track[i].data, data + offset, track[i].size);
}
inst = new herad_inst[nInsts];
offset = *(uint16_t *)data;
v2 = true;
for (int i = 0; i < nInsts; i++)
{
memcpy(inst[i].data, data + offset + i * HERAD_INST_SIZE, HERAD_INST_SIZE);
if (v2 && inst[i].param.mode == HERAD_INSTMODE_SDB1)
v2 = false;
}
delete[] data;
goto good;
failure:
delete[] data;
return false;
good:
rewind(0);
return true;
}
void CheradPlayer::rewind(int subsong)
{
uint32_t j;
wTime = 0;
songend = false;
ticks_pos = -1; // there's always 1 excess tick at start
total_ticks = 0;
loop_pos = -1;
loop_times = 1;
for (int i = 0; i < nTracks; i++)
{
track[i].pos = 0;
j = 0;
while (track[i].pos < track[i].size)
{
j += GetTicks(i);
switch (track[i].data[track[i].pos++] & 0xF0)
{
case 0x80: // Note Off
track[i].pos += (v2 ? 1 : 2);
break;
case 0x90: // Note On
case 0xA0: // Unused
case 0xB0: // Unused
track[i].pos += 2;
break;
case 0xC0: // Program Change
case 0xD0: // Aftertouch
case 0xE0: // Pitch Bend
track[i].pos++;
break;
default:
track[i].pos = track[i].size;
break;
}
}
if (j > total_ticks)
total_ticks = j;
track[i].pos = 0;
track[i].counter = 0;
track[i].ticks = 0;
chn[i].program = 0;
chn[i].playprog = 0;
chn[i].note = 0;
chn[i].keyon = false;
chn[i].bend = HERAD_BEND_CENTER;
chn[i].slide_dur = 0;
}
if (v2)
{
if (!wLoopStart || wLoopCount) wLoopStart = 1; // if loop not specified, start from beginning
if (!wLoopEnd || wLoopCount) wLoopEnd = getpatterns() + 1; // till the end
if (wLoopCount) wLoopCount = 0; // repeats forever
}
opl->init();
opl->write(1, 32); // Enable Waveform Select
opl->write(0xBD, 0); // Disable Percussion Mode
opl->write(8, 64); // Enable Note-Sel
if (AGD)
{
opl->setchip(1);
opl->write(5, 1); // Enable OPL3
opl->write(4, 0); // Disable 4OP Mode
opl->setchip(0);
}
}
/*
* Get delta ticks (t - track index)
*/
uint32_t CheradPlayer::GetTicks(uint8_t t)
{
uint32_t result = 0;
do
{
result <<= 7;
result |= track[t].data[track[t].pos] & 0x7F;
} while (track[t].data[track[t].pos++] & 0x80 && track[t].pos < track[t].size);
return result;
}
/*
* Execute event (t - track index)
*/
void CheradPlayer::executeCommand(uint8_t t)
{
uint8_t status, note, par;
if (t >= nTracks)
return;
if (t >= (AGD ? HERAD_NUM_VOICES * 2 : HERAD_NUM_VOICES))
{
track[t].pos = track[t].size;
return;
}
// execute MIDI command
status = track[t].data[track[t].pos++];
if (status == 0xFF)
{
track[t].pos = track[t].size;
}
else
{
switch (status & 0xF0)
{
case 0x80: // Note Off
note = track[t].data[track[t].pos++];
par = (v2 ? 0 : track[t].data[track[t].pos++]);
ev_noteOff(t, note, par);
break;
case 0x90: // Note On
note = track[t].data[track[t].pos++];
par = track[t].data[track[t].pos++];
ev_noteOn(t, note, par);
break;
case 0xA0: // Unused
case 0xB0: // Unused
track[t].pos += 2;
break;
case 0xC0: // Program Change
par = track[t].data[track[t].pos++];
ev_programChange(t, par);
break;
case 0xD0: // Aftertouch
par = track[t].data[track[t].pos++];
ev_aftertouch(t, par);
break;
case 0xE0: // Pitch Bend
par = track[t].data[track[t].pos++];
ev_pitchBend(t, par);
break;
default:
track[t].pos = track[t].size;
break;
}
}
}
void CheradPlayer::ev_noteOn(uint8_t ch, uint8_t note, uint8_t vel)
{
int8_t macro;
if (chn[ch].keyon)
{
// turn off last active note
chn[ch].keyon = false;
playNote(ch, chn[ch].note, HERAD_NOTE_OFF);
}
if (v2 && inst[chn[ch].program].param.mode == HERAD_INSTMODE_KMAP)
{
// keymap is used
int8_t mp = note - (inst[chn[ch].program].keymap.offset + 24);
if (mp < 0 || mp >= HERAD_INST_SIZE - 4)
return; // if not in range, skip note
chn[ch].playprog = inst[chn[ch].program].keymap.index[mp];
changeProgram(ch, chn[ch].playprog);
}
chn[ch].note = note;
chn[ch].keyon = true;
chn[ch].bend = HERAD_BEND_CENTER;
if (v2 && inst[chn[ch].playprog].param.mode == HERAD_INSTMODE_KMAP)
return; // single keymapped instrument can't be keymap (avoid recursion)
playNote(ch, note, HERAD_NOTE_ON);
macro = inst[chn[ch].playprog].param.mc_mod_out_vel;
if (macro != 0)
macroModOutput(ch, chn[ch].playprog, macro, vel);
macro = inst[chn[ch].playprog].param.mc_car_out_vel;
if (macro != 0)
macroCarOutput(ch, chn[ch].playprog, macro, vel);
macro = inst[chn[ch].playprog].param.mc_fb_vel;
if (macro != 0)
macroFeedback(ch, chn[ch].playprog, macro, vel);
}
void CheradPlayer::ev_noteOff(uint8_t ch, uint8_t note, uint8_t vel)
{
if (note != chn[ch].note || !chn[ch].keyon)
return;
chn[ch].keyon = false;
playNote(ch, note, HERAD_NOTE_OFF);
}
void CheradPlayer::ev_programChange(uint8_t ch, uint8_t prog)
{
if (prog >= nInsts) // out of index
return;
chn[ch].program = prog;
chn[ch].playprog = prog;
changeProgram(ch, prog);
}
void CheradPlayer::ev_aftertouch(uint8_t ch, uint8_t vel)
{
int8_t macro;
if (v2) // version 2 ignores this event
return;
macro = inst[chn[ch].playprog].param.mc_mod_out_at;
if (macro != 0)
macroModOutput(ch, chn[ch].playprog, macro, vel);
macro = inst[chn[ch].playprog].param.mc_car_out_at;
if (macro != 0 && inst[chn[ch].playprog].param.mc_car_out_vel != 0)
macroCarOutput(ch, chn[ch].playprog, macro, vel);
macro = inst[chn[ch].playprog].param.mc_fb_at;
if (macro != 0)
macroFeedback(ch, chn[ch].playprog, macro, vel);
}
void CheradPlayer::ev_pitchBend(uint8_t ch, uint8_t bend)
{
chn[ch].bend = bend;
if (chn[ch].keyon) // update pitch
playNote(ch, chn[ch].note, HERAD_NOTE_UPDATE);
}
/*
* Play Note (c - channel, note number, note state - see HERAD_NOTE_*)
*/
void CheradPlayer::playNote(uint8_t c, uint8_t note, uint8_t state)
{
if (inst[chn[c].playprog].param.mc_transpose != 0)
macroTranspose(¬e, chn[c].playprog);
note = (note - 24) & 0xFF;
if (state != HERAD_NOTE_UPDATE && note >= 0x60)
note = 0; // clip too low/high notes
int8_t oct = note / HERAD_NUM_NOTES;
int8_t key = note % HERAD_NUM_NOTES;
if (state != HERAD_NOTE_UPDATE && inst[chn[c].playprog].param.mc_slide_dur)
{
chn[c].slide_dur = (state == HERAD_NOTE_ON ? inst[chn[c].playprog].param.mc_slide_dur : 0);
}
uint8_t bend = chn[c].bend;
int16_t amount, detune = 0;
uint8_t amount_lo, amount_hi;
if (!(inst[chn[c].playprog].param.mc_slide_coarse & 1))
{ // fine tune
if (bend - HERAD_BEND_CENTER < 0)
{ // slide down
amount = HERAD_BEND_CENTER - bend;
amount_lo = (amount >> 5);
amount_hi = (amount << 3) & 0xFF;
key -= amount_lo;
if (key < 0)
{
key += HERAD_NUM_NOTES;
oct--;
}
if (oct < 0)
{
key = 0;
oct = 0;
}
detune = -1 * ((fine_bend[key] * amount_hi) >> 8);
}
else
{ // slide up
amount = bend - HERAD_BEND_CENTER;
amount_lo = (amount >> 5);
amount_hi = (amount << 3) & 0xFF;
key += amount_lo;
if (key >= HERAD_NUM_NOTES)
{
key -= HERAD_NUM_NOTES;
oct++;
}
detune = (fine_bend[key + 1] * amount_hi) >> 8;
}
}
else
{ // coarse tune
uint8_t offset;
if (bend - HERAD_BEND_CENTER < 0)
{ // slide down
amount = HERAD_BEND_CENTER - bend;
key -= amount / 5;
if (key < 0)
{
key += HERAD_NUM_NOTES;
oct--;
}
if (oct < 0)
{
key = 0;
oct = 0;
}
offset = (amount % 5) + (key >= 6 ? 5 : 0);
detune = -1 * coarse_bend[offset];
}
else
{ // slide up
amount = bend - HERAD_BEND_CENTER;
key += amount / 5;
if (key >= HERAD_NUM_NOTES)
{
key -= HERAD_NUM_NOTES;
oct++;
}
offset = (amount % 5) + (key >= 6 ? 5 : 0);
detune = coarse_bend[offset];
}
}
setFreq(c, oct, FNum[key] + detune, state != HERAD_NOTE_OFF);
}
/*
* Set Frequency and Key (c - channel, octave, frequency, note on)
*/
void CheradPlayer::setFreq(uint8_t c, uint8_t oct, uint16_t freq, bool on)
{
uint8_t reg, val;
if (c >= HERAD_NUM_VOICES) opl->setchip(1);
reg = 0xA0 + (c % HERAD_NUM_VOICES);
val = freq & 0xFF;
opl->write(reg, val);
reg = 0xB0 + (c % HERAD_NUM_VOICES);
val = ((freq >> 8) & 3) |
((oct & 7) << 2) |
((on ? 1 : 0) << 5);
opl->write(reg, val);
if (c >= HERAD_NUM_VOICES) opl->setchip(0);
}
/*
* Change Program (c - channel, i - instrument index)
*/
void CheradPlayer::changeProgram(uint8_t c, uint8_t i)
{
uint8_t reg, val;
if (v2 && inst[i].param.mode == HERAD_INSTMODE_KMAP)
return;
if (c >= HERAD_NUM_VOICES) opl->setchip(1);
// Amp Mod / Vibrato / EG type / Key Scaling / Multiple
reg = 0x20 + slot_offset[c % HERAD_NUM_VOICES];
val = (inst[i].param.mod_mul & 15) |
((inst[i].param.mod_ksr & 1) << 4) |
((inst[i].param.mod_eg > 0 ? 1 : 0) << 5) |
((inst[i].param.mod_vib & 1) << 6) |
((inst[i].param.mod_am & 1) << 7);
opl->write(reg, val);
reg += 3;
val = (inst[i].param.car_mul & 15) |
((inst[i].param.car_ksr & 1) << 4) |
((inst[i].param.car_eg > 0 ? 1 : 0) << 5) |
((inst[i].param.car_vib & 1) << 6) |
((inst[i].param.car_am & 1) << 7);
opl->write(reg, val);
// Key scaling level / Output level
reg = 0x40 + slot_offset[c % HERAD_NUM_VOICES];
val = (inst[i].param.mod_out & 63) |
((inst[i].param.mod_ksl & 3) << 6);
opl->write(reg, val);
reg += 3;
val = (inst[i].param.car_out & 63) |
((inst[i].param.car_ksl & 3) << 6);
opl->write(reg, val);
// Attack Rate / Decay Rate
reg = 0x60 + slot_offset[c % HERAD_NUM_VOICES];
val = (inst[i].param.mod_D & 15) |
((inst[i].param.mod_A & 15) << 4);
opl->write(reg, val);
reg += 3;
val = (inst[i].param.car_D & 15) |
((inst[i].param.car_A & 15) << 4);
opl->write(reg, val);
// Sustain Level / Release Rate
reg = 0x80 + slot_offset[c % HERAD_NUM_VOICES];
val = (inst[i].param.mod_R & 15) |
((inst[i].param.mod_S & 15) << 4);
opl->write(reg, val);
reg += 3;
val = (inst[i].param.car_R & 15) |
((inst[i].param.car_S & 15) << 4);
opl->write(reg, val);
// Panning / Feedback strength / Connection type
reg = 0xC0 + (c % HERAD_NUM_VOICES);
val = (inst[i].param.con > 0 ? 0 : 1) |
((inst[i].param.feedback & 7) << 1) |
((AGD ? (inst[i].param.pan == 0 || inst[i].param.pan > 3 ? 3 : inst[i].param.pan) : 0) << 4);
opl->write(reg, val);
// Wave Select
reg = 0xE0 + slot_offset[c % HERAD_NUM_VOICES];
val = inst[i].param.mod_wave & (AGD ? 7 : 3);
opl->write(reg, val);
reg += 3;
val = inst[i].param.car_wave & (AGD ? 7 : 3);
opl->write(reg, val);
if (c >= HERAD_NUM_VOICES) opl->setchip(0);
}
/*
* Macro: Change Modulator Output (c - channel, i - instrument index, sensitivity, level)
*/
void CheradPlayer::macroModOutput(uint8_t c, uint8_t i, int8_t sens, uint8_t level)
{
uint8_t reg, val;
uint16_t output;
if (sens < -4 || sens > 4)
return;
if (sens < 0)
{
output = (level >> (sens + 4) > 63 ? 63 : level >> (sens + 4));
}
else
{
output = ((0x80 - level) >> (4 - sens) > 63 ? 63 : (0x80 - level) >> (4 - sens));
}
output += inst[i].param.mod_out;
if (output > 63) output = 63;
if (c >= HERAD_NUM_VOICES) opl->setchip(1);
// Key scaling level / Output level
reg = 0x40 + slot_offset[c % HERAD_NUM_VOICES];
val = (output & 63) |
((inst[i].param.mod_ksl & 3) << 6);
opl->write(reg, val);
if (c >= HERAD_NUM_VOICES) opl->setchip(0);
}
/*
* Macro: Change Carrier Output (c - channel, i - instrument index, sensitivity, level)
*/
void CheradPlayer::macroCarOutput(uint8_t c, uint8_t i, int8_t sens, uint8_t level)
{
uint8_t reg, val;
uint16_t output;
if (sens < -4 || sens > 4)
return;
if (sens < 0)
{
output = (level >> (sens + 4) > 63 ? 63 : level >> (sens + 4));
}
else
{
output = ((0x80 - level) >> (4 - sens) > 63 ? 63 : (0x80 - level) >> (4 - sens));
}
output += inst[i].param.car_out;
if (output > 63) output = 63;
if (c >= HERAD_NUM_VOICES) opl->setchip(1);
// Key scaling level / Output level
reg = 0x43 + slot_offset[c % HERAD_NUM_VOICES];
val = (output & 63) |
((inst[i].param.car_ksl & 3) << 6);
opl->write(reg, val);
if (c >= HERAD_NUM_VOICES) opl->setchip(0);
}
/*
* Macro: Change Feedback (c - channel, i - instrument index, sensitivity, level)
*/
void CheradPlayer::macroFeedback(uint8_t c, uint8_t i, int8_t sens, uint8_t level)
{
uint8_t reg, val;
uint8_t feedback;
if (sens < -6 || sens > 6)
return;
if (sens < 0)
{
feedback = (level >> (sens + 7) > 7 ? 7 : level >> (sens + 7));
}
else
{
feedback = ((0x80 - level) >> (7 - sens) > 7 ? 7 : (0x80 - level) >> (7 - sens));
}
feedback += inst[i].param.feedback;
if (feedback > 7) feedback = 7;
if (c >= HERAD_NUM_VOICES) opl->setchip(1);
// Panning / Feedback strength / Connection type
reg = 0xC0 + (c % HERAD_NUM_VOICES);
val = (inst[i].param.con > 0 ? 0 : 1) |
((feedback & 7) << 1) |
((AGD ? (inst[i].param.pan == 0 || inst[i].param.pan > 3 ? 3 : inst[i].param.pan) : 0) << 4);
opl->write(reg, val);
if (c >= HERAD_NUM_VOICES) opl->setchip(0);
}
/*
* Macro: Root Note Transpose (note, i - instrument index)
*/
void CheradPlayer::macroTranspose(uint8_t * note, uint8_t i)
{
uint8_t tran = inst[i].param.mc_transpose;
uint8_t diff = (tran - 0x31) & 0xFF;
if (v2 && diff < 0x60)
*note = (diff + 0x18) & 0xFF;
else
*note = (*note + tran) & 0xFF;
}
/*
* Macro: Pitch Bend Slide (c - channel)
*/
void CheradPlayer::macroSlide(uint8_t c)
{
if (!chn[c].slide_dur)
return;
chn[c].slide_dur--;
chn[c].bend += inst[chn[c].playprog].param.mc_slide_range;
if (!(chn[c].note & 0x7F))
return;
playNote(c, chn[c].note, HERAD_NOTE_UPDATE);
}
void CheradPlayer::processEvents()
{
uint8_t i;
songend = true;
if (wLoopStart && wLoopEnd && (ticks_pos + 1) % HERAD_MEASURE_TICKS == 0 && (ticks_pos + 1) / HERAD_MEASURE_TICKS + 1 == wLoopStart)
{
loop_pos = ticks_pos;
for (i = 0; i < nTracks; i++)
{
loop_data[i].counter = track[i].counter;
loop_data[i].ticks = track[i].ticks;
loop_data[i].pos = track[i].pos;
}
}
for (i = 0; i < nTracks; i++)
{
if (chn[i].slide_dur > 0 && chn[i].keyon)
macroSlide(i);
if (track[i].pos >= track[i].size)
continue;
songend = false; // track is not finished
if (!track[i].counter)
{
bool first = track[i].pos == 0;
track[i].ticks = GetTicks(i);
if (first && track[i].ticks)
track[i].ticks++; // workaround to synchronize tracks (there's always 1 excess tick at start)
}
if (++track[i].counter >= track[i].ticks)
{
track[i].counter = 0;
while (track[i].pos < track[i].size)
{
executeCommand(i);
if (track[i].pos >= track[i].size) {
break;
}
else if (!track[i].data[track[i].pos]) // if next delay is zero
{
track[i].pos++;
}
else break;
}
}
else if (track[i].ticks >= 0x8000)
{
track[i].pos = track[i].size;
track[i].counter = track[i].ticks;
}
}
if (!songend)
ticks_pos++;
if (wLoopStart && wLoopEnd && (ticks_pos == total_ticks || (ticks_pos % HERAD_MEASURE_TICKS == 0 && ticks_pos / HERAD_MEASURE_TICKS + 1 == wLoopEnd)))
{
#ifdef HERAD_USE_LOOPING
if (!wLoopCount)
songend = true;
else if (songend && loop_times < wLoopCount)
songend = false;
if (!wLoopCount || loop_times < wLoopCount)
{
ticks_pos = loop_pos;
for (i = 0; i < nTracks; i++)
{
track[i].counter = loop_data[i].counter;
track[i].ticks = loop_data[i].ticks;
track[i].pos = loop_data[i].pos;
}
if (wLoopCount)
loop_times++;
}
#endif
}
}
bool CheradPlayer::update()
{
wTime = wTime - 256;
if (wTime < 0)
{
wTime = wTime + wSpeed;
processEvents();
}
return !songend;
}
|
c4c067a2a4676f506b562c6d5df58909fde25828 | 2fbeb09a417bd678963ee8417766dade77dcd4c1 | /game_framework/systems/item_system.cpp | 790661c169cab99879fd2e25a2af9ce137cf343f | [] | no_license | Kartezjan/Augmentations | 5ebdb5b770e99a3c8e6ee79ec7db3a9b76c3e3a7 | d8397cf0951bdbb66d8be14173f36ccbe733586e | refs/heads/master | 2021-04-15T06:52:56.278827 | 2016-02-29T22:34:34 | 2016-02-29T22:34:34 | 52,829,837 | 0 | 0 | null | 2016-02-29T22:32:41 | 2016-02-29T22:32:41 | null | UTF-8 | C++ | false | false | 6,992 | cpp | item_system.cpp | #include "item_system.h"
#include "../messages/intent_message.h"
#include "../messages/trigger_hit_confirmation_message.h"
#include "../messages/trigger_hit_request_message.h"
#include "../messages/item_slot_transfer_request.h"
#include "entity_system/world.h"
#include "../components/item_component.h"
#include "../components/physics_component.h"
#include "../components/force_joint_component.h"
#include "../components/item_slot_transfers_component.h"
#include "../shared/inventory_utils.h"
#include "../shared/inventory_slot.h"
void item_system::handle_trigger_confirmations_as_pick_requests() {
auto& confirmations = parent_world.get_message_queue<messages::trigger_hit_confirmation_message>();
for (auto& e : confirmations) {
auto* item_slot_transfers = e.detector_body->find<components::item_slot_transfers>();
auto* item = e.trigger->find<components::item>();
if (item_slot_transfers && item && e.domain == detection_domain::WORLD_ITEMS) {
messages::item_slot_transfer_request request;
request.item = e.trigger;
request.target_slot = determine_pickup_target_slot(e.trigger, e.detector_body);
if (request.target_slot.alive()) {
if (check_timeout_and_reset(item_slot_transfers->pickup_timeout)) {
parent_world.post_message(request);
}
}
else {
// TODO: post gui message
}
}
}
}
void item_system::handle_throw_item_intents() {
auto& requests = parent_world.get_message_queue<messages::intent_message>();
for (auto& r : requests) {
if (r.intent == intent_type::THROW_PRIMARY_ITEM
|| r.intent == intent_type::THROW_SECONDARY_ITEM
) {
if (r.subject->find<components::item_slot_transfers>()) {
auto hand = map_primary_action_to_secondary_hand_if_primary_empty(r.subject, intent_type::THROW_SECONDARY_ITEM == r.intent);
if (hand.has_items()) {
messages::item_slot_transfer_request request;
request.item = hand->items_inside[0];
parent_world.post_message(request);
}
}
}
}
}
void item_system::handle_holster_item_intents() {
auto& requests = parent_world.get_message_queue<messages::intent_message>();
for (auto& r : requests) {
if (r.intent == intent_type::HOLSTER_PRIMARY_ITEM
|| r.intent == intent_type::HOLSTER_SECONDARY_ITEM
) {
if (r.subject->find<components::item_slot_transfers>()) {
auto hand = map_primary_action_to_secondary_hand_if_primary_empty(r.subject, intent_type::HOLSTER_SECONDARY_ITEM == r.intent);
if (hand.has_items()) {
messages::item_slot_transfer_request request;
request.item = hand->items_inside[0];
request.target_slot = determine_hand_holstering_slot(hand->items_inside[0], r.subject);
parent_world.post_message(request);
}
}
}
}
}
void components::item_slot_transfers::interrupt_mounting() {
mounting.current_item.unset();
mounting.intented_mounting_slot.unset();
}
void item_system::process_mounting_and_unmounting() {
for (auto& e : targets) {
auto& item_slot_transfers = e->get<components::item_slot_transfers>();
auto& currently_mounted_item = item_slot_transfers.mounting.current_item;
if (currently_mounted_item.alive()) {
auto& item = currently_mounted_item->get<components::item>();
if (item.current_slot != item_slot_transfers.mounting.intented_mounting_slot) {
item_slot_transfers.interrupt_mounting();
}
else {
assert(item.intended_mounting != item.current_mounting);
if (item.montage_time_left_ms > 0) {
item.montage_time_left_ms -= delta_milliseconds();
}
else {
item.current_mounting = item.intended_mounting;
if (item.current_mounting == components::item::UNMOUNTED) {
messages::item_slot_transfer_request after_unmount_transfer;
after_unmount_transfer.item = currently_mounted_item;
after_unmount_transfer.target_slot = item.target_slot_after_unmount;
parent_world.post_message(after_unmount_transfer);
}
}
}
}
if (currently_mounted_item.dead()) {
item_slot_transfers.mounting = components::item_slot_transfers::find_suitable_montage_operation(e);
}
}
}
void item_system::consume_item_slot_transfer_requests() {
auto& requests = parent_world.get_message_queue<messages::item_slot_transfer_request>();
for (auto& r : requests) {
auto root1 = get_root_container(r.item);
auto root2 = get_root_container(r.target_slot.container_entity);
auto& item = r.item->get<components::item>();
if (root1 != root2 || r.target_slot == item.current_slot) {
assert(0);
continue;
}
if (item.current_mounting == components::item::MOUNTED) {
item.request_unmount(r.target_slot);
item.mark_parent_enclosing_containers_for_unmount();
continue;
}
auto& item_physics = r.item->get<components::physics>();
auto& container_transform = r.target_slot.container_entity->get<components::transform>();
auto& force_joint = r.item->get<components::force_joint>();
auto previous_slot = item.current_slot;
previous_slot.remove_item(r.item);
if (r.target_slot.alive() && !r.target_slot.can_contain(r.item)) {
assert(0);
previous_slot.add_item(r.item);
continue;
}
r.target_slot.add_item(r.item);
bool is_drop_request = previous_slot.alive() && r.target_slot.dead();
if (is_drop_request) {
item_physics.set_active(true);
item_physics.set_transform(previous_slot.container_entity);
item_physics.apply_impulse(vec2().set_from_degrees(container_transform.rotation).set_length(10), vec2().random_on_circle(20));
r.item->disable(force_joint);
}
else {
if (r.target_slot.should_item_inside_keep_physical_body()) {
item_physics.set_active(true);
auto& item_joint_def = force_joint;
auto& attachment_joint_def = r.target_slot->attachment_force_joint_def;
item_joint_def.distance_when_force_easing_starts = attachment_joint_def.distance_when_force_easing_starts;
item_joint_def.force_towards_chased_entity = attachment_joint_def.force_towards_chased_entity;
item_joint_def.power_of_force_easing_multiplier = attachment_joint_def.power_of_force_easing_multiplier;
item_joint_def.chased_entity = r.target_slot.container_entity;
auto target_attachment_offset_from_container = attachment_joint_def.chased_entity_offset;
target_attachment_offset_from_container.pos += item_physics.get_aabb_size().get_sticking_offset(r.target_slot->attachment_sticking_mode);
target_attachment_offset_from_container.pos += item.attachment_offsets_per_sticking_mode[size_t(r.target_slot->attachment_sticking_mode)];
item_joint_def.chased_entity_offset = target_attachment_offset_from_container;
r.item->enable(item_joint_def);
item_physics.set_transform(r.target_slot.container_entity->get<components::transform>() + target_attachment_offset_from_container);
}
else {
item_physics.set_active(false);
r.item->disable(force_joint);
}
}
if (item.current_slot->items_need_mounting) {
item.intended_mounting = components::item::MOUNTED;
}
}
requests.clear();
}
|
e1dea825fd876525b21495ed9e5929d26db5ffc0 | 79a634d9357a750cbd0efea04d932938e1b7f632 | /Contest/USACO/CHAP2/Sec2.1/frac1.cpp | 461b6844e7dcb099c7c17d5b0974f0bf6a05449c | [] | no_license | hphp/Algorithm | 5f42fe188422427a7762dbbe7af539b89fa796ed | ccbb368a37eed1b0cb37356026b299380f9c008b | refs/heads/master | 2016-09-06T02:24:43.141927 | 2014-05-27T00:49:44 | 2014-05-27T00:49:44 | 14,009,913 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 997 | cpp | frac1.cpp | /*
ID: hanjiatong1
PROG: frac1
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#define E 0.000000
#define N 161
using namespace std;
struct Frac
{
int n;
int d;
}f[N*N];
bool cmp(Frac a , Frac b)
{
double aa = a.n*1.0/a.d;
double bb = b.n*1.0/b.d;
if(aa < bb+E)
return 1;
return 0;
}
int gcd(int a,int b)
{
if(b == 0)
return a;
return gcd(b,a%b);
}
int main() {
std::ofstream fout ("frac1.out");
std::ifstream fin ("frac1.in");
int n;
fin >> n;
int cnt = 0;
f[cnt].n = 0;
f[cnt++].d = 1;
f[cnt].n = 1;
f[cnt++].d = 1;
for(int i=2;i<=n;i++)
for(int j=1;j<i;j++)
{
if(gcd(j,i)!=1)continue;
f[cnt].n = j;
f[cnt++].d = i;
}
sort(f,f+cnt,cmp);
for(int i=0;i<cnt;i++)
{
fout << f[i].n << '/' << f[i].d << endl;
}
return 0;
}
/*
Name:
Copyright:
Author:
Date: 16-06-10 21:06
Description:
*/
|
1cf3d99da06cc8e599a0d238cd5456e95329e604 | 46889ce97d827d287db87a85d543758096b1f814 | /src/materialsystem/shaderapidx11/shaderapidx11.h | 35156d67b07c56bb57c4ffe3271cab33a8472381 | [] | no_license | lachbr/SourceEngine | 8dbaf562fe0e8c3ca33b2f077420f15823177808 | e1bab45d8e9774fe2fe473448009dbd59becd0e8 | refs/heads/master | 2022-04-10T19:33:46.206407 | 2020-02-29T22:18:32 | 2020-02-29T22:18:32 | 240,649,072 | 0 | 0 | null | 2020-02-16T00:15:05 | 2020-02-15T05:15:58 | C++ | WINDOWS-1252 | C++ | false | false | 29,947 | h | shaderapidx11.h | //===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======//
//
// Purpose:
//
// $NoKeywords: $
//
//===========================================================================//
#ifndef SHADERAPIDX11_H
#define SHADERAPIDX11_H
#ifdef _WIN32
#pragma once
#endif
#include <d3d11.h>
#include "shaderapidx9/shaderapibase.h"
#include "shaderapi/ishadershadow.h"
#include "materialsystem/idebugtextureinfo.h"
#include "shaderapidx9/hardwareconfig.h"
#include "imaterialinternal.h"
#include "shaderapidx9/meshbase.h"
#include "ShaderConstantBufferDx11.h"
#include "utllinkedlist.h"
#include "StatesDx11.h"
#include "TextureDx11.h"
#include "meshdx11.h"
#include "materialsystem/imesh.h"
#include "utlstack.h"
//-----------------------------------------------------------------------------
// Forward declarations
//-----------------------------------------------------------------------------
struct MaterialSystemHardwareIdentifier_t;
//-----------------------------------------------------------------------------
// A record describing the state on the board
//-----------------------------------------------------------------------------
struct DynamicStateDx11_t
{
MaterialFogMode_t m_FogMode;
float m_flFogStart;
float m_flFogEnd;
float m_flFogZ;
float m_flFogMaxDensity;
Vector4D m_AmbientLightCube[6];
LightDesc_t m_Lights[MAX_NUM_LIGHTS];
int m_NumLights;
};
struct MatrixItemDx11_t
{
DirectX::XMMATRIX m_Matrix;
int m_Flags;
};
//-----------------------------------------------------------------------------
// The Dx11 implementation of the shader API
//-----------------------------------------------------------------------------
class CShaderAPIDx11 : public CShaderAPIBase, public IDebugTextureInfo
{
typedef CShaderAPIBase BaseClass;
public:
// constructor, destructor
CShaderAPIDx11();
virtual ~CShaderAPIDx11();
// Methods of IShaderAPI
// NOTE: These methods have been ported over
public:
virtual void SetViewports( int nCount, const ShaderViewport_t *pViewports );
virtual int GetViewports( ShaderViewport_t *pViewports, int nMax ) const;
virtual void ClearBuffers( bool bClearColor, bool bClearDepth, bool bClearStencil, int renderTargetWidth, int renderTargetHeight );
virtual void ClearColor3ub( unsigned char r, unsigned char g, unsigned char b );
virtual void ClearColor4ub( unsigned char r, unsigned char g, unsigned char b, unsigned char a );
virtual void SetRasterState( const ShaderRasterState_t &state );
virtual void BindVertexShader( VertexShaderHandle_t hVertexShader );
virtual void BindGeometryShader( GeometryShaderHandle_t hGeometryShader );
virtual void BindPixelShader( PixelShaderHandle_t hPixelShader );
virtual void BindVertexBuffer( int nStreamID, IVertexBuffer *pVertexBuffer, int nOffsetInBytes, int nFirstVertex, int nVertexCount, VertexFormat_t fmt, int nRepetitions = 1 );
virtual void BindIndexBuffer( IIndexBuffer *pIndexBuffer, int nOffsetInBytes );
virtual void Draw( MaterialPrimitiveType_t primitiveType, int nFirstIndex, int nIndexCount );
void DrawIndexed( int nFirstIndex, int nIndexCount, int nBaseVertexLocation );
void DrawNotIndexed( int nFirstVertex, int nVertCount );
void DrawMesh( IMesh *pMesh );
virtual void UpdateConstantBuffer( ConstantBuffer_t cbuffer, void *pNewData );
virtual ConstantBuffer_t GetInternalConstantBuffer( int type );
virtual void BindPixelShaderConstantBuffer( ConstantBuffer_t );
virtual void BindVertexShaderConstantBuffer( ConstantBuffer_t );
virtual void BindGeometryShaderConstantBuffer( ConstantBuffer_t );
FORCEINLINE bool TextureIsAllocated( ShaderAPITextureHandle_t hTexture )
{
return m_Textures.IsValidIndex( hTexture ) && ( GetTexture( hTexture ).m_nFlags & CTextureDx11::IS_ALLOCATED );
}
// Methods of IShaderDynamicAPI
public:
virtual void GetBackBufferDimensions( int &nWidth, int &nHeight ) const;
public:
// Methods of CShaderAPIBase
virtual bool OnDeviceInit();
virtual void OnDeviceShutdown();
virtual void ReleaseShaderObjects();
virtual void RestoreShaderObjects();
virtual void BeginPIXEvent( unsigned long color, const char *szName )
{
}
virtual void EndPIXEvent()
{
}
virtual void AdvancePIXFrame()
{
}
// NOTE: These methods have not been ported over.
// IDebugTextureInfo implementation.
public:
virtual bool IsDebugTextureListFresh( int numFramesAllowed = 1 )
{
return false;
}
virtual void EnableDebugTextureList( bool bEnable )
{
}
virtual void EnableGetAllTextures( bool bEnable )
{
}
virtual KeyValues *GetDebugTextureList()
{
return NULL;
}
virtual int GetTextureMemoryUsed( TextureMemoryType eTextureMemory )
{
return 0;
}
virtual bool SetDebugTextureRendering( bool bEnable )
{
return false;
}
public:
// Other public methods
void Unbind( VertexShaderHandle_t hShader );
void Unbind( GeometryShaderHandle_t hShader );
void Unbind( PixelShaderHandle_t hShader );
void UnbindVertexBuffer( ID3D11Buffer *pBuffer );
void UnbindIndexBuffer( ID3D11Buffer *pBuffer );
void SetTopology( MaterialPrimitiveType_t topology );
void IssueStateChanges( bool bForce = false );
IMaterialInternal *GetBoundMaterial() const;
void GetMatrix( MaterialMatrixMode_t matrixMode, DirectX::XMMATRIX &dst );
D3D11_CULL_MODE GetCullMode() const;
private:
// Returns a d3d texture associated with a texture handle
virtual IDirect3DBaseTexture *GetD3DTexture( ShaderAPITextureHandle_t hTexture );
virtual void QueueResetRenderState()
{
}
virtual bool DoRenderTargetsNeedSeparateDepthBuffer() const;
void SetHardwareGammaRamp( float fGamma )
{
}
// Used to clear the transition table when we know it's become invalid.
void ClearSnapshots();
// Sets the mode...
bool SetMode( void *hwnd, int nAdapter, const ShaderDeviceInfo_t &info );
void ChangeVideoMode( const ShaderDeviceInfo_t &info )
{
}
// Called when the dx support level has changed
virtual void DXSupportLevelChanged()
{
}
virtual void EnableUserClipTransformOverride( bool bEnable )
{
}
virtual void UserClipTransform( const VMatrix &worldToView )
{
}
virtual bool GetUserClipTransform( VMatrix &worldToView )
{
return false;
}
// Sets the default *dynamic* state
void SetDefaultState();
// Returns the snapshot id for the shader state
StateSnapshot_t TakeSnapshot();
// Returns true if the state snapshot is transparent
bool IsTranslucent( StateSnapshot_t id ) const;
bool IsAlphaTested( StateSnapshot_t id ) const;
bool UsesVertexAndPixelShaders( StateSnapshot_t id ) const;
virtual bool IsDepthWriteEnabled( StateSnapshot_t id ) const;
// Gets the vertex format for a set of snapshot ids
VertexFormat_t ComputeVertexFormat( int numSnapshots, StateSnapshot_t *pIds ) const;
// Gets the vertex format for a set of snapshot ids
VertexFormat_t ComputeVertexUsage( int numSnapshots, StateSnapshot_t *pIds ) const;
// Begins a rendering pass that uses a state snapshot
void BeginPass( StateSnapshot_t snapshot );
// Uses a state snapshot
void UseSnapshot( StateSnapshot_t snapshot );
// Use this to get the mesh builder that allows us to modify vertex data
CMeshBuilder *GetVertexModifyBuilder();
// Sets the color to modulate by
void Color3f( float r, float g, float b );
void Color3fv( float const *pColor );
void Color4f( float r, float g, float b, float a );
void Color4fv( float const *pColor );
// Faster versions of color
void Color3ub( unsigned char r, unsigned char g, unsigned char b );
void Color3ubv( unsigned char const *rgb );
void Color4ub( unsigned char r, unsigned char g, unsigned char b, unsigned char a );
void Color4ubv( unsigned char const *rgba );
// Sets the lights
void SetLight( int lightNum, const LightDesc_t &desc );
void SetAmbientLight( float r, float g, float b );
void SetAmbientLightCube( Vector4D cube[6] );
virtual void SetLightingOrigin( Vector vLightingOrigin )
{
}
// Get the lights
int GetMaxLights( void ) const;
const LightDesc_t &GetLight( int lightNum ) const;
// Render state for the ambient light cube (vertex shaders)
void SetVertexShaderStateAmbientLightCube();
virtual void SetPixelShaderStateAmbientLightCube( int pshReg, bool bForceToBlack = false )
{
}
void SetPixelShaderStateAmbientLightCube( int pshReg )
{
}
virtual void GetDX9LightState( LightState_t *state ) const
{
}
float GetAmbientLightCubeLuminance( void )
{
return 0.0f;
}
void SetSkinningMatrices();
// Lightmap texture binding
void BindLightmap( TextureStage_t stage );
void BindLightmapAlpha( TextureStage_t stage )
{
}
void BindBumpLightmap( TextureStage_t stage );
void BindFullbrightLightmap( TextureStage_t stage );
void BindWhite( TextureStage_t stage );
void BindBlack( TextureStage_t stage );
void BindGrey( TextureStage_t stage );
void BindFBTexture( TextureStage_t stage, int textureIdex );
void CopyRenderTargetToTexture( ShaderAPITextureHandle_t texID )
{
}
void CopyRenderTargetToTextureEx( ShaderAPITextureHandle_t texID, int nRenderTargetID, Rect_t *pSrcRect, Rect_t *pDstRect )
{
}
// Special system flat normal map binding.
void BindFlatNormalMap( TextureStage_t stage );
void BindNormalizationCubeMap( TextureStage_t stage );
void BindSignedNormalizationCubeMap( TextureStage_t stage );
// Set the number of bone weights
void SetNumBoneWeights( int numBones );
// Flushes any primitives that are buffered
void FlushBufferedPrimitives();
// Creates/destroys Mesh
IMesh *CreateStaticMesh( VertexFormat_t fmt, const char *pTextureBudgetGroup, IMaterial *pMaterial = NULL );
void DestroyStaticMesh( IMesh *mesh );
// Gets the dynamic mesh; note that you've got to render the mesh
// before calling this function a second time. Clients should *not*
// call DestroyStaticMesh on the mesh returned by this call.
IMesh *GetDynamicMesh( IMaterial *pMaterial, int nHWSkinBoneCount, bool buffered, IMesh *pVertexOverride, IMesh *pIndexOverride );
IMesh *GetDynamicMeshEx( IMaterial *pMaterial, VertexFormat_t fmt, int nHWSkinBoneCount, bool buffered, IMesh *pVertexOverride, IMesh *pIndexOverride );
IVertexBuffer *GetDynamicVertexBuffer( IMaterial *pMaterial, bool buffered );
IIndexBuffer *GetDynamicIndexBuffer( IMaterial *pMaterial, bool buffered );
IMesh *GetFlexMesh();
// Renders a single pass of a material
void RenderPass( int nPass, int nPassCount );
// stuff related to matrix stacks
void MatrixMode( MaterialMatrixMode_t matrixMode );
void PushMatrix();
void PopMatrix();
void LoadMatrix( float *m );
void LoadBoneMatrix( int boneIndex, const float *m )
{
}
void MultMatrix( float *m );
void MultMatrixLocal( float *m );
void GetMatrix( MaterialMatrixMode_t matrixMode, float *dst );
void LoadIdentity( void );
void LoadCameraToWorld( void );
void Ortho( double left, double top, double right, double bottom, double zNear, double zFar );
void PerspectiveX( double fovx, double aspect, double zNear, double zFar );
void PerspectiveOffCenterX( double fovx, double aspect, double zNear, double zFar, double bottom, double top, double left, double right );
void PickMatrix( int x, int y, int width, int height );
void Rotate( float angle, float x, float y, float z );
void Translate( float x, float y, float z );
void Scale( float x, float y, float z );
void ScaleXY( float x, float y );
// Fog methods...
void FogMode( MaterialFogMode_t fogMode );
void FogStart( float fStart );
void FogEnd( float fEnd );
void SetFogZ( float fogZ );
void FogMaxDensity( float flMaxDensity );
void GetFogDistances( float *fStart, float *fEnd, float *fFogZ );
void FogColor3f( float r, float g, float b );
void FogColor3fv( float const *rgb );
void FogColor3ub( unsigned char r, unsigned char g, unsigned char b );
void FogColor3ubv( unsigned char const *rgb );
virtual void SceneFogColor3ub( unsigned char r, unsigned char g, unsigned char b );
virtual void SceneFogMode( MaterialFogMode_t fogMode );
virtual void GetSceneFogColor( unsigned char *rgb );
virtual MaterialFogMode_t GetSceneFogMode();
virtual int GetPixelFogCombo();
void SetHeightClipZ( float z );
void SetHeightClipMode( enum MaterialHeightClipMode_t heightClipMode );
void SetClipPlane( int index, const float *pPlane );
void EnableClipPlane( int index, bool bEnable );
void SetFastClipPlane( const float *pPlane );
void EnableFastClip( bool bEnable );
// We use smaller dynamic VBs during level transitions, to free up memory
virtual int GetCurrentDynamicVBSize( void );
virtual void DestroyVertexBuffers( bool bExitingLevel = false );
// Sets the vertex and pixel shaders
void SetVertexShaderIndex( int vshIndex );
void SetPixelShaderIndex( int pshIndex );
// Sets the constant register for vertex and pixel shaders
void SetVertexShaderConstant( int var, float const *pVec, int numConst = 1, bool bForce = false );
void SetPixelShaderConstant( int var, float const *pVec, int numConst = 1, bool bForce = false );
void SetBooleanVertexShaderConstant( int var, BOOL const *pVec, int numBools = 1, bool bForce = false )
{
Assert( 0 );
}
void SetIntegerVertexShaderConstant( int var, int const *pVec, int numIntVecs = 1, bool bForce = false )
{
Assert( 0 );
}
void SetBooleanPixelShaderConstant( int var, BOOL const *pVec, int numBools = 1, bool bForce = false )
{
Assert( 0 );
}
void SetIntegerPixelShaderConstant( int var, int const *pVec, int numIntVecs = 1, bool bForce = false )
{
Assert( 0 );
}
bool ShouldWriteDepthToDestAlpha( void ) const
{
Assert( 0 );
return false;
}
void InvalidateDelayedShaderConstants( void );
// Gamma<->Linear conversions according to the video hardware we're running on
float GammaToLinear_HardwareSpecific( float fGamma ) const
{
return 0.;
}
float LinearToGamma_HardwareSpecific( float fLinear ) const
{
return 0.;
}
//Set's the linear->gamma conversion textures to use for this hardware for both srgb writes enabled and disabled(identity)
void SetLinearToGammaConversionTextures( ShaderAPITextureHandle_t hSRGBWriteEnabledTexture, ShaderAPITextureHandle_t hIdentityTexture );
// Cull mode
void CullMode( MaterialCullMode_t cullMode );
// Force writes only when z matches. . . useful for stenciling things out
// by rendering the desired Z values ahead of time.
void ForceDepthFuncEquals( bool bEnable );
// Forces Z buffering on or off
void OverrideDepthEnable( bool bEnable, bool bDepthEnable );
// Sets the shade mode
void ShadeMode( ShaderShadeMode_t mode );
// Binds a particular material to render with
void Bind( IMaterial *pMaterial );
// Returns the nearest supported format
ImageFormat GetNearestSupportedFormat( ImageFormat fmt ) const;
ImageFormat GetNearestRenderTargetFormat( ImageFormat fmt ) const;
// Sets the texture state
void BindTexture( Sampler_t stage, ShaderAPITextureHandle_t textureHandle );
void UnbindTexture( ShaderAPITextureHandle_t textureHandle );
void SetRenderTarget( ShaderAPITextureHandle_t colorTextureHandle, ShaderAPITextureHandle_t depthTextureHandle )
{
SetRenderTargetEx( 0, colorTextureHandle, depthTextureHandle );
}
void SetRenderTargetEx( int nRenderTargetID, ShaderAPITextureHandle_t colorTextureHandle, ShaderAPITextureHandle_t depthTextureHandle );
// Indicates we're going to be modifying this texture
// TexImage2D, TexSubImage2D, TexWrap, TexMinFilter, and TexMagFilter
// all use the texture specified by this function.
void ModifyTexture( ShaderAPITextureHandle_t textureHandle );
// Texture management methods
void TexImage2D( int level, int cubeFace, ImageFormat dstFormat, int zOffset, int width, int height,
ImageFormat srcFormat, bool bSrcIsTiled, void *imageData );
void TexSubImage2D( int level, int cubeFace, int xOffset, int yOffset, int zOffset, int width, int height,
ImageFormat srcFormat, int srcStride, bool bSrcIsTiled, void *imageData );
bool TexLock( int level, int cubeFaceID, int xOffset, int yOffset,
int width, int height, CPixelWriter &writer );
void TexUnlock();
// These are bound to the texture, not the texture environment
void TexMinFilter( ShaderTexFilterMode_t texFilterMode );
void TexMagFilter( ShaderTexFilterMode_t texFilterMode );
void TexWrap( ShaderTexCoordComponent_t coord, ShaderTexWrapMode_t wrapMode );
void TexSetPriority( int priority );
ShaderAPITextureHandle_t CreateTexture(
int width,
int height,
int depth,
ImageFormat dstImageFormat,
int numMipLevels,
int numCopies,
int flags,
const char *pDebugName,
const char *pTextureGroupName );
void CreateTextures(
ShaderAPITextureHandle_t *pHandles,
int count,
int width,
int height,
int depth,
ImageFormat dstImageFormat,
int numMipLevels,
int numCopies,
int flags,
const char *pDebugName,
const char *pTextureGroupName );
ShaderAPITextureHandle_t CreateDepthTexture( ImageFormat renderFormat, int width, int height, const char *pDebugName, bool bTexture );
void DeleteTexture( ShaderAPITextureHandle_t textureHandle );
bool IsTexture( ShaderAPITextureHandle_t textureHandle );
bool IsTextureResident( ShaderAPITextureHandle_t textureHandle );
// stuff that isn't to be used from within a shader
void ClearBuffersObeyStencil( bool bClearColor, bool bClearDepth );
void PerformFullScreenStencilOperation( void );
void ReadPixels( int x, int y, int width, int height, unsigned char *data, ImageFormat dstFormat );
virtual void ReadPixels( Rect_t *pSrcRect, Rect_t *pDstRect, unsigned char *data, ImageFormat dstFormat, int nDstStride );
// Selection mode methods
int SelectionMode( bool selectionMode );
void SelectionBuffer( unsigned int *pBuffer, int size );
void ClearSelectionNames();
void LoadSelectionName( int name );
void PushSelectionName( int name );
void PopSelectionName();
void WriteHitRecord();
bool IsInSelectionMode() const;
void RegisterSelectionHit( float minz, float maxz );
void FlushHardware();
void ResetRenderState( bool bFullReset = true );
// Can we download textures?
virtual bool CanDownloadTextures() const;
// Board-independent calls, here to unify how shaders set state
// Implementations should chain back to IShaderUtil->BindTexture(), etc.
// Use this to begin and end the frame
void BeginFrame();
void EndFrame();
// returns current time
double CurrentTime() const;
// Get the current camera position in world space.
void GetWorldSpaceCameraPosition( float *pPos ) const;
void ForceHardwareSync( void );
int GetCurrentNumBones( void ) const;
bool IsHWMorphingEnabled() const;
int GetCurrentLightCombo( void ) const;
int MapLightComboToPSLightCombo( int nLightCombo ) const;
MaterialFogMode_t GetCurrentFogType( void ) const;
void RecordString( const char *pStr );
void EvictManagedResources();
void SetTextureTransformDimension( TextureStage_t textureStage, int dimension, bool projected );
void DisableTextureTransform( TextureStage_t textureStage )
{
}
void SetBumpEnvMatrix( TextureStage_t textureStage, float m00, float m01, float m10, float m11 );
// Gets the lightmap dimensions
virtual void GetLightmapDimensions( int *w, int *h );
virtual void SyncToken( const char *pToken );
// Setup standard vertex shader constants (that don't change)
// This needs to be called anytime that overbright changes.
virtual void SetStandardVertexShaderConstants( float fOverbright )
{
}
// Scissor Rect
virtual void SetScissorRect( const int nLeft, const int nTop, const int nRight, const int nBottom, const bool bEnableScissor )
{
}
// Reports support for a given CSAA mode
bool SupportsCSAAMode( int nNumSamples, int nQualityLevel )
{
return false;
}
// Level of anisotropic filtering
virtual void SetAnisotropicLevel( int nAnisotropyLevel );
void SetDefaultDynamicState()
{
}
virtual void CommitPixelShaderLighting( int pshReg )
{
}
virtual void MarkUnusedVertexFields( unsigned int nFlags, int nTexCoordCount, bool *pUnusedTexCoords )
{
}
// Occlusion queries
ShaderAPIOcclusionQuery_t CreateOcclusionQueryObject( void );
void DestroyOcclusionQueryObject( ShaderAPIOcclusionQuery_t handle );
void BeginOcclusionQueryDrawing( ShaderAPIOcclusionQuery_t handle );
void EndOcclusionQueryDrawing( ShaderAPIOcclusionQuery_t handle );
int OcclusionQuery_GetNumPixelsRendered( ShaderAPIOcclusionQuery_t handle, bool bFlush );
virtual void AcquireThreadOwnership()
{
}
virtual void ReleaseThreadOwnership()
{
}
virtual bool SupportsNormalMapCompression() const
{
return false;
}
virtual bool SupportsBorderColor() const
{
return false;
}
virtual bool SupportsFetch4() const
{
return true;
}
virtual void EnableBuffer2FramesAhead( bool bEnable )
{
}
virtual void SetDepthFeatheringPixelShaderConstant( int iConstant, float fDepthBlendScale )
{
}
void SetPixelShaderFogParams( int reg )
{
}
virtual bool InFlashlightMode() const
{
return false;
}
virtual bool InEditorMode() const
{
return false;
}
// What fields in the morph do we actually use?
virtual MorphFormat_t ComputeMorphFormat( int numSnapshots, StateSnapshot_t *pIds ) const;
// Gets the bound morph's vertex format; returns 0 if no morph is bound
virtual MorphFormat_t GetBoundMorphFormat();
void GetStandardTextureDimensions( int *pWidth, int *pHeight, StandardTextureId_t id );
// Binds a standard texture
virtual void BindStandardTexture( Sampler_t stage, StandardTextureId_t id )
{
}
virtual void BindStandardVertexTexture( VertexTextureSampler_t stage, StandardTextureId_t id )
{
}
virtual void SetFlashlightState( const FlashlightState_t &state, const VMatrix &worldToTexture )
{
}
virtual void SetFlashlightStateEx( const FlashlightState_t &state, const VMatrix &worldToTexture, ITexture *pFlashlightDepthTexture )
{
}
virtual const FlashlightState_t &GetFlashlightState( VMatrix &worldToTexture ) const
{
static FlashlightState_t blah;
return blah;
}
virtual const FlashlightState_t &GetFlashlightStateEx( VMatrix &worldToTexture, ITexture **pFlashlightDepthTexture ) const
{
static FlashlightState_t blah;
return blah;
}
virtual void SetModeChangeCallback( ModeChangeCallbackFunc_t func )
{
}
virtual void ClearVertexAndPixelShaderRefCounts()
{
}
virtual void PurgeUnusedVertexAndPixelShaders()
{
}
// Binds a vertex texture to a particular texture stage in the vertex pipe
virtual void BindVertexTexture( VertexTextureSampler_t nStage, ShaderAPITextureHandle_t hTexture )
{
}
// Sets morph target factors
virtual void SetFlexWeights( int nFirstWeight, int nCount, const MorphWeight_t *pWeights )
{
}
// NOTE: Stuff after this is added after shipping HL2.
ITexture *GetRenderTargetEx( int nRenderTargetID )
{
return NULL;
}
void SetToneMappingScaleLinear( const Vector &scale )
{
}
const Vector &GetToneMappingScaleLinear( void ) const
{
static Vector dummy;
return dummy;
}
virtual float GetLightMapScaleFactor( void ) const
{
return 1.0;
}
// For dealing with device lost in cases where SwapBuffers isn't called all the time (Hammer)
virtual void HandleDeviceLost()
{
}
virtual void EnableLinearColorSpaceFrameBuffer( bool bEnable )
{
}
// Lets the shader know about the full-screen texture so it can
virtual void SetFullScreenTextureHandle( ShaderAPITextureHandle_t h )
{
}
void SetFloatRenderingParameter( int parm_number, float value )
{
}
void SetIntRenderingParameter( int parm_number, int value )
{
}
void SetVectorRenderingParameter( int parm_number, Vector const &value )
{
}
float GetFloatRenderingParameter( int parm_number ) const
{
return 0;
}
int GetIntRenderingParameter( int parm_number ) const
{
return 0;
}
Vector GetVectorRenderingParameter( int parm_number ) const
{
return Vector( 0, 0, 0 );
}
// Methods related to stencil
void SetStencilEnable( bool onoff );
void SetStencilFailOperation( StencilOperation_t op );
void SetStencilZFailOperation( StencilOperation_t op );
void SetStencilPassOperation( StencilOperation_t op );
void SetStencilCompareFunction( StencilComparisonFunction_t cmpfn );
void SetStencilReferenceValue( int ref );
void SetStencilTestMask( uint32 msk );
void SetStencilWriteMask( uint32 msk );
void ClearStencilBufferRectangle( int xmin, int ymin, int xmax, int ymax, int value )
{
}
virtual void GetDXLevelDefaults( uint &max_dxlevel, uint &recommended_dxlevel )
{
max_dxlevel = recommended_dxlevel = 110;
}
virtual void GetMaxToRender( IMesh *pMesh, bool bMaxUntilFlush, int *pMaxVerts, int *pMaxIndices )
{
MeshMgr()->GetMaxToRender( pMesh, bMaxUntilFlush, pMaxVerts, pMaxIndices );
}
// Returns the max possible vertices + indices to render in a single draw call
virtual int GetMaxVerticesToRender( IMaterial *pMaterial )
{
return MeshMgr()->GetMaxVerticesToRender( pMaterial );
}
virtual int GetMaxIndicesToRender()
{
return MeshMgr()->GetMaxIndicesToRender();
}
virtual int CompareSnapshots( StateSnapshot_t snapshot0, StateSnapshot_t snapshot1 )
{
return 0;
}
virtual void DisableAllLocalLights()
{
}
virtual bool SupportsMSAAMode( int nMSAAMode )
{
return false;
}
// Hooks for firing PIX events from outside the Material System...
virtual void SetPIXMarker( unsigned long color, const char *szName )
{
}
virtual void ComputeVertexDescription( unsigned char *pBuffer, VertexFormat_t vertexFormat, MeshDesc_t &desc ) const
{
return MeshMgr()->ComputeVertexDescription( pBuffer, vertexFormat, desc );
}
virtual bool SupportsShadowDepthTextures()
{
return false;
}
virtual int NeedsShaderSRGBConversion( void ) const
{
return 1;
}
virtual bool SupportsFetch4()
{
return false;
}
virtual void SetShadowDepthBiasFactors( float fShadowSlopeScaleDepthBias, float fShadowDepthBias )
{
}
virtual void SetDisallowAccess( bool )
{
}
virtual void EnableShaderShaderMutex( bool )
{
}
virtual void ShaderLock()
{
}
virtual void ShaderUnlock()
{
}
virtual void EnableHWMorphing( bool bEnable )
{
}
ImageFormat GetNullTextureFormat( void )
{
return IMAGE_FORMAT_ABGR8888;
} // stub
virtual void PushDeformation( DeformationBase_t const *Deformation )
{
}
virtual void PopDeformation()
{
}
virtual int GetNumActiveDeformations() const
{
return 0;
}
virtual void ExecuteCommandBuffer( uint8 *pBuf )
{
}
void SetStandardTextureHandle( StandardTextureId_t, ShaderAPITextureHandle_t )
{
}
int GetPackedDeformationInformation( int nMaskOfUnderstoodDeformations,
float *pConstantValuesOut,
int nBufferSize,
int nMaximumDeformations,
int *pNumDefsOut ) const
{
*pNumDefsOut = 0;
return 0;
}
virtual bool OwnGPUResources( bool bEnable )
{
return false;
}
private:
enum
{
TRANSLUCENT = 0x1,
ALPHATESTED = 0x2,
VERTEX_AND_PIXEL_SHADERS = 0x4,
DEPTHWRITE = 0x8,
};
void EnableAlphaToCoverage(){};
void DisableAlphaToCoverage(){};
ImageFormat GetShadowDepthTextureFormat()
{
return IMAGE_FORMAT_UNKNOWN;
};
//
// NOTE: Under here are real methods being used by dx11 implementation
// above is stuff I still have to port over.
//
private:
//void ClearShaderState( ShaderStateDx11_t *pState );
void CreateTextureHandles( ShaderAPITextureHandle_t *handles, int count );
CTextureDx11 &GetTexture(ShaderAPITextureHandle_t handle);
ShaderAPITextureHandle_t CreateTextureHandle();
void DoIssueVertexShader();
void DoIssuePixelShader();
void DoIssueGeometryShader();
bool DoIssueConstantBuffers( bool bForce );
void DoIssueTexture();
void DoIssueSampler();
void DoIssueRasterState();
void DoIssueBlendState();
void DoIssueDepthStencilState();
bool DoIssueVertexBuffer( bool bForce );
void DoIssueIndexBuffer();
void DoIssueInputLayout();
void DoIssueTopology();
void DoIssueViewports();
void DoIssueConstantBufferUpdates();
void DoIssueTransform();
void DoIssueRenderTargets();
void AdvanceCurrentTextureCopy( ShaderAPITextureHandle_t handle );
bool MatrixIsChanging() const;
bool IsDeactivated() const;
DirectX::XMMATRIX &GetMatrix( MaterialMatrixMode_t mode );
DirectX::XMMATRIX &GetCurrentMatrix();
DirectX::XMMATRIX GetMatrixCopy( MaterialMatrixMode_t mode ) const;
DirectX::XMMATRIX GetCurrentMatrixCopy() const;
void HandleMatrixModified();
void RenderPassWithVertexAndIndexBuffers();
private:
// Current material + mesh
IMaterialInternal *m_pMaterial;
CMeshBase *m_pMesh;
int m_nDynamicVBSize;
// Members related to textures
// UNDONE: Should this stuff be in ShaderDeviceDx11?
CUtlFixedLinkedList<CTextureDx11> m_Textures;
char m_ModifyTextureLockedLevel;
ShaderAPITextureHandle_t m_ModifyTextureHandle;
ShaderAPITextureHandle_t m_hBackBuffer;
ShaderAPITextureHandle_t m_hDepthBuffer;
// Current and target states
StateSnapshot_t m_CurrentSnapshot;
bool m_bResettingRenderState : 1;
StatesDx11::RenderState m_TargetState;
StatesDx11::RenderState m_State;
DynamicStateDx11_t m_DynamicState;
// Setting matrices
MaterialMatrixMode_t m_MatrixMode;
MatrixItemDx11_t *m_pCurMatrixItem;
CUtlStack<MatrixItemDx11_t> m_MatrixStacks[NUM_MATRIX_MODES];
bool m_ChangedMatrices[NUM_MATRIX_MODES];
bool m_bSelectionMode;
// Mesh builder used to modify vertex data
CMeshBuilder m_ModifyBuilder;
// Selection name stack
CUtlStack< int > m_SelectionNames;
bool m_InSelectionMode;
unsigned int *m_pSelectionBufferEnd;
unsigned int *m_pSelectionBuffer;
unsigned int *m_pCurrSelectionRecord;
float m_SelectionMinZ;
float m_SelectionMaxZ;
int m_NumHits;
friend class CTempMeshDX11;
friend class CMeshDX11;
friend class CDynamicMeshDX11;
friend class CBufferedMeshDX11;
friend class CMeshMgr;
friend class CShaderDeviceDx11;
};
//-----------------------------------------------------------------------------
// Singleton global
//-----------------------------------------------------------------------------
extern CShaderAPIDx11 *g_pShaderAPIDx11;
#endif // SHADERAPIDX11_H
|
bd6f3a615c678efecee320e3ce7e9bcce13a996a | 7ef3b116486dd794905d62b912a6901a696053df | /main-segmentation-hw.cpp | c01e738dad2f36735fbabffc9cd6ddcfef3df6bb | [] | no_license | trehman65/backtoschool | d22a3b51ff23e02ba7cdc9afd948e7f9b8c17a89 | 9b4d1f35572c997f9404152a4002348a2f43f6a0 | refs/heads/master | 2021-01-23T08:04:24.809347 | 2017-04-03T15:37:52 | 2017-04-03T15:37:52 | 86,474,995 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,774 | cpp | main-segmentation-hw.cpp | #include <iostream>
#include <iostream>
#include <string>
#include <fstream>
// Open CV headers
#include "opencv2/imgproc/imgproc.hpp"
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "bg-estimate.h"
using namespace cv;
using namespace std;
using namespace std;
string currentDirectory;
string filename;
void binarizeShafait(Mat &gray, Mat &binary, int w, double k);
void conComps(const Mat &binary, vector<vector<Point2i> > &blobs, vector<Rect> &blob_rects);
void findLineBoxes(const Mat &greyImage, vector<Rect> &resultantBoxes);
void cropboxes(Mat, vector<Rect>);
void test(string);
void binarizeBG(cv::Mat &gray, cv::Mat &grayBG, cv::Mat &binary);
int main(int argc, char **argv) {
test(argv[1]);
return 0;
}
void test(string fname){
Mat imgRgb;
Mat imgGray;
std::vector<cv::Rect> rboxes;
std::vector<Rect> resultantBoxes;
imgRgb = imread(fname, CV_LOAD_IMAGE_COLOR); // Read the file
string::size_type pAtPath = fname.find_last_of('/');
string filePath = fname.substr(0, pAtPath + 1);
string fileFullName = fname.substr(pAtPath + 1);
string::size_type pAtExt = fileFullName.find_last_of('.'); // Find extension point
string fileBaseName = fileFullName.substr(0, pAtExt);
currentDirectory=filePath;
filename=fileBaseName;
cvtColor( imgRgb, imgGray, CV_BGR2GRAY );
findLineBoxes(imgGray, resultantBoxes);
}
void findLineBoxes(const Mat &greyImage, vector<Rect> &resultantBoxes) {
const float H_GAP_FACTOR = 10 ;
Mat greyImage2 = greyImage.clone();
// Convert image to binary
Mat imgShahrukh;
Mat temp;
// binarizeBG(greyImage2,temp, imgShahrukh);
binarizeShafait(greyImage2, imgShahrukh, 50, 0.30);
// if (m_debug) {
// string imgFileName = m_debugImgPrefix + "-00a-binary-shahrukh.png";
// imwrite(imgFileName, imgShahrukh);
// }
//
cv::Mat copy = imgShahrukh.clone();
copy /= 255;
copy = 1 - copy;
vector<vector<Point>> blobs;
vector<Rect> rects;
conComps(copy, blobs, rects);
copy = 1 - copy;
copy *= 255;
// return std::max(0,std::min(a.y + a.height, b.y + b.height) - std::max(a.y, b.y)) >0;
int medianHeight;
{
Mat filteredImage=copy.clone();
Mat element5(5, 5, CV_8U, Scalar(1));
erode(filteredImage, filteredImage, element5);
dilate(filteredImage, filteredImage, element5);
vector<vector<Point>> blobsFilteredImage;
vector<Rect> rectsFilteredImage;
filteredImage /= 255;
filteredImage= 1 - filteredImage;
conComps(filteredImage, blobsFilteredImage, rectsFilteredImage);
filteredImage= 1 - filteredImage;
filteredImage *= 255;
std::sort(rectsFilteredImage.begin(), rectsFilteredImage.end(),
[&](const Rect &d1, const Rect &d2) -> bool {
return d1.height > d2.height;
});
vector<Rect> rectsFilteredImageSmallRemoved;
Mat filteredImageBrg;
cvtColor(filteredImage,filteredImageBrg,CV_GRAY2BGR);
for (auto &i:rectsFilteredImage) {
if (i.height < 10 || i.width < 3)
continue;
rectsFilteredImageSmallRemoved.push_back(i);
rectangle(filteredImageBrg,i,Scalar(0,0,255),3);
}
// if (m_debug) {
// string imgFileName = m_debugImgPrefix + "-filtered-image.png";
// imwrite(imgFileName, filteredImageBrg);
// }
if (rectsFilteredImage.size() == 0)
return;
// if(m_debug) {
// cout << "Debug: Filtered rects size "<<rectsFilteredImageSmallRemoved.size()<<endl;
// }
medianHeight = rectsFilteredImageSmallRemoved[rectsFilteredImageSmallRemoved.size() / 2].height;
}
vector<Rect> copiedRects;
for (auto &i:rects) {
if (i.height < 10 || i.width < 3)
continue;
copiedRects.push_back(i);
}
// if(m_debug) {
// cout<<"Debug: Initially ";
// cout<<rects.size()<<endl;
// cout<<"Debug: Finally ";
// cout<<copiedRects.size()<<endl;
// }
std::sort(rects.begin(), rects.end(),
[&](const Rect &d1, const Rect &d2) -> bool {
return d1.height > d2.height;
});
if (copiedRects.size() == 0)
return;
//int medianHeight = copiedRects[copiedRects.size() / 2].height;
// if(m_debug)
// cout<<"Debug: Median height " <<medianHeight<<endl;
for (auto i:copiedRects) {
if (i.width > greyImage.cols / 3) {
continue;
}
if (i.height > greyImage.rows / 3) {
continue;
}
for (auto j:copiedRects) {
if (i.width > greyImage.cols / 3)
continue;
if (i.height > greyImage.rows / 3)
continue;
bool overlap = max(0, std::min(i.y + i.height, j.y + j.height) - std::max(i.y, j.y)) > 0;
int distance = j.x - i.x - i.width;
if (distance >= 0 && distance <= (medianHeight * H_GAP_FACTOR) && overlap) {
Rect rect(i.x, i.y, j.x + j.width - i.x, i.height);
rectangle(copy, rect, 0, CV_FILLED, 0, 0);
}
}
}
// // if (m_debug) {
// string imgFileName = m_debugImgPrefix + "-00a-rlsa-shahrukh.png";
// imwrite(imgFileName, copy);
// //}
copy /= 255;
copy = 1 - copy;
// Clear up stuff before reuse
blobs.clear();
rects.clear();
// Fine connected components again
conComps(copy, blobs, rects);
int totalBoundingRectArea = 0;
int totalBoundingRects = rects.size();
for (auto i:rects) {
totalBoundingRectArea += i.area();
}
float meanBoundingRectsArea = totalBoundingRectArea / totalBoundingRects;
resultantBoxes.clear();
for (auto i:rects) {
if (i.height > 0.7 * medianHeight && i.height < 4 * medianHeight && i.area() > 0.2*meanBoundingRectsArea) {
//if(i.height>10){
resultantBoxes.push_back(i);
}
}
Mat imageTableComponentsDrawn;
cvtColor((1 - copy) * 255, imageTableComponentsDrawn, COLOR_GRAY2BGR);
Scalar redColor(0, 0, 255);
for (auto i:resultantBoxes) {
rectangle(imageTableComponentsDrawn, i, redColor);
}
cropboxes(imgShahrukh, resultantBoxes);
if (1) {
string imgFileName = "/Users/talha/Downloads/line-boxes.png";
imwrite(imgFileName, imageTableComponentsDrawn);
}
}
void binarizeShafait(Mat &gray, Mat &binary, int w, double k) {
Mat sum, sumsq;
gray.copyTo(binary);
int half_width = w >> 1;
integral(gray, sum, sumsq, CV_64F);
for (int i = 0; i < gray.rows; i++) {
for (int j = 0; j < gray.cols; j++) {
int x_0 = (i > half_width) ? i - half_width : 0;
int y_0 = (j > half_width) ? j - half_width : 0;
int x_1 = (i + half_width >= gray.rows) ? gray.rows - 1 : i + half_width;
int y_1 = (j + half_width >= gray.cols) ? gray.cols - 1 : j + half_width;
double area = (x_1 - x_0) * (y_1 - y_0);
double mean = (sum.at<double>(x_0, y_0) + sum.at<double>(x_1, y_1) - sum.at<double>(x_0, y_1) -
sum.at<double>(x_1, y_0)) / area;
double sq_mean = (sumsq.at<double>(x_0, y_0) + sumsq.at<double>(x_1, y_1) - sumsq.at<double>(x_0, y_1) -
sumsq.at<double>(x_1, y_0)) / area;
double stdev = sqrt(sq_mean - (mean * mean));
double threshold = mean * (1 + k * ((stdev / 128) - 1));
if (gray.at<uchar>(i, j) > threshold)
binary.at<uchar>(i, j) = 255;
else
binary.at<uchar>(i, j) = 0;
}
}
}
void conComps(const Mat &binary, vector<vector<Point2i> > &blobs, vector<Rect> &blob_rects) {
blobs.clear();
blob_rects.clear();
// Fill the label_image with the blobs
// 0 - background
// 1 - unlabelled foreground
// 2+ - labelled foreground
cv::Mat label_image;
binary.convertTo(label_image, CV_32FC1); // weird it doesn't support CV_32S!
int label_count = 2; // starts at 2 because 0,1 are used already
for (int y = 0; y < binary.rows; y++) {
for (int x = 0; x < binary.cols; x++) {
if ((int) label_image.at<float>(y, x) != 1) {
continue;
}
cv::Rect rect;
cv::floodFill(label_image, cv::Point(x, y), cv::Scalar(label_count), &rect, cv::Scalar(0), cv::Scalar(0),
4);
std::vector<cv::Point2i> blob;
for (int i = rect.y; i < (rect.y + rect.height); i++) {
for (int j = rect.x; j < (rect.x + rect.width); j++) {
if ((int) label_image.at<float>(i, j) != label_count) {
continue;
}
blob.push_back(cv::Point2i(j, i));
}
}
blobs.push_back(blob);
label_count++;
}
}
for (size_t i = 0; i < blobs.size(); i++) {
int top = 10000, bottom = -1, left = 10000, right = -1;
for (size_t j = 0; j < blobs[i].size(); j++) {
int x = blobs[i][j].x;
int y = blobs[i][j].y;
if (x < left)
left = x;
if (x > right)
right = x;
if (y < top)
top = y;
if (y > bottom)
bottom = y;
}
int w = right - left;
int h = bottom - top;
blob_rects.push_back(Rect(left, top, w, h));
}
}
void cropboxes(Mat imgBin, vector<Rect> lboxes){
string newDirectory=currentDirectory+filename;
string command="mkdir -p " + newDirectory;
system(command.c_str());
Mat cropped;
for(int i=0; i<lboxes.size(); i++) {
imgBin(lboxes[i]).copyTo(cropped);
int top = (int) (0.1*cropped.rows);int bottom = (int) (0.1*cropped.rows);
int left = (int) (0.01*cropped.cols);int right = (int) (0.01*cropped.cols);
Mat outframe = cropped;
Scalar value;
value=Scalar(255,255,255);
copyMakeBorder( cropped, outframe, top, bottom, left, right, BORDER_CONSTANT,value );
imwrite(newDirectory+"/line-"+to_string(i)+".png", outframe);
// imwrite(newDirectory+"/line-"+to_string(i)+".png", cropped);
}
}
void binarizeBG(cv::Mat &gray, cv::Mat &grayBG, cv::Mat &binary) {
grayBG = gray.clone();
// Estimate image background using Percentile filter
CBgEstimate bg;
bg.bgEstimatePercentile(gray, grayBG);
bg.binarizeByBackgroundOtsu(gray, grayBG, binary);
}
|
8e95af474921e13854ee1848cc6bbfeaf953ade5 | f6bd1680e4f49ec2d3491deb48b9fda9ac297a2a | /main.cpp | 2abec474c68ecd74f3e51e0bad72ddc413e00b88 | [] | no_license | diamondmalik/snake-game | 28ec01589e4559713109757142cfeb5a37e1aee4 | 584e0457257a875182373b826ce65958a1d111b5 | refs/heads/master | 2020-08-21T18:19:24.843245 | 2019-10-19T14:17:19 | 2019-10-19T14:17:19 | 216,217,211 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,810 | cpp | main.cpp | #include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
class snake{
bool gameover;
const int width = 20;
const int height = 20;
int x,y; //coordinates of head
int fruitx,fruity;
int score;
enum eDirection{stop=0,left,right,up,down};
eDirection dir;
//for tail now,
int tailx[100],taily[100];
int ntail; //this specifies length of tail
public:
void setup(){
gameover = false;
dir = stop; //snake moves only after we start moving it
x = width/2;y=height/2; // snake centered in middle
fruitx = rand()%width;
fruity = rand()%height;
score = 0;
}
void draw(){
//top
for(int i = 0;i<width+2;i++)
cout << "#";
cout << endl;
//middle
for(int i = 0;i<height;i++){
for(int j = 0;j<width;j++){
if(j==0)
cout << "#";
if(i==y && j==x)
cout << "O"; //head
else if(i==fruity&&j==fruitx)
cout << "F";
else{
bool print = false;
for(int k = 0; k<ntail;k++){
if(tailx[k]==j&&taily[k]==i){
cout << "o";
print = true;
}
}
if(!print)
cout << " ";}
if(j==width-1)
cout << "#";
}
cout << endl;
}
//bottom
for(int i = 0;i<width+2;i++)
cout << "#";
cout << "SCORE" << score << endl;
}
void input(){
if(_kbhit()){
switch(_getch()){
case 'a':
dir = left;
break;
case 'd':
dir = right;
break;
case 's':
dir = down;
break;
case 'w':
dir = up;
break;
}
}
}
void logic(){
int prevx = tailx[0];
int prevy = taily[0];
int prev2x,prev2y;
tailx[0] = x;
taily[0] = y;
for(int i = 1;i<ntail;i++){
prev2x = tailx[i];
prev2y = taily[i];
tailx[i] = prevx;
taily[i] = prevy;
prevx = prev2x;
prevy = prev2y;
}
switch(dir){
case left:
x--;
break;
case right:
x++;
break;
case up:
y--;
break;
case down:
y++;
break;
}
if(x>width||x<0||y>height||y<0)
gameover = true;
for(int i = 0; i<ntail;i++){
if(tailx[i]==x&&taily[i]==y)
gameover = true;
}
if(x==fruitx&&y==fruity){
score+=10;
fruitx = rand()%width;
fruity = rand()%height;
}
if(x==fruitx&&y==fruity)
ntail++;
}
bool get_status(){
return gameover;}
};
int main(){
snake s;
s.setup();
while(!s.get_status()){
s.draw();
s.input();
s.logic();
}
}
|
2a68f65444776672146927f3f7577adc3695de84 | a989d4c80d5d99e4f22eeeb21b029365796f7f02 | /src/core/extension_api.cpp | 784f330d13169c225f415b624e97147cb9ade91a | [] | no_license | darius98/mcga-test | 53ffb32afde682670ee338a65757c7c9a6aea4db | 3b716ca03e1c68a033917ca4f88dac3bc699cfea | refs/heads/master | 2022-08-11T20:28:39.325060 | 2022-07-07T20:52:52 | 2022-07-07T20:52:52 | 150,012,028 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,311 | cpp | extension_api.cpp | #include "extension_api.hpp"
namespace mcga::test {
ExtensionApi::ExtensionApi(Extension* extensions, std::size_t numExtensions)
: extensions(extensions), numExtensions(numExtensions) {
}
void ExtensionApi::init() {
forEach([](Extension ext) {
ext.vtable->init(ext.data);
});
}
void ExtensionApi::onGroupDiscovered(const GroupPtr& group) {
forEach([&group](Extension ext) {
ext.vtable->onGroupDiscovered(ext.data, group);
});
}
void ExtensionApi::onTestDiscovered(const Test& test) {
forEach([&test](Extension ext) {
ext.vtable->onTestDiscovered(ext.data, test);
});
}
void ExtensionApi::beforeTestExecution(
const Test& test, std::optional<Test::ExecutionInfo>& info) {
forEach([&test, &info](Extension ext) {
ext.vtable->beforeTestExecution(ext.data, test, info);
});
}
void ExtensionApi::afterTestExecution(const Test& test) {
forEach([&test](Extension ext) {
ext.vtable->afterTestExecution(ext.data, test);
});
}
void ExtensionApi::onWarning(const Warning& warning) {
forEach([&warning](Extension ext) {
ext.vtable->onWarning(ext.data, warning);
});
}
void ExtensionApi::destroy() {
forEach([](Extension ext) {
ext.vtable->destroy(ext.data);
});
}
} // namespace mcga::test
|
d53b675480946132e86c30528ddf2bd431f288a6 | e2f061bbe58f3569b4ad154e0de8ee34001dd0fe | /CodeBlocksWithSFMLProjects/Entity.cpp | 7037c559c4186f9b2922e5f4314f53483a948177 | [] | no_license | guivmc/PokemonTest | fae0db0a4aeface035a1dcc13769416eb7dc5505 | 7dd460ecc2d189992e5861782d7034f13cd0458a | refs/heads/master | 2021-07-08T10:08:45.815056 | 2017-09-25T20:17:53 | 2017-09-25T20:17:53 | 104,797,636 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,141 | cpp | Entity.cpp | #include "Entity.h"
Entity::Entity(){}
Entity::~Entity(){}
Entity::Entity(float x, float y, const char* fileName) //: pos_x(x), pos_y(y)
{
pos_x = x;
pos_y = y;
loadAndSetTexture(fileName);
}
Entity::Entity(float x, float y, const char* fileName, IntRect rect)// : pos_x(x), pos_y(y), entityRect(rect)
{
pos_x = x;
pos_y = y;
loadAndSetTexture(fileName);
setSpriteRect(rect);
}
void Entity::loadAndSetTexture(const char* fileName)
{
if(!texture.loadFromFile(fileName))
{
return;
}
displayable = true;
entitySprite.setTexture(texture);
}
void Entity::drawEntity(RenderWindow &gameWindow)
{
if(displayable) gameWindow.draw(entitySprite);
}
//Getters
float Entity::getPos_x()
{
return pos_x;
}
float Entity::getPos_y()
{
return pos_y;
}
Sprite Entity::getEntitySprite()
{
return entitySprite;
}
//Setters
void Entity::setPos_x(float x)
{
pos_x = x;
}
void Entity::setPos_y(float y)
{
pos_y = y;
}
void Entity::setSpriteRect(IntRect rect)
{
entitySprite.setTextureRect(rect);
}
|
7102a2d3198bdcc8dd7b1886a3b5df5a91a3a456 | 1aeaf760e3ce0e298963854e0aef8be6bef6ec61 | /Translator/Translator.cpp | 034d575b888e6e4e94552f275204eb4505a67ba6 | [] | no_license | jamescoll/cpp_portfolio | b7742f49ac9bd8f20ebdb293a46da75d409c7afe | c2ff80d9da0fd46baef9856f1ca50007ee9c8313 | refs/heads/master | 2016-09-03T07:29:41.726708 | 2013-08-13T00:36:34 | 2013-08-13T00:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,909 | cpp | Translator.cpp | /*
* Translator.cpp
*
* Created on: 6 Apr 2013
* Author: James Coll
*/
#include "Translator.h"
#include <iostream>
#include <fstream>
#include <map>
#include <algorithm>
#include <string.h>
using namespace std;
Translator::Translator(const char filename[])
{
// we don't want to do file io in the constructor
this->LoadDictionary(filename);
}
void Translator::LoadDictionary(const char filename[])
{
//open the dictionary file
fstream infile;
infile.open(filename, ios::in);
if (infile.fail())
{
cerr<<"Problem opening dictionary file";
return;
}
string line, english, elfish;
//go through the file line by line dealing with the problematic tabs and whitespaces
//we're going to use two maps to store the dictionary
//this turns out to be more efficient than using one map and a reverse find
while(infile.good())
{
getline(infile, line);
if(!line.empty())
{
//this gets me all the English words by hunting for whitespace and tabs
unsigned found = line.find_first_of(" \t");
english = line.substr(0, found);
//we'll dump what's left in elfish and then remove the whitespaces and tabs from it
elfish = line.substr(found, string::npos);
elfish.erase(remove(elfish.begin(), elfish.end(), '\t'), elfish.end());
elfish.erase(remove(elfish.begin(), elfish.end(), ' '), elfish.end());
//now place these into a map
engtoelfdictionary.insert(std::pair<string, string>(english, elfish));
elftoengdictionary.insert(std::pair<string, string>(elfish, english));
//now create capital pairs
english[0] = toupper(english[0]);
elfish[0] = toupper(elfish[0]);
//populate the map with capitalized pairs - this saves on work later
engtoelfdictionary.insert(std::pair<string, string>(english, elfish));
elftoengdictionary.insert(std::pair<string, string>(elfish, english));
}
}
return;
}
void Translator::toElvish(char translatedLine[], const char lineToTranslate[])
{
string inputLine(lineToTranslate);
string tmp, trans;
for(int i = 0; i<inputLine.size()+1; i++)
{
if(isalpha(inputLine[i])||inputLine[i]=='-')
{
tmp += inputLine[i];
}
else
{
//probably need to check if this is empty or not
if(!tmp.empty())
{
if(engtoelfdictionary.count(tmp)==1)
{
trans += engtoelfdictionary[tmp];
}//this is our special case words 'already translated'
else
{
tmp.insert(tmp.begin(), '*');
tmp.insert(tmp.end(), '*');
trans += tmp;
}
}
trans += inputLine[i];
tmp.clear();
}
}
//this translates our string back into a character array
char *ch=new char[trans.size()+1];
ch[trans.size()]=0;
memcpy(ch,trans.c_str(),trans.size());
strcpy(translatedLine, ch);
}
void Translator::toEnglish(char translatedLine[], const char lineToTranslate[])
{
string inputLine(lineToTranslate);
string tmp, trans;
bool bTranslate = true;
for(int i = 0; i<inputLine.size()+1; i++)
{
if(inputLine[i]=='*')
{
//we can flip this each time a first star is encountered
//this saves on a look-up
bTranslate = !bTranslate;
}
else if(isalpha(inputLine[i])||inputLine[i]=='-')
{
tmp += inputLine[i];
}
else
{
//check if this is empty or not
//we need to look up all of the words which have two meanings
if(!tmp.empty())
{
if(elftoengdictionary.count(tmp)==1&&bTranslate)
{
trans += elftoengdictionary[tmp];
}
else
{
trans += tmp;
}
}
trans += inputLine[i];
tmp.clear();
}
}
//this translates our string back into a character array
char *ch=new char[trans.size()+1];
ch[trans.size()]=0;
memcpy(ch,trans.c_str(),trans.size());
strcpy(translatedLine, ch);
}
|
e3124206cf94987e2f3be35e84c5229a7c171805 | 96262a0e0e14242f024635d8f6b2d75f235ac19b | /include/primer/support/types.hpp | 216b7196a15478f4aca9010638ed7c2d0924fa22 | [
"BSL-1.0",
"MIT"
] | permissive | cbeck88/lua-primer | e1e83a313c917ef900be3313a28ddd08ce96db34 | f6b96a24f96bc3bf03896aea0f758d76ae388fb9 | refs/heads/master | 2020-04-12T05:39:33.729750 | 2018-01-29T02:39:52 | 2018-01-29T02:39:52 | 61,611,350 | 14 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 832 | hpp | types.hpp | // (C) Copyright 2015 - 2018 Christopher Beck
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
#pragma once
/***
* Various special types recognized by push and read
*/
#include <primer/base.hpp>
PRIMER_ASSERT_FILESCOPE;
#include <string>
//[ primer_support_types
namespace primer {
// Use this type if you want to push nil onto the stack using primer::push
// interface.
struct nil_t {};
// Use this type if you want primer to convert given type to a boolean, even if
// it was not originally a boolean
struct truthy {
bool value;
};
// Use this type if you want primer to convert given type to a string, even if
// it was not originally a string
struct stringy {
std::string value;
};
} // end namespace primer
//]
|
69874a7157fb1d68811a1eb9e7716afea801eaea | 6b646e456d139af3c6fd78ef26868a0129112ced | /delphi-code/DevExpress/Source/ExpressQuantumGrid/Demos/CBuilder/UnboundSimpleDemo/UnboundSimpleDemoMain.h | 7a6ce3f46c55e832d91f297737d595dc56f2219f | [] | no_license | wkfff/delphi-codes | 7d8836418fae3a83f9e70989bc9f27e5ebd2f312 | 7585e71c85bc8f0d88e456aa3bd1b40daf4bcc71 | refs/heads/master | 2020-04-11T00:58:29.018665 | 2018-07-10T05:37:30 | 2018-07-10T05:37:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,237 | h | UnboundSimpleDemoMain.h | //---------------------------------------------------------------------------
#ifndef UnboundSimpleDemoMainH
#define UnboundSimpleDemoMainH
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include "cxClasses.hpp"
#include "cxControls.hpp"
#include "cxCustomData.hpp"
#include "cxData.hpp"
#include "cxDBData.hpp"
#include "cxEdit.hpp"
#include "cxFilter.hpp"
#include "cxGraphics.hpp"
#include "cxGrid.hpp"
#include "cxGridCustomTableView.hpp"
#include "cxGridCustomView.hpp"
#include "cxGridDBTableView.hpp"
#include "cxGridLevel.hpp"
#include "cxGridTableView.hpp"
#include "cxStyles.hpp"
#include <ActnList.hpp>
#include <ComCtrls.hpp>
#include <DB.hpp>
#include <ImgList.hpp>
#include <Menus.hpp>
#include "cxEditRepositoryItems.hpp"
#include "cxLookAndFeels.hpp"
#include "BaseForm.h"
#include "cxDataStorage.hpp"
#include "cxGridCardView.hpp"
#include "cxLookAndFeelPainters.hpp"
//---------------------------------------------------------------------------
class TUnboundSimpleDemoMainForm : public TfmBaseForm
{
__published: // IDE-managed Components
TcxGrid *cxGrid;
TcxGridTableView *tvPlanets;
TcxGridColumn *tvPlanetsNAME;
TcxGridColumn *tvPlanetsNO;
TcxGridColumn *tvPlanetsORBITS;
TcxGridColumn *tvPlanetsDISTANCE;
TcxGridColumn *tvPlanetsPERIOD;
TcxGridColumn *tvPlanetsDISCOVERER;
TcxGridColumn *tvPlanetsDATE;
TcxGridColumn *tvPlanetsRADIUS;
TcxGridLevel *lvPlanets;
TcxEditRepository *edrepMain;
TcxEditRepositoryTextItem *edrepCenterText;
TcxEditRepositoryTextItem *edrepRightText;
void __fastcall FormCreate(TObject *Sender);
private: // User declarations
void __fastcall CustomizeColumns();
void __fastcall LoadData();
void __fastcall SetFilter();
void __fastcall InitRecord(String const Str, int AInt, TStringList* AValues);
public: // User declarations
__fastcall TUnboundSimpleDemoMainForm(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TUnboundSimpleDemoMainForm *UnboundSimpleDemoMainForm;
//---------------------------------------------------------------------------
#endif
|
1667f0cb8fb84a4904ac530083f1cb2165e982dc | 74ef11065048fcf08ee5b9ef1c11c0ce10079301 | /src/voronota.cpp | d91fb03e355644dd64b40b38613f783f940eda5d | [
"MIT"
] | permissive | kliment-olechnovic/voronota | fa2548c9ccc3dd6f5a10a054300aca8b6d31ecf4 | 52c2b0d55f2979d0eef478ed0be20376cb3d561a | refs/heads/master | 2023-09-04T05:09:11.275304 | 2023-08-30T07:59:07 | 2023-08-30T07:59:07 | 203,789,299 | 19 | 6 | MIT | 2023-07-04T06:25:54 | 2019-08-22T12:20:48 | C++ | UTF-8 | C++ | false | false | 12,244 | cpp | voronota.cpp | #include <iostream>
#include <functional>
#include <exception>
#include <limits>
#include <vector>
#include <algorithm>
#include "voronota_version.h"
#include "auxiliaries/program_options_handler.h"
void get_balls_from_atoms_file(const voronota::auxiliaries::ProgramOptionsHandler&);
void calculate_vertices(const voronota::auxiliaries::ProgramOptionsHandler&);
void calculate_vertices_in_parallel(const voronota::auxiliaries::ProgramOptionsHandler&);
void calculate_contacts(const voronota::auxiliaries::ProgramOptionsHandler&);
void query_balls(const voronota::auxiliaries::ProgramOptionsHandler&);
void query_contacts(const voronota::auxiliaries::ProgramOptionsHandler&);
void draw_contacts(const voronota::auxiliaries::ProgramOptionsHandler&);
void score_contacts_energy(const voronota::auxiliaries::ProgramOptionsHandler&);
void score_contacts_quality(const voronota::auxiliaries::ProgramOptionsHandler&);
void score_contacts_potential(const voronota::auxiliaries::ProgramOptionsHandler&);
void compare_contacts(const voronota::auxiliaries::ProgramOptionsHandler&);
void write_balls_to_atoms_file(const voronota::auxiliaries::ProgramOptionsHandler&);
void query_balls_clashes(const voronota::auxiliaries::ProgramOptionsHandler&);
void expand_descriptors(const voronota::auxiliaries::ProgramOptionsHandler&);
void query_balls_sequences_pairings_stats(const voronota::auxiliaries::ProgramOptionsHandler&);
void draw_balls(const voronota::auxiliaries::ProgramOptionsHandler&);
void query_contacts_depth_values(const voronota::auxiliaries::ProgramOptionsHandler&);
void plot_contacts(const voronota::auxiliaries::ProgramOptionsHandler&);
void score_contacts_potentials_stats(const voronota::auxiliaries::ProgramOptionsHandler&);
void score_contacts_energy_stats(const voronota::auxiliaries::ProgramOptionsHandler&);
void vectorize_contacts(const voronota::auxiliaries::ProgramOptionsHandler&);
void vectorize_points(const voronota::auxiliaries::ProgramOptionsHandler&);
void calculate_mock_solvent(const voronota::auxiliaries::ProgramOptionsHandler&);
void query_contacts_simulating_unfolding(const voronota::auxiliaries::ProgramOptionsHandler&);
void vectorize_contact_environments(const voronota::auxiliaries::ProgramOptionsHandler&);
void write_qa_scores_in_casp_format(const voronota::auxiliaries::ProgramOptionsHandler&);
void score_contacts_global_energy_by_cuts(const voronota::auxiliaries::ProgramOptionsHandler&);
void simulate_potential_for_membrane_proteins(const voronota::auxiliaries::ProgramOptionsHandler&);
void query_contacts_solvation_values(const voronota::auxiliaries::ProgramOptionsHandler&);
void query_contacts_interchain_exposure_values(const voronota::auxiliaries::ProgramOptionsHandler&);
void score_scores(const voronota::auxiliaries::ProgramOptionsHandler&);
void demo_ses(const voronota::auxiliaries::ProgramOptionsHandler&);
void rotational_optimization_demo(const voronota::auxiliaries::ProgramOptionsHandler&);
void place_membrane(const voronota::auxiliaries::ProgramOptionsHandler&);
void demo_polygon_triangulation(const voronota::auxiliaries::ProgramOptionsHandler&);
void demo_hypercut(const voronota::auxiliaries::ProgramOptionsHandler&);
void run_script(const voronota::auxiliaries::ProgramOptionsHandler&);
void draw_values_bitmap(const voronota::auxiliaries::ProgramOptionsHandler&);
void reprint_hbp(const voronota::auxiliaries::ProgramOptionsHandler&);
void compare_files_as_sets(const voronota::auxiliaries::ProgramOptionsHandler&);
void calculate_path_centralities(const voronota::auxiliaries::ProgramOptionsHandler&);
void query_balls_distances(const voronota::auxiliaries::ProgramOptionsHandler&);
void split_atoms_file(const voronota::auxiliaries::ProgramOptionsHandler&);
void demo_blank(const voronota::auxiliaries::ProgramOptionsHandler&);
struct ModeDescriptor
{
typedef std::pointer_to_unary_function<const voronota::auxiliaries::ProgramOptionsHandler&, void> FunctionPtr;
std::string name;
FunctionPtr func_ptr;
ModeDescriptor(const std::string& name, const FunctionPtr& func_ptr) : name(name), func_ptr(func_ptr)
{
}
bool operator==(const std::string& check_name) const
{
return (check_name==name);
}
};
std::vector<ModeDescriptor> get_list_of_modes()
{
std::vector<ModeDescriptor> list_of_modes;
list_of_modes.push_back(ModeDescriptor("get-balls-from-atoms-file", ModeDescriptor::FunctionPtr(get_balls_from_atoms_file)));
list_of_modes.push_back(ModeDescriptor("calculate-vertices", ModeDescriptor::FunctionPtr(calculate_vertices)));
list_of_modes.push_back(ModeDescriptor("calculate-vertices-in-parallel", ModeDescriptor::FunctionPtr(calculate_vertices_in_parallel)));
list_of_modes.push_back(ModeDescriptor("calculate-contacts", ModeDescriptor::FunctionPtr(calculate_contacts)));
list_of_modes.push_back(ModeDescriptor("query-balls", ModeDescriptor::FunctionPtr(query_balls)));
list_of_modes.push_back(ModeDescriptor("query-contacts", ModeDescriptor::FunctionPtr(query_contacts)));
list_of_modes.push_back(ModeDescriptor("draw-contacts", ModeDescriptor::FunctionPtr(draw_contacts)));
list_of_modes.push_back(ModeDescriptor("score-contacts-energy", ModeDescriptor::FunctionPtr(score_contacts_energy)));
list_of_modes.push_back(ModeDescriptor("score-contacts-quality", ModeDescriptor::FunctionPtr(score_contacts_quality)));
list_of_modes.push_back(ModeDescriptor("score-contacts-potential", ModeDescriptor::FunctionPtr(score_contacts_potential)));
list_of_modes.push_back(ModeDescriptor("compare-contacts", ModeDescriptor::FunctionPtr(compare_contacts)));
list_of_modes.push_back(ModeDescriptor("write-balls-to-atoms-file", ModeDescriptor::FunctionPtr(write_balls_to_atoms_file)));
list_of_modes.push_back(ModeDescriptor("query-balls-clashes", ModeDescriptor::FunctionPtr(query_balls_clashes)));
list_of_modes.push_back(ModeDescriptor("run-script", ModeDescriptor::FunctionPtr(run_script)));
list_of_modes.push_back(ModeDescriptor("expand-descriptors", ModeDescriptor::FunctionPtr(expand_descriptors)));
return list_of_modes;
}
std::vector<ModeDescriptor> get_list_of_xmodes()
{
std::vector<ModeDescriptor> list_of_modes;
list_of_modes.push_back(ModeDescriptor("x-query-balls-sequences-pairings-stats", ModeDescriptor::FunctionPtr(query_balls_sequences_pairings_stats)));
list_of_modes.push_back(ModeDescriptor("x-draw-balls", ModeDescriptor::FunctionPtr(draw_balls)));
list_of_modes.push_back(ModeDescriptor("x-query-contacts-depth-values", ModeDescriptor::FunctionPtr(query_contacts_depth_values)));
list_of_modes.push_back(ModeDescriptor("x-plot-contacts", ModeDescriptor::FunctionPtr(plot_contacts)));
list_of_modes.push_back(ModeDescriptor("x-score-contacts-potentials-stats", ModeDescriptor::FunctionPtr(score_contacts_potentials_stats)));
list_of_modes.push_back(ModeDescriptor("x-score-contacts-energy-stats", ModeDescriptor::FunctionPtr(score_contacts_energy_stats)));
list_of_modes.push_back(ModeDescriptor("x-vectorize-contacts", ModeDescriptor::FunctionPtr(vectorize_contacts)));
list_of_modes.push_back(ModeDescriptor("x-vectorize-points", ModeDescriptor::FunctionPtr(vectorize_points)));
list_of_modes.push_back(ModeDescriptor("x-calculate-mock-solvent", ModeDescriptor::FunctionPtr(calculate_mock_solvent)));
list_of_modes.push_back(ModeDescriptor("x-query-contacts-simulating-unfolding", ModeDescriptor::FunctionPtr(query_contacts_simulating_unfolding)));
list_of_modes.push_back(ModeDescriptor("x-vectorize-contact-environments", ModeDescriptor::FunctionPtr(vectorize_contact_environments)));
list_of_modes.push_back(ModeDescriptor("x-write-qa-scores-in-casp-format", ModeDescriptor::FunctionPtr(write_qa_scores_in_casp_format)));
list_of_modes.push_back(ModeDescriptor("x-score-contacts-global-energy-by-cuts", ModeDescriptor::FunctionPtr(score_contacts_global_energy_by_cuts)));
list_of_modes.push_back(ModeDescriptor("x-simulate-potential-for-membrane-proteins", ModeDescriptor::FunctionPtr(simulate_potential_for_membrane_proteins)));
list_of_modes.push_back(ModeDescriptor("x-query-contacts-solvation-values", ModeDescriptor::FunctionPtr(query_contacts_solvation_values)));
list_of_modes.push_back(ModeDescriptor("x-query-contacts-interchain-exposure-values", ModeDescriptor::FunctionPtr(query_contacts_interchain_exposure_values)));
list_of_modes.push_back(ModeDescriptor("x-score-scores", ModeDescriptor::FunctionPtr(score_scores)));
list_of_modes.push_back(ModeDescriptor("x-demo-ses", ModeDescriptor::FunctionPtr(demo_ses)));
list_of_modes.push_back(ModeDescriptor("x-rotational-optimization-demo", ModeDescriptor::FunctionPtr(rotational_optimization_demo)));
list_of_modes.push_back(ModeDescriptor("x-place-membrane", ModeDescriptor::FunctionPtr(place_membrane)));
list_of_modes.push_back(ModeDescriptor("x-demo-polygon-triangulation", ModeDescriptor::FunctionPtr(demo_polygon_triangulation)));
list_of_modes.push_back(ModeDescriptor("x-demo-hypercut", ModeDescriptor::FunctionPtr(demo_hypercut)));
list_of_modes.push_back(ModeDescriptor("x-draw-values-bitmap", ModeDescriptor::FunctionPtr(draw_values_bitmap)));
list_of_modes.push_back(ModeDescriptor("x-reprint-hbp", ModeDescriptor::FunctionPtr(reprint_hbp)));
list_of_modes.push_back(ModeDescriptor("x-compare-files-as-sets", ModeDescriptor::FunctionPtr(compare_files_as_sets)));
list_of_modes.push_back(ModeDescriptor("x-calculate-path-centralities", ModeDescriptor::FunctionPtr(calculate_path_centralities)));
list_of_modes.push_back(ModeDescriptor("x-query-balls-distances", ModeDescriptor::FunctionPtr(query_balls_distances)));
list_of_modes.push_back(ModeDescriptor("x-split-atoms-file", ModeDescriptor::FunctionPtr(split_atoms_file)));
list_of_modes.push_back(ModeDescriptor("x-demo-blank", ModeDescriptor::FunctionPtr(demo_blank)));
return list_of_modes;
}
void print_error_message(const std::string& mode, const std::string& message)
{
std::cerr << "Voronota version " << voronota::version();
if(!mode.empty())
{
std::cerr << " command '" << mode << "'";
}
std::cerr << " exit error: " << message;
std::cerr << std::endl;
}
int main(const int argc, const char** argv)
{
const std::string mode=(argc>1 ? std::string(argv[1]) : std::string());
const std::string xmode_prefix="x-";
const bool xmode=(mode.rfind(xmode_prefix, 0)==0);
std::cin.exceptions(std::istream::badbit);
std::cout.exceptions(std::ostream::badbit);
std::ios_base::sync_with_stdio(false);
try
{
voronota::auxiliaries::ProgramOptionsHandler poh(argc, argv);
const bool help=poh.contains_option("--help");
{
const std::string output_precision_option_name="--stdout-precision";
if(poh.contains_option_with_argument(output_precision_option_name))
{
std::cout << std::fixed;
std::cout.precision(poh.argument<int>(output_precision_option_name));
poh.remove_option(output_precision_option_name);
}
}
if(!xmode)
{
const std::vector<ModeDescriptor> list_of_modes=get_list_of_modes();
if(!mode.empty() && std::count(list_of_modes.begin(), list_of_modes.end(), mode)>0)
{
std::find(list_of_modes.begin(), list_of_modes.end(), mode)->func_ptr(poh);
return (help ? 1 : 0);
}
else
{
std::ostream& output=std::cout;
output << "Voronota version " << voronota::version() << "\n\n";
output << "Commands:\n\n";
for(std::vector<ModeDescriptor>::const_iterator it=list_of_modes.begin();it!=list_of_modes.end();++it)
{
output << it->name << "\n";
}
output << "\n";
if(help)
{
for(std::vector<ModeDescriptor>::const_iterator it=list_of_modes.begin();it!=list_of_modes.end();++it)
{
output << "Command '" << it->name << "' options:\n";
it->func_ptr(poh);
output << "\n";
}
}
}
}
else
{
const std::vector<ModeDescriptor> list_of_modes=get_list_of_xmodes();
if(!mode.empty() && std::count(list_of_modes.begin(), list_of_modes.end(), mode)>0)
{
std::find(list_of_modes.begin(), list_of_modes.end(), mode)->func_ptr(poh);
return (help ? 1 : 0);
}
else
{
throw std::runtime_error("Invalid xmode.");
}
}
return 1;
}
catch(const std::exception& e)
{
print_error_message(mode, e.what());
}
catch(...)
{
print_error_message(mode, "Unknown exception caught.");
}
return 2;
}
|
e4f524804becb61760b52d39e2d5b44c3f676274 | a69bed1a6cfc3df6d2a13401e249550956f36cdc | /sw-expert-academy/6853. 직사각형과 점.cpp | 0ae042702b7a7590d369082d33cac899335ed2f7 | [] | no_license | junhwanyun/problem-solving | ef63f009b7b383706541526ea6625cac414a6d5d | e360c4cf0c09827234beb91857b4cc95b641e86b | refs/heads/master | 2021-07-16T13:06:02.166177 | 2021-01-04T12:47:35 | 2021-01-04T12:47:35 | 235,753,269 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 587 | cpp | 6853. 직사각형과 점.cpp | #include <iostream>
using namespace std;
int T, X1, Y1, X2, Y2, N;
int result, res, r;
int main() {
cin >> T;
for(int t = 1; t <= T; t++) {
result = 0;
res = 0;
r = 0;
cin >> X1 >> Y1 >> X2 >> Y2;
cin >> N;
int x;
int y;
for(int i = 0; i < N; i++) {
cin >> x >> y;
if(x > X1 && x < X2 && y > Y1 && y < Y2) {
result++;
}else if(x < X1 || x > X2 || y < Y1 || y > Y2) {
r++;
}else {
res++;
}
}
cout << '#' << t << ' ' << result << ' ' << res << ' ' << r << '\n';
}
return 0;
}
|
b70e7e24f2d155bb392f2d7253ea9bf41424b939 | 03ba0b0f140549f4022793e57859f5c400cc9892 | /ZFFramework/src/ZFCore/ZFObjectDef/ZFObjectUtilDef.cpp | d732240c72b9cce4cfa938c035e9ca798f2a746f | [
"MIT"
] | permissive | nifh80s/ZFFramework | f6f17fb6d4dfc9645f96a923f2313195417c62ad | b88a4d750ec5c5b30bc3bf445c8144acc3386dcd | refs/heads/master | 2020-12-03T09:17:03.671149 | 2016-01-16T09:33:55 | 2016-01-16T09:33:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,796 | cpp | ZFObjectUtilDef.cpp | /* ====================================================================== *
* Copyright (c) 2010-2015 ZSaberLv0
* home page: http://ZFFramework.com
* blog: http://zsaber.com
* contact: master@zsaber.com (Chinese and English only)
*
*
* Distributed under MIT license:
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* ====================================================================== */
#include "ZFPrivate_ZFCore_ZFObjectDef.hh"
#include "ZFObjectUtilDef.h"
ZF_NAMESPACE_GLOBAL_BEGIN
// ============================================================
// ZFPointerHolder
ZFOBJECT_REGISTER(ZFPointerHolder)
#define _ZFP_ZFPointerHolderCacheSize 5
static ZFPointerHolder *_ZFP_ZFPointerHolderCache[_ZFP_ZFPointerHolderCacheSize];
static ZFPointerHolder **_ZFP_ZFPointerHolderCacheAvailable = _ZFP_ZFPointerHolderCache - 1;
static ZFPointerHolder **_ZFP_ZFPointerHolderCacheAvailableEnd = _ZFP_ZFPointerHolderCache + _ZFP_ZFPointerHolderCacheSize - 1;
ZF_GLOBAL_INITIALIZER_INIT_WITH_LEVEL(ZFPointerHolderCacheHolder, ZFLevelZFFrameworkEssential)
{
zfmemset(_ZFP_ZFPointerHolderCache, 0, sizeof(_ZFP_ZFPointerHolderCache));
_ZFP_ZFPointerHolderCacheAvailable = _ZFP_ZFPointerHolderCache - 1;
}
ZF_GLOBAL_INITIALIZER_DESTROY(ZFPointerHolderCacheHolder)
{
while(_ZFP_ZFPointerHolderCacheAvailable >= _ZFP_ZFPointerHolderCache)
{
zfReleaseInternal(*_ZFP_ZFPointerHolderCacheAvailable);
--_ZFP_ZFPointerHolderCacheAvailable;
}
}
ZF_GLOBAL_INITIALIZER_END(ZFPointerHolderCacheHolder)
ZFPointerHolder *ZFPointerHolder::cacheAccess(void)
{
ZFPointerHolder *ret = zfnull;
ZFCoreMutexLock();
if(_ZFP_ZFPointerHolderCacheAvailable >= _ZFP_ZFPointerHolderCache)
{
ret = *_ZFP_ZFPointerHolderCacheAvailable;
--_ZFP_ZFPointerHolderCacheAvailable;
}
else
{
ret = zfAllocInternal(ZFPointerHolder);
}
ZFCoreMutexUnlock();
return ret;
}
void ZFPointerHolder::cacheRelease(ZF_IN ZFPointerHolder *obj)
{
ZFCoreMutexLock();
obj->holdedData = zfnull;
obj->tagRemoveAll();
if(_ZFP_ZFPointerHolderCacheAvailable == _ZFP_ZFPointerHolderCacheAvailableEnd)
{
zfReleaseInternal(obj);
}
else
{
++_ZFP_ZFPointerHolderCacheAvailable;
*_ZFP_ZFPointerHolderCacheAvailable = obj;
}
ZFCoreMutexUnlock();
}
void ZFPointerHolder::objectInfoT(ZF_IN_OUT zfstring &ret)
{
ret += ZFTOKEN_ZFObjectInfoLeft;
ret += ZFPointerHolder::ClassData()->className();
ret += zfText(" ");
ret += zfsFromPointer(this->holdedData);
ret += ZFTOKEN_ZFObjectInfoRight;
}
void ZFPointerHolder::objectInfoVerboseT(ZF_IN_OUT zfstring &ret)
{
ret += ZFTOKEN_ZFObjectInfoLeft;
ret += ZFPointerHolder::ClassData()->className();
ret += zfstringWithFormat(zfText("(%p) %p"), this, this->holdedData);
ret += ZFTOKEN_ZFObjectInfoRight;
}
zfidentity ZFPointerHolder::objectHash(void)
{
return zfidentityCalcPointer(this->holdedData);
}
ZFCompareResult ZFPointerHolder::objectCompare(ZF_IN ZFObject *anotherObj)
{
if(this == anotherObj) {return ZFCompareTheSame;}
zfself *another = ZFCastZFObject(zfself *, anotherObj);
if(another == zfnull) {return ZFCompareUncomparable;}
if(this->holdedData == another->holdedData)
{
return ZFCompareTheSame;
}
else
{
return ZFCompareUncomparable;
}
}
// ============================================================
// ZFTypeHolder
ZFOBJECT_REGISTER(ZFTypeHolder)
void ZFTypeHolder::objectInfoT(ZF_IN_OUT zfstring &ret)
{
ret += ZFTOKEN_ZFObjectInfoLeft;
ret += ZFTypeHolder::ClassData()->className();
ret += zfText(" ");
ret += zfsFromPointer(this->holdedData);
ret += ZFTOKEN_ZFObjectInfoRight;
}
void ZFTypeHolder::objectInfoVerboseT(ZF_IN_OUT zfstring &ret)
{
ret += ZFTOKEN_ZFObjectInfoLeft;
ret += ZFTypeHolder::ClassData()->className();
ret += zfstringWithFormat(zfText("(%p) %p %p"),
this, this->holdedData, ZFCastReinterpret(void *, this->deleteCallback));
ret += ZFTOKEN_ZFObjectInfoRight;
}
zfidentity ZFTypeHolder::objectHash(void)
{
return zfidentityHash(
zfidentityCalcPointer(this->holdedData),
zfidentityCalcPointer(ZFCastReinterpret(void *, this->deleteCallback)));
}
ZFCompareResult ZFTypeHolder::objectCompare(ZF_IN ZFObject *anotherObj)
{
if(this == anotherObj) {return ZFCompareTheSame;}
zfself *another = ZFCastZFObject(zfself *, anotherObj);
if(another == zfnull) {return ZFCompareUncomparable;}
if(this->holdedData == another->holdedData
&& this->deleteCallback == another->deleteCallback)
{
return ZFCompareTheSame;
}
else
{
return ZFCompareUncomparable;
}
}
ZF_NAMESPACE_GLOBAL_END
|
254f36c96dae8fe210c77fdfe26b89093b96dbc2 | 0207f0b9af36ac91c1f8fb0112b194565299cb96 | /Assignment2.10/MonsterChaseDX/MonsterEngine/MessageSystem.h | a15605e7a3b2576e50ad0f4600976352e5508182 | [] | no_license | yashkapani/2DGameEngine | dc204503b11fd9890583a93f149da167ae163a12 | 0021947fb981281098fa0560b28328e67e31da58 | refs/heads/master | 2021-07-25T19:40:21.234862 | 2017-11-08T20:43:47 | 2017-11-08T20:43:47 | 110,028,411 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 715 | h | MessageSystem.h | #ifndef __MESSAGE_SYSTEM_H
#define __MESSAGE_SYSTEM_H
#include "HashedString.h"
#include <map>
#include <vector>
namespace Engine
{
class MessageSystem
{
public:
class IMessageHandler
{
public:
virtual ~IMessageHandler();
virtual void HandleMessage(const HashedString & i_Message, void * i_pMessageSender, void * i_pMessageData) = 0;
};
static void AddMessageHandler(const HashedString & i_Message, IMessageHandler * i_pHandler);
static void SendMessage(const HashedString & i_Message, void * i_pMessageSender, void * i_pMessageData);
private:
static std::map< HashedString, std::vector<IMessageHandler *> > m_MessageHandlers;
};
} // namespace Engine
#endif // __MESSAGE_SYSTEM_H |
31f425834ad215f614e6b9f7822267e0a725f119 | 0d653408de7c08f1bef4dfba5c43431897097a4a | /cmajor/soulng/util/Log.cpp | d1285795299d5ec95b75ac2319ddd99b7e1aa5b7 | [] | no_license | slaakko/cmajorm | 948268634b8dd3e00f86a5b5415bee894867b17c | 1f123fc367d14d3ef793eefab56ad98849ee0f25 | refs/heads/master | 2023-08-31T14:05:46.897333 | 2023-08-11T11:40:44 | 2023-08-11T11:40:44 | 166,633,055 | 7 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,625 | cpp | Log.cpp | // =================================
// Copyright (c) 2022 Seppo Laakko
// Distributed under the MIT license
// =================================
#include <soulng/util/Log.hpp>
#include <soulng/util/TextUtils.hpp>
#include <soulng/util/Unicode.hpp>
#include <iostream>
#include <mutex>
#include <list>
#include <condition_variable>
#include <thread>
#include <chrono>
#include <atomic>
namespace soulng { namespace util {
using namespace soulng::unicode;
#ifndef __MINGW32__
std::mutex logMutex;
std::condition_variable messageEnqueuedOrEndLog;
#endif
LogMode logMode = LogMode::console;
bool endLog = false;
std::list<std::string> log;
void SetLogMode(LogMode mode)
{
logMode = mode;
}
void StartLog()
{
endLog = false;
}
void EndLog()
{
#ifndef __MINGW32__
for (int i = 0; i < 10; ++i)
{
if (!log.empty())
{
messageEnqueuedOrEndLog.notify_one();
std::this_thread::sleep_for(std::chrono::milliseconds{ 500 });
}
else
{
break;
}
}
endLog = true;
messageEnqueuedOrEndLog.notify_one();
#endif
}
void LogMessage(int logStreamId, const std::string& message)
{
#ifndef __MINGW32__
std::lock_guard<std::mutex> lock(logMutex);
#endif
if (logMode == LogMode::console)
{
if (logStreamId == -1)
{
std::cout << message << std::endl;
}
else
{
std::cout << Format(std::to_string(logStreamId), 2, FormatWidth::min, FormatJustify::right, '0') << ">" << message << std::endl;
}
}
else if (logMode == LogMode::queue)
{
if (logStreamId == -1)
{
log.push_back(message);
}
else
{
log.push_back(Format(std::to_string(logStreamId), 2, FormatWidth::min, FormatJustify::right, '0') + ">" + message);
}
#ifndef __MINGW32__
messageEnqueuedOrEndLog.notify_one();
#endif
}
}
void LogMessage(int logStreamId, const std::string& message, int indent)
{
LogMessage(logStreamId, std::string(indent, ' ') + message);
}
std::string logMessage;
int WaitForLogMessage()
{
#ifndef __MINGW32__
std::unique_lock<std::mutex> lock(logMutex);
messageEnqueuedOrEndLog.wait(lock, []{ return !log.empty() || endLog; });
if (!log.empty())
{
logMessage = log.front();
log.pop_front();
return logMessage.length();
}
else
{
return -1;
}
#else
return -1;
#endif
}
int FetchLogMessage(char16_t* buf, int size)
{
std::u16string utf16LogMessage = ToUtf16(logMessage);
if (size <= utf16LogMessage.length())
{
return -1;
}
else
{
int n = utf16LogMessage.length();
for (int i = 0; i < n; ++i)
{
char16_t c = utf16LogMessage[i];
buf[i] = c;
}
buf[n] = u'\0';
return n;
}
}
std::string FetchLogMessage(bool& endOfLog, int timeoutMs, bool& timeout)
{
#ifndef __MINGW32__
endOfLog = false;
std::unique_lock<std::mutex> lock(logMutex);
if (timeoutMs)
{
if (!messageEnqueuedOrEndLog.wait_for(lock, std::chrono::milliseconds{ timeoutMs }, [] { return !log.empty() || endLog; }))
{
timeout = true;
return std::string();
}
}
else
{
messageEnqueuedOrEndLog.wait(lock, [] { return !log.empty() || endLog; });
}
if (!log.empty())
{
logMessage = log.front();
log.pop_front();
return logMessage;
}
#endif
endOfLog = true;
return std::string();
}
} } // namespace soulng::util
|
984767fd0d735dabb509f914faad6122a82663d6 | ef42493d2ad83def2a1b2902c684b6925218c5ba | /Optimization/boostutil.h | 58674ca39c899a2b5a9b7bd88e7f6b8b508e40fd | [
"LGPL-2.1-or-later",
"BSD-3-Clause"
] | permissive | federatedcloud/Lake_Problem_DPS | 5fcc0fe27d0261cc04869094f4015981a2213b56 | 07600c49ed543165ccdc642c1097b3bed87c28f0 | refs/heads/master | 2020-03-19T10:38:56.455896 | 2018-10-09T21:16:58 | 2018-10-09T21:16:58 | 136,389,356 | 1 | 2 | BSD-3-Clause | 2019-07-08T21:25:17 | 2018-06-06T21:44:19 | Python | UTF-8 | C++ | false | false | 1,372 | h | boostutil.h | // utility functions for boost matrices/vectors
#include <fstream>
namespace ublas = boost::numeric::ublas;
using namespace std;
double vsum(ublas::vector<double> v)
{
double s = 0.0;
for(unsigned int i = 0; i < v.size(); i++)
s += v(i);
return s;
}
double vmax(ublas::vector<double> v)
{
return *max_element(v.begin(), v.end());
}
double vmin(ublas::vector<double> v)
{
return *min_element(v.begin(), v.end());
}
void zero(ublas::vector<double> & v)
{
for(unsigned int i = 0; i < v.size(); i++)
v(i) = 0.0;
}
void loadtxt(string fname, ublas::matrix<double> & M)
{
ifstream f (fname.c_str());
if(!f.is_open())
{
cerr << "Error opening file " << fname << ". Exiting..." << endl;
exit(EXIT_FAILURE);
}
for (unsigned int i = 0; i < M.size1(); i++)
for (unsigned int j = 0; j < M.size2(); j++)
f >> M(i,j);
f.close();
}
void savetxt(string fname, ublas::matrix<double> & M)
{
ofstream f (fname.c_str());
if(!f.is_open())
{
cerr << "Error opening file " << fname << ". Exiting..." << endl;
exit(EXIT_FAILURE);
}
for (unsigned int i = 0; i < M.size1(); i++)
{
for (unsigned int j = 0; j < M.size2(); j++)
{
f << M(i,j);
if(j < M.size2()-1) f << " ";
else f << endl;
}
}
f.close();
}
|
f0ff3649a25361742e9427709fbbfbbfd676864b | 0db5517b2159d771e1afbe54a89f611452005649 | /IronWrought/Source/Engine/NodeTypeVariableGetInt.cpp | 10ebc0c81cce67dc39dd98d9537e46dec83a5d4b | [] | no_license | HaqvinBager/G3SP7 | f117be0c343469ba2eb67205a29d3b64e088ed60 | 2e04646ffbc6b9d2e78d435ff88ca56fddda10f4 | refs/heads/master | 2023-05-04T17:05:35.963943 | 2021-05-19T13:51:52 | 2021-05-19T13:51:52 | 327,616,500 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,096 | cpp | NodeTypeVariableGetInt.cpp | #include "stdafx.h"
#include "NodeTypeVariableGetInt.h"
#include "NodeInstance.h"
#include "NodeDataManager.h"
CNodeTypeVariableGetInt::CNodeTypeVariableGetInt()
{
myPins.push_back(SPin("OUT", SPin::EPinTypeInOut::EPinTypeInOut_OUT, SPin::EPinType::EInt)); //0
myPins.push_back(SPin("Local", SPin::EPinTypeInOut::EPinTypeInOut_IN, SPin::EPinType::EBool)); //1
}
int CNodeTypeVariableGetInt::OnEnter(CNodeInstance* aTriggeringNodeInstance)
{
CGameObject* gameObject = aTriggeringNodeInstance->GetCurrentGameObject();
SPin::EPinType outType;
NodeDataPtr someData = nullptr;
size_t outSize = 0;
GetDataOnPin(aTriggeringNodeInstance, 1, outType, someData, outSize);
bool local = NodeData::Get<bool>(someData);
int output;
if (!local)
output = CNodeDataManager::Get()->GetData<int>(myNodeDataKey);
else
output = CNodeDataManager::Get()->GetData<int>(myNodeDataKey + std::to_string(gameObject->InstanceID()));
std::vector<SPin>& pins = aTriggeringNodeInstance->GetPins();
DeclareDataOnPinIfNecessary<int>(pins[0]);
memcpy(pins[0].myData, &output, sizeof(int));
return -1;
} |
1d96e35cfe79e2051fa690864ea95af080870719 | 5832f65747e6142d1b8de9d46aa507092782aafc | /Codeforces/Codeforces Round #202 (Div. 2) - 349/349A-Cinema Line.cpp | d87479407928b491429b315c68443aff854b9fd5 | [] | no_license | subhashreddykallam/Competitive-Programming | 64cc42c5b23c03536187a1bb54e2b2ed82ee7844 | 973b66b4eb81352b98409ca52fa3aa75c28d8b6f | refs/heads/master | 2022-05-28T21:07:43.012922 | 2020-05-05T20:34:20 | 2020-05-05T20:34:20 | 226,814,369 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 958 | cpp | 349A-Cinema Line.cpp | #include<bits/stdc++.h>
using namespace std;
# define ll long long
# define append push_back
# define add insert
# define loop(i, k, n, inc) for(ll i = k; i < n; i+=inc)
# define rloop(i, k, n, inc) for(ll i = k; i > n; i+=inc)
# define printlist(a) {for(auto i : a){cout<<i<<' '; cout<<'\n';}}
int main(){
ios_base::sync_with_stdio(false);
ll n; cin>>n;
map<ll, ll> d;
loop(i, 0, n, 1){
int x; cin>>x;
if (x==25) d[25]++;
else if (x==50){
d[50]++;
if (d[25]) d[25]--;
else{
cout<<"NO\n";
return 0;
}
}
else{
d[100]++;
if ((d[25] >= 1 && d[50] >= 1)){
d[25]--;
d[50]--;
}
else if (d[25] >= 3) d[25]-=3;
else {
cout<<"NO\n";
return 0;
}
}
}
cout<<"YES\n";
return 0;
} |
bbed36208c595d5a2a3c7d3b6d3e10b70e1c9390 | e30e2263ed121c849edc8094f0c0b4cec4b1f862 | /Bölüm 2 PDF Rev/Bolum_2_Uyg_8/Bolum_2_Uyg_8.ino | e66f8aa56c643d98e92bc3c73feece5e90cb3025 | [] | no_license | tayfunslife/pratikarduinouygulamalar | 689e903911d7ac4d090c7c8e3d389f25fc9cc45b | c8c6aafa26d1b1a3b134b11f35af4bee19f18467 | refs/heads/master | 2021-06-12T06:41:01.676810 | 2017-03-12T14:50:01 | 2017-03-12T14:50:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 548 | ino | Bolum_2_Uyg_8.ino | int xPin = A1;
int yPin = A2;
int butonPin = A0;
int xPozisyonu = 0;
int yPozisyonu = 0;
int butonDurum = 0;
void setup() {
Serial.begin(9600);
pinMode(xPin, INPUT);
pinMode(yPin, INPUT);
pinMode(butonPin, INPUT_PULLUP);
}
void loop() {
xPozisyonu = analogRead(xPin);
yPozisyonu = analogRead(yPin);
butonDurum = digitalRead(butonPin);
Serial.print("X: ");
Serial.print(xPozisyonu);
Serial.print(" | Y: ");
Serial.print(yPozisyonu);
Serial.print(" | Buton: ");
Serial.println(butonDurum);
delay(1000);
}
|
5a07e16840de6073ba9ce97136315afdbc536c5c | 74b07525eb549885dee25faf259959c3f2b3ced8 | /Backtracking/GenerateallParenthesesII.cpp | 66847879005cc5b4c48c5ff77bf6d0da4c637c5d | [
"MIT"
] | permissive | ashaywalke/InterviewBit-Solutions | 6ce1e5a8a48d3fcbf2739fcb7310acbbfb5f8442 | 6757929e1fd3e65780cc4243266c1d477a2d225b | refs/heads/master | 2020-03-30T19:47:27.847666 | 2018-10-04T11:05:19 | 2018-10-04T11:05:19 | 151,558,475 | 1 | 0 | MIT | 2018-10-04T11:03:49 | 2018-10-04T11:03:49 | null | UTF-8 | C++ | false | false | 756 | cpp | GenerateallParenthesesII.cpp | //https://www.interviewbit.com/problems/generate-all-parentheses-ii/
void sol(int n1, int n2, int N, string str, vector<string> &S)
{
if(n1 + n2 == 2*N )
{
S.push_back(str);
}
else
{
if(n1>=n2 )
{
if(n1<N){
str.push_back('(');
sol(n1+1, n2, N, str, S);
}
if(n1!=n2)
{
if(n1==N)str.push_back(')');
else str[str.length()-1] = ')';
sol(n1, n2+1, N, str, S);
}
}
else return;
}
}
vector<string> Solution::generateParenthesis(int N)
{
string str;
vector<string> S;
sol(0, 0, N, str, S);
sort(S.begin(), S.end());
return S;
}
|
0d174ae4da5e153e870c5fb5f7b5ea8ae3ab2195 | b03d0f363ce4254eeade58d4da6aa84f0fd9c652 | /HelperFiles/Lex_cpp/util.h | ffc21721db062183109936794c6fd50092c5a589 | [] | no_license | suix2/TCompiler | beb556a389be2fb4559abf35f3222d6f0ea9d9d3 | 3a4ec8a9d7ff3c3a1914fad60d6258fa0f8b5644 | refs/heads/master | 2020-04-06T07:17:12.466339 | 2016-09-10T09:19:19 | 2016-09-10T09:19:19 | 65,870,990 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 603 | h | util.h | #ifndef UTIL_H
#include <iostream>
#include <memory>
namespace util
{
class U_BoolList
{
using SP_U_BoolList=std::shared_ptr<U_BoolList>;
friend SP_U_BoolList get_U_BoolList(bool head, SP_U_BoolList tail);
private:
U_BoolList(){}
public:
bool head;
SP_U_BoolList tail;
SP_U_BoolList get_U_BoolList(bool head, SP_U_BoolList tail);
};
using SP_U_BoolList=std::shared_ptr<U_BoolList>;
SP_U_BoolList get_U_BoolList(bool head, SP_U_BoolList tail);
}
#define UTIL_H
#endif
|
883300654fdde82c6426725d901f7d01e4a0b3e0 | dccd1058e723b6617148824dc0243dbec4c9bd48 | /yukicoder/349.cpp | a3e0b64e1a4daad8f91e4b13d88335dba6ad5cf0 | [] | no_license | imulan/procon | 488e49de3bcbab36c624290cf9e370abfc8735bf | 2a86f47614fe0c34e403ffb35108705522785092 | refs/heads/master | 2021-05-22T09:24:19.691191 | 2021-01-02T14:27:13 | 2021-01-02T14:27:13 | 46,834,567 | 7 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 559 | cpp | 349.cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i,n) for(i=0;i<n;++i)
#define each(itr,c) for(__typeof(c.begin()) itr=c.begin(); itr!=c.end(); ++itr)
#define mp make_pair
#define pb push_back
#define fi first
#define sc second
int main()
{
int i;
int n;
cin >>n;
map<string,int> m;
rep(i,n)
{
string a;
cin >>a;
if(m.find(a)==m.end()) m[a]=1;
else ++m[a];
}
int x=0;
each(it,m) x=max(x,it->sc);
//std::cout << x << std::endl;
string ans="NO";
if(x<=(n+1)/2) ans="YES";
std::cout << ans << std::endl;
}
|
2eacda73405b134eafcb46ccab3944d37ec5259d | 7c60a4cd1cc117f1b76d2cbf101074500e72f471 | /obd/src/protocols/AbstractCANProtocol.cpp | b3533acfae9629afcc0eb8031fbc25c6abc34962 | [
"Apache-2.0"
] | permissive | Yanick-Salzmann/carpi | 0d32b452fe2c0e69434e3aa5989b6993af90e0db | 29f5e1bf1eb6243e45690f040e4df8e7c228e897 | refs/heads/master | 2020-09-15T23:26:07.396758 | 2020-03-28T22:07:36 | 2020-03-28T22:07:36 | 223,575,460 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,005 | cpp | AbstractCANProtocol.cpp | #include <common_utils/conversion.hpp>
#include "obd/protocols/AbstractCANProtocol.hpp"
namespace carpi::obd::protocols {
LOGGER_IMPL(AbstractCANProtocol);
AbstractCANProtocol::AbstractCANProtocol(const StringVector &init_lines, std::size_t num_id_bits) : _num_id_bits(num_id_bits) {
process_init_lines(init_lines);
}
bool AbstractCANProtocol::parse_frame(msg::ObdFrame &frame) {
auto raw = frame.raw();
if (_num_id_bits == 11) {
raw = std::string{"00000"} + raw;
}
std::vector<uint8_t> raw_data{};
if (!parse_and_verify_frame_data(raw, raw_data, 6, 12)) {
return false;
}
if (_num_id_bits == 11) {
frame.priority(raw_data[2] & 0x0Fu)
.addr_mode(raw_data[3] & 0xF0u);
if (frame.addr_mode() == 0xD0) {
frame.rx_id(raw_data[3] & 0x0Fu)
.tx_id(0xF1);
} else if (raw_data[3] & 0x08u) {
frame.rx_id(0xF1)
.tx_id(raw_data[3] & 0x07u);
} else {
frame.rx_id(raw_data[3] & 0x07u)
.tx_id(0xF1);
}
} else {
frame.priority(raw_data[0])
.addr_mode(raw_data[1])
.rx_id(raw_data[2])
.tx_id(raw_data[3]);
}
std::vector<uint8_t> frame_data{raw_data.begin() + 4, raw_data.end()};
frame.data(frame_data)
.type((frame_data[0] & 0xF0u) >> 4u);
switch(frame.type()) {
case FRAME_TYPE_SINGLE: {
frame.data_size(frame_data[0] & 0x0Fu);
if(!frame.data_size()) {
return false;
}
break;
}
case FRAME_TYPE_FIRST: {
frame.data_size(((frame_data[0] & 0x0Fu) << 8u) | (frame_data[1]));
if(!frame.data_size()) {
return false;
}
break;
}
case FRAME_TYPE_SEQUENCE: {
frame.sequence(frame_data[0] & 0x0Fu);
break;
}
default: {
log->debug("Dropping frame with unknown frame type. Frame data: {}", frame);
return false;
}
}
return true;
}
bool AbstractCANProtocol::tx_id_engine_constant(uint32_t &tx_id) const {
tx_id = TX_ID_ENGINE;
return true;
}
bool AbstractCANProtocol::tx_id_transmission_constant(uint32_t &tx_id) const {
tx_id = TX_ID_TRANSMISSION;
return true;
}
bool AbstractCANProtocol::parse_message(msg::ObdMessage &msg) {
auto frames = msg.frames();
if(frames.size() == 1) {
const auto& frame = frames[0];
if(frame.type() != FRAME_TYPE_SINGLE) {
log->warn("Dropping message with single frame that is not marked as FRAME_TYPE_SINGLE: {}", frame);
return false;
}
auto frame_data = frame.data();
msg.data() = std::vector<uint8_t>{frame_data.begin() + 1, frame_data.begin() + 1 + frame.data_size()};
} else {
std::vector<msg::ObdFrame> first_frames{};
std::vector<msg::ObdFrame> next_frames{};
for(const auto& frame : msg.frames()) {
if(frame.type() == FRAME_TYPE_FIRST) {
first_frames.emplace_back(frame);
} else if(frame.type() == FRAME_TYPE_SEQUENCE) {
next_frames.emplace_back(frame);
} else {
log->debug("Ignoring frame that is not marked as FRAME_TYPE_FIRST or FRAME_TYPE_SEQUENCE in multi frame message: {}", frame);
}
}
if(first_frames.size() != 1) {
log->warn("Received multiple or no frames marked as FRAME_TYPE_FIRST. Must be exactly one, but got {}. Dropping message", first_frames.size());
return false;
}
if(next_frames.empty()) {
log->warn("Received multiple frames, but none marked as FRAME_TYPE_SEQUENCE. Dropping message");
return false;
}
auto last_seq = next_frames[0].sequence();
for(auto i = std::size_t{1}; i < next_frames.size(); ++i) {
auto& cur_frame = next_frames[i];
auto seq = (last_seq & 0xF0u) + cur_frame.sequence();
if(seq + 7 < last_seq) {
seq += 0x10;
}
last_seq = seq;
cur_frame.sequence(seq);
}
std::sort(next_frames.begin(), next_frames.end(), [](const auto& f1, const auto& f2) {
return f1.sequence() < f2.sequence();
});
if(!verify_frame_order(next_frames)) {
return false;
}
std::vector<uint8_t> msg_data{};
const auto first_frame_data = first_frames[0].data();
msg_data.insert(msg_data.end(), first_frame_data.begin() + 2, first_frame_data.end());
for(const auto& frame : next_frames) {
const auto frame_data = frame.data();
msg_data.insert(msg_data.end(), frame_data.begin() + 1, frame_data.end());
}
msg_data.resize(first_frames[0].data_size());
msg.data() = msg_data;
}
if(msg.data()[0] == 0x43) {
const auto dtc_size = msg.data()[1] * 2;
msg.data().resize(dtc_size + 2);
}
return true;
}
bool AbstractCANProtocol::verify_frame_order(const std::vector<msg::ObdFrame> &frames) {
uint32_t next_index = 1;
for (const auto &frame : frames) {
if (frame.sequence() != next_index) {
return false;
}
++next_index;
}
return true;
}
} |
be98c6773f1222a76a038e75df1404b1ab40b756 | 08117ab7baf16d5ff519c8434d79c5f7263b0630 | /codeforces/510A.cpp | 15639a3fc9c58d660f84aea89c2bf99cdaaa9d20 | [] | no_license | wh00am1/practice | 4c66b0543ac96e971e8aacf787911b191f34e518 | cb7fca4fc4dc6fb6717410727ed7be51793b879a | refs/heads/master | 2023-04-07T09:06:41.857372 | 2023-03-20T11:42:02 | 2023-03-20T11:42:02 | 252,885,225 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 687 | cpp | 510A.cpp | #include <bits/stdc++.h>
#pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
#define ll long long
#define ld long double
#define endl " \n"
#define FOR(a, b) for(ll (a)=0; (a)<(ll)(b); ++(a))
#define EACH(u, v) for(auto& u : v)
using namespace std;
const int INF = 0x3f3f3f3f;
void AkagiMyWife(){
ios_base::sync_with_stdio(0);
cin.tie(0);
}
int main(int argc, char const *argv[]){
AkagiMyWife();
int n, m, ctr=0;
cin >> n >> m;
FOR(i, n){
if(i&1){
if(ctr&1){
cout << '#';
FOR(j, m-1) cout << '.';
}
else
FOR(j, m) cout << ".#"[j==m-1];
++ctr;
}
else
FOR(j, m) cout << '#';
cout << endl[1];
}
return 0;
}
|
aa11b99745644c593ef1c520e5c910efcd70dbd4 | f86d8682bfd7961f2633b268bb342a953efac152 | /transpiler/benchmarks/arithmetic_openfhe.cc | c467f6a28cc7cb2d298331c21fe4d9f4afcf9560 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | google/fully-homomorphic-encryption | b0484efd43503c951c21ae92719401cb6bdb8e11 | c3ce0498b85fbf891ff83e2345e194d0141a0033 | refs/heads/main | 2023-08-31T17:15:42.946914 | 2023-08-24T20:49:40 | 2023-08-24T20:50:19 | 364,705,340 | 3,419 | 249 | Apache-2.0 | 2023-09-06T13:36:59 | 2021-05-05T21:04:00 | C++ | UTF-8 | C++ | false | false | 1,948 | cc | arithmetic_openfhe.cc | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <stdint.h>
#include "benchmark/benchmark.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "openfhe/binfhe/binfhecontext.h"
#include "transpiler/data/openfhe_data.h"
#ifdef USE_YOSYS_OPTIMIZER
#include "transpiler/benchmarks/add_char_yosys_openfhe.h"
#include "transpiler/benchmarks/add_int_yosys_openfhe.h"
#else
#include "transpiler/benchmarks/add_char_xls_openfhe.h"
#include "transpiler/benchmarks/add_int_xls_openfhe.h"
#endif
// OpenFHE parameters
constexpr lbcrypto::BINFHE_PARAMSET kSecurityLevel = lbcrypto::MEDIUM;
void BM_AddChar(benchmark::State& state) {
auto cc = lbcrypto::BinFHEContext();
cc.GenerateBinFHEContext(kSecurityLevel);
auto sk = cc.KeyGen();
cc.BTKeyGen(sk);
auto a = OpenFhe<char>::Encrypt('a', cc, sk);
auto b = OpenFhe<char>::Encrypt('b', cc, sk);
OpenFhe<char> result(cc);
for (auto s : state) {
benchmark::DoNotOptimize(AddChar(result, a, b, cc));
}
}
BENCHMARK(BM_AddChar);
void BM_AddInt(benchmark::State& state) {
auto cc = lbcrypto::BinFHEContext();
cc.GenerateBinFHEContext(kSecurityLevel);
auto sk = cc.KeyGen();
cc.BTKeyGen(sk);
auto a = OpenFhe<int>::Encrypt('a', cc, sk);
auto b = OpenFhe<int>::Encrypt('b', cc, sk);
OpenFhe<int> result(cc);
for (auto s : state) {
benchmark::DoNotOptimize(AddInt(result, a, b, cc));
}
}
BENCHMARK(BM_AddInt);
|
4dbba85a0a88c0d1e6a25a238951b943dd87f6ed | 8da8b9f81cbe0871e5e5f38080bbddf0adaff309 | /exercicios/beecrowd/ad-hoc/1618.cpp | 7d857497f346905386e3f55114ceed1189456f08 | [] | no_license | jessicaccp/competitive-programming | 7727f79845895043364ef2f284f229782fc91b4a | 87939b6938fa0346d220b776470d7dfefeb7c5a5 | refs/heads/master | 2022-07-23T13:10:54.844877 | 2022-07-17T01:43:19 | 2022-07-17T01:43:19 | 94,829,627 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 350 | cpp | 1618.cpp | #include<bits/stdc++.h>
using namespace std;
int main () {
ios_base::sync_with_stdio(false);
int t, ax, ay, bx, by, cx, cy, dx, dy, rx, ry;
cin >> t;
while (t--) {
cin >> ax >> ay >> bx >> by >> cx >> cy >> dx >> dy >> rx >> ry;
if (rx>=ax and rx<=cx and ry>=ay and ry<=cy)
cout << "1\n";
else
cout << "0\n";
}
return 0;
}
|
646e4539eb61093902c10d62902efc797c1ad32e | dcee007c5bd1580d3ba359b5de7d6d1a03f503dd | /lesson7/2-4.cpp | 5998dd30b2568fee9615464b88e960046d3c9009 | [] | no_license | guolalala/Summer-lesson2021 | 2f13c8ecead18977e4b659ab2a18550252b36a39 | 465131fb2c210bb938ff740127b35fa55a8a4818 | refs/heads/main | 2023-07-20T10:52:07.858621 | 2021-09-05T06:03:13 | 2021-09-05T06:03:13 | 386,492,733 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,103 | cpp | 2-4.cpp | //4级龙格库塔R-K法(经典法)
//ODE
#include <iostream>
#include <sstream>
#include <iomanip>
#include <cmath>
#define maxn 100
#define MAX 20
using namespace std;
#define Error 1e-6
void RK4(double ta,double tb,double y0,int M);//4级龙格库塔R-K法
double f(double t,double y);
double y_t(double t);
int main()
{
int i;
printf("四级龙格库达塔法求解常微分方程1\n");
printf("步长h\t步数M\ty(3)近似值yM\ty(3)-yM\t\tO(h)\n");
for(i=0;i<=6;i++)
{
RK4(0,3,1,i);
//cout<<endl;
}
return 0;
}
//4级R-K法(Kutta法)
void RK4(double ta,double tb,double y0,int m)
{
double h=1/pow(2,m),t0=ta,k1,k2,k3,k4;
int i, M=pow(2,m)*(tb-ta);
for(i=1;i<=M;i++)
{
k1=f(t0,y0);
k2=f(t0+h/2,y0+h*k1/2);
k3=f(t0+h/2,y0+h*k2/2);
k4=f(t0+h,y0+h*k3);
y0=y0+h/6*(k1+2*k2+2*k3+k4);
t0=t0+h;
}
printf("%.3f\t%d\t%.8f\t%.8e\t%.3f\n",h,M,y0,fabs(y_t(t0)-y0),0.256*h);
}
double f(double t,double y)
{
return (t-y)/2 ;
}
double y_t(double t)
{
return 3*exp(-t/2)-2+t;
} |
eacadaff2c8ffd82ffd315e40f0b2e5cf5f6891b | 19a5b07061685f7c9617c8bf1b5aaa8aa1a8e59c | /data_structure/week3/infix2postfix.cpp | 5d9136fdc498986e070d3dc7d5499a3cd9c3c709 | [] | no_license | cxgoal-97/hw | 49589d798aa1de1367efc590a06e088dbed834e6 | 4c064ddfc5819de760df3c762601a879eb141228 | refs/heads/master | 2021-09-20T09:44:59.390523 | 2018-08-08T02:56:51 | 2018-08-08T02:56:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,947 | cpp | infix2postfix.cpp | //
#include <iostream>
#include <cstdio>
#include <string>
#include <stack>
using namespace std;
// 将中缀表达式转换为后缀表达式
string infix2postfix(string i_string);
int main(){
int k = 0;
cin>>k;
getchar();
for(int j=0; j<k; j++){
string i_string;
getline(cin, i_string);
string t_string;
getline(cin,t_string);
string result = infix2postfix(i_string);
string result_t = infix2postfix(t_string);
cout<<result<<endl;
cout<<result_t<<endl;
}
return 1;
}
string infix2postfix(string i_string){
string result;
stack<char> stack_a;
for(unsigned int i=0; i<i_string.length(); i++){
char t = i_string[i];
// 排除空格和tab
if (t=='\t'||t==' '||t=='\n')
continue;
// 如果为 左括号
else if(t=='(')
stack_a.push(t);
// 如果为 高级别操作数
else if(t=='/'||t=='*'){
while(!stack_a.empty()&&(stack_a.top()=='/'||stack_a.top()=='*')){
result = result+stack_a.top();
stack_a.pop();
}
stack_a.push(t);
}
// 如果为 低级别操作数,
// 若栈中有高级别操作数,则显示并弹出
else if(t=='+'||t=='-'){
while(!stack_a.empty()&&
(stack_a.top()!='(')){
result = result+stack_a.top();
stack_a.pop();
}
stack_a.push(t);
}
// 如果为 右括号
else if(t==')'){
while(stack_a.top()!='('){
//cout<<stack_a.top();
result = result+stack_a.top();
stack_a.pop();
}
stack_a.pop();
}else
result = result+t;
}
while(!stack_a.empty()){
result = result+stack_a.top();
stack_a.pop();
}
return result;
}
|
c9d4779114504b678673d9ee1462b6b1722480ae | 6035fb168576b8fdbef1a3dbc871e1a06e191278 | /final_test/4/t8564_532_F_10757411.cpp | 65e7c64e73c887be105dc7cd6b2ab21f1f4777ef | [] | no_license | pavellevap/code_antiplagiat | 69ef3ecea5e8e88dfd3b800c0ce351fa32ee9762 | d75603e4e25519d9bb9b9720923136e324328be4 | refs/heads/master | 2021-01-10T05:30:44.560926 | 2015-04-30T14:25:34 | 2015-04-30T14:25:34 | 45,319,257 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,694 | cpp | t8564_532_F_10757411.cpp | #include <iostream>
#include <iomanip>
#include <cstdio>
#include <stdio.h>
#include <cstdlib>
#include <bitset>
#include <memory>
#include <algorithm>
#include <set>
#include <map>
#include <vector>
#include <list>
#include <string>
#include <cstring>
#include <fstream>
#include <functional>
#include <stack>
#include <complex>
#include <wchar.h>
#include <wctype.h>
#include <cmath>
#include <queue>
#include <ctime>
#include <numeric>
#include <bitset>
#include <cassert>
using namespace std;
template<typename T> T mabs(const T &a){ return a<0?-a:a;}
#define rep(x,y,z) for(int x=(y),e##x=(z);x<e##x;x++)
#define SQR(x) ((x)*(x))
#define all(c) (c).begin(), (c).end()
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef unsigned int ui;
typedef short int si;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef pair<double, int> pdi;
typedef pair<double, double> pdd;
const int SZ = 200200;
int isGood[SZ];
int pref[2*SZ + 10];
char buff[2*SZ + 10];
void kmp(char *pat, char *str, int add)
{
int n = strlen(pat);
int m = strlen(str);
strcpy(buff, pat);
buff[n] = '#';
buff[n+1] = 0;
strcat(buff, str);
pref[0] = 0;
int len = n + m + 1;
rep(i,1,len)
{
int curr = pref[i-1];
while (curr > 0 && buff[curr] != buff[i])
curr = pref[curr-1];
if (buff[curr] == buff[i])
++curr;
pref[i] = curr;
if (curr == n && (i - n - 1) - n + 1 >=0)
isGood[(i - n - 1) - n + 1] += add;
}
// cout<<buff<<endl;
// rep(i,0,len)
// cout<<pref[i];
// cout<<endl<<endl;
}
char A[SZ], B[SZ];
char ChA[SZ], ChB[SZ];
void run()
{
memset(isGood, 0, sizeof(isGood));
int n,m;
cin>>n>>m;
scanf("%s%s",A,B);
rep(a,'a','z'+1)
rep(b, a,'z'+1)
{
rep(i,0,n)
ChA[i] = A[i] == a ? '1' : A[i] == b ? '2' : '0';
int cnt = 0;
rep(i,0,m)
{
ChB[i] = B[i] == b ? '1' : B[i] == a ? '2' : '0';
cnt += ChB[i] != '0';
}
kmp(ChB, ChA, cnt);
}
vector<int> res;
rep(i,0,n)
if (isGood[i] == m)
res.push_back(i);
cout<<res.size()<<endl;
rep(i,0,res.size())
cout<<res[i] + 1<<' ';
}
//#define prob "graph"
int main()
{
#ifdef _MONYURA_
freopen("../test.in","r",stdin);
freopen("../test.out","w",stdout);
time_t st=clock();
#else
#ifdef prob
freopen(prob".in","r",stdin);
freopen(prob".out","w",stdout);
#endif
#endif
run();
#ifdef _MONYURA_
printf( "\n=============\n");
printf("Time: %.2lf sec\n",(clock()-st)/double(CLOCKS_PER_SEC));
#endif
return 0;
} |
ec2774ca0e52f60ad2aaf2152fba231d46bf329d | 96e7347db30d3ae35f2df119a18472cf5b251fa2 | /Classes/Native/System_Xml_System_Xml_XmlParserContext2532808825.h | 22fb08d3234dfceec8c023ef8e833cc2c6610b79 | [] | no_license | Henry0285/abcwriting | 04b111887489d9255fd2697a4ea8d9971dc17d89 | ed2e4da72fbbad85d9e0e9d912e73ddd33bc91ec | refs/heads/master | 2021-01-20T14:16:48.025648 | 2017-05-08T06:00:06 | 2017-05-08T06:00:06 | 90,583,162 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,870 | h | System_Xml_System_Xml_XmlParserContext2532808825.h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
// System.String
struct String_t;
// System.Text.Encoding
struct Encoding_t2125916575;
// System.Xml.XmlNamespaceManager
struct XmlNamespaceManager_t3654972885;
// System.Xml.XmlNameTable
struct XmlNameTable_t1855692664;
// System.Collections.ArrayList
struct ArrayList_t1468494371;
// Mono.Xml.DTDObjectModel
struct DTDObjectModel_t281012916;
#include "mscorlib_System_Object707969140.h"
#include "System_Xml_System_Xml_XmlSpace2881005573.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Xml.XmlParserContext
struct XmlParserContext_t2532808825 : public Il2CppObject
{
public:
// System.String System.Xml.XmlParserContext::baseURI
String_t* ___baseURI_0;
// System.String System.Xml.XmlParserContext::docTypeName
String_t* ___docTypeName_1;
// System.Text.Encoding System.Xml.XmlParserContext::encoding
Encoding_t2125916575 * ___encoding_2;
// System.String System.Xml.XmlParserContext::internalSubset
String_t* ___internalSubset_3;
// System.Xml.XmlNamespaceManager System.Xml.XmlParserContext::namespaceManager
XmlNamespaceManager_t3654972885 * ___namespaceManager_4;
// System.Xml.XmlNameTable System.Xml.XmlParserContext::nameTable
XmlNameTable_t1855692664 * ___nameTable_5;
// System.String System.Xml.XmlParserContext::publicID
String_t* ___publicID_6;
// System.String System.Xml.XmlParserContext::systemID
String_t* ___systemID_7;
// System.String System.Xml.XmlParserContext::xmlLang
String_t* ___xmlLang_8;
// System.Xml.XmlSpace System.Xml.XmlParserContext::xmlSpace
int32_t ___xmlSpace_9;
// System.Collections.ArrayList System.Xml.XmlParserContext::contextItems
ArrayList_t1468494371 * ___contextItems_10;
// System.Int32 System.Xml.XmlParserContext::contextItemCount
int32_t ___contextItemCount_11;
// Mono.Xml.DTDObjectModel System.Xml.XmlParserContext::dtd
DTDObjectModel_t281012916 * ___dtd_12;
public:
inline static int32_t get_offset_of_baseURI_0() { return static_cast<int32_t>(offsetof(XmlParserContext_t2532808825, ___baseURI_0)); }
inline String_t* get_baseURI_0() const { return ___baseURI_0; }
inline String_t** get_address_of_baseURI_0() { return &___baseURI_0; }
inline void set_baseURI_0(String_t* value)
{
___baseURI_0 = value;
Il2CppCodeGenWriteBarrier(&___baseURI_0, value);
}
inline static int32_t get_offset_of_docTypeName_1() { return static_cast<int32_t>(offsetof(XmlParserContext_t2532808825, ___docTypeName_1)); }
inline String_t* get_docTypeName_1() const { return ___docTypeName_1; }
inline String_t** get_address_of_docTypeName_1() { return &___docTypeName_1; }
inline void set_docTypeName_1(String_t* value)
{
___docTypeName_1 = value;
Il2CppCodeGenWriteBarrier(&___docTypeName_1, value);
}
inline static int32_t get_offset_of_encoding_2() { return static_cast<int32_t>(offsetof(XmlParserContext_t2532808825, ___encoding_2)); }
inline Encoding_t2125916575 * get_encoding_2() const { return ___encoding_2; }
inline Encoding_t2125916575 ** get_address_of_encoding_2() { return &___encoding_2; }
inline void set_encoding_2(Encoding_t2125916575 * value)
{
___encoding_2 = value;
Il2CppCodeGenWriteBarrier(&___encoding_2, value);
}
inline static int32_t get_offset_of_internalSubset_3() { return static_cast<int32_t>(offsetof(XmlParserContext_t2532808825, ___internalSubset_3)); }
inline String_t* get_internalSubset_3() const { return ___internalSubset_3; }
inline String_t** get_address_of_internalSubset_3() { return &___internalSubset_3; }
inline void set_internalSubset_3(String_t* value)
{
___internalSubset_3 = value;
Il2CppCodeGenWriteBarrier(&___internalSubset_3, value);
}
inline static int32_t get_offset_of_namespaceManager_4() { return static_cast<int32_t>(offsetof(XmlParserContext_t2532808825, ___namespaceManager_4)); }
inline XmlNamespaceManager_t3654972885 * get_namespaceManager_4() const { return ___namespaceManager_4; }
inline XmlNamespaceManager_t3654972885 ** get_address_of_namespaceManager_4() { return &___namespaceManager_4; }
inline void set_namespaceManager_4(XmlNamespaceManager_t3654972885 * value)
{
___namespaceManager_4 = value;
Il2CppCodeGenWriteBarrier(&___namespaceManager_4, value);
}
inline static int32_t get_offset_of_nameTable_5() { return static_cast<int32_t>(offsetof(XmlParserContext_t2532808825, ___nameTable_5)); }
inline XmlNameTable_t1855692664 * get_nameTable_5() const { return ___nameTable_5; }
inline XmlNameTable_t1855692664 ** get_address_of_nameTable_5() { return &___nameTable_5; }
inline void set_nameTable_5(XmlNameTable_t1855692664 * value)
{
___nameTable_5 = value;
Il2CppCodeGenWriteBarrier(&___nameTable_5, value);
}
inline static int32_t get_offset_of_publicID_6() { return static_cast<int32_t>(offsetof(XmlParserContext_t2532808825, ___publicID_6)); }
inline String_t* get_publicID_6() const { return ___publicID_6; }
inline String_t** get_address_of_publicID_6() { return &___publicID_6; }
inline void set_publicID_6(String_t* value)
{
___publicID_6 = value;
Il2CppCodeGenWriteBarrier(&___publicID_6, value);
}
inline static int32_t get_offset_of_systemID_7() { return static_cast<int32_t>(offsetof(XmlParserContext_t2532808825, ___systemID_7)); }
inline String_t* get_systemID_7() const { return ___systemID_7; }
inline String_t** get_address_of_systemID_7() { return &___systemID_7; }
inline void set_systemID_7(String_t* value)
{
___systemID_7 = value;
Il2CppCodeGenWriteBarrier(&___systemID_7, value);
}
inline static int32_t get_offset_of_xmlLang_8() { return static_cast<int32_t>(offsetof(XmlParserContext_t2532808825, ___xmlLang_8)); }
inline String_t* get_xmlLang_8() const { return ___xmlLang_8; }
inline String_t** get_address_of_xmlLang_8() { return &___xmlLang_8; }
inline void set_xmlLang_8(String_t* value)
{
___xmlLang_8 = value;
Il2CppCodeGenWriteBarrier(&___xmlLang_8, value);
}
inline static int32_t get_offset_of_xmlSpace_9() { return static_cast<int32_t>(offsetof(XmlParserContext_t2532808825, ___xmlSpace_9)); }
inline int32_t get_xmlSpace_9() const { return ___xmlSpace_9; }
inline int32_t* get_address_of_xmlSpace_9() { return &___xmlSpace_9; }
inline void set_xmlSpace_9(int32_t value)
{
___xmlSpace_9 = value;
}
inline static int32_t get_offset_of_contextItems_10() { return static_cast<int32_t>(offsetof(XmlParserContext_t2532808825, ___contextItems_10)); }
inline ArrayList_t1468494371 * get_contextItems_10() const { return ___contextItems_10; }
inline ArrayList_t1468494371 ** get_address_of_contextItems_10() { return &___contextItems_10; }
inline void set_contextItems_10(ArrayList_t1468494371 * value)
{
___contextItems_10 = value;
Il2CppCodeGenWriteBarrier(&___contextItems_10, value);
}
inline static int32_t get_offset_of_contextItemCount_11() { return static_cast<int32_t>(offsetof(XmlParserContext_t2532808825, ___contextItemCount_11)); }
inline int32_t get_contextItemCount_11() const { return ___contextItemCount_11; }
inline int32_t* get_address_of_contextItemCount_11() { return &___contextItemCount_11; }
inline void set_contextItemCount_11(int32_t value)
{
___contextItemCount_11 = value;
}
inline static int32_t get_offset_of_dtd_12() { return static_cast<int32_t>(offsetof(XmlParserContext_t2532808825, ___dtd_12)); }
inline DTDObjectModel_t281012916 * get_dtd_12() const { return ___dtd_12; }
inline DTDObjectModel_t281012916 ** get_address_of_dtd_12() { return &___dtd_12; }
inline void set_dtd_12(DTDObjectModel_t281012916 * value)
{
___dtd_12 = value;
Il2CppCodeGenWriteBarrier(&___dtd_12, value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
|
5620bfdec23416b0d28a3c97f7493c5b3b207864 | 6348b3b6ceacd7dac91f44036b3df8ad5192a136 | /include/sol/policies.hpp | d373bb897e2364c085663cc711567fa6be60ee5e | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | ThePhD/sol2 | b0167676fecf9c65f371f6319833393cdbda0bbe | 9c882a28fdb6f4ad79a53a4191b43ce48a661175 | refs/heads/develop | 2023-08-22T21:48:22.328223 | 2023-08-06T21:47:47 | 2023-08-06T21:47:47 | 49,177,547 | 3,912 | 572 | MIT | 2023-07-18T17:46:18 | 2016-01-07T03:09:13 | C++ | UTF-8 | C++ | false | false | 3,358 | hpp | policies.hpp | // sol2
// The MIT License (MIT)
// Copyright (c) 2013-2022 Rapptz, ThePhD and contributors
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#ifndef SOL_FILTERS_HPP
#define SOL_FILTERS_HPP
#include <sol/traits.hpp>
#include <array>
namespace sol {
namespace detail {
struct policy_base_tag { };
} // namespace detail
template <int Target, int... In>
struct static_stack_dependencies : detail::policy_base_tag { };
typedef static_stack_dependencies<-1, 1> self_dependency;
template <int... In>
struct returns_self_with : detail::policy_base_tag { };
typedef returns_self_with<> returns_self;
struct stack_dependencies : detail::policy_base_tag {
int target;
std::array<int, 64> stack_indices;
std::size_t len;
template <typename... Args>
stack_dependencies(int stack_target, Args&&... args) : target(stack_target), stack_indices(), len(sizeof...(Args)) {
std::size_t i = 0;
(void)detail::swallow { int(), (stack_indices[i++] = static_cast<int>(std::forward<Args>(args)), int())... };
}
int& operator[](std::size_t i) {
return stack_indices[i];
}
const int& operator[](std::size_t i) const {
return stack_indices[i];
}
std::size_t size() const {
return len;
}
};
template <typename F, typename... Policies>
struct policy_wrapper {
typedef std::index_sequence_for<Policies...> indices;
F value;
std::tuple<Policies...> policies;
template <typename Fx, typename... Args, meta::enable<meta::neg<std::is_same<meta::unqualified_t<Fx>, policy_wrapper>>> = meta::enabler>
policy_wrapper(Fx&& fx, Args&&... args) : value(std::forward<Fx>(fx)), policies(std::forward<Args>(args)...) {
}
policy_wrapper(const policy_wrapper&) = default;
policy_wrapper& operator=(const policy_wrapper&) = default;
policy_wrapper(policy_wrapper&&) = default;
policy_wrapper& operator=(policy_wrapper&&) = default;
};
template <typename F, typename... Args>
auto policies(F&& f, Args&&... args) {
return policy_wrapper<std::decay_t<F>, std::decay_t<Args>...>(std::forward<F>(f), std::forward<Args>(args)...);
}
namespace detail {
template <typename T>
using is_policy = meta::is_specialization_of<T, policy_wrapper>;
template <typename T>
inline constexpr bool is_policy_v = is_policy<T>::value;
} // namespace detail
} // namespace sol
#endif // SOL_FILTERS_HPP
|
fa59413a63d148b58640a87f4ac14157cbee56c7 | 88d53997584014f7a91f2231b7eb19f34029e56a | /Kattis/ImageDecoding/imagedecoding.cpp | b8a69559a07b8bb4177c659e3203b21edfd70353 | [] | no_license | edkwcheng/dojo | 80631b420e077c3d2cb4c1274f81444e299d728d | fb52c19a524b3c05e6a1b2d2362d887604a346cd | refs/heads/master | 2021-01-22T17:39:00.544022 | 2018-11-27T18:47:12 | 2018-11-27T18:47:12 | 100,728,147 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,250 | cpp | imagedecoding.cpp | #include <iostream>
#include <string>
int main()
{
int first = 1;
while (1)
{
int numLines = 0;
std::cin >> numLines;
std::cin.ignore(1, '\n');
if (numLines == 0)
{
break;
}
if (!first)
{
std::cout << "\n";
}
int pixels[numLines];
for (int i=0; i<numLines; i++)
{
pixels[i] = 0;
std::string input;
getline(std::cin, input);
char outputChar = input.front();
unsigned int pos = 0, end = 0;
do
{
pos = input.find_first_of(" ", end);
end = input.find_first_not_of(" ", pos);
end = (end < input.size()) ? input.find_first_of(" ", end) : input.size();
int num = std::stoi(input.substr(pos, end));
pixels[i] += num;
while (num > 0)
{
std::cout << outputChar;
num--;
}
outputChar = (outputChar == '#') ? '.' : '#';
} while (end < input.size());
std::cout << "\n";
}
int invalid = 0;
for (int i=0; i<numLines; i++)
{
if (pixels[0] != pixels[i])
{
invalid = 1;
}
}
if (invalid)
{
std:: cout << "Error decoding image" << "\n";
}
first = 0;
}
}
|
88b922fa12f4903de52df0da29d148d37b53d009 | 6581059fa73d55ec06a80d2ee9c618b0c62ae02a | /Practise Ladders/test.cpp | 20ac3f5191d11c7d14706525ab8dbfd7ac95b293 | [] | no_license | allenjamesvinoy14/Competitive-Programming | 1268325b4bc48bc5a0b9a25c9632cf5f0b691229 | 46cab08f41363fda316987df0f29433242c223da | refs/heads/master | 2022-11-22T10:29:20.133850 | 2020-07-25T19:41:21 | 2020-07-25T19:41:21 | 266,506,688 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,092 | cpp | test.cpp | // Naive C++ implementation to find LCA in a tree
#include<bits/stdc++.h>
using namespace std;
#define MAXN 1001
int depth[MAXN]; // stores depth for each node
int parent[MAXN]; // stores first parent for each node
vector <int> adj[MAXN];
void addEdge(int u,int v)
{
adj[u].push_back(v);
adj[v].push_back(u);
}
void dfs(int cur, int prev)
{
parent[cur] = prev;
depth[cur] = depth[prev] + 1;
for (int i=0; i<adj[cur].size(); i++)
if (adj[cur][i] != prev)
dfs(adj[cur][i],cur);
}
void preprocess()
{
depth[0] = -1;
dfs(1,0);
}
int LCANaive(int u,int v)
{
if (u == v) return u;
if (depth[u] > depth[v])
swap(u, v);
v = parent[v];
return LCANaive(u,v);
}
int main(int argc, char const *argv[])
{
addEdge(1,2);
addEdge(1,3);
addEdge(1,4);
addEdge(2,5);
addEdge(2,6);
addEdge(3,7);
addEdge(4,8);
addEdge(4,9);
addEdge(9,10);
addEdge(9,11);
addEdge(7,12);
addEdge(7,13);
preprocess();
cout << "LCA(11,8) : " << LCANaive(11,8) << endl;
cout << "LCA(3,13) : " << LCANaive(3,13) << endl;
return 0;
}
|
17b402f8cb3253cab93ee933afbb84f020fbc85e | fd92df8b3b497c2f5dd722e4f9572ab4a4dc23a0 | /src/Background.h | 569acbb9f1e5854982f2758c74d8fde6e50cc5b2 | [] | no_license | alaniv/tetrisClone | 79ccf06f6781fba3566648b4dc25dac03baf7854 | d0f91a4d27ce7f91a884657e923e8179d1b45635 | refs/heads/master | 2021-07-15T20:46:18.772899 | 2021-07-01T13:46:31 | 2021-07-01T13:46:31 | 228,294,934 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 107 | h | Background.h | #ifndef BACKGROUND_H
#define BACKGROUND_H
class Background {
public:
void render();
};
#endif |
2486fe555c195700cbf2c5b66bc238b73aa46e9a | 2ea7eee88cc16ffedb88083094b76031c8a81413 | /ABC/ABC089/ABC089B.cpp | f2ee2a14cff61d212095f3e7b9cee3903777afaa | [] | no_license | shotauedaGit/cp_practice | c6ea658f47ac84e3e4cdecf691d7cad10789133d | e2d006a6d7c392692dff9ab182e214b3f855b554 | refs/heads/master | 2023-01-24T10:36:08.742179 | 2023-01-07T05:34:26 | 2023-01-07T05:34:26 | 248,667,877 | 0 | 0 | null | 2020-05-07T07:38:49 | 2020-03-20T04:28:05 | C++ | UTF-8 | C++ | false | false | 440 | cpp | ABC089B.cpp | #include <bits/stdc++.h>
using namespace std;
int main(){
int ans=0;
int n;
cin >> n;
char ch;
for (int i = 0; i < n; i++){
cin >> ch;
if(ch=='Y'){
std::cout << "Four" << '\n';
return 0;
}
}
//cout <<fixed<<setprecision(16)<< << endl;
cout << "Three" << endl;
//if(flag==1)cout << "Yes" <<endl;
//else cout << "No" <<endl;
return 0;
}
|
a0ec60837a387c88025314829feba5730c95e4ca | 0cc42358634d30a7b39767f65eddae591ccea1cc | /Ultrasonic_sensor_LCD_arduino.ino | f309eceec36771259737f101b850b028488a525e | [] | no_license | SPANDANA2904/smartbridge-es | a4a59b84562c00caafdbde191bcd6cd0913bbf4f | 652d4947ca51c351a3a1e588b4d300d475bbe914 | refs/heads/master | 2020-05-30T21:48:50.529913 | 2019-06-28T09:51:07 | 2019-06-28T09:51:07 | 189,981,635 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 649 | ino | Ultrasonic_sensor_LCD_arduino.ino | #include<LiquidCrystal.h>
const int trigPin=2;
const int echoPin=4;
long duration;
int distance;
const int rs=22,en=23,d4=5,d5=18,d6=19,d7=21;
LiquidCrystal lcd(rs,en,d4,d5,d6,d7);
void setup()
{
lcd.begin(16,2);
pinMode(trigPin,OUTPUT);
pinMode(echoPin,INPUT);
Serial.begin(9600);
}
void loop()
{
digitalWrite(trigPin,LOW);
delayMicroseconds(2);
digitalWrite(trigPin,HIGH);
delayMicroseconds(10);
digitalWrite(trigPin,LOW);
duration=pulseIn(echoPin,HIGH);
distance=duration*0.034/2;
Serial.print("distance: ");
Serial.println(distance);
lcd.print("distance: ");
lcd.println(distance);
}
|
66efbf3b35b07d7164d133c3103cbec659675bad | edc5b1e0bbfe683f23dd14c811f2da456f5603a1 | /cpp/subsys/Intake.cpp | a298652f3b1dd240bbf44cc246f199be6aae66c1 | [
"MIT"
] | permissive | JacksterGamingYT/2019DestinationDeepSpace | fca67d7dbe022ca2289af8bab3091f368e21073e | e863c5b9a7c31e6edd41eb09bb2b33cfde7669d5 | refs/heads/master | 2020-04-22T19:18:25.859421 | 2019-02-12T13:49:49 | 2019-02-12T13:49:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,681 | cpp | Intake.cpp | /*----------------------------------------------------------------------------*/
/* Copyright (c) 2018 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#include "subsys/Intake.h"
#include "hal/PDP.h"
Intake::Intake(IDragonMotorControllerVector motorControllers) :
m_intakeMotor(nullptr)
{
for (int i = 0; i < motorControllers.size(); i++)
{
switch (motorControllers[i]->GetType())
{
case IDragonMotorController::TALON_TYPE::INTAKE:
m_intakeMotor = static_cast<DragonTalon*>(motorControllers[i]);
break;
default:
break;
}
}
m_intakeMotor->SetControlMode(IDragonMotorController::DRAGON_CONTROL_MODE::PERCENT_OUTPUT);
m_intakeMotor->Set(0);
}
void Intake::IntakeManual(double speed)
{
m_intakeMotor->Set(speed);
}
void Intake::IntakePreset(bool cargo, bool outtake)
{
if(cargo)
m_intakeMotor->Set(CARGO_INTAKE_SPEED);
else if(cargo && outtake)
m_intakeMotor->Set(CARGO_OUTTAKE_SPEED);
else if(outtake)
m_intakeMotor->Set(HATCH_OUTTAKE_SPEED);
else
m_intakeMotor->Set(HATCH_INTAKE_SPEED);
}
bool Intake::ObjectPresent()
{
return true; //Yay we have one we did it go score!!!!
}
IMechanism::MECHANISM_TYPE Intake::GetType() const
{
return IMechanism::MECHANISM_TYPE::INTAKE;
} |
55b4c5d2c275cf55df9747cfefdeee08bde218ef | 124e8db708315c87eae0e4ee559612138ac79ce3 | /Server/Commands/CommandHit.h | a9814ca7383c17c59fe82616087ecf45b725ff6b | [] | no_license | protective/anno3112 | 7e2beec4a0a9892fb084d9237baf770cab655c81 | 8de8a12880501876d89893d9ed92d118c14ffe38 | refs/heads/master | 2021-01-22T23:54:32.286050 | 2014-09-27T20:27:59 | 2014-09-27T20:27:59 | 15,630,219 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 574 | h | CommandHit.h | /*
* File: CommandHit.h
* Author: karsten
*
* Created on 1. juni 2014, 22:27
*/
#ifndef COMMANDHIT_H
#define COMMANDHIT_H
#include "../SFunctions.h"
#include "Command.h"
class CommandHit : public Command{
public:
CommandHit(uint32_t target, uint32_t shot, uint32_t dmg, DmgTypes::Enum dmgType, Shields::Enum impact, int32_t x, int32_t y);
virtual uint32_t execute();
virtual ~CommandHit();
protected:
uint32_t _target;
uint32_t _shot;
uint32_t _dmg;
DmgTypes::Enum _dmgType;
Shields::Enum _impact;
int32_t _x;
int32_t _y;
};
#endif /* COMMANDHIT_H */
|
c6e251f3dc15e0d6c4132acf1c8fd52f98dd58b4 | 1c6466dbf61f36fb4168260de8418be02379dddb | /New Version/A1142.cpp | 1db9d53945018b09bbb0fc7862c83fd75e73d6a0 | [] | no_license | jiujiangluck/PAT-Advanced-Level-Practise | a3ccb914251f4fcd9097f756d6dd19f756efd136 | bec80797914df8fa08c1977863753b27fcafabff | refs/heads/master | 2020-03-26T21:15:51.682996 | 2019-07-14T09:30:31 | 2019-07-14T09:30:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 962 | cpp | A1142.cpp | #include<iostream>
#include<vector>
using namespace std;
int g[210][210];
vector<int> v;
int num, num1, k, visited[210] = { 0 };
bool isC(int k) {
for (int i = 0; i < v.size(); i++) {
if (g[k][v[i]] != 1) {
return false;
}
}
return true;
}
bool isMax() {
for (int i = 1; i <= num; i++) {
if (isC(i) == true && visited[i] == 0) return false;
}
return true;
}
int main() {
std::ios::sync_with_stdio(false);
cin >> num >> num1;
for (int i = 0; i < num1; i++) {
int t, r;
cin >> t >> r;
g[t][r] = 1;
g[r][t] = 1;
}
cin >> k;
for (int i = 0; i < k; i++) {
int n, temp;
cin >> n;
v.clear();
fill(visited, visited + 210, 0);
for (int j = 0; j < n; j++) {
cin >> temp;
visited[temp] = 1;;
if (isC(temp)) {
v.push_back(temp);
}
}
if (v.size() != n) {
cout << "Not a Clique\n";
}
else {
if (isMax()) cout << "Yes\n";
else cout << "Not Maximal\n";
}
}
system("pause");
return 0;
} |
3de582faada820a810915dc168e77d588651507e | 08b8cf38e1936e8cec27f84af0d3727321cec9c4 | /data/crawl/make/new_hunk_1224.cpp | a357a8fdbbebb819bc3f13f106d4514b2a810fd1 | [] | no_license | ccdxc/logSurvey | eaf28e9c2d6307140b17986d5c05106d1fd8e943 | 6b80226e1667c1e0760ab39160893ee19b0e9fb1 | refs/heads/master | 2022-01-07T21:31:55.446839 | 2018-04-21T14:12:43 | 2018-04-21T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 600 | cpp | new_hunk_1224.cpp | live and call reap_children again. */
block_sigs ();
#ifdef MAKE_JOBSERVER
/* If this job has a token out, return it. */
if (c->job_token)
{
assert(job_slots_used > 0);
write (job_fds[1], &c->job_token, 1);
if (debug_flag)
printf ("Released token `%c' for child 0x%08lx.\n",
c->job_token, (unsigned long int) c);
c->job_token = 0;
}
#endif
/* There is now another slot open. */
if (job_slots_used > 0)
--job_slots_used;
/* Remove the child from the chain and free it. */
if (lastc == 0)
children = c->next;
|
23d6149888de02a9f80e736597abf9aff13a33a1 | 0df0df4843c0ce881a9fbe3af1bd02232be9ff37 | /EcdisRadar_2.0/EcdisRadar/filepath.h | 99ca6dc16fb14b13fe5a6d89f2ccd0450c6d3bda | [] | no_license | yikaikai/ActivityManagerServiceSimulation | 159ebbee96128c1a0d2736fc8006d62f58cfbe78 | 407f9a935ae5d8b200b58be420be8a39a4d6af73 | refs/heads/master | 2021-06-12T19:52:18.078297 | 2017-03-30T00:53:17 | 2017-03-30T00:53:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 798 | h | filepath.h | #ifndef FILEPATH_H_
#define FILEPATH_H_
#include <string>
class FilePath
{
public:
FilePath() { }
FilePath(const std::string &fpath);
FilePath(const char *fpath);
~FilePath();
std::string string() const { return filepath; }
std::string extension();
bool exists();
void create_directory();
void win32_to_unix();
FilePath branch_path();
FilePath operator/(FilePath &rhs);
FilePath &operator/=(FilePath &rhs);
FilePath operator/(std::string &rhs);
FilePath &operator/=(std::string &rhs);
FilePath operator/(const char *rhs);
FilePath &operator/=(const char *rhs);
private:
void RemoveWhitespace(std::string &str);
std::string filepath;
};
#endif
|
1480051380cfacecbd40fb25202c44b3acde6caa | 12cd044c57f4fb42362b28820d526e79684365f2 | /deps/parallel_quickstep/src/parallel_batch.cpp | 6485dfaa8f34837c9de1367d323721442168e428 | [
"Apache-2.0"
] | permissive | ci-group/gazebo | 29abd12997e7b8ce142c01410bdce4b46b97815f | 1e8bdf272217e74eeb49349da22a38d3275e5d72 | refs/heads/gazebo6-revolve | 2021-07-09T16:05:29.272321 | 2019-11-11T17:56:01 | 2019-11-11T17:56:01 | 82,048,176 | 3 | 2 | NOASSERTION | 2020-05-18T13:49:18 | 2017-02-15T10:22:37 | C++ | UTF-8 | C++ | false | false | 11,261 | cpp | parallel_batch.cpp | #include <parallel_batch.h>
#include <parallel_utils.h>
#include <map>
#include <boost/unordered_map.hpp>
namespace parallel_ode
{
using ::parallel_utils::permuteVector;
using ::parallel_utils::fillSequentialVector;
typedef boost::unordered_map<int, int> BatchMap;
typedef std::multimap<int, int, std::greater<int> > BatchMultimap;
typedef BatchMultimap::iterator BatchMultimapIterator;
int BatchStrategy::baseBatch( const int* pairList,
const BatchVector& constraintIndices,
const BatchVector& batchSizes,
BatchVector& batchIndices,
BatchVector& bodyRepetitionCount0,
BatchVector& bodyRepetitionCount1,
BatchVector& maxBodyRepetitionCount )
{
batchIndicesFromBatchSizes( batchSizes, batchIndices, isAligning( ), getAlignment( ) );
return batchRepetitionCount( pairList, constraintIndices, batchSizes, bodyRepetitionCount0, bodyRepetitionCount1, maxBodyRepetitionCount );
}
void BatchStrategy::batchIndicesFromBatchSizes( const BatchVector& batchSizes, BatchVector& batchIndices, bool bAlign, int alignment )
{
batchIndices.resize( batchSizes.size() );
for( size_t batchID = 0, batchOffset = 0; batchID < batchSizes.size(); batchID++ )
{
if( bAlign ) alignOffset( batchOffset, alignment );
batchIndices[ batchID ] = batchOffset;
batchOffset += batchSizes[ batchID ];
}
}
int BatchStrategy::batchRepetitionCount( const int *pairList,
const BatchVector& constraintIndices,
const BatchVector& batchSizes,
BatchVector& bodyRepetitionCount0,
BatchVector& bodyRepetitionCount1,
BatchVector& maxBodyRepetitionCountInBatch )
{
maxBodyRepetitionCountInBatch.resize( getMaxBatches() );
int maxRepetitionCount = 0;
BatchVector bodyRepetitionMap( bodyRepetitionCount0.size() );
for( size_t batchID = 0, constraintID = 0; batchID < batchSizes.size(); batchID++ )
{
bodyRepetitionMap.assign( bodyRepetitionMap.size(), 0 );
int maxRepetitionCountInBatch = 0;
for( int iter = 0; iter < batchSizes[ batchID ]; ++iter,++constraintID )
{
int bodyID0 = pairList[ constraintIndices[ constraintID ]*2 ] ;
int bodyID1 = pairList[ constraintIndices[ constraintID ]*2+1 ] ;
if( bodyID0 >= 0 ) {
bodyRepetitionCount0[ constraintID ] = bodyRepetitionMap[ bodyID0 ]++;
maxRepetitionCountInBatch = std::max( maxRepetitionCountInBatch, bodyRepetitionMap[ bodyID0 ] );
}
if( bodyID1 >= 0 ) {
bodyRepetitionCount1[ constraintID ] = bodyRepetitionMap[ bodyID1 ]++;
maxRepetitionCountInBatch = std::max( maxRepetitionCountInBatch, bodyRepetitionMap[ bodyID1 ] );
}
}
maxBodyRepetitionCountInBatch[ batchID ] = maxRepetitionCountInBatch;
maxRepetitionCount = std::max( maxRepetitionCount, maxRepetitionCountInBatch );
}
return maxRepetitionCount;
}
int BatchStrategy::batch( const int* pairList, const int numConstraints, const int numBodies,
BatchVector& constraintIndices,
BatchVector& bodyRepetitionCount0,
BatchVector& bodyRepetitionCount1,
BatchVector& maxBodyRepetitionCountInBatch,
BatchVector& batchIndices,
BatchVector& batchSizes )
{
batchSizes.resize( getMaxBatches() );
batchSizes.assign( getMaxBatches(), 0 );
// Place all constraints in the first batch
fillSequentialVector( constraintIndices );
permuteVector( constraintIndices );
const int batchSize = numConstraints / getMaxBatches( );
batchSizes[ 0 ] = batchSize + ( numConstraints % batchSize );
for( int batchID = 1; batchID < getMaxBatches(); ++batchID ) {
batchSizes[ batchID ] = batchSize;
}
return baseBatch( pairList, constraintIndices, batchSizes, batchIndices, bodyRepetitionCount0, bodyRepetitionCount1, maxBodyRepetitionCountInBatch );
}
int GreedyBatchStrategy::batch( const int* pairList, const int numConstraints, const int numBodies,
BatchVector& constraintIndices,
BatchVector& bodyRepetitionCount0,
BatchVector& bodyRepetitionCount1,
BatchVector& maxBodyRepetitionCountInBatch,
BatchVector& batchIndices,
BatchVector& batchSizes )
{
int constraintsUsed = 0;
std::vector<bool> constraintAssigned( numConstraints, false );
std::vector<bool> bodyUsed( numBodies );
batchSizes.resize( getMaxBatches() );
batchSizes.assign( getMaxBatches(), 0 );
constraintIndices.assign( numConstraints, -1 );
int currentBatchSize = 0;
// First we assign constraints to a batch, without assigning them particular ordered indices
do {
for(int batchID = 0; batchID < getMaxBatches(); ++batchID)
{
currentBatchSize = 0;
bodyUsed.assign( numBodies, false );
for(int constraintID = 0; constraintID < numConstraints; ++constraintID)
{
if( constraintAssigned[ constraintID ] ) continue;
const int b1 = pairList[ constraintID*2 ];
const int b2 = pairList[ constraintID*2 + 1];
if((b1 < 0 || !bodyUsed[ b1 ]) && ( b2 < 0 || !bodyUsed[ b2 ]))
{
if( b1 >= 0 ) bodyUsed[ b1 ] = true;
if( b2 >= 0 ) bodyUsed[ b2 ] = true;
constraintAssigned[ constraintID ] = true;
constraintIndices[ constraintID ] = batchID;
++constraintsUsed;
++currentBatchSize;
}
}
batchSizes[ batchID ] += currentBatchSize;
}
} while( constraintsUsed < numConstraints);
BatchVector batchSizesCopy = batchSizes;
BatchVector constraintIndicesCopy = constraintIndices;
// Now recover the ordered constraint indices from their batch assignment
for(int constraintID = 0; constraintID < numConstraints; ++constraintID) {
const int constraintBatchID = constraintIndicesCopy[ constraintID ];
const int newConstraintID = --batchSizesCopy[ constraintBatchID ];
constraintIndices[ constraintID ] = newConstraintID;
}
return baseBatch( pairList, constraintIndices, batchSizes, batchIndices, bodyRepetitionCount0, bodyRepetitionCount1, maxBodyRepetitionCountInBatch );
}
int ColoringBatchStrategy::batch( const int* pairList, const int numConstraints, const int numBodies,
BatchVector& constraintIndices,
BatchVector& bodyRepetitionCount0,
BatchVector& bodyRepetitionCount1,
BatchVector& maxBodyRepetitionCountInBatch,
BatchVector& batchIndices,
BatchVector& batchSizes )
{
BatchMultimap bodyConstraintMap;
BatchMultimap constraintHeap;
std::vector<BatchMultimapIterator> pointers( numConstraints );
BatchVector colors( numConstraints, std::numeric_limits<int>::max() );
int maxDegree( 0 ), numColors( 1 ), degree;
// Build body to constraint map
for( int constraintID = 0; constraintID < numConstraints; ++constraintID )
{
bodyConstraintMap.insert( std::make_pair( pairList[ constraintID*2 ], constraintID ) );
bodyConstraintMap.insert( std::make_pair( pairList[ constraintID*2 + 1 ], constraintID ) );
}
// Find the maximal degree, and degree, for each constraint
for( int constraintID = 0; constraintID < numConstraints; ++constraintID ) {
const int b1( pairList[ constraintID*2 ] );
const int b2( pairList[ constraintID*2 + 1 ] );
int degree = 0;
if( b1 >= 0 && b2 >= 0)
degree = bodyConstraintMap.count( b1 ) + bodyConstraintMap.count( b2 ) - 1;
else if( b1 >= 0 )
degree = bodyConstraintMap.count( b1 );
else if( b2 >= 0 )
degree = bodyConstraintMap.count( b2 );
if( degree > 0 ) {
pointers[ constraintID ] = constraintHeap.insert( std::make_pair( degree, constraintID ) );
maxDegree = std::max( maxDegree, degree );
}
}
BatchVector occurrences( getMaxBatches() );
BatchVector colorCount( numColors, 0 );
while( !constraintHeap.empty() ) {
int constraintID = constraintHeap.begin()->second;
constraintHeap.erase( constraintHeap.begin() );
occurrences.assign( numColors, 0 );
const int bodyIDs[2] = { pairList[ constraintID*2 ], pairList[ constraintID*2 + 1 ] };
for( int j = 0; j < 2; ++j) {
BatchMultimapIterator it = bodyConstraintMap.find( bodyIDs[ j ] );
if( it == bodyConstraintMap.end() ) continue;
BatchMultimapIterator end = bodyConstraintMap.upper_bound( bodyIDs[ j ] );
for(; it != end; ++it ) {
int bodyConstraintID = it->second;
if( bodyConstraintID == constraintID ) continue;
if( colors[ bodyConstraintID ] < numColors ) {
// Exclude color
++occurrences[ colors[ bodyConstraintID ] ];
}
else {
// Decrement degree ( the constraint has been assigned )
degree = pointers[ bodyConstraintID ]->first;
if( pointers[bodyConstraintID] == constraintHeap.begin() ) {
constraintHeap.erase( pointers[ bodyConstraintID ] );
pointers[ bodyConstraintID ] = constraintHeap.insert( std::make_pair( degree - 1, bodyConstraintID ) );
}
else {
constraintHeap.erase( pointers[ bodyConstraintID ]-- );
pointers[ bodyConstraintID ] = constraintHeap.insert( pointers[ bodyConstraintID ], std::make_pair( degree - 1, bodyConstraintID ) );
}
}
}
}
// Ensure creation of a well-balanced coloring
int minColor = 0;
for( int colorID = 1; colorID < numColors; ++colorID )
{
if( ( occurrences[ colorID ] < occurrences[ minColor ] ) ||
( occurrences[ colorID ] == occurrences[ minColor ] && colorCount[ colorID ] < colorCount[ minColor ] ) )
{
minColor = colorID;
}
}
if( occurrences[ minColor ] > 0 && numColors < getMaxBatches() )
{
colors[ constraintID ] = numColors++;
colorCount.resize( numColors );
colorCount[ colors[ constraintID ] ] = 1;
}
else
{
colors[ constraintID ] = minColor;
colorCount[ colors[ constraintID ] ]++;
}
}
batchSizes.resize( getMaxBatches(), 0 );
batchSizes = colorCount;
batchIndicesFromBatchSizes( batchSizes, batchIndices, isAligning( ), getAlignment( ) );
// Assign indices from colors
for( int constraintID = 0; constraintID < numConstraints; ++constraintID ) {
const int constraintBatchID = colors[ constraintID ];
constraintIndices[ constraintID ] = batchIndices[ constraintBatchID ] + ( batchSizes[ constraintBatchID ] - colorCount[ constraintBatchID ] );
--colorCount[ constraintBatchID ];
}
return batchRepetitionCount( pairList, constraintIndices, batchSizes, bodyRepetitionCount0, bodyRepetitionCount1, maxBodyRepetitionCountInBatch );
}
}
|
3de7d5ec312aca755f2c9611aa04443667b61236 | f978efedff0d32e980c37b25057d931476f0ad64 | /OnClass/ManageStudent/include/Person.h | 8fc91be325c5456f8e18289768149fb54de1cfcf | [] | no_license | mimiicteam/OOP | 18ae5ed7093a42a206de7c1a0e19fea33fe5701a | 9c5e3ea293311dac670e8253e4013e50034d3c94 | refs/heads/main | 2023-08-21T20:21:38.393455 | 2021-09-26T12:41:44 | 2021-09-26T12:41:44 | 403,605,551 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,736 | h | Person.h | #ifndef PERSON_H
#define PERSON_H
#include<iostream>
#include<string>
#include<cstring>
#include<Date.h>
using namespace std;
class Person
{
protected:
string firstName;
string lastName;
Date dob;
bool gender;
string address;
public:
Person()
{
firstName = "Nguyen Van ";
lastName = "Quoc";
}
string GetfirstName()
{
return firstName;
}
void SetfirstName(string val)
{
firstName = val;
}
string GetlastName()
{
return lastName;
}
void SetlastName(string val)
{
lastName = val;
}
Date Getdob()
{
return dob;
}
void Setdob(Date val)
{
dob = val;
}
bool Getgender()
{
return gender;
}
void Setgender(bool val)
{
gender = val;
}
string getAddress(){
return this->address;
}
void setAddress(string add){
this->address = add;
}
bool isName(string name)
{
for (int i = 0; i < name.length(); i++)
{
if(!isalpha(name[0]))
return false;
}
return true;
}
bool isNumber(string number){
for (int i = 0; i < number.length(); i++)
{
if(isalpha(number[0]))
return false;
}
return true;
}
string format(string fullname)
{
string name [fullname.length()] ;
int length = 0;
int begin = -1;
int end = 0 ;
for(int i = 0 ; i < fullname.length(); i++ )
{
if(isalpha(fullname[i]) && begin == -1 )
{
begin =i;
}
if(isalpha(fullname[i]) &&( isspace(fullname[i+1]) || i == fullname.length() - 1))
{
end = i;
string s = "";
s = fullname.substr(begin,end - begin + 1);
s[0] = islower(s[0]) ? (s[0] - 32): s[0];
for(int i = 1 ; i < s.length(); i++ )
{
if(isupper(s[i]))
s[i] = s[i] + 32;
}
name[length] = s;
length ++ ;
begin = -1;
}
}
string format = "";
for(int i = 0; i< length-1 ; i++ )
{
format += name[i] + " ";
}
format += name[length - 1];
return format;
}
void SetInputName(string sen , string &typeName ){
do
{
cout<<sen<<endl;
getline(cin,typeName);
}
while(!isName(typeName));
typeName = format(typeName);
}
friend istream& operator >>(istream &is , Person &p1 );
friend ostream& operator <<(ostream &is , Person p1 );
};
//istream& operator >>(istream &is , Person &p1 ){
// p1.SetInputName("Please Enter First Name ",p1.firstName);
// p1.SetInputName("Please Enter Last Name ",p1.lastName);
//
// int choose;
// do
// {
// cout<<"Please Enter your gender : 1/male 0/female"<<endl;
// is>>choose;
// }
// while(choose != 1 && choose != 0);
// p1.gender = choose;
// cout<<"Please Enter Address " <<endl;
// cin>>p1.address;
// p1.address = p1.format(p1.address);
// fflush(stdin);
// cout<<"Please Enter Day Of Birth " <<endl;
// is>>p1.dob;
// return is;
//}
// ostream& operator <<(ostream &os , Person p1 ){
// os<<"Full Name :"<<p1.firstName<<" "<<p1.lastName<<endl;
// os<<"Gender :"<<(p1.gender ? "male" : "female")<<endl;
// os<<"Date Of Birth :"<<p1.dob;
// return os;
// }
#endif // PERSON_H
|
a78b010e63501663629049bfc1ced98e7d65d23f | 0ba672d85df06c158c700855793c80c5b76fbeb0 | /acmicpc/cpp/2231.cc | 499b5edeb3c920769aa41b609a696ca7813c27db | [] | no_license | jhnaldo/problem-solving | 6b986a6d19cfe293c5e148e101fe2a7f88a4e45e | b4fec804b25d88a94cb65a8981f744b290849c1d | refs/heads/master | 2022-07-23T14:06:39.727661 | 2022-07-07T11:17:40 | 2022-07-07T11:17:40 | 122,852,274 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 378 | cc | 2231.cc | #include <stdio.h>
int main(){
int n, k;
scanf("%d", &n);
k = (n<60?0:n-60);
for (; k <= n; k++){
int sum = k;
int tmp = k;
while (k){
sum += k%10;
k /= 10;
}
k = tmp;
if (sum == n){
printf ("%d\n", k);
return 0;
}
}
printf("0\n");
return 0;
}
|
eef457927e887f7428890d7e24f89b24ccd4dfce | c3d209317a9ad3cd84fc41e3889380fd5e8f1931 | /lab1/palindrome/main.cpp | fe47ea4fc89b58ac90d2c9e3275a8c810057e397 | [] | no_license | skwiatkowska/jimp2-exercises | 9b8b4e4a2315d42223b2dc4f191a97fb8b3423fe | 9dbc427eab345941db50f2589a939e8241314dd5 | refs/heads/master | 2020-04-02T02:31:27.035029 | 2018-06-24T09:40:38 | 2018-06-24T09:40:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 630 | cpp | main.cpp | #include <iostream>
#include "Palindrome.h"
using namespace std;
int main(){
int menu;
string palindrome;
cout << "MENU" << endl << "\t0 - Wyjscie" << endl << "\t1 - Sprawdz palindrom" << endl;
cin >> menu;
if (menu==0){
return 0;
}
else if (menu==1){
cin >> palindrome;
if (IsPalindrome(palindrome)){
cout << "WYraz jest palindromem" << endl;
}
else{
cout << "Wyraz nie jest palindromem" << endl;
}
}
else{
cout << "Wpisano zly numer" << endl << "Podaj jeszcze raz: ";
cin >> menu;
}
return 0;
} |
d860d130ffdbf357b52c2a615ea53b956c29d8cb | c220031f8d01711ef95b7f9d74dabcdb169cd1fc | /include/Core/CompositeObject.hpp | ecf35b61f8adc9e492f211e1cdadf728cf84f0d5 | [] | no_license | MrPickle311/QuickCurses | 9c9e25b8243ee834cf197c059aeb0e7c36df5690 | 3314fd859c9c2672e2982915ccb61f728e618c31 | refs/heads/master | 2023-03-26T20:06:15.918633 | 2021-03-11T14:19:39 | 2021-03-11T14:19:39 | 329,426,916 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 139 | hpp | CompositeObject.hpp | #pragma once
#include "Object.hpp"
class CompositeObject:
public Object
{
public:
virtual void setParent(CompositeObject&) = 0;
}; |
824850616daa5be65925bc7e47e6f3a525bfe047 | c3027d7bd4285c60fbec46ef9bdd0c942124d20e | /xcore/UnitInvSwapEvent.cpp | efc9cb8153d27d6ef68196d6dfe0f0f84e0a50f1 | [
"MIT"
] | permissive | blazeroni/foxc | d35d15deab9882022b3a00af63fbfdfedabc8762 | c143edb63b90a6c500193ea5eac95f9c89e3c4ff | refs/heads/master | 2022-12-22T03:10:54.097399 | 2020-09-26T07:41:35 | 2020-09-26T07:41:35 | 298,534,484 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 644 | cpp | UnitInvSwapEvent.cpp | #include "includes.h"
#include "UnitInvSwapEvent.h"
BOOST_CLASS_EXPORT_GUID(xcore::UnitInvSwapEvent, "UNIT_INVSWAP_EVENT")
namespace xcore
{
UnitInvSwapEvent::UnitInvSwapEvent(uint32 unitID, int slot1, int slot2) :
Event(UNIT_INVSWAP),
_unitID(unitID),
_slot1(slot1),
_slot2(slot2)
{
}
UnitInvSwapEvent::~UnitInvSwapEvent()
{
}
uint32 UnitInvSwapEvent::getUnitID() const
{
return _unitID;
}
int UnitInvSwapEvent::getSlot1() const
{
return _slot1;
}
int UnitInvSwapEvent::getSlot2() const
{
return _slot2;
}
void UnitInvSwapEvent::process(IEventListener* handler)
{
handler->handleEvent(*this);
}
} // namespace
|
ed67846e3f1b425679a456843421b07a7ee27e1f | 065852abb89ebd78660b784030ea2fa175ba00d7 | /Functions/Random2.h | 533382150f3ce4110873b13e829a7e89e8c01bab | [] | no_license | Raj6713/BasicCpp | ed2c7858c0af31807cef0937f9ff3a964ad08264 | 47ada849826faf08b4e8668deb6cafbfa0e9c643 | refs/heads/master | 2021-07-05T13:09:52.729329 | 2017-09-29T21:48:11 | 2017-09-29T21:48:11 | 103,849,456 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,517 | h | Random2.h | /*This class will show functionality of srand class and show output*/
#include<iostream>
using namespace std;
#include<string>
#include<iomanip>
#include<cstdlib>
class Random2
{
private:
int i,upperLimit,freq1,freq2,freq3,freq4,freq5,freq6,seed;
string message;
public:
Random2();
~Random2();
void setUpperLimit(int);
int getUpperLimit();
void setSeed(int);
int getSeed();
void allocator();
void switcher(int);
void displayMessage();
};
Random2::Random2()
{
message="";
upperLimit=0;
freq1=freq2=freq3=freq4=freq5=freq6=0;
}
Random2::~Random2(){}
void Random2::setUpperLimit(int p)
{
if(p>0)
upperLimit=p;
else
upperLimit=50;
}
void Random2::setSeed(int p)
{
seed=p;
}
int Random2::getUpperLimit(){return upperLimit;}
int Random2::getSeed(){return seed;}
void Random2::allocator()
{
srand(getSeed());
for(int i=0;i<getUpperLimit();i++)
{
switcher(rand()%6+1);
}
message+="\nFrequency Graph for a dice:";
message+="\nFrequency[1]: "+to_string(freq1)+
"\nFrequency[2]: "+to_string(freq2)+
"\nFrequency[3]: "+to_string(freq3)+
"\nFrequency[4]: "+to_string(freq4)+
"\nFrequency[5]: "+to_string(freq5)+
"\nFrequency[6]: "+to_string(freq6);
}
void Random2::switcher(int p)
{
switch(p)
{
case 1: ++freq1; break;
case 2: ++freq2; break;
case 3: ++freq3; break;
case 4: ++freq4; break;
case 5: ++freq5; break;
case 6: ++freq6; break;
}
}
void Random2::displayMessage()
{
allocator();
cout<<message<<endl;
} |
52dbd23a466bd7d280cb3355aefc6bbea75cc0ee | 051839cfdc698f7dc53c08de696c925dc3cde79e | /codeforces/codeforces328/A.cpp | 39ef22d96802fb44de3a469eb20c20acc5168594 | [] | no_license | juangil/programmingContests | 37645ba582921cb104a66cd5332dfd94d59a9deb | dc0e7b11003411ebfee8f4fcb4024a10e5649b07 | refs/heads/master | 2021-01-17T13:40:07.398771 | 2016-07-13T15:25:50 | 2016-07-13T15:25:50 | 10,767,650 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,384 | cpp | A.cpp | # include <bits/stdc++.h>
using namespace std;
int main(){
vector<string> mio(8);
for(int i = 0; i < 8; ++i)
cin >> mio[i];
pair<char,int> winner = make_pair('A',10000);
for(int i = 0; i < 8; ++i){
for(int j = 0; j < 8; ++j){
char tmp = mio[i][j];
if(tmp == 'W'){
bool paila = false;
for(int k = i - 1; k >= 0; k--){
//cout << (mio[k][j] == '.') << endl;
if(mio[k][j] != '.')
paila = true;
}
//cout << paila << endl;
if(!paila){
if(winner.second >= i){
winner.second = i;
winner.first = 'A';
}
}
}
if(tmp == 'B'){
bool paila = false;
for(int k = i + 1; k < 8; k++){
if(mio[k][j] != '.')
paila = true;
}
if(!paila){
int dist = 7 - i;
if(winner.second > dist){
winner.second = dist;
winner.first = 'B';
}
}
}
}
}
cout << winner.first<< endl;
//cout << winner.second << endl;
return 0;
}
|
6485c7cb525cc2b7d0c5eb13166ed8087cdf2806 | b8765e762b1087505189506a35cffce43638fba7 | /question/Codeforces/contest/Educational Codeforces Round 5#/c/c.cpp | ef064e636df4bd1f9b4b5a71279c9b69387f03fb | [] | no_license | yaoling1997/desktop | 0d0782f44cca18ac97e806e919fc7c6446872a00 | 1053d1a30b1e45e82ceec90cfd3b31eec361c1e2 | refs/heads/master | 2022-02-17T12:50:54.349782 | 2019-05-18T06:13:03 | 2019-05-18T06:13:03 | 120,167,243 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,375 | cpp | c.cpp | #include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cstring>
#include<vector>
#define ll long long
#define ld long double
using namespace std;
const int maxn= 1e3+10,maxm= 1e6+10;
char s[maxn][maxn];
int B[maxn][maxn],sta[maxn];
int X[5],Y[5];
int f[maxm],sum[maxm],vis[maxm];
int n,m,i,j,k,tot,la,ans,x,y;
int find(int o){
if (o==f[o]) return o;
return f[o]= find(f[o]);
}
int main()
{
//freopen("1.in","r",stdin);
//freopen("1.out","w",stdout);
scanf("%d%d",&n, &m);
for (i= 1;i<=n;i++)
scanf("%s",s[i]+1);
X[1]= 1;
X[2]= -1;
Y[3]= 1;
Y[4]= -1;
for (i= 1;i<=n;i++)
for (j= 1;j<=m;j++)
B[i][j]= ++tot;
for (i= 1;i<=tot;i++)
f[i]= i;
for (i= 1;i<=n;i++){
for (j= 1;j<=m;j++)
if (s[i][j]=='.')
for (k= 1;k<=4;k++){
int xx= i+X[k],yy= j+Y[k];
if (s[xx][yy]=='.'){
x= B[i][j];
y= B[xx][yy];
find(x);
find(y);
f[f[x]]= f[y];
}
}
}
for (i= 1;i<=tot;i++){
find(i);
sum[f[i]]++;
}
for (i= 1;i<=n;i++){
for (j= 1;j<=m;j++)
if (s[i][j]=='.') printf(".");
else {
ans= 1;
for (k= 1;k<=4;k++){
int xx= i+X[k],yy= j+Y[k];
if (s[xx][yy]!='.') continue;
x= f[B[xx][yy]];
if (vis[x]) continue;
vis[x]= 1;
sta[++la]= x;
ans+= sum[x];
}
printf("%d",ans%10);
while (la)
vis[sta[la--]]= 0;
}
printf("\n");
}
return 0;
}
|
932d917c838a27cf56b43598f774dbf5983447f0 | cbe835b522c0fb035505304a44391e6db1db271d | /Binary matrix/Solver.h | 59a737d7838402e6cbb1cfd21ca7dd3c5fb472be | [] | no_license | Artvell/pract_5 | d5d36b27dec5b420514c446dfa94ec40fbf4c8a7 | f1e2e5fc6f9134999723078c573697d8b724cda1 | refs/heads/master | 2022-12-29T01:45:20.869668 | 2020-10-12T11:58:09 | 2020-10-12T11:58:09 | 301,372,201 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 622 | h | Solver.h | #pragma once
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
class Solver {
public:
vector<vector<int>> matrix;
int strings, rows;
vector<int> deleted;
ifstream in;
ofstream out;
string filename;
Solver(string name) {
filename = name;
}
int openWrite(); //done
int maxUnitString(); //done
int deleteCrossRows(); //done
bool isZerosExists(int ind);
int writeAnswer();
int solve();
int isExists(int n);
void print() {
for (int i = 0; i < matrix.size(); i++) {
for (int j = 0; j < matrix[i].size(); j++) {
cout << matrix[i][j] << " ";
}
cout << "\n";
}
}
}; |
5b5e024778b938d98da5d077543aa75e61082c22 | b3a7799c9a6e4057060f524928ba980be6c3a92c | /vk_dragons/src/StagingBuffer.h | db706b5f18bc7d9922e18810876e54899d30510d | [
"MIT"
] | permissive | aiekick/vk_dragons | 8b332015506c98562ea5d176396f56fc0fbf1d2e | e5b4708ac06087d169bd0d8631e588a1c894ab5b | refs/heads/master | 2021-07-25T20:50:33.626276 | 2017-09-30T23:00:01 | 2017-09-30T23:00:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 442 | h | StagingBuffer.h | #pragma once
#include "ProgramUtilities.h"
class StagingBuffer {
public:
StagingBuffer(Renderer& renderer, size_t size, const void* data);
~StagingBuffer();
void CopyToBuffer(VkCommandBuffer commandBuffer, VkBuffer dest);
void CopyToImage(VkCommandBuffer commandBuffer, VkImage dest, uint32_t width, uint32_t height, uint32_t arrayLayer);
private:
Renderer& renderer;
size_t size;
Buffer buffer;
void* mapping;
}; |
a644c417e76c08ef7f66a803581f58c827cbffe3 | e0b4fc8aaf60ff3c4187646ab132027b603da0be | /CR265/CR265_E/main.cpp | 4db38ce845aa9312e7a96a45c032167b6e4406ba | [] | no_license | tupieurods/SportProgramming | c886a2b3759d43d1ec52e949c7027c9c43bf6ef1 | 9f2362e14b51f249141166c1867d081f125e7358 | refs/heads/master | 2021-01-23T22:53:20.521768 | 2014-10-29T16:27:13 | 2014-10-29T16:27:13 | 15,796,982 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,358 | cpp | main.cpp | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <string>
#include <iostream>
using namespace std;
#define MOD 1000000007LL;
string s, comm[100009];
int n;
void ReadData()
{
cin >> s;
cin >> n;
for(int i = 0; i < n; i++)
{
cin >> comm[i];
}
}
__int64 answer;
__int64 trans[10], powers[10];
void Solve()
{
for(int i = 0; i < 10; i++)
{
trans[i] = i;
powers[i] = 10;
}
for(int i = n - 1; i >= 0; i--)
{
__int64 conv = 0;
__int64 newPow = 1;
int l = comm[i].length();
if(l > 3)
{
for(int j = 3; j < l; j++)
{
conv = (conv * powers[comm[i][j] - '0'] + trans[comm[i][j] - '0']) % MOD;
newPow = (powers[comm[i][j] - '0'] * newPow) % MOD;
}
}
trans[comm[i][0] - '0'] = conv;
powers[comm[i][0] - '0'] = newPow;
}
answer = 0;
__int64 nxtPow = 1;
int l = s.length();
for(int i = 0; i < l; i++)
{
answer = (answer * nxtPow + trans[s[i] - '0']) % MOD;
if(i != l - 1)
{
nxtPow = powers[s[i + 1] - '0'];
}
}
}
void WriteData()
{
cout << answer << endl;
}
int main()
{
int QWE = 1;
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
//scanf("%d", &QWE);
cin >> QWE;
#endif
for(int T = 0; T < QWE; T++)
{
ReadData();
Solve();
WriteData();
}
return 0;
} |
9641f510d09b31ca0c46217cf69b2e64454b0a7c | d1b5a40a428b8f7b2523c58ea2a2707aed84cc3b | /euler/euler1.cpp | c84f70c5c315a105f9aec54f5e37bcd7f2b34da3 | [] | no_license | pedroluiscastillo/cc2 | 8b1cd6924e551146cd1bb5dee1f3f02ec2cfb326 | ab86f30c065e3a09c0510e978400a509724f43ae | refs/heads/master | 2023-05-25T22:36:46.945921 | 2023-05-17T13:11:40 | 2023-05-17T13:11:40 | 180,625,504 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 167 | cpp | euler1.cpp | #include <iostream>
using namespace std;
int main(){
int a=0;
for(int x=0;x<1000;x++){
if(x%3==0 || x%5==0)
a=a+x;
}
cout<<a<<endl;
return 0;
} |
b098f93e1cd227100f45d0fb773713716450b3c3 | 96eb30bbf3237b9419c254008ff5bac5c3ebc3ab | /multicord_v1/spi_tests/SPI_firstTime_1/SPI_firstTime_1.ino | a16a676774b63c0b6d9658273ec2565a74f05c31 | [] | no_license | dovydasgulbinas/arduino-projects | 238178e7d3302afef300a884b644759c1fbe9c6b | 5d4162d034eb090bb4db0b8fea8747a7fefbea6f | refs/heads/master | 2021-06-06T20:49:42.661729 | 2016-12-03T22:16:58 | 2016-12-03T22:16:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 446 | ino | SPI_firstTime_1.ino | #include<SPI.h>
int SS = 10;
void setup() {
SPI.begin(); //initializes SPI
pinMode(SS,OUTPUT); //Creates a Slave select pin
digitalWrite(SS,HIGH);
}
void pushBytes(int reg, int data){
digitalWrite(SS,LOW); // SS pin is active low
SPI.transfer(); //Push the bytes from data sheet?
SPI.transfer(); // What push?
// ....
digitalWrite(SS,HIGH); // Ending Session
}
void loop() {
// put your main code here, to run repeatedly:
}
|
680c12d21a0438175129ed5af2c16c08fcc4950b | 34ec47abbff08f1b44af46e6d414242c4c079054 | /reference_wrapper.cpp | 0f5ccc92dbbe7648661b557c3c717ef581cb6103 | [] | no_license | gccross/snippets | 9b6692f9c31d1c06eb254800b3b07ed42af20625 | 6664702f442b97483aed9a029c5b70bbd5fa294a | refs/heads/master | 2021-01-11T12:36:04.760083 | 2020-10-04T18:06:00 | 2020-10-04T18:06:00 | 76,301,599 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,962 | cpp | reference_wrapper.cpp | /*
The objective of this code is to wrap a collection of functions in to a class
together so they can be called via overload resolution.
reference_wrapper's operator T&() causes ambiguity for our overload solution
see John's solution below, which only provides an operator(), and no operator T&()
#include <functional>
#include <iostream>
using func = void (*) (int, int); //typedef void (*func) (int, int);
// the name 'func' now denotes a pointer to function:
void example(int, int) {}
func f_alias = example;
template<typename F1, typename F2>
struct overload2 : public F1, public F2
{
overload2(const F1 & f1, const F2 & f2)
: F1(f1), F2(f2)
{}
// using F1::operator();
// using F2::operator();
};
void f(double d)
{
std::cout << "double d = " << d << std::endl;
}
void g(int x)
{
std::cout << "x = " << x << std::endl;
}
int main()
{
std::reference_wrapper<decltype(f)> fw(f);
std::reference_wrapper<decltype(g)> gw(g);
overload2<std::reference_wrapper<decltype(f)>,
std::reference_wrapper<decltype(g)>> F(fw, gw);
F(2.5);
F(3)r
}
*/
#include <iostream>
int f1(int)
{
std::cout << "void f1(int)" << std::endl;
return(0);
}
int f2(double)
{
std::cout << "void f2(double)" << std::endl;
return(0);
}
template<typename C>
struct functorize;
template<typename R, typename... Ps>
struct functorize<R (Ps...)>
{
functorize(R (&f)(Ps...))
: f(f)
{}
R operator()(Ps... args) const
{
return(f(args...));
}
R (*f)(Ps...);
};
struct A
{
int operator()(int x){ return f1(x); };
};
struct B
{
int operator()(double x){ return f2(x); };
};
struct C : B, A
{
};
struct c5 : functorize<int (int)>, functorize<int (double)>
{
c5(int (&f1)(int), int (&f2)(double))
: functorize<int (int)>(f1), functorize<int (double)>(f2)
{}
// using functorize<int (int)>::operator(), functorize<int (double)>::operator();
};
int main()
{
c5 c5_obj(f1, f2);
c5_obj(3.3);
c5_obj(3);
C c;
c(3);
c(3.3);
}
|
32ef5958f1e16b042de4d4dc6c37a0df29254068 | d8432c0d0c4c48a36a8b21f9b22700136869ed09 | /multi/multi.ino | 8e82d85f0fa3e854a23d71d04afc87b7a4fa9e32 | [] | no_license | ishiikurisu/clube_dudu | 07b904b0dd510db1dd28318476859f23fd9dcd73 | edd3f1326c4b4c54236ad09242fd094730826b39 | refs/heads/master | 2021-01-13T02:23:03.337996 | 2019-04-23T00:18:30 | 2019-04-23T00:18:30 | 24,171,266 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 591 | ino | multi.ino | class Thread {
public:
unsigned long period;
unsigned long last_call;
Thread(unsigned long new_period) {
period = new_period;
last_call = 0;
}
void thread(void (*function)(void)) {
unsigned long now = millis();
if (now - last_call >= period) {
last_call = now;
function();
}
}
};
Thread marcie(300);
Thread bonibel(500);
void setup() {
Serial.begin(9600);
}
void marceline() {
Serial.println("marceline");
}
void bubblegum() {
Serial.println("bubblegum");
}
void loop() {
marcie.thread(marceline);
bonibel.thread(bubblegum);
}
|
1754e944efff832b34c6bbac6b41c9d55a624eaa | 8fe21861a48bc8d4dbc897589e534a6c8d06325a | /AtCoder/Beginner 160/B.cpp | 334dc7f272e091b107a3dd5af29fdc77454e6909 | [] | no_license | MarcosFelipeBC/competitive-programming | c0470f1a3e31925997315e8e562248f3e4916cf2 | 5e4d6ab5d48af605fe5c76c7f7bda6911195b386 | refs/heads/master | 2021-07-08T10:26:25.853680 | 2020-10-15T20:26:44 | 2020-10-15T20:26:44 | 200,125,814 | 4 | 3 | null | 2020-10-15T20:49:50 | 2019-08-01T22:17:35 | C++ | UTF-8 | C++ | false | false | 229 | cpp | B.cpp | //https://atcoder.jp/contests/abc160/tasks/abc160_b
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
scanf("%d", &n);
long long ans = 1000LL * (n/500);
n %= 500;
ans += 5 * (n/5);
printf("%lld\n", ans);
} |
372f30e4bb5aad92375cc99b1384540c06077a15 | 0f7cf20a9d2c3567fa33240862756fd0c8e42142 | /TestaValidaNumero/include/ValorAbaixoException.h | c4404a34cadc05fa0a8672f2174f048d8350c9ee | [] | no_license | dionart/Lista2 | fb167dbb1cb1c7d7732826f81749ceefc0540d60 | 2f9fa68e479f5910362249426085aa2aa3631b25 | refs/heads/master | 2020-07-08T12:54:40.217674 | 2019-08-22T04:35:59 | 2019-08-22T04:35:59 | 203,678,564 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 324 | h | ValorAbaixoException.h | #ifndef VALORABAIXOEXCEPTION_H
#define VALORABAIXOEXCEPTION_H
#include <iostream>
class ValorAbaixoException
{
public:
ValorAbaixoException();
virtual std::string what();
protected:
std::string error = "Valor abaixo\n";
private:
};
#endif // VALORABAIXOEXCEPTION_H
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.