language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
TypeScript | UTF-8 | 407 | 2.71875 | 3 | [] | no_license | export function getFileNameExtension(fileName: string): string | null {
const fileNameParts: string[] = fileName.split('.');
const fileExtension: string = fileNameParts[fileNameParts.length - 1];
return fileExtension || null;
}
export function getBase64ImageType(base64String: string): string | null {
return base64String.substring('data:image/'.length, base64String.indexOf(';base64')) || null;
}
|
Java | UTF-8 | 790 | 2.109375 | 2 | [] | no_license | package com.xlcxx.services;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
/**
* Description: nocos_test
* Created by yhsh on 2020/3/14 13:44
* version 2.0
* 方法说明
*/
@FeignClient(name = "royal-provider")
public interface ConsumerServices {
@GetMapping(value = "/echoProvideFegin/{str}")
String echo(@PathVariable("str") String str);
}
class FeignConfiguration {
@Bean
public EchoServiceFallback echoServiceFallback() {
return new EchoServiceFallback();
}
}
class EchoServiceFallback implements ConsumerServices {
public String echo(String str) {
return "服务熔断";
}
}
|
Python | UTF-8 | 421 | 2.515625 | 3 | [] | no_license | # Get audio files from midi
import pretty_midi
import scipy.io.wavfile
from glob import glob
inDir = '../Pipeline/MIDI/'
outDir = '../Pipeline/audio/'
def write_audio(mid):
midi = pretty_midi.PrettyMIDI(mid)
audio = midi.synthesize()
out_name = mid.split('/')[-1].replace('.mid','.wav')
scipy.io.wavfile.write(outDir+out_name, 44100, audio)
return
files = glob(inDir+'*')
for f in files:
print(f)
write_audio(f) |
Java | UTF-8 | 844 | 2.640625 | 3 | [] | no_license | import com.test.*;
import javafx.application.*;
import javafx.stage.Stage;
import java.util.List;
import java.util.ArrayList;
public class Main {
// @Override
// public void start(Stage primaryStage) {
// }
// public static void main() { launch(args); }
public static void main(String [] args) {
Progression progression = new Progression(1, 2.345);
for(int i = 0; i < 20; i++) {
progression.next();
}
System.out.println(progression.sum(21));
System.out.println(progression.sum());
System.out.println(Math.round(progression.sum()) == Math.round(progression.sum(21)));
try {
progression.throwException();
} catch (CustomException e) {
System.out.println(e.toString() + "\n" + e.getNumber());
}
}
} |
Python | UTF-8 | 423 | 3.25 | 3 | [] | no_license | class Solution(object):
def nextGreatestLetter(self, letters, target):
"""
:type letters: List[str]
:type target: str
:rtype: str
"""
tnum = ord(target) - 96
for l in letters:
if (ord(l)-96) > tnum:
return l
return letters[0]
#https://leetcode.com/problems/find-smallest-letter-greater-than-target/ |
Markdown | UTF-8 | 2,142 | 2.59375 | 3 | [] | no_license | # booking-tables
Aplicativo para realizar reservas de mesas em restaurantes. Primeiramente o usuário poderá ver o menu do restaurante, algumas reviews e um mapa geral do local disponibilizado pelo restaurante, com marcações para mesas e o usuário poderá visualizar as mesas disponíveis para reservas.
## Principais Classes
- FirebaseManager: lida com a comunicação com o FIrebase
- RestaurantModel, DishModel, RatingModel: modelos dos dados da aplicação. As três classes implementam a interface Parceable (funciona semelhante a uma serialização) e, para evitar o boilerplate dos métodos do Parceable, uma anotação @Parcelize deve ser adicionado à classe:
```kotlin
@Parcelize
data class DishModel(val name: String, val price: Double, val rating: Int) : Parcelable
```
- RestaurantModel: Contém nome, endereço, um array de RatingModel, um par de coordenadas (lat, long), um array de DishModel e um array de RatingModel
- DishModel: Contém nome, preço
- RatingModel: Contém comentário e o rating
- MapsActivity: Activity que implementa a API de mapas do Google. A partir dos restaurantes cadastrados o mesmo plota markers relativo ao lat, long de cada restaurante e, ao clicar em um marker, a Activity inicia uma intent para a RestaurantActivity e adiciona o restaurante referente àquela posição na intent (putExtra para cada parâmetro do restaurante ou um putExtra com o restaurante, passando o tipo Parceable)
-
## Helping
## TabLayout with RecyclerView
Library to add a TabLayout with RecyclerView. Useful when having
- Many tabs layout
- Infinite loop scrolling (imitated)
[RecyclerTabLayout](https://github.com/nshmura/RecyclerTabLayout)
### Running With Android Studio and Redmi devices
#### INSTALL_FAILED_USER_RESTRICTED error
If this error is occurring, do the following steps:
- *Settings -> Additional Settings -> Developer options*
- Turn off "MIUI optimization" and Restart
- Turn On "USB Debugging"
- Turn On "Install via USB"
[StackOverFlow Reference](https://stackoverflow.com/questions/47239251/install-failed-user-restricted-android-studio-using-redmi-4-device
)
|
PHP | WINDOWS-1252 | 8,870 | 2.703125 | 3 | [] | no_license | <ul>
<li><a href="<?php echo $article->url; ?>#intro">Introducción</a></li>
<li><a href="<?php echo $article->url; ?>#solucion">Solución</a></li>
<li><a href="<?php echo $article->url; ?>#notas">Notas finales</a></li>
<li><a href="<?php echo $article->url; ?>#enlaces">Enlaces</a></li>
</ul>
<a name="intro"></a>
<h2>Introducción</h2>
<p>Delegar es una cosa que mola. En la vida en general y en Flash en particular. Sobre todo cuando nos movemos de AS1 a AS2 + clases. Los foros de Flash están llenos de preguntas que tienen que ver con el "scope" o ámbito dentro de los famosos "callbacks" de objetos como XML, LoadVars, XMLSocket, etc. Flash necesita estas funciones porque las llamadas al servidor en Flash son asíncronas, es decir, el player no detiene la ejecución del código cuando se hace, por ejemplo, una petición de un fichero xml:</p>
<p class="asCode">class A{<br><br>
private var oneVar:String = "Hello world";<br><br>
function A():Void{<br><br>
var myXML:XML = new XML();<br>
myXML.ignoreWhite = true; // alguien ha encontrado esto en false????<br><br>
myXML.onLoad = function():Void{<br>
trace(oneVar); // undefined <br>
}<br><br>
myXML.load("myXML.xml");<br><br>
}<br><br>
}</p>
<p>Esto pasa porque el ámbito "dentro" del onLoad es el propio objeto myXML, NO la clase. Puedes hacer la prueba haciendo trace(this) dentro del onLoad.</p>
<p>Una de las primeras soluciones que se utilizó para esto fue crear dentro de la función principal una variable que hacía referencia a la propia clase. Algo como esto:</p>
<p class="asCode">class A{<br><br>
private var oneVar:String = "Hello world";<br><br>
function A():Void{<br><br>
var owner = this;<br>
var myXML:XML = new XML();<br>
myXML.ignoreWhite = true;<br><br>
myXML.onLoad = function():Void{<br>
trace(owner.oneVar); // yeah!<br>
}<br><br>
myXML.load("myXML.xml");<br><br>
}<br><br>
}</p>
<p>Y esto funciona. Este comportamiento "peculiar" de Flash (de los ECMAScript, vamos) se llama <strong>closure</strong>, algo de lo que yo me enteré en <a href="http://www.domestika.org/foros/viewtopic.php?t=47694">éste post de Domestika</a>. Más información en <a href="http://timotheegroleau.com/Flash/articles/scope_chain.htm">Scope Chain and Memory waste in Flash MX</a> y en la <a href="http://en.wikipedia.org/wiki/Closure_%28computer_science%29">Wikipedia</a> (para campeones).</p>
<p class="subir"><a href="<?php echo $article->url; ?>#inicio" title="Volver al comienzo del artículo">Subir</a></p>
<a name="solucion"></a>
<h2>Solución</h2>
<p>La misión era clara, buscar una forma más sencilla y elegante de resolver el problema del ámbito en las llamadas asíncronas. Pues a todo esto llegó la version 7.2 del Flash IDE y el señor Mike Chambers introdujo la clase Delegate. Utilizando esa clase dejaríamos el código anterior en algo como esto:</p>
<p class="asCode">import mx.utils.Delegate;<br><br>
class A{<br><br>
private var oneVar:String = "Hello world 2";<br><br>
function A(){<br><br>
var myXML:XML = new XML();<br>
myXML.ignoreWhite = true;<br>
myXML.onLoad = Delegate.create(this,xmlLoaded);<br>
myXML.load("myXML.xml");<br><br>
}<br><br>
private function xmlLoaded(success:Boolean):Void{<br>
trace(oneVar);<br>
}<br><br>
}</p>
<p>Estamos "delegando" el onLoad en la función xmlLoaded, pero, lo más importante, el ámbito de la función xmlLoaded es la clase original, por lo que "encontramos" la variable sin problemas. Ahora empezamos a molar.</p>
<p>Esto definitivamente NO es lo mismo que hacer: <span class="asCode">myXML.onLoad = xmlLoaded</span>. Si lo probáis, estaréis con el mismo problema que antes, el ámbito de la función xmlLoaded será el objeto myXML, por lo que el trace volverá a ser undefined.</p>
<p>El mayor problema de la clase de Macromedia (aún era Macromedia) es que NO permite el paso de parámetros a la función delegada, pero pronto llegaron los frikis para solucionarlo haciendo sus propias clases para delegar. <a href="Delegate.as">La que yo utilizo</a> es una copia con alguna modificación de una que encontré en la lista de <a href="http://lists.motion-twin.com/pipermail/mtasc/2005-April/001602.html">MTASC</a>. Con estas nuevas clases se pueden pasar parámetros de la siguiente forma:</p>
<p class="asCode">myXML.onLoad = Delegate.create(this,xmlLoaded,"val1",val2);</p>
<p><strong>OJO</strong>, nuestros parámetros llegarán despué de los "oficiales", en este caso el típico success que llega a los onLoad del objeto XML.</p>
<p>Como curiosidad apuntar que con las clases de Delegate se pueden hacer cosas como esta:</p>
<p class="asCode">import tv.zarate.Utils.Delegate;<br><br>
class A{<br><br>
function A(){<br><br>
// delegamos la funcion en una variable local<br><br>
var delegatedOne:Function = Delegate.create(this,getOneValue);<br>
// pasamos la funcion delegada como parametro<br><br>
doLater(delegatedOne);<br><br>
}<br><br>
private function doLater(delegated:Function):Void{<br><br>
// ejecutamos la funcion pero no devuelve nada<br>
trace("Pero no me devuelve nada? " + delegated());<br><br>
}<br><br>
private function getOneValue():String{<br><br>
trace("La funcion se ejecuta");<br>
return "I rock \m/";<br><br>
}<br><br>
}</p>
<p>Decidir si esta manera de trabajar es una <i>best practice</i> o no es cosa de cada uno. Hace poco me encontré con una aplicación MVC en la que el modelo le pasaba a la vista las funciones delegadas para los botones de la interface. A gusto del consumidor.</p>
<p class="subir"><a href="<?php echo $article->url; ?>#inicio" title="Volver al comienzo del artículo">Subir</a></p>
<a name="notas"></a>
<h2>Notas finales</h2>
<p>Lo gracioso de esto es que <i>dentro de poco</i> las clases de delegar no se van a utilizar porque en AS3 la delegación es automática (echad un ojo a <a href="http://www.adobe.com/devnet/actionscript/articles/actionscript3_overview.html">AS3 overview</a>, Method closures). Pero vamos, al ritmo que se va adoptando las nuevas versiones, yo creo que este artículo aún puede ser útil a mucha gente.</p>
<p>Pues esto es todo familia, <strong>HTH</strong>.</p>
<p class="subir"><a href="<?php echo $article->url; ?>#inicio" title="Volver al comienzo del artículo">Subir</a></p>
<a name="enlaces"></a>
<h2>Enlaces</h2>
<ul>
<li><a href="http://www.adobe.com/devnet/flash/articles/eventproxy.html">Proxying Events with the mx.utils.Delegate Class</a></li>
<li><a href="http://lists.motion-twin.com/pipermail/mtasc/2005-April/001602.html">Implementación original de Till Schneidereit sobre la que está hecha la clase que yo utilizo.</a></li>
<li><a href="http://www.domestika.org/foros/viewtopic.php?t=47694">Post sobre <i>closures</i> en Domestika en el que queda patente mi inculticia :P</a></li>
<li><a href="http://en.wikipedia.org/wiki/Closure_%28computer_science%29">Explicación en la Wikipedia sobre closures. Para muy gafotas.</a></li>
</ul>
<p class="subir"><a href="<?php echo $article->url; ?>#inicio" title="Volver al comienzo del artículo">Subir</a></p> |
Java | UTF-8 | 1,419 | 2.453125 | 2 | [] | no_license | package com.example.exchangetoysback.ExchangeToysBack.controller.DTOmodels;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class FilterDTO {
private String mainCategory;//null if any category
private String age;//null if each age
private String tags;//null if any category
private String anyKeyword;//null if doesn't matter
private Boolean isDidactic;//null if both
private Boolean isVintage;//null if both
private double latitude;
private double longitude;
private Integer radius;
public Integer getAge() {
if (age == null)
return null;
switch (age) {
case "0-3":
return 1;
case "4-7":
return 2;
case "8-12":
return 3;
case "13-15":
return 4;
case "16-100":
return 5;
}
return null;
}
public boolean isPseudoEmpty() {
return mainCategory == null && age == null && tags == null && radius == null
&& anyKeyword == null && isDidactic == null && isVintage == null;
}
public Integer isDidacticNumber() {
if (isDidactic == null) return null;
return isDidactic ? 1 : 0;
}
public Integer isVintageNumber() {
if (isVintage == null) return null;
return isVintage ? 1 : 0;
}
}
|
Markdown | UTF-8 | 4,015 | 3 | 3 | [] | no_license | <h1>Extend VdoCipher plugin</h1>
<p>Using this plugin you can extend the VdoCipher WordPress plugin. This plugin requires the VdoCipher WordPress plugin version 1.26 or more to be installed.</p>
<p>We have implemented the child theme - theme framework architecture, so that you can freely extend the VdoCipher plugin without having to worry about breaking changes when the main VdoCipher plugin updates.</p>
<p>In this plugin, we provide functions for two use cases:</p>
<ul>
<li>Adding Chapters links over the player, so that user can skip ahead to the relevant time in the video</li>
<li>Add custom watermark attributes</li>
</ul>
<p>These remain the most common requirements from our users. If you have any additional requirements you should be able to go through the functions given here and tweak them according to your requirement, or else contact our support team at VdoCipher.</p>
<h3>Hooks</h3>
<h4><code>vdocipher_customize_player</code></h4>
<p>All functions attached to this hook run at the very end of the vdocipher shortcode parsing.</p>
<h3>Filters</h3>
<h4><code>vdocipher_add_shortcode_attributes</code></h4>
<p>Using this filter you can add your own attributes to the shortcode</p>
<h4><code>vdocipher_annotate_preprocess</code></h4>
<p>Use this filter to display custom user information - before any processing by the vdocipher plugin itself</p>
<h4><code>vdocipher_annotate_postprocess</code></h4>
<p>Use this filter to display custom user information - after the vdocipher plugin has processed {name}, {email}, {username}, {id}, {ip}, and {date}</p>
<h4><code>vdocipher_modify_otp_request</code></h4>
<p>Use this to send additional OTP body specifications, as can be found in the <a href="https://dev.vdocipher.com/api/docs/book/playbackauth/reqbody.html" target="_blank">Server API docs</a></p>
<h2>Use Cases</h2>
<p>The following class should always be included:<code>classes/vdocipher-customize-essentials.php</code>. It enqueues the files <code>js/vdocipherapiready.js</code> and <code>styles/overlay.css</code>. You can add all custom css in the <code>overlay.css</code> file. Make sure that all css classes are preceded by <code>.vc-container</code> selector</p>
<h3>Add Chapters</h3>
<ol>
<li>Make sure that <code>classes/vdocipher-add-chapters.php</code> is included in the main plugin file</li>
<li>The function <code>new_vdo_shortcode_attribute</code> adds a new attribute to the vdocipher shortcode - <code>chapters</code>. This function is hooked to the filter <code>vdocipher_add_shortcode_attributes</code></li>
<li>The value given to the attribute is then processed in <code>insert_chapters</code> and <code>insert_chapters_with_names</code> function. <strong>Please use only one of these functions.</strong> All the functions are called by attaching them to VdoCipher hooks and filters, in the class constructor of <code>VdoCipherAddChapters</code> class. Uncomment the function that you would like to use. </li>
<li><code>insert_chapters</code> takes comma separated time values, and outputs list of chapters over the video, with chapters labelled as <em>Chapter 1</em>, <em>Chapter 2</em> and so on. The usage is
<pre>[vdo id="1234567890" chapters="500,700,1000"]</pre>
Each of the comma separated values is the duration in the video in seconds that clicking the button will seek to</li>
<li>In the <code>insert_chapters_with_names</code> function, the chapters attribute takes in chapter names and the time to seek as input. The format is
<pre>[vdo id="1234567890" chapters="Chapter 1, 500; Chapter 2, 700; Chapter 3, 1000"]</pre>
Chapter name and Chapter time in seconds are separated by comma, different chapter values are separated by semi-colons.
</li>
</ol>
<p><strong>Please use only one of these two functions</strong>. These functions <code>insert_chapters</code> and <code>insert_chapters_with_names</code> are presented here for completeness. If there is any code here that you do not require, you are free to remove it.</p>
|
Python | UTF-8 | 903 | 2.78125 | 3 | [
"MIT"
] | permissive | from .conv_to_str import conv_to_str
class WriteBase:
use_colons = False
def sort_key(self, i):
if isinstance(i, str):
return i.lower()
return i
def write_D(self, path, D):
with open(path, 'w', encoding='utf-8') as f:
for key, sub_D in list(D.items()):
if not isinstance(key, (list, tuple)):
key = [key]
if len(key)==1 and key[0].strip()==key[0]:
key = '[%s]' % key[0]
else:
key = repr([conv_to_str(i) for i in key])
if self.use_colons:
# Add a python-esque ":" after headings
key = '%s:' % key
f.write('%s\n' % key)
f.write('%s\n\n' % self.process_section(key, sub_D))
def process(self, section, D):
raise NotImplementedError
|
Java | UTF-8 | 1,018 | 2.15625 | 2 | [] | no_license | package com.driftdirect.service.round;
import com.driftdirect.service.gcm.GCMService;
import com.driftdirect.service.gcm.TopicBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
/**
* Created by Paul on 2/20/2016.
*/
@Service
public class RoundNotificationService {
private TopicBuilder topicBuilder;
private GCMService gcmService;
@Autowired
public RoundNotificationService(TopicBuilder topicBuilder, GCMService gcmService) {
this.topicBuilder = topicBuilder;
this.gcmService = gcmService;
}
public void notifyCurrentQualifierUpdated(Long roundId) throws IOException {
String topic = topicBuilder.buildQualificationsTopic(roundId);
gcmService.notifyTopic(topic);
}
public void notifyCurrentBattleUpdated(Long roundId) throws IOException {
String topic = topicBuilder.buildBattlesTopic(roundId);
gcmService.notifyTopic(topic);
}
}
|
Markdown | UTF-8 | 3,641 | 2.875 | 3 | [] | no_license | # Active Directory Bundle
- [Installation](#using-the-configuration)
- [Configuration](#configuration)
- [Definitions](#definitions)
- [Account Suffix (required)](#account-suffix-required)
- [Domain Controllers (required)](#domain-controllers-required)
- [Base Distinguished Name (required)](#base-distinguished-name-required)
Configuring Active Directory Bundle is really easy. Let's get started.
## Installation
Install using composer:
```bash
composer config repositories.repo-name vcs ssh://git@gitlab.com:22/xrow-shared/activedirectory-bundle.git
composer require xrow/activedirectory-bundle
```
Add to `$bundles` array in `app/AppKernel.php`:
```php
new Xrow\ActiveDirectoryBundle\XrowActiveDirectoryBundle(),
```
## Configuration
You can configure Active Directory Bundle by supplying an array of settings. Keep in mind not all of these are required. This will be discussed below.
Here is an example configuration (for example in `app/config.yml`) with all possible configuration options:
```yaml
xrow_active_directory:
account_suffix: xrow.lan
domain_controllers: [ "dc01.xrow.lan","192.168.0.220"]
base_dn: "dc=XROW,dc=LAN"
```
## Working with Active Directory user groups
Once the a new active directory did try to authenticate against ezplatform. All of the user groups are available from the cms backend. You can now assign (Admin Panel->Roles) the eZ Platform security policy Administrator to the Active Directory group Administrators (Admin Panel->Users->Administators). Beware the only difference between eZ Platform user groups and Active Directory user groups is a special remote_id that is not visible from the cms backend. Deleted Active Directory items will appear again once a user authenticates again with the platform.
## Definitions
### Account Suffix (required)
The account suffix option is the suffix of your user accounts in AD. For example, if your domain DN is `DC=corp,DC=acme,DC=org`,
then your account suffix would be `corp.acme.org`. This is then appended to the end of your user accounts on authentication.
For example, if you're binding as a user, and your username is `jdoe`, then Adldap would try to authenticate with
your server as `jdoe@corp.acme.org`.
### Domain Controllers (required)
The domain controllers option is an array of servers located on your network that serve Active Directory. You insert as many
servers or as few as you'd like depending on your forest (with the minimum of one of course).
For example, if the server name that hosts AD on my network is named `ACME-DC01`, then I would insert `['ACME-DC01.corp.acme.org']`
inside the domain controllers option array.
### Base Distinguished Name (required)
The base distinguished name is the base distinguished name you'd like to perform operations on. An example base DN would be `DC=corp,DC=acme,DC=org`.
If one is not defined, you will not retrieve any search results.
## Toubleshooting
### System report "Invalid directory user" during login
Certain Active Directory users might be not able to authenticate against the Active Directory Server. In those cases the message "Invalid directory user" will appear. This means that the user username@account.suffix with the given password can`t authenticate against teh server. Please consult the domain adminsitrator to help. You can replicate the issue using a LDAP browser like [LDAP Admin](http://www.ldapadmin.org).
### Need of adding a second Active Directory
In case you need to add a second active directory structure we recommend you to build a [forest](https://en.wikipedia.org/wiki/Active_Directory#Forests,_trees_and_domains).
|
JavaScript | UTF-8 | 3,840 | 3.390625 | 3 | [] | no_license | //if the quiz has ended then display score otherwise display question, display choices and display progress
var QuizUI = {
displayNext: function () {
if (quiz.hasEnded()) {
this.displayScore();
countDown();
} else {
this.displayQuestion();
this.displayChoices();
this.displayProgress();
this.progressBar();
this.showCurrentScore();
}
},
displayQuestion: function () {
// call insertTextInHTML method
this.insertTextInHTML('question', quiz.getCurrentQuestion().text);
},
displayChoices: function () {
//get the choices of current question
var choices = quiz.getCurrentQuestion().choices;
for (var i = 0; i < choices.length; i++) {
this.insertTextInHTML("guess" + i, choices[i]);
this.guessHandler("guess" + i, choices[i]);
document.getElementById("guess"+[i]).className="btn";
}
},
// display <h1>game Over</h1> , <h2>your score is: quiz.score</h2>
// call insertTextInHTML method. and pass "quiz and gameOverHTML";
displayScore: function () {
document.body.className = "black";
var gameOverHTML = '<h2 id="continue"><a class="animated infinite flash" href="index.html">Continue?</a></h2>';
gameOverHTML += '<h2 class="your-score">Yor Score is: ' + quiz.score + '</h2>';
this.insertTextInHTML('quiz', gameOverHTML);
var win = new Audio('./media/You Win Perfect.mp3');
var loose = new Audio('./media/You Loose.mp3');
if (quiz.score === 10) {
win.play();
var image = new Image;
image.src = "./img/winner.png";
document.body.appendChild(image);
document.getElementById('continue').className = "hidden";
} else {
loose.play();
//Add the video
function addSourceToVideo(element, src, type) {
var source = document.createElement('source');
source.src = src;
source.type = type;
element.appendChild(source);
}
var video = document.createElement('video');
document.body.appendChild(video);
addSourceToVideo(video, './media/looser.mp4', 'video/mp4');
video.play();
}
},
insertTextInHTML: function (id, text) {
var element = document.getElementById(id);
element.innerHTML = text;
},
guessHandler: function (id, guess) {
var hadokenSound = new Audio('./media/Hadoken.mp3');
var button = document.getElementById(id);
button.onclick = function () {
quiz.guessIsCorrect(guess);
QuizUI.displayNext();
hadoken();
hadokenSound.play();
}
},
displayProgress: function () {
var currentQuestionNumber = quiz.indexOfCurrentQuestion + 1;
// get the index number of current question
//call insertTextInHTML method
this.insertTextInHTML('progress', 'Question ' + currentQuestionNumber + ' of ' + questions.length);
},
progressBar: function () {
var percent = quiz.indexOfCurrentQuestion;
document.getElementById("progress-bar").style.width = percent + "0%";
},
showCurrentScore: function () {
if (quiz.score === 0 && quiz.wrong ===0) {
document.getElementById("score").innerHTML = "You can do it!";
document.getElementById("wrong").innerHTML = "Don't loose!";
} else {
document.getElementById("score").innerHTML = "You've got " + quiz.score + " right so far!";
document.getElementById("wrong").innerHTML = "You've got " + quiz.wrong + " wrong so far!";
}
}
}; |
Python | UTF-8 | 167 | 3.140625 | 3 | [
"MIT"
] | permissive | from datetime import timedelta
def add(moment):
"""Calculate the moment when someone has lived for 10^9 seconds."""
return moment + timedelta(seconds=10**9)
|
JavaScript | UTF-8 | 6,472 | 2.546875 | 3 | [
"MIT"
] | permissive | /**
* Created by Divinemaniac on 3/13/2016.
*/
ImageIndex = {
selectToggleClass: "img-list-thumbnail",
selectableContainerClass: "selectable",
selectedItemClass: "selected",
selectText : " Select Multiple", //The text to display in the switch button when multiple selection is on
deselectText : " Manage", //The text to display in the switch button when multiple selection is off
imageList: null, //The ALister Class which will handle adding and removing of items
mode: null, //The mode of the Image Index
//Function Disablers
disableSingleSelect: false,
disableBulkSelect: false,
disableManage: false,
disableView: false,
disableDelete: false,
disableEdit: false,
disableBulkDelete: false,
//Callbacks
onModeChange: null, //Method to call when the mode is changed
onSelect: null, //Method to call when an item is selected
//Sets the container for the image list
//The passed parameter must be the id of the container to use
setContainer: function(containerId) {
ImageIndex.imageList = new ALister({
containerID: containerId,
uniqueProperty: 'id',
addItem: ImageIndex.addNewItem
});
ImageIndex.imageList.fetchSettings.limit = 20;
},
//Sets the fetch URL
setFetchURL: function(URL) {
ImageIndex.imageList.fetchSettings.url = URL;
},
//Sets the delete URL
setDeleteURL: function(URL) {
if(ImageIndex.disableDelete) return;
ImageIndex.imageList.deleteSettings.url = URL;
},
//Method that is called internally when the mode of the ImageIndex is changed.
notifyModeChanged: function(oldMode) {
ImageIndex.imageList.resetSelected();
if(ImageIndex.onModeChange) ImageIndex.onModeChange.call(null,oldMode,ImageIndex.mode);
},
//Gets the current mode of the ImageIndex
getMode : function() {
return ImageIndex.mode;
},
//Changes the mode of ImageIndex to manage mode
//calls the notifyModeChanged method
setManageMode : function() {
if(ImageIndex.disableManage || ImageIndex.mode=="manage") return;
var oldMode = ImageIndex.mode;
ImageIndex.mode = 'manage';
ImageIndex.imageList.makeUnselectable();
ImageIndex.notifyModeChanged(oldMode);
},
//Changes the mode of ImageIndex to Single selection mode
//calls the notifyModeChanged method
setSingleSelectMode : function() {
if(ImageIndex.disableSingleSelect || ImageIndex.mode=="single_select") return;
var oldMode = ImageIndex.mode;
ImageIndex.mode = 'single_select';
ImageIndex.imageList.makeSelectable({
selectLimit : 1,
toggleClass : ImageIndex.selectToggleClass,
selectableContainerClass : ImageIndex.selectableContainerClass,
selectedItemClass : ImageIndex.selectedItemClass
});
ImageIndex.notifyModeChanged(oldMode);
},
//Changes the mode of ImageIndex to Bulk/Multiple selection mode
//calls the notifyModeChanged method
setBulkSelectMode : function() {
if(ImageIndex.disableBulkSelect || ImageIndex.mode=="bulk_select") return;
var oldMode = ImageIndex.mode;
ImageIndex.mode = 'bulk_select';
ImageIndex.imageList.makeSelectable({
selectLimit : false,
toggleClass : ImageIndex.selectToggleClass,
selectableContainerClass : ImageIndex.selectableContainerClass,
selectedItemClass : ImageIndex.selectedItemClass
});
ImageIndex.notifyModeChanged(oldMode);
},
//Deletes selected items
deleteSelected : function() {
if(ImageIndex.disableDelete || ImageIndex.disableBulkDelete) return;
var imageList = ImageIndex.imageList;
if(imageList.getSelectedCount() > 0) {
imageList.deleteSelected();
return true;
}
return false;
},
//Defines the template for a new item in the list
//calls the notifyModeChanged method
addNewItem : function(imageData) {
//The thumbnail container
var container = document.createElement('div');
container.setAttribute('class','dstyle margin-top-10 img-list-item uk-width-1-2 uk-width-medium-1-6 uk-width-large-1-8 uk-width-small-1-4');
//The figure
var figure = document.createElement('figure');
figure.setAttribute('id','img-id-'+imageData.id);
figure.setAttribute('class','uk-overlay uk-overlay-hover img-list-thumbnail');
//The image
var image = new Image();
image.src = ImageIndex.imageRoot+imageData.id+"."+imageData.extension;
image.setAttribute('class', 'uk-overlay-scale');
figure.appendChild(image);
//The figcaption
var figcaption = document.createElement('figcaption');
figcaption.setAttribute('class','uk-overlay-panel uk-overlay-background uk-overlay-fade actions');
if(!ImageIndex.disableEdit) {
//The link that holds the edit button
var editLink = document.createElement('a');
editLink.innerText = " Edit";
editLink.setAttribute('class', 'uk-icon-pencil-square img-list-item-edit');
figcaption.appendChild(editLink);
}
if(!ImageIndex.disableDelete) {
//The link that holds the delete button
var deleteLink = document.createElement('a');
deleteLink.innerText = " Delete";
deleteLink.setAttribute('class', 'uk-icon-trash img-list-item-delete');
figcaption.appendChild(deleteLink);
}
figure.appendChild(figcaption);
container.appendChild(figure);
//Image name div
var nameDiv = document.createElement('div');
nameDiv.setAttribute('class','img-name');
if(imageData.name.length > 14) {
nameDiv.innerText = imageData.name.substring(0,14) + "..";
} else {
nameDiv.innerText = imageData.name;
}
container.appendChild(nameDiv);
//The span that displays the selected tick
var span = document.createElement('span');
span.setAttribute('class','uk-icon-check-circle');
container.appendChild(span);
return container;
}
}; |
Ruby | UTF-8 | 283 | 2.59375 | 3 | [] | no_license |
# Learned during process:
# "gem list" (in termial) lists all local gems
# "ls -lah" (in terminal) lists permissions for file
# --> "chmod +x filename" would give that filename executable permissions
# "ls | grep read" basically a search for keyword of "read" within that ls
|
JavaScript | UTF-8 | 1,302 | 3.1875 | 3 | [] | no_license | "use strict";
const outputDiv = document.getElementById("output");
const domBuilder = (sandwichOption) => {
let domString = "";
domString += `<div class="caption" id="item-container">`;
domString += `<label class="form-check-label">`;
domString += `<input class="form-check-input" type="checkbox" value="${Object.keys(sandwichOption)[1]}">`;
domString += `${Object.keys(sandwichOption)[1]}`;
domString += `<div class="col-xs-1"></div>`;
domString += `</label>`;
domString += `</div>`;
return domString;
};
const domOutput = (currentArray) => {
let domOutput = "";
for (let i = 0; i < currentArray.length; i++) {
domOutput += (i % 12 === 0) ? `<div class="row">` : "";
domOutput += (i === 0) ? `<div data-category= ${currentArray[i].category} class="thumbnail">` : "";
domOutput += (i === 0) ? `<h3>${currentArray[i].category}</h3>` : "";
domOutput += (i === 0) ? `<div class="col-sm-6 col-md-4 col-md-offset-1">` : "";
domOutput += domBuilder(currentArray[i]);
domOutput += (i % 6 === 2) ? `</div>` : "";
domOutput += (i % 6 === 2) ? `</div>` : "";
domOutput += (i % 6 === 2) ? `</div>` : "";
}
return domOutput;
};
const printToDom = (currentArray) => {
outputDiv.innerHTML += domOutput(currentArray);
};
module.exports = printToDom; |
Python | UTF-8 | 9,704 | 3.171875 | 3 | [
"MIT"
] | permissive | from scoring import *
import twl #for auto blank resolution
import configs
class Board:
SIZE = 15
def __init__(self):
self.board = [None for x in range(0,Board.SIZE**2)]
def set(self, x,y,c):
if x < 0 or x > Board.SIZE-1 or y < 0 or y > Board.SIZE-1:
raise ValueError
self.board[y*Board.SIZE + x] = c
def get(self, x,y):
if x < 0 or x > Board.SIZE-1 or y < 0 or y > Board.SIZE-1:
return None
return self.board[y*Board.SIZE + x]
#Returns a deep copy of self
def copy(self):
b = Board()
b.board = list(self.board)
return b
#Gets the nearest points around (x,y) that are non none
def get_nearest_not_none(self, x,y, num):
matches = []
def search_ring(n):
ring_matches = []
i = x - n
j = y - n
def check_and_append(a,b):
p = self.get(a,b)
if p is not None:
ring_matches.append(p)
#Check top of box
while i < x + n:
check_and_append(i,j)
i += 1
#Check right side of box
while j < y + n:
check_and_append(i,j)
j += 1
#Check bottom of box
while i > x - n:
check_and_append(i,j)
i -= 1
#Check left side of box
while j > y - n:
check_and_append(i,j)
j -= 1
return ring_matches
cring = 1
while len(matches) < num and cring < 14:
matches += search_ring(cring)
cring += 1
return matches[:num]
#Returns differences between two boards in (x,y, new content from b2) tuples
@classmethod
def differences(cls, old, new):
diffs = []
for i in range(0,Board.SIZE):
for j in range(0,Board.SIZE):
if old.get(i,j) != new.get(i,j):
diffs.append((i,j,new.get(i,j)))
return diffs
#Takes a set of diffs and makes sure they're a valid move (i.e all letters in a single line)
def verify_diffs(self, diffs):
points = list(map(lambda p: (p[0],p[1]), diffs))
x_p = list(map(lambda p: p[0], points))
y_p = list(map(lambda p: p[1], points))
if len(diffs) == 0:
#Skip trun
return True
if len(set(x_p)) == 1: #All elements are lined up vertically
o_p = y_p
from_board = map(lambda m: m[0], filter(lambda p: p[1] is not None, [(y, self.get(x_p[0], y)) for y in range(0,Board.SIZE)]))
elif len(set(y_p)) == 1: #All elements are lined up horizontally
o_p = x_p
from_board = map(lambda m: m[0], filter(lambda p: p[1] is not None, [(x, self.get(x, y_p[0])) for x in range(0,Board.SIZE)]))
else:
#Elements are not all in one line
return False
#Make sure all the values in o_p are continuous
o_p.sort()
#Get anything on the board between the min and max letters we placed
board_relevant = list(filter(lambda x: x > o_p[0] and x < o_p[-1], from_board))
print("Board relevant: " + str(board_relevant))
#get row from board
o_p += board_relevant
o_p.sort()
#Make sure all values are continuous
paired = zip(o_p, o_p[1:])
continuous_values = all(map(lambda p: p[1] == p[0]+1, paired))
if not continuous_values:
return False
#Verify that at least one letter is next to an existing letter (unless board is empty)
def next_to_existing_letter(p):
return (self.get(p[0]+1,p[1]) is not None) or (self.get(p[0]-1, p[1]) is not None) or (self.get(p[0], p[1]-1) is not None) or (self.get(p[0], p[1]+1) is not None)
def board_is_empty():
return all(map(lambda x: x is None, self.board))
if not any(map(next_to_existing_letter, points)):
#Check if the board is empty
if not board_is_empty():
return False
#All checks pass
return True
#Adds a set of differences to this board
def add_diffs(self, diffs):
for (x,y,c) in diffs:
self.set(x,y,c)
#Copies all non-none values from the other board to this board
def merge(self, other):
for i in range(0, Board.SIZE):
for j in range(0, Board.SIZE):
if other.get(i,j) != None:
self.set(i,j, other.get(i,j))
#Gets the word containing the letter at element at x,y
def get_word(self, x, y, horizontal=True):
#Backtrack to the start of the word
sx, sy = x, y
while self.get(sx, sy) != None:
if horizontal:
sx -= 1
else:
sy -= 1
if horizontal:
sx += 1
else:
sy += 1
word_start = (sx, sy)
word = ""
#Read out the word
while self.get(sx, sy) != None:
word += str(self.get(sx, sy))
if horizontal:
sx += 1
else:
sy += 1
if len(word) < 2:
return None
return (word, word_start, horizontal)
#Brute force test of all blanks against dictionary in an attempt to resolve it ourselves
@classmethod
def auto_resolve_blanks(cls, diffs, new_board, word_set):
count = 0
x = 0
y = 0
for (i,j,v) in diffs:
if v == '-':
x = i
y = j
count += 1
if count != 1:
return #Auto resolver can only resolve exactly one blank at the moment
letters = letter_points.keys()
test_board = new_board.copy()
possible_letters = []
#Test word set with all possible letters
for l in letters:
#Make testing change in the test board
test_board.set(x,y,l)
new_words = []
#Get set of new words resulting from this change
for (word, (a,b), horizontal) in word_set:
if '-' in word:
(new_wrd,j,k) = test_board.get_word(a,b,horizontal)
new_words.append(new_wrd)
if all(map(twl.check, new_words)):
possible_letters.append(l) #All new words pass dictionary check
print("Possible letters for blank: %s" % str(possible_letters))
if len(possible_letters) == 1:
l = possible_letters[0]
print("Auto resolving blank to %s" % l)
diffs.remove((x,y,'-'))
blnk = Blank(l)
diffs.append((x,y,blnk))
new_board.set(x,y,blnk)
@classmethod
def blank_resolver(cls, diffs, word_set, new_board, blank_prompter):
#This method must:
#Blanks must be resolved at this point for the diffs and word set' strings must be fixed
#And new board must be updated
#Attempt to automatically resolve blanks using our dictionary
Board.auto_resolve_blanks(diffs, new_board, word_set)
#Resolve all remaining blanks in our diff set
for (i,j,v) in list(diffs):
if v == '-':
blnk = Blank(blank_prompter(i,j))
diffs.remove((i,j,v))
diffs.append((i,j,blnk))
new_board.set(i,j,blnk)
#Fix our detected word set
for (word, pt, horizontal) in word_set:
if '-' in word:
(x,y) = pt
new_word = new_board.get_word(x,y,horizontal)
word_set.remove((word,pt,horizontal))
word_set.add(new_word)
#Scores a word given the new board and the list of diffs
def score_word(self, t, diffs):
(word, word_start, horizontal) = t
def is_new(x,y):
for (i,j,c) in diffs:
if x == i and y == j:
return True
return False
c_mult = 1
score = 0
sx, sy = word_start
while self.get(sx, sy) != None:
#Score letter!
l = self.get(sx, sy)
lm = 1
if is_new(sx, sy):
#Multipliers are applicable for this letter
lm *= get_letter_mult(sx,sy)
c_mult *= get_word_mult(sx,sy)
score += lm * get_letter_points(l)
if horizontal:
sx += 1
else:
sy += 1
return score * c_mult
class AveragedBoard:
"""
AveragedBoard represents a grid of letters with hysteresis.
"""
def __init__(self):
self.reset()
def reset(self):
self._board_letters = [[] for x in range(0,15**2)]
def _acc(self, x, y):
return self._board_letters[y*15 +x]
def observe(self, x, y, c):
"""
Observe letter `c` at position x,y
"""
a = self._acc(x, y)
a.insert(0,c)
while len(a) > configs.BOARD_LETTER_HISTORY_SIZE:
a.pop()
def get(self, x, y):
"""
Get the average letter at position x,y
"""
a = self._acc(x,y)
d = {}
for l in a:
if l not in d:
d[l] = 1
else:
d[l] = d[l] + 1
dd = list(zip(d.values(), d.keys()))
dd.sort(reverse=True, key=lambda x: x[0])
if len(dd) == 0:
return None
if dd[0][1] == None and len(dd) >= 2:
nc = dd[0][0]
ncf = float(nc) / len(a)
if ncf > configs.BLANK_REQ_PERCENT:
return None
else:
dd.remove(dd[0])
return dd[0][1]
|
Java | UTF-8 | 1,624 | 3.015625 | 3 | [] | no_license | package com.jc02.wjm;
import java.util.Scanner;
/**
* \\\|///
* \\ .-.- //
* ( .@.@ )
* +-------oOOo-----( _ )-----oOOo--------------------------------------------+
* | @author 万家明 |
* | @author 江西财经大学 |
* | @create 2017年07月20日 - 16:59
* | @description s
* +---------------------------------Oooo---------------------------------------+
*/
public class Wjm {
public static void main(String[] args) {
int e,f;
Calander c=new Calander();
Scanner input=new Scanner(System.in);
System.out.println("请输入 年份");
int y=input.nextInt();
int m=1;
do {
c.showCalander(y,m);
System.out.println("\n请选择n显示接下来一个月,p显示前一个月,all显示当年所有月,其他键退出");
String d=input.next();
if(d.equalsIgnoreCase("n")) {
m++;
if(m>12)
{y++;
m=1;}
}
else if(d.equalsIgnoreCase("p")) {
m--;
if(m<1)
{
y--;
m=12;}
}
else if(d.equalsIgnoreCase("all")) {
for(int k=1;k<=11;k++)
c.showCalander(y,k);
m=12;
}
else {
break;
}
}while (true);
}
} |
PHP | UTF-8 | 4,241 | 2.53125 | 3 | [] | no_license | <?php
include(__DIR__ . '/Big52003.php');
ini_set('memory_limit', '2048m');
class Updater
{
public function getInfoFromURL($url)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, $url);
$content = curl_exec($curl);
curl_close($curl);
$ret = new StdClass;
if (!preg_match('#檔案下載:<a onclick="SaveDownloadLog\(\)" target="_blank" class="link" href="([^"]*)">([^<]*)</a></br>#', $content, $matches)) {
throw new Exception("找不到 {$url} 的檔案下載連結");
}
$ret->link = $matches[1];
if (!preg_match('#最後更新時間:([^<]*)#', $content, $matches)) {
throw new Exception("找不到 {$url} 的最後更新時間");
}
$ret->updated_at = $matches[1];
return $ret;
}
public function downloadFromURL($file_url, $folder, $source_srs, $encoding)
{
$url = 'http://shp2json.ronny.tw/api/downloadurl?url=' . urlencode($file_url);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$ret = curl_exec($curl);
if (!$ret = json_decode($ret) or $ret->error) {
throw new Exception("下載 {$file_url} 失敗: " . $ret->message);
}
$url = $ret->getshp_api;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$ret = curl_exec($curl);
if (!$ret = json_decode($ret) or $ret->error) {
throw new Exception("取得 {$file_url} shp 列表失敗: " . $ret->message);
}
$target_dir = __DIR__ . '/../geo/' . $folder;
if (!file_exists($target_dir)) {
mkdir($target_dir);
}
foreach ($ret->data as $shpfile) {
$url = $shpfile->geojson_api . '&source_srs=' . urlencode($source_srs);
error_log($url);
$curl = curl_init($url);
$download_fp = tmpfile();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FILE, $download_fp);
curl_exec($curl);
curl_close($curl);
fflush($download_fp);
$file_name = preg_replace_callback('/#U([0-9a-f]*)/', function($e){
return mb_convert_encoding('&#' . hexdec($e[1]) . ';','UTF-8', 'HTML-ENTITIES');
}, substr($shpfile->file, 0, -4));
$target_file = $target_dir . '/' . $file_name . '.json';
mkdir(dirname($target_file), 0777, true);
if (strtolower($encoding) == 'big5') {
$cmd = ("env LC_ALL=C sed -i " . escapeshellarg('s/\([\x81-\xFE]\\\\\)\\\\/\1/g') . ' ' . escapeshellarg(stream_get_meta_data($download_fp)['uri']));
exec($cmd);
exec("piconv -f Big5 < " . escapeshellarg(stream_get_meta_data($download_fp)['uri']) . ' > ' . escapeshellarg($target_file));
} else {
rename(stream_get_meta_data($download_fp)['uri'], $target_file);
}
$cmd = "node " . escapeshellarg(__DIR__ . '/geojson_parse.js') . " get_type " . escapeshellarg($target_file);
exec($cmd, $outputs, $ret);
if ($ret) {
throw new Exception("取得 {$file_url} JSON 格式錯誤: " . $ret->message);
}
}
}
public function main($argv)
{
$fp = fopen(__DIR__ . '/../geo.csv', 'r');
$fp_new = fopen(__DIR__ . '/../geo_new.csv', 'w');
$columns = fgetcsv($fp);
fputcsv($fp_new, $columns);
while ($row = fgetcsv($fp)) {
list($folder, $name, $url, $srs, $origin_encoding, $updated_at) = $row;
$info = $this->getInfoFromURL($url);
if ($updated_at != $info->updated_at) {
$this->downloadFromURL($info->link, $folder, $srs, $origin_encoding);
$updated_at = $info->updated_at;
}
fputcsv($fp_new, array($folder, $name, $url, $srs, $origin_encoding, $updated_at));
}
fclose($fp_new);
rename(__DIR__ . '/../geo_new.csv', __DIR__ . '/../geo.csv');
}
}
$u = new Updater;
$u->main($_SERVER['argv']);
|
Shell | UTF-8 | 860 | 3.859375 | 4 | [
"BSD-2-Clause"
] | permissive | #!/bin/bash
#
# Simple script to fetch journald logs while keeping state.
# Requires the 'jq' package to be installed.
#
PATH=/bin:/usr/bin:/sbin:/usr/sbin
CUR_DIR=$(dirname $0)
STATE_DIR="${CUR_DIR}/../state"
STATE_FILE="${STATE_DIR}/journald.state"
STATE_LOGFILE="${STATE_DIR}/journald.log"
update_state () {
if [ -s ${STATE_LOGFILE} ]; then
# only update state if we have a new one
STATE=$(tail -n1 ${STATE_LOGFILE} | jq -j '.__CURSOR')
echo -n ${STATE} > ${STATE_FILE}
fi
}
if [ -s ${STATE_FILE} ]; then
# get state and logs
CURSOR=$(cat ${STATE_FILE})
journalctl --after-cursor="${CURSOR}" --no-tail --no-pager -o json | tee ${STATE_LOGFILE}
update_state
fi
if ! [ -f ${STATE_FILE} ]; then
# no state (first run?); get logs of today
journalctl --no-tail --since today --no-pager -o json | tee ${STATE_LOGFILE}
update_state
fi
# EOF
|
Java | UTF-8 | 1,934 | 2.34375 | 2 | [] | no_license | package com.minhui.vpn.parser;
public class ShowDataType {
public static final int ALL=0;
public static final int TEXT=1;
public static final int IMAGE=2;
public static final int AUDIO=3;
public static final int VIDEO =4;
public static final int UDP =5;
public static final int OTHER =6;
public static final String HTML_STR = "html";
public static final String JSON_STR = "json";
public static final String TXT_STR = "txt";
public static final String TEXT_STR = "text";
public static final String JAVA_STR = "java";
public static final String MULTI_FORM_STR = "multipart";
public static final String ZIP_STR = "zip";
public static final String IMAGE_STR = "image";
public static final String URLENCODED_STR = "urlencoded";
public static final String AUDIO_STR = "audio";
public static final String VIDEO_STR = "video";
public static final String BYTES_STR = "BYTES";
public static final String CONTENT_FILE_STR = "contentFile";
public static int getContentType(String contentType) {
if (contentType != null) {
String toLowerCase = contentType.toLowerCase();
if (contentType.contains(HTML_STR)
|| contentType.contains(JSON_STR)
|| contentType.contains(TXT_STR)
|| contentType.contains(JAVA_STR)
|| contentType.contains(TEXT_STR)) {
return ShowDataType.TEXT;
}
if (toLowerCase.contains(IMAGE_STR)) {
return ShowDataType.IMAGE;
} else if (toLowerCase.contains(VIDEO_STR)) {
return ShowDataType.VIDEO;
} else if (toLowerCase.contains(AUDIO_STR)) {
return ShowDataType.AUDIO;
} else {
return ShowDataType.OTHER;
}
} else {
return ShowDataType.TEXT;
}
}
}
|
Python | UTF-8 | 1,544 | 2.640625 | 3 | [] | no_license | import requests
from bs4 import BeautifulSoup
from colorama import Fore, Back, Style
sites = [
{
'name': 'Spotify - IL',
'url': 'https://www.spotify.com/il/premium/',
'selector': ["p", {"class": "subhead bellow-headline"}],
'expectation': 'Try Premium free for 30 days. Only ₪19.90/month after.*'
},
{
'name': 'Spotify - FR',
'url': 'https://www.spotify.com/fr/premium/',
'selector': ["p", {"class": "subhead bellow-headline"}],
'expectation': 'Essayez Spotify Premium gratuitement pendant 30 jours. Seulement 9,99 €/mois ensuite.*'
},
{
'name': 'Spotify - EN',
'url': 'https://www.spotify.com/en/premium/',
'selector': ["p", {"class": "subhead bellow-headline"}],
'expectation': 'Try Premium free for 30 days. Only ₪19.90/month after.*'
},
{
'name': 'Deezer - FR',
'url': 'https://www.deezer.com/fr/offers/',
'selector': ["div", {"class": "offers-link"}],
'expectation': 'Essayer pendant 30 jours'
},
{
'name': 'Deezer - EN',
'url': 'https://www.deezer.com/en/offers/',
'selector': ["div", {"class": "offers-link"}],
'expectation': 'Start your 30 day trial'
}
]
for site in sites:
page = requests.get(site['url'])
soup = BeautifulSoup(page.content, 'html.parser')
price_line = soup.find(*site['selector'])
result = price_line.getText().strip()
if 'clean_function' in site:
result = site['clean_function'](result)
if result == site['expectation']:
print(Fore.RED + site['name'] + Style.RESET_ALL)
else:
print(Fore.GREEN + site['name'] + '\n\t' + result + Style.RESET_ALL)
|
Java | UTF-8 | 321 | 1.625 | 2 | [] | no_license | package com.intentfilter.profileservice.repositories;
import com.intentfilter.profileservice.models.Profile;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ProfileRepository extends MongoRepository<Profile, String> {
}
|
C++ | UTF-8 | 901 | 2.90625 | 3 | [] | no_license | #include "ctranspiler.h"
#include "iremitter.h"
#include "parser.h"
#include <fstream>
#include <iostream>
using namespace std;
int main(int argc, char const* argv[])
{
if (argc < 3) {
cout << "scc llvm|c file|-" << endl;
cout << "* llvm ir or c output" << endl;
cout << "* file or stdin" << endl;
return 1;
}
bool isllvm = (string(argv[1]) == "llvm");
bool isstdin = (string(argv[2]) == "-");
vector<Instruction> ins;
if (isstdin) {
Parser p(&cin);
ins = p.parse();
} else {
ifstream fin(argv[2], ios::in);
Parser p(&fin);
ins = p.parse();
if (fin)
fin.close();
}
if (isllvm) {
// convert to llvm ir
IREmitter e(&cout, ins);
e.ir_emit();
} else {
// convert to c
Transpiler t(&cout, ins);
t.transpile_c();
}
} |
Python | UTF-8 | 2,264 | 3.40625 | 3 | [
"Apache-2.0"
] | permissive | """
Policy Gradient, Reinforcement Learning.
The cart pole example
View more on my tutorial page: https://morvanzhou.github.io/tutorials/
Using:
Tensorflow: 1.0
gym: 0.8.0
"""
import gym
from RL_brain import PolicyGradient
import matplotlib.pyplot as plt
DISPLAY_REWARD_THRESHOLD = 400 # 当回合总reward大于400的时候显示模拟窗口
RENDER = False # 边训练边显示会拖慢训练速度,我们等程序先学习一段时间
env = gym.make('CartPole-v0') # 创建 CardPole这个模拟
env.seed(1) # 创建随机种子
env = env.unwrapped # 取消限制
print(env.action_space) #输出可用的动作
print(env.observation_space) # 显示可用 state 的 observation
print(env.observation_space.high) # 显示 observation 最高值
print(env.observation_space.low) # 显示 observation 最低值
# 定义使用 Policy_gradient 的算法
RL = PolicyGradient(
n_actions=env.action_space.n,
n_features=env.observation_space.shape[0],
learning_rate=0.02,
reward_decay=0.99,
# output_graph=True,
)
for i_episode in range(3000):
observation = env.reset() # 获取回合 i_episode 第一个 observation
while True:
if RENDER: env.render() # 刷新环境
action = RL.choose_action(observation) # 选行为
observation_, reward, done, info = env.step(action) # 获取下一个state
RL.store_transition(observation, action, reward) # 存储这一回合的transition
if done: # 一个回合结束,开始更新参数
ep_rs_sum = sum(RL.ep_rs) # 统计每回合的reward
if 'running_reward' not in globals():
running_reward = ep_rs_sum
else:
running_reward = running_reward * 0.99 + ep_rs_sum * 0.01
if running_reward > DISPLAY_REWARD_THRESHOLD: RENDER = True # 判断是否开始模拟
print("episode:", i_episode, " reward:", int(running_reward))
vt = RL.learn() # 学习参数,输出vt
if i_episode == 0: # 画图
plt.plot(vt)
plt.xlabel('episode steps')
plt.ylabel('normalized state-action value')
plt.show()
break
observation = observation_ |
Markdown | UTF-8 | 1,683 | 2.671875 | 3 | [] | no_license | ### 项目的CI/CD流程
此项目中的ci文件夹包含了ci脚本,其可用于测试阶段的每一个步骤。ci系统确保了对项目所提交的PR能够在 Windows, Linux, and macOS等系统环境下进行单元测试,并可以实现测试的自动运行。
ci的很多操作在docker容器中执行。并且为了测试环境的多样性,也为了某些情况得以复现,测试阶段需要docker。测试环境的容器化保证了不同测试环境之间的隔离性以及保证了测试环境的轻量级启动、使用。
在ci阶段的测试过程中,项目会在不同环境下进行测试。如下图琐事我们是可以看到多种类型的环境。
<img src="https://xlab-video.oss-cn-shanghai.aliyuncs.com/xlab-work/image1.png">
举个例子来看,比如在centos的测试环境中,会在docker容器中加载各种工具包,然后设置相应的运行时环境,以及容器的名称等基本信息。
<img src="https://xlab-video.oss-cn-shanghai.aliyuncs.com/xlab-work/image2.png">
为保证测试时的项目版本一致性,测试者将使用./depends文件夹下的依赖生成器,而并非使用测试系统中的包管理器去加载依赖。此外,为避免每次"构建项目"时依赖的重复下载,在某次"项目构建"时这些依赖将会被缓存,以备之后的重复使用。
<img src="https://xlab-video.oss-cn-shanghai.aliyuncs.com/xlab-work/image3.png">
此项目中没有使用.gitlab-ci.yml文件来定义基础的CI流程,而是更关注于项目新增变更在多个使用环境中的兼容性。
项目的测试多是使用脚本文件去运行项目,不同脚本文件之间存在较松的耦合。
|
PHP | UTF-8 | 2,339 | 3.171875 | 3 | [] | no_license | <?php
/**
* File PathBasedParser.php
*
* @package Poppins
* @license http://www.gnu.org/licenses/gpl-3.0.en.html GNU Public License
* @author Bruno Dooms, Frank Van Damme
*/
//require parent class
require_once dirname(__FILE__) . '/Parser.php';
/**
* Class PathBasedParser
*/
class PathBasedParser extends Parser
{
/**
* Get a value based on dot notation
* E.g. $keys['foo.bar'] gets $array['foo']['bar']
*
* @param string $index The index (dotted string)
* @param string $default Default value is empty unless otherwise
* @return string Value stored in array
*/
public function get($index, $default = '')
{
//if no dotes, return index
if (!preg_match('/\./', $index)) {
return $this->Store->stored()[$index];
}
$current = $this->Store->stored();
$p = strtok($index, '.');
while ($p !== false) {
if (!isset($current[$p])) {
return $default;
}
$current = $current[$p];
$p = strtok('.');
}
return $current;
}
/**
* Check if value is set based on dotted notation
* E.g. $keys['foo.bar'] gets $array['foo']['bar']
*
* @param string $index The index (dotted notation)
* @return bool Is set or not?
*/
public function is_set($index)
{
//if no dotes, return index
if (!preg_match('/\./', $index)) {
return isset($this->Store->stored()[$index]);
}
// dots
$current = $this->Store->stored();
$p = strtok($index, '.');
while ($p !== false) {
if (!isset($current[$p])) {
return false;
}
$current = $current[$p];
$p = strtok('.');
}
return isset($current);
}
/**
* Set a value based on array notation
* E.g. set('foo.bar', 'something') sets $array['foo']['bar'] to 'something'
*
* @param $index The keys of the array based on dotted string
* @param $value The value to be set
* @return boolean Return true if successful
*/
public function set($index, $value)
{
$index = explode('.', $index);
$parser = new KeyBasedParser($this->Store);
return $parser->set($index, $value);
}
}
|
C# | UTF-8 | 2,220 | 3 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Globalization;
namespace Round1BProblemA
{
class R1B_ProblemA
{
static void Main(string[] args)
{
//const string fileName = "test";
//const string fileName = "A-small-attempt0";
const string fileName = "A-large";
string DataFolder = @"D:\Projects\CSharp\CodeJam2012\Round1BProblemA\Data\";
StreamReader sr = File.OpenText(DataFolder + fileName + ".in");
using (StreamWriter sw = File.CreateText(DataFolder + fileName + ".out"))
{
int caseCount = int.Parse(sr.ReadLine());
for (int caseNumber = 1; caseNumber <= caseCount; ++caseNumber)
{
string[] s = sr.ReadLine().Split();
int N = int.Parse(s[0]);
Debug.Assert(N + 1 == s.Length);
int[] J = new int[N];
int[] stat = new int[101];
int sum = 0;
for (int i = 0; i < N; ++i)
{
J[i] = int.Parse(s[i + 1]);
stat[J[i]]++;
sum += J[i];
}
int nCount = 0;
int delta = 0;
int val = 0;
while (delta < sum && val <= 100)
{
nCount += stat[val];
delta += nCount;
val++;
}
double level = val + ((sum - delta) / (double)nCount);
sw.Write("Case #" + caseNumber.ToString() + ":");
for (int i = 0; i < N; ++i)
{
double p = (J[i] >= level) ? 0 : ((double)(level - J[i]) * 100) / sum;
sw.Write(" " + p.ToString("F8", CultureInfo.InvariantCulture));
}
sw.WriteLine();
}
}
}
}
}
|
JavaScript | UTF-8 | 478 | 3.984375 | 4 | [] | no_license | // The rest parameter allows us to pass an indefinite number of parameters to a function and access them in an array.
// ...rest(any name can be placed on the place of rest)
let fun1 = function(msg, y, ...colors){
console.log(msg);
console.log(y);
for(let i in colors){
console.log(colors[i]);
}
}
let msg = 'list : ';
let y = 'colors : ';
fun1(msg, y, 'red', 'green');
fun1(msg, y, 'red', 'green', 'blue');
fun1(msg, y, 'red', 'green', 'blue', 'green'); |
Java | UTF-8 | 3,946 | 2.828125 | 3 | [] | no_license | package com.example.orbital_layoutfrontend;
import android.os.Build;
import androidx.annotation.RequiresApi;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.io.Serializable;
import java.util.Objects;
public class OldPlayer implements Serializable {
private String name;
private String teamName;
private ArrayList<OldGame> oldGameHistory;
private String position;
private String experienceLevel;
/**
* Constructor for a new player with no game history.
* @param name
* @param teamName
* @param position
* @param experienceLevel
*/
public OldPlayer(String name, String teamName,
String position, String experienceLevel) throws InvalidParameterException {
this.name = name;
this.teamName = teamName;
oldGameHistory = new ArrayList<>();
if (position.equals("Handler") || position.equals("Cutter") ||
position.equals("Beginner")) {
this.position = position;
} else {
throw new InvalidParameterException("Invalid Position");
}
if (experienceLevel.equals("Beginner") || experienceLevel.equals("Intermediate") ||
experienceLevel.equals("Advanced") || experienceLevel.equals("Professional")) {
this.experienceLevel = experienceLevel;
} else {
throw new InvalidParameterException("Invalid Experience Level");
}
}
public OldPlayer(String name, String teamName, ArrayList<OldGame> oldGameHistory,
String position, String experienceLevel) throws InvalidParameterException {
this.name = name;
this.teamName = teamName;
this.oldGameHistory = oldGameHistory;
if (position.equals("Handler") || position.equals("Cutter") ||
position.equals("Beginner")) {
this.position = position;
} else {
throw new InvalidParameterException("Invalid Position");
}
if (experienceLevel.equals("Beginner") || experienceLevel.equals("Intermediate") ||
experienceLevel.equals("Advanced") || experienceLevel.equals("Professional")) {
this.experienceLevel = experienceLevel;
} else {
throw new InvalidParameterException("Invalid Experience Level");
}
}
public String getName() {
return name;
}
public String getTeam() {
return teamName;
}
public String toString() {
return name;
}
public void addGame(OldGame newOldGame) {
oldGameHistory.add(newOldGame);
}
public String getExperienceLevel() {
return experienceLevel;
}
public Integer getGameCount() {
return oldGameHistory.size();
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
OldPlayer oldPlayer = (OldPlayer) o;
return Objects.equals(name, oldPlayer.name);
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public int hashCode() {
return Objects.hash(name);
}
public void changeTeam(String newTeam) {
this.teamName = newTeam;
}
public void changeExperienceLevel(String experienceLevel) {
if (experienceLevel.equals("Beginner") || experienceLevel.equals("Intermediate") ||
experienceLevel.equals("Advanced") || experienceLevel.equals("Professional")) {
this.experienceLevel = experienceLevel;
} else {
throw new InvalidParameterException("Invalid Experience Level");
}
}
public ArrayList<OldGame> getGameHistory() {
return oldGameHistory;
}
public OldGame getLatestGame() {
return oldGameHistory.get(getGameCount() - 1);
}
}
|
Python | UTF-8 | 2,744 | 3.328125 | 3 | [] | no_license | import src.utils as utils
from src.bubble import Bubble
from src.bubble_types import BubbleTypes
class TestUtils:
def test_create_empty_board(self):
board = utils.create_empty_board(6,5)
bubble = Bubble(BubbleTypes.Empty)
for i in range(len(board)):
for j in range(len(board[i])):
assert board[i][j] == bubble
assert len(board[i]) == 5
assert len(board) == 6
def test_num_matrix_to_bubble_matrix(self):
num_matrix = [
[0,0,0,0,0],
[1,0,0,2,1],
[0,0,1,0,0],
[1,1,0,3,0]
]
bubble_matrix = [
[Bubble(BubbleTypes.Empty) , Bubble(BubbleTypes.Empty) , Bubble(BubbleTypes.Empty) , Bubble(BubbleTypes.Empty) , Bubble(BubbleTypes.Empty) ],
[Bubble(BubbleTypes.Red) , Bubble(BubbleTypes.Empty) , Bubble(BubbleTypes.Empty) , Bubble(BubbleTypes.Green) , Bubble(BubbleTypes.Red) ],
[Bubble(BubbleTypes.Empty) , Bubble(BubbleTypes.Empty) , Bubble(BubbleTypes.Red) , Bubble(BubbleTypes.Empty) , Bubble(BubbleTypes.Empty) ],
[Bubble(BubbleTypes.Red) , Bubble(BubbleTypes.Red) , Bubble(BubbleTypes.Empty) , Bubble(BubbleTypes.Yellow) , Bubble(BubbleTypes.Empty) ]
]
assert utils.num_matrix_to_bubble_matrix(num_matrix) == bubble_matrix
def test_are_adjacent(self):
matrix = [
[0,0,0,0,0],
[1,0,0,2,1],
[0,0,1,0,0],
[1,1,0,3,0]
]
matrix = utils.num_matrix_to_bubble_matrix(matrix)
matrix2 = [
[1,0,0,0,0],
[0,0,0,2,1],
[1,0,1,0,0],
[0,1,0,3,0]
]
matrix2 = utils.num_matrix_to_bubble_matrix(matrix2)
assert utils.are_adjacent(matrix, 1, 0, 3, 0)
assert utils.are_adjacent(matrix, 3, 1, 3, 3)
assert utils.are_adjacent(matrix, 1, 3, 1, 4)
assert utils.are_adjacent(matrix, 3, 3, 1, 3)
assert utils.are_adjacent(matrix, 1, 0, 1, 3)
assert not utils.are_adjacent(matrix, 2, 1, 0, 1)
assert not utils.are_adjacent(matrix, 2, 1, 1, 1)
assert not utils.are_adjacent(matrix, 1, 0, 1, 2)
assert not utils.are_adjacent(matrix, 0, 1, 2, 2)
assert not utils.are_adjacent(matrix, 1, 0, 1, 4)
assert not utils.are_adjacent(matrix, 1, 1, 1, 1)
assert utils.are_adjacent(matrix2, 0, 0, 2, 0)
def test_calculate_board_value(self):
matrix = [
[4,0,0,0,0],
[1,0,0,2,1],
[0,0,1,0,0],
[1,1,0,3,0]
]
matrix = utils.num_matrix_to_bubble_matrix(matrix)
board_value = utils.calculate_board_value(matrix)
assert board_value == 14
def test_get_matrix_borders(self):
matrix = [
[4,0,0,0,0],
[1,0,0,2,1],
[0,0,1,0,0],
[1,1,0,3,0]
]
expected = [4,0,0,0,0,1,0,0,3,0,1,1,0,1]
borders = utils.get_matrix_borders(matrix)
assert borders == expected |
Java | UTF-8 | 3,171 | 2.96875 | 3 | [] | no_license | package active_record;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class UserAdmMenu {
static String[] menuLines = {"Wybierz jedną z opcji:", "* add - dodanie użytkownika",
"* edit - edycja użytkownika", "* delete - usunięcie użytkownika", "* quit - zakończenie programu"};
public static void main(String[] args) {
String db = "warsztat2";
String conCommand = "jdbc:mysql://localhost:3306/"+db+"?useSSL=false";
String dbUser = "root";
String password = "coderslab";
try (Connection conn = DriverManager.getConnection(conCommand, dbUser, password)){
boolean isExit = false;
while (!isExit) {
User[] users = User.loadAll(conn);
UserDisplayUtils.displayAll(users);
String command = Panel.mainMenu(menuLines);
User user;
switch (command) {
case "add" : user = addUser();
if (user != null)
user.saveToDB(conn);
break;
case "edit" : user = editUser(conn);
if (user != null)
user.saveToDB(conn);
break;
case "delete": user = deleteUser(conn);
if (user != null)
user.delete(conn);
break;
case "quit" : isExit = true;
break;
}
}
} catch (SQLException e) {
e.printStackTrace();
}
Panel.close();
}
static public User addUser() {
String username = Panel.getConsoleString("Podaj imię i nazwisko użytkownika: ");
String email = Panel.getConsoleEmail("Podaj e-mail użytkownika: ");
if (email == null) {
System.out.println("Wprowadzanie anulowane ");
return null;
}
String password = Panel.getConsolePassword("Podaj hasło użytkownika: ");
int groupId = Panel.getConsoleInt("Podaj nr grupy, do której użytkownik jest przypisany: ");
User user = new User(username, email, password, groupId);
return user;
}
static public User editUser(Connection conn) throws SQLException {
int userId = Panel.getConsoleInt("Podaj id użytkownika, którego chcesz edytować: ");
User user = User.loadById(conn, userId);
if (user != null) {
UserDisplayUtils.display(user);
String username = Panel.getConsoleString("Podaj imię i nazwisko użytkownika: ");
String email = Panel.getConsoleEmail("Podaj e-mail użytkownika: ");
if (email == null) {
System.out.println("Wprowadzanie anulowane ");
return null;
}
String password = Panel.getConsolePassword("Podaj hasło użytkownika: ");
int groupId = Panel.getConsoleInt("Podaj nr grupy, do której użytkownik jest przypisany: ");
if (Panel.isConfirmed("Wprowadzono zmiany")) {
user.setUsername(username);
user.setEmail(email);
user.setPassword(password);
user.setGroupId(groupId);
return user;
} else {
return null;
}
}
return null;
}
static public User deleteUser(Connection conn) throws SQLException {
int userId = Panel.getConsoleInt("Podaj id użytkownika, którego chcesz usunąć: ");
User user = User.loadById(conn, userId);
if (Panel.isConfirmed("Wybrano użytkownika do usunięcia")) {
return user;
} else {
return null;
}
}
}
|
Python | UTF-8 | 3,009 | 2.75 | 3 | [] | no_license |
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 26 09:39:08 2015
@author: tanfan.zjh
"""
import cPickle
import numpy
#import theano
def prepare_data(seqs, labels):
"""
Create the matrices from the datasets.
This pad each sequence to the same lenght: the lenght of the
longuest sequence or maxlen.
if maxlen is set, we will cut all sequence to this maximum
lenght.
This swap the axis!
"""
lengths = [len(s) for s in seqs]
max_len = numpy.max(lengths)
n_samples = len(seqs)
x = numpy.zeros((max_len,n_samples)).astype('int64')
x_mask = numpy.zeros((max_len,n_samples)).astype(theano.config.floatX)
for idx,s in enumerate(seqs):
x[:lengths[idx],idx] = s
x_mask[:lengths[idx],idx] = 1
##x_mask: like x but all 1
return x, x_mask, labels
import constant
def load_data(path='data/'+constant.dataset+'.pkl',valid_portion=0.1):
'''
Loads the dataset
'''
f=open(path,'rb')
train_set = cPickle.load(f)
test_set = cPickle.load(f)
f.close()
# split training set into validation set
train_set_x, train_set_y = train_set
n_samples = len(train_set_x)
sidx = numpy.random.permutation(n_samples)#0-n_samples的随机序列,目的是打乱样本
n_train = int(numpy.round(n_samples * (1. - valid_portion)))#训练样本个数
valid_set_x = [train_set_x[s] for s in sidx[n_train:]]
valid_set_y = [train_set_y[s] for s in sidx[n_train:]]
train_set_x = [train_set_x[s] for s in sidx[:n_train]]
train_set_y = [train_set_y[s] for s in sidx[:n_train]]
return (train_set_x,train_set_y), (valid_set_x,valid_set_y), test_set
def prepare_data_tree(seqs, labels):
"""
Create the matrices from the datasets.
This pad each sequence to the same lenght: the lenght of the
longuest sequence or maxlen.
if maxlen is set, we will cut all sequence to this maximum
lenght.
This swap the axis!
"""
x = numpy.zeros((max_len,n_samples)).astype('int64')
x_mask = numpy.zeros((max_len,n_samples)).astype(theano.config.floatX)
for idx,s in enumerate(seqs):
x[:lengths[idx],idx] = s
x_mask[:lengths[idx],idx] = 1
##x_mask: like x but all 1
return x, x_mask, labels
def load_data_tree():
idx_file = open('data/tree/train_idx.txt')
parent_file = open('data/tree/train_idx_parent.txt')
label_file = open('data/tree/train_labels.txt')
idx_array = []
for line in idx_file:
toks = line.split()
idx_array.append([int(tok) for tok in toks])
idx_file.close()
parent_array = []
for line in parent_file:
toks = line.split()
parent_array.append([int(tok) for tok in toks])
parent_file.close()
label_array=[]
for line in label_file:
label_array.append(int(line.strip()))
label_file.close()
return numpy.asarray(idx_array),numpy.asarray(parent_array),numpy.asarray(label_array)
if __name__ == '__main__':
print load_data_tree() |
C | UTF-8 | 2,412 | 3.671875 | 4 | [] | no_license | /* reverseFileHeader.h : Operating System Assignment 1 : Reversing the contents of a text file
*
* Author : Arpit Bhayani
* E-mail : arpit.bhayani@students.iiit.ac.in
* Roll no.: 201305515
*/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
/*
* This function prints out the Usage for the file reversal code.
* It validates the number of command line arguments and provides corressponding usage statements.
* @argument : int argc : number of command line argument passed.
* @returns : void
*/
void printUsage(int);
/*
* This function reverses the buffer "buffer" and stores the reversed buffer into reversedBuffer which is passed as argument.
* @argument : char * reversedBuffer : the buffer in which the rever content will be stored.
* @argument : char * buffer : the buffer of which contents are to be reversed.
* @argumenr : int count : count is the length of the buffer.
* @returns : pointer to reversedBuffer
*/
void reverseFile(char *);
/*
* For debugging only.
* This function prints out the buffer passed from index 0 to length
* @argument : char * buffer : buffer to b printed onto console
* @argument : int length : length of the buffer.
* @returns : void
*
*/
void printBuffer(char * , int);
/*
* This function takes argument as char * which is the input file name
* and returns a pointer to character string which is the output file name in a format specified as below
* If inputFilename = "textfile.txt"
* then outputFilename = "reverse_textfile.txt"
* @argument : char * inputFilename : the path of the file.
* @returns : pointer to the string "reverse_<inputFilename>"
*/
char * getOutputFilename(char * , char *);
/*
* This function reverses the buffer "buffer" and stores the reversed buffer into reversedBuffer which is passed as argument.
* @argument : char * reversedBuffer : the buffer in which the rever content will be stored.
* @argument : char * buffer : the buffer of which contents are to be reversed.
* @argumenr : int count : count is the length of the buffer.
* @returns : pointer to reversedBuffer
*/
char * reverseBuffer(char * , int);
/*
* This function takes argument as char *
* and returns the length of the string.
* If string = "textfile.txt"
* then return value = 12
* @argument : char * string.
* @returns : length of the string
*/
int getLength( char * );
|
TypeScript | UTF-8 | 2,566 | 2.625 | 3 | [] | no_license | import got from 'got';
import async from 'async';
import express from 'express';
import { RequestHandler } from 'express';
import { maxSatisfying } from 'semver';
import { NPMPackage, RemotePackageRoot } from '../types';
import { Logger } from 'pino';
let queue: async.QueueObject<RemotePackageRoot>;
let dependencyTree: RemotePackageRoot;
const MAX_CONCURRENCY = process.env.MAX_CONCURRENCY ?? 10;
/**
* Attempts to retrieve package data from the npm registry and return it
*/
export const getPackage: RequestHandler = async function (
req: express.Request,
res,
next
) {
const { log } = req;
const { name, version } = req.params;
log.info({
message: 'Started retrieving dependencies',
});
queue = async.queue<RemotePackageRoot>((task, done) => {
getDependencies(task, done, log);
}, MAX_CONCURRENCY);
try {
const npmPackage = await got(
`https://registry.npmjs.org/${name}`
).json<NPMPackage>();
log.info({
message: 'Fetching root dependencies',
});
const dependencies = npmPackage?.versions?.[version]?.dependencies ?? {};
dependencyTree = {
name,
version,
dependencies: {},
};
for (const [depName, depVersion] of Object.entries(dependencies)) {
log.info({
message: `Adding work to queue for dependency: ${depName}`,
});
queue.push({
name: depName,
version: depVersion,
dependencies: dependencyTree.dependencies,
});
}
if (queue.length() > 0) {
await queue.drain();
}
log.info({
message: 'Retrieved all dependencies',
});
return res.status(200).json(dependencyTree);
} catch (error) {
return next(error);
}
};
async function getDependencies(
task: RemotePackageRoot,
done: async.ErrorCallback<Error>,
log: Logger
) {
const npmPackage = await got(
`https://registry.npmjs.org/${task.name}`
).json<NPMPackage>();
const selectedVersion = maxSatisfying(
Object.keys(npmPackage.versions),
task.version
);
if (selectedVersion) {
const newDependencies =
npmPackage.versions[selectedVersion].dependencies ?? {};
task.dependencies[task.name] = {
version: selectedVersion,
dependencies: {},
};
for (const [name, version] of Object.entries(newDependencies)) {
log.info({
message: `Adding work to queue for dependency: ${name}`,
});
queue.push({
name,
version,
dependencies: task.dependencies[task.name].dependencies,
});
}
}
done();
}
|
JavaScript | UTF-8 | 1,091 | 2.796875 | 3 | [] | no_license | import React, { Component } from 'react';
class ShelfControl extends Component {
initialBook = this.props.book
state = {
bookShelf: this.initialBook.shelf
}
handleChange = (event) => {
// setState keeps the control button up to date according to changed value
this.setState({bookShelf: event.target.value})
// Provide the changed selection value to the book object
this.initialBook.shelf = event.target.value
this.props.onSelectionChange(this.initialBook)
console.log(this.initialBook)
}
render() {
return(
<div style={{padding: "15px"}}>
<img src={this.initialBook.imageUrl}/>
<p>{this.initialBook.title}</p>
<p>{this.initialBook.author}</p>
<select value={this.state.bookShelf} onChange={this.handleChange}>
<option value="none" disabled>Move to...</option>
<option value="currentlyReading">Currently Reading</option>
<option value="wantToRead">Want to Read</option>
<option value="read">Read</option>
<option value="none">None</option>
</select>
</div>
)
}
}
export default ShelfControl; |
C++ | UTF-8 | 1,375 | 2.796875 | 3 | [] | no_license | #include "police.h"
#include <iostream>
#include <time.h>
#include <string>
using namespace std;
Police::Police()
{
_stressAnalysis = random(10);
_resistanceBribe = random(25);
_catching = random(25);
_searchDrug = random(15);
_posture = random(10);
}
int Police::getResistanceBribe() {return _resistanceBribe;}
int Police::getPosture() {return _posture;}
int Police::getCatching() {return _catching;}
bool Police::check(Smuggler* smuggler)
{
int s = smuggler->getStress();
int d = smuggler->getDocuments();
if (((s+d) - (_stressAnalysis)) > 20)
{
_searchDrug += random(10) + 1;
cout << "Wezwanie psa! Umiejetnosc znalezienia narkotykow policjanta wynosi teraz: " + to_string(_searchDrug) << endl;
}
return (_stressAnalysis < (s + d));
}
bool Police::searchHideout(Smuggler* smuggler)
{
int h = smuggler->getHideout();
int r = 1; //random(4);
return (h == r);
}
bool Police::searchDrug(Smuggler* smuggler)
{
int h = smuggler->getHideDrug();
return (_searchDrug > h);
}
string Police::description()
{
return "STATYSTYKI POLICJANTA:\n"
"Analiza stresu: " + to_string(_stressAnalysis) + "\n" +
"Odpornosc na lapowke: " + to_string(_resistanceBribe) + "\n" +
"Umiejetnosc poscigu: " + to_string(_catching) + "\n" +
"Umiejetnosc szukania narkotykow: " + to_string(_searchDrug) + "\n" +
"Postura: " + to_string(_posture) + "\n\n";
}
|
JavaScript | UTF-8 | 318 | 3.296875 | 3 | [] | no_license | class Animal{
constructor(name = 'noname', age = 0, weight = 0){
this.name = name;
this.age = age;
this.weight = weight;
}
info(){
return `${this.name} is ${this.age} old and weight = ${this.weight} kg`;
}
}
const name = 'Тот кого нельзя называть';
export {Animal, name}; |
C# | UTF-8 | 1,225 | 3.65625 | 4 | [
"MIT"
] | permissive | namespace _10.Explicit_Interfaces
{
using Interfaces;
using Models;
using System;
public class StartUp
{
public static void Main()
{
// PrintNamesAsDifferentInterfaces(); // Both variants work
PrintNamesWithTypeCasting(); // Both variants work
}
private static void PrintNamesWithTypeCasting()
{
var name = Console.ReadLine().Split();
while (name[0] != "End")
{
var human = new Citizen(name[0]);
Console.WriteLine(((IPerson)human).GetName());
Console.WriteLine(((IResident)human).GetName());
name = Console.ReadLine().Split();
}
}
private static void PrintNamesAsDifferentInterfaces()
{
var name = Console.ReadLine().Split();
while (name[0] != "End")
{
IPerson person = new Citizen(name[0]);
Console.WriteLine(person.GetName());
IResident resident = new Citizen(name[0]);
Console.WriteLine(resident.GetName());
name = Console.ReadLine().Split();
}
}
}
}
|
Java | UTF-8 | 810 | 1.835938 | 2 | [
"Apache-2.0"
] | permissive | package com.gzxant.service;
import com.gzxant.base.service.IBaseService;
import com.gzxant.base.vo.DataTable;
import com.gzxant.entity.SysUser;
import com.gzxant.entity.SysUserOffice;
/**
*
* @author chen
* @date 2017/11/16
* <p>
* Email 122741482@qq.com
* <p>
* Describe:
*/
public interface ISysUserOfficeService extends IBaseService<SysUserOffice> {
/**
* 移除组织中的人
* @param officeId
* @param userIds
*/
void removeUsers(Long officeId, Long[] userIds);
/**
* 向组织中添加用户
* @param officeId
* @param userIds
* @param major
*/
void addUsers(Long officeId, Long[] userIds, String major);
/**
* 获取组织的用户列表
* @param dt
* @return
*/
DataTable<SysUser> userList(DataTable dt);
}
|
C# | UTF-8 | 1,661 | 3 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using N_Shared = NameSorter.Shared;
namespace NameSorter.Process
{
/// <summary>
/// <code>Sort by Surname Then Given Name Assistant</code> assists <code>Back Office</code> admin to sort names by surname.
/// --- Function: Adds capability to sort by surname then given name for <code>Back Office</code> object.
/// --- Reference: Design Pattern - Decorator.
/// </summary>
public class SortBySurnameThenGivenNameAssistant : BackOfficeAssistant
{
/// <summary>
/// Constructor.
/// </summary>
/// <param name="admin"><code>Back Office</code> admin.</param>
public SortBySurnameThenGivenNameAssistant(BackOffice admin)
: base(admin)
{
}
/// <summary>
/// Sorts a list of paired data based on surname (key).
/// </summary>
/// <param name="data">Input data as a list of paired data.</param>
/// <returns>Sorted list of paired data.</returns>
public List<Tuple<string, string>> SortBySurnameThenGivenName(List<Tuple<string, string>> data)
{
List<Tuple<string, string>> result = data;
if (_validator.ValidateNullOrEmpty(data) == true)
{
_logger.LogInformation(N_Shared.SharedVar.LOGTITLE_SORTBYSURNAMETHENGIVENNAME, N_Shared.SharedVar.LOGDESC_INFO_SORTBYSURNAMETHENGIVENNAME);
result = result.OrderBy(x => x.Item1)
.ThenBy(x => x.Item2)
.ToList();
}
return result;
}
}
}
|
Java | UTF-8 | 2,808 | 2.03125 | 2 | [] | no_license | package com.sneaker.mall.api.model;
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class Customer extends Company {
/**
* 业务员
*/
private long suid;
/**
* 业务员名称
*/
private String suname;
/**
* 客户类型
*/
private String cctype;
/**
* 客户类型 展示用
*/
private int type;
private String name;
/**
* 仓库ID
*/
private String sid;
/**
* 客户名称
*/
private String ccname;
/**
* 客户id
*/
private long ccid;
/**
* 客户拼音 展示用
*/
private String pinyin;
private String ccpyname;
public String getCctype() {
return cctype;
}
public void setCctype(String cctype) {
this.cctype = cctype;
}
public String getSid() {
return sid;
}
public void setSid(String sid) {
this.sid = sid;
}
public String getSuname() {
return suname;
}
public void setSuname(String suname) {
this.suname = suname;
}
public long getSuid() {
return suid;
}
public void setSuid(long suid) {
this.suid = suid;
}
public void setCcname(String ccname) {
this.ccname = ccname;
}
public String getCcname() {
return ccname;
}
public void setCcid(long ccid) {
this.ccid = ccid;
}
public long getCcid() {
return ccid;
}
public void setPinyin(String ccpyname) {
this.pinyin = ccpyname;
}
public String getPinyin() {
return pinyin;
}
public void setType(int type) {
this.type = type;
}
public int getType() {
return type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setCcpyname(String ccpyname) {
this.ccpyname = ccpyname;
}
public String getCcpyname() {
return ccpyname;
}
}
|
Java | UTF-8 | 1,208 | 3.046875 | 3 | [] | no_license | import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.BorderLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Main {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main window = new Main();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Main() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 860, 468);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout(0, 0));
MyTimer myTimer = new MyTimer();
frame.getContentPane().add(myTimer, BorderLayout.CENTER);
JButton btnNewButton = new JButton("O programie");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
frame.getContentPane().add(btnNewButton, BorderLayout.NORTH);
}
}
|
C# | UTF-8 | 520 | 3.21875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace fibonacci_series
{
class Program
{
static void Main(string[] args)
{
int f1 = 0, f2 = 1, f3 = 0;
Console.Write(f1);
Console.Write(f2);
for(int i=1;i<=7;i++)
{
f3 = f1 + f2;
Console.Write(f3);
f1 = f2;
f2 = f3;
}
}
}
}
|
Markdown | UTF-8 | 10,159 | 3.734375 | 4 | [] | no_license |
##Unit 1 名词、冠词##
###名词的作用:当 主词、补语、受词###
>- 目录
- <a href="#A1">名词的种类</a>
- 普通名词
- 集合名词
- 专有名词
- 物质名词
- 抽象名词
- <a href="#B1">名词的数</a>
- 规则变化的复数名词
- 不规则变化的复数名词
- <a href="#C1">名词的所有格</a>
- <a href="#D1">冠词</a>
- 不定冠词 a / an
- 定冠词 the
<a id="A1"></a>
###一. 名词的种类###
>- **单数 / 复数 名词**
<br/>
>- **普通名词** :book / pencil / dog / .. 等
- 取普通名词造句:
- I like dog ( 我喜欢狗,但是名词在句子里面,要把他的单数或复数表现出来 )
- 所以修改为:
- I like a dog (表示:我喜欢某一只狗)
- I like dogs (表示:我喜欢狗这种动物)
<br />
>- **集合名词**:class / family / audience / ... 等
- <br/>
- class [ 可以表示班级,可以表示班级里的一个或多个学生 ]
- family [ 可以表示家庭,可以表示家庭里的一个或多个成员 ]
- audience [ 可以表示观众,可以表示一个或多个观众 ]
- <br/>
- 例:family 可以表示一个家庭 、或家庭里的成员
- 1. **My family is large** ( 我的大家庭 )
- 此句的family表示的是一个家庭是一个单数名词,所以后面跟be动词 is
- 2. **My family are all early risers** (我的家人都是早起的人)
- 此句的family 表示的是家庭里成员是一个复数名词,所以后面跟be动词 are
<br/>
>- **专有名词**: Bob / Smith / Xuzhiqiao / April / ... 等
- 专有名词是:某个(些)人,地方,机构等专有的名称 (专有名词开头都要大写)。
- 如:Beijing 值地名 。
- 专有名词注意:
- 专有名词前不能加冠词:如: Beijing 前不能加冠词 a 或 an , 后面也不能加s。总不能说有很多个北京吧(因为专有名词数量只有一个)
- 但事情总有例外,有些专有名词前需要加定冠词the, 比如一些组织或国家名前
- 例如:美利坚合众国 the United States of America ( 出自百度翻译 )
<br/>
>- **物质名词**:glass (玻璃) / wood (木材) / paper (纸) / air(空气) / fruit (水果) / .... 等
- 物质名词表示无法分为个体的实物
- 物质名词是不能有 单复数 或 a an
- <br/>
- 例:如果想表示 “多个木材” 该怎样表示,直接加s吗,,但 wood 直接加s 就成了森林,woods (森林)
- 如要表示:一块玻璃、一块木材,只能用一些固定的表现形式:
- **格式:数字 + 容器(度量衡) + of + 物质名词**
- 实例: **a piece of wood** ( 一块木材 )
- 实例: **two baskets of fruit** ( 两箩水果 )
<br/>
>- **抽象名词**:beauty (美丽) / honesty (诚实) / love (爱) / ... 等
- 抽象名词表示动作、状态、品质、感情等抽象概念
<a id="B1"></a>
<br/>
###二. 名词的数###
>- 名词分为:**可数名词** / **不可数名词**
>- 复数名词的变化分为:**规则变化** 和 **不规则变化**
<br/>
>- **规则变化**的复数名词
- **大部分**名词字尾直接加 s
- **小部分**名词字尾为 **s / sh / ch / x / o 就加 es [ ɪz ]**
- 例:class 加 es => classes [ clasɪz ]
- 例:bench 加 es => benches [ bɪnʧ ɪz ]
- <br />
- **名词字尾为子音 + o 时**,加的 es [ ɪz ] 变为 es [ z ]
- 例:tomato 加 es => tomatoes [ təˈmeɪtoʊ ]
- 注意:名词字尾为o时,有可恶的例外:photos / pianos
- <br />
- **名词字尾为子音+y时**,去 y 加 ies (因为 y 和 i 相同发音,同时,因为 ies 的 i 发 [ ɪ ], es 改为发 [ z ])
- 例:baby 加 es => babies [ bebɪz ]
- 例:city 加 es => cities [ sɪtɪz ]
- <br />
- **名词字尾为 f 或 fe 时** ,去掉 f / fe 加 ves
- 例:half 去 f 加 ves => halves [ hævz ]
- 为什么去掉 f 或 fe ,很简单因为如果这个单词结尾是[ f ] ,复数名词 [ s ] ,[ f ] [ s ] 根本读不了(但是也有例外)
- 但去掉 f / fe 后,为什么是加 ves 而不是 aes / bes / ces ? 原因是为了保持单词本身的读音,
结尾字音 [ f ] 的相对 有声子音是 [ v ] ,所以他们两个读音最像
- 注意:有例外:名词字尾为 f 时,有直接就加 s 的词。如:handkerchiefs \ chiefs \ roofs
<br/>
>- **不规则变化**的复数名词
- 不规则变化复数名词的变化有两种:名词字尾改为:**en / ren** 或 **改变单词的母音**
<br/>
- <br/>
- **名词字尾为:en / ren**
- 例:ox => oxen
- 例:child => children
- <br/>
- **改变单词母音:**
- 例:man => men
- 例:woman [ ˈwʊmən ] => women [ ˈwɪmɪn ]
- 例:goose => geese
- 例:tooth => teeth
- 例:mouse => mice
<br/>
>- 单复数同形
- 单复数同形指的是:一个单词无论是单数或复数都用同一个单词,但这种单复数同形只是指数量上的,而不是种类上的
- 例:fish / deer / sheep / Chinses / Japanese
- 例:表示鱼的数量:
- one fish (一条鱼)
- two fish (两条鱼)
- <br/>
- 前面说过,单复数同形只能用在名词在数量上用同一个单词(如一条或多条鱼用同一个fish),但到名词的 种类(如有两种鱼) 上就该按照正常的复数形式变化了
- 例:表示鱼的种类
- **one kind of fish** ( 一种鱼类 )
- **three kinds of fishes** ( 三种鱼类 )
<a id="C1"></a>
<br/>
###三. 名词的所有格###
>- 名词的所有格表示所属关系,它分 ’s 所有格和 of 所以格两种形式
<br/>
>- **单数名词所有格** => 名词 ′ s ( ′ s 代表“的”,如:boy ′ s 男孩的)
- 例:the **programmer ′s** computer ( 那个程序员的电脑 )
<br/>
>- **复数名词所有格** => 名词 ′ ( ′ 代表“的”,如:boys ′ 男孩的 )
- 例:**a girls′ school** ( 一所女生们的学校 (女校))
- 例:**these students′ teacher** ( 这些学生们的老师 )
- <br/>
- 但是复数名词我们知道有:**规则复数名词** 和 **不规则复数名词**
- **规则复数名词**的每个词最后都是s 所以格式固定为: xxxxs ′
- **不规则复数名词**后面是没有s的, 所以 child => children 所有格 == children ′s
- <br />
- 小结:无论是规则复数 或是 无规则复数 名词,单词后有s ,就只能加 ′ ,如没有 s , 就加 ′ s , 来代表名词的所有格
<br/>
>- 特别注意所有格的用法
- **共同所有格** 和 **个别所有格**
- <br/>
- 共同所有格 => 名词 + 名词 + ... + 名词's
- 个别所有格 => 名词's + 名词's + ... + 名词's
- <br/>
- 共同所有格示例:
- mao and dog's father is a scientist (mao和dog的父亲是科学家)
- mao 和 dog 的父亲是他们两共同的父亲,只需一个 's 就能代表到: “mao的” "dog的"
- <br/>
- 个别所有格
- mao's and dog's fathers are scientists (mao的 和 dog的 父亲是科学家)
- 用了两次 's , father 也加 s 了 , be动词也变成复数形式了
<br/>
>- 名词所有格 **of** 形式
- 名词的所有格形式除 **'s** 外,还可用 **of**+名词构成短语修饰前面的名词或表示两个名词间的所有关系。
- 一般, **'s** 所有格多用于**有生命的东西**,**of** 所有格多用于**无生命的东西**,但也有许多例外。
- 格式:B of A
- <br/>
- 例:battery of phone (手机的电池)
- 例:engine of car (汽车的发动机)
- 上面的例是不能按照中文的思想去理解的,因为中文是从前到后的理解句子,但英文是把重要的单词先放前面( 比如汽车的发动机,重点是发动机,所以engine放前面 )
- <br/>
- 例:the legs of the table (桌子的脚)
- 例:the door of the car (车门)
- 是不是觉得少了个 "的" , 车的门? 变通一点不用那么死板的翻译
<a id="D1"></a>
<br/>
###四. 冠词###
>- 冠词通常放在名词前,用来修饰名词(其实就是把名词讲清楚)
>- 冠词分为:
- **不定冠词**: **a / an**
- **定冠词** : **the**
<br/>
>- 不定冠词 **a / an** 用法:
- a + **子音**开头的单数名词
- an + **母音**开头的单数名词 (母音开头为:**a , e , i , o , u** )
- <br/>
- 例: I have **a** computer
- 还有一种情况:a young man
- 如果有一个形容词在名词前,那么就认形容词的开头子母音
- 例: I hava **an** apple
- <br/>
- 为什么不定冠词 a 后面要是子音而不是母音呢?
- 因为 a 的音标是 [ ə ],如果后面的单词开头又是母音的话,他们两个母音就会撞在一起,无法连读。
<br/>
>- 不定冠词 **a / an** 的发音:
- **a [ ə ]** , 如果 a 作强调则发 **a [ e ]**
- **an [ ən ]**, 如果 an 作强调则发 **a [ æn ]**
- <br/>
- 例:I read **a[ə]** novel. (我读了一本小说)
- 例:I read **a[e]** novel , not two ( 我读了一本小说,不是两本 )
- 强调我只读了一本小说,不是两本,所以表示一本的 a 要发作 a [ e ]
<br/>
>- 定冠词 the 用法:
- 中文解释:这个、这些、那个、那些。(在有时翻译时是忽略不译的)
- <br/>
- **the[ ðɪ ]** + 母音开头的单词
- **the[ ðə ]** + 子音开头的单词
- <br/>
- 例:Please shut the door
- 例:The rich aren't always happy
- <br/>
- the + 形容词,泛指 “ 什么什么的人 ”,代表复数。
- 例:the young (所有的年轻人)
- 例:the old (所有的老年人)
- 例:the rich (所有的有钱人)
|
PHP | UTF-8 | 1,268 | 2.625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers\UserAddress;
use App\Http\Controllers\Controller;
use App\Http\Requests\Address;
use App\Users;
use Illuminate\Http\Request;
class AddAddressController extends Controller
{
/**
* Where to redirect users after login.
*
* @var string
*/
protected $redirectTo = '/';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
public function index(Request $request)
{
$userID = $request->route('var1');
return view('useraddress.add', ['userID' => $userID]);
}
public function add(Address $request)
{
if ($request->post()) {
$userID = $request->route('var1');
$Users = new Users();
$data = [
'id' => $userID,
'street' => $request->street,
'city' => $request->city,
'zipcode' => $request->zipcode
];
if ($Users->addUserAddress($data)) {
$request->session()->flash('success', 'Pomyślnie dodano adres użytkownika');
return redirect('/users/details/' . $userID);
}
}
}
}
|
Java | UTF-8 | 839 | 3.203125 | 3 | [] | no_license | /*
Christos Perchanidis
AEM: 3194
pmchrist@csd.auth.gr
Aristotle University of Thessaloniki
May 2019
*/
import java.util.ArrayList;
import java.util.TreeSet;
/**
*
* This class creates graph that we use in the whole project later
*
*/
class allEdges{
/**
*
* Finding graph that connects all Ants
*
* @param Ants set of points to connect
* @return TreeSet of edges in a graph
*/
public TreeSet<GraphEdge> getEdges(ArrayList<Ant> Ants){
//We need edges sorted, therefore using TreeSet
TreeSet<GraphEdge> result = new TreeSet<>();
//Add all possible Edges between all Ants
for (int i=0; i<Ants.size(); i++){
for (int j=i+1; j<Ants.size(); j++){
result.add(new GraphEdge(Ants.get(i), Ants.get(j)));
}
}
return result;
}
} |
Java | UTF-8 | 29,905 | 2.390625 | 2 | [] | no_license | package com.lwxf.newstore.webapp.common.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.sql.*;
import java.util.*;
import java.util.Date;
import com.lwxf.commons.constant.CommonConstant;
import com.lwxf.commons.utils.DateUtil;
import com.lwxf.commons.utils.LwxfStringUtils;
/**
* 功能:自定义根据表名生成实体工具
*
* @author:renzhongshan(d3shan@126.com)
* @create:2018-05-18 11:26:30
* @version:2018 Version:1.0
* @company:老屋新房 Created with IntelliJ IDEA
*/
public class GenEntity {
/**
* 数据库连接
*/
private static final String URL = "jdbc:mysql://192.168.1.4:3306/newstore?useUnicode=true&characterEncoding=UTF-8";
private static final String NAME = "root";
private static final String PASS = "lwxf@123";
private static final String DRIVER = "com.mysql.jdbc.Driver";
/**
* 不允许修改的列
*/
Map<String, String> mapDisabledUpdate = new HashMap<>();
/**
* 不允许修改列属性
*/
List<String> disableUpdateCol = new ArrayList<>();
/**
* 外键注解
*/
Map fkMap = new HashMap<String, String>();
/**
* 约束注解
*/
Map uqMap = new HashMap<String, String>();
/**
* 约束注解串
*/
String uqStr = "";
/**
* 用户名
*/
private String username = "easypm4_schema";
/**
* 包的路径
*/
private String packageUrl = "com.lwxf.newstore.webapp.domain.entity.";
/**
* 类输出路径
*/
private String outputPath = "E:\\workspace\\newstore\\codes\\lwxf_newstore\\trunk\\src\\main\\java\\com\\chuanghai\\easypm\\webapp\\domain\\entity\\";
/**
* 表名
*/
private String tablename = "";
/**
* 列名数组
*/
private String[] colnames;
/**
* 数据库列名数组
*/
private String[] dbColNames;
/**
* 列名类型数组
*/
private String[] colTypes;
/**
* 列名描述数组
*/
private String[] colDescs;
/**
* 列名大小数组
*/
private int[] colSizes;
/**
* 是否允许为空
*/
private String[] colIsNullAble;
/**
* 默认值
*/
private String[] colDefaultValue;
/**
* 表的主键信息注解
*/
private String primaryConstraints = "";
/**
* 是否需要导入包java.util.*
*/
private boolean importUtil = true;
/**
* 是否需要导入包java.sql.*
*/
private boolean importSql = true;
private String author;
/**
* 构造函数
*/
public GenEntity(final String tName, final String packageName, final String appointPath, final Map<String, String> mapDisabledUpdate) {
this(tName,packageName,appointPath,mapDisabledUpdate,"renzhongshan(d3shan@126.com)");
}
/**
* 构造函数
*/
public GenEntity(final String tName, final String packageName, final String appointPath, final Map<String, String> mapDisabledUpdate, String author) {
//表名转化为小写
this.tablename = LwxfStringUtils.lowerCase(tName);
this.packageUrl = this.packageUrl + packageName;
this.outputPath = this.outputPath + packageName;
this.mapDisabledUpdate = mapDisabledUpdate;
this.author = author;
this.disableUpdateCol = getDisableUpdateCol();
if (appointPath != null) {
this.outputPath = appointPath + "\\" + packageName;
}
//创建连接
Connection con = null;
Statement statement = null;
StringBuilder fkSqlSb = new StringBuilder();
fkSqlSb.append("select t.CONSTRAINT_NAME,t.COLUMN_NAME,t.REFERENCED_TABLE_NAME,t.REFERENCED_COLUMN_NAME from INFORMATION_SCHEMA.KEY_COLUMN_USAGE t where t.TABLE_SCHEMA='")
.append(username)
.append("' and t.TABLE_NAME='")
.append(tablename)
.append("' and t.REFERENCED_TABLE_NAME is not null");
try {
try {
Class.forName(DRIVER);
con = DriverManager.getConnection(URL, NAME, PASS);
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
/*************************取外键信息 start *********************/
String key;
String className;
String referencedColumnName;
String fkAnnotation;
if (con != null) {
statement = con.createStatement();
}
String uqSql;
ResultSet uqRs = null;
String uKey;
String uValue;
StringBuffer uqTempSb;
Iterator iterator;
String uqTemp;
DatabaseMetaData databaseMetaData = null;
ResultSet pkRs;
List<String> pkList = new ArrayList<>();
ResultSet rs = null;
int size;
int i;
String content;
String outPutFileName;
ResultSet fkRs = null;
if (statement != null) {
try {
fkRs = statement.executeQuery(fkSqlSb.toString());
} catch (SQLException e) {
e.printStackTrace();
}
}
try {
if (fkRs != null) {
while (fkRs.next()) {
key = initcapCol(fkRs.getString("COLUMN_NAME"));
className = initcap(fkRs.getString("REFERENCED_TABLE_NAME"));
referencedColumnName = initcapCol(fkRs.getString("REFERENCED_COLUMN_NAME"));
fkAnnotation = "@ForeignKey(refEntityClass = " + className + ".class,refFieldName = \"" + referencedColumnName + "\")";
fkMap.put(key, fkAnnotation);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fkRs != null) {
fkRs.close();
}
}
/*************************取外键信息 end *********************/
/*************************取约束信息 start**********************/
uqSql = "select t.CONSTRAINT_NAME,t.COLUMN_NAME from INFORMATION_SCHEMA.KEY_COLUMN_USAGE t where lower(t.CONSTRAINT_NAME) like 'u%' and t.TABLE_SCHEMA='" + username + "' and t.TABLE_NAME='" + tName + "'";
if (statement != null) {
uqRs = statement.executeQuery(uqSql);
}
if (uqRs != null) {
while (uqRs.next()) {
uKey = uqRs.getString("CONSTRAINT_NAME");
String uTempValue = "\"" + initcapCol(uqRs.getString("COLUMN_NAME")) + "\"";
uValue = (String) uqMap.get(uKey);
if (uValue == null) {
uqMap.put(uKey, uTempValue);
} else {
uValue = uValue .concat( ",").concat(uTempValue);
uqMap.put(uKey, uValue);
}
}
uqRs.close();
}
uqTempSb = new StringBuffer();
iterator = uqMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry) iterator.next();
Object val = entry.getValue();
uqTempSb.append("@UniqueConstraint(fieldNames = {")
.append(String.valueOf(val))
.append("}),");
}
uqTemp = uqTempSb.toString();
if (uqTemp.length() > 0) {
uqTemp = uqTemp.substring(0, uqTemp.length() - 1);
uqStr = "uniqueConstraints = {";
uqStr = uqStr + uqTemp;
uqStr = uqStr + "},";
}
/*************************取约束信息 end **********************/
if (con != null) {
databaseMetaData = con.getMetaData();
}
if (databaseMetaData != null) {
pkRs = databaseMetaData.getPrimaryKeys(null, "%", tablename);
while (pkRs.next()) {
pkList.add(initcapCol(pkRs.getString("COLUMN_NAME")));
System.out.println("主键:" + pkRs.getString("COLUMN_NAME"));
}
if (pkList.size() > 0) {
if (pkList.size() > 1) {
primaryConstraints = " primaryConstraints = @PrimaryConstraint(fieldNames = {";
for (String col : pkList) {
primaryConstraints = primaryConstraints .concat("\"") .concat(col).concat("\",");
}
primaryConstraints = primaryConstraints.substring(0, primaryConstraints.length() - 1);
primaryConstraints = primaryConstraints + "}), ";
}
}
rs = databaseMetaData.getColumns(null, "%", tablename, "%");
}
//直接取表字段
System.out.println("表名:" + tablename + "\t\n表字段信息:");
if (rs != null) {
rs.last();
size = rs.getRow();
rs.beforeFirst();
dbColNames = new String[size];
colnames = new String[size];
colTypes = new String[size];
colSizes = new int[size];
colDescs = new String[size];
colIsNullAble = new String[size];
colDefaultValue = new String[size];
i = 0;
while (rs.next()) {
System.out.println(rs.getString("COLUMN_NAME") + "----" + rs.getString("REMARKS") + "----" + rs.getString("TYPE_NAME") + "--COLUMN_SIZE:" + rs.getInt("COLUMN_SIZE"));
dbColNames[i] = rs.getString("COLUMN_NAME");
colnames[i] = initcapCol(rs.getString("COLUMN_NAME"));
colTypes[i] = rs.getString("TYPE_NAME");
colDescs[i] = rs.getString("REMARKS");
colSizes[i] = rs.getInt("COLUMN_SIZE");
colIsNullAble[i] = rs.getString("IS_NULLABLE");
colDefaultValue[i] = rs.getString(13);
if (CommonConstant.STRING_DATETIME.equalsIgnoreCase(colTypes[i])) {
importUtil = true;
}
if (CommonConstant.STRING_IMAGE.equalsIgnoreCase(colTypes[i]) || CommonConstant.STRING_TEXT.equalsIgnoreCase(colTypes[i])) {
importSql = true;
}
i++;
}
}
content = parse(colnames, colTypes, colSizes);
try {
File directory = new File(outputPath);
try {
directory.mkdirs();
} catch (Exception e) {
e.printStackTrace();
}
outPutFileName = outputPath + "\\" + initcap(tablename) + ".java";
System.out.println("输出路径:" + outPutFileName);
File file = new File(outPutFileName);
try (FileOutputStream fop = new FileOutputStream(file)) {
// if file doesn't exists, then create it
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
// get the content in bytes
byte[] contentInBytes = content.getBytes(Charset.defaultCharset());
fop.write(contentInBytes);
fop.flush();
fop.close();
System.out.println("写文件内容完成");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (con != null) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
/**
* 功能:生成实体类主体代码
*
* @param colnames
* @param colTypes
* @param colSizes
* @return
*/
private String parse(String[] colnames, String[] colTypes, int[] colSizes) {
StringBuffer sb = new StringBuffer();
//判断是否导入工具包
sb.append("package ").append(packageUrl).append(";\r\n");
if (importUtil) {
sb.append("import java.util.*;\r\n");
}
if (importSql) {
sb.append("import java.sql.*;\r\n");
}
sb.append("import java.util.Date;\r\n");
sb.append("import java.util.Arrays;\r\n");
sb.append("import java.util.List;\r\n");
sb.append("\r\n");
sb.append("import com.lwxf.mybatis.utils.TypesExtend;\r\n");
sb.append("import com.lwxf.commons.exception.ErrorCodes;\r\n");
sb.append("import com.lwxf.commons.utils.DataValidatorUtils;\r\n");
sb.append("import com.lwxf.commons.utils.LwxfStringUtils;\r\n");
sb.append("import com.lwxf.mybatis.annotation.Table;\r\n");
sb.append("import com.lwxf.mybatis.annotation.Column;\r\n");
if (uqStr.length() > 0) {
sb.append("import com.lwxf.mybatis.annotation.UniqueConstraint;\r\n");
}
if (fkMap.size() > 0) {
sb.append("import com.lwxf.mybatis.annotation.ForeignKey;\r\n");
}
sb.append("\r\n");
if (createExtendsIdEntity().length() > 0) {
sb.append("import com.lwxf.newstore.webapp.domain.entity.base.IdEntity;\r\n");
}
sb.append("import com.lwxf.mybatis.utils.MapContext;\r\n");
sb.append("import com.lwxf.newstore.webapp.common.result.RequestResult;\r\n");
sb.append("import com.lwxf.newstore.webapp.common.result.ResultFactory;\r\n");
//注释部分
sb.append("/**\r\n");
sb.append(" * 功能:").append(tablename).append(" 实体类\r\n");
sb.append(" *\r\n");
sb.append(" * @author:").append(this.author).append("\r\n");
sb.append(" * @created:" + DateUtil.dateTimeToString(new Date(), "yyyy-MM-dd hh:mm") + " \r\n");
sb.append(" * @version:2018 Version:1.0 \r\n");
sb.append(" * @company:老屋新房 Created with IntelliJ IDEA" + " \r\n");
sb.append(" */ \r\n");
//实体表注解
sb.append("@Table(name = \"" + tablename + "\"," + primaryConstraints + uqStr + "displayName = \"" + tablename + "\")");
//实体部分
sb.append("\r\npublic class " + initcap(tablename) + createExtendsIdEntity() + " {\r\n");
if (createExtendsIdEntity().length() > 0) {
sb.append("\tprivate static final long serialVersionUID = 1L;\r\n");
}
//属性
processAllAttrs(sb);
sb.append("\r\n");
sb.append(" public " + initcap(tablename) + "() { \r\n");
sb.append(" } \r\n");
sb.append("\r\n");
//验证方法生成
processValidate(sb);
processValidateMap(sb);
sb.append("\r\n");
//get set方法
processAllMethod(sb);
sb.append("}\r\n");
return sb.toString();
}
private void processValidate(StringBuffer sb) {
//验证头
sb.append("\tpublic RequestResult validateFields() {\r\n");
sb.append("\t\tMap<String, String> validResult = new HashMap<>();\r\n");
for (int i = 0; i < colnames.length; i++) {
//id不生成
if ("id".equalsIgnoreCase(colnames[i])) {
continue;
}
//验证体开始
if ("bigint".equalsIgnoreCase(colTypes[i]) || "INT UNSIGNED".equalsIgnoreCase(colTypes[i]) || "INT".equalsIgnoreCase(colTypes[i]) ||
"tinyint".equalsIgnoreCase(colTypes[i]) || "TINYINT UNSIGNED".equalsIgnoreCase(colTypes[i]) || "BIGINT UNSIGNED".equalsIgnoreCase(colTypes[i]) ||
"bit".equalsIgnoreCase(colTypes[i]) || "datetime".equalsIgnoreCase(colTypes[i])) {
//是否允许为空
if ("NO".equalsIgnoreCase(colIsNullAble[i])) {
sb.append("\t\tif (this." + colnames[i] + " == null) {\r\n");
sb.append("\t\t\tvalidResult.put(\"" + colnames[i] + "\", ErrorCodes.VALIDATE_NOTNULL);\r\n");
sb.append("\t\t}\r\n");
}
}
//验证体开始
if ("varchar".equalsIgnoreCase(colTypes[i]) || "char".equalsIgnoreCase(colTypes[i])) {
//是否允许为空
if ("NO".equalsIgnoreCase(colIsNullAble[i])) {
sb.append("\t\tif (this." + colnames[i] + " == null) {\r\n");
sb.append("\t\t\tvalidResult.put(\"" + colnames[i] + "\", ErrorCodes.VALIDATE_NOTNULL);\r\n");
sb.append("\t\t}");
//长度校验
sb.append("else{\r\n " +
"\t\t\tif (LwxfStringUtils.getStringLength(this." + colnames[i] + ") > " + colSizes[i] + ") {\r\n");
sb.append("\t\t\t\tvalidResult.put(\"" + colnames[i] + "\", ErrorCodes.VALIDATE_LENGTH_TOO_LONG);\r\n");
sb.append("\t\t\t}\r\n");
//特殊验证生成
sb.append(generateSpecialValidator(colnames[i], true));
sb.append("\t\t}\r\n");
} else {
//长度校验
sb.append("\t\tif (LwxfStringUtils.getStringLength(this." + colnames[i] + ") > " + colSizes[i] + ") {\r\n");
sb.append("\t\t\tvalidResult.put(\"" + colnames[i] + "\", ErrorCodes.VALIDATE_LENGTH_TOO_LONG);\r\n");
sb.append("\t\t}\r\n");
//特殊验证生成
sb.append(generateSpecialValidator(colnames[i], true));
}
}
}
sb.append("\t\tif(validResult.size()>0){\n")
.append("\t\t\treturn ResultFactory.generateErrorResult(ErrorCodes.VALIDATE_ERROR,validResult);\n")
.append("\t\t}else {\n")
.append("\t\t\treturn null;\n")
.append("\t\t}\r\n");
sb.append("\t}\r\n");
}
/**
* 生成特殊情况验证
*
* @param key 验证的字段名
* @param flag 不带else
* @return
*/
private String generateSpecialValidator(String key, boolean flag) {
StringBuffer sb = new StringBuffer();
if ("email".equalsIgnoreCase(key)) {
if (flag) {
//email校验
sb.append("\t\t\telse if(!ValidateUtils.isEmail(this." + key + ")){\r\n")
.append("\t\t\t\tvalidResult.put(\"" + key + "\", ErrorCodes.VALIDATE_INVALID_EMAIL);\r\n")
.append("\t\t\t}\r\n");
} else {
//email校验
sb.append("\t\t\telse if(!ValidateUtils.isEmail(map.getTypedValue(\"" + key + "\",String.class))){\r\n")
.append("\t\t\t\tvalidResult.put(\"" + key + "\", ErrorCodes.VALIDATE_INVALID_EMAIL);\r\n")
.append("\t\t\t}\r\n");
}
}
if ("mobile".equalsIgnoreCase(key)) {
if (flag) {
//mobile校验
sb.append("\t\tif(this." + key + "!=null){\r\n")
.append("\t\t\tif(!ValidateUtils.isMobile(this." + key + ")){\r\n")
.append("\t\t\t\tvalidResult.put(\"" + key + "\", ErrorCodes.VALIDATE_INVALID_MOBILE_NO);\r\n")
.append("\t\t\t}\r\n")
.append("\t\t}\r\n");
} else {
//mobile校验 if(map.get("mobile")!=null) {}再执行
sb.append("\t\t\telse if(!ValidateUtils.isMobile(map.getTypedValue(\"" + key + "\",String.class))){\r\n")
.append("\t\t\t\tvalidResult.put(\"" + key + "\", ErrorCodes.VALIDATE_INVALID_MOBILE_NO);\r\n")
.append("\t\t\t}\r\n");
}
}
return sb.toString();
}
private List<String> getDisableUpdateCol() {
List<String> disableUpdateColTmp;
List<String> disableUpdateCol = new ArrayList<>();
String s = mapDisabledUpdate.get(tablename);
if (s != null) {
disableUpdateColTmp = Arrays.asList(s.split(","));
int count = disableUpdateColTmp.size();
for (int i = 0; i < count; i++) {
disableUpdateCol.add(i, initcapCol(disableUpdateColTmp.get(i)));
}
}
return disableUpdateCol;
}
/**
* 生成MapContext验证方法
*
* @param sb
*/
private void processValidateMap(StringBuffer sb) {
//1.2. 处理不需要更新的字段
List<String> disableUpdateCol = getDisableUpdateCol();
//2. 验证有没有多余的参数
int colLen = colnames.length;
StringBuffer psSb = new StringBuffer();
for (int j = 0; j < colLen; j++) {
//如果包含在不更新字段里面,就不再生成
if (disableUpdateCol.contains(colnames[j])) {
continue;
}
psSb.append("\"")
.append(colnames[j])
.append("\",");
}
String tmpStr = psSb.toString();
int len = tmpStr.length();
if (len > 1) {
tmpStr = tmpStr.substring(0, len - 1);
}
sb.append("\r\n")
.append("\tprivate final static List<String> propertiesList = Arrays.asList(" + tmpStr + ");\r\n")
.append("\r\n")
.append("\tpublic static RequestResult validateFields(MapContext map) {\r\n")
.append("\t\tMap<String, String> validResult = new HashMap<>();\r\n")
.append("\t\tif(map.size()==0){\r\n")
.append("\t\t\treturn ResultFactory.generateErrorResult(\"error\",ErrorCodes.VALIDATE_NOTNULL);\r\n")
.append("\t\t}\r\n")
.append("\t\tboolean flag;\r\n")
.append("\t\tSet<String> mapSet = map.keySet();\r\n")
.append("\t\tflag = propertiesList.containsAll(mapSet);\r\n")
.append("\t\tif(!flag){\r\n")
.append("\t\t\treturn ResultFactory.generateErrorResult(\"error\",ErrorCodes.VALIDATE_ILLEGAL_ARGUMENT);\r\n")
.append("\t\t}\r\n");
for (int i = 0; i < colnames.length; i++) {
//id不生成
if ("id".equalsIgnoreCase(colnames[i])) {
continue;
}
//不需要更新的列跳过
if (disableUpdateCol != null && disableUpdateCol.size() > 0) {
if (disableUpdateCol.contains(colnames[i])) {
continue;
}
}
String validatorMethodName = "";
//开始生成数据格式校验
if ("BigDecimal".equals(sqlTypeToJavaType(colTypes[i], colSizes[i]))) {
validatorMethodName = "isDecmal4(";
}
if ("Long".equals(sqlTypeToJavaType(colTypes[i], colSizes[i]))) {
validatorMethodName = "isLong(";
}
if ("Float".equals(sqlTypeToJavaType(colTypes[i], colSizes[i]))) {
validatorMethodName = "isFloat(";
}
if ("Integer".equals(sqlTypeToJavaType(colTypes[i], colSizes[i]))) {
validatorMethodName = "isInteger1(";
}
if ("Short".equals(sqlTypeToJavaType(colTypes[i], colSizes[i]))) {
validatorMethodName = "isShort1(";
}
if ("Byte".equals(sqlTypeToJavaType(colTypes[i], colSizes[i]))) {
validatorMethodName = "isByte1(";
}
if ("Boolean".equals(sqlTypeToJavaType(colTypes[i], colSizes[i]))) {
validatorMethodName = "isBoolean(";
}
if ("Date".equals(sqlTypeToJavaType(colTypes[i], colSizes[i]))) {
validatorMethodName = "isDate(";
}
if (validatorMethodName.length() > 0) {
sb.append("\t\tif(map.containsKey(\"" + colnames[i] + "\")) {\r\n");
sb.append("\t\t\tif (!DataValidatorUtils." + validatorMethodName + "map.getTypedValue(\"" + colnames[i] + "\",String.class))) {\r\n");
sb.append("\t\t\t\tvalidResult.put(\"" + colnames[i] + "\", ErrorCodes.VALIDATE_INCORRECT_DATA_FORMAT);\r\n");
sb.append("\t\t\t}\r\n");
sb.append("\t\t}\r\n");
}
}
for (int i = 0; i < colnames.length; i++) {
//id不生成
if ("id".equalsIgnoreCase(colnames[i])) {
continue;
}
if (disableUpdateCol != null) {
if (disableUpdateCol.contains(colnames[i])) {
continue;
}
}
//验证体开始
if ("bigint".equalsIgnoreCase(colTypes[i]) || "INT UNSIGNED".equalsIgnoreCase(colTypes[i]) || "INT".equalsIgnoreCase(colTypes[i]) ||
"tinyint".equalsIgnoreCase(colTypes[i]) || "TINYINT UNSIGNED".equalsIgnoreCase(colTypes[i]) || "BIGINT UNSIGNED".equalsIgnoreCase(colTypes[i]) ||
"bit".equalsIgnoreCase(colTypes[i]) || "datetime".equalsIgnoreCase(colTypes[i])) {
//是否允许为空
if ("NO".equalsIgnoreCase(colIsNullAble[i])) {
sb.append("\t\tif(map.containsKey(\"" + colnames[i] + "\")) {\r\n");
sb.append("\t\t\tif (map.get(\"" + colnames[i] + "\") == null) {\r\n");
sb.append("\t\t\t\tvalidResult.put(\"" + colnames[i] + "\", ErrorCodes.VALIDATE_NOTNULL);\r\n");
sb.append("\t\t\t}\r\n");
sb.append("\t\t}\r\n");
}
}
//验证体开始
if ("varchar".equalsIgnoreCase(colTypes[i]) || "char".equalsIgnoreCase(colTypes[i])) {
//是否允许为空
if ("NO".equalsIgnoreCase(colIsNullAble[i])) {
sb.append("\t\tif(map.containsKey(\"" + colnames[i] + "\")) {\r\n");
sb.append("\t\t\tif (map.getTypedValue(\"" + colnames[i] + "\",String.class) == null) {\r\n");
sb.append("\t\t\t\tvalidResult.put(\"" + colnames[i] + "\", ErrorCodes.VALIDATE_NOTNULL);\r\n");
sb.append("\t\t\t}");
//长度校验
sb.append("else{\r\n" +
" \t\t\t\tif (LwxfStringUtils.getStringLength(map.getTypedValue(\"" + colnames[i] + "\",String.class)) > " + colSizes[i] + ") {\r\n");
sb.append("\t\t\t\t\tvalidResult.put(\"" + colnames[i] + "\", ErrorCodes.VALIDATE_LENGTH_TOO_LONG);\r\n");
sb.append("\t\t\t\t}\r\n");
//特殊验证生成
sb.append(generateSpecialValidator(colnames[i], false));
sb.append("\t\t\t}\r\n");
sb.append("\t\t}\r\n");
} else {
sb.append("\t\tif(map.containsKey(\"" + colnames[i] + "\")) {\r\n");
//长度校验
sb.append("\t\t\tif (LwxfStringUtils.getStringLength(map.getTypedValue(\"" + colnames[i] + "\",String.class)) > " + colSizes[i] + ") {\r\n");
sb.append("\t\t\t\tvalidResult.put(\"" + colnames[i] + "\", ErrorCodes.VALIDATE_LENGTH_TOO_LONG);\r\n");
sb.append("\t\t\t}\r\n");
//特殊验证生成
sb.append(generateSpecialValidator(colnames[i], false));
sb.append("\t\t}\r\n");
}
}
}
sb.append("\t\tif(validResult.size()>0){\n")
.append("\t\t\treturn ResultFactory.generateErrorResult(ErrorCodes.VALIDATE_ERROR,validResult);\n")
.append("\t\t}else {\n")
.append("\t\t\treturn null;\n")
.append("\t\t}\r\n");
sb.append("\t}\r\n");
}
/**
* 只有id为Long的才继承 IdEntity
* @return
*/
private String createExtendsIdEntity() {
String r = "";
for (int i = 0; i < colnames.length; i++) {
//id不生成
if ("id".equalsIgnoreCase(colnames[i]) && "String".equals(sqlTypeToJavaType(colTypes[i], colSizes[i]))) {
r = " extends IdEntity ";
break;
}
}
return r;
}
private String getDisableUpdateColStr(String name) {
if (this.disableUpdateCol != null) {
if (disableUpdateCol.indexOf(name)>-1) {
return "updatable = false,";
}
}
return "";
}
/**
* 功能:生成所有属性
*
* @param sb
*/
private void processAllAttrs(StringBuffer sb) {
for (int i = 0; i < colnames.length; i++) {
//id不生成
if ("id".equalsIgnoreCase(colnames[i])) {
continue;
}
sb.append("\t@Column(" + getJavaSqlType(colTypes[i]) + "," + getDbColLength(colTypes[i], colSizes[i]) + getDefaultValue(colDefaultValue[i]) + getNullAble(colIsNullAble[i]) + getDisableUpdateColStr(colnames[i]) + "name = \"" + dbColNames[i] + "\",displayName = \"" + colDescs[i] + "\")\r\n");
//生成外键注解
String fkString = (String) fkMap.get(colnames[i]);
if (fkString != null) {
sb.append("\t" + fkString + "\r\n");
}
sb.append("\tprivate " + sqlTypeToJavaType(colTypes[i], colSizes[i]) + " " + colnames[i] + ";\r\n");
}
}
/**
* varchar设置长度
* @param sqlType
* @param length
* @return
*/
private String getDbColLength(String sqlType, int length) {
String r = "";
if ("varchar".equalsIgnoreCase(sqlType)) {
r = "length = " + length + ",";
}
if ("char".equalsIgnoreCase(sqlType)) {
r = "length = " + length + ",";
} else if ("numeric".equalsIgnoreCase(sqlType)) {
r = "precision = " + length + ",scale=2,";
} else if ("decimal".equalsIgnoreCase(sqlType)) {
r = "precision = " + length + ",scale=2,";
}
return r;
}
private String getDefaultValue(String s) {
String r = "";
if (s != null) {
s = s.replaceAll("b'", "");
s = s.replaceAll("'", "");
r = "defaultValue = \"" + s + "\",";
}
return r;
}
private String getNullAble(String s) {
String r = "";
boolean b = true;
if (s == null) {
b = true;
} else if ("NO".equalsIgnoreCase(s)) {
b = false;
} else if ("YES".equalsIgnoreCase(s)) {
b = true;
}
if (!b) {
r = "nullable = false,";
}
return r;
}
private String getJavaSqlType(String colType) {
String r;
if ("DATETIME".equalsIgnoreCase(colType)) {
r = "type = TypesExtend.DATETIME";
} else if ("DATE".equalsIgnoreCase(colType)) {
r = "type = Types.DATE";
} else if ("TINYINT UNSIGNED".equalsIgnoreCase(colType)) {
r = "type = Types.INTEGER";
} else if ("BIGINT UNSIGNED".equalsIgnoreCase(colType)) {
r = "type = Types.BIGINT";
} else if ("INT UNSIGNED".equalsIgnoreCase(colType)) {
r = "type = Types.INTEGER";
} else if ("INT".equalsIgnoreCase(colType)) {
r = "type = Types.INTEGER";
} else if ("LONGTEXT".equalsIgnoreCase(colType)) {
r = "type = Types.LONGVARCHAR";
} else if ("TEXT".equalsIgnoreCase(colType)) {
r = "type = Types.CLOB";
} else {
r = "type = Types." + colType;
}
return r;
}
/**
* 功能:生成所有方法
*
* @param sb
*/
private void processAllMethod(StringBuffer sb) {
for (int i = 0; i < colnames.length; i++) {
if ("id".equalsIgnoreCase(colnames[i])) {
continue;
}
sb.append("\r\n\tpublic void set" + initcap(colnames[i]) + "(" + sqlTypeToJavaType(colTypes[i], colSizes[i]) + " " +
colnames[i] + "){\r\n");
sb.append("\t\tthis." + colnames[i] + "=" + colnames[i] + ";\r\n");
sb.append("\t}\r\n");
sb.append("\r\n\tpublic " + sqlTypeToJavaType(colTypes[i], colSizes[i]) + " get" + initcap(colnames[i]) + "(){\r\n");
sb.append("\t\treturn " + colnames[i] + ";\r\n");
sb.append("\t}\r\n");
}
}
/**
* 功能:将输入字符串的首字母及下划线后的字母改成大写
*
* @param str
* @return
*/
private String initcap(String str) {
String[] arr = str.split("_");
StringBuffer tempSb = new StringBuffer();
if (arr.length > 0) {
for (String st : arr) {
char[] c = st.toCharArray();
if (c[0] >= 'a' && c[0] <= 'z') {
c[0] = (char) (c[0] - 32);
}
tempSb.append(new String(c));
}
}
return tempSb.toString();
}
/**
* 功能:将输入字符串的下划线后的字母改成大写
*
* @param str
* @return
*/
private String initcapCol(String str) {
if (str.startsWith("is_")) {
str = str.replaceFirst("is_", "");
}
String[] arr = str.split("_");
StringBuffer tempSb = new StringBuffer();
if (arr.length > 1) {
int i = 0;
for (String st : arr) {
if (i > 0) {
char[] c = st.toCharArray();
if (c[0] >= 'a' && c[0] <= 'z') {
c[0] = (char) (c[0] - 32);
}
tempSb.append(new String(c));
} else {
tempSb.append(st);
}
i++;
}
} else {
tempSb.append(str);
}
return tempSb.toString();
}
/**
* 功能:获得列的数据类型
*
* @param sqlType
* @return
*/
private String sqlTypeToJavaType(String sqlType, int typeSize) {
if ("bit".equalsIgnoreCase(sqlType)) {
return "Boolean";
} else if ("tinyint".equalsIgnoreCase(sqlType)) {
return "Byte";
} else if ("TINYINT UNSIGNED".equalsIgnoreCase(sqlType)) {
return "Byte";
} else if ("smallint".equalsIgnoreCase(sqlType)) {
return "Short";
} else if ("INT".equalsIgnoreCase(sqlType)) {
return "Integer";
} else if ("int".equalsIgnoreCase(sqlType)) {
// if(typeSize>=10){
// return "Long";
// }else{
return "Integer";
// }
} else if ("INT UNSIGNED".equalsIgnoreCase(sqlType)) {
return "Integer";
} else if ("bigint".equalsIgnoreCase(sqlType)) {
return "Long";
} else if ("BIGINT UNSIGNED".equalsIgnoreCase(sqlType)) {
return "Long";
} else if ("float".equalsIgnoreCase(sqlType)) {
return "Float";
} else if ("real".equalsIgnoreCase(sqlType) || "money".equalsIgnoreCase(sqlType)
|| "smallmoney".equalsIgnoreCase(sqlType) || "double".equalsIgnoreCase(sqlType)) {
return "Double";
} else if ("varchar".equalsIgnoreCase(sqlType) || "char".equalsIgnoreCase(sqlType)
|| "nvarchar".equalsIgnoreCase(sqlType) || "nchar".equalsIgnoreCase(sqlType)
|| "text".equalsIgnoreCase(sqlType)) {
return "String";
} else if ("datetime".equalsIgnoreCase(sqlType) || "date".equalsIgnoreCase(sqlType) || "timestamp".equalsIgnoreCase(sqlType)) {
return "Date";
} else if ("image".equalsIgnoreCase(sqlType)) {
return "Blod";
} else if ("longtext".equalsIgnoreCase(sqlType)) {
return "String";
} else if ("decimal".equalsIgnoreCase(sqlType)
|| "numeric".equalsIgnoreCase(sqlType)) {
return "BigDecimal";
}
return null;
}
} |
TypeScript | UTF-8 | 838 | 2.515625 | 3 | [] | no_license | import { HttpClient, HttpRequestParamsInterface } from '@/models/http-client';
import { PaletteApiClientUrlsInterface } from './PaletteApiClientUrls.interface';
import { PaletteApiClientInterface } from './PaletteApiClient.interface';
import { PaletteType } from '@/models/palette';
/**
* @Name PaletteApiClientModel
* @description
* Implements the PaletteApiClientInterface interface
*/
export class PaletteApiClientModel implements PaletteApiClientInterface {
private readonly urls!: PaletteApiClientUrlsInterface
constructor(urls: PaletteApiClientUrlsInterface) {
this.urls = urls;
}
fetchPalette (): Promise<PaletteType[]> {
const getParameters: HttpRequestParamsInterface = {
url: this.urls.fetchPalette,
requiresToken: false,
};
return HttpClient.get<PaletteType[]>(getParameters);
}
} |
Java | UTF-8 | 7,413 | 2 | 2 | [] | no_license | package com.tcd.waggon.ui;
import com.tcd.waggon.Constants;
import com.tcd.waggon.R;
import com.tcd.waggon.WaggonApplication;
import com.tcd.waggon.data.Session;
import com.tcd.waggon.service.Connector;
import com.tcd.waggon.util.Utils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends Activity {
private Context mContext = null;
private EditText txt_user = null;
private EditText txt_pwd = null;
//private String mSessionID = "";
private Session s = null;
private ProgressDialog dlg = null;
private static final int MSG_BEGIN_LOGIN = 1;
private static final int MSG_LOGIN_SUCCEED = 2;
private static final int MSG_LOGIN_FAIL = 3;
private static final int MSG_LOGIN_TIMEOUT = 4;
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (Constants.IS_DEBUG) Log.d(Constants.LOG_TAG, "Get Message " + msg.what);
switch (msg.what){
case MSG_BEGIN_LOGIN:
dlg = new ProgressDialog(mContext);
//dlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dlg.setMessage(mContext.getResources().getString(R.string.txt_login));
dlg.setIndeterminate(false);
dlg.setCancelable(false);
dlg.setProgress(100);
/*dlg.setButton(mContext.getResources().getString(R.string.btn_cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Message message = Message.obtain();
message.what = MSG_CANCEL_DOWNLOAD;
handler.sendMessage(message);
}
});*/
dlg.show();
break;
case MSG_LOGIN_SUCCEED:
if (dlg != null) dlg.dismiss();
Intent intent = new Intent();
intent.setClass(LoginActivity.this, MainActivity.class);
mContext.startActivity(intent);
LoginActivity.this.finish();
break;
case MSG_LOGIN_FAIL:
if (dlg != null) dlg.dismiss();
Toast.makeText(mContext, mContext.getResources().getString(R.string.login_failed), Toast.LENGTH_SHORT).show();
break;
case MSG_LOGIN_TIMEOUT:
if (dlg != null) dlg.dismiss();
Toast.makeText(mContext, mContext.getResources().getString(R.string.login_timeout), Toast.LENGTH_SHORT).show();
break;
}
}
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.login);
mContext = this;
Utils.initWaggonDir();
Button btn_ok = (Button) this.findViewById(R.id.login_btn);
Button btn_forget_pwd = (Button) this.findViewById(R.id.login_forget_pwd);
txt_user = (EditText) this.findViewById(R.id.login_user_edit);
txt_pwd = (EditText) this.findViewById(R.id.login_pwd_edit);
btn_ok.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (txt_user.getText().toString().equals("") || txt_pwd.getText().toString().equals("")) {
Toast.makeText(mContext, mContext.getResources().getString(R.string.login_empty), Toast.LENGTH_SHORT).show();
} else {
login_verify();
/*if () {
Intent intent = new Intent();
intent.setClass(LoginActivity.this, MainActivity.class);
mContext.startActivity(intent);
LoginActivity.this.finish();
} else {
Toast.makeText(mContext, mContext.getResources().getString(R.string.login_failed), Toast.LENGTH_SHORT).show();
}*/
}
}
});
btn_forget_pwd.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(mContext, mContext.getResources().getString(R.string.login_forget_pwd), Toast.LENGTH_SHORT).show();
}
});
}
private void login_verify() {
if (Utils.isConnected(mContext)) {
Log.i(Constants.LOG_TAG, "Connection found, will do online check.");
Message message = Message.obtain();
message.what = MSG_BEGIN_LOGIN;
handler.sendMessage(message);
new Thread() {
public void run() {
String mSessionID = Connector.getInstance().login(txt_user.getText().toString().trim(), txt_pwd.getText().toString().trim());
Message message;
if (Constants.LOGIN_FAILED.equals(mSessionID)) {
message = Message.obtain();
message.what = MSG_LOGIN_FAIL;
handler.sendMessage(message);
} else if (Constants.LOGIN_TIMEOUT.equals(mSessionID)) {
message = Message.obtain();
message.what = MSG_LOGIN_TIMEOUT;
handler.sendMessage(message);
} else {
initData(mSessionID);
// save to local
if (Utils.saveToLocal(s)) {
message = Message.obtain();
message.what = MSG_LOGIN_SUCCEED;
handler.sendMessage(message);
} else {
message = Message.obtain();
message.what = MSG_LOGIN_FAIL;
handler.sendMessage(message);
}
}
}
}.start();
//mSessionID = Connector.getInstance().loginFake(txt_user.getText().toString(), txt_pwd.getText().toString());
/*if (Constants.LOGIN_FAILED.equals(mSessionID)) {
return false;
} else {
WaggonApplication app = WaggonApplication.getInstance();
app.putData(Constants.SESSION_ID, mSessionID);
app.putData(Constants.CHECK_FLAG, "NO");
app.putData(Constants.DOWNLOAD_FLAG, "NO");
app.putData(Constants.UPLOAD_FLAG, "NO");
return true;
}*/
} else {
Log.i(Constants.LOG_TAG, "Connection not found, will do local check.");
Message message;
// Do local check
if (Utils.localCheck(txt_user.getText().toString().trim(), txt_pwd.getText().toString().trim())) {
initData(Constants.SESSION_LOCAL);
message = Message.obtain();
message.what = MSG_LOGIN_SUCCEED;
handler.sendMessage(message);
} else {
message = Message.obtain();
message.what = MSG_LOGIN_FAIL;
handler.sendMessage(message);
}
}
}
private void initData(String sid) {
WaggonApplication app = WaggonApplication.getInstance();
s = new Session();
s.setSessionID(sid);
s.setUser(txt_user.getText().toString().trim());
s.setPasswd(txt_pwd.getText().toString().trim());
app.putData(Constants.SESSION, s);
Utils.initUserDir(s.getUser());
/*app.putData(Constants.SESSION_ID, sid);
app.putData(Constants.CHECK_FLAG, "NO");
app.putData(Constants.DOWNLOAD_FLAG, "NO");
app.putData(Constants.UPLOAD_FLAG, "NO");*/
}
} |
Java | UTF-8 | 1,600 | 3.53125 | 4 | [] | no_license |
/**
* Write a description of class Serie1 here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class SerieDeNumeros{
public long serie1(int parametro){ //ejercicio1
long a = 1;
long b;
int ct = 1;;
System.out.println(" ");
System.out.print(a + " ");
while(ct < parametro){
int i = 1;
while((ct < parametro) && (i <= 3)){
b = a + i;
a = b;
i = i + 1;
ct = ct + 1;
System.out.print(b + " ");
}
if(ct < parametro){
b = a + 2;
a = b;
ct = ct + 1;
System.out.print(b + " ");
}
}
System.out.println(" ");
System.out.println("***************************************************************************************************");
System.out.println(" ");
return a;
}
public long sucesionPadovan(int parametro){ //ejercicio2
long a = 1;
long b = 1;
long c = 1;
System.out.print(a + " " + b + " " + c + " ");
for(int i = 1; i <= (parametro - 3); i++){
long aux = c;
c = a + b;
a = b;
b = aux;
System.out.print(c + " ");
}
System.out.println(" ");
System.out.println("***************************************************************************************************");
System.out.println(" ");
return c;
}
}
|
Markdown | UTF-8 | 698 | 2.78125 | 3 | [] | no_license | # Examen 2
* 1.Cual es la diferencia entre sin() y sind()
* 2.Que hace linspace(0,100,1)?
* 3.Que hace [0:1:100]?
* 4.Sea: A=[1 2 3; 4 5 6; 7 8 9]; Que imprime?: A(:,2)
* 5.Escribe el codigo para crear una cuadricula que contiene 9 plots, usa subplot
* 6.Como harias esta grafica?, considera que es una cuadricula de plots de 9 cuadros

* 7.Codigo para sacar las raices del polinomio 
* 8.Que hace scatter?
* 9.¿Con que comando guardo mi Workspace?
* 10.¿Qué son los archivos csv?
* 11.Si conduces un camion y se suben 10 personas despues se bajan 3 pero dos no te pagan, como se llama el conductor?
|
PHP | UTF-8 | 1,297 | 2.78125 | 3 | [] | no_license | <?php
require_once(dirname(__DIR__) . "/classes/autoload.php");
require_once("/etc/apache2/mysql/encrypted-config.php");
require_once(dirname(__DIR__) . "/lib/xsrf.php");
try {
//ensures that the fields are filled out
if(@isset($_POST["loginEmail"]) === false || @isset($_POST["loginPassword"]) === false) {
throw(new InvalidArgumentException("form not complete. Please verify and try again"));
}
// verify the XSRF challenge
if(session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
verifyXsrf();
// create a salt and hash for user
$pdo = connectToEncryptedMySQL("/etc/apache2/mysql/trufork.ini");
$user = User::getUserByEmail($pdo, $_POST["loginEmail"]);
if($user === null) {
throw(new InvalidArgumentException("email or password is invalid"));
}
$hash = hash_pbkdf2("sha512", $_POST["loginPassword"], $user->getSalt(), 262144, 128);
if($hash !== $user->getHash()) {
throw(new InvalidArgumentException("email or password is invalid"));
}
$_SESSION["user"] = $user;
// $_SESSION["userName"] = $user->getName();
$userName = $_SESSION["user"]->getName();
echo "<p class=\"alert alert-success\">Welcome Back, " . $userName . "!<p/>";
} catch(Exception $exception) {
echo "<p class=\"alert alert-danger\">Exception: " . $exception->getMessage() . "</p>";
}
|
Python | UTF-8 | 2,733 | 3.0625 | 3 | [] | no_license | from ai.logic.sub_logic import SubLogic
class MoneyCalculator(SubLogic):
MONTE_CARLO_ITER = 10
simulation = False
def __init__(self, logic):
super().__init__(logic)
self.prices = []
def load_game(self, graph=None):
game_copy = self.logic.game.copy()
if graph:
unrolled = graph.unroll()
filled = game_copy.players.fill_unrolled_graph(unrolled)
game_copy.board.change_owners(filled)
return game_copy
def get(self, index):
return self.prices[index]
def calculate_prices(self, graphs):
self.prices = []
for graph in graphs:
self.prices.append(self.approximation(graph))
def verify_trades(self, index, trades):
target = self.get_player().id
prices = self.get(index)
trades.sort(key=lambda x: prices[target][x[0]])
total = {target: 0}
for player, _ in trades:
needed = prices[target][player]
if needed > 0:
total[target] += needed
else:
total[player] = -needed
for player in total:
if not self.logic.game.get_player_by_id(player).has(total[player]):
return False
return True
def approximation(self, graph):
diffs = self.gains_of_each(graph)
matrix = {}
for player_1 in graph:
matrix[player_1] = {}
for player_2 in graph:
matrix[player_1][player_2] = int((diffs[player_1] - diffs[player_2]) / 100)
return matrix
def gains_of_each(self, graph):
diffs = {}
for player in graph:
diffs[player] = 0
unrolled = graph.unroll()
groups = []
for owner, tile_index in unrolled:
tile = self.logic.game.get_tile(tile_index)
pair = (owner, tile.group)
if pair not in groups:
groups.append(pair)
for owner, group in groups:
for tile in group:
for player in graph:
if player == owner:
diffs[player] += tile.rents[5]
else:
diffs[player] -= tile.rents[5]
return diffs
def monte_carlo(self, graph=None):
game_copy = self.load_game(graph)
wins = 0
MoneyCalculator.simulation = True
for i in range(MoneyCalculator.MONTE_CARLO_ITER):
game_instance = game_copy.copy()
me = game_instance.players.get_by_id(self.logic.player.id)
game_instance.start()
if game_instance.winner is me:
wins += 1
return wins / MoneyCalculator.MONTE_CARLO_ITER
|
Java | UTF-8 | 1,238 | 2.421875 | 2 | [] | no_license | package com.disablerouting.network;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class NetworkChangeReceiver extends BroadcastReceiver {
private ConnectionChangeListener mConnectionChangeListener;
public void setConnectionListener(ConnectionChangeListener mConnectionChangeListener) {
this.mConnectionChangeListener = mConnectionChangeListener;
}
@Override
public void onReceive(final Context context, final Intent intent) {
if (intent.getExtras() != null) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
assert cm != null;
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
if (mConnectionChangeListener != null) {
mConnectionChangeListener.onNetworkConnectionChanged(isConnected);
}
}
}
public interface ConnectionChangeListener {
void onNetworkConnectionChanged(boolean isConnected);
}
} |
JavaScript | UTF-8 | 588 | 2.609375 | 3 | [
"MIT"
] | permissive |
function init() {
$('a.del').click(function (event) {
event.stopImmediatePropagation();
// console.log(event.target.id);
removeUser(event.target.id);
return false;
});
}
function removeUser(id) {
var url = "/testsApplication/User/removeUser/?id=" + id;
$.ajax({
url: url,
success: function(answer){
var result = JSON.parse(answer);
if(result.type == "success")
{
$("tr."+id).remove();
}
}
});
}
function showResult(type, message) {
} |
C++ | UTF-8 | 430 | 3 | 3 | [] | no_license | #include "Stack.h"
#include <iostream>
using namespace std;
int main(){
Stack st;
st.initialize();
double d;
double* dd;
for (int i = 0 ; i < 25 ; i++){
double* temp = new double(1/static_cast<double>(i));
st.push(temp);
}
for (int i = 0 ; i <25 ; i++){
dd = reinterpret_cast<double*>((st.pop()));
cout << "stack.pop() = " << *dd << endl;
//delete dd;
}
}
|
Markdown | UTF-8 | 2,772 | 2.875 | 3 | [] | no_license | ---
nav_order: 4
published: true
---
# FAQs
### Q: What is Parsec?
A: Parsec is a desktop capturing application primarily used for cloud-based gaming through video streaming.
### Q: Is Parsec free?
A: Yes, it is free to download [here](https://parsecgaming.com/downloads/)
### Q: Any settings I need to set in Parsec?
A: In client settings for sure turn off v-sync, while host settings should set the resolution to 1280x720. Also in host settings the bandwith limit should lowered depending if frame skips/drops are occuring. Other settings such as full screen/window mode should be player's preference.
### Q: What's the purpose of using Cloud PCs rather than just using your normal PC?
A: To avoid host advantage where the host is basically playing the game with 0 input delay while the client is playing with input delay. Also the host's upload speed might not be strong enough to host.
### Q: Why go through all this trouble and instead use the game's base netcode?
A: Many fighting games use delay based netcode which has been notoriously bad for the player's experience. With this setup players are able to get usually consistent input delay with little worry of it fluctuating. Some issues may occur with dropping/skipping frames which is related to your PC specs and/or download speed since it is a video stream.
### Q: Do I need to own the game to use with Parsec?
A: If you are hosting yes. If you are connecting to someone then they're the ones that need to own the game.
### Q: Are Cloud PCs free?
A: No, Amazon Webservices, Google Cloud, Microsoft Azure all cost money.
### Q: Which service do you reccomend?
A: It depends on your location and preferences. Google Cloud has the same areas as AWS but also has Iowa and LA, while Azure has Texas. Google Cloud has had a few stability issues with certain people. Google Cloud offers $300 credit for 1 year use on a brand new account while Azure offers $200 credit for 1 month use, AWS has no known free trial offers.
### Q: How do I set up a Cloud PC?
A: [Here](https://www.youtube.com/watch?v=QLyTBHJY7jM) is a tutorial by [datHazy](https://twitter.com/datHazy) for AWS. Other tutorials exist on Azure/Google Cloud with near identical steps on youtube. Once you figure out how to setup one, you should be able to figure out the other services easily.
### Q: I see something about reducing the costs, what is that about?
A: With these services they have spot/preemptible instances which usually cost 1/2 the price of on demand instances. But they usually have some sort of restriction attached depending on the service.
### Q: Can I contact you for questions/inquiries?
A: Sure, I'm always down to help/chat! Feel free to [DM me on Twitter](https://twitter.com/Jason_GameDev)
|
JavaScript | UTF-8 | 851 | 3.53125 | 4 | [
"MIT"
] | permissive | /**
* @param {number[]} nums
* @return {number}
*/
var longestSubarray = function(nums) {
const numbers = [];
const counts = [];
let index = 0;
while(index<nums.length){
const digit = nums[index++];
let count = 1;
while(index<nums.length && nums[index] === digit){
count++;
index++;
}
numbers.push(digit);
counts.push(count);
}
if(numbers.length === 1){
if(numbers[0] === 0){
return 0;
}
return counts[0]-1;
}
let result = 0;
for(let i=0;i<numbers.length;i++){
if(numbers[i] === 1){
result = Math.max(result,counts[i]);
}else if(counts[i] === 1 && i>0 && i<numbers.length-1){
result = Math.max(result,counts[i-1]+counts[i+1]);
}
}
return result;
}; |
Python | UTF-8 | 620 | 3.171875 | 3 | [] | no_license | import bs4
def soup_text(soup_elem):
try:
# text = soup_elem.get_text(',,,', strip=True).decode('utf-8')
# text = self.newline_re.sub(" ", text)
# text = re.sub(r',,,', '\n', text)
text = soup_elem.get_text('\n', strip=True).encode('utf8')
return text
except AttributeError:
if isinstance(soup_elem, bs4.element.NavigableString):
return unicode(soup_elem)
else:
raise Exception('Unhandled type: {}'.format(
type(soup_elem)))
def html_to_text(html):
soup = bs4.BeautifulSoup(html)
return soup_text(soup)
|
JavaScript | UTF-8 | 5,660 | 2.703125 | 3 | [] | no_license | import React, { Component } from "react";
import "./AddStocks.css";
import Modal from "../Modal/Modal";
import Axios from "axios";
class AddStocks extends Component {
constructor() {
super();
this.state = {
stocks: [],
modal: false,
myStocks: []
};
}
componentDidMount() {
Axios.get(
"https://financial-pf-tracker.firebaseio.com/stocks.json?auth=7S5VnVzMGMBN8wudel6jnQp2SOblrVG89nzJucyt"
).then(response => {
let stocks = response.data;
console.log("stocks", stocks);
this.setState({ stocks });
});
Axios.get(
"https://financial-pf-tracker.firebaseio.com/myStocks.json?auth=7S5VnVzMGMBN8wudel6jnQp2SOblrVG89nzJucyt"
).then(response => {
let myStocks = response.data;
// console.log("myStocks", myStocks);
this.setState({ myStocks });
});
}
componentDidUpdate() {
Axios.get(
"https://financial-pf-tracker.firebaseio.com/myStocks.json?auth=7S5VnVzMGMBN8wudel6jnQp2SOblrVG89nzJucyt"
).then(response => {
let myStocks = response.data;
// console.log("myStocks", myStocks);
this.setState({ myStocks });
});
}
addStocksBtn = event => {
this.setState({
modal: true,
stockName: event.target.name,
stockSymbol: event.target.id
});
};
inputHandler = event => {
this.setState({ [event.target.name]: event.target.value });
};
stockFormCancelBtn = () => {
this.setState({ modal: false });
this.stockFormReset();
};
addStockHandler = () => {
let myStocksArr = Object.keys(this.state.myStocks);
var warning;
if(myStocksArr.length < 5){
myStocksArr.forEach(stock => {
let selectedStockName = this.state.myStocks[stock].stockName;
if (this.state.stockName === selectedStockName) {
this.setState({ warningText: "The selected stock is already added !" });
warning = true;
this.stockFormReset();
} else if (selectedStockName !== this.state.stockName) {
warning = false;
this.setState({ warningText: "" });
} else {
this.stockFormCancelBtn();
}
});
if (warning === false) {
this.setState({ warningText: "" });
this.postData();
this.stockFormCancelBtn();
console.log("posting...");
} else {
this.setState({ warningText: "The selected stock is already added !" });
}
}
else {
this.setState({ warningText: "Can't add more than five stocks !"});
}
};
stockFormReset = () => {
this.setState({
numberOfShares: null,
buyPrice: null,
buyDate: null,
warningText: ""
});
};
postData = () => {
Axios.post(
"https://financial-pf-tracker.firebaseio.com/myStocks.json?auth=7S5VnVzMGMBN8wudel6jnQp2SOblrVG89nzJucyt",
{
stockName: this.state.stockName,
stockSymbol: this.state.stockSymbol,
numberOfShares: this.state.numberOfShares,
buyPrice: this.state.buyPrice,
buyDate: this.state.buyDate
}
).then(response => console.log(response));
};
render() {
let modalContent = (
<>
<button id="xcancel" onClick={this.stockFormCancelBtn}>
<img src={require("../images/redcross.png")} alt='✘'/>
</button>
<div className="AddStockForm">
<h2>
Add <span>{this.state.stockName}</span> to my stocks
</h2>
<div>
<h4>Company Name : </h4>
<span>{this.state.stockName}</span>
</div>
<div>
<h4>
No. of Shares : <span>{this.state.numberOfShares}</span>
</h4>
<input
id="noShares"
type="number"
placeholder="No. of Shares"
name="numberOfShares"
onChange={this.inputHandler}
/>
</div>
<div>
<h4>
Buy Price : <span>{this.state.buyPrice}</span>
</h4>
<input
id="buyPrice"
type="number"
placeholder="Buying price"
name="buyPrice"
onChange={this.inputHandler}
/>
</div>
<div>
<h4>
Buy Date : <span>{this.state.buyDate}</span>
</h4>
<span id="warning">{this.state.warningText}</span>
<input id="buyDate" type="date" name="buyDate" onChange={this.inputHandler} />
</div>
<button className="AddButton" onClick={this.addStockHandler}>
Add
</button>
</div>
</>
);
let stockArr = Object.keys(this.state.stocks);
return (
<>
<div className="add-stocks-title">
<h2>Add stocks to my stocks</h2>
</div>
<div className="AddStocksTitle">
<ul>
{stockArr.map(stock => {
return (
<li key={stock}>
<button
className="StockButton"
onClick={this.addStocksBtn}
name={ this.state.stocks[stock].name}
id={this.state.stocks[stock].symbol}
>
{this.state.stocks[stock].symbol}
</button>
<span>{this.state.stocks[stock].name}</span>
</li>
);
})}
</ul>
{this.state.modal ? (
<Modal content={modalContent} test="working" />
) : null}
</div>
</>
);
}
}
export default AddStocks;
|
Markdown | UTF-8 | 1,283 | 3.609375 | 4 | [] | no_license | ---
layout: post
title: LeetCode之螺旋矩阵II
---
# 1. 题目描述
https://leetcode-cn.com/problems/spiral-matrix-ii/
# 2. 示例代码
```
class Solution {
public int[][] generateMatrix(int n)
{
int[][] res = new int[n][n];
int above_row = 0;
int below_row = n-1;
int left_col = 0;
int right_col = n-1;
int num =1;
while(above_row <= below_row && left_col <= right_col)
{
//从左到右
for(int i = left_col;i<=right_col;i++)
{
res[above_row][i] = num;
num++;
}
above_row++;
//从上到下
for(int i= above_row;i<=below_row;i++)
{
res[i][right_col] = num;
num++;
}
right_col--;
//从右到左
for(int i = right_col;i>=left_col;i--)
{
res[below_row][i] = num;
num++;
}
below_row--;
//从下到上
for(int i = below_row;i>=above_row;i--)
{
res[i][left_col] = num;
num++;
}
left_col++;
}
return res;
}
}
```
|
C++ | UTF-8 | 1,740 | 2.859375 | 3 | [] | no_license | #ifndef ANIMATION_H
#define ANIMATION_H
using namespace DirectX;
struct Keyframe{
Keyframe() : TimePos(0.0f), Translation(0.0f, 0.0f, 0.0f), Scale(1.0f, 1.0f, 1.0f), RotationQuat(0.0f, 0.0f, 0.0f, 1.0f) {}
float TimePos;
XMFLOAT3 Translation;
XMFLOAT3 Scale;
XMFLOAT4 RotationQuat;
};
struct BoneAnimation {
float GetStartTime() const { return Keyframes.front().TimePos; }
float GetEndTime()const { return Keyframes.back().TimePos; }
void Interpolate(float time, XMFLOAT4X4& M) const;//return a transformation Matrix which can transform this bone under given time t, to be the calculated position, scale and orientation
std::vector<Keyframe> Keyframes;
};
struct AnimationClip {
float GetClipStartTime() const;
float GetClipEndTime() const;
void Interpolate(float t, std::vector<XMFLOAT4X4>& bonesTransforms) const;
std::vector<BoneAnimation> BoneAnimations; //for all bones of this model
};
class AnimationData {
public:
size_t BoneCount() const { return mBoneHierarchyTree.size(); }
float GetClipStartTime(const std::string& clipName) const { return mAnimations.at(clipName).GetClipStartTime(); }
float GetClipEndTime(const std::string& clipName) const { return mAnimations.at(clipName).GetClipEndTime(); }
void Set(std::vector<int>& boneHierarchy, std::vector<XMFLOAT4X4>& boneOffsets, std::unordered_map<std::string, AnimationClip>& animations) { mBoneHierarchyTree = boneHierarchy; mBoneOffsets = boneOffsets; mAnimations = animations; }
void GetFinalTransfroms(const std::string& clipName, float timePos, std::vector<XMFLOAT4X4>& finalTransforms) const;
private:
std::vector<int> mBoneHierarchyTree;
std::vector<XMFLOAT4X4> mBoneOffsets;
std::unordered_map<std::string, AnimationClip> mAnimations;
};
#endif
|
Java | UTF-8 | 1,542 | 3.140625 | 3 | [] | no_license | package mazeProblem;
import java.util.Scanner;
import java.io.FileInputStream;
import java.util.Queue;
import java.util.LinkedList;
class SWEA1227
{
public static void main(String args[]) throws Exception
{
System.setIn(new FileInputStream("queue/res/input3.txt"));
Scanner sc = new Scanner(System.in);
for(int test_case = 1; test_case <= 10; test_case++)
{
test_case = sc.nextInt();
sc.nextLine();
char[][] mazeMap = new char[100][100];
Node start = new Node(0, 0);
for(int i = 0; i < 100; i++) {
String s = sc.nextLine();
mazeMap[i] = s.toCharArray();
if(s.contains("2")) {
start = new Node(i, s.indexOf("2"));
}
}
System.out.println("#" + test_case + " " + bfs(mazeMap, start));
}
}
public static int bfs(char[][] mazeMap, Node start) {
int answer = 0;
int[][] direction = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
boolean[][] visited = new boolean[100][100];
Queue<Node> queue = new LinkedList<>();
queue.add(start);
visited[start.x][start.y] = true;
while(!queue.isEmpty() && answer == 0) {
Node target = queue.poll();
for(int i = 0; i < 4; i++) {
int x = target.x + direction[i][0];
int y = target.y + direction[i][1];
if(x < 0 || x >= 100 || y < 0 || y >= 100) {
break;
}
if(mazeMap[x][y] == '0' && !visited[x][y]) {
queue.add(new Node(x, y));
visited[x][y] = true;
} else if(mazeMap[x][y] == '3') {
answer = 1;
break;
}
}
}
return answer;
}
} |
PHP | UTF-8 | 513 | 2.6875 | 3 | [] | no_license | <?php
$servidor = "localhost1"; //também pode ser web(um site como o banco online )
$dbname = "umnomequalquer"; //Nome do banco de dados a ser colocada a informação. Criado antes no MySQL
$dbusuario ="root11"; //usuário do banco EXEMPLO.
$dbsenha = "***"; //Senha do usuário EXEMPLO
//Método de conexão com o Banco de Dados.
$conn = mysqli_connect($servidor, $dbusuario, $dbsenha, $dbname);
if(!$conn){
die ("Conexão falhou: " . mysqli_connect_error());
//"morte" da entrada da conexão.
}
?> |
Python | UTF-8 | 2,156 | 3.125 | 3 | [
"MIT"
] | permissive | #!/usr/bin/python
import time
import math
import Adafruit_CharLCD as LCD
# Raspberry Pi configuration:
lcd_rs = 27 # Change this to pin 21 on older revision Raspberry Pi's
lcd_en = 22
lcd_d4 = 25
lcd_d5 = 24
lcd_d6 = 23
lcd_d7 = 18
lcd_red = 4
lcd_green = 17
lcd_blue = 7 # Pin 7 is CE1
# Alternatively specify a 20x4 LCD.
lcd_columns = 20
lcd_rows = 4
def dots(col, row):
count = 0
lcd.set_cursor(col, row)
while count < 3:
lcd.write8(ord('.'), True)
time.sleep(0.5)
count += 1
lcd.set_cursor(col, row)
lcd.message(' ')
# print arrow pointing to switch
# ->
# -->
# --->
def arrow(col, row):
dash = 20 - col
count = 0
while count < dash:
lcd.message(' ' * dash)
lcd.set_cursor(col, row)
lcd.message('-' * count)
lcd.message('>')
time.sleep(0.5)
count += 1
lcd.set_cursor(col, row)
def reset_row(row):
lcd.set_cursor(0, row)
lcd.message(' ' * 20)
lcd.set_cursor(0, row)
# Initialize the LCD using the pins above.
lcd = LCD.Adafruit_RGBCharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7,
lcd_columns, lcd_rows, lcd_red, lcd_green, lcd_blue)
lcd.set_color(1.0, 0.0, 0.0)
lcd.clear()
lcd.home()
msg = ''' NG Sec. Industries
-REASON- v0.0.1'''
lcd.message(msg)
states = [
'Initializing',
'Ignite Reactor',
'Stablizing',
'Warming Up Rails'
]
# for i, state in enumerate(states):
# count = 0
#
# reset_row(2)
# print(i)
# idx = float(i + 1)
# print(idx)
# pct = float(len(states)) / float(lcd_columns)
# print(pct)
# bar = math.ceil(pct * idx * lcd_columns)
# print(bar)
# while bar:
# lcd.message('#')
# bar -= 1
# lcd.set_cursor(7, 2)
# lcd.message(str(pct * idx * 100))
# lcd.message('%')
#
# reset_row(3)
# lcd.message(state)
# while count < 2:
# l = len(state) + 1
# dots(col=l, row=3)
# count += 1
reset_row(2)
lcd.message('####################')
reset_row(3)
fire = 'Ready To Fire'
lcd.message(fire)
pw_sw = 0
while pw_sw < 1:
arrow(len(fire) + 1, 3)
|
PHP | UTF-8 | 4,436 | 2.53125 | 3 | [] | no_license | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Album;
use App\Photo;
class GallaryController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
$album=Album::all();
return view('welcome')->with('album',$album);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
return view("createAlbum");
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
$album =new Album();
$album->name=$request->input('name');
$album->bio=$request->input('bio');
$album->image=$request->input('image');
dd($album);
$album->save();
return redirect('/');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show(Request $request)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
//create Album
public function upload(Request $request){
$album =new Album();
$album->name=$request->input('name');
$album->bio=$request->input('bio');
// $file=$request->input('file');
//getting file name with extension EXAMPLE jpg
$filenamewithext = $request->file('file')->getClientOriginalName();
//get file name without extension example jpg
$filename=pathinfo($filenamewithext,PATHINFO_FILENAME);
//get extension
$extension = $request->file('file')->getClientOriginalExtension();
//file name to store with time
$filenametostore=$filename.'_'.time().'.'.$extension;
//save file name wih path in storage folder
$path=$request->file('file')->storeAs('public/Album_cover',$filenametostore);
$album->image=$filenametostore;
$album->save();
return redirect('/');
}
//photos
public function photos($id){
$album=Album::find($id);
$photos=$album->photo;
$back=back();
return view('photos')->with( 'photos',$photos)->with('id',$id)->with('back',$back);
}
public function photoscreate($id){
return view('createphotos')->with('id',$id);
}
public function photoupload(Request $request,$id){
$photo =new Photo();
$photo->name=$request->input('name');
$photo->bio=$request->input('bio');
$photo->album_id=$id;
// $file=$request->input('file');
//getting file name with extension EXAMPLE jpg
$filenamewithext = $request->file('file')->getClientOriginalName();
//get file name without extension example jpg
$filename=pathinfo($filenamewithext,PATHINFO_FILENAME);
//get extension
$extension = $request->file('file')->getClientOriginalExtension();
//file name to store with time
$filenametostore=$filename.'_'.time().'.'.$extension;
//save file name wih path in storage folder
$path=$request->file('file')->storeAs('public/Album_cover',$filenametostore);
$photo->image=$filenametostore;
$photo->save();
return back();
}
public function allphotos(){
$photos=Photo::all();
$back=back();
return view('photos')->with( 'photos',$photos)->with('id','0')->with('back',$back);
}
}
|
JavaScript | UTF-8 | 4,289 | 2.578125 | 3 | [
"MIT"
] | permissive | (function($, window){
var ChartVis = function(csvRequestPath){
var self = this;
this.init = function(){
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = ($(window).width() - 15) - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
var bisectEmails = d3.bisector(function(d) { return d.emails; }).left;
var x = d3.scale.linear()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(5);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(5);
var valueline = d3.svg.line()
.x(function(d) { return x(d.emails); })
.y(function(d) { return y(d.occurrences); });
var svg = d3.select("#chart-vis").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var focus = svg.append("g")
.style("display", "none");
d3.csv(csvRequestPath, function(error, data) {
$('#chart-loading-placeholder').hide();
data.forEach(function(d) {
d.occurrences = +d.occurrences;
d.emails = +d.emails;
});
data.sort(function(a, b) {
return a.emails - b.emails;
});
// scale the range of the data
x.domain(d3.extent(data, function(d) { return d.emails; }));
y.domain([0, d3.max(data, function(d) { return d.occurrences; })]);
// add the value line
svg.append("path")
.attr("class", "line")
.attr("d", valueline(data));
// add axes
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
// add legends
svg.append("text")
.attr("x", width / 2 )
.attr("y", height + margin.bottom)
.style("text-anchor", "middle")
.text("No. of Emails Exchanged");
svg.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 0 - margin.left)
.attr("x",0 - (height / 2))
.attr("dy", "1em")
.style("text-anchor", "middle")
.text("No. of Connections");
// append circle and text
focus.append("circle")
.attr("class", "y")
.style("fill", "none")
.style("stroke", "#07A69C")
.attr("r", 4);
focus.append("text")
.attr("x", 9)
.attr("dy", "-0.5em");
// capture mouse
svg.append("rect")
.attr("width", width)
.attr("height", height)
.style("fill", "none")
.style("pointer-events", "all")
.on("mouseover", function() { focus.style("display", null); })
.on("mouseout", function() { focus.style("display", "none"); })
.on("mousemove", mousemove);
function mousemove() {
var x0 = x.invert(d3.mouse(this)[0]),
i = bisectEmails(data, x0, 1),
d0 = data[i - 1],
d1 = data[i]
d = x0 - d0.emails > d1.emails - x0 ? d1 : d0;
var plural = (d.occurrences > 1) ? 'connections' : 'connection';
focus.attr("transform", "translate(" + x(d.emails) + "," + y(d.occurrences) + ")");
focus.select("text").text(d.emails + ' emails: ' + d.occurrences + ' ' + plural);
}
});
};
};
// go go gadget namespaces
window.artsapi = window.artsapi || new Object();
window.artsapi.ChartVis = ChartVis;
})($, window) |
PHP | UTF-8 | 1,042 | 2.515625 | 3 | [] | no_license | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePricingItemsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('pricing_items', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('pricing_id');
$table->string('title');
$table->string('description')->nullable()->default(null);
$table->unsignedInteger('position')->nullable()->default(null);
$table->decimal('price');
$table->string('link')->nullable()->default(null);
$table->timestamps();
$table->foreign('pricing_id')->references('id')->on('pricing')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('pricing_items');
}
}
|
PHP | UTF-8 | 2,955 | 2.875 | 3 | [
"MIT"
] | permissive | <?php
class FileHandler
{
private $config = [];
private $videos_ext = ".{avi,mp4,flv,mkv}";
private $musics_ext = ".{mp3,ogg,m4a}";
public function __construct()
{
$this->config = require dirname(__DIR__).'/config/config.php';
}
public function listVideos()
{
$videos = [];
if(!$this->outuput_folder_exists())
return;
$folder = dirname(__DIR__).'/'.$this->config["outputFolder"].'/';
foreach(glob($folder.'*'.$this->videos_ext, GLOB_BRACE) as $file)
{
$video = [];
$video["name"] = str_replace($folder, "", $file);
$video["size"] = $this->to_human_filesize(filesize($file));
$videos[] = $video;
}
return $videos;
}
public function listMusics()
{
$musics = [];
if(!$this->outuput_folder_exists())
return;
$folder = dirname(__DIR__).'/'.$this->config["outputFolder"].'/';
foreach(glob($folder.'*'.$this->musics_ext, GLOB_BRACE) as $file)
{
$music = [];
$music["name"] = str_replace($folder, "", $file);
$music["size"] = $this->to_human_filesize(filesize($file));
$musics[] = $music;
}
return $musics;
}
public function delete($id, $type)
{
$folder = dirname(__DIR__).'/'.$this->config["outputFolder"].'/';
$i = 0;
if($type === 'v')
{
$exts = $this->videos_ext;
}
elseif($type === 'm')
{
$exts = $this->musics_ext;
}
else
{
return;
}
foreach(glob($folder.'*'.$exts, GLOB_BRACE) as $file)
{
if($i == $id)
{
unlink($file);
}
$i++;
}
}
public function get_download_link($id, $type)
{
$folder = dirname(__DIR__).'/'.$this->config["outputFolder"].'/';
$i = 0;
if($type === 'v')
{
$exts = $this->videos_ext;
}
elseif($type === 'm')
{
$exts = $this->musics_ext;
}
else
{
return;
}
foreach(glob($folder.'*'.$exts, GLOB_BRACE) as $file)
{
if($i == $id)
{
return $this->get_site_protocol().$_SERVER['HTTP_HOST'].str_replace($_SERVER['DOCUMENT_ROOT'], '', $file);
}
$i++;
}
}
private function outuput_folder_exists()
{
if(!is_dir($this->config['outputFolder']))
{
//Folder doesn't exist
if(!mkdir('./'.$this->config['outputFolder'], 0777))
{
return false; //No folder and creation failed
}
}
return true;
}
public function to_human_filesize($bytes, $decimals = 0)
{
$sz = 'BKMGTP';
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
}
public function free_space()
{
return $this->to_human_filesize(disk_free_space($this->config["outputFolder"]));
}
public function get_downloads_folder()
{
return $this->config["outputFolder"];
}
public function get_site_protocol() {
if(isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') return $protocol = 'https://'; else return $protocol = 'http://';
}
}
?>
|
Java | UTF-8 | 685 | 2.96875 | 3 | [] | no_license | package com.junhua.design.pattern.mediator;
import java.util.Random;
/**
* @author Junhua E-mail:xjhclks@163.com
* @version create time:2018/11/18 7:52 AM
*/
public class Sale extends AbstractColleague{
public Sale(AbstractMediator mediator) {
super(mediator);
}
/**
* 获取销售状况
* @return
*/
public int getSaleStatus() {
Random random = new Random();
return random.nextInt(100);
}
public void sellIBMcomputer(int number) {
System.out.println("卖出电脑" + number + "台");
super.mediator.execute("sale.sell", number);
}
/**
* 打折处理
*/
public void offSale() {
super.mediator.execute("sale.offSell");
}
}
|
C++ | UTF-8 | 4,337 | 3.0625 | 3 | [] | no_license | // problem source: https://www.hackerrank.com/challenges/swap-nodes-algo/problem
#include <bits/stdc++.h>
using namespace std;
/*
* Complete the swapNodes function below.
*/
class treeNode{
public:
treeNode* left = nullptr;
treeNode* right = nullptr;
int data;
int depth;
treeNode(int da, int dep){
data = da;
depth = dep;
}
};
vector<vector<treeNode*>> bfsInsert(vector<vector<int>> indexes, treeNode* root){
vector< vector<treeNode*> > arrs;
arrs.resize(1);
queue<treeNode*> que;
que.push(root);
int i = 0;
arrs[0].push_back(root);
while(!que.empty()){
if(indexes[i][0] != -1){
treeNode* newLeftNode = new treeNode(indexes[i][0], que.front()->depth + 1);
que.front()->left = newLeftNode;
que.push(newLeftNode);
if(newLeftNode->depth > arrs.size()){
arrs.resize(newLeftNode->depth);
arrs[newLeftNode->depth - 1].push_back(newLeftNode);
}else{
arrs[newLeftNode->depth - 1].push_back(newLeftNode);
}
}
if(indexes[i][1] != -1){
treeNode* newRightNode = new treeNode(indexes[i][1], que.front()->depth + 1);
que.front()->right = newRightNode;
que.push(newRightNode);
if(newRightNode->depth > arrs.size()){
arrs.resize(newRightNode->depth);
arrs[newRightNode->depth - 1].push_back(newRightNode);
}else{
arrs[newRightNode->depth - 1].push_back(newRightNode);
}
}
i++;
que.pop();
}
return arrs;
}
vector<int> inOrder(treeNode* root, vector<int> result){
if(root == nullptr){
return result;
}
result = inOrder(root->left, result);
result.push_back(root->data);
result = inOrder(root->right, result);
return result;
}
vector<vector<int>> swapNodes(vector<vector<int>> indexes, vector<int> queries) {
/*
* Write your code here.
*/
treeNode* root = new treeNode(1, 1);
// 把樹轉成二維陣列,縱軸為樹的深度,橫軸為此深度的所有node
vector< vector<treeNode*> > depthArrs = bfsInsert(indexes, root);
treeNode* temp = root;
vector<vector<int>> result(queries.size());
for(int i = 0; i < queries.size(); ++i){
for(int j = queries[i], l = 1; j <= depthArrs.size(); l++, j = queries[i] * l ){
for(int k = 0; k < depthArrs[j-1].size(); ++k){
temp = depthArrs[j-1][k]->left;
depthArrs[j-1][k]->left = depthArrs[j-1][k]->right;
depthArrs[j-1][k]->right = temp;
}
}
result[i] = inOrder(root, result[i]);
}
return result;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
int n;
cin >> n;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
vector<vector<int>> indexes(n);
for (int indexes_row_itr = 0; indexes_row_itr < n; indexes_row_itr++) {
indexes[indexes_row_itr].resize(2);
for (int indexes_column_itr = 0; indexes_column_itr < 2; indexes_column_itr++) {
cin >> indexes[indexes_row_itr][indexes_column_itr];
}
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
int queries_count;
cin >> queries_count;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
vector<int> queries(queries_count);
for (int queries_itr = 0; queries_itr < queries_count; queries_itr++) {
int queries_item;
cin >> queries_item;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
queries[queries_itr] = queries_item;
}
vector<vector<int>> result = swapNodes(indexes, queries);
for (int result_row_itr = 0; result_row_itr < result.size(); result_row_itr++) {
for (int result_column_itr = 0; result_column_itr < result[result_row_itr].size(); result_column_itr++) {
fout << result[result_row_itr][result_column_itr];
if (result_column_itr != result[result_row_itr].size() - 1) {
fout << " ";
}
}
if (result_row_itr != result.size() - 1) {
fout << "\n";
}
}
fout << "\n";
fout.close();
return 0;
}
|
C++ | UTF-8 | 20,323 | 3.140625 | 3 | [] | no_license | #include "D_tree.h"
using namespace d_tree;
struct d_tree::State{
Label symbol;
Label condition;
};
struct d_tree::IdLabel{
Label label;
Label id;
Label idlabel;
};
struct d_tree::Elem{
State state;
IdLabel infoLabel;
};
struct d_tree::treeNode {
Elem infoEdge;
Tree firstChild;
Tree nextSibling;
};
struct Cell{
List next;
string s;
};
Tree d_tree::createEmpty(){
Tree t = new treeNode;
t->firstChild = t->nextSibling = emptyTree;
t->infoEdge.infoLabel.idlabel = emptyLabel;
return t;
}
//////////////////////////////////////////
// Check if idlabel is inside the Tree
//////////////////////////////////////////
bool member(const Label idlabel, const Tree& tree){
if (tree == emptyTree)
return false;
// if tree idlabel is the idlabel searched
if (tree->infoEdge.infoLabel.idlabel == idlabel)
return true;
// recursive call on each child of t while not return true
Tree auxT = tree->firstChild;
while (auxT != emptyTree) {
if (!member(idlabel, auxT)) // not found in this subtree, go ahead searching in his siblings
auxT = auxT->nextSibling;
else // found idlabel
return true;
}
return false;
}
//////////////////////////////////////////
// Check if label is inside the Tree
//////////////////////////////////////////
bool memberLabel(const Label label, const Tree& tree){
if (tree == emptyTree)
return false;
// if tree label is the label searched
if (tree->infoEdge.infoLabel.label == label)
return true;
// recursive call on each child of t while not return true
Tree auxT = tree->firstChild;
while (auxT != emptyTree) {
if (!memberLabel(label, auxT)) // not found in this subtree, go ahead searching in his siblings
auxT = auxT->nextSibling;
else // found label
return true;
}
return false;
}
//////////////////////////////////////////
// Return node with specific label
//////////////////////////////////////////
Tree getNode(const Label l, const Tree& t){
if (t == emptyTree || l == emptyLabel)
return emptyTree;
// if tree idlabel is the idlabel searched return t
if (t->infoEdge.infoLabel.idlabel == l){
return t;
}
// recursive call on each child of t while not return emptyTree
Tree auxT = t->firstChild;
Tree resNode;
while (auxT != emptyTree) {
resNode = getNode(l, auxT);
if (resNode == emptyTree) // not found in this subtree, go ahead searching in his siblings
auxT = auxT->nextSibling;
else // found node return it
return resNode;
}
return emptyTree;
}
//////////////////////////////////////////
// Get prevSibling node with label l
//////////////////////////////////////////
Tree prevSibling(const Label l, const Tree& t){
// if tree is empty or doesn't have childs
if (t == emptyTree || t->firstChild == emptyTree || l == emptyLabel)
return emptyTree;
if (t->firstChild->infoEdge.infoLabel.idlabel == l) // if the node has as first child with the label searched doesn't have previous siblings
return emptyTree;
else{
Tree prevChild = t->firstChild;
Tree currentChild = prevChild->nextSibling;
Tree auxT;
while (currentChild != emptyTree && currentChild->infoEdge.infoLabel.idlabel != l){
prevChild = currentChild;
currentChild = currentChild->nextSibling;
}
if ( currentChild != emptyTree && currentChild->infoEdge.infoLabel.idlabel == l)
return prevChild;
else{
currentChild = t->firstChild;
while (currentChild != emptyTree){
auxT = prevSibling(l, currentChild);
if (auxT != emptyTree)
return auxT;
else
currentChild = currentChild->nextSibling;
}
}
}
return emptyTree;
}
//////////////////////////////////////////
// Get father node with label l
//////////////////////////////////////////
Label father(const Label l, const Tree& t){
if (t == emptyTree) return emptyLabel;
if (t->firstChild->infoEdge.infoLabel.idlabel != emptyLabel) return t->infoEdge.infoLabel.idlabel;
Tree child = t->firstChild;
Label auxL;
while (child != emptyTree){
auxL = father(l, child);
if (auxL != emptyLabel)
return auxL;
else
child = child->nextSibling;
}
return emptyLabel;
}
//////////////////////////////////////////
// Modify label (auxiliary function)
//////////////////////////////////////////
Error auxModifyElem(const Label labelToModify, const Label newLabel, const Label newCondition, const Tree& t){
if(t == emptyTree) return FAIL;
if(t->infoEdge.infoLabel.idlabel == labelToModify){
t->infoEdge.infoLabel.idlabel = newLabel;
t->infoEdge.infoLabel.id.clear(); //clear fileds of node to modify
t->infoEdge.infoLabel.label.clear();
t->infoEdge.state.symbol.clear();
t->infoEdge.state.condition.clear();
unsigned int i = 0;
while(i < newLabel.size()) {
if(
newLabel[i] == '_' || newLabel[i] == '0'||
newLabel[i] == '1' || newLabel[i] == '2'||
newLabel[i] == '3' || newLabel[i] == '4'||
newLabel[i] == '5' || newLabel[i] == '6'||
newLabel[i] == '7' || newLabel[i] == '8'||
newLabel[i] == '9'
)
t->infoEdge.infoLabel.id += newLabel[i]; // id example : "_1"
else
t->infoEdge.infoLabel.label += newLabel[i]; // label example : "Age"
i++;
}
i = 0;
while(i < newCondition.size()) {
if( newCondition[i] == '<' || newCondition[i] == '>' || newCondition[i] == '='|| newCondition[i] == '!')
t->infoEdge.state.symbol += newCondition[i]; // symbols accepted < > = !
else
t->infoEdge.state.condition += newCondition[i]; //in the condition I put the condition without symbols (for example if I have> 23 as a condition here I will put only 23)
i++;
}
return OK;
}
Tree auxT = t->firstChild;
Error res;
while (auxT != emptyTree) { //resursive search to identify the node to modify
res = auxModifyElem(labelToModify,newLabel, newCondition, auxT);
if(res == OK)
return OK;
else
auxT = auxT->nextSibling;
}
return FAIL;
}
//////////////////////////////////////////
// Modify label
//////////////////////////////////////////
Error d_tree::modifyElem(const Label labelToModify, const Label newLabel, const Label newCondition, const Tree& t){
if(t->infoEdge.infoLabel.idlabel == labelToModify || member(newLabel, t) || !member(labelToModify, t) )
return FAIL;
return auxModifyElem(labelToModify, newLabel, newCondition, t);
}
//////////////////////////////////////////
// Add new node
//////////////////////////////////////////
Error d_tree::addElem(const Label labelOfNodeInTree, const Label labelOfNodeToAdd, const Label condition, Tree& t){
if(t == emptyTree)
return FAIL;
if(member(labelOfNodeToAdd,t->firstChild))
return FAIL;
if( t->infoEdge.infoLabel.idlabel == emptyLabel){ //if label is empty add root
t->infoEdge.infoLabel.idlabel = labelOfNodeToAdd; //idlabel = label + id for example "Age_1"
unsigned int j = 0;
while(j < labelOfNodeToAdd.size()) {
if(
labelOfNodeToAdd[j] == '_' || labelOfNodeToAdd[j] == '0'||
labelOfNodeToAdd[j] == '1' || labelOfNodeToAdd[j] == '2'||
labelOfNodeToAdd[j] == '3' || labelOfNodeToAdd[j] == '4'||
labelOfNodeToAdd[j] == '5' || labelOfNodeToAdd[j] == '6'||
labelOfNodeToAdd[j] == '7' || labelOfNodeToAdd[j] == '8'||
labelOfNodeToAdd[j] == '9'
)
t->infoEdge.infoLabel.id += labelOfNodeToAdd[j]; //id example: "_1"
else
t->infoEdge.infoLabel.label += labelOfNodeToAdd[j]; //label example: "Age"
j++;
}
return OK;
}
if(t->infoEdge.infoLabel.idlabel == labelOfNodeInTree){ //case where I don't have to insert the root but its children
Tree s = createEmpty();
s->infoEdge.infoLabel.idlabel = labelOfNodeToAdd;
unsigned int i = 0;
while(i < labelOfNodeToAdd.size()) {
if(
labelOfNodeToAdd[i] == '_' || labelOfNodeToAdd[i] == '0'
|| labelOfNodeToAdd[i] == '1' || labelOfNodeToAdd[i] == '2'
|| labelOfNodeToAdd[i] == '3' || labelOfNodeToAdd[i] == '4'
|| labelOfNodeToAdd[i] == '5' || labelOfNodeToAdd[i] == '6'
|| labelOfNodeToAdd[i] == '7' || labelOfNodeToAdd[i] == '8'
|| labelOfNodeToAdd[i] == '9'
)
s->infoEdge.infoLabel.id += labelOfNodeToAdd[i];
else
s->infoEdge.infoLabel.label += labelOfNodeToAdd[i];
i++;
}
i = 0;
while(i < condition.size()) {
if( condition[i] == '<' || condition[i] == '>' || condition[i] == '='|| condition[i] == '!')
s->infoEdge.state.symbol += condition[i];
else
s->infoEdge.state.condition += condition[i];
i++;
}
s->nextSibling = t->firstChild;
t->firstChild = s;
return OK;
}
Tree auxT = t->firstChild;
Error res;
while (auxT != emptyTree) { //scan tree to search where attach new node
res = d_tree::addElem(labelOfNodeInTree,labelOfNodeToAdd, condition, auxT);
if(res == OK)
return res;
else
auxT = auxT->nextSibling;
}
return FAIL;
}
//////////////////////////////////////////
// Remove node
//////////////////////////////////////////
Error d_tree::deleteElem(const Label l, Tree& t){
if(t == emptyTree)
return FAIL;
if(!member(l, t))
return FAIL;
Tree fatherTree = getNode(father(l,t), t); // get father node of node to remove
if(fatherTree == emptyTree)
return FAIL;
if (fatherTree != emptyTree && fatherTree->firstChild == emptyTree) { // can remove tree root just if it has no childs
t = emptyTree;
return OK;
}
else {
Tree nodeToRemove = getNode(l, t);
Tree prevSibl = prevSibling(l, t); // get prev sibling of node to remove
if (prevSibl == emptyTree) // if no prev sibling, the node to remove is the first: so update firstchild of father node to remove the node
fatherTree->firstChild = fatherTree->firstChild->nextSibling;
else // else update nextsibling of prevsibling to remove the node
prevSibl->nextSibling = nodeToRemove->nextSibling;
delete nodeToRemove; // delete the node to remove
}
return OK;
}
//////////////////////////////////////////
// Print tree
//////////////////////////////////////////
void d_tree::printTree(const Tree& t, int counter){
if(t == emptyTree) return;
if( t->infoEdge.state.symbol == emptyLabel && t->infoEdge.state.condition == emptyLabel)
cout<< t->infoEdge.infoLabel.idlabel <<endl;
else{
for(int i = 0; i < counter; ++i)
cout << "--" ;
cout << t->infoEdge.infoLabel.idlabel << " " << t->infoEdge.state.symbol << t->infoEdge.state.condition << endl;
}
Tree auxT = t->firstChild;
while (auxT != emptyTree) {
d_tree::printTree(auxT, counter+1);
auxT = auxT->nextSibling;
}
}
//////////////////////////////////////////
// Print label
//////////////////////////////////////////
void d_tree::printLabel(const Tree& t){
if(t == emptyTree) return;
if(t->infoEdge.infoLabel.id == "_1" && t->infoEdge.infoLabel.label != "END")
cout << t->infoEdge.infoLabel.label << " " << endl;
d_tree::printLabel(t->nextSibling);
d_tree::printLabel(t->firstChild);
}
//////////////////////////////////////////
// Symbol translation
//////////////////////////////////////////
bool d_tree::translation(const Label s, const Label conditionOfUserToroot , const Label conditionOfRoot) {
int firstNumber = str2int(conditionOfUserToroot);
int secondNumber = str2int(conditionOfRoot);
switch(s[0]) {
case '>' :
if(s[1] == '='){
if (firstNumber >= secondNumber) return true;
}
else if(firstNumber > secondNumber) return true;
else return false;
case '<' :
if(s[1] == '='){
if (firstNumber <= secondNumber) return true;
}
else if(firstNumber < secondNumber) return true;
else return false;
case '=' : return firstNumber == secondNumber;
case '!' : return firstNumber != secondNumber;
default : return false;
}
}
Tree list(List& l, string str, int count,const Tree supp, const Tree& t){
List aux, temp;
Tree res = supp;
int i = 1;
aux = new Cell;
aux->s = str;
aux->next = l;
l = aux;
if(count > 1){ //if count > 1 more than one condition verified
temp = l;
count = rand() % count + 1; // choose random condition between the verified conditions
while(i != count){ // search in the list the label of the condition chosen
temp = temp->next;
++i;
}
res = getNode(temp->s, t); // assign to res the node with that label
}
return res;
}
//////////////////////////////////////////
// Prediction Tree once by one
//////////////////////////////////////////
Label d_tree::predictionTree_OnceByOne(const Tree& t) {
if(t == emptyTree) return emptyLabel;
Label conditionOfUserToroot, conditionOfUserToNodeInTree;
List l;
int count = 0;
Tree foundNode = emptyTree;
Tree aux = t->firstChild;
cout << "Inserisci "<< t->infoEdge.infoLabel.label<<": "; // ask to insert the condition
cin >> conditionOfUserToroot;
while(aux != emptyTree){
if(translation(aux->infoEdge.state.symbol, conditionOfUserToroot, aux->infoEdge.state.condition)){ //if condition verified
++count; //count tells me how many conditions verified there are
foundNode = list(l, aux->infoEdge.infoLabel.idlabel, count, aux, t); // save in foundNode the condition chosen if count > 1
aux = aux->nextSibling; // go ahead in the siblings to check conditions
}
else
aux = aux->nextSibling;
}
if(foundNode == emptyTree) return emptyLabel; //if equal to emptyTree all conditions are false
aux = foundNode;
if(aux->firstChild->infoEdge.infoLabel.label == "END") return aux->firstChild->infoEdge.state.condition;//if label of first child is END return his condition
else{
cout << "Inserisci "<< aux->infoEdge.infoLabel.label<<": ";//insert condition to search in the node where condition was verified
cin >> conditionOfUserToNodeInTree;
cout << endl;
}
aux = aux->firstChild;
while(aux != emptyTree){
if(aux->infoEdge.state.condition == conditionOfUserToNodeInTree){// search condition
aux = aux->firstChild;
return aux->infoEdge.state.condition;
}
else
aux = aux->nextSibling;
}
return emptyLabel;
}
Label d_tree::predictionTree(const Label labelOfNodeInTree, const Label conditionOfUserToNodeInTree,const Label root, const Label conditionOfUserToroot, const Tree& t) {
if(t == emptyTree || (t->infoEdge.infoLabel.label != root) || (!memberLabel(labelOfNodeInTree, t))) return emptyLabel;
List l;
int count = 0;
Tree foundNode = emptyTree;
Tree aux = t->firstChild;
while(aux != emptyTree){
if(translation(aux->infoEdge.state.symbol, conditionOfUserToroot, aux->infoEdge.state.condition)){
++count; //count tells me how many true conditions there are (choose at random if count> 1)
foundNode = list(l, aux->infoEdge.infoLabel.idlabel, count, aux, t); // save in foundNode the chosen condition if count > 1 rlde foundNode = aux
aux = aux->nextSibling; //go ahead in the siblings to check the conditions
}
else
aux = aux->nextSibling;
}
if(foundNode == emptyTree) return emptyLabel; //if equal to emptyTree all conditions are false
aux = foundNode; //update aux with the node with true condition
if(aux->firstChild->infoEdge.infoLabel.label == "END") //if label of first child is END return his condition
return aux->firstChild->infoEdge.state.condition;
aux = aux->firstChild; //else go ahead to search in the childs' conditions
while(aux != emptyTree){
if(aux->infoEdge.state.condition == conditionOfUserToNodeInTree){ //search condition in his childs
aux = aux->firstChild;
return aux->infoEdge.state.condition;
}
else
aux = aux->nextSibling;
}
return emptyLabel;
}
Tree readFromStream(istream& str){
Tree t = createEmpty();
string line;
Label rootLabel, fatherLabel, childLabel, condition;
getline(str, line);
istringstream instream; // variable of type istringstream to be able to scan the pieces of each line using >>
instream.clear();
instream.str(line);
instream >> rootLabel; // the first element encountered in the file is the root label
removeBlanksandOther(fatherLabel); // normalize the root label
addElem(emptyLabel, rootLabel, emptyLabel, t); // insert it in the empty tree, indicating that the father is not there (first argument emptyLabel)
getline(str, line); // start to scan the following rows
instream.clear();
instream.str(line);
while (!str.eof()){
instream >> fatherLabel; // in each line of the file, the first element is the parent node label and the others are the child labels
removeBlanksandOther(fatherLabel); // normalize father label
while(!instream.eof()){
instream >> childLabel; //insert child label
removeBlanksandOther(childLabel); // normalize child label
instream >> condition; //insert child condition
removeBlanksandOther(condition); // normalize child condition
addElem(fatherLabel, childLabel, condition, t); // add row to decision tree
}
getline(str, line);
instream.clear();
instream.str(line);
}
str.clear();
return t;
}
Tree readFromFile(string nome_file)
{
ifstream ifs(nome_file.c_str()); // opening a stream associated with a file, reading mode
if (!ifs){
cout << "\nErrore apertura file, verificare di avere inserito un nome corretto\n";
return createEmpty();
}
return readFromStream(ifs);
}
|
Java | UTF-8 | 115,211 | 1.648438 | 2 | [] | no_license |
package mx.babel.bansefi.banksystem.cuentas.webservices.aprobacionplazo;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Clase Java para anonymous complex type.
*
* <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="USERHEADER" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="PASSHEADER" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="IPHEADER" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="ITR_APROB_SOL_IMPSCN_PAG">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="TR_APROB_SOL_IMPSCN_PAG_E">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="IP_IMPSCN_P">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="COD_NRBE_EN">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000004"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="COD_CENT_UO">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000004"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="NUM_SEC_AC">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <maxInclusive value="9999999999"/>
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </element>
* <element name="NUM_SUBAC">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <maxInclusive value="9999999"/>
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="COD_INTERNO_UO">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000004"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="FECHA_VTO">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <maxInclusive value="99999999"/>
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </element>
* <element name="FECHA_VALOR">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <maxInclusive value="99999999"/>
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="STD_TRN_I_PARM_V">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ID_INTERNO_TERM_TN">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000008"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="ID_EMPL_AUT">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000008"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="NUM_SEC">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <maxInclusive value="9999999"/>
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </element>
* <element name="COD_TX">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000008"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="COD_TX_DI">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000004"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="STD_AUTORIZA_V">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="IND_BORRADO_AR">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000001"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="DESCR_TX">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000050"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="IND_AUT_SOLIC">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000001"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="IND_ATRIB_MANC_EP">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000001"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="COD_ESTADO_AR">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000001"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="ID_EMPL_SOL_AUT">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000008"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="IND_VERIF_ATRIB">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000001"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="IND_URG_AR">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000001"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="MOTIVO_ACCION_AUT_LEN">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <maxInclusive value="9999"/>
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </element>
* <element name="MOTIVO_ACCION_AUT">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000200"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="IND_ESCALABLE">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000001"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="IMP_AUT">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}decimal">
* <totalDigits value="0000000015"/>
* <fractionDigits value="02"/>
* <maxInclusive value="9999999999999.99"/>
* <minInclusive value="0.0"/>
* </restriction>
* </simpleType>
* </element>
* <element name="IMPORTE_AR">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}decimal">
* <totalDigits value="0000000015"/>
* <fractionDigits value="02"/>
* <maxInclusive value="9999999999999.99"/>
* <minInclusive value="0.0"/>
* </restriction>
* </simpleType>
* </element>
* <element name="AR_AUT_REMOTA_P">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="COD_NRBE_EN">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000004"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="ID_INTERNO_TERM_TN">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000008"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="FECHA_OPRCN">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <maxInclusive value="99999999"/>
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </element>
* <element name="HORA_OPRCN">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <maxInclusive value="99999999"/>
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="AR_TRN_MSJ_PARM_V" maxOccurs="10">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="TEXT_CODE">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <maxInclusive value="9999"/>
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </element>
* <element name="TEXT_ARG1">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000018"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="STD_TARGET_TERMINAL_V" maxOccurs="50">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ID_INTERNO_EMPL_EP">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000008"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="ID_INTERNO_TERM_TN">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000008"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="COD_ECV_SESION">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000001"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="AR_ID_SALTADO_V">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ID_INTERNO_EMPL_EP">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000008"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"userheader",
"passheader",
"ipheader",
"itraprobsolimpscnpag"
})
@XmlRootElement(name = "Ejecutar")
public class Ejecutar {
@XmlElement(name = "USERHEADER", required = true)
protected String userheader;
@XmlElement(name = "PASSHEADER", required = true)
protected String passheader;
@XmlElement(name = "IPHEADER", required = true)
protected String ipheader;
@XmlElement(name = "ITR_APROB_SOL_IMPSCN_PAG", required = true)
protected Ejecutar.ITRAPROBSOLIMPSCNPAG itraprobsolimpscnpag;
/**
* Obtiene el valor de la propiedad userheader.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUSERHEADER() {
return userheader;
}
/**
* Define el valor de la propiedad userheader.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUSERHEADER(String value) {
this.userheader = value;
}
/**
* Obtiene el valor de la propiedad passheader.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPASSHEADER() {
return passheader;
}
/**
* Define el valor de la propiedad passheader.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPASSHEADER(String value) {
this.passheader = value;
}
/**
* Obtiene el valor de la propiedad ipheader.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIPHEADER() {
return ipheader;
}
/**
* Define el valor de la propiedad ipheader.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIPHEADER(String value) {
this.ipheader = value;
}
/**
* Obtiene el valor de la propiedad itraprobsolimpscnpag.
*
* @return
* possible object is
* {@link Ejecutar.ITRAPROBSOLIMPSCNPAG }
*
*/
public Ejecutar.ITRAPROBSOLIMPSCNPAG getITRAPROBSOLIMPSCNPAG() {
return itraprobsolimpscnpag;
}
/**
* Define el valor de la propiedad itraprobsolimpscnpag.
*
* @param value
* allowed object is
* {@link Ejecutar.ITRAPROBSOLIMPSCNPAG }
*
*/
public void setITRAPROBSOLIMPSCNPAG(Ejecutar.ITRAPROBSOLIMPSCNPAG value) {
this.itraprobsolimpscnpag = value;
}
/**
* <p>Clase Java para anonymous complex type.
*
* <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="TR_APROB_SOL_IMPSCN_PAG_E">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="IP_IMPSCN_P">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="COD_NRBE_EN">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000004"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="COD_CENT_UO">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000004"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="NUM_SEC_AC">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <maxInclusive value="9999999999"/>
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </element>
* <element name="NUM_SUBAC">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <maxInclusive value="9999999"/>
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="COD_INTERNO_UO">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000004"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="FECHA_VTO">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <maxInclusive value="99999999"/>
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </element>
* <element name="FECHA_VALOR">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <maxInclusive value="99999999"/>
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="STD_TRN_I_PARM_V">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ID_INTERNO_TERM_TN">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000008"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="ID_EMPL_AUT">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000008"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="NUM_SEC">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <maxInclusive value="9999999"/>
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </element>
* <element name="COD_TX">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000008"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="COD_TX_DI">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000004"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="STD_AUTORIZA_V">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="IND_BORRADO_AR">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000001"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="DESCR_TX">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000050"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="IND_AUT_SOLIC">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000001"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="IND_ATRIB_MANC_EP">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000001"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="COD_ESTADO_AR">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000001"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="ID_EMPL_SOL_AUT">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000008"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="IND_VERIF_ATRIB">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000001"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="IND_URG_AR">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000001"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="MOTIVO_ACCION_AUT_LEN">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <maxInclusive value="9999"/>
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </element>
* <element name="MOTIVO_ACCION_AUT">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000200"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="IND_ESCALABLE">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000001"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="IMP_AUT">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}decimal">
* <totalDigits value="0000000015"/>
* <fractionDigits value="02"/>
* <maxInclusive value="9999999999999.99"/>
* <minInclusive value="0.0"/>
* </restriction>
* </simpleType>
* </element>
* <element name="IMPORTE_AR">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}decimal">
* <totalDigits value="0000000015"/>
* <fractionDigits value="02"/>
* <maxInclusive value="9999999999999.99"/>
* <minInclusive value="0.0"/>
* </restriction>
* </simpleType>
* </element>
* <element name="AR_AUT_REMOTA_P">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="COD_NRBE_EN">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000004"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="ID_INTERNO_TERM_TN">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000008"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="FECHA_OPRCN">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <maxInclusive value="99999999"/>
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </element>
* <element name="HORA_OPRCN">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <maxInclusive value="99999999"/>
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="AR_TRN_MSJ_PARM_V" maxOccurs="10">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="TEXT_CODE">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <maxInclusive value="9999"/>
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </element>
* <element name="TEXT_ARG1">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000018"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="STD_TARGET_TERMINAL_V" maxOccurs="50">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ID_INTERNO_EMPL_EP">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000008"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="ID_INTERNO_TERM_TN">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000008"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="COD_ECV_SESION">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000001"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="AR_ID_SALTADO_V">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ID_INTERNO_EMPL_EP">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000008"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"traprobsolimpscnpage",
"stdtrniparmv",
"stdautorizav"
})
public static class ITRAPROBSOLIMPSCNPAG {
@XmlElement(name = "TR_APROB_SOL_IMPSCN_PAG_E", required = true)
protected Ejecutar.ITRAPROBSOLIMPSCNPAG.TRAPROBSOLIMPSCNPAGE traprobsolimpscnpage;
@XmlElement(name = "STD_TRN_I_PARM_V", required = true)
protected Ejecutar.ITRAPROBSOLIMPSCNPAG.STDTRNIPARMV stdtrniparmv;
@XmlElement(name = "STD_AUTORIZA_V", required = true)
protected Ejecutar.ITRAPROBSOLIMPSCNPAG.STDAUTORIZAV stdautorizav;
/**
* Obtiene el valor de la propiedad traprobsolimpscnpage.
*
* @return
* possible object is
* {@link Ejecutar.ITRAPROBSOLIMPSCNPAG.TRAPROBSOLIMPSCNPAGE }
*
*/
public Ejecutar.ITRAPROBSOLIMPSCNPAG.TRAPROBSOLIMPSCNPAGE getTRAPROBSOLIMPSCNPAGE() {
return traprobsolimpscnpage;
}
/**
* Define el valor de la propiedad traprobsolimpscnpage.
*
* @param value
* allowed object is
* {@link Ejecutar.ITRAPROBSOLIMPSCNPAG.TRAPROBSOLIMPSCNPAGE }
*
*/
public void setTRAPROBSOLIMPSCNPAGE(Ejecutar.ITRAPROBSOLIMPSCNPAG.TRAPROBSOLIMPSCNPAGE value) {
this.traprobsolimpscnpage = value;
}
/**
* Obtiene el valor de la propiedad stdtrniparmv.
*
* @return
* possible object is
* {@link Ejecutar.ITRAPROBSOLIMPSCNPAG.STDTRNIPARMV }
*
*/
public Ejecutar.ITRAPROBSOLIMPSCNPAG.STDTRNIPARMV getSTDTRNIPARMV() {
return stdtrniparmv;
}
/**
* Define el valor de la propiedad stdtrniparmv.
*
* @param value
* allowed object is
* {@link Ejecutar.ITRAPROBSOLIMPSCNPAG.STDTRNIPARMV }
*
*/
public void setSTDTRNIPARMV(Ejecutar.ITRAPROBSOLIMPSCNPAG.STDTRNIPARMV value) {
this.stdtrniparmv = value;
}
/**
* Obtiene el valor de la propiedad stdautorizav.
*
* @return
* possible object is
* {@link Ejecutar.ITRAPROBSOLIMPSCNPAG.STDAUTORIZAV }
*
*/
public Ejecutar.ITRAPROBSOLIMPSCNPAG.STDAUTORIZAV getSTDAUTORIZAV() {
return stdautorizav;
}
/**
* Define el valor de la propiedad stdautorizav.
*
* @param value
* allowed object is
* {@link Ejecutar.ITRAPROBSOLIMPSCNPAG.STDAUTORIZAV }
*
*/
public void setSTDAUTORIZAV(Ejecutar.ITRAPROBSOLIMPSCNPAG.STDAUTORIZAV value) {
this.stdautorizav = value;
}
/**
* <p>Clase Java para anonymous complex type.
*
* <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="IND_BORRADO_AR">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000001"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="DESCR_TX">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000050"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="IND_AUT_SOLIC">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000001"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="IND_ATRIB_MANC_EP">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000001"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="COD_ESTADO_AR">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000001"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="ID_EMPL_SOL_AUT">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000008"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="IND_VERIF_ATRIB">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000001"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="IND_URG_AR">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000001"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="MOTIVO_ACCION_AUT_LEN">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <maxInclusive value="9999"/>
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </element>
* <element name="MOTIVO_ACCION_AUT">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000200"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="IND_ESCALABLE">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000001"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="IMP_AUT">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}decimal">
* <totalDigits value="0000000015"/>
* <fractionDigits value="02"/>
* <maxInclusive value="9999999999999.99"/>
* <minInclusive value="0.0"/>
* </restriction>
* </simpleType>
* </element>
* <element name="IMPORTE_AR">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}decimal">
* <totalDigits value="0000000015"/>
* <fractionDigits value="02"/>
* <maxInclusive value="9999999999999.99"/>
* <minInclusive value="0.0"/>
* </restriction>
* </simpleType>
* </element>
* <element name="AR_AUT_REMOTA_P">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="COD_NRBE_EN">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000004"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="ID_INTERNO_TERM_TN">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000008"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="FECHA_OPRCN">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <maxInclusive value="99999999"/>
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </element>
* <element name="HORA_OPRCN">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <maxInclusive value="99999999"/>
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="AR_TRN_MSJ_PARM_V" maxOccurs="10">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="TEXT_CODE">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <maxInclusive value="9999"/>
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </element>
* <element name="TEXT_ARG1">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000018"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="STD_TARGET_TERMINAL_V" maxOccurs="50">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ID_INTERNO_EMPL_EP">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000008"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="ID_INTERNO_TERM_TN">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000008"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="COD_ECV_SESION">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000001"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="AR_ID_SALTADO_V">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ID_INTERNO_EMPL_EP">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000008"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"indborradoar",
"descrtx",
"indautsolic",
"indatribmancep",
"codestadoar",
"idemplsolaut",
"indverifatrib",
"indurgar",
"motivoaccionautlen",
"motivoaccionaut",
"indescalable",
"impaut",
"importear",
"arautremotap",
"artrnmsjparmv",
"stdtargetterminalv",
"aridsaltadov"
})
public static class STDAUTORIZAV {
@XmlElement(name = "IND_BORRADO_AR", required = true)
protected String indborradoar;
@XmlElement(name = "DESCR_TX", required = true)
protected String descrtx;
@XmlElement(name = "IND_AUT_SOLIC", required = true)
protected String indautsolic;
@XmlElement(name = "IND_ATRIB_MANC_EP", required = true)
protected String indatribmancep;
@XmlElement(name = "COD_ESTADO_AR", required = true)
protected String codestadoar;
@XmlElement(name = "ID_EMPL_SOL_AUT", required = true)
protected String idemplsolaut;
@XmlElement(name = "IND_VERIF_ATRIB", required = true)
protected String indverifatrib;
@XmlElement(name = "IND_URG_AR", required = true)
protected String indurgar;
@XmlElement(name = "MOTIVO_ACCION_AUT_LEN")
protected int motivoaccionautlen;
@XmlElement(name = "MOTIVO_ACCION_AUT", required = true)
protected String motivoaccionaut;
@XmlElement(name = "IND_ESCALABLE", required = true)
protected String indescalable;
@XmlElement(name = "IMP_AUT", required = true)
protected BigDecimal impaut;
@XmlElement(name = "IMPORTE_AR", required = true)
protected BigDecimal importear;
@XmlElement(name = "AR_AUT_REMOTA_P", required = true)
protected Ejecutar.ITRAPROBSOLIMPSCNPAG.STDAUTORIZAV.ARAUTREMOTAP arautremotap;
@XmlElement(name = "AR_TRN_MSJ_PARM_V", required = true)
protected List<Ejecutar.ITRAPROBSOLIMPSCNPAG.STDAUTORIZAV.ARTRNMSJPARMV> artrnmsjparmv;
@XmlElement(name = "STD_TARGET_TERMINAL_V", required = true)
protected List<Ejecutar.ITRAPROBSOLIMPSCNPAG.STDAUTORIZAV.STDTARGETTERMINALV> stdtargetterminalv;
@XmlElement(name = "AR_ID_SALTADO_V", required = true)
protected Ejecutar.ITRAPROBSOLIMPSCNPAG.STDAUTORIZAV.ARIDSALTADOV aridsaltadov;
/**
* Obtiene el valor de la propiedad indborradoar.
*
* @return
* possible object is
* {@link String }
*
*/
public String getINDBORRADOAR() {
return indborradoar;
}
/**
* Define el valor de la propiedad indborradoar.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setINDBORRADOAR(String value) {
this.indborradoar = value;
}
/**
* Obtiene el valor de la propiedad descrtx.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDESCRTX() {
return descrtx;
}
/**
* Define el valor de la propiedad descrtx.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDESCRTX(String value) {
this.descrtx = value;
}
/**
* Obtiene el valor de la propiedad indautsolic.
*
* @return
* possible object is
* {@link String }
*
*/
public String getINDAUTSOLIC() {
return indautsolic;
}
/**
* Define el valor de la propiedad indautsolic.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setINDAUTSOLIC(String value) {
this.indautsolic = value;
}
/**
* Obtiene el valor de la propiedad indatribmancep.
*
* @return
* possible object is
* {@link String }
*
*/
public String getINDATRIBMANCEP() {
return indatribmancep;
}
/**
* Define el valor de la propiedad indatribmancep.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setINDATRIBMANCEP(String value) {
this.indatribmancep = value;
}
/**
* Obtiene el valor de la propiedad codestadoar.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCODESTADOAR() {
return codestadoar;
}
/**
* Define el valor de la propiedad codestadoar.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCODESTADOAR(String value) {
this.codestadoar = value;
}
/**
* Obtiene el valor de la propiedad idemplsolaut.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIDEMPLSOLAUT() {
return idemplsolaut;
}
/**
* Define el valor de la propiedad idemplsolaut.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIDEMPLSOLAUT(String value) {
this.idemplsolaut = value;
}
/**
* Obtiene el valor de la propiedad indverifatrib.
*
* @return
* possible object is
* {@link String }
*
*/
public String getINDVERIFATRIB() {
return indverifatrib;
}
/**
* Define el valor de la propiedad indverifatrib.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setINDVERIFATRIB(String value) {
this.indverifatrib = value;
}
/**
* Obtiene el valor de la propiedad indurgar.
*
* @return
* possible object is
* {@link String }
*
*/
public String getINDURGAR() {
return indurgar;
}
/**
* Define el valor de la propiedad indurgar.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setINDURGAR(String value) {
this.indurgar = value;
}
/**
* Obtiene el valor de la propiedad motivoaccionautlen.
*
*/
public int getMOTIVOACCIONAUTLEN() {
return motivoaccionautlen;
}
/**
* Define el valor de la propiedad motivoaccionautlen.
*
*/
public void setMOTIVOACCIONAUTLEN(int value) {
this.motivoaccionautlen = value;
}
/**
* Obtiene el valor de la propiedad motivoaccionaut.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMOTIVOACCIONAUT() {
return motivoaccionaut;
}
/**
* Define el valor de la propiedad motivoaccionaut.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMOTIVOACCIONAUT(String value) {
this.motivoaccionaut = value;
}
/**
* Obtiene el valor de la propiedad indescalable.
*
* @return
* possible object is
* {@link String }
*
*/
public String getINDESCALABLE() {
return indescalable;
}
/**
* Define el valor de la propiedad indescalable.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setINDESCALABLE(String value) {
this.indescalable = value;
}
/**
* Obtiene el valor de la propiedad impaut.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getIMPAUT() {
return impaut;
}
/**
* Define el valor de la propiedad impaut.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setIMPAUT(BigDecimal value) {
this.impaut = value;
}
/**
* Obtiene el valor de la propiedad importear.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getIMPORTEAR() {
return importear;
}
/**
* Define el valor de la propiedad importear.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setIMPORTEAR(BigDecimal value) {
this.importear = value;
}
/**
* Obtiene el valor de la propiedad arautremotap.
*
* @return
* possible object is
* {@link Ejecutar.ITRAPROBSOLIMPSCNPAG.STDAUTORIZAV.ARAUTREMOTAP }
*
*/
public Ejecutar.ITRAPROBSOLIMPSCNPAG.STDAUTORIZAV.ARAUTREMOTAP getARAUTREMOTAP() {
return arautremotap;
}
/**
* Define el valor de la propiedad arautremotap.
*
* @param value
* allowed object is
* {@link Ejecutar.ITRAPROBSOLIMPSCNPAG.STDAUTORIZAV.ARAUTREMOTAP }
*
*/
public void setARAUTREMOTAP(Ejecutar.ITRAPROBSOLIMPSCNPAG.STDAUTORIZAV.ARAUTREMOTAP value) {
this.arautremotap = value;
}
/**
* Gets the value of the artrnmsjparmv property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the artrnmsjparmv property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getARTRNMSJPARMV().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Ejecutar.ITRAPROBSOLIMPSCNPAG.STDAUTORIZAV.ARTRNMSJPARMV }
*
*
*/
public List<Ejecutar.ITRAPROBSOLIMPSCNPAG.STDAUTORIZAV.ARTRNMSJPARMV> getARTRNMSJPARMV() {
if (artrnmsjparmv == null) {
artrnmsjparmv = new ArrayList<Ejecutar.ITRAPROBSOLIMPSCNPAG.STDAUTORIZAV.ARTRNMSJPARMV>();
}
return this.artrnmsjparmv;
}
/**
* Gets the value of the stdtargetterminalv property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the stdtargetterminalv property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getSTDTARGETTERMINALV().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Ejecutar.ITRAPROBSOLIMPSCNPAG.STDAUTORIZAV.STDTARGETTERMINALV }
*
*
*/
public List<Ejecutar.ITRAPROBSOLIMPSCNPAG.STDAUTORIZAV.STDTARGETTERMINALV> getSTDTARGETTERMINALV() {
if (stdtargetterminalv == null) {
stdtargetterminalv = new ArrayList<Ejecutar.ITRAPROBSOLIMPSCNPAG.STDAUTORIZAV.STDTARGETTERMINALV>();
}
return this.stdtargetterminalv;
}
/**
* Obtiene el valor de la propiedad aridsaltadov.
*
* @return
* possible object is
* {@link Ejecutar.ITRAPROBSOLIMPSCNPAG.STDAUTORIZAV.ARIDSALTADOV }
*
*/
public Ejecutar.ITRAPROBSOLIMPSCNPAG.STDAUTORIZAV.ARIDSALTADOV getARIDSALTADOV() {
return aridsaltadov;
}
/**
* Define el valor de la propiedad aridsaltadov.
*
* @param value
* allowed object is
* {@link Ejecutar.ITRAPROBSOLIMPSCNPAG.STDAUTORIZAV.ARIDSALTADOV }
*
*/
public void setARIDSALTADOV(Ejecutar.ITRAPROBSOLIMPSCNPAG.STDAUTORIZAV.ARIDSALTADOV value) {
this.aridsaltadov = value;
}
/**
* <p>Clase Java para anonymous complex type.
*
* <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="COD_NRBE_EN">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000004"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="ID_INTERNO_TERM_TN">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000008"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="FECHA_OPRCN">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <maxInclusive value="99999999"/>
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </element>
* <element name="HORA_OPRCN">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <maxInclusive value="99999999"/>
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"codnrbeen",
"idinternotermtn",
"fechaoprcn",
"horaoprcn"
})
public static class ARAUTREMOTAP {
@XmlElement(name = "COD_NRBE_EN", required = true)
protected String codnrbeen;
@XmlElement(name = "ID_INTERNO_TERM_TN", required = true)
protected String idinternotermtn;
@XmlElement(name = "FECHA_OPRCN")
protected int fechaoprcn;
@XmlElement(name = "HORA_OPRCN")
protected int horaoprcn;
/**
* Obtiene el valor de la propiedad codnrbeen.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCODNRBEEN() {
return codnrbeen;
}
/**
* Define el valor de la propiedad codnrbeen.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCODNRBEEN(String value) {
this.codnrbeen = value;
}
/**
* Obtiene el valor de la propiedad idinternotermtn.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIDINTERNOTERMTN() {
return idinternotermtn;
}
/**
* Define el valor de la propiedad idinternotermtn.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIDINTERNOTERMTN(String value) {
this.idinternotermtn = value;
}
/**
* Obtiene el valor de la propiedad fechaoprcn.
*
*/
public int getFECHAOPRCN() {
return fechaoprcn;
}
/**
* Define el valor de la propiedad fechaoprcn.
*
*/
public void setFECHAOPRCN(int value) {
this.fechaoprcn = value;
}
/**
* Obtiene el valor de la propiedad horaoprcn.
*
*/
public int getHORAOPRCN() {
return horaoprcn;
}
/**
* Define el valor de la propiedad horaoprcn.
*
*/
public void setHORAOPRCN(int value) {
this.horaoprcn = value;
}
}
/**
* <p>Clase Java para anonymous complex type.
*
* <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ID_INTERNO_EMPL_EP">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000008"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"idinternoemplep"
})
public static class ARIDSALTADOV {
@XmlElement(name = "ID_INTERNO_EMPL_EP", required = true)
protected String idinternoemplep;
/**
* Obtiene el valor de la propiedad idinternoemplep.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIDINTERNOEMPLEP() {
return idinternoemplep;
}
/**
* Define el valor de la propiedad idinternoemplep.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIDINTERNOEMPLEP(String value) {
this.idinternoemplep = value;
}
}
/**
* <p>Clase Java para anonymous complex type.
*
* <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="TEXT_CODE">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <maxInclusive value="9999"/>
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </element>
* <element name="TEXT_ARG1">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000018"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"textcode",
"textarg1"
})
public static class ARTRNMSJPARMV {
@XmlElement(name = "TEXT_CODE")
protected int textcode;
@XmlElement(name = "TEXT_ARG1", required = true)
protected String textarg1;
/**
* Obtiene el valor de la propiedad textcode.
*
*/
public int getTEXTCODE() {
return textcode;
}
/**
* Define el valor de la propiedad textcode.
*
*/
public void setTEXTCODE(int value) {
this.textcode = value;
}
/**
* Obtiene el valor de la propiedad textarg1.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTEXTARG1() {
return textarg1;
}
/**
* Define el valor de la propiedad textarg1.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTEXTARG1(String value) {
this.textarg1 = value;
}
}
/**
* <p>Clase Java para anonymous complex type.
*
* <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ID_INTERNO_EMPL_EP">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000008"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="ID_INTERNO_TERM_TN">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000008"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="COD_ECV_SESION">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000001"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"idinternoemplep",
"idinternotermtn",
"codecvsesion"
})
public static class STDTARGETTERMINALV {
@XmlElement(name = "ID_INTERNO_EMPL_EP", required = true)
protected String idinternoemplep;
@XmlElement(name = "ID_INTERNO_TERM_TN", required = true)
protected String idinternotermtn;
@XmlElement(name = "COD_ECV_SESION", required = true)
protected String codecvsesion;
/**
* Obtiene el valor de la propiedad idinternoemplep.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIDINTERNOEMPLEP() {
return idinternoemplep;
}
/**
* Define el valor de la propiedad idinternoemplep.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIDINTERNOEMPLEP(String value) {
this.idinternoemplep = value;
}
/**
* Obtiene el valor de la propiedad idinternotermtn.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIDINTERNOTERMTN() {
return idinternotermtn;
}
/**
* Define el valor de la propiedad idinternotermtn.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIDINTERNOTERMTN(String value) {
this.idinternotermtn = value;
}
/**
* Obtiene el valor de la propiedad codecvsesion.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCODECVSESION() {
return codecvsesion;
}
/**
* Define el valor de la propiedad codecvsesion.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCODECVSESION(String value) {
this.codecvsesion = value;
}
}
}
/**
* <p>Clase Java para anonymous complex type.
*
* <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ID_INTERNO_TERM_TN">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000008"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="ID_EMPL_AUT">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000008"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="NUM_SEC">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <maxInclusive value="9999999"/>
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </element>
* <element name="COD_TX">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000008"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="COD_TX_DI">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000004"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"idinternotermtn",
"idemplaut",
"numsec",
"codtx",
"codtxdi"
})
public static class STDTRNIPARMV {
@XmlElement(name = "ID_INTERNO_TERM_TN", required = true)
protected String idinternotermtn;
@XmlElement(name = "ID_EMPL_AUT", required = true)
protected String idemplaut;
@XmlElement(name = "NUM_SEC")
protected int numsec;
@XmlElement(name = "COD_TX", required = true)
protected String codtx;
@XmlElement(name = "COD_TX_DI", required = true)
protected String codtxdi;
/**
* Obtiene el valor de la propiedad idinternotermtn.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIDINTERNOTERMTN() {
return idinternotermtn;
}
/**
* Define el valor de la propiedad idinternotermtn.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIDINTERNOTERMTN(String value) {
this.idinternotermtn = value;
}
/**
* Obtiene el valor de la propiedad idemplaut.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIDEMPLAUT() {
return idemplaut;
}
/**
* Define el valor de la propiedad idemplaut.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIDEMPLAUT(String value) {
this.idemplaut = value;
}
/**
* Obtiene el valor de la propiedad numsec.
*
*/
public int getNUMSEC() {
return numsec;
}
/**
* Define el valor de la propiedad numsec.
*
*/
public void setNUMSEC(int value) {
this.numsec = value;
}
/**
* Obtiene el valor de la propiedad codtx.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCODTX() {
return codtx;
}
/**
* Define el valor de la propiedad codtx.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCODTX(String value) {
this.codtx = value;
}
/**
* Obtiene el valor de la propiedad codtxdi.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCODTXDI() {
return codtxdi;
}
/**
* Define el valor de la propiedad codtxdi.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCODTXDI(String value) {
this.codtxdi = value;
}
}
/**
* <p>Clase Java para anonymous complex type.
*
* <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="IP_IMPSCN_P">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="COD_NRBE_EN">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000004"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="COD_CENT_UO">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000004"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="NUM_SEC_AC">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <maxInclusive value="9999999999"/>
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </element>
* <element name="NUM_SUBAC">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <maxInclusive value="9999999"/>
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="COD_INTERNO_UO">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000004"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="FECHA_VTO">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <maxInclusive value="99999999"/>
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </element>
* <element name="FECHA_VALOR">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <maxInclusive value="99999999"/>
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"ipimpscnp",
"codinternouo",
"fechavto",
"fechavalor"
})
public static class TRAPROBSOLIMPSCNPAGE {
@XmlElement(name = "IP_IMPSCN_P", required = true)
protected Ejecutar.ITRAPROBSOLIMPSCNPAG.TRAPROBSOLIMPSCNPAGE.IPIMPSCNP ipimpscnp;
@XmlElement(name = "COD_INTERNO_UO", required = true)
protected String codinternouo;
@XmlElement(name = "FECHA_VTO")
protected int fechavto;
@XmlElement(name = "FECHA_VALOR")
protected int fechavalor;
/**
* Obtiene el valor de la propiedad ipimpscnp.
*
* @return
* possible object is
* {@link Ejecutar.ITRAPROBSOLIMPSCNPAG.TRAPROBSOLIMPSCNPAGE.IPIMPSCNP }
*
*/
public Ejecutar.ITRAPROBSOLIMPSCNPAG.TRAPROBSOLIMPSCNPAGE.IPIMPSCNP getIPIMPSCNP() {
return ipimpscnp;
}
/**
* Define el valor de la propiedad ipimpscnp.
*
* @param value
* allowed object is
* {@link Ejecutar.ITRAPROBSOLIMPSCNPAG.TRAPROBSOLIMPSCNPAGE.IPIMPSCNP }
*
*/
public void setIPIMPSCNP(Ejecutar.ITRAPROBSOLIMPSCNPAG.TRAPROBSOLIMPSCNPAGE.IPIMPSCNP value) {
this.ipimpscnp = value;
}
/**
* Obtiene el valor de la propiedad codinternouo.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCODINTERNOUO() {
return codinternouo;
}
/**
* Define el valor de la propiedad codinternouo.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCODINTERNOUO(String value) {
this.codinternouo = value;
}
/**
* Obtiene el valor de la propiedad fechavto.
*
*/
public int getFECHAVTO() {
return fechavto;
}
/**
* Define el valor de la propiedad fechavto.
*
*/
public void setFECHAVTO(int value) {
this.fechavto = value;
}
/**
* Obtiene el valor de la propiedad fechavalor.
*
*/
public int getFECHAVALOR() {
return fechavalor;
}
/**
* Define el valor de la propiedad fechavalor.
*
*/
public void setFECHAVALOR(int value) {
this.fechavalor = value;
}
/**
* <p>Clase Java para anonymous complex type.
*
* <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="COD_NRBE_EN">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000004"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="COD_CENT_UO">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="0000000004"/>
* <whiteSpace value="preserve"/>
* </restriction>
* </simpleType>
* </element>
* <element name="NUM_SEC_AC">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <maxInclusive value="9999999999"/>
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </element>
* <element name="NUM_SUBAC">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}integer">
* <maxInclusive value="9999999"/>
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"codnrbeen",
"codcentuo",
"numsecac",
"numsubac"
})
public static class IPIMPSCNP {
@XmlElement(name = "COD_NRBE_EN", required = true)
protected String codnrbeen;
@XmlElement(name = "COD_CENT_UO", required = true)
protected String codcentuo;
@XmlElement(name = "NUM_SEC_AC")
protected long numsecac;
@XmlElement(name = "NUM_SUBAC")
protected int numsubac;
/**
* Obtiene el valor de la propiedad codnrbeen.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCODNRBEEN() {
return codnrbeen;
}
/**
* Define el valor de la propiedad codnrbeen.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCODNRBEEN(String value) {
this.codnrbeen = value;
}
/**
* Obtiene el valor de la propiedad codcentuo.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCODCENTUO() {
return codcentuo;
}
/**
* Define el valor de la propiedad codcentuo.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCODCENTUO(String value) {
this.codcentuo = value;
}
/**
* Obtiene el valor de la propiedad numsecac.
*
*/
public long getNUMSECAC() {
return numsecac;
}
/**
* Define el valor de la propiedad numsecac.
*
*/
public void setNUMSECAC(long value) {
this.numsecac = value;
}
/**
* Obtiene el valor de la propiedad numsubac.
*
*/
public int getNUMSUBAC() {
return numsubac;
}
/**
* Define el valor de la propiedad numsubac.
*
*/
public void setNUMSUBAC(int value) {
this.numsubac = value;
}
}
}
}
}
|
Python | UTF-8 | 2,663 | 2.6875 | 3 | [
"Apache-2.0"
] | permissive | from tornado import web, websocket, httpserver, ioloop
import os, datetime, json
import redis
class Log(object):
def __init__(self, text):
super(Log, self).__init__()
utc_datetime = datetime.datetime.utcnow()
self.timestamp = utc_datetime.strftime("%Y-%m-%d %H:%M:%S")
self.text = text
def json(self):
return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True)
class RedisLog(object):
callbacks = []
def __init__(self):
super(RedisLog, self).__init__()
redis_url = os.getenv('REDISTOGO_URL', 'redis://localhost:6379')
self.redis = redis.from_url(redis_url)
self.log_db = 'log'
def add(self, log):
self.redis.lpush(self.log_db, log.json())
self.notifyCallbacks(log.json())
def list(self):
# read data
data = self.redis.lrange(self.log_db, 0, 9)
# decode json strings
data = [json.loads(e) for e in data]
return data
def register(self, callback):
self.callbacks.append(callback)
def unregister(self, callback):
self.callbacks.remove(callback)
def notifyCallbacks(self, log):
for callback in self.callbacks:
callback(log)
class Application(web.Application):
def __init__(self):
handlers = [
(r'/', MainHandler),
(r'/logs', StatusHandler)
]
settings = dict(
template_path=os.path.join(os.path.dirname(__file__), 'templates'),
static_path=os.path.join(os.path.dirname(__file__), 'static'),
debug=True,
autoescape=None
)
self.db = RedisLog()
web.Application.__init__(self, handlers, **settings)
def to_do(self):
return 'done'
def update(self):
result = self.to_do()
self.db.add(Log(result))
class MainHandler(web.RequestHandler):
def get(self):
logs = self.application.db.list()
self.render("index.html", logs=logs)
class StatusHandler(websocket.WebSocketHandler):
def open(self):
self.application.db.register(self.callback)
def on_close(self):
self.application.db.unregister(self.callback)
def on_message(self, message):
pass
def callback(self, log):
self.write_message(log)
def main():
app = Application()
server = httpserver.HTTPServer(app)
server.listen(os.getenv("PORT", 5000))
server_loop = ioloop.IOLoop.instance()
# background update every 30 sec
task = ioloop.PeriodicCallback(app.update,30*1000)
task.start()
server_loop.start()
if __name__ == '__main__':
main() |
C++ | UTF-8 | 1,715 | 3.40625 | 3 | [] | no_license | /**
* @file Lab3.cpp
* @author your name (you@domain.com)
* @brief Area of Eclipse
* @version 0.1
* @date 2020-04-09
*
* @copyright Copyright (c) 2020
*
*/
#include <iomanip>
#include <iostream>
using namespace std;
bool isInside(long double x, long double y, double a, double b)
{
return (x * x) / (a * a) + (y * y) / (b * b) < 1;
}
long long calculateGrid(double a, double b, double precision)
{
long long numOfGrid = 0;
int x = 0;
for (x = (a / precision); x > 0; x--)
{
int start = 0, end = (b / precision);
while (start < end)
{
int mid = start + (end - start) / 2;
if (isInside(x * precision, mid * precision, a, b) &&
!isInside((x)*precision, (mid + 1) * precision, a, b))
{
numOfGrid += mid;
// cout << numOfGrid << endl;
break;
}
else if (isInside(x * precision, (mid + 1) * precision, a, b))
{
start = mid + 1;
}
else if (!isInside(x * precision, mid * precision, a, b))
{
end = mid;
}
}
}
return 4 * numOfGrid;
}
long double calculateArea(long long numOfGrid, double precision)
{
long double area = numOfGrid * precision * precision;
return area;
}
int main()
{
double precision = 0.0;
double a, b;
long double area;
cout << "Enter the precision:" << endl;
cin >> precision;
cout << "Enter the 'a' and 'b' of ellipse" << endl;
cin >> a >> b;
area = calculateArea(calculateGrid(a, b, precision), precision);
cout.precision(10);
cout << (long double)area << endl;
return 0;
} |
Ruby | UTF-8 | 674 | 3.921875 | 4 | [] | no_license | name = "Felicia Torres"
def test(name)
name_chars = name.chars
new_arr = []
all_letters = ('a'..'z').to_a
vowels, consonants = all_letters.partition { |a| vowels.include?(a) }
name_chars.each do |name_char|
lower_name_char = name_char.downcase
if consonants.include?(lower_name_char)
new_arr << name_char.next
elsif vowels.include?(lower_name_char)
new_arr << next_vowel(vowels, lower_name_char)
else
new_arr << lower_name_char
end
end
new_arr
end
def next_vowel(vowels, char)
index = vowels.index(char)
if index.next < vowels.size
next_index = index.next
else
next_index = 0
end
vowels.at(next_index)
end |
C++ | UTF-8 | 943 | 3.375 | 3 | [] | no_license | // Kadane's algorithm
#include <iostream>
using namespace std;
int start = 0, end_ = 0;
int maxSubarraySum(int a[], int n){
int max_eh = 0;
int max_sf = -10000001;
for(int i=0; i<n; i++)
{
max_eh = max_eh + a[i];
if(a[i] > max_eh)
{
max_eh = a[i];
if(a[i] >= 0)
{
start = i;
end_ = i;
}
}
if(max_eh > max_sf)
{
max_sf = max_eh;
end_ = i;
}
}
return max_sf;
}
int main()
{
int a[] = {-2,-3,4,-1,-2,1,5,-3};
// int a[] {-1,-2,-3,-4};
int size = sizeof(a)/sizeof(a[0]);
int sum = maxSubarraySum(a, size);
cout<<"Subarray: ";
for(int i=start; i<=end_; i++)
cout<<a[i]<<" ";
cout<<endl<<"Sum: "<<sum;
return 0;
}
|
PHP | UTF-8 | 1,969 | 2.828125 | 3 | [
"MIT"
] | permissive | <?php
namespace Chef\Project\Path;
use Chef\Project\ProjectPathProviderInterface;
use Chef\Utils\Github\RepositoryManager;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
/**
* Class GitHubRepositoryProjectPathProvider
*
* @package Chef\Project\Path
*/
class GitHubRepositoryProjectPathProvider implements ProjectPathProviderInterface
{
/** @var LoggerInterface */
private $logger;
/** @var string */
private $username;
/** @var string */
private $token;
/** @var string */
private $path;
/** @var string */
private $revision;
public function __construct(LoggerInterface $logger = null)
{
$this->logger = $logger ?: new NullLogger();
}
/**
* @param $token
* @param null $username
*/
public function setAuthentication($token, $username = null)
{
$this->username = $username ?: get_current_user();
$this->token = $token;
$this->revision = 'master';
}
/**
* @inheritdoc
*/
public function exists($name)
{
$path = $this->getProjectPath($name);
$this->logger->info(sprintf('%s: Project Path %s', __NAMESPACE__, $path));
// Fetch & Clone the repo
$git = new RepositoryManager($this->logger, $path, $name, $this->username, $this->token);
$git->checkout($this->revision);
return true;
}
/**
* @inheritdoc
*/
public function getProjectPath($name)
{
return sprintf('%s/%s', $this->path, str_replace('/', '-', $name));
}
/**
* @param $revision
*/
public function setRevision($revision)
{
$this->revision = $revision;
}
/**
* @inheritdoc
*/
public function setPath($path)
{
if (!is_writable($path)) {
throw new \RuntimeException(sprintf('Project Provider Path is not writeable, path: %s', $this->path));
}
$this->path = $path;
}
}
|
JavaScript | UTF-8 | 2,815 | 3 | 3 | [] | no_license | var app = new Vue({
el: '#app',
data: {
totalText1: "Joker Öncesi",
totalText2: "Jokerli Tutar",
beforeTotal: 0,
afterTotal: 0,
prices: [{
beforePrice: 0,
afterPrice: 0,
piece: 1
}
]
},
methods: {
addBtn: function () {//Adding new price data
newPrice = {
beforePrice: 0,
afterPrice: 0,
piece: 1
};
this.prices.push(newPrice);
},
calculateData: function () {//Calculating All Data
//Setting Beforetotal
this.beforeTotal = parseFloat(0);
this.prices.forEach(price => {
if (Number.isNaN(parseFloat(price.beforePrice)))
price.beforePrice = 0;
if (Number.isNaN(parseFloat(price.piece)))
price.piece = 1;
this.beforeTotal += (parseFloat(price.beforePrice) * parseFloat(price.piece));
});
//setting After Total
if (parseFloat(this.beforeTotal) < 30) {
this.afterTotal = this.beforeTotal;
}
else if (parseFloat(this.beforeTotal) >= 30 && parseFloat(this.beforeTotal) < 40) {
this.afterTotal = parseFloat(this.beforeTotal) - 10;
}
else if (parseFloat(this.beforeTotal) >= 40 && parseFloat(this.beforeTotal) < 70) {
this.afterTotal = parseFloat(this.beforeTotal) - 15;
}
else if (parseFloat(this.beforeTotal) >= 70 && parseFloat(this.beforeTotal) < 120) {
this.afterTotal = parseFloat(this.beforeTotal) - 25;
}
else if (parseFloat(this.beforeTotal) >= 120) {
this.afterTotal = parseFloat(this.beforeTotal) - 45;
}
else {
this.afterTotal = this.beforeTotal;
}
//setting Prices
this.prices.forEach(price => {
price.afterPrice = (parseFloat(price.beforePrice) / parseFloat(this.beforeTotal)) * parseFloat(this.afterTotal);
price.afterPrice = parseFloat(price.afterPrice) * 100;
price.afterPrice = Math.floor(parseFloat(price.afterPrice));
price.afterPrice = parseFloat(price.afterPrice) / 100;
if (Number.isNaN(parseFloat(price.afterPrice)))
price.afterPrice = 0;
});
},
removeElement: function (index) {
this.prices.splice(index, 1);
this.calculateData();
},
clearData: function () {
this.prices = [{ beforePrice: 0, afterPrice: 0, piece: 1 }]
this.beforeTotal = 0;
this.afterTotal = 0;
}
}
}); |
Markdown | UTF-8 | 780 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | # angular2-stackdriver-typescript
Angular 2-6 stackdriver reporting class written in TypeScript
Based on: https://github.com/GoogleCloudPlatform/stackdriver-errors-js
This class can be used with Angular Error handler to report errors to Google Stackdriver.
At first in ErrorHandler create instance of class
```javascript
constructor(injector: Injector) {
this.errorReportingInstance = new StackdriverErrorReporterSSR({
key: STACKDRIVER_API_KEY,
projectId: STACKDRIVER_PROJECT_ID,
service: STACKDRIVER_SERVICE,
}, injector.get(HttpClient));
}
```
then you can report errors with:
```javascript
this.errorReportingInstance.report()
```
Then go to https://console.cloud.google.com/errors to see errors.
|
Python | UTF-8 | 441 | 2.890625 | 3 | [] | no_license |
def we_have_house(hh, hw, hd, rh):
if hh + rh > 20:
return 'No permission.'
if hw < 15 or hd < 11:
return 'House too small.'
if hw > 44 or hd > 44:
return 'House too big.'
y = 2 * (hw * hh + .5 * hw * rh) + 2 * (hd * hh)
y -= 117 + 2 * hw + 2 * (hw-3) + 4 * hd
g = 2 * hw + 2 * (hw-3) + 4 * hd
myans = 'Yellow: ' + str(int(y)) + ', Gray: ' + str(int(g))
return myans
|
Python | UTF-8 | 12,748 | 2.859375 | 3 | [] | no_license | import re
import random
import operator
from nltk import pos_tag, word_tokenize
import random, re, sys, pronouncing
import keras
from keras.models import Sequential, model_from_json
from keras.layers import Activation,LSTM,Dense,Embedding
from keras.optimizers import Adam
from scipy.sparse import csr_matrix
import pickle, random
import re, json
import csv
import numpy as np
from nltk import word_tokenize
from keras.models import model_from_json
reload(sys)
sys.setdefaultencoding('utf8')
# freqDict is a dict of dict containing frequencies
def addToDict(fileName, freqDict):
f = open(fileName, 'r')
# words = re.sub("\n", " \n", f.read()).lower().split(' ')
words = re.sub("\n", " \n", f.read()).split(' ')
# text = f.read()
# words = text.split()
# count frequencies curr -> succ
for curr, succ in zip(words[1:], words[:-1]):
# check if curr is already in the dict of dicts
if curr not in freqDict:
freqDict[curr] = {succ: 1}
else:
# check if the dict associated with curr already has succ
if succ not in freqDict[curr]:
freqDict[curr][succ] = 1;
else:
freqDict[curr][succ] += 1;
# compute percentages
probDict = {}
for curr, currDict in freqDict.items():
probDict[curr] = {}
currTotal = sum(currDict.values())
for succ in currDict:
probDict[curr][succ] = currDict[succ] / currTotal
return probDict
z = 0
def markov_next(curr, probDict,posDict):
global z
# random.choice(pos_dict[word].keys())
# random.choice(list(probDict.keys()))
if curr not in probDict:
return random.choice(posDict.keys())
else:
succProbs = probDict[curr]
randProb = random.random()
currProb = 0.0
maxima=0.0
name=""
for succ in succProbs:
currProb += succProbs[succ]
# randProb <= currProb and
if succ in posDict.keys():
print ("yo",z)
z+=1
return succ
return random.choice(posDict.keys())
prior_probs_dict = {} #number of occurrences for each prior prior probability pair
total_pos = {} #total number of occurrences for each pos
pos_dict = {} #dict of dicts that contains each part of speech, the words that make up those parts of speech, and number of each occurrence for each word
word_dict = {} #dictionary of words and occurrences of each corresponding pos
subsequent_dict = {} #dictionary of probabilities. showcases the likelihood of a given pos following another pos
count = 0
pos_count = 0
pos_count_2 = 0
def main():
#use nltk to determine parts of speech for old songs, write to "oldsong.pos"
rapFreqDict = {}
#rapProbDict = addToDict('lyrics3.txt', rapFreqDict)
# rapProbDict = addToDict('oldsong.txt', rapFreqDict)
pos_lyrics("poemdata.txt")
input_file = open("oldsong.pos", "r")
text = input_file.read()
line = text.split()
rapProbDict = addToDict('poemdata.txt', rapFreqDict)
#calcuate prior probabilites in "oldsong.pos"
probabilities(line)
#add each word in lyrics to a list and return it
the_song = lyrics(rapProbDict)
print_lyrics(the_song) #you know what to do
def pos_lyrics(input_file):
f_read = open(input_file, "r")
f_write = open("oldsong.pos", "w")
text = f_read.read()
list_of_pos = pos_tag(word_tokenize(text))
for word in list_of_pos:
f_write.write(word[0].lower() + " " + word[1] + "\n")
f_read.close()
f_write.close()
def probabilities(line):
pos_count = 0
pos_count_2 = 0
hmm_count = 0
count = 0
#find prior probabilities and add to a dictionary
for word in range(int(len(line)/2-1)):
word = line[count + 1] + " "
following_word = line[count + 3] + " "
word_combo = word + "-> " + following_word
# check if word_combo exists in prior_probs_dict dictionary
if word_combo in prior_probs_dict:
#add to count
prior_probs_dict[word_combo] += 1
else:
#create key and add to count
prior_probs_dict[word_combo] = 1
count += 2
if len(line) == count:
count = 0
break
#find total number of occurrences for each pos
for word in range(int(len(line)/2-1)):
#total up each pos in total_pos dictionary
pos = line[pos_count +1] + " "
if pos in total_pos:
total_pos[pos] += 1
else:
total_pos[pos] = 1
pos_count += 2
for pos in total_pos:
subsequent_dict[pos] = {}
for word_combo in prior_probs_dict:
if word_combo.startswith(pos):
#probability is the number of word_combos/total occurrences of pos
occurrences_of_word_combo = prior_probs_dict[word_combo]
occurrences_of_pos = total_pos[pos]
probability = (occurrences_of_word_combo)/float(occurrences_of_pos)
subsequent_dict[pos][word_combo] = probability
#have a dictionary of dictionaries that contains each part of speech, the words that make up those parts of speech, and number of each occurrence for each word
for word in range(len(line)):
word = line[pos_count_2]
pos = line[pos_count_2 +1]
#check if pos exists in dictionary
#POS DICT-------------------------------
if pos in pos_dict:
#check to see if word is already in nested dict. if not, add
if word in pos_dict[pos]:
pos_dict[pos][word] += 1
else:
pos_dict[pos][word] = 1
else:
#add that pos to the dict, add add word to nested dict
pos_dict[pos] = {}
pos_dict[pos][word] = 1
#WORD DICT-------------------------------
if word in word_dict:
#check to see if word is already in nested dict. if not, add
if pos in word_dict[word]:
word_dict[word][pos] += 1
else:
word_dict[word][pos] = 1
else:
#add that pos to the dict, add add word to nested dict
word_dict[word] = {}
word_dict[word][pos] = 1
pos_count_2 += 2
if len(line) == pos_count_2:
pos_count_2 = 0
break
def loadGloveModel(gloveFile):
print("Loading Glove Model")
f = open(gloveFile,'r')
Glove_model = {}
Glove_words = []
for line in f:
splitLine = line.split()
word = splitLine[0]
Glove_words.insert(0,word)
embedding = np.array([float(val) for val in splitLine[1:]])
Glove_model[word] = embedding
print("Done.",len(Glove_model)," words loaded!")
return Glove_model, Glove_words
glove_model, glove_words = loadGloveModel("glove.6B.50d.txt")
json_file = open('model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)
# load weights into new model
loaded_model.load_weights("model.h5")
# print("Loaded model from disk")
# evaluate loaded model on test data
loaded_model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy','top_k_categorical_accuracy'])
def find_nearest(vec, prev_word, method='cosine'):
if method == 'cosine':
nearest_word = ""
max_val = -1
list_vec = []
rhymed_words = pronouncing.rhymes(prev_word)
for word in rhymed_words:
try:
val = np.dot(vec, glove_model[word])
list_vec.insert(0,[val, word])
if max_val < val:
max_val = val
nearest_word = word
except Exception as e:
pass
sorted_list_vec = sorted(list_vec, key=lambda x: x[0])
# if previous_word == sorted_list_vec[0][1]:
# return sorted_list_vec[1][0],sorted_list_vec[1][1]
# else:
# return sorted_list_vec[0][0],sorted_list_vec[0][1]
len_gen = len(rhymed_words)
for y in range(len(sorted_list_vec)):
flag = 0
for x in rhymed_words:
if x == sorted_list_vec[y][1]:
break
flag+=1
if flag == len_gen:
return sorted_list_vec[y][0],sorted_list_vec[y][1]
else:
raise Exception('{} is not an excepted method parameter'.format(method))
def lyrics(probDict):
lyrics = []
total_words = 0 #no more than 250 words/song
count = 0
#hardcode it so that first word is a noun, yolo
startWord = raw_input("What do you want to start your rap with?\n > ")
lyrics.append(startWord)
#print("Alright, here's your rap:")
# for word in pos_dict:
# if word == "NN":
# count += 1
# for words in pos_dict[word]:
# #randomly pick some common Drake noun
# #add_word = markov_next(rap[-1], probDict,pos_dict[word])
# add_word = random.choice(pos_dict[word].keys())
# lyrics.append(add_word)
# if (count ==1):
# count = 0
# break
next_newline = 7
line =1
while total_words != 500:
pick = []
#based on the first word, come up with the other words!
#determine POS for current word
current_word = lyrics[total_words]
if current_word == "\n":
current_word = lyrics[total_words-1]
pos_of_current_word = max(word_dict[current_word].iteritems(), key=operator.itemgetter(1))[0] + " "
#determine top two possible POS for subsequent word
pos_options = dict(sorted(subsequent_dict[pos_of_current_word].iteritems(), key=operator.itemgetter(1), reverse=True)[:2])
#pick one at random
full_pos = random.choice(pos_options.keys())
length_of_old_pos = len(pos_of_current_word) + 3
pos_of_next_word = split(full_pos, length_of_old_pos)
#generate a random word from the list of words for that given part of speech
for word in pos_dict:
if (word + " ") == pos_of_next_word:
for words in pos_dict[word]:
#randomly pick some common Drake word
#add_word = random.choice(pos_dict[word].keys())
# print (pos_dict[word].keys())
add_word = markov_next(current_word, probDict,pos_dict[word])
lyrics.append(add_word)
total_words += 1
count += 1
if count == next_newline:
lyrics.append("\n")
line += 1
next_newline += random.randint(6, 12)
if line % 2:
previous_word_odd = add_word
else:
previous_word_even = add_word
try:
if line>=3:
#########################################################################
maxlen = 3
x_sample=lyrics[len(lyrics)-3:len(lyrics)]
x=np.zeros((1,maxlen*50))
for ix in range(0):
# choose random index in features
try:
for iy in range(maxlen):
# print(iy)
x[0][iy*50:(iy+1)*50] = list(glove_model[x_sample[iy]])
except:
ix -= 1
probs=loaded_model.predict(x)
# print(i, probs)
# probs=np.reshape(probs,probs.shape[1])
if line % 2:
prob, word = find_nearest(probs, previous_word_odd)
else:
prob, word = find_nearest(probs, previous_word_even)
previous_word = word
lyrics.append(word)
count += 1
total_words += 1
except:
pass
if count == next_newline:
lyrics.append("\n")
line += 1
next_newline += random.randint(6, 12)
if line % 2:
previous_word_odd = word
else:
previous_word_even = word
#########################################################################
# total_words += 1
return lyrics
def print_lyrics(lyrics):
print(lyrics)
# def print_lyrics(lyrics):
# output = open("newsong1.txt", "w")
# count = 0
# #hardcode title to be first three words
# title = lyrics[:3]
# #hardcode chorus to be next 50 words
# chorus = lyrics[3:53]
# #hardcode verses to be remaining
# verses = lyrics[53:]
# output.write("TITLE:")
# for words in title:
# output.write(words + " ")
# output.write("\n\n")
# print_chorus(chorus, output)
# output.write("\n\n")
# for words in lyrics:
# output.write(words + " ")
# count += 1
# if count % 10 ==0:
# output.write("\n")
# elif count % 83 == 0:
# output.write("\n\n")
# print_chorus(chorus, output)
# output.write("\n\n")
# output.close()
# def print_chorus(words_in_chorus, output):
# count = 0
# output.write("CHORUS:")
# for words in words_in_chorus:
# output.write(words + " ")
# count += 1
# if count % 10 ==0:
# output.write("\n")
def split(s, n):
return s[n:]
if __name__ == "__main__":
main()
|
Markdown | UTF-8 | 279 | 2.546875 | 3 | [] | no_license | ## Scrapper for Linkedin
# Before running below commands, create config.py and add following details:
linkedin = dict(
username = your_linkedin_mail_id,
password = your_linkedin_password,
)
# Steps to Install and run:
1. pip install -r requirements.txt
2. python index.py
|
Markdown | UTF-8 | 20,531 | 3.953125 | 4 | [] | no_license | # 解谜计算机科学
教人们编程,该教什么。我一开始想以一个语言开始,教人们写出第一个程序,让程序打印出Hello World。然而当我看了王垠的文章《解谜计算机科学》之后,我改变了想法。这才是真正的编程第一课。此篇文章是我看了那篇文章后的复述。来,一起来理解计算机科学的基本概念。
## 手指算术
到底什么是计算。从手指算术开始讲起。小时候,当妈妈问,`2+5`等于什么的时候。我们紧握手指头,开始数数。拿出左手,伸出2根。接着拿出右手,伸出5根。接着,看有多少根手指头伸出来了。开始数数,1、2、3、4、5、6、7。嗯,有7根。所以答案是7。
这背后到底发生什么呢。计算机如何来实现这个过程呢。在这过程中,我们其实就是一台计算机。我们在做计算。`2+5`是输入。`7`是输出。我们用头脑和身体完成了计算。
计算机科学就是根植于这类非常简单的过程。
## 符号和模型
当问一个刚出生的幼儿,`2+5`等于多少的时候。他是不知道的。他完全不知道这什么意思。在这之前,是教小孩子认数字。我们说2根指头就是2,5根指头就是5。2只猫是2,5只猫是5。这意味着什么。我们在教会孩子数字这个概念。当学习另外一种语言的时候,就体会很深刻了。`あ`是什么?你知道吗。还没学习日语的时候,就不知道。这个字有点像`女`字,是`女`字的弯曲版本。
所以我们会用以往的概念来理解。后来才知道`あ`相当于拼音的音标`a`。所以`2`同样是一个符号,是一条曲线。这个概念叫符号(symbol)。我们把它转化成了大脑里的一个模型(model)。
符号和模型,是编译器里的概念。编译器又是什么。后面说。总之,要区分这是两个不一样的东西。符号是图形化的。模型是富含意义的。一个模型可以用不同的符号来表达。就好像钱,有人民币符号`¥`,有美元符号`$`。钱就是模型,币种的图形表达就是符号。
所以,在回答`2+5`等于多少的时候。需要先会表达1到10。伸出一根手指就是1。伸出10根手指就是10。这就是为什么人类通常用10进制来表达算数。
这里还有一点是,手指是非常灵活的。这相当于一个机械装置。当伸出3根指头时,再多伸出1根,就是4根。弯曲伸缩一下,就更改了一种状态。
## 计算图
在计算机领域,通常用一些抽象的图示来表达计算的过程。这样可以直观地看到信息的流动。这样的图示看起来像是箭头和一些形状连接起来的。我们把它叫做`计算图`。
上面的计算可以表达为:
<img src="./img/add.png" alt="add" style="zoom:40%;" />
这样的图示可以表达一类的计算。清晰地表达了输入和输出的方向。当我们给这个圆圈两个输入,就会得到一个结果。这里其实把`加法`抽象化了。这个圆圈不妨把它叫做加法器。在手指算术中,这个加法器就是我们自己。还可以用一堆石头,算盘,电子线路来做成这个加法器。具体的方式很多时候我们是不关心的。总之它能做加法就行。所以,这里把加法抽象化了。抽象(abstraction)是计算机科学重要的一种思维方式。我们把事物一层层抽象,从而可以做很复杂的事情。每一层抽象,都把复杂的事情化为更为简单的事情,直到计算机的电子电路可以很容易地表达它,根据需要而更改电子电路的状态。
## 表达式
计算机科学当然不止`2+5`这么简单。然而它确实是由像`2+5`这种简单的计算元素构成的。这种,叫做表达式。表达式是什么。我们先不去定义它。来看一个稍微复杂一点的表达式:
```c
3*(2+5)
```
这叫做复合表达式。它的计算图该如何表达。我们把3乘上`2+5`的结果。多了一个运算。所以应该画一个乘法器。一边是3,一边是`2+5`。如下:
<img src="./img/expression.png" alt="expression" style="zoom:40%;" />
由此可以知道计算图的威力。想象一张拥有千百分支的计算图。计算机就是这么工作的。
由此可以知道什么。`3*2+5`的计算图又是如何的。它肯定和`3*(2+5)`不一样。计算顺序是重要的。在`3*(2+5)`中,怎么知道先算2+5。因为有括号。而括号只是一种符号。一种数学上的表示。想象来到另外一个星球,这里人们用`{}`来表达优先级,即是`3*{2+5}`。所以,这里也体现了`符号`和`模型`的差别。符号只是模型的一种表达。符号不是本质的东西。模型才是本质的。
`3*(2+5)`是这个计算图的一种表达,或者叫编码(coding)。这个计算图该怎么计算呢。一起来由结果处推算起。当计算乘法的时候,一边`3`是已知的,而另外一边是加法器,是未知的。故得先计算`2+5`。由此得到结果是7。接着才能进行乘法计算。于是得到21。
所以,从符号得到模型,接着才能开始计算。这个过程,在计算机科学里,叫做`语法分析`(parsing)。后面会详细讲讲。
来给表达式一个定义。这个定义是不完善的。然而尝试理解它,才更好深入这一切。
定义(表达式):表达式可以是如下几种东西。
1. 数字。如1、2、3、4……。
2. 表达式+表达式。两个表达式相加,也是一个表达式。
3. 表达式-表达式。两个表达式相减,也是一个表达式。
4. 表达式*表达式。两个表达式相乘,也是一个表达式。
5. 表达式/表达式。两个表达式相除,也是一个表达式。
为了能一直本质地理解这些,当在说上面的定义的时候,在脑子里也应该出现的是计算图。也就是说,`表达式+表达式`,更本质的存在是:
<img src="./img/expression_plus.png" alt="expression_plus1" style="zoom:50%;" />
是不是觉得这个表达式有点奇怪。一个表达式竟然是两个表达式相加。在表达式的定义中,用到了自己。这种叫做递归定义。所谓递归(recursion),就是一个东西的定义中用到了它本身自己。这是重要的一个思想。在于它能把事情变得很简洁清晰。同时它表达的东西又是强大的。
所以可以来验证一下,`3*(2+5)`是不是一个表达式。严格来说,它是的。证明如下:
* 3是数字,它是表达式。2和5也都是数字,都是表达式。它们都符合表达式的第1种定义。
* `(2+5)`是一个表达式,它是表达式+表达式,符合表达式的第2种定义。
* 接着`3*(2+5)`,它是表达式*表达式,符合表达式的第4种定义。
那什么不是上面定义的表达式。到目前为止,`a+b`不是定义的表达式。a字符是什么。不知道。所以由此,目前的定义,无法计算`a+b`这样的表达。
## 并行计算
考虑这样一个表达式:
```c
(2+3)*(1+5)
```
现实生活中会怎么计算呢。小孩子会怎么计算呢。
假如妈妈只有你一个小孩,大概你有两种方法:
* 先用手指算`2+3`,得到5。记下来。接着算`1+5`,得到6。接着乘起来,从纸牌盒里拿出纸牌,一次拿5张,拿6次,最后再数纸牌数。
* 先算`1+5`,得到6。再算`2+3`,得到5。接着数纸牌,一次拿6张,拿5次。
考虑这个先后顺序。为什么不能同时计算`2+3`和`1+5`。因为只有两只手。
假如你还有一个妹妹,那么你算`2+3`的时候,她算`1+5`。你俩同时算。然后再由一个人来做乘法。这便是并行计算(parallel computing)。
然而你和妹妹从妈妈那里听到这个题目的时候,你俩需要商量,谁算什么,怎么来配合,最后谁算乘法。这就是`通信开销`。尽管你妹妹和你算得同样快,但你妹妹说话比较慢的话,通信开销还挺大的。假如你妹妹和你计算能力不同的话,又该怎么分配工作。如今,计算机界的科学家们,在并行计算方面讨论的问题便是,如何根据计算单元的能力不同和通信开销的差异,提高计算效率,降低所需的时间。
## 变量和赋值
如果你有一个非常复杂的表达式,如:
```c
(8-3)*(3+5*(6*3-5))
```
由于它有很多层的嵌套,人眼很难一下子搞明白它在做什么,它的意义是什么。这时候,则希望用一些`名字`来表达中间结果,这样表达式更好理解。
举个例子,如你爸爸的妈妈的弟弟的女儿,该怎么称呼。你时常记不住。也不想去搞明白风俗是怎么叫的。然而,爸爸告诉你,她叫阿兰姐。你以后就记住了。
按刚刚的表达式来说,
```c
3*(2+5)
```
可以写成等价的、含有变量的代码:
```c
{
a=2+5 //定义变量a,并赋值
3*a //代码块的值
}
```
上面的`a`,在计算机科学上,这样的名字,叫做变量(variable)。这里用a,也可以用b、c、d……a1……z10等等,都可以。接着,`a=2+5`是一条赋值语句。
这里`//`是表示注释语句,是用来帮助人理解代码意思的。就好像Word软件的批注一样。这些注释语句不会影响代码的逻辑运行,就好像批注内容不会被打印一样。
`3*a`的结果将会被作为这个代码块的值。`{}`来表示代码块的边界符号。它们都只是一种表示方式。这种表示方式在不同的语言有不同的实现。比如有可能是BEGIN和END来表示边界。用花括号`{}`把语句括起来,是因为不想把这些语句和括号外的语句混淆。由`{`开始的,到`}`结束的,加上这两行代码,这一整个的,叫做代码块(block)。
通常总是以最后一条语句的结果作为代码块的值。这里`3*a`是最后一条语句。它的结果也就是这个代码块的结果。可能会有别的代码用到这个代码块的结果。
其次值得注意的是,变量是可以重复赋值的。如:
```c
{
a=2+5
b=a
a=3
c=a*4
}
```
这里,运行完毕后,a、b、c的值等于多少呢。a一开始是7,后来变成3。b是7,c则是12。注意到a后来的值变了。注意到a尽管后来变为3,b还是原来a的值。因为当a变更值时,b已经赋值完毕了。计算是有顺序的。
总是可以对同一变量赋值,但值得注意的是,只有当它们前后表示同一意义的时候,去赋值,才是比较好的做法。比如当用阿兰姐来称呼喜爱的一只猫的时候,那就可能出现混淆了。
## 编译
一旦引入变量,就不需要复合表达式了。可以把任意复杂的复合表达式,拆开为`单操作算术表达式`(像`2+5`这样)。
上面的例子:
```c
(8-3)*(3+5*(6*3-5))
```
可以表达为:
```c
{
a=8-3
b=6*3
c=b-5
d=5*c
e=3+d
f=a*e
}
```
这时一步步去计算每一个简单的表达式,便可以得到上面复杂表达式的结果。这其实就是编译(compile)。我们手工做了编译。我们自己做了编译器(compiler)。根据运算的优先级,把一个复杂的表达式写成了等价的简单表达式。
实际上这代码已经非常接近现代处理器(CPU)的汇编码(assembly)了。只需要多加一些转换,就能变成机器指令。
编译当然是涉及更多复杂的细节,但本质上就像上面的一样。计算机编译过程中,包含了更多符号到模型的转化,各种表达式优先级的排序,还有更多丰富的基础表达式。
我们一开始就理解了编译器是什么,后续只需加深这种理解。
## 函数
到目前为止,已知的计算都是发生在数字之间的。然而现实生活中,有些计算却依赖于一些未知数。
比如设想一种风扇控制器。它的转速总是当前温度的两倍。这个当前的温度便是一个未知数。它是一个输入(input)。这个风扇控制器必须要有一个输入。这个输入是温度感应器的度数。然后它也要有一个输出。这个输出用来当做转速。
这个风扇控制器可以写成:
```c
t -> t *2
```
t来表示输入。t * 2则是表达输出。这种表达,不附加在任何具体的编程语言上。这只是我们自己的定义。
用计算图来表达会是怎样。
<img src="./img/fan1.png" style="zoom:50%;" />
t 可以理解为电线。可见这样表达便是很清晰。信息的流动一目了然。当在说`风扇控制器`时,其实是不关心`温度传感器`和`风扇`的。也就是说,风扇控制器可以表达为:
<img src="./img/fan2.png" style="zoom:50%;" />
可见,这图其实很像`t->t*2`。这幅图就是函数所代表的计算图。t来表达它的一个未知数输入。
所以像 `t->t*2`这样含有未知数的构造,我们称之为函数(function)。其中,`t`这个符号,叫做函数的参数。所以这个参数,也可以叫别的,a、b、c等等。
## 参数、变量和电线
接下来,借助计算图来理解参数、变量这些概念。上面的例子:
```c
{
a=2+5
3*a
}
```
表达为计算图,会是怎么样。`t`来表达参数。变量可不可以也是参数呢。a可不可以画到t的位置上。
<img src="./img/variable_a.png" alt="variable_a" style="zoom:50%;" />
如上图所示。为了更像原先的表达式,这里把位置进行了调整。不再是从左到右,而是从右到左。所以可见这个代码块之所以和`3*(2+5)`结果一样,是因为计算图并没有改变什么。只是在某一分支上,用一个字符来表示这个连接。
`a`这里也可以想象是刚刚的电线。所以变量、参数,它们俩在计算图上都是同一个东西。接着改掉`a`的名字,改成`b`,计算图是怎样。
<img src="./img/variable_b.png" alt="variable_b" style="zoom:50%;" />
可见这并不会改变计算图的结构。
说明上面的代码块和下面的代码块是等价的:
```c
{
b=2+5
3*b
}
```
同样当面对函数,`t->t*2`、`x->x*2`和 `f->f*2`都是一个东西。
这样看,是否说名字不重要。名字也挺重要的,只是在代码块不要重复就行,否则容易引起混淆。
## 有名字的函数
既然变量可以代表值,那是否可以变量也可以代表函数。意思是让一个变量变成函数。这个变量表示一个函数。既然可以:
```c
b=2+5
```
那么是否可以:
```c
f=t->t*2
```
我们用变量f来保存这个函数。稍微调整一下,可以写得像数学上的那样:
```c
f(t)=t*2
```
然而当这样写时,却不可以写成:
```c
f=t*2
```
函数必须要有一个明确的输入来表示未知数。否则就会混淆。比如说。
代码块A:
```c
t=3
f(t)=t*2
```
代码块B:
```c
t=3
f=t*2
```
这两个代码块不是一个东西。代码块A里的f是一个函数,代码块B里的f则是一个变量。`f(t)=t*2`表示了一种函数规则。`f=t*2`则表达一种赋值。
用计算图来表示是怎样。
`f(t)=t*2`:
<img src="img/ft.png" alt="ft" style="zoom:50%;" />
`f=t*2`:
<img src="./img/ft2.png" alt="ft2" style="zoom:50%;" />
所以需要明确指出t是一个`输入`,才能知道它是一个函数的参数,而不是函数之外的变量。
然而这个道理,有些数学家却不明白,他们写书,经常这么写:
```c
有一个函数y=x*2
```
这是不对的。这里没有明确指出x是函数y的参数。
## 函数调用
我们给函数起了名字。那如何使用一个函数。那得告诉函数,它的未知数参数是什么,得告诉风扇控制器当前温度是多少。比如这样:
```c
f(2)
```
那就会得到4。
当没有调用函数时,它会做什么。它什么也不会做。它不知道输入是什么。当看到这个定义之后,机器该做什么。机器什么也不会做,它只是记录下了这个函数。
## 分支
到目前为止,我们的代码都是闷声不吭的,不问任何问题的埋头执行。我们缺少`问问题`的一种方法。比如我们想表达`运动选择器`这种东西。如果没下雨,则返回`play basketball`表示出去打球。下雨的话,则返回`jump rope`表示在家跳绳。
<img src="./img/branch.png" alt="branch" style="zoom:50%;" />
这里用`t`来表示是否下雨,0表示不下雨,1表示下雨。`t==1`表示来判断是否下雨。中间的判断结构叫做分支(branching),通常用菱形表示。
可以想象它就像一块大石头一样。代码流碰到它就分成了两叉。当满足条件时,就执行一边的语句。当不满足条件时,则执行另外一边的语句。
这是图形化的表示。为了书写方便。我们该怎么表达呢。
```c
t -> if (t==1)
{
"play basketball"
}
else
{
"jump rope"
}
```
注意到上面的`else`其实是不必要的。然而可能会把两个语句块混淆,所以这里多用一个词,来隔开两个语句块。
# 字符串
注意到上一节,我们使用了之前没有见过的元素,用双引号引起来的。这叫字符串(string)。这是一种跟数字同等重要的一种基本数据类型。
字符串对于应用程序很重要,然而它却不是计算机科学里最本质的东西。很多编程书在前面花了很多篇幅讲字符串的内容。初学者在练习打印字符串的东西,几个星期后都还没学到函数,这是非常可惜的。
## 布尔值
上面的`t==1`其实叫布尔表达式。可以把`==`看作是跟加法差不多的东西。类似的布尔运算符还有`<`、`>`,这样的表达式如`t<12`,`t>12`。
布尔值有两个,true 和 false,也就是`真`和`假`。
我们为什么需要布尔值这种东西。它的存在可以简化我们的思维。
## 计算的要素
好了,到这里,我们已经掌握了计算机科学的几乎所有基本要素。每一种编程语言都包括这些构造:
1. 基础的数值。比如整数、字符串、布尔值等。
2. 表达式。包括基本的算术表达式,嵌套的表达式。
3. 变量和赋值语句。
4. 分支语句。
5. 函数和函数调用。
这些基础要素就像语言里的音标、文字、单词、句子和语法一样。也就像开车的方向盘、油门、刹车和挂挡一样。当任何一部车,掌握了这些基础要素之外,理论就可以开车上路了。虽然车还有更多的功能细节,路上有很多的交通规则。我们需要很多的练习,来了解这些细节,熟练这些规则。
## 什么是计算
什么是计算,似乎是很哲学的问题。用手指算术是计算,用算盘是计算,用草稿纸演算是计算,用机械装置是计算。而如这一篇文章所言,表达式、分支、函数也都是表达了一种计算。
如果真要定义,那从广义的来说,计算就是`机械化地信息处理`。所谓机械化,可以用手算,计算机算,算盘算。可以有代码,也可以没有代码。甚至可以是生物活动或化学反应。
为什么你可以相信计算机科学的精华就是这些。因为计算就是处理信息,信息有它的诞生位置(输入设备,固定数值),它传输的方式(赋值,函数调用,返回值),它被查看的地方(分支)。你想象不到对于信息还有别的什么操作,所以你就可以很安心地相信,这就是计算机科学这种`棋类游戏`的全部规则了。
## 练习
* 阅读完此文后,可以将[王垠的文章](http://www.yinwang.org/blog-cn/2018/04/13/computer-science)过一遍。原文更详细一些。
* 构想一些算术表达式和场景,用Keynote、PowerPoint或流程图工具,画出相应的计算图。如本文上面的例子。本文有10张计算图。学生需要换个算术表达式和场景,来把计算图都画一遍。
* 完成练习后,可提交一篇图文形式的文档。有10个小节。每个小节一段文字描述算术表达式或场景,一张图片表达相应的计算图。
|
Python | UTF-8 | 719 | 2.671875 | 3 | [] | no_license | import subprocess
import sys
# needs ffmpeg and ffprobe on path of the machine
class SoundCloudDownloader(object):
def download(self, url, path, debug=False):
# --exec \'move {} ' + path + '\' '
c = subprocess.Popen(
r'youtube-dl.exe --restrict-filenames -x --audio-quality 320K --audio-format mp3 --exec "move {} ' + path + r'\{}" --output %(uploader)s-%(title)s.%(ext)s ' + url,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = c.communicate()
if debug:
print(err)
return out
if __name__ == '__main__':
downloader = SoundCloudDownloader()
downloader.download(sys.argv[1], '.', debug=True)
|
C | UTF-8 | 283 | 3.59375 | 4 | [] | no_license | #include<stdio.h>
#include<math.h>
int check(long num)
{
for(long i=2;i<=sqrt(num);i++)
{
if(num%i == 0)
return 0;
}
return 1;
}
int main()
{
long sum=0;
for(long i=2;i<=2000000;i++)
{
if(check(i))
{
sum+=i;
}
}
printf("%ld\n", sum);
}
|
C# | UTF-8 | 139 | 2.8125 | 3 | [] | no_license | using System;
public class Cockroach
{
public static int CockroachSpeed(double x)
{
return (int)(x * 1000 / 36);
}
} |
C++ | UTF-8 | 30,416 | 3.203125 | 3 | [] | no_license | #include "matrix.h"
using namespace std;
int matrix::permutation_count = 0;
int gcd(int num1, int num2)
{
if(num1 <= 0 && num2 <= 0)
throw "error occurs in 'gcd(int num1, int num2)'.\nnum1 and num2 must be positive.";
int tmp;
while (num2 != 0)
{
tmp = num1 % num2;
num1 = num2;
num2 = tmp;
}
return num1;
}
int lcm(int num1, int num2)
{
if(num1 <= 0 && num2 <= 0) {
throw "error occurs in 'lcm(int num1, int num2).\nnum1 and num2 must be positive.";
}
return num1 * num2 / gcd(num1, num2);
}
term::
term() : base(1), root(1), coefficient(0) { }
term::
term(int _coefficient) : term() {
coefficient = _coefficient;
}
term::
term(int _root, int _base) : term(1) {
if(_root <= 0) {
throw "error occurs in 'term::term(int _base, int _root)'.\nterm::root must be positive.";
}
if(_base == 0) {
coefficient = 0;
base = 1;
root = 1;
}
else {
base = _base;
root = _root;
}
}
term::
term(int _coefficient, int _root, int _base) : term(_root, _base) {
coefficient = _coefficient;
}
term::
term(const term& _term) : term(_term.coefficient, _term.root, _term.base) { }
void term::
simplify() {
if(root <= 0)
throw "error occurs in 'term::simplify()'.\nterm::root must be positive.";
map<int, int> factors;
if(base == 0) {
root = 1;
base = 1;
coefficient = 0;
}
int tmp = base;
for(int i = 2; i <= tmp; i++) {
if(tmp % i == 0) {
factors.insert(make_pair(i, 1));
tmp /= i;
}
while(tmp % i == 0) {
tmp /= i;
factors[i]++;
}
}
for(map<int, int>::iterator it = factors.begin(); it != factors.end(); it++) {
while(it -> second >= root) {
coefficient *= (it -> first);
base /= int(pow(double(it -> first), double(root)));
it -> second -= root;
}
}
if(base == 1)
root = 1;
else {
int gcd_ = root;
for(map<int, int>::iterator it = factors.begin(); it != factors.end(); it++) {
if(it -> second != 0)
gcd_ = gcd(gcd_, it -> second);
}
root /= gcd_;
base = int(pow(double(base), double(1)/double(gcd_)));
}
}
void term::
test_show() {
cout << "coefficient : " << coefficient << endl;
cout << "root : " << root << endl;
cout << "base : " << base << endl;
cout << endl;
}
term operator+(const term& termR) {
return termR;
}
term operator-(const term& termR) {
term result(termR);
result.coefficient *= -1;
return result;
}
term operator*(const int& numL, const term& termR) {
term result(termR);
result.coefficient = termR.coefficient * numL;
result.simplify();
return result;
}
term operator*(const term& termL, const int& numR) {
term result;
result = numR * termL;
result.simplify();
return result;
}
term operator*(const term& termL, const term& termR) {
term result;
result.coefficient = termL.coefficient * termR.coefficient;
result.root = lcm(termL.root, termR.root);
result.base = int(
pow(double(termL.base), double(result.root/termL.root)) *
pow(double(termL.base), double(result.root/termR.root)));
result.simplify();
return result;
}
terms::
terms() : num_of_terms(0) {
this -> push_back(0);
}
terms::
terms(const term& _term) : terms() {
this -> push_back(_term);
}
terms::
terms(const terms& _terms) : terms() {
for(int i = 0; i < _terms.num_of_terms; i++)
this -> push_back(_terms.arr[i]);
}
void terms::
push_back(const term& _term) {
arr.push_back(_term);
num_of_terms++;
}
void terms::
push_back(const int& num) {
term input(num);
this -> push_back(input);
}
void terms::
test_show() {
for(int i = 0; i < num_of_terms; i++)
arr[i].test_show();
}
void terms::
sort() {
bool change = true;
term tmp;
while(change) {
change = false;
for(int i = 0; i < num_of_terms - 1; i++) {
if(arr[i].root > arr[i+1].root) {
tmp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = tmp;
change = true;
}
}
}
change = true;
while(change) {
change = false;
for(int i = 0; i < num_of_terms - 1; i++) {
if(arr[i].root == arr[i+1].root) {
if(arr[i].base > arr[i+1].base) {
tmp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = tmp;
change = true;
}
}
}
}
}
void terms::
simplify() {
for(int i = 0; i < num_of_terms; i++) {
arr[i].simplify();
}
sort();
for(int i = 0; i < num_of_terms - 1; i++) {
if(arr[i].root == 1) {
while(arr[i+1].root == 1) {
arr[i].coefficient = arr[i].coefficient +
arr[i+1].coefficient;
vector<term>::iterator it = arr.begin();
arr.erase(it + i + 1);
--num_of_terms;
if(it + i + 1 == arr.end())
break;
}
}
else {
while(arr[i].root == arr[i+1].root &&
arr[i].base == arr[i+1].base) {
arr[i].coefficient = arr[i].coefficient +
arr[i+1].coefficient;
vector<term>:: iterator it = arr.begin();
arr.erase(it + i + 1);
--num_of_terms;
if(it + i + 1 == arr.end())
break;
}
}
}
}
terms operator+(const terms& _terms) {
return _terms;
}
terms operator-(const terms& _terms) {
terms result(_terms);
for(int i = 0; i < _terms.arr.size(); i++)
result.arr[i] = -1 * result.arr[i];
return result;
}
terms operator+(const term& termL, const term& termR) {
terms result;
result.arr.push_back(termL);
result.arr.push_back(termR);
result.simplify();
return result;
}
terms operator+(const int& numL, const term& termR) {
term tmp(numL);
terms result;
result = tmp + termR;
result.simplify();
return result;
}
terms operator+(const term& termL, const int& numR) {
terms result;
result = numR + termL;
result.simplify();
return result;
}
terms operator+(const terms& termsL, const int& numR){
terms temp(termsL);
temp.push_back(numR);
temp.simplify();
return temp;
}
terms operator+(const int& numL, const terms& termsR){
terms temp(termsR);
temp.push_back(numL);
temp.simplify();
return temp;
}
terms operator+(const terms& termsL, const term& termR){
terms temp(termsL);
temp.push_back(termR);
temp.simplify();
return temp;
}
terms operator+(const term& termL, const terms& termsR){
terms temp(termsR);
temp.push_back(termL);
temp.simplify();
return temp;
}
terms operator+(const terms& termsL, const terms& termsR){
terms temp(termsL);
for(int i = 0 ; i < termsR.num_of_terms ; ++i)
temp.push_back(termsR.arr[i]);
temp.simplify();
return temp;
}
terms operator-(const term& termL, const term& termR) {
terms temp;
temp = termL + -termR;
temp.simplify();
return temp;
}
terms operator-(const int& numL, const term& termR) {
terms temp;
temp = numL + -termR;
temp.simplify();
return temp;
}
terms operator-(const terms& termsL, const int& numR){
terms temp;
temp = termsL + -numR;
temp.simplify();
return temp;
}
terms operator-(const int& numL, const terms& termsR){
terms temp;
temp = numL + -termsR;
temp.simplify();
return temp;
}
terms operator-(const terms& termsL, const term& termR){
terms temp;
temp = termsL + -termR;
temp.simplify();
return temp;
}
terms operator-(const term& termL, const terms& termsR){
terms temp;
temp = termL + -termsR;
temp.simplify();
return temp;
}
terms operator-(const terms& termsL, const terms& termsR){
terms temp(termsL);
for(int i = 0 ; i < termsR.num_of_terms ; ++i)
temp.push_back(-termsR.arr[i]);
temp.simplify();
return temp;
}
terms operator*(const term& termL, const terms& termsR){
terms temp(termsR);
for(int i = 0 ; i < temp.num_of_terms ; ++i) temp.arr[i] = temp.arr[i] * termL;
temp.simplify();
return temp;
}
terms operator*(const terms& termsL, const term& termR){
terms temp(termsL);
for(int i = 0 ; i < temp.num_of_terms ; ++i) temp.arr[i] = temp.arr[i] * termR;
temp.simplify();
return temp;
}
terms operator*(const terms& termsL, const terms& termsR){
terms temp;
for(int i = 0 ; i < termsL.num_of_terms ; ++i){
for(int j = 0 ; j < termsR.num_of_terms ; ++j){
term temp_term = termsL.arr[i] * termsR.arr[j];
temp.push_back(temp_term);
}
}
temp.simplify();
return temp;
}
terms operator*(const int& numL, const terms& termsR) {
terms result(termsR);
for(int i = 0; i < termsR.arr.size(); i++)
result.arr[i] = numL * result.arr[i];
result.simplify();
return result;
}
terms operator*(const terms& termsL, const int& numR) {
terms result;
result = numR * termsL;
result.simplify();
return result;
}
fraction::
fraction() : fract(make_pair(1,1)), length(1) { }
fraction::
fraction(pair<int, int> p) {
fract = p;
setLength();
}
fraction::
fraction(int num) {
fract = make_pair(num, 1);
setLength();
}
fraction::
fraction(int num1, int num2) {
fract = make_pair(num1, num2);
setLength();
}
fraction::
fraction(const fraction& rhs){
fract = rhs.fract; length = rhs.length;
}
//simplification of fraction
void fraction::
simplify(){
int count = 0;
int l = fract.first > 0 ? fract.first : -fract.first,
r = fract.second > 0 ? fract.second : -fract.second;
int m = l > r ? l : r;
if((fract.first < 0 && fract.first*fract.second > 0) || fract.second==-1){
fract.first = -fract.first;
fract.second = -fract.second;
}
if( fract.second < 0 && fract.first > 0){
fract.first = -fract.first;
fract.second =-fract.second;
}
for(int i = m ; i > 1 ; --i)
if( fract.first%i == 0 && fract.second%i == 0){
count++;
fract.first /= i;
fract.second /= i;
}
setLength();
}
int fraction::
getLength() {
return length;
}
bool fraction::
is_zero() {
return fract.first == 0;
}
bool operator==(const int& numL, const fraction& fracR) {
if(fracR.fract.second == 0)
return false;
if((fracR.fract.first)%(fracR.fract.second) == 0)
if(fracR.fract.first/fracR.fract.second == numL)
return true;
return false;
}
bool operator!=(const int& numL, const fraction& fracR) {
if(numL == fracR)
return false;
return true;
}
bool operator==(const fraction& fracL, const int& numR) {
return numR == fracL;
}
bool operator!=(const fraction& fracL, const int& numR) {
return numR != fracL;
}
bool operator==(const double& numL, const fraction& fracR) {
if(fracR.fract.second == 0)
return false;
if((double)fracR.fract.first/(double)fracR.fract.second == numL)
return true;
return false;
}
bool operator!=(const double& numL, const fraction& fracR) {
if(numL == fracR)
return false;
return true;
}
bool operator==(const fraction& fracL, const double& numR) {
return numR == fracL;
}
bool operator==(const float& numL, const fraction& fracR) {
if(fracR.fract.second == 0)
return false;
if((float)fracR.fract.first/(float)fracR.fract.second == numL)
return true;
return false;
}
bool operator!=(const float& numL, const fraction& fracR) {
if(numL == fracR)
return false;
return true;
}
bool operator==(const fraction& fracL, const float& numR) {
return numR == fracL;
}
bool operator!=(const fraction& fracL, const float& numR) {
return numR != fracL;
}
bool operator==(const pair<int, int>& pairL, const fraction& fracR) {
fraction temp(pairL.first, pairL.second);
return temp == fracR;
}
bool operator!=(const pair<int, int>& pairL, const fraction& fracR) {
if(pairL == fracR)
return false;
return true;
}
bool operator==(const fraction& fracL, const pair<int, int>& pairR) {
return pairR == fracL;
}
bool operator!=(const fraction& fracL, const pair<int, int>& pairR) {
return pairR != fracL;
}
bool operator==(const fraction& fracL, const fraction& fracR) {
fraction temp1(fracL);
fraction temp2(fracR);
temp1.simplify();
temp2.simplify();
if(temp1.fract.first == temp2.fract.first &&
temp1.fract.second == temp2.fract.second)
return true;
return false;
}
bool operator!=(const fraction& fracL, const fraction& fracR) {
if(fracL == fracR)
return false;
return true;
}
fraction operator+(const fraction& l, const fraction& r){
int num1 = l.fract.first * r.fract.second + l.fract.second*r.fract.first,
num2 = l.fract.second*r.fract.second;
fraction p( make_pair(num1,num2) );
p.simplify();
return p;
}
fraction operator-(const fraction& l, const fraction& r){
int num1 = l.fract.first * r.fract.second - l.fract.second*r.fract.first,
num2 = l.fract.second*r.fract.second;
fraction p( make_pair(num1,num2) );
p.simplify();
return p;
}
fraction operator*(const fraction& l, const fraction& r){
int num1 = l.fract.first * r.fract.first,
num2 = l.fract.second * r.fract.second;
fraction p( make_pair(num1,num2) );
p.simplify();
return p;
}
fraction operator/(const fraction& l, const fraction& r){
fraction reverse_r( make_pair(r.fract.second , r.fract.first));
fraction result = l * reverse_r;
return result;
}
fraction operator-(const fraction& rhs){
fraction result(-rhs.fract.first,rhs.fract.second);
return result;
}
ostream& operator<<(ostream& out, const fraction& rhs){
if(rhs.fract.second == 1) return out << rhs.fract.first << ' ';
else return out << rhs.fract.first << '/' << rhs.fract.second << ' ';
}
istream& operator>>(istream& in, fraction& rhs){
size_t idx;
int num1,num2;
string str;
cin >> str;
idx = str.find("/");
bool is_integer = (idx==-1);
if(!is_integer) str = str.substr(0,idx) + " " + str.substr(idx+1);
istringstream iss(str);
if(is_integer){
iss >> num1;
rhs.fract = make_pair(num1,1);
}
else{
iss >> num1 >> num2;
rhs.fract = make_pair(num1,num2);
}
rhs.simplify();
}
void blank(int num){
for(int i = 0 ; i < num ; ++i) cout << ' ';
}
//instead of make_pair
fraction make_entry(int num1, int num2){
fraction result(num1,num2);
return result;
}
//to make a better print of pair(such as 3/10).
void fraction::
setLength(){
int len;
int num1 = fract.first , num2 = fract.second;
bool neg = num1 < 0;
if(num2 == 1) len = 0;
else{
len = 1;
while(num2!=0){
len++;
num2 /= 10;
}
}
if(neg){
len++;
num1 = -num1;
}
if(num1 == 0) len++;
while(num1!=0){
len++;
num1 /= 10;
}
length = len;
}
matrix operator+ (const matrix& l, const matrix& r){
if( l.row != r.row || r.col != l.col ){
matrix temp(0,0);
return temp;
}
else{
matrix temp(l.row, r.col);
for(int i = 0 ; i < l.row ; ++i)
for(int j = 0 ; j < l.col ; ++j)
temp.arr[i][j] = l.arr[i][j] + r.arr[i][j];
return temp;
}
}
matrix operator- (const matrix& l, const matrix& r){
if( l.row != r.row || r.col != l.col ){
matrix temp(0,0);
return temp;
}
else{
matrix temp(l.row,l.col);
for(int i = 0 ; i < l.row ; ++i)
for(int j = 0 ; j < l.col ; ++j)
temp.arr[i][j] = l.arr[i][j] - r.arr[i][j];
return temp;
}
}
matrix operator* (const matrix& l, const matrix& r){
if(l.col != r.row){
matrix temp(0,0);
return temp;
}
else{
matrix temp(l.row, r.col);
for(int i = 0 ; i < l.row ; ++i){
for(int j = 0 ; j < r.col ; ++j){
fraction p(make_pair(0,1));
for(int k = 0 ; k < l.col ; ++k) {
fraction q = l.arr[i][k]*r.arr[k][j];
p = p + q;
}
temp.arr[i][j] = p;
}
}
return temp;
}
}
matrix operator* (const fraction& fracL, const matrix& matR) {
matrix result(matR.row, matR.col);
for(int i = 0; i < matR.row; i++)
for(int j = 0; j < matR.col; j++)
result.arr[i][j] = fracL * matR.arr[i][j];
return result;
}
matrix operator* (const matrix& matL, const fraction& fracR) {
return fracR * matL;
}
matrix operator* (const int& intL, const matrix& matR) {
return fraction(intL) * matR;
}
matrix operator* (const matrix& matL, const int& intR) {
return intR * matL;
}
bool operator== (const matrix& matL, const matrix& matR) {
if(matL.row != matR.row || matL.col != matR.col)
return false;
for(int i = 0; i < matL.row; i++)
for(int j = 0; j < matL.col; j++)
if(matL.arr[i][j] != matR.arr[i][j])
return false;
return true;
}
bool operator!= (const matrix& matL, const matrix& matR) {
if(matL == matR)
return false;
return true;
}
fraction dotproduct(const matrix& matL, const matrix& matR) {
if(matL.row != matR.row || matL.col != 1 || matR.col != 1)
throw "error occurs in 'dotproduct(const martix& matL, const matrix& matR)'.\nyou can dotproduct between two vectors whose row is equal to each row.";
matrix temp;
temp = matL.transpose();
return (temp * matR).arr[0][0];
}
matrix::
matrix() : row(0), col(0) { }
matrix::
matrix(int r, int c) : row(r), col(c) {
make_identity_matrix();
}
matrix::
matrix(const matrix& mat) {
row = mat.row;
col = mat.col;
arr = mat.arr;
}
matrix::
~matrix() {
// delete permutation_matrix_ptr;
// delete elimination_matrix_ptr;
}
int matrix::
get_row() {
return row;
}
int matrix::
get_col() {
return col;
}
vector < vector < fraction > > matrix::
get_arr() {
return arr;
}
int matrix::
get_permutation_count() {
return permutation_count;
}
void matrix::
increase_permutation_count(){
permutation_count++;
}
matrix& matrix::
operator=(const matrix& rhs){
row = rhs.row;
col = rhs.col;
arr = rhs.arr;
}
void matrix::
set_arr (int r, int c, fraction num) {
if(arr.size() != 0 && arr[0].size() != 0 && r < row && c < col && r >= 0 && c >= 0) arr[r][c] = num;
}
void matrix::
fill(){
for(int i = 0 ; i < row ; ++i)
for(int j = 0 ; j < col ; ++j)
cin >> arr[i][j];
}
void matrix::
initialize() {
fraction f(make_pair(0,1));
vector<fraction> temp;
for(int i = 0 ; i < col ; ++i) temp.push_back(f);
for(int i = 0 ; i < row ; ++i) arr.push_back(temp);
}
//square matrix일 때만 identity_matrix가 나오게 할까?
void matrix::
make_identity_matrix() {
initialize();
fraction f(make_pair(1,1));
for(int i = 0; i < min(row,col); i++)
arr[i][i] = f;
}
void matrix::
make_all_entry_zero() {
fraction zero_entry(make_pair(0,1));
for(int i = 0; i < row; i++)
for(int j = 0; j < col; j++)
arr[i][j] = zero_entry;
}
void matrix::
show(bool no_paranthesis){
if(row*col==0) cout << "[]" << endl;
else{
int colNum[row] = {0,};
vector<int> colMax;
for(int i = 0 ; i < col ; ++i){
for(int j = 0 ; j < row ; ++j)
colNum[j] = arr[j][i].getLength();
int max = -1;
for(int k = 0 ; k < row ; ++k) max = max > colNum[k] ? max : colNum[k];
colMax.push_back(max);
}
for(int i = 0 ; i < row ; ++i){
if(!no_paranthesis) cout << '[' << ' ';
else cout << ' ';
for(int j = 0 ; j < col ; ++j){
blank(colMax[j] - arr[i][j].getLength());
cout << arr[i][j];
}
if(!no_paranthesis) cout << ']' << endl;
else cout << endl;
}
}
}
void matrix::
matrix_simplification(){
for(int i = 0 ; i < row ; ++i)
for(int j = 0 ; j < col ; ++j)
arr[i][j].simplify();
}
matrix matrix::
change_two_rows(int row1, int row2) {
matrix result(this -> get_row(), this -> get_row());
result.make_all_entry_zero();
for(int i = 0; i < this -> get_row(); i++) {
if(i == row1)
result.set_arr(i, row2, make_entry(1,1));
else if(i == row2)
result.set_arr(i, row1, make_entry(1,1));
else
result.set_arr(i, i, make_entry(1,1));
}
this -> increase_permutation_count();
return result;
}
matrix matrix::
move_a_row_to_last_row(int row) {
matrix result(this -> get_row(), this -> get_row());
result.set_arr(this -> get_row() - 1, this -> get_row() - 1, make_pair(0,1));
result.set_arr(this -> get_row() - 1, row, make_entry(1,1));
for(int i = row; i < this -> get_row() - 1; i++) {
result.set_arr(i, i, make_entry(0,1));
result.set_arr(i, i+1, make_entry(1,1));
}
// cout << "permutation" << endl;
//result.show();
for(int i = row ; i < this -> get_row(); ++i) this -> increase_permutation_count();
return result;
}
matrix matrix::
remove_entry(int substitution_row, int row, int col) {
vector< vector<fraction> > arr = this -> get_arr();
fraction entry1 = arr[row][col], entry2 = -arr[substitution_row][col];
fraction multiflyer = entry1 / entry2;
multiflyer.simplify();
matrix result(this -> get_row(), this -> get_row());
result.make_all_entry_zero();
for(int i = 0 ; i < this -> get_row() ; ++i)
result.set_arr(i, i, make_entry(1,1));
result.set_arr(row, substitution_row, multiflyer);
return result;
}
matrix matrix::
eliminate() {
matrix mat = *this;
matrix temp;
bool has_zero_pivot;
int num_of_pivots = min(mat.get_row(), mat.get_col());
for(int i = 0; i < num_of_pivots; i++) {
// cout << "i : " << i << endl;
for(int j = i; j < mat.get_col(); j++) {
has_zero_pivot = false;
// cout << "j : " << j << endl;
for(int k = i; k < mat.get_row(); k++) {
// cout << "k : " << k << endl;
if(!mat.get_arr()[i][j].is_zero()) break;
temp = mat.move_a_row_to_last_row(i);
mat = temp * mat;
// mat.show();
if(k == mat.get_row() - 1) has_zero_pivot = true;
// cout << has_zero_pivot << "k end" << endl;
}
if(!has_zero_pivot) {
for(int k = i+1; k < mat.get_row();k++) {
// cout << "k2 : " << k << endl;
// mat.show();
temp = mat.remove_entry(i, k, j);
mat = temp * mat;
// mat.show();
// cout << "k2 end" << endl;
}
break;
}
// cout << "j end" << endl;
}
// cout << "i end" << endl;
}
return mat;
}
matrix matrix::
permutation_matrix() {
matrix mat = *this;
matrix permutation_matrix(row, row);
matrix temp;
bool has_zero_pivot;
int num_of_pivots = min(mat.get_row(), mat.get_col());
for(int i = 0; i < num_of_pivots; i++) {
for(int j = i; j < mat.get_col(); j++) {
has_zero_pivot = false;
for(int k = i; k < mat.get_row(); k++) {
if(!mat.get_arr()[i][j].is_zero()) break;
temp = mat.move_a_row_to_last_row(i);
permutation_matrix = temp * permutation_matrix;
mat = temp * mat;
if(k == mat.get_row() - 1) has_zero_pivot = true;
}
if(!has_zero_pivot) {
for(int k = i+1; k < mat.get_row();k++) {
temp = mat.remove_entry(i, k, j);
mat = temp * mat;
mat = mat.remove_entry(i,k,j) * mat;
}
break;
}
}
}
return permutation_matrix;
}
matrix matrix::
elimination_matrix() {
matrix mat = permutation_matrix() * *this;
matrix elimination_matrix(row, row);
matrix temp;
int num_of_pivots = min(col, row);
int num_of_zeropivots = 0;
for(int i = 0; i < num_of_pivots; i++) {
while(mat.arr[i][i+num_of_zeropivots].is_zero())
num_of_zeropivots++;
for(int j = i+1; j < row; j++) {
temp = mat.remove_entry(i, j, i+num_of_zeropivots);
mat = temp * mat;
elimination_matrix = temp * elimination_matrix;
}
}
elimination_matrix.matrix_simplification();
return elimination_matrix;
}
//P와 D가 identity일 때 안 출력되게 업글하기
bool matrix::
LDUfactorization() {
if(row != col) {
cout << "You can't do LDU factorization." << endl;
return false;
}
if(permutation_matrix() != matrix(row,row)) {
cout << "P" << endl;
permutation_matrix().show();
cout << endl;
}
cout << "A" << endl;
show();
cout << endl;
cout << "L" << endl;
elimination_matrix().inverse_matrix().show();
cout << endl;
matrix upper_triangle = eliminate();
matrix diagonal = matrix(row, row);
for(int i = 0; i < row; i++) {
diagonal.arr[i][i] = upper_triangle.arr[i][i];
for(int j = i; j < row; j++)
upper_triangle.set_arr(i, j, upper_triangle.arr[i][j] / upper_triangle.arr[i][i]);
}
if(diagonal != matrix(row, row)) {
cout << "D" << endl;
diagonal.show();
cout << endl;
}
cout << "U" << endl;
upper_triangle.show();
cout << endl;
return true;
}
matrix matrix::
inverse_matrix() {
matrix eliminated;
matrix result;
matrix remove_entry;
bool singular = false;
if(row != col)
return result;
else {
eliminated = this -> eliminate();
for(int i = 0; i < row; i++) {
if(eliminated.arr[i][i] == 0) {
singular = true;
return result;
}
}
}
matrix elimination_matrix = this -> elimination_matrix();
for(int i = row - 1; i >= 0; i--) {
for(int j = i - 1; j >= 0; j--) {
remove_entry = eliminated.remove_entry(i, j, i);
elimination_matrix = remove_entry * elimination_matrix;
eliminated = remove_entry * eliminated;
}
}
matrix inverse_of_diagonal(row, row);
for(int i = 0; i < row; i++) {
fraction one;
inverse_of_diagonal.set_arr(i, i, one / eliminated.arr[i][i]);
}
matrix permutation_matrix = this -> permutation_matrix();
result = elimination_matrix * permutation_matrix;
result = inverse_of_diagonal * result;
return result;
}
matrix matrix::
transpose() const {
matrix mat(col, row);
for(int i = 0; i < row; i++)
for(int j = 0; j < col; j++)
mat.arr[j][i] = arr[i][j];
return mat;
}
//matrix matrix::
//get_permutation_matrix() {
// eliminate();
// return *permutation_matrix_ptr;
//}
//matrix matrix::
//get_elimination_matrix() {
// eliminate();
// return *Felimination_matrix_ptr;
//}
fraction matrix::
get_determinant(){
return determinant;
}
void matrix::
find_determinant(){
if(row!=col)
cout << "not a square matrix" << endl;
else{
matrix temp = *this;
fraction result(1,1);
temp = temp.eliminate();
for(int i = 0 ; i < temp.get_row() ; ++i)
result = result * temp.get_arr()[i][i];
this -> determinant = result;
}
}
matrix matrix::
RREF(){
matrix temp = *this;
temp = this -> eliminate();
int pivot[temp.get_row()] = {0,};
for(int i = 0 ; i < temp.get_row() ; ++i)
for(int j = 0 ; j < temp.get_col() ; ++j)
if(!temp.get_arr()[i][j].is_zero()){
pivot[i] = j;
break;
}
for(int i = 0 ; i < temp.get_row() ; ++i){
if(i!=0&&pivot[i]==0) continue;
for(int j = i ; j > 0 ; --j){
temp = temp.remove_entry(i,j-1,pivot[i]) * temp;
}
}
for(int i = 0 ; i < temp.get_row() ; ++i){
fraction div = temp.get_arr()[i][ pivot[i] ];
for(int j = pivot[i] ; j < temp.get_col() ; ++j){
if(div.is_zero()) break;
fraction temp_fraction = temp.get_arr()[i][j] / div;
temp.set_arr(i,j,temp_fraction);
}
}
//cout << endl << "RREF" << endl;
temp.matrix_simplification();
//temp.show();
return temp;
}
matrix matrix::
null_space(){
matrix temp = this -> RREF();
int pivot[temp.get_row()] = {0,};
int num_pivot = 0;
for(int i = 0 ; i < temp.get_row() ; ++i)
for(int j = 0 ; j < temp.get_col() ; ++j){
if(!temp.get_arr()[i][j].is_zero()){
pivot[i] = j;
break;
}
else
pivot[i] = -1;
}
for(int i = 0 ; i < temp.get_row() ; ++i)
if(pivot[i] != -1) num_pivot++;
int permutate_column[temp.get_col()] = {0,};
for(int i = 0 ; i < temp.get_col() ; ++i) permutate_column[i] = i;
for(int i = 0 ; i < num_pivot ; ++i){
if(i != pivot[i] && pivot[i] != -1){
permutate_column[i] = pivot[i];
permutate_column[ pivot[i] ] = i;
}
}
matrix permutation_column_matrix(temp.get_col(), temp.get_col());
permutation_column_matrix.initialize();
permutation_column_matrix.make_all_entry_zero();
for(int i = 0 ; i < temp.get_col() ; ++i){
permutation_column_matrix.set_arr(i,permutate_column[i], make_entry(1,1));
}
temp = temp * permutation_column_matrix;
matrix null_basis(temp.get_col() , temp.get_col() - num_pivot);
null_basis.make_all_entry_zero();
for(int i = 0 ; i < num_pivot ; ++i){
for(int j = 0 ; j < null_basis.get_col() ; ++j){
null_basis.set_arr(i,j, - temp.get_arr()[i][j + num_pivot]);
}
}
for(int i = num_pivot ; i < null_basis.get_row() ; ++i){
null_basis.set_arr(i,i - num_pivot ,make_entry(1,1));
}
null_basis = permutation_column_matrix * null_basis;
return null_basis;
}
matrix matrix::
column_space(){
matrix temp = *this;
temp = temp.transpose();
matrix permu = temp.permutation_matrix();
bool independent[temp.get_row()];
int num_independent = 0;
for(int i = 0 ; i < temp.get_row() ; ++i) independent[i] = false;
temp = permu * temp.eliminate();
for(int i = 0 ; i < temp.get_row() ; ++i){
for(int j = 0 ; j < temp.get_col() ; ++j)
if(!temp.get_arr()[i][j].is_zero() ){
independent[i] = true;
}
}
for(int i = 0 ; i < temp.get_row() ; ++i) if(independent[i]) num_independent++;
int idx = 0;
temp = this->transpose();
matrix column_space(num_independent, temp.get_col());
for(int i = 0 ; i < temp.get_row() ; ++i){
if(independent[i]){
for(int j = 0 ; j < temp.get_col() ; ++j)
column_space.set_arr(idx, j, temp.get_arr()[i][j]);
}
idx++;
}
column_space = column_space.transpose();
return column_space;
}
matrix matrix::
projection_matrix() const {
return *(this) * (transpose() * *(this)).inverse_matrix() * transpose();
}
matrix matrix::
project(const matrix& mat) {
if(col != 1 || row != mat.row)
throw "error occurs in 'matrix::project(const matrix& mat)'.\nyou can project correct vector.";
return mat.projection_matrix() * *(this);
}
matrix matrix::
augumented(matrix& b){
matrix temp(this->get_row(), this->get_col() + 1);
temp.make_all_entry_zero();
for(int i = 0 ; i < temp.get_row() ; ++i){
for(int j = 0 ; j < temp.get_col() ; ++j){
if(j >= this->get_col()) temp.set_arr(i,j, b.get_arr()[i][j - this->get_col()]);
else temp.set_arr(i,j, this->get_arr()[i][j]);
}
}
return temp;
}
matrix matrix::
all_solution(matrix b){
matrix temp = this->augumented(b);
matrix null_space = this->null_space();
temp = temp.RREF();
int pivot[temp.get_row()] = {0,};
int num_pivot = 0;
for(int i = 0 ; i < temp.get_row() ; ++i)
for(int j = 0 ; i < j < temp.get_col() ; ++j){
if(!temp.get_arr()[i][j].is_zero()){
pivot[i] = j;
break;
}
else
pivot[i] = -1;
}
for(int i = 0 ; i < temp.get_row() ; ++i){
if(pivot[i] == temp.get_col() -1){
cout << "no particular solution" << endl;
cout << "It's the closest solution" << endl;
matrix p = b.project(*this);
return this->all_solution(p);
}
else if(pivot[i] != -1) num_pivot++;
}
matrix particular(null_space.get_row(), 1);
particular.make_all_entry_zero();
for(int i = 0 ; i < num_pivot ; ++i)
particular.set_arr(pivot[i], 0, temp.get_arr()[i][temp.get_col() - 1]);
return particular;
}
matrix matrix::
gram_schmidt() {
matrix* col_arr = new matrix[col];
for(int i = 0; i < col; i++) {
col_arr[i] = matrix(row, 1);
for(int j = 0; j < row; j++) {
col_arr[i].arr[j][0] = arr[j][i];
}
}
for(int i = 0; i < col; i++) {
// col_arr[i].normalize();
if(i < col - 1) {
col_arr[i+1] = col_arr[i+1] - dotproduct(col_arr[i], col_arr[i+1])*(fraction()/dotproduct(col_arr[i],col_arr[i]))*col_arr[i];
}
}
matrix result(row, col);
for(int i = 0; i < row; i++)
for(int j = 0; j < col; j++)
result.arr[i][j] = col_arr[j].arr[i][0];
delete[] col_arr;
return result;
}
//root를 생각해야함!! -> fraction에 대대적인 변화가 필요
//void matrix::
//normalize() {
// if(col != 1)
// throw exception();
// for(int i = 0; i < row; i++)
//}
|
Python | UTF-8 | 1,165 | 2.78125 | 3 | [
"BSD-3-Clause"
] | permissive | import numpy as np
import csv
from PIL import Image
from matplotlib import cm
import seaborn as sns
import matplotlib.pylab as plt
if __name__ == "__main__":
filename = "dump.csv"
f = open(filename)
reader = csv.reader(f)
data=[r for r in reader]
arr = np.array(data, dtype=np.float)
new_arr = (arr - np.min(arr))/(np.max(arr) - np.min(arr))
# Lateral inversion along x-axis
new_arr = np.flip(new_arr, axis=0)
print(np.min(new_arr))
print(np.max(new_arr))
im = Image.fromarray(np.uint8(cm.gist_earth(new_arr)*255))
im.save("image.png")
sns.color_palette("rocket_r", as_cmap=True)
ax = sns.heatmap(new_arr, center=0.5, cmap="icefire_r")
#plt.show()
#plt.savefig("map.png")
#ax.plot()
#ax.savefig("pi.png")
f.close()
f = open("path.csv")
reader = csv.reader(f)
matrix = np.zeros((100,206))
for r in reader:
for rec in r:
print(rec)
x,y = rec.split(":")
x = int(x)
y = int(y)
matrix[x][y] = 1
matrix = np.flip(matrix, axis=0)
ax2 = sns.heatmap(matrix, cmap="Oranges")
f.close()
plt.show()
|
SQL | UTF-8 | 286 | 3.375 | 3 | [] | no_license | SELECT usuario.username, persona.nombre, billetera.billetera_id, cuenta.cuenta_id, cuenta.saldo
FROM usuario
JOIN persona ON usuario.persona_id = persona.persona_id
JOIN billetera ON persona.persona_id = billetera.persona_id
JOIN cuenta ON billetera.billetera_id = cuenta.billetera_id;
|
TypeScript | UTF-8 | 3,061 | 2.609375 | 3 | [] | no_license | import { BaseDB } from "./baseDB";
import { VideoGatweay } from "../business/gateways/videoGateway";
import { Video } from "../business/entities/video";
import { BadRequestError } from "../business/errors/badRequestError";
export class VideoDB extends BaseDB implements VideoGatweay{
private videoCollection = "videos"
private userCollection = "users"
public async insertNewVideo( video:Video, userToken:string ): Promise<void>{
try{
const verifiedToken = await this.dbFirebaseAdmin.auth().verifyIdToken( userToken )
const userId = verifiedToken.uid
await this.dbFirestore.collection( this.videoCollection ).doc().set( {
title: video.getTitle(),
description: video.getDescription(),
url: video.getUrl(),
userId
} )
}catch( err ){
throw new BadRequestError( err.message )
}
}
public async getVideosByUserId( userToken:string ): Promise<Video[]>{
try{
const verifiedToken = await this.dbFirebaseAdmin.auth().verifyIdToken( userToken )
const userId = verifiedToken.uid
const result = await this.dbFirestore.collection( this.videoCollection )
.where( "userId", "==", userId )
.get()
return result.docs.map( ( doc ) => {
let video = new Video(
doc.data().url,
doc.data().description,
doc.data().title,
doc.id
)
return video
} )
}catch( err ){
throw new BadRequestError( err.message )
}
}
public async updateVideoById( videoId:string, title:string, description:string ): Promise<void>{
try{
await this.dbFirestore.collection( this.videoCollection ).doc( videoId ).update( {
title,
description
} )
}catch( err ){
throw new BadRequestError( err.message )
}
}
public async deleteVideoById( videoId:string ): Promise<void>{
try{
await this.dbFirestore.collection( this.videoCollection ).doc( videoId ).delete()
}catch( err ){
throw new BadRequestError( err.message )
}
}
public async getVideoInfoById( videoId:string ): Promise<object>{
try{
const result = await this.dbFirestore.collection( this.videoCollection ).doc( videoId ).get()
const userId = result.data()?.userId
const user = await this.dbFirestore.collection( this.userCollection ).doc( userId ).get()
const videoInfo = {
title: result.data()?.title,
description: result.data()?.description,
url: result.data()?.url,
userName: user.data()?.name,
userPhoto: user.data()?.photo
}
return videoInfo
}catch( err ){
throw new BadRequestError( err.message )
}
}
public async getAllVideos(): Promise<Video[]>{
const result = await this.dbFirestore.collection( this.videoCollection ).get()
return result.docs.map( ( doc ) => {
let video = new Video(
doc.data().url,
doc.data().description,
doc.data().title,
doc.id
)
return video
} )
}
}
|
C++ | UTF-8 | 1,956 | 2.71875 | 3 | [] | no_license | #include <uC++.h>
#include "student.h"
#include "MPRNG.h"
#include "vendingMachine.h"
#include <iostream>
using namespace std;
extern MPRNG rng;
void Student::main() {
int purchases = rng(1, maxPurchases); // number of puchases the student will make
VendingMachine::Flavours fav =
static_cast<VendingMachine::Flavours>(rng(0, 3)); // Cast favourite flavour to enum
prt.print( Printer::Student, id, 'S', fav, purchases );
WATCard::FWATCard futureCard = cardOffice.create(id, 5); // Create watcard
VendingMachine* vend = nameServer.getMachine( id ); // Get vending machine
prt.print( Printer::Student, id, 'V', vend->getId() );
while ( purchases > 0 ) {
// Wait
yield(rng(1, 10));
while ( true ) {
try {
VendingMachine::Status status = vend->buy(fav, *futureCard()); // Attempt purchase
if ( status == VendingMachine::BUY ) {
// Successful purchase, one less to buy
--purchases;
prt.print( Printer::Student, id, 'B', futureCard()->getBalance() );
break;
} else if ( status == VendingMachine::FUNDS ) {
// Acquire more funds
futureCard = cardOffice.transfer(id, 5 + vend->cost(), futureCard);
} else if ( status == VendingMachine::STOCK ) {
// Get a new vending machine
vend = nameServer.getMachine( id );
prt.print( Printer::Student, id, 'V', vend->getId() );
yield(rng(1, 10));
} // if
} catch ( WATCardOffice::Lost ) {
// Get a new watcard because couriers lost current one
prt.print( Printer::Student, id, 'L' );
futureCard = cardOffice.create(id, 5);
} // try/catch
} // while
} // while
delete futureCard(); // cleanup futureCard
prt.print( Printer::Student, id, 'F' );
} // main
Student::Student( Printer &prt, NameServer &nameServer, WATCardOffice &cardOffice, unsigned int id,
unsigned int maxPurchases ) : prt(prt), nameServer(nameServer), cardOffice(cardOffice),
id(id), maxPurchases(maxPurchases) {} |
Markdown | UTF-8 | 12,034 | 2.578125 | 3 | [
"CC-BY-4.0",
"MIT"
] | permissive | ---
title: Aktivera disk kryptering för Linux-kluster
description: I den här artikeln beskrivs hur du aktiverar disk kryptering för Azure Service Fabric klusternoder i Linux med Azure Resource Manager och Azure Key Vault.
ms.topic: article
ms.date: 03/22/2019
ms.openlocfilehash: c600d822d20b0e5a0ca613935b1dfa4be838fcec
ms.sourcegitcommit: f28ebb95ae9aaaff3f87d8388a09b41e0b3445b5
ms.translationtype: MT
ms.contentlocale: sv-SE
ms.lasthandoff: 03/29/2021
ms.locfileid: "78252818"
---
# <a name="enable-disk-encryption-for-azure-service-fabric-cluster-nodes-in-linux"></a>Aktivera disk kryptering för Azure Service Fabric klusternoder i Linux
> [!div class="op_single_selector"]
> * [Disk kryptering för Linux](service-fabric-enable-azure-disk-encryption-linux.md)
> * [Disk kryptering för Windows](service-fabric-enable-azure-disk-encryption-windows.md)
>
>
I den här självstudien får du lära dig hur du aktiverar disk kryptering på Azure Service Fabric klusternoder i Linux. Du måste följa dessa steg för var och en av nodtypen och skalnings uppsättningar för virtuella datorer. För att kryptera noderna använder vi Azure Disk Encryption-funktionen på virtuella datorers skalnings uppsättningar.
Guiden omfattar följande ämnen:
* Viktiga begrepp som du bör känna till när du aktiverar disk kryptering på Service Fabric skalnings uppsättningar för virtuella kluster datorer i Linux.
* Steg att följa innan du aktiverar disk kryptering på Service Fabric klusternoder i Linux.
* Steg som ska följas för att aktivera disk kryptering på Service Fabric klusternoder i Linux.
[!INCLUDE [updated-for-az](../../includes/updated-for-az.md)]
## <a name="prerequisites"></a>Förutsättningar
**Själv registrering**
För hands versionen av disk kryptering för den virtuella datorns skalnings uppsättning krävs själv registrering. Gör så här:
1. Kör följande kommando:
```powershell
Register-AzProviderFeature -ProviderNamespace Microsoft.Compute -FeatureName "UnifiedDiskEncryption"
```
2. Vänta cirka 10 minuter tills statusen *har lästs.* Du kan kontrol lera statusen genom att köra följande kommando:
```powershell
Get-AzProviderFeature -ProviderNamespace "Microsoft.Compute" -FeatureName "UnifiedDiskEncryption"
Register-AzResourceProvider -ProviderNamespace Microsoft.Compute
```
**Azure Key Vault**
1. Skapa ett nyckel valv i samma prenumeration och region som skalnings uppsättningen. Välj sedan **EnabledForDiskEncryption** -åtkomst principen i nyckel valvet med hjälp av dess PowerShell-cmdlet. Du kan också ange principen med hjälp av Key Vault gränssnittet i Azure Portal med följande kommando:
```powershell
Set-AzKeyVaultAccessPolicy -VaultName $keyVaultName -EnabledForDiskEncryption
```
2. Installera den senaste versionen av [Azure CLI](/cli/azure/install-azure-cli), som har de nya krypterings kommandona.
3. Installera den senaste versionen av [Azure SDK från Azure PowerShell](https://github.com/Azure/azure-powershell/releases) -versionen. Följande är skalnings uppsättningen för den virtuella datorn Azure Disk Encryption-cmdletar för att aktivera ([Ange](/powershell/module/az.compute/set-azvmssdiskencryptionextension)) kryptering, Hämta ([Hämta](/powershell/module/az.compute/get-azvmssvmdiskencryption)) krypterings status och ta bort ([inaktivera](/powershell/module/az.compute/disable-azvmssdiskencryption)) kryptering på skalnings uppsättnings instansen.
| Kommando | Version | Källa |
| ------------- |-------------| ------------|
| Get-AzVmssDiskEncryptionStatus | 1.0.0 eller senare | Az.Compute |
| Get-AzVmssVMDiskEncryptionStatus | 1.0.0 eller senare | Az.Compute |
| Disable-AzVmssDiskEncryption | 1.0.0 eller senare | Az.Compute |
| Get-AzVmssDiskEncryption | 1.0.0 eller senare | Az.Compute |
| Get-AzVmssVMDiskEncryption | 1.0.0 eller senare | Az.Compute |
| Set-AzVmssDiskEncryptionExtension | 1.0.0 eller senare | Az.Compute |
## <a name="supported-scenarios-for-disk-encryption"></a>Scenarier som stöds för disk kryptering
* Kryptering för skalnings uppsättningar för virtuella datorer stöds bara för skalnings uppsättningar som skapats med hanterade diskar. Det finns inte stöd för interna (eller ohanterade) disk skalnings uppsättningar.
* Både kryptering och inaktive ring av kryptering stöds för OS-och data volymer i skalnings uppsättningar för virtuella datorer i Linux.
* Avbildnings-och uppgraderings åtgärder för virtuella datorer (VM) för virtuella datorer stöds inte i den aktuella för hands versionen.
## <a name="create-a-new-cluster-and-enable-disk-encryption"></a>Skapa ett nytt kluster och aktivera disk kryptering
Använd följande kommandon för att skapa ett kluster och aktivera disk kryptering med hjälp av en Azure Resource Manager-mall och ett självsignerat certifikat.
### <a name="sign-in-to-azure"></a>Logga in på Azure
Logga in med följande kommandon:
```powershell
Login-AzAccount
Set-AzContext -SubscriptionId <guid>
```
```azurecli
azure login
az account set --subscription $subscriptionId
```
### <a name="use-the-custom-template-that-you-already-have"></a>Använd den anpassade mall som du redan har
Om du behöver skapa en anpassad mall rekommenderar vi starkt att du använder en av mallarna på sidan exempel på [mall för skapande av Azure Service Fabric-kluster](https://github.com/Azure-Samples/service-fabric-cluster-templates/tree/master) .
Om du redan har en anpassad mall, kontrol lera att alla tre certifikat-relaterade parametrar i mallen och parameter filen har namnet enligt följande. Se också till att värdena är null enligt följande:
```Json
"certificateThumbprint": {
"value": ""
},
"sourceVaultValue": {
"value": ""
},
"certificateUrlValue": {
"value": ""
},
```
Eftersom endast data disk kryptering stöds för skalnings uppsättningar för virtuella datorer i Linux, måste du lägga till en datadisk med hjälp av en Resource Manager-mall. Uppdatera mallen för data disk etablering på följande sätt:
```Json
"storageProfile": {
"imageReference": {
"publisher": "[parameters('vmImagePublisher')]",
"offer": "[parameters('vmImageOffer')]",
"sku": "[parameters('vmImageSku')]",
"version": "[parameters('vmImageVersion')]"
},
"osDisk": {
"caching": "ReadOnly",
"createOption": "FromImage",
"managedDisk": {
"storageAccountType": "[parameters('storageAccountType')]"
}
},
"dataDisks": [
{
"diskSizeGB": 1023,
"lun": 0,
"createOption": "Empty"
```
```powershell
$resourceGroupLocation="westus"
$resourceGroupName="mycluster"
$CertSubjectName="mycluster.westus.cloudapp.azure.com"
$certPassword="Password!1" | ConvertTo-SecureString -AsPlainText -Force
$certOutputFolder="c:\certificates"
$parameterFilePath="c:\templates\templateparam.json"
$templateFilePath="c:\templates\template.json"
New-AzServiceFabricCluster -ResourceGroupName $resourceGroupName -CertificateOutputFolder $certOutputFolder -CertificatePassword $certpassword -CertificateSubjectName $CertSubjectName -TemplateFile $templateFilePath -ParameterFile $parameterFilePath
```
Här är motsvarande CLI-kommando. Ändra värdena i declare-instruktionerna till lämpliga värden. CLI stöder alla andra parametrar som stöds av föregående PowerShell-kommando.
```azurecli
declare certPassword=""
declare resourceGroupLocation="westus"
declare resourceGroupName="mylinux"
declare certSubjectName="mylinuxsecure.westus.cloudapp.azure.com"
declare parameterFilePath="c:\mytemplates\linuxtemplateparm.json"
declare templateFilePath="c:\mytemplates\linuxtemplate.json"
declare certOutputFolder="c:\certificates"
az sf cluster create --resource-group $resourceGroupName --location $resourceGroupLocation \
--certificate-output-folder $certOutputFolder --certificate-password $certPassword \
--certificate-subject-name $certSubjectName \
--template-file $templateFilePath --parameter-file $parametersFilePath
```
### <a name="mount-a-data-disk-to-a-linux-instance"></a>Montera en datadisk till en Linux-instans
Innan du fortsätter med kryptering på en skalnings uppsättning för en virtuell dator måste du se till att den tillagda datadisken är korrekt monterad. Logga in på den virtuella Linux-klustret och kör kommandot **LSBLK** . Utdata ska visa den tillagda datadisken i kolumnen **monterings punkt** .
### <a name="deploy-application-to-a-service-fabric-cluster-in-linux"></a>Distribuera program till ett Service Fabric kluster i Linux
Om du vill distribuera ett program till klustret följer du stegen och anvisningarna i [snabb start: distribuera Linux-behållare till Service Fabric](service-fabric-quickstart-containers-linux.md).
### <a name="enable-disk-encryption-for-the-virtual-machine-scale-sets-created-previously"></a>Aktivera disk kryptering för de virtuella datorernas skalnings uppsättningar som skapats tidigare
Om du vill aktivera disk kryptering för de skalnings uppsättningar för virtuella datorer som du skapade i föregående steg, kör du följande kommandon:
```powershell
$VmssName = "nt1vm"
$vaultName = "mykeyvault"
$resourceGroupName = "mycluster"
$KeyVault = Get-AzKeyVault -VaultName $vaultName -ResourceGroupName $rgName
$DiskEncryptionKeyVaultUrl = $KeyVault.VaultUri
$KeyVaultResourceId = $KeyVault.ResourceId
Set-AzVmssDiskEncryptionExtension -ResourceGroupName $resourceGroupName -VMScaleSetName $VmssName -DiskEncryptionKeyVaultUrl $DiskEncryptionKeyVaultUrl -DiskEncryptionKeyVaultId $KeyVaultResourceId -VolumeType All
```
```azurecli
az vmss encryption enable -g <resourceGroupName> -n <VMSS name> --disk-encryption-keyvault <KeyVaultResourceId>
```
### <a name="validate-if-disk-encryption-is-enabled-for-a-virtual-machine-scale-set-in-linux"></a>Verifiera om disk kryptering har Aktiver ATS för en skalnings uppsättning för virtuella datorer i Linux
Kör följande kommandon för att hämta status för en hel skalnings uppsättning för virtuella datorer eller en instans i en skalnings uppsättning.
Dessutom kan du logga in på den virtuella Linux-klustret och köra **LSBLK** -kommandot. Utdata ska visa den tillagda datadisken i kolumnen **monterings punkt** och kolumnen **typ** ska vara Read *crypt*.
```powershell
$VmssName = "nt1vm"
$resourceGroupName = "mycluster"
Get-AzVmssDiskEncryption -ResourceGroupName $resourceGroupName -VMScaleSetName $VmssName
Get-AzVmssVMDiskEncryption -ResourceGroupName $resourceGroupName -VMScaleSetName $VmssName -InstanceId "0"
```
```azurecli
az vmss encryption show -g <resourceGroupName> -n <VMSS name>
```
### <a name="disable-disk-encryption-for-a-virtual-machine-scale-set-in-a-service-fabric-cluster"></a>Inaktivera disk kryptering för en skalnings uppsättning för virtuella datorer i ett Service Fabric kluster
Inaktivera disk kryptering för en skalnings uppsättning för virtuella datorer genom att köra följande kommandon. Observera att om du inaktiverar disk kryptering gäller hela skalnings uppsättningen för den virtuella datorn och inte en enskild instans.
```powershell
$VmssName = "nt1vm"
$resourceGroupName = "mycluster"
Disable-AzVmssDiskEncryption -ResourceGroupName $rgName -VMScaleSetName $VmssName
```
```azurecli
az vmss encryption disable -g <resourceGroupName> -n <VMSS name>
```
## <a name="next-steps"></a>Nästa steg
I det här läget bör du ha ett säkert kluster och veta hur du aktiverar och inaktiverar disk kryptering för Service Fabric klusternoder och skalnings uppsättningar för virtuella datorer. För liknande vägledning om Service Fabric klusternoder i Linux, se [disk kryptering för Windows](service-fabric-enable-azure-disk-encryption-windows.md).
|
Shell | UTF-8 | 1,085 | 3.28125 | 3 | [
"Apache-2.0"
] | permissive | #!/bin/bash
set -ex
# redirect stderr to stdout
exec 2>&1
JOB_DIR=/var/vcap/jobs/registry-broker
PACKAGES_DIR=/var/vcap/packages
PATH=$PACKAGES_DIR/cf/bin:$PATH
PATH=$PACKAGES_DIR/jq/bin:$PATH
CF_ADMIN_USERNAME=<%= p("cf.admin_username") %>
CF_ADMIN_PASSWORD=<%= p("cf.admin_password") %>
CF_API_URL=<%= p("cf.system_api_url") %>
CF_SYSTEM_DOMAIN=<%= p("cf.system_domain") %>
BROKER_NAME=<%= p("nfs_volume_broker.name") %>
function authenticate() {
cf api $CF_API_URL <% if p("cf.ha_proxy.skip_cert_verify") %>--skip-ssl-validation<% end %>
cf auth $CF_ADMIN_USERNAME $CF_ADMIN_PASSWORD
}
function register_service_broker() {
local results=$(cf curl /v2/service_brokers?q=name:$BROKER_CF_APP_NAME | jq '.total_results | tonumber')
local action="create-service-broker"
if [ $results -eq 1 ]; then
action="update-service-broker"
fi
cf $action \
$BROKER_NAME \
<%= p("nfs_volume_broker.username") %> \
<%= p("nfs_volume_broker.password") %> \
<%= p("nfs_volume_broker.url") %>
cf enable-service-access nfs
}
authenticate
register_service_broker
|
Python | UTF-8 | 412 | 3.3125 | 3 | [] | no_license | a1 = eval(input())
d = eval(input())
n = eval(input())
t = (2*a1 + d*(n-1))*n/2
for i in range(1,n+1):
an = a1 + (i-1)*d
if i == n:
if an < 0:
print('(%s) = '%(an),end='')
else:
print('%s = '%(an),end='')
else:
if an < 0:
print('(%s) + '%(an),end='')
else:
print('%s + '%(an),end='')
print('%d'%(t),sep='',end='')
|
C++ | UTF-8 | 3,184 | 2.828125 | 3 | [
"BSD-3-Clause"
] | permissive | /** @file PythonUtilities.h
@author M. Kerr
This file collects routines for sending/receiving data to/from the Python
interpreter.
*/
#ifndef skymaps_PythonUtilities_h
#define skymaps_PythonUtilities_h
#include <vector>
#include "skymaps/WeightedSkyDir.h"
#include "astro/SkyDir.h"
#include "astro/SkyFunction.h"
namespace skymaps {
/// Class to group utilities in a single namespace.
class PythonUtilities
{
public:
// This will take the flat grid at the equator, rotate it to the
// ROI frame, and evaluate a SkyFunction over it.
static void val_grid(double* rvals, int rvals_size,
const std::vector<double>& lons, const std::vector<double>&lats,
const astro::SkyDir& roi_center, const astro::SkyFunction& myfunc);
// This will rotate a grid of lons/lats from the ROI frame to the
// flat grid frame on the equator. (Presumably the lons/lats
// are in the ROI.) They are in the Galactic coordinate system.
// @brief get the rotated lons and lats for a list of positions
// @param rvals pre-allocated memory, 2 float for each member of sdirs
// @param sdirs vector of grid points to rotate
static void rot_grid (double *rvals, int rvals_size,
const std::vector<astro::SkyDir> sdirs,
const astro::SkyDir& roi_center);
// Return the arclength (in radians) between the SkyDirs in sdirs
// and the SkyDir specified by roi_center
static void arclength(double *rvals, int rvals_size,
const std::vector<astro::SkyDir> sdirs,
const astro::SkyDir& roi_center);
// Get a column of floats from a FITS file
static void get_float_col(double *rvals, int rvals_size,
const std::string file_name,
const std::string table_name,
const std::string col_name);
// convert barycentered times to topocentric (at LAT) MET
// input should be TDB in MJD units
// tolerance is in (s)
static void tdb2met(double *rvals, int rvals_size,
double ra, double dec,
const std::string sc_file,
double tol);
// convert MET (topocentric TT) to barycentered times
// input should be MET in s; output is in TDB in s referenced to MET origin
static void met2tdb(double *rvals, int rvals_size,
double ra, double dec,
const std::string sc_file);
// convert MET (topocentric TT) to geocentric TT
// input should be MET in s; output is in TT@geocenter referenced to MET origin
static void met2geo(double *rvals, int rvals_size,
double ra, double dec,
const std::string sc_file);
static void get_wsdl_weights(double *rvals, int rvals_size,
const skymaps::BaseWeightedSkyDirList& wsdl);
static void set_wsdl_weights(const std::vector<double>& weights,
skymaps::BaseWeightedSkyDirList& wsdl);
};
}
#endif
|
Java | UTF-8 | 1,967 | 1.882813 | 2 | [] | no_license | package world;
public class GameIDs {
public static enum Zone{
RESIDENTIAL,
POLICE,
FIRE,
COMMERCIAL,
INDUSTRIAL,
NUCLEAR,
COAL,
AIRPORT,
SEAPORT,
STADIUM,
GIFT,
COALREFINERY
}
public static enum Block{
DIRT,
ROAD,
RAIL,
POWERLINE,
FOREST,
COALMINER,
OILMINER,
URANIUMMINER,
RAREMETALMINER
}
public static enum Value{
// every block is one of these for calculating land value, consider using different names as
// negatives still translate to positive points
MAJORNEGATIVE, // airport/seaport/coal pollution
MINORNEGATIVE, // industrial pollution, road pollution, certain gifts
NEUTRAL, // population, service, railway, powerline, nuclear
MINORPOSITIVE, // forest, certain gifts
MAJORPOSITIVE, // water, forest park, certain gifts
}
public static enum Image{
DIRT,
FOREST,
ROAD,
RAIL,
RESIDENTIAL,
INDUSTRIAL,
COMMERCIAL,
POLICE,
NUCLEAR,
POWERLINE,
POWEROFF,
BUILDINGSCROLLER,
BUILDER3,
RESOURCESELECTOR,
WATER,
BUTTONS,
AIRPORT,
SEAPORT,
COALMINER,
COALREFINER,
COALPLANT,
OILMINER,
OILREFINER,
OILPLANT,
URANIUMMINER,
URANIUMREFINER,
URANIUMPLANT,
RAREMETALMINER,
RAREMETALREFINER,
RAREMETALPLANT,
RESOURCEMENU,
BUTTONGREEN,
BUTTONRED,
POINTER,
CURSOR,
TOPBUTTONS,
BACKGROUND_GREY,
BACKGROUND_LIGHTGREEN,
BACKGROUND_DARKGREEN
}
public static enum Cursor{
BULLDOZE,
SELECT,
ONE,
THREE,
FOUR,
SIX
}
public static enum Button{
BULLDOZE,
ROAD,
RAIL,
POWERLINE,
FOREST,
RESIDENTIAL,
COMMERCIAL,
INDUSTRIAL,
POLICE,
FIRE,
STADIUM,
SEAPORT,
COAL,
NUCLEAR,
AIRPORT,
GIFT,
BLOCKCLICK,
UNDEFINED
}
public enum TopButton{
GAMESPEED,
SETUP,
DISASTERS,
STATISTICS,
SAVELOAD,
ADVICE,
MAGNIFY,
HELICOPTER
}
}
|
C++ | UTF-8 | 1,300 | 2.625 | 3 | [
"LGPL-3.0-only"
] | permissive | #pragma once
#include "software/backend/backend.h"
#include "software/backend/input/network/networking/network_client.h"
#include "software/backend/output/radio/radio_output.h"
class RadioBackend : public Backend
{
public:
static const std::string name;
RadioBackend();
private:
static const int DEFAULT_RADIO_CONFIG = 0;
void onValueReceived(ConstPrimitiveVectorPtr primitives) override;
/**
* This is registered as an async callback function so that it is called
* with a new world every time one is available
*
* @param world The new world
*/
void receiveWorld(World world);
/**
* Convert robot_status to TbotsRobotMsg and send as a SensorMsg to observers
*
* @param robot_status The RobotStatus
*/
void receiveRobotStatus(RobotStatus robot_status);
// The interface with the network that lets us get new information about the world
NetworkClient network_input;
// The interface that lets us send primitives to the robots over radio
RadioOutput radio_output;
std::optional<World> most_recently_received_world;
std::mutex most_recently_received_world_mutex;
ConstPrimitiveVectorPtr most_recently_received_primitives;
std::mutex most_recently_received_primitives_mutex;
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.