code
stringlengths 46
37.2k
| language
stringclasses 9
values | AST_depth
int64 3
30
| alphanumeric_fraction
float64 0.2
0.91
| max_line_length
int64 13
399
| avg_line_length
float64 5.67
140
| num_lines
int64 7
299
| original_docstring
stringlengths 22
42.6k
| source
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|
pub fn assert_json_matches_no_panic<Lhs, Rhs>(
lhs: &Lhs,
rhs: &Rhs,
config: Config,
) -> Result<(), String>
where
Lhs: Serialize,
Rhs: Serialize,
{
let lhs = serde_json::to_value(lhs).unwrap_or_else(|err| {
panic!(
"Couldn't convert left hand side value to JSON. Serde error: {}",
err
)
});
let rhs = serde_json::to_value(rhs).unwrap_or_else(|err| {
panic!(
"Couldn't convert right hand side value to JSON. Serde error: {}",
err
)
});
let diffs = diff(&lhs, &rhs, config);
if diffs.is_empty() {
Ok(())
} else {
let msg = diffs
.into_iter()
.map(|d| d.to_string())
.collect::<Vec<_>>()
.join("\n\n");
Err(msg)
}
} | rust | 18 | 0.476132 | 78 | 23.787879 | 33 | /// Compares two JSON values without panicking.
///
/// Instead it returns a `Result` where the error is the message that would be passed to `panic!`.
/// This is might be useful if you want to control how failures are reported and don't want to deal
/// with panics. | function |
func (r *Handler) SetContext(ctx context.Context) *Handler {
if r == nil {
return r
}
if r.clientName == rjs.ClientGoRedis {
if old, ok := r.implementation.(*clients.GoRedis); ok {
return &Handler{
clientName: r.clientName,
implementation: clients.NewGoRedisClient(ctx, old.Conn),
}
}
}
return r
} | go | 17 | 0.654434 | 60 | 22.428571 | 14 | // SetContext helps redis-clients, provide use of command level context
// in the ReJSON commands.
// Currently, only go-redis@v8 supports command level context, therefore
// a separate method is added to support it, maintaining the support for
// other clients and for backward compatibility. (nitishm/go-rejson#46) | function |
public class MergekSortedLists {
public ListNode mergeKLists(ListNode[] lists) {
if(lists.length < 1) return null;
PriorityQueue<ListNode> queue = new PriorityQueue<>(lists.length, new Comparator<ListNode>(){
@Override
public int compare(ListNode node1, ListNode node2){
return node1.val - node2.val;
}
});
for(ListNode node : lists){
if(node != null)
queue.add(node);
}
ListNode head = new ListNode(0);
ListNode current = head;
while(!queue.isEmpty()){
ListNode p_node = queue.poll();
current.next = p_node;
current = current.next;
if(current.next != null)
queue.add(current.next);
}
return head.next;
}
} | java | 16 | 0.527943 | 102 | 30.185185 | 27 | /**
* Creator : wangtaishan
* Date : 2018/9/2
* Title : 23. Merge k Sorted Lists
* Description :
*
*Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
*
* Example:
*
* Input:
* [
* 1->4->5,
* 1->3->4,
* 2->6
* ]
* Output: 1->1->2->3->4->4->5->6
*
* Analysis :
*
* Using PriorityQueue datatype, it has many implementations. The most common one is binary heap.
*
* the top element of the heap is the least number among the elements in heap.
*
*
* solution 2:
*
* using the idea of merge sort. treat list as an element a number in original merge sort case.
*
* //the time complexity is O(nlogk)
*
* //n represents the total number of nodes
* //k represents the number of lists.
*
* //T(k) = 2(k/2) + n;
*
*/ | class |
final class ServletContextCleaner {
private static final Logger LOG = LoggerFactory.getLogger(ServletContextCleaner.class);
private static final Set<String> REMOVE_PREFIX = ImmutableSet.of(
"org.jboss.resteasy",
"resteasy",
"org.apache.shiro",
"sonia.scm"
);
private ServletContextCleaner() {
}
/**
* Remove cached attributes from {@link ServletContext}.
*
* @param servletContext servlet context
*/
static void cleanup(ServletContext servletContext) {
LOG.info("remove cached attributes from context");
Enumeration<String> attributeNames = servletContext.getAttributeNames();
while( attributeNames.hasMoreElements()) {
String name = attributeNames.nextElement();
if (shouldRemove(name)) {
LOG.info("remove attribute {} from servlet context", name);
servletContext.removeAttribute(name);
} else {
LOG.info("keep attribute {} in servlet context", name);
}
}
}
private static boolean shouldRemove(String name) {
for (String prefix : REMOVE_PREFIX) {
if (name.startsWith(prefix)) {
return true;
}
}
return false;
}
} | java | 13 | 0.666953 | 89 | 24.911111 | 45 | /**
* Remove cached resources from {@link ServletContext} to allow a clean restart of scm-manager without stale or
* duplicated data.
*
* @since 2.0.0
*/ | class |
class Device:
"""GPU Device class.
This class manages GPU id.
The purpose of this device class instead of PyTorch device class is
to assign GPU ids when the algorithm is trained in parallel with
scikit-learn utilities such as `sklearn.model_selection.cross_validate` or
`sklearn.model_selection.GridSearchCV`.
.. code-block:: python
from d3rlpy.context import parallel
from d3rlpy.algos.cql import CQL
from sklearn.model_selection import cross_validate
cql = CQL(use_gpu=True)
# automatically assign different GPUs to parallel training process
with parallel():
scores = cross_validate(cql, ..., n_jobs=2)
Args:
idx: GPU id.
"""
_idx: int
def __init__(self, idx: int = 0):
self._idx = idx
def get_id(self) -> int:
"""Returns GPU id.
Returns:
GPU id.
"""
return self._idx
def __deepcopy__(self, memo: Any) -> "Device":
if get_parallel_flag():
# this bahavior is only for sklearn.base.clone
self._idx += 1
if self._idx >= get_gpu_count():
self._idx = 0
obj = self.__class__(self._idx)
return obj
def __eq__(self, obj: Any) -> bool:
if isinstance(obj, Device):
return self._idx == obj.get_id()
raise ValueError("Device cannot be comapred with non Device objects.")
def __ne__(self, obj: Any) -> bool:
return not self.__eq__(obj)
def get_params(self, deep: bool = False) -> Dict[str, Any]:
return {"idx": self._idx} | python | 12 | 0.573006 | 78 | 26.644068 | 59 | GPU Device class.
This class manages GPU id.
The purpose of this device class instead of PyTorch device class is
to assign GPU ids when the algorithm is trained in parallel with
scikit-learn utilities such as `sklearn.model_selection.cross_validate` or
`sklearn.model_selection.GridSearchCV`.
.. code-block:: python
from d3rlpy.context import parallel
from d3rlpy.algos.cql import CQL
from sklearn.model_selection import cross_validate
cql = CQL(use_gpu=True)
# automatically assign different GPUs to parallel training process
with parallel():
scores = cross_validate(cql, ..., n_jobs=2)
Args:
idx: GPU id.
| class |
def minutes_for_days(cal, ordered_days=False):
random.seed('deterministic')
if ordered_days:
ordered_session_list = random.sample(list(cal.all_sessions), 500)
ordered_session_list.sort()
def session_picker(day):
return ordered_session_list[day]
else:
def session_picker(day):
return random.choice(cal.all_sessions[:-1])
return [cal.minutes_for_session(session_picker(cnt))
for cnt in range(500)] | python | 14 | 0.636743 | 73 | 39 | 12 |
500 randomly selected days.
This is used to make sure our test coverage is unbiased towards any rules.
We use a random sample because testing on all the trading days took
around 180 seconds on my laptop, which is far too much for normal unit
testing.
We manually set the seed so that this will be deterministic.
Results of multiple runs were compared to make sure that this is actually
true.
This returns a generator of tuples each wrapping a single generator.
Iterating over this yields a single day, iterating over the day yields
the minutes for that day.
| function |
public class DeclinedPaymentException : DeclinedTransactionException
{
public CreatePaymentResult CreatePaymentResult => _errors?.PaymentResult;
public DeclinedPaymentException(System.Net.HttpStatusCode statusCode, string responseBody, PaymentErrorResponse errors)
: base(BuildMessage(errors, responseBody), statusCode, responseBody, errors?.ErrorId, errors?.Errors)
{
_errors = errors;
}
readonly PaymentErrorResponse _errors;
static string BuildMessage(PaymentErrorResponse errors, string responseBody)
{
Payment payment = errors?.PaymentResult?.Payment;
if (payment != null)
{
return "declined payment '" + payment.Id + "' with status '" + payment.Status + "'";
}
return "the Ingenico ePayments platform returned a declined refund response";
}
} | c# | 13 | 0.651087 | 127 | 47.473684 | 19 | /// <summary>
/// Represents an error response from a create payment call.
/// </summary> | class |
public static HttpRequestProperties ODataProperties(this HttpRequest request)
{
if (request == null)
{
throw Error.ArgumentNull("request");
}
HttpRequestProperties properties;
if (!HttpRequestPropertiesDict.TryGetValue(request, out properties))
{
properties = new HttpRequestProperties(request);
HttpRequestPropertiesDict[request] = properties;
}
return properties;
} | c# | 11 | 0.56926 | 80 | 36.714286 | 14 | /// <summary>
/// Gets the <see cref="HttpRequestProperties"/> instance containing OData methods and properties
/// for given <see cref="HttpRequest"/>.
/// </summary>
/// <param name="request">The request of interest.</param>
/// <returns>
/// An object through which OData methods and properties for given <paramref name="request"/> are available.
/// </returns> | function |
Value merge_defs(Source::Pos pos, rc<Env> env, optional<const Value&> existing, const Value& fresh) {
if (!existing) return fresh;
else if (fresh.type.of(K_UNDEFINED)) return *existing;
else if (existing->type.of(K_UNDEFINED)) return fresh;
else if (existing->type.of(K_FORM_FN)) {
if (fresh.form == existing->form) {
if (fresh.type.of(K_FUNCTION))
*(rc<AbstractFunction>)fresh.data.fn = *(rc<AbstractFunction>)existing->data.fl_fn;
if (fresh.type.of(K_FORM_FN))
*(rc<AbstractFunction>)fresh.data.fl_fn = *(rc<AbstractFunction>)existing->data.fl_fn;
return fresh;
}
else return add_form_overload(pos, *existing, fresh);
}
else if (existing->type.of(K_FORM_ISECT)) {
auto found = t_overload_for(existing->type, fresh.form);
if (found) {
auto types = t_form_isect_members(existing->type);
auto cases = existing->data.fl_isect->overloads;
Value merged = merge_defs(pos, env, some<const Value&>(cases[fresh.form]), fresh);
if (merged.type == T_ERROR) return merged;
else {
types[fresh.form] = merged.type;
cases[fresh.form] = merged;
return v_form_isect(pos, t_form_isect(types), existing->form, move(cases));
}
}
else {
return add_form_overload(pos, *existing, fresh);
}
}
else if (existing->type.of(K_FUNCTION)) {
if (existing->form != fresh.form) {
return add_form_overload(pos, *existing, fresh);
}
else if (fresh.type.of(K_FORM_FN) || fresh.type.of(K_UNDEFINED))
return *existing;
else {
return add_type_overload(pos, *existing, fresh);
}
}
else if (existing->type.of(K_INTERSECT)) {
if (existing->form != fresh.form) {
return add_form_overload(pos, *existing, fresh);
}
else if (fresh.type.of(K_UNDEFINED) || fresh.type.of(K_FORM_FN))
return *existing;
else {
return add_type_overload(pos, *existing, fresh);
}
}
else panic("Couldn't merge defs!");
return v_error({});
} | c++ | 26 | 0.50811 | 106 | 44.685185 | 54 | // Unifies two values representing functions, which may or may not be fully-defined.
// In general, this function intends to:
// - Replace undefined/form-level versions of functions with their concrete values.
// - Merge values with different forms into form-level intersections.
// - Merge values with different types into type-level intersections.
// - Return an error value if an incompatibility is observed.
| function |
public boolean process( int sideLength,
@Nullable double[] diag,
@Nullable double[] off,
double[] eigenvalues ) {
if (diag != null && off != null)
helper.init(diag, off, sideLength);
if (Q == null)
Q = CommonOps_DDRM.identity(helper.N);
helper.setQ(Q);
this.followingScript = true;
this.eigenvalues = eigenvalues;
this.fastEigenvalues = false;
return _process();
} | java | 9 | 0.492481 | 52 | 37.071429 | 14 | /**
* Computes the eigenvalue of the provided tridiagonal matrix. Note that only the upper portion
* needs to be tridiagonal. The bottom diagonal is assumed to be the same as the top.
*
* @param sideLength Number of rows and columns in the input matrix.
* @param diag Diagonal elements from tridiagonal matrix. Modified.
* @param off Off diagonal elements from tridiagonal matrix. Modified.
* @return true if it succeeds and false if it fails.
*/ | function |
func waitForDeletion(ctx context.Context, clientset k8sclient.Interface, pvcName, ns string) error {
for true {
_, err := clientset.CoreV1().PersistentVolumeClaims(ns).Get(ctx, pvcName, metav1.GetOptions{})
if k8serrors.IsNotFound(err) {
break
} else if err != nil {
return err
}
select {
case <-time.After(time.Second / 20):
continue
case <-ctx.Done():
return fmt.Errorf("context ended waiting for PVC %s in %s to be deleted", pvcName, ns)
}
}
return nil
} | go | 13 | 0.684426 | 100 | 27.764706 | 17 | // waitForDeletion waits for the provided pvcName to not be found, and returns early if any error besides 'not found' is given | function |
static void eqos_eee_ctrl_timer(unsigned long data)
{
struct eqos_prv_data *pdata =
(struct eqos_prv_data *)data;
DBGPR_EEE("-->eqos_eee_ctrl_timer\n");
eqos_enable_eee_mode(pdata);
DBGPR_EEE("<--eqos_eee_ctrl_timer\n");
} | c | 8 | 0.688596 | 51 | 27.625 | 8 | /*!
* \brief API to control EEE mode.
*
* \details This function will move the MAC transmitter in LPI mode
* if there is no data transfer and MAC is not already in LPI state.
*
* \param[in] data - data hook
*
* \return void
*/ | function |
def create_streamer(file, connect_to='tcp://127.0.0.1:5555', loop=True):
if os.path.isfile(file):
cap = cv2.VideoCapture(file)
else:
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), file)
sender = imagezmq.ImageSender(connect_to=connect_to)
host_name = socket.gethostname()
while True:
ret, frame = cap.read()
if ret:
sender.send_image(host_name, frame)
else:
if loop:
cap = cv2.VideoCapture(file)
else:
break | python | 14 | 0.576854 | 78 | 33.625 | 16 |
You can use this function to emulate an IP camera for the counting apps.
Parameters
----------
file : str
Path to the video file you want to stream.
connect_to : str, optional
Where the video shall be streamed to.
The default is 'tcp://127.0.0.1:5555'.
loop : bool, optional
Whether the video shall be looped. The default is True.
Returns
-------
None.
| function |
private Thread CreateNewThread(string customName)
{
TurboContract.Ensures(TurboContract.Result<Thread>() != null);
Thread res = new Thread(ThreadStartUpProc);
int threadNum = Interlocked.Increment(ref _currentThreadNum);
res.IsBackground = _isBackgroundThreads;
if (string.IsNullOrEmpty(customName))
res.Name = string.Format("{0} (#{1})", _name, threadNum);
else
res.Name = string.Format("{0} (#{1}). {2}", _name, threadNum, customName);
return res;
} | c# | 13 | 0.576329 | 90 | 47.666667 | 12 | /// <summary>
/// Creates a new Thread (does not start that Thread)
/// </summary>
/// <param name="customName">Specific name for thread</param>
/// <returns>Created thread</returns> | function |
public class DeviceRemovedEventArgs
{
public ButtplugClientDevice Device { get; }
public DeviceRemovedEventArgs(ButtplugClientDevice aDevice)
{
Device = aDevice;
}
} | c# | 8 | 0.626728 | 67 | 26.25 | 8 | /// <summary>
/// Event wrapper for Buttplug DeviceAdded or DeviceRemoved messages. Used when the server
/// informs the client of a device connecting or disconnecting.
/// </summary> | class |
boolean validatePanel() {
if (manualRadioButton.isSelected()) {
return manualImageDirPath != null && manualImageDirPath.toFile().exists();
} else if (imageTable.getSelectedRow() != -1) {
Path path = Paths.get((String) imageTableModel.getValueAt(imageTable.convertRowIndexToModel(imageTable.getSelectedRow()), 2));
return path != null && path.toFile().exists();
} else {
return false;
}
} | java | 17 | 0.609342 | 138 | 46.2 | 10 | /**
* Should we enable the next button of the wizard?
*
* @return true if a proper image has been selected, false otherwise
*/ | function |
static bool s10_free_buffers(struct fpga_manager *mgr)
{
struct s10_priv *priv = mgr->priv;
uint num_free = 0;
uint i;
for (i = 0; i < NUM_SVC_BUFS; i++) {
if (!priv->svc_bufs[i].buf) {
num_free++;
continue;
}
if (!test_and_set_bit_lock(SVC_BUF_LOCK,
&priv->svc_bufs[i].lock)) {
stratix10_svc_free_memory(priv->chan,
priv->svc_bufs[i].buf);
priv->svc_bufs[i].buf = NULL;
num_free++;
}
}
return num_free == NUM_SVC_BUFS;
} | c | 14 | 0.585837 | 54 | 22.35 | 20 | /*
* Free buffers allocated from the service layer's pool that are not in use.
* Return true when all buffers are freed.
*/ | function |
public String generateUsername(String regName) {
if (regName.equals("{PLATFORM}")) {
return JiveGlobals.getProperty("plugin.gateway.facebook.platform.apikey")+"|"+JiveGlobals.getProperty("plugin.gateway.facebook.platform.apisecret");
}
else if (regName.indexOf("@") > -1) {
if (getTransport().getType().equals(TransportType.gtalk)) {
return regName;
}
else {
return regName.substring(0, regName.indexOf("@"));
}
}
else {
if (getTransport().getType().equals(TransportType.gtalk)) {
return regName+"@gmail.com";
}
else {
return regName;
}
}
} | java | 14 | 0.515707 | 160 | 35.428571 | 21 | /**
* Returns a username based off of a registered name (possible JID) passed in.
*
* If it already looks like a username, returns what was passed in.
*
* @param regName Registered name to turn into a username.
* @return Converted registered name.
*/ | function |
lstm* reset_lstm(lstm* f){
if(f == NULL)
return NULL;
int i,j,k;
for(i = 0; i < 4; i++){
for(j = 0; j < f->output_size*f->input_size; j++){
if(exists_d_params_lstm(f)){
f->d_w[i][j] = 0;
}
}
for(j = 0; j < f->output_size*f->output_size; j++){
if(exists_d_params_lstm(f)){
f->d_u[i][j] = 0;
}
if(j < f->output_size){
if(exists_d_params_lstm(f))
f->d_biases[i][j] = 0;
if(!i){
f->dropout_mask_up[j] = 1;
}
if(!i){
f->dropout_mask_right[j] = 1;
}
}
}
}
for(i = 0; i < f->window; i++){
for(j = 0; j < 4; j++){
for(k = 0; k < f->output_size; k++){
f->lstm_z[i][j][k] = 0;
f->lstm_hidden[i][k] = 0;
f->lstm_cell[i][k] = 0;
f->out_up[i][k] = 0;
}
}
}
if(exists_edge_popup_stuff_lstm(f)){
for(i = 0; i < 4; i++){
for(j = 0; j < f->output_size*f->input_size; j++){
f->d_w_scores[i][j] = 0;
}
for(j = 0; j < f->output_size*f->output_size; j++){
f->d_u_scores[i][j] = 0;
}
sort(f->w_scores[i],f->w_indices[i],0,f->output_size*f->input_size-1);
sort(f->u_scores[i],f->u_indices[i],0,f->output_size*f->output_size-1);
get_used_outputs_lstm(f->w_active_output_neurons[i],f->input_size,f->output_size,f->w_indices[i],f->k_percentage);
get_used_outputs_lstm(f->u_active_output_neurons[i],f->output_size,f->output_size,f->u_indices[i],f->k_percentage);
}
}
if(f->norm_flag == GROUP_NORMALIZATION){
for(i = 0; i < f->window/f->n_grouped_cell; i++){
reset_bn(f->bns[i]);
}
}
return f;
} | c | 15 | 0.391763 | 127 | 33.947368 | 57 | /* this function reset all the arrays of a lstm layer
* used during the feed forward and backpropagation
* You have a lstm* f structure, this function resets all the arrays used
* for the feed forward and back propagation with partial derivatives D inculded
* but the weights and D1 and D2 don't change
*
*
* Input:
*
* @ lstm* f:= a lstm* f layer
*
* */ | function |
def create_card_with_note(self, note):
url = self._build_url("projects", "columns", str(self.id), "cards")
json = None
if note:
json = self._json(
self._post(
url, data={"note": note}, headers=Project.CUSTOM_HEADERS
),
201,
)
return self._instance_or_null(ProjectCard, json) | python | 15 | 0.479899 | 76 | 35.272727 | 11 | Create a note card in this project column.
:param str note:
(required), the note content
:returns:
the created card
:rtype:
:class:`~github3.projects.ProjectCard`
| function |
public class SwingFormComponentListener implements ComponentListener {
private JPanel panel = null;
private static final String J_FILE_CHOOSER = "JFileChooser";
private final Map<String,SwingField> field_map;
private final AppContext conn;
private final Logger log;
public SwingFormComponentListener(AppContext c) {
conn=c;
field_map=new LinkedHashMap<>();
log = conn.getService(LoggerService.class).getLogger(getClass());
}
public <I> SwingField<I> getSwingField(Field<I> f){
String key = f.getKey();
@SuppressWarnings("unchecked")
SwingField<I> result = field_map.get(key);
if( result != null ){
return result;
}
result = new SwingField<>(conn, f);
field_map.put(key, result);
return result;
}
@Override
public void componentHidden(ComponentEvent e) {
log.debug("hidden " + e.paramString());
}
@Override
public void componentMoved(ComponentEvent e) {
// TODO Auto-generated method stub
}
@Override
public void componentResized(ComponentEvent e) {
log.debug("resize " + e.paramString());
}
@Override
public void componentShown(ComponentEvent e) {
log.debug("shown " + e.paramString());
}
/**
* Get a JPanel containing the filled editing controls for this form. Note
* that this code assumes that only a single Panel is in existance at a time
* and while the panel is in use no other edits are made to the Form other
* than through the Panel
* @param form
*
* @param validate
* boolean should the form be validated to show errors in initial
* state
*
* @return JPanel
* @throws Exception
*/
public JPanel getPanel(Iterable<Field> form,boolean validate) throws Exception {
panel = new JPanel();
panel.setLayout(new SpringLayout());
int nrow = 0;
// build form contents from fields
for (Field field : form) {
try{
SwingField f = getSwingField(field);
f.addLabel(panel);
f.addInput(panel,null);
nrow++;
if(validate){
// pre validate the inputs
f.validate();
}
}catch(Exception e){
conn.error(e, "Error registering field");
}
}
makeCompactGrid(panel, nrow, 2, 5, 5, 5, 5);
panel.addComponentListener(this);
return panel;
}
/** Validate a form (Including updating SwingField errors)
*
* @param form
* @return boolean false if SwingFields fail to validate
* @throws ValidateException
*/
public boolean validate(Form form) throws ValidateException{
boolean ok = true;
for(Field f : form){
SwingField sf = getSwingField(f);
if( ! sf.validate()){
ok = false;
}
}
if( ok ){
for(FormValidator val : form.getValidators()){
val.validate(form);
}
return true;
}
return false;
}
public static JFileChooser getChooser(AppContext conn){
JFileChooser chooser = (JFileChooser) conn.getAttribute(J_FILE_CHOOSER);
if( chooser == null ){
chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
conn.setAttribute(J_FILE_CHOOSER, chooser);
}
return chooser;
}
/* Used by makeCompactGrid. */
private static SpringLayout.Constraints getConstraintsForCell(int row,
int col, Container parent, int cols) {
SpringLayout layout = (SpringLayout) parent.getLayout();
Component c = parent.getComponent(row * cols + col);
return layout.getConstraints(c);
}
/**
* Aligns the first <code>rows</code> * <code>cols</code> components of
* <code>parent</code> in a grid. Each component in a column is as wide as
* the maximum preferred width of the components in that column; height is
* similarly determined for each row. The parent is made just big enough to
* fit them all.
*
* @param parent
*
* @param rows
* number of rows
* @param cols
* number of columns
* @param initialX
* x location to start the grid at
* @param initialY
* y location to start the grid at
* @param xPad
* x padding between cells
* @param yPad
* y padding between cells
*/
public static void makeCompactGrid(Container parent, int rows, int cols,
int initialX, int initialY, int xPad, int yPad) {
SpringLayout layout;
try {
layout = (SpringLayout) parent.getLayout();
} catch (ClassCastException exc) {
System.err
.println("The first argument to makeCompactGrid must use SpringLayout.");
return;
}
// Align all cells in each column and make them the same width.
Spring x = Spring.constant(initialX);
for (int c = 0; c < cols; c++) {
Spring width = Spring.constant(0);
for (int r = 0; r < rows; r++) {
width = Spring.max(width, getConstraintsForCell(r, c, parent,
cols).getWidth());
}
for (int r = 0; r < rows; r++) {
SpringLayout.Constraints constraints = getConstraintsForCell(r,
c, parent, cols);
constraints.setX(x);
constraints.setWidth(width);
}
x = Spring.sum(x, Spring.sum(width, Spring.constant(xPad)));
}
// Align all cells in each row and make them the same height.
Spring y = Spring.constant(initialY);
for (int r = 0; r < rows; r++) {
Spring height = Spring.constant(0);
for (int c = 0; c < cols; c++) {
height = Spring.max(height, getConstraintsForCell(r, c, parent,
cols).getHeight());
}
for (int c = 0; c < cols; c++) {
SpringLayout.Constraints constraints = getConstraintsForCell(r,
c, parent, cols);
constraints.setY(y);
constraints.setHeight(height);
}
y = Spring.sum(y, Spring.sum(height, Spring.constant(yPad)));
}
// Set the parent's size.
SpringLayout.Constraints pCons = layout.getConstraints(parent);
pCons.setConstraint(SpringLayout.SOUTH, y);
pCons.setConstraint(SpringLayout.EAST, x);
}
public void setComponentValues(){
for(SwingField field : field_map.values()){
try {
field.setComponentValue();
} catch (Exception e) {
conn.error(e,"Error setting compoment: "+field.toString());
}
}
}
} | java | 16 | 0.666219 | 82 | 26.82243 | 214 | /** class to map {@link Field}s to {@link SwingField}s and handle events.
* This also performs the default mapping of Forms to panels.
* @author spb
*
*/ | class |
def update_memory(self, dataset, t, batch_size):
dataloader = DataLoader(dataset, batch_size=batch_size)
tot = 0
for mbatch in dataloader:
x, y, tid = mbatch[0], mbatch[1], mbatch[-1]
if tot + x.size(0) <= self.patterns_per_experience:
if t not in self.memory_x:
self.memory_x[t] = x.clone()
self.memory_y[t] = y.clone()
self.memory_tid[t] = tid.clone()
else:
self.memory_x[t] = torch.cat((self.memory_x[t], x), dim=0)
self.memory_y[t] = torch.cat((self.memory_y[t], y), dim=0)
self.memory_tid[t] = torch.cat((self.memory_tid[t], tid),
dim=0)
else:
diff = self.patterns_per_experience - tot
if t not in self.memory_x:
self.memory_x[t] = x[:diff].clone()
self.memory_y[t] = y[:diff].clone()
self.memory_tid[t] = tid[:diff].clone()
else:
self.memory_x[t] = torch.cat((self.memory_x[t], x[:diff]),
dim=0)
self.memory_y[t] = torch.cat((self.memory_y[t], y[:diff]),
dim=0)
self.memory_tid[t] = torch.cat((self.memory_tid[t],
tid[:diff]), dim=0)
break
tot += x.size(0) | python | 18 | 0.406111 | 78 | 51.4 | 30 |
Update replay memory with patterns from current experience.
| function |
class RingBuffer {
private byte[][] buffers;
private int unit;
private int count;
private long capacity;
/**
* Index number of the next position to be read (index number starts from 0)
* */
private volatile long readPos;
/**
* The index number of the next position to be written (the index number starts from 0),
* and the variable value is equal to the number of bytes written
* */
private volatile long writePos;
private volatile long minReadablePos;
private volatile long maxReadyWritePos;
private volatile long cachedValue;
public RingBuffer(int unit, int count) {
if (Long.bitCount(unit) != 1 || Long.bitCount(count) != 1)
throw new IllegalArgumentException("unit and count must be powers of 2");
this.unit = unit;
this.count = count;
this.capacity = (long) unit * (long) count;
buffers = new byte[count][];
for (int i = 0; i < buffers.length; i++) {
buffers[i] = new byte[unit];
}
}
public int writeWithLock(ByteBuffer src) {
int remaining = src.remaining();
long currentPos = writePos;
long nextPos = currentPos + remaining;
long wrapPoint = nextPos - capacity;
long cachedValue = this.cachedValue;
if (wrapPoint > cachedValue || cachedValue > currentPos) {
while (wrapPoint > (cachedValue = readPos)) {
LockSupport.parkNanos(1L);
}
this.cachedValue = cachedValue;
}
return write(src);
}
public void unLock(long position) {
readPos = position;
}
public int write(ByteBuffer src) {
int remaining = src.remaining();
int length = remaining;
maxReadyWritePos += length;
long currentPos = writePos;
int bufferIndex = bufferIndex(currentPos);
int bufferPos = bufferPos(currentPos);
while (remaining > 0) {
byte[] dest = buffers[bufferIndex];
int localLength = Math.min(remaining, dest.length - bufferPos);
src.get(dest, bufferPos, localLength);
bufferPos += localLength;
remaining -= localLength;
if (bufferPos == dest.length) {
bufferIndex = (bufferIndex + 1) & (buffers.length - 1);// next buffer index
bufferPos = 0;
}
}
writePos += length;
return length;
}
int bufferIndex(long position) {
return (int) ((position / unit) & (count - 1));
}
int bufferPos(long position) {
return (int) (position & (unit - 1));
}
public long position() {
return writePos;
}
public int read(ByteBuffer dst, long position) {
long writePos = this.writePos;
if (position >= writePos || position < minReadablePos) {
return -1;
}
int backup = dst.position();
int bufferIndex = bufferIndex(position);
int bufferPos = bufferPos(position);
long readPos = position;
int remaining = dst.remaining();
int length = remaining;
while (remaining > 0 && readPos < writePos) {
byte[] src = buffers[bufferIndex];
int localLength = Math.min(remaining, src.length - bufferPos);
dst.put(src, bufferPos, localLength);
bufferPos += localLength;
readPos += localLength;
remaining -= localLength;
if (bufferPos == src.length) {
bufferIndex = (bufferIndex + 1) & (buffers.length - 1);// next buffer index
bufferPos = 0;
}
}
// check available
long minReadablePos = Math.max(this.minReadablePos, maxReadyWritePos - capacity);
if (minReadablePos > position) {
dst.position(backup);
return -1;
}
this.minReadablePos = minReadablePos;
return length - remaining;
}
public ByteBuffer sliceAsReadOnly(long startPos) {
long endPos = writePos;
long minReadablePos = Math.max(this.minReadablePos, maxReadyWritePos - capacity);
if (startPos >= endPos || startPos < minReadablePos) {
throw new IndexOutOfBoundsException(Long.toString(startPos));
}
int length = (int) (endPos - startPos);
int bufferIndex = bufferIndex(startPos);
int bufferPos = bufferPos(startPos);
if (bufferIndex == bufferIndex(endPos) && bufferPos < bufferPos(endPos)) {
ByteBuffer dst = ByteBuffer.wrap(buffers[bufferIndex]);
dst.position(bufferPos).limit(bufferPos + length);
return dst.asReadOnlyBuffer();
}
ByteBuffer dst = ByteBuffer.allocate(length);
read(dst, startPos);
dst.flip();
return dst.asReadOnlyBuffer();
}
public boolean truncate(long position) {
long minReadablePos = Math.max(this.minReadablePos, maxReadyWritePos - capacity);
if (position < minReadablePos) {
return false;
}
maxReadyWritePos = position;
writePos = position;
return true;
}
public void release() {
this.reset();
this.buffers = null;
}
public void reset() {
writePos = 0;
readPos = 0;
minReadablePos = 0;
maxReadyWritePos = 0;
cachedValue = 0;
}
public long getCapacity() {
return capacity;
}
} | java | 15 | 0.558054 | 93 | 29.287234 | 188 | /**
* 1. Both write and read allow concurrent operations
* 2. Both sliceasreadonly and read allow concurrent operations
* 3. Both sliceasreadonly and write do not allow concurrent operations
* 4. Write or read operations are not allowed during truncate, reset and release operations
*
* */ | class |
func (ccs *crChains) makeChainForNewOp(targetPtr data.BlockPointer, newOp op) error {
switch realOp := newOp.(type) {
case *createOp:
return ccs.makeChainForNewOpWithUpdate(targetPtr, newOp, &realOp.Dir)
case *rmOp:
return ccs.makeChainForNewOpWithUpdate(targetPtr, newOp, &realOp.Dir)
case *renameOp:
co, err := newCreateOp(realOp.NewName, realOp.NewDir.Unref, data.File)
if err != nil {
return err
}
err = ccs.makeChainForNewOpWithUpdate(targetPtr, co, &co.Dir)
if err != nil {
return err
}
chain, ok := ccs.byMostRecent[targetPtr]
if !ok {
return errors.Errorf("Couldn't find chain for %v after making it",
targetPtr)
}
if len(chain.ops) != 1 {
return errors.Errorf("Chain of unexpected length for %v after "+
"making it", targetPtr)
}
chain.ops[0] = realOp
return nil
case *setAttrOp:
return ccs.makeChainForNewOpWithUpdate(targetPtr, newOp, &realOp.Dir)
case *syncOp:
return ccs.makeChainForNewOpWithUpdate(targetPtr, newOp, &realOp.File)
default:
return errors.Errorf("Couldn't make chain with unknown operation %s",
newOp)
}
} | go | 13 | 0.714545 | 85 | 30.457143 | 35 | // makeChainForNewOp makes a new chain for an op that does not yet
// have its pointers initialized. It does so by setting Unref and Ref
// to be the same for the duration of this function, and calling the
// usual makeChainForOp method. This function is not goroutine-safe
// with respect to newOp. Also note that rename ops will not be split
// into two ops; they will be placed only in the new directory chain. | function |
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
public static bool RemoveAllACE(string dc,
string distinguishedname,
string username,
string password)
{
DirectoryEntry dirEntry = new DirectoryEntry(
string.Format("LDAP://{0}/{1}", dc, distinguishedname),
username, password,
AuthenticationTypes.Secure);
IADsSecurityDescriptor sd;
try
{
sd = (IADsSecurityDescriptor)dirEntry.Properties["nTSecurityDescriptor"].Value;
}
catch (System.Runtime.InteropServices.COMException e)
{
string errorMessage = e.Message;
TestClassBase.BaseTestSite.Log.Add(LogEntryKind.Comment, "RemoveAllACE : " + errorMessage);
throw;
}
IADsAccessControlList dacl = (IADsAccessControlList)sd.DiscretionaryAcl;
foreach (AccessControlEntry ace in dacl)
{
dacl.RemoveAce(ace);
}
sd.DiscretionaryAcl = dacl;
dirEntry.Properties["nTSecurityDescriptor"].Value = sd;
dirEntry.CommitChanges();
return true;
} | c# | 15 | 0.53966 | 120 | 44.580645 | 31 | /// <summary>
/// Removes all ACE rights for the ntSecurityDescriptor for specified user.
/// </summary>
/// <param name="distinguishedname">specifies dn</param>
/// <param name="username">user name</param>
/// <param name="password">password</param>
/// <returns></returns> | function |
protected long allocateSecondary(long size){
secondaryLock.readLock().lock();
try {
while(true){
final long out = secondaryWritePos.get();
final long newSecondaryPos = out + size;
if(newSecondaryPos >= secondaryMapper.size()){
break;
} else {
if(secondaryWritePos.compareAndSet(out, newSecondaryPos)) return out;
}
}
} finally {
secondaryLock.readLock().unlock();
}
secondaryLock.writeLock().lock();
try {
if(secondaryWritePos.get() + size >= secondaryMapper.size())
secondaryMapper.doubleLength();
} catch(Exception e){
throw new RuntimeException(e);
} finally {
secondaryLock.writeLock().unlock();
}
return allocateSecondary(size);
} | java | 13 | 0.675599 | 74 | 26.307692 | 26 | /**Allocates the given amount of space in secondary storage, and returns a
* pointer to it. Expands secondary storage if necessary.*/ | function |
ecma_string_t *
ecma_stringbuilder_finalize (ecma_stringbuilder_t *builder_p)
{
ecma_stringbuilder_header_t *header_p = builder_p->header_p;
JERRY_ASSERT (header_p != NULL);
const lit_utf8_size_t string_size = ECMA_STRINGBUILDER_STRING_SIZE (header_p);
lit_utf8_byte_t *string_begin_p = ECMA_STRINGBUILDER_STRING_PTR (header_p);
ecma_string_t *string_p = ecma_find_special_string (string_begin_p, string_size);
if (JERRY_UNLIKELY (string_p != NULL))
{
ecma_stringbuilder_destroy (builder_p);
return string_p;
}
#ifndef JERRY_NDEBUG
builder_p->header_p = NULL;
#endif
size_t container_size = sizeof (ecma_short_string_t);
const lit_string_hash_t hash = lit_utf8_string_calc_hash (string_begin_p, string_size);
const lit_utf8_size_t length = lit_utf8_string_length (string_begin_p, string_size);
if (JERRY_LIKELY (string_size <= UINT16_MAX))
{
if (JERRY_LIKELY (length == string_size) && string_size <= (UINT8_MAX + 1))
{
string_p = (ecma_string_t *) header_p;
string_p->refs_and_container = ECMA_STRING_CONTAINER_HEAP_ASCII_STRING | ECMA_STRING_REF_ONE;
string_p->u.hash = hash;
ECMA_ASCII_STRING_SET_SIZE (string_p, string_size);
return (ecma_string_t *) string_p;
}
}
else
{
container_size = sizeof (ecma_long_string_t);
}
const size_t utf8_string_size = string_size + container_size;
header_p = jmem_heap_realloc_block (header_p, header_p->current_size, utf8_string_size);
memmove (((lit_utf8_byte_t *) header_p + container_size), ECMA_STRINGBUILDER_STRING_PTR (header_p), string_size);
#if JERRY_MEM_STATS
jmem_stats_allocate_string_bytes (container_size - ECMA_ASCII_STRING_HEADER_SIZE);
#endif
if (JERRY_LIKELY (string_size <= UINT16_MAX))
{
ecma_short_string_t *short_string_p = (ecma_short_string_t *) header_p;
short_string_p->header.refs_and_container = ECMA_STRING_CONTAINER_HEAP_UTF8_STRING | ECMA_STRING_REF_ONE;
short_string_p->header.u.hash = hash;
short_string_p->size = (uint16_t) string_size;
short_string_p->length = (uint16_t) length;
return (ecma_string_t *) short_string_p;
}
ecma_long_string_t *long_string_p = (ecma_long_string_t *) header_p;
long_string_p->header.refs_and_container = ECMA_STRING_CONTAINER_LONG_OR_EXTERNAL_STRING | ECMA_STRING_REF_ONE;
long_string_p->header.u.hash = hash;
long_string_p->string_p = ECMA_LONG_STRING_BUFFER_START (long_string_p);
long_string_p->size = string_size;
long_string_p->length = length;
return (ecma_string_t *) long_string_p;
} | c | 12 | 0.686738 | 115 | 43.596491 | 57 | /**
* Finalize a string builder, returning the created string, and releasing the underlying buffer.
*
* Note:
* The builder should no longer be used.
*
* @return the created string
*/ | function |
public bool LosslessCompress(Stream stream)
{
ImageOptimizerHelper.CheckStream(stream);
bool isCompressed = false;
long startPosition = stream.Position;
using (var images = new MagickImageCollection(stream))
{
if (images.Count == 1)
isCompressed = DoLosslessCompress(images[0], stream, startPosition);
stream.Position = startPosition;
}
return isCompressed;
} | c# | 15 | 0.559687 | 88 | 38.384615 | 13 | /// <summary>
/// Performs lossless compression on the specified stream. If the new stream size is not smaller
/// the stream won't be overwritten.
/// </summary>
/// <param name="stream">The stream of the gif image to compress.</param>
/// <returns>True when the image could be compressed otherwise false.</returns> | function |
public class RunningTextRunnable implements Runnable
{
private static final String TAG = RunningTextRunnable.class.getSimpleName();
private static final int MAX_CHARS_PER_CYCLE = 4;
private IRunningTextContext context;
private String text;
private int beginIndex = 0;
private boolean isFirstRun = true;
RunningTextRunnable(IRunningTextContext context, String text)
{
this.context = context;
StringBuilder stringBuilder = new StringBuilder();
// Append leading spaces (text runs completely from right to left).
for(int i = 0; i < MAX_CHARS_PER_CYCLE; i++)
{
stringBuilder.append(' ');
}
// Append trimmed text.
stringBuilder.append(text.trim());
// Append trailing spaces.
int spacesCount = MAX_CHARS_PER_CYCLE - (text.length() % MAX_CHARS_PER_CYCLE);
for(int i = 0; i < spacesCount; i++)
{
stringBuilder.append(' ');
}
this.text = stringBuilder.toString();
Log.d(TAG, "Running text with trailed text: '"+this.text+"'");
}
@Override
public void run()
{
// Try to display the current visible part of the text string.
try
{
context.getAlphaNumericDisplay().display(text.substring(beginIndex));
}
catch (IOException e)
{
e.printStackTrace();
}
// Check if finished parameters are valid.
if(!isFirstRun && beginIndex == 0)
{
context.onRunningTextFinished();
return;
}
// Update the beginIndex for the next cycle.
beginIndex = (beginIndex + 1) % text.length();
isFirstRun = false;
// Post next cycle execution with a delay.
context.getRunningTextHandler().postDelayed(this, 750L);
}
} | java | 12 | 0.592593 | 86 | 27.242424 | 66 | /**
* Running text Runnable that prepares the given text to be
* more segment display friendly.
*
* Original inspiration:
* - Author: JS Koran (https://github.com/jdkoren)
* - Gist: https://gist.github.com/jdkoren/a3c37883f839c0b3adcee43821128329
*/ | class |
def gmass(x=None, y=None, z=None, dx=None, dy=None, dz=None, model=None, ppar=None, **kwargs):
ncell = x.shape[0]
rho = np.zeros([ncell, kwargs['nsample']], dtype=np.float64)
for isample in range(int(kwargs['nsample'])):
xoffset = (np.random.random_sample(ncell) - 0.5) * dx * 4.0
yoffset = (np.random.random_sample(ncell) - 0.5) * dy * 4.0
zoffset = (np.random.random_sample(ncell) - 0.5) * dz * 4.0
rho[:, isample] = model.getGasDensity(x + xoffset, y + yoffset, z + zoffset, ppar=ppar)
mass = rho.max(1) * dx * dy * dz * 8.0
jj = (mass > ppar['threshold'])
decision = np.zeros(ncell, dtype=bool)
if True in jj:
decision[jj] = True
return decision | python | 14 | 0.596394 | 95 | 50.571429 | 14 |
Example function to be used as decision function for resolving cells in tree building. It calculates the gas density
at a random sample of coordinates within a given cell than take the ratio of the max/min density. If it is larger
than a certain threshold value it will return True (i.e. the cell should be resolved) if the density variation is
less than the threshold it returns False (i.e. the cell should not be resolved)
Parameters
----------
x : ndarray
Cell centre coordinates of the cells in the first dimension
y : ndarray
Cell centre coordinates of the cells in the second dimension
z : ndarray
Cell centre coordinates of the cells in the third dimension
dx : ndarray
Half size of the cells in the first dimension
dy : ndarray
Half size of the cells in the second dimension
dz : ndarray
Half size of the cells in the third dimension
model : object
A radmc3dPy model (must contain a getGasDensity() function)
ppar : dictionary
All parameters of the problem (from the problem_params.inp file). It is not used here, but must be present
for compatibility reasons.
**kwargs: dictionary
Parameters used to decide whether the cell should be resolved. It should contain the following keywords;
'nsample', which sets the number of random points the gas desity is sampled at within the cell and
'threshold' that sets the threshold value for max(gasdens)/min(gasdens) above which the cell should
be resolved.
| function |
public static String toCSSBackgroundProperty(String dataUrl, Repetition repetition) {
if (dataUrl != null && dataUrl.trim().length() > 0) {
String repetitionToApply = Key.isValid(repetition) ? repetition.value() : Constants.EMPTY_STRING;
return applyTemplate(PATTERN_TEMPLATE, dataUrl, repetitionToApply);
}
return Constants.EMPTY_STRING;
} | java | 10 | 0.756374 | 100 | 49.571429 | 7 | /**
* Returns a URL CSS property for the data URL for the current content of the canvas element.
*
* @param dataUrl the data URL for the current content of the canvas element
* @param repetition repetition of image
* @return a URL CSS property for the current content of the canvas element
*/ | function |
def _lock(self):
lock_failure_response = 'false'
key_success_status_code = 200
endpoint = self._endpoint(self._kv_endpoints['kv'], self._lock_key)
params = {'acquire': self._session_id}
acquire_response = requests.put(endpoint, params=params,
data=self._lock_value, timeout=self._requests_timeout)
if acquire_response.content == lock_failure_response:
self._release_session()
raise self.LockAcquireException('Failed to acquire lock')
response = requests.get(endpoint, timeout=self._requests_timeout)
if response.status_code == key_success_status_code:
response_list = response.json()
for lock in response_list:
if lock['Session'] != self._session_id:
self._release_session()
raise self.LockAcquireException('Failed to acquire lock')
else:
self._release_session()
raise self.LockAcquireException('Could not get the lock key')
return self | python | 13 | 0.60509 | 77 | 49.571429 | 21 |
At this point we should have a session and heartbeating working so we can
acquire a key to act as the lock for the session. If we fail to acquire the key
then throw an exception.
| function |
def matchTransforms(self, obj, position=True, rotation=True, scale=True):
if position:
self._nativePointer.Kinematics.Global.Parameters('posx').Value = obj.nativePointer().Kinematics.Global.Parameters('posx').Value
self._nativePointer.Kinematics.Global.Parameters('posy').Value = obj.nativePointer().Kinematics.Global.Parameters('posy').Value
self._nativePointer.Kinematics.Global.Parameters('posz').Value = obj.nativePointer().Kinematics.Global.Parameters('posz').Value
if rotation:
self._nativePointer.Kinematics.Global.Parameters('rotx').Value = obj.nativePointer().Kinematics.Global.Parameters('rotx').Value
self._nativePointer.Kinematics.Global.Parameters('roty').Value = obj.nativePointer().Kinematics.Global.Parameters('roty').Value
self._nativePointer.Kinematics.Global.Parameters('rotz').Value = obj.nativePointer().Kinematics.Global.Parameters('rotz').Value
if scale:
self._nativePointer.Kinematics.Global.Parameters('sclx').Value = obj.nativePointer().Kinematics.Global.Parameters('sclx').Value
self._nativePointer.Kinematics.Global.Parameters('scly').Value = obj.nativePointer().Kinematics.Global.Parameters('scly').Value
self._nativePointer.Kinematics.Global.Parameters('sclz').Value = obj.nativePointer().Kinematics.Global.Parameters('sclz').Value
if application.autokey():
self.key()
return True | python | 14 | 0.777037 | 130 | 83.4375 | 16 |
Currently the auto-key support is a bit lite, but it should cover most of the cases.
| function |
def asarray(val, dtype=None):
if dtype:
dtype = utils.to_tf_type(dtype)
if isinstance(val, arrays.ndarray) and (
not dtype or utils.to_numpy_type(dtype) == val.dtype):
return val
return array(val, dtype, copy=False) | python | 10 | 0.676596 | 60 | 32.714286 | 7 | Return ndarray with contents of `val`.
Args:
val: array_like. Could be an ndarray, a Tensor or any object that can
be converted to a Tensor using `tf.convert_to_tensor`.
dtype: Optional, defaults to dtype of the `val`. The type of the
resulting ndarray. Could be a python type, a NumPy type or a TensorFlow
`DType`.
Returns:
An ndarray. If `val` is already an ndarray with type matching `dtype` it is
returned as is.
| function |
def _get_tlrd_pages(self, uri):
def count(data):
pages = 0
platforms = 0
translations = 0
for translation in data:
translations = translations + 1
for platform in data[translation]:
platforms = platforms + 1
pages = pages + len(data[translation][platform])
self._logger.debug(
"read total of %d tldr pages from %d translations and %d platforms",
pages,
translations,
platforms,
)
pages = {}
match = self.RE_CATCH_GITHUB_PAGE.search(uri)
if match and match.group("page"):
self._logger.debug(
"read tldr page: %s :from branch: %s",
match.group("page"),
match.group("branch"),
)
pages = {match.group("translation"): {match.group("platform"): (uri,)}}
count(pages)
return pages
match = self.RE_CATCH_GITHUB_PLATFORM.search(uri)
if match and match.group("platform"):
self._logger.debug(
"read tldr pages from platform: %s :from branch: %s",
match.group("platform"),
match.group("branch"),
)
pages = self._get_github_tldr_pages(
match.group("branch"),
(match.group("translation"),),
(match.group("platform"),),
)
count(pages)
return pages
match = self.RE_CATCH_GITHUB_TRANSLATION.search(uri)
if match and match.group("translation"):
pages = self._get_github_tldr_pages(
match.group("branch"),
(match.group("translation"),),
self.TLDR_PLATFORMS,
)
count(pages)
return pages
match = self.RE_CATCH_LOCAL_TLDR_PAGES.search(uri)
if match:
translation = match.groupdict().get("translations", "undefined")
platform = match.groupdict().get("platform", "undefined")
if os.path.isfile(uri) and os.access(uri, os.R_OK):
pages = {translation: {platform: (uri,)}}
count(pages)
elif os.path.isdir(uri) and os.access(uri, os.R_OK):
files = glob(os.path.join(uri, "*.md"))
if files:
pages = {translation: {platform: tuple(files)}}
else:
pages[translation] = {}
platforms = os.listdir(uri)
for platform in platforms:
if platform in self.TLDR_PLATFORMS:
files = glob(os.path.join(uri + platform, "*.md"))
pages[translation][platform] = tuple(files)
count(pages)
else:
Cause.push(
Cause.HTTP_FORBIDDEN,
"local tldr pages cannot be read: {}".format(uri),
)
return pages | python | 22 | 0.474992 | 84 | 40.333333 | 75 | Get all ``tldr pages``.
Read all tldr pages from the given URI. The pages are returned in a
dictionary that contains keys for translations and tldr platforms.
The tldr pages are in a list of full GitHub raw URLs under each
platform.
Args:
uri (str): URI where the tldr pages are read.
Returns:
dict: All tldr pages with GitHib raw URL.
| function |
class MessageProvider {
constructor() {
this.messages = [];
}
/**
* info - this method flags the current message to be presented as an
* informational message in the UI.
* For more information, see:
* https://developer.gtnexus.com/platform/scripts/built-in-functions/error-messages-to-ui
*
* @return {MessageBuilder}
*/
info() {
let self = this;
return new MessageBuilder('info', (msg) => {
this.messages.push(msg);
});
}
warning() {
let self = this;
return new MessageBuilder('warning', (msg) => {
this.messages.push(msg);
});
}
/**
* error - This method flags the current message to be presented as an error
* message in the UI.
* For more information, see:
* https://developer.gtnexus.com/platform/scripts/built-in-functions/error-messages-to-ui
*
* @return {MessageBuilder}
*/
error() {
return new MessageBuilder('error', (msg) => {
this.messages.push(msg);
});
}
getMessages() {
return this.messages.slice();
}
reset() {
this.messages = [];
}
} | javascript | 14 | 0.529177 | 101 | 23.54902 | 51 | /**
* The MessageProvider allows scripting to display informational or error
* messages on the user interface to end users.
*
* For more information, see:
* https://developer.gtnexus.com/platform/scripts/built-in-functions/error-messages-to-ui
*/ | class |
def __gen_load(self, load):
concurrency = load.concurrency if load.concurrency is not None else 1
load_elem = etree.Element("load")
if load.duration:
duration, unit = self.__time_to_tsung_time(int(round(load.duration)))
load_elem.set('duration', str(duration))
load_elem.set('unit', unit)
phases = []
if load.hold:
duration, unit = self.__time_to_tsung_time(int(round(load.hold)))
users = etree.Element("users", arrivalrate=str(concurrency), unit="second")
phase = etree.Element("arrivalphase",
phase=str("1"),
duration=str(duration),
unit=unit)
phase.append(users)
phases.append(phase)
else:
raise ValueError("You must specify test duration with `hold-for`")
for phase in phases:
load_elem.append(phase)
return load_elem | python | 14 | 0.532274 | 87 | 44.818182 | 22 |
Generate Tsung load profile.
Tsung load progression is scenario-based. Virtual users are erlang processes which are spawned according to
load profile. Each user executes assigned session (requests + think-time + logic) and then dies.
:param scenario:
:param load:
:return:
| function |
public bool TryRequestAdditionalTime(int minutes)
{
Log.Debug($"AlgorithmTimeLimitManager.TryRequestAdditionalTime({minutes}): Requesting additional time. Available: {AdditionalTimeBucket.AvailableTokens}");
if (AdditionalTimeBucket.TryConsume(minutes))
{
var newValue = Interlocked.Add(ref _additionalMinutes, minutes);
Log.Debug($"AlgorithmTimeLimitManager.TryRequestAdditionalTime({minutes}): Success: AdditionalMinutes: {newValue}");
return true;
}
return false;
} | c# | 13 | 0.648649 | 167 | 52.909091 | 11 | /// <summary>
/// Attempts to requests additional time to continue executing the current time step.
/// At time of writing, this is intended to be used to provide training scheduled events
/// additional time to allow complex training models time to execute while also preventing
/// abuse by enforcing certain control parameters set via the job packet.
///
/// Each time this method is invoked, this time limit manager will increase the allowable
/// execution time by the specified number of whole minutes
/// </summary> | function |
def load(path: Union[pathlib.Path, str] = None, text: str = None) -> Dict[str, Dict[str, Union[bytes, int, str]]]:
if not path and not text:
raise exceptions.FRUException('*path* or *text* must be specified')
data = {
'common': shared.get_default_common_section(),
'board': shared.get_default_board_section(),
'chassis': shared.get_default_chassis_section(),
'product': shared.get_default_product_section(),
'internal': shared.get_default_internal_section(),
}
if path:
toml_data = toml.load(path)
else:
toml_data = toml.loads(text)
for section in data:
if section in toml_data:
data[section].update(toml_data[section])
integers: Tuple[Tuple[str, str], ...] = (
('common', 'size'),
('common', 'format_version'),
('board', 'language_code'),
('chassis', 'type'),
('product', 'language_code'),
)
dates = (
('board', 'mfg_date_time'),
)
for section in ['internal', 'chassis', 'board', 'product', 'multirecord']:
include_section = f'include_{section}'
if not data['common'].get(include_section, True) and section in data:
del(data[section])
if include_section in data['common']:
del(data['common'][include_section])
for section, key in integers:
if not isinstance(data.get(section, {}).get(key, 0), int):
msg = f'Section [{section}] key "{key}" must be a number'
raise exceptions.TOMLException(msg)
for section, key in dates:
if section in data and key in data[section]:
if not data[section][key]:
data[section][key] = '1996-01-01 00:00'
if not isinstance(data[section][key], str):
msg = f'Section [{section}] key "{key}" must be a string'
raise exceptions.TOMLException(msg)
data[section][key] = convert_str_to_minutes(data[section][key])
if data.get('internal', {}).get('data'):
msg = f'Section [internal] key "data" must be a list of numbers or a string'
try:
data['internal']['data'] = bytes(data['internal']['data'])
except TypeError:
try:
data['internal']['data'] = data['internal']['data'].encode('utf8')
except AttributeError:
raise exceptions.TOMLException(msg)
elif data.get('internal', {}).get('file'):
internal_file = os.path.join(
os.path.dirname(path), data['internal']['file']
)
try:
with open(internal_file, 'rb') as f:
data['internal']['data'] = f.read()
except FileNotFoundError:
msg = f'Internal info area file {internal_file} not found'
raise exceptions.TOMLException(msg)
if 'file' in data.get('internal', {}):
del(data['internal']['file'])
return data | python | 17 | 0.564033 | 114 | 42.835821 | 67 | Load a TOML file and return its data as a dictionary.
If *path* is specified it must be a TOML-formatted file.
If *text* is specified it must be a TOML-formatted string.
| function |
func (d *DockerOps) StartSMBServer(volName string) (int, string, bool) {
var service swarm.ServiceSpec
var options dockerTypes.ServiceCreateOptions
service.Name = serviceNamePrefix + volName
service.TaskTemplate.ContainerSpec.Image = sambaImageName
containerArgs := []string{"-s",
FileShareName + ";/mount;yes;no;no;all;" +
SambaUsername + ";" + SambaUsername,
"-u",
SambaUsername + ";" + SambaPassword}
service.TaskTemplate.ContainerSpec.Args = containerArgs
var mountInfo []swarm.Mount
mountInfo = append(mountInfo, swarm.Mount{
Type: swarm.MountType("volume"),
Source: internalVolumePrefix + volName,
Target: "/mount"})
service.TaskTemplate.ContainerSpec.Mounts = mountInfo
var uintContainerNum uint64
uintContainerNum = 1
numContainers := swarm.ReplicatedService{Replicas: &uintContainerNum}
service.Mode = swarm.ServiceMode{Replicated: &numContainers}
var exposedPorts []swarm.PortConfig
exposedPorts = append(exposedPorts, swarm.PortConfig{
Protocol: swarm.PortConfigProtocolTCP,
TargetPort: defaultSambaPort,
})
service.EndpointSpec = &swarm.EndpointSpec{
Mode: swarm.ResolutionModeVIP,
Ports: exposedPorts,
}
resp, err := d.Dockerd.ServiceCreate(context.Background(),
service, options)
if err != nil {
log.Warningf("Failed to create file server for volume %s. Reason: %v",
volName, err)
return 0, "", false
}
ticker := time.NewTicker(checkTicker)
defer ticker.Stop()
timer := time.NewTimer(GetServiceStartTimeout())
defer timer.Stop()
for {
select {
case <-ticker.C:
log.Infof("Checking status of file server container...")
port, isRunning := d.isFileServiceRunning(resp.ID, volName)
if isRunning {
return int(port), serviceNamePrefix + volName, isRunning
}
case <-timer.C:
log.Warningf("Timeout reached while waiting for file server container for volume %s",
volName)
return 0, "", false
}
}
} | go | 14 | 0.735263 | 88 | 32.946429 | 56 | // StartSMBServer - Start SMB server
// Input - Name of the volume for which SMB has to be started
// Output
// int: The overlay network port number on which the
// newly created SMB server listens. This port
// is opened on every host VM in the swarm.
// string: Name of the SMB service started
// bool: Indicated success/failure of the function. If
// false, ignore other output values. | function |
def validateMetaDataService(smallKey, workspace, metaDataUrl, logs, geocatUrl, geocatUsername, geocatPassword):
isValid =True
jsonPath = os.path.join(workspace, smallKey + '.json')
jsonData = open(jsonPath)
jsonObj = json.load(jsonData)
jsonData.close()
uuid = jsonObj['config']['UUID']
metaDataUrl = metaDataUrl.replace("{0}", uuid)
base64string = base64.b64encode('%s:%s' % (geocatUsername, geocatPassword)).replace('\n', '')
request = urllib2.Request(metaDataUrl)
request.add_header("Authorization", "Basic %s" % base64string)
printLog(logs,"Checking metadata: " + metaDataUrl)
try:
response = urllib2.urlopen(request)
except urllib2.URLError as e:
if hasattr(e, 'reason'):
printLog(logs,'Cannot access Catalogue metadata: We failed to reach a server.')
printLog(logs,'Reason: %s' % e.reason)
elif hasattr(e, 'code'):
responses = BaseHTTPRequestHandler.responses
printLog(logs,'Cannot access Catalogue metadata: The server couldn\'t fulfill the request.')
printLog(logs,'Error code: %s - %s: %s' % (e.code, responses[e.code][0], responses[e.code][1]))
isValid=False
return isValid | python | 17 | 0.657512 | 111 | 50.625 | 24 | Validate meta data setvice in the Data Catalogue
Args:
smallKey: ID of shapefile.
workspace: Folder in which data is unzipped to.
metaDataUrl:Malformed metadata url
logs: log list holds all log items for current publication
geocatUrl: The URL to the Data Catalogue
geocatUsername: The username to login to the Data Catalogue
geocatPassword: The password to login to the Data Catalogue
returns: True if valid, False otherwise
| function |
Configuration toConfigurationNode(
ConvertedConfiguration awsConfiguration, Region region, Warnings warnings) {
Configuration cfgNode =
Utils.newAwsConfiguration(
nodeName(_subnetId), "aws", _tags, DeviceModel.AWS_SUBNET_PRIVATE);
cfgNode.getVendorFamily().getAws().setVpcId(_vpcId);
cfgNode.getVendorFamily().getAws().setSubnetId(_subnetId);
cfgNode.getVendorFamily().getAws().setRegion(region.getName());
String instancesIfaceName = instancesInterfaceName(_subnetId);
Ip instancesIfaceIp = computeInstancesIfaceIp();
ConcreteInterfaceAddress instancesIfaceAddress =
ConcreteInterfaceAddress.create(instancesIfaceIp, _cidrBlock.getPrefixLength());
Utils.newInterface(
instancesIfaceName, cfgNode, instancesIfaceAddress, "To instances " + _subnetId);
Configuration vpcConfigNode = awsConfiguration.getNode(Vpc.nodeName(_vpcId));
vpcConfigNode
.getVrfs()
.values()
.forEach(
vrf -> {
String interfaceSuffix = vrf.getName().equals(DEFAULT_VRF_NAME) ? "" : vrf.getName();
connect(
awsConfiguration,
cfgNode,
DEFAULT_VRF_NAME,
vpcConfigNode,
vrf.getName(),
interfaceSuffix);
addStaticRoute(
vrf,
toStaticRoute(
_cidrBlock,
interfaceNameToRemote(cfgNode, interfaceSuffix),
getInterfaceLinkLocalIp(
cfgNode, interfaceNameToRemote(vpcConfigNode, interfaceSuffix))));
});
@Nullable
String vpnGatewayId = region.findVpnGateway(_vpcId).map(VpnGateway::getId).orElse(null);
Optional<RouteTable> routeTable = region.findRouteTable(_vpcId, _subnetId);
Optional<InternetGateway> optInternetGateway = region.findInternetGateway(_vpcId);
if (optInternetGateway.isPresent()
&& routeTable.isPresent()
&& isPublicSubnet(optInternetGateway.get(), routeTable.get())) {
cfgNode.setDeviceModel(DeviceModel.AWS_SUBNET_PUBLIC);
}
List<String> vpcGatewayIds =
Streams.concat(
Stream.of(optInternetGateway.map(InternetGateway::getId).orElse(null)),
Stream.of(vpnGatewayId),
region.getVpcEndpoints().values().stream()
.filter(
vpce ->
vpce instanceof VpcEndpointGateway && vpce.getVpcId().equals(_vpcId))
.map(VpcEndpoint::getId))
.filter(Objects::nonNull)
.collect(ImmutableList.toImmutableList());
if (!routeTable.isPresent()) {
warnings.redFlag(
String.format("Route table not found for subnet %s in vpc %s", _subnetId, _vpcId));
} else {
routeTable
.get()
.getRoutes()
.forEach(
route ->
processRoute(
cfgNode,
region,
route,
vpcConfigNode,
vpcGatewayIds,
awsConfiguration,
warnings));
}
installNetworkAcls(cfgNode, region, warnings);
cfgNode.setLocationInfo(
cfgNode.getAllInterfaces().values().stream()
.flatMap(
iface ->
Stream.of(
immutableEntry(
interfaceLocation(iface), subnetInterfaceLocationInfo(iface)),
immutableEntry(
interfaceLinkLocation(iface), subnetInterfaceLinkLocationInfo(iface))))
.collect(ImmutableMap.toImmutableMap(Entry::getKey, Entry::getValue)));
return cfgNode;
} | java | 17 | 0.576833 | 99 | 43.068966 | 87 | /**
* Returns the {@link Configuration} node for this subnet.
*
* <p>We also do the work needed to connect to the VPC router here: Add an interface on the VPC
* router and create the necessary static routes.
*/ | function |
[DllImport(api_ms_win_service_management_l2_1_0, SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ChangeServiceConfig(
SafeServiceHandle hService,
ServiceType dwServiceType,
ServiceStartType dwStartType,
ServiceErrorControl dwErrorControl,
string lpBinaryPathName,
string lpLoadOrderGroup,
int lpdwTagId,
string lpDependencies,
string lpServiceStartName,
string lpPassword,
string lpDisplayName); | c# | 8 | 0.642623 | 97 | 42.642857 | 14 | /// <summary>
/// Changes the configuration parameters of a service.
/// To change the optional configuration parameters, use the <see cref="ChangeServiceConfig2(SafeServiceHandle, ServiceInfoLevel, void*)"/> function.
/// </summary>
/// <param name="hService">
/// A handle to the service.
/// This handle is returned by the <see cref="OpenService"/> or <see cref="CreateService(SafeServiceHandle,string,string,ACCESS_MASK,ServiceType,ServiceStartType,ServiceErrorControl,string,string,int, string,string,string)"/> function and
/// must have the <see cref="ServiceAccess.SERVICE_CHANGE_CONFIG"/> access right.
/// </param>
/// <param name="dwServiceType">
/// The type of service. Specify <see cref="SERVICE_NO_CHANGE"/> if you are not changing the existing service type;
/// otherwise, specify one of the following service types.
/// <list type="bullet">
/// <item>
/// <see cref="ServiceType.SERVICE_FILE_SYSTEM_DRIVER"/>
/// </item>
/// <item>
/// <see cref="ServiceType.SERVICE_KERNEL_DRIVER"/>
/// </item>
/// <item>
/// <see cref="ServiceType.SERVICE_WIN32_OWN_PROCESS"/>
/// </item>
/// <item>
/// <see cref="ServiceType.SERVICE_WIN32_SHARE_PROCESS"/>
/// </item>
/// </list>
/// </param>
/// If you specify either <see cref="ServiceType.SERVICE_WIN32_OWN_PROCESS"/> or <see cref="ServiceType.SERVICE_WIN32_SHARE_PROCESS"/>,
/// and the service is running in the context of the LocalSystem account, you can also specify the following type.
/// <see cref="ServiceType.SERVICE_INTERACTIVE_PROCESS"/>
/// <param name="dwStartType">
/// The type of service. Specify <see cref="SERVICE_NO_CHANGE"/> if you are not changing the existing service type;
/// otherwise, specify one of the following service types.
/// <list type="bullet">
/// <item>
/// <see cref="ServiceStartType.SERVICE_AUTO_START"/>
/// </item>
/// <item>
/// <see cref="ServiceStartType.SERVICE_BOOT_START"/>
/// </item>
/// <item>
/// <see cref="ServiceStartType.SERVICE_DEMAND_START"/>
/// </item>
/// <item>
/// <see cref="ServiceStartType.SERVICE_DISABLED"/>
/// </item>
/// <item>
/// <see cref="ServiceStartType.SERVICE_SYSTEM_START"/>
/// </item>
/// </list>
/// </param>
/// <param name="dwErrorControl">
/// The severity of the error, and action taken, if this service fails to start. Specify SERVICE_NO_CHANGE if you are not changing the existing error control;
/// otherwise, specify one of the following values.
/// <list type="bullet">
/// <item>
/// <see cref="ServiceErrorControl.SERVICE_ERROR_CRITICAL"/>
/// </item>
/// <item>
/// <see cref="ServiceErrorControl.SERVICE_ERROR_IGNORE"/>
/// </item>
/// <item>
/// <see cref="ServiceErrorControl.SERVICE_ERROR_NORMAL"/>
/// </item>
/// <item>
/// <see cref="ServiceErrorControl.SERVICE_ERROR_SEVERE"/>
/// </item>
/// </list>
/// </param>
/// <param name="lpBinaryPathName">
/// The fully qualified path to the service binary file. Specify NULL if you are not changing the existing path.
/// If the path contains a space, it must be quoted so that it is correctly interpreted.
/// For example, "d:\\my share\\myservice.exe" should be specified as "\"d:\\my share\\myservice.exe\"".
/// The path can also include arguments for an auto-start service.
/// For example, "d:\\myshare\\myservice.exe arg1 arg2". These arguments are passed to the service entry point (typically the main function).
/// If you specify a path on another computer, the share must be accessible by the computer account of the local computer because this is the security context used in the remote call.
/// However, this requirement allows any potential vulnerabilities in the remote computer to affect the local computer. Therefore, it is best to use a local file.
/// </param>
/// <param name="lpLoadOrderGroup">
/// The name of the load ordering group of which this service is a member. Specify NULL if you are not changing the existing group. Specify an empty string if the service does not belong to a group.
/// The startup program uses load ordering groups to load groups of services in a specified order with respect to the other groups. The list of load ordering groups is contained in the ServiceGroupOrder value of the following registry key:
/// HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control
/// </param>
/// <param name="lpdwTagId">
/// A pointer to a variable that receives a tag value that is unique in the group specified in the lpLoadOrderGroup parameter. Specify NULL if you are not changing the existing tag.
/// You can use a tag for ordering service startup within a load ordering group by specifying a tag order vector in the following registry value:
/// HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\GroupOrderList
/// Tags are only evaluated for driver services that have <see cref="ServiceStartType.SERVICE_BOOT_START"/> or <see cref="ServiceStartType.SERVICE_SYSTEM_START"/> start types.
/// </param>
/// <param name="lpDependencies">
/// A pointer to a double null-terminated array of null-separated names of services or load ordering groups that the system must start before this service. Specify NULL or an empty string if the service has no dependencies.
/// Dependency on a group means that this service can run if at least one member of the group is running after an attempt to start all members of the group.
/// You must prefix group names with SC_GROUP_IDENTIFIER so that they can be distinguished from a service name, because services and service groups share the same name space.
/// </param>
/// <param name="lpServiceStartName">
/// The name of the account under which the service should run.
/// If the service type is <see cref="ServiceType.SERVICE_WIN32_OWN_PROCESS"/>, use an account name in the form DomainName\UserName.
/// The service process will be logged on as this user.
/// If the account belongs to the built-in domain, you can specify .\UserName.
/// </param>
/// <param name="lpPassword">
/// The password to the account name specified by the lpServiceStartName parameter.
/// Specify an empty string if the account has no password or if the service runs in the LocalService, NetworkService, or LocalSystem account.
/// If the account name specified by the lpServiceStartName parameter is the name of a managed service account or virtual account name, the lpPassword parameter must be NULL.
/// Passwords are ignored for driver services.
/// </param>
/// <param name="lpDisplayName">
/// The display name to be used by applications to identify the service for its users. Specify NULL if you are not changing the existing display name; otherwise, this string has a maximum length of 256 characters. The name is case-preserved in the service control manager. Display name comparisons are always case-insensitive.
/// This parameter can specify a localized string using the following format:
/// @[path\]dllname,-strID
/// </param>
/// <returns>
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
/// The following error codes may be set by the service control manager.
/// Other error codes may be set by the registry functions that are called by the service control manager.
/// <list type="bullet">
/// <item>
/// <see cref="Win32ErrorCode.ERROR_ACCESS_DENIED"/>
/// </item>
/// <item>
/// <see cref="Win32ErrorCode.ERROR_CIRCULAR_DEPENDENCY"/>
/// </item>
/// <item>
/// <see cref="Win32ErrorCode.ERROR_DUPLICATE_SERVICE_NAME"/>
/// </item>
/// <item>
/// <see cref="Win32ErrorCode.ERROR_INVALID_HANDLE"/>
/// </item>
/// <item>
/// <see cref="Win32ErrorCode.ERROR_INVALID_PARAMETER"/>
/// </item>
/// <item>
/// <see cref="Win32ErrorCode.ERROR_INVALID_SERVICE_ACCOUNT"/>
/// </item>
/// <item>
/// <see cref="Win32ErrorCode.ERROR_SERVICE_MARKED_FOR_DELETE"/>
/// </item>
/// </list>
/// </returns> | function |
CSGObject*
ListOfCSGObjects::createCsgObject()
{
CSGObject* csgo = NULL;
try
{
SPATIAL_CREATE_NS(spatialns, getSBMLNamespaces());
csgo = new CSGObject(spatialns);
delete spatialns;
}
catch (...)
{
}
if(csgo != NULL)
{
appendAndOwn(csgo);
}
return csgo;
} | c++ | 10 | 0.62116 | 54 | 14.473684 | 19 | /**
* Creates a new CSGObject object, adds it to this ListOfCSGObjects
* CSGObject and returns the CSGObject object created.
*
* @return a new CSGObject object instance
*
* @see addCSGObject(const CSGObject* csgo)
*/ | function |
public sealed class UnicastIPAddressInformation : IPAddressInformation
{
private IP_ADAPTER_UNICAST_ADDRESS iaua;
internal UnicastIPAddressInformation(IP_ADAPTER_UNICAST_ADDRESS unicastAddress)
{
this.iaua = unicastAddress;
address = GetAddressFromSocketAddress(iaua.Address.lpSockaddr);
isDnsEligible = iaua.Flags.HasFlag(IP_ADAPTER_ADDRESS.DNS_ELIGIBLE);
isTransient = iaua.Flags.HasFlag(IP_ADAPTER_ADDRESS.TRANSIENT);
}
public long AddressPreferredLifetime
{
get
{
return (long)iaua.PreferredLifetime;
}
}
public long AddressValidLifetime
{
get
{
return (long)iaua.ValidLifetime;
}
}
public long DhcpLeaseLifetime
{
get
{
return (long)iaua.LeaseLifetime;
}
}
public DuplicateAddressDetectionState DuplicateAddressDetectionState
{
get
{
return iaua.DadState;
}
}
public PrefixOrigin PrefixOrigin
{
get
{
return iaua.PrefixOrigin;
}
}
public SuffixOrigin SuffixOrigin
{
get
{
return iaua.SuffixOrigin;
}
}
} | c# | 12 | 0.507576 | 87 | 26.415094 | 53 | /// <summary>
/// Provides information about a network interface's unicast address.
/// </summary> | class |
public static class Properties {
public final static Property Id = new Property(0, Long.class, "id", true, "_id");
public final static Property Token = new Property(1, String.class, "token", false, "TOKEN");
public final static Property Firstname = new Property(2, String.class, "firstname", false, "FIRSTNAME");
public final static Property Lastname = new Property(3, String.class, "lastname", false, "LASTNAME");
public final static Property PrimaryEmail = new Property(4, String.class, "primaryEmail", false, "PRIMARY_EMAIL");
public final static Property UserpicFilename = new Property(5, String.class, "userpicFilename", false, "USERPIC_FILENAME");
public final static Property LastLogin = new Property(6, String.class, "lastLogin", false, "LAST_LOGIN");
public final static Property JoinedSince = new Property(7, String.class, "joinedSince", false, "JOINED_SINCE");
public final static Property Uuid = new Property(8, String.class, "uuid", false, "UUID");
public final static Property Created = new Property(9, String.class, "created", false, "CREATED");
} | java | 8 | 0.69808 | 131 | 94.583333 | 12 | /**
* Properties of entity DbUser.<br/>
* Can be used for QueryBuilder and for referencing column names.
*/ | class |
private Command prepareChange(String args) {
String[] argComponents= args.trim().split(DELIMITER_BLANK_SPACE);
if(argComponents[CHANGE_LOCATION].equals("location") && argComponents[CHANGE_LOCATION_TO].equals("to")){
return new ChangeCommand(argComponents[CHANGE_LOCATION_TO_PATH]);
} else {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, ChangeCommand.MESSAGE_USAGE));
}
} | java | 11 | 0.688453 | 116 | 56.5 | 8 | /**
* Parses arguments in the context of the change data file location command.
*
* @param args
* full command args string
* @return the prepared command
*/ | function |
int webots_physics_collide(dGeomID g1, dGeomID g2) {
dContact contact[10];
dVector3 start, d;
int i, n, ray_color;
if (dAreGeomsSame(g1, ray_geom) || dAreGeomsSame(g2, ray_geom)) {
if ((dAreGeomsSame(g2, ray_geom) && (dSpaceQuery((dSpaceID)robot_geom, g1) == 1 || dGeomIsSpace(g1))) ||
(dAreGeomsSame(g1, ray_geom) && (dSpaceQuery((dSpaceID)robot_geom, g2) == 1 || dGeomIsSpace(g1)))) {
ray_color = 0;
dWebotsSend(2, &ray_color, sizeof(int));
return 1;
}
n = dCollide(g1, g2, 10, &contact[0].geom, sizeof(dContact));
if (n == 0) {
ray_color = 0;
dWebotsSend(2, &ray_color, sizeof(int));
return 1;
}
dVector3 dir;
dGeomRayGet(ray_geom, start, dir);
for (i = 0; i < 3; i++)
d[i] = start[i] - contact[0].geom.pos[i];
const float ray_distance = sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);
dWebotsConsolePrintf("Obstacle detected at a distance of %g after %g s\n", ray_distance, dWebotsGetTime() / 1000);
ray_color = ray_collision_occured = 2;
dWebotsSend(2, &ray_color, sizeof(int));
return 2;
} else if ((dAreGeomsSame(g1, wings_geom[0]) || dAreGeomsSame(g1, wings_geom[1])) ||
(dAreGeomsSame(g2, wings_geom[0]) || dAreGeomsSame(g2, wings_geom[1]))) {
return 1;
} else if ((dAreGeomsSame(g1, floor_geom) && dSpaceQuery((dSpaceID)robot_geom, g2) == 1) ||
(dSpaceQuery((dSpaceID)robot_geom, g1) == 1 && dAreGeomsSame(g2, floor_geom))) {
n = dCollide(g1, g2, 10, &contact[0].geom, sizeof(dContact));
if (n == 0)
return 1;
dBodyID body = dGeomGetBody(g1);
if (body == NULL)
body = dGeomGetBody(g2);
if (body == NULL)
return 0;
dWorldID world = dBodyGetWorld(body);
dJointGroupID contact_joint_group = dWebotsGetContactJointGroup();
for (i = 0; i < n; i++) {
contact[i].surface.mode = dContactMu2 | dContactBounce | dContactApprox1 | dContactSoftCFM;
contact[i].surface.mu = 0.4;
contact[i].surface.mu2 = 0.8;
contact[i].surface.bounce = 0;
contact[i].surface.bounce_vel = 0;
contact[i].surface.soft_cfm = 0.001;
pthread_mutex_lock(&mutex);
dJointAttach(dJointCreateContact(world, contact_joint_group, &contact[i]), robot_body, NULL);
pthread_mutex_unlock(&mutex);
}
return 1;
} else
return 0;
} | c | 18 | 0.606202 | 118 | 41.053571 | 56 | /*
* This function is called every time a collision is detected between two
* Geoms. It allows you to handle the collisions as you want.
* Here you can either simply detect collisions for informations, disable
* useless collisions or handle them.
* This function is called various times for each time step.
* For a given collision, if you return 1 this means that you have handled the
* collision yourself and so it will be ignored by Webots. If you return 0,
* this means that you want Webots to handle it for you.
* The g1 and g2 parameter may refer only to placeable ODE Geoms (no Space).
* To be able to identify who these Geoms are, you must compare them with the
* ones you have stored. If the Geom you have stored is really a Geom too,
* you can compare them simply using the == operator but if it is a Space, you
* should use the dSpaceQuery(geom,gX) function.
*/ | function |
def sample_teacher_forcing(self, inp):
batch_size, _ = inp.size()
hidden = self.init_hidden(batch_size)
pred = self.forward(inp, hidden)
samples = torch.argmax(pred, dim=-1).view(batch_size, -1)
log_prob = F.nll_loss(pred, samples.view(-1), reduction='none').view(batch_size, -1)
return samples, log_prob | python | 12 | 0.616477 | 92 | 49.428571 | 7 |
Generating samples from the real data via teacher forcing
:param inp: batch_size * seq_len
:param target: batch_size * seq_len
:return
samples: batch_size * seq_len
log_prob: batch_size * seq_len (log probabilities)
| function |
def train_model(train_data, dev_data, model, gen, args):
if args.cuda:
model = model.cuda()
gen = gen.cuda()
args.lr = args.init_lr
optimizer = utils.get_optimizer([model, gen], args)
num_epoch_sans_improvement = 0
epoch_stats = metrics.init_metrics_dictionary(modes=['train', 'dev'])
step = 0
if args.class_balance:
sampler = torch.utils.data.sampler.WeightedRandomSampler(
weights=train_data.weights,
num_samples=len(train_data),
replacement=True)
train_loader = torch.utils.data.DataLoader(
train_data,
num_workers= args.num_workers,
sampler=sampler,
batch_size=args.batch_size)
else:
train_loader = torch.utils.data.DataLoader(
train_data,
batch_size=args.batch_size,
shuffle=True,
num_workers=args.num_workers,
drop_last=True)
dev_loader = torch.utils.data.DataLoader(
dev_data,
batch_size=args.batch_size,
shuffle=False,
num_workers=args.num_workers,
drop_last=False)
for epoch in range(1, args.epochs + 1):
print("-------------\nEpoch {}:\n".format(epoch))
for mode, dataset, loader in [('Train', train_data, train_loader), ('Dev', dev_data, dev_loader)]:
train_model = mode == 'Train'
print('{}'.format(mode))
key_prefix = mode.lower()
epoch_details, step, _, _, _, _, _, _ = run_epoch(
data_loader=loader,
train_model=train_model,
model=model,
gen=gen,
optimizer=optimizer,
step=step,
args=args)
epoch_stats, log_statement = metrics.collate_epoch_stat(epoch_stats, epoch_details, key_prefix, args)
print(log_statement)
if not train_model:
print('---- Best Dev Loss is {:.4f}'.format(
min(epoch_stats['dev_loss'])))
if min(epoch_stats['dev_loss']) == epoch_stats['dev_loss'][-1]:
num_epoch_sans_improvement = 0
if not os.path.isdir(args.save_dir):
os.makedirs(args.save_dir)
epoch_stats['best_epoch'] = epoch - 1
torch.save(model, args.model_path)
torch.save(gen, utils.get_gen_path(args.model_path))
else:
num_epoch_sans_improvement += 1
if num_epoch_sans_improvement >= args.patience:
print("Reducing learning rate")
num_epoch_sans_improvement = 0
model.cpu()
gen.cpu()
model = torch.load(args.model_path)
gen = torch.load(utils.get_gen_path(args.model_path))
if args.cuda:
model = model.cuda()
gen = gen.cuda()
args.lr *= .5
optimizer = utils.get_optimizer([model, gen], args)
if os.path.exists(args.model_path):
model.cpu()
model = torch.load(args.model_path)
gen.cpu()
gen = torch.load(utils.get_gen_path(args.model_path))
return epoch_stats, model, gen | python | 18 | 0.535625 | 113 | 40.038462 | 78 |
Train model and tune on dev set. If model doesn't improve dev performance within args.patience
epochs, then halve the learning rate, restore the model to best and continue training.
At the end of training, the function will restore the model to best dev version.
returns epoch_stats: a dictionary of epoch level metrics for train and test
returns model : best model from this call to train
| function |
AzFramework::PhysicsComponentNotifications::Collision StarterGameUtility::CreatePseudoCollisionEvent(const AZ::EntityId& entity, const AZ::Vector3& position, const AZ::Vector3& normal, const AZ::Vector3& direction)
{
AzFramework::PhysicsComponentNotifications::Collision coll;
coll.m_entity = entity;
coll.m_position = position;
coll.m_normal = normal;
coll.m_surfaces[1] = GetSurfaceFromRayCast(position, direction);
return coll;
} | c++ | 7 | 0.715164 | 214 | 53.333333 | 9 | // This function was created because I couldn't populate the 'Collision' struct in Lua. | function |
def count_frequencies(file) -> dict:
dictionary = {}
for line in file:
for char in line:
if char not in dictionary:
dictionary[char] = 1
else:
dictionary[char] = dictionary[char] + 1
return dictionary | python | 14 | 0.536232 | 55 | 29.777778 | 9 |
This function opens a text file as an argument and then returns the
frequencies each character occurs in the text file. The characters
are then sorted out by order starting from the lowest frequency to
the highest. Values sorted by ascending order.
| function |
public class AMF3StringProtocol extends AbstractNettyProtocol
{
/**
* The maximum size of the incoming message in bytes. The
* {@link DelimiterBasedFrameDecoder} will use this value in order to throw
* a {@link TooLongFrameException}.
*/
int maxFrameSize;
/**
* The flash client would encode the AMF3 bytes into a base 64 encoded
* string, this decoder is used to decode it back.
*/
private Base64Decoder base64Decoder;
/**
* Once the game handler is done with its operations, it writes back the
* java object to the client. When writing back to flash client, it needs to
* use this encoder to encode it to AMF3 format.
*/
private JavaObjectToAMF3Encoder javaObjectToAMF3Encoder;
/**
* The flash client expects a AMF3 bytes to be passed in as base 64 encoded
* string. This encoder will encode the bytes accordingly.
*/
private Base64Encoder base64Encoder;
/**
* Flash client expects a nul byte 0x00 to be added as the end byte of any
* communication with it. This encoder will add this nul byte to the end of
* the message. Could be considered as a message "footer".
*/
private NulEncoder nulEncoder;
public AMF3StringProtocol()
{
super("AMF3_STRING");
}
@Override
public void applyProtocol(PlayerSession playerSession)
{
ChannelPipeline pipeline = NettyUtils
.getPipeLineOfConnection(playerSession);
// Upstream handlers or encoders (i.e towards server) are added to
// pipeline now.
pipeline.addLast("framer", new DelimiterBasedFrameDecoder(maxFrameSize,
Delimiters.nulDelimiter()));
pipeline.addLast("base64Decoder", base64Decoder);
pipeline.addLast("amf3ToJavaObjectDecoder", createAMF3ToJavaObjectDecoder());
// Downstream handlers - Filter for data which flows from server to
// client. Note that the last handler added is actually the first
// handler for outgoing data.
pipeline.addLast("nulEncoder", nulEncoder);
pipeline.addLast("base64Encoder", base64Encoder);
pipeline.addLast("javaObjectToAMF3Encoder", javaObjectToAMF3Encoder);
}
protected AMF3ToJavaObjectDecoder createAMF3ToJavaObjectDecoder()
{
return new AMF3ToJavaObjectDecoder();
}
public int getMaxFrameSize()
{
return maxFrameSize;
}
public void setMaxFrameSize(int frameSize)
{
this.maxFrameSize = frameSize;
}
public Base64Decoder getBase64Decoder()
{
return base64Decoder;
}
public void setBase64Decoder(Base64Decoder base64Decoder)
{
this.base64Decoder = base64Decoder;
}
public JavaObjectToAMF3Encoder getJavaObjectToAMF3Encoder()
{
return javaObjectToAMF3Encoder;
}
public void setJavaObjectToAMF3Encoder(
JavaObjectToAMF3Encoder javaObjectToAMF3Encoder)
{
this.javaObjectToAMF3Encoder = javaObjectToAMF3Encoder;
}
public Base64Encoder getBase64Encoder()
{
return base64Encoder;
}
public void setBase64Encoder(Base64Encoder base64Encoder)
{
this.base64Encoder = base64Encoder;
}
public NulEncoder getNulEncoder()
{
return nulEncoder;
}
public void setNulEncoder(NulEncoder nulEncoder)
{
this.nulEncoder = nulEncoder;
}
} | java | 12 | 0.761189 | 79 | 25.859649 | 114 | /**
* This protocol defines AMF3 that is base 64 and String encoded sent over the
* wire. Used by XMLSocket flash clients to send AMF3 data.
*
* @author Abraham Menacherry
*
*/ | class |
public String invoke(List<String> formInputNames, List<String> formInputValues) throws IOException {
StringBuilder query = new StringBuilder("");
for(int i=0; i<formInputNames.size(); i++) {
query.append(formInputNames.get(i));
String value = formInputValues.get(i);
if(!StringUtils.isEmpty(value)) {
query.append("=").append(URLEncoder.encode(value, "UTF-8"));
}
if(i < formInputNames.size()-1)
query.append("&");
}
if(debug) {
log.println("Invoking " + url + "?" + query.toString());
}
HttpURLConnection uc = null;
if(method == HttpMethod.METHOD_GET) {
uc = (HttpURLConnection)new URL(url + "?" + query.toString()).openConnection();
} else {
uc = (HttpURLConnection)new URL(url).openConnection();
uc.setRequestMethod("POST");
uc.setDoOutput(true);
uc.setDoInput(true);
uc.setAllowUserInteraction(false);
uc.setUseCaches (false);
uc.setInstanceFollowRedirects(true);
DataOutputStream dos = new DataOutputStream(uc.getOutputStream());
dos.writeBytes(query.toString());
dos.close();
}
StringBuilder page = new StringBuilder("");
BufferedReader reader = new BufferedReader(new InputStreamReader(uc.getInputStream()));
String nextline;
while ((nextline = reader.readLine()) != null) {
page.append(nextline).append("\n");
}
reader.close();
return page.toString();
} | java | 14 | 0.644197 | 100 | 36.894737 | 38 | /**
* It invokes the web page with the form attributes and values that are passed to the function,
* and then returns the resulting page that is returned by the web server
* @param formInputNames - The names of the form attributes to send to the server
* @param formInputValues - Values of the corresponding form attributes
* @return - The resulting page returned by the web server.
* @throws IOException
*/ | function |
def generate_answers(self, levers):
question_set = self.test_set['data']
k_retrieve = levers['k_retrieve']
k_read = levers['k_read']
answer_set = []
elapsed_times = []
for qa in question_set:
question = qa['question']
ground_truth = qa['answer']
begin_time = datetime.datetime.now()
prediction = self.finder.get_answers(question=question, top_k_retriever=k_retrieve, top_k_reader=k_read)
logging.info(f"Question: {question}\nPredicted Answer: {prediction}\n")
end_time = datetime.datetime.now()
total_elapsed = end_time - begin_time
logging.info(f"Total elapsed time: {total_elapsed}.")
elapsed_times.append(total_elapsed)
predicted_answer = prediction['answers'][0]['answer']
exact_match, f1, combined = self.evaluate_answers(predicted_answer, ground_truth)
answer_set.append({
"question": prediction['question'],
"predicted_answer": predicted_answer,
"context": prediction['answers'][0]['context'],
"ground_truth": ground_truth,
"exact_match_score": exact_match,
"f1_score": f1,
"combined_score": combined,
"query_time": total_elapsed
})
time_ints = []
for time_string in elapsed_times:
time_ints.append(time_string.total_seconds())
total_questions = len(elapsed_times)
average_return = self.__average_list(time_ints)
logging.info(f"You asked a total of {total_questions} questions with an average response time of {average_return}.")
return(answer_set) | python | 14 | 0.576417 | 124 | 48.942857 | 35 |
Given a set of questions and answers, this method runs through each, returning
a predicted answer from Haystack Finder's get_answers method
Each prediction is then scored using evaluate_answers, and the results
are stored and then returned in the answer_set list of dictionaries
| function |
private void processIter(DetailAST root, AstState astState) {
DetailAST curNode = root;
while (curNode != null) {
notifyVisit(curNode, astState);
DetailAST toVisit = curNode.getFirstChild();
while (curNode != null && toVisit == null) {
notifyLeave(curNode, astState);
toVisit = curNode.getNextSibling();
if (toVisit == null) {
curNode = curNode.getParent();
}
}
curNode = toVisit;
}
} | java | 13 | 0.503597 | 61 | 36.133333 | 15 | /**
* Processes a node calling interested checks at each node.
* Uses iterative algorithm.
* @param root the root of tree for process
* @param astState state of AST.
*/ | function |
public class MainScene {
private JPanel JPanel;
//Init main screen label
JLabel Action_with_requirements = new JLabel("Action_with_requirement {E} / {$}") ;
JLabel Action_Set_Rqrm;
JLabel Action_no_requirement;
JLabel Action_Set_Free;
JLabel Main_Scene_wallpaper = new JLabel("");
final JToggleButton tglbtnExplain = new JToggleButton("INFO");
/**
*
* @param jPanel MainScene Panel
*/
public MainScene(JPanel jPanel) {
super();
JPanel = jPanel;
initMainScene(); // init of all component
init(); // add all component into panel
}
/**
* init add all component into MainScene panel
*/
private void init() {
//Add all label in Main_Scene panel
JPanel.add(Main_Scene_wallpaper);
JPanel.add(tglbtnExplain);
JPanel.add(Action_with_requirements);
JPanel.add(Action_Set_Rqrm);
JPanel.add(Action_no_requirement);
JPanel.add(Action_Set_Free);
}
/**
* initMainScene including set fond, background, bounds, layout, Opaque, button, allignment
* Init component in MainScene panel design
*/
public void initMainScene() { //Init component in MainScene
tglbtnExplain.setFont(new Font("Tw Cen MT Condensed Extra Bold", Font.PLAIN, 15));
tglbtnExplain.setBounds(175, 230, 75, 25); // End of button -INFO (MainScene)
//INFO (MainScene)
tglbtnExplain.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
INFO_MainScene();}});
Main_Scene_wallpaper.setIcon(new ImageIcon(GUI_body.class.getResource("/game_Use/img/Wiki-background_7.jpg")));
Main_Scene_wallpaper.setFont(new Font("Tw Cen MT Condensed Extra Bold", Font.PLAIN, 15));
Main_Scene_wallpaper.setBounds(252, 11, 462, 279);
Main_Scene_wallpaper.setOpaque(true);
Action_with_requirements.setForeground(new Color(160, 82, 45));
Action_with_requirements.setBackground(new Color(222, 184, 135));
Action_with_requirements.setFont(new Font("Tw Cen MT Condensed Extra Bold", Font.PLAIN, 16));
Action_with_requirements.setBounds(10, 11, 240, 20);
Action_with_requirements.setOpaque(true);
Action_Set_Rqrm = new JLabel("<html>"
+ "[0]Tend to crops<br>"
+ "[1]Play with Animal<br>"
+ "[2]Harvest Crop<br>"
+ "[3]Tend to Farm_Land <br>");
Action_Set_Rqrm.setForeground(new Color(184, 134, 11));
Action_Set_Rqrm.setBackground(new Color(255, 228, 181));
Action_Set_Rqrm.setFont(new Font("Tw Cen MT Condensed Extra Bold", Font.PLAIN, 15));
Action_Set_Rqrm.setBounds(10, 31, 240, 90);
Action_Set_Rqrm.setOpaque(true);
Action_no_requirement = new JLabel("Action_no_requirements");
Action_no_requirement.setForeground(new Color(160, 82, 45));
Action_no_requirement.setBackground(new Color(222, 184, 135));
Action_no_requirement.setFont(new Font("Tw Cen MT Condensed Extra Bold", Font.PLAIN, 16));
Action_no_requirement.setBounds(10, 120, 240, 20);
Action_no_requirement.setOpaque(true);
Action_Set_Free = new JLabel("<html>"
+ "[4]Go to Farm / Barn / Chicken hoop<br>"
+ "[5]Shopping in Supermarket / Pharmacy<br>"
+ "[6]Trading in Poultry Farm<br>"
+ "[7]Feeding Animal");
Action_Set_Free.setForeground(new Color(184, 134, 11));
Action_Set_Free.setBackground(new Color(255, 228, 181));
Action_Set_Free.setFont(new Font("Tw Cen MT Condensed Extra Bold", Font.PLAIN, 15));
Action_Set_Free.setBounds(10, 140, 240, 90);
Action_Set_Free.setOpaque(true);
}
/**
* INFO_MainScene Substitute s set of information into the wallpaper label when toggle button is pressed
*/
public void INFO_MainScene() { //Display initial message in main scene
if (tglbtnExplain.isSelected()) {
Main_Scene_wallpaper.setIcon(null);
Main_Scene_wallpaper.setBackground(new Color(222, 184, 135));
Main_Scene_wallpaper.setText("<html>[0] Chop tree stump. - Can sell the lumber to blacksmith. Consume 1 Energy. <br>"
+ "[1] Play footbal with the Animals in Barn. - Happiness of Animal +1.<br>"
+ "[2] Harvest selected Crop & sell to Trading market.- GOLD++ <br>"
+ "[3] Keep Farm Land tidy and well maintained. - Crop slot +1 <br>"
+ "[4] Walk towards selected place. - Able to view Plant / Animal status.<br>"
+ "[5] Go to the shop. - Purchase / Trade items.<br>"
+ "[6] Trade Animals with another farm (Buy & Sell)- GOLD +-<br>"
+ "[7] Prepare Corn_Feed for Animals. - Animals's healthiness +1"
+ "<br><br> *** Bunch of hidden events and random scenario!");
}
else {
Main_Scene_wallpaper.setBackground(new Color(240, 240, 240)); // Set background to blank/white
Main_Scene_wallpaper.setIcon(new ImageIcon(GUI_body.class.getResource("/game_Use/img/Wiki-background_7.jpg"))); //Show image
Main_Scene_wallpaper.setText(""); // Update String of lblExplanation back to null
}
}
} | java | 19 | 0.69197 | 127 | 39.880342 | 117 | /**
* Main Scene Class is implemented as a View class (Project is trying to approach to Model-view-controller design pattern)
* This class implemented to display content to the user
* Contain all label and a toggle button in MainScene for displaying certain Info
* @author Edward Wong - University of Canterbury SENG_201
* 16/05/2020
*/ | class |
private void DisplayAutomaticInspectorGUI()
{
EditorGUILayout.Separator();
GUIStyle style = new GUIStyle();
style.alignment = TextAnchor.MiddleCenter;
style.fontStyle = FontStyle.Bold;
EditorGUILayout.Foldout(true, "Automatic " + target.GetType().ToString() + " Properties", style);
base.OnInspectorGUI();
} | c# | 14 | 0.658402 | 105 | 39.444444 | 9 | /// <summary>
/// This displays the automatic inspector gui. Call this if you have public members
/// you wish to edit automatically without manually setting up your inspector gui.
/// </summary> | function |
static void ConnCompAndRectangularize(Image pix, DebugPixa *pixa_debug, Boxa **boxa,
Pixa **pixa) {
*boxa = nullptr;
*pixa = nullptr;
if (textord_tabfind_show_images && pixa_debug != nullptr) {
pixa_debug->AddPix(pix, "Conncompimage");
}
*boxa = pixConnComp(pix, pixa, 8);
int npixes = 0;
if (*boxa != nullptr && *pixa != nullptr) {
npixes = pixaGetCount(*pixa);
}
for (int i = 0; i < npixes; ++i) {
int x_start, x_end, y_start, y_end;
Image img_pix = pixaGetPix(*pixa, i, L_CLONE);
if (textord_tabfind_show_images && pixa_debug != nullptr) {
pixa_debug->AddPix(img_pix, "A component");
}
if (pixNearlyRectangular(img_pix, kMinRectangularFraction, kMaxRectangularFraction,
kMaxRectangularGradient, &x_start, &y_start, &x_end, &y_end)) {
Image simple_pix = pixCreate(x_end - x_start, y_end - y_start, 1);
pixSetAll(simple_pix);
img_pix.destroy();
pixaReplacePix(*pixa, i, simple_pix, nullptr);
img_pix = pixaGetPix(*pixa, i, L_CLONE);
l_int32 x, y, width, height;
boxaGetBoxGeometry(*boxa, i, &x, &y, &width, &height);
Box *simple_box = boxCreate(x + x_start, y + y_start, x_end - x_start, y_end - y_start);
boxaReplaceBox(*boxa, i, simple_box);
}
img_pix.destroy();
}
} | c++ | 12 | 0.591716 | 94 | 40 | 33 | // Generates a Boxa, Pixa pair from the input binary (image mask) pix,
// analogous to pixConnComp, except that connected components which are nearly
// rectangular are replaced with solid rectangles.
// The returned boxa, pixa may be nullptr, meaning no images found.
// If not nullptr, they must be destroyed by the caller.
// Resolution of pix should match the source image (Tesseract::pix_binary_)
// so the output coordinate systems match. | function |
int AppReadTimeSeriesFile(
REAL8 ***recs,
size_t *nrSteps,
size_t *nrCols,
BOOL *geoeas,
const char *inputFile,
const char *mv,
CSF_VS vs,
CSF_CR cr,
int sepChar)
{
size_t i,c,lineDelta;
size_t nrRecordsRead,nrMVvalueColumn,nrMVcoordColumn;
if (appHeader == APP_NOHEADER)
handleAnError = HandleAnErrorTss;
if ( ReadAllColumnFile(recs, nrSteps, nrCols,
&nrRecordsRead,&nrMVvalueColumn,&nrMVcoordColumn, FALSE,
geoeas, inputFile, mv, sepChar,NULL) )
return 1;
handleAnError = HandleAnErrorDefault;
lineDelta = (*geoeas) ? ((*nrCols)+2) : 0;
for (i = 0; i < (*nrSteps); i++)
{
REAL8 *r = allRecList[i];
for(c=0; c < (*nrCols); c++)
{
switch(c) {
case 0:
if (IS_MV_REAL8(r+0))
{
if (appHeader == APP_NOHEADER)
r[0] = i+1;
else {
ErrorNested("timestep column (column 1) on line %u contains a MV",
i+lineDelta+1);
goto error;
}
}
if (r[0] != (i+1))
{
ErrorNested("timestep column (column 1) on line %u is not %u but %g",
i+lineDelta+1, i+1, r[c]);
goto error;
}
break;
default:
if (!IS_MV_REAL8(r+c))
{
if (AppCheckValNum(r[c], vs, cr))
{
ErrorNested("column %u on line %u", c+1, i+lineDelta+1);
goto error;
}
if (vs == VS_DIRECTION && r[c] != -1)
r[c] = AppInputDirection(r[c]);
}
break;
}
}
}
return 0;
error:
FreeAllRecs();
return 1;
} | c | 20 | 0.491071 | 73 | 24.861538 | 65 | /* Read a timeseries file.
* Errors are printed to ErrorNested, the name of the input file is not
* printed on Error.
* Returns 1 in case of error, 0 otherwise.
*/ | function |
private void searchForLanguageConstants(
GoogleAdsClient googleAdsClient, long customerId, String languageName) {
try (GoogleAdsServiceClient googleAdsServiceClient =
googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
String searchQuery =
"SELECT language_constant.id, "
+ "language_constant.code, "
+ "language_constant.name, "
+ "language_constant.targetable "
+ "FROM language_constant "
+ "WHERE language_constant.name LIKE '%"
+ languageName
+ "%'";
SearchGoogleAdsStreamRequest request =
SearchGoogleAdsStreamRequest.newBuilder()
.setCustomerId(Long.toString(customerId))
.setQuery(searchQuery)
.build();
ServerStream<SearchGoogleAdsStreamResponse> stream =
googleAdsServiceClient.searchStreamCallable().call(request);
for (SearchGoogleAdsStreamResponse response : stream) {
for (GoogleAdsRow googleAdsRow : response.getResultsList()) {
LanguageConstant languageConstant = googleAdsRow.getLanguageConstant();
System.out.printf(
"Language with ID %d, code '%s', name '%s', and targetable '%s' was found.%n",
languageConstant.getId(),
languageConstant.getCode(),
languageConstant.getName(),
languageConstant.getTargetable());
}
}
}
} | java | 15 | 0.620875 | 92 | 44.030303 | 33 | /**
* Searches for language constants where the name includes the specified language name.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param languageName the string to use for searching for language constants.
*/ | function |
def login(host, protocol="https", port=443, **kwargs):
base_url = "{protocol}://{host}:{port}"\
.format(protocol=protocol,
host=host,
port=int(port))
conn = requests.Session()
if "username" and "password" in kwargs:
conn.auth = (kwargs["username"], kwargs["password"])
conn.headers = {
"Content-Type": "application/json",
"Accept": "application/json",
}
if "request_headers" in kwargs:
conn.headers.update(kwargs["request_headers"])
if "cert" and "key" in kwargs:
key_file = tempfile.NamedTemporaryFile()
cert_file = tempfile.NamedTemporaryFile()
key_file.write(kwargs["key"])
key_file.seek(0)
cert_file.write(kwargs["cert"])
cert_file.seek(0)
conn.cert = (cert_file.name, key_file.name)
else:
key_file = None
cert_file = None
if "timeout" in kwargs:
timeout = kwargs["timeout"]
else:
timeout = 30
conn.verify = False
client = Client(host=host, base_url=base_url, \
conn=conn, key_file=key_file, \
cert_file=cert_file, timeout=timeout)
atexit.register(logout, client)
return client | python | 10 | 0.561459 | 60 | 35.057143 | 35 | Login to the rest http plugin
Args:
host (str): rest http host
protocol (Optional[str]): rest http protocol
port (Optional[int]): rest http port
Kwargs:
token (str): rest http token
username (str): rest http username
password (str): rest http password
cert (str): rest http certificate
key (str): rest http keyfile
timeout (int): rest http timeout
Returns:
Client: client connection object
Raises:
n/a: This function didn't raise.
Usage:
>>> login(host="rest_http.lan",
protocol="http",
port="8080")
| function |
def validate_file(filename):
with open(filename, 'r') as infp:
try:
data = read_yaml(infp)
except Exception as e:
click.secho('%s: could not parse YAML: %s' % (filename, e), fg='red', bold=True)
return 1
validator = get_validator()
errors = sorted(
validator.iter_errors(data),
key=lambda error: (relevance(error), repr(error.path)),
)
if not errors:
success('%s: No errors' % filename)
return 0
click.secho('%s: %d errors' % (filename, len(errors)), fg='yellow', bold=True)
for error in errors:
simplified_schema_path = [
el
for el
in list(error.relative_schema_path)[:-1]
if el not in ('properties', 'items')
]
obj_path = [str(el) for el in error.path]
click.echo(' {validator} validation on {schema_path}: {message} ({path})'.format(
validator=click.style(error.validator.title(), bold=True),
schema_path=click.style('.'.join(simplified_schema_path), bold=True),
message=click.style(error.message, fg='red'),
path=click.style('.'.join(obj_path), bold=True),
))
click.echo()
return len(errors) | python | 16 | 0.560703 | 92 | 38.15625 | 32 |
Validate `filename`, print its errors, and return the number of errors.
:param filename: YAML filename
:type filename: str
:return: Number of errors
:rtype: int
| function |
private void initTile(int tileNum) throws IOException {
if(tilePartPositions == null) in.seek(lastPos);
String strInfo = "";
int ncbQuit = -1;
boolean isTilePartRead = false;
boolean isEOFEncountered = false;
try {
int tpNum = 0;
while(remainingTileParts!=0 &&
(totTileParts[tileNum] == 0 ||
tilePartsRead[tileNum] < totTileParts[tileNum])) {
isTilePartRead = true;
if(tilePartPositions != null) {
in.seek((int)tilePartPositions[tileNum][tpNum++]);
}
tilePartStart = in.getPos();
try {
t = readTilePartHeader();
if(isEOCFound) {
break;
}
tp = tilePartsRead[t];
if(isPsotEqualsZero) {
tilePartLen[t][tp] = in.length()-2-tilePartStart;
}
} catch(EOFException e) {
firstPackOff[t][tp] = in.length();
throw e;
}
pos = in.getPos();
if(isTruncMode && ncbQuit == -1) {
if((pos-cdstreamStart)>tnbytes) {
firstPackOff[t][tp] = in.length();
rateReached = true;
break;
}
}
firstPackOff[t][tp] = pos;
tilePartHeadLen[t][tp] = (pos-tilePartStart);
if(printInfo)
strInfo += "Tile-part "+tp+" of tile "+t+" : "+tilePartStart
+", "+tilePartLen[t][tp]+", "+tilePartHeadLen[t][tp]+"\n";
totTileLen[t] += tilePartLen[t][tp];
totTileHeadLen[t] += tilePartHeadLen[t][tp];
totAllTileLen += tilePartLen[t][tp];
if(isTruncMode) {
if(anbytes+tilePartLen[t][tp]>tnbytes) {
anbytes += tilePartHeadLen[t][tp];
headLen += tilePartHeadLen[t][tp];
rateReached = true;
nBytes[t] += (tnbytes-anbytes);
break;
} else {
anbytes += tilePartHeadLen[t][tp];
headLen += tilePartHeadLen[t][tp];
nBytes[t] += (tilePartLen[t][tp]-
tilePartHeadLen[t][tp]);
}
} else {
if(anbytes+tilePartHeadLen[t][tp]>tnbytes) {
break;
} else {
anbytes += tilePartHeadLen[t][tp];
headLen += tilePartHeadLen[t][tp];
}
}
if(tptot==0)
firstTilePartHeadLen = tilePartHeadLen[t][tp];
tilePartsRead[t]++;
int nextMarkerPos = tilePartStart+tilePartLen[t][tp];
if(tilePartPositions == null) {
in.seek(nextMarkerPos);
}
if(nextMarkerPos > maxPos) {
maxPos = nextMarkerPos;
}
remainingTileParts--;
maxTP--;
tptot++;
if(isPsotEqualsZero) {
if(remainingTileParts!=0) {
FacilityManager.getMsgLogger().printmsg
(MsgLogger.WARNING,"Some tile-parts have not "+
"been found. The codestream may be corrupted.");
}
break;
}
}
} catch(EOFException e) {
isEOFEncountered = true;
if(printInfo) {
FacilityManager.getMsgLogger().
printmsg(MsgLogger.INFO,strInfo);
}
FacilityManager.getMsgLogger().
printmsg(MsgLogger.WARNING,"Codestream truncated in tile "+t);
int fileLen = in.length();
if(fileLen<tnbytes) {
tnbytes = fileLen;
trate = tnbytes*8f/hd.getMaxCompImgWidth()/
hd.getMaxCompImgHeight();
}
}
if(!isTilePartRead) return;
/* XXX: BEGIN Updating the resolution here is logical when all tile-part
headers are read as was the case with the original version of this
class. With initTile() however the tiles could be read in random
order so modifying the resolution value could cause unexpected
results if a given tile-part has fewer levels than the main header
indicated.
// Update 'res' value once all tile-part headers are read
if(j2krparam.getResolution()== -1) {
targetRes = decSpec.dls.getMin();
} else {
targetRes = j2krparam.getResolution();
if(targetRes<0) {
throw new
IllegalArgumentException("Specified negative "+
"resolution level index: "+
targetRes);
}
}
// Verify reduction in resolution level
int mdl = decSpec.dls.getMin();
if(targetRes>mdl) {
FacilityManager.getMsgLogger().
printmsg(MsgLogger.WARNING,
"Specified resolution level ("+targetRes+
") is larger"+
" than the maximum possible. Setting it to "+
mdl +" (maximum possible)");
targetRes = mdl;
}
XXX: END */
if(!isEOFEncountered) {
if(printInfo) {
FacilityManager.getMsgLogger().printmsg(MsgLogger.INFO,strInfo);
}
if(remainingTileParts == 0) {
if(!isEOCFound && !isPsotEqualsZero && !rateReached) {
try {
int savePos = in.getPos();
in.seek(maxPos);
if(in.readShort()!=EOC) {
FacilityManager.getMsgLogger().
printmsg(MsgLogger.WARNING,"EOC marker not found. "+
"Codestream is corrupted.");
}
in.seek(savePos);
} catch(EOFException e) {
FacilityManager.getMsgLogger().
printmsg(MsgLogger.WARNING,"EOC marker is missing");
}
}
}
}
if(!isTruncMode) {
allocateRate();
} else if(remainingTileParts == 0 && !isEOFEncountered) {
if(in.getPos()>=tnbytes)
anbytes += 2;
}
if(tilePartPositions == null) lastPos = in.getPos();
for (int tIdx=0; tIdx<nt; tIdx++) {
baknBytes[tIdx] = nBytes[tIdx];
if(printInfo) {
FacilityManager.getMsgLogger().
println(""+hi.toStringTileHeader(tIdx,tilePartLen[tIdx].
length),2,2);
}
}
} | java | 21 | 0.433004 | 84 | 41.918605 | 172 | /**
* Read all tile-part headers of the requested tile. All tile-part
* headers prior to the last tile-part header of the current tile will
* also be read.
*
* @param tileNum The index of the tile for which to read tile-part
* headers.
*/ | function |
func (in *ReportDataSourceSpec) DeepCopy() *ReportDataSourceSpec {
if in == nil {
return nil
}
out := new(ReportDataSourceSpec)
in.DeepCopyInto(out)
return out
} | go | 7 | 0.72619 | 66 | 20.125 | 8 | // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ReportDataSourceSpec. | function |
public Object
update
(
PluginUpdateReq req
)
{
TaskTimer timer = new TaskTimer();
timer.acquire();
pPluginLock.acquireReadLock();
try {
timer.resume();
Long cycleID = req.getCycleID();
TripleMap<String, String, VersionID, Object[]> builders =
pBuilderCollection.collectUpdated(cycleID);
TripleMap<String, String, VersionID, LayoutGroup> groups =
new TripleMap<String, String, VersionID, LayoutGroup>();
for(String vendor : builders.keySet()) {
for(String name : builders.keySet(vendor)) {
for(VersionID vid : builders.keySet(vendor, name)) {
groups.put(vendor, name, vid, pBuilderCollectionLayouts.get(vendor, name, vid));
}
}
}
TripleMap<String, String, VersionID, Object[]> annotations =
pAnnotations.collectUpdated(cycleID);
TripleMap<String, String, VersionID, AnnotationPermissions> annotPerms =
new TripleMap<String,String,VersionID,AnnotationPermissions>();
TripleMap<String,String,VersionID,TreeSet<AnnotationContext>> annotContexts =
new TripleMap<String,String,VersionID,TreeSet<AnnotationContext>>();
for(String vendor : annotations.keySet()) {
for(String name : annotations.keySet(vendor)) {
for(VersionID vid : annotations.keySet(vendor, name)) {
annotPerms.put(vendor, name, vid, pAnnotationPermissions.get(vendor, name, vid));
annotContexts.put(vendor, name, vid, pAnnotationContexts.get(vendor, name, vid));
}
}
}
/* Prepare a copy of the PluginStatus table. This contains the status for
all plugins that are loaded, missing, unknown and even the details of
being permanent or underdevelopment.
PluginStatus is indexed by PluginType and PluginID. */
DoubleMap<PluginType,PluginID,PluginStatus> pluginStatus =
new DoubleMap<PluginType,PluginID,PluginStatus>();
for(PluginType ptype : pPluginStatus.keySet()) {
for(PluginID pid : pPluginStatus.keySet(ptype)) {
PluginStatus pstat = pPluginStatus.get(ptype, pid);
pluginStatus.put(ptype, pid, pstat);
}
}
return new PluginUpdateRsp(timer, pLoadCycleID,
pEditors.collectUpdated(cycleID),
pActions.collectUpdated(cycleID),
pComparators.collectUpdated(cycleID),
pTools.collectUpdated(cycleID),
annotations,
pArchivers.collectUpdated(cycleID),
pMasterExts.collectUpdated(cycleID),
pQueueExts.collectUpdated(cycleID),
pKeyChoosers.collectUpdated(cycleID),
builders,
groups,
annotPerms, annotContexts,
pluginStatus);
}
finally {
pPluginLock.releaseReadLock();
}
} | java | 16 | 0.601767 | 93 | 43.955882 | 68 | /**
* Get any new or updated plugin classes.
*
* @param req
* The request.
*
* @return
* <CODE>PluginUpdateRsp</CODE> if successful or
* <CODE>FailureRsp</CODE> if unable to get the updated plugins.
*/ | function |
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool CompareExchange(ref double location1, double value, ref double comparand)
{
var comparandLocal = comparand;
comparand = Interlocked.CompareExchange(ref location1, value, comparandLocal);
return comparandLocal.Equals(comparand);
} | c# | 9 | 0.696379 | 100 | 50.428571 | 7 | /// <summary>
/// Compares two double-precision floating point numbers for equality and, if they are equal, replaces the first
/// value.
/// </summary>
/// <param name="location1">
/// The destination, whose value is compared with <paramref name="comparand" /> and possibly
/// replaced.
/// </param>
/// <param name="value">The value that replaces the destination value if the comparison results in equality.</param>
/// <param name="comparand">
/// The value that is compared to the value at <paramref name="location1" /> and receive the value
/// of the <paramref name="location1" /> at the moment of comparision.
/// </param>
/// <returns><see langword="true" />, if the exchange was performed, <see langword="false" /> otherwise.</returns>
/// <exception cref="NullReferenceException">The address of <paramref name="location1" /> is a null pointer.</exception> | function |
function _updateButtonState() {
if (this.voice.followed) {
this.dom.updateHTML(this.el, this.constructor.FOLLOWING_TEXT);
} else {
this.dom.updateHTML(this.el, this.constructor.FOLLOW_TEXT);
}
return this;
} | javascript | 11 | 0.532203 | 78 | 36 | 8 | /* Updates the button's text based on if currentPerson is following the
* current voice.
* @method _updateButtonState <private> [Function]
* @return VoiceFollowButton
*/ | function |
pub fn parse(&self) -> Result<String, Error> {
match self {
Self::Text(contents) | Self::Html(contents) => Ok(contents.to_string()),
Self::Mjml(mjml) => {
let parsed = mrml::parse(mjml).map_err(|e| Error::Markup {
source: anyhow::Error::msg(e.to_string()),
markup_type: MarkupType::Mjml,
context: Some("failed to parse the MJML"),
})?;
let rendered =
parsed
.render(&MrmlOptions::default())
.map_err(|e| Error::Markup {
source: anyhow::Error::msg(e.to_string()),
markup_type: MarkupType::Mjml,
context: Some("failed to render the MJML"),
})?;
Ok(rendered)
}
}
} | rust | 20 | 0.414395 | 84 | 42.714286 | 21 | /// Parse the markup into a string. Some types of markup need to parsed
/// (MJML), while others can directly return their contents (Text). | function |
static void
mcp5x_set_intr(nv_port_t *nvp, int flag)
{
nv_ctl_t *nvc = nvp->nvp_ctlp;
ddi_acc_handle_t bar5_hdl = nvc->nvc_bar_hdl[5];
uint16_t intr_bits =
MCP5X_INT_ADD|MCP5X_INT_REM|MCP5X_INT_COMPLETE;
uint16_t int_en;
if (flag & NV_INTR_DISABLE_NON_BLOCKING) {
int_en = nv_get16(bar5_hdl, nvp->nvp_mcp5x_int_ctl);
int_en &= ~intr_bits;
nv_put16(bar5_hdl, nvp->nvp_mcp5x_int_ctl, int_en);
return;
}
ASSERT(mutex_owned(&nvp->nvp_mutex));
NVLOG(NVDBG_INTR, nvc, nvp, "mcp055_set_intr: enter flag: %d", flag);
if (flag & NV_INTR_CLEAR_ALL) {
NVLOG(NVDBG_INTR, nvc, nvp,
"mcp5x_set_intr: NV_INTR_CLEAR_ALL", NULL);
nv_put16(bar5_hdl, nvp->nvp_mcp5x_int_status, MCP5X_INT_CLEAR);
}
if (flag & NV_INTR_ENABLE) {
NVLOG(NVDBG_INTR, nvc, nvp, "mcp5x_set_intr: NV_INTR_ENABLE",
NULL);
int_en = nv_get16(bar5_hdl, nvp->nvp_mcp5x_int_ctl);
int_en |= intr_bits;
nv_put16(bar5_hdl, nvp->nvp_mcp5x_int_ctl, int_en);
}
if (flag & NV_INTR_DISABLE) {
NVLOG(NVDBG_INTR, nvc, nvp,
"mcp5x_set_intr: NV_INTR_DISABLE", NULL);
int_en = nv_get16(bar5_hdl, nvp->nvp_mcp5x_int_ctl);
int_en &= ~intr_bits;
nv_put16(bar5_hdl, nvp->nvp_mcp5x_int_ctl, int_en);
}
} | c | 10 | 0.643333 | 70 | 32.361111 | 36 | /*
* enable or disable the 3 interrupts the driver is interested in:
* completion interrupt, hot add, and hot remove interrupt.
*/ | function |
public static void writePlistFile(Map<String, Object> eoModelMap, String eomodeldFullPath, String filename, boolean useXml) throws FileNotFoundException, UnsupportedEncodingException {
PrintWriter plistWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(eomodeldFullPath, filename)), "UTF-8")));
if (useXml) {
plistWriter.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
plistWriter.println("<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">");
plistWriter.println("<plist version=\"1.0\">");
writePlistPropertyMapXml(eoModelMap, 0, plistWriter);
plistWriter.println("</plist>");
} else {
writePlistPropertyMap(eoModelMap, 0, plistWriter, false);
}
plistWriter.close();
} | java | 15 | 0.667035 | 184 | 68.615385 | 13 | /**
* Writes model information in the Apple EOModelBundle format.
*
* For document structure and definition see: http://developer.apple.com/documentation/InternetWeb/Reference/WO_BundleReference/Articles/EOModelBundle.html
*
* @param eoModelMap
* @param eomodeldFullPath
* @param filename
* @throws FileNotFoundException
* @throws UnsupportedEncodingException
*/ | function |
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
protected override void Dispose(bool disposing)
{
if (disposing && components != null)
{
components.Dispose();
}
if (this.fSysFont != System.IntPtr.Zero)
{
NativeMethods.DeleteObject(this.fSysFont);
this.fSysFont = System.IntPtr.Zero;
}
fUpDown.ReleaseHandle();
base.Dispose(disposing);
} | c# | 12 | 0.549912 | 114 | 37.133333 | 15 | /// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> | function |
def capture_time_domain(self, rfe_mode, freq, rbw, device_settings=None,
min_points=128):
prop = self.real_device.properties
self.configure_device(dict(
freq=freq,
rfe_mode=rfe_mode,
**(device_settings if device_settings else {})))
if self._configure_device_flag:
self.real_device.apply_device_settings(self._device_set)
self._configure_device_flag = False
full_bw = prop.FULL_BW[rfe_mode]
self.real_device.abort()
self.real_device.flush()
self.real_device.request_read_perm()
self._vrt_context = {}
points = round(max(min_points, full_bw / rbw))
points = 2 ** math.ceil(math.log(points, 2))
fshift = self._device_set.get('fshift', 0)
decimation = self._device_set.get('decimation', 1)
self.usable_bins = compute_usable_bins(prop, rfe_mode, points,
decimation, fshift)
if self.async_callback:
self.real_device.set_async_callback(self.read_data)
self.real_device.capture(points, 1)
return
self.real_device.capture(points, 1)
result = None
while result is None:
result = self.read_data(self.real_device.read())
return result | python | 12 | 0.590454 | 72 | 42.333333 | 30 |
Initiate a capture of raw time domain IQ or I-only data
:param rfe_mode: radio front end mode, e.g. 'ZIF', 'SH', ...
:param freq: center frequency
:param rbw: requested RBW in Hz (output RBW may be smaller than
requested)
:type rbw: float
:param device_settings: attenuator, decimation frequency shift
and other device settings
:type dict:
:param min_points: smallest number of points per capture from real_device
:type min_points: int
| function |
inline
itk::TransformBase::Pointer
readTransformBase( std::string fileName )
{
typedef itk::TransformFileReader TransformReaderType;
typedef TransformReaderType::TransformListType TransformListType;
TransformReaderType::Pointer reader = TransformReaderType::New();
reader->SetFileName( fileName );
try
{
reader->Update();
}
catch( itk::ExceptionObject& )
{
throw std::runtime_error( "Could not read the input transformation." );
}
TransformListType * list = reader->GetTransformList();
if ( list->empty() )
throw std::runtime_error( "The input file does not contain any transformation." );
else if ( list->size()>1 )
throw std::runtime_error( "The input file contains more than one transformation." );
return list->front();
} | c++ | 10 | 0.666667 | 92 | 35.173913 | 23 | /**
* Reads a transform from a text file and returns a TransformBase::Pointer object.
* @param fileName path to the input transformation file
* @return transformation read as TransformBase::Pointer object
*/ | function |
def lookUpForSolver(self):
if self.solver == None or self.solver == '*' or self.solver == 'symbolicsys':
return self._symbolicSysSolveMechanism
elif self.solver == 'sympy':
return self._sympySolveMechanism
else:
raise AbsentRequiredObjectError("element from {}" % self.expected_solver_names, self.solver) | python | 11 | 0.642857 | 104 | 51.142857 | 7 |
Define the solver mechanism used for solution of the problem, given the name of desired mechanism in the instantiation of current Solver object
Uses the mechanism provided by the pyneqsys package
| function |
def csr_sum_indices(csr_matrices):
if len(csr_matrices) == 0: return [], _np.empty(0, int), _np.empty(0, int), 0
N = csr_matrices[0].shape[0]
for mx in csr_matrices:
assert(mx.shape == (N, N)), "Matrices must have the same square shape!"
indptr = [0]
indices = []
csr_sum_array = [list() for mx in csr_matrices]
for iRow in range(N):
dataInds = {}
for iMx, mx in enumerate(csr_matrices):
for i in range(mx.indptr[iRow], mx.indptr[iRow + 1]):
iCol = mx.indices[i]
if iCol not in dataInds:
indices.append(iCol)
dataInds[iCol] = len(indices) - 1
csr_sum_array[iMx].append(dataInds[iCol])
indptr.append(len(indices))
csr_sum_array = [_np.array(lst, _np.int64) for lst in csr_sum_array]
indptr = _np.array(indptr)
indices = _np.array(indices)
return csr_sum_array, indptr, indices, N | python | 16 | 0.5625 | 81 | 42.681818 | 22 |
Precomputes the indices needed to sum a set of CSR sparse matrices.
Computes the index-arrays needed for use in :method:`csr_sum`,
along with the index pointer and column-indices arrays for constructing
a "template" CSR matrix to be the destination of `csr_sum`.
Parameters
----------
csr_matrices : list
The SciPy CSR matrices to be summed.
Returns
-------
ind_arrays : list
A list of numpy arrays giving the destination data-array indices
of each element of `csr_matrices`.
indptr, indices : numpy.ndarray
The row-pointer and column-indices arrays specifying the sparsity
structure of a the destination CSR matrix.
N : int
The dimension of the destination matrix (and of each member of
`csr_matrices`)
| function |
public void createPackageContents() {
if (isCreated) return;
isCreated = true;
domainLNEClass = createEClass(DOMAIN_LN);
createEReference(domainLNEClass, DOMAIN_LN__MODE);
createEReference(domainLNEClass, DOMAIN_LN__BEHAVIOUR);
createEReference(domainLNEClass, DOMAIN_LN__HEALTH);
createEReference(domainLNEClass, DOMAIN_LN__NAME_PLT);
} | java | 7 | 0.775568 | 57 | 38.222222 | 9 | /**
* Creates the meta-model objects for the package. This method is
* guarded to have no affect on any invocation but its first.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/ | function |
protected Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {
Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder = new Jackson2ObjectMapperBuilder();
jackson2ObjectMapperBuilder.indentOutput(true);
/*
* Install the custom Jackson module that supports serializing and de-serializing ISO 8601 date
* and date/time values. The jackson-datatype-jsr310 module provided by Jackson was not used as
* it does not handle timezones correctly for LocalDateTime objects.
*/
jackson2ObjectMapperBuilder.modulesToInstall(new DateTimeModule());
return jackson2ObjectMapperBuilder;
} | java | 8 | 0.794212 | 99 | 55.636364 | 11 | /**
* Returns the <b>Jackson2ObjectMapperBuilder</b> bean, which configures the Jackson JSON
* processor package.
*
* @return the <b>Jackson2ObjectMapperBuilder</b> bean, which configures the Jackson JSON
* processor package
*/ | function |
public virtual void ClearMap()
{
if (HasQuit && (Application.isPlaying || !mapsService.MapPreviewOptions.Enable))
{
return;
}
if (mapsService.GameObjectManager != null)
{
mapsService.GameObjectManager.DestroyAll();
}
foreach (Transform child in mapsService.transform)
{
Destroy(child.gameObject);
}
} | c# | 11 | 0.489407 | 92 | 30.533333 | 15 | /// <summary>
/// Notifies the sdk that we are destroying geometry so that it can be reloaded from the apis
/// correctly.
/// This function also destroy the <see cref="GameObject"/>s in the scene.
/// The MapsService keeps an internal cache of <see cref="GameObject"/>s, and their
/// relationships to MapFeatures. When these <see cref="GameObject"/>s are destroyed in the
/// scene through gameplay for example, it is a best practice to notify the MapsService about
/// the changes. MapsService will then update its dictionary of MapFeatures, and will trigger
/// the appropriate WillCreate/DidCreate MapEvents next time a call to MakeMapLoadRegion is
/// called. It won't invoke these events if the associated map features are still in its cache.
/// </summary> | function |
class rESOURCEpOOL {
constructor({name, size, available, resourceType, resources}) {
this.name = name;
if (Number.isInteger( size) || size === Infinity) { // a count pool
this.size = size;
if (!Number.isInteger( available)) this.available = size;
else this.available = available;
} else if (resourceType) { // an individual pool
this.resourceType = resourceType;
this.busyResources = [];
this.availResources = [];
if (Array.isArray( resources)) {
for (const res of resources) {
if (res.status === rESOURCEsTATUS.AVAILABLE) this.availResources.push( res);
else if (res.status === rESOURCEsTATUS.BUSY) this.busyResources.push( res);
}
}
} else {
console.log(`Resource pool ${name} is not well-defined!`)
}
this.dependentNodes = [];
}
isAvailable( card=1) {
if (this.resourceType) { // individual pool
if (this.availResources.length >= card) return true;
// check if there are alternative resources
const altResTypes = this.resourceType.alternativeResourceTypes;
if (Array.isArray( altResTypes) && altResTypes.length > 0) {
const rP = sim.Classes[altResTypes[0]].resourcePool;
return rP && rP.isAvailable( card);
} else return false;
} else return this.available >= card;
}
nmrAvailable() {
return this.availResources?.length || this.available;
}
allocateAll() {
if (this.availResources) { // individual pool
let allocatedRes = [...this.availResources];
for (const res of this.availResources) {
res.status = rESOURCEsTATUS.BUSY;
this.busyResources.push( res);
}
this.availResources.length = 0;
return allocatedRes;
} else this.available = 0; // count pool
}
allocate( card=1) {
var rP=null;
if (this.availResources) { // individual pool
if (this.availResources.length >= card) {
rP = this;
} else {
const altResTypes = this.resourceType.alternativeResourceTypes;
if (Array.isArray( altResTypes) && altResTypes.length > 0) {
//TODO: use all altResTypes, not just altResTypes[0]
rP = sim.Classes[altResTypes[0]].resourcePool;
if (!rP?.isAvailable( card)) rP = null;
}
}
if (!rP) {
console.error(`The pool ${this.name} does not have enough resources at simulation step ${sim.step}!`,
JSON.stringify(this));
return [];
}
if (rP !== this) {
console.log(`Allocate ${this.resourceType.name} from pool ${rP.name}`);
}
// remove the first card resources from availResources
const allocatedRes = rP.availResources.splice( 0, card);
for (const res of allocatedRes) {
res.status = rESOURCEsTATUS.BUSY;
rP.busyResources.push( res);
}
return allocatedRes;
} else { // count pool
this.available -= card;
}
}
release( nmrOrRes) { // number or resource(s)
if (nmrOrRes === undefined) nmrOrRes = 1;
if (typeof nmrOrRes === "number" && this.size) { // count pool
this.available += nmrOrRes;
} else if (typeof nmrOrRes === "object") { // individual pool
let resources = nmrOrRes;
if (!Array.isArray( resources)) resources = [resources];
for (const res of resources) {
const i = this.busyResources.indexOf( res);
if (i === -1) {
console.error(`The pool ${this.name} does not contain resource ${res.name}
at simulation step ${sim.step}!`);
return;
} else {
// remove resource from busyResources list
this.busyResources.splice( i, 1);
// add resource to availResources list
res.status = rESOURCEsTATUS.AVAILABLE;
this.availResources.push( res);
}
}
} else {
console.error(`Release attempt for pool ${this.name} with "nmrOrRes" = ${nmrOrRes} failed
at simulation step ${sim.step}!`);
return;
}
// try starting enqueued tasks depending on this type of resource
for (const node of this.dependentNodes) {
node.ifAvailAllocReqResAndStartNextActivity();
}
}
clear() {
if (this.resourceType) { // individual pool
// resources are added in setupInitialState
this.busyResources.length = 0;
this.availResources.length = 0;
} else { // count pool
this.available = this.size;
}
}
toString() {
if (this.resourceType) { // individual pool
const availRes = this.availResources.map( r => r.name || r.id);
return `av. ${this.name}: ${availRes}`;
} else {
return `av. ${this.name}: ${this.available}`;
}
}
} | javascript | 20 | 0.607204 | 109 | 35.664063 | 128 | /****************************************************************************
A resource pool can take one of two forms:
(1) a count pool abstracts away from individual resources and just maintains
an "available" counter of the available resources of some type
(2) an individual pool is a collection of individual resource objects
Each resource role must be associated with a pool. By default, a count pool
is directly associated with a resource role, while an individual pool is
associated with the range of a resource role, which is a resource type. Resource
pools may be globally indexed in the map "sim.scenario.resourcePools" with resource type
names or resource role names as keys. Otherwise, if they are identified by
the combination of node and resRoleName, they can be locally indexed
in the map "node.resourceRoles[resRoleName].resourcePool".
For any performer role (defined in an activity type definition), an individual
pool is defined with a (lower-cased and pluralized) name obtained from the
role's range name if it's a position or, otherwise, from the closest position
subtyping the role's range.
****************************************************************************/ | class |
public class SOAPAttachmentHandler implements XMLAttachmentMarshaller {
private int count = 0;
private HashMap<String, DataHandler> attachments = new HashMap<String,DataHandler>();
public boolean hasAttachments() {
return attachments.size() > 0;
}
public Map<String, DataHandler> getAttachments() {
return attachments;
}
public String addSwaRefAttachment(DataHandler data) {
++count;
String name = "cid:ref" + count;
attachments.put(name, data);
return name;
}
public String addSwaRefAttachment(byte[] data, int start, int length) {
++count;
String name = "cid:ref" + count;
DataHandler dataHandler = new DataHandler(new ByteArrayDataSource(data,
"application/octet-stream"));
attachments.put(name, dataHandler);
return name;
}
public String addMtomAttachment(DataHandler data, String elementName, String namespace) {
String name = "cid:" + randomUUID().toString();
attachments.put(name, data);
return name;
}
public String addMtomAttachment(byte[] data, int start, int len, String mimeType,
String elementName, String namespace) {
String name = "cid:" + randomUUID().toString();
DataHandler dataHandler = new DataHandler(new ByteArrayDataSource(data,
"application/octet-stream"));
attachments.put(name, dataHandler);
return name;
}
public boolean isXOPPackage() {
return true;
}
} | java | 12 | 0.644112 | 93 | 31.041667 | 48 | /**
* <p><b>INTERNAL</b>: implementation of EclipseLink {@link XMLAttachmentMarshaller} implementation
* handles binary attachments
*
* @author Mike Norman - [email protected]
* @since EclipseLink 1.x
*/ | class |
int Aggregator_distinct::composite_key_cmp(void* arg, uchar* key1, uchar* key2)
{
Aggregator_distinct *aggr= (Aggregator_distinct *) arg;
Field **field = aggr->table->field;
Field **field_end= field + aggr->table->s->fields;
uint32 *lengths=aggr->field_lengths;
for (; field < field_end; ++field)
{
Field* f = *field;
int len = *lengths++;
int res = f->cmp(key1, key2);
if (res)
return res;
key1 += len;
key2 += len;
}
return 0;
} | c++ | 9 | 0.60334 | 79 | 25.666667 | 18 | /**
Correctly compare composite keys.
Used by the Unique class to compare keys. Will do correct comparisons
for composite keys with various field types.
@param arg Pointer to the relevant Aggregator_distinct instance
@param key1 left key image
@param key2 right key image
@return comparison result
@retval <0 if key1 < key2
@retval =0 if key1 = key2
@retval >0 if key1 > key2
*/ | function |
class CaptionBubbleLabel : public views::Label {
public:
METADATA_HEADER(CaptionBubbleLabel);
#if defined(NEED_FOCUS_FOR_ACCESSIBILITY)
CaptionBubbleLabel() {
ax_mode_observer_ =
std::make_unique<CaptionBubbleLabelAXModeObserver>(this);
SetFocusBehaviorForAccessibility();
}
#else
CaptionBubbleLabel() = default;
#endif
~CaptionBubbleLabel() override = default;
CaptionBubbleLabel(const CaptionBubbleLabel&) = delete;
CaptionBubbleLabel& operator=(const CaptionBubbleLabel&) = delete;
void GetAccessibleNodeData(ui::AXNodeData* node_data) override {
node_data->role = ax::mojom::Role::kDocument;
node_data->SetRestriction(ax::mojom::Restriction::kReadOnly);
#if defined(NEED_FOCUS_FOR_ACCESSIBILITY)
node_data->SetNameFrom(ax::mojom::NameFrom::kAttributeExplicitlyEmpty);
#endif
}
void SetText(const std::u16string& text) override {
views::Label::SetText(text);
auto& ax_lines = GetViewAccessibility().virtual_children();
if (text.empty() && !ax_lines.empty()) {
GetViewAccessibility().RemoveAllVirtualChildViews();
NotifyAccessibilityEvent(ax::mojom::Event::kChildrenChanged, true);
return;
}
const size_t num_lines = GetRequiredLines();
size_t start = 0;
for (size_t i = 0; i < num_lines - 1; ++i) {
size_t end = GetTextIndexOfLine(i + 1);
std::u16string substring = text.substr(start, end - start);
UpdateAXLine(substring, i, gfx::Range(start, end));
start = end;
}
std::u16string substring = text.substr(start, text.size() - start);
if (!substring.empty()) {
UpdateAXLine(substring, num_lines - 1, gfx::Range(start, text.size()));
}
size_t num_ax_lines = ax_lines.size();
for (size_t i = num_lines; i < num_ax_lines; ++i) {
GetViewAccessibility().RemoveVirtualChildView(ax_lines.back().get());
NotifyAccessibilityEvent(ax::mojom::Event::kChildrenChanged, true);
}
}
#if defined(NEED_FOCUS_FOR_ACCESSIBILITY)
void SetFocusBehaviorForAccessibility() {
if (ui::AXPlatformNode::GetAccessibilityMode().has_mode(
ui::AXMode::kScreenReader)) {
SetFocusBehavior(FocusBehavior::ALWAYS);
} else {
SetFocusBehavior(FocusBehavior::NEVER);
}
}
#endif
private:
void UpdateAXLine(const std::u16string& line_text,
const size_t line_index,
const gfx::Range& text_range) {
auto& ax_lines = GetViewAccessibility().virtual_children();
DCHECK(line_index <= ax_lines.size());
if (line_index == ax_lines.size()) {
auto ax_line = std::make_unique<views::AXVirtualView>();
ax_line->GetCustomData().role = ax::mojom::Role::kStaticText;
GetViewAccessibility().AddVirtualChildView(std::move(ax_line));
NotifyAccessibilityEvent(ax::mojom::Event::kChildrenChanged, true);
}
ui::AXNodeData& ax_node_data = ax_lines[line_index]->GetCustomData();
if (base::UTF8ToUTF16(ax_node_data.GetStringAttribute(
ax::mojom::StringAttribute::kName)) != line_text) {
ax_node_data.SetName(line_text);
std::vector<gfx::Rect> bounds = GetSubstringBounds(text_range);
ax_node_data.relative_bounds.bounds = gfx::RectF(bounds[0]);
ax_lines[line_index]->NotifyAccessibilityEvent(
ax::mojom::Event::kTextChanged);
}
}
#if defined(NEED_FOCUS_FOR_ACCESSIBILITY)
std::unique_ptr<CaptionBubbleLabelAXModeObserver> ax_mode_observer_;
#endif
} | c++ | 15 | 0.678104 | 77 | 39.952381 | 84 | // CaptionBubble implementation of Label. This class takes care of setting up
// the accessible virtual views of the label in order to support braille
// accessibility. The CaptionBubbleLabel is a readonly document with a paragraph
// inside. Inside the paragraph are staticText nodes, one for each visual line
// in the rendered text of the label. These staticText nodes are shown on a
// braille display so that a braille user can read the caption text line by
// line. | class |
public abstract class BsWhiteOnlyOneToOneFrom extends AbstractEntity implements DomainEntity {
// ===================================================================================
// Definition
// ==========
/** The serial version UID for object serialization. (Default) */
private static final long serialVersionUID = 1L;
// ===================================================================================
// Attribute
// =========
/** FROM_ID: {PK, ID, NotNull, BIGINT(19)} */
protected Long _fromId;
/** FROM_NAME: {NotNull, VARCHAR(200)} */
protected String _fromName;
// ===================================================================================
// DB Meta
// =======
/** {@inheritDoc} */
public DBMeta asDBMeta() {
return DBMetaInstanceHandler.findDBMeta(asTableDbName());
}
/** {@inheritDoc} */
public String asTableDbName() {
return "white_only_one_to_one_from";
}
// ===================================================================================
// Key Handling
// ============
/** {@inheritDoc} */
public boolean hasPrimaryKeyValue() {
if (_fromId == null) { return false; }
return true;
}
// ===================================================================================
// Foreign Property
// ================
/** white_only_one_to_one_to by FROM_ID, named 'whiteOnlyOneToOneToAsOne'. */
protected OptionalEntity<WhiteOnlyOneToOneTo> _whiteOnlyOneToOneToAsOne;
/**
* [get] white_only_one_to_one_to by FROM_ID, named 'whiteOnlyOneToOneToAsOne'.
* Optional: alwaysPresent(), ifPresent().orElse(), get(), ...
* @return the entity of foreign property(referrer-as-one) 'whiteOnlyOneToOneToAsOne'. (NotNull, EmptyAllowed: when e.g. no data, no setupSelect)
*/
public OptionalEntity<WhiteOnlyOneToOneTo> getWhiteOnlyOneToOneToAsOne() {
if (_whiteOnlyOneToOneToAsOne == null) { _whiteOnlyOneToOneToAsOne = OptionalEntity.relationEmpty(this, "whiteOnlyOneToOneToAsOne"); }
return _whiteOnlyOneToOneToAsOne;
}
/**
* [set] white_only_one_to_one_to by FROM_ID, named 'whiteOnlyOneToOneToAsOne'.
* @param whiteOnlyOneToOneToAsOne The entity of foreign property(referrer-as-one) 'whiteOnlyOneToOneToAsOne'. (NullAllowed)
*/
public void setWhiteOnlyOneToOneToAsOne(OptionalEntity<WhiteOnlyOneToOneTo> whiteOnlyOneToOneToAsOne) {
_whiteOnlyOneToOneToAsOne = whiteOnlyOneToOneToAsOne;
}
// ===================================================================================
// Referrer Property
// =================
protected <ELEMENT> List<ELEMENT> newReferrerList() { // overriding to import
return new ArrayList<ELEMENT>();
}
// ===================================================================================
// Basic Override
// ==============
@Override
protected boolean doEquals(Object obj) {
if (obj instanceof BsWhiteOnlyOneToOneFrom) {
BsWhiteOnlyOneToOneFrom other = (BsWhiteOnlyOneToOneFrom)obj;
if (!xSV(_fromId, other._fromId)) { return false; }
return true;
} else {
return false;
}
}
@Override
protected int doHashCode(int initial) {
int hs = initial;
hs = xCH(hs, asTableDbName());
hs = xCH(hs, _fromId);
return hs;
}
@Override
protected String doBuildStringWithRelation(String li) {
StringBuilder sb = new StringBuilder();
if (_whiteOnlyOneToOneToAsOne != null && _whiteOnlyOneToOneToAsOne.isPresent())
{ sb.append(li).append(xbRDS(_whiteOnlyOneToOneToAsOne, "whiteOnlyOneToOneToAsOne")); }
return sb.toString();
}
protected <ET extends Entity> String xbRDS(org.dbflute.optional.OptionalEntity<ET> et, String name) { // buildRelationDisplayString()
return et.get().buildDisplayString(name, true, true);
}
@Override
protected String doBuildColumnString(String dm) {
StringBuilder sb = new StringBuilder();
sb.append(dm).append(xfND(_fromId));
sb.append(dm).append(xfND(_fromName));
if (sb.length() > dm.length()) {
sb.delete(0, dm.length());
}
sb.insert(0, "{").append("}");
return sb.toString();
}
@Override
protected String doBuildRelationString(String dm) {
StringBuilder sb = new StringBuilder();
if (_whiteOnlyOneToOneToAsOne != null && _whiteOnlyOneToOneToAsOne.isPresent())
{ sb.append(dm).append("whiteOnlyOneToOneToAsOne"); }
if (sb.length() > dm.length()) {
sb.delete(0, dm.length()).insert(0, "(").append(")");
}
return sb.toString();
}
@Override
public WhiteOnlyOneToOneFrom clone() {
return (WhiteOnlyOneToOneFrom)super.clone();
}
// ===================================================================================
// Accessor
// ========
/**
* [get] FROM_ID: {PK, ID, NotNull, BIGINT(19)} <br>
* @return The value of the column 'FROM_ID'. (basically NotNull if selected: for the constraint)
*/
public Long getFromId() {
checkSpecifiedProperty("fromId");
return _fromId;
}
/**
* [set] FROM_ID: {PK, ID, NotNull, BIGINT(19)} <br>
* @param fromId The value of the column 'FROM_ID'. (basically NotNull if update: for the constraint)
*/
public void setFromId(Long fromId) {
registerModifiedProperty("fromId");
_fromId = fromId;
}
/**
* [get] FROM_NAME: {NotNull, VARCHAR(200)} <br>
* @return The value of the column 'FROM_NAME'. (basically NotNull if selected: for the constraint)
*/
public String getFromName() {
checkSpecifiedProperty("fromName");
return _fromName;
}
/**
* [set] FROM_NAME: {NotNull, VARCHAR(200)} <br>
* @param fromName The value of the column 'FROM_NAME'. (basically NotNull if update: for the constraint)
*/
public void setFromName(String fromName) {
registerModifiedProperty("fromName");
_fromName = fromName;
}
} | java | 14 | 0.449967 | 149 | 42.394118 | 170 | /**
* The entity of WHITE_ONLY_ONE_TO_ONE_FROM as TABLE. <br>
* <pre>
* [primary-key]
* FROM_ID
*
* [column]
* FROM_ID, FROM_NAME
*
* [sequence]
*
*
* [identity]
* FROM_ID
*
* [version-no]
*
*
* [foreign table]
* WHITE_ONLY_ONE_TO_ONE_TO(AsOne)
*
* [referrer table]
* WHITE_ONLY_ONE_TO_ONE_TO
*
* [foreign property]
* whiteOnlyOneToOneToAsOne
*
* [referrer property]
*
*
* [get/set template]
* /= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
* Long fromId = entity.getFromId();
* String fromName = entity.getFromName();
* entity.setFromId(fromId);
* entity.setFromName(fromName);
* = = = = = = = = = =/
* </pre>
* @author DBFlute(AutoGenerator)
*/ | class |
public void SetBaseline(IGridView<T> baseline)
{
if (baseline.Width != BaseGrid.Width || baseline.Height != BaseGrid.Height)
throw new ArgumentException(
$"Baseline grid view's width/height must be same as {nameof(BaseGrid)}.",
nameof(baseline));
if (_diffs.Count != 0)
throw new InvalidOperationException("Baseline values must be set before any diffs are recorded.");
_baseGrid.ApplyOverlay(baseline);
} | c# | 14 | 0.587121 | 114 | 51.9 | 10 | /// <summary>
/// Sets the baseline values (eg. values before any diffs are recorded) to the values from the given grid view.
/// Only valid to do before any diffs are recorded.
/// </summary>
/// <param name="baseline">Baseline values to use. Must have same width/height as <see cref="BaseGrid"/>.</param> | function |
static truncateToWidth(
context,
str,
width,
fontWidth = GridRenderer.DEFAULT_FONT_WIDTH
) {
if (width <= 0 || str.length <= 0) {
return '';
}
const lo = Math.min(
Math.max(0, Math.floor(width / fontWidth / 2) - 5),
str.length
);
const hi = Math.min(Math.ceil((width / fontWidth) * 2), str.length);
return GridRenderer.binaryTruncateToWidth(context, str, width, lo, hi);
} | javascript | 12 | 0.592166 | 75 | 26.1875 | 16 | /**
* Truncate a string (if necessary) to fit in the specified width.
* First uses the estimated font width to calculate a lower/upper bound
* Then uses binary search within those bounds to find the exact max length
* @param {Context} context The drawing context
* @param {string} str The string to calculate max length for
* @param {number} width The width to truncate within
* @param {number} fontWidth The estimated width of each character
* @returns {string} The truncated string that fits within the width provided
*/ | function |
private static CharPred allCharsExcept(Character excluded,
boolean returnPred){
if(excluded == null){
if(returnPred)
return(SlowExample.TRUE_RET);
else
return(StdCharPred.TRUE);
}
char prev = excluded; prev--;
char next = excluded; next++;
return(new CharPred(ImmutableList.of(ImmutablePair.of(CharPred.MIN_CHAR,
prev),
ImmutablePair.of(next,
CharPred.MAX_CHAR)),
returnPred));
} | java | 12 | 0.44012 | 78 | 40.8125 | 16 | /**
* allCharsExcept() builds a CharPred predicate that accepts any character
* except for "excluded". If "excluded" is null, it returns the TRUE
* predicate.
*
* @param excluded the character to exclude
* @param returnPred whether or not we should generate a return predicate
* @return the predicate
*/ | function |
public class CustomServerPlatformAdapter extends ServerPlatformAdapter {
// property change
public final static String SERVER_CLASS_NAME_PROPERTY = "serverClassName";
public final static String EXTERNAL_TRANSACTION_CONTROLLER_CLASS_PROPERTY = "externalTransactionControllerClass";
/**
* Default constructor
*/
CustomServerPlatformAdapter() {
super();
}
/**
* Creates a new Platform for the specified model object.
*/
CustomServerPlatformAdapter( SCAdapter parent, CustomServerPlatformConfig scConfig) {
super( parent, scConfig);
}
/**
* Creates a new Platform.
*/
protected CustomServerPlatformAdapter( SCAdapter parent) {
super( parent);
}
/**
* Returns this Config Model Object.
*/
private final CustomServerPlatformConfig platformConfig() {
return ( CustomServerPlatformConfig)this.getModel();
}
/**
* Factory method for building this model.
*/
protected Object buildModel() {
return new CustomServerPlatformConfig();
}
public boolean isCustom() {
return true;
}
/**
* Returns this config model property.
*/
public String getServerClassName() {
return this.platformConfig().getServerClassName();
}
/**
* Sets this config model property.
*/
public void setServerClassName( String name) {
Object old = this.platformConfig().getServerClassName();
this.platformConfig().setServerClassName( name);
this.firePropertyChanged( SERVER_CLASS_NAME_PROPERTY, old, name);
}
/**
* Returns this config model property.
*/
public String getExternalTransactionControllerClass() {
return this.platformConfig().getExternalTransactionControllerClass();
}
/**
* Sets this config model property.
*/
public void setExternalTransactionControllerClass( String name) {
Object old = this.platformConfig().getExternalTransactionControllerClass();
this.platformConfig().setExternalTransactionControllerClass( name);
this.firePropertyChanged( EXTERNAL_TRANSACTION_CONTROLLER_CLASS_PROPERTY, old, name);
}
/**
* Add any problems from this adapter to the given set.
*/
protected void addProblemsTo( List branchProblems) {
super.addProblemsTo(branchProblems);
verifyExternalTransactionControllerClass(branchProblems);
verifyServerClassName(branchProblems);
}
private void verifyExternalTransactionControllerClass( List branchProblems) {
String className = getExternalTransactionControllerClass();
if( StringTools.stringIsEmpty( className)) {
branchProblems.add( buildProblem( SCProblemsConstants.CUSTOM_SERVER_PLATFORM_JTA, getParent().displayString()));
}
}
private void verifyServerClassName( List branchProblems) {
String className = getServerClassName();
if( StringTools.stringIsEmpty( className)) {
branchProblems.add( buildProblem( SCProblemsConstants.CUSTOM_SERVER_PLATFORM_SERVER_CLASS_NAME, getParent().displayString()));
}
}
} | java | 15 | 0.724046 | 129 | 25.925234 | 107 | /**
* Session Configuration model adapter class for the
* TopLink Foudation Library class CustomServerPlatformConfig
*
* @see CustomServerPlatformConfig
*
* @author Tran Le
*/ | class |
def add_artificial_noise(sci_image,var_image,model_image):
Max_SN_now=np.max(sci_image)/np.max(np.sqrt(var_image))
dif_in_SN=Max_SN_now/220
artifical_noise=np.zeros_like(model_image)
artifical_noise=np.array(artifical_noise)
min_var_value=np.min(var_image)
for i in range(len(artifical_noise)):
for j in range(len(artifical_noise)):
artifical_noise[i,j]=np.random.randn()*np.sqrt((dif_in_SN**2-1)*(var_image[i,j]-min_var_value))
if dif_in_SN>1:
return (sci_image+artifical_noise),((dif_in_SN**2)*(var_image-min_var_value)+min_var_value),model_image
else:
return (sci_image),((dif_in_SN**2)*(var_image-min_var_value)+min_var_value),model_image | python | 16 | 0.654646 | 111 | 54.538462 | 13 |
add extra noise so that it has comparable noise as if the max flux in the image (in the single pixel) is 40000
@array[in] sci_image numpy array with the values for the cutout of the science image (20x20 cutout)
@array[in] var_image numpy array with the cutout for the cutout of the variance image (20x20 cutout)
@array[in] model_image model (20x20 image)
@array[out] sci_image if max flux smaller than 40000, unchanged science image (20x20 cutout)
if max flux larger than 40000, degraded science image
@array[out] modified variance image
@array[out] model_image unchagned model (20x20 image)
| function |
def register_jvm_tool(self, key, tools, ini_section=None, ini_key=None):
if not tools:
raise ValueError("No implementations were provided for tool '%s'" % key)
self._products.require_data('jvm_build_tools_classpath_callbacks')
tool_product_map = self._products.get_data('jvm_build_tools') or {}
tool_product_config_map = self._products.get_data('jvm_build_tools_config') or {}
existing = tool_product_map.get(key)
if existing is not None:
if existing != tools:
raise TaskError('Attemping to change tools under %s from %s to %s.'
% (key, existing, tools))
else:
tool_product_map[key] = tools
tool_product_config_map[key] = {'ini_section': ini_section, 'ini_key': ini_key}
self._products.safe_create_data('jvm_build_tools', lambda: tool_product_map)
self._products.safe_create_data('jvm_build_tools_config', lambda: tool_product_config_map) | python | 12 | 0.663812 | 96 | 57.4375 | 16 | Register a list of targets against a key.
We can later use this key to get a callback that will resolve these targets.
Note: Not reentrant. We assume that all registration is done in the main thread.
| function |
public Matrix GetDampedPseudoInverse(double lambda)
{
Matrix result = null;
Matrix transpose = Transpose();
if (NrRows >= NrCols)
{
result = (transpose * this + lambda * lambda * Matrix.Eye(NrCols)).GetInvert() * transpose;
}
if (NrCols > NrRows)
{
result = transpose * (this * transpose + lambda * lambda * Matrix.Eye(NrRows)).GetInvert();
}
return result;
} | c# | 17 | 0.493204 | 107 | 35.857143 | 14 | /// <summary>
/// The damping makes the pseudo inverse more stable in close to singular cases
/// Calling it with dambda = 0 results in a normal pseudo invers
/// </summary>
/// <param name="lambda"></param>
/// <returns></returns> | function |
public bool VerifyInput(string hashedInput, object rawData)
{
if (hashedInput == Hasher.Add0x(HashWithSalt(Parser.JsonEncode(rawData))))
{
return true;
}
return false;
} | c# | 15 | 0.526104 | 86 | 30.25 | 8 | /// <summary>
/// Takes the raw input and hashed_input, and makes a comparison.
/// </summary>
/// <param name="hashedInput"></param>
/// <param name="rawData"></param>
/// <returns>value (boolean): are they the same or not</returns> | function |
private void computeFVs(List<DTGraph<ApproxStringLabel,ApproxStringLabel>> graphs, SparseVector[] featureVectors, double weight, int lastIndex) {
int index;
for (int i = 0; i < graphs.size(); i++) {
featureVectors[i].setLastIndex(lastIndex);
for (DTNode<ApproxStringLabel,ApproxStringLabel> vertex : graphs.get(i).nodes()) {
String lab = vertex.label().toString();
if (!noDuplicateSubtrees || vertex.label().getSameAsPrev() == 0) {
index = Integer.parseInt(lab);
featureVectors[i].setValue(index, featureVectors[i].getValue(index) + weight);
}
}
for (DTLink<ApproxStringLabel,ApproxStringLabel> edge : graphs.get(i).links()) {
String lab = edge.tag().toString();
if (!noDuplicateSubtrees || edge.tag().getSameAsPrev() == 0) {
index = Integer.parseInt(lab);
featureVectors[i].setValue(index, featureVectors[i].getValue(index) + weight);
}
}
}
} | java | 15 | 0.684268 | 145 | 44.5 | 20 | /**
* Compute feature vector for the graphs based on the label dictionary created in the previous two steps
*
* @param graphs
* @param featureVectors
* @param startLabel
* @param currentLabel
*/ | function |
static void nasmt_nl_data_ready (struct sk_buff *skb)
{
struct nlmsghdr *nlh = NULL;
#ifdef NETLINK_DEBUG
printk("nasmt_nl_data_ready - begin \n");
#endif
if (!skb) {
printk("nasmt_nl_data_ready - input parameter skb is NULL \n");
return;
}
#ifdef NETLINK_DEBUG
printk("nasmt_nl_data_ready - Received socket from PDCP\n");
#endif
nlh = (struct nlmsghdr *)skb->data;
nasmt_COMMON_QOS_receive(nlh);
} | c | 9 | 0.674584 | 67 | 25.375 | 16 | // This can also be implemented using thread to get the data from PDCP without blocking.
//---------------------------------------------------------------------------
// Function for transfer with PDCP (from NASLITE) | function |
int ardp_receive (int sock, char **s)
{
int n, rec, sa_len;
struct sockaddr_in source;
struct ardpdata a;
*s = NULL;
sa_len = sizeof (struct sockaddr_in);
rec = recvfrom (sock, recv_buffer, RECV_SIZE, 0, (struct sockaddr *) &source, &sa_len);
if (sa_len != sizeof (struct sockaddr_in))
{
return 0;
}
if (source.sin_family != conn.server.sin_family ||
source.sin_port != conn.server.sin_port )
{
return 0;
}
if (rec <= 0)
{
return 0;
}
ardp_parse_header (recv_buffer, rec, &a);
in_sequence = 1;
if (a.flag_control_only)
{
ardp_ping (sock);
return 0;
}
if (a.totalpkt > n_expected) n_expected = a.totalpkt;
switch (a.option)
{
case 0:
if (a.pktno == n_received + 1)
{
*s = recv_buffer+a.hdrlen;
n_received++;
n = rec-a.hdrlen;
(*s)[n] = '\0';
if (n_received == n_expected && n_expected != 0)
{
ardp_ping (sock);
in_sequence = 0;
}
return n;
}
return 0;
case 1:
return -1;
default:
return 0;
}
} | c | 13 | 0.459135 | 91 | 23.019231 | 52 | /* ----------------------------------------------------------------------------
receives data from server. returns length of malloc()ed buffer (s), or -1 if error.
0 indicates that pending data were discarded and no useful input is available */ | function |
private void OnClearPane(object sender, EventArgs args)
{
if (!mefTextBuffer.EditInProgress)
{
ClearReadOnlyRegion();
SetCursorAtEndOfBuffer();
}
} | c# | 9 | 0.506494 | 55 | 28 | 8 | /// <summary>
/// Function called when the user select the "Clear Pane" menu item from the context menu.
/// This will clear the content of the console window leaving only the console cursor and
/// resizing the read-only region.
/// </summary> | function |
static void
nfsd_sanitize_attrs(struct inode *inode, struct iattr *iap)
{
#define BOTH_TIME_SET (ATTR_ATIME_SET | ATTR_MTIME_SET)
#define MAX_TOUCH_TIME_ERROR (30*60)
if ((iap->ia_valid & BOTH_TIME_SET) == BOTH_TIME_SET &&
iap->ia_mtime.tv_sec == iap->ia_atime.tv_sec) {
time_t delta = iap->ia_atime.tv_sec - get_seconds();
if (delta < 0)
delta = -delta;
if (delta < MAX_TOUCH_TIME_ERROR &&
inode_change_ok(inode, iap) != 0) {
iap->ia_valid &= ~BOTH_TIME_SET;
}
}
if (iap->ia_valid & ATTR_MODE) {
iap->ia_mode &= S_IALLUGO;
iap->ia_mode |= (inode->i_mode & ~S_IALLUGO);
}
if (!S_ISDIR(inode->i_mode) &&
((iap->ia_valid & ATTR_UID) || (iap->ia_valid & ATTR_GID))) {
iap->ia_valid |= ATTR_KILL_PRIV;
if (iap->ia_valid & ATTR_MODE) {
iap->ia_mode &= ~S_ISUID;
if (iap->ia_mode & S_IXGRP)
iap->ia_mode &= ~S_ISGID;
} else {
iap->ia_valid |= (ATTR_KILL_SUID | ATTR_KILL_SGID);
}
}
} | c | 12 | 0.588486 | 66 | 29.290323 | 31 | /*
* Go over the attributes and take care of the small differences between
* NFS semantics and what Linux expects.
*/ | function |
public class DataObjectWithMapAddersConverter {
private static final Base64.Decoder BASE64_DECODER = JsonUtil.BASE64_DECODER;
private static final Base64.Encoder BASE64_ENCODER = JsonUtil.BASE64_ENCODER;
public static void fromJson(Iterable<java.util.Map.Entry<String, Object>> json, DataObjectWithMapAdders obj) {
for (java.util.Map.Entry<String, Object> member : json) {
switch (member.getKey()) {
case "booleanValues":
if (member.getValue() instanceof JsonObject) {
((Iterable<java.util.Map.Entry<String, Object>>)member.getValue()).forEach(entry -> {
if (entry.getValue() instanceof Boolean)
obj.addBooleanValue(entry.getKey(), (Boolean)entry.getValue());
});
}
break;
case "dataObjectValues":
if (member.getValue() instanceof JsonObject) {
((Iterable<java.util.Map.Entry<String, Object>>)member.getValue()).forEach(entry -> {
if (entry.getValue() instanceof JsonObject)
obj.addDataObjectValue(entry.getKey(), new io.vertx.codegen.testmodel.TestDataObject((io.vertx.core.json.JsonObject)entry.getValue()));
});
}
break;
case "doubleValues":
if (member.getValue() instanceof JsonObject) {
((Iterable<java.util.Map.Entry<String, Object>>)member.getValue()).forEach(entry -> {
if (entry.getValue() instanceof Number)
obj.addDoubleValue(entry.getKey(), ((Number)entry.getValue()).doubleValue());
});
}
break;
case "enumValues":
if (member.getValue() instanceof JsonObject) {
((Iterable<java.util.Map.Entry<String, Object>>)member.getValue()).forEach(entry -> {
if (entry.getValue() instanceof String)
obj.addEnumValue(entry.getKey(), io.vertx.codegen.testmodel.TestEnum.valueOf((String)entry.getValue()));
});
}
break;
case "floatValues":
if (member.getValue() instanceof JsonObject) {
((Iterable<java.util.Map.Entry<String, Object>>)member.getValue()).forEach(entry -> {
if (entry.getValue() instanceof Number)
obj.addFloatValue(entry.getKey(), ((Number)entry.getValue()).floatValue());
});
}
break;
case "genEnumValues":
if (member.getValue() instanceof JsonObject) {
((Iterable<java.util.Map.Entry<String, Object>>)member.getValue()).forEach(entry -> {
if (entry.getValue() instanceof String)
obj.addGenEnumValue(entry.getKey(), io.vertx.codegen.testmodel.TestGenEnum.valueOf((String)entry.getValue()));
});
}
break;
case "instantValues":
if (member.getValue() instanceof JsonObject) {
((Iterable<java.util.Map.Entry<String, Object>>)member.getValue()).forEach(entry -> {
if (entry.getValue() instanceof String)
obj.addInstantValue(entry.getKey(), Instant.from(DateTimeFormatter.ISO_INSTANT.parse((String)entry.getValue())));
});
}
break;
case "integerValues":
if (member.getValue() instanceof JsonObject) {
((Iterable<java.util.Map.Entry<String, Object>>)member.getValue()).forEach(entry -> {
if (entry.getValue() instanceof Number)
obj.addIntegerValue(entry.getKey(), ((Number)entry.getValue()).intValue());
});
}
break;
case "jsonArrayValues":
if (member.getValue() instanceof JsonObject) {
((Iterable<java.util.Map.Entry<String, Object>>)member.getValue()).forEach(entry -> {
if (entry.getValue() instanceof JsonArray)
obj.addJsonArrayValue(entry.getKey(), ((JsonArray)entry.getValue()).copy());
});
}
break;
case "jsonObjectValues":
if (member.getValue() instanceof JsonObject) {
((Iterable<java.util.Map.Entry<String, Object>>)member.getValue()).forEach(entry -> {
if (entry.getValue() instanceof JsonObject)
obj.addJsonObjectValue(entry.getKey(), ((JsonObject)entry.getValue()).copy());
});
}
break;
case "longValues":
if (member.getValue() instanceof JsonObject) {
((Iterable<java.util.Map.Entry<String, Object>>)member.getValue()).forEach(entry -> {
if (entry.getValue() instanceof Number)
obj.addLongValue(entry.getKey(), ((Number)entry.getValue()).longValue());
});
}
break;
case "shortValues":
if (member.getValue() instanceof JsonObject) {
((Iterable<java.util.Map.Entry<String, Object>>)member.getValue()).forEach(entry -> {
if (entry.getValue() instanceof Number)
obj.addShortValue(entry.getKey(), ((Number)entry.getValue()).shortValue());
});
}
break;
case "stringValues":
if (member.getValue() instanceof JsonObject) {
((Iterable<java.util.Map.Entry<String, Object>>)member.getValue()).forEach(entry -> {
if (entry.getValue() instanceof String)
obj.addStringValue(entry.getKey(), (String)entry.getValue());
});
}
break;
}
}
}
public static void toJson(DataObjectWithMapAdders obj, JsonObject json) {
toJson(obj, json.getMap());
}
public static void toJson(DataObjectWithMapAdders obj, java.util.Map<String, Object> json) {
}
} | java | 28 | 0.582733 | 151 | 44.870968 | 124 | /**
* Converter and mapper for {@link io.vertx.codegen.testmodel.DataObjectWithMapAdders}.
* NOTE: This class has been automatically generated from the {@link io.vertx.codegen.testmodel.DataObjectWithMapAdders} original class using Vert.x codegen.
*/ | class |
def parse_provinces(provinces, savegame):
provinces = split("-(\d+)=[{]", provinces)[1:]
province_id_list = provinces[::2]
province_list = provinces[1::2]
for province, x in zip(province_list, range(len(province_list))):
province_list[x] = province.split("history")[0]
province_list[x] += province.split("discovered_by=")[-1]
province_regex = "name=\"(?P<name>[^\n]+)\".+?" \
"base_tax=(?P<base_tax>\d+).+?" \
"base_production=(?P<base_production>\d+).+?base_manpower=(?P<base_manpower>\d+).+?" \
"trade_goods=(?P<trade_goods>[^\n]+)"
province_regex2 = "owner=\"(?P<owner>[^\n]+)\""
province_regex3 = "religion=(?P<religion>[^\n]+)"
province_regex4 = "culture=(?P<culture>[^\n]+)"
province_regex5 = "trade_power=(?P<trade_power>[^\n]+)"
province_x = compile(province_regex, DOTALL)
province_x2 = compile(province_regex2, DOTALL)
province_x3 = compile(province_regex3, DOTALL)
province_x4 = compile(province_regex4, DOTALL)
province_x5 = compile(province_regex5, DOTALL)
try:
i = -1
for province, id in zip(province_list,province_id_list):
try:
result = province_x.search(province).groupdict()
for cat in ("base_tax", "base_production", "base_manpower"):
result[cat] = int(result[cat])
result["development"] = result["base_tax"] + result["base_production"] + result["base_manpower"]
result["province_id"] = id
result["savegame_id"] = savegame.id
trade_good = TradeGood.query.filter_by(name = result["trade_goods"]).first()
if trade_good:
result["trade_good_id"] = trade_good.id
del result["name"]
del result["trade_goods"]
owner = province_x2.search(province)
if owner:
result["nation_tag"] = owner.group(1)
religion = province_x3.search(province)
if religion:
result["religion"] = religion.group(1)
culture = province_x4.search(province)
if culture:
result["culture"] = culture.group(1)
trade_power = province_x5.search(province)
if trade_power:
result["trade_power"] = float(trade_power.group(1))
prov = NationSavegameProvinces(**result)
db.session.add(prov)
except AttributeError as e:
pass
db.session.flush()
i -= 1
except IntegrityError as e:
print(e)
db.session.rollback()
else:
db.session.commit() | python | 18 | 0.650989 | 100 | 38.241379 | 58 | First part of the main parser.
Parses all province-related information.
Takes only content from start till end of province information of the savegame.
Return list of lists with all revelant stats for each province.
Each Province has its own sub-list with following information (in order):
[Province_ID, Name, Owner, Tax, Production, Manpower, Development, Trade Node, Culture,
Religion, Trade Good, Area, Region, Superregion]
| function |
static short fsys_copy(const char * src_path, const char * dst_path) {
unsigned char buffer[256];
t_file_info file;
short fd_src = -1;
short fd_dst = -1;
short result = 0;
short n = 0;
if (strcicmp(src_path, dst_path) == 0) {
return ERR_COPY_SELF;
}
result = sys_fsys_stat(src_path, &file);
if (result < 0) {
return result;
} else {
if (file.attributes & FSYS_AM_DIR) {
return ERR_COPY_SRC_IS_DIR;
}
}
if (is_directory(dst_path)) {
return ERR_COPY_DST_IS_DIR;
}
fd_src = sys_fsys_open(src_path, FSYS_READ);
if (fd_src > 0) {
fd_dst = sys_fsys_open(dst_path, FSYS_WRITE | FSYS_CREATE_ALWAYS);
if (fd_dst > 0) {
do {
n = sys_chan_read(fd_src, buffer, 256);
if (n > 0) {
result = sys_chan_write(fd_dst, buffer, n);
}
} while ((n > 0) && (result >= 0));
sys_fsys_close(fd_src);
sys_fsys_close(fd_dst);
return 0;
} else {
sys_fsys_close(fd_src);
return fd_dst;
}
} else {
return fd_src;
}
} | c | 15 | 0.472107 | 74 | 27.619048 | 42 | /**
* Perform the actual copy of the files, given the full paths to the files
*
* @param src_path the path to the source file to be copied
* @param dst_path the path to the destination file (will be deleted if it already exists)
* @return 0 on success, a negative number on error
*/ | function |
Subsets and Splits