func_before
stringlengths 12
22.8k
| func_after
stringlengths 11
24.7k
| commit_msg
stringlengths 1
32.6k
⌀ | commit_url
stringlengths 48
124
| cve_id
stringclasses 530
values | cwe_id
stringclasses 134
values | file_name
stringlengths 4
244
| vulnerability_score
int64 0
4
| extension
stringclasses 6
values | is_test
bool 1
class | date
stringdate 1999-11-10 02:42:49
2024-01-29 16:00:57
⌀ |
|---|---|---|---|---|---|---|---|---|---|---|
function h(n,t){for(var r=-1,e=null==n?0:n.length;++r<e;)if(t(n[r],r,n))return true;return false}
|
function h(n,t){for(var r=-1,e=null==n?0:n.length;++r<e;)if(t(n[r],r,n))return!0;return!1}
|
Update vendor libs
|
https://github.com/cockpit-hq/cockpit/commit/690016208850f2d788ebc3c67884d4c692587eb8
|
CVE-2023-1160
|
['CWE-1103']
|
modules/App/assets/vendor/lodash.js
| 0
|
js
| false
|
2023-02-22T01:10:02Z
|
private CompletableFuture<String> authorize() {
HttpClient.DerivedClientBuilder builder = client.newBuilder();
builder.addOrReplaceInterceptor(TokenRefreshInterceptor.NAME, null);
HttpClient clone = builder.build();
URL url;
try {
url = new URL(URLUtils.join(config.getMasterUrl(), AUTHORIZATION_SERVER_PATH));
} catch (MalformedURLException e) {
throw KubernetesClientException.launderThrowable(e);
}
CompletableFuture<HttpResponse<String>> responseFuture = clone.sendAsync(clone.newHttpRequestBuilder().url(url).build(),
String.class);
return responseFuture.thenCompose(response -> {
if (!response.isSuccessful() || response.body() == null) {
throw new KubernetesClientException("Unexpected response (" + response.code() + " " + response.message() + ")");
}
String body = response.body();
try {
JsonNode jsonResponse = Serialization.jsonMapper().readTree(body);
String authorizationServer = jsonResponse.get("authorization_endpoint").asText();
URL authorizeQuery = new URL(authorizationServer + AUTHORIZE_QUERY);
String credential = HttpClientUtils.basicCredentials(config.getUsername(), config.getPassword());
return clone.sendAsync(client.newHttpRequestBuilder().url(authorizeQuery).setHeader(AUTHORIZATION, credential).build(),
String.class);
} catch (Exception e) {
throw KubernetesClientException.launderThrowable(e);
}
}).thenApply(response -> {
HttpResponse<?> responseOrPrevious = response.previousResponse().isPresent() ? response.previousResponse().get()
: response;
List<String> location = responseOrPrevious.headers(LOCATION);
String token = !location.isEmpty() ? location.get(0) : null;
if (token == null || token.isEmpty()) {
throw new KubernetesClientException("Unexpected response (" + responseOrPrevious.code() + " "
+ responseOrPrevious.message() + "), to the authorization request. Missing header:[" + LOCATION + "]!");
}
token = token.substring(token.indexOf(BEFORE_TOKEN) + BEFORE_TOKEN.length());
token = token.substring(0, token.indexOf(AFTER_TOKEN));
return token;
});
}
|
private CompletableFuture<String> authorize() {
HttpClient.DerivedClientBuilder builder = client.newBuilder();
builder.addOrReplaceInterceptor(TokenRefreshInterceptor.NAME, null);
HttpClient clone = builder.build();
URL url;
try {
url = new URL(URLUtils.join(config.getMasterUrl(), AUTHORIZATION_SERVER_PATH));
} catch (MalformedURLException e) {
throw KubernetesClientException.launderThrowable(e);
}
CompletableFuture<HttpResponse<String>> responseFuture = clone.sendAsync(clone.newHttpRequestBuilder().url(url).build(),
String.class);
return responseFuture.thenCompose(response -> {
if (!response.isSuccessful() || response.body() == null) {
throw new KubernetesClientException("Unexpected response (" + response.code() + " " + response.message() + ")");
}
String body = response.body();
try {
JsonNode jsonResponse = Serialization.jsonMapper().readTree(body);
String authorizationServer = jsonResponse.get("authorization_endpoint").asText();
URL authorizeQuery = new URL(authorizationServer + AUTHORIZE_QUERY);
String credential = HttpClientUtils.basicCredentials(config.getUsername(), config.getPassword());
return clone.sendAsync(client.newHttpRequestBuilder().url(authorizeQuery).setHeader(AUTHORIZATION, credential).build(),
String.class);
} catch (Exception e) {
throw KubernetesClientException.launderThrowable(e);
}
}).thenApply(response -> {
HttpResponse<?> responseOrPrevious = response.previousResponse().isPresent() ? response.previousResponse().get()
: response;
List<String> location = responseOrPrevious.headers(LOCATION);
String token = !location.isEmpty() ? location.get(0) : null;
if (token == null || token.isEmpty()) {
throw new KubernetesClientException("Unexpected response (" + responseOrPrevious.code() + " "
+ responseOrPrevious.message() + "), to the authorization request. Missing header:[" + LOCATION
+ "]. More than likely the username / password are not correct.");
}
token = token.substring(token.indexOf(BEFORE_TOKEN) + BEFORE_TOKEN.length());
token = token.substring(0, token.indexOf(AFTER_TOKEN));
return token;
});
}
|
review: address comments regarding test scenarios for PATCH
Signed-off-by: Marc Nuri <marc@marcnuri.com>
|
https://github.com/fabric8io/kubernetes-client/commit/88a9dde129610a174fa801eedcb0e87395138e70
| null | null |
openshift-client/src/main/java/io/fabric8/openshift/client/internal/OpenShiftOAuthInterceptor.java
| 0
|
java
| false
|
2022-12-20T15:30:05Z
|
function m(u,F){G=!1;var C=null!=u.Text&&u.Text.t?u.Text:null!=u.Value&&u.Value.t?u.Value:
null!=u.Lane_0&&u.Lane_0.t?u.Lane_0:null;null==C&&null!=u.State?u.State.t&&(C=u.State):null==C&&null!=u.Note?u.Note.t&&(C=u.Note):null==C&&null!=u.Title?u.Title.t&&(C=u.Title):u.t&&(C=u);null==C&&null!=u.TextAreas?null!=u.TextAreas.Text&&null!=u.TextAreas.Text.Value&&u.TextAreas.Text.Value.t&&(C=u.TextAreas.Text.Value):null==C&&null!=u.t0&&u.t0.t&&(C=u.t0);if(null!=C){if(null!=C.t){var t=C.t;t=t.replace(/\u2028/g,"\n");C=C.m;try{/ /.test(t)&&(LucidImporter.hasUnknownShapes=!0);for(var e=0;e<C.length;e++)if(0<
C[e].s||null!=C[e].e&&C[e].e<t.length||"t"==C[e].n||"ac"==C[e].n||"lk"==C[e].n){G=!0;break}if(G=G||F)return B(t,C,u)}catch(N){console.log(N)}t=t.replace(/</g,"<");return t=t.replace(/>/g,">")}if(null!=C.Value&&null!=C.Value.t)return C.Value.t=C.Value.t.replace(/</g,"<"),C.Value.t=C.Value.t.replace(/>/g,">"),C.Value.t}return""}
|
function m(u,F){G=!1;var D=null!=u.Text&&u.Text.t?u.Text:null!=u.Value&&u.Value.t?u.Value:
null!=u.Lane_0&&u.Lane_0.t?u.Lane_0:null;null==D&&null!=u.State?u.State.t&&(D=u.State):null==D&&null!=u.Note?u.Note.t&&(D=u.Note):null==D&&null!=u.Title?u.Title.t&&(D=u.Title):u.t&&(D=u);null==D&&null!=u.TextAreas?null!=u.TextAreas.Text&&null!=u.TextAreas.Text.Value&&u.TextAreas.Text.Value.t&&(D=u.TextAreas.Text.Value):null==D&&null!=u.t0&&u.t0.t&&(D=u.t0);if(null!=D){if(null!=D.t){var t=D.t;t=t.replace(/\u2028/g,"\n");D=D.m;try{/ /.test(t)&&(LucidImporter.hasUnknownShapes=!0);for(var e=0;e<D.length;e++)if(0<
D[e].s||null!=D[e].e&&D[e].e<t.length||"t"==D[e].n||"ac"==D[e].n||"lk"==D[e].n){G=!0;break}if(G=G||F)return B(t,D,u)}catch(O){console.log(O)}t=t.replace(/</g,"<");return t=t.replace(/>/g,">")}if(null!=D.Value&&null!=D.Value.t)return D.Value.t=D.Value.t.replace(/</g,"<"),D.Value.t=D.Value.t.replace(/>/g,">"),D.Value.t}return""}
|
21.6.3 release
|
https://github.com/jgraph/drawio/commit/1db2c2c653aa245d175d30c210239e3946bfcb95
|
CVE-2023-3973
|
['CWE-79']
|
src/main/webapp/js/extensions.min.js
| 0
|
js
| false
|
2023-07-18T17:20:28Z
|
void registerServer() {
VersionAgnosticCommandManager.get().registerServerCommand(
CommandManager.literal(Modget.NAMESPACE_SERVER)
.then(CommandManager.literal(COMMAND_PARTS[0])
.then(CommandManager.literal(COMMAND_PARTS[1])
.then(CommandManager.argument(COMMAND_PARTS[2], StringArgumentType.greedyString())
.requires(source -> source.hasPermissionLevel(PERMISSION_LEVEL))
.executes(context -> {
PlayerEntity player = context.getSource().getPlayer();
new StartThread(player, StringArgumentType.getString(context, COMMAND_PARTS[2])).start();
return 1;
})
)
)
)
);
}
|
void registerServer() {
VersionAgnosticServerCommandManager.get().register(
CommandManager.literal(Modget.NAMESPACE_SERVER)
.then(CommandManager.literal(COMMAND_PARTS[0])
.then(CommandManager.literal(COMMAND_PARTS[1])
.then(CommandManager.argument(COMMAND_PARTS[2], StringArgumentType.greedyString())
.requires(source -> source.hasPermissionLevel(PERMISSION_LEVEL))
.executes(context -> {
PlayerEntity player = context.getSource().getPlayer();
new StartThread(player, StringArgumentType.getString(context, COMMAND_PARTS[2])).start();
return 1;
})
)
)
)
);
}
|
Don't upload modget-core build artifacts
|
https://github.com/ReviversMC/modget-minecraft/commit/17f5235f98d112ceb086533d1c4901e7a2a3fce9
| null | null |
modget-core/src/main/java/com/github/reviversmc/modget/minecraft/command/ReposAddCommand.java
| 0
|
java
| false
|
2022-08-12T14:50:34Z
|
@Override
public void run() {
// The first time running this, need to setup the block list if a reset:
if ( position == 0 ) {
if ( runSetupCancelAutoResets() ) {
// If the reset should be canceled then just return, and that will
// terminate the reset. There is nothing else that needs to be done.
return;
}
}
List<MineTargetPrisonBlock> targetBlocks = mine.getMineTargetPrisonBlocks();
int pageEndPosition = position + getConfigAsyncResetPageSize();
while ( position < pageEndPosition ) {
int endIndex = position + getConfigSyncSubPageSlice();
if ( endIndex > targetBlocks.size() ) {
endIndex = targetBlocks.size();
pageEndPosition = endIndex;
}
// Isolate the sub-list from the main targetBlocks list:
List<MineTargetPrisonBlock> tBlocks = new ArrayList<>();
for (MineTargetPrisonBlock mtpb : targetBlocks.subList( position, endIndex )) {
tBlocks.add(mtpb);
}
int size = tBlocks.size();
position += size;
mine.getWorld().get().setBlocksSynchronously( tBlocks, resetType, getNanos() );
}
// Keep resubmitting this task until it is completed:
if ( position < targetBlocks.size() ) {
submitTaskSync();
}
else {
// Finished running the task and let it end:
runShutdown();
}
}
|
@Override
public void run() {
// The first time running this, need to setup the block list if a reset:
if ( position == 0 ) {
if ( runSetupCancelAutoResets() ) {
// If the reset should be canceled then just return, and that will
// terminate the reset. There is nothing else that needs to be done.
return;
}
}
List<MineTargetPrisonBlock> targetBlocks = mine.getMineTargetPrisonBlocks();
int pageEndPosition = position + getConfigAsyncResetPageSize();
while ( position < pageEndPosition ) {
int endIndex = position + getConfigSyncSubPageSlice();
if ( endIndex > targetBlocks.size() ) {
endIndex = targetBlocks.size();
pageEndPosition = endIndex;
}
// Isolate the sub-list from the main targetBlocks list:
List<MineTargetPrisonBlock> tBlocks = new ArrayList<>();
for (MineTargetPrisonBlock mtpb : targetBlocks.subList( position, endIndex )) {
tBlocks.add(mtpb);
}
int size = tBlocks.size();
position += size;
mine.getWorld().get().setBlocksSynchronously( tBlocks, resetType, getNanos() );
}
// Keep resubmitting this task until it is completed:
if ( position < targetBlocks.size() ) {
submitTaskAsyncInternalNextPage();
}
else {
// Finished running the task and let it end:
runShutdown();
}
}
|
Mine resets: Fixed an issue when dealing with zero-block resets on a very small mine, such as a one block mine in that the 5 second delay was preventing from rapid resets.
Bypass both 5 second cooldown on resets and blockmatching when 25 blocks or less for the mine size.
With running resets in async mode, with rapid resets for a one-block mine, the handling of the block breaks can occur out of order, which will trigger the block mismatch.
|
https://github.com/PrisonTeam/Prison/commit/a91dbdae13c0bf0874a9d6af970684f0b028a8ae
| null | null |
prison-mines/src/main/java/tech/mcprison/prison/mines/tasks/MinePagedResetAsyncTask.java
| 0
|
java
| false
|
2022-06-20T05:07:28Z
|
function ViewConsumable() {
Object(_var_www_lime25_limesurvey_assets_packages_questiongroup_node_modules_babel_runtime_corejs2_helpers_esm_classCallCheck__WEBPACK_IMPORTED_MODULE_7__["default"])(this, ViewConsumable);
/**
* Map of consumable elements. If {@link module:engine/view/element~Element element} is used as a key,
* {@link module:engine/conversion/viewconsumable~ViewElementConsumables ViewElementConsumables} instance is stored as value.
* For {@link module:engine/view/text~Text text nodes} and
* {@link module:engine/view/documentfragment~DocumentFragment document fragments} boolean value is stored as value.
*
* @protected
* @member {Map.<module:engine/conversion/viewconsumable~ViewElementConsumables|Boolean>}
*/
this._consumables = new Map();
}
|
function ViewConsumable() {
Object(_var_www_limedev_assets_packages_questiongroup_node_modules_babel_runtime_corejs2_helpers_esm_classCallCheck__WEBPACK_IMPORTED_MODULE_7__["default"])(this, ViewConsumable);
/**
* Map of consumable elements. If {@link module:engine/view/element~Element element} is used as a key,
* {@link module:engine/conversion/viewconsumable~ViewElementConsumables ViewElementConsumables} instance is stored as value.
* For {@link module:engine/view/text~Text text nodes} and
* {@link module:engine/view/documentfragment~DocumentFragment document fragments} boolean value is stored as value.
*
* @protected
* @member {Map.<module:engine/conversion/viewconsumable~ViewElementConsumables|Boolean>}
*/
this._consumables = new Map();
}
|
DEV: changed routes in vue.js part questiongroupedit.js and deleted old controller+views
|
https://github.com/LimeSurvey/LimeSurvey/commit/d7a309bf1a73e95187528982b9db7ec03fee6913
|
CVE-2020-23710
|
['CWE-79']
|
assets/packages/questiongroup/build/js/questiongroupedit.js
| 0
|
js
| false
|
2020-06-08T09:23:29Z
|
public void seslInitConfigurations(Context var1) {
ViewConfiguration var2 = ViewConfiguration.get(var1);
Resources var3 = var1.getResources();
this.mTouchSlop = var2.getScaledTouchSlop();
this.mSeslTouchSlop = var2.getScaledTouchSlop();
this.mSeslPagingTouchSlop = var2.getScaledPagingTouchSlop();
this.mScaledHorizontalScrollFactor = ViewConfigurationCompat.getScaledHorizontalScrollFactor(var2, var1);
this.mScaledVerticalScrollFactor = ViewConfigurationCompat.getScaledVerticalScrollFactor(var2, var1);
this.mMinFlingVelocity = var2.getScaledMinimumFlingVelocity();
this.mMaxFlingVelocity = var2.getScaledMaximumFlingVelocity();
this.mHoverTopAreaHeight = (int) (TypedValue.applyDimension(1, 25.0F, var3.getDisplayMetrics()) + 0.5F);
this.mHoverBottomAreaHeight = (int) (TypedValue.applyDimension(1, 25.0F, var3.getDisplayMetrics()) + 0.5F);
this.mGoToTopBottomPadding = var3.getDimensionPixelSize(R.dimen.sesl_go_to_top_scrollable_view_gap);
this.mGoToTopImmersiveBottomPadding = 0;
this.mGoToTopSize = var3.getDimensionPixelSize(R.dimen.sesl_go_to_top_scrollable_view_size);
this.mGoToTopElevation = var3.getDimensionPixelSize(R.dimen.sesl_go_to_top_elevation);
this.mNavigationBarHeight = var3.getDimensionPixelSize(R.dimen.sesl_navigation_bar_height);
}
|
public void seslInitConfigurations(Context var1) {
ViewConfiguration var2 = ViewConfiguration.get(var1);
Resources var3 = var1.getResources();
this.mTouchSlop = var2.getScaledTouchSlop();
this.mSeslTouchSlop = var2.getScaledTouchSlop();
this.mSeslPagingTouchSlop = var2.getScaledPagingTouchSlop();
this.mScaledHorizontalScrollFactor = ViewConfigurationCompat.getScaledHorizontalScrollFactor(var2, var1);
this.mScaledVerticalScrollFactor = ViewConfigurationCompat.getScaledVerticalScrollFactor(var2, var1);
this.mMinFlingVelocity = var2.getScaledMinimumFlingVelocity();
this.mMaxFlingVelocity = var2.getScaledMaximumFlingVelocity();
this.mHoverTopAreaHeight = (int) (TypedValue.applyDimension(1, 25.0F, var3.getDisplayMetrics()) + 0.5F);
this.mHoverBottomAreaHeight = (int) (TypedValue.applyDimension(1, 25.0F, var3.getDisplayMetrics()) + 0.5F);
this.mGoToTopBottomPadding = var3.getDimensionPixelSize(R.dimen.sesl_go_to_top_scrollable_view_gap);
this.mGoToTopImmersiveBottomPadding = 0;
this.mGoToTopSize = var3.getDimensionPixelSize(R.dimen.sesl_go_to_top_scrollable_view_size);
this.mGoToTopElevation = var3.getDimension(R.dimen.sesl_go_to_top_elevation);
this.mNavigationBarHeight = var3.getDimensionPixelSize(R.dimen.sesl_navigation_bar_height);
}
|
app: OneUI 4 DetailedColorPicker, GoToTop, Preference text size (#62)
* app: OneUI 4 DetailedColorPicker, GoToTop, Preference text size
Signed-off-by: BlackMesa123 <giangrecosalvo9@gmail.com>
* app: fix SwipeRefreshLayout scale down anim, night mode DetailedColorPicker tabs
Signed-off-by: BlackMesa123 <giangrecosalvo9@gmail.com>
* app: OneUI 4 fast scroller
Signed-off-by: BlackMesa123 <giangrecosalvo9@gmail.com>
* app/SwipeRefreshLayout: fix crashes
Signed-off-by: BlackMesa123 <giangrecosalvo9@gmail.com>
* app/oneuiexample: there's a SwipeRefreshLayout test in case you didn't notice
Signed-off-by: BlackMesa123 <giangrecosalvo9@gmail.com>
|
https://github.com/OneUIProject/OneUI-Design-Library/commit/7d82261d6821ece4c02d4e8157560a41156436eb
| null | null |
yanndroid/oneui/src/main/java/de/dlyt/yanndroid/oneui/view/RecyclerView.java
| 0
|
java
| false
| null |
function updateRole(userId, meetingId, role) {
check(userId, String);
check(meetingId, String);
check(role, String);
const selector = {
userId,
meetingId,
};
const modifier = {
$set: {
role,
},
};
try {
UsersPersistentData.update(selector, modifier);
} catch (err) {
Logger.error(`Updating users persistent data's role to the collection: ${err}`);
}
}
|
async function updateRole(userId, meetingId, role) {
check(userId, String);
check(meetingId, String);
check(role, String);
const selector = {
userId,
meetingId,
};
const modifier = {
$set: {
role,
},
};
try {
await UsersPersistentData.updateAsync(selector, modifier);
} catch (err) {
Logger.error(`Updating users persistent data's role to the collection: ${err}`);
}
}
|
Merge branch 'v2.6.x-release' of github.com:bigbluebutton/bigbluebutton into ssrf-fix
|
https://github.com/bigbluebutton/bigbluebutton/commit/22de2b49a5d218910923a1048bb73395e53c99bf
|
CVE-2023-33176
|
['CWE-918']
|
bigbluebutton-html5/imports/api/users-persistent-data/server/modifiers/updateRole.js
| 0
|
js
| false
|
2023-04-13T12:40:07Z
|
def invoke_defer_method(self):
"""Method to easily redefine triggers which are being used in child classes."""
trigger_start_time = utcnow()
self.defer(
trigger=KubernetesPodTrigger(
pod_name=self.pod.metadata.name,
pod_namespace=self.pod.metadata.namespace,
trigger_start_time=trigger_start_time,
kubernetes_conn_id=self.kubernetes_conn_id,
cluster_context=self.cluster_context,
config_dict=self._config_dict,
in_cluster=self.in_cluster,
poll_interval=self.poll_interval,
should_delete_pod=self.is_delete_operator_pod,
get_logs=self.get_logs,
startup_timeout=self.startup_timeout_seconds,
base_container_name=self.base_container_name,
),
method_name="execute_complete",
)
|
def invoke_defer_method(self):
"""Method to easily redefine triggers which are being used in child classes."""
trigger_start_time = utcnow()
self.defer(
trigger=KubernetesPodTrigger(
pod_name=self.pod.metadata.name,
pod_namespace=self.pod.metadata.namespace,
trigger_start_time=trigger_start_time,
kubernetes_conn_id=self.kubernetes_conn_id,
cluster_context=self.cluster_context,
config_file=self.config_file,
in_cluster=self.in_cluster,
poll_interval=self.poll_interval,
should_delete_pod=self.is_delete_operator_pod,
get_logs=self.get_logs,
startup_timeout=self.startup_timeout_seconds,
base_container_name=self.base_container_name,
),
method_name="execute_complete",
)
|
load the config file in the triggerer instead of loading it in the worker and pass it as a dict
|
https://github.com/apache/airflow/commit/e7b0e39557602ae215cc8722a97ec6b43df1c3ab
| null | null |
airflow/providers/cncf/kubernetes/operators/kubernetes_pod.py
| 0
|
py
| false
|
2023-02-21T00:28:45Z
|
function ImageTextAlternativeEditing() {
Object(_var_www_lime25_limesurvey_assets_packages_questiongroup_node_modules_babel_runtime_corejs2_helpers_esm_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, ImageTextAlternativeEditing);
return Object(_var_www_lime25_limesurvey_assets_packages_questiongroup_node_modules_babel_runtime_corejs2_helpers_esm_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__["default"])(this, Object(_var_www_lime25_limesurvey_assets_packages_questiongroup_node_modules_babel_runtime_corejs2_helpers_esm_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__["default"])(ImageTextAlternativeEditing).apply(this, arguments));
}
|
function ImageTextAlternativeEditing() {
Object(_var_www_limedev_assets_packages_questiongroup_node_modules_babel_runtime_corejs2_helpers_esm_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, ImageTextAlternativeEditing);
return Object(_var_www_limedev_assets_packages_questiongroup_node_modules_babel_runtime_corejs2_helpers_esm_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__["default"])(this, Object(_var_www_limedev_assets_packages_questiongroup_node_modules_babel_runtime_corejs2_helpers_esm_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__["default"])(ImageTextAlternativeEditing).apply(this, arguments));
}
|
DEV: changed routes in vue.js part questiongroupedit.js and deleted old controller+views
|
https://github.com/LimeSurvey/LimeSurvey/commit/d7a309bf1a73e95187528982b9db7ec03fee6913
|
CVE-2020-23710
|
['CWE-79']
|
assets/packages/questiongroup/build/js/questiongroupedit.js
| 0
|
js
| false
|
2020-06-08T09:23:29Z
|
def latest_partition(
cls,
table_name: str,
schema: Optional[str],
database: Database,
show_first: bool = False,
) -> Tuple[List[str], Optional[List[str]]]:
"""Returns col name and the latest (max) partition value for a table
:param table_name: the name of the table
:param schema: schema / database / namespace
:param database: database query will be run against
:type database: models.Database
:param show_first: displays the value for the first partitioning key
if there are many partitioning keys
:type show_first: bool
>>> latest_partition('foo_table')
(['ds'], ('2018-01-01',))
"""
indexes = database.get_indexes(table_name, schema)
if not indexes:
raise SupersetTemplateException(
f"Error getting partition for {schema}.{table_name}. "
"Verify that this table has a partition."
)
if len(indexes[0]["column_names"]) < 1:
raise SupersetTemplateException(
"The table should have one partitioned field"
)
if not show_first and len(indexes[0]["column_names"]) > 1:
raise SupersetTemplateException(
"The table should have a single partitioned field "
"to use this function. You may want to use "
"`presto.latest_sub_partition`"
)
column_names = indexes[0]["column_names"]
return column_names, cls._latest_partition_from_df(
df=database.get_df(
sql=cls._partition_query(
table_name,
schema,
indexes,
database,
limit=1,
order_by=[(column_name, True) for column_name in column_names],
),
schema=schema,
)
)
|
def latest_partition(
cls,
table_name: str,
schema: str | None,
database: Database,
show_first: bool = False,
) -> tuple[list[str], list[str] | None]:
"""Returns col name and the latest (max) partition value for a table
:param table_name: the name of the table
:param schema: schema / database / namespace
:param database: database query will be run against
:type database: models.Database
:param show_first: displays the value for the first partitioning key
if there are many partitioning keys
:type show_first: bool
>>> latest_partition('foo_table')
(['ds'], ('2018-01-01',))
"""
indexes = database.get_indexes(table_name, schema)
if not indexes:
raise SupersetTemplateException(
f"Error getting partition for {schema}.{table_name}. "
"Verify that this table has a partition."
)
if len(indexes[0]["column_names"]) < 1:
raise SupersetTemplateException(
"The table should have one partitioned field"
)
if not show_first and len(indexes[0]["column_names"]) > 1:
raise SupersetTemplateException(
"The table should have a single partitioned field "
"to use this function. You may want to use "
"`presto.latest_sub_partition`"
)
column_names = indexes[0]["column_names"]
return column_names, cls._latest_partition_from_df(
df=database.get_df(
sql=cls._partition_query(
table_name,
schema,
indexes,
database,
limit=1,
order_by=[(column_name, True) for column_name in column_names],
),
schema=schema,
)
)
|
Merge branch 'master' into fix/db-val-param-perms
|
https://github.com/apache/superset/commit/4e2fd6f4f04c61e8c1d3ec3f233581a05f8b6213
| null | null |
superset/db_engine_specs/presto.py
| 0
|
py
| false
|
2023-06-05T08:42:54Z
|
def get_ndb_model_from_beam_entity(beam_entity):
"""Returns an NDB model equivalent to the given Apache Beam entity.
Args:
beam_entity: beam_datastore_types.Entity. The Apache Beam entity.
Returns:
datastore_services.Model. The NDB model.
"""
ndb_key = get_ndb_key_from_beam_key(beam_entity.key)
# We use private _lookup_model and _entity_from_ds_entity here because it
# provides a functionality that we need and writing it ourselves would be
# too complicated.
ndb_model_class = datastore_services.Model._lookup_model(ndb_key.kind()) # pylint: disable=protected-access
return ndb_model._entity_from_ds_entity( # pylint: disable=protected-access
beam_entity.to_client_entity(), model_class=ndb_model_class)
|
def get_ndb_model_from_beam_entity(
beam_entity: beam_datastore_types.Entity
) -> datastore_services.Model:
"""Returns an NDB model equivalent to the given Apache Beam entity.
Args:
beam_entity: beam_datastore_types.Entity. The Apache Beam entity.
Returns:
datastore_services.Model. The NDB model.
"""
ndb_key = get_ndb_key_from_beam_key(beam_entity.key)
# We use private _lookup_model and _entity_from_ds_entity here because it
# provides a functionality that we need and writing it ourselves would be
# too complicated.
ndb_model_class = get_model_class(ndb_key.kind()) # pylint: disable=protected-access
return ndb_model._entity_from_ds_entity( # pylint: disable=protected-access
beam_entity.to_client_entity(), model_class=ndb_model_class)
|
Merge remote-tracking branch 'upstream/develop' into secure-redirection
|
https://github.com/oppia/oppia/commit/11a7838e2269729b17513eca910b04951daa83ee
| null | null |
jobs/job_utils.py
| 0
|
py
| false
|
2021-09-25T13:52:17Z
|
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
// This makes sure that the container activity has implemented
// the callback interfaces. If not, it throws an exception
try {
mToolbarAndFABCallback = (ToolbarAndFABCallback) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement ToolbarAndFABCallback");
}
try {
mRecentAlbumsSelectedListener = (OnRecentAlbumsSelectedListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement OnRecentAlbumsSelectedListener");
}
}
|
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
// This makes sure that the container activity has implemented
// the callback interfaces. If not, it throws an exception
try {
mToolbarAndFABCallback = (ToolbarAndFABCallback) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement ToolbarAndFABCallback");
}
try {
mRecentAlbumsSelectedListener = (OnRecentAlbumsSelectedListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement OnRecentAlbumsSelectedListener");
}
if(mSearchView != null) {
mSearchView.setOnQueryTextListener(new SearchTextObserver());
}
}
|
update volley to 1.2.1
|
https://github.com/gateship-one/odyssey/commit/1c6c859c8805bdf1c1c488f874f6324c457fa866
| null | null |
app/src/main/java/org/gateshipone/odyssey/fragments/MyMusicFragment.java
| 0
|
java
| false
|
2021-10-25T15:43:13Z
|
def _render_job_button_for_obj(job_button, obj, context, content_type):
"""
Helper method for job_buttons templatetag to reduce repetition of code.
Returns:
(str, str): (button_html, form_html)
"""
# Pass select context data when rendering the JobButton text as Jinja2
button_context = {
"obj": obj,
"debug": context.get("debug", False), # django.template.context_processors.debug
"request": context["request"], # django.template.context_processors.request
"user": context["user"], # django.contrib.auth.context_processors.auth
"perms": context["perms"], # django.contrib.auth.context_processors.auth
}
try:
text_rendered = render_jinja2(job_button.text, button_context)
except Exception as exc:
return (
format_html(
'<a class="btn btn-sm btn-{}" disabled="disabled" title="{}"><i class="mdi mdi-alert"></i> {}</a>\n',
"default" if not job_button.group_name else "link",
exc,
job_button.name,
),
SAFE_EMPTY,
)
if not text_rendered:
return (SAFE_EMPTY, SAFE_EMPTY)
# Disable buttons if the user doesn't have permission to run the underlying Job.
has_run_perm = Job.objects.check_perms(context["user"], instance=job_button.job, action="run")
hidden_inputs = format_html(
HIDDEN_INPUTS,
csrf_token=context["csrf_token"],
object_pk=obj.pk,
object_model_name=f"{content_type.app_label}.{content_type.model}",
redirect_path=context["request"].path,
)
template_args = {
"button_id": job_button.pk,
"button_text": text_rendered,
"button_class": job_button.button_class if not job_button.group_name else "link",
"button_url": reverse("extras:job_run", kwargs={"slug": job_button.job.slug}),
"object": obj,
"job": job_button.job,
"hidden_inputs": hidden_inputs,
"disabled": "" if has_run_perm else "disabled",
}
if job_button.confirmation:
return (
format_html(CONFIRM_BUTTON, **template_args),
format_html(CONFIRM_MODAL, **template_args),
)
else:
return (
format_html(NO_CONFIRM_BUTTON, **template_args),
format_html(NO_CONFIRM_FORM, **template_args),
)
|
def _render_job_button_for_obj(job_button, obj, context, content_type):
"""
Helper method for job_buttons templatetag to reduce repetition of code.
Returns:
(str, str): (button_html, form_html)
"""
# Pass select context data when rendering the JobButton text as Jinja2
button_context = {
"obj": obj,
"debug": context.get("debug", False), # django.template.context_processors.debug
"request": context["request"], # django.template.context_processors.request
"user": context["user"], # django.contrib.auth.context_processors.auth
"perms": context["perms"], # django.contrib.auth.context_processors.auth
}
try:
text_rendered = render_jinja2(job_button.text, button_context)
except Exception as exc:
return (
format_html(
'<a class="btn btn-sm btn-{}" disabled="disabled" title="{}"><i class="mdi mdi-alert"></i> {}</a>\n',
"default" if not job_button.group_name else "link",
exc,
job_button.name,
),
SAFE_EMPTY_STR,
)
if not text_rendered:
return (SAFE_EMPTY_STR, SAFE_EMPTY_STR)
# Disable buttons if the user doesn't have permission to run the underlying Job.
has_run_perm = Job.objects.check_perms(context["user"], instance=job_button.job, action="run")
hidden_inputs = format_html(
HIDDEN_INPUTS,
csrf_token=context["csrf_token"],
object_pk=obj.pk,
object_model_name=f"{content_type.app_label}.{content_type.model}",
redirect_path=context["request"].path,
)
template_args = {
"button_id": job_button.pk,
"button_text": text_rendered,
"button_class": job_button.button_class if not job_button.group_name else "link",
"button_url": reverse("extras:job_run", kwargs={"slug": job_button.job.slug}),
"object": obj,
"job": job_button.job,
"hidden_inputs": hidden_inputs,
"disabled": "" if has_run_perm else "disabled",
}
if job_button.confirmation:
return (
format_html(CONFIRM_BUTTON, **template_args),
format_html(CONFIRM_MODAL, **template_args),
)
else:
return (
format_html(NO_CONFIRM_BUTTON, **template_args),
format_html(NO_CONFIRM_FORM, **template_args),
)
|
s/SAFE_EMPTY/SAFE_EMPTY_STR/
|
https://github.com/nautobot/nautobot/commit/1d6f8b855ff3303bf76787dbbad19c1b189a2b3c
| null | null |
nautobot/extras/templatetags/job_buttons.py
| 0
|
py
| false
| null |
def retry_building_docs_if_needed(
all_build_errors,
all_spelling_errors,
args,
docs_only,
jobs,
package_build_errors,
package_spelling_errors,
current_packages,
spellcheck_only,
):
to_retry_packages = [
package_name
for package_name, errors in package_build_errors.items()
if any(any((m in e.message) for m in ERRORS_ELIGIBLE_TO_REBUILD) for e in errors)
]
if to_retry_packages and spellcheck_only:
# in case spellchecking fails with retry all packages should be rebuilt without spell-checking
# in case the failed package refers to another package
to_retry_packages = current_packages
if to_retry_packages:
for package_name in to_retry_packages:
if package_name in all_build_errors:
del all_build_errors[package_name]
if package_name in all_spelling_errors:
del all_spelling_errors[package_name]
package_build_errors, package_spelling_errors = build_docs_for_packages(
current_packages=to_retry_packages,
docs_only=docs_only,
spellcheck_only=False,
jobs=jobs,
verbose=args.verbose,
)
if package_build_errors:
all_build_errors.update(package_build_errors)
if package_spelling_errors:
all_spelling_errors.update(package_spelling_errors)
return package_build_errors, package_spelling_errors
return package_build_errors, package_spelling_errors
|
def retry_building_docs_if_needed(
all_build_errors: dict[str, list[DocBuildError]],
all_spelling_errors: dict[str, list[SpellingError]],
args: argparse.Namespace,
docs_only: bool,
jobs: int,
package_build_errors: dict[str, list[DocBuildError]],
originally_built_packages: list[str],
rebuild_all_packages: bool,
) -> dict[str, list[DocBuildError]]:
to_retry_packages = [
package_name
for package_name, errors in package_build_errors.items()
if any(any((m in e.message) for m in ERRORS_ELIGIBLE_TO_REBUILD) for e in errors)
]
if not to_retry_packages:
console.print("[green]No packages to retry. No more passes are needed.[/]")
return package_build_errors
console.print("[warning] Some packages failed to build due to dependencies. We need another pass.[/]")
# if we are rebuilding all packages, we need to retry all packages
# even if there is one package to rebuild only
if rebuild_all_packages:
console.print("[warning]Rebuilding all originally built package as this is the first build pass:[/]")
to_retry_packages = originally_built_packages
console.print(f"[bright_blue]Packages to rebuild: {to_retry_packages}[/]")
for package_name in to_retry_packages:
if package_name in all_build_errors:
del all_build_errors[package_name]
if package_name in all_spelling_errors:
del all_spelling_errors[package_name]
package_build_errors, package_spelling_errors = build_docs_for_packages(
packages_to_build=to_retry_packages,
docs_only=docs_only,
spellcheck_only=False,
jobs=jobs,
verbose=args.verbose,
)
if package_build_errors:
all_build_errors.update(package_build_errors)
if package_spelling_errors:
all_spelling_errors.update(package_spelling_errors)
return package_build_errors
|
Merge branch 'main' into trigger_encryption
|
https://github.com/apache/airflow/commit/bbc7408e175819eb8a2666acddd5bc48f403baf7
| null | null |
docs/build_docs.py
| 0
|
py
| false
|
2024-01-08T23:50:49Z
|
public static int setVideoQuality(Object[] qualities, int quality, Object qInterface, String qIndexMethod) {
int preferredQuality;
Field[] fields;
if (!ReVancedUtils.isNewVideoStarted() && !userChangedQuality || qInterface == null) {
return quality;
}
Class<?> intType = Integer.TYPE;
ArrayList<Integer> iStreamQualities = new ArrayList<>();
try {
for (Object streamQuality : qualities) {
for (Field field : streamQuality.getClass().getFields()) {
if (field.getType().isAssignableFrom(intType)) { // converts quality index to actual readable resolution
int value = field.getInt(streamQuality);
if (field.getName().length() <= 2) {
iStreamQualities.add(value);
}
}
}
}
} catch (Exception ignored) {
}
Collections.sort(iStreamQualities);
int index = 0;
if (userChangedQuality) {
for (int convertedQuality : iStreamQualities) {
int selectedQuality2 = qualities.length - selectedQuality1 + 1;
index++;
if (selectedQuality2 == index) {
LogHelper.debug(VideoQualityPatch.class, "Quality index is: " + index + " and corresponding value is: " + convertedQuality);
changeDefaultQuality(convertedQuality);
return selectedQuality2;
}
}
}
ReVancedUtils.setNewVideo(false);
LogHelper.debug(VideoQualityPatch.class, "Quality: " + quality);
Context context = ReVancedUtils.getContext();
if (context == null) {
LogHelper.printException(VideoQualityPatch.class, "Context is null or settings not initialized, returning quality: " + quality);
return quality;
}
if (isConnectedWifi(context)) {
SharedPreferences wifi = context.getSharedPreferences("revanced_prefs", 0);
preferredQuality = wifi.getInt("wifi_quality", -2);
LogHelper.debug(VideoQualityPatch.class, "Wi-Fi connection detected, preferred quality: " + preferredQuality);
} else if (isConnectedMobile(context)) {
SharedPreferences mobile = context.getSharedPreferences("revanced_prefs", 0);
preferredQuality = mobile.getInt("mobile_quality", -2);
LogHelper.debug(VideoQualityPatch.class, "Mobile data connection detected, preferred quality: " + preferredQuality);
} else {
LogHelper.debug(VideoQualityPatch.class, "No Internet connection!");
return quality;
}
if (preferredQuality == -2) {
return quality;
}
for (int streamQuality2 : iStreamQualities) {
LogHelper.debug(VideoQualityPatch.class, "Quality at index " + index + ": " + streamQuality2);
index++;
}
for (Integer iStreamQuality : iStreamQualities) {
int streamQuality3 = iStreamQuality;
if (streamQuality3 <= preferredQuality) {
quality = streamQuality3;
}
}
if (quality == -2) {
return quality;
}
int qualityIndex = iStreamQualities.indexOf(quality);
LogHelper.debug(VideoQualityPatch.class, "Index of quality " + quality + " is " + qualityIndex);
try {
Class<?> cl = qInterface.getClass();
Method m = cl.getMethod(qIndexMethod, Integer.TYPE);
LogHelper.debug(VideoQualityPatch.class, "Method is: " + qIndexMethod);
m.invoke(qInterface, iStreamQualities.get(qualityIndex));
LogHelper.debug(VideoQualityPatch.class, "Quality changed to: " + qualityIndex);
return qualityIndex;
} catch (Exception ex) {
LogHelper.printException(VideoQualityPatch.class, "Failed to set quality", ex);
return qualityIndex;
}
}
|
public static int setVideoQuality(Object[] qualities, int quality, Object qInterface, String qIndexMethod) {
int preferredQuality;
Field[] fields;
if (!(newVideo || userChangedQuality) || qInterface == null) {
return quality;
}
Class<?> intType = Integer.TYPE;
ArrayList<Integer> iStreamQualities = new ArrayList<>();
try {
for (Object streamQuality : qualities) {
for (Field field : streamQuality.getClass().getFields()) {
if (field.getType().isAssignableFrom(intType)) { // converts quality index to actual readable resolution
int value = field.getInt(streamQuality);
if (field.getName().length() <= 2) {
iStreamQualities.add(value);
}
}
}
}
} catch (Exception ignored) {
}
Collections.sort(iStreamQualities);
int index = 0;
if (userChangedQuality) {
for (int convertedQuality : iStreamQualities) {
int selectedQuality2 = qualities.length - selectedQuality1 + 1;
index++;
if (selectedQuality2 == index) {
LogHelper.debug(VideoQualityPatch.class, "Quality index is: " + index + " and corresponding value is: " + convertedQuality);
changeDefaultQuality(convertedQuality);
return selectedQuality2;
}
}
}
newVideo = false;
LogHelper.debug(VideoQualityPatch.class, "Quality: " + quality);
Context context = ReVancedUtils.getContext();
if (context == null) {
LogHelper.printException(VideoQualityPatch.class, "Context is null or settings not initialized, returning quality: " + quality);
return quality;
}
if (isConnectedWifi(context)) {
SharedPreferences wifi = context.getSharedPreferences("revanced_prefs", 0);
preferredQuality = wifi.getInt("wifi_quality", -2);
LogHelper.debug(VideoQualityPatch.class, "Wi-Fi connection detected, preferred quality: " + preferredQuality);
} else if (isConnectedMobile(context)) {
SharedPreferences mobile = context.getSharedPreferences("revanced_prefs", 0);
preferredQuality = mobile.getInt("mobile_quality", -2);
LogHelper.debug(VideoQualityPatch.class, "Mobile data connection detected, preferred quality: " + preferredQuality);
} else {
LogHelper.debug(VideoQualityPatch.class, "No Internet connection!");
return quality;
}
if (preferredQuality == -2) {
return quality;
}
for (int streamQuality2 : iStreamQualities) {
LogHelper.debug(VideoQualityPatch.class, "Quality at index " + index + ": " + streamQuality2);
index++;
}
for (Integer iStreamQuality : iStreamQualities) {
int streamQuality3 = iStreamQuality;
if (streamQuality3 <= preferredQuality) {
quality = streamQuality3;
}
}
if (quality == -2) {
return quality;
}
int qualityIndex = iStreamQualities.indexOf(quality);
LogHelper.debug(VideoQualityPatch.class, "Index of quality " + quality + " is " + qualityIndex);
try {
Class<?> cl = qInterface.getClass();
Method m = cl.getMethod(qIndexMethod, Integer.TYPE);
LogHelper.debug(VideoQualityPatch.class, "Method is: " + qIndexMethod);
m.invoke(qInterface, iStreamQualities.get(qualityIndex));
LogHelper.debug(VideoQualityPatch.class, "Quality changed to: " + qualityIndex);
return qualityIndex;
} catch (Exception ex) {
LogHelper.printException(VideoQualityPatch.class, "Failed to set quality", ex);
return qualityIndex;
}
}
|
fix: `default-video-quality` patch crashing (#100)
|
https://github.com/ReVanced/revanced-integrations/commit/c6b7528eaea76cf04851f4085d6e6a48731fb2dc
| null | null |
app/src/main/java/app/revanced/integrations/patches/VideoQualityPatch.java
| 0
|
java
| false
| null |
public Map<String, String> getAuthScriptAsMap() {
return Map.of("auth_script", this.getAuthRefreshScript(), "refresh_interval", String.valueOf(getAuthRefreshInterval()));
}
|
public Map<String, String> getAuthScriptAsMap() {
return Map.of("auth_script", this.getAuthRefreshScript(), "auth_refresh", String.valueOf(getAuthRefreshInterval()));
}
|
Update quarkus to latest version
|
https://github.com/Endava/cats/commit/0b8736cdd7403b1471e7cd5ef2f59c40e6fd026b
| null | null |
src/main/java/com/endava/cats/args/AuthArguments.java
| 0
|
java
| false
| null |
def load_or_create_client_key(key_file):
"""Load the ACME account key from a file, creating it if it does not exist.
Args:
key_file (str): name of the file to use as the account key
"""
# this is based on txacme.endpoint.load_or_create_client_key, but doesn't
# hardcode the 'client.key' filename
acme_key_file = FilePath(key_file)
if acme_key_file.exists():
logger.info("Loading ACME account key from '%s'", acme_key_file)
key = serialization.load_pem_private_key(
acme_key_file.getContent(), password=None, backend=default_backend()
)
else:
logger.info("Saving new ACME account key to '%s'", acme_key_file)
key = generate_private_key("rsa")
acme_key_file.setContent(
key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption(),
)
)
return JWKRSA(key=key)
|
def load_or_create_client_key(key_file: str) -> JWKRSA:
"""Load the ACME account key from a file, creating it if it does not exist.
Args:
key_file: name of the file to use as the account key
"""
# this is based on txacme.endpoint.load_or_create_client_key, but doesn't
# hardcode the 'client.key' filename
acme_key_file = FilePath(key_file)
if acme_key_file.exists():
logger.info("Loading ACME account key from '%s'", acme_key_file)
key = serialization.load_pem_private_key(
acme_key_file.getContent(), password=None, backend=default_backend()
)
else:
logger.info("Saving new ACME account key to '%s'", acme_key_file)
key = generate_private_key("rsa")
acme_key_file.setContent(
key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption(),
)
)
return JWKRSA(key=key)
|
Merge remote-tracking branch 'origin/develop' into clokep/template-clean-up
|
https://github.com/matrix-org/synapse/commit/ba7f48a37848dcec60e99bc23ecd5e16137d2b45
| null | null |
synapse/handlers/acme_issuing_service.py
| 0
|
py
| false
|
2021-01-27T13:35:31Z
|
function Q(){var b;return 93===a.charCodeAt(vc)?(b=hc,vc++):(b=X,0===Bc&&g(ic)),b}
|
function Q(){var b;return 93===a.charCodeAt(sc)?(b=ec,sc++):(b=X,0===xc&&g(fc)),b}
|
fix for prototype pollution vulnerability
|
https://github.com/linkedin/dustjs/commit/ddb6523832465d38c9d80189e9de60519ac307c3
|
CVE-2021-4264
|
['CWE-1321']
|
dist/dust-full.min.js
| 0
|
js
| false
|
2021-09-08T00:12:45Z
|
static Image *ReadWEBPImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
#define ThrowWEBPException(severity,tag) \
{ \
if (stream != (unsigned char *) NULL) \
stream=(unsigned char*) RelinquishMagickMemory(stream); \
if (webp_image != (WebPDecBuffer *) NULL) \
WebPFreeDecBuffer(webp_image); \
ThrowReaderException(severity,tag); \
}
Image
*image;
int
webp_status;
MagickBooleanType
status;
register unsigned char
*p;
size_t
length;
ssize_t
count,
y;
unsigned char
header[12],
*stream;
WebPDecoderConfig
configure;
WebPDecBuffer
*magick_restrict webp_image = &configure.output;
WebPBitstreamFeatures
*magick_restrict features = &configure.input;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
stream=(unsigned char *) NULL;
webp_image=(WebPDecBuffer *) NULL;
if (WebPInitDecoderConfig(&configure) == 0)
ThrowReaderException(ResourceLimitError,"UnableToDecodeImageFile");
webp_image->colorspace=MODE_RGBA;
count=ReadBlob(image,12,header);
if (count != 12)
ThrowWEBPException(CorruptImageError,"InsufficientImageDataInFile");
status=IsWEBP(header,count);
if (status == MagickFalse)
ThrowWEBPException(CorruptImageError,"CorruptImage");
length=(size_t) (ReadWebPLSBWord(header+4)+8);
if (length < 12)
ThrowWEBPException(CorruptImageError,"CorruptImage");
if (length > GetBlobSize(image))
ThrowWEBPException(CorruptImageError,"InsufficientImageDataInFile");
stream=(unsigned char *) AcquireQuantumMemory(length,sizeof(*stream));
if (stream == (unsigned char *) NULL)
ThrowWEBPException(ResourceLimitError,"MemoryAllocationFailed");
(void) memcpy(stream,header,12);
count=ReadBlob(image,length-12,stream+12);
if (count != (ssize_t) (length-12))
ThrowWEBPException(CorruptImageError,"InsufficientImageDataInFile");
webp_status=WebPGetFeatures(stream,length,features);
if (webp_status == VP8_STATUS_OK)
{
image->columns=(size_t) features->width;
image->rows=(size_t) features->height;
image->depth=8;
image->alpha_trait=features->has_alpha != 0 ? BlendPixelTrait :
UndefinedPixelTrait;
if (IsWEBPImageLossless(stream,length) != MagickFalse)
image->quality=100;
if (image_info->ping != MagickFalse)
{
stream=(unsigned char*) RelinquishMagickMemory(stream);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
{
stream=(unsigned char*) RelinquishMagickMemory(stream);
(void) CloseBlob(image);
return(DestroyImageList(image));
}
webp_status=WebPDecode(stream,length,&configure);
}
if (webp_status != VP8_STATUS_OK)
switch (webp_status)
{
case VP8_STATUS_OUT_OF_MEMORY:
{
ThrowWEBPException(ResourceLimitError,"MemoryAllocationFailed");
break;
}
case VP8_STATUS_INVALID_PARAM:
{
ThrowWEBPException(CorruptImageError,"invalid parameter");
break;
}
case VP8_STATUS_BITSTREAM_ERROR:
{
ThrowWEBPException(CorruptImageError,"CorruptImage");
break;
}
case VP8_STATUS_UNSUPPORTED_FEATURE:
{
ThrowWEBPException(CoderError,"DataEncodingSchemeIsNotSupported");
break;
}
case VP8_STATUS_SUSPENDED:
{
ThrowWEBPException(CorruptImageError,"decoder suspended");
break;
}
case VP8_STATUS_USER_ABORT:
{
ThrowWEBPException(CorruptImageError,"user abort");
break;
}
case VP8_STATUS_NOT_ENOUGH_DATA:
{
ThrowWEBPException(CorruptImageError,"InsufficientImageDataInFile");
break;
}
default:
ThrowWEBPException(CorruptImageError,"CorruptImage");
}
p=(unsigned char *) webp_image->u.RGBA.rgba;
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*q;
register ssize_t
x;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
WebPFreeDecBuffer(webp_image);
stream=(unsigned char*) RelinquishMagickMemory(stream);
(void) CloseBlob(image);
return(image);
}
|
static Image *ReadWEBPImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
#define ThrowWEBPException(severity,tag) \
{ \
if (stream != (unsigned char *) NULL) \
stream=(unsigned char*) RelinquishMagickMemory(stream); \
if (webp_image != (WebPDecBuffer *) NULL) \
WebPFreeDecBuffer(webp_image); \
ThrowReaderException(severity,tag); \
}
Image
*image;
int
webp_status;
MagickBooleanType
status;
register unsigned char
*p;
size_t
length;
ssize_t
count,
y;
unsigned char
header[12],
*stream;
WebPDecoderConfig
configure;
WebPDecBuffer
*magick_restrict webp_image = &configure.output;
WebPBitstreamFeatures
*magick_restrict features = &configure.input;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
stream=(unsigned char *) NULL;
if (WebPInitDecoderConfig(&configure) == 0)
ThrowReaderException(ResourceLimitError,"UnableToDecodeImageFile");
webp_image->colorspace=MODE_RGBA;
count=ReadBlob(image,12,header);
if (count != 12)
ThrowWEBPException(CorruptImageError,"InsufficientImageDataInFile");
status=IsWEBP(header,count);
if (status == MagickFalse)
ThrowWEBPException(CorruptImageError,"CorruptImage");
length=(size_t) (ReadWebPLSBWord(header+4)+8);
if (length < 12)
ThrowWEBPException(CorruptImageError,"CorruptImage");
if (length > GetBlobSize(image))
ThrowWEBPException(CorruptImageError,"InsufficientImageDataInFile");
stream=(unsigned char *) AcquireQuantumMemory(length,sizeof(*stream));
if (stream == (unsigned char *) NULL)
ThrowWEBPException(ResourceLimitError,"MemoryAllocationFailed");
(void) memcpy(stream,header,12);
count=ReadBlob(image,length-12,stream+12);
if (count != (ssize_t) (length-12))
ThrowWEBPException(CorruptImageError,"InsufficientImageDataInFile");
webp_status=WebPGetFeatures(stream,length,features);
if (webp_status == VP8_STATUS_OK)
{
image->columns=(size_t) features->width;
image->rows=(size_t) features->height;
image->depth=8;
image->alpha_trait=features->has_alpha != 0 ? BlendPixelTrait :
UndefinedPixelTrait;
if (IsWEBPImageLossless(stream,length) != MagickFalse)
image->quality=100;
if (image_info->ping != MagickFalse)
{
stream=(unsigned char*) RelinquishMagickMemory(stream);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
{
stream=(unsigned char*) RelinquishMagickMemory(stream);
(void) CloseBlob(image);
return(DestroyImageList(image));
}
webp_status=WebPDecode(stream,length,&configure);
}
if (webp_status != VP8_STATUS_OK)
switch (webp_status)
{
case VP8_STATUS_OUT_OF_MEMORY:
{
ThrowWEBPException(ResourceLimitError,"MemoryAllocationFailed");
break;
}
case VP8_STATUS_INVALID_PARAM:
{
ThrowWEBPException(CorruptImageError,"invalid parameter");
break;
}
case VP8_STATUS_BITSTREAM_ERROR:
{
ThrowWEBPException(CorruptImageError,"CorruptImage");
break;
}
case VP8_STATUS_UNSUPPORTED_FEATURE:
{
ThrowWEBPException(CoderError,"DataEncodingSchemeIsNotSupported");
break;
}
case VP8_STATUS_SUSPENDED:
{
ThrowWEBPException(CorruptImageError,"decoder suspended");
break;
}
case VP8_STATUS_USER_ABORT:
{
ThrowWEBPException(CorruptImageError,"user abort");
break;
}
case VP8_STATUS_NOT_ENOUGH_DATA:
{
ThrowWEBPException(CorruptImageError,"InsufficientImageDataInFile");
break;
}
default:
ThrowWEBPException(CorruptImageError,"CorruptImage");
}
p=(unsigned char *) webp_image->u.RGBA.rgba;
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*q;
register ssize_t
x;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
WebPFreeDecBuffer(webp_image);
stream=(unsigned char*) RelinquishMagickMemory(stream);
(void) CloseBlob(image);
return(image);
}
|
https://github.com/ImageMagick/ImageMagick/issues/639
|
https://github.com/ImageMagick/ImageMagick/commit/06ccb0ccdcca8219862a05c5589329903473235f
| null | null |
coders/webp.c
| 0
|
c
| false
| null |
public void showMultichoicePoiFilterDialog(final MapActivity mapActivity, final DismissListener listener) {
final OsmandApplication app = getApplication();
final PoiFiltersHelper poiFilters = app.getPoiFilters();
final ContextMenuAdapter adapter = new ContextMenuAdapter(app);
final List<PoiUIFilter> list = new ArrayList<>();
for (PoiUIFilter f : poiFilters.getSortedPoiFilters(true)) {
if (!f.isTopWikiFilter()) {
addFilterToList(adapter, list, f, true);
}
}
list.add(poiFilters.getCustomPOIFilter());
adapter.setProfileDependent(true);
adapter.setNightMode(isNightMode(app));
final ArrayAdapter<ContextMenuItem> listAdapter = adapter.createListAdapter(mapActivity, !isNightMode(app));
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(ctx, getThemeRes(app)));
final ListView listView = new ListView(ctx);
listView.setDivider(null);
listView.setClickable(true);
listView.setAdapter(listAdapter);
listView.setOnItemClickListener((parent, view, position, id) -> {
ContextMenuItem item = listAdapter.getItem(position);
if (item != null) {
item.setSelected(!item.getSelected());
ItemClickListener clickListener = item.getItemClickListener();
if (clickListener != null) {
clickListener.onContextMenuClick(listAdapter, position, position, item.getSelected(), null);
}
listAdapter.notifyDataSetChanged();
}
});
builder.setView(listView)
.setTitle(R.string.show_poi_over_map)
.setPositiveButton(R.string.shared_string_ok, (dialog, which) -> {
for (int i = 0; i < listAdapter.getCount(); i++) {
ContextMenuItem item = listAdapter.getItem(i);
PoiUIFilter filter = list.get(i);
if (item != null && item.getSelected()) {
if (filter.isStandardFilter()) {
filter.removeUnsavedFilterByName();
}
poiFilters.addSelectedPoiFilter(filter);
} else {
poiFilters.removeSelectedPoiFilter(filter);
}
}
mapActivity.getMapView().refreshMap();
})
.setNegativeButton(R.string.shared_string_cancel, null)
// TODO go to single choice dialog
.setNeutralButton(" ", (dialog, which) -> showSingleChoicePoiFilterDialog(mapActivity, listener));
final AlertDialog alertDialog = builder.create();
alertDialog.setOnShowListener(dialog -> {
Button neutralButton = alertDialog.getButton(DialogInterface.BUTTON_NEUTRAL);
Drawable drawable = app.getUIUtilities().getThemedIcon(R.drawable.ic_action_singleselect);
neutralButton.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
neutralButton.setContentDescription(app.getString(R.string.shared_string_filters));
});
alertDialog.setOnDismissListener(dialog -> listener.dismiss());
alertDialog.show();
}
|
public void showMultichoicePoiFilterDialog(final MapActivity mapActivity, final DismissListener listener) {
final OsmandApplication app = getApplication();
final PoiFiltersHelper poiFilters = app.getPoiFilters();
final ContextMenuAdapter adapter = new ContextMenuAdapter(app);
final List<PoiUIFilter> list = new ArrayList<>();
for (PoiUIFilter f : poiFilters.getSortedPoiFilters(true)) {
if (!f.isTopWikiFilter()) {
addFilterToList(adapter, list, f, true);
}
}
list.add(poiFilters.getCustomPOIFilter());
adapter.setProfileDependent(true);
adapter.setNightMode(isNightMode(app));
final ArrayAdapter<ContextMenuItem> listAdapter = adapter.createListAdapter(mapActivity, !isNightMode(app));
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(mapActivity, getThemeRes(app)));
final ListView listView = new ListView(ctx);
listView.setDivider(null);
listView.setClickable(true);
listView.setAdapter(listAdapter);
listView.setOnItemClickListener((parent, view, position, id) -> {
ContextMenuItem item = listAdapter.getItem(position);
if (item != null) {
item.setSelected(!item.getSelected());
ItemClickListener clickListener = item.getItemClickListener();
if (clickListener != null) {
clickListener.onContextMenuClick(listAdapter, position, position, item.getSelected(), null);
}
listAdapter.notifyDataSetChanged();
}
});
builder.setView(listView)
.setTitle(R.string.show_poi_over_map)
.setPositiveButton(R.string.shared_string_ok, (dialog, which) -> {
for (int i = 0; i < listAdapter.getCount(); i++) {
ContextMenuItem item = listAdapter.getItem(i);
PoiUIFilter filter = list.get(i);
if (item != null && item.getSelected()) {
if (filter.isStandardFilter()) {
filter.removeUnsavedFilterByName();
}
poiFilters.addSelectedPoiFilter(filter);
} else {
poiFilters.removeSelectedPoiFilter(filter);
}
}
mapActivity.getMapView().refreshMap();
})
.setNegativeButton(R.string.shared_string_cancel, null)
// TODO go to single choice dialog
.setNeutralButton(" ", (dialog, which) -> showSingleChoicePoiFilterDialog(mapActivity, listener));
final AlertDialog alertDialog = builder.create();
alertDialog.setOnShowListener(dialog -> {
Button neutralButton = alertDialog.getButton(DialogInterface.BUTTON_NEUTRAL);
Drawable drawable = app.getUIUtilities().getThemedIcon(R.drawable.ic_action_singleselect);
neutralButton.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
neutralButton.setContentDescription(app.getString(R.string.shared_string_filters));
});
alertDialog.setOnDismissListener(dialog -> listener.dismiss());
alertDialog.show();
}
|
Fix configure map dialogs crash
|
https://github.com/osmandapp/OsmAnd/commit/0ae8e376ec7c31009c0aecc043629dc20ac1103e
| null | null |
OsmAnd/src/net/osmand/plus/views/MapLayers.java
| 0
|
java
| false
| null |
function L(n,t){for(var r=-1,e=n.length,u=0,i=[];++r<e;){var o=n[r];o!==t&&"__lodash_placeholder__"!==o||(n[r]="__lodash_placeholder__",i[u++]=r)}return i}
|
function L(n,t){for(var r=n.length;r--&&y(t,n[r],0)>-1;);return r}
|
Update vendor libs
|
https://github.com/cockpit-hq/cockpit/commit/690016208850f2d788ebc3c67884d4c692587eb8
|
CVE-2023-1160
|
['CWE-1103']
|
modules/App/assets/vendor/lodash.js
| 0
|
js
| false
|
2023-02-22T01:10:02Z
|
function parseAttributes(attrs) {
if (Object(lodash_es__WEBPACK_IMPORTED_MODULE_29__["isPlainObject"])(attrs)) {
attrs = Object(_ckeditor_ckeditor5_utils_src_objecttomap__WEBPACK_IMPORTED_MODULE_26__["default"])(attrs);
} else {
attrs = new Map(attrs);
}
var _iteratorNormalCompletion7 = true;
var _didIteratorError7 = false;
var _iteratorError7 = undefined;
try {
for (var _iterator7 = attrs[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
var _step7$value = Object(_var_www_lime25_limesurvey_assets_packages_questiongroup_node_modules_babel_runtime_corejs2_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_6__["default"])(_step7.value, 2),
key = _step7$value[0],
value = _step7$value[1];
if (value === null) {
attrs.delete(key);
} else if (typeof value != 'string') {
attrs.set(key, String(value));
}
}
} catch (err) {
_didIteratorError7 = true;
_iteratorError7 = err;
} finally {
try {
if (!_iteratorNormalCompletion7 && _iterator7.return != null) {
_iterator7.return();
}
} finally {
if (_didIteratorError7) {
throw _iteratorError7;
}
}
}
return attrs;
} // Parses inline styles and puts property - value pairs into styles map.
|
function parseAttributes(attrs) {
if (Object(lodash_es__WEBPACK_IMPORTED_MODULE_29__["isPlainObject"])(attrs)) {
attrs = Object(_ckeditor_ckeditor5_utils_src_objecttomap__WEBPACK_IMPORTED_MODULE_26__["default"])(attrs);
} else {
attrs = new Map(attrs);
}
var _iteratorNormalCompletion7 = true;
var _didIteratorError7 = false;
var _iteratorError7 = undefined;
try {
for (var _iterator7 = attrs[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
var _step7$value = Object(_var_www_limedev_assets_packages_questiongroup_node_modules_babel_runtime_corejs2_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_6__["default"])(_step7.value, 2),
key = _step7$value[0],
value = _step7$value[1];
if (value === null) {
attrs.delete(key);
} else if (typeof value != 'string') {
attrs.set(key, String(value));
}
}
} catch (err) {
_didIteratorError7 = true;
_iteratorError7 = err;
} finally {
try {
if (!_iteratorNormalCompletion7 && _iterator7.return != null) {
_iterator7.return();
}
} finally {
if (_didIteratorError7) {
throw _iteratorError7;
}
}
}
return attrs;
} // Parses inline styles and puts property - value pairs into styles map.
|
DEV: changed routes in vue.js part questiongroupedit.js and deleted old controller+views
|
https://github.com/LimeSurvey/LimeSurvey/commit/d7a309bf1a73e95187528982b9db7ec03fee6913
|
CVE-2020-23710
|
['CWE-79']
|
assets/packages/questiongroup/build/js/questiongroupedit.js
| 0
|
js
| false
|
2020-06-08T09:23:29Z
|
@LuaFunction
public final Object[] seek(Optional<String> whence, Optional<Long> offset) throws LuaException {
this.checkOpen();
return handleSeek(this.seekable, whence, offset);
}
|
@LuaFunction
public final Object[] seek( Optional<String> whence, Optional<Long> offset ) throws LuaException
{
checkOpen();
return handleSeek( seekable, whence, offset );
}
|
Make rightAlt only close menu, never open it. (#672)
Fixes #669
|
https://github.com/cc-tweaked/cc-restitched/commit/094e0d4f33ff28462d9e4721edcb8c8d1581b410
| null | null |
src/main/java/dan200/computercraft/core/apis/handles/BinaryReadableHandle.java
| 0
|
java
| false
|
2021-01-13T22:10:44Z
|
static int __kprobes
do_page_fault(unsigned long addr, unsigned int fsr, struct pt_regs *regs)
{
struct task_struct *tsk;
struct mm_struct *mm;
int fault, sig, code;
if (notify_page_fault(regs, fsr))
return 0;
tsk = current;
mm = tsk->mm;
/*
* If we're in an interrupt or have no user
* context, we must not take the fault..
*/
if (in_atomic() || !mm)
goto no_context;
/*
* As per x86, we may deadlock here. However, since the kernel only
* validly references user space from well defined areas of the code,
* we can bug out early if this is from code which shouldn't.
*/
if (!down_read_trylock(&mm->mmap_sem)) {
if (!user_mode(regs) && !search_exception_tables(regs->ARM_pc))
goto no_context;
down_read(&mm->mmap_sem);
} else {
/*
* The above down_read_trylock() might have succeeded in
* which case, we'll have missed the might_sleep() from
* down_read()
*/
might_sleep();
#ifdef CONFIG_DEBUG_VM
if (!user_mode(regs) &&
!search_exception_tables(regs->ARM_pc))
goto no_context;
#endif
}
fault = __do_page_fault(mm, addr, fsr, tsk);
up_read(&mm->mmap_sem);
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, 0, regs, addr);
if (fault & VM_FAULT_MAJOR)
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, 0, regs, addr);
else if (fault & VM_FAULT_MINOR)
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, 0, regs, addr);
/*
* Handle the "normal" case first - VM_FAULT_MAJOR / VM_FAULT_MINOR
*/
if (likely(!(fault & (VM_FAULT_ERROR | VM_FAULT_BADMAP | VM_FAULT_BADACCESS))))
return 0;
if (fault & VM_FAULT_OOM) {
/*
* We ran out of memory, call the OOM killer, and return to
* userspace (which will retry the fault, or kill us if we
* got oom-killed)
*/
pagefault_out_of_memory();
return 0;
}
/*
* If we are in kernel mode at this point, we
* have no context to handle this fault with.
*/
if (!user_mode(regs))
goto no_context;
if (fault & VM_FAULT_SIGBUS) {
/*
* We had some memory, but were unable to
* successfully fix up this page fault.
*/
sig = SIGBUS;
code = BUS_ADRERR;
} else {
/*
* Something tried to access memory that
* isn't in our memory map..
*/
sig = SIGSEGV;
code = fault == VM_FAULT_BADACCESS ?
SEGV_ACCERR : SEGV_MAPERR;
}
__do_user_fault(tsk, addr, fsr, sig, code, regs);
return 0;
no_context:
__do_kernel_fault(mm, addr, fsr, regs);
return 0;
}
|
static int __kprobes
do_page_fault(unsigned long addr, unsigned int fsr, struct pt_regs *regs)
{
struct task_struct *tsk;
struct mm_struct *mm;
int fault, sig, code;
if (notify_page_fault(regs, fsr))
return 0;
tsk = current;
mm = tsk->mm;
/*
* If we're in an interrupt or have no user
* context, we must not take the fault..
*/
if (in_atomic() || !mm)
goto no_context;
/*
* As per x86, we may deadlock here. However, since the kernel only
* validly references user space from well defined areas of the code,
* we can bug out early if this is from code which shouldn't.
*/
if (!down_read_trylock(&mm->mmap_sem)) {
if (!user_mode(regs) && !search_exception_tables(regs->ARM_pc))
goto no_context;
down_read(&mm->mmap_sem);
} else {
/*
* The above down_read_trylock() might have succeeded in
* which case, we'll have missed the might_sleep() from
* down_read()
*/
might_sleep();
#ifdef CONFIG_DEBUG_VM
if (!user_mode(regs) &&
!search_exception_tables(regs->ARM_pc))
goto no_context;
#endif
}
fault = __do_page_fault(mm, addr, fsr, tsk);
up_read(&mm->mmap_sem);
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, regs, addr);
if (fault & VM_FAULT_MAJOR)
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, regs, addr);
else if (fault & VM_FAULT_MINOR)
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, regs, addr);
/*
* Handle the "normal" case first - VM_FAULT_MAJOR / VM_FAULT_MINOR
*/
if (likely(!(fault & (VM_FAULT_ERROR | VM_FAULT_BADMAP | VM_FAULT_BADACCESS))))
return 0;
if (fault & VM_FAULT_OOM) {
/*
* We ran out of memory, call the OOM killer, and return to
* userspace (which will retry the fault, or kill us if we
* got oom-killed)
*/
pagefault_out_of_memory();
return 0;
}
/*
* If we are in kernel mode at this point, we
* have no context to handle this fault with.
*/
if (!user_mode(regs))
goto no_context;
if (fault & VM_FAULT_SIGBUS) {
/*
* We had some memory, but were unable to
* successfully fix up this page fault.
*/
sig = SIGBUS;
code = BUS_ADRERR;
} else {
/*
* Something tried to access memory that
* isn't in our memory map..
*/
sig = SIGSEGV;
code = fault == VM_FAULT_BADACCESS ?
SEGV_ACCERR : SEGV_MAPERR;
}
__do_user_fault(tsk, addr, fsr, sig, code, regs);
return 0;
no_context:
__do_kernel_fault(mm, addr, fsr, regs);
return 0;
}
|
perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <a.p.zijlstra@chello.nl>
Cc: Michael Cree <mcree@orcon.net.nz>
Cc: Will Deacon <will.deacon@arm.com>
Cc: Deng-Cheng Zhu <dengcheng.zhu@gmail.com>
Cc: Anton Blanchard <anton@samba.org>
Cc: Eric B Munson <emunson@mgebm.net>
Cc: Heiko Carstens <heiko.carstens@de.ibm.com>
Cc: Paul Mundt <lethal@linux-sh.org>
Cc: David S. Miller <davem@davemloft.net>
Cc: Frederic Weisbecker <fweisbec@gmail.com>
Cc: Jason Wessel <jason.wessel@windriver.com>
Cc: Don Zickus <dzickus@redhat.com>
Link: http://lkml.kernel.org/n/tip-agjev8eu666tvknpb3iaj0fg@git.kernel.org
Signed-off-by: Ingo Molnar <mingo@elte.hu>
|
https://github.com/torvalds/linux/commit/a8b0ca17b80e92faab46ee7179ba9e99ccb61233
| null | null |
arch/arm/mm/fault.c
| 0
|
c
| false
| null |
static int _receive(gnrc_pktsnip_t *pkt)
{
/* NOTE: In receiving direction: pkt = payload, payload->next = tcp, tcp->next = nw */
uint16_t ctl = 0;
uint16_t src = 0;
uint16_t dst = 0;
uint8_t hdr_size = 0;
uint8_t syn = 0;
gnrc_pktsnip_t *ip = NULL;
gnrc_pktsnip_t *reset = NULL;
gnrc_tcp_tcb_t *tcb = NULL;
tcp_hdr_t *hdr;
/* Get write access to the TCP header */
gnrc_pktsnip_t *tcp = gnrc_pktbuf_start_write(pkt);
if (tcp == NULL) {
DEBUG("gnrc_tcp_eventloop.c : _receive() : can't write to packet\n");
gnrc_pktbuf_release(pkt);
return -EACCES;
}
pkt = tcp;
#ifdef MODULE_GNRC_IPV6
/* Get IPv6 header, discard packet if doesn't contain an ip header */
LL_SEARCH_SCALAR(pkt, ip, type, GNRC_NETTYPE_IPV6);
if (ip == NULL) {
DEBUG("gnrc_tcp_eventloop.c : _receive() : pkt contains no IP Header\n");
gnrc_pktbuf_release(pkt);
return 0;
}
#endif
/* Get TCP header */
LL_SEARCH_SCALAR(pkt, tcp, type, GNRC_NETTYPE_TCP);
if (tcp == NULL) {
DEBUG("gnrc_tcp_eventloop.c : _receive() : pkt contains no TCP Header\n");
gnrc_pktbuf_release(pkt);
return 0;
}
/* Extract control bits, src and dst ports and check if SYN is set (not SYN+ACK) */
hdr = (tcp_hdr_t *)tcp->data;
ctl = byteorder_ntohs(hdr->off_ctl);
src = byteorder_ntohs(hdr->src_port);
dst = byteorder_ntohs(hdr->dst_port);
syn = ((ctl & MSK_SYN_ACK) == MSK_SYN);
/* Validate offset */
if (GET_OFFSET(ctl) < TCP_HDR_OFFSET_MIN) {
DEBUG("gnrc_tcp_eventloop.c : _receive() : unexpected Offset Value\n");
gnrc_pktbuf_release(pkt);
return -ERANGE;
}
/* Calculate TCP header size */
hdr_size = GET_OFFSET(ctl) * 4;
/* Mark TCP header if it contains any payload */
if ((pkt->type == GNRC_NETTYPE_TCP) && (pkt->size != hdr_size)) {
tcp = gnrc_pktbuf_mark(pkt, hdr_size, GNRC_NETTYPE_TCP);
if (tcp == NULL) {
DEBUG("gnrc_tcp_eventloop.c : _receive() : Header marking failed\n");
gnrc_pktbuf_release(pkt);
return -ENOMSG;
}
pkt->type = GNRC_NETTYPE_UNDEF;
}
/* Validate checksum */
if (byteorder_ntohs(hdr->checksum) != _pkt_calc_csum(tcp, ip, pkt)) {
DEBUG("gnrc_tcp_eventloop.c : _receive() : Invalid checksum\n");
gnrc_pktbuf_release(pkt);
return -EINVAL;
}
/* Find TCB to for this packet */
mutex_lock(&_list_tcb_lock);
tcb = _list_tcb_head;
while (tcb) {
#ifdef MODULE_GNRC_IPV6
/* Check if current TCB is fitting for the incomming packet */
if (ip->type == GNRC_NETTYPE_IPV6 && tcb->address_family == AF_INET6) {
/* If SYN is set, a connection is listening on that port ... */
ipv6_addr_t *tmp_addr = NULL;
if (syn && tcb->local_port == dst && tcb->state == FSM_STATE_LISTEN) {
/* ... and local addr is unspec or pre configured */
tmp_addr = &((ipv6_hdr_t *)ip->data)->dst;
if (ipv6_addr_equal((ipv6_addr_t *) tcb->local_addr, (ipv6_addr_t *) tmp_addr) ||
ipv6_addr_is_unspecified((ipv6_addr_t *) tcb->local_addr)) {
break;
}
}
/* If SYN is not set and the ports match ... */
if (!syn && tcb->local_port == dst && tcb->peer_port == src) {
/* .. and the IPv6 addresses match */
tmp_addr = &((ipv6_hdr_t * )ip->data)->src;
if (ipv6_addr_equal((ipv6_addr_t *) tcb->peer_addr, (ipv6_addr_t *) tmp_addr)) {
break;
}
}
}
#else
/* Supress compiler warnings if TCP is build without network layer */
(void) syn;
(void) src;
(void) dst;
#endif
tcb = tcb->next;
}
mutex_unlock(&_list_tcb_lock);
/* Call FSM with event RCVD_PKT if a fitting TCB was found */
if (tcb != NULL) {
_fsm(tcb, FSM_EVENT_RCVD_PKT, pkt, NULL, 0);
}
/* No fitting TCB has been found. Respond with reset */
else {
DEBUG("gnrc_tcp_eventloop.c : _receive() : Can't find fitting tcb\n");
if ((ctl & MSK_RST) != MSK_RST) {
_pkt_build_reset_from_pkt(&reset, pkt);
gnrc_netapi_send(gnrc_tcp_pid, reset);
}
return -ENOTCONN;
}
gnrc_pktbuf_release(pkt);
return 0;
}
|
static int _receive(gnrc_pktsnip_t *pkt)
{
/* NOTE: In receiving direction: pkt = payload, payload->next = tcp, tcp->next = nw */
uint16_t ctl = 0;
uint16_t src = 0;
uint16_t dst = 0;
uint8_t hdr_size = 0;
uint8_t syn = 0;
gnrc_pktsnip_t *ip = NULL;
gnrc_pktsnip_t *reset = NULL;
gnrc_tcp_tcb_t *tcb = NULL;
tcp_hdr_t *hdr;
/* Get write access to the TCP header */
gnrc_pktsnip_t *tcp = gnrc_pktbuf_start_write(pkt);
if (tcp == NULL) {
DEBUG("gnrc_tcp_eventloop.c : _receive() : can't write to packet\n");
gnrc_pktbuf_release(pkt);
return -EACCES;
}
pkt = tcp;
#ifdef MODULE_GNRC_IPV6
/* Get IPv6 header, discard packet if doesn't contain an ip header */
LL_SEARCH_SCALAR(pkt, ip, type, GNRC_NETTYPE_IPV6);
if (ip == NULL) {
DEBUG("gnrc_tcp_eventloop.c : _receive() : pkt contains no IP Header\n");
gnrc_pktbuf_release(pkt);
return 0;
}
#endif
/* Get TCP header */
LL_SEARCH_SCALAR(pkt, tcp, type, GNRC_NETTYPE_TCP);
if (tcp == NULL) {
DEBUG("gnrc_tcp_eventloop.c : _receive() : pkt contains no TCP Header\n");
gnrc_pktbuf_release(pkt);
return 0;
}
/* Extract control bits, src and dst ports and check if SYN is set (not SYN+ACK) */
hdr = (tcp_hdr_t *)tcp->data;
ctl = byteorder_ntohs(hdr->off_ctl);
src = byteorder_ntohs(hdr->src_port);
dst = byteorder_ntohs(hdr->dst_port);
syn = ((ctl & MSK_SYN_ACK) == MSK_SYN);
/* Validate offset */
if (GET_OFFSET(ctl) < TCP_HDR_OFFSET_MIN) {
DEBUG("gnrc_tcp_eventloop.c : _receive() : unexpected Offset Value\n");
gnrc_pktbuf_release(pkt);
return -ERANGE;
}
/* Calculate TCP header size */
hdr_size = GET_OFFSET(ctl) * 4;
/* Mark TCP header if it contains any payload */
if ((pkt->type == GNRC_NETTYPE_TCP) && (pkt->size != hdr_size)) {
tcp = gnrc_pktbuf_mark(pkt, hdr_size, GNRC_NETTYPE_TCP);
if (tcp == NULL) {
DEBUG("gnrc_tcp_eventloop.c : _receive() : Header marking failed\n");
gnrc_pktbuf_release(pkt);
return -ENOMSG;
}
pkt->type = GNRC_NETTYPE_UNDEF;
}
/* Validate checksum */
if (byteorder_ntohs(hdr->checksum) != _pkt_calc_csum(tcp, ip, pkt)) {
DEBUG("gnrc_tcp_eventloop.c : _receive() : Invalid checksum\n");
gnrc_pktbuf_release(pkt);
return -EINVAL;
}
/* Find TCB to for this packet */
mutex_lock(&_list_tcb_lock);
tcb = _list_tcb_head;
while (tcb) {
#ifdef MODULE_GNRC_IPV6
/* Check if current TCB is fitting for the incomming packet */
if (ip->type == GNRC_NETTYPE_IPV6 && tcb->address_family == AF_INET6) {
/* If SYN is set, a connection is listening on that port ... */
ipv6_addr_t *tmp_addr = NULL;
if (syn && tcb->local_port == dst && tcb->state == FSM_STATE_LISTEN) {
/* ... and local addr is unspec or pre configured */
tmp_addr = &((ipv6_hdr_t *)ip->data)->dst;
if (ipv6_addr_equal((ipv6_addr_t *) tcb->local_addr, (ipv6_addr_t *) tmp_addr) ||
ipv6_addr_is_unspecified((ipv6_addr_t *) tcb->local_addr)) {
break;
}
}
/* If SYN is not set and the ports match ... */
if (!syn && tcb->local_port == dst && tcb->peer_port == src) {
/* .. and the IPv6 addresses match */
tmp_addr = &((ipv6_hdr_t * )ip->data)->src;
if (ipv6_addr_equal((ipv6_addr_t *) tcb->peer_addr, (ipv6_addr_t *) tmp_addr)) {
break;
}
}
}
#else
/* Supress compiler warnings if TCP is build without network layer */
(void) syn;
(void) src;
(void) dst;
#endif
tcb = tcb->next;
}
mutex_unlock(&_list_tcb_lock);
/* Call FSM with event RCVD_PKT if a fitting TCB was found */
if (tcb != NULL) {
_fsm(tcb, FSM_EVENT_RCVD_PKT, pkt, NULL, 0);
}
/* No fitting TCB has been found. Respond with reset */
else {
DEBUG("gnrc_tcp_eventloop.c : _receive() : Can't find fitting tcb\n");
if ((ctl & MSK_RST) != MSK_RST) {
_pkt_build_reset_from_pkt(&reset, pkt);
gnrc_netapi_send(gnrc_tcp_pid, reset);
}
gnrc_pktbuf_release(pkt);
return -ENOTCONN;
}
gnrc_pktbuf_release(pkt);
return 0;
}
|
gnrc_tcp: Fix memory leak
|
https://github.com/RIOT-OS/RIOT/commit/c6df2064aff1ffb4015d4cedbaefb8850cb50aa8
| null | null |
sys/net/gnrc/transport_layer/tcp/gnrc_tcp_eventloop.c
| 0
|
c
| false
| null |
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
) -> str:
"""Call to Modal endpoint."""
params = self.model_kwargs or {}
response = requests.post(
url=self.endpoint_url,
headers={
"Content-Type": "application/json",
},
json={"prompt": prompt, **params},
)
try:
if prompt in response.json()["prompt"]:
response_json = response.json()
except KeyError:
raise ValueError("LangChain requires 'prompt' key in response.")
text = response_json["prompt"]
if stop is not None:
# I believe this is required since the stop tokens
# are not enforced by the model parameters
text = enforce_stop_tokens(text, stop)
return text
|
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
"""Call to Modal endpoint."""
params = self.model_kwargs or {}
params = {**params, **kwargs}
response = requests.post(
url=self.endpoint_url,
headers={
"Content-Type": "application/json",
},
json={"prompt": prompt, **params},
)
try:
if prompt in response.json()["prompt"]:
response_json = response.json()
except KeyError:
raise ValueError("LangChain requires 'prompt' key in response.")
text = response_json["prompt"]
if stop is not None:
# I believe this is required since the stop tokens
# are not enforced by the model parameters
text = enforce_stop_tokens(text, stop)
return text
|
Merge remote-tracking branch 'upstream/master'
|
https://github.com/hwchase17/langchain/commit/e12294f00cb3c6d3afd6eaf0541dc3056029fc10
| null | null |
langchain/llms/modal.py
| 0
|
py
| false
|
2023-06-21T06:45:39Z
|
private void ini() {
set(hea);
set(len);
set(max);
add(bg);
add(cas);
add(con);
add(mus);
add(jm1);
set(jhea);
set(jlen);
set(jbg);
set(jcas);
set(jmax);
set(name);
set(jm0);
set(jmh);
add(lt);
set(loop);
set(lop);
set(loop1);
set(lop1);
set(minres);
set(minrest);
set(cost);
set(cos);
con.setSelected(true);
for (int i = 0; i < 4; i++)
set(star[i] = new JTF());
addListeners();
abler(false);
}
|
private void ini() {
set(hea);
set(len);
set(max);
add(bg);
add(cas);
add(con);
add(mus);
set(jhea);
set(jlen);
set(jbg);
set(jcas);
set(jmax);
set(name);
set(jm0);
set(jmh);
set(jm1);
add(lt);
set(loop);
set(lop);
set(loop1);
set(lop1);
set(minres);
set(minrest);
set(cost);
set(cos);
con.setSelected(true);
for (int i = 0; i < 4; i++)
set(star[i] = new JTF());
addListeners();
abler(false);
}
|
Added toggle to consider/ignore traits for certain attack types
|
https://github.com/battlecatsultimate/BCU-java-PC/commit/732c4b5bcf529137b46b325e97235fe479e2efb6
| null | null |
src/main/java/page/info/edit/HeadEditTable.java
| 0
|
java
| false
|
2021-05-03T00:32:57Z
|
public String executeXML(String sparqlQuery, int timeout) throws Exception {
logger.info("Json " + sparqlQuery);
initializeHybridStore(locationHdt);
ParsedQuery parsedQuery =
QueryParserUtil.parseQuery(QueryLanguage.SPARQL, sparqlQuery, null);
RepositoryConnection connection = repository.getConnection();
try {
if (parsedQuery instanceof ParsedTupleQuery) {
TupleQuery query = connection.prepareTupleQuery(sparqlQuery);
ByteArrayOutputStream out = new ByteArrayOutputStream();
TupleQueryResultHandler writer = new SPARQLResultsXMLWriter(out);
query.setMaxExecutionTime(timeout);
try {
query.evaluate(writer);
} catch (QueryEvaluationException q) {
logger.error("This exception was caught [" + q + "]");
} finally {
connection.close();
}
return out.toString("UTF8");
} else if (parsedQuery instanceof ParsedBooleanQuery) {
BooleanQuery query = model.get(locationHdt).prepareBooleanQuery(sparqlQuery);
if (query.evaluate() == true) {
connection.close();
return "{ \"head\" : { } , \"boolean\" : true }";
} else {
connection.close();
return "{ \"head\" : { } , \"boolean\" : false }";
}
} else {
System.out.println("Not knowledge-base yet: query is neither a SELECT nor an ASK");
return "Bad Request : query not supported ";
}
} finally {
connection.close();
}
}
|
public String executeXML(String sparqlQuery, int timeout) throws Exception {
logger.info("Json " + sparqlQuery);
initializeHybridStore(locationHdt);
ParsedQuery parsedQuery =
QueryParserUtil.parseQuery(QueryLanguage.SPARQL, sparqlQuery, null);
RepositoryConnection connection = repository.getConnection();
try {
if (parsedQuery instanceof ParsedTupleQuery) {
TupleQuery query = connection.prepareTupleQuery(sparqlQuery);
ByteArrayOutputStream out = new ByteArrayOutputStream();
TupleQueryResultHandler writer = new SPARQLResultsXMLWriter(out);
query.setMaxExecutionTime(timeout);
try {
query.evaluate(writer);
} catch (QueryEvaluationException q) {
logger.error("This exception was caught [" + q + "]");
} finally {
connection.close();
}
return out.toString("UTF8");
} else if (parsedQuery instanceof ParsedBooleanQuery) {
BooleanQuery query = connection.prepareBooleanQuery(sparqlQuery);
if (query.evaluate() == true) {
connection.close();
return "{ \"head\" : { } , \"boolean\" : true }";
} else {
connection.close();
return "{ \"head\" : { } , \"boolean\" : false }";
}
} else {
System.out.println("Not knowledge-base yet: query is neither a SELECT nor an ASK");
return "Bad Request : query not supported ";
}
} finally {
connection.close();
}
}
|
add step crashing and start tests
|
https://github.com/the-qa-company/qEndpoint/commit/90451be4445b0b51472755345784c13307f2a5a1
| null | null |
hdt-qs-backend/src/main/java/com/the_qa_company/q_endpoint/controller/Sparql.java
| 0
|
java
| false
|
2022-02-04T15:11:26Z
|
private void addCertCaToTrustStore(String alias, Map<String, String> certData) {
try {
File certFile = File.createTempFile("tls", "-cert");
Files.write(certFile.toPath(), Base64.getDecoder().decode(certData.get(CA_CRT)));
try {
File trustStoreFile = File.createTempFile("tls", "-truststore");
if (certData.containsKey(CA_STORE)) {
Files.write(trustStoreFile.toPath(), Base64.getDecoder().decode(certData.get(CA_STORE)));
}
try {
String trustStorePassword = certData.containsKey(CA_STORE_PASSWORD) ?
new String(Base64.getDecoder().decode(certData.get(CA_STORE_PASSWORD)), StandardCharsets.US_ASCII) :
passwordGenerator.generate();
certManager.addCertToTrustStore(certFile, alias, trustStoreFile, trustStorePassword);
certData.put(CA_STORE, Base64.getEncoder().encodeToString(Files.readAllBytes(trustStoreFile.toPath())));
certData.put(CA_STORE_PASSWORD, Base64.getEncoder().encodeToString(trustStorePassword.getBytes(StandardCharsets.US_ASCII)));
} finally {
delete(reconciliation, trustStoreFile);
}
} finally {
delete(reconciliation, certFile);
}
} catch (IOException | CertificateException | KeyStoreException | NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
|
private void addCertCaToTrustStore(String alias, Map<String, String> certData) {
try {
File certFile = Files.createTempFile("tls", "-cert").toFile();
Files.write(certFile.toPath(), Base64.getDecoder().decode(certData.get(CA_CRT)));
try {
File trustStoreFile = Files.createTempFile("tls", "-truststore").toFile();
if (certData.containsKey(CA_STORE)) {
Files.write(trustStoreFile.toPath(), Base64.getDecoder().decode(certData.get(CA_STORE)));
}
try {
String trustStorePassword = certData.containsKey(CA_STORE_PASSWORD) ?
new String(Base64.getDecoder().decode(certData.get(CA_STORE_PASSWORD)), StandardCharsets.US_ASCII) :
passwordGenerator.generate();
certManager.addCertToTrustStore(certFile, alias, trustStoreFile, trustStorePassword);
certData.put(CA_STORE, Base64.getEncoder().encodeToString(Files.readAllBytes(trustStoreFile.toPath())));
certData.put(CA_STORE_PASSWORD, Base64.getEncoder().encodeToString(trustStorePassword.getBytes(StandardCharsets.US_ASCII)));
} finally {
delete(reconciliation, trustStoreFile);
}
} finally {
delete(reconciliation, certFile);
}
} catch (IOException | CertificateException | KeyStoreException | NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
|
Improve JavaDoc comments before moving to Java 17 (#7664)
Signed-off-by: Jakub Scholz <www@scholzj.com>
|
https://github.com/strimzi/strimzi-kafka-operator/commit/9b53334d5d38ac5bf7cfb60ceed5bd84b989d2f3
| null | null |
operator-common/src/main/java/io/strimzi/operator/cluster/model/Ca.java
| 0
|
java
| false
|
2022-11-22T23:20:42Z
|
public static void loadImages() {
for (int i = 0; i <= 20; i++) {
MANA_IMAGES.put(String.valueOf(i), FSkin.getImage(FSkinProp.valueOf("IMG_MANA_" + i), manaImageSize, manaImageSize));
}
MANA_IMAGES.put("X", FSkin.getImage(FSkinProp.IMG_MANA_X, manaImageSize, manaImageSize));
MANA_IMAGES.put("Y", FSkin.getImage(FSkinProp.IMG_MANA_Y, manaImageSize, manaImageSize));
MANA_IMAGES.put("Z", FSkin.getImage(FSkinProp.IMG_MANA_Z, manaImageSize, manaImageSize));
MANA_IMAGES.put("C", FSkin.getImage(FSkinProp.IMG_MANA_COLORLESS, manaImageSize, manaImageSize));
MANA_IMAGES.put("B", FSkin.getImage(FSkinProp.IMG_MANA_B, manaImageSize, manaImageSize));
MANA_IMAGES.put("BG", FSkin.getImage(FSkinProp.IMG_MANA_HYBRID_BG, manaImageSize, manaImageSize));
MANA_IMAGES.put("BR", FSkin.getImage(FSkinProp.IMG_MANA_HYBRID_BR, manaImageSize, manaImageSize));
MANA_IMAGES.put("G", FSkin.getImage(FSkinProp.IMG_MANA_G, manaImageSize, manaImageSize));
MANA_IMAGES.put("GU", FSkin.getImage(FSkinProp.IMG_MANA_HYBRID_GU, manaImageSize, manaImageSize));
MANA_IMAGES.put("GW", FSkin.getImage(FSkinProp.IMG_MANA_HYBRID_GW, manaImageSize, manaImageSize));
MANA_IMAGES.put("R", FSkin.getImage(FSkinProp.IMG_MANA_R, manaImageSize, manaImageSize));
MANA_IMAGES.put("RG", FSkin.getImage(FSkinProp.IMG_MANA_HYBRID_RG, manaImageSize, manaImageSize));
MANA_IMAGES.put("RW", FSkin.getImage(FSkinProp.IMG_MANA_HYBRID_RW, manaImageSize, manaImageSize));
MANA_IMAGES.put("U", FSkin.getImage(FSkinProp.IMG_MANA_U, manaImageSize, manaImageSize));
MANA_IMAGES.put("UB", FSkin.getImage(FSkinProp.IMG_MANA_HYBRID_UB, manaImageSize, manaImageSize));
MANA_IMAGES.put("UR", FSkin.getImage(FSkinProp.IMG_MANA_HYBRID_UR, manaImageSize, manaImageSize));
MANA_IMAGES.put("W", FSkin.getImage(FSkinProp.IMG_MANA_W, manaImageSize, manaImageSize));
MANA_IMAGES.put("WB", FSkin.getImage(FSkinProp.IMG_MANA_HYBRID_WB, manaImageSize, manaImageSize));
MANA_IMAGES.put("WU", FSkin.getImage(FSkinProp.IMG_MANA_HYBRID_WU, manaImageSize, manaImageSize));
MANA_IMAGES.put("PW", FSkin.getImage(FSkinProp.IMG_MANA_PHRYX_W, manaImageSize, manaImageSize));
MANA_IMAGES.put("PR", FSkin.getImage(FSkinProp.IMG_MANA_PHRYX_R, manaImageSize, manaImageSize));
MANA_IMAGES.put("PU", FSkin.getImage(FSkinProp.IMG_MANA_PHRYX_U, manaImageSize, manaImageSize));
MANA_IMAGES.put("PB", FSkin.getImage(FSkinProp.IMG_MANA_PHRYX_B, manaImageSize, manaImageSize));
MANA_IMAGES.put("PG", FSkin.getImage(FSkinProp.IMG_MANA_PHRYX_G, manaImageSize, manaImageSize));
MANA_IMAGES.put("2W", FSkin.getImage(FSkinProp.IMG_MANA_2W, manaImageSize, manaImageSize));
MANA_IMAGES.put("2U", FSkin.getImage(FSkinProp.IMG_MANA_2U, manaImageSize, manaImageSize));
MANA_IMAGES.put("2R", FSkin.getImage(FSkinProp.IMG_MANA_2R, manaImageSize, manaImageSize));
MANA_IMAGES.put("2G", FSkin.getImage(FSkinProp.IMG_MANA_2G, manaImageSize, manaImageSize));
MANA_IMAGES.put("2B", FSkin.getImage(FSkinProp.IMG_MANA_2B, manaImageSize, manaImageSize));
MANA_IMAGES.put("S", FSkin.getImage(FSkinProp.IMG_MANA_SNOW, manaImageSize, manaImageSize));
MANA_IMAGES.put("T", FSkin.getImage(FSkinProp.IMG_TAP, manaImageSize, manaImageSize));
MANA_IMAGES.put("E", FSkin.getImage(FSkinProp.IMG_ENERGY, 40, 40));
MANA_IMAGES.put("EXPERIENCE", FSkin.getImage(FSkinProp.IMG_EXPERIENCE, 40, 30));
MANA_IMAGES.put("slash", FSkin.getImage(FSkinProp.IMG_SLASH, manaImageSize, manaImageSize));
MANA_IMAGES.put("attack", FSkin.getImage(FSkinProp.IMG_ATTACK, 32, 32));
MANA_IMAGES.put("defend", FSkin.getImage(FSkinProp.IMG_DEFEND, 32, 32));
MANA_IMAGES.put("summonsick", FSkin.getImage(FSkinProp.IMG_SUMMONSICK, 32, 32));
MANA_IMAGES.put("phasing", FSkin.getImage(FSkinProp.IMG_PHASING, 32, 32));
MANA_IMAGES.put("sacrifice", FSkin.getImage(FSkinProp.IMG_COSTRESERVED, 40, 40));
MANA_IMAGES.put("counters1", FSkin.getImage(FSkinProp.IMG_COUNTERS1));
MANA_IMAGES.put("counters2", FSkin.getImage(FSkinProp.IMG_COUNTERS2));
MANA_IMAGES.put("counters3", FSkin.getImage(FSkinProp.IMG_COUNTERS3));
MANA_IMAGES.put("countersMulti", FSkin.getImage(FSkinProp.IMG_COUNTERS_MULTI));
MANA_IMAGES.put("foil01", FSkin.getImage(FSkinProp.FOIL_01));
MANA_IMAGES.put("foil02", FSkin.getImage(FSkinProp.FOIL_02));
MANA_IMAGES.put("foil03", FSkin.getImage(FSkinProp.FOIL_03));
MANA_IMAGES.put("foil04", FSkin.getImage(FSkinProp.FOIL_04));
MANA_IMAGES.put("foil05", FSkin.getImage(FSkinProp.FOIL_05));
MANA_IMAGES.put("foil06", FSkin.getImage(FSkinProp.FOIL_06));
MANA_IMAGES.put("foil07", FSkin.getImage(FSkinProp.FOIL_07));
MANA_IMAGES.put("foil08", FSkin.getImage(FSkinProp.FOIL_08));
MANA_IMAGES.put("foil09", FSkin.getImage(FSkinProp.FOIL_09));
MANA_IMAGES.put("foil10", FSkin.getImage(FSkinProp.FOIL_10));
MANA_IMAGES.put("foil11", FSkin.getImage(FSkinProp.FOIL_11));
MANA_IMAGES.put("foil12", FSkin.getImage(FSkinProp.FOIL_12));
MANA_IMAGES.put("foil13", FSkin.getImage(FSkinProp.FOIL_13));
MANA_IMAGES.put("foil14", FSkin.getImage(FSkinProp.FOIL_14));
MANA_IMAGES.put("foil15", FSkin.getImage(FSkinProp.FOIL_15));
MANA_IMAGES.put("foil16", FSkin.getImage(FSkinProp.FOIL_16));
MANA_IMAGES.put("foil17", FSkin.getImage(FSkinProp.FOIL_17));
MANA_IMAGES.put("foil18", FSkin.getImage(FSkinProp.FOIL_18));
MANA_IMAGES.put("foil19", FSkin.getImage(FSkinProp.FOIL_19));
MANA_IMAGES.put("foil20", FSkin.getImage(FSkinProp.FOIL_20));
//ability icons
MANA_IMAGES.put("deathtouch", FSkin.getImage(FSkinProp.IMG_ABILITY_DEATHTOUCH));
MANA_IMAGES.put("defender", FSkin.getImage(FSkinProp.IMG_ABILITY_DEFENDER));
MANA_IMAGES.put("doublestrike", FSkin.getImage(FSkinProp.IMG_ABILITY_DOUBLE_STRIKE));
MANA_IMAGES.put("firststrike", FSkin.getImage(FSkinProp.IMG_ABILITY_FIRST_STRIKE));
MANA_IMAGES.put("fear", FSkin.getImage(FSkinProp.IMG_ABILITY_FEAR));
MANA_IMAGES.put("flash", FSkin.getImage(FSkinProp.IMG_ABILITY_FLASH));
MANA_IMAGES.put("flying", FSkin.getImage(FSkinProp.IMG_ABILITY_FLYING));
MANA_IMAGES.put("hexproof", FSkin.getImage(FSkinProp.IMG_ABILITY_HEXPROOF));
MANA_IMAGES.put("indestructible", FSkin.getImage(FSkinProp.IMG_ABILITY_INDESTRUCTIBLE));
MANA_IMAGES.put("intimidate", FSkin.getImage(FSkinProp.IMG_ABILITY_INTIMIDATE));
MANA_IMAGES.put("lifelink", FSkin.getImage(FSkinProp.IMG_ABILITY_LIFELINK));
MANA_IMAGES.put("menace", FSkin.getImage(FSkinProp.IMG_ABILITY_MENACE));
MANA_IMAGES.put("reach", FSkin.getImage(FSkinProp.IMG_ABILITY_REACH));
MANA_IMAGES.put("shroud", FSkin.getImage(FSkinProp.IMG_ABILITY_SHROUD));
MANA_IMAGES.put("trample", FSkin.getImage(FSkinProp.IMG_ABILITY_TRAMPLE));
MANA_IMAGES.put("vigilance", FSkin.getImage(FSkinProp.IMG_ABILITY_VIGILANCE));
//hexproof from
MANA_IMAGES.put("hexproofR", FSkin.getImage(FSkinProp.IMG_ABILITY_HEXPROOF_R));
MANA_IMAGES.put("hexproofG", FSkin.getImage(FSkinProp.IMG_ABILITY_HEXPROOF_G));
MANA_IMAGES.put("hexproofB", FSkin.getImage(FSkinProp.IMG_ABILITY_HEXPROOF_B));
MANA_IMAGES.put("hexproofU", FSkin.getImage(FSkinProp.IMG_ABILITY_HEXPROOF_U));
MANA_IMAGES.put("hexproofW", FSkin.getImage(FSkinProp.IMG_ABILITY_HEXPROOF_W));
MANA_IMAGES.put("hexproofC", FSkin.getImage(FSkinProp.IMG_ABILITY_HEXPROOF_C));
MANA_IMAGES.put("hexproofUB", FSkin.getImage(FSkinProp.IMG_ABILITY_HEXPROOF_UB));
//token icon
MANA_IMAGES.put("token", FSkin.getImage(FSkinProp.IMG_ABILITY_TOKEN));
//protection from
MANA_IMAGES.put("protectAll", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_ALL));
MANA_IMAGES.put("protectB", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_B));
MANA_IMAGES.put("protectBU", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_BU));
MANA_IMAGES.put("protectBW", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_BW));
MANA_IMAGES.put("protectColoredSpells", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_COLOREDSPELLS));
MANA_IMAGES.put("protectG", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_G));
MANA_IMAGES.put("protectGB", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_GB));
MANA_IMAGES.put("protectGU", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_GU));
MANA_IMAGES.put("protectGW", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_GW));
MANA_IMAGES.put("protectGeneric", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_GENERIC));
MANA_IMAGES.put("protectR", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_R));
MANA_IMAGES.put("protectRB", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_RB));
MANA_IMAGES.put("protectRG", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_RG));
MANA_IMAGES.put("protectRU", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_RU));
MANA_IMAGES.put("protectRW", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_RW));
MANA_IMAGES.put("protectU", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_U));
MANA_IMAGES.put("protectUW", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_UW));
MANA_IMAGES.put("protectW", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_W));
}
|
public static void loadImages() {
for (int i = 0; i <= 20; i++) {
MANA_IMAGES.put(String.valueOf(i), FSkin.getImage(FSkinProp.valueOf("IMG_MANA_" + i), manaImageSize, manaImageSize));
}
MANA_IMAGES.put("X", FSkin.getImage(FSkinProp.IMG_MANA_X, manaImageSize, manaImageSize));
MANA_IMAGES.put("Y", FSkin.getImage(FSkinProp.IMG_MANA_Y, manaImageSize, manaImageSize));
MANA_IMAGES.put("Z", FSkin.getImage(FSkinProp.IMG_MANA_Z, manaImageSize, manaImageSize));
MANA_IMAGES.put("C", FSkin.getImage(FSkinProp.IMG_MANA_COLORLESS, manaImageSize, manaImageSize));
MANA_IMAGES.put("B", FSkin.getImage(FSkinProp.IMG_MANA_B, manaImageSize, manaImageSize));
MANA_IMAGES.put("BG", FSkin.getImage(FSkinProp.IMG_MANA_HYBRID_BG, manaImageSize, manaImageSize));
MANA_IMAGES.put("BR", FSkin.getImage(FSkinProp.IMG_MANA_HYBRID_BR, manaImageSize, manaImageSize));
MANA_IMAGES.put("G", FSkin.getImage(FSkinProp.IMG_MANA_G, manaImageSize, manaImageSize));
MANA_IMAGES.put("GU", FSkin.getImage(FSkinProp.IMG_MANA_HYBRID_GU, manaImageSize, manaImageSize));
MANA_IMAGES.put("GW", FSkin.getImage(FSkinProp.IMG_MANA_HYBRID_GW, manaImageSize, manaImageSize));
MANA_IMAGES.put("R", FSkin.getImage(FSkinProp.IMG_MANA_R, manaImageSize, manaImageSize));
MANA_IMAGES.put("RG", FSkin.getImage(FSkinProp.IMG_MANA_HYBRID_RG, manaImageSize, manaImageSize));
MANA_IMAGES.put("RW", FSkin.getImage(FSkinProp.IMG_MANA_HYBRID_RW, manaImageSize, manaImageSize));
MANA_IMAGES.put("U", FSkin.getImage(FSkinProp.IMG_MANA_U, manaImageSize, manaImageSize));
MANA_IMAGES.put("UB", FSkin.getImage(FSkinProp.IMG_MANA_HYBRID_UB, manaImageSize, manaImageSize));
MANA_IMAGES.put("UR", FSkin.getImage(FSkinProp.IMG_MANA_HYBRID_UR, manaImageSize, manaImageSize));
MANA_IMAGES.put("W", FSkin.getImage(FSkinProp.IMG_MANA_W, manaImageSize, manaImageSize));
MANA_IMAGES.put("WB", FSkin.getImage(FSkinProp.IMG_MANA_HYBRID_WB, manaImageSize, manaImageSize));
MANA_IMAGES.put("WU", FSkin.getImage(FSkinProp.IMG_MANA_HYBRID_WU, manaImageSize, manaImageSize));
MANA_IMAGES.put("PW", FSkin.getImage(FSkinProp.IMG_MANA_PHRYX_W, manaImageSize, manaImageSize));
MANA_IMAGES.put("PR", FSkin.getImage(FSkinProp.IMG_MANA_PHRYX_R, manaImageSize, manaImageSize));
MANA_IMAGES.put("PU", FSkin.getImage(FSkinProp.IMG_MANA_PHRYX_U, manaImageSize, manaImageSize));
MANA_IMAGES.put("PB", FSkin.getImage(FSkinProp.IMG_MANA_PHRYX_B, manaImageSize, manaImageSize));
MANA_IMAGES.put("PG", FSkin.getImage(FSkinProp.IMG_MANA_PHRYX_G, manaImageSize, manaImageSize));
MANA_IMAGES.put("2W", FSkin.getImage(FSkinProp.IMG_MANA_2W, manaImageSize, manaImageSize));
MANA_IMAGES.put("2U", FSkin.getImage(FSkinProp.IMG_MANA_2U, manaImageSize, manaImageSize));
MANA_IMAGES.put("2R", FSkin.getImage(FSkinProp.IMG_MANA_2R, manaImageSize, manaImageSize));
MANA_IMAGES.put("2G", FSkin.getImage(FSkinProp.IMG_MANA_2G, manaImageSize, manaImageSize));
MANA_IMAGES.put("2B", FSkin.getImage(FSkinProp.IMG_MANA_2B, manaImageSize, manaImageSize));
MANA_IMAGES.put("S", FSkin.getImage(FSkinProp.IMG_MANA_SNOW, manaImageSize, manaImageSize));
MANA_IMAGES.put("T", FSkin.getImage(FSkinProp.IMG_TAP, manaImageSize, manaImageSize));
MANA_IMAGES.put("E", FSkin.getImage(FSkinProp.IMG_ENERGY, 40, 40));
MANA_IMAGES.put("EXPERIENCE", FSkin.getImage(FSkinProp.IMG_EXPERIENCE, 40, 30));
MANA_IMAGES.put("slash", FSkin.getImage(FSkinProp.IMG_SLASH, manaImageSize, manaImageSize));
MANA_IMAGES.put("attack", FSkin.getImage(FSkinProp.IMG_ATTACK, 32, 32));
MANA_IMAGES.put("defend", FSkin.getImage(FSkinProp.IMG_DEFEND, 32, 32));
MANA_IMAGES.put("summonsick", FSkin.getImage(FSkinProp.IMG_SUMMONSICK, 32, 32));
MANA_IMAGES.put("phasing", FSkin.getImage(FSkinProp.IMG_PHASING, 32, 32));
MANA_IMAGES.put("sacrifice", FSkin.getImage(FSkinProp.IMG_COSTRESERVED, 40, 40));
MANA_IMAGES.put("counters1", FSkin.getImage(FSkinProp.IMG_COUNTERS1));
MANA_IMAGES.put("counters2", FSkin.getImage(FSkinProp.IMG_COUNTERS2));
MANA_IMAGES.put("counters3", FSkin.getImage(FSkinProp.IMG_COUNTERS3));
MANA_IMAGES.put("countersMulti", FSkin.getImage(FSkinProp.IMG_COUNTERS_MULTI));
MANA_IMAGES.put("foil01", FSkin.getImage(FSkinProp.FOIL_01));
MANA_IMAGES.put("foil02", FSkin.getImage(FSkinProp.FOIL_02));
MANA_IMAGES.put("foil03", FSkin.getImage(FSkinProp.FOIL_03));
MANA_IMAGES.put("foil04", FSkin.getImage(FSkinProp.FOIL_04));
MANA_IMAGES.put("foil05", FSkin.getImage(FSkinProp.FOIL_05));
MANA_IMAGES.put("foil06", FSkin.getImage(FSkinProp.FOIL_06));
MANA_IMAGES.put("foil07", FSkin.getImage(FSkinProp.FOIL_07));
MANA_IMAGES.put("foil08", FSkin.getImage(FSkinProp.FOIL_08));
MANA_IMAGES.put("foil09", FSkin.getImage(FSkinProp.FOIL_09));
MANA_IMAGES.put("foil10", FSkin.getImage(FSkinProp.FOIL_10));
MANA_IMAGES.put("foil11", FSkin.getImage(FSkinProp.FOIL_11));
MANA_IMAGES.put("foil12", FSkin.getImage(FSkinProp.FOIL_12));
MANA_IMAGES.put("foil13", FSkin.getImage(FSkinProp.FOIL_13));
MANA_IMAGES.put("foil14", FSkin.getImage(FSkinProp.FOIL_14));
MANA_IMAGES.put("foil15", FSkin.getImage(FSkinProp.FOIL_15));
MANA_IMAGES.put("foil16", FSkin.getImage(FSkinProp.FOIL_16));
MANA_IMAGES.put("foil17", FSkin.getImage(FSkinProp.FOIL_17));
MANA_IMAGES.put("foil18", FSkin.getImage(FSkinProp.FOIL_18));
MANA_IMAGES.put("foil19", FSkin.getImage(FSkinProp.FOIL_19));
MANA_IMAGES.put("foil20", FSkin.getImage(FSkinProp.FOIL_20));
//ability icons
MANA_IMAGES.put("deathtouch", FSkin.getImage(FSkinProp.IMG_ABILITY_DEATHTOUCH));
MANA_IMAGES.put("defender", FSkin.getImage(FSkinProp.IMG_ABILITY_DEFENDER));
MANA_IMAGES.put("doublestrike", FSkin.getImage(FSkinProp.IMG_ABILITY_DOUBLE_STRIKE));
MANA_IMAGES.put("firststrike", FSkin.getImage(FSkinProp.IMG_ABILITY_FIRST_STRIKE));
MANA_IMAGES.put("fear", FSkin.getImage(FSkinProp.IMG_ABILITY_FEAR));
MANA_IMAGES.put("flash", FSkin.getImage(FSkinProp.IMG_ABILITY_FLASH));
MANA_IMAGES.put("flying", FSkin.getImage(FSkinProp.IMG_ABILITY_FLYING));
MANA_IMAGES.put("haste", FSkin.getImage(FSkinProp.IMG_ABILITY_HASTE));
MANA_IMAGES.put("hexproof", FSkin.getImage(FSkinProp.IMG_ABILITY_HEXPROOF));
MANA_IMAGES.put("indestructible", FSkin.getImage(FSkinProp.IMG_ABILITY_INDESTRUCTIBLE));
MANA_IMAGES.put("intimidate", FSkin.getImage(FSkinProp.IMG_ABILITY_INTIMIDATE));
MANA_IMAGES.put("lifelink", FSkin.getImage(FSkinProp.IMG_ABILITY_LIFELINK));
MANA_IMAGES.put("menace", FSkin.getImage(FSkinProp.IMG_ABILITY_MENACE));
MANA_IMAGES.put("reach", FSkin.getImage(FSkinProp.IMG_ABILITY_REACH));
MANA_IMAGES.put("shroud", FSkin.getImage(FSkinProp.IMG_ABILITY_SHROUD));
MANA_IMAGES.put("trample", FSkin.getImage(FSkinProp.IMG_ABILITY_TRAMPLE));
MANA_IMAGES.put("vigilance", FSkin.getImage(FSkinProp.IMG_ABILITY_VIGILANCE));
//hexproof from
MANA_IMAGES.put("hexproofR", FSkin.getImage(FSkinProp.IMG_ABILITY_HEXPROOF_R));
MANA_IMAGES.put("hexproofG", FSkin.getImage(FSkinProp.IMG_ABILITY_HEXPROOF_G));
MANA_IMAGES.put("hexproofB", FSkin.getImage(FSkinProp.IMG_ABILITY_HEXPROOF_B));
MANA_IMAGES.put("hexproofU", FSkin.getImage(FSkinProp.IMG_ABILITY_HEXPROOF_U));
MANA_IMAGES.put("hexproofW", FSkin.getImage(FSkinProp.IMG_ABILITY_HEXPROOF_W));
MANA_IMAGES.put("hexproofC", FSkin.getImage(FSkinProp.IMG_ABILITY_HEXPROOF_C));
MANA_IMAGES.put("hexproofUB", FSkin.getImage(FSkinProp.IMG_ABILITY_HEXPROOF_UB));
//token icon
MANA_IMAGES.put("token", FSkin.getImage(FSkinProp.IMG_ABILITY_TOKEN));
//protection from
MANA_IMAGES.put("protectAll", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_ALL));
MANA_IMAGES.put("protectB", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_B));
MANA_IMAGES.put("protectBU", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_BU));
MANA_IMAGES.put("protectBW", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_BW));
MANA_IMAGES.put("protectColoredSpells", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_COLOREDSPELLS));
MANA_IMAGES.put("protectG", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_G));
MANA_IMAGES.put("protectGB", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_GB));
MANA_IMAGES.put("protectGU", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_GU));
MANA_IMAGES.put("protectGW", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_GW));
MANA_IMAGES.put("protectGeneric", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_GENERIC));
MANA_IMAGES.put("protectR", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_R));
MANA_IMAGES.put("protectRB", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_RB));
MANA_IMAGES.put("protectRG", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_RG));
MANA_IMAGES.put("protectRU", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_RU));
MANA_IMAGES.put("protectRW", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_RW));
MANA_IMAGES.put("protectU", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_U));
MANA_IMAGES.put("protectUW", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_UW));
MANA_IMAGES.put("protectW", FSkin.getImage(FSkinProp.IMG_ABILITY_PROTECT_W));
}
|
- Fix auto mana payment for Chromatic Orrery and friends
- Fix the Haste icon crashing in desktop Forge
|
https://github.com/Card-Forge/forge/commit/71f191e71b1d3108ba6bd001fbc84c115ec16195
| null | null |
forge-gui-desktop/src/main/java/forge/toolbox/CardFaceSymbols.java
| 0
|
java
| false
| null |
def del_version(request, client_id, project, version):
if request.method == 'GET':
client = Client.objects.get(id=client_id)
try:
scrapyd = get_scrapyd(client)
result = scrapyd.delete_version(project=project, version=version)
return JsonResponse(result)
except ConnectionError:
return JsonResponse({'message': 'Connect Error'})
|
def del_version(request, client_id, project, version):
if request.method == 'GET':
client = Client.objects.get(id=client_id)
scrapyd = get_scrapyd(client)
result = scrapyd.delete_version(project=project, version=version)
return JsonResponse(result)
|
to b1
|
https://github.com/Gerapy/Gerapy/commit/e8446605eb2424717418eae199ec7aad573da2d2
| null | null |
gerapy/server/core/views.py
| 0
|
py
| false
|
2020-07-06T14:57:10Z
|
private static void initialize()
{
if (!dbManagerReady.get())
{
synchronized (dbManagerReady)
{
if (!dbManagerReady.get())
{
LOGGER.info("DatabaseManager starting initialization");
long start = System.currentTimeMillis();
register(new H2Manager());
register(new SqlServerManager());
register(new SnowflakeManager());
register(new BigQueryManager());
register(new DatabricksManager());
register(new PostgresManager());
register(new RedshiftManager());
MutableList<ConnectionExtension> extensions = Iterate.addAllTo(ServiceLoader.load(ConnectionExtension.class), Lists.mutable.empty());
extensions.flatCollect(ConnectionExtension::getAdditionalDatabaseManager).forEach(DatabaseManager::register);
dbManagerReady.getAndSet(true);
LOGGER.info("DatabaseManager initialisation took {}", System.currentTimeMillis() - start);
}
}
}
}
|
private static void initialize()
{
if (!dbManagerReady.get())
{
synchronized (dbManagerReady)
{
if (!dbManagerReady.get())
{
LOGGER.info("DatabaseManager starting initialization");
long start = System.currentTimeMillis();
register(new H2Manager());
register(new SnowflakeManager());
register(new BigQueryManager());
register(new DatabricksManager());
register(new PostgresManager());
register(new RedshiftManager());
MutableList<ConnectionExtension> extensions = Iterate.addAllTo(ServiceLoader.load(ConnectionExtension.class), Lists.mutable.empty());
extensions.flatCollect(ConnectionExtension::getAdditionalDatabaseManager).forEach(DatabaseManager::register);
dbManagerReady.getAndSet(true);
LOGGER.info("DatabaseManager initialisation took {}", System.currentTimeMillis() - start);
}
}
}
}
|
Add protocol v1_24_0 (#847)
* Add protocol v1_24_0
* Update PureClientVersions to use v1_24_0
|
https://github.com/finos/legend-engine/commit/b00cd1bc8085c5d6c778827bca59174c70eaf06c
| null | null |
legend-engine-xt-relationalStore-executionPlan-connection/src/main/java/org/finos/legend/engine/plan/execution/stores/relational/connection/driver/DatabaseManager.java
| 0
|
java
| false
| null |
function D(qa,O,X){if(X||q!=document.activeElement&&y!=document.activeElement){qa=!1;for(O=0;O<C.length;O++)X=C[O],da?"custom"==X.key&&(d.value=X.key,da=!1):null!=X.format&&("a4"==X.key?826==k.width?(k=mxRectangle.fromRectangle(k),k.width=827):826==k.height&&(k=mxRectangle.fromRectangle(k),k.height=827):"a5"==X.key&&(584==k.width?(k=mxRectangle.fromRectangle(k),k.width=583):584==k.height&&(k=mxRectangle.fromRectangle(k),k.height=583)),k.width==
X.format.width&&k.height==X.format.height?(d.value=X.key,t.setAttribute("checked","checked"),t.defaultChecked=!0,t.checked=!0,E.removeAttribute("checked"),E.defaultChecked=!1,E.checked=!1,qa=!0):k.width==X.format.height&&k.height==X.format.width&&(d.value=X.key,t.removeAttribute("checked"),t.defaultChecked=!1,t.checked=!1,E.setAttribute("checked","checked"),E.defaultChecked=!0,qa=E.checked=!0));qa?(f.style.display="",l.style.display="none"):(q.value=k.width/100,y.value=k.height/100,t.setAttribute("checked",
"checked"),d.value="custom",f.style.display="none",l.style.display="")}}
|
function D(qa,O,X){if(X||q!=document.activeElement&&y!=document.activeElement){qa=!1;for(O=0;O<C.length;O++)X=C[O],da?"custom"==X.key&&(d.value=X.key,da=!1):null!=X.format&&("a4"==X.key?826==k.width?(k=mxRectangle.fromRectangle(k),k.width=827):826==k.height&&(k=mxRectangle.fromRectangle(k),k.height=827):"a5"==X.key&&(584==k.width?(k=mxRectangle.fromRectangle(k),k.width=583):584==k.height&&(k=mxRectangle.fromRectangle(k),k.height=583)),k.width==
X.format.width&&k.height==X.format.height?(d.value=X.key,t.setAttribute("checked","checked"),t.defaultChecked=!0,t.checked=!0,E.removeAttribute("checked"),E.defaultChecked=!1,E.checked=!1,qa=!0):k.width==X.format.height&&k.height==X.format.width&&(d.value=X.key,t.removeAttribute("checked"),t.defaultChecked=!1,t.checked=!1,E.setAttribute("checked","checked"),E.defaultChecked=!0,qa=E.checked=!0));qa?(f.style.display="",m.style.display="none"):(q.value=k.width/100,y.value=k.height/100,t.setAttribute("checked",
"checked"),d.value="custom",f.style.display="none",m.style.display="")}}
|
18.1.3 release
|
https://github.com/jgraph/drawio/commit/064729fec4262f9373d9fdcafda0be47cd18dd50
|
CVE-2023-3398
|
['CWE-400']
|
src/main/webapp/js/viewer-static.min.js
| 0
|
js
| false
| null |
public boolean canPlayerModify(Player player) {
return mainNode.isReady() && mainNode.getGrid().getSecurityService().hasPermission(player, SecurityPermissions.BUILD);
}
|
public boolean canPlayerModify(Player player) {
//TODO add check
return mainNode.isReady() && mainNode.getGrid().getSecurityService().hasPermission(player, SecurityPermissions.BUILD);
}
|
update removal
|
https://github.com/Team-EnderIO/EnderIO/commit/4e6a733589c3a8033e33ead854dca6b4d3e3947d
| null | null |
src/conduits/java/com/enderio/conduits/common/integrations/ae2/AE2InWorldConduitNodeHost.java
| 0
|
java
| false
|
2022-10-18T14:55:12Z
|
public JFrame render()
{
final Colormap colormap = displaySettings.getColormap();
// X label
final String xAxisLabel = xFeature + " (" + TMUtils.getUnitsFor( xDimension, model.getSpaceUnits(), model.getTimeUnits() ) + ")";
// Find how many different dimensions
final Set< Dimension > dimensions = getUniqueValues( yFeatures, yDimensions );
// Generate one panel per different dimension
final ArrayList< ExportableChartPanel > chartPanels = new ArrayList<>( dimensions.size() );
for ( final Dimension dimension : dimensions )
{
// Y label
final String yAxisLabel = TMUtils.getUnitsFor( dimension, model.getSpaceUnits(), model.getTimeUnits() );
// Collect suitable feature for this dimension
final List< String > featuresThisDimension = getCommonKeys( dimension, yFeatures, yDimensions );
// Title
final String title = buildPlotTitle( featuresThisDimension, featureNames );
// Data-set for points (easy)
final XYSeriesCollection pointDataset = buildMainDataSet( featuresThisDimension );
// Point renderer
final XYLineAndShapeRenderer pointRenderer = new XYLineAndShapeRenderer( false, true );
// Edge renderer
final XYEdgeRenderer edgeRenderer = new XYEdgeRenderer();
// Data-set for edges
final XYEdgeSeriesCollection edgeDataset = buildConnectionDataSet( featuresThisDimension );
// The chart
final JFreeChart chart = ChartFactory.createXYLineChart( title, xAxisLabel, yAxisLabel, pointDataset, PlotOrientation.VERTICAL, true, true, false );
chart.getTitle().setFont( FONT );
chart.getLegend().setItemFont( SMALL_FONT );
chart.setBackgroundPaint( bgColor );
chart.setBorderVisible( false );
chart.getLegend().setBackgroundPaint( bgColor );
// The plot
final XYPlot plot = chart.getXYPlot();
if ( edgeDataset != null )
{
plot.setDataset( 1, edgeDataset );
plot.setRenderer( 1, edgeRenderer );
}
plot.setRenderer( 0, pointRenderer );
plot.getRangeAxis().setLabelFont( FONT );
plot.getRangeAxis().setTickLabelFont( SMALL_FONT );
plot.getDomainAxis().setLabelFont( FONT );
plot.getDomainAxis().setTickLabelFont( SMALL_FONT );
plot.setOutlineVisible( false );
plot.setDomainCrosshairVisible( false );
plot.setDomainGridlinesVisible( false );
plot.setRangeCrosshairVisible( false );
plot.setRangeGridlinesVisible( false );
plot.setBackgroundAlpha( 0f );
// Plot range.
( ( NumberAxis ) plot.getRangeAxis() ).setAutoRangeIncludesZero( false );
// Ticks. Fewer of them.
plot.getRangeAxis().setTickLabelInsets( new RectangleInsets( 20, 10, 20, 10 ) );
plot.getDomainAxis().setTickLabelInsets( new RectangleInsets( 10, 20, 10, 20 ) );
// Paint
// pointRenderer.setUseOutlinePaint( true );
if ( edgeDataset != null )
{
final int nseries = edgeDataset.getSeriesCount();
for ( int i = 0; i < nseries; i++ )
{
// pointRenderer.setSeriesOutlinePaint( i, Color.black );
pointRenderer.setSeriesLinesVisible( i, false );
pointRenderer.setSeriesShape( i, DEFAULT_SHAPE, false );
pointRenderer.setSeriesPaint( i, colormap.getPaint( ( double ) i / nseries ), false );
edgeRenderer.setSeriesPaint( i, colormap.getPaint( ( double ) i / nseries ), false );
}
}
// The panel
final ExportableChartPanel chartPanel = new ExportableChartPanel( chart );
chartPanel.setPreferredSize( new java.awt.Dimension( 500, 270 ) );
chartPanels.add( chartPanel );
}
return renderCharts( chartPanels );
}
|
public JFrame render()
{
// X label
final String xAxisLabel = xFeature + " (" + TMUtils.getUnitsFor( xDimension, spaceUnits, timeUnits ) + ")";
// Find how many different dimensions
final Set< Dimension > dimensions = getUniqueValues( yFeatures, yDimensions );
// Generate one panel per different dimension
final ArrayList< ExportableChartPanel > chartPanels = new ArrayList<>( dimensions.size() );
for ( final Dimension dimension : dimensions )
{
// Y label
final String yAxisLabel = TMUtils.getUnitsFor( dimension, spaceUnits, timeUnits );
// Collect suitable feature for this dimension
final List< String > featuresThisDimension = getCommonKeys( dimension, yFeatures, yDimensions );
// Title
final String title = buildPlotTitle( featuresThisDimension, featureNames );
// Dataset.
final ModelDataset dataset = buildMainDataSet( featuresThisDimension );
final XYItemRenderer renderer = dataset.getRenderer();
// The chart
final JFreeChart chart = ChartFactory.createXYLineChart( title, xAxisLabel, yAxisLabel, dataset, PlotOrientation.VERTICAL, true, true, false );
chart.getTitle().setFont( FONT );
chart.getLegend().setItemFont( SMALL_FONT );
chart.setBackgroundPaint( bgColor );
chart.setBorderVisible( false );
chart.getLegend().setBackgroundPaint( bgColor );
// The plot
final XYPlot plot = chart.getXYPlot();
plot.setRenderer( renderer );
plot.getRangeAxis().setLabelFont( FONT );
plot.getRangeAxis().setTickLabelFont( SMALL_FONT );
plot.getDomainAxis().setLabelFont( FONT );
plot.getDomainAxis().setTickLabelFont( SMALL_FONT );
plot.setOutlineVisible( false );
plot.setDomainCrosshairVisible( false );
plot.setDomainGridlinesVisible( false );
plot.setRangeCrosshairVisible( false );
plot.setRangeGridlinesVisible( false );
plot.setBackgroundAlpha( 0f );
// Plot range.
( ( NumberAxis ) plot.getRangeAxis() ).setAutoRangeIncludesZero( false );
// Ticks. Fewer of them.
plot.getRangeAxis().setTickLabelInsets( new RectangleInsets( 20, 10, 20, 10 ) );
plot.getDomainAxis().setTickLabelInsets( new RectangleInsets( 10, 20, 10, 20 ) );
// The panel
final ExportableChartPanel chartPanel = new ExportableChartPanel( chart );
chartPanel.setPreferredSize( new java.awt.Dimension( 500, 270 ) );
chartPanels.add( chartPanel );
}
return renderCharts( chartPanels );
}
|
Use the new spot dataset in the grapher.
Required to change Set -> List to the collection of objects to plot
and the set of features to plot.
|
https://github.com/trackmate-sc/TrackMate/commit/c15faf6268865e90b1da8be72bbeeab0605153ec
| null | null |
src/main/java/fiji/plugin/trackmate/features/AbstractFeatureGrapher.java
| 0
|
java
| false
| null |
public void writeString(@NotNull String string) {
this.ensureWriting();
byte[] stringBytes = string.getBytes(CHARSET_UTF_8);
this.writeByteArray(stringBytes);
}
|
public void writeString(@NotNull String string) {
this.ensureWriting();
byte[] stringBytes = string.getBytes(StandardCharsets.UTF_8);
this.writeByteArray(stringBytes);
}
|
Fix Bukkit not sending handshake response/crashing client
|
https://github.com/2008Choco/VeinMiner/commit/2984ce29813e6145245466c2f7d13bf82903489e
| null | null |
VeinMiner-Common/src/main/java/wtf/choco/veinminer/network/PluginMessageByteBuffer.java
| 0
|
java
| false
|
2022-01-28T22:30:43Z
|
public void addTrait(BeeTrait trait){
if (trait != null) {
if (trait.hasDamagePotionEffects()) {
this.potionDamageEffects.addAll(trait.getPotionDamageEffects());
}
if (trait.hasDamageImmunities()) {
this.damageImmunities.addAll(trait.getDamageImmunities());
}
if (trait.hasPotionImmunities()) {
this.potionImmunities.addAll(trait.getPotionImmunities());
}
if (trait.hasDamageTypes()) {
this.damageTypes.addAll(trait.getDamageTypes());
}
if (trait.hasSpecialAbilities()) {
this.specialAbilities.addAll(trait.getSpecialAbilities());
}
if (trait.hasParticleEffect()) {
this.particleEffects.add(trait.getParticleEffect());
}
}
}
|
public void addTrait(BeeTrait trait){
if (trait != null) {
if (trait.hasDamagePotionEffects()) {
this.potionDamageEffects.addAll(trait.getPotionDamageEffects());
}
if (trait.hasDamageImmunities()) {
this.damageImmunities.addAll(trait.getDamageImmunities());
}
if (trait.hasPotionImmunities()) {
this.potionImmunities.addAll(trait.getPotionImmunities());
}
if (trait.hasDamageTypes()) {
this.damageTypes.addAll(trait.getDamageTypes());
}
if (trait.hasSpecialAbilities()) {
this.specialAbilities.addAll(trait.getSpecialAbilities());
}
if (trait.hasParticleEffect()) {
this.particleEffects.add(trait.getParticleEffect());
}
if (trait.hasBeeAuras()) {
this.beeAuras.addAll(trait.getAuras());
}
}
}
|
Added initial aura code
bees can now also do other damage types with traits
the amplifier will determine how much damage each trait damage type will deal
the default sting attack will still also occur
|
https://github.com/Team-Resourceful/ResourcefulBees/commit/8aa5c6ce0ca209025f5a27685fb08d86bf76398f
| null | null |
src/main/java/com/resourcefulbees/resourcefulbees/api/beedata/TraitData.java
| 0
|
java
| false
| null |
def get_stacktrace() -> Optional[str]:
if current_app.config["SHOW_STACKTRACE"]:
return traceback.format_exc()
return None
|
def get_stacktrace() -> str | None:
if current_app.config["SHOW_STACKTRACE"]:
return traceback.format_exc()
return None
|
Merge branch 'master' into fix/db-val-param-perms
|
https://github.com/apache/superset/commit/4e2fd6f4f04c61e8c1d3ec3f233581a05f8b6213
| null | null |
superset/utils/core.py
| 0
|
py
| false
|
2023-06-05T08:42:54Z
|
public void aiStep() {
super.aiStep();
if (this.getAttackTimer() > 0) {
this.entityData.set(ATTACK_TIMER, this.getAttackTimer() - 1);
}
if (this.getRockTimer() > 0) {
this.entityData.set(ROCK_TIMER, this.getRockTimer() - 1);
}
}
|
public void aiStep() {
super.aiStep();
if (this.getRockTimer() == 5) {
this.throwRocks();
}
if (this.getAttackTimer() > 0) {
this.entityData.set(ATTACK_TIMER, this.getAttackTimer() - 1);
}
if (this.getRockTimer() > 0) {
this.entityData.set(ROCK_TIMER, this.getRockTimer() - 1);
}
}
|
Finished Dwarf throw attack and added Dwarf sounds
|
https://github.com/infernalstudios/Infernal-Expansion/commit/652ce735930a0b2db7131eeb881dc997cf07a860
| null | null |
src/main/java/org/infernalstudios/infernalexp/entities/BlackstoneDwarfEntity.java
| 0
|
java
| false
| null |
def _find_working_git(self):
test_cmd = 'version'
if app.GIT_PATH:
main_git = '"' + app.GIT_PATH + '"'
else:
main_git = 'git'
log.debug(u'Checking if we can use git commands: {0} {1}', main_git, test_cmd)
_, _, exit_status = self._run_git(main_git, test_cmd)
if exit_status == 0:
log.debug(u'Using: {0}', main_git)
return main_git
else:
log.debug(u'Not using: {0}', main_git)
# trying alternatives
alternative_git = []
# osx people who start sr from launchd have a broken path, so try a hail-mary attempt for them
if platform.system().lower() == 'darwin':
alternative_git.append('/usr/local/git/bin/git')
if platform.system().lower() == 'windows':
if main_git != main_git.lower():
alternative_git.append(main_git.lower())
if alternative_git:
log.debug(u'Trying known alternative git locations')
for cur_git in alternative_git:
log.debug(u'Checking if we can use git commands: {0} {1}', cur_git, test_cmd)
_, _, exit_status = self._run_git(cur_git, test_cmd)
if exit_status == 0:
log.debug(u'Using: {0}', cur_git)
return cur_git
else:
log.debug(u'Not using: {0}', cur_git)
|
def _find_working_git(self):
test_cmd = 'version'
main_git = app.GIT_PATH or 'git'
log.debug(u'Checking if we can use git commands: {0} {1}', main_git, test_cmd)
_, _, exit_status = self._run_git(main_git, test_cmd)
if exit_status == 0:
log.debug(u'Using: {0}', main_git)
return main_git
else:
log.debug(u'Not using: {0}', main_git)
# trying alternatives
alternative_git = []
# osx people who start sr from launchd have a broken path, so try a hail-mary attempt for them
if platform.system().lower() == 'darwin':
alternative_git.append('/usr/local/git/bin/git')
if platform.system().lower() == 'windows':
if main_git != main_git.lower():
alternative_git.append(main_git.lower())
if alternative_git:
log.debug(u'Trying known alternative git locations')
for cur_git in alternative_git:
log.debug(u'Checking if we can use git commands: {0} {1}', cur_git, test_cmd)
_, _, exit_status = self._run_git(cur_git, test_cmd)
if exit_status == 0:
log.debug(u'Using: {0}', cur_git)
return cur_git
else:
log.debug(u'Not using: {0}', cur_git)
|
Ensure that git_path is a valid file (#11138)
* Ensure that git_path is a valid file
* Update github_updater.py
|
https://github.com/pymedusa/Medusa/commit/66d4be8f0872bd5ddcdc5c5a58cb014d22834a45
| null | null |
medusa/updater/github_updater.py
| 0
|
py
| false
|
2023-02-22T10:23:45Z
|
static expr_ty
ast_for_atom(struct compiling *c, const node *n)
{
/* atom: '(' [yield_expr|testlist_comp] ')' | '[' [testlist_comp] ']'
| '{' [dictmaker|testlist_comp] '}' | NAME | NUMBER | STRING+
| '...' | 'None' | 'True' | 'False'
*/
node *ch = CHILD(n, 0);
switch (TYPE(ch)) {
case NAME: {
PyObject *name;
const char *s = STR(ch);
size_t len = strlen(s);
if (len >= 4 && len <= 5) {
if (!strcmp(s, "None"))
return NameConstant(Py_None, LINENO(n), n->n_col_offset, c->c_arena);
if (!strcmp(s, "True"))
return NameConstant(Py_True, LINENO(n), n->n_col_offset, c->c_arena);
if (!strcmp(s, "False"))
return NameConstant(Py_False, LINENO(n), n->n_col_offset, c->c_arena);
}
name = new_identifier(s, c);
if (!name)
return NULL;
/* All names start in Load context, but may later be changed. */
return Name(name, Load, LINENO(n), n->n_col_offset, c->c_arena);
}
case STRING: {
expr_ty str = parsestrplus(c, n);
if (!str) {
const char *errtype = NULL;
if (PyErr_ExceptionMatches(PyExc_UnicodeError))
errtype = "unicode error";
else if (PyErr_ExceptionMatches(PyExc_ValueError))
errtype = "value error";
if (errtype) {
char buf[128];
const char *s = NULL;
PyObject *type, *value, *tback, *errstr;
PyErr_Fetch(&type, &value, &tback);
errstr = PyObject_Str(value);
if (errstr)
s = PyUnicode_AsUTF8(errstr);
if (s) {
PyOS_snprintf(buf, sizeof(buf), "(%s) %s", errtype, s);
} else {
PyErr_Clear();
PyOS_snprintf(buf, sizeof(buf), "(%s) unknown error", errtype);
}
Py_XDECREF(errstr);
ast_error(c, n, buf);
Py_DECREF(type);
Py_XDECREF(value);
Py_XDECREF(tback);
}
return NULL;
}
return str;
}
case NUMBER: {
PyObject *pynum;
const char *s = STR(ch);
/* Underscores in numeric literals are only allowed in Python 3.6 or greater */
/* Check for underscores here rather than in parse_number so we can report a line number on error */
if (c->c_feature_version < 6 && strchr(s, '_') != NULL) {
ast_error(c, ch,
"Underscores in numeric literals are only supported in Python 3.6 and greater");
return NULL;
}
pynum = parsenumber(c, s);
if (!pynum)
return NULL;
if (PyArena_AddPyObject(c->c_arena, pynum) < 0) {
Py_DECREF(pynum);
return NULL;
}
return Num(pynum, LINENO(n), n->n_col_offset, c->c_arena);
}
case ELLIPSIS: /* Ellipsis */
return Ellipsis(LINENO(n), n->n_col_offset, c->c_arena);
case LPAR: /* some parenthesized expressions */
ch = CHILD(n, 1);
if (TYPE(ch) == RPAR)
return Tuple(NULL, Load, LINENO(n), n->n_col_offset, c->c_arena);
if (TYPE(ch) == yield_expr)
return ast_for_expr(c, ch);
/* testlist_comp: test ( comp_for | (',' test)* [','] ) */
if ((NCH(ch) > 1) && (TYPE(CHILD(ch, 1)) == comp_for))
return ast_for_genexp(c, ch);
return ast_for_testlist(c, ch);
case LSQB: /* list (or list comprehension) */
ch = CHILD(n, 1);
if (TYPE(ch) == RSQB)
return List(NULL, Load, LINENO(n), n->n_col_offset, c->c_arena);
REQ(ch, testlist_comp);
if (NCH(ch) == 1 || TYPE(CHILD(ch, 1)) == COMMA) {
asdl_seq *elts = seq_for_testlist(c, ch);
if (!elts)
return NULL;
return List(elts, Load, LINENO(n), n->n_col_offset, c->c_arena);
}
else
return ast_for_listcomp(c, ch);
case LBRACE: {
/* dictorsetmaker: ( ((test ':' test | '**' test)
* (comp_for | (',' (test ':' test | '**' test))* [','])) |
* ((test | '*' test)
* (comp_for | (',' (test | '*' test))* [','])) ) */
expr_ty res;
ch = CHILD(n, 1);
if (TYPE(ch) == RBRACE) {
/* It's an empty dict. */
return Dict(NULL, NULL, LINENO(n), n->n_col_offset, c->c_arena);
}
else {
int is_dict = (TYPE(CHILD(ch, 0)) == DOUBLESTAR);
if (NCH(ch) == 1 ||
(NCH(ch) > 1 &&
TYPE(CHILD(ch, 1)) == COMMA)) {
/* It's a set display. */
res = ast_for_setdisplay(c, ch);
}
else if (NCH(ch) > 1 &&
TYPE(CHILD(ch, 1)) == comp_for) {
/* It's a set comprehension. */
res = ast_for_setcomp(c, ch);
}
else if (NCH(ch) > 3 - is_dict &&
TYPE(CHILD(ch, 3 - is_dict)) == comp_for) {
/* It's a dictionary comprehension. */
if (is_dict) {
ast_error(c, n, "dict unpacking cannot be used in "
"dict comprehension");
return NULL;
}
res = ast_for_dictcomp(c, ch);
}
else {
/* It's a dictionary display. */
res = ast_for_dictdisplay(c, ch);
}
if (res) {
res->lineno = LINENO(n);
res->col_offset = n->n_col_offset;
}
return res;
}
}
default:
PyErr_Format(PyExc_SystemError, "unhandled atom %d", TYPE(ch));
return NULL;
}
}
|
static expr_ty
ast_for_atom(struct compiling *c, const node *n)
{
/* atom: '(' [yield_expr|testlist_comp] ')' | '[' [testlist_comp] ']'
| '{' [dictmaker|testlist_comp] '}' | NAME | NUMBER | STRING+
| '...' | 'None' | 'True' | 'False'
*/
node *ch = CHILD(n, 0);
switch (TYPE(ch)) {
case NAME: {
PyObject *name;
const char *s = STR(ch);
size_t len = strlen(s);
if (len >= 4 && len <= 5) {
if (!strcmp(s, "None"))
return NameConstant(Py_None, LINENO(n), n->n_col_offset, c->c_arena);
if (!strcmp(s, "True"))
return NameConstant(Py_True, LINENO(n), n->n_col_offset, c->c_arena);
if (!strcmp(s, "False"))
return NameConstant(Py_False, LINENO(n), n->n_col_offset, c->c_arena);
}
name = new_identifier(s, c);
if (!name)
return NULL;
/* All names start in Load context, but may later be changed. */
return Name(name, Load, LINENO(n), n->n_col_offset, c->c_arena);
}
case STRING: {
expr_ty str = parsestrplus(c, n);
if (!str) {
const char *errtype = NULL;
if (PyErr_ExceptionMatches(PyExc_UnicodeError))
errtype = "unicode error";
else if (PyErr_ExceptionMatches(PyExc_ValueError))
errtype = "value error";
if (errtype) {
char buf[128];
const char *s = NULL;
PyObject *type, *value, *tback, *errstr;
PyErr_Fetch(&type, &value, &tback);
errstr = PyObject_Str(value);
if (errstr)
s = PyUnicode_AsUTF8(errstr);
if (s) {
PyOS_snprintf(buf, sizeof(buf), "(%s) %s", errtype, s);
} else {
PyErr_Clear();
PyOS_snprintf(buf, sizeof(buf), "(%s) unknown error", errtype);
}
Py_XDECREF(errstr);
ast_error(c, n, buf);
Py_DECREF(type);
Py_XDECREF(value);
Py_XDECREF(tback);
}
return NULL;
}
return str;
}
case NUMBER: {
PyObject *pynum;
const char *s = STR(ch);
/* Underscores in numeric literals are only allowed in Python 3.6 or greater */
/* Check for underscores here rather than in parse_number so we can report a line number on error */
if (c->c_feature_version < 6 && strchr(s, '_') != NULL) {
ast_error(c, ch,
"Underscores in numeric literals are only supported in Python 3.6 and greater");
return NULL;
}
pynum = parsenumber(c, STR(ch));
if (!pynum)
return NULL;
if (PyArena_AddPyObject(c->c_arena, pynum) < 0) {
Py_DECREF(pynum);
return NULL;
}
return Num(pynum, LINENO(n), n->n_col_offset, c->c_arena);
}
case ELLIPSIS: /* Ellipsis */
return Ellipsis(LINENO(n), n->n_col_offset, c->c_arena);
case LPAR: /* some parenthesized expressions */
ch = CHILD(n, 1);
if (TYPE(ch) == RPAR)
return Tuple(NULL, Load, LINENO(n), n->n_col_offset, c->c_arena);
if (TYPE(ch) == yield_expr)
return ast_for_expr(c, ch);
/* testlist_comp: test ( comp_for | (',' test)* [','] ) */
if ((NCH(ch) > 1) && (TYPE(CHILD(ch, 1)) == comp_for))
return ast_for_genexp(c, ch);
return ast_for_testlist(c, ch);
case LSQB: /* list (or list comprehension) */
ch = CHILD(n, 1);
if (TYPE(ch) == RSQB)
return List(NULL, Load, LINENO(n), n->n_col_offset, c->c_arena);
REQ(ch, testlist_comp);
if (NCH(ch) == 1 || TYPE(CHILD(ch, 1)) == COMMA) {
asdl_seq *elts = seq_for_testlist(c, ch);
if (!elts)
return NULL;
return List(elts, Load, LINENO(n), n->n_col_offset, c->c_arena);
}
else
return ast_for_listcomp(c, ch);
case LBRACE: {
/* dictorsetmaker: ( ((test ':' test | '**' test)
* (comp_for | (',' (test ':' test | '**' test))* [','])) |
* ((test | '*' test)
* (comp_for | (',' (test | '*' test))* [','])) ) */
expr_ty res;
ch = CHILD(n, 1);
if (TYPE(ch) == RBRACE) {
/* It's an empty dict. */
return Dict(NULL, NULL, LINENO(n), n->n_col_offset, c->c_arena);
}
else {
int is_dict = (TYPE(CHILD(ch, 0)) == DOUBLESTAR);
if (NCH(ch) == 1 ||
(NCH(ch) > 1 &&
TYPE(CHILD(ch, 1)) == COMMA)) {
/* It's a set display. */
res = ast_for_setdisplay(c, ch);
}
else if (NCH(ch) > 1 &&
TYPE(CHILD(ch, 1)) == comp_for) {
/* It's a set comprehension. */
res = ast_for_setcomp(c, ch);
}
else if (NCH(ch) > 3 - is_dict &&
TYPE(CHILD(ch, 3 - is_dict)) == comp_for) {
/* It's a dictionary comprehension. */
if (is_dict) {
ast_error(c, n, "dict unpacking cannot be used in "
"dict comprehension");
return NULL;
}
res = ast_for_dictcomp(c, ch);
}
else {
/* It's a dictionary display. */
res = ast_for_dictdisplay(c, ch);
}
if (res) {
res->lineno = LINENO(n);
res->col_offset = n->n_col_offset;
}
return res;
}
}
default:
PyErr_Format(PyExc_SystemError, "unhandled atom %d", TYPE(ch));
return NULL;
}
}
|
Fully incorporate the code from Python 3.7.2 (#78)
This is a full port, following the recipe in update_process.md. I've also tried to keep the recipe up to date and improved the automation (see tools/script). I haven't cleaned up the commits. As of #77 there are a few tests that sanity-check this (though it's far from a full test suite), and they're run by Travis-CI and AppVeyor.
|
https://github.com/python/typed_ast/commit/156afcb26c198e162504a57caddfe0acd9ed7dce
| null | null |
ast3/Python/ast.c
| 0
|
c
| false
|
2019-01-23T03:09:26Z
|
async def _complete_login(
self,
user_id: str,
login_submission: JsonDict,
callback: Optional[Callable[[LoginResponse], Awaitable[None]]] = None,
create_non_existent_users: bool = False,
ratelimit: bool = True,
auth_provider_id: Optional[str] = None,
should_issue_refresh_token: bool = False,
auth_provider_session_id: Optional[str] = None,
should_check_deactivated: bool = True,
) -> LoginResponse:
"""Called when we've successfully authed the user and now need to
actually login them in (e.g. create devices). This gets called on
all successful logins.
Applies the ratelimiting for successful login attempts against an
account.
Args:
user_id: ID of the user to register.
login_submission: Dictionary of login information.
callback: Callback function to run after login.
create_non_existent_users: Whether to create the user if they don't
exist. Defaults to False.
ratelimit: Whether to ratelimit the login request.
auth_provider_id: The SSO IdP the user used, if any.
should_issue_refresh_token: True if this login should issue
a refresh token alongside the access token.
auth_provider_session_id: The session ID got during login from the SSO IdP.
should_check_deactivated: True if the user should be checked for
deactivation status before logging in.
This exists purely for appservice's configured sender_localpart
which deosn't have an associated user in the database.
Returns:
Dictionary of account information after successful login.
"""
# Before we actually log them in we check if they've already logged in
# too often. This happens here rather than before as we don't
# necessarily know the user before now.
if ratelimit:
await self._account_ratelimiter.ratelimit(None, user_id.lower())
if create_non_existent_users:
canonical_uid = await self.auth_handler.check_user_exists(user_id)
if not canonical_uid:
canonical_uid = await self.registration_handler.register_user(
localpart=UserID.from_string(user_id).localpart
)
user_id = canonical_uid
# If the account has been deactivated, do not proceed with the login.
if should_check_deactivated:
deactivated = await self._main_store.get_user_deactivated_status(user_id)
if deactivated:
raise UserDeactivatedError("This account has been deactivated")
device_id = login_submission.get("device_id")
# If device_id is present, check that device_id is not longer than a reasonable 512 characters
if device_id and len(device_id) > 512:
raise LoginError(
400,
"device_id cannot be longer than 512 characters.",
errcode=Codes.INVALID_PARAM,
)
if self._require_approval:
approved = await self.auth_handler.is_user_approved(user_id)
if not approved:
# If the user isn't approved (and needs to be) we won't allow them to
# actually log in, so we don't want to create a device/access token.
return LoginResponse(
user_id=user_id,
home_server=self.hs.hostname,
)
initial_display_name = login_submission.get("initial_device_display_name")
(
device_id,
access_token,
valid_until_ms,
refresh_token,
) = await self.registration_handler.register_device(
user_id,
device_id,
initial_display_name,
auth_provider_id=auth_provider_id,
should_issue_refresh_token=should_issue_refresh_token,
auth_provider_session_id=auth_provider_session_id,
)
result = LoginResponse(
user_id=user_id,
access_token=access_token,
home_server=self.hs.hostname,
device_id=device_id,
)
if valid_until_ms is not None:
expires_in_ms = valid_until_ms - self.clock.time_msec()
result["expires_in_ms"] = expires_in_ms
if refresh_token is not None:
result["refresh_token"] = refresh_token
if callback is not None:
await callback(result)
return result
|
async def _complete_login(
self,
user_id: str,
login_submission: JsonDict,
callback: Optional[Callable[[LoginResponse], Awaitable[None]]] = None,
create_non_existent_users: bool = False,
ratelimit: bool = True,
auth_provider_id: Optional[str] = None,
should_issue_refresh_token: bool = False,
auth_provider_session_id: Optional[str] = None,
should_check_deactivated: bool = True,
) -> LoginResponse:
"""Called when we've successfully authed the user and now need to
actually login them in (e.g. create devices). This gets called on
all successful logins.
Applies the ratelimiting for successful login attempts against an
account.
Args:
user_id: ID of the user to register.
login_submission: Dictionary of login information.
callback: Callback function to run after login.
create_non_existent_users: Whether to create the user if they don't
exist. Defaults to False.
ratelimit: Whether to ratelimit the login request.
auth_provider_id: The SSO IdP the user used, if any.
should_issue_refresh_token: True if this login should issue
a refresh token alongside the access token.
auth_provider_session_id: The session ID got during login from the SSO IdP.
should_check_deactivated: True if the user should be checked for
deactivation status before logging in.
This exists purely for appservice's configured sender_localpart
which doesn't have an associated user in the database.
Returns:
Dictionary of account information after successful login.
"""
# Before we actually log them in we check if they've already logged in
# too often. This happens here rather than before as we don't
# necessarily know the user before now.
if ratelimit:
await self._account_ratelimiter.ratelimit(None, user_id.lower())
if create_non_existent_users:
canonical_uid = await self.auth_handler.check_user_exists(user_id)
if not canonical_uid:
canonical_uid = await self.registration_handler.register_user(
localpart=UserID.from_string(user_id).localpart
)
user_id = canonical_uid
# If the account has been deactivated, do not proceed with the login.
if should_check_deactivated:
deactivated = await self._main_store.get_user_deactivated_status(user_id)
if deactivated:
raise UserDeactivatedError("This account has been deactivated")
device_id = login_submission.get("device_id")
# If device_id is present, check that device_id is not longer than a reasonable 512 characters
if device_id and len(device_id) > 512:
raise LoginError(
400,
"device_id cannot be longer than 512 characters.",
errcode=Codes.INVALID_PARAM,
)
if self._require_approval:
approved = await self.auth_handler.is_user_approved(user_id)
if not approved:
# If the user isn't approved (and needs to be) we won't allow them to
# actually log in, so we don't want to create a device/access token.
return LoginResponse(
user_id=user_id,
home_server=self.hs.hostname,
)
initial_display_name = login_submission.get("initial_device_display_name")
(
device_id,
access_token,
valid_until_ms,
refresh_token,
) = await self.registration_handler.register_device(
user_id,
device_id,
initial_display_name,
auth_provider_id=auth_provider_id,
should_issue_refresh_token=should_issue_refresh_token,
auth_provider_session_id=auth_provider_session_id,
)
result = LoginResponse(
user_id=user_id,
access_token=access_token,
home_server=self.hs.hostname,
device_id=device_id,
)
if valid_until_ms is not None:
expires_in_ms = valid_until_ms - self.clock.time_msec()
result["expires_in_ms"] = expires_in_ms
if refresh_token is not None:
result["refresh_token"] = refresh_token
if callback is not None:
await callback(result)
return result
|
Fix typos.
Co-authored-by: David Robertson <davidr@element.io>
|
https://github.com/matrix-org/synapse/commit/07e16191a10c1e3355e6263acf0e8fa5eb8905c7
| null | null |
synapse/rest/client/login.py
| 0
|
py
| false
| null |
int cp_vbnn_ver(const ec_t r, const bn_t z, const bn_t h, const uint8_t *id,
size_t id_len, const uint8_t *msg, int msg_len, const ec_t mpk) {
int len, result = 0;
uint8_t *buf = NULL, *buf_i, hash[RLC_MD_LEN];
bn_t n, c, _h;
ec_t Z;
ec_t t;
/* zero variables */
bn_null(n);
bn_null(c);
bn_null(_h);
ec_null(Z);
ec_null(t);
RLC_TRY {
bn_new(n);
bn_new(c);
bn_new(_h);
ec_new(Z);
ec_new(t);
/* calculate c */
len = id_len + msg_len + 2 * ec_size_bin(r, 1);
buf = RLC_ALLOCA(uint8_t, len);
if (buf == NULL) {
RLC_THROW(ERR_NO_MEMORY);
}
/* get order of ECC group */
ec_curve_get_ord(n);
buf_i = buf;
memcpy(buf_i, id, id_len);
buf_i += id_len;
ec_write_bin(buf_i, ec_size_bin(r, 1), r, 1);
len = id_len + ec_size_bin(r, 1);
md_map(hash, buf, len);
bn_read_bin(c, hash, RLC_MD_LEN);
bn_mod(c, c, n);
/* calculate Z */
ec_mul_gen(Z, z);
ec_mul(t, mpk, c);
ec_add(t, t, r);
ec_norm(t, t);
ec_mul(t, t, h);
ec_sub(Z, Z, t);
ec_norm(Z, Z);
/* calculate h_verify */
buf_i = buf;
memcpy(buf_i, id, id_len);
buf_i += id_len;
memcpy(buf_i, msg, msg_len);
buf_i += msg_len;
ec_write_bin(buf_i, ec_size_bin(r, 1), r, 1);
buf_i += ec_size_bin(r, 1);
ec_write_bin(buf_i, ec_size_bin(Z, 1), Z, 1);
len = id_len + msg_len + ec_size_bin(r, 1) + ec_size_bin(Z, 1);
md_map(hash, buf, len);
bn_read_bin(_h, hash, RLC_MD_LEN);
bn_mod(_h, _h, n);
RLC_FREE(buf);
if (bn_cmp(h, _h) == RLC_EQ) {
result = 1;
} else {
result = 0;
}
}
|
int cp_vbnn_ver(const ec_t r, const bn_t z, const bn_t h, const uint8_t *id,
size_t id_len, const uint8_t *msg, int msg_len, const ec_t mpk) {
size_t len;
uint8_t *buf = NULL, *buf_i, hash[RLC_MD_LEN];
bn_t n, c, _h;
ec_t Z, t;
int result = 0;
/* zero variables */
bn_null(n);
bn_null(c);
bn_null(_h);
ec_null(Z);
ec_null(t);
RLC_TRY {
bn_new(n);
bn_new(c);
bn_new(_h);
ec_new(Z);
ec_new(t);
/* calculate c */
len = id_len + msg_len + 2 * ec_size_bin(r, 1);
buf = RLC_ALLOCA(uint8_t, len);
if (buf == NULL) {
RLC_THROW(ERR_NO_MEMORY);
}
/* get order of ECC group */
ec_curve_get_ord(n);
buf_i = buf;
memcpy(buf_i, id, id_len);
buf_i += id_len;
ec_write_bin(buf_i, ec_size_bin(r, 1), r, 1);
len = id_len + ec_size_bin(r, 1);
md_map(hash, buf, len);
bn_read_bin(c, hash, RLC_MD_LEN);
bn_mod(c, c, n);
/* calculate Z */
ec_mul_gen(Z, z);
ec_mul(t, mpk, c);
ec_add(t, t, r);
ec_norm(t, t);
ec_mul(t, t, h);
ec_sub(Z, Z, t);
ec_norm(Z, Z);
/* calculate h_verify */
buf_i = buf;
memcpy(buf_i, id, id_len);
buf_i += id_len;
memcpy(buf_i, msg, msg_len);
buf_i += msg_len;
ec_write_bin(buf_i, ec_size_bin(r, 1), r, 1);
buf_i += ec_size_bin(r, 1);
ec_write_bin(buf_i, ec_size_bin(Z, 1), Z, 1);
len = id_len + msg_len + ec_size_bin(r, 1) + ec_size_bin(Z, 1);
md_map(hash, buf, len);
bn_read_bin(_h, hash, RLC_MD_LEN);
bn_mod(_h, _h, n);
RLC_FREE(buf);
if (bn_cmp(h, _h) == RLC_EQ) {
result = 1;
} else {
result = 0;
}
}
|
Huge commit improving the API to use size_t instead of int.
|
https://github.com/relic-toolkit/relic/commit/34580d840469361ba9b5f001361cad659687b9ab
| null | null |
src/cp/relic_cp_vbnn.c
| 0
|
c
| false
|
2022-11-14T20:47:12Z
|
def remove_duplicates(
items: Iterable[InputType], key: Optional[Callable[[InputType], Any]] = None
) -> List[InputType]:
"""Remove duplicate items in an iterable."""
if not key:
return list(dict.fromkeys(items).keys())
seen = set()
result = []
for item in items:
item_key = key(item)
if item_key not in seen:
seen.add(item_key)
result.append(item)
return result
|
def remove_duplicates(
items: Iterable[InputType], key: Callable[[InputType], Any] | None = None
) -> list[InputType]:
"""Remove duplicate items in an iterable."""
if not key:
return list(dict.fromkeys(items).keys())
seen = set()
result = []
for item in items:
item_key = key(item)
if item_key not in seen:
seen.add(item_key)
result.append(item)
return result
|
Merge branch 'master' into fix/db-val-param-perms
|
https://github.com/apache/superset/commit/4e2fd6f4f04c61e8c1d3ec3f233581a05f8b6213
| null | null |
superset/utils/core.py
| 0
|
py
| false
|
2023-06-05T08:42:54Z
|
static int setupStream(PRTSP_MESSAGE response, char* target, int* error) {
RTSP_MESSAGE request;
int ret;
char* transportValue;
*error = -1;
ret = initializeRtspRequest(&request, "SETUP", target);
if (ret != 0) {
if (hasSessionId) {
if (!addOption(&request, "Session", sessionIdString)) {
ret = 0;
goto FreeMessage;
}
}
if (ServerMajorVersion >= 6) {
// It looks like GFE doesn't care what we say our port is but
// we need to give it some port to successfully complete the
// handshake process.
transportValue = "unicast;X-GS-ClientPort=50000-50001";
}
else {
transportValue = " ";
}
if (addOption(&request, "Transport", transportValue) &&
addOption(&request, "If-Modified-Since",
"Thu, 01 Jan 1970 00:00:00 GMT")) {
ret = transactRtspMessage(&request, response, 0, error);
}
else {
ret = 0;
}
FreeMessage:
freeMessage(&request);
}
return ret;
}
|
static int setupStream(PRTSP_MESSAGE response, char* target, int* error) {
RTSP_MESSAGE request;
int ret;
char* transportValue;
*error = -1;
ret = initializeRtspRequest(&request, "SETUP", target);
if (ret != 0) {
if (hasSessionId) {
if (!addOption(&request, "Session", sessionIdString)) {
ret = 0;
goto FreeMessage;
}
}
if (AppVersionQuad[0] >= 6) {
// It looks like GFE doesn't care what we say our port is but
// we need to give it some port to successfully complete the
// handshake process.
transportValue = "unicast;X-GS-ClientPort=50000-50001";
}
else {
transportValue = " ";
}
if (addOption(&request, "Transport", transportValue) &&
addOption(&request, "If-Modified-Since",
"Thu, 01 Jan 1970 00:00:00 GMT")) {
ret = transactRtspMessage(&request, response, 0, error);
}
else {
ret = 0;
}
FreeMessage:
freeMessage(&request);
}
return ret;
}
|
API update to provide enough information to support GFE 3.0.7
|
https://github.com/moonlight-stream/moonlight-common-c/commit/f57bd745b4cbed577ea654fad4701bea4d38b44c
| null | null |
src/RtspConnection.c
| 0
|
c
| false
| null |
public boolean isAfterLast() throws SQLException {
return !open && !emptyResultSet;
}
|
public boolean isAfterLast() {
return !open && !emptyResultSet;
}
|
fix(jdbc): getDate, getTime, and getTimestamp crash on empty text
Closes: #490
|
https://github.com/xerial/sqlite-jdbc/commit/bc5174ba197e6e6a1d054542d3e63f1e7d09ccd9
| null | null |
src/main/java/org/sqlite/jdbc3/JDBC3ResultSet.java
| 0
|
java
| false
|
2022-08-30T08:31:15Z
|
function x(t,e){var n=L(e);return n&&(!function(t,e){e.prefinished||e.finalCalled||("function"==typeof t._final?(e.pendingcb++,e.finalCalled=!0,o.nextTick(b,t,e)):(e.prefinished=!0,t.emit("prefinish")))}(t,e),0===e.pendingcb&&(e.finished=!0,t.emit("finish"))),n}
|
function x(t,e){e=e||0;for(var r=Math.max(0,t.length-e),n=new Array(r),i=0;i<r;i++)n[i]=t[i+e];return n}
|
[API] Update swagger version
|
https://github.com/mailcow/mailcow-dockerized/commit/000894dabda7c2116f43ad6ff926962295d8095c
|
CVE-2022-39258
|
['CWE-200', 'CWE-451', 'CWE-601']
|
data/web/api/swagger-ui-standalone-preset.js
| 0
|
js
| false
|
2022-09-26T13:56:24Z
|
@Override
protected void onStart()
{
super.onStart();
if (action != null) {
boolean serviceStarted = GlobalUtils.isServiceRunning(getApplicationContext(), PhoneProfilesService.class, false);
if (!serviceStarted) {
AutostartPermissionNotification.showNotification(getApplicationContext(), true);
PPApplication.setApplicationStarted(getApplicationContext(), true);
Intent serviceIntent = new Intent(getApplicationContext(), PhoneProfilesService.class);
//serviceIntent.putExtra(PhoneProfilesService.EXTRA_DEACTIVATE_PROFILE, false);
serviceIntent.putExtra(PhoneProfilesService.EXTRA_ACTIVATE_PROFILES, false);
serviceIntent.putExtra(PPApplication.EXTRA_APPLICATION_START, true);
serviceIntent.putExtra(PPApplication.EXTRA_DEVICE_BOOT, false);
serviceIntent.putExtra(PhoneProfilesService.EXTRA_START_ON_PACKAGE_REPLACE, false);
boolean extraDataOk;
if (action.equals(ACTION_ACTIVATE_PROFILE)) {
extraDataOk = profile_id != 0;
serviceIntent.putExtra(PhoneProfilesService.EXTRA_START_FOR_EXTERNAL_APP_DATA_TYPE,
PhoneProfilesService.START_FOR_EXTERNAL_APP_PROFILE);
serviceIntent.putExtra(PhoneProfilesService.EXTRA_START_FOR_EXTERNAL_APP_DATA_VALUE, profileName);
}
else
if (!action.equals(ACTION_RESTART_EVENTS)) {
extraDataOk = event_id != 0;
serviceIntent.putExtra(PhoneProfilesService.EXTRA_START_FOR_EXTERNAL_APP_DATA_TYPE,
PhoneProfilesService.START_FOR_EXTERNAL_APP_EVENT);
serviceIntent.putExtra(PhoneProfilesService.EXTRA_START_FOR_EXTERNAL_APP_DATA_VALUE, eventName);
}
else
extraDataOk = true;
if (extraDataOk) {
serviceIntent.putExtra(PhoneProfilesService.EXTRA_START_FOR_EXTERNAL_APPLICATION, true);
serviceIntent.putExtra(PhoneProfilesService.EXTRA_START_FOR_EXTERNAL_APP_ACTION, action);
}
// PPApplication.logE("[START_PP_SERVICE] ActionForExternalApplicationActivity.onStart", "xxx");
PPApplication.startPPService(this, serviceIntent);
finish();
return;
}
switch (action) {
case ACTION_ACTIVATE_PROFILE:
PPApplication.addActivityLog(getApplicationContext(), PPApplication.ALTYPE_ACTION_FROM_EXTERNAL_APP_PROFILE_ACTIVATION,
null, profileName, "");
if (profile_id != 0) {
Profile profile = dataWrapper.getProfileById(profile_id, false, false, false);
if (profile != null) {
//if (Permissions.grantProfilePermissions(getApplicationContext(), profile, false, true,
// /*false, false, 0,*/ PPApplication.STARTUP_SOURCE_EXTERNAL_APP, false, true, false)) {
if (!DataWrapperStatic.displayPreferencesErrorNotification(profile, null, true, getApplicationContext())) {
dataWrapper.activateProfileFromMainThread(profile, false, PPApplication.STARTUP_SOURCE_EXTERNAL_APP, false, this, false);
} else
dataWrapper.finishActivity(PPApplication.STARTUP_SOURCE_EXTERNAL_APP, false, this);
}
else
dataWrapper.finishActivity(PPApplication.STARTUP_SOURCE_EXTERNAL_APP, false, this);
} else {
showNotification(getString(R.string.action_for_external_application_notification_title),
getString(R.string.action_for_external_application_notification_no_profile_text));
dataWrapper.finishActivity(PPApplication.STARTUP_SOURCE_EXTERNAL_APP, false, this);
}
break;
case ACTION_RESTART_EVENTS:
PPApplication.addActivityLog(getApplicationContext(), PPApplication.ALTYPE_ACTION_FROM_EXTERNAL_APP_RESTART_EVENTS,
null, null, "");
dataWrapper.restartEventsWithRescan(true, true, true, false, true, true);
dataWrapper.finishActivity(PPApplication.STARTUP_SOURCE_EXTERNAL_APP, false, this);
break;
case ACTION_ENABLE_RUN_FOR_EVENT:
PPApplication.addActivityLog(getApplicationContext(), PPApplication.ALTYPE_ACTION_FROM_EXTERNAL_APP_ENABLE_RUN_FOR_EVENT,
eventName, null, "");
if (event_id != 0) {
final Event event = dataWrapper.getEventById(event_id);
if (event != null) {
if (event.getStatus() != Event.ESTATUS_RUNNING) {
final Context appContext = getApplicationContext();
//PPApplication.startHandlerThread(/*"ActionForExternalApplicationActivity.onStart.1"*/);
//final Handler __handler = new Handler(PPApplication.handlerThread.getLooper());
//__handler.post(new PPHandlerThreadRunnable(
// getApplicationContext(), dataWrapper, event) {
//__handler.post(() -> {
Runnable runnable = () -> {
// PPApplication.logE("[IN_EXECUTOR] PPApplication.startHandlerThread", "START run - from=ActionForExternalApplicationActivity.onStart.1");
//Context appContext= appContextWeakRef.get();
//DataWrapper dataWrapper = dataWrapperWeakRef.get();
//Event event = eventWeakRef.get();
//if ((appContext != null) && (dataWrapper != null) && (event != null)) {
PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = null;
try {
if (powerManager != null) {
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":ActionForExternalApplicationActivity_ACTION_ENABLE_RUN_FOR_EVENT");
wakeLock.acquire(10 * 60 * 1000);
}
synchronized (PPApplication.eventsHandlerMutex) {
event.pauseEvent(dataWrapper, true, false,
false, true, null, false, false, true);
}
//_dataWrapper.restartEvents(false, true, true, true, false);
dataWrapper.restartEventsWithRescan(true, false, false, false, true, true);
} catch (Exception e) {
// PPApplication.logE("[IN_EXECUTOR] PPApplication.startHandlerThread", Log.getStackTraceString(e));
PPApplication.recordException(e);
} finally {
if ((wakeLock != null) && wakeLock.isHeld()) {
try {
wakeLock.release();
} catch (Exception ignored) {
}
}
}
//}
}; //);
PPApplication.createBasicExecutorPool();
PPApplication.basicExecutorPool.submit(runnable);
}
}
else
dataWrapper.finishActivity(PPApplication.STARTUP_SOURCE_EXTERNAL_APP, false, this);
} else {
showNotification(getString(R.string.action_for_external_application_notification_title),
getString(R.string.action_for_external_application_notification_no_event_text));
}
dataWrapper.finishActivity(PPApplication.STARTUP_SOURCE_EXTERNAL_APP, false, this);
break;
case ACTION_PAUSE_EVENT:
PPApplication.addActivityLog(getApplicationContext(), PPApplication.ALTYPE_ACTION_FROM_EXTERNAL_APP_PAUSE_EVENT,
eventName, null, "");
if (event_id != 0) {
final Event event = dataWrapper.getEventById(event_id);
if (event != null) {
if (event.getStatus() == Event.ESTATUS_RUNNING) {
final Context appContext = getApplicationContext();
//PPApplication.startHandlerThread(/*"ActionForExternalApplicationActivity.onStart.11"*/);
//final Handler __handler = new Handler(PPApplication.handlerThread.getLooper());
//__handler.post(new PPHandlerThreadRunnable(
// getApplicationContext(), dataWrapper, event) {
//__handler.post(() -> {
Runnable runnable = () -> {
// PPApplication.logE("[IN_EXECUTOR] PPApplication.startHandlerThread", "START run - from=ActionForExternalApplicationActivity.onStart.11");
//Context appContext= appContextWeakRef.get();
//DataWrapper dataWrapper = dataWrapperWeakRef.get();
//Event event = eventWeakRef.get();
//if ((appContext != null) && (dataWrapper != null) && (event != null)) {
PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = null;
try {
if (powerManager != null) {
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":ActionForExternalApplicationActivity_ACTION_PAUSE_EVENT");
wakeLock.acquire(10 * 60 * 1000);
}
synchronized (PPApplication.eventsHandlerMutex) {
event.pauseEvent(dataWrapper, true, false,
false, true, null, true, false, true);
}
} catch (Exception e) {
// PPApplication.logE("[IN_EXECUTOR] PPApplication.startHandlerThread", Log.getStackTraceString(e));
PPApplication.recordException(e);
} finally {
if ((wakeLock != null) && wakeLock.isHeld()) {
try {
wakeLock.release();
} catch (Exception ignored) {
}
}
}
//}
}; //);
PPApplication.createBasicExecutorPool();
PPApplication.basicExecutorPool.submit(runnable);
}
}
else
dataWrapper.finishActivity(PPApplication.STARTUP_SOURCE_EXTERNAL_APP, false, this);
} else {
showNotification(getString(R.string.action_for_external_application_notification_title),
getString(R.string.action_for_external_application_notification_no_event_text));
}
dataWrapper.finishActivity(PPApplication.STARTUP_SOURCE_EXTERNAL_APP, false, this);
break;
case ACTION_STOP_EVENT:
PPApplication.addActivityLog(getApplicationContext(), PPApplication.ALTYPE_ACTION_FROM_EXTERNAL_APP_STOP_EVENT,
eventName, null, "");
if (event_id != 0) {
final Event event = dataWrapper.getEventById(event_id);
if (event != null) {
if (event.getStatus() != Event.ESTATUS_STOP) {
final Context appContext = getApplicationContext();
//PPApplication.startHandlerThread(/*"ActionForExternalApplicationActivity.onStart.2"*/);
//final Handler __handler = new Handler(PPApplication.handlerThread.getLooper());
//__handler.post(new PPHandlerThreadRunnable(
// getApplicationContext(), dataWrapper, event) {
//__handler.post(() -> {
Runnable runnable = () -> {
// PPApplication.logE("[IN_EXECUTOR] PPApplication.startHandlerThread", "START run - from=ActionForExternalApplicationActivity.onStart.2");
//Context appContext= appContextWeakRef.get();
//DataWrapper dataWrapper = dataWrapperWeakRef.get();
//Event event = eventWeakRef.get();
//if ((appContext != null) && (dataWrapper != null) && (event != null)) {
PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = null;
try {
if (powerManager != null) {
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":ActionForExternalApplicationActivity_ACTION_STOP_EVENT");
wakeLock.acquire(10 * 60 * 1000);
}
synchronized (PPApplication.eventsHandlerMutex) {
event.stopEvent(dataWrapper, true, false,
true, true, true); // activate return profile
}
//_dataWrapper.restartEvents(false, true, true, true, false);
dataWrapper.restartEventsWithRescan(true, false, false, false, true, true);
} catch (Exception e) {
// PPApplication.logE("[IN_EXECUTOR] PPApplication.startHandlerThread", Log.getStackTraceString(e));
PPApplication.recordException(e);
} finally {
if ((wakeLock != null) && wakeLock.isHeld()) {
try {
wakeLock.release();
} catch (Exception ignored) {
}
}
}
//}
}; //);
PPApplication.createBasicExecutorPool();
PPApplication.basicExecutorPool.submit(runnable);
}
}
else
dataWrapper.finishActivity(PPApplication.STARTUP_SOURCE_EXTERNAL_APP, false, this);
} else {
showNotification(getString(R.string.action_for_external_application_notification_title),
getString(R.string.action_for_external_application_notification_no_event_text));
}
dataWrapper.finishActivity(PPApplication.STARTUP_SOURCE_EXTERNAL_APP, false, this);
break;
default:
showNotification(getString(R.string.action_for_external_application_notification_title),
getString(R.string.action_for_external_application_notification_bad_action));
dataWrapper.finishActivity(PPApplication.STARTUP_SOURCE_EXTERNAL_APP, false, this);
break;
}
}
else {
showNotification(getString(R.string.action_for_external_application_notification_title),
getString(R.string.action_for_external_application_notification_no_action));
dataWrapper.finishActivity(PPApplication.STARTUP_SOURCE_EXTERNAL_APP, false, this);
}
}
|
@Override
protected void onStart()
{
super.onStart();
if (action != null) {
boolean serviceStarted = GlobalUtils.isServiceRunning(getApplicationContext(), PhoneProfilesService.class, false);
if (!serviceStarted) {
AutostartPermissionNotification.showNotification(getApplicationContext(), true);
PPApplication.setApplicationStarted(getApplicationContext(), true);
Intent serviceIntent = new Intent(getApplicationContext(), PhoneProfilesService.class);
//serviceIntent.putExtra(PhoneProfilesService.EXTRA_DEACTIVATE_PROFILE, false);
serviceIntent.putExtra(PhoneProfilesService.EXTRA_ACTIVATE_PROFILES, false);
serviceIntent.putExtra(PPApplication.EXTRA_APPLICATION_START, true);
serviceIntent.putExtra(PPApplication.EXTRA_DEVICE_BOOT, false);
serviceIntent.putExtra(PhoneProfilesService.EXTRA_START_ON_PACKAGE_REPLACE, false);
boolean extraDataOk;
if (action.equals(ACTION_ACTIVATE_PROFILE)) {
extraDataOk = profile_id != 0;
serviceIntent.putExtra(PhoneProfilesService.EXTRA_START_FOR_EXTERNAL_APP_DATA_TYPE,
PhoneProfilesService.START_FOR_EXTERNAL_APP_PROFILE);
serviceIntent.putExtra(PhoneProfilesService.EXTRA_START_FOR_EXTERNAL_APP_DATA_VALUE, profileName);
}
else
if (!action.equals(ACTION_RESTART_EVENTS)) {
extraDataOk = event_id != 0;
serviceIntent.putExtra(PhoneProfilesService.EXTRA_START_FOR_EXTERNAL_APP_DATA_TYPE,
PhoneProfilesService.START_FOR_EXTERNAL_APP_EVENT);
serviceIntent.putExtra(PhoneProfilesService.EXTRA_START_FOR_EXTERNAL_APP_DATA_VALUE, eventName);
}
else
extraDataOk = true;
if (extraDataOk) {
serviceIntent.putExtra(PhoneProfilesService.EXTRA_START_FOR_EXTERNAL_APPLICATION, true);
serviceIntent.putExtra(PhoneProfilesService.EXTRA_START_FOR_EXTERNAL_APP_ACTION, action);
}
PPApplication.logE("[START_PP_SERVICE] ActionForExternalApplicationActivity.onStart", "xxx");
PPApplication.startPPService(this, serviceIntent);
finish();
return;
}
switch (action) {
case ACTION_ACTIVATE_PROFILE:
PPApplication.addActivityLog(getApplicationContext(), PPApplication.ALTYPE_ACTION_FROM_EXTERNAL_APP_PROFILE_ACTIVATION,
null, profileName, "");
if (profile_id != 0) {
Profile profile = dataWrapper.getProfileById(profile_id, false, false, false);
if (profile != null) {
//if (Permissions.grantProfilePermissions(getApplicationContext(), profile, false, true,
// /*false, false, 0,*/ PPApplication.STARTUP_SOURCE_EXTERNAL_APP, false, true, false)) {
if (!DataWrapperStatic.displayPreferencesErrorNotification(profile, null, true, getApplicationContext())) {
dataWrapper.activateProfileFromMainThread(profile, false, PPApplication.STARTUP_SOURCE_EXTERNAL_APP, false, this, false);
} else
dataWrapper.finishActivity(PPApplication.STARTUP_SOURCE_EXTERNAL_APP, false, this);
}
else
dataWrapper.finishActivity(PPApplication.STARTUP_SOURCE_EXTERNAL_APP, false, this);
} else {
showNotification(getString(R.string.action_for_external_application_notification_title),
getString(R.string.action_for_external_application_notification_no_profile_text));
dataWrapper.finishActivity(PPApplication.STARTUP_SOURCE_EXTERNAL_APP, false, this);
}
break;
case ACTION_RESTART_EVENTS:
PPApplication.addActivityLog(getApplicationContext(), PPApplication.ALTYPE_ACTION_FROM_EXTERNAL_APP_RESTART_EVENTS,
null, null, "");
dataWrapper.restartEventsWithRescan(true, true, true, false, true, true);
dataWrapper.finishActivity(PPApplication.STARTUP_SOURCE_EXTERNAL_APP, false, this);
break;
case ACTION_ENABLE_RUN_FOR_EVENT:
PPApplication.addActivityLog(getApplicationContext(), PPApplication.ALTYPE_ACTION_FROM_EXTERNAL_APP_ENABLE_RUN_FOR_EVENT,
eventName, null, "");
if (event_id != 0) {
final Event event = dataWrapper.getEventById(event_id);
if (event != null) {
if (event.getStatus() != Event.ESTATUS_RUNNING) {
final Context appContext = getApplicationContext();
//PPApplication.startHandlerThread(/*"ActionForExternalApplicationActivity.onStart.1"*/);
//final Handler __handler = new Handler(PPApplication.handlerThread.getLooper());
//__handler.post(new PPHandlerThreadRunnable(
// getApplicationContext(), dataWrapper, event) {
//__handler.post(() -> {
Runnable runnable = () -> {
// PPApplication.logE("[IN_EXECUTOR] PPApplication.startHandlerThread", "START run - from=ActionForExternalApplicationActivity.onStart.1");
//Context appContext= appContextWeakRef.get();
//DataWrapper dataWrapper = dataWrapperWeakRef.get();
//Event event = eventWeakRef.get();
//if ((appContext != null) && (dataWrapper != null) && (event != null)) {
PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = null;
try {
if (powerManager != null) {
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":ActionForExternalApplicationActivity_ACTION_ENABLE_RUN_FOR_EVENT");
wakeLock.acquire(10 * 60 * 1000);
}
synchronized (PPApplication.eventsHandlerMutex) {
event.pauseEvent(dataWrapper, true, false,
false, true, null, false, false, true);
}
//_dataWrapper.restartEvents(false, true, true, true, false);
dataWrapper.restartEventsWithRescan(true, false, false, false, true, true);
} catch (Exception e) {
// PPApplication.logE("[IN_EXECUTOR] PPApplication.startHandlerThread", Log.getStackTraceString(e));
PPApplication.recordException(e);
} finally {
if ((wakeLock != null) && wakeLock.isHeld()) {
try {
wakeLock.release();
} catch (Exception ignored) {
}
}
}
//}
}; //);
PPApplication.createBasicExecutorPool();
PPApplication.basicExecutorPool.submit(runnable);
}
}
else
dataWrapper.finishActivity(PPApplication.STARTUP_SOURCE_EXTERNAL_APP, false, this);
} else {
showNotification(getString(R.string.action_for_external_application_notification_title),
getString(R.string.action_for_external_application_notification_no_event_text));
}
dataWrapper.finishActivity(PPApplication.STARTUP_SOURCE_EXTERNAL_APP, false, this);
break;
case ACTION_PAUSE_EVENT:
PPApplication.addActivityLog(getApplicationContext(), PPApplication.ALTYPE_ACTION_FROM_EXTERNAL_APP_PAUSE_EVENT,
eventName, null, "");
if (event_id != 0) {
final Event event = dataWrapper.getEventById(event_id);
if (event != null) {
if (event.getStatus() == Event.ESTATUS_RUNNING) {
final Context appContext = getApplicationContext();
//PPApplication.startHandlerThread(/*"ActionForExternalApplicationActivity.onStart.11"*/);
//final Handler __handler = new Handler(PPApplication.handlerThread.getLooper());
//__handler.post(new PPHandlerThreadRunnable(
// getApplicationContext(), dataWrapper, event) {
//__handler.post(() -> {
Runnable runnable = () -> {
// PPApplication.logE("[IN_EXECUTOR] PPApplication.startHandlerThread", "START run - from=ActionForExternalApplicationActivity.onStart.11");
//Context appContext= appContextWeakRef.get();
//DataWrapper dataWrapper = dataWrapperWeakRef.get();
//Event event = eventWeakRef.get();
//if ((appContext != null) && (dataWrapper != null) && (event != null)) {
PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = null;
try {
if (powerManager != null) {
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":ActionForExternalApplicationActivity_ACTION_PAUSE_EVENT");
wakeLock.acquire(10 * 60 * 1000);
}
synchronized (PPApplication.eventsHandlerMutex) {
event.pauseEvent(dataWrapper, true, false,
false, true, null, true, false, true);
}
} catch (Exception e) {
// PPApplication.logE("[IN_EXECUTOR] PPApplication.startHandlerThread", Log.getStackTraceString(e));
PPApplication.recordException(e);
} finally {
if ((wakeLock != null) && wakeLock.isHeld()) {
try {
wakeLock.release();
} catch (Exception ignored) {
}
}
}
//}
}; //);
PPApplication.createBasicExecutorPool();
PPApplication.basicExecutorPool.submit(runnable);
}
}
else
dataWrapper.finishActivity(PPApplication.STARTUP_SOURCE_EXTERNAL_APP, false, this);
} else {
showNotification(getString(R.string.action_for_external_application_notification_title),
getString(R.string.action_for_external_application_notification_no_event_text));
}
dataWrapper.finishActivity(PPApplication.STARTUP_SOURCE_EXTERNAL_APP, false, this);
break;
case ACTION_STOP_EVENT:
PPApplication.addActivityLog(getApplicationContext(), PPApplication.ALTYPE_ACTION_FROM_EXTERNAL_APP_STOP_EVENT,
eventName, null, "");
if (event_id != 0) {
final Event event = dataWrapper.getEventById(event_id);
if (event != null) {
if (event.getStatus() != Event.ESTATUS_STOP) {
final Context appContext = getApplicationContext();
//PPApplication.startHandlerThread(/*"ActionForExternalApplicationActivity.onStart.2"*/);
//final Handler __handler = new Handler(PPApplication.handlerThread.getLooper());
//__handler.post(new PPHandlerThreadRunnable(
// getApplicationContext(), dataWrapper, event) {
//__handler.post(() -> {
Runnable runnable = () -> {
// PPApplication.logE("[IN_EXECUTOR] PPApplication.startHandlerThread", "START run - from=ActionForExternalApplicationActivity.onStart.2");
//Context appContext= appContextWeakRef.get();
//DataWrapper dataWrapper = dataWrapperWeakRef.get();
//Event event = eventWeakRef.get();
//if ((appContext != null) && (dataWrapper != null) && (event != null)) {
PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = null;
try {
if (powerManager != null) {
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":ActionForExternalApplicationActivity_ACTION_STOP_EVENT");
wakeLock.acquire(10 * 60 * 1000);
}
synchronized (PPApplication.eventsHandlerMutex) {
event.stopEvent(dataWrapper, true, false,
true, true, true); // activate return profile
}
//_dataWrapper.restartEvents(false, true, true, true, false);
dataWrapper.restartEventsWithRescan(true, false, false, false, true, true);
} catch (Exception e) {
// PPApplication.logE("[IN_EXECUTOR] PPApplication.startHandlerThread", Log.getStackTraceString(e));
PPApplication.recordException(e);
} finally {
if ((wakeLock != null) && wakeLock.isHeld()) {
try {
wakeLock.release();
} catch (Exception ignored) {
}
}
}
//}
}; //);
PPApplication.createBasicExecutorPool();
PPApplication.basicExecutorPool.submit(runnable);
}
}
else
dataWrapper.finishActivity(PPApplication.STARTUP_SOURCE_EXTERNAL_APP, false, this);
} else {
showNotification(getString(R.string.action_for_external_application_notification_title),
getString(R.string.action_for_external_application_notification_no_event_text));
}
dataWrapper.finishActivity(PPApplication.STARTUP_SOURCE_EXTERNAL_APP, false, this);
break;
default:
showNotification(getString(R.string.action_for_external_application_notification_title),
getString(R.string.action_for_external_application_notification_bad_action));
dataWrapper.finishActivity(PPApplication.STARTUP_SOURCE_EXTERNAL_APP, false, this);
break;
}
}
else {
showNotification(getString(R.string.action_for_external_application_notification_title),
getString(R.string.action_for_external_application_notification_no_action));
dataWrapper.finishActivity(PPApplication.STARTUP_SOURCE_EXTERNAL_APP, false, this);
}
}
|
Fix: Maybe fixed: android.app.RemoteServiceException: Bad notification(tag=null, id=100) posted from package sk.henrichg.phoneprofilesplus, crashing app(uid=10258, pid=11649): Couldn't inflate contentViewsandroid.view.InflateException: Binary XML file line #2 in sk.henrichg.phoneprofilesplus:layout/popup_window_run_stop_indicator: Binary XML file line #2 in sk.henrichg.phoneprofilesplus:layout/popup_window_run_stop_indicator: Error inflating class androidx.cardview.widget.CardView.
|
https://github.com/henrichg/PhoneProfilesPlus/commit/c6f2ebe8b00b13bbc5379a4a7cc72069a2710242
| null | null |
phoneProfilesPlus/src/main/java/sk/henrichg/phoneprofilesplus/ActionForExternalApplicationActivity.java
| 0
|
java
| false
|
2022-09-23T18:30:21Z
|
void UpdateProfile(DeviceProfile profile);
|
void UpdateProfile(string profileId, DeviceProfile profile);
|
Merge remote-tracking branch 'upstream/master' into client-logger
|
https://github.com/jellyfin/jellyfin/commit/f444e93a56f6613baa8a722099159f2935d4d942
| null | null |
MediaBrowser.Controller/Dlna/IDlnaManager.cs
| 0
|
cs
| false
|
2021-11-02T23:56:12Z
|
function a(){o.removeClass("active").find("> .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),i.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),s?(i[0].offsetWidth,i.addClass("in")):i.removeClass("fade"),i.parent(".dropdown-menu").length&&i.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),r&&r()}
|
function a(){n._addClass(i.newTab.closest("li"),"ui-tabs-active","ui-state-active"),r.length&&n.options.show?n._show(r,n.options.show,s):(r.show(),s())}
|
Merge pull request #10171 from snipe/fixes/xss_svg_in_file_uploads
Fixed SVG XSS vuln
|
https://github.com/snipe/snipe-it/commit/fc5efd857f61f7e45c61db567bb66612bcb53128
|
CVE-2021-3863
|
['CWE-79']
|
public/js/dist/all.js
| 0
|
js
| false
|
2021-10-06T19:38:51Z
|
@DaemonOnly
@HiddenMethod(name = "strDebugOpToOp", type = MType.STATIC_METHOD, cls = AppOpsManager.class)
public abstract int strDebugOpToOp(String opName) throws NoSuchMethodError;
|
@DaemonOnly
@HiddenMethod(name = "strDebugOpToOp", type = MType.STATIC_METHOD, cls = AppOpsManager.class)
public abstract int strDebugOpToOp(String opName) throws HiddenAPIsError;
|
Bump library versions
|
https://github.com/mirfatif/PermissionManagerX/commit/a73b6999996e43e52238f5dc31c037bb97efd5fa
| null | null |
priv_library/src/main/java/com/mirfatif/privtasks/hiddenapis/HiddenAPIs.java
| 0
|
java
| false
|
2021-02-15T23:50:27Z
|
static ANTLR3_INLINE
void mSLASH(pbelle_sip_messageLexer ctx)
{
ANTLR3_UINT32 _type;
_type = SLASH;
// ../grammars/belle_sip_message.g:2058:3: ( '/' )
// ../grammars/belle_sip_message.g:2058:5: '/'
{
MATCHC('/');
if (HASEXCEPTION())
{
goto ruleSLASHEx;
}
}
LEXSTATE->type = _type;
// This is where rules clean up and exit
//
goto ruleSLASHEx; /* Prevent compiler warnings */
ruleSLASHEx: ;
}
|
static ANTLR3_INLINE
void mSLASH(pbelle_sip_messageLexer ctx)
{
ANTLR3_UINT32 _type;
_type = SLASH;
// ../grammars/belle_sip_message.g:2059:3: ( '/' )
// ../grammars/belle_sip_message.g:2059:5: '/'
{
MATCHC('/');
if (HASEXCEPTION())
{
goto ruleSLASHEx;
}
}
LEXSTATE->type = _type;
// This is where rules clean up and exit
//
goto ruleSLASHEx; /* Prevent compiler warnings */
ruleSLASHEx: ;
}
|
Fix crash while receiving some kind of invalid from header.
|
https://github.com/BelledonneCommunications/belle-sip/commit/116e3eb48fe43ea63eb9f3c4b4b30c48d58d6ff0
| null | null |
src/grammars/belle_sip_messageLexer.c
| 0
|
c
| false
|
2021-05-13T14:08:12Z
|
protected final void setBlock(final BlockWrapper cb) {
final IBlock block = getWorld().getBlock(this.getTargetBlock().getX() + cb.getX(), this.getTargetBlock().getY() + cb.getY(), this.getTargetBlock().getZ() + cb.getZ());
addOperation(new BlockOperation(block.getLocation(), block.getBlockData(), cb.getBlockData()));
block.setBlockData(cb.getBlockData());
}
|
protected final void setBlock(final BlockWrapper cb) {
final IBlock block = getWorld().getBlock(this.getTargetBlock().getX() + cb.getX(), this.getTargetBlock().getY() + cb.getY(), this.getTargetBlock().getZ() + cb.getZ());
addOperation(new BlockOperation(block.getLocation(), block.getBlockData(), cb.getBlockData()));
}
|
Added BrushUsersCounter (#98)
* Added BrushUsersCounter
* Added some structure and comments to the main class
* Fix
* Another fix
Co-authored-by: Lennart99 <le.le@live.nl>
|
https://github.com/KevinDaGame/VoxelSniper-Reimagined/commit/9d8073798b209230b78dbe814151548839c422c0
| null | null |
VoxelSniperCore/src/main/java/com/github/kevindagame/brush/StampBrush.java
| 0
|
java
| false
|
2023-01-07T19:55:00Z
|
@SuppressWarnings("deprecation")
public static BuildType getBuildType(Context ctx) {
try {
Signature[] signatures;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
// NOTE: PCAPdroid does not use multiple signatures
PackageInfo pInfo = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), PackageManager.GET_SIGNING_CERTIFICATES);
signatures = (pInfo.signingInfo == null) ? null : pInfo.signingInfo.getSigningCertificateHistory();
} else {
PackageInfo pInfo = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), PackageManager.GET_SIGNATURES);
signatures = pInfo.signatures;
}
// can be null in robolectric tests
if((signatures == null) || (signatures.length < 1))
return BuildType.UNKNOWN;
MessageDigest sha1 = MessageDigest.getInstance("SHA");
sha1.update(signatures[0].toByteArray());
// keytool -printcert -jarfile file.apk
String hex = byteArrayToHex(sha1.digest(), sha1.getDigestLength());
switch(hex) {
case "511140392BFF2CFB4BD825895DD6510CE1807F6D":
return BuildType.DEBUG;
case "EE953D4F988C8AC17575DFFAA1E3BBCE2E29E81D":
return isPlaystore() ? BuildType.PLAYSTORE : BuildType.GITHUB;
case "72777D6939EF150099219BBB68C17220DB28EA8E":
return BuildType.FDROID;
case "9F030FABC158A428CFDB90570A426EA88B39A153":
return BuildType.WORKFLOW;
}
} catch (PackageManager.NameNotFoundException | NoSuchAlgorithmException e) {
Log.e("Utils", "Could not retrieve package version");
}
return BuildType.UNKNOWN;
}
|
@SuppressWarnings("deprecation")
public static BuildType getBuildType(Context ctx) {
try {
Signature[] signatures;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
// NOTE: PCAPdroid does not use multiple signatures
PackageInfo pInfo = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), PackageManager.GET_SIGNING_CERTIFICATES);
signatures = (pInfo.signingInfo == null) ? null : pInfo.signingInfo.getSigningCertificateHistory();
} else {
PackageInfo pInfo = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), PackageManager.GET_SIGNATURES);
signatures = pInfo.signatures;
}
// can be null in robolectric tests
if((signatures == null) || (signatures.length < 1))
return BuildType.UNKNOWN;
MessageDigest sha1 = MessageDigest.getInstance("SHA");
sha1.update(signatures[0].toByteArray());
// keytool -printcert -jarfile file.apk
String hex = byteArrayToHex(sha1.digest(), sha1.getDigestLength());
switch(hex) {
case "511140392BFF2CFB4BD825895DD6510CE1807F6D":
return BuildType.DEBUG;
case "EE953D4F988C8AC17575DFFAA1E3BBCE2E29E81D":
return isPlaystore() ? BuildType.PLAYSTORE : BuildType.GITHUB;
case "72777D6939EF150099219BBB68C17220DB28EA8E":
return BuildType.FDROID;
case "9F030FABC158A428CFDB90570A426EA88B39A153":
return BuildType.WORKFLOW;
}
} catch (PackageManager.NameNotFoundException | NoSuchAlgorithmException e) {
Log.e("Utils", "Could not determine the build type");
}
return BuildType.UNKNOWN;
}
|
Fix CaptureCtrl crash on Android 11/12
The CaptureCtrl is only started when the PCAPdroid control API is
invoked. The crash occurred because getInsetsController was called
before setContentView.
Fixes #179
|
https://github.com/emanuele-f/PCAPdroid/commit/cebeb37a384ac73757fbdec52a06b281f9e19f03
| null | null |
app/src/main/java/com/emanuelef/remote_capture/Utils.java
| 0
|
java
| false
|
2022-01-14T11:51:19Z
|
private static void throwError (Throwable throwable) {
StackTraceElement[] elements = throwable.getStackTrace();
if (elements != null) {
StackTraceElement[] newElements = new StackTraceElement[elements.length + 1];
System.arraycopy(elements, 0, newElements, 1, elements.length);
newElements[0] = new StackTraceElement("org.drinkmore.Tracer", "throwError", "Tracer.java", 49);
throwable.setStackTrace(newElements);
}
if (throwable instanceof ClientException_1451)
throw (ClientException_1451) throwable;
RuntimeException exception = new RuntimeException(format(throwable.getClass().getSimpleName() + ": " + throwable.getMessage()), throwable.getCause());
exception.setStackTrace(throwable.getStackTrace());
throw exception;
}
|
private static void throwError (Throwable throwable) {
StackTraceElement[] elements = throwable.getStackTrace();
if (elements != null) {
StackTraceElement[] newElements = new StackTraceElement[elements.length + 1];
System.arraycopy(elements, 0, newElements, 1, elements.length);
newElements[0] = new StackTraceElement("org.drinkmore.Tracer", "throwError", "Tracer.java", 49);
throwable.setStackTrace(newElements);
}
if (throwable instanceof ClientException_1452)
throw (ClientException_1452) throwable;
RuntimeException exception = new RuntimeException(format(throwable.getClass().getSimpleName() + ": " + throwable.getMessage()), throwable.getCause());
exception.setStackTrace(throwable.getStackTrace());
throw exception;
}
|
version bump to 1452 + fixed crash when trying to clear from cache
|
https://github.com/TGX-Android/Telegram-X/commit/bbf9d6bb6599b66a1d9cdd7b1f2962d0ab64bcc2
| null | null |
app/src/main/java/org/drinkmore/Tracer.java
| 0
|
java
| false
|
2021-10-29T16:34:45Z
|
function RootElement(doc, name) {
var _this;
var rootName = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'main';
Object(_var_www_lime25_limesurvey_assets_packages_questiongroup_node_modules_babel_runtime_corejs2_helpers_esm_classCallCheck__WEBPACK_IMPORTED_MODULE_2__["default"])(this, RootElement);
_this = Object(_var_www_lime25_limesurvey_assets_packages_questiongroup_node_modules_babel_runtime_corejs2_helpers_esm_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__["default"])(this, Object(_var_www_lime25_limesurvey_assets_packages_questiongroup_node_modules_babel_runtime_corejs2_helpers_esm_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(RootElement).call(this, name));
/**
* Document that is an owner of this root.
*
* @private
* @member {module:engine/model/document~Document}
*/
_this._doc = doc;
/**
* Unique root name used to identify this root element by {@link module:engine/model/document~Document}.
*
* @readonly
* @member {String}
*/
_this.rootName = rootName;
return _this;
}
|
function RootElement(doc, name) {
var _this;
var rootName = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'main';
Object(_var_www_limedev_assets_packages_questiongroup_node_modules_babel_runtime_corejs2_helpers_esm_classCallCheck__WEBPACK_IMPORTED_MODULE_2__["default"])(this, RootElement);
_this = Object(_var_www_limedev_assets_packages_questiongroup_node_modules_babel_runtime_corejs2_helpers_esm_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__["default"])(this, Object(_var_www_limedev_assets_packages_questiongroup_node_modules_babel_runtime_corejs2_helpers_esm_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(RootElement).call(this, name));
/**
* Document that is an owner of this root.
*
* @private
* @member {module:engine/model/document~Document}
*/
_this._doc = doc;
/**
* Unique root name used to identify this root element by {@link module:engine/model/document~Document}.
*
* @readonly
* @member {String}
*/
_this.rootName = rootName;
return _this;
}
|
DEV: changed routes in vue.js part questiongroupedit.js and deleted old controller+views
|
https://github.com/LimeSurvey/LimeSurvey/commit/d7a309bf1a73e95187528982b9db7ec03fee6913
|
CVE-2020-23710
|
['CWE-79']
|
assets/packages/questiongroup/build/js/questiongroupedit.js
| 0
|
js
| false
|
2020-06-08T09:23:29Z
|
public static boolean adjustCamera(IWrapperPlayer player, Point3D cameraAdjustedPosition, RotationMatrix cameraRotation, float partialTicks) {
//Get variables.
AEntityB_Existing ridingEntity = player.getEntityRiding();
PartSeat sittingSeat = ridingEntity instanceof PartSeat ? (PartSeat) ridingEntity : null;
EntityVehicleF_Physics ridingVehicle = sittingSeat != null ? sittingSeat.vehicleOn : null;
EntityPlayerGun playerGunEntity = EntityPlayerGun.playerClientGuns.get(player.getID());
//Reset FOV, sensitivity, overlay, and effect.
if (!enableCustomCameras) {
if (currentFOV != 0) {
InterfaceManager.clientInterface.setFOV(currentFOV);
currentFOV = 0;
}
if (currentMouseSensitivity != 0) {
InterfaceManager.clientInterface.setMouseSensitivity(currentMouseSensitivity);
currentMouseSensitivity = 0;
}
}
customCameraOverlay = null;
if (nightVisionEnabled) {
player.removePotionEffect(NIGHT_VISION_CAMERA_POTION);
nightVisionEnabled = false;
}
//Do camera operations.
if (InterfaceManager.clientInterface.inFirstPerson()) {
//Force custom cameras for some states.
//If we are sneaking and holding a gun, or it has forced cameras, enable custom cameras.
if (playerGunEntity != null && playerGunEntity.activeGun != null && sittingSeat == null) {
enableCustomCameras = playerGunEntity.activeGun.isHandHeldGunAimed || playerGunEntity.activeGun.definition.gun.forceHandheldCameras;
customCameraIndex = 0;
}
//If our seat is set to automatically use custom cameras, enable them.
if (!enableCustomCameras && sittingSeat != null && sittingSeat.placementDefinition.forceCameras) {
enableCustomCameras = true;
customCameraIndex = 0;
}
//Do custom camera, or do normal rendering.
if (enableCustomCameras) {
//Get cameras from entity or hand-held gun.
//We check active cameras until we find one that we can use.
runningCustomCameras = true;
customCamerasChecked = 0;
JSONCameraObject camera = null;
AEntityD_Definable<?> cameraProvider = null;
AnimationSwitchbox switchbox = null;
if (ridingVehicle != null) {
camera = checkProviderForCameras(ridingVehicle, partialTicks);
if (camera != null) {
cameraProvider = ridingVehicle;
switchbox = ridingVehicle.cameraSwitchboxes.get(camera);
}
if (camera == null) {
for (APart part : ridingVehicle.allParts) {
camera = checkProviderForCameras(part, partialTicks);
if (camera != null) {
cameraProvider = part;
switchbox = part.cameraSwitchboxes.get(camera);
break;
}
}
}
} else if (playerGunEntity != null && playerGunEntity.activeGun != null) {
camera = checkProviderForCameras(playerGunEntity.activeGun, partialTicks);
if (camera != null) {
cameraProvider = playerGunEntity.activeGun;
switchbox = playerGunEntity.activeGun.cameraSwitchboxes.get(camera);
}
}
//If we found a camera, use it. If not, turn off custom cameras and go back to first-person mode.
if (camera != null) {
//Set current overlay for future calls.
customCameraOverlay = camera.overlay != null ? camera.overlay + ".png" : null;
//If the camera has an FOV override, apply it.
if (camera.fovOverride != 0) {
if (currentFOV == 0) {
currentFOV = InterfaceManager.clientInterface.getFOV();
}
InterfaceManager.clientInterface.setFOV(camera.fovOverride);
}
//If the camera has a mouse sensitivity override, apply it.
if (camera.mouseSensitivityOverride != 0) {
if (currentMouseSensitivity == 0) {
currentMouseSensitivity = InterfaceManager.clientInterface.getMouseSensitivity();
}
InterfaceManager.clientInterface.setMouseSensitivity(camera.mouseSensitivityOverride);
}
//First set the position of the camera to the defined position.
cameraAdjustedPosition.set(camera.pos);
//Now run transforms on this position to get it's proper position.
if (switchbox != null) {
switchbox.runSwitchbox(partialTicks, false);
cameraAdjustedPosition.transform(switchbox.netMatrix);
}
//Get the rotational component of the operation.
//First, get the orientation of the entity we are on.
cameraProvider.getInterpolatedOrientation(cameraRotation, partialTicks);
//We need to rotate the camera position by our orientation here.
//This puts the position into global orientation rather than animation-local.
cameraAdjustedPosition.rotate(cameraRotation);
//Now add the rotation from the animation, plus the definition rotation, if we have it.
if (switchbox != null) {
cameraRotation.multiply(switchbox.rotation);
}
if (camera.rot != null) {
cameraRotation.multiply(camera.rot);
}
//Rotational portion is good. Finally, get the offset from the player to the provider origin.
//This is required as that's the camera's reference point.
//However, the math is in global space so just add to our offset.
cameraOffset.set(cameraProvider.prevPosition).interpolate(cameraProvider.position, partialTicks).subtract(player.getRenderedPosition(partialTicks));
cameraOffset.y -= player.getEyeHeight();
cameraAdjustedPosition.add(cameraOffset);
//Also check night vision.
if (camera.nightVision) {
player.addPotionEffect(NIGHT_VISION_CAMERA_POTION);
nightVisionEnabled = true;
}
return true;
}
//We wern't running a custom camera. Set running variable to false.
enableCustomCameras = false;
runningCustomCameras = false;
} else if (sittingSeat != null) {
sittingSeat.getInterpolatedOrientation(cameraRotation, partialTicks);
double eyeHeight = player.getEyeHeight();
double seatOffset = player.getSeatOffset();
double verticalScale = player.getVerticalScale();
cameraAdjustedPosition.set(0, (eyeHeight + seatOffset) * verticalScale, 0).rotate(cameraRotation).add(0, -eyeHeight, 0);
sittingSeat.getRiderInterpolatedOrientation(riderOrientation, partialTicks);
cameraRotation.multiply(riderOrientation);
return true;
} else {
//No custom camera, and no seat camera modifications. Standard world view.
enableCustomCameras = false;
runningCustomCameras = false;
return false;
}
} else if (InterfaceManager.clientInterface.inThirdPerson()) {
//If we were running a custom camera, and hit the switch key, increment our camera index.
//We then go back to first-person to render the proper camera.
//If we weren't running a custom camera, try running one. This will become active when we
//go back into first-person mode. This only has an effect if we are riding an entity.
if (runningCustomCameras) {
if (InterfaceManager.clientInterface.changedCameraState()) {
++customCameraIndex;
InterfaceManager.clientInterface.toggleFirstPerson();
}
} else if (sittingSeat != null) {
//Try to enable custom cameras.
enableCustomCameras = true;
customCameraIndex = 0;
//Add the zoom offset for third-person view. This takes hold if we don't have any custom cameras.
sittingSeat.getInterpolatedOrientation(cameraRotation, partialTicks);
double eyeHeight = player.getEyeHeight();
double seatOffset = player.getSeatOffset();
double verticalScale = player.getVerticalScale();
cameraAdjustedPosition.set(0, (eyeHeight + seatOffset) * verticalScale, 0).rotate(cameraRotation).add(0, -eyeHeight, 0);
sittingSeat.getRiderInterpolatedOrientation(riderOrientation, partialTicks);
cameraRotation.multiply(riderOrientation);
cameraAdjustedPosition.add(cameraOffset.set(0, 0, -zoomLevel).rotate(cameraRotation));
return true;
}
} else {
//Assuming inverted third-person mode.
//If we get here, and don't have any custom cameras, stay here.
//If we do have custom cameras, use them instead.
if (sittingSeat != null) {
if (InterfaceManager.clientInterface.changedCameraState()) {
if (ridingVehicle.definition.rendering.cameraObjects != null) {
InterfaceManager.clientInterface.toggleFirstPerson();
} else {
for (APart part : ridingVehicle.allParts) {
if (part.definition.rendering != null && part.definition.rendering.cameraObjects != null) {
InterfaceManager.clientInterface.toggleFirstPerson();
break;
}
}
}
}
//Add the zoom offset for third-person view.
sittingSeat.getInterpolatedOrientation(cameraRotation, partialTicks);
double eyeHeight = player.getEyeHeight();
double seatOffset = player.getSeatOffset();
double verticalScale = player.getVerticalScale();
cameraAdjustedPosition.set(0, (eyeHeight + seatOffset) * verticalScale, 0).rotate(cameraRotation).add(0, -eyeHeight, 0);
sittingSeat.getRiderInterpolatedOrientation(riderOrientation, partialTicks);
cameraRotation.multiply(riderOrientation);
cameraAdjustedPosition.add(cameraOffset.set(0, 0, zoomLevel).rotate(cameraRotation));
return true;
}
}
return false;
}
|
public static boolean adjustCamera(IWrapperPlayer player, Point3D cameraAdjustedPosition, RotationMatrix cameraRotation, float partialTicks) {
//Get variables.
AEntityB_Existing ridingEntity = player.getEntityRiding();
PartSeat sittingSeat = ridingEntity instanceof PartSeat ? (PartSeat) ridingEntity : null;
EntityPlayerGun playerGunEntity = EntityPlayerGun.playerClientGuns.get(player.getID());
//Reset FOV, sensitivity, overlay, and effect.
if (!enableCustomCameras) {
if (currentFOV != 0) {
InterfaceManager.clientInterface.setFOV(currentFOV);
currentFOV = 0;
}
if (currentMouseSensitivity != 0) {
InterfaceManager.clientInterface.setMouseSensitivity(currentMouseSensitivity);
currentMouseSensitivity = 0;
}
}
customCameraOverlay = null;
if (nightVisionEnabled) {
player.removePotionEffect(NIGHT_VISION_CAMERA_POTION);
nightVisionEnabled = false;
}
//Do camera operations.
if (InterfaceManager.clientInterface.inFirstPerson()) {
//Force custom cameras for some states.
//If we are sneaking and holding a gun, or it has forced cameras, enable custom cameras.
if (playerGunEntity != null && playerGunEntity.activeGun != null && sittingSeat == null) {
enableCustomCameras = playerGunEntity.activeGun.isHandHeldGunAimed || playerGunEntity.activeGun.definition.gun.forceHandheldCameras;
customCameraIndex = 0;
}
//If our seat is set to automatically use custom cameras, enable them.
if (!enableCustomCameras && sittingSeat != null && sittingSeat.placementDefinition.forceCameras) {
enableCustomCameras = true;
customCameraIndex = 0;
}
//Do custom camera, or do normal rendering.
if (enableCustomCameras) {
//Get cameras from entity or hand-held gun.
//We check active cameras until we find one that we can use.
runningCustomCameras = true;
customCamerasChecked = 0;
JSONCameraObject camera = null;
AEntityD_Definable<?> cameraProvider = null;
AnimationSwitchbox switchbox = null;
if (sittingSeat != null) {
camera = checkProviderForCameras(sittingSeat.masterEntity, partialTicks);
if (camera != null) {
cameraProvider = sittingSeat.masterEntity;
switchbox = sittingSeat.masterEntity.cameraSwitchboxes.get(camera);
}
if (camera == null) {
for (APart part : sittingSeat.masterEntity.allParts) {
camera = checkProviderForCameras(part, partialTicks);
if (camera != null) {
cameraProvider = part;
switchbox = part.cameraSwitchboxes.get(camera);
break;
}
}
}
} else if (playerGunEntity != null && playerGunEntity.activeGun != null) {
camera = checkProviderForCameras(playerGunEntity.activeGun, partialTicks);
if (camera != null) {
cameraProvider = playerGunEntity.activeGun;
switchbox = playerGunEntity.activeGun.cameraSwitchboxes.get(camera);
}
}
//If we found a camera, use it. If not, turn off custom cameras and go back to first-person mode.
if (camera != null) {
//Set current overlay for future calls.
customCameraOverlay = camera.overlay != null ? camera.overlay + ".png" : null;
//If the camera has an FOV override, apply it.
if (camera.fovOverride != 0) {
if (currentFOV == 0) {
currentFOV = InterfaceManager.clientInterface.getFOV();
}
InterfaceManager.clientInterface.setFOV(camera.fovOverride);
}
//If the camera has a mouse sensitivity override, apply it.
if (camera.mouseSensitivityOverride != 0) {
if (currentMouseSensitivity == 0) {
currentMouseSensitivity = InterfaceManager.clientInterface.getMouseSensitivity();
}
InterfaceManager.clientInterface.setMouseSensitivity(camera.mouseSensitivityOverride);
}
//First set the position of the camera to the defined position.
cameraAdjustedPosition.set(camera.pos);
//Now run transforms on this position to get it's proper position.
if (switchbox != null) {
switchbox.runSwitchbox(partialTicks, false);
cameraAdjustedPosition.transform(switchbox.netMatrix);
}
//Get the rotational component of the operation.
//First, get the orientation of the entity we are on.
cameraProvider.getInterpolatedOrientation(cameraRotation, partialTicks);
//We need to rotate the camera position by our orientation here.
//This puts the position into global orientation rather than animation-local.
cameraAdjustedPosition.rotate(cameraRotation);
//Now add the rotation from the animation, plus the definition rotation, if we have it.
if (switchbox != null) {
cameraRotation.multiply(switchbox.rotation);
}
if (camera.rot != null) {
cameraRotation.multiply(camera.rot);
}
//Rotational portion is good. Finally, get the offset from the player to the provider origin.
//This is required as that's the camera's reference point.
//However, the math is in global space so just add to our offset.
cameraOffset.set(cameraProvider.prevPosition).interpolate(cameraProvider.position, partialTicks).subtract(player.getRenderedPosition(partialTicks));
cameraOffset.y -= player.getEyeHeight();
cameraAdjustedPosition.add(cameraOffset);
//Also check night vision.
if (camera.nightVision) {
player.addPotionEffect(NIGHT_VISION_CAMERA_POTION);
nightVisionEnabled = true;
}
return true;
}
//We wern't running a custom camera. Set running variable to false.
enableCustomCameras = false;
runningCustomCameras = false;
} else if (sittingSeat != null) {
sittingSeat.getInterpolatedOrientation(cameraRotation, partialTicks);
double eyeHeight = player.getEyeHeight();
double seatOffset = player.getSeatOffset();
double verticalScale = player.getVerticalScale();
cameraAdjustedPosition.set(0, (eyeHeight + seatOffset) * verticalScale, 0).rotate(cameraRotation).add(0, -eyeHeight, 0);
sittingSeat.getRiderInterpolatedOrientation(riderOrientation, partialTicks);
cameraRotation.multiply(riderOrientation);
return true;
} else {
//No custom camera, and no seat camera modifications. Standard world view.
enableCustomCameras = false;
runningCustomCameras = false;
return false;
}
} else if (InterfaceManager.clientInterface.inThirdPerson()) {
//If we were running a custom camera, and hit the switch key, increment our camera index.
//We then go back to first-person to render the proper camera.
//If we weren't running a custom camera, try running one. This will become active when we
//go back into first-person mode. This only has an effect if we are riding an entity.
if (runningCustomCameras) {
if (InterfaceManager.clientInterface.changedCameraState()) {
++customCameraIndex;
InterfaceManager.clientInterface.toggleFirstPerson();
}
} else if (sittingSeat != null) {
//Try to enable custom cameras.
enableCustomCameras = true;
customCameraIndex = 0;
//Add the zoom offset for third-person view. This takes hold if we don't have any custom cameras.
sittingSeat.getInterpolatedOrientation(cameraRotation, partialTicks);
double eyeHeight = player.getEyeHeight();
double seatOffset = player.getSeatOffset();
double verticalScale = player.getVerticalScale();
cameraAdjustedPosition.set(0, (eyeHeight + seatOffset) * verticalScale, 0).rotate(cameraRotation).add(0, -eyeHeight, 0);
sittingSeat.getRiderInterpolatedOrientation(riderOrientation, partialTicks);
cameraRotation.multiply(riderOrientation);
cameraAdjustedPosition.add(cameraOffset.set(0, 0, -zoomLevel).rotate(cameraRotation));
return true;
}
} else {
//Assuming inverted third-person mode.
//If we get here, and don't have any custom cameras, stay here.
//If we do have custom cameras, use them instead.
if (sittingSeat != null) {
if (InterfaceManager.clientInterface.changedCameraState()) {
if (sittingSeat.masterEntity.definition.rendering != null && sittingSeat.masterEntity.definition.rendering.cameraObjects != null) {
InterfaceManager.clientInterface.toggleFirstPerson();
} else {
for (APart part : sittingSeat.masterEntity.allParts) {
if (part.definition.rendering != null && part.definition.rendering.cameraObjects != null) {
InterfaceManager.clientInterface.toggleFirstPerson();
break;
}
}
}
}
//Add the zoom offset for third-person view.
sittingSeat.getInterpolatedOrientation(cameraRotation, partialTicks);
double eyeHeight = player.getEyeHeight();
double seatOffset = player.getSeatOffset();
double verticalScale = player.getVerticalScale();
cameraAdjustedPosition.set(0, (eyeHeight + seatOffset) * verticalScale, 0).rotate(cameraRotation).add(0, -eyeHeight, 0);
sittingSeat.getRiderInterpolatedOrientation(riderOrientation, partialTicks);
cameraRotation.multiply(riderOrientation);
cameraAdjustedPosition.add(cameraOffset.set(0, 0, zoomLevel).rotate(cameraRotation));
return true;
}
}
return false;
}
|
Vairables for guided weapons (#1465)
* Add scanning variable for the YZ axial lane
finds contact's angle vertically like direction does with the XZ plane.
* Fix Angle and direction
Fixed angle variable for radars. Had wrong math. Removed Orientation from direction variable as it will only work if the plane's wings are level. Relative bearing shouldn't change depending on roll. For angle, pitch matter as it should read 0 when pointed at the contact.
* Fix Angle and direction
Fixed angle variable for radars. For angle, pitch matters as it should read 0 when pointed at the contact. even if it is above or below you.
* Crash prevention for new guidances
* Update LegacyCompatSystem.java
* Update LegacyCompatSystem.java
Adds backwards compat for JSONs that have no target or lock on types.
* Add ability to distinguish targets to lock on to.
4 separate target types
-DEFAULT/ALL: Like its always worked, locks on to any entity the controller is looking at
-AIRCRAFT: Only locks aircraft if included in the list
-GROUND: Only locks ground vehicles if enabled
-SOFT: Only locks on to soft targets such as players or mobs
Only default locking method is coded for with this commit. Others will come after
* Added JSON Variables for lock and target types
* Added JSON variables for guidance type
* Update JSONBullet.java
Not ready for these variables yet
* Update PartGun.java
* Update PartGun.java
* Update LegacyCompatSystem.java
* change from types to type.
* Change from types to type
* Tightened it up a little
Also added HARD targetType. Got it to where a switch wouldn't crash, however it would no longer lock targets.
Also made it so it wont lock dead vehicles.
* Put lock on code into a set of switches.
Confirmed working properly. Blank statements are for future lock types.
* Added boresight lockType code.
Doesn't Include "ALL" target type yet. Might need some help on that one. However, may not be practical to use that with this LockOnType.
* Fix Default Lock Bug
Fixed bug I found where once a lock was made, It would not break the lock after looking away from said target. This fixes that.
* Fix Boresight Logic
Made it so it picks up the closest vehicle inside the configured cone that still has health. Previously if a dead vehicle was closer than a living one, with both being within range, it would stop a lock from being made.
* Changed gun logic around.
* Screwed up and used lastController rather than controller.
* Added needed JSON variables for guided weapons
Adds lockMaxAngle and lockRange
* Fixed errors that made the compiler whine.
* Dead vehicles were being targeted.
Fixed by moving where this was checked for.
* Remove unused Import
bullet guidance types will come later.
* Add pitch indicator variable
Used in my gyroscopic gunsights
Co-authored-by: DonBruce64 <rapscallion827@gmail.com>
|
https://github.com/DonBruce64/MinecraftTransportSimulator/commit/5eea2796571b58f0a356a5a2b292e575f484ba26
| null | null |
mccore/src/main/java/minecrafttransportsimulator/systems/CameraSystem.java
| 0
|
java
| false
| null |
def estimate_query_cost(
cls,
database: Database,
schema: str,
sql: str,
source: Optional[utils.QuerySource] = None,
) -> List[Dict[str, Any]]:
"""
Estimate the cost of a multiple statement SQL query.
:param database: Database instance
:param schema: Database schema
:param sql: SQL query with possibly multiple statements
:param source: Source of the query (eg, "sql_lab")
"""
extra = database.get_extra() or {}
if not cls.get_allow_cost_estimate(extra):
raise Exception("Database does not support cost estimation")
parsed_query = sql_parse.ParsedQuery(sql)
statements = parsed_query.get_statements()
costs = []
with database.get_raw_connection(schema=schema, source=source) as conn:
cursor = conn.cursor()
for statement in statements:
processed_statement = cls.process_statement(statement, database)
costs.append(cls.estimate_statement_cost(processed_statement, cursor))
return costs
|
def estimate_query_cost(
cls,
database: Database,
schema: str,
sql: str,
source: utils.QuerySource | None = None,
) -> list[dict[str, Any]]:
"""
Estimate the cost of a multiple statement SQL query.
:param database: Database instance
:param schema: Database schema
:param sql: SQL query with possibly multiple statements
:param source: Source of the query (eg, "sql_lab")
"""
extra = database.get_extra() or {}
if not cls.get_allow_cost_estimate(extra):
raise Exception("Database does not support cost estimation")
parsed_query = sql_parse.ParsedQuery(sql)
statements = parsed_query.get_statements()
costs = []
with database.get_raw_connection(schema=schema, source=source) as conn:
cursor = conn.cursor()
for statement in statements:
processed_statement = cls.process_statement(statement, database)
costs.append(cls.estimate_statement_cost(processed_statement, cursor))
return costs
|
Merge branch 'master' into fix/db-val-param-perms
|
https://github.com/apache/superset/commit/4e2fd6f4f04c61e8c1d3ec3f233581a05f8b6213
| null | null |
superset/db_engine_specs/base.py
| 0
|
py
| false
|
2023-06-05T08:42:54Z
|
private static int getThemeResId(Context context, int themeId) {
if (themeId == 0) {
// If the provided theme is 0, then retrieve the dialogTheme from our theme
TypedValue outValue = new TypedValue();
if (context.getTheme().resolveAttribute(com.google.android.material.R.attr.bottomSheetDialogTheme, outValue, true)) {
themeId = outValue.resourceId;
} else {
// bottomSheetDialogTheme is not provided; we default to our light theme
themeId = R.style.Theme_Design_TopSheetDialog;
}
}
return themeId;
}
|
private static int getThemeResId(Context context, int themeId) {
if (themeId == 0) {
// If the provided theme is 0, then retrieve the dialogTheme from our theme
TypedValue outValue = new TypedValue();
if (context.getTheme().resolveAttribute(R.attr.bottomSheetDialogTheme, outValue, true)) {
themeId = outValue.resourceId;
} else {
// bottomSheetDialogTheme is not provided; we default to our light theme
themeId = R.style.Theme_Design_TopSheetDialog;
}
}
return themeId;
}
|
Android - Bug fix for Kava CDP crash
|
https://github.com/cosmostation/cosmostation-android/commit/7e33dbcdbe70e7ef40a707eb0836d7d9eeef2ec1
| null | null |
Cosmos-Android/app/src/main/java/wannabit/io/cosmostaion/dialog/TopSheetDialog.java
| 0
|
java
| false
| null |
def add_missing_metrics(self, metrics: List["BaseMetric"]) -> None:
existing_metrics = {m.metric_name for m in self.metrics}
for metric in metrics:
if metric.metric_name not in existing_metrics:
metric.table_id = self.id
self.metrics.append(metric)
|
def add_missing_metrics(self, metrics: list[BaseMetric]) -> None:
existing_metrics = {m.metric_name for m in self.metrics}
for metric in metrics:
if metric.metric_name not in existing_metrics:
metric.table_id = self.id
self.metrics.append(metric)
|
Merge branch 'master' into fix/db-val-param-perms
|
https://github.com/apache/superset/commit/4e2fd6f4f04c61e8c1d3ec3f233581a05f8b6213
| null | null |
superset/connectors/base/models.py
| 0
|
py
| false
|
2023-06-05T08:42:54Z
|
function EditingKeystrokeHandler(editor) {
var _this;
Object(_var_www_lime25_limesurvey_assets_packages_questiongroup_node_modules_babel_runtime_corejs2_helpers_esm_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, EditingKeystrokeHandler);
_this = Object(_var_www_lime25_limesurvey_assets_packages_questiongroup_node_modules_babel_runtime_corejs2_helpers_esm_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__["default"])(this, Object(_var_www_lime25_limesurvey_assets_packages_questiongroup_node_modules_babel_runtime_corejs2_helpers_esm_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__["default"])(EditingKeystrokeHandler).call(this));
/**
* The editor instance.
*
* @readonly
* @member {module:core/editor/editor~Editor}
*/
_this.editor = editor;
return _this;
}
|
function EditingKeystrokeHandler(editor) {
var _this;
Object(_var_www_limedev_assets_packages_questiongroup_node_modules_babel_runtime_corejs2_helpers_esm_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, EditingKeystrokeHandler);
_this = Object(_var_www_limedev_assets_packages_questiongroup_node_modules_babel_runtime_corejs2_helpers_esm_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__["default"])(this, Object(_var_www_limedev_assets_packages_questiongroup_node_modules_babel_runtime_corejs2_helpers_esm_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__["default"])(EditingKeystrokeHandler).call(this));
/**
* The editor instance.
*
* @readonly
* @member {module:core/editor/editor~Editor}
*/
_this.editor = editor;
return _this;
}
|
DEV: changed routes in vue.js part questiongroupedit.js and deleted old controller+views
|
https://github.com/LimeSurvey/LimeSurvey/commit/d7a309bf1a73e95187528982b9db7ec03fee6913
|
CVE-2020-23710
|
['CWE-79']
|
assets/packages/questiongroup/build/js/questiongroupedit.js
| 0
|
js
| false
|
2020-06-08T09:23:29Z
|
def main() -> None:
parser = argparse.ArgumentParser()
# Configure debug logging before running parse_args, because there could be an error raised before the construction of the argument parser.
logging.basicConfig(
level=logging.DEBUG
if ("--debug" in sys.argv or "-d" in sys.argv)
else logging.INFO
)
parser.add_argument("-d", "--debug", action="store_true")
parser.add_argument(
"--built-version",
choices=tuple(built_version_choices_list),
default="case-" + CURRENT_CASE_VERSION,
help="Ontology version to use to supplement query, such as for subclass querying. Does not require networking to use. Default is most recent CASE release.",
)
parser.add_argument(
"--disallow-empty-results",
action="store_true",
help="Raise error if no results are returned for query.",
)
parser.add_argument(
"out_table",
help="Expected extensions are .html for HTML tables or .md for Markdown tables.",
)
parser.add_argument(
"in_sparql",
help="File containing a SPARQL SELECT query. Note that prefixes not mapped with a PREFIX statement will be mapped according to their first occurrence among input graphs.",
)
parser.add_argument("in_graph", nargs="+")
args = parser.parse_args()
graph = rdflib.Graph()
for in_graph_filename in args.in_graph:
graph.parse(in_graph_filename)
# Inherit prefixes defined in input context dictionary.
nsdict = {k: v for (k, v) in graph.namespace_manager.namespaces()}
select_query_text = None
with open(args.in_sparql, "r") as in_fh:
select_query_text = in_fh.read().strip()
_logger.debug("select_query_text = %r." % select_query_text)
if "subClassOf" in select_query_text:
case_utils.ontology.load_subclass_hierarchy(
graph, built_version=args.built_version
)
# Build columns list from SELECT line.
select_query_text_lines = select_query_text.split("\n")
select_line = [
line for line in select_query_text_lines if line.startswith("SELECT ")
][0]
variables = select_line.replace(" DISTINCT", "").replace("SELECT ", "").split(" ")
tally = 0
records = []
select_query_object = rdflib.plugins.sparql.processor.prepareQuery(
select_query_text, initNs=nsdict
)
for (row_no, row) in enumerate(graph.query(select_query_object)):
tally = row_no + 1
record = []
for (column_no, column) in enumerate(row):
if column is None:
column_value = ""
elif (
isinstance(column, rdflib.term.Literal)
and column.datatype == NS_XSD.hexBinary
):
# Use hexlify to convert xsd:hexBinary to ASCII.
# The render to ASCII is in support of this script rendering results for website viewing.
# .decode() is because hexlify returns bytes.
column_value = binascii.hexlify(column.toPython()).decode()
else:
column_value = column.toPython()
if row_no == 0:
_logger.debug("row[0]column[%d] = %r." % (column_no, column_value))
record.append(column_value)
records.append(record)
if tally == 0:
if args.disallow_empty_results:
raise ValueError("Failed to return any results.")
df = pd.DataFrame(records, columns=variables)
table_text = None
if args.out_table.endswith(".html"):
# https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_html.html
# Add CSS classes for CASE website Bootstrap support.
table_text = df.to_html(classes=("table", "table-bordered", "table-condensed"))
elif args.out_table.endswith(".md"):
# https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_markdown.html
# https://pypi.org/project/tabulate/
# Assume Github-flavored Markdown.
table_text = df.to_markdown(tablefmt="github")
if table_text is None:
raise NotImplementedError(
"Unsupported output extension for output filename %r.", args.out_table
)
with open(args.out_table, "w") as out_fh:
out_fh.write(table_text)
|
def main() -> None:
parser = argparse.ArgumentParser()
# Configure debug logging before running parse_args, because there could be an error raised before the construction of the argument parser.
logging.basicConfig(
level=logging.DEBUG
if ("--debug" in sys.argv or "-d" in sys.argv)
else logging.INFO
)
parser.add_argument("-d", "--debug", action="store_true")
parser.add_argument(
"--built-version",
choices=tuple(built_version_choices_list),
default="case-" + CURRENT_CASE_VERSION,
help="Ontology version to use to supplement query, such as for subclass querying. Does not require networking to use. Default is most recent CASE release.",
)
parser.add_argument(
"--disallow-empty-results",
action="store_true",
help="Raise error if no results are returned for query.",
)
parser.add_argument(
"out_table",
help="Expected extensions are .html for HTML tables or .md for Markdown tables.",
)
parser.add_argument(
"in_sparql",
help="File containing a SPARQL SELECT query. Note that prefixes not mapped with a PREFIX statement will be mapped according to their first occurrence among input graphs.",
)
parser.add_argument("in_graph", nargs="+")
args = parser.parse_args()
graph = rdflib.Graph()
for in_graph_filename in args.in_graph:
graph.parse(in_graph_filename)
# Inherit prefixes defined in input context dictionary.
nsdict = {k: v for (k, v) in graph.namespace_manager.namespaces()}
select_query_text = None
with open(args.in_sparql, "r") as in_fh:
select_query_text = in_fh.read().strip()
_logger.debug("select_query_text = %r." % select_query_text)
if "subClassOf" in select_query_text:
case_utils.ontology.load_subclass_hierarchy(
graph, built_version=args.built_version
)
# Build columns list from SELECT line.
select_query_text_lines = select_query_text.split("\n")
select_line = [
line for line in select_query_text_lines if line.startswith("SELECT ")
][0]
variables = select_line.replace(" DISTINCT", "").replace("SELECT ", "").split(" ")
tally = 0
records = []
select_query_object = rdflib.plugins.sparql.processor.prepareQuery(
select_query_text, initNs=nsdict
)
for row_no, row in enumerate(graph.query(select_query_object)):
tally = row_no + 1
record = []
for column_no, column in enumerate(row):
if column is None:
column_value = ""
elif (
isinstance(column, rdflib.term.Literal)
and column.datatype == NS_XSD.hexBinary
):
# Use hexlify to convert xsd:hexBinary to ASCII.
# The render to ASCII is in support of this script rendering results for website viewing.
# .decode() is because hexlify returns bytes.
column_value = binascii.hexlify(column.toPython()).decode()
else:
column_value = column.toPython()
if row_no == 0:
_logger.debug("row[0]column[%d] = %r." % (column_no, column_value))
record.append(column_value)
records.append(record)
if tally == 0:
if args.disallow_empty_results:
raise ValueError("Failed to return any results.")
df = pd.DataFrame(records, columns=variables)
table_text = None
if args.out_table.endswith(".html"):
# https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_html.html
# Add CSS classes for CASE website Bootstrap support.
table_text = df.to_html(classes=("table", "table-bordered", "table-condensed"))
elif args.out_table.endswith(".md"):
# https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_markdown.html
# https://pypi.org/project/tabulate/
# Assume Github-flavored Markdown.
table_text = df.to_markdown(tablefmt="github")
if table_text is None:
raise NotImplementedError(
"Unsupported output extension for output filename %r.", args.out_table
)
with open(args.out_table, "w") as out_fh:
out_fh.write(table_text)
|
Merge branches 'HotFix-0.7.1-set_pyshacl_ceiling' and 'support-0.6.x' into release-0.7.1
|
https://github.com/casework/CASE-Utilities-Python/commit/e4ffadc3d56fd303b8f465d727c4a58213d311a1
| null | null |
case_utils/case_sparql_select/__init__.py
| 0
|
py
| false
| null |
public long getFileSize(String uri){
final BlockBlobURL blockBlobURL = getBlobURL(uri);
final BlobGetPropertiesHeaders headers = blockBlobURL.getProperties().blockingGet().headers();
return headers.contentLength();
}
|
public long getFileSize(String uri){
return getBlobURL(uri).getProperties().getBlobSize();
}
|
Extend heatmap registration CLI reference
|
https://github.com/epam/NGB/commit/a962d051083a78be974351b4d43825ec431044df
| null | null |
server/catgenome/src/main/java/com/epam/catgenome/util/azure/AzureBlobClient.java
| 0
|
java
| false
|
2021-10-13T15:33:15Z
|
function meetingHasEnded(meetingId) {
if (!process.env.BBB_HTML5_ROLE || process.env.BBB_HTML5_ROLE === 'frontend') {
removeAnnotationsStreamer(meetingId);
removeCursorStreamer(meetingId);
removeExternalVideoStreamer(meetingId);
}
return Meetings.remove({ meetingId }, () => {
clearCaptions(meetingId);
clearPads(meetingId);
clearGroupChat(meetingId);
clearGuestUsers(meetingId);
clearPresentationPods(meetingId);
clearBreakouts(meetingId);
clearPolls(meetingId);
clearAnnotations(meetingId);
clearSlides(meetingId);
clearUsers(meetingId);
clearUsersSettings(meetingId);
clearVoiceUsers(meetingId);
clearUserInfo(meetingId);
clearConnectionStatus(meetingId);
clearAudioCaptions(meetingId);
clearLocalSettings(meetingId);
clearMeetingTimeRemaining(meetingId);
clearRecordMeeting(meetingId);
clearExternalVideoMeeting(meetingId);
clearVoiceCallStates(meetingId);
clearVideoStreams(meetingId);
clearAuthTokenValidation(meetingId);
clearWhiteboardMultiUser(meetingId);
clearScreenshare(meetingId);
clearUsersPersistentData(meetingId);
Metrics.removeMeeting(meetingId);
Logger.info(`Cleared Meetings with id ${meetingId}`);
});
}
|
async function meetingHasEnded(meetingId) {
if (!process.env.BBB_HTML5_ROLE || process.env.BBB_HTML5_ROLE === 'frontend') {
removeAnnotationsStreamer(meetingId);
removeCursorStreamer(meetingId);
removeExternalVideoStreamer(meetingId);
}
await Meetings.removeAsync({ meetingId });
await Promise.all([
clearCaptions(meetingId),
clearPads(meetingId),
clearGroupChat(meetingId),
clearGuestUsers(meetingId),
clearPresentationPods(meetingId),
clearBreakouts(meetingId),
clearPolls(meetingId),
clearAnnotations(meetingId),
clearSlides(meetingId),
clearUsers(meetingId),
clearUsersSettings(meetingId),
clearVoiceUsers(meetingId),
clearUserInfo(meetingId),
clearConnectionStatus(meetingId),
clearAudioCaptions(meetingId),
clearLocalSettings(meetingId),
clearMeetingTimeRemaining(meetingId),
clearRecordMeeting(meetingId),
clearExternalVideoMeeting(meetingId),
clearVoiceCallStates(meetingId),
clearVideoStreams(meetingId),
clearAuthTokenValidation(meetingId),
clearWhiteboardMultiUser(meetingId),
clearScreenshare(meetingId),
clearUsersPersistentData(meetingId),
]);
await Metrics.removeMeeting(meetingId);
return Logger.info(`Cleared Meetings with id ${meetingId}`);
}
|
Merge branch 'v2.6.x-release' of github.com:bigbluebutton/bigbluebutton into ssrf-fix
|
https://github.com/bigbluebutton/bigbluebutton/commit/22de2b49a5d218910923a1048bb73395e53c99bf
|
CVE-2023-33176
|
['CWE-918']
|
bigbluebutton-html5/imports/api/meetings/server/modifiers/meetingHasEnded.js
| 0
|
js
| false
|
2023-04-13T12:40:07Z
|
function mt(t,e,n){for(var i,r,o=0,a=0,s=e.length;a<s;){for(i=e[a].firstChild,r=n?n[a].firstChild:null;i;)1===i.nodeType&&(n?t(i,r,o):t(i,o),o++),i=i.nextSibling,r=n?r.nextSibling:null;a++}}
|
function mt(t,e,n){var i,r,o=Math.min(t/=255,e/=255,n/=255),a=Math.max(t,e,n),s=a-o,l=(a+o)/2;return s?(r=l<.5?s/(a+o):s/(2-a-o),i=t==a?(e-n)/s+(e<n?6:0):e==a?(n-t)/s+2:(t-e)/s+4,i*=60):(i=NaN,r=0<l&&l<1?0:i),new et(i,r,l)}
|
Updated PapaParse config to prevent CSV injection.
I've updated the PapaParse JS library to the latest version from the master branch which supports the `escapeForumlae` option in order to prevent malicious event entries from being parsed and executed by the Gophish user's spreadsheet software.
When a new PapaParse release is created, I'll update this code to use the updated minified file.
|
https://github.com/gophish/gophish/commit/b25f5ac5e468f6730e377f43c7995e18f8fccc2b
|
CVE-2020-24707
|
['CWE-1236']
|
static/js/dist/vendor.min.js
| 0
|
js
| false
|
2020-07-25T03:44:24Z
|
@Override
public void onPlayerStoppedUsing(ItemStack stack, World worldIn, LivingEntity entityLiving, int timeLeft) {
if (entityLiving instanceof PlayerEntity) {
PlayerEntity playerentity = (PlayerEntity)entityLiving;
boolean flag = playerentity.abilities.isCreativeMode || EnchantmentHelper.getEnchantmentLevel(Enchantments.INFINITY, stack) > 0;
ItemStack itemstack = playerentity.findAmmo(stack);
int i = this.getUseDuration(stack) - timeLeft;
i = net.minecraftforge.event.ForgeEventFactory.onArrowLoose(stack, worldIn, playerentity, i, !itemstack.isEmpty() || flag);
if (i < 0) return;
if (!itemstack.isEmpty() || flag) {
if (itemstack.isEmpty()) {
itemstack = new ItemStack(Items.ARROW);
}
if (!worldIn.isRemote) {
ArrowItem arrowitem = (ArrowItem)(itemstack.getItem() instanceof ArrowItem ? itemstack.getItem() : Items.ARROW);
UltimateArrowEntity abstractarrowentity = new UltimateArrowEntity(worldIn, playerentity);
abstractarrowentity = (UltimateArrowEntity) customArrow(abstractarrowentity);
abstractarrowentity.setDirectionAndMovement(playerentity, playerentity.rotationPitch, playerentity.rotationYaw, 0.0F, 3.0F, 0F);
abstractarrowentity.setIsCritical(true);
abstractarrowentity.setDamage(abstractarrowentity.getDamage() + 1.5D);
abstractarrowentity.setKnockbackStrength(2);
abstractarrowentity.setFire(300);
stack.damageItem(1, playerentity, (player) -> {
player.sendBreakAnimation(playerentity.getActiveHand());
});
worldIn.addEntity(abstractarrowentity);
worldIn.playSound((PlayerEntity)null, playerentity.getPosX(), playerentity.getPosY(), playerentity.getPosZ(), SoundEvents.ENTITY_ARROW_SHOOT, SoundCategory.PLAYERS, 1.0F, 1.0F / (random.nextFloat() * 0.4F + 1.2F) + 0.5F);
playerentity.addStat(Stats.ITEM_USED.get(this));
}
}
}
}
|
@Override
public void onPlayerStoppedUsing(ItemStack stack, World worldIn, LivingEntity entityLiving, int timeLeft) {
if (entityLiving instanceof PlayerEntity) {
PlayerEntity playerentity = (PlayerEntity)entityLiving;
boolean flag = playerentity.abilities.isCreativeMode || EnchantmentHelper.getEnchantmentLevel(Enchantments.INFINITY, stack) > 0;
ItemStack itemstack = playerentity.findAmmo(stack);
int i = this.getUseDuration(stack) - timeLeft;
i = net.minecraftforge.event.ForgeEventFactory.onArrowLoose(stack, worldIn, playerentity, i, !itemstack.isEmpty() || flag);
if (i < 0) return;
if (!itemstack.isEmpty() || flag) {
if (itemstack.isEmpty()) {
itemstack = new ItemStack(Items.ARROW);
}
if (!worldIn.isRemote) {
ArrowItem arrowitem = (ArrowItem)(itemstack.getItem() instanceof ArrowItem ? itemstack.getItem() : Items.ARROW);
UltimateArrowEntity abstractarrowentity = new UltimateArrowEntity(worldIn, playerentity);
abstractarrowentity = (UltimateArrowEntity) customArrow(abstractarrowentity);
abstractarrowentity.setDirectionAndMovement(playerentity, playerentity.rotationPitch, playerentity.rotationYaw, 0.0F, 3.0F, 0F);
abstractarrowentity.setIsCritical(true);
abstractarrowentity.setDamage(abstractarrowentity.getDamage() + 3D);
abstractarrowentity.setKnockbackStrength(2);
abstractarrowentity.setFire(300);
if (!playerentity.isCreative()) {
stack.damageItem(1, entityLiving, (entity) -> {
entity.sendBreakAnimation(EquipmentSlotType.MAINHAND);
});
}
worldIn.addEntity(abstractarrowentity);
worldIn.playSound((PlayerEntity)null, playerentity.getPosX(), playerentity.getPosY(), playerentity.getPosZ(), SoundEvents.ENTITY_ARROW_SHOOT, SoundCategory.PLAYERS, 1.0F, 1.0F / (random.nextFloat() * 0.4F + 1.2F) + 0.5F);
playerentity.addStat(Stats.ITEM_USED.get(this));
}
}
}
}
|
Fixed ultimate bow crash and added crystal dim assets
|
https://github.com/ChaosAwakens/ChaosAwakens/commit/15417d890f12a57656f8e67e495a8f6922af778a
| null | null |
src/main/java/io/github/chaosawakens/items/UltimateBow.java
| 0
|
java
| false
| null |
public String getDisplayName() {
return stack.getDisplayName().getUnformattedComponentText();
}
|
public String getDisplayName() {
return stack.getDisplayName().getString();
}
|
1.2.16
Added Level emitter
Fixed terminal sorting
Implemented Inventory Proxy filter feature from Fabric
Made Wireless terminals are non-stackable (Closes #32)
Fixed REI intergation (Closes #35)
Fixed data overflow crash (Closes #33)
|
https://github.com/tom5454/Toms-Storage/commit/e2155ba7626e7a999f33069bcb914e6ad8d7700c
| null | null |
src/main/java/com/tom/storagemod/StoredItemStack.java
| 0
|
java
| false
|
2021-03-09T17:45:30Z
|
function updateDocumentPlaceholders(doc, writer) {
var placeholders = documentPlaceholders.get(doc);
var wasViewModified = false;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = placeholders[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var _step$value = Object(_var_www_lime25_limesurvey_assets_packages_questiongroup_node_modules_babel_runtime_corejs2_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_0__["default"])(_step.value, 2),
element = _step$value[0],
config = _step$value[1];
if (updatePlaceholder(writer, element, config)) {
wasViewModified = true;
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return wasViewModified;
} // Updates a single placeholder in a post–fixer callback.
|
function updateDocumentPlaceholders(doc, writer) {
var placeholders = documentPlaceholders.get(doc);
var wasViewModified = false;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = placeholders[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var _step$value = Object(_var_www_limedev_assets_packages_questiongroup_node_modules_babel_runtime_corejs2_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_0__["default"])(_step.value, 2),
element = _step$value[0],
config = _step$value[1];
if (updatePlaceholder(writer, element, config)) {
wasViewModified = true;
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return wasViewModified;
} // Updates a single placeholder in a post–fixer callback.
|
DEV: changed routes in vue.js part questiongroupedit.js and deleted old controller+views
|
https://github.com/LimeSurvey/LimeSurvey/commit/d7a309bf1a73e95187528982b9db7ec03fee6913
|
CVE-2020-23710
|
['CWE-79']
|
assets/packages/questiongroup/build/js/questiongroupedit.js
| 0
|
js
| false
|
2020-06-08T09:23:29Z
|
private static void loadPreferenceLine(String line) {
if (line.isEmpty())
return;
String[] args = line.split(":");
if (args.length < 2)
return;
String key = args[0].toUpperCase().trim();
String val = args[1].trim();
// for values that may have embedded :, like the save dir path
String fullVal = val;
for (int i=2;i<args.length;i++)
fullVal = fullVal+":"+args[i];
if (key.isEmpty() || val.isEmpty())
return;
if (Rotp.logging)
System.out.println("Key:"+key+" value:"+val);
switch(key) {
case "DISPLAY_MODE": displayMode = displayModeFromSettingName(val); return;
case "GRAPHICS": graphicsMode = graphicsModeFromSettingName(val); return;
case "MUSIC": playMusic = yesOrNo(val); return;
case "SOUNDS": playSounds = yesOrNo(val); return;
case "MUSIC_VOLUME": setMusicVolume(val); return;
case "SOUND_VOLUME": setSoundVolume(val); return;
case "SAVE_DIR": saveDir = fullVal.trim(); return;
case "BACKUP_TURNS": backupTurns = Integer.valueOf(val); return;
case "AUTOCOLONIZE": autoColonize = yesOrNo(val); return;
case "AUTOBOMBARD": autoBombardMode = autoBombardFromSettingName(val); return;
case "TEXTURES": texturesMode = texturesFromSettingName(val); return;
case "SENSITIVITY": sensitivityMode = sensitivityFromSettingName(val); return;
case "SHOW_MEMORY": showMemory = yesOrNo(val); return;
case "DISPLAY_YEAR": displayYear = yesOrNo(val); return;
case "SCREEN_SIZE_PCT": screenSizePct(Integer.valueOf(val)); return;
case "UI_TEXTURE_LEVEL": uiTexturePct(Integer.valueOf(val)); return;
case "LANGUAGE": selectLanguage(val); return;
default:
raceNames.put(key, val); break;
}
}
|
private static void loadPreferenceLine(String line) {
if (line.isEmpty())
return;
String[] args = line.split(":");
if (args.length < 2)
return;
String key = args[0].toUpperCase().trim();
String val = args[1].trim();
// for values that may have embedded :, like the save dir path
String fullVal = val;
for (int i=2;i<args.length;i++)
fullVal = fullVal+":"+args[i];
if (key.isEmpty() || val.isEmpty())
return;
if (Rotp.logging)
System.out.println("Key:"+key+" value:"+val);
switch(key) {
case "DISPLAY_MODE": displayMode = displayModeFromSettingName(val); return;
case "GRAPHICS": graphicsMode = graphicsModeFromSettingName(val); return;
case "MUSIC": playMusic = yesOrNo(val); return;
case "SOUNDS": playSounds = yesOrNo(val); return;
case "MUSIC_VOLUME": setMusicVolume(val); return;
case "SOUND_VOLUME": setSoundVolume(val); return;
case "SAVE_DIR": saveDir = fullVal.trim(); return;
case "BACKUP_TURNS": backupTurns = Integer.valueOf(val); return;
case "AUTOCOLONIZE": autoColonize = yesOrNo(val); return;
case "AUTOBOMBARD": autoBombardMode = autoBombardFromSettingName(val); return;
case "TEXTURES": texturesMode = texturesFromSettingName(val); return;
case "SENSITIVITY": sensitivityMode = sensitivityFromSettingName(val); return;
case "SHOW_MEMORY": showMemory = yesOrNo(val); return;
case "DISPLAY_YEAR": displayYear = yesOrNo(val); return;
case "DEFAULT_MAX_BASES": defaultMaxBases = Integer.valueOf(val); return;
case "DIVERT_COLONY_EXCESS_TO_RESEARCH": divertColonyExcessToResearch = yesOrNo(val); return;
case "SCREEN_SIZE_PCT": screenSizePct(Integer.valueOf(val)); return;
case "UI_TEXTURE_LEVEL": uiTexturePct(Integer.valueOf(val)); return;
case "LANGUAGE": selectLanguage(val); return;
default:
raceNames.put(key, val); break;
}
}
|
Default for Missile-base-limit and whether divert excess production to research are enabled is now configurable in Remnants.cfg (#68)
* Update AISpyMaster.java
I consider espionage and sabotage against darloks a bit of a fruitless endevour.
* UI stuff
Slight tweak to research-slider-allocation-management.
Transports that are being sent this turn now are represented by negative pop-growth in the colony-screen.
Fixed an issue where colony-screen would not have the system that was clicked on the main-screen preselected.
* Update AIDiplomat.java
Include Ray's improvements to AI-tech-trading.
* Update AIDiplomat.java
Including Ray's tech-trading-improvements.
Tweaks to war-declaration-logic.
* Update AIFleetCommander.java
New smarth-pathing-algorithm implemented. It makes AI-fleets take stops instead of flying directly to the destination.
* Update AIScientist.java
Reverted recent change about when to stop allocating into a category and made some tiny tweaks to initial allocations.
* Update AIShipDesigner.java
Prevented two rare but possible lock-ups regarding scrapping all designs and fixed an issue where a weaponless-design would not be scrapped.
* Update AISpyMaster.java
No longer inciting rebellions on opponents not at war with.
* Update NewShipTemplate.java
Fixed an issue that allowed weaponless designs to be made.
* Update ShipFleet.java
Fixed an issue with incorrect display of ETA when fleet passed nebula or slower ships were scrapped during the travel.
* Update Empire.java
Fix for ships can't see other ships at 0 range after scanner-rework.
* Update AIFleetCommander.java
Fixed that buffering had broken hyperspace-communication-usage.
Removed a previous change about overestimating how much to send to a colony.
* Update AIDiplomat.java
Preparations for how alliances could work. But afterall commented out because it just doesn't feel right.
* Update AIDiplomat.java
Hostility now impacts readyness for war and alliances.
* Update AIFleetCommander.java
Now giving cover to ongoing invasions
* Update AIScientist.java
Adjusted values of a bunch of techs.
* Update AIShipCaptain.java
Fixed accidental removal of range-adjustment in new target-selection-formula and removed unused code.
* Update NewShipTemplate.java
Allowing missiles to be used again under certain circumstances, taking ECM into account and basing weapon-decision on actual shield-levels rather than best possible.
* Update TechMissileWeapon.java
Fixed that 2-rack-missiles didn't have +1 speed as they should have according to official strategy-guide.
* Update AIScientist.java
Tech-Slider-Allocations now depend on racial-bonuses, not leader-personality.
* Immersive Xilmi-AI
When set to AI: Selectable, the Xilmi AI now goes in immersive-mode, once again making numerous uses of leader-traits.
* Update CombatStackColony.java
Fixed a bug, that planets without missile-bases always absorbed damage as if they already had a shield-built, even if they had none and even if they were in a nebula.
* Tactical combat improvements
Can now detect when someone protects another stack with repulsor-beams and retreats, when it cannot counter it with long-range-weapons.
Optimal range for firing missiles increased by repulsor-radius so missile-ships won't be affected by the can't counter repulsors-detection.
Missiles will now be held back until getting closer to prevent target from dodging them easily.
Unused specials like Repulsor will no longer prevent ships from kiting.
* Update AIShipCaptain.java
Only kite when there's either repulsor-beam or missile-weapons installed on the ship.
* Update AIFleetCommander.java
Defending is only half as desirable as attacking now.
* Immersive Xilmi-AI
Lot's of changes for the personality-mode of Xilmi-AI.
* Update DiplomaticEmbassy.java
Fix for one empire still holding a grudge against the other when signing a peace-treaty.
* Update AIShipCaptain.java
Somehow the Xilmi-AI must have had conquered a system with a missile-base on it against another type of AI and then crashed at this place, I didn't even think it would get to for a colony.
* Update AISpyMaster.java
No longer consider computer-advantage for how much to spend into counter-espionage.
* Race-fitting-playstyles implemented
and leader-specfic-self-restrictions removed.
* Update AIGeneral.java
Invader-AI back to normal victim-selection.
* Update AIGovernor.java
Turns out espionage didn't work like I thought it would.
So Darlok just building ships and relying on stealing techs was a bad idea.
(You can only steal techs below your highest level in any given tree!)
* Update AIDiplomat.java
Fixed issue where AI wouldn't allow the player to ask for tech-trades and where they would take deals that are horrible for themselves when trading with other AIs.
Trades are now usually all done within a 66%-150% tech-cost-range.
* Update AIGeneral.java
Giving themselves a personality/objective-combination that fits their behavior.
* Update AIDiplomat.java
Tech exchange only will work within same tier now.
* Update AIGeneral.java
Removed setting of personalities as this causes issue with missing texts.
* Update AIScientist.java
Fixed issue for Silicoids trading for Eco-restoration-techs.
* Update ColonyDefense.java
* Update ColonyDefense.java
Shield will now only be built automatically under the following circumstances:
There's missile-bases existing
There's missile-bases needing to be upgraded
There's missile-bases to be built
* Update AIDiplomat.java
Avoid false positives in war-declaration for incoming fleets when the system in question was only recently colonized.
* Update AIShipCaptain.java
Fixed a rare but not impossible crash.
* Update AIDiplomat.java
No longer accept joint-war-proposals from empires we like less than who they propose as victim.
* Update AIGovernor.java
Now building missile-bases... under very specific and rare circumstances.
* Update AIShipCaptain.java
Fixed crash when handling missile-bases.
Individual stacks that can't find a target to attack no longer automatically retreat and instead let their behavior be governed by whether the whole fleet would want to retreat.
* Update ColonyDefense.java
Reverted previous changes which also happened to prevent AI from building shields.
* Update CombatStackShip.java
Fixed issue where multi-shot-weapons weren't reported as used when they were used.
* Update AIFleetCommander.java
Fleets now are split depending on their warp-speed unless they are on the way to their final-attack-target.
* Update AIDiplomat.java
Knowing about uncolonized systems no longer prevents wars.
* Update CombatStackShip.java
Revert change to shipComponentIsUsed
* Update AIShipCaptain.java
Moved logic that detects if a weapon has been used to this file.
* Update AIScientist.java
Try to avoid researching techs we know our neighbors already have since we can trade for it or steal it.
* Update AIFleetCommander.java
Colony ships now only ignore distance if they are huge as otherwise ignoring distance was horrible in late-game with hyperspace-communications.
Keeping scout-designs around for longer.
* Fixed a very annoying issue that caused eco-spending to become...
insufficient and thus people to die when adjusting espionage- or security-spending.
* Reserve-management-improvements
Rich and Ultra-Rich planets now put their production into reserve when they would otherwise conduct research.
Reserve will now try to keep an emergency-reserve for dealing with events like Supernova.
Exceeding twice the amount of that reserve will always be spent so the money doesn't just lie around unused, when there's no new colonies that still need industry.
* Update AIShipCaptain.java
Removed an unneccessary white line 8[
* Update AIFleetCommander.java
Reversed keeping scouts for longer
* Update AIGovernor.java
no industry, when under siege
* Update AIGovernor.java
Small fixed to sieged colonies building industry when they shouldn't.
* Update Rotp.java
Versioning 0.93a
* Update RacesUI.java
Race-selector no longer jumps after selecting a race.
Race-selector scroll-speed when dragging is no longer amplified like the scroll-bar but instead moves 1:1 the distance dragged.
* Update AIFleetCommander.java
Smart-Path will no longer path over systems further away than the target-system.
Fleets will now always be split by speed if more than 2/3rd of the fleet have the fastest speed possible.
* Update AIGovernor.java
Build more fleet when fighting someone who has no or extremely little fleet.
* Update AIShipCaptain.java
Kiting no longer uses path-finding during auto-resolve.
Ships with repulsor and long-range will no longer get closer than 2 tiles before firing against ships that don't have long range.
Will only retreat to system with enemy fleets when there's no system without enemy fleets to retreat to.
* Update CombatStackColony.java
Added override for optimal firing-range for missile-bases. It is 9.
* Update CombatStackShip.java
Optimal firing-range for ship-stacks with missiles will now be at least two when they have repulsors.
* Update NewShipTemplate.java
The willingness of the AI to use repulsor-beam now scales with how many opponent ships have long range. It will be higher if there's only a few but drop down to 0 if all opponent ships use them.
* Update AI.java
Improved logic for shuttling around population within the empire.
* Update ShipBattleUI.java
Fixed a bug where remaining commands were transferred from one stack to another, which could also cause a crash when missile-bases were involved.
* Update Colony.java
currentProductionCapacity now correctly takes into consideration how many factories are actually operated.
* Update NewShipTemplate.java
Fixes and improvements to special-selection. Mainly bigger emphasis on using cloaking-device and stasis-field.
* Update AIShipDesigner.java
Consider getting an important special like cloaking, stasis or black-hole-generator as reason to immediately make a new design.
* Update SystemView.java
Systems with enemy-fleets will now flash the Alert. Especially usefull when under siege by cloaked enemy fleets.
* Update AIShipCaptain.java
Added check whether retreat was possible when retreating for the reason that nothing can be done.
* Update AIGovernor.java
Taking natural pop-growth and the cost of terraforming into account when deciding to build factories or population. This usually results to prefering factories almost always when they can be operated.
* War- and Peace-making changes.
Prevent war-declaration when there's barely any fleet to attack with.
Smarter selection of preferred victim. In particular taking their diplomatic status with others into account.
Toned down overall aggressiveness. Several personalities now are taken into account for determining behavior.
* Update General.java
Don't attack too early.
* Update AIFleetCommander.java
Colony ships will now always prefer undefended targets instead of waiting for help if they want to colonize a defended system.
* Update Rotp.java
Version 0.93b
* Update NewShipTemplate.java
Not needing ranged weapon, when we have cloaking-device.
* Improved behavior when using missiles to act according to expectations of /u/bot39lvl
* Showing pop-growth at clean-eco.
* New Version with u/bot39lvl recommended changes to missile-boat-handling
* Fixed issue that caused ships being scrapped after loading a game, no longer taking incoming enemy fleets into consideration that are more than one turn away from reaching their target.
* Stacks that want to retreat will now also try and damage their target if it is more than one space away as long as they don't use up all movement-points. Planets with no missile-bases will not become a target unless all non-bomb-weapons were used.
* Fixed an issue where a new design would override a similar existing one.
* When defending or when having better movement-speed now shall always try to get the 1st strike.
* Not keeping a defensive fleet on duty when the incoming opponent attack will overwhelm them anyways.
* Using more unique ship-names
* Avoid ship-information being cut off by drawing ship-button-overlay into the upper direction as soon as a stack is below the middle of the screen.
* Fixed exploit that allowed player to ignore enemy repulsor-beams via auto-resolve.
* Fixed issue that caused missile-ships to sometimes retreat when they shouldn't.
* Calling beam/missileDefense() method instead of looking at the member since the function also takes stealth into account which we want to do for better decision-making.
* Ships with limited shot-weapons no longer think they can land all hits at once.
* Best tech of each type no longer gets it's research-value reduced.
* Halfed inertial-value again as it otherwise may suppress vital range-tech.
* Prevent overbuilding colony-ships in lategame by taking into consideration when systems can build more than one per turn.
* Design-names now use name of a system that is actually owned and add a number to make sure they are unique.
* Fixed some issues with no longer firing before retreating after rework and now ignoring stacks in stasis for whether to retreat or not.
* Evenly distributing population across the empire led to an increase of almost 30% productivity at a reference turn in tests and thus turned out to be a much better population-distribution-strategy when compared to the "bring new colonies to 25%"-rule-of-thumb as suggested in the official-strategy-guide.
* Last defending stacks in stasis are now also made to autoretreat as otherwise this would result in 100 turns of "you can't do anything but watch".
* Avoid having more than two designs with Stasis-Field as it doesn't stack.
* Should fix an issue that caused usage of Hyper-Space-Communications to be inefficient.
* Futher optimization on population-shuttling.
* Fixed possible crash from trying to make peace while being involved in a final war.
* Fixed infinite loop when trying to scrap the last existing design.
* Making much better use of natural growth.
* Some further slight adjustments to economy-handling that lead to an even better result in my test.
* Fix for "Hyperspace Communications: can't reroute back to the starting planet - bug" by setting system to null, when leaving the orbit. In this vein no longer check for a stargate-connection when a fleet isn't at a system anymore.
* Only the victor and the owner of the colony fought over get a scan on the system. Not all participants. Especially not someone who fled from the orion-guardian and wanted to exploit this bug to get free high-end-techs!
* Prepare next version number since Ray hasn't commited anything yet since the beginning of June. :(
* Presumably a better fix to the issue of carrying over button-presses to the next stack. But I don't have a good save to test it.
* Fixed that for certain techs the inherited baseValue method either had no override or the override did not reference to the corresponding AI-method.
* Reverted fix for redirecting ships with hyperspace-communications to their source-system because it could crash the game when trying to redirect ships using rally-points.
* Using same ship-design-naming-pattern for all types of ships so player can't idintify colony-ships by looking at the name.
* Added missing override for baseValue from AI.
* Made separate method for upgradeCost so it can be used from outside, like AI for example.
* Fixed an issue where ships wouldn't retreat when they couldn't path to their preferred target.
* Changed how much the AI values certain technologies. Most notably will it like warp-speed-improvements more.
* Introduced an algorithm that guesses how long it will take to kill another empire and how long it would take the other empire to kill ourselves. This is used in target-selection and also in order to decide on whether we should go all in with our military. If we think the other empire can kill us more quickly than what it takes to benefit from investments into economy, we go all-in with building military.
* Fixed an issue that prevented ships being sent back to where they came from while in space via using hyperspace-communications. Note: The intention of that code is already handled by the "CanSendTo"-check just above of it. At this place the differientiation between beeing in transit is made, so that code was redundant for it's intended use-case.
* Production- and reseach-modifier now considered in decision to build ships non-stop or not. Fixed bug that caused AI-colonies to not build ships when they should. Consider incoming transports in decision whether to build population or not.
* Big revamp of dimplomatic AI-behavior. AI should now make much more sophisticated decisions about when to go to war.
* No longer bolstering population of low-pop-systems during war as this is pretty exploitable and detracts from producting military.
* Version
* Fixed a weird issue that prevented AIs from bombarding each other unless the player had knowledge about who the owner of the system to be bombarded is.
* Less willing to go to war, when there's other ways to expand.
* Fixed issue with colonizers and hyper-space-communications, that I thought I had fixed before.
When there's other possible targets to attack, a fleet waiting for invasion-forces, that can glass the system it is orbiting will split up and continue its attack.
* Only building excess colonizers, when someone we know (including ourselves) is at war and there's potential to colonize systems that are freed up by that war.
* At 72% and higher population a system wanting to build a colonizer will go all-in on it. This mostly affects Sakkra and Meklar, so they expand quicker and make more use of fast pop-growth.
* Fixed extremely rare crash.
* 0.93g
* Guessing travel-time and impact of nebulae instead of actually calculating the correct travel-times including nebulae to improve turn-times.
* No longer using bestVictim in ship-Design-Code.
* Lower limit from transport-size removed.
* Yet another big revamp about when to go to war. It's much more simple now.
* Transports sent towards someone who we don't want to have a war with now will be set to surrender on arrival. Travel-distance-calculation simplified in favor of turn-processing. Fixed dysfunctional defense-code that was recently broken.
* Pop-growth now plays a role in invasion-decisionmaking. Invasions now can occur without a fleet in orbit. Code for estimating kill-time now takes invasions into account. Drastically simplified victim-selection.
* Due to the changes in how the AI handles it's fleets during the wait time for invasions the amount of bombers built was increased.
* Changed how it is determined whether to retreat against fleets with repulsors. Fixed issue with not firing missiles under certain circumstances. Stacks of smaller ships fighting against stacks of bigger ships are now more likely to retreat, when they can't kill at least one of the bigger ships per turn.
* Moved accidental-stargate-building-prevention-workaround to where it actually is effective.
* Fixed an issue where a combat would end prematurely when missiles were fired but still on their way to their target.
* Removed commented-out code
* Removed actual war-weariness from the reasons to make peace as there's now other and better reasons to make peace.
* Bombers are now more specialized as in better at bombing and worse at actual combat.
* Bomb-Percentage now considers all opponents, not just the current enemy.
* The usage of designs is now recognized by their loadout and not by what role it was assigned to it during design.
* No longer super-heavy commitment to ship-production in war. Support of hybrid-playstyle.
* Fixed issue that sometimes prevented shooting missiles.
* Lowered counter-espionage by no longer looking at average tech-level of opponents but instead at tech-level of highest opponent.
* Support for hybrid ship-designs and many tweaks- and fixes in scrapping-logic.
* Setting eco-slider with a popup that promts for a percentage now uses the percentage of the amount that isn't required to keep clean.
* Fixed previously integrated potential dead-lock.
* Indentation
* Fix for becoming enemy of others before they are in range in the always-war-mode.
* Version-number for next inofficial build.
* No security-spending when no contact. But luckily that actually makes no difference between it only actually gets detracted from income when there's contacts.
* Revert "Setting eco-slider with a popup that promts for a percentage now uses the percentage of the amount that isn't required to keep clean."
This reverts commit a2fe5dce3c1be344b6c96b6bfa1b5d16b321fafa.
* Taught AI to use divert-reserve to research-checkbox
* I don't know how it can happen but I've seen rare cases of colonies with negative-population. This is a workaround that changes them back to 1 pop.
* Skip AI turn when corresponing empire is dead.
* Fixed possible endless-loop from scrapping last existing ship-design.
* Fixed issue where AI would build colonizers as bombers after having scrapped their last existing bomber-design.
* Removed useless code.
* Removed useless code.
* Xilmi AI now capable of deciding when to use bio-weapons.
* Bioweapon-support
* New voting behavior: Xilmi Ai now votes for whoever they are most scared of but aren't at war with.
* Fixed for undecisive behavior of launching an assault but retreating until transports arrive because developmentPct is no longer maxxed after sending transports. (War would still get triggered by the invasion but the fleet sent to accompany the invasion would retreat)
* No longer escorting colony-ships on their way to presumably undefended systems. Reason: This oftentimes used a good portion of the fleet for no good reason, when they could be better used for attacking/defending.
* Requiring closer range to fire missiles.
* Lower score for using bio-weapons depending on how many missile-bases are seen.
* No longer altering tech-allocations based on war-state.
* New, more diverse and supposedly more interesting diplomatic behavior for AI.
* Pick weapon to counter best enemy shield in use rather than average to avoid situations where lasers or scatterpack-V are countered too hard. Also: Make sure that there is a design with the most current bomb before considering bio-weapons.
* Weapons that allow heavy-mounts don't get their value decreased so AI doesn't end up without decent repulsor-counter.
* Moved negative-population workaround to a place where it is actually called.
* Smarter decision-making about when to bomb or not to bomb during on-going invasions.
* Incoming invasions of oneself should be slightly better covered but without tying too much of the fleet to it.
* Choose target by distance from fleet.
* Giving more cover to incoming invasions.
* Made rank-check-functions available outside of diplomat too.
* Always abstain if not both candidates are known. Superpowers should avoid wars.
* Fixed an issue where defenders wouldn't always stay back when they should.
* Don't hold back full power when in war anymore.
* Quality of ships now more important for scrapping than before.
* Reversed prior change in retreat-logic for smaller ships: Yes, the enemy could retreat but control over the system is probably more important than preserving some ships.
* Fixed issue where AI would retreat from repulsors when they had missiles.
* Minimum speed-requirement for missiles now takes repulsor-beams and diagonals into account.
* AI will prepare their wars a little better and also take having to prepare into account before invadion.
* No longer voting until both candidates are met. AI now knows much better to capitalize on an advantage and actually win the game instead of throwing it in a risky way.
* Moved a debug-output to another place.
* 0.93l
* Better preparations before going to war. Removed alliances again.
* Pick war-target by population-center rather than potential population center.
* Fixed a bunch of issued leading to bad colony-ship-management in the lategame.
* The better an AI is doing, the more careful they are about how to pick their enemies.
* Increased minimum ship-maintenance-threshold for the early-game.
* New version
* Forgot to remove a debug-message.
* Fixed issue reported by u/Individual_Act289: Transports launched before final war disappear on arrival.
* Fixed logical error in maxFiringRange-method which could cause unwanted retreats.
* When at war, AI will not make so many colony-ships, fixed issue where invasions wouldn't happen against partially built missile-bases, build more bombers when there's a high military-superiority
* Willingness to defend now scales with defense-ratio.
* Holding back before going to war as long as techs can still be easily researched.
* AI will get a bit more tech when it's opportune instead of going for war.
* Smart path will avoid paths where the detour would be longer than 50%, fleets that would otherwise go to a staging-point while they are orbiting an enemy will instead stay in orbit of the enemy.
* Yet unused methor determining the required count of fighters to shoo scouts away.
* Techs that are more than 5 levels behind the average will now be researched even if they are low priority.
* Handling for enemy missile-frigates.
* No longer scrap ships while at war.
* Shields are seen as more useful, new way of determining what size ships should be.
* enemyTransportsInTransit now also returns transports of neutral/cold-war-opponents
* Created separate method unfriendlyTransportsInTransit
* Improved algorithm to determine ship-design-size, reduction in score for hybrids without bombs
* Run from missile code should no longer try to outrun missiles that are too close already
* New method for unfriendlyTransportsInTransit used
* Taught AI to protect their systems against scouting
* Taught AI to protect their systems against scouting
* Fixed issue that prevented scouts from being sent to long-range-targets when they were part of a fleet with other ships.
* Xilmi-AI now declaring war at any poploss, not just at 30+
* Sanity check for fleeing from missiles: Only do it when something could actually be lost.
* Prepare better for potential attacks.
* Some code cleanup
* Fixed issue where other ships than destroyers could be built as scout-repellers.
* Avoid downsizing of weapons in non-destroyer-ships.
* Distances need to be recalculated immediately after obtaining new system as otherwise AI would act on outdated information. In this case it led to the AI offering peace due to losing range on an opponent whos colony it just conquered despite that act bringing lots of new systems into range.
* Fixed an issue where AI would consider an opponents contacts instead of their own when determining the opponents relative standing. Also no longer looking at empires outside of ship-range for potential wars.
* Priority for my purpose needs to be above 1000 and below 1400. Below 1000 it gets into conflict with scouts and above 1400 it will rush out the ships under all circumstances.
* The widespread usage of scout-repellers makes adding a weapon to a colony-ship much more important.
* Added missing override for maxFiringRange
* Fixed that after capturing a colony the default for max-bases was not used from the settings of the new owner.
* Default for bases on new systems and whether excess-spending goes to research can now be changed in Remnants.cfg
|
https://github.com/rayfowler/rotp-public/commit/ae8d59a471c4dfd937b78eea543333207c1009a8
| null | null |
src/rotp/ui/UserPreferences.java
| 0
|
java
| false
|
2021-10-01T02:25:33Z
|
public List<GKEClusterVH> fetchGKEClusterInventory(ProjectVH project) throws IOException, GeneralSecurityException {
List<GKEClusterVH> gkeClusterlist = new ArrayList<>();
logger.info("### GKe cluster collector ###########");
try {
List<String> regions = gcPlocationUtil.getZoneList(project.getProjectId());
regions.addAll(gcPlocationUtil.getLocations(project.getProjectId()));
regions.remove("us");
regions.remove("global");
logger.debug("Number of regions {}", regions.size());
logger.debug("Regions are:{}", regions);
for (String region : regions) {
logger.info("### GKe cluster clusterList inside region {}", region);
ClusterManagerClient clusterManagerClient = gcpCredentialsProvider.getClusterManagerClient();
String parent="projects/"+project.getProjectId()+"/locations/"+region;
ListClustersResponse clusterList=null;
try {
clusterList=clusterManagerClient.listClusters(parent);
logger.info("cluster Size {}", clusterManagerClient.listClusters(parent).getClustersList());
}
catch (Exception e){
logger.info("Exception {}",e.getMessage());
}
for (Cluster cluster : clusterList.getClustersList()) {
GKEClusterVH gkeClusterVH = new GKEClusterVH();
gkeClusterVH.setId(cluster.getId());
gkeClusterVH.setProjectName(project.getProjectName());
gkeClusterVH.setProjectId(project.getProjectId());
gkeClusterVH.set_cloudType(InventoryConstants.CLOUD_TYPE_GCP);
gkeClusterVH.setIPAlias(cluster.getIpAllocationPolicy().getUseIpAliases());
gkeClusterVH.setCloudLogging(cluster.getLoggingService());
gkeClusterVH.setCloudMonitoring(cluster.getMonitoringService());
logger.info("monitoring services {} {}", cluster.getName(),cluster.getMonitoringService()); if(cluster.getAddonsConfig()!=null && !cluster.getAddonsConfig().getAllFields().isEmpty()){
gkeClusterVH.setDisableKubernetesDashBoard(cluster.getAddonsConfig().getKubernetesDashboard().getDisabled());
}
if(cluster.getPrivateClusterConfig()!=null){
gkeClusterVH.setEnablePrivateNodes(cluster.getPrivateClusterConfig().getEnablePrivateNodes());
gkeClusterVH.setEnablePrivateEndPoints(cluster.getPrivateClusterConfig().getEnablePrivateEndpoint());
}
else{
gkeClusterVH.setEnablePrivateNodes(false);
gkeClusterVH.setEnablePrivateEndPoints(false);
}
gkeClusterVH.setClientKey(cluster.getMasterAuth().getClientKey());
gkeClusterVH.setVersion(cluster.getCurrentMasterVersion());
gkeClusterVH.setRegion(cluster.getLocation());
if (cluster.getMasterAuthorizedNetworksConfig() !=null && !cluster.getMasterAuthorizedNetworksConfig().getAllFields().isEmpty()) {
logger.info("getMasterAuthorizedNetworksConfig {} ***********",cluster.getMasterAuthorizedNetworksConfig().toString());
HashMap<String, Object> masterAuthorizedNetworksConfigMap = new HashMap<>();
cluster.getMasterAuthorizedNetworksConfig().getAllFields().forEach((fieldDescriptor, o) -> {
logger.info("field Descriptor {} {}",fieldDescriptor.getName(),o.toString());
masterAuthorizedNetworksConfigMap.put(fieldDescriptor.getName(),o.toString());
}
);
gkeClusterVH.setMasterAuthorizedNetworksConfig(masterAuthorizedNetworksConfigMap);
}
if (cluster.getDatabaseEncryption().getKeyName() != null) {
String keyName = new Gson().fromJson(
cluster.getDatabaseEncryption().getKeyName(), String.class);
gkeClusterVH.setKeyName(keyName);
}
gkeClusterVH.setLegacyAuthorization(cluster.hasLegacyAbac());
gkeClusterVH.setIntraNodeVisibility(cluster.getNetworkConfig().getEnableIntraNodeVisibility());
String nodepoolParent = "projects/" + project.getProjectId() + "/locations/" + region + "/clusters/" + cluster.getName();
ListNodePoolsResponse listNodePools = null;
try {
listNodePools = clusterManagerClient.listNodePools(nodepoolParent);
} catch (Exception e) {
logger.debug(e.getMessage());
}
List<NodePoolVH> nodePoolVHList = new ArrayList<>();
if (listNodePools != null) {
for (NodePool nodePool : listNodePools.getNodePoolsList()) {
NodePoolVH nodePoolVH=new NodePoolVH();
nodePoolVH.setAutoUpgrade(nodePool.getManagement().getAutoUpgrade());
nodePoolVH.setAutoRepair(nodePool.getManagement().getAutoRepair());
if(nodePool.getConfig().getBootDiskKmsKey()!=null){
String bootDiskKmsKey=new Gson().fromJson(nodePool.getConfig().getBootDiskKmsKey(),String.class);
gkeClusterVH.setBootDiskKmsKey(bootDiskKmsKey);
}
nodePoolVH.setEnableIntegrityMonitoring(nodePool.getConfig().getShieldedInstanceConfig().getEnableIntegrityMonitoring());
nodePoolVH.setEnableSecureBoot(nodePool.getConfig().getShieldedInstanceConfig().getEnableSecureBoot());
nodePoolVHList.add(nodePoolVH);
}
}
gkeClusterVH.setNodePools(nodePoolVHList);
gkeClusterVH.setEnableKubernetesAlpha(cluster.getEnableKubernetesAlpha());
gkeClusterVH.setPassword(cluster.getMasterAuth().getPassword());
gkeClusterVH.setUsername(cluster.getMasterAuth().getUsername());
gkeClusterlist.add(gkeClusterVH);
}
logger.debug("##########ending########-> {}", gkeClusterlist);
}
} catch (Exception e) {
logger.debug(e.getMessage());
}
return gkeClusterlist;
}
|
public List<GKEClusterVH> fetchGKEClusterInventory(ProjectVH project) throws IOException, GeneralSecurityException {
List<GKEClusterVH> gkeClusterlist = new ArrayList<>();
logger.info("### GKe cluster collector ###########");
try {
List<String> regions = gcPlocationUtil.getZoneList(project.getProjectId());
regions.addAll(gcPlocationUtil.getLocations(project.getProjectId()));
regions.remove("us");
regions.remove("global");
logger.debug("Number of regions {}", regions.size());
logger.debug("Regions are:{}", regions);
for (String region : regions) {
logger.info("### GKe cluster clusterList inside region {}", region);
ClusterManagerClient clusterManagerClient = gcpCredentialsProvider.getClusterManagerClient();
String parent="projects/"+project.getProjectId()+"/locations/"+region;
ListClustersResponse clusterList=null;
try {
clusterList=clusterManagerClient.listClusters(parent);
logger.info("cluster Size {}", clusterManagerClient.listClusters(parent).getClustersList());
}
catch (Exception e){
logger.info("Exception {}",e.getMessage());
}
for (Cluster cluster : clusterList.getClustersList()) {
GKEClusterVH gkeClusterVH = new GKEClusterVH();
gkeClusterVH.setId(cluster.getId());
gkeClusterVH.setProjectName(project.getProjectName());
gkeClusterVH.setProjectId(project.getProjectId());
gkeClusterVH.set_cloudType(InventoryConstants.CLOUD_TYPE_GCP);
gkeClusterVH.setIPAlias(cluster.getIpAllocationPolicy().getUseIpAliases());
gkeClusterVH.setCloudLogging(cluster.getLoggingService());
gkeClusterVH.setCloudMonitoring(cluster.getMonitoringService());
logger.info("monitoring services {} {}", cluster.getName(),cluster.getMonitoringService()); if(cluster.getAddonsConfig()!=null && !cluster.getAddonsConfig().getAllFields().isEmpty()){
gkeClusterVH.setDisableKubernetesDashBoard(cluster.getAddonsConfig().getKubernetesDashboard().getDisabled());
}
if(cluster.getPrivateClusterConfig()!=null){
gkeClusterVH.setEnablePrivateNodes(cluster.getPrivateClusterConfig().getEnablePrivateNodes());
gkeClusterVH.setEnablePrivateEndPoints(cluster.getPrivateClusterConfig().getEnablePrivateEndpoint());
}
else{
gkeClusterVH.setEnablePrivateNodes(false);
gkeClusterVH.setEnablePrivateEndPoints(false);
}
gkeClusterVH.setClientKey(cluster.getMasterAuth().getClientKey());
gkeClusterVH.setVersion(cluster.getCurrentMasterVersion());
gkeClusterVH.setRegion(cluster.getLocation());
if (cluster.getMasterAuthorizedNetworksConfig() !=null && !cluster.getMasterAuthorizedNetworksConfig().getAllFields().isEmpty()) {
logger.info("getMasterAuthorizedNetworksConfig {} ***********",cluster.getMasterAuthorizedNetworksConfig().toString());
HashMap<String, Object> masterAuthorizedNetworksConfigMap = new HashMap<>();
cluster.getMasterAuthorizedNetworksConfig().getAllFields().forEach((fieldDescriptor, o) -> {
logger.info("field Descriptor {} {}",fieldDescriptor.getName(),o.toString());
masterAuthorizedNetworksConfigMap.put(fieldDescriptor.getName(),o.toString());
}
);
gkeClusterVH.setMasterAuthorizedNetworksConfig(masterAuthorizedNetworksConfigMap);
}
if (cluster.getDatabaseEncryption().getKeyName() != null) {
String keyName = new Gson().fromJson(
cluster.getDatabaseEncryption().getKeyName(), String.class);
gkeClusterVH.setKeyName(keyName);
}
gkeClusterVH.setLegacyAuthorization(cluster.getLegacyAbac().getEnabled());
gkeClusterVH.setIntraNodeVisibility(cluster.getNetworkConfig().getEnableIntraNodeVisibility());
String nodepoolParent = "projects/" + project.getProjectId() + "/locations/" + region + "/clusters/" + cluster.getName();
ListNodePoolsResponse listNodePools = null;
try {
listNodePools = clusterManagerClient.listNodePools(nodepoolParent);
} catch (Exception e) {
logger.debug(e.getMessage());
}
List<NodePoolVH> nodePoolVHList = new ArrayList<>();
if (listNodePools != null) {
for (NodePool nodePool : listNodePools.getNodePoolsList()) {
NodePoolVH nodePoolVH=new NodePoolVH();
nodePoolVH.setAutoUpgrade(nodePool.getManagement().getAutoUpgrade());
nodePoolVH.setAutoRepair(nodePool.getManagement().getAutoRepair());
if(nodePool.getConfig().getBootDiskKmsKey()!=null){
String bootDiskKmsKey=new Gson().fromJson(nodePool.getConfig().getBootDiskKmsKey(),String.class);
gkeClusterVH.setBootDiskKmsKey(bootDiskKmsKey);
}
nodePoolVH.setEnableIntegrityMonitoring(nodePool.getConfig().getShieldedInstanceConfig().getEnableIntegrityMonitoring());
nodePoolVH.setEnableSecureBoot(nodePool.getConfig().getShieldedInstanceConfig().getEnableSecureBoot());
nodePoolVHList.add(nodePoolVH);
}
}
gkeClusterVH.setNodePools(nodePoolVHList);
gkeClusterVH.setEnableKubernetesAlpha(cluster.getEnableKubernetesAlpha());
gkeClusterVH.setPassword(cluster.getMasterAuth().getPassword());
gkeClusterVH.setUsername(cluster.getMasterAuth().getUsername());
gkeClusterlist.add(gkeClusterVH);
}
logger.debug("##########ending########-> {}", gkeClusterlist);
}
} catch (Exception e) {
logger.debug(e.getMessage());
}
return gkeClusterlist;
}
|
fix: addressed azure and gcp bug fixes
|
https://github.com/PaladinCloud/CE/commit/ae6a5b4c1636a53884d9fdaddbd288f722cf6e22
| null | null |
jobs/gcp-discovery/src/main/java/com/tmobile/pacbot/gcp/inventory/collector/GKEClusterInventoryCollector.java
| 0
|
java
| false
| null |
@SubscribeEvent
public void onPostChatEvent(ChatEvent.Post e) {
if (McIf.getUnformattedText(e.getMessage()).matches("Type the price in emeralds or type 'cancel' to cancel:")) {
priceInput = true;
if (UtilitiesConfig.Market.INSTANCE.openChatMarket)
scheduledGuiScreen = new ChatGUI();
}
if (UtilitiesConfig.Market.INSTANCE.openChatMarket) {
if (McIf.getUnformattedText(e.getMessage()).matches("Type the (item name|amount you wish to (buy|sell)) or type 'cancel' to cancel:")) {
scheduledGuiScreen = new ChatGUI();
}
}
if (UtilitiesConfig.Bank.INSTANCE.openChatBankSearch) {
if (McIf.getUnformattedText(e.getMessage()).matches("Please type an item name in chat!")) {
scheduledGuiScreen = new ChatGUI();
}
}
}
|
@SubscribeEvent
public void onPostChatEvent(ChatEvent.Post e) {
if (McIf.getUnformattedText(e.getMessage()).matches("Type the price in emeralds or type 'cancel' to cancel:")) {
priceInput = true;
if (UtilitiesConfig.Market.INSTANCE.openChatMarket)
scheduledGuiScreen = new ChatGUI();
}
if (UtilitiesConfig.Market.INSTANCE.openChatMarket) {
if (McIf.getUnformattedText(e.getMessage()).matches("Type the (item name|amount you wish to (buy|sell)) or type 'cancel' to cancel:")) {
scheduledGuiScreen = new ChatGUI();
}
}
if (UtilitiesConfig.Bank.INSTANCE.openChatBankSearch) {
if (McIf.getUnformattedText(e.getMessage()).matches("Please type an item name in chat!")) {
scheduledGuiScreen = new ChatGUI();
}
}
Matcher warMatcher = WAR_CHAT_MESSAGE_PATTERN.matcher(McIf.getUnformattedText(e.getMessage()));
if (warMatcher.matches()) {
String territory = warMatcher.group(1);
ITextComponent m = new TextComponentString("Click here to set your waypoint to " + territory + ".");
m.getStyle()
.setColor(TextFormatting.BLUE)
.setUnderlined(true)
.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/territory " + territory))
.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponentString("Set waypoint to: " + territory)));
McIf.player().sendMessage(m);
}
}
|
feat: Implement dialogue hotbar button override (#399)
* Implement dialogue hotbar button fix
* Tighten dialogue state checks
|
https://github.com/Wynntils/Wynntils/commit/ecbd62849ae0bef80adf256cd009968c8a2c2756
| null | null |
src/main/java/com/wynntils/modules/utilities/events/ClientEvents.java
| 0
|
java
| false
| null |
public static boolean attackEntity(IToolStackView tool, LivingEntity attackerLiving, InteractionHand hand,
Entity targetEntity, DoubleSupplier cooldownFunction, boolean isExtraAttack, EquipmentSlot sourceSlot) {
// broken? give to vanilla
if (tool.isBroken() || !tool.hasTag(TinkerTags.Items.MELEE)) {
return false;
}
// nothing to do? cancel
// TODO: is it a problem that we return true instead of false when isExtraAttack and the final damage is 0 or we fail to hit? I don't think anywhere clientside uses that
if (attackerLiving.level.isClientSide || !targetEntity.isAttackable() || targetEntity.skipAttackInteraction(attackerLiving)) {
return true;
}
// fetch relevant entities
LivingEntity targetLiving = getLivingEntity(targetEntity);
Player attackerPlayer = null;
if (attackerLiving instanceof Player player) {
attackerPlayer = player;
}
// players base damage (includes tools damage stat)
// hack for offhand attributes: remove mainhand temporarily, and apply offhand
float damage = getAttributeAttackDamage(tool, attackerLiving, sourceSlot);
// missing: enchantment modifiers, we handle ourselves
// determine cooldown
float cooldown = (float)cooldownFunction.getAsDouble();
boolean fullyCharged = cooldown > 0.9f;
// calculate if it's a critical hit
// that is, in the air, not blind, targeting living, and not sprinting
boolean isCritical = !isExtraAttack && fullyCharged && attackerLiving.fallDistance > 0.0F && !attackerLiving.isOnGround() && !attackerLiving.onClimbable()
&& !attackerLiving.isInWater() && !attackerLiving.hasEffect(MobEffects.BLINDNESS)
&& !attackerLiving.isPassenger() && targetLiving != null && !attackerLiving.isSprinting();
// shared context for all modifier hooks
ToolAttackContext context = new ToolAttackContext(attackerLiving, attackerPlayer, hand, sourceSlot, targetEntity, targetLiving, isCritical, cooldown, isExtraAttack);
// calculate actual damage
// boost damage from traits
float baseDamage = damage;
List<ModifierEntry> modifiers = tool.getModifierList();
for (ModifierEntry entry : modifiers) {
damage = entry.getModifier().getEntityDamage(tool, entry.getLevel(), context, baseDamage, damage);
}
// no damage? do nothing
if (damage <= 0) {
return !isExtraAttack;
}
// forge patches in the knockback attribute for use on players
// vanilla halves the knockback attribute later, we half it in all our hooks, so halving the attribute makes it equivelent
float knockback = (float)attackerLiving.getAttributeValue(Attributes.ATTACK_KNOCKBACK) / 2f;
// vanilla applies 0.4 knockback to living via the attack hook
if (targetLiving != null) {
knockback += 0.4f;
}
// if sprinting, deal bonus knockback
SoundEvent sound;
if (attackerLiving.isSprinting() && fullyCharged) {
sound = SoundEvents.PLAYER_ATTACK_KNOCKBACK;
knockback += 0.5f;
} else if (fullyCharged) {
sound = SoundEvents.PLAYER_ATTACK_STRONG;
} else {
sound = SoundEvents.PLAYER_ATTACK_WEAK;
}
// knockback moved lower
// apply critical boost
if (!isExtraAttack) {
float criticalModifier = isCritical ? 1.5f : 1.0f;
if (attackerPlayer != null) {
CriticalHitEvent hitResult = ForgeHooks.getCriticalHit(attackerPlayer, targetEntity, isCritical, isCritical ? 1.5F : 1.0F);
isCritical = hitResult != null;
if (isCritical) {
criticalModifier = hitResult.getDamageModifier();
}
}
if (isCritical) {
damage *= criticalModifier;
}
}
// removed: sword check hook, replaced by weapon callback
// removed: fire aspect check, replaced by before damage lower
// apply cutoff and cooldown, store if damage was above base for magic particles
boolean isMagic = damage > baseDamage;
if (cooldown < 1) {
damage *= (0.2f + cooldown * cooldown * 0.8f);
}
// track original health and motion before attack
Vec3 originalTargetMotion = targetEntity.getDeltaMovement();
float oldHealth = 0.0F;
if (targetLiving != null) {
oldHealth = targetLiving.getHealth();
}
// removed: vanilla knockback enchant support
// changed: knockback halved for simplicity
// apply modifier knockback and special effects
float baseKnockback = knockback;
for (ModifierEntry entry : modifiers) {
knockback = entry.getModifier().beforeEntityHit(tool, entry.getLevel(), context, damage, baseKnockback, knockback);
}
// set hand for proper looting context
ModifierLootingHandler.setLootingSlot(attackerLiving, sourceSlot);
// prevent knockback if needed
Optional<AttributeInstance> knockbackModifier = getKnockbackAttribute(targetLiving);
// if knockback is below the vanilla amount, we need to prevent knockback, the remainder will be applied later
boolean canceledKnockback = false;
if (knockback < 0.4f) {
canceledKnockback = true;
knockbackModifier.ifPresent(ToolAttackUtil::disableKnockback);
} else if (targetLiving != null) {
// we will apply 0.4 of the knockback in the attack hook, need to apply the remainder ourself
knockback -= 0.4f;
}
///////////////////
// actual attack //
///////////////////
// removed: sword special attack check and logic, replaced by this
boolean didHit;
if (isExtraAttack) {
didHit = dealDefaultDamage(attackerLiving, targetEntity, damage);
} else {
didHit = tool.getDefinition().getData().getAttack().dealDamage(tool, context, damage);
}
// reset hand to make sure we don't mess with vanilla tools
ModifierLootingHandler.setLootingSlot(attackerLiving, EquipmentSlot.MAINHAND);
// reset knockback if needed
if (canceledKnockback) {
knockbackModifier.ifPresent(ToolAttackUtil::enableKnockback);
}
// if we failed to hit, fire failure hooks
if (!didHit) {
if (!isExtraAttack) {
attackerLiving.level.playSound(null, attackerLiving.getX(), attackerLiving.getY(), attackerLiving.getZ(), SoundEvents.PLAYER_ATTACK_NODAMAGE, attackerLiving.getSoundSource(), 1.0F, 1.0F);
}
// alert modifiers nothing was hit, mainly used for fiery
for (ModifierEntry entry : modifiers) {
entry.getModifier().failedEntityHit(tool, entry.getLevel(), context);
}
return !isExtraAttack;
}
// determine damage actually dealt
float damageDealt = damage;
if (targetLiving != null) {
damageDealt = oldHealth - targetLiving.getHealth();
}
// apply knockback
if (knockback > 0) {
if (targetLiving != null) {
targetLiving.knockback(knockback, Mth.sin(attackerLiving.getYRot() * DEGREE_TO_RADIANS), -Mth.cos(attackerLiving.getYRot() * DEGREE_TO_RADIANS));
} else {
targetEntity.push(-Mth.sin(attackerLiving.getYRot() * DEGREE_TO_RADIANS) * knockback, 0.1d, Mth.cos(attackerLiving.getYRot() * DEGREE_TO_RADIANS) * knockback);
}
attackerLiving.setDeltaMovement(attackerLiving.getDeltaMovement().multiply(0.6D, 1.0D, 0.6D));
attackerLiving.setSprinting(false);
}
// removed: sword sweep attack, handled above
// apply velocity change to players if needed
if (targetEntity.hurtMarked && targetEntity instanceof ServerPlayer serverPlayer) {
serverPlayer.connection.send(new ClientboundSetEntityMotionPacket(targetEntity));
targetEntity.hurtMarked = false;
// TODO: why was this needed before? targetEntity.setDeltaMovement(originalTargetMotion);
}
// play sound effects and particles
if (attackerPlayer != null) {
// particles
if (isCritical) {
sound = SoundEvents.PLAYER_ATTACK_CRIT;
attackerPlayer.crit(targetEntity);
}
if (isMagic) {
attackerPlayer.magicCrit(targetEntity);
}
// sounds
attackerLiving.level.playSound(null, attackerLiving.getX(), attackerLiving.getY(), attackerLiving.getZ(), sound, attackerLiving.getSoundSource(), 1.0F, 1.0F);
}
if (damageDealt > 2.0F && attackerLiving.level instanceof ServerLevel server) {
int particleCount = (int)(damageDealt * 0.5f);
server.sendParticles(ParticleTypes.DAMAGE_INDICATOR, targetEntity.getX(), targetEntity.getY(0.5), targetEntity.getZ(), particleCount, 0.1, 0, 0.1, 0.2);
}
// deal attacker thorns damage
attackerLiving.setLastHurtMob(targetEntity);
if (targetLiving != null) {
EnchantmentHelper.doPostHurtEffects(targetLiving, attackerLiving);
}
// apply modifier effects
// removed: bane of arthropods hook, replaced by this
int durabilityLost = targetLiving != null ? 1 : 0;
for (ModifierEntry entry : modifiers) {
durabilityLost += entry.getModifier().afterEntityHit(tool, entry.getLevel(), context, damageDealt);
}
// hurt resistance adjustment for high speed weapons
float speed = tool.getStats().get(ToolStats.ATTACK_SPEED);
int time = Math.round(20f / speed);
if (time < targetEntity.invulnerableTime) {
targetEntity.invulnerableTime = (targetEntity.invulnerableTime + time) / 2;
}
// final attack hooks
if (attackerPlayer != null) {
if (targetLiving != null) {
if (!attackerLiving.level.isClientSide && !isExtraAttack) {
ItemStack held = attackerLiving.getItemBySlot(sourceSlot);
if (!held.isEmpty()) {
held.hurtEnemy(targetLiving, attackerPlayer);
}
}
attackerPlayer.awardStat(Stats.DAMAGE_DEALT, Math.round(damageDealt * 10.0F));
}
// removed: fire damage, handled in modifier hook above
attackerPlayer.causeFoodExhaustion(0.1F);
// add usage stat
if (!isExtraAttack) {
attackerPlayer.awardStat(Stats.ITEM_USED.get(tool.getItem()));
}
}
// damage the tool
if (!tool.hasTag(TinkerTags.Items.UNARMED)) {
if (!tool.hasTag(TinkerTags.Items.MELEE_PRIMARY)) {
durabilityLost *= 2;
}
ToolDamageUtil.damageAnimated(tool, durabilityLost, attackerLiving);
}
return true;
}
|
public static boolean attackEntity(IToolStackView tool, LivingEntity attackerLiving, InteractionHand hand,
Entity targetEntity, DoubleSupplier cooldownFunction, boolean isExtraAttack, EquipmentSlot sourceSlot) {
// broken? give to vanilla
if (tool.isBroken() || !tool.hasTag(TinkerTags.Items.MELEE_OR_UNARMED)) {
return false;
}
// nothing to do? cancel
// TODO: is it a problem that we return true instead of false when isExtraAttack and the final damage is 0 or we fail to hit? I don't think anywhere clientside uses that
if (attackerLiving.level.isClientSide || !targetEntity.isAttackable() || targetEntity.skipAttackInteraction(attackerLiving)) {
return true;
}
// fetch relevant entities
LivingEntity targetLiving = getLivingEntity(targetEntity);
Player attackerPlayer = null;
if (attackerLiving instanceof Player player) {
attackerPlayer = player;
}
// players base damage (includes tools damage stat)
// hack for offhand attributes: remove mainhand temporarily, and apply offhand
float damage = getAttributeAttackDamage(tool, attackerLiving, sourceSlot);
// missing: enchantment modifiers, we handle ourselves
// determine cooldown
float cooldown = (float)cooldownFunction.getAsDouble();
boolean fullyCharged = cooldown > 0.9f;
// calculate if it's a critical hit
// that is, in the air, not blind, targeting living, and not sprinting
boolean isCritical = !isExtraAttack && fullyCharged && attackerLiving.fallDistance > 0.0F && !attackerLiving.isOnGround() && !attackerLiving.onClimbable()
&& !attackerLiving.isInWater() && !attackerLiving.hasEffect(MobEffects.BLINDNESS)
&& !attackerLiving.isPassenger() && targetLiving != null && !attackerLiving.isSprinting();
// shared context for all modifier hooks
ToolAttackContext context = new ToolAttackContext(attackerLiving, attackerPlayer, hand, sourceSlot, targetEntity, targetLiving, isCritical, cooldown, isExtraAttack);
// calculate actual damage
// boost damage from traits
float baseDamage = damage;
List<ModifierEntry> modifiers = tool.getModifierList();
for (ModifierEntry entry : modifiers) {
damage = entry.getModifier().getEntityDamage(tool, entry.getLevel(), context, baseDamage, damage);
}
// no damage? do nothing
if (damage <= 0) {
return !isExtraAttack;
}
// forge patches in the knockback attribute for use on players
// vanilla halves the knockback attribute later, we half it in all our hooks, so halving the attribute makes it equivelent
float knockback = (float)attackerLiving.getAttributeValue(Attributes.ATTACK_KNOCKBACK) / 2f;
// vanilla applies 0.4 knockback to living via the attack hook
if (targetLiving != null) {
knockback += 0.4f;
}
// if sprinting, deal bonus knockback
SoundEvent sound;
if (attackerLiving.isSprinting() && fullyCharged) {
sound = SoundEvents.PLAYER_ATTACK_KNOCKBACK;
knockback += 0.5f;
} else if (fullyCharged) {
sound = SoundEvents.PLAYER_ATTACK_STRONG;
} else {
sound = SoundEvents.PLAYER_ATTACK_WEAK;
}
// knockback moved lower
// apply critical boost
if (!isExtraAttack) {
float criticalModifier = isCritical ? 1.5f : 1.0f;
if (attackerPlayer != null) {
CriticalHitEvent hitResult = ForgeHooks.getCriticalHit(attackerPlayer, targetEntity, isCritical, isCritical ? 1.5F : 1.0F);
isCritical = hitResult != null;
if (isCritical) {
criticalModifier = hitResult.getDamageModifier();
}
}
if (isCritical) {
damage *= criticalModifier;
}
}
// removed: sword check hook, replaced by weapon callback
// removed: fire aspect check, replaced by before damage lower
// apply cutoff and cooldown, store if damage was above base for magic particles
boolean isMagic = damage > baseDamage;
if (cooldown < 1) {
damage *= (0.2f + cooldown * cooldown * 0.8f);
}
// track original health and motion before attack
Vec3 originalTargetMotion = targetEntity.getDeltaMovement();
float oldHealth = 0.0F;
if (targetLiving != null) {
oldHealth = targetLiving.getHealth();
}
// removed: vanilla knockback enchant support
// changed: knockback halved for simplicity
// apply modifier knockback and special effects
float baseKnockback = knockback;
for (ModifierEntry entry : modifiers) {
knockback = entry.getModifier().beforeEntityHit(tool, entry.getLevel(), context, damage, baseKnockback, knockback);
}
// set hand for proper looting context
ModifierLootingHandler.setLootingSlot(attackerLiving, sourceSlot);
// prevent knockback if needed
Optional<AttributeInstance> knockbackModifier = getKnockbackAttribute(targetLiving);
// if knockback is below the vanilla amount, we need to prevent knockback, the remainder will be applied later
boolean canceledKnockback = false;
if (knockback < 0.4f) {
canceledKnockback = true;
knockbackModifier.ifPresent(ToolAttackUtil::disableKnockback);
} else if (targetLiving != null) {
// we will apply 0.4 of the knockback in the attack hook, need to apply the remainder ourself
knockback -= 0.4f;
}
///////////////////
// actual attack //
///////////////////
// removed: sword special attack check and logic, replaced by this
boolean didHit;
if (isExtraAttack) {
didHit = dealDefaultDamage(attackerLiving, targetEntity, damage);
} else {
didHit = tool.getDefinition().getData().getAttack().dealDamage(tool, context, damage);
}
// reset hand to make sure we don't mess with vanilla tools
ModifierLootingHandler.setLootingSlot(attackerLiving, EquipmentSlot.MAINHAND);
// reset knockback if needed
if (canceledKnockback) {
knockbackModifier.ifPresent(ToolAttackUtil::enableKnockback);
}
// if we failed to hit, fire failure hooks
if (!didHit) {
if (!isExtraAttack) {
attackerLiving.level.playSound(null, attackerLiving.getX(), attackerLiving.getY(), attackerLiving.getZ(), SoundEvents.PLAYER_ATTACK_NODAMAGE, attackerLiving.getSoundSource(), 1.0F, 1.0F);
}
// alert modifiers nothing was hit, mainly used for fiery
for (ModifierEntry entry : modifiers) {
entry.getModifier().failedEntityHit(tool, entry.getLevel(), context);
}
return !isExtraAttack;
}
// determine damage actually dealt
float damageDealt = damage;
if (targetLiving != null) {
damageDealt = oldHealth - targetLiving.getHealth();
}
// apply knockback
if (knockback > 0) {
if (targetLiving != null) {
targetLiving.knockback(knockback, Mth.sin(attackerLiving.getYRot() * DEGREE_TO_RADIANS), -Mth.cos(attackerLiving.getYRot() * DEGREE_TO_RADIANS));
} else {
targetEntity.push(-Mth.sin(attackerLiving.getYRot() * DEGREE_TO_RADIANS) * knockback, 0.1d, Mth.cos(attackerLiving.getYRot() * DEGREE_TO_RADIANS) * knockback);
}
attackerLiving.setDeltaMovement(attackerLiving.getDeltaMovement().multiply(0.6D, 1.0D, 0.6D));
attackerLiving.setSprinting(false);
}
// removed: sword sweep attack, handled above
// apply velocity change to players if needed
if (targetEntity.hurtMarked && targetEntity instanceof ServerPlayer serverPlayer) {
serverPlayer.connection.send(new ClientboundSetEntityMotionPacket(targetEntity));
targetEntity.hurtMarked = false;
// TODO: why was this needed before? targetEntity.setDeltaMovement(originalTargetMotion);
}
// play sound effects and particles
if (attackerPlayer != null) {
// particles
if (isCritical) {
sound = SoundEvents.PLAYER_ATTACK_CRIT;
attackerPlayer.crit(targetEntity);
}
if (isMagic) {
attackerPlayer.magicCrit(targetEntity);
}
// sounds
attackerLiving.level.playSound(null, attackerLiving.getX(), attackerLiving.getY(), attackerLiving.getZ(), sound, attackerLiving.getSoundSource(), 1.0F, 1.0F);
}
if (damageDealt > 2.0F && attackerLiving.level instanceof ServerLevel server) {
int particleCount = (int)(damageDealt * 0.5f);
server.sendParticles(ParticleTypes.DAMAGE_INDICATOR, targetEntity.getX(), targetEntity.getY(0.5), targetEntity.getZ(), particleCount, 0.1, 0, 0.1, 0.2);
}
// deal attacker thorns damage
attackerLiving.setLastHurtMob(targetEntity);
if (targetLiving != null) {
EnchantmentHelper.doPostHurtEffects(targetLiving, attackerLiving);
}
// apply modifier effects
// removed: bane of arthropods hook, replaced by this
int durabilityLost = targetLiving != null ? 1 : 0;
for (ModifierEntry entry : modifiers) {
durabilityLost += entry.getModifier().afterEntityHit(tool, entry.getLevel(), context, damageDealt);
}
// hurt resistance adjustment for high speed weapons
float speed = tool.getStats().get(ToolStats.ATTACK_SPEED);
int time = Math.round(20f / speed);
if (time < targetEntity.invulnerableTime) {
targetEntity.invulnerableTime = (targetEntity.invulnerableTime + time) / 2;
}
// final attack hooks
if (attackerPlayer != null) {
if (targetLiving != null) {
if (!attackerLiving.level.isClientSide && !isExtraAttack) {
ItemStack held = attackerLiving.getItemBySlot(sourceSlot);
if (!held.isEmpty()) {
held.hurtEnemy(targetLiving, attackerPlayer);
}
}
attackerPlayer.awardStat(Stats.DAMAGE_DEALT, Math.round(damageDealt * 10.0F));
}
// removed: fire damage, handled in modifier hook above
attackerPlayer.causeFoodExhaustion(0.1F);
// add usage stat
if (!isExtraAttack) {
attackerPlayer.awardStat(Stats.ITEM_USED.get(tool.getItem()));
}
}
// damage the tool
if (!tool.hasTag(TinkerTags.Items.UNARMED)) {
if (!tool.hasTag(TinkerTags.Items.MELEE_PRIMARY)) {
durabilityLost *= 2;
}
ToolDamageUtil.damageAnimated(tool, durabilityLost, attackerLiving);
}
return true;
}
|
Fix chestplates being unable to attack (#5080)
|
https://github.com/SlimeKnights/TinkersConstruct/commit/ae60c1aec3b72eb31d63b75aa34e1b1b424a6e07
| null | null |
src/main/java/slimeknights/tconstruct/library/tools/helper/ToolAttackUtil.java
| 0
|
java
| false
| null |
public void setUpArrows() {
terminal.registerHandler(KEY_STROKE_UP, t -> {
if(choiceIndex < 0) {
originalInput = terminal.getPartialInput();
}
if(choiceIndex < choices.length - 1) {
choiceIndex++;
t.replaceInput(choices[choiceIndex], false);
}
return new ReadHandlerData(ReadInterruptionStrategy.Action.CONTINUE);
});
terminal.registerHandler(KEY_STROKE_DOWN, t -> {
if(choiceIndex >= 0) {
choiceIndex--;
String text = (choiceIndex < 0) ? originalInput : choices[choiceIndex];
t.replaceInput(text, false);
}
return new ReadHandlerData(ReadInterruptionStrategy.Action.CONTINUE);
});
}
|
private void setUpArrows() {
terminal.registerHandler(KEY_STROKE_UP, t -> {
if(choiceIndex < 0) {
originalInput = terminal.getPartialInput();
}
if(choiceIndex < choices.length - 1) {
choiceIndex++;
t.replaceInput(choices[choiceIndex], false);
}
return new ReadHandlerData(ReadInterruptionStrategy.Action.CONTINUE);
});
terminal.registerHandler(KEY_STROKE_DOWN, t -> {
if(choiceIndex >= 0) {
choiceIndex--;
String text = (choiceIndex < 0) ? originalInput : choices[choiceIndex];
t.replaceInput(text, false);
}
return new ReadHandlerData(ReadInterruptionStrategy.Action.CONTINUE);
});
}
|
Remove fixed Reporting Authorities
Changes:
- Deleted the ReportingAuthorityType enum
- Settlement only holds the ReportingAuthoirty and does not return the
type
- Equality methods on ReportingAuthority
- On save the restored ReportingAuthority instance override those loaded
from the XML file
- Dependent non-core classes (UI) converted to reference the 'code'
#412
|
https://github.com/mars-sim/mars-sim/commit/4b02ad2c07676c2952dd03f07c791f34d9418778
| null | null |
mars-sim-console/src/main/java/org/mars/sim/console/CommanderProfile.java
| 0
|
java
| false
|
2021-08-04T16:56:43Z
|
void addCanPacketTables() {
canPacketRawTableModel = new CanPacketRawTableModel();
canPacketRawTable = new JTable(canPacketRawTableModel);
canPacketRawTable.setAutoCreateRowSorter(true);
canPacketRawTable.addMouseListener(this);
JScrollPane scrollPane = new JScrollPane (canPacketRawTable,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
canPacketRawTable.setFillsViewportHeight(true);
canPacketRawTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
String PREV = "prev";
String NEXT = "next";
InputMap inMap = canPacketRawTable.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
inMap.put(KeyStroke.getKeyStroke("UP"), PREV);
inMap.put(KeyStroke.getKeyStroke("DOWN"), NEXT);
ActionMap actMap = canPacketRawTable.getActionMap();
actMap.put(PREV, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
// System.out.println("PREV");
int row = canPacketRawTable.getSelectedRow();
if (row > 0)
displayRow(table,NO_ROW_SELECTED, row-1);
}
});
actMap.put(NEXT, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
// System.out.println("NEXT");
int row = canPacketRawTable.getSelectedRow();
if (row < canPacketRawTable.getRowCount()-1)
displayRow(table,NO_ROW_SELECTED, row+1);
}
});
//table.setMinimumSize(new Dimension(6200, 6000));
healthPanel.add(scrollPane);
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment( JLabel.CENTER );
TableColumn column = null;
column = canPacketRawTable.getColumnModel().getColumn(0);
column.setPreferredWidth(45); // reset
column = canPacketRawTable.getColumnModel().getColumn(1);
column.setPreferredWidth(55); // uptime
column = canPacketRawTable.getColumnModel().getColumn(2);
column.setPreferredWidth(55); // seq
column = canPacketRawTable.getColumnModel().getColumn(3);
column.setPreferredWidth(55); // ID
column = canPacketRawTable.getColumnModel().getColumn(4);
column.setPreferredWidth(55); // ID HEX
for (int i=0; i<canPacketRawTable.getColumnCount()-5; i++) {
column = canPacketRawTable.getColumnModel().getColumn(i+5);
column.setPreferredWidth(30);
}
}
|
void addCanPacketTables() {
canPacketRawTableModel = new CanPacketRawTableModel();
canPacketRawTable = new JTable(canPacketRawTableModel);
canPacketRawTable.setAutoCreateRowSorter(true);
canPacketRawTable.addMouseListener(this);
JScrollPane scrollPane = new JScrollPane (canPacketRawTable,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
canPacketRawTable.setFillsViewportHeight(true);
canPacketRawTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
String PREV = "prev";
String NEXT = "next";
InputMap inMap = canPacketRawTable.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
inMap.put(KeyStroke.getKeyStroke("UP"), PREV);
inMap.put(KeyStroke.getKeyStroke("DOWN"), NEXT);
ActionMap actMap = canPacketRawTable.getActionMap();
actMap.put(PREV, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
//System.out.println("PREV CAN MSG");
int row = canPacketRawTable.getSelectedRow();
if (row > 0)
displayRow(canPacketRawTable,NO_ROW_SELECTED, row-1);
}
});
actMap.put(NEXT, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
//System.out.println("NEXT CAN MSG");
int row = canPacketRawTable.getSelectedRow();
if (row < canPacketRawTable.getRowCount()-1)
displayRow(canPacketRawTable,NO_ROW_SELECTED, row+1);
}
});
//table.setMinimumSize(new Dimension(6200, 6000));
healthPanel.add(scrollPane);
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment( JLabel.CENTER );
TableColumn column = null;
column = canPacketRawTable.getColumnModel().getColumn(0);
column.setPreferredWidth(45); // reset
column = canPacketRawTable.getColumnModel().getColumn(1);
column.setPreferredWidth(55); // uptime
column = canPacketRawTable.getColumnModel().getColumn(2);
column.setPreferredWidth(55); // seq
column = canPacketRawTable.getColumnModel().getColumn(3);
column.setPreferredWidth(55); // ID
column = canPacketRawTable.getColumnModel().getColumn(4);
column.setPreferredWidth(55); // ID HEX
for (int i=0; i<canPacketRawTable.getColumnCount()-5; i++) {
column = canPacketRawTable.getColumnModel().getColumn(i+5);
column.setPreferredWidth(30);
}
}
|
#720 fix crash when arrow keys used in CAN Packet table
|
https://github.com/ac2cz/FoxTelem/commit/d98c5ffce18f34e9ef422ad8902475aa561550b9
| null | null |
src/gui/tabs/CanExperimentTab.java
| 0
|
java
| false
|
2021-11-17T14:45:17Z
|
private static boolean isManaSourceReserved(Player ai, Card sourceCard, SpellAbility sa) {
if (sa == null) {
return false;
}
if (!(ai.getController() instanceof PlayerControllerAi)) {
return false;
}
AiController aic = ((PlayerControllerAi)ai.getController()).getAi();
int chanceToReserve = aic.getIntProperty(AiProps.RESERVE_MANA_FOR_MAIN2_CHANCE);
// Mana reserved for spell synchronization
if (AiCardMemory.isRememberedCard(ai, sourceCard, AiCardMemory.MemorySet.HELD_MANA_SOURCES_FOR_NEXT_SPELL)) {
return true;
}
PhaseType curPhase = ai.getGame().getPhaseHandler().getPhase();
// For combat tricks, always obey mana reservation
if (curPhase == PhaseType.COMBAT_DECLARE_BLOCKERS || curPhase == PhaseType.CLEANUP) {
if (!(ai.getGame().getPhaseHandler().isPlayerTurn(ai))) {
AiCardMemory.clearMemorySet(ai, AiCardMemory.MemorySet.HELD_MANA_SOURCES_FOR_ENEMY_DECLBLK);
AiCardMemory.clearMemorySet(ai, AiCardMemory.MemorySet.CHOSEN_FOG_EFFECT);
} else
AiCardMemory.clearMemorySet(ai, AiCardMemory.MemorySet.HELD_MANA_SOURCES_FOR_DECLBLK);
} else {
if ((AiCardMemory.isRememberedCard(ai, sourceCard, AiCardMemory.MemorySet.HELD_MANA_SOURCES_FOR_DECLBLK)) ||
(AiCardMemory.isRememberedCard(ai, sourceCard, AiCardMemory.MemorySet.HELD_MANA_SOURCES_FOR_ENEMY_DECLBLK))) {
// This mana source is held elsewhere for a combat trick.
return true;
}
}
// If it's a low priority spell (it's explicitly marked so elsewhere in the AI with a SVar), always
// obey mana reservations for Main 2; otherwise, obey mana reservations depending on the "chance to reserve"
// AI profile variable.
if (sa.getSVar("LowPriorityAI").equals("")) {
if (chanceToReserve == 0 || MyRandom.getRandom().nextInt(100) >= chanceToReserve) {
return false;
}
}
if (curPhase == PhaseType.MAIN2 || curPhase == PhaseType.CLEANUP) {
AiCardMemory.clearMemorySet(ai, AiCardMemory.MemorySet.HELD_MANA_SOURCES_FOR_MAIN2);
} else {
if (AiCardMemory.isRememberedCard(ai, sourceCard, AiCardMemory.MemorySet.HELD_MANA_SOURCES_FOR_MAIN2)) {
// This mana source is held elsewhere for a Main Phase 2 spell.
return true;
}
}
return false;
}
|
private static boolean isManaSourceReserved(Player ai, Card sourceCard, SpellAbility sa) {
if (sa == null) {
return false;
}
if (!(ai.getController() instanceof PlayerControllerAi)) {
return false;
}
// Mana reserved for spell synchronization
if (AiCardMemory.isRememberedCard(ai, sourceCard, AiCardMemory.MemorySet.HELD_MANA_SOURCES_FOR_NEXT_SPELL)) {
return true;
}
PhaseType curPhase = ai.getGame().getPhaseHandler().getPhase();
AiController aic = ((PlayerControllerAi)ai.getController()).getAi();
int chanceToReserve = aic.getIntProperty(AiProps.RESERVE_MANA_FOR_MAIN2_CHANCE);
// For combat tricks, always obey mana reservation
if (curPhase == PhaseType.COMBAT_DECLARE_BLOCKERS || curPhase == PhaseType.CLEANUP) {
if (!(ai.getGame().getPhaseHandler().isPlayerTurn(ai))) {
AiCardMemory.clearMemorySet(ai, AiCardMemory.MemorySet.HELD_MANA_SOURCES_FOR_ENEMY_DECLBLK);
AiCardMemory.clearMemorySet(ai, AiCardMemory.MemorySet.CHOSEN_FOG_EFFECT);
} else
AiCardMemory.clearMemorySet(ai, AiCardMemory.MemorySet.HELD_MANA_SOURCES_FOR_DECLBLK);
} else {
if ((AiCardMemory.isRememberedCard(ai, sourceCard, AiCardMemory.MemorySet.HELD_MANA_SOURCES_FOR_DECLBLK)) ||
(AiCardMemory.isRememberedCard(ai, sourceCard, AiCardMemory.MemorySet.HELD_MANA_SOURCES_FOR_ENEMY_DECLBLK))) {
// This mana source is held elsewhere for a combat trick.
return true;
}
}
// If it's a low priority spell (it's explicitly marked so elsewhere in the AI with a SVar), always
// obey mana reservations for Main 2; otherwise, obey mana reservations depending on the "chance to reserve"
// AI profile variable.
if (sa.getSVar("LowPriorityAI").equals("")) {
if (chanceToReserve == 0 || MyRandom.getRandom().nextInt(100) >= chanceToReserve) {
return false;
}
}
if (curPhase == PhaseType.MAIN2 || curPhase == PhaseType.CLEANUP) {
AiCardMemory.clearMemorySet(ai, AiCardMemory.MemorySet.HELD_MANA_SOURCES_FOR_MAIN2);
} else {
if (AiCardMemory.isRememberedCard(ai, sourceCard, AiCardMemory.MemorySet.HELD_MANA_SOURCES_FOR_MAIN2)) {
// This mana source is held elsewhere for a Main Phase 2 spell.
return true;
}
}
return false;
}
|
Fix infinite looping with two Basalt Monolith
|
https://github.com/Card-Forge/forge/commit/d857694d7ca0ce0b82ada368fb0206a775d26153
| null | null |
forge-ai/src/main/java/forge/ai/ComputerUtilMana.java
| 0
|
java
| false
|
2021-11-30T16:41:14Z
|
function hostbasedCb(buf, cb) {
var signature = privateKey.sign(buf);
if (signature instanceof Error) {
signature.message = 'Error while signing data with privateKey: '
+ signature.message;
signature.level = 'client-authentication';
self.emit('error', signature);
return tryNextAuth();
}
cb(signature);
}
|
function hostbasedCb(buf, cb) {
const signature = privateKey.sign(buf);
if (signature instanceof Error) {
signature.message =
`Error while signing with privateKey: ${signature.message}`;
signature.level = 'client-authentication';
this.emit('error', signature);
return tryNextAuth();
}
cb(signature);
}
|
examples,lib,test: switch to code rewrite
For more information see: https://github.com/mscdex/ssh2/issues/935
|
https://github.com/mscdex/ssh2/commit/f763271f41320e71d5cbee02ea5bc6a2ded3ca21
|
CVE-2020-26301
|
['CWE-78']
|
lib/client.js
| 0
|
js
| false
|
2020-10-07T19:57:49Z
|
@Override
public <TYPE> ColumnRegionObject<TYPE, Values> makeColumnRegionObject(
@NotNull final ColumnDefinition<TYPE> columnDefinition) {
// noinspection unchecked
final Class<TYPE> dataType = columnDefinition.getDataType();
final ColumnChunkPageStore<ATTR>[] sources = getPageStores(columnDefinition);
final ColumnChunkPageStore<DictionaryKeys>[] dictKeySources = getDictionaryKeysPageStores(columnDefinition);
final Chunk<ATTR>[] dicts = getDictionaries(columnDefinition);
if (sources.length == 1) {
// noinspection unchecked
return (ColumnRegionObject<TYPE, Values>) makeSingleColumnRegionObject(dataType, sources[0],
dictKeySources[0], dicts[0]);
}
// noinspection unchecked
return (ColumnRegionObject<TYPE, Values>) new ColumnRegionObject.StaticPageStore<TYPE, ATTR>(
tl().getRegionParameters(),
IntStream.range(0, sources.length)
.mapToObj(ri -> makeSingleColumnRegionObject(dataType, sources[ri], dictKeySources[ri],
dicts[ri]))
.toArray(ColumnRegionObject[]::new));
}
|
@Override
public <TYPE> ColumnRegionObject<TYPE, Values> makeColumnRegionObject(
@NotNull final ColumnDefinition<TYPE> columnDefinition) {
// noinspection unchecked
final Class<TYPE> dataType = columnDefinition.getDataType();
final ColumnChunkPageStore<ATTR>[] sources = getPageStores(columnDefinition);
final ColumnChunkPageStore<DictionaryKeys>[] dictKeySources =
getDictionaryKeysPageStores(columnDefinition);
final Supplier<Chunk<ATTR>>[] dictionaryChunkSuppliers =
getDictionaryChunkSuppliers(columnDefinition);
if (sources.length == 1) {
// noinspection unchecked
return (ColumnRegionObject<TYPE, Values>) makeSingleColumnRegionObject(dataType,
sources[0], dictKeySources[0], dictionaryChunkSuppliers[0]);
}
// noinspection unchecked
return (ColumnRegionObject<TYPE, Values>) new ColumnRegionObject.StaticPageStore<TYPE, ATTR>(
tl().getRegionParameters(),
IntStream.range(0, sources.length)
.mapToObj(ri -> makeSingleColumnRegionObject(dataType, sources[ri],
dictKeySources[ri], dictionaryChunkSuppliers[ri]))
.toArray(ColumnRegionObject[]::new));
}
|
QST to graphviz DOT format; and SVG, PNG, and others (#935)
|
https://github.com/deephaven/deephaven-core/commit/7b2eacfb6aeb9ec889ca6bba02146d737856ed4c
| null | null |
DB/src/main/java/io/deephaven/db/v2/locations/parquet/local/ParquetColumnLocation.java
| 0
|
java
| false
|
2021-08-26T19:49:30Z
|
public boolean containsCode() {
return codeLength >= 0;
}
|
public boolean containsCode() {
return codeAndExceptions != null;
}
|
Re-add uninlining for negative double/float consts (#10)
* Re-add uninlining for negative double/float consts
* Fix missing negative signs
* Remove negative POSITIVE/NEGATIVE_INFINITYs
|
https://github.com/Earthcomputer/kotlin-decompiler/commit/b60ebfaaea4f6163eb3722a433398817773d8a8d
| null | null |
src/org/jetbrains/java/decompiler/struct/StructMethod.java
| 0
|
java
| false
|
2021-05-29T23:35:09Z
|
public void clearWarnings() throws SQLException {}
|
public void clearWarnings() {}
|
fix(jdbc): getDate, getTime, and getTimestamp crash on empty text
Closes: #490
|
https://github.com/xerial/sqlite-jdbc/commit/bc5174ba197e6e6a1d054542d3e63f1e7d09ccd9
| null | null |
src/main/java/org/sqlite/jdbc3/JDBC3ResultSet.java
| 0
|
java
| false
|
2022-08-30T08:31:15Z
|
@Override
public boolean place(ISeedReader world, ChunkGenerator chunkGenerator, Random random, BlockPos position, StructureTargetConfig config) {
BlockPos.Mutable mutable = new BlockPos.Mutable();
BlockState chorusFlower = Blocks.CHORUS_FLOWER.defaultBlockState();
for(int i = 0; i < config.attempts; i++){
mutable.set(position).move(
random.nextInt(7) - 3,
-1,
random.nextInt(7) - 3
);
if(world.getBlockState(mutable).isAir() && world.getBlockState(mutable.above()).isAir() && world.getBlockState(mutable.move(Direction.DOWN)).canOcclude()){
// expensive. Do this check very last
// This seems to sometimes deadlock only on Forge. But not Fabric.
//!world.getLevel().structureFeatureManager().getStructureAt(mutable, true, config.targetStructure).isValid()
// Alternative. Won't follow the structure's bounds perfectly tho...
if(!world.startsForFeature(SectionPos.of(mutable), config.targetStructure).findAny().isPresent()){
continue;
}
world.setBlock(mutable, Blocks.END_STONE.defaultBlockState(), 3);
if(random.nextFloat() < 0.33f){
world.setBlock(
mutable.move(Direction.UP),
chorusFlower.setValue(ChorusFlowerBlock.AGE, 5 - random.nextInt(random.nextInt(6) + 1)),
3);
continue;
}
// check to make sure this chorus stem can be placed
boolean isValidSpot = true;
for(Direction direction : Direction.Plane.HORIZONTAL){
mutable.move(direction);
if(world.getBlockState(mutable).is(Blocks.CHORUS_PLANT)){
isValidSpot = false;
break;
}
mutable.move(direction.getOpposite());
}
if(!isValidSpot) continue;
mutable.move(Direction.UP);
world.setBlock(mutable,
Blocks.CHORUS_PLANT.defaultBlockState()
.setValue(ChorusPlantBlock.DOWN, true)
.setValue(ChorusPlantBlock.UP, true),
3);
Direction direction = Direction.Plane.HORIZONTAL.getRandomDirection(random);
if(random.nextFloat() < 0.33f || !world.getBlockState(mutable.relative(direction)).isAir()) {
world.setBlock(
mutable.move(Direction.UP),
chorusFlower.setValue(ChorusFlowerBlock.AGE, 5 - random.nextInt(random.nextInt(6) + 1)),
3);
continue;
}
world.setBlock(mutable.move(Direction.UP),
Blocks.CHORUS_PLANT.defaultBlockState()
.setValue(ChorusPlantBlock.DOWN, true)
.setValue(SixWayBlock.PROPERTY_BY_DIRECTION.get(direction), true),
3);
world.setBlock(mutable.move(direction), chorusFlower.setValue(ChorusFlowerBlock.AGE, random.nextInt(5)), 3);
}
}
return true;
}
|
@Override
public boolean place(ISeedReader world, ChunkGenerator chunkGenerator, Random random, BlockPos position, StructureTargetConfig config) {
BlockPos.Mutable mutable = new BlockPos.Mutable();
BlockState chorusFlower = Blocks.CHORUS_FLOWER.defaultBlockState();
for(int i = 0; i < config.attempts; i++){
mutable.set(position).move(
random.nextInt(7) - 3,
-1,
random.nextInt(7) - 3
);
if(world.getBlockState(mutable).isAir() && world.getBlockState(mutable.above()).isAir() && world.getBlockState(mutable.move(Direction.DOWN)).canOcclude()){
world.setBlock(mutable, Blocks.END_STONE.defaultBlockState(), 3);
if(random.nextFloat() < 0.33f){
world.setBlock(
mutable.move(Direction.UP),
chorusFlower.setValue(ChorusFlowerBlock.AGE, 5 - random.nextInt(random.nextInt(6) + 1)),
3);
continue;
}
// check to make sure this chorus stem can be placed
boolean isValidSpot = true;
for(Direction direction : Direction.Plane.HORIZONTAL){
mutable.move(direction);
if(world.getBlockState(mutable).is(Blocks.CHORUS_PLANT)){
isValidSpot = false;
break;
}
mutable.move(direction.getOpposite());
}
if(!isValidSpot) continue;
mutable.move(Direction.UP);
world.setBlock(mutable,
Blocks.CHORUS_PLANT.defaultBlockState()
.setValue(ChorusPlantBlock.DOWN, true)
.setValue(ChorusPlantBlock.UP, true),
3);
Direction direction = Direction.Plane.HORIZONTAL.getRandomDirection(random);
if(random.nextFloat() < 0.33f || !world.getBlockState(mutable.relative(direction)).isAir()) {
world.setBlock(
mutable.move(Direction.UP),
chorusFlower.setValue(ChorusFlowerBlock.AGE, 5 - random.nextInt(random.nextInt(6) + 1)),
3);
continue;
}
world.setBlock(mutable.move(Direction.UP),
Blocks.CHORUS_PLANT.defaultBlockState()
.setValue(ChorusPlantBlock.DOWN, true)
.setValue(SixWayBlock.PROPERTY_BY_DIRECTION.get(direction), true),
3);
world.setBlock(mutable.move(direction), chorusFlower.setValue(ChorusFlowerBlock.AGE, random.nextInt(5)), 3);
}
}
return true;
}
|
fixed translations and fluid separation
|
https://github.com/TelepathicGrunt/RepurposedStructures/commit/ea4158695280e6091435af8aeb5b70ef74c889a2
| null | null |
src/main/java/com/telepathicgrunt/repurposedstructures/world/features/StructureChorus.java
| 0
|
java
| false
|
2021-06-06T21:58:13Z
|
private void onFinishInflate() {
loadDimens();
mKeyguardStatusBar = mView.findViewById(R.id.keyguard_header);
mBigClockContainer = mView.findViewById(R.id.big_clock_container);
UserAvatarView userAvatarView = null;
KeyguardUserSwitcherView keyguardUserSwitcherView = null;
if (mKeyguardUserSwitcherEnabled && mUserManager.isUserSwitcherEnabled()) {
if (mKeyguardQsUserSwitchEnabled) {
ViewStub stub = mView.findViewById(R.id.keyguard_qs_user_switch_stub);
userAvatarView = (UserAvatarView) stub.inflate();
} else {
ViewStub stub = mView.findViewById(R.id.keyguard_user_switcher_stub);
keyguardUserSwitcherView = (KeyguardUserSwitcherView) stub.inflate();
}
}
updateViewControllers(
mView.findViewById(R.id.keyguard_status_view),
userAvatarView,
mKeyguardStatusBar,
keyguardUserSwitcherView);
mNotificationContainerParent = mView.findViewById(R.id.notification_container_parent);
NotificationStackScrollLayout stackScrollLayout = mView.findViewById(
R.id.notification_stack_scroller);
mNotificationStackScrollLayoutController.attach(stackScrollLayout);
mNotificationStackScrollLayoutController.setOnHeightChangedListener(
mOnHeightChangedListener);
mNotificationStackScrollLayoutController.setOverscrollTopChangedListener(
mOnOverscrollTopChangedListener);
mNotificationStackScrollLayoutController.setOnScrollListener(this::onNotificationScrolled);
mNotificationStackScrollLayoutController.setOnStackYChanged(this::onStackYChanged);
mNotificationStackScrollLayoutController.setOnEmptySpaceClickListener(
mOnEmptySpaceClickListener);
addTrackingHeadsUpListener(mNotificationStackScrollLayoutController::setTrackingHeadsUp);
mKeyguardBottomArea = mView.findViewById(R.id.keyguard_bottom_area);
mPreviewContainer = mView.findViewById(R.id.preview_container);
mKeyguardBottomArea.setPreviewContainer(mPreviewContainer);
mLastOrientation = mResources.getConfiguration().orientation;
initBottomArea();
mWakeUpCoordinator.setStackScroller(mNotificationStackScrollLayoutController);
mQsFrame = mView.findViewById(R.id.qs_frame);
mPulseExpansionHandler.setUp(mNotificationStackScrollLayoutController,
amount -> {
float progress = amount / mView.getHeight();
float overstretch = Interpolators.getOvershootInterpolation(progress,
(float) mMaxOverscrollAmountForPulse / mView.getHeight(),
0.2f);
setOverStrechAmount(overstretch);
});
mWakeUpCoordinator.addListener(new NotificationWakeUpCoordinator.WakeUpListener() {
@Override
public void onFullyHiddenChanged(boolean isFullyHidden) {
updateKeyguardStatusBarForHeadsUp();
}
@Override
public void onPulseExpansionChanged(boolean expandingChanged) {
if (mKeyguardBypassController.getBypassEnabled()) {
// Position the notifications while dragging down while pulsing
requestScrollerTopPaddingUpdate(false /* animate */);
updateQSPulseExpansion();
}
}
});
mView.setRtlChangeListener(layoutDirection -> {
if (layoutDirection != mOldLayoutDirection) {
mAffordanceHelper.onRtlPropertiesChanged();
mOldLayoutDirection = layoutDirection;
}
});
mView.setAccessibilityDelegate(mAccessibilityDelegate);
if (mShouldUseSplitNotificationShade) {
updateResources();
}
mTapAgainViewController.init();
}
|
private void onFinishInflate() {
loadDimens();
mKeyguardStatusBar = mView.findViewById(R.id.keyguard_header);
mBigClockContainer = mView.findViewById(R.id.big_clock_container);
UserAvatarView userAvatarView = null;
KeyguardUserSwitcherView keyguardUserSwitcherView = null;
if (mKeyguardUserSwitcherEnabled && mUserManager.isUserSwitcherEnabled()) {
if (mKeyguardQsUserSwitchEnabled) {
ViewStub stub = mView.findViewById(R.id.keyguard_qs_user_switch_stub);
userAvatarView = (UserAvatarView) stub.inflate();
} else {
ViewStub stub = mView.findViewById(R.id.keyguard_user_switcher_stub);
keyguardUserSwitcherView = (KeyguardUserSwitcherView) stub.inflate();
}
}
updateViewControllers(
mView.findViewById(R.id.keyguard_status_view),
userAvatarView,
mKeyguardStatusBar,
keyguardUserSwitcherView);
mNotificationContainerParent = mView.findViewById(R.id.notification_container_parent);
NotificationStackScrollLayout stackScrollLayout = mView.findViewById(
R.id.notification_stack_scroller);
mNotificationStackScrollLayoutController.attach(stackScrollLayout);
mNotificationStackScrollLayoutController.setOnHeightChangedListener(
mOnHeightChangedListener);
mNotificationStackScrollLayoutController.setOverscrollTopChangedListener(
mOnOverscrollTopChangedListener);
mNotificationStackScrollLayoutController.setOnScrollListener(this::onNotificationScrolled);
mNotificationStackScrollLayoutController.setOnStackYChanged(this::onStackYChanged);
mNotificationStackScrollLayoutController.setOnEmptySpaceClickListener(
mOnEmptySpaceClickListener);
addTrackingHeadsUpListener(mNotificationStackScrollLayoutController::setTrackingHeadsUp);
mKeyguardBottomArea = mView.findViewById(R.id.keyguard_bottom_area);
mPreviewContainer = mView.findViewById(R.id.preview_container);
mKeyguardBottomArea.setPreviewContainer(mPreviewContainer);
mLastOrientation = mResources.getConfiguration().orientation;
initBottomArea();
mWakeUpCoordinator.setStackScroller(mNotificationStackScrollLayoutController);
mQsFrame = mView.findViewById(R.id.qs_frame);
mPulseExpansionHandler.setUp(mNotificationStackScrollLayoutController);
mWakeUpCoordinator.addListener(new NotificationWakeUpCoordinator.WakeUpListener() {
@Override
public void onFullyHiddenChanged(boolean isFullyHidden) {
updateKeyguardStatusBarForHeadsUp();
}
@Override
public void onPulseExpansionChanged(boolean expandingChanged) {
if (mKeyguardBypassController.getBypassEnabled()) {
// Position the notifications while dragging down while pulsing
requestScrollerTopPaddingUpdate(false /* animate */);
}
}
});
mView.setRtlChangeListener(layoutDirection -> {
if (layoutDirection != mOldLayoutDirection) {
mAffordanceHelper.onRtlPropertiesChanged();
mOldLayoutDirection = layoutDirection;
}
});
mView.setAccessibilityDelegate(mAccessibilityDelegate);
if (mShouldUseSplitNotificationShade) {
updateResources();
}
mTapAgainViewController.init();
}
|
Fix drag down animation when bypassing
The drag down animation didn't do the transition
to the full shade visually, so things would look
out of place.
Fixes: 191282610
Test: drag down while bypassing
Change-Id: Icdd62155f3762621c1046ed5271476ec0b4e2635
Merged-In: Icdd62155f3762621c1046ed5271476ec0b4e2635
|
https://github.com/PixelExperience/frameworks_base/commit/286825f60c9f3e6155e9429eb8d6c312da562121
| null | null |
packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelViewController.java
| 0
|
java
| false
| null |
private void startForegroundService() {
notificationManager = NotificationManagerCompat.from(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel(CHANNEL_ID, CHANNEL_NAME);
}
remoteViewsSmall = new RemoteViews(getPackageName(), R.layout.layout_play_notification_small);
remoteViewsSmall.setOnClickPendingIntent(R.id.btn_pause, getPendingSelfIntent(getApplicationContext(), ACTION_PAUSE_PLAYBACK));
remoteViewsSmall.setOnClickPendingIntent(R.id.btn_close, getPendingSelfIntent(getApplicationContext(), ACTION_CLOSE));
remoteViewsSmall.setTextViewText(R.id.txt_name, recordName);
remoteViewsSmall.setInt(R.id.container, "setBackgroundColor", this.getResources().getColor(colorMap.getPrimaryColorRes()));
// remoteViewsBig = new RemoteViews(getPackageName(), R.layout.layout_play_notification_big);
// remoteViewsBig.setOnClickPendingIntent(R.id.btn_pause, getPendingSelfIntent(getApplicationContext(), ACTION_PAUSE_PLAYBACK));
// remoteViewsBig.setOnClickPendingIntent(R.id.btn_close, getPendingSelfIntent(getApplicationContext(), ACTION_CLOSE));
// remoteViewsBig.setTextViewText(R.id.txt_name, recordName);
// remoteViewsBig.setInt(R.id.container, "setBackgroundColor", this.getResources().getColor(colorMap.getPrimaryColorRes()));
// Create notification default intent.
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
// Create notification builder.
builder = new NotificationCompat.Builder(this, CHANNEL_ID);
builder.setWhen(System.currentTimeMillis());
builder.setContentTitle(getResources().getString(R.string.app_name));
builder.setSmallIcon(R.drawable.ic_play_circle);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
builder.setPriority(NotificationManagerCompat.IMPORTANCE_LOW);
} else {
builder.setPriority(Notification.PRIORITY_LOW);
}
// Make head-up notification.
builder.setContentIntent(pendingIntent);
builder.setCustomContentView(remoteViewsSmall);
// builder.setCustomBigContentView(remoteViewsBig);
builder.setOngoing(true);
builder.setOnlyAlertOnce(true);
builder.setDefaults(0);
builder.setSound(null);
notification = builder.build();
startForeground(NOTIF_ID, notification);
started = true;
}
|
private void startForegroundService() {
notificationManager = NotificationManagerCompat.from(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel(CHANNEL_ID, CHANNEL_NAME);
}
remoteViewsSmall = new RemoteViews(getPackageName(), R.layout.layout_play_notification_small);
remoteViewsSmall.setOnClickPendingIntent(R.id.btn_pause, getPendingSelfIntent(getApplicationContext(), ACTION_PAUSE_PLAYBACK));
remoteViewsSmall.setOnClickPendingIntent(R.id.btn_close, getPendingSelfIntent(getApplicationContext(), ACTION_CLOSE));
remoteViewsSmall.setTextViewText(R.id.txt_name, recordName);
remoteViewsSmall.setInt(R.id.container, "setBackgroundColor", this.getResources().getColor(colorMap.getPrimaryColorRes()));
// remoteViewsBig = new RemoteViews(getPackageName(), R.layout.layout_play_notification_big);
// remoteViewsBig.setOnClickPendingIntent(R.id.btn_pause, getPendingSelfIntent(getApplicationContext(), ACTION_PAUSE_PLAYBACK));
// remoteViewsBig.setOnClickPendingIntent(R.id.btn_close, getPendingSelfIntent(getApplicationContext(), ACTION_CLOSE));
// remoteViewsBig.setTextViewText(R.id.txt_name, recordName);
// remoteViewsBig.setInt(R.id.container, "setBackgroundColor", this.getResources().getColor(colorMap.getPrimaryColorRes()));
// Create notification default intent.
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
contentPendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
startForeground(NOTIF_ID, buildNotification());
started = true;
}
|
Fixed notifications progress update app crash
|
https://github.com/Dimowner/AudioRecorder/commit/16ebdf529e048332c210e86747428d3332d6f45a
| null | null |
app/src/main/java/com/dimowner/audiorecorder/app/PlaybackService.java
| 0
|
java
| false
|
2021-11-16T18:49:45Z
|
protected static string GetMappedPath(BaseItem item, string path, MediaProtocol? protocol)
{
if (protocol.HasValue && protocol.Value == MediaProtocol.File)
{
return LibraryManager.GetPathAfterNetworkSubstitution(path, item);
}
return path;
}
|
protected static string GetMappedPath(BaseItem item, string path, MediaProtocol? protocol)
{
if (protocol == MediaProtocol.File)
{
return LibraryManager.GetPathAfterNetworkSubstitution(path, item);
}
return path;
}
|
Merge remote-tracking branch 'upstream/master' into client-logger
|
https://github.com/jellyfin/jellyfin/commit/d3d9311f486e2a33b40cf0db7958cf5faaf22124
| null | null |
MediaBrowser.Controller/Entities/BaseItem.cs
| 0
|
cs
| false
|
2021-11-05T19:12:37Z
|
static int
_Py_SetArgcArgv(Py_ssize_t argc, wchar_t * const *argv)
{
const PyWideStringList argv_list = {.length = argc, .items = (wchar_t **)argv};
int res;
PyMemAllocatorEx old_alloc;
_PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
// XXX _PyRuntime.orig_argv only gets cleared by Py_Main(),
// so it it currently leaks for embedders.
res = _PyWideStringList_Copy(&_PyRuntime.orig_argv, &argv_list);
PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
return res;
}
|
static int
_Py_SetArgcArgv(Py_ssize_t argc, wchar_t * const *argv)
{
const PyWideStringList argv_list = {.length = argc, .items = (wchar_t **)argv};
int res;
PyMemAllocatorEx old_alloc;
_PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
// XXX _PyRuntime.orig_argv only gets cleared by Py_Main(),
// so it currently leaks for embedders.
res = _PyWideStringList_Copy(&_PyRuntime.orig_argv, &argv_list);
PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
return res;
}
|
Merge remote-tracking branch 'upstream/main' into 106242
|
https://github.com/python/cpython/commit/726da048d4c8bbdcf332fe43d6c41a232337b66f
| null | null |
Python/initconfig.c
| 0
|
c
| false
|
2023-07-03T19:38:51Z
|
@Override
public void renderButton(PoseStack matrices, int mouseX, int mouseY, float delta) {
Font textRenderer = client.font;
RenderSystem.setShader(GameRenderer::getPositionTexShader);
RenderSystem.setShaderTexture(0, WIDGETS_LOCATION);
RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, this.alpha);
int i = this.getYImage(this.isHovered());
RenderSystem.enableBlend();
RenderSystem.defaultBlendFunc();
RenderSystem.enableDepthTest();
blit(matrices, this.x, this.y, 0, 46 + i * 20, this.width / 2, this.height);
blit(matrices, this.x + this.width / 2, this.y, 200 - this.width / 2, 46 + i * 20, this.width / 2, this.height);
if (parent.getMicrophoneValue() > 0.95D) {
RenderSystem.setShaderColor(1.0F, 0.0F, 0.0F, this.alpha);
} else if (parent.getMicrophoneValue() > 0.7D) {
RenderSystem.setShaderColor(1.0F, 1.0F, 0.0F, this.alpha);
} else {
RenderSystem.setShaderColor(0.0F, 1.0F, 0.0F, this.alpha);
}
blit(matrices, this.x + 1, this.y + 1, 1, 47, (int) ((this.width - 2) * parent.getMicrophoneValue()), this.height - 2);
if (slider) {
this.renderBg(matrices, client, mouseX, mouseY);
int j = this.active ? 16777215 : 10526880;
drawCenteredString(matrices, textRenderer, this.getMessage(), this.x + this.width / 2, this.y + (this.height - 8) / 2, j | Mth.ceil(this.alpha * 255.0F) << 24);
}
// drawCenteredString(matrices, textRenderer, new TextComponent(String.format("%.2f dB", parent.getHighestDB())),
// this.x + this.width / 2, this.y + (this.height - 8) / 2, 16777215);
RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, this.alpha);
for (Button button : this.microphoneTest) {
button.x = this.x + this.width + 2;
button.y = this.y;
button.render(matrices, mouseX, mouseY, delta);
}
}
|
@Override
public void renderButton(PoseStack matrices, int mouseX, int mouseY, float delta) {
Font textRenderer = client.font;
RenderSystem.setShader(GameRenderer::getPositionTexShader);
RenderSystem.setShaderTexture(0, WIDGETS_LOCATION);
RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, this.alpha);
int i = this.getYImage(this.isHovered());
RenderSystem.enableBlend();
RenderSystem.defaultBlendFunc();
RenderSystem.enableDepthTest();
blit(matrices, this.x, this.y, 0, 46 + i * 20, this.width / 2, this.height);
blit(matrices, this.x + this.width / 2, this.y, 200 - this.width / 2, 46 + i * 20, this.width / 2, this.height);
if (parent.getMicrophoneValue() > 0.95D) {
RenderSystem.setShaderColor(1.0F, 0.0F, 0.0F, this.alpha);
} else if (parent.getMicrophoneValue() > 0.7D) {
RenderSystem.setShaderColor(1.0F, 1.0F, 0.0F, this.alpha);
} else {
RenderSystem.setShaderColor(0.0F, 1.0F, 0.0F, this.alpha);
}
blit(matrices, this.x + 1, this.y + 1, 1, 47, (int) ((this.width - 2) * parent.getMicrophoneValue()), this.height - 2);
if (slider) {
this.renderBg(matrices, client, mouseX, mouseY);
int j = this.active ? 16777215 : 10526880;
drawCenteredString(matrices, textRenderer, this.getMessage(), this.x + this.width / 2, this.y + (this.height - 8) / 2, j | Mth.ceil(this.alpha * 255.0F) << 24);
}
// drawCenteredString(matrices, textRenderer, new TextComponent(String.format("%.2f dB", parent.getHighestDB())),
// this.x + this.width / 2, this.y + (this.height - 8) / 2, 16777215);
RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, this.alpha);
for (BackgroundImageButton button : this.microphoneTest) {
button.x = this.x + this.width + 2;
button.y = this.y;
button.render(matrices, mouseX, mouseY, delta);
if (button.isHovered(false)) {
parent.setTooltip(ImmutableList.of(
new TranslatableComponent("gui.plasmo_voice.general.not_available")
));
}
}
}
|
• Downgrade Fabric API
• Fixed #110
|
https://github.com/plasmoapp/plasmo-voice/commit/9006b52de09c70b253be1134ea10e42fc81f9f95
| null | null |
common/src/main/java/su/plo/voice/client/gui/widgets/MicrophoneThresholdWidget.java
| 0
|
java
| false
|
2021-10-23T12:03:33Z
|
@Override
protected boolean enableTextToSpeech() {
return false;
}
|
@Override
public boolean enableTextToSpeech() {
return false;
}
|
fix crash, i hope
closes #147
|
https://github.com/badasintended/wthit/commit/e5279e894012592edde52e2a8d222aa27268851e
| null | null |
src/main/java/mcp/mobius/waila/gui/screen/ThemeEditorScreen.java
| 0
|
java
| false
|
2022-07-02T08:06:27Z
|
public int getConcurrency() throws SQLException {
return ResultSet.CONCUR_READ_ONLY;
}
|
public int getConcurrency() {
return ResultSet.CONCUR_READ_ONLY;
}
|
fix(jdbc): getDate, getTime, and getTimestamp crash on empty text
Closes: #490
|
https://github.com/xerial/sqlite-jdbc/commit/bc5174ba197e6e6a1d054542d3e63f1e7d09ccd9
| null | null |
src/main/java/org/sqlite/jdbc3/JDBC3ResultSet.java
| 0
|
java
| false
|
2022-08-30T08:31:15Z
|
def POST(self, path, body=None, ensure_encoding=True, log_request_body=True):
return self._request('POST', path, body=body, ensure_encoding=ensure_encoding,
log_request_body=log_request_body)
|
def POST(self, path, body=None, ensure_encoding=True, log_request_body=True,
ignore_prefix=False):
return self._request('POST', path, body=body, ensure_encoding=ensure_encoding,
log_request_body=log_request_body, ignore_prefix=ignore_prefix)
|
convert consumer register to bindings
|
https://github.com/pulp/pulp/commit/b542d7465f7e6e02e1ea1aec059ac607a65cefe7
| null | null |
bindings/pulp/bindings/server.py
| 0
|
py
| false
|
2015-09-04T19:29:00Z
|
@EventListener(priority = ListenerPriority.HIGH)
private static void init(TextureRegisterEvent event) {
TERRAIN = new SquareAtlas("/terrain.png", 16).setTessellator(Tessellator.INSTANCE);
GUI_ITEMS = new SquareAtlas("/gui/items.png", 16);
STATION_TERRAIN = new ExpandableAtlas(of(StationAPI.MODID, "terrain"), TERRAIN).initTessellator();
STATION_GUI_ITEMS = new ExpandableAtlas(of(StationAPI.MODID, "gui_items"), GUI_ITEMS);
STATION_JSON_MODELS = new JsonModelAtlas(of(StationAPI.MODID, "json_textures")).initTessellator();
JSON_MISSING = STATION_JSON_MODELS.addTexture(ResourceManager.parsePath(of(MODID, "missing"), "/textures", "png"));
//noinspection deprecation
TextureManager textureManager = ((Minecraft) FabricLoader.getInstance().getGameInstance()).textureManager;
TextureBinder textureBinder;
textureManager.addTextureBinder(new StationVanillaTextureBinder(TERRAIN.getTexture(BlockBase.FLOWING_WATER.texture), new StationStillWaterTextureBinder(), "/custom_water_still.png"));
textureBinder = new StationVanillaTextureBinder(TERRAIN.getTexture(BlockBase.FLOWING_WATER.texture + 1), new StationFlowingWaterTextureBinder(), "/custom_water_flowing.png");
textureBinder.textureSize = 2;
textureManager.addTextureBinder(textureBinder);
textureManager.addTextureBinder(new StationVanillaTextureBinder(TERRAIN.getTexture(BlockBase.FLOWING_LAVA.texture), new StationStillLavaTextureBinder(), "/custom_lava_still.png"));
textureBinder = new StationVanillaTextureBinder(TERRAIN.getTexture(BlockBase.FLOWING_LAVA.texture + 1), new StationFlowingLavaTextureBinder(), "/custom_lava_flowing.png");
textureBinder.textureSize = 2;
textureManager.addTextureBinder(textureBinder);
textureManager.addTextureBinder(new StationVanillaTextureBinder(TERRAIN.getTexture(BlockBase.FIRE.texture), new StationFireTextureBinder(0), "/custom_fire_e_w.png"));
textureManager.addTextureBinder(new StationVanillaTextureBinder(TERRAIN.getTexture(BlockBase.FIRE.texture + 16), new StationFireTextureBinder(1), "/custom_fire_n_s.png"));
textureManager.addTextureBinder(new StationVanillaTextureBinder(TERRAIN.getTexture(BlockBase.PORTAL.texture), new StationPortalTextureBinder(), "/custom_portal.png"));
textureManager.addTextureBinder(new StationCompassTextureBinder());
textureManager.addTextureBinder(new StationClockTextureBinder());
}
|
@EventListener(priority = ListenerPriority.HIGH)
private static void init(TextureRegisterEvent event) {
TERRAIN = new SquareAtlas("/terrain.png", 16).setTessellator(Tessellator.INSTANCE);
GUI_ITEMS = new SquareAtlas("/gui/items.png", 16);
STATION_TERRAIN = new ExpandableAtlas(of(StationAPI.MODID, "terrain"), TERRAIN).initTessellator();
STATION_GUI_ITEMS = new ExpandableAtlas(of(StationAPI.MODID, "gui_items"), GUI_ITEMS);
STATION_JSON_MODELS = new JsonModelAtlas(of(StationAPI.MODID, "json_textures")).setTessellator(TessellatorAccessor.newInst(8388608));
JSON_MISSING = STATION_JSON_MODELS.addTexture(ResourceManager.parsePath(of(MODID, "missing"), "/textures", "png"));
//noinspection deprecation
TextureManager textureManager = ((Minecraft) FabricLoader.getInstance().getGameInstance()).textureManager;
TextureBinder textureBinder;
textureManager.addTextureBinder(new StationVanillaTextureBinder(TERRAIN.getTexture(BlockBase.FLOWING_WATER.texture), new StationStillWaterTextureBinder(), "/custom_water_still.png"));
textureBinder = new StationVanillaTextureBinder(TERRAIN.getTexture(BlockBase.FLOWING_WATER.texture + 1), new StationFlowingWaterTextureBinder(), "/custom_water_flowing.png");
textureBinder.textureSize = 2;
textureManager.addTextureBinder(textureBinder);
textureManager.addTextureBinder(new StationVanillaTextureBinder(TERRAIN.getTexture(BlockBase.FLOWING_LAVA.texture), new StationStillLavaTextureBinder(), "/custom_lava_still.png"));
textureBinder = new StationVanillaTextureBinder(TERRAIN.getTexture(BlockBase.FLOWING_LAVA.texture + 1), new StationFlowingLavaTextureBinder(), "/custom_lava_flowing.png");
textureBinder.textureSize = 2;
textureManager.addTextureBinder(textureBinder);
textureManager.addTextureBinder(new StationVanillaTextureBinder(TERRAIN.getTexture(BlockBase.FIRE.texture), new StationFireTextureBinder(0), "/custom_fire_e_w.png"));
textureManager.addTextureBinder(new StationVanillaTextureBinder(TERRAIN.getTexture(BlockBase.FIRE.texture + 16), new StationFireTextureBinder(1), "/custom_fire_n_s.png"));
textureManager.addTextureBinder(new StationVanillaTextureBinder(TERRAIN.getTexture(BlockBase.PORTAL.texture), new StationPortalTextureBinder(), "/custom_portal.png"));
textureManager.addTextureBinder(new StationCompassTextureBinder());
textureManager.addTextureBinder(new StationClockTextureBinder());
}
|
Refactored PR #15
|
https://github.com/ModificationStation/StationAPI/commit/2eb940e6cb777415a097fc565fd38e904fb9a442
| null | null |
station-render-api-v0/src/main/java/net/modificationstation/stationapi/impl/client/texture/TextureInit.java
| 0
|
java
| false
|
2021-09-18T22:09:51Z
|
@Method(0x8001bbccL)
public static void FUN_8001bbcc(final int x, final int y) {
FUN_8001b92c();
final long s2 = _800bd700.getAddress();
long packet;
if(doubleBufferFrame_800bb108.get() != 0) {
//LAB_8001bf3c
GPU.queueCommand(6, new GpuCommandPoly(4)
.bpp(Bpp.BITS_15)
.vramPos(128, 256)
.monochrome((int)MEMORY.ref(4, s2).offset(0x8L).get() >> 8)
.pos(0, x + 128, y)
.pos(1, x + 383, y)
.pos(2, x + 128, y + displayHeight_1f8003e4.get() - 1)
.pos(3, x + 383, y + displayHeight_1f8003e4.get() - 1)
.uv(0, 0, 0)
.uv(1, 255, 0)
.uv(2, 0, 239)
.uv(3, 255, 239)
);
GPU.queueCommand(6, new GpuCommandPoly(4)
.bpp(Bpp.BITS_15)
.vramPos(0, 256)
.monochrome((int)MEMORY.ref(4, s2).offset(0x8L).get() >> 8)
.pos(0, x, y)
.pos(1, x + 255, y)
.pos(2, x, y + displayHeight_1f8003e4.get() - 1)
.pos(3, x + 255, y + displayHeight_1f8003e4.get() - 1)
.uv(0, 0, 0)
.uv(1, 255, 0)
.uv(2, 0, 239)
.uv(3, 255, 239)
);
if(displayWidth_1f8003e0.get() == 640) {
packet = gpuPacketAddr_1f8003d8.get();
MEMORY.ref(1, packet).offset(0x03L).setu(0x9L);
MEMORY.ref(4, packet).offset(0x04L).setu(0x2c80_8080L);
gpuLinkedListSetCommandTransparency(packet, false);
MEMORY.ref(1, packet).offset(0x04L).setu((int)MEMORY.ref(4, s2).offset(0x8L).get() >> 8);
MEMORY.ref(1, packet).offset(0x05L).setu((int)MEMORY.ref(4, s2).offset(0x8L).get() >> 8);
MEMORY.ref(1, packet).offset(0x06L).setu((int)MEMORY.ref(4, s2).offset(0x8L).get() >> 8);
MEMORY.ref(2, packet).offset(0x08L).setu(x + 256);
MEMORY.ref(2, packet).offset(0x0aL).setu(y);
MEMORY.ref(1, packet).offset(0x0cL).setu(0);
MEMORY.ref(1, packet).offset(0x0dL).setu(0);
MEMORY.ref(2, packet).offset(0x10L).setu(x + 511);
MEMORY.ref(2, packet).offset(0x12L).setu(y);
MEMORY.ref(1, packet).offset(0x14L).setu(255);
MEMORY.ref(1, packet).offset(0x15L).setu(0);
MEMORY.ref(2, packet).offset(0x16L).setu(0x114);
MEMORY.ref(2, packet).offset(0x18L).setu(x + 256);
MEMORY.ref(2, packet).offset(0x1aL).setu(y - 1 + displayHeight_1f8003e4.get());
MEMORY.ref(1, packet).offset(0x1cL).setu(0);
MEMORY.ref(1, packet).offset(0x1dL).setu(239);
MEMORY.ref(2, packet).offset(0x20L).setu(x + 511);
MEMORY.ref(2, packet).offset(0x22L).setu(y - 1 + displayHeight_1f8003e4.get());
MEMORY.ref(1, packet).offset(0x24L).setu(255);
MEMORY.ref(1, packet).offset(0x25L).setu(239);
queueGpuPacket(tags_1f8003d0.deref().get(6).getAddress(), packet);
gpuPacketAddr_1f8003d8.addu(0x28L);
packet = gpuPacketAddr_1f8003d8.get();
MEMORY.ref(1, packet).offset(0x03L).setu(0x9L);
MEMORY.ref(4, packet).offset(0x04L).setu(0x2c80_8080L);
gpuLinkedListSetCommandTransparency(packet, false);
MEMORY.ref(1, packet).offset(0x04L).setu((int)MEMORY.ref(4, s2).offset(0x8L).get() >> 8);
MEMORY.ref(1, packet).offset(0x05L).setu((int)MEMORY.ref(4, s2).offset(0x8L).get() >> 8);
MEMORY.ref(1, packet).offset(0x06L).setu((int)MEMORY.ref(4, s2).offset(0x8L).get() >> 8);
MEMORY.ref(2, packet).offset(0x08L).setu(x + 384);
MEMORY.ref(2, packet).offset(0x0aL).setu(y);
MEMORY.ref(1, packet).offset(0x0cL).setu(0);
MEMORY.ref(1, packet).offset(0x0dL).setu(0);
MEMORY.ref(2, packet).offset(0x10L).setu(x + 639);
MEMORY.ref(2, packet).offset(0x12L).setu(y);
MEMORY.ref(1, packet).offset(0x14L).setu(255);
MEMORY.ref(1, packet).offset(0x15L).setu(0);
MEMORY.ref(2, packet).offset(0x16L).setu(0x116);
MEMORY.ref(2, packet).offset(0x18L).setu(x + 384);
MEMORY.ref(2, packet).offset(0x1aL).setu(y - 1 + displayHeight_1f8003e4.get());
MEMORY.ref(1, packet).offset(0x1cL).setu(0);
MEMORY.ref(1, packet).offset(0x1dL).setu(239);
MEMORY.ref(2, packet).offset(0x20L).setu(x + 639);
MEMORY.ref(2, packet).offset(0x22L).setu(y - 1 + displayHeight_1f8003e4.get());
MEMORY.ref(1, packet).offset(0x24L).setu(255);
MEMORY.ref(1, packet).offset(0x25L).setu(239);
queueGpuPacket(tags_1f8003d0.deref().get(6).getAddress(), packet);
gpuPacketAddr_1f8003d8.addu(0x28L);
}
} else {
GPU.queueCommand(6, new GpuCommandPoly(4)
.bpp(Bpp.BITS_15)
.vramPos(128, 0)
.monochrome((int)MEMORY.ref(4, s2).offset(0x8L).get() >> 8)
.pos(0, x + 128, y)
.pos(1, x + 383, y)
.pos(2, x + 128, y + displayHeight_1f8003e4.get() - 1)
.pos(3, x + 383, y + displayHeight_1f8003e4.get() - 1)
.uv(0, 0, 16)
.uv(1, 255, 16)
.uv(2, 0, 255)
.uv(3, 255, 255)
);
GPU.queueCommand(6, new GpuCommandPoly(4)
.bpp(Bpp.BITS_15)
.vramPos(0, 0)
.monochrome((int)MEMORY.ref(4, s2).offset(0x8L).get() >> 8)
.pos(0, x, y)
.pos(1, x + 255, y)
.pos(2, x, y + displayHeight_1f8003e4.get() - 1)
.pos(3, x + 255, y + displayHeight_1f8003e4.get() - 1)
.uv(0, 0, 16)
.uv(1, 255, 16)
.uv(2, 0, 255)
.uv(3, 255, 255)
);
if(displayWidth_1f8003e0.get() == 640) {
packet = gpuPacketAddr_1f8003d8.get();
MEMORY.ref(1, packet).offset(0x03L).setu(0x9L);
MEMORY.ref(4, packet).offset(0x04L).setu(0x2c80_8080L);
gpuLinkedListSetCommandTransparency(packet, false);
MEMORY.ref(1, packet).offset(0x04L).setu((int)MEMORY.ref(4, s2).offset(0x8L).get() >> 8);
MEMORY.ref(1, packet).offset(0x05L).setu((int)MEMORY.ref(4, s2).offset(0x8L).get() >> 8);
MEMORY.ref(1, packet).offset(0x06L).setu((int)MEMORY.ref(4, s2).offset(0x8L).get() >> 8);
MEMORY.ref(2, packet).offset(0x08L).setu(x + 256);
MEMORY.ref(2, packet).offset(0x0aL).setu(y);
MEMORY.ref(1, packet).offset(0x0cL).setu(0);
MEMORY.ref(1, packet).offset(0x0dL).setu(16);
MEMORY.ref(2, packet).offset(0x10L).setu(x + 511);
MEMORY.ref(2, packet).offset(0x12L).setu(y);
MEMORY.ref(1, packet).offset(0x14L).setu(255);
MEMORY.ref(1, packet).offset(0x15L).setu(16);
MEMORY.ref(2, packet).offset(0x16L).setu(0x104);
MEMORY.ref(2, packet).offset(0x18L).setu(x + 256);
MEMORY.ref(2, packet).offset(0x1aL).setu(y - 1 + displayHeight_1f8003e4.get());
MEMORY.ref(1, packet).offset(0x1cL).setu(0);
MEMORY.ref(1, packet).offset(0x1dL).setu(255);
MEMORY.ref(2, packet).offset(0x20L).setu(x + 511);
MEMORY.ref(2, packet).offset(0x22L).setu(y - 1 + displayHeight_1f8003e4.get());
MEMORY.ref(1, packet).offset(0x24L).setu(255);
MEMORY.ref(1, packet).offset(0x25L).setu(255);
queueGpuPacket(tags_1f8003d0.deref().get(6).getAddress(), packet);
gpuPacketAddr_1f8003d8.addu(0x28L);
packet = gpuPacketAddr_1f8003d8.get();
MEMORY.ref(1, packet).offset(0x03L).setu(0x9L);
MEMORY.ref(4, packet).offset(0x04L).setu(0x2c80_8080L);
gpuLinkedListSetCommandTransparency(packet, false);
MEMORY.ref(1, packet).offset(0x04L).setu((int)MEMORY.ref(4, s2).offset(0x8L).get() >> 8);
MEMORY.ref(1, packet).offset(0x05L).setu((int)MEMORY.ref(4, s2).offset(0x8L).get() >> 8);
MEMORY.ref(1, packet).offset(0x06L).setu((int)MEMORY.ref(4, s2).offset(0x8L).get() >> 8);
MEMORY.ref(2, packet).offset(0x08L).setu(x + 384);
MEMORY.ref(2, packet).offset(0x0aL).setu(y);
MEMORY.ref(1, packet).offset(0x0cL).setu(0);
MEMORY.ref(1, packet).offset(0x0dL).setu(16);
MEMORY.ref(2, packet).offset(0x10L).setu(x + 639);
MEMORY.ref(2, packet).offset(0x12L).setu(y);
MEMORY.ref(1, packet).offset(0x14L).setu(255);
MEMORY.ref(1, packet).offset(0x15L).setu(16);
MEMORY.ref(2, packet).offset(0x16L).setu(0x106);
MEMORY.ref(2, packet).offset(0x18L).setu(x + 384);
MEMORY.ref(2, packet).offset(0x1aL).setu(y - 1 + displayHeight_1f8003e4.get());
MEMORY.ref(1, packet).offset(0x1cL).setu(0);
MEMORY.ref(1, packet).offset(0x1dL).setu(255);
MEMORY.ref(2, packet).offset(0x20L).setu(x + 639);
MEMORY.ref(2, packet).offset(0x22L).setu(y - 1 + displayHeight_1f8003e4.get());
MEMORY.ref(1, packet).offset(0x24L).setu(255);
MEMORY.ref(1, packet).offset(0x25L).setu(255);
queueGpuPacket(tags_1f8003d0.deref().get(6).getAddress(), packet);
gpuPacketAddr_1f8003d8.addu(0x28L);
}
}
}
|
@Method(0x8001bbccL)
public static void FUN_8001bbcc(final int x, final int y) {
FUN_8001b92c();
final long s2 = _800bd700.getAddress();
long packet;
if(doubleBufferFrame_800bb108.get() != 0) {
//LAB_8001bf3c
GPU.queueCommand(6, new GpuCommandPoly(4)
.bpp(Bpp.BITS_15)
.vramPos(128, 256)
.monochrome((int)MEMORY.ref(4, s2).offset(0x8L).get() >> 8)
.pos(0, x + 128, y)
.pos(1, x + 383, y)
.pos(2, x + 128, y + displayHeight_1f8003e4.get() - 1)
.pos(3, x + 383, y + displayHeight_1f8003e4.get() - 1)
.uv(0, 0, 0)
.uv(1, 255, 0)
.uv(2, 0, 239)
.uv(3, 255, 239)
);
GPU.queueCommand(6, new GpuCommandPoly(4)
.bpp(Bpp.BITS_15)
.vramPos(0, 256)
.monochrome((int)MEMORY.ref(4, s2).offset(0x8L).get() >> 8)
.pos(0, x, y)
.pos(1, x + 255, y)
.pos(2, x, y + displayHeight_1f8003e4.get() - 1)
.pos(3, x + 255, y + displayHeight_1f8003e4.get() - 1)
.uv(0, 0, 0)
.uv(1, 255, 0)
.uv(2, 0, 239)
.uv(3, 255, 239)
);
if(displayWidth_1f8003e0.get() == 640) {
GPU.queueCommand(6, new GpuCommandPoly(4)
.bpp(Bpp.BITS_15)
.vramPos(256, 256)
.monochrome((int)MEMORY.ref(4, s2).offset(0x8L).get() >> 8)
.pos(0, x + 256, y)
.pos(1, x + 511, y)
.pos(2, x + 256, y + displayHeight_1f8003e4.get() - 1)
.pos(3, x + 511, y + displayHeight_1f8003e4.get() - 1)
.uv(0, 0, 0)
.uv(1, 255, 0)
.uv(2, 0, 239)
.uv(3, 255, 239)
);
GPU.queueCommand(6, new GpuCommandPoly(4)
.bpp(Bpp.BITS_15)
.vramPos(384, 256)
.monochrome((int)MEMORY.ref(4, s2).offset(0x8L).get() >> 8)
.pos(0, x + 384, y)
.pos(1, x + 639, y)
.pos(2, x + 384, y + displayHeight_1f8003e4.get() - 1)
.pos(3, x + 639, y + displayHeight_1f8003e4.get() - 1)
.pos(0, 0, 0)
.pos(1, 255, 0)
.pos(2, 0, 239)
.pos(3, 255, 239)
);
}
} else {
GPU.queueCommand(6, new GpuCommandPoly(4)
.bpp(Bpp.BITS_15)
.vramPos(128, 0)
.monochrome((int)MEMORY.ref(4, s2).offset(0x8L).get() >> 8)
.pos(0, x + 128, y)
.pos(1, x + 383, y)
.pos(2, x + 128, y + displayHeight_1f8003e4.get() - 1)
.pos(3, x + 383, y + displayHeight_1f8003e4.get() - 1)
.uv(0, 0, 16)
.uv(1, 255, 16)
.uv(2, 0, 255)
.uv(3, 255, 255)
);
GPU.queueCommand(6, new GpuCommandPoly(4)
.bpp(Bpp.BITS_15)
.vramPos(0, 0)
.monochrome((int)MEMORY.ref(4, s2).offset(0x8L).get() >> 8)
.pos(0, x, y)
.pos(1, x + 255, y)
.pos(2, x, y + displayHeight_1f8003e4.get() - 1)
.pos(3, x + 255, y + displayHeight_1f8003e4.get() - 1)
.uv(0, 0, 16)
.uv(1, 255, 16)
.uv(2, 0, 255)
.uv(3, 255, 255)
);
if(displayWidth_1f8003e0.get() == 640) {
GPU.queueCommand(6, new GpuCommandPoly(4)
.bpp(Bpp.BITS_15)
.vramPos(256, 0)
.monochrome((int)MEMORY.ref(4, s2).offset(0x8L).get() >> 8)
.pos(0, x + 256, y)
.pos(1, x + 511, y)
.pos(2, x + 256, y + displayHeight_1f8003e4.get() - 1)
.pos(3, x + 511, y + displayHeight_1f8003e4.get() - 1)
.uv(0, 0, 16)
.uv(1, 255, 16)
.uv(2, 0, 255)
.uv(3, 255, 255)
);
GPU.queueCommand(6, new GpuCommandPoly(4)
.bpp(Bpp.BITS_15)
.vramPos(384, 0)
.monochrome((int)MEMORY.ref(4, s2).offset(0x8L).get() >> 8)
.pos(0, x + 384, y)
.pos(1, x + 639, y)
.pos(2, x + 384, y + displayHeight_1f8003e4.get() - 1)
.pos(3, x + 639, y + displayHeight_1f8003e4.get() - 1)
.uv(0, 0, 16)
.uv(1, 255, 16)
.uv(2, 0, 255)
.uv(3, 255, 255)
);
}
}
}
|
Cleanup; fix item list; fix addition squares not being red on counter-attack
|
https://github.com/Legend-of-Dragoon-Modding/Severed-Chains/commit/f99608ab535148601d96a08d1dce2806342fd5dd
| null | null |
src/main/java/legend/game/Scus94491BpeSegment.java
| 0
|
java
| false
|
2022-11-02T20:33:19Z
|
public static void init() {
ResourceManagerHelper.get(ResourceType.SERVER_DATA).registerReloadListener(new BodyManager.ReloadListener());
ServerWorldEvents.LOAD.register(BodyManager::onWorldLoad);
ServerWorldEvents.UNLOAD.register(BodyManager::onWorldUnload);
ServerPlayConnectionEvents.JOIN.register(BodyManager::onPlayerJoin);
TickEvent.SERVER_PRE.register((server) -> {
for (var playerEntity : server.getPlayerManager().getPlayerList()) {
if (playerEntity.currentScreenHandler instanceof ExtendedBlockEntityScreenHandler screenHandler) {
if (screenHandler.getBlockEntity() != null) {
screenHandler.getBlockEntity().syncData();
break;
}
}
if (playerEntity.currentScreenHandler instanceof ExtendedEntityScreenHandler screenHandler) {
if (screenHandler.getEntity() != null) {
screenHandler.getEntity().syncData();
}
}
}
});
TickEvent.SERVER_LEVEL_PRE.register((world -> {
var component = NetworkComponent.get(world);
if (component != null) {
component.tick();
}
}));
// Sync the rocket interiors so the game doesn't die when people interact with rockets.
ServerTickEvents.END_SERVER_TICK.register((server) -> {
var world = server.getWorld(AMWorlds.ROCKET_INTERIORS);
if (world == null) return;
AMComponents.ROCKET_COMPONENTS.get(world).getRockets().forEach(Rocket::tick);
AMComponents.ROCKET_COMPONENTS.sync(world);
});
}
|
public static void init() {
ResourceManagerHelper.get(ResourceType.SERVER_DATA).registerReloadListener(new BodyManager.ReloadListener());
ServerWorldEvents.LOAD.register(BodyManager::onWorldLoad);
ServerWorldEvents.UNLOAD.register(BodyManager::onWorldUnload);
ServerPlayConnectionEvents.JOIN.register(BodyManager::onPlayerJoin);
TickEvent.SERVER_PRE.register((server) -> {
for (var playerEntity : server.getPlayerManager().getPlayerList()) {
if (playerEntity.currentScreenHandler instanceof ExtendedBlockEntityScreenHandler screenHandler) {
if (screenHandler.getBlockEntity() != null) {
screenHandler.getBlockEntity().syncData();
break;
}
}
if (playerEntity.currentScreenHandler instanceof ExtendedEntityScreenHandler screenHandler) {
if (screenHandler.getEntity() != null) {
screenHandler.getEntity().syncData();
}
}
}
});
TickEvent.SERVER_LEVEL_PRE.register((world -> {
var component = NetworkComponent.get(world);
if (component != null) {
component.tick();
}
}));
// Sync the rocket interiors so the game doesn't die when people interact with rockets.
ServerTickEvents.END_SERVER_TICK.register((server) -> {
var world = server.getWorld(AMWorlds.ROCKET_INTERIORS);
if (world == null) return;
AMComponents.ROCKET_COMPONENTS.get(world).getRockets().forEach(Rocket::initStorage);
AMComponents.ROCKET_COMPONENTS.get(world).getRockets().forEach(Rocket::tick);
AMComponents.ROCKET_COMPONENTS.sync(world);
});
}
|
fix: include generated resources in source set
|
https://github.com/Mixinors/Astromine/commit/81db045c3b63a9a641374cff762528ec71c1ea66
| null | null |
src/main/java/com/github/mixinors/astromine/registry/common/AMEvents.java
| 0
|
java
| false
| null |
@SuppressLint("NotifyDataSetChanged")
private void updateRowsId(boolean notify) {
rowCount = 0;
cameraTypeHeaderRow = -1;
cameraTypeSelectorRow = -1;
cameraXOptimizeRow = -1;
cameraXFpsRow = -1;
cameraAdviseRow = -1;
suppressionRow = -1;
stickerSizeHeaderRow = rowCount++;
stickerSizeRow = rowCount++;
stickerSizeDividerRow = rowCount++;
if (CameraXUtilities.isCameraXSupported()) {
cameraTypeHeaderRow = rowCount++;
cameraTypeSelectorRow = rowCount++;
if (OwlConfig.cameraType == 1) {
cameraXOptimizeRow = rowCount++;
cameraXFpsRow = rowCount++;
}
cameraAdviseRow = rowCount++;
}
chatHeaderRow = rowCount++;
mediaSwipeByTapRow = rowCount++;
jumpChannelRow = rowCount++;
showGreetings = rowCount++;
playGifAsVideoRow = rowCount++;
hideKeyboardRow = rowCount++;
scrollableRow = rowCount++;
openArchiveOnPullRow = rowCount++;
chatDividerRow = rowCount++;
audioVideoHeaderRow = rowCount++;
if (AudioEnhance.isAvailable()) {
suppressionRow = rowCount++;
}
turnSoundOnVDKeyRow = rowCount++;
proximitySensorRow = rowCount++;
rearCameraStartingRow = rowCount++;
confirmSendRow = rowCount++;
confirmStickersGIFsRow = rowCount++;
audioVideoDividerRow = rowCount++;
foldersHeaderRow = rowCount++;
showFolderWhenForwardRow = rowCount++;
foldersDividerRow = rowCount++;
messageMenuHeaderRow = rowCount++;
showDeleteRow = rowCount++;
showCopyPhotoRow = rowCount++;
showNoQuoteForwardRow = rowCount++;
showAddToSMRow = rowCount++;
showRepeatRow = rowCount++;
showTranslateRow = rowCount++;
showReportRow = rowCount++;
showMessageDetailsRow = rowCount++;
if (listAdapter != null && notify) {
listAdapter.notifyDataSetChanged();
}
}
|
@SuppressLint("NotifyDataSetChanged")
private void updateRowsId(boolean notify) {
rowCount = 0;
cameraTypeHeaderRow = -1;
cameraTypeSelectorRow = -1;
cameraXOptimizeRow = -1;
cameraXFpsRow = -1;
cameraAdviseRow = -1;
suppressionRow = -1;
stickerSizeHeaderRow = rowCount++;
stickerSizeRow = rowCount++;
stickerSizeDividerRow = rowCount++;
if (CameraXUtilities.isCameraXSupported()) {
cameraTypeHeaderRow = rowCount++;
cameraTypeSelectorRow = rowCount++;
if (OwlConfig.cameraType == 1) {
cameraXOptimizeRow = rowCount++;
cameraXFpsRow = rowCount++;
}
cameraAdviseRow = rowCount++;
}
chatHeaderRow = rowCount++;
mediaSwipeByTapRow = rowCount++;
jumpChannelRow = rowCount++;
showGreetings = rowCount++;
playGifAsVideoRow = rowCount++;
hideKeyboardRow = rowCount++;
openArchiveOnPullRow = rowCount++;
chatDividerRow = rowCount++;
audioVideoHeaderRow = rowCount++;
if (AudioEnhance.isAvailable()) {
suppressionRow = rowCount++;
}
turnSoundOnVDKeyRow = rowCount++;
proximitySensorRow = rowCount++;
rearCameraStartingRow = rowCount++;
confirmSendRow = rowCount++;
confirmStickersGIFsRow = rowCount++;
audioVideoDividerRow = rowCount++;
foldersHeaderRow = rowCount++;
showFolderWhenForwardRow = rowCount++;
foldersDividerRow = rowCount++;
messageMenuHeaderRow = rowCount++;
showDeleteRow = rowCount++;
showCopyPhotoRow = rowCount++;
showNoQuoteForwardRow = rowCount++;
showAddToSMRow = rowCount++;
showRepeatRow = rowCount++;
showTranslateRow = rowCount++;
showReportRow = rowCount++;
showMessageDetailsRow = rowCount++;
if (listAdapter != null && notify) {
listAdapter.notifyDataSetChanged();
}
}
|
Fixed Some Crash & Removed Scrollable Chat Preview
|
https://github.com/OwlGramDev/OwlGram/commit/9797c903f77da2bccc5b2bd250a0a742b092fb90
| null | null |
TMessagesProj/src/main/java/it/owlgram/android/settings/OwlgramChatSettings.java
| 0
|
java
| false
|
2022-06-26T16:22:53Z
|
private void batchEditLyrics() {
LayoutInflater inflater = this.getLayoutInflater();
final View view = inflater.inflate(R.layout.dialog_adjust, null);
final TextView batchTitle = view.findViewById(R.id.title);
batchTitle.setText(R.string.batch_edit_prompt);
final TextView batchTimestamp = view.findViewById(R.id.content);
batchTimestamp.setText("+00:00.00");
final Timestamp timestamp = new Timestamp("00:00.00");
final Handler batchTimestampUpdater = new Handler();
final int[] longPressed = {0};
final boolean[] batchTimeNegative = {false}; // Have to use arrays because Java
final Runnable updateBatchTimestamp = new Runnable() {
@Override
public void run() {
/* `longPressed[0]` will be +1 if the '+' button is pressed */
/* `longPressed[0]` will be -1 if the '-' button is pressed */
/* `longPressed[0]` will be 0 if none of the buttons are pressed */
/* `batchTimeNegative[0]` will be true when the offset is negative; false otherwise */
if (longPressed[0] != 0) {
if (longPressed[0] == 1) {
if (batchTimeNegative[0]) {
timestamp.alterTimestamp(-timestampAdjustStep);
} else {
timestamp.alterTimestamp(timestampAdjustStep);
}
if (batchTimeNegative[0] && timestamp.toMilliseconds() <= 0) {
batchTimeNegative[0] = false;
}
} else {
if (!batchTimeNegative[0] && timestamp.toMilliseconds() - timestampAdjustStep < 0) {
batchTimeNegative[0] = true;
}
if (batchTimeNegative[0]) {
timestamp.alterTimestamp(timestampAdjustStep);
} else {
timestamp.alterTimestamp(-timestampAdjustStep);
}
}
if (!batchTimeNegative[0]) {
batchTimestamp.setText(
String.format(Locale.getDefault(), "+%s", timestamp.toString()));
} else {
batchTimestamp.setText(
String.format(Locale.getDefault(), "-%s", timestamp.toString()));
}
timestampUpdater.postDelayed(this, 50);
}
}
};
ImageButton increase = view.findViewById(R.id.increase_button);
if (isDarkTheme) {
increase.setImageDrawable(getDrawable(R.drawable.ic_add_light));
}
increase.setOnClickListener(v -> {
if (batchTimeNegative[0]) {
timestamp.alterTimestamp(-timestampAdjustStep);
} else {
timestamp.alterTimestamp(timestampAdjustStep);
}
if (batchTimeNegative[0] && timestamp.toMilliseconds() <= 0) {
batchTimeNegative[0] = false;
}
if (!batchTimeNegative[0]) {
batchTimestamp.setText(
String.format(Locale.getDefault(), "+%s", timestamp.toString()));
} else {
batchTimestamp.setText(
String.format(Locale.getDefault(), "-%s", timestamp.toString()));
}
longPressed[0] = 0;
});
increase.setOnLongClickListener(v -> {
if (longPressed[0] != 1) {
longPressed[0] = 1;
batchTimestampUpdater.post(updateBatchTimestamp);
}
return false;
});
ImageButton decrease = view.findViewById(R.id.decrease_button);
if (isDarkTheme) {
decrease.setImageDrawable(getDrawable(R.drawable.ic_minus_light));
}
decrease.setOnClickListener(v -> {
if (!batchTimeNegative[0] && timestamp.toMilliseconds() - timestampAdjustStep < 0) {
batchTimeNegative[0] = true;
}
if (batchTimeNegative[0]) {
timestamp.alterTimestamp(timestampAdjustStep);
} else {
timestamp.alterTimestamp(-timestampAdjustStep);
}
if (!batchTimeNegative[0]) {
batchTimestamp.setText(
String.format(Locale.getDefault(), "+%s", timestamp.toString()));
} else {
batchTimestamp.setText(
String.format(Locale.getDefault(), "-%s", timestamp.toString()));
}
longPressed[0] = 0;
});
decrease.setOnLongClickListener(v -> {
if (longPressed[0] != -1) {
longPressed[0] = -1;
batchTimestampUpdater.post(updateBatchTimestamp);
}
return false;
});
new AlertDialog.Builder(this)
.setView(view)
.setTitle(R.string.batch_edit)
.setPositiveButton(getString(R.string.adjust), (dialog1, which) -> {
changedData = true;
longPressed[0] = 0;
if (batchTimeNegative[0]) {
offsetTimestamps(-timestamp.toMilliseconds());
} else {
offsetTimestamps(timestamp.toMilliseconds());
}
if (actionMode != null) {
actionMode.finish();
}
actionMode = null;
})
.setNegativeButton(getString(R.string.cancel), (dialog12, which) -> longPressed[0] = 0)
.setCancelable(false)
.create()
.show();
}
|
private void batchEditLyrics() {
LayoutInflater inflater = this.getLayoutInflater();
final View view = inflater.inflate(R.layout.dialog_adjust, null);
final TextView batchTitle = view.findViewById(R.id.title);
batchTitle.setText(R.string.batch_edit_prompt);
final TextView batchTimestamp = view.findViewById(R.id.content);
batchTimestamp.setText("+00:00.00");
final Timestamp timestamp = new Timestamp("00:00.00");
final Handler batchTimestampUpdater = new Handler();
final int[] longPressed = {0};
final boolean[] batchTimeNegative = {false}; // Have to use arrays because Java
final Runnable updateBatchTimestamp = new Runnable() {
@Override
public void run() {
/* `longPressed[0]` will be +1 if the '+' button is pressed */
/* `longPressed[0]` will be -1 if the '-' button is pressed */
/* `longPressed[0]` will be 0 if none of the buttons are pressed */
/* `batchTimeNegative[0]` will be true when the offset is negative; false otherwise */
if (longPressed[0] != 0) {
if (longPressed[0] == 1) {
if (batchTimeNegative[0]) {
timestamp.alterTimestamp(-timestampAdjustStep);
} else {
timestamp.alterTimestamp(timestampAdjustStep);
}
if (batchTimeNegative[0] && timestamp.toMilliseconds() <= 0) {
batchTimeNegative[0] = false;
}
} else {
if (!batchTimeNegative[0] && timestamp.toMilliseconds() - timestampAdjustStep < 0) {
batchTimeNegative[0] = true;
}
if (batchTimeNegative[0]) {
timestamp.alterTimestamp(timestampAdjustStep);
} else {
timestamp.alterTimestamp(-timestampAdjustStep);
}
}
if (!batchTimeNegative[0]) {
batchTimestamp.setText(
String.format(Locale.getDefault(), "+%s", timestamp.toString()));
} else {
batchTimestamp.setText(
String.format(Locale.getDefault(), "-%s", timestamp.toString()));
}
batchTimestampUpdater.postDelayed(this, 50);
}
}
};
ImageButton increase = view.findViewById(R.id.increase_button);
if (isDarkTheme) {
increase.setImageDrawable(getDrawable(R.drawable.ic_add_light));
}
increase.setOnClickListener(v -> {
if (batchTimeNegative[0]) {
timestamp.alterTimestamp(-timestampAdjustStep);
} else {
timestamp.alterTimestamp(timestampAdjustStep);
}
if (batchTimeNegative[0] && timestamp.toMilliseconds() <= 0) {
batchTimeNegative[0] = false;
}
if (!batchTimeNegative[0]) {
batchTimestamp.setText(
String.format(Locale.getDefault(), "+%s", timestamp.toString()));
} else {
batchTimestamp.setText(
String.format(Locale.getDefault(), "-%s", timestamp.toString()));
}
longPressed[0] = 0;
});
increase.setOnLongClickListener(v -> {
if (longPressed[0] != 1) {
longPressed[0] = 1;
batchTimestampUpdater.post(updateBatchTimestamp);
}
return false;
});
ImageButton decrease = view.findViewById(R.id.decrease_button);
if (isDarkTheme) {
decrease.setImageDrawable(getDrawable(R.drawable.ic_minus_light));
}
decrease.setOnClickListener(v -> {
if (!batchTimeNegative[0] && timestamp.toMilliseconds() - timestampAdjustStep < 0) {
batchTimeNegative[0] = true;
}
if (batchTimeNegative[0]) {
timestamp.alterTimestamp(timestampAdjustStep);
} else {
timestamp.alterTimestamp(-timestampAdjustStep);
}
if (!batchTimeNegative[0]) {
batchTimestamp.setText(
String.format(Locale.getDefault(), "+%s", timestamp.toString()));
} else {
batchTimestamp.setText(
String.format(Locale.getDefault(), "-%s", timestamp.toString()));
}
longPressed[0] = 0;
});
decrease.setOnLongClickListener(v -> {
if (longPressed[0] != -1) {
longPressed[0] = -1;
batchTimestampUpdater.post(updateBatchTimestamp);
}
return false;
});
new AlertDialog.Builder(this)
.setView(view)
.setTitle(R.string.batch_edit)
.setPositiveButton(getString(R.string.adjust), (dialog1, which) -> {
changedData = true;
longPressed[0] = 0;
if (batchTimeNegative[0]) {
offsetTimestamps(-timestamp.toMilliseconds());
} else {
offsetTimestamps(timestamp.toMilliseconds());
}
if (actionMode != null) {
actionMode.finish();
}
actionMode = null;
})
.setNegativeButton(getString(R.string.cancel), (dialog12, which) -> longPressed[0] = 0)
.setCancelable(false)
.create()
.show();
}
|
Crash fixes
I can't reproduce these issues but I got some crash reports on them
|
https://github.com/Spikatrix/LRC-Editor/commit/53cec5920f83a88d33ec7759c405cbc37467018b
| null | null |
app/src/main/java/com/cg/lrceditor/EditorActivity.java
| 0
|
java
| false
|
2021-02-25T16:29:28Z
|
@Override
public boolean canUse() {
return mob.canSummon() && !done;
}
|
@Override
public boolean canUse() {
return mob.canSummon();
}
|
Dynamic summoning, ram attack
|
https://github.com/baileyholl/Ars-Nouveau/commit/69794838e7700e1d8246134bcacfa688dd40fc8b
| null | null |
src/main/java/com/hollingsworth/arsnouveau/common/entity/goal/chimera/ChimeraSummonGoal.java
| 0
|
java
| false
|
2021-07-16T03:00:18Z
|
function Q(e){return"undefined"==typeof BigInt?ee:e}
|
function Q(e){var t=e.return;t&&t.call(e)}
|
base64 encode encrypted
Signed-off-by: Louis Chemineau <louis@chmn.me>
|
https://github.com/nextcloud/end_to_end_encryption/commit/d120dfa76ca0b7b66591589e7333ea853159e1c3
|
CVE-2023-35173
|
['CWE-284', 'NVD-CWE-Other']
|
js/end_to_end_encryption-filedrop.js
| 0
|
js
| false
|
2023-03-30T11:05:29Z
|
public void printCandidates(String type){
if("payloads".equals(type) && isExploit && exploit != null){
Class<?> clazz = exploit.getClass();
if(payload != null){
Logger.normal("Current Payload: "+ColorStyle.makeWordRed(payload.getClass().getSimpleName()));
}else{
Logger.normal("Current Payload: "+ColorStyle.makeWordRed("null"));
}
Printer.printCandidates("payloads", clazz);
}
if("bullets".equals(type) && payload != null){
Class<?> clazz = payload.getClass();
if(bullet != null){
Logger.normal("Current Bullet: "+ColorStyle.makeWordRed(bullet.getClass().getSimpleName()));
}else{
Logger.normal("Current Bullet: "+ColorStyle.makeWordRed("null"));
}
Printer.printCandidates("bullets", clazz);
}
}
|
public void printCandidates(String type){
if("payloads".equals(type) && isExploit && exploit != null){
Class<?> clazz = exploit.getClass();
if(payload != null){
Logger.normal("Current Payload: "+ColorStyle.makeWordRed(payload.getClass().getSimpleName()));
}else{
Logger.normal("Current Payload: "+ColorStyle.makeWordRed("null"));
}
Printer.printCandidates("payloads", clazz, true, console.payloads);
}
if("bullets".equals(type) && payload != null){
Class<?> clazz = payload.getClass();
if(bullet != null){
Logger.normal("Current Bullet: "+ColorStyle.makeWordRed(bullet.getClass().getSimpleName()));
}else{
Logger.normal("Current Bullet: "+ColorStyle.makeWordRed("null"));
}
Printer.printCandidates("bullets", clazz, true, console.bullets);
}
}
|
add some exploits' script
|
https://github.com/wh1t3p1g/ysomap/commit/5d9b4bf9baec7caa3d31e25ca1b90de93408a9a0
| null | null |
cli/src/main/java/ysomap/cli/Session.java
| 0
|
java
| false
|
2021-06-16T15:18:32Z
|
static void finish_object(struct object *obj,
struct strbuf *path, const char *name,
void *cb_data)
{
struct rev_list_info *info = cb_data;
if (obj->type == OBJ_BLOB && !has_object_file(&obj->oid))
die("missing blob object '%s'", oid_to_hex(&obj->oid));
if (info->revs->verify_objects && !obj->parsed && obj->type != OBJ_COMMIT)
parse_object(obj->oid.hash);
}
|
static void finish_object(struct object *obj, const char *name, void *cb_data)
{
struct rev_list_info *info = cb_data;
if (obj->type == OBJ_BLOB && !has_object_file(&obj->oid))
die("missing blob object '%s'", oid_to_hex(&obj->oid));
if (info->revs->verify_objects && !obj->parsed && obj->type != OBJ_COMMIT)
parse_object(obj->oid.hash);
}
|
list-objects: pass full pathname to callbacks
When we find a blob at "a/b/c", we currently pass this to
our show_object_fn callbacks as two components: "a/b/" and
"c". Callbacks which want the full value then call
path_name(), which concatenates the two. But this is an
inefficient interface; the path is a strbuf, and we could
simply append "c" to it temporarily, then roll back the
length, without creating a new copy.
So we could improve this by teaching the callsites of
path_name() this trick (and there are only 3). But we can
also notice that no callback actually cares about the
broken-down representation, and simply pass each callback
the full path "a/b/c" as a string. The callback code becomes
even simpler, then, as we do not have to worry about freeing
an allocated buffer, nor rolling back our modification to
the strbuf.
This is theoretically less efficient, as some callbacks
would not bother to format the final path component. But in
practice this is not measurable. Since we use the same
strbuf over and over, our work to grow it is amortized, and
we really only pay to memcpy a few bytes.
Signed-off-by: Jeff King <peff@peff.net>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
|
https://github.com/git/git/commit/de1e67d0703894cb6ea782e36abb63976ab07e60
| null | null |
builtin/rev-list.c
| 0
|
c
| false
| null |
@Override
public void onInitialize() {
Registry.register(Registry.ITEM, new Identifier("bettercombat", "claymore"), CLAYMORE);
ClientLifecycleEvents.CLIENT_STARTED.register((client) -> {
loadAnimations("slash");
});
}
|
@Override
public void onInitialize() {
Registry.register(Registry.ITEM, new Identifier("bettercombat", "claymore"), CLAYMORE);
WeaponRegistry.register(new Identifier("bettercombat", "claymore"), new MeleeWeaponAttributes());
}
|
Add attack speed support
|
https://github.com/ZsoltMolnarrr/BetterCombat/commit/5bafbaa6cd2da60b7a377be164e20c4bb5713368
| null | null |
src/main/java/net/bettercombat/BetterCombat.java
| 0
|
java
| false
|
2022-05-10T20:50:54Z
|
private ActionDumpWriter createActionDumpWriter(CommandEnvironment env)
throws InvalidPackagePathSymlinkException, ActionDumpFileCreationException {
OptionsParsingResult parsingResult = env.getOptions();
BuildEventProtocolOptions bepOptions =
Preconditions.checkNotNull(parsingResult.getOptions(BuildEventProtocolOptions.class));
ExecutionGraphOptions executionGraphOptions =
Preconditions.checkNotNull(parsingResult.getOptions(ExecutionGraphOptions.class));
if (bepOptions.streamingLogFileUploads) {
return new StreamingActionDumpWriter(
env.getRuntime().getBugReporter(),
env.getOptions().getOptions(LocalExecutionOptions.class).localLockfreeOutput,
newUploader(env, bepOptions).startUpload(LocalFileType.PERFORMANCE_LOG, null),
env.getCommandId(),
executionGraphOptions.depType,
executionGraphOptions.queueSize);
}
Path actionGraphFile =
env.getWorkingDirectory().getRelative(executionGraphOptions.executionGraphLogFile);
try {
return new FilesystemActionDumpWriter(
env.getRuntime().getBugReporter(),
env.getOptions().getOptions(LocalExecutionOptions.class).localLockfreeOutput,
actionGraphFile,
env.getCommandId(),
executionGraphOptions.depType,
executionGraphOptions.queueSize);
} catch (IOException e) {
throw new ActionDumpFileCreationException(actionGraphFile, e);
}
}
|
private ActionDumpWriter createActionDumpWriter(CommandEnvironment env)
throws InvalidPackagePathSymlinkException, ActionDumpFileCreationException {
OptionsParsingResult parsingResult = env.getOptions();
BuildEventProtocolOptions bepOptions =
checkNotNull(parsingResult.getOptions(BuildEventProtocolOptions.class));
ExecutionGraphOptions executionGraphOptions =
checkNotNull(parsingResult.getOptions(ExecutionGraphOptions.class));
if (bepOptions.streamingLogFileUploads) {
return new StreamingActionDumpWriter(
env.getRuntime().getBugReporter(),
env.getOptions().getOptions(LocalExecutionOptions.class).localLockfreeOutput,
newUploader(env, bepOptions).startUpload(LocalFileType.PERFORMANCE_LOG, null),
env.getCommandId(),
executionGraphOptions.depType,
executionGraphOptions.queueSize);
}
Path actionGraphFile =
env.getWorkingDirectory().getRelative(executionGraphOptions.executionGraphLogFile);
try {
return new FilesystemActionDumpWriter(
env.getRuntime().getBugReporter(),
env.getOptions().getOptions(LocalExecutionOptions.class).localLockfreeOutput,
actionGraphFile,
env.getCommandId(),
executionGraphOptions.depType,
executionGraphOptions.queueSize);
} catch (IOException e) {
throw new ActionDumpFileCreationException(actionGraphFile, e);
}
}
|
Add shared actions to the execution graph.
Currently, only the action that wins the execution race is represented in the execution graph. Dependency edges on actions which lose the shared action execution race are not represented. This could result in an underestimated critical path.
With this change, shared actions all share the same execution graph node. Artifacts from the executed action are guaranteed to already exist in the execution graph because `ActionCompletionEvent` is posted prior to construction of `ActionStepOrResult.Finished`, which is needed for the shared action to observe it as done. Nevertheless, I used `logUnexpected` to avoid a crash if this assumption does not hold.
PiperOrigin-RevId: 506140972
Change-Id: Ia2d5e48c524a1afab198d3c61f21a5d893aa1cee
|
https://github.com/bazelbuild/bazel/commit/2036a0f0fa093d6e48fc02431e28734907cfca63
| null | null |
src/main/java/com/google/devtools/build/lib/runtime/ExecutionGraphModule.java
| 0
|
java
| false
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.