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
|
---|---|---|---|---|---|---|---|
JavaScript
|
UTF-8
| 631 | 2.765625 | 3 |
[] |
no_license
|
/**
* @author Morgan Wheatman
*/
window.addEventListener('load', function() {
'use strict';
const contactForm = document.getElementById('contact');
contactForm.submit.onclick = checkConsent;
var consentSelected = false;
function checkConsent(_evt){
var consent = contactForm.consent;
if(consent.value == "selectOption"){
consentSelected = false;
}else{
consentSelected = true;
}
if(consentSelected == false){
_evt.preventDefault();
var message = document.getElementById('errorMessage');
message.style.display = 'block';
}
}
});
|
Markdown
|
UTF-8
| 533 | 2.5625 | 3 |
[] |
no_license
|
# Article L121-2
Les associations sportives scolaires et universitaires sont soumises aux dispositions du présent code ainsi qu'aux livres V
et VIII du code de l'éducation.
**Liens relatifs à cet article**
**Anciens textes**:
- Loi n°84-610 1984-07-16 art. 7, alinéa 2
- Loi n°84-610 du 16 juillet 1984 - art. 7 (Ab)
**Cité par**:
- Décret n°2002-488 du 9 avril 2002 - art. 1 (Ab)
- Décret n°2002-761 du 2 mai 2002 - art. 2 (M)
**Codifié par**:
- Ordonnance 2006-596 2006-05-23 JORF 25 mai 2006
|
Java
|
UTF-8
| 345 | 1.742188 | 2 |
[] |
no_license
|
package org.capstore.rest.dao;
import javax.transaction.Transactional;
import org.capstore.rest.model.Order;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Transactional
@Repository("orderDao")
public interface IOrderDao extends JpaRepository<Order, Integer> {
}
|
C++
|
UTF-8
| 8,451 | 3.1875 | 3 |
[] |
no_license
|
#include "intdeque.hpp"
#include <stdlib.h>
#include <stdio.h>
/* Output Functions */
void addleft_o(IntDeque & _deque, int _element, const char * name);
void addright_o(IntDeque & _deque, int _element, const char * name);
void removeleft_o(IntDeque & _deque, const char * name);
void removeright_o(IntDeque & _deque, const char * name);
void int_plus_deque_o(IntDeque & _deque, int _element, const char * name);
void deque_plus_int_o(IntDeque & _deque, int _element, const char * name);
void prefix_deque_o(IntDeque & _deque, const char * name);
void postfix_deque_o(IntDeque & _deque, const char * name);
void if_equals_deque_o(IntDeque & _deque1, const char * name1,IntDeque & _deque2, const char * name2);
/* End of Output Functions */
/* Debug Functions */
void print_deque_state(IntDeque & input, const char* name);
void print_deque(IntDeque & input, const char* name);
/* End of Debug Functions */
int main() {
IntDeque pdeque01,pdeque02;
printf(" Fiiling up pdeque01...\n");
int_plus_deque_o(pdeque01, 1, "pdeque01");
int_plus_deque_o(pdeque01, 5, "pdeque01");
int_plus_deque_o(pdeque01, 6, "pdeque01");
deque_plus_int_o(pdeque01, 7, "pdeque01");
deque_plus_int_o(pdeque01, 6, "pdeque01");
deque_plus_int_o(pdeque01, 9, "pdeque01");
printf(" Testing --pdeque01 only...\n");
prefix_deque_o(pdeque01, "pdeque01");
prefix_deque_o(pdeque01, "pdeque01");
prefix_deque_o(pdeque01, "pdeque01");
prefix_deque_o(pdeque01, "pdeque01");
prefix_deque_o(pdeque01, "pdeque01");
prefix_deque_o(pdeque01, "pdeque01");
prefix_deque_o(pdeque01, "pdeque01");
prefix_deque_o(pdeque01, "pdeque01");
printf(" Fiiling up pdeque01...\n");
int_plus_deque_o(pdeque01, 1, "pdeque01");
int_plus_deque_o(pdeque01, 5, "pdeque01");
int_plus_deque_o(pdeque01, 6, "pdeque01");
deque_plus_int_o(pdeque01, 7, "pdeque01");
deque_plus_int_o(pdeque01, 6, "pdeque01");
deque_plus_int_o(pdeque01, 9, "pdeque01");
printf(" Testing pdeque01-- only...\n");
postfix_deque_o(pdeque01, "pdeque01");
postfix_deque_o(pdeque01, "pdeque01");
postfix_deque_o(pdeque01, "pdeque01");
postfix_deque_o(pdeque01, "pdeque01");
postfix_deque_o(pdeque01, "pdeque01");
postfix_deque_o(pdeque01, "pdeque01");
postfix_deque_o(pdeque01, "pdeque01");
postfix_deque_o(pdeque01, "pdeque01");
printf(" Fiiling up pdeque01...\n");
int_plus_deque_o(pdeque01, 1, "pdeque01");
int_plus_deque_o(pdeque01, 5, "pdeque01");
int_plus_deque_o(pdeque01, 6, "pdeque01");
deque_plus_int_o(pdeque01, 7, "pdeque01");
deque_plus_int_o(pdeque01, 6, "pdeque01");
deque_plus_int_o(pdeque01, 9, "pdeque01");
printf(" Testing --pdeque01 and pdeque01-- together...\n");
postfix_deque_o(pdeque01, "pdeque01");
prefix_deque_o(pdeque01, "pdeque01");
prefix_deque_o(pdeque01, "pdeque01");
postfix_deque_o(pdeque01, "pdeque01");
prefix_deque_o(pdeque01, "pdeque01");
postfix_deque_o(pdeque01, "pdeque01");
prefix_deque_o(pdeque01, "pdeque01");
prefix_deque_o(pdeque01, "pdeque01");
postfix_deque_o(pdeque01, "pdeque01");
prefix_deque_o(pdeque01, "pdeque01");
printf(" Fiiling up pdeque01...\n");
int_plus_deque_o(pdeque01, 3, "pdeque01");
int_plus_deque_o(pdeque01, 2, "pdeque01");
int_plus_deque_o(pdeque01, 1, "pdeque01");
deque_plus_int_o(pdeque01, 4, "pdeque01");
deque_plus_int_o(pdeque01, 5, "pdeque01");
deque_plus_int_o(pdeque01, 6, "pdeque01");
printf(" Fiiling up pdeque02...\n");
int_plus_deque_o(pdeque02, 3, "pdeque02");
int_plus_deque_o(pdeque02, 2, "pdeque02");
int_plus_deque_o(pdeque02, 1, "pdeque02");
deque_plus_int_o(pdeque02, 4, "pdeque02");
deque_plus_int_o(pdeque02, 5, "pdeque02");
deque_plus_int_o(pdeque02, 6, "pdeque02");
printf(" Is pdeque01 equals pdeque02?\n");
if_equals_deque_o(pdeque01, "pdeque01", pdeque02, "pdeque02");
printf(" Changing pdeque01...\n");
prefix_deque_o(pdeque01, "pdeque01");
prefix_deque_o(pdeque01, "pdeque01");
printf(" Is pdeque01 equals pdeque02?\n");
if_equals_deque_o(pdeque01, "pdeque01", pdeque02, "pdeque02");
printf(" Let's make an equation between pdeque01 and pdeque02...\n");
prefix_deque_o(pdeque02, "pdeque02");
prefix_deque_o(pdeque02, "pdeque02");
printf(" Is pdeque01 equals pdeque02?\n");
if_equals_deque_o(pdeque01, "pdeque01", pdeque02, "pdeque02");
printf(" Constructing pdeque03...\n");
IntDeque pdeque03;
printf(" Assigning pdeque01 to pdeque03...\n");
pdeque03 = pdeque01;
printf(" Is pdeque03 equals pdeque02?\n");
if_equals_deque_o(pdeque03, "pdeque03", pdeque02, "pdeque02");
postfix_deque_o(pdeque01, "pdeque01");
postfix_deque_o(pdeque01, "pdeque01");
postfix_deque_o(pdeque01, "pdeque01");
postfix_deque_o(pdeque01, "pdeque01");
postfix_deque_o(pdeque01, "pdeque01");
postfix_deque_o(pdeque01, "pdeque01");
postfix_deque_o(pdeque01, "pdeque01");
postfix_deque_o(pdeque01, "pdeque01");
pdeque03 = pdeque02 = pdeque01;
postfix_deque_o(pdeque03, "pdeque03");
postfix_deque_o(pdeque02, "pdeque02");
printf(" Is pdeque03 equals pdeque02?\n");
if_equals_deque_o(pdeque03, "pdeque03", pdeque02, "pdeque02");
return 0;
}
void int_plus_deque_o(IntDeque & _deque, int _element, const char * name) {
int * tmp;
tmp = _element + _deque;
printf("%d + %s == ", _element, name);
if (tmp) {
printf("OK\n");
} else {
printf("NoMemory\n");
}
};
void deque_plus_int_o(IntDeque & _deque, int _element, const char * name) {
int * tmp;
tmp = _deque + _element;
printf("%s + %d == ", name, _element);
if (tmp) {
printf("OK\n");
} else {
printf("NoMemory\n");
}
};
void prefix_deque_o(IntDeque & _deque, const char * name) {
int * tmp;
tmp = --_deque;
printf("--%s == ",name);
if (tmp) {
printf("%d\n",*tmp);
} else {
printf("DequeIsEmpty\n");
}
};
void postfix_deque_o(IntDeque & _deque, const char * name) {
int * tmp;
tmp = _deque--;
printf("%s-- == ",name);
if (tmp) {
printf("%d\n",*tmp);
} else {
printf("DequeIsEmpty\n");
}
};
void if_equals_deque_o(IntDeque & _deque1, const char * name1,IntDeque & _deque2, const char * name2) {
int tmp;
tmp = _deque1 == _deque2;
if (tmp == 1) {
printf("%s == %s\n",name1,name2);
} else {
printf("%s != %s\n",name1,name2);
}
};
void addleft_o(IntDeque & _deque, int _element, const char * name) {
_deque.AddLeft(_element);
printf("%s.AddLeft(%d); %s.GetElement() == %d\n", name, _element, name, _deque.GetElement());
};
void addright_o(IntDeque & _deque, int _element, const char * name) {
_deque.AddRight(_element);
printf("%s.AddRight(%d); %s.GetElement() == %d\n", name, _element, name, _deque.GetElement());
};
void removeleft_o(IntDeque & _deque, const char * name) {
int * tmp;
tmp = _deque.RemoveLeft();
if (tmp != NULL) {
printf("%s.RemoveLeft(); %s.GetElement == %d\n", name, name, _deque.GetElement());
} else {
printf("%s.RemoveLeft() == NULL\n", name);
}
};
void removeright_o(IntDeque & _deque, const char * name) {
int * tmp;
tmp = _deque.RemoveRight();
if (tmp != NULL) {
printf("%s.RemoveRight(); %s.GetElement == %d\n", name, name, _deque.GetElement());
} else {
printf("%s.RemoveRight() == NULL\n", name);
}
};
/* Debug Functions (request access to private fields) */
/*void print_deque_state(IntDeque & input,const char* name) {
printf("\nname == %s\nleft == %p\nright == %p\nbuffer == %d\n", name, input.left, input -> right, input -> buffer);
};
void print_deque(IntDeque & input, const char* name) {
IntDequeElement * tmp;
printf("\nPrinted %s: \n\n",name);
tmp = input.left;
while(tmp) {
printf("elem: %d \n", tmp->GetElement());
printf("addr: %p \n", &tmp);
printf("prev: %p \n", tmp->GetPrev());
printf("next: %p \n", tmp->GetNext());
printf("\n");
tmp = tmp -> GetNext();
}
};*/
/* End of Debug Functions */
|
Python
|
UTF-8
| 313 | 3.1875 | 3 |
[] |
no_license
|
from bokeh.plotting import figure
from bokeh.io import output_file, show
import pandas as pd
x = [1,2,3,4,5]
y = [6,7,8,9,10]
output_file('line.html')
f = figure()
f.line(x,y)
show(f)
df = pd.read_csv('data.csv')
x1 = df['x']
y1 = df['y']
output_file('line_from_csv.html')
f = figure()
f.line(x1,y1)
show(f)
|
C#
|
UTF-8
| 4,704 | 3.03125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Windows.Forms;
namespace Hu.WinControler
{
internal class App
{
// IntPtr hwnd; //进程句柄
Process process;
List<AppFunction> functions = new List<AppFunction>();
public App() { }
public App(int command, string description,string path,bool started)
{
Command = command;
Description = description;
Path = path;
Started = started;
}
//程序是否已启动
public bool Started { get; set; }
/// <summary>
/// 程序主窗体句柄
/// </summary>
public IntPtr Handle
{
get { return process.MainWindowHandle;}
// private set { this.hwnd = value; }
}
/// <summary>
/// 关联的进程是否已退出
/// </summary>
/// <returns></returns>
public bool HasExited
{
get { return process.HasExited; }
}
/// <summary>
/// 应用程序的启动路径
/// </summary>
public string Path { get; set; }
/// <summary>
/// 应用程序描述
/// </summary>
public string Description { get; set; }
/// <summary>
/// 程序对应命令
/// </summary>
public int Command { get; set; }
/// <summary>
/// 发送命令
/// </summary>
/// <param name="command">要发送的功能命令</param>
public void Send(int command)
{
SendFunction(command);
}
/// <summary>
/// 发送命令,并且在此方法中修改选择应用程序标志
/// </summary>
/// <param name="command">要发送的命令</param>
/// <param name="isSelectingApplication">是否处于选择程序的模式</param>
public void Send(int command, ref bool isSelectingApplication)
{
throw new System.NotImplementedException("方法未实现:app.send(int,ref bool)");
}
/// <summary>
/// 判断程序是否包含funtionCommand功能命令对应的功能
/// </summary>
/// <param name="functionCommand"></param>
/// <returns></returns>
public bool ContainsFunction(int functionCommand)
{
return functions.Exists(e => e.Command == functionCommand);
}
/// <summary>
/// 执行程序功能
/// </summary>
/// <param name="functionCommand">功能命令</param>
public void SendFunction(int functionCommand)
{
functions.ForEach(e =>
{
if (e.Command == functionCommand && Handle == Win32.User32.GetForegroundWindow())
e.Send();
});
}
#region 程序打开与关闭
/// <summary>
/// 启动程序
/// </summary>
/// <returns>启动成功则返回true,否则返回false</returns>
public bool Start()
{
try
{
if (process == null)
process = Process.Start(Path);
else
if (process.HasExited)
process.Start();
return process != null;
}
catch
{
new Exception(string.Format("程序:\"{0}\"无法启动!",Path));
return false;
}
}
/// <summary>
/// 关闭程序
/// </summary>
/// <returns>关闭成功则返回true,否则返回false</returns>
public bool Close()
{
if (process != null && !process.HasExited)
{
process.CloseMainWindow();
return process.HasExited;
}
else
return false;
}
#endregion
#region 向程序添加功能
/// <summary>
/// 向程序添加功能
/// </summary>
/// <param name="func"></param>
public void AddFunction(AppFunction function)
{
functions.Add(function);
}
/// <summary>
/// 向程序添加功能集
/// </summary>
/// <param name="functions"></param>
public void AddFunction(List<AppFunction> functions)
{
this.functions.AddRange(functions);
}
#endregion
public override string ToString()
{
return this.Description;
}
}
}
|
Python
|
UTF-8
| 286 | 4.0625 | 4 |
[] |
no_license
|
#PIG LATIN
# Asks user to input a sentence
# conver words to Pig Latin
# moving first letter to end and add "ay" to the word
def main():
words = str(input("Enter a Sentence: ")).split()
for word in words:
print(word[1:] + word[0] + "ay", end = " ")
print()
main()
|
JavaScript
|
UTF-8
| 1,283 | 4.5625 | 5 |
[] |
no_license
|
/**
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
*/
/**
* @param {string} s
* @return {number}
*/
var lengthOfLongestSubstring = function(s) {
if(typeof s === 'undefined' || !s) return 0;
if(s.length <= 1) return s.length;
let maxlen = 0;
let as = s.split('');
let temp = [];
let index = 0;
while(as.length > 1){
temp.push(as.shift());
for(let c of as){
if(temp.indexOf(c) !== -1) break;
temp.push(c);
}
maxlen = maxlen > temp.length ? maxlen : temp.length;
index++;
temp = [];
}
return maxlen;
};
//console.log(lengthOfLongestSubstring('abcabcbb')); // 3
//console.log(lengthOfLongestSubstring('bbbbb')); // 1
//console.log(lengthOfLongestSubstring('pwwkew')); // 3
console.log(lengthOfLongestSubstring(' ')); // 3
|
C#
|
UTF-8
| 530 | 3.65625 | 4 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApp1
{
class Binary_Number_with_Alternating_Bits
{
//The solution is to use bit manipulation. And d is last digit of n.
public static bool HasAlternatingBits(int n)
{
int d = n & 1; // last pos value in n's binary format
while ((n & 1) == d)
{
d = 1 - d;
n >>= 1;
}
return n == 0;
}
}
}
|
Java
|
UTF-8
| 670 | 1.890625 | 2 |
[] |
no_license
|
package com.fjsimon.uberweisung.service;
import com.fjsimon.uberweisung.domain.service.request.CreateTransactionRequest;
import com.fjsimon.uberweisung.domain.service.request.GetTransactionsRequest;
import com.fjsimon.uberweisung.domain.service.response.CreateTransactionResponse;
import com.fjsimon.uberweisung.domain.service.response.GetTransactionResponse;
import javax.validation.Valid;
import java.util.List;
public interface UberweisungService {
List<GetTransactionResponse> getTransactions(@Valid GetTransactionsRequest request);
CreateTransactionResponse createTransaction(@Valid CreateTransactionRequest request);
String generateGlobalId();
}
|
Java
|
UTF-8
| 9,742 | 2.28125 | 2 |
[] |
no_license
|
package com.sahil.mychatapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Toolbar;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.sahil.mychatapp.Adapter.MessageAdapter;
import com.sahil.mychatapp.Model.Chat;
import com.sahil.mychatapp.Model.User;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
public class MessageActivity extends AppCompatActivity {
private static final String TAG ="MessageActivity" ;
private ImageView Message_imageView;
private TextView Message_username;
private Toolbar toolbar;
private RecyclerView recyclerView;
private EditText send_msg_txt;
private ImageButton send_btn;
private FirebaseUser fuser;
private DatabaseReference ref;
private Intent intent ,inten1;
private List<Chat>mChat;
private MessageAdapter messageAdapter;
private ImageButton backBtn;
private TextView user_status;
String userid;
ValueEventListener seenlistener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
////////
requestWindowFeature(Window.FEATURE_NO_TITLE);//will hide the title
getSupportActionBar().hide(); //hide the title bar
///////
setContentView(R.layout.activity_message);
Message_imageView = findViewById(R.id.Message_imageView);
Message_username = findViewById(R.id.Message_username);
send_msg_txt = findViewById(R.id.send_msg_txt);
send_btn = findViewById(R.id.send_btn);
backBtn = findViewById(R.id.back_btn);
user_status = findViewById(R.id.user_status);
toolbar = findViewById(R.id.toolbar);
//Recycler view
recyclerView = findViewById(R.id.Mess_recyclerView);
// recyclerView.setHasFixedSize(true);
LinearLayoutManager manager = new LinearLayoutManager(getApplicationContext());
// manager.setStackFromEnd(true);
manager.canScrollVertically();
recyclerView.setLayoutManager(manager);
intent = getIntent();
userid = intent.getStringExtra("userid");
send_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String msg = send_msg_txt.getText().toString();
if (!msg.equals("")) {
sendMessage(msg, userid, fuser.getUid()); // fn to send msg to userid(friend) by you(firebaseUser.getUId)
} else {
Toast.makeText(MessageActivity.this, "Type something..",
Toast.LENGTH_SHORT).show();
}
send_msg_txt.setText("");
}
});
backBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MessageActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
});
fuser = FirebaseAuth.getInstance().getCurrentUser();
ref = FirebaseDatabase.getInstance().getReference("MyUsers").child(userid);
Log.d(TAG, "userId iss... " + ref);
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class); // get the values of data of user and storing in user obj.
Message_username.setText(user.getUserName());
user_status.setText(user.getStatus());
if (user.getImageURL().equals("default")) {
// Message_imageView.setImageResource(R.mipmap.ic_launcher_round);
Glide.with(getApplicationContext())
.load(R.drawable.default_dp)
.apply(RequestOptions.circleCropTransform())
.into(Message_imageView);
} else {
// Adding glide library
Glide.with(getApplicationContext())
.load(user.getImageURL())
.apply(RequestOptions.circleCropTransform())
.into(Message_imageView);
}
readMessage(fuser.getUid(), userid);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Log.d(TAG, "error hai ... " + error);
}
});
seenmessage(userid);
}
private void seenmessage(final String userid) {
ref = FirebaseDatabase.getInstance().getReference("Chats");
seenlistener= ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot d : snapshot.getChildren()) {
try{
Chat chat = d.getValue(Chat.class);
if (chat.getReceiver().equals(fuser.getUid()) && chat.getSender().equals(userid)) {
HashMap<String, Object> map = new HashMap<>();
map.put("isseen", true);
d.getRef().updateChildren(map);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Log.d("SEEEN", " f " + error);
}
});
}
private void sendMessage(String Message, final String Receiver, String Sender) {
DatabaseReference myreference = FirebaseDatabase.getInstance().getReference();
HashMap<String,Object>hashMap = new HashMap<>(); // creating a HashMap and storing all tha values in key value pairs and
hashMap.put("Sender", Sender); //set them in address child by push set value.
hashMap.put("Receiver", Receiver);
hashMap.put("Message", Message);
hashMap.put("isseen", false);
myreference.child("Chats").push().setValue(hashMap);
//Adding User to chat Fragments: Latest Chats with contacts
final DatabaseReference chatref = FirebaseDatabase.getInstance().getReference("ChatList")
.child(fuser.getUid())
.child(userid);
chatref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if(!snapshot.exists()){
chatref.child("id").setValue(userid);
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
final DatabaseReference chatRefReceiver = FirebaseDatabase.getInstance().getReference("ChatList")
.child(userid)
.child(fuser.getUid());
chatRefReceiver.child("id").setValue(fuser.getUid());
}
private void readMessage(final String senderId , final String receiverId) {
mChat = new ArrayList<>();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Chats");
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
mChat.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Chat chat = dataSnapshot.getValue(Chat.class);
if (Objects.equals(chat.getSender(), senderId) && Objects.equals(chat.getReceiver(), receiverId)
|| Objects.equals(chat.getSender(), receiverId) && Objects.equals(chat.getReceiver(), senderId)) {
mChat.add(chat);
}
messageAdapter = new MessageAdapter(MessageActivity.this, mChat);
recyclerView.setAdapter(messageAdapter);
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
private void checkstatus(String status){
ref = FirebaseDatabase.getInstance().getReference("MyUsers").child(fuser.getUid());
HashMap<String ,Object>map = new HashMap<>();
map.put("status", status);
ref.updateChildren(map);
}
@Override
protected void onPostResume() {
super.onPostResume();
checkstatus("online");
}
@Override
protected void onPause() {
super.onPause();
ref.removeEventListener(seenlistener);
checkstatus("offline");
}
}
|
Java
|
UTF-8
| 7,454 | 1.953125 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.androidpublisher.model;
/**
* A single subscription for an app.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Google Play Android Developer API. For a detailed
* explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class Subscription extends com.google.api.client.json.GenericJson {
/**
* Output only. Whether this subscription is archived. Archived subscriptions are not available to
* any subscriber any longer, cannot be updated, and are not returned in list requests unless the
* show archived flag is passed in.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean archived;
/**
* The set of base plans for this subscription. Represents the prices and duration of the
* subscription if no other offers apply.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<BasePlan> basePlans;
static {
// hack to force ProGuard to consider BasePlan used, since otherwise it would be stripped out
// see https://github.com/google/google-api-java-client/issues/543
com.google.api.client.util.Data.nullOf(BasePlan.class);
}
/**
* Required. List of localized listings for this subscription. Must contain at least an entry for
* the default language of the parent app.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<SubscriptionListing> listings;
/**
* Immutable. Package name of the parent app.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String packageName;
/**
* Immutable. Unique product ID of the product. Unique within the parent app. Product IDs must be
* composed of lower-case letters (a-z), numbers (0-9), underscores (_) and dots (.). It must
* start with a lower-case letter or number, and be between 1 and 40 (inclusive) characters in
* length.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String productId;
/**
* Details about taxes and legal compliance.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private SubscriptionTaxAndComplianceSettings taxAndComplianceSettings;
/**
* Output only. Whether this subscription is archived. Archived subscriptions are not available to
* any subscriber any longer, cannot be updated, and are not returned in list requests unless the
* show archived flag is passed in.
* @return value or {@code null} for none
*/
public java.lang.Boolean getArchived() {
return archived;
}
/**
* Output only. Whether this subscription is archived. Archived subscriptions are not available to
* any subscriber any longer, cannot be updated, and are not returned in list requests unless the
* show archived flag is passed in.
* @param archived archived or {@code null} for none
*/
public Subscription setArchived(java.lang.Boolean archived) {
this.archived = archived;
return this;
}
/**
* The set of base plans for this subscription. Represents the prices and duration of the
* subscription if no other offers apply.
* @return value or {@code null} for none
*/
public java.util.List<BasePlan> getBasePlans() {
return basePlans;
}
/**
* The set of base plans for this subscription. Represents the prices and duration of the
* subscription if no other offers apply.
* @param basePlans basePlans or {@code null} for none
*/
public Subscription setBasePlans(java.util.List<BasePlan> basePlans) {
this.basePlans = basePlans;
return this;
}
/**
* Required. List of localized listings for this subscription. Must contain at least an entry for
* the default language of the parent app.
* @return value or {@code null} for none
*/
public java.util.List<SubscriptionListing> getListings() {
return listings;
}
/**
* Required. List of localized listings for this subscription. Must contain at least an entry for
* the default language of the parent app.
* @param listings listings or {@code null} for none
*/
public Subscription setListings(java.util.List<SubscriptionListing> listings) {
this.listings = listings;
return this;
}
/**
* Immutable. Package name of the parent app.
* @return value or {@code null} for none
*/
public java.lang.String getPackageName() {
return packageName;
}
/**
* Immutable. Package name of the parent app.
* @param packageName packageName or {@code null} for none
*/
public Subscription setPackageName(java.lang.String packageName) {
this.packageName = packageName;
return this;
}
/**
* Immutable. Unique product ID of the product. Unique within the parent app. Product IDs must be
* composed of lower-case letters (a-z), numbers (0-9), underscores (_) and dots (.). It must
* start with a lower-case letter or number, and be between 1 and 40 (inclusive) characters in
* length.
* @return value or {@code null} for none
*/
public java.lang.String getProductId() {
return productId;
}
/**
* Immutable. Unique product ID of the product. Unique within the parent app. Product IDs must be
* composed of lower-case letters (a-z), numbers (0-9), underscores (_) and dots (.). It must
* start with a lower-case letter or number, and be between 1 and 40 (inclusive) characters in
* length.
* @param productId productId or {@code null} for none
*/
public Subscription setProductId(java.lang.String productId) {
this.productId = productId;
return this;
}
/**
* Details about taxes and legal compliance.
* @return value or {@code null} for none
*/
public SubscriptionTaxAndComplianceSettings getTaxAndComplianceSettings() {
return taxAndComplianceSettings;
}
/**
* Details about taxes and legal compliance.
* @param taxAndComplianceSettings taxAndComplianceSettings or {@code null} for none
*/
public Subscription setTaxAndComplianceSettings(SubscriptionTaxAndComplianceSettings taxAndComplianceSettings) {
this.taxAndComplianceSettings = taxAndComplianceSettings;
return this;
}
@Override
public Subscription set(String fieldName, Object value) {
return (Subscription) super.set(fieldName, value);
}
@Override
public Subscription clone() {
return (Subscription) super.clone();
}
}
|
C++
|
UTF-8
| 2,241 | 3.921875 | 4 |
[] |
no_license
|
/*
PROBLEM STATEMENT
Perform merge sort using linked list
input - number of elements in sequence
sequence of integers
*/
#include <bits/stdc++.h>
using namespace std;
struct node
{
int data;
node* nxt;
};
// Insert a node in the front of the list
void insert(int indata, node ** head)
{
node *temp = new node;
temp->data = indata;
temp->nxt = *head;
*head = temp;
}
// Merging utility for sorted sublists
node * merge_util(node *h1, node *h2)
{
node *h3, *last;
if (h1->data < h2->data)
{
h3 = h1;
h1 = h1->nxt;
h3->nxt = NULL;
}
else
{
h3 = h2;
h2 = h2->nxt;
h3->nxt = NULL;
}
last = h3;
while (h1!=NULL && h2!=NULL)
{
if (h1->data < h2->data)
{
last->nxt = h1;
h1 = h1->nxt;
last = last->nxt;
last->nxt = NULL;
}
else
{
last->nxt = h2;
h2 = h2->nxt;
last = last->nxt;
last->nxt = NULL;
}
}
if (h1 != NULL)
last->nxt = h1;
else if (h2 != NULL)
last->nxt = h2;
return h3;
}
// Recursive merge sort function
void mergesort(node **ptr, int sz)
{
if (sz==1) return;
int sz1 = sz/2;
node *h1 = *ptr;
node *h2 = *ptr;
for (int i=0; i<sz1-1; i++)
h2 = h2->nxt;
node *temp = h2;
h2 = h2->nxt;
temp->nxt = NULL;
temp = NULL;
mergesort(&h1,sz1);
mergesort(&h2,sz-sz1);
*ptr = merge_util(h1,h2);
}
void showlist(node * head)
{
node *ptr = head;
while (ptr != NULL)
{
cout << ptr->data << " ";
ptr = ptr->nxt;
}
cout << "\n";
}
void removelist(node **ptr)
{
if (*ptr == NULL) return;
removelist(&((*ptr)->nxt));
(*ptr)->nxt = NULL;
// cout << (*ptr)->data << " ";
delete *ptr;
// cout << (*ptr)->data << " ";
}
int main()
{
node *head = NULL;
int n;
cin >> n;
for (int i=0; i<n; i++)
{
int newdata;
cin >> newdata;
insert(newdata, &head);
}
mergesort(&head, n);
showlist(head);
removelist(&head);
head = NULL;
return 0;
}
|
Markdown
|
UTF-8
| 450 | 2.546875 | 3 |
[] |
no_license
|
{{#markdown}}
### Gérer les conflit (2/2)
```bash
# Savoir quels outils de résolution de conflit sont disponible
$ git mergetool --tool-help
# Lancer un outil de résolution de conflit
$ git mergetool -t <outil>
```
```bash
# Annuler une fusion conflictuelle
$ git merge --abort
```
```bash
# Reprendre un rebase après la résolution des conflits
$ git rebase --continue
# Annuler un rebase avec conflit
$ git rebase --abort
```
{{/markdown}}
|
Java
|
UTF-8
| 5,483 | 1.960938 | 2 |
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/*
* Straal3dsResponseCallableTest.java
* Created by Kamil Czanik on 14.01.2021
* Straal SDK for Android
* Copyright 2021 Straal Sp. z o. o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.straal.sdk;
import com.straal.sdk.data.RedirectUrls;
import com.straal.sdk.exceptions.ResponseParseException;
import com.straal.sdk.http.HttpResponse;
import com.straal.sdk.response.StraalEncrypted3dsResponse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.straal.sdk.response.TransactionStatus.CHALLENGE_3DS;
import static com.straal.sdk.response.TransactionStatus.SUCCESS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@DisplayName("Straal3dsResponseCallable")
class Straal3dsResponseCallableTest {
private Straal3dsResponseCallable straal3DSResponseCallable;
private HttpCallable httpResponseCallable = mock(HttpCallable.class);
private RedirectUrls redirectUrls = new RedirectUrls("url/success", "url/failure");
@BeforeEach
void createStraal3DSResponseCallable() {
straal3DSResponseCallable = new Straal3dsResponseCallable(httpResponseCallable, redirectUrls);
}
@DisplayName("Should return response with Transaction.SUCCESS when response is successful and location is nul")
@Test
void shouldReturnResponseWithSuccessStatusWhenSuccessfulAndLocationIsNull() throws Exception {
String requestId = "request-id";
mockHttpCallableResponse(requestId, Collections.emptyMap());
StraalEncrypted3dsResponse expected = new StraalEncrypted3dsResponse(requestId, redirectUrls, "", SUCCESS);
StraalEncrypted3dsResponse response = straal3DSResponseCallable.call();
assertResponse(expected, response);
}
@DisplayName("Should return response with Transaction.SUCCESS when response is successful and location equals successUrl")
@Test
void shouldReturnResponseWithSuccessStatusWhenSuccessfulAndLocationEqualsSuccessUrl() throws Exception {
String requestId = "request-id";
mockHttpCallableResponse(requestId, locationHeaders(redirectUrls.successUrl));
StraalEncrypted3dsResponse expected = new StraalEncrypted3dsResponse(requestId, redirectUrls, "", SUCCESS);
StraalEncrypted3dsResponse response = straal3DSResponseCallable.call();
assertResponse(expected, response);
}
@DisplayName("Should return response with Transaction.CHALLENGE_3DS when response is successful and location is not null")
@Test
void shouldReturnResponseWithChallenge3DSWhenSuccessfulAndLocationUrlIsAvailable() throws Exception {
String requestId = "request-id";
String locationUrl = "url/location";
mockHttpCallableResponse(requestId, locationHeaders(locationUrl));
StraalEncrypted3dsResponse expected = new StraalEncrypted3dsResponse(requestId, redirectUrls, locationUrl, CHALLENGE_3DS);
StraalEncrypted3dsResponse response = straal3DSResponseCallable.call();
assertResponse(expected, response);
}
@DisplayName("Should throw exception when successful and request_id is null")
@Test
void shouldThrowExceptionWhenSuccessfulAndRequestIdIsNull() {
Executable executable = new Executable() {
@Override
public void execute() throws Throwable {
HttpResponse httpResponse = new HttpResponse(200, "{}", Collections.emptyMap());
when(httpResponseCallable.call()).thenReturn(httpResponse);
straal3DSResponseCallable.call();
}
};
assertThrows(ResponseParseException.class, executable);
}
private Map<String, List<String>> locationHeaders(String locationUrl) {
HashMap<String, List<String>> result = new HashMap<>();
List<String> locations = new ArrayList<>();
locations.add(locationUrl);
result.put("Location", locations);
return result;
}
private void mockHttpCallableResponse(String requestId, Map<String, List<String>> headerFields) throws Exception {
HttpResponse httpResponse = new HttpResponse(200, "{\"request_id\":" + requestId + "}", headerFields);
when(httpResponseCallable.call()).thenReturn(httpResponse);
}
private void assertResponse(StraalEncrypted3dsResponse expected, StraalEncrypted3dsResponse actual) {
assertEquals(expected.status, actual.status);
assertEquals(expected.requestId, actual.requestId);
assertEquals(expected.locationUrl, actual.locationUrl);
assertEquals(expected.redirectUrls, actual.redirectUrls);
}
}
|
Python
|
UTF-8
| 2,491 | 4 | 4 |
[] |
no_license
|
# HW1 根據題目給的 DataFrame 完成下列操作:
#- 計算每個不同種類 animal 的 age 的平均數
#- 計算每個不同種類 animal 的 age 的平均數
#- 將資料依照 Age 欄位由小到大排序,再依照 visits 欄位由大到小排序
#- 將 priority 欄位中的 yes 和 no 字串,換成是布林值 的 True 和 False
import pandas as pd
import numpy as np
data = {
'animal': ['cat', 'cat', 'snake', 'dog', 'dog', 'cat', 'snake', 'cat', 'dog', 'dog'],
'age': [2.5, 3, 0.5, np.nan, 5, 2, 4.5, np.nan, 7, 3],
'visits': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'priority': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']
}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(data, index=labels)
print(df)
print(df[df['animal']=='cat'].age.mean())
print(df[df['animal']=='snake'].age.mean())
print(df[df['animal']=='dog'].age.mean())
df1=df.sort_values(by=['age'])
df2=df1.sort_values(by=['visits'],ascending=False)
print(df2)
df['priority']=df['priority'].str.replace('yes','True')
df['priority']=df['priority'].str.replace('no','False')
print(df)
# HW2 一個包含兩個欄位的 DataFrame,將每個數字減去
df = pd.DataFrame(np.random.random(size=(5, 3)))
print(df)
print(df.apply(lambda i : i-i.mean(axis=0)))
print(df.apply(lambda i : i-df.mean(axis=1)))
# 哪一比的資料總合最小
print(df.sum(axis=0).argmin())
# 哪一欄位的資料總合最小
print(df.sum(axis=1).argmin())
# 進階
#6號學生(student_id=6)3科平均分數為何?
#6號學生3科平均分數是否有贏過班上一半的同學?
#由於班上同學成績不好,所以學校統一加分,加分方式為開根號乘以十,請問6號同學3科成績分別是?
#承上題,加分後各科班平均變多少?
import pandas as pd
score_df = pd.DataFrame([[1,56,66,70],
[2,90,45,34],
[3,45,32,55],
[4,70,77,89],
[5,56,80,70],
[6,60,54,55],
[7,45,70,79],
[8,34,77,76],
[9,25,87,60],
[10,88,40,43]],columns=['student_id','math_score','english_score','chinese_score'])
score_df = score_df.set_index('student_id')
print(score_df)
print(score_df.mean(axis=1)[5:6])
x=score_df.mean(axis=1)
print(x[6])
if x[6]>score_df.mean(axis=1).median() :
print('yes')
else :
print('no')
print(score_df.apply(lambda x: x**(0.5)*10))
x=score_df.apply(lambda x: x**(0.5)*10)
print(x[5:6])
print(x.mean())
|
Python
|
UTF-8
| 1,552 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
from .Mode import Mode
FILTER_VERTEX_OPTIONS = [
['Pagerank (relative)', 'pagerankRelative'],
['Pagerank', 'pagerank'],
['Closeness (relative)', 'closenessRelative'],
['Closeness', 'closeness'],
['Betweenness (relative)', 'betweennessRelative'],
['Betweenness', 'betweenness'],
['Out degree', 'outdegree'],
['In degree', 'indegree'],
['Reference count', 'refCount'],
['Image count', 'imgCount'],
['Category count', 'catCount'],
]
class FilterMode(Mode):
priority = 3
def __init__(self, canvas):
super().__init__(canvas)
self.min = float('-inf')
self.max = float('inf')
self.attr = 'pagerank'
def onUpdateViewRect(self):
if self.attr in ['outdegree', 'indegree']:
shouldBeDrawn = lambda v: self.min <= getattr(v, self.attr)() <= self.max
else:
shouldBeDrawn = lambda v: False if v[self.attr] is None else self.min <= v[self.attr] <= self.max
canvas = self.canvas
toDraw = []
toHide = set()
for v in canvas.g.vs:
if shouldBeDrawn(v):
toDraw.append(v)
else:
toHide.add(v.index)
canvas.verticesToDraw = toDraw
toDraw = []
for e in canvas.g.es:
if not (e.source in toHide or e.target in toHide):
toDraw.append(e)
canvas.edgesToDraw = toDraw
def setFilter(self, attr, minValue, maxValue):
self.attr = attr
self.min = minValue
self.max = maxValue
|
C#
|
UTF-8
| 908 | 2.71875 | 3 |
[] |
no_license
|
public sealed class FacebookMapper : IMapper
{
private static readonly IEnumerable<FacebookUser> NullFacebookUsers =
Enumerable.Repeat(new FacebookUser(null), 1);
public IEnumerable<User> MapFrom(IEnumerable<User> users)
{
var facebookUsers = GetFacebookUsers(users).Concat(NullFacebookUsers);
return from user in users
join facebookUser in facebookUsers on
user.FacebookUid equals facebookUser.uid
select user.WithAvatar(facebookUser.pic_square);
}
private Facebook.user[] GetFacebookUsers(IEnumerable<User> users)
{
var uids = (from u in users
where u.FacebookUid != null
select u.FacebookUid.Value).ToList();
// return facebook users for uids using WCF
}
}
|
C#
|
UTF-8
| 2,790 | 2.578125 | 3 |
[] |
no_license
|
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace WebApplication1.ApiModel {
/// <summary>
///
/// </summary>
[DataContract]
public class ModificationPromotion {
/// <summary>
/// Bold flag: true, false, null
/// </summary>
/// <value>Bold flag: true, false, null</value>
[DataMember(Name="bold", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "bold")]
public bool? Bold { get; set; }
/// <summary>
/// DepartmentPage flag: true, false, null
/// </summary>
/// <value>DepartmentPage flag: true, false, null</value>
[DataMember(Name="departmentPage", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "departmentPage")]
public bool? DepartmentPage { get; set; }
/// <summary>
/// Emphasized flag: true, false, null
/// </summary>
/// <value>Emphasized flag: true, false, null</value>
[DataMember(Name="emphasized", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "emphasized")]
public bool? Emphasized { get; set; }
/// <summary>
/// EmphasizedHighlightBoldPackage flag: true, false, null
/// </summary>
/// <value>EmphasizedHighlightBoldPackage flag: true, false, null</value>
[DataMember(Name="emphasizedHighlightBoldPackage", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "emphasizedHighlightBoldPackage")]
public bool? EmphasizedHighlightBoldPackage { get; set; }
/// <summary>
/// Highlight flag: true, false, null
/// </summary>
/// <value>Highlight flag: true, false, null</value>
[DataMember(Name="highlight", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "highlight")]
public bool? Highlight { get; set; }
/// <summary>
/// Get the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString() {
var sb = new StringBuilder();
sb.Append("class ModificationPromotion {\n");
sb.Append(" Bold: ").Append(Bold).Append("\n");
sb.Append(" DepartmentPage: ").Append(DepartmentPage).Append("\n");
sb.Append(" Emphasized: ").Append(Emphasized).Append("\n");
sb.Append(" EmphasizedHighlightBoldPackage: ").Append(EmphasizedHighlightBoldPackage).Append("\n");
sb.Append(" Highlight: ").Append(Highlight).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Get the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson() {
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
}
}
|
Python
|
UTF-8
| 1,981 | 3.21875 | 3 |
[] |
no_license
|
#!/usr/bin/env python
import time
import threading
class Logger(object):
def __init__(self):
self.log_level = 0
self.observers = dict()
def log(self, log_message):
for name, lis in self.observers.items():
print("list name:", name)
for observer, level in lis:
if self.log_level >= level:
if name == "async":
threading.Thread(target=observer.log, args=(log_message,)).start()
else:
observer.log(log_message)
print()
def register_logger(self, log_backend, level):
self.__add_log_backend_to_observers_list(log_backend, level, 'sync')
def register_async_logger(self, log_backend, level):
self.__add_log_backend_to_observers_list(log_backend, level, 'async')
def __add_log_backend_to_observers_list(self, log_backend, level, observers_list_name):
if observers_list_name not in self.observers:
self.observers[observers_list_name] = []
self.observers[observers_list_name].append((log_backend, level))
def set_log_level(self, log_level):
self.log_level = log_level
class LogBackend(object):
def log(self, msg):
print(msg)
class NormalLogger(LogBackend):
def log(self, msg):
print("normal logger logging:", msg)
class DecoratedLogger(LogBackend):
def __init__(self, opening, closing):
self.opening = opening
self.closing = closing
def log(self, msg):
print(self.opening, msg, self.closing)
def main():
logger = Logger()
logger.set_log_level(1)
logger.register_logger(NormalLogger(), 1)
logger.register_async_logger(DecoratedLogger('[-', '-]'), 2)
logger.log(":D")
logger.log("segmentation fault! :D")
logger.set_log_level(2)
logger.log("undefined behavior")
logger.log("Another log")
time.sleep(1)
if __name__ == '__main__':
main()
|
Markdown
|
UTF-8
| 1,213 | 2.90625 | 3 |
[] |
no_license
|
## [**Long-term Recurrent Convolutional Networks for Visual Recognition and Description**](http://jeffdonahue.com/lrcn/)/[Code](http://www.eecs.berkeley.edu/~lisa_anne/LRCN_video) <br/>
They propose a <span style="color:red">*Long-term recurrent convolutional networks(LRCNs)*</span> which combines CNN and long-range temporal recursion and is end-to-end trainable.<br/>
<span style="color:red">Feature extraction: </span>Given visual inputs $v_t, t\in T$, first they use CNN to get feature transformation $\phi_V(v_t)$, where $V$ is the parameter of CNN network, to get a fixed-length vector representation $\phi_t \in R^d; <\phi_1, ..., \phi_T>$. <br/>
<span style="color:red">Sequence generation: </span> two layer LSTM map the input features to the output $z_t$, which $z_t=h_t$. And $h_1=f_W(x_1,h_0)=f_W(x_1,0)$, then $h_2=f_W(x_2,h_1)$, etc., up to $h_T$.<br/>
<span style="color:red">Final prediction: </span> Use softmax over the ouputs $z_t$. $P(y_t=c)=\frac{exp(W_{zc}z_{t,c}+b_c)}{\sum_{c1\in C}exp(W_{zc}z_{t,c`}+b_c)}$.<br/>
<span style="color:red">Objective function: </span> Minimize the negative log likelihood $L(V,W)=-logP_{V,W}(y_t|x_{1:t},y_{1:t-1})$ of the training data $(x,y)$.<br/>
|
TypeScript
|
UTF-8
| 37,579 | 2.9375 | 3 |
[] |
no_license
|
import Forth, { GetterSetter, HeaderFlags } from './Forth';
import ForthException from './ForthException';
const whitespaces = [' ', '\r', '\n', '\t'];
function isWhitespace(ch: string) {
return ch == ' ' || ch == '\r' || ch == '\n' || ch == '\t';
}
// TODO: turn into a primitive
function scan(f: Forth, ...until: string[]) {
const { sourceAddr, sourceLen, toIn } = ForthBuiltins;
let current = '';
while (toIn() < sourceLen()) {
const ch = String.fromCharCode(f.fetch8(sourceAddr() + toIn()));
toIn(toIn() + 1);
if (until.includes(ch)) return current;
current += ch;
}
if (current) return current;
}
function doPictureDigit(full: number, base: number) {
const digit = (full % base).toString(base);
const value = Math.floor(full / base);
return { value, char: digit.charCodeAt(0) };
}
function aligned(addr: number, mod: number) {
const offset = addr % mod;
return offset ? addr - offset + mod : addr;
}
// TODO: is this always correct?
function loopPassed(limit: number, index: number, step: number, orig: number) {
if (step > 0) {
return index >= limit && orig < limit;
} else {
return index < limit && orig >= limit;
}
}
const numberChars = '0123456789abcdefghijklmnopqrstuvwxyz';
function asNumber(
src: string,
base: number
): [value: number, left: number, double: boolean] {
if (src[0] === "'" && src[2] === "'") return [src.charCodeAt(1), 0, false];
var i = 0;
if (src[i] === '#') {
base = 10;
i++;
} else if (src[i] === '$') {
base = 16;
i++;
} else if (src[i] === '%') {
base = 2;
i++;
}
var negative = false;
if (src[i] === '-') {
negative = true;
i++;
}
var double = false;
var value = 0;
const avail = numberChars.slice(0, base);
const num = src.toLowerCase();
for (; i < src.length; i++) {
const ch = num[i];
const j = avail.indexOf(ch);
if (j >= 0) value = value * base + j;
else {
if (ch === '.' && i == src.length - 1) {
double = true;
break;
}
if (negative) value = -value;
return [value, src.length - i, double];
}
}
if (negative) value = -value;
return [value, 0, double];
}
export default class ForthBuiltins {
// TODO: remove the need for these; they prevent saving as binary
static base: GetterSetter<number>;
static picbuf: number;
static sourceAddr: GetterSetter<number>;
static sourceId: GetterSetter<number>;
static sourceLen: GetterSetter<number>;
static state: GetterSetter<number>;
static toPicbuf: GetterSetter<number>;
static toIn: GetterSetter<number>;
static wordbuf: number;
static async attach(f: Forth) {
const { IsHidden, IsImmediate, IsCompileOnly } = HeaderFlags;
ForthBuiltins.state = f.addVariable('state', 0);
ForthBuiltins.base = f.addVariable('base', 10);
ForthBuiltins.sourceAddr = f.addVariable('source-addr', 0);
ForthBuiltins.sourceId = f.addVariable('source-id', 0);
ForthBuiltins.sourceLen = f.addVariable('source-len', 0);
ForthBuiltins.toIn = f.addVariable('>in', 0);
f.here += f.options.holdsize;
ForthBuiltins.picbuf = f.here;
f.addConstant('picbuf', ForthBuiltins.picbuf, IsHidden);
ForthBuiltins.toPicbuf = f.addVariable(
'>picbuf',
ForthBuiltins.picbuf,
IsHidden
);
ForthBuiltins.wordbuf = f.here;
f.here += f.options.wordsize;
f.addConstant('false', 0);
f.addConstant('true', -1);
// some useful internals
f.addBuiltin('latestxt', this.latestxt);
f.addBuiltin('sp@', this.sptop);
f.addBuiltin('sp!', this.spstore);
f.addBuiltin('rp@', this.rptop);
f.addBuiltin('rp!', this.rpstore);
f.addBuiltin('rdrop', this.rdrop);
f.addBuiltin('2rdrop', this.rdrop2);
// --- nonstandard
f.addBuiltin('compile-only', this.compileonly);
f.addBuiltin('debug!', this.setdebug);
f.addBuiltin('s=', this.seq);
f.addBuiltin('(literal)', this.literalRt, IsHidden);
f.addBuiltin('(2literal)', this.literal2Rt, IsHidden);
f.addBuiltin('(sliteral)', this.sliteralRt, IsHidden);
f.addBuiltin('(branch)', this.branch, IsHidden);
f.addBuiltin('(branch0)', this.branch0, IsHidden);
f.addBuiltin('(do)', this.doRt, IsHidden);
f.addBuiltin('(loop)', this.loopRt, IsHidden);
f.addBuiltin('(+loop)', this.addloopRt, IsHidden);
// --- core
f.addBuiltin('!', this.store);
f.addBuiltin('#', this.picdigit);
f.addBuiltin('#>', this.picend);
f.addBuiltin('#s', this.picall);
f.addBuiltin("'", this.quote);
f.addBuiltin('(', this.comment, IsImmediate);
f.addBuiltin('*', this.mul);
f.addBuiltin('*/', this.muldiv);
f.addBuiltin('*/mod', this.muldivmod);
f.addBuiltin('+', this.add);
f.addBuiltin('+!', this.addstore);
f.addBuiltin('+loop', this.addloop, IsImmediate | IsCompileOnly);
f.addBuiltin(',', this.comma);
f.addBuiltin('-', this.sub);
f.addBuiltin('.', this.dot);
f.addBuiltin('."', this.dotquote);
f.addBuiltin('/', this.div);
f.addBuiltin('/mod', this.divmod);
f.addBuiltin('0<', this.zlt);
f.addBuiltin('0=', this.zeq);
f.addBuiltin('1+', this.inc);
f.addBuiltin('1-', this.dec);
f.addBuiltin('2!', this.store2);
f.addBuiltin('2*', this.mul2);
f.addBuiltin('2/', this.div2);
f.addBuiltin('2@', this.fetch2);
f.addBuiltin('2drop', this.drop2);
f.addBuiltin('2dup', this.dup2);
f.addBuiltin('2over', this.over2);
f.addBuiltin('2swap', this.swap2);
f.addBuiltin(':', this.colon);
f.addBuiltin(';', this.semicolon, IsImmediate | IsCompileOnly);
f.addBuiltin('<', this.lt);
f.addBuiltin('<#', this.picstart);
f.addBuiltin('=', this.eq);
f.addBuiltin('>', this.gt);
f.addBuiltin('>body', this.tobody);
f.addBuiltin('>number', this.toNumber);
f.addBuiltin('>r', this.tor);
f.addBuiltin('?dup', this.qdup);
f.addBuiltin('@', this.fetch);
f.addBuiltin('abort', this.abort);
f.addBuiltin('abort"', this.aborts);
f.addBuiltin('abs', this.abs);
f.addBuiltin('accept', this.accept);
f.addBuiltin('align', this.align);
f.addBuiltin('aligned', this.aligned);
f.addBuiltin('allot', this.allot);
f.addBuiltin('and', this.and);
f.addBuiltin('begin', this.begin, IsImmediate | IsCompileOnly);
f.addBuiltin('bl', this.bl);
f.addBuiltin('c!', this.cstore);
f.addBuiltin('c,', this.ccomma);
f.addBuiltin('c@', this.cfetch);
f.addBuiltin('cell+', this.cellp);
f.addBuiltin('cells', this.cells);
f.addBuiltin('char', this.char);
f.addBuiltin('char+', this.charp);
f.addBuiltin('chars', this.chars);
f.addBuiltin('count', this.count);
f.addBuiltin('cr', this.cr);
f.addBuiltin('create', this.create);
f.addBuiltin('decimal', this.decimal);
f.addBuiltin('depth', this.depth);
f.addBuiltin('do', this.do, IsImmediate | IsCompileOnly);
f.addBuiltin('does>', this.does);
f.addBuiltin('drop', this.drop);
f.addBuiltin('dup', this.dup);
f.addBuiltin('else', this.else, IsImmediate | IsCompileOnly);
f.addBuiltin('emit', this.emit);
f.addBuiltin('environment?', this.envq);
f.addBuiltin('evaluate', this.evaluate);
f.addBuiltin('execute', this.execute);
f.addBuiltin('exit', this.exit);
f.addBuiltin('fill', this.fill);
f.addBuiltin('find', this.find);
f.addBuiltin('fm/mod', this.fmmod);
f.addBuiltin('here', this.here);
f.addBuiltin('hold', this.hold);
f.addBuiltin('i', this.rpeek);
f.addBuiltin('if', this.if, IsImmediate | IsCompileOnly);
f.addBuiltin('immediate', this.immediate);
f.addBuiltin('invert', this.invert);
f.addBuiltin('j', this.rpeek2);
f.addBuiltin('key', this.key);
f.addBuiltin('leave', this.leave, IsImmediate | IsCompileOnly);
f.addBuiltin('literal', this.literal, IsImmediate | IsCompileOnly);
f.addBuiltin('loop', this.loop, IsImmediate | IsCompileOnly);
f.addBuiltin('lshift', this.lshift);
f.addBuiltin('m*', this.mmul);
f.addBuiltin('max', this.max);
f.addBuiltin('min', this.min);
f.addBuiltin('mod', this.mod);
f.addBuiltin('move', this.move);
f.addBuiltin('negate', this.negate);
f.addBuiltin('or', this.or);
f.addBuiltin('over', this.over);
f.addBuiltin('postpone', this.postpone, IsImmediate | IsCompileOnly);
// f.addBuiltin('quit', this.quit);
f.addBuiltin('r>', this.fromr);
f.addBuiltin('r@', this.rpeek);
f.addBuiltin('recurse', this.recurse, IsImmediate | IsCompileOnly);
f.addBuiltin('repeat', this.repeat, IsImmediate | IsCompileOnly);
f.addBuiltin('rot', this.rot);
f.addBuiltin('rshift', this.rshift);
f.addBuiltin('s"', this.squote, IsImmediate);
f.addBuiltin('s>d', this.stod);
f.addBuiltin('sign', this.picsign);
f.addBuiltin('sm/rem', this.smrem);
f.addBuiltin('source', this.source);
f.addBuiltin('space', this.space);
f.addBuiltin('spaces', this.spaces);
f.addBuiltin('swap', this.swap);
f.addBuiltin('then', this.then, IsImmediate | IsCompileOnly);
f.addBuiltin('type', this.type);
f.addBuiltin('u.', this.udot);
f.addBuiltin('u<', this.ult);
f.addBuiltin('um*', this.ummul);
f.addBuiltin('um/mod', this.ummod);
f.addBuiltin('unloop', this.rdrop2);
f.addBuiltin('until', this.until, IsImmediate | IsCompileOnly);
f.addBuiltin('while', this.while, IsImmediate | IsCompileOnly);
f.addBuiltin('word', this.word);
f.addBuiltin('xor', this.xor);
f.addBuiltin('[', this.interpretMode, IsImmediate | IsCompileOnly);
f.addBuiltin(']', this.compileMode);
await f.runString(": ['] ' postpone literal ; immediate compile-only");
await f.runString(
': [char] char postpone literal ; immediate compile-only'
);
await f.runString(': nop ;');
await f.runString(': constant create , does> @ ;');
await f.runString(': variable create 0 , ;');
// --- core-ext
// f.addBuiltin('.(', this.dotbracket);
// f.addBuiltin('.r', this.dotr);
f.addBuiltin('0<>', this.zne);
f.addBuiltin('0>', this.zgt);
f.addBuiltin('2>r', this.dtor);
f.addBuiltin('2r>', this.dfromr);
f.addBuiltin('2r@', this.drpeek);
// f.addBuiltin(':noname', this.noname);
f.addBuiltin('<>', this.ne);
// f.addBuiltin('?do', this.qdo);
// f.addBuiltin('action-of', this.actionof);
// f.addBuiltin('again', this.again);
await f.runString(': buffer: create allot ;');
// f.addBuiltin('c"', this.cquote);
// f.addBuiltin('case', this.case);
// f.addBuiltin('compile,', this.compile);
// f.addBuiltin('defer', this.defer);
// f.addBuiltin('defer!', this.deferstore);
// f.addBuiltin('defer@', this.deferfetch);
// f.addBuiltin('endcase', this.endcase);
// f.addBuiltin('endof', this.endof);
// f.addBuiltin('erase', this.erase);
// f.addBuiltin('false', this.false);
f.addBuiltin('hex', this.hex);
f.addBuiltin('holds', this.holds);
// f.addBuiltin('is', this.is);
// f.addBuiltin('marker', this.marker);
f.addBuiltin('nip', this.nip);
// f.addBuiltin('of', this.of);
// f.addBuiltin('pad', this.pad);
// f.addBuiltin('parse', this.parse);
// f.addBuiltin('parse-name', this.parsename);
// f.addBuiltin('pick', this.pick);
// f.addBuiltin('refill', this.refill);
// f.addBuiltin('restore-input', this.restoreinput);
// f.addBuiltin('roll', this.roll);
// f.addBuiltin('s\\"', this.sbackquote);
// f.addBuiltin('save-input', this.saveinput);
// f.addBuiltin('to', this.to);
// f.addBuiltin('true', this.true);
// f.addBuiltin('tuck', this.tuck);
// f.addBuiltin('u.r', this.udotr);
// f.addBuiltin('u>', this.ugt);
f.addBuiltin('unused', this.unused);
// f.addBuiltin('value', this.value);
f.addBuiltin('within', this.within);
f.addBuiltin('\\', this.backslash, IsImmediate);
// --- double-number (incomplete list)
f.addBuiltin('2literal', this.literal2, IsImmediate | IsCompileOnly);
f.addBuiltin('d.', this.ddot);
f.addBuiltin('d=', this.deq);
await f.runString(': 2variable create 0 , 0 , ;');
// --- facility (incomplete list)
f.addBuiltin('at-xy', this.atxy);
f.addBuiltin('key?', this.keyq);
// --- programming-tools (incomplete list)
f.addBuiltin('.s', this.showstack);
f.addBuiltin('words', this.words);
}
static dup(f: Forth) {
const x = f.stack.top();
f.stack.push(x);
}
static qdup(f: Forth) {
const x = f.stack.top();
if (x) f.stack.push(x);
}
static dup2(f: Forth) {
const x2 = f.stack.top(1);
const x1 = f.stack.top();
f.stack.push(x1);
f.stack.push(x2);
}
static drop(f: Forth) {
f.stack.pop();
}
static drop2(f: Forth) {
f.stack.pop();
f.stack.pop();
}
static swap(f: Forth) {
const x2 = f.stack.pop();
const x1 = f.stack.pop();
f.stack.push(x2);
f.stack.push(x1);
}
static swap2(f: Forth) {
const x4 = f.stack.pop();
const x3 = f.stack.pop();
const x2 = f.stack.pop();
const x1 = f.stack.pop();
f.stack.push(x3);
f.stack.push(x4);
f.stack.push(x1);
f.stack.push(x2);
}
static add(f: Forth) {
const n2 = f.stack.pop();
const n1 = f.stack.pop();
f.stack.push(n1 + n2);
}
static sub(f: Forth) {
const n2 = f.stack.pop();
const n1 = f.stack.pop();
f.stack.push(n1 - n2);
}
static comma(f: Forth) {
const x = f.stack.pop();
f.write(x);
}
static ccomma(f: Forth) {
const c = f.stack.pop();
f.write8(c);
}
static fetch(f: Forth) {
const aaddr = f.stack.pop();
f.stack.push(f.fetch(aaddr));
}
static cfetch(f: Forth) {
const aaddr = f.stack.pop();
f.stack.push(f.fetch8(aaddr));
}
static fetch2(f: Forth) {
const aaddr = f.stack.pop();
f.stack.pushd(f.fetchd(aaddr));
}
static store(f: Forth) {
const aaddr = f.stack.pop();
const x = f.stack.pop();
f.store(aaddr, x);
}
static cstore(f: Forth) {
const aaddr = f.stack.pop();
const x = f.stack.pop();
f.store8(aaddr, x);
}
static store2(f: Forth) {
const aaddr = f.stack.pop();
const d = f.stack.popd();
f.stored(aaddr, d);
}
static addstore(f: Forth) {
const aaddr = f.stack.pop();
const x = f.stack.pop();
f.store(aaddr, f.fetch(aaddr) + x);
}
static emit(f: Forth) {
const c = f.stack.pop();
f.options.output.emit(String.fromCharCode(c));
}
static count(f: Forth) {
const caddr = f.stack.pop();
f.stack.push(caddr + f.options.cellsize);
f.stack.push(f.fetch(caddr));
}
static type(f: Forth) {
const u = f.stack.pop();
const caddr = f.stack.pop();
const str = f.readString(caddr, u);
f.options.output.type(str);
}
static cr(f: Forth) {
f.options.output.cr();
}
static mul(f: Forth) {
const n2 = f.stack.pop();
const n1 = f.stack.pop();
f.stack.push(n1 * n2);
}
static div(f: Forth) {
const n2 = f.stack.pop();
const n1 = f.stack.pop();
if (n2 == 0) return f.throw(ForthException.divzero, 'division by zero');
f.stack.push(n1 / n2);
}
static mod(f: Forth) {
const n2 = f.stack.pop();
const n1 = f.stack.pop();
if (n2 == 0) return f.throw(ForthException.divzero, 'division by zero');
f.stack.push(n1 % n2);
}
static muldiv(f: Forth) {
const n3 = f.stack.pop();
const n2 = f.stack.pop();
const n1 = f.stack.pop();
if (n3 == 0) return f.throw(ForthException.divzero, 'division by zero');
f.stack.push((n1 * n2) / n3);
}
static muldivmod(f: Forth) {
const n3 = f.stack.pop();
const n2 = f.stack.pop();
const n1 = f.stack.pop();
if (n3 == 0) return f.throw(ForthException.divzero, 'division by zero');
const product = n1 * n2;
f.stack.push(product % n3);
f.stack.push(product / n3);
}
static divmod(f: Forth) {
const n2 = f.stack.pop();
const n1 = f.stack.pop();
if (n2 == 0) return f.throw(ForthException.divzero, 'division by zero');
f.stack.push(n1 % n2);
f.stack.push(n1 / n2);
}
static and(f: Forth) {
const x2 = f.stack.pop();
const x1 = f.stack.pop();
f.stack.push(x1 & x2);
}
static or(f: Forth) {
const x2 = f.stack.pop();
const x1 = f.stack.pop();
f.stack.push(x1 | x2);
}
static xor(f: Forth) {
const x2 = f.stack.pop();
const x1 = f.stack.pop();
f.stack.push(x1 ^ x2);
}
static nip(f: Forth) {
const x2 = f.stack.pop();
f.stack.pop();
f.stack.push(x2);
}
static over(f: Forth) {
const x = f.stack.top(1);
f.stack.push(x);
}
static over2(f: Forth) {
const x2 = f.stack.top(2);
const x1 = f.stack.top(3);
f.stack.push(x1);
f.stack.push(x2);
}
static rot(f: Forth) {
const x3 = f.stack.pop();
const x2 = f.stack.pop();
const x1 = f.stack.pop();
f.stack.push(x2);
f.stack.push(x3);
f.stack.push(x1);
}
static depth(f: Forth) {
f.stack.push(f.stack.contents.length);
}
static within(f: Forth) {
const u3 = f.stack.pop();
const u2 = f.stack.pop();
const u1 = f.stack.pop();
f.stack.pushf(u2 <= u1 && u1 < u3);
}
static lt(f: Forth) {
const n2 = f.signed(f.stack.pop());
const n1 = f.signed(f.stack.pop());
f.stack.pushf(n1 < n2);
}
static ult(f: Forth) {
const n2 = f.stack.pop();
const n1 = f.stack.pop();
f.stack.pushf(n1 < n2);
}
static eq(f: Forth) {
const x2 = f.stack.pop();
const x1 = f.stack.pop();
f.stack.pushf(x1 == x2);
}
static deq(f: Forth) {
const d2 = f.stack.popd();
const d1 = f.stack.popd();
f.stack.pushf(d1 == d2);
}
static ne(f: Forth) {
const x2 = f.stack.pop();
const x1 = f.stack.pop();
f.stack.pushf(x1 != x2);
}
static gt(f: Forth) {
const n2 = f.signed(f.stack.pop());
const n1 = f.signed(f.stack.pop());
f.stack.pushf(n1 > n2);
}
static zlt(f: Forth) {
const n = f.signed(f.stack.pop());
f.stack.pushf(n < 0);
}
static zeq(f: Forth) {
const n = f.stack.pop();
f.stack.pushf(n == 0);
}
static zne(f: Forth) {
const n = f.stack.pop();
f.stack.pushf(n != 0);
}
static zgt(f: Forth) {
const n = f.signed(f.stack.pop());
f.stack.pushf(n > 0);
}
static tor(f: Forth) {
const x = f.stack.pop();
f.rstack.push(x);
}
static dtor(f: Forth) {
const d = f.stack.popd();
f.rstack.pushd(d);
}
static fromr(f: Forth) {
const x = f.rstack.pop();
f.stack.push(x);
}
static dfromr(f: Forth) {
const d = f.rstack.popd();
f.stack.pushd(d);
}
static rpeek(f: Forth) {
const x = f.rstack.top();
f.stack.push(x);
}
static rpeek2(f: Forth) {
const x = f.rstack.top(2);
f.stack.push(x);
}
static drpeek(f: Forth) {
const d = f.rstack.topd();
f.stack.pushd(d);
}
static dec(f: Forth) {
const x = f.stack.pop();
f.stack.push(x - 1);
}
static inc(f: Forth) {
const x = f.stack.pop();
f.stack.push(x + 1);
}
static atxy(f: Forth) {
const ny = f.stack.pop();
const nx = f.stack.pop();
f.options.output.goto(nx, ny);
}
static unused(f: Forth) {
f.stack.push(f.unused);
}
static async key(f: Forth) {
return f.options.input.key().then(
e => f.stack.push(e.code),
() => {
// TODO: throw?
f.stack.push(0);
}
);
}
static keyq(f: Forth) {
f.stack.pushf(f.options.input.keyq);
}
static throw(f: Forth) {
f.throw(f.signed(f.stack.pop()), 'throw');
}
static sptop(f: Forth) {
f.stack.push(f.stack.ptop);
}
static spstore(f: Forth) {
f.stack.p = f.stack.pop();
}
static rptop(f: Forth) {
f.stack.push(f.rstack.ptop);
}
static rpstore(f: Forth) {
f.rstack.p = f.stack.pop();
}
static here(f: Forth) {
f.stack.push(f.here);
}
static allot(f: Forth) {
f.here += f.signed(f.stack.pop());
}
static latestxt(f: Forth) {
f.stack.push(f.link + f.options.cellsize);
}
static async execute(f: Forth) {
await f.execute(f.stack.pop());
}
// TODO: this kinda sucks, still
static async evaluate(f: Forth) {
const {
base,
sourceAddr,
sourceLen,
sourceId,
state,
toIn,
} = ForthBuiltins;
sourceLen(f.stack.pop());
sourceAddr(f.stack.pop());
sourceId(-1);
toIn(0);
var current = '';
var exit = false;
const handle = async () => {
if (current) {
const lc = current.toLowerCase();
if (f.viswords[lc]) {
await f.xw(lc);
} else {
const [value, left, double] = asNumber(current, base());
if (left) {
f.throw(
ForthException.invalidnumber,
`invalid number: ${current} (in base ${base()})`
);
} else {
f.debug('number:', value);
double ? f.stack.pushd(value) : f.stack.push(value);
if (state())
double ? ForthBuiltins.literal2(f) : ForthBuiltins.literal(f);
}
}
if (f.exception) exit = true;
current = '';
}
};
while (toIn() < sourceLen()) {
const ch = String.fromCharCode(f.fetch8(sourceAddr() + toIn()));
toIn(toIn() + 1);
if (isWhitespace(ch)) {
await handle();
if (exit) break;
} else {
current += ch;
}
}
await handle();
sourceId(0);
}
static udot(f: Forth) {
const base = ForthBuiltins.base();
const value = f.stack.pop();
f.options.output.type(value.toString(base) + ' ');
}
static dot(f: Forth) {
const base = ForthBuiltins.base();
const value = f.signed(f.stack.pop());
f.options.output.type(value.toString(base) + ' ');
}
static ddot(f: Forth) {
const base = ForthBuiltins.base();
const value = f.stack.popd();
f.options.output.type(value.toString(base) + ' ');
}
static showstack(f: Forth) {
const base = ForthBuiltins.base();
f.options.output.type(`<${f.stack.contents.length.toString(base)}> `);
f.stack.contents.forEach(n =>
f.options.output.type(f.signed(n).toString(base) + ' ')
);
}
static dotquote(f: Forth) {
const result = scan(f, '"');
if (typeof result === 'string') {
f.options.output.type(result);
return;
}
// TODO
f.options.output.type('mismatched quote\n');
}
static source(f: Forth) {
const { sourceAddr, sourceLen } = ForthBuiltins;
f.stack.push(sourceAddr());
f.stack.push(sourceLen());
}
static quote(f: Forth) {
const result = scan(f, ...whitespaces);
if (typeof result === 'string') {
const xt = f.viswords[result.toLowerCase()];
if (!xt)
return f.throw(
ForthException.undefinedword,
`undefined word: ${result}`
);
f.stack.push(xt);
return;
}
// TODO
f.options.output.type("invalid use of '\n");
}
static postpone(f: Forth) {
const result = scan(f, ...whitespaces);
if (typeof result === 'string') {
const xt = f.viswords[result.toLowerCase()];
if (!xt)
return f.throw(
ForthException.undefinedword,
`undefined word: ${result}`
);
f.debug('compile:', result);
f.write(xt);
return;
}
// TODO
f.options.output.type('invalid use of postpone\n');
}
static comment(f: Forth) {
const result = scan(f, ')');
if (typeof result === 'string') return;
// TODO
f.options.output.type('mismatched (\n');
}
static words(f: Forth) {
const wdict = f.viswords;
f.options.output.type(Object.keys(wdict).join(' '));
}
static interpretMode(f: Forth) {
ForthBuiltins.state(0);
}
static compileMode(f: Forth) {
ForthBuiltins.state(1);
}
static literal(f: Forth) {
const x = f.stack.pop();
f.debug('compile: (literal)', x);
f.write(f.words['(literal)']);
f.write(x);
}
static literalRt(f: Forth) {
const value = f.fetch(f.ip);
f.ip += f.options.cellsize;
f.stack.push(value);
}
static literal2(f: Forth) {
const d = f.stack.popd();
f.debug('compile: (2literal)', d);
f.write(f.words['(2literal)']);
f.writed(d);
}
static literal2Rt(f: Forth) {
const d = f.fetchd(f.ip);
f.ip += f.options.cellsize * 2;
f.stack.pushd(d);
}
static exit(f: Forth) {
f.popIp();
}
static async colon(f: Forth) {
// parse-name header, ]
const result = scan(f, ...whitespaces);
if (typeof result === 'string') {
const name = result.toLowerCase();
f.debug('defining:', name);
f.header(name);
const cfa = f.here + f.options.cellsize;
f.write(cfa);
return ForthBuiltins.compileMode(f);
}
// TODO
f.options.output.type('no word???');
}
static async semicolon(f: Forth) {
// TODO: check cstack
// postpone exit [
const xt = f.words.exit;
f.debug('compile: exit');
f.write(xt);
ForthBuiltins.interpretMode(f);
}
static char(f: Forth) {
const result = scan(f, ...whitespaces);
if (typeof result === 'string') {
const value = result.charCodeAt(0);
f.stack.push(value);
return;
}
// TODO
f.options.output.type('no word???');
}
static immediate(f: Forth) {
const xt = f.link + f.options.cellsize;
f.store(xt, f.fetch(xt) | HeaderFlags.IsImmediate);
}
static compileonly(f: Forth) {
const xt = f.link + f.options.cellsize;
f.store(xt, f.fetch(xt) | HeaderFlags.IsCompileOnly);
}
static abs(f: Forth) {
const n = f.signed(f.stack.pop());
f.stack.push(n < 0 ? -n : n);
}
static bl(f: Forth) {
f.stack.push(' '.charCodeAt(0));
}
static decimal(f: Forth) {
ForthBuiltins.base(10);
}
static hex(f: Forth) {
ForthBuiltins.base(16);
}
static create(f: Forth) {
const result = scan(f, ...whitespaces);
if (typeof result === 'string') {
const name = result.toLowerCase();
f.debug('defining:', name);
f.here = aligned(f.here, f.options.cellsize);
f.header(name, HeaderFlags.IsCreate);
const xt = f.words.nop;
const winfo = f.wordinfo(xt);
f.debug(`${name} does> nop`);
f.write(winfo.dfa);
return;
}
// TODO
f.options.output.type('no word???');
}
static does(f: Forth) {
const xt = f.link + f.options.cellsize;
const winfo = f.wordinfo(xt);
f.debug(`${winfo.name} does> ${f.ip}`);
f.store(winfo.cfa, f.ip);
f.popIp();
}
static tobody(f: Forth) {
const xt = f.stack.pop();
const winfo = f.wordinfo(xt);
f.stack.push(winfo.dfa);
}
static picstart(f: Forth) {
const { picbuf, toPicbuf } = ForthBuiltins;
toPicbuf(picbuf);
}
static picend(f: Forth) {
const { picbuf, toPicbuf } = ForthBuiltins;
f.stack.popd();
const len = picbuf - toPicbuf();
f.stack.push(toPicbuf());
f.stack.push(len);
}
static picdigit(f: Forth) {
const { base, toPicbuf } = ForthBuiltins;
const value = f.stack.popd();
const offset = toPicbuf() - 1;
const result = doPictureDigit(value, base());
f.store8(offset, result.char);
toPicbuf(offset);
f.stack.pushd(result.value);
}
static picall(f: Forth) {
const { base, toPicbuf } = ForthBuiltins;
const b = base();
var value = f.stack.popd();
while (true) {
const offset = toPicbuf() - 1;
const result = doPictureDigit(value, b);
f.store8(offset, result.char);
toPicbuf(offset);
value = result.value;
if (!value) break;
}
f.stack.pushd(0);
}
static squote(f: Forth) {
const state = ForthBuiltins.state();
const result = scan(f, '"');
if (typeof result === 'string') {
f.debug('parsed:', result);
if (state) {
const xt = f.words['(sliteral)'];
f.debug('compiling: (sliteral)', result);
f.write(xt);
}
const addr = f.writeString(result);
if (!state) {
f.stack.push(addr);
f.stack.push(result.length);
}
return;
}
// TODO
f.options.output.type('invalid used of "\n');
}
static sliteralRt(f: Forth) {
const length = f.fetch(f.ip);
const addr = f.ip + f.options.cellsize;
f.stack.push(addr);
f.stack.push(length);
f.ip += f.options.cellsize + length;
}
static cellp(f: Forth) {
f.stack.push(f.stack.pop() + f.options.cellsize);
}
static cells(f: Forth) {
f.stack.push(f.stack.pop() * f.options.cellsize);
}
static charp(f: Forth) {
f.stack.push(f.stack.pop() + 1);
}
static chars() {}
static seq(f: Forth) {
const len2 = f.stack.pop();
const addr2 = f.stack.pop();
const len1 = f.stack.pop();
const addr1 = f.stack.pop();
if (len1 !== len2) f.stack.pushf(false);
else {
const str1 = f.readString(addr1, len1);
const str2 = f.readString(addr2, len2);
f.stack.pushf(str1 === str2);
}
}
static hold(f: Forth) {
const { toPicbuf } = ForthBuiltins;
const char = f.stack.pop();
const addr = toPicbuf() - 1;
f.store8(addr, char);
toPicbuf(addr);
}
static holds(f: Forth) {
const { toPicbuf } = ForthBuiltins;
const len = f.stack.pop();
const src = f.stack.pop();
const str = f.readString(src, len);
const addr = toPicbuf() - len;
for (var i = 0; i < len; i++) f.store8(addr + i, str.charCodeAt(i));
toPicbuf(addr);
}
static picsign(f: Forth) {
const { toPicbuf } = ForthBuiltins;
const val = f.signed(f.stack.pop());
if (val < 0) {
const addr = toPicbuf() - 1;
f.store8(addr, 45); // '-'
toPicbuf(addr);
}
}
static abort(f: Forth) {
return f.throw(ForthException.abort, 'abort');
}
static aborts(f: Forth) {
const result = scan(f, '"');
if (typeof result === 'string') {
f.debug('parsed:', result);
return f.throw(ForthException.aborts, result);
}
// TODO
f.options.output.type('invalid used of "\n');
}
static align(f: Forth) {
f.here = aligned(f.here, f.options.cellsize);
}
static aligned(f: Forth) {
const val = f.stack.pop();
f.stack.push(aligned(val, f.options.cellsize));
}
static space(f: Forth) {
f.options.output.emit(' ');
}
static spaces(f: Forth) {
const amount = f.signed(f.stack.pop());
for (var i = 0; i < amount; i++) f.options.output.emit(' ');
}
static fill(f: Forth) {
const char = f.stack.pop();
const len = f.signed(f.stack.pop());
const addr = f.stack.pop();
for (var i = 0; i < len; i++) f.store8(addr + i, char);
}
static max(f: Forth) {
const n2 = f.stack.pop();
const n1 = f.stack.pop();
f.stack.push(Math.max(n1, n2));
}
static min(f: Forth) {
const n2 = f.stack.pop();
const n1 = f.stack.pop();
f.stack.push(Math.min(n1, n2));
}
static negate(f: Forth) {
f.stack.push(-f.signed(f.stack.pop()));
}
static invert(f: Forth) {
f.stack.push(~f.stack.pop());
}
static recurse(f: Forth) {
const xt = f.link + f.options.cellsize;
f.debug('compile:', f.wordinfo(xt).name);
f.write(xt);
}
static setdebug(f: Forth) {
const x = f.stack.pop();
f.options.debug = x !== 0;
}
static begin(f: Forth) {
f.cstack.push(f.here);
f.debug('dest:', f.here);
}
static branch(f: Forth) {
f.ip = f.fetch(f.ip);
}
static branch0(f: Forth) {
const x = f.stack.pop();
const dest = f.fetch(f.ip);
if (x) f.ip += f.options.cellsize;
else {
// f.debug('branch0 passed test');
f.ip = dest;
}
}
// TODO: refactor to primitives
static until(f: Forth) {
const dest = f.cstack.pop();
const xt = f.words['(branch0)'];
f.debug('compile: (branch0)', dest);
f.write(xt);
f.write(dest);
}
// TODO: refactor to primitives
static while(f: Forth) {
const dest = f.cstack.pop();
const xt = f.words['(branch0)'];
f.debug('compile: (branch0)', '???');
f.write(xt);
const orig = f.here;
f.write(-1);
f.debug('orig:', orig);
f.cstack.push(orig);
// f.debug('dest:', dest);
f.cstack.push(dest);
}
// TODO: refactor to primitives
static repeat(f: Forth) {
const dest = f.cstack.pop();
const orig = f.cstack.pop();
const xt = f.words['(branch)'];
f.debug('compile: (branch)', dest);
f.write(xt);
f.write(dest);
f.debug('resolve:', orig, f.here);
f.store(orig, f.here);
}
// TODO: refactor to primitives
static if(f: Forth) {
const xt = f.words['(branch0)'];
f.debug('compile: (branch0)', '???');
f.write(xt);
const orig = f.here;
f.write(-1);
f.debug('orig:', orig);
f.cstack.push(orig);
}
// TODO: refactor to primitives
static else(f: Forth) {
const xt = f.words['(branch)'];
f.debug('compile: (branch)', '???');
f.write(xt);
const orig = f.here;
f.write(-1);
const old = f.cstack.pop();
f.debug('resolve:', old, f.here);
f.store(old, f.here);
f.debug('orig:', orig);
f.cstack.push(orig);
}
// TODO: refactor to primitives
static then(f: Forth) {
const orig = f.cstack.pop();
f.debug('resolve:', orig, f.here);
f.store(orig, f.here);
}
static mul2(f: Forth) {
const x = f.stack.pop();
f.stack.push(x << 1);
}
static lshift(f: Forth) {
const u = f.stack.pop();
const x = f.stack.pop();
f.stack.push(x << u);
}
static div2(f: Forth) {
const x = f.stack.pop();
f.stack.push(x >> 1);
}
static rshift(f: Forth) {
const u = f.stack.pop();
const x = f.stack.pop();
f.stack.push(x >> u);
}
static envq(f: Forth) {
const len = f.stack.pop();
const addr = f.stack.pop();
const str = f.readString(addr, len).toUpperCase();
if (f.environment[str]) {
f.environment[str].forEach(n => f.stack.push(n));
f.stack.push(-1);
} else f.stack.push(0);
}
static stod(f: Forth) {
const x = f.signed(f.stack.top());
f.stack.push(x < 0 ? -1 : 0);
}
// TODO: incorrect (see tests)
static fmmod(f: Forth) {
const n = f.signed(f.stack.pop());
const d = f.signedd(f.stack.popd());
if (n == 0) return f.throw(ForthException.divzero, 'division by zero');
const div = Math.floor(d / n);
const rem = d % n;
f.stack.push(rem);
f.stack.push(div);
}
static ummod(f: Forth) {
const u = f.stack.pop();
const ud = f.stack.popd();
if (u == 0) return f.throw(ForthException.divzero, 'division by zero');
const div = Math.floor(ud / u);
const rem = ud % u;
f.stack.push(rem);
f.stack.push(div);
}
// TODO: incorrect (see tests)
static smrem(f: Forth) {
const n = f.signed(f.stack.pop());
const d = f.signedd(f.stack.popd());
if (n == 0) return f.throw(ForthException.divzero, 'division by zero');
const div = Math.floor(d / n);
const rem = d % n;
f.stack.push(rem);
f.stack.push(div);
}
static mmul(f: Forth) {
const n2 = f.signed(f.stack.pop());
const n1 = f.signed(f.stack.pop());
const d = n1 * n2;
f.stack.pushd(d);
}
static ummul(f: Forth) {
const u2 = f.stack.pop();
const u1 = f.stack.pop();
const d = u1 * u2;
f.stack.pushd(d);
}
static move(f: Forth) {
const len = f.signed(f.stack.pop());
const dst = f.stack.pop();
const src = f.stack.pop();
if (len > 0) {
const data: number[] = [];
for (var i = 0; i < len; i++) data.push(f.fetch8(src + i));
for (var i = 0; i < len; i++) f.store8(dst + i, data[i]);
}
}
static accept(f: Forth) {
const maxlen = f.signed(f.stack.pop());
const addr = f.stack.pop();
if (maxlen <= 0) f.stack.push(0);
else
return new Promise<void>(async (resolve, reject) => {
var i = 0;
while (true) {
const e = await f.options.input.key();
if (e.key === 'Enter') {
f.stack.push(i);
return resolve();
}
f.store8(addr + i, e.code);
i++;
if (i >= maxlen) {
f.stack.push(i);
return resolve();
}
}
});
}
static do(f: Forth) {
const xt = f.words['(do)'];
f.debug('compile: (do)');
f.write(xt);
f.cstack.push(f.here);
f.debug('dest:', f.here);
// number of LEAVEs
// TODO: should this really use the data stack?
f.stack.push(0);
}
static doRt(f: Forth) {
const index = f.stack.pop();
const limit = f.stack.pop();
f.rstack.push(limit);
f.rstack.push(index);
}
static loop(f: Forth) {
const xt = f.words['(loop)'];
f.debug('compile: (loop)');
f.write(xt);
const dest = f.cstack.pop();
const xt2 = f.words['(branch0)'];
f.debug('compile: (branch0)', dest);
f.write(xt2);
f.write(dest);
ForthBuiltins.resolveLeave(f);
}
static leave(f: Forth) {
const xt = f.words['2rdrop'];
f.debug('compile: 2rdrop');
f.write(xt);
const xt2 = f.words['(branch)'];
f.debug('compile: (branch)', '???');
f.write(xt2);
// TODO: should this really use the data stack?
const count = f.stack.pop();
f.stack.push(f.here);
f.stack.push(count + 1);
f.write(-1);
}
// TODO: should this really use the data stack?
static resolveLeave(f: Forth) {
const count = f.stack.pop();
for (var i = 0; i < count; i++) {
const orig = f.stack.pop();
f.debug('resolve:', orig, f.here);
f.store(orig, f.here);
}
}
// TODO: this code kinda sucks
static loopRt(f: Forth) {
const orig = f.rstack.pop();
const limit = f.rstack.top();
f.rstack.push(orig + 1);
const index = f.rstack.top();
if (f.signed(index) === f.signed(limit)) {
f.rstack.popd();
f.stack.pushf(true);
} else {
f.stack.pushf(false);
}
}
// TODO: resolve LEAVEs
static addloop(f: Forth) {
const xt = f.words['(+loop)'];
f.debug('compile: (+loop)');
f.write(xt);
const dest = f.cstack.pop();
const xt2 = f.words['(branch0)'];
f.debug('compile: (branch0)', dest);
f.write(xt2);
f.write(dest);
ForthBuiltins.resolveLeave(f);
}
// TODO: this code kinda sucks
static addloopRt(f: Forth) {
const step = f.stack.pop();
const orig = f.rstack.pop();
const limit = f.rstack.top();
f.rstack.push(orig + step);
const index = f.rstack.top();
if (loopPassed(limit, index, f.signed(step), orig)) {
f.rstack.popd();
f.stack.pushf(true);
} else {
f.stack.pushf(false);
}
}
static rdrop(f: Forth) {
f.rstack.pop();
}
static rdrop2(f: Forth) {
f.rstack.popd();
}
static find(f: Forth) {
const caddr = f.stack.pop();
const str = f.readString(caddr + f.options.cellsize, f.fetch(caddr));
const xt = f.viswords[str.toLowerCase()];
if (xt) {
const winfo = f.wordinfo(xt);
f.stack.push(xt);
f.stack.push(winfo.flags & HeaderFlags.IsImmediate ? 1 : -1);
} else {
f.stack.push(caddr);
f.stack.push(0);
}
}
static word(f: Forth) {
const x = f.stack.pop();
const ch = String.fromCharCode(x);
const result = scan(f, ch, '\n');
const caddr = ForthBuiltins.wordbuf;
if (result) f.writeStringAt(caddr, result.slice(0, f.options.wordsize));
else f.writeStringAt(caddr, '');
f.stack.push(caddr);
}
// TODO: can I reuse asNumber? this is much stricter
static toNumber(f: Forth) {
const { base } = ForthBuiltins;
const len = f.stack.pop();
const addr = f.stack.pop();
var value = f.stack.popd();
const src = f.readString(addr, len).toLowerCase();
var i = 0;
const available = numberChars.slice(0, base());
for (; i < src.length; i++) {
const ch = src[i];
const j = available.indexOf(ch);
if (j >= 0) value = value * base() + j;
else break;
}
f.stack.pushd(value);
f.stack.push(addr + i);
f.stack.push(src.length - i);
}
static backslash(f: Forth) {
scan(f, '\n');
}
}
|
Java
|
UTF-8
| 2,843 | 3.59375 | 4 |
[] |
no_license
|
package package55;
/**
* @ClassName Sequence
* @Description TODO
* @Author tanwenwei
* @Date 2019/4/23 21:28
* @Version 1.0
*/
interface Selector {
boolean end();
Object current();
void next();
Sequence getSeq();
}
public class Sequence {
private Object[] items;
private int next = 0;
public Sequence(int size) {
items = new Object[size];
}
public void add(Object x) {
if (next < items.length) {
items[next++] = x;
}
}
private class SequenceSelector implements Selector {
private int i = 0;
@Override
public boolean end() {
return i == items.length;
}
@Override
public Object current() {
return items[i];
}
@Override
public void next() {
if (i < items.length) {
i++;
}
}
@Override
public Sequence getSeq() {
return Sequence.this;
}
}
public Selector getSelector() {
return new SequenceSelector();
}
public static void main(String[] args) {
var sequence = new Sequence(10);
int a = (int) 'a';
for (var i = 0; i < 10; i++) {
sequence.add(new HasString("ab" + ((char) (a + i))));
}
var selector = sequence.getSelector();
System.out.println(sequence == selector.getSeq());
while (!selector.end()) {
System.out.println(selector.current() + " ");
selector.next();
}
}
}
class HasString {
private String str;
HasString(String str) {
this.str = str;
}
@Override
public String toString() {
return str;
}
}
class Test {
public static void main(String[] args) {
var seq = new Sequence(10);
seq.add(1);
Selector selector = seq.getSelector();
System.out.println(selector.current());
var objs = new Object[10];
objs[0] = 1;
}
}
interface InnerInterface {
void method();
}
class Outer {
private class Inner implements InnerInterface {
@Override
public void method() {
}
}
InnerInterface getInner() {
return new Inner();
}
}
class TestOutAndInner {
public static void main(String[] args) {
var outer = new Outer();
var inner = outer.getInner();
inner.method();
}
}
class NewOuter {
private String name;
NewOuter(String name) {
this.name = name;
}
class NewInner {
public String toString() {
return name;
}
}
}
class UseThis {
public static void main(String[] args) {
var o1 = new NewOuter("laotan");
var i1 = o1.new NewInner();
System.out.println(i1);
}
}
|
PHP
|
UTF-8
| 389 | 3.078125 | 3 |
[] |
no_license
|
<?php
namespace Voting\Domain;
use Voting\Exception\DomainException;
class Id
{
private $id;
public function __construct($id = null)
{
if (!is_null($id) && !is_integer($id)) {
throw new DomainException('Id should be an integer or null');
}
$this->id = $id;
}
public function value()
{
return (int) $this->id;
}
}
|
C#
|
UTF-8
| 1,754 | 2.578125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Bai_Tap_9
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
rbNam.Checked = true;
chkDangDiHoc.Checked = true;
}
private void btnHienThongTin_Click(object sender, EventArgs e)
{
String gioiTinh, tinhTrang;
if (rbNam.Checked == true)
gioiTinh = "Nam";
else
gioiTinh = "Nữ";
if (chkDangDiHoc.Checked == true && chkDangDiLam.Checked == true)
tinhTrang = "Vừa học vừa làm";
else if (chkDangDiHoc.Checked == true)
tinhTrang = "Đang đi học";
else
tinhTrang = "Đang đi làm";
MessageBox.Show("Họ tên: " + txtHoTen.Text + "\nGiới Tính: " + gioiTinh
+ "\nNgày sinh: " + dateTimePicker.Value.ToString("dd/MM/yyyy")
+ "\nĐịa chỉ: " + txtDiaChi.Text + "\nĐiện thoại: " + txtDienThoai.Text
+ "\nEmail: " + txtEmail.Text + "\nTình trạng: " + tinhTrang);
}
private void btnThoat_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Do you want to exit", "Câu hỏi", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.OK)
Application.Exit();
}
}
}
|
Markdown
|
UTF-8
| 4,448 | 3.875 | 4 |
[] |
no_license
|
# 灵活的语言——JavaScript
需求:实现一个验证表单功能的任务,内容不多,仅需要验证用户名、邮箱、密码等。
## 1.1 入职第一天
```javascript
function checkName() {
//验证用户名
}
function checkEmail() {
//验证邮箱
}
function checkPassword() {
//验证密码
}
```
>> 缺点:创建了很多全局变量,团队开发中,如果别人也定义了同样的方法就会覆盖掉原有的功能,如果定义了很多方法,这种互相覆盖的问题很不容易被察觉。
>> 解决:可以将他们放在一个变量里保存,可以减少覆盖和被覆盖的风险,一旦被覆盖,所有功能都会失效,这种现象很明显,容易被察觉到。
## 1.2 用对象收编变量
```javascript
var checkObject = {
checkName : function() {
//验证姓名
},
checkEmail : function(){
//验证邮箱
},
checkPassword : function() {
//验证密码
}
}
checkObject.checkName();
```
## 1.3 对象的另外一种形式
```javascript
var checkObject = function(){};
checkObject.checkName = function(){};
checkObject.checkEmail = function(){};
checkObject.checkPassword = function(){};
```
>> 缺点:虽然满足了需求,但是当别人想用这个对象方法时就有写麻烦了,因为对象不能复制一份,或者这个对象类在用**new**关键字创建新的对象时,新创建的对象是不能继承这些方法的。
## 1.4 真假对象
```javascript
var CheckObject = function() {
return {
checkName:function(){},
checkEmail:function(){},
checkPassword:function(){}
}
}
var a = CheckObject();
a.checkEmail();
```
当每次调用这个函数的时候,把我们之前写的对象返回回来,当别人每次调用这个函数时,都返回一个新对象,这样每个人在使用时就互相不影响了。
>> 缺点:虽然通过创建了新对象完成了我们的需求,但是它不是一个真正意义上类的创建方式,并且创建的对象a和对象CheckObject没有任何关系。
## 1.5 类也可以
```javascript
var CheckObject = function(){
this.checkName = function(){};
this.checkEmail = function(){};
this.checkpassword = function(){};
}
var a = new CheckObject();
a.checkName();
```
>> 缺点:把所有的方法放在函数的内部,通过this定义的,所以每一次通过new关键字穿件新对象的时候,新创建的对象都会对类的this上的属性进行复制。所以这些新创建的对象都会有自己的一套方法,然而有时候这么做造成的消耗是很奢侈的。
## 1.6 一个检测类
```javascript
var CheckObject = function(){};
CheckObject.prototype.checkName = function();
CheckObject.prototype.checkEmail = function();
CheckObject.prototype.checkPassword = function();
```
或者:
```javascript
var CheckObject = function(){};
CheckObject.prototype = {
checkName:function(){},
checkWEmail:function(){},
checkPassword:function(){}
}
var a= new CheckObject();
a.checkName();
a.checkEmail();
a.checkPassword();
```
>> 缺点:调用了三个方法,对象a书写了三遍,可以在书写的方法末尾将当前的对象返回。
## 1.7 方法还可以这样用
```javascript
var CheckObject = {
checkName:function (){
//验证姓名
return this;
},
checkEmail:function(){
return this;
},
checkPassword:function(){
return this;
}
}
CheckObject.checkName().checkEmail().checkPassword();
```
或者:
```javascript
var CheckObject = function(){};
CheckObject.prototype = {
checkName:function(){ return this;},
checkWEmail:function(){ return this;},
checkPassword:function(){ return this;}
}
var a= new CheckObject();
a.checkName().checkEmail().checkPassword();
```
## 1.8 函数的祖先
如果想给每个函数都添加一个检测邮箱的方法可以这样做:
```javascript
Function.prototype.checkEmail = function();
var f = function (){};
f.checkEmail;
var f2 = new Function();
f2.checkEmail();
```
但是上述做法污染了原生对象Function,所以别人创建的函数也会被污染,造成不必要的开销,可以抽象出一个统一的添加方法的功能方法:
```javascript
Function.prototype.addMethod = function(name,fn){
this[name] = fn;
}
var methods = new Function();
methods.addMethod('checkName',function(){});
methods.checkName();
```
|
C#
|
UTF-8
| 3,618 | 2.796875 | 3 |
[] |
no_license
|
using Demon.Core.Domain;
namespace Demon.Report
{
public class Helpers
{
public static uint ReadULong(byte[] buf)
{
uint value = 0;
for(int x = 0; x < 4; ++x)
{
value <<= 8;
value += buf[x];
}
return value;
}
public static string ReadString(byte[] buf, int len)
{
string value = "";
for(int x = 0; x < len; ++x)
value += (char)buf[x];
return value;
}
/// <summary>
/// Map from source SourceType to ControlType.
/// </summary>
public static ControlType MapSourceTypeToControlType(ContentSourceType sourceType)
{
ControlType controlType = ControlType.None;
switch(sourceType)
{
case ContentSourceType.RadioButton: controlType = ControlType.RadioButton; break;
case ContentSourceType.Checkbox: controlType = ControlType.Checkbox; break;
case ContentSourceType.TextEntry: controlType = ControlType.TextEntry; break;
case ContentSourceType.StaticText: controlType = ControlType.StaticText; break;
case ContentSourceType.PhotoList: controlType = ControlType.PhotoList; break;
case ContentSourceType.MultiSelect: controlType = ControlType.MultiSelect; break;
case ContentSourceType.SingleSelect: controlType = ControlType.SingleSelect; break;
case ContentSourceType.Photo: controlType = ControlType.Photo; break;
case ContentSourceType.Form: controlType = ControlType.Form; break;
case ContentSourceType.Section: controlType = ControlType.Section; break;
case ContentSourceType.CalculationList: controlType = ControlType.CalculationList; break;
case ContentSourceType.Calculation: controlType = ControlType.Calculation; break;
case ContentSourceType.CalculationVariable: controlType = ControlType.CalculationVariable; break;
}
return controlType;
}
/// <summary>
/// Map from source ControlType to SourceType.
/// </summary>
public static ContentSourceType MapControlTypeToSourceType(ControlType controlType)
{
ContentSourceType sourceType = ContentSourceType.None;
switch(controlType)
{
case ControlType.RadioButton: sourceType = ContentSourceType.RadioButton; break;
case ControlType.Checkbox: sourceType = ContentSourceType.Checkbox; break;
case ControlType.TextEntry: sourceType = ContentSourceType.TextEntry; break;
case ControlType.StaticText: sourceType = ContentSourceType.StaticText; break;
case ControlType.PhotoList: sourceType = ContentSourceType.PhotoList; break;
case ControlType.MultiSelect: sourceType = ContentSourceType.MultiSelect; break;
case ControlType.SingleSelect: sourceType = ContentSourceType.SingleSelect; break;
case ControlType.Photo: sourceType = ContentSourceType.Photo; break;
case ControlType.Form: sourceType = ContentSourceType.Form; break;
case ControlType.Section: sourceType = ContentSourceType.Section; break;
case ControlType.CalculationList: sourceType = ContentSourceType.CalculationList; break;
case ControlType.Calculation: sourceType = ContentSourceType.Calculation; break;
case ControlType.CalculationVariable: sourceType = ContentSourceType.CalculationVariable; break;
}
return sourceType;
}
}
}
|
C
|
UTF-8
| 839 | 3.78125 | 4 |
[] |
no_license
|
#include <stdio.h>
#include <string.h>
#include <math.h>
int main()
{
FILE *handle = fopen("integers_output.txt", "w");
if (handle == NULL)
{
fprintf(stderr, "Fehler. Datei konnte nicht angelegt werden.");
return 1;
}
fprintf(stdout, "Geben Sie Ihren Text ein: \n");
char input[200];
while (input[0] != '\n')
{
fgets(input, 200, stdin);
int i = 0;
while (input[i] != '\0')
{
if (input[i] > 47 && input[i] < 58)
{
fprintf(handle, "%c", input[i]);
if (input[i + 1] < 48 || input[i + 1] > 57)
fprintf(handle, " ");
}
if (input[i] == '\n')
fprintf(handle, "\n");
i++;
fflush(handle);
}
}
fprintf(stdout, "Ende der Eingabe!\n");
fclose(handle);
return 0;
}
|
Java
|
UTF-8
| 2,101 | 2.828125 | 3 |
[
"Apache-2.0"
] |
permissive
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.shaman.terrain;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Sebastian Weiss
*/
public class HeightmapTest {
public HeightmapTest() {
}
@Test
public void testInterpolating() {
Heightmap map = new Heightmap(4);
for (int x=0; x<4; ++x) {
for (int y=0; y<4; ++y) {
map.setHeightAt(x, y, -10);
}
}
map.setHeightAt(1, 1, 0);
map.setHeightAt(1, 2, 1);
map.setHeightAt(2, 1, 2);
map.setHeightAt(2, 2, 3);
float e = 0.0001f;
float f = 0.000001f;
assertEquals(0, map.getHeightInterpolating(1, 1), e);
assertEquals(1, map.getHeightInterpolating(1, 2), e);
assertEquals(2, map.getHeightInterpolating(2, 1), e);
assertEquals(3, map.getHeightInterpolating(2, 2), e);
assertEquals(0, map.getHeightInterpolating(1+f, 1), e);
assertEquals(1, map.getHeightInterpolating(1+f, 2), e);
assertEquals(2, map.getHeightInterpolating(2+f, 1), e);
assertEquals(3, map.getHeightInterpolating(2+f, 2), e);
assertEquals(0, map.getHeightInterpolating(1-f, 1), e);
assertEquals(1, map.getHeightInterpolating(1-f, 2), e);
assertEquals(2, map.getHeightInterpolating(2-f, 1), e);
assertEquals(3, map.getHeightInterpolating(2-f, 2), e);
assertEquals(0, map.getHeightInterpolating(1, 1+f), e);
assertEquals(1, map.getHeightInterpolating(1, 2+f), e);
assertEquals(2, map.getHeightInterpolating(2, 1+f), e);
assertEquals(3, map.getHeightInterpolating(2, 2+f), e);
assertEquals(0, map.getHeightInterpolating(1, 1-f), e);
assertEquals(1, map.getHeightInterpolating(1, 2-f), e);
assertEquals(2, map.getHeightInterpolating(2, 1-f), e);
assertEquals(3, map.getHeightInterpolating(2, 2-f), e);
assertEquals(0.5, map.getHeightInterpolating(1, 1.5f), e);
assertEquals(1, map.getHeightInterpolating(1.5f, 1), e);
assertEquals(2, map.getHeightInterpolating(1.5f, 2), e);
assertEquals(2.5, map.getHeightInterpolating(2, 1.5f), e);
}
}
|
Java
|
UTF-8
| 186 | 1.8125 | 2 |
[] |
no_license
|
package winep.ir.contentcentricapp.Presenter.Observer;
/**
* Created by ShaisteS on 8/27/2016.
*/
public interface ObserverAudioPlayerListener {
void changeAudioPlayerStatus();
}
|
C#
|
UTF-8
| 4,668 | 2.671875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using Nofs.Net.AnnotationDriver;
using Nofs.Net.Common.Interfaces.Library;
namespace Nofs.Net.nofs_addressbook
{
[RootFolderObject]
[Serializable]
public class Book
{
private IDomainObjectContainer _bookContainer;
private IDomainObjectContainerManager _containerManager;
public Book()
{
#if (DEBUG)
_names.Add(Guid.NewGuid().ToString());
#endif
Information = new BookInfo();
}
#region only for test
private List<string> _names = new List<string>();
[DomainObject]
public string[] Names
{
get
{
return _names.ToArray();
}
}
public IList<string> AliasName
{
get
{
return _names;
}
}
#endregion
[NeedsContainer]
public IDomainObjectContainer Container
{
get
{
return _bookContainer;
}
set
{
_bookContainer = value;
}
}
[NeedsContainerManager]
public IDomainObjectContainerManager ContainerManager
{
get
{
if (_containerManager == null)
{
throw new System.Exception("container manager is null");
}
return _containerManager;
}
set
{
_containerManager = value;
}
}
private IDomainObjectContainer CategoryDomainObjectContainer
{
get
{
return ContainerManager.GetContainer(typeof(Category));
}
}
public IEnumerable<Category> Categories
{
[FolderObject]
get
{
foreach (Category item in CategoryDomainObjectContainer.GetAllInstances<Category>())
{
yield return item;
}
}
}
private IDomainObjectContainer ContactDomainObjectContainer
{
get
{
return ContainerManager.GetContainer(typeof(Contact));
}
}
[FolderObject]
public IEnumerable<Contact> Contacts
{
get
{
foreach (Contact item in ContactDomainObjectContainer.GetAllInstances<Contact>())
{
yield return item;
}
}
}
[DomainObject]
public BookInfo Information
{
private set;
get;
}
[FolderObject(FolderOperatorObject.CanAdd | FolderOperatorObject.CanRemove)]
public IEnumerable<Contact> getFirstTenContacts()
{
return ContactDomainObjectContainer.GetAllInstances<Contact>().Take<Contact>(10);
}
public Contact SearchbyName(String name)
{
return Contacts.FirstOrDefault(item => item.Name == name);
}
[Executable]
public Contact AddAContact(String name, String phone)
{
Contact contact = ContactDomainObjectContainer.NewPersistentInstance<Contact>();
contact.Name = name;
contact.PhoneNumber = phone;
_bookContainer.ObjectChanged(this);
return contact;
}
[Executable]
public void RemoveAContact(Contact contact)
{
if (contact != null)
{
ContactDomainObjectContainer.Remove(contact);
_bookContainer.ObjectChanged(this);
}
else
{
Console.WriteLine("Remove A Contact: failed!");
}
}
[Executable]
public Contact RenameAContact(Contact contact, String newName)
{
if (contact != null)
{
String oldName = contact.Name;
contact.Name = newName;
ContactDomainObjectContainer.ObjectRenamed(contact, oldName, newName);
ContactDomainObjectContainer.ObjectChanged(contact);
}
else
{
Console.WriteLine("Rename A Contact: failed!");
}
return contact;
}
}
}
|
PHP
|
UTF-8
| 5,645 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace App;
use App\Helpers\MeetAndCodeHelper;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
/**
* App\MeetAndCodeRSSItem
*
* @property int $id
* @property string $title
* @property string $description
* @property string $link
* @property string $pubDate
* @property string $organisation_mail
* @property string $school_name
* @property string $organisation_type
* @property string $activity_type
* @property string $country
* @property string $address
* @property string $organiser_website
* @property string $organiser_email
* @property string $image_link
* @property string $start_date
* @property string $end_date
* @property float $lat
* @property float $lon
* @property string|null $imported_at
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @method static \Illuminate\Database\Eloquent\Builder|MeetAndCodeRSSItem newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|MeetAndCodeRSSItem newQuery()
* @method static \Illuminate\Database\Eloquent\Builder|MeetAndCodeRSSItem query()
* @method static \Illuminate\Database\Eloquent\Builder|MeetAndCodeRSSItem whereActivityType($value)
* @method static \Illuminate\Database\Eloquent\Builder|MeetAndCodeRSSItem whereAddress($value)
* @method static \Illuminate\Database\Eloquent\Builder|MeetAndCodeRSSItem whereCountry($value)
* @method static \Illuminate\Database\Eloquent\Builder|MeetAndCodeRSSItem whereCreatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|MeetAndCodeRSSItem whereDescription($value)
* @method static \Illuminate\Database\Eloquent\Builder|MeetAndCodeRSSItem whereEndDate($value)
* @method static \Illuminate\Database\Eloquent\Builder|MeetAndCodeRSSItem whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder|MeetAndCodeRSSItem whereImageLink($value)
* @method static \Illuminate\Database\Eloquent\Builder|MeetAndCodeRSSItem whereImportedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|MeetAndCodeRSSItem whereLat($value)
* @method static \Illuminate\Database\Eloquent\Builder|MeetAndCodeRSSItem whereLink($value)
* @method static \Illuminate\Database\Eloquent\Builder|MeetAndCodeRSSItem whereLon($value)
* @method static \Illuminate\Database\Eloquent\Builder|MeetAndCodeRSSItem whereOrganisationMail($value)
* @method static \Illuminate\Database\Eloquent\Builder|MeetAndCodeRSSItem whereOrganisationType($value)
* @method static \Illuminate\Database\Eloquent\Builder|MeetAndCodeRSSItem whereOrganiserEmail($value)
* @method static \Illuminate\Database\Eloquent\Builder|MeetAndCodeRSSItem whereOrganiserWebsite($value)
* @method static \Illuminate\Database\Eloquent\Builder|MeetAndCodeRSSItem wherePubDate($value)
* @method static \Illuminate\Database\Eloquent\Builder|MeetAndCodeRSSItem whereSchoolName($value)
* @method static \Illuminate\Database\Eloquent\Builder|MeetAndCodeRSSItem whereStartDate($value)
* @method static \Illuminate\Database\Eloquent\Builder|MeetAndCodeRSSItem whereTitle($value)
* @method static \Illuminate\Database\Eloquent\Builder|MeetAndCodeRSSItem whereUpdatedAt($value)
* @mixin \Eloquent
*/
class MeetAndCodeRSSItem extends Model
{
public function getCountryIso()
{
switch ($this->country) {
case 'North Macedonia':
return 'MK';
case 'Italia':
return 'IT';
case 'Bosnia&Herzegovina':
return 'BA';
default:
return Country::where('name', 'like', $this->country)->first()->iso;
}
}
private function mapOrganisationTypes($organisation_type)
{
switch ($organisation_type) {
case "Non-Profit Organisation":
return "non profit";
default:
return "other";
}
}
private function mapActivityTypes($activity_type)
{
switch ($activity_type) {
case "offline and open":
return "open-in-person";
case "online and open":
return "open-online";
default:
return "other";
}
}
public function createEvent($user)
{
$event = new Event([
'status' => "APPROVED",
'title' => htmlspecialchars_decode($this->title),
'slug' => Str::slug($this->title),
'organizer' => $this->school_name,
'description' => $this->description,
'organizer_type' => $this->mapOrganisationTypes($this->organisation_type),
'activity_type' => $this->mapActivityTypes($this->activity_type),
'location' => $this->address,
'event_url' => $this->link,
'user_email' => $this->organiser_email,
'creator_id' => $user->id,
'country_iso' => $this->getCountryIso(),
'picture' => $this->image_link,
"pub_date" => now(),
"created" => now(),
"updated" => now(),
"codeweek_for_all_participation_code" => 'cw-meetcode',
"start_date" => $this->start_date,
"end_date" => $this->end_date,
"longitude" => $this->lon,
"latitude" => $this->lat,
"geoposition" => $this->lat . "," . $this->lon,
"language" => MeetAndCodeHelper::getLanguage($this->link)
]);
$event->save();
//Link Other as theme and audience
$event->audiences()->attach(8);
$event->themes()->attach(8);
return $event;
}
}
|
Python
|
UTF-8
| 838 | 2.75 | 3 |
[] |
no_license
|
import cv2
import numpy as np
img1 = cv2.imread('3D-Matplotlib.png')
img2 = cv2.imread('mainlogo.png')
rows,cols,channels = img2.shape
roi = img1[0:rows, 0:cols]
img2gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(img2gray, 220, 255, cv2.THRESH_BINARY_INV)
mask_inv = cv2.bitwise_not(mask)
img1_bg = cv2.bitwise_and(roi, roi, mask=mask_inv)
img2_fg = cv2.bitwise_and(img2, img2, mask=mask)
dst = cv2.add(img1_bg, img2_fg)
img1[0:rows, 0:cols] = dst
# add = img1 + img2
# (155, 211, 79) + (50, 170, 200) = 205, 381, 279...taranlated to (205, 255, 255)
# add = cv2.add(img1, img2)
# weighted = cv2.addWeighted(img1, 0.6, img2, 0.4, 0)
cv2.imshow('res', img1)
cv2.imshow('add', mask_inv)
cv2.imshow('add1', img1_bg)
cv2.imshow('add2', img2_fg)
cv2.imshow('ad3', dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
Go
|
UTF-8
| 425 | 3.234375 | 3 |
[] |
no_license
|
package util
type SimpleIDGenerator struct {
sequence chan int64
}
func NewSimpleIDGenerator() *SimpleIDGenerator {
ig := &SimpleIDGenerator{sequence: make(chan int64)}
go func() {
id := int64(1)
for {
ig.sequence <- id
if id == 0 {
continue
}
id++
}
}()
return ig
}
func (r *SimpleIDGenerator) NextID() (int64, bool) {
id := <-r.sequence
if id == 0 {
return 0, false
}
return id, true
}
|
C++
|
UTF-8
| 692 | 2.515625 | 3 |
[] |
no_license
|
///////////////////////////////////////////////////////////////////////
//
// Filename: Player.cpp
// Date: March 14, 2019
// Programmer: Daniel Posse
//
// Description:
// Player object, inherits from Character
//
///////////////////////////////////////////////////////////////////////
#include <SFML/Graphics.hpp>
#include "Player.h"
using namespace sf;
//Player::Player() : Player(20.f) {}
Player::Player(float radius) : Character(new CircleShape(20.f)) {}
void Player::move() {
} //end move
void Player::shoot() {
} //end shoot
|
C++
|
UTF-8
| 4,862 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
/**
* @file teleportState.h
* @brief スキル状態
*
* @author wem
* @date 2016.1.2
*/
#include "precompiled.h"
//! TeleportStateに遷移した瞬間にフレームレートを下げる
void TeleportState::setup(Player* player) {
currentAcc_ = g_local->FrameAcc();
g_local->SetFrameAcc(player->getReduce());
cursorPos_ = player->getPos();
cursorSize_ = player->getSize();
}
void TeleportState::handleInput(Player* player, StateManager* stateMgr, ofxJoystick& input) {
if (input.isRelease(Input::X)) {
player->setPos(cursorPos_);
g_local->SetFrameAcc(currentAcc_);
stateMgr->pop();
}
}
//! 移動先の指定だけはフレームレート変更の影響を受けないようになっています
void TeleportState::update(float deltaTime, Player* player, ofxJoystick& input) {
// スキル使用中の落下速度を一定の値にしてみる(試しに重力加速度の3倍に調整)
if (player->getVel().y < -(player->getGravity() * 3)) { player->setVel(ofVec2f(player->getVel().x, -(player->getGravity() * 3))); }
float sync = g_local->LastFrame() * ofGetFrameRate();
cursorPos_ += cursorVel_ * sync;
moveTelePos(player, input);
}
void TeleportState::draw(Player* player) {
auto p_pos = player->getPos();
auto p_size = player->getSize();
// スキルの有効範囲をPlayeの中心から円で表示
ofPushStyle();
ofPushMatrix();
ofNoFill();
ofSetColor(255, 255, 255);
ofDrawCircle((p_pos + (p_size / 2)), player->getTeleportCircle());
ofPopMatrix();
ofPopStyle();
// 移動先を四角形で表示
ofPushStyle();
ofPushMatrix();
ofNoFill();
ofSetColor(255, 255, 255);
ofDrawPlane(cursorPos_.x + cursorSize_.x / 2,
cursorPos_.y + cursorSize_.y,
cursorSize_.x, cursorSize_.y);
ofPopMatrix();
ofPopStyle();
}
/**
* @brief Brickとの当たり判定がないと落下するので、ここにもBrickを貫通しない処理を追加
* @note PlayerがActorに潰された場合の処理は不明なので後程追加します。
*/
void TeleportState::onCollision(Player* player, Actor* c_actor) {
// プレイヤーと衝突判定を行うオブジェクトの必要パラメータを取得
auto p_pos = player->getPos();
auto p_vel = player->getVel();
auto p_size = player->getSize();
auto c_pos = c_actor->getPos();
auto c_size = c_actor->getSize();
// Brick以外の物と判定しないように制限
if (c_actor->getTag() == BRICK) {
// Brickに上からぶつかったら加速度を0に(左右への移動量はそのまま)
// Brickの上にPlayerの位置を修正
if (p_pos.y + p_vel.y < c_pos.y + c_size.y &&
(p_pos.y + p_size.y / 3) - p_vel.y > c_pos.y + c_size.y &&
p_pos.x + (p_size.x / 10) <= c_pos.x + c_size.x &&
p_pos.x + p_size.x - (p_size.x / 10) >= c_pos.x &&
p_vel.y < 0) {
player->onFloor(true);
player->setVel(ofVec2f(p_vel.x, 0.0f));
player->setPos(ofVec2f(p_pos.x, c_pos.y + c_size.y));
}
// Playerの上辺がBrickの底辺とCollisionした場合
else if (p_pos.y + p_vel.y < c_pos.y &&
p_pos.y + p_size.y + p_vel.y > c_pos.y &&
p_pos.x < c_pos.x + c_size.x &&
p_pos.x + p_size.x > c_pos.x &&
p_vel.y >= 0) {
player->setVel(ofVec2f(p_vel.x, 0.0f));
player->setPos(ofVec2f(p_pos.x, c_pos.y - p_size.y));
}
// Playerの左辺がBrickの右辺とCollisionした場合
else if (p_pos.x < c_pos.x + c_size.x &&
p_pos.x + p_size.x > c_pos.x + c_size.x &&
p_pos.y - p_vel.y * 2 < c_pos.y + c_size.y &&
p_pos.y + p_size.y > c_pos.y) {
player->setVel(ofVec2f(0.0f, p_vel.y));
player->setPos(ofVec2f(c_pos.x + c_size.x, p_pos.y));
}
// Playerの右辺がBrickの左辺とCollisionした場合
else if (p_pos.x + p_size.x > c_pos.x &&
p_pos.x < c_pos.x &&
p_pos.y - p_vel.y * 2 < c_pos.y + c_size.y &&
p_pos.y + p_size.y > c_pos.y) {
player->setVel(ofVec2f(0.0f, p_vel.y));
player->setPos(ofVec2f(c_pos.x - p_size.x, p_pos.y));
}
}
}
// カーソルの移動処理
void TeleportState::moveTelePos(Player* player, ofxJoystick& input) {
// 左右への移動
if (input.isPushing(Input::Left) &&
cursorPos_.x >= 0) {
cursorVel_.x = -player->getCursorSpeed();
}
else if (input.isPushing(Input::Right) &&
cursorPos_.x + cursorSize_.x <= ofGetWindowWidth()) {
cursorVel_.x = player->getCursorSpeed();
}
else {
cursorVel_.x = 0.0f;
}
// 上下への移動
if (input.isPushing(Input::Down)) {
cursorVel_.y = -player->getCursorSpeed();
}
else if (input.isPushing(Input::Up)) {
cursorVel_.y = player->getCursorSpeed();
}
else {
cursorVel_.y = 0.0f;
}
}
|
Java
|
UTF-8
| 1,203 | 3.453125 | 3 |
[] |
no_license
|
package com.peter12.solution.medium;
public class MEDIUM_0165_COMPARE_VERSION_NUMBERS {
public static int compareVersion(String version1, String version2) {
String[] split1 = version1.split("\\.");
String[] split2 = version2.split("\\.");
int size = ( split1.length < split2.length )? split1.length : split2.length;
for( int i = 0; i < size; i++ ) {
Integer digit1 = Integer.valueOf( split1[i] );
Integer digit2 = Integer.valueOf( split2[i] );
if( digit1 > digit2 ) {
return 1;
} else if( digit1 < digit2 ) {
return -1;
}
}
if( split1.length == split2.length ) {
return 0;
} else {
String[] large = ( split1.length < split2.length )? split2 : split1;
for( int i = size; i < large.length; i++ ) {
Integer digit = Integer.valueOf( large[i] );
if( digit != 0 ) {
if( large == split1 ) {
return 1;
} else {
return -1;
}
}
}
return 0;
}
}
}
|
Java
|
UTF-8
| 1,730 | 3.234375 | 3 |
[] |
no_license
|
package com.grudnov.lessons.lesson22.hw3_4;
import java.util.function.Consumer;
import java.util.function.Predicate;
public class Application {
public static void main(String[] args) {
University university = new University();
university.addCourse(Course.getInstance());
university.addCourse(Course.getInstance());
university.addCourse(Course.getInstance());
university.addCourse(Course.getInstance());
university.addCourse(Course.getInstance());
Predicate<Course> getCoursesLessThreeMonths = (course)->course.getDuration() < 3;
Predicate<Course> getCoursesWithOptimalPrice = (course)->course.getPrice() < 20_000;
Predicate<Course> getCoursesByNameJJD = (course)->course.getName().equals("JJD");
Predicate<Course> getBestCourses = (course)->course.getDuration()<3 && course.getPrice() < 20_000 ;
Predicate<Course> getBestCourses2 = (course)->(course.getDuration()<3 && course.getPrice() < 20_000) ||
course.getName().equals("JJD");
Consumer<Course> incPriceByTen = (course)-> course.setPrice(course.getPrice() + 10_000);
System.out.println(university.getCourses());
//System.out.println(university.filtered(getCoursesLessThreeMonths));
//System.out.println(university.filtered(getCoursesWithOptimalPrice));
//System.out.println(university.filtered(getCoursesByNameJJD));
//System.out.println(university.filtered(getBestCourses));
//System.out.println(university.filtered(getBestCourses2));
for (Course course : university.getCourses()) {
incPriceByTen.accept(course);
}
System.out.println(university.getCourses());
}
}
|
Python
|
UTF-8
| 1,172 | 3.1875 | 3 |
[] |
no_license
|
import math
import os
import random
import re
import sys
# Complete the biggerIsGreater function below.
def biggerIsGreater(w):
alph = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
my_weight = []
for letter in w:
my_weight.append(alph.index(letter))
my_weight.reverse()
for i in range(0, len(my_weight) - 1):
if my_weight[i] > my_weight[i + 1]:
tmp = my_weight[0:i + 1]
for j, w in enumerate(tmp):
if my_weight[i + 1] < w:
my_weight[i + 1], tmp[j] = tmp[j], my_weight[i + 1]
break
tmp.sort()
for k in range(len(tmp)):
my_weight[i - k] = tmp[k]
break
else:
return 'no answer'
my_weight.reverse()
result = []
for weight in my_weight:
result.append(alph[weight])
result = ''.join(result)
return result
if __name__ == '__main__':
T = int(input())
for T_itr in range(T):
w = input()
result = biggerIsGreater(w)
print(result + '\n')
|
Java
|
UTF-8
| 6,486 | 3.28125 | 3 |
[] |
no_license
|
package collections.arraylist;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class MyListImpl implements MyList, ListIterable {
private static final Object[] EMPTY_ELEMENT_DATA = {};
private static final int DEFAULT_CAPACITY;
private final int capacity;
private int pointer;
private Object[] array;
static {
DEFAULT_CAPACITY = 10;
}
MyListImpl() {
this(0);
}
private MyListImpl(final int initialCapacity) {
if (initialCapacity > 0) {
this.array = new Object[initialCapacity];
capacity = initialCapacity;
} else if (initialCapacity == 0) {
this.array = EMPTY_ELEMENT_DATA;
capacity = DEFAULT_CAPACITY;
} else {
throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity);
}
}
MyListImpl(MyList list) {
pointer = list.size();
if (pointer != 0) {
array = list.toArray();
} else {
array = EMPTY_ELEMENT_DATA;
}
capacity = DEFAULT_CAPACITY;
}
@Override
public void add(Object obj) {
if (array == EMPTY_ELEMENT_DATA) {
init(capacity);
}
if (pointer >= array.length) {
resize(array.length + (array.length >> 1));
}
array[pointer++] = obj;
}
@Override
public Object get(int index) {
rangeCheck(index);
return array[index];
}
@Override
public void clear() {
array = EMPTY_ELEMENT_DATA;
init(capacity);
}
@Override
public boolean remove(Object obj) {
if (obj == null) {
for (int i = 0; i < pointer; i++) {
if (array[i] == null) {
rebuild(i);
return true;
}
}
} else {
for (int i = 0; i < pointer; i++) {
if (this.array[i].equals(obj)) {
rebuild(i);
return true;
}
}
}
return false;
}
@Override
public Object[] toArray() {
Object[] temp = new Object[size()];
System.arraycopy(array, 0, temp, 0, size());
return temp;
}
@Override
public int size() {
return pointer;
}
@Override
public boolean contains(Object obj) {
for (int i = 0; i < pointer; i++) {
if (array[i].equals(obj)) {
return true;
}
}
return false;
}
@Override
public boolean containsAll(MyList list) {
for (int i = 0; i < list.size(); i++) {
if (!contains(list.get(i))) {
return false;
}
}
return true;
}
@Override
public void remove(int index) {
rangeCheck(index);
rebuild(index);
}
@Override
public Iterator<Object> iterator() {
return new IteratorImpl();
}
@Override
public ListIterator listIterator() {
return new ListIteratorImpl();
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < size(); i++) {
stringBuilder.append(array[i].toString());
if (i < size() - 1) stringBuilder.append(", ");
}
return stringBuilder.insert(0, "[").append("]").toString();
}
private void init(final int size) {
pointer = 0;
array = new Object[size];
}
private void resize(final int len) {
Object[] temp = new Object[len];
System.arraycopy(array, 0, temp, 0, pointer);
array = temp;
}
private void rangeCheck(final int index) {
if (index >= pointer) {
throw new IndexOutOfBoundsException(
"size = " + size() + ", index = " + index);
}
}
private void rebuild(final int index) {
if (index == size() - 1) {
array[index] = null;
} else {
int lengthCopy = size() - index - 1;
System.arraycopy(array, index + 1, array, index, lengthCopy);
}
pointer--;
}
private class IteratorImpl implements Iterator<Object> {
int cursor = 0;
boolean condition = false;
boolean con = false;
@Override
public boolean hasNext() {
return cursor != size() && array[cursor] != null;
}
@Override
public Object next() {
if (cursor >= size()) {
throw new NoSuchElementException();
}
condition = true;
return array[cursor++];
}
@Override
public void remove() {
int index = --cursor;
if (!condition && !con) {
throw new IllegalStateException();
}
if (this.hasNext()) {
MyListImpl.this.remove(array[index]);
}
condition = false;
}
}
private class ListIteratorImpl extends IteratorImpl implements ListIterator {
@Override
public boolean hasPrevious() {
return cursor != 0;
}
@Override
public Object previous() {
int index = cursor - 1;
if (index < 0) {
throw new NoSuchElementException();
}
if (index >= array.length) {
throw new IndexOutOfBoundsException();
}
cursor = index;
con = true;
return array[index];
}
@Override
public void set(Object obj) {
if (!condition && !con) {
throw new IllegalStateException();
}
if (condition) {
int index = cursor - 1;
array[index] = obj;
condition = false;
}
if (con) {
array[cursor] = obj;
con = false;
}
}
@Override
public void remove() {
if (!condition && !con) {
throw new IllegalStateException();
}
if (condition) {
super.remove();
condition = false;
}
if (con) {
++cursor;
super.remove();
con = false;
}
}
}
}
|
C++
|
UTF-8
| 969 | 3.015625 | 3 |
[] |
no_license
|
//TC1031.500
//Myroslava Sánchez Andrade A01730712
//Ituriel Mejía Garita A01730875
//Fecha: 17/11/2020
//Act 4.2 - Grafos: Algoritmos complementarios
//Se agregan librerías
#include "iostream"
#include "string"
#include "queue"
#include "vector"
using namespace std;
//Incluimos los archivos
#include "toLetters.h"
#include "Node.h"
#include "NodeAdyacente.h"
#include "loadGraph.h"
#include "isTree.h"
#include "topologicalSort.h"
int main(){
bool tree;
int nNodos,nArcos;
//Se reciben como inputs el número de nodos y arcos
cin>>nNodos;
cin>>nArcos;
//Creamos el pointer que apuntará a la lista
struct Node* head=loadGraph(nNodos, nArcos);
//Lammamos a la función isTree() para verificar si se trata de un árbol
if(nNodos>=1 || nArcos>=1)
tree=isTree(head, nNodos, nArcos);
if(tree)
cout<<"true"<<endl;
else
cout<<"false"<<endl;
//Hacemos el recorrido topolofical
topologicalSort(head, nNodos, nArcos);
return 0;
}
|
PHP
|
UTF-8
| 2,170 | 2.6875 | 3 |
[] |
no_license
|
<?php
namespace NikitaMikhno\LaravelDiscourse\Traits;
trait Posts
{
/**
* createPost
*
* NOT WORKING YET
*
* @param string $bodyText
* @param $topicId
* @param string $userName
* @return \stdClass
*/
public function createPost(string $bodyText, $topicId, string $userName): \stdClass
{
$params = [
'raw' => $bodyText,
'archetype' => 'regular',
'topic_id' => $topicId
];
return $this->postRequest('/posts', [$params], $userName);
}
/**
* getPostsByNumber
* @param $topic_id
* @param $post_number
* @return mixed HTTP return code and API return object
*/
public function getPostsByNumber($topic_id, $post_number)
{
return $this->getRequest('/posts/by_number/' . $topic_id . '/' . $post_number . '.json');
}
/**
* UpdatePost
* @param $bodyhtml
* @param $post_id
* @param string $userName
* @return \stdClass
*/
public function updatePost($bodyhtml, $post_id, $userName = 'system'): \stdClass
{
$bodyraw = htmlspecialchars_decode($bodyhtml);
$params = [
'post[cooked]' => $bodyhtml,
'post[edit_reason]' => '',
'post[raw]' => $bodyraw
];
return $this->putRequest('/posts/' . $post_id, [$params], $userName);
}
/**
* get count posts from topic
* @param int $topicId
* @param int $limit
* @return object|null
*/
public function getSpecificPostsInTopic(int $topicId, int $limit = 10)
{
$discourseTopic = $this->getTopic($topicId);
if (!isset($discourseTopic->apiresult->post_stream->stream)) {
return null;
}
$postIds = array_slice($discourseTopic->apiresult->post_stream->stream, 0, $limit);
if (!empty($postIds)) {
return $this->getRequest(
"/t/$topicId/posts.json",
['post_ids' => $postIds],
'system',
false
)->apiresult->post_stream->posts ?? null;
}
return null;
}
}
|
C++
|
UTF-8
| 688 | 2.9375 | 3 |
[] |
no_license
|
#pragma once
#include <iostream>
#include "Component.hpp"
class VelocityComponent : public Components
{
public:
float m_Velocity;
public:
VelocityComponent() = default;
VelocityComponent(int id) : Components(id, getCompId()){};
virtual ~VelocityComponent() = default;
static Components *Create(const int &id) { return new VelocityComponent(id); };
virtual void modify(float Velocity) { m_Velocity = Velocity; }
virtual void dump() { std::cout << "Velocity = " << m_Velocity << std::endl; }
virtual Components *clone() { return new VelocityComponent(*this); }
int getEntityId() const { return m_entityId; }
static int getCompId() { return 1; };
};
|
Python
|
UTF-8
| 1,761 | 3.71875 | 4 |
[] |
no_license
|
'''
answer
'''
class Solution:
# @param n, an integer
# @return an integer
def hammingWeight(self, n):
s = 0
while n is not 0:
if n % 2 == 1:
s += 1
n /= 2
return s
'''
resolving
'''
def hammingWeight(n):
s = 0
while n is not 0:
if n % 2 == 1:
s += 1
print "n: ", n
n /= 2
# n = n >> 1
return s
q = 0x10111011011 # count 8 1-bits
print bin(q)
print hammingWeight(q)
'''
wikipedia version
'''
def wiki_hamming(x):
m1 = 0x5555555555555555; # binary: 0101...
m2 = 0x3333333333333333; # binary: 00110011..
m4 = 0x0f0f0f0f0f0f0f0f; # binary: 4 zeros, 4 ones ...
m8 = 0x00ff00ff00ff00ff; # binary: 8 zeros, 8 ones ...
m16 = 0x0000ffff0000ffff; # binary: 16 zeros, 16 ones ...
m32 = 0x00000000ffffffff; # binary: 32 zeros, 32 ones
hff = 0xffffffffffffffff; # binary: all ones
h01 = 0x0101010101010101; # the sum of 256 to the power of 0,1,2,3...
x = (x & m1 ) + ((x >> 1) & m1 ); # put count of each 2 bits into those 2 bits
print bin(x)
x = (x & m2 ) + ((x >> 2) & m2 ); # put count of each 4 bits into those 4 bits
print bin(x)
x = (x & m4 ) + ((x >> 4) & m4 ); # put count of each 8 bits into those 8 bits
print bin(x)
x = (x & m8 ) + ((x >> 8) & m8 ); # put count of each 16 bits into those 16 bits
print bin(x)
x = (x & m16) + ((x >> 16) & m16); # put count of each 32 bits into those 32 bits
print bin(x)
x = (x & m32) + ((x >> 32) & m32); # put count of each 64 bits into those 64 bits
print bin(x)
return x;
print "q: ", bin(q)
print wiki_hamming(q)
|
Python
|
UTF-8
| 461 | 3.859375 | 4 |
[] |
no_license
|
import turtle
#设定循环次数
#实现一个操作,常量
#常量修改变量
length=50 #初始
step=50 #每次加50
num=0 #循环10次,
while num<10:
print(num)
num+=1
turtle.penup()
turtle.goto(length*2,length)
turtle.pendown()
turtle.goto(length*2,-1*length)
turtle.goto(-2*length,-1*length)
turtle.goto(-2*length,length)
turtle.goto(length*2,length)
length+=step
else:
print("out",num)
turtle.done()
|
C++
|
UTF-8
| 1,563 | 2.828125 | 3 |
[] |
no_license
|
#include "gameState.h"
#include <iostream>
#include "main_Menu.h"
#include "options.h"
#include "raylib.h"
// -----***** Game Idea *****----- //
// This is gonna be the main menu for the game, I would have...
// ... to port this to my Assessable.
int main() {
int screenWidth = 910;
int screenHeight = 540;
InitWindow(screenWidth, screenHeight, "Singletons & Enums");
SetTargetFPS(60);
// Sets the game to start in the Main Menu
GameState::GetInstance().setState(0);
if (GameState::GetInstance().getState() == 0) {
std::cout << GameState::GetInstance().getState() << std::endl;
}
mainMenu mainMenuObject;
options optionsObject;
while (!WindowShouldClose()) {
BeginDrawing();
ClearBackground(SKYBLUE);
SetWindowPosition(screenWidth / 2, screenHeight / 2);
// If the Game State is 0 (Main Menu)
if (GameState::GetInstance().getState() == 0) {
mainMenuObject.update(GetFrameTime());
mainMenuObject.draw(screenWidth / 4, screenHeight / 16);
}
//// If the Game State is 1 (Start -> Character Select)
//if (GameState::GetInstance().getState() == 1) {
// mainMenuObject.update(GetFrameTime());
// mainMenuObject.draw(screenWidth / 4, screenHeight / 16);
//}
// If the Game State is 2 (Options)
if (GameState::GetInstance().getState() == 2) {
optionsObject.update(GetFrameTime());
//optionsObject.draw(39, 50);
}
//// If the Game State is 6 (Game Exit)
//if (GameState::GetInstance().getState() == 6) {
// CloseWindow();
//
// return 0;
//}
EndDrawing();
}
CloseWindow();
return 0;
}
|
Go
|
UTF-8
| 2,175 | 3.4375 | 3 |
[
"MIT"
] |
permissive
|
package filesort
import (
"bufio"
"fmt"
"io"
"strings"
"testing"
)
func testLessLine(a, b interface{}) bool { return a.(string) < b.(string) }
type testLineEncoder struct {
w io.WriteCloser
}
func newTestLineEncoder(w io.WriteCloser) Encoder {
return &testLineEncoder{w: w}
}
func (le *testLineEncoder) Encode(a interface{}) error {
if _, err := le.w.Write([]byte(a.(string) + "\n")); err != nil {
return err
}
return nil
}
func (le *testLineEncoder) Close() error {
return le.w.Close()
}
type testLineDecoder struct {
r *bufio.Reader
}
func newTestLineDecoder(r io.Reader) Decoder {
return &testLineDecoder{r: bufio.NewReader(r)}
}
func (ld *testLineDecoder) Decode() (interface{}, error) {
val, err := ld.r.ReadString(0xa)
if err != nil {
return nil, err
}
return strings.TrimRight(val, "\n"), nil
}
func TestSort(t *testing.T) {
sort, err := New(WithLess(testLessLine), WithEncoderNew(newTestLineEncoder), WithDecoderNew(newTestLineDecoder), WithMaxMemoryBuffer(3))
if err != nil {
t.Fatal(err)
}
lines := []string{
"aaaa",
"zzzz",
"yyyy",
"iiii",
"ffff",
"kkkk",
"qqqq",
"tttt",
}
for _, l := range lines {
if err := sort.Write(l); err != nil {
t.Fatal(err)
}
}
if err := sort.Close(); err != nil {
t.Fatal(err)
}
var n int
prev := ""
for {
out, err := sort.Read()
if err != nil {
t.Fatal(err)
}
if out == nil {
break
}
n++
str := out.(string)
if len(str) != 4 || str <= prev {
t.Errorf("%s came after %s", str, prev)
}
prev = str
}
if n != len(lines) {
t.Errorf("expected to read %d values, but got %d", len(lines), n)
}
}
func TestSortStable(t *testing.T) {
sort, err := New(
WithLess(func(a, b interface{}) bool { return false }),
WithEncoderNew(newTestLineEncoder),
WithDecoderNew(newTestLineDecoder),
WithMaxMemoryBuffer(3),
)
if err != nil {
t.Fatal(err)
}
for i := 0; i < 100; i++ {
sort.Write(fmt.Sprintf("%d", i))
}
sort.Close()
for i := 0; i < 100; i++ {
exp := fmt.Sprintf("%d", i)
s, err := sort.Read()
if err != nil {
t.Fatal(err)
}
if s.(string) != exp {
t.Fatalf("expected %s but got %s", exp, s.(string))
}
}
}
|
PHP
|
UTF-8
| 20,281 | 2.640625 | 3 |
[] |
no_license
|
<?php
// Init
function ms_midtrans_core_va_init() {
class MS_Midtrans_Core_VA_Gateway extends WC_Payment_Gateway {
/**
* Class constructor
*/
public function __construct() {
$this->id = 'ms_midtrans_core_va';
$this->icon = '';
$this->has_fields = true; // in case you do not need a custom credit card form
$this->method_title = __( 'MS Midtrans - Virtual Account', 'ms-midtrans-core' );
$this->method_description = __( 'Virtual Account payment gateway using Midtrans core API', 'ms-midtrans-core' );
/**
* gateways can support subscriptions, refunds, saved payment methods,
*/
$this->supports = array( 'products', 'refunds' );
// Method with all the options fields
$this->init_form_fields();
// Load the settings.
$this->init_settings();
$this->enabled = $this->get_option( 'enabled' );
$this->title = $this->get_option( 'title' );
$this->description = $this->get_option( 'description' );
$this->instructions = $this->get_option( 'instructions' );
$this->sandbox_mode = 'yes' === $this->get_option( 'sandbox_mode' );
$this->client_key = $this->get_option( 'client_key' );
$this->server_key = $this->get_option( 'server_key' );
$this->expiry_time = $this->get_option( 'expiry_time' );
$this->expiry_unit = $this->get_option( 'expiry_unit' );
$this->callback_url = $this->get_option( 'callback_url' );
$this->date_format = $this->get_option( 'date_format' );
$this->time_format = $this->get_option( 'time_format' );
$this->notification_url = '';
$this->redirect = $this->get_option( 'redirect' );
// api url
$this->api_url = $this->sandbox_mode ? 'https://api.sandbox.midtrans.com' : 'https://api.midtrans.com';
// This action hook saves the settings
add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
// Print instructions in thank you page
add_action( 'woocommerce_thankyou_' . $this->id, array( $this, 'payment_instructions' ) );
/**
* Do you need custom scripts?
* add_action( 'wp_enqueue_scripts', array( $this, 'payment_scripts' ) );
*/
/**
* You can also register a webhook here
* woocommerce_api_{webhook name}
* url must be http://domain/wc-api/ms-midtrans-payment-status/
*/
add_action( 'woocommerce_api_ms-midtrans-payment-status', array( $this, 'check_payment_status' ) );
}
/**
* Payment settings
*/
public function init_form_fields(){
$this->form_fields = array(
'enabled' => array(
'title' => __( 'Enable/Disable', 'ms-midtrans-core' ),
'label' => __( 'Enable MS Midtrans Virtual Account', 'ms-midtrans-core' ),
'type' => 'checkbox',
'description' => '',
'default' => 'no'
),
'title' => array(
'title' => __( 'Title', 'ms-midtrans-core' ),
'type' => 'text',
'description' => __( 'This controls the title which the user sees during checkout.', 'ms-midtrans-core' ),
'default' => 'Virtual Account',
'desc_tip' => true,
),
'description' => array(
'title' => __( 'Description', 'ms-midtrans-core' ),
'type' => 'textarea',
'description' => __( 'This controls the description which the user sees during checkout.', 'ms-midtrans-core' ),
'default' => __( 'Pay with Virtual Account via our super-cool payment gateway.', 'ms-midtrans-core' ),
),
'instructions' => array(
'title' => __( 'Instructions', 'ms-midtrans-core' ),
'type' => 'textarea_html',
'description' => __( 'Available tag {{countdown}}, {{expiry_date}}, {{expiry_time}}, {{expiry_datetime}}, {{vanumber}}, {{amount}}, {{order_url}}', 'ms-midtrans-core' ),
'default' => __( 'Pay with Virtual Account via our super-cool payment gateway.', 'ms-midtrans-core' ),
'desc_tip' => false
),
'sandbox_mode' => array(
'title' => __( 'Sandbox mode', 'ms-midtrans-core' ),
'label' => __( 'Enable Sandbox Mode', 'ms-midtrans-core' ),
'type' => 'checkbox',
'description' => __( 'Place the payment gateway in sandbox mode.', 'ms-midtrans-core' ),
'default' => 'yes',
'desc_tip' => true,
),
'merchant_id' => array(
'title' => __( 'Merchant ID', 'ms-midtrans-core' ),
'type' => 'text'
),
'client_key' => array(
'title' => __( 'Client Key', 'ms-midtrans-core' ),
'type' => 'text'
),
'server_key' => array(
'title' => __( 'Server Key', 'ms-midtrans-core' ),
'type' => 'text',
),
'expiry_time' => array(
'title' => __( 'Payment Expiry Duration', 'ms-midtrans-core' ),
'type' => 'number',
'default' => 24,
'step' => 1,
'description' => __( 'If blank default expiry time form Midtrans will be used.', 'ms-midtrans-core' )
),
'expiry_unit' => array(
'title' => __( 'Payment Expiry Unit', 'ms-midtrans-core' ),
'type' => 'select',
'options' => array(
'second' => __( 'Second', 'ms-midtrans-core' ),
'minute' => __( 'Minute', 'ms-midtrans-core' ),
'hour' => __( 'Hour', 'ms-midtrans-core' ),
'day' => __( 'Day', 'ms-midtrans-core' )
),
'default' => 'hour'
),
'date_format' => array(
'title' => __( 'Expiry Date Format', 'ms-midtrans-core' ),
'type' => 'text',
'default' => get_option( 'date_format' )
),
'time_format' => array(
'title' => __( 'Expiry Time Format', 'ms-midtrans-core' ),
'type' => 'text',
'default' => get_option( 'time_format' )
),
'callback_url' => array(
'title' => __( 'Callback URL', 'ms-midtrans-core' ),
'type' => 'text',
'description' => __( 'If blank default callback will be disabled.', 'ms-midtrans-core' )
),
'notifcation_url' => array(
'title' => 'Notification URL',
'type' => 'hidden',
'custom_attributes' => array(
'disabled' => 'true'
),
'description' => '<code>' . home_url( '/wc-api/ms-midtrans-payment-status/' ) . '</code><br/>Please make sure permalink already set to %postname%'
),
'redirect' => array(
'title' => __( 'Custom Payment Page', 'ms-midtrans-core' ),
'label' => __( 'Redirect to custom payment page', 'ms-midtrans-core' ),
'type' => 'select',
'description' => 'Insert this shortcode <code>[ms-midtrans-core-payment]</code> to the page. Leave empty to disable.',
'default' => '',
'options' => $this->custom_thankyou_page()
),
);
}
/**
* Payment fields: Bank selections
*/
public function payment_fields() {
if ( $this->description ) {
if ( $this->sandbox_mode ) {
$this->description .= ' TEST MODE ENABLED. No payment placed.';
$this->description = trim( $this->description );
}
echo '<fieldset style="background:transparent">' . wpautop( wp_kses_post( $this->description ) ) . '</fieldset>';
}
echo '<fieldset id="wc-' . esc_attr( $this->id ) . '-form" class=wc-payment-form" style="background:transparent;">';
do_action( 'woocommerce_credit_card_form_start', $this->id );
?>
<p>
<label>
<input type="radio" name="ms_midtrans_vabank" value="bca">
<?php _e( 'BCA' ); ?>
</label>
</p>
<p>
<label>
<input type="radio" name="ms_midtrans_vabank" value="mandiri">
<?php _e( 'Mandiri'); ?>
</label>
</p>
<p>
<label>
<input type="radio" name="ms_midtrans_vabank" value="bni">
<?php _e( 'BNI' ); ?>
</label>
</p>
<p>
<label>
<input type="radio" name="ms_midtrans_vabank" value="permata">
<?php _e( 'Permata' ); ?>
</label>
</p>
<?php
do_action( 'woocommerce_credit_card_form_end', $this->id );
echo '<div class="clear"></div></fieldset>';
}
/*
* Insert custom scripts here
* public function payment_scripts() {}
*/
/*
* Fields validation
*/
public function validate_fields() {
if( empty( $_POST[ 'ms_midtrans_vabank' ] ) ) {
wc_add_notice( 'Please select a Bank.', 'error' );
return false;
}
return true;
}
/*
* We're processing the payments here
*/
public function process_payment( $order_id ) {
global $woocommerce;
// we need it to get any order detailes
$order = wc_get_order( $order_id );
$url = $this->api_url . "/v2/charge";
$body = array();
$bank = $_POST['ms_midtrans_vabank'];
// charge details
if ( $bank == 'bca' || $bank == 'bni' ) {
$payment_type = 'bank_transfer';
$body['bank_transfer'] = array(
'bank' => $bank
);
} else if ( $bank == 'mandiri' ) {
$payment_type = 'echannel';
$body['echannel'] = array(
'bill_info1' => __( 'Payment For:', 'ms-midtrans-core' ),
'bill_info2' => sprintf( __( 'Order #%s', 'ms-midtrans-core' ), $order_id ),
'bill_info3' => $order->get_formatted_billing_full_name()
);
} else {
$payment_type = 'permata';
}
// payment type
$body['payment_type'] = $payment_type;
// transactions details
$body['transaction_details'] = array(
'order_id' => $order_id,
'gross_amount' => $order->get_total()
);
// customer details
$body['customer_details'] = array(
'first_name' => $order->get_billing_first_name(),
'last_name' => $order->get_billing_last_name(),
'email' => $order->get_billing_email(),
'phone' => $order->get_billing_phone()
);
// items
$items = $order->get_items();
$body['item_details'] = array();
foreach( $items as $item ) {
$body['item_details'][] = array(
'id' => $item->get_id(),
'price' => ceil($order->get_item_subtotal( $item, false )),
'quantity' => $item->get_quantity(),
'name' => $item->get_name()
);
}
// shipping
if ( $order->get_total_shipping() > 0 ) {
$body['item_details'][] = array(
'id' => 'shipping',
'price' => ceil($order->get_total_shipping()),
'quantity' => 1,
'name' => __( 'shipping', 'ms-midtrans-core' )
);
}
// tax
if ( $order->get_total_tax() > 0 ) {
$body['item_details'][] = array(
'id' => 'tax',
'price' => ceil( $order->get_total_tax() ),
'quantity' => 1,
'name' => __( 'tax', 'ms-midtrans-core' )
);
}
// discount
if ( $order->get_total_discount() > 0 ) {
$body['item_details'][] = array(
'id' => 'discount',
'price' => ceil( $order->get_total_discount() ) *-1,
'quantity' => 1,
'name' => __( 'discount', 'ms-midtrans-core' )
);
}
// fees
if ( sizeof( $order->get_fees() ) > 0 ) {
$fees = $order->get_fees();
$i = 0;
foreach( $fees as $item ) {
$body['item_details'][] = array(
'id' => 'fee' . $i,
'price' => ceil( $item['line_total'] ),
'quantity' => 1,
'name' => $item['name'],
);
$i++;
}
}
// recalculate gross amount
$data_items = $body['item_details'];
$total_amount = 0;
foreach( $data_items as $dataitem ) {
$total_amount+=($dataitem ['price']*$dataitem['quantity']);
}
// set new gross amount
$body['transaction_details']['gross_amount'] = $total_amount;
// expiry
if ( '' != $this->expiry_time && $this->expiry_time != '0' ) {
$body['custom_expiry'] = array(
'expiry_duration' => $this->expiry_time,
'unit' => $this->expiry_unit
);
}
// parameter
$args = array(
'headers' => array(
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'Authorization' => 'Basic ' . base64_encode( $this->server_key . ':' )
),
'body' => json_encode( $body )
);
/*
* Your API interaction could be built with wp_remote_post()
*/
$response = wp_remote_post( $url, $args );
if ( !is_wp_error( $response ) ) {
$response_body = json_decode( wp_remote_retrieve_body( $response ), true );
if ( $response_body['status_code'] == '201' ) {
// save response
update_post_meta( $order_id, '_ms_midtrans_payment_response', maybe_serialize( $response_body ) );
// set expiry time
$this->set_payment_expiry( $order_id, $response_body['transaction_time'], $this->expiry_time, $this->expiry_unit );
// note
$order->add_order_note( __( 'Order placed.', 'ms-midtrans-core' ) );
// note
$order->add_order_note(
sprintf( '%s: %s [%s]. %s',
__( 'Midtrans HTTP notifications received', 'ms-midtrans-core' ),
$response_body['status_message'],
$response_body['status_code'],
$this->method_title
)
);
// Empty cart
$woocommerce->cart->empty_cart();
// note
$order->add_order_note( __( 'Order status Pending.', 'ms-midtrans-core' ) );
// Redirect to the thank you page
return array(
'result' => 'success',
'redirect' => $this->get_return_url( $order )
);
} else {
// Note
$order->add_order_note(
sprintf( '%s: %s [%s]. %s',
__( 'Midtrans HTTP notifications received', 'ms-midtrans-core' ),
$response_body['status_message'],
$response_body['status_code'],
$this->method_title
)
);
wc_add_notice( $response_body['status_message'], 'error' );
return;
}
} else {
wc_add_notice( 'Connection error.', 'error' );
return;
}
}
/**
* We're processing refund here
*/
public function process_refund( $order_id, $amount = null, $reason = '' ) {
if ( $amount == null || '0' == $amount ) {
return false;
}
// api url
$url = $this->api_url . "/v2/{$order_id}/refund";
$order = wc_get_order( $order_id );
// parameter
$body = array(
'refund_key' => sprintf( __( 'order-refund-%s', 'ms-midtrans-core' ), $order_id ),
'amount' => $amount
);
if ( '' <> $reason ) {
$body['reason'] = $reason;
}
// args
$args = array(
'headers' => array(
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'Authorization' => 'Basic ' . base64_encode( $this->server_key . ':' )
),
'body' => json_encode( $body )
);
/*
* Your API interaction could be built with wp_remote_post()
*/
$response = wp_remote_post( $url, $args );
if ( !is_wp_error( $response ) ) {
$response_body = json_decode( wp_remote_retrieve_body( $response ), true );
if ( $response_body['status_code'] == '200' ) {
// Note
$order->add_order_note(
sprintf( '%s: %s [%s]. %s',
__( 'Midtrans HTTP notifications received', 'ms-midtrans-core' ),
$response_body['status_message'],
$response_body['status_code'],
$this->method_title
)
);
// save respose
update_post_meta( $order_id, '_ms_midtrans_refund_status', maybe_serialize( $response_body ) );
return true;
} else {
// Note
$order->add_order_note(
sprintf( '%s: %s [%s]. %s',
__( 'Midtrans HTTP notifications received', 'ms-midtrans-core' ),
$response_body['status_message'],
$response_body['status_code'],
$this->method_title
)
);
return false;
}
} else {
$order->add_order_note( __( 'Connection error: Refund failed', 'ms-midtrans-core' ) . '. ' . $this->method_title );
return false;
}
}
/**
* Thank you
*/
public function payment_instructions( $order_id ) {
$resposne = get_post_meta( $order_id, '_ms_midtrans_payment_response', true );
$order = wc_get_order( $order_id );
$payment_gateway = wc_get_payment_gateway_by_order( $order );
// include html
include( MS_MIDTRANS_CORE_DIR . '/views/thankyou.php' );
}
/**
* Custom thank you page
*/
public function custom_thankyou_page() {
$pages = get_pages();
$empty_val = array( '' => __( '-- Select page --', 'ms-midtrans-core' ) );
$options = $empty_val + wp_list_pluck( $pages, 'post_title', 'ID' );
return $options;
}
/*
* In case you need a webhook, like instant notification, IPN, etc
* Autocomplete on successful payment
*/
public function check_payment_status() {
// get post data
$body = file_get_contents('php://input');
if ( $body ) {
$response = json_decode( $body );
$order_id = $response->order_id;
$order = wc_get_order( $order_id );
// success
if ( $response->status_code == '200' ) {
// note
$order->add_order_note(
sprintf( '%s: %s [%s]. %s',
__( 'Midtrans HTTP notifications received', 'ms-midtrans-core' ),
$response->transaction_status,
$response->status_code,
$this->method_title
)
);
// processing with note
wc_reduce_stock_levels( $order_id );
// $order->payment_complete(); with note
$order->update_status( 'processing' );
// completed with note
$order->update_status( 'completed' );
}
// pending payent
else if ( $response->status_code == '201' ) {
// note
$order->add_order_note(
sprintf( '%s: %s [%s]. %s',
__( 'Midtrans HTTP notifications received', 'ms-midtrans-core' ),
$response->transaction_status,
$response->status_code,
$this->method_title
)
);
}
// failed or denied payment
else {
// note
$order->add_order_note(
sprintf( '%s: %s [%s]. %s',
__( 'Midtrans HTTP notifications received', 'ms-midtrans-core' ),
$response->transaction_status,
$response->status_code,
$this->method_title
)
);
// cancelled
$order->update_status( 'cancelled', __( 'The order was cancelled due to no payment from customer.', 'ms-midtrans-core') );
// note
$order->add_order_note( __( 'Order status changed from Pending payment to Cancelled.', 'ms-midtrans-core' ) );
}
// save payment status notifications
update_post_meta( $order_id, '_ms_midtrans_payment_status', maybe_serialize( json_decode( $body, true ) ) );
/**
* $this->write_log( 'Ping from midtrans' );
* $this->write_log( $response );
*/
}
exit;
}
/**
* Custom settings fields
*/
public function generate_textarea_html_html( $key, $data ) {
$field = $this->plugin_id . $this->id . '_' . $key;
$defaults = array(
'class' => 'button-secondary',
'css' => '',
'custom_attributes' => array(),
'desc_tip' => false,
'description' => '',
'title' => '',
);
$data = wp_parse_args( $data, $defaults );
ob_start();
?>
<tr valign="top">
<th scope="row" class="titledesc">
<label for="<?php echo esc_attr( $field ); ?>"><?php echo wp_kses_post( $data['title'] ); ?></label>
<?php echo $this->get_tooltip_html( $data ); ?>
</th>
<td class="forminp">
<?php
$content = $this->instructions;
$editor_id = $field;
$settings = array(
'textarea_name' => $field,
'textarea_rows' => 10,
);
wp_editor( $content, $editor_id, $settings ); ?>
<?php echo $this->get_description_html( $data ); ?>
</td>
</tr>
<?php
return ob_get_clean();
}
/**
* Set expiry time
*/
public function set_payment_expiry( $order_id, $transaction_time, $expiry, $unit ) {
switch ($unit) {
case 'minute':
$add = $expiry * MINUTE_IN_SECONDS;
break;
case 'hour':
$add = $expiry * HOUR_IN_SECONDS;
break;
case 'day':
$add = $expiry * DAY_IN_SECONDS;
break;
default:
$add = $expiry;
break;
}
$expiry_time = strtotime( $transaction_time ) + $add;
update_post_meta( $order_id, '_ms_midtrans_payment_expiry', $expiry_time );
}
/*
* Helper
* Writing log & debug
*/
public function write_log($log) {
if (true === WP_DEBUG) {
if (is_array($log) || is_object($log)) {
error_log(print_r($log, true));
} else {
error_log($log);
}
}
}
}
}
add_action( 'plugins_loaded', 'ms_midtrans_core_va_init' );
|
Java
|
UTF-8
| 3,953 | 2.28125 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2021 FormDev Software GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.formdev.flatlaf.icons;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Path2D;
import java.util.Map;
import javax.swing.AbstractButton;
import javax.swing.ButtonModel;
import javax.swing.UIManager;
import com.formdev.flatlaf.ui.FlatStylingSupport;
import com.formdev.flatlaf.ui.FlatStylingSupport.Styleable;
import com.formdev.flatlaf.ui.FlatUIUtils;
/**
* "clear" icon for search fields.
*
* @uiDefault SearchField.clearIconColor Color
* @uiDefault SearchField.clearIconHoverColor Color
* @uiDefault SearchField.clearIconPressedColor Color
*
* @author Karl Tauber
* @since 1.5
*/
public class FlatClearIcon
extends FlatAbstractIcon
{
@Styleable protected Color clearIconColor = UIManager.getColor( "SearchField.clearIconColor" );
@Styleable protected Color clearIconHoverColor = UIManager.getColor( "SearchField.clearIconHoverColor" );
@Styleable protected Color clearIconPressedColor = UIManager.getColor( "SearchField.clearIconPressedColor" );
private final boolean ignoreButtonState;
public FlatClearIcon() {
this( false );
}
/** @since 2 */
public FlatClearIcon( boolean ignoreButtonState ) {
super( 16, 16, null );
this.ignoreButtonState = ignoreButtonState;
}
/** @since 2 */
public Object applyStyleProperty( String key, Object value ) {
return FlatStylingSupport.applyToAnnotatedObject( this, key, value );
}
/** @since 2 */
public Map<String, Class<?>> getStyleableInfos() {
return FlatStylingSupport.getAnnotatedStyleableInfos( this );
}
/** @since 2.5 */
public Object getStyleableValue( String key ) {
return FlatStylingSupport.getAnnotatedStyleableValue( this, key );
}
@Override
protected void paintIcon( Component c, Graphics2D g ) {
if( !ignoreButtonState && c instanceof AbstractButton ) {
ButtonModel model = ((AbstractButton)c).getModel();
if( model.isPressed() || model.isRollover() ) {
/*
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<path fill="#7F8B91" fill-opacity=".5" fill-rule="evenodd" d="M8,1.75 C11.4517797,1.75 14.25,4.54822031 14.25,8 C14.25,11.4517797 11.4517797,14.25 8,14.25 C4.54822031,14.25 1.75,11.4517797 1.75,8 C1.75,4.54822031 4.54822031,1.75 8,1.75 Z M10.5,4.5 L8,7 L5.5,4.5 L4.5,5.5 L7,8 L4.5,10.5 L5.5,11.5 L8,9 L10.5,11.5 L11.5,10.5 L9,8 L11.5,5.5 L10.5,4.5 Z"/>
</svg>
*/
// paint filled circle with cross
g.setColor( model.isPressed() ? clearIconPressedColor : clearIconHoverColor );
Path2D path = new Path2D.Float( Path2D.WIND_EVEN_ODD );
path.append( new Ellipse2D.Float( 1.75f, 1.75f, 12.5f, 12.5f ), false );
path.append( FlatUIUtils.createPath( 4.5,5.5, 5.5,4.5, 8,7, 10.5,4.5, 11.5,5.5, 9,8, 11.5,10.5, 10.5,11.5, 8,9, 5.5,11.5, 4.5,10.5, 7,8 ), false );
g.fill( path );
return;
}
}
/*
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<path fill="none" stroke="#7F8B91" stroke-linecap="square" stroke-opacity=".5" d="M5,5 L11,11 M5,11 L11,5"/>
</svg>
*/
// paint cross
g.setColor( clearIconColor );
Path2D path = new Path2D.Float( Path2D.WIND_EVEN_ODD, 4 );
path.moveTo( 5, 5 );
path.lineTo( 11, 11 );
path.moveTo( 5, 11 );
path.lineTo( 11, 5 );
g.draw( path );
}
}
|
Python
|
UTF-8
| 5,523 | 2.921875 | 3 |
[] |
no_license
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
================================================================
******FECHA CREACION******
Feb 5 09:58:19 2021
******PROGRAMA******:
VIDA MEDIA MUÓN
******INSTITUCION******:
Universidad del Valle de Guatemala
Introduccion a la Fisica de Particulas
*****AUTORES******:
-Christian Ramirez
-Pablo Marroquin
-Julio Monzon
-Paula Valdes
================================================================
"""
#LIBRERIA PARA GRAFICAR
import matplotlib.pyplot as plt
import os
import pathlib
from scipy.optimize import curve_fit
import numpy as np
#===============================================================
#DECLARACION DE VARIABLES
"""
temp_particulas=0
num_archivo=0
cant_particulas=[]
psn=[] # posicion nuevo archivo en lista archivo
"""
t_maxes=[] # estan guardados los valores de tiempo donde ocurre el pico
tiempos=[] # tiempos de decaimiento del muon
t12=[] # tiempos que aparecen abajo de cada 12 datos
archivo = [] #lista de lineas del archivo dat
cargas = [] #lista de cargas medidas
cargas_integradas=[] #lista de cargas integradas calculadas
suma_parcial_cargas = [] #variable temporal para sumar cargas
#===============================================================
ruta = pathlib.Path(__file__).parent.absolute() #se guarda la ruta actual
for root, dirs, files in os.walk(ruta): # se recorre todo el directorio
for file in files: # se guardan archivos en lista
filename, extension = os.path.splitext(file)
if extension == '.dat': #se verifica que sean .dat
with open(file, "r") as file: #se lee el archivo
for linea in file: #se recorre el archivo
if linea[0]=="#": #se ignoran las línas que inician con numeral
if linea[2]=="t":
t12.append(float(linea[6:]))
else:
pass
else:
archivo.append(linea) #se agrega cada lineal del archivo a la lista
"""psn.append(len(archivo))"""
#print("escribi en psn")
#===============================================================
for indice in archivo: #se recorre la lista
try:
valor_carga = abs(int(indice[:3]) - 50) #se toma el valor de la carga en la linea
cargas.append(valor_carga) #se agrega el valor a la lista de cargas
except:
pass
#===============================================================
for indice in range(len(cargas)): #se recorre la lista
if indice%12 == 0 and indice!=0: #se revisa el indice para saber si termina la suma parcial
try:
suma_parcial_cargas.append(cargas[indice]) #se agrega cada carga a la suma parcial
carga_n = sum(suma_parcial_cargas) #se hace la suma parcial y se guarda en carga_n
cargas_integradas.append(carga_n) #se agrega la carga_n a la lista de cargas integradas
suma_parcial_cargas = [] #IMPORTANTE se vacia la lista de la suma parcial
except:
pass
else:
suma_parcial_cargas.append(cargas[indice]) #se revisa el indice para saber si termina la suma parcial
#================================================================
# verificar si el evento es un muón
for i in range(0,len(cargas_integradas)-1,1):
carga = cargas_integradas[i]
t=t12[i]
carga_sig=cargas_integradas[i+1]
t_sig=t12[i+1]
#Si la carga esta en el rango 354-642 y el siguiente es menor que 354, entonces se cataloga como muón
if( (carga<= 642 and carga >= 354) and (carga_sig<354)):
tiempos.append( t_sig-t + ((12/40)*10**(-6)) ) #se toma el tiempo entre eventos
else:
pass
""" #codigo alternativo para obtener alturas de los bines
# alturas de los bines
ax = plt.gca()
#p son todos los bins
p = ax.patches
dens=[]
for i in p:
dens.append(i.get_height())
"""
n, bins, patches = plt.hist(tiempos, bins=1000, log=False) #se realiza el histograma para luego utilizar las alturas para la vida media del muón
bins=bins[1:]
plt.plot(bins,n)
# se imprimen en archivos los datos para poder realizar la regresión exponencial en Excel
f1 = open("bins.txt", "w")
for i in range(0,len(bins),1) :
f1.write(str(bins[i])+ "\n")
f2 = open("n.txt", "w")
for i in range(0,len(n),1) :
f2.write(str(n[i])+ "\n")
#===============================================================
|
Markdown
|
UTF-8
| 639 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
@vlah.io/ngx-success-box
Set of reusable Angular components (factory workers) to help display success messages.
### Usage (code example)
```
constructor(private successBoxWorker: SuccessBoxWorker) {
}
render(): void {
this.successBoxWorker.render(message: string, options: DisplayOptionsInterface = {}): ComponentRef<SuccessBoxComponent>
}
```
### CSS styles
```
/* You can add global styles to this file, and also import other style files */
@import "../../ngx-success-box/src/assets/css/ngx-success-box.css";
```
For more details read [here](https://github.com/vlah-io/ngx-success-box/blob/master/INSTALLATION.md).
|
Python
|
UTF-8
| 219 | 3.5 | 4 |
[] |
no_license
|
n = int(input())
c = list(input())
px = 0
py = 0
for i in c:
if i == "L":
px += 1
elif i == "R":
px -= 1
elif i == "U":
py += 1
else:
py -= 1
print(n - abs(px) - abs(py))
|
Java
|
UTF-8
| 808 | 3.3125 | 3 |
[] |
no_license
|
package QuickSort;
public class QuickSort {
private int[] sortedArray;
public int[] getSortedArray() {
return sortedArray;
}
public QuickSort(int[] arr) {
int length = arr.length;
sortedArray = new int[length];
sortedArray = arr;
qs(sortedArray, 0, length - 1);
}
private void qs(int[] arr, int left, int right) {
if (left < right) {
int index = partition(arr, left, right);
qs(arr, left, index - 1);
qs(arr, index + 1, right);
}
}
private int partition(int[] arr, int left, int right) {
int pivot = arr[right];
int i = left - 1;
for (int j = left; j < right; j++) {
if (arr[j] <= pivot) {
i++;
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
int tmp = arr[i + 1];
arr[i + 1] = arr[right];
arr[right] = tmp;
return i + 1;
}
}
|
JavaScript
|
UTF-8
| 706 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
import { enterChatroom, leaveChatroom } from "../services/users";
export function enterChatRequest(nickname) {
return dispatch => {
dispatch({
type: "ENTER_CHAT_REQUEST"
});
enterChatroom(nickname).then(userObj => {
dispatch(enterChat(userObj))
});
};
}
function enterChat(userObj) {
return {
type: "ENTER_CHAT",
user: userObj
}
}
export function leaveChatRequest(userId){
return dispatch => {
dispatch({
type: "LEAVE_CHAT_REQUEST"
});
leaveChatroom(userId).then(() => dispatch(leaveChat()));
};
}
function leaveChat() {
return {
type: "LEAVE_CHAT"
}
}
|
Python
|
UTF-8
| 1,437 | 3.046875 | 3 |
[] |
no_license
|
from bearlibterminal.terminal import printf as terminal_printf
from entities.entity import Entity
from entities.food import Food
from entities.wall import Wall
class Player(Entity):
def __init__(self, controller, x=40, y=10, speed=1):
self.controller = controller
self.x = x
self.y = y
self.speed = speed
self.symbol = '@'
self.hunger = 5
self.is_game_over = False
self.tmp_coords = [x, y]
def move(self):
self.tmp_coords = [self.x, self.y]
if self.controller.is_up:
self.y -= self.speed
self.hunger -= 1
if self.controller.is_down:
self.y += self.speed
self.hunger -= 1
if self.controller.is_left:
self.x -= self.speed
self.hunger -= 1
if self.controller.is_right:
self.x += self.speed
self.hunger -= 1
def render(self):
terminal_printf(self.x, self.y, self.symbol)
def update(self):
self.move()
if self.hunger <= 0:
self.is_game_over = True
def collide(self, other):
if isinstance(other, Wall):
if other.is_visible:
self.x = self.tmp_coords[0]
self.y = self.tmp_coords[1]
if isinstance(other, Food):
if other.is_visible:
self.hunger += 2
other.is_visible = False
|
Python
|
UTF-8
| 2,665 | 3.109375 | 3 |
[] |
no_license
|
# -*- coding:utf-8 -*-
"""
@ide: PyCharm
@author: mesie
@date: 2019/4/7 21:25
@summary: 简单提取特征
https://blog.csdn.net/red_stone1/article/details/83859845
"""
import pandas as pd
from datetime import date
from o2o.feature.data_util import load_data
def get_discount_type(row):
"""打折类型"""
if row == 'null':
return 0
elif ':' in row:
return 1
else:
return 2
def convert_rate(row):
"""折扣率"""
if row == 'null':
return 1.0
elif ':' in row:
rows = row.split(':')
return 1.0 - float(rows[1]) / float(rows[0])
else:
return float(row)
def get_discount_man(row):
"""满多少"""
if ':' in row:
rows = row.split(':')
return int(rows[0])
else:
return 0
def get_discount_jian(row):
"""减多少"""
if ':' in row:
rows = row.split(':')
return int(rows[1])
else:
return 0
def get_week_day(row):
"""日期处理"""
if row == 'null':
return row
else:
return date(int(row[0:4]), int(row[4:6]), int(row[6:8])).weekday() + 1
def get_label(row):
"""1:正样本,0负样本,-1表示没有领到优惠券,无需考虑 """
if row['Date_received'] == 'null':
return -1
if row['Date'] != 'null':
td = pd.to_datetime(row['Date'], format='%Y%m%d') - pd.to_datetime(row['Date_received'], format='%Y%m%d')
if td <= pd.Timedelta(15, 'D'):
return 1
return 0
def process_data(df, lable=False):
# 处理Discount_rate
df['discount_type'] = df['Discount_rate'].apply(get_discount_type)
df['discount_rate'] = df['Discount_rate'].apply(convert_rate)
df['discount_man'] = df['Discount_rate'].apply(get_discount_man)
df['discount_jian'] = df['Discount_rate'].apply(get_discount_jian)
# 处理Distance
df['distance'] = df['Distance'].replace('null', -1).astype(int)
# 处理Date_received
df['weekday'] = df['Date_received'].astype(str).apply(get_week_day)
df['weekday'] = df['weekday'].replace('null', 0).astype(int)
# weekday_type:周六和周日为1,其他为0
df['weekday_type'] = df['weekday'].apply(lambda x: 1 if x in [6, 7] else 0)
if lable:
df['label'] = df.apply(get_label, axis=1)
# print(df['discount_type'].unique())
# print(df['label'].value_counts())
# df = df[['discount_type'], ['discount_rate'], ['discount_man'], ['discount_jian'], ['distance'], ['weekday'],
# ['weekday_type'], ['label']]
return df
if __name__ == '__main__':
pd_train, pd_test = load_data()
d = process_data(pd_train)
print(d.head(5))
|
JavaScript
|
UTF-8
| 7,582 | 2.5625 | 3 |
[] |
no_license
|
window.onload = video_controls;
var v, pbtn, seekBar, ctime, dtime, fscreen, canvas, can, cbtn, cContents, lineColor, move, poleft, optop;
function video_controls() {
v = document.getElementById('vContents');
pbtn = document.getElementById('pbtn');
seekBar = document.getElementById('seekBar');
ctime = document.getElementById('curtime');
dtime = document.getElementById('durtime');
// fscreen = document.getElementById('full');
canvas = document.getElementById('canvas');
cbtn = document.getElementById('cbtn');
cContents = document.getElementById('canvas_container');
move = document.getElementById('move');
lineColor = 'white';
// play button event
canvas.width = v.offsetWidth;
canvas.height = v.offsetHeight;
pbtn.addEventListener('click', playEvent, false);
seekBar.addEventListener('change', changeEvent, false);
v.addEventListener('timeupdate', timeEvent, false);
// fscreen.addEventListener('click', fullEvent, false);
cbtn.addEventListener('click', canvasEvent, false);
}
function playEvent() {
if (v.paused) {
if (cContents.style.display == 'inline') {
cContents.style.display = 'none';
document.getElementById('selectColor').style.display = 'none';
document.getElementById('canvas_tool').style.display = 'none';
vContents.style.display = 'inline';
}
v.play();
pbtn.value = 'paused';
} else {
v.pause();
pbtn.value = 'play';
}
}
function changeEvent() {
// duration 총 재생시간, currentTime 현재생시간
let time = (seekBar.value / 100) * v.duration;
v.currentTime = time;
}
function timeEvent() {
let point = v.currentTime * (100 / v.duration);
seekBar.value = point;
let curtime = v.currentTime.toFixed(2).split('.');
let durtime = v.duration.toFixed(2).split('.');
let csecs = curtime[0];
let cmsecs = curtime[1];
let dsecs = durtime[0];
let dmsecs = durtime[1];
if (csecs < 10) {
csecs = "0" + csecs;
}
if (cmsecs < 10 && cmsecs.length < 2) {
cmsecs = "0" + cmsecs;
}
if (dsecs < 10) {
dsecs = "0" + dsecs;
}
// if (dmsecs < 10) {
// dmsecs = "0" + dmsecs;
// }
ctime.innerText = csecs+':'+cmsecs;
dtime.innerText = dsecs+':'+dmsecs;
}
// function fullEvent() {
// var fullScreen = document.getElementById('left_container');
// var org = document.getElementById('left_container');
// if (v.requestFullscreen) {
// org.requestFullscreen();
// } else if (v.mozRequestFullScreen) {
// org.mozRequestFullscreen();
// } else if (v.webkitRequestFullscreen) {
// org.webkitRequestFullscreen();
// }
//
// org.style.width = '100%';
// org.style.height = '100%';
// }
//
// document.addEventListener("webkitfullscreenchange", function(){
// if(!document.webkitIsFullScreen){
// org.remove;
// document.getElementById('container').innerHTML = fullScreen;
// }
// });
function canvasEvent() {
v.pause();
pbtn.value = 'play';
vContents.style.display = 'none';
cContents.style.display = 'inline';
document.getElementById('selectColor').style.display = 'inline';
document.getElementById('canvas_tool').style.display = 'inline';
can = canvas.getContext('2d');
can.drawImage(v,0,0,canvas.width,canvas.height);
poleft = canvas.offsetLeft;
potop = canvas.offsetTop;
// if (move.value == 'stop') {
canvas.addEventListener('mousedown', listener);
canvas.addEventListener('mousemove', listener);
canvas.addEventListener('mouseup', listener);
canvas.addEventListener('mouseout', listener);
// }
}
var pos = {
drawable: false,
x: -1,
y: -1
};
function listener(event) {
let et = event.type;
switch (et) {
case "mousedown":
if (move.value=='stop') {
initDraw(event);
}
break;
case "mousemove":
if(pos.drawable){
draw(event);
}
break;
case "mouseout":
case "mouseup":
finisDraw();
break;
}
}
function initDraw(event){
can.beginPath();
pos.drawable = true;
var coors = getPosition(event);
pos.X = coors.X;
pos.Y = coors.Y;
can.moveTo(pos.X, pos.Y);
}
function draw(event){
var coors = getPosition(event);
can.lineTo(coors.X, coors.Y);
pos.X = coors.X;
pos.Y = coors.Y;
can.strokeStyle = lineColor; // 선색지정
can.stroke();
}
function finisDraw(event) {
pos.drawable = false;
pos.X = -1;
pos.Y = -1;
}
function getPosition(event) {
var x = event.pageX - poleft;
var y = event.pageY - potop;
return {X:x,Y:y};
}
function changeLineColor(t) {
lineColor = t.style.backgroundColor;
document.getElementById('selectColor').style.backgroundColor = lineColor;
}
var a = document.getElementById('list');
a.addEventListener('click', function() {
let diCheck = document.getElementById('file_list').style.display;
let show = document.getElementById('show_list');
if (diCheck == 'none') {
document.getElementById('file_list').style.display = 'inline';
show.style.width = 49+'%';
// show.style.marginLeft = 30+'%';
} else {
document.getElementById('file_list').style.display = 'none';
show.style.width = 60+'%';
}
})
function getData(data) {
let divin = document.getElementById('show_list');
let name = data.innerText;
let check = document.getElementById(name) ? true : false;
if (check) {
alert('Object is already loaded in timeline');
return;
} else {
let img = document.createElement('img');
img.setAttribute('id',name);
img.setAttribute('src', "/video/"+name+'.png');
img.style = 'width:60%; height:80%; margin-left:1%; margin-right:1%; margin-top:5%;';
divin.appendChild(img);
document.getElementById(name).addEventListener('dblclick', changeData, false);
}
}
function changeData(event) {
let el = event.toElement;
name = el.id;
v.src = '/video/'+name+'.mp4';
}
// zomm in and out test
var zin = document.getElementById('zoom_in');
var zout = document.getElementById('zoom_out');
var zreset = document.getElementById('z_reset');
var zValue = 1;
zin.addEventListener('click', zoomIn, false);
zout.addEventListener('click', zoomOut, false);
zreset.addEventListener('click', zoomReset, false);
function zoomIn() {
// zValue = Math.max(1, zValue-0.25);
zValue = Math.max(1, zValue-0.25);
canvas.style.transform = 'scale(' + (1/zValue) + ')';
}
function zoomOut() {
zValue = zValue+0.25;
canvas.style.transform = 'scale(' + (1/zValue) + ')';
}
function zoomReset() {
zValue = 1;
canvas.style.transform = 'scale(' + zValue + ')';
}
// imge drag
var moveImge = document.getElementById('move');
moveImge.addEventListener('click', moveTo, false);
function moveTo(){
move.value = 'move';
canvas_container.addEventListener('mousedown', startMove, false);
}
let l, t, target;
function startMove() {
if (move.value == 'move') {
console.log(this);
target = event.toElement;
let e = event;
l = target.offsetLeft - e.offsetX;
t = target.offsetTop - e.offsetY;
document.onmousemove = moveDrag;
document.onmouseup = stopDrag;
move.value = 'stop';
}
}
function moveDrag() {
e = event;
poleft = parseInt(e.offsetX+l);
potop = parseInt(e.offsetY+t);
target.style.transform = 'translate3d('+poleft+'px,'+potop+'px,'+'0px)';
// 아래방법으로 하면 해당 스타일에 포지션 절대위치에 왼쪽과 탑 값을 줘야 이동 됨 따라서 위방법으로 교체
// target.style.top = dy+'px';
//target.style.left = dx+'px';
return false;
}
function stopDrag() {
document.onmousemove = null;
document.onmouseup = null;
}
|
PHP
|
UTF-8
| 1,079 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
<?php namespace App\Http\Controllers;
use App\Bases\Controller;
use App\Http\Requests\ContactRequest;
/**
* Class ContactController
*
* @package App\Http\Controllers
* @author ARCANEDEV <arcanedev.maroc@gmail.com>
*/
class ContactController extends Controller
{
/* ------------------------------------------------------------------------------------------------
| Main Functions
| ------------------------------------------------------------------------------------------------
*/
/**
* Get contact form.
*
* @return \Illuminate\View\View
*/
public function getForm()
{
$this->seo()
->setTitle('Contact us')
->setDescription('This is the contact us page description.')
->setKeywords(['contact', 'us', 'page', 'map', 'phone']);
$this->addBreadcrumb('Contact us');
return $this->view('contact');
}
/**
* Post contact form.
*
* @param ContactRequest $request
*/
public function postForm(ContactRequest $request)
{
//
}
}
|
Rust
|
UTF-8
| 2,606 | 3.1875 | 3 |
[] |
no_license
|
extern crate tl_casper;
use tl_casper::{Message, Validator, Weight};
use std::collections::{HashMap, HashSet};
fn main() {
// allows us to give ids to messages for ordering
let mut id_iterator = interator(0);
let validator1: Validator = 1;
let validator2: Validator = 2;
let validator3: Validator = 3;
let validator4: Validator = 4;
let validators_weights: Vec<(Validator, Weight)> = vec![
(validator1, 1.0),
(validator2, 1.0),
// if you change the next weight to something > 2, the blockchain changes completely
// even though the validator 3 only has the genesis block as a justification
// and validator 4 has all the messages as justification
(validator3, 1.0),
(validator4, 1.0),
];
// maps validators to their respective weights
// note: validator 0 is used to "send" the genesis block
let validators_weights: HashMap<_, _> = validators_weights.into_iter().collect();
// create a genesis message
let genesis_block:Message = Message::genesis(&mut id_iterator);
println!("Genesis Message: {:#?}", genesis_block);
let mut j1: HashSet<& Message> = HashSet::new();
j1.insert(&genesis_block);
let m1: Message = Message::new(
validator1,
j1,
&genesis_block,
&mut id_iterator,
&validators_weights);
println!("Message 1: {:#?}", m1);
let mut j2: HashSet<& Message> = HashSet::new();
j2.insert(&genesis_block);
j2.insert(&m1);
let m2: Message = Message::new(
validator2,
j2,
&genesis_block,
&mut id_iterator,
&validators_weights);
println!("Message 2: {:#?}", m2);
let mut j3: HashSet<& Message> = HashSet::new();
j3.insert(&genesis_block);
// j3.insert(&m1);
// j3.insert(&m2);
let m3: Message = Message::new(
validator3,
j3,
&genesis_block,
&mut id_iterator,
&validators_weights);
println!("Message 3: {:#?}", m3);
let mut j4: HashSet<& Message> = HashSet::new();
j4.insert(&genesis_block);
j4.insert(&m1);
j4.insert(&m2);
j4.insert(&m3);
let m4: Message = Message::new(
validator4,
j4,
&genesis_block,
&mut id_iterator,
&validators_weights);
println!("Message 4: {:#?}", m4);
}
// practicing iterators...
fn interator(start:i64) -> It
{
It { curr: start-1 }
}
struct It{
curr: i64,
}
impl Iterator for It{
type Item = i64;
fn next(&mut self) -> Option<i64>{
self.curr = self.curr + 1;
Some(self.curr)
}
}
|
C
|
UTF-8
| 377 | 3.03125 | 3 |
[] |
no_license
|
#include<stdio.h>
#include<stdlib.h>
main()
{
int bilangan, faktor=0, i, batas;
printf("prima: ");
for(bilangan=2;bilangan<=21;bilangan++){
faktor=0;
for(i=1;i<=bilangan;i++){
if(bilangan%i==0){
faktor++;
}
}
if (faktor==2){
printf("%d ", bilangan);
}
}
return 0;
}
|
Java
|
UTF-8
| 601 | 2.078125 | 2 |
[] |
no_license
|
package com.matveyenka.entity;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.time.LocalDateTime;
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Entity
@Table(name = "employee_meeting", schema = "employee_storage")
public class EmployeeMeeting extends BaseEntity<Long> {
@ManyToOne
@JoinColumn(name = "employee_id")
private Employee employee;
@ManyToOne
@JoinColumn(name = "meeting_id")
private Meeting meeting;
@Column(name = "meeting_date")
private LocalDateTime meetingDate;
}
|
PHP
|
UTF-8
| 1,298 | 2.53125 | 3 |
[] |
no_license
|
<meta charset="UTF-8" />
<?php
session_start();
date_default_timezone_set('Europe/Paris');
$db= mysqli_connect("localhost","root","","livreor");
if(!isset($_SESSION["id"])){
header("Location:index.php");
}
if(isset($_POST['valider'])){
$message=htmlspecialchars($_POST['message']);
$id_user=$_POST['id_user'];
$date= date('Y-m-d H:i:s');
$add_comment=" INSERT INTO `commentaires`( `commentaire`, `id_utilisateur`, `date`) VALUES ('$message', '$id_user', '$date')";
mysqli_query($db, $add_comment);
header("Location: livre-or.php");
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Ajouter un commentaire</title>
</head>
<body>
<header><?php include("header.php");?></header>
<main class=main_form>
<h1>Ajouter un commentaire</h1>
<form action="" method="post">
<input type="hidden" name='id_user' value=<?= $_SESSION["id"]?>>
<textarea name='message' placeholder="Votre message ici..."></textarea>
<button type="submit" name='valider'>Envoyer</button>
</form>
</main>
<footer><?php include("footer.php");?></footer>
</body>
</html>
|
C
|
UTF-8
| 493 | 3.421875 | 3 |
[] |
no_license
|
#include<stdio.h>
void main()
{
int i=1,no,temp,prev=0,next=1;
printf("How many numbers of fabonaci series you want: ");
scanf("%d",&no);
while(i<=no)
{
temp=prev;
prev=next;
next=prev+temp;
i++;
}
printf("\n\nReversed fabonaci Series is: ");
while(i>1)
{
temp=next;
next=prev;
prev=temp-next;
printf("%d ",prev);
i--;
}
printf("\n\n");
}
|
Markdown
|
UTF-8
| 1,185 | 2.703125 | 3 |
[] |
no_license
|
# Article R314-233
Par dérogation aux dispositions de l'article R. 314-232, le cadre normalisé de l'état réalisé des recettes et des dépenses
est remplacé :
1° Pour les activités médico-sociales relevant d'un établissement public de santé, par un état réalisé des charges et des
produits qui regroupe les comptes de résultat prévisionnels annexes ;
2° Pour les établissements d'hébergement pour personnes âgées dépendantes relevant des articles L. 342-1 à L. 342-6, par un
état réalisé des recettes et des dépenses simplifié qui regroupe, le cas échéant, le compte de résultat principal et le ou
les comptes de résultat annexes.
Ces documents comportent un tableau de répartition des charges communes.
Ils sont conformes aux modèles fixés par les ministres chargés de la sécurité sociale et des affaires sociales.
**Liens relatifs à cet article**
_Créé par_:
- Décret n°2016-1815 du 21 décembre 2016 - art. 2
_Cite_:
- Code de l'action sociale et des familles - art. L342-1 (V)
- Code de l'action sociale et des familles - art. R314-232 (V)
_Cité par_:
- Code de l'action sociale et des familles - art. R314-75 (V)
|
Ruby
|
UTF-8
| 900 | 2.796875 | 3 |
[] |
no_license
|
class Animal < ActiveRecord::Base
#Relationships
has_many :samples
has_one :parameter
#Validations
CD_REGEX = /\A[A-Z]{3}\s{1}(?:[A-Z_]{4}|[A-Z]{3}[.]{1})\Z/
# 3 Caps + space + (4 Caps Or 3 Caps and a period)
SCI_REGEX = /\A[A-Z]{1}[a-z]+\s{1}(?:[a-z]+|sp\.)\Z/
#A capital followed by lowercase 1 space and the rest lowercase letters or sp.
COM_REGEX = /\A[A-Z][a-z]+(?:\s[A-Z][a-z\.]+)*?\Z/
validates :comname,
:allow_blank => true,
:format => {
:with => COM_REGEX,
:message => 'must contain only spaces letters and periods'
}
validates :species_cd, :presence => true,
:format => {:with => CD_REGEX,
:message => 'must be capitalized, with first 4 letters
of the genus and first 3 of the species'},
:uniqueness => true
validates :sciname, :presence => true,
:format => {
:with => SCI_REGEX,
:message => 'must be a valid scientific name'
}
end
|
C++
|
UTF-8
| 4,729 | 2.71875 | 3 |
[] |
no_license
|
#pragma once
#include "field/field.h"
#include "objects/base.h"
#include "objects/object.h"
#include "fabrics/objectFabric.h"
#include "fabrics/landscapefabric.h"
#include "landscapes/cliffProxy.h"
#include "landscapes/gladeProxy.h"
#include "landscapes/swampProxy.h"
#include "strategies/istrategy.h"
#include "rules.h"
template <typename T>
class Game
{
public:
~Game(){
}
T rules;
bool win = false;
int winH = 2;
int winW = 2;
int currNumBase = false;
Field* field;
Base *base1;
Base *base2;
Landscape* cliff;
Landscape* glade;
Landscape* swamp;
bool isActionDone = false;
int isAttackDone = false;
Game(){}
Game(int h, int w, T rules)
{
field = new Field(h, w);
currNumBase = rules.currNumBase;
win = rules.end;
if(win){
winH = std::rand() % h +1;;
winW = std::rand() % w +1;;
}
LandscapeFabric landFabric;
cliff = landFabric.cliff();
glade = landFabric.glade();
swamp = landFabric.swamp();
for (int i = 1; i <= h; i++){
for (int j = 1; j <= w; j++){
int random = std::rand() % 7 +1;
if(field->cells(i,j).innerObject){
field->cells(i, j).landscape = glade;
}else{
if(random==1){
field->cells(i, j).landscape = cliff;
}else if(random==2){
field->cells(i, j).landscape = swamp;
}else{
field->cells(i, j).landscape = glade;
}
}
}
}
objectFabric fabric;
base1 = fabric.createBase(1,1,0);
base2 = fabric.createBase(h,w,1); //numbase 0 ??????
field->addObject(base1, base1->baseCell->x, base1->baseCell->y);
field->addObject(base2, base2->baseCell->x, base2->baseCell->y);
if(rules.first){
int randomH = std::rand() % h +1;
int randomW = std::rand() % w +1;
field->addObject(base1->createUnit("Archer"),randomH,randomW-1);
randomH = std::rand() % h +1;
randomW = std::rand() % w +1;
field->addObject(base2->createUnit("Archer"),randomH,randomW-1);
}else{
field->addObject(base1->createUnit("Archer"),1,2);
field->addObject(base2->createUnit("Archer"),h,w-1);
}
for (int i = 1; i <= h; i++){
for (int j = 1; j <= w; j++){
int random = std::rand() % 20 +1;
if(field->cells(i,j).innerObject == nullptr){
if(random==1){
field->addObject(fabric.createMedicineChest(), i, j);
//field->cells(i, j).innerObject = fabric.createMedicineChest();
}else if(random==2){
field->addObject(fabric.createPowerUp(), i, j);
//field->cells(i, j).innerObject = fabric.createPowerUp();
}else if(random==3){
field->addObject(fabric.createShield(), i, j);
//field->cells(i, j).innerObject = fabric.createShield();
}else if(random==4){
field->addObject(fabric.createHorse(), i, j);
//field->cells(i, j).innerObject = fabric.createHorse();
}
}
}
}
}
void atack(Unit* unit, Object* base){
if(!(((Unit*)base)->shieldEnabled)){
base->health = base->health - unit->damage;
}else{
((Unit*)base)->shieldEnabled = false;
((Unit*)base)->shieldUsed = true;
}
if(base->health == 0){
del((Unit*)base);
}
}
bool move(int x1, int y1, int x2, int y2){
field->cells(x2,y2).landscape->action->interact((Unit*)field->cells(x1,y1).innerObject);
if((Unit*)field->cells(x1,y1).innerObject->health == 0){
del((Unit*)field->cells(x1,y1).innerObject);
}else{
field->moveObject(x1,y1,x2,y2);
}
}
bool moveToNeutral(Unit* unit, NeutralObject* obj){
/*...*/
obj->action->interact(unit);
field->moveObject(unit->x,unit->y,obj->x,obj->y);
}
bool add(std::string who, bool numBase, int x, int y){
if(!numBase){
field->addObject(base1->createUnit(who),x,y);
}else{
field->addObject(base2->createUnit(who),x,y);
}
return true;
}
void del(Unit* unit){
field->deleteObject(unit->x, unit->y);
}
};
|
Python
|
UTF-8
| 314 | 3.140625 | 3 |
[] |
no_license
|
class LibDivider:
"""Library for dividing integers"""
ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
def divide(self, a, b=1):
"""Return quotient of division"""
if int(b) == 0:
raise AssertionError("Fail")
self.quotient = int(a) / int(b)
return str(int(self.quotient))
|
Python
|
UTF-8
| 3,376 | 2.96875 | 3 |
[] |
no_license
|
#!/usr/bin/env python
# coding: utf-8
# In[105]:
import os
import csv
from pathlib import Path
path = Path('/Users/yanrujiang/Desktop/python-challenge/PyPoll/election_data.csv')
Total_Votes=[]
Candidate = []
Khan=[]
Correy=[]
Li=[]
OTooley=[]
Name_List=[]
# In[106]:
with open (path, newline ='')as csvfile:
csvreader = csv.reader(csvfile,delimiter=",")
header = next(csvreader)
for row in csvreader:
Total_Votes.append(row[0])
Candidate.append(row[2])
# In[107]:
# for d in range(len(Total_Votes)):
# Name_List.append(Candidate[d+1]!=Candidate[d])
# break
# for i in range(len(Total_Votes)):
# Khan.append(Candidate[i]=="Kahn")
# for a in range(len(Total_Votes)):
# Correy.append(Candidate[a]=="Correy")
# for b in range(len(Total_Votes)):
# Li.append(Candidate[b]=="Li")
# for c in range(len(Total_Votes)):
# OTooley.append(Candidate[c]=="O'Tooley")
for i in range(len(Total_Votes)):
if Candidate[i]=="Khan":
Khan.append(Candidate[i])
elif Candidate[i]=="Correy":
Correy.append(Candidate[i])
elif Candidate[i]=="Li":
Li.append(Candidate[i])
elif Candidate[i]=="O'Tooley":
OTooley.append(Candidate[i])
# In[108]:
Khan_Count = len(Khan)
Correy_Count = len(Correy)
Li_Count = len(Li)
OTooley_Count= len(OTooley)
# In[109]:
print(Khan_Count+Correy_Count+Li_Count+OTooley_Count)
# In[110]:
Khan_percent = round(len(Khan)/len(Total_Votes)*100,3)
Correy_percent=round(len(Correy)/len(Total_Votes)*100,3)
Li_percent=round(len(Li)/len(Total_Votes)*100,3)
OTooley_percent=round(len(OTooley)/len(Total_Votes)*100,3)
# In[111]:
#Name = ["Khan","Correy","Li","O'Tooley"]
#Count = [Khan_Count,Correy_Count,Li_Count,OTooley_Count]
#match = zip(Name,Count)
#max_vote = max[Count]
#winner=name[max_vote.index(max_vote)]
#winner = max[Khan_Count,Correy_Count,Li_Count,OTooley_Count]
# In[112]:
print ("Election Results")
print ("----------------------------")
print( "Total Votes: " + str(len(Total_Votes)))
print ("----------------------------")
print(f"Khan: {Khan_percent}% ({Khan_Count})")
print(f"Correy: {Correy_percent}% ({Correy_Count})")
print(f"Li: {Li_percent}% ({Li_Count})")
print(f"O'Tooley: {OTooley_percent}% ({OTooley_Count})")
print ("----------------------------")
print(f"Winner: Khan")
print ("----------------------------")
# In[113]:
output_file = Path("Output.txt")
# In[114]:
with open(output_file,"w") as file:
file.write("Election Results")
file.write("\n")
file.write("----------------------------")
file.write("\n")
file.write("Total Votes: " + str(len(Total_Votes)))
file.write("\n")
file.write("----------------------------")
file.write("\n")
file.write(f"Khan: {Khan_percent}% ({Khan_Count})")
file.write("\n")
file.write(f"Correy: {Correy_percent}% ({Correy_Count})")
file.write("\n")
file.write(f"Li: {Li_percent}% ({Li_Count})")
file.write("\n")
file.write(f"O'Tooley: {OTooley_percent}% ({OTooley_Count})")
file.write("\n")
file.write("----------------------------")
file.write("\n")
file.write(f"Winner: Khan")
file.write("\n")
file.write("----------------------------")
# In[ ]:
|
Markdown
|
UTF-8
| 10,713 | 2.546875 | 3 |
[] |
no_license
|
---
description: Transcribing knowledge to make sense for me and other people
---
# Motyvacija
## Principai
_**Have you ever had the feeling that your head is not quite big enough to hold everything you want to remember?**_
Asmeninių minčių kaupimo konceptas egzistuoja nuo senovės laikų ir žinomas, kaip [commonplace book](https://www.wikiwand.com/en/Commonplace_book). Pasak Wikipedijos tai:
> _a way to compile knowledge, usually by writing information into books. Such books are essentially scrapbooks filled with items of every kind: recipes, quotes, letters, poems, tables of weights and measures, proverbs, prayers, legal formulas. Commonplaces are used by readers, writers, students, and scholars as an aid for remembering useful concepts or facts they have learned. Each commonplace book is unique to its creator's particular interests._
Šiais laikais toks commonplace book procesas virto į [personal knowledge base](https://www.wikiwand.com/en/Personal_knowledge_base):
> _an electronic tool used to express, capture, and later retrieve the personal knowledge of an individual. It differs from a traditional database in that it contains subjective material particular to the owner, that others may not agree with nor care about. Importantly, a PKB consists primarily of knowledge, rather than information; in other words, it is not a collection of documents or other sources an individual has encountered, but rather an expression of the distilled knowledge the owner has extracted from those sources._
Jau ne vienerius metus pasamoniškai to gainiojuosi: pradedant nuo asmeninio tinklaraščio ir ypač "Rinktinės kruopos" rubrikos, kurių sugebėjau išspausti visas 9-ias, tęsiant nuolatiniais shared post'ais su pastebėjimais ar kita informacija soc. tinkluose. Taipogi niekaip nerandu ir vis ieškau įrankių organizuoti savo ganėtinai chaotiškoms mintims ir vis šokinėju tarp skirtingų notes ir todo apps'ų, kurie padėtų informaciją iš galvos ištraukti ir ją susisteminti su kuo mažiau trinties.
Manau, kad nesu [polimatas](https://www.wikiwand.com/en/Polymath), tačiau tikrai turiu panašių polinkių. Turiu gan didelį alkį žinioms ir man labai patinka sužinoti vis kažką naujo, įgauti vis naujų įžvalgų vis skirtingose srityse. Ir taip, visi žinom, kaip yra sakoma _Jack of all trades, master of none_, kinų alternatyva: _Equipped with knives all over, yet none is sharp_, o estiškas variantas: _Nine trades, the tenth one — hunger_, tačiau turint platų požiūrį, insight'ų iš daug įvairių sričių ir generalizuotas žinias, tai gali suteikti unikalią [kombinaciją](https://medium.com/accelerated-intelligence/modern-polymath-81f882ce52db), kuri taipogi gali būti pranašumu.
_If we read without taking notes, our knowledge increases for a short time only. Once we forget what we knew, having read the text becomes worthless. You can bet that you’ll forget about the text’s information one day. It’s guaranteed. Thus, reading without taking notes is just a waste of time in the long run. It’s as if reading never happened._
Tačiau visgi neužtenka viską tiesiog kaupti ar tai būtų citatos, straipsniai, video įrašai, bookmarksai ir kita. Tai tik sukuria informacijos kaupimo iliuziją ir jeigu su šia nauja info nėra dirbama, reflektuojama ir ji nėra kitaip panaudojama - iš to kaupimo yra išties mažai naudos. Perdėlioji iš vieno stalčiuko į kitą ir jokios realios naudos tai nesukuria.
> _Early in his academic career, Luhmann realized that a note was only as valuable as its context – its network of associations, relationships, and connections to other information._
> _Knowledge is acquired when we succeed in fitting a new experience into the system of concepts based upon our old experiences._
David'o Allen'o išgrynintas [Getting Things Done](https://gettingthingsdone.com/what-is-gtd/) \(GTD\) metodas susiveda į 5 pagrindinius žingsnius: Capture, Clarify, Organize, Reflect and Engage. Kitas gan idealogiškai panašus metodas - [zettelkasten](https://zettelkasten.de/posts/), kurį susumuoti būtų galima į: Collect, Process, Cross-Reference and Use. Tai ir tapo mano šūkiu ir būtent taip išsivystė šis Wiki stiliaus PKB projektas. Toks eklektiškas asmeninės informacijos, profesinių interesų, pastebėjimų, pamąstymų, kelionių įspūdžių, bookmarksų, straipsnių, pomėgių ir reflekcijų rinkinys. Natūrali mano tinklaraščio progresija - visgi daugiametis jo slogan'as ir buvo: _Asmeninės nuomonės, įžvalgų bei patirties tinklaraštis. Technologijos, istorijos, faktai ir gyvenimas_.
## Priežastys
Viena pagrindinių priežasčių kodėl noriu turėti asmeninę wiki - nes manau, kad vien atminties neužtenka. Viskas anksčiau ar vėliau nulekia į nebūtį, tampa nereikšminga ir neišsaugota. Lyg ne pats būtum visą tai skaitęs, patyręs, gyvenęs, o tik matęs pro greitai lekiančio automobilio langą. Ir rašymas yra viena geriausių priemonių visą tai užkonservuoti. O taipogi tikriausiai girdėjote faktą, jog šiuolaikinis žmogus per dieną bombarduojamas didesniu kiekiu informacijos, nei senovėje žmonės sužinodavo per visą savo gyvenimą ar kad bendras informacijos kiekis dvigubėja kas 12 mėn. Tad nenuostabu, kad ieškau būdų offloadinti jai - noriu turėti išorinę informacijos saugyklą, padaryti ją lengvai pasiekiamą, organizuotą ir lengvai ieškomą, kad reikiamą šaltinį ar mintį galėčiau ištraukti labai greitai, nesvarbu kokiame kontekste. Ir jei jau skyriau sąlyginai nemažai laiko domėdamasis, kontempliuodamas apie kažką konkretaus, tai galima skirti bent minimaliai ir dar truputis laiko viso to konspektavimui.
## Paskirtis
_**Our goal in life is to collect the dots and connect the dots but we can't do both at the same time. A wiki makes a history of both and tries to make sence of all of this.**_
Taigi personal knowledge stiliaus wiki turi 3 pagrindines paskirtis:
1. minčių saugojimas, organizavimas ir padarymas jas greitai randamonis
2. prieinamumas
3. knowledge path kūrimas
-Pirmasis punktas susijęs su tuo, kad saugomos informacijos vertė auga tiesiogiai nuo to, kaip lengvai ji gali būti randama ir perpanaudojama. Taipogi bandant informaciją sudėlioti trumpai, sklandžiai ir sugrupuotai, toks informacijos apdorojimas priverčia apie ją galvoti kiek ilgiau, giliau ir dėlto ji yra geriau įsisavinama. Visada manau, jog koncepcijos, visumos supratimas yra svarbiau, nei specifinės detalės.
> _The best way to transform the information into our knowledge is to interpret something new to us based on what we have learned and share them.
Interpreting helps us organize and digest information. Therefore it can translate information into our embedded knowledge. And sharing is not only a contribution to the information age but also our motivation to keep outputting better works, which is the reason why I believe that information becomes knowledge via organizing and sharing._
-Kalbant apie antrąją paskirtį - visada mėgau tomis žiniomis dalintis. Jeigu anksčiau tai darydavau tinklaraščio pagalba, dabar manau, kad tai atima per daug laiko. Parašyti vieną long grid'ą atimdavo ne vieną h, nes rašydamas pirmiausia atlieku gan nemažai research'o, fact checking'o ir straipsnis susilaukia daugybės revision'ų ir formulavimų taisymų. Suveikia taisyklė, jog 80% darbo išeikvoja pusę projekto laiko, o likę 20% sueikvoja likusią pusę. Taip pastebėjau, jog tinklaraščio rašymas įgavo didelį slengstį, per kurį perlipti pradėjo darytis vis sunkiau. Didelis, įpareigojantis rašymas į kurį tuomet žiūri, kaip į darbą. Paskutiniu metu labiau parėjau į micro-blogging'ą: nuoroda su keliais komentarais ir tiek. Toks flow pasirodė patrauklus: numeti savo mintį, padedi kitiems sužinoti ir atkreipti dėmesį į tai, ką sužinojai ar galvoji tu, kartais iššauki diskusijas ir svarbiausia - tai galima padaryti lengvai, greitai ir neįpareigojančiai. Toks pat flow labai puikiai persikelia ir į wiki, tik skirtumas, jog tai nepasimeta bendrame pasąmonės sraute, kas yra soc. tinklai.
-Trečioji paskirtis, knowledge path arba timeline - labai įdomu išsaugoti nueitą kelią. Taip lengviau susidaryti kontekstą. Stebint galima matyti per kokias temas šokinėjama, kaip atsiranda asmeninis vystymasis, asmeninis žinių kelias ir kaip po truputėlis jungiasi visi tie surinkti taškai.
Dėl šių priežasčių ir atsirado šis gyvas, be perstojo besikeičiantis žinių indeksas, sudarytas iš nuotrupų su įvairiomis mintimis, konspektais ir šaltiniais. Tai informacijos, saviugdos, pamąstymų ir straipsnių rinkinys ir tai, jog jis yra pasiekiamas viešai, galbūt atneš naudos ne tik man. Tikslas visgi nėra skaitytojų auditorija ar rinki aukštus statistikos skaičiukus.
## Įkvėpimas
Mintis daryti kažką panašaus, mane persekioja jau porą metų, tačiau visą tą laiką taip ir neišgryninau tikslaus koncepto. Tačiau įkvėpimas ir aiškumas pagaliau atėjo, kai suradau bendraminčių:
* pagrindinis konceptas pasiskolintas iš [Nikita Voloboev](https://wiki.nikitavoloboev.xyz)
* taipogi [sąrašas žmonių](https://github.com/RichardLitt/meta-knowledge#readme), kurie iš esmės daro tą patį
## A Portrait of J. Random Hacker
> _Although high general intelligence is common among hackers, it is not the_ [_sine qua non_](https://www.wikiwand.com/en/Sine_qua_non) _one might expect. Another trait is probably even more important: the ability to mentally absorb, retain, and reference large amounts of ‘meaningless’ detail, trusting to later experience to give it context and meaning. A person of merely average analytical intelligence who has this trait can become an effective hacker, but a creative genius who lacks it will swiftly find himself outdistanced by people who routinely upload the contents of thick reference manuals into their brains._
> _Contrary to stereotype, hackers are not usually intellectually narrow; they tend to be interested in any subject that can provide mental stimulation, and can often discourse knowledgeably and even interestingly on any number of obscure subjects — if you can get them to talk at all, as opposed to, say, going back to their hacking._
> _Hackers are generally only very weakly motivated by conventional rewards such as social approval or money. They tend to be attracted by challenges and excited by interesting toys, and to judge the interest of work or other activities in terms of the challenges offered and the toys they get to play with._ - [Jargon File 4.4.7](http://www.catb.org/jargon/html/personality.html)
|
JavaScript
|
UTF-8
| 513 | 3 | 3 |
[] |
no_license
|
// for (var i = 0; i <= 500; i += 100) {
// console.log(i);
// };
// for (var i = 1; i <= 64; i *= 2) {
// console.log(i);
// };
// for (var i = 1; i <= 3; i ++) {
// console.log(i);
// console.log(i);
// console.log(i);
// };
// for (var i = 0; i <= 10; i += 2) {
// console.log(i);
// };
// for (var i = 3; i <= 15; i += 3) {
// console.log(i);
// };
// for (var i = 9; i >= 0; i--) {
// console.log(i);
// };
for (var y = 1; y <= 3; y++) {
for (var i = 0; i <= 3; i ++) {
console.log(i);
};
};
|
Java
|
UTF-8
| 2,556 | 2.265625 | 2 |
[] |
no_license
|
package com.ykh.yinmeng.ymykh2.bean;
import android.os.Parcel;
import android.os.Parcelable;
/**
* 银行卡列表
*/
public class CardBean implements Parcelable{
/**
* id : 21
* uid : 34109
* banks : 中国银行
* branch : 河南省-郑州市-金水区-农业路支行
* banksNumber : 45596558633333
* banksAccount : 李四
* status : 0
*/
public int id;
public int uid;
public String banks;
public String branch;
public String banksNumber;
public String banksAccount;
public int status;
protected CardBean(Parcel in) {
id = in.readInt();
uid = in.readInt();
banks = in.readString();
branch = in.readString();
banksNumber = in.readString();
banksAccount = in.readString();
status = in.readInt();
}
public static final Creator<CardBean> CREATOR = new Creator<CardBean>() {
@Override
public CardBean createFromParcel(Parcel in) {
return new CardBean(in);
}
@Override
public CardBean[] newArray(int size) {
return new CardBean[size];
}
};
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getBanks() {
return banks;
}
public void setBanks(String banks) {
this.banks = banks;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
public String getBanksNumber() {
return banksNumber;
}
public void setBanksNumber(String banksNumber) {
this.banksNumber = banksNumber;
}
public String getBanksAccount() {
return banksAccount;
}
public void setBanksAccount(String banksAccount) {
this.banksAccount = banksAccount;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(id);
parcel.writeInt(uid);
parcel.writeString(banks);
parcel.writeString(branch);
parcel.writeString(banksNumber);
parcel.writeString(banksAccount);
parcel.writeInt(status);
}
}
|
Shell
|
UTF-8
| 2,506 | 3.890625 | 4 |
[] |
no_license
|
#!/usr/bin/env bash
# Start Project
function start_project(){
# Composer Commands
echo "------------- START PROJECT --------------"
echo "==================> Executing composer network install ..."
composer network install --card PeerAdmin@hlfv1 --archiveFile book-counterfeit-composer@"$version".bna
echo "==================> composer network start ..."
composer network start --networkName book-counterfeit-composer --networkVersion "$version" --networkAdmin admin --networkAdminEnrollSecret adminpw --card PeerAdmin@hlfv1 --file networkadmin.card
echo "==================> Beginnig API ..."
composer-rest-server -c admin@book-counterfeit-composer -n never -u true -w -p 3001
exit 0
}
# Upgrade Project
function upgrade_project(){
#Composer Commands
echo "------------- START PROJECT --------------"
echo "==================> composer archive create ..."
composer archive create --sourceType dir --sourceName . -a book-counterfeit-composer@"$version".bna
echo "==================> Executing composer network install ..."
composer network install --card PeerAdmin@hlfv1 --archiveFile book-counterfeit-composer@"$version".bna
echo "==================> Executing composer network upgrade ..."
composer network upgrade -c PeerAdmin@hlfv1 -n book-counterfeit-composer -V $version
echo "==================> Beginnig API ..."
# composer-rest-server -c admin@book-counterfeit-composer -n never -u true -w -p 3000
composer-rest-server -c admin@book-counterfeit-composer -n never -u true -w -p 3001
exit 0
}
#Incase 1 argument misses
helpFunction()
{
echo ""
echo "Usage: $0 -f fun -v version "
echo -e "\t-f Description of what is function to execute"
echo -e "\t-v Description of what is version of the project"
exit 1 # Exit script after printing help
}
while getopts "f:v:" opt
do
case "$opt" in
f ) fun="$OPTARG" ;;
v ) version="$OPTARG" ;;
? ) helpFunction ;; # Print helpFunction in case parameter is non-existent
esac
done
# Print helpFunction in case parameters are empty
if [ -z "$fun" ] || [ -z "$version" ]
# Choose functio to execute
while [ $# -ne 0 ]
do
arg="$1"
case "$arg" in
--start)
start_project
;;
--upgrade)
upgrade_project
;;
--help)
menu
;;
--halt)
stop
;;
esac
shift
done
then
echo "Some or all of the parameters are empty";
helpFunction
fi
# Begin script in case all parameters are correct
echo "$fun"
echo "$version"
|
PHP
|
UTF-8
| 99 | 2.71875 | 3 |
[] |
no_license
|
<?php
interface PJInterface
{
public function getCnpj();
public function setCnpj($cnpj);
}
|
C++
|
UTF-8
| 4,867 | 2.8125 | 3 |
[
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] |
permissive
|
#include <babylon/core/logging/logger.h>
#include <babylon/core/logging/log_message.h>
#include <iostream>
namespace BABYLON {
LogMessageHandler::LogMessageHandler()
: _minLevel{LogLevels::LEVEL_QUIET}, _maxLevel{LogLevels::LEVEL_TRACE}
{
for (unsigned int lvl = _minLevel; lvl <= _maxLevel; ++lvl) {
_logMessageListeners[lvl] = std::vector<LogMessageListener*>();
}
}
bool LogMessageHandler::takes(unsigned int level)
{
return (level >= _minLevel) && (level <= _maxLevel);
}
void LogMessageHandler::handle(const LogMessage& msg)
{
if (_logMessageListeners.find(msg.level())
!= _logMessageListeners.end()) {
for (auto& logMsgListener : _logMessageListeners[msg.level()]) {
(*logMsgListener)(LogMessage(msg));
}
}
#ifdef __EMSCRIPTEN__
std::cout << msg.toString() << "\n";
#endif
}
//BABYLON::Logger& Logger::Instance()
//{
// // Since it's a static variable, if the class has already been created,
// // It won't be created again.
// // And it **is** thread-safe in C++11.
// static Logger loggerInstance;
//
// // Return a reference to our instance.
// return loggerInstance;
//}
Logger & LoggerInstance()
{
// Since it's a static variable, if the class has already been created,
// It won't be created again.
// And it **is** thread-safe in C++11.
static Logger loggerInstance;
// Return a reference to our instance.
return loggerInstance;
}
Logger::Logger() = default;
Logger::~Logger()
{
// Cleanly shutting down log message handler
_impl._logMessageListeners.clear();
}
LogMessage Logger::CreateMessage(unsigned int level, std::string context,
char const* file, int lineNumber,
char const* func, char const* prettyFunc)
{
LogMessage logMessage{level, context};
logMessage.setFile(file);
logMessage.setLineNumber(lineNumber);
logMessage.setFunction(func);
logMessage.setPrettyFunction(prettyFunc);
return logMessage;
}
void Logger::log(const LogMessage& msg)
{
_impl.handle(msg);
}
bool Logger::takes(unsigned int level)
{
return _impl.takes(level);
}
bool Logger::isSubscribed(unsigned int level,
LogMessageListener& logMsgListener)
{
bool subscribed = false;
if (_impl._logMessageListeners.find(level)
!= _impl._logMessageListeners.end()) {
auto& _logMsgListenersLvl = _impl._logMessageListeners[level];
auto it = std::find(_logMsgListenersLvl.begin(), _logMsgListenersLvl.end(),
&logMsgListener);
subscribed = (it != _logMsgListenersLvl.end());
}
return subscribed;
}
void Logger::registerLogMessageListener(LogMessageListener& logMsgListener)
{
for (auto& keyVal : _impl._logMessageListeners) {
auto& _logMsgListenersLvl = _impl._logMessageListeners[keyVal.first];
auto it = std::find(_logMsgListenersLvl.begin(), _logMsgListenersLvl.end(),
&logMsgListener);
if (it == _logMsgListenersLvl.end()) {
auto l = &logMsgListener;
_logMsgListenersLvl.emplace_back(l);
}
}
}
void Logger::unregisterLogMessageListener(
const LogMessageListener& logMsgListener)
{
for (const auto& keyVal : _impl._logMessageListeners) {
auto& _logMsgListenersLvl = _impl._logMessageListeners[keyVal.first];
auto it = std::find(_logMsgListenersLvl.begin(), _logMsgListenersLvl.end(),
&logMsgListener);
if (it != _logMsgListenersLvl.end()) {
_logMsgListenersLvl.erase(it);
}
}
}
void Logger::registerLogMessageListener(unsigned int level,
LogMessageListener& logMsgListener)
{
if (_impl.takes(level)) {
if (_impl._logMessageListeners.find(level)
!= _impl._logMessageListeners.end()) {
auto& _logMsgListenersLvl = _impl._logMessageListeners[level];
auto l = &logMsgListener;
auto it
= std::find(_logMsgListenersLvl.begin(), _logMsgListenersLvl.end(), l);
if (it == _logMsgListenersLvl.end()) {
_impl._logMessageListeners[level].emplace_back(l);
}
}
}
}
void Logger::unregisterLogMessageListener(
unsigned int level, const LogMessageListener& logMsgListener)
{
if (_impl.takes(level)) {
if (_impl._logMessageListeners.find(level)
!= _impl._logMessageListeners.end()) {
auto& _logMsgListenersLvl = _impl._logMessageListeners[level];
auto it = std::find(_logMsgListenersLvl.begin(),
_logMsgListenersLvl.end(), &logMsgListener);
if (it != _logMsgListenersLvl.end()) {
_logMsgListenersLvl.erase(it);
}
}
}
} // namespace BABYLON
} // end of namespace BABYLON
|
Markdown
|
UTF-8
| 1,330 | 2.609375 | 3 |
[] |
no_license
|
# Article R653-76
Les opérations de monte publique relatives aux espèces bovine, ovine, caprine et porcine, définies à l'article R. 653-75,
sont réglementées par les dispositions du présent paragraphe précisées par des arrêtés du ministre chargé de l'agriculture.
Ces arrêtés fixent, pour chaque espèce et chaque catégorie de monte, les normes applicables au choix et à l'utilisation des
animaux reproducteurs mâles pouvant être employés en monte publique. Ces normes concernent notamment la race et l'origine du
reproducteur, ses qualités zootechniques, celles de ses ascendants et, éventuellement, d'un échantillon de ses descendants.
Ces arrêtés peuvent étendre certaines de ces règles à la monte privée.
Ces arrêtés peuvent fixer les méthodes d'identification du matériel génétique de reproduction et les modalités d'évaluation
de la valeur génétique des animaux reproducteurs ainsi que les informations relatives aux animaux reproducteurs devant être
communiquées au public.
**Liens relatifs à cet article**
_Codifié par_:
- Décret n°2003-851 2003-09-01
_Modifié par_:
- Décret n°2006-1662 du 21 décembre 2006 - art. 3 () JORF 23 décembre 2006
_Cite_:
- Code rural - art. R653-75 (V)
_Cité par_:
- Code rural et de la pêche maritime - art. R653-78 (VD)
|
C++
|
UTF-8
| 9,110 | 3.421875 | 3 |
[] |
no_license
|
#include <iostream>
#include <string.h>
#include <conio.h>
#include <fstream>
#define max 100
using namespace std;
// concepts of oops used
// inheritence,
// array of objects,
// exception handling,
// file handling
//Class Patient
class Patient
{
public:
char name[100];
char address[100];
char phone[12];
char from_date[20];
char to_date[20];
float payment_advance;
int booking_id;
};
class Room
{
public:
char type;
char stype;
char ac;
int roomNumber;
int rent;
int status;
char special;
class Patient patient;
class Room addRoom(int);
void searchRoom(int);
void deleteRoom(int);
void displayRoom(Room);
};
//Global Declarations
// number of rooms in hospital
// and count of that room
Room rooms[max];
int count = 0;
Room Room::addRoom(int rno)
{
class Room room;
room.roomNumber = rno;
ofstream outFile;//file handling
outFile.open("room.dat",ios::binary|ios::app);
cout << "\n Is this a room in COVID-19 ward ? (Y/N) : ";
cin >> room.special;
cout << "\nType AC/Non-AC (A/N) : ";
cin >> room.ac;
cout << "\nType Comfort (S/N) : ";
cin >> room.type;
cout << "\nType Bed Size (B/S) : ";
cin >> room.stype;
cout << "\nDaily Rent : ";
cin >> room.rent;
room.status = 0;
outFile.write(reinterpret_cast<char *> (&room), sizeof(Room));
cout << "\n Room Added Successfully!";
getch();
return room;
}
void Room::searchRoom(int rno)
{
int i, found = 0;
for (i = 0; i < count; i++)
{
if (rooms[i].roomNumber == rno)
{
found = 1;
break;
}
}
try//exception handling
{
if (found == 1)
{
cout << "Room Details\n";
if (rooms[i].status == 1)
{
cout << "\nRoom is Reserved";
}
else
{
cout << "\nRoom is available";
}
displayRoom(rooms[i]);
getch();
}
else
{
throw found;
}
}
catch (int y)
{
//"Exception occured (" << y << "):
cout << " Room not found!!" << endl;
getch();
}
}
void Room::displayRoom(Room tempRoom)
{
cout << "\nRoom Number: \t" << tempRoom.roomNumber;
cout << "\nCOVID-19 Room (Y/N) " << tempRoom.special;
cout << "\nType AC/Non-AC (A/N) " << tempRoom.ac;
cout << "\nType Comfort (S/N) " << tempRoom.type;
cout << "\nType Size (B/S) " << tempRoom.stype;
cout << "\nRent: " << tempRoom.rent;
}
//hospital management class
//inheritence
class HospitalMgnt : protected Room
{
public:
void checkIn();
void getAvailRoom();
void searchPatient(char *);
void checkOut(int);
void totalPatientsSummary();
};
void HospitalMgnt::totalPatientsSummary()
{
if (count == 0)
{
cout << "\n No patient in Hospital !!";
}
for (int i = 0; i < count; i++)
{
if (rooms[i].status == 1)
{
cout << "\n Person's First Name : " << rooms[i].patient.name;
cout << "\n Room Number : " << rooms[i].roomNumber;
if (rooms[i].special == 'Y')
cout << "\n COVID-19 : "
<< "Positive";
else
cout << "\n COVID-19 : "
<< "Negative";
cout << "\n Address (only city) : " << rooms[i].patient.address;
cout << "\n Phone : " << rooms[i].patient.phone;
cout << "\n---------------------------------------";
}
}
getch();
}
//hospital management reservation of room
void HospitalMgnt::checkIn()
{
int i, found = 0, rno;
class Room room;
cout << "\nEnter Room number : ";
cin >> rno;
for (i = 0; i < count; i++)
{
if (rooms[i].roomNumber == rno)
{
found = 1;
break;
}
}
try//exception handling
{
if (found == 1)
{
if (rooms[i].status == 1)
{
cout << "\nRoom is already Booked";
getch();
return;
}
cout << "\nEnter booking id: ";
cin >> rooms[i].patient.booking_id;
cout << "\nEnter Patient's Name (First Name): ";
cin >> rooms[i].patient.name;
cout << "\nEnter Address (only city): ";
cin >> rooms[i].patient.address;
cout << "\nEnter Phone: ";
cin >> rooms[i].patient.phone;
cout << "\nEnter Admit Date: ";
cin >> rooms[i].patient.from_date;
//cout<<"\nEnter to Date: ";
//cin>>rooms[i].patient.to_date;
cout << "\nEnter Advance Payment: ";
cin >> rooms[i].patient.payment_advance;
rooms[i].status = 1;
cout << "\n Patient Checked-in Successfully..";
getch();
}
else
{
throw found;
}
}
catch (int found)
{
// cout << "Exception occured : "
cout << "No room with " << rno << " room number!" << endl;
getch();
}
}
//hospital management shows available rooms
void HospitalMgnt::getAvailRoom()
{
int i, found = 0;
for (i = 0; i < count; i++)
{
if (rooms[i].status == 0)
{
displayRoom(rooms[i]);
cout << "\n\nPress enter for next room";
found = 1;
getch();
}
}
if (found == 0)
{
cout << "\nAll rooms are reserved right now";
getch();
}
}
//hospital management shows all patients that have booked room
void HospitalMgnt::searchPatient(char *pname)
{
int i, found = 0;
for (i = 0; i < count; i++)
{
if (rooms[i].status == 1 && stricmp(rooms[i].patient.name, pname) == 0)
{
cout << "\nPatient's Name: " << rooms[i].patient.name;
cout << "\nRoom Number: " << rooms[i].roomNumber;
if (rooms[i].special == 'Y')
cout << "\nThis patient is COVID-19 positive";
else
cout << "\nThis patient is COVID-19 negative\n";
cout << "\n\nPress enter for next record";
found = 1;
getch();
}
}
if (found == 0)
{
cout << "\nPatient not found.";
getch();
}
}
//hospital management generates the bill of the expenses
void HospitalMgnt::checkOut(int roomNum)
{
int i, found = 0, days, rno;
float billAmount = 0;
for (i = 0; i < count; i++)
{
if (rooms[i].status == 1 && rooms[i].roomNumber == roomNum)
{
//rno = rooms[i].roomNumber;
found = 1;
//getch();
break;
}
}
try
{
if (found == 1)
{
cout << "\nEnter Number of Days:\t";
cin >> days;
billAmount = days * rooms[i].rent;
cout << "\n\t######## CheckOut Details ########\n";
cout << "\nPatient's Name : " << rooms[i].patient.name;
cout << "\nRoom Number : " << rooms[i].roomNumber;
if (rooms[i].special == 'Y')
cout << "\nCOVID-19 recovered Patient\n";
cout << "\nAddress : " << rooms[i].patient.address;
cout << "\nPhone : " << rooms[i].patient.phone;
cout << "\nTotal Amount Due : " << billAmount << " /-";
cout << "\nAdvance Paid: " << rooms[i].patient.payment_advance << " /-";
cout << "\n*** Total Payable: " << billAmount - rooms[i].patient.payment_advance << "/- only";
rooms[i].status = 0;
getch();
}
else
{
throw found;
}
}
catch (int found)
{
cout << "Error occured : NO such room no. is present!" << endl;
getch();
}
}
//managing rooms (adding and searching available rooms)
void manageRooms()
{
class Room room;
int opt, rno, i, flag = 0;
char ch;
do
{
system("cls");
cout << "\n ### Manage Rooms ###";
cout << "\n 1. Add Room";
cout << "\n 2. Search Room";
cout << "\n 3. Back to Main Menu";
cout << "\n\n Enter Option: ";
cin >> opt;
//switch statement
switch (opt)
{
case 1:
cout << "\n Enter Room Number: ";
cin >> rno;
i = 0;
for (i = 0; i < count; i++)
{
if (rooms[i].roomNumber == rno)
{
flag = 1;
}
}
if (flag == 1)
{
cout << "\n Room Number is already present.\n Please enter unique Number";
flag = 0;
getch();
}
else
{
rooms[count] = room.addRoom(rno);
count++;
}
break;
case 2:
cout << "\n Enter room number: ";
cin >> rno;
room.searchRoom(rno);
break;
case 3:
//nothing to do
break;
default:
cout << "\n Please Enter correct option";
break;
}
} while (opt != 3);
}
int main()
{
class HospitalMgnt hm;
int i, j, opt, rno;
char ch;
char pname[100];
system("cls");
do
{
system("cls");
cout << "######## Hospital Bed Management in COVID-19 period #########\n";
cout << "\n 1. Manage Rooms";
cout << "\n 2. Check-In Room";
cout << "\n 3. Available Rooms";
cout << "\n 4. Search Patient";
cout << "\n 5. Check-Out Room";
cout << "\n 6. All Patient's Summary";
cout << "\n 7. Exit";
cout << "\n\n Enter Option: ";
cin >> opt;
switch (opt)
{
case 1:
manageRooms();
break;
case 2:
if (count == 0)
{
cout << "\nRooms data is not available.\nPlease add the rooms first.";
getch();
}
else
hm.checkIn();
break;
case 3:
if (count == 0)
{
cout << "\nRooms data is not available.\nPlease add the rooms first.";
getch();
}
else
hm.getAvailRoom();
break;
case 4:
if (count == 0)
{
cout << "\nRooms are not available.\nPlease add the rooms first.";
getch();
}
else
{
cout << "Enter Patient's Name: ";
cin >> pname;
hm.searchPatient(pname);
}
break;
case 5:
if (count == 0)
{
cout << "\nRooms are not available.\nPlease add the rooms first.";
getch();
}
else
{
cout << "Enter Room Number : ";
cin >> rno;
hm.checkOut(rno);
}
break;
case 6:
hm.totalPatientsSummary();
break;
case 7:
cout << "\nTHANK YOU! FOR USING OUR SOFTWARE. GREETINGS OF THE DAY..";
break;
default:
cout << "\nPlease Enter correct option";
break;
}
} while (opt != 7);
getch();
return 0;
}
|
Java
|
UTF-8
| 5,614 | 2.265625 | 2 |
[] |
no_license
|
package com.e2esp.nestlemythbusting.adapters;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.e2esp.nestlemythbusting.R;
import com.e2esp.nestlemythbusting.callbacks.OnVideoClickListener;
import com.e2esp.nestlemythbusting.models.Video;
import com.e2esp.nestlemythbusting.utils.Utility;
import java.util.ArrayList;
/**
* Created by Zain on 3/22/2017.
*/
public class VideoRecyclerAdapter extends RecyclerView.Adapter<VideoRecyclerAdapter.VideoViewHolder> {
private Context context;
private ArrayList<Video> videosList;
private OnVideoClickListener onVideoClickListener;
private Typeface font;
public VideoRecyclerAdapter(Context context, ArrayList<Video> videosList, OnVideoClickListener onVideoClickListener) {
this.context = context;
this.videosList = videosList;
this.onVideoClickListener = onVideoClickListener;
this.font = Utility.getArialFont(context);
}
@Override
public VideoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.card_video_layout, parent, false);
return new VideoViewHolder(view);
}
@Override
public int getItemCount() {
return videosList.size();
}
@Override
public void onBindViewHolder(VideoViewHolder holder, int position) {
holder.bindView(videosList.get(position));
}
public class VideoViewHolder extends RecyclerView.ViewHolder {
private View topView;
private ImageView imageViewPreview;
private TextView textViewTitle;
private TextView textViewStatus;
private TextView textViewDownload;
private ProgressBar progressBar;
public VideoViewHolder(View itemView) {
super(itemView);
topView = itemView;
imageViewPreview = (ImageView) itemView.findViewById(R.id.imageViewVideoPreview);
textViewTitle = (TextView) itemView.findViewById(R.id.textViewVideoTitle);
textViewTitle.setTypeface(font);
textViewTitle.setSelected(true);
textViewStatus = (TextView) itemView.findViewById(R.id.textViewVideoStatus);
textViewStatus.setTypeface(font);
textViewDownload = (TextView) itemView.findViewById(R.id.textViewVideoDownload);
textViewDownload.setTypeface(font);
progressBar = (ProgressBar) itemView.findViewById(R.id.progressBarVideoProgress);
}
public void bindView(final Video video) {
textViewTitle.setText(video.getTitleWithoutExt());
switch (video.getStatus()) {
case NotDownloaded:
textViewStatus.setText("");
textViewDownload.setVisibility(View.VISIBLE);
textViewDownload.setText(context.getString(R.string.download));
progressBar.setVisibility(View.GONE);
imageViewPreview.setImageResource(R.drawable.video_preview);
break;
case Downloading:
textViewStatus.setText(video.getProgressText());
textViewDownload.setVisibility(View.INVISIBLE);
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(video.getProgress());
imageViewPreview.setImageResource(R.drawable.video_preview);
break;
case Downloaded:
textViewStatus.setText("");
textViewDownload.setVisibility(View.INVISIBLE);
progressBar.setVisibility(View.GONE);
Bitmap thumbnail = video.getThumbnail();
if (thumbnail != null) {
imageViewPreview.setImageBitmap(video.getThumbnail());
}
break;
case Incomplete:
textViewStatus.setText(context.getString(R.string.incomplete));
textViewDownload.setVisibility(View.VISIBLE);
textViewDownload.setText(context.getString(R.string.download_again));
progressBar.setVisibility(View.GONE);
imageViewPreview.setImageResource(R.drawable.video_preview);
break;
case Deleted:
textViewStatus.setText(context.getString(R.string.deleted));
textViewDownload.setVisibility(View.VISIBLE);
textViewDownload.setText(context.getString(R.string.download_again));
progressBar.setVisibility(View.GONE);
imageViewPreview.setImageResource(R.drawable.video_preview);
break;
}
topView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onVideoClickListener.onVideoClick(video);
}
});
textViewDownload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onVideoClickListener.onDownloadClick(video);
}
});
}
}
}
|
C++
|
UTF-8
| 1,547 | 2.953125 | 3 |
[] |
no_license
|
//
// eliminarElemDecreciente.h
// EDA
//
// Created by Irene Martin berlanga on 21/05/2019.
// Copyright © 2019 Irene Martin berlanga. All rights reserved.
//
#ifndef eliminarElemDecreciente_h
#define eliminarElemDecreciente_h
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include "queue_eda.h"
template<typename T>
class eliminarElemCreciente : public queue<T>{
using Nodo = typename queue<T>::Nodo;
public:
void eliminar(){
Nodo* nodo_actual = this->prim;
Nodo* nodo_siguiente = nodo_actual->sig;
while(nodo_siguiente != nullptr){
if(nodo_siguiente->elem < nodo_actual->elem){
nodo_actual->sig = nodo_siguiente->sig;
nodo_siguiente = nodo_actual->sig;
//delete nodo_siguiente;
--this->nelems;
}else{
nodo_actual = nodo_siguiente;
nodo_siguiente = nodo_actual->sig;
}
}
}
void print(std::ostream & o = std::cout)const{
if(!this->empty()){
Nodo *nodo_actual = this->prim;
while(nodo_actual != nullptr){
o << nodo_actual->elem << ' ';
nodo_actual = nodo_actual->sig;
}
}
}
};
template <class T>
inline std::ostream & operator<<(std::ostream & out, eliminarElemCreciente<T> const& cola)
{
cola.print(out);
return out;
}
#endif /* eliminarElemDecreciente_h */
|
Markdown
|
UTF-8
| 8,440 | 2.984375 | 3 |
[] |
no_license
|
---
title: 千里馬計畫歷程分享 Part 1 - 準備申請
date: 2020-01-28 00:42:54
categories: [Exchange]
tags: [exchange, uchicago, usa]
---
我在 2019 年 5 月左右決定在博士生涯的最後一年利用科技部的千里馬計畫補助出國。 現在已經到了進到最後的準備步驟了。 我想最好將我中間過程的經歷與準備記錄下來,以幫助未來也想要申請補助出國去看看的博士生。
<!--more-->
## 計畫介紹
千里馬計畫目前的正式名稱是「科技部補助博士生赴國外研究」。 因此如果要去科技部網站搜尋的話,用正式名稱比較容易找到資料。
這個計畫簡單來說就是政府以非常寬鬆的條件提供一年 90 萬新台幣(2019 年以前是 60 萬)的補助,讓在台灣的博士生能夠出國到國外的研究機構進行交流與研究。 補助會先用借款的方式在出國前提撥給受補助人,然後回國之後依照實際在當地執行計畫的天數依比例計算該補助多少。 如果實際上借用的金額高於應該補助的金額,則需要將多領的部分歸還給政府。 例如實際上只待 300 天,那麼補助金額就是 (300 / 365 * 90) 萬。 不過除此之外這筆補助使用上沒有任何限制,而且金額在大部分的國家很夠用。 只要省吃儉用一點,就有很大機會不需要動用到自己的錢。 因此對想要出國的博士生來說算是實惠的補助。
那這個補助有什麼應盡義務嗎? 除了計畫結案時要繳交一份報告外,最重要的義務就是計畫結束後必須要回台灣完成學業。 相較於許多企業的補助會要求必須要去公司上班等等,這種條件基本上等於沒有條件。 所以我很推薦想要在博士生生涯出國看看的人申請。
2019 年計劃的 [申請說明網頁](https://www.most.gov.tw/sci/ch/detail?article_uid=b3d896f9-c70a-4bec-8fcb-e387b51b2a54&menu_id=6b4a4661-9126-4d0c-897a-4022c82114a9&content_type=P&view_mode=listView)
## 我怎麼會想申請呢?
我一開始得知這個計畫是來自於系上的一個博士生學長,他當時申請到京都的大學交換。 聽說之後,我就稍微研究一下,發現這個補助申請並沒有想像中困難,而且金額不小,對家裡不富裕的我來說算是很好的機會,於是就開始思考我是不是想出國看看呢?
做了很多考量之後,我最後認為最重要的因素就是想要脫離現在的舒適圈。 我在清華大學從大學一路念上來,包括碩士與博士已經待了將近十年的時間。 我從來都沒有跳脫這個環境,這樣我認為無論如何都對我未來很不利,而且思考的方式也許也缺乏變化。 我想要到其他環境親眼看看別人跟我們有何不同。 再來另一方面我覺得也需要出國去拓展一下人脈,大家常說多結交朋友絕對不是壞事。 無論以後打算往哪個方面繼續,人脈一定可以派得上用場的。
不過我最後決定要申請的時候已經有點晚了。 千里馬計畫是每年 6/1 開放申請到 7/31。 我決定要申請的時候已經五月中了。 因為準備申請資料也非常花費時間,包括要考英文檢定(如果以前沒考過的話)、聯絡國外機構取得同意函等等。 因此建議正在思考的人提早下決定,想要申請的人最好三月就開始準備。
## 申請需要的準備
申請千里馬根據 2019 年的規定需要準備以下資料:
1. 外國語文能力鑑定證明
- 關於能力鑑定證明有詳盡的 [規定](https://www.most.gov.tw/most/attachments/2ebfb38f-58ed-4a24-875b-77d3c5443e6c),每年可能會有些微的變化。 歷年來最大的不同在於取消最低門檻(例如托福需達總分 79 分)。
- 通常就是去講哪種語言的國家就要付哪種語言證明。 例如日本就日檢,美國就托福、雅思等等。
2. 國外研究機構或國外指導教授接受前往研究之同意函
- 需有國外機構負責人或指導教授簽名
3. 所長或博士指導教授出具之資格證明
- 千里馬說明網頁上有固定格式的文件,下載請老師簽名即可。
4. 所長或博士指導教授出具之推薦函
- 就是推薦信,請指導老師寫好並簽名後,掃描並請老師從他的科技部帳號上傳。
5. 大學、碩士及博士學程歷年成績單
- 學校提供的成績單。
- 這邊有個有趣的狀況是,因為我是碩士念到一半直攻博士,所以我同一份成績單內有碩士跟博士的修課成績。 這邊只要在成績單上註明哪些是碩士哪些是博士就沒有問題。
6. 國外研究計畫書
- 20 頁以內的研究計畫書。 之後另外說明。
更詳細的說明可以參考官方的 [作業要點](https://www.most.gov.tw/most/attachments/65ca5c42-9ebb-4325-b7e6-df44fd10a9f6) (注意這是 2019 年的作業要點)。
上面這些資料中,最需要提早準備的就是第 1 跟 2 項。 第 1 項是因為考試需要時間準備,還要等成績出來。 例如托福我花了一個月左右準備,然後兩週等成績出來。 第 2 項則是因為要看找不找得到收你的國外教授,可能需要跟好幾位教授面談,最後還需要請願意收的教授開同意函給你。 花費時間快的話可能一個禮拜搞定,久的話可能會弄到好幾個月。 我是運氣不錯不到一個月就搞定,不然可能就來不及申請。
另外要注意一點,雖然科技部寫說 7/31 截止,但實際上每個學校會有自己的繳交期限。 例如我們學校(清大)在 7/30 中午就截止了,建議問問學校的全球或國際事務處。
## 我的時間軸
以下紀錄從決定申請到現在為止發生的重要事件:
- 2019/5 月中旬 - 決定申請千里馬計畫
- 2019/6/1 - 科技部系統開放申請
- 2019/6/9 - 跟指導老師討論要前往哪一位教授的 lab
- 2019/6/12 - 報名 TOEFL iBT 考試
- 2019/6/29 - TOEFL iBT 應考
- 2019/7/8 - 決定要前往的實驗室與連絡上國外的教授
- 從研究要去哪間研究室到這步驟拖了點時間,因為當時正在忙著投一篇論文。 這也是為什麼要提早找教授,不然跟我一樣卡個論文 deadline 就可能會 delay。
- 2019/7/9 - TOEFL iBT 開放線上查成績(總成績:93)
- 2019/7/18 - 與國外教授線上面談
- 2019/7/30 - 收到國外教授的接受函(超驚險)
- 2019/7/30 - 送出申請,並由校內統合送出
- 2019/11/29 - 科技部官網公布 [通過名冊](https://www.most.gov.tw/folksonomy/detail?subSite=&l=ch&article_uid=342f7b32-5bc4-4885-9607-32d946c067cc&menu_id=d3c30297-bb63-44c5-ad30-38a65b203288)
- 2019/12/4 - 通知國外指導教授並開始申請 DS-2019 (申請美國簽證必備文件)
- 2019/12/26 - 參加芝加哥大學英文能力測驗 (APEA)
- 2020/1/7 - 收到芝加哥大學通知通過 APEA 測驗,並完成 DS-2019 申請
- 2020/1/16 - 收到 DS-2019,開始申請 J-1 Visa (交換生簽證)
- 2020/1/21 - 送出校內簽約資料,以申請補助款
- 這個需要付 DS-2019 的副本,加上我到 1/18 都不在台灣。 所以拖到這個時候才提出申請。
- 現在 (2020/1/28) - 正在申請 J-1 Visa 中
- 預計 2020/3/30 前抵達芝加哥大學
大家可以注意到我在 7/30 才拿到接受函,這顯示了提早開始接洽的重要性。 其實國外教授面談完不久就表明可以收我,可是我們後來發現芝加哥大學有額外的英文門檻,而且我的托福的口說成績不夠高。 這中間的時間都在跟該校的國際事務處確認我是否需要通過該門檻(因為該校的規定上寫的有點出入)。 結論是我還是要通過該門檻,可是也來不及考托福了,所以國外教授還是先給我接受函,但是在信上加上以下但書:
> ... assuming all internal requirements are satisfied for University of Chicago’s non-degree visting students (such as https://internationalaffairs.uchicago.edu/page/english-language-requirements).
後來科技部也接受了,代表只要有教授表明願意收我就好。 至於後來怎麼通過該校的英文門檻... 後來也不是用托福通過,而是參加該校的另一個測驗 (APEA),這點之後再做說明。
## 待續...
之後預計說明:我怎麼撰寫研究計畫書、怎麼準備托福、怎麼跟教授面談...
|
Java
|
UTF-8
| 925 | 2.390625 | 2 |
[] |
no_license
|
package my.edu.tarc.lab32registration;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements MyDateFragment.OnDateSelectedListener{
private Button buttonDOB;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonDOB = (Button)findViewById(R.id.buttonDOB);
}
public void showDatePickerDialog(View v) {
MyDateFragment newFragment = new MyDateFragment();
newFragment.show(getFragmentManager(), "datePicker");
//or newFragment.show(getSupportFragmentManager(), "datePicker");
}
@Override
public void onDateSelected(int year, int month, int day) {
buttonDOB.setText(day + "-"+ month + "-" + year);
}
}
|
C++
|
UTF-8
| 1,361 | 3.546875 | 4 |
[] |
no_license
|
#include "common/common.h"
pair<int,int> partion(int* array, int begin, int end, int v) {
int low = begin;
int high = end - 1;
int i = begin;
while (i <= high && low <= high) {
if (array[i] < v) {
if (i == low) {
++i;
} else {
swap(array[i], array[low]);
}
++low;
} else if (array[i] > v) {
swap(array[i], array[high]);
--high;
} else {
++i;
}
}
return make_pair(low, high);
}
int quick_selection(int* array, int len, int k) {
int begin = 0;
int end = len;
while (true) {
pair<int,int> tmp = partion(array, begin, end, array[k]);
if (k >= tmp.first && k <= tmp.second) {
return array[k];
} else {
if (tmp.first > k) {
end = tmp.first;
} else {
begin = tmp.second;
}
}
}
}
void test() {
int array[] = {1, 5, 2, 1, 4, 4, 5, 8, 9};
pair<int,int> res = partion(array, 0, sizeof(array) / sizeof(int), 4);
cout<<res.first<<" "<<res.second<<endl;
print(array, array + sizeof(array) / sizeof(int));
cout<<quick_selection(array, sizeof(array) / sizeof(int), 7);
print(array, array + sizeof(array) / sizeof(int));
}
int main() {
test();
}
|
C
|
UTF-8
| 3,415 | 3.65625 | 4 |
[] |
no_license
|
#include<stdio.h>
#include<stdlib.h>
typedef struct
{
int id ;
char name[50] , surname[50] , dept[20] ;
float cgpa ;
} student ;
struct Node
{
struct Node *left , *right ;
int height ;
student stu ;
} ;
int max( int a , int b)
{
return (a>b)?a:b ;
}
int height(struct Node *N)
{
if(N==NULL)
return 0 ;
return N->height ;
}
struct Node* newNode(student s)
{
struct Node *node = (struct Node*)malloc(sizeof(struct Node)) ;
node->left = NULL ;
node->right = NULL ;
node->height = 1 ;
node->stu = s ;
return node ;
}
struct Node *rightrotate(struct Node *y)
{
struct Node *x = y->left ;
struct Node *z = x->right ;
x->right = y ;
y->left = z ;
x->height = max(height(x->right) , height(x->left)) + 1 ;
y->height = max(height(y->right) , height(y->left)) + 1 ;
return x ;
}
struct Node *leftrotate(struct Node *y)
{
struct Node *x = y->right ;
struct Node *z = x->left ;
x->left = y ;
y->right = z ;
x->height = max(height(x->right) , height(x->left)) + 1 ;
y->height = max(height(y->right) , height(y->left)) + 1 ;
return x ;
}
int getBal(struct Node* N)
{
if(N==NULL)
return 0 ;
return (height(N->left) - height(N->right)) ;
}
void inorder(struct Node *root)
{
if(root!=NULL)
{
inorder(root->left) ;
printf("%d\t%s\t%s\t%s\t%f\n" , root->stu.id , root->stu.name , root->stu.surname , root->stu.dept , root->stu.cgpa) ;
inorder(root->right) ;
}
}
struct Node *insert(struct Node *node , student key)
{
if(node==NULL)
return(newNode(key)) ;
if(key.id < node->stu.id)
node->left = insert(node->left,key) ;
else if(key.id > node->stu.id)
node->right = insert(node->right,key) ;
else return node ;
node->height = 1 + max(height(node->left) , height(node->right)) ;
int balance = getBal(node) ;
if(balance>1 && key.id < node->left->stu.id)
return rightrotate(node) ;
if(balance<-1 && key.id>node->right->stu.id)
return leftrotate(node) ;
if(balance>1 && key.id > node->left->stu.id)
{
node->left = leftrotate(node->left) ;
return rightrotate(node) ;
}
if(balance<-1 && key.id<node->right->stu.id)
{
node->right = rightrotate(node->right) ;
return leftrotate(node) ;
}
return node ;
}
void search(struct Node* root , int key)
{
if(root!=NULL)
{
if(key < root->stu.id)
search(root->left , key) ;
else if(key > root->stu.id)
search(root->right , key) ;
else if( key == root->stu.id)
printf("%d\t%s\t%s\t%s\t%f\n" , root->stu.id , root->stu.name , root->stu.surname , root->stu.dept , root->stu.cgpa) ;
}
else
printf("Not found!\n") ;
}
int main()
{
struct Node *root = NULL ;
student s1 ;
int id , ch = 1;
while(1)
{
printf("\n1. Enter data\n2. InOrder Traversal\n3. Search\n4. Exit\nEnter your choice : ") ;
scanf("%d",&ch) ;
switch(ch)
{
case 1 :
printf("Enter data for student\n") ;
printf("Enter ID : ") ;
scanf("%d",&s1.id) ;
printf("Enter name : ") ;
scanf("%s",&s1.name) ;
printf("Enter surname : ") ;
scanf("%s",&s1.surname) ;
printf("Enter department : ") ;
scanf("%s",&s1.dept) ;
printf("Enter CGPA : ") ;
scanf("%f",&s1.cgpa) ;
root = insert(root,s1) ;
break ;
case 2 :
printf("Inorder traversal of AVL TREE : \n\n") ;
inorder(root) ;
break ;
case 3 :
printf("Enter ID : ") ;
scanf("%d",&id) ;
search(root , id) ;
break ;
case 4 :
exit(1) ;
}
}
return 0 ;
}
|
Markdown
|
UTF-8
| 20,260 | 2.59375 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
# DocuSign_eSign::WorkspacesApi
All URIs are relative to *https://www.docusign.net/restapi*
Method | HTTP request | Description
------------- | ------------- | -------------
[**create_workspace**](WorkspacesApi.md#create_workspace) | **POST** /v2/accounts/{accountId}/workspaces | Create a Workspace
[**create_workspace_file**](WorkspacesApi.md#create_workspace_file) | **POST** /v2/accounts/{accountId}/workspaces/{workspaceId}/folders/{folderId}/files | Creates a workspace file.
[**delete_workspace**](WorkspacesApi.md#delete_workspace) | **DELETE** /v2/accounts/{accountId}/workspaces/{workspaceId} | Delete Workspace
[**delete_workspace_folder_items**](WorkspacesApi.md#delete_workspace_folder_items) | **DELETE** /v2/accounts/{accountId}/workspaces/{workspaceId}/folders/{folderId} | Deletes workspace one or more specific files/folders from the given folder or root.
[**get_workspace**](WorkspacesApi.md#get_workspace) | **GET** /v2/accounts/{accountId}/workspaces/{workspaceId} | Get Workspace
[**get_workspace_file**](WorkspacesApi.md#get_workspace_file) | **GET** /v2/accounts/{accountId}/workspaces/{workspaceId}/folders/{folderId}/files/{fileId} | Get Workspace File
[**list_workspace_file_pages**](WorkspacesApi.md#list_workspace_file_pages) | **GET** /v2/accounts/{accountId}/workspaces/{workspaceId}/folders/{folderId}/files/{fileId}/pages | List File Pages
[**list_workspace_folder_items**](WorkspacesApi.md#list_workspace_folder_items) | **GET** /v2/accounts/{accountId}/workspaces/{workspaceId}/folders/{folderId} | List Workspace Folder Contents
[**list_workspaces**](WorkspacesApi.md#list_workspaces) | **GET** /v2/accounts/{accountId}/workspaces | List Workspaces
[**update_workspace**](WorkspacesApi.md#update_workspace) | **PUT** /v2/accounts/{accountId}/workspaces/{workspaceId} | Update Workspace
[**update_workspace_file**](WorkspacesApi.md#update_workspace_file) | **PUT** /v2/accounts/{accountId}/workspaces/{workspaceId}/folders/{folderId}/files/{fileId} | Update Workspace File Metadata
# **create_workspace**
> Workspace create_workspace(account_id, opts)
Create a Workspace
Creates a new workspace.
### Example
```ruby
# load the gem
require 'docusign_esign'
api_instance = DocuSign_eSign::WorkspacesApi.new
account_id = "account_id_example" # String | The external account number (int) or account ID Guid.
opts = {
workspace: DocuSign_eSign::Workspace.new # Workspace |
}
begin
#Create a Workspace
result = api_instance.create_workspace(account_id, opts)
p result
rescue DocuSign_eSign::ApiError => e
puts "Exception when calling WorkspacesApi->create_workspace: #{e}"
end
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**account_id** | **String**| The external account number (int) or account ID Guid. |
**workspace** | [**Workspace**](Workspace.md)| | [optional]
### Return type
[**Workspace**](Workspace.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
# **create_workspace_file**
> WorkspaceItem create_workspace_file(account_id, folder_id, workspace_id)
Creates a workspace file.
### Example
```ruby
# load the gem
require 'docusign_esign'
api_instance = DocuSign_eSign::WorkspacesApi.new
account_id = "account_id_example" # String | The external account number (int) or account ID Guid.
folder_id = "folder_id_example" # String | The ID of the folder being accessed.
workspace_id = "workspace_id_example" # String | Specifies the workspace ID GUID.
begin
#Creates a workspace file.
result = api_instance.create_workspace_file(account_id, folder_id, workspace_id)
p result
rescue DocuSign_eSign::ApiError => e
puts "Exception when calling WorkspacesApi->create_workspace_file: #{e}"
end
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**account_id** | **String**| The external account number (int) or account ID Guid. |
**folder_id** | **String**| The ID of the folder being accessed. |
**workspace_id** | **String**| Specifies the workspace ID GUID. |
### Return type
[**WorkspaceItem**](WorkspaceItem.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
# **delete_workspace**
> Workspace delete_workspace(account_id, workspace_id)
Delete Workspace
Deletes an existing workspace (logically).
### Example
```ruby
# load the gem
require 'docusign_esign'
api_instance = DocuSign_eSign::WorkspacesApi.new
account_id = "account_id_example" # String | The external account number (int) or account ID Guid.
workspace_id = "workspace_id_example" # String | Specifies the workspace ID GUID.
begin
#Delete Workspace
result = api_instance.delete_workspace(account_id, workspace_id)
p result
rescue DocuSign_eSign::ApiError => e
puts "Exception when calling WorkspacesApi->delete_workspace: #{e}"
end
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**account_id** | **String**| The external account number (int) or account ID Guid. |
**workspace_id** | **String**| Specifies the workspace ID GUID. |
### Return type
[**Workspace**](Workspace.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
# **delete_workspace_folder_items**
> delete_workspace_folder_items(account_id, folder_id, workspace_id, opts)
Deletes workspace one or more specific files/folders from the given folder or root.
### Example
```ruby
# load the gem
require 'docusign_esign'
api_instance = DocuSign_eSign::WorkspacesApi.new
account_id = "account_id_example" # String | The external account number (int) or account ID Guid.
folder_id = "folder_id_example" # String | The ID of the folder being accessed.
workspace_id = "workspace_id_example" # String | Specifies the workspace ID GUID.
opts = {
workspace_item_list: DocuSign_eSign::WorkspaceItemList.new # WorkspaceItemList |
}
begin
#Deletes workspace one or more specific files/folders from the given folder or root.
api_instance.delete_workspace_folder_items(account_id, folder_id, workspace_id, opts)
rescue DocuSign_eSign::ApiError => e
puts "Exception when calling WorkspacesApi->delete_workspace_folder_items: #{e}"
end
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**account_id** | **String**| The external account number (int) or account ID Guid. |
**folder_id** | **String**| The ID of the folder being accessed. |
**workspace_id** | **String**| Specifies the workspace ID GUID. |
**workspace_item_list** | [**WorkspaceItemList**](WorkspaceItemList.md)| | [optional]
### Return type
nil (empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
# **get_workspace**
> Workspace get_workspace(account_id, workspace_id)
Get Workspace
Retrives properties about a workspace given a unique workspaceId.
### Example
```ruby
# load the gem
require 'docusign_esign'
api_instance = DocuSign_eSign::WorkspacesApi.new
account_id = "account_id_example" # String | The external account number (int) or account ID Guid.
workspace_id = "workspace_id_example" # String | Specifies the workspace ID GUID.
begin
#Get Workspace
result = api_instance.get_workspace(account_id, workspace_id)
p result
rescue DocuSign_eSign::ApiError => e
puts "Exception when calling WorkspacesApi->get_workspace: #{e}"
end
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**account_id** | **String**| The external account number (int) or account ID Guid. |
**workspace_id** | **String**| Specifies the workspace ID GUID. |
### Return type
[**Workspace**](Workspace.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
# **get_workspace_file**
> get_workspace_file(account_id, file_id, folder_id, workspace_id, opts)
Get Workspace File
Retrieves a workspace file (the binary).
### Example
```ruby
# load the gem
require 'docusign_esign'
api_instance = DocuSign_eSign::WorkspacesApi.new
account_id = "account_id_example" # String | The external account number (int) or account ID Guid.
file_id = "file_id_example" # String | Specifies the room file ID GUID.
folder_id = "folder_id_example" # String | The ID of the folder being accessed.
workspace_id = "workspace_id_example" # String | Specifies the workspace ID GUID.
opts = {
is_download: "is_download_example", # String | When set to **true**, the Content-Disposition header is set in the response. The value of the header provides the filename of the file. Default is **false**.
pdf_version: "pdf_version_example" # String | When set to **true** the file returned as a PDF.
}
begin
#Get Workspace File
api_instance.get_workspace_file(account_id, file_id, folder_id, workspace_id, opts)
rescue DocuSign_eSign::ApiError => e
puts "Exception when calling WorkspacesApi->get_workspace_file: #{e}"
end
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**account_id** | **String**| The external account number (int) or account ID Guid. |
**file_id** | **String**| Specifies the room file ID GUID. |
**folder_id** | **String**| The ID of the folder being accessed. |
**workspace_id** | **String**| Specifies the workspace ID GUID. |
**is_download** | **String**| When set to **true**, the Content-Disposition header is set in the response. The value of the header provides the filename of the file. Default is **false**. | [optional]
**pdf_version** | **String**| When set to **true** the file returned as a PDF. | [optional]
### Return type
nil (empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
# **list_workspace_file_pages**
> PageImages list_workspace_file_pages(account_id, file_id, folder_id, workspace_id, opts)
List File Pages
Retrieves a workspace file as rasterized pages.
### Example
```ruby
# load the gem
require 'docusign_esign'
api_instance = DocuSign_eSign::WorkspacesApi.new
account_id = "account_id_example" # String | The external account number (int) or account ID Guid.
file_id = "file_id_example" # String | Specifies the room file ID GUID.
folder_id = "folder_id_example" # String | The ID of the folder being accessed.
workspace_id = "workspace_id_example" # String | Specifies the workspace ID GUID.
opts = {
count: "count_example", # String | The maximum number of results to be returned by this request.
dpi: "dpi_example", # String | Number of dots per inch for the resulting image. The default if not used is 94. The range is 1-310.
max_height: "max_height_example", # String | Sets the maximum height (in pixels) of the returned image.
max_width: "max_width_example", # String | Sets the maximum width (in pixels) of the returned image.
start_position: "start_position_example" # String | The position within the total result set from which to start returning values. The value **thumbnail** may be used to return the page image.
}
begin
#List File Pages
result = api_instance.list_workspace_file_pages(account_id, file_id, folder_id, workspace_id, opts)
p result
rescue DocuSign_eSign::ApiError => e
puts "Exception when calling WorkspacesApi->list_workspace_file_pages: #{e}"
end
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**account_id** | **String**| The external account number (int) or account ID Guid. |
**file_id** | **String**| Specifies the room file ID GUID. |
**folder_id** | **String**| The ID of the folder being accessed. |
**workspace_id** | **String**| Specifies the workspace ID GUID. |
**count** | **String**| The maximum number of results to be returned by this request. | [optional]
**dpi** | **String**| Number of dots per inch for the resulting image. The default if not used is 94. The range is 1-310. | [optional]
**max_height** | **String**| Sets the maximum height (in pixels) of the returned image. | [optional]
**max_width** | **String**| Sets the maximum width (in pixels) of the returned image. | [optional]
**start_position** | **String**| The position within the total result set from which to start returning values. The value **thumbnail** may be used to return the page image. | [optional]
### Return type
[**PageImages**](PageImages.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
# **list_workspace_folder_items**
> WorkspaceFolderContents list_workspace_folder_items(account_id, folder_id, workspace_id, opts)
List Workspace Folder Contents
Retrieves workspace folder contents, which can include sub folders and files.
### Example
```ruby
# load the gem
require 'docusign_esign'
api_instance = DocuSign_eSign::WorkspacesApi.new
account_id = "account_id_example" # String | The external account number (int) or account ID Guid.
folder_id = "folder_id_example" # String | The ID of the folder being accessed.
workspace_id = "workspace_id_example" # String | Specifies the workspace ID GUID.
opts = {
count: "count_example", # String | The maximum number of results to be returned by this request.
include_files: "include_files_example", # String | When set to **true**, file information is returned in the response along with folder information. The default is **false**.
include_sub_folders: "include_sub_folders_example", # String | When set to **true**, information about the sub-folders of the current folder is returned. The default is **false**.
include_thumbnails: "include_thumbnails_example", # String | When set to **true**, thumbnails are returned as part of the response. The default is **false**.
include_user_detail: "include_user_detail_example", # String | Set to **true** to return extended details about the user. The default is **false**.
start_position: "start_position_example", # String | The position within the total result set from which to start returning values.
workspace_user_id: "workspace_user_id_example" # String | If set, then the results are filtered to those associated with the specified userId.
}
begin
#List Workspace Folder Contents
result = api_instance.list_workspace_folder_items(account_id, folder_id, workspace_id, opts)
p result
rescue DocuSign_eSign::ApiError => e
puts "Exception when calling WorkspacesApi->list_workspace_folder_items: #{e}"
end
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**account_id** | **String**| The external account number (int) or account ID Guid. |
**folder_id** | **String**| The ID of the folder being accessed. |
**workspace_id** | **String**| Specifies the workspace ID GUID. |
**count** | **String**| The maximum number of results to be returned by this request. | [optional]
**include_files** | **String**| When set to **true**, file information is returned in the response along with folder information. The default is **false**. | [optional]
**include_sub_folders** | **String**| When set to **true**, information about the sub-folders of the current folder is returned. The default is **false**. | [optional]
**include_thumbnails** | **String**| When set to **true**, thumbnails are returned as part of the response. The default is **false**. | [optional]
**include_user_detail** | **String**| Set to **true** to return extended details about the user. The default is **false**. | [optional]
**start_position** | **String**| The position within the total result set from which to start returning values. | [optional]
**workspace_user_id** | **String**| If set, then the results are filtered to those associated with the specified userId. | [optional]
### Return type
[**WorkspaceFolderContents**](WorkspaceFolderContents.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
# **list_workspaces**
> WorkspaceList list_workspaces(account_id)
List Workspaces
Gets information about the Workspaces that have been created.
### Example
```ruby
# load the gem
require 'docusign_esign'
api_instance = DocuSign_eSign::WorkspacesApi.new
account_id = "account_id_example" # String | The external account number (int) or account ID Guid.
begin
#List Workspaces
result = api_instance.list_workspaces(account_id)
p result
rescue DocuSign_eSign::ApiError => e
puts "Exception when calling WorkspacesApi->list_workspaces: #{e}"
end
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**account_id** | **String**| The external account number (int) or account ID Guid. |
### Return type
[**WorkspaceList**](WorkspaceList.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
# **update_workspace**
> Workspace update_workspace(account_id, workspace_id, opts)
Update Workspace
Updates information about a specific workspace.
### Example
```ruby
# load the gem
require 'docusign_esign'
api_instance = DocuSign_eSign::WorkspacesApi.new
account_id = "account_id_example" # String | The external account number (int) or account ID Guid.
workspace_id = "workspace_id_example" # String | Specifies the workspace ID GUID.
opts = {
workspace: DocuSign_eSign::Workspace.new # Workspace |
}
begin
#Update Workspace
result = api_instance.update_workspace(account_id, workspace_id, opts)
p result
rescue DocuSign_eSign::ApiError => e
puts "Exception when calling WorkspacesApi->update_workspace: #{e}"
end
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**account_id** | **String**| The external account number (int) or account ID Guid. |
**workspace_id** | **String**| Specifies the workspace ID GUID. |
**workspace** | [**Workspace**](Workspace.md)| | [optional]
### Return type
[**Workspace**](Workspace.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
# **update_workspace_file**
> WorkspaceItem update_workspace_file(account_id, file_id, folder_id, workspace_id)
Update Workspace File Metadata
Updates workspace item metadata for one or more specific files/folders.
### Example
```ruby
# load the gem
require 'docusign_esign'
api_instance = DocuSign_eSign::WorkspacesApi.new
account_id = "account_id_example" # String | The external account number (int) or account ID Guid.
file_id = "file_id_example" # String | Specifies the room file ID GUID.
folder_id = "folder_id_example" # String | The ID of the folder being accessed.
workspace_id = "workspace_id_example" # String | Specifies the workspace ID GUID.
begin
#Update Workspace File Metadata
result = api_instance.update_workspace_file(account_id, file_id, folder_id, workspace_id)
p result
rescue DocuSign_eSign::ApiError => e
puts "Exception when calling WorkspacesApi->update_workspace_file: #{e}"
end
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**account_id** | **String**| The external account number (int) or account ID Guid. |
**file_id** | **String**| Specifies the room file ID GUID. |
**folder_id** | **String**| The ID of the folder being accessed. |
**workspace_id** | **String**| Specifies the workspace ID GUID. |
### Return type
[**WorkspaceItem**](WorkspaceItem.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
|
C++
|
UTF-8
| 955 | 3.765625 | 4 |
[] |
no_license
|
#include<bits/stdc++.h>
using namespace std;
struct node{
int data;
node *next;
};
void display(node *n){
while(n!=NULL)
{
cout<<n->data<<" ";
n = n->next;
}
}
void push(node **head_ref, int newData){
node *newNode = new node();
newNode -> data = newData;
newNode -> next = *head_ref;
*head_ref = newNode;
}
void append(node **head_ref, int newData) // append function is use for add new node in last node
{
node *newNode = new node();
newNode -> data = newData;
newNode -> next = NULL;
node *last = *head_ref;
if(*head_ref==NULL)
{
*head_ref = newNode;
return;
}
while(last -> next != NULL)
{
last = last -> next;
}
last -> next = newNode;
return;
}
int main()
{
node *head=NULL;
push(&head,5);
push(&head,4);
push(&head,3);
push(&head,2);
push(&head,1);
// 1 2 3 4 5
append(&head, 90);
display(head);
return 0;
}
|
Python
|
UTF-8
| 6,029 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env python3
import bpy
import numpy as np
import os
MIN_RAD = 0.4
DEC_PERC = 0.995
START_RAD = 0.5
class Path(object):
"""Creates a 3D path from input points"""
def __init__(self, points, title):
super(Path, self).__init__()
self.level = int(points[0][0])
self.points = points[1:]
self.title = title
dec_rad = START_RAD * (DEC_PERC ** self.level)
self.radius = max(MIN_RAD, dec_rad)
self.obj = None
def render_curve(self):
# data
coords = self.points
# create the Curve Datablock
curveData = bpy.data.curves.new('treeCurve', type='CURVE')
curveData.dimensions = '3D'
curveData.resolution_u = 2
curveData.use_fill_caps = True
#Add Bevel object
tor0refCirc = vecCircle("tor0refCirc", self.radius, 'CURVE')
curveData.bevel_object = tor0refCirc
#Add Taper Object
dec_perc = DEC_PERC ** len(self.points)
if (dec_perc * self.radius <= MIN_RAD):
dec_perc = MIN_RAD / self.radius
taper_obj = taperCurve(dec_perc)
curveData.taper_object = taper_obj
# map coords to spline
polyline = curveData.splines.new('NURBS')
polyline.use_endpoint_u = True
polyline.points.add(len(coords)-1)
for i, coord in enumerate(coords):
x,y,z = coord
polyline.points[i].co = (x, y, z, 1)
# create Object
curveOB = bpy.data.objects.new(self.title, curveData)
# attach to scene and validate context
scn = bpy.context.scene
scn.objects.link(curveOB)
scn.objects.active = curveOB
curveOB.select = True
self.obj = curveOB
def delete_default():
'''
Removes default objects from the scene.
'''
names = ['Cube', 'Icosphere', 'Sphere']
for name in names:
try:
bpy.data.objects[name].select = True
bpy.ops.object.delete()
except Exception:
pass
return
def save_blend(fn):
bpy.ops.wm.save_as_mainfile(filepath=fn)
return
def taperCurve(dec_perc):
bpy.ops.curve.primitive_nurbs_path_add(location=(0.0, 0.0, 0.0))
obj = bpy.context.active_object
obj.name = "taperCurve"
num_points = len(obj.data.splines[0].points)
inc = (1.0 - dec_perc) / num_points
for i in range(num_points):
co = obj.data.splines[0].points[i].co
obj.data.splines[0].points[i].co = (co[0], 1.0 - i*inc, 0.0, 1.0)
return obj
def vecCircle(name, radius, obj_type='MESH'):
num_verts = 8
bpy.ops.mesh.primitive_circle_add(vertices=num_verts, radius=radius)
obj = bpy.context.active_object
obj.name = name
if obj_type == 'CURVE':
bpy.ops.object.convert(target='CURVE', keep_original=False)
return obj
def export_stl(curves):
# get the current path and make a new folder for the exported meshes
path = bpy.path.abspath('//stlexport/')
if not os.path.exists(path):
os.makedirs(path)
# deselect all meshes
bpy.ops.object.select_all(action='DESELECT')
for curve in curves:
if curve.obj:
# select the object
curve.obj.select = True
print("exporting to stl ...")
# export object with its name as file name
fPath = str((path + curves[0].title + '.stl'))
bpy.ops.export_mesh.stl(filepath=fPath)
def make_single_path(filename):
points = np.loadtxt(filename)
if points.shape == (3,):
print("Hole found in mesh")
return None
with open("title.txt") as f:
content = f.readlines()
title = content[0] + "_growth"
P = Path(points, title)
P.render_curve()
return P
def join_all(curves):
# deselect all meshes
bpy.ops.object.select_all(action='DESELECT')
for curve in curves:
if curve.obj:
# select the object
curve.obj.select = True
#Convert to mesh
bpy.ops.object.convert(target='MESH')
#join all curves
bpy.ops.object.join()
return bpy.context.selected_objects[0]
def animate_all(curves):
#set duration and speed
frame_chunk = 0.5
max_level = max([(curve.level + len(curve.points)) for curve in curves])
duration = max_level * frame_chunk
# prepare a scene
scn = bpy.context.scene
scn.frame_start = 1
scn.frame_end = duration
for curve in curves:
animate(curve, frame_chunk)
def animate(curve, frame_chunk):
# deselect all objects
bpy.ops.object.select_all(action='DESELECT')
# select the object
curve.obj.select = True
start_frame = 1 + (curve.level*frame_chunk)
num_steps = len(curve.points)
bevel_chunk = 1.0 / num_steps
if (num_steps >= 3):
iter_list = [0, int(num_steps/2.0), int(num_steps) - 1]
else:
iter_list = range(int(num_steps))
for i in iter_list:
# move to frame
cur_fram = (i * frame_chunk) + start_frame
bpy.context.scene.frame_set(cur_fram)
curve.obj.data.bevel_factor_end = i * bevel_chunk
curve.obj.data.keyframe_insert(data_path="bevel_factor_end",frame=cur_fram)
def assign_materials(curves):
# Get material
mat = bpy.data.materials.get("Material")
if mat is None:
# create material
mat = bpy.data.materials.new(name="Material")
for curve in curves:
ob = curve.obj
# Assign it to object
if ob.data.materials:
# assign to 1st material slot
ob.data.materials[0] = mat
else:
# no slots
ob.data.materials.append(mat)
ob.active_material.diffuse_color = (0.093986, 0.386677, 0.8)
# ob.active_material.diffuse_color = (0.00810887, 0.661868, 0.0641863)
def main():
from time import time
t1 = time()
delete_default()
paths = []
for file in os.listdir("./growth_paths"):
if file.endswith(".txt"):
filename = os.path.join("./growth_paths", file)
path = make_single_path(filename)
if path != None:
paths.append(path)
print('\nAlg Time:',time()-t1,'\n\n')
#export File as stl
export_stl(paths)
# Add animation keyframes to belnder file
animate_all(paths)
assign_materials(paths)
#save blend file
blend_name = "./blend/" + paths[0].title + ".blend"
save_blend(blend_name)
print('\nTotal time:',time()-t1,'\n\n')
return 0;
if __name__ == '__main__':
main()
|
C#
|
UTF-8
| 473 | 2.96875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Euclidian3D
{
class Path
{
private readonly List<Point3D> points = new List<Point3D>();
public List<Point3D> Points
{
get { return points; }
}
public void Add(Point3D point)
{
points.Add(point);
}
public void Remove(Point3D point)
{
points.Remove(point);
}
}
}
|
C++
|
UTF-8
| 1,140 | 3.171875 | 3 |
[
"Apache-2.0"
] |
permissive
|
/**
* @class Score
* @brief The Score class encapsulates the functionality of a scoreboard in the Centipede Wars Game.
* @author Rashaad Cassim 1099797 and Jason Parry 1046955
* @file Score.h
*/
#ifndef SCORE_H
#define SCORE_H
#include "EventManager.h"
#include "entity.h"
/**
* An enum class to define player movements and user inputs.
* This allows the user inputs to be recorded by the EventManager.
*/
enum class entityShot{Mush,/*!< A mushroom has been destroyed */
Centi,/*!< A centipede segment has been destroyed */
Play,/*!< The player has been hit*/
DDT /*!< The DDT bomb has destroyed an Entity*/};
class Score
{
public:
/**
* @brief Default constructor.
*/
Score();
/**
* @brief Returns the Player object's current score
*/
int getScore()const;
/**
* @brief Updates the Score based on what Entity was hit.
* \see entityShot
* @param entities is the entity shot defined by the enum class entityShot.
*/
void updateScore(std::vector<entityShot> entities);
/**
* @brief Destructor.
*/
~Score();
private:
int _score=0;
};
#endif // SCORE_H
|
TypeScript
|
UTF-8
| 2,209 | 4.1875 | 4 |
[] |
no_license
|
// 1021. 删除最外层的括号
// 有效括号字符串为空 ("")、"(" + A + ")" 或 A + B,其中 A 和 B 都是有效的括号字符串,+ 代表字符串的连接。例如,"","()","(())()" 和 "(()(()))" 都是有效的括号字符串。
// 如果有效字符串 S 非空,且不存在将其拆分为 S = A+B 的方法,我们称其为原语(primitive),其中 A 和 B 都是非空有效括号字符串。
// 给出一个非空有效字符串 S,考虑将其进行原语化分解,使得:S = P_1 + P_2 + ... + P_k,其中 P_i 是有效括号字符串原语。
// 对 S 进行原语化分解,删除分解中每个原语字符串的最外层括号,返回 S 。
// 示例 1:
// 输入:"(()())(())"
// 输出:"()()()"
// 解释:
// 输入字符串为 "(()())(())",原语化分解得到 "(()())" + "(())",
// 删除每个部分中的最外层括号后得到 "()()" + "()" = "()()()"。
// 示例 2:
// 输入:"(()())(())(()(()))"
// 输出:"()()()()(())"
// 解释:
// 输入字符串为 "(()())(())(()(()))",原语化分解得到 "(()())" + "(())" + "(()(()))",
// 删除每个部分中的最外层括号后得到 "()()" + "()" + "()(())" = "()()()()(())"。
// 示例 3:
// 输入:"()()"
// 输出:""
// 解释:
// 输入字符串为 "()()",原语化分解得到 "()" + "()",
// 删除每个部分中的最外层括号后得到 "" + "" = ""。
// 提示:
// S.length <= 10000
// S[i] 为 "(" 或 ")"
// S 是一个有效括号字符串
function removeOuterParentheses(S: string): string {
let stack: string[] = [];
let result = '';
S.split('').forEach((str, index) => {
if(str === '('){
// 是左括号的时候,如果栈为空则一定是第一个元素,不需要拼接
if(stack.length) {
result += str;
}
stack.push(str);
}else{
stack.pop();
// 出栈了一个元素后,如果栈为空则表示当前的元素一定是和第一个元素想匹配的最后一个元素,不需要拼接
if(stack.length){
result += str;
}
}
});
return result;
};
|
Java
|
UTF-8
| 1,159 | 2.109375 | 2 |
[] |
no_license
|
package com.yaoguang.lib.appcommon.utils;
import android.app.ActionBar;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.view.View;
import android.widget.PopupWindow;
/**
* Created by Administrator on 2017/7/4 0004.
*/
public class PopupWindowUtils {
private PopupWindow mPopupWindow;
public void init(Activity context, View view) {
mPopupWindow = new PopupWindow(view, ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT, true);
mPopupWindow.setTouchable(true);
mPopupWindow.setOutsideTouchable(true);
mPopupWindow.setBackgroundDrawable(new BitmapDrawable(context.getResources(), (Bitmap) null));
}
public void showAsDropDown(View showAsDropDown) {
mPopupWindow.showAsDropDown(showAsDropDown);
}
public void showAsDropDown(View showAsDropDown, int x, int y) {
mPopupWindow.showAsDropDown(showAsDropDown, x, y);
}
public void onDestroyPopupView() {
if (mPopupWindow != null) {
mPopupWindow.dismiss();
mPopupWindow = null;
}
}
}
|
C++
|
UTF-8
| 3,956 | 2.671875 | 3 |
[] |
no_license
|
/********************************************************************************
* *
* THERMINATOR 2: THERMal heavy-IoN generATOR 2 *
* *
* Version: *
* Release, 2.0.3, 1 February 2011 *
* *
* Authors: *
* Mikolaj Chojnacki (Mikolaj.Chojnacki@ifj.edu.pl) *
* Adam Kisiel (kisiel@if.pw.edu.pl) *
* Wojciech Broniowski (Wojciech.Broniowski@ifj.edu.pl) *
* Wojciech Florkowski (Wojciech.Florkowski@ifj.edu.pl) *
* *
* Project homepage: *
* http://therminator2.ifj.edu.pl/ *
* *
* For the detailed description of the program and further references *
* to the description of the model please refer to *
* http://arxiv.org/abs/1102.0273 *
* *
* This code can be freely used and redistributed. However if you decide to *
* make modifications to the code, please, inform the authors. *
* Any publication of results obtained using this code must include the *
* reference to arXiv:1102.0273 and the published version of it, when *
* available. *
* *
********************************************************************************/
#ifndef _TH2_ENERGY_H_
#define _TH2_ENERGY_H_
#include "Vector3D.h"
class Energy
{
public:
Energy();
~Energy();
int GetEnergyType() const;
double GetEnergy() const;
double GetEnergy(double aX, double aY, double aZ) const;
void SetEnergy(double aEnergy);
void SetEnergy(Vector3D* aEnergy);
private:
int mEnergyType;
double mEnergyConst;
Vector3D* mEnergyVar;
};
#endif
/*! @file Energy.h
* @brief Definition of Energy class. Gives the local energy density @f$ \varepsilon @f$.
*/
/*! @class Energy
* @brief Class gives the local energy density @f$ \varepsilon @f$.
*
* If SetEnergy() is called with a Vector3D object it will return energy density at @f$ \varepsilon(x,y,z) @f$
* in other case it will return a constant value of energy density.
*
* @fn Energy::Energy()
* @brief Default constructor.
*
* @fn Energy::~Energy()
* @brief Destructor.
*
* @fn int Energy::GetEnergyType() const
* @brief Get the type of energy density stored.
* @retval 0 constant, @f$ \varepsilon = const @f$
* @retval 1 variable, @f$ \varepsilon = \varepsilon(x,y,z) @f$
* @retval -1 unknown, @f$ \varepsilon = 0 @f$
*
* @fn double Energy::GetEnergy() const
* @brief Returns constant energy density value
*
* @fn double Energy::GetEnergy(double aX, double aY, double aZ) const
* @brief Returns energy density as a function of <b>x</b>,<b>y</b> and <b>z</b>
* @param [in] aX x-coordinate
* @param [in] aY y-coordinate
* @param [in] aZ z-coordinate
*
* @fn void Energy::SetEnergy(double aEnergy)
* @brief Sets the energy density type to constant.
* @param [in] aEnergy constant energy density value
*
* @fn void Energy::SetEnergy(Vector3D* aEnergy)
* @brief Sets the energy density type to variable.
* @param [in] aEnergy pointer to Vector3D object with the energy density data
*/
|
SQL
|
UTF-8
| 1,151 | 3.5625 | 4 |
[] |
no_license
|
select
tdl.TX_ID as CHARGE_ID
,cast(tdl.ORIG_SERVICE_DATE as date) as SERVICE_DATE
,cast(tdl.POST_DATE as date) as POST_DATE
,sa.RPT_GRP_TEN as REGION_ID
,upper(sa.NAME) as REGION
,loc.LOC_ID
,loc.LOC_NAME
,dep.DEPARTMENT_ID
,dep.DEPARTMENT_NAME
,eap.PROC_CODE as CPT_CODE
,eap.PROC_NAME as CPT_DESCRIPTION
,ser_bill.PROV_NAME as BILLING_PROVIDER
,ser_perf.PROV_NAME as SERVICE_PROVIDER
,tdl.AMOUNT as CHARGE_AMT
,tdl.PROCEDURE_QUANTITY as UNITS
from clarity_tdl_tran tdl
left join CLARITY_EAP eap on eap.PROC_ID = tdl.PROC_ID
left join ARPB_TRANSACTIONS arpb_tx on arpb_tx.TX_ID = tdl.TX_ID
left join CLARITY_DEP dep on dep.DEPARTMENT_ID = tdl.DEPT_ID
left join CLARITY_LOC loc on loc.LOC_ID = tdl.LOC_id
left join ZC_LOC_RPT_GRP_10 sa on sa.RPT_GRP_TEN = loc.RPT_GRP_TEN
left join CLARITY_SER ser_bill on ser_bill.PROV_ID = tdl.BILLING_PROVIDER_ID
left join CLARITY_SER ser_perf on ser_perf.PROV_ID = tdl.PERFORMING_PROV_ID
where tdl.proc_id in
(30779
,23656
,23658
,23660
,23662
,23664)
and tdl.detail_type = 1
and orig_service_Date >= '1/1/2018'
and arpb_tx.VOID_DATE is null
and loc.RPT_GRP_TEN in (1,11,13,16,17,18,19)
order by tdl.TX_ID
|
Python
|
UTF-8
| 2,131 | 2.734375 | 3 |
[
"MIT"
] |
permissive
|
"""
mbtileserver.py
===============
A minimal Flask application for serving map tiles from an MBTiles file.
Quick Usage:
MBTILES_PATH=/path/to/my.mbtiles python mbtileserver.py
Copyright 2013 Evan Friis
License: MIT
"""
from flask import Flask, g, abort, Blueprint, current_app
from flask.ext.cache import Cache
import os
import sqlite3
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO # NOQA
frontend = Blueprint('frontend', __name__)
cache = Cache()
@frontend.before_request
def before_request():
"""Ensure database is connected for each request """
g.db = sqlite3.connect(current_app.config['MBTILES_PATH'])
@frontend.teardown_request
def teardown_request(exception):
"""Cleanup database afterwards """
if hasattr(g, 'db'):
g.db.close()
@frontend.route("/<int:zoom>/<int:column>/<int:row>.<ext>")
@cache.cached(timeout=300)
def query_tile(zoom, column, row, ext):
"""Get a tile from the MBTiles database """
query = 'SELECT tile_data FROM tiles '\
'WHERE zoom_level = ? AND tile_column = ? AND tile_row = ?;'
cur = g.db.execute(query, (zoom, column, row))
results = cur.fetchall()
if not results:
abort(404)
the_image = results[0][0]
mimeType = "image/png"
if ext == "jpg":
mimeType = 'image/jpeg'
elif ext == "pbf":
mimeType = "application/x-protobuf"
return current_app.response_class(
StringIO(the_image).read(),
mimetype=mimeType
)
def create_app(mbtiles=None, cache_config=None):
"""Initialize the application with a given configuration.
mbtiles must be a path to the MBTiles sqlite file.
"""
app = Flask(__name__)
app.config.update({
'MBTILES_PATH': mbtiles
})
app.register_blueprint(frontend)
cache.init_app(app, config=cache_config)
return app
if __name__ == "__main__":
app = create_app(
mbtiles=os.environ['MBTILES_PATH'],
cache_config={
'CACHE_TYPE': 'simple',
}
)
app.run(debug=True, port=int(os.environ.get('MBTILES_PORT', 41815)))
|
C#
|
UTF-8
| 6,231 | 3.59375 | 4 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Drawing;
namespace NWSELib.common
{
/// <summary>
/// 工具类
/// Utility
/// </summary>
public static class Utility
{
public static Random rng = new Random();
/// <summary>
/// 字符串转double集合
/// str to List<double>
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static List<double> parse(String s)
{
if (s == null || s.Trim() == "") return new List<double>();
return s.Split(',').ToList().ConvertAll(x => Double.Parse(x)).ToList<double>();
}
public static string toString(List<int> values, String sep = ",")
{
if (values == null || values.Count <= 0) return "";
return values.ConvertAll(v => v.ToString()).Aggregate((x, y) => x + sep + y);
}
public static string toString(List<double> values,String sep =",",int precise=3)
{
if (values == null || values.Count <= 0) return "";
else if (values.Count == 1) return String.Format("{0:f"+ precise.ToString()+"}", values[0]);
else return values.ConvertAll(v => String.Format("{0:f"+ precise.ToString()+"}", v)).Aggregate((a, b) => a + sep + b);
}
/// <summary>
/// 判断两个集合是否完全想等
/// Wether two sets are equal.
/// </summary>
/// <param name="v1"></param>
/// <param name="v2"></param>
/// <returns></returns>
public static bool equals<T>(List<T> v1,List<T> v2)
{
for(int i=0;i<v1.Count;i++)
{
if (!v2.Exists(v => v.Equals(v1[i]))) return false;
}
for(int i=0;i<v2.Count;i++)
{
if (!v1.Exists(v => v.Equals(v2[i]))) return false;
}
return true;
}
public static void shuffle<T>(this List<T> list)
{
if (list == null) return;
List<int> index = new List<int>();
for (int i = 0; i < list.Count; i++) index.Add(i);
for(int i=0;i<list.Count;i++)
{
int t = rng.Next(0, index.Count);
T temp = list[i];
list[i] = list[index[t]];
list[index[t]] = temp;
index.RemoveAt(t);
}
}
/// <summary>
/// argmax
/// </summary>
/// <param name="values"></param>
/// <returns></returns>
public static int argmax(this List<double> values)
{
if (values == null || values.Count <= 0) return -1;
if (values.All(v => double.IsNaN(v))) return -1;
if (values.Count == 1) return 0;
double max = values.FindAll(v => !double.IsNaN(v)).Max();
for(int i=0;i<values.Count;i++)
{
if (max == values[i]) return i;
}
return 0;
}
/// <summary>
/// argmin
/// </summary>
/// <param name="values"></param>
/// <returns></returns>
public static int argmin(this List<double> values)
{
double min = values.FindAll(v=>!double.IsNaN(v)).Min();
for (int i = 0; i < values.Count; i++)
{
if (min == values[i]) return i;
}
return 0;
}
public static List<int> argsort(this List<double> values)
{
List<double> temp = new List<double>(values);
List<int> index = new List<int>();
for (int i = 0; i < temp.Count; i++)
index.Add(i);
for(int i=0;i< temp.Count;i++)
{
for(int j=i+1;j< temp.Count;j++)
{
if(double.IsNaN(temp[i]) || temp[i] > temp[j])
{
double t = temp[i];
temp[i] = temp[j];
temp[j] = t;
int k = index[i];
index[i] = index[j];
index[j] = k;
}
}
}
return index;
}
public static int IndexOf<T>(this List<T> list,Predicate<T> p)
{
if (list == null || list.Count <= 0) return -1;
for(int i=0;i<list.Count;i++)
{
if (p(list[i])) return i;
}
return -1;
}
/// <summary>
/// 给定概率,计算对应的x值
/// </summary>
/// <param name="mean"></param>
/// <param name="variance"></param>
/// <param name="prob"></param>
/// <returns></returns>
public static double[] getGaussianByProb(double mean,double variance,double prob)
{
double t1 = System.Math.Log(System.Math.Sqrt(2 * System.Math.PI * variance)* prob)
* -2 * variance;
double t2 = Math.Sqrt(t1);
double t3 = -t2;
t2 += mean;
t3 += mean;
return t2 < t3 ? new double[] { t2,t3}: new double[] { t3,t2};
}
internal static bool intersection<T>(List<T> l1, List<T> l2)
{
for(int i=0;i<l1.Count;i++)
{
for(int j = 0;j<l2.Count;j++)
{
if (l1[i].Equals(l2[j])) return true;
}
}
return false;
}
/// <summary>
/// v1是否全部包含v2
/// </summary>
/// <param name="v1"></param>
/// <param name="v2"></param>
/// <returns></returns>
public static bool ContainsAll(List<int> v1, List<int> v2)
{
if (v1 == null || v1.Count <= 0) return false;
if (v2 == null || v2.Count <= 0) return false;
for(int i=0;i<v2.Count;i++)
{
if (!v1.Contains(v2[i])) return false;
}
return true;
}
}
}
|
Java
|
UTF-8
| 3,876 | 2.140625 | 2 |
[] |
no_license
|
package com.morningglory.basic.webservice.ws;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* <p>moMessageResDetail complex type的 Java 类。
*
* <p>以下模式片段指定包含在此类中的预期内容。
*
* <pre>
* <complexType name="moMessageResDetail">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="content" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="demo" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="phoneNumber" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="revTime" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/>
* <element name="subCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "moMessageResDetail", propOrder = {
"content",
"demo",
"phoneNumber",
"revTime",
"subCode"
})
public class MoMessageResDetail {
protected String content;
protected String demo;
protected String phoneNumber;
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar revTime;
protected String subCode;
/**
* 获取content属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String getContent() {
return content;
}
/**
* 设置content属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setContent(String value) {
this.content = value;
}
/**
* 获取demo属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String getDemo() {
return demo;
}
/**
* 设置demo属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDemo(String value) {
this.demo = value;
}
/**
* 获取phoneNumber属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String getPhoneNumber() {
return phoneNumber;
}
/**
* 设置phoneNumber属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPhoneNumber(String value) {
this.phoneNumber = value;
}
/**
* 获取revTime属性的值。
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getRevTime() {
return revTime;
}
/**
* 设置revTime属性的值。
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setRevTime(XMLGregorianCalendar value) {
this.revTime = value;
}
/**
* 获取subCode属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String getSubCode() {
return subCode;
}
/**
* 设置subCode属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSubCode(String value) {
this.subCode = value;
}
}
|
Python
|
UTF-8
| 3,592 | 2.5625 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
from unittest import TestCase
from nose.tools import assert_equal, assert_raises, assert_list_equal
from ir_profile_tracker.models import Member, SR, RaceType
class TestSR(TestCase):
def setUp(self):
self.sr = SR(4365)
def test_str(self):
assert_equal(str(self.sr), "B3.65")
def test_parse_from_int(self):
self.sr.parse_from_int(5499)
assert_equal(self.sr.licence_class, 'A')
assert_equal(self.sr.number, 4.99)
def test_parse_licence_wrong_value_raise_exception(self):
with assert_raises(ValueError):
self.sr.parse_from_int(8499)
def test_wrong_number_raise_exception(self):
with assert_raises(ValueError):
self.sr.parse_from_int(8599)
def test_licence_as_number(self):
assert_equal(self.sr.licence_as_number, 4365)
class TestMember(TestCase):
def setUp(self):
self.member = Member(custid=2020, name="John Doe")
def test_str(self):
assert_equal(self.member.__str__(), "John Doe - 2020")
def test_update_sr_wrong_value(self):
with assert_raises(ValueError):
self.member.update_sr(RaceType.Oval, 9268)
def test_update_irating_wrong_value(self):
with assert_raises(ValueError):
self.member.update_irating(RaceType.Oval, 3750.25)
def test_road_ir_property(self):
value = 3000
self.member.update_irating(RaceType.Road, value)
assert_equal(self.member.road_irating, value)
def test_droad_ir_property(self):
value = 3800
self.member.update_irating(RaceType.Dirt_Road, value)
assert_equal(self.member.dRoad_irating, value)
def test_oval_ir_property(self):
value = 500
self.member.update_irating(RaceType.Oval, value)
assert_equal(self.member.oval_irating, value)
def test_doval_ir_property(self):
value = 1800
self.member.update_irating(RaceType.Dirt_Oval, value)
assert_equal(self.member.dOval_irating, value)
def test_road_sr_property(self):
value = 5499
self.member.update_sr(RaceType.Road, value)
assert_equal(self.member.road_sr.number, 4.99)
assert_equal(self.member.road_sr.licence_class, 'A')
def test_droad_sr_property(self):
value = 5475
self.member.update_sr(RaceType.Dirt_Road, value)
assert_equal(self.member.dRoad_sr.number, 4.75)
assert_equal(self.member.dRoad_sr.licence_class, 'A')
def test_oval_sr_property(self):
value = 2222
self.member.update_sr(RaceType.Oval, value)
assert_equal(self.member.oval_sr.number, 2.22)
assert_equal(self.member.oval_sr.licence_class, 'D')
def test_doval_sr_property(self):
value = 7350
self.member.update_sr(RaceType.Dirt_Oval, value)
assert_equal(self.member.dOval_sr.number, 3.50)
assert_equal(self.member.dOval_sr.licence_class, 'PRO_WC')
def test_irating_as_dict(self):
ir_expected = [1000, 2500, 3850, 6200]
for item in range(0, 4):
self.member.update_irating(RaceType(item+1), ir_expected[item])
values = [item for item in self.member.irating_as_dict().values()]
assert_list_equal(ir_expected, values)
def test_sr_as_dict(self):
sr_expected = [2342, 4365, 5499, 2128]
for item in range(0, 4):
self.member.update_sr(RaceType(item+1), sr_expected[item])
values = [item.licence_as_number for item in self.member.sr_as_dict().values()]
assert_list_equal(sr_expected, values)
|
Go
|
UTF-8
| 2,277 | 2.875 | 3 |
[] |
no_license
|
package models
import (
"github.com/jinzhu/gorm"
"github.com/lionelritchie29/staem-backend/database"
"time"
)
type GameTag struct {
ID uint `gorm:"primaryKey"`
Name string
IsAdult bool
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt *time.Time `gorm:"index"`
}
func init() {
db := database.GetInstance()
db.DropTableIfExists(&GameTag{})
db.AutoMigrate(&GameTag{})
p := &GameTag{}
p.seed(db)
}
func (p *GameTag) seed(db *gorm.DB) {
db.Create(&GameTag{
Name: "Building",
IsAdult: false,
CreatedAt: time.Time{},
UpdatedAt: time.Time{},
DeletedAt: nil,
})
db.Create(&GameTag{
Name: "Sandbox",
IsAdult: false,
CreatedAt: time.Time{},
UpdatedAt: time.Time{},
DeletedAt: nil,
})
db.Create(&GameTag{
Name: "Simulation",
IsAdult: false,
CreatedAt: time.Time{},
UpdatedAt: time.Time{},
DeletedAt: nil,
})
db.Create(&GameTag{
Name: "Indie",
IsAdult: false,
CreatedAt: time.Time{},
UpdatedAt: time.Time{},
DeletedAt: nil,
})
db.Create(&GameTag{
Name: "Funny",
IsAdult: false,
CreatedAt: time.Time{},
UpdatedAt: time.Time{},
DeletedAt: nil,
})
db.Create(&GameTag{
Name: "War",
IsAdult: false,
CreatedAt: time.Time{},
UpdatedAt: time.Time{},
DeletedAt: nil,
})
db.Create(&GameTag{
Name: "Strategy",
IsAdult: false,
CreatedAt: time.Time{},
UpdatedAt: time.Time{},
DeletedAt: nil,
})
db.Create(&GameTag{
Name: "Violence",
IsAdult: true,
CreatedAt: time.Time{},
UpdatedAt: time.Time{},
DeletedAt: nil,
})
db.Create(&GameTag{
Name: "Gore",
IsAdult: true,
CreatedAt: time.Time{},
UpdatedAt: time.Time{},
DeletedAt: nil,
})
db.Create(&GameTag{
Name: "Nudity",
IsAdult: true,
CreatedAt: time.Time{},
UpdatedAt: time.Time{},
DeletedAt: nil,
})
db.Create(&GameTag{
Name: "Multiplayer",
IsAdult: false,
CreatedAt: time.Time{},
UpdatedAt: time.Time{},
DeletedAt: nil,
})
db.Create(&GameTag{
Name: "Open World",
IsAdult: false,
CreatedAt: time.Time{},
UpdatedAt: time.Time{},
DeletedAt: nil,
})
db.Create(&GameTag{
Name: "Single Player",
IsAdult: false,
CreatedAt: time.Time{},
UpdatedAt: time.Time{},
DeletedAt: nil,
})
}
|
Java
|
UTF-8
| 835 | 1.890625 | 2 |
[] |
no_license
|
package com.mindtree.mindtreeemployeesapp.exception.service.custom;
public class MindtreeEmployeesAppException extends Exception {
private static final long serialVersionUID = -4574959786639190582L;
public MindtreeEmployeesAppException() {
// TODO Auto-generated constructor stub
}
public MindtreeEmployeesAppException(String arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
public MindtreeEmployeesAppException(Throwable arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
public MindtreeEmployeesAppException(String arg0, Throwable arg1) {
super(arg0, arg1);
// TODO Auto-generated constructor stub
}
public MindtreeEmployeesAppException(String arg0, Throwable arg1, boolean arg2, boolean arg3) {
super(arg0, arg1, arg2, arg3);
// TODO Auto-generated constructor stub
}
}
|
C#
|
UTF-8
| 27,661 | 2.984375 | 3 |
[] |
no_license
|
using System;
using System.Data;
using CrudUsuarios.Entities;
using CrudUsuarios.Services;
namespace CrudUsuarios {
class Program {
static void Main(string[] args) {
BD banco = new BD();
int? controlePrincipal = null;
int? controleSecundario = null;
while (controlePrincipal != 0) {
Console.Clear();
Console.WriteLine("*********** Menu Inicial ***********");
Console.WriteLine();
Console.WriteLine("1 - Acessar Ambiente de Usuários");
Console.WriteLine("2 - Acessar Ambiente de Clientes");
Console.WriteLine("0 - Sair do Sistema");
Console.Write("Escolha uma opção: ");
controlePrincipal = int.Parse(Console.ReadLine());
controleSecundario = null;
switch (controlePrincipal) {
case 1:
while (controleSecundario != 0 && controleSecundario != 9) {
Console.Clear();
Console.WriteLine("*********** Menu de Usuários ***********");
Console.WriteLine();
Console.WriteLine("1 - Inserir Usuário");
Console.WriteLine("2 - Atualizar Usuário");
Console.WriteLine("3 - Remover Usuário");
Console.WriteLine("4 - Buscar Usuário");
Console.WriteLine("5 - Listar Usuários");
Console.WriteLine("9 - Voltar para o Menu Inicial");
Console.WriteLine("0 - Sair do Sistema");
Console.Write("Escolha uma opção: ");
controleSecundario = int.Parse(Console.ReadLine());
int retorno = 0;
switch (controleSecundario) {
case 1:
while (retorno == 0) {
Console.Clear();
Console.WriteLine("*********** Menu de Inserção de Usuários ***********");
Console.WriteLine();
Console.Write("Nome: ");
string nome = Console.ReadLine();
Console.Write("E-mail: ");
string email = Console.ReadLine();
Console.Write("Setor: ");
string setor = Console.ReadLine();
Console.Write("RG: ");
string rg = Console.ReadLine();
Console.Write("CPF: ");
string cpf = Console.ReadLine();
Usuario usuario = new Usuario(nome, email, setor, rg, cpf);
string query = "insert into usuario (nome, email, setor, rg, cpf) " +
"Values(" +
"'" + usuario.Nome + "', " +
"'" + usuario.Email + "', " +
"'" + usuario.Setor + "', " +
"'" + usuario.Rg + "', " +
"'" + usuario.Cpf + "'" +
")";
retorno = banco.Set(query);
if (retorno >= 1) {
Console.WriteLine();
Console.WriteLine("Usuário inserido com sucesso! Pressione Enter para continuar");
Console.ReadLine();
} else {
Console.WriteLine();
Console.WriteLine("Ocorreu um erro ao inserir o usuário, deseja tentar novamente? (0 = Sim, 1 = Não)");
retorno = int.Parse(Console.ReadLine());
}
}
break;
case 2:
retorno = 0;
while (retorno == 0) {
Console.Clear();
Console.WriteLine("*********** Menu de Atualização de Usuários ***********");
Console.WriteLine();
Console.Write("Digite o CPF do usuário que deseja atualizar: ");
string cpf = Console.ReadLine();
Console.Write("Nome: ");
string nome = Console.ReadLine();
Console.Write("E-mail: ");
string email = Console.ReadLine();
Console.Write("Setor: ");
string setor = Console.ReadLine();
Console.Write("RG: ");
string rg = Console.ReadLine();
Usuario usuario = new Usuario(nome, email, setor, rg, cpf);
string query = "update usuario " +
"set " +
"nome = '" + usuario.Nome + "', " +
"email = '" + usuario.Email + "', " +
"setor = '" + usuario.Setor + "', " +
"rg = '" + usuario.Rg + "'" +
"WHERE cpf = '" + usuario.Cpf + "';";
retorno = banco.Set(query);
if (retorno >= 1) {
Console.WriteLine();
Console.WriteLine("Usuário atualizado com sucesso! Pressione Enter para continuar");
Console.ReadLine();
} else {
Console.WriteLine();
Console.WriteLine("Ocorreu um erro ao atualizar o usuário, deseja tentar novamente? (0 = Sim, 1 = Não)");
retorno = int.Parse(Console.ReadLine());
}
}
break;
case 3:
retorno = 0;
while (retorno == 0) {
Console.Clear();
Console.WriteLine("*********** Menu de Remoção de Usuários ***********");
Console.WriteLine();
Console.Write("Digite o CPF do usuário que deseja remover: ");
string cpf = Console.ReadLine();
string query = "delete from usuario where cpf = '" + cpf + "'";
retorno = banco.Set(query);
if (retorno >= 1) {
Console.WriteLine();
Console.WriteLine("Usuário removido com sucesso! Pressione Enter para continuar");
Console.ReadLine();
} else {
Console.WriteLine();
Console.WriteLine("Ocorreu um erro ao remover o usuário, deseja tentar novamente? (0 = Sim, 1 = Não)");
retorno = int.Parse(Console.ReadLine());
}
}
break;
case 4:
retorno = 0;
while (retorno == 0) {
Console.Clear();
Console.WriteLine("*********** Menu de Consulta de Usuários ***********");
Console.WriteLine();
Console.Write("Digite o CPF do usuário que deseja buscar: ");
string cpf = Console.ReadLine();
string query = "select nome, email, setor, rg, cpf " +
"from usuario " +
"where cpf = '" + cpf + "';";
DataTable table = banco.Get(query);
if (table.Rows.Count > 0 && table != null) {
foreach (DataRow row in table.Rows) {
Console.WriteLine("Nome: " + row["nome"].ToString());
Console.WriteLine("Email: " + row["email"].ToString());
Console.WriteLine("Setor: " + row["setor"].ToString());
Console.WriteLine("RG: " + row["rg"].ToString());
Console.WriteLine("CPF: " + row["cpf"].ToString());
Console.WriteLine();
}
} else {
Console.WriteLine("Não há nenhum registro na tabela. Pressione enter para continuar");
Console.ReadLine();
retorno = 1;
}
Console.WriteLine();
Console.WriteLine("Deseja buscar outro usuário? (0 = Sim, 1 = Não)");
retorno = int.Parse(Console.ReadLine());
}
break;
case 5:
retorno = 0;
while (retorno == 0) {
Console.Clear();
Console.WriteLine("*********** Listagem de Usuários ***********");
Console.WriteLine();
string query = "SELECT * FROM usuario";
DataTable table = banco.Get(query);
if (table.Rows.Count > 0 && table != null) {
foreach (DataRow row in table.Rows) {
Console.WriteLine("Nome: " + row["nome"].ToString());
Console.WriteLine("Email: " + row["email"].ToString());
Console.WriteLine("Setor: " + row["setor"].ToString());
Console.WriteLine("RG: " + row["rg"].ToString());
Console.WriteLine("CPF: " + row["cpf"].ToString());
Console.WriteLine();
}
} else {
Console.WriteLine("Não há nenhum registro na tabela. Pressione enter para continuar");
Console.ReadLine();
retorno = 1;
}
Console.WriteLine();
Console.WriteLine("Deseja listar novamente? (0 = Sim, 1 = Não)");
retorno = int.Parse(Console.ReadLine());
}
break;
case 0:
controlePrincipal = 0;
break;
case 9:
controlePrincipal = null;
break;
default:
Console.WriteLine();
Console.WriteLine("Opção inválida tente novamente");
break;
}
}
break;
case 2:
while (controleSecundario != 0 && controleSecundario != 9) {
Console.Clear();
Console.WriteLine("*********** Menu de Clientes ***********");
Console.WriteLine();
Console.WriteLine("1 - Inserir Cliente");
Console.WriteLine("2 - Atualizar Cliente");
Console.WriteLine("3 - Remover Cliente");
Console.WriteLine("4 - Buscar Cliente");
Console.WriteLine("5 - Listar Clientes");
Console.WriteLine("9 - Voltar para o menu anterior");
Console.WriteLine("0 - Sair do Sistema");
Console.Write("Escolha uma opção: ");
controleSecundario = int.Parse(Console.ReadLine());
int retorno = 0;
switch (controleSecundario) {
case 1:
while (retorno == 0) {
Console.Clear();
Console.WriteLine("*********** Menu de Inserção de Clientes ***********");
Console.WriteLine();
Console.Write("Nome: ");
string nome = Console.ReadLine();
Console.Write("Endereco: ");
string endereco = Console.ReadLine();
Console.Write("Bairro: ");
string bairro = Console.ReadLine();
Console.Write("Cidade: ");
string cidade = Console.ReadLine();
Console.Write("Telefone: ");
string telefone = Console.ReadLine();
Console.Write("CPF: ");
string cpf = Console.ReadLine();
Cliente cliente = new Cliente(nome, endereco, bairro, cidade, telefone, cpf);
string query = "insert into cliente (nome, endereco, bairro, cidade, telefone, cpf) " +
"Values(" +
"'" + cliente.Nome + "', " +
"'" + cliente.Endereco + "', " +
"'" + cliente.Bairro + "', " +
"'" + cliente.Cidade + "', " +
"'" + cliente.Telefone + "', " +
"'" + cliente.Cpf + "'" +
")";
retorno = banco.Set(query);
if (retorno >= 1) {
Console.WriteLine();
Console.WriteLine("Cliente inserido com sucesso! Pressione Enter para continuar");
Console.ReadLine();
} else {
Console.WriteLine();
Console.WriteLine("Ocorreu um erro ao inserir o cliente, deseja tentar novamente? (0 = Sim, 1 = Não)");
retorno = int.Parse(Console.ReadLine());
}
}
break;
case 2:
retorno = 0;
while (retorno == 0) {
Console.Clear();
Console.WriteLine("*********** Menu de Atualização de Clientes ***********");
Console.WriteLine();
Console.Write("Digite o CPF do cliente que deseja atualizar: ");
string cpf = Console.ReadLine();
Console.Write("Nome: ");
string nome = Console.ReadLine();
Console.Write("Endereco: ");
string endereco = Console.ReadLine();
Console.Write("Bairro: ");
string bairro = Console.ReadLine();
Console.Write("Cidade: ");
string cidade = Console.ReadLine();
Console.Write("Telefone: ");
string telefone = Console.ReadLine();
Cliente cliente = new Cliente(nome, endereco, bairro, cidade, telefone, cpf);
string query = "update cliente " +
"set " +
"nome = '" + cliente.Nome + "', " +
"endereco = '" + cliente.Endereco + "', " +
"bairro = '" + cliente.Bairro + "', " +
"cidade = '" + cliente.Cidade + "'," +
"telefone = '" + cliente.Telefone + "' " +
"WHERE cpf = '" + cliente.Cpf + "';";
retorno = banco.Set(query);
if (retorno >= 1) {
Console.WriteLine();
Console.WriteLine("Cliente atualizado com sucesso! Pressione Enter para continuar");
Console.ReadLine();
} else {
Console.WriteLine();
Console.WriteLine("Ocorreu um erro ao atualizar o cliente, deseja tentar novamente? (0 = Sim, 1 = Não)");
retorno = int.Parse(Console.ReadLine());
}
}
break;
case 3:
retorno = 0;
while (retorno == 0) {
Console.Clear();
Console.WriteLine("*********** Menu de Remoção de Clientes ***********");
Console.WriteLine();
Console.Write("Digite o CPF do cliente que deseja remover: ");
string cpf = Console.ReadLine();
string query = "delete from cliente where cpf = '" + cpf + "'";
retorno = banco.Set(query);
if (retorno >= 1) {
Console.WriteLine();
Console.WriteLine("Cliente removido com sucesso! Pressione Enter para continuar");
Console.ReadLine();
} else {
Console.WriteLine();
Console.WriteLine("Ocorreu um erro ao remover o cliente, deseja tentar novamente? (0 = Sim, 1 = Não)");
retorno = int.Parse(Console.ReadLine());
}
}
break;
case 4:
retorno = 0;
while (retorno == 0) {
Console.Clear();
Console.WriteLine("*********** Menu de Consulta de Clientes ***********");
Console.WriteLine();
Console.Write("Digite o CPF do usuário que deseja buscar: ");
string cpf = Console.ReadLine();
string query = "select nome, endereco, bairro, cidade, telefone, cpf " +
"from cliente " +
"where cpf = '" + cpf + "';";
DataTable table = banco.Get(query);
if (table.Rows.Count > 0 && table != null) {
foreach (DataRow row in table.Rows) {
Console.WriteLine("Nome: " + row["nome"].ToString());
Console.WriteLine("Endereço: " + row["endereco"].ToString());
Console.WriteLine("Bairro: " + row["bairro"].ToString());
Console.WriteLine("Cidade: " + row["cidade"].ToString());
Console.WriteLine("Telefone: " + row["telefone"].ToString());
Console.WriteLine("CPF: " + row["cpf"].ToString());
Console.WriteLine();
}
} else {
Console.WriteLine("Não há nenhum registro na tabela. Pressione enter para continuar");
Console.ReadLine();
retorno = 1;
}
Console.WriteLine();
Console.WriteLine("Deseja buscar outro cliente? (0 = Sim, 1 = Não)");
retorno = int.Parse(Console.ReadLine());
}
break;
case 5:
retorno = 0;
while (retorno == 0) {
Console.Clear();
Console.WriteLine("*********** Listagem de Clientes ***********");
Console.WriteLine();
string query = "SELECT * FROM cliente";
DataTable table = banco.Get(query);
if (table.Rows.Count > 0 && table != null) {
foreach (DataRow row in table.Rows) {
Console.WriteLine("Nome: " + row["nome"].ToString());
Console.WriteLine("Endereço: " + row["endereco"].ToString());
Console.WriteLine("Bairro: " + row["bairro"].ToString());
Console.WriteLine("Cidade: " + row["cidade"].ToString());
Console.WriteLine("Telefone: " + row["telefone"].ToString());
Console.WriteLine("CPF: " + row["cpf"].ToString());
Console.WriteLine();
}
} else {
Console.WriteLine("Não há nenhum registro na tabela. Pressione enter para continuar");
Console.ReadLine();
retorno = 1;
}
Console.WriteLine();
Console.WriteLine("Deseja listar novamente? (0 = Sim, 1 = Não)");
retorno = int.Parse(Console.ReadLine());
}
break;
case 0:
controlePrincipal = 0;
break;
case 9: break;
default:
Console.WriteLine();
Console.WriteLine("Opção inválida tente novamente");
break;
}
}
break;
default:
break;
}
}
}
}
}
|
JavaScript
|
UTF-8
| 5,074 | 2.71875 | 3 |
[] |
no_license
|
import '@materializecss/materialize';
import '../css/options.scss';
const BIBLE_API_BASE_URL = 'https://api.scripture.api.bible/v1/';
const BIBLE_API_KEY = process.env.BIBLE_API_KEY;
const DEFAULT_TRANS = '9879dbb7cfe39e4d-04';
const DEFAULT_LANGUAGE = 'eng';
let version_select = document.getElementById('bible-version');
let language_select = document.getElementById('language');
let status = document.getElementById('save-status');
/**
* Verify that the response is good from the fetch call
*
* @param {Response} response The response object
* @returns {object} The JSON associated with the response
* @throws Error if response is bad
*/
function check_fetch_ok_response(response) {
if (!response.ok) {
throw new Error('HTTP status ' + response.status);
}
return response.json();
}
/**
* Gets the available bible languages
*
* @param {Function} cb Function to call once the languages have been fetched
*/
function get_languages(cb) {
fetch(`${BIBLE_API_BASE_URL}bibles`, {
headers: new Headers({
'api-key': BIBLE_API_KEY,
}),
})
.then(check_fetch_ok_response)
.then(res => {
const separator = ':::';
const versions = res.data.map(function (items) {
return `${items.language.name}${separator}${items.language.id}`;
});
for (const version of Array.from(new Set(versions)).sort()) {
const [name, id] = version.split(separator);
// English is the first item in the list
if (id !== 'eng') {
language_select.add(new Option(name, id));
}
}
cb();
// eslint-disable-next-line no-undef
M.FormSelect.init(language_select, {});
})
.catch(error => {
console.error(error);
});
}
/**
* Populate the version selector
*
* @param {object} versions The available bible versions
*/
function populate_version_select(versions) {
version_select.options.length = 0;
for (let op in version_select.options) {
version_select.remove(op);
}
for (const ver of versions) {
if (ver['name'] !== '') {
let fullName = ver['name'];
if (ver['description']) {
fullName += ` - ${ver['description']}`;
}
version_select.add(new Option(fullName, ver['id']));
}
}
}
/**
* Get the available bible versions based on the selected language
*
* @param {boolean} is_event If this is being called in response to an event
* @param {Function} cb Function to call once the versions have been obtained
*/
function get_versions(is_event, cb) {
// TODO: Remove extra fetch call, can just pass dictionary from language call
fetch(`${BIBLE_API_BASE_URL}bibles?language=${language_select.options[language_select.selectedIndex].value}`, {
headers: new Headers({
'api-key': BIBLE_API_KEY,
}),
})
.then(check_fetch_ok_response)
.then(res => {
populate_version_select(res.data);
if (!is_event) {
cb();
}
// Reinitialize the select to show the new options
// eslint-disable-next-line no-undef
M.FormSelect.init(version_select, {});
version_select.removeAttribute('disabled');
})
.catch(error => {
console.error(error);
});
}
/**
* Saves options to chrome.storage
*/
function save_options() {
chrome.storage.sync.set({
'language': language_select.options[language_select.selectedIndex].value,
'translation': version_select.options[version_select.selectedIndex].value
}, function () {
// Update status to let user know options were saved.
status.textContent = 'Options saved.';
setTimeout(function () {
status.textContent = '';
}, 2000);
});
}
/**
* Restores select box and checkbox state using the preferences stored in chrome.storage.
*
* @param {Function} cb Function to call after the options are loaded
*/
function restore_options(cb) {
chrome.storage.sync.get({
'language': DEFAULT_LANGUAGE,
'translation': DEFAULT_TRANS
}, function (settings) {
document.getElementById('save-button').classList.remove('disabled');
cb(settings);
});
}
document.getElementById('save-button').addEventListener('click', save_options);
document.addEventListener('DOMContentLoaded', function () {
restore_options(function (settings) {
// eslint-disable-next-line no-undef
M.FormSelect.init(language_select, {});
language_select.value = settings['language'];
get_languages(function () {
get_versions(false, function () {
version_select.value = settings['translation'];
version_select.removeAttribute('disabled');
});
});
});
document.getElementById('language').onchange = get_versions;
});
|
Markdown
|
UTF-8
| 767 | 2.5625 | 3 |
[] |
no_license
|
----
title: eCommerce SEO 1
subtitle: nourishedlife.com
cute_description: Doing SEO the right way.
description: Carefully crafted product descriptions that encourage results.
date: 2014
category: eCommerce | Beauty | Lifestyle
image: Category_intro.jpg
----
* Structured tone of voice: happy, fun, casual, passionate
* Focus on high quality, unique content interwoven with keywords, anchors and links
* Showcase product benefits within a fun 'how to use' context
* Click-worthy meta description text
<a href="http://www.nourishedlife.com.au" target=_blank class='btn btn-primary'>Visit shop</a>
***
# Product descriptions



|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.