├── .gitignore ├── .gitmodules ├── LICENSE ├── README.md ├── app.py ├── apply_colors.py ├── basemodel.py ├── config.sample.py ├── consume.py ├── create.py ├── extra_data.py ├── markov.py ├── models.py ├── parsexml.py ├── poetry.lock ├── pyproject.toml ├── server.py ├── shuffle.py ├── templates ├── base.html ├── detail.html ├── list.html ├── macros.html └── quiz.html ├── text_generator.py ├── todb.py ├── updater.py ├── utils.py └── web ├── __init__.py └── static ├── js ├── app.js └── awesomplete.min.js └── sass ├── _awesomplete.base.scss ├── _awesomplete.custom.scss ├── _pagination.scss ├── _variables.scss └── style.scss /.gitignore: -------------------------------------------------------------------------------- 1 | sites 2 | raw 3 | downloads 4 | chains 5 | word-rnn-tensorflow/ 6 | .idea/ 7 | __pycache__/ 8 | config.py 9 | *.old 10 | 11 | web/static/css/ 12 | !web/static/css/.gitkeep 13 | count.txt 14 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "web/milligram"] 2 | path = web/milligram 3 | url = git@github.com:Findus23/milligram.git 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # se-simulator 2 | Generating fun Stack Exchange questions using Markov chains 3 | 4 | ### [try it out](http://se-simulator.lw1.at/) 5 | 6 | ### Requirements 7 | 8 | - python 3.5+ (only tested with python 3.6) 9 | - 7z 10 | 11 | For Debian and similar distribution install with: 12 | 13 | ```bash 14 | sudo apt-get install p7zip-full 15 | ``` 16 | 17 | ### Setup 18 | 19 | - git clone with submodules 20 | 21 | ```bash 22 | git clone https://github.com/Findus23/se-simulator 23 | cd se-simulator 24 | git submodule init 25 | git submodule update 26 | ``` 27 | 28 | - `pip install -r requirements.txt` 29 | - create a MySQL database called `se-simulator` 30 | - rename `config.sample.py` to `config.py` and fill in the database details and create a `secret_key` 31 | - run `create.py`, which creates the database and fetches the list of SE sites 32 | - run `apply_colors.py` (which should run really quickly) 33 | - create folders called `chains`, `download` and `raw` (or syminks to somewhere where more disk space is left) 34 | - [download](https://archive.org/details/stackexchange] `.7z` files for the sites you want to generate (it's recommend to start with a file <100MB) 35 | - If the `.7z` has another name as the site has now, rename it 36 | - run `consume.py` 37 | - It should check the hash, move the file to `raw/`, unpack it and extract the needed content from the `.xml` files into new `.jsonl` files. It also writes the data of the file into the db, so it won't be imported again. 38 | - now the most important step: run `todb.py` 39 | - this will generate the markov chains and save them (or use existing ones on the next run) 40 | - afterwards 100 questions will be added to the db, with corresponding answers, titles and usernames 41 | - run `shuffle.py` 42 | - I haven't found a performant way to get a random question without asigning every question an integer and saving the maximum to `count.txt` 43 | - run `server.py` 44 | - this starts the Flask server on `http://127.0.0.1:5000/` 45 | - if I didn't miss an important step, the site should be working fine now. 46 | 47 | ### other files 48 | 49 | - `app.py`: needed for Flask 50 | - `basemodel.py` and `models.py`: [peewee](https://github.com/coleifer/peewee/) ORM 51 | - `extra_data.py`: manually collected colors of every site with an custom theme 52 | - `markov.py`: extending the great [markovify library](https://github.com/jsvine/markovify/) for my use case 53 | - `parsexml.py`: reading in the Stack Exchange dump XML files with no more than 40MB RAM usage. 54 | - `text_generator.py`: everything that creates the content and handles the Markov chains 55 | - `updater.py`: probably not working anymore, checks for newer dump files 56 | - `utils.py`: everything else 57 | -------------------------------------------------------------------------------- /app.py: -------------------------------------------------------------------------------- 1 | # Blog configuration values. 2 | import sentry_sdk 3 | from flask import Flask 4 | from playhouse.flask_utils import FlaskDB 5 | from playhouse.pool import PooledMySQLDatabase 6 | from sentry_sdk.integrations.flask import FlaskIntegration 7 | 8 | import config 9 | 10 | DATABASE = PooledMySQLDatabase("se-simulator", **config.db) 11 | 12 | if config.sentryDSN: 13 | sentry_sdk.init( 14 | dsn=config.sentryDSN, 15 | integrations=[FlaskIntegration()] 16 | ) 17 | 18 | # Create a Flask WSGI app and configure it using values from the module. 19 | app = Flask(__name__) 20 | app.config.from_object(__name__) 21 | 22 | flask_db = FlaskDB(app) 23 | 24 | db = flask_db.database 25 | -------------------------------------------------------------------------------- /apply_colors.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import utils 3 | from models import * 4 | from extra_data import site_colors 5 | 6 | for site in Site.select(): 7 | if site.url in site_colors: 8 | site.primary_color = "#" + site_colors[site.url]["primary"] 9 | site.foreground_color = "#" + site_colors[site.url]["fg"] 10 | site.background_color = "#" + site_colors[site.url]["bg"] 11 | site.save() 12 | -------------------------------------------------------------------------------- /basemodel.py: -------------------------------------------------------------------------------- 1 | import __main__ 2 | from peewee import Model, MySQLDatabase 3 | 4 | import config 5 | 6 | if __main__.__file__ != "server.py": 7 | db = MySQLDatabase("se-simulator", **config.db) 8 | db.connect() 9 | else: 10 | from app import db 11 | 12 | 13 | class BaseModel(Model): 14 | class Meta: 15 | database = db 16 | -------------------------------------------------------------------------------- /config.sample.py: -------------------------------------------------------------------------------- 1 | # database must be "se-simulator" 2 | db = { 3 | "host": "localhost", 4 | "user": "username", 5 | "passwd": "password", 6 | } 7 | 8 | # Check http://flask.pocoo.org/docs/0.12/quickstart/#sessions on how to create 9 | secret_key = 10 | 11 | # See https://pythonhosted.org/Flask-Session/ 12 | session_type = "filesystem" 13 | 14 | make_cacheable = False 15 | 16 | production = False 17 | -------------------------------------------------------------------------------- /consume.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import glob 3 | import os 4 | import shutil 5 | import subprocess 6 | from datetime import datetime 7 | 8 | from models import * 9 | from parsexml import parse_posts, parse_comments, parse_usernames 10 | from utils import * 11 | 12 | files = get_files() 13 | 14 | # TODO: name sites/id after real url 15 | 16 | for file in glob.glob("downloads/**/*.7z", recursive=True): 17 | if "meta" in file: 18 | continue 19 | filename = os.path.basename(file) 20 | code = os.path.splitext(filename)[0] 21 | if filename not in files: 22 | print("{file} doesn't exist on archive.org".format(file=file)) 23 | continue 24 | meta = files[filename] 25 | sha1 = file_hash(file) 26 | if sha1 != meta["sha1"]: 27 | print("{file}: hashes don't match".format(file=filename)) 28 | continue 29 | alias = Alias.select().where(Alias.url == code) 30 | if len(alias) != 0: 31 | site_id = alias[0].site_id 32 | print(site_id) 33 | site = Site.select().where(Site.id == site_id)[0] 34 | else: 35 | db_element = Site().select().where(Site.url == code) 36 | if len(db_element) == 0: 37 | print("{site} not found in database".format(site=code)) 38 | continue 39 | site = db_element[0] 40 | mtime = datetime.fromtimestamp(int(meta["mtime"])) 41 | if site.last_download == mtime: 42 | print("{site} is up to date".format(site=filename)) 43 | continue 44 | else: 45 | site.last_download = mtime 46 | site.save() 47 | print(code) 48 | currentdir = os.getcwd() 49 | rawdir = "raw/" + code 50 | chainsdir = "chains/" + code 51 | for dir in [rawdir, chainsdir]: 52 | if not os.path.exists(dir): 53 | os.mkdir(dir) 54 | 55 | shutil.copy2(file, rawdir) 56 | os.chdir(rawdir) 57 | print("Start extracting") 58 | subprocess.check_output(["7z", "x", "-aoa", code + ".7z"]) 59 | os.chdir(currentdir) 60 | print("Start parsing") 61 | parse_posts(rawdir, rawdir) 62 | parse_comments(rawdir, rawdir) 63 | parse_usernames(rawdir, rawdir) 64 | print("DONE") 65 | -------------------------------------------------------------------------------- /create.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import html 3 | from urllib.parse import urlparse 4 | 5 | import requests 6 | 7 | from models import * 8 | 9 | mdls = [Answer, Question, Title, User, Alias, Site] 10 | for i in mdls: 11 | i.drop_table() 12 | for i in reversed(mdls): 13 | print(i) 14 | i.create_table() 15 | 16 | r = requests.get("https://api.stackexchange.com/2.2/sites?pagesize=500") 17 | for site in r.json()["items"]: 18 | if site["site_type"] == "meta_site": 19 | continue 20 | element, created = Site.get_or_create(shortname=site["api_site_parameter"]) 21 | print(created) 22 | element.name = html.unescape(site["name"]) 23 | element.shortname = site["api_site_parameter"] 24 | element.url = urlparse(site["site_url"]).hostname 25 | element.icon_url = site["high_resolution_icon_url"] if "high_resolution_icon_url" in site else site["icon_url"] 26 | styling = site["styling"] 27 | element.tag_background_color = styling["tag_background_color"] 28 | element.tag_foreground_color = styling["tag_foreground_color"] 29 | element.link_color = styling["link_color"] 30 | element.save() 31 | if "aliases" in site: 32 | for al in site["aliases"]: 33 | domain = urlparse(al).hostname 34 | alias, created = Alias.get_or_create(url=domain, site=element) 35 | -------------------------------------------------------------------------------- /extra_data.py: -------------------------------------------------------------------------------- 1 | site_colors = { 2 | "stackoverflow.com": {"fg": "FF9900", "bg": "ffffff", "primary": "FF9900"}, 3 | "serverfault.com": {"fg": "F3F1D9", "bg": "444444", "primary": "F3F1D9"}, 4 | "superuser.com": {"fg": "ffffff", "bg": "00a1c9", "primary": "00a1c9"}, 5 | "webapps.stackexchange.com": {"fg": "d9dde0", "bg": "444444", "primary": "d9dde0"}, 6 | "webmasters.stackexchange.com": {"fg": "ffffff", "bg": "6ad4fc", "primary": "6ad4fc"}, 7 | "gamedev.stackexchange.com": {"fg": "416d63", "bg": "fffeee", "primary": "edec80"}, 8 | "gaming.stackexchange.com": {"fg": "ffffff", "bg": "374a75", "primary": "374a75"}, 9 | "cooking.stackexchange.com": {"fg": "bc4133", "bg": "e5f9e7", "primary": "bc4133"}, 10 | "photo.stackexchange.com": {"fg": "ffffff", "bg": "4d4b4b", "primary": "4d4b4b"}, 11 | "stats.stackexchange.com": {"fg": "155078", "bg": "ffffff", "primary": "e8eceb"}, 12 | "math.stackexchange.com": {"fg": "0f3559", "bg": "ffffff", "primary": "cb181f"}, 13 | "diy.stackexchange.com": {"fg": "ffffff", "bg": "5588b9", "primary": "5588b9"}, 14 | "gis.stackexchange.com": {"fg": "748a95", "bg": "f2e8d0", "primary": "f2e8d0"}, 15 | "tex.stackexchange.com": {"fg": "c14748", "bg": "fefef6", "primary": "c14748"}, 16 | "askubuntu.com": {"fg": "ffffff", "bg": "de4508", "primary": "de4508"}, 17 | "english.stackexchange.com": {"fg": "382f2a", "bg": "f4e3c8", "primary": "f4e3c8"}, 18 | "unix.stackexchange.com": {"fg": "ffffff", "bg": "293a5d", "primary": "293a5d"}, 19 | "cstheory.stackexchange.com": {"fg": "103f5f", "bg": "b8e3fe", "primary": "b8e3fe"}, 20 | "apple.stackexchange.com": {"fg": "333333", "bg": "dde9f4", "primary": "f1f2f3"}, 21 | "bicycles.stackexchange.com": {"fg": "ffffff", "bg": "0ba097", "primary": "0ba097"}, 22 | "electronics.stackexchange.com": {"fg": "e74c3c", "bg": "ffffff", "primary": "e74c3c"}, 23 | "android.stackexchange.com": {"fg": "ffffff", "bg": "1589e4", "primary": "1589e4"}, 24 | "physics.stackexchange.com": {"fg": "3d9d9e", "bg": "daede1", "primary": "3d9d9e"}, 25 | "scifi.stackexchange.com": {"fg": "74abb2", "bg": "000000", "primary": "000000"}, 26 | "music.stackexchange.com": {"fg": "141045", "bg": "3e9cd8", "primary": "3e9cd8"}, 27 | "christianity.stackexchange.com": {"fg": "0093b6", "bg": "fcf5e0", "primary": "0093b6"}, 28 | "workplace.stackexchange.com": {"fg": "2e4d64", "bg": "acdadd", "primary": "acdadd"}, 29 | "vegetarianism.stackexchange.com": {"fg": "ffffff", "bg": "3e9cd8", "primary": "3e9cd8"}, 30 | "quantumcomputing.stackexchange.com": {"fg": "ffffff", "bg": "213341", "primary": "213341"}, 31 | "money.stackexchange.com": {"fg": "3f6673", "bg": "e5efe1", "primary": "e5efe1"}, 32 | "wordpress.stackexchange.com": {"fg": "ffffff", "bg": "363c42", "primary": "363c42"}, 33 | "ux.stackexchange.com": {"fg": "ffffff", "bg": "23629f", "primary": "23629f"}, 34 | "rpg.stackexchange.com": {"fg": "ffffff", "bg": "613121", "primary": "613121"}, 35 | "softwareengineering.stackexchange.com": {"fg": "1b3e6c", "bg": "f8f8f8", "primary": "1b3e6c"}, 36 | "security.stackexchange.com": {"fg": "98dbe7", "bg": "112a3d", "primary": "112a3d"}, 37 | "graphicdesign.stackexchange.com": {"fg": "ea4a5a", "bg": "f4f4f4", "primary": "ea4a5a"}, 38 | "dba.stackexchange.com": {"fg": "2180a9", "bg": "f8f8f8", "primary": "2180a9"}, 39 | "codereview.stackexchange.com": {"fg": "485A62", "bg": "e9eff3", "primary": "485A62"}, 40 | "skeptics.stackexchange.com": {"fg": "222222", "bg": "fdfdf9", "primary": "33ace3"}, 41 | "sharepoint.stackexchange.com": {"fg": "ffffff", "bg": "1cb8d2", "primary": "3a3552"}, 42 | "judaism.stackexchange.com": {"fg": "663a2a", "bg": "fbefdc", "primary": "663a2a"}, 43 | "japanese.stackexchange.com": {"fg": "e16558", "bg": "f0f1f4", "primary": "e16558"}, 44 | "travel.stackexchange.com": {"fg": "ffffff", "bg": "18748a", "primary": "18748a"}, 45 | "crypto.stackexchange.com": {"fg": "ffffff", "bg": "1a2f4d", "primary": "1a2f4d"}, 46 | "dsp.stackexchange.com": {"fg": "2db9c5", "bg": "f4f4f4", "primary": "2db9c5"}, 47 | "academia.stackexchange.com": {"fg": "5b5b5b", "bg": "fbf8f3", "primary": "5b5b5b"}, 48 | "cs.stackexchange.com": {"fg": "ffffff", "bg": "42bbbc", "primary": "42bbbc"}, 49 | "chemistry.stackexchange.com": {"fg": "ffffff", "bg": "2c8559", "primary": "2c8559"}, 50 | "mathematica.stackexchange.com": {"fg": "3b3b3b", "bg": "fcfcfc", "primary": "d35036"}, 51 | "movies.stackexchange.com": {"fg": "000000", "bg": "ed2f0b", "primary": "ed2f0b"}, 52 | "biology.stackexchange.com": {"fg": "65a9a5", "bg": "eeeee0", "primary": "65a9a5"}, 53 | "raspberrypi.stackexchange.com": {"fg": "ffffff", "bg": "3ab37d", "primary": "e41f3f"}, 54 | "salesforge.stackexchange.com": {"fg": "ffffff", "bg": "01344e", "primary": "01344e"}, 55 | "patents.stackexchange.com": {"fg": "ffffff", "bg": "4ea6d8", "primary": "4ea6d8"}, 56 | "expressionengine.stackexchange.com": {"fg": "ffffff", "bg": "e74c3c", "primary": "e74c3c"}, 57 | "magento.stackexchange.com": {"fg": "ffffff", "bg": "fd7620", "primary": "fd7620"}, 58 | "ell.stackexchange.com": {"fg": "4b4f51", "bg": "d1e8e7", "primary": "f2f2e0"}, 59 | "networkengineering.stackexchange.com": {"fg": "ffffff", "bg": "464343", "primary": "464343"}, 60 | "puzzling.stackexchange.com": {"fg": "2d4254", "bg": "e5e5c5", "primary": "15b58a"}, 61 | "worldbuilding.stackexchange.com": {"fg": "385a5f", "bg": "f0c09e", "primary": "f0c09e"}, 62 | "emacs.stackexchange.com": {"fg": "5a85e6", "bg": "ebebeb", "primary": "5a85e6"}, 63 | "blender.stackexchange.com": {"fg": "ffffff", "bg": "0069ac", "primary": "f37929"}, 64 | "mathoverflow.net": {"fg": "ffffff", "bg": "777777", "primary": "777777"}, 65 | "aviation.stackexchange.com": {"fg": "f74f57", "bg": "daecec", "primary": "f74f57"}, 66 | "softwarerecs.stackexchange.com": {"fg": "ffffff", "bg": "134a5d", "primary": "134a5d"}, 67 | } 68 | -------------------------------------------------------------------------------- /markov.py: -------------------------------------------------------------------------------- 1 | import markovify 2 | from sacremoses import MosesDetokenizer, MosesTokenizer 3 | 4 | tokenizer = MosesTokenizer() 5 | detokenizer = MosesDetokenizer() 6 | 7 | 8 | class MarkovText(markovify.Text): 9 | def word_split(self, sentence): 10 | return tokenizer.tokenize(sentence) 11 | 12 | def word_join(self, words): 13 | return detokenizer.detokenize(words, return_str=True) 14 | 15 | 16 | class MarkovUserName(markovify.Text): 17 | def word_split(self, word): 18 | return list(word) 19 | 20 | def word_join(self, characters): 21 | return "".join(characters) 22 | -------------------------------------------------------------------------------- /models.py: -------------------------------------------------------------------------------- 1 | from peewee import * 2 | 3 | from basemodel import BaseModel 4 | 5 | 6 | class Site(BaseModel): 7 | shortname = CharField(unique=True, max_length=30) 8 | url = CharField() 9 | name = CharField() 10 | icon_url = CharField() 11 | last_download = DateTimeField(null=True) 12 | tag_background_color = CharField(max_length=7) 13 | tag_foreground_color = CharField(max_length=7) 14 | link_color = CharField(max_length=7) 15 | background_color = CharField(max_length=7, null=True) 16 | foreground_color = CharField(max_length=7, null=True) 17 | primary_color = CharField(max_length=7, null=True) 18 | enabled = BooleanField(default=True) 19 | 20 | 21 | class Alias(BaseModel): 22 | site = ForeignKeyField(Site) 23 | url = CharField(unique=True, max_length=50) 24 | 25 | 26 | class Title(BaseModel): 27 | text = CharField() 28 | slug = CharField() 29 | site = ForeignKeyField(Site) 30 | 31 | 32 | class User(BaseModel): 33 | username = CharField() 34 | site = ForeignKeyField(Site) 35 | 36 | 37 | class Question(BaseModel): 38 | text = TextField() 39 | upvotes = IntegerField(default=1) 40 | downvotes = IntegerField(default=1) 41 | title = ForeignKeyField(Title) 42 | user = ForeignKeyField(User) 43 | site = ForeignKeyField(Site) 44 | datetime = DateTimeField() 45 | random = IntegerField(null=True) 46 | 47 | 48 | class Answer(BaseModel): 49 | text = TextField() 50 | upvotes = IntegerField(default=1) 51 | downvotes = IntegerField(default=1) 52 | datetime = DateTimeField() 53 | question = ForeignKeyField(Question, null=True) 54 | user = ForeignKeyField(User) 55 | site = ForeignKeyField(Site) 56 | -------------------------------------------------------------------------------- /parsexml.py: -------------------------------------------------------------------------------- 1 | import jsonlines 2 | from lxml import etree 3 | 4 | from utils import * 5 | 6 | 7 | def parse_posts(inputdir, outputdir): 8 | i = 0 9 | skipped = 0 10 | iterator = etree.iterparse(inputdir + "/Posts.xml", events=("start", "end")) 11 | _, root = next(iterator) 12 | with jsonlines.open(outputdir + "/Questions.jsonl", mode="w") as questions, \ 13 | jsonlines.open(outputdir + "/Answers.jsonl", mode="w") as answers, \ 14 | jsonlines.open(outputdir + "/Titles.jsonl", "w") as titles: 15 | for event, element in iterator: 16 | title = element.get("Title") 17 | # if element.get("Score") and int(element.get("Score")) <= 10: 18 | # skipped += 1 19 | # element.clear() 20 | # continue 21 | if title: 22 | titles.write(title) 23 | body = element.get("Body") 24 | if body: 25 | text = html2text(body) 26 | if element.get("PostTypeId") == "1": 27 | questions.write(text) 28 | else: 29 | answers.write(text) 30 | element.clear() 31 | if i % 100 == 0: 32 | root.clear() 33 | print(i, skipped, i + skipped, end="\r") 34 | i += 1 35 | print_stats(i, skipped) 36 | 37 | 38 | def parse_comments(inputdir, outputdir): 39 | i = 0 40 | iterator = etree.iterparse(inputdir + "/Comments.xml", events=("start", "end")) 41 | _, root = next(iterator) 42 | with jsonlines.open(outputdir + "/Comments.jsonl", mode="w") as comments: 43 | for event, element in iterator: 44 | text = element.get("Text") 45 | if text: 46 | comments.write(text) 47 | element.clear() 48 | if i % 100 == 0: 49 | root.clear() 50 | print(i, end="\r") 51 | i += 1 52 | print_stats(i) 53 | 54 | 55 | def parse_usernames(inputdir, outputdir): 56 | i = 0 57 | iterator = etree.iterparse(inputdir + "/Users.xml", events=("start", "end")) 58 | _, root = next(iterator) 59 | with jsonlines.open(outputdir + "/Usernames.jsonl", mode="w") as usernames: 60 | for event, element in iterator: 61 | displayname = element.get("DisplayName") 62 | if displayname: 63 | usernames.write(displayname) 64 | element.clear() 65 | if i % 100 == 0: 66 | root.clear() 67 | print(i, end="\r") 68 | i += 1 69 | print_stats(i) 70 | 71 | 72 | if __name__ == "__main__": 73 | settings = get_settings(1) 74 | # parse_posts(settings) 75 | # parse_comments(settings) 76 | # parse_comments(settings) 77 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "stackdata" 3 | version = "0.1.0" 4 | description = "" 5 | authors = ["Lukas Winkler "] 6 | 7 | [tool.poetry.dependencies] 8 | python = "^3.11" 9 | Flask = "^3.0.0" 10 | Flask-Limiter = "^3.6.0" 11 | Flask-Session = "^0.8.0" 12 | gunicorn = "^22.0.0" 13 | libsass = "^0.23.0" 14 | Pillow = "^10.3.0" 15 | sentry-sdk = {extras = ["flask"], version = "^2.0.1"} 16 | peewee = "^3.13.1" 17 | markovify = "^0.9.0" 18 | PyMySQL = "^1.0.0" 19 | redis = "^5.0.0" 20 | setproctitle = "^1.2.1" 21 | setuptools = "^69.5.1" 22 | 23 | [tool.poetry.dev-dependencies] 24 | jsonlines = "^4.0.0" 25 | lxml = "^5.0.0" 26 | requests = "^2.22.0" 27 | internetarchive = "^4.0.0" 28 | python-slugify = "^8.0.0" 29 | beautifulsoup4 = "^4.8.1" 30 | 31 | [build-system] 32 | requires = ["poetry>=0.12"] 33 | build-backend = "poetry.masonry.api" 34 | -------------------------------------------------------------------------------- /server.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import subprocess 3 | import time 4 | from io import BytesIO 5 | from random import shuffle, randint 6 | 7 | import sass 8 | from PIL import ImageFont, Image, ImageDraw 9 | from flask import render_template, send_from_directory, abort, session, jsonify, make_response, redirect, url_for, \ 10 | request, send_file 11 | from flask_limiter import Limiter 12 | from flask_limiter.util import get_remote_address 13 | from flask_session import Session 14 | from playhouse.flask_utils import PaginatedQuery, get_object_or_404 15 | from playhouse.shortcuts import model_to_dict 16 | from sassutils.wsgi import SassMiddleware 17 | 18 | import config 19 | import utils 20 | from app import app 21 | from models import * 22 | 23 | app.jinja_env.globals.update(prettydate=utils.prettydate) 24 | app.jinja_env.globals.update(is_light_color=utils.is_light_color) 25 | 26 | SESSION_TYPE = config.session_type 27 | if config.session_type == "redis": 28 | SESSION_REDIS = config.redis_instance 29 | SESSION_COOKIE_SECURE = config.production 30 | SESSION_USE_SIGNER = True 31 | SESSION_KEY_PREFIX = "StackDataSessions:" 32 | app.config.from_object(__name__) 33 | app.secret_key = config.secret_key 34 | Session(app) 35 | 36 | limiter = Limiter( 37 | app=app, 38 | key_func=get_remote_address, 39 | headers_enabled=True 40 | ) 41 | 42 | question_count = utils.load_question_count() 43 | 44 | 45 | @app.context_processor 46 | def git_hash(): 47 | return dict(git_hash=subprocess.check_output(["git", "rev-parse", "--short", "HEAD"]).decode().strip()) 48 | 49 | 50 | @app.route("/") 51 | @app.route("/s/") 52 | def index(site=None): 53 | query = Question.select(Question, User, Site, Title, SQL(utils.rating_sql)).join(Site).switch(Question).join( 54 | User).switch( 55 | Question).join( 56 | Title) 57 | if site: 58 | query = query.where(Site.url == site) 59 | try: 60 | site_element = Site.select().where(Site.url == site).get() 61 | except DoesNotExist: 62 | abort(404) 63 | return 64 | else: 65 | site_element = utils.get_fallback_site() 66 | query = query.order_by(SQL("ci_lower_bound DESC, random")) 67 | # return jsonify(model_to_dict(query.get())) 68 | paginated_query = PaginatedQuery(query, paginate_by=10, check_bounds=True) 69 | pagearray = utils.create_pagination(paginated_query.get_page_count(), paginated_query.get_page()) 70 | return render_template( 71 | "list.html", 72 | pagearray=pagearray, 73 | num_pages=paginated_query.get_page_count(), 74 | page=paginated_query.get_page(), 75 | questions=paginated_query.get_object_list(), 76 | site=site_element, 77 | voted=session["voted"] if "voted" in session and not config.make_cacheable else None, 78 | infohidden="hide" in request.cookies 79 | ) 80 | 81 | 82 | @app.route("/q/") 83 | def question(slug): 84 | query = Question.select(Question, Title, User, Site) \ 85 | .join(Title).switch(Question) \ 86 | .join(User).switch(Question) \ 87 | .join(Site).where(Title.slug == slug) 88 | question = get_object_or_404(query) 89 | answers = Answer.select(Answer, User, SQL(utils.rating_sql)) \ 90 | .join(User).where(Answer.question == question) \ 91 | .order_by(SQL("ci_lower_bound DESC")) 92 | return render_template( 93 | "detail.html", 94 | question=question, 95 | answers=answers, 96 | voted=session["voted"] if "voted" in session and not config.make_cacheable else None, 97 | infohidden="hide" in request.cookies 98 | ) 99 | 100 | 101 | @app.route("/quiz/") 102 | def hello(): 103 | return redirect(url_for("quiz", difficulty="easy"), code=302) 104 | 105 | 106 | @app.route("/quiz/") 107 | def quiz(difficulty): 108 | if difficulty not in ["easy", "hard"]: 109 | return abort(404) 110 | time1 = time.time() 111 | while True: 112 | random = randint(0, question_count - 1) 113 | print(random) 114 | try: 115 | question = Question.select(Question, Title, User, Site) \ 116 | .join(Title).switch(Question) \ 117 | .join(User).switch(Question) \ 118 | .join(Site).where((Question.upvotes - Question.downvotes >= 0) & (Question.random == random)).get() 119 | except DoesNotExist: 120 | continue 121 | break 122 | 123 | if difficulty == "easy": 124 | sites = [question.site] 125 | query = Site.select().where((Site.last_download.is_null(False)) & (Site.id != question.site.id)) \ 126 | .order_by(SQL("RAND()")).limit(3) 127 | for site in query: 128 | sites.append(site) 129 | shuffle(sites) 130 | else: 131 | sites = None 132 | time2 = time.time() 133 | print("{} ms".format((time2 - time1) * 1000.0)) 134 | return render_template( 135 | "quiz.html", 136 | question=question, 137 | stats=session["quiz"][difficulty] if "quiz" in session else {"total": 0, "correct": 0}, 138 | difficulty=difficulty, 139 | choices=sites, 140 | infohidden="hide" in request.cookies 141 | ) 142 | 143 | 144 | @app.route("/api/quiz///", methods=["POST"]) 145 | def quiz_api(id, guess, difficulty): 146 | if difficulty not in ["easy", "hard"]: 147 | return abort(404) 148 | if "quiz" not in session: 149 | session["quiz"] = {"easy": {"total": 0, "correct": 0}, "hard": {"total": 0, "correct": 0}} 150 | session["quiz"][difficulty]["total"] += 1 151 | query = Question.select(Site).join(Site).where(Question.id == id).get() 152 | if guess == query.site.url: 153 | correct = True 154 | session["quiz"][difficulty]["correct"] += 1 155 | else: 156 | correct = False 157 | return jsonify({"site": model_to_dict(query)["site"], "correct": correct}) 158 | 159 | 160 | @app.route("/api/sites") 161 | def sites(): 162 | sites = Site.select().where(Site.last_download.is_null(False)) 163 | data = {} 164 | for site in sites: 165 | data[site.url] = (model_to_dict(site)) 166 | return jsonify(data) 167 | 168 | 169 | @app.route("/image") 170 | @app.route("/image/") 171 | @limiter.limit("10 per minute") 172 | def image(site_id=None): 173 | if site_id: 174 | query = Site.select().where((Site.last_download.is_null(False)) & (Site.id == site_id)) 175 | site = get_object_or_404(query) 176 | else: 177 | class DummySite(object): 178 | pass 179 | 180 | site = DummySite() 181 | site.foreground_color = "black" 182 | site.background_color = "white" 183 | # parameters 184 | text = "Stack Exchange\nSimulator" 185 | selected_font = "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf" 186 | font_size = 70 187 | W, H = (600, 600) 188 | # # get the size of the text 189 | img = Image.new("RGBA", (W, H), (site.background_color if site.background_color else "white")) 190 | font = ImageFont.truetype(selected_font, font_size) 191 | draw = ImageDraw.Draw(img) 192 | left, top, right, bottom = draw.multiline_textbbox((0, 0), text, font) 193 | w, h = right - left, bottom - top 194 | 195 | draw.multiline_text(((W - w) / 2, (H - h) / 2), text, 196 | font=font, align="center", 197 | fill=(site.foreground_color if site.foreground_color else "black")) 198 | 199 | byte_io = BytesIO() 200 | img.save(byte_io, "PNG", optimize=True) 201 | byte_io.seek(0) 202 | return send_file(byte_io, mimetype="image/png") 203 | 204 | 205 | @app.route("/api/vote///", methods=["POST"]) 206 | @limiter.limit("10 per minute") 207 | def vote(type, id, vote): 208 | abort(403) # remove voting completely to not change historical data anymore 209 | if "voted" not in session: 210 | session["voted"] = {} 211 | print(session["voted"]) 212 | if (type, id) in session["voted"]: 213 | abort(403) 214 | if type == "question": 215 | if vote == "up": 216 | query = Question.update(upvotes=Question.upvotes + 1).where(Question.id == id) 217 | elif vote == "down": 218 | query = Question.update(downvotes=Question.downvotes + 1).where(Question.id == id) 219 | else: 220 | return abort(404) 221 | elif type == "answer": 222 | if vote == "up": 223 | query = Answer.update(upvotes=Answer.upvotes + 1).where(Answer.id == id) 224 | elif vote == "down": 225 | query = Answer.update(downvotes=Answer.downvotes + 1).where(Answer.id == id) 226 | else: 227 | return abort(404) 228 | else: 229 | return abort(404) 230 | session["voted"][(type, id)] = vote == "up" 231 | query.execute() 232 | if type == "question": 233 | query = Question.select(Question.upvotes, Question.downvotes).where(Question.id == id).get() 234 | else: 235 | query = Answer.select(Answer.upvotes, Answer.downvotes).where(Answer.id == id).get() 236 | return jsonify({ 237 | "upvotes": query.upvotes, 238 | "downvotes": query.downvotes 239 | }) 240 | 241 | 242 | @app.errorhandler(429) 243 | def ratelimit_handler(e): 244 | return make_response(jsonify(error="ratelimit exceeded {}".format(e.description)), 429) 245 | 246 | 247 | @app.errorhandler(403) 248 | def ratelimit_handler(e): 249 | return make_response(jsonify(error="access denied"), 403) 250 | 251 | 252 | if __name__ == "__main__": 253 | import logging 254 | 255 | logger = logging.getLogger("peewee") 256 | logger.setLevel(logging.DEBUG) 257 | logger.addHandler(logging.StreamHandler()) 258 | 259 | 260 | @app.route("/static/js/") 261 | def send_js(path): 262 | return send_from_directory("web/static/js", path) 263 | 264 | 265 | app.debug = True 266 | app.wsgi_app = SassMiddleware(app.wsgi_app, manifests={ 267 | "web": ("static/sass", "static/css", "/static/css") 268 | }) 269 | app.run() 270 | 271 | else: 272 | css, sourcemap = sass.compile( 273 | filename="web/static/sass/style.scss", 274 | output_style="compressed", 275 | source_map_filename="web/static/css/style.css.map" 276 | ) 277 | with open("web/static/css/style.css", "w") as style_css: 278 | style_css.write(css) 279 | with open("web/static/css/style.css.map", "w") as style_css_map: 280 | style_css_map.write(sourcemap) 281 | -------------------------------------------------------------------------------- /shuffle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import utils 3 | from models import * 4 | from extra_data import site_colors 5 | 6 | query = Question.select().order_by(SQL("RAND()")) 7 | 8 | count = query.count() 9 | utils.save_question_count(count) 10 | i = 0 11 | for question in query: 12 | question.random = i 13 | i += 1 14 | if i % 50 == 0: 15 | print("{}/{}".format(i, count)) 16 | question.save() 17 | -------------------------------------------------------------------------------- /templates/base.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {% block title %}Stack Exchange Simulator{% endblock %} 6 | 7 | {% if config['DEBUG'] %} 8 | 9 | {% else %} 10 | 12 | {% endif %} 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | {% block extrameta %}{% endblock %} 22 | 23 | 42 | 43 | 44 | 45 | 46 | 47 |
48 | {% for message in get_flashed_messages() %} 49 |
{{ message }}
50 | {% endfor %} 51 | {% block body %}{% endblock %} 52 | 57 |
58 | 77 | 78 | 79 | 80 | 81 | 82 | -------------------------------------------------------------------------------- /templates/detail.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% from 'macros.html' import siteheader %} 3 | {% block title %} 4 | {{ question.title.text }} - Stack Exchange Simulator 5 | {% endblock %} 6 | {% block extrameta %} 7 | 9 | 10 | 11 | 13 | 14 | 15 | {% endblock %} 16 | {% block body %} 17 | {{ siteheader(question.site) }} 18 |

