text
stringlengths 27
775k
|
|---|
package com.kylecorry.sol.science.astronomy.locators
import com.kylecorry.sol.science.astronomy.meteors.MeteorShower
import com.kylecorry.sol.science.astronomy.units.EquatorialCoordinate
import com.kylecorry.sol.science.astronomy.units.UniversalTime
import com.kylecorry.sol.science.astronomy.units.timeToAngle
internal class MeteorShowerLocator(private val shower: MeteorShower) : ICelestialLocator {
override fun getCoordinates(ut: UniversalTime): EquatorialCoordinate {
return getRadiant()
}
private fun getRadiant(): EquatorialCoordinate {
return when (shower) {
MeteorShower.Quadrantids -> EquatorialCoordinate(49.7, timeToAngle(15, 20, 0))
MeteorShower.Lyrids -> EquatorialCoordinate(33.3, timeToAngle(18, 10, 0))
MeteorShower.EtaAquariids -> EquatorialCoordinate(
-1.1,
timeToAngle(22, 30, 0)
)
MeteorShower.DeltaAquariids -> EquatorialCoordinate(
-16.4,
timeToAngle(22, 42, 0)
)
MeteorShower.Perseids -> EquatorialCoordinate(58.0, timeToAngle(3, 13, 0))
MeteorShower.Orionids -> EquatorialCoordinate(15.6, timeToAngle(6, 19, 0))
MeteorShower.Leonids -> EquatorialCoordinate(21.6, timeToAngle(10, 16, 0))
MeteorShower.Geminids -> EquatorialCoordinate(32.2, timeToAngle(7, 36, 0))
MeteorShower.Ursids -> EquatorialCoordinate(75.3, timeToAngle(14, 36, 0))
}
}
}
|
using Employees.Services.Interfaces;
using EmployeesMapping.App.Commands.Interfaces;
namespace EmployeesMapping.App.Commands
{
public class ManagerInfoCommand : ICommand
{
private readonly IEmployeeService empService;
public ManagerInfoCommand(IEmployeeService empService)
{
this.empService = empService;
}
public string Execute(params string[] arguments)
{
int employeeId = int.Parse(arguments[0]);
string result = this.empService.GetManagerInfo(employeeId);
return result;
}
}
}
|
module ExactTargetSDK
class TriggeredSend < APIObject
array_property 'Attributes'
array_property 'Subscribers'
property 'TriggeredSendDefinition', :required => true
property 'Client'
end
end
|
# Stereo Matching using CoEx with TensorRT in C++
Sample project to run Stereo Matching using CoEx
Click the image to open in YouTube. https://youtu.be/fCIdXr0Hpbk
[](https://youtu.be/fCIdXr0Hpbk)
* Test image data is "2011_09_26_drive_0005" from The KITTI Dataset
## Target Environment, How to Build, How to Run
1. Please follow the instruction: https://github.com/iwatake2222/play_with_tensorrt/blob/master/README.md
2. Additional steps:
- Download the model using the following script
- https://github.com/PINTO0309/PINTO_model_zoo/blob/main/135_CoEx/download.sh
- copy `saved_model/coex_480x640.onnx` to `resource/model/coex_480x640.onnx`
- Build `pj_tensorrt_depth_stereo_coex` project (this directory)
## Acknowledgements
- https://github.com/antabangun/coex
- https://github.com/PINTO0309/PINTO_model_zoo
- http://www.cvlibs.net/datasets/kitti/raw_data.php
|
package com.signify.hue.flutterreactiveble.channelhandlers
import com.signify.hue.flutterreactiveble.ble.BleClient
import io.flutter.plugin.common.EventChannel
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.disposables.SerialDisposable
import java.util.concurrent.TimeUnit
import com.signify.hue.flutterreactiveble.ProtobufModel as pb
class BleStatusHandler(private val bleClient: BleClient) : EventChannel.StreamHandler {
companion object {
private const val delayListenBleStatus = 500L
}
private val subscriptionDisposable = SerialDisposable()
override fun onListen(arg: Any?, eventSink: EventChannel.EventSink?) {
subscriptionDisposable.set(eventSink?.let(::listenToBleStatus))
}
override fun onCancel(arg: Any?) {
subscriptionDisposable.set(null)
}
private fun listenToBleStatus(eventSink: EventChannel.EventSink): Disposable =
Observable.timer(delayListenBleStatus, TimeUnit.MILLISECONDS)
.switchMap { bleClient.observeBleStatus() }
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ bleStatus ->
val message = pb.BleStatusInfo.newBuilder()
.setStatus(bleStatus.code)
.build()
eventSink.success(message.toByteArray())
}, { throwable ->
eventSink.error("ObserveBleStatusFailure", throwable.message, null)
})
}
|
#!/bin/bash
# This script runs kotlin test app compilation with ksp and kapt repeatedly to measure time spent for each of them.
# Each build is executed once first (to cache all other tasks), and then N times for just ksp/kapt tasks.
set -e
declare -A totals
declare -A taskTotals
function log {
echo $1
}
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
PROJECT_DIR="$SCRIPT_DIR/.."
# move to the project directory
cd $PROJECT_DIR;
KSP_TASK=":room:integration-tests:room-testapp-kotlin:kspWithKspDebugAndroidTestKotlin"
KAPT_TASK=":room:integration-tests:room-testapp-kotlin:kaptGenerateStubsWithKaptDebugAndroidTestKotlin \
:room:integration-tests:room-testapp-kotlin:kaptWithKaptDebugAndroidTestKotlin"
# parses the given profile file, extracts task durations that we are interested in and adds them to the global tracking
# usage: parseTimes profileFileURI prefix
function parseTimes {
local filePath=$1
local prefix=$2
# get the times
local result=`curl -s $filePath|grep :$prefix -A1`
local total=0
local taskName="ERROR-$prefix"
while read -r line
do
if [[ "$line" == *"numeric"* ]]; then
local taskTime=`echo $line|awk -F'[>s<]' '{print $5*1000}'`
total=$(($total + $taskTime))
taskTotals[$taskName]=$((taskTotals[$taskName] + $taskTime))
elif [[ "$line" == *":"* ]]; then
taskName=`echo $line|awk -F'[><]' '{print $3}'|awk -F'[:]' '{print $NF}'`
fi
done <<< $result
echo "total time spent for in this run $prefix: $total"
totals[$prefix]=$((totals[$prefix] + $total))
}
# Runs the kotlin integration test app with either ksp or kapt then records the duration of tasks.
# usage: runBuild ksp / runBuild kapt
function runBuild {
local type=$1
local task=""
if [ "$type" = "ksp" ]; then
task=$KSP_TASK
elif [ "$type" = "kapt" ]; then
task=$KAPT_TASK
else
echo "bad arg '$type'"
exit 1
fi
local cmd="./gradlew --no-daemon --init-script \
$SCRIPT_DIR/rerun-requested-task-init-script.gradle \
--profile $task"
log "Executing $cmd"
local profileFile=`$cmd|grep -v "buildSrc"|awk '/profiling report at:/ {print $6}'`
log "result: $profileFile"
parseTimes $profileFile $type
}
# Runs the compilation with kapt and ksp for the given number of times
# usage: runTest 3
function runTest {
local limit=$1
for (( c=1; c<=$limit; c++ ))
do
echo "run #$c of $limit"
runBuild "ksp"
runBuild "kapt"
done
}
function printData {
local -n data=$1
echo "$1:"
for i in "${!data[@]}"
do
echo "$i : ${data[$i]} ms"
done
}
# build once so all other tasks are cached
./gradlew $KSP_TASK $KAPT_TASK
runTest 10
printData totals
printData taskTotals
|
package template.base.extensions
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import timber.log.Timber
fun CoroutineScope.launchSafe(
action: suspend () -> Unit,
onError: (Throwable) -> Unit = {}
) {
launch {
try {
action()
} catch (e: CancellationException) {
Timber.d(e, "Job cancelled")
} catch (e: Exception) {
onError(e)
}
}
}
|
Import-Module .\PSWriteHTML.psd1 -Force
$DataTable3 = @(
[PSCustomObject] @{
'Tree Parent?' = 'Testing Tree ?'
'Other Tree (Rigth)' = 'Ok You mean Me (Test)'
'Hierarchy Table Recaluculation interval (minutes)' = "\\*\NETLOGON"
"Test" = "\\Ooops\C$\Windows\System32\config\netlogon.dns"
"\\*\SYSVOL" = 'Test me \\*\SYSVOL and \\*\NETLOGON shares.'
"\\*\NETLOGON" = 'Test me \\*\SYSVOL and \\*\NETLOGON shares.'
'Test^' = 'Oops1'
"Hello+Motto" = 'Oops2'
'Hello|Motto' = 'Oops3'
'Hello{Value}' = 'Oops4'
'Hello$Value' = 'Oops5'
'Hello.Value' = 'Oops6'
'Hello Value' = 'Oops7.Test'
"TestOt" = "MSFT_NetAdapter (CreationClassName = `"MSFT_NetAdapter`", DeviceID = `"{49B2B54A-37B5-4130-8D41-AAAD57854F3A}`", SystemCreationClassName = `"CIM_NetworkPort`", SystemName = `"EVOWIN.ad.evotec.xyz`")"
"Test3" = "MSFT_NetRoute (InstanceID = `";C?8;@B8??:8:9??55;?55:8:8:8:55;`")"
}
)
#$DataTable3 | ConvertTo-Json
#$DataTable3 | ConvertTo-JsonLiteral | ConvertFrom-Json
#$DataTable3 | Out-HtmlView -DataStore JavaScript -FilePath $PSScriptRoot\Example7_10_DataStoreJava.html -Online
#$T = Get-HotFix -ComputerName AD1 | Sort-Object -Property InstalledOn -Descending | Select-Object -First 1
$T | Out-HtmlView -DataStore JavaScript -FilePath $PSScriptRoot\Example7_10_DataStoreJava.html -Online -Filtering
<#
"NetAdapter":"MSFT_NetAdapter (CreationClassName = "MSFT_NetAdapter", DeviceID = "{49B2B54A-37B5-4130-8D41-AAAD57854F3A}", SystemCreationClassName = "CIM_NetworkPort", SystemName = "EVOWIN.ad.evotec.xyz")",
"NetRoute":"MSFT_NetRoute (InstanceID = ";C?8;@B8??:8:9??55;?55:8:8:8:55;")",
"InterfaceAlias":"vEthernet (External Switch)",
"InterfaceIndex":14,
"InterfaceDescription":"Hyper-V Virtual Ethernet Adapter #2",
"NetAdapter":"MSFT_NetAdapter (CreationClassName = "MSFT_NetAdapter", DeviceID = "{49B2B54A-37B5-4130-8D41-AAAD57854F3A}", SystemCreationClassName = "CIM_NetworkPort", SystemName = "EVOWIN.ad.evotec.xyz")",
"NetRoute":"MSFT_NetRoute (InstanceID = ";C?8;@B8??:8:9??55;?55:8:8:8:55;")",
"SourceAddress":"192.168.240.221",
"NameResolutionSucceeded":"True",
"BasicNameResolution":"Microsoft.DnsClient.Commands.DnsRecord_A",
"LLMNRNetbiosRecords":"Microsoft.DnsClient.Commands.DnsRecord_A",
"__SERVER":"AD1",
"__NAMESPACE":"root\\cimv2",
"__PATH":"\\\\AD1\\root\\cimv2:Win32_QuickFixEngineering.HotFixID=\"KB4577015\",ServicePackInEffect=\"\"",
"Caption":"https://support.microsoft.com/help/4577015",
"CSName":"AD1",
"Description":"Security Update",
"FixComments":"",
"HotFixID":"KB4577015",
"InstallDate":"",
"InstalledBy":"NT AUTHORITY\\SYSTEM",
"Name":"",
"ServicePackInEffect":"",
"Status":"",
"Scope":"System.Management.ManagementScope",
"Path":"\AD1
oot mv2:Win32_QuickFixEngineering.HotFixID="KB4577015",ServicePackInEffect=""",
"Options":"System.Management.ObjectGetOptions",
"ClassPath":"\AD1
oot mv2:Win32_QuickFixEngineering",
"Properties":"System.Management.PropertyDataCollection",
"SystemProperties":"System.Management.PropertyDataCollection",
"Qualifiers":"System.Management.QualifierDataCollection",
#>
|
<?php namespace SmashPig\PaymentProviders\PayPal;
use LogicException;
use SmashPig\Core\Context;
use SmashPig\Core\Http\OutboundRequest;
class PayPalPaymentsAPI {
/**
* @param array $post_fields Associative array of fields posted to listener
* @return bool
*/
public function validate( $post_fields = [] ) {
$post_fields['cmd'] = '_notify-validate';
$url = Context::get()->getProviderConfiguration()->val( 'postback-url' );
$request = new OutboundRequest( $url, 'POST' );
$request->setBody( $post_fields );
$response = $request->execute();
if ( $response['body'] === 'VERIFIED' ) {
return true;
} elseif ( $response['body'] === 'INVALID' ) {
return false;
}
throw new LogicException(
'EnumValidator should not allow reaching this point!'
);
}
}
|
# Copyright 2020 Google, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require_relative "helper"
require_relative "../sample.rb"
describe "Logging Samples" do
parallelize_me!
let(:rand_pre) { "logging_samples_test_" }
let(:log_name) { rand_pre + "log_" + SecureRandom.hex }
let(:payload) { "logging sample test payload" }
let(:bucket_name) { rand_pre + "bucket_" + SecureRandom.hex }
let(:bucket) { create_bucket_helper bucket_name }
let(:sink_name) { rand_pre + "sink_" + SecureRandom.hex }
let :sink do
bucket.acl.add_owner "group-cloud-logs@google.com"
logging.create_sink sink_name, "storage.googleapis.com/#{bucket.id}"
end
let :entry do
log_entry = logging.entry
log_entry.payload = payload
log_entry.log_name = log_name
log_entry.resource.type = "gae_app"
logging.write_entries log_entry
log_entry
end
describe "create_logging_client" do
it "creates a logging client" do
assert create_logging_client.is_a? logging.class
end
end
describe "list_log_sinks" do
after do
logging.sink(sink_name).delete
delete_bucket_helper bucket_name
end
it "lists the log sinks" do
sink
out, _err = capture_io do
list_log_sinks
end
assert_includes out, sink_name
end
end
describe "create_log_sink" do
after do
logging.sink(sink_name).delete
delete_bucket_helper bucket_name
end
it "creates a log sink" do
out, _err = capture_io do
create_log_sink bucket_name: bucket_name, sink_name: sink_name
end
sinks = logging.sinks.map(&:name)
assert_includes out, sink_name
assert_includes sinks, sink_name
end
end
describe "update_log_sink" do
after do
logging.sink(sink_name).delete
delete_bucket_helper bucket_name
delete_bucket_helper "#{bucket_name}_2"
end
it "changes the destination of a sink" do
sink
other_bucket_name = "#{bucket_name}_2"
out, _err = capture_io do
update_log_sink bucket_name: other_bucket_name, sink_name: sink_name
end
destination = "storage.googleapis.com/#{storage.bucket(other_bucket_name).id}"
assert_equal out, "Updated sink destination for #{sink_name} to #{destination}\n"
sink.reload!
assert_equal sink.destination, destination
end
end
describe "delete_log_sink" do
after do
delete_bucket_helper bucket_name
end
it "changes the destination of a sink" do
assert_output "Deleted sink: #{sink.name}\n" do
delete_log_sink sink_name: sink_name
end
refute_includes logging.sinks.map(&:name), sink_name
end
end
describe "list_log_entries" do
after do
delete_log_helper log_name
end
it "lists entries of a log" do
found = get_entries_helper entry.log_name
# Try to reduce flakiness. We think the logging service is sometimes
# taking a long time to index new logs.
skip if found.empty?
out, _err = capture_io do
list_log_entries log_name: entry.log_name
end
entries = logging.entries filter: "logName:#{entry.log_name}",
max: 1000,
order: "timestamp desc"
entries.map! { |entry| "[#{entry.timestamp}] #{entry.log_name} #{entry.payload.inspect}" }
out_entries = out.split "\n"
assert(out_entries.any? { |entry| entries.include? entry })
end
end
describe "write_log_entry" do
after do
delete_log_helper log_name
end
it "writes an entry to a log" do
assert_output "Wrote payload: #{payload} to log: #{log_name}\n" do
write_log_entry log_name: log_name, payload: payload
end
entries = get_entries_helper(log_name).map(&:payload)
skip if entries.empty?
assert_includes entries, payload
end
end
describe "delete_log" do
it "deletes a log" do
entry
found = get_entries_helper log_name
skip if found.empty?
assert_output "Deleted log: #{log_name}\n" do
delete_log log_name: log_name
end
assert_empty get_entries_helper(log_name)
end
end
describe "write_log_entry_using_ruby_logger" do
after do
delete_log_helper log_name
end
it "writes a log entry" do
write_log_entry_using_ruby_logger payload: payload, log_name: log_name
entries = get_entries_helper(log_name).map(&:payload)
skip if entries.empty?
assert_includes entries, payload
end
end
end
|
SELECT e.`first_name`, e.`last_name`, e.`department_id`
FROM `employees` AS e,
(SELECT e.`department_id`, AVG(e.`salary`) AS 'avg_sal'
FROM `employees` AS e
GROUP BY e.`department_id`) AS avg_sal_res
WHERE e.`department_id` = avg_sal_res.`department_id` AND e.`salary` > avg_sal_res.`avg_sal`
ORDER BY e.`department_id`
LIMIT 10;
|
module Temperature (tempToC, tempToF) where
tempToC :: Integer -> Float
tempToC temp = (fromInteger temp - 32) / 1.8
tempToF :: Float -> Integer
tempToF temp = ceiling $ temp * 1.8 + 32
|
package me.unei.configuration.api;
import me.unei.configuration.api.exceptions.NoFieldException;
import me.unei.configuration.api.fs.NavigableFile;
import me.unei.configuration.formats.StorageType;
import java.util.List;
public interface IConfiguration extends IFlatConfiguration, NavigableFile {
/**
* Returns the top-most parent starting from this configuration.
*
* @return this configuration's top-most parent
*/
public IConfiguration getRoot();
/**
* Returns the first parent of this configuration.
*
* @return this configuration's first parent
*/
public IConfiguration getParent();
/**
* Returns the direct child element of this configuration which has
* the specified name, as an {@link IConfiguration IConfiguration}.
* <p>
* Newbies: Prefer using {@link #getSubSection(String)} over this one.
*
* @param name the name of the child to retrieve
* @return the direct child element with the specified name as an {@link IConfiguration IConfiguration}
*/
public IConfiguration getChild(String name);
/**
* Returns the direct child element of this configuration at the
* specified index, as an {@link IConfiguration IConfiguration}.
* <p>
* Only works when this section is acting as a list, the behavior
* of this method is undefined otherwise.
*
* @param index the index of the child to retrieve
* @return the direct child element at the specified index as an {@link IConfiguration IConfiguration}
*/
public IConfiguration getAt(int index);
/**
* Returns the name of this configuration section.
*
* @return the name of this configuration section
*/
public String getName();
/**
* Returns the type of this configuration section.
*
* @return the type of this configuration section.
*/
public StorageType getType();
/**
* Sets the type of this configuration section.
*
* @param type the new (or expected) type of this configuration section.
*/
public void setType(StorageType type);
/**
* Returns the element at the specified path, starting at
* this configuration.
*
* @param path the path pointing to the element to retrieve
* @return the element at the specified path
*/
public Object get(String path);
/**
* Tries to get the object associated with the specified key as name,
* if possible. In case that name does not refer to a value
* a {@link NoFieldException} will be thrown.
*
* @param path the path pointing to the element to retrieve
* @return the element at the specified path
* @throws NoFieldException if the specified name does not refer to any value.
*/
public Object tryGet(String path) throws NoFieldException;
/**
* Returns the the value associated with the specified key as name,
* if possible. In case that name does not refer to any value the
* specified default value will be returned (but not stored !).
*
* @param path the name of the value to retrieve.
* @param def the default value to return of none available.
* @return the value with the specified name.
*/
public Object get(String path, Object def);
/*
/**
* Returns the element at the specified path, starting at
* this configuration, as {@link String String}, if possible.
*
* @param path the path pointing to the element to retrieve
* @return the element at the specified path as {@link String String}
* /
public String getString(String path);
/**
* Returns the element at the specified path, starting at
* this configuration, as double, if possible.
*
* @param path the path pointing to the element to retrieve
* @return the element at the specified path as double
* /
public double getDouble(String path);
/**
* Returns the element at the specified path, starting at
* this configuration, as boolean, if possible.
*
* @param path the path pointing to the element to retrieve
* @return the element at the specified path as boolean
* /
public boolean getBoolean(String path);
/**
* Returns the element at the specified path, starting at
* this configuration, as byte, if possible.
*
* @param path the path pointing to the element to retrieve
* @return the element at the specified path as byte
* /
public byte getByte(String path);
/**
* Returns the element at the specified path, starting at
* this configuration, as float, if possible.
*
* @param path the path pointing to the element to retrieve
* @return the element at the specified path as float
* /
public float getFloat(String path);
/**
* Returns the element at the specified path, starting at
* this configuration, as int, if possible.
*
* @param path the path pointing to the element to retrieve
* @return the element at the specified path as int
* /
public int getInteger(String path);
/**
* Returns the element at the specified path, starting at
* this configuration, as long, if possible.
*
* @param path the path pointing to the element to retrieve
* @return the element at the specified path as long
* /
public long getLong(String path);
*/
/**
* Returns the element at the specified path, starting at
* this configuration, as {@link Byte Byte} {@link List List}, if possible.
*
* @param path the path pointing to the element to retrieve
* @return the element at the specified path as {@link Byte Byte} {@link List List}
*/
public List<Byte> getByteList(String path);
/**
* Returns the element at the specified path, starting at
* this configuration, as {@link Integer Integer} {@link List List}, if possible.
*
* @param path the path pointing to the element to retrieve
* @return the element at the specified path as {@link Integer Integer} {@link List List} list
*/
public List<Integer> getIntegerList(String path);
/**
* Returns the element at the specified path, starting at
* this configuration, as {@link Long Long} {@link List List}, if possible.
*
* @param path the path pointing to the element to retrieve
* @return the element at the specified path as {@link Long Long} {@link List List}
*/
public List<Long> getLongList(String path);
/**
* Returns the sub-section at the specified path, starting at
* this configuration.
*
* @param path the path pointing to the sub-section to retrieve
* @return the sub-section at the specified path
*/
public IConfiguration getSubSection(String path);
/**
* Sets the element at the specified path, starting at
* this configuration.
*
* @param path the path pointing to the element to set
* @param value the element to set at the specified path
*/
public void set(String path, Object value);
/*
/**
* Sets the element at the specified path, starting at
* this configuration, to the specified {@link String String}.
*
* @param path the path pointing to the element to set
* @param value the {@link String String} to set at the specified path
* /
public void setString(String path, String value);
/**
* Sets the element at the specified path, starting at
* this configuration, to the specified double.
*
* @param path the path pointing to the element to set
* @param value the double to set at the specified path
* /
public void setDouble(String path, double value);
/**
* Sets the element at the specified path, starting at
* this configuration, to the specified boolean.
*
* @param path the path pointing to the element to set
* @param value the boolean to set at the specified path
* /
public void setBoolean(String path, boolean value);
/**
* Sets the element at the specified path, starting at
* this configuration, to the specified byte.
*
* @param path the path pointing to the element to set
* @param value the byte to set at the specified path
* /
public void setByte(String path, byte value);
/**
* Sets the element at the specified path, starting at
* this configuration, to the specified float.
*
* @param path the path pointing to the element to set
* @param value the float to set at the specified path
* /
public void setFloat(String path, float value);
/**
* Sets the element at the specified path, starting at
* this configuration, to the specified int.
*
* @param path the path pointing to the element to set
* @param value the int to set at the specified path
* /
public void setInteger(String path, int value);
/**
* Sets the element at the specified path, starting at
* this configuration, to the specified long.
*
* @param path the path pointing to the element to set
* @param value the long to set at the specified path
* /
public void setLong(String path, long value);
*/
/**
* Sets the element at the specified path, starting at
* this configuration, to the specified {@link Byte Byte} {@link List List}.
*
* @param path the path pointing to the element to set
* @param value the {@link Byte Byte} {@link List List} to set at the specified path
*/
public void setByteList(String path, List<Byte> value);
/**
* Sets the element at the specified path, starting at
* this configuration, to the specified {@link Integer Integer} {@link List List}.
*
* @param path the path pointing to the element to set
* @param value the {@link Integer Integer} {@link List List} to set at the specified path
*/
public void setIntegerList(String path, List<Integer> value);
/**
* Sets the element at the specified path, starting at
* this configuration, to the specified {@link Long Long} {@link List List}.
*
* @param path the path pointing to the element to set
* @param value the {@link Long Long} {@link List List} to set at the specified path
*/
public void setLongList(String path, List<Long> value);
/**
* Sets the sub-section at the specified path, starting at
* this configuration.
*
* @param path the path pointing to the sub-section to set
* @param value the sub-section to set at the specified path
*/
public void setSubSection(String path, IConfiguration value);
/*
/**
* Removes any element with the specified path, starting at
* this configuration.
*
* @param path the path of the element to remove
* /
public void remove(String path);*/
}
|
package model.service
import model.domain.classification.ClassifierService
import org.apache.spark.mllib.classification.NaiveBayesModel
import org.apache.spark.mllib.feature.HashingTF
import org.apache.spark.{SparkConf, SparkContext}
class IsRelevantClassifier extends ClassifierService{
val conf: SparkConf = new SparkConf().setMaster("local[*]").setAppName("IsRelevantClassifier")
val sc: SparkContext = new SparkContext(conf)
val htf: HashingTF = new HashingTF(10000)
val model: NaiveBayesModel = NaiveBayesModel.load(sc, "conf/model")
def classify(text: String): String ={
if (text.length < 10)
"0.0"
else
model.predict(htf.transform(text.replaceAll("""<(?!\/?a(?=>|\s.*>))\/?.*?>""", "").split(" "))).toString
}
}
|
/*
* Your installation or use of this SugarCRM file is subject to the applicable
* terms available at
* http://support.sugarcrm.com/Resources/Master_Subscription_Agreements/.
* If you do not agree to all of the applicable terms or do not have the
* authority to bind the entity as an authorized representative, then do not
* install or use this SugarCRM file.
*
* Copyright (C) SugarCRM Inc. All rights reserved.
*/
({
events: {
'click [data-action=toggle]': 'toggleIsRead',
'mouseover [data-action=toggle]': 'toggleMouse',
'mouseout [data-action=toggle]': 'toggleMouse'
},
/**
* @inheritdoc
*
* The read field is always a readonly field.
*
* If `mark_as_read` option is enabled on metadata it means we should
* automatically mark the notification as read.
*
*/
initialize: function(options) {
options.def.readonly = true;
this._super('initialize', [options]);
if (options.def && options.def.mark_as_read) {
this.markAs(true);
}
},
/**
* Event handler for mouse events.
*
* @param {Event} event Mouse over / mouse out.
*/
toggleMouse: function(event) {
var $target= this.$(event.currentTarget),
isRead = this.model.get('is_read');
if (!isRead) {
return;
}
var label = event.type === 'mouseover' ? 'LBL_UNREAD' : 'LBL_READ';
$target.html(app.lang.get(label, this.module));
$target.toggleClass('label-inverse', event.type === 'mouseover');
},
/**
* Toggle notification `is_read` flag.
*/
toggleIsRead: function() {
this.markAs(!this.model.get('is_read'));
},
/**
* Mark notification as read/unread.
*
* @param {Boolean} read `True` marks notification as read, `false` as
* unread.
*/
markAs: function(read) {
if (read === this.model.get('is_read')) {
return;
}
this.model.save({is_read: !!read}, {
success: _.bind(function() {
if (!this.disposed) {
this.render();
}
}, this)
});
}
})
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebClient.PizzaWaiterTestServiceReference;
using WebClient.Models;
namespace WebClient {
/// TODO : Replace dummie
public partial class ShowMenu : System.Web.UI.Page {
/// TODO: prop proxy
IPizzaWaiterTestService proxy;
private int RestaurantID;
private static List<RestaurantMenu> restaurantMenues;
static List<PartOrder> order;
private static User user;
private static bool isLoggedIn;
protected void Page_Load(object sender, EventArgs e) {
proxy = Proxy.Get();
//If user is logged in
if (!IsPostBack) {
//setting the logged in state and set its state
SetLoginState();
RestaurantID = Convert.ToInt32(Request.QueryString["ID"]);
if (RestaurantID>0) {
restaurantMenues = proxy.GetRestaurantMenues(RestaurantID).ToList();
this.ltRestaurantTitle.Text = restaurantMenues[0].Restaurant.Name;
BindMenu();
}
order = new List<PartOrder>();
//this part should only work on login
if(isLoggedIn)
{
this.ddlAllAddresses.Visible = true;
this.ddlAllAddresses.Enabled = true;
this.txtPhoneNr.Text = user.PhoneNumber;
BindFavoritesToOrder();
BindAllAddresses();
}
}
}
protected void BindAllAddresses() {
this.ddlAllAddresses.Items.Clear();
this.ddlAllAddresses.DataTextField = "UserAddress";
this.ddlAllAddresses.DataValueField = "ID";
List<Address> addresses = proxy.GetAddressesByUserId(user.ID).ToList();
this.ddlAllAddresses.DataSource = addresses;
this.ddlAllAddresses.DataBind();
}
protected void BindMenu() {
this.rptMenu.DataSource = restaurantMenues.OrderBy(x=>x.Position);
this.rptMenu.DataBind();
}
protected string FormatMenuTitle(WebClient.PizzaWaiterTestServiceReference.Menu m) {
return m.Title;
}
protected IEnumerable<Dish> GetDishes(object item) {
RestaurantMenu rm = (RestaurantMenu)item;
List<Dish> dl = proxy.GetDishesByRestaurantMenuId(rm.ID).ToList();
return dl;
}
protected string FormatIngredientName(WebClient.PizzaWaiterTestServiceReference.Ingredient i)
{
string result = "";
if (i!=null) {
result = i.Name;
}
return i.Name;
}
protected IEnumerable<DishIngredient> GetIngredients(object item)
{
Dish di = (Dish)item;
List<DishIngredient> il = proxy.GetIngredientsByDishId(di.ID).ToList();
return il;
}
protected void blAddToOrder(object sender, CommandEventArgs e) {
//order = (List<PartOrder>)Session["order"];
int dishId = Convert.ToInt32(e.CommandArgument);
List<PartOrder> sameDishes = order.Where(x => x.Dish.ID == dishId).ToList();
if (sameDishes.Count==0) {
//add part order
this.AddPartOrder(dishId);
} else {
PartOrder unchanged = sameDishes.FirstOrDefault(x => x.CustomIngredients.Count() == 0);
if (unchanged!=null) {
unchanged.Amount++;
} else {
this.AddPartOrder(dishId);
}
// found unchanged dish in order, and new dish is unchanged => increment
// new dish is changed and a changes match is found in order => increment
// new dish is changed and a changes match is not found in order => new part order
}
this.BindOrder();
}
protected string GetDishIdFromPartOrder(object item)
{
string result = "";
PartOrder po = (PartOrder) item;
result = po.Dish.ID.ToString();
return result;
}
protected string GetDishIngredientsFromPartOrder(object item)
{
string result = "";
PartOrder po = (PartOrder) item;
return result;
}
protected void removeDishFromOrder(object sender, CommandEventArgs e) {
int dishID = Convert.ToInt32(e.CommandArgument);
List<PartOrder> match = order.Where(x => x.Dish.ID == dishID).ToList();
string ingredients = e.CommandName;
if (ingredients == "") {
PartOrder po = match.FirstOrDefault(x => x.CustomIngredients.Count() == 0);
if (po.Amount==1) {
order.Remove(po);
} else {
po.Amount--;
}
}
this.BindOrder();
}
protected void BindOrder() {
this.rptOrder.DataSource = order;
this.rptOrder.DataBind();
}
protected void AddPartOrder(int dishId) {
PartOrder po = new PartOrder();
po.Dish = proxy.GetDishById(dishId);
/// TODO: convertion to array can give trouble, solve it if occures
List<CustomIngredient> cis = new List<CustomIngredient>();
po.CustomIngredients = cis.ToArray();
po.Amount = 1;
order.Add(po);
}
protected void IncrementPartOrder() {
}
protected string CalculatePrice() {
decimal priceTotal = 0;
if (order.Count>0) {
foreach (PartOrder po in order) {
int amount = po.Amount;
decimal dishPrice = po.Dish.Price;
priceTotal += amount * dishPrice;
}
}
return String.Format("{0:0.00}", priceTotal);
}
protected string FormatPartOrder(object item) {
// po has only id.
//in order to print info need to get full object from server
PartOrder po = (PartOrder)item;
string result = string.Format("{0} - {1}x{2} kr",po.Dish.Name,po.Amount,po.Dish.Price);
return result;
}
protected void btnSubmitOrder_Click(object sender, EventArgs e) {
string phoneNr = this.txtPhoneNr.Text;
string address = this.txtAddress.Text;
if (isLoggedIn && this.ddlAllAddresses.Items.Count > 0 && address == "")
{
/// TODO: refactor into reading address ID and using it for insertion
address = this.ddlAllAddresses.SelectedItem.Text;
}
if (phoneNr!="" && address !="" && order.Count()!=0) {
if(proxy.ProcessOrder(order.ToArray(), phoneNr, address))
{
this.ltConfirmation.Text = "Order is sent";
//session favorites should de deleted since it should not show them again in the orders
Session["Favorites"] = null;
}
} else {
this.ltConfirmation.Text = "Fill up the hone number, address and the order";
}
}
protected void ibAddToFavorites_Command(object sender, CommandEventArgs e)
{
int dishID = Convert.ToInt32(e.CommandArgument);
proxy.AddFavorite(user.ID, dishID);
BindMenu();
}
protected void BindFavoritesToOrder()
{
//check if we even have a session with favorites.
if(Session["Favorites"] != null)
{
List<Favorite> favorites = (List<Favorite>)Session["Favorites"];
if (favorites.Count > 0)
{
foreach (Favorite f in favorites)
{
//This makes sure that the dish is from the restaurant.
if (f.Dish.RestaurantMenu.Restaurant.ID == RestaurantID)
{
this.AddPartOrder(f.DishID);
}
}
BindOrder();
}
}
}
protected bool ShowFavoriteButton(object stringDishID)
{
bool exists = false;
int dishID = Convert.ToInt32(stringDishID);
if (isLoggedIn)
{
Favorite userFavorites = proxy.GetFavoritesByUserID(user.ID).FirstOrDefault(x => x.DishID == dishID);
if(userFavorites != null)
{
//enable favorites button on repeater
exists = true;
}
}
return (!exists);
}
private void SetLoginState()
{
//If user is logged in
if (Globals.UserInSessionID != 0)
{
//show favorites buttons.
isLoggedIn = true;
user = proxy.GetUserByID(Globals.UserInSessionID);
}
else
{
isLoggedIn = false;
}
}
protected void txtAddress_TextChanged(object sender, EventArgs e) {
if (isLoggedIn) {
if (this.txtAddress.Text != "") {
this.ddlAllAddresses.Enabled = false;
} else {
this.ddlAllAddresses.Enabled = true;
}
}
}
}
}
|
--------------------------------------------------------------------------------------------------------------------------------------
-- Export the original FAERS current and legacy source data from the staging tables as CSV files.
-- Export the standardized data tables produced by this ETL process as CSV files.
-- Compress the CSV files to a single gzip file using: gzip -c *.csv > faersdbstats.gz
--
-- LTS Computing LLC
--------------------------------------------------------------------------------------------------------------------------------------
-- export the original FAERS current and legacy source data from the staging tables as CSV files
set search_path = faers;
-- export the legacy FAERS source data
copy demo_legacy to '/data/outbound/demo_legacy.csv' CSV header;
copy drug_legacy to '/data/outbound/drug_legacy.csv' CSV header;
copy reac_legacy to '/data/outbound/reac_legacy.csv' CSV header;
copy outc_legacy to '/data/outbound/outc_legacy.csv' CSV header;
copy rpsr_legacy to '/data/outbound/rpsr_legacy.csv' CSV header;
copy ther_legacy to '/data/outbound/ther_legacy.csv' CSV header;
copy indi_legacy to '/data/outbound/indi_legacy.csv' CSV header;
-- export the current FAERS source data
copy demo to '/data/outbound/demo.csv' CSV header;
copy drug to '/data/outbound/drug.csv' CSV header;
copy reac to '/data/outbound/reac.csv' CSV header;
copy outc to '/data/outbound/outc.csv' CSV header;
copy rpsr to '/data/outbound/rpsr.csv' CSV header;
copy ther to '/data/outbound/ther.csv' CSV header;
copy indi to '/data/outbound/indi.csv' CSV header;
-- export the standardized data tables produced by this ETL process as CSV files.
set search_path = standard;
copy standard_case_drug to '/data/outbound/standard_case_drug.csv' CSV header;
copy standard_case_indication to '/data/outbound/standard_case_indication.csv' CSV header;
copy standard_case_outcome to '/data/outbound/standard_case_outcome.csv' CSV header;
copy standard_case_outcome_category to '/data/outbound/standard_case_outcome_category.csv' CSV header;
copy standard_drug_outcome_contingency_table to '/data/outbound/standard_drug_outcome_contingency_table.csv' CSV header;
copy standard_drug_outcome_count to '/data/outbound/standard_drug_outcome_count.csv' CSV header;
copy standard_drug_outcome_statistics to '/data/outbound/standard_drug_outcome_statistics.csv' CSV header;
copy standard_unique_all_case to '/data/outbound/standard_unique_all_case.csv' CSV header;
copy standard_drug_outcome_drilldown to '/data/outbound/standard_drug_outcome_drilldown.csv' CSV header;
|
import 'dart:async';
import 'package:bouncer/bouncer.dart';
import 'package:test/test.dart';
void main() {
Future<int> fastRequest() => Future.value(3);
Future<int> slowRequest() => Future.delayed(Duration(seconds: 3), () => 3);
test('NoBouncer lets everyone in', () {
final bouncer = NoBouncer();
var completer = Completer();
var subscription = bouncer.debounce(
request: fastRequest,
responseHandler: completer.complete,
);
expect(subscription, null);
expect(completer.future, completion(equals(3)));
});
group('TimerBouncer', () {
test('it lets everyone in', () {
final bouncer = TimerBouncer(Duration.zero);
var completer = Completer();
var subscription = bouncer.debounce(
request: fastRequest,
responseHandler: completer.complete,
);
expect(subscription, isA<Subscription>());
expect(completer.future, completes);
});
test('double cancel makes no harm', () {
final bouncer = TimerBouncer(Duration.zero);
var completer = Completer();
var subscription = bouncer.debounce(
request: fastRequest,
responseHandler: completer.complete,
);
subscription.cancel();
subscription.cancel();
});
test('it allows to cancel responseHandler', () {
final bouncer = TimerBouncer(Duration.zero);
var completer = Completer();
var subscription = bouncer.debounce(
request: slowRequest,
responseHandler: completer.complete,
);
subscription.cancel();
expect(completer.future, doesNotComplete);
});
test('it actually postpones request', () {
final bouncer = TimerBouncer(Duration(seconds: 3));
var completer1 = Completer();
var completer2 = Completer();
Future<int> fastRequestThatWillNotRun() {
completer1.complete();
return Future.value(3);
}
var subscription = bouncer.debounce(
request: fastRequestThatWillNotRun,
responseHandler: completer2.complete,
);
expect(completer1.future, doesNotComplete);
expect(completer2.future, doesNotComplete);
subscription.cancel();
});
test('it cancels previous subscription', () {
final bouncer = TimerBouncer(Duration.zero);
var completer1 = Completer();
var completer2 = Completer();
var subscription = bouncer.debounce(
request: slowRequest,
responseHandler: completer1.complete,
);
bouncer.debounce(
request: slowRequest,
responseHandler: completer2.complete,
oldSubscription: subscription,
);
expect(completer1.future, doesNotComplete);
expect(completer2.future, completes);
});
});
}
|
package states
import (
"io"
"bytes"
. "github.com/Ontology/common/serialization"
"github.com/Ontology/core/code"
"github.com/Ontology/smartcontract/types"
. "github.com/Ontology/errors"
)
type ContractState struct {
StateBase
Code *code.FunctionCode
VmType types.VmType
NeedStorage bool
Name string
Version string
Author string
Email string
Description string
}
func (this *ContractState) Serialize(w io.Writer) error {
this.StateBase.Serialize(w)
err := this.Code.Serialize(w)
if err != nil {
return NewDetailErr(err, ErrNoCode, "ContractState Code Serialize failed.")
}
err = WriteByte(w, byte(this.VmType))
if err != nil {
return NewDetailErr(err, ErrNoCode, "ContractState VmType Serialize failed.")
}
err = WriteBool(w, this.NeedStorage)
if err != nil {
return NewDetailErr(err, ErrNoCode, "ContractState NeedStorage Serialize failed.")
}
err = WriteVarString(w, this.Name)
if err != nil {
return NewDetailErr(err, ErrNoCode, "ContractState Name Serialize failed.")
}
err = WriteVarString(w, this.Version)
if err != nil {
return NewDetailErr(err, ErrNoCode, "ContractState Version Serialize failed.")
}
err = WriteVarString(w, this.Author)
if err != nil {
return NewDetailErr(err, ErrNoCode, "ContractState Author Serialize failed.")
}
err = WriteVarString(w, this.Email)
if err != nil {
return NewDetailErr(err, ErrNoCode, "ContractState Email Serialize failed.")
}
err = WriteVarString(w, this.Description)
if err != nil {
return NewDetailErr(err, ErrNoCode, "ContractState Description Serialize failed.")
}
return nil
}
func (this *ContractState) Deserialize(r io.Reader) error {
if this == nil {
this = new(ContractState)
}
f := new(code.FunctionCode)
err := this.StateBase.Deserialize(r)
if err != nil {
return NewDetailErr(err, ErrNoCode, "ContractState StateBase Deserialize failed.")
}
err = f.Deserialize(r)
if err != nil {
return NewDetailErr(err, ErrNoCode, "ContractState Code Deserialize failed.")
}
this.Code = f
vmType, err := ReadByte(r)
if err != nil {
return NewDetailErr(err, ErrNoCode, "ContractState VmType Deserialize failed.")
}
this.VmType = types.VmType(vmType)
this.NeedStorage, err = ReadBool(r)
if err != nil {
return NewDetailErr(err, ErrNoCode, "ContractState NeedStorage Deserialize failed.")
}
this.Name, err = ReadVarString(r)
if err != nil {
return NewDetailErr(err, ErrNoCode, "ContractState Name Deserialize failed.")
}
this.Version, err = ReadVarString(r)
if err != nil {
return NewDetailErr(err, ErrNoCode, "ContractState Version Deserialize failed.")
}
this.Author, err = ReadVarString(r)
if err != nil {
return NewDetailErr(err, ErrNoCode, "ContractState Author Deserialize failed.")
}
this.Email, err = ReadVarString(r)
if err != nil {
return NewDetailErr(err, ErrNoCode, "ContractState Email Deserialize failed.")
}
this.Description, err = ReadVarString(r)
if err != nil {
return NewDetailErr(err, ErrNoCode, "ContractState Description Deserialize failed.")
}
return nil
}
func (contractState *ContractState) ToArray() []byte {
b := new(bytes.Buffer)
contractState.Serialize(b)
return b.Bytes()
}
|
/*
* Copyright (c) 2017 Tran Le Duy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.duy.pascal.interperter.libraries.android.utils;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import com.duy.pascal.interperter.ast.expressioncontext.ExpressionContextMixin;
import com.duy.pascal.interperter.libraries.PascalLibrary;
import com.duy.pascal.interperter.libraries.android.AndroidLibraryManager;
import com.duy.pascal.interperter.libraries.annotations.PascalMethod;
import com.duy.pascal.ui.utils.DLog;
import com.googlecode.sl4a.rpc.RpcStopEvent;
import java.lang.reflect.Field;
/**
* Exposes Batterymanager API. Note that in order to use any of the batteryGet* functions, you need
* to batteryStartMonitoring, and then wait for a "battery" event. Sleeping for a second will
* usually work just as well.
*
* @author Alexey Reznichenko (alexey.reznichenko@gmail.com)
* @author Robbie Matthews (rjmatthews62@gmail.com)
*/
public class AndroidBatteryLib extends PascalLibrary {
public static final String NAME = "aBattery".toLowerCase();
/**
* Power source is an AC charger.
*/
public static final int BATTERY_PLUGGED_AC = 1;
/**
* Power source is a USB port.
*/
public static final int BATTERY_PLUGGED_USB = 2;
private final Context mContext;
private BatteryStateListener mReceiver;
private volatile Bundle mBatteryData = null;
private volatile int mBatteryStatus = -1;
private volatile int mBatteryHealth = -1;
private volatile int mPlugType = -1;
private volatile boolean mBatteryPresent = false;
private volatile int mBatteryLevel = -1;
private volatile int mBatteryMaxLevel = -1;
private volatile int mBatteryVoltage = -1;
private volatile int mBatteryTemperature = -1;
private volatile String mBatteryTechnology = null;
public AndroidBatteryLib(AndroidLibraryManager manager) {
mContext = manager.getContext();
mReceiver = null;
mBatteryData = null;
}
private String getBatteryManagerFieldValue(String name) {
try {
Field f = BatteryManager.class.getField(name);
return f.get(null).toString();
} catch (Exception e) {
DLog.e(e);
}
return null;
}
@PascalMethod(description = "Returns the most recently recorded battery data.")
public Bundle readBatteryData() {
return mBatteryData;
}
/**
* throws "battery" events
*/
@PascalMethod(description = "Starts tracking battery state.")
public void batteryStartMonitoring() {
if (mReceiver == null) {
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_BATTERY_CHANGED);
mReceiver = new BatteryStateListener();
mContext.registerReceiver(mReceiver, filter);
}
}
@PascalMethod(description = "Stops tracking battery state.")
@RpcStopEvent("battery")
public void batteryStopMonitoring() {
if (mReceiver != null) {
mContext.unregisterReceiver(mReceiver);
mReceiver = null;
}
mBatteryData = null;
}
@Override
@PascalMethod(description = "stop")
public void onFinalize() {
batteryStopMonitoring();
}
@Override
public String getName() {
return null;
}
@Override
public void declareConstants(ExpressionContextMixin context) {
}
@Override
public void declareTypes(ExpressionContextMixin context) {
}
@Override
public void declareVariables(ExpressionContextMixin context) {
}
@Override
public void declareFunctions(ExpressionContextMixin context) {
}
@PascalMethod(description = "Returns the most recently received battery status data:" + "\n1 - unknown;"
+ "\n2 - charging;" + "\n3 - discharging;" + "\n4 - not charging;" + "\n5 - full;")
public int batteryGetStatus() {
return mBatteryStatus;
}
@PascalMethod(description = "Returns the most recently received battery health data:" + "\n1 - unknown;"
+ "\n2 - good;" + "\n3 - overheat;" + "\n4 - dead;" + "\n5 - over voltage;"
+ "\n6 - unspecified failure;")
public int batteryGetHealth() {
return mBatteryHealth;
}
@PascalMethod(description = "Returns the most recently received plug type data:" + "\n-1 - unknown"
+ "\n0 - unplugged;" + "\n1 - power source is an AC charger"
+ "\n2 - power source is a USB port")
public int batteryGetPlugType() {
return mPlugType;
}
@PascalMethod(description = "Returns the most recently received battery presence data.")
public boolean batteryCheckPresent() {
return mBatteryPresent;
}
@PascalMethod(description = "Returns the most recently received battery level (percentage).")
public int batteryGetLevel() {
if (mBatteryMaxLevel == -1 || mBatteryMaxLevel == 100 || mBatteryMaxLevel == 0) {
return mBatteryLevel;
} else {
return (int) (mBatteryLevel * 100.0 / mBatteryMaxLevel);
}
}
@PascalMethod(description = "Returns the most recently received battery voltage.")
public int batteryGetVoltage() {
return mBatteryVoltage;
}
@PascalMethod(description = "Returns the most recently received battery temperature.")
public int batteryGetTemperature() {
return mBatteryTemperature;
}
@PascalMethod(description = "Returns the most recently received battery technology data.")
public StringBuilder batteryGetTechnology() {
return new StringBuilder(mBatteryTechnology);
}
private class BatteryStateListener extends BroadcastReceiver {
private BatteryStateListener() {
}
@Override
public void onReceive(Context context, Intent intent) {
mBatteryStatus = intent.getIntExtra("status", 1);
mBatteryHealth = intent.getIntExtra("health", 1);
mPlugType = intent.getIntExtra("plugged", -1);
mBatteryPresent = intent.getBooleanExtra(getBatteryManagerFieldValue("EXTRA_PRESENT"), false);
mBatteryLevel = intent.getIntExtra(getBatteryManagerFieldValue("EXTRA_LEVEL"), -1);
mBatteryMaxLevel = intent.getIntExtra(getBatteryManagerFieldValue("EXTRA_SCALE"), 0);
mBatteryVoltage = intent.getIntExtra(getBatteryManagerFieldValue("EXTRA_VOLTAGE"), -1);
mBatteryTemperature = intent.getIntExtra(getBatteryManagerFieldValue("EXTRA_TEMPERATURE"), -1);
mBatteryTechnology = intent.getStringExtra(getBatteryManagerFieldValue("EXTRA_TECHNOLOGY"));
Bundle data = new Bundle();
data.putInt("status", mBatteryStatus);
data.putInt("health", mBatteryHealth);
data.putInt("plugged", mPlugType);
data.putBoolean("battery_present", mBatteryPresent);
if (mBatteryMaxLevel == -1 || mBatteryMaxLevel == 100 || mBatteryMaxLevel == 0) {
data.putInt("level", mBatteryLevel);
} else {
data.putInt("level", (int) (mBatteryLevel * 100.0 / mBatteryMaxLevel));
}
data.putInt("voltage", mBatteryVoltage);
data.putInt("temperature", mBatteryTemperature);
data.putString("technology", mBatteryTechnology);
mBatteryData = data;
}
}
}
|
package models
import akka.http.scaladsl.util.FastFuture._
import env.Env
import org.joda.time.DateTime
import play.api.libs.json._
import storage.BasicStore
import scala.concurrent.duration.Duration
import scala.concurrent.{ExecutionContext, Future}
import scala.util.Try
case class BackOfficeUser(randomId: String,
name: String,
email: String,
profile: JsValue,
authorizedGroup: Option[String],
simpleLogin: Boolean,
createdAt: DateTime = DateTime.now(),
expiredAt: DateTime = DateTime.now()) {
def save(duration: Duration)(implicit ec: ExecutionContext, env: Env): Future[BackOfficeUser] = {
val withDuration = this.copy(expiredAt = expiredAt.plusMillis(duration.toMillis.toInt))
env.datastores.backOfficeUserDataStore.set(withDuration, Some(duration)).fast.map(_ => withDuration)
}
def delete()(implicit ec: ExecutionContext, env: Env): Future[Boolean] =
env.datastores.backOfficeUserDataStore.delete(randomId)
def toJson: JsValue = BackOfficeUser.fmt.writes(this)
}
object BackOfficeUser {
val fmt = new Format[BackOfficeUser] {
override def reads(json: JsValue): JsResult[BackOfficeUser] =
Try {
JsSuccess(
BackOfficeUser(
randomId = (json \ "randomId").as[String],
name = (json \ "name").as[String],
email = (json \ "email").as[String],
profile = (json \ "profile").asOpt[JsValue].getOrElse(Json.obj()),
authorizedGroup = (json \ "authorizedGroup").asOpt[String],
simpleLogin = (json \ "simpleLogin").asOpt[Boolean].getOrElse(true),
createdAt = (json \ "createdAt").asOpt[Long].map(l => new DateTime(l)).getOrElse(DateTime.now()),
expiredAt = (json \ "expiredAt").asOpt[Long].map(l => new DateTime(l)).getOrElse(DateTime.now()),
)
)
} recover {
case e => JsError(e.getMessage)
} get
override def writes(o: BackOfficeUser): JsValue = Json.obj(
"randomId" -> o.randomId,
"name" -> o.name,
"email" -> o.email,
"profile" -> o.profile,
"authorizedGroup" -> o.authorizedGroup.map(JsString.apply).getOrElse(JsNull).as[JsValue],
"simpleLogin" -> o.simpleLogin,
"createdAt" -> o.createdAt.getMillis,
"expiredAt" -> o.expiredAt.getMillis,
)
}
}
trait BackOfficeUserDataStore extends BasicStore[BackOfficeUser] {
def blacklisted(email: String)(implicit ec: ExecutionContext, env: Env): Future[Boolean]
def hasAlreadyLoggedIn(email: String)(implicit ec: ExecutionContext, env: Env): Future[Boolean]
def alreadyLoggedIn(email: String)(implicit ec: ExecutionContext, env: Env): Future[Long]
def sessions()(implicit ec: ExecutionContext, env: Env): Future[Seq[JsValue]]
def discardSession(id: String)(implicit ec: ExecutionContext, env: Env): Future[Long]
def discardAllSessions()(implicit ec: ExecutionContext, env: Env): Future[Long]
}
|
package poc
import "testing"
import "gopkg.in/nowk/assert.v2"
func TestPoc(t *testing.T) {
p := New()
go p.Write([]byte("Hello World!"))
b := make([]byte, 1024)
n, err := p.Read(b)
assert.Nil(t, err)
assert.Equal(t, "Hello World!", string(b[:n]))
}
func TestReadBuffers(t *testing.T) {
p := New()
go func() {
p.Write([]byte("Hello World!"))
p.Write([]byte("Wat!"))
}()
for _, c := range []byte("Hello World!") {
b := make([]byte, 1)
n, err := p.Read(b)
assert.Nil(t, err)
assert.Equal(t, 1, n)
assert.Equal(t, string(c), string(b[:n]))
}
b := make([]byte, 1024)
n, err := p.Read(b)
assert.Nil(t, err)
assert.Equal(t, 4, n)
assert.Equal(t, "Wat!", string(b[:n]))
}
|
package s99.p01
object P01 {
def last[T](xs: List[T]): T =
xs match {
case List() => throw new NoSuchElementException("Last element in list " + xs + " does not exist")
case x :: List() => x
case _ :: t => last(t)
}
}
|
# encoding: utf-8
require File.join(File.dirname(__FILE__), 'helper')
class TestTls < MosquittoTestCase
def test_tls_set
client = Mosquitto::Client.new
assert_raises Mosquitto::Error do
client.tls_set(nil, nil, ssl_object('client.crt'), ssl_object('client.key'), nil)
end
assert_raises Mosquitto::Error do
client.tls_set(ssl_object('all-ca.crt'), ssl_path, ssl_object('client.crt'), nil, nil)
end
assert_raises Mosquitto::Error do
client.tls_set(ssl_object('all-ca.crt'), ssl_path, nil, ssl_object('client.key'), nil)
end
assert_raises TypeError do
client.tls_set(ssl_object('all-ca.crt'), ssl_path, ssl_object('client.crt'), :invalid, nil)
end
client.tls_set(ssl_object('all-ca.crt'), ssl_path, ssl_object('client.crt'), ssl_object('client.key'), nil)
end
def test_connect
connected = false
client = Mosquitto::Client.new
client.logger = Logger.new(STDOUT)
assert client.loop_start
client.on_connect do |rc|
connected = true
end
assert client.tls_opts_set(Mosquitto::SSL_VERIFY_PEER, "tlsv1.2", nil)
client.tls_set(ssl_object('test-root-ca.crt'), nil, ssl_object('client.crt'), ssl_object('client.key'), nil)
assert client.connect(TLS_TEST_HOST, TLS_TEST_PORT, TIMEOUT)
client.wait_readable && sleep(3)
assert connected
ensure
client.loop_stop(true)
end
def test_insecure
client = Mosquitto::Client.new
assert_raises TypeError do
client.tls_insecure = nil
end
assert (client.tls_insecure = true)
end
def test_tls_opts_set
client = Mosquitto::Client.new
assert_raises Mosquitto::Error do
client.tls_opts_set(3, nil, nil)
end
assert_raises TypeError do
client.tls_opts_set(Mosquitto::SSL_VERIFY_PEER, :invalid, nil)
end
assert client.tls_opts_set(Mosquitto::SSL_VERIFY_PEER, "tlsv1.2", nil)
assert client.tls_opts_set(Mosquitto::SSL_VERIFY_PEER, "tlsv1.2", nil)
end
def test_tls_psk_set
client = Mosquitto::Client.new
assert_raises TypeError do
client.tls_psk_set("deadbeef", :invalid, nil)
end
assert client.tls_psk_set("deadbeef", "psk-id", nil)
end
end
|
DROP TABLE IF EXISTS `empty`;
CREATE TABLE `empty` (
`id` INTEGER PRIMARY KEY AUTO_INCREMENT,
`space` VARCHAR(255)
);
|
unit GlassContols;
interface
uses
GlassForm,
Windows, Messages, SysUtils, Variants, Classes, Graphics;
type
TGlassContols = class (TComponent)
private
FFont: TFont;
FBrush: TBrush;
FWidth: integer;
FTop: integer;
FHeight: integer;
FLeft: integer;
procedure SetHeight(const Value: integer);
procedure SetLeft(const Value: integer);
procedure SetTop(const Value: integer);
procedure SetWidth(const Value: integer);
protected
function GlassForm:TGlassForm;
procedure do_EraseBackGround; virtual;
procedure do_Repaint; virtual;
function get_TextWidth(AText:string):integer;
function get_TextHeight(AText:string):integer;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Repaint;
published
property Font : TFont read FFont;
property Brush : TBrush read FBrush;
property Left : integer read FLeft write SetLeft;
property Top : integer read FTop write SetTop;
property Width : integer read FWidth write SetWidth;
property Height : integer read FHeight write SetHeight;
end;
implementation
type
TGlassFormCopy = class (TGlassForm)
end;
{ TGlassContols }
constructor TGlassContols.Create(AOwner: TComponent);
begin
inherited;
FFont := TFont.Create;
FBrush := TBrush.Create;
end;
destructor TGlassContols.Destroy;
begin
FreeAndNil(FFont);
FreeAndNil(FBrush);
inherited;
end;
procedure TGlassContols.do_EraseBackGround;
var
OldFont : TFont;
OldBrush : TBrush;
begin
OldFont := TFont.Create;
OldBrush := TBrush.Create;
try
OldFont.Assign(GlassForm.Bitmap.Canvas.Font);
OldBrush.Assign(GlassForm.Bitmap.Canvas.Brush);
try
GlassForm.Bitmap.Canvas.Brush.Style := bsSolid;
GlassForm.Bitmap.Canvas.Brush.Color := GlassForm.TransparentColor;
GlassForm.Bitmap.Canvas.FillRect(Rect(Left, Top, Left+Width, Top+Height));
finally
GlassForm.Bitmap.Canvas.Font.Assign(OldFont);
GlassForm.Bitmap.Canvas.Brush.Assign(OldBrush);
end;
finally
OldFont.Free;
end;
end;
procedure TGlassContols.do_Repaint;
begin
end;
function TGlassContols.get_TextHeight(AText: string): integer;
var
OldFont : TFont;
OldBrush : TBrush;
begin
OldFont := TFont.Create;
OldBrush := TBrush.Create;
try
OldFont.Assign(GlassForm.Bitmap.Canvas.Font);
OldBrush.Assign(GlassForm.Bitmap.Canvas.Brush);
try
GlassForm.Bitmap.Canvas.Font.Assign(Font);
GlassForm.Bitmap.Canvas.Brush.Assign(Brush);
Result := GlassForm.Bitmap.Canvas.TextHeight(AText);
finally
GlassForm.Bitmap.Canvas.Font.Assign(OldFont);
GlassForm.Bitmap.Canvas.Brush.Assign(OldBrush);
end;
finally
OldFont.Free;
end;
end;
function TGlassContols.get_TextWidth(AText: string): integer;
var
OldFont : TFont;
OldBrush : TBrush;
begin
OldFont := TFont.Create;
OldBrush := TBrush.Create;
try
OldFont.Assign(GlassForm.Bitmap.Canvas.Font);
OldBrush.Assign(GlassForm.Bitmap.Canvas.Brush);
try
GlassForm.Bitmap.Canvas.Font.Assign(Font);
GlassForm.Bitmap.Canvas.Brush.Assign(Brush);
Result := GlassForm.Bitmap.Canvas.TextWidth(AText);
finally
GlassForm.Bitmap.Canvas.Font.Assign(OldFont);
GlassForm.Bitmap.Canvas.Brush.Assign(OldBrush);
end;
finally
OldFont.Free;
end;
end;
function TGlassContols.GlassForm: TGlassForm;
begin
Result := Pointer(Owner);
end;
procedure TGlassContols.Repaint;
var
OldFont : TFont;
OldBrush : TBrush;
begin
OldFont := TFont.Create;
OldBrush := TBrush.Create;
try
OldFont.Assign(GlassForm.Bitmap.Canvas.Font);
OldBrush.Assign(GlassForm.Bitmap.Canvas.Brush);
try
GlassForm.Bitmap.Canvas.Font.Assign(Font);
GlassForm.Bitmap.Canvas.Brush.Assign(Brush);
do_Repaint;
TGlassFormCopy(GlassForm).FIsNeedCrystalize := true;
finally
GlassForm.Bitmap.Canvas.Font.Assign(OldFont);
GlassForm.Bitmap.Canvas.Brush.Assign(OldBrush);
end;
finally
OldFont.Free;
end;
end;
procedure TGlassContols.SetHeight(const Value: integer);
begin
FHeight := Value;
Repaint;
end;
procedure TGlassContols.SetLeft(const Value: integer);
begin
FLeft := Value;
Repaint;
end;
procedure TGlassContols.SetTop(const Value: integer);
begin
FTop := Value;
Repaint;
end;
procedure TGlassContols.SetWidth(const Value: integer);
begin
FWidth := Value;
Repaint;
end;
end.
|
###
# Class Region
#
# A Region object is a container for Areas. Regions logically segregate groups of Areas. A game server
# will usually only house one Region for its local Areas, but it is possible to define multiple Regions
# for various organizationsl purposes.
#
class Region < DMUDObject
attr_accessor :metadata
# Initialization
def initialize(
name = 'New Region',
description = ''
)
super()
# Instance Variables
@metadata = {
:name => name,
:description => description
}
@areas = []
end
# Utility: add_area
def add_area( area )
# TODO: Check for duplicates
@areas << area
return true
end
end
|
---
title: Autoboxing and Unboxing
description: Autoboxing and Unboxing
header: Autoboxing and Unboxing
tags: [Java, Autoboxing, Unboxing]
---
Autoboxing과 Unboxing은 Java 5에서 소개되었다.
## Autoboxing
기본 데이터 유형(Primitive type)을 Wrapper 클래스로 변환하는 것을 말한다. 예를 들어 int를 Integer로 변환하거나 long을 Long으로 변환하는 것이다.
## Unboxing
Wrapper 클래스의 유형을 다시 기본 데이터 유형으로 되돌려 놓는 것을 Unboxing이라 한다.
```java
import java.util.ArrayList;
import java.util.List;
public class AutoboxingUnboxing {
public static void main(String[] args) {
int i = 5;
long j = 105L;
// passed the int, will get converted to Integer object at Runtime using
// autoboxing in java
doSomething(i);
List<Long> list = new ArrayList<>();
// java autoboxing to add primitive type in collection classes
list.add(j);
}
private static void doSomething(Integer in) {
// unboxing in java, at runtime Integer.intValue() is called implicitly to
// return int
int j = in;
// java unboxing, Integer is passed where int is expected
doPrimitive(in);
}
private static void doPrimitive(int i) {
}
}
```
<br/>
| Primitive type | Wrapper class |
| --- | --- |
| boolean | Boolean |
| byte | Byte |
| char | Character |
| float | Float |
| int | Integer |
| long | Long |
| short | Short |
| double | Double |
> 참고<br/>
> https://www.journaldev.com/1005/autoboxing-java
> https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html
|
# frozen_string_literal: true
require 'simp/cli/environment/omni_env_controller'
require 'simp/cli/environment/puppet_dir_env'
require 'simp/cli/environment/secondary_dir_env'
require 'simp/cli/environment/writable_dir_env'
require 'spec_helper'
require 'yaml'
describe Simp::Cli::Environment::OmniEnvController do
OMNI_ENVIRONMENT = %i[puppet secondary writable].freeze
EXTRA_ENVIRONMENT = %i[secondary writable].freeze
subject(:described_object) { described_class.new(opts, 'foo') }
let(:opts_yaml) { File.read(File.join(__dir__, 'files/omni_env_controller_opts.yaml')) }
let(:opts) { YAML.load(opts_yaml) }
let(:opts_pup_disabled) do
opts = YAML.load(opts_yaml)
opts[:types][:puppet][:enabled] = false
opts
end
shared_examples 'it delegates to enabled Env objects' do |method, expected_envs|
let(:spies) do
{
# rubocop:disable RSpec/VerifiedDoubles
puppet: spy('puppet environment spy'),
secondary: spy('secondary environment spy'),
writable: spy('writable environment spy')
# rubocop:enable RSpec/VerifiedDoubles
}
end
before(:each) do
allow(Simp::Cli::Environment::PuppetDirEnv).to receive(:new).and_return(spies[:puppet])
allow(Simp::Cli::Environment::SecondaryDirEnv).to receive(:new).and_return(spies[:secondary])
allow(Simp::Cli::Environment::WritableDirEnv).to receive(:new).and_return(spies[:writable])
allow($stdout).to receive(:write)
end
it "calls #{method}() for enabled environments: #{expected_envs.map(&:to_s).join(', ')}" do
subject.call
spies.select { |k, _v| expected_envs.include?(k) }.each do |_env, spy|
expect(spy).to have_received(method).once
end
end
disabled_envs = OMNI_ENVIRONMENT - expected_envs
unless disabled_envs.empty?
it "does not call #{method}() for disabled environment: #{disabled_envs.join(', ')}" do
subject.call
spies.select { |k, _v| expected_envs.include?(k) }.each do |_env, spy|
expect(spy).to have_received(method).once
end
end
end
end
describe '#new' do
subject(:new) { proc { described_class.new(opts, 'foo') } }
it { expect { new.call }.not_to raise_error }
it { expect(new.call).to be_a described_class }
end
describe '#create' do
subject(:create) { proc { described_object.create } }
it_behaves_like 'it delegates to enabled Env objects', :fail_unless_createable, OMNI_ENVIRONMENT
it_behaves_like 'it delegates to enabled Env objects', :create, OMNI_ENVIRONMENT
it_behaves_like 'it delegates to enabled Env objects', :fix, EXTRA_ENVIRONMENT
context 'when the Puppet environment is not enabled' do
let(:opts) { opts_pup_disabled }
it_behaves_like 'it delegates to enabled Env objects', :fail_unless_createable, %i[secondary writable]
it_behaves_like 'it delegates to enabled Env objects', :create, %i[secondary writable]
it_behaves_like('it delegates to enabled Env objects', :fix, %i[secondary writable])
end
end
describe '#fix' do
subject(:fix) { proc { described_object.create } }
it_behaves_like 'it delegates to enabled Env objects', :fix, %i[puppet secondary writable]
context 'when the Puppet environment is not enabled' do
let(:opts) { opts_pup_disabled }
it_behaves_like('it delegates to enabled Env objects', :fix, EXTRA_ENVIRONMENT)
end
end
end
|
/** @file
Provides Mach-O parsing helper functions.
Copyright (c) 2016 - 2018, Download-Fritz. All rights reserved.<BR>
This program and the accompanying materials are licensed and made available
under the terms and conditions of the BSD License which accompanies this
distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php.
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#ifndef OC_MACHO_LIB_H
#define OC_MACHO_LIB_H
#include <IndustryStandard/AppleMachoImage.h>
///
/// Default assumed page size.
///
#define MACHO_PAGE_SIZE 4096U
///
/// Macro to align by default assumed page size.
///
#define MACHO_ALIGN(x) ALIGN_VALUE((x), MACHO_PAGE_SIZE)
///
/// Context used to refer to a Mach-O. This struct is exposed for reference
/// only. Members are not guaranteed to be sane.
///
typedef struct {
MACH_HEADER_ANY *MachHeader;
UINT32 FileSize;
UINT32 ContainerOffset;
MACH_SYMTAB_COMMAND *Symtab;
MACH_NLIST_ANY *SymbolTable;
CHAR8 *StringTable;
MACH_DYSYMTAB_COMMAND *DySymtab;
MACH_NLIST_ANY *IndirectSymbolTable;
MACH_RELOCATION_INFO *LocalRelocations;
MACH_RELOCATION_INFO *ExternRelocations;
BOOLEAN Is32Bit;
} OC_MACHO_CONTEXT;
/**
Initializes a 32-bit Mach-O Context.
@param[out] Context Mach-O Context to initialize.
@param[in] FileData Pointer to the file's expected Mach-O header.
@param[in] FileSize File size of FileData.
@param[in] ContainerOffset The amount of Bytes the Mach-O header is offset
from the base (container, e.g. KC) of the file.
@return Whether Context has been initialized successfully.
**/
BOOLEAN
MachoInitializeContext32 (
OUT OC_MACHO_CONTEXT *Context,
IN VOID *FileData,
IN UINT32 FileSize,
IN UINT32 ContainerOffset
);
/**
Initializes a 64-bit Mach-O Context.
@param[out] Context Mach-O Context to initialize.
@param[in] FileData Pointer to the file's expected Mach-O header.
@param[in] FileSize File size of FileData.
@param[in] ContainerOffset The amount of Bytes the Mach-O header is offset
from the base (container, e.g. KC) of the file.
@return Whether Context has been initialized successfully.
**/
BOOLEAN
MachoInitializeContext64 (
OUT OC_MACHO_CONTEXT *Context,
IN VOID *FileData,
IN UINT32 FileSize,
IN UINT32 ContainerOffset
);
/**
Initializes a Mach-O Context.
@param[out] Context Mach-O Context to initialize.
@param[in] FileData Pointer to the file's expected Mach-O header.
@param[in] FileSize File size of FileData.
@param[in] ContainerOffset The amount of Bytes the Mach-O header is offset
from the base (container, e.g. KC) of the file.
@param[in] Is32Bit TRUE if Mach-O is 32-bit.
@return Whether Context has been initialized successfully.
**/
BOOLEAN
MachoInitializeContext (
OUT OC_MACHO_CONTEXT *Context,
IN VOID *FileData,
IN UINT32 FileSize,
IN UINT32 ContainerOffset,
IN BOOLEAN Is32Bit
);
/**
Returns the universal Mach-O Header structure.
@param[in,out] Context Context of the Mach-O.
**/
MACH_HEADER_ANY *
MachoGetMachHeader (
IN OUT OC_MACHO_CONTEXT *Context
);
/**
Returns the 32-bit Mach-O Header structure.
@param[in,out] Context Context of the Mach-O.
**/
MACH_HEADER *
MachoGetMachHeader32 (
IN OUT OC_MACHO_CONTEXT *Context
);
/**
Returns the 64-bit Mach-O Header structure.
@param[in,out] Context Context of the Mach-O.
**/
MACH_HEADER_64 *
MachoGetMachHeader64 (
IN OUT OC_MACHO_CONTEXT *Context
);
/**
Returns the Mach-O's file size.
@param[in,out] Context Context of the Mach-O.
**/
UINT32
MachoGetFileSize (
IN OUT OC_MACHO_CONTEXT *Context
);
/**
Returns the Mach-O's virtual address space size.
@param[out] Context Context of the Mach-O.
**/
UINT32
MachoGetVmSize (
IN OUT OC_MACHO_CONTEXT *Context
);
/**
Returns the last virtual address of a Mach-O.
@param[in] Context Context of the Mach-O.
@retval 0 The binary is malformed.
**/
UINT64
MachoGetLastAddress (
IN OUT OC_MACHO_CONTEXT *Context
);
/**
Retrieves the first UUID Load Command.
@param[in,out] Context Context of the Mach-O.
@retval NULL NULL is returned on failure.
**/
MACH_UUID_COMMAND *
MachoGetUuid (
IN OUT OC_MACHO_CONTEXT *Context
);
/**
Retrieves the first segment by the name of SegmentName.
@param[in,out] Context Context of the Mach-O.
@param[in] SegmentName Segment name to search for.
@retval NULL NULL is returned on failure.
**/
MACH_SEGMENT_COMMAND_ANY *
MachoGetSegmentByName (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST CHAR8 *SegmentName
);
/**
Retrieves the first 32-bit segment by the name of SegmentName.
@param[in,out] Context Context of the Mach-O.
@param[in] SegmentName Segment name to search for.
@retval NULL NULL is returned on failure.
**/
MACH_SEGMENT_COMMAND *
MachoGetSegmentByName32 (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST CHAR8 *SegmentName
);
/**
Retrieves the first 64-bit segment by the name of SegmentName.
@param[in,out] Context Context of the Mach-O.
@param[in] SegmentName Segment name to search for.
@retval NULL NULL is returned on failure.
**/
MACH_SEGMENT_COMMAND_64 *
MachoGetSegmentByName64 (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST CHAR8 *SegmentName
);
/**
Retrieves the first section by the name of SectionName.
@param[in,out] Context Context of the Mach-O.
@param[in] Segment Segment to search in.
@param[in] SectionName Section name to search for.
@retval NULL NULL is returned on failure.
**/
MACH_SECTION_ANY *
MachoGetSectionByName (
IN OUT OC_MACHO_CONTEXT *Context,
IN MACH_SEGMENT_COMMAND_ANY *Segment,
IN CONST CHAR8 *SectionName
);
/**
Retrieves the first 32-bit section by the name of SectionName.
@param[in,out] Context Context of the Mach-O.
@param[in] Segment Segment to search in.
@param[in] SectionName Section name to search for.
@retval NULL NULL is returned on failure.
**/
MACH_SECTION *
MachoGetSectionByName32 (
IN OUT OC_MACHO_CONTEXT *Context,
IN MACH_SEGMENT_COMMAND *Segment,
IN CONST CHAR8 *SectionName
);
/**
Retrieves the first 64-bit section by the name of SectionName.
@param[in,out] Context Context of the Mach-O.
@param[in] Segment Segment to search in.
@param[in] SectionName Section name to search for.
@retval NULL NULL is returned on failure.
**/
MACH_SECTION_64 *
MachoGetSectionByName64 (
IN OUT OC_MACHO_CONTEXT *Context,
IN MACH_SEGMENT_COMMAND_64 *Segment,
IN CONST CHAR8 *SectionName
);
/**
Retrieves a section within a segment by the name of SegmentName.
@param[in,out] Context Context of the Mach-O.
@param[in] SegmentName The name of the segment to search in.
@param[in] SectionName The name of the section to search for.
@retval NULL NULL is returned on failure.
**/
MACH_SECTION_ANY *
MachoGetSegmentSectionByName (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST CHAR8 *SegmentName,
IN CONST CHAR8 *SectionName
);
/**
Retrieves a 32-bit section within a segment by the name of SegmentName.
@param[in,out] Context Context of the Mach-O.
@param[in] SegmentName The name of the segment to search in.
@param[in] SectionName The name of the section to search for.
@retval NULL NULL is returned on failure.
**/
MACH_SECTION *
MachoGetSegmentSectionByName32 (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST CHAR8 *SegmentName,
IN CONST CHAR8 *SectionName
);
/**
Retrieves a 64-bit section within a segment by the name of SegmentName.
@param[in,out] Context Context of the Mach-O.
@param[in] SegmentName The name of the segment to search in.
@param[in] SectionName The name of the section to search for.
@retval NULL NULL is returned on failure.
**/
MACH_SECTION_64 *
MachoGetSegmentSectionByName64 (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST CHAR8 *SegmentName,
IN CONST CHAR8 *SectionName
);
/**
Retrieves the next segment.
@param[in,out] Context Context of the Mach-O.
@param[in] Segment Segment to retrieve the successor of.
if NULL, the first segment is returned.
@retval NULL NULL is returned on failure.
**/
MACH_SEGMENT_COMMAND_ANY *
MachoGetNextSegment (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST MACH_SEGMENT_COMMAND_ANY *Segment OPTIONAL
);
/**
Retrieves the next 32-bit segment.
@param[in,out] Context Context of the Mach-O.
@param[in] Segment Segment to retrieve the successor of.
if NULL, the first segment is returned.
@retval NULL NULL is returned on failure.
**/
MACH_SEGMENT_COMMAND *
MachoGetNextSegment32 (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST MACH_SEGMENT_COMMAND *Segment OPTIONAL
);
/**
Retrieves the next 64-bit segment.
@param[in,out] Context Context of the Mach-O.
@param[in] Segment Segment to retrieve the successor of.
if NULL, the first segment is returned.
@retval NULL NULL is returned on failure.
**/
MACH_SEGMENT_COMMAND_64 *
MachoGetNextSegment64 (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST MACH_SEGMENT_COMMAND_64 *Segment OPTIONAL
);
/**
Retrieves the next section of a segment.
@param[in,out] Context Context of the Mach-O.
@param[in] Segment The segment to get the section of.
@param[in] Section The section to get the successor of.
@retval NULL NULL is returned on failure.
**/
MACH_SECTION_ANY *
MachoGetNextSection (
IN OUT OC_MACHO_CONTEXT *Context,
IN MACH_SEGMENT_COMMAND_ANY *Segment,
IN MACH_SECTION_ANY *Section OPTIONAL
);
/**
Retrieves the next 32-bit section of a segment.
@param[in,out] Context Context of the Mach-O.
@param[in] Segment The segment to get the section of.
@param[in] Section The section to get the successor of.
@retval NULL NULL is returned on failure.
**/
MACH_SECTION *
MachoGetNextSection32 (
IN OUT OC_MACHO_CONTEXT *Context,
IN MACH_SEGMENT_COMMAND *Segment,
IN MACH_SECTION *Section OPTIONAL
);
/**
Retrieves the next 64-bit section of a segment.
@param[in,out] Context Context of the Mach-O.
@param[in] Segment The segment to get the section of.
@param[in] Section The section to get the successor of.
@retval NULL NULL is returned on failure.
**/
MACH_SECTION_64 *
MachoGetNextSection64 (
IN OUT OC_MACHO_CONTEXT *Context,
IN MACH_SEGMENT_COMMAND_64 *Segment,
IN MACH_SECTION_64 *Section OPTIONAL
);
/**
Retrieves a section by its index.
@param[in,out] Context Context of the Mach-O.
@param[in] Index Index of the section to retrieve.
@retval NULL NULL is returned on failure.
**/
MACH_SECTION_ANY *
MachoGetSectionByIndex (
IN OUT OC_MACHO_CONTEXT *Context,
IN UINT32 Index
);
/**
Retrieves a 32-bit section by its index.
@param[in,out] Context Context of the Mach-O.
@param[in] Index Index of the section to retrieve.
@retval NULL NULL is returned on failure.
**/
MACH_SECTION *
MachoGetSectionByIndex32 (
IN OUT OC_MACHO_CONTEXT *Context,
IN UINT32 Index
);
/**
Retrieves a 64-bit section by its index.
@param[in,out] Context Context of the Mach-O.
@param[in] Index Index of the section to retrieve.
@retval NULL NULL is returned on failure.
**/
MACH_SECTION_64 *
MachoGetSectionByIndex64 (
IN OUT OC_MACHO_CONTEXT *Context,
IN UINT32 Index
);
/**
Retrieves a 32-bit section by its address.
@param[in,out] Context Context of the Mach-O.
@param[in] Address Address of the section to retrieve.
@retval NULL NULL is returned on failure.
**/
MACH_SECTION *
MachoGetSectionByAddress32 (
IN OUT OC_MACHO_CONTEXT *Context,
IN UINT32 Address
);
/**
Retrieves a 64-bit section by its address.
@param[in,out] Context Context of the Mach-O.
@param[in] Address Address of the section to retrieve.
@retval NULL NULL is returned on failure.
**/
MACH_SECTION_64 *
MachoGetSectionByAddress64 (
IN OUT OC_MACHO_CONTEXT *Context,
IN UINT64 Address
);
/**
Merge Mach-O segments into one with lowest protection.
@param[in,out] Context Context of the Mach-O.
@param[in] Prefix Segment prefix to merge.
@retval TRUE on success
**/
BOOLEAN
MachoMergeSegments (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST CHAR8 *Prefix
);
/**
Returns whether 32-bit Symbol describes a section.
@param[in] Symbol Symbol to evaluate.
**/
BOOLEAN
MachoSymbolIsSection32 (
IN CONST MACH_NLIST *Symbol
);
/**
Returns whether 64-bit Symbol describes a section.
@param[in] Symbol Symbol to evaluate.
**/
BOOLEAN
MachoSymbolIsSection64 (
IN CONST MACH_NLIST_64 *Symbol
);
/**
Returns whether Symbol is defined.
@param[in,out] Context Context of the Mach-O.
@param[in] Symbol Symbol to evaluate.
**/
BOOLEAN
MachoSymbolIsDefined (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST MACH_NLIST_ANY *Symbol
);
/**
Returns whether 32-bit Symbol is defined.
@param[in] Symbol Symbol to evaluate.
**/
BOOLEAN
MachoSymbolIsDefined32 (
IN CONST MACH_NLIST *Symbol
);
/**
Returns whether 64-bit Symbol is defined.
@param[in] Symbol Symbol to evaluate.
**/
BOOLEAN
MachoSymbolIsDefined64 (
IN CONST MACH_NLIST_64 *Symbol
);
/**
Returns whether Symbol is defined locally.
@param[in,out] Context Context of the Mach-O.
@param[in] Symbol Symbol to evaluate.
**/
BOOLEAN
MachoSymbolIsLocalDefined (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST MACH_NLIST_ANY *Symbol
);
/**
Returns whether 32-bit Symbol is defined locally.
@param[in,out] Context Context of the Mach-O.
@param[in] Symbol Symbol to evaluate.
**/
BOOLEAN
MachoSymbolIsLocalDefined32 (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST MACH_NLIST *Symbol
);
/**
Returns whether 64-bit Symbol is defined locally.
@param[in,out] Context Context of the Mach-O.
@param[in] Symbol Symbol to evaluate.
**/
BOOLEAN
MachoSymbolIsLocalDefined64 (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST MACH_NLIST_64 *Symbol
);
/**
Retrieves a locally defined symbol by its name.
@param[in] Context Context of the Mach-O.
@param[in] Name Name of the symbol to locate.
**/
MACH_NLIST_ANY *
MachoGetLocalDefinedSymbolByName (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST CHAR8 *Name
);
/**
Retrieves a locally defined 32-bit symbol by its name.
@param[in] Context Context of the Mach-O.
@param[in] Name Name of the symbol to locate.
**/
MACH_NLIST *
MachoGetLocalDefinedSymbolByName32 (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST CHAR8 *Name
);
/**
Retrieves a locally defined 64-bit symbol by its name.
@param[in] Context Context of the Mach-O.
@param[in] Name Name of the symbol to locate.
**/
MACH_NLIST_64 *
MachoGetLocalDefinedSymbolByName64 (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST CHAR8 *Name
);
/**
Retrieves a symbol by its index.
@param[in] Context Context of the Mach-O.
@param[in] Index Index of the symbol to locate.
@retval NULL NULL is returned on failure.
**/
MACH_NLIST_ANY *
MachoGetSymbolByIndex (
IN OUT OC_MACHO_CONTEXT *Context,
IN UINT32 Index
);
/**
Retrieves a 32-bit symbol by its index.
@param[in] Context Context of the Mach-O.
@param[in] Index Index of the symbol to locate.
@retval NULL NULL is returned on failure.
**/
MACH_NLIST *
MachoGetSymbolByIndex32 (
IN OUT OC_MACHO_CONTEXT *Context,
IN UINT32 Index
);
/**
Retrieves a 64-bit symbol by its index.
@param[in] Context Context of the Mach-O.
@param[in] Index Index of the symbol to locate.
@retval NULL NULL is returned on failure.
**/
MACH_NLIST_64 *
MachoGetSymbolByIndex64 (
IN OUT OC_MACHO_CONTEXT *Context,
IN UINT32 Index
);
/**
Retrieves a Symbol's name.
@param[in,out] Context Context of the Mach-O.
@param[in] Symbol Symbol to retrieve the name of.
@retval symbol name.
**/
CONST CHAR8 *
MachoGetSymbolName (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST MACH_NLIST_ANY *Symbol
);
/**
Retrieves a 32-bit Symbol's name.
@param[in,out] Context Context of the Mach-O.
@param[in] Symbol Symbol to retrieve the name of.
@retval symbol name.
**/
CONST CHAR8 *
MachoGetSymbolName32 (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST MACH_NLIST *Symbol
);
/**
Retrieves a 64-bit Symbol's name.
@param[in,out] Context Context of the Mach-O.
@param[in] Symbol Symbol to retrieve the name of.
@retval symbol name.
**/
CONST CHAR8 *
MachoGetSymbolName64 (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST MACH_NLIST_64 *Symbol
);
/**
Retrieves a Symbol's name.
@param[in,out] Context Context of the Mach-O.
@param[in] Symbol Indirect symbol to retrieve the name of.
@retval NULL NULL is returned on failure.
**/
CONST CHAR8 *
MachoGetIndirectSymbolName (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST MACH_NLIST_ANY *Symbol
);
/**
Retrieves a 32-bit Symbol's name.
@param[in,out] Context Context of the Mach-O.
@param[in] Symbol Indirect symbol to retrieve the name of.
@retval NULL NULL is returned on failure.
**/
CONST CHAR8 *
MachoGetIndirectSymbolName32 (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST MACH_NLIST *Symbol
);
/**
Retrieves a 64-bit Symbol's name.
@param[in,out] Context Context of the Mach-O.
@param[in] Symbol Indirect symbol to retrieve the name of.
@retval NULL NULL is returned on failure.
**/
CONST CHAR8 *
MachoGetIndirectSymbolName64 (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST MACH_NLIST_64 *Symbol
);
/**
Returns whether the symbol's value is a valid address within the Mach-O
referenced to by Context.
@param[in,out] Context Context of the Mach-O.
@param[in] Symbol Symbol to verify the value of.
**/
BOOLEAN
MachoIsSymbolValueInRange (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST MACH_NLIST_ANY *Symbol
);
/**
Returns whether the 32-bit symbol's value is a valid address within the Mach-O
referenced to by Context.
@param[in,out] Context Context of the Mach-O.
@param[in] Symbol Symbol to verify the value of.
**/
BOOLEAN
MachoIsSymbolValueInRange32 (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST MACH_NLIST *Symbol
);
/**
Returns whether the 64-bit symbol's value is a valid address within the Mach-O
referenced to by Context.
@param[in,out] Context Context of the Mach-O.
@param[in] Symbol Symbol to verify the value of.
**/
BOOLEAN
MachoIsSymbolValueInRange64 (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST MACH_NLIST_64 *Symbol
);
/**
Retrieves the 32-bit symbol referenced by the Relocation targeting Address.
@param[in,out] Context Context of the Mach-O.
@param[in] Address Address to search for.
@param[out] Symbol Buffer to output the symbol referenced by the
Relocation into. The output is undefined when FALSE
is returned. May be NULL.
@returns Whether the Relocation exists.
**/
BOOLEAN
MachoGetSymbolByRelocationOffset32 (
IN OUT OC_MACHO_CONTEXT *Context,
IN UINT32 Address,
OUT MACH_NLIST **Symbol
);
/**
Retrieves the 64-bit symbol referenced by the Relocation targeting Address.
@param[in,out] Context Context of the Mach-O.
@param[in] Address Address to search for.
@param[out] Symbol Buffer to output the symbol referenced by the
Relocation into. The output is undefined when FALSE
is returned. May be NULL.
@returns Whether the Relocation exists.
**/
BOOLEAN
MachoGetSymbolByRelocationOffset64 (
IN OUT OC_MACHO_CONTEXT *Context,
IN UINT64 Address,
OUT MACH_NLIST_64 **Symbol
);
/**
Retrieves the symbol referenced by the extern Relocation targeting Address.
@param[in,out] Context Context of the Mach-O.
@param[in] Address Address to search for.
@param[out] Symbol Buffer to output the symbol referenced by the
Relocation into. The output is undefined when FALSE
is returned. May be NULL.
@returns Whether the Relocation exists.
**/
BOOLEAN
MachoGetSymbolByExternRelocationOffset (
IN OUT OC_MACHO_CONTEXT *Context,
IN UINT64 Address,
OUT MACH_NLIST_ANY **Symbol
);
/**
Retrieves the 32-bit symbol referenced by the extern Relocation targeting Address.
@param[in,out] Context Context of the Mach-O.
@param[in] Address Address to search for.
@param[out] Symbol Buffer to output the symbol referenced by the
Relocation into. The output is undefined when FALSE
is returned. May be NULL.
@returns Whether the Relocation exists.
**/
BOOLEAN
MachoGetSymbolByExternRelocationOffset32 (
IN OUT OC_MACHO_CONTEXT *Context,
IN UINT32 Address,
OUT MACH_NLIST **Symbol
);
/**
Retrieves the 64-bit symbol referenced by the extern Relocation targeting Address.
@param[in,out] Context Context of the Mach-O.
@param[in] Address Address to search for.
@param[out] Symbol Buffer to output the symbol referenced by the
Relocation into. The output is undefined when FALSE
is returned. May be NULL.
@returns Whether the Relocation exists.
**/
BOOLEAN
MachoGetSymbolByExternRelocationOffset64 (
IN OUT OC_MACHO_CONTEXT *Context,
IN UINT64 Address,
OUT MACH_NLIST_64 **Symbol
);
/**
Relocate Symbol to be against LinkAddress.
@param[in,out] Context Context of the Mach-O.
@param[in] LinkAddress The address to be linked against.
@param[in,out] Symbol The symbol to be relocated.
@returns Whether the operation has been completed successfully.
**/
BOOLEAN
MachoRelocateSymbol (
IN OUT OC_MACHO_CONTEXT *Context,
IN UINT64 LinkAddress,
IN OUT MACH_NLIST_ANY *Symbol
);
/**
Relocate 32-bit Symbol to be against LinkAddress.
@param[in,out] Context Context of the Mach-O.
@param[in] LinkAddress The address to be linked against.
@param[in,out] Symbol The symbol to be relocated.
@returns Whether the operation has been completed successfully.
**/
BOOLEAN
MachoRelocateSymbol32 (
IN OUT OC_MACHO_CONTEXT *Context,
IN UINT32 LinkAddress,
IN OUT MACH_NLIST *Symbol
);
/**
Relocate 64-bit Symbol to be against LinkAddress.
@param[in,out] Context Context of the Mach-O.
@param[in] LinkAddress The address to be linked against.
@param[in,out] Symbol The symbol to be relocated.
@returns Whether the operation has been completed successfully.
**/
BOOLEAN
MachoRelocateSymbol64 (
IN OUT OC_MACHO_CONTEXT *Context,
IN UINT64 LinkAddress,
IN OUT MACH_NLIST_64 *Symbol
);
/**
Retrieves the Mach-O file offset of the address pointed to by a 32-bit Symbol.
@param[in,out] Context Context of the Mach-O.
@param[in] Symbol Symbol to retrieve the offset of.
@param[out] FileOffset Pointer the file offset is returned into.
If FALSE is returned, the output is undefined.
@param[out] MaxSize Maximum data safely available from FileOffset.
@retval 0 0 is returned on failure.
**/
BOOLEAN
MachoSymbolGetFileOffset32 (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST MACH_NLIST *Symbol,
OUT UINT32 *FileOffset,
OUT UINT32 *MaxSize OPTIONAL
);
/**
Retrieves the Mach-O file offset of the address pointed to by a 64-bit Symbol.
@param[in,out] Context Context of the Mach-O.
@param[in] Symbol Symbol to retrieve the offset of.
@param[out] FileOffset Pointer the file offset is returned into.
If FALSE is returned, the output is undefined.
@param[out] MaxSize Maximum data safely available from FileOffset.
@retval 0 0 is returned on failure.
**/
BOOLEAN
MachoSymbolGetFileOffset64 (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST MACH_NLIST_64 *Symbol,
OUT UINT32 *FileOffset,
OUT UINT32 *MaxSize OPTIONAL
);
/**
Retrieves the Mach-O file offset of the address pointed to by a Symbol.
@param[in,out] Context Context of the Mach-O.
@param[in] Symbol Symbol to retrieve the offset of.
@param[out] FileOffset Pointer the file offset is returned into.
If FALSE is returned, the output is undefined.
@param[out] MaxSize Maximum data safely available from FileOffset.
@retval 0 0 is returned on failure.
**/
BOOLEAN
MachoSymbolGetFileOffset (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST MACH_NLIST_ANY *Symbol,
OUT UINT32 *FileOffset,
OUT UINT32 *MaxSize OPTIONAL
);
/**
Retrieves the Mach-O file offset of the address pointed to by a Symbol.
@param[in,out] Context Context of the Mach-O.
@param[in] Address Virtual address to retrieve the offset of.
@param[out] FileOffset Pointer the file offset is returned into.
If FALSE is returned, the output is undefined.
@param[out] MaxSize Maximum data safely available from FileOffset.
@retval 0 0 is returned on failure.
**/
BOOLEAN
MachoSymbolGetDirectFileOffset (
IN OUT OC_MACHO_CONTEXT *Context,
IN UINT64 Address,
OUT UINT32 *FileOffset,
OUT UINT32 *MaxSize OPTIONAL
);
/**
Returns whether Name is pure virtual.
@param[in] Name The name to evaluate.
**/
BOOLEAN
MachoSymbolNameIsPureVirtual (
IN CONST CHAR8 *Name
);
/**
Returns whether Name is a Padslot.
@param[in] Name The name to evaluate.
**/
BOOLEAN
MachoSymbolNameIsPadslot (
IN CONST CHAR8 *Name
);
/**
Returns whether SymbolName defines a Super Metaclass Pointer.
@param[in,out] Context Context of the Mach-O.
@param[in] SymbolName The symbol name to check.
**/
BOOLEAN
MachoSymbolNameIsSmcp (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST CHAR8 *SymbolName
);
/**
Returns whether SymbolName defines a Super Metaclass Pointer.
@param[in,out] Context Context of the Mach-O.
@param[in] SymbolName The symbol name to check.
**/
BOOLEAN
MachoSymbolNameIsMetaclassPointer (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST CHAR8 *SymbolName
);
/**
Retrieves the class name of a Super Meta Class Pointer.
@param[in,out] Context Context of the Mach-O.
@param[in] SmcpName SMCP Symbol name to get the class name of.
@param[in] ClassNameSize The size of ClassName.
@param[out] ClassName The output buffer for the class name.
@returns Whether the name has been retrieved successfully.
**/
BOOLEAN
MachoGetClassNameFromSuperMetaClassPointer (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST CHAR8 *SmcpName,
IN UINTN ClassNameSize,
OUT CHAR8 *ClassName
);
/**
Retrieves the class name of a VTable.
@param[out] VtableName The VTable's name.
**/
CONST CHAR8 *
MachoGetClassNameFromVtableName (
IN CONST CHAR8 *VtableName
);
/**
Retrieves the function prefix of a class name.
@param[in] ClassName The class name to evaluate.
@param[in] FunctionPrefixSize The size of FunctionPrefix.
@param[out] FunctionPrefix The output buffer for the function prefix.
@returns Whether the name has been retrieved successfully.
**/
BOOLEAN
MachoGetFunctionPrefixFromClassName (
IN CONST CHAR8 *ClassName,
IN UINTN FunctionPrefixSize,
OUT CHAR8 *FunctionPrefix
);
/**
Retrieves the class name of a Meta Class Pointer.
@param[in,out] Context Context of the Mach-O.
@param[in] MetaClassName MCP Symbol name to get the class name of.
@param[in] ClassNameSize The size of ClassName.
@param[out] ClassName The output buffer for the class name.
@returns Whether the name has been retrieved successfully.
**/
BOOLEAN
MachoGetClassNameFromMetaClassPointer (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST CHAR8 *MetaClassName,
IN UINTN ClassNameSize,
OUT CHAR8 *ClassName
);
/**
Retrieves the VTable name of a class name.
@param[in] ClassName Class name to get the VTable name of.
@param[in] VtableNameSize The size of VtableName.
@param[out] VtableName The output buffer for the VTable name.
@returns Whether the name has been retrieved successfully.
**/
BOOLEAN
MachoGetVtableNameFromClassName (
IN CONST CHAR8 *ClassName,
IN UINTN VtableNameSize,
OUT CHAR8 *VtableName
);
/**
Retrieves the Meta VTable name of a class name.
@param[in] ClassName Class name to get the Meta VTable name of.
@param[in] VtableNameSize The size of VtableName.
@param[out] VtableName The output buffer for the VTable name.
@returns Whether the name has been retrieved successfully.
**/
BOOLEAN
MachoGetMetaVtableNameFromClassName (
IN CONST CHAR8 *ClassName,
IN UINTN VtableNameSize,
OUT CHAR8 *VtableName
);
/**
Retrieves the final symbol name of a class name.
@param[in] ClassName Class name to get the final symbol name of.
@param[in] FinalSymbolNameSize The size of FinalSymbolName.
@param[out] FinalSymbolName The output buffer for the final symbol name.
@returns Whether the name has been retrieved successfully.
**/
BOOLEAN
MachoGetFinalSymbolNameFromClassName (
IN CONST CHAR8 *ClassName,
IN UINTN FinalSymbolNameSize,
OUT CHAR8 *FinalSymbolName
);
/**
Returns whether SymbolName defines a VTable.
@param[in] SymbolName The symbol name to check.
**/
BOOLEAN
MachoSymbolNameIsVtable (
IN CONST CHAR8 *SymbolName
);
/**
Returns whether the symbol name describes a C++ symbol.
@param[in] Name The name to evaluate.
**/
BOOLEAN
MachoSymbolNameIsCxx (
IN CONST CHAR8 *Name
);
/**
Retrieves Metaclass symbol of a SMCP.
@param[in,out] Context Context of the Mach-O.
@param[in] Smcp The SMCP to evaluate.
@retval NULL NULL is returned on failure.
**/
MACH_NLIST_ANY *
MachoGetMetaclassSymbolFromSmcpSymbol (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST MACH_NLIST_ANY *Smcp
);
/**
Retrieves 32-bit Metaclass symbol of a SMCP.
@param[in,out] Context Context of the Mach-O.
@param[in] Smcp The SMCP to evaluate.
@retval NULL NULL is returned on failure.
**/
MACH_NLIST *
MachoGetMetaclassSymbolFromSmcpSymbol32 (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST MACH_NLIST *Smcp
);
/**
Retrieves 64-bit Metaclass symbol of a SMCP.
@param[in,out] Context Context of the Mach-O.
@param[in] Smcp The SMCP to evaluate.
@retval NULL NULL is returned on failure.
**/
MACH_NLIST_64 *
MachoGetMetaclassSymbolFromSmcpSymbol64 (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST MACH_NLIST_64 *Smcp
);
/**
Retrieves VTable and Meta VTable of a SMCP.
Logically matches XNU's get_vtable_syms_from_smcp.
@param[in,out] Context Context of the Mach-O.
@param[in] SmcpName SMCP Symbol mame to retrieve the VTables from.
@param[out] Vtable Output buffer for the VTable symbol pointer.
@param[out] MetaVtable Output buffer for the Meta VTable symbol pointer.
**/
BOOLEAN
MachoGetVtableSymbolsFromSmcp (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST CHAR8 *SmcpName,
OUT CONST MACH_NLIST_ANY **Vtable,
OUT CONST MACH_NLIST_ANY **MetaVtable
);
/**
Retrieves 32-bit VTable and Meta VTable of a SMCP.
Logically matches XNU's get_vtable_syms_from_smcp.
@param[in,out] Context Context of the Mach-O.
@param[in] SmcpName SMCP Symbol mame to retrieve the VTables from.
@param[out] Vtable Output buffer for the VTable symbol pointer.
@param[out] MetaVtable Output buffer for the Meta VTable symbol pointer.
**/
BOOLEAN
MachoGetVtableSymbolsFromSmcp32 (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST CHAR8 *SmcpName,
OUT CONST MACH_NLIST **Vtable,
OUT CONST MACH_NLIST **MetaVtable
);
/**
Retrieves 64-bit VTable and Meta VTable of a SMCP.
Logically matches XNU's get_vtable_syms_from_smcp.
@param[in,out] Context Context of the Mach-O.
@param[in] SmcpName SMCP Symbol mame to retrieve the VTables from.
@param[out] Vtable Output buffer for the VTable symbol pointer.
@param[out] MetaVtable Output buffer for the Meta VTable symbol pointer.
**/
BOOLEAN
MachoGetVtableSymbolsFromSmcp64 (
IN OUT OC_MACHO_CONTEXT *Context,
IN CONST CHAR8 *SmcpName,
OUT CONST MACH_NLIST_64 **Vtable,
OUT CONST MACH_NLIST_64 **MetaVtable
);
/**
Returns whether the Relocation's type indicates a Pair for the Intel 32
platform.
@param[in] Type The Relocation's type to verify.
**/
BOOLEAN
MachoRelocationIsPairIntel32 (
IN UINT8 Type
);
/**
Returns whether the Relocation's type indicates a Pair for the Intel 64
platform.
@param[in] Type The Relocation's type to verify.
**/
BOOLEAN
MachoRelocationIsPairIntel64 (
IN UINT8 Type
);
/**
Returns whether the Relocation's type matches a Pair's for the Intel 64
platform.
@param[in] Type The Relocation's type to verify.
**/
BOOLEAN
MachoIsRelocationPairTypeIntel64 (
IN UINT8 Type
);
/**
Returns whether the Relocation shall be preserved for the Intel 64 platform.
@param[in] Type The Relocation's type to verify.
**/
BOOLEAN
MachoPreserveRelocationIntel64 (
IN UINT8 Type
);
/*
Initialises Context with the symbol tables of SymsContext.
@param[in,out] Context The context to initialise the symbol info of.
@param[in] SymsContext The context to retrieve the symbol tables from.
@returns Whether the operation was successful.
*/
BOOLEAN
MachoInitialiseSymtabsExternal (
IN OUT OC_MACHO_CONTEXT *Context,
IN OC_MACHO_CONTEXT *SymsContext
);
/**
Obtain symbol tables.
@param[in] Context Context of the Mach-O.
@param[out] SymbolTable Symbol table.
@param[out] StringTable String table for that symbol table.
@param[out] LocalSymbols Local symbol table.
@param[out] NumLocalSymbols Number of symbols in local symbol table.
@param[out] ExternalSymbols External symbol table.
@param[out] NumExternalSymbols Number of symbols in external symbol table.
@param[out] UndefinedSymbols Undefined symbol table.
@param[out] NumUndefinedSymbols Number of symbols in undefined symbol table.
@return number of symbols in symbol table or 0.
**/
UINT32
MachoGetSymbolTable (
IN OUT OC_MACHO_CONTEXT *Context,
OUT CONST MACH_NLIST_ANY **SymbolTable,
OUT CONST CHAR8 **StringTable OPTIONAL,
OUT CONST MACH_NLIST_ANY **LocalSymbols OPTIONAL,
OUT UINT32 *NumLocalSymbols OPTIONAL,
OUT CONST MACH_NLIST_ANY **ExternalSymbols OPTIONAL,
OUT UINT32 *NumExternalSymbols OPTIONAL,
OUT CONST MACH_NLIST_ANY **UndefinedSymbols OPTIONAL,
OUT UINT32 *NumUndefinedSymbols OPTIONAL
);
/**
Obtain 32-bit symbol tables.
@param[in] Context Context of the Mach-O.
@param[out] SymbolTable Symbol table.
@param[out] StringTable String table for that symbol table.
@param[out] LocalSymbols Local symbol table.
@param[out] NumLocalSymbols Number of symbols in local symbol table.
@param[out] ExternalSymbols External symbol table.
@param[out] NumExternalSymbols Number of symbols in external symbol table.
@param[out] UndefinedSymbols Undefined symbol table.
@param[out] NumUndefinedSymbols Number of symbols in undefined symbol table.
@return number of symbols in symbol table or 0.
**/
UINT32
MachoGetSymbolTable32 (
IN OUT OC_MACHO_CONTEXT *Context,
OUT CONST MACH_NLIST **SymbolTable,
OUT CONST CHAR8 **StringTable OPTIONAL,
OUT CONST MACH_NLIST **LocalSymbols OPTIONAL,
OUT UINT32 *NumLocalSymbols OPTIONAL,
OUT CONST MACH_NLIST **ExternalSymbols OPTIONAL,
OUT UINT32 *NumExternalSymbols OPTIONAL,
OUT CONST MACH_NLIST **UndefinedSymbols OPTIONAL,
OUT UINT32 *NumUndefinedSymbols OPTIONAL
);
/**
Obtain 64-bit symbol tables.
@param[in] Context Context of the Mach-O.
@param[out] SymbolTable Symbol table.
@param[out] StringTable String table for that symbol table.
@param[out] LocalSymbols Local symbol table.
@param[out] NumLocalSymbols Number of symbols in local symbol table.
@param[out] ExternalSymbols External symbol table.
@param[out] NumExternalSymbols Number of symbols in external symbol table.
@param[out] UndefinedSymbols Undefined symbol table.
@param[out] NumUndefinedSymbols Number of symbols in undefined symbol table.
@return number of symbols in symbol table or 0.
**/
UINT32
MachoGetSymbolTable64 (
IN OUT OC_MACHO_CONTEXT *Context,
OUT CONST MACH_NLIST_64 **SymbolTable,
OUT CONST CHAR8 **StringTable OPTIONAL,
OUT CONST MACH_NLIST_64 **LocalSymbols OPTIONAL,
OUT UINT32 *NumLocalSymbols OPTIONAL,
OUT CONST MACH_NLIST_64 **ExternalSymbols OPTIONAL,
OUT UINT32 *NumExternalSymbols OPTIONAL,
OUT CONST MACH_NLIST_64 **UndefinedSymbols OPTIONAL,
OUT UINT32 *NumUndefinedSymbols OPTIONAL
);
/**
Obtain indirect symbol table.
@param[in] Context Context of the Mach-O.
@param[in,out] SymbolTable Indirect symbol table.
@return number of symbols in indirect symbol table or 0.
**/
UINT32
MachoGetIndirectSymbolTable (
IN OUT OC_MACHO_CONTEXT *Context,
OUT CONST MACH_NLIST_ANY **SymbolTable
);
/**
Obtain indirect 32-bit symbol table.
@param[in] Context Context of the Mach-O.
@param[in,out] SymbolTable Indirect symbol table.
@return number of symbols in indirect symbol table or 0.
**/
UINT32
MachoGetIndirectSymbolTable32 (
IN OUT OC_MACHO_CONTEXT *Context,
OUT CONST MACH_NLIST **SymbolTable
);
/**
Obtain indirect 64-bit symbol table.
@param[in] Context Context of the Mach-O.
@param[in,out] SymbolTable Indirect symbol table.
@return number of symbols in indirect symbol table or 0.
**/
UINT32
MachoGetIndirectSymbolTable64 (
IN OUT OC_MACHO_CONTEXT *Context,
OUT CONST MACH_NLIST_64 **SymbolTable
);
/**
Returns a pointer to the Mach-O file at the specified virtual address.
@param[in,out] Context Context of the Mach-O.
@param[in] Address Virtual address to look up.
@param[out] MaxSize Maximum data safely available from FileOffset.
If NULL is returned, the output is undefined.
**/
VOID *
MachoGetFilePointerByAddress (
IN OUT OC_MACHO_CONTEXT *Context,
IN UINT64 Address,
OUT UINT32 *MaxSize OPTIONAL
);
/**
Expand Mach-O image to Destination (make segment file sizes equal to vm sizes).
@param[in] Context Context of the Mach-O.
@param[out] Destination Output buffer.
@param[in] DestinationSize Output buffer maximum size.
@param[in] Strip Output with stripped prelink commands.
@param[in] FileOffset Pointer to the file offset of the first segment.
@returns New image size or 0 on failure.
**/
UINT32
MachoExpandImage (
IN OC_MACHO_CONTEXT *Context,
OUT UINT8 *Destination,
IN UINT32 DestinationSize,
IN BOOLEAN Strip,
OUT UINT64 *FileOffset OPTIONAL
);
/**
Calculates size required for expanded Mach-O image using MachoExpandImage().
@param[in] Context Context of the Mach-O.
@returns New image size or 0 on failure.
**/
UINT32
MachoGetExpandedImageSize (
IN OC_MACHO_CONTEXT *Context
);
/**
Find Mach-O entry point from LC_UNIXTHREAD loader command.
This command does not verify Mach-O and assumes it is valid.
@param[in] Image Loaded Mach-O image.
@returns Entry point or 0.
**/
UINT64
MachoRuntimeGetEntryAddress (
IN VOID *Image
);
/**
Retrieves the next Load Command of type LoadCommandType.
@param[in,out] Context Context of the Mach-O.
@param[in] LoadCommandType Type of the Load Command to retrieve.
@param[in] LoadCommand Previous Load Command.
If NULL, the first match is returned.
@retval NULL NULL is returned on failure.
**/
MACH_LOAD_COMMAND *
MachoGetNextCommand (
IN OUT OC_MACHO_CONTEXT *Context,
IN MACH_LOAD_COMMAND_TYPE LoadCommandType,
IN CONST MACH_LOAD_COMMAND *LoadCommand OPTIONAL
);
/**
Returns offset and size of specified slice in case
FAT Mach-O is used. If no FAT is detected, FatOffset and
FatSize are set to 0 and FullSize respectively.
@param[in] Buffer Pointer to the buffer data.
@param[in] BufferSize Size of Buffer.
@param[in] FullSize Full file size, used to validate sizes
within FAT structure.
@param[in] CpuType Desired CPU slice to use.
@param[out] FatOffset Pointer to offset of FAT slice.
@param[out] FatSize Pointer to size of FAT slice.
@return EFI_SUCCESS if no FAT, or arch was found in valid FAT image.
**/
EFI_STATUS
FatGetArchitectureOffset (
IN CONST UINT8 *Buffer,
IN UINT32 BufferSize,
IN UINT32 FullSize,
IN MACH_CPU_TYPE CpuType,
OUT UINT32 *FatOffset,
OUT UINT32 *FatSize
);
/**
Moves file pointer and size to point to specified slice in case
FAT Mach-O is used.
@param[in,out] FileData Pointer to pointer of the file's data.
@param[in,out] FileSize Pointer to file size of FileData.
@param[in] CpuType Desired CPU slice to use.
@return EFI_SUCCESS if no FAT, or arch was found in valid FAT image.
**/
EFI_STATUS
FatFilterArchitectureByType (
IN OUT UINT8 **FileData,
IN OUT UINT32 *FileSize,
IN MACH_CPU_TYPE CpuType
);
/**
Moves file pointer and size to point to x86 slice in case
FAT Mach-O is used.
@param[in,out] FileData Pointer to pointer of the file's data.
@param[in,out] FileSize Pointer to file size of FileData.
@return EFI_SUCCESS if no FAT, or a valid 32-bit arch exists.
**/
EFI_STATUS
FatFilterArchitecture32 (
IN OUT UINT8 **FileData,
IN OUT UINT32 *FileSize
);
/**
Moves file pointer and size to point to x86_64 slice in case
FAT Mach-O is used.
@param[in,out] FileData Pointer to pointer of the file's data.
@param[in,out] FileSize Pointer to file size of FileData.
@return EFI_SUCCESS if no FAT, or a valid 64-bit arch exists.
**/
EFI_STATUS
FatFilterArchitecture64 (
IN OUT UINT8 **FileData,
IN OUT UINT32 *FileSize
);
#endif // OC_MACHO_LIB_H
|
<?php
namespace content_cms\visitor\chart;
class view
{
public static function config()
{
$myTitle = T_("Visitor chart");
$myDesc = T_('Check list of visitor and search or filter in them to find your visitor.');
\dash\data::page_title($myTitle);
\dash\data::page_desc($myDesc);
$args = [];
if(\dash\request::get('period'))
{
$args['period'] = \dash\request::get('period');
}
$file = 'chart';
if(\dash\request::get('type'))
{
$args['type'] = \dash\request::get('type');
$file = $args['type'];
}
$chart_detail = [];
$chart_detail['data'] = \dash\app\visitor::chart($args);
$chart_detail['file'] = 'content_cms/visitor/chart/'. $file. '.js';
\dash\data::chartDetail($chart_detail);
}
}
?>
|
import net.runelite.mapping.ObfuscatedGetter;
import net.runelite.mapping.ObfuscatedName;
import net.runelite.mapping.ObfuscatedSignature;
import net.runelite.rs.ScriptOpcodes;
@ObfuscatedName("dw")
public class class120 extends DualNode {
@ObfuscatedName("c")
@ObfuscatedGetter(
intValue = 1678979845
)
int field1471;
@ObfuscatedName("l")
@ObfuscatedSignature(
descriptor = "[[Ldt;"
)
public class115[][] field1470;
@ObfuscatedName("s")
@ObfuscatedSignature(
descriptor = "[[Ldt;"
)
class115[][] field1472;
@ObfuscatedName("e")
@ObfuscatedGetter(
intValue = -1072517793
)
int field1473;
@ObfuscatedName("r")
@ObfuscatedGetter(
intValue = -1031841031
)
int field1474;
@ObfuscatedName("o")
@ObfuscatedSignature(
descriptor = "Lgs;"
)
public Skeleton field1478;
@ObfuscatedName("i")
@ObfuscatedGetter(
intValue = 1707817163
)
int field1476;
@ObfuscatedName("w")
boolean field1475;
@ObfuscatedSignature(
descriptor = "(Lkq;Lkq;IZ)V",
garbageValue = "0"
)
public class120(AbstractArchive var1, AbstractArchive var2, int var3, boolean var4) {
this.field1470 = null;
this.field1472 = null;
this.field1476 = 0;
this.field1471 = var3;
byte[] var5 = var1.takeFile(this.field1471 >> 16 & 65535, this.field1471 & 65535);
Buffer var6 = new Buffer(var5);
int var7 = var6.readUnsignedByte();
int var8 = var6.readUnsignedShort();
byte[] var9 = var2.getFile(var8, 0);
this.field1478 = new Skeleton(var8, var9);
this.method2660(var6, var7);
}
@ObfuscatedName("c")
@ObfuscatedSignature(
descriptor = "(Lpi;IB)V",
garbageValue = "79"
)
void method2660(Buffer var1, int var2) {
this.field1473 = var1.readUnsignedShort();
this.field1474 = var1.readUnsignedShort();
this.field1476 = var1.readUnsignedByte();
int var3 = var1.readUnsignedShort();
this.field1472 = new class115[this.field1478.method3887().method3871()][];
this.field1470 = new class115[this.field1478.method3886()][];
for (int var4 = 0; var4 < var3; ++var4) {
class116 var5 = class113.method2600(var1.readUnsignedByte());
int var6 = var1.readShortSmart();
int var8 = var1.readUnsignedByte();
class117 var9 = (class117)class140.findEnumerated(SoundCache.method792(), var8);
if (var9 == null) {
var9 = class117.field1457;
}
class115 var10 = new class115();
var10.method2619(var1, var2);
int var11 = var5.method2640();
class115[][] var12;
if (var5 == class116.field1436) {
var12 = this.field1472;
} else {
var12 = this.field1470;
}
if (var12[var6] == null) {
var12[var6] = new class115[var11];
}
var12[var6][var9.method2647()] = var10;
if (var5 == class116.field1441) {
this.field1475 = true;
}
}
}
@ObfuscatedName("l")
@ObfuscatedSignature(
descriptor = "(B)I",
garbageValue = "-14"
)
int method2661() {
return this.field1473;
}
@ObfuscatedName("s")
@ObfuscatedSignature(
descriptor = "(I)I",
garbageValue = "-1685844440"
)
int method2662() {
return this.field1474;
}
@ObfuscatedName("e")
@ObfuscatedSignature(
descriptor = "(I)I",
garbageValue = "1200373585"
)
public int method2666() {
return this.field1476;
}
@ObfuscatedName("r")
@ObfuscatedSignature(
descriptor = "(I)I",
garbageValue = "1020257728"
)
public int method2693() {
return this.method2662() - this.method2661();
}
@ObfuscatedName("o")
@ObfuscatedSignature(
descriptor = "(B)Z",
garbageValue = "30"
)
public boolean method2697() {
return this.field1475;
}
@ObfuscatedName("i")
@ObfuscatedSignature(
descriptor = "(ILdm;IIB)V",
garbageValue = "1"
)
public void method2679(int var1, class113 var2, int var3, int var4) {
class371 var5 = WorldMapSection0.method4716();
this.method2687(var5, var3, var2, var1);
this.method2669(var5, var3, var2, var1);
this.method2680(var5, var3, var2, var1);
var2.method2565(var5);
var5.method6703();
}
@ObfuscatedName("w")
@ObfuscatedSignature(
descriptor = "(Lni;ILdm;IS)V",
garbageValue = "5450"
)
void method2687(class371 var1, int var2, class113 var3, int var4) {
float[] var5 = var3.method2569(this.field1476);
float var6 = var5[0];
float var7 = var5[1];
float var8 = var5[2];
if (this.field1472[var2] != null) {
class115 var9 = this.field1472[var2][0];
class115 var10 = this.field1472[var2][1];
class115 var11 = this.field1472[var2][2];
if (var9 != null) {
var6 = var9.method2611(var4);
}
if (var10 != null) {
var7 = var10.method2611(var4);
}
if (var11 != null) {
var8 = var11.method2611(var4);
}
}
class370 var20 = GrandExchangeOfferNameComparator.method5704();
var20.method6669(1.0F, 0.0F, 0.0F, var6);
class370 var21;
synchronized(class370.field4235) {
if (class370.field4231 == 0) {
var21 = new class370();
} else {
class370.field4235[--class370.field4231].method6643();
var21 = class370.field4235[class370.field4231];
}
}
var21.method6669(0.0F, 1.0F, 0.0F, var7);
class370 var12;
synchronized(class370.field4235) {
if (class370.field4231 == 0) {
var12 = new class370();
} else {
class370.field4235[--class370.field4231].method6643();
var12 = class370.field4235[class370.field4231];
}
}
var12.method6669(0.0F, 0.0F, 1.0F, var8);
class370 var14;
synchronized(class370.field4235) {
if (class370.field4231 == 0) {
var14 = new class370();
} else {
class370.field4235[--class370.field4231].method6643();
var14 = class370.field4235[class370.field4231];
}
}
var14.method6663(var12);
var14.method6663(var20);
var14.method6663(var21);
class371 var16 = WorldMapSection0.method4716();
var16.method6683(var14);
var1.method6682(var16);
var20.method6642();
var21.method6642();
var12.method6642();
var14.method6642();
var16.method6703();
}
@ObfuscatedName("v")
@ObfuscatedSignature(
descriptor = "(Lni;ILdm;II)V",
garbageValue = "238134222"
)
void method2680(class371 var1, int var2, class113 var3, int var4) {
float[] var5 = var3.method2589(this.field1476);
float var6 = var5[0];
float var7 = var5[1];
float var8 = var5[2];
if (this.field1472[var2] != null) {
class115 var9 = this.field1472[var2][3];
class115 var10 = this.field1472[var2][4];
class115 var11 = this.field1472[var2][5];
if (var9 != null) {
var6 = var9.method2611(var4);
}
if (var10 != null) {
var7 = var10.method2611(var4);
}
if (var11 != null) {
var8 = var11.method2611(var4);
}
}
var1.field4241[12] = var6;
var1.field4241[13] = var7;
var1.field4241[14] = var8;
}
@ObfuscatedName("a")
@ObfuscatedSignature(
descriptor = "(Lni;ILdm;II)V",
garbageValue = "1303358455"
)
void method2669(class371 var1, int var2, class113 var3, int var4) {
float[] var5 = var3.method2570(this.field1476);
float var6 = var5[0];
float var7 = var5[1];
float var8 = var5[2];
if (this.field1472[var2] != null) {
class115 var9 = this.field1472[var2][6];
class115 var10 = this.field1472[var2][7];
class115 var11 = this.field1472[var2][8];
if (var9 != null) {
var6 = var9.method2611(var4);
}
if (var10 != null) {
var7 = var10.method2611(var4);
}
if (var11 != null) {
var8 = var11.method2611(var4);
}
}
class371 var12 = WorldMapSection0.method4716();
var12.method6681(var6, var7, var8);
var1.method6682(var12);
var12.method6703();
}
@ObfuscatedName("e")
@ObfuscatedSignature(
descriptor = "(ILbl;ZI)I",
garbageValue = "1719618305"
)
static int method2698(int var0, Script var1, boolean var2) {
int var4;
int var9;
if (var0 == ScriptOpcodes.CC_CREATE) {
Interpreter.Interpreter_intStackSize -= 3;
var9 = Interpreter.Interpreter_intStack[Interpreter.Interpreter_intStackSize];
var4 = Interpreter.Interpreter_intStack[Interpreter.Interpreter_intStackSize + 1];
int var11 = Interpreter.Interpreter_intStack[Interpreter.Interpreter_intStackSize + 2];
if (var4 == 0) {
throw new RuntimeException();
} else {
Widget var6 = class130.getWidget(var9);
if (var6.children == null) {
var6.children = new Widget[var11 + 1];
}
if (var6.children.length <= var11) {
Widget[] var7 = new Widget[var11 + 1];
for (int var8 = 0; var8 < var6.children.length; ++var8) {
var7[var8] = var6.children[var8];
}
var6.children = var7;
}
if (var11 > 0 && var6.children[var11 - 1] == null) {
throw new RuntimeException("" + (var11 - 1));
} else {
Widget var12 = new Widget();
var12.type = var4;
var12.parentId = var12.id = var6.id;
var12.childIndex = var11;
var12.isIf3 = true;
var6.children[var11] = var12;
if (var2) {
class16.scriptDotWidget = var12;
} else {
Interpreter.scriptActiveWidget = var12;
}
class112.invalidateWidget(var6);
return 1;
}
}
} else {
Widget var3;
if (var0 == ScriptOpcodes.CC_DELETE) {
var3 = var2 ? class16.scriptDotWidget : Interpreter.scriptActiveWidget;
Widget var10 = class130.getWidget(var3.id);
var10.children[var3.childIndex] = null;
class112.invalidateWidget(var10);
return 1;
} else if (var0 == ScriptOpcodes.CC_DELETEALL) {
var3 = class130.getWidget(Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize]);
var3.children = null;
class112.invalidateWidget(var3);
return 1;
} else if (var0 == 103) {
Interpreter.Interpreter_intStackSize -= 3;
return 1;
} else if (var0 == 104) {
--Interpreter.Interpreter_intStackSize;
return 1;
} else if (var0 != ScriptOpcodes.CC_FIND) {
if (var0 == ScriptOpcodes.IF_FIND) {
var3 = class130.getWidget(Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize]);
if (var3 != null) {
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 1;
if (var2) {
class16.scriptDotWidget = var3;
} else {
Interpreter.scriptActiveWidget = var3;
}
} else {
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 0;
}
return 1;
} else if (var0 == 202) {
Interpreter.Interpreter_intStack[Interpreter.Interpreter_intStackSize + 1] = 0;
return 1;
} else if (var0 == 203) {
Interpreter.Interpreter_intStack[--Interpreter.Interpreter_intStackSize + 1] = 0;
return 1;
} else {
return 2;
}
} else {
Interpreter.Interpreter_intStackSize -= 2;
var9 = Interpreter.Interpreter_intStack[Interpreter.Interpreter_intStackSize];
var4 = Interpreter.Interpreter_intStack[Interpreter.Interpreter_intStackSize + 1];
Widget var5 = ModeWhere.getWidgetChild(var9, var4);
if (var5 != null && var4 != -1) {
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 1;
if (var2) {
class16.scriptDotWidget = var5;
} else {
Interpreter.scriptActiveWidget = var5;
}
} else {
Interpreter.Interpreter_intStack[++Interpreter.Interpreter_intStackSize - 1] = 0;
}
return 1;
}
}
}
@ObfuscatedName("j")
@ObfuscatedSignature(
descriptor = "(I)V",
garbageValue = "1669093139"
)
static void method2699() {
Login.worldSelectOpen = false;
class260.leftTitleSprite.drawAt(Login.xPadding, 0);
FriendSystem.rightTitleSprite.drawAt(Login.xPadding + 382, 0);
class28.logoSprite.drawAt(Login.xPadding + 382 - class28.logoSprite.subWidth / 2, 18);
}
}
|
- [Constructors & Destructors](Constructor_Destructor.md)
- Types Of Constructors:
- [Default Constructor](default-constructor.md)
- [Parametrized Constructor](parametrized-constructor.md)
- [Constructors in derived classes ](Constructors_in_Derived_Classes.md)
- [Advanced Destructor](Advanced-Destructor.md)
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import * as nls from 'vscode-nls';
import { SimpleBrowserManager } from './simpleBrowserManager';
import { SimpleBrowserView } from './simpleBrowserView';
declare class URL {
constructor(input: string, base?: string | URL);
hostname: string;
}
const localize = nls.loadMessageBundle();
const openApiCommand = 'simpleBrowser.api.open';
const showCommand = 'simpleBrowser.show';
const enabledHosts = new Set<string>([
'localhost',
// localhost IPv4
'127.0.0.1',
// localhost IPv6
'0:0:0:0:0:0:0:1',
'::1',
// all interfaces IPv4
'0.0.0.0',
// all interfaces IPv6
'0:0:0:0:0:0:0:0',
'::'
]);
const openerId = 'simpleBrowser.open';
export function activate(context: vscode.ExtensionContext) {
const manager = new SimpleBrowserManager(context.extensionUri);
context.subscriptions.push(manager);
context.subscriptions.push(vscode.window.registerWebviewPanelSerializer(SimpleBrowserView.viewType, {
deserializeWebviewPanel: async (panel, state) => {
manager.restore(panel, state);
}
}));
context.subscriptions.push(vscode.commands.registerCommand(showCommand, async (url?: string) => {
if (!url) {
url = await vscode.window.showInputBox({
placeHolder: localize('simpleBrowser.show.placeholder', "https://example.com"),
prompt: localize('simpleBrowser.show.prompt', "Enter url to visit")
});
}
if (url) {
manager.show(url);
}
}));
context.subscriptions.push(vscode.commands.registerCommand(openApiCommand, (url: vscode.Uri, showOptions?: {
preserveFocus?: boolean,
viewColumn: vscode.ViewColumn,
}) => {
manager.show(url.toString(), showOptions);
}));
context.subscriptions.push(vscode.window.registerExternalUriOpener(openerId, {
canOpenExternalUri(uri: vscode.Uri) {
const originalUri = new URL(uri.toString());
if (enabledHosts.has(originalUri.hostname)) {
return isWeb()
? vscode.ExternalUriOpenerPriority.Default
: vscode.ExternalUriOpenerPriority.Option;
}
return vscode.ExternalUriOpenerPriority.None;
},
openExternalUri(resolveUri: vscode.Uri) {
return manager.show(resolveUri.toString(), {
viewColumn: vscode.window.activeTextEditor ? vscode.ViewColumn.Beside : vscode.ViewColumn.Active
});
}
}, {
schemes: ['http', 'https'],
label: localize('openTitle', "Open in simple browser"),
}));
}
function isWeb(): boolean {
// @ts-expect-error
return typeof navigator !== 'undefined' && vscode.env.uiKind === vscode.UIKind.Web;
}
|
# Contributing to confkit
For branching management, this project uses
[git-flow](https://github.com/petervanderdoes/gitflow-avh). The `main` branch is
reserved for releases: the development process occurs on `develop` and feature
branches. **Please never commit to `main`.**
## Setup
### Local repository
1. Fork the repository
2. Clone your fork to a local repository:
$ git clone https://github.com/you/confkit.git
$ cd confkit
3. Add the main repository as a remote:
$ git remote add upstream https://github.com/ejpcmac/confkit.git
4. Checkout to `develop`:
$ git checkout develop
### Git-flow
If you want to use `git-flow` and use the standard project configuration, please
run:
$ direnv allow
$ ./.gitsetup
## Workflow
To make a change, please use this workflow:
1. Checkout to `develop` and apply the last upstream changes (use rebase, not
merge!):
$ git checkout develop
$ git fetch --all --prune
$ git rebase upstream/develop
2. For a tiny patch, create a new branch with an explicit name:
$ git checkout -b <my_branch>
Alternatively, if you are working on a feature which would need more work,
you can create a feature branch with `git-flow`:
$ git flow feature start <my_feature>
*Note: always open an issue and ask before starting a big feature, to avoid
it not beeing merged and your time lost.*
3. Work on your feature (don’t forget to write typespecs and tests; you can
check your coverage with `mix coveralls.html` and open
`cover/excoveralls.html`):
# Some work
$ git commit -am "My first change"
# Some work
$ git commit -am "My second change"
...
4. When your feature is ready, feel free to use
[interactive rebase](https://help.github.com/articles/about-git-rebase/) so
your history looks clean and is easy to follow. Then, apply the last
upstream changes on `develop` to prepare integration:
$ git checkout develop
$ git fetch --all --prune
$ git rebase upstream/develop
5. If there were commits on `develop` since the beginning of your feature
branch, integrate them by **rebasing** if your branch has few commits, or
merging if you had a long-lived branch:
$ git checkout <my_feature_branch>
$ git rebase develop
*Note: the only case you should merge is when you are working on a big
feature. If it is the case, we should have discussed this before as stated
above.*
6. Open a pull request to merge your branch into the `develop` branch on the
main repository.
|
# persian-to-slug
Slugifies persian (simple and clean)
## Use
- CDN
```html
<script src="https://unpkg.com/persian-to-slug@latest/dist/persian-to-slug.js"></script>
```
- Npm
```javascript
const PersianToSlug = require("persian-to-slug");
/*
PersianToSlug(
input,
part = 6,
separator = "-",
myWords = {}
)
*/
PersianToSlug("عنوان Article، به زبان فارسی");
/* => "title-article-language-farsi" */
```
## Test
```bash
√ PersianToSlug(
"عنوان Article، به زبان فارسی"
)
=> "title-article-language-farsi" (8 ms)
√ PersianToSlug(
"عنوان Article، به زبان فارسی",
2
)
=> "title-article" (1 ms)
√ PersianToSlug(
"عنوان Article، به زبان فارسی",
3,
"_"
)
=> "title_article_language" (1 ms)
√ PersianToSlug(
"عنوان Article، به زبان فارسی",
6,
"___",
{ "زبان": "zaban" }
)
=> "title___article___zaban___farsi" (1 ms)
```
|
// tslint:disable-next-line:variable-name
export const enum Locale {
pong = "pong",
config_action_title = "config_action_title",
collect_save_success = "collect_save_success",
collect_save_fail = "collect_save_fail",
collect_save_no_images_found = "collect_save_no_images_found",
initial_run_upload_stickers = "initial_run_upload_stickers",
}
|
package io.github.mariazevedo88.travelsjavaapi.repository.travel;
import java.time.LocalDateTime;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import io.github.mariazevedo88.travelsjavaapi.model.travel.Travel;
/**
* Interface that implements the Travel Repository, with JPA CRUD methods
* and other customized searches.
*
* @author Mariana Azevedo
* @since 28/03/2020
*/
@Repository
public interface TravelRepository extends JpaRepository<Travel, Long> {
/**
* Method to search for all the travels in the API in a period of time.
*
* @author Mariana Azevedo
* @since 21/08/2020
*
* @return <code>Page<Travel></code> object
*/
Page<Travel> findAllByStartDateGreaterThanEqualAndStartDateLessThanEqual
(LocalDateTime startDate, LocalDateTime endDate, Pageable pg);
/**
* Method to search for all the travel in the same order number (unique number).
*
* @author Mariana Azevedo
* @since 28/03/2020
*
* @return <code>Optional<Travel></code> object
*/
Optional<Travel> findByOrderNumber(String orderNumber);
}
|
import Vue from 'vue';
// import axios from 'axios';
// import VueAxios from 'vue-axios';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import config from '@/config';
import moment from 'moment';
import App from './App.vue';
import router from './router';
Vue.config.productionTip = false;
// Vue.use(VueAxios, axios);
Vue.use(ElementUI);
Vue.prototype.$config = config;
moment.locale('zh-cn');
Vue.prototype.$moment = moment;
Vue.prototype.GlobalCliObj = {
name: 'liubei',
age: 18,
};
new Vue({
router,
render: (h) => h(App),
}).$mount('#app');
|
require 'test_helper'
require 'webmock/minitest'
require 'notifiers/maintainer_notifier'
require 'notifiers/notifier_with_rescue_handler'
WebMock.allow_net_connect!
Pushing::Base.logger = Logger.new(STDOUT)
Pushing.configure do |config|
config.fcm.server_key = ENV.fetch('FCM_TEST_SERVER_KEY')
config.apn.environment = :development
config.apn.certificate_path = File.join(File.expand_path("./"), ENV.fetch('APN_TEST_CERTIFICATE_PATH'))
config.apn.certificate_password = ENV.fetch('APN_TEST_CERTIFICATE_PASSWORD')
config.apn.default_headers = {
apns_topic: ENV.fetch('APN_TEST_TOPIC')
}
end
|
package com.github.pekoto.fastfuzzystringmatcher;
/**
* A result returned after searching using the string matcher.
*
* @author Graham McRobbie
*
* @param <T> The type of data associated with each string keyword.
*/
public class SearchResult<T> {
private CharSequence keyword;
private T associatedData;
private float matchPercentage;
public SearchResult(CharSequence keyword, T associatedData, float matchPercentage) {
this.keyword = keyword;
this.associatedData = associatedData;
this.matchPercentage = matchPercentage;
}
public CharSequence getKeyword() {
return keyword;
}
public T getAssociatedData() {
return associatedData;
}
public float getMatchPercentage() {
return matchPercentage;
}
@Override
public String toString() {
return String.format("%s/%s/%f", keyword, associatedData, matchPercentage);
}
}
|
describe("ShowcaseScreen", () => {
beforeEach(async () => await device.reloadReactNative());
test("should have first page at first", async () => {
// await element(by.text("⋙")).tap(); //晕, 这还找不到?! 我打印下view hierarchy, 发现text已经是"⋙"
await element(by.text("⋙")).tap();
await expect(element(by.text("First Page"))).toBeVisible();
});
test("swipe test", async () => {
await element(by.text("⋙")).tap();
// 这里取巧了. 因为detox不支持testID在自定义view上, 所以无法使用by.id("viewpager"). 只好试一下Text, 竟然成功了!
await element(by.text("First Page")).swipe("left"); // swipe("left")表示滑动到去看右边一页!
await expect(element(by.text("Second Page"))).toBeVisible();
});
});
|
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace CozyKxlol.Engine.Tiled.Json
{
public class CozyTiledJsonParser
{
public object ParseWithFile(string filename)
{
string json = null;
using (var fs = new StreamReader(new FileStream(filename, FileMode.Open, FileAccess.Read)))
{
json = fs.ReadToEnd();
}
if(json != null)
{
return Parse(json);
}
return null;
}
public object Parse(string json)
{
CozyTileJsonResult node = new CozyTileJsonResult();
JObject jo = JObject.Parse(json);
var tiles = jo["tiles"];
if (tiles != null && tiles.HasValues)
{
node.tiles = JsonConvert.DeserializeObject<List<CozyJsonTilesData>>(tiles.ToString());
}
var blocks = jo["blocks"];
if (blocks != null && blocks.HasValues)
{
var square = blocks["square"];
if (square != null && square.HasValues)
{
node.square = JsonConvert.DeserializeObject<List<CozyJsonBlockData>>(square.ToString());
foreach(var obj in node.square)
{
obj.type = "square";
}
}
var rect = blocks["rect"];
if (rect != null && rect.HasValues)
{
node.rect = JsonConvert.DeserializeObject<List<CozyJsonBlockData>>(rect.ToString());
foreach (var obj in node.rect)
{
obj.type = "rect";
}
}
}
return node;
}
}
}
|
// Copyright © Pixel Crushers. All rights reserved.
using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections.Generic;
namespace PixelCrushers.LoveHate
{
/// <summary>
/// This abstract class is the workhorse for GossipTrigger and GossipTrigger2D.
/// </summary>
public abstract class AbstractGossipTrigger : AbstractTriggerInteractor
{
/// <summary>
/// At least this many seconds must pass before gossiping with the same character.
/// </summary>
[Tooltip("This many seconds must pass before gossiping with the same character again")]
public float timeBetweenGossip = 300f;
private Dictionary<FactionMember, float> lastGossip = new Dictionary<FactionMember, float>();
private FactionMember m_self = null;
protected virtual void Awake()
{
m_self = GetComponentInChildren<FactionMember>() ?? GetComponentInParent<FactionMember>();
}
protected virtual void HandleOnTriggerEnter(GameObject other)
{
TryGossip(GetFactionMember(other));
}
/// <summary>
/// Tries to gossip between this faction member and another, based on affinity
/// and when they last gossiped.
/// </summary>
/// <param name="other">Other faction member.</param>
public virtual void TryGossip(FactionMember other)
{
if (ShouldGossip(other))
{
Gossip(other);
}
}
protected virtual bool ShouldGossip(FactionMember other)
{
if (m_self == null || other == null || other == m_self ||
other.factionID == FactionDatabase.PlayerFactionID || other.CompareTag("Player")) return false;
var tooRecent = lastGossip.ContainsKey(other) && (GameTime.time < (lastGossip[other] + timeBetweenGossip));
return !tooRecent && (m_self.GetAffinity(other) > 0);
}
protected virtual void Gossip(FactionMember other)
{
if (m_self == null || other == null) return;
UpdateLastGossipTime(other);
var otherGossipTrigger = other.GetComponent<AbstractGossipTrigger>();
if (otherGossipTrigger != null)
{
otherGossipTrigger.UpdateLastGossipTime(m_self);
}
m_self.ShareRumors(other);
other.ShareRumors(m_self);
ExecuteEvents.Execute<IGossipEventHandler>(m_self.gameObject, null, (x, y) => x.OnGossip(other));
ExecuteEvents.Execute<IGossipEventHandler>(other.gameObject, null, (x, y) => x.OnGossip(m_self));
}
public void UpdateLastGossipTime(FactionMember other)
{
lastGossip[other] = GameTime.time;
}
}
}
|
function _get(name,context) {
if (context) {
// if you pass in a 3rd argument, which should be an html element, then that is set as teh context.
// this ensures garbage collection of the values when that element is removed.
return $.data(context[0],name);
} else {
return $.data(document.body,name);
}
}
function _set(name,value,context) {
if (context) {
// if you pass in a 3rd argument, which should be an html element, then that is set as teh context.
// this ensures garbage collection of the values when that element is removed.
return $.data(context[0],name,value);
} else {
return $.data(document.body,name,value);
}
}
|
---
to: package.json
inject: true
at_line: 1
eof_last: false
---
"name": "<%= name %>",
"version": "<%= version %>",
"license": "<%= license %>",
"author": "<%= author %>",
|
import { InjectionToken } from '@angular/core';
import { Observable } from 'rxjs';
import { Shop } from '@dsh/api-codegen/capi';
export const SHOPS = new InjectionToken<Observable<Shop[]>>('Shops');
|
#pragma once
#include <vector>
#include "Shape.h"
class FileSVG;
class FileEPS;
class Document
{
public:
void AddCircle();
void AddRectangle();
void RemoveShape(const Shape*) {}
Shape* GetShapeByCoord(int, int);
Shape* GetSelectedShape() { return m_selectedShape; }
void SelectShape(Shape* shape);
void UnselectShape();
void ImportFromSVG(const FileSVG&) {}
void ImportFromEPS(const FileEPS&) {}
void ExportToSVG(FileSVG* file);
void ExportToEPS(FileEPS* file);
void Draw() const;
~Document();
private:
std::vector<Shape*> m_shapeList;
Shape* m_selectedShape = nullptr;
};
|
{-# LANGUAGE FlexibleContexts #-}
--------------------------------------------------------------------------------
-- |
-- Module : Network.OpenID.Authentication
-- Copyright : (c) Trevor Elliott, 2008
-- License : BSD3
--
-- Maintainer : Trevor Elliott <trevor@geekgateway.com>
-- Stability :
-- Portability :
--
module Network.OpenID.Authentication (
-- * Types
CheckIdMode(..)
-- * Authentication
, authenticationURI
, verifyAuthentication
) where
-- friends
import Codec.Binary.Base64
import Network.OpenID.Association.Manager
import Network.OpenID.HTTP
import Network.OpenID.Types
import Network.OpenID.Utils
-- libraries
import Data.List
import MonadLib
import Network.HTTP
import Network.URI
import Numeric
import qualified Data.ByteString as BS
import qualified Data.Digest.OpenSSL.HMAC as HMAC
--------------------------------------------------------------------------------
-- Types
data CheckIdMode = Immediate | Setup
instance Show CheckIdMode where
show Immediate = "checkid_immediate"
show Setup = "checkid_setup"
instance Read CheckIdMode where
readsPrec _ s | "checkid_immediate" `isPrefixOf` s = [(Immediate, drop 17 s)]
| "checkid_setup" `isPrefixOf` s = [(Setup, drop 13 s)]
| otherwise = []
--------------------------------------------------------------------------------
-- Utilities
-- | Get the mac hash type
macHash :: AssocType -> HMAC.CryptoHashFunction
macHash HmacSha1 = HMAC.sha1
macHash HmacSha256 = HMAC.sha256
-- | Parse a provider within the Result monad
parseProvider' :: ExceptionM m Error => String -> m Provider
parseProvider' = maybe err return . parseProvider
where err = raise (Error "unable to parse openid.op_endpoint")
-- | Get the signed fields from a set of parameters
getSignedFields :: ExceptionM m Error => [String] -> Params -> m Params
getSignedFields ks ps = maybe err return (mapM lkp ks)
where
err = raise (Error "not all signed parameters present")
lkp k = (,) k `fmap` lookup ("openid." ++ k) ps
--------------------------------------------------------------------------------
-- Authentication
-- | Generate an authentication URL
authenticationURI :: AssociationManager am
=> am -> CheckIdMode -> Provider -> Identifier -> ReturnTo
-> Maybe Realm -> URI
authenticationURI am mode prov ident rt mb_realm =
addParams params (providerURI prov)
where
params = [ ("openid.ns", openidNS)
, ("openid.mode", show mode)
, ("openid.claimed_id", getIdentifier ident)
, ("openid.identity", getIdentifier ident)
, ("openid.return_to", rt)
] ++ ah ++
maybe [] (\r -> [("openid.realm", r)]) mb_realm
ah = case findAssociation am prov of
Nothing -> []
Just a -> [("openid.assoc_handle", assocHandle a)]
-- | Verify a signature on a set of params.
verifyAuthentication :: (Monad m, AssociationManager am)
=> am -> Params -> ReturnTo -> Resolver m
-> m (Either Error ())
verifyAuthentication am ps rto resolve =
runExceptionT $ do
u <- lookupParam "openid.return_to" ps
unless (u == rto) $ raise $ Error $ "invalid return path: " ++ u
prov <- parseProvider' =<< lookupParam "openid.op_endpoint" ps
case findAssociation am prov of
Nothing -> verifyDirect ps prov resolve
Just assoc -> verifyWithAssociation ps assoc
-- | Verify an assertion directly
verifyDirect :: Monad m
=> Params -> Provider -> Resolver m -> ExceptionT Error m ()
verifyDirect ps prov resolve = do
let body = formatParams
$ ("openid.mode","check_authentication")
: filter (\p -> fst p /= "openid.mode") ps
ersp <- lift $ resolve Request
{ rqURI = providerURI prov
, rqMethod = POST
, rqHeaders =
[ Header HdrContentLength $ show $ length body
, Header HdrContentType "application/x-www-form-urlencoded"
]
, rqBody = body
}
withResponse ersp $ \rsp -> do
let rps = parseDirectResponse (rspBody rsp)
case lookup "is_valid" rps of
Just "true" -> return ()
_ -> raise (Error "invalid authentication request")
-- | Verify with an association
verifyWithAssociation :: Monad m
=> Params -> Association -> ExceptionT Error m ()
verifyWithAssociation ps a = do
mode <- lookupParam "openid.mode" ps
unless (mode == "id_res") $ raise $ Error $ "unexpected openid.mode: " ++ mode
sigParams <- breaks (',' ==) `fmap` lookupParam "openid.signed" ps
sig <- decode `fmap` lookupParam "openid.sig" ps
sps <- getSignedFields sigParams ps
let h = macHash (assocType a)
msg = map (toEnum . fromEnum) (formatDirectParams sps)
mc = HMAC.unsafeHMAC h (BS.pack (assocMacKey a)) (BS.pack msg)
sig' = case readHex mc of
[(x,"")] -> unroll x
_ -> []
unless (sig' == sig) $ raise $ Error "invalid signature"
|
ALTER TABLE client ADD COLUMN productoffersconfigurations jsonb;
CREATE TABLE IF NOT EXISTS productOffers (
clientId uuid PRIMARY KEY REFERENCES client (id),
hash text,
productOffers jsonb
);
|
// @filename: a.ts
export default abstract class A {}
// @filename: b.ts
import A from './a'
|
# *****************************************************************************
# *****************************************************************************
#
# Name: generate.rb
# Author: Paul Robson (paul@robsons.org.uk)
# Date: 1st October 2021
# Reviewed: No
# Purpose: Generate include files
#
# *****************************************************************************
# *****************************************************************************
require 'pathname'
require '../roms/romconvert.rb'
# *****************************************************************************
#
# File Objects
#
# *****************************************************************************
class FileObject
def initialize(path)
@file_name = Pathname(path)
#puts "#{full_path} #{file_owner} #{is_rom}"
end
def full_path
@file_name.to_s end
def file_owner
owner = @file_name.basename.to_s.split("_")[0].split(".")[0].downcase end
def is_rom
@file_name.extname == ".bin"
end
def to_s
@file_name.basename
end
end
class RomImage < FileObject
def export
rom = EncodedROM.new(full_path)
rom.export_binary(file_owner+".cqc")
end
end
class CassetteFile < FileObject
end
class CassetteGroup
def initialize
@bas_root = nil
@files = []
end
#
def add(f)
if f.full_path.downcase.include?("_bas.")
raise "Duplicate bas for "+f.full_path if @bas_root
@bas_root = f
else
@files.append(f)
end
end
#
def export
if @bas_root
files = [@bas_root] + @files
else
files = @files
end
h = open(files[0].file_owner+".cqc","wb")
files.each do |f|
data = open(f.full_path,"rb").each_byte.collect { |a| a }
data.each { |b| h.write(b.chr) }
end
h.close
end
#
def to_s
files = @files.collect { |f| f.to_s }.join(",")
@bas_root.to_s + " : " + files
end
end
#
# Get all files
#
file_list = []
Dir.glob('../virtualaquarius/rom/**/*.bin').each { |f| file_list.append(RomImage.new(f))}
Dir.glob('../virtualaquarius/cassette/**/*.caq').each { |f| file_list.append(CassetteFile.new(f))}
Dir.glob('../virtualaquarius/cassette/**/*.CAQ').each { |f| file_list.append(CassetteFile.new(f))}
#
# Identify those with dodgy names
#
puts "Bad : #{file_list.select {|l| l.file_owner.length > 6 }.collect { |a| a.to_s}.join(",")}"
file_list = file_list.select { |l| l.file_owner.length <= 6 }
#
# Do all the ROMs
#
file_list.select { |f| f.is_rom }.each { |f| f.export }
#
# Build group cassette objects
#
cassette_groups = {}
file_list.select { |f| not f.is_rom }.each do |f|
key = f.file_owner
cassette_groups[key] = CassetteGroup.new unless cassette_groups.include? key
cassette_groups[key].add(f)
end
cassette_groups.each { |k,v| v.export }
|
#include <fstream>
#include <iostream>
#include <stdint.h>
#include <string.h>
#include <time.h>
#include <vector>
using namespace std;
struct MyData {
uint16_t x;
uint16_t y;
std::vector<uint32_t> samples;
};
void serialize(std::vector<MyData> indata) {
size_t size{0};
size += sizeof(size_t); // add space for array of MyData
size += sizeof(time_t); // add space for a time stamp too just in case
for (const auto &item : indata) {
// clang-format off
size += sizeof(MyData::x) + sizeof(MyData::y) + item.samples.size() * sizeof(uint32_t);
// clang-format on
size += sizeof(size_t); // need to add space for array lenght too..
}
cout << "Total size = " << size << endl;
uint8_t *buffer = new uint8_t[size];
memset(buffer, 0, size);
size_t offset = 0;
*((size_t *)buffer) = indata.size();
offset += sizeof(size_t);
// add optional timestamp here..
for (auto const &item : indata) {
*((uint16_t *)(buffer + offset)) = item.x;
offset += sizeof(MyData::x);
*((uint16_t *)(buffer + offset)) = item.y;
offset += sizeof(MyData::y);
*((size_t *)(buffer + offset)) = item.samples.size();
offset += sizeof(size_t);
for (auto const &sample : item.samples) {
*((uint32_t *)(buffer + offset)) = sample;
offset += sizeof(uint32_t);
}
}
cout << "Offset = " << offset << " size = " << size << endl;
for (size_t index = 0; index < size; index++) {
cout << std::hex << " 0x" << (uint64_t)buffer[index] << endl;
}
ofstream outfile;
outfile.open("data.bin", ios::out | ios::binary);
if (outfile) {
outfile.write((char *)buffer, size);
}
delete[] buffer;
}
int main() {
cout << "Serializer!" << endl;
std::vector<MyData> data{
{.x = 0x1234,
.y = 0x5678,
.samples{0x1234aabb, 0x34ffeeff, 0x5612, 0x7812, 0x9012}},
{.x = 0x12, .y = 0x13, .samples{0x12aabbcc, 0x34ddeeff, 0x56, 0x78, 0x90}}};
serialize(data);
return 0;
}
|
from dataclasses import dataclass
from ..pieces import PieceManager
from .action import Action
@dataclass
class Batch:
commands : list[Action]
# def __len__(self):
# return len(self.commands)
def __iter__(self):
return iter(self.commands)
def execute(self, piece_manager : PieceManager):
completed_commands = []
try:
for action in self.commands:
action.execute(piece_manager)
completed_commands.append(action)
except Exception as err:
for action in reversed(completed_commands):
action.undo(piece_manager)
raise err
def undo(self, piece_manager : PieceManager) -> None:
for action in self.commands:
action.undo(piece_manager)
def redo(self, piece_manager : PieceManager) -> None:
for action in self.commands:
action.redo(piece_manager)
|
package diwan.fablab.gemals.graphics;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.math.Affine2;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import gwel.game.graphics.DrawableCircle;
import gwel.game.graphics.DrawablePolygon;
public class DrawablePhysics {
public Body body;
public DrawablePolygon[] shapes;
private final Affine2 transform = new Affine2();
public DrawablePhysics(Body body) {
this.body = body;
shapes = new DrawablePolygon[body.getFixtureList().size];
int s = 0;
for (Fixture fixture : body.getFixtureList()) {
switch (fixture.getType()) {
case Polygon:
PolygonShape polygonShape = (PolygonShape) fixture.getShape();
Vector2 vertex = new Vector2();
float[] vertices = new float[polygonShape.getVertexCount() * 2];
for (int i = 0; i < polygonShape.getVertexCount(); i++) {
polygonShape.getVertex(i, vertex);
vertices[i*2] = vertex.x;
vertices[i*2 + 1] = vertex.y;
}
DrawablePolygon polygon = new DrawablePolygon(vertices);
polygon.setColor(0.5f, 0.5f, 0.5f, 1);
if (fixture.isSensor())
polygon.setColorMod(1, 1, 1, 0.4f);
shapes[s++] = polygon;
break;
case Circle:
CircleShape circleShape = (CircleShape) fixture.getShape();
Vector2 position = circleShape.getPosition();
DrawableCircle circle = new DrawableCircle(position.x, position.y, circleShape.getRadius());
circle.setColor(0.5f, 0.5f, 0.5f, 1);
if (fixture.isSensor())
circle.setColorMod(1, 1, 1, 0.4f);
shapes[s++] = circle;
break;
}
}
}
public void setColor(int i, Color color) {
shapes[i].setColor(color);
}
public void setColorMod(float rm, float gm, float bm, float am) {
for (DrawablePolygon shape : shapes)
shape.setColorMod(rm, gm, bm, am);
}
public void draw(MyRenderer renderer) {
transform.setToTranslation(body.getPosition());
transform.rotateRad(body.getAngle());
renderer.pushMatrix(transform);
for (DrawablePolygon shape : shapes)
shape.draw(renderer);
renderer.popMatrix();
}
}
|
#!/bin/bash
docker run --rm -v `pwd`:/home/myapp mono-pcqq:proto ./generate_stub.sh
|
require_relative "../kamayan"
# Diagram of a queue:
#
# New elements are added here
# |
# v
# +---+---+---+
# | x | y | z |
# +---+---+---+
# ^
# |
# Elements are removed from here
#
#
# Diagram of a queue as you run operations on it:
#
# +
# Empty queue: |
# +
#
# +---+
# enqueue(a): | a |
# +---+
#
# +---+---+
# enqueue(b): | a | b |
# +---+---+
#
# +---+---+---+
# enqueue(c): | a | b | c |
# +---+---+---+
#
# peek()
# => a
#
# +---+---+
# dequeue(): | b | c |
# => a +---+---+
#
# peek()
# => b
#
# +---+
# dequeue(): | c |
# => b +---+
#
# peek()
# => c
#
# +
# dequeue(): |
# => c +
#
class Serving06Queues < Attestify::Test
def test_internal_collection_implements_each
# The each method will be used for other tests, so if you decided not to use
# the DoublyLinkedList, you will need to implement `each` for your chosen
# collection.
assert_method_exists Queue.new.instance_variable_get(:@list).class, :each, 0
end
def test_enqueue_exists
assert_method_exists Queue, :enqueue, 1
end
def test_enqueue_adds_elements
queue = Queue.new
queue.enqueue(42)
assert_equal 1, queue.size
queue.enqueue(43)
queue.enqueue(1)
queue.enqueue(2)
assert_equal 4, queue.size
end
def test_enqueue_adds_to_the_end_of_the_queue
queue = Queue.new
queue.enqueue(42)
actual_elements = []
queue.instance_variable_get(:@list).each { |element| actual_elements << element }
assert_equal [42], actual_elements
queue.enqueue(43)
queue.enqueue(1)
queue.enqueue(2)
actual_elements = []
queue.instance_variable_get(:@list).each { |element| actual_elements << element }
assert_equal [42, 43, 1, 2], actual_elements
end
def test_enqueue_returns_self_so_it_can_be_chained
queue = Queue.new
assert_equal queue, queue.enqueue(42)
assert_equal queue, queue.enqueue(43)
end
def test_enqueue_can_be_called_a_lot
queue = Queue.new
1000.times { queue.enqueue(42) }
assert_equal 1000, queue.size
end
def test_dequeue_exists
assert_method_exists Queue, :dequeue, 0
end
def test_dequeue_raises_an_error_if_the_queue_is_empty
queue = Queue.new
assert_raises(IndexError) { queue.dequeue }
end
def test_dequeue_returns_the_first_element_of_the_queue
queue = Queue.new.enqueue(42)
assert_equal 42, queue.dequeue
queue.enqueue(43)
assert_equal 43, queue.dequeue
end
def test_dequeue_alters_the_size_of_the_queue
queue = Queue.new.enqueue(42).enqueue(43)
assert_equal 2, queue.size
queue.dequeue
assert_equal 1, queue.size
queue.dequeue
assert_equal 0, queue.size
end
def test_dequeue_raises_an_error_if_the_queue_is_empty_after_being_emptied
queue = Queue.new.enqueue(42)
queue.dequeue
assert_raises(IndexError) { queue.dequeue }
end
def test_dequeue_returns_the_first_element_added
queue = Queue.new.enqueue(42).enqueue(43).enqueue(1).enqueue(2)
assert_equal 42, queue.dequeue
assert_equal 43, queue.dequeue
assert_equal 1, queue.dequeue
assert_equal 2, queue.dequeue
end
def test_empty_exists
assert_method_exists Queue, :empty?, 0
end
def test_empty_returns_true_for_new_queues
queue = Queue.new
assert queue.empty?
queue.enqueue(42)
queue.dequeue
assert queue.empty?
end
def test_empty_returns_true_for_queues_that_have_been_emptied
queue = Queue.new.enqueue(42)
queue.dequeue
assert queue.empty?
end
def test_empty_returns_false_for_non_empty_queues
queue = Queue.new.enqueue(42)
refute queue.empty?
queue.enqueue(43)
refute queue.empty?
end
def test_empty_returns_false_for_queues_that_have_been_emptied_and_grown_again
queue = Queue.new.enqueue(42).enqueue(43)
queue.dequeue
queue.dequeue
queue.enqueue(1)
refute queue.empty?
end
def test_peek_exists
assert_method_exists Queue, :peek, 0
end
def test_peek_raises_an_error_if_the_queue_is_empty
queue = Queue.new
assert_raises(IndexError) { queue.peek }
queue.enqueue(42)
queue.dequeue
assert_raises(IndexError) { queue.peek }
end
def test_peek_returns_the_first_value_of_the_queue
queue = Queue.new.enqueue(42)
assert_equal 42, queue.peek
queue.enqueue(43)
assert_equal 42, queue.peek
end
def test_peek_can_by_called_multiple_times_without_affecting_the_size
queue = Queue.new.enqueue(42)
assert_equal 42, queue.peek
assert_equal 42, queue.peek
assert_equal 42, queue.peek
assert_equal 1, queue.size
queue.enqueue(43)
assert_equal 42, queue.peek
assert_equal 42, queue.peek
assert_equal 42, queue.peek
assert_equal 2, queue.size
end
end
|
package org.wikipedia.feed.mostread;
import androidx.annotation.NonNull;
import org.wikipedia.json.annotations.Required;
import java.util.Date;
import java.util.List;
@SuppressWarnings("unused,NullableProblems")
public final class MostRead {
@Required @NonNull private Date date;
@Required @NonNull private List<MostReadArticles> articles;
@NonNull public Date date() {
return date;
}
@NonNull public List<MostReadArticles> articles() {
return articles;
}
}
|
#!/bin/bash
EXODUS_VERSION=$1
echo EXODUS_VERSION=$EXODUS_VERSION
#./googlecode_upload.py --help
#Usage: googlecode-upload.py -s SUMMARY -p PROJECT [options] FILE
#
#Options:
# -h, --help show this help message and exit
# -s SUMMARY, --summary=SUMMARY
# Short description of the file
# -p PROJECT, --project=PROJECT
# Google Code project name
# -u USER, --user=USER Your Google Code username
# -w PASSWORD, --password=PASSWORD
# Your Google Code password
# -l LABELS, --labels=LABELS
# An optional list of comma-separated labels to attach
# to the file
#save current directory (to find googlecode_upload.py later)
export ORIG_DIRXYZ=`pwd`
#get into BitRock's .app output folder
pushd /Applications/BitRock*/output
#delete any old zip
if [ -f "exodus-${EXODUS_VERSION}-osx-installer.app.zip" ]
then
rm exodus-${EXODUS_VERSION}-osx-installer.app.zip
fi
#make a new zip
zip -r \
exodus-${EXODUS_VERSION}-osx-installer.app.zip \
exodus-${EXODUS_VERSION}-osx-installer.app/*
#view new zip size
ls -l exodus-${EXODUS_VERSION}-osx-installer.app.zip
#upload the new zip to google code
${ORIG_DIRXYZ}/googlecode_upload.py \
-s "Mac OSX 64bit Snow Leopard" \
-p "exodusdb" \
-u "neosys.com@gmail.com" \
-w "${GOOGLECODE_PASS}" \
-l "Featured,Type-Package,OpSys-OSX" \
exodus-${EXODUS_VERSION}-osx-installer.app.zip
#get back to whereever we started
popd
|
#[derive(Debug)]
#[derive(PartialEq)]
#[allow(non_camel_case_types)]
pub enum TokenType {
INSTRUCTION,
LABEL,
INTEGER,
DOUBLE,
STRING,
REGISTER,
METHOD,
VARIABLE_DECL,
VARIABLE,
INCLUDE,
CHAR
}
pub struct Token {
pub token_t: TokenType,
pub data: String
}
impl Token {
pub fn new(t: TokenType, d: String) -> Self {
return Token {
token_t: t,
data: d
}
}
}
|
"""
identify_condition(df::AbstractDataFrame,cols::Vector{Symbol},codes::Vector{String})
produces a vector of Boolean `true` or `false` depending on whether columns `cols` contain
any of the string values in `codes`. This function is designed to easily identify comorbid
conditions in inpatient or outpatient records that are coded in ICD-9 or ICD-10 codes.
The values in `cols` are compared to the values (`code`) in `codes` only up to the length of
the `code`. For example, when detecting "diabetes", one may use "250.xx" in ICD-9,
which can be specified as identify_condition(df,[:diag1,:diag2,:diag3,:diag4,:diag5],["250"]).
All values that start with "250" in :diag1 - :diag4 (e.g., "25010") will match.
"""
function identify_condition(ip::AbstractDataFrame,vicd::Vector{Symbol},codes::Vector{String})
retvec = zeros(Bool,nrow(ip))
for i in 1:nrow(ip)
for v in vicd
if ismissing(ip[i,v])
continue
end
vlen=length(ip[i,v])
for c in codes
clen = length(c)
if vlen >= clen && c == ip[i,v][1:length(c)]
retvec[i] = true
break
end
end
if retvec[i] == true
break
end
end
end
return retvec
end
"""
identify_condition2(df::AbstractDataFrame,cols::Vector{Symbol},codes::Vector{String})
produces a vector of Boolean `true` or `false` depending on whether columns `cols` contain
any of the string values in `codes`. This function is designed to easily identify comorbid
conditions in inpatient or outpatient records that are coded in ICD-9 or ICD-10 codes.
The values in `cols` are compared to the values in `codes` exactly as they are specified.
"""
function identify_condition2(ip::AbstractDataFrame,vicd::Vector{Symbol},codes::Vector{String})
retvec = zeros(Bool,nrow(ip))
for i in 1:nrow(ip)
for v in vicd
if ismissing(ip[i,v])
continue
end
if ip[i,v] in codes
retvec[i] = true
end
end
end
return retvec
end
|
$: << File.dirname(__FILE__) + '/..'
require 'helper'
describe Clive::Argument::AlwaysTrue do
subject { Clive::Argument::AlwaysTrue }
it 'is always true for the method given' do
subject.for(:hey).hey.must_be_true
end
it 'is always true for the methods given' do
a = subject.for(:one, :two, :three)
a.one.must_be_true
a.two.must_be_true
a.three.must_be_true
end
end
describe Clive::Argument do
subject { Clive::Argument }
describe '#initialize' do
it 'converts name to Symbol' do
subject.new('arg').name.must_be_kind_of Symbol
end
it 'calls #to_proc on a Symbol constraint' do
c = mock
c.expects(:respond_to?).with(:to_proc).returns(true)
c.expects(:to_proc)
subject.new :a, :constraint => c
end
it 'merges given options with DEFAULTS' do
opts = {:optional => true}
Clive::Argument::DEFAULTS.expects(:merge).with(opts).returns({})
subject.new('arg', opts)
end
it 'finds the correct type class' do
subject.new(:a, :type => String).type.must_equal Clive::Type::String
end
it 'uses the class passed if type cannot be found' do
type = Class.new
subject.new(:a, :type => type).type.must_equal type
end
end
describe '#optional?' do
it 'is true if the argument is optional' do
subject.new(:arg, :optional => true).must_be :optional?
end
it 'is false if the argument is not optional' do
subject.new(:arg, :optional => false).wont_be :optional?
end
it 'is false by default' do
subject.new(:arg).wont_be :optional?
end
end
describe '#infinite?' do
it 'is true if the argument is infinite' do
subject.new(:arg, :infinite => true).must_be :infinite?
end
it 'is false if the argument is not infinite' do
subject.new(:arg, :infinite => false).wont_be :infinite?
end
it 'is false by default' do
subject.new(:arg).wont_be :infinite?
end
end
describe '#to_s' do
it 'surrounds the name by < and >' do
subject.new(:a).to_s.must_equal '<a>'
end
it 'surrounds optional arguments with [ and ]' do
subject.new(:a, :optional => true).to_s.must_equal '[<a>]'
end
end
describe '#choice_str' do
it 'returns the array of values allowed' do
subject.new(:a, :within => %w(a b c)).choice_str.must_equal '(a, b, c)'
end
it 'returns the range of values allowed' do
subject.new(:a, :within => 1..5).choice_str.must_equal '(1..5)'
end
end
describe '#possible?' do
describe 'for @type' do
subject { Clive::Argument.new :a, :type => Clive::Type::Time }
it 'is true for correct string values' do
subject.must_be :possible?, '12:34'
end
it 'is true for objects of type' do
subject.must_be :possible?, Time.parse('12:34')
end
unless RUBY_VERSION == '1.8.7' # No big problem so just ignore
it 'is false for incorrect values' do
subject.wont_be :possible?, 'not-a-time'
end
end
end
describe 'for @match' do
subject { Clive::Argument.new :a, :match => /^[a-e]+![f-o]+\?.$/ }
it 'is true for matching values' do
subject.must_be :possible?, 'abe!off?.'
end
it 'is false for non-matching values' do
subject.wont_be :possible?, 'off?abe!.'
end
end
describe 'for @within' do
subject { Clive::Argument.new :a, :within => %w(dog cat fish) }
it 'is true for elements included in the collection' do
subject.must_be :possible?, 'dog'
end
it 'is false for elements not in the collection' do
subject.wont_be :possible?, 'mouse'
end
end
describe 'for @constraint' do
subject { Clive::Argument.new :a, :constraint => proc {|i| i.size == 5 } }
it 'is true if the proc returns true' do
subject.must_be :possible?, 'abcde'
end
it 'is false if the proc returns false' do
subject.wont_be :possible?, 'abcd'
end
end
end
describe '#coerce' do
it 'uses @type to return the correct object' do
type = mock
type.expects(:typecast).with('str').returns(5)
subject.new(:a, :type => type).coerce("str").must_equal 5
end
end
end
|
use serde::{Deserialize, Serialize};
use url::Url;
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct User {
pub id: String,
pub username: String,
pub links: UserLinks,
pub profile_image: UserProfileImage,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct UserLinks {
pub html: String,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct UserProfileImage {
pub large: Url,
}
|
INSERT INTO history
(
from_title,
description,
amount,
"date"
)
VALUES
($1,$2,$3,$4)
;
|
use Test::Unit::HarnessUnit;
use lib qw(t/tlib);
my $r = Test::Unit::HarnessUnit->new();
$r->start( 'P4::Objects::Test::Connection' );
|
using System.Collections.Generic;
namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects
{
public interface ISymbolModel
{
string Type { get; }
string Binding { get; set; }
string Replaces { get; set; }
IReadOnlyList<IReplacementContext> ReplacementContexts { get; }
}
}
|
require_relative "../../../../test_helper"
describe Restforce::DB::RecordTypes::Salesforce do
configure!
mappings!
let(:record_type) { mapping.salesforce_record_type }
describe "#create!", :vcr do
let(:database_record) do
database_model.create!(
name: "Something",
example: "Something else",
)
end
let(:sync_from) { Restforce::DB::Instances::ActiveRecord.new(database_model, database_record, mapping) }
let(:instance) { record_type.create!(sync_from).record }
it "creates a record in Salesforce from the passed database record's attributes" do
Salesforce.records << [salesforce_model, instance.Id]
expect(instance.Name).to_equal database_record.name
expect(instance.Example_Field__c).to_equal database_record.example
end
it "updates the database record with the Salesforce record's ID" do
Salesforce.records << [salesforce_model, instance.Id]
expect(sync_from.synced?).to_equal(true)
end
it "wipes the temporary SynchronizationId__c value used for upsert" do
Salesforce.records << [salesforce_model, instance.Id]
expect(instance.SynchronizationId__c).to_be_nil
end
describe "when a Salesforce record already exists for the database instance" do
it "uses the existing record" do
salesforce_id = Salesforce.create!(
salesforce_model,
"SynchronizationId__c" => sync_from.uuid,
)
expect(instance.Id).to_equal salesforce_id
end
end
end
describe "#find", :vcr do
let(:id) { Salesforce.create!(salesforce_model) }
it "finds existing records in Salesforce" do
expect(record_type.find(id)).to_be_instance_of Restforce::DB::Instances::Salesforce
end
it "returns nil when no matching record exists" do
expect(record_type.find("a001a000001E1vFAKE")).to_be_nil
end
describe "given a set of mapping conditions" do
let(:conditions) { ["Visible__c = TRUE"] }
describe "when a record meets the conditions" do
it "finds the record" do
expect(record_type.find(id)).to_be_instance_of Restforce::DB::Instances::Salesforce
end
end
describe "when a record does not meet the conditions" do
let(:id) { Salesforce.create!(salesforce_model, "Visible__c" => false) }
it "does not find the record" do
expect(record_type.find(id)).to_be_nil
end
end
end
end
describe "#all", :vcr do
let(:id) { Salesforce.create!(salesforce_model) }
before { id }
it "returns a list of the existing records in Salesforce" do
record = record_type.all.first
expect(record).to_be_instance_of(Restforce::DB::Instances::Salesforce)
expect(record.id).to_equal(id)
end
end
end
|
#!/bin/bash
if [ "$ROOT_DIR" = "" ]; then
exit "Must set ROOT_DIR!"
else
. $ROOT_DIR/bin/include.sh
fi
SIMNAME=$1
INTERVAL=$2
SIMDIR=$RESEARCH_DIR/$SIMNAME
LOGFILE=$SIMDIR/intraday.log
#JAVA_ARGS="-Xmx1500m"
JAVA_ARGS=""
rm -f $SIMDIR/calcres_intraday/*
$JAVA $JAVA_ARGS ase.apps.IntradayCalcresGenerator $SIMDIR $INTERVAL 2> $LOGFILE
exit $?
|
append([], A, A).
append([H|T], A, [H|R]) :-
append(T, A, R).
partition([H|T],Pivot,[H|LessThan],GreaterThan) :- H=<Pivot,
partition(T,Pivot,LessThan,GreaterThan).
partition([H|T],Pivot,LessThan,[H|GreaterThan]) :- H > Pivot,
partition(T,Pivot,LessThan,GreaterThan).
partition([],_,[],[]).
quicksort([],[]).
quicksort([H|T],Out) :- quicksortDiff([H|T],Out-[]).
quicksortDiff([],L-L).
quicksortDiff([H|T],S-E) :- partition(T,H,Left,Right),
quicksortDiff(Left,S-[H|L]),
quicksortDiff(Right,L-E).
|
<?php
namespace App\Http\Controllers;
use App\typeAbonner;
use Illuminate\Http\Request;
class TypeAbonnerController extends Controller
{
public function createType(Request $request) {
$request->validate([
'type' => 'required|string',
]);
$type = new typeAbonner();
$type->type = $request->type;
$type->save();
return response()->json(array('message'=>'type crée','success'=>true,200));
}
public function listType() {
$liste = typeAbonner::all();
return response()->json($liste);
}
}
|
<?php
use fr\dieunelson\HeaderManager;
use fr\dieunelson\webservices\Request;
use fr\dieunelson\webservices\Response;
use fr\dieunelson\webservices\Route;
use fr\dieunelson\webservices\hello\Hello;
use fr\dieunelson\webservices\hello\HelloCtrl;
use fr\dieunelson\webservices\hello\HelloValidator;
Route::get("/hello/:variable", function (Request $req, Response $res)
{
$hello = new Hello();
$controller = new HelloCtrl();
$view = $controller->hello($hello);
$res->send($view->render());
}, new HelloValidator());
Route::get("/", function (Request $req, Response $res)
{
HeaderManager::Location("./hello");
});
|
export function promptCustomizationUpload() {
$('#config-upload').trigger('click');
}
export function init() {
$('#config-upload').on('change', function(){
$(this).closest('form').submit();
});
$('#toggle-json').on('click', function(){
$('#customization-json').toggle();
if ($('#customization-json').is(':visible')) {
$(this).html('Hide JSON');
}
else {
$(this).html('Show JSON');
}
});
$('#btn-upload-customization').on('click', () => {
promptCustomizationUpload();
});
}
document.addEventListener('DOMContentLoaded', () => init());
|
package com.dev.nytimes.models.news
import android.os.Parcelable
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
import kotlinx.android.parcel.Parcelize
/**
* Sub data class for sample response.
*/
@Parcelize
data class AllNewsResultImages (
@SerializedName("url")
@Expose
val url : String,
@SerializedName("format")
@Expose
val format : String,
@SerializedName("height")
@Expose
val height : Int,
@SerializedName("width")
@Expose
val width : Int
): Parcelable
|
package it.nerdammer.spark
import it.nerdammer.spark.hbase.conversion.{FieldReaderConversions, FieldWriterConversions}
package object hbase
extends HBaseSparkContextConversions
with SaltingProviderConversions
with FieldReaderConversions
with FieldWriterConversions
with HBaseReaderBuilderConversions
with HBaseWriterBuilderConversions
|
#!/bin/bash
nbDb2MemberVms=$1
nbDb2CfVms=$2
acceleratedNetworkingOnDB2=$3
nbGlusterfsVms=3
sudo bash -c "echo \"192.168.0.5 jumpbox\" >> /etc/hosts"
sudo bash -c "echo \"192.168.0.40 wcli0\" >> /etc/hosts"
sudo bash -c "echo \"192.168.0.60 witn0\" >> /etc/hosts"
db2servers=()
for (( i=0; i<$nbDb2MemberVms; i++ ))
do
db2servers+=(192.168.0.2$i)
sudo bash -c "echo \"192.168.0.2${i} d${i}\" >> /etc/hosts"
done
for (( i=0; i<$nbDb2CfVms; i++ ))
do
db2servers+=(192.168.0.3$i)
sudo bash -c "echo \"192.168.0.3${i} cf${i}\" >> /etc/hosts"
done
if [ "$acceleratedNetworkingOnDB2" == "false" ]
then
# reboot DB2 servers so that they have the right kernel version
for db2srv in "${db2servers[@]}"
do
ssh $db2srv sudo shutdown -r now
done
fi
scp /tmp/fromg0_root.sh 192.168.0.10:/tmp/
ssh 192.168.0.10 sudo -n -u root -s "bash -v /tmp/fromg0_root.sh"
for (( i=0; i<$nbGlusterfsVms; i++ ))
do
sudo bash -c "echo \"192.168.0.1${i} g${i}\" >> /etc/hosts"
done
# wait for the reboots or starts to finish
source /tmp/wait4reboots_src.sh
scp /tmp/fromd0getwwids_root.sh 192.168.0.20:/tmp/
ssh 192.168.0.20 sudo -n -u root -s "bash -v /tmp/fromd0getwwids_root.sh"
scp 192.168.0.20:/tmp/initwwids.sh /tmp/initwwids.sh
source /tmp/initwwids.sh
# setup multipath.conf
cat > /tmp/tmpcmd002.sh <<EOF
uname -r
df
cat > /etc/multipath.conf <<EOF2
defaults {
user_friendly_names no
bindings_file /etc/multipath/bindings4db2
max_fds max
flush_on_last_del yes
queue_without_daemon no
dev_loss_tmo infinity
fast_io_fail_tmo 5
}
blacklist {
wwid "SAdaptec*"
devnode "^hd[a-z]"
devnode "^(ram|raw|loop|fd|md|dm-|sr|scd|st)[0-9]*"
devnode "^sda[0-9]*"
devnode "^sdb[0-9]*"
devnode "^sdc[0-9]*"
devnode "^cciss.*"
}
multipaths {
multipath {
wwid ${wwiddb2data1}
alias db2data1
}
multipath {
wwid ${wwiddb2log1}
alias db2log1
}
multipath {
wwid ${wwiddb2shared}
alias db2shared
}
multipath {
wwid ${wwiddb2tieb}
alias db2tieb
}
}
EOF2
modprobe dm-multipath
systemctl start multipathd
chkconfig multipathd on
iscsiadm -m discovery -t sendtargets -p 192.168.1.10
iscsiadm -m node -L automatic
iscsiadm -m session
multipath -l
sleep 5s
lsblk
ls -ls /dev/mapper
EOF
for db2srv in "${db2servers[@]}"
do
scp /tmp/tmpcmd002.sh ${db2srv}:/tmp/
ssh $db2srv sudo bash -v /tmp/tmpcmd002.sh
done
scp /tmp/fromd0_root.sh 192.168.0.20:/tmp/
cat > /tmp/tmpcmd003.sh <<EOF
sudo -n -u root bash -c "bash -v /tmp/fromd0_root.sh \"$nbDb2MemberVms\" \"$nbDb2CfVms\""
EOF
cat /tmp/tmpcmd003.sh
scp /tmp/tmpcmd003.sh 192.168.0.20:/tmp/
ssh 192.168.0.20 bash /tmp/tmpcmd003.sh
|
using System;
namespace InitializingArray
{
class MainApp
{
static void Main(string[] args)
{
string[] array1 = new string[3]{ "안녕", "Hello", "Halo" };
Console.WriteLine("array1...");
foreach (string greeting in array1)
Console.WriteLine($" {greeting}");
string[] array2 = new string[] { "안녕", "Hello", "Halo" };
Console.WriteLine("\narray2...");
foreach (string greeting in array2)
Console.WriteLine($" {greeting}");
string[] array3 = { "안녕", "Hello", "Halo" };
Console.WriteLine("\narray3...");
foreach (string greeting in array3)
Console.WriteLine($" {greeting}");
}
}
}
|
#!/usr/bin/sh
count=`ls -t chr*.depth | wc -l | awk '{print $1}'`
for ((i=1;i<=$count;i++))
do
#fetch the file name
file=`ls -t chr*.depth | awk "NR==$i {print \$1}"`
#remove file ending from filename
chr=`echo $file | sed -e 's/.depth//'`
echo $file, $chr
#change R script to run on new file
sed -e "s/chrXL_group3b/$chr/g" coverage.R >$chr.R
#change shell script to run on each chromsome
sed -e "s/chrXL_group3b/$chr/g" run_coverage.sh >$chr.sh
#add executable privaleges
chmod +x $chr.sh
#submit to ASC queue
run_script $chr.sh
done
|
---
title: "Distribution"
excerpt: "분포 확인하기"
categories:
- SQL_Query_Book
tags:
- 1
last_modified_at: 2021-07-23
toc: true
toc_label: "Table Of Contents"
toc_icon: "cog"
toc_sticky: true
use_math: true
---
<br>
- SQL 에서 바로 분포를 확인하기 위한 쿼리를 작성해 보았습니다.
# [Conti] Round 를 이용한 확인
```sql
SELECT bucket,
count(*) AS cnt,
RPAD(' ', LN(COUNT(*)), '*') AS bar
FROM (
SELECT ROUND(cases, -2) AS bucket
FROM covid
)
GROUP BY bucket
ORDER BY bucket;
```

- 위와 같이 Round 를 활용하여, Continuous 한 값을 Binning 을 통해 Discrete 한 값으로 바꾼 후에, 히스토그램을 그릴 수 있습니다.
<br>
# [conti] Equal width bining
```sql
WITH bins AS(
SELECT min(cases) AS min_value
, ((max(cases)-min(cases)) / 1000) + 0.0000001 AS bin_width
FROM covid
)
SELECT bin,
count(*) AS cnt
FROM (
SELECT covid.cases,
floor((cases-bins.min_value) / bins.bin_width ) AS bin
FROM covid, bins
)
GROUP BY bin
ORDER BY bin ;
```

- 위와 같이, 히스토그램을 이용하여 Binnning 을 시도할 수 있습니다.
- width 는 max-mid /1000 이고 , bin 은 총 1000개가 형성됩니다.
|
# xnet
V port of Golang's [net/ip](https://github.com/golang/go/blob/master/src/net/ip.go).
## Development
```
$ git clone https://github.com/alexferl/xnet.git
$ cd xnet
$ make dev
```
To run the tests:
```
$ make test
```
|
Ill figure this out one day
20100206 13:47:49 nbsp Welcome to the Wiki. If you need help figuring this out, just ask. Users/JasonAller
|
package com.chinazyjr.githubapplication.ui.login.presenter
import android.app.Activity
import android.content.Context
import com.chinazyjr.haollyv2.base.BasePresenter
import com.chinazyjr.haollyv2.base.IBaseView
/**
* Created by shanghai on 2018/4/26.
*/
class EmptyPresenter(mContext: Activity) : BasePresenter<IBaseView>(mContext) {
}
|
// #Sireum
package art
import org.sireum._
import art.Art.BridgeId
@ext object ArtTimer {
def setTimeout(bridgeId: BridgeId, eventId: String, wait: Art.Time, autoClear: B, callback: () => Unit): Unit = $
def clearTimeout(eventId: String): Unit = $
}
|
library computed_value_notifier;
import 'package:flutter/foundation.dart';
/// A class that can be used to derive a value based on data from another
/// Listenable or Listenables.
///
/// The value will be recomputed when the provided [_listenable] notifies the
/// listeners that values have changed.
///
/// ### Simple Example
///
/// ```dart
/// final email = ValueNotifier<String>('a');
///
/// // Determine whether or not the email is valid using a (hacky) validator.
/// final emailValid = ComputedValueNotifier(
/// email,
/// () => email.value.contains('@'),
/// );
///
/// // The function provided to ComputedValueNotifier is immediately executed,
/// // and the computed value is available synchronously.
/// print(emailValid.value); // prints 'false'.
///
/// // When the email ValueNotifier is changed, the function will be run again!
/// email.value = 'a@b.com';
/// print(emailValid.value); // prints 'true'.
/// ```
///
/// ### Deriving data from multiple listenables
///
/// In this case, we can use the `Lisetenable.merge` function provided by
/// Flutter to merge several variables.
///
/// ```dart
/// final email = ValueNotifier<String>('');
/// final password = ValueNotifier<String>('');
///
/// // Determine whether the email is valid, and make that a Listenable!
/// final emailValid = ComputedValueNotifier<bool>(
/// email,
/// () => email.value.contains('@'),
/// );
///
/// // Determine whether the password is valid, and make that a Listenable!
/// final passwordValid = ComputedValueNotifier<bool>(
/// password,
/// () => password.value.length >= 6,
/// );
///
/// // Now, we will only enable the "Login Button" when the email and
/// // password are valid. To do so, we can listen to the emailValid and
/// // passwordValid ComputedValueNotifiers.
/// final loginButtonEnabled = ComputedValueNotifier<bool>(
/// Listenable.merge([emailValid, passwordValid]),
/// () => emailValid.value && passwordValid.value,
/// );
///
/// // Update the email
/// print(emailValid.value); // false
/// print(loginButtonEnabled.value); // false
/// email.value = 'a@b.com';
/// print(emailValid.value); // true
/// print(loginButtonEnabled.value); // false
///
/// // Update the password
/// print(passwordValid.value); // false
/// password.value = '123456';
/// print(passwordValid.value); // true
/// print(loginButtonEnabled.value); // true
/// ```
class ComputedValueNotifier<T> extends ChangeNotifier
implements ValueListenable<T> {
final Listenable _listenable;
final T Function() _compute;
T _value;
/// The current value stored in this notifier.
@override
T get value => _value;
/// Computed [value] based on another [listenable]
ComputedValueNotifier({
required Listenable listenable,
required T Function() compute,
}) : _listenable = listenable,
_compute = compute,
_value = compute() {
_listenable.addListener(_updateValue);
}
/// When the value is replaced with something that is not equal to the old
/// value as evaluated by the equality operator ==, this class notifies its
/// listeners.
void _updateValue() {
final newValue = _compute();
if (newValue == _value) return;
_value = newValue;
notifyListeners();
}
@override
String toString() => '${describeIdentity(this)}($_value)';
@override
void dispose() {
_listenable.removeListener(_updateValue);
super.dispose();
}
}
|
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/3/28
* Time: 23:41
*/
namespace app\platformmanage\controller;
use think\Controller;
use think\db;
class Notesbg extends Controller
{
/**
* * 功能描述:显示遊記管理页面/可以模糊查询加分页
* 参数:无
* 返回:无
* 作者:min H
* 时间:18-4-4
**/
public function notesbg()
{
$search=input('?post.input_search')?input('post.input_search'):'';
// $join=[
// ['store_hotel_order a','a.huId=b.hId']
// ];
$where=[];
$where['title']=['like',"%".$search."%"];
$getnotes=db('user_story')->where($where)->paginate(4);
// 获取分页显示
$page = $getnotes->render();
$this->assign('notes',$getnotes);
$this->assign('page', $page);
return $this->fetch() ;
}
/**
* * 功能描述:审核游记内容
* 参数:无
* 返回:无
* 作者:min H
* 时间:18-4-9
**/
public function notesAudit(){
$hotelid=input('?post.nowhotelid') ?input('post.nowhotelid'):'';
$updateaudit=db('store_shotel')->where('hId',$hotelid)->update(['audit'=>1]);
if($updateaudit) {
echo 1;
}
}
}
|
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using SalesProject.Domain.Constants.Database;
using SalesProject.Domain.Entities;
namespace SalesProject.Infra.Mapping
{
public class InvoiceMap : IEntityTypeConfiguration<Invoice>
{
public void Configure(EntityTypeBuilder<Invoice> builder)
{
builder.Property(i => i.Id).
ValueGeneratedOnAdd().
HasColumnType("uniqueidentifier").
HasComment(InvoiceConstants.Id);
builder.Property(i => i.ReleaseDate).
HasColumnName(InvoiceConstants.FieldReleaseDate).
HasColumnType("date").
IsRequired().
HasComment(InvoiceConstants.ReleaseDate);
builder.Property(i => i.OriginOperation).
HasColumnName(InvoiceConstants.FieldOriginOperation).
HasMaxLength(150).
HasColumnType("varchar(150)").
IsRequired().
HasComment(InvoiceConstants.OriginOperation);
builder.Property(i => i.BaseCalcIcms).
HasColumnName(InvoiceConstants.FieldBaseCalcIcms).
HasColumnType("money").
IsRequired().
HasComment(InvoiceConstants.BaseCalcIcms);
builder.Property(i => i.TotalIcms).
HasColumnName(InvoiceConstants.FieldTotalIcms).
HasColumnType("money").
IsRequired().
HasComment(InvoiceConstants.TotalIcms);
builder.Property(i => i.TotalProducts).
HasColumnName(InvoiceConstants.FieldTotalProducts).
HasColumnType("money").
IsRequired().
HasComment(InvoiceConstants.TotalProducts);
builder.Property(i => i.TotalInvoice).
HasColumnName(InvoiceConstants.FieldTotalInvoice).
HasColumnType("money").
IsRequired().
HasComment(InvoiceConstants.TotalInvoice);
builder.Property(c => c.IntegratedPlugNotasApi).
HasColumnName(InvoiceConstants.FieldIntegratedPlugNotasApi).
HasMaxLength(1).
HasColumnType("varchar(1)").
IsRequired().
HasComment(InvoiceConstants.IntegratedPlugNotasApi);
builder.Property(c => c.IdPlugNotasIntegration).
HasColumnName(InvoiceConstants.FieldIdPlugNotasIntegration).
HasMaxLength(40).
HasColumnType("varchar(40)").
IsRequired(false).
HasComment(InvoiceConstants.IdPlugNotasIntegration);
builder.Property(i => i.OrderId).
HasColumnName(InvoiceConstants.FieldOrderId).
IsRequired(false).
HasComment(InvoiceConstants.OrderId);
builder.Ignore(i => i.Notifications);
builder.Ignore(i => i.Valid);
builder.HasMany(i => i.InvoiceLines).WithOne();
builder.HasOne(i => i.Order)
.WithOne()
.OnDelete(DeleteBehavior.SetNull);
builder.HasKey(i => i.Id);
builder.ToTable(InvoiceConstants.TableInvoice);
}
}
}
|
<?php
namespace Shopsys\FrameworkBundle\Model\Product\Availability;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Prezent\Doctrine\Translatable\Annotation as Prezent;
use Shopsys\FrameworkBundle\Model\Localization\AbstractTranslatableEntity;
/**
* @ORM\Table(name="availabilities")
* @ORM\Entity
*/
class Availability extends AbstractTranslatableEntity
{
/**
* @var int
*
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* @var \Shopsys\FrameworkBundle\Model\Product\Availability\AvailabilityTranslation[]
*
* @Prezent\Translations(targetEntity="Shopsys\FrameworkBundle\Model\Product\Availability\AvailabilityTranslation")
*/
protected $translations;
/**
* @var int|null
*
* @ORM\Column(type="integer", nullable=true)
*/
protected $dispatchTime;
/**
* @param \Shopsys\FrameworkBundle\Model\Product\Availability\AvailabilityData $availabilityData
*/
public function __construct(AvailabilityData $availabilityData)
{
$this->translations = new ArrayCollection();
$this->setTranslations($availabilityData);
$this->dispatchTime = $availabilityData->dispatchTime;
}
/**
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* @param string|null $locale
* @return string
*/
public function getName($locale = null)
{
return $this->translation($locale)->getName();
}
/**
* @param \Shopsys\FrameworkBundle\Model\Product\Availability\AvailabilityData $availabilityData
*/
protected function setTranslations(AvailabilityData $availabilityData)
{
foreach ($availabilityData->name as $locale => $name) {
$this->translation($locale)->setName($name);
}
}
/**
* @return \Shopsys\FrameworkBundle\Model\Product\Availability\AvailabilityTranslation
*/
protected function createTranslation()
{
return new AvailabilityTranslation();
}
/**
* @param \Shopsys\FrameworkBundle\Model\Product\Availability\AvailabilityData $availabilityData
*/
public function edit(AvailabilityData $availabilityData)
{
$this->setTranslations($availabilityData);
$this->dispatchTime = $availabilityData->dispatchTime;
}
/**
* @return int|null
*/
public function getDispatchTime()
{
return $this->dispatchTime;
}
}
|
-- phpMyAdmin SQL Dump
-- version 4.6.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1:3306
-- Generation Time: Jan 02, 2017 at 04:52 PM
-- Server version: 5.6.33
-- PHP Version: 5.6.27
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `yii2bsc`
--
-- --------------------------------------------------------
--
-- Table structure for table `kategoriruangan`
--
CREATE TABLE `kategoriruangan` (
`idkategoriruangan` int(11) NOT NULL,
`nama_kategori` varchar(45) DEFAULT NULL,
`detail_kategori` text
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Table structure for table `kegiatan`
--
CREATE TABLE `kegiatan` (
`idkegiatan` int(11) NOT NULL,
`nama_kegiatan` varchar(45) DEFAULT NULL,
`pengguna` int(11) DEFAULT NULL,
`mulai_kegiatan` datetime DEFAULT NULL,
`selesai_kegiatan` datetime DEFAULT NULL,
`ruangan_kegiatan` int(11) DEFAULT NULL,
`keterangan` text
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Table structure for table `pengguna`
--
CREATE TABLE `pengguna` (
`idpengguna` int(11) NOT NULL,
`nama_pengguna` varchar(45) NOT NULL,
`bagian_pengguna` enum('Internal','Eksternal') NOT NULL DEFAULT 'Internal',
`keterangan` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Table structure for table `ruangan`
--
CREATE TABLE `ruangan` (
`idruangan` int(11) NOT NULL,
`kategori_ruangan` int(11) DEFAULT NULL,
`nama_ruangan` varchar(45) DEFAULT NULL,
`kapasitas_ruangan` int(11) DEFAULT NULL,
`fasilitas_ruangan` text
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`user_id` int(11) NOT NULL,
`username` varchar(30) NOT NULL,
`password` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `kategoriruangan`
--
ALTER TABLE `kategoriruangan`
ADD PRIMARY KEY (`idkategoriruangan`);
--
-- Indexes for table `kegiatan`
--
ALTER TABLE `kegiatan`
ADD PRIMARY KEY (`idkegiatan`),
ADD KEY `pengguna_idx` (`pengguna`),
ADD KEY `ruangan_idx` (`ruangan_kegiatan`);
--
-- Indexes for table `pengguna`
--
ALTER TABLE `pengguna`
ADD PRIMARY KEY (`idpengguna`);
--
-- Indexes for table `ruangan`
--
ALTER TABLE `ruangan`
ADD PRIMARY KEY (`idruangan`),
ADD KEY `kategori_idx` (`kategori_ruangan`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `kategoriruangan`
--
ALTER TABLE `kategoriruangan`
MODIFY `idkategoriruangan` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `kegiatan`
--
ALTER TABLE `kegiatan`
MODIFY `idkegiatan` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `pengguna`
--
ALTER TABLE `pengguna`
MODIFY `idpengguna` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `ruangan`
--
ALTER TABLE `ruangan`
MODIFY `idruangan` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
using System;
using Xunit;
using TowersOfHanoi;
namespace HanoiTestsct1
{
public class UnitTest1
{
[Fact]
public void CanPeek()
{
//Arrange / Act
MyStack testStack = new MyStack(new Node() { Value = 5 });
//Assert
Assert.Equal("5", testStack.Peek().Value.ToString());
}
[Fact]
public void CanBuildNode()
{
//Arrange / Act
Node testNode = new Node() { Value = 5 };
//Assert
Assert.Equal("5", testNode.Value.ToString());
}
[Fact]
public void CanBuildStack()
{
//Arrange / Act
MyStack testStack = new MyStack(new Node() { Value = 5 });
testStack.Push(new Node() { Value = 8 });
testStack.Push(new Node() { Value = 14 });
testStack.Pop();
//Assert
Assert.Equal("8", testStack.Peek().Value.ToString());
}
}
}
|
CONN xmlusr/xmlusr
BEGIN
DBMS_XMLSCHEMA.registerschema(
'emp.xsd',
'<xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xdb="http://xmlns.oracle.com/xdb">
<xs:element name="EMPLOYEE" type="EMP_TYP"/>
<xs:complexType name="EMP_TYP" xdb:SQLType="EMP_T"
xdb:maintainDOM="false">
<xs:sequence>
<xs:element name="ENAME" type ="enameType" xdb:SQLName="ENAME"
xdb:SQLType="VARCHAR2"/>
<xs:element name="SALARY" type ="salaryType" xdb:SQLName="SALARY"
xdb:SQLType="NUMBER"/>
</xs:sequence>
<xs:attribute name="id" type="xs:positiveInteger"
xdb:SQLName="EMPNO"
xdb:SQLType="NUMBER"/>
</xs:complexType>
<xs:simpleType name="salaryType">
<xs:restriction base="xs:double">
<xs:maxExclusive value="100000"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="enameType">
<xs:restriction base="xs:string">
<xs:minLength value="2"/>
<xs:maxLength value="30"/>
</xs:restriction>
</xs:simpleType>
</xs:schema>',
TRUE,
TRUE,
FALSE,
FALSE
);
END;
/
|
var GLOBALVAR = window.GLOBALVAR || {};
GLOBALVAR.credits = {};
GLOBALVAR.holidays = {};
require.config({
paths: {
'jquery': 'vendor/jquery.min',
'backbone': 'vendor/backbone-min',
'underscore': 'vendor/underscore-min',
'html5shiv': "vendor/html5shiv.min",
'text': 'vendor/text',
'handlebars':'vendor/handlebars.min'
,templates: '../templates'
},
shim: {
jquery: {
exports: "$"
},
underscore: {
exports: "_"
},
backbone: {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
},
html5shiv: {
exports: "html5shiv"
},
handlebars: {
deps: ['html5shiv'],
exports: "Handlebars"
},
},
deps: ['require'],
});
{require([
""]
, function () {
console.log("require.config is loaded");
});
}
// {require([
// "test"]
// , function (test) {
// });
//}
|
---
layout: reference
title: GetString.srv
package: oort_msgs
category: service-message
tags:
- oort
---
## Message Definition
```
---
string data
```
## Arguments
#### `data`
Returned string.
## Related Documentation
``/oort_ros_mapping/map/name``
``/oort_ros_mapping/map/state``
|
module DashboardTimeline
extend ActiveSupport::Concern
def setup_timeline(school_observations)
school_observations.visible.order('at DESC').limit(10)
end
end
|
package ru.intertrust.cm.core.gui.impl.markup.DialogBoxWidget;
/**
* Created with IntelliJ IDEA.
* User: lvov
* Date: 24.10.13
* Time: 14:49
* To change this template use File | Settings | File Templates.
*/
public class Entity {
boolean aBoolean;
String string;
String pop;
public Entity(boolean aBoolean, String string, String pop) {
this.aBoolean = aBoolean;
this.string = string;
this.pop = pop;
}
public String getPop() {
return pop;
}
public boolean isaBoolean() {
return aBoolean;
}
public String getString() {
return string;
}
public void setaBoolean(boolean aBoolean) {
this.aBoolean = aBoolean;
}
public void setString(String string) {
this.string = string;
}
public void setPop(String pop) {
this.pop = pop;
}
}
|
{{rimport}}('__init__.r')
infile = {{i.infile | R}}
outfile = {{o.outfile | R}}
params = {{args.params | R}}
inopts = {{args.inopts | R}}
inparams = list(
file = infile,
header = as.logical(inopts$cnames),
row.names = if (as.logical(inopts$rnames)) 1 else NULL,
skip = if (is.null(inopts$skip)) 0 else as.numeric(inopts$skip),
sep = inopts$delimit
)
mat = do.call(read.table.nodup, c(inparams, params))
{% if isinstance(args.code, list) %}
{% for c in args.code %}
{{c}}
{% endfor %}
{% else %}
{{args.code}}
{% endif %}
outparams = list(
x = mat,
file = outfile,
sep = inopts$delimit,
quote = F,
col.names = as.logical(inopts$cnames),
row.names = as.logical(inopts$rnames)
)
do.call(write.table, outparams)
|
package de.quinesoft.checklist.model
import enumeratum._
import io.circe.Codec
import io.circe.generic.semiauto._
import scala.collection.immutable
sealed trait Role extends EnumEntry
object Role extends Enum[Role] with CirceEnum[Role] {
case object Admin extends Role
case object User extends Role
override def values: immutable.IndexedSeq[Role] = findValues
}
case class User(name: String, password: String, lists: List[ToDoList], role: Role)
object User {
implicit val userCodec: Codec[User] = deriveCodec[User]
}
|
<?php
namespace PonyFire\Core;
use Exception;
use PonyFire\Http\Request;
use PonyFire\Core\Exceptions\RouterProcessorException;
use PonyFire\Router\Exceptions\InvalidArgumentException;
use FastRoute\Dispatcher;
class RouterProcessor
{
/**
* @var string $method
*/
protected string $method;
/**
* @var string
*/
protected string $uri;
/**
* @var \FastRoute\Dispatcher
*/
protected Dispatcher $dispatcher;
public function __construct()
{
$this->method = '';
$this->uri = '';
}
/**
* @param string $method Metode HTTP Request
*
* @return \PonyFire\Core\RouterProcessor
*/
public function setMethod(string $method): RouterProcessor
{
$this->method = $method;
return $this;
}
/**
* @param string $uri URI yang di input user
*
* @return \PonyFire\Core\RouterProcessor
*/
public function setUri(string $uri): RouterProcessor
{
$this->uri = $uri;
return $this;
}
/**
* @param \FastRoute\Dispatcher
*
* @return \PonyFire\Core\RouterProcessor
*/
public function setDispatcher(Dispatcher $dispatcher): RouterProcessor
{
$this->dispatcher = $dispatcher;
return $this;
}
public function execute()
{
$routeInfo = $this->dispatcher->dispatch(
$this->method,
$this->uri
);
switch ($routeInfo[0])
{
case Dispatcher::NOT_FOUND:
// Memberikan response page not found
break;
case Dispatcher::METHOD_NOT_ALLOWED:
break;
// Memberikan response page not found
case Dispatcher::FOUND:
// Eksekusi handler
$handler = $routeInfo[0];
$params = $routeInfo[1];
// TODO: Menambahkan $params pada request
$this->processHandler($handler, $params);
break;
}
}
/**
* Memproses handler yang sudah disediakan
*
* @param string|callback $handler
* @param array $params
*
* @return void
*/
protected function processHandler($handler, array $params)
{
// Jika handler bertipe string
// Maka class controller akan di eksekusi
if (is_string($handler))
{
/** @var \PonyFire\Core\ControllerProcessor */
$controller = new ControllerProcessor();
$controllerDelimiter = '::';
$handler = explode($controllerDelimiter, $handler);
$class = $handler[0];
$method = $handler[1] ?? 'index';
// Mengeksekusi controller
$controller->call($class, $method);
}
// Jika handler bertipe callable/function
// Maka $handler akan dipanggil langsung sebagai callable
elseif (is_callable($handler))
{
$controller->callCallable($handler);
}
else
{
throw new InvalidArgumentException();
}
}
}
|
// SPDX-License-Identifier: Apache-2.0
package firrtlTests
import firrtl.testutils._
class NegSpec extends FirrtlFlatSpec {
"unsigned neg" should "be correct and lint-clean" in {
val input =
"""|circuit UnsignedNeg :
| module UnsignedNeg :
| input in : UInt<8>
| output out : SInt
| out <= neg(in)
|""".stripMargin
val expected =
"""|module UnsignedNegRef(
| input [7:0] in,
| output [8:0] out
|);
| assign out = 8'd0 - in;
|endmodule""".stripMargin
firrtlEquivalenceWithVerilog(input, expected)
lintVerilog(compileToVerilog(input))
}
"signed neg" should "be correct and lint-clean" in {
val input =
"""|circuit SignedNeg :
| module SignedNeg :
| input in : SInt<8>
| output out : SInt
| out <= neg(in)
|""".stripMargin
// -$signed(in) is a lint warning in Verilator but is functionally correct
val expected =
"""|module SignedNegRef(
| input [7:0] in,
| output [8:0] out
|);
| assign out = -$signed(in);
|endmodule""".stripMargin
firrtlEquivalenceWithVerilog(input, expected)
lintVerilog(compileToVerilog(input))
}
}
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class BuildingSpacePrice extends Model
{
/**
* {@inheritDoc}
*/
public static $types = [
'hourly' => '/jam',
'daily' => '/hari',
'weekly' => '/minggu',
'monthly' => '/bulan',
'yearly' => '/tahun',
];
/**
* Get formatted price on rupiah.
*
* @return string
*/
public function getFormattedPriceAttribute()
{
return 'Rp.' . number_format($this->price);
}
/**
* An asset price belongs to asset.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function buildingSpace(): BelongsTo
{
return $this->belongsTo(BuildingSpace::class, 'building_space_id');
}
}
|
import { Request,
XHRBackend,
BrowserXhr,
ResponseOptions,
XSRFStrategy,
Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
export class AuthConnectionBackend extends XHRBackend {
constructor(private browserXhr: BrowserXhr,
private baseResponseOptions: ResponseOptions,
private xsrfStrategy: XSRFStrategy) {
super(browserXhr, baseResponseOptions, xsrfStrategy);
}
createConnection(request: Request) {
let xhrConnection = super.createConnection(request);
xhrConnection.response = xhrConnection.response.catch((error: Response) => {
if ((error.status === 401 || error.status === 403)
&& (window.location.href.match(/\?/g) || []).length < 2) {
console.warn('The authentication session has expired or the '
+ 'user is not authorized for this content. Forcing refresh '
+ 'of the current page.');
window.location.href = window.location.href + '?'
+ new Date().getMilliseconds();
window.location.reload();
}
return Observable.throw(error);
});
return xhrConnection;
}
}
|
use specs::prelude::*;
use specs::world::EntitiesRes;
use paddlers_shared_lib::prelude::*;
use paddlers_shared_lib::game_mechanics::town::*;
use crate::prelude::*;
use crate::game::town::Town;
use crate::net::graphql::query_types::HoboEffect;
use crate::game::units::attackers::insert_duck;
pub (crate) fn insert_buildings(town: &mut Town, entities: &EntitiesRes, lazy: &LazyUpdate) {
town.insert_new_building(entities, lazy, (0,0), BuildingType::BlueFlowers);
town.insert_new_building(entities, lazy, (0,1), BuildingType::BlueFlowers);
town.insert_new_building(entities, lazy, (0,2), BuildingType::BlueFlowers);
town.insert_new_building(entities, lazy, (1,0), BuildingType::BlueFlowers);
town.insert_new_building(entities, lazy, (1,1), BuildingType::BlueFlowers);
town.insert_new_building(entities, lazy, (1,2), BuildingType::BlueFlowers);
town.insert_new_building(entities, lazy, (2,1), BuildingType::PresentA);
town.insert_new_building(entities, lazy, (4,1), BuildingType::Temple);
town.insert_new_building(entities, lazy, (6,1), BuildingType::PresentB);
town.insert_new_building(entities, lazy, (7,0), BuildingType::RedFlowers);
town.insert_new_building(entities, lazy, (7,1), BuildingType::RedFlowers);
town.insert_new_building(entities, lazy, (7,2), BuildingType::RedFlowers);
town.insert_new_building(entities, lazy, (8,0), BuildingType::RedFlowers);
town.insert_new_building(entities, lazy, (8,1), BuildingType::RedFlowers);
town.insert_new_building(entities, lazy, (8,2), BuildingType::RedFlowers);
town.insert_new_building(entities, lazy, (3,5), BuildingType::Tree);
town.insert_new_building(entities, lazy, (3,6), BuildingType::Tree);
town.insert_new_building(entities, lazy, (4,5), BuildingType::Tree);
town.insert_new_building(entities, lazy, (4,6), BuildingType::Tree);
town.insert_new_building(entities, lazy, (5,5), BuildingType::Tree);
town.insert_new_building(entities, lazy, (5,6), BuildingType::Tree);
town.insert_new_building(entities, lazy, (6,5), BuildingType::Tree);
town.insert_new_building(entities, lazy, (6,6), BuildingType::Tree);
town.insert_new_building(entities, lazy, (7,5), BuildingType::SawMill);
town.insert_new_building(entities, lazy, (7,6), BuildingType::BundlingStation);
}
pub (crate) fn insert_hobos(world : &mut World) -> PadlResult<()> {
let now = utc_now();
let ul = world.fetch::<ScreenResolution>().unit_length();
let w = TOWN_X as f32 * ul;
let x = w - ul * 0.6;
let y = TOWN_LANE_Y as f32 * ul;
let pos0 = (x,y);
let pos1 = (x - ul/2.0,y + ul/2.0);
let color = UnitColor::Camo;
let birth_time = now;
let speed = (-10.0, 0.0);
let hp = 3;
let netid = 1;
let effects = Vec::<HoboEffect>::new();
insert_duck(world, pos0, color, birth_time, speed, hp, ul, netid, &effects)?;
insert_duck(world, pos1, color, birth_time, speed, hp, ul, netid, &effects)?;
let dt = 5_000_000;
let birth_time = birth_time - dt;
insert_duck(world, pos0, color, birth_time, speed, hp, ul, netid, &effects)?;
insert_duck(world, pos1, color, birth_time, speed, hp, ul, netid, &effects)?;
let birth_time = birth_time - dt;
insert_duck(world, pos0, color, birth_time, speed, hp, ul, netid, &effects)?;
insert_duck(world, pos1, color, birth_time, speed, hp, ul, netid, &effects)?;
let birth_time = birth_time - dt;
insert_duck(world, pos0, color, birth_time, speed, hp, ul, netid, &effects)?;
insert_duck(world, pos1, color, birth_time, speed, hp, ul, netid, &effects)?;
let birth_time = birth_time - dt;
insert_duck(world, pos0, color, birth_time, speed, hp, ul, netid, &effects)?;
insert_duck(world, pos1, color, birth_time, speed, hp, ul, netid, &effects)?;
let birth_time = birth_time - 10*dt;
let color0 = UnitColor::Yellow;
let color1 = UnitColor::White;
insert_duck(world, pos0, color0, birth_time, speed, hp, ul, netid, &effects)?;
insert_duck(world, pos1, color1, birth_time, speed, hp, ul, netid, &effects)?;
let birth_time = birth_time - dt;
insert_duck(world, pos0, color1, birth_time, speed, hp, ul, netid, &effects)?;
insert_duck(world, pos1, color0, birth_time, speed, hp, ul, netid, &effects)?;
let birth_time = birth_time - dt;
insert_duck(world, pos0, color0, birth_time, speed, hp, ul, netid, &effects)?;
insert_duck(world, pos1, color1, birth_time, speed, hp, ul, netid, &effects)?;
let birth_time = birth_time - dt;
insert_duck(world, pos0, color1, birth_time, speed, hp, ul, netid, &effects)?;
insert_duck(world, pos1, color0, birth_time, speed, hp, ul, netid, &effects)?;
let birth_time = birth_time - 2*dt;
insert_duck(world, pos0, color0, birth_time, speed, hp, ul, netid, &effects)?;
insert_duck(world, pos1, color1, birth_time, speed, hp, ul, netid, &effects)?;
let birth_time = birth_time - dt;
insert_duck(world, pos0, color1, birth_time, speed, hp, ul, netid, &effects)?;
insert_duck(world, pos1, color0, birth_time, speed, hp, ul, netid, &effects)?;
Ok(())
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.