text:
99 3918 566 3455 8290 6455 1197 6667 2607 8290 6455 8248 4031 4545 4018 5695 6262 6667 7342 4545 4018 5558 2835 273 4376 4059 3455 166 3547 4509 5845 4545 7299 195 2911 879 166 3923 3455 2666 6667 3822 3989 7215 1202 5573 4663 1175 3255 7944 8063 3901 8431 6040 7944 8063 8053 954 4545 3378 2176 7342 4545 4018 3948 4545 7299 4509 7958 8431 4447 2936 6667
4227 6455 5735 3761 8162 1092 3892 7141 2063 4227 6455 3751 2062 5731 5392 300 5735 3689 7208 7590 6797 1202 1732 6637 3493 7324 6637 4441 3297 2558 3901 40 190 4227 7179 7364 4470 5092 7084 4620 6220 5016 7771 1118 1118 6455 4569 6660 8265 377 40 6756 88 4532 6557 5735 6830 7147 6557 2221 1651 2182 4227 8213 6895 5066 5480 285 537 5731 1335 1732 2200 2480 1515 4861 1697 2221 241 300 329 3693 5480 6362 676 615 6797 6989 5731 5792 2111 1308 7508 6020 2823 3683
8365 1753 4275 5310 7601 8131 3365 944 3378 5607 8234 5310 1331 1595 4791 4107 8290 825 7601 8131 3365 4275 420 3907 183 2829 8162 3516 5744 3365 5695 218 4425 4861 5418 8172 3365 6309 233 289 7981 1339 6727 2592 2367 645 4107 2163 3020 676 8063 183 5744 3365 3767 4595 3959 6220 5601 8063 4705 7450 6179 1523 5608 7319 1523 8063 7870 5223 3450 8063 166 1943 3707 5601 6667 7870 7046 3779 6070 2296 5695 8251 8063 6649 5601 8063 259 219 6219 7215 5109 5520 2231 3052 5601 8063 4275 7601 3365 5743 4107 5560 1163
1580 6235 4895 36 7944 7326 1202 1580 7944 7303 183 5362 5340 8069 4057 4654 4765 1163 7068 7346 1739 7402 7875 5218 4057 7118 7382 6455 40 3989 5044 5311 1040 5392 7875 165 5078 2293 3579 7262 6219 215 1862 6292 1862 6634 7752 7271 3157 7644 4057 7875 6850 7755 4595 4654 3767 221 1389 217 4492 4595 4654 935 4993 6494 5930 7817 7318 220 221 6900 7981 2230 7981 3829 5149 7613 3829 7968 6634 5218 7346 5199 825 7464 2296 1022 40 1971 3901 8431 6235 5816 2501 7817 1186 961
3568 8100 7800 4856 3378 17 6667 2035 8282 8326 5417 3500 6578 7469 17 8063 8063 4818 1681 5417 1202 8100 6667 2502 7817 6106 3579 6243 71 7959 1468 1001 1809 4554 3297 7416 5928 5624 7984 1001 4356 7959 6106 3989 7959 1001 4856 1001 6570 6599 2157 183 7959 8100 6667 8063 3767 513 1687 227 1389 2935 7981 6727 5132 8063 1943 8063 7870 3880 7515 6299 7981 3063 1340 8063 3767 220 1389 7870 6243 7418 1943 8063 7402 6745 5573 7241 4818 1687 3941 4183 1453 2296 7613 3901 4751 6667 5477 7303 17 6667 3253 2400
7944 7326 6462 17 1163 4039 3550 7192 7944 7326 17 1163 4039 1202 5210 1681 4716 4895 4039 227 675 1748 7544 1163 733 733 4830 6287 6263 7944 7303 6599 6136 7326 676 626 6923 545 4327 1163 4039 3767 2008 1056 227 1389 2935 7981 6727 6444 7326 6243 6455 5057 8063 1105 5109 5520 4039 482 7019 157 7981 6727 994 3822 3989 7303 7019 5109 5520 2137 2571 7895 3948 7533 7895 3989 462 2911 1434 7613 17 1163 4039 3853 3761
1019 8162 2896 203 5735 3901 203 5735 6455 5735 6858 1357 4778 6902 5980 4751 5735 1747 5731 999 1523 6692 218 6570 8206 7937 8162 5905 3693 5480 6787 8290 6452 3924 1327 5336 203 1118 7318 2730 7686 4669 5480 313 329 1862 40 1591 6645
7571 7686 1327 5336 6830 7967 2645 3794 7967 4227 6240 7299 291 675 3767 2275 935 4801 3959 1528 7595 1730 1389 2155 5002 1327 5336 1887 7967 1712 5735 6902 2591 3584 7967 6464 4193 3693 5480 1862 1327 5336 5845 5503 5284 1327 5480 6781 1862 5287 1706 1327 5336 8096 607 4936 4051 1600 5731 3767 2275 935 2502 7686 5503 5967 1327 5336 4597 7967 3767 2275 935 4801 3959 2502 7686 2111 8367 1327
2501 2230 2236 6550 5684 2501 3901 5011 1357 6550 5986 237 2761 2236 3719 6550 5011 2896 6894 227 5538 6468 286 3829 3829 3516 2395 235 2230 5845 1535 241 6352 7897 326 7897 40 6550 1311 1643 4649 133 3596 2343 5480 6440 5856 6574 6660 4870 4649 133 5964 3080 474 4644 5666 2591 2278 5964 503 307 215 3829 5011 5634 1202 2135 3829 1643 4649 7215 8054 227 2236 462 3128 6578 6773 3780 2297 825 3613 2403 463 2278 2236 8231 244 3829 3824 5695 5807 5856 5695 5786 6550 7883 5986 7958 7492 3516 6550 5986 7146 4649 2666 4240 4146 40 8387
7837 3337 6605 5131 3655 3071 3448 6462 463 6894 7837 3337 6103 6605 5131 6267 3655 4089 5102 3071 4863 7819 193 2671 5666 3986 1357 1909 7923 2954 5102 7819 2334 2592 7321 2967 329 5503 6573 193 1887 1843 6573 6684 7295 285 5503 5102 7819 6267 4089 3053 379 6571 193 1909 3463 3986 1357 7906 4581 183 7819 619 193 5666 2591 7493 6971 8084 2592 3448 7923 5339 7215 7969 3448 7853 6837 7215 484 3608 4092 1022 7330 6267 4089 7625 7215 5119 1099 3986 1357 6723 5666 2533 6265 7113 5744 3576 5970 8365 7853 3608
1360 1118 2413 5735 2573 5334 6573 4176 8341 6020 5735 2573 6400 3157 2829 40 383 6455 5811 40 6530 2010 6455 7361 6400 704 5733 5176 1644 1022 2257 704 4545 4018 5735 8206 5119 8291 2257 704 3455 40 2497 6400 7745 4295 7745 431 7745 4295 619 4227 1758 4545 4018 5695 3923 6702 6220 6702 4295 7745 7745 40 2497 4545 3455 166 4051 1534 2573 7745 1320 7100 4545 4018 2473 40 6530 6992 4847 281 56 40 2591 3643 5392 40 2497 8365 215
3568 4895 36 3499 7944 6667 1893 928 835 8094 6797 1097 7215 4895 36 1497 1365 3853 6573 1797 463 6667 835 8094 6894 928 6616 6727 6243 3020 4595 3959 626 4716 1874 6463 4895 36 7944 6667 6667 6839 8100 545 3841 6667 3767 4595 4654 7936 1389 2368 4856 7541 2287 1220 7329 8063 1389 2935 619 239 7981 6727 218 220 8063 4847 1943 8063 7981 219 7981 7870 3880 7046 7870 8063 7704 6466 4376 8063 4245 1943 219 7981 6727 4376 2501 7514 2296 2403 1943 8063 4047 3989 3880 2471 3779 5109 5520 3552 2700 2403 7981 6727 2888 2062 7216 6667 239 7981 6727 2660 7129 2257 2076 3301 6667 2403 913 2531 6886 6219 7012 7974 8063 3097 7928 928 835
649 2658 7837 5109 4554 7837 859 5486 186 5109 4554 1357 4554 1052 6574 3463 7208 7963 3989 5280 7412 7523 595 5744 1185 2903 5109 5520 595 5744 7461 1185 4245 3835 5967 859 5486 7521 5520 1311 688 2903 8391 3989 2334 5109 4554 4285 2111 8391 1655 3463 7208 7963 4673 4678 4030 641 5520 5280 7412 2658 482 3989 1135 5109 4554 4285 8072 595 5744 2658 1971 7958 8431 5109 4554 3989 2658 3063 7432 859 5486 186 52 3627 2732 4895 3312 7461 7944 6667
484 3850 4016 5059 3358 8414 6839 6455 4554 2825 4678 7944 8063 3513 4117 3850 4016 5059 3089 5626 5210 6839 6455 4554 2825 2403 6667 6727 7988 3693 8063 3767 3063 5343 8084 218 5343 2524 313 3850 8084 629 218 122 6502 5032 2775 8157 8084 5015 4260 329 5032 2775 363 7310 8084 633 6574 220 5503 619 6667 6727 6667 2879 6855 2825 8063 1655 1872 6886 913 2531 6886 6219 619 6667 6727 5558 5695 3576 263 275 257 262 191 5119 7100 3576 6634 5458 7251 354 6925 7041 3576 3165 6219 7215 5458 6502 6922 6127 6280 3576 6219 5695 3923 8084 629 4280 5695 8084 5015 4295 3901 6119 3850 4016 5059 979 8335 7239
7464 2701 2530 2956 6101 45 2830 8353 3182 221 2911 3485 1311 2423 2701 503 1607 236 2911 4509 1646 3820 3446 7464 2701 2591 15 3182 5197 221 2911 6220 2701 3080 2591 928 6585 503 7157 15 4733 503 8140 5664 2310 2701 3926 2701 3080 6220 7464
4441 43 5625 6152 1570 341 2458 746 5610 4441 43 5625 4289 4240 2236 6212 6152 1570 341 7464 216 813 4240 2236 4266 7899 2230 813 2236 4266 3343 7899 4275 6693 1780 298 4710 1868 7949 5386 2322 7100 746 5610 298 2236 4266 7899 4266 4275 2135 2007 813 7215 2474 6888 746 298 1360 3901 4716 2236 8355 665 746 2801 1570 341 1705 8355 895
3568 1244 162 890 2111 6875 8038 463 6891 484 2111 3083 7159 1457 2039 5412 3083 7091 86 7237 4685 2592 4967 186 7493 4150 3405 2367 4442 8367 244 7981 7176 7968 7215 5119 2100 7969 162 1357 5845 8038 7969 4468 4373 429 229 7981 3576 8367 7722 3083 7091 219 236 7981 7991 7091 219 7981 6220 5144 8367 219 7981 7722 7091 6578 1363 162 1357 4295 8367 219 7981 7991 7091 5695 1705 162 3405 7722 7091 8367 4295 3901 7492 6875 8038 485 2474 6888 162 1357 8281 3083 7091 7722 7091 4183 7991
2463 3083 8221 3448 6462 4046 913 3083 8221 7159 3880 3857 4470 2855 3448 6462 4989 463 240 2236 3448 6799 1679 913 4046 6528 3901 6220 5865 6101 2236 3083 7159 2135 3083 5255 2971 3083 2085 6528 913 5573 2671 2222 289 4562 6528 1263 312 4562 3141 285 4562 2010 306 4562 3141 285 4562 913 3448 1357 1891 3795 4094 2467 2236 4578 3455 6515 5573 3455 3923 6515 3923 1105 1211 5969 3901 913 217 4562 3141 277 4562 5119 3083 5255 1596 6528 913 6528 6838 4183 1896 3083 8221 6462 913 3118 4578 3455 1583 1420 3707 25 6455 3172 188 1357
6915 3509 2236 5865 4525 7708 1733 1311 2236 2256 7431 7708 4875 2666 4151 2434 7880 6152 3509 183 3795 6450 5460 3795 4763 3960 5401 7708 6152 3509 4805 4648 5937 4847 7937 2545 183 7432 7708 3509 4454 5937 3960 2236 5567 6179 2217 5567 1528 1261 3979 5841 3901 7364 4038 6152 3509 234 4648 5937 4963 2256 7708 3509 232 3299 6783 4633 1733 4805 7096 1951 4787 7899 6830 1893 3960 1826 4793 7968 6152 7708 2236 302 7937 6381 1589 2130 302 7937 6381 1589 2130 4716 2224 5865 7361 6849 3024 1320 7968 3553 5865 3960 6624
1893 3282 2367 2971 865 3501 6827 484 3509 1194 2236 3509 1311 7855 1014 1434 911 2367 865 3501 1052 3282 2367 4275 1717 7390 2911 3960 3509 3820 2715 6977 3501 1052 4119 2715 2222 3282 2367 329 1263 2010 5969 2575 2100 2575 2169 2591 3501 5969 2100 186 4275 3960 3509 8365 7379 4275 5855 3501 186 3282 2367 2074 1637 3397 6469 2007 5078 3697
8045 7046 7800 3246 3255 4759 7812 6444 2236 5711 4759 7812 1311 7372 1598 4221 7007 7516 1626 4759 7812 1769 7046 7800 3246 3820 3923 3202 239 4759 566 2135 4759 7812 8206 4759 1022 4830 8241 1241 4602 8241 4892 1606 7064 5628 4569 2236 7800 3246 2299 4759 7812 7226 4569 5220 150 3454 2236 6644 6637 3526 2299 7226 4569 155 257 4759 7812 5198 5164 5642 8206 2135 2417 7458 4759 4221 8241 7458 4759 4221 7515 6841 8096 7226 5284 4759 2423 7515 6694 6535 682 4892 8241 7046 7800 3246 2417 4221 4759 7812 6841 8096 7515 5164 5642 8206 8241 6841 8096 4221 7515 7458 4759 2423 7515 4228 6336 682 4892 8241 7458 4569 7046 7800 3246 7458 4759 4221 8096 607 2497 5573 4759 7812 8206 4228 8241 6841 8096 5392 4759 566 6380 325 682 1823 8241 7046 7800 3246 6841 8096 4221 8096 607 8206 1910 5392 4759 3820 8096 607 2417 4221 8096 607 150 4759 7812 4759 1598 4221 7958 6577 1823 3255 4759 7812 2236 1311 4526 1606 7064 4569 7046 7800 3246 5392 4569 4963 4759
7968 323 4774 5108 2463 4624 4235 558 1203 323 4774 4892 1472 2305 6835 323 4774 4624 3926 452 4537 6098 4851 1203 2645 323 4774 1420 5108 7984 682 2135 7595 3198 4240 7058 2371 7968 163 682 7595 3198 3513 4235 55 558 2301 3184 682 682 437 6320 4624 8321 6947 463 220 6320 217 682 3184 2135 3824 6223 7949 3834 2876 7431 1866 682 4283 5726 6815 956 3202 1439 2473 220 265 6291 6220 216 336 216 6945 2984 6815 66 3202 431 6830 2473 220 257 6291 220 6300 219 4295 4847 682 6837 6673 2217 2059 682 6815 4228 6321 7938 6837 2473 4624 52 2220 4624 6835 3568 2173 4702
2964 6675 1889 5402 8217 1204 1308 2964 6179 4396 6675 6256 3697 1065 3892 463 2371 7417 5968 4640 2666 3510 8324 2944 1889 3510 4050 4509 1889 7235 6382 3824 3829 5942 1625 1889 5815 2964 4513 123 4142 7176 6865 3824 6839 2526 1053 1080 6381 1027 1095 848 1889 5845 2964 6963 6675 1889 8231 3824 452 1504 1590 2432 52 48 3780 3303 3786 5968 2449
4117 7382 7416 3815 555 6191 629 484 5864 391 7382 2076 5970 5250 3255 4062 7382 7382 2076 5970 1468 3815 555 3466 5928 8414 5727 2801 5520 1461 2884 5520 1655 5970 1987 4257 1978 8414 1887 1216 4435 5626 2881 391 5792 8414 5727 4435 8109 7382 7416 3493 8200 7343 7416 8414 8109 7416 8255 5558 5047 7613
3083 4816 1357 4269 3839 463 384 1474 5556 4335 1357 3266 4269 6455 193 8367 6806 4269 239 676 615 4669 6455 5480 285 1439 5424 6455 5556 7930 5037 6815 5556 6357 2829 2163 5748 6357 1355 3685 4895 2088 1311 232 6570 4269 6570 2395 5558 5556 8423 2829 5558 5954 2163 6713 4335 2200 3526 5626 4038 4335 6637 7800 6822 8200 6628 4335 2200 3024 5198 232 6570 5556 7930 2858 8290 2829 8423 166 8200 2163 7966 7215 1114 5796 5748 1355 7077 7958 7492 3266 4269 193 8335 3714 6357 928 2132 1474 2403 1114 5796 232 6570 5060 4269 8431 1626
999 2501 551 1357 2556 2015 7809 4453 484 2015 551 1357 278 8353 7432 6966 551 1357 6574 813 2236 1311 5267 4509 1220 227 2236 7831 1889 906 5669 7891 5267 1220 4183 551 2257 40 5223 8021 6381 3948 166 2282 4509 7491 906 5669 5695 3923 228 2236 5267 1590 2236 906 5669 2299 3824 3576 1311 3657 2236 239 3829 2236 215 3829 4183 551 2257 40 5558 675 1132 5267 2015 675 1132 215 3829 16 5573 5626 4051 3697 3901 551 6563 8353 7432 1076 5258 2501 5626 551
4275 6152 1570 341 3360 6152 1570 341 2340 6673 248 8000 4201 7932 3096 7076 4875 5206 3434 385 1570 341 6192 2474 3519 7349 5279 3924 7698 4094 7632 4275 6152 1570
582 1783 6462 4253 6966 4558 220 647 1460 2081 582 1783 6462 4253 6966 220 647 227 1460 2236 1864 8021 6745 1299 551 8167 2903 6667 17 5634 2299 2135 5319 6667 1061 2299 2236 6667 5666 291 5044 1357 1889 7260 7897 582 1783 6462 5360 1683 8021 8063 6382 1801
5768 4833 5011 1987 1326 2554 4857 8028 6828 2422 3823 5097 6828 2422 3823 3095 3943 5695 7458 2497 4857 2898 2085 4833 3516 4238 5799 91 867 5768 4833 5011 7464 259 2236 3719 4485 6012 2403 217 7897 249 7897 6894 2671 5768 4833 5011 4857 5768 4833 5011 2085 2403 215 259 2236 232 2085 2395 4807 2236 4992 5768 5799 7159 5768 4833 3385 4701 2085 4435 1215 1271 7159 1749 40 1987 215 2236 2855 4238 4833 5011 1357 3901 8431 6527 1292 3710 8124 1595 4857 5768 4833 5011 2085 3498 296 1352 2282 4833 5011 3863 1543 7141 7007 4031