{{ question.title.text }}

19 | {% set vote=voted[("question", question.id)] %} 20 |
21 |
22 | 23 |
{{ question.upvotes - question.downvotes }}
24 | 25 |
26 |
27 | 28 | {% for paragraph in question.text.split("\n") %} 29 |

{{ paragraph }}

30 | {% endfor %} 31 | 38 |
39 |
40 |

{{ answers|length }} Answers

41 | {% for answer in answers %} 42 | {% set vote=voted[("answer", answer.id)] %} 43 |
44 |
45 | 46 |
{{ answer.upvotes - answer.downvotes }}
47 | 48 |
49 |
50 | {% for paragraph in answer.text.split("\n") %} 51 |

{{ paragraph }}

52 | {% endfor %} 53 | 60 |
61 |
62 | {% endfor %} 63 | {% endblock %} 64 | -------------------------------------------------------------------------------- /templates/list.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% from 'macros.html' import pagination, siteheader %} 3 | {% block extrameta %} 4 | 6 | 7 | 8 | 10 | {% if site.background_color %} 11 | 12 | {% endif %} 13 | {% endblock %} 14 | {% block body %} 15 | {{ siteheader(site) }} 16 | 17 |
19 | 22 | {% if not site.fallback %} 23 | Clear 24 | {% endif %} 25 |
26 |
28 | Easy Quiz 29 | Hard Quiz 30 |
31 | {{ pagination(pagearray, num_pages, page, site.url if not site.fallback else None, True) }} 32 | {% for question in questions %} 33 | {% set vote=voted[("question", question.id)] %} 34 |
36 |
37 | 38 |
{{ question.upvotes - question.downvotes }}
39 | 40 |
41 |
42 | 46 | {{ question.text|truncate(200, False, ' …', 10) }} 47 |
48 | 56 |
57 |
58 |
59 | {% endfor %} 60 | {{ pagination(pagearray, num_pages, page, site.url if not site.fallback else None, False) }} 61 | {% endblock %} 62 | -------------------------------------------------------------------------------- /templates/macros.html: -------------------------------------------------------------------------------- 1 | {% macro printpage(i,active, site) %} 2 | {# {{ i }}#} 3 | {{ i }} 5 | {% endmacro %} 6 | 7 | {% macro pagination(pagearray, num_pages, page, site, top) %} 8 | 9 | 44 | {%- endmacro %} 45 | 46 | {% macro siteheader(site) %} 47 | 57 | {% endmacro %} 58 | -------------------------------------------------------------------------------- /templates/quiz.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% block title %} 3 | Stack Exchange Simulator Quiz - {{ question.title.text }} 4 | {% endblock %} 5 | {% block extrameta %} 6 | 8 | 9 | 10 | 12 | {% endblock %} 13 | {% block extraclasses %}quiz{% endblock %} 14 | {% block body %} 15 | 16 |
17 |

Stack Exchange Simulator Quiz

18 |
19 | 20 | {% if stats.correct <3 %} 21 |
22 |

Tutorial:

23 |

Guess which of the Stack Exchange sites this question could belong to.

24 | {% if difficulty=="easy" %} 25 |

There are four possible answers below.

26 |

Press Next to get to the next Question.

27 |

28 | If you think this is too easy, you can try out 29 | the hard quiz 30 | which doesn't have possible answers. 31 |

32 | {% else %} 33 |

34 | Then enter your guess into the textbox below, select the website 35 | and click on check to confirm your guess. 36 |

37 |

Alternativly you can select a site with the arrow keys and press enter twice to confirm it.

38 |

39 | If you think this is too hard, you can try out 40 | the easy quiz 41 | which does have possible answers to choose from. 42 |

43 | {% endif %} 44 |
45 | {% endif %} 46 | 47 | {% if difficulty=="easy" %} 48 |
49 | {% for choice in choices %} 50 | 54 | {% endfor %} 55 |
56 | {% else %} 57 |
58 | 60 | 61 |
62 | {% endif %} 63 |
64 |
65 | Correct! 66 |
67 |
68 | Incorrect! 69 |
70 |
71 |
72 |
Total
{{ stats.total }}
73 |
Correct
{{ stats.correct }}
74 |
Ratio
{{ '%d' | format((stats.correct / stats.total * 100) if stats.correct > 0 else 0) }}% 75 |
76 | 77 |
78 | 79 | 82 | 83 | 84 |

{{ question.title.text }}

85 |
86 |
87 | 88 |
{{ question.upvotes - question.downvotes }}
89 | 90 |
91 |
92 | 93 | {% for paragraph in question.text.split("\n") %} 94 |

{{ paragraph }}

95 | {% endfor %} 96 | 103 |
104 |
105 | 106 | {% endblock %} 107 | -------------------------------------------------------------------------------- /text_generator.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | 4 | import jsonlines 5 | import markovify 6 | 7 | from markov import MarkovText, MarkovUserName 8 | from utils import * 9 | 10 | 11 | def get_markov(mode): 12 | if mode == "Usernames": 13 | return MarkovUserName 14 | else: 15 | return MarkovText 16 | 17 | 18 | def get_state_size(mode): 19 | return 1 if mode == "Titles" else 3 if mode == "Usernames" else 2 20 | 21 | 22 | def load_chain(chainfile, mode): 23 | markov = get_markov(mode) 24 | with open(chainfile, "r") as myfile: 25 | data = myfile.read() 26 | print("using existing file\n") 27 | return markov.from_json(data) 28 | 29 | 30 | def generate_chain(sourcedir, chainfile, mode): 31 | combined_cains = None 32 | chainlist = [] 33 | markov = get_markov(mode) 34 | i = 0 35 | with jsonlines.open(sourcedir + "/{type}.jsonl".format(type=mode), mode="r") as content: 36 | for text in content: 37 | text = text.strip() 38 | try: 39 | chain = markov(text, get_state_size(mode), retain_original=False) 40 | except KeyError: 41 | continue 42 | chainlist.append(chain) 43 | if i % 100 == 0: 44 | print(i, end="\r") 45 | if i % 10000 == 0: 46 | subtotal_chain = markovify.combine(chainlist) 47 | if not combined_cains: 48 | combined_cains = subtotal_chain 49 | else: 50 | combined_cains = markovify.combine(models=[combined_cains, subtotal_chain]) 51 | chainlist = [] 52 | i += 1 53 | subtotal_chain = markovify.combine(chainlist) 54 | chain = markovify.combine([combined_cains, subtotal_chain]) 55 | with open(chainfile, "w") as outfile: 56 | outfile.write(chain.to_json()) 57 | print_ram() 58 | return chain 59 | 60 | 61 | def get_chain(url, mode): 62 | sourcedir = "raw/{url}".format(url=url, type=mode) 63 | chainfile = "chains/{url}/{type}.chain.json".format(url=url, type=mode) 64 | if os.path.exists(chainfile): 65 | return load_chain(chainfile, mode) 66 | else: 67 | return generate_chain(sourcedir, chainfile, mode) 68 | 69 | 70 | def generate_text(chain: markovify.Text, model): 71 | if model == "Titles": 72 | return chain.make_short_sentence(70) 73 | if model == "Usernames": 74 | return chain.make_short_sentence(36) 75 | if model == "Questions" or "Answers": 76 | paragraphs = [] 77 | sentences = [] 78 | count = int((random.randint(2, 6) * random.randint(3, 6) / 5)) 79 | for _ in range(count): 80 | sentences.append(chain.make_sentence()) 81 | if random.random() < 0.4: 82 | paragraphs.append(sentences) 83 | sentences = [] 84 | paragraphs.append(sentences) 85 | return "\n".join([" ".join(paragraph) for paragraph in paragraphs]) 86 | return chain.make_sentence() 87 | 88 | 89 | if __name__ == "__main__": 90 | basedir, mode = get_settings(2) 91 | if mode not in ["Questions", "Answers", "Titles", "Usernames"]: 92 | print("error") 93 | exit() 94 | chain = get_chain("sites/astronomy.stackexchange.com", mode) 95 | for _ in range(10): 96 | # walk = [] 97 | # for text in chain.gen(): 98 | # if len(walk) > 100: 99 | # break 100 | # walk.append(text) 101 | # result = detokenizer.detokenize(walk, return_str=True) 102 | # print(result.replace("THISISANEWLINE ", "\n")) 103 | print(chain.make_sentence()) 104 | print("-----------------------------------") 105 | 106 | print_ram() 107 | -------------------------------------------------------------------------------- /todb.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import random 3 | from datetime import datetime 4 | 5 | import sys 6 | from slugify import slugify 7 | 8 | import utils 9 | from models import * 10 | from text_generator import get_chain, generate_text 11 | 12 | 13 | def get_unused_users(site, count): 14 | return User.select().join(Question, JOIN.LEFT_OUTER).switch(User).join(Answer, JOIN.LEFT_OUTER) \ 15 | .where((User.site == site) & (Question.id.is_null()) & (Answer.id.is_null())) 16 | 17 | 18 | def add_username(site, count=500): 19 | print("usernames") 20 | chain = get_chain(site.url, "Usernames") 21 | for _ in range(count): 22 | username = generate_text(chain, "Usernames") 23 | User.create(username=username, site=site) 24 | 25 | 26 | def add_title(site, count=100): 27 | print("titles") 28 | # TODO: Make sure that every slug is unique 29 | chain = get_chain(site.url, "Titles") 30 | for _ in range(count): 31 | title = generate_text(chain, "Titles") 32 | slug = slugify(title, max_length=70, word_boundary=True) 33 | Title.create(text=title, slug=slug, site=site) 34 | 35 | 36 | def add_answer(site, count=300): 37 | print("answers") 38 | users = get_unused_users(site, count) 39 | chain = get_chain(site.url, "Answers") 40 | 41 | for i in range(count): 42 | text = generate_text(chain, "Answers") 43 | user = users[i] 44 | time = datetime.now() 45 | Answer.create(text=text, user_id=user, site_id=site, datetime=time) 46 | 47 | 48 | def add_question(site, count=100): 49 | print("Questions") 50 | users = get_unused_users(site, count) 51 | titles = Title.select().join(Question, JOIN.LEFT_OUTER) \ 52 | .where((Title.site == site) & (Question.id.is_null())) \ 53 | .limit(count) 54 | chain = get_chain(site.url, "Questions") 55 | 56 | for i in range(count): 57 | text = generate_text(chain, "Questions") 58 | title = titles[i] 59 | user = users[i] 60 | time = datetime.now() 61 | question = Question.create(text=text, title_id=title, user_id=user, site_id=site, datetime=time) 62 | num_answers = random.randint(1, 4) 63 | answers = Answer.select().where((Answer.site == site) & (Answer.question.is_null())).limit(num_answers) 64 | for answer in answers: 65 | answer.question = question 66 | answer.save() 67 | 68 | 69 | if __name__ == "__main__": 70 | if len(sys.argv) > 1: 71 | sites = sys.argv[1:] 72 | query = Site.select().where((Site.last_download.is_null(False)) & (Site.url.in_(sites))) 73 | else: 74 | query = Site.select().join(Question, JOIN.LEFT_OUTER).where( 75 | (Question.id.is_null()) & (Site.last_download.is_null(False))).limit(10) 76 | print([i.name for i in query]) 77 | for s in query: 78 | print(s.name) 79 | add_username(s) 80 | add_title(s) 81 | add_answer(s) 82 | add_question(s) 83 | -------------------------------------------------------------------------------- /updater.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from internetarchive import get_item, download 3 | 4 | from models import * 5 | from utils import * 6 | 7 | ignored_se_sites = ["cs50.stackexchange.com"] 8 | 9 | files = get_files() 10 | for site in Site.select()[1:]: 11 | if site.url in ignored_se_sites: 12 | continue 13 | key = site.url + ".7z" 14 | offset = 0 15 | while True: 16 | if key in files: 17 | file = files[key] 18 | break 19 | query = Alias.select(Alias.url).where(Alias.site == site).limit(1).offset(offset) 20 | if len(query) == 0: 21 | print("{site} ({url}) doesn't have a dump".format(site=site.name, url=site.url)) 22 | file = {} 23 | break 24 | key = query[0].url + ".7z" 25 | offset += 1 26 | if file: 27 | sizeMB = int(file["size"]) / 1024 / 1024 28 | if sizeMB < 50: 29 | print(file) 30 | print(sizeMB) 31 | exit() 32 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import random 3 | import resource 4 | import string 5 | import sys 6 | from datetime import datetime 7 | 8 | from bs4 import BeautifulSoup 9 | from internetarchive import get_item 10 | 11 | 12 | def print_stats(i, skipped=None): 13 | print("{number} total entries".format(number=i)) 14 | if skipped: 15 | print("{number} skipped".format(number=skipped)) 16 | print_ram() 17 | 18 | 19 | def print_ram(): 20 | print("used {mb}MB".format(mb=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss // 1024)) 21 | 22 | 23 | def html2text(body): 24 | soup = BeautifulSoup(body, "lxml") 25 | for code in soup.find_all("code"): 26 | code.decompose() 27 | return str(soup.get_text()) 28 | 29 | 30 | def get_files(): 31 | ia = get_item("stackexchange") 32 | return {x["name"]: x for x in ia.files} 33 | 34 | 35 | def file_hash(filename): 36 | """from https://stackoverflow.com/a/44873382/4398037""" 37 | h = hashlib.sha1() 38 | with open(filename, "rb", buffering=0) as f: 39 | for b in iter(lambda: f.read(128 * 1024), b""): 40 | h.update(b) 41 | return h.hexdigest() 42 | 43 | 44 | def get_settings(count): 45 | if len(sys.argv) != count + 1: 46 | if count == 1: 47 | return "sites/workplace" 48 | elif count == 2: 49 | return "sites/workplace", "Title" 50 | 51 | print("Please specify {x} parameters".format(x=count)) 52 | if count == 1: 53 | return sys.argv[1] 54 | elif count == 2: 55 | return sys.argv[1], sys.argv[2] 56 | 57 | 58 | def get_random_string(length): 59 | return "".join(random.choices(string.ascii_uppercase + string.digits, k=length)) 60 | 61 | 62 | def prettydate(d): 63 | diff = datetime.now() - d 64 | s = diff.seconds 65 | if diff.days > 7 or diff.days < 0: 66 | return d.strftime("%d %b %y") 67 | elif diff.days == 1: 68 | return "1 day ago" 69 | elif diff.days > 1: 70 | return "{} days ago".format(diff.days) 71 | elif s <= 1: 72 | return "just now" 73 | elif s < 60: 74 | return "{} seconds ago".format(s) 75 | elif s < 120: 76 | return "1 minute ago" 77 | elif s < 3600: 78 | return "{} minutes ago".format(int(s / 60)) 79 | elif s < 7200: 80 | return "1 hour ago" 81 | else: 82 | return "{} hours ago".format(int(s / 3600)) 83 | 84 | 85 | def create_pagination(num_pages, page, padding=2): 86 | pages = ["1"] 87 | i = 2 88 | while i <= num_pages: 89 | if i < (page - padding - 1): 90 | pages.append("d") 91 | i = page - padding 92 | elif (i > (page + padding)) and (num_pages > (page + padding + 2)): 93 | pages.append("d") 94 | i = num_pages 95 | pages.append(str(i)) 96 | i += 1 97 | return pages 98 | 99 | 100 | def rand(): 101 | return random.randint(-2 ** 31, 2 ** 31 - 1) 102 | 103 | 104 | rating_sql = """ 105 | ((upvotes + 1.9208) / (upvotes + downvotes) - 106 | 1.96 * SQRT((upvotes * downvotes) / (upvotes + downvotes) + 0.9604) / 107 | (upvotes + downvotes)) / (1 + 3.8416 / (upvotes + downvotes)) 108 | AS ci_lower_bound 109 | """ 110 | 111 | 112 | def get_fallback_site(): 113 | return { 114 | "id": None, 115 | "name": "Stack Exchange", 116 | "url": "stackexchange.com/", 117 | "icon_url": "https://cdn.sstatic.net/Sites/stackexchange/img/apple-touch-icon.png", 118 | "fallback": True, 119 | "background_color": False, 120 | "foreground_color": False, 121 | "primary_color": False 122 | } 123 | 124 | 125 | def hex_to_rgb(hex): 126 | """ https://stackoverflow.com/a/29643643 """ 127 | return tuple(int(hex[i:i + 2], 16) for i in (0, 2, 4)) 128 | 129 | 130 | def is_light_color(hex): 131 | """ https://stackoverflow.com/a/596241 """ 132 | r, g, b = hex_to_rgb(hex[1:]) 133 | brightness = 0.2126 * r + 0.7152 * g + 0.0722 * b 134 | return brightness > 245 135 | 136 | 137 | def save_question_count(count): 138 | with open("count.txt", "w") as f: 139 | f.write(str(count)) 140 | 141 | 142 | def load_question_count(): 143 | with open("count.txt", "r") as f: 144 | return int(f.readline()) 145 | -------------------------------------------------------------------------------- /web/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Findus23/se-simulator/61359887b56712b41066afd16e3787f564590567/web/__init__.py -------------------------------------------------------------------------------- /web/static/js/app.js: -------------------------------------------------------------------------------- 1 | document.addEventListener("DOMContentLoaded", function (event) { 2 | var vote = document.getElementsByClassName("vote"); 3 | Array.prototype.forEach.call(vote, function (elvote) { 4 | var id = elvote.dataset.id; 5 | var type = elvote.dataset.type; 6 | Array.prototype.forEach.call(elvote.querySelectorAll("a"), function (el) { 7 | el.addEventListener("click", function (event) { 8 | var vote = el.classList[0]; 9 | var request = new XMLHttpRequest(); 10 | request.open("POST", "/api/vote/" + type + "/" + id + "/" + vote, true); 11 | 12 | request.onload = function () { 13 | if (this.status >= 200 && this.status < 400) { 14 | var resp = JSON.parse(this.response); 15 | el.classList.add("active"); 16 | elvote.querySelector("div").textContent = resp.upvotes - resp.downvotes 17 | } else { 18 | // We reached our target server, but it returned an error 19 | 20 | } 21 | }; 22 | request.onerror = function () { 23 | // There was a connection error of some sort 24 | }; 25 | request.send(); 26 | }) 27 | }); 28 | }); 29 | var input = document.getElementById("siteselector"); 30 | var check = document.getElementById("check"); 31 | var header = document.getElementsByClassName("siteheader")[0]; 32 | var next = document.getElementById("next"); 33 | var choices = document.getElementById("quizchoices"); 34 | var info = document.getElementById("infowrapper"); 35 | var close = document.getElementById("closeinfo"); 36 | var selectedSite, headerimg, headertitle, entered; 37 | 38 | function toast(type, message) { 39 | console.warn(type, message) 40 | } 41 | 42 | function setHeader(site, sure) { 43 | while (header.firstChild) { 44 | header.removeChild(header.firstChild); 45 | } 46 | headerimg = new Image(30, 30); 47 | headerimg.src = site.icon_url; 48 | headertitle = document.createElement('span'); 49 | headertitle.innerText = site.name + (sure ? "" : "?"); 50 | header.appendChild(headerimg); 51 | header.appendChild(headertitle); 52 | } 53 | 54 | function checkQuiz(selection, id) { 55 | console.info(selection, id); 56 | if (input) { 57 | input.disabled = true; 58 | check.disabled = true; 59 | } else { 60 | [].forEach.call(choices.children, function (child) { 61 | if (selection.url === child.dataset.url) { 62 | child.classList.add("selection") 63 | } 64 | child.disabled = true; 65 | }); 66 | } 67 | var request = new XMLHttpRequest(); 68 | request.open("POST", "/api/quiz/" + id + "/" + selection.url + "/" + (input ? "hard" : "easy"), true); 69 | 70 | request.onload = function () { 71 | if (this.status >= 200 && this.status < 400) { 72 | var resp = JSON.parse(this.response); 73 | console.log(resp.correct); 74 | setHeader(resp.site, true); 75 | // headertitle.innerText = resp.site.name; 76 | // headerimg.src = resp.site.icon_url; 77 | header.style.backgroundColor = resp.site.background_color; 78 | header.style.color = resp.site.foreground_color; 79 | var result = document.getElementById(resp.correct ? "correct" : "incorrect"); 80 | result.style.display = "block"; 81 | next.focus() 82 | } else { 83 | // We reached our target server, but it returned an error 84 | 85 | } 86 | }; 87 | request.onerror = function () { 88 | // There was a connection error of some sort 89 | }; 90 | request.send(); 91 | 92 | } 93 | 94 | if (input) { 95 | var mode = input.dataset.mode; 96 | var request = new XMLHttpRequest(); 97 | request.open("GET", "/api/sites", true); 98 | 99 | request.onload = function () { 100 | if (this.status >= 200 && this.status < 400) { 101 | var resp = JSON.parse(this.response); 102 | var list = []; 103 | for (var key in resp) { 104 | if (resp.hasOwnProperty(key)) { 105 | var site, shortname; 106 | site = resp[key]; 107 | shortname = site.url.replace(".stackexchange.com", ".SE"); 108 | list.push({ 109 | label: site.name + " (" + shortname + ")", 110 | value: site.url 111 | }); 112 | } 113 | } 114 | new Awesomplete(input, { 115 | list: list, 116 | minChars: 0, 117 | autoFirst: true 118 | }); 119 | if (mode === "quiz") { 120 | console.log(input); 121 | input.focus() 122 | } 123 | input.addEventListener("awesomplete-select", function (event) { 124 | if (!(event.text.value in resp)) { // shouldn't happen 125 | return false 126 | } 127 | selectedSite = resp[event.text.value]; 128 | 129 | if (mode === "filter") { 130 | window.location.href = "/s/" + selectedSite.url 131 | } else if (mode === "quiz") { 132 | input.focus(); 133 | 134 | entered = true; 135 | console.log(selectedSite); 136 | check.style.backgroundColor = selectedSite.background_color; 137 | header.style.backgroundColor = selectedSite.background_color; 138 | check.style.color = selectedSite.foreground_color; 139 | header.style.color = selectedSite.foreground_color; 140 | setHeader(selectedSite, false) 141 | } 142 | }); 143 | } else { 144 | // We reached our target server, but it returned an error 145 | 146 | } 147 | }; 148 | request.onerror = function () { 149 | // There was a connection error of some sort 150 | }; 151 | request.send(); 152 | if (mode === "quiz") { 153 | 154 | var handler = function (event) { 155 | // event.preventDefault(); 156 | if (event.keyCode === 13 && entered) { 157 | checkQuiz(selectedSite, input.dataset.id); 158 | input.removeEventListener("keydown", handler, false) 159 | } 160 | }; 161 | input.addEventListener("keydown", handler); 162 | input.addEventListener("input", function () { 163 | entered = false 164 | }); 165 | check.addEventListener("click", function () { 166 | if (entered) { 167 | checkQuiz(selectedSite, input.dataset.id, true); 168 | 169 | } else { 170 | toast("warning", "please select a site") 171 | } 172 | }); 173 | } 174 | 175 | } else if (choices) { 176 | console.info("TEST"); 177 | choices.addEventListener('click', function (e) { 178 | if (e.target.tagName === "BUTTON") { 179 | var data = e.target.dataset; 180 | checkQuiz({url: data.url}, choices.dataset.id); 181 | } 182 | }) 183 | } 184 | if (next) { 185 | next.addEventListener("click", function () { 186 | window.location.reload(false); 187 | }); 188 | next.addEventListener("click", function (event) { 189 | if (event.keyCode === 13) { 190 | window.location.reload(false); 191 | } 192 | }); 193 | } 194 | close.addEventListener("click", function (ev) { 195 | info.style.display = "none"; 196 | document.cookie = "hide = 1;secure"; 197 | }); 198 | document.getElementById("showdisclaimer").addEventListener("click", function (ev) { 199 | info.style.display = "block" 200 | }) 201 | }); 202 | -------------------------------------------------------------------------------- /web/static/js/awesomplete.min.js: -------------------------------------------------------------------------------- 1 | // Awesomplete - Lea Verou - MIT license 2 | !function(){function t(t){var e=Array.isArray(t)?{label:t[0],value:t[1]}:"object"==typeof t&&"label"in t&&"value"in t?t:{label:t,value:t};this.label=e.label||e.value,this.value=e.value}function e(t,e,i){for(var n in e){var s=e[n],r=t.input.getAttribute("data-"+n.toLowerCase());"number"==typeof s?t[n]=parseInt(r):!1===s?t[n]=null!==r:s instanceof Function?t[n]=null:t[n]=r,t[n]||0===t[n]||(t[n]=n in i?i[n]:s)}}function i(t,e){return"string"==typeof t?(e||document).querySelector(t):t||null}function n(t,e){return o.call((e||document).querySelectorAll(t))}function s(){n("input.awesomplete").forEach(function(t){new r(t)})}var r=function(t,n){var s=this;r.count=(r.count||0)+1,this.count=r.count,this.isOpened=!1,this.input=i(t),this.input.setAttribute("autocomplete","off"),this.input.setAttribute("aria-expanded","false"),this.input.setAttribute("aria-owns","awesomplete_list_"+this.count),this.input.setAttribute("role","combobox"),this.options=n=n||{},e(this,{minChars:2,maxItems:10,autoFirst:!1,data:r.DATA,filter:r.FILTER_CONTAINS,sort:!1!==n.sort&&r.SORT_BYLENGTH,container:r.CONTAINER,item:r.ITEM,replace:r.REPLACE,tabSelect:!1},n),this.index=-1,this.container=this.container(t),this.ul=i.create("ul",{hidden:"hidden",role:"listbox",id:"awesomplete_list_"+this.count,inside:this.container}),this.status=i.create("span",{className:"visually-hidden",role:"status","aria-live":"assertive","aria-atomic":!0,inside:this.container,textContent:0!=this.minChars?"Type "+this.minChars+" or more characters for results.":"Begin typing for results."}),this._events={input:{input:this.evaluate.bind(this),blur:this.close.bind(this,{reason:"blur"}),keydown:function(t){var e=t.keyCode;s.opened&&(13===e&&s.selected?(t.preventDefault(),s.select()):9===e&&s.selected&&s.tabSelect?s.select():27===e?s.close({reason:"esc"}):38!==e&&40!==e||(t.preventDefault(),s[38===e?"previous":"next"]()))}},form:{submit:this.close.bind(this,{reason:"submit"})},ul:{mousedown:function(t){t.preventDefault()},click:function(t){var e=t.target;if(e!==this){for(;e&&!/li/i.test(e.nodeName);)e=e.parentNode;e&&0===t.button&&(t.preventDefault(),s.select(e,t.target))}}}},i.bind(this.input,this._events.input),i.bind(this.input.form,this._events.form),i.bind(this.ul,this._events.ul),this.input.hasAttribute("list")?(this.list="#"+this.input.getAttribute("list"),this.input.removeAttribute("list")):this.list=this.input.getAttribute("data-list")||n.list||[],r.all.push(this)};r.prototype={set list(t){if(Array.isArray(t))this._list=t;else if("string"==typeof t&&t.indexOf(",")>-1)this._list=t.split(/\s*,\s*/);else if((t=i(t))&&t.children){var e=[];o.apply(t.children).forEach(function(t){if(!t.disabled){var i=t.textContent.trim(),n=t.value||i,s=t.label||i;""!==n&&e.push({label:s,value:n})}}),this._list=e}document.activeElement===this.input&&this.evaluate()},get selected(){return this.index>-1},get opened(){return this.isOpened},close:function(t){this.opened&&(this.input.setAttribute("aria-expanded","false"),this.ul.setAttribute("hidden",""),this.isOpened=!1,this.index=-1,this.status.setAttribute("hidden",""),i.fire(this.input,"awesomplete-close",t||{}))},open:function(){this.input.setAttribute("aria-expanded","true"),this.ul.removeAttribute("hidden"),this.isOpened=!0,this.status.removeAttribute("hidden"),this.autoFirst&&-1===this.index&&this.goto(0),i.fire(this.input,"awesomplete-open")},destroy:function(){if(i.unbind(this.input,this._events.input),i.unbind(this.input.form,this._events.form),!this.options.container){var t=this.container.parentNode;t.insertBefore(this.input,this.container),t.removeChild(this.container)}this.input.removeAttribute("autocomplete"),this.input.removeAttribute("aria-autocomplete");var e=r.all.indexOf(this);-1!==e&&r.all.splice(e,1)},next:function(){var t=this.ul.children.length;this.goto(this.index-1&&e.length>0&&(e[t].setAttribute("aria-selected","true"),this.status.textContent=e[t].textContent+", list item "+(t+1)+" of "+e.length,this.input.setAttribute("aria-activedescendant",this.ul.id+"_item_"+this.index),this.ul.scrollTop=e[t].offsetTop-this.ul.clientHeight+e[t].clientHeight,i.fire(this.input,"awesomplete-highlight",{text:this.suggestions[this.index]}))},select:function(t,e){if(t?this.index=i.siblingIndex(t):t=this.ul.children[this.index],t){var n=this.suggestions[this.index];i.fire(this.input,"awesomplete-select",{text:n,origin:e||t})&&(this.replace(n),this.close({reason:"select"}),i.fire(this.input,"awesomplete-selectcomplete",{text:n}))}},evaluate:function(){var e=this,i=this.input.value;i.length>=this.minChars&&this._list&&this._list.length>0?(this.index=-1,this.ul.innerHTML="",this.suggestions=this._list.map(function(n){return new t(e.data(n,i))}).filter(function(t){return e.filter(t,i)}),!1!==this.sort&&(this.suggestions=this.suggestions.sort(this.sort)),this.suggestions=this.suggestions.slice(0,this.maxItems),this.suggestions.forEach(function(t,n){e.ul.appendChild(e.item(t,i,n))}),0===this.ul.children.length?(this.status.textContent="No results found",this.close({reason:"nomatches"})):(this.open(),this.status.textContent=this.ul.children.length+" results found")):(this.close({reason:"nomatches"}),this.status.textContent="No results found")}},r.all=[],r.FILTER_CONTAINS=function(t,e){return RegExp(i.regExpEscape(e.trim()),"i").test(t)},r.FILTER_STARTSWITH=function(t,e){return RegExp("^"+i.regExpEscape(e.trim()),"i").test(t)},r.SORT_BYLENGTH=function(t,e){return t.length!==e.length?t.length-e.length:t$&"),role:"option","aria-selected":"false",id:"awesomplete_list_"+this.count+"_item_"+n})},r.REPLACE=function(t){this.input.value=t.value},r.DATA=function(t){return t},Object.defineProperty(t.prototype=Object.create(String.prototype),"length",{get:function(){return this.label.length}}),t.prototype.toString=t.prototype.valueOf=function(){return""+this.label};var o=Array.prototype.slice;i.create=function(t,e){var n=document.createElement(t);for(var s in e){var r=e[s];if("inside"===s)i(r).appendChild(n);else if("around"===s){var o=i(r);o.parentNode.insertBefore(n,o),n.appendChild(o),null!=o.getAttribute("autofocus")&&o.focus()}else s in n?n[s]=r:n.setAttribute(s,r)}return n},i.bind=function(t,e){if(t)for(var i in e){var n=e[i];i.split(/\s+/).forEach(function(e){t.addEventListener(e,n)})}},i.unbind=function(t,e){if(t)for(var i in e){var n=e[i];i.split(/\s+/).forEach(function(e){t.removeEventListener(e,n)})}},i.fire=function(t,e,i){var n=document.createEvent("HTMLEvents");n.initEvent(e,!0,!0);for(var s in i)n[s]=i[s];return t.dispatchEvent(n)},i.regExpEscape=function(t){return t.replace(/[-\\^$*+?.()|[\]{}]/g,"\\$&")},i.siblingIndex=function(t){for(var e=0;t=t.previousElementSibling;e++);return e},"undefined"!=typeof self&&(self.Awesomplete=r),"undefined"!=typeof Document&&("loading"!==document.readyState?s():document.addEventListener("DOMContentLoaded",s)),r.$=i,r.$$=n,"object"==typeof module&&module.exports&&(module.exports=r)}(); 3 | //# sourceMappingURL=awesomplete.min.js.map 4 | -------------------------------------------------------------------------------- /web/static/sass/_awesomplete.base.scss: -------------------------------------------------------------------------------- 1 | .awesomplete [hidden] { 2 | display: none; 3 | } 4 | 5 | .awesomplete .visually-hidden { 6 | position: absolute; 7 | clip: rect(0, 0, 0, 0); 8 | } 9 | 10 | .awesomplete { 11 | display: inline-block; 12 | position: relative; 13 | } 14 | 15 | .awesomplete > input { 16 | display: block; 17 | } 18 | 19 | .awesomplete > ul { 20 | position: absolute; 21 | left: 0; 22 | z-index: 1; 23 | min-width: 100%; 24 | box-sizing: border-box; 25 | list-style: none; 26 | padding: 0; 27 | margin: 0; 28 | background: #fff; 29 | } 30 | 31 | .awesomplete > ul:empty { 32 | display: none; 33 | } 34 | -------------------------------------------------------------------------------- /web/static/sass/_awesomplete.custom.scss: -------------------------------------------------------------------------------- 1 | // Based on https://github.com/LeaVerou/awesomplete/blob/gh-pages/awesomplete.theme.css 2 | // Copyright (c) 2015 Lea Verou 3 | // MIT License 4 | 5 | @import "awesomplete.base"; 6 | 7 | .awesomplete { 8 | background: inherit; 9 | > ul { 10 | padding: 1rem 1rem 0; 11 | margin: .2em 0 0; 12 | 13 | border: 1px solid rgba(0, 0, 0, .3); 14 | box-shadow: .05em .2em .6em rgba(0, 0, 0, .2); 15 | text-shadow: none; 16 | > li { 17 | position: relative; 18 | padding: .2em .5em; 19 | cursor: pointer; 20 | &:hover { 21 | background: hsl(200, 40%, 80%); 22 | color: black; 23 | mark { 24 | background: hsl(68, 100%, 41%); 25 | } 26 | } 27 | &[aria-selected="true"] { 28 | background: hsl(205, 40%, 40%); 29 | color: white; 30 | mark { 31 | background: hsl(86, 100%, 21%); 32 | color: inherit; 33 | } 34 | } 35 | } 36 | &:before { // pointer 37 | content: ""; 38 | position: absolute; 39 | top: -.43em; 40 | left: 1em; 41 | width: 0; 42 | height: 0; 43 | padding: .4em; 44 | background: inherit; 45 | border: inherit; 46 | border-right: 0; 47 | border-bottom: 0; 48 | -webkit-transform: rotate(45deg); 49 | transform: rotate(45deg); 50 | } 51 | } 52 | mark { 53 | background: hsl(65, 100%, 50%); 54 | } 55 | } 56 | 57 | -------------------------------------------------------------------------------- /web/static/sass/_pagination.scss: -------------------------------------------------------------------------------- 1 | .pagination { 2 | $color: #f69c55; 3 | &.top { 4 | } 5 | &.bottom { 6 | } 7 | margin: 20px 0; 8 | 9 | a { 10 | .mobile { 11 | display: none; 12 | } 13 | 14 | font-size: 16px; 15 | color: gray; 16 | display: inline-block; 17 | padding: 2px 10px; 18 | border: thin lightgray solid; 19 | margin: 0 2px; 20 | &.dots { 21 | border: none; 22 | padding: 0; 23 | } 24 | transition: color .3s, background-color .3s; 25 | 26 | svg { 27 | transition: fill .3s; 28 | height: 18px; 29 | vertical-align: middle; 30 | fill: gray; 31 | } 32 | 33 | @include desktop-only { 34 | &:hover:not(.disabled), &.active { 35 | color: white; 36 | background-color: $color; 37 | svg { 38 | fill: white; 39 | } 40 | } 41 | } 42 | 43 | &.disabled { 44 | color: $lightTextGray; 45 | 46 | svg { 47 | fill: $lightTextGray; 48 | } 49 | } 50 | 51 | @include mobile-only { 52 | &.active::before { 53 | content: "page "; 54 | } 55 | 56 | &.other { 57 | display: none; 58 | } 59 | } 60 | } 61 | } 62 | 63 | -------------------------------------------------------------------------------- /web/static/sass/_variables.scss: -------------------------------------------------------------------------------- 1 | $link-color: #07C; 2 | $link-hover-color: #3af; 3 | $mobile-break-point: 500px; 4 | $stackexchange-blue: #ebf2f5; 5 | -------------------------------------------------------------------------------- /web/static/sass/style.scss: -------------------------------------------------------------------------------- 1 | @import "variables"; 2 | 3 | @mixin mobile-only() { 4 | @media (max-width: $mobile-break-point) { 5 | @content ; 6 | } 7 | } 8 | 9 | @mixin desktop-only() { 10 | @media (min-width: $mobile-break-point) { 11 | @content ; 12 | } 13 | } 14 | 15 | @import "../../milligram/src/milligram"; 16 | @import "awesomplete.custom"; 17 | @import "pagination"; 18 | 19 | body { 20 | font-size: 15px; 21 | color: #111; 22 | } 23 | 24 | .container { 25 | padding: 0 10px; 26 | } 27 | 28 | pre > code { 29 | white-space: pre-wrap; 30 | } 31 | 32 | .content { 33 | position: relative; 34 | 35 | display: flex; 36 | flex-direction: row; 37 | padding: 15px 5px 15px; 38 | &:not(.singlequestion) { 39 | border-bottom: solid lightgray 1px; 40 | } 41 | &.question:not(.singlequestion) { 42 | border-right: solid 10px lightgray; 43 | } 44 | .contentbox { 45 | margin-left: 10px; 46 | width: 100%; 47 | .sitename { 48 | color: grey; 49 | &:hover { 50 | text-decoration: underline; 51 | } 52 | } 53 | .rightwrapper { 54 | display: flex; 55 | flex-direction: row; 56 | justify-content: flex-end; 57 | @include mobile-only { 58 | justify-content: left; 59 | } 60 | .metadata { 61 | font-size: 12px; 62 | color: grey; 63 | text-align: right; 64 | } 65 | } 66 | .contentfooter { 67 | display: flex; 68 | justify-content: right; 69 | margin: 0; 70 | .authorbox { 71 | background: #E1ECF9; 72 | font-size: 12px; 73 | padding: 5px; 74 | color: #111; 75 | } 76 | 77 | } 78 | } 79 | .title { 80 | font-size: 20px; 81 | color: $link-color; 82 | &:hover { 83 | color: $link-hover-color; 84 | } 85 | } 86 | .vote { 87 | width: 30px; 88 | display: flex; 89 | flex-direction: column; 90 | div { 91 | text-align: center; 92 | margin: 10px 0; 93 | } 94 | a { 95 | font-size: 20px; 96 | width: 0; 97 | height: 0; 98 | border-style: solid; 99 | cursor: pointer; 100 | transition: border-color .3s; 101 | } 102 | .up { 103 | border-width: 0 15px 15px 15px; 104 | border-color: transparent transparent #858c93 transparent; 105 | &:hover, &:focus, &.active { 106 | border-color: transparent transparent darken(#858c93, 20%) transparent; 107 | } 108 | } 109 | .down { 110 | border-width: 15px 15px 0 15px; 111 | border-color: #858c93 transparent transparent transparent; 112 | &:hover, &:focus, &.active { 113 | border-color: darken(#858c93, 20%) transparent transparent transparent; 114 | } 115 | 116 | } 117 | } 118 | } 119 | 120 | h1, h2 { 121 | border-bottom: solid 1px lightgray; 122 | padding-bottom: 10px; 123 | margin-bottom: 0; 124 | margin-top: 10px; 125 | color: inherit; 126 | } 127 | 128 | h2 { 129 | font-size: 18px 130 | } 131 | 132 | .siteheader { 133 | background: $stackexchange-blue; 134 | transition: background-color .3s, color .3s; 135 | display: flex; 136 | height: 50px; 137 | align-items: center; 138 | padding: 0 10px; 139 | a { 140 | color: inherit; 141 | } 142 | .gotolink { 143 | margin-left: auto; 144 | } 145 | img { 146 | background: rgba(255, 255, 255, 0.5); 147 | padding: 5px; 148 | border-radius: 50%; 149 | margin-right: 10px; 150 | } 151 | } 152 | 153 | #quizselector { 154 | background-color: white; 155 | margin: 15px; 156 | display: flex; 157 | flex-direction: row; 158 | justify-content: center; 159 | > .awesomplete { 160 | margin-right: 5px; 161 | width: 70%; 162 | input { 163 | font-size: 20px; 164 | width: 100%; 165 | } 166 | } 167 | } 168 | 169 | #quizchoices { 170 | margin: 15px; 171 | 172 | display: flex; 173 | flex-direction: row; 174 | justify-content: space-between; 175 | flex-wrap: wrap; 176 | button.selection { 177 | opacity: 1; 178 | } 179 | } 180 | 181 | button { 182 | background-color: lightgray; 183 | color: #606c76; 184 | border: none; 185 | transition: opacity .3s; 186 | &:hover, &:focus { 187 | opacity: .6; 188 | background-color: lightgray; 189 | color: #606c76; 190 | } 191 | &:disabled { 192 | &:hover, &:active, &:focus { 193 | background-color: lightgray; 194 | color: #606c76; 195 | opacity: 0.5; 196 | } 197 | } 198 | } 199 | 200 | #next, #check { 201 | background-color: #f69c55; 202 | color: white; 203 | } 204 | 205 | #check { 206 | height: 32px; 207 | line-height: 32px; 208 | } 209 | 210 | #result { 211 | > div { 212 | width: 100%; 213 | padding: 20px 0; 214 | font-size: 25px; 215 | text-align: center; 216 | display: none; 217 | } 218 | } 219 | 220 | #correct { 221 | background-color: $success; 222 | } 223 | 224 | #incorrect { 225 | background-color: $warning; 226 | } 227 | 228 | #stats { 229 | display: flex; 230 | flex-direction: row; 231 | justify-content: space-around; 232 | text-align: center; 233 | padding: 20px 0; 234 | } 235 | 236 | footer { 237 | padding: 1rem 2rem; 238 | display: flex; 239 | flex-direction: row; 240 | justify-content: space-between; 241 | a { 242 | color: #111; 243 | 244 | } 245 | } 246 | 247 | :target { 248 | animation: target-fade 3s 1; 249 | } 250 | 251 | @keyframes target-fade { 252 | 0% { 253 | background-color: rgba(0, 0, 0, .1); 254 | } 255 | 100% { 256 | background-color: rgba(0, 0, 0, 0); 257 | } 258 | } 259 | 260 | #filterwrapper { 261 | background-color: $stackexchange-blue; 262 | display: flex; 263 | justify-content: center; 264 | input { 265 | color: currentColor; 266 | background: inherit; 267 | border-radius: 0; 268 | transition: all .3s; 269 | padding: 10px; 270 | &:hover, &:focus { 271 | background-color: white; 272 | color: #606c76; 273 | border-color: lightgray; 274 | } 275 | 276 | } 277 | .clear { 278 | @extend input; 279 | padding: 0 10px; 280 | display: flex; 281 | border: 0.1rem solid #d1d1d1; 282 | border-left: none; 283 | span { 284 | align-self: center; 285 | } 286 | } 287 | ::placeholder { 288 | color: #666 289 | } 290 | 291 | } 292 | 293 | #quizteaster { 294 | display: flex; 295 | background-color: $stackexchange-blue; 296 | a { 297 | border: 1px lightgray; 298 | border-top-style: solid; 299 | &:first-child { 300 | border-right-style: solid; 301 | } 302 | display: block; 303 | flex-basis: 50%; 304 | text-align: center; 305 | color: inherit; 306 | padding: 10px; 307 | transition: all .3s; 308 | &:hover, &:focus { 309 | background-color: white; 310 | color: #606c76; 311 | } 312 | } 313 | } 314 | 315 | html.quiz { 316 | min-height: 100vh; 317 | body { 318 | display: flex; 319 | align-items: center; 320 | justify-content: center; 321 | min-height: 100vh; 322 | } 323 | .container { 324 | } 325 | } 326 | 327 | .tutorial { 328 | margin: 10px 0; 329 | padding: 5px; 330 | border: solid 1px lightgray; 331 | border-right-width: 4px; 332 | background-color: #ffffe0; 333 | h3 { 334 | font-size: 20px 335 | } 336 | p { 337 | margin-bottom: 3px; 338 | } 339 | strong { 340 | font-weight: 700; 341 | } 342 | a { 343 | color: inherit; 344 | font-weight: 700; 345 | &:hover, &:focus, &:active { 346 | text-decoration: underline; 347 | } 348 | } 349 | } 350 | 351 | #infowrapper { 352 | position: fixed; 353 | bottom: 20px; 354 | right: auto; 355 | left: auto; 356 | width: 100%; 357 | padding: 0 10px; 358 | > div { 359 | position: relative; 360 | margin: 0 auto; 361 | max-width: 130.0rem; 362 | background: lightyellow; 363 | padding: 25px; 364 | box-shadow: 2px 2px 5px 0 rgba(50, 50, 50, 0.4); 365 | p:last-of-type { 366 | margin: 0; 367 | } 368 | .close { 369 | position: absolute; 370 | padding: 10px; 371 | top: 0; 372 | right: 0; 373 | font-size: 20px; 374 | cursor: pointer; 375 | } 376 | footer { 377 | padding: 1rem 0 0; 378 | } 379 | } 380 | } 381 | --------------------------------------------------------------------------------