code
stringlengths 0
29.6k
| language
stringclasses 9
values | AST_depth
int64 3
30
| alphanumeric_fraction
float64 0.2
0.86
| max_line_length
int64 13
399
| avg_line_length
float64 5.02
139
| num_lines
int64 7
299
| source
stringclasses 4
values |
---|---|---|---|---|---|---|---|
package com.icss.snacks.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.icss.snacks.entity.Category;
import com.icss.snacks.util.DbFactory;
/**
*
* @author zly
*
*/
public class CategoryDao {
/**
*
* @param category
* @return row
* @throws Exception
*/
public Integer add(Category category) throws Exception {
Integer row = 0;
// 1. 连接数据库
Connection connection = DbFactory.openConnection();
// 2. 编写SQL语句 添加语句 "INSERT "
String sql = "INSERT INTO tb_category(category_parentid, name) VALUE(?, ?)";
// 3. 创建执行SQL对象
PreparedStatement ps = connection.prepareStatement(sql);
// 4. 设置占位符的值
ps.setInt(1, category.getCategory_parentid());
ps.setString(2, category.getName());
// 5. 执行SQL返回受影响的行数
row = ps.executeUpdate();
// 6. 释放资源
ps.close();
return row;
}
/**
*
* @param category_id
* @return row
* @throws Exception
*/
public Integer delete(Integer category_id) throws Exception {
Integer row = 0;
// 1. 连接数据库
Connection connection = DbFactory.openConnection();
// 2. 编写SQL语句
String sql = "DELETE FROM tb_category WHERE category_id = ?";
// 3. 创建执行SQL对象
PreparedStatement ps = connection.prepareStatement(sql);
// 4. 设置占位符的值
ps.setInt(1, category_id);
// 5. 执行SQL返回受影响的行数
row = ps.executeUpdate();
// 6. 释放资源
ps.close();
return row;
}
/**
*
* @param category
* @return row
* @throws Exception
*/
public Integer update(Category category) throws Exception {
Integer row = 0;
// 1. 连接数据库
Connection connection = DbFactory.openConnection();
// 2. 编写SQL语句
String sql = "UPDATE tb_category SET category_parentid = ?, name = ? WHERE category_id = ?";
// 3. 创建执行SQL对象
PreparedStatement ps = connection.prepareStatement(sql);
// 4. 设置占位符的值
ps.setInt(1, category.getCategory_parentid());
ps.setString(2, category.getName());
ps.setInt(3, category.getCategory_id());
// 5. 执行SQL返回受影响的行数
row = ps.executeUpdate();
// 6. 释放资源
ps.close();
return row;
}
/**
*
* @param category_id
* @return category
* @throws Exception
*/
public Category findByCategoryid(Integer category_id) throws Exception {
Category category = null;
// 1. 连接数据库
Connection connection = DbFactory.openConnection();
// 2. 编写SQL语句
String sql = "SELECT * FROM tb_category WHERE category_id=?";
// 3. 创建执行SQL对象
PreparedStatement ps = connection.prepareStatement(sql);
// 4. 设置占位符的值
ps.setInt(1, category_id);
// 5. 执行SQL,返回结果集
ResultSet rs = ps.executeQuery();
// 6. 将结果集中数据提取到对象属性中
if(rs.next()) {
category = new Category();
category.setCategory_id(rs.getInt("category_id"));
category.setCategory_parentid(rs.getInt("category_parentid"));
category.setName(rs.getString("name"));
}
// 7. 释放资源
rs.close();
ps.close();
return category;
}
public int findBrandIdByBrandName(String category_name) throws Exception{
/**
* 查询用户详情
*/
Category category = null;
//1.连接数据库
Connection connection = DbFactory.openConnection();
//2.编写sql语句 添加语句
String sql = "select * from tb_category where name like ?";
//3.创建执行sql的对象
PreparedStatement ps = connection.prepareStatement(sql);
//4.设置占位符的值
ps.setString(1, category_name);
//5.执行sql,返回结果集
ResultSet rs = ps.executeQuery();
//6.将结果集中数据提取到对象的属性中
if(rs.next()) {
category = new Category();
category.setCategory_id(rs.getInt("category_id"));
category.setCategory_parentid(rs.getInt("category_parentid"));
category.setName(rs.getString("name"));
}
//6.释放资源
rs.close();
ps.close();
return category.getCategory_id();
}
/**
*
* @return categoryList
* @throws Exception
*/
public List findAll() throws Exception {
List categoryList = new ArrayList
// 1. 连接数据库
Connection connection = DbFactory.openConnection();
// 2. 编写SQL语句
String sql = "SELECT * FROM tb_category";
// 3. 创建执行SQL对象,添加到集合中
PreparedStatement ps = connection.prepareStatement(sql);
// 4. 执行SQL,返回结果集
ResultSet rs = ps.executeQuery();
// 5. 循环后去用户对象,添加到集合中
while (rs.next()) {
Category category = new Category();
category.setCategory_id(rs.getInt("category_id"));
category.setCategory_parentid(rs.getInt("category_parentid"));
category.setName(rs.getString("name"));
categoryList.add(category);
}
// 6. 释放资源
rs.close();
ps.close();
return categoryList;
}
/**
*
* @return count
* @throws Exception
*/
public Integer findCount() throws Exception {
Integer count = 0;
// 1. 连接数据库
Connection connection = DbFactory.openConnection();
// 2. 编写SQL语句
String sql = "SELECT COUNT(*) FROM tb_category";
// 3. 创建执行SQL对象,添加到集合中
PreparedStatement ps = connection.prepareStatement(sql);
// 4. 执行SQL,返回结果集
ResultSet rs = ps.executeQuery();
// 5. 循环后去用户对象,添加到集合中
if (rs.next()) {
count = rs.getInt(1);
}
// 6. 释放资源
rs.close();
ps.close();
return count;
}
public List findByParentId(Integer parent_id) throws Exception {
List categoryList = new ArrayList
// 1. 连接数据库
Connection connection = DbFactory.openConnection();
// 2. 编写SQL语句
String sql = "SELECT * FROM tb_category WHERE category_parentid = ?";
// 3. 创建执行SQL对象,添加到集合中
PreparedStatement ps = connection.prepareStatement(sql);
// 4. 设置占位符的值
ps.setInt(1, parent_id);
// 5. 执行SQL,返回结果集
ResultSet rs = ps.executeQuery();
// 6. 循环后去用户对象,添加到集合中
while (rs.next()) {
Category category = new Category();
category.setCategory_id(rs.getInt("category_id"));
category.setCategory_parentid(rs.getInt("category_parentid"));
category.setName(rs.getString("name"));
categoryList.add(category);
}
rs.close();
ps.close();
return categoryList;
}
public List findCategoryListByBrandId(int brand_id) throws Exception {
List categoryList = new ArrayList
Connection connection = DbFactory.openConnection();
String sql = "SELECT DISTINCT" +
" category.*" +
" FROM" +
" `tb_brand` b" +
" INNER JOIN `tb_commodity` commodity ON commodity.brand_id = b.brand_id" +
" INNER JOIN `tb_category` category ON category.category_id = commodity.category_id AND category.category_parentid = 0" +
" WHERE" +
" b.brand_id = ?;";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setInt(1, brand_id);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Category category = new Category();
category.setCategory_id(rs.getInt("category_id"));
category.setCategory_parentid(rs.getInt("category_parentid"));
category.setName(rs.getString("name"));
categoryList.add(category);
}
rs.close();
ps.close();
return categoryList;
}
}
|
java
| 15 | 0.674083 | 125 | 25.306202 | 258 |
starcoderdata
|
public class MascotaSimple{
private int edad = 8;
private String nombre;
public MascotaSimple(){
this.nombre= "Kitty";
}
public MascotaSimple(String nombre){
this.nombre= nombre;
}
public MascotaSimple(String nombre, int edad){
this.nombre= nombre;
this.edad = edad;
}
public String getNombre(){
return this.nombre;
}
public int getEdad(){
return this.edad;
}
}
|
java
| 8 | 0.557377 | 50 | 17.769231 | 26 |
starcoderdata
|
@Override
public ScoredDocuments rerank(ScoredDocuments docs, RerankerContext<Integer> context) {
Document[] documents = docs.documents;
IndexReader reader = context.getIndexSearcher().getIndexReader();
int qid = context.getQueryId();
LOG.info("Beginning rerank");
for (int i =0; i < docs.documents.length; i++ ) {
try {
Terms terms = reader.getTermVector(docs.ids[i], LuceneDocumentGenerator.FIELD_BODY);
float[] features = this.extractorChain.extractAll(documents[i], terms, context);
String docId = documents[i].get(LuceneDocumentGenerator.FIELD_ID);
// QREL 0 in this case, will be assigned if needed later
//qid
BaseFeatureExtractor.writeFeatureVector(out, qid, this.qrels.getRelevanceGrade(qid, docId), docId, features);
LOG.info("Finished writing similarityPair");
} catch (IOException e) {
LOG.error(String.format("IOExecption trying to retrieve feature vector for %d doc", docs.ids[i]));
continue;
}
}
// Does nothing to the actual docs, we just need to extract the feature vector
return docs;
}
|
java
| 15 | 0.683466 | 118 | 48.217391 | 23 |
inline
|
// Text stuff.
#include
typedef struct text_column {
byte data[8];
} text_column;
typedef struct text {
// Length of the buffer in columns.
// Each column is 8 bytes.
int len;
text_column* buffer;
} text;
// Gets the lightness of a given pixel.
// Font is 8px tall at max. Proportional.
byte text_point(text* rendered, int x, int y);
// Renders text.
// Returns heap allocated pointer or NULL if something failed.
text* text_render(const char* txt);
// Frees rendered text. Do it. Don't forget to, leaks a bad, mmkay?
// Does nothing if called with NULL.
void text_free(text* rendered);
|
c
| 7 | 0.707438 | 67 | 25.304348 | 23 |
starcoderdata
|
def wfile(self, fname, name, inputd):
""" The user enters some details which is written in the file.
It provides a user to write the contents in the file.
"""
# The function is used to write inside a file.
self.fns = name
self.fname = f"{fname}\\"
self.input = inputd
self.iuytr = False
try:
self.pm = os.path.join(self.pthh, self.fname)
self.path = os.path.join(self.pm, self.fns)
# print(self.path)
with open(self.path, 'w') as iuy:
iuy.write(self.input)
self.iuytr = True
except Exception as error:
print(error)
finally:
return self.iuytr
|
python
| 12 | 0.521277 | 70 | 35.7 | 20 |
inline
|
package deployfile
import (
"bytes"
"crypto/md5"
"crypto/sha1"
"encoding/hex"
"fmt"
"hash"
"io"
"net/http"
"net/url"
"os"
"github.com/jcmturner/gomvn/metadata"
"github.com/jcmturner/gomvn/pom"
"github.com/jcmturner/gomvn/repo"
)
func Upload(repoURL, groupID, artifactID, packaging, version, file, username, password string, cl *http.Client) ([]*url.URL, error) {
var uploaded []*url.URL
if cl == nil {
cl = http.DefaultClient
}
groupURL, versionURL, fileName := repo.ParseCoordinates(repoURL, groupID, artifactID, packaging, version)
// open readers of the artifact
f, err := os.Open(file)
if err != nil {
return uploaded, fmt.Errorf("could not open artifact file: %v", err)
}
defer f.Close()
rw := new(bytes.Buffer)
t := io.TeeReader(f, rw)
// PUT the artifact
u, err := url.Parse(versionURL + fileName)
if err != nil {
return uploaded, fmt.Errorf("target URL for artifact not avlid: %v", err)
}
req, err := http.NewRequest("PUT", u.String(), t)
if err != nil {
return uploaded, fmt.Errorf("could not create upload request for the artifact")
}
req.SetBasicAuth(username, password)
resp, err := cl.Do(req)
if err != nil {
return uploaded, fmt.Errorf("error uploading the artifact: %v", err)
}
if resp.StatusCode != http.StatusCreated {
return uploaded, fmt.Errorf("return code when uploading the artifact %d", resp.StatusCode)
}
uploaded = append(uploaded, u)
// PUT artifact hash files
us, err := uploadHashFiles(rw, versionURL, fileName, username, password, cl)
if err != nil {
return uploaded, err
}
uploaded = append(uploaded, us...)
// PUT POM
p := pom.New(groupID, artifactID, version, packaging)
pb, err := p.Marshal()
if err != nil {
return uploaded, fmt.Errorf("error marshaling pom: %v", err)
}
purl, err := pom.URL(repoURL, groupID, artifactID, version)
if err != nil {
return uploaded, fmt.Errorf("URL for POM not valid: %v", err)
}
prw := new(bytes.Buffer)
pt := io.TeeReader(bytes.NewReader(pb), prw)
req, err = http.NewRequest("PUT", purl.String(), pt)
if err != nil {
return uploaded, fmt.Errorf("could not create upload request for %s : %v", purl.String(), err)
}
req.SetBasicAuth(username, password)
resp, err = cl.Do(req)
if err != nil {
return uploaded, fmt.Errorf("error uploading %s : %v", purl.String(), err)
}
if resp.StatusCode != http.StatusCreated {
return uploaded, fmt.Errorf("uploading %s: return code %d", purl.String(), resp.StatusCode)
}
uploaded = append(uploaded, purl)
// PUT POM hash files
pomName := fmt.Sprintf("%s-%s.pom", artifactID, version)
us, err = uploadHashFiles(prw, versionURL, pomName, username, password, cl)
if err != nil {
return uploaded, fmt.Errorf("error uploading pom hash files: %v", err)
}
uploaded = append(uploaded, us...)
// Generate and PUT metadata
md, err := metadata.Generate(repoURL, groupID, artifactID, version, cl)
if err != nil {
return uploaded, fmt.Errorf("error updating metadata: %v", err)
}
mdb, err := md.Marshal()
if err != nil {
return uploaded, fmt.Errorf("error marshaling metadata: %v", err)
}
mdPath := fmt.Sprintf("%s%s/%s", groupURL, artifactID, metadata.MavenMetadataFile)
murl, err := url.Parse(mdPath)
if err != nil {
return uploaded, fmt.Errorf("URL for metadata not valid: %v", err)
}
mdrw := new(bytes.Buffer)
mdt := io.TeeReader(bytes.NewReader(mdb), mdrw)
req, err = http.NewRequest("PUT", murl.String(), mdt)
if err != nil {
return uploaded, fmt.Errorf("could not create upload request for %s : %v", mdPath, err)
}
req.SetBasicAuth(username, password)
resp, err = cl.Do(req)
if err != nil {
return uploaded, fmt.Errorf("error uploading %s : %v", mdPath, err)
}
if resp.StatusCode != http.StatusCreated {
return uploaded, fmt.Errorf("uploading %s: return code %d", mdPath, resp.StatusCode)
}
uploaded = append(uploaded, murl)
// PUT metadata hash files
mdPath = fmt.Sprintf("%s%s/", groupURL, artifactID)
us, err = uploadHashFiles(mdrw, mdPath, metadata.MavenMetadataFile, username, password, cl)
if err != nil {
return uploaded, fmt.Errorf("error uploading metadata hash files: %v", err)
}
uploaded = append(uploaded, us...)
return uploaded, nil
}
func uploadHashFiles(r io.Reader, locationURL, filename, username, password string, cl *http.Client) ([]*url.URL, error) {
var uploaded []*url.URL
if cl == nil {
cl = http.DefaultClient
}
hs := []struct {
suffix string
hash hash.Hash
}{
{"sha1", sha1.New()},
{"md5", md5.New()},
//{"sha256", sha256.New()},
}
// Create a chain of readers to use as each is read to upload
readers := make([]*bytes.Buffer, len(hs)-1)
t := r
for i := 1; i < len(hs); i++ {
rw := new(bytes.Buffer)
t = io.TeeReader(t, rw)
readers[len(readers)-i] = rw
}
for i, h := range hs {
turl := locationURL + filename + "." + h.suffix
req, err := hashPutRequest(t, h.hash, turl, username, password)
if err != nil {
return uploaded, fmt.Errorf("could not generate request to put %s : %v", turl, err)
}
resp, err := cl.Do(req)
if err != nil {
return uploaded, fmt.Errorf("error uploading %s : %v", turl, err)
}
if resp.StatusCode != http.StatusCreated {
return uploaded, fmt.Errorf("uploading %s: return code %d", turl, resp.StatusCode)
}
u, err := url.Parse(turl)
if err == nil {
uploaded = append(uploaded, u)
}
if i < len(readers) {
t = readers[i]
}
}
return uploaded, nil
}
func hashPutRequest(f io.Reader, h hash.Hash, targetURL, username, password string) (*http.Request, error) {
_, err := io.Copy(h, f)
if err != nil {
return nil, err
}
hashb := h.Sum(nil)
hexb := make([]byte, hex.EncodedLen(len(hashb)))
hex.Encode(hexb, hashb)
req, err := http.NewRequest("PUT", targetURL, bytes.NewReader(hexb))
if err != nil {
return req, err
}
req.SetBasicAuth(username, password)
return req, nil
}
|
go
| 12 | 0.667693 | 133 | 29.4375 | 192 |
starcoderdata
|
/****************************************************************************//*
* Copyright (C) 2021
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom
* the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
******************************************************************************/
#ifndef FDM_WINCHLAUNCHER_H
#define FDM_WINCHLAUNCHER_H
////////////////////////////////////////////////////////////////////////////////
#include
#include
////////////////////////////////////////////////////////////////////////////////
namespace fdm
{
/**
* @brief Sailplane winch launcher class.
*
* XML configuration file format:
* @code
*
* { [m] x-coordinate } { [m] y-coordinate } { [m] z-coordinate }
* { [N] maximum cable force }
* { [m] maximum cable length }
* { [rad] maximum cable angle }
* { [m/s] maximum cable velocity }
* { [s] force time constant }
* { [s] velocity time constant }
* { [N/m^2] cable stiffness }
*
* @endcode
*/
class FDMEXPORT WinchLauncher
{
public:
/** @brief Constructor. */
WinchLauncher();
/** @brief Destructor. */
virtual ~WinchLauncher();
/**
* @brief Reads data.
* @param dataNode XML node
*/
virtual void readData( XmlNode &dataNode );
/**
* @brief Computes force and moment.
* @param wgs2bas matrix of rotation from WGS to BAS
* @param pos_wgs [m] aircraft position expressed in WGS
*/
virtual void computeForceAndMoment( const fdm::Matrix3x3 &wgs2bas,
const Vector3 &pos_wgs );
/**
* @brief Update winch model.
* @param timeStep [s] time step
* @param bas2wgs matrix of rotation from BAS to WGS
* @param wgs2ned matrix of rotation from WGS to NED
* @param pos_wgs [m] aircraft position expressed in WGS
* @param altitude_agl [m] altitude above ground level
*/
virtual void update( double timeStep,
const fdm::Matrix3x3 &bas2wgs,
const fdm::Matrix3x3 &wgs2ned,
const Vector3 &pos_wgs,
double altitude_agl );
inline const Vector3& getFor_BAS() const { return _for_bas; }
inline const Vector3& getMom_BAS() const { return _mom_bas; }
protected:
Vector3 _for_bas; ///< [N] total force vector expressed in BAS
Vector3 _mom_bas; ///< [N*m] total moment vector expressed in BAS
Vector3 _r_a_bas; ///< [m] winch cable attachment point expressed in BAS
Vector3 _pos_wgs; ///< [m] winch position expressed in WGS
double _for_max; ///< [N] maximum cable force
double _len_max; ///< [m] maximum cable length
double _ang_max; ///< [rad] maximum elevation
double _vel_max; ///< [m/s] maximum cable velocity
double _tc_for; ///< [s] force time constant
double _tc_vel; ///< [s] velocity time constant
double _stiffness; ///< [N/m^2] cable stiffness
double _for; ///< [N] current cable force
double _vel; ///< [m/s] current cable velocity
double _len; ///< [m] current cable length
bool _active; ///< specify if winch is active
};
} // end of fdm namespace
////////////////////////////////////////////////////////////////////////////////
#endif // FDM_WINCHLAUNCHER_H
|
c
| 11 | 0.573834 | 106 | 36.354839 | 124 |
starcoderdata
|
<td id="greetingMsgSetup">
<script src="@("https://unpkg.com/@microsoft/[email protected]/dist/MicrosoftTeams.min.js")">
<script src="~/Scripts/jquery-1.10.2.js">
<script src="https://code.jquery.com/jquery-3.1.1.js" integrity=" crossorigin="anonymous">
<script src="https://statics.teams.cdn.office.net/sdk/v1.6.0/js/MicrosoftTeams.min.js" integrity=" crossorigin="anonymous">
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.17/js/adal.min.js" integrity=" crossorigin="anonymous">
<script type="text/javascript">
microsoftTeams.initialize();
console.log(localStorage.getItem("displayName"));
window.onload = function () {
document.getElementById("greetingMsgSetup").innerHTML = `Welcome ${localStorage.getItem("displayName")}...`;
};
|
c#
| 20 | 0.655479 | 138 | 39.56 | 25 |
starcoderdata
|
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Controllers\Server\Status;
use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\ReplicationGui;
use PhpMyAdmin\Response;
use PhpMyAdmin\Server\Status\Data;
use PhpMyAdmin\Template;
use PhpMyAdmin\Url;
use PhpMyAdmin\Util;
use function implode;
/**
* Object the server status page: processes, connections and traffic.
*/
class StatusController extends AbstractController
{
/** @var ReplicationGui */
private $replicationGui;
/** @var DatabaseInterface */
private $dbi;
/**
* @param Response $response
* @param Data $data
* @param DatabaseInterface $dbi
*/
public function __construct($response, Template $template, $data, ReplicationGui $replicationGui, $dbi)
{
parent::__construct($response, $template, $data);
$this->replicationGui = $replicationGui;
$this->dbi = $dbi;
}
public function index(): void
{
global $err_url;
$err_url = Url::getFromRoute('/');
if ($this->dbi->isSuperUser()) {
$this->dbi->selectDb('mysql');
}
$replicationInfo = $this->data->getReplicationInfo();
$primaryInfo = $replicationInfo->getPrimaryInfo();
$replicaInfo = $replicationInfo->getReplicaInfo();
$traffic = [];
$connections = [];
$replication = '';
if ($this->data->dataLoaded) {
// In some case the data was reported not to exist, check it for all keys
if (isset($this->data->status['Bytes_received'], $this->data->status['Bytes_sent'])) {
$networkTraffic = implode(
' ',
Util::formatByteDown(
$this->data->status['Bytes_received'] + $this->data->status['Bytes_sent'],
3,
1
)
);
}
if (isset($this->data->status['Uptime'])) {
$uptime = Util::timespanFormat($this->data->status['Uptime']);
}
$startTime = Util::localisedDate($this->getStartTime());
$traffic = $this->getTrafficInfo();
$connections = $this->getConnectionsInfo();
if ($primaryInfo['status']) {
$replication .= $this->replicationGui->getHtmlForReplicationStatusTable('master');
}
if ($replicaInfo['status']) {
$replication .= $this->replicationGui->getHtmlForReplicationStatusTable('slave');
}
}
$this->render('server/status/status/index', [
'is_data_loaded' => $this->data->dataLoaded,
'network_traffic' => $networkTraffic ?? null,
'uptime' => $uptime ?? null,
'start_time' => $startTime ?? null,
'traffic' => $traffic,
'connections' => $connections,
'is_master' => $primaryInfo['status'],
'is_slave' => $replicaInfo['status'],
'replication' => $replication,
]);
}
private function getStartTime(): int
{
return (int) $this->dbi->fetchValue(
'SELECT UNIX_TIMESTAMP() - ' . $this->data->status['Uptime']
);
}
/**
* @return array
*/
private function getTrafficInfo(): array
{
$hourFactor = 3600 / $this->data->status['Uptime'];
return [
[
'name' => __('Received'),
'number' => implode(
' ',
Util::formatByteDown(
$this->data->status['Bytes_received'],
3,
1
)
),
'per_hour' => implode(
' ',
Util::formatByteDown(
$this->data->status['Bytes_received'] * $hourFactor,
3,
1
)
),
],
[
'name' => __('Sent'),
'number' => implode(
' ',
Util::formatByteDown(
$this->data->status['Bytes_sent'],
3,
1
)
),
'per_hour' => implode(
' ',
Util::formatByteDown(
$this->data->status['Bytes_sent'] * $hourFactor,
3,
1
)
),
],
[
'name' => __('Total'),
'number' => implode(
' ',
Util::formatByteDown(
$this->data->status['Bytes_received'] + $this->data->status['Bytes_sent'],
3,
1
)
),
'per_hour' => implode(
' ',
Util::formatByteDown(
($this->data->status['Bytes_received'] + $this->data->status['Bytes_sent']) * $hourFactor,
3,
1
)
),
],
];
}
/**
* @return array
*/
private function getConnectionsInfo(): array
{
$hourFactor = 3600 / $this->data->status['Uptime'];
$failedAttemptsPercentage = '---';
$abortedPercentage = '---';
if ($this->data->status['Connections'] > 0) {
$failedAttemptsPercentage = Util::formatNumber(
$this->data->status['Aborted_connects'] * 100 / $this->data->status['Connections'],
0,
2,
true
) . '%';
$abortedPercentage = Util::formatNumber(
$this->data->status['Aborted_clients'] * 100 / $this->data->status['Connections'],
0,
2,
true
) . '%';
}
return [
[
'name' => __('Max. concurrent connections'),
'number' => Util::formatNumber(
$this->data->status['Max_used_connections'],
0
),
'per_hour' => '---',
'percentage' => '---',
],
[
'name' => __('Failed attempts'),
'number' => Util::formatNumber(
$this->data->status['Aborted_connects'],
4,
1,
true
),
'per_hour' => Util::formatNumber(
$this->data->status['Aborted_connects'] * $hourFactor,
4,
2,
true
),
'percentage' => $failedAttemptsPercentage,
],
[
'name' => __('Aborted'),
'number' => Util::formatNumber(
$this->data->status['Aborted_clients'],
4,
1,
true
),
'per_hour' => Util::formatNumber(
$this->data->status['Aborted_clients'] * $hourFactor,
4,
2,
true
),
'percentage' => $abortedPercentage,
],
[
'name' => __('Total'),
'number' => Util::formatNumber(
$this->data->status['Connections'],
4,
0
),
'per_hour' => Util::formatNumber(
$this->data->status['Connections'] * $hourFactor,
4,
2
),
'percentage' => Util::formatNumber(100, 0, 2) . '%',
],
];
}
}
|
php
| 23 | 0.411967 | 114 | 30.603113 | 257 |
starcoderdata
|
package main
import (
"fmt"
"github.com/hawell/cache-compare/cacher"
"math/rand"
"sync"
"time"
)
func main() {
// TestHitRatio()
TestThroughput()
}
func TestHitRatio() {
caches := []cacher.Cacher {
&cacher.Optimal{},
&cacher.Ristretto{},
&cacher.BigCache{},
&cacher.FreeCache{},
&cacher.FastCache{},
&cacher.GoBurrow{},
&cacher.CCache{},
}
// Minimum cacheSize*itemSize for FastCache is 32MB
// itemSize should be less than 1/1024 of cacheSize*itemSize for FreeCache
ratio := 0.01
cacheSize := 60 * 1024
itemSize := 1024
dbSize := int(float64(cacheSize) / ratio)
queryCount := 10000000
for i := range caches {
caches[i].Init(cacheSize, itemSize)
}
entry := make([]byte, itemSize)
var wg sync.WaitGroup
for _, cache := range caches {
go func(cache cacher.Cacher) {
wg.Add(1)
source := rand.NewSource(rand.Int63n(int64(time.Now().Nanosecond())))
r := rand.New(source)
zipf := rand.NewZipf(r, 1.00001, 1, uint64(dbSize))
for i:=0 ;i < queryCount; i++ {
z := zipf.Uint64()
// log.Println(z)
_, found := cache.Get(z)
if !found {
cache.Set(z, entry)
}
}
wg.Done()
}(cache)
}
time.Sleep(time.Second)
wg.Wait()
for i := range caches {
fmt.Println(caches[i].HitRatio())
}
}
func TestThroughput() {
read := func(cache cacher.Cacher, zipf *rand.Zipf, entry []byte) {
z := zipf.Uint64()
// log.Println(z)
_, found := cache.Get(z)
if !found {
cache.Set(z, entry)
}
}
write := func(cache cacher.Cacher, zipf *rand.Zipf, entry []byte) {
z := zipf.Uint64()
cache.Set(z, entry)
}
caches := []cacher.Cacher{
&cacher.GoBurrow{},
&cacher.Ristretto{},
&cacher.CCache{},
&cacher.FastCache{},
&cacher.FreeCache{},
&cacher.BigCache{},
}
// ratio 1 = all read
// ratio 0 = all write
ratio := 0.0
goroutines := []int{4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64}
cacheSize := 60 * 1024
itemSize := 1024
dbSize := cacheSize
duration := 5
for _, cache := range caches {
cache.Init(cacheSize, itemSize)
}
entry := make([]byte, itemSize)
for _, cache := range caches {
var wg sync.WaitGroup
for _, count := range goroutines {
sum := make([]int, count)
for i := 0; i < count; i++ {
var fn func(cacher.Cacher, *rand.Zipf, []byte)
if i < int(float64(count)*ratio) {
fn = read
} else {
fn = write
}
go func(i int, fn func(cacher.Cacher, *rand.Zipf, []byte)) {
wg.Add(1)
source := rand.NewSource(rand.Int63n(int64(time.Now().Nanosecond())))
r := rand.New(source)
zipf := rand.NewZipf(r, 1.00001, 1, uint64(dbSize))
t := time.NewTicker(time.Second * time.Duration(duration))
for {
select {
case <-t.C:
wg.Done()
return
default:
fn(cache, zipf, entry)
sum[i]++
}
}
}(i, fn)
}
time.Sleep(time.Second)
wg.Wait()
total := 0
for i := range sum {
total += sum[i]
}
fmt.Print(total/duration, ",")
}
fmt.Println()
}
}
|
go
| 25 | 0.59447 | 82 | 19.958621 | 145 |
starcoderdata
|
package ir.coinance.service;
import ir.coinance.config.security.SecurityUtils;
import ir.coinance.domain.SettlementRequest;
import ir.coinance.dto.SettlementRequestDto;
import ir.coinance.mapper.SettlementRequestMapper;
import ir.coinance.repository.EnumTypeRepository;
import ir.coinance.repository.SettlementRequestRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class SettlementRequestService {
@Autowired
private SettlementRequestRepository repository;
@Autowired
private SettlementRequestMapper mapper;
@Autowired
private SecurityUtils securityUtils;
@Autowired
private EnumTypeRepository enumTypeRepository;
@Transactional
public SettlementRequestDto add(Float amount){
return mapper.toDto(repository.save(new SettlementRequest().builder()
.amount(amount)
.status(enumTypeRepository.findByKey("settlement_request_status_wait"))
.user(securityUtils.getCurrentUser())
.build()));
}
@Transactional
public SettlementRequestDto updateStatus(Long id, Long statusId){
SettlementRequest settlementRequest = repository.getOne(id);
settlementRequest.setStatus(enumTypeRepository.getOne(statusId));
if (settlementRequest.getStatus().getKey().equals("settlement_request_status_paid")){
// send pay sms to customer
}
return mapper.toDto(repository.save(settlementRequest));
}
@Transactional(readOnly = true)
public Page findAll(Pageable pageable){
return repository.findAll(pageable)
.map(mapper::toDto);
}
}
|
java
| 17 | 0.742632 | 93 | 32.928571 | 56 |
starcoderdata
|
/*
* Copyright (C) 2007-2009 Michal Simek <[email protected]>
* Copyright (C) 2007-2009 PetaLogix
* Copyright (C) 2006 Atmark Techno, Inc.
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#ifndef _ASM_MICROBLAZE_SETUP_H
#define _ASM_MICROBLAZE_SETUP_H
#define COMMAND_LINE_SIZE 256
# ifndef __ASSEMBLY__
# ifdef __KERNEL__
extern unsigned int boot_cpuid; /* move to smp.h */
extern char cmd_line[COMMAND_LINE_SIZE];
void early_printk(const char *fmt, ...);
int setup_early_printk(char *opt);
void disable_early_printk(void);
#if defined(CONFIG_EARLY_PRINTK)
#define eprintk early_printk
#else
#define eprintk printk
#endif
void heartbeat(void);
void setup_heartbeat(void);
# ifdef CONFIG_MMU
extern void mmu_reset(void);
extern void early_console_reg_tlb_alloc(unsigned int addr);
# endif /* CONFIG_MMU */
extern void of_platform_reset_gpio_probe(void);
void time_init(void);
void init_IRQ(void);
void machine_early_init(const char *cmdline, unsigned int ram,
unsigned int fdt, unsigned int msr);
void machine_restart(char *cmd);
void machine_shutdown(void);
void machine_halt(void);
void machine_power_off(void);
# endif/* __KERNEL__ */
# endif /* __ASSEMBLY__ */
#endif /* _ASM_MICROBLAZE_SETUP_H */
|
c
| 10 | 0.718497 | 77 | 23.232143 | 56 |
research_code
|
using System;
using System.Text;
using CleverDock.Managers;
namespace CleverDock.Interop
{
public class Win32Window
{
public Win32Window(IntPtr _hwnd)
{
Hwnd = _hwnd;
}
public void Toggle()
{
if (IsActive)
Minimize();
else
Restore();
}
public void Minimize()
{
WindowInterop.ShowWindow(Hwnd, WindowInterop.ShowStyle.Minimize);
if (IsActive)
WindowManager.Manager.ActiveWindow = IntPtr.Zero;
}
public void Restore()
{
WindowInterop.SetForegroundWindow(Hwnd);
if (IsMinimized)
WindowInterop.ShowWindow(Hwnd, WindowInterop.ShowStyle.Restore);
}
public void Close()
{
WindowInterop.SendMessage(Hwnd, WindowMessage.CLOSE, 0, 0);
}
public IntPtr Hwnd { get; set; }
public string FileName
{
get
{
return ProcessManager.GetExecutablePath(ProcessId);
}
}
public int ProcessId
{
get
{
int procId;
WindowInterop.GetWindowThreadProcessId(Hwnd, out procId);
return procId;
}
}
public bool IsActive
{
get
{
return Hwnd == WindowManager.Manager.ActiveWindow;
}
}
public bool IsChild
{
get
{
return ParentHwnd != IntPtr.Zero && OwnerHwnd != IntPtr.Zero;
}
}
public IntPtr ParentHwnd
{
get
{
return WindowInterop.GetParent(Hwnd);
}
}
public IntPtr OwnerHwnd
{
get
{
return WindowInterop.GetWindow(Hwnd, WindowInterop.GW_OWNER);
}
}
public bool IsMinimized
{
get
{
return WindowInterop.IsIconic(Hwnd);
}
}
public string Title
{
get
{
StringBuilder builder = new StringBuilder(200);
WindowInterop.GetWindowText(Hwnd, builder, builder.Capacity);
return builder.ToString();
}
}
public string ClassName
{
get
{
StringBuilder builder = new StringBuilder(200);
WindowInterop.GetClassName(Hwnd, builder, builder.Capacity);
return builder.ToString();
}
}
}
}
|
c#
| 16 | 0.46123 | 80 | 21.516393 | 122 |
starcoderdata
|
/**
*
*/
package com.woshidaniu.web.servlet.filter.chain.impl;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.woshidaniu.basicutils.CollectionUtils;
import com.woshidaniu.basicutils.StringUtils;
import com.woshidaniu.web.core.exception.ServletFilterException;
import com.woshidaniu.web.servlet.filter.Nameable;
import com.woshidaniu.web.servlet.filter.NamedFilterList;
import com.woshidaniu.web.servlet.filter.PathProcessor;
import com.woshidaniu.web.servlet.filter.chain.FilterChainManager;
/**
*
*
* 说明:Implements FilterChainManager
*
* @author <a href="#">Zhangxiaobin[1036]
* @version 2016年7月19日下午4:20:08
*/
public class DefaultFilterChainManager implements FilterChainManager {
private static transient final Logger log = LoggerFactory.getLogger(DefaultFilterChainManager.class);
private FilterConfig filterConfig;
private Map<String, Filter> filters;
private Map<String, NamedFilterList> filterChains;
private final static String DEFAULT_CHAIN_DEFINATION_DELIMITER_CHAR = ",";
public DefaultFilterChainManager() {
this.filters = new LinkedHashMap<String, Filter>();
this.filterChains = new LinkedHashMap<String, NamedFilterList>();
}
public DefaultFilterChainManager(FilterConfig filterConfig) {
this.filters = new LinkedHashMap<String, Filter>();
this.filterChains = new LinkedHashMap<String, NamedFilterList>();
setFilterConfig(filterConfig);
}
/**
* Returns the {@code FilterConfig} provided by the Servlet container at webapp startup.
*
* @return the {@code FilterConfig} provided by the Servlet container at webapp startup.
*/
public FilterConfig getFilterConfig() {
return filterConfig;
}
/**
* Sets the {@code FilterConfig} provided by the Servlet container at webapp startup.
*
* @param filterConfig the {@code FilterConfig} provided by the Servlet container at webapp startup.
*/
public void setFilterConfig(FilterConfig filterConfig) {
this.filterConfig = filterConfig;
}
public Map<String, Filter> getFilters() {
return filters;
}
public void setFilters(Map<String, Filter> filters) {
this.filters = filters;
}
public Map<String, NamedFilterList> getFilterChains() {
return filterChains;
}
public void setFilterChains(Map<String, NamedFilterList> filterChains) {
this.filterChains = filterChains;
}
public Filter getFilter(String name) {
return this.filters.get(name);
}
public void addFilter(String name, Filter filter) {
addFilter(name, filter, false);
}
public void addFilter(String name, Filter filter, boolean init) {
addFilter(name, filter, init, true);
}
public void createChain(String chainName, String chainDefinition) {
if (StringUtils.isBlank(chainName)) {
throw new NullPointerException("chainName cannot be null or empty.");
}
if (StringUtils.isBlank(chainDefinition)) {
throw new NullPointerException("chainDefinition cannot be null or empty.");
}
if (log.isDebugEnabled()) {
log.debug("Creating chain [" + chainName + "] from String definition [" + chainDefinition + "]");
}
String[] filterTokens = splitChainDefinition(chainDefinition);
for (String token : filterTokens) {
addToChain(chainName, token);
}
}
/**
* Splits the comma-delimited filter chain definition line into individual filter definition tokens.
*/
protected String[] splitChainDefinition(String chainDefinition) {
String trimToNull = StringUtils.trimToNull(chainDefinition);
if(trimToNull == null){
return null;
}
String[] split = StringUtils.splits(trimToNull, DEFAULT_CHAIN_DEFINATION_DELIMITER_CHAR);
for (int i = 0; i < split.length; i++) {
split[i] = StringUtils.trimToNull(split[i]);
}
return split;
}
public static void main(String[] args) {
}
protected void addFilter(String name, Filter filter, boolean init, boolean overwrite) {
Filter existing = getFilter(name);
if (existing == null || overwrite) {
if (filter instanceof Nameable) {
((Nameable) filter).setName(name);
}
if (init) {
initFilter(filter);
}
this.filters.put(name, filter);
}
}
public void addToChain(String chainName, String filterName) {
if (StringUtils.isBlank(chainName)) {
throw new IllegalArgumentException("chainName cannot be null or empty.");
}
Filter filter = getFilter(filterName);
if (filter == null) {
throw new IllegalArgumentException("There is no filter with name '" + filterName +
"' to apply to chain [" + chainName + "] in the pool of available Filters. Ensure a " +
"filter with that name/path has first been registered with the addFilter method(s).");
}
applyChainConfig(chainName, filter);
NamedFilterList chain = ensureChain(chainName);
chain.add(filter);
}
protected void applyChainConfig(String chainName, Filter filter) {
if (log.isDebugEnabled()) {
log.debug("Attempting to apply path [" + chainName + "] to filter [" + filter + "] ");
}
if (filter instanceof PathProcessor) {
((PathProcessor) filter).processPath(chainName);
} else {
String msg = "the underlying " +
"Filter instance is not an 'instanceof' " +
PathProcessor.class.getName() + ". This is required if the filter is to accept " +
"chain-specific configuration.";
throw new ServletFilterException(msg);
}
}
protected NamedFilterList ensureChain(String chainName) {
NamedFilterList chain = getChain(chainName);
if (chain == null) {
chain = new DefaultNamedFilterList(chainName);
this.filterChains.put(chainName, chain);
}
return chain;
}
public NamedFilterList getChain(String chainName) {
return this.filterChains.get(chainName);
}
public boolean hasChains() {
return !CollectionUtils.isEmpty(this.filterChains);
}
@SuppressWarnings("unchecked")
public Set getChainNames() {
return this.filterChains != null ? this.filterChains.keySet() : Collections.EMPTY_SET;
}
public FilterChain proxy(FilterChain original, String chainName) {
NamedFilterList configured = getChain(chainName);
if (configured == null) {
String msg = "There is no configured chain under the name/key [" + chainName + "].";
throw new IllegalArgumentException(msg);
}
return configured.proxy(original);
}
/**
* Initializes the filter by calling {@link #getFilterConfig() getFilterConfig()} );
*
* @param filter the filter to initialize with the {@code FilterConfig}.
*/
protected void initFilter(Filter filter) {
FilterConfig filterConfig = getFilterConfig();
if (filterConfig == null) {
throw new IllegalStateException("FilterConfig attribute has not been set. This must occur before filter " +
"initialization can occur.");
}
try {
filter.init(filterConfig);
} catch (ServletException e) {
throw new ServletFilterException(e);
}
}
}
|
java
| 16 | 0.649479 | 120 | 33.357759 | 232 |
starcoderdata
|
<?php
namespace AnyB1s\ShippingCalculator\Package;
class Weight implements \JsonSerializable
{
private $weight;
private $unit;
public function __construct(float $aWeight, string $aUnit)
{
$this->weight = $aWeight;
$this->unit = $aUnit;
}
public function quantity()
{
return $this->weight;
}
public function isBetween(float $from, float $to)
{
return $this->weight > $from && $this->weight < $to;
}
public function isGreaterThan(float $weight)
{
return $this->weight > $weight;
}
public function isLessThan(float $weight)
{
return $this->weight > $weight;
}
public function __toString()
{
return $this->weight . ' ' . $this->unit;
}
public function jsonSerialize()
{
return [
'quantity' => $this->weight,
'unit' => $this->unit
];
}
}
|
php
| 10 | 0.553763 | 62 | 18.375 | 48 |
starcoderdata
|
protected static String makeBaseRelativePath(final Source source, final String resourcePath) {
String result = resourcePath;
if (resourcePath.startsWith("/")) {
// TODO this is an ugly hack in part because RIP uses config root instead of module root
// special case handling for descriptor and actions
if (resourcePath.equals("/../"+ HCM_MODULE_YAML)) {
// short-circuit here, because we want to skip JCR name escaping
return "../"+ HCM_MODULE_DESCRIPTOR;
}
if (resourcePath.equals("/../"+ACTIONS_YAML)) {
// short-circuit here, because we want to skip JCR name escaping
return "../"+ HCM_ACTIONS;
}
result = StringUtils.stripStart(result, "/");
}
else {
final String sourcePath = source.getPath();
int lastSlash = sourcePath.lastIndexOf('/');
if (lastSlash < 0) {
result = resourcePath;
}
else {
result = sourcePath.substring(0, lastSlash+1) + resourcePath;
}
}
// escape JCR-illegal chars here, since resource paths are intended to be filesystem paths, not JCR paths
String[] pathSegments = result.split("/");
for (int i = 0; i < pathSegments.length; i++) {
pathSegments[i] = NodeNameCodec.encode(pathSegments[i]);
}
return String.join("/", pathSegments);
}
|
java
| 13 | 0.559973 | 113 | 43.411765 | 34 |
inline
|
function (key, listener) {
var keyHandlers;
if (this.handlers.hasOwnProperty(key)) {
// Check handler is not already stored
keyHandlers = this.handlers[key];
var length = keyHandlers.length;
for (var i = 0; i < length; i += 1) {
if (keyHandlers[i] === listener) {
// Event handler has already been added
return;
}
}
} else {
keyHandlers = this.handlers[key] = [];
}
keyHandlers.push(listener);
}
|
javascript
| 12 | 0.470085 | 59 | 29.842105 | 19 |
inline
|
def __init__(self):
# Configure logger.
self._logger = spd.FileLogger("logger", "/tmp/calls.log")
self._logger.set_pattern("[%Y-%m-%d %H:%M:%S.%F] pid=%P tid=%t %v")
# Parse backend configuration.
backend_filename = "/etc/opt/BuzzBlog/backend.yml"
with open(backend_filename) as backend_file:
self._backend_conf = yaml.safe_load(backend_file)
|
python
| 9 | 0.645161 | 71 | 45.625 | 8 |
inline
|
using Hotel.Server.Models;
using Hotel.Shared;
using System;
using System.Collections.Generic;
namespace Hotel.Server.Tests
{
public static class MockData
{
public static List MockBookings => new List {
new Booking { Id = 1, BookingNumber = "foo", CheckInDate = DateTime.Now, CheckOutDate = DateTime.Now.AddDays(5), FirstName = "Test", LastName = "Testsson" },
new Booking { Id = 2, BookingNumber = "bar", CheckInDate = DateTime.Now, CheckOutDate = DateTime.Now.AddDays(5), FirstName = "Test2", LastName = "Testsson2" },
};
public static List MockRooms => new List {
new Room { Id = 1, Beds = 1, DoubleBeds = 1, IsCondo = false, IsSuite = false },
new Room { Id = 2, Beds = 2, DoubleBeds = 1, IsCondo = true, IsSuite = false },
new Room { Id = 3, Beds = 2, DoubleBeds = 0, IsCondo = false, IsSuite = false },
};
public static List MockRoomAvailabilityRequest => new List
{
new RoomAvailabilityRequest {CheckInDate = DateTime.Now.AddDays(2), CheckOutDate = DateTime.Now.AddDays(3), Guests = 1},
new RoomAvailabilityRequest {CheckInDate = DateTime.Now.AddDays(5), CheckOutDate = DateTime.Now.AddDays(9), Guests = 3},
new RoomAvailabilityRequest {CheckInDate = DateTime.Now.AddDays(5), CheckOutDate = DateTime.Now.AddDays(9), Guests = 2},
new RoomAvailabilityRequest {CheckInDate = DateTime.Now.AddDays(5), CheckOutDate = DateTime.Now.AddDays(9), Guests = 1},
new RoomAvailabilityRequest {CheckInDate = DateTime.Now.AddDays(7), CheckOutDate = DateTime.Now.AddDays(11), Guests = 3},
};
public static BookingRequest MockBookingRequest => new BookingRequest
{
Address = "Test Avenue 126", // booking info
CheckInDate = DateTime.Now.AddDays(7),
CheckOutDate = DateTime.Now.AddDays(11),
Email = "
FirstName = "Hotello",
LastName = "Testovich",
Guests = 1,
PhoneNumber = "+46738429270",
Beds = 1, // room info
DoubleBeds = 1,
SpaAccess = false,
IsSuite = false,
Breakfast = true
};
public static List MockReviews => new List
{
new Review
{
Id = 1,
Description = "The most awesome hotel that I have ever visited, heads up to receptionist for being kind!",
Grade = 5,
Anonymous = false,
FirstName = "Hasse",
LastName = "Tagesson",
BookingNumber = "f10db40a-8906-4788-99c8-8292361be7c2"
},
new Review
{
Id = 2,
Description = "Awesome service",
Grade = 4,
Anonymous = false,
FirstName = "Tage",
LastName = "Hassesson",
BookingNumber = "f10db40a-8906-4788-99c8-8292361be7h3"
},
new Review
{
Id = 3,
Description = "Friendly staff and extraordinary food in the restaurant.",
Grade = 5,
Anonymous = false,
FirstName = "TageHasse",
LastName = "TageHassesson",
BookingNumber = "f10db40a-8906-4788-99c8-8292361je7h3"
},
};
public static Review MockReview => new Review
{
Id = 4,
Description = "Friendly staff and extraordinary food in the restaurant.",
Grade = 5,
Anonymous = false,
FirstName = "TageHasse",
LastName = "TageHassesson",
BookingNumber = "f10db40a-8906-4788-99c8-8292361je7h3"
};
}
}
|
c#
| 15 | 0.553116 | 175 | 41.612903 | 93 |
starcoderdata
|
package com.mcleodmoores.quandl.robustwrapper;
import org.testng.annotations.Test;
import com.jimmoores.quandl.MultiDataSetRequest;
import com.jimmoores.quandl.QuandlCodeRequest;
import com.jimmoores.quandl.QuandlSession;
import com.opengamma.util.test.TestGroup;
@Test(groups = TestGroup.UNIT)
public class RobustQuandlSessionTest {
@Test
public void testMultiGet() {
final RobustQuandlSession session = new RobustQuandlSession(QuandlSession.create());
session.getDataSets(MultiDataSetRequest.Builder.of(QuandlCodeRequest.allColumns("FRED/DSWP10")).build());
}
}
|
java
| 14 | 0.80895 | 109 | 33.176471 | 17 |
starcoderdata
|
package lotsize.impl;
import lotsize.AbstractVerfahren;
import lotsize.HeuristikEnum;
import lotsize.Input;
/**
* Das Stückkostenverfahren berechnet das optimale Los nach der Eigenschaft
* des klassischen Losgrößenverfahrens, dass der Quotient aus den Gesamtkosten
* in einem Zyklus und dem Los im Optimum minimal ist.
*/
public class StueckkostenVerfahren extends AbstractVerfahren {
public StueckkostenVerfahren(HeuristikEnum heuristik, Input input) {
super(heuristik, input);
}
/**
* @return Kostenkriterium C der Vorperiode (t-1)
*/
@Override
protected double calcV(Integer tau, Integer t) {
return calcC(tau, t - 1);
}
/**
* Berechnet für das Stückkostenverfahren die Durchschnittlichen Stückkosten
* C aus dem Quotienten der Gesamtkosten und der Summe der Bedarfe zur Periode t.
* Greift auf die Eingangsgrößen der Klasse {@link Input} zu.
*/
@Override
protected double calcC(Integer tau, Integer t) {
double sum_d1 = 0.0;
double sum_d2 = 0.0;
for (int j = tau + 1; j <= t; j++) {
sum_d1 += input.getRequirements().get(j) * (j - tau);
}
for (int j = tau; j <= t; j++) {
sum_d2 += input.getRequirements().get(j);
}
return (input.getSetupCostsConcrete() + input.getHoldingCostsConcrete() * sum_d1) / sum_d2;
}
}
|
java
| 13 | 0.649892 | 99 | 29.23913 | 46 |
starcoderdata
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Auth;
use Carbon\Carbon;
class BarCodeController extends Controller
{
public function index($id)
{
$mensaje = "";
$tipe = 1;
$productos = DB::table('productos')->where('id',$id)->get();
return view('admin_panel/barcode', compact('productos','tipe' ,'mensaje'));
}
public function index_barr($id)
{
$mensaje = "";
$tipe = 2;
$productos = DB::table('productos')->where('id',$id)->get();
return view('admin_panel/barcode', compact('productos','tipe','mensaje'));
}
}
|
php
| 13 | 0.640961 | 83 | 24.516129 | 31 |
starcoderdata
|
from FrEIA.modules import InvertibleModule
import numpy as np
import torch
import torch.nn as nn
from torch.nn.functional import conv2d, conv_transpose2d
class ActNorm(InvertibleModule):
def __init__(self, dims_in, dims_c=None, init_data=None):
super().__init__(dims_in, dims_c)
self.dims_in = dims_in[0]
param_dims = [1, self.dims_in[0]] + [1 for i in range(len(self.dims_in) - 1)]
self.scale = nn.Parameter(torch.zeros(*param_dims))
self.bias = nn.Parameter(torch.zeros(*param_dims))
if init_data:
self.initialize_with_data(init_data)
else:
self.init_on_next_batch = True
def on_load_state_dict(*args):
# when this module is loading state dict, we SHOULDN'T init with data,
# because that will reset the trained parameters. Registering a hook
# that disable this initialisation.
self.init_on_next_batch = False
self._register_load_state_dict_pre_hook(on_load_state_dict)
def initialize_with_data(self, data):
# Initialize to mean 0 and std 1 with sample batch
# 'data' expected to be of shape (batch, channels[, ...])
assert all([data.shape[i+1] == self.dims_in[i] for i in range(len(self.dims_in))]),\
"Can't initialize ActNorm layer, provided data don't match input dimensions."
self.scale.data.view(-1)[:] \
= torch.log(1 / data.transpose(0,1).contiguous().view(self.dims_in[0], -1).std(dim=-1))
data = data * self.scale.exp()
self.bias.data.view(-1)[:] \
= -data.transpose(0,1).contiguous().view(self.dims_in[0], -1).mean(dim=-1)
self.init_on_next_batch = False
def forward(self, x, rev=False, jac=True):
if self.init_on_next_batch:
self.initialize_with_data(x[0])
jac = (self.scale.sum() * np.prod(self.dims_in[1:])).repeat(x[0].shape[0])
if rev:
jac = -jac
if not rev:
return [x[0] * self.scale.exp() + self.bias], jac
else:
return [(x[0] - self.bias) / self.scale.exp()], jac
def output_dims(self, input_dims):
assert len(input_dims) == 1, "Can only use 1 input"
return input_dims
|
python
| 18 | 0.594774 | 99 | 37.288136 | 59 |
starcoderdata
|
package com.github.khaledroushdy.browser;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class JavascriptDriver {
private JavascriptExecutor js;
public JavascriptExecutor getJs(WebDriver driver) {
js = (JavascriptExecutor) driver;
return js;
}
public Object executeJsScript(String script, WebDriver driver, WebElement element) {
return getJs(driver).executeScript(script, element);
}
public void executeJsScript(String script, WebDriver driver) {
getJs(driver).executeScript(script);
}
}
|
java
| 7 | 0.791209 | 85 | 25.541667 | 24 |
starcoderdata
|
/*
* Copyright DataGenerator Contributors
*
* 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 org.finra.datagenerator.engine.scxml.tags;
import org.apache.commons.logging.Log;
import org.apache.commons.scxml.ErrorReporter;
import org.apache.commons.scxml.EventDispatcher;
import org.apache.commons.scxml.SCInstance;
import org.apache.commons.scxml.SCXMLExpressionException;
import org.apache.commons.scxml.model.Action;
import org.apache.commons.scxml.model.ModelException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Implementation of dg:nwise tag
*/
public class NWiseExtension implements CustomTagExtension {
public Class getTagActionClass() {
return NWiseAction.class;
}
public String getTagName() {
return "nwise";
}
public String getTagNameSpace() {
return "org.finra.datagenerator";
}
private void makeNWiseTuplesHelper(List resultTuples, String[] variables,
int startVariable, Set preGivenVariables, int nWise) {
if (nWise <= 0) {
Set result = new HashSet<>(preGivenVariables);
resultTuples.add(result);
return;
}
for (int varIndex = startVariable; varIndex <= variables.length - nWise; varIndex++) {
preGivenVariables.add(variables[varIndex]);
makeNWiseTuplesHelper(resultTuples, variables, varIndex + 1, preGivenVariables, nWise - 1);
preGivenVariables.remove(variables[varIndex]);
}
}
/**
* Produces all tuples of size n chosen from a list of variable names
*
* @param variables the list of variable names to make tuples of
* @param nWise the size of the desired tuples
* @return all tuples of size nWise
*/
public List makeNWiseTuples(String[] variables, int nWise) {
List completeTuples = new ArrayList<>();
makeNWiseTuplesHelper(completeTuples, variables, 0, new HashSet nWise);
return completeTuples;
}
private void expandTupleHelper(List<Map<String, String>> resultExpansions, String[] variables,
Map<String, String[]> variableDomains, int nextVariable,
Map<String, String> partialAssignment) {
if (nextVariable >= variables.length) {
Map<String, String> resultAssignment = new HashMap<>(partialAssignment);
resultExpansions.add(resultAssignment);
return;
}
String variable = variables[nextVariable];
for (String domainValue : variableDomains.get(variable)) {
partialAssignment.put(variable, domainValue);
expandTupleHelper(resultExpansions, variables, variableDomains, nextVariable + 1, partialAssignment);
}
}
/**
* Expands a tuple of variable names into every combination of assignments to those variables
*
* @param tuple a list of variables
* @param variableDomains a map defining the domain for each variable
* @return the cartesian product of the domains of each variable in the tuple
*/
public List<Map<String, String>> expandTupleIntoTestCases(Set tuple, Map<String, String[]> variableDomains) {
List<Map<String, String>> expandedTestCases = new ArrayList<>();
String[] variables = tuple.toArray(new String[tuple.size()]);
expandTupleHelper(expandedTestCases, variables, variableDomains, 0, new HashMap<String, String>());
return expandedTestCases;
}
/**
* Finds all nWise combinations of a set of variables, each with a given domain of values
*
* @param nWise the number of variables in each combination
* @param coVariables the varisbles
* @param variableDomains the domains
* @return all nWise combinations of the set of variables
*/
public List<Map<String, String>> produceNWise(int nWise, String[] coVariables, Map<String, String[]> variableDomains) {
List tuples = makeNWiseTuples(coVariables, nWise);
List<Map<String, String>> testCases = new ArrayList<>();
for (Set tuple : tuples) {
testCases.addAll(expandTupleIntoTestCases(tuple, variableDomains));
}
return testCases;
}
/**
* Uses current variable assignments and info in an NWiseActionTag to expand on an n wise combinatorial set
*
* @param action an NWiseAction Action
* @param possibleStateList a current list of possible states produced so far from expanding a model state
* @return every input possible state expanded on an n wise combinatorial set defined by that input possible state
*/
public List<Map<String, String>> pipelinePossibleStates(NWiseAction action, List<Map<String, String>> possibleStateList) {
String[] coVariables = action.getCoVariables().split(",");
int n = Integer.valueOf(action.getN());
List<Map<String, String>> newPossibleStateList = new ArrayList<>();
for (Map<String, String> possibleState : possibleStateList) {
Map<String, String[]> variableDomains = new HashMap<>();
Map<String, String> defaultVariableValues = new HashMap<>();
for (String variable : coVariables) {
String variableMetaInfo = possibleState.get(variable);
String[] variableDomain = variableMetaInfo.split(",");
variableDomains.put(variable, variableDomain);
defaultVariableValues.put(variable, variableDomain[0]);
}
List<Map<String, String>> nWiseCombinations = produceNWise(n, coVariables, variableDomains);
for (Map<String, String> nWiseCombination : nWiseCombinations) {
Map<String, String> newPossibleState = new HashMap<>(possibleState);
newPossibleState.putAll(defaultVariableValues);
newPossibleState.putAll(nWiseCombination);
newPossibleStateList.add(newPossibleState);
}
}
return newPossibleStateList;
}
/**
* A custom Action for the 'dg:nwise' tag inside models
*/
public static class NWiseAction extends Action {
private String coVariables;
private String n;
public String getCoVariables() {
return coVariables;
}
public void setCoVariables(String coVariables) {
this.coVariables = coVariables;
}
public String getN() {
return n;
}
public void setN(String n) {
this.n = n;
}
/**
* Required implementation of an abstract method in Action
*
* @param eventDispatcher unused
* @param errorReporter unused
* @param scInstance unused
* @param log unused
* @param collection unused
* @throws ModelException never
* @throws SCXMLExpressionException never
*/
public void execute(EventDispatcher eventDispatcher, ErrorReporter errorReporter, SCInstance scInstance,
Log log, Collection collection) throws ModelException, SCXMLExpressionException {
}
}
}
|
java
| 14 | 0.654534 | 126 | 38.460784 | 204 |
starcoderdata
|
@Test
public void testRequestFilter() {
request.setPath("/test");
service.findMatch(new StubRequest(request));
request.setPath("/test");
request.setParams(Arrays.asList(new StubParam("foo", "bar")));
service.findMatch(new StubRequest(request));
assertEquals(2, service.getRequests().size());
StubRequest filter = new StubRequest();
filter.setParams(Arrays.asList(new StubParam("foo", "b.r")));
assertEquals(1, service.findRequests(filter).size()); // should only match one of the requests
}
|
java
| 11 | 0.619765 | 102 | 38.866667 | 15 |
inline
|
def to_csv(self, output: str) -> None:
"""
write parsed vcf data to a csv
@param output: output file
"""
if not output.endswith(".gz"):
output += ".gz"
print(itertools.islice(self.record_data, 100000-1))
dataframes: Mapping[pd.DataFrame, Dict[str, Union[str, int, float]]]
dataframes = map(pd.DataFrame, helpers._group_iterator(self.record_data))
write_header = True
for dataframe in dataframes:
print("here")
cc
csverve.write_dataframe_to_csv_and_yaml(dataframe, output,
dataframe.dtypes, write_header=write_header
)
write_header=False
yaml_file: str = output + ".yaml"
metadata: Dict[str, str] = yaml.load(open(yaml_file))
metadata["samples"] = {"tumor": self.tumor, "normal": self.normal}
with open(yaml_file, 'wt') as f:
yaml.safe_dump(metadata, f, default_flow_style=False)
|
python
| 15 | 0.559724 | 81 | 42.130435 | 23 |
inline
|
@Async
void resetPasswordRequest(Customer customer, String resetLink, MerchantStore store, Locale locale)
throws Exception {
try {
// creation of a user, send an email
String[] storeEmail = { store.getStoreEmailAddress() };
Map<String, String> templateTokens = emailUtils.createEmailObjectsMap(imageUtils.getContextPath(), store,
messages, locale);
templateTokens.put(EmailConstants.LABEL_HI, messages.getMessage("label.generic.hi", locale));
templateTokens.put(EmailConstants.EMAIL_CUSTOMER_FIRSTNAME, customer.getBilling().getFirstName());
templateTokens.put(RESET_PASSWORD_LINK, resetLink);
templateTokens.put(RESET_PASSWORD_TEXT,
messages.getMessage("email.reset.password.text", new String[] { store.getStorename() }, locale));
templateTokens.put(EmailConstants.LABEL_LINK_TITLE,
messages.getMessage("email.link.reset.password.title", locale));
templateTokens.put(EmailConstants.LABEL_LINK, messages.getMessage("email.link", locale));
templateTokens.put(EmailConstants.EMAIL_CONTACT_OWNER,
messages.getMessage("email.contactowner", storeEmail, locale));
Email email = new Email();
email.setFrom(store.getStorename());
email.setFromEmail(store.getStoreEmailAddress());
email.setSubject(messages.getMessage("email.link.reset.password.title", locale));
email.setTo(customer.getEmailAddress());
email.setTemplateName(ACCOUNT_PASSWORD_RESET_TPL);
email.setTemplateTokens(templateTokens);
emailService.sendHtmlEmail(store, email);
} catch (Exception e) {
throw new Exception("Cannot send email to customer", e);
}
}
|
java
| 14 | 0.755915 | 108 | 44.914286 | 35 |
inline
|
/*
* Copyright (c)
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
const fs = require( 'fs' );
module.exports = ( filePath, template, encrypted ) => new Promise( ( resolve, reject ) => fs.writeFile(
filePath,
template.replace( /{encrypted}/, encrypted.hmac + encrypted.encrypted ),
e => {
if ( e ) {
return reject( e );
}
resolve();
}
) );
|
javascript
| 16 | 0.581028 | 103 | 17.740741 | 27 |
starcoderdata
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
*/
package org.searchisko.api.reindexer;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.enterprise.event.Event;
import org.hamcrest.CustomMatcher;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import org.searchisko.api.ContentObjectFields;
import org.searchisko.api.events.ContentBeforeIndexedEvent;
import org.searchisko.api.service.ProviderService;
import org.searchisko.api.service.ProviderServiceTest;
import org.searchisko.api.service.SearchClientService;
import org.searchisko.api.tasker.TaskExecutionContext;
import org.searchisko.api.testtools.ESRealClientTestBase;
import org.searchisko.persistence.service.ContentPersistenceService;
import org.searchisko.persistence.service.ContentTuple;
import org.searchisko.persistence.service.ListRequest;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
/**
* Unit test for {@link ReindexFromPersistenceTask}
*
* @author (velias at redhat dot com)
*/
public class ReindexFromPersistenceTaskTest extends ESRealClientTestBase {
String sysContentType = "tt";
String indexName = "myindex";
String typeName = "mytype";
@SuppressWarnings("unchecked")
@Test
public void performTask_ok() throws Exception {
try {
ReindexFromPersistenceTask tested = new ReindexFromPersistenceTask();
tested.setExecutionContext("tid", Mockito.mock(TaskExecutionContext.class));
tested.searchClientService = Mockito.mock(SearchClientService.class);
Mockito.when(tested.searchClientService.getClient()).thenReturn(prepareESClientForUnitTest());
Mockito.doCallRealMethod().when(tested.searchClientService)
.performDeleteOldRecords(Mockito.anyString(), Mockito.anyString(), Mockito.any(Date.class));
tested.sysContentType = sysContentType;
tested.providerService = Mockito.mock(ProviderService.class);
tested.eventBeforeIndexed = Mockito.mock(Event.class);
List<Map<String, Object>> preprocessorsDef = new ArrayList<Map<String, Object>>();
configProviderServiceMock(tested, preprocessorsDef);
indexDelete(indexName);
indexCreate(indexName);
indexMappingCreate(indexName, typeName, "{ \"" + typeName + "\" : {\"_timestamp\" : { \"enabled\" : true }}}");
// case - put it into empty index
{
tested.contentPersistenceService = getContentPersistenceServiceMock(false);
tested.performTask();
indexFlushAndRefresh(indexName);
Assert.assertNotNull(indexGetDocument(indexName, typeName, "tt-1"));
Assert.assertNotNull(indexGetDocument(indexName, typeName, "tt-2"));
Assert.assertNotNull(indexGetDocument(indexName, typeName, "tt-3"));
Assert.assertNotNull(indexGetDocument(indexName, typeName, "tt-4"));
Assert.assertNotNull(indexGetDocument(indexName, typeName, "tt-5"));
Assert.assertNotNull(indexGetDocument(indexName, typeName, "tt-6"));
Assert.assertNotNull(indexGetDocument(indexName, typeName, "tt-7"));
Assert.assertNotNull(indexGetDocument(indexName, typeName, "tt-8"));
Assert.assertNull(indexGetDocument(indexName, typeName, "tt-9"));
Mockito.verify(tested.providerService, Mockito.times(8)).runPreprocessors(Mockito.eq(sysContentType),
Mockito.eq(preprocessorsDef), Mockito.anyMap());
verify(tested.eventBeforeIndexed).fire(prepareContentBeforeIndexedEventMatcher("tt-1"));
verify(tested.eventBeforeIndexed).fire(prepareContentBeforeIndexedEventMatcher("tt-2"));
verify(tested.eventBeforeIndexed).fire(prepareContentBeforeIndexedEventMatcher("tt-3"));
verify(tested.eventBeforeIndexed).fire(prepareContentBeforeIndexedEventMatcher("tt-4"));
verify(tested.eventBeforeIndexed).fire(prepareContentBeforeIndexedEventMatcher("tt-5"));
verify(tested.eventBeforeIndexed).fire(prepareContentBeforeIndexedEventMatcher("tt-6"));
verify(tested.eventBeforeIndexed).fire(prepareContentBeforeIndexedEventMatcher("tt-7"));
verify(tested.eventBeforeIndexed).fire(prepareContentBeforeIndexedEventMatcher("tt-8"));
verifyNoMoreInteractions(tested.eventBeforeIndexed);
}
// case - put it into non empty index to check if records are deleted correctly
{
Mockito.reset(tested.providerService, tested.eventBeforeIndexed);
configProviderServiceMock(tested, preprocessorsDef);
tested.contentPersistenceService = getContentPersistenceServiceMock(true);
tested.performTask();
indexFlushAndRefresh(indexName);
Assert.assertNotNull(indexGetDocument(indexName, typeName, "tt-1"));
Assert.assertNotNull(indexGetDocument(indexName, typeName, "tt-2"));
Assert.assertNotNull(indexGetDocument(indexName, typeName, "tt-3"));
Assert.assertNotNull(indexGetDocument(indexName, typeName, "tt-4"));
Assert.assertNotNull(indexGetDocument(indexName, typeName, "tt-5"));
Assert.assertNotNull(indexGetDocument(indexName, typeName, "tt-6"));
// next two must be removed from index because not in persistent store anymore
Assert.assertNull(indexGetDocument(indexName, typeName, "tt-7"));
Assert.assertNull(indexGetDocument(indexName, typeName, "tt-8"));
Mockito.verify(tested.providerService, Mockito.times(6)).runPreprocessors(Mockito.eq(sysContentType),
Mockito.eq(preprocessorsDef), Mockito.anyMap());
verify(tested.eventBeforeIndexed).fire(prepareContentBeforeIndexedEventMatcher("tt-1"));
verify(tested.eventBeforeIndexed).fire(prepareContentBeforeIndexedEventMatcher("tt-2"));
verify(tested.eventBeforeIndexed).fire(prepareContentBeforeIndexedEventMatcher("tt-3"));
verify(tested.eventBeforeIndexed).fire(prepareContentBeforeIndexedEventMatcher("tt-4"));
verify(tested.eventBeforeIndexed).fire(prepareContentBeforeIndexedEventMatcher("tt-5"));
verify(tested.eventBeforeIndexed).fire(prepareContentBeforeIndexedEventMatcher("tt-6"));
verifyNoMoreInteractions(tested.eventBeforeIndexed);
}
} finally {
finalizeESClientForUnitTest();
}
}
private ContentBeforeIndexedEvent prepareContentBeforeIndexedEventMatcher(final String expectedId) {
return Mockito.argThat(new CustomMatcher [contentId="
+ expectedId + "]") {
@Override
public boolean matches(Object paramObject) {
ContentBeforeIndexedEvent e = (ContentBeforeIndexedEvent) paramObject;
return e.getContentId().equals(expectedId) && e.getContentData() != null;
}
});
}
private void configProviderServiceMock(ReindexFromPersistenceTask tested, List<Map<String, Object>> preprocessorsDef) {
Map<String, Object> typeDef = new HashMap<String, Object>();
typeDef.put(ProviderService.INPUT_PREPROCESSORS, preprocessorsDef);
Map<String, Object> index = new HashMap<String, Object>();
typeDef.put(ProviderService.INDEX, index);
index.put(ProviderService.NAME, indexName);
index.put(ProviderService.TYPE, typeName);
Mockito.when(tested.providerService.findContentType(sysContentType)).thenReturn(
ProviderServiceTest.createProviderContentTypeInfo(typeDef));
}
private ContentPersistenceService getContentPersistenceServiceMock(boolean shorter) {
ContentPersistenceService ret = Mockito.mock(ContentPersistenceService.class);
TestListRequest listRequest1 = new TestListRequest();
addContent(listRequest1, "tt-1");
addContent(listRequest1, "tt-2");
addContent(listRequest1, "tt-3");
Mockito.when(ret.listRequestInit(sysContentType)).thenReturn(listRequest1);
TestListRequest listRequest2 = new TestListRequest();
addContent(listRequest2, "tt-4");
addContent(listRequest2, "tt-5");
addContent(listRequest2, "tt-6");
Mockito.when(ret.listRequestNext(listRequest1)).thenReturn(listRequest2);
if (!shorter) {
TestListRequest listRequest3 = new TestListRequest();
addContent(listRequest3, "tt-7");
addContent(listRequest3, "tt-8");
Mockito.when(ret.listRequestNext(listRequest2)).thenReturn(listRequest3);
Mockito.when(ret.listRequestNext(listRequest3)).thenReturn(new TestListRequest());
} else {
Mockito.when(ret.listRequestNext(listRequest2)).thenReturn(new TestListRequest());
}
return ret;
}
private void addContent(TestListRequest listRequest1, String id) {
Map<String, Object> content = new HashMap<String, Object>();
content.put(ContentObjectFields.SYS_ID, id);
content.put(ContentObjectFields.SYS_CONTENT_TYPE, sysContentType);
content.put(ContentObjectFields.SYS_DESCRIPTION, "value " + id);
listRequest1.content.add(new ContentTuple<String, Map<String, Object>>(id, content));
}
protected static class TestListRequest implements ListRequest {
List<ContentTuple<String, Map<String, Object>>> content = new ArrayList<>();
@Override
public boolean hasContent() {
return content != null && !content.isEmpty();
}
@Override
public List<ContentTuple<String, Map<String, Object>>> content() {
return content;
}
}
}
|
java
| 17 | 0.776101 | 120 | 43.950495 | 202 |
starcoderdata
|
import sys
sys.setrecursionlimit(700000)
def s_in():
return input()
def n_in():
return int(input())
def l_in():
return list(map(int, input().split()))
n=n_in()
base=[]
for _ in range(n):
s = s_in()
c = s[0]
cnt = 1
ar = []
for t in range(1,len(s)):
if s[t-1] == s[t]:
cnt += 1
else:
ar.append((c,cnt))
c = s[t]
cnt = 1
ar.append((c,cnt))
start = 0
if ar[0][0] == ")":
start = 1
r = 0 # ( の数
sgn = 1
for c,cnt in ar[start:]:
r += sgn*cnt
sgn *= -1
res = ()
if ar[0][0] == ")":
if r >= 0:
res = (ar[0][1], r)
else:
res = (ar[0][1]-r,0)
else:
if r >= 0:
res = (0, r)
else:
res = (-r, 0)
base.append(res)
i_cnt = 0
j_cnt = 0
base2 = []
for i,j in base:
i_cnt += i
j_cnt += j
if j > 0:
base2.append((i,-(j-i),j))
if i_cnt != j_cnt:
print("No")
exit()
base2.sort()
current = 0
for i,p,j in sorted(filter(lambda x: x[1] <= 0 ,base2)):
if current < i:
print("No")
exit()
current -= i
current += j
base3 = []
for i,p,j in filter(lambda x: x[1] > 0 ,base2):
base3.append((p,i,j))
base3.sort()
for p,i,j in base3:
if current < i:
print("No")
exit()
current -= i
current += j
print("Yes")
|
python
| 14 | 0.415512 | 56 | 13.44 | 100 |
codenet
|
<?php
namespace app\shuozhuo_benyilipin\controller\web;
use wxsaas\controller\AddonsBaseController;
use wxsaas\model\Users;
use wxapp\aes\WXBizDataCrypt;
class LoginController extends AddonsBaseController
{
public function index()
{
$shop = new \shop\Test();
}
public function show(){
$appid = 'wx4f4bc4dec97d474b';
$sessionKey = '
$encryptedData = "
/
u0fjpXfz/YqYzBIBzD6WUfTIF9GRHpOn
/
C
/
20f0a04COwfneQAGGwd5oa+T8yO5hzuy
Db/XcxxmK01EpqOyuxINew==";
$iv = 'r7BXXKkLb8qrSNn05n0qiA==';
$pc = new WXBizDataCrypt($appid, $sessionKey);
$errCode = $pc->decryptData($encryptedData, $iv, $data);
if ($errCode == 0) {
var_dump($data);
} else {
var_dump($errCode);
}
}
}
|
php
| 13 | 0.524638 | 64 | 26.236842 | 38 |
starcoderdata
|
/*
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.layertools;
import java.io.File;
import java.nio.file.Paths;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.util.Assert;
/**
* Context for use by commands.
*
* @author
*/
class Context {
private final File jarFile;
private final File workingDir;
private String relativeDir;
/**
* Create a new {@link Context} instance.
*/
Context() {
this(new ApplicationHome().getSource(), Paths.get(".").toAbsolutePath().normalize().toFile());
}
/**
* Create a new {@link Context} instance with the specified value.
* @param jarFile the source jar file
* @param workingDir the working directory
*/
Context(File jarFile, File workingDir) {
Assert.state(jarFile != null && jarFile.isFile() && jarFile.exists()
&& jarFile.getName().toLowerCase().endsWith(".jar"), "Unable to find source JAR");
this.jarFile = jarFile;
this.workingDir = workingDir;
this.relativeDir = deduceRelativeDir(jarFile.getParentFile(), this.workingDir);
}
private String deduceRelativeDir(File sourceFolder, File workingDir) {
String sourcePath = sourceFolder.getAbsolutePath();
String workingPath = workingDir.getAbsolutePath();
if (sourcePath.equals(workingPath) || !sourcePath.startsWith(workingPath)) {
return null;
}
String relativePath = sourcePath.substring(workingPath.length() + 1);
return (relativePath.length() > 0) ? relativePath : null;
}
/**
* Return the source jar file that is running in tools mode.
* @return the jar file
*/
File getJarFile() {
return this.jarFile;
}
/**
* Return the current working directory.
* @return the working dir
*/
File getWorkingDir() {
return this.workingDir;
}
/**
* Return the directory relative to {@link #getWorkingDir()} that contains the jar or
* {@code null} if none relative directory can be deduced.
* @return the relative dir ending in {@code /} or {@code null}
*/
String getRelativeJarDir() {
return this.relativeDir;
}
}
|
java
| 13 | 0.714827 | 96 | 27.354839 | 93 |
starcoderdata
|
def delete_duplicate_segments(segments):
new_segment_list = []
for segment in segments:
to_add = True
start = segment.get_start()
end = segment.get_end()
for other_segment in new_segment_list:
duplicate = False
#Checks if the endpoints match
if ehm.compare_points(other_segment.get_start(), start, 0.4) and \
ehm.compare_points(other_segment.get_end(), end, 0.4):
duplicate = True
elif ehm.compare_points(other_segment.get_start(), end, 0.4) and \
ehm.compare_points(other_segment.get_end(), start, 0.4):
duplicate = True
if duplicate:
to_add = False
if to_add:
new_segment_list.append(segment)
#Attracts the endpoints of the line segments together after removing duplicates, since duplicates interfere with this process
attract_endpoints(new_segment_list)
return new_segment_list
|
python
| 14 | 0.593439 | 129 | 40.958333 | 24 |
inline
|
<?php
namespace Drupal\Core\Access;
use Drupal\Component\Utility\ArgumentsResolver;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* Resolves the arguments to pass to an access check callable.
*/
class AccessArgumentsResolverFactory implements AccessArgumentsResolverFactoryInterface {
/**
* {@inheritdoc}
*/
public function getArgumentsResolver(RouteMatchInterface $route_match, AccountInterface $account, Request $request = NULL) {
$route = $route_match->getRouteObject();
// Defaults for the parameters defined on the route object need to be added
// to the raw arguments.
$raw_route_arguments = $route_match->getRawParameters()->all() + $route->getDefaults();
$upcasted_route_arguments = $route_match->getParameters()->all();
// Parameters which are not defined on the route object, but still are
// essential for access checking are passed as wildcards to the argument
// resolver. An access-check method with a parameter of type Route,
// RouteMatchInterface, AccountInterface or Request will receive those
// arguments regardless of the parameter name.
$wildcard_arguments = [$route, $route_match, $account];
if (isset($request)) {
$wildcard_arguments[] = $request;
}
return new ArgumentsResolver($raw_route_arguments, $upcasted_route_arguments, $wildcard_arguments);
}
}
|
php
| 11 | 0.735194 | 126 | 34.829268 | 41 |
starcoderdata
|
func (d *Driver) Verify(vReq interface{}) (*receipt.Receipt, error) {
verifyReq, ok := vReq.(*VerifyRequest)
if !ok {
return nil, e.ErrInternal{
Message: "vReq is not of type VerifyRequest",
}
}
// step 1: get transaction result
tranRes, err := d.getTranResult(verifyReq)
if err != nil {
return nil, err
}
payGateTranID, ok := tranRes["PayGateTranID"].(string)
if !ok {
return nil, e.ErrInternal{
Message: "PayGateTranID is not of type string",
}
}
// step 2: verify payment
err = d.verifyRequest(payGateTranID)
if err != nil {
return nil, err
}
// step 3: settlement payment
err = d.settlementRequest(payGateTranID)
if err != nil {
return nil, err
}
rec := receipt.NewReceipt(tranRes["rrn"].(string), d.GetDriverName())
rec.Detail("cardNumber", tranRes["payment"].(map[string]interface{})["cardNumber"].(string))
rec.Detail("transactionId", tranRes["payment"].(map[string]interface{})["refID"].(string))
return rec, nil
}
|
go
| 12 | 0.679089 | 93 | 26.628571 | 35 |
inline
|
#include<bits/stdc++.h>
#define REP(i,n) for(int i=0,i##_len=(n);i<i##_len;++i)
#define int long long
using namespace std;
typedef pair<int,int> P;
signed main(){
int N;
cin>>N;
vector<string> S(N);
vector<int> p(N);
REP(i,N) cin>>S[i]>>p[i];
vector<int> ord(N);
iota(ord.begin(),ord.end(),0);
sort(ord.begin(),ord.end(),
[&](int x,int y){
if(S[x]!=S[y])return S[x]<S[y];
else return p[x]>p[y];
}
);
REP(i,N) cout<<ord[i]+1<<endl;
}
|
c++
| 14 | 0.500967 | 55 | 22.545455 | 22 |
codenet
|
using RegexParser.Nodes;
namespace RegexParser
{
///
/// RegexTree is a wrapper for a RegexNode tree.
///
public class RegexTree
{
public RegexNode Root { get; }
public RegexTree(RegexNode root)
{
Root = root;
}
}
}
|
c#
| 10 | 0.550489 | 52 | 17.117647 | 17 |
starcoderdata
|
package api;
import javafx.scene.image.Image;
/**
*
* @author 3/29/18
*
* Interface for determining image/object intersections
*/
public interface Intersect {
/**
* Method for determining if two images overlap
*
* @param otherImage:
* @return boolean: true if the images are overlapping, false otherwise
*/
public boolean overlap(Image otherImage);
}
|
java
| 6 | 0.652812 | 75 | 18.47619 | 21 |
starcoderdata
|
from assemblyline import odm
from assemblyline.common import forge
Classification = forge.get_classification()
ACL = {"R", "W", "E"}
USER_TYPES = {"admin", "signature_manager", "signature_importer", "user"}
@odm.model(index=False, store=False)
class ApiKey(odm.Model):
acl = odm.List(odm.Enum(values=ACL)) # Access control list for the apikey
password = odm.Keyword() # BCrypt hash of the password for the apikey
@odm.model(index=True, store=True)
class User(odm.Model):
agrees_with_tos = odm.Optional(odm.Date(index=False, store=False)) # Date the user agree with terms of service
api_quota = odm.Integer(default=10, store=False) # Max number of concurrent API requests
apikeys = odm.Mapping(odm.Compound(ApiKey), default={},
index=False, store=False) # Mapping of api keys
can_impersonate = odm.Boolean(default=False, index=False,
store=False) # Allowed to query on behalf of others
classification = odm.Classification(
is_user_classification=True, copyto="__text__",
default=Classification.UNRESTRICTED) # Max classification for the user
dn = odm.Optional(odm.Keyword(store=False, copyto="__text__")) # User ldap DN
email = odm.Optional(odm.Keyword(copyto="__text__")) # User's email address
groups = odm.List(odm.Keyword(), copyto="__text__",
default=["USERS"]) # List of groups the user submits to
is_active = odm.Boolean(default=True) # is the user active
name = odm.Keyword(copyto="__text__") # Full name of the user
otp_sk = odm.Optional(odm.Keyword(index=False, store=False)) # Secret key to generate one time passwords
password = odm.Keyword(index=False, store=False) # BCrypt hash of the user's password
submission_quota = odm.Integer(default=5, store=False) # Maximum number of concurrent submissions
type = odm.List(odm.Enum(values=USER_TYPES), default=['user']) # Type of user
security_tokens = odm.Mapping(odm.Keyword(), index=False,
store=False, default={}) # Map of security tokens
uname = odm.Keyword(copyto="__text__") # Username
|
python
| 12 | 0.580826 | 117 | 64.605263 | 38 |
starcoderdata
|
import path from 'path'
import fs from 'fs-extra'
import { pd as beautify } from 'pretty-data'
import rewriteRoot from '../root'
import serialize from '../serialize'
import generateImportCode from '../import'
import {
relativePath,
normalizePath
} from '../../../../utils'
export default function rewriter (pagePath, nodes, imports, styleCode, options) {
if (!fs.existsSync(pagePath)) {
const importTemplateCode = generateImportCode(imports, options)
const templateCode = beautify.xml(rewriteRoot(serialize(nodes), true))
const folder = path.join(pagePath, '..')
const files = ['polyfill' + options.ext.wxss, 'app' + options.ext.wxss]
const importCode = files.map(file => {
return `@import '${normalizePath(relativePath(folder, path.join(options.output, file)))}';`
}).join('\r\n')
return `${importTemplateCode}
${templateCode}
${importCode}
${styleCode}
Template({
props: ['data'],
onInit() {
this.setPropsData(this.data)
this.$watch('data','handlePropsData')
},
setPropsData(data){
data&&Object.keys(data).forEach(key => this.$set(key, data[key]))
},
handlePropsData(newVal,oldVal){
this.setPropsData(newVal)
}
},{
module: module,
exports: exports,
$app_require$: $app_require$
})
`
}
}
|
javascript
| 24 | 0.65593 | 97 | 24.773585 | 53 |
starcoderdata
|
@Override
public OutputStream getOutputStream() {
FileOutputStream fos = null; // Stream to write to
try {
fos = new FileOutputStream("C:/DEV/" + fileName);
} catch (final java.io.FileNotFoundException e) {
new Notification("Could not open file<br/>", e.getMessage(),
Notification.Type.ERROR_MESSAGE)
.show(Page.getCurrent());
return null;
}
return fos;
}
|
java
| 12 | 0.480804 | 76 | 40.230769 | 13 |
inline
|
//
// InnoDrmDataSource.h
// InnoPlayer_iOS_SDK
//
// Created by on 10/08/21.
// Copyright © 2021 MNC Innovation Center. All rights reserved.
//
#import
@protocol InnoDrmDataSource
/**
* Called when the InnoPlayer need content id for DRM content
*/
- (void)fetchContentIdentifierForRequest:(NSURL *)requestURL;
/**
* Called when the InnoPlayer need certificate for DRM content
*/
- (void)fetchCertificateForRequest:(NSURL *)requestURL;
/**
* Called when the InnoPlayer need content key for DRM content
*/
- (void)fetchContentKeyWithRequest:(NSData *)requestSPC;
@end
|
c
| 8 | 0.744957 | 77 | 22.931034 | 29 |
starcoderdata
|
PowerGym.Prefabs.MenuLvlOptions = function(game, lvlNum, okCallback, cancelCallback) {
var isMobile = !game.game.device.desktop || PowerGym.UserData.forceMobile;
this.window = game.add.group(game.world, "menuLvlOptionsWindow");
game.add.sprite(0, 0, "menuLvlOptionsBg", 0, this.window);
if (lvlNum == 1 || lvlNum == 2) {
var btnOk = game.add.button(0, 0, "btnOk", okCallback, game, 1, 0, 2, 0, this.window),
btnCancel = game.add.button(0, 0, "btnCancel", cancelCallback, game, 1, 0, 2, 0, this.window),
btnMargin = 10;
if (isMobile) {
btnOk.scale.set(1.4);
btnCancel.scale.set(1.4);
}
btnOk.x = this.window.width / 2 + btnMargin;
btnOk.y = this.window.height - this.window.height / 4;
btnCancel.x = this.window.width / 2 - btnCancel.width - btnMargin;
btnCancel.y = this.window.height - this.window.height / 4;
}
if (lvlNum == 1 || lvlNum == 2) {
if (lvlNum == 1 && typeof PowerGym.UserData.lvl1Difficulty == "undefined") {
PowerGym.UserData.lvl1Difficulty = 0;
}
if (lvlNum == 2 && typeof PowerGym.UserData.lvl2Difficulty == "undefined") {
PowerGym.UserData.lvl2Difficulty = 0;
}
// Weights
this._weights = [];
for (var i = 0; i < 3; i++) {
this._weights[i] = game.add.sprite(0, 0, "menuLvlOptionsLvl" + lvlNum + "Weights", i, this.window);
if (isMobile) {
this._weights[i].scale.set(1.4);
}
this._weights[i].x = this.window.width / 2 - this._weights[i].width / 2;
this._weights[i].y = isMobile ? (this.window.height / 9) * 3 : (this.window.height / 5) * 2;
if (lvlNum == 1) {
if (PowerGym.UserData.lvl1Difficulty != i) {
this._weights[i].visible = false;
}
} else if (lvlNum == 2) {
if (PowerGym.UserData.lvl2Difficulty != i) {
this._weights[i].visible = false;
}
}
}
}
if (lvlNum == 1 || lvlNum == 2) {
var leftArrowCallback, rightArrowCallback;
if (lvlNum == 1) {
leftArrowCallback = this.btnLeftArrowCallback1;
rightArrowCallback = this.btnRightArrowCallback1;
} else if (lvlNum == 2) {
leftArrowCallback = this.btnLeftArrowCallback2;
rightArrowCallback = this.btnRightArrowCallback2;
}
var btnLeftArrow = game.add.button(0, 0, "btnMenuLvlOptionsArrow", leftArrowCallback, this, 1, 0, 1, 0, this.window),
btnRightArrow = game.add.button(0, 0, "btnMenuLvlOptionsArrow", rightArrowCallback, this, 1, 0, 1, 0, this.window);
if (isMobile) {
btnLeftArrow.scale.set(1.4);
btnRightArrow.scale.set(1.4);
}
btnLeftArrow.anchor.y = 0.5;
btnLeftArrow.anchor.x = 1;
btnLeftArrow.x = btnCancel.left - 30;
btnLeftArrow.y = (this.window.height / 8) * 3;
btnRightArrow.anchor.y = 0.5;
btnRightArrow.anchor.x = 0.9; // turetų būt 1 bet turbūt nelygios rodyklės
btnRightArrow.x = btnOk.right + 30;
btnRightArrow.y = (this.window.height / 8) * 3;
btnRightArrow.rotation = Math.PI;
}
};
PowerGym.Prefabs.MenuLvlOptions.prototype = {
update: function() {
},
destroy: function() {
this.window.destroy();
},
btnLeftArrowCallback1: function() {
var nextIndex = PowerGym.UserData.lvl1Difficulty - 1;
if (nextIndex >= 0) {
this._weights[PowerGym.UserData.lvl1Difficulty].visible = false;
this._weights[nextIndex].visible = true;
PowerGym.UserData.lvl1Difficulty = nextIndex;
}
},
btnRightArrowCallback1: function() {
var nextIndex = PowerGym.UserData.lvl1Difficulty + 1;
if (nextIndex < this._weights.length) {
this._weights[PowerGym.UserData.lvl1Difficulty].visible = false;
this._weights[nextIndex].visible = true;
PowerGym.UserData.lvl1Difficulty = nextIndex;
}
},
btnLeftArrowCallback2: function() {
var nextIndex = PowerGym.UserData.lvl2Difficulty - 1;
if (nextIndex >= 0) {
this._weights[PowerGym.UserData.lvl2Difficulty].visible = false;
this._weights[nextIndex].visible = true;
PowerGym.UserData.lvl2Difficulty = nextIndex;
}
},
btnRightArrowCallback2: function() {
var nextIndex = PowerGym.UserData.lvl2Difficulty + 1;
if (nextIndex < this._weights.length) {
this._weights[PowerGym.UserData.lvl2Difficulty].visible = false;
this._weights[nextIndex].visible = true;
PowerGym.UserData.lvl2Difficulty = nextIndex;
}
}
}
|
javascript
| 20 | 0.637124 | 123 | 29.503448 | 145 |
starcoderdata
|
/*
* *
* * Created by on 2021
* * Copyright (c). All rights reserved.
* * Last modified 22.01.21 0:15
* بِسْمِ ٱللّٰهِ ٱلرَّحْمَٰنِ ٱلرَّحِيم *
*
*/
package com.aid.moneymanager.ui.main;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import com.aid.moneymanager.ui.main.history.HistoryFragment;
import com.aid.moneymanager.ui.main.home.HomeFragment;
import com.aid.moneymanager.ui.main.statistics.StatistikaFragment;
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private static int TAB_SON =3;
public ViewPagerAdapter(@NonNull FragmentManager fm) {
super(fm);
}
@NonNull
@Override
public Fragment getItem(int position) {
switch (position){
case 0:
return HomeFragment.newInstance();
case 1:
return HistoryFragment.newInstance();
case 2:
return StatistikaFragment.newInstance();
}
return null;
}
@Override
public int getCount() {
return TAB_SON;
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return HomeFragment.TITLE;
case 1:
return HistoryFragment.TITLE;
case 2:
return StatistikaFragment.TITLE;
}
return super.getPageTitle(position);
}
}
|
java
| 11 | 0.635161 | 66 | 25.45 | 60 |
starcoderdata
|
package party.lemons.biomemakeover.entity.render.feature;
import net.minecraft.client.render.LightmapTextureManager;
import net.minecraft.client.render.VertexConsumerProvider;
import net.minecraft.client.render.entity.MobEntityRenderer;
import net.minecraft.client.render.entity.feature.FeatureRenderer;
import net.minecraft.client.render.entity.feature.FeatureRendererContext;
import net.minecraft.client.render.entity.model.VillagerResemblingModel;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.LightType;
import party.lemons.biomemakeover.BiomeMakeover;
import party.lemons.biomemakeover.entity.DecayedEntity;
import party.lemons.biomemakeover.entity.MushroomVillagerEntity;
import party.lemons.biomemakeover.entity.render.DecayedEntityModel;
public class MushroomVillagerOverlayFeatureRenderer extends FeatureRenderer<MushroomVillagerEntity, VillagerResemblingModel
{
private static final Identifier TEXTURE = BiomeMakeover.ID("textures/entity/mushrooming_trader_outer.png");
private final VillagerResemblingModel model = new VillagerResemblingModel(0);
public MushroomVillagerOverlayFeatureRenderer(MobEntityRenderer<MushroomVillagerEntity, VillagerResemblingModel featureRendererContext) {
super(featureRendererContext);
}
public void render(MatrixStack matrixStack, VertexConsumerProvider vertexConsumerProvider, int i, MushroomVillagerEntity e, float f, float g, float h, float j, float k, float l) {
BlockPos blockPos = new BlockPos(e.method_31166(f));
int light = LightmapTextureManager.pack(e.isOnFire() ? 15 : e.world.getLightLevel(LightType.BLOCK, blockPos), e.world.getLightLevel(LightType.SKY, blockPos));
render(this.getContextModel(), this.model, TEXTURE, matrixStack, vertexConsumerProvider, light, e, f, g, j, k, l, h, 1.0F, 1.0F, 1.0F);
}
}
|
java
| 11 | 0.839097 | 180 | 60.235294 | 34 |
starcoderdata
|
package dev._2lstudios.teams.listeners;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityCombustByEntityEvent;
import dev._2lstudios.teams.managers.TeamPlayerManager;
import dev._2lstudios.teams.managers.TeamManager;
import dev._2lstudios.teams.managers.TeamsManager;
import dev._2lstudios.teams.team.TeamPlayer;
import dev._2lstudios.teams.team.Team;
public class EntityCombustByEntityListener implements Listener {
private final TeamManager teamManager;
private final TeamPlayerManager tPlayerManager;
public EntityCombustByEntityListener(TeamsManager teamsManager) {
this.teamManager = teamsManager.getTeamManager();
this.tPlayerManager = teamsManager.getTeamPlayerManager();
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onEntityCombustByEntity(EntityCombustByEntityEvent event) {
Entity entity = event.getEntity();
if (entity instanceof Player) {
Entity combuster = event.getCombuster();
if (combuster instanceof Player) {
Player damager = (Player) combuster;
TeamPlayer teamPlayer = this.tPlayerManager.getPlayer(entity.getName());
TeamPlayer teamPlayer1 = this.tPlayerManager.getPlayer(damager.getName());
if (teamPlayer != null && teamPlayer1 != null) {
String teamName = teamPlayer.getTeam();
Team team = this.teamManager.getTeam(teamName);
if (team != null && !team.isPvp() && teamName.equals(teamPlayer1.getTeam()))
event.setCancelled(true);
}
}
}
}
}
|
java
| 16 | 0.75084 | 86 | 39.590909 | 44 |
starcoderdata
|
package br.edu.ifba.wmobile.huehue.produtos.compras;
import java.util.ArrayList;
import java.util.List;
public class Compras implements ICompras {
private double valorDaCompra;
private String produto;
public Compras(double valorDaCompra, String produto){
this.valorDaCompra = valorDaCompra;
this.produto = produto;
}
@Override
public List getNome() {
List itens = new ArrayList
itens.add(this.produto);
return itens;
}
@Override
public double getPreco() {
return this.valorDaCompra;
}
}
|
java
| 10 | 0.716753 | 54 | 18.965517 | 29 |
starcoderdata
|
"""A spectral clusterer class to perform clustering."""
import numpy as np
from spectralcluster import base_spectral_clusterer
from spectralcluster import custom_distance_kmeans
from spectralcluster import utils
class SpectralClusterer(base_spectral_clusterer.BaseSpectralClusterer):
"""Spectral clustering class."""
def __init__(self,
min_clusters=None,
max_clusters=None,
refinement_options=None,
laplacian_type=None,
stop_eigenvalue=1e-2,
row_wise_renorm=False,
custom_dist="cosine",
max_iter=300
):
"""Constructor of the clusterer.
Args:
min_clusters: minimal number of clusters allowed (only effective if not
None)
max_clusters: maximal number of clusters allowed (only effective if not
None), can be used together with min_clusters to fix the number of
clusters
refinement_options: a RefinementOptions object that contains refinement
arguments for the affinity matrix
laplacian_type: str. "unnormalized", "graph_cut", or "random_walk". if
"unnormalized", compute the unnormalied laplacian. if "graph_cut",
compute the graph cut view normalized laplacian, D^{-1/2}LD^{-1/2}. if
"random_walk", compute the random walk view normalized laplacian,
D^{-1}L. If None, we do not use a laplacian matrix
stop_eigenvalue: when computing the number of clusters using Eigen Gap, we
do not look at eigen values smaller than this value
row_wise_renorm: if True, perform row-wise re-normalization on the
spectral embeddings
custom_dist: str or callable. custom distance measure for k-means. if a
string, "cosine", "euclidean", "mahalanobis", or any other distance
functions defined in scipy.spatial.distance can be used
max_iter: the maximum number of iterations for the custom k-means
."""
super().__init__(
min_clusters=min_clusters,
max_clusters=max_clusters,
refinement_options=refinement_options,
laplacian_type=laplacian_type,
stop_eigenvalue=stop_eigenvalue,
row_wise_renorm=row_wise_renorm,
custom_dist=custom_dist,
max_iter=max_iter)
def predict(self, embeddings, output_centers=False):
"""Perform spectral clustering on data embeddings.
The spectral clustering is performed on an affinity matrix.
Args:
embeddings: numpy array of shape (n_samples, n_features)
output_centers: bool whether the centroids should be returned
Returns:
labels: numpy array of shape (n_samples,)
Raises:
TypeError: if embeddings has wrong type
ValueError: if embeddings has wrong shape
"""
if not isinstance(embeddings, np.ndarray):
raise TypeError("embeddings must be a numpy array")
if len(embeddings.shape) != 2:
raise ValueError("embeddings must be 2-dimensional")
# Compute affinity matrix.
affinity = utils.compute_affinity_matrix(embeddings)
if self.refinement_options:
# Perform refinement operations on the affinity matrix.
for refinement_name in self.refinement_options.refinement_sequence:
op = self._get_refinement_operator(refinement_name)
affinity = op.refine(affinity)
if not self.laplacian_type:
# Perform eigen decomposion.
(eigenvalues, eigenvectors) = utils.compute_sorted_eigenvectors(affinity)
# Get number of clusters.
k = utils.compute_number_of_clusters(
eigenvalues, self.max_clusters, self.stop_eigenvalue, descend=True)
if self.laplacian_type:
# Compute Laplacian matrix
laplacian_norm = utils.compute_laplacian(
affinity, lp_type=self.laplacian_type)
# Perform eigen decomposion. Eigen values are sorted in an ascending order
(eigenvalues, eigenvectors) = utils.compute_sorted_eigenvectors(
laplacian_norm, descend=False)
# Get number of clusters. Eigen values are sorted in an ascending order
k = utils.compute_number_of_clusters(
eigenvalues, self.max_clusters, descend=False)
if self.min_clusters is not None:
k = max(k, self.min_clusters)
# Get spectral embeddings.
spectral_embeddings = eigenvectors[:, :k]
if self.row_wise_renorm:
# Perfrom row wise re-normalization.
rows_norm = np.linalg.norm(spectral_embeddings, axis=1, ord=2)
spectral_embeddings = spectral_embeddings / np.reshape(
rows_norm, (spectral_embeddings.shape[0], 1))
# Run K-means on spectral embeddings.
return custom_distance_kmeans.run_kmeans(
spectral_embeddings,
n_clusters=k,
custom_dist=self.custom_dist,
max_iter=self.max_iter,
output_centers=output_centers,
)
|
python
| 15 | 0.676082 | 80 | 39.082645 | 121 |
starcoderdata
|
package controller;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import model.Booking;
import model.FoodDrink;
import model.Purchase;
import model.Transaction;
import service.repositories.BookingRepo;
import service.repositories.FoodDrinkRepo;
import service.repositories.PurchaseRepo;
import service.repositories.TransactionRepo;
import view.BookingTransactionView;
public class BookingTransactionController {
private TransactionRepo transactionRepo;
private BookingRepo bookingRepo;
private PurchaseRepo purchaseRepo;
private FoodDrinkRepo foodDrinkRepo;
private BookingTransactionView bookingTransactionView;
public BookingTransactionController() {
this.transactionRepo = TransactionRepo.getInstance();
this.bookingRepo = BookingRepo.getInstance();
this.purchaseRepo = PurchaseRepo.getInstance();
this.foodDrinkRepo = FoodDrinkRepo.getInstance();
this.bookingTransactionView = new BookingTransactionView();
}
public void addTransaction(Booking booking) {
List listPurchase = new ArrayList
int newID = 0;
long totalPayment = 0;
boolean satisfied = false;
while(!satisfied) {
// foodDrinkController.printFoodDrink();
int option = bookingTransactionView.chooseFood(foodDrinkRepo.getAllFoodDrink());
if(option==0) {
satisfied = true;
}
else {
FoodDrink foodDrink = foodDrinkRepo.getFoodDrinkById(option);
if(foodDrink==null) {
bookingTransactionView.wrongOption();
}
else {
int quantity = bookingTransactionView.enterQuantity();
Purchase newPurchase = new Purchase(foodDrink, quantity);
for(Purchase purchase : purchaseRepo.getAllPurchase()){
int tempID = purchase.getPurchaseNumber();
if(tempID>newID){
newID = tempID;
}
}
newPurchase.setPurchaseNumber(newID+1);
newPurchase.setPurchaseTime(LocalDateTime.now());
totalPayment += foodDrink.getItemPrice()*quantity;
listPurchase.add(newPurchase);
purchaseRepo.insertPurchase(newPurchase);
}
}
}
newID = 0;
for(Transaction transactionTemp : transactionRepo.getAllTransaction()){
int tempID = transactionTemp.getTransactionNumber();
if(tempID>newID){
newID = tempID;
}
}
if(bookingTransactionView.hasMembership()) {
long discount = (totalPayment * 20)/100;
totalPayment -= discount;
}
Transaction newTransaction = new Transaction(newID+1, totalPayment,
LocalDateTime.now(), booking, listPurchase);
transactionRepo.insertTransaction(newTransaction);
}
public void printAllTransactions() {
bookingTransactionView.printAllTransactions(transactionRepo.getAllTransaction());
}
}
|
java
| 17 | 0.71293 | 83 | 32.093023 | 86 |
starcoderdata
|
#include "tree.h"
#include
int main()
{
struct avltree* root = NULL;
for (int i = 1; i < 131080; i++)
{
root = avltree_insert(root, i);
}
AVLtree_print(root);
printf("\n");
deleteNode(root, 2);
AVLtree_print(root);
printf("\n");
struct avltree* temp1 = avltree_lookup(root, 65536);
printf("%d\n", AVLTree_height(temp1));
struct avltree* temp2 = avltree_lookup(root, 131079);
printf("%d\n", AVLTree_height(temp2));
return 0;
}
|
c
| 9 | 0.577899 | 57 | 23.227273 | 22 |
starcoderdata
|
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Beffyman.AspNetCore.Client.Generator.SignalR
{
public class MessageDefinition
{
public string Name { get; }
public IEnumerable Types { get; }
public MessageDefinition(AttributeSyntax attribute)
{
if (attribute.ArgumentList.Arguments.Count == 1)//Only HTTP value was provided, assumed to have no body
{
Name = attribute.ArgumentList.Arguments.SingleOrDefault().ToFullString().TrimQuotes();
Types = Enumerable.Empty
}
else//Has 2 or more arguments, parse rest as types
{
Name = attribute.ArgumentList.Arguments.FirstOrDefault().ToFullString().TrimQuotes();
Types = attribute.ArgumentList.Arguments.Skip(1).Select(x => x.ToFullString().Replace("typeof", "").Trim().TrimStart('(').TrimEnd(')'));
}
}
public override string ToString()
{
return $"{Name} {string.Join(", ", Types)}";
}
}
}
|
c#
| 25 | 0.728519 | 140 | 31.176471 | 34 |
starcoderdata
|
inline int EAMainShutdown(int errorCount)
{
static bool sEAMainShutdown_ShutdownHandled = false;
if(!sEAMainShutdown_ShutdownHandled)
{
sEAMainShutdown_ShutdownHandled = true;
// Handle the application specific exit code.
//
#if defined(EA_PLATFORM_IPHONE)
// Get test result. (iOS 5 bug prevents iPhone Runner from getting this from the exit code)
if (errorCount == 0)
Report("\nAll tests completed successfully.\n");
else
Report("\nTests failed. Total error count: %d\n", errorCount);
fflush(stdout);
#endif
#if !defined(EA_PLATFORM_DESKTOP) && !defined(EA_PLATFORM_SERVER) // TODO: change define to something related to the StdC library used on the system.
fflush(stdout);
#endif
// Required so the EAMainPrintServer can terminate with the correct error code.
//
EA::EAMain::Report("RETURNCODE=%d\n", errorCount);
// Shutdown the EAMain print manager.
//
EA::EAMain::PrintManager::Instance().Shutdown();
}
return errorCount;
}
|
c++
| 12 | 0.482265 | 171 | 42.147059 | 34 |
inline
|
package eu.fox7.rexp.isc.experiment4;
import eu.fox7.rexp.data.CharSymbol;
import eu.fox7.rexp.data.Symbol;
import eu.fox7.rexp.data.UniSymbolWord;
import eu.fox7.rexp.data.Word;
import eu.fox7.rexp.isc.analysis.corejobs.Director;
import eu.fox7.rexp.isc.cnfa.core.Cnfa;
import eu.fox7.rexp.isc.experiment.MemoryMeasurer;
import eu.fox7.rexp.isc.experiment4.IncEval.DoubleAggregator;
import eu.fox7.rexp.isc.experiment4.algo.*;
import eu.fox7.rexp.isc.experiment4.db.CsvHelper;
import eu.fox7.rexp.isc.experiment4.db.PostProcessor;
import eu.fox7.rexp.isc.experiment4.util.DirectOutputter;
import eu.fox7.rexp.isc.experiment4.util.Outputter;
import eu.fox7.rexp.isc.experiment4.util.TeeAppendable;
import eu.fox7.rexp.regexp.base.RegExp;
import eu.fox7.rexp.regexp.core.Counter;
import eu.fox7.rexp.regexp.core.ReSymbol;
import eu.fox7.rexp.tree.nfa.lw.LwNfa;
import eu.fox7.rexp.util.FileX;
import eu.fox7.rexp.util.RefHolder;
import eu.fox7.rexp.util.UtilX;
import eu.fox7.rexp.util.mini.Callback;
import eu.fox7.rexp.util.mini.Transform;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.sql.SQLException;
import java.util.*;
import java.util.concurrent.Callable;
public class ScratchEval {
public static void main(String[] args) throws IOException {
Director.setup();
List xs0 = new ArrayList
List xs1 = new ArrayList
List xs2 = new ArrayList
Integer[] a0 = {10000, 100000, 1000000};
Integer[] a1 = {1000,};
Integer[] a2 = {6, 10, 20, 40, 60, 80, 100,};
xs0.addAll(Arrays.asList(a0));
xs1.addAll(Arrays.asList(a1));
xs2.addAll(Arrays.asList(a2));
java.util.Collections.reverse(xs0);
java.util.Collections.reverse(xs1);
java.util.Collections.reverse(xs2);
Execution executions0 = new Execution
CNFA_INC_SEQ,
NFA_SIM,
CNFA_SIM,
};
Execution executions1 = new Execution
NFA_INC_SEQ,
CNFA_INC_SEQ,
NFA_SIM,
CNFA_SIM,
};
Execution executions2 = new Execution
NFA_INC_SEQ,
CNFA_INC_SEQ,
NFA_SIM,
CNFA_SIM,
RE_SHARP,
};
final Transform<Integer, Integer> R = new NonLinearReps(5000.d);
final Input[] inputs = {
new Input(xs0, Arrays.asList(executions0)),
new Input(xs1, Arrays.asList(executions1)),
new Input(xs2, Arrays.asList(executions2)),
};
String FULL1_FILE1 = "./analysis/bench_fest.csv";
if (!(args.length > 0 && args[0].equals("b"))) {
ScratchEval.withAppender(FULL1_FILE1, new Callback {
@Override
public void call(Appendable tee) {
ScratchEval o = new ScratchEval(tee, Arrays.asList(inputs), R);
o.execute();
}
});
}
String FULL1_FILE2 = "./analysis/bench_fest_t.csv";
final String inFileName = FULL1_FILE1;
final String outputFileName = FULL1_FILE2;
if (!(args.length > 0 && args[0].equals("a"))) {
ScratchEval.withAppender(outputFileName, new Callback {
@Override
public void call(Appendable tee) {
File inFile = FileX.newFile(inFileName);
try {
PostProcessor.process(tee, inFile, CsvHelper.TAB, PostProcessor.FULL_QUERY1);
} catch (SQLException ex) {
throw new RuntimeException(ex);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
});
}
}
static final Symbol s = new CharSymbol('a');
static final ReSymbol rs = new ReSymbol(s);
private static final SanityChecker sanityChecker = CounterSanityChecker.INSTANCE;
private final List inputs;
private Transform<Integer, Integer> rep;
private Outputter outputter;
private List boundExecutors;
public static final Execution CNFA_SIM = new Execution CnfaSim());
public static final Execution RE_SHARP = new Execution ReSharp());
public static final Execution RE_SHARP_TR = new Execution ReSharp2());
public static final Execution NFA_SIM = new Execution NfaSim());
public static final Execution CNFA_INC = new Execution CnfaInc());
public static final Execution NFA_INC = new Execution NfaInc());
public static final Execution CNFA_INC_SEQ = new Execution CnfaIncSeq());
public static final Execution NFA_INC_SEQ = new Execution NfaIncSeq());
public ScratchEval(Appendable appendable, List inputs, Transform<Integer, Integer> rep) {
this.inputs = inputs;
this.rep = rep;
outputter = new DirectOutputter(appendable);
boundExecutors = new ArrayList
}
public void execute() {
for (Input input : inputs) {
for (int x : input.getValues()) {
generateTests(x, input.getExecutions());
}
}
System.out.println("----------------");
for (BoundExecutor e : boundExecutors) {
MemoryMeasurer.gc();
e.execute();
}
}
void generateTests(int x, List executions) {
int k = 3 * x / 4;
int l = 5 * x / 4;
generateTest(x, k, l, k - 1, "A", executions);
generateTest(x, k, l, k, "B", executions);
generateTest(x, k, l, x, "C", executions);
generateTest(x, k, l, l, "D", executions);
generateTest(x, k, l, l + 1, "E", executions);
}
void generateTest(int x, int k, int l, int n, String tag, List executions) {
RegExp c = new Counter(rs, k, l);
Word w = new UniSymbolWord(s, n);
Map<Object, Object> output = new LinkedHashMap<Object, Object>();
int r = rep.transform(x);
output.put("x", x);
output.put("k", k);
output.put("l", l);
output.put("n", n);
output.put("r", r);
output.put("TAG", tag);
for (Execution e : executions) {
ParamBundle b = new ParamBundle(c, w, sanityChecker, output, r, outputter);
boundExecutors.add(new BoundExecutor(e, b));
}
}
public static class ConstantReps implements Transform<Integer, Integer> {
private final int i;
public ConstantReps(int i) {
this.i = i;
}
@Override
public Integer transform(Integer data) {
return i;
}
}
public static class NonLinearReps implements Transform<Integer, Integer> {
private final double d;
public NonLinearReps(double d) {
this.d = d;
}
@Override
public Integer transform(Integer data) {
return calculate(data, d);
}
public static int calculate(int x, double d) {
return (int) Math.max(Math.round((1.d / x) * d), 1L);
}
}
private static final DoubleAggregator aggregator = IncEval.TRIM_ARITHMETIC_MEAN;
public static T measure(Callable c, int rep, RefHolder average, T nullValue) {
try {
T r = nullValue;
long t1, t2;
aggregator.init(rep);
for (int i = 0; i < rep; i++) {
t1 = System.nanoTime();
r = c.call();
t2 = System.nanoTime();
aggregator.submit(t2 - t1);
}
if (rep > 0) {
average.set(aggregator.get());
}
return r;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public static void addRange(List points, int low, int high, int step) {
if (step <= 0) {
throw new IllegalArgumentException("step <= 0");
}
for (int i = low; i <= high; i += step) {
points.add(i);
}
}
protected static void withAppender(String outputFileName, Callback callback) throws IOException {
FileOutputStream fos = null;
try {
File outFile = FileX.newFile(outputFileName);
outFile.createNewFile();
fos = new FileOutputStream(outFile);
PrintStream ps = new PrintStream(fos, true, "UTF-8");
Appendable tee = new TeeAppendable(System.out, ps);
callback.call(tee);
} finally {
UtilX.silentClose(fos);
}
}
}
|
java
| 18 | 0.685037 | 110 | 28.839844 | 256 |
starcoderdata
|
<?php
use App\Http\Controllers\Admin\AdminController;
use App\Http\Controllers\Admin\AssignController;
use App\Http\Controllers\Admin\HomeController as HomeAdmin;
use App\Http\Controllers\Admin\ScheduleController;
use App\Http\Controllers\Admin\StatisticController;
use App\Http\Controllers\Admin\StudentController;
use App\Http\Controllers\Admin\TeacherController;
use App\Http\Controllers\Auth\ChangePasswordController;
use App\Http\Controllers\Auth\LoginController;
use App\Http\Controllers\Auth\ProfileController;
use App\Http\Controllers\ClassroomController;
use App\Http\Controllers\GradeController;
use App\Http\Controllers\HomeController as Home;
use App\Http\Controllers\LessonController;
use App\Http\Controllers\SubjectController;
use App\Http\Controllers\Teacher\AttendanceController;
use App\Http\Controllers\Teacher\HomeController as HomeTeacher;
use App\Http\Controllers\Teacher\WorkController;
use App\Http\Controllers\YearSchoolController;
use App\Http\Controllers\Admin\Schedule\ScheduleExport;
use App\Models\Assign;
use App\Models\Attendance;
use App\Models\Grade;
use App\Models\Student;
use App\Models\Teacher;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
// chi danh cho user(admin,teacher)
Route::middleware(['auth:admin,teacher', 'isActive'])->group(function() {
// logout
Route::get('/logout', [LoginController::class, 'logout'])->name('logout');
//profile
Route::name('profile.')->group(function() {
// show profile
Route::get('/profile', [ProfileController::class, 'show'])
->name('show');
// update profile
Route::put('/profile', [ProfileController::class, 'update'])
->name('update');
});
// change password
Route::put('/password', [ChangePasswordController::class, 'changePassword'])
->name('password');
});
// chi danh cho admin
Route::middleware(['auth:admin', 'isActive'])->group(function() {
Route::prefix('admin')->name('admin.')->group(function() {
// dashboard
Route::get('', [HomeAdmin::class, 'index'])
->name('dashboard');
Route::resource('yearschool', YearSchoolController::class);
Route::resource('grade', GradeController::class);
Route::resource('subject', SubjectController::class);
Route::resource('classroom', ClassroomController::class);
// manager teacher
// import
Route::get('teacher-manager/import', [
TeacherController::class, 'showFormImport'
])->name('teacher-manager.form_import');
Route::post('teacher-manager/import', [
TeacherController::class, 'importExcel'
])->name('teacher-manager.import_excel');
// export
Route::get('teacher-manager/export', [
TeacherController::class, 'exportExcel'
])->name('teacher-manager.export_excel');
Route::resource('teacher-manager', TeacherController::class)
->middleware('preventCache');
// manager admin
// import
Route::get('admin-manager/import', [
AdminController::class, 'showFormImport'
])->name('admin-manager.form_import');
Route::post('admin-manager/import', [
AdminController::class, 'importExcel'
])->name('admin-manager.import_excel');
// export
Route::get('admin-manager/export', [
AdminController::class, 'exportExcel'
])->name('admin-manager.export_excel');
Route::resource('admin-manager', AdminController::class)
->middleware(['isSuper', 'preventCache']);
Route::resource('lesson', LessonController::class);
// STUDENT
// import
Route::get('student-manager/import', [
StudentController::class, 'showFormImport'
])->name('student-manager.form_import');
Route::post('student-manager/import', [
StudentController::class, 'importExcel'
])->name('student-manager.import_excel');
// export
Route::get('student-manager/export', [
StudentController::class, 'exportExcel'
])->name('student-manager.export_excel');
Route::resource('student-manager', StudentController::class)
->middleware('preventCache');
// assign
Route::resource('assign', AssignController::class);
// schedule
Route::resource('schedule', ScheduleController::class);
Route::get('scheduleIndexAll', [ScheduleController::class, 'indexAll'])->name('schedule.indexAll');
Route::get('scheduleIndexTeacher', [ScheduleController::class, 'indexTeacher'])->name('schedule.indexTeacher');
Route::get('scheduleIndexClass', [ScheduleController::class, 'indexClass'])->name('schedule.indexClass');
Route::POST('schedule.ajax', [ScheduleController::class, 'requestAjax'])->name('schedule.requestAjax');
Route::POST('schedule.update.ajax', [ScheduleController::class, 'updateMultiSchedule'])->name('schedule.updateMultiSchedule');
Route::GET('schedule.export.signal/{id}', [ScheduleExport::class, 'exportForClass'])->name('schedule.export.signal');
Route::POST('schedule.export.multiple', [ScheduleExport::class, 'exportMultipleForClass'])->name('schedule.export.multiple');
// thong ke
Route::prefix('statistic')->name('statistic.')->group(function() {
Route::get('attendance', [StatisticController::class, 'attendance'])
->name('attendance');
Route::post('export', [StatisticController::class, 'exportExcel'])
->name('export');
Route::post('send-email', [StatisticController::class, 'sendEmail'])
->name('send_email');
});
});
});
// chi danh cho teacher
Route::middleware(['auth:teacher', 'isActive'])->group(function() {
Route::prefix('teacher')->name('teacher.')->group(function() {
Route::get('', [HomeTeacher::class, 'index'])
->name('dashboard');
// attendance
Route::get('attendance/history', [
AttendanceController::class, 'history'
])->name('attendance.history');
Route::post('attendance/history', [
AttendanceController::class, 'updatehistory'
])->name('attendance.update_history');
Route::resource('attendance', AttendanceController::class);
// work
Route::prefix('work')->name('work.')->group(function() {
Route::get('assign', [WorkController::class, 'assign'])
->name('assign');
Route::get('schedule', [WorkController::class, 'schedule'])
->name('schedule');
});
});
});
// route dang nhap
Route::prefix('login')->name('login.')->group(function() {
Route::get('admin', [LoginController::class, 'showAdminLoginForm'])
->name('admin_form');
Route::get('teacher', [LoginController::class, 'showTeacherLoginForm'])
->name('teacher_form');
Route::post('admin', [LoginController::class, 'adminLogin'])
->name('admin');
Route::post('teacher', [LoginController::class, 'teacherLogin'])
->name('teacher');
});
// home page (auth, guest)
Route::get('/', [Home::class, 'index'])->name('home');
// error
Route::prefix('error')->name('error.')->group(function() {
Route::view('401', 'errors.401')->name('401');
Route::view('403', 'errors.403')->name('403');
Route::view('404', 'errors.404')->name('404');
Route::view('419', 'errors.419')->name('419');
Route::view('429', 'errors.429')->name('429');
Route::view('500', 'errors.500')->name('500');
Route::view('503', 'errors.503')->name('503');
Route::view('', 'errors.custom')->name('custom');
});
// test
Route::get('/test', function() {
$grade = Grade::find(1);
$students = $grade->students;
$mails = $students->map(function($student) {
return $student->email;
})->toArray();
dd($mails);
});
|
php
| 27 | 0.624865 | 134 | 36 | 225 |
starcoderdata
|
namespace HealthCheckCLI.Models
{
public class Group : DataItem
{
}
}
|
c#
| 5 | 0.582418 | 33 | 12.142857 | 7 |
starcoderdata
|
import Ember from 'ember';
import ConfigurationMixin from 'gooru-web/mixins/configuration';
/**
* Class navigation
*
* Component responsible for enabling more flexible navigation options for the class.
* For example, where {@link class/gru-class-navigation.js}} allows access the class information and navigate through the menu options.
* @module
* @see controllers/class.js
* @augments ember/Component
*/
export default Ember.Component.extend(ConfigurationMixin, {
// -------------------------------------------------------------------------
// Dependencies
/**
* @requires service:session
*/
session: Ember.inject.service('session'),
// -------------------------------------------------------------------------
// Attributes
classNames: ['gru-class-navigation'],
// -------------------------------------------------------------------------
// Actions
actions: {
/**
*
* Triggered when an menu item is selected
* @param item
*/
selectItem: function(item) {
if (this.get('onItemSelected')) {
this.selectItem(item);
this.sendAction('onItemSelected', item);
}
},
/**
*
* Triggered when the Info icon is selected for sm and xs
* @param item
*/
showDescription: function() {
this.$('.greetings').toggleClass('in');
}
},
// -------------------------------------------------------------------------
// Events
/**
* DidInsertElement ember event
*/
didInsertElement: function() {
var item = this.get('selectedMenuItem');
this.selectItem(item);
},
// -------------------------------------------------------------------------
// Properties
teamsURL: Ember.computed('teamsURLs', function() {
const mappedHost = this.get('configurationService.configuration.teams.url');
const sessionToken = this.get('session.token-api3');
const classId = this.get('class.id');
return `${mappedHost}/#/integration/gooru?token=${sessionToken}&classId=${classId}`;
}),
/**
* @property {Class} class
*/
class: null,
/**
* @property {String|Function} onItemSelected - event handler for when an menu item is selected
*/
onItemSelected: null,
/**
* @property {String} selectedMenuItem - menu Item selected
*/
selectedMenuItem: null,
// -------------------------------------------------------------------------
// Observers
/**
* Refreshes the left navigation with the selected menu item
*/
refreshSelectedMenuItem: function() {
var item = this.get('selectedMenuItem');
this.selectItem(item);
}.observes('selectedMenuItem'),
// -------------------------------------------------------------------------
// Methods
/**
* Triggered when a menu item is selected. Set the class icon for the item selected showing in the mobiles dropdown menu.
* @param {string} item
*/
selectItem: function(item) {
var classIconItem = 'info';
if (item) {
var itemElement = `.${item}`;
this.$('.class-menu-item').removeClass('selected');
this.$(itemElement).addClass('selected');
}
switch (item) {
case 'overview':
classIconItem = 'dashboard';
break;
case 'analytics.performance':
classIconItem = 'graphic_eq';
break;
case 'teams':
classIconItem = 'group';
break;
case 'info':
classIconItem = 'info';
break;
}
this.set('iconClassMenuItem', classIconItem);
}
});
|
javascript
| 15 | 0.538198 | 135 | 26.40625 | 128 |
starcoderdata
|
def clean_string(string, sentence_droprate=0, max_length=5000):
"""
Performs tokenization and string cleaning
"""
if sentence_droprate > 0:
lines = [x for x in tokenize.sent_tokenize(string) if len(x) > 1]
lines_drop = [x for x in lines if random.randint(0, 100) > 100 * sentence_droprate]
string = ' '.join(lines_drop if len(lines_drop) > 0 else lines)
string = re.sub(r'[^A-Za-z0-9]', ' ', string)
string = re.sub(r'\s{2,}', ' ', string)
tokenized_string = string.lower().strip().split()
return tokenized_string[:min(max_length, len(tokenized_string))]
|
python
| 13 | 0.628478 | 91 | 46.076923 | 13 |
inline
|
#pragma once
#include "mull/ExecutionResult.h"
#include <optional>
#include <string>
#include <unordered_map>
#include <vector>
namespace mull {
class Diagnostics;
class Runner {
public:
explicit Runner(Diagnostics &diagnostics);
ExecutionResult runProgram(const std::string &program, const std::vector<std::string> &arguments,
const std::unordered_map<std::string, std::string> &environment,
long long int timeout, bool captureOutput, bool failSilently,
std::optional<std::string> optionalWorkingDirectory);
private:
Diagnostics &diagnostics;
};
} // namespace mull
|
c
| 10 | 0.665165 | 99 | 25.64 | 25 |
research_code
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from girder.constants import AccessType
from girder.exceptions import ValidationException
from girder.models.setting import Setting
from ..constants import PluginSettings
from .annotationparameters import AnnotationParameters
def _validateInt(value):
if not isinstance(value, int):
value = int(value)
return value
def _validateFloat(value):
if not isinstance(value, float):
value = float(value)
return value
class RNAScopeParameters(AnnotationParameters):
def _find(self, annotation, creator, **kwargs):
query = {
'annotationId': annotation['_id'],
'creatorId': creator['_id']
}
existing = self.find(query, limit=2, **kwargs)
count = existing.count()
if count > 1:
raise ValidationException(
'there is more than one parameter set for annotation')
if count:
return existing.next() # noqa: B305
def getParameters(self, annotation, creator, parameters=None, **kwargs):
self.RNASCOPE_SINGLE_VIRION_COLOR = \
Setting().get(PluginSettings.RNASCOPE_SINGLE_VIRION_COLOR)
self.RNASCOPE_PRODUCTIVE_INFECTION_COLOR = \
Setting().get(PluginSettings.RNASCOPE_PRODUCTIVE_INFECTION_COLOR)
self.RNASCOPE_AGGREGATE_VIRIONS_COLOR = \
Setting().get(PluginSettings.RNASCOPE_AGGREGATE_VIRIONS_COLOR)
if parameters is None:
parameters = {}
doc = self._find(annotation, creator)
if doc is None:
doc = super(RNAScopeParameters, self).createAnnotationParameters(
annotation, creator, parameters, **kwargs)
else:
self.requireAccess(doc, user=creator, level=AccessType.WRITE)
doc['parameters'].update(parameters)
self.save(doc)
return doc
def createParameters(self, annotation, creator, parameters=None, **kwargs):
doc = super(RNAScopeParameters, self).createAnnotationParameters(
annotation, creator, parameters, **kwargs)
return doc
def updateParameters(self, annotation, creator, parameters=None, **kwargs):
if parameters is None:
parameters = {}
doc = self._find(annotation, creator)
if doc is None:
doc = super(RNAScopeParameters, self).createAnnotationParameters(
annotation, creator, parameters, **kwargs)
else:
self.requireAccess(doc, user=creator, level=AccessType.WRITE)
doc['parameters'].update(parameters)
self.save(doc)
return doc
def validate(self, doc):
parameters = doc['parameters']
parameters['pixelsPerVirion'] = _validateInt(
parameters.get('pixelsPerVirion',
Setting().get(
PluginSettings.RNASCOPE_PIXELS_PER_VIRION)))
parameters['pixelThreshold'] = _validateInt(
parameters.get('pixelThreshold',
Setting().get(
PluginSettings.RNASCOPE_PIXEL_THRESHOLD)))
parameters['roundnessThreshold'] = _validateFloat(
parameters.get('roundnessThreshold',
Setting().get(
PluginSettings.RNASCOPE_ROUNDNESS_THRESHOLD)))
if parameters['pixelsPerVirion'] < 1:
raise ValidationException(
'Pixels per virion cannot be less than 1')
if parameters['pixelThreshold'] < 1:
raise ValidationException(
'Pixel threshold cannot be less than 1')
if parameters['pixelsPerVirion'] > parameters['pixelThreshold']:
raise ValidationException(
'Pixels per virion cannot be greater than productive infection'
' threshold')
return doc
def classify(self, parameters, pixels, roundness):
parameters = parameters['parameters']
if pixels < parameters['pixelsPerVirion']:
return 'single virion'
elif (pixels > parameters['pixelThreshold'] and
roundness > parameters['roundnessThreshold']):
return 'productive infection'
return 'aggregate virions'
def color(self, classification):
if classification == 'single virion':
return self.RNASCOPE_SINGLE_VIRION_COLOR
elif classification == 'productive infection':
return self.RNASCOPE_PRODUCTIVE_INFECTION_COLOR
elif classification == 'aggregate virions':
return self.RNASCOPE_AGGREGATE_VIRIONS_COLOR
Rnascopeparameters = RNAScopeParameters
|
python
| 15 | 0.6192 | 79 | 37.508197 | 122 |
starcoderdata
|
<?php
namespace App;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
class Quota extends Model {
public $timestamps = false;
public static function createEmpty($userId) {
$quota = new Quota();
$quota->user_id = $userId;
$quota->standard = 0;
$quota->extended = 0;
$quota->simulator = 0;
$quota->exclusive = 0;
$quota->standard_expiry = Carbon::NOW();
$quota->extended_expiry = Carbon::NOW();
$quota->simulator_expiry = Carbon::NOW();
$quota->exclusive_expiry = Carbon::NOW();
return $quota;
}
}
|
php
| 9 | 0.583333 | 49 | 22.538462 | 26 |
starcoderdata
|
@Override
public int hashCode() {
Long id = getId();
String name = getName();
String note = getNote();
Long ownerId = getOwnerId();
// Set<User> users = getUsers();
final int prime = 13;
int result = 1;
result = prime * result + (id != null ? id.hashCode() : 0);
result = prime * result + (name != null ? name.hashCode() : 0);
result = prime * result + (note != null ? note.hashCode() : 0);
result = prime * result + (ownerId != null ? ownerId.hashCode() : 0);
// result = prime * result + users.hashCode();
return result;
}
|
java
| 10 | 0.600362 | 71 | 31.588235 | 17 |
inline
|
const {resolve} = require('path');
/**
* The wiki url, pointing to /api.php
*/
const ENDPOINT = 'https://griftlands.fandom.com/api.php';
// const ENDPOINT = 'http://127.0.0.1/mediawiki/api.php';
/**
* Authentication information, obtained from `Special:BotPasswords`, needed by `push`.
*/
const CREDENTIALS = resolve(__dirname + '/credentials.json');
// const CREDENTIALS = resolve(__dirname + '/credentials_local.json');
/**
* A file name (in the local OS file system) cannot contain some special characters, so we replace them.
* Besides those, we're also replacing SPACE with UNDERSCORE.
*/
const REPLACEMENTS = {
'\\': '%5C',
'/': '%2F',
':': '%3A',
'*': '%2A', // Doesn't get encoded by `encodeURIComponent()`
'?': '%3F',
'"': '%22',
'<': '%3C',
'>': '%3E',
'|': '%7C',
' ': '_', // Special treatment
};
/**
* Installation directory, which should contain the game archives ("data_scripts.zip" and others).
*/
const GAME_DIR = 'C:/Program Files (x86)/Steam/steamapps/common/Griftlands';
/**
* Directory where we store the pulled pages.
*/
const STORAGE = __dirname + '/../../wiki';
/**
* Directory where we store the images that correspond to each json in the "File" folder.
*/
const RAW_WEB = __dirname + '/../../raw/web';
/**
* Directory where we store assets extracted (datamined) from the game.
*/
const RAW_GAME = __dirname + '/../../raw/game';
/**
* A flag for verbosity.
*/
const DEBUG = true;
/**
* The location of a file containing the latest pulled or pushed timestamp of the online wiki.
*/
const SAFETY_TIMESTAMP_PATH = __dirname + '/safetyTimestamp.txt';
// =====================================================================================================================
// E X P O R T
// =====================================================================================================================
module.exports = {
ENDPOINT,
CREDENTIALS,
REPLACEMENTS,
GAME_DIR,
STORAGE,
RAW_WEB,
RAW_GAME,
DEBUG,
SAFETY_TIMESTAMP_PATH,
};
|
javascript
| 11 | 0.553699 | 120 | 26.565789 | 76 |
starcoderdata
|
<?php
namespace App\Repository;
use App\User;
class UserRepository
{
public function getAll()
{
return User::get();
}
public function getAllPaginate()
{
return User::paginate(5);
}
public function insert($data)
{
$user = new User();
$user->name = $data['name'];
$user->phonenumber = $data['phonenumber'];
$user->gender = $data['gender'];
$user->email = $data['email'];
$user->password = $data['password'];
$user->save();
return $user;
}
public function show($id)
{
$user = User::findOrFail($id);
return $user;
}
public function update($id,$data)
{
$user= User::findOrFail($id);
$user->name = $data['name'];
$user->phonenumber = $data['phonenumber'];
$user->gender = $data['gender'];
$user->email = $data['email'];
$user->password = $data['password'];
$user->save();
return $user;
}
public function delete($id)
{
$user = User::findOrFail($id);
// $user->detachRole();
$user->delete();
return $user;
}
}
|
php
| 11 | 0.505541 | 50 | 20.345455 | 55 |
starcoderdata
|
/*
* Work Flow Constants
* Each action has a corresponding type, which the reducer knows and picks up on.
* To avoid weird typos between the reducer and the actions, we save them as
* constants here. We prefix them with 'yourproject/YourComponent' so we avoid
* reducers accidentally picking up actions they shouldn't.
*
* Follow this format:
* export const YOUR_ACTION_CONSTANT = 'yourproject/YourContainer/YOUR_ACTION_CONSTANT';
*/
export const WFLOW_RESETSTATE = 'hcmwebapp/WorkflowAndApproval/WFLOW_RESETSTATE';
// Work flow Processes List
export const WFLOW_PROCSLIST_SUCCESS = 'hcmwebapp/WorkflowAndApproval/WFLOW_PROCSLIST_SUCCESS';
export const WFLOW_PROCSLIST_FAILED = 'hcmwebapp/WorkflowAndApproval/WFLOW_PROCSLIST_FAILED';
export const WFLOW_PROCSLIST = 'hcmwebapp/WorkflowAndApproval/WFLOW_PROCSLIST';
export const WFLOW_PROCS_SELECTEDITEM = 'hcmwebapp/WorkflowAndApproval/WFLOW_PROCS_SELECTEDITEM';
// Work flow Templates List
export const WFLOW_TEMPLATELIST_SUCCESS = 'hcmwebapp/WorkflowAndApproval/WFLOW_TEMPLATELIST_SUCCESS';
export const WFLOW_TEMPLATELIST_FAILED = 'hcmwebapp/WorkflowAndApproval/WFLOW_TEMPLATELIST_FAILED';
export const WFLOW_TEMPLATELIST = 'hcmwebapp/WorkflowAndApproval/WFLOW_TEMPLATELIST';
export const WFLOW_TEMPLATE_SELECTEDITEM = 'hcmwebapp/WorkflowAndApproval/WFLOW_TEMPLATE_SELECTEDITEM';
export const WFLOW_TEMPLATE_STEP = 'hcmwebapp/WorkflowAndApproval/WFLOW_TEMPLATE_STEP';
// export const WFLOW_TEMPLATE_STEP_SELECTEDITEM = 'hcmwebapp/WorkflowAndApproval/WFLOW_TEMPLATE_STEP_SELECTEDITEM';
export const WFLOW_TEMPLATE_STEP_SUCCESS = 'hcmwebapp/WorkflowAndApproval/WFLOW_TEMPLATE_STEP_SUCCESS';
export const WFLOW_TEMPLATE_STEP_FAILED = 'hcmwebapp/WorkflowAndApproval/WFLOW_TEMPLATE_STEP_FAILED';
export const WFLOW_PROCESSTEMPLATE_SUCCESS = 'hcmwebapp/WorkflowAndApproval/WFLOW_PROCESSTEMPLATE_SUCCESS';
export const WFLOW_PROCESSTEMPLATE_FAILED = 'hcmwebapp/WorkflowAndApproval/WFLOW_PROCESSTEMPLATE_FAILED';
export const WFLOW_PROCESSTEMPLATE = 'hcmwebapp/WorkflowAndApproval/WFLOW_PROCESSTEMPLATE';
export const WFLOW_PROCESSRESET = 'hcmwebapp/WorkflowAndApproval/WFLOW_PROCESSRESET';
// Employee, WorkGroup and Department List
export const WFLOW_EMPWGDP_LIST = 'hcmwebapp/WorkflowAndApproval/WFLOW_EMPWGDP_LIST';
export const WFLOW_EMPWGDP_SUCCESS = 'hcmwebapp/WorkflowAndApproval/WFLOW_EMPWGDP_SUCCESS';
export const WFLOW_EMPWGDP_FAILED = 'hcmwebapp/WorkflowAndApproval/WFLOW_EMPWGDP_FAILED';
export const WFLOW_EMPWGDP_SELECTEDITEMS = 'hcmwebapp/WorkflowAndApproval/WFLOW_EMPWGDP_SELECTEDITEMS';
// Assign to Entity
export const WFLOW_ENTITY = 'hcmwebapp/WorkflowAndApproval/WFLOW_ENTITY';
export const WFLOW_ENT_SUCCESS = 'hcmwebapp/WorkflowAndApproval/WFLOW_ENT_SUCCESS';
export const WFLOW_ENT_FAILED = 'hcmwebapp/WorkflowAndApproval/WFLOW_ENT_FAILED';
export const WFLOW_ENT_SELECTEDITEM = 'hcmwebapp/WorkflowAndApproval/WFLOW_ENT_SELECTEDITEM';
|
javascript
| 3 | 0.822548 | 116 | 61.468085 | 47 |
starcoderdata
|
/*
* This header is generated by classdump-dyld 1.0
* on Sunday, September 27, 2020 at 11:44:41 AM Mountain Standard Time
* Operating System: Version 14.0 (Build 18A373)
* Image Source: /System/Library/PrivateFrameworks/DuetExpertCenter.framework/DuetExpertCenter
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by
*/
@interface _DECXPCObjectFactory : NSObject {
unsigned long long _priorityLevel;
unsigned long long _allowBattery;
BOOL _repeating;
BOOL _requireScreenSleep;
BOOL _requireClassC;
BOOL _requireClassA;
long long _intervalHours;
long long _intervalMinutes;
long long _intervalSeconds;
}
@property (assign,nonatomic) long long intervalHours; //@synthesize intervalHours=_intervalHours - In the implementation block
@property (assign,nonatomic) long long intervalMinutes; //@synthesize intervalMinutes=_intervalMinutes - In the implementation block
@property (assign,nonatomic) long long intervalSeconds; //@synthesize intervalSeconds=_intervalSeconds - In the implementation block
@property (assign,nonatomic) BOOL repeating; //@synthesize repeating=_repeating - In the implementation block
@property (assign,nonatomic) BOOL requireScreenSleep; //@synthesize requireScreenSleep=_requireScreenSleep - In the implementation block
@property (assign,nonatomic) BOOL requireClassC; //@synthesize requireClassC=_requireClassC - In the implementation block
@property (assign,nonatomic) BOOL requireClassA; //@synthesize requireClassA=_requireClassA - In the implementation block
-(long long)intervalMinutes;
-(id)getXPCObject;
-(long long)intervalSeconds;
-(BOOL)requireClassA;
-(void)setRequireScreenSleep:(BOOL)arg1 ;
-(void)setIntervalMinutes:(long long)arg1 ;
-(long long)intervalHours;
-(void)setIntervalSeconds:(long long)arg1 ;
-(id)init;
-(BOOL)requireScreenSleep;
-(void)setIntervalHours:(long long)arg1 ;
-(BOOL)requireClassC;
-(void)setRequireClassA:(BOOL)arg1 ;
-(long long)_getInterval;
-(void)setRequireClassC:(BOOL)arg1 ;
-(BOOL)repeating;
-(const char*)_activityPriority;
-(BOOL)_shouldAllowBattery;
-(void)setPriorityLevelMaintenance;
-(void)setPriorityLevelUtility;
-(void)disallowBattery;
-(void)setRepeating:(BOOL)arg1 ;
-(void)allowBattery;
@end
|
c
| 6 | 0.752752 | 151 | 41.178571 | 56 |
starcoderdata
|
/*
Fibonacci Dizisi
(c) 2018
Lisans : MIT (https://github.com/alpeer/Fibonacci/)
*/
let Fibonacci=new Proxy({ratio:(Math.sqrt(5)+1)/2},{
get:function(n,num){
if(['oran','ratio','Sayısı','Number'].indexOf(num)>-1){return n.ratio;}
return (Math.pow(n.ratio,num=Number(num)+1)-Math.pow(-n.ratio,-num))/Math.sqrt(5)
}
})
Math.PHI=Fibonacci.Sayısı;
|
javascript
| 15 | 0.640964 | 86 | 26.733333 | 15 |
starcoderdata
|
<?php
namespace Guni\Comments;
use \Anax\DI\DIInterface;
/**
* Helper for html-code
*/
class Misc
{
protected $di;
/**
* Constructor injects with DI container and the id to update.
*
* @param Anax\DI\DIInterface $di a service container
*/
public function __construct(DIInterface $di)
{
$this->di = $di;
}
/**
* Sets the callable to use for creating routes.
*
* @param callable $urlCreate to create framework urls.
*
* @return void
*/
public function setUrlCreator($route)
{
$url = $this->di->get("url");
return call_user_func([$url, "create"], $route);
}
/**
* Returns link for gravatar img
*
* @param object $item
* @return string htmlcode
*/
public function getGravatar($item, $size = 20)
{
$comm = new Comm();
$gravatar = $comm->getGravatar($item, $size);
return '<img src="' . $gravatar . '" alt=""/>';
}
/**
* @param integer $commentid - question to answer
*
* @return string htmlcode for answering a question
*/
public function getAnswerLink($commentid)
{
return '<a href="' . $this->setUrlCreator("comm/create") . '/' . $commentid . '">Svara
}
/**
* @param integer $commentid - question or answer to comment
*
* @return string htmlcode for commenting
*/
public function getCommentLink($commentid)
{
return '<a href="' . $this->setUrlCreator("comm/comment") . '/' . $commentid . '">Kommentera
}
/**
* @return string htmltext
*/
public function isUpdated($item)
{
if ($item->parentid !== null) {
return 'Svar: ' . $item->created . ', Ändrad: ' . $item->updated;
} else {
return 'Fråga: ' . $item->created . ', Ändrad: ' . $item->updated;
}
}
/**
* @return string htmltext
*/
public function isNotUpdated($item)
{
if ($item->parentid !== null) {
return 'Svar: ' . $item->created;
} else {
return 'Fråga: ' . $item->created;
}
}
/**
* Returns when created or updated
*
* @param object $item
* @return string htmlcode
*/
public function getWhen($item)
{
$when = $item->updated ? $this->isUpdated($item) : $this->isNotUpdated($item);
return $when;
}
/**
* Returns html for user item
*
* @param array $item - userinfo
* @param string $viewone - path
*
* @return string htmlcode
*/
public function getUsersHtml($item)
{
$gravatar = $this->getGravatar($item['email']);
$arr['acronym'] = '<a href="' . $this->setUrlCreator("user/view-one") . "/" . $item['id'] . '">' . $item['acronym'] . '
$arr['gravatar'] = '<a href="' . $this->setUrlCreator("user/view-one") . "/" . $item['id'] . '">' . $gravatar . '
return $arr;
}
/**
* Sort list of dates
*
* @param string $first
* @param string $second - dates
*
* @return sorted dates
*/
public function dateSort($first, $second)
{
return strtotime($first->created) - strtotime($second->created);
}
/**
* @param Comm $item - current comment
* @param array $numbers - counted points, answers and comments
* @param string $when - when comment was created
* @param $user
* @param integer $isadmin
*
* @return string $html
*/
public function getTheText($item, $numbers, $when, $user)
{
$gravatar = $this->getGravatar($user[0]);
$showid = $user[2] === true ? '(' . $item->id . '): ' : "";
$title = '<a href="' . $this->setUrlCreator("comm/view-one") . '/' . $item->id . '">';
$title .= $showid . ' ' . $item->title . '
$html = ' class = "allmember">' . $gravatar . ' ' . $user[1] . '
$html .= '<td class = "alltitle">' . $title . '
$html .= '<td class = "asked">' . $when . '
$html .= '<td = "respons"><span class = "smaller">' . $numbers[0] . $numbers[1] . $numbers[2] . '
$html .= '
return $html;
}
/**
* Returns correct loginlink
*
* @param integer $isloggedin
* @param boolean $isadmin
*
* @return string htmlcode
*/
public function getLoginLink($isloggedin, $isadmin)
{
$loggedin = '<a href="user/login">Logga in om du vill kommentera
if ($isloggedin) {
$loggedin = ' <a href="' . $this->setUrlCreator("comm/create") .'">Skriv ett inlägg
if ($isadmin === true) {
$loggedin .= ' | <a href="' . $this->setUrlCreator("comm/delete/0") . '">Ta bort ett inlägg
}
}
return $loggedin;
}
}
|
php
| 17 | 0.514581 | 133 | 24.590674 | 193 |
starcoderdata
|
import unittest
import tempfile
import os
import shutil
from spark_python_jobs.main import SampleJob
from pyspark.sql import SparkSession
from unittest.mock import MagicMock
from pyspark.sql import functions as F
class SampleJobUnitTest(unittest.TestCase):
def setUp(self):
self.test_dir = tempfile.TemporaryDirectory().name
self.output = os.path.join(self.test_dir, "output")
self.spark = SparkSession.builder.master("local[1]").getOrCreate()
self.job = SampleJob(self.spark)
# self.job.set_spark(self.spark)
self.job.set_output(self.output)
self.job.launch()
self.df = self.spark.read.format("parquet").load(self.output)
def test_sample_count(self):
output_count = (
self.df.count()
)
self.assertEqual(output_count, 7)
def test_sample_price(self):
price = self.df.take(1)[0][2]
self.assertEqual(price, 7)
def test_sample_amount(self):
amount = self.df.take(1)[0][3]
self.assertEqual(amount, 10)
def tearDown(self):
shutil.rmtree(self.output)
if __name__ == "__main__":
unittest.main()
|
python
| 13 | 0.64433 | 74 | 26.093023 | 43 |
starcoderdata
|
node *insert(node *T, int x)
{
if (T == NULL)
{
T = (node *)malloc(sizeof(node));
T->data = x;
T->left = NULL;
T->right = NULL;
}
else if (x > T->data) // insert in right subtree
{
T->right = insert(T->right, x);
if (BF(T) == -2)
if (x > T->right->data)
T = RR(T);
else
T = RL(T);
}
else if (x < T->data)
{
T->left = insert(T->left, x);
if (BF(T) == 2)
if (x < T->left->data)
T = LL(T);
else
T = LR(T);
}
T->ht = height(T);
return (T);
}
|
c++
| 16 | 0.349014 | 52 | 19.625 | 32 |
inline
|
yang_stmt *
ys_module(yang_stmt *ys)
{
yang_node *yn;
#if 1
if (ys==NULL || ys->ys_keyword==Y_SPEC)
return NULL;
#else
if (ys==NULL || ys->ys_keyword==Y_SPEC)
return ys;
#endif
while (ys != NULL && ys->ys_keyword != Y_MODULE && ys->ys_keyword != Y_SUBMODULE){
yn = ys->ys_parent;
/* Some extra stuff to ensure ys is a stmt */
if (yn && yn->yn_keyword == Y_SPEC)
yn = NULL;
ys = (yang_stmt*)yn;
}
/* Here it is either NULL or is a typedef-kind yang-stmt */
return ys;
}
|
c
| 10 | 0.580709 | 86 | 22.136364 | 22 |
inline
|
@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {
//
// Loop at all stack elements, starting from the top
//
StringBuilder sb = new StringBuilder("(");
for (int i = 0; i < stack.depth(); i++) {
Object o = stack.get(i);
String type = "bytearray";
if (o instanceof Long) {
type = "long";
} else if (o instanceof Integer) {
type = "int";
} else if (o instanceof Double) {
type = "double";
} else if (o instanceof Float) {
type = "float";
} else if (o instanceof BigDecimal) {
type = "bigdecimal";
} else if (o instanceof BigInteger) {
type = "biginteger";
} else if (o instanceof String) {
type = "chararray";
} else if (o instanceof Boolean) {
type = "boolean";
} else if (o instanceof byte[]) {
type = "bytearray";
} else if (o instanceof Vector || o instanceof Set) {
type = "bag{}";
} else if (o instanceof List) {
type = "tuple:()";
} else if (o instanceof Map) {
type = "map:[]";
} else if (o instanceof GeoTimeSerie) {
type = "bytearray";
} else if (o instanceof DateTime) {
type = "datetime";
} else {
type = "bytearray";
}
if (i > 0) {
sb.append(", ");
}
if (0 == i) {
sb.append("top");
} else {
sb.append("l");
sb.append(i + 1);
}
sb.append(": ");
sb.append(type);
}
sb.append(")");
stack.push(sb.toString());
return stack;
}
|
java
| 23 | 0.48704 | 73 | 24.538462 | 65 |
inline
|
var RedisStore = require('../RedisStore');
var describeSessionStore = require('./describeSessionStore');
describe('RedisStore', function () {
describeSessionStore(
new RedisStore({
secret: 'secret'
}),
process.env.WITH_REDIS !== '1'
);
});
|
javascript
| 10 | 0.670103 | 61 | 23.25 | 12 |
starcoderdata
|
<?php
namespace common\components\log;
use common\components\log\constant\Event;
use common\components\log\event\BatchModelEvent;
use common\components\log\event\ModelEvent;
use common\components\log\event\RpcEvent;
use common\components\log\model\LogModel;
class OperateLog extends \yii\base\Component
{
public $dbName = 'db';
public $tableName = "{{%logs}}";
private $_event = null;
/**
* 获取事件
*
* @param string $type
*
* @return BatchModelEvent|ModelEvent|RpcEvent|null
*/
public function getEvent(string $type = Event::OTHER)
{
switch ($type) {
case Event::MODEL:
$this->_event = new ModelEvent();
break;
case Event::BATCH_MODEL:
$this->_event = new BatchModelEvent();
break;
case Event::RPC:
$this->_event = new RpcEvent();
break;
}
return $this->_event;
}
/**
* 记录日志
*
* @param array $data
*
* @return bool
*/
public function record()
{
LogModel::$dbName = $this->dbName;
LogModel::$tableName = $this->tableName;
$model = new LogModel();
$model->setAttributes($this->_event->record(), false);
return $model->save(false);
}
}
|
php
| 12 | 0.549664 | 62 | 22.086207 | 58 |
starcoderdata
|
def TestSAMRAI(time, suffix):
OpenDatabase(data_path("samrai_test_data/sil_changes/dumps.visit"))
AddPlot("Pseudocolor", "Primitive Var _number_0")
DrawPlots()
# Set the colortable to one that has white at the bottom values.
SetActiveContinuousColorTable("rainbow")
pc = PseudocolorAttributes()
pc.colorTableName = "Default"
SetPlotOptions(pc)
AddOperator("Slice", 1)
slice = SliceAttributes()
slice.originType = slice.Percent
slice.originPercent = 18
slice.axisType = slice.ZAxis
slice.project2d = 1
SetOperatorOptions(slice, 0, 1)
DrawPlots()
ResetView()
SetTimeSliderState(1)
#Do some lineouts
p0 = (3, 3)
p1 = (0, 20)
p2 = (30, 0)
nsteps = 15
for i in range(nsteps):
t = float(i) / float(nsteps - 1)
p3x = t * p2[0] + (1. - t) * p1[0]
p3y = t * p2[1] + (1. - t) * p1[1]
SetActiveWindow(1)
Lineout(p0, (p3x, p3y))
if (time == 1):
SetActiveWindow(1)
Test("LineoutSAMRAI")
SetActiveWindow(2)
InitAnnotation()
Test("CurvesFromSAMRAI" + suffix)
DeleteWindow()
DeleteAllPlots()
ResetPickLetter()
ResetLineoutColor()
|
python
| 11 | 0.610788 | 71 | 24.125 | 48 |
inline
|
class Solution {
public:
vector XXX(TreeNode* root) {//用队列的大小标记每一层大小
vector records;
if(!root) return records;
vector record;
queue s;
s.push(root);
while(!s.empty()){
int size=s.size();//记录了每一层的节点数目
for(int i=0;i<size;++i){
TreeNode* temp=s.front();
s.pop();
record.push_back(temp->val);
if(temp->left) s.push(temp->left);
if(temp->right) s.push(temp->right);
}
records.push_back(record);
record.clear();
}
return records;
}
};
|
c++
| 14 | 0.475146 | 60 | 27.5 | 24 |
starcoderdata
|
package socialite.logic.commands;
import static java.util.Objects.requireNonNull;
import socialite.model.ContactList;
import socialite.model.Model;
/**
* Clears the contact list.
*/
public class ClearCommand extends Command {
public static final String COMMAND_WORD = "clear";
public static final String MESSAGE_SUCCESS = "Contact list has been cleared!";
@Override
public CommandResult execute(Model model) {
requireNonNull(model);
model.setContactList(new ContactList());
return new CommandResult(MESSAGE_SUCCESS);
}
}
|
java
| 10 | 0.738863 | 82 | 26.125 | 24 |
starcoderdata
|
var vows = require('vows');
var assert = require('assert');
var Router = require('../core/server/router');
var InternalRouter = Router.InternalRouter;
var InternalRoute = Router.InternalRoute;
vows.describe('Router').addBatch({
build: {
'it builds routes': function() {
var routes = Router(function(route) {
return [
route.get('/', 'foo@bar')
];
});
assert(routes.length === 1);
assert(routes[0] instanceof InternalRoute);
},
'it flattens dimensions': function() {
var routes = Router(function(route) {
return [
[
route.get('/', 'foo@bar')
]
];
});
assert(routes.length === 1);
assert(routes[0] instanceof InternalRoute);
}
},
get: {
topic: new InternalRouter(),
'it outputs get route': function(router) {
assert.deepEqual({
method: 'GET',
path: '/',
resource: 'foo@bar',
config: {}
}, router.get('/', 'foo@bar'));
}
},
post: {
topic: new InternalRouter(),
'it outputs post route': function(router) {
assert.deepEqual({
method: 'POST',
path: '/',
resource: 'foo@bar',
config: {}
}, router.post('/', 'foo@bar'));
}
},
put: {
topic: new InternalRouter(),
'it outputs put route': function(router) {
assert.deepEqual({
method: 'PUT',
path: '/',
resource: 'foo@bar',
config: {}
}, router.put('/', 'foo@bar'));
}
},
delete: {
topic: new InternalRouter(),
'it outputs delete route': function(router) {
assert.deepEqual({
method: 'DELETE',
path: '/',
resource: 'foo@bar',
config: {}
}, router.delete('/', 'foo@bar'));
}
},
resource: {
topic: new InternalRouter(),
'it outputs resource routes': function(router) {
var resources = router.resource('foo', 'bar');
assert(Array.isArray(resources));
resources.forEach(function(route) {
assert(route instanceof InternalRoute);
});
},
'it outputs resource routes without index': function(router) {
var indexTestRegExp = /\@index$/;
var resources = router.resource('foo', 'bar', {
except: ['index']
});
for (var i = 0; i < resources.length; i++) {
assert(!indexTestRegExp.test(resources[i].resource));
}
},
'it outputs resource routes with only index': function(router) {
var indexTestRegExp = /\@index$/;
var resources = router.resource('foo', 'bar', {
only: ['index']
});
assert(resources.length === 1);
assert(indexTestRegExp.test(resources[0].resource));
}
}
}).export(module);
|
javascript
| 24 | 0.539971 | 68 | 24.719626 | 107 |
starcoderdata
|
namespace Atata
{
///
/// Defines functionality that provides the properties bag.
///
public interface IPropertySettings
{
///
/// Gets the properties bag.
///
PropertyBag Properties { get; }
}
}
|
c#
| 8 | 0.538961 | 63 | 21.692308 | 13 |
starcoderdata
|
package net.minecraft.server;
import java.util.Random;
public class ItemEnchantedBook extends Item {
public ItemEnchantedBook() {}
public boolean e_(ItemStack itemstack) {
return false;
}
public EnumItemRarity f(ItemStack itemstack) {
return this.g(itemstack).size() > 0 ? EnumItemRarity.UNCOMMON : super.f(itemstack);
}
public NBTTagList g(ItemStack itemstack) {
return itemstack.tag != null && itemstack.tag.hasKeyOfType("StoredEnchantments", 9) ? (NBTTagList) itemstack.tag.get("StoredEnchantments") : new NBTTagList();
}
public void a(ItemStack itemstack, EnchantmentInstance enchantmentinstance) {
NBTTagList nbttaglist = this.g(itemstack);
boolean flag = true;
for (int i = 0; i < nbttaglist.size(); ++i) {
NBTTagCompound nbttagcompound = nbttaglist.get(i);
if (nbttagcompound.getShort("id") == enchantmentinstance.enchantment.id) {
if (nbttagcompound.getShort("lvl") < enchantmentinstance.level) {
nbttagcompound.setShort("lvl", (short) enchantmentinstance.level);
}
flag = false;
break;
}
}
if (flag) {
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
nbttagcompound1.setShort("id", (short) enchantmentinstance.enchantment.id);
nbttagcompound1.setShort("lvl", (short) enchantmentinstance.level);
nbttaglist.add(nbttagcompound1);
}
if (!itemstack.hasTag()) {
itemstack.setTag(new NBTTagCompound());
}
itemstack.getTag().set("StoredEnchantments", nbttaglist);
}
public ItemStack a(EnchantmentInstance enchantmentinstance) {
ItemStack itemstack = new ItemStack(this);
this.a(itemstack, enchantmentinstance);
return itemstack;
}
public StructurePieceTreasure b(Random random) {
return this.a(random, 1, 1, 1);
}
public StructurePieceTreasure a(Random random, int i, int j, int k) {
ItemStack itemstack = new ItemStack(Items.BOOK, 1, 0);
EnchantmentManager.a(random, itemstack, 30);
return new StructurePieceTreasure(itemstack, i, j, k);
}
}
|
java
| 16 | 0.6313 | 166 | 31.314286 | 70 |
starcoderdata
|
<!doctype html>
<!--
Material Design Lite
Copyright 2015 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License
-->
<html lang="en">
<?php include_once("include/head.incl.php"); ?>
<script src="http://code.highcharts.com/highcharts.js">
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="
crossorigin="anonymous">
<script type="text/javascript">
function GetUrlParameter() {
idx = window.location.href.indexOf("?");
if (idx < 0) return "";
return window.location.href.substring(idx + 1);
}
urlParameter = GetUrlParameter();
function GetChartXml() {
switch (urlParameter) {
case "t3h":
case "t24h":
case "t48h":
case "t1w":
case "t1m":
case "t3m":
case "t1y":
case "h3h":
case "h24h":
case "h48h":
case "h1w":
case "h1m":
case "h3m":
case "h1y":
case "f3h":
case "f24h":
case "f48h":
case "f1w":
case "f1m":
case "f3m":
case "f1y":
return "http://srv3.home/homecontrol-backend/states/temperatures/xml/all_" + urlParameter + ".xml";
}
return "http://srv3.home/homecontrol-backend/states/temperatures/xml/all_t24h.xml";
}
function GetChartTitle() {
switch (urlParameter) {
case "t3h":
return "Temperatur der letzten 3 Stunden";
case "t24h":
return "Temperatur der letzten 24 Stunden";
case "t48h":
return "Temperatur der letzten 48 Stunden";
case "t1w":
return "Temperatur der letzten Woche";
case "t1m":
return "Temperatur des letzten Monats";
case "t3m":
return "Temperatur der letzten 3 Monate";
case "t1y":
return "Temperatur des letzten Jahres";
case "h3h":
return "Luftfeuchtigkeit der letzten 3 Stunden";
case "h24h":
return "Luftfeuchtigkeit der letzten 24 Stunden";
case "h48h":
return "Luftfeuchtigkeit der letzten 48 Stunden";
case "h1w":
return "Luftfeuchtigkeit der letzten Woche";
case "h1m":
return "Luftfeuchtigkeit des letzten Monats";
case "h3m":
return "Luftfeuchtigkeit der letzten 3 Monate";
case "h1y":
return "Luftfeuchtigkeit des letzten Jahres";
}
return "Temperatur der letzten 24 Stunden";
};
$(document).ready(function() {
options = {
chart: {
renderTo: 'container',
type: 'spline'
},
title: {
text: 'Temperatures of the last 24h'
},
colors: ['#4572A7', '#AA4643', '#89A54E', '#80699B', '#3D96AE',
'#DB843D', '#92A8CD', '#A47D7C', '#B5CA92'],
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
hour: '%H. %M',
}
},
yAxis: {
title: {
text: 'Deg.C)'
}
},
plotOptions: {
series: {
marker: {
radius: 2
}
}
},
lineWidth: 1,
series: []
}
// Load the data from the XML file
$.ajax({
type: "GET",
url: GetChartXml(),
dataType: "xml",
success: function(xml) {
var series = []
//define series
$(xml).find("entry").each(function() {
var seriesOptions = {
name: $(this).text(),
data: []
};
options.series.push(seriesOptions);
});
//populate with data
$(xml).find("row").each(function() {
var t = parseInt($(this).find("t").text()) * 1000 //Zeitzone?
$(this).find("v").each(function(index) {
var v = parseFloat($(this).text())
v = v || null
if (v != null) {
options.series[index].data.push([t, v])
};
});
});
options.title.text = GetChartTitle()
$.each(series, function(index) {
options.series.push(series[index]);
});
chart = new Highcharts.Chart(options);
}
})
});
<div class="demo-layout mdl-layout mdl-js-layout mdl-layout--fixed-drawer mdl-layout--fixed-header">
<?php
$pagetitle="Diagramme";
include_once("include/top-header.incl.php");
include_once("include/nav.incl.php");
?>
<main class="mdl-layout__content mdl-color--grey-100">
<div class="mdl-grid demo-content">
<div id="container" style="width:100%; height:400px;">
<?php include_once("include/scriptsource.incl.php"); ?>
|
php
| 5 | 0.422173 | 127 | 36.624309 | 181 |
starcoderdata
|
fn usart_send_raw_str(data: &[u8]) -> usize {
let peripherals = unsafe { Peripherals::steal() };
// First, disable send interrupts.
peripherals.USART.ier_mut().modify(|_, v| v.threinten().disable_the_thre_int());
// Insert data to the ring buffer
let mut inserted_len = ring_buffer_insert_mult(unsafe { &mut USART_WRITE_RING_BUFFER }, data);
// Send the contents of the ring buffer
while peripherals.USART.lsr.read().thre().is_empty() {
if let Some(val) = unsafe { USART_WRITE_RING_BUFFER .dequeue() } {
peripherals.USART.thr_mut().write(|v| unsafe { v.thr().bits(val) });
} else {
break;
}
}
// Try to insert some more contents in the ring buffer.
inserted_len += ring_buffer_insert_mult(unsafe { &mut USART_WRITE_RING_BUFFER }, &data[inserted_len..]);
// Re-enable send interrupts
peripherals.USART.ier_mut().modify(|_, v| v.threinten().enable_the_thre_inte());
inserted_len
}
|
rust
| 19 | 0.625 | 108 | 36.884615 | 26 |
inline
|
using Recipes.Data.Models;
using System;
namespace Recipes.Desktop.Events
{
public class EditRecipeEventArgs : EventArgs
{
public Recipe Recipe { get; set; }
public EditRecipeEventArgs(Recipe recipe)
{
this.Recipe = recipe;
}
}
}
|
c#
| 11 | 0.660167 | 69 | 21.4375 | 16 |
starcoderdata
|
func main() {
cleanup, err := dcgm.Init(dcgm.Embedded)
if err != nil {
log.Panicln(err)
}
defer cleanup()
// Request DCGM to start recording stats for GPU process fields
group, err := dcgm.WatchPidFields()
if err != nil {
log.Panicln(err)
}
// Before retrieving process stats, wait few seconds for watches to be enabled and collect data
log.Println("Enabling DCGM watches to start collecting process stats. This may take a few seconds....")
time.Sleep(3000 * time.Millisecond)
flag.Parse()
pidInfo, err := dcgm.GetProcessInfo(group, *process)
if err != nil {
log.Panicln(err)
}
t := template.Must(template.New("Process").Parse(processInfo))
for _, gpu := range pidInfo {
if err = t.Execute(os.Stdout, gpu); err != nil {
log.Panicln("Template error:", err)
}
}
}
|
go
| 12 | 0.683814 | 104 | 24.741935 | 31 |
inline
|
def __init__(self, alias='', calibrations=None, category='', connection=None,
description='', is_operable=False, maintenances=None,
manufacturer='', model='', serial='', team='', unique_key='', **user_defined):
"""Contains the information about an equipment record in an :ref:`equipment-database`.
Parameters
----------
alias : :class:`str`
An alias to use to reference this equipment by.
calibrations : :class:`list` of :class:`.CalibrationRecord`
The calibration history of the equipment.
category : :class:`str`
The category (e.g., Laser, DMM) that the equipment belongs to.
connection : :class:`.ConnectionRecord`
The information necessary to communicate with the equipment.
description : :class:`str`
A description about the equipment.
is_operable : :class:`bool`
Whether the equipment is able to be used.
maintenances : :class:`list` of :class:`.MaintenanceRecord`
The maintenance history of the equipment.
manufacturer : :class:`str`
The name of the manufacturer of the equipment.
model : :class:`str`
The model number of the equipment.
serial : :class:`str`
The serial number (or unique identifier) of the equipment.
team : :class:`str`
The team (e.g., Light Standards) that the equipment belongs to.
unique_key : :class:`str`
The key that uniquely identifies the equipment record in a database.
**user_defined
All additional key-value pairs are added to the :attr:`.user_defined` attribute.
"""
self.alias = alias # the alias should be of type str, but this is up to the user
""":class:`str`: An alias to use to reference this equipment by.
The `alias` can be defined in 4 ways:
* by specifying it when the EquipmentRecord is created
* by setting the value after the EquipmentRecord has been created
* in the **<equipment>** XML tag in a :ref:`configuration-file`
* in the **Properties** field in a :ref:`connections-database`
"""
self.calibrations = self._set_calibrations(calibrations)
""":class:`tuple` of :class:`.CalibrationRecord`: The calibration history of the equipment."""
self.category = '{}'.format(category)
""":class:`str`: The category (e.g., Laser, DMM) that the equipment belongs to."""
self.description = '{}'.format(description)
""":class:`str`: A description about the equipment."""
self.is_operable = bool(is_operable)
""":class:`bool`: Whether the equipment is able to be used."""
self.maintenances = self._set_maintenances(maintenances)
""":class:`tuple` of :class:`.MaintenanceRecord`: The maintenance history of the equipment."""
self.manufacturer = '{}'.format(manufacturer)
""":class:`str`: The name of the manufacturer of the equipment."""
self.model = '{}'.format(model)
""":class:`str`: The model number of the equipment."""
self.serial = '{}'.format(serial)
""":class:`str`: The serial number (or unique identifier) of the equipment."""
# requires self.manufacturer, self.model and self.serial to be already defined
self.connection = self._set_connection(connection)
""":class:`.ConnectionRecord`: The information necessary to communicate with the equipment."""
# cache this value because __str__ is called a lot during logging
self._str = 'EquipmentRecord<{}|{}|{}>'.format(self.manufacturer, self.model, self.serial)
self.team = '{}'.format(team)
""":class:`str`: The team (e.g., Light Standards) that the equipment belongs to."""
self.unique_key = '{}'.format(unique_key)
""":class:`str`: The key that uniquely identifies the equipment record in a database."""
try:
# a 'user_defined' kwarg was explicitly defined
ud = user_defined.pop('user_defined')
except KeyError:
ud = user_defined
else:
ud.update(**user_defined) # the user_defined dict might still contain other key-value pairs
self.user_defined = RecordDict(ud)
""":class:`.RecordDict`: User-defined, key-value pairs."""
|
python
| 10 | 0.609953 | 104 | 46.468085 | 94 |
inline
|
/**
* plugin.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/*global tinymce:true */
(function () {
var ajaxUrl = '/utils/uploadimg';
var loadingImage = '<img id="loadingImg" src="http://static.cnblogs.com/images/loading.gif" alt="" />';
tinymce.create('tinymce.plugins.PasteUploadPlugin', {
init: function (ed, url) {
ed.on("Paste", (function (e) {
debugger;
var image, pasteEvent, text;
pasteEvent = e;
if (pasteEvent.clipboardData && pasteEvent.clipboardData.items) {
image = isImage(pasteEvent);
if (image) {
e.preventDefault();
return uploadFile(image.getAsFile(), getFilename(pasteEvent));
}
}
}));
ed.on('Drop', function (event) {
var filename, image, pasteEvent, text;
pasteEvent = event
if (pasteEvent.dataTransfer && pasteEvent.dataTransfer.files) {
image = isImageForDrop(pasteEvent);
if (image) {
filename = pasteEvent.dataTransfer.files[0].name || "image.png";
event.preventDefault();
return uploadFile(image, filename);
}
}
});
isImageForDrop = function (data) {
var i, item;
i = 0;
while (i < data.dataTransfer.files.length) {
item = data.dataTransfer.files[i];
if (item.type.indexOf("image") !== -1) {
return item;
}
i++;
}
return false;
};
function isImage(data) {
var i, item;
i = 0;
while (i < data.clipboardData.items.length) {
item = data.clipboardData.items[i];
if (item.type.indexOf("image") !== -1) {
return item;
}
i++;
}
return false;
};
function uploadFile(file, filename) {
var formData = new FormData();
formData.append('imageFile', file);
formData.append("mimeType", file.type);
$.ajax({
url: ajaxUrl,
data: formData,
type: 'post',
processData: false,
contentType: false,
dataType: 'json',
success: function (result) {
if (result.errorcode == 0) {
insertIntoTinymce(result.data.image);
} else {
}
},
error: function (xOptions, textStatus) {
console.log(xOptions.responseText);
}
});
};
function insertIntoTinymce(url) {
var content = ed.getContent();
// content = content.replace(loadingImage, '<img src="' + url + '">');
// ed.setContent(content);
ed.insertContent('<img src="/assets/images/' + url + '">');
ed.selection.select(ed.getBody(), true);
ed.selection.collapse(false);
debugger;
};
function replaceLoading(filename) {
var content = ed.getContent();
content = content.replace(loadingImage, filename);
ed.setContent(content);
ed.selection.select(ed.getBody(), true);
ed.selection.collapse(false);
};
function getFilename(e) {
var value;
if (window.clipboardData && window.clipboardData.getData) {
value = window.clipboardData.getData("Text");
} else if (e.clipboardData && e.clipboardData.getData) {
value = e.clipboardData.getData("text/plain");
}
value = value.split("\r");
return value[0];
};
},
});
// Register plugin
tinymce.PluginManager.add("pasteUpload", tinymce.plugins.PasteUploadPlugin);
})();
|
javascript
| 29 | 0.484883 | 107 | 34.516393 | 122 |
starcoderdata
|
import _ from 'lodash'
export default {
getRootElement() {
return this.vm.$el
},
getElement(selector) {
return _.isNil(selector)
? this.getRootElement()
: this.getRootElement().querySelector(selector)
},
getElements(selector) {
return Array.from(this.getRootElement().querySelectorAll(selector))
},
hasElement(selector) {
return this.getElements(selector).length !== 0
}
}
|
javascript
| 9 | 0.667436 | 71 | 18.681818 | 22 |
starcoderdata
|
namespace TexasHoldem.Logic.Players
{
using System.Collections.Generic;
public class StartGameContext
{
public StartGameContext(IReadOnlyCollection playerNames, int startMoney)
{
this.PlayerNames = playerNames;
this.StartMoney = startMoney;
}
public IReadOnlyCollection PlayerNames { get; }
public int StartMoney { get; }
}
}
|
c#
| 9 | 0.703636 | 123 | 29.555556 | 18 |
starcoderdata
|
const cv = global.dut;
const { assertDataDeepEquals, assertDataAlmostDeepEquals, assertMetaData } = global.utils;
const { charMax, charMin, ucharMax, shortMax, shortMin, ushortMax, intMax,
intMin, floatMin, floatMax, doubleMin, doubleMax } = require('./typeRanges');
const rows = 4;
const cols = 3;
const matDataFromValue = val => Array(rows).fill(Array(cols).fill(val));
const createAndAssertMatFilled = (type, value) => {
const mat = new cv.Mat(rows, cols, type, value);
assertMetaData(mat)(rows, cols, type);
if ([cv.CV_32FC1, cv.CV_32FC2, cv.CV_32FC3, cv.CV_32FC4].some(matType => matType === type)) {
assertDataAlmostDeepEquals(matDataFromValue(value), mat.getDataAsArray());
} else {
assertDataDeepEquals(matDataFromValue(value), mat.getDataAsArray());
}
};
module.exports = () =>
describe('constructor fill with value', () => {
it('should initialize CV_8UC1 with correct data', () => {
createAndAssertMatFilled(cv.CV_8UC1, ucharMax);
});
it('should initialize CV_8UC2 with correct data', () => {
createAndAssertMatFilled(cv.CV_8UC2, [ucharMax, 0]);
});
it('should initialize CV_8UC3 with correct data', () => {
createAndAssertMatFilled(cv.CV_8UC3, [ucharMax, 0, ucharMax]);
});
it('should initialize CV_8UC4 with correct data', () => {
createAndAssertMatFilled(cv.CV_8UC4, [ucharMax, 0, ucharMax, 0]);
});
it('should initialize CV_8SC1 with correct data', () => {
createAndAssertMatFilled(cv.CV_8SC1, charMax);
createAndAssertMatFilled(cv.CV_8SC1, charMin);
});
it('should initialize CV_8SC2 with correct data', () => {
createAndAssertMatFilled(cv.CV_8SC2, [charMax, charMin]);
});
it('should initialize CV_8SC3 with correct data', () => {
createAndAssertMatFilled(cv.CV_8SC3, [charMax, charMin, 0]);
});
it('should initialize CV_8SC4 with correct data', () => {
createAndAssertMatFilled(cv.CV_8SC4, [charMax, charMin, 0, charMax]);
});
it('should initialize CV_16UC1 with correct data', () => {
createAndAssertMatFilled(cv.CV_16UC1, ushortMax);
});
it('should initialize CV_16UC2 with correct data', () => {
createAndAssertMatFilled(cv.CV_16UC2, [ushortMax, 0]);
});
it('should initialize CV_16UC3 with correct data', () => {
createAndAssertMatFilled(cv.CV_16UC3, [ushortMax, 0, ushortMax]);
});
it('should initialize CV_16UC4 with correct data', () => {
createAndAssertMatFilled(cv.CV_16UC4, [ushortMax, 0, ushortMax, 0]);
});
it('should initialize CV_16SC1 with correct data', () => {
createAndAssertMatFilled(cv.CV_16SC1, shortMax);
createAndAssertMatFilled(cv.CV_16SC1, shortMin);
});
it('should initialize CV_16SC2 with correct data', () => {
createAndAssertMatFilled(cv.CV_16SC2, [shortMax, shortMin]);
});
it('should initialize CV_16SC3 with correct data', () => {
createAndAssertMatFilled(cv.CV_16SC3, [shortMax, shortMin, 0]);
});
it('should initialize CV_16SC4 with correct data', () => {
createAndAssertMatFilled(cv.CV_16SC4, [shortMax, shortMin, 0, shortMax]);
});
it('should initialize CV_32SC1 with correct data', () => {
createAndAssertMatFilled(cv.CV_32SC1, intMax);
createAndAssertMatFilled(cv.CV_32SC1, intMin);
});
it('should initialize CV_32SC2 with correct data', () => {
createAndAssertMatFilled(cv.CV_32SC2, [intMax, intMin]);
});
it('should initialize CV_32SC3 with correct data', () => {
createAndAssertMatFilled(cv.CV_32SC3, [intMax, intMin, 0]);
});
it('should initialize CV_32SC4 with correct data', () => {
createAndAssertMatFilled(cv.CV_32SC4, [intMax, intMin, 0, intMax]);
});
it('should initialize CV_32FC1 with correct data', () => {
createAndAssertMatFilled(cv.CV_32FC1, floatMax);
createAndAssertMatFilled(cv.CV_32FC1, floatMin);
createAndAssertMatFilled(cv.CV_32FC1, -floatMax);
createAndAssertMatFilled(cv.CV_32FC1, -floatMin);
});
it('should initialize CV_32FC2 with correct data', () => {
createAndAssertMatFilled(cv.CV_32FC2, [floatMax, floatMin]);
createAndAssertMatFilled(cv.CV_32FC2, [-floatMax, -floatMin]);
});
it('should initialize CV_32FC3 with correct data', () => {
createAndAssertMatFilled(cv.CV_32FC3, [floatMax, floatMin, 0]);
createAndAssertMatFilled(cv.CV_32FC3, [-floatMax, -floatMin, 0]);
});
it('should initialize CV_32FC4 with correct data', () => {
createAndAssertMatFilled(cv.CV_32FC4, [floatMax, floatMin, -floatMax, -floatMin]);
});
it('should initialize CV_64FC1 with correct data', () => {
createAndAssertMatFilled(cv.CV_64FC1, doubleMax);
createAndAssertMatFilled(cv.CV_64FC1, doubleMin);
createAndAssertMatFilled(cv.CV_64FC1, -doubleMax);
createAndAssertMatFilled(cv.CV_64FC1, -doubleMin);
});
it('should initialize CV_64FC2 with correct data', () => {
createAndAssertMatFilled(cv.CV_64FC2, [doubleMax, doubleMin]);
createAndAssertMatFilled(cv.CV_64FC2, [-doubleMax, -doubleMin]);
});
it('should initialize CV_64FC3 with correct data', () => {
createAndAssertMatFilled(cv.CV_64FC3, [doubleMax, doubleMin, 0]);
createAndAssertMatFilled(cv.CV_64FC3, [-doubleMax, -doubleMin, 0]);
});
it('should initialize CV_64FC4 with correct data', () => {
createAndAssertMatFilled(cv.CV_64FC4, [doubleMax, doubleMin, -doubleMax, -doubleMin]);
});
});
|
javascript
| 18 | 0.661547 | 95 | 36.831081 | 148 |
starcoderdata
|
func main() {
// Get connection env variable.
conn := common.GetEnv()
// Options.
version := flag.Bool("version", false, "Version")
node := flag.String("node", "", "Etcd node")
port := flag.String("port", "2379", "Etcd port")
dir := flag.String("dir", "/", "Etcd directory")
format := flag.String("format", "JSON", "Data serialization format YAML, TOML or JSON")
output := flag.String("output", "", "Output file")
flag.Parse()
// Print version.
if *version {
fmt.Printf("etcd-export %s\n", common.Version)
os.Exit(0)
}
// Validate input.
if len(conn) < 1 && *node == "" {
log.Fatalf("You need to specify Etcd host.")
}
// Get data format.
f, err := iodatafmt.Format(*format)
if err != nil {
log.Fatal(err.Error())
}
// Setup Etcd client.
if *node != "" {
conn = []string{fmt.Sprintf("http://%v:%v", *node, *port)}
}
client := etcd.NewClient(conn)
// Export data.
res, err := client.Get(*dir, true, true)
if err != nil {
log.Fatal(err.Error())
}
m := etcdmap.Map(res.Node)
// Write output.
if *output != "" {
iodatafmt.Write(*output, m, f)
} else {
iodatafmt.Print(m, f)
}
}
|
go
| 13 | 0.601417 | 88 | 21.6 | 50 |
inline
|
# Copyright (C) 2021-2022 Modin authors
#
# SPDX-License-Identifier: Apache-2.0
"""Core base object ref specific functionality."""
class ObjectRef:
"""
A class that wraps an object ref specific for the backend.
Parameters
----------
ref : object ref
An object ref specific for the backend.
"""
def __init__(self, ref):
self._ref = ref
|
python
| 8 | 0.618454 | 62 | 19.05 | 20 |
starcoderdata
|
# filefuzzer.py
#
# python script
#
# "file fuzzer"
#
# generates a bunch of random data using os.urandom then writes it to fuzzy.csv
# this was used to generate fuzzy.csv
# fuzzy.csv is used to test error handling when reading data
import os
with open('fuzzy.csv', 'wb') as fout:
fout.write(os.urandom(1024*50)) # replace 1024 with size_kb if not unreasonably large
|
python
| 9 | 0.735849 | 89 | 27.615385 | 13 |
starcoderdata
|
from django.conf.urls.defaults import *
from sphene.sphboard.feeds import LatestThreads, LatestGlobalThreads
urlpatterns = patterns('',
#url(r'^$', 'django.views.generic.simple.redirect_to', {'url': 'show/0/'}, name = 'sphboard-index'),
url(r'^feeds/latest/(?P
LatestThreads(),
{},
'sphboard-feeds'),
url(r'^feeds/all/$',
LatestGlobalThreads(),
{},
'sphboard-global-feeds')
)
urlpatterns += patterns('sphene.sphboard.views',
url(r'^$', 'showCategory', {'category_id': '0'}, name = 'sphboard-index'),
url(r'^show/(?P 'showCategory', name = 'sphboard_show_category'),
url(r'^show/(?P 'showCategory', name = 'sphboard_show_category_without_slug'),
url(r'^list_threads/(?P 'listThreads', ),
url(r'^latest/(?P 'showCategory', { 'showType': 'threads' }, name = 'sphboard_latest'),
url(r'^thread/(?P 'showThread', name = 'sphboard_show_thread'),
url(r'^thread/(?P 'showThread', name = 'sphboard_show_thread_without_slug'),
url(r'^options/(?P 'options', name = 'sphboard_options'),
url(r'^move/(?P 'move', name = 'sphboard_move_thread'),
(r'^post/(?P 'post'),
url(r'^post/(?P 'post', name = 'sphboard_post_thread'),
url(r'^reply/(?P 'reply', name = 'sphboard_reply'),
(r'^annotate/(?P 'annotate'),
(r'^hide/(?P 'hide'),
url(r'^move_post_1/(?P 'move_post_1', name='move_post_1'),
url(r'^move_post_2/(?P 'move_post_2', name='move_post_2'),
url(r'^move_post_3_cat/(?P 'move_post_3', name='move_post_3'),
url(r'^move_post_3_thr/(?P 'move_post_3', name='move_post_3'),
url(r'^delete_moved_info/(?P 'delete_moved_info', name='delete_moved_info'),
(r'^vote/(?P 'vote'),
url(r'^togglemonitor_(?P 'toggle_monitor', name = 'sphboard_toggle_user_monitor'),
url(r'^togglemonitor_(?P 'toggle_monitor', name = 'sphboard_toggle_monitor'),
(r'^catchup/(?P 'catchup'),
url(r'^poll/(?P 'edit_poll', name = 'sphboard_edit_poll'),
url(r'^admin/(?P 'admin_user_posts', name = 'sphboard_admin_user_posts'),
url(r'^admin/(?P 'admin_post_delete', name = 'sphboard_admin_post_delete'),
url(r'^admin/(?P 'admin_posts_delete', name = 'sphboard_admin_posts_delete'),
)
|
python
| 10 | 0.469793 | 171 | 81.043478 | 46 |
starcoderdata
|
<?php
$selectedId = (
isset($_GET['groupId']) && is_int((int) $_GET['groupId'])
? $_GET['groupId']
: '0');
$showLabels = (
isset($_GET['showLabels'])
? $_GET['showLabels']
: "false");
?>
<!DOCTYPE html>
<link rel="icon" type="image/png" href="frameworks/led-icon-set/chart_line.png?v=2" />
<script src="frameworks/jquery-1.11.2.min.js">
<script src="frameworks/bootstrap-3.3.2-dist/js/bootstrap.min.js">
<link rel="stylesheet" href="frameworks/bootstrap-3.3.2-dist/css/bootstrap.min.css">
<script src="frameworks/sigmajs/sigma.min.js">
<script src="frameworks/sigmajs/plugins/sigma.parsers.json.min.js">
<script src="frameworks/sigmajs/plugins/sigma.layout.forceAtlas2.min.js">
<script src="frameworks/dagre.min.js">
var selectedGroupId = <?php echo $selectedId; ?>;
var showLabels = <?php echo $showLabels; ?>
<script src="common.js">
<script src="ui-Graph.getColour.js">
<script src="ui-Graph.applyDagre.js">
<script src="ui-Graph.prepareTheGraph.js">
<script src="ui-Graph.logic.js">
body { font-family: sans-serif; padding: 20px; }
.panel-heading { font-size: 120%; font-weight: bold; }
h1 { margin-top: 0em; margin-bottom: 0.5em; }
.page-header { margin-top: 0; padding-top: 0; }
@media print {
#sidebar { display: none; }
}
<body onload="bodyDidLoad()">
<h1 class="page-header">LitFam paper dependencies/citations Graph
<div class="row">
<div class="col-md-10">
<div class="panel panel-default">
<div class="panel-body">
<div id="sigmajsContainer" style="height:85vh;margin:10px;">
<div class="col-md-2" id="sidebar">
<div class="panel panel-default">
<div class="panel-heading">Guide
<ul class="list-group">
<li class="list-group-item"><span style="color: #505693;">█ journal, <2010
<li class="list-group-item"><span style="color: #4E9AFF;">█ journal, >2010
<li class="list-group-item"><span style="color: #5EB231;">█ <2010
<li class="list-group-item"><span style="color: #A5E433;">█ >2010
<li class="list-group-item"><span style="color: #E59F00;">█ journal, <2010
<li class="list-group-item"><span style="color: #FFDF00;">█ journal, >2010
<li class="list-group-item"><span style="color: rgb(100,100,100);">█ journal info
<div class="panel panel-default">
<div class="panel-heading">Group Filter
<ul class="list-group" id="ulGroups">
|
php
| 12 | 0.633766 | 119 | 38.487179 | 78 |
starcoderdata
|
public void checkThatMappingsHaveNoMWReferences() {
Iterator mappings = null;
// check table reference mappings
Collection tableReferenceMappings = getMappingsForClass( MWAbstractTableReferenceMapping.class, getCrimeSceneProject());
assertTrue( "there are no table reference mappings to test.", tableReferenceMappings.size() > 0);
mappings = tableReferenceMappings.iterator();
while (mappings.hasNext()) {
MWAbstractTableReferenceMapping mapping = (MWAbstractTableReferenceMapping) mappings.next();
assertTrue("TableRef mapping " + mapping.getName() + " in " + mapping.getParentDescriptor().getName() + " should not have a table reference.", mapping.getReference() == null);
}
// check many to many mappings
Collection manyToManyMappings = getMappingsForClass( MWManyToManyMapping.class, getCrimeSceneProject());
assertTrue( "there are no MtoM mappings to test.", manyToManyMappings.size() > 0);
mappings = manyToManyMappings.iterator();
while (mappings.hasNext()) {
MWManyToManyMapping mapping = (MWManyToManyMapping) mappings.next();
assertTrue("MtoM mapping " + mapping.getName() + " in " + mapping.getParentDescriptor().getName() + " should not have a table reference.", mapping.getSourceReference() == null && mapping.getTargetReference() == null);
}
}
|
java
| 14 | 0.69209 | 229 | 63.409091 | 22 |
inline
|
<div class="col-md-12">
<?php
echo $this->session->flashdata('notif');
// echo '<div class="notif_dp">
?>
function startCalc(){
interval = setInterval("calc()",1);}
function calc(){
//pendpatan
one = document.autoSumForm.harga_service.value;
two = document.autoSumForm.harga_acc.value;
document.autoSumForm.total.value = (one * 1) + (two * 1);
//pengeluaran
}
function stopCalc(){
clearInterval(interval);}
<div class="col-md-3">
<!-- general form elements -->
<div class="box box-primary">
<div class="box-header">
<h3 class="box-title">Booking Service
/.box-header -->
<!-- form start -->
<form role="form" action="<?php echo base_url()?>ControllerBooking/edit" method="post">
<div class="box-body">
<input type="hidden" name="id_booking" id="id">
<div class="form-group">
Member
<input type="text" class="form-control" id="id_membera" placeholder="Nama Member" required readonly >
<div class="form-group">
<select class="form-control" id="id_mekanik" name="id_mekanik">
<?php foreach($tampil_me->result_array() as $keyy)
{
?>
<option value="<?php echo $keyy['id_mekanik'];?>"><?php echo $keyy['nama_mekanik'];?>
<?php }?>
<div class="form-group">
Service
<select class="form-control" id="st" name="s_service">
<option value="-">Dalam Antrian
<option value="1">Belum Dikerjakan
<option value="2">Sedang Dikerjakan
<option value="3">Selesai
<div class="form-group">
DP
<select class="form-control" id="std" name="status_bayar">
<option value="-">-- Pilih Status DP --
<option value="0">Belum Membayar DP
<option value="1">Sudah Membayar DP
<div class="form-group">
Pembayaran DP
<input type="text" class="form-control" id="jumlah_dp" name="jumlah_dp" placeholder="Jumlah DP" required>
<div class="bootstrap-timepicker">
<div class="form-group">
Selesai
<div class="input-group">
<input type="text" name="estimasi_selesai" class="form-control timepicker">
<div class="input-group-addon">
<i class="fa fa-clock-o">
<!-- /.input group -->
<div class="box-footer">
<button type="submit" class="btn btn-primary">Submit
<button type="reset" class="btn btn-primary">Reset
/.box -->
<div class="modal fade" id="mymodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">× class="sr-only">Close
<h4 class="modal-title" id="myModalLabel">Edit Aksesoris
<div class="modal-body">
<form role="form" action="<?php echo base_url()?>ControllerAcc/edit" method="post">
<div class="box-body">
<input type="hidden" class="form-control" name="id" id="id" >
<div class="form-group">
Aksesoris
<input type="text" id="nm" class="form-control" name="nama_acc" placeholder="Nama" required>
<div class="form-group">
Aksesoris
<input type="text" id="hg" class="form-control" name="harga_acc" placeholder="Harga" required>
<div class="form-group">
<input type="text" id="jn" class="form-control" name="jenis" placeholder="Jenis" required>
/.box-body -->
<div class="box-footer">
<button type="submit" class="btn btn-primary">Edit
<button type="reset" class="btn btn-primary">Reset
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close
(left) -->
<!-- right column -->
<div class="col-md-9">
<!-- general form elements disabled -->
<div class="box box-primary">
<div class="box-header">
<h3 class="box-title">Data Booking
/.box-header -->
<div class="box-body">
<table id="Admin1" class="table table-bordered table-striped">
Member
Service
Aksesoris
Mekanik
Booking
Booking
Service
Pembayaran DP
Bayar DP
Bayar Dp
Service
Selesai
<?php
$a=1;
foreach ($tampil->result_array() as $key) {
?>
echo $a; ?>
echo $key["nama"];?>
echo $key["paket_service"];?>
echo $key["nama_acc"];?>
echo $key["nama_mekanik"];?>
echo $key["jam_booking"];?>
echo $key["tgl_booking"];?>
<?php if ($key["s_service"] == '-') { ?>
class="label bg-yellow">Masi Dalam Antrian
<?php }elseif($key["s_service"] == '1') { ?>
class="label bg-yellow">Belum Dikerjakan
<?php }elseif ($key["s_service"] == '2') { ?>
class="label bg-yellow">Sedang Dikerjakan
<?php }elseif ($key["s_service"] == '3') { ?>
class="label bg-yellow">Selesai
<?php }?>
echo $key["jam_bayar_dp"];?>
<?php if ($key["status_bayar"] == '0') { ?>
class="label bg-yellow">Belum Membayar DP
<?php }elseif($key["status_bayar"] == '1') { ?>
class="label bg-primary">Sudah Membayar DP
<?php } ?>
echo $key["jumlah_dp"];?>
<!-- echo $key["s_service"];?> -->
echo $key["total"];?>
<?php if ($key["estimasi_selesai"] == '-') { ?>
class="label bg-yellow">Masi Dalam Antrian
<?php }else{ ?>
echo $key["estimasi_selesai"];?>
<?php } ?>
<button class="btn btn-danger btn-sm" onclick="hapus('<?php echo $key["id_booking"]; ?>')">Hapus -->
<button class="btn btn-info btn-sm" onclick="edit('<?php echo $key["id_booking"]; ?>','<?php echo $key["nama"]; ?>','<?php echo $key["id_mekanik"]; ?>','<?php echo $key["s_service"]; ?>','<?php echo $key["status_bayar"]; ?>','<?php echo $key["jumlah_dp"]; ?>')">Edit
<?php $a++; } ?>
/.box-body -->
/.box -->
<!-- (right) -->
<script type="text/javascript">
function hapus($id){
var conf=window.confirm('Data Akan Dihapus ?');
if (conf) {
document.location='<?php echo base_url(); ?>ControllerBooking/hapus/'+$id;
}
}
function edit(id,nama,id_mekanik,st,std,jml_dp){
$('#id').val(id);
$('#id_membera').val(nama);
$('#id_mekanik').val(id_mekanik);
$('#st').val(st);
$('#std').val(std);
$('#jumlah_dp').val(jml_dp);
}
|
php
| 9 | 0.322004 | 320 | 51.914729 | 258 |
starcoderdata
|
import React, { Component } from 'react';
import ControlledCarousel from './right-carousel';
class RightColumn extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className='right-column'>
<ControlledCarousel />
);
}
}
export default RightColumn;
|
javascript
| 9 | 0.568282 | 60 | 19.681818 | 22 |
starcoderdata
|
// Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/ui/bin/root_presenter/constants.h"
#include
#include
#include "src/lib/files/file.h"
namespace root_presenter {
uint32_t ChattyMax() {
static bool first_run = true;
static uint32_t chatty_max = 0; // fallback value is quiet and friendly
if (first_run) {
first_run = false; // don't try file again
if (std::string str; files::ReadFileToString("/config/data/chatty_max", &str)) {
if (int file_val = atoi(str.c_str()); file_val >= 0) {
chatty_max = file_val;
}
}
}
return chatty_max;
}
} // namespace root_presenter
|
c++
| 18 | 0.674074 | 84 | 26.931034 | 29 |
starcoderdata
|
#
# Copyright 2012-2014
#
import miner_globals
from base import *
def p_top_command(p):
'''command : TOP integer expression'''
p[0] = TopCommand(p[2], p[3])
def p_bottom_command(p):
'''command : BOTTOM integer expression'''
p[0] = BottomCommand(p[2], p[3])
class TopCommand(CommandBase):
NAME = "TOP"
SHORT_HELP = "TOP expression - Returns at most of top records ordered by expression"
LONG_HELP = """TOP expression
Returns of records with maximum values of expression in decreasing order
Heap sorting is used. O(n*log(number))
"""
def __init__(self, number, exp, ascending=False):
CommandBase.__init__(self)
self.myNumber = number
self.myExpression = exp
self.myAscending = ascending
def getVariableNames(self):
return self.myParent.getVariableNames()
def createGenerator(self, name, parentGeneratorName):
op = "heapq.nsmallest" if self.myAscending else "heapq.nlargest"
s = """
def %s():
import heapq
def getkey( record ):
%s = record
return %s
allData = %s(%s, %s(), key=getkey)
return allData
""" % (name, createTupleString(self.getVariableNames()), self.myExpression.getValue(), op, self.myNumber, parentGeneratorName)
return s
class BottomCommand(TopCommand):
NAME = "BOTTOM"
SHORT_HELP = "BOTTOM expression - Returns at most of bottom records ordered by expression"
LONG_HELP = """BOTTOM expression
Returns of records with minimum values of expression in increasing order
Heap sorting is used. O(n*log(number))
"""
def __init__(self, number, exp):
TopCommand.__init__(self, number, exp, ascending = True)
miner_globals.addKeyWord(command="TOP")
miner_globals.addKeyWord(command="BOTTOM")
miner_globals.addHelpClass(TopCommand)
miner_globals.addHelpClass(BottomCommand)
|
python
| 13 | 0.673196 | 126 | 32.448276 | 58 |
starcoderdata
|
#define LED_BUILTIN 2
#include // handling of WiFi and NTP
#include // handling of the e-ink display
#include // handling of de BME680
unsigned long nextUpdate = 0;
void setup()
{
// initalize serial comunication
Serial.begin(115200);
Serial.println();
Serial.println("----- begin setup -----");
delay(100);
// connect WiFi
connectWiFi();
delay(200);
// set NTP time
setNTP();
delay(200);
// initalize Sensor
initSensor();
delay(200);
// initalize display
initDisplay();
delay(200);
}
void loop()
{
tm timeinfo;
if (millis() > nextUpdate || nextUpdate - millis() > 3600000)
{
getLocalTime(&timeinfo, 3000);
nextUpdate = millis() + (60 - timeinfo.tm_sec) *1000;
Serial.println("\n-----------------------------------------------------");
Serial.println(&timeinfo, "Datum: %d.%m.%y Zeit: %H:%M:%S");
Serial.println("\n----- Update Puffer -----");
drawFrame(); // clear display and draws Frame in buffer
drawClock(timeinfo);
newData(); // chekst for new Sensor Data
drawData(iaqSensor.temperature, iaqSensor.humidity, iaqSensor.pressure/100, iaqSensor.iaq, iaqSensor.staticIaq, iaqSensor.iaqAccuracy);
Serial.println("\n Gas Resitance: " + String(iaqSensor.gasResistance));
Serial.println("IAQ static: " + String(iaqSensor.staticIaq));
Serial.println("IAQ: " + String(iaqSensor.iaq));
Serial.println("IAQ accuracy: " + String(iaqSensor.iaqAccuracy));
Serial.println("\n----- Update Display -----");
display.display(false); // full update
Serial.println("----- Update Done -----\n");
}
delay(500);
}
|
c++
| 12 | 0.623972 | 139 | 23.314286 | 70 |
starcoderdata
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.