text:
#include <algorithm>
#include <ostream>
#include <string>
#include <vector>
#include "abstract_node.h"

abstract_node::abstract_node(std::string name)
	: name_(std::move(name)), parent_(nullptr)
{
}

abstract_node* abstract_node::next_sibling() const
{
	auto siblings = get_parent()->get_children();
	auto position = std::find(siblings.begin(), siblings.end(), this);
	return ++position != siblings.end() ? *position : nullptr;

}

void abstract_node::set_name(const std::string& name)
{
	name_ = name;
}

void abstract_node::set_parent(abstract_node* const parent)
{
	parent_ = parent;
}

std::string abstract_node::get_name() const
{
	return name_;
}

abstract_node* abstract_node::get_parent() const
{
	return parent_;
}

const  std::vector<abstract_node*>& abstract_node::get_children()
{
	static std::vector<abstract_node*> dummy{};
	return dummy;
}

abstract_node::Iterator abstract_node::begin()
{
	return Iterator{ this };
}

abstract_node::Iterator abstract_node::end()
{
	return Iterator{ nullptr };
}

void abstract_node::print(std::ostream& os) const
{
	os << "name_: " << this->name_;
}

std::ostream& operator<<(std::ostream& os, const abstract_node& obj)
{
	obj.print(os);
	return os;

}

bool operator==(const abstract_node& lhs, const abstract_node& rhs)
{
	return lhs.name_ == rhs.name_
		&& lhs.parent_ == rhs.parent_;
}

bool operator!=(const abstract_node& lhs, const abstract_node& rhs)
{
	return !(lhs == rhs);
}

repository: LimagoHub/cpp-tree-with-iterator

license_type: permissive

repo_name: LimagoHub/cpp-tree-with-iterator

branch_name: refs/heads/main

extension: cpp


text:
// potcut extracts plain text passwords from pot files
package main

import (
	"bufio"
	"fmt"
	"log"
	"os"

	"github.com/coolbry95/bitset"
	"github.com/dchest/siphash"
)

func main() {

	// check the commandline
	if len(os.Args) != 3 {
		log.Printf("usage: %s original pot\n", os.Args[0])
		os.Exit(-1)
	}

	// open the hash file for reading
	hashFile, err := os.Open(os.Args[1])
	if err != nil {
		log.Println(err.Error())
	}
	defer hashFile.Close()

	// open the pot file for reading
	potFile, err := os.Open(os.Args[2])
	if err != nil {
		log.Println(err.Error())
	}
	defer potFile.Close()

	// make the original and pot map
	original := bitset.NewBitset(500)

	// make the scanner for the hash file
	scanner := bufio.NewScanner(hashFile)

	// only scan the first one get the length
	// and store it in the original map
	scanner.Scan()
	temp := scanner.Bytes()

	// the size of the hash is to big for the bitset
	// this
	// https://github.com/Workiva/go-datastructures/blob/master/hashmap/fastinteger/hashmap.go#L47
	fmt.Println(siphash.Hash(9, 10, temp))
	original.Set(siphash.Hash(9, 10, temp) % 64 )

	// read throught the hash file
	// increment each time the same hash is seen
	for scanner.Scan() {
		original.Set(siphash.Hash(1, 0, scanner.Bytes()) % 64)
	}

	// check for errors in the scanner
	if err := scanner.Err(); err != nil {
		log.Println(err)
	}

	// make a scanner for the pot file
	scan := bufio.NewScanner(potFile)
	for scan.Scan() {
		temp := scan.Bytes()
		if original.Get(siphash.Hash(1, 0, temp)) {
			continue
		}
		//fmt.Println(string(temp))
	}

	// check for errors in the scanner
	if err := scanner.Err(); err != nil {
		log.Println(err)
	}
}

license: MIT

branch_name: refs/heads/master

extension: go


text:
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using Kafka.Client.Requests;

namespace Kafka.Client.Serialization
{
    /// <summary>
    ///     Reads data from underlying stream using big endian bytes order for primitive types
    ///     and UTF-8 encoding for strings.
    /// </summary>
    public class KafkaBinaryReader : BinaryReader
    {
        /// <summary>
        ///     Initializes a new instance of the <see cref="KafkaBinaryReader" /> class
        ///     using big endian bytes order for primive types and UTF-8 encoding for strings.
        /// </summary>
        /// <param name="input">
        ///     The input stream.
        /// </param>
        public KafkaBinaryReader(Stream input)
            : base(input) { }

        public bool DataAvailable
        {
            get
            {
                if (BaseStream is NetworkStream)
                {
                    return ((NetworkStream) BaseStream).DataAvailable;
                }

                return BaseStream.Length != BaseStream.Position;
            }
        }

        /// <summary>
        ///     Resets position pointer.
        /// </summary>
        /// <param name="disposing">
        ///     Not used
        /// </param>
        protected override void Dispose(bool disposing)
        {
            if (BaseStream.CanSeek)
            {
                BaseStream.Position = 0;
            }
        }

        /// <summary>
        ///     Reads two-bytes signed integer from the current stream using big endian bytes order
        ///     and advances the stream position by two bytes
        /// </summary>
        /// <returns>
        ///     The two-byte signed integer read from the current stream.
        /// </returns>
        public override short ReadInt16()
        {
            var value = base.ReadInt16();
            var currentOrdered = IPAddress.NetworkToHostOrder(value);
            return currentOrdered;
        }

        /// <summary>
        ///     Reads four-bytes signed integer from the current stream using big endian bytes order
        ///     and advances the stream position by four bytes
        /// </summary>
        /// <returns>
        ///     The four-byte signed integer read from the current stream.
        /// </returns>
        public override int ReadInt32()
        {
            var value = base.ReadInt32();
            var currentOrdered = IPAddress.NetworkToHostOrder(value);
            return currentOrdered;
        }

        [CLSCompliant(false)]
        public override uint ReadUInt32()
        {
            var value = ReadBytes(4);
            return BitConverter.ToUInt32(value.Reverse().ToArray(), 0);
        }

        /// <summary>
        ///     Reads eight-bytes signed integer from the current stream using big endian bytes order
        ///     and advances the stream position by eight bytes
        /// </summary>
        /// <returns>
        ///     The eight-byte signed integer read from the current stream.
        /// </returns>
        public override long ReadInt64()
        {
            var value = base.ReadInt64();
            var currentOrdered = IPAddress.NetworkToHostOrder(value);
            return currentOrdered;
        }

        /// <summary>
        ///     Reads four-bytes signed integer from the current stream using big endian bytes order
        ///     and advances the stream position by four bytes
        /// </summary>
        /// <returns>
        ///     The four-byte signed integer read from the current stream.
        /// </returns>
        public override int Read()
        {
            var value = base.Read();
            var currentOrdered = IPAddress.NetworkToHostOrder(value);
            return currentOrdered;
        }

        /// <summary>
        ///     Reads fixed-length short string from underlying stream using given encoding.
        /// </summary>
        /// <param name="encoding">
        ///     The encoding to use.
        /// </param>
        /// <returns>
        ///     The read string.
        /// </returns>
        public string ReadShortString(string encoding = AbstractRequest.DefaultEncoding)
        {
            var length = ReadInt16();
            if (length == -1)
            {
                return null;
            }

            var bytes = ReadBytes(length);
            var encoder = Encoding.GetEncoding(encoding);
            return encoder.GetString(bytes);
        }
    }
}

repository: IvanZheng/IFramework

repo_name: IvanZheng/IFramework

gha_license_id: MIT

gha_language: C#

extension: cs


text:
package x0

import (
	"encoding/json"

	"github.com/x0tf/x0go/schema"
)

// InstanceClient is used to execute API requests directed to the general instance
type InstanceClient struct {
	http *httpClient
}

// GetInfo requests the instance information for the specified x0 instance
func (client *InstanceClient) GetInfo() (*schema.InstanceInfo, error) {
	response, err := client.http.execute("GET", endpointInfo, nil)
	if err != nil {
		return nil, err
	}

	info := new(schema.InstanceInfo)
	if err := json.Unmarshal(response, info); err != nil {
		return nil, err
	}
	return info, nil
}


text:
package data

import "encoding/json"

// Aluno -> representa um determinado aluno
type Aluno struct {
	Nome  string `json:"nome"`
	Curso string `json:"curso"`
}

// Matricula -> Representa uma determinada matrícula
type Matricula struct {
	Ra    string `json:"ra"`
	Aluno *Aluno
}

// Operations -> Representa as operações possíveis
type Operations interface {
	Serializar() ([]byte, error)
}

// CriarAluno -> Cria um novo aluno
func CriarAluno(nome, curso string) *Aluno {
	return &Aluno{
		Nome:  nome,
		Curso: curso,
	}
}

// CriarMatricula -> Cria uma nova matrícula
func CriarMatricula(aluno *Aluno) *Matricula {
	return &Matricula{
		Ra:    "",
		Aluno: aluno,
	}
}

// Serializar -> Serializa uma matrícula no formato JSON
func (matricula *Matricula) Serializar() ([]byte, error) {
	return json.Marshal(matricula)
}

repository: V-H-R-Oliveira/Sistemas-Distribuidos

repo_name: V-H-R-Oliveira/Sistemas-Distribuidos


text:
package i18n

import (
	"fmt"
	"strings"
)

// type MinorBundle struct {
// 	local string
// 	langs map[string]string
// }

// func (mb *MinorBundle) Local() string {
// 	return mb.local
// }

type BundleEntry map[string]string

type Bundle map[string]BundleEntry

func (b Bundle) Lang(local, name string, args ...interface{}) (lang string) {

	if !localReg.MatchString(local) {
		return
	}
	// var ok bool
	local = strings.ToUpper(local)
	name = strings.ToUpper(name)
	major := local
	entry, _ := b[local]
	if entry == nil {
		index := strings.Index(local, "-")
		if index > 0 {
			major = local[:index]
			minor := local[index+1:]

			entry, _ = b[major]
			if entry == nil {
				entry, _ = b[minor]
			}
		}
		if entry == nil {
			for loc, entryLike := range b {
				if strings.HasPrefix(loc, major) {
					entry = entryLike
					break
				}
			}
		}
	}

	var tag string
	if entry != nil {
		tag, _ = entry[name]
	}
	if tag == "" {
		for loc, entry := range b {
			if strings.HasPrefix(loc, major) {
				continue
			}
			tag, _ = entry[name]
			if tag != "" {
				break
			}
		}
	}
	// logs.Debug("tag:%s,name:%s  %s  %s    %+v", tag, name, local, major, entry)
	return fmt.Sprintf(tag, args...)
}

repository: hereyou-go/web

repo_name: hereyou-go/web


text:
package bot

import (
	"encoding/json"
	"fmt"
	"reflect"
	"regexp"

	"github.com/ghodss/yaml"
	"github.com/lnxjedi/gopherbot/robot"
)

// loadTaskConfig() updates task/job/plugin configuration and namespaces/parametersets
// from robot.yaml and external configuration, then updates the
// globalTasks struct.
func loadTaskConfig(processed *configuration, preConnect bool) (*taskList, error) {
	newList := &taskList{
		t:             []interface{}{struct{}{}}, // initialize 0 to "nothing", for namespaces & parametersets only
		nameMap:       make(map[string]int),
		idMap:         make(map[string]int),
		nameSpaces:    make(map[string]ParameterSet),
		parameterSets: make(map[string]ParameterSet),
	}
	currentCfg.RLock()
	current := taskList{
		t:       currentCfg.t,
		nameMap: currentCfg.nameMap,
	}
	currentCfg.RUnlock()

	// Start with all the Go tasks, plugins and jobs
	for taskname := range taskHandlers {
		t := current.getTaskByName(taskname)
		newList.addTask(t)
	}

	for plugname := range pluginHandlers {
		t := current.getTaskByName(plugname)
		newList.addTask(t)
	}

	for jobname := range jobHandlers {
		t := current.getTaskByName(jobname)
		newList.addTask(t)
	}

	for _, ns := range processed.nsList {
		if _, ok := newList.nameMap[ns.Name]; ok {
			return newList, fmt.Errorf("NameSpace '%s' conflicts with another task/job/plugin/parameterset name", ns.Name)
		}
		newList.nameSpaces[ns.Name] = ParameterSet{
			name:        ns.Name,
			Description: ns.Description,
			Parameters:  ns.Parameters,
		}
		// The nameMap is the definitive list of all names, but namespaces don't correspond
		// to an actual task.
		newList.nameMap[ns.Name] = 0
	}

	for _, ps := range processed.psList {
		if _, ok := newList.nameMap[ps.Name]; ok {
			return newList, fmt.Errorf("ParameterSet '%s' conflicts with another task/job/plugin/parameterset name", ps.Name)
		}
		newList.parameterSets[ps.Name] = ParameterSet{
			name:        ps.Name,
			Description: ps.Description,
			Parameters:  ps.Parameters,
		}
		// The nameMap is the definitive list of all names, but parameter sets don't correspond
		// to an actual task.
		newList.nameMap[ps.Name] = 0
	}

	// Return disabled, error
	checkTaskSettings := func(ts TaskSettings, task *Task) (bool, error) {
		if ts.Disabled {
			task.Disabled = true
			task.reason = fmt.Sprintf("disabled in %s", robotConfigFileName)
			return true, nil
		}
		if len(ts.NameSpace) > 0 {
			if _, ok := newList.nameSpaces[ts.NameSpace]; !ok {
				return false, fmt.Errorf("configured NameSpace '%s' for task '%s' doesn't exist", ts.NameSpace, ts.Name)
			}
			task.NameSpace = ts.NameSpace
		}
		if len(ts.ParameterSets) > 0 {
			for _, set := range ts.ParameterSets {
				if _, ok := newList.parameterSets[set]; !ok {
					return false, fmt.Errorf("configured ParameterSet '%s' for task '%s' doesn't exist", set, ts.Name)
				}
			}
			task.ParameterSets = ts.ParameterSets
		}
		task.Description = ts.Description
		task.Parameters = ts.Parameters
		return false, nil
	}

	setupGoTask := func(ts TaskSettings, ttype pipeAddType) error {
		t := newList.getTaskByName(ts.Name)
		if t == nil {
			return fmt.Errorf("configuring Go task '%s' - no task found with that name", ts.Name)
		}
		task, plug, job := getTask(t)
		if (ttype == typePlugin && plug == nil) || (ttype == typeJob && job == nil) || task == nil {
			return fmt.Errorf("configuring Go task '%s' (type %s) - no task of that type registered with that name", ts.Name, ttype)
		}
		_, err := checkTaskSettings(ts, task)
		return err
	}

	// Get basic task configurations
	for _, ts := range processed.goTasks {
		if err := setupGoTask(ts, typeTask); err != nil {
			return newList, err
		}
	}
	for _, ts := range processed.goPlugins {
		if err := setupGoTask(ts, typePlugin); err != nil {
			return newList, err
		}
	}
	for _, ts := range processed.goJobs {
		if err := setupGoTask(ts, typeJob); err != nil {
			return newList, err
		}
	}

	addExternalTask := func(ts TaskSettings, ttype pipeAddType) (*Task, error) {
		if !identifierRe.MatchString(ts.Name) {
			return nil, fmt.Errorf("external task '%s' (type %s) doesn't match task name regex '%s'", ts.Name, ttype, identifierRe.String())
		}
		if ts.Name == "bot" {
			return nil, fmt.Errorf("illegal external task name 'bot' (type %s)", ts.Name)
		}
		if _, ok := newList.nameSpaces[ts.Name]; ok {
			return nil, fmt.Errorf("external task '%s' duplicates name of configured NameSpace", ts.Name)
		}
		if _, ok := newList.parameterSets[ts.Name]; ok {
			return nil, fmt.Errorf("external task '%s' duplicates name of configured ParameterSet", ts.Name)
		}
		if dupidx, ok := newList.nameMap[ts.Name]; ok {
			dupt := newList.t[dupidx]
			duptask, _, _ := getTask(dupt)
			if duptask.taskType == taskGo {
				return nil, fmt.Errorf("external task '%s' duplicates name of existing Go task/plugin/job", ts.Name)
			}
			return nil, fmt.Errorf("external task '%s' duplicates name of other external task/plugin/job", ts.Name)
		}
		task := &Task{
			name:        ts.Name,
			taskType:    taskExternal,
			Description: ts.Description,
			Parameters:  ts.Parameters,
		}
		// Note that disabled external tasks are skipped in conf.go
		_, err := checkTaskSettings(ts, task)
		if err != nil {
			return nil, err
		}
		if len(ts.Path) == 0 {
			return nil, fmt.Errorf("zero-length path for external task '%s'", ts.Name)
		}
		if _, _, err := getObjectPath(ts.Path); err != nil {
			return nil, fmt.Errorf("getting path '%s' for task '%s': %v", ts.Path, ts.Name, err)
		}
		task.Path = ts.Path
		return task, nil
	}

	for _, script := range processed.externalPlugins {
		var task *Task
		var err error
		if task, err = addExternalTask(script, typePlugin); err != nil {
			return newList, err
		}
		task.Privileged = *script.Privileged
		task.Homed = script.Homed
		p := &Plugin{
			Task: task,
		}
		newList.addTask(p)
	}

	for _, script := range processed.externalJobs {
		var task *Task
		var err error
		if task, err = addExternalTask(script, typeJob); err != nil {
			return newList, err
		}
		task.Privileged = *script.Privileged
		task.Homed = script.Homed
		j := &Job{
			Task: task,
		}
		newList.addTask(j)
	}

	for _, script := range processed.externalTasks {
		var task *Task
		var err error
		if task, err = addExternalTask(script, typeTask); err != nil {
			return newList, err
		}
		task.Privileged = *script.Privileged
		task.Homed = script.Homed
		newList.addTask(task)
	}

	// Load configuration for all valid tasks. Note that this is all being loaded
	// in to non-shared data structures that will replace current configuration
	// under lock at the end.
LoadLoop:
	for _, j := range newList.t[1:] {
		var plugin *Plugin
		var job *Job
		var task *Task
		var isPlugin, isJob bool
		switch t := j.(type) {
		case *Plugin:
			isPlugin = true
			plugin = t
			task = t.Task
			// Reset list of channels
			task.Channels = []string{}
		case *Job:
			isJob = true
			job = t
			task = t.Task
		// a bare task with no config to load
		default:
			continue
		}

		if task.Disabled {
			continue
		}
		tcfgdefault := make(map[string]interface{})
		tcfgload := make(map[string]json.RawMessage)
		if isPlugin {
			Log(robot.Info, "Loading configuration for plugin '%s', type %s", task.name, task.taskType)
		} else {
			Log(robot.Info, "Loading configuration for job '%s', type %s", task.name, task.taskType)
		}

		// Don't get plugin external configuration during preconnect,
		// since plugins may rely on stuff loaded by init jobs.
		if isPlugin && !preConnect {
			if plugin.taskType == taskExternal {
				// External plugins spit their default config to stdout when called with command="configure"
				cfg, err := getExtDefCfg(task)
				if err != nil {
					msg := fmt.Sprintf("Getting default configuration for external plugin, disabling: %v", err)
					Log(robot.Error, msg)
					task.Disabled = true
					task.reason = msg
					continue
				}
				if err := yaml.Unmarshal(*cfg, &tcfgdefault); err != nil {
					msg := fmt.Sprintf("Unmarshalling default configuration, disabling: %v", err)
					Log(robot.Error, "Problem unmarshalling plugin default config for '%s', disabling: %v", task.name, err)
					task.Disabled = true
					task.reason = msg
					continue
				}
			} else {
				if err := yaml.Unmarshal([]byte(pluginHandlers[task.name].DefaultConfig), &tcfgdefault); err != nil {
					msg := fmt.Sprintf("Unmarshalling default configuration, disabling: %v", err)
					Log(robot.Error, "Problem unmarshalling plugin default config for '%s', disabling: %v", task.name, err)
					task.Disabled = true
					task.reason = msg
					continue
				}
			}
		}
		// getConfigFile overlays the default config with configuration from the install path, then config path
		cpath := "jobs/"
		if isPlugin {
			cpath = "plugins/"
		}
		if err := getConfigFile(cpath+task.name+".yaml", false, tcfgload, tcfgdefault); err != nil {
			msg := fmt.Sprintf("Problem loading configuration file(s) for task '%s', disabling: %v", task.name, err)
			Log(robot.Error, msg)
			task.Disabled = true
			task.reason = msg
			continue
		}
		if disjson, ok := tcfgload["Disabled"]; ok {
			disabled := false
			if err := json.Unmarshal(disjson, &disabled); err != nil {
				msg := fmt.Sprintf("Problem unmarshalling value for 'Disabled' in plugin/job '%s', disabling: %v", task.name, err)
				Log(robot.Error, msg)
				task.Disabled = true
				task.reason = msg
				continue
			}
			if disabled {
				msg := fmt.Sprintf("Plugin/Job '%s' is disabled by configuration", task.name)
				Log(robot.Info, msg)
				task.Disabled = true
				task.reason = msg
				continue
			}
		}
		// Boolean false values can be explicitly false, or default to false
		// when not specified. In some cases that matters.
		explicitAllChannels := false
		explicitAllowDirect := false

		for key, value := range tcfgload {
			var strval string
			var intval int
			var boolval bool
			var sarrval []string
			var hval []PluginHelp
			var mval []InputMatcher
			var tval []JobTrigger
			var val interface{}
			skip := false
			switch key {
			case "Elevator", "Authorizer", "AuthRequire", "NameSpace", "Channel":
				val = &strval
			case "KeepLogs":
				val = &intval
			case "Disabled":
				skip = true
			case "AllowDirect", "AmbientMatchCommand", "DirectOnly", "DenyDirect", "AllChannels", "RequireAdmin", "AuthorizeAllCommands", "CatchAll", "MatchUnlisted", "Quiet":
				val = &boolval
			case "Channels", "ElevatedCommands", "ElevateImmediateCommands", "Users", "AuthorizedCommands", "AllowedHiddenCommands", "AdminCommands", "ParameterSets":
				val = &sarrval
			case "Help":
				val = &hval
			case "CommandMatchers", "ReplyMatchers", "MessageMatchers", "Arguments":
				val = &mval
			case "Triggers":
				val = &tval
			case "Config":
				skip = true
			case "Privileged":
				return newList, fmt.Errorf("task '%s' illegally specifies 'Privileged' outside of %s", task.name, robotConfigFileName)
			default:
				msg := fmt.Sprintf("Invalid configuration key for task '%s': %s - disabling", task.name, key)
				Log(robot.Error, msg)
				task.Disabled = true
				task.reason = msg
				continue LoadLoop
			}

			if !skip {
				if err := json.Unmarshal(value, val); err != nil {
					msg := fmt.Sprintf("Disabling plugin '%s' - error unmarshalling value '%s': %v", task.name, key, err)
					Log(robot.Error, msg)
					task.Disabled = true
					task.reason = msg
					continue LoadLoop
				}
			}

			mismatch := false
			// Defaults
			switch key {
			case "AllowDirect":
				task.AllowDirect = *(val.(*bool))
				explicitAllowDirect = true
			case "DirectOnly":
				task.DirectOnly = *(val.(*bool))
			// plugins can be scheduled, so Channel applies to both
			case "Channel":
				task.Channel = *(val.(*string))
			// Channels are only used for plugin visibility
			case "Channels":
				if isPlugin {
					task.Channels = *(val.(*[]string))
				} else {
					mismatch = true
				}
			case "AllChannels":
				task.AllChannels = *(val.(*bool))
				explicitAllChannels = true
			case "RequireAdmin":
				task.RequireAdmin = *(val.(*bool))
			case "AdminCommands":
				if isPlugin {
					plugin.AdminCommands = *(val.(*[]string))
				} else {
					mismatch = true
				}
			case "NameSpace":
				Log(robot.Error, "Task '%s' specifies NameSpace outside of %s, ignoring", robotConfigFileName)
			case "ParameterSets":
				Log(robot.Error, "Task '%s' specifies ParameterSets outside of %s, ignoring", robotConfigFileName)
			case "Elevator":
				task.Elevator = *(val.(*string))
			case "ElevatedCommands":
				if isPlugin {
					plugin.ElevatedCommands = *(val.(*[]string))
				} else {
					mismatch = true
				}
			case "ElevateImmediateCommands":
				if isPlugin {
					plugin.ElevateImmediateCommands = *(val.(*[]string))
				} else {
					mismatch = true
				}
			case "Users":
				task.Users = *(val.(*[]string))
			case "KeepLogs":
				if isPlugin {
					mismatch = true
				} else {
					job.KeepLogs = *(val.(*int))
				}
			case "Authorizer":
				task.Authorizer = *(val.(*string))
			case "AuthRequire":
				task.AuthRequire = *(val.(*string))
			case "AllowedHiddenCommands":
				if isPlugin {
					plugin.AllowedHiddenCommands = *(val.(*[]string))
				} else {
					mismatch = true
				}
			case "AuthorizedCommands":
				if isPlugin {
					plugin.AuthorizedCommands = *(val.(*[]string))
				} else {
					mismatch = true
				}
			case "AuthorizeAllCommands":
				if isPlugin {
					plugin.AuthorizeAllCommands = *(val.(*bool))
				} else {
					mismatch = true
				}
			case "Help":
				if isPlugin {
					plugin.Help = *(val.(*[]PluginHelp))
				} else {
					mismatch = true
				}
			case "CommandMatchers":
				if isPlugin {
					plugin.CommandMatchers = *(val.(*[]InputMatcher))
				} else {
					mismatch = true
				}
			case "ReplyMatchers":
				if isPlugin {
					task.ReplyMatchers = *(val.(*[]InputMatcher))
				} else {
					mismatch = true
				}
			case "MessageMatchers":
				if isPlugin {
					plugin.MessageMatchers = *(val.(*[]InputMatcher))
				} else {
					mismatch = true
				}
			case "Arguments":
				if isPlugin {
					mismatch = true
				} else {
					job.Arguments = *(val.(*[]InputMatcher))
				}
			case "AmbientMatchCommand":
				if isPlugin {
					plugin.AmbientMatchCommand = *(val.(*bool))
				} else {
					mismatch = true
				}
			case "CatchAll":
				if isPlugin {
					plugin.CatchAll = *(val.(*bool))
				} else {
					mismatch = true
				}
			case "MatchUnlisted":
				if isPlugin {
					plugin.MatchUnlisted = *(val.(*bool))
				} else {
					mismatch = true
				}
			case "Quiet":
				if isPlugin {
					mismatch = true
				} else {
					job.Quiet = *(val.(*bool))
				}
			case "Triggers":
				if isPlugin {
					mismatch = true
				} else {
					job.Triggers = *(val.(*[]JobTrigger))
				}
			case "Config":
				task.Config = value
			}
			if mismatch {
				var msg string
				if isPlugin {
					msg = fmt.Sprintf("Disabling plugin '%s' - invalid configuration key: %s", task.name, key)
				} else {
					msg = fmt.Sprintf("Disabling job '%s' - invalid configuration key: %s", task.name, key)
				}
				Log(robot.Error, msg)
				task.Disabled = true
				task.reason = msg
				continue LoadLoop
			}
		}
		// End of reading configuration keys

		// Start sanity checking of configuration
		if task.DirectOnly {
			if explicitAllowDirect {
				if !task.AllowDirect {
					msg := fmt.Sprintf("Task '%s' has conflicting values for AllowDirect (false) and DirectOnly (true), disabling", task.name)
					Log(robot.Error, msg)
					task.Disabled = true
					task.reason = msg
					continue
				}
			} else {
				Log(robot.Debug, "DirectOnly specified without AllowDirect; setting AllowDirect = true")
				task.AllowDirect = true
				explicitAllowDirect = true
			}
		}

		if !explicitAllowDirect {
			task.AllowDirect = processed.defaultAllowDirect
		}

		// Sanity checking / default for channel / channels
		if isJob && len(task.Channel) == 0 {
			task.Channel = processed.defaultJobChannel
		}
		if isPlugin {
			// Use bot default plugin channels if none defined, unless AllChannels requested.
			if len(task.Channels) == 0 {
				if len(processed.plugChannels) > 0 {
					if !task.AllChannels { // AllChannels = true is always explicit
						task.Channels = processed.plugChannels
					}
				} else { // no default channels specified
					if !explicitAllChannels { // if AllChannels wasn't explicitly configured, and no default channels, default to AllChannels = true
						task.AllChannels = true
					}
				}
			}
		}

		// Considering possible default channels, is the plugin visible anywhere?
		if isPlugin {
			if len(task.Channels) > 0 {
				msg := fmt.Sprintf("Plugin '%s' will be available in channels %q", task.name, task.Channels)
				Log(robot.Info, msg)
			} else {
				if !(task.AllowDirect || task.AllChannels) {
					msg := fmt.Sprintf("Plugin '%s' not visible in any channels or by direct message, disabling", task.name)
					Log(robot.Error, msg)
					task.Disabled = true
					task.reason = msg
					continue
				} else {
					Log(robot.Info, "Plugin '%s' has no channel restrictions configured; all channels: %t", task.name, task.AllChannels)
				}
			}
		} else {
			if len(task.Channel) == 0 {
				Log(robot.Error, "Job '%s' has no channel, and no DefaultJobChannel set, disabling", task.name)
				task.Disabled = true
				task.reason = "no channel set"
				continue
			} else {
				Log(robot.Info, "Job '%s' will run in channel '%s'", task.name, task.Channel)
			}
		}

		// Compile the regex's
		if isPlugin {
			for i := range plugin.CommandMatchers {
				command := &plugin.CommandMatchers[i]
				regex := `^(?s:\s*` + command.Regex + `\s*)$`
				re, err := regexp.Compile(regex)
				if err != nil {
					msg := fmt.Sprintf("Disabling '%s', couldn't compile command regular expression '%s': %v", task.name, regex, err)
					Log(robot.Error, msg)
					task.Disabled = true
					task.reason = msg
					continue LoadLoop
				} else {
					// Store the modified regex
					command.Regex = regex
					command.re = re
				}
			}
			for i := range plugin.MessageMatchers {
				// Note that full message regexes don't get the beginning and end anchors added - the individual plugin
				// will need to do this if necessary.
				message := &plugin.MessageMatchers[i]
				re, err := regexp.Compile(message.Regex)
				if err != nil {
					msg := fmt.Sprintf("Disabling '%s', couldn't compile message regular expression '%s': %v", task.name, message.Regex, err)
					Log(robot.Error, msg)
					task.Disabled = true
					task.reason = msg
					continue LoadLoop
				} else {
					message.re = re
				}
			}
		} else {
			for i := range job.Triggers {
				trigger := &job.Triggers[i]
				if len(trigger.User) == 0 || len(trigger.Channel) == 0 {
					msg := fmt.Sprintf("Disabling '%s', zero-length User or Channel for trigger #%d", task.name, i+1)
					Log(robot.Error, msg)
					task.Disabled = true
					task.reason = msg
					continue LoadLoop
				}
				re, err := regexp.Compile(trigger.Regex)
				if err != nil {
					msg := fmt.Sprintf("Disabling '%s', couldn't compile trigger regular expression '%s': %v", task.name, trigger.Regex, err)
					Log(robot.Error, msg)
					task.Disabled = true
					task.reason = msg
					continue LoadLoop
				} else {
					trigger.re = re
				}
			}
			for i := range job.Arguments {
				argument := &job.Arguments[i]
				label := argument.Label
				if stockRepliesRe.MatchString(label) {
					msg := fmt.Sprintf("Disabling '%s', invalid regex label '%s' starts with capital letter", task.name, label)
					Log(robot.Error, msg)
					task.Disabled = true
					task.reason = msg
					continue LoadLoop
				}
				regex := `^\s*` + argument.Regex + `\s*$`
				re, err := regexp.Compile(regex)
				if err != nil {
					msg := fmt.Sprintf("Disabling '%s', couldn't compile argument regular expression '%s': %v", task.name, regex, err)
					Log(robot.Error, msg)
					task.Disabled = true
					task.reason = msg
					continue LoadLoop
				} else {
					argument.Regex = regex
					argument.re = re
				}
			}
		}
		for i := range task.ReplyMatchers {
			reply := &task.ReplyMatchers[i]
			label := reply.Label
			if stockRepliesRe.MatchString(label) {
				msg := fmt.Sprintf("Disabling '%s', invalid regex label '%s' starts with capital letter", task.name, label)
				Log(robot.Error, msg)
				task.Disabled = true
				task.reason = msg
				continue LoadLoop
			}
			re, err := regexp.Compile(`^\s*` + reply.Regex + `\s*$`)
			if err != nil {
				msg := fmt.Sprintf("Skipping %s, couldn't compile reply regular expression '%s': %v", task.name, reply.Regex, err)
				Log(robot.Error, msg)
				task.Disabled = true
				task.reason = msg
				continue LoadLoop
			} else {
				reply.re = re
			}
		}

		// Make sure all security-related command lists resolve to actual
		// commands to guard against typos.
		if isPlugin {
			cmdlist := []struct {
				ctype string
				clist []string
			}{
				{"elevated", plugin.ElevatedCommands},
				{"elevate immediate", plugin.ElevateImmediateCommands},
				{"authorized", plugin.AuthorizedCommands},
				{"admin", plugin.AdminCommands},
			}
			for _, cmd := range cmdlist {
				if len(cmd.clist) > 0 {
					for _, i := range cmd.clist {
						cmdfound := false
						for _, j := range plugin.CommandMatchers {
							if i == j.Command {
								cmdfound = true
								break
							}
						}
						if !cmdfound {
							for _, j := range plugin.MessageMatchers {
								if i == j.Command {
									cmdfound = true
									break
								}
							}
						}
						if !cmdfound {
							msg := fmt.Sprintf("Disabling %s, %s command %s didn't match a command from CommandMatchers or MessageMatchers", task.name, cmd.ctype, i)
							Log(robot.Error, msg)
							task.Disabled = true
							task.reason = msg
							continue LoadLoop
						}
					}
				}
			}
			// For Go plugins, use the provided empty config struct to go ahead
			// and unmarshall Config. The GetTaskConfig call just sets a pointer
			// without unmshalling again.
			if plugin.taskType == taskGo {
				// Copy the pointer to the empty config struct / empty struct (when no config)
				// pluginHandlers[name].Config is an empty struct for unmarshalling provided
				// in RegisterPlugin.
				pt := reflect.ValueOf(pluginHandlers[task.name].Config)
				if pt.Kind() == reflect.Ptr {
					if task.Config != nil {
						// reflect magic: create a pointer to a new empty config struct for the plugin
						task.config = reflect.New(reflect.Indirect(pt).Type()).Interface()
						if err := json.Unmarshal(task.Config, task.config); err != nil {
							msg := fmt.Sprintf("Unmarshalling plugin config json to config, disabling: %v", err)
							Log(robot.Error, msg)
							task.Disabled = true
							task.reason = msg
							continue
						}
					} else {
						// Providing custom config not required (should it be?)
						Log(robot.Warn, "Plugin '%s' has custom config, but none is configured", task.name)
					}
				} else {
					if task.Config != nil {
						msg := fmt.Sprintf("Custom configuration data provided for Go plugin '%s', but no config struct was registered; disabling", task.name)
						Log(robot.Error, msg)
						task.Disabled = true
						task.reason = msg
					} else {
						Log(robot.Debug, "Config interface isn't a pointer, skipping unmarshal for Go plugin '%s'", task.name)
					}
				}
			}
		}

		Log(robot.Debug, "Configured task '%s'", task.name)
	}
	// End of configuration loading. All invalid tasks are disabled.

	return newList, nil
}

repository: lnxjedi/gopherbot

repo_name: lnxjedi/gopherbot

gha_language: Go


text:
//go:build digitalocean || do || !onlyprovider

package digitalocean

import (
	"context"
	"encoding/json"
	"fmt"
	"os"
	"strconv"
	"strings"

	"github.com/digitalocean/godo"
	"github.com/nanovms/ops/lepton"
	"github.com/olekukonko/tablewriter"
)

// CreateInstance - Creates instance on Digital Ocean Platform
func (do *DigitalOcean) CreateInstance(ctx *lepton.Context) error {
	config := ctx.Config()

	image, err := do.getImageByName(ctx, config.CloudConfig.ImageName)
	if err != nil {
		return err
	}

	imageID, _ := strconv.Atoi(image.ID)

	flavor := "s-1vcpu-1gb"
	if config.CloudConfig.Flavor != "" {
		flavor = config.CloudConfig.Flavor
	}

	instanceName := config.RunConfig.InstanceName
	imageName := "image:" + image.Name

	keys, _, err := do.Client.Keys.List(context.TODO(), &godo.ListOptions{
		Page:    1,
		PerPage: 200,
	})
	if err != nil {
		return err
	}

	dropletKeys := []godo.DropletCreateSSHKey{}

	for _, key := range keys {
		dropletKeys = append(dropletKeys, godo.DropletCreateSSHKey{
			ID:          key.ID,
			Fingerprint: key.Fingerprint,
		})
	}

	createReq := &godo.DropletCreateRequest{
		Name:   instanceName,
		Size:   flavor,
		Region: config.CloudConfig.Zone,
		Image: godo.DropletCreateImage{
			ID: imageID,
		},
		Tags:    []string{opsTag, imageName},
		SSHKeys: dropletKeys,
	}

	_, _, err = do.Client.Droplets.Create(context.TODO(), createReq)
	if err != nil {
		return err
	}

	return nil
}

// GetInstanceByName returns instance with given name
func (do *DigitalOcean) GetInstanceByName(ctx *lepton.Context, name string) (*lepton.CloudInstance, error) {
	droplets, err := do.GetInstances(ctx)
	if err != nil {
		return nil, err
	}

	if len(droplets) == 0 {
		return nil, lepton.ErrInstanceNotFound(name)
	}

	for _, d := range droplets {
		if d.Name == name {
			return &d, nil
		}
	}

	return nil, lepton.ErrInstanceNotFound(name)
}

// GetInstances return all instances on DigitalOcean
// TODO
func (do *DigitalOcean) GetInstances(ctx *lepton.Context) ([]lepton.CloudInstance, error) {
	opt := &godo.ListOptions{}
	list, _, err := do.Client.Droplets.ListByTag(context.TODO(), opsTag, opt)
	if err != nil {
		return nil, err
	}

	cinstances := []lepton.CloudInstance{}
	for _, droplet := range list {
		privateIPV4, _ := droplet.PrivateIPv4()
		publicIPV4, _ := droplet.PublicIPv4()
		publicIPV6, _ := droplet.PublicIPv6()

		instance := lepton.CloudInstance{
			ID:         fmt.Sprintf("%d", droplet.ID),
			Name:       droplet.Name,
			Status:     droplet.Status,
			Created:    droplet.Created,
			PrivateIps: []string{privateIPV4},
			PublicIps:  []string{publicIPV4, publicIPV6},
		}

		isOpsImage := false

		for _, t := range droplet.Tags {
			if t == opsTag {
				isOpsImage = true
			} else if strings.Contains(t, "image:") {
				parts := strings.Split(t, ":")
				if len(parts) > 1 {
					instance.Image = parts[1]
				}
			}
		}

		if isOpsImage {
			cinstances = append(cinstances, instance)
		}

	}

	return cinstances, nil
}

// ListInstances lists instances on DO
func (do *DigitalOcean) ListInstances(ctx *lepton.Context) error {
	instances, err := do.GetInstances(ctx)
	if err != nil {
		return err
	}
	if ctx.Config().RunConfig.JSON {
		return json.NewEncoder(os.Stdout).Encode(instances)
	}
	// print list of images in table
	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Name", "Id", "Status", "Created", "Private Ips", "Public Ips", "Image"})
	table.SetHeaderColor(
		tablewriter.Colors{tablewriter.Bold, tablewriter.FgCyanColor},
		tablewriter.Colors{tablewriter.Bold, tablewriter.FgCyanColor},
		tablewriter.Colors{tablewriter.Bold, tablewriter.FgCyanColor},
		tablewriter.Colors{tablewriter.Bold, tablewriter.FgCyanColor},
		tablewriter.Colors{tablewriter.Bold, tablewriter.FgCyanColor},
		tablewriter.Colors{tablewriter.Bold, tablewriter.FgCyanColor},
		tablewriter.Colors{tablewriter.Bold, tablewriter.FgCyanColor})
	table.SetRowLine(true)
	for _, instance := range instances {
		var rows []string
		rows = append(rows, instance.Name)
		rows = append(rows, instance.ID)
		rows = append(rows, instance.Status)
		rows = append(rows, instance.Created)
		rows = append(rows, strings.Join(instance.PrivateIps, ","))
		rows = append(rows, strings.Join(instance.PublicIps, ","))
		rows = append(rows, instance.Image)
		table.Append(rows)
	}
	table.Render()
	return nil

}

// DeleteInstance deletes instance from DO
func (do *DigitalOcean) DeleteInstance(ctx *lepton.Context, instancename string) error {
	instance, err := do.GetInstanceByName(ctx, instancename)
	if err != nil {
		return err
	}

	instanceID, _ := strconv.Atoi(instance.ID)

	_, err = do.Client.Droplets.Delete(context.TODO(), instanceID)
	if err != nil {
		return err
	}

	return nil
}

// StartInstance starts an instance in DO
func (do *DigitalOcean) StartInstance(ctx *lepton.Context, instancename string) error {
	instance, err := do.GetInstanceByName(ctx, instancename)
	if err != nil {
		return err
	}

	instanceID, _ := strconv.Atoi(instance.ID)

	_, _, err = do.Client.DropletActions.PowerOn(context.TODO(), instanceID)
	if err != nil {
		return err
	}

	return nil
}

// StopInstance deletes instance from DO
func (do *DigitalOcean) StopInstance(ctx *lepton.Context, instancename string) error {
	instance, err := do.GetInstanceByName(ctx, instancename)
	if err != nil {
		return err
	}

	instanceID, _ := strconv.Atoi(instance.ID)

	_, _, err = do.Client.DropletActions.PowerOff(context.TODO(), instanceID)
	if err != nil {
		return err
	}

	return nil
}

// GetInstanceLogs gets instance related logs
func (do *DigitalOcean) GetInstanceLogs(ctx *lepton.Context, instancename string) (string, error) {
	return "", nil
}

// PrintInstanceLogs writes instance logs to console
func (do *DigitalOcean) PrintInstanceLogs(ctx *lepton.Context, instancename string, watch bool) error {
	l, err := do.GetInstanceLogs(ctx, instancename)
	if err != nil {
		return err
	}
	fmt.Printf(l)
	return nil
}

repository: nanovms/ops

repo_name: nanovms/ops


text:
// ***********************************************************************
// Assembly         : XLabs.Forms
// Author           : XLabs Team
// Created          : 12-27-2015
//
// Last Modified By : XLabs Team
// Last Modified On : 01-04-2016
// ***********************************************************************
// <copyright file="ContentControl.cs" company="XLabs Team">
//     Copyright (c) XLabs Team. All rights reserved.
// </copyright>
// <summary>
//       This project is licensed under the Apache 2.0 license
//       https://github.com/XLabs/Xamarin-Forms-Labs/blob/master/LICENSE
//
//       XLabs is a open source project that aims to provide a powerfull and cross
//       platform set of controls tailored to work with Xamarin Forms.
// </summary>
// ***********************************************************************
//

using Xamarin.Forms;

namespace XLabs.Forms.Controls
{
    /// <summary>
    /// A view that renders its content based on a data template. Typical usage is to either set an explicit
    /// <see cref="BindableObject.BindingContext"/> on this element or use an inhereted one, then set a display.
    /// </summary>
    public class ContentControl : ContentView
    {
        /// <summary>
        /// The content template property
        /// </summary>
        public static readonly BindableProperty ContentTemplateProperty =
            BindableProperty.Create(nameof(ContentTemplate),typeof(DataTemplate), typeof(ContentControl), null, propertyChanged: OnContentTemplateChanged);

        private static void OnContentTemplateChanged(BindableObject bindable, object oldvalue, object newvalue)
        {
            var cp = (ContentControl)bindable;

            var template = cp.ContentTemplate;
            if (template != null)
            {
                var content = (View)template.CreateContent();
                cp.Content = content;
            }
            else
            {
                cp.Content = null;
            }
        }

        /// <summary>
        /// A <see cref="DataTemplate"/> used to render the view. This property is bindable.
        /// </summary>
        public DataTemplate ContentTemplate
        {
            get
            {
                return (DataTemplate)GetValue(ContentTemplateProperty);
            }
            set
            {
                SetValue(ContentTemplateProperty, value);
            }
        }

    }
}