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 |
|---|---|---|---|---|---|---|---|
Java | UTF-8 | 16,540 | 2.140625 | 2 | [] | no_license | package stefan.jovanovic.chatapplication;
import android.content.Context;
import android.content.SharedPreferences;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import static android.content.Context.MODE_PRIVATE;
public class HttpHelper {
private static final int SUCCESS = 200;
public static final String MY_PREFS_NAME = "PrefsFile";
private static String BASE_URL = "http://18.205.194.168:80";
private static String CONTACTS_URL = BASE_URL + "/contacts";
private static String LOGIN_URL = BASE_URL + "/login";
private static String LOGOUT_URL = BASE_URL + "/logout";
private static String GET_MESSAGE_URL = BASE_URL + "/message/";
private static String POST_MESSAGE_URL = BASE_URL + "/message";
private static String DELETE_CONTACT_URL = BASE_URL + "/contact/";
private static String REGISTER_URL = BASE_URL + "/register";
private static String DELETE_MESSAGE = BASE_URL + "/message";
private static String GET_NOTIFICATION_URL = BASE_URL + "/getfromservice";
public boolean registerUserOnServer(Context context, JSONObject jsonObject) throws IOException{
HttpURLConnection urlConnection;
java.net.URL url = new URL(REGISTER_URL);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
urlConnection.setRequestProperty("Accept","application/json");
urlConnection.setReadTimeout(1000 /* milliseconds */ );
urlConnection.setConnectTimeout(15000 /* milliseconds */ );
/*needed when used POST or PUT methods*/
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
try {
urlConnection.connect();
} catch (IOException e) {
return false;
}
DataOutputStream os = new DataOutputStream(urlConnection.getOutputStream());
/*write json object*/
os.writeBytes(jsonObject.toString());
os.flush();
os.close();
int responseCode = urlConnection.getResponseCode();
if(responseCode!=SUCCESS) {
SharedPreferences.Editor editor = context.getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
String responseMsg = urlConnection.getResponseMessage();
String registerErr = Integer.toString(responseCode) + " : " + responseMsg;
editor.putString("registerErr", registerErr);
editor.apply();
}
urlConnection.disconnect();
return (responseCode==SUCCESS);
}
public boolean logInUserOnServer(Context context, JSONObject jsonObject) throws IOException{
HttpURLConnection urlConnection;
java.net.URL url = new URL(LOGIN_URL);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
urlConnection.setRequestProperty("Accept","application/json");
urlConnection.setReadTimeout(1000 /* milliseconds */ );
urlConnection.setConnectTimeout(15000 /* milliseconds */ );
/*needed when used POST or PUT methods*/
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
try {
urlConnection.connect();
} catch (IOException e) {
return false;
}
DataOutputStream os = new DataOutputStream(urlConnection.getOutputStream());
/*write json object*/
os.writeBytes(jsonObject.toString());
os.flush();
os.close();
int responseCode = urlConnection.getResponseCode();
String sessionId = urlConnection.getHeaderField("sessionid");
SharedPreferences.Editor editor = context.getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
if(responseCode==SUCCESS) {
editor.putString("sessionId", sessionId);
editor.apply();
} else {
String responseMsg = urlConnection.getResponseMessage();
String loginErr = Integer.toString(responseCode) + " : " + responseMsg;
editor.putString("loginErr", loginErr);
editor.apply();
}
urlConnection.disconnect();
return (responseCode==SUCCESS);
}
public JSONArray getContactsFromServer(Context context) throws IOException, JSONException {
HttpURLConnection urlConnection;
java.net.URL url = new URL(CONTACTS_URL);
urlConnection = (HttpURLConnection) url.openConnection();
SharedPreferences prefs = context.getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String sessionId = prefs.getString("sessionId", null);
/*header fields*/
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("sessionid", sessionId);
//urlConnection.addRequestProperty("Content-Type", "application/json;charset=UTF-8");
urlConnection.setReadTimeout(10000 /* milliseconds */ );
urlConnection.setConnectTimeout(15000 /* milliseconds */ );
try {
urlConnection.connect();
} catch (IOException e) {
return null;
}
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
String jsonString = sb.toString();
int responseCode = urlConnection.getResponseCode();
String responseMsg = urlConnection.getResponseMessage();
SharedPreferences.Editor editor = context.getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
urlConnection.disconnect();
if (responseCode == SUCCESS){
return new JSONArray(jsonString);
} else {
String getContactsErr = Integer.toString(responseCode) + " : " + responseMsg;
editor.putString("getContactsErr", getContactsErr);
editor.apply();
return null;
}
}
public boolean logOutUserFromServer(Context context) throws IOException, JSONException {
HttpURLConnection urlConnection;
java.net.URL url = new URL(LOGOUT_URL);
SharedPreferences prefs = context.getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String sessionId = prefs.getString("sessionId", null);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("sessionid", sessionId);
urlConnection.setReadTimeout(1000 /* milliseconds */ );
urlConnection.setConnectTimeout(15000 /* milliseconds */ );
/*needed when used POST or PUT methods*/
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
try {
urlConnection.connect();
} catch (IOException e) {
return false;
}
int responseCode = urlConnection.getResponseCode();
SharedPreferences.Editor editor = context.getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
if(responseCode!=SUCCESS) {
String responseMsg = urlConnection.getResponseMessage();
String logoutErr = Integer.toString(responseCode) + " : " + responseMsg;
editor.putString("logoutErr", logoutErr);
editor.apply();
}
urlConnection.disconnect();
return (responseCode==SUCCESS);
}
public boolean sendMessageToServer(Context context, JSONObject jsonObject) throws IOException, JSONException {
HttpURLConnection urlConnection;
java.net.URL url = new URL(POST_MESSAGE_URL);
SharedPreferences prefs = context.getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String sessionId = prefs.getString("sessionId", null);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("sessionid", sessionId);
urlConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
urlConnection.setRequestProperty("Accept","application/json");
urlConnection.setReadTimeout(1000 /* milliseconds */ );
urlConnection.setConnectTimeout(15000 /* milliseconds */ );
/*needed when used POST or PUT methods*/
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
try {
urlConnection.connect();
} catch (IOException e) {
return false;
}
DataOutputStream os = new DataOutputStream(urlConnection.getOutputStream());
/*write json object*/
os.writeBytes(jsonObject.toString());
os.flush();
os.close();
int responseCode = urlConnection.getResponseCode();
SharedPreferences.Editor editor = context.getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
if(responseCode!=SUCCESS) {
String responseMsg = urlConnection.getResponseMessage();
String sendMsgErr = Integer.toString(responseCode) + " : " + responseMsg;
editor.putString("sendMsgErr", sendMsgErr);
editor.apply();
}
urlConnection.disconnect();
return (responseCode==SUCCESS);
}
public JSONArray getMessagesFromServer(Context context, String contact) throws IOException, JSONException {
HttpURLConnection urlConnection;
java.net.URL url = new URL(GET_MESSAGE_URL + contact);
urlConnection = (HttpURLConnection) url.openConnection();
SharedPreferences prefs = context.getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String sessionId = prefs.getString("sessionId", null);
/*header fields*/
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("sessionid", sessionId);
urlConnection.setReadTimeout(10000 /* milliseconds */ );
urlConnection.setConnectTimeout(15000 /* milliseconds */ );
try {
urlConnection.connect();
} catch (IOException e) {
return null;
}
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
String jsonString = sb.toString();
int responseCode = urlConnection.getResponseCode();
String responseMsg = urlConnection.getResponseMessage();
SharedPreferences.Editor editor = context.getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
urlConnection.disconnect();
if (responseCode == SUCCESS){
return new JSONArray(jsonString);
} else {
String getMessagesErr = Integer.toString(responseCode) + " : " + responseMsg;
editor.putString("getMessagesErr", getMessagesErr);
editor.apply();
return null;
}
}
/*HTTP delete*/
public boolean deleteUserFromServer(Context context, String contact) throws IOException, JSONException {
HttpURLConnection urlConnection = null;
java.net.URL url = new URL(DELETE_CONTACT_URL + contact);
urlConnection = (HttpURLConnection) url.openConnection();
SharedPreferences prefs = context.getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String sessionId = prefs.getString("sessionId", null);
urlConnection.setRequestMethod("DELETE");
urlConnection.setRequestProperty("sessionid", sessionId);
urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
urlConnection.setRequestProperty("Accept","application/json");
try {
urlConnection.connect();
} catch (IOException e) {
return false;
}
int responseCode = urlConnection.getResponseCode();
if (responseCode != SUCCESS) {
SharedPreferences.Editor editor = context.getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
String responseMsg = urlConnection.getResponseMessage();
String deleteContactErr = Integer.toString(responseCode) + " : " + responseMsg;
editor.putString("deleteContactErr", deleteContactErr);
editor.apply();
}
urlConnection.disconnect();
return (responseCode==SUCCESS);
}
/*HTTP delete*/
public boolean deleteMessageFromServer(Context context, JSONObject jsonObject) throws IOException, JSONException {
HttpURLConnection urlConnection = null;
java.net.URL url = new URL(DELETE_MESSAGE);
urlConnection = (HttpURLConnection) url.openConnection();
SharedPreferences prefs = context.getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String sessionId = prefs.getString("sessionId", null);
urlConnection.setRequestMethod("DELETE");
urlConnection.setRequestProperty("sessionid",sessionId);
urlConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
urlConnection.setRequestProperty("Accept","application/json");
urlConnection.setReadTimeout(1000 /* milliseconds */ );
urlConnection.setConnectTimeout(15000 /* milliseconds */ );
/*needed when used POST or PUT methods*/
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
try {
urlConnection.connect();
} catch (IOException e) {
return false;
}
DataOutputStream os = new DataOutputStream(urlConnection.getOutputStream());
os.writeBytes(jsonObject.toString());
os.flush();
os.close();
int responseCode = urlConnection.getResponseCode();
if (responseCode != SUCCESS) {
SharedPreferences.Editor editor = context.getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
String responseMsg = urlConnection.getResponseMessage();
String deleteMsgErr = Integer.toString(responseCode) + " : " + responseMsg;
editor.putString("deleteMsgErr", deleteMsgErr);
editor.apply();
}
urlConnection.disconnect();
return (responseCode==SUCCESS);
}
/*HTTP getNotification*/
public boolean getNotification(Context context) throws IOException, JSONException {
HttpURLConnection urlConnection = null;
java.net.URL url = new URL(GET_NOTIFICATION_URL);
urlConnection = (HttpURLConnection) url.openConnection();
SharedPreferences prefs = context.getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String sessionId = prefs.getString("sessionId", null);
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("sessionid", sessionId);
urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
urlConnection.setRequestProperty("Accept","application/json");
try {
urlConnection.connect();
} catch (IOException e) {
return false;
}
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
Boolean response = Boolean.valueOf(sb.toString());
urlConnection.disconnect();
return (response);
}
public boolean checkServer() throws IOException {
HttpURLConnection urlConnection;
java.net.URL url = new URL(BASE_URL);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Connection", "close");
urlConnection.setConnectTimeout(2000 /* milliseconds */ );
try {
urlConnection.connect();
return true;
} catch (IOException e) {
return false;
}
}
}
|
Python | UTF-8 | 905 | 2.765625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
from sklearn import mixture
fig = plt.figure()
ax = fig.gca(projection="3d")
# prepare data
delta = 0.5
#x = np.arange(0, 9, delta)
#y = np.arange(0, 9, delta)
x = np.arange(0, 9, delta)
y = np.arange(0, 9, delta)
x, y = np.meshgrid(x,y)
# set function for generating z
r = np.sqrt(x ** 2 + y ** 2)
z = np.sin(r)*10
surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm) # cmap means color map
#add color card
fig.colorbar(surf, shrink=0.4, aspect=7)
# shrink represents the shrinkage ratio,aspect affects the width of bar, the larger aspect is,the narrow bar is
fig.tight_layout()
cfig = plt.gcf() # 'get current figure'
cfig.savefig('3D.pdf', format='pdf', dpi=1000)
plt.show() |
PHP | UTF-8 | 2,163 | 2.625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use App\Award;
use App\Http\Requests\MakeAwardRequest;
use App\Repositories\Award\AwardRepository;
use App\Repositories\Award\AwardRepositoryInterface;
use App\Repositories\Personal\PersonalRepositoryInterface;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
class AwardsController extends Controller
{
//
protected $award;
protected $currentUser;
public function __construct(Award $award)
{
// set the model
$this->award = new AwardRepository($award);
//set currently logged in user
$this->middleware(function ($request, $next){
$this->currentUser = auth()->user()->id;
return $next($request);
});
}
//create award view action
public function createAward(PersonalRepositoryInterface $personalRepo){
//see PersonalRepository method
$personal = $personalRepo->find($this->currentUser);
$personal_id = $personal->id;
return view('education.award.create-award', compact('personal_id'));
}
//store created award action
public function storeAward(MakeAwardRequest $request){
$this->award->create($request->all());
return redirect('/education')->with(Session::flash('message', 'Honor or Scholarship Successfully Added!'));
}
public function editAward($id, PersonalRepositoryInterface $personalRepo, AwardRepositoryInterface $awardRepo){
$award = $awardRepo->get($id);
//see PersonalRepository method
//TODO clean up the edit award form template(s) to include personal_id automatically, but provide it for create
$personal = $personalRepo->find($this->currentUser);
$personal_id = $personal->id;
return view('education.award.edit-award', compact('award', 'personal_id'));
}
//update & store Award action
public function updateAward(MakeAwardRequest $request, $id){
$this->award->update($request->all(), $id);
//redirect back
return Redirect::back()->with(Session::flash('message', 'Award Successfully Updated!'));
}
}
|
Java | UTF-8 | 2,602 | 2.28125 | 2 | [] | no_license | package mundial.initics.martes;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.andrognito.patternlockview.PatternLockView;
import com.andrognito.patternlockview.listener.PatternLockViewListener;
import com.andrognito.patternlockview.utils.PatternLockUtils;
import com.squareup.picasso.Picasso;
import java.util.List;
public class MainActivity extends AppCompatActivity implements PatternLockViewListener {
SharedPreferences SP;
SharedPreferences.Editor EDITOR;
Button rgistrar,login;
PatternLockView mPatternLockView;
String patron;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView imagen = (ImageView)findViewById(R.id.imageView2);
Picasso.with(this).load("http://www.initics.com/img/logo.png").into(imagen);
mPatternLockView = (PatternLockView) findViewById(R.id.pattern_lock_view);
mPatternLockView.addPatternLockListener(this);
SP=getSharedPreferences("patron", Context.MODE_PRIVATE);
EDITOR = SP.edit();
rgistrar=(Button)findViewById(R.id.btn_registrar);
rgistrar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EDITOR.putString("patron_key",patron);
EDITOR.apply();
mPatternLockView.clearPattern();
}
});
login=(Button)findViewById(R.id.btn_login);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(SP.getString("patron_key","").equalsIgnoreCase(patron)){
Toast.makeText(getApplicationContext(),"INGRESO CORRECTO",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(),"ERROR , ERROR , ERROR",Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
public void onStarted() {
}
@Override
public void onProgress(List<PatternLockView.Dot> progressPattern) {
}
@Override
public void onComplete(List<PatternLockView.Dot> pattern) {
patron = PatternLockUtils.patternToString(mPatternLockView, pattern);
}
@Override
public void onCleared() {
}
}
|
Java | UTF-8 | 577 | 3.21875 | 3 | [] | no_license | import java.util.Scanner;
public class Ejercicio5 {
public static void main (String args[]){
int edad;
int media;
int contador=0;
int suma=0;
Scanner teclado = new Scanner (System.in);
System.out.println("Introduce la edad ");
edad= teclado.nextInt();
while (edad !=0) {
suma=suma+edad;
contador= contador+1;
System.out.println("Introduce la edad ");
edad= teclado.nextInt();
}
media= suma/contador;
System.out.println("Procesando..." + media);
}
}
|
Java | UTF-8 | 216 | 2.21875 | 2 | [] | no_license | package Encapsulation;
public class pembungkusan {
public static void main(String[] args) {
hewan h = new hewan();
h.set_tinggi(129);
System.out.println(h.get_tinggi());
}
}
|
TypeScript | UTF-8 | 968 | 3.96875 | 4 | [] | no_license | interface ITypeFunction {
(a:number, b:number):boolean;
}
var add: ITypeFunction;
add = (varA:number, varB:number):boolean => {
return true
}
interface IColor {
(codeColor:string, title?:string):{codeColor:string, title?:string}
}
var getNewColor:IColor;
getNewColor = function(codeColor:string, title?:string):{codeColor:string, title?:string} {
if (title) {
return {codeColor, title}
}
return {codeColor}
}
console.log(getNewColor("#000", "black"))
interface IArrayTypeString {
[index:number]:string
}
var a:IArrayTypeString
a = ["teste"]
console.log('a => ', a)
a = ["teste", 27]
console.log('a => ', a)
interface IArrayTypeNumber {
[index:string]:number
}
var b:IArrayTypeNumber
b = [1]
console.log('b => ', b)
b = [1, 'teste b']
console.log('b => ', b)
interface IArrayString {
[index:string]:string
}
var c:IArrayString
c = ['1']
console.log('c => ', c)
c = ["1", 'teste c']
console.log('c => ', c)
|
Python | UTF-8 | 6,466 | 2.65625 | 3 | [
"MIT"
] | permissive | from FrictionlessDarwinCore import *
from pathlib import Path
import sys
import shutil
import requests
import zipfile
import tempfile
import xml.etree.ElementTree as ET
class DwCArchive:
voc = DwCVocabulary()
ns = {'dwc': 'http://rs.tdwg.org/dwc/text/'}
def __init__(self, path_or_url):
self.valid = True
self.dwca = path_or_url
self.meta_dir = ''
self.metadata = None
self.structure = None
self.tf = None
self.need_conversion = False
if self.dwca.startswith('http'):
self.path = self.download()
else:
self.path = self.dwca
def download(self):
# download DwCArchive into temporary file
self.tf = tempfile.NamedTemporaryFile()
try:
response = requests.get(self.dwca)
self.tf.write(response.content)
except requests.exceptions.RequestException as err:
print(err)
self.valid = False
else:
print('downloading ' + self.dwca + ' as ' + self.tf.name)
return self.tf.name
def infer(self):
if zipfile.is_zipfile(self.path):
self.load()
else:
self.valid = False
print('dwca is not a zipfile')
def load(self):
eml = ''
meta = ''
zf = zipfile.ZipFile(self.path, mode='r')
try:
for info in zf.infolist():
p=Path(info.filename)
if p.name in ('eml.xml','metadata.xml'):
eml = zf.read(info.filename).decode()
if p.name == 'meta.xml':
meta = zf.read(info.filename).decode()
self.meta_dir = p.parent.name
if eml != '' and meta != '':
self.metadata = DwCMetadata(eml)
self.structure = DwCStructure(meta, eml, self.meta_dir)
self.metadata.convert()
self.structure.convert()
self.valid = self.metadata.valid and self.structure.valid
self.need_conversion = self.structure.has_default_values
else:
print('EML or Meta file missing')
self.valid = False
except BaseException:
print(sys.exc_info())
print('load zip failed')
self.valid = False
finally:
zf.close()
def _load_data(self, zf, filename, meta):
try:
resource = None
for info in zf.infolist():
p = Path(info.filename)
if p.name == filename:
data = zf.read(info.filename)
resource = DwCResource(meta, data)
except KeyError:
print ('Did not find %s in zip file' % p)
self.valid = False
except BaseException:
print(sys.exc_info())
print('load data from zip failed')
self.valid = False
return resource
def save(self, output):
if self.need_conversion:
# convert all data files
self._save_data(output)
self._save_dwc_meta(output)
else:
# No Data conversion need, first copy zipfile to output
shutil.copyfile(self.path, output)
self._save_meta(output)
def _save_meta(self, output):
# Append structure and metadata
zf = zipfile.ZipFile(output, mode='a')
try:
# Add a README.md file that describes the package
zf.writestr('readme.md', self.metadata.as_markdown())
# Add a datapackage.json
zf.writestr('datapackage.json', self.structure.as_json())
except IOError as e:
print("Unable to copy file. %s" % e)
else:
print('saving zipfile to ' + output)
finally:
zf.close()
def _save_dwc_meta(self, output):
# Append original eml.xml , meta.xml or metadata.xml in meta_dir
izf = zipfile.ZipFile(self.path, mode='r')
ozf = zipfile.ZipFile(output, mode='a')
try:
for info in izf.infolist():
p=Path(info.filename)
if p.parent.name == self.meta_dir and p.suffix == '.xml' and not p.name.startswith('.'):
print ('copying ',info.filename, self.meta_dir)
ozf.writestr(p.name, izf.read(info.filename).decode())
except BaseException:
print(sys.exc_info())
print('load zip failed')
self.valid = False
finally:
izf.close()
ozf.close()
def _save_data(self, output):
# create empty output zipfile
izf = zipfile.ZipFile(self.path, mode='r')
ozf = zipfile.ZipFile(output, mode='w')
# add core and extension data as CSV files
try:
archive = ET.fromstring(self.structure.meta)
core = archive.find('dwc:core', DwCArchive.ns)
files = core.find('dwc:files', DwCArchive.ns)
location = files.find('dwc:location', DwCArchive.ns)
resource = self._load_data(izf, location.text, core)
if resource is not None:
ozf.writestr(location.text, resource.convert())
for extension in archive.findall('dwc:extension', DwCArchive.ns):
files = extension.find('dwc:files', DwCArchive.ns)
location = files.find('dwc:location', DwCArchive.ns)
resource = self._load_data(izf,location.text, extension)
if resource is not None:
ozf.writestr(location.text, resource.convert())
except IOError as e:
print("Unable to copy file. %s" % e)
finally:
izf.close()
ozf.close()
def to_csv(self, output):
self._save_data(output)
def to_json(self, output):
o = open(output, 'w')
try:
o.write(self.structure.as_json())
except IOError as e:
print("Unable to write file. %s" % e)
else:
print('saving json to ' + output)
finally:
o.close()
def to_markdown(self, output):
o = open(output, 'w')
try:
o.write(self.metadata.as_markdown())
except IOError as e:
print("Unable to write file. %s" % e)
else:
print('saving markdown to ' + output)
finally:
o.close()
|
PHP | UTF-8 | 613 | 2.90625 | 3 | [] | no_license | <?php
class departments{
public function addDepartment($data){
$c=new Connect();
$connection=$c->connection();
$sql="INSERT INTO departments($id_user,
name_department,
updated_date)
VALUES ('$data[0]',
'$data[1]',
'$data[2]'
)";
return mysqli_query($connection,$sql);
}
public function updateDepartment($data){
$c=new Connect();
$connection=$c->connection();
$sql="UPDATE departments SET name_department='$data[2]',updated_date='$data[3]'
WHERE id_department='$data[0]'";
return mysqli_query($connection,$sql);
}
}
?>
|
Java | UTF-8 | 2,575 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | package com.github.jjYBdx4IL.streaming.clients;
import com.github.jjYBdx4IL.streaming.clients.twitch.TwitchIRCClient;
import com.github.jjYBdx4IL.streaming.clients.twitch.api.Channel;
import com.github.jjYBdx4IL.streaming.clients.twitch.api.TwitchRESTClient;
import java.io.IOException;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author jjYBdx4IL
*/
public class TwitchClientConnectionManager extends ConnectionManager {
private static final Logger LOG = LoggerFactory.getLogger(TwitchClientConnectionManager.class);
private TwitchIRCClient client = null;
private boolean gameUpdated = false;
public TwitchClientConnectionManager(GenericConfig config) {
super(config);
}
@Override
public void reconnect() {
LOG.info("(re)connect");
notifyReconnect();
if (client != null) {
client.shutdown();
client = null;
}
try {
TwitchConfig config = new TwitchConfig();
config.read();
client = new TwitchIRCClient(config.botname, config.oauthToken);
client.connect();
client.joinChannel(config.channel, new TwitchChatListener() {
@Override
public void onChatMessage(String from, String message) {
LOG.info(from + ": " + message);
for (ChatListener listener : getChatListeners()) {
listener.onChatMessage(from, message);
}
}
});
notifyConnected();
updateTwitchGame();
} catch (IOException | InterruptedException ex) {
LOG.error("", ex);
}
}
@Override
public boolean isConnected() {
return client != null && client.isConnected();
}
/**
* update twitch game title depending on stream title
*/
private void updateTwitchGame() throws IOException {
if (gameUpdated) {
return;
}
gameUpdated = true;
TwitchRESTClient client = new TwitchRESTClient();
Channel channel = client.getChannelStatus();
for (String game : genericConfig.games) {
if (channel.status.toLowerCase(Locale.ROOT).contains(game.toLowerCase(Locale.ROOT))) {
channel.game = game;
LOG.info("setting Twitch channel info to " + channel);
client.putChannelStatus(channel);
break;
}
}
}
}
|
Java | UTF-8 | 450 | 3 | 3 | [] | no_license |
public class CalculoSalario {
public static void main(String[] args) {
//variaveis
double salario=1000,
ano = 2005,
aumento = 0.15;
do{
salario = salario + (salario * aumento);
aumento = aumento * 2;
System.out.println("Ano: "+ ano + " Salario: " + (long)salario);
ano++;
}while(ano <= 2018);
}
}
|
Java | UTF-8 | 795 | 3 | 3 | [] | no_license | package com.zhuanche.util;
import java.security.SecureRandom;
import java.util.Random;
public final class NumberUtil {
private static final String SEED_CHARS = "0123456789";
private static final Random rnd = new SecureRandom();
public static String genRandomCode( int length ) {
StringBuffer sb = new StringBuffer( length );
for(int i=0;i<length;i++) {
int index = rnd.nextInt( SEED_CHARS.length() );
char cha = SEED_CHARS.charAt(index);
sb.append(cha);
}
return sb.toString();
}
public static String genRandomCode( int length, String seed ) {
StringBuilder builder = new StringBuilder();
for(int i=0;i<length;i++) {
int index = rnd.nextInt( seed.length() );
char cha = seed.charAt(index);
builder.append(cha);
}
return builder.toString();
}
} |
Python | UTF-8 | 298 | 3 | 3 | [] | no_license | def iAddition(self):
total = 0
while (current != None):
total = total + current.getData()
current = current.getNext()
return total
def rAddition(listPtr):
if listPtr == None:
return 0
else:
return listPtr + rAddition(listPtr.getNext())
|
PHP | UTF-8 | 1,052 | 2.859375 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Components\Message\Notifier;
use App\Components\Message\MessageSendResult;
use App\Components\Message\INotifier;
use App\Components\Message\Message;
use App\Components\Message\Manager;
class GroupNotifier implements INotifier {
/**
* 发送消息
*
* @param MessageGroup $message 消息对象,一个MessageGroup
*
* @return MessageSendResult 返回消息发送的结果,只有在全部发送成功情况下,才会是成功,没有response和error信息
*/
public function send($message) : MessageSendResult
{
$manager = Manager::instance();
$messages = $message->getData();
$flag = true;
for ($i = 0, $len = count($messages); $i < $len; $i++) {
$send_result = $manager->sendSync($messages[$i]);
$flag |= $send_result->isSuccess();
}
$result = new MessageSendResult();
if ($flag) {
$result->result = 0; // 全部发送成功
} else {
$result->result = 1;
}
return $result;
}
} |
Java | UTF-8 | 792 | 2.375 | 2 | [] | no_license | package com.ibm.service;
import com.ibm.model.EmailRequest;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MessageBuilder {
public static Message createNewMimeMsg(EmailRequest request) {
Message message = new MimeMessage(SessionBuilder.getInstance());
try {
message.setFrom(new InternetAddress(request.getToEmail()));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(request.getToEmail()));
message.setSubject(request.getBody());
message.setText(request.getBody());
} catch (MessagingException e) {
e.printStackTrace();
}
return message;
}
}
|
JavaScript | UTF-8 | 1,103 | 2.953125 | 3 | [] | no_license | 'use strict';
const Graph = require('../../graph/graph');
const getEdge = require('../getEdge');
describe('getEdge', () => {
let graph;
let cities;
beforeEach(() => {
graph = new Graph();
graph.addNode('Seattle');
graph.addNode('Bellevue');
graph.addNode('Renton');
graph.addNode('Tukwila');
graph.addNode('Tacoma');
graph.addEdge('Seattle','Bellevue', 10);
graph.addEdge('Seattle','Renton', 15);
graph.addEdge('Bellevue','Tacoma', 25);
graph.addEdge('Renton', 'Tukwila', 10);
})
it('Happy case: will return true with the correct amount', () => {
cities = ['Seattle', 'Bellevue','Tacoma'];
expect(getEdge(graph, cities)).toEqual([true, '$35'])
});
it('Fail case: will return false with a zero dollar amount', () => {
cities['Seattle','Tukwila'];
expect(getEdge(graph,cities)).toEqual([false, '$0']);
});
it('Will return null if the graph or cities are empty', () => {
cities = [];
expect(getEdge(graph, cities)).toBe(null);
})
}) |
JavaScript | UTF-8 | 1,625 | 2.59375 | 3 | [] | no_license | 'use strict';
const checkboxes = document.querySelectorAll('.text input[type=checkbox]');
const sendRequest = document.querySelector('#send-request');
checkboxes.forEach((checkbox, i) => {
checkbox.addEventListener('change', (e) => {
checkboxes.forEach((checkbox) => {
checkbox.checked = false;
});
const inputText = document.querySelector('#param-value');
e.target.checked = true;
inputText.value = 'text=' + e.target.value;
});
});
sendRequest.addEventListener('click', (e) => {
const acceptType = document.querySelector('#accept-type');
const paramValue = document.querySelector('#param-value');
if (paramValue.value) {
if (acceptType.value === 'application/json') {
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
const init = {
headers: {
Accept: 'application/json',
Authorization: `Basic ${username}:${password}`,
},
};
fetch(`/query?${paramValue.value}`, init)
.then((response) => response.json())
.then((data) => {
console.log(data);
const jsonWrapper = document.querySelector('#json-wrapper');
jsonWrapper.firstChild.remove();
jsonWrapper.style.display = 'block';
renderjson.set_show_to_level(3);
document.querySelector('#json-wrapper').appendChild(renderjson(data));
})
.catch((err) => console.log(err));
} else if (acceptType.value === 'text/html') {
window.open(`/query?${paramValue.value}`);
} else {
// Do nothing
}
}
});
|
Python | UTF-8 | 1,276 | 2.9375 | 3 | [
"MIT"
] | permissive | import unittest
from protectedblob.blob import PassphraseProtectedBlob
from protectedblob.cipher_suites import AES256CBCSHA256
from protectedblob.key_derivation import PBKDF2SHA256AES256
class TestPassphraseProtectedBlob(unittest.TestCase):
def test_roundtrip(self):
plaintext = b'hello, world!'
passphrase = 'foobar'
blob = PassphraseProtectedBlob(
cipher_suite=AES256CBCSHA256,
kdf=PBKDF2SHA256AES256)
blob.populate_with_plaintext(passphrase, plaintext, rounds=1000)
decrypted_text = blob.get_plaintext(passphrase)
self.assertEqual(decrypted_text, plaintext)
def test_change_passphrase(self):
plaintext = b'hello, world!'
passphrase = 'foobar'
blob = PassphraseProtectedBlob(
cipher_suite=AES256CBCSHA256,
kdf=PBKDF2SHA256AES256)
blob.populate_with_plaintext(passphrase, plaintext, rounds=1000)
decrypted_text = blob.get_plaintext(passphrase)
self.assertEqual(decrypted_text, plaintext)
new_passphrase = 'barfoo'
blob.change_passphrase(passphrase, new_passphrase)
new_decrypted_text = blob.get_plaintext(new_passphrase)
self.assertEqual(new_decrypted_text, decrypted_text)
|
C | UTF-8 | 208 | 2.5625 | 3 | [] | no_license | #include <stdio.h>
#include <string.h>
int main(void)
{
char* p;
char* c;
p = "this is a test but very hard to";
c = "butteegergerfdsfgsdfgsdfgsdfgd";
printf("something -- \n ---- %i.\n", c-p);
return 0;
}
|
Java | UTF-8 | 1,794 | 2.5 | 2 | [] | no_license | package com.goldgov.origin.core.web.validator.impl;
import java.lang.reflect.Field;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.goldgov.origin.core.web.annotation.OperateType;
import com.goldgov.origin.core.web.validator.ConstraintValidator;
import com.goldgov.origin.core.web.validator.annotation.Max;
public class MaxValidator implements ConstraintValidator<Max,String>{
private long max;
private OperateType[] types;
@Override
public void initialize(Max constraintAnnotation) {
max = constraintAnnotation.max();
types = constraintAnnotation.type();
}
@Override
public boolean isValid(String name, String value, Field field, OperateType type, HttpServletRequest request,
HttpServletResponse response) {
if(Utils.operatingValidate(type, types)){
if(value == null){
return true;
}
if(field.getType() == String.class){
if(value.length() <= max){
return true;
}
}else if(field.getType() == Integer.class){
Integer intValue = Integer.valueOf(value);
if(intValue <= max){
return true;
}
}else if(field.getType() == Double.class){
Double doubleValue = Double.valueOf(value);
if(doubleValue <= max){
return true;
}
}else if(field.getType() == Long.class){
Long longValue = Long.valueOf(value);
if(longValue <= max){
return true;
}
}else if(field.getType() == Date.class){
throw new RuntimeException("暂不支持Date类型的转换判断,请参考@Future和@Past注解的使用");
}else{
throw new RuntimeException("不支持类型的转换判断:" + field.getType());
}
return false;
}
return true;
}
}
|
Go | UTF-8 | 980 | 3.109375 | 3 | [] | no_license | package main
import (
"fmt"
"gopl-practise/ch4/4-10/github"
"log"
"os"
"time"
)
const (
lessOneMonth string = "less than a month"
lessOneYear string = "less than a year"
moreOneYear string = "more than a year"
)
func main() {
result, err := github.SearchIssues(os.Args[1:])
if err != nil {
log.Fatal(err)
}
issueCount := make(map[string][]github.Issue, 3)
for _, item := range result.Items {
item := *item
Y, M, _ := item.CreatedAt.Date()
curY, curM, _ := time.Now().Date()
switch {
case curY-Y > 1:
issueCount[moreOneYear] = append(issueCount[moreOneYear], item)
case curM-M > time.Month(1):
issueCount[lessOneYear] = append(issueCount[lessOneYear], item)
case curM-M <= time.Month(1):
issueCount[lessOneMonth] = append(issueCount[lessOneMonth], item)
}
}
var total int
for class, issues := range issueCount {
fmt.Printf("class: %s, issues: %d\n", class, len(issues))
total += len(issues)
}
fmt.Printf("Total: %d", total)
}
|
C++ | UTF-8 | 2,027 | 3.078125 | 3 | [] | no_license | #include<iostream>
using namespace std;
class book
{
private:
int bookId, quantity, presentQuantity;
char name[100], author[100], genre[100],pub[100];
public:
book():bookId(-1),quantity(-1){}
void new_book()
{
cout<<"BookID : ";
cin>>bookId;
cin.ignore();
cout<<"Name : ";
cin.getline(name,100);
cout<<"Author : ";
cin.getline(author,100);
cout<<"Genre : ";
cin.getline(genre,100);
cout<<"Pub : ";
cin.getline(pub,100);
cout<<"Quantity : ";
cin>>quantity;
cin.ignore();
presentQuantity=quantity;
}
void display()
{
cout<<"-----------------------------------"<<endl;
cout<<"BookID : "<<bookId<<endl
<<"Name: "<<name<<endl
<<"Author: "<<author<<endl
<<"Genre : "<<genre <<endl
<<"Publisher : "<<pub<<endl
<<"Quantity : "<<quantity<<endl
<<"Present Quantity : "<<presentQuantity<<endl;
cout<<"-----------------------------------"<<endl;
}
int get_bookID(){return bookId;}
int get_quantity(){return quantity;}
char* get_name(){return name;}
char* get_publisher(){return pub;}
char* get_genre(){return genre;}
char* get_author(){return author;}
int get_presentQuan(){return presentQuantity;}
void set_quantity(int quan){quantity+=quan;presentQuantity+=quan;}
void set_name(char *nam){strcpy(name,nam);}
void set_publisher(char* publisher){strcpy(pub,publisher);}
void set_genre(char* gen){strcpy(genre, gen);}
void set_author(char *auth){strcpy(author,auth);}
void set_presentQuan(){presentQuantity-=1;}
void set_presenQuanincement(){presentQuantity+=1;}
}; |
Java | UTF-8 | 329 | 1.75 | 2 | [] | no_license | package com.selenium.pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
public class MyAccountsPage {
@FindBy(how = How.ID, using = "email")
//@FindBy(how = How.XPATH, using = "//*[@id=\"email\"]")
public static WebElement myAccount;
}
|
Markdown | UTF-8 | 3,044 | 2.90625 | 3 | [
"MIT"
] | permissive | Iron.Layout
==============================================================================
Dynamic layout with support for rendering dynamic templates into regions.
Iron.Layout is the page rendering engine for Iron.Router. Layouts can also
be used independently for composing templates. For example, your app might
have a standard dialog box layout and you want to populate content dynamically
into the dialog box depending upon what kind of dialog it is.
## Reusing Templates with a Layout
```html
<template name="DialogBox">
<div id="header">
{{> yield "header"}}
</div>
<div id="main">
{{> yield}}
</div>
<div id="footer">
{{> yield "footer"}}
</div>
</template>
<template name="SomeDialog">
{{#Layout template="DialogBox" data=getSomeDataContext}}
{{#contentFor "header"}}
<h1>My Header</h1>
{{/contentFor}}
<p>
The main content goes here.
</p>
{{#contentFor "footer"}}
Footer content goes here.
{{/contentFor}}
{{/Layout}}
</template>
```
## From JavaScript
```html
<body>
<div id="optional-container">
</div>
</body>
```
```javascript
if (Meteor.isClient) {
Meteor.startup(function () {
layout = new Iron.Layout({/* template: 'MyLayout', data: dataFunction */ });
// insert the layout with an optinoal container element
layout.insert({el: '#optional-container'});
// set the template for the layout
layout.template('DialogBox');
// set the data context for the layout
layout.data({title: 'Some Layout Title'});
// render MainTemplate into the main region of the layout
layout.render('MainTemplate');
// render the MyHeader template to the 'header' region of the layout.
layout.render('MyHeader', {to: 'header'});
// render the MyFooter template to the 'footer' region of the layout. Also set a custom data context for the region.
layout.render('MyFooter', {to: 'footer', data: {title: 'Custom footer data context'}});
});
}
```
## Rendering Transactions
```javascript
if (Meteor.isClient) {
Meteor.startup(function () {
layout = new Iron.Layout({template: 'DialogBox'});
// insert the layout with an optinoal container element
layout.insert({el: '#optional-container'});
// start recording which regions have been rendered into
layout.beginRendering();
// render MainTemplate into the main region of the layout
layout.render('MainTemplate');
// render the MyHeader template to the 'header' region of the layout.
layout.render('MyHeader', {to: 'header'});
// render the MyFooter template to the 'footer' region of the layout. Also set a custom data context for the region.
layout.render('MyFooter', {to: 'footer', data: {title: 'Custom footer data context'}});
// force a Deps.flush and get an object of
// regions that have been rendered. In this case:
// => {"main": true, "header": true, "footer": true}
var renderedRegions = layout.endRendering();
});
}
```
|
Java | UTF-8 | 6,765 | 3.640625 | 4 | [] | no_license | package jvmConfig;
public class HeapStack {
/*
Java堆空间
Java运行时使用Java堆空间将内存分配给Objects和JRE类。每当我们创建对象时,它总是在堆空间中创建。
垃圾回收在堆内存上运行以释放没有任何引用的对象使用的内存。在堆空间中创建的任何对象都具有全局访问权限,并且可以从应用程序的任何位置进行引用。
Java堆栈内存
Java Stack内存用于执行线程。它们包含短期的特定于方法的值以及对从该方法引用的堆中其他对象的引用。
堆栈存储器始终按LIFO(后进先出)顺序引用。每当调用方法时,都会在堆栈存储器中创建一个新块,以容纳该方法的本地原始值并引用该方法中的其他对象。
方法结束后,该块将立即变为未使用状态,并可用于下一个方法。
与堆内存相比,堆栈内存的大小要小得多。
Java程序中的堆和堆栈内存
让我们通过一个简单的程序来了解堆和堆栈的内存使用情况。
package com.journaldev.test;
public class Memory {
}
“堆内存和堆栈内存的区别”图片展示了上边程序堆和栈内存的引用,并且是怎么用来存储原始值、对象和变量的引用。
我们来看看程序执行的过程:
1、只要我们一运行这个程序,它会加载所有的运行类到堆内存中去,当在第一行找到main()方法的时候,Java创建可以被main()方法线程使用的栈内存。
2、当在第一行,我们创建了本地原始变量,它在main()的栈中创建和保存。
3、因为我们在第三行创建了对象,它在堆内存中被创建,在栈内存中保存了它的引用,同样的过程也发生在第四行我们创建Memory对象的时候。
4、当在第五行我们调用foo()方法的时候,在堆的顶部创建了一个块来被foo()方法使用,因为Java是值传递的,在第六行一个新的对象的引用在foo()方法中的栈中被创建
5、在第七行一个String被创建,它在堆空间中的String池中运行,并且它的引用也在foo()方法的栈空间中被创建
6、foo()方法在第八行结束,此时在堆中为foo()方法分配的内存块可以被释放
7、在第九行,main()方法结束,栈为main()方法创建的内存空间可以被销毁。同样程序也在行结束,Java释放了所有的内存,结束了程序的运行
堆内存和栈内存的区别
基于上边的解释我们可以很简单的总结出堆和栈的区别:
1、应用程序所有的部分都使用堆内存,然后栈内存通过一个线程运行来使用。
2、不论对象什么时候创建,他都会存储在堆内存中,栈内存包含它的引用。栈内存只包含原始值变量好和堆中对象变量的引用。
3、存储在堆中的对象是全局可以被访问的,然而栈内存不能被其他线程所访问。
4、栈中的内存管理使用LIFO的方式完成,而堆内存的管理要更复杂了,因为它是全局被访问的。堆内存被分为,年轻一代,老一代等等,更多的细节请看,这篇文章
5、栈内存是生命周期很短的,然而堆内存的生命周期从程序的运行开始到运行结束。
6、我们可以使用-Xms和-Xmx JVM选项定义开始的大小和堆内存的最大值,我们可以使用-Xss定义栈的大小
7、当栈内存满的时候,Java抛出java.lang.StackOverFlowError异常而堆内存满的时候抛出java.lang.OutOfMemoryError: Java Heap Space错误
8、和堆内存比,栈内存要小的多,因为明确使用了内存分配规则(LIFO),和堆内存相比栈内存非常快。
让我们看一下程序执行的步骤。
一旦运行程序,它将所有运行时类加载到堆空间中。在第1行找到main()方法时,Java Runtime将创建要由main()方法线程使用的堆栈内存。
我们在第2行创建原始的局部变量,因此将其创建并存储在main()方法的堆栈存储器中。
由于我们是在第三行中创建一个对象,因此将在堆内存中创建该对象,而堆栈内存将包含该对象的引用。当我们在第四行中创建Memory对象时,也会发生类似的过程。
现在,当我们在第5行调用foo()方法时,将在堆栈顶部创建一个块,以供foo()方法使用。由于Java是按值传递的,因此在第六行的foo()堆栈块中创建了对Object的新引用。
在第7行创建一个字符串,该字符串进入堆空间的“ 字符串池”,并在foo()堆栈空间中为其创建引用。
foo()方法在第8行终止,这时为堆栈中的foo()分配的内存块变为可用。
在第9行中,main()方法终止,并且为main()方法创建的堆栈存储器被销毁。而且,程序在此行结束,因此Java Runtime释放了所有内存并结束了程序的执行。
Java堆空间和堆栈内存之间的区别
根据以上解释,我们可以轻松得出Heap和Stack内存之间的以下差异。
堆内存由应用程序的所有部分使用,而堆栈内存仅由一个执行线程使用。
每当创建对象时,它始终存储在堆空间中,并且堆栈存储器包含对该对象的引用。堆栈内存仅包含局部原始变量和堆空间中对象的引用变量。
堆中存储的对象可以全局访问,而其他线程则不能访问堆栈内存。
堆栈中的内存管理以LIFO方式完成,而在Heap内存中则更为复杂,因为它在全球范围内使用。堆内存分为Young-Generation,Old-Generation等,有关更多信息,请参见Java Garbage Collection。
堆栈内存是短暂的,而堆内存是从应用程序执行的开始一直到结束。
我们可以使用-Xms和-Xmx JVM选项来定义启动大小和堆内存的最大大小。我们可以使用-Xss定义堆栈内存大小。
当堆栈内存已满时,Java运行时将引发,java.lang.StackOverFlowError而如果堆内存已满,则将引发java.lang.OutOfMemoryError: Java Heap Space错误。
与堆内存相比,堆栈内存的大小要小得多。由于内存分配(LIFO)的简单性,与堆内存相比,堆栈内存非常快
*/
public static void main(String[] args) { // Line 1
int i=1; // Line 2
Object obj = new Object(); // Line 3
HeapStack mem = new HeapStack(); // Line 4
mem.foo(obj); // Line 5
} // Line 9
public void foo(Object param) { // Line 6
String str = param.toString(); //// Line 7
System.out.println(str);
} // Line 8
}
|
Markdown | UTF-8 | 1,061 | 2.984375 | 3 | [
"Apache-2.0"
] | permissive | # 代码埋点
传统代码埋点
实现方案:Coding阶段手动埋点。
代表解决方案:友盟、百度统计。
优点:灵活、准确,可以定制化。
缺点:业务埋点量非常大,开发成本高,不易维护,如果要修改、新增埋点,需要重新发版。
代码埋点是指在产品开发阶段,PM通过对产品上线后需要做的数据分析的场景,设计数据需求,
撰写数据需求文档,然后交由开发在每个需要采集的数据点写入代码,通过写入的代码进行数据监测与上报。
即在需要埋点的节点调用接口直接上传埋点数据,友盟、百度统计等第三方数据统计服务商大都采用这种方案。
## 特点
代码埋点虽然使用起来灵活,但是开发成本较高,并且一旦上线就很难修改。
如果发生严重的数据问题,只能通过发热修复解决。
代码埋点是一种典型的命令式编程,因此埋点代码常常要侵入具体的业务逻辑,这使埋点代码变得很繁琐并且容易出错。
|
Java | UTF-8 | 12,309 | 1.851563 | 2 | [] | no_license | /*
* JBoss, Home of Professional Open Source.
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.jms.serverless;
import org.jboss.logging.Logger;
import java.io.Serializable;
import javax.jms.Session;
import javax.jms.BytesMessage;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.StreamMessage;
import javax.jms.JMSException;
import javax.jms.TextMessage;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.MessageConsumer;
import javax.jms.Destination;
import javax.jms.Queue;
import javax.jms.Topic;
import javax.jms.TopicSubscriber;
import javax.jms.QueueBrowser;
import javax.jms.TemporaryQueue;
import javax.jms.TemporaryTopic;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
/**
*
* @author Ovidiu Feodorov <ovidiu@jboss.org>
* @version $Revision: 57195 $ $Date: 2006-09-26 08:08:17 -0400 (Tue, 26 Sep 2006) $
*
**/
class SessionImpl implements Session {
private static final Logger log = Logger.getLogger(SessionImpl.class);
private SessionManager sessionManager;
private String id;
private List subscribers;
private List receivers;
private boolean transacted;
private int acknowledgeMode;
private int receiverCounter = 0;
/**
* @param id - the session id. The SessionManager instance guarantees uniqueness during its
* lifetime.
**/
SessionImpl(SessionManager sessionManager,
String id,
boolean transacted,
int acknowledgeMode) {
this.sessionManager = sessionManager;
this.id = id;
subscribers = new ArrayList();
receivers = new ArrayList();
this.transacted = transacted;
this.acknowledgeMode = acknowledgeMode;
if (transacted) {
throw new NotImplementedException("Transacted sessions not supported");
}
}
public String getID() {
return id;
}
void send(Message m) throws JMSException {
sessionManager.getConnection().send(m);
}
/**
* Delivery to topic subscribers.
**/
// TO_DO: acknowledgement, deal with failed deliveries
void deliver(Message m) {
// TO_DO: single threaded access for sessions
// So far, the only thread that accesses dispatch() is the connection's puller thread and
// this will be the unique thread that accesses the Sessions. This may not be sufficient
// for high load, consider the possiblity to (dynamically) add new threads to handle
// delivery, possibly a thread per session.
Destination destination = null;
try {
destination = m.getJMSDestination();
}
catch(JMSException e) {
// TO_DO: cannot deliver, a failure handler should take over
log.error("Unhandled failure", e);
return;
}
// TO_DO: properly handle the case when the destination is null
for(Iterator i = subscribers.iterator(); i.hasNext(); ) {
TopicSubscriberImpl sub = (TopicSubscriberImpl)i.next();
if (destination.equals(sub.getDestination())) {
MessageListener l = null;
try {
l = sub.getMessageListener();
}
catch(JMSException e) {
// TO_DO: cannot deliver, a failure handler should take over
log.error("Unhandled failure", e);
continue;
}
if (l == null) {
continue;
}
l.onMessage(m);
}
}
}
/**
* Delivery to queue receivers.
**/
// TO_DO: acknowledgement, deal with failed deliveries
void deliver(Message m, String receiverID) {
// TO_DO: single threaded access for sessions
// So far, the only thread that accesses dispatch() is the connection's puller thread and
// this will be the unique thread that accesses the Sessions. This may not be sufficient
// for high load, consider the possiblity to (dynamically) add new threads to handle
// delivery, possibly a thread per session.
QueueReceiverImpl receiver = null;
for(Iterator i = receivers.iterator(); i.hasNext(); ) {
QueueReceiverImpl crtRec = (QueueReceiverImpl)i.next();
if (crtRec.getID().equals(receiverID)) {
receiver = crtRec;
break;
}
}
if (receiver == null) {
log.error("No such receiver: "+receiverID+". Delivery failed!");
return;
}
MessageListener l = null;
try {
l = receiver.getMessageListener();
}
catch(JMSException e) {
// TO_DO: cannot deliver, a failure handler should take over
log.error("Unhandled failure", e);
return;
}
if (l == null) {
log.warn("No message listener for receiver "+receiverID+". Delivery failed!");
}
else {
l.onMessage(m);
}
}
//
// Session INTERFACE IMPLEMEMENTATION
//
public BytesMessage createBytesMessage() throws JMSException {
throw new NotImplementedException();
}
public MapMessage createMapMessage() throws JMSException {
throw new NotImplementedException();
}
public Message createMessage() throws JMSException {
throw new NotImplementedException();
}
public ObjectMessage createObjectMessage() throws JMSException {
throw new NotImplementedException();
}
public ObjectMessage createObjectMessage(Serializable object) throws JMSException {
throw new NotImplementedException();
}
public StreamMessage createStreamMessage() throws JMSException {
throw new NotImplementedException();
}
public TextMessage createTextMessage() throws JMSException {
return new TextMessageImpl();
}
public TextMessage createTextMessage(String text) throws JMSException {
throw new NotImplementedException();
}
public boolean getTransacted() throws JMSException {
return transacted;
}
public int getAcknowledgeMode() throws JMSException {
return acknowledgeMode;
}
public void commit() throws JMSException {
throw new NotImplementedException();
}
public void rollback() throws JMSException {
throw new NotImplementedException();
}
public void close() throws JMSException {
throw new NotImplementedException();
}
public void recover() throws JMSException {
throw new NotImplementedException();
}
public MessageListener getMessageListener() throws JMSException {
throw new NotImplementedException();
}
public void setMessageListener(MessageListener listener) throws JMSException {
throw new NotImplementedException();
}
public void run() {
throw new NotImplementedException();
}
public MessageProducer createProducer(Destination destination) throws JMSException {
if (destination instanceof Topic) {
return new TopicPublisherImpl(this, (Topic)destination);
}
else if (destination instanceof Queue) {
return new QueueSenderImpl(this, (Queue)destination);
}
throw new JMSException("Destination not a Topic or Queue");
}
public MessageConsumer createConsumer(Destination destination) throws JMSException {
if (destination instanceof Topic) {
TopicSubscriberImpl ts = new TopicSubscriberImpl(this, (Topic)destination);
subscribers.add(ts);
return ts;
}
else if (destination instanceof Queue) {
QueueReceiverImpl qr =
new QueueReceiverImpl(this, generateReceiverID(), (Queue)destination);
sessionManager.advertiseQueueReceiver(getID(), qr, true);
receivers.add(qr);
return qr;
}
throw new JMSException("Destination not a Topic or Queue");
}
public MessageConsumer createConsumer(Destination destination, String messageSelector)
throws JMSException {
throw new NotImplementedException();
}
public MessageConsumer createConsumer(Destination destination,
String messageSelector,
boolean NoLocal)
throws JMSException {
throw new NotImplementedException();
}
public Queue createQueue(String queueName) throws JMSException {
throw new NotImplementedException();
}
public Topic createTopic(String topicName) throws JMSException {
throw new NotImplementedException();
}
public TopicSubscriber createDurableSubscriber(Topic topic,
String name) throws JMSException {
throw new NotImplementedException();
}
public TopicSubscriber createDurableSubscriber(Topic topic,
String name,
String messageSelector,
boolean noLocal) throws JMSException {
throw new NotImplementedException();
}
public QueueBrowser createBrowser(Queue queue) throws JMSException {
throw new NotImplementedException();
}
public QueueBrowser createBrowser(Queue queue,
String messageSelector) throws JMSException {
throw new NotImplementedException();
}
public TemporaryQueue createTemporaryQueue() throws JMSException {
throw new NotImplementedException();
}
public TemporaryTopic createTemporaryTopic() throws JMSException {
throw new NotImplementedException();
}
public void unsubscribe(String name) throws JMSException {
throw new NotImplementedException();
}
//
// END Session INTERFACE IMPLEMEMENTATION
//
/**
* The reverse of createConsumer().
**/
void removeConsumer(MessageConsumer consumer) throws JMSException {
if (consumer instanceof QueueReceiverImpl) {
if (!receivers.contains(consumer)) {
throw new JMSException("No such QueueReceiver: "+consumer);
}
sessionManager.advertiseQueueReceiver(getID(), (QueueReceiverImpl)consumer, false);
receivers.remove(consumer);
}
else if (consumer instanceof TopicSubscriberImpl) {
throw new NotImplementedException();
}
else {
throw new JMSException("MessageConsumer not a TopicSubscriber or a QueueReceiver");
}
}
/**
* Generate a queue receiver ID that is quaranteed to be unique for the life time of this
* Session instance.
**/
private synchronized String generateReceiverID() {
return Integer.toString(receiverCounter++);
}
//
// LIST MANAGEMENT METHODS
//
//private QueueReceiverImpl getReceiver(String receiverID)
//
// END OF LIST MANAGEMENT METHODS
//
}
|
C++ | UTF-8 | 693 | 2.609375 | 3 | [] | no_license | #ifndef FSMANAGER_H
#define FSMANAGER_H
#include "interface/IFSManager.h"
#include "interface/IConfiguration.h"
#include <memory>
/**
* @brief Реализация воркера файловой системы.
*/
class FSManager : public IFSManager
{
public:
/**
* @brief Конструктор воркера ФС
*
* @param configuration - конфигурация приложения
*/
FSManager(std::shared_ptr<IConfiguration> configuration);
std::string readFile(const std::string& name);
void writeFile(const std::string&name, const std::string&data);
private:
std::shared_ptr<IConfiguration> _configuration;
};
#endif // FSMANAGER_H
|
Java | UTF-8 | 1,186 | 2.53125 | 3 | [] | no_license | package robert.trojan.entity;
import javax.persistence.*;
@Entity
@Table(name = "defaultWord")
public class DAODefaultWord {
@GeneratedValue(strategy= GenerationType.AUTO)
@Id
@Column
private Integer id;
@Column
private String word;
@Column
private String definition;
@ManyToOne
private DAODefaultSet defaultSet;
public DAODefaultWord(String word, String definition, DAODefaultSet defaultSet) {
this.word = word;
this.definition = definition;
this.defaultSet = defaultSet;
}
public DAODefaultWord() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public String getDefinition() {
return definition;
}
public void setDefinition(String definition) {
this.definition = definition;
}
public DAODefaultSet getDefualtSet() {
return defaultSet;
}
public void setDefualtSet(DAODefaultSet defaultSet) {
this.defaultSet = defaultSet;
}
}
|
C# | UTF-8 | 16,609 | 2.890625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CoreMP
{
/// <summary>
/// The LibraryScanController carries out the asynchronous actions involved in scanning a library
/// </summary>
internal class LibraryScanController
{
/// <summary>
/// Asynchronous method called to carry out a library scan
/// </summary>
/// <param name="libraryToScan"></param>
public async void ScanLibraryAsynch( Library libraryToScan, Action scanFinished, Func<bool> scanCancelledCheck )
{
// Ignore this if there is already a scan in progress
if ( scanInProgress == false )
{
// Prevent this from being executed twice
scanInProgress = true;
// Keep track of any existing songs that have not been matched in the scan
List<Song> unmatchedSongs = new List<Song>();
// Keep track of all the albums that have been scanned
List<ScannedAlbum> newAlbums = new List<ScannedAlbum>();
// Keep track of the songs for which the album name has changed
List<Song> songsWithChangedAlbumNames = new List<Song>();
// Form a lookup table for Artists in this library
artistsInLibrary = Artists.ArtistCollection.Where( art => art.LibraryId == libraryToScan.Id ).ToDictionary( art => art.Name.ToUpper() );
await Task.Run( async () =>
{
foreach ( Source source in libraryToScan.Sources )
{
// Get the songs as well as we're going to need them below
source.GetSongs();
// Add the songs from this source to a dictionary. For UPnP sources don't use the path stored with the song as that may have
// changed. Instead use a combination of the Artist Name, Song Name, Album Name and track number
Dictionary<string, Song> pathLookup = null;
if ( source.AccessMethod != Source.AccessType.UPnP )
{
pathLookup = new Dictionary<string, Song>( source.Songs.ToDictionary( song => song.Path ) );
}
else
{
pathLookup = new Dictionary<string, Song>();
foreach ( Song songToAdd in source.Songs )
{
string key = $"{songToAdd.Album.ArtistName}:{songToAdd.Title}:{songToAdd.Album.Name}:{songToAdd.Track}";
if ( pathLookup.ContainsKey( key ) == false )
{
pathLookup[ key ] = songToAdd;
}
else
{
Logger.Log( string.Format( $"Duplicate song key {key}" ) );
}
}
}
// Reset the scan action for all Songs
source.Songs.ForEach( song => song.ScanAction = Song.ScanActionType.NotMatched );
// Use a SongStorage instance to check for song changes
SongStorage scanStorage = new SongStorage( source, pathLookup );
// Check the source scanning method
if ( source.AccessMethod == Source.AccessType.FTP )
{
// Scan using the generic FTPScanner but with our callbacks
await new FTPScanner( scanStorage, scanCancelledCheck ).Scan( source.ScanSource );
}
else if ( source.AccessMethod == Source.AccessType.Local )
{
// Scan using the generic InternalScanner but with our callbacks
await new InternalScanner( scanStorage, scanCancelledCheck ).Scan( source.ScanSource );
}
else if ( source.AccessMethod == Source.AccessType.UPnP )
{
// Scan using the generic UPnPScanner but with our callbacks
await new UPnPScanner( scanStorage, scanCancelledCheck ).Scan( source.ScanSource );
}
// Add any unmatched songs to a list that'll be processed when all sources have been scanned
unmatchedSongs.AddRange( pathLookup.Values.Where( song => song.ScanAction == Song.ScanActionType.NotMatched ) );
// Add the new scanned albums to the model
newAlbums.AddRange( scanStorage.NewAlbums );
// Add the songs with changed albums names to the model
songsWithChangedAlbumNames.AddRange( scanStorage.SongsWithChangedAlbumNames );
}
// If the scan process has not been cancelled then store the scanned albums and delete any unmatched songs
if ( scanCancelledCheck.Invoke() == false )
{
// Delete songs for which the album name has changed
DeleteSongs( songsWithChangedAlbumNames );
foreach ( ScannedAlbum album in newAlbums )
{
await StoreAlbumAsync( album, libraryToScan.Id );
}
// Delete unmatched songs
DeleteSongs( unmatchedSongs );
}
} );
// If there have been any changes to the library, and it is the library currently being displayed then force a refresh
if ( ( ( songsWithChangedAlbumNames.Count > 0 ) || ( newAlbums.Count > 0 ) || ( unmatchedSongs.Count > 0 ) ) &&
( libraryToScan.Id == ConnectionDetailsModel.LibraryId ) )
{
new SelectedLibraryChangedMessage() { SelectedLibrary = libraryToScan.Id }.Send();
}
scanInProgress = false;
// Report the completion back through the delegate
scanFinished.Invoke();
}
}
/// <summary>
/// Delete the list of songs from the library
/// </summary>
/// <param name="songsToDelete"></param>
private void DeleteSongs( List<Song> songsToDelete )
{
// Keep track of any albums that are deleted so that other controllers can be notified
List<int> deletedAlbumIds = new List<int>();
// Delete all the Songs.
Songs.DeleteSongs( songsToDelete );
// Delete all the PlaylistItems associated with the songs.
Playlists.DeletePlaylistItems( songsToDelete.Select( song => song.Id ).ToHashSet() );
// Form a distinct list of all the ArtistAlbum items referenced by the deleted songs
IEnumerable<int> artistAlbumIds = songsToDelete.Select( song => song.ArtistAlbumId ).Distinct();
// Check if any of these ArtistAlbum items are now empty and need deleting
foreach ( int id in artistAlbumIds )
{
int deletedAlbumId = CheckForAlbumDeletion( id );
if ( deletedAlbumId != -1 )
{
deletedAlbumIds.Add( deletedAlbumId );
}
}
if ( deletedAlbumIds.Count > 0 )
{
new AlbumsDeletedMessage() { DeletedAlbumIds = deletedAlbumIds }.Send();
}
}
/// <summary>
/// Called to process a group of songs belonging to the same album name ( but not necessarily the same artist )
/// </summary>
/// <param name="album"></param>
private async Task StoreAlbumAsync( ScannedAlbum album, int libraryId )
{
Logger.Log( string.Format( "Album: {0} Single artist: {1}", album.Name, album.SingleArtist ) );
// Get an existing or new Album entry for the songs
Album songAlbum = await GetAlbumToHoldSongsAsync( album, libraryId );
// Keep track of Artist and ArtistAlbum entries in case they can be reused for different artists
ArtistAlbum songArtistAlbum = null;
Artist songArtist = null;
// Add all the songs in the album
foreach ( ScannedSong songScanned in album.Songs )
{
// If there is no existing Artist entry or the current one if for the wrong Artist name then get or create a new one
if ( ( songArtist == null ) || ( songArtist.Name != songScanned.ArtistName ) )
{
// As this is a new Artist the ArtistAlbum needs to be re-initialised.
if ( songArtistAlbum != null )
{
songArtistAlbum.Songs.Sort( ( a, b ) => a.Track.CompareTo( b.Track ) );
}
songArtistAlbum = null;
// Find the Artist for this song
songArtist = await GetArtistToHoldSongsAsync( songScanned.ArtistName, libraryId );
}
// If there is an existing ArtistAlbum then use it as it will be for the correct Artist, i.e. not cleared above
if ( songArtistAlbum == null )
{
// Find an existing or create a new ArtistAlbum entry
songArtistAlbum = await GetArtistAlbumToHoldSongsAsync( songArtist, songAlbum );
}
// Add the song to the database, the album and the album artist
Song songToAdd = new Song()
{
Title = songScanned.Tags.Title,
Track = songScanned.Track,
Path = songScanned.SourcePath,
ModifiedTime = songScanned.Modified,
Length = songScanned.Length,
AlbumId = songAlbum.Id,
ArtistAlbumId = songArtistAlbum.Id,
SourceId = album.ScanSource.Id
};
// No need to wait for this
await Songs.AddSongAsync( songToAdd );
Logger.Log( string.Format(
"Song added with Artist: {0} Title: {1} Track: {2} Modified: {3} Length {4} Year {5} Album Id: {6} ArtistAlbum Id: {7}",
songScanned.Tags.Artist, songScanned.Tags.Title, songScanned.Tags.Track, songScanned.Modified, songScanned.Length, songScanned.Year,
songToAdd.AlbumId, songToAdd.ArtistAlbumId ) );
// Add to the Album
songAlbum.Songs.Add( songToAdd );
// Keep track whether or not to update the album
bool updateAlbum = false;
// Store the artist name with the album
if ( ( songAlbum.ArtistName == null ) || ( songAlbum.ArtistName.Length == 0 ) )
{
songAlbum.ArtistName = songArtist.Name;
updateAlbum = true;
}
else
{
// The artist has already been stored - check if it is the same artist
if ( songAlbum.ArtistName != songArtist.Name )
{
songAlbum.ArtistName = SongStorage.VariousArtistsString;
updateAlbum = true;
}
}
// Update the album year if not already set and this song has a year set
if ( ( songAlbum.Year != songScanned.Year ) && ( songAlbum.Year == 0 ) )
{
songAlbum.Year = songScanned.Year;
updateAlbum = true;
}
// Update the album genre.
// Only try updating if a genre is defined for the song
// If the album does not have a genre then get one for the song and store it in the album
if ( ( songScanned.Tags.Genre.Length > 0 ) && ( songAlbum.Genre.Length == 0 ) )
{
songAlbum.Genre = songScanned.Tags.Genre;
updateAlbum = true;
}
if ( updateAlbum == true )
{
await DbAccess.UpdateAsync( songAlbum );
}
// Add to the source
album.ScanSource.Songs.Add( songToAdd );
// Add to the ArtistAlbum
songArtistAlbum.Songs.Add( songToAdd );
}
if ( songArtistAlbum != null )
{
songArtistAlbum.Songs.Sort( ( a, b ) => a.Track.CompareTo( b.Track ) );
}
}
/// <summary>
/// Either find an existing album or create a new album to hold the songs.
/// If all songs are from the same artist then check is there is an existing album of the same name associated with that artist.
/// If the songs are from different artists then check in the "Various Artists" artist.
/// These artists may not exist at this stage
/// </summary>
/// <returns></returns>
private async Task<Album> GetAlbumToHoldSongsAsync( ScannedAlbum album, int libraryId )
{
Album songAlbum = null;
string artistName = ( album.SingleArtist == true ) ? album.Songs[ 0 ].ArtistName : SongStorage.VariousArtistsString;
// Check if the artist already exists in the library.
Artist songArtist = artistsInLibrary.GetValueOrDefault( artistName.ToUpper() );
// If the artist exists then check for existing album. The artist will hold ArtistAlbum entries rather than Album entries, but the ArtistAlbum entries
// have the same name as the albums. Cannot just use the album name as that may not be unique.
if ( songArtist != null )
{
ArtistAlbum songArtistAlbum = songArtist.ArtistAlbums.SingleOrDefault( p => ( p.Name.ToUpper() == album.Songs[ 0 ].Tags.Album.ToUpper() ) );
if ( songArtistAlbum != null )
{
Logger.Log( string.Format( "Artist {0} and ArtistAlbum {1} both found", artistName, songArtistAlbum.Name ) );
songAlbum = songArtistAlbum.Album;
}
else
{
Logger.Log( string.Format( "Artist {0} found ArtistAlbum {1} not found", artistName, album.Songs[ 0 ].Tags.Album ) );
}
}
else
{
Logger.Log( string.Format( "Artist {0} for album {1} not found", artistName, album.Name ) );
}
// If no existing album create a new one
if ( songAlbum == null )
{
songAlbum = new Album() { Name = album.Name, LibraryId = libraryId };
await Albums.AddAlbumAsync( songAlbum );
Logger.Log( string.Format( "Create album {0} Id: {1}", songAlbum.Name, songAlbum.Id ) );
}
return songAlbum;
}
/// <summary>
/// Get an existing Artist or create a new one.
/// </summary>
/// <param name="artistName"></param>
/// <returns></returns>
private async Task<Artist> GetArtistToHoldSongsAsync( string artistName, int libraryId )
{
// Find the Artist for this song. The 'scanLibrary' can be used for this search as it is already fully populated with the
// artists
Artist songArtist = artistsInLibrary.GetValueOrDefault( artistName.ToUpper() );
if ( songArtist == null )
{
// Create a new Artist and add it to the database
songArtist = new Artist() { Name = artistName, ArtistAlbums = new List<ArtistAlbum>(), LibraryId = libraryId };
await Artists.AddArtistAsync( songArtist );
Logger.Log( string.Format( "Artist: {0} not found. Created with Id: {1}", artistName, songArtist.Id ) );
// Add it to the collection for this library only
artistsInLibrary[ songArtist.Name.ToUpper() ] = songArtist;
}
else
{
Logger.Log( string.Format( "Artist: {0} found with Id: {1}", songArtist.Name, songArtist.Id ) );
}
return songArtist;
}
/// <summary>
/// Get an existing or new ArtistAlbum entry to hold the songs associated with a particular Artist
/// </summary>
/// <param name="songArtist"></param>
/// <param name="songAlbum"></param>
/// <returns></returns>
private async Task<ArtistAlbum> GetArtistAlbumToHoldSongsAsync( Artist songArtist, Album songAlbum )
{
ArtistAlbum songArtistAlbum = null;
// Find an existing or create a new ArtistAlbum entry
songArtistAlbum = songArtist.ArtistAlbums.SingleOrDefault( p => ( p.Name.ToUpper() == songAlbum.Name.ToUpper() ) );
Logger.Log( string.Format( "ArtistAlbum: {0} {1}", songAlbum.Name, ( songArtistAlbum != null ) ? "found" : "not found creating in db" ) );
if ( songArtistAlbum == null )
{
// Create a new ArtistAlbum and add it to the database and the Artist
songArtistAlbum = new ArtistAlbum()
{
Name = songAlbum.Name,
Album = songAlbum,
Songs = new List<Song>(),
ArtistId = songArtist.Id,
Artist = songArtist,
AlbumId = songAlbum.Id
};
await ArtistAlbums.AddArtistAlbumAsync( songArtistAlbum );
Logger.Log( string.Format( "ArtistAlbum: {0} created with Id: {1}", songArtistAlbum.Name, songArtistAlbum.Id ) );
songArtist.ArtistAlbums.Add( songArtistAlbum );
}
else
{
Logger.Log( string.Format( "ArtistAlbum: {0} found with Id: {1}", songArtistAlbum.Name, songArtistAlbum.Id ) );
// Get the children of the existing ArtistAlbum
if ( songArtistAlbum.Songs == null )
{
songArtistAlbum.Songs = Songs.GetArtistAlbumSongs( songArtistAlbum.Id );
}
}
return songArtistAlbum;
}
/// <summary>
/// Check if the specified ArtistAlbum should be deleted and any associated Album or Artist
/// </summary>
/// <param name="artistAlbumId"></param>
/// <returns></returns>
private int CheckForAlbumDeletion( int artistAlbumId )
{
// Keep track in the Tuple of any albums or artists deleted
int deletedAlbumId = -1;
// Refresh the contents of the ArtistAlbum
ArtistAlbum artistAlbum = ArtistAlbums.GetArtistAlbumById( artistAlbumId );
artistAlbum.Songs = Songs.GetArtistAlbumSongs( artistAlbum.Id );
// Check if this ArtistAlbum is being referenced by any songs
if ( artistAlbum.Songs.Count == 0 )
{
// Delete the ArtistAlbum as it is no longer being referenced
ArtistAlbums.DeleteArtistAlbum( artistAlbum );
// Remove this ArtistAlbum from the Artist
Artist artist = Artists.GetArtistById( artistAlbum.ArtistId );
artist.ArtistAlbums.Remove( artistAlbum );
// Does the associated Artist have any other Albums
if ( artist.ArtistAlbums.Count == 0 )
{
// Delete the Artist
Artists.DeleteArtist( artist );
}
// Does any other ArtistAlbum reference the Album
if ( ArtistAlbums.ArtistAlbumCollection.Any( art => art.AlbumId == artistAlbum.AlbumId ) == false )
{
// Not referenced by any ArtistAlbum. so delete it
Albums.DeleteAlbum( artistAlbum.Album );
deletedAlbumId = artistAlbum.AlbumId;
}
}
return deletedAlbumId;
}
/// <summary>
/// Flag indicating whether or not the this controller is busy scanning a library
/// </summary>
private bool scanInProgress = false;
/// <summary>
/// The Artists in the Library being scanned
/// </summary>
private Dictionary<string, Artist> artistsInLibrary = null;
}
}
|
C++ | UTF-8 | 1,212 | 2.875 | 3 | [] | no_license | //Name: Saurav Bhattarai
//File: Alien.h
#ifndef ALIEN_H
#define ALIEN_H
#include "Game_obj.h"
#include "Laser.h"
#include <string>
class Alien: public Game_obj
{
protected:
int full_health_;
int health_;
std::string state_;
Image & image_;
bool isalive_;
int dx_;
int dy_;
int score_;
int org_x_;
int org_y_;
int last_shooted_;
public:
Alien(Image & image, int x, int y, int dx, int dy)
: image_(image), Game_obj(image, x, y), full_health_(0), health_(0), state_("NORMAL"), isalive_(true), dx_(dx), dy_(dy)
, score_(0), org_x_(x), org_y_(y), last_shooted_(0)
{}
void print(Surface &) const;
void move(bool &, int, std::list< Laser> &);
void attack();
void shoot(std::list< Laser > &) const;
bool isalive() const;
bool & isalive();
int health() const;
int & health();
int full_health() const;
int x() const;
int y() const;
int & x();
int & y();
int org_x() const;
int org_y() const;
int & org_x();
int & org_y();
int dx() const;
int dy() const;
int & dx();
int & dy();
int score() const;
std::string state() const;
std::string & state();
};
#endif
|
Java | UTF-8 | 9,340 | 2.53125 | 3 | [
"BSD-2-Clause"
] | permissive | package jpaint;
import javafx.application.Platform;
import javafx.embed.swing.SwingFXUtils;
import javafx.fxml.FXML;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.*;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import jpaint.exceptions.AlertException;
import javax.imageio.ImageIO;
import java.awt.*;
import javafx.print.PrinterJob;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import static jpaint.helpers.*;
/**
* The class with the FXML functionality methods
*
* @author Carter Brainerd
* @version 1.0.3 14 Apr 2017
*
*/
@SuppressWarnings("JavaDoc") // For custom tags
public class PaintController {
@FXML
private Canvas canvas;
@FXML
private ColorPicker colorPicker;
@FXML
private TextField brushSize;
@FXML
private CheckBox eraser;
@FXML
private MenuButton brushSelectButton;
// For onSaveAs
private final FileChooser fileChooser = new FileChooser();
// For onOpen
private final FileChooser openFileChooser = new FileChooser();
// For setBrushBrush and setBrushPencil
private boolean isBrushBrush;
/**
* Called automatically by the <code>FXMLLoader</code>.
* Allows for the actual painting to happen on the <code>Canvas</code>
* @since 1.0.0
* @custom.Updated 1.0.2
*/
public void initialize() {
GraphicsContext g = canvas.getGraphicsContext2D();
setBrushBrush();
// Get screen dimensions and set the canvas accordingly
Dimension screenSize = getScreenSize();
double screenWidth = screenSize.getWidth();
double screenHeight = screenSize.getHeight();
canvas.setHeight(screenHeight/1.5);
canvas.setWidth(screenWidth/1.5);
canvas.setStyle("-fx-background-color: rgba(255, 255, 255, 1);"); //Set the background to be translucent
canvas.setOnMouseDragged(e -> {
double size = Double.parseDouble(brushSize.getText());
double x = e.getX() - size / 2;
double y = e.getY() - size / 2;
if (eraser.isSelected()) {
g.clearRect(x, y, size, size);
} else {
g.setFill(colorPicker.getValue());
if (isBrushBrush) {
g.fillOval(x, y, size, size);
} else {
g.fillRect(x, y, size, size);
}
}
});
canvas.setOnMouseClicked(e -> {
double size = Double.parseDouble(brushSize.getText());
double x = e.getX() - size / 2;
double y = e.getY() - size / 2;
if (eraser.isSelected()) {
g.clearRect(x, y, size, size);
} else {
g.setFill(colorPicker.getValue());
if(isBrushBrush) {
g.fillOval(x, y, size, size);
} else {
g.fillRect(x, y, size, size);
}
}
});
}
/**
* Saves a <code>png</code> snapshot of the image (as of 1.0.0, it's <code>paint.png</code>)
* @since 1.0.0
*/
public void onSave(){
try{
Image snapshot = canvas.snapshot(null, null);
ImageIO.write(SwingFXUtils.fromFXImage(snapshot, null), "png", new File("paint.png"));
infoAlert("Image saved to " + new File("paint.png").getAbsolutePath(), "Save successful.");
log("Image saved to " + new File("paint.png").getAbsolutePath(), LogType.SUCCESS);
} catch (Exception e){
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
log(sw.toString(), LogType.ERROR);
}
}
/**
* Opens a <code>FileChooser</code> window and saves the image as the inputted name.png
* @see javafx.stage.FileChooser
* @see javax.imageio.ImageIO
* @since 1.0.1
*/
public void onSaveAs(){
Stage stage = new Stage(StageStyle.UTILITY);
fileChooser.setTitle("Save Image As");
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("PNG files", "*.png");
fileChooser.getExtensionFilters().add(extFilter);
try {
Image snapshot = canvas.snapshot(null, null);
File file = fileChooser.showSaveDialog(stage);
String filepath = file.getAbsolutePath();
// This is just a failsafe
if (file != null) {
ImageIO.write(SwingFXUtils.fromFXImage(snapshot, null), "png", file);
log("Image saved to " + filepath, LogType.SUCCESS);
} else {
log("Saving action cancelled", LogType.WARNING);
}
} catch (Exception e){
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
log(sw.toString(), LogType.ERROR);
}
}
/**
* Opens a file and displays it on the <code>Canvas</code>
* @since 1.0.1
* @custom.Updated 1.0.2
*/
public void onOpen(){
GraphicsContext g = canvas.getGraphicsContext2D();
Stage stage = new Stage(StageStyle.UTILITY);
openFileChooser.setTitle("Open Image");
// PNG file filter
FileChooser.ExtensionFilter pngFilter = new FileChooser.ExtensionFilter("PNG files", "*.png");
openFileChooser.getExtensionFilters().add(pngFilter);
// JPEG file filter
FileChooser.ExtensionFilter jpegFilter = new FileChooser.ExtensionFilter("JPG files", "*.jpeg, *.jpg");
openFileChooser.getExtensionFilters().add(jpegFilter);
try{
File openImageFile = openFileChooser.showOpenDialog(stage);
InputStream fileStream = new FileInputStream(openImageFile);
Image openImage = new Image(fileStream);
String filepath = openImageFile.getAbsolutePath();
if (openImageFile != null){
g.drawImage(openImage, 0, 0);
log("Opened " + filepath, LogType.SUCCESS);
} else {
log("Tried to open a file with a blank filename", LogType.WARNING);
}
} catch (Exception e){
log("Couldn't open file. Error: " + e.getStackTrace().toString(), LogType.ERROR);
}
}
/**
* Has the user select a printer, then starts a <code>PrinterJob</code> to print the canvas
* @see javafx.print.PrinterJob
*/
public void onPrint(){
PrinterJob job = PrinterJob.createPrinterJob();
if (job != null && job.showPrintDialog(canvas.getScene().getWindow())) {
boolean success = job.printPage(canvas);
if (success) {
job.endJob();
}
}
}
/**
* Exits out of the program
* @since 1.0.0
*/
public void onExit(){
log("Exiting program", LogType.INFO);
Platform.exit();
}
/**
* Displays the "about" message using {@link helpers#alertUser(String, String, String, Alert.AlertType)}
* @since 1.0.0
*/
public void displayAbout(){
String s = "Author: Carter Brainerd\n" +
"JPaint version: 1.0.3\n" +
"JPaint is a free and open source software written in JavaFX.\n" +
"See the source here: https://github.com/thecarterb/JPaint\n";
try {
alertUser("About JPaint", s, "About JPaint", Alert.AlertType.INFORMATION);
} catch (AlertException ae){
log(ae.toString(), LogType.ERROR);
}
}
/**
* Opens a GitHub link to the source code of JPaint
* @since 1.0.3
* @throws AlertException If the error alert can't show
* @throws IOException If the GitHub URL wasn't reachable
*/
public void openSource() throws AlertException, IOException{
if(Desktop.isDesktopSupported()){
try {
Desktop.getDesktop().browse(new URI("https://github.com/thecarterb/JPaint"));
log("Source code successfully opened in browser", LogType.SUCCESS);
} catch (IOException | URISyntaxException e){
errorAlert("Unable to open URL", "Error");
log(e.getMessage(), LogType.ERROR);
}
} else {
System.err.println("Unable to open source.");
log("Desktops are not supported on your OS!", LogType.WARNING);
}
}
/**
* Setter for brush type (Changes it to circle)
* @since 1.0.2
*/
public void setBrushBrush(){
isBrushBrush = true;
brushSelectButton.setText("Brush");
}
/**
* Setter for brush type (Changes it to square)
* @since 1.0.2
*/
public void setBrushPencil(){
isBrushBrush = false;
brushSelectButton.setText("Pencil");
}
/**
* Clears the <code>canvas</code>
*
* @since 1.0.3
*/
public void onClear() {
GraphicsContext g = canvas.getGraphicsContext2D();
g.clearRect(0, 0, 10000, 10000);
log("Canvas cleared", LogType.INFO);
}
}
|
Java | UTF-8 | 3,404 | 1.8125 | 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.
*/
package com.aliyuncs.rds.model.v20140815;
import java.util.List;
import com.aliyuncs.AcsResponse;
import com.aliyuncs.rds.transform.v20140815.DescribeDBInstanceHAConfigResponseUnmarshaller;
import com.aliyuncs.transform.UnmarshallerContext;
/**
* @author auto create
* @version
*/
public class DescribeDBInstanceHAConfigResponse extends AcsResponse {
private String dBInstanceId;
private String requestId;
private String hAMode;
private String syncMode;
private List<NodeInfo> hostInstanceInfos;
public String getDBInstanceId() {
return this.dBInstanceId;
}
public void setDBInstanceId(String dBInstanceId) {
this.dBInstanceId = dBInstanceId;
}
public String getRequestId() {
return this.requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public String getHAMode() {
return this.hAMode;
}
public void setHAMode(String hAMode) {
this.hAMode = hAMode;
}
public String getSyncMode() {
return this.syncMode;
}
public void setSyncMode(String syncMode) {
this.syncMode = syncMode;
}
public List<NodeInfo> getHostInstanceInfos() {
return this.hostInstanceInfos;
}
public void setHostInstanceInfos(List<NodeInfo> hostInstanceInfos) {
this.hostInstanceInfos = hostInstanceInfos;
}
public static class NodeInfo {
private String logSyncTime;
private String nodeType;
private String zoneId;
private String syncStatus;
private String dataSyncTime;
private String nodeId;
private String regionId;
public String getLogSyncTime() {
return this.logSyncTime;
}
public void setLogSyncTime(String logSyncTime) {
this.logSyncTime = logSyncTime;
}
public String getNodeType() {
return this.nodeType;
}
public void setNodeType(String nodeType) {
this.nodeType = nodeType;
}
public String getZoneId() {
return this.zoneId;
}
public void setZoneId(String zoneId) {
this.zoneId = zoneId;
}
public String getSyncStatus() {
return this.syncStatus;
}
public void setSyncStatus(String syncStatus) {
this.syncStatus = syncStatus;
}
public String getDataSyncTime() {
return this.dataSyncTime;
}
public void setDataSyncTime(String dataSyncTime) {
this.dataSyncTime = dataSyncTime;
}
public String getNodeId() {
return this.nodeId;
}
public void setNodeId(String nodeId) {
this.nodeId = nodeId;
}
public String getRegionId() {
return this.regionId;
}
public void setRegionId(String regionId) {
this.regionId = regionId;
}
}
@Override
public DescribeDBInstanceHAConfigResponse getInstance(UnmarshallerContext context) {
return DescribeDBInstanceHAConfigResponseUnmarshaller.unmarshall(this, context);
}
}
|
C | UTF-8 | 1,472 | 4.34375 | 4 | [] | no_license | /*
* Date: 2018-10-14
*
* Description:
* Maximize value of (a[i] - i) - (a[j] - j) in an unsorted array
*
* Approach:
* Consider a[i] - i and a[j] - j as independent, idea is to find maximum and
* minimum value of a[x] - x and subtract them to max required value.
*
* Complexity:
* O(N)
*/
#include "stdio.h"
#include "stdlib.h"
int main() {
int i = 0;
int n = 0;
int *a = NULL;
int max = 0, min = 65536;
printf("Enter number of elements: ");
scanf("%d", &n);
a = (int *)malloc(sizeof(int) * n);
for (i = 0; i < n; i++) {
printf("Enter element[%d]: ", i);
scanf("%d", &a[i]);
}
for (i = 0; i < n; i++) {
if (max < a[i] - i)
max = a[i] - i;
if (min > a[i] - i)
min = a[i] - i;
}
printf ("Max((a[i] - i) - (a[j] - j)) is: %d\n", max - min);
return 0;
}
/*
* Output:
* -------------------
* Enter number of elements: 5
* Enter element[0]: 1
* Enter element[1]: 2
* Enter element[2]: 3
* Enter element[3]: 4
* Enter element[4]: 5
* Max((a[i] - i) - (a[j] - j)) is: 0
*
* Enter number of elements: 5
* Enter element[0]: 5
* Enter element[1]: 4
* Enter element[2]: 3
* Enter element[3]: 2
* Enter element[4]: 1
* Max((a[i] - i) - (a[j] - j)) is: 8
*
* Enter number of elements: 7
* Enter element[0]: 2
* Enter element[1]: 5
* Enter element[2]: 9
* Enter element[3]: 10
* Enter element[4]: 0
* Enter element[5]: 3
* Enter element[6]: 4
* Max((a[i] - i) - (a[j] - j)) is: 11
*/
|
Python | UTF-8 | 173 | 2.84375 | 3 | [] | no_license | i,j=1,1;
while(i<=10):
print("*Arquam");
i+=1;
while(j<=10):
if(j%2==0):
print("\[]One-EXPLOITS's")
j+=1;
print("\n\ni===",i,"j==",j) |
C# | UTF-8 | 1,063 | 2.75 | 3 | [] | no_license | using AutoMapper;
using BLL.Interface.Entities;
using BLL.Interface.Factories;
using System.Collections.Generic;
using System.Linq;
namespace BLL.Mappers
{
public static class EntitiesMapper
{
public static List<AbstractBankAccount> ToAbstractBankAccountList(List<DAL.Interface.DTO.BankAccount> accounts)
{
return accounts.Select((m) =>
{
var result = BankAccountFactory.Create(Mapper.Map<BankAccountType>(m.AccountType), m.AccountNumber);
result.Owner = Mapper.Map<AccountOwner>(m.Owner);
result.Balance = m.Balance;
result.BonusPoints = m.BonusPoints;
return result;
}).ToList();
}
public static DAL.Interface.DTO.BankAccount ToDtoBankAccont(AbstractBankAccount account)
{
var result = DAL.Interface.Factories.BankAccountFactory.Create(
(DAL.Interface.DTO.BankAccountType)(int)account.AccountType, account.AccountNumber);
result.Owner = Mapper.Map<DAL.Interface.DTO.AccountOwner>(account.Owner);
result.Balance = account.Balance;
result.BonusPoints = account.BonusPoints;
return result;
}
}
}
|
C | UTF-8 | 746 | 3.078125 | 3 | [
"MIT"
] | permissive | #include <stdio.h>
#include <unistd.h>
int main(){
int len,i,apipe[2];
char buf[BUFSIZ];
if(pipe(apipe) == -1){
perror("could not make pipe");
exit(1);
}
printf("got a pipe!it is file descriptors:{ %d %d }\n",apipe[0],apipe[1]);
while(fgets(buf,BUFSIZ,stdin)){
len = strlen(buf);
if(write(apipe[1],buf,len) != len){
perror("writing to pipe");
break;
}
for(i =0;i<len;i++){
buf[i] = 'X';
}
len = read(apipe[0],buf,BUFSIZ);
if(len == -1){
perror("reading from pipe");
break;
}
if(write(1,buf,len)!=len){
perror("write stdout");
break;
}
}
} |
C++ | UTF-8 | 1,303 | 3.515625 | 4 | [] | no_license | //
// Created by ZachZhang on 2017/5/1.
//
#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;
class Solution {
public:
int findMinDifference(vector<string>& timePoints) {
vector<string> times(timePoints);
bool flag = false;
for (auto str : timePoints) {
if (str.substr(0, 2) == "00") {
times.push_back("24" + str.substr(2, 3));
flag = true;
}
}
sort(times.begin(), times.end());
if (!flag) {
int hour = stoi(times[0].substr(0, 2)) + 24;
times.push_back(to_string(hour) + times[0].substr(2, 3));
}
int hour1, hour2, minute1, minute2;
int min_minute = 24 * 60;
for (int i=0; i < times.size() - 1; i++) {
hour1 = atoi(times[i].substr(0, 2).c_str());
hour2 = atoi(times[i+1].substr(0, 2).c_str());
minute1 = atoi(times[i].substr(3, 2).c_str());
minute2 = atoi(times[i+1].substr(3, 2).c_str());
min_minute = min((hour2 - hour1) * 60 + minute2 - minute1, min_minute);
}
return min_minute;
}
};
int main(void) {
Solution s;
vector<string> strv = {"05:31", "22:08", "00:35"};
cout << s.findMinDifference(strv) << endl;
} |
Python | UTF-8 | 6,831 | 2.734375 | 3 | [] | no_license | #!/usr/bin python
#coding=utf-8
############################
# @author Jason Wong
# @date 2013-12-08
############################
# connect to aotm db
# generate documents of songs
############################
import MySQLdb
import sys
import numpy
import pylab as pl
import logging
import os
from nltk.stem.lancaster import LancasterStemmer
import DBProcess
import matplotlib.pyplot as plt
# reload sys and set encoding to utf-8
reload(sys)
sys.setdefaultencoding('utf-8')
# set log's localtion and level
logging.basicConfig(filename=os.path.join(os.getcwd(),'log/docgenerate_log.txt'),level=logging.DEBUG,format='%(asctime)s-%(levelname)s:%(message)s')
# define some global varibale
DBHOST = 'localhost'
DBUSER = 'root'
DBPWD = 'wst'
DBPORT = 3306
DBNAME = 'aotm'
DBCHARSET = 'utf8'
#read stop words from stop words file
# return stop words list
def readStopwordsFromFile(filename):
words = []
stopfile = open(filename,"r")
while 1:
line = stopfile.readline()
if not line:
break
line = line.rstrip('\n')
line = line.strip()
line = line.lower()
if line not in words:
words.append(line)
stopfile.close()
return words
#combine two stop words lists
#return a combined stopwords list/file
def combineTwoStopwordsFile():
if os.path.exists("stopwords.txt"):
print "stop words file is existing......"
return
first = readStopwordsFromFile("EnglishStopWords_datatang.txt")
second = readStopwordsFromFile("EnglishStopWords_url.txt")
result = list(set(first).union(set(second)))
rFile = open("stopwords.txt","w")
for word in result:
rFile.write(word+'\n')
rFile.close()
return result
#get stopwords list
stopwords = readStopwordsFromFile("stopwords.txt")
vocabulary = []
#add word to word dictionary
#tagDict:word dictionary of a song(word:count)
#tagStr:tag string
#tagCount:the count of tag's appearance
def addItemToDict(tagDict,tagStr,tagCount):
#include global variable
global vocabulary
#stemmer
st = LancasterStemmer()
#split tagStr
items = tagStr.split()
for item in items:
item = item.lower()
#stem
item = st.stem(item)
#remove stopwords and too short words
if item not in stopwords and len(item) > 1:
if item not in tagDict:
tagDict[item] = tagCount
else:
tagDict[item] = tagDict[item] + tagCount
#add item to vocabulary list
if item not in vocabulary:
vocabulary.append(item)
#generate tag dictionary of given song
def generateTagDictofSong(sname,aname,tags):
tagDict = {}
#add sname to tagDict
addItemToDict(tagDict,sname,50)
#add aname to tagDict
addItemToDict(tagDict,aname,50)
#split tags<tag:count>
tagInfos = tags.split("##==##")
#loop every tag Information
for tagInfo in tagInfos:
#cannot use split(":") because some tag contains ":" like <hello:world:3>
#find : from right index
index = tagInfo.rfind(":")
tagStr = tagInfo[:index]
tagCount = tagInfo[index+1:]
#avoid some tags without count
#if a tag has no count, ignore it
if len(tagCount) == 0:
continue
else:
#add tag to dict
addItemToDict(tagDict,tagStr,int(tagCount))
return tagDict
#rm dir,no matter it is empty or not
def rmDir(whichdir):
print 'begin to rm dir %s' % whichdir
for dirpath,dirname,filenames in os.walk(whichdir):
for filename in filenames:
filepath = os.path.join(dirpath,filename)
os.remove(filepath)
print 'delete %d files in %s' % (len(filenames),whichdir)
os.rmdir(whichdir)
print 'end of rming dir %s' % whichdir
#generate document of given song from its tagDict
def generateDocofSong(sid,tagDict):
#if song file exists, return
if os.path.exists("data/songs/%d" % sid):
print '%d is existing...' % sid
logging.warning('%d is existing...' % sid)
return
#else new a file
sFile = open("data/songs/%d" % sid, "w")
#repeat: write tag into file
for tag in tagDict.keys():
count = (int)(tagDict[tag] / 4)
content = ""
#construct a line and write to file
for i in range(0,count):
content = "%s %s" % (content,tag)
sFile.write(content+'\n')
sFile.close()
#generate all docs of all songs
#get statistics of tags,listener number and playcount
def generateDocs():
#import global variable
global DBHOST
global DBUSER
global DBPWD
global DBPORT
global DBNAME
global DBCHARSET
#rm folder songs
rmDir("data/songs")
#mkdir songs
os.mkdir("data/songs")
try:
#connect db and select db name
conn = MySQLdb.Connect(host=DBHOST,user=DBUSER,passwd=DBPWD,port=DBPORT,charset=DBCHARSET)
cur = conn.cursor()
conn.select_db(DBNAME)
#get song dict and playlist dict from DBProcess
songDict,playlistDict = DBProcess.genEffectivePlaylist()
#tags'count:number
countDict = {}
#listeners'count:number
lisDict = {}
#playcount:number
playDict = {}
songNum = len(songDict)
index = 0
for sid in songDict.keys():
index = index + 1
print 'begin to generate file of song %d(%d/%d)' % (sid,index,songNum)
logging.debug('begin to generate file of song %d(%d/%d)' % (sid,index,songNum))
#select info of a song with sid
cur.execute('select sname,aname,count,tags,listeners,playcount,useful from effective_song where id = %d' % sid)
result = cur.fetchone()
sname = result[0]
aname = result[1]
count = int(result[2])
#update count dict
if count not in countDict:
countDict[count] = 1
else:
countDict[count] = countDict[count] + 1
tags = result[3]
#update listener dict
listeners = int(result[4])
if listeners not in lisDict:
lisDict[listeners] = 1
else:
lisDict[listeners] = lisDict[listeners] + 1
#update playcount dict
playcount = int(result[5])
if playcount not in playDict:
playDict[playcount] = 1
else:
playDict[playcount] = playDict[playcount] + 1
useful = int(result[6])
if useful == 0:
print '%d useful is 0...' % sid
logging.warning('%d useful is 0...' % sid)
return
tagDict = generateTagDictofSong(sname,aname,tags)
generateDocofSong(sid,tagDict)
print 'end of generating file of song %d' % sid
logging.debug('end of generating file of song %d' % sid)
conn.commit()
cur.close()
conn.close()
print 'There are %d different tag count' % len(countDict)
print 'There are %d different listener numbers' % len(lisDict)
print 'There are %d different playcount numbers' % len(playDict)
return countDict,lisDict,playDict
except MySQLdb.Error,e:
print 'Mysql Error %d:%s' % (e.args[0],e.args[1])
logging.error('Mysql Error %d:%s' % (e.args[0],e.args[1]))
if __name__ == "__main__":
generateDocs()
|
Ruby | UTF-8 | 1,607 | 3.046875 | 3 | [
"MIT"
] | permissive | class GroupTrips
attr_reader :llist
def self.call(llist, traveller_home)
new(llist).chunk(traveller_home)
end
def initialize(llist)
@llist = llist
end
def output(traveller_home)
@output ||= llist.select_by do |elem|
case elem.datum.type
when 'Flight'
Flight.new(elem, nil, nil).head_and_last(traveller_home)
when 'Hotel'
end
end
end
alias_method :extract_sequences, :output
class Flight
attr_reader :elem,
# :current_llist,
# :acc,
:datum,
:home
def initialize(elem, current_llist, acc)
@elem = elem
@current_llist = current_llist
@acc = acc
@datum = elem.datum
end
def head_and_last(home)
palindromes
# if datum.id == 3
# head = elem.find_previous_by do |e|
# e.datum.id == 1
# end
# { head: head.datum, last: elem.datum }
# end
end
def palindromes
found = nil
elem.each do |e|
if is_flight?(e) && go_and_return?(e)
found = DoubleLinkedList::Sequence.new(head: elem, last: e)
end
break if found
end
found
end
private
def go_and_return?(element)
return unless is_flight?(element)
element.datum.destination == datum.origin
end
def is_flight?(element)
element.datum.type == 'Flight'
end
def current_head
current_llist.head.datum
end
def prev
elem.prev
end
end
end
|
Markdown | UTF-8 | 1,441 | 3.171875 | 3 | [
"MIT"
] | permissive | <!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
**Table of Contents**
- [Cursors](#cursors)
- [Available cursor values](#available-cursor-values)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Cursors
The `cursor()` function returns the correct cursor value based on the desired type.
```scss
// Use the 'pointer' cursor value
.foo {
cursor: cursor(pointer);
}
// Use the 'help' cursor
.bar {
cursor: cursor(help);
}
```
This is also available as a mixin:
```scss
.foo {
@include cursor(pointer);
}
```
## Available cursor values
> These values are currently basically 1-to-1 with the actual CSS values. We expect this to change
> over time as we create usage-driven names.
| Value | Meaning |
|---------------|-----------------------------------------|
| `auto` | Let the browser decide |
| `text` | Indicates text controls |
| `pointer` | Indicates interaction |
| `not-allowed` | Indicates no available interaction |
| `copy` | Indicates ability to copy |
| `alias` | Indicates an alias or copy will be made |
| `help` | Indicates help is available |
Passing an invalid cursor `$type` will throw a Sass compilation warning.
|
Java | UTF-8 | 2,834 | 2.421875 | 2 | [] | no_license | package aglf.data.dao.commons;
import org.hibernate.Criteria;
import org.hibernate.FlushMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.Serializable;
import java.util.List;
/**
* @param <IdT>
* @param <E>
*/
public class HbmGenericDaoBase<IdT extends Serializable, E> implements AbstractDao<IdT, E> {
/**
* Hibernate session factory instance
*/
@Autowired
private SessionFactory sessionFactory;
/**
* Entity class instance used for db operations.
*/
private Class<E> entityClass;
public HbmGenericDaoBase() {
}
public HbmGenericDaoBase(Class<E> entityClass) {
super();
this.entityClass = entityClass;
}
public E findById(IdT id) {
E result = (E) getSessionFactory().getCurrentSession().get(entityClass, id);
return result;
}
public List<E> findAll() {
Session currentSession = getSessionFactory().getCurrentSession();
List<E> list = currentSession.createCriteria(entityClass).list();
return list;
}
public List<E> findAllWithLimit(int maxResults) {
Session currentSession = getSessionFactory().getCurrentSession();
Criteria criteria = currentSession.createCriteria(entityClass);
criteria.setMaxResults(maxResults);
List<E> list = criteria.list();
return list;
}
public void saveAll(List<E> entityList) {
for (E entity : entityList) {
save(entity);
}
}
public void save(E entity) {
getSessionFactory().getCurrentSession().saveOrUpdate(entity);
}
public void delete(E entity) {
getSessionFactory().getCurrentSession().delete(entity);
}
@Override
public E merge(E entity) {
Session currentSession = getSessionFactory().getCurrentSession();
E merged = (E) currentSession.merge(entity);
return merged;
}
@Override
public void delete(IdT entityId) {
Session currentSession = getSessionFactory().getCurrentSession();
Object object = currentSession.load(entityClass, entityId);
currentSession.delete(object);
}
@Override
public E loadById(IdT entityId) {
E result = (E) getSessionFactory().getCurrentSession().load(entityClass, entityId);
return result;
}
@Override
public void flush() {
getSession().flush();
}
@Override
public void clear() {
getSession().clear();
}
protected SessionFactory getSessionFactory() {
sessionFactory.getCurrentSession().setFlushMode(FlushMode.COMMIT);
return sessionFactory;
}
protected Session getSession() {
return getSessionFactory().getCurrentSession();
}
}
|
Python | UTF-8 | 1,204 | 2.890625 | 3 | [] | no_license | #!/usr/bin/env python3
from collections import OrderedDict
from sys import stdin
from build_table import parse_grammar, classify_terms, build
label = lambda iterable: OrderedDict(map(reversed, enumerate(iterable)))
def main():
rules, goal = parse_grammar(stdin)
nonterminals, terminals = classify_terms(rules)
table = build(rules, goal)
rules = label(rules)
item_sets = label(table['item_sets'])
print({
'start': item_sets[table['start']],
'finish': item_sets[table['finish']],
'shifts': {
(item_sets[state[0]], state[1]): item_sets[transition[1]] \
for state, transition in table['shifts'].items() \
if state[1] in terminals
},
'reductions': {
item_sets[state]: (rule[0], len(rule[1]), rules[rule]) \
for state, rule in table['reductions'].items()
},
'gotos': {
(item_sets[state[0]], state[1]): item_sets[transition[1]] \
for state, transition in table['shifts'].items() \
if state[1] in nonterminals
},
})
if __name__ == '__main__':
main()
|
C++ | UTF-8 | 1,310 | 3.421875 | 3 | [] | no_license | class Solution {
public:
bool isValid(string s) {
return wellFormedBrackets(s, 0, s.size());
// finish code 14:49
}
// True if well formed, false else.
// Change to reference and see if it works.
// [start, end[
bool wellFormedBrackets(string s, int start, int end, ){
if(start == end){
return true;
}
switch(s.at(start)){
case '(':
if(s.at(end-1) == ')' && wellFormedBrackets(s, start+1, end-1)){
return true;
}
return false;
// finish this case: 14:45
case '{':
if(s.at(end-1) == '}' && wellFormedBrackets(s, start+1, end-1)){
return true;
}
return false;
case '[':
if(s.at(end-1) == ']' && wellFormedBrackets(s, start+1, end-1)){
return true;
}
return false;
default:
return false;
}
// finish this block 14:48
}
};
/*
Reading: 14:20 - 14:22
Solving: 14:22 -
Let's use recursion.
Time: O(n)
Space:O(n)
String:
( well formed )
{ well formed }
[ well formed ]
''
well formed = well formed brackets
*/
|
Java | UTF-8 | 181 | 1.820313 | 2 | [] | no_license |
package com.tencent.appframework.thread;
public interface FutureListener<T> {
public void onFutureBegin(Future<T> future);
public void onFutureDone(Future<T> future);
}
|
Java | ISO-8859-1 | 9,991 | 2.640625 | 3 | [] | no_license | package cocktailprogramm;
import java.awt.event.WindowEvent;
import java.io.*;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
public class RezeptGUI extends JFrame implements Serializable
{
DefaultListModel model = new DefaultListModel();
RezeptListe rezeptListe;
File e;
Object nameEnter;
public static void main (String args[])
{
if (args.length==0) {
JOptionPane.showMessageDialog (
new JFrame(), "Sie haben kein Argument angegeben, deshalb wurde eine Datei " +" namens rezepte.dat erstellt.",
"Information",
JOptionPane.INFORMATION_MESSAGE);
System.out.println("Sie haben kein Argument angegeben, deshalb wurde eine Datei " +" namens rezepte.dat erstellt.");
new RezeptGUI("rezepte.dat") .setVisible(true);
}
else if (args.length > 1) {
System.out.println ("Geben Sie ein Argument ein");
System.exit(0);
} else {
if (args[0].endsWith(".dat")) {
new RezeptGUI (args[0]).setVisible(true);
}
else if (args[0].endsWith(".csv")) {
new RezeptGUI (args[0]).setVisible(true);
}
else {
System.out.println("Bitte geben Sie eine .csv Datei oder eine .dat Datei ein");
System.exit(0);
}
}
}
public RezeptGUI(String args)
{
e = new File (args);
rezeptListe = new RezeptListe ();
if (args.endsWith(".dat")) {
if (e.exists())
{
ObjectInputStream in = null;
try
{
in = new ObjectInputStream (new FileInputStream (e));
rezeptListe = (RezeptListe) in.readObject();
} catch (IOException ex)
{
System.out.println ("Die .dat Datei konnte nicht geladen werden, " +" bitte versuchen Sie es erenut.");
Logger.getLogger (RezeptGUI.class.getName()).log (
Level.SEVERE, null, ex);
}
catch (ClassNotFoundException ex) {
System.out.println("Die .dat Datei konnte nicht geladen werden, " +" bitte versuchen Sie es erenut.");
Logger.getLogger(RezeptGUI.class.getName()).log(
Level.SEVERE, null, ex);
}
finally {
try {in.close();}
catch (IOException ex) {
System.out.println("Es gab einen Fehler beim schlieen der Datei.");
Logger.getLogger(RezeptGUI.class.getName()).log(
Level.SEVERE, null, ex);
}
}
}
}
else if (args.endsWith(". csv"))
{
if (e.exists()) {
try {
readCSV(e);
} catch (FileNotFoundException ex)
{
System.out.println ("Die .csv Datei konnte nicht geladen werden, " +" bitte versuchen Sie es erenut.");
Logger.getLogger(RezeptGUI.class.getName()).log(
Level.SEVERE, null, ex);
} catch (IOException ex)
{
Logger.getLogger(RezeptGUI.class.getName()).log(
Level.SEVERE, null, ex);
}
}
}
try
{
UIManager.setLookAndFeel (UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
Logger.getLogger(RezeptGUI.class.getName())
.log(Level.SEVERE, null, ex);
}
initComponents();
showList();
toggleEnabled();
select(0);
addAlleZutaten();
}
public void readCSV (File e) throws FileNotFoundException, IOException
{
String thisLine;
BufferedReader reader = new BufferedReader (new InputStreamReader (
new FileInputStream (e)));
String nameField = null;
Rezept r = null;
while ((thisLine = reader.readLine()) !=null)
{
StringTokenizer st = new StringTokenizer (thisLine, ",");
String temp = st.nextToken();
if(!st.hasMoreTokens()) {
if (!temp.equals("---------")) {
nameField = temp;
r=new Rezept(nameField, rezeptListe.getAlleZutaten());
}
else {rezeptListe.addRezept (r);}
}
while (st.hasMoreTokens()){
String quant = st.nextToken();
double quants = Double.parseDouble(quant);
String meas = st.nextToken();
r.AddZutaten(new Zutaten(temp, quants, meas));
}
}
}
public void addRezept(Rezept r){
String res = rezeptListe.addRezept(r);
if (res.equals("")){
showList();
select(0);
toggleEnabled();
addAlleZutaten();
}
else{
showError(res);
}
}
public void addAlleZutaten()
{
rezeptListe.getAlleZutaten().clear();
for (int a = 0; a < rezeptListe.getAlleRezepte().size(); a++){
for (int j = 0; j < rezeptListe.getRezept(a).getListe().size(); j++){
rezeptListe.getAlleZutaten().add(
rezeptListe.getRezept(a).getListe().get(j));
}
}
}
public void showList()
{
model.removeAllElements();
for (int i = 0; i < rezeptListe.getAlleRezepte().size(); i++){
model.add(i, rezeptListe.getRezept(i).getName());
}
}
public void toggleEnabled()
{
if (rezeptListe.getAlleRezepte().size() == 0){
saveButton.setEnabled(false);
ViewSummary.setEnabled(false);
deleteButton.setEnabled(false);
MENUsave.setEnabled(false);
} else
{
saveButton.setEnabled(true);
ViewSummary.setEnabled(true);
deleteButton.setEnabled(true);
MENUsave.setEnabled(true);
}
}
public void save()
{
if (saveButton.isEnabled()){
ObjectOutputStream out;
PrintWriter pw = null;
try
{
out = new ObjectOutputStream(new FileOutputStream("rezepte.dat"));
out.writeObject(rezeptListe);
out.close();
JOptionPane.showMessageDialog(
new JFrame(), "Die Rezeptlsite wurde gespeichert.", "Speichern",
JOptionPane.INFORMATION_MESSAGE);
} catch (IOException ex)
{
showError("Die Liste konnte nicht gespeichert werden, da die Datei noch offen ist");
Logger.getLogger(RezeptGUI.class.getName()).log(Level.SEVERE,null,ex);
return;
}
try
{
pw = new PrintWriter(new FileOutputStream("rezepte.csv"));
for (int i = 0; i < rezeptListe.getAlleRezepte().size(); i++) {
pw.printf(rezeptListe.getRezept(i).getName());
for(int j=0; j < rezeptListe.getRezept(i).zutaten.size();j++)
{
pw.printf("n" +
rezeptListe.getRezept(i).zutaten.get(j).getName() + "," +
rezeptListe.getRezept(i).zutaten.get(j).getMenge() + ",");
if (rezeptListe.getRezept(i).zutaten.get(j).getMengeneinheit(). equals(""))
{
pw.printf(" ");
} else
{
pw.printf(rezeptListe.getRezept(i).zutaten.get(j). getMengeneinheit());
}
}
pw.printf("n---------n");
pw.close();
}
pw.flush();
} catch (Exception e)
{
showError("Es gab ein Problem beim speichern der .csv Datei");
System.out.println(e);
}
}
}
public void showError(String message)
{
JOptionPane.showMessageDialog(
new JFrame(), message,
"Fehler",
JOptionPane.ERROR_MESSAGE);
return;
}
public void select(int i)
{
if (i == 0){
if (!model.isEmpty()){displayList.addSelectionInterval(0, 0);}
} else{
if (!model.isEmpty()){
displayList.addSelectionInterval(model.getSize()-1,model.getSize()-1);
}
}
}
public void loadRezeptForm(String name, ArrayList<Zutaten> zutatIn)
{
RezeptForm r = new RezeptForm(name, zutatIn, rezeptListe, this);
r.setVisible(true);
}
public void exit(){
int option = JOptionPane.showConfirmDialog(new JFrame(),
"Sind Sie sicher, dass sie das Programm verlassen wollen?",
"Beenden Besttigen", JOptionPane.OK_CANCEL_OPTION);
if (option == 0){
processEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
}
}
public void add(java.awt.event.ActionEvent evt){
nameEnter = JOptionPane.showInputDialog(
new JFrame(),
"Bitte geben Sie einen Rezeptnamen ein:",
"Neues Rezept hinzufgen",
JOptionPane.INFORMATION_MESSAGE,
null, null, null);
if (nameEnter == null){return;}
if (nameEnter.toString().trim().equals("")) {
showError("Bitte geben Sie einen Rezeptnamen ein.");
AddRecipeButtonActionPerformed(evt);
} else {
for (int i = 0; i < rezeptListe.getAlleRezepte().size(); i++){
if (rezeptListe.getRezept(i).getName().toLowerCase().equals(
nameEnter.toString().toLowerCase())){
showError("Der Rezeptname \""
+nameEnter+"\" ist schon in der Liste.");
return;
}
}
loadRezeptForm(nameEnter.toString(), rezeptListe.getAlleZutaten());
}
select(1);
addAlleZutaten();
}
public void viewSummary(){
if (ViewSummary.isEnabled())
{
Rezept rec = rezeptListe.getRezept(displayList.getSelectedIndex());
String message = "";
for (int i = 0; i < rec.getListe().size(); i++)
{
message += rec.getListe().get(i).getName() + ": ";
String s = "" + rec.getListe().get(i).getMenge();
if (s.endsWith(".0")) {
NumberFormat formatter = new DecimalFormat("#0");
message += formatter.format(rec.getListe().get(i).getMenge())+"";
} else {
message += rec.getListe().get(i).getMenge() + "";
}
message += rec.getListe().get(i).getMengeneinheit();
message += "n";
}
JOptionPane.showMessageDialog(
new JFrame(), message,
"Summary of " + rec.getName(),
JOptionPane.INFORMATION_MESSAGE);
}
}
public void delete(){
if (deleteButton.isEnabled())
{
int option = JOptionPane.showConfirmDialog(new JFrame(),
"Sind Sie sicher, dass Sie das Rezept lschen wollen?",
"Lschen Besttigen", JOptionPane.OK_CANCEL_OPTION);
if (option == 0) {
Rezept rec = rezeptListe.getRecipe(displayList.getSelectedIndex());
if(rezeptListe.removeRezept(rec.getName()))
{
showList();
toggleEnabled();
select(0);
addAlleZutaten();
}
else{showError("Es gab ein Problem beim Lschen des Rezepts"); }
}
}
}
public void about(){
JOptionPane.showMessageDialog(
new JFrame(),
"Programmieren II Projekt SS 2020" +
" \n " +
"Kim Niklas Neuhusler und Toni Zubac" +
" \n " +
"Matr. Nr.: 80045 und Matr. Nr.: 79441",
JOptionPane.INFORMATION_MESSAGE, null);
}
}
|
Markdown | UTF-8 | 11,083 | 2.5625 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | permissive | # Default Product Ports
This page describes the default ports used by each runtime of WSO2 API Manager.
!!! Note
If you [change the default runtime ports]({{base_path}}/install-and-setup/setup/deployment-best-practices/changing-the-default-ports-with-offset), most of the runtime ports change automatically based on the offset.
## API-M ports
Listed below are the ports used by the API-M runtime when the [port offset]({{base_path}}/install-and-setup/setup/deployment-best-practices/changing-the-default-ports-with-offset/#configuring-the-port-offset) is 0.
!!! Info
See the instructions on [changing the default API-I ports]({{base_path}}/install-and-setup/setup/deployment-best-practices/changing-the-default-ports-with-offset/#changing-the-default-api-m-ports).
<table>
<tr>
<th>
Default Port
</th>
<th>
Description
</th>
</tr>
<tr>
<td>
<code>9443</code>
</td>
<td>
Port of the HTTPS servlet transport. The default HTTPS URL of the management console is <code>https://localhost:9443/carbon</code>.
</td>
</tr>
<tr>
<td>
<code>9763</code>
</td>
<td>
Port of the HTTP servlet transport. The default HTTP URL of the management console is <code>http://localhost:9763/carbon</code>.
</td>
</tr>
<tr>
<td>
<code>10389</code>
</td>
<td>
Port of the embedded LDAP server.
</td>
</tr>
<tr>
<td>
<code>5672</code>
</td>
<td>
Port of the internal Message Broker of the API-M runtime.
</td>
</tr>
<tr>
<td>
<code>8280</code>
</td>
<td>
Port of the Passthrough or NIO HTTP transport.
</td>
</tr>
<tr>
<td>
<code>8243</code>
</td>
<td>
Port of the Passthrough or NIO HTTPS transport.
</td>
</tr>
<tr>
<td>
<code>9611</code>
</td>
<td>
TCP port to receive throttling events. This is required when the binary data publisher is used for throttling.
</td>
</tr>
<tr>
<td>
<code>9711</code>
</td>
<td>
SSL port of the secure transport for receiving throttling events. This is required when the binary data publisher is used for throttling.
</td>
</tr>
<tr>
<td>
<code>9099</code>
</td>
<td>
Web Socket ports.
</td>
</tr>
<tr>
<td>
<code>8000</code>
</td>
<td>
Port exposing the Kerberos key distribution center server.
</td>
</tr>
<tr>
<td>
<code>45564</code>
</td>
<td>
Opened if the membership scheme is multicast.
</td>
</tr>
<tr>
<td>
<code>4000</code>
</td>
<td>
Opened if the membership scheme is WKA.
</td>
</tr>
<tr>
<td>
<code>11111</code>
</td>
<td>
The RMIRegistry port. Used to monitor Carbon remotely.
</td>
</tr>
<tr>
<td>
<code>9999</code>
</td>
<td>
The MIServer port. Used along with the RMIRegistry port when Carbon is monitored from a JMX client that is behind a firewall
</td>
</tr>
</table>
## Micro Integrator ports
By default, the Micro Integrator is **internally** configured with a port offset of 10. Listed below are the ports that are effective in the Micro Integrator by default (due to the internal port offset of 10).
!!! Info
See the instructions on [changing the default MI ports]({{base_path}}/install-and-setup/setup/deployment-best-practices/changing-the-default-ports-with-offset/#changing-the-default-mi-ports).
<table>
<tr>
<th>
Default Port
</th>
<th>
Description
</th>
</tr>
<tr>
<td>
<code>8290</code>
</td>
<td>
The port of the HTTP Passthrough transport.
</td>
</tr>
<tr>
<td>
<code>8253</code>
</td>
<td>
The port of the HTTPS Passthrough transport.
</td>
</tr>
<tr>
<td>
<code>9201</code>
</td>
<td>
The HTTP port of the <a href="{{base_path}}/observe/mi-observe/working-with-management-api">Management API</a> of WSO2 Micro Integrator.</br></br>
<b>Configuring the default HTTP port</b></br>
If required, you can manually change the HTTP port in the <code>deployment.toml</code> file (stored in the <code>MI_HOME/conf</code> folder) as shown below.</br></br>
<div>
<code>[mediation]</code></br>
<code>internal_http_api_port = http_port </code></br>
</div></br>
<b>Note</b>: With the default internal port offset, the effective port will be <code>http_port + 10</code>.
</td>
</tr>
<tr>
<td>
<code>9164</code>
</td>
<td>
The HTTPS port of the <a href="{{base_path}}/observe/mi-observe/working-with-management-api">Management API</a> of WSO2 Micro Integrator.</br></br>
<b>Configuring the default HTTPS port</b></br>
If required, you can manually change the HTTPS port in the <code>deployment.toml</code> file (stored in the <code>MI_HOME/conf</code> folder) as shown below.</br></br>
<div>
<code>[mediation]</code></br>
<code>internal_https_api_port = https_port </code>
</div></br>
<b>Note</b>: With the default internal port offset, the effective port will be <code>https_port + 10</code>.
</td>
</tr>
</table>
## Streaming Integrator Ports
Listed below are the default ports used by the Streaming Integrator runtime and the Streaming Integrator Tooling runtime. The default port offset in these runtimes are `0` and `3` respectively.
!!! Info
See the instructions on [changing the default SI ports]({{base_path}}/install-and-setup/setup/deployment-best-practices/changing-the-default-ports-with-offset/#changing-the-default-si-ports).
- Thrift and Binary ports:
<table>
<tr>
<th>
Default Port
</th>
<th>
Description
</th>
</tr>
<tr>
<td>
<code>7611</code>
</td>
<td>
Thrift TCP port to receive events from clients.
</td>
</tr>
<tr>
<td>
<code>7711</code>
</td>
<td>
Thrift SSL port for the secure transport where the client is authenticated.
</td>
</tr>
<tr>
<td>
<code>9611</code>
</td>
<td>
Binary TCP port to receive events from clients.
</td>
</tr>
<tr>
<td>
<code>9711 </code>
</td>
<td>
Binary SSL port for the secure transport where the client is authenticated.
</td>
</tr>
</table>
- Management ports:
**Streaming Integrator runtime**
<table>
<tr>
<th>
Default Port
</th>
<th>
Description
</th>
</tr>
<tr>
<td>
<code>9090</code>
</td>
<td>
HTTP netty transport.
</td>
</tr>
<tr>
<td>
<code>9443</code>
</td>
<td>
HTTPS netty transport.
</td>
</tr>
</table>
**Streaming Integrator Tooling runtime**:
<table>
<tr>
<th>
Default Port
</th>
<th>
Description
</th>
</tr>
<tr>
<td>
<code>9390</code>
</td>
<td>
HTTP netty transport.
</td>
</tr>
<tr>
<td>
<code>9743</code>
</td>
<td>
HTTPS netty transport.
</td>
</tr>
</table>
- Streaming Integrator clustering ports:
**Minimum High Availability (HA) Deployment**
<table>
<tr>
<th>
Default Port
</th>
<th>
Description
</th>
</tr>
<tr>
<td>
<code>9090</code>
</td>
<td>
HTTP netty transport.
</td>
</tr>
<tr>
<td>
<code>9090</code>
</td>
<td>
The port of the node for the <code>advertisedPort</code> parameter in the <code>liveSync</code> section. The HTTP netty transport port is considered the default port.
</td>
</tr>
<tr>
<td>
<code>9443</code>
</td>
<td>
HTTPS netty transport.
</td>
</tr>
</table>
**Multi Datacenter High-Availability Deployment**
In addition to the ports used in clustering setups (i.e. a minimum HA deployment or a scalable cluster), the following port is required:
<table>
<tr>
<th>
Default Port
</th>
<th>
Description
</th>
</tr>
<tr>
<td>
<code>9092</code>
</td>
<td>
Ports of the two separate instances of the broker deployed in each data center (e.g., `bootstrap.servers= 'host1:9092, host2:9092'. The default is `9092` where the external kafka servers start.).
</td>
</tr>
</table>
## Random ports
Certain ports are randomly opened during server startup. This is due to the specific properties and configurations that become effective when the product is started. Note that the IDs of these random ports will change every time the server is started.
- A random TCP port will open at server startup because the `-Dcom.sun.management.jmxremote` property is set in the server startup script. This property is used for the JMX monitoring facility in JVM.
- A random UDP port is opened at server startup due to the log4j appender (`SyslogAppender`), which is configured in the `<PRODUCT_HOME>/repository/conf/log4j2.properties` file.
|
C++ | UTF-8 | 1,717 | 3.40625 | 3 | [] | no_license | #include <deque>
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <iomanip>
using namespace std;
template<class T> class mergesort{
public:
mergesort(string inFile, string outFile);
private:
int readInFile(ifstream &inputFile);
void printFile(string inFile,deque<T> &data,bool apend);
string tostring(int number);
int max_deque_size;
};
//mergesort()
template<class T> mergesort<T>::mergesort(string inFile,string outFile){
int numFiles;
ifstream inputFile;
this->max_deque_size=5;
try{
inputFile.open(inFile.c_str());
}catch(int e){
cout << "Error opening file!! \n ERROR" << e;
}
cout << "Reading input file...\n";
numFiles = readInFile(inputFile);
cout << "Done! \n";
cout << numFiles <<" num files." << endl;
inputFile.close();
}
/*tostring()
string tostring(int number){
stringstream ss;
ss << number;
return ss.str();
}*/
//readInFile()
template<class T> mergesort<T>::readInFile(ifstream &inputFile){
deque<T> data;
T temp;
int fileOut = 0;
int numFiles;
string fileName;
for(numFiles = 0; inputFile.good(); numFiles++){
fileName = "sortfile_";
fileName += to_string(numFiles);
for(int i =0;(i<max_deque_size && inputFile >> temp); i++){
data.push_back(temp);
}
//data = SORT(data)
printFile(fileName,data,false);
data.clear();
cout << "*";
}
cout << endl;
return numFiles + 1;
}
//printFile()
template<class T> void mergesort<T>::printFile(string inFile,deque<T> &data,bool apend){
ofstream outFile;
if(apend){
outFile.open(inFile.c_str(), ios::app);
}else{
outFile.open(inFile.c_str());
}
while(data.size() > 0){
outFile << data.front() << endl;
data.pop_front();
}
outFile.close();
}
|
Swift | UTF-8 | 199 | 2.625 | 3 | [
"MIT"
] | permissive | import Foundation
public protocol ReceiptProtocol {
//associatedtype PurchaseItem;
var code: Int { get }
var receipt: String { get }
var purchases: [PurchaseItemProtocol] { get }
}
|
Markdown | UTF-8 | 1,292 | 3.1875 | 3 | [] | no_license | 在 前端的编程范式中有三种主流的异常处理风格。
## 回调式
比如微信小程序的接口都是使用这种风格的。以 `wx.request` 为例。
一般是向下面这样使用:
```js
wx.request({
url: "/test/",
success: res => {
// 请求成功
},
fail: error => {
// 请求失败
}
});
```
## Promise 的 then/catch
还是以上面的 `wx.request` 为便。我们可以将 `wx.request` 封装一下,然后返回 `Promise`,
这个封装的代码,可以参考 [promisify](https://github.com/banxi1988/mpex/blob/5c0e49ba9ce370a2415660113d7315f32bd0f881/lib/index.ts#L23)
当我们使用返回 `Promise` 的代码,使用上面 `mpex` 库封装好的 `request`,将上面的使用代码改写如下:
```js
request({ url: "/test" })
.then(res => {
// 请求成功
})
.catch(error => {
// 请求失败
});
```
## async/await + try/catch
虽然 Promise 风格的 `then/catch` 写法相比回调风格已经好很多了,但是 Promise 本身还是有点绕,特别是当有多个 `Promise` 接口调用时。此时我们可以使用 `async/await` 来优化:
```js
async function loadData() {
try {
const res = await request({ url: "/test" });
// 请求成功
} catch (error) {
// 请求失败
}
}
```
|
Markdown | UTF-8 | 7,635 | 2.765625 | 3 | [
"MIT"
] | permissive | #  *-* gitRabbit
*Le reproducteur le plus rapide de l'ouest*
**Papa lapin veille sur ses lapereaux et leurs fait faire beaucoup de choses, mais toujours avec amour :heart:**
---
**gitRabbit**, est un petit script qui permet de déployer des repos git en production, ainsi que de les garder a jour avec leur branche.
Il embarque un log info/erreur, un garde fou pour restreindre l'execution, un quiet mode et une gestion des "trap" 2/3.
Il est aussi possible de l'utiliser comme service avec [SystemD](#-utilisation-en-service-systemd) ou [SystemBSD](#-utilisation-en-service-systembsd).
**Il est possible:**
* D'ajouter un nombre illimité de repos
* D'utiliser des branches
* D'executer des commandes avant/aprés un "git pull"
* D'utiliser une clé *[avec ~/.ssh/config]*
* D'utiliser un combo user/passwd *[https://* **\<user>**:**\<passwd>** *@urldeclone/repos.git]*
**Il n'est pas encore possible:**
* D'utiliser une clé avec passphrase
**Il à besoin de:**
* Git
* Bash
* *... cd echo mkdir sleep exit*
## :rocket: Les options de lancement
```
usage : gitRabbit [-q] [-c <path>] [-u <user>] [-w <path>]
[-g <parh>] [-n] [-l <path>] [-s <time>] [-t|-tt]
-q Afficher uniquement les erreur fatales
-c Spécifier un fichier de configuration alternatif
-u Définir l'utilisateur autorisé a lancer ce script
Ceci est un garde fou, pour eviter de lancer en root par exemple
Une entrés incorecte cause une erreur fatal
-w Emplacement des datas
Il est préférable que ce soit un lien absolut
-l Définir un dossier de log alternatif
-g Path for storing all git repository separates from the work tree
-n Don't remove the .git file from work tree (from clone)
-s Temps a attendre avant de revérifier le repository
-t, -tt Afficher moins d'informations dans le log
Doubler l'option(-tt) pour loguer uniquement les erreurs
```
*Les options suivantes peuvent uniquement étre définies au lancement du script*
*Ou avant, via des `export .*=".*"`*
### [-w] WORK_DIR *(workDir)*
*[DEFAULT: /tmp/gitrabbit]*
Définit le dossier principale, il est de base de tous le reste,
si les autres options *(-c -l -g)* ne sont pas définies.
Il doit étre un lien absolut (de preference) et ouvert en ecriture.
### [-c] forceConf
*[DEFAULT: \<datas -w>/lapereaux.conf]*
Permet de forcer un fichier de configuration à un autre emplacement,
ex: `/etc/gitrabbit/lapereaux.conf`.
Doit étre un lien absolut et ouvert en lecture.
### [-l] forceLog
*[DEFAULT: \<datas -w>/log]*
Pour forcer un dossier de log alternatif comme `/var/log/gitrabbit`,
il est pratique pour faire de la rotation de log.
L'emplacement doit étre un lien absolut et ouvert en ecriture.
### [-g] forceGitDir
*[DEFAULT: \<datas -w>/git]*
Tous les `.git` vont ce retrouver dans ce dossier,
ça permet de sécuriser les infos contenu en ne les plassant pas dans `work tree`.
Doit étre un lien absolut et ouvert en ecriture.
## :pencil: Fichier de configuration
*lapereaux.conf*
Les options suivantes, peuvent étre définies dans le fichier de conf ou en option de lancement(voir section précédente)
### tinyLog
*[DEFAULT: 0]*
Permet de réduire les log, les valeurs disponibles sont
**0/\*** Print les informations, informations importantes et erreurs
**1** Print les informations importantes et erreurs
**2** Print uniquement les erreurs
### forceUser
*[DEFAULT: null]*
C'est un garde fou, il permet d'éviter d'utiliser le script avec un utilisateur indésirable
Il n'est cependant pas a considérer comme une mesure de sécurité, mais uniquement de garde fou.
Pour une utilisation en Cron il est necessaire de définir avant tout la variable USER.
### sleepTime
*[DEFAULT: 60]*
Elle permet de définir le tems entre chaque passe de vérification des repository git,
une fois tous les repos considéré comme UpToDate, un temps de pause est marqué,
cette variable en définie le temps en secondes
### quietMode
*[DEFAULT: false]*
Permet de ne rien afficher dans la sortie console, ses valeurs sont:
**false** Affiche les infos et erreurs dans la sortie
**true** N'affiche que les erreurs fatales
### noGitDot
*[DEFAULT: true]*
Le script utilise `--separate-git-dir` un fichier .git est tout de même créer pour indiquer le `gitdir`,
ce fichier n'est pas necessaire pour le script et est donc supprimé
**false** ne pas supprimer le fichier .git
**true** supprime le fichier .git
--
*Voyons les options pour ajouter un repos*
### lapereaux
Est la variable contenant l'intégralité des dépos qu'il faut utiliser,
le nom donné au repos ne doit contenir que des caractaires alpha-numerique et _ [a-z0-9\_].
Toutes les variables de configuration suivante doivent étre préfixé, avec le nom ici renségné.
**ex:** lapereaux+=("mon_repos")
### \*_url
Pour définir l'emplacement du repos a cloner
Il est possible d'utiliser un repos privé *[https://* **\<user>**:**\<passwd>** *@urldeclone/repos.git]*
**ex:** toto_url='http(s)://blabla.com/montruc.git'
### \*_before
La variable utilisé pour définir des actions a définir avant le "git pull",
il est préférable d'utiliser les quotes simples (') aux doubles (").
Il est possible d'utiliser des variables du main script, je vous encourage
a ne pas redéfinir une de ses variable, sous peine de gros problémes:
- \_lapDir
- logDir
- workDir
- logFile
- confFile
**ex:** toto_after='mv ${\_lapDir}/conf.ini /tmp/maconfagarder'
**ps:** Éxecuté avec `eval` dans le dossier du repos
### \*_after
Exactement comme la variable précédente, mais aprés le "git pull"
**ex:** toto_before='mv /tmp/maconfagarder ${\_lapDir}/conf.ini'
### \*_branch
Pour définir la branche a utiliser, histoire de ne pas utiliser master pour la prod,
**ex:** toto_branch='prod'
### \*_remove
Est utilisé pour supprimer un repos en éditant simplement le fichier de conf
Attention, une fois supprimé, si vous ne retirez pas les lignes concernant ce
repos, cela générera une erreur dans les log, expliquant qu'il est impossible
de le suprimer étant donné qu'il n'existe plus.
Les valeurs possibles sont **false** ou **true**
**ex:** toto_remove='true'
### Exemple
Vous pouvez voir le fichier d'exemple [[ici]](https://git.iglou.eu/Laboratory/gitRabbit/src/branch/master/lapereaux.conf.sample)
## :alarm_clock: Utilisation en tache CRON
Au minimum, la configuration en cron est:
`@reboot /emplacement/script/gitRabbit -c /emplacement/conf/lapereaux.conf`
## :shipit: Utilisation en Service (systemd)
1. Création d'un compte utilisateur dédié `useradd -r -s /bin/bash -U -M gitrabbit`
2. Ajout d'un fichier de configuration `/etc/gitRabbit/lapereaux.conf` (root:gitrabbit / 740)
3. Ajout d'un dossier data `/var/lib/gitRabbit` (root:gitrabbit / 775)
4. Création de la fiche service [[gitrabbit.service]](https://git.iglou.eu/Laboratory/gitRabbit/raw/branch/master/gitrabbit.service) *(/etc/systemd/system/gitrabbit.service)*
5. Enable/Start `systemctl enable gitrabbit`
## :shipit: Utilisation en Service (systemBSD)
1. Création d'un compte utilisateur dédié `useradd -s /bin/bash gitrabbit`
2. Ajout d'un fichier de configuration `/etc/gitrabbit/lapereaux.conf` (root:gitrabbit / 740)
3. Ajout d'un dossier data `/var/gitrabbit` (root:gitrabbit / 775)
4. Création de la fiche service [[gitrabbitd]](https://git.iglou.eu/Laboratory/gitRabbit/raw/branch/master/gitrabbitd) *(/etc/rc.d/gitrabbitd)*
5. Enable/Start `rcctl enable gitrabbit` |
Python | UTF-8 | 1,091 | 3.546875 | 4 | [] | no_license | """
맞게는 나오나 sort썼는데 문자열로 sort되서 그런지
숫자 크기순이 아니라 문자열 순서대로 나옴.
나머지는 다 맞으나 백준에서 시간초과됨
"""
import random
l=[]
while(1):
k=input()
if(k=="0"):
break
l.append(k)
for i in l:
s1=int(i[0])
s2=i[2:]
s2=s2.split()
s3=s1
sum=1
p=0
while(1):
sum*=s3
s3-=1
p+=1
if(p==6):
break
for i in range(1,7):
sum=sum//i
s_final=[]
while(1):
s_list = []
s_list2=[]
s_str=""
while(1):
r=random.randint(0,s1-1)
s_list.append(s2[r])
s_list2=set(s_list)
if(len(s_list2)==6):
break
s_list2=list(s_list2)
s_list2.sort()
for i in s_list2:
s_str+=i+" "
s_final.append(s_str)
if(len(set(s_final))==sum):
s_final=list(set(s_final))
s_final.sort()
for i in s_final:
print(i)
break
print("\n") |
C# | UTF-8 | 440 | 2.53125 | 3 | [
"MIT"
] | permissive | using System.Collections.Generic;
namespace Toe.SPIRV.CodeGenerator.Views
{
public static class ExtensionMethods
{
public static IEnumerable<T> Concat<T>(this IEnumerable<T> items, T item)
{
if (items != null)
{
foreach (var i in items)
{
yield return i;
}
}
yield return item;
}
}
} |
JavaScript | UTF-8 | 947 | 2.609375 | 3 | [] | no_license | 'use strict';
//操作:セーブ
$('#btn-save').click(function () {
memo.save();
});
//操作:アップデート
$('#btn-update').on('click', function () {
memo.update();
});
//操作:お気に入り登録
$('#btn-fav').click(function () {
var fav = $('#btn-fav').attr('class');
if (!fav) {
$('#btn-fav').attr('class', 'fav');
} else {
$('#btn-fav').removeClass('fav');
}
memo.fav();
});
//操作:削除
$('#btn-delete').click(function () {
memo.trash();
});
//操作:お気に入りのみ表示、全体表示のトグル
$('#btn-favlist').click(function () {
$('#list').toggle();
$('#list-fav').toggle();
});
//操作:一覧から編集したいメモを選ぶ ※documentを指定しないと動的に生成されたDOMを選択できない
$(document).on('click', '#list li, #list-fav li', function () {
var _idx = $(this).attr('class');
memo.getData(_idx);
}); |
Python | UTF-8 | 245 | 2.703125 | 3 | [] | no_license | from lxml import etree
doc = etree.parse('provinciasypoblaciones.xml')
# 2)Programa que lista todos los municipios
raiz=doc.getroot()
municipios=doc.findall("provincia/localidades/localidad")
for localidad in municipios:
print(localidad.text) |
Python | UTF-8 | 171 | 3.421875 | 3 | [] | no_license | phi = float(22/7)
r = int(input("Masukan jari-jari: "))
luas = (phi*r*r)
print("Luas lingkaran dengan jari-jari:",r,"cm adalah luas" ,"{:.2f}".format(luas), "cm\u00b2") |
Python | UTF-8 | 1,361 | 2.703125 | 3 | [] | no_license | import sys, json, re
sys.path.append('./database/DAO')
from DatabaseManager import DatabaseManager
def main():
print "Reading minID"
fp = open('ids.txt', 'r')
for line in fp:
ids = line.strip().split(",")
minID = ids[0]
maxID = ids[1]
fp.close()
print "minID: ", minID
print "maxID: ", maxID
dbm = DatabaseManager()
print "running query..."
places = dbm.runQuery("SELECT id, bounding_box FROM Places \
WHERE lat_1 IS NULL AND id >= {0} AND id < {1}".format(minID, maxID))
print "query done!"
cont = 0.0;
for row in places:
try:
idPlace = row[0]
bounding_box = row[1]
tmp = re.sub(r'u\'','\'', bounding_box)
tmp = re.sub(r'\'','"', tmp)
obj = json.loads(tmp)
box_coords = obj['coordinates'][0]
lat_1 = box_coords[0][1]
long_1 = box_coords[0][0]
lat_2 = box_coords[1][1]
long_2 = box_coords[1][0]
lat_3 = box_coords[2][1]
long_3 = box_coords[2][0]
lat_4 = box_coords[3][1]
long_4 = box_coords[3][0]
query = u"""UPDATE Places SET lat_1={0}, long_1={1}, lat_2={2}, long_2={3},lat_3={4}, long_3={5}, lat_4={6}, long_4={7} WHERE id = {8}""".format(lat_1, long_1, lat_2, long_2, lat_3, long_3, lat_4, long_4, idPlace)
print cont
dbm.runCommit(query)
except Exception as e:
print "error with id=", row[0]
print e
cont += 1
if __name__ == '__main__':
main()
|
Python | UTF-8 | 493 | 4.1875 | 4 | [] | no_license | n = int(input('Enter the number of elements:'))
arr = []
#taking input from the user
for x in range(n):
arr.append(int(input()))
b=[]
j=0#first index
last = len(arr)#last index
for i in range(len(arr)):
if(arr[i]==0):#if the element is 0, then push it in the beginning
b.insert(j,arr[i])
j+=1
elif(arr[i]==1):#if the element is 1, then push it to the end
b.insert(last,arr[i])
last-=1
print('original array: '+str(arr))
print('new array: '+str(b))
|
C++ | UTF-8 | 1,933 | 3.234375 | 3 | [] | no_license | /* ECFileIO
Written by: Nate Fanning */
#include "ECFileIO.h"
using namespace std;
/* Class ECFileIO */
// Private methods
ECFileIO:: ECFileIO(string path) {
this->path = path;
if(path == "None") {
cerr << "No filename" << endl;
exit(EXIT_FAILURE);
} else {
readMode();
}
}
ECFileIO:: ~ECFileIO() {
file.flush();
file.close();
}
vector<string> ECFileIO:: read() {
vector<string> intext;
string line;
while(getline(file, line)) {
if(file.fail()) {
cerr << "Read from file failed" << endl;
exit(EXIT_FAILURE);
}
intext.push_back(line);
}
return intext;
}
void ECFileIO::write(vector<string> output) {
writeMode();
file.clear();
for(string line : output) {
if(file.fail()) {
if(!file.is_open()) cerr << "File is not open" << endl;
cerr << "Failed writing output to file" << endl;
exit(EXIT_FAILURE);
}
file << line << endl;
}
}
// Private
void ECFileIO:: readMode() {
if(file.is_open()) file.close();
file.clear();
file.open(path, fstream::in);
if(file.fail()) { // File opening error checking
// If file could not be opened, try creating it.
file.clear();
file.open(path, ios::out);
if(file.fail()) {
cerr << "File could not be created" << endl;
exit(EXIT_FAILURE);
}
file.close();
file.clear();
file.open(path, fstream::in);
if(file.fail()) {
cerr << "File could not be opened after creation" << endl;
exit(EXIT_FAILURE);
}
}
}
void ECFileIO:: writeMode() {
if(file.is_open()) file.close();
file.clear();
file.open(path, fstream::out | fstream::trunc);
if(file.fail()) {
cerr << "File could not be opened for writing" << endl;
exit(EXIT_FAILURE);
}
} |
C | UTF-8 | 706 | 3.75 | 4 | [] | no_license | #include "myMathFunc.h"
#include <stdio.h>
int main(){
int a, b;
printf("The program takes 2 integers and swaps them");
printf("-----");
printf ("Enter integer a: ");
scanf ("%d", &a);
printf ("Enter integer b: ");
scanf ("%d", &b);
int result = swap(&a,&b);
printf("A = %d and B = %d; ",a,b);
return result;
int x, y;
printf ("The program takes two numbers to see if they are equal or not");
printf ("Enter integer x: ");
scanf ("%f", &x);
printf ("Enter integer y: ");
scanf ("%f", &y);
float ans= isEqual(x,y);
if (ans==1){
printf("X & Y are equal", ans);
return 0;
}
else{
printf("X & Y are not equal", ans);
return 0;
}
} |
C++ | UTF-8 | 4,200 | 2.78125 | 3 | [] | no_license | #include "bullet.h"
#include <QTimer>
#include <QDebug>
#include <QList>
#include <enemy.h>
#include <viewgame.h>
extern ViewGame* vgame; // объявили использование указателя на внешнюю глобальную переменную класса ViewGame (для того чтобы через нее можно было добраться до переменных и методов класса Game
Bullet::Bullet()
{
//setRect(0,0,10,50); // Создаем размер для пули (если требуется создать прямоугольник)
setPixmap(QPixmap(":/images/Rocket.png").scaled(10,50,Qt::IgnoreAspectRatio)); //Зададим изображение для выстрела (ракета) и при помощи метода scaled изменим размер на нужные параметры
QTimer *timer = new QTimer(); //Создали объект типа QTimer для того что бы подсоединить к нему слот функцию move()
connect(timer,SIGNAL(timeout()),this,SLOT(move())); //Соединяем сиглал от таймера со слотом move этого объекта
timer->start(50); //Устанавливаем счетчик для объекта timer (каждые 50 милесекунд будет выполянться метод move)
}
void Bullet::move() //Метод смещения пули вверх
{
//Проверяем на столкновении пули и врага, удаление оба объекта при столкновении
QList<QGraphicsItem *> colliding_items = collidingItems(); //Создадим список "Сталкивающиеся предметы" (из указателей на сталкивающиеся объеткы) и при помощи функции collidingItems()(возвращает указатель на тот объект с которым произошло столкновение, в нашем случае на того врага с которым столкнулась эта пуля) заполним его
for (int i = 0;i < colliding_items.size(); ++i)
{
if(typeid(*(colliding_items[i])) == typeid(Enemy)) //Если в списке есть указатель на объект типа враг то удаляем его, т.к. он был занесен в список ранее, значит пуля столкнулась с данных объектом
{
vgame->scene->score->increase(); //Т.к. объявили указатель на внешнюю глобальную переменную(указатель) game, то можно через него вызвать метод increase() класса Score
scene()->removeItem(colliding_items[i]); //Удаляем врага из объекта scene
scene()->removeItem(this); //Удаляем пулю столкнувшиюся с врагом из объекта scene
delete colliding_items[i]; //Удаляем сам объект врага из пямяти
delete this; //Удаляем пулю (объект) столкнувшиюся с врагом из памяти
return; //После удаления нужно выйти из функции дабы не продолжать выполнение последующего кода
}
}
setPos(x(),y()-10);
if ((pos().y() + pixmap().height()) < 0) // Если позиция по координате y стала меньше 0 в ситеме координат scene то удалим этот объект из scene
{
scene()->removeItem(this); // Удаляем объект из объекта scene класса QGraphicsScene
//qDebug() << "Пуля удалена";
delete this; // Удаляем сам объект пуля из памяти
}
}
|
C++ | UTF-8 | 411 | 3.015625 | 3 | [
"MIT"
] | permissive | class Solution {
public:
vector<int> lexicalOrder(int n) {
vector<int> res;
solve(1, n, res);
return res;
}
void solve(int target, int n, vector<int> &res) {
if (target > n) {
return;
}
res.push_back(target);
solve(target * 10, n, res);
if (target % 10 != 9) {
solve(target + 1, n, res);
}
}
}; |
Shell | UTF-8 | 2,047 | 3.796875 | 4 | [] | no_license | #!/bin/sh
# Abbreviated tree ID for this brain
GITREF="$(git ls-tree -d --abbrev=8 HEAD brain | cut -f 1 | cut -f 3 -d' ')"
# Depth of git history, for better sorting
#GITDEPTH="$(git rev-list HEAD | wc -l)"
#But let's use the time of the commit. Let's get it in unix format and format it ourselves, in UTC
GITTIME="$(git show --format="%at" -s HEAD)"
GITTIME="$(TZ=UTC date -r $GITTIME "+%Y-%m-%d-%H%M")"
# Get the GUID to use. We accept one on the command line, but will generate or reuse one below.
GUID="$1"
truname() {
(cd "$1"; echo "$PWD")
}
BINDIR=$(dirname "$0")
export PATH="$BINDIR:$PATH"
ROOTDIR=$(truname $(dirname "$BINDIR"))
BRAINDIR="$ROOTDIR/brain"
TMPDIR="$ROOTDIR/tmp"
BUILDDIR="$ROOTDIR/build"
GUIDFILE="$ROOTDIR/.git/info/brain-guid"
# Reuse prio GUID, or generate (if needed) and save.
if [ -e "$GUIDFILE" ]; then
GUID="${GUID:-$(cat "$GUIDFILE")}"
else
GUID="${GUID:-$(uuidgen | tr A-Z a-z)}"
echo "$GUID" >"$GUIDFILE"
fi
K_NAME="7501869f-6fc5-5c4b-b838-f3f7287c138c"
BRAIN_NAME="$(jq -r 'select(.Id=="'$K_NAME'") .Value' <brain/settings.json)"
BRAIN_NAME="${BRAIN_NAME}-$(echo "$GUID" | git hash-object --stdin | cut -c 1-8)"
BRZ="$BUILDDIR/${BRAIN_NAME}-$GITTIME-$GITREF.brz"
echo "Name: ${BRAIN_NAME}"
echo "Source: $BRAINDIR"
echo "Brain ID: $GUID"
echo "Commit Time: $GITTIME (UTC)"
echo "Tree Id: $GITREF"
echo "Building: $BRZ"
#echo "Root: $ROOTDIR"
#echo "Temp: $TMPDIR"
function BOM() {
printf "\xef\xbb\xbf"
}
mkdir -p "$TMPDIR"
rm -rf "$TMPDIR"/*
cp -rp "$BRAINDIR"/ "$TMPDIR"/
for j in "$BRAINDIR"/*.json; do
f="${TMPDIR}/$(basename "$j")"
echo "Updating GUID for $f"
(BOM; jq --compact-output '.BrainId = "'"$GUID"'"' <"$f" )>"$f".tmp
mv "$f".tmp "$f"
done
(BOM; jq --compact-output 'if .Id=="'$K_NAME'" then .Value="'$BRAIN_NAME'" else . end' <"$TMPDIR/settings.json" )>"$TMPDIR/settings.json.tmp"
mv "$TMPDIR/settings.json.tmp" "$TMPDIR/settings.json"
mkdir -p "$BUILDDIR"
rm -f "$BRZ"
(cd $TMPDIR; zip --recurse-paths -q "$BRZ" .)
rm -rf "$TMPDIR"
|
Python | UTF-8 | 9,193 | 2.8125 | 3 | [
"MIT"
] | permissive | import os
import time
from astropy import units as u
from astropy.time import Time
from ..utils import current_time
from ..utils import error
from ..utils import listify
class PanStateLogic(object):
""" The enter and exit logic for each state. """
def __init__(self, **kwargs):
self.logger.debug("Setting up state logic")
self._sleep_delay = kwargs.get('sleep_delay', 2.5) # Loop delay
self._safe_delay = kwargs.get('safe_delay', 60 * 5) # Safety check delay
self._is_safe = False
# This should all move to the `states.pointing` module or somewhere else
point_config = self.config.get('pointing', {})
self._max_iterations = point_config.get('max_iterations', 3)
self._pointing_exptime = point_config.get('exptime', 30) * u.s
self._pointing_threshold = point_config.get('threshold', 0.01) * u.deg
self._pointing_iteration = 0
##################################################################################################
# State Conditions
##################################################################################################
def check_safety(self, event_data=None):
""" Checks the safety flag of the system to determine if safe.
This will check the weather station as well as various other environmental
aspects of the system in order to determine if conditions are safe for operation.
Note:
This condition is called by the state machine during each transition
Args:
event_data(transitions.EventData): carries information about the event if
called from the state machine.
Returns:
bool: Latest safety flag
"""
self.logger.debug("Checking safety for {}".format(event_data.event.name))
# It's always safe to be in some states
if event_data and event_data.event.name in ['park', 'set_park', 'clean_up', 'goto_sleep', 'get_ready']:
self.logger.debug("Always safe to move to {}".format(event_data.event.name))
is_safe = True
else:
is_safe = self.is_safe()
return is_safe
def is_safe(self):
""" Checks the safety flag of the system to determine if safe.
This will check the weather station as well as various other environmental
aspects of the system in order to determine if conditions are safe for operation.
Note:
This condition is called by the state machine during each transition
Args:
event_data(transitions.EventData): carries information about the event if
called from the state machine.
Returns:
bool: Latest safety flag
"""
is_safe_values = dict()
# Check if night time
if 'night' in self.config['simulator']:
self.logger.debug("Night simulator says safe")
is_safe_values['is_dark'] = True
else:
is_safe_values['is_dark'] = self.is_dark()
# Check weather
if 'weather' in self.config['simulator']:
self.logger.debug("Weather simluator always safe")
is_safe_values['good_weather'] = True
else:
is_safe_values['good_weather'] = self.is_weather_safe()
self.logger.debug("Safety: {}".format(is_safe_values))
safe = all(is_safe_values.values())
if not safe:
self.logger.warning('System is not safe')
self.logger.warning('{}'.format(is_safe_values))
# Not safe so park unless we are not active
if self.state not in ['sleeping', 'parked', 'parking', 'housekeeping', 'ready']:
self.logger.warning('Safety failed so sending to park')
self.park()
self.logger.debug("Safe: {}".format(safe))
return safe
def is_dark(self):
""" Is it dark
Checks whether it is dark at the location provided. This checks for the config
entry `location.horizon` or 18 degrees (astronomical twilight).
Returns:
bool: Is night at location
"""
is_dark = self.observatory.is_dark
self.logger.debug("Dark: {}".format(is_dark))
return is_dark
def is_weather_safe(self, stale=180):
""" Determines whether current weather conditions are safe or not
Args:
stale(int): If reading is older than `stale` seconds, return False. Default 180 (seconds).
Returns:
bool: Conditions are safe (True) or unsafe (False)
"""
assert self.db.current, self.logger.warning("No connection to sensors, can't check weather safety")
# Always assume False
is_safe = False
record = {'safe': False}
self.logger.debug("Weather Safety:")
try:
record = self.db.current.find_one({'type': 'weather'})
is_safe = record['data'].get('safe', False)
self.logger.debug("\t is_safe: {}".format(is_safe))
timestamp = record['date']
self.logger.debug("\t timestamp: {}".format(timestamp))
age = (current_time().datetime - timestamp).total_seconds()
self.logger.debug("\t age: {} seconds".format(age))
except:
if 'weather' not in self.config['simulator']:
self.logger.warning("Weather not safe or no record found in Mongo DB")
else:
if age > stale:
self.logger.warning("Weather record looks stale, marking unsafe.")
is_safe = False
finally:
self._is_safe = is_safe
return self._is_safe
def mount_is_tracking(self, event_data):
""" Transitional check for mount.
This is used as a conditional check when transitioning between certain
states.
"""
return self.observatory.mount.is_tracking
def mount_is_initialized(self, event_data):
""" Transitional check for mount.
This is used as a conditional check when transitioning between certain
states.
"""
return self.observatory.mount.is_initialized
##################################################################################################
# Convenience Methods
##################################################################################################
def sleep(self, delay=2.5, with_status=True):
""" Send POCS to sleep
This just loops for `delay` number of seconds.
Keyword Arguments:
delay {float} -- Number of seconds to sleep (default: 2.5)
with_status {bool} -- Show system status while sleeping (default: {True if delay > 2.0})
"""
if delay is None:
delay = self._sleep_delay
if with_status and delay > 2.0:
self.status()
time.sleep(delay)
def wait_until_files_exist(self, filenames, transition=None, callback=None, timeout=150):
""" Loop to wait for the existence of files on the system """
assert filenames, self.logger.error("Filename(s) required for loop")
filenames = listify(filenames)
self.logger.debug("Waiting for files: {}".format(filenames))
_files_exist = False
# Check if all files exist
exist = [os.path.exists(f) for f in filenames]
if type(timeout) is not u.Quantity:
timeout = timeout * u.second
end_time = Time.now() + timeout
self.logger.debug("Timeout for files: {}".format(end_time))
while not all(exist):
if Time.now() > end_time:
# TODO Interrupt the camera properly
raise error.Timeout("Timeout while waiting for files")
break
self.sleep()
exist = [os.path.exists(f) for f in filenames]
else:
self.logger.debug("All files exist, now exiting loop")
_files_exist = True
if transition is not None:
if hasattr(self, transition):
trans = getattr(self, transition)
trans()
else:
self.logger.debug("Can't call transition {}".format(transition))
if callback is not None:
if hasattr(self, callback):
cb = getattr(self, callback)
cb()
else:
self.logger.debug("Can't call callback {}".format(callback))
return _files_exist
def wait_until_safe(self):
""" Waits until weather is safe
This will wait until a True value is returned from the safety check,
blocking until then.
"""
if 'weather' not in self.config['simulator']:
while not self.is_safe():
self.sleep(delay=60)
else:
self.logger.debug("Weather simulator on, return safe")
##################################################################################################
# Private Methods
##################################################################################################
|
Java | UTF-8 | 2,654 | 2.484375 | 2 | [
"Apache-2.0"
] | permissive | package com.lememo.sentinel.freqparamflow;
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.EntryType;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleManager;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Collections;
/**
* @author houyi
* @date 2019-01-19
**/
@Controller
public class FreqParamFlowController {
/**
* 热点限流的资源名
*/
private String resourceName = "freqParam";
public FreqParamFlowController(){
// 定义热点限流的规则,对第一个参数设置 qps 限流模式,阈值为5
ParamFlowRule rule = new ParamFlowRule(resourceName)
.setParamIdx(0)
.setGrade(RuleConstant.FLOW_GRADE_QPS)
.setCount(5);
ParamFlowRuleManager.loadRules(Collections.singletonList(rule));
}
/**
* 热点参数限流
* 构造不同的uid的值,并且以不同的频率来请求该方法,查看效果
*/
@GetMapping("/freqParamFlow")
public @ResponseBody
String freqParamFlow(@RequestParam("uid") Long uid,@RequestParam("ip") Long ip) {
Entry entry = null;
String retVal;
try{
// 只对参数 uid 的值进行限流,参数 ip 的值不进行限制
entry = SphU.entry(resourceName, EntryType.IN,1,uid);
retVal = "passed";
}catch(BlockException e){
retVal = "blocked";
}finally {
if(entry!=null){
entry.exit();
}
}
return retVal;
}
/**
* 热点参数限流
*/
@GetMapping("/freqParamFlowWithoutParam")
public @ResponseBody
String freqParamFlowWithoutParam(@RequestParam("uid") Long uid,@RequestParam("ip") Long ip) {
Entry entry = null;
String retVal;
try{
// 如果不传入任何参数,来查询热点参数限流的效果
entry = SphU.entry(resourceName, EntryType.IN,1);
retVal = "passed";
}catch(BlockException e){
retVal = "blocked";
}finally {
if(entry!=null){
entry.exit();
}
}
return retVal;
}
}
|
Java | UTF-8 | 255 | 3.0625 | 3 | [] | no_license | public class objectTest
{
public static void main(String[] args) {
person p=new person();
p.say("Hello");
}
}
class person
{
public String name;
public int age;
public void say(String content)
{
System.out.println(content);
}
}
|
TypeScript | UTF-8 | 2,944 | 2.890625 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | import global from './global';
import has from './has';
import { Handle } from './interfaces';
import { QueueItem } from './queue';
/**
* Create macro-scheduler based nextTick function.
*/
function createMacroScheduler(
schedule: ((callback: () => void, timeout?: number) => void),
clearSchedule: ((handle: any) => void)
) {
let queue = new CallbackQueue();
let timer: any;
return function(callback: () => void): Handle {
let handle = queue.add(callback);
if (!timer) {
timer = schedule(function (): void {
clearSchedule(timer);
timer = null;
queue.drain();
}, 0);
}
return handle;
};
}
/**
* A queue of callbacks that will be executed in FIFO order when the queue is drained.
*/
class CallbackQueue {
private _callbacks: QueueItem[] = [];
add(callback: () => void): { destroy: () => void } {
let _callback = {
isActive: true,
callback: callback
};
this._callbacks.push(_callback);
callback = null;
return {
destroy: function() {
this.destroy = function() {};
_callback.isActive = false;
_callback = null;
}
};
}
drain(...args: any[]): void {
let callbacks = this._callbacks;
let item: QueueItem;
let count = callbacks.length;
// Any callbacks added after drain is called will be processed
// the next time drain is called
this._callbacks = [];
for (let i = 0; i < count; i++) {
item = callbacks[i];
if (item && item.isActive) {
item.callback.apply(null, args);
}
}
}
}
let nextTick: (callback: () => void) => Handle;
let nodeVersion = has('host-node');
if (nodeVersion) {
// In Node.JS 0.9.x and 0.10.x, deeply recursive process.nextTick calls can cause stack overflows, so use
// setImmediate.
if (nodeVersion.indexOf('0.9.') === 0 || nodeVersion.indexOf('0.10.') === 0) {
nextTick = createMacroScheduler(setImmediate, clearImmediate);
}
else {
nextTick = function(callback: () => void): Handle {
let removed = false;
process.nextTick(function (): void {
// There isn't an API to remove a pending call from `process.nextTick`
if (removed) {
return;
}
callback();
});
return {
destroy: function (): void {
this.destroy = () => {};
removed = true;
}
};
};
}
}
else if (has('dom-mutationobserver')) {
let queue = new CallbackQueue();
nextTick = (function (): typeof nextTick {
let MutationObserver = this.MutationObserver || this.WebKitMutationObserver;
let element = document.createElement('div');
let observer = new MutationObserver(function (): void {
queue.drain();
});
observer.observe(element, { attributes: true });
return function(callback: () => void): Handle {
let handle = queue.add(callback);
element.setAttribute('drainQueue', '1');
return handle;
};
})();
}
else {
// If nothing better is available, fallback to setTimeout
nextTick = createMacroScheduler(setTimeout, clearTimeout);
}
export default nextTick;
|
C# | UTF-8 | 488 | 2.96875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Aula11_Exercicio2
{
class Program
{
static void Main(string[] args)
{
int cont = 0;
while(cont < 1000)
{
Console.WriteLine(cont);
cont = cont + 1;
Thread.Sleep(500);
}
Console.ReadKey();
}
}
}
|
JavaScript | UTF-8 | 951 | 3.296875 | 3 | [] | no_license |
class Enemy extends Drawable
{
constructor(sketch, config, x, y, type)
{
super(sketch, config, x, y);
this.pictures = [
config.getImage(0, 16 * type, 16, 16),
config.getImage(16, 16 * type, 16, 16)];
this.timer = 0;
this.imageIndex = 0;
this.hit = false;
this.variant = type;
this.firingTime = Math.random() * 2000;
}
move(deltaX, deltaY)
{
this.x += deltaX;
this.y += deltaY;
}
}
Enemy.prototype.draw = function(update)
{
this.firingTime -= update;
this.timer++;
if (this.timer > 40)
{
this.timer = 0;
this.imageIndex = ++this.imageIndex % 2;
}
this.sketch.image(
this.pictures[this.imageIndex],
this.getX(), this.getY(),
this.getWidth(), this.getHeight());
}
Enemy.prototype.resetFiringTimer = function()
{
this.firingTime = 2000 + (Math.random() * 3000);
} |
Markdown | UTF-8 | 1,799 | 3.921875 | 4 | [] | no_license | <img src="morning-exercise.png" width="100%" />
# Morning Exercise
Create a one page website, using semantic html (using `header`, `main`, `footer` tags as top level elements) where within the `main` tag you have 3 `section` elements.
Content & Structure:
- Each section should have an `id` starting with `section-[section-number]` (e.g the first section should have an `id` of `section-1`, the second section should be `section-2`, etc)
- The `section` elements should have the text "Section 1", "Section 2", "Section 3" respectively within each element.
- The `header` should have a `nav` element nested within it
- The `nav` should have 3 links nested within it where the anchor text should say "Jump to Section 1", "Jump to Section 2", "Jump to Section 3" respectively. When clicked each anchor should jump to the matching section. (e.g "Jump to Section 2 should jump to the section with `id="section-2"`)
- The `footer` should just have the text "Footer" within it
Design Requirements:
- The `header`, `section` and `footer` elements should have a height of `600px` and occupy the entire window width
- The `header`, 3 `section`, and `footer` elements should alternate background colors between `#759FBC` (light-blue) and `#B9B8D3` (light-purple)
- Each section should have `center` aligned text
- The `header`, `section` and `footer` elements should have a `font-size` of `40px`,`font-family` of `sans-serif` and `20px` of padding
- The `header` should have `right` aligned text
- The `footer` should have `center` aligned text
- The text `color` should be `#fff` when the background is light-blue and should be `#1F2D3D` when the background color is light-purple
The end result should look something like this:
<img src="top.png" width="100%" />
<img src="bottom.png" width="100%" /> |
Java | UTF-8 | 1,414 | 2.140625 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2012 M3, Inc.
*
* 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.m3.multilane.action;
import com.m3.scalaflavor4j.Either;
/**
* Action that will be executed asynchronously
*
* @param <INPUT> input type
* @param <OUTPUT> output type
*/
public interface Action<INPUT, OUTPUT> {
/**
* Getter for input
*
* @return input
*/
INPUT getInput();
/**
* Setter for input
*
* @param input input
*/
void setInput(INPUT input);
/**
* Getter for timeout millis
*
* @return timeout millis
*/
Integer getTimeoutMillis();
/**
* Setter for timeout millis
*
* @param millis timeout millis
*/
void setTimeoutMillis(Integer millis);
/**
* Apply this action synchronously
*
* @return result as an either
*/
Either<Throwable, OUTPUT> apply();
} |
Python | UTF-8 | 5,993 | 2.71875 | 3 | [] | no_license | '''Create database models.
Profile -- A model used to add more fields to a user.
Availability -- A model to model the availabily timings of users.
Skill -- Used to model the skills of a user.
Notification -- Used to model the notification sent to a user.
'''
import uuid
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class Profile(models.Model):
'''This class models a profile with 7 fields.
id -- The primary field of the Profile model.
user -- A one-to-one field that is a user.
bio -- A text field for a user's bio.
user_type -- The user type of a user (e.g student or tutor)
profile_pic -- The profile pic of a user.
email_verified -- A boolean field which tells us if the user has verified
his email or not.
has_signed_up -- A boolean field which tells us if it's the user's first
time signing up or not.
show_tutorial -- A boolean field which tells us if have to show
the tutorial when they open the agenda page.
'''
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(max_length=500, blank=True, null=True, default='')
user_type = models.CharField(max_length=16, blank=False, null=False)
profile_pic = models.ImageField(upload_to="profile_pics", blank=False, default='profile_pics/default.png')
email_verified = models.BooleanField(default=False)
# the following field is useful for google sign ups
has_signed_up = models.BooleanField(default=False)
show_tutorial = models.BooleanField(default=True)
def __str__(self):
'''Used for string outputs for a profile'''
return str(self.user.get_full_name())
class Availability(models.Model):
'''This class models an availability with 5 fields.
id -- The primary field of the Availability model.
profile -- A one-to-one field that is a profile.
day -- The name of the day (e.g Monday)
start_time -- When the availability starts.
end_time -- When the availability ends.
'''
id = models.AutoField(primary_key=True)
profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
day = models.CharField(max_length=15)
start_time = models.DateTimeField()
end_time = models.DateTimeField()
def __str__(self):
'''Used for string outputs for an Availability'''
return '{} from {} to {} on {}'.format(
self.profile.user.get_full_name(), self.start_time, self.end_time,
self.day)
class Skill(models.Model):
'''This class models a skill with 2 fields.
Profile -- A ForeignKey which tells us which profile the skill belongs to.
Skill -- A charfield that tells us the actual skill.
'''
profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
skill = models.CharField(max_length=30)
def __str__(self):
'''Used for string outputs for a skill'''
return self.profile.user.get_full_name() + ' has skill: ' + self.skill
class BlockedUsers(models.Model):
'''This class models a blocking relationship between a user blocking another
user
User -- The person who's blocking
Blocked_User -- The blocked person.
'''
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_rel')
blocked_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blocked_user_rel')
def __str__(self):
'''Used for string outputs for a blocked user'''
return '{} blocked {}'.format(self.user.get_full_name(),
self.blocked_user.get_full_name())
class Notification(models.Model):
'''This class models a notification with 6 fields.
user -- A one-to-one field that is a user.
message -- A char field that holds the notification message.
created_on -- The date the notification was created on.
picture -- The picture of the notification.
unread -- A boolean field which tells us if this notification is read or not
link -- A charfield that holds the link that the user can go to if he clicks
on the notification.
'''
user = models.ForeignKey(User, on_delete=models.CASCADE)
message = models.CharField(max_length=150)
created_on = models.DateTimeField()
picture = models.ImageField(upload_to="notification_pictures", blank=True)
unread = models.BooleanField(default=True)
link = models.CharField(max_length=70, default='')
def __str__(self):
'''Used for string outputs for a notification'''
return self.message
class Preference(models.Model):
'''This class models a notification with 4 fields.
id - The ID to track the preference object.
user -- A one-to-one field that is a user.
title -- The title of the preference.
description -- The description of the preference.
active -- Whether the preference is active or not.
'''
id = models.AutoField(primary_key=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=80)
description = models.CharField(max_length=150)
active = models.BooleanField(default=True)
@classmethod
def create(cls, user, title, description, active):
preference = cls(user=user, title=title, description=description,
active=active).save()
return preference
# Below code is necessary
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
'''Creates a profile when a user object is created.'''
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
'''Saves a profile when a profile object is created.'''
instance.profile.save()
|
PHP | UTF-8 | 2,393 | 2.671875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | <?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
/*
* =======================================
* Author : Jagdish
* License : Protected
* Email : dev@lastingerp.com
*
* =======================================
*/
class Efs_api {
public function api_init($url,$fields=null,$method=null,$file=null){
//ini_set("default_socket_timeout", 10);
// required:
// url = include http or https
// optionals:
// fields = must be array (e.g.: 'field1' => $field1, ...)
// method = "GET", "POST"
// file = if want to download a file, declare store location and file name (e.g.: /var/www/img.jpg, ...)
// please create 'cookies' dir to store local cookies if neeeded
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
if($file!=null){
if (!curl_setopt($ch, CURLOPT_FILE, $file)){ // Handle error
die("curl setopt bit the dust: " . curl_error($ch));
}
//curl_setopt($ch, CURLOPT_FILE, $file);
//$timeout= 3600;
}
$timeout= 3600;
//curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
if($fields!=null){
$postvars = http_build_query($fields); // build the urlencoded data
//$postvars = $fields; // build the urlencoded data
//print_r($postvars);
if($method=="POST"){
// set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
}
if($method=="GET"){
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
$url = $url.'?'.$postvars;
//$url = $url.'?'.urldecode($postvars);
//$url = $url.'?clientId='.$postvars.'&request=all';
}
}
curl_setopt($ch, CURLOPT_URL, $url);
$content = curl_exec($ch);
if (!$content){
$error = curl_error($ch);
$info = curl_getinfo($ch);
die("cURL request failed, error = {$error}; info = " . print_r($info, true));
}
if(curl_errno($ch)){
echo 'error:' . curl_error($ch);
} else {
$output = simplexml_load_string($content,'SimpleXMLElement',LIBXML_NOCDATA) or die("Error: Cannot create object");
print_r($url);echo"<br>";
return $output;
}
curl_close($ch);
}
}
?> |
Python | UTF-8 | 1,376 | 2.875 | 3 | [
"MIT"
] | permissive | from django.test import TestCase
from django.contrib.auth import get_user_model
class ModelTest(TestCase):
def test_create_user_with_email_succeful(self):
"""test that create a new user woth email is succefully done"""
email = "test@test.com"
password = "test123"
user = get_user_model().objects.create_user(
email=email,
password=password
)
self.assertEqual(user.email, email)
self.assertTrue(user.check_password(password))
def test_email_is_normalized(self):
"""test that new user email is normalized"""
email = "test@TESt.cOM"
user = get_user_model().objects.create_user(
email=email,
password="test123"
)
self.assertEqual(user.email, email.lower())
def test_new_user_should_have_email(self):
"""test that new user requires email"""
with self.assertRaises(ValueError):
get_user_model().objects.create_user(
email=None,
password="test123"
)
def test_create_superuser(self):
"""test that createsuper user works"""
user = get_user_model().objects.create_superuser(
email="test@test.com",
password="test123"
)
self.assertTrue(user.is_staff)
self.assertTrue(user.is_superuser)
|
TypeScript | UTF-8 | 203 | 2.5625 | 3 | [] | no_license | import dayjs from 'dayjs';
function formatTime(value: string, format = 'DD/MM/YYYY HH:mm') {
if (!value) return null;
else {
return dayjs(value).format(format);
}
}
export default formatTime;
|
C++ | UTF-8 | 1,612 | 2.65625 | 3 | [] | no_license | #include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "previewentry.h"
using namespace enlighten::lib;
class PreviewEntryTest : public testing::Test
{
public:
PreviewEntryTest()
{
fakeUuid = "3829E5FC-7F3F-4B22-94F3-FB5E2C796026";
fakeDigest = "07cc63f155500a902b21fef7be6585b5";
fakeLevels.push_back(PreviewEntryLevel(1, 67.0f));
fakeLevels.push_back(PreviewEntryLevel(2, 134.0f));
fakeLevels.push_back(PreviewEntryLevel(3, 543.0f));
fakeLevels.push_back(PreviewEntryLevel(4, 1068.0f));
}
protected:
std::string fakeUuid;
std::string fakeDigest;
std::vector<PreviewEntryLevel> fakeLevels;
};
TEST_F(PreviewEntryTest, ShouldReturnNumberOfLevelsAvailable)
{
PreviewEntry entry(fakeUuid, fakeDigest, fakeLevels);
unsigned int numberOfLevels = entry.numberOfLevels();
EXPECT_EQ(4, numberOfLevels);
}
TEST_F(PreviewEntryTest, ShouldPrepareAValidFilepath)
{
PreviewEntry entry(fakeUuid, fakeDigest, fakeLevels);
std::string generatedPath = entry.filePathRelativeToRoot();
EXPECT_STREQ("3/3829/3829E5FC-7F3F-4B22-94F3-FB5E2C796026-"
"07cc63f155500a902b21fef7be6585b5.lrprev", generatedPath.c_str());
}
TEST_F(PreviewEntryTest, ShouldReturnClosestLevelToAGivenDimension)
{
PreviewEntry entry(fakeUuid, fakeDigest, fakeLevels);
unsigned int level = entry.closestLevelToDimension(256.0f);
EXPECT_EQ(3, level);
}
TEST_F(PreviewEntryTest, ShouldReturnAnInvalidLevelIndexIfNoSuitableDimensionExists)
{
PreviewEntry entry(fakeUuid, fakeDigest, fakeLevels);
unsigned int level = entry.closestLevelToDimension(2048.0f);
EXPECT_EQ(PreviewEntry::INVALID_LEVEL_INDEX, level);
}
|
C# | UTF-8 | 1,689 | 2.6875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OOD.EMS.Users;
namespace OOD.EMS.Execution
{
[Serializable()]
public class OrganizationStructure
{
private static OrganizationStructure instance;
private List<Department> departments;
public Department Root { get; set; }
private OrganizationStructure()
{
departments = new List<Department>();
Department root = new Department("سازمان", null, null);
this.create(root);
}
public static OrganizationStructure getInstance()
{
if (instance == null)
{
if (Storage.getInstance().structure == null)
instance = new OrganizationStructure();
else instance = Storage.getInstance().structure;
}
return instance;
}
public List<Department> all()
{
return departments;
}
public void create(Department dept)
{
if (Root == null && dept.Supervisor == null)
{
Root = dept;
departments.Add(dept);
}
else if (Root != null && dept.Supervisor != null && departments.Contains(dept.Supervisor) && !departments.Contains(dept))
{
departments.Add(dept);
}
}
public void remove(Department d)
{
foreach (Department child in d.getChildren())
{
remove(child);
}
departments.Remove(d);
}
}
}
|
C# | UTF-8 | 16,697 | 2.96875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Globalization;
namespace T.Pratico
{
public class Loja
{
// lista de clientes
private List<Cliente> clientes = new List<Cliente>();
// lista de instrumentos
private List<Instrumento> instrumentos = new List<Instrumento>();
// lista de alugueres
// A lista de alugueres guarda todos os alugueres que existem no momento
private List<aluguer> alugueres = new List<aluguer>();
// A lista de alugueres guarda todos os alugueres que ja foram feitos e fechados
private List<aluguer> hist_alugueresloja = new List<aluguer>();
// --------- Funcoes --------- //
// --------- Clientes --------- //
//criar cliente
public bool Criar_cliente(string n, string t)
{
Cliente novo = new Cliente(n, t);
clientes.Add(novo);
if (clientes.Contains(novo))
{
return true;
}
else
{
return false;
}
}
//Verifica se o nome do cliente ja existe
public bool Verifica_existe_nome(string nome)
{
if (clientes.Count != 0)
{
foreach (var c in clientes)
{
if (c.nome == nome)
return true;
}
return false;
}
return false;
}
//Procura cliente com nome recebido
public bool mudar_nome_cliente(string nome,string novonome)
{
foreach (var cliente in clientes)
{
if (cliente.nome == nome)
{
cliente.nome = novonome;
return true;
}
}
return false;
}
//Procurar cliente e muda telefone
public bool mudar_telefone_cliente(string nome, string novotele)
{
foreach (var cliente in clientes)
{
if (cliente.nome == nome)
{
cliente.telefone = novotele;
return true;
}
}
return false;
}
// Retorna numa string os dados de um aluguer no historico de um cliente, dado por nome
public string dados_aluguere_historico_cliente(string nomecliente)
{
foreach (var cliente in clientes)
{
if (cliente.nome == nomecliente)
{
string dados = cliente.dados_aluguer_historico();
return dados;
}
}
return null;
}
// Retorna uma string com os dados de um cliente da lista dado por nome
public string informcacoes_cliente_pedido(int i)
{
string dados = "Nome cliente: " + clientes[i].nome + "\nTelefone: " + clientes[i].telefone +
"\nGuitarras alugadas de momento: "
+ clientes[i].num_alugueres_actuais_abertos();
return dados;
}
//Funcao que da os atrasos do cliente nos alugueres que ja entregou
public int cliente_atrasos(string nomecliente)
{
foreach (var cliente in clientes)
{
if (cliente.nome == nomecliente)
{
return cliente.getatrasos();
}
}
return 0;
}
// Retorna quando alugueres, ja finalizados, fez o cliente
public int num_alugueres_concluidos_cliente(string nomecliente)
{
foreach (var cliente in clientes)
{
if (cliente.nome == nomecliente)
{
return cliente.numalugueres_historico();
}
}
return 0;
}
// Retorna quando alugueres, em aberto, tem o cliente
public int num_alugueres_abertos_cliente(string nomecliente)
{
foreach (var cliente in clientes)
{
if (cliente.nome == nomecliente)
{
return cliente.num_alugueres_actuais_abertos();
}
}
return 0;
}
// Quantas vezes os instrumentos vieram danificados, de alugueres que ja finalizaram de um dado cliente
public int cliente_danificadas(string nomecliente)
{
foreach (var cliente in clientes)
{
if (cliente.nome == nomecliente)
{
return cliente.getdanificadas();
}
}
return 0;
}
// --------- Alugueres --------- //
// Guardar o aluguer na lista de alugueres da loja e enviar ao cliente para este guardar na sua lista de alugueres em aberto
public bool guardar_aluguer(string nome, int id, int diasaluguer)
{
aluguer novo = new aluguer(nome, id, diasaluguer);
alugueres.Add(novo);
foreach (var cliente in clientes)
{
if (cliente.nome == nome)
{
cliente.guarda_aluguer_aberto(novo);
foreach (var instrumento in instrumentos)
{
if(instrumento.getid == id)
instrumento.mudar_estado(2);
}
}
}
return true;
}
// Funcao retorna numero de alugueres em aberto da loja
public int num_alugueres_abertosloja()
{
return alugueres.Count;
}
// Funcao retorna numero de alugueres concluidos da loja
public int num_alugueres_historicoloja()
{
return hist_alugueresloja.Count;
}
// Retorna dados do aluguer se o ID do instrumento for o pedido
public string dados_historicoaluguer_Id(int id)
{
foreach (var aluguer in hist_alugueresloja)
{
if (aluguer.getIDaluguer() == id)
{
return aluguer.dados_aluguer();
}
}
return null;
}
//Retorna dados dos alugueres todos em historico
public string dados_aluguer_aberto()
{
foreach (var aluguer in alugueres)
{
return aluguer.dados_aluguer();
}
return null;
}
//Retorna dados dos alugueres todos em historico
public string dados_historicoaluguer_todos()
{
string dados;
foreach (var aluguer in hist_alugueresloja)
{
dados = aluguer.dados_aluguer_hist();
if (aluguer.atraso_aluguer() == true)
{
dados += "\nAtraso na entrega: Sim";
if (aluguer.getdanificado() == true)
{
dados += "\nDanificado na entrega: Sim";
return dados;
}
else
{
dados += "\nDanificado na entrega: Não";
return dados;
}
}
else
{
dados += "\nAtraso na entrega: Não";
if (aluguer.getdanificado() == true)
{
dados += "\nDanificado na entrega: Sim";
return dados;
}
else
{
dados += "\nDanificado na entrega: Não";
return dados;
}
}
}
return null;
}
// lista de melhores clientes
public string melhores_clientes()
{
List<Cliente> melhorestemp = new List<Cliente>();
int cont = 0;
for (int i = 0; i < clientes.Count-1; i++)
{
for (int j = 1; j < clientes.Count; j++)
{
if (clientes[i].numalugueres_historico() < clientes[j].numalugueres_historico())
{
cont++;
}
}
if (melhorestemp.Count < Limitadores.Max_melhores_clientes)
{
if (cont < Limitadores.Max_melhores_clientes)
{
melhorestemp.Add(clientes[i]);
}
}
else
{
goto enviardados;
}
}
enviardados:
foreach (var melhore in melhorestemp)
{
string dados = "\nNome: " + melhore.nome + "\nTelefone: " + melhore.telefone;
return dados;
}
return "";
}
// Encerrar aluguer
public bool encerra_aluguer(string n, int id, string d)
{
List<aluguer> temp = new List<aluguer>();
for (int i = 0; i < alugueres.Count; i++)
{
if (alugueres[i].getnomealuguer() == n && alugueres[i].getIDaluguer() == id)
{
temp.Add(alugueres[i]);
aluguer temporario = alugueres[i];
foreach (var cliente in clientes)
{
if (cliente.nome == n)
{
cliente.apaga_aluguer_aberto(temporario);
}
}
temporario.dataentrega_final();
temporario.atraso_aluguer();
if (temporario.danificado_aluguer(d) == true)
{
foreach (var instrumento in instrumentos)
{
if (instrumento.getid == id)
{
instrumento.mudar_estado(4); //mudar para danificada
temporario.setdanificado();
}
}
}
else
{
foreach (var instrumento in instrumentos)
{
if (instrumento.getid == id)
{
instrumento.mudar_estado(1); //mudar para disponivel
}
}
}
hist_alugueresloja.Add(temporario);
foreach (var cliente in clientes)
{
if (cliente.nome == n)
{
cliente.guarda_aluguer_historico(temporario);
}
}
goto remover;
}
}
remover:
foreach (var aluguer in temp)
{
alugueres.Remove(aluguer);
}
return true;
}
// -------------------------------- //
// --------- Instrumentos --------- //
// Numero de clientes que existem
public int numclientes()
{
return clientes.Count;
}
// Criar instrumento guitarra
public bool Cria_guitarra(string descrisao, decimal preco_dia, decimal valor)
{
Instrumento novo = new Guitarra(descrisao,preco_dia,valor);
instrumentos.Add(novo);
if (instrumentos.Contains(novo))
return true;
else
return false;
}
// Criar instrumento acordeao
public bool Cria_acordeao(string descrisao, decimal preco_dia, decimal valor)
{
Instrumento novo = new Acordeão(descrisao,preco_dia,valor);
return true;
}
//Estado de um instrumento por ID
public string estadoinstrumento(int id)
{
foreach (var inst in instrumentos)
{
if (inst.getid == id)
{
return inst.get_estado();
}
}
return null;
}
//Preço diario de um instrumento por ID
public bool mudavaloraluguerdiario(int id,decimal valor)
{
foreach (var inst in instrumentos)
{
if (inst.getid == id)
{
inst.valor_diario = valor;
return true;
}
}
return false;
}
//Valor de um instrumento por ID
public bool mudavalor_instrumento(int id, decimal valor)
{
foreach (var inst in instrumentos)
{
if (inst.getid == id)
{
inst.valor_instrumento = valor;
return true;
}
}
return false;
}
//Ver se um instrumento existe por ID
public bool existeid(int id)
{
foreach (var inst in instrumentos)
{
if (inst.getid == id)
return true;
}
return false;
}
// Numero de instrumento que existem na lista
public int numinstrumentos()
{
return instrumentos.Count;
}
// Informacoes de um instrumento por ID
public bool enviar_instrumento_reparacao(int id)
{
foreach (var inst in instrumentos)
{
if (inst.getid == id)
{
if (inst.get_estado() == "danificado")
{
inst.mudar_estado(3);
return true;
}
}
return false;
}
return false;
}
// Informacoes de um instrumento por ID
public bool Voltar_instrumento_reparacao(int id)
{
foreach (var inst in instrumentos)
{
if (inst.getid == id)
{
if (inst.get_estado() == "reparacao")
{
inst.mudar_estado(1);
return true;
}
}
return false;
}
return false;
}
// Informacoes de um instrumento por ID
public string dadosinstrumentos(int id)
{
foreach (var inst in instrumentos)
{
if (inst.getid == id)
{
return inst.ToString();
}
}
return null;
}
// Funcao que retorna o valor de um instrumento
public decimal valor_do_insturmento(int id)
{
foreach (var inst in instrumentos)
{
if (inst.getid == id)
{
return inst.valor_instrumento;
}
}
return 0;
}
// Retorna id do instrumento no aluguer de uma dado utilizador
public bool id_aluguer_utilizador_dado(string nomecliente, int id)
{
foreach (var aluguer in alugueres)
{
if (aluguer.getnomealuguer() == nomecliente)
{
if (aluguer.getIDaluguer() == id)
{
return true;
}
return false;
}
return false;
}
return false;
}
}
} |
C | UTF-8 | 571 | 3.015625 | 3 | [] | no_license | #include<stdio.h>
int read_file(char path[20]){
FILE *fp = NULL;
fp = fopen(path,"r");
char data[8192];
if (fp == NULL)
{
perror("文件打开失败:\n");
return -1;
}
fgets(data,8192,fp);
fclose(fp);
printf("%s\n", data);
return 0;
}
int main(){
char contents[30] = "";
char path[30] = "test.log";
FILE *fd = NULL;
printf("请输入内容:\n" );
scanf("%s",contents);
fd = fopen(path,"w+");
if (fd == NULL)
{
perror("打开文件失败:" );
}
fputs(contents,fd);
fclose(fd);
printf("完成写入\n");
read_file(path);
return 0;
} |
C++ | UTF-8 | 611 | 2.828125 | 3 | [] | no_license | //#include <iostream>
//#include <vector>
//using namespace std;
//
//int main() {
// int W, L;
// cin >> W >> L;
// if (W == 0 || L == 0) {
// cout << 0 << endl;
// return 0;
// }
// vector<int> v;
// v.resize(L);
// for (int i = 0; i < L; i++) {
// cin >> v[i];
// }
// int max = 0;
// int sum = 0;
// for (int i = v.size() - 1; i >= 0; i--) {
// if (max > v[i]) {
// sum += (max - v[i]);
// }
// else {
// max = v[i];
// }
// }
// int Vmax = sum * W;
// cout << Vmax << endl;
// return 0;
//} |
Java | UTF-8 | 694 | 2.734375 | 3 | [] | no_license | package ru.universum.Server;
/**
* Created by Aleksandr on 23.02.17.
*/
public class Out {
String parent = "";
public Out(String parent) {
this.parent = parent;
}
public void printMessage(String string){
System.out.println("[СООБЩЕНИЕ]("+parent+"): " + string);
}
public void printException(String exception){
System.err.println("[ИСКЛЮЧИНИЕ]("+parent+"): " + exception);
}
public void printWarning(String warning){
System.out.println("[ВНИМАНИЕ]("+parent+"): "+ warning);
}
public void printError(String error){
System.err.println(": "+error);
}
}
|
JavaScript | UTF-8 | 3,757 | 2.59375 | 3 | [] | no_license | import { Alert } from 'react-native';
import { openDatabase } from 'react-native-sqlite-storage';
var db = openDatabase({ name: 'tableSd.db' });
// This function will create currency table in database
export const createTableForCurrency = () => {
db.transaction(function (txn) {
txn.executeSql(
"SELECT name FROM sqlite_master WHERE type='table' AND name='Currency'",
[],
(tx, res) => {
console.log('currency', res.rows.length);
if (res.rows.length == 0) {
txn.executeSql('DROP TABLE IF EXISTS Currency', []);
txn.executeSql(
'CREATE TABLE IF NOT EXISTS Currency(Currency_id INTEGER PRIMARY KEY AUTOINCREMENT, currency_name VARCHAR(20), currency_symbol VARCHAR(20))',
[]
);
}
}
);
});
}
// This function will add currency to database
export const AddCurrency = (currencyName, currencySymbol) => {
if (!currencyName) {
alert('Please fill currency name');
return;
}
if (!currencySymbol) {
alert('Give currency sign');
return;
}
db.transaction(function (tx) {
tx.executeSql(
'INSERT INTO Currency(currency_name, currency_symbol) VALUES (?,?)',
[currencyName, currencySymbol],
(tx, results) => {
console.log('Results', results.rowsAffected);
if (results.rowsAffected > 0) {
Alert.alert(
'Success',
'Settings updated',
[
{
text: 'Ok',
},
],
{ cancelable: false }
);
} else alert('Registration Failed');
}
);
});
};
// This function will create tax table in database
export const createTableForTax = () => {
db.transaction(function (txn) {
txn.executeSql(
"SELECT name FROM sqlite_master WHERE type='table' AND name='Tax'",
[],
(tx, res) => {
console.log('Tax', res.rows.length);
if (res.rows.length == 0) {
txn.executeSql('DROP TABLE IF EXISTS Tax', []);
txn.executeSql(
'CREATE TABLE IF NOT EXISTS Tax(Tax_id INTEGER PRIMARY KEY AUTOINCREMENT, tax_name VARCHAR(20), tax_type VARCHAR(20), ratio INT(20))',
[]
);
}
}
);
});
}
// This funtion will insert tax information in database
export const addTaxInfo = (taxName, taxType, ratio) => {
if (!taxName) {
Alert.alert('fill tax name field');
}
if (!taxType) {
Alert.alert('select tax type');
}
if (!ratio) {
Alert.alert('fill ratio field');
}
db.transaction(function (tx) {
tx.executeSql(
'INSERT INTO Tax(tax_name, tax_type, ratio) VALUES (?,?,?)',
[taxName, taxType, ratio],
(tx, results) => {
console.log('Results', results.rowsAffected);
if (results.rowsAffected > 0) {
Alert.alert(
'Success',
'TAX info updated',
[
{
text: 'Ok',
},
],
{ cancelable: false }
);
} else alert('Registration Failed');
}
);
});
} |
Java | UTF-8 | 3,682 | 2.515625 | 3 | [] | no_license | package _02_TripAndJournal.model.dao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import _00_Misc.HibernateUtil_H4_Ver1;
import _02_TripAndJournal.model.JournalDetailVO;
import _02_TripAndJournal.model.JournalPhotoVO;
public class JournalPhotoDAOHibernate {
public JournalPhotoVO select(Integer journalPhotoId) {
JournalPhotoVO vo = null;
Session session = HibernateUtil_H4_Ver1.getSessionFactory()
.getCurrentSession();
try {
session.beginTransaction();
vo = (JournalPhotoVO) session.get(JournalPhotoVO.class,
journalPhotoId);
session.getTransaction().commit();
} catch (RuntimeException ex) {
session.beginTransaction().rollback();
}
return vo;
}
// 由遊記明細編號搜尋遊記照片
private static final String SELECT_BY_JOURNALDETAILID = "from JournalPhotoVO where journalDetailId=:journalDetailId";
public List<JournalPhotoVO> selectByJournalDetailId(int journalDetailId) {
List<JournalPhotoVO> result = null;
Session session = HibernateUtil_H4_Ver1.getSessionFactory()
.getCurrentSession();
try {
session.beginTransaction();
Query query = session.createQuery(SELECT_BY_JOURNALDETAILID);
query.setParameter("journalDetailId", journalDetailId);
result = query.list();
session.getTransaction().commit();
} catch (RuntimeException ex) {
session.getTransaction().rollback();
throw ex;
}
return result;
}
// 查詢遊記主圖
public JournalPhotoVO selectCover(List<JournalDetailVO> journalDetailVOs) {
JournalPhotoVO result = null;
for (JournalDetailVO vo : journalDetailVOs) {
List<JournalPhotoVO> temps = selectByJournalDetailId(vo
.getJournalDetailId());
for (JournalPhotoVO temp : temps) {
if (temp.getCover()) {
result = temp;
}
}
}
return result;
}
public List<JournalPhotoVO> select() {
List<JournalPhotoVO> result = null;
Session session = HibernateUtil_H4_Ver1.getSessionFactory()
.getCurrentSession();
try {
session.beginTransaction();
Query query = session.createQuery("from JournalPhotoVO");
result = query.list();
session.getTransaction().commit();
} catch (RuntimeException ex) {
session.getTransaction().rollback();
throw ex;
}
return result;
}
// 修改資料
public JournalPhotoVO update(JournalPhotoVO vo) {
Session session = HibernateUtil_H4_Ver1.getSessionFactory()
.getCurrentSession();
try {
session.beginTransaction();
session.saveOrUpdate(vo);
session.getTransaction().commit();
} catch (RuntimeException ex) {
session.getTransaction().rollback();
throw ex;
}
return vo;
}
// 新增資料
public JournalPhotoVO insert(JournalPhotoVO vo) {
Session session = HibernateUtil_H4_Ver1.getSessionFactory()
.getCurrentSession();
try {
session.beginTransaction();
session.save(vo);
session.getTransaction().commit();
} catch (RuntimeException ex) {
session.getTransaction().rollback();
throw ex;
}
return vo;
}
// 刪除資料
public boolean delete(Integer journalPhotoId) {
if (this.select(journalPhotoId) != null) {
Session session = HibernateUtil_H4_Ver1.getSessionFactory()
.getCurrentSession();
try {
session.beginTransaction();
JournalPhotoVO vo = (JournalPhotoVO) session.get(
JournalPhotoVO.class, journalPhotoId);
session.delete(vo);
session.getTransaction().commit();
} catch (RuntimeException ex) {
session.getTransaction().rollback();
throw ex;
}
return true;
} else {
return false;
}
}
}
|
C# | UTF-8 | 760 | 2.75 | 3 | [] | no_license | using UnityEngine;
using System.Collections;
public class BoltSkill : BaseSkill {
// Bolt skills are the most basic spell, ranged, single target, damage of a school type
// These are generated at run time for whatever school you want.
public BoltSkill(BaseSchool school)
:base(){
this.Power = 20;
this.Cooldown = 1;
this.TargetEnemy = true;
this.Ranged = true;
this.Ethereal = true;
this.School = school;
this.Information = BuildInformation (school);
}
private BaseObjectInformation BuildInformation (BaseSchool school){
string name = school.Information.Name + " Bolt";
string description = "A ranged ethereal spell that deals "+ school.Information.Name +" damage";
return new BaseObjectInformation (name, description);
}
}
|
JavaScript | UTF-8 | 7,391 | 2.625 | 3 | [] | no_license | window.addEventListener('load', init, false)
let socket
let slider, toolbox, info, picker, login
let allowedToDraw = true
let connected, started = false,
loggedIn = false
let typePlace, chatHeader, collapsable, chatWindow, chat
let lineToDraw = {
curr: {
X: 0,
Y: 0
},
prev: {
X: 0,
Y: 0
},
width: 2,
color: "black",
shape: "line"
}
// P5 drawing stuff
//-----------------------------
function setup() {
let cnv = createCanvas(3200, 1800)
cnv.style('border', 'solid');
background(255)
let lines = REST("GET", "/api/lines").data
for (let i = 0; i < lines.length; i++)
drawLine(lines[i])
}
//mouse input
//----------------------
function mouseDragged() {
if (touches.length > 0) return
drawing(mouseX, mouseY)
}
function mousePressed() {
lineToDraw.prev = lineToDraw.curr
started = true
}
function mouseReleased() {
started = false
}
//---------------------
//touch input
//---------------------
function touchMoved() {
if (touches.length > 1) return
drawing(touches[0].x, touches[0].y)
}
function touchStarted() {
if (touches.length > 0) {
lineToDraw.prev = {
x: touches[0].x,
y: touches[0].y
}
started = true
}
}
function touchEnded() {
started = false
}
//---------------------
function drawing(x, y) {
if (!connected || !loggedIn || !allowedToDraw) return
if (mouseIsPressed && mouseButton === "center") return
if (mouseX < 0 || mouseX > width || mouseY < 0 || mouseY > height) return
lineToDraw.curr.X = x
lineToDraw.curr.Y = y
console.log(`from (${lineToDraw.prev.x},${lineToDraw.prev.y}) to (${lineToDraw.curr.x},${lineToDraw.curr.y})`)
drawLine(lineToDraw)
socket.emit("draw", lineToDraw)
updateInfo()
}
function drawLine(l) {
switch (l.shape) {
case "line":
stroke(color(l.color))
strokeWeight(l.width)
line(l.curr.X, l.curr.Y, l.prev.X, l.prev.Y)
l.prev = {
X: mouseX,
Y: mouseY
}
break
case "rect":
rectMode(CENTER)
fill(color(l.color))
noStroke()
rect(l.curr.X, l.curr.Y, l.width, l.width)
break
case "circ":
ellipseMode(CENTER)
fill(color(l.color))
noStroke()
ellipse(l.curr.X, l.curr.Y, parseInt(l.width))
}
}
//-----------------------------
// HTML stuff
//-----------------------------
function init() {
socket = io()
loadDOMelements()
addEventListeners()
updateInfo()
loggingIn(false)
socket.emit("userConnect", REST('GET', 'https://api.ipify.org?format=json'))
let mes = REST('GET', '/api/messages').data
for (let i = 0; i < mes.length; i++) {
let m = mes[i]
chat.innerHTML += '<li ><div id = "name" > <i class="' + m.flag + '"></i> ' + m.name + '</div> <div id = "message" > ' + m.message + '</div> <hr> </li>'
}
updateScroll()
connected = true
addSocketListeners()
}
function changeColor(obj) {
lineToDraw.color = obj.id
if (obj.id == "white") {
lineToDraw.width = 50;
slider.value = 50
} else lineToDraw.width = slider.value
updateInfo()
}
function updateInfo() {
info.innerHTML = `color: ${lineToDraw.color} - width ${lineToDraw.width}`
}
function loadDOMelements() {
toolbox = document.getElementById("toolbox")
info = document.getElementById("info")
slider = document.getElementById("slider")
picker = document.getElementById("picker")
typePlace = document.getElementById("typingplace")
chatHeader = document.getElementById("chatHeader")
collapsable = document.getElementById("collapsable")
chatWindow = document.getElementById("chatWindow")
chat = document.getElementById("chat")
login = document.getElementById("login")
updateScroll()
}
function addEventListeners() {
typePlace.addEventListener("keyup", event => {
if (event.key === "Enter") {
if (loggedIn) {
socket.emit("message", {
id: socket.id,
m: typePlace.value
})
typePlace.value = ""
}
}
})
login.addEventListener("keyup", event => {
if (event.key === "Enter") {
if (connected) {
socket.emit("login", {
id: socket.id,
m: login.value
})
login.value = ""
loggingIn(true)
}
}
})
picker.addEventListener("change", () => {
lineToDraw.color = picker.value
})
slider.addEventListener("mouseover", () => {
allowedToDraw = false
})
slider.addEventListener("mouseleave", () => {
allowedToDraw = true
})
chatWindow.addEventListener("mouseover", () => {
allowedToDraw = false
})
chatWindow.addEventListener("mouseleave", () => {
allowedToDraw = true
})
document.getElementById("btnErase").addEventListener('click', () => {
socket.emit('delete')
noStroke()
fill(255)
rect(0, 0, width, height)
})
document.getElementById("saveIMG").addEventListener('click', () => {
socket.emit("saved")
saveCanvas("image")
})
slider.addEventListener("change", () => {
lineToDraw.width = slider.value
updateInfo()
})
let chatCollapsed = true
chatHeader.addEventListener("click", () => {
if (chatCollapsed) {
collapsable.style.display = "block"
chatWindow.style.height = "300px"
} else {
collapsable.style.display = "none"
chatWindow.style.height = "25px"
}
chatCollapsed = !chatCollapsed;
})
}
function addSocketListeners() {
socket.on("draw", (rLine) => {
drawLine(rLine)
})
socket.on("delete", () => {
fill(255)
noStroke()
rect(0, 0, width, height)
})
socket.on("login", login => {
chat.innerHTML += '<li> <div id="metaChat">' + login + ' logged in </div><hr></li>'
})
socket.on("logout", logout => {
chat.innerHTML += '<li> <div id="metaChat">' + logout + ' logged out</div> <hr></li>'
})
socket.on("message", m => {
chat.innerHTML += '<li ><div id = "name" > <i class="' + m.flag +
'"></i> ' + m.name + '</div> <div id = "message" > ' + m.message + '</div> <hr> </li>'
updateScroll()
})
}
function loggingIn(b) {
let con = document.getElementById("connected")
let discon = document.getElementById("notConnected")
if (b) {
con.style.display = "block"
discon.style.display = "none"
} else {
con.style.display = "none"
discon.style.display = "block"
}
loggedIn = b
}
function updateScroll() {
var element = document.getElementById("chat");
element.scrollTop = element.scrollHeight;
}
function REST(method, url, message) {
var xhttp = new XMLHttpRequest()
xhttp.open(method, url, false)
xhttp.setRequestHeader("Content-type", "application/json")
if (message)
xhttp.send(message)
else
xhttp.send()
return JSON.parse(xhttp.responseText)
}
|
C# | UTF-8 | 11,586 | 2.671875 | 3 | [] | no_license | using BeanBag.Models;
using BeanBag.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using X.PagedList;
namespace BeanBag.Controllers
{
/* This controller is used to send and retrieve data to the dashboard
view using AI Model and Blob Service functions. */
public class AiModelController : Controller
{
// Global variables needed for calling the service classes.
private readonly IAiService _aIService;
private readonly IBlobStorageService _blobService;
// Constructor.
public AiModelController(IAiService aIService, IBlobStorageService blobService)
{
_aIService = aIService;
_blobService = blobService;
}
/* This function adds a page parameter, a current sort order parameter, and a current filter
parameter to the method signature and returns a view model with pagination to return an AI model list. */
public IActionResult Index(string sortOrder, string currentFilter, string searchString, int? page,
DateTime from, DateTime to)
{
if(User.Identity is {IsAuthenticated: true})
{
//A ViewBag property provides the view with the current sort order, because this must be included in
// the paging links in order to keep the sort order the same while paging
ViewBag.CurrentSort = sortOrder;
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
List<AIModel> modelList;
//ViewBag.CurrentFilter, provides the view with the current filter string.
//the search string is changed when a value is entered in the text box and the submit
//button is pressed. In that case, the searchString parameter is not null.
if (searchString != null)
{
page = 1;
}
else
{
searchString = currentFilter;
}
ViewBag.CurrentFilter = searchString;
var model = from s in _aIService.GetAllModels() select s;
//Search and match data, if search string is not null or empty
if (!String.IsNullOrEmpty(searchString))
{
model = model.Where(s => s.projectName.Contains(searchString));
}
switch (sortOrder)
{
case "name_desc":
modelList = model.OrderByDescending(s => s.projectName).ToList();
break;
default:
modelList = model.OrderBy(s => s.projectName).ToList();
break;
}
//TO DO: Date sorting --- need to add sorting once date created to DB
/* if (sortOrder == "date")
{
modelList =( model.Where(t => t.createdDate > from && t.createdDate < to)).ToList();
}*/
//indicates the size of list
int pageSize = 5;
//set page to one is there is no value, ?? is called the null-coalescing operator.
int pageNumber = (page ?? 1);
//Initialise data and models to be returned to the view.
AIModel mod = new AIModel();
Pagination viewModel = new Pagination();
IPagedList<AIModel> pagedList = modelList.ToPagedList(pageNumber, pageSize);
viewModel.AIModel = mod;
viewModel.PagedListModels = pagedList;
@ViewBag.totalModels = _aIService.GetAllModels().Count;
return View(viewModel);
}
else
{
return LocalRedirect("/");
}
}
/* This function adds a page parameter, a current sort order parameter, and a current filter parameter
to the method signature and returns a view model with pagination to return an AI model version list. */
public IActionResult ModelVersions(Guid projectId, string sortOrder, string currentFilter,
string searchString, int? page,DateTime from, DateTime to)
{
if(User.Identity is {IsAuthenticated: true})
{
//A ViewBag property provides the view with the current sort order, because this must be included in
// the paging links in order to keep the sort order the same while paging
ViewBag.CurrentSort = sortOrder;
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
List<AIModelVersions> modelList;
//ViewBag.CurrentFilter, provides the view with the current filter string.
//the search string is changed when a value is entered in the text box and the submit button is
//pressed. In that case, the searchString parameter is not null.
if (searchString != null)
{
page = 1;
}
else
{
searchString = currentFilter;
}
ViewBag.CurrentFilter = searchString;
var model = from s in _aIService.GetProjectIterations(projectId)
select s;
//Search and match data, if search string is not null or empty
if (!String.IsNullOrEmpty(searchString))
{
model = model.Where(s => s.iterationName.Contains(searchString));
}
switch (sortOrder)
{
case "name_desc":
modelList = model.OrderByDescending(s => s.iterationName).ToList();
break;
default:
modelList = model.OrderBy(s => s.iterationName).ToList();
break;
}
//TO DO: Date sorting --- need to add date created to DB
/* if (sortOrder == "date")
{
modelList =( model.Where(t => t.createdDate > from && t.createdDate < to)).ToList();
}*/
//indicates the size of list
int pageSize = 5;
//set page to one is there is no value, ?? is called the null-coalescing operator.
int pageNumber = (page ?? 1);
//Setting models to be returned to the view
AIModelVersions mod = new AIModelVersions();
Pagination viewModel = new Pagination();
IPagedList<AIModelVersions> pagedList = modelList.ToPagedList(pageNumber, pageSize);
viewModel.AIModelVersions = mod;
viewModel.PagedListVersions = pagedList;
@ViewBag.totalModels = _aIService.GetProjectIterations(projectId).Count;
ViewBag.projectId = projectId;
return View(viewModel);
}
else
{
return LocalRedirect("/");
}
}
// This function is the post method used to create an AI Model instance using the create project AI Service.
[HttpPost]
public async Task<IActionResult> CreateModel(Pagination mods)
{
Guid id = await _aIService.CreateProject(mods.AIModel.projectName);
return LocalRedirect("/AIModel/TestImages?projectId=" + id.ToString());
}
// This function returns the view along with the name of the model to the test image AI model page.
public IActionResult TestImages(Guid projectId)
{
@ViewBag.ID = projectId;
var mods = _aIService.GetAllModels();
foreach (var t in mods.Where(t => t.projectId.Equals(projectId)))
{
@ViewBag.Name = t.projectName ;
}
return View();
}
// This function allows the user to upload images to train a new AI Model.
[HttpPost]
public async Task<IActionResult> UploadTestImages([FromForm(Name = "files")] IFormFileCollection files,
[FromForm(Name ="projectId")] Guid projectId, [FromForm(Name ="tags")] string[] tags,
[FromForm(Name = "LastTestImages")] string lastTestImages)
{
//Checking if images are more than 5
if(files.Count < 5)
{
//Change this error handling
return Ok("Image count less than 5");
}
//Checking if each tag is not empty or not an empty string
foreach(var tag in tags)
{
if (tag.Equals("") || tag.Equals(" "))
{
return Ok("Tag entry invalid");
}
}
List<string> imageUrls = await _blobService.UploadTestImages(files, projectId.ToString());
_aIService.UploadTestImages(imageUrls, tags, projectId);
if (lastTestImages != null)
return LocalRedirect("/AIModel/ModelVersions?projectId=" + projectId.ToString());
else
return LocalRedirect("/AIModel/TestImages?projectId=" + projectId.ToString());
}
// This function allows the user to train the AI model they had created by calling TrainModel AI Model service.
public IActionResult TrainModel(Guid projectId)
{
_aIService.TrainModel(projectId);
return LocalRedirect("/AIModel/ModelVersions?projectId=" + projectId.ToString());
}
// This function allows the user to publish an iteration by calling the PublishIteration AI Model service.
public IActionResult PublishIteration(Guid projectId, Guid iterationId)
{
_aIService.PublishIteration(projectId, iterationId);
return LocalRedirect("/AIModel/ModelVersions?projectId=" + projectId.ToString());
}
// This function allows the user to publish an iteration by calling the publishIteration AI Model service.
public IActionResult UnpublishIteration(Guid projectId, Guid iterationId)
{
_aIService.UnpublishIteration(projectId, iterationId);
return LocalRedirect("/AIModel/ModelVersions?projectId=" + projectId.ToString());
}
// This function allows the user to edit a model by calling the EditModel AI Model service.
public IActionResult EditModel()
{
throw new NotImplementedException();
}
// This function allows the user to delete a model by calling the DeleteModel AI Model service.
public IActionResult DeleteModel()
{
throw new NotImplementedException();
}
// This function allows the user to edit a model version by calling the EditVersion AI Model service.
public IActionResult EditVersion()
{
throw new NotImplementedException();
}
// This function allows the user to delete a model version by calling the DeleteVersion AI Model service.
public IActionResult DeleteVersion()
{
throw new NotImplementedException();
}
}
}
|
Java | UTF-8 | 307 | 2.75 | 3 | [
"Unlicense"
] | permissive | package com.github.diegopacheco.sandbox.scripts.scala.java;
public class JavaUseScalaClass {
public static void main(String[] args) {
Person p = new Person();
p.setName("Diego Pacheco");
p.setAge(26);
String toStringResult = p.toString() + " | Java add some string!";
p.show(toStringResult);
}
}
|
Java | UTF-8 | 3,750 | 1.945313 | 2 | [] | no_license | package app.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.google.gson.Gson;
import com.microservice.dao.entity.crawler.search.SearchTask;
import com.microservice.dao.repository.crawler.search.SearchTaskRepository;
import app.bean.IsDoneBean;
import app.bean.SanWangJsonBean;
import app.commontracerlog.TracerLog;
import app.service.SearchCrawlerService;
import app.service.log.SysLog;
/**
*
* 项目名称:common-microservice-search
* 类名称:aa
* 类描述:
* 创建人:hyx
* 创建时间:2018年1月17日 上午11:29:24
* @version
*/
/**
* 城市 Controller 实现 Restful HTTP 服务
* <p>
* Created by bysocket on 03/05/2017.
*/
@RestController
@Configuration
@RequestMapping("/api-service/sanwang/search")
@EnableJpaAuditing
public class NewsRestController {
@Autowired
private SearchCrawlerService searchCrawlerService;
@Autowired
private SearchTaskRepository searchTaskRepository;
@Autowired
private TracerLog tracerLog;
@Autowired
private SysLog sysLog;
private Gson gs = new Gson();
@PostMapping(path = "/task")
public IsDoneBean creatTask(@RequestBody SanWangJsonBean sanWangJsonBean) {
tracerLog.qryKeyValue("taskid", sanWangJsonBean.getTaskid());
tracerLog.output("sanWangJsonBean", gs.toJson(sanWangJsonBean));
if (null == sanWangJsonBean.getTaskid()) {
tracerLog.output("taskid is null !", "");
IsDoneBean isDoneBean = new IsDoneBean();
isDoneBean.setErrormessage("taskid is null !");
return isDoneBean;
}
if (sanWangJsonBean.getKeys().size() < 0) {
tracerLog.output("keys is null !", "");
IsDoneBean isDoneBean = new IsDoneBean();
isDoneBean.setErrormessage("keys is null !");
}
return searchCrawlerService.createTaskList(sanWangJsonBean);
}
@RequestMapping(value = "/gettask", method = RequestMethod.POST)
public List<SearchTask> getTask() {
return searchCrawlerService.getTask();
}
@GetMapping(path = "/statue/taskid")
public IsDoneBean isdone(@RequestParam(value = "taskid") String taskid) {
sysLog.output("taskid", taskid);
List<SearchTask> list = searchTaskRepository.findByTaskid(taskid);
int totalnum = list.size();
int finishednum = 0;
int crawleringnum = 0;
int errornum = 0;
IsDoneBean isDoneBean = new IsDoneBean();
isDoneBean.setTaskid(taskid);
for (SearchTask searchTask : list) {
if (searchTask.getPhase().trim() != "0") {
if (searchTask.getPhase().trim().indexOf("1") != -1) {
crawleringnum++;
}
if (searchTask.getPhase().trim().indexOf("200") != -1
|| searchTask.getPhase().trim().indexOf("404") != -1) {
finishednum++;
if (searchTask.getPhase().indexOf("404") != -1) {
errornum++;
}
}
}
}
isDoneBean.setTotalnum(totalnum);
isDoneBean.setUnfinishednum(totalnum - finishednum);
isDoneBean.setFinishednum(finishednum);
isDoneBean.setCrawleringnum(crawleringnum);
isDoneBean.setErrornum(errornum);
return isDoneBean;
}
@Scheduled(cron = "0/2 * * * * ?")
public void geterror() {
searchCrawlerService.geterror();
}
}
|
Markdown | UTF-8 | 1,471 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | ---
layout: post
title: Beta assessment
category: The HMRC Tax Platform
---
The move from Alpha phase to Beta phase in HMRC has traditionally been a move from a small private Beta to a public Beta where the number of customers able to use the service is not artifically controlled. If your transition does not fit this model then I suggest that you read the buyers guide introduction to [Alpha assessment][alpha assessment].
If you are transitioning from private beta to public beta you will find the offering much the same as the baseline for private beta but with a few more extras in terms of online support.
### Live Support
Due to the crital nature of Beta services to HMRC's users the live support level surrounding these services is higher than what you would expect from private Beta. We will always attempt to keep your service running out of hours but when you move into public Beta we can offer these extras:
* Your own team within Pagerduty allowing your team members to be contacted if your service shows an app exception
* Scripted user testing (providing you can supply the test user)
* enhanced support around key business events (tax deadlines etc...)
### Customer Support
Many services that have moved into public Beta have required an enhanced level of customer support involving additional tax specialist teams to answer queries. This can be organised with the Customer Support team.
[alpha assessment]: /buyers-guide2/Alpha%20assessment/ |
PHP | UTF-8 | 2,179 | 2.53125 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | <?php
class JxAdmin_photos_albums extends JxAdmin
{
function JxAdmin_photos_albums()
{
$this->JxAdmin();
$this->table = 'photos_albums';
$this->label = 'photos_albums';
$this->primaryKey = 'albumID';
$this->titles = array('AlbumID',
'Title',
'Description',
'UserID',
'Posted');
$this->showFields= array('albumID',
'title',
'description',
'userID',
'posted');
$this->addField(array('name' => 'albumID',
'label' => 'albumID',
'type' => 'JxFieldText',
'size' => '2',
'required' => 'true',
'value' => $_POST['albumID']));
$this->addField(array('name' => 'title',
'label' => 'title',
'type' => 'JxFieldText',
'size' => '45',
'required' => 'true',
'value' => $_POST['title']));
$this->addField(array('name' => 'description',
'label' => 'description',
'type' => 'JxFieldTextarea',
'value' => $_POST['description']));
$this->addField(array('name' => 'userID',
'label' => 'userID',
'type' => 'JxFieldText',
'size' => '9',
'required' => 'true',
'value' => $_POST['userID']));
$this->addField(array('name' => 'posted',
'label' => 'posted',
'type' => 'JxFieldText',
'size' => '11',
'required' => 'true',
'value' => $_POST['posted']));
}
function _JxAdmin_photos_albums()
{
$this->_JxAdmin();
}
}
?> |
Java | UTF-8 | 956 | 2.953125 | 3 | [] | no_license | package tw.com.ischool.oneknow.util;
import android.text.TextUtils;
public class StringUtil {
public static final String EMPTY = "";
public static final String WHITESPACE = " ";
public static Boolean isNullOrWhitespace(String string) {
if (string == null)
return true;
if (string.equalsIgnoreCase("null"))
return true;
String trimed = string.trim();
return TextUtils.isEmpty(trimed);
}
public static String getExceptionMessage(Throwable ex) {
StringBuilder sb = new StringBuilder(ex.getClass().getSimpleName())
.append(":");
if (ex.getMessage() != null) {
sb.append(ex.getMessage()).append("\n");
}
for (StackTraceElement element : ex.getStackTrace()) {
sb.append(element.toString()).append("-")
.append(element.getLineNumber()).append("\n");
}
if (ex.getCause() != null) {
String inner = getExceptionMessage(ex.getCause());
sb.append(inner);
}
sb.append("\n");
return sb.toString();
}
}
|
Shell | UTF-8 | 202 | 3.078125 | 3 | [] | no_license | #!/usr/bin/env bash
READELF=$(which readelf)
GREP=$(which egrep)
PROG=${1}
[[ -z ${READELF} || -z ${GREP} ]] && exit 1
[[ -z ${PROG} ]] && exit 2
${READELF} -s ${PROG} | ${GREP} -q "\s(_+)?mcount\b"
|
Markdown | UTF-8 | 1,222 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | Before we start we need to configure Grafana to use InfluxDB as a data source and load some dashboards. To do this run the following command by clicking on the action block below.
```terminal:execute
command: setup-grafana
```
The workshop uses these action blocks for various purposes. Anytime you see such a block with an icon on the right hand side, you can click on it and it will perform the listed action for you, you do not need to enter in the commands yourself.
To verify that Grafana is running okay, open the **Grafana** dashboard tab.
```dashboard:open-dashboard
name: Grafana
```
There is no need to login to Grafana as anonymous access is enabled for viewing Grafana dashboards.
Check that the dashboards have been loaded by selecting on **Dashboards->Manage** in Grafana.
```dashboard:reload-dashboard
name: Grafana
url: {{ingress_protocol}}://grafana-{{session_namespace}}.{{ingress_domain}}{{ingress_port_suffix}}/dashboards
```
We will also be using the embedded VS Code editor later on as well, open the **Editor** dashboard tab to warm it up.
```dashboard:open-dashboard
name: Editor
```
Finally, return back to the **Terminal** dashboard tab:
```dashboard:open-dashboard
name: Terminal
```
|
PHP | UTF-8 | 999 | 2.59375 | 3 | [
"MIT"
] | permissive | <?php
include 'conexao.php';
$nome = $_POST['txtnome'];
$email = $_POST['txtemail'];
$senha = $_POST['txtsenha'];
$cep = $_POST['txtcep'];
$num = $_POST['txtnum'];
//a variável global $_POST é usada pois o método do formulário é post.
/*
echo $nome .'<br>';
echo $email .'<br>';
echo $senha .'<br>';
echo $cep .'<br>';
echo $num . '<br>';
*/
$consulta = $con->query("select email_usu from usuario where email_usu ='$email'");
$exibe = $consulta->fetch(PDO::FETCH_ASSOC);
if($consulta->rowCount()==1){
header('location:erro_usu.php');
}
else{
$incluir = $con->query("
insert into usuario(nome_usu, email_usu, senha_usu, zap_usu, cep_usu, num_end_usu)
values('$nome','$email','$senha','0','$cep', '$num')");
header('location:usu_cadastrado.php');
//agora, a página inserir os dados no banco. Lá no MySQL, basta dar um select na tabela
//e serão visíveis os novos dados.
//as duas páginas serão criadas na próxima aula
}
?> |
C# | UTF-8 | 1,774 | 2.921875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PatternOrientedRefactoring
{
class Parser
{
public NodeFactory nodeFactory { set; get; }
public Boolean ShouldRemoveEscapeCharactor { set; get; }
}
public interface Node { }
class NodeFactory
{
public Boolean decodeStringNodes { set; get; }
public Node createStringNode(StringBuilder textBuffer, int textBegin, int textEnd)
{
if(decodeStringNodes)
return new DecodingStringNode(new StringNode(textBuffer, textBegin, textEnd));
return new StringNode(textBuffer, textBegin, textEnd);
}
public Node createStringNode(StringBuilder textBuffer, int textBegin, int textEnd, Boolean shouldDecode)
{
if (shouldDecode)
return new DecodingStringNode(new StringNode(textBuffer, textBegin, textEnd));
return new StringNode(textBuffer, textBegin, textEnd);
}
}
class StringParser
{
public Node find(StringBuilder textBuffer, int textBegin, int textEnd, bool shouldDecode)
{
Parser parser = new Parser();
NodeFactory nodeFactory = new NodeFactory();
nodeFactory.decodeStringNodes = shouldDecode;
parser.nodeFactory = nodeFactory;
return parser.nodeFactory.createStringNode(textBuffer, textBegin, textEnd);
}
}
class DecodingStringNode : Node
{
public DecodingStringNode(StringNode string_node) { }
}
class StringNode : Node
{
public StringNode(StringBuilder textBuffer, int textBegin, int textEnd)
{
}
}
}
|
C++ | WINDOWS-1250 | 4,470 | 2.625 | 3 | [
"MIT"
] | permissive | #pragma once
#define _CRT_SECURE_NO_WARNINGS
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#define STRICT
#include <Windows.h>
#include <vector>
#include <string>
#include <cassert>
#include <cstdarg>
#include <map>
#include <algorithm>
using std::vector;
using std::string;
using std::min;
using std::max;
typedef unsigned char byte;
typedef unsigned int uint;
typedef const char* cstring;
#define IS_SET(flaga,bit) (((flaga) & (bit)) != 0)
extern string g_tmp_string;
extern DWORD tmp;
extern char BUF[256];
bool LoadFileToString(cstring path, string& str);
cstring Format(cstring fmt, ...);
bool Unescape(const string& str_in, uint pos, uint length, string& str_out);
inline bool Unescape(const string& str_in, string& str_out)
{
return Unescape(str_in, 0u, str_in.length(), str_out);
}
int StringToNumber(cstring s, __int64& i, float& f);
bool DirectoryExists(cstring filename);
bool DeleteDirectory(cstring filename);
template<typename T>
inline T& Add1(vector<T>& v)
{
v.resize(v.size() + 1);
return v.back();
}
// return index of character in cstring
inline int strchr_index(cstring chrs, char c)
{
int index = 0;
do
{
if(*chrs == c)
return index;
++index;
++chrs;
} while(*chrs);
return -1;
}
// Usuwanie elementw wektora
template<typename T>
inline void DeleteElements(vector<T>& v)
{
for(vector<T>::iterator it = v.begin(), end = v.end(); it != end; ++it)
delete *it;
v.clear();
}
//-----------------------------------------------------------------------------
// kontener uywany na tymczasowe obiekty ktre s potrzebne od czasu do czasu
//-----------------------------------------------------------------------------
#ifdef _DEBUG
//# define CHECK_POOL_LEAK
#endif
template<typename T>
struct ObjectPool
{
~ObjectPool()
{
DeleteElements(pool);
#ifdef CHECK_POOL_LEAK
#endif
}
inline T* Get()
{
T* t;
if(pool.empty())
t = new T;
else
{
t = pool.back();
pool.pop_back();
}
return t;
}
inline void Free(T* t)
{
assert(t);
#ifdef CHECK_POOL_LEAK
delete t;
#else
pool.push_back(t);
#endif
}
inline void Free(vector<T*>& elems)
{
if(elems.empty())
return;
#ifdef _DEBUG
for(vector<T*>::iterator it = elems.begin(), end = elems.end(); it != end; ++it)
{
assert(*it);
#ifdef CHECK_POOL_LEAK
delete *it;
#endif
}
#endif
#ifndef CHECK_POOL_LEAK
pool.insert(pool.end(), elems.begin(), elems.end());
#endif
elems.clear();
}
private:
vector<T*> pool;
};
// tymczasowe stringi
extern ObjectPool<string> StringPool;
extern ObjectPool<vector<void*> > VectorPool;
//-----------------------------------------------------------------------------
// Lokalny string ktry wykorzystuje StringPool
//-----------------------------------------------------------------------------
struct LocalString
{
LocalString()
{
s = StringPool.Get();
s->clear();
}
LocalString(cstring str)
{
s = StringPool.Get();
*s = str;
}
LocalString(const string& str)
{
s = StringPool.Get();
*s = str;
}
~LocalString()
{
StringPool.Free(s);
}
inline void operator = (cstring str)
{
*s = str;
}
inline void operator = (const string& str)
{
*s = str;
}
inline char at_back(uint offset) const
{
assert(offset < s->size());
return s->at(s->size() - 1 - offset);
}
inline void pop(uint count)
{
assert(s->size() > count);
s->resize(s->size() - count);
}
inline void operator += (cstring str)
{
*s += str;
}
inline void operator += (const string& str)
{
*s += str;
}
inline void operator += (char c)
{
*s += c;
}
inline operator cstring() const
{
return s->c_str();
}
inline string& get_ref()
{
return *s;
}
inline string* get_ptr()
{
return s;
}
inline string* operator -> ()
{
return s;
}
inline const string* operator -> () const
{
return s;
}
inline bool operator == (cstring str) const
{
return *s == str;
}
inline bool operator == (const string& str) const
{
return *s == str;
}
inline bool operator == (const LocalString& str) const
{
return *s == *str.s;
}
inline bool operator != (cstring str) const
{
return *s != str;
}
inline bool operator != (const string& str) const
{
return *s != str;
}
inline bool operator != (const LocalString& str) const
{
return *s != *str.s;
}
inline bool empty() const
{
return s->empty();
}
inline cstring c_str() const
{
return s->c_str();
}
inline void clear()
{
s->clear();
}
private:
string* s;
};
|
Python | UTF-8 | 1,009 | 2.5625 | 3 | [] | no_license | import shutil
import os
import sys
def install_qt_menu_nib():
# For Qt to work on Mac, we need to put the qt_menu.nib directory
# at the appropriate location..
#path_src = '/opt/local/Library/Frameworks/QtGui.framework/Versions/4/Resources/qt_menu.nib'
path_src = None
# Get .nib dir in a smart way. Taken from cx_Freeze
from PySide import QtCore
lpath = QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.LibrariesPath)
for subpath in ['QtGui.framework/Resources', 'Resources']:
path = os.path.join(lpath, subpath, 'qt_menu.nib')
if os.path.exists(path):
path_src = path
break
# Copy the directory!
if path_src:
path_dst = sys.prefix + '/lib/Contents/Resources/qt_menu.nib'
shutil.copytree(path_src, path_dst)
else:
raise RuntimeError('Could not find qt_menu.nib')
if __name__ == '__main__':
install_qt_menu_nib()
|
Python | UTF-8 | 10,486 | 3.296875 | 3 | [] | no_license | import math
from scipy.integrate import quad
from matplotlib import pyplot as plt
import numpy as np
f = open("20103082.txt", "r")
f_out = open("20103082_output","w+")
def estimate_parameters(pdf , data):
n = len(data)
if pdf == "Normal":
# by method of Maximum Likelihood
# calculate estimated paramters
sum_x = 0
for i in range(0,n):
sum_x += data[i]
estimated_mean = (1.0 * sum_x/n)
squared_sum = 0
for i in range(0,n):
squared_sum += math.pow((data[i] - estimated_mean),2)
estimated_variance = (1.0*squared_sum/(n-1))
estimated_stddev = math.sqrt(estimated_variance)
return [estimated_mean,estimated_stddev]
if pdf == "Chi-Square":
#Dof = k - 1 - m
# k = 2 * sqrt(n) . To get the no. of bins
# m = 1 for nu(Parameter for Chi-Square.
k = 2 * math.sqrt(n)
return k - 1 - 1
if pdf == "Exponential":
#By using method of Max. Likelihood
lamda = 1.0 * n / sum(data)
return lamda
def confidence_interval(distribution, data, *params):
#we have to calculate for 90% CI.
n = len(data)
if distribution == "Normal":
#Population variance is not known
#1. Calculate sample mean
#2. Calculate S^2
X_bar = 1.0 * sum(data)/n
squared_sum = 0
for i in range(0,n):
squared_sum += math.pow((data[i] - X_bar),2)
S_square = 1.0 * squared_sum/(n-1)
sample_stddev = math.sqrt(S_square)
##Calculate the CI using formula [ X_bar - t(n-1,alpha/2) * S/sqrt(n) , X_bar - t(n-1,alpha/2) * S/sqrt(n) ]
## Value of t(100,5%) from T-distribution table = 1.66
low_mean = X_bar - 1.66 * sample_stddev/math.sqrt(n)
high_mean = X_bar + 1.66 * sample_stddev/math.sqrt(n)
## CI for Variance
## Population mean is not known
## 1.We get the CI using formula [ (n-1) * S^2 / Cu , (n-1) * S^2 / Cl ]
## For the Interval Estimation we use the Chi square dist. table.
## Cu = 123 and Cl = 76 for dof = 99 and alpha/2 = 0.05 and 0.95 respectively.
Cu = 123
Cl = 76
low_stddev = math.sqrt((n - 1) * S_square/Cu)
high_stddev = math.sqrt((n - 1) * S_square/Cl)
return [[low_mean,high_mean],[low_stddev,high_stddev]]
if distribution == "Chi-Square":
## 2*dof = std. deviation
## Estimating the CI for std deviation and from that we can estimate CI for dof.
## CI for VARIANCE = [(n-1)*S^2/Chi-Square(alpha/2) ,(n-1)*S^2/Chi-Square(alpha/2) ]
## alpha/2 = 0.05
dof = params[0]
sample_mean = sum(data)/n
print "Value of Chi-Square dist for dof = {} for alpha = {} and {} \n is {} {} respectively".format(dof,0.05,0.95, 27.587, 8.672)
squared_sum = 0
for i in range(0,n):
squared_sum += math.pow((data[i] - sample_mean),2)
S_square = 1.0 * squared_sum/(n-1)
low_variance = 1.0 * (n - 1) * S_square / 27.587
high_variance = 1.0 * (n - 1) * S_square / 8.672
return [low_variance, high_variance]
if distribution == "Exponential":
## To Calculate the CI for the Exponential Distribution
## As mean = 1/lamda
## we use formula [1/X_bar (1 - Z(alpha/2)/sqrt(n)), 1/X_bar (1 + Z(alpha/2)/sqrt(n)) ]
## Z(alpha/2) = 1.645 for alpha = 90%
sample_mean = sum(data)/n
low_lambda = 1/sample_mean * (1 - 1.645/ math.sqrt(n))
high_lambda = 1/sample_mean * (1 + 1.645/ math.sqrt(n))
return [low_lambda,high_lambda]
def hypothesis_testing(data, mean = -1 , variance = 0):
n = len(data)
#H0 => mu = mu_0 = 2500
#HA => mu != mu_0
mu_0 = 2500
#(5% significance level)
significance_level = 5
if variance == 0:
#Compute Test Statistic using T-Distribution
#Population Variance is not known
sample_mean = sum(data)/n
squared_sum = 0
for i in range(0,n):
squared_sum += math.pow((data[i] - sample_mean),2)
S_square = 1.0 * squared_sum/(n-1)
sample_stddev = math.sqrt(S_square)
#Test Statistic
T = 1.0 * (sample_mean - mu_0)/(1.0 * sample_stddev/math.sqrt(n))
print "Test Statistic for Hypothesis Testing that mean discharge = 2500 is {}".format(T)
f_out.write("Test Statistic for Hypothesis Testing that mean discharge = 2500 is {}".format(T))
#For significance level 5 we have to check between
# range -1.987 to 1.987 for dof = n - 1 = 99
if T < 1.987 and T > -1.987:
return ["H0 cannot be rejected",1]
else:
return ["H0 can be rejected",0]
data1 = []
data2 = []
data3 = []
data4 = []
header = f.readline()
while True:
line = f.readline()
if len(line) != 0:
val = line.split()
data1.append(float(val[0]))
data2.append(float(val[1]))
data3.append(float(val[2]))
data4.append(float(val[3]))
else:
break
print("###########################################################################")
print("######################## For DATA SITE 1 ##################################")
print("###########################################################################")
f_out.write("###########################################################################\n")
f_out.write("######################## For DATA SITE 1 ##################################\n")
f_out.write("###########################################################################\n")
#Assuming the above distribution to be Normal using Histogram
#1. P(X > x_k) = 0.01 ,so P(X < x_k) = 0.99
#2. P(Z < (x_k - mean)/variance) = 0.99
#3a. According to Std. Normal Distribution table
#3b. (x_k - mean)/std_dev = 2.33
# Estimate the Paramters.
[est_mean,est_stddev] = estimate_parameters("Normal",data1)
print "est_mean = {}".format(est_mean)
print "est_stddev = {}".format(est_stddev)
f_out.write("est_mean = {}\n".format(est_mean))
f_out.write("est_stddev = {}\n".format(est_stddev))
#Rearranging the eqn (x_k - mean)/stddev = 2.33 from #3b
# we get x_k = 2.33 * std_dev + mean
x_k = 2.33 * est_stddev + est_mean
print "Value of x_k = {}".format(x_k)
f_out.write("Value of x_k = {}\n".format(x_k))
[mean_interval, variance_interval] = confidence_interval("Normal", data1)
print "mean_interval = {}".format(mean_interval)
print "variance_interval = {}".format(variance_interval)
f_out.write("90 % CI for mean = {}\n".format(mean_interval))
f_out.write("90 % CI for variance = {}\n".format(variance_interval))
H0 = "mu = mu_0 = 2500"
HA = "mu != mu_0"
res = hypothesis_testing(data1)
if res[1] == 1:
f_out.write("{} {}\n".format(H0,res[0]))
else:
f_out.write("{} {}\n".format(HA,res[0]))
f_out.write('\n')
print("###########################################################################")
print("######################## For DATA SITE 2 ##################################")
print("###########################################################################")
f_out.write("###########################################################################\n")
f_out.write("######################## For DATA SITE 2 #################################\n")
f_out.write("###########################################################################\n")
# Estimate the Paramters.
[est_mean,est_stddev] = estimate_parameters("Normal",data2)
print "est_mean = {}".format(est_mean)
print "est_stddev = {}".format(est_stddev)
f_out.write("estimated mean = {}\n".format(est_mean))
f_out.write("estimated standard deviation = {}\n".format(est_stddev))
#Rearranging the eqn (x_k - mean)/variance = 2.33 from #3b
# we get x_k = 2.33 * est_stddev + est_mean
x_k = 2.33 * est_stddev + est_mean
print "Value of x_k = {}".format(x_k)
f_out.write("Value of x_k = {}\n".format(x_k))
[mean_interval, variance_interval] = confidence_interval("Normal", data2)
print "mean_interval = {}".format(mean_interval)
print "variance_interval = {}".format(variance_interval)
f_out.write("90 % CI for mean = {}\n".format(mean_interval))
f_out.write("90 % CI for variance = {}\n".format(variance_interval))
res = hypothesis_testing(data2)
if res[1] == 1:
f_out.write("{} {}\n".format(H0,res[0]))
else:
f_out.write("{} {}\n".format(HA,res[0]))
f_out.write('\n')
print("###########################################################################")
print("######################## For DATA SITE 3 ##################################")
print("###########################################################################")
f_out.write("###########################################################################\n")
f_out.write("######################## For DATA SITE3 #################################\n")
f_out.write("###########################################################################\n")
dof = estimate_parameters("Chi-Square",data3)
print "Degree of freedom = {}".format(dof)
f_out.write("Degree of freedom = {}\n".format(dof))
variance_interval = confidence_interval("Chi-Square", data3,dof)
stddev_interval = [math.sqrt(variance_interval[0]), math.sqrt(variance_interval[1])]
print "Confidence Interval for Std dev = {} ".format(stddev_interval)
f_out.write("Confidence Interval for Std dev = {} \n".format(stddev_interval))
f_out.write('\n')
print("###########################################################################")
print("######################## For DATA SITE 4 ##################################")
print("###########################################################################")
f_out.write("###########################################################################\n")
f_out.write("######################## For DATA SITE 4 #################################\n")
f_out.write("###########################################################################\n")
#Estimate the Paramters.
lamda = estimate_parameters("Exponential",data4)
print "lambda = {}\n".format(lamda)
f_out.write("lambda = {}\n".format(lamda))
lambda_interval = confidence_interval("Exponential", data4)
print "Confidence Interval for Lambda = {}".format(lambda_interval)
f_out.write("90 % Confidence Interval for Lambda = {}\n".format(lambda_interval))
######################################
######## Calculate x_k ###############
######################################
## Getting the Value of x_k by integrating the distibution
## function in interval 0 to x_k and equating with 0.99
## Got the Value of x_k from Matlab Code(Snippet Pasted in Report)
x_k = 11050
print "x_k value obtained by using matlab code(Snipped Pasted) for integration"
print "Value of x_k = {}".format(x_k)
f_out.write("Value of x_k = {}\n".format(x_k))
res = hypothesis_testing(data4)
if res[1] == 1:
f_out.write("{} {}\n".format(H0,res[0]))
else:
f_out.write("{} {}\n".format(HA,res[0]))
|
JavaScript | UTF-8 | 1,219 | 2.796875 | 3 | [] | no_license | const linksSocialMedia = {
github: "SandroJuniorr",
instagram: "sandrorogeriojunior",
facebook: "maykbrito",
youtube: "Rocketseat",
twitter: "Rocketseat",
};
function changeSocialMediasLinks() {
for (let li of socialLinks.children) {
const social = li.getAttribute("class");
li.children[0].href = `https://${social}.com/${linksSocialMedia[social]}`;
}
}
changeSocialMediasLinks();
function getGitHubProfileInfos(){
const url = `https://api.github.com/users/${linksSocialMedia.github}`
fetch(url)
.then(response => response.json())
.then(data => {
userName.textContent = data.name;
userLink.href = data.html_url
userBio.textContent = data.bio
userPicture.src = data.avatar_url
userLogin.textContent = data.login
})
}
getGitHubProfileInfos()
putEventLI()
function putEventLI() {
for (let li of socialLinks.children){
li.addEventListener("mouseover", ()=>{
let social = li.getAttribute("class")
li.children[0].children[0].src = `assets/${social}-hover.png`
})
li.addEventListener("mouseout", ()=>{
let social = li.getAttribute("class")
li.children[0].children[0].src = `assets/${social}.svg`
})
}
};
|
C | UTF-8 | 7,169 | 2.9375 | 3 | [] | no_license | #include "Evolution.h"
#include "Snake.h"
#include "random.h"
#include <stdlib.h>
#include <math.h>
static void randomInitializer(Matrix matrix, void* ctx) {
for(matrix_index_t i = 0; i < matrix->size; i++) {
matrix->values[i] = 2.0 * randomFloat() - 1.0;
}
}
static Network makeRandomNetwork(Evolution self) {
Network network = networkCreate();
networkAddLayer(network, (NetworkLayerParams){
.inputSize = 3 * self->params.snakeRaysCount,
.units = self->params.networkUnitsCount,
.activation = self->params.networkActivation,
.initializer = randomInitializer
});
for(size_t i = 0; i < self->params.networkHiddenLayersCount; i++) {
networkAddLayer(network, (NetworkLayerParams){
.units = self->params.networkUnitsCount,
.activation = self->params.networkActivation,
.initializer = randomInitializer
});
}
networkAddLayer(network, (NetworkLayerParams){
.units = 4,
.activation = ActivationFunctions.softmax,
.initializer = randomInitializer
});
networkCompile(network);
return network;
}
static matrix_index_t getMaxIndex(Matrix matrix) {
matrix_index_t maxIndex = 0;
for(matrix_index_t i = 1; i < matrix->size; i++) {
if(matrix->values[i] > matrix->values[maxIndex]) {
maxIndex = i;
}
}
return maxIndex;
}
static float evaluate(Evolution self, Network network) {
Snake snake = snakeCreate(self->params.snakeBoardSize, self->params.snakeRaysCount);
size_t length = 1;
size_t life = 100;
size_t ticks = 0;
long r;
while(life > 0) {
life -= 1;
ticks += 1;
Matrix distanceMatrix = snakeCalcDistanceMatrix(snake);
Matrix output = networkFit(network, distanceMatrix);
SnakeDirection direction = getMaxIndex(output);
matrixDelete(distanceMatrix);
matrixDelete(output);
if((r = snakeMove(snake, direction)) >= 0) {
if(snake->body->size > length) {
life = 100;
length = snake->body->size;
}
}
else {
break;
}
}
snakeDelete(snake);
return (powf(length, 1.5) - (float)ticks / 100.0); // * (r == -1 ? 0.75 : 1.0);
}
static float evaluateAvg(Evolution self, Network network) {
float score = 0.0;
for(int i = 0; i < 5; i++) {
score += evaluate(self, network);
}
return score / 5;
}
Evolution evolutionCreate(EvolutionParams params) {
Evolution self = malloc(sizeof(struct Evolution));
self->params = params;
self->bestIndex = 0;
self->population = malloc(params.populationSize * sizeof(Chromosome));
return self;
}
void evolutionDelete(Evolution self) {
for(size_t i = 0; i < self->params.populationSize; i++) {
networkDelete(self->population[i].network);
}
free(self->population);
free(self);
}
void evolutionInit(Evolution self) {
for(size_t i = 0; i < self->params.populationSize; i++) {
self->population[i].network = makeRandomNetwork(self);
self->population[i].score = evaluateAvg(self, self->population[i].network);
if(self->population[i].score > self->population[self->bestIndex].score) {
self->bestIndex = i;
}
}
}
static Matrix crossMatrices(Matrix a, Matrix b) {
for(matrix_index_t i = 0; i < a->size; i++) {
a->values[i] = randomFloat() < 0.5 ? a->values[i] : b->values[i];
}
return a;
}
static Matrix normalizeMatrix(Matrix a) {
matrix_number_t max = 0.0;
for(matrix_index_t i = 0; i < a->size; i++) {
if(a->values[i] > max) {
max = fabsf(a->values[i]);
}
}
if(max > 1.0) {
for(matrix_index_t i = 0; i < a->size; i++) {
a->values[i] = a->values[i] / max;
}
}
return a;
}
void evolutionNextGeneration(Evolution self) {
Chromosome* newPopulation = malloc(self->params.populationSize * sizeof(Chromosome));
Chromosome* best = &self->population[self->bestIndex];
size_t newBestIndex = 0;
for(size_t i = 0; i < self->params.populationSize; i++) {
Network m = networkCreate();
Chromosome* a = &self->population[randomInt(0, self->params.populationSize - 1)];
Chromosome* b = &self->population[randomInt(0, self->params.populationSize - 1)];
if(self->params.chooseBest == false) {
best = &self->population[randomInt(0, self->params.populationSize - 1)];
}
ListIterator p = listGetIterator(best->network->layers);
ListIterator q = listGetIterator(a->network->layers);
ListIterator r = listGetIterator(b->network->layers);
while(p.present) {
NetworkLayer pl = p.value;
NetworkLayer ql = q.value;
NetworkLayer rl = r.value;
Matrix weights = matrixSubstract(rl->weights, ql->weights);
Matrix bias = matrixSubstract(rl->bias, ql->bias);
matrixMultiplyInPlace(weights, self->params.f);
matrixMultiplyInPlace(bias, self->params.f);
matrixAddInPlace(weights, pl->weights);
matrixAddInPlace(bias, pl->bias);
crossMatrices(weights, pl->weights);
crossMatrices(bias, pl->bias);
if(self->params.normalizeMatrices) {
normalizeMatrix(weights);
normalizeMatrix(bias);
}
networkAddLayer(m, (NetworkLayerParams){
.weights = weights,
.bias = bias,
.activation = pl->activation
});
listIteratorNext(&p);
listIteratorNext(&q);
listIteratorNext(&r);
}
networkCompile(m);
const float score = evaluateAvg(self, m);
if(score > self->population[i].score) {
newPopulation[i].network = m;
newPopulation[i].score = score;
}
else {
networkDelete(m);
newPopulation[i].network = networkCopy(self->population[i].network);
newPopulation[i].score = self->population[i].score;
}
if(newPopulation[i].score > newPopulation[newBestIndex].score) {
newBestIndex = i;
}
}
for(size_t i = 0; i < self->params.populationSize; i++) {
networkDelete(self->population[i].network);
}
free(self->population);
self->population = newPopulation;
self->bestIndex = newBestIndex;
}
float evolutionGetBestScore(Evolution self) {
return self->population[self->bestIndex].score;
}
Network evolutionGetBestNetwork(Evolution self) {
return self->population[self->bestIndex].network;
}
Evolution jsEvolutionCreate(void) {
return evolutionCreate((EvolutionParams){
.populationSize = 100,
.snakeBoardSize = 15,
.snakeRaysCount = 4,
.networkHiddenLayersCount = 0,
.networkUnitsCount = 32,
.networkActivation = ActivationFunctions.leakyRelu,
.f = 0.5,
.normalizeMatrices = true,
.chooseBest = false
});
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.