identifier
stringlengths
42
383
collection
stringclasses
1 value
open_type
stringclasses
1 value
license
stringlengths
0
1.81k
date
float64
1.99k
2.02k
title
stringlengths
0
100
creator
stringlengths
1
39
language
stringclasses
157 values
language_type
stringclasses
2 values
word_count
int64
1
20k
token_count
int64
4
1.32M
text
stringlengths
5
1.53M
__index_level_0__
int64
0
57.5k
https://github.com/garrynigel/Priam/blob/master/priam/src/main/java/com/netflix/priam/config/PriamConfiguration.java
Github Open Source
Open Source
Apache-2.0
null
Priam
garrynigel
Java
Code
1,857
6,883
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.priam.config; import com.fasterxml.jackson.annotation.JsonIgnore; import com.google.inject.Inject; import com.google.inject.Singleton; import com.netflix.priam.configSource.IConfigSource; import com.netflix.priam.identity.config.InstanceInfo; import com.netflix.priam.scheduler.UnsupportedTypeException; import com.netflix.priam.tuner.GCType; import java.io.File; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Singleton public class PriamConfiguration implements IConfiguration { public static final String PRIAM_PRE = "priam"; private final IConfigSource config; private static final Logger logger = LoggerFactory.getLogger(PriamConfiguration.class); @JsonIgnore private InstanceInfo instanceInfo; @Inject public PriamConfiguration(IConfigSource config, InstanceInfo instanceInfo) { this.config = config; this.instanceInfo = instanceInfo; } @Override public void initialize() { this.config.initialize(instanceInfo.getAutoScalingGroup(), instanceInfo.getRegion()); } @Override public String getCassandraBaseDirectory() { return config.get(PRIAM_PRE + ".cass.base", "/var/lib/cassandra"); } @Override public String getCassStartupScript() { return config.get(PRIAM_PRE + ".cass.startscript", "/etc/init.d/cassandra start"); } @Override public String getCassStopScript() { return config.get(PRIAM_PRE + ".cass.stopscript", "/etc/init.d/cassandra stop"); } @Override public int getGracefulDrainHealthWaitSeconds() { return -1; } @Override public int getRemediateDeadCassandraRate() { return config.get( PRIAM_PRE + ".remediate.dead.cassandra.rate", 3600); // Default to once per hour } @Override public String getCassHome() { return config.get(PRIAM_PRE + ".cass.home", "/etc/cassandra"); } @Override public String getBackupLocation() { return config.get(PRIAM_PRE + ".s3.base_dir", "backup"); } @Override public String getBackupPrefix() { return config.get(PRIAM_PRE + ".s3.bucket", "cassandra-archive"); } @Override public int getBackupRetentionDays() { return config.get(PRIAM_PRE + ".backup.retention", 0); } @Override public List<String> getBackupRacs() { return config.getList(PRIAM_PRE + ".backup.racs"); } @Override public String getRestorePrefix() { return config.get(PRIAM_PRE + ".restore.prefix"); } @Override public String getDataFileLocation() { return config.get(PRIAM_PRE + ".data.location", getCassandraBaseDirectory() + "/data"); } @Override public String getLogDirLocation() { return config.get(PRIAM_PRE + ".logs.location", getCassandraBaseDirectory() + "/logs"); } @Override public String getCacheLocation() { return config.get( PRIAM_PRE + ".cache.location", getCassandraBaseDirectory() + "/saved_caches"); } @Override public String getCommitLogLocation() { return config.get( PRIAM_PRE + ".commitlog.location", getCassandraBaseDirectory() + "/commitlog"); } @Override public String getBackupCommitLogLocation() { return config.get(PRIAM_PRE + ".backup.commitlog.location", ""); } @Override public long getBackupChunkSize() { long size = config.get(PRIAM_PRE + ".backup.chunksizemb", 10); return size * 1024 * 1024L; } @Override public int getJmxPort() { return config.get(PRIAM_PRE + ".jmx.port", 7199); } @Override public String getJmxUsername() { return config.get(PRIAM_PRE + ".jmx.username", ""); } @Override public String getJmxPassword() { return config.get(PRIAM_PRE + ".jmx.password", ""); } /** @return Enables Remote JMX connections n C* */ @Override public boolean enableRemoteJMX() { return config.get(PRIAM_PRE + ".jmx.remote.enable", false); } public int getNativeTransportPort() { return config.get(PRIAM_PRE + ".nativeTransport.port", 9042); } @Override public int getThriftPort() { return config.get(PRIAM_PRE + ".thrift.port", 9160); } @Override public int getStoragePort() { return config.get(PRIAM_PRE + ".storage.port", 7000); } @Override public int getSSLStoragePort() { return config.get(PRIAM_PRE + ".ssl.storage.port", 7001); } @Override public String getSnitch() { return config.get(PRIAM_PRE + ".endpoint_snitch", "org.apache.cassandra.locator.Ec2Snitch"); } @Override public String getAppName() { return config.get(PRIAM_PRE + ".clustername", "cass_cluster"); } @Override public List<String> getRacs() { return config.getList(PRIAM_PRE + ".zones.available", instanceInfo.getDefaultRacks()); } @Override public String getHeapSize() { return config.get((PRIAM_PRE + ".heap.size.") + instanceInfo.getInstanceType(), "8G"); } @Override public String getHeapNewSize() { return config.get( (PRIAM_PRE + ".heap.newgen.size.") + instanceInfo.getInstanceType(), "2G"); } @Override public String getMaxDirectMemory() { return config.get( (PRIAM_PRE + ".direct.memory.size.") + instanceInfo.getInstanceType(), "50G"); } @Override public String getBackupCronExpression() { return config.get(PRIAM_PRE + ".backup.cron", "0 0 12 1/1 * ? *"); // Backup daily at 12 } @Override public GCType getGCType() throws UnsupportedTypeException { String gcType = config.get(PRIAM_PRE + ".gc.type", GCType.CMS.getGcType()); return GCType.lookup(gcType); } @Override public String getJVMExcludeSet() { return config.get(PRIAM_PRE + ".jvm.options.exclude"); } @Override public String getJVMUpsertSet() { return config.get(PRIAM_PRE + ".jvm.options.upsert"); } @Override public String getFlushCronExpression() { return config.get(PRIAM_PRE + ".flush.cron", "-1"); } @Override public String getCompactionCronExpression() { return config.get(PRIAM_PRE + ".compaction.cron", "-1"); } @Override public String getCompactionIncludeCFList() { return config.get(PRIAM_PRE + ".compaction.cf.include"); } @Override public String getCompactionExcludeCFList() { return config.get(PRIAM_PRE + ".compaction.cf.exclude"); } @Override public String getSnapshotIncludeCFList() { return config.get(PRIAM_PRE + ".snapshot.cf.include"); } @Override public String getSnapshotExcludeCFList() { return config.get(PRIAM_PRE + ".snapshot.cf.exclude"); } @Override public String getIncrementalIncludeCFList() { return config.get(PRIAM_PRE + ".incremental.cf.include"); } @Override public String getIncrementalExcludeCFList() { return config.get(PRIAM_PRE + ".incremental.cf.exclude"); } @Override public String getRestoreIncludeCFList() { return config.get(PRIAM_PRE + ".restore.cf.include"); } @Override public String getRestoreExcludeCFList() { return config.get(PRIAM_PRE + ".restore.cf.exclude"); } @Override public String getRestoreSnapshot() { return config.get(PRIAM_PRE + ".restore.snapshot", ""); } @Override public boolean isRestoreEncrypted() { return config.get(PRIAM_PRE + ".encrypted.restore.enabled", false); } @Override public String getSDBInstanceIdentityRegion() { return config.get(PRIAM_PRE + ".sdb.instanceIdentity.region", "us-east-1"); } @Override public boolean isMultiDC() { return config.get(PRIAM_PRE + ".multiregion.enable", false); } @Override public int getBackupThreads() { return config.get(PRIAM_PRE + ".backup.threads", 2); } @Override public int getRestoreThreads() { return config.get(PRIAM_PRE + ".restore.threads", 8); } @Override public boolean isRestoreClosestToken() { return config.get(PRIAM_PRE + ".restore.closesttoken", false); } @Override public String getSiblingASGNames() { return config.get(PRIAM_PRE + ".az.sibling.asgnames", ","); } @Override public String getACLGroupName() { return config.get(PRIAM_PRE + ".acl.groupname", this.getAppName()); } @Override public boolean isIncrementalBackupEnabled() { return config.get(PRIAM_PRE + ".backup.incremental.enable", true); } @Override public int getUploadThrottle() { return config.get(PRIAM_PRE + ".upload.throttle", -1); } @Override public int getRemoteFileSystemObjectExistsThrottle() { return config.get(PRIAM_PRE + ".remoteFileSystemObjectExistThrottle", -1); } @Override public boolean isLocalBootstrapEnabled() { return config.get(PRIAM_PRE + ".localbootstrap.enable", false); } @Override public int getCompactionThroughput() { return config.get(PRIAM_PRE + ".compaction.throughput", 8); } @Override public int getMaxHintWindowInMS() { return config.get(PRIAM_PRE + ".hint.window", 10800000); } public int getHintedHandoffThrottleKb() { return config.get(PRIAM_PRE + ".hints.throttleKb", 1024); } @Override public String getBootClusterName() { return config.get(PRIAM_PRE + ".bootcluster", ""); } @Override public String getSeedProviderName() { return config.get( PRIAM_PRE + ".seed.provider", "com.netflix.priam.cassandra.extensions.NFSeedProvider"); } public double getMemtableCleanupThreshold() { return config.get(PRIAM_PRE + ".memtable.cleanup.threshold", 0.11); } @Override public int getStreamingThroughputMB() { return config.get(PRIAM_PRE + ".streaming.throughput.mb", 400); } public String getPartitioner() { return config.get(PRIAM_PRE + ".partitioner", "org.apache.cassandra.dht.RandomPartitioner"); } public String getKeyCacheSizeInMB() { return config.get(PRIAM_PRE + ".keyCache.size"); } public String getKeyCacheKeysToSave() { return config.get(PRIAM_PRE + ".keyCache.count"); } public String getRowCacheSizeInMB() { return config.get(PRIAM_PRE + ".rowCache.size"); } public String getRowCacheKeysToSave() { return config.get(PRIAM_PRE + ".rowCache.count"); } @Override public String getCassProcessName() { return config.get(PRIAM_PRE + ".cass.process", "CassandraDaemon"); } public String getYamlLocation() { return config.get(PRIAM_PRE + ".yamlLocation", getCassHome() + "/conf/cassandra.yaml"); } @Override public boolean supportsTuningJVMOptionsFile() { return config.get(PRIAM_PRE + ".jvm.options.supported", false); } @Override public String getJVMOptionsFileLocation() { return config.get(PRIAM_PRE + ".jvm.options.location", getCassHome() + "/conf/jvm.options"); } public String getAuthenticator() { return config.get( PRIAM_PRE + ".authenticator", "org.apache.cassandra.auth.AllowAllAuthenticator"); } public String getAuthorizer() { return config.get( PRIAM_PRE + ".authorizer", "org.apache.cassandra.auth.AllowAllAuthorizer"); } @Override public boolean doesCassandraStartManually() { return config.get(PRIAM_PRE + ".cass.manual.start.enable", false); } public String getInternodeCompression() { return config.get(PRIAM_PRE + ".internodeCompression", "all"); } @Override public boolean isBackingUpCommitLogs() { return config.get(PRIAM_PRE + ".clbackup.enabled", false); } @Override public String getCommitLogBackupPropsFile() { return config.get( PRIAM_PRE + ".clbackup.propsfile", getCassHome() + "/conf/commitlog_archiving.properties"); } @Override public String getCommitLogBackupArchiveCmd() { return config.get( PRIAM_PRE + ".clbackup.archiveCmd", "/bin/ln %path /mnt/data/backup/%name"); } @Override public String getCommitLogBackupRestoreCmd() { return config.get(PRIAM_PRE + ".clbackup.restoreCmd", "/bin/mv %from %to"); } @Override public String getCommitLogBackupRestoreFromDirs() { return config.get(PRIAM_PRE + ".clbackup.restoreDirs", "/mnt/data/backup/commitlog/"); } @Override public String getCommitLogBackupRestorePointInTime() { return config.get(PRIAM_PRE + ".clbackup.restoreTime", ""); } @Override public int maxCommitLogsRestore() { return config.get(PRIAM_PRE + ".clrestore.max", 10); } public boolean isClientSslEnabled() { return config.get(PRIAM_PRE + ".client.sslEnabled", false); } public String getInternodeEncryption() { return config.get(PRIAM_PRE + ".internodeEncryption", "none"); } public boolean isDynamicSnitchEnabled() { return config.get(PRIAM_PRE + ".dsnitchEnabled", true); } public boolean isThriftEnabled() { return config.get(PRIAM_PRE + ".thrift.enabled", true); } public boolean isNativeTransportEnabled() { return config.get(PRIAM_PRE + ".nativeTransport.enabled", false); } public int getConcurrentReadsCnt() { return config.get(PRIAM_PRE + ".concurrentReads", 32); } public int getConcurrentWritesCnt() { return config.get(PRIAM_PRE + ".concurrentWrites", 32); } public int getConcurrentCompactorsCnt() { int cpus = Runtime.getRuntime().availableProcessors(); return config.get(PRIAM_PRE + ".concurrentCompactors", cpus); } public String getRpcServerType() { return config.get(PRIAM_PRE + ".rpc.server.type", "hsha"); } public int getRpcMinThreads() { return config.get(PRIAM_PRE + ".rpc.min.threads", 16); } public int getRpcMaxThreads() { return config.get(PRIAM_PRE + ".rpc.max.threads", 2048); } @Override public int getCompactionLargePartitionWarnThresholdInMB() { return config.get(PRIAM_PRE + ".compaction.large.partition.warn.threshold", 100); } public String getExtraConfigParams() { return config.get(PRIAM_PRE + ".extra.params"); } @Override public Map<String, String> getExtraEnvParams() { String envParams = config.get(PRIAM_PRE + ".extra.env.params"); if (envParams == null) { logger.info("getExtraEnvParams: No extra env params"); return null; } Map<String, String> extraEnvParamsMap = new HashMap<>(); String[] pairs = envParams.split(","); logger.info("getExtraEnvParams: Extra cass params. From config :{}", envParams); for (String pair1 : pairs) { String[] pair = pair1.split("="); if (pair.length > 1) { String priamKey = pair[0]; String cassKey = pair[1]; String cassVal = config.get(priamKey); logger.info( "getExtraEnvParams: Start-up/ env params: Priamkey[{}], CassStartupKey[{}], Val[{}]", priamKey, cassKey, cassVal); if (!StringUtils.isBlank(cassKey) && !StringUtils.isBlank(cassVal)) { extraEnvParamsMap.put(cassKey, cassVal); } } } return extraEnvParamsMap; } public String getCassYamlVal(String priamKey) { return config.get(priamKey); } public boolean getAutoBoostrap() { return config.get(PRIAM_PRE + ".auto.bootstrap", true); } @Override public boolean isCreateNewTokenEnable() { return config.get(PRIAM_PRE + ".create.new.token.enable", true); } @Override public String getPrivateKeyLocation() { return config.get(PRIAM_PRE + ".private.key.location"); } @Override public String getRestoreSourceType() { return config.get(PRIAM_PRE + ".restore.source.type"); } @Override public boolean isEncryptBackupEnabled() { return config.get(PRIAM_PRE + ".encrypted.backup.enabled", false); } @Override public String getAWSRoleAssumptionArn() { return config.get(PRIAM_PRE + ".roleassumption.arn"); } @Override public String getClassicEC2RoleAssumptionArn() { return config.get(PRIAM_PRE + ".ec2.roleassumption.arn"); } @Override public String getVpcEC2RoleAssumptionArn() { return config.get(PRIAM_PRE + ".vpc.roleassumption.arn"); } @Override public boolean isDualAccount() { return config.get(PRIAM_PRE + ".roleassumption.dualaccount", false); } @Override public String getGcsServiceAccountId() { return config.get(PRIAM_PRE + ".gcs.service.acct.id"); } @Override public String getGcsServiceAccountPrivateKeyLoc() { return config.get( PRIAM_PRE + ".gcs.service.acct.private.key", "/apps/tomcat/conf/gcsentryptedkey.p12"); } @Override public String getPgpPasswordPhrase() { return config.get(PRIAM_PRE + ".pgp.password.phrase"); } @Override public String getPgpPublicKeyLoc() { return config.get(PRIAM_PRE + ".pgp.pubkey.file.location"); } @Override public boolean enableAsyncIncremental() { return config.get(PRIAM_PRE + ".async.incremental", false); } @Override public boolean enableAsyncSnapshot() { return config.get(PRIAM_PRE + ".async.snapshot", false); } @Override public int getBackupQueueSize() { return config.get(PRIAM_PRE + ".backup.queue.size", 100000); } @Override public int getDownloadQueueSize() { return config.get(PRIAM_PRE + ".download.queue.size", 100000); } @Override public long getUploadTimeout() { return config.get(PRIAM_PRE + ".upload.timeout", (2 * 60 * 60 * 1000L)); } public long getDownloadTimeout() { return config.get(PRIAM_PRE + ".download.timeout", (10 * 60 * 60 * 1000L)); } @Override public int getTombstoneWarnThreshold() { return config.get(PRIAM_PRE + ".tombstone.warning.threshold", 1000); } @Override public int getTombstoneFailureThreshold() { return config.get(PRIAM_PRE + ".tombstone.failure.threshold", 100000); } @Override public int getStreamingSocketTimeoutInMS() { return config.get(PRIAM_PRE + ".streaming.socket.timeout.ms", 86400000); } @Override public String getFlushKeyspaces() { return config.get(PRIAM_PRE + ".flush.keyspaces"); } @Override public String getBackupStatusFileLoc() { return config.get( PRIAM_PRE + ".backup.status.location", getDataFileLocation() + File.separator + "backup.status"); } @Override public boolean useSudo() { return config.get(PRIAM_PRE + ".cass.usesudo", true); } @Override public boolean enableBackupNotification() { return config.get(PRIAM_PRE + ".enableBackupNotification", true); } @Override public String getBackupNotificationTopicArn() { return config.get(PRIAM_PRE + ".backup.notification.topic.arn", ""); } @Override public boolean isPostRestoreHookEnabled() { return config.get(PRIAM_PRE + ".postrestorehook.enabled", false); } @Override public String getPostRestoreHook() { return config.get(PRIAM_PRE + ".postrestorehook"); } @Override public String getPostRestoreHookHeartbeatFileName() { return config.get( PRIAM_PRE + ".postrestorehook.heartbeat.filename", getDataFileLocation() + File.separator + "postrestorehook_heartbeat"); } @Override public String getPostRestoreHookDoneFileName() { return config.get( PRIAM_PRE + ".postrestorehook.done.filename", getDataFileLocation() + File.separator + "postrestorehook_done"); } @Override public int getPostRestoreHookTimeOutInDays() { return config.get(PRIAM_PRE + ".postrestorehook.timeout.in.days", 2); } @Override public int getPostRestoreHookHeartBeatTimeoutInMs() { return config.get(PRIAM_PRE + ".postrestorehook.heartbeat.timeout", 120000); } @Override public int getPostRestoreHookHeartbeatCheckFrequencyInMs() { return config.get(PRIAM_PRE + ".postrestorehook.heartbeat.check.frequency", 120000); } @Override public String getProperty(String key, String defaultValue) { return config.get(key, defaultValue); } @Override public String getMergedConfigurationCronExpression() { // Every minute on the top of the minute. return config.get(PRIAM_PRE + ".configMerge.cron", "0 * * * * ? *"); } @Override public int getGracePeriodDaysForCompaction() { return config.get(PRIAM_PRE + ".gracePeriodDaysForCompaction", 5); } @Override public int getForgottenFileGracePeriodDaysForRead() { return config.get(PRIAM_PRE + ".forgottenFileGracePeriodDaysForRead", 3); } @Override public boolean isForgottenFileMoveEnabled() { return config.get(PRIAM_PRE + ".forgottenFileMoveEnabled", false); } }
24,503
https://github.com/gabzon/onlinedance/blob/master/resources/views/welcome.blade.php
Github Open Source
Open Source
MIT
null
onlinedance
gabzon
PHP
Code
88
440
<x-guest-layout> <x-slot name="pixel"> {{ $settings->fb_pixel }} </x-slot> <div class="py-12"> <div class="max-w-7xl mx-auto sm:px-6 lg:px-8"> <div class="bg-white overflow-hidden shadow-xl sm:rounded-lg"> <x-welcome.landing /> </div> </div> </div> <div class="py-12"> <div class="max-w-7xl mx-auto sm:px-6 lg:px-8"> <div id="styles" class="bg-white overflow-hidden shadow-xl sm:rounded-lg"> <x-welcome.styles /> </div> </div> </div> @if (config('services.school.name') == 'dancefloor') <div class="pt-12"> <x-welcome.testimonials /> </div> @endif @if (config('services.school.name') != 'dancefloor') <div class="py-12"> <div class="max-w-7xl mx-auto sm:px-6 lg:px-8"> <div id="instructors" class="bg-white overflow-hidden shadow-xl sm:rounded-lg"> <x-partials.instructors /> </div> </div> </div> @endif <div class=""> <div id="pricing" class="bg-white overflow-hidden shadow-xl sm:rounded-lg"> <x-welcome.pricing /> </div> </div> </x-guest-layout>
16,747
https://github.com/three-lovely-idiots/dream/blob/master/myItems/application/common/validate/ProductPosterValidate.php
Github Open Source
Open Source
Apache-2.0
2,019
dream
three-lovely-idiots
PHP
Code
38
112
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2019/4/10 0010 * Time: 下午 1:26 */ namespace app\common\validate; class ProductPosterValidate extends BaseValidate { protected $rule = [ 'id'=>'require',//产品的id ]; protected $message = [ 'id'=>'id必须存在', ]; }
38,286
https://github.com/mtoto6469/vinton/blob/master/frontend/views/site/changepasword.php
Github Open Source
Open Source
BSD-3-Clause
null
vinton
mtoto6469
PHP
Code
129
580
<?php /* @var $this yii\web\View */ /* @var $form yii\bootstrap\ActiveForm */ /* @var $model \common\models\LoginForm */ use yii\helpers\Html; use yii\bootstrap\ActiveForm; $sesssion = Yii::$app->session; if (!$sesssion->isActive) { $sesssion->open(); } if (isset($_SESSION['error'])){ if( $_SESSION['error']!= null){ echo'<div class="alert alert-danger">'. $_SESSION['error'].'</div>'; }$_SESSION['error']= null; } $this->title = 'تغییر رمز'; $this->params['breadcrumbs'][] = $this->title; ?> <div style="padding: 5% 15%; "> <div class="site-login"> <p> کلمه عبور فقط می تواند شامل عدد و کاراکتر باشد </p> <div class="row"> <div class="col-lg-6 col-lg-offset-3 styll"> <h1 style="text-align: right;padding-bottom: 20px;"><?= Html::encode($this->title) ?></h1> <?php $form = ActiveForm::begin(); ?> <?= $form->field($model,'username',['inputOptions'=>[ 'placeholder'=>'username' ]])->textInput() ?> <?= $form->field($model,'oldpass',['inputOptions'=>[ 'placeholder'=>'Old Password' ]])->passwordInput() ?> <?= $form->field($model,'newpass',['inputOptions'=>[ 'placeholder'=>'New Password' ]])->passwordInput() ?> <?= $form->field($model,'repeatnewpass',['inputOptions'=>[ 'placeholder'=>'Repeat New Password' ]])->passwordInput() ?> <div class="form-group"> <?= Html::submitButton('ثبت', ['class' => 'btn btn-primary btnb', 'name' => 'login-button']) ?> </div> <?php ActiveForm::end(); ?> </div> </div> </div> </div>
50,230
https://github.com/QualitySolution/QSProjects/blob/master/QS.Project.Gtk/RepresentationModel.GtkUI/RepresentationAttributies.cs
Github Open Source
Open Source
Apache-2.0
2,023
QSProjects
QualitySolution
C#
Code
15
52
using System; namespace QS.RepresentationModel.GtkUI { [AttributeUsage (AttributeTargets.Property)] public class UseForSearchAttribute : Attribute { } }
43,786
https://github.com/Kerbores/NUTZ-ONEKEY/blob/master/thunder/thunder-bean/src/main/java/club/zhcs/thunder/bean/struts/package-info.java
Github Open Source
Open Source
Apache-2.0
2,021
NUTZ-ONEKEY
Kerbores
Java
Code
5
21
/** * */ package club.zhcs.thunder.bean.struts;
54
https://github.com/KasRoid/VegeXI/blob/master/VegeXI/VegeXI/Write/View/MyPageCategoryView.swift
Github Open Source
Open Source
MIT
2,021
VegeXI
KasRoid
Swift
Code
384
1,705
// // MyPageCategoryView.swift // VegeXI // // Created by Doyoung Song on 8/13/20. // Copyright © 2020 TeamSloth. All rights reserved. // import UIKit class MyPageCategoryView: UIView { // MARK: - Properties private let firstSection = UIView() private let firstSectionLabel = UILabel().then { $0.text = MyPageStrings.myPost.generateString() $0.font = UIFont.spoqaHanSansBold(ofSize: 15) $0.textColor = .vegeTextBlackColor } private let secondSection = UIView() private let secondSectionLabel = UILabel().then { $0.text = MyPageStrings.myBookmark.generateString() $0.font = UIFont.spoqaHanSansRegular(ofSize: 15) $0.textColor = .vegeCategoryTextColor } private let separator = UIView().then { $0.backgroundColor = .vegeLightGrayButtonColor } private let sectionIndicator = UIView().then { $0.backgroundColor = .vegeTextBlackColor } private var selectedSectionNumber = 0 private var firstSectionTapGesture: UITapGestureRecognizer? private var secondSectionTapGesture: UITapGestureRecognizer? private var controlSections: (Int) -> Void = { _ in return } // MARK: - Lifecycle override init(frame: CGRect) { super.init(frame: frame) configureUI() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - UI private func configureUI() { setPropertyAttributes() setConstraints() } private func setPropertyAttributes() { firstSectionTapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTapGestures(_:))) secondSectionTapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTapGestures(_:))) guard let firstSectionTapGesture = firstSectionTapGesture, let secondSectionTapGesture = secondSectionTapGesture else { return } firstSection.addGestureRecognizer(firstSectionTapGesture) firstSection.isUserInteractionEnabled = true secondSection.addGestureRecognizer(secondSectionTapGesture) secondSection.isUserInteractionEnabled = true } private func setConstraints() { let viewSize = UIScreen.main.bounds.size [firstSection, secondSection, separator, sectionIndicator].forEach { self.addSubview($0) } firstSection.addSubview(firstSectionLabel) secondSection.addSubview(secondSectionLabel) firstSection.snp.makeConstraints { $0.top.leading.equalToSuperview() $0.width.equalTo(viewSize.width / 2) $0.height.equalToSuperview() } secondSection.snp.makeConstraints { $0.top.trailing.equalToSuperview() $0.leading.equalTo(firstSection.snp.trailing) $0.trailing.equalToSuperview() $0.height.equalToSuperview() } firstSectionLabel.snp.makeConstraints { $0.centerX.centerY.equalToSuperview() } secondSectionLabel.snp.makeConstraints { $0.centerX.centerY.equalToSuperview() } separator.snp.makeConstraints { $0.height.equalTo(1) $0.leading.trailing.bottom.equalToSuperview() } sectionIndicator.snp.makeConstraints { $0.height.equalTo(2) $0.leading.trailing.equalTo(firstSection) $0.bottom.equalToSuperview() } } // MARK: - Helpers private func handleSectionSelected(sectionNumber: Int) { UIView.animate(withDuration: 0.15) { switch sectionNumber { case 0: self.firstSectionLabel.font = UIFont.spoqaHanSansBold(ofSize: 15) self.firstSectionLabel.textColor = .vegeTextBlackColor self.secondSectionLabel.font = UIFont.spoqaHanSansRegular(ofSize: 15) self.secondSectionLabel.textColor = .vegeCategoryTextColor case 1: self.firstSectionLabel.font = UIFont.spoqaHanSansRegular(ofSize: 15) self.firstSectionLabel.textColor = .vegeCategoryTextColor self.secondSectionLabel.font = UIFont.spoqaHanSansBold(ofSize: 15) self.secondSectionLabel.textColor = .vegeTextBlackColor default: break } self.layoutIfNeeded() } animateIndicator(sectionNumber: sectionNumber) } private func animateIndicator(sectionNumber: Int) { UIView.animate(withDuration: 0.15) { switch sectionNumber { case 0: self.sectionIndicator.snp.removeConstraints() self.sectionIndicator.snp.makeConstraints { $0.height.equalTo(2) $0.leading.trailing.equalTo(self.firstSection) $0.bottom.equalToSuperview() } case 1: self.sectionIndicator.snp.removeConstraints() self.sectionIndicator.snp.makeConstraints { $0.height.equalTo(2) $0.leading.trailing.equalTo(self.secondSection) $0.bottom.equalToSuperview() } default: break } self.layoutIfNeeded() } } // MARK: - Selectors @objc private func handleTapGestures(_ sender: UITapGestureRecognizer) { switch sender { case firstSectionTapGesture: selectedSectionNumber = 0 handleSectionSelected(sectionNumber: selectedSectionNumber) controlSections(selectedSectionNumber) case secondSectionTapGesture: selectedSectionNumber = 1 handleSectionSelected(sectionNumber: selectedSectionNumber) controlSections(selectedSectionNumber) default: break } } // MARK: - Helpers func prepareForActions(action: @escaping (Int) -> Void) { controlSections = action } }
8,949
https://github.com/skill6/skill6-parent/blob/master/skill6-common/src/main/java/cn/skill6/common/encrypt/DesEncrypt.java
Github Open Source
Open Source
Apache-2.0
2,021
skill6-parent
skill6
Java
Code
361
1,371
package cn.skill6.common.encrypt; import cn.skill6.common.exception.tools.StackTrace2Str; import lombok.extern.slf4j.Slf4j; import javax.crypto.*; import javax.crypto.spec.DESKeySpec; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.util.Base64; /** * DES加密工具 * * @author 何明胜 * @version 1.2 * @since 2018年3月19日 上午9:15:27 */ @Slf4j public final class DesEncrypt { /** * 加密算法 */ private static final String DES_ALGORITHM = "DES"; /** * 8位默认密钥 */ public static final String DEFAULT_DES_KEY = "IwL1EOba"; /** * DES加密,使用默认密钥 * * @param dataSource * @return 加密后的字符串 * @throws Exception */ public static String encrypt(final String dataSource) throws Exception { return encrypt(dataSource, DEFAULT_DES_KEY); } /** * DES加密 * * @param dataSource 原始字符串 * @param secretKey 加密密钥 * @return 加密后的字符串 * @throws Exception */ public static String encrypt(final String dataSource, final String secretKey) throws Exception { Cipher cipher = null; try { cipher = Cipher.getInstance(DES_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, generateKey(secretKey)); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) { log.error(StackTrace2Str.exceptionStackTrace2Str(e)); } try { // 为了防止解密时报javax.crypto.IllegalBlockSizeException: Input length must // be multiple of 8 when decrypting with padded cipher异常, // 不能把加密后的字节数组直接转换成字符串 byte[] buf = cipher.doFinal(dataSource.getBytes()); return Base64.getEncoder().encodeToString(buf); } catch (IllegalBlockSizeException e) { log.error(StackTrace2Str.exceptionStackTrace2Str(e)); throw new Exception("IllegalBlockSizeException", e); } catch (BadPaddingException e) { log.error(StackTrace2Str.exceptionStackTrace2Str(e)); throw new Exception("BadPaddingException", e); } } /** * DES解密,使用默认密钥 * * @param dataSource * @return 解密后的字符串 * @throws Exception */ public static String decrypt(final String dataSource) throws Exception { return decrypt(dataSource, DEFAULT_DES_KEY); } /** * DES解密 * * @param dataSource 密码字符串 * @param secretKey 解密密钥 * @return 原始字符串 * @throws Exception */ public static String decrypt(final String dataSource, final String secretKey) throws Exception { Cipher cipher = null; try { cipher = Cipher.getInstance(DES_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, generateKey(secretKey)); } catch (NoSuchAlgorithmException e) { log.error(StackTrace2Str.exceptionStackTrace2Str(e)); throw new Exception("NoSuchAlgorithmException", e); } catch (NoSuchPaddingException e) { log.error(StackTrace2Str.exceptionStackTrace2Str(e)); throw new Exception("NoSuchPaddingException", e); } catch (InvalidKeyException e) { log.error(StackTrace2Str.exceptionStackTrace2Str(e)); throw new Exception("InvalidKeyException", e); } try { byte[] buf = cipher.doFinal(Base64.getDecoder().decode(dataSource)); return new String(buf); } catch (IllegalBlockSizeException e) { log.error(StackTrace2Str.exceptionStackTrace2Str(e)); throw new Exception("IllegalBlockSizeException", e); } catch (BadPaddingException e) { log.error(StackTrace2Str.exceptionStackTrace2Str(e)); throw new Exception("BadPaddingException", e); } } /** * 获得秘密密钥 * * @param secretKey * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws InvalidKeyException */ private static SecretKey generateKey(final String secretKey) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException { SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES_ALGORITHM); DESKeySpec keySpec = new DESKeySpec(secretKey.getBytes()); keyFactory.generateSecret(keySpec); return keyFactory.generateSecret(keySpec); } }
23,592
https://github.com/TheoChevalier/gaia/blob/master/dev_apps/uitest/js/UI/alert.js
Github Open Source
Open Source
Apache-2.0
2,020
gaia
TheoChevalier
JavaScript
Code
94
494
'use strict'; var clickHandlers = { 'button1': function() { window.parent.alert('Hello world!'); }, 'button2': function() { window.parent.alert(window.parent.confirm('Hello world?')); }, 'button3': function() { window.parent.alert(window.parent.prompt('Hello world:', 'initial value')); }, 'button21': function() { alert('Hello world!'); }, 'button22': function() { alert(confirm('Hello world?')); }, 'button23': function() { alert(prompt('Hello world:', 'initial value')); }, 'button31': function() { var msg = 'Hello world!1\n2\n3\n4\n5\n6\n7\n8\n9'; msg += '\n10\n11\n12\n13\n14\n15\n16\n17\n18\n'; alert(msg); }, 'button32': function() { var msg = 'Hello world!1\n2\n3\n4\n5\n6\n7\n8\n9'; msg += '\n10\n11\n12\n13\n14\n15\n16\n17\n18\n'; alert(confirm(msg)); }, 'button33': function() { var msg = 'Hello world!1\n2\n3\n4\n5\n6\n7\n8\n9'; msg += '\n10\n11\n12\n13\n14\n15\n16\n17\n18\n'; alert(prompt(msg)); } }; document.body.addEventListener('click', function(evt) { if (clickHandlers[evt.target.id]) clickHandlers[evt.target.id].call(this, evt); });
24,851
https://github.com/csoap/csoap.github.io/blob/master/sourceCode/dotNet4.6/wpf/src/Framework/MS/Internal/Printing/NativeMethods.cs
Github Open Source
Open Source
Apache-2.0
2,021
csoap.github.io
csoap
C#
Code
500
1,498
using System; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; namespace MS.Internal.Printing { internal static class NativeMethods { internal const UInt32 PD_ALLPAGES = 0x00000000; internal const UInt32 PD_SELECTION = 0x00000001; internal const UInt32 PD_PAGENUMS = 0x00000002; internal const UInt32 PD_NOSELECTION = 0x00000004; internal const UInt32 PD_NOPAGENUMS = 0x00000008; internal const UInt32 PD_USEDEVMODECOPIESANDCOLLATE = 0x00040000; internal const UInt32 PD_DISABLEPRINTTOFILE = 0x00080000; internal const UInt32 PD_HIDEPRINTTOFILE = 0x00100000; internal const UInt32 PD_CURRENTPAGE = 0x00400000; internal const UInt32 PD_NOCURRENTPAGE = 0x00800000; internal const UInt32 PD_RESULT_CANCEL = 0x0; internal const UInt32 PD_RESULT_PRINT = 0x1; internal const UInt32 PD_RESULT_APPLY = 0x2; internal const UInt32 START_PAGE_GENERAL = 0xFFFFFFFF; [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Auto)] internal class PRINTDLGEX32 { public int lStructSize = Marshal.SizeOf(typeof(PRINTDLGEX32)); public IntPtr hwndOwner = IntPtr.Zero; public IntPtr hDevMode = IntPtr.Zero; public IntPtr hDevNames = IntPtr.Zero; public IntPtr hDC = IntPtr.Zero; public UInt32 Flags = 0; public UInt32 Flags2 = 0; public UInt32 ExclusionFlags = 0; public UInt32 nPageRanges = 0; public UInt32 nMaxPageRanges = 0; public IntPtr lpPageRanges = IntPtr.Zero; public UInt32 nMinPage = 0; public UInt32 nMaxPage = 0; public UInt32 nCopies = 0; public IntPtr hInstance = IntPtr.Zero; public IntPtr lpPrintTemplateName = IntPtr.Zero; public IntPtr lpCallback = IntPtr.Zero; public UInt32 nPropertyPages = 0; public IntPtr lphPropertyPages = IntPtr.Zero; public UInt32 nStartPage = START_PAGE_GENERAL; public UInt32 dwResultAction = 0; } [StructLayout(LayoutKind.Sequential, Pack = 8, CharSet = CharSet.Auto)] internal class PRINTDLGEX64 { public int lStructSize = Marshal.SizeOf(typeof(PRINTDLGEX64)); public IntPtr hwndOwner = IntPtr.Zero; public IntPtr hDevMode = IntPtr.Zero; public IntPtr hDevNames = IntPtr.Zero; public IntPtr hDC = IntPtr.Zero; public UInt32 Flags = 0; public UInt32 Flags2 = 0; public UInt32 ExclusionFlags = 0; public UInt32 nPageRanges = 0; public UInt32 nMaxPageRanges = 0; public IntPtr lpPageRanges = IntPtr.Zero; public UInt32 nMinPage = 0; public UInt32 nMaxPage = 0; public UInt32 nCopies = 0; public IntPtr hInstance = IntPtr.Zero; public IntPtr lpPrintTemplateName = IntPtr.Zero; public IntPtr lpCallback = IntPtr.Zero; public UInt32 nPropertyPages = 0; public IntPtr lphPropertyPages = IntPtr.Zero; public UInt32 nStartPage = START_PAGE_GENERAL; public UInt32 dwResultAction = 0; } [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Auto)] internal struct DEVMODE { private const int CCHDEVICENAME = 32; private const int CCHFORMNAME = 32; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCHDEVICENAME)] public string dmDeviceName; public short dmSpecVersion; public short dmDriverVersion; public short dmSize; public short dmDriverExtra; public int dmFields; public int dmPositionX; public int dmPositionY; public int dmDisplayOrientation; public int dmDisplayFixedOutput; public short dmColor; public short dmDuplex; public short dmYResolution; public short dmTTOption; public short dmCollate; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCHFORMNAME)] public string dmFormName; public short dmLogPixels; public int dmBitsPerPel; public int dmPelsWidth; public int dmPelsHeight; public int dmDisplayFlags; public int dmDisplayFrequency; public int dmICMMethod; public int dmICMIntent; public int dmMediaType; public int dmDitherType; public int dmReserved1; public int dmReserved2; public int dmPanningWidth; public int dmPanningHeight; } [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Auto)] internal struct DEVNAMES { public ushort wDriverOffset; public ushort wDeviceOffset; public ushort wOutputOffset; public ushort wDefault; } [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Auto)] internal struct PRINTPAGERANGE { public UInt32 nFromPage; public UInt32 nToPage; } } }
14,614
https://github.com/xygdev/XYG_ALB2B/blob/master/src/com/xinyiglass/springSample/controller/CustController.java
Github Open Source
Open Source
MIT
2,017
XYG_ALB2B
xygdev
Java
Code
180
1,100
package com.xinyiglass.springSample.controller; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import xygdev.commons.util.TypeConvert; import com.xinyiglass.springSample.entity.UserCustVO; import com.xinyiglass.springSample.service.UserCustVOService; import com.xinyiglass.springSample.util.LogUtil; @Controller @RequestMapping("/cust") @Scope("prototype") public class CustController { @Autowired UserCustVOService ucvs; protected HttpServletRequest req; protected HttpServletResponse res; protected HttpSession sess; protected Long loginId; @ModelAttribute public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException{ this.req = request; this.res = response; this.sess = request.getSession(); req.setCharacterEncoding("utf-8"); res.setCharacterEncoding("utf-8"); res.setContentType("text/html;charset=utf-8"); loginId=(Long)sess.getAttribute("LOGIN_ID"); } @RequestMapping(value = "/getUserCustPage.do", method = RequestMethod.POST) public void getUserCustPage() throws Exception { int pageSize = Integer.parseInt(req.getParameter("pageSize")); int pageNo = Integer.parseInt(req.getParameter("pageNo")); boolean goLastPage = Boolean.parseBoolean(req.getParameter("goLastPage")); Map<String,Object> conditionMap=new HashMap<String,Object>(); conditionMap.put("orderBy", req.getParameter("orderby")); conditionMap.put("userId", Long.parseLong(req.getParameter("USER_ID"))); res.getWriter().print(ucvs.findForPage(pageSize, pageNo, goLastPage, conditionMap,loginId)); } @RequestMapping(value = "/insert.do", method = RequestMethod.POST) public void insret() throws Exception { UserCustVO u = new UserCustVO(); u.setUserId(TypeConvert.str2Long(req.getParameter("USER_ID"))); u.setOrgId(TypeConvert.str2Long(req.getParameter("ORG_ID"))); u.setCustomerId(TypeConvert.str2Long(req.getParameter("CUSTOMER_ID"))); u.setStartDate(TypeConvert.str2uDate(req.getParameter("START_DATE"))); LogUtil.log("Time:"+req.getParameter("END_DATE")); u.setEndDate(TypeConvert.str2uDate(req.getParameter("END_DATE"))); res.getWriter().print(ucvs.insert(u,loginId).toJsonStr()); } @RequestMapping(value = "/preUpdate.do", method = RequestMethod.POST) public void preUpdate() throws Exception { Long userCustId = Long.parseLong(req.getParameter("USER_CUST_ID")); res.getWriter().print(ucvs.findByIdForJSON(userCustId,loginId)); } @RequestMapping(value = "/update.do", method = RequestMethod.POST) public void update() throws Exception { UserCustVO u = new UserCustVO(); u.setUserCustId(TypeConvert.str2Long(req.getParameter("USER_CUST_ID"))); u.setEndDate(TypeConvert.str2uDate(req.getParameter("END_DATE"))); res.getWriter().print(ucvs.update(u,loginId).toJsonStr()); } }
45,685
https://github.com/karlatt/NativeScript-PluginsDemo/blob/master/app/ar/ar.module.ts
Github Open Source
Open Source
MIT
null
NativeScript-PluginsDemo
karlatt
TypeScript
Code
69
228
import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core"; import { NativeScriptCommonModule } from "nativescript-angular/common"; import { ARRoutingModule } from "./ar-routing.module"; import { ARComponent } from "./ar.component"; import { TNSFontIconModule } from "nativescript-ngx-fonticon"; import { DropDownModule } from "nativescript-drop-down/angular"; import { registerElement } from "nativescript-angular/element-registry"; registerElement("AR", () => require("nativescript-ar").AR); @NgModule({ imports: [ NativeScriptCommonModule, ARRoutingModule, TNSFontIconModule, DropDownModule ], declarations: [ ARComponent ], schemas: [ NO_ERRORS_SCHEMA ] }) export class ARModule { }
30,990
https://github.com/FuscaSoftware/qr-image-handler/blob/master/application/core/classes/Map.php
Github Open Source
Open Source
MIT
null
qr-image-handler
FuscaSoftware
PHP
Code
430
1,288
<?php //require_once __DIR__ . "/Collection.php"; /** * User: sbraun * Date: 18.07.17 * Time: 14:02 */ class Map extends stdClass implements Serializable, ArrayAccess, Countable { protected $map = []; public function __construct(array $map = null) { if (!is_null($map) && is_array($map)) { if (!(count(array_keys($map)) == count(array_values($map)))) throw new Exception("\$map is not valid!"); ksort($map); $this->map = $map; } } /** * Whether a offset exists * @link http://php.net/manual/en/arrayaccess.offsetexists.php * * @param mixed $offset <p> * An offset to check for. * </p> * * @return boolean true on success or false on failure. * </p> * <p> * The return value will be casted to boolean if non-boolean was returned. * @since 5.0.0 */ public function offsetExists($offset) { return isset($this->map[$offset]); } /** * Offset to retrieve * @link http://php.net/manual/en/arrayaccess.offsetget.php * * @param mixed $offset <p> * The offset to retrieve. * </p> * * @return mixed Can return all value types. * @since 5.0.0 */ public function offsetGet($offset) { if (is_numeric($offset) && !$this->offsetExists($offset) && count($this->map) > $offset) $offset = array_keys($this->map)[$offset]; if ($offset == "keys" && !$this->offsetExists($offset) && count($this->map) > 0) return array_keys($this->map); if ($offset == "values" && !$this->offsetExists($offset) && count($this->map) > 0) return array_values($this->map); return [$offset => $this->map[$offset]]; } /** * Offset to set * @link http://php.net/manual/en/arrayaccess.offsetset.php * * @param mixed $offset <p> * The offset to assign the value to. * </p> * @param mixed $value <p> * The value to set. * </p> * * @return void * @since 5.0.0 */ public function offsetSet($offset, $value) { $r = $this->map[$offset] = $value; ksort($this->map); return $r; } /** * Offset to unset * @link http://php.net/manual/en/arrayaccess.offsetunset.php * * @param mixed $offset <p> * The offset to unset. * </p> * * @return void * @since 5.0.0 */ public function offsetUnset($offset) { unset($this->map[$offset]); } /** * String representation of object * @link http://php.net/manual/en/serializable.serialize.php * @return string the string representation of the object or null * @since 5.1.0 */ public function serialize() { return serialize($this->map); } /** * Constructs the object * @link http://php.net/manual/en/serializable.unserialize.php * * @param string $serialized <p> * The string representation of the object. * </p> * * @return void * @since 5.1.0 */ public function unserialize($serialized) { $this->map = unserialize($serialized); } /** * @return string|false */ public function as_key() { if (empty($this->map)) return false; ksort($this->map); $keys = array_keys($this->map); $values = array_values($this->map); if (count($keys) == 1 && count($values) == 1) $string = $keys[0] ."--".$values[0]; if (count($keys) == 2 && count($values) == 2) $string = $keys[0] ."--".$values[0]."---".$keys[1] ."--".$values[1]; return rawurlencode($string); } public function to_string() { return $this->as_key(); } public function get_knot_key() { return $this->to_string(); } public function count() { return count($this->map); } }
14,488
https://github.com/rejasupotaro/RobotGirl/blob/master/RobotGirl/src/instrumentTest/java/rejasupotaro/robotgirl/test/UriTypeSerializer.java
Github Open Source
Open Source
Apache-2.0
2,017
RobotGirl
rejasupotaro
Java
Code
64
201
package rejasupotaro.robotgirl.test; import android.net.Uri; import com.activeandroid.serializer.TypeSerializer; public class UriTypeSerializer extends TypeSerializer { @Override public Class<?> getDeserializedType() { return Uri.class; } @Override public Class<?> getSerializedType() { return String.class; } @Override public String serialize(Object data) { if (data == null) { return null; } return data.toString(); } @Override public Uri deserialize(Object data) { if (data == null) { return null; } return Uri.parse((String) data); } }
45,371
https://github.com/Khosiyat/anima/blob/master/anima/env/fusion/toolbox.py
Github Open Source
Open Source
MIT
2,021
anima
Khosiyat
Python
Code
1,098
4,119
# -*- coding: utf-8 -*- import os from anima.ui.base import AnimaDialogBase from anima.ui.lib import QtCore, QtGui, QtWidgets from anima.ui.utils import add_button, add_line __here__ = os.path.abspath(__file__) def UI(app_in=None, executor=None, **kwargs): """ :param environment: The :class:`~stalker.models.env.EnvironmentBase` can be None to let the UI to work in "environmentless" mode in which it only creates data in database and copies the resultant version file path to clipboard. :param mode: Runs the UI either in Read-Write (0) mode or in Read-Only (1) mode. :param app_in: A Qt Application instance, which you can pass to let the UI be attached to the given applications event process. :param executor: Instead of calling app.exec_ the UI will call this given function. It also passes the created app instance to this executor. """ from anima.ui.base import ui_caller return ui_caller(app_in, executor, ToolboxDialog, **kwargs) class ToolboxDialog(QtWidgets.QDialog, AnimaDialogBase): """The toolbox dialog """ def __init__(self, environment=None, parent=None): super(ToolboxDialog, self).__init__(parent) self._setup_ui() def _setup_ui(self): self.setWindowModality(QtCore.Qt.ApplicationModal) self.setModal(True) self.resize(300, 300) size_policy = QtWidgets.QSizePolicy( QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred ) size_policy.setHorizontalStretch(1) size_policy.setVerticalStretch(1) size_policy.setHeightForWidth(self.sizePolicy().hasHeightForWidth()) self.setSizePolicy(size_policy) self.setSizeGripEnabled(True) self.horizontal_layout = QtWidgets.QHBoxLayout(self) self.toolbox_widget = QtWidgets.QWidget(self) self.horizontal_layout.addWidget(self.toolbox_widget) self.toolbox_layout = ToolboxLayout(self.toolbox_widget) self.toolbox_layout.setSizeConstraint(QtWidgets.QLayout.SetMaximumSize) self.toolbox_layout.setContentsMargins(0, 0, 0, 0) # setup icon global __here__ icon_path = os.path.abspath( os.path.join(__here__, "../../../ui/images/fusion9.png") ) icon = QtGui.QIcon(icon_path) self.setWindowIcon(icon) class ToolboxLayout(QtWidgets.QVBoxLayout): """The toolbox """ def __init__(self, *args, **kwargs): super(ToolboxLayout, self).__init__(*args, **kwargs) self.setup_ui() def setup_ui(self): """add tools """ # create the main tab layout main_tab_widget = QtWidgets.QTabWidget(self.widget()) self.addWidget(main_tab_widget) # add the General Tab general_tab_widget = QtWidgets.QWidget(self.widget()) general_tab_vertical_layout = QtWidgets.QVBoxLayout() general_tab_vertical_layout.setSizeConstraint( QtWidgets.QLayout.SetMaximumSize ) general_tab_widget.setLayout(general_tab_vertical_layout) main_tab_widget.addTab(general_tab_widget, 'Generic') # Create tools for general tab # ------------------------------------------------------------------- # Open Version add_button( 'Open Version', general_tab_vertical_layout, GenericTools.version_dialog, callback_kwargs={"parent": self.parent(), "mode": 1} ) # Save As Version add_button( 'Save As Version', general_tab_vertical_layout, GenericTools.version_dialog, callback_kwargs={"parent": self.parent(), "mode": 0} ) # Update Outputs add_button( 'Update Savers', general_tab_vertical_layout, GenericTools.update_savers ) # Loader Report add_button( 'Loader Report', general_tab_vertical_layout, GenericTools.loader_report ) # PassThrough All Saver nodes add_button( 'PassThrough All Savers', general_tab_vertical_layout, GenericTools.pass_through_all_savers ) # Insert Pipe Router add_button( 'Insert Pipe Router', general_tab_vertical_layout, GenericTools.insert_pipe_router_to_selected_node ) # Loader From Saver add_button( 'Loader from Saver', general_tab_vertical_layout, GenericTools.loader_from_saver ) # Delete Recent Comps add_button( 'Delete Recent Comps', general_tab_vertical_layout, GenericTools.delete_recent_comps ) # Set Frames At Once To 1, 5 and 10 hbox_layout = QtWidgets.QHBoxLayout() general_tab_vertical_layout.addLayout(hbox_layout) set_frames_at_once_label = QtWidgets.QLabel() set_frames_at_once_label.setText("Set Frames At Once To") hbox_layout.addWidget(set_frames_at_once_label) for i in [1, 5, 10]: button = add_button( '%s' % i, hbox_layout, GenericTools.set_frames_at_once, callback_kwargs={'count': i} ) button.setMinimumSize(QtCore.QSize(25, 0)) add_line(general_tab_vertical_layout) # Range From Shot add_button( 'Get Comp Range From Database', general_tab_vertical_layout, GenericTools.range_from_shot ) # Shot From Range add_button( 'Set Comp Range To Database', general_tab_vertical_layout, GenericTools.shot_from_range ) add_line(general_tab_vertical_layout) # Render Merger add_button( 'Render Merger', general_tab_vertical_layout, GenericTools.render_merger, tooltip="Creates comp setup to merge renders created with Render Slicer." ) # Render Merger import functools add_button( '3DE4 Lens Distort', general_tab_vertical_layout, functools.partial(GenericTools.tde4_lens_distort_node_creator, self.parent()), tooltip=GenericTools.tde4_lens_distort_node_creator.__doc__ ) # ------------------------------------------------------------------- # Add the stretcher general_tab_vertical_layout.addStretch() class GenericTools(object): """Generic Tools """ @classmethod def version_dialog(cls, **args): """version dialog """ # from anima.ui.scripts import fusion # fusion.version_dialog(*args) from anima.utils import do_db_setup do_db_setup() from anima.env import fusion fusion_env = fusion.Fusion() fusion_env.name = 'Fusion' from anima.ui import version_dialog ui_instance = version_dialog.MainDialog( environment=fusion_env, **args ) ui_instance.show() ui_instance.center_window() @classmethod def update_savers(cls): """updates savers, creates missing ones """ from anima.utils import do_db_setup do_db_setup() from anima.env import fusion fusion_env = fusion.Fusion() v = fusion_env.get_current_version() fusion_env.create_main_saver_node(version=v) @classmethod def loader_report(cls): """returns the loaders in this comp """ from anima.env import fusion fs = fusion.Fusion() comp = fs.comp paths = [] all_loader_nodes = comp.GetToolList(False, 'Loader').values() for loader_node in all_loader_nodes: node_input_list = loader_node.GetInputList() for input_entry_key in node_input_list.keys(): input_entry = node_input_list[input_entry_key] input_id = input_entry.GetAttrs()['INPS_ID'] if input_id == 'Clip': # value = node_input_list[input_entry_key] # input_entry[0] = value # break value = input_entry[0] if value != '' or value is not None: paths.append(value) for path in sorted(paths): print(path) @classmethod def pass_through_all_savers(cls): """disables all saver nodes in the current comp """ from anima.env import fusion fusion_env = fusion.Fusion() comp = fusion_env.comp saver_nodes = comp.GetToolList(False, 'Saver').values() for node in saver_nodes: node.SetAttrs({"TOOLB_PassThrough": True}) @classmethod def insert_pipe_router_to_selected_node(cls): """inserts a Pipe Router node between the selected node and the nodes connected to its output """ from anima.env import fusion fusion_env = fusion.Fusion() comp = fusion_env.comp # get active node node = comp.ActiveTool # get all node outputs output = node.FindMainOutput(1) connected_inputs = output.GetConnectedInputs() # create pipe router pipe_router = comp.PipeRouter({"Input": node}) # connect it to the other nodes for connected_input in connected_inputs.values(): connected_input.ConnectTo(pipe_router) @classmethod def update_secondary_savers(cls): """Updates Savers which are not a Main Saver node """ # get all saver nodes from anima.env import fusion fusion_env = fusion.Fusion() comp = fusion_env.comp all_saver_nodes = fusion_env.comp.GetToolList(False, 'Saver').values() # filter all Main Saver nodes main_savers = fusion_env.get_main_saver_node() secondary_savers = [ node for node in all_saver_nodes if node not in main_savers ] # get the output path from one of the main savers @classmethod def loader_from_saver(cls): """creates a loader from the selected saver node """ from anima.env import fusion fusion_env = fusion.Fusion() comp = fusion_env.comp node = comp.ActiveTool flow = comp.CurrentFrame.FlowView x, y = flow.GetPosTable(node).values() node_input_list = node.GetInputList() path = '' key = 'Clip' for input_entry_key in node_input_list.keys(): input_entry = node_input_list[input_entry_key] input_id = input_entry.GetAttrs()['INPS_ID'] if input_id == key: path = input_entry[0] break comp.Lock() loader_node = comp.AddTool('Loader') comp.Unlock() node_input_list = loader_node.GetInputList() for input_entry_key in node_input_list.keys(): input_entry = node_input_list[input_entry_key] input_id = input_entry.GetAttrs()['INPS_ID'] if input_id == key: input_entry[0] = path break # set position near to the saver node flow.SetPos(loader_node, x, y + 1.0) flow.Select(node, False) flow.Select(loader_node, True) comp.SetActiveTool(loader_node) @classmethod def delete_recent_comps(cls): """Deletes the Recent Comps value in the current preferences. This was created to remedy the low performance bug under Fusion 9 and Windows. It is not clear for now what happens under the other OSes. """ import BlackmagicFusion as bmf fusion = bmf.scriptapp("Fusion") print("Erasing RecentComps value!") fusion.SetPrefs('Global.RecentComps', {}) fusion.SavePrefs() @classmethod def set_frames_at_once(cls, count=1): """Sets the frames at once value to the given number :param count: :return: """ import BlackmagicFusion as bmf fusion = bmf.scriptapp("Fusion") comp = fusion.GetCurrentComp() comp.SetPrefs("Comp.Memory.FramesAtOnce", count) @classmethod def afanasy_job_submitter(cls): """alpha feature """ # call the lua script from /opt/cgru/plugins/fusion/ pass @classmethod def range_from_shot(cls): """sets the range from the shot """ from anima.utils import do_db_setup do_db_setup() from anima.env import fusion fusion_env = fusion.Fusion() version = fusion_env.get_current_version() fusion_env.set_range_from_shot(version) @classmethod def shot_from_range(cls): """updates the Shot.cut_in and Shot.cut_out attributes from the current range """ from anima.utils import do_db_setup do_db_setup() from anima.env import fusion fusion_env = fusion.Fusion() version = fusion_env.get_current_version() try: fusion_env.set_shot_from_range(version) except BaseException as e: QtWidgets.QMessageBox.critical(None, "Error", "%s" % e) finally: QtWidgets.QMessageBox.information(None, "Success", "Shot Range has been updated successfully!") @classmethod def render_merger(cls): """calls the render merger """ from anima.env.fusion import render_merger rm = render_merger.RenderMerger() rm.ui() @classmethod def tde4_lens_distort_node_creator(cls, parent): """creates lens distort nodes from the given 3de4 lens file """ # show a file browser dialog = QtWidgets.QFileDialog(parent, "Choose file") dialog.setNameFilter("3DE4 Lens Files (*.txt)") dialog.setFileMode(QtWidgets.QFileDialog.ExistingFile) if dialog.exec_(): file_path = dialog.selectedFiles()[0] if not file_path: return from anima.env.fusion.utils import TDE4LensDistortionImporter lens_importer = TDE4LensDistortionImporter() lens_importer.import_(file_path)
24,963
https://github.com/seblammers/dplyr/blob/master/tests/testthat/test-deprec-src-local.r
Github Open Source
Open Source
MIT
2,021
dplyr
seblammers
R
Code
106
363
test_that("src_tbls() includes all tbls (#4326)", { withr::local_options(lifecycle_verbosity = "quiet") expect_equal( src_tbls(src_df(env = env(. = iris))), "." ) }) test_that("src_local only overwrites if overwrite = TRUE", { withr::local_options(lifecycle_verbosity = "quiet") env <- new.env(parent = emptyenv()) env$x <- 1 src_env <- src_df(env = env) df <- tibble(x = 1) copy_to(src_env, df, name = "x", overwrite = TRUE) expect_equal(env$x, df) }) test_that("src_df() is deprecated / errors", { withr::local_options(lifecycle_verbosity = "quiet") # src_local errs with pkg/env expect_snapshot(error = TRUE, src_df("base", new.env())) expect_snapshot(error = TRUE, src_df()) env <- new.env(parent = emptyenv()) env$x <- 1 src_env <- src_df(env = env) expect_snapshot(error = TRUE, copy_to(src_env, tibble(x = 1), name = "x") ) })
44,148
https://github.com/josewilsoncc/MyCI/blob/master/.htaccess
Github Open Source
Open Source
MIT
2,015
MyCI
josewilsoncc
ApacheConf
Code
11
62
RewriteEngine on RewriteCond $1 !^(index.php|public|robots.txt|assets|uploads) RewriteRule ^(.*)$ /MyCI/index.php/$1 [L] AddDefaultCharset UTF-8
39,670
https://github.com/kaka-lin/pycon.tw/blob/master/src/proposals/tests/forms/test_additional_speaker.py
Github Open Source
Open Source
MIT
2,018
pycon.tw
kaka-lin
Python
Code
411
1,435
import pytest from proposals.forms import ( AdditionalSpeakerCancelForm, AdditionalSpeakerCreateForm, AdditionalSpeakerSetStatusForm, ) from proposals.models import AdditionalSpeaker @pytest.fixture def cancelled_additional_speaker(additional_speaker): additional_speaker.cancelled = True additional_speaker.save() return additional_speaker def test_additional_speaker_create_form(additional_speaker): with pytest.raises(ValueError) as ctx: AdditionalSpeakerCreateForm(instance=additional_speaker) assert str(ctx.value) == ( 'Additional speaker creation form cannot be used with an instance.' ) def test_additional_speaker_create_form_instance(): form = AdditionalSpeakerCreateForm() assert list(form.fields) == ['email'] def test_additional_speaker_create_form_no_request(user): form = AdditionalSpeakerCreateForm(data={'email': user.email}) assert not form.is_valid() assert form.errors == { '__all__': [ 'Additional speaker creation requires a request object.', ], 'email': [ 'Additional speaker creation requires a proposal instance.', ], } def test_additional_speaker_create_form_invalid_submitter( request, invalid_user, proposal, another_user): request.user = invalid_user form = AdditionalSpeakerCreateForm( request=request, proposal=proposal, data={'email': another_user.email}, ) assert not form.is_valid() assert form.errors == { '__all__': [ 'Only authenticated user with complete speaker profile may ' 'create an additional speaker.', ], } def test_additional_speaker_create_form_proposal_not_owned( request, user, proposal, another_user): request.user = another_user form = AdditionalSpeakerCreateForm( request=request, proposal=proposal, data={'email': another_user.email}, ) assert not form.is_valid() assert form.errors == { '__all__': [ 'User can only add additional speakers to owned proposals.', ], } def test_additional_speaker_create_form_invalid_additional_speaker( request, user, proposal, another_bare_user): request.user = user form = AdditionalSpeakerCreateForm( request=request, proposal=proposal, data={'email': another_bare_user.email}, ) assert not form.is_valid() assert form.errors == { 'email': ['No valid speaker found with your selection.'], } def test_additional_speaker_create_form_submitter_as_additional_speaker( request, user, proposal): request.user = user form = AdditionalSpeakerCreateForm( request=request, proposal=proposal, data={'email': user.email}, ) assert not form.is_valid() assert form.errors == { 'email': ['This user is already a speaker for the proposal.'], } def test_additional_speaker_create_form_valid( request, user, proposal, another_user): request.user = user form = AdditionalSpeakerCreateForm( request=request, proposal=proposal, data={'email': another_user.email}, ) assert form.is_valid() speaker = form.save() assert not speaker.cancelled def test_additional_speaker_create_form_duplicate_user( request, user, proposal, another_user, additional_speaker): request.user = user form = AdditionalSpeakerCreateForm( request=request, proposal=proposal, data={'email': another_user.email}, ) assert not form.is_valid() assert form.errors == { 'email': ['This user is already a speaker for the proposal.'], } def test_additional_speaker_create_form_cancelled_user( request, user, proposal, another_user, cancelled_additional_speaker): """If a matching additional speaker already exists, the creation form should reuse the same additional speaker instance instead of creating a new one. The "cancelled" flag of the existing epeaker should be set to False. """ request.user = user form = AdditionalSpeakerCreateForm( request=request, proposal=proposal, data={'email': another_user.email}, ) assert form.is_valid() after = form.save() assert after.pk == cancelled_additional_speaker.pk assert not after.cancelled @pytest.mark.parametrize('form_class', [ AdditionalSpeakerCancelForm, AdditionalSpeakerSetStatusForm, ]) def test_additional_speaker_update_form_no_instance(form_class): with pytest.raises(ValueError) as ctx: form_class() assert str(ctx.value) == ( 'Additional speaker update form must be initialized with an instance.' ) def test_additional_speaker_cancel_form(additional_speaker): form = AdditionalSpeakerCancelForm(instance=additional_speaker) assert list(form.fields) == ['cancelled'] def test_additional_speaker_cancel_form_save(additional_speaker): assert not additional_speaker.cancelled form = AdditionalSpeakerCancelForm( data={'cancelled': 'true'}, instance=additional_speaker, ) form.save() assert AdditionalSpeaker.objects.get(pk=additional_speaker.pk).cancelled
4,637
https://github.com/samonzeweb/godb/blob/master/testallwithdocker.sh
Github Open Source
Open Source
MIT
2,022
godb
samonzeweb
Shell
Code
256
956
#!/usr/bin/env bash COMPOSE_FILE="docker-compose-test.yml" MARIADB_USER=godb MARIADB_PASSWORD=godb export GODB_MYSQL="$MARIADB_USER:$MARIADB_PASSWORD@/godb?parseTime=true" POSTGRESQL_USER=godb POSTGRESQL_PASSWORD=godb export GODB_POSTGRESQL="postgres://$POSTGRESQL_USER:$POSTGRESQL_PASSWORD@localhost/godb?sslmode=disable" SQLSERVER_USER=sa SQLSERVER_PASSWORD=NotSoStr0ngP@ssword export GODB_MSSQL="Server=127.0.0.1;Database=godb;User Id=$SQLSERVER_USER;Password=$SQLSERVER_PASSWORD" STARTLOOP_SLEEP=2 STARTLOOP_MAXITERATIONS=30 start_containers() { docker-compose -f "$COMPOSE_FILE" up -d } stop_containers() { docker-compose -f "$COMPOSE_FILE" down } stop_containers_and_exit() { docker-compose -f "$COMPOSE_FILE" down exit 1 } wait_db() { NAME=$1 CMDCHECK=$2 COUNT=0 until ( $CMDCHECK >& /dev/null); do echo "$NAME is starting..." sleep $STARTLOOP_SLEEP COUNT=$((COUNT+1)) if (( $COUNT == $STARTLOOP_MAXITERATIONS )); then echo "$NAME take too long time to start." return 1 fi done } setup_mariadb() { wait_db "MariaDB" "docker exec godb_test_mariadb mysql -u$MARIADB_USER -p$MARIADB_PASSWORD -h127.0.0.1 -e exit" \ || return 1 } setup_postgresql() { wait_db "PostgreSQL" "docker exec godb_test_postgresql psql -U$POSTGRESQL_USER -c \\q" \ || return 1 } setup_sqlserver() { wait_db "SQLServer" "docker exec godb_test_sqlserver /opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P $SQLSERVER_PASSWORD -q exit" \ || return 1 docker exec -i godb_test_sqlserver /opt/mssql-tools/bin/sqlcmd -S localhost -U $SQLSERVER_USER -P NotSoStr0ngP@ssword <<-EOF create database godb; go alter database godb set READ_COMMITTED_SNAPSHOT ON; go exit EOF } # Start all containers start_containers || stop_containers_and_exit echo Containers are starting... # Install dependencies (while containers are starting) echo Fetch Go dependencies go mod download # Wait for and setup each DB echo Wait until DB are ready setup_postgresql || stop_containers_and_exit setup_mariadb || stop_containers_and_exit setup_sqlserver || stop_containers_and_exit echo Containers are started, DB are ready. # Let's test (without cache) ! go clean -testcache go test -v ./... testresult=$? # Cleanup stop_containers # Display and return a clear test status echo ---------- if [ $testresult -eq 0 ]; then echo OK else echo FAIL fi exit $testresult
50,272
https://github.com/wavedigital/active_merchant/blob/master/test/unit/gateways/bpoint_test.rb
Github Open Source
Open Source
MIT
2,020
active_merchant
wavedigital
Ruby
Code
766
6,647
require 'test_helper' class BpointTest < Test::Unit::TestCase include CommStub def setup @gateway = BpointGateway.new( username: '', password: '', merchant_number: '' ) @credit_card = credit_card @amount = 100 @options = { order_id: '1', billing_address: address, description: 'Store Purchase' } end def test_successful_store @gateway.expects(:ssl_post).returns(successful_store_response) response = @gateway.store(@credit_card) assert_success response end def test_failed_store @gateway.expects(:ssl_post).returns(failed_store_response) response = @gateway.store(@credit_card) assert_failure response end def test_successful_purchase @gateway.expects(:ssl_post).returns(successful_purchase_response) response = @gateway.purchase(@amount, @credit_card, @options) assert_success response assert_equal '218990188', response.authorization assert response.test? end def test_failed_purchase @gateway.expects(:ssl_post).returns(failed_purchase_response) response = @gateway.purchase(@amount, @credit_card, @options) assert_failure response assert_equal 'Declined', response.message end def test_successful_authorize @gateway.expects(:ssl_post).returns(successful_authorize_response) response = @gateway.authorize(@amount, @credit_card, @options) assert_success response assert_equal '219388558', response.authorization end def test_failed_authorize @gateway.expects(:ssl_post).returns(failed_authorize_response) response = @gateway.authorize(@amount, @credit_card, @options) assert_failure response end def test_successful_capture @gateway.expects(:ssl_post).returns(successful_capture_response) response = @gateway.capture(@amount, '') assert_success response end def test_failed_capture @gateway.expects(:ssl_post).returns(failed_capture_response) response = @gateway.capture(@amount, '') assert_failure response end def test_successful_refund @gateway.expects(:ssl_post).returns(successful_refund_response) response = @gateway.capture(@amount, '') assert_success response end def test_failed_refund @gateway.expects(:ssl_post).returns(failed_capture_response) response = @gateway.refund(@amount, '') assert_failure response end def test_successful_void @gateway.expects(:ssl_post).returns(successful_void_response) response = @gateway.void('', amount: 300) assert_success response end def test_void_passes_correct_transaction_reference stub_comms do # transaction number from successful authorize response @gateway.void('219388558', amount: 300) end.check_request do |endpoint, data, headers| assert_match(%r(<OriginalTransactionNumber>219388558</OriginalTransactionNumber>)m, data) assert_match(%r(<Amount>300</Amount>)m, data) end.respond_with(successful_void_response) end def test_failed_void @gateway.expects(:ssl_post).returns(failed_void_response) response = @gateway.void('') assert_failure response end def test_successful_verify @gateway.expects(:ssl_post).times(2).returns(successful_verify_response) response = @gateway.verify(@credit_card) assert_success response end def test_successful_verify_with_failed_void response = stub_comms do @gateway.verify(@credit_card) end.respond_with(successful_authorize_response, failed_void_response) assert_success response end def test_failed_verify @gateway.expects(:ssl_post).returns(failed_verify_response) response = @gateway.verify(@credit_card) assert_failure response end def test_scrub assert @gateway.supports_scrubbing? assert_equal @gateway.scrub(pre_scrubbed), post_scrubbed end def test_passing_biller_code stub_comms do @gateway.authorize(@amount, @credit_card, { biller_code: '1234' }) end.check_request do |endpoint, data, headers| assert_match(%r(<BillerCode>1234</BillerCode>)m, data) end.respond_with(successful_authorize_response) end def test_passing_reference_and_crn stub_comms do @gateway.authorize(@amount, @credit_card, @options.merge({ crn1: 'ref' })) end.check_request do |endpoint, data, headers| assert_match(%r(<MerchantReference>1</MerchantReference>)m, data) assert_match(%r(<CRN1>ref</CRN1>)m, data) end.respond_with(successful_authorize_response) end private def pre_scrubbed <<-PRE_SCRUBBED <- "POST /evolve/service_1_4_4.asmx HTTP/1.1\r\nContent-Type: application/soap+xml; charset=utf-8\r\nAccept-Encoding: gzip;q=1.0,deflate;q=0.6,identity;q=0.3\r\nAccept: */*\r\nUser-Agent: Ruby\r\nConnection: close\r\nHost: www.bpoint.com.au\r\nContent-Length: 843\r\n\r\n" <- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">\n <soap12:Body>\n <ProcessPayment xmlns=\"urn:Eve_1_4_4\">\n <username>waysact</username>\n <password>O5dIyDv148</password>\n <merchantNumber>DEMONSTRATION731</merchantNumber>\n <txnReq>\n <PaymentType>PAYMENT</PaymentType>\n <TxnType>WEB_SHOP</TxnType>\n <BillerCode/>\n <MerchantReference/>\n <CRN1/>\n <CRN2/>\n <CRN3/>\n <Amount>100</Amount>\n <CardNumber>4987654321098769</CardNumber>\n <ExpiryDate>9900</ExpiryDate>\n <CVC>123</CVC>\n <OriginalTransactionNumber/>\n </txnReq>\n </ProcessPayment>\n </soap12:Body>\n</soap12:Envelope>\n" -> "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><soap:Body><ProcessPaymentResponse xmlns=\"urn:Eve_1_4_4\"><ProcessPaymentResult><ResponseCode>0</ResponseCode><AcquirerResponseCode>00</AcquirerResponseCode><AuthorisationResult>Approved</AuthorisationResult><TransactionNumber>219617445</TransactionNumber><ReceiptNumber>53559987445</ReceiptNumber><AuthoriseId>122025580862</AuthoriseId><SettlementDate>20150513</SettlementDate><MaskedCardNumber>498765...769</MaskedCardNumber><CardType>VC</CardType></ProcessPaymentResult><response><ResponseCode>SUCCESS</ResponseCode></response></ProcessPaymentResponse></soap:Body></soap:Envelope>" PRE_SCRUBBED end def post_scrubbed <<-POST_SCRUBBED <- "POST /evolve/service_1_4_4.asmx HTTP/1.1\r\nContent-Type: application/soap+xml; charset=utf-8\r\nAccept-Encoding: gzip;q=1.0,deflate;q=0.6,identity;q=0.3\r\nAccept: */*\r\nUser-Agent: Ruby\r\nConnection: close\r\nHost: www.bpoint.com.au\r\nContent-Length: 843\r\n\r\n" <- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">\n <soap12:Body>\n <ProcessPayment xmlns=\"urn:Eve_1_4_4\">\n <username>waysact</username>\n <password>[FILTERED]</password>\n <merchantNumber>DEMONSTRATION731</merchantNumber>\n <txnReq>\n <PaymentType>PAYMENT</PaymentType>\n <TxnType>WEB_SHOP</TxnType>\n <BillerCode/>\n <MerchantReference/>\n <CRN1/>\n <CRN2/>\n <CRN3/>\n <Amount>100</Amount>\n <CardNumber>[FILTERED]</CardNumber>\n <ExpiryDate>9900</ExpiryDate>\n <CVC>[FILTERED]</CVC>\n <OriginalTransactionNumber/>\n </txnReq>\n </ProcessPayment>\n </soap12:Body>\n</soap12:Envelope>\n" -> "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><soap:Body><ProcessPaymentResponse xmlns=\"urn:Eve_1_4_4\"><ProcessPaymentResult><ResponseCode>0</ResponseCode><AcquirerResponseCode>00</AcquirerResponseCode><AuthorisationResult>Approved</AuthorisationResult><TransactionNumber>219617445</TransactionNumber><ReceiptNumber>53559987445</ReceiptNumber><AuthoriseId>122025580862</AuthoriseId><SettlementDate>20150513</SettlementDate><MaskedCardNumber>498765...769</MaskedCardNumber><CardType>VC</CardType></ProcessPaymentResult><response><ResponseCode>SUCCESS</ResponseCode></response></ProcessPaymentResponse></soap:Body></soap:Envelope>" POST_SCRUBBED end def successful_purchase_response %( <?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soap:Body> <ProcessPaymentResponse xmlns="urn:Eve_1_4_4"> <ProcessPaymentResult> <ResponseCode>0</ResponseCode> <AcquirerResponseCode>00</AcquirerResponseCode> <AuthorisationResult>Approved</AuthorisationResult> <TransactionNumber>218990188</TransactionNumber> <ReceiptNumber>53440560188</ReceiptNumber> <AuthoriseId>081017039863</AuthoriseId> <SettlementDate>20150509</SettlementDate> <MaskedCardNumber>498765...769</MaskedCardNumber> <CardType>VC</CardType> </ProcessPaymentResult> <response> <ResponseCode>SUCCESS</ResponseCode> </response> </ProcessPaymentResponse> </soap:Body> </soap:Envelope> ) end def failed_purchase_response %( <?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soap:Body> <ProcessPaymentResponse xmlns="urn:Eve_1_4_4"> <ProcessPaymentResult> <ResponseCode>2</ResponseCode> <AcquirerResponseCode>01</AcquirerResponseCode> <AuthorisationResult>Declined</AuthorisationResult> <TransactionNumber>219013928</TransactionNumber> <ReceiptNumber>53452203928</ReceiptNumber> <AuthoriseId /> <SettlementDate>20150509</SettlementDate> <MaskedCardNumber>498765...769</MaskedCardNumber> <CardType>VC</CardType> </ProcessPaymentResult> <response> <ResponseCode>SUCCESS</ResponseCode> </response> </ProcessPaymentResponse> </soap:Body> </soap:Envelope> ) end def successful_authorize_response %( <?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soap:Body> <ProcessPaymentResponse xmlns="urn:Eve_1_4_4"> <ProcessPaymentResult> <ResponseCode>0</ResponseCode> <AcquirerResponseCode>00</AcquirerResponseCode> <AuthorisationResult>Approved</AuthorisationResult> <TransactionNumber>219388558</TransactionNumber> <ReceiptNumber>53530098558</ReceiptNumber> <AuthoriseId>111751554356</AuthoriseId> <SettlementDate>20150512</SettlementDate> <MaskedCardNumber>498765...769</MaskedCardNumber> <CardType>VC</CardType> </ProcessPaymentResult> <response> <ResponseCode>SUCCESS</ResponseCode> </response> </ProcessPaymentResponse> </soap:Body> </soap:Envelope> ) end alias_method :successful_verify_response, :successful_authorize_response def failed_authorize_response %( <?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soap:Body> <ProcessPaymentResponse xmlns="urn:Eve_1_4_4"> <ProcessPaymentResult> <ResponseCode>2</ResponseCode> <AcquirerResponseCode>01</AcquirerResponseCode> <AuthorisationResult>Declined</AuthorisationResult> <TransactionNumber>219389176</TransactionNumber> <ReceiptNumber>53530629176</ReceiptNumber> <AuthoriseId /> <SettlementDate>20150512</SettlementDate> <MaskedCardNumber>498765...769</MaskedCardNumber> <CardType>VC</CardType> </ProcessPaymentResult> <response> <ResponseCode>SUCCESS</ResponseCode> </response> </ProcessPaymentResponse> </soap:Body> </soap:Envelope> ) end alias_method :failed_verify_response, :failed_authorize_response def successful_capture_response %( <?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soap:Body> <ProcessPaymentResponse xmlns="urn:Eve_1_4_4"> <ProcessPaymentResult> <ResponseCode>0</ResponseCode> <AcquirerResponseCode>00</AcquirerResponseCode> <AuthorisationResult>Approved</AuthorisationResult> <TransactionNumber>219389381</TransactionNumber> <ReceiptNumber>53530769381</ReceiptNumber> <AuthoriseId>111827122671</AuthoriseId> <SettlementDate>20150512</SettlementDate> <MaskedCardNumber>498765...769</MaskedCardNumber> <CardType>VC</CardType> </ProcessPaymentResult> <response> <ResponseCode>SUCCESS</ResponseCode> </response> </ProcessPaymentResponse> </soap:Body> </soap:Envelope> ) end def failed_capture_response %( <?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soap:Body> <ProcessPaymentResponse xmlns="urn:Eve_1_4_4"> <ProcessPaymentResult> <ResponseCode>PT_R1</ResponseCode> <AuthorisationResult>Original transaction not found</AuthorisationResult> <TransactionNumber>219389566</TransactionNumber> <ReceiptNumber>53530899566</ReceiptNumber> <CardType /> </ProcessPaymentResult> <response> <ResponseCode>SUCCESS</ResponseCode> </response> </ProcessPaymentResponse> </soap:Body> </soap:Envelope> ) end def successful_refund_response %( <?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soap:Body> <ProcessPaymentResponse xmlns="urn:Eve_1_4_4"> <ProcessPaymentResult> <ResponseCode>0</ResponseCode> <AcquirerResponseCode>00</AcquirerResponseCode> <AuthorisationResult>Approved</AuthorisationResult> <TransactionNumber>219391527</TransactionNumber> <ReceiptNumber>53532101527</ReceiptNumber> <AuthoriseId>111939009260</AuthoriseId> <SettlementDate>20150512</SettlementDate> <MaskedCardNumber>498765...769</MaskedCardNumber> <CardType>VC</CardType> </ProcessPaymentResult> <response> <ResponseCode>SUCCESS</ResponseCode> </response> </ProcessPaymentResponse> </soap:Body> </soap:Envelope> ) end def failed_refund_response %( <?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soap:Body> <ProcessPaymentResponse xmlns="urn:Eve_1_4_4"> <ProcessPaymentResult> <ResponseCode>PT_R1</ResponseCode> <AuthorisationResult>Original transaction not found</AuthorisationResult> <TransactionNumber>219395831</TransactionNumber> <ReceiptNumber>53533405831</ReceiptNumber> <CardType /> </ProcessPaymentResult> <response> <ResponseCode>SUCCESS</ResponseCode> </response> </ProcessPaymentResponse> </soap:Body> </soap:Envelope> ) end def successful_void_response %( <?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soap:Body> <ProcessPaymentResponse xmlns="urn:Eve_1_4_4"> <ProcessPaymentResult> <ResponseCode>0</ResponseCode> <AcquirerResponseCode>00</AcquirerResponseCode> <AuthorisationResult>Approved</AuthorisationResult> <TransactionNumber>219397643</TransactionNumber> <ReceiptNumber>53533757643</ReceiptNumber> <AuthoriseId>112107050623</AuthoriseId> <SettlementDate>20150512</SettlementDate> <MaskedCardNumber>498765...769</MaskedCardNumber> <CardType>VC</CardType> </ProcessPaymentResult> <response> <ResponseCode>SUCCESS</ResponseCode> </response> </ProcessPaymentResponse> </soap:Body> </soap:Envelope> ) end def failed_void_response %( <?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soap:Body> <ProcessPaymentResponse xmlns="urn:Eve_1_4_4"> <ProcessPaymentResult> <ResponseCode>PT_R1</ResponseCode> <AuthorisationResult>Original transaction not found</AuthorisationResult> <TransactionNumber>219397820</TransactionNumber> <ReceiptNumber>53533887820</ReceiptNumber> <CardType /> </ProcessPaymentResult> <response> <ResponseCode>SUCCESS</ResponseCode> </response> </ProcessPaymentResponse> </soap:Body> </soap:Envelope> ) end def successful_store_response %( <?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soap:Body> <AddTokenResponse xmlns="urn:Eve_1_4_4"> <AddTokenResult> <Token>5999992142370790</Token> <MaskedCardNumber>498765...769</MaskedCardNumber> <CardType>VC</CardType> </AddTokenResult> <response> <ResponseCode>SUCCESS</ResponseCode> </response> </AddTokenResponse> </soap:Body> </soap:Envelope> ) end def failed_store_response %( <?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soap:Body> <AddTokenResponse xmlns="urn:Eve_1_4_4"> <AddTokenResult /> <response> <ResponseCode>ERROR</ResponseCode> <ResponseMessage>invalid card number: invalid length</ResponseMessage> </response> </AddTokenResponse> </soap:Body> </soap:Envelope> ) end end
17,991
https://github.com/dlang/tools/blob/master/contributors.d
Github Open Source
Open Source
BSL-1.0
2,023
tools
dlang
D
Code
470
1,551
#!/usr/bin/env rdmd /** Query contributors between two D releases. Copyright: D Language Foundation 2017. License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0). Example usage: --- ./contributors.d "v2.074.0..v2.075.0" --- Author: Sebastian Wilzbach */ import std.array; import std.algorithm; import std.conv; import std.exception; import std.file; import std.format; import std.process; import std.path; import std.range; import std.stdio; import std.string; import std.typecons; /// Name <my@email.com> struct GitAuthor { string name, email; string toString() { return "%s <%s>".format(name, email); } } /// Options for finding authors struct FindConfig { bool refreshTags; /// will query github.com for new tags bool noMerges; // will ignore merge commits bool showAllContributors; // will ignore the revRange and show all contributors string cwd; // working directory (should be tools) string mailmapFile; // location to the .mailmap file } /** Search all git commit messages within revRange of all D repositories Returns: Array that maps each git `Author: ...` line to a GitAuthor */ auto findAuthors(string revRange, FindConfig config) { Appender!(GitAuthor[]) authors; int commits; auto repos = ["dmd", "phobos", "dlang.org", "tools", "installer"]; if (config.showAllContributors) repos ~= ["dub", "dub-registry", "dconf.org"]; foreach (repo; repos.map!(r => buildPath(config.cwd, "..", r))) { if (!repo.exists) { stderr.writefln("Warning: %s doesn't exist. " ~ "Consider running: git clone https://github.com/dlang/%s ../%2$s", repo, repo.baseName); continue; } if (config.refreshTags) { auto cmd = ["git", "-C", repo, "fetch", "--tags", "https://github.com/dlang/" ~ repo.baseName, "+refs/heads/*:refs/remotes/upstream/*"]; auto p = pipeProcess(cmd, Redirect.stdout); enforce(wait(p.pid) == 0, "Failed to execute '%(%s %)'.".format(cmd)); } auto cmd = ["git", "-c", "mailmap.file=%s".format(config.mailmapFile), "-C", repo, "log", "--use-mailmap", "--pretty=format:%aN|%aE"]; if (!config.showAllContributors) cmd ~= revRange; if (config.noMerges) cmd ~= "--no-merges"; auto p = pipeProcess(cmd, Redirect.stdout); scope(exit) enforce(wait(p.pid) == 0, "Failed to execute '%(%s %)'.".format(cmd)); authors ~= p.stdout .byLineCopy .tee!(_ => commits++) .map!((line){ auto ps = line.splitter("|"); return GitAuthor(ps.front, ps.dropOne.front); }) .filter!(a => a.name != "The Dlang Bot"); } if (!config.showAllContributors) stderr.writefln("Looked at %d commits in %s", commits, revRange); else stderr.writefln("Looked at %d commits", commits); return authors.data; } /// Sorts the authors and filters for duplicates auto reduceAuthors(GitAuthors)(GitAuthors authors) { import std.uni : sicmp; return authors .sort!((a, b) => sicmp(a.name, b.name) < 0) .uniq!((a, b) => a.name == b.name); } version(Contributors_Lib) {} else int main(string[] args) { import std.getopt; string revRange; FindConfig config = { cwd: __FILE_FULL_PATH__.dirName.asNormalizedPath.to!string, }; config.mailmapFile = config.cwd.buildPath(".mailmap"); enum PrintMode { name, markdown, ddoc, csv, git} PrintMode printMode; auto helpInformation = getopt( args, std.getopt.config.passThrough, "f|format", "Result format (name, markdown, ddoc, csv, git)", &printMode, "a|all", "Show all contributors", &config.showAllContributors, "refresh-tags", "Refresh tags", &config.refreshTags, "no-merges", "Ignore merge commits", &config.noMerges, ); if (helpInformation.helpWanted || (args.length < 2 && !config.showAllContributors)) { `D contributors extractor. ./contributors.d "v2.075.0..v2.076.0"`.defaultGetoptPrinter(helpInformation.options); return 1; } revRange = args.length > 1 ? args[1] : null; revRange.findAuthors(config) .reduceAuthors .each!((a){ with(PrintMode) final switch (printMode) { case name: a.name.writeln; break; case markdown: writefln("- %s", a.name); break; case ddoc: writefln("$(D_CONTRIBUTOR %s)", a.name); break; case csv: writefln("%s, %s", a.name, a.email); break; case git: writefln("%s <%s>", a.name, a.email); break; } }); return 0; }
31,718
https://github.com/we4tech/restaurant-review-mobile/blob/master/Resources/window_nearby.js
Github Open Source
Open Source
Apache-2.0
2,011
restaurant-review-mobile
we4tech
JavaScript
Code
109
349
// // Create Window for nearby restaurants // var nearbyWindow = Titanium.UI.createWindow({ title: 'Nearby Restaurants', backgroundColor: '#fff' }); var nearbyTab = Titanium.UI.createTab({ icon: 'icon_nearby.png', title: 'Nearby', window: nearbyWindow }); var nearbyTableHeader = Ti.UI.createLabel({ text: ' Restaurants near to YOU!', top: 0, left: 0, height: 30, //backgroundColor: '#FFFFCC', backgroundImage: 'searchbar_bg.png', color: '#fff' }); var nearbyResultView = Titanium.UI.createTableView({ backgroundColor:"white", data: [ { title: 'Searching nearby restaurants...' } ], separatorColor: "white", top: 0, width:320, headerView: nearbyTableHeader }); // Add events nearbyWindow.addEventListener('open', function(e) { // Retrieve current location SearchService.findLocation(function(lng, lat) { var options = {}; options.keywords = ''; options.lat = lat; options.lng = lng; SearchService.search(options, nearbyResultView); }); }); // Add to window nearbyWindow.add(nearbyResultView);
2,263
https://github.com/gregzakh/sketches/blob/master/cpp/curpshndlvals.cpp
Github Open Source
Open Source
MIT
2,022
sketches
gregzakh
C++
Code
147
514
#ifndef UNICODE #define UNICODE #endif #include <windows.h> #include <winternl.h> #include <iostream> #include <string> #include <vector> #include <locale> typedef LONG NTSTATUS; #pragma comment (lib, "ntdll.lib") #define ProcessHandleTable (static_cast<PROCESSINFOCLASS>(58)) #define NtCurrentProcess() (reinterpret_cast<HANDLE>(static_cast<LONG_PTR>(-1))) int wmain(void) { using namespace std; locale::global(locale("")); auto getlasterror = [](NTSTATUS nts) { HLOCAL loc{}; DWORD size = FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, nullptr, RtlNtStatusToDosError(nts), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<LPWSTR>(&loc), 0, nullptr ); if (!size) wcout << L"[?] Unknown error has been occured." << endl; else { wstring msg(reinterpret_cast<LPWSTR>(loc)); wcout << L"[!] " << msg.substr(0, size - sizeof(WCHAR)) << endl; } if (nullptr != LocalFree(loc)) wcout << L"LocalFree (" << GetLastError() << L") fatal error." << endl; }; vector<ULONG> buf(0x400); NTSTATUS nts = NtQueryInformationProcess( NtCurrentProcess(), ProcessHandleTable, &buf[0], buf.size(), nullptr ); if (!NT_SUCCESS(nts)) { getlasterror(nts); return 1; } for (const auto val : buf) { if (0 == val) break; wcout << hex << val << endl; } return 0; }
43,323
https://github.com/quangdangfit/go-admin/blob/master/app/middleware/cache/gredis.go
Github Open Source
Open Source
MIT
2,021
go-admin
quangdangfit
Go
Code
316
887
package cache import ( "context" "encoding/json" "fmt" "time" "github.com/go-redis/redis/v8" "github.com/quangdangfit/gocommon/logger" "github.com/quangdangfit/go-admin/config" ) // constants cache const ( RedisExpiredTimes = 600 ) var ctx = context.Background() // GRedis struct type GRedis struct { client *redis.Client expiryTime int } // NewRedis new redis pointer func NewRedis() *GRedis { redisConfig := config.Config.Redis rdb := redis.NewClient(&redis.Options{ Addr: fmt.Sprintf("%s:%d", redisConfig.Host, redisConfig.Port), Password: redisConfig.Password, DB: redisConfig.Database, }) pong, err := rdb.Ping(ctx).Result() if err != nil { logger.Error(pong, err) return nil } expiryTime := config.Config.Cache.ExpiryTime if expiryTime <= 0 { expiryTime = RedisExpiredTimes } return &GRedis{client: rdb, expiryTime: expiryTime} } // IsConnected check redis is connected or not func (g *GRedis) IsConnected() bool { if g.client == nil { return false } _, err := g.client.Ping(ctx).Result() if err != nil { return false } return true } // Get get key from redis func (g *GRedis) Get(key string, data interface{}) error { val, err := g.client.Get(ctx, key).Bytes() if err == redis.Nil { return nil } if err != nil { logger.Info("Cache fail to get: ", err) return nil } logger.Debugf("Get from redis %s - %s", key, val) err = json.Unmarshal(val, &data) if err != nil { return err } return nil } // Set data to redis func (g *GRedis) Set(key string, val []byte) error { err := g.client.Set(ctx, key, val, time.Duration(g.expiryTime)*time.Second).Err() if err != nil { logger.Error("Cache fail to set: ", err) return err } logger.Debugf("Set to redis %s - %s", key, val) return nil } // Remove return list keys from redis func (g *GRedis) Remove(keys ...string) error { err := g.client.Del(ctx, keys...).Err() if err != nil { logger.Errorf("Cache fail to delete key %s: %s", keys, err) return err } logger.Debug("Cache deleted key", keys) return nil } // Keys get redis keys by pattern regex func (g *GRedis) Keys(pattern string) ([]string, error) { keys, err := g.client.Keys(ctx, pattern).Result() if err != nil { return nil, err } return keys, nil }
7,342
https://github.com/goofwear/FormatDialogs/blob/master/dialogsearchstrings.cpp
Github Open Source
Open Source
MIT
2,020
FormatDialogs
goofwear
C++
Code
312
1,072
// copyright (c) 2019-2020 hors<horsicq@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #include "dialogsearchstrings.h" #include "ui_dialogsearchstrings.h" DialogSearchStrings::DialogSearchStrings(QWidget *parent) : QDialog(parent), ui(new Ui::DialogSearchStrings) { ui->setupUi(this); pHandleStrings=new SearchStrings; pHandleModel=new SearchStrings; pThreadSearch=new QThread; pThreadModel=new QThread; pHandleStrings->moveToThread(pThreadSearch); pHandleModel->moveToThread(pThreadModel); connect(pThreadSearch, SIGNAL(started()), pHandleStrings, SLOT(processSearch())); connect(pHandleStrings, SIGNAL(completed(qint64)), this, SLOT(onCompleted(qint64))); connect(pHandleStrings, SIGNAL(errorMessage(QString)), this, SLOT(errorMessage(QString))); connect(pHandleStrings, SIGNAL(progressValue(qint32)), this, SLOT(progressValue(qint32))); connect(pThreadModel, SIGNAL(started()), pHandleModel, SLOT(processModel())); connect(pHandleModel, SIGNAL(completed(qint64)), this, SLOT(onCompleted(qint64))); connect(pHandleModel, SIGNAL(errorMessage(QString)), this, SLOT(errorMessage(QString))); connect(pHandleModel, SIGNAL(progressValue(qint32)), this, SLOT(progressValue(qint32))); ui->progressBar->setMaximum(100); ui->progressBar->setMinimum(0); } DialogSearchStrings::~DialogSearchStrings() { pHandleStrings->stop(); pHandleModel->stop(); pThreadSearch->quit(); pThreadSearch->wait(); pThreadModel->quit(); pThreadModel->wait(); delete ui; delete pThreadSearch; delete pThreadModel; delete pHandleStrings; delete pHandleModel; } void DialogSearchStrings::processSearch(QIODevice *pDevice, QList<SearchStrings::RECORD> *pListRecords, SearchStrings::OPTIONS *pOptions) { setWindowTitle(tr("Search strings")); pHandleStrings->setSearchData(pDevice,pListRecords,pOptions); pThreadSearch->start(); } void DialogSearchStrings::processModel(QList<SearchStrings::RECORD> *pListRecords, QStandardItemModel **ppModel, SearchStrings::OPTIONS *pOptions) { setWindowTitle(tr("Create view model")); pHandleModel->setModelData(pListRecords,ppModel,pOptions); pThreadModel->start(); } void DialogSearchStrings::on_pushButtonCancel_clicked() { pHandleStrings->stop(); pHandleModel->stop(); } void DialogSearchStrings::errorMessage(QString sText) { QMessageBox::critical(this,tr("Error"),sText); } void DialogSearchStrings::onCompleted(qint64 nElapsed) { Q_UNUSED(nElapsed) this->close(); } void DialogSearchStrings::progressValue(qint32 nValue) { ui->progressBar->setValue(nValue); }
16,532
https://github.com/kutenai/sharpertool/blob/master/django_root/sharpertool/settings/dev.py
Github Open Source
Open Source
MIT
2,015
sharpertool
kutenai
Python
Code
32
120
print("Loading development settings.") from .base import * DEBUG = True TEMPLATE_DEBUG = DEBUG # Make this unique, and don't share it with anybody. SECRET_KEY = "bungus" RAVEN_CONFIG = { 'dsn': 'https://53acba3177ec4ce4be06cca3ba5602f3:4ee592373d8c41968c730327cfb6b808@app.getsentry.com/41135', }
19,204
https://github.com/hkalodner/buidler-issue/blob/master/contracts/Test.sol
Github Open Source
Open Source
Apache-2.0
null
buidler-issue
hkalodner
Solidity
Code
22
67
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.5.11; contract Test { string public constant test = "test"; function shutdown() external { selfdestruct(msg.sender); } }
41,672
https://github.com/getodk/collect/blob/master/collect_app/src/androidTest/java/org/odk/collect/android/feature/formentry/FormFinalizingTest.kt
Github Open Source
Open Source
Apache-2.0
2,023
collect
getodk
Kotlin
Code
138
990
package org.odk.collect.android.feature.formentry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Rule import org.junit.Test import org.junit.rules.RuleChain import org.junit.runner.RunWith import org.odk.collect.android.R import org.odk.collect.android.support.pages.AccessControlPage import org.odk.collect.android.support.pages.FormEntryPage import org.odk.collect.android.support.pages.MainMenuPage import org.odk.collect.android.support.pages.ProjectSettingsPage import org.odk.collect.android.support.pages.SaveOrDiscardFormDialog import org.odk.collect.android.support.rules.CollectTestRule import org.odk.collect.android.support.rules.TestRuleChain.chain @RunWith(AndroidJUnit4::class) class FormFinalizingTest { private val rule = CollectTestRule() @get:Rule val copyFormChain: RuleChain = chain().around(rule) @Test fun fillingForm_andPressingFinalize_finalizesForm() { rule.startAtMainMenu() .copyForm(FORM) .assertNumberOfFinalizedForms(0) .startBlankForm("One Question") .fillOutAndFinalize(FormEntryPage.QuestionAndAnswer("what is your age", "52")) .assertNumberOfEditableForms(0) .assertNumberOfFinalizedForms(1) } @Test fun fillingForm_andPressingSaveAsDraft_doesNotFinalizesForm() { rule.startAtMainMenu() .copyForm(FORM) .assertNumberOfFinalizedForms(0) .startBlankForm("One Question") .swipeToEndScreen() .clickSaveAsDraft() .assertNumberOfEditableForms(1) .assertNumberOfFinalizedForms(0) } @Test fun fillingForm_andPressingBack_andPressingSave_doesNotFinalizesForm() { rule.startAtMainMenu() .copyForm(FORM) .assertNumberOfFinalizedForms(0) .startBlankForm("One Question") .closeSoftKeyboard() .pressBack(SaveOrDiscardFormDialog(MainMenuPage())) .clickSaveChanges() .assertNumberOfEditableForms(1) .assertNumberOfFinalizedForms(0) } @Test fun disablingSaveAsDraftInSettings_disablesItInTheEndScreen() { rule.startAtMainMenu() .openProjectSettingsDialog() .clickSettings() .clickAccessControl() .clickFormEntrySettings() .clickOnSaveAsDraftInFormEnd() .pressBack(AccessControlPage()) .pressBack(ProjectSettingsPage()) .pressBack(MainMenuPage()) .copyForm(FORM) .startBlankForm("One Question") .swipeToEndScreen() .assertTextDoesNotExist(org.odk.collect.strings.R.string.save_as_draft) } @Test fun disablingFinalizeInSettings_disablesItInTheEndScreen() { rule.startAtMainMenu() .openProjectSettingsDialog() .clickSettings() .clickAccessControl() .clickFormEntrySettings() .clickOnString(org.odk.collect.strings.R.string.finalize) .pressBack(AccessControlPage()) .pressBack(ProjectSettingsPage()) .pressBack(MainMenuPage()) .copyForm(FORM) .startBlankForm("One Question") .swipeToEndScreen() .assertTextDoesNotExist(org.odk.collect.strings.R.string.finalize) } companion object { private const val FORM = "one-question.xml" } }
38,282
https://github.com/bettio/qt5-configuration-plugins/blob/master/qml/settings/hemeraqmlsimpleqmlapplication.h
Github Open Source
Open Source
Apache-2.0
2,021
qt5-configuration-plugins
bettio
C++
Code
154
431
/* * */ #ifndef HEMERA_QML_SETTINGS_SIMPLEQMLAPPLICATION_H #define HEMERA_QML_SETTINGS_SIMPLEQMLAPPLICATION_H #include "hemeraqmlsimplecppapplication.h" namespace Hemera { namespace Qml { namespace Settings { class SimpleQmlApplicationPrivate; /** * @class SimpleQmlApplication * @ingroup HemeraQmlSettings * * @brief SimpleQmlApplication is used to create a QtQuick2 QML-only application, with no C++ logic. * * If your QtQuick2 application features no C++ logic, you can use SimpleQmlApplication to automatically * build and generate an Hemera application from your QML files. Specify them as resourceFiles, and * point to the mainQmlFile, the rest will be done automatically. */ class SimpleQmlApplication : public Hemera::Qml::Settings::SimpleCppApplication { Q_OBJECT Q_DISABLE_COPY(SimpleQmlApplication) Q_DECLARE_PRIVATE(SimpleQmlApplication) /** * The main QML file. It needs to be installed with resourceFiles, and will be the QML file started * by the engine when the application is launched. */ Q_PROPERTY(QString mainQmlFile READ mainQmlFile WRITE setMainQmlFile) public: explicit SimpleQmlApplication(QObject *parent = nullptr); virtual ~SimpleQmlApplication(); QString mainQmlFile() const; void setMainQmlFile(const QString &name); }; } } } #endif // HEMERA_QML_SETTINGS_SIMPLEQMLAPPLICATION_H
22,727
https://github.com/Knappek/mongodbatlas-operator/blob/master/vendor/github.com/operator-framework/operator-sdk/internal/util/k8sutil/object.go
Github Open Source
Open Source
Apache-2.0
2,019
mongodbatlas-operator
Knappek
Go
Code
112
341
package k8sutil import ( yaml "github.com/ghodss/yaml" "k8s.io/apimachinery/pkg/runtime" ) // GetObjectBytes marshalls an object and removes runtime-managed fields: // 'status', 'creationTimestamp' func GetObjectBytes(obj interface{}) ([]byte, error) { u, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj) if err != nil { return nil, err } deleteKeys := []string{"status", "creationTimestamp"} for _, dk := range deleteKeys { deleteKeyFromUnstructured(u, dk) } return yaml.Marshal(u) } func deleteKeyFromUnstructured(u map[string]interface{}, key string) { if _, ok := u[key]; ok { delete(u, key) return } for _, v := range u { switch t := v.(type) { case map[string]interface{}: deleteKeyFromUnstructured(t, key) case []interface{}: for _, ti := range t { if m, ok := ti.(map[string]interface{}); ok { deleteKeyFromUnstructured(m, key) } } } } }
15,480
https://github.com/Activiti/Activiti/blob/master/activiti-api/activiti-api-process-model/src/main/java/org/activiti/api/process/model/builders/CreateProcessPayloadBuilder.java
Github Open Source
Open Source
Apache-2.0
2,023
Activiti
Activiti
Java
Code
178
427
/* * Copyright 2010-2020 Alfresco Software, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.activiti.api.process.model.builders; import org.activiti.api.process.model.payloads.CreateProcessInstancePayload; public class CreateProcessPayloadBuilder { private String processDefinitionId; private String processDefinitionKey; private String name; private String businessKey; public CreateProcessPayloadBuilder() { } public CreateProcessPayloadBuilder withProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; return this; } public CreateProcessPayloadBuilder withName(String name) { this.name = name; return this; } public CreateProcessPayloadBuilder withProcessDefinitionKey(String processDefinitionKey) { this.processDefinitionKey = processDefinitionKey; return this; } public CreateProcessPayloadBuilder withBusinessKey(String businessKey) { this.businessKey = businessKey; return this; } public CreateProcessInstancePayload build() { return new CreateProcessInstancePayload(processDefinitionId, processDefinitionKey, name, businessKey); } }
2,580
https://github.com/AtriCZE23/POe-full/blob/master/PoE-Overlay-master/src/app/modules/market/component/market-panel-group/market-panel-group.component.spec.ts
Github Open Source
Open Source
MIT, CNRI-Python-GPL-Compatible, BSD-3-Clause
2,020
POe-full
AtriCZE23
TypeScript
Code
52
193
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { MarketPanelGroupComponent } from './market-panel-group.component'; describe('MarketPanelGroupComponent', () => { let component: MarketPanelGroupComponent; let fixture: ComponentFixture<MarketPanelGroupComponent>; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ declarations: [MarketPanelGroupComponent] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(MarketPanelGroupComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
48,225
https://github.com/jack5315/FedBE/blob/master/models/FedM.py
Github Open Source
Open Source
Apache-2.0
2,021
FedBE
jack5315
Python
Code
134
476
#!/usr/bin/env python # -*- coding: utf-8 -*- # Python version: 3.6 import copy import torch from torch import nn import numpy as np def create_local_init(glob, local, bias_ratio): assert bias_ratio <=1.0 and bias_ratio >= 0.0 for k in glob.keys(): if bias_ratio > 0: glob[k] = glob[k]*(1-bias_ratio) + local[k]*(bias_ratio) else: glob[k] = (glob[k]+local[k]*bias_ratio)/(1.0 + bias_ratio) return glob def FedAvgM(w, gpu, w_org, mom, size_arr=None): (global_w, momentum) = w_org w_avg = {} for k in w[0].keys(): w_avg[k] = torch.zeros(w[0][k].size()) w_mom = dict(w_avg) # Prepare p if size_arr is not None: total_num = np.sum(size_arr) size_arr = np.array([float(p)/total_num for p in size_arr])*len(size_arr) else: size_arr = np.array([1.0]*len(size_arr)) for k in w_avg.keys(): for i in range(0, len(w)): grad = global_w[k] - w[i][k] w_avg[k] += size_arr[i]*grad mom_k = torch.div(w_avg[k], len(w))*(1-mom) + momentum[k]*mom w_avg[k] = global_w[k] - mom_k w_mom[k] = mom_k return w_avg, w_mom
10,731
https://github.com/superzanttu/ansible-awx-demo/blob/master/local_config.sh
Github Open Source
Open Source
MIT
2,021
ansible-awx-demo
superzanttu
Shell
Code
6
28
#!/bin/bash ansible-playbook -i local_inventory -K local_config.yml
48,286
https://github.com/s-expressionists/Eclector/blob/master/test/code-reading-utilities.lisp
Github Open Source
Open Source
BSD-2-Clause
2,023
Eclector
s-expressionists
Common Lisp
Code
106
416
(cl:in-package #:eclector.test) (defun map-all-system-files (function &key (systems '("eclector" "eclector/test" "eclector-concrete-syntax-tree" "eclector-concrete-syntax-tree/test")) (filter (constantly t))) (labels ((map-component-files (component) (typecase component (asdf:source-file (when (and (equal (asdf:file-type component) "lisp") #-sbcl (not (eq (asdf/component:component-if-feature component) :sbcl))) (list (funcall function component)))) (asdf:module (let ((children (asdf:component-children component))) (mapcan #'map-component-files children)))))) (alexandria:mappend (lambda (system-name) (when (funcall filter system-name) (let ((system (asdf:find-system system-name))) (map-component-files system)))) systems))) (defun map-all-system-expressions (function reader &rest args &key systems filter) (declare (ignore systems filter)) (apply #'map-all-system-files (lambda (file) (let ((filename (asdf:component-pathname file))) (alexandria:with-input-from-file (stream filename) (loop for form-number from 0 for object = (funcall reader stream nil stream) until (eq object stream) do (funcall function filename form-number object))))) args))
36,609
https://github.com/NoobsEnslaver/loris/blob/master/utils/test_call.js
Github Open Source
Open Source
Apache-2.0
2,018
loris
NoobsEnslaver
JavaScript
Code
579
2,126
var host = window.location.origin; var connection; var token = ""; var loginPage = document.querySelector('#login-page'), msisdnInput = document.querySelector('#msisdn'), codeInput = document.querySelector('#code'), loginButton = document.querySelector('#login'), callPage = document.querySelector('#call-page'), theirMSISDNInput = document.querySelector('#their-msisdn'), callButton = document.querySelector('#call'), hangUpButton = document.querySelector('#hang-up'), sendsmsButton = document.querySelector('#send_sms'); var yourVideo = document.querySelector('#yours'), theirVideo = document.querySelector('#theirs'), yourConnection, connectedUser, stream, my_turn; callPage.style.display = "none"; // Login when the user clicks the button loginButton.addEventListener("click", function (event) { var xhr = new XMLHttpRequest(); var body = {msisdn: parseInt(msisdnInput.value), sms_code: parseInt(codeInput.value)}; xhr.open("POST", host + "/v3/auth/json", false); xhr.onloadend = function (e) { var resp = e.target.response; token = JSON.parse(resp).token; console.log("sucessfuly authorized, token: ", token); loginPage.style.display = "none"; callPage.style.display = "block"; // Get the plumbing ready for a call startConnection(); }; xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8'); xhr.send(JSON.stringify(body)); var url = "wss://" + window.location.host + "/session/" + token + "/ws/v1/chat"; connection = new WebSocket(url, ["msgpack"]); connection.binaryType = "arraybuffer"; connection.onopen = function () { console.log("Connected"); send({msg_type: 39}); }; connection.onmessage = function (message) { var Data = new Uint8Array(message.data); var data = msgpack.decode(Data); console.log("Got message", data); switch(data.msg_type) { case 119: var their_turn = { "iceServers": [{ url: 'turn:' + data.turn_server.adress + ':' + data.turn_server.port, username: data.turn_server.username, credential: data.turn_server.credential, credentialType: data.turn_server.credential_type }] }; send({msg_type: 35}); if(window.confirm("Receive call from " + data.msisdn + " ?")){ onOffer(data.msisdn, {type: "offer", sdp: data.sdp}, their_turn); } else{ hangUpButton.click(); } break; case 120: onAck(); break; case 121: onCandidate(JSON.parse(data.candidate)); break; case 122: onLeave(data.code); break; case 123: onAnswer({type: "answer", sdp: data.sdp}); break; case 124: my_turn = { "iceServers": [{ url: 'turn:' + data.adress + ':' + data.port, username: data.username, credential: data.credential, credentialType: data.credential_type }] }; break; default: console.log("unexpected msg: ", data); break; } }; connection.onerror = function (err) { console.log("Got error", err); }; }); sendsmsButton.addEventListener("click", function (event) { var xhr = new XMLHttpRequest(); var body = {msisdn: parseInt(msisdnInput.value)}; xhr.open("POST", host + "/v1/sms", true); xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8'); xhr.send(JSON.stringify(body)); xhr.onloadend = function () { console.log("sms sucessfuly sended"); }; }); function onAck(){ return {}; } function send(message) { var serialized_data = msgpack.encode(message); connection.send(serialized_data); }; callButton.addEventListener("click", function () { var theirUsername = parseInt(theirMSISDNInput.value); startPeerConnection(theirUsername); }); hangUpButton.addEventListener("click", function () { send({ msg_type: 37, code: 200 }); onLeave(); }); function onOffer(name, offer, turn) { setupPeerConnection(turn); connectedUser = name; yourConnection.setRemoteDescription(new RTCSessionDescription(offer)); yourConnection.createAnswer(function (answer) { yourConnection.setLocalDescription(answer); send({ msg_type: 38, sdp: answer.sdp }); }, function (error) { alert("An error has occurred"); }); }; function onAnswer(answer) { yourConnection.setRemoteDescription(new RTCSessionDescription(answer)); }; function onCandidate(candidate) { yourConnection.addIceCandidate(new RTCIceCandidate(candidate)); }; function onLeave(Code) { connectedUser = null; theirVideo.src = null; yourConnection.close(); yourConnection.onicecandidate = null; yourConnection.onaddstream = null; setupPeerConnection(my_turn); console.log("Connection closed with code: %o", Code); }; function hasUserMedia() { navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; return !!navigator.getUserMedia; }; function hasRTCPeerConnection() { window.RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection; window.RTCSessionDescription = window.RTCSessionDescription || window.webkitRTCSessionDescription || window.mozRTCSessionDescription; window.RTCIceCandidate = window.RTCIceCandidate || window.webkitRTCIceCandidate || window.mozRTCIceCandidate; return !!window.RTCPeerConnection; }; function startConnection() { if (hasUserMedia()) { navigator.getUserMedia({ video: true, audio: true }, function (myStream) { stream = myStream; //yourVideo.src = window.URL.createObjectURL(stream); if (hasRTCPeerConnection()) { } else { alert("Sorry, your browser does not support WebRTC."); } }, function (error) { console.log(error); }); } else { alert("Sorry, your browser does not support WebRTC."); } }; function setupPeerConnection(config) { yourConnection = new RTCPeerConnection(config); // Setup stream listening yourConnection.addStream(stream); yourConnection.onaddstream = function (e) { theirVideo.src = window.URL.createObjectURL(e.stream); }; // Setup ice handling yourConnection.onicecandidate = function (event) { if (event.candidate) { send({ msg_type: 36, candidate: JSON.stringify(event.candidate) }); } }; }; function startPeerConnection(user) { connectedUser = user; setupPeerConnection(my_turn); // Begin the offer yourConnection.createOffer(function (offer) { send({ msg_type: 34, msisdn: user, sdp: offer.sdp }); yourConnection.setLocalDescription(offer); }, function (error) { alert("An error has occurred."); }); };
7,637
https://github.com/andredezzy/exercises-runner/blob/master/src/main/java/me/andredezzy/exercisesrunner/exercises/oop/learning/Main.java
Github Open Source
Open Source
MIT
null
exercises-runner
andredezzy
Java
Code
40
197
package me.andredezzy.exercisesrunner.exercises.oop.learning; import me.andredezzy.exercisesrunner.exercises.Exercise; import me.andredezzy.exercisesrunner.exercises.oop.learning.models.Secretary; import java.util.ArrayList; import java.util.Arrays; public class Main implements Exercise { @Override public void run(String[] args) { ArrayList<Secretary> secretaries = new ArrayList<>(); Secretary secretary1 = new Secretary(1); secretary1.setName("Ana"); secretaries.add(secretary1); System.out.println("Lista de secretárias:"); System.out.println(Arrays.toString(secretaries.toArray())); } }
12,184
https://github.com/blakemcbride/PC-LISP/blob/master/src/bufopen.c
Github Open Source
Open Source
BSD-2-Clause
2,022
PC-LISP
blakemcbride
C
Code
262
549
/* | PC-LISP (C) 1984-1989 Peter J.Ashwood-Smith */ #include <stdio.h> #include <math.h> #include "lisp.h" /************************************************************************* ** bufopen: Open file with mode returns a new opened filecell. Note ** ** that since a string or atom is allowed for either parameter we may ** ** have to make an atom before linking into the file cell fname field. ** ** Note that the insert/new order avoids having to push the fcell. ** ** After the file is successfully opened, we call routine buresetlog ** ** with parameter fd and 1 to tell it we just opened 'fd'. It will use ** ** this information if ever a (resetio) is done by the user. bufclose ** ** will call buresetlog with fd and 0 to indicate a close. ** ** ************************************ ** ** NOTE that CreateInterned and MakePort allocate space hence strings ** ** may be relocated. Because of this the name must be copied to a temp ** ** buffer first. This is true of all calls to GetString so be carefull,** ** this took me several days to track down with a very spurious error. ** *************************************************************************/ struct conscell *bufopen(form) struct conscell *form; { char *fname, *fmode; FILE *fd,*fopen(); char name[MAXATOMSIZE + 1]; if ((form != NULL)&&(GetString(form->carp,&fname))) { form = form->cdrp; strcpy(name, fname); /* 'fname' could get relocated! so copy it */ if ((form!=NULL)&&(GetString(form->carp,&fmode))&&(form->cdrp==NULL)) { if ((fd = fopen(fname,fmode)) == NULL) { errno = 0; /* don't want apply to catch it */ return(NULL); } buresetlog(fd,1); return(LIST(MakePort(fd,CreateInternedAtom(name)))); } } ierror("fileopen"); /* doesn't return */ return NULL; /* keep compiler happy */ }
22,494
https://github.com/sqmedeiros/pegparser/blob/master/test/java18/test/no/InterfaceBodyErr.java
Github Open Source
Open Source
MIT
2,021
pegparser
sqmedeiros
Java
Code
4
10
public interface InterfaceBodyErr }
41,840
https://github.com/codeages/qiqiuyun-player-ios-sdk/blob/master/Example/QiqiuyunPlayerSDK/Video/ControlView/ESPopoverView.h
Github Open Source
Open Source
MIT
null
qiqiuyun-player-ios-sdk
codeages
C
Code
109
439
// // ESPopoverView.h // EduSoho // // Created by Edusoho on 14-10-10. // Copyright (c) 2015年 Kuozhi Network Technology. All rights reserved. // #import <UIKit/UIKit.h> typedef NS_ENUM(NSUInteger, ESPopoverAnimationType) { ESPopoverAnimationNone = 0, ESPopoverAnimationTypeLinear, ESPopoverAnimationTypeScale }; @interface ESPopoverView : UIViewController - (instancetype)initWithView:(UIView *)view titles:(NSArray *)titles images:(NSArray <UIImage *>*)images; - (instancetype)initWithEvent:(UIEvent *)event titles:(NSArray *)titles images:(NSArray <UIImage *>*)images; - (instancetype)initWithPoint:(CGPoint)point titles:(NSArray *)titles images:(NSArray <UIImage *>*)images; - (void)show; - (void)showWithAnimationType:(ESPopoverAnimationType)animationType; - (void)dismiss:(BOOL)animated; - (void)reloadIndex:(NSInteger)index title:(NSString *)title titleColor:(UIColor *)color; - (void)showMaskRedBadgeIndex:(NSInteger)index; - (void)clearMskRedBadgeIndex:(NSInteger)index; @property (nonatomic, copy) UIColor *backColor; @property (nonatomic, copy) UIColor *titleColor; @property (nonatomic, copy) UIColor *selectedTitleColor; @property (nonatomic, assign) NSInteger selectedIndex; @property (nonatomic) CGPoint showPoint; @property (nonatomic, copy) void (^selectRowAtIndex)(NSInteger index); @end
28,307
https://github.com/veceravojtech/graphQL/blob/master/src/Entity/User.php
Github Open Source
Open Source
MIT
null
graphQL
veceravojtech
PHP
Code
347
1,107
<?php namespace App\Entity; use App\Repository\UserRepository; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; /** * @ORM\Entity(repositoryClass=UserRepository::class) * @UniqueEntity(fields={"login"}, message="user.exists") */ class User implements UserInterface { /** * @var UuidInterface * * @ORM\Id * @ORM\Column(type="uuid", unique=true, nullable=false) */ private $id; /** * @ORM\Column(type="string", length=180, unique=true) */ private $email; /** * @ORM\Column(type="json") */ private $roles = []; /** * @var string The hashed password * @ORM\Column(type="string") */ private $password; /** * @ORM\Column(type="text", nullable=true) */ private $token; /** * @ORM\OneToMany(targetEntity=Project::class, mappedBy="user") */ private $project; public function __construct() { $this->id = Uuid::uuid4(); $this->project = new ArrayCollection(); } public function getId(): ?UuidInterface { return Uuid::fromString($this->id); } public function getEmail(): ?string { return $this->email; } public function setEmail(string $email): self { $this->email = $email; return $this; } /** * A visual identifier that represents this user. * * @see UserInterface */ public function getUsername(): string { return (string) $this->email; } /** * @see UserInterface */ public function getRoles(): array { $roles = $this->roles; // guarantee every user at least has ROLE_USER $roles[] = 'ROLE_USER'; return array_unique($roles); } public function setRoles(array $roles): self { $this->roles = $roles; return $this; } /** * @see UserInterface */ public function getPassword(): string { return (string) $this->password; } public function setPassword(string $password): self { $this->password = $password; return $this; } /** * @see UserInterface */ public function getSalt() { // not needed when using the "bcrypt" algorithm in security.yaml } /** * @see UserInterface */ public function eraseCredentials() { // If you store any temporary, sensitive data on the user, clear it here // $this->plainPassword = null; } public function getToken(): ?string { return $this->token; } public function setToken(?string $token): self { $this->token = $token; return $this; } /** * @return Collection|Project[] */ public function getProject(): Collection { return $this->project; } public function addProject(Project $project): self { if (!$this->project->contains($project)) { $this->project[] = $project; $project->setUser($this); } return $this; } public function removeProject(Project $project): self { if ($this->project->contains($project)) { $this->project->removeElement($project); // set the owning side to null (unless already changed) if ($project->getUser() === $this) { $project->setUser(null); } } return $this; } }
20,691
https://github.com/ortexx/museria-player/blob/master/src/client.js
Github Open Source
Open Source
MIT
2,020
museria-player
ortexx
JavaScript
Code
18
44
const Client = require('musiphone/src/client')(); module.exports = (Parent) => { return class ClientMuseriaPlayer extends (Parent || Client) {} };
23,008
https://github.com/delta94/CV-builder/blob/master/src/client/app/sidebar/add_section/AddSection.container.tsx
Github Open Source
Open Source
MIT
2,020
CV-builder
delta94
TSX
Code
226
856
import React, { Component, ReactNode } from 'react'; import { withTranslation, WithTranslation } from 'react-i18next'; import Title from '@components/Title.view'; import Courses from '../courses/Courses.container'; import { Container, Body, Wrapper } from './AddSection.style'; interface Props extends WithTranslation { currentStep: number; } interface State { showCourses: boolean; showHobbies: boolean; showCustomSection: boolean; showExtraActivities: boolean; showLanguages: boolean; showInternships: boolean; showReferences: boolean; } class AddSection extends Component<Props, State> { state = { showCourses: false, showHobbies: false, showCustomSection: false, showExtraActivities: false, showLanguages: false, showInternships: false, showReferences: false, }; coursesHandler = (): void => { this.setState({ showCourses: !this.state.showCourses, }); }; hobbiesHandler = (): void => { this.setState({ showHobbies: !this.state.showHobbies, }); }; languagesHandler = (): void => { this.setState({ showLanguages: !this.state.showLanguages, }); }; extraActivitiesHandler = (): void => { this.setState({ showExtraActivities: !this.state.showExtraActivities, }); }; internshipsHandler = (): void => { this.setState({ showInternships: !this.state.showInternships, }); }; referencesHandler = (): void => { this.setState({ showReferences: !this.state.showReferences, }); }; customSectionHandler = (): void => { this.setState({ showCustomSection: !this.state.showCustomSection, }); }; public render(): ReactNode { const { currentStep, t } = this.props; if (currentStep !== 7) return null; const { showCourses } = this.state; return ( <Container> <Title>{t('add.section')}</Title> {showCourses && <Courses />} <Body> <Wrapper> <label onClick={this.customSectionHandler}>{t('custom.section')}</label> </Wrapper> <Wrapper> <label onClick={this.coursesHandler}>{t('courses')}</label> </Wrapper> <Wrapper> <label onClick={this.internshipsHandler}>{t('internships')}</label> </Wrapper> <Wrapper> <label onClick={this.extraActivitiesHandler}>{t('extra.activities')}</label> </Wrapper> <Wrapper> <label onClick={this.hobbiesHandler}>{t('hobbies')}</label> </Wrapper> <Wrapper> <label onClick={this.languagesHandler}>{t('languages')}</label> </Wrapper> <Wrapper> <label onClick={this.referencesHandler}>{t('references')}</label> </Wrapper> </Body> </Container> ); } } export default withTranslation()(AddSection);
30,288
https://github.com/ukc-co663/dependency-solver-2019-lBanks98/blob/master/version1/depsolver_1/Main.java
Github Open Source
Open Source
MIT
null
dependency-solver-2019-lBanks98
ukc-co663
Java
Code
1,579
4,893
package depsolver; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.*; class Package { private String name; private String version; private Integer size; private List<List<String>> depends = new ArrayList<>(); private List<String> conflictsArray = new ArrayList<>(); public String getName() { return name; } public String getVersion() { return version; } public Integer getSize() { return size; } public List<List<String>> getDepends() { return depends; } public List<String> getConflicts() { return conflictsArray; } public void setName(String name) { this.name = name; } public void setVersion(String version) { this.version = version; } public void setSize(Integer size) { this.size = size; } public void setDepends(List<List<String>> depends) { this.depends = depends; } public void setConflicts(List<String> conflictsArray) { this.conflictsArray = conflictsArray; } public String getPackage() { String returnPackage = "Name " + getName() + "=" + getVersion() + "Size " + getSize() + "Dep : " + getDepends().toString() + "conflictsArray: " + getConflicts(); return returnPackage; } } public class Main { public static String nameCons; public static boolean testConflict; public static HashSet<String> dontAddHash; public static int advance; public static int checks; public ArrayList<String> stateCommands; public ArrayList<String> conflictsArray; public static void main(String[] args) throws IOException { TypeReference<List<Package>> repoType = new TypeReference<List<Package>>() { }; List<Package> repo = JSON.parseObject(readFile(args[0]), repoType); TypeReference<List<String>> strListType = new TypeReference<List<String>>() { }; List<String> initial = JSON.parseObject(readFile(args[1]), strListType); List<String> constraints = JSON.parseObject(readFile(args[2]), strListType); List<String> commands = new ArrayList<String>(); // 1. a repository description, holding a package list with dependencies and conflicts; // 2. a valid state T of that repository; // 3. a set of constraints, each in the form of a package reference: // a positive constraint requires that at least one of the referred packages is installed // a negative constraint requires that all the referred packages are not installed. // Your task is twofold: // 1. find a valid state T that satisfies the given constraints (as well as the repository'T constraints), and // 2. construct a list of commands that transforms the given state T into your target state T, such that all intermediate // states are valid, and you minimize the cost of the transformation. // For this assignment, the "vertices" x and y are each a set of packages. There is an "arc" from x to y if x and y // are the same set with the exception of one package. A set of packages is VALID if it satisfies all the constraints // from repository.json. A set of packages is FINAL if it satisfies all the constraints from constraints.json. // CHANGE CODE BELOW: // using repo, initial and constraints, compute a solution and print the answer //Commands list for (String T : constraints) { String operator = "" + T.charAt(0); String tempCons = T.substring(1); ArrayList<String> consArray = splitString(tempCons); String nameCons = consArray.get(0); String versionCons = consArray.get(1); ArrayList<String> initialCheckArray = initialCheck(repo, consArray, initial, constraints); ArrayList<String> conflictsArray = new ArrayList<String>(); ArrayList<String> stateArray = new ArrayList<String>(); HashSet<String> dontAddHash = new HashSet<String>(); if (operator.equals("+")) { testConflict = false; commands.addAll(depBuildArray(repo, consArray, stateArray, dontAddHash, true)); } else if (operator.equals("-")) { commands.add(T); } } if (initial.size() > 0) { for (String x : constraints) { String operator = "" + x.charAt(0); String tempCons = x.substring(1); ArrayList<String> consArray = splitString(tempCons); String nameCons = consArray.get(0); String versionCons = consArray.get(1); ArrayList<String> initialCheckArray = initialCheck(repo, consArray, initial, constraints); commands.addAll(initialCheckArray); } } Collections.reverse(commands); System.out.println(JSON.toJSONString(commands)); } public static ArrayList<String> initialCheck(List<Package> repo, ArrayList<String> consArray, List<String> initial, List<String> constraints) { if (initial.size() == 0) { ArrayList<String> emptyStateArray = new ArrayList<String>(); return emptyStateArray; } HashSet<String> emptyHash = new HashSet<String>(); ArrayList<String> emptyStateArray = new ArrayList<String>(); ArrayList<String> newCommandArray = new ArrayList<String>(); ArrayList<String> commandsChecker = depBuildArray(repo, consArray, emptyStateArray, emptyHash, true); for (String initialS : initial) { ArrayList<String> addInitialArray = new ArrayList<String>(); addInitialArray.add(initialS); if (validState(commandsChecker, addInitialArray, repo, dontAddHash)) { if (initialS.charAt(0) == '-') { if (constraints.contains(initialS)) { String restOf = initialS.substring(1); String newS = "+" + initialS; newCommandArray.add(newS); } else { newCommandArray.add(initialS); } } else { String addNewString = "-" + initialS; newCommandArray.add(addNewString); } } } return newCommandArray; } public static boolean compareVersion(String versX, String versY, String operator) { if (operator.equals("=")) { return versX.equals(versY); } else if (operator.equals("<")) { if (versX.equals(versY)) { return true; } else { return versX.compareTo(versY) < 0; } } else if (operator.equals("<=")) { return versX.compareTo(versY) < 0; } else if (operator.equals(">")) { if (versX.equals(versY)) { return true; } else { return versX.compareTo(versY) > 0; } } else if (operator.equals(">=")) { return versX.compareTo(versY) > 0; } else return operator.equals("Any"); } public static int getChecks() { return checks; } public static void setChecks(int checkVal) { checks = checkVal; } //Build the depedencies public static ArrayList<String> depBuildArray(List<Package> repo, List<String> item, ArrayList<String> states, HashSet<String> dontAddHash, boolean cont) { String nameCons; String versionCons; String operator; ArrayList<String> originalStateArray = new ArrayList<String>(states); ArrayList<String> emptyArray = new ArrayList<String>(); if (cont == false) { } ArrayList<String> packageArray = new ArrayList<String>(); if (item.contains("=")) { nameCons = item.get(0); versionCons = item.get(1); operator = item.get(2); } else { ArrayList<String> consArray = splitString(item.toString()); nameCons = consArray.get(0); versionCons = consArray.get(1); if (versionCons.equals("Any")) { operator = "Any"; String[] c = nameCons.split(","); nameCons = c[0]; } else { operator = consArray.get(2); } } //Starting the process for (Package p : repo) { if ((p.getName().equals(nameCons) && compareVersion(p.getVersion(), versionCons, operator))) { if (dontAddHash.contains("+" + p.getName() + "=" + p.getVersion())) { } ArrayList<String> stateTestArray = new ArrayList<String>(originalStateArray); stateTestArray.add("+" + p.getName() + "=" + p.getVersion()); ArrayList<String> addTestArray = new ArrayList<String>(); addTestArray.add("+" + p.getName() + "=" + p.getVersion()); Set<String> testDupeArray = new HashSet<String>(stateTestArray); if (testDupeArray.size() < stateTestArray.size()) { testConflict = true; return emptyArray; } if (validState(stateTestArray, addTestArray, repo, dontAddHash)) { packageArray.add("+" + p.getName() + "=" + p.getVersion()); states.add("+" + p.getName() + "=" + p.getVersion()); dontAddHash.add("+" + p.getName() + "=" + p.getVersion()); // Size = 0 then return current state within stateArray if (p.getDepends().size() == 0) { cont = false; testConflict = false; return states; } if (p.getDepends().size() >= 1) { for (List<String> dependancyList : p.getDepends()) { if (dependancyList.size() == 1) { ArrayList<String> addedArray = new ArrayList<String>(depBuildArray(repo, dependancyList, states, dontAddHash, true)); ArrayList<String> stateTemp = new ArrayList<String>(states); stateTemp.addAll(addedArray); if ((validState(stateTestArray, addedArray, repo, dontAddHash))) { if (testConflict = false) { packageArray.addAll(addedArray); states.addAll(addedArray); } } else { dontAddHash.addAll(addedArray); testConflict = true; } } } for (List<String> depends : p.getDepends()) { int advance = 1; // boolean contin = true; if (depends.size() > 1) { int looper = 0; while (looper < depends.size() && advance == 1) { String z = depends.get(looper); //Compares conflictsArray and adds them if valid. ArrayList<String> x = new ArrayList<String>(); x.add(z); ArrayList<String> addedArray = new ArrayList<String>(depBuildArray(repo, x, states, dontAddHash, true)); ArrayList<String> stateFTArray = new ArrayList<String>(states); stateFTArray.addAll(addedArray); if ((validState(stateTestArray, addedArray, repo, dontAddHash))) { if (dontAddHash.contains(addedArray)) { } else if (testConflict = false) { packageArray.addAll(addedArray); states.addAll(packageArray); advance = 2; } } else { dontAddHash.addAll(addedArray); testConflict = true; String adding = addedArray.toString().replace("[", ""); adding = adding.replace("]", ""); states.remove(adding); } looper++; } } } } } } } return states; } public static ArrayList<String> conflictBuilder(List<Package> repo, ArrayList<String> stateArray) { ArrayList<String> tempConArray = new ArrayList<String>(); for (String T : stateArray) { ArrayList<String> stateAsArray = splitString(T); String name = stateAsArray.get(0); String version = stateAsArray.get(1); String symbol; name = name.replace("+", ""); for (Package pack : repo) { if ((pack.getName().equals(name) && pack.getVersion().equals(version)) || (pack.getName().equals(name) && compareVersion(pack.getVersion(), version, "="))) { tempConArray.addAll(pack.getConflicts()); } } } return tempConArray; } //Remove Conflicts public static boolean validState(ArrayList<String> stateArray, ArrayList<String> addedArray, List<Package> repo, HashSet<String> dontAddHash) { Set<String> testDupeArray = new HashSet<String>(stateArray); if (testDupeArray.size() < stateArray.size()) { return false; } ArrayList<String> conflictsArray = conflictBuilder(repo, stateArray); ArrayList<Package> addedAlreadyArray = new ArrayList<Package>(); ArrayList<Package> statePackArray = new ArrayList<Package>(); for (String T : stateArray) { ArrayList<String> stateAsArray = splitString(T); String nameCons = stateAsArray.get(0); String versionCons = stateAsArray.get(1); String operator; if (versionCons.equals("Any")) { operator = "Any"; String[] c = nameCons.split(""); nameCons = c[1]; } else { operator = stateAsArray.get(2); } nameCons = nameCons.replace("+", ""); for (Package p : repo) { if ((p.getName().equals(nameCons) && versionCons.equals("Any")) || (p.getName().equals(nameCons) && compareVersion(p.getVersion(), versionCons, operator))) { statePackArray.add(p); } } } for (Package pack : statePackArray) { for (String confl : conflictsArray) { ArrayList<String> stateAsArray = splitString(confl); String nameCons = stateAsArray.get(0); String versionCons = stateAsArray.get(1); String operator; if (versionCons.equals("Any")) { operator = "Any"; } else { operator = stateAsArray.get(2); } if (pack.getName().equals(nameCons) && compareVersion(pack.getVersion(), versionCons, operator)) { return false; } } addedAlreadyArray.add(pack); if (pack.getDepends().size() == 1) { if (pack.getDepends().get(0).size() == 1) { String dependant = pack.getDepends().get(0).toString(); ArrayList<String> stateAsArray = splitString(dependant); String nameCons = stateAsArray.get(0); String versionCons = stateAsArray.get(1); String operator; if (versionCons.equals("Any")) { operator = "Any"; } else { operator = stateAsArray.get(2); } for (Package pa : addedAlreadyArray) { if (pa.getName().equals(nameCons) && compareVersion(pa.getVersion(), versionCons, operator)) { return false; } } } } } return true; } static String readFile(String filename) throws IOException { BufferedReader bf = new BufferedReader(new FileReader(filename)); StringBuilder sb = new StringBuilder(); bf.lines().forEach(line -> sb.append(line)); return sb.toString(); } // The string is then converted to name and operator needed. public static ArrayList<String> splitString(String input) { ArrayList returnArray = new ArrayList(); if (input.contains("<=")) { input = input.replace("[", ""); input = input.replace("]", ""); String[] spli_t = input.split("<="); returnArray.add(spli_t[0]); returnArray.add(spli_t[1]); returnArray.add("<="); return returnArray; } else if (input.contains("<")) { input = input.replace("[", ""); input = input.replace("]", ""); String[] spli_t = input.split("<"); returnArray.add(spli_t[0]); returnArray.add(spli_t[1]); returnArray.add("<"); return returnArray; } else if (input.contains(">=")) { input = input.replace("[", ""); input = input.replace("]", ""); String[] spli_t = input.split(">="); returnArray.add(spli_t[0]); returnArray.add(spli_t[1]); returnArray.add(">="); return returnArray; } else if (input.contains(">")) { input = input.replace("[", ""); input = input.replace("]", ""); String[] spli_t = input.split(">"); returnArray.add(spli_t[0]); returnArray.add(spli_t[1]); returnArray.add(">"); return returnArray; } else if (input.contains("=")) { input = input.replace("[", ""); input = input.replace("]", ""); String[] spli_t = input.split("="); returnArray.add(spli_t[0]); returnArray.add(spli_t[1]); returnArray.add("="); return returnArray; } else { input = input.replace("[", ""); input = input.replace("]", ""); returnArray.add(input); returnArray.add("Any"); return returnArray; } } }
24,779
https://github.com/timefrozen/ahoviewer/blob/master/lib/ahoviewer/statusbar.rb
Github Open Source
Open Source
MIT
2,014
ahoviewer
timefrozen
Ruby
Code
164
742
module AhoViewer class StatusBar < Gtk::HBox include Singleton module Priority NORMAL = 0 HIGH = 1 end def initialize super(false, 2) @page_info = Gtk::Label.new @resolution = Gtk::Label.new @filename = Gtk::Label.new @msg_separator = Gtk::VSeparator.new @message = Gtk::Label.new @msg_priority = Priority::NORMAL @page_info.set_width_chars(16) @resolution.set_width_chars(20) @filename.set_ellipsize(Pango::ELLIPSIZE_END) @filename.set_xalign(0) @message.set_xalign(1) pack_start(@page_info, false, false, 8) pack_start(Gtk::VSeparator.new, false, false, 2) pack_start(@resolution, false, false, 8) pack_start(Gtk::VSeparator.new, false, false, 2) pack_start(@filename, true, true, 8) pack_start(@msg_separator, false, false, 2) pack_start(@message, false, false, 8) signal_connect("realize") { @msg_separator.hide if @message.text.empty? } end def clear_message @message.set_text("") @msg_separator.hide @msg_priority = 0 end def clear_page_info @page_info.set_text("") end def clear_resolution @resolution.set_text("") end def clear_filename @filename.set_text("") end def set_message(msg, opts = { :priority => Priority::NORMAL, :delay => 3000 }) priority = opts[:priority] || Priority::NORMAL return if @msg_priority > priority @msg_priority = priority GLib::Source.remove(@message_id) if @message_id @message.set_text(msg) @msg_separator.show Gtk.main_iteration while Gtk.events_pending? @message_id = GLib::Timeout.add(opts[:delay] || 3000) { clear_message; false } end def set_page_info(page, total) @page_info.set_text("#{page} / #{total}") end def set_resolution(width, height, scale, zoom_mode) @resolution.set_text("#{width}x#{height} (#{scale.to_i}%) [#{zoom_mode}]") end def set_filename(filename) @filename.set_text(filename) end end end
48,566
https://github.com/vantreeseba/coc-haxe/blob/master/src/commands/index.ts
Github Open Source
Open Source
MIT
2,022
coc-haxe
vantreeseba
TypeScript
Code
22
66
import GotoHxml from './GotoHxml'; import ChangeHxml from './ChangeHxml'; import RestartClient from './RestartClient'; import PrintConfig from './PrintConfig'; export default [GotoHxml, RestartClient, PrintConfig, ChangeHxml];
12,456
https://github.com/leeqiang250/Android_Reader/blob/master/PbbReader/src/main/java/cn/com/pyc/pbbonline/common/Code.java
Github Open Source
Open Source
MIT
null
Android_Reader
leeqiang250
Java
Code
334
1,168
package cn.com.pyc.pbbonline.common; /** * 请求响应的状态码 <br/> * * @author hudq */ public final class Code { public static final String _SUCCESS = "1001"; //成功! public static final String _8001 = "8001"; //请先领取分享 public static final String _8002 = "8002"; //请先绑定分享 public static final String _8003 = "8003"; //您尚未登录,请用您输入的手机号登录领取分享 public static final String _8004 = "8004"; //您输入的手机号尚未注册,请先完成注册,再领取文件 public static final String _8005 = "8005"; //请退出当前登录账户,用您输入的手机号登录领取分享 public static final String _8006 = "8006"; //登录状态已失效,请重新登录 public static final String _8007 = "8007"; //文件正在打包...... public static final String _9001 = "9001"; //参数传递错误 public static final String _9002 = "9002"; //分享不存在 public static final String _9003 = "9003"; //该分享已经过期 public static final String _9004 = "9004"; //该分享设备数超过限制 public static final String _9005 = "9005"; //余额不足,请联系分享者进行充值 public static final String _9006 = "9006"; //您无权领取该分享 public static final String _9007 = "9007"; //您尚未登录,无法进行该操作 public static final String _9008 = "9008"; //您未领取该分享 public static final String _9009 = "9009"; //日期格式不正确 public static final String _9010 = "9010"; //分享约束不存在 public static final String _9011 = "9011"; //该分享没有分享给任何人 public static final String _9012 = "9012"; //当前账户不存在 public static final String _9013 = "9013"; //您尚未绑定该设备 public static final String _9014 = "9014"; //不能绑定尚未接收的分享 public static final String _9015 = "9015"; //程序逻辑错误 public static final String _9016 = "9016"; //不能重复领取 public static final String _9017 = "9017"; //不能重复绑定 public static final String _9018 = "9018"; //保存消费流水失败 public static final String _9019 = "9019"; //扣费失败 public static final String _9020 = "9020"; //server error public static final String _9021 = "9021"; //can not find this share public static final String _9022 = "9022"; //领取人数超出 public static final String _9101 = "9101"; //密码错误 public static final String _9102 = "9102"; //用户未注册 public static final String _9103 = "9103"; //该用户已经被注册 public static final String _9104 = "9104"; //手机短信验证码发送失败 public static final String _9105 = "9105"; //手机号格式错误 public static final String _9106 = "9106"; //注册失败 public static final String _9107 = "9107"; //图片验证码错误 public static final String _9109 = "9109"; //用户未登录 public static final String _9110 = "9110"; //参数传递错误,//从session中获取图片验证码失败 }
12,338
https://github.com/NASA-LIS/lisf-test/blob/master/lis/surfacemodels/land/clm2/biogeophys/Biogeophysics2.F90
Github Open Source
Open Source
Apache-2.0
2,021
lisf-test
NASA-LIS
Fortran Free Form
Code
842
2,527
!-----------------------BEGIN NOTICE -- DO NOT EDIT----------------------- ! NASA Goddard Space Flight Center Land Information System (LIS) v7.2 ! ! Copyright (c) 2015 United States Government as represented by the ! Administrator of the National Aeronautics and Space Administration. ! All Rights Reserved. !-------------------------END NOTICE -- DO NOT EDIT----------------------- #include "LIS_misc.h" subroutine Biogeophysics2 (clm,cgrnd,cgrndl,cgrnds,tg,emg,htvp, dlrad,ulrad,tssbef) !----------------------------------------------------------------------- ! ! CLMCLMCLMCLMCLMCLMCLMCLMCL A community developed and sponsored, freely ! L M available land surface process model. ! M --COMMON LAND MODEL-- C ! C L CLM WEB INFO: http://clm.gsfc.nasa.gov ! LMCLMCLMCLMCLMCLMCLMCLMCLM CLM ListServ/Mailing List: ! !----------------------------------------------------------------------- ! Purpose: ! This is the main subroutine to execute the calculation of soil/snow and ! ground temperatures and update surface fluxes based on the new ground ! temperature ! ! Method: ! Calling sequence is: ! Biogeophysics2: surface biogeophysics driver ! -> SoilTemperature: soil/snow and ground temperatures ! -> SoilTermProp thermal conductivities and heat ! capacities ! -> Tridiagonal tridiagonal matrix solution ! -> PhaseChange phase change of liquid/ice contents ! ! (1) Snow and soil temperatures ! o The volumetric heat capacity is calculated as a linear combination ! in terms of the volumetric fraction of the constituent phases. ! o The thermal conductivity of soil is computed from ! the algorithm of Johansen (as reported by Farouki 1981), and the ! conductivity of snow is from the formulation used in ! SNTHERM (Jordan 1991). ! o Boundary conditions: ! F = Rnet - Hg - LEg (top), F= 0 (base of the soil column). ! o Soil / snow temperature is predicted from heat conduction ! in 10 soil layers and up to 5 snow layers. ! The thermal conductivities at the interfaces between two ! neighboring layers (j, j+1) are derived from an assumption that ! the flux across the interface is equal to that from the node j ! to the interface and the flux from the interface to the node j+1. ! The equation is solved using the Crank-Nicholson method and ! results in a tridiagonal system equation. ! ! (2) Phase change (see PhaseChange.F90) ! ! Author: ! 15 September 1999: Yongjiu Dai; Initial code ! 15 December 1999: Paul Houser and Jon Radakovich; F90 Revision ! !----------------------------------------------------------------------- ! $Id: Biogeophysics2.F90,v 1.8 2004/11/24 22:56:18 jim Exp $ !----------------------------------------------------------------------- use LIS_precisionMod use clm2type use clm2_varcon, only : hvap, cpair, grav, vkc, tfrz, sb use clm2_varpar, only : nlevsoi implicit none !----Arguments---------------------------------------------------------- type (clm1d), intent(inout) :: clm !CLM 1-D Module !----Local Variables---------------------------------------------------- ! integer j ! do loop index real(r8) fact(clm%snl+1 : nlevsoi) ! used in computing tridiagonal matrix real(r8) egsmax ! max. evaporation which soil can provide at one time step real(r8) egidif ! the excess of evaporation over "egsmax" real(r8) xmf ! total latent heat of phase change of ground water real(r8) tinc ! temperature difference of two time step real(r8) :: cgrnd real(r8) :: cgrndl real(r8) :: cgrnds real(r8) :: tg real(r8) :: emg real(r8) :: htvp real(r8) :: dlrad real(r8) :: ulrad real(r8) :: tssbef(-5:10) !----End Variable List-------------------------------------------------- ! ! Determine soil temperatures including surface soil temperature ! call SoilTemperature(clm , tssbef, htvp, emg, cgrnd, & dlrad, tg , xmf , fact ) ! ! Correct fluxes to present soil temperature ! tinc = clm%t_soisno(clm%snl+1) - tssbef(clm%snl+1) clm%eflx_sh_grnd = clm%eflx_sh_grnd + tinc*cgrnds clm%qflx_evap_soi = clm%qflx_evap_soi + tinc*cgrndl ! ! egidif holds the excess energy if all water is evaporated from ! the top soil layer during the timestep. This energy is added to ! the sensible heat flux. ! egsmax = (clm%h2osoi_ice(clm%snl+1)+clm%h2osoi_liq(clm%snl+1)) / clm%dtime egidif = max( 0._r4, clm%qflx_evap_soi - egsmax ) clm%qflx_evap_soi = min ( clm%qflx_evap_soi, egsmax ) clm%eflx_sh_grnd = clm%eflx_sh_grnd + htvp*egidif ! ! Ground heat flux ! clm%eflx_soil_grnd = clm%sabg + dlrad + (1-clm%frac_veg_nosno)*emg*clm%forc_lwrad & - emg*sb*tssbef(clm%snl+1)**3*(tssbef(clm%snl+1) + 4.*tinc) & - (clm%eflx_sh_grnd+clm%qflx_evap_soi*htvp) ! ! Total fluxes (vegetation + ground) ! clm%eflx_sh_tot = clm%eflx_sh_veg + clm%eflx_sh_grnd clm%qflx_evap_tot = clm%qflx_evap_veg + clm%qflx_evap_soi clm%eflx_lh_tot= hvap*clm%qflx_evap_veg + htvp*clm%qflx_evap_soi ! (account for sublimation) ! ! Assign ground evaporation to sublimation from soil ice or to dew ! on snow or ground ! clm%qflx_evap_grnd = 0. clm%qflx_sub_snow = 0. clm%qflx_dew_snow = 0. clm%qflx_dew_grnd = 0. if (clm%qflx_evap_soi >= 0.) then ! Do not allow for sublimation in melting (melting ==> evap. ==> sublimation) clm%qflx_evap_grnd = min(clm%h2osoi_liq(clm%snl+1)/clm%dtime, clm%qflx_evap_soi) clm%qflx_sub_snow = clm%qflx_evap_soi - clm%qflx_evap_grnd else if (tg < tfrz) then clm%qflx_dew_snow = abs(clm%qflx_evap_soi) else clm%qflx_dew_grnd = abs(clm%qflx_evap_soi) endif endif ! ! Outgoing long-wave radiation from vegetation + ground ! clm%eflx_lwrad_out = ulrad & + (1-clm%frac_veg_nosno)*(1.-emg)*clm%forc_lwrad & + (1-clm%frac_veg_nosno)*emg*sb * tssbef(clm%snl+1)**4 & ! For conservation we put the increase of ground longwave to outgoing + 4.*emg*sb*tssbef(clm%snl+1)**3*tinc ! ! Radiative temperature ! clm%t_rad = (clm%eflx_lwrad_out/sb)**0.25 ! ! Soil Energy balance check ! ! clm%errsoi = 0. ! do j = clm%snl+1, nlevsoi ! clm%errsoi = clm%errsoi - (clm%t_soisno(j)-tssbef(j))/fact(j) ! enddo ! clm%errsoi = clm%errsoi + clm%eflx_soil_grnd - xmf ! ! Variables needed by history tape ! ! clm%dt_grnd = tinc ! clm%eflx_lh_vege = (clm%qflx_evap_veg - clm%qflx_tran_veg) * hvap ! clm%eflx_lh_vegt = clm%qflx_tran_veg * hvap ! clm%eflx_lh_grnd = clm%qflx_evap_soi * htvp clm%eflx_lwrad_net = clm%eflx_lwrad_out - clm%forc_lwrad end subroutine Biogeophysics2
47,410
https://github.com/Zwordi/koillection/blob/master/templates/App/_partials/_footer.html.twig
Github Open Source
Open Source
MIT
2,022
koillection
Zwordi
Twig
Code
32
173
<div class="spacer"></div> <footer> {{ 'global.created_at'|trans({'%date%': object.createdAt|date(app.user.dateFormat|default('Y-m-d'), app.user.timezone|default('UTC'))}) }} {% if object.updatedAt %} · {{ 'global.updated_at'|trans({'%date%': object.updatedAt|date(app.user.dateFormat|default('Y-m-d'), app.user.timezone|default('UTC')) }) }} {% endif %} · {{ ('global.seen_counter.' ~ class)|trans({'%count%': object.seenCounter + 1}) }} </footer>
4,115
https://github.com/hafizurcsejnu/ecommerce-3dmodels/blob/master/public/assets/node_modules/.staging/jqtree-1b390ba5/src/tree.jquery.d.ts
Github Open Source
Open Source
MIT
null
ecommerce-3dmodels
hafizurcsejnu
TypeScript
Code
525
1,617
type NodeId = number | string; type DefaultRecord = Record<string, unknown>; type NodeData = string | DefaultRecord; type IterateCallback = (node: INode, level: number) => boolean; declare class INode { public id?: NodeId; public name: string; public children: INode[]; public element: HTMLElement; public is_open: boolean; public parent: INode | null; [key: string]: unknown; public iterate(callback: IterateCallback): void; } type DataUrlFunction = (node?: Node) => JQuery.AjaxSettings; type DataUrl = string | JQuery.AjaxSettings | DataUrlFunction; // eslint-disable-next-line @typescript-eslint/no-unused-vars interface ClickNodeEvent { node: INode; deselected_node?: INode | null; click_event: JQuery.ClickEvent; previous_node?: INode; } interface SavedState { open_nodes: NodeId[]; selected_node: NodeId[]; } interface IJQTreeOptions { animationSpeed?: string | number; autoEscape?: boolean; autoOpen?: boolean | number | string; buttonLeft?: boolean; closedIcon?: string | Element; data?: NodeData[]; dataFilter?: (data: unknown) => NodeData[]; dataUrl?: DataUrl; dragAndDrop?: boolean; nodeClass?: any; keyboardSupport?: boolean; onCanMove?: (node: INode) => boolean; onCanSelectNode?: (node: INode) => boolean; onCreateLi?: (node: INode, el: JQuery, isSelected: boolean) => void; onDragMove?: (node: INode, event: JQuery.Event | Touch) => void; onDragStop?: (node: INode, event: JQuery.Event | Touch) => void; onIsMoveHandle?: (el: JQuery) => boolean; onLoadFailed?: (response: JQuery.jqXHR) => void; onLoading?: (isLoading: boolean, node: INode, $el: JQuery) => void; onGetStateFromStorage?: () => string; onSetStateFromStorage?: (data: string) => void; openedIcon?: string | Element; openFolderDelay?: number; rtl?: boolean; selectable?: boolean; saveState?: boolean | string; slide?: boolean; showEmptyFolder?: boolean; tabIndex?: number; useContextMenu?: boolean; } interface IJQTreePlugin { (): JQuery; (options: IJQTreeOptions): JQuery; ( behavior: "addNodeAfter", newNodeInfo: NodeData, existingNode: INode ): INode | null; ( behavior: "addNodeBefore", newNodeInfo: NodeData, existingNode: INode ): INode | null; ( behavior: "addParentNode", newNodeInfo: NodeData, existingNode: INode ): INode | null; (behavior: "addToSelection", node: INode, mustSetFocus?: boolean): JQuery; (behavior: "appendNode", newNodeInfo: NodeData, parentNode?: INode): INode; (behavior: "closeNode", node: INode, slide?: boolean): JQuery; (behavior: "destroy"): void; ( behavior: "getNodeByCallback", callback: (node: INode) => boolean ): INode | null; (behavior: "getNodeByHtmlElement", element: Element | JQuery): INode | null; (behavior: "getNodeById", id: NodeId): INode | null; (behavior: "getNodeByName", name: string): INode | null; (behavior: "getNodeByNameMustExist", name: string): INode; (behavior: "getNodesByProperty", key: string, value: unknown): INode[]; (behavior: "getSelectedNode"): INode | false; (behavior: "getSelectedNodes"): INode[]; (behavior: "getState"): SavedState | null; (behavior: "getStateFromStorage"): INode | null; (behavior: "getTree"): INode; (behavior: "getVersion"): string; (behavior: "isNodeSelected", node: INode): boolean; (behavior: "loadData", data: NodeData[], parentNode?: INode): JQuery; ( behavior: "loadDataFromUrl", param1?: string | null | INode, param2?: INode | null | (() => void), param3?: () => void ): JQuery; (behavior: "moveDown"): JQuery; ( behavior: "moveNode", node: INode, targetNode: INode, position: string ): JQuery; (behavior: "moveUp"): JQuery; (behavior: "openNode", node: INode): JQuery; (behavior: "openNode", node: INode, slide: boolean): JQuery; ( behavior: "openNode", node: INode, onFinished: (node: INode) => void ): JQuery; ( behavior: "openNode", node: INode, slide: boolean, onFinished?: (node: INode) => void ): JQuery; (behavior: "prependNode", newNodeInfo: NodeData, parentNode?: INode): INode; (behavior: "reload", onFinished?: () => void): JQuery; (behavior: "removeFromSelection", node: INode): JQuery; (behavior: "removeNode", node: INode): JQuery; (behavior: "scrollToNode", node: INode): JQuery; (behavior: "selectNode", node: INode | null): JQuery; (behavior: "setMouseDelay", delay: number): void; (behavior: "setOption", option: string, value: unknown): JQuery; (behavior: "setState", options: DefaultRecord): JQuery; (behavior: "toggle", node: INode, slideParam?: boolean): JQuery; (behavior: "toJson"): string; (behavior: "updateNode", node: INode, data: NodeData): JQuery; } interface JQuery { tree: IJQTreePlugin; }
6,299
https://github.com/mpaetzold/camel/blob/master/catalog/camel-main-maven-plugin/src/main/docs/camel-main-maven-plugin.adoc
Github Open Source
Open Source
Apache-2.0
2,020
camel
mpaetzold
AsciiDoc
Code
1,039
2,096
= Camel Main Maven Plugin The Camel Main Maven Plugin supports the following goals - camel-main:generate - To pre-scan your project and prepare autowiring and sprint boot tooling support by classpath scanning. == Autowiring To pre-scan your project and prepare autowiring by classpath scanning. The idea is to use this maven plugin at build/compile time and detect what's on the classpath and preconfigure some convention over configurations for using Camel Main with configuration. This is done by checking which Camel components are available on the classpath, and check if they have any component options that are complex objects (not string, number, booleans etc) and is an interface, which can be autowired from an implementation class that are also available on the classpath. A classic example is to setup JMS `ConnectionFactory` on the JMS component to which JMS client you are using. Another example is JDBC drivers etc. In other words its a bit like Spring Boot _starter_ JARs that also offers a similar concept, but without the phase of doing this during build time. == Spring Boot Tooling To pre-scan your project and builds spring boot tooling metafiles which fools tools to offer code completion for editing properties files. This will generate a Spring Boot tooling metadata file in `src/main/resouces/META-INF/spring-configuration-metadata.json` which contains all the options from Camel Main and the components from the classpath. For example if you have camel-jms on the classpath, then Java tools that has support for Spring Boot, can offer code completions when you edit `application.properties` file: ---- camel.component.jms.CURSOR HERE ---- Just press ctrl + space at the _CURSOR HERE_ location and you will get all the options you can configure on the JMS component. == Using the plugin ---- mvn camel-main:generate ---- You can also enable the plugin to automatic run as part of the build to catch these errors. [source,xml] ---- <plugin> <groupId>org.apache.camel</groupId> <artifactId>camel-main-maven-plugin</artifactId> <executions> <execution> <phase>process-classes</phase> <goals> <goal>generate</goal> </goals> </execution> </executions> </plugin> ---- The phase determines when the plugin runs. In the sample above the phase is `process-classes` which runs after the compilation of the main source code. === Include and Exclude properties or components By default the plugin will scan all the detected Camel components from the classpath. For example as shown below, there are 29 detected Camel components, and 1 mapping was created in the `autowire.properties` file [source,text] ---- [INFO] --- camel-main-maven-plugin:3.0.0-SNAPSHOT:generate (generate) @ camel-example-main-artemis --- [INFO] Detected Camel version used in project: 3.0.0-SNAPSHOT [INFO] Pre-scanning using Camel version: 3.0.0-SNAPSHOT [INFO] Discovered 29 Camel components from classpath: [bean, browse, class, controlbus, dataformat, dataset, dataset-test, direct, direct-vm, file, jms, language, log, mock, properties, quartz, ref, rest, rest-api, saga, scheduler, seda, spring-event, stub, timer, validator, vm, xslt] [INFO] Created file: /Users/davsclaus/workspace/camel/examples/camel-example-main-artemis/target/classes/META-INF/services/org/apache/camel/autowire.properties (autowire by classpath: 1) ---- You can use exclude and include patterns to specify which properties and/or components to use. For example to only include the JMS component you can do: [source,xml] ---- <plugin> <groupId>org.apache.camel</groupId> <artifactId>camel-main-maven-plugin</artifactId> <configuration> <logClasspath>false</logClasspath> <!-- just include only the jms component --> <include>jms</include> </configuration> <executions> <execution> <phase>process-classes</phase> <goals> <goal>generate</goal> </goals> </execution> </executions> </plugin> ---- For more advanced patterns you can use wildcards and regular expressions, for example to only include JMS or AMQP components: [source,xml] ---- <include>(jms|amqp)</include> ---- You can also work with property names, for example to only configure `ConnectionFactory` you can do: [source,xml] ---- <include>connection-factory</include> ---- You can also specify which Camel component this would apply, such as the JMS component: [source,xml] ---- <include>camel.component.jms.connection-factory</include> ---- NOTE: If you use excludes then they take precedence over include. === Mappings Mappings are used for more complex mappings where you can specify the class type of the property value. For example one of the default mappings is as shown: [source,properties] ---- javax.jms.ConnectionFactory=org.apache.activemq.artemis.jms.client.ActiveMQJMSConnectionFactory;org.apache.activemq.ActiveMQConnectionFactory ---- This tells the `generate` goal that if the value of the property is a `javax.jms.ConnectionFactory` type then we should only accept the following implementations when scanning the classpath: - `org.apache.activemq.artemis.jms.client.ActiveMQJMSConnectionFactory` - `org.apache.activemq.ActiveMQConnectionFactory` This means when there for example are 8 implementations in the classpath for `javax.jms.ConnectionFactory` then this mapping will select the on of the 2 above if they are on the classpath in the given prioritized order. This allows us to have convention over configuration and just drop either the Apache Artemis JMS client or Apache ActiveMQ JMS client on the classpath, and the Camel JMS component will automatic be configured to use their `ConnectionFactory` classes. You can also specify the skip certain types, such as [source,properties] ---- org.springframework.jms.core.JmsOperations=#skip# ---- Which means the `generate` goal skips any property values that are of type `org.springframework.jms.core.JmsOperations`. === Options The maven plugin *generate* goal supports the following options which can be configured from the command line (use `-D` syntax), or defined in the `pom.xml` file in the `<configuration>` tag. |=== | Parameter | Default Value | Description | autowireEnabled | true | Whether generating autowiring is enabled. | springBootEnabled | true | Whether generating spring boot tooling support is enabled. | logClasspath | false | Whether to log the classpath when starting | logUnmapped | false | When autowiring has detected multiple implementations (2 or more) of a given interface, which cannot be mapped, should they be logged so you can see and add manual mapping if needed. | downloadVersion | true | Whether to allow downloading Camel catalog version from the internet. This is needed if the project * uses a different Camel version than this plugin is using by default. | downloadSourceJars | true | Whether to allow downloading -source JARs when generating spring boot tooling to include javadoc as description for discovered options. | exclude | | To exclude autowiring specific properties with these key names. You can also configure a single entry and separate the excludes with comma. | include | | To include autowiring specific properties with these key names. You can also configure a single entry and separate the includes with comma. | mappings | | To setup special mappings between known types as key=value pairs. You can also configure a single entry and separate the mappings with comma. | mappingsFile | | Optional mappings file loaded from classpath, with mapping that override any default mappings. Will by default load the file `camel-main-mappings.properties` from the classpath root. |=== === Examples You can find more details and a working example at `examples/camel-example-main-artemis`.
21,681
https://github.com/achen163/cs152phase2/blob/master/miniL.lex
Github Open Source
Open Source
AFL-1.1
null
cs152phase2
achen163
Lex
Code
417
1,206
/* cs152-miniL phase1 */ %{ /* write your C code here for definitions of variables and including headers */ #include "miniL-parser.h" int currPosition = 1; int currLine = 1; %} /* some common rules */ DIGIT [0-9] LETTER [A-Za-z] UNDERSCORE [_] %% /* specific lexer rules in regex */ "function" {return FUNCTION; currPosition += yyleng;} "beginparams" {return BEGIN_PARAMS; currPosition += yyleng;} "endparams" {return END_PARAMS; currPosition += yyleng;} "beginlocals" {return BEGIN_LOCALS; currPosition += yyleng;} "endlocals" {return END_LOCALS; currPosition += yyleng;} "beginbody" {return BEGIN_BODY; currPosition += yyleng;} "endbody" {return END_BODY; currPosition += yyleng;} "integer" {return INTEGER; currPosition += yyleng;} "array" {return ARRAY; currPosition += yyleng;} "of" {return OF; currPosition += yyleng;} "if" {return IF; currPosition += yyleng;} "then" {return THEN; currPosition += yyleng;} "endif" {return ENDIF; currPosition += yyleng;} "else" {return ELSE; currPosition += yyleng;} "while" {return WHILE; currPosition += yyleng;} "do" {return DO; currPosition += yyleng;} "beginloop" {return BEGINLOOP; currPosition += yyleng;} "endloop" {return ENDLOOP; currPosition += yyleng;} "continue" {return CONTINUE; currPosition += yyleng;} "break" {return BREAK; currPosition += yyleng;} "read" {return READ; currPosition += yyleng;} "write" {return WRITE; currPosition += yyleng;} "not" {return NOT; currPosition += yyleng;} "true" {return TRUE; currPosition += yyleng;} "false" {return FALSE; currPosition += yyleng;} "return" {return RETURN; currPosition += yyleng;} "-" {return SUB; currPosition += yyleng;} "+" {return ADD; currPosition += yyleng;} "*" {return MULT; currPosition += yyleng;} "/" {return DIV; currPosition += yyleng;} "%" {return MOD; currPosition += yyleng;} "==" {return EQ; currPosition += yyleng;} "<>" {return NEQ; currPosition += yyleng;} "<" {return LT; currPosition += yyleng;} ">" {return GT; currPosition += yyleng;} "<=" {return LTE; currPosition += yyleng;} ">=" {return GTE; currPosition += yyleng;} [A-Za-z0-9_]*{UNDERSCORE} {printf("Error at line %d, column %d: identifier \"%s\" cannot end with underscore\n", currLine, currPosition, yytext); exit(0);} [a-zA-Z][A-Za-z0-9_]* {yylval.stringToken = yytext; return IDENT; currPosition += yyleng; } {DIGIT}+ {yylval.numToken= atoi(yytext); return NUMBER; currPosition += yyleng;} ";" {return SEMICOLON; currPosition += yyleng;} ":" {return COLON; currPosition += yyleng;} "," {return COMMA; currPosition += yyleng;} "(" {return L_PAREN; currPosition += yyleng;} ")" {return R_PAREN; currPosition += yyleng;} "[" {return L_SQUARE_BRACKET; currPosition += yyleng;} "]" {return R_SQUARE_BRACKET; currPosition += yyleng;} ":=" {return ASSIGN; currPosition += yyleng;} "##".* { currPosition += yyleng; currLine++;} "\n" { currPosition = 1; currLine++;} "\t" { currPosition += yyleng;} " " { currPosition += yyleng;} [0-9_]+[A-Za-z0-9_]* {printf("Error at line %d, column %d: identifier \"%s\" must begin with a letter\n", currLine, currPosition, yytext); exit(0);} . {printf("Error at line %d, column %d unrecognized symbol: \"%s\"\n", currLine, currPosition, yytext); exit(0);} %% /* C functions used in lexer */
8,107
https://github.com/OSDeploy/OSDBuilder/blob/master/Private/AllFunctions.ps1
Github Open Source
Open Source
MIT
2,023
OSDBuilder
OSDeploy
PowerShell
Code
20,000
68,676
function Add-ContentADKWinPE { [CmdletBinding()] param () #================================================= # Abort #================================================= if (($ScriptName -ne 'New-OSBuild') -and ($ScriptName -ne 'New-PEBuild')) {Return} if ([string]::IsNullOrWhiteSpace($WinPEADKPE)) {Return} $global:ReapplyLCU = $true #================================================= # Execute #================================================= Show-ActionTime; Write-Host -ForegroundColor Green "WinPE: WinPE.wim ADK Optional Components" $WinPEADKPE = $WinPEADKPE | Sort-Object Length foreach ($PackagePath in $WinPEADKPE) { if ($PackagePath -like "*WinPE-NetFx*") { $CurrentLog = "$PEInfo\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-ContentADKWinPE.log" Write-Verbose "CurrentLog: $CurrentLog" Write-Host -ForegroundColor Gray " $SetOSDBuilderPathContent\$PackagePath" Try {Add-WindowsPackage -PackagePath "$SetOSDBuilderPathContent\$PackagePath" -Path "$MountWinPE" -LogPath "$CurrentLog" | Out-Null} Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } } } $WinPEADKPE = $WinPEADKPE | Where-Object {$_.Name -notlike "*WinPE-NetFx*"} foreach ($PackagePath in $WinPEADKPE) { if ($PackagePath -like "*WinPE-PowerShell*") { $CurrentLog = "$PEInfo\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-ContentADKWinPE.log" Write-Verbose "CurrentLog: $CurrentLog" Write-Host -ForegroundColor Gray " $SetOSDBuilderPathContent\$PackagePath" Try {Add-WindowsPackage -PackagePath "$SetOSDBuilderPathContent\$PackagePath" -Path "$MountWinPE" -LogPath "$CurrentLog" | Out-Null} Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } } } $WinPEADKPE = $WinPEADKPE | Where-Object {$_.Name -notlike "*WinPE-PowerShell*"} foreach ($PackagePath in $WinPEADKPE) { Write-Host -ForegroundColor Gray " $SetOSDBuilderPathContent\$PackagePath" $CurrentLog = "$PEInfo\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-ContentADKWinPE.log" Write-Verbose "CurrentLog: $CurrentLog" if ($OSMajorVersion -eq 6) { dism /Image:"$MountWinPE" /Add-Package /PackagePath:"$SetOSDBuilderPathContent\$PackagePath" /LogPath:"$CurrentLog" } else { Try {Add-WindowsPackage -PackagePath "$SetOSDBuilderPathContent\$PackagePath" -Path "$MountWinPE" -LogPath "$CurrentLog" | Out-Null} Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } } } } function Add-ContentADKWinRE { [CmdletBinding()] param () #================================================= # Abort #================================================= if (($ScriptName -ne 'New-OSBuild') -and ($ScriptName -ne 'New-PEBuild')) {Return} if ([string]::IsNullOrWhiteSpace($WinPEADKRE)) {Return} $global:ReapplyLCU = $true #================================================= # Execute #================================================= Show-ActionTime; Write-Host -ForegroundColor Green "WinPE: WinRE.wim ADK Optional Components" $WinPEADKRE = $WinPEADKRE | Sort-Object Length foreach ($PackagePath in $WinPEADKRE) { $CurrentLog = "$PEInfo\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-ContentADKWinRE.log" Write-Verbose "CurrentLog: $CurrentLog" if ($PackagePath -like "*WinPE-NetFx*") { Write-Host -ForegroundColor Gray " $SetOSDBuilderPathContent\$PackagePath" Try {Add-WindowsPackage -PackagePath "$SetOSDBuilderPathContent\$PackagePath" -Path "$MountWinRE" -LogPath "$CurrentLog" | Out-Null} Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } } } $WinPEADKRE = $WinPEADKRE | Where-Object {$_.Name -notlike "*WinPE-NetFx*"} foreach ($PackagePath in $WinPEADKRE) { $CurrentLog = "$PEInfo\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-ContentADKWinRE.log" Write-Verbose "CurrentLog: $CurrentLog" if ($PackagePath -like "*WinPE-PowerShell*") { Write-Host -ForegroundColor Gray " $SetOSDBuilderPathContent\$PackagePath" Try {Add-WindowsPackage -PackagePath "$SetOSDBuilderPathContent\$PackagePath" -Path "$MountWinRE" -LogPath "$CurrentLog" | Out-Null} Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } } } $WinPEADKRE = $WinPEADKRE | Where-Object {$_.Name -notlike "*WinPE-PowerShell*"} foreach ($PackagePath in $WinPEADKRE) { $CurrentLog = "$PEInfo\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-ContentADKWinRE.log" Write-Verbose "CurrentLog: $CurrentLog" Write-Host -ForegroundColor Gray " $SetOSDBuilderPathContent\$PackagePath" if ($OSMajorVersion -eq 6) { dism /Image:"$MountWinRE" /Add-Package /PackagePath:"$SetOSDBuilderPathContent\$PackagePath" /LogPath:"$CurrentLog" } else { Try {Add-WindowsPackage -PackagePath "$SetOSDBuilderPathContent\$PackagePath" -Path "$MountWinRE" -LogPath "$CurrentLog" | Out-Null} Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } } } } function Add-ContentADKWinSE { [CmdletBinding()] param () #================================================= # Abort #================================================= if (($ScriptName -ne 'New-OSBuild') -and ($ScriptName -ne 'New-PEBuild')) {Return} if ([string]::IsNullOrWhiteSpace($WinPEADKSE)) {Return} $global:ReapplyLCU = $true #================================================= # Header #================================================= Show-ActionTime Write-Host -ForegroundColor Green "WinPE: WinSE.wim ADK Optional Components" #================================================= # Execute #================================================= $WinPEADKSE = $WinPEADKSE | Sort-Object Length foreach ($PackagePath in $WinPEADKSE) { $CurrentLog = "$PEInfo\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-ContentADKWinSE.log" Write-Verbose "CurrentLog: $CurrentLog" if ($PackagePath -like "*WinPE-NetFx*") { Write-Host -ForegroundColor Gray " $SetOSDBuilderPathContent\$PackagePath" Try {Add-WindowsPackage -PackagePath "$SetOSDBuilderPathContent\$PackagePath" -Path "$MountWinSE" -LogPath "$CurrentLog" | Out-Null} Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } } } $WinPEADKSE = $WinPEADKSE | Where-Object {$_.Name -notlike "*WinPE-NetFx*"} foreach ($PackagePath in $WinPEADKSE) { $CurrentLog = "$PEInfo\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-ContentADKWinSE.log" Write-Verbose "CurrentLog: $CurrentLog" if ($PackagePath -like "*WinPE-PowerShell*") { Write-Host -ForegroundColor Gray " $SetOSDBuilderPathContent\$PackagePath" Try {Add-WindowsPackage -PackagePath "$SetOSDBuilderPathContent\$PackagePath" -Path "$MountWinSE" -LogPath "$CurrentLog" | Out-Null} Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } } } $WinPEADKSE = $WinPEADKSE | Where-Object {$_.Name -notlike "*WinPE-PowerShell*"} foreach ($PackagePath in $WinPEADKSE) { $CurrentLog = "$PEInfo\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-ContentADKWinSE.log" Write-Verbose "CurrentLog: $CurrentLog" Write-Host -ForegroundColor Gray " $SetOSDBuilderPathContent\$PackagePath" if ($OSMajorVersion -eq 6) { dism /Image:"$MountWinSE" /Add-Package /PackagePath:"$SetOSDBuilderPathContent\$PackagePath" /LogPath:"$CurrentLog.log" } else { Try {Add-WindowsPackage -PackagePath "$SetOSDBuilderPathContent\$PackagePath" -Path "$MountWinSE" -LogPath "$CurrentLog" | Out-Null} Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } } } } function Add-ContentDriversOS { [CmdletBinding()] param () #================================================= # Abort #================================================= if ($ScriptName -ne 'New-OSBuild') {Return} #================================================= # Task #================================================= if ($Drivers) { Show-ActionTime; Write-Host -ForegroundColor Green "OS: Drivers TASK" foreach ($Driver in $Drivers) { Write-Host " $SetOSDBuilderPathContent\$Driver" -ForegroundColor DarkGray $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-ContentDriversOS-Task.log" Write-Verbose "CurrentLog: $CurrentLog" if ($OSMajorVersion -eq 6) { dism /Image:"$MountDirectory" /Add-Driver /Driver:"$SetOSDBuilderPathContent\$Driver" /Recurse /ForceUnsigned /LogPath:"$CurrentLog" } else { Try {Add-WindowsDriver -Driver "$SetOSDBuilderPathContent\$Driver" -Recurse -Path "$MountDirectory" -ForceUnsigned -LogPath "$CurrentLog" | Out-Null} Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } } } } #================================================= # Template #================================================= if ($DriverTemplates) { Show-ActionTime; Write-Host -ForegroundColor Green "OS: Drivers TEMPLATE" foreach ($Driver in $DriverTemplates) { Write-Host "$($Driver.FullName)" -ForegroundColor DarkGray $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-ContentDriversOS-Template.log" Write-Verbose "CurrentLog: $CurrentLog" if ($OSMajorVersion -eq 6) { dism /Image:"$MountDirectory" /Add-Driver /Driver:"$($Driver.FullName)" /Recurse /ForceUnsigned /LogPath:"$CurrentLog" } else { Try {Add-WindowsDriver -Driver "$($Driver.FullName)" -Recurse -Path "$MountDirectory" -ForceUnsigned -LogPath "$CurrentLog" | Out-Null} Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } } } } } function Add-ContentDriversPE { [CmdletBinding()] param () #================================================= # Abort #================================================= if ($ScriptName -ne 'New-OSBuild') {Return} #================================================= # MountPaths #================================================= $MountPaths = @( $MountWinPE $MountWinRE $MountWinSE ) #================================================= # Task #================================================= if ([string]::IsNullOrWhiteSpace($WinPEDrivers)) {Return} Show-ActionTime; Write-Host -ForegroundColor Green "WinPE: Add-ContentDriversPE" foreach ($WinPEDriver in $WinPEDrivers) { Write-Host " $SetOSDBuilderPathContent\$WinPEDriver" -ForegroundColor DarkGray foreach ($MountPath in $MountPaths) { $CurrentLog = "$PEInfo\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-ContentDriversPE-Task.log" Write-Verbose "CurrentLog: $CurrentLog" if ($OSMajorVersion -eq 6) { dism /Image:"$MountPath" /Add-Driver /Driver:"$SetOSDBuilderPathContent\$WinPEDriver" /Recurse /ForceUnsigned /LogPath:"$CurrentLog" } else { Add-WindowsDriver -Path "$MountPath" -Driver "$SetOSDBuilderPathContent\$WinPEDriver" -Recurse -ForceUnsigned -LogPath "$CurrentLog" | Out-Null } } } } function Add-ContentExtraFilesOS { [CmdletBinding()] param () #================================================= # ABORT #================================================= if ($ScriptName -ne 'New-OSBuild') {Return} #================================================= # TASK #================================================= if ($ExtraFiles) { Show-ActionTime; Write-Host -ForegroundColor Green "OS: Extra Files TASK" foreach ($ExtraFile in $ExtraFiles) { $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-ContentExtraFilesOS-Task.log" Write-Verbose "CurrentLog: $CurrentLog" Write-Host " $SetOSDBuilderPathContent\$ExtraFile" -ForegroundColor DarkGray robocopy "$SetOSDBuilderPathContent\$ExtraFile" "$MountDirectory" *.* /s /ndl /xx /b /np /ts /tee /r:0 /w:0 /Log+:"$CurrentLog" | Out-Null } } #================================================= # TEMPLATE #================================================= if ($ExtraFilesTemplates) { Show-ActionTime; Write-Host -ForegroundColor Green "OS: Extra Files TEMPLATE" foreach ($ExtraFile in $ExtraFilesTemplates) { $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-ContentExtraFilesOS-Template.log" Write-Verbose "CurrentLog: $CurrentLog" Write-Host "$($ExtraFile.FullName)" -ForegroundColor DarkGray robocopy "$($ExtraFile.FullName)" "$MountDirectory" *.* /s /ndl /xx /b /np /ts /tee /r:0 /w:0 /Log+:"$CurrentLog" | Out-Null } } } function Add-ContentExtraFilesPE { [CmdletBinding()] param () #================================================= # ABORT #================================================= if ($ScriptName -ne 'New-OSBuild') {Return} #================================================= # TASK #================================================= if ($WinPEExtraFilesPE -or $WinPEExtraFilesRE -or $WinPEExtraFilesSE) { Show-ActionTime; Write-Host -ForegroundColor Green "WinPE: Extra Files TASK" foreach ($ExtraFile in $WinPEExtraFilesPE) { Write-Host " Source: $SetOSDBuilderPathContent\$ExtraFile" -ForegroundColor DarkGray $CurrentLog = "$PEInfo\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-ContentExtraFilesPE.log" Write-Verbose "CurrentLog: $CurrentLog" #robocopy "$SetOSDBuilderPathContent\$ExtraFile" "$MountWinPE" *.* /s /ndl /xx /np /ts /tee /r:0 /w:0 /Log+:"$CurrentLog" | Out-Null robocopy "$SetOSDBuilderPathContent\$ExtraFile" "$MountWinPE" *.* /S /ZB /COPY:D /NODCOPY /XJ /NDL /NP /TEE /TS /XX /R:0 /W:0 /LOG+:"$CurrentLog" | Out-Null } foreach ($ExtraFile in $WinPEExtraFilesRE) { Write-Host " Source: $SetOSDBuilderPathContent\$ExtraFile" -ForegroundColor DarkGray $CurrentLog = "$PEInfo\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-ContentExtraFilesPE.log" Write-Verbose "CurrentLog: $CurrentLog" robocopy "$SetOSDBuilderPathContent\$ExtraFile" "$MountWinRE" *.* /S /ZB /COPY:D /NODCOPY /XJ /NDL /NP /TEE /TS /XX /R:0 /W:0 /LOG+:"$CurrentLog" | Out-Null } foreach ($ExtraFile in $WinPEExtraFilesSE) { Write-Host " Source: $SetOSDBuilderPathContent\$ExtraFile" -ForegroundColor DarkGray $CurrentLog = "$PEInfo\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-ContentExtraFilesPE.log" Write-Verbose "CurrentLog: $CurrentLog" robocopy "$SetOSDBuilderPathContent\$ExtraFile" "$MountWinSE" *.* /S /ZB /COPY:D /NODCOPY /XJ /NDL /NP /TEE /TS /XX /R:0 /W:0 /LOG+:"$CurrentLog" | Out-Null } } else { Return } } function Add-ContentScriptsOS { [CmdletBinding()] param () #================================================= # ABORT #================================================= if ($ScriptName -ne 'New-OSBuild') {Return} #================================================= # TASK #================================================= if ($Scripts) { Show-ActionTime; Write-Host -ForegroundColor Green "OS: Scripts TASK" foreach ($Script in $Scripts) { if (Test-Path "$SetOSDBuilderPathContent\$Script") { Write-Host -ForegroundColor Cyan "Source: $SetOSDBuilderPathContent\$Script" Invoke-Expression "& '$SetOSDBuilderPathContent\$Script'" } } } #================================================= # TEMPLATE #================================================= if ($ScriptTemplates) { Show-ActionTime; Write-Host -ForegroundColor Green "OS: Scripts TEMPLATE" foreach ($Script in $ScriptTemplates) { if (Test-Path "$($Script.FullName)") { Write-Host -ForegroundColor Cyan "Source: $($Script.FullName)" Invoke-Expression "& '$($Script.FullName)'" } } } } function Add-ContentScriptsPE { [CmdletBinding()] param () #================================================= # Abort #================================================= if ($ScriptName -ne 'New-OSBuild') {Return} #================================================= # TASK #================================================= if ($WinPEScriptsPE -or $WinPEScriptsRE -or $WinPEScriptsSE) { Show-ActionTime; Write-Host -ForegroundColor Green "WinPE: Scripts TASK" foreach ($PSWimScript in $WinPEScriptsPE) { if (Test-Path "$SetOSDBuilderPathContent\$PSWimScript") { Write-Host " Source: $SetOSDBuilderPathContent\$PSWimScript" -ForegroundColor Cyan (Get-Content "$SetOSDBuilderPathContent\$PSWimScript").replace('winpe.wim.log', 'WinPE.log') | Set-Content "$SetOSDBuilderPathContent\$PSWimScript" Invoke-Expression "& '$SetOSDBuilderPathContent\$PSWimScript'" } } foreach ($PSWimScript in $WinPEScriptsRE) { if (Test-Path "$SetOSDBuilderPathContent\$PSWimScript") { Write-Host " Source: $SetOSDBuilderPathContent\$PSWimScript" -ForegroundColor Cyan (Get-Content "$SetOSDBuilderPathContent\$PSWimScript").replace('winre.wim.log', 'WinRE.log') | Set-Content "$SetOSDBuilderPathContent\$PSWimScript" Invoke-Expression "& '$SetOSDBuilderPathContent\$PSWimScript'" } } foreach ($PSWimScript in $WinPEScriptsSE) { if (Test-Path "$SetOSDBuilderPathContent\$PSWimScript") { Write-Host " Source: $SetOSDBuilderPathContent\$PSWimScript" -ForegroundColor Cyan (Get-Content "$SetOSDBuilderPathContent\$PSWimScript").replace('MountSetup', 'MountWinSE') | Set-Content "$SetOSDBuilderPathContent\$PSWimScript" (Get-Content "$SetOSDBuilderPathContent\$PSWimScript").replace('setup.wim.log', 'WinSE.log') | Set-Content "$SetOSDBuilderPathContent\$PSWimScript" Invoke-Expression "& '$SetOSDBuilderPathContent\$PSWimScript'" } } } } function Add-ContentStartLayout { [CmdletBinding()] param () #================================================= # Abort #================================================= if ($ScriptName -ne 'New-OSBuild') {Return} if ($OSMajorVersion -ne 10) {Return} if ([string]::IsNullOrWhiteSpace($StartLayoutXML)) {Return} #================================================= # TASK #================================================= Show-ActionTime; Write-Host -ForegroundColor Green "OS: Use Content StartLayout" Write-Host " $SetOSDBuilderPathContent\$StartLayoutXML" -ForegroundColor DarkGray Try { Copy-Item -Path "$SetOSDBuilderPathContent\$StartLayoutXML" -Destination "$MountDirectory\Users\Default\AppData\Local\Microsoft\Windows\Shell\LayoutModification.xml" -Recurse -Force | Out-Null } Catch { $ErrorMessage = $_.Exception.Message Write-Warning "$ErrorMessage" } } function Add-ContentUnattEnd { [CmdletBinding()] param () #================================================= # Abort #================================================= if ($ScriptName -ne 'New-OSBuild') {Return} if ($OSMajorVersion -ne 10) {Return} if ([string]::IsNullOrWhiteSpace($UnattendXML)) {Return} #================================================= # Header #================================================= Show-ActionTime; Write-Host -ForegroundColor Green "OS: Use Content Unattend" #================================================= # Execute #================================================= Write-Host " $SetOSDBuilderPathContent\$UnattendXML" -ForegroundColor DarkGray if (!(Test-Path "$MountDirectory\Windows\Panther")) {New-Item -Path "$MountDirectory\Windows\Panther" -ItemType Directory -Force | Out-Null} Copy-Item -Path "$SetOSDBuilderPathContent\$UnattendXML" -Destination "$MountDirectory\Windows\Panther\Unattend.xml" -Force $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-ContentUnattend.log" Write-Verbose "CurrentLog: $CurrentLog" Try {Use-WindowsUnattend -UnattendPath "$SetOSDBuilderPathContent\$UnattendXML" -Path "$MountDirectory" -LogPath "$CurrentLog" | Out-Null} Catch { $ErrorMessage = $_.Exception.Message Write-Warning "$ErrorMessage" } } function Add-ContentPack { [CmdletBinding()] param ( [ValidateSet( 'MEDIA', 'OSCapability', 'OSDrivers', 'OSExtraFiles', 'OSLanguageFeatures', 'OSLanguagePacks', 'OSLocalExperiencePacks', 'OSPackages', 'OSPoshMods', 'OSRegistry', 'OSScripts', 'OSStartLayout', 'PEADK', 'PEADKLang', 'PEDaRT', 'PEDrivers', 'PEExtraFiles', 'PEPackages', 'PEPoshMods', 'PERegistry', 'PEScripts' )] [Alias('Type')] [string]$PackType = 'All' ) #================================================= # ABORT #================================================= if (Get-IsTemplatesEnabled) {Return} if ($SkipContentPacks -eq $true) {Return} if (($ScriptName -ne 'New-OSBuild') -and ($ScriptName -ne 'New-PEBuild')) {Return} #================================================= # BUILD #================================================= if ($ContentPacks) { if ($ReleaseID -match '1909') {$MSUX = '1903'} elseif ($ReleaseID -match '20H2') {$MSUX = '2004'} elseif ($ReleaseID -match '21H1') {$MSUX = '2004'} elseif ($ReleaseID -match '21H2') {$MSUX = '2004'} elseif ($ReleaseID -match '22H2') {$MSUX = '2004'} else {$MSUX = $ReleaseID} #================================================= # MEDIA ContentPacks #================================================= if ($PackType -eq 'MEDIA') { Show-ActionTime; Write-Host -ForegroundColor Green "MEDIA ContentPack" foreach ($ContentPack in $ContentPacks) { $ContentPackPath = Join-Path $SetOSDBuilderPathContentPacks "$ContentPack\MEDIA" $ContentPaths = @( "$ContentPackPath\ALL" "$ContentPackPath\$OSArchitecture" "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture" ) foreach ($ContentPath in $ContentPaths) { if (! (Test-Path $ContentPath)) {New-Item -Path $ContentPath -ItemType Directory -Force -ErrorAction Ignore | Out-Null} Add-ContentPackMEDIA -ContentPackContent $ContentPath } } } #================================================= # OS ContentPacks #================================================= if ($PackType -eq 'OSDrivers') { Show-ActionTime; Write-Host -ForegroundColor Green "OSDrivers ContentPack" foreach ($ContentPack in $ContentPacks) { $ContentPackPath = Join-Path $SetOSDBuilderPathContentPacks "$ContentPack\OSDrivers" $ContentPaths = @( "$ContentPackPath\ALL" "$ContentPackPath\$OSArchitecture" "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture" ) foreach ($ContentPath in $ContentPaths) { if (! (Test-Path $ContentPath)) {New-Item -Path $ContentPath -ItemType Directory -Force -ErrorAction Ignore | Out-Null} Add-ContentPackOSDrivers -ContentPackContent $ContentPath } } } if ($PackType -eq 'OSExtraFiles') { Show-ActionTime; Write-Host -ForegroundColor Green "OSExtraFiles ContentPack" foreach ($ContentPack in $ContentPacks) { $ContentPackPath = Join-Path $SetOSDBuilderPathContentPacks "$ContentPack\OSExtraFiles" $ContentPaths = @( "$ContentPackPath\ALL" "$ContentPackPath\$OSArchitecture" "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture" ) foreach ($ContentPath in $ContentPaths) { if (! (Test-Path $ContentPath)) {New-Item -Path $ContentPath -ItemType Directory -Force -ErrorAction Ignore | Out-Null} Add-ContentPackOSExtraFiles -ContentPackContent $ContentPath } Get-ChildItem "$ContentPackPath\All Subdirs" -Directory -ErrorAction SilentlyContinue | foreach {Add-ContentPackOSExtraFiles -ContentPackContent "$($_.FullName)"} Get-ChildItem "$ContentPackPath\$OSArchitecture Subdirs" -Directory -ErrorAction SilentlyContinue | foreach {Add-ContentPackOSExtraFiles -ContentPackContent "$($_.FullName)"} } } if ($PackType -eq 'OSCapability') { Show-ActionTime; Write-Host -ForegroundColor Green "OSCapability ContentPack" foreach ($ContentPack in $ContentPacks) { $ContentPackPath = Join-Path $SetOSDBuilderPathContentPacks "$ContentPack\OSCapability" if (! (Test-Path "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture")) {New-Item -Path "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture" -ItemType Directory -Force -ErrorAction Ignore | Out-Null} Add-ContentPackOSCapability -ContentPackContent "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture" if (! (Test-Path "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture RSAT")) {New-Item -Path "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture RSAT" -ItemType Directory -Force -ErrorAction Ignore | Out-Null} Add-ContentPackOSCapability -ContentPackContent "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture RSAT" -RSAT } } if ($PackType -eq 'OSLanguageFeatures') { Show-ActionTime; Write-Host -ForegroundColor Green "OSLanguageFeatures ContentPack" foreach ($ContentPack in $ContentPacks) { $ContentPackPath = Join-Path $SetOSDBuilderPathContentPacks "$ContentPack\OSLanguageFeatures" if (! (Test-Path "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture")) {New-Item -Path "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture" -ItemType Directory -Force -ErrorAction Ignore | Out-Null} Add-ContentPackOSLanguageFeatures -ContentPackContent "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture" } } if ($PackType -eq 'OSLanguagePacks') { Show-ActionTime; Write-Host -ForegroundColor Green "OSLanguagePacks ContentPack" foreach ($ContentPack in $ContentPacks) { $ContentPackPath = Join-Path $SetOSDBuilderPathContentPacks "$ContentPack\OSLanguagePacks" if (! (Test-Path "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture")) {New-Item -Path "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture" -ItemType Directory -Force -ErrorAction Ignore | Out-Null} Add-ContentPackOSLanguagePacks -ContentPackContent "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture" } } if ($PackType -eq 'OSLocalExperiencePacks') { Show-ActionTime; Write-Host -ForegroundColor Green "OSLocalExperiencePacks ContentPack" foreach ($ContentPack in $ContentPacks) { $ContentPackPath = Join-Path $SetOSDBuilderPathContentPacks "$ContentPack\OSLocalExperiencePacks" if (! (Test-Path "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture")) {New-Item -Path "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture" -ItemType Directory -Force -ErrorAction Ignore | Out-Null} Add-ContentPackOSLocalExperiencePacks -ContentPackContent "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture" } } if ($PackType -eq 'OSPackages') { Show-ActionTime; Write-Host -ForegroundColor Green "OSPackages ContentPack" foreach ($ContentPack in $ContentPacks) { $ContentPackPath = Join-Path $SetOSDBuilderPathContentPacks "$ContentPack\OSPackages" if (! (Test-Path "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture")) {New-Item -Path "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture" -ItemType Directory -Force -ErrorAction Ignore | Out-Null} Add-ContentPackOSPackages -ContentPackContent "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture" } } if ($PackType -eq 'OSPoshMods') { Show-ActionTime; Write-Host -ForegroundColor Green "OSPoshMods ContentPack" foreach ($ContentPack in $ContentPacks) { $ContentPackPath = Join-Path $SetOSDBuilderPathContentPacks "$ContentPack\OSPoshMods" if (! (Test-Path "$ContentPackPath\ProgramFiles")) {New-Item -Path "$ContentPackPath\ProgramFiles" -ItemType Directory -Force -ErrorAction Ignore | Out-Null} Add-ContentPackOSPoshMods -ContentPackContent "$ContentPackPath\ProgramFiles" } foreach ($ContentPack in $ContentPacks) { $ContentPackPath = Join-Path $SetOSDBuilderPathContentPacks "$ContentPack\OSPoshMods" if (! (Test-Path "$ContentPackPath\System")) {New-Item -Path "$ContentPackPath\System" -ItemType Directory -Force -ErrorAction Ignore | Out-Null} Add-ContentPackOSPoshModsSystem -ContentPackContent "$ContentPackPath\System" } } if ($PackType -eq 'OSRegistry') { Show-ActionTime; Write-Host -ForegroundColor Green "OSRegistry ContentPack" foreach ($ContentPack in $ContentPacks) { $ContentPackPath = Join-Path $SetOSDBuilderPathContentPacks "$ContentPack\OSRegistry" $ContentPaths = @( "$ContentPackPath\ALL" "$ContentPackPath\$OSArchitecture" "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture" ) foreach ($ContentPath in $ContentPaths) { if (! (Test-Path $ContentPath)) {New-Item -Path $ContentPath -ItemType Directory -Force -ErrorAction Ignore | Out-Null} Add-ContentPackOSRegistry -ContentPackContent $ContentPath } } } if ($PackType -eq 'OSScripts') { Show-ActionTime; Write-Host -ForegroundColor Green "OSScripts ContentPack" foreach ($ContentPack in $ContentPacks) { $ContentPackPath = Join-Path $SetOSDBuilderPathContentPacks "$ContentPack\OSScripts" $ContentPaths = @( "$ContentPackPath\ALL" "$ContentPackPath\$OSArchitecture" "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture" ) foreach ($ContentPath in $ContentPaths) { if (! (Test-Path $ContentPath)) {New-Item -Path $ContentPath -ItemType Directory -Force -ErrorAction Ignore | Out-Null} Add-ContentPackOSScripts -ContentPackContent $ContentPath } } } if ($PackType -eq 'OSStartLayout') { Show-ActionTime; Write-Host -ForegroundColor Green "OSStartLayout ContentPack" foreach ($ContentPack in $ContentPacks) { $ContentPackPath = Join-Path $SetOSDBuilderPathContentPacks "$ContentPack\OSStartLayout" $ContentPaths = @( "$ContentPackPath\ALL" "$ContentPackPath\$OSArchitecture" "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture" ) foreach ($ContentPath in $ContentPaths) { if (! (Test-Path $ContentPath)) {New-Item -Path $ContentPath -ItemType Directory -Force -ErrorAction Ignore | Out-Null} Add-ContentPackOSStartLayouts -ContentPackContent $ContentPath } } } #================================================= # WinPE ContentPacks #================================================= if ($PackType -eq 'PEADK') { Show-ActionTime; Write-Host -ForegroundColor Green "WinPE: PEADK ContentPack" foreach ($ContentPack in $ContentPacks) { $ContentPackPath = Join-Path $SetOSDBuilderPathContentPacks "$ContentPack\PEADK" if (! (Test-Path "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture")) {New-Item -Path "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture" -ItemType Directory -Force -ErrorAction Ignore | Out-Null} Add-ContentPackPEADK -ContentPackContent "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture" } } if ($PackType -eq 'PEADKLang') { Show-ActionTime; Write-Host -ForegroundColor Green "WinPE: PEADKLang ContentPack" foreach ($ContentPack in $ContentPacks) { $ContentPackPath = Join-Path $SetOSDBuilderPathContentPacks "$ContentPack\PEADKLang" if (! (Test-Path "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture")) {New-Item -Path "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture" -ItemType Directory -Force -ErrorAction Ignore | Out-Null} Add-ContentPackPEADK -ContentPackContent "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture" -Lang } } if ($PackType -eq 'PEDaRT') { Show-ActionTime; Write-Host -ForegroundColor Green "WinPE: PEDaRT ContentPack" foreach ($ContentPack in $ContentPacks) { $ContentPackPath = Join-Path $SetOSDBuilderPathContentPacks "$ContentPack\PEDaRT" if (! (Test-Path $ContentPackPath)) {New-Item -Path $ContentPackPath -ItemType Directory -Force -ErrorAction Ignore | Out-Null} Add-ContentPackPEDaRT -ContentPackContent "$ContentPackPath" } } if ($PackType -eq 'PEDrivers') { Show-ActionTime; Write-Host -ForegroundColor Green "WinPE: PEDrivers ContentPack" foreach ($ContentPack in $ContentPacks) { $ContentPackPath = Join-Path $SetOSDBuilderPathContentPacks "$ContentPack\PEDrivers" $ContentPaths = @( "$ContentPackPath\ALL" "$ContentPackPath\$OSArchitecture" "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture" ) foreach ($ContentPath in $ContentPaths) { if (! (Test-Path $ContentPath)) {New-Item -Path $ContentPath -ItemType Directory -Force -ErrorAction Ignore | Out-Null} Add-ContentPackPEDrivers -ContentPackContent $ContentPath } } } if ($PackType -eq 'PEExtraFiles') { Show-ActionTime; Write-Host -ForegroundColor Green "WinPE: PEExtraFiles ContentPack" foreach ($ContentPack in $ContentPacks) { $ContentPackPath = Join-Path $SetOSDBuilderPathContentPacks "$ContentPack\PEExtraFiles" $ContentPaths = @( "$ContentPackPath\ALL" "$ContentPackPath\$OSArchitecture" "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture" ) foreach ($ContentPath in $ContentPaths) { if (! (Test-Path $ContentPath)) {New-Item -Path $ContentPath -ItemType Directory -Force -ErrorAction Ignore | Out-Null} Add-ContentPackPEExtraFiles -ContentPackContent $ContentPath } Get-ChildItem "$ContentPackPath\ALL Subdirs" -Directory -ErrorAction SilentlyContinue | foreach { Add-ContentPackPEExtraFiles -ContentPackContent "$($_.FullName)" } Get-ChildItem "$ContentPackPath\$OSArchitecture Subdirs" -Directory -ErrorAction SilentlyContinue | foreach { Add-ContentPackPEExtraFiles -ContentPackContent "$($_.FullName)" } } } if ($PackType -eq 'PEPoshMods') { Show-ActionTime; Write-Host -ForegroundColor Green "WinPE: PEPoshMods ContentPack" foreach ($ContentPack in $ContentPacks) { $ContentPackPath = Join-Path $SetOSDBuilderPathContentPacks "$ContentPack\PEPoshMods" if (! (Test-Path "$ContentPackPath\ProgramFiles")) {New-Item -Path "$ContentPackPath\ProgramFiles" -ItemType Directory -Force -ErrorAction Ignore | Out-Null} Add-ContentPackPEPoshMods -ContentPackContent "$ContentPackPath\ProgramFiles" } foreach ($ContentPack in $ContentPacks) { $ContentPackPath = Join-Path $SetOSDBuilderPathContentPacks "$ContentPack\PEPoshMods" if (! (Test-Path "$ContentPackPath\System")) {New-Item -Path "$ContentPackPath\System" -ItemType Directory -Force -ErrorAction Ignore | Out-Null} Add-ContentPackPEPoshModsSystem -ContentPackContent "$ContentPackPath\System" } } if ($PackType -eq 'PERegistry') { Show-ActionTime; Write-Host -ForegroundColor Green "WinPE: PERegistry ContentPack" foreach ($ContentPack in $ContentPacks) { $ContentPackPath = Join-Path $SetOSDBuilderPathContentPacks "$ContentPack\PERegistry" $ContentPaths = @( "$ContentPackPath\ALL" "$ContentPackPath\$OSArchitecture" "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture" ) foreach ($ContentPath in $ContentPaths) { if (! (Test-Path $ContentPath)) {New-Item -Path $ContentPath -ItemType Directory -Force -ErrorAction Ignore | Out-Null} Add-ContentPackPERegistry -ContentPackContent $ContentPath } } } if ($PackType -eq 'PEScripts') { Show-ActionTime; Write-Host -ForegroundColor Green "WinPE: PEScripts ContentPack" foreach ($ContentPack in $ContentPacks) { $ContentPackPath = Join-Path $SetOSDBuilderPathContentPacks "$ContentPack\PEScripts" $ContentPaths = @( "$ContentPackPath\ALL" "$ContentPackPath\$OSArchitecture" "$ContentPackPath\$UpdateOS $ReleaseID $OSArchitecture" ) foreach ($ContentPath in $ContentPaths) { if (! (Test-Path $ContentPath)) {New-Item -Path $ContentPath -ItemType Directory -Force -ErrorAction Ignore | Out-Null} Add-ContentPackPEScripts -ContentPackContent $ContentPath } } } } } function Add-ContentPackMEDIA { [CmdletBinding()] param ( [Parameter(Mandatory)] [string]$ContentPackContent ) #Write-Host -ForegroundColor DarkGray "AutoApply Content $ContentPackContent" #====================================================================================== # Test #====================================================================================== if (!(Test-Path "$ContentPackContent\*")) { Write-Host -ForegroundColor DarkGray " $ContentPackContent" Return } else { Write-Host -ForegroundColor Gray " $ContentPackContent" } #====================================================================================== # Import #====================================================================================== $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-ContentPackMEDIA.log" Write-Verbose "CurrentLog: $CurrentLog" Get-ChildItem "$ContentPackContent" *.* -File -Recurse | Select-Object -Property FullName | foreach {Write-Host -ForegroundColor Gray "$($_.FullName)"} robocopy "$ContentPackContent" "$OS" *.* /s /ndl /xx /b /np /ts /tee /r:0 /w:0 /Log+:"$CurrentLog" | Out-Null } function Add-ContentPackOSDrivers { [CmdletBinding()] param ( [Parameter(Mandatory)] [string]$ContentPackContent #[string]$MountDirectory ) #Write-Host -ForegroundColor DarkGray "AutoApply Content $ContentPackContent" #====================================================================================== # Test #====================================================================================== if (!(Test-Path "$ContentPackContent\*")) { Write-Host -ForegroundColor DarkGray " $ContentPackContent" Return } else { Write-Host -ForegroundColor Gray " $ContentPackContent" } #====================================================================================== # Import #====================================================================================== $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-ContentPackOSDrivers.log" Write-Verbose "CurrentLog: $CurrentLog" Get-ChildItem "$ContentPackContent" *.inf -File -Recurse | Select-Object -Property FullName | foreach {Write-Host -ForegroundColor Gray "$($_.FullName)"} if ($OSMajorVersion -eq 6) { dism /Image:"$MountDirectory" /Add-Driver /Driver:"$ContentPackContent" /Recurse /ForceUnsigned /LogPath:"$CurrentLog" } else { Add-WindowsDriver -Driver "$ContentPackContent" -Recurse -Path "$MountDirectory" -ForceUnsigned -LogPath "$CurrentLog" | Out-Null } } function Add-ContentPackOSExtraFiles { [CmdletBinding()] param ( [Parameter(Mandatory)] [string]$ContentPackContent ) #Write-Host -ForegroundColor DarkGray "AutoApply Content $ContentPackContent" #====================================================================================== # Test #====================================================================================== if (!(Test-Path "$ContentPackContent\*")) { Write-Host -ForegroundColor DarkGray " $ContentPackContent" Return } else { Write-Host -ForegroundColor Gray " $ContentPackContent" } #====================================================================================== # Import #====================================================================================== $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-ContentPackOSExtraFiles.log" Write-Verbose "CurrentLog: $CurrentLog" Get-ChildItem "$ContentPackContent" *.* -File -Recurse | Select-Object -Property FullName | foreach {Write-Host -ForegroundColor Gray "$($_.FullName)"} robocopy "$ContentPackContent" "$MountDirectory" *.* /s /ndl /xx /b /np /ts /tee /r:0 /w:0 /Log+:"$CurrentLog" | Out-Null } function Add-ContentPackOSCapability { [CmdletBinding()] param ( [Parameter(Mandatory)] [string]$ContentPackContent, [switch]$RSAT ) #====================================================================================== # Test #====================================================================================== if (!(Test-Path "$ContentPackContent\FoDMetadata_Client.cab")) { Write-Host -ForegroundColor DarkGray " $ContentPackContent" Return } else { $global:ReapplyLCU = $true Write-Host -ForegroundColor Cyan " $ContentPackContent" } #====================================================================================== # Import #====================================================================================== if (Get-Command Get-WindowsCapability) { if ($RSAT.IsPresent) { if ((Get-Command Get-WindowsCapability).Parameters.ContainsKey('LimitAccess')) { Get-WindowsCapability -Path $MountDirectory -LimitAccess | Where-Object {$_.Name -match 'RSAT'} | Where-Object {$_.State -eq 'NotPresent'} | foreach { $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-ContentPackOSCapability-$($_.Name).log" Write-Verbose "CurrentLog: $CurrentLog" Write-Host -ForegroundColor DarkGray " $($_.Name)" Try { Add-WindowsCapability -Path $MountDirectory -Name $_.Name -Source $ContentPackContent -LimitAccess -LogPath $CurrentLog | Out-Null } Catch { if ($_.Exception.Message -match '0x800f081e') { Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose } else { Write-Warning $_.Exception.ErrorCode Write-Warning $_.Exception.Message } } } } else { Get-WindowsCapability -Path $MountDirectory | Where-Object {$_.Name -match 'RSAT'} | Where-Object {$_.State -eq 'NotPresent'} | foreach { $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-ContentPackOSCapability-$($_.Name).log" Write-Verbose "CurrentLog: $CurrentLog" Write-Host -ForegroundColor DarkGray " $($_.Name)" Try { Add-WindowsCapability -Path $MountDirectory -Name $_.Name -Source $ContentPackContent -LogPath $CurrentLog | Out-Null } Catch { if ($_.Exception.Message -match '0x800f081e') { Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose } else { Write-Warning $_.Exception.ErrorCode Write-Warning $_.Exception.Message } } } } } else { if ((Get-Command Get-WindowsCapability).Parameters.ContainsKey('LimitAccess')) { Get-WindowsCapability -Path $MountDirectory -LimitAccess | Where-Object {$_.Name -notmatch 'Language'} | Where-Object {$_.Name -notmatch 'RSAT'} | Where-Object {$_.State -eq 'NotPresent'} | foreach { $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-ContentPackOSCapability-$($_.Name).log" Write-Verbose "CurrentLog: $CurrentLog" Write-Host -ForegroundColor DarkGray " $($_.Name)" Try { Add-WindowsCapability -Path $MountDirectory -Name $_.Name -Source $ContentPackContent -LimitAccess -LogPath $CurrentLog | Out-Null } Catch { if ($_.Exception.Message -match '0x800f081e') { Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose } else { Write-Warning $_.Exception.ErrorCode Write-Warning $_.Exception.Message } } } } else { Get-WindowsCapability -Path $MountDirectory | Where-Object {$_.Name -notmatch 'Language'} | Where-Object {$_.Name -notmatch 'RSAT'} | Where-Object {$_.State -eq 'NotPresent'} | foreach { $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-ContentPackOSCapability-$($_.Name).log" Write-Verbose "CurrentLog: $CurrentLog" Write-Host -ForegroundColor DarkGray " $($_.Name)" Try { Add-WindowsCapability -Path $MountDirectory -Name $_.Name -Source $ContentPackContent -LogPath $CurrentLog | Out-Null } Catch { if ($_.Exception.Message -match '0x800f081e') { Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose } else { Write-Warning $_.Exception.ErrorCode Write-Warning $_.Exception.Message } } } } } } <# if ($RSAT.IsPresent) { Get-WindowsCapability -Path $MountDirectory -LimitAccess | Where-Object {$_.Name -match 'RSAT'} | Where-Object {$_.State -eq 'NotPresent'} | foreach { $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-ContentPackOSCapability-$($_.Name).log" Write-Verbose "CurrentLog: $CurrentLog" Write-Host -ForegroundColor Gray " $($_.Name)" Try { Add-WindowsCapability -Path $MountDirectory -Name $_.Name -Source $ContentPackContent -LimitAccess -LogPath $CurrentLog | Out-Null } Catch { if ($_.Exception.Message -match '0x800f081e') { Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose } else { Write-Warning $_.Exception.ErrorCode Write-Warning $_.Exception.Message } } } } else { Get-WindowsCapability -Path $MountDirectory -LimitAccess | Where-Object {$_.Name -notmatch 'Language'} | Where-Object {$_.Name -notmatch 'RSAT'} | Where-Object {$_.State -eq 'NotPresent'} | foreach { $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-ContentPackOSCapability-$($_.Name).log" Write-Verbose "CurrentLog: $CurrentLog" Write-Host -ForegroundColor Gray " $($_.Name)" Try { Add-WindowsCapability -Path $MountDirectory -Name $_.Name -Source $ContentPackContent -LimitAccess -LogPath $CurrentLog | Out-Null } Catch { if ($_.Exception.Message -match '0x800f081e') { Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose } else { Write-Warning $_.Exception.ErrorCode Write-Warning $_.Exception.Message } } } } #> <# $OSFeaturesFiles = Get-ChildItem "$ContentPackContent\*" -Include *.cab -File -Recurse | Sort-Object Name | Select-Object Name, FullName, Directory Pause Get-WindowsCapability -Offline -Path $MountDirectory foreach ($item in $OSFeaturesFiles) { $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-ContentPackOSCapability-$($item.Name).log" Write-Verbose "CurrentLog: $CurrentLog" Write-Host "$($item.FullName)" -ForegroundColor DarkGray if ($MountDirectory) { Try {Add-WindowsCapability -Name $item.FullName -Path $MountDirectory -Source $item.Directory -LimitAccess -LogPath $CurrentLog | Out-Null} Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } Try {Add-WindowsPackage -PackagePath "$($item.FullName)" -Path "$MountDirectory" -LogPath $CurrentLog | Out-Null} Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } } } #> } function Add-ContentPackOSLanguageFeatures { [CmdletBinding()] param ( [Parameter(Mandatory)] [string]$ContentPackContent ) #Write-Host -ForegroundColor DarkGray "AutoApply Content $ContentPackContent" #====================================================================================== # Test #====================================================================================== if (!(Test-Path "$ContentPackContent\*")) { Write-Host -ForegroundColor DarkGray " $ContentPackContent" Return } else { Write-Host -ForegroundColor Gray " $ContentPackContent" } #====================================================================================== # Import #====================================================================================== $OSLanguageFeaturesFiles = Get-ChildItem "$ContentPackContent\*" -Include *.cab -File -Recurse | Sort-Object Length -Descending | Select-Object Name, FullName foreach ($OSLanguageFeaturesFile in $OSLanguageFeaturesFiles) { $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-ContentPackOSLanguageFeatures-$($OSLanguageFeaturesFile.Name).log" Write-Verbose "CurrentLog: $CurrentLog" Write-Host "$($OSLanguageFeaturesFile.FullName)" -ForegroundColor DarkGray if ($MountDirectory) { Try { $global:ReapplyLCU = $true Add-WindowsPackage -PackagePath "$($OSLanguageFeaturesFile.FullName)" -Path "$MountDirectory" -LogPath $CurrentLog | Out-Null } Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } } } } function Add-ContentPackOSLanguagePacks { [CmdletBinding()] param ( [Parameter(Mandatory)] [string]$ContentPackContent ) #Write-Host -ForegroundColor DarkGray "AutoApply Content $ContentPackContent" #====================================================================================== # Test #====================================================================================== if (!(Test-Path "$ContentPackContent\*")) { Write-Host -ForegroundColor DarkGray " $ContentPackContent" Return } else { Write-Host -ForegroundColor Gray " $ContentPackContent" } #====================================================================================== # Import #====================================================================================== $OSLanguagePacksFiles = Get-ChildItem "$ContentPackContent\*" -Include *.cab -File | Sort-Object Length -Descending | Select-Object Name, FullName foreach ($OSLanguagePacksFile in $OSLanguagePacksFiles) { $global:ReapplyLCU = $true $global:UpdateLanguageContent = $true $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-ContentPackOSLanguagePacks-$($OSLanguagePacksFile.Name).log" Write-Verbose "CurrentLog: $CurrentLog" Write-Host "$($OSLanguagePacksFile.FullName)" -ForegroundColor DarkGray if ($MountDirectory) { Try {Add-WindowsPackage -PackagePath "$($OSLanguagePacksFile.FullName)" -Path "$MountDirectory" -LogPath $CurrentLog | Out-Null} Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } } } } function Add-ContentPackOSLocalExperiencePacks { [CmdletBinding()] param ( [Parameter(Mandatory)] [string]$ContentPackContent ) #Write-Host -ForegroundColor DarkGray "AutoApply Content $ContentPackContent" #====================================================================================== # Test #====================================================================================== if (!(Test-Path "$ContentPackContent\*")) { Write-Host -ForegroundColor DarkGray " $ContentPackContent" Return } else { Write-Host -ForegroundColor Gray " $ContentPackContent" } #====================================================================================== # Import #====================================================================================== $OSLocalExperiencePacksFiles = Get-ChildItem "$ContentPackContent" *.appx -File -Recurse | Sort-Object Length -Descending | Select-Object Name, FullName foreach ($OSLocalExperiencePacksFile in $OSLocalExperiencePacksFiles) { $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-ContentPackOSLocalExperiencePacks-$($OSLocalExperiencePacksFile.Name).log" Write-Verbose "CurrentLog: $CurrentLog" Write-Host "$($OSLocalExperiencePacksFile.FullName)" -ForegroundColor DarkGray if ($MountDirectory) { $LicensePath = "$((Get-Item $OSLocalExperiencePacksFile.FullName).Directory.FullName)\License.xml" if (!(Test-Path $LicensePath)) { Write-Warning "Unable to find Appx License at $LicensePath" } else { Try { $global:ReapplyLCU = $true Add-AppxProvisionedPackage -Path "$MountDirectory" -PackagePath $OSLocalExperiencePacksFile.FullName -LicensePath $LicensePath -LogPath $CurrentLog | Out-Null } Catch {$ErrorMessage = $_.Exception.$ErrorMessage; Write-Warning "$CurrentLog"; Write-Host "$ErrorMessage"} } } } } function Add-ContentPackOSPackages { [CmdletBinding()] param ( [Parameter(Mandatory)] [string]$ContentPackContent ) #Write-Host -ForegroundColor DarkGray "AutoApply Content $ContentPackContent" #====================================================================================== # Test #====================================================================================== if (!(Test-Path "$ContentPackContent\*")) { Write-Host -ForegroundColor DarkGray " $ContentPackContent" Return } else { Write-Host -ForegroundColor Gray " $ContentPackContent" } #====================================================================================== # Import #====================================================================================== $OSPackagesFiles = Get-ChildItem "$ContentPackContent\*" -Include *.cab -File -Recurse | Sort-Object Name | Select-Object Name, FullName foreach ($item in $OSPackagesFiles) { $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-ContentPackOSPackages-$($item.Name).log" Write-Verbose "CurrentLog: $CurrentLog" Write-Host "$($item.FullName)" -ForegroundColor DarkGray if ($MountDirectory) { Try { $global:ReapplyLCU = $true Add-WindowsPackage -PackagePath "$($item.FullName)" -Path "$MountDirectory" -LogPath $CurrentLog | Out-Null } Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } } } } function Add-ContentPackOSPoshMods { [CmdletBinding()] param ( [Parameter(Mandatory)] [string]$ContentPackContent ) #Write-Host -ForegroundColor DarkGray "AutoApply Content $ContentPackContent" Write-Warning "OSPoshMods is being deprecated in the near future" #====================================================================================== # Test #====================================================================================== if (!(Test-Path "$ContentPackContent\*")) { Write-Host -ForegroundColor DarkGray " $ContentPackContent" Return } else { Write-Host -ForegroundColor Gray " $ContentPackContent" } #====================================================================================== # Import #====================================================================================== $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-ContentPackOSPoshMods.log" Write-Verbose "CurrentLog: $CurrentLog" Get-ChildItem "$ContentPackContent" *.* -File -Recurse | Select-Object -Property FullName | foreach {Write-Host -ForegroundColor Gray "$($_.FullName)"} robocopy "$ContentPackContent" "$MountDirectory\Program Files\WindowsPowerShell\Modules" *.* /s /ndl /xx /b /np /ts /tee /r:0 /w:0 /Log+:"$CurrentLog" | Out-Null } function Add-ContentPackOSPoshModsSystem { [CmdletBinding()] param ( [Parameter(Mandatory)] [string]$ContentPackContent ) #Write-Host -ForegroundColor DarkGray "AutoApply Content $ContentPackContent" Write-Warning "OSPoshModsSystem is being deprecated in the near future" #====================================================================================== # Test #====================================================================================== if (!(Test-Path "$ContentPackContent\*")) { Write-Host -ForegroundColor DarkGray " $ContentPackContent" Return } else { Write-Host -ForegroundColor Gray " $ContentPackContent" } #====================================================================================== # Import #====================================================================================== $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-ContentPackOSPoshModsSystem.log" Write-Verbose "CurrentLog: $CurrentLog" Get-ChildItem "$ContentPackContent" *.* -File -Recurse | Select-Object -Property FullName | foreach {Write-Host -ForegroundColor Gray "$($_.FullName)"} robocopy "$ContentPackContent" "$MountDirectory\Windows\System32\WindowsPowerShell\v1.0\Modules" *.* /s /ndl /xx /b /np /ts /tee /r:0 /w:0 /Log+:"$CurrentLog" | Out-Null } function Add-ContentPackOSRegistry { [CmdletBinding()] param ( [Parameter(Mandatory)] [string]$ContentPackContent, [switch]$ShowRegContent ) #Write-Host -ForegroundColor DarkGray "AutoApply Content $ContentPackContent" #====================================================================================== # Test-OSDContentPackOSRegistry #====================================================================================== if (!(Test-Path "$ContentPackContent\*")) { Write-Host -ForegroundColor DarkGray " $ContentPackContent" Return } else { Write-Host -ForegroundColor Gray " $ContentPackContent" } #====================================================================================== # Mount-OfflineRegistryHives #====================================================================================== if (($MountDirectory) -and (Test-Path "$MountDirectory" -ErrorAction SilentlyContinue)) { if (Test-Path "$MountDirectory\Users\Default\NTUser.dat") { Write-Verbose "Loading Offline Registry Hive Default User" Start-Process reg -ArgumentList "load HKLM\OfflineDefaultUser $MountDirectory\Users\Default\NTUser.dat" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path "$MountDirectory\Windows\System32\Config\DEFAULT") { Write-Verbose "Loading Offline Registry Hive DEFAULT" Start-Process reg -ArgumentList "load HKLM\OfflineDefault $MountDirectory\Windows\System32\Config\DEFAULT" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path "$MountDirectory\Windows\System32\Config\SOFTWARE") { Write-Verbose "Loading Offline Registry Hive SOFTWARE" Start-Process reg -ArgumentList "load HKLM\OfflineSoftware $MountDirectory\Windows\System32\Config\SOFTWARE" -Wait -WindowStyle Hidden -ErrorAction Stop } if (Test-Path "$MountDirectory\Windows\System32\Config\SYSTEM") { Write-Verbose "Loading Offline Registry Hive SYSTEM" Start-Process reg -ArgumentList "load HKLM\OfflineSystem $MountDirectory\Windows\System32\Config\SYSTEM" -Wait -WindowStyle Hidden -ErrorAction Stop } $OSDContentPackTemp = "$env:TEMP\$(Get-Random)" if (!(Test-Path $OSDContentPackTemp)) {New-Item -Path "$OSDContentPackTemp" -ItemType Directory -Force | Out-Null} } #====================================================================================== # Get-RegFiles #====================================================================================== [array]$ContentPackContentFiles = @() [array]$ContentPackContentFiles = Get-ChildItem "$ContentPackContent" *.reg -Recurse | Select-Object -Property Name, BaseName, Extension, Directory, FullName #====================================================================================== # Add-ContentPackOSRegistryFiles #====================================================================================== foreach ($OSDRegistryRegFile in $ContentPackContentFiles) { $OSDRegistryImportFile = $OSDRegistryRegFile.FullName if ($MountDirectory) { $RegFileContent = Get-Content -Path $OSDRegistryImportFile $OSDRegistryImportFile = "$OSDContentPackTemp\$($OSDRegistryRegFile.BaseName).reg" $RegFileContent = $RegFileContent -replace 'HKEY_CURRENT_USER','HKEY_LOCAL_MACHINE\OfflineDefaultUser' $RegFileContent = $RegFileContent -replace 'HKEY_LOCAL_MACHINE\\SOFTWARE','HKEY_LOCAL_MACHINE\OfflineSoftware' $RegFileContent = $RegFileContent -replace 'HKEY_LOCAL_MACHINE\\SYSTEM','HKEY_LOCAL_MACHINE\OfflineSystem' $RegFileContent = $RegFileContent -replace 'HKEY_USERS\\.DEFAULT','HKEY_LOCAL_MACHINE\OfflineDefault' $RegFileContent | Set-Content -Path $OSDRegistryImportFile -Force } Write-Host "$OSDRegistryImportFile" -ForegroundColor DarkGray if ($ShowRegContent.IsPresent){ $OSDContentPackRegFileContent = @() $OSDContentPackRegFileContent = Get-Content -Path $OSDRegistryImportFile foreach ($Line in $OSDContentPackRegFileContent) { Write-Host "$Line" -ForegroundColor Gray } } Start-Process reg -ArgumentList ('import',"`"$OSDRegistryImportFile`"") -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } #====================================================================================== # Remove-OSDContentPackTemp #====================================================================================== if ($MountDirectory) { if (Test-Path $OSDContentPackTemp) {Remove-Item -Path "$OSDContentPackTemp" -Recurse -Force | Out-Null} } #====================================================================================== # Dismount-RegistryHives #====================================================================================== Dismount-OSDOfflineRegistry -MountPath $MountDirectory } function Add-ContentPackOSScripts { [CmdletBinding()] param ( [Parameter(Mandatory)] [string]$ContentPackContent ) #Write-Host -ForegroundColor DarkGray "AutoApply Content $ContentPackContent" #====================================================================================== # TEST #====================================================================================== if (!(Test-Path "$ContentPackContent\*")) { Write-Host -ForegroundColor DarkGray " $ContentPackContent" Return } else {Write-Host -ForegroundColor Cyan " $ContentPackContent"} #====================================================================================== # BUILD #====================================================================================== $ContentPackOSScripts = Get-ChildItem "$ContentPackContent" *.ps1 -File -Recurse | Select-Object -Property FullName foreach ($ContentPackOSScript in $ContentPackOSScripts) { Write-Host "$($ContentPackOSScript.FullName)" -ForegroundColor DarkGray Invoke-Expression "& '$($ContentPackOSScript.FullName)'" } } function Add-ContentPackOSStartLayouts { [CmdletBinding()] param ( [Parameter(Mandatory)] [string]$ContentPackContent ) #====================================================================================== # TEST #====================================================================================== if (!(Test-Path "$ContentPackContent\*")) { Write-Host -ForegroundColor DarkGray " $ContentPackContent" Return } else { Write-Host -ForegroundColor Gray " $ContentPackContent" } #====================================================================================== # BUILD #====================================================================================== $ContentPackOSStartLayouts = Get-ChildItem "$ContentPackContent\*.xml" -File | Select-Object -Property FullName foreach ($ContentPackOSStartLayout in $ContentPackOSStartLayouts) { Write-Host -ForegroundColor Cyan " $($ContentPackOSStartLayout.FullName)" Try { Copy-Item -Path "$($ContentPackOSStartLayout.FullName)" -Destination "$MountDirectory\Users\Default\AppData\Local\Microsoft\Windows\Shell\LayoutModification.xml" -Recurse -Force | Out-Null } Catch { $ErrorMessage = $_.Exception.Message Write-Warning "$ErrorMessage" } } } function Add-ContentPackPEADK { [CmdletBinding()] param ( [Parameter(Mandatory)] [string]$ContentPackContent, [string]$MountPath, [switch]$Lang #[ValidateSet('MDT','Recovery','WinPE')] #[string]$WinPEOutput, #[ValidateSet('WinPE','WinRE')] #[string]$SourceWim ) #====================================================================================== # Test #====================================================================================== if (!(Test-Path "$ContentPackContent\*")) { Write-Host -ForegroundColor DarkGray " $ContentPackContent" Return } else { Write-Host -ForegroundColor Gray " $ContentPackContent" } if ($Lang.IsPresent) { $global:ReapplyLCU = $true $global:UpdateLanguageContent = $true } #====================================================================================== # Import #====================================================================================== $ADKFiles = Get-ChildItem "$ContentPackContent\*" -Include *.cab -File | Sort-Object Length -Descending | Select-Object Name, FullName $ADKFilesSub = Get-ChildItem "$ContentPackContent\*\*" -Include *.cab -File -Recurse | Sort-Object Length -Descending | Select-Object Name, FullName if ($ScriptName -eq 'New-PEBuild') { if ($WinPEOutput -eq 'MDT') {} if ($WinPEOutput -eq 'Recovery') {} if ($WinPEOutput -eq 'WinPE') {} if ($SourceWim -eq 'WinPE') { $ADKFiles = $ADKFiles | Where-Object {$_.Name -notmatch 'setup'} | Where-Object {$_.Name -notmatch 'wifi'} | Where-Object {$_.Name -notmatch 'appxpackaging'} | Where-Object {$_.Name -notmatch 'rejuv'} | Where-Object {$_.Name -notmatch 'opcservices'} $ADKFilesSub = $ADKFilesSub | Where-Object {$_.Name -notmatch 'setup'} | Where-Object {$_.Name -notmatch 'wifi'} | Where-Object {$_.Name -notmatch 'appxpackaging'} | Where-Object {$_.Name -notmatch 'rejuv'} | Where-Object {$_.Name -notmatch 'opcservices'} } if ($SourceWim -eq 'WinRE') { $ADKFiles = $ADKFiles | Where-Object {$_.Name -notmatch 'setup'} $ADKFilesSub = $ADKFiles | Where-Object {$_.Name -notmatch 'setup'} } foreach ($ADKFile in $ADKFiles | Where-Object {$_.Name -eq 'lp.cab'}) { $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-ContentPackPEADK-$($ADKFile.Name).log" Write-Verbose "CurrentLog: $CurrentLog" Write-Host -ForegroundColor Cyan " $($ADKFile.Name)" if ($MountDirectory) { Try { Add-WindowsPackage -PackagePath "$($ADKFile.FullName)" -Path "$MountDirectory" -LogPath "$CurrentLog" | Out-Null } Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } } } foreach ($ADKFile in $ADKFiles | Where-Object {$_.Name -ne 'lp.cab'}) { $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-ContentPackPEADK-$($ADKFile.Name).log" Write-Verbose "CurrentLog: $CurrentLog" Write-Host -ForegroundColor Cyan " $($ADKFile.Name)" if ($MountDirectory) { Try {Add-WindowsPackage -PackagePath "$($ADKFile.FullName)" -Path "$MountDirectory" -LogPath "$CurrentLog" | Out-Null} Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } } } foreach ($ADKFile in $ADKFilesSub | Where-Object {$_.Name -eq 'lp.cab'}) { $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-ContentPackPEADK-$($ADKFile.Name).log" Write-Verbose "CurrentLog: $CurrentLog" Write-Host -ForegroundColor Cyan " $($ADKFile.Name)" if ($MountDirectory) { Try {Add-WindowsPackage -PackagePath "$($ADKFile.FullName)" -Path "$MountDirectory" -LogPath "$CurrentLog" | Out-Null} Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } } } foreach ($ADKFile in $ADKFilesSub | Where-Object {$_.Name -ne 'lp.cab'}) { $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-ContentPackPEADK-$($ADKFile.Name).log" Write-Verbose "CurrentLog: $CurrentLog" Write-Host -ForegroundColor Cyan " $($ADKFile.Name)" if ($MountDirectory) { Try {Add-WindowsPackage -PackagePath "$($ADKFile.FullName)" -Path "$MountDirectory" -LogPath "$CurrentLog" | Out-Null} Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } } } Return } foreach ($ADKFile in $ADKFiles | Where-Object {$_.Name -notmatch 'Setup'}) { Write-Host -ForegroundColor Cyan " $($ADKFile.Name)" if ($MountWinPE) { $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-ContentPackPEADK-$($ADKFile.Name).log" Try { Add-WindowsPackage -PackagePath "$($ADKFile.FullName)" -Path "$MountWinPE" -LogPath "$CurrentLog" | Out-Null } Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } } if ($MountWinRE) { $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-ContentPackPEADK-$($ADKFile.Name).log" Try { Add-WindowsPackage -PackagePath "$($ADKFile.FullName)" -Path "$MountWinRE" -LogPath "$CurrentLog" | Out-Null } Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } } if ($MountWinSE) { $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-ContentPackPEADK-$($ADKFile.Name).log" Try { Add-WindowsPackage -PackagePath "$($ADKFile.FullName)" -Path "$MountWinSE" -LogPath "$CurrentLog" | Out-Null } Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } } } $ADKFilesWinPE = $ADKFilesSub | Where-Object {$_.Name -notmatch 'setup'} | Where-Object {$_.Name -notmatch 'wifi'} | Where-Object {$_.Name -notmatch 'appxpackaging'} | Where-Object {$_.Name -notmatch 'rejuv'} | Where-Object {$_.Name -notmatch 'opcservices'} $ADKFilesWinRE = $ADKFilesSub | Where-Object {$_.Name -notmatch 'setup'} $ADKFilesWinSE = $ADKFilesSub | Where-Object {$_.Name -notmatch 'wifi'} | Where-Object {$_.Name -notmatch 'legacysetup'} | Where-Object {$_.Name -notmatch 'appxpackaging'} | Where-Object {$_.Name -notmatch 'rejuv'} | Where-Object {$_.Name -notmatch 'opcservices'} foreach ($ADKFile in $ADKFilesWinPE | Where-Object {$_.Name -eq 'lp.cab'}) { if ($MountWinPE) { $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-ContentPackPEADK-$($ADKFile.Name).log" Write-Host -ForegroundColor Cyan " $($ADKFile.Name) (WinPE)" Try { Add-WindowsPackage -PackagePath "$($ADKFile.FullName)" -Path "$MountWinPE" -LogPath "$CurrentLog" | Out-Null } Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } } } foreach ($ADKFile in $ADKFilesWinRE | Where-Object {$_.Name -eq 'lp.cab'}) { if ($MountWinRE) { $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-ContentPackPEADK-$($ADKFile.Name).log" Write-Host -ForegroundColor Cyan " $($ADKFile.Name) (WinRE)" Try { Add-WindowsPackage -PackagePath "$($ADKFile.FullName)" -Path "$MountWinRE" -LogPath "$CurrentLog" | Out-Null } Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } } } foreach ($ADKFile in $ADKFilesWinSE | Where-Object {$_.Name -eq 'lp.cab'}) { if ($MountWinSE) { $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-ContentPackPEADK-$($ADKFile.Name).log" Write-Host -ForegroundColor Cyan " $($ADKFile.Name) (WinSE)" Try { Add-WindowsPackage -PackagePath "$($ADKFile.FullName)" -Path "$MountWinSE" -LogPath "$CurrentLog" | Out-Null } Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } } } foreach ($ADKFile in $ADKFilesWinPE | Where-Object {$_.Name -ne 'lp.cab'}) { if ($MountWinPE) { $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-ContentPackPEADK-$($ADKFile.Name).log" Write-Host -ForegroundColor Cyan " $($ADKFile.Name) (WinPE)" Try { Add-WindowsPackage -PackagePath "$($ADKFile.FullName)" -Path "$MountWinPE" -LogPath "$CurrentLog" | Out-Null } Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } } } foreach ($ADKFile in $ADKFilesWinRE | Where-Object {$_.Name -ne 'lp.cab'}) { if ($MountWinRE) { $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-ContentPackPEADK-$($ADKFile.Name).log" Write-Host -ForegroundColor Cyan " $($ADKFile.Name) (WinRE)" Try { Add-WindowsPackage -PackagePath "$($ADKFile.FullName)" -Path "$MountWinRE" -LogPath "$CurrentLog" | Out-Null } Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } } } foreach ($ADKFile in $ADKFilesWinSE | Where-Object {$_.Name -ne 'lp.cab'}) { if ($MountWinSE) { $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-ContentPackPEADK-$($ADKFile.Name).log" Write-Host -ForegroundColor Cyan " $($ADKFile.Name) (WinSE)" Try { Add-WindowsPackage -PackagePath "$($ADKFile.FullName)" -Path "$MountWinSE" -LogPath "$CurrentLog" | Out-Null } Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } } } } function Add-ContentPackPEDaRT { [CmdletBinding()] param ( [Parameter(Mandatory)] [string]$ContentPackContent ) #====================================================================================== # TEST #====================================================================================== if (!(Test-Path "$ContentPackContent\Tools$($OSArchitecture).cab")) { Write-Host -ForegroundColor DarkGray " $ContentPackContent" Return } else { Write-Host -ForegroundColor Cyan " $ContentPackContent\Tools$($OSArchitecture).cab" } #====================================================================================== # BUILD #====================================================================================== $MicrosoftDartCab = "$ContentPackContent\Tools$($OSArchitecture).cab" if (Test-Path $MicrosoftDartCab) { if ($MountWinPE) {expand.exe "$MicrosoftDartCab" -F:*.* "$MountWinPE" | Out-Null} if ($MountWinRE) {expand.exe "$MicrosoftDartCab" -F:*.* "$MountWinRE" | Out-Null} if ($MountWinSE) {expand.exe "$MicrosoftDartCab" -F:*.* "$MountWinSE" | Out-Null} $MicrosoftDartConfig = $(Join-Path $(Split-Path "$MicrosoftDartCab") 'DartConfig.dat') if (Test-Path $MicrosoftDartConfig) { if ($MountWinPE) {Copy-Item -Path $MicrosoftDartConfig -Destination "$MountWinPE\Windows\System32\DartConfig.dat" -Force} if ($MountWinRE) {Copy-Item -Path $MicrosoftDartConfig -Destination "$MountWinSE\Windows\System32\DartConfig.dat" -Force} if ($MountWinSE) {Copy-Item -Path $MicrosoftDartConfig -Destination "$MountWinRE\Windows\System32\DartConfig.dat" -Force} } $MicrosoftDartConfig = $(Join-Path $(Split-Path "$MicrosoftDartCab") 'DartConfig8.dat') if (Test-Path $MicrosoftDartConfig) { if ($MountWinPE) {Copy-Item -Path $MicrosoftDartConfig -Destination "$MountWinPE\Windows\System32\DartConfig.dat" -Force} if ($MountWinRE) {Copy-Item -Path $MicrosoftDartConfig -Destination "$MountWinSE\Windows\System32\DartConfig.dat" -Force} if ($MountWinSE) {Copy-Item -Path $MicrosoftDartConfig -Destination "$MountWinRE\Windows\System32\DartConfig.dat" -Force} } if ($ScriptName -eq 'New-OSBuild') { if (Test-Path "$MountWinPE\Windows\System32\winpeshl.ini") {Remove-Item -Path "$MountWinPE\Windows\System32\winpeshl.ini" -Force} (Get-Content "$MountWinRE\Windows\System32\winpeshl.ini") | ForEach-Object {$_ -replace '-prompt','-network'} | Out-File "$MountWinRE\Windows\System32\winpeshl.ini" if (Test-Path "$MountWinSE\Windows\System32\winpeshl.ini") {Remove-Item -Path "$MountWinSE\Windows\System32\winpeshl.ini" -Force} } if ($ScriptName -eq 'New-PEBuild') { if ($WinPEOutput -eq 'Recovery') { (Get-Content "$MountDirectory\Windows\System32\winpeshl.ini") | ForEach-Object {$_ -replace '-prompt','-network'} | Out-File "$MountDirectory\Windows\System32\winpeshl.ini" } } } else { Write-Warning "Microsoft DaRT do not exist in $MicrosoftDartCab" } } function Add-ContentPackPEDrivers { [CmdletBinding()] param ( [Parameter(Mandatory)] [string]$ContentPackContent ) #====================================================================================== # Test #====================================================================================== if (!(Test-Path "$ContentPackContent\*")) { Write-Host -ForegroundColor DarkGray " $ContentPackContent" Return } else { Write-Host -ForegroundColor Gray " $ContentPackContent" } #====================================================================================== # Import #====================================================================================== $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-ContentPackPEDrivers.log" Write-Verbose "CurrentLog: $CurrentLog" Get-ChildItem "$ContentPackContent" *.inf -File -Recurse | Select-Object -Property FullName | foreach {Write-Host -ForegroundColor Gray "$($_.FullName)"} if ($OSMajorVersion -eq 6) { if ($MountWinPE) {dism /Image:"$MountWinPE" /Add-Driver /Driver:"$ContentPackContent" /Recurse /ForceUnsigned /LogPath:"$CurrentLog" | Out-Null} if ($MountWinRE) {dism /Image:"$MountWinRE" /Add-Driver /Driver:"$ContentPackContent" /Recurse /ForceUnsigned /LogPath:"$CurrentLog" | Out-Null} if ($MountWinSE) {dism /Image:"$MountWinSE" /Add-Driver /Driver:"$ContentPackContent" /Recurse /ForceUnsigned /LogPath:"$CurrentLog" | Out-Null} } else { if ($MountWinPE) {Add-WindowsDriver -Driver "$ContentPackContent" -Recurse -Path "$MountWinPE" -ForceUnsigned -LogPath "$CurrentLog" | Out-Null} if ($MountWinRE) {Add-WindowsDriver -Driver "$ContentPackContent" -Recurse -Path "$MountWinRE" -ForceUnsigned -LogPath "$CurrentLog" | Out-Null} if ($MountWinSE) {Add-WindowsDriver -Driver "$ContentPackContent" -Recurse -Path "$MountWinSE" -ForceUnsigned -LogPath "$CurrentLog" | Out-Null} } } function Add-ContentPackPEExtraFiles { [CmdletBinding()] param ( [Parameter(Mandatory)] [string]$ContentPackContent ) #====================================================================================== # Test #====================================================================================== if (!(Test-Path "$ContentPackContent\*")) { Write-Host -ForegroundColor DarkGray " $ContentPackContent" Return } else { Write-Host -ForegroundColor Gray " $ContentPackContent" } #====================================================================================== # Import #====================================================================================== $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-ContentPackPEExtraFiles.log" Write-Verbose "CurrentLog: $CurrentLog" Get-ChildItem "$ContentPackContent" *.* -File -Recurse | Select-Object -Property FullName | foreach {Write-Host -ForegroundColor Gray "$($_.FullName)"} #Save-WindowsImage -Path $MountWinPE | Out-Null if ($MountWinPE) { #robocopy "$ContentPackContent" "$MountWinPE" *.* /s /ndl /xx /b /np /ts /tee /r:0 /w:0 /Log+:"$CurrentLog" | Out-Null robocopy "$ContentPackContent" "$MountWinPE" *.* /S /B /COPY:D /NODCOPY /XJ /FP /NS /NC /NDL /NJH /NJS /NP /TEE /XX /R:0 /W:0 /LOG+:"$CurrentLog" | Out-Null #xcopy "$ContentPackContent" "$MountWinPE" /F /C /H /E /R /Y /J #Copy-Item "$ContentPackContent\*" -Destination "$MountWinPE\" -Recurse -Force } if ($MountWinRE) { #robocopy "$ContentPackContent" "$MountWinRE" *.* /s /ndl /xx /b /np /ts /tee /r:0 /w:0 /Log+:"$CurrentLog" | Out-Null robocopy "$ContentPackContent" "$MountWinRE" *.* /S /B /COPY:D /NODCOPY /XJ /FP /NS /NC /NDL /NJH /NJS /NP /TEE /XX /R:0 /W:0 /LOG+:"$CurrentLog" | Out-Null } if ($MountWinSE) { #robocopy "$ContentPackContent" "$MountWinSE" *.* /s /ndl /xx /b /np /ts /tee /r:0 /w:0 /Log+:"$CurrentLog" | Out-Null robocopy "$ContentPackContent" "$MountWinSE" *.* /S /B /COPY:D /NODCOPY /XJ /FP /NS /NC /NDL /NJH /NJS /NP /TEE /XX /R:0 /W:0 /LOG+:"$CurrentLog" | Out-Null } #Start-Sleep -Seconds 1 } function Add-ContentPackPEPoshMods { [CmdletBinding()] param ( [Parameter(Mandatory)] [string]$ContentPackContent ) #====================================================================================== # Test #====================================================================================== if (!(Test-Path "$ContentPackContent\*")) { Write-Host -ForegroundColor DarkGray " $ContentPackContent" Return } else { Write-Host -ForegroundColor Gray " $ContentPackContent" } #====================================================================================== # Import #====================================================================================== $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-ContentPackPEPoshMods.log" Write-Verbose "CurrentLog: $CurrentLog" Get-ChildItem "$ContentPackContent" *.* -File -Recurse | Select-Object -Property FullName | foreach {Write-Host -ForegroundColor Gray "$($_.FullName)"} if ($MountWinPE) {robocopy "$ContentPackContent" "$MountWinPE\Program Files\WindowsPowerShell\Modules" *.* /s /ndl /xx /b /np /ts /tee /r:0 /w:0 /Log+:"$CurrentLog" | Out-Null} if ($MountWinRE) {robocopy "$ContentPackContent" "$MountWinRE\Program Files\WindowsPowerShell\Modules" *.* /s /ndl /xx /b /np /ts /tee /r:0 /w:0 /Log+:"$CurrentLog" | Out-Null} if ($MountWinSE) {robocopy "$ContentPackContent" "$MountWinSE\Program Files\WindowsPowerShell\Modules" *.* /s /ndl /xx /b /np /ts /tee /r:0 /w:0 /Log+:"$CurrentLog" | Out-Null} } function Add-ContentPackPEPoshModsSystem { [CmdletBinding()] param ( [Parameter(Mandatory)] [string]$ContentPackContent ) #====================================================================================== # Test #====================================================================================== if (!(Test-Path "$ContentPackContent\*")) { Write-Host -ForegroundColor DarkGray " $ContentPackContent" Return } else { Write-Host -ForegroundColor Gray " $ContentPackContent" } #====================================================================================== # Import #====================================================================================== $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-ContentPackPEPoshModsSystem.log" Write-Verbose "CurrentLog: $CurrentLog" Get-ChildItem "$ContentPackContent" *.* -File -Recurse | Select-Object -Property FullName | foreach {Write-Host -ForegroundColor Gray "$($_.FullName)"} if ($MountWinPE) {robocopy "$ContentPackContent" "$MountWinPE\Windows\System32\WindowsPowerShell\v1.0\Modules" *.* /s /ndl /xx /b /np /ts /tee /r:0 /w:0 /Log+:"$CurrentLog" | Out-Null} if ($MountWinRE) {robocopy "$ContentPackContent" "$MountWinRE\Windows\System32\WindowsPowerShell\v1.0\Modules" *.* /s /ndl /xx /b /np /ts /tee /r:0 /w:0 /Log+:"$CurrentLog" | Out-Null} if ($MountWinSE) {robocopy "$ContentPackContent" "$MountWinSE\Windows\System32\WindowsPowerShell\v1.0\Modules" *.* /s /ndl /xx /b /np /ts /tee /r:0 /w:0 /Log+:"$CurrentLog" | Out-Null} } function Add-ContentPackPERegistry { [CmdletBinding()] param ( [Parameter(Mandatory)] [string]$ContentPackContent, [switch]$ShowRegContent ) #====================================================================================== # Test-OSDContentPackPERegistry #====================================================================================== if (!(Test-Path "$ContentPackContent\*")) { Write-Host -ForegroundColor DarkGray " $ContentPackContent" Return } else { Write-Host -ForegroundColor Gray " $ContentPackContent" } #====================================================================================== # Mount-OfflineRegistryHives #====================================================================================== if (($MountWinPE) -and (Test-Path "$MountWinPE" -ErrorAction SilentlyContinue)) { Mount-OSDOfflineRegistryPE -MountPath $MountWinPE } else { Return } $OSDContentPackTemp = "$env:TEMP\$(Get-Random)" if (!(Test-Path $OSDContentPackTemp)) {New-Item -Path "$OSDContentPackTemp" -ItemType Directory -Force | Out-Null} #====================================================================================== # Get-RegFiles #====================================================================================== [array]$ContentPackContentFiles = @() [array]$ContentPackContentFiles = Get-ChildItem "$ContentPackContent" *.reg -Recurse | Select-Object -Property Name, BaseName, Extension, Directory, FullName #====================================================================================== # Add-ContentPackPERegistryFiles #====================================================================================== foreach ($OSDRegistryRegFile in $ContentPackContentFiles) { $OSDRegistryImportFile = $OSDRegistryRegFile.FullName if ($MountWinPE) { $RegFileContent = Get-Content -Path $OSDRegistryImportFile $OSDRegistryImportFile = "$OSDContentPackTemp\$($OSDRegistryRegFile.BaseName).reg" $RegFileContent = $RegFileContent -replace 'HKEY_CURRENT_USER','HKEY_LOCAL_MACHINE\OfflineDefaultUser' $RegFileContent = $RegFileContent -replace 'HKEY_LOCAL_MACHINE\\SOFTWARE','HKEY_LOCAL_MACHINE\OfflineSoftware' $RegFileContent = $RegFileContent -replace 'HKEY_LOCAL_MACHINE\\SYSTEM','HKEY_LOCAL_MACHINE\OfflineSystem' $RegFileContent = $RegFileContent -replace 'HKEY_USERS\\.DEFAULT','HKEY_LOCAL_MACHINE\OfflineDefault' $RegFileContent | Set-Content -Path $OSDRegistryImportFile -Force } Write-Host "$OSDRegistryImportFile" -ForegroundColor DarkGray if ($ShowRegContent.IsPresent){ $OSDContentPackRegFileContent = @() $OSDContentPackRegFileContent = Get-Content -Path $OSDRegistryImportFile foreach ($Line in $OSDContentPackRegFileContent) { Write-Host "$Line" -ForegroundColor Gray } } Start-Process reg -ArgumentList ('import',"`"$OSDRegistryImportFile`"") -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } #====================================================================================== # Remove-OSDContentPackTemp #====================================================================================== if ($MountWinPE) { if (Test-Path $OSDContentPackTemp) { Remove-Item -Path "$OSDContentPackTemp" -Recurse -Force | Out-Null } } #====================================================================================== # Dismount-RegistryHives #====================================================================================== Dismount-OSDOfflineRegistry -MountPath $MountWinPE #====================================================================================== # Mount-OfflineRegistryHives #====================================================================================== if (($MountWinRE) -and (Test-Path "$MountWinRE" -ErrorAction SilentlyContinue)) { Mount-OSDOfflineRegistryPE -MountPath $MountWinRE } else { Return } $OSDContentPackTemp = "$env:TEMP\$(Get-Random)" if (!(Test-Path $OSDContentPackTemp)) {New-Item -Path "$OSDContentPackTemp" -ItemType Directory -Force | Out-Null} #====================================================================================== # Get-RegFiles #====================================================================================== [array]$ContentPackContentFiles = @() [array]$ContentPackContentFiles = Get-ChildItem "$ContentPackContent" *.reg -Recurse | Select-Object -Property Name, BaseName, Extension, Directory, FullName #====================================================================================== # Add-ContentPackPERegistryFiles #====================================================================================== foreach ($OSDRegistryRegFile in $ContentPackContentFiles) { $OSDRegistryImportFile = $OSDRegistryRegFile.FullName if ($MountWinRE) { $RegFileContent = Get-Content -Path $OSDRegistryImportFile $OSDRegistryImportFile = "$OSDContentPackTemp\$($OSDRegistryRegFile.BaseName).reg" $RegFileContent = $RegFileContent -replace 'HKEY_CURRENT_USER','HKEY_LOCAL_MACHINE\OfflineDefaultUser' $RegFileContent = $RegFileContent -replace 'HKEY_LOCAL_MACHINE\\SOFTWARE','HKEY_LOCAL_MACHINE\OfflineSoftware' $RegFileContent = $RegFileContent -replace 'HKEY_LOCAL_MACHINE\\SYSTEM','HKEY_LOCAL_MACHINE\OfflineSystem' $RegFileContent = $RegFileContent -replace 'HKEY_USERS\\.DEFAULT','HKEY_LOCAL_MACHINE\OfflineDefault' $RegFileContent | Set-Content -Path $OSDRegistryImportFile -Force } Write-Host "$OSDRegistryImportFile" -ForegroundColor DarkGray if ($ShowRegContent.IsPresent){ $OSDContentPackRegFileContent = @() $OSDContentPackRegFileContent = Get-Content -Path $OSDRegistryImportFile foreach ($Line in $OSDContentPackRegFileContent) { Write-Host "$Line" -ForegroundColor Gray } } Start-Process reg -ArgumentList ('import',"`"$OSDRegistryImportFile`"") -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } #====================================================================================== # Remove-OSDContentPackTemp #====================================================================================== if ($MountWinRE) { if (Test-Path $OSDContentPackTemp) {Remove-Item -Path "$OSDContentPackTemp" -Recurse -Force | Out-Null} } #====================================================================================== # Dismount-RegistryHives #====================================================================================== Dismount-OSDOfflineRegistry -MountPath $MountWinRE #====================================================================================== # Mount-OfflineRegistryHives #====================================================================================== if (($MountWinSE) -and (Test-Path "$MountWinSE" -ErrorAction SilentlyContinue)) { Mount-OSDOfflineRegistryPE -MountPath $MountWinSE } else { Return } $OSDContentPackTemp = "$env:TEMP\$(Get-Random)" if (!(Test-Path $OSDContentPackTemp)) { New-Item -Path "$OSDContentPackTemp" -ItemType Directory -Force | Out-Null } #====================================================================================== # Get-RegFiles #====================================================================================== [array]$ContentPackContentFiles = @() [array]$ContentPackContentFiles = Get-ChildItem "$ContentPackContent" *.reg -Recurse | Select-Object -Property Name, BaseName, Extension, Directory, FullName #====================================================================================== # Add-ContentPackPERegistryFiles #====================================================================================== foreach ($OSDRegistryRegFile in $ContentPackContentFiles) { $OSDRegistryImportFile = $OSDRegistryRegFile.FullName if ($MountWinSE) { $RegFileContent = Get-Content -Path $OSDRegistryImportFile $OSDRegistryImportFile = "$OSDContentPackTemp\$($OSDRegistryRegFile.BaseName).reg" $RegFileContent = $RegFileContent -replace 'HKEY_CURRENT_USER','HKEY_LOCAL_MACHINE\OfflineDefaultUser' $RegFileContent = $RegFileContent -replace 'HKEY_LOCAL_MACHINE\\SOFTWARE','HKEY_LOCAL_MACHINE\OfflineSoftware' $RegFileContent = $RegFileContent -replace 'HKEY_LOCAL_MACHINE\\SYSTEM','HKEY_LOCAL_MACHINE\OfflineSystem' $RegFileContent = $RegFileContent -replace 'HKEY_USERS\\.DEFAULT','HKEY_LOCAL_MACHINE\OfflineDefault' $RegFileContent | Set-Content -Path $OSDRegistryImportFile -Force } Write-Host "$OSDRegistryImportFile" -ForegroundColor DarkGray if ($ShowRegContent.IsPresent){ $OSDContentPackRegFileContent = @() $OSDContentPackRegFileContent = Get-Content -Path $OSDRegistryImportFile foreach ($Line in $OSDContentPackRegFileContent) { Write-Host "$Line" -ForegroundColor Gray } } Start-Process reg -ArgumentList ('import',"`"$OSDRegistryImportFile`"") -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } #====================================================================================== # Remove-OSDContentPackTemp #====================================================================================== if ($MountWinSE) { if (Test-Path $OSDContentPackTemp) {Remove-Item -Path "$OSDContentPackTemp" -Recurse -Force | Out-Null} } #====================================================================================== # Dismount-RegistryHives #====================================================================================== Dismount-OSDOfflineRegistry -MountPath $MountWinSE } function Add-ContentPackPEScripts { [CmdletBinding()] param ( [Parameter(Mandatory)] [string]$ContentPackContent ) #Write-Host -ForegroundColor DarkGray "AutoApply Content $ContentPackContent" #====================================================================================== # TEST #====================================================================================== if (!(Test-Path "$ContentPackContent\*")) { Write-Host -ForegroundColor DarkGray " $ContentPackContent" Return } else {Write-Host -ForegroundColor Cyan " $ContentPackContent"} #====================================================================================== # BUILD #====================================================================================== $ContentPackPEScripts = Get-ChildItem "$ContentPackContent" *.ps1 -File -Recurse | Select-Object -Property FullName foreach ($ContentPackPEScript in $ContentPackPEScripts) { Write-Host "$($ContentPackPEScript.FullName)" -ForegroundColor DarkGray Invoke-Expression "& '$($ContentPackPEScript.FullName)'" } } function Add-FeaturesOnDemandOS { [CmdletBinding()] param () #================================================= # Abort #================================================= if ($ScriptName -ne 'New-OSBuild') {Return} if ([string]::IsNullOrWhiteSpace($FeaturesOnDemand)) {Return} #================================================= # Execute #================================================= Show-ActionTime; Write-Host -ForegroundColor Green "OS: Features On Demand" foreach ($FOD in $FeaturesOnDemand) { $global:ReapplyLCU = $true Write-Host " $SetOSDBuilderPathContent\$FOD" -ForegroundColor DarkGray $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-FeaturesOnDemandOS.log" Write-Verbose "CurrentLog: $CurrentLog" Try { Add-WindowsPackage -Path "$MountDirectory" -PackagePath "$SetOSDBuilderPathContent\$FOD" -LogPath "$CurrentLog" | Out-Null } Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "OSDBuilder: Review the log for more information" -Verbose Write-Verbose "$CurrentLog" -Verbose } } #================================================= # PostAction #================================================= #Update-CumulativeOS -Force #Invoke-DismCleanupImage } function Add-LanguageFeaturesOnDemandOS { [CmdletBinding()] param () #================================================= # Abort #================================================= if ($ScriptName -ne 'New-OSBuild') {Return} if ($OSMajorVersion -ne 10) {Return} if ([string]::IsNullOrWhiteSpace($LanguageFeatures)) {Return} #================================================= # Execute #================================================= Show-ActionTime; Write-Host -ForegroundColor Green "OS: Language Features On Demand" foreach ($Update in $LanguageFeatures | Where-Object {$_ -notlike "*Speech*"}) { $global:ReapplyLCU = $true if (Test-Path "$SetOSDBuilderPathContent\$Update") { Write-Host " $SetOSDBuilderPathContent\$Update" -ForegroundColor DarkGray $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-LanguageFeaturesOnDemandOS.log" Try {Add-WindowsPackage -Path "$MountDirectory" -PackagePath "$SetOSDBuilderPathContent\$Update" -LogPath $CurrentLog | Out-Null} Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } } } foreach ($Update in $LanguageFeatures | Where-Object {$_ -like "*TextToSpeech*"}) { $global:ReapplyLCU = $true if (Test-Path "$SetOSDBuilderPathContent\$Update") { Write-Host " $SetOSDBuilderPathContent\$Update" -ForegroundColor DarkGray $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-LanguageFeaturesOnDemandOS.log" Try {Add-WindowsPackage -Path "$MountDirectory" -PackagePath "$SetOSDBuilderPathContent\$Update" -LogPath $CurrentLog | Out-Null} Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } } } foreach ($Update in $LanguageFeatures | Where-Object {$_ -like "*Speech*" -and $_ -notlike "*TextToSpeech*"}) { $global:ReapplyLCU = $true if (Test-Path "$SetOSDBuilderPathContent\$Update") { Write-Host " $SetOSDBuilderPathContent\$Update" -ForegroundColor DarkGray $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-LanguageFeaturesOnDemandOS.log" Try {Add-WindowsPackage -Path "$MountDirectory" -PackagePath "$SetOSDBuilderPathContent\$Update" -LogPath $CurrentLog | Out-Null} Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } } } } function Add-LanguageInterfacePacksOS { [CmdletBinding()] param () #================================================= # Abort #================================================= if ($ScriptName -ne 'New-OSBuild') {Return} if ($OSMajorVersion -ne 10) {Return} if ([string]::IsNullOrWhiteSpace($LanguageInterfacePacks)) {Return} #================================================= # Header #================================================= Show-ActionTime; Write-Host -ForegroundColor Green "OS: Language Interface Packs" #================================================= # Execute #================================================= foreach ($Update in $LanguageInterfacePacks) { if (Test-Path "$SetOSDBuilderPathContent\$Update") { Write-Host " $SetOSDBuilderPathContent\$Update" -ForegroundColor DarkGray $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-LanguageInterfacePacksOS.log" Try { $global:ReapplyLCU = $true Add-WindowsPackage -Path "$MountDirectory" -PackagePath "$SetOSDBuilderPathContent\$Update" -LogPath $CurrentLog | Out-Null } Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } } else { Write-Warning "Not Found: $SetOSDBuilderPathContent\$Update" } } } function Add-LanguagePacksOS { [CmdletBinding()] param () #================================================= # Abort #================================================= if ($ScriptName -ne 'New-OSBuild') {Return} if ($OSMajorVersion -ne 10) {Return} if ([string]::IsNullOrWhiteSpace($LanguagePacks)) {Return} #================================================= # Header #================================================= Show-ActionTime; Write-Host -ForegroundColor Green "OS: Language Packs" #================================================= # Execute #================================================= foreach ($Update in $LanguagePacks) { if (Test-Path "$SetOSDBuilderPathContent\$Update") { if ($Update -like "*.cab") { Write-Host " $SetOSDBuilderPathContent\$Update" -ForegroundColor DarkGray $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-LanguagePacksOS.log" Try { $global:ReapplyLCU = $true Add-WindowsPackage -Path "$MountDirectory" -PackagePath "$SetOSDBuilderPathContent\$Update" -LogPath $CurrentLog | Out-Null } Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "$CurrentLog" -Verbose } } elseif ($Update -like "*.appx") { Write-Host " $SetOSDBuilderPathContent\$Update" -ForegroundColor DarkGray Add-AppxProvisionedPackage -Path "$MountDirectory" -PackagePath "$SetOSDBuilderPathContent\$Update" -LicensePath "$((Get-Item $SetOSDBuilderPathContent\$Update).Directory.FullName)\License.xml" -LogPath "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-LanguagePacksOS.log" | Out-Null } } else { Write-Warning "Not Found: $SetOSDBuilderPathContent\$Update" } } } function Add-LocalExperiencePacksOS { [CmdletBinding()] param () #================================================= # Abort #================================================= if ($ScriptName -ne 'New-OSBuild') {Return} if ($OSMajorVersion -ne 10) {Return} if ([string]::IsNullOrWhiteSpace($LocalExperiencePacks)) {Return} #================================================= # Header #================================================= Show-ActionTime Write-Host -ForegroundColor Green "OS: Local Experience Packs" #================================================= # Execute #================================================= foreach ($Update in $LocalExperiencePacks) { if (Test-Path "$SetOSDBuilderPathContent\$Update") { Write-Host " $SetOSDBuilderPathContent\$Update" -ForegroundColor DarkGray $global:ReapplyLCU = $true Add-AppxProvisionedPackage -Path "$MountDirectory" -PackagePath "$SetOSDBuilderPathContent\$Update" -LicensePath "$((Get-Item $SetOSDBuilderPathContent\$Update).Directory.FullName)\License.xml" -LogPath "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-LocalExperiencePacksOS.log" | Out-Null } else { Write-Warning "Not Found: $SetOSDBuilderPathContent\$Update" } } } function Add-WindowsPackageOS { [CmdletBinding()] param () #================================================= # Abort #================================================= if ($ScriptName -ne 'New-OSBuild') {Return} #================================================= # Task #================================================= if ([string]::IsNullOrWhiteSpace($Packages)) {Return} Show-ActionTime; Write-Host -ForegroundColor Green "OS: Add Packages" foreach ($PackagePath in $Packages) { Write-Host -ForegroundColor Gray " $SetOSDBuilderPathContent\$PackagePath" $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Add-WindowsPackageOS.log" Try { $global:ReapplyLCU = $true Add-WindowsPackage -PackagePath "$SetOSDBuilderPathContent\$PackagePath" -Path "$MountDirectory" -LogPath $CurrentLog | Out-Null } Catch { if ($_.Exception.Message -match '0x800f081e') {Write-Verbose "OSDBuilder: 0x800f081e The package is not applicable to this image" -Verbose} Write-Verbose "OSDBuilder: Review the log for more information" -Verbose Write-Verbose "$CurrentLog" -Verbose } } } function Copy-MediaLanguageSources { [CmdletBinding()] param () #================================================= # Abort #================================================= if ($ScriptName -ne 'New-OSBuild') {Return} if ($OSMajorVersion -ne 10) {Return} if ([string]::IsNullOrWhiteSpace($LanguageCopySources)) {Return} #================================================= # Header #================================================= Show-ActionTime Write-Host -ForegroundColor Green "OS: Language Sources" #================================================= # Execute #================================================= foreach ($LanguageSource in $LanguageCopySources) { $CurrentLanguageSource = Get-OSMedia -Revision OK | Where-Object {$_.OSMFamily -eq $LanguageSource} | Select-Object -Property FullName Write-Host "Copying Language Resources from $($CurrentLanguageSource.FullName)" -ForegroundColor DarkGray robocopy "$($CurrentLanguageSource.FullName)\OS" "$OS" *.* /s /xf *.wim /ndl /xc /xn /xo /xf /xx /b /np /ts /tee /r:0 /w:0 /Log+:"$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Copy-MediaLanguageSources.log" | Out-Null } #================================================= } function Copy-MediaOperatingSystem { [CmdletBinding()] param () #================================================= # Header #================================================= Show-ActionTime Write-Host -ForegroundColor Green "MEDIA: Copy Operating System to $WorkingPath" #================================================= # Execute #================================================= #Copy-Item -Path "$OSMediaPath\*" -Destination "$WorkingPath" -Exclude ('*.wim','*.iso','*.vhd','*.vhx') -Recurse -Force | Out-Null robocopy "$OSMediaPath" "$WorkingPath" *.* /s /r:0 /w:0 /nfl /ndl /xf *.wim *.iso *.vhd *.vhx *.vhdx | Out-Null if (Test-Path "$WorkingPath\ISO") {Remove-Item -Path "$WorkingPath\ISO" -Force -Recurse | Out-Null} if (Test-Path "$WorkingPath\VHD") {Remove-Item -Path "$WorkingPath\VHD" -Force -Recurse | Out-Null} #Copy-Item -Path "$OSMediaPath\OS\sources\install.wim" -Destination "$WimTemp\install.wim" -Force | Out-Null robocopy "$OSMediaPath\OS\sources" "$WimTemp" install.wim /r:0 /w:0 /nfl /ndl | Out-Null #Copy-Item -Path "$OSMediaPath\WinPE\*.wim" -Destination "$WimTemp" -Exclude boot.wim -Force | Out-Null robocopy "$OSMediaPath\WinPE" "$WimTemp" *.wim /r:0 /w:0 /nfl /ndl /xf boot.wim | Out-Null } function Disable-WindowsOptionalFeatureOS { [CmdletBinding()] param () #================================================= # Abort #================================================= if ($ScriptName -ne 'New-OSBuild') {Return} if ([string]::IsNullOrWhiteSpace($DisableFeature)) {Return} #================================================= # Header #================================================= Show-ActionTime Write-Host -ForegroundColor Green "OS: Disable Windows Optional Feature" #================================================= # Execute #================================================= foreach ($FeatureName in $DisableFeature) { Write-Host -ForegroundColor DarkGray " $FeatureName" Try { Disable-WindowsOptionalFeature -FeatureName $FeatureName -Path "$MountDirectory" -LogPath "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Disable-WindowsOptionalFeature.log" | Out-Null } Catch { $ErrorMessage = $_.Exception.Message Write-Warning "$ErrorMessage" } } #================================================= } function Dismount-InstallwimOS { [CmdletBinding()] param () #================================================= # Header #================================================= Show-ActionTime Write-Host -ForegroundColor Green "OS: Dismount from $MountDirectory" #================================================= # Execute #================================================= if ($WaitDismount.IsPresent){[void](Read-Host 'Press Enter to Continue')} $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Dismount-WindowsImage.log" Write-Verbose "CurrentLog: $CurrentLog" Start-Sleep -Seconds 10 try { Dismount-WindowsImage -Path "$MountDirectory" -Save -LogPath "$CurrentLog" -ErrorAction SilentlyContinue | Out-Null } catch { Write-Warning "Could not dismount Install.wim ... Waiting 30 seconds ..." Start-Sleep -Seconds 30 Dismount-WindowsImage -Path "$MountDirectory" -Save -LogPath "$CurrentLog" | Out-Null } #================================================= } function Dismount-OSDOfflineRegistry { [CmdletBinding()] param ( [Parameter(Mandatory)] [string]$MountPath ) #====================================================================================== # Dismount-RegistryHives #====================================================================================== if (($MountPath) -and (Test-Path "$MountPath" -ErrorAction SilentlyContinue)) { if (Test-Path -Path "HKLM:\OfflineDefaultUser") { Write-Verbose "Unloading Registry HKLM\OfflineDefaultUser" Start-Process reg -ArgumentList "unload HKLM\OfflineDefaultUser" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path -Path "HKLM:\OfflineDefault") { Write-Verbose "Unloading Registry HKLM\OfflineDefault" Start-Process reg -ArgumentList "unload HKLM\OfflineDefault" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path -Path "HKLM:\OfflineSoftware") { Write-Verbose "Unloading Registry HKLM\OfflineSoftware" Start-Process reg -ArgumentList "unload HKLM\OfflineSoftware" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path -Path "HKLM:\OfflineSystem") { Write-Verbose "Unloading Registry HKLM\OfflineSystem" Start-Process reg -ArgumentList "unload HKLM\OfflineSystem" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path -Path "HKLM:\OfflineDefaultUser") { Write-Verbose "Unloading Registry HKLM\OfflineDefaultUser (Second Attempt)" Start-Process reg -ArgumentList "unload HKLM\OfflineDefaultUser" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path -Path "HKLM:\OfflineDefault") { Write-Verbose "Unloading Registry HKLM\OfflineDefault (Second Attempt)" Start-Process reg -ArgumentList "unload HKLM\OfflineDefault" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path -Path "HKLM:\OfflineSoftware") { Write-Verbose "Unloading Registry HKLM\OfflineSoftware (Second Attempt)" Start-Process reg -ArgumentList "unload HKLM\OfflineSoftware" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path -Path "HKLM:\OfflineSystem") { Write-Verbose "Unloading Registry HKLM\OfflineSystem (Second Attempt)" Start-Process reg -ArgumentList "unload HKLM\OfflineSystem" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path -Path "HKLM:\OfflineDefaultUser") { Write-Warning "HKLM:\OfflineDefaultUser could not be dismounted. Open Regedit and unload the Hive manually" Pause } if (Test-Path -Path "HKLM:\OfflineDefault") { Write-Warning "HKLM:\OfflineDefault could not be dismounted. Open Regedit and unload the Hive manually" Pause } if (Test-Path -Path "HKLM:\OfflineSoftware") { Write-Warning "HKLM:\OfflineSoftware could not be dismounted. Open Regedit and unload the Hive manually" Pause } if (Test-Path -Path "HKLM:\OfflineSystem") { Write-Warning "HKLM:\OfflineSystem could not be dismounted. Open Regedit and unload the Hive manually" Pause } } } function Dismount-WimsPE { [CmdletBinding()] param ( [string]$OSMediaPath ) #================================================= # Header #================================================= Show-ActionTime Write-Host -ForegroundColor Green "WinPE: Dismount-WimsPE" #================================================= # Execute #================================================= Start-Sleep -Seconds 10 Write-Verbose "$MountWinPE" $CurrentLog = "$OSMediaPath\WinPE\info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Dismount-WimsPE-WinPE.log" Write-Verbose "CurrentLog: $CurrentLog" try { Dismount-WindowsImage -Path "$MountWinPE" -Save -LogPath "$CurrentLog" -ErrorAction SilentlyContinue | Out-Null } catch { Write-Warning "Could not dismount WinPE ... Waiting 30 seconds ..." Start-Sleep -Seconds 30 Dismount-WindowsImage -Path "$MountWinPE" -Save -LogPath "$CurrentLog" | Out-Null } Write-Verbose "$MountWinRE" $CurrentLog = "$OSMediaPath\WinPE\info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Dismount-WimsPE-WinRE.log" Write-Verbose "CurrentLog: $CurrentLog" try { Dismount-WindowsImage -Path "$MountWinRE" -Save -LogPath "$CurrentLog" -ErrorAction SilentlyContinue | Out-Null } catch { Write-Warning "Could not dismount WinRE ... Waiting 30 seconds ..." Start-Sleep -Seconds 30 Dismount-WindowsImage -Path "$MountWinRE" -Save -LogPath "$CurrentLog" | Out-Null } Write-Verbose "$MountWinSE" $CurrentLog = "$OSMediaPath\WinPE\info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Dismount-WimsPE-WinSE.log" Write-Verbose "CurrentLog: $CurrentLog" try { Dismount-WindowsImage -Path "$MountWinSE" -Save -LogPath "$CurrentLog" -ErrorAction SilentlyContinue | Out-Null } catch { Write-Warning "Could not dismount WinSE ... Waiting 30 seconds ..." Start-Sleep -Seconds 30 Dismount-WindowsImage -Path "$MountWinSE" -Save -LogPath "$CurrentLog" | Out-Null } #================================================= } function Enable-NetFXOS { [CmdletBinding()] param () #================================================= # Abort #================================================= if ($ScriptName -ne 'New-OSBuild') {Return} if ($EnableNetFX3 -ne $true) {Return} if ($OSMajorVersion -ne 10) {Return} #================================================= # Header #================================================= Show-ActionTime Write-Host -ForegroundColor Green "OS: Enable NetFX 3.5" #================================================= # Execute #================================================= $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Enable-NetFXOS.log" Write-Verbose "CurrentLog: $CurrentLog" Try { Enable-WindowsOptionalFeature -Path "$MountDirectory" -FeatureName NetFX3 -All -LimitAccess -Source "$OS\sources\sxs" -LogPath "$CurrentLog" | Out-Null } Catch { $ErrorMessage = $_.Exception.Message Write-Warning "$ErrorMessage" } #================================================= # Post Action #================================================= Update-DotNetOS -Force Update-CumulativeOS -Force #================================================= } function Enable-WindowsOptionalFeatureOS { [CmdletBinding()] param () #================================================= # Abort #================================================= if ($ScriptName -ne 'New-OSBuild') {Return} if ([string]::IsNullOrWhiteSpace($EnableFeature)) {Return} #================================================= # Header #================================================= Show-ActionTime Write-Host -ForegroundColor Green "OS: Enable Windows Optional Feature" #================================================= # Execute #================================================= foreach ($FeatureName in $EnableFeature) { Write-Host -ForegroundColor Gray " $FeatureName" Try { $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Enable-WindowsOptionalFeatureOS.log" Write-Verbose "CurrentLog: $CurrentLog" Enable-WindowsOptionalFeature -FeatureName $FeatureName -Path "$MountDirectory" -All -LogPath "$CurrentLog" | Out-Null } Catch { $ErrorMessage = $_.Exception.Message Write-Warning "$ErrorMessage" } } #================================================= # Post Action #================================================= Update-CumulativeOS -Force Invoke-DismCleanupImage #================================================= } function Enable-WinREWiFi { [CmdletBinding()] param () #================================================= # Abort #================================================= if (($ScriptName -ne 'New-OSBuild') -and ($ScriptName -ne 'New-OSDCloudOSMedia')) {Return} if ($WinREWiFi -ne $true) {Return} #================================================= # Header #================================================= Show-ActionTime; Write-Host -ForegroundColor Green "WinPE: Enable WinREWiFi" #================================================= # Execute #================================================= if ($OSArchitecture -eq 'x64') { $OSDCatalogIntelWirelessDriver = Get-OSDCatalogIntelWirelessDriver | ` Where-Object {($_.OSVersion -match '10.0')} | ` Where-Object {($_.OSArch -match 'x64')} | ` Select-Object -First 1 $IntelWirelessDriverUrl = $OSDCatalogIntelWirelessDriver.DriverUrl } else { $OSDCatalogIntelWirelessDriver = Get-OSDCatalogIntelWirelessDriver | ` Where-Object {($_.OSVersion -match '10.0')} | ` Where-Object {($_.OSArch -match 'x86')} | ` Select-Object -First 1 $IntelWirelessDriverUrl = $OSDCatalogIntelWirelessDriver.DriverUrl } if (Test-WebConnection -Uri $IntelWirelessDriverUrl) { $SaveWebFile = Save-WebFile -SourceUrl $IntelWirelessDriverUrl if (Test-Path $SaveWebFile.FullName) { $DriverCab = Get-Item -Path $SaveWebFile.FullName $ExpandPath = Join-Path $DriverCab.Directory $DriverCab.BaseName Write-Verbose -Verbose "Expanding Intel Wireless Drivers to $ExpandPath" Expand-Archive -Path $DriverCab -DestinationPath $ExpandPath -Force Add-WindowsDriver -Path $MountWinRE -Driver $ExpandPath -Recurse -ForceUnsigned -Verbose } } else { Write-Warning "Unable to connect to $IntelWirelessDriverUrl" } } function Enable-WinPEOSDCloud { [CmdletBinding()] param () #================================================= # Abort #================================================= if (($ScriptName -ne 'New-OSBuild') -and ($ScriptName -ne 'New-PEBuild') -and ($ScriptName -ne 'New-OSDCloudOSMedia')) {Return} if ($WinPEOSDCloud -ne $true) {Return} #================================================= # Header #================================================= Show-ActionTime; Write-Host -ForegroundColor Green "WinPE: Enable OSDCloud" #================================================= # MountPaths #================================================= $MountPaths = @( $MountWinPE $MountWinRE $MountWinSE ) #======================================================================= # PowerShell Execution Policy #======================================================================= Show-ActionTime; Write-Host -ForegroundColor Green "Set WinPE PowerShell ExecutionPolicy to Bypass" foreach ($MountPath in $MountPaths) { $null = Set-WindowsImageExecutionPolicy -Path $MountPath -ExecutionPolicy Bypass } #======================================================================= # Enable PowerShell Gallery #======================================================================= Show-ActionTime; Write-Host -ForegroundColor Green "Enable WinPE PowerShell Gallery" foreach ($MountPath in $MountPaths) { $null = Enable-PEWindowsImagePSGallery -Path $MountPath } $RegistryConsole = @' Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\Default\Console] "ColorTable00"=dword:000c0c0c "ColorTable01"=dword:00da3700 "ColorTable02"=dword:000ea113 "ColorTable03"=dword:00dd963a "ColorTable04"=dword:001f0fc5 "ColorTable05"=dword:00981788 "ColorTable06"=dword:00009cc1 "ColorTable07"=dword:00cccccc "ColorTable08"=dword:00767676 "ColorTable09"=dword:00ff783b "ColorTable10"=dword:000cc616 "ColorTable11"=dword:00d6d661 "ColorTable12"=dword:005648e7 "ColorTable13"=dword:009e00b4 "ColorTable14"=dword:00a5f1f9 "ColorTable15"=dword:00f2f2f2 "CtrlKeyShortcutsDisabled"=dword:00000000 "CursorColor"=dword:ffffffff "CursorSize"=dword:00000019 "DefaultBackground"=dword:ffffffff "DefaultForeground"=dword:ffffffff "EnableColorSelection"=dword:00000000 "ExtendedEditKey"=dword:00000001 "ExtendedEditKeyCustom"=dword:00000000 "FaceName"="Consolas" "FilterOnPaste"=dword:00000001 "FontFamily"=dword:00000036 "FontSize"=dword:00140000 "FontWeight"=dword:00000000 "ForceV2"=dword:00000000 "FullScreen"=dword:00000000 "HistoryBufferSize"=dword:00000032 "HistoryNoDup"=dword:00000000 "InsertMode"=dword:00000001 "LineSelection"=dword:00000001 "LineWrap"=dword:00000001 "LoadConIme"=dword:00000001 "NumberOfHistoryBuffers"=dword:00000004 "PopupColors"=dword:000000f5 "QuickEdit"=dword:00000001 "ScreenBufferSize"=dword:23290078 "ScreenColors"=dword:00000007 "ScrollScale"=dword:00000001 "TerminalScrolling"=dword:00000000 "TrimLeadingZeros"=dword:00000000 "WindowAlpha"=dword:000000ff "WindowSize"=dword:001e0078 "WordDelimiters"=dword:00000000 [HKEY_LOCAL_MACHINE\Default\Console\%SystemRoot%_System32_cmd.exe] "FaceName"="Consolas" "FilterOnPaste"=dword:00000000 "FontSize"=dword:00100000 "FontWeight"=dword:00000190 "LineSelection"=dword:00000000 "LineWrap"=dword:00000000 "WindowAlpha"=dword:00000000 "WindowPosition"=dword:00000000 "WindowSize"=dword:00110054 [HKEY_LOCAL_MACHINE\Default\Console\%SystemRoot%_System32_WindowsPowerShell_v1.0_powershell.exe] "ColorTable05"=dword:00562401 "ColorTable06"=dword:00f0edee "FaceName"="Consolas" "FilterOnPaste"=dword:00000000 "FontFamily"=dword:00000036 "FontSize"=dword:00140000 "FontWeight"=dword:00000190 "LineSelection"=dword:00000000 "LineWrap"=dword:00000000 "PopupColors"=dword:000000f3 "QuickEdit"=dword:00000001 "ScreenBufferSize"=dword:03e8012c "ScreenColors"=dword:00000056 "WindowAlpha"=dword:00000000 "WindowSize"=dword:0020006c [HKEY_LOCAL_MACHINE\Default\Console\%SystemRoot%_SysWOW64_WindowsPowerShell_v1.0_powershell.exe] "ColorTable05"=dword:00562401 "ColorTable06"=dword:00f0edee "FaceName"="Consolas" "FilterOnPaste"=dword:00000000 "FontFamily"=dword:00000036 "FontSize"=dword:00140000 "FontWeight"=dword:00000190 "LineSelection"=dword:00000000 "LineWrap"=dword:00000000 "PopupColors"=dword:000000f3 "QuickEdit"=dword:00000001 "ScreenBufferSize"=dword:03e8012c "ScreenColors"=dword:00000056 "WindowAlpha"=dword:00000000 "WindowSize"=dword:0020006c '@ #======================================================================= # Registry Fixes #======================================================================= Show-ActionTime; Write-Host -ForegroundColor Green "Modifying WinPE CMD and PowerShell Console settings" $RegistryConsole | Out-File -FilePath "$env:TEMP\RegistryConsole.reg" -Encoding ascii -Width 2000 -Force foreach ($MountPath in $MountPaths) { Start-Process reg -ArgumentList "load HKLM\Default $MountPath\Windows\System32\Config\DEFAULT" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue Start-Process reg -ArgumentList "import $env:TEMP\RegistryConsole.reg" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue Start-Process reg -ArgumentList "unload HKLM\Default" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } #======================================================================= # OSD Module #======================================================================= Write-Host -ForegroundColor Yellow "Saving OSD PowerShell Module to mounted WinPE at Program Files\WindowsPowerShell\Modules" if ($ScriptName -ne 'New-PEBuild') { Save-Module -Name OSD -Path "$MountWinPE\Program Files\WindowsPowerShell\Modules" -Force Save-Module -Name OSD -Path "$MountWinRE\Program Files\WindowsPowerShell\Modules" -Force Save-Module -Name OSD -Path "$MountWinSE\Program Files\WindowsPowerShell\Modules" -Force } else { Save-Module -Name OSD -Path "$MountDirectory\Program Files\WindowsPowerShell\Modules" -Force } } function Expand-DaRTPE { [CmdletBinding()] param () #================================================= # Abort #================================================= if (($ScriptName -ne 'New-OSBuild') -and ($ScriptName -ne 'New-PEBuild')) {Return} if ([string]::IsNullOrWhiteSpace($WinPEDaRT)) {Return} #================================================= # Header #================================================= $MicrosoftDartCab = "$SetOSDBuilderPathContent\$WinPEDaRT" Show-ActionTime; Write-Host -ForegroundColor Green "Microsoft DaRT: $MicrosoftDartCab" #================================================= # Execute #================================================= if (Test-Path "$MicrosoftDartCab") { if ($MountWinPE) {expand.exe "$MicrosoftDartCab" -F:*.* "$MountWinPE" | Out-Null} if ($MountWinRE) {expand.exe "$MicrosoftDartCab" -F:*.* "$MountWinRE" | Out-Null} if ($MountWinSE) {expand.exe "$MicrosoftDartCab" -F:*.* "$MountWinSE" | Out-Null} $MicrosoftDartConfig = $(Join-Path $(Split-Path "$MicrosoftDartCab") 'DartConfig.dat') if (Test-Path $MicrosoftDartConfig) { if ($MountWinPE) {Copy-Item -Path $MicrosoftDartConfig -Destination "$MountWinPE\Windows\System32\DartConfig.dat" -Force} if ($MountWinRE) {Copy-Item -Path $MicrosoftDartConfig -Destination "$MountWinSE\Windows\System32\DartConfig.dat" -Force} if ($MountWinSE) {Copy-Item -Path $MicrosoftDartConfig -Destination "$MountWinRE\Windows\System32\DartConfig.dat" -Force} } $MicrosoftDartConfig = $(Join-Path $(Split-Path "$MicrosoftDartCab") 'DartConfig8.dat') if (Test-Path $MicrosoftDartConfig) { if ($MountWinPE) {Copy-Item -Path $MicrosoftDartConfig -Destination "$MountWinPE\Windows\System32\DartConfig.dat" -Force} if ($MountWinRE) {Copy-Item -Path $MicrosoftDartConfig -Destination "$MountWinSE\Windows\System32\DartConfig.dat" -Force} if ($MountWinSE) {Copy-Item -Path $MicrosoftDartConfig -Destination "$MountWinRE\Windows\System32\DartConfig.dat" -Force} } if ($ScriptName -eq 'New-OSBuild') { if (Test-Path "$MountWinPE\Windows\System32\winpeshl.ini") {Remove-Item -Path "$MountWinPE\Windows\System32\winpeshl.ini" -Force} (Get-Content "$MountWinRE\Windows\System32\winpeshl.ini") | ForEach-Object {$_ -replace '-prompt','-network'} | Out-File "$MountWinRE\Windows\System32\winpeshl.ini" if (Test-Path "$MountWinSE\Windows\System32\winpeshl.ini") {Remove-Item -Path "$MountWinSE\Windows\System32\winpeshl.ini" -Force} } if ($ScriptName -eq 'New-PEBuild') { if ($WinPEOutput -eq 'Recovery') { (Get-Content "$MountDirectory\Windows\System32\winpeshl.ini") | ForEach-Object {$_ -replace '-prompt','-network'} | Out-File "$MountDirectory\Windows\System32\winpeshl.ini" } else { if (Test-Path "$MountDirectory\Windows\System32\winpeshl.ini") {Remove-Item -Path "$MountDirectory\Windows\System32\winpeshl.ini" -Force} } } } else {Write-Warning "Microsoft DaRT do not exist in $MicrosoftDartCab"} } function Export-InstallwimOS { [CmdletBinding()] param () #================================================= # Header #================================================= Show-ActionTime Write-Host -ForegroundColor Green "OS: Export to $OS\sources\install.wim" #================================================= # Execute #================================================= $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Export-WindowsImage.log" Write-Verbose "CurrentLog: $CurrentLog" Export-WindowsImage -SourceImagePath "$WimTemp\install.wim" -SourceIndex 1 -DestinationImagePath "$OS\sources\install.wim" -LogPath "$CurrentLog" | Out-Null } function Export-PEBootWim { [CmdletBinding()] param ( [string]$OSMediaPath ) #================================================= # Header #================================================= Show-ActionTime Write-Host -ForegroundColor Green "WinPE: Rebuild $OSMediaPath\OS\sources\boot.wim" #================================================= # Execute #================================================= $CurrentLog = "$OSMediaPath\WinPE\info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Export-WindowsImage-WinPE.log" Write-Verbose "CurrentLog: $CurrentLog" Export-WindowsImage -SourceImagePath "$OSMediaPath\WimTemp\winpe.wim" -SourceIndex 1 -DestinationImagePath "$OSMediaPath\WinPE\boot.wim" -LogPath "$CurrentLog" | Out-Null $CurrentLog = "$OSMediaPath\WinPE\info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Export-WindowsImage-WinSE.log" Write-Verbose "CurrentLog: $CurrentLog" Export-WindowsImage -SourceImagePath "$OSMediaPath\WimTemp\winse.wim" -SourceIndex 1 -DestinationImagePath "$OSMediaPath\WinPE\boot.wim" -Setbootable -LogPath "$CurrentLog" | Out-Null Copy-Item -Path "$OSMediaPath\WinPE\boot.wim" -Destination "$OSMediaPath\OS\sources\boot.wim" -Force | Out-Null } function Export-PEWims { [CmdletBinding()] param ( [string]$OSMediaPath ) #================================================= # Header #================================================= Show-ActionTime Write-Host -ForegroundColor Green "WinPE: Export WIMs to $OSMediaPath\WinPE" #================================================= # Execute #================================================= $CurrentLog = "$OSMediaPath\WinPE\info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Export-WindowsImage-WinPE.log" Write-Verbose "CurrentLog: $CurrentLog" Export-WindowsImage -SourceImagePath "$OSMediaPath\WimTemp\winpe.wim" -SourceIndex 1 -DestinationImagePath "$OSMediaPath\WinPE\winpe.wim" -LogPath "$CurrentLog" | Out-Null $CurrentLog = "$OSMediaPath\WinPE\info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Export-WindowsImage-WinRE.log" Write-Verbose "CurrentLog: $CurrentLog" Export-WindowsImage -SourceImagePath "$OSMediaPath\WimTemp\winre.wim" -SourceIndex 1 -DestinationImagePath "$OSMediaPath\WinPE\winre.wim" -LogPath "$CurrentLog" | Out-Null $CurrentLog = "$OSMediaPath\WinPE\info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Export-WindowsImage-WinSE.log" Write-Verbose "CurrentLog: $CurrentLog" Export-WindowsImage -SourceImagePath "$OSMediaPath\WimTemp\winse.wim" -SourceIndex 1 -DestinationImagePath "$OSMediaPath\WinPE\winse.wim" -LogPath "$CurrentLog" | Out-Null } function Export-SessionsXmlOS { [CmdletBinding()] param ( [string]$OSMediaPath ) Write-Verbose "$OSMediaPath\Sessions.xml" Copy-Item "$OSMediaPath\Sessions.xml" "$OSMediaPath\info\Sessions.xml" -Force | Out-Null [xml]$SessionsXML = Get-Content -Path "$OSMediaPath\info\Sessions.xml" $Sessions = $SessionsXML.SelectNodes('Sessions/Session') | ForEach-Object { New-Object -Type PSObject -Property @{ Id = $_.Tasks.Phase.package.id KBNumber = $_.Tasks.Phase.package.name TargetState = $_.Tasks.Phase.package.targetState Client = $_.Client Complete = $_.Complete Status = $_.Status } } $Sessions = $Sessions | Where-Object {$_.Id -like "Package*"} $Sessions = $Sessions | Select-Object -Property Id, KBNumber, TargetState, Client, Status, Complete | Sort-Object Complete -Descending $Sessions | Out-File "$OSMediaPath\Sessions.txt" $Sessions | Out-File "$OSMediaPath\info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Sessions.txt" $Sessions | Export-Clixml -Path "$OSMediaPath\info\xml\Sessions.xml" $Sessions | Export-Clixml -Path "$OSMediaPath\info\xml\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Sessions.xml" $Sessions | ConvertTo-Json | Out-File "$OSMediaPath\info\json\Sessions.json" $Sessions | ConvertTo-Json | Out-File "$OSMediaPath\info\json\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Sessions.json" Remove-Item "$OSMediaPath\Sessions.xml" -Force | Out-Null } function Get-FeatureUpdateDownloads { $FeatureUpdateDownloads = @() $FeatureUpdateDownloads = Get-WSUSXML -Catalog FeatureUpdate <# $CatalogsXmls = @() $CatalogsXmls = Get-ChildItem "$($MyInvocation.MyCommand.Module.ModuleBase)\CatalogsESD\*" -Include *.xml foreach ($CatalogsXml in $CatalogsXmls) { $FeatureUpdateDownloads += Import-Clixml -Path "$($CatalogsXml.FullName)" } #> #================================================= # Get Downloadeds #================================================= foreach ($Download in $FeatureUpdateDownloads) { $FullUpdatePath = Join-Path $SetOSDBuilderPathFeatureUpdates $Download.FileName if (Test-Path $FullUpdatePath) { $Download.OSDStatus = "Downloaded" } } #================================================= # Return #================================================= $FeatureUpdateDownloads = $FeatureUpdateDownloads | Select-Object -Property * | Sort-Object -Property CreationDate -Descending Return $FeatureUpdateDownloads } function Get-IsContentPacksEnabled { [CmdletBinding()] param () if ($global:SetOSDBuilder.AllowContentPacks -eq $false) {Return $false} if (Test-Path $SetOSDBuilderPathTemplates\Drivers) {Return $false} if (Test-Path $SetOSDBuilderPathTemplates\ExtraFiles) {Return $false} if (Test-Path $SetOSDBuilderPathTemplates\Registry) {Return $false} if (Test-Path $SetOSDBuilderPathTemplates\Scripts) {Return $false} Return $true } function Get-IsTemplatesEnabled { #Is Templates Content enabled [CmdletBinding()] param () if (Test-Path $SetOSDBuilderPathTemplates\Drivers) {Return $true} if (Test-Path $SetOSDBuilderPathTemplates\ExtraFiles) {Return $true} if (Test-Path $SetOSDBuilderPathTemplates\Registry) {Return $true} if (Test-Path $SetOSDBuilderPathTemplates\Scripts) {Return $true} Return $false } function Get-OSBuildTask { [CmdletBinding()] param ( [switch]$GridView ) Begin { #Write-Host '========================================================================================' -ForegroundColor DarkGray #Write-Host "$($MyInvocation.MyCommand.Name) BEGIN" #================================================= Write-Verbose '19.1.1 Initialize OSDBuilder' #================================================= Get-OSDBuilder -CreatePaths -HideDetails #================================================= Write-Verbose '19.1.1 Gather All OSBuildTask' #================================================= $AllOSBuildTasks = @() $AllOSBuildTasks = Get-ChildItem -Path $SetOSDBuilderPathTasks OSBuild*.json -File | Select-Object -Property * } Process { #Write-Host '========================================================================================' -ForegroundColor DarkGray #Write-Host "$($MyInvocation.MyCommand.Name) PROCESS" $OSBuildTask = foreach ($Item in $AllOSBuildTasks) { #================================================= #Write-Verbose '19.1.1 Get Windows Image Information' #================================================= $OSBuildTaskPath = $($Item.FullName) Write-Verbose "OSBuildTask Full Path: $OSBuildTaskPath" $OSBTask = @() $OSBTask = Get-Content "$($Item.FullName)" | ConvertFrom-Json $OSBTaskProps = @() $OSBTaskProps = Get-Item "$($Item.FullName)" | Select-Object -Property * if ([System.Version]$OSBTask.TaskVersion -lt [System.Version]"19.1.3.0") { $ObjectProperties = @{ LastWriteTime = $OSBTaskProps.LastWriteTime TaskName = $OSBTask.TaskName TaskVersion = $OSBTask.TaskVersion OSMediaName = $OSBTask.MediaName FullName = $Item.FullName } New-Object -TypeName PSObject -Property $ObjectProperties Write-Verbose "" } if ([System.Version]$OSBTask.TaskVersion -gt [System.Version]"19.1.3.0") { if ($OSBTask.ReleaseId -match '2009') {$OSBTask.ReleaseId = '20H2'} if ($null -eq $OSBTask.Languages) { Write-Warning "Reading Task: $OSBuildTaskPath" Write-Warning "Searching for OSMFamily: $($OSBTask.OSMFamily)" $LangUpdate = Get-OSMedia | Where-Object {$_.OSMFamilyV1 -eq $OSBTask.OSMFamily} | Select-Object -Last 1 Write-Warning "Adding Language: $($LangUpdate.Languages)" $OSBTask | Add-Member -Type NoteProperty -Name 'Languages' -Value "$LangUpdate.Languages" $OSBTask.Languages = $LangUpdate.Languages $OSBTask.OSMFamily = $OSBTask.InstallationType + " " + $OSBTask.EditionId + " " + $OSBTask.Arch + " " + [string]$OSBTask.Build + " " + $OSBTask.Languages Write-Warning "Updating OSMFamily: $($OSBTask.OSMFamily)" Write-Warning "Updating Task: $OSBuildTaskPath" $OSBTask | ConvertTo-Json | Out-File $OSBuildTaskPath Write-Host "" } $ObjectProperties = @{ TaskType = $OSBTask.TaskType TaskVersion = $OSBTask.TaskVersion TaskName = $OSBTask.TaskName TaskGuid = $OSBTask.TaskGuid CustomName = $OSBTask.CustomName SourceOSMedia = $OSBTask.Name ImageName = $OSBTask.ImageName Arch = $OSBTask.Arch ReleaseId = $OSBTask.ReleaseId UBR = $OSBTask.UBR Languages = $OSBTask.Languages EditionId = $OSBTask.EditionId FullName = $Item.FullName LastWriteTime = $OSBTaskProps.LastWriteTime CreatedTime = [datetime]$OSBTask.CreatedTime ModifiedTime = [datetime]$OSBTask.ModifiedTime OSMFamily = $OSBTask.OSMFamily OSMGuid = $OSBTask.OSMGuid } New-Object -TypeName PSObject -Property $ObjectProperties Write-Verbose "" } } #================================================= #Write-Verbose '19.1.3 Output' #================================================= if ($GridView.IsPresent) {$OSBuildTask | Select-Object TaskType,TaskVersion,TaskName,CustomName,SourceOSMedia,ImageName,Arch,ReleaseId,UBR,Languages,EditionId,FullName,LastWriteTime,OSMFamily,OSMGuid | Sort-Object TaskName | Out-GridView -PassThru -Title 'OSBuildTask'} else {$OSBuildTask | Select-Object TaskType,TaskVersion,TaskName,CustomName,SourceOSMedia,ImageName,Arch,ReleaseId,UBR,Languages,EditionId,FullName,LastWriteTime,OSMFamily,OSMGuid | Sort-Object TaskName } } End { #Write-Host '========================================================================================' -ForegroundColor DarkGray #Write-Host "$($MyInvocation.MyCommand.Name) END" } } function Get-OSDFromJson { param( [Parameter(Mandatory=$true, Position=1)] [string]$Path ) function Get-Value { param( $value ) $result = $null if ( $value -is [System.Management.Automation.PSCustomObject] ) { Write-Verbose "Get-Value: value is PSCustomObject" $result = @{} $value.psobject.properties | ForEach-Object { $result[$_.Name] = Get-Value -value $_.Value } } elseif ($value -is [System.Object[]]) { $list = New-Object System.Collections.ArrayList Write-Verbose "Get-Value: value is Array" $value | ForEach-Object { $list.Add((Get-Value -value $_)) | Out-Null } $result = $list } else { Write-Verbose "Get-Value: value is type: $($value.GetType())" $result = $value } return $result } if (Test-Path $Path) { $json = Get-Content $Path -Raw } else { $json = '{}' } $hashtable = Get-Value -value (ConvertFrom-Json $json) return $hashtable } function Get-OSDUpdateDownloads { [CmdletBinding()] param ( [string]$OSDGuid, [string]$UpdateTitle, [switch]$Silent ) #================================================= # Filtering #================================================= if ($OSDGuid) { $OSDUpdateDownload = Get-OSDUpdates -Silent | Where-Object {$_.OSDGuid -eq $OSDGuid} } elseif ($UpdateTitle) { $OSDUpdateDownload = Get-OSDUpdates -Silent | Where-Object {$_.UpdateTitle -eq $UpdateTitle} } else { Break } #================================================= # Download #================================================= foreach ($Update in $OSDUpdateDownload) { $DownloadPath = $SetOSDBuilderPathUpdates $DownloadFullPath = Join-Path $DownloadPath $(Split-Path $Update.OriginUri -Leaf) #================================================= # Download #================================================= $SourceUrl = $Update.OriginUri $SourceUrl = [Uri]::EscapeUriString($SourceUrl) if (!(Test-Path $DownloadPath)) {New-Item -Path "$DownloadPath" -ItemType Directory -Force | Out-Null} if (!(Test-Path $DownloadFullPath)) { Write-Host "$DownloadFullPath" Write-Host "$($Update.OriginUri)" -ForegroundColor Gray if (Get-Command 'curl.exe' -ErrorAction SilentlyContinue) { Write-Verbose "cURL: $SourceUrl" if ($host.name -match 'ConsoleHost') { Invoke-Expression "& curl.exe --insecure --location --output `"$DownloadFullPath`" --url `"$SourceUrl`"" } else { #PowerShell ISE will display a NativeCommandError, so progress will not be displayed $Quiet = Invoke-Expression "& curl.exe --insecure --location --output `"$DownloadFullPath`" --url `"$SourceUrl`" 2>&1" } } else { [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls1 $WebClient = New-Object System.Net.WebClient $WebClient.DownloadFile("$SourceUrl", "$DownloadFullPath") $WebClient.Dispose() } } } } function Get-OSDUpdates { param ( [switch]$Silent ) $AllOSDUpdates = @() if ($Silent.IsPresent) { $AllOSDUpdates = Get-WSUSXML -Catalog Windows -Silent } else { $AllOSDUpdates = Get-WSUSXML -Catalog Windows } #================================================= # Get Downloaded Updates #================================================= foreach ($Update in $AllOSDUpdates) { $FullUpdatePath = Join-Path $SetOSDBuilderPathUpdates $(Split-Path $Update.OriginUri -Leaf) if (Test-Path $FullUpdatePath) { $Update.OSDStatus = "Downloaded" } } #================================================= # Return #================================================= $AllOSDUpdates = $AllOSDUpdates | Where-Object {$_.FileName -notmatch '.wim'} $AllOSDUpdates = $AllOSDUpdates | Where-Object {$_.FileName -notmatch 'desktopdeployment'} $AllOSDUpdates = $AllOSDUpdates | Where-Object {$_.FileName -notmatch 'aggregatedmetadata'} $AllOSDUpdates = $AllOSDUpdates | Where-Object {$_.FileName -notmatch 'fodmetadata'} $AllOSDUpdates = $AllOSDUpdates | Select-Object -Property * Return $AllOSDUpdates } function Get-OSTemplateDrivers { [CmdletBinding()] param () #================================================= # Abort #================================================= if (Get-IsContentPacksEnabled) {Return} #================================================= # Process #================================================= $DriverTemplates = @() #Write-Host " $SetOSDBuilderPathTemplates\Drivers\AutoApply\Global" -ForegroundColor Gray [array]$DriverTemplates = Get-Item "$SetOSDBuilderPathTemplates\Drivers\AutoApply\Global" #Write-Host " $SetOSDBuilderPathTemplates\Drivers\AutoApply\Global $OSArchitecture" -ForegroundColor Gray [array]$DriverTemplates += Get-Item "$SetOSDBuilderPathTemplates\Drivers\AutoApply\Global $OSArchitecture" #Write-Host " $SetOSDBuilderPathTemplates\Drivers\AutoApply\$UpdateOS" -ForegroundColor Gray [array]$DriverTemplates += Get-Item "$SetOSDBuilderPathTemplates\Drivers\AutoApply\$UpdateOS" if ($OSInstallationType -notlike "*Server*") { #Write-Host " $SetOSDBuilderPathTemplates\Drivers\AutoApply\$UpdateOS $OSArchitecture" -ForegroundColor Gray [array]$DriverTemplates += Get-Item "$SetOSDBuilderPathTemplates\Drivers\AutoApply\$UpdateOS $OSArchitecture" } if ($OSInstallationType -notlike "*Server*" -and $OSMajorVersion -eq 10) { #Write-Host " $SetOSDBuilderPathTemplates\Drivers\AutoApply\$UpdateOS $OSArchitecture $ReleaseId" -ForegroundColor Gray [array]$DriverTemplates += Get-Item "$SetOSDBuilderPathTemplates\Drivers\AutoApply\$UpdateOS $OSArchitecture $ReleaseId" } Return $DriverTemplates } function Get-OSTemplateExtraFiles { [CmdletBinding()] param () #================================================= # Abort #================================================= if (Get-IsContentPacksEnabled) {Return} #================================================= # Process #================================================= $ExtraFilesTemplates = @() #Write-Host " $SetOSDBuilderPathTemplates\ExtraFiles\AutoApply\Global" -ForegroundColor DarkGray [array]$ExtraFilesTemplates = Get-ChildItem "$SetOSDBuilderPathTemplates\ExtraFiles\AutoApply\Global" | Where-Object {$_.PSIsContainer -eq $true} #Write-Host " $SetOSDBuilderPathTemplates\ExtraFiles\AutoApply\Global $OSArchitecture" -ForegroundColor DarkGray [array]$ExtraFilesTemplates += Get-ChildItem "$SetOSDBuilderPathTemplates\ExtraFiles\AutoApply\Global $OSArchitecture" | Where-Object {$_.PSIsContainer -eq $true} #Write-Host " $SetOSDBuilderPathTemplates\ExtraFiles\AutoApply\$UpdateOS" -ForegroundColor DarkGray [array]$ExtraFilesTemplates += Get-ChildItem "$SetOSDBuilderPathTemplates\ExtraFiles\AutoApply\$UpdateOS" | Where-Object {$_.PSIsContainer -eq $true} if ($OSInstallationType -notlike "*Server*") { #Write-Host " $SetOSDBuilderPathTemplates\ExtraFiles\AutoApply\$UpdateOS $OSArchitecture" -ForegroundColor DarkGray [array]$ExtraFilesTemplates += Get-ChildItem "$SetOSDBuilderPathTemplates\ExtraFiles\AutoApply\$UpdateOS $OSArchitecture" | Where-Object {$_.PSIsContainer -eq $true} } if ($OSInstallationType -notlike "*Server*" -and $OSMajorVersion -eq 10) { #Write-Host " $SetOSDBuilderPathTemplates\ExtraFiles\AutoApply\$UpdateOS $OSArchitecture $ReleaseId" -ForegroundColor DarkGray [array]$ExtraFilesTemplates += Get-ChildItem "$SetOSDBuilderPathTemplates\ExtraFiles\AutoApply\$UpdateOS $OSArchitecture $ReleaseId" | Where-Object {$_.PSIsContainer -eq $true} } Return $ExtraFilesTemplates } function Get-OSTemplateRegistryReg { [CmdletBinding()] param () #================================================= # Abort #================================================= if (Get-IsContentPacksEnabled) {Return} #================================================= # Process #================================================= $RegistryTemplatesRegOriginal = @() $RegistryTemplatesRegOriginal = Get-ChildItem "$SetOSDBuilderPathTemplates\Registry\AutoApply" *.reg -Recurse | Select-Object -Property Name, BaseName, Extension, Directory, FullName foreach ($REG in $RegistryTemplatesRegOriginal) { if (!(Test-Path "$($REG.FullName).Offline")) { Write-Host "Creating $($REG.FullName).Offline" -ForegroundColor DarkGray $REGContent = Get-Content -Path $REG.FullName $REGContent = $REGContent -replace 'HKEY_CURRENT_USER','HKEY_LOCAL_MACHINE\OfflineDefaultUser' $REGContent = $REGContent -replace 'HKEY_LOCAL_MACHINE\\SOFTWARE','HKEY_LOCAL_MACHINE\OfflineSoftware' $REGContent = $REGContent -replace 'HKEY_LOCAL_MACHINE\\SYSTEM','HKEY_LOCAL_MACHINE\OfflineSystem' $REGContent = $REGContent -replace 'HKEY_USERS\\.DEFAULT','HKEY_LOCAL_MACHINE\OfflineDefault' $REGContent | Set-Content "$($REG.FullName).Offline" -Force } } $RegistryTemplatesReg = @() #Write-Host " $SetOSDBuilderPathTemplates\Registry\AutoApply\Global" -ForegroundColor DarkGray [array]$RegistryTemplatesReg = Get-ChildItem "$SetOSDBuilderPathTemplates\Registry\AutoApply\Global\*" *.reg.Offline -Recurse #Write-Host " $SetOSDBuilderPathTemplates\Registry\AutoApply\Global $OSArchitecture" -ForegroundColor DarkGray [array]$RegistryTemplatesReg += Get-ChildItem "$SetOSDBuilderPathTemplates\Registry\AutoApply\Global $OSArchitecture\*" *.reg.Offline -Recurse #Write-Host " $SetOSDBuilderPathTemplates\Registry\AutoApply\$UpdateOS" -ForegroundColor DarkGray [array]$RegistryTemplatesReg += Get-ChildItem "$SetOSDBuilderPathTemplates\Registry\AutoApply\$UpdateOS\*" *.reg.Offline -Recurse if ($OSInstallationType -notlike "*Server*") { #Write-Host " $SetOSDBuilderPathTemplates\Registry\AutoApply\$UpdateOS $OSArchitecture" -ForegroundColor DarkGray [array]$RegistryTemplatesReg += Get-ChildItem "$SetOSDBuilderPathTemplates\Registry\AutoApply\$UpdateOS $OSArchitecture\*" *.reg.Offline -Recurse } if ($OSInstallationType -notlike "*Server*" -and $OSMajorVersion -eq 10) { #Write-Host " $SetOSDBuilderPathTemplates\Registry\AutoApply\$UpdateOS $OSArchitecture $ReleaseId" -ForegroundColor DarkGray [array]$RegistryTemplatesReg += Get-ChildItem "$SetOSDBuilderPathTemplates\Registry\AutoApply\$UpdateOS $OSArchitecture $ReleaseId\*" *.reg.Offline -Recurse } Return $RegistryTemplatesReg } function Get-OSTemplateRegistryXml { [CmdletBinding()] param () #================================================= # Abort #================================================= if (Get-IsContentPacksEnabled) {Return} #================================================= # Process #================================================= $RegistryTemplatesXml = @() #Write-Host " $SetOSDBuilderPathTemplates\Registry\AutoApply\Global" -ForegroundColor DarkGray [array]$RegistryTemplatesXml = Get-ChildItem "$SetOSDBuilderPathTemplates\Registry\AutoApply\Global\*" *.xml -Recurse #Write-Host " $SetOSDBuilderPathTemplates\Registry\AutoApply\Global $OSArchitecture" -ForegroundColor DarkGray [array]$RegistryTemplatesXml += Get-ChildItem "$SetOSDBuilderPathTemplates\Registry\AutoApply\Global $OSArchitecture\*" *.xml -Recurse #Write-Host " $SetOSDBuilderPathTemplates\Registry\AutoApply\$UpdateOS" -ForegroundColor DarkGray [array]$RegistryTemplatesXml += Get-ChildItem "$SetOSDBuilderPathTemplates\Registry\AutoApply\$UpdateOS\*" *.xml -Recurse if ($OSInstallationType -notlike "*Server*") { #Write-Host " $SetOSDBuilderPathTemplates\Registry\AutoApply\$UpdateOS $OSArchitecture" -ForegroundColor DarkGray [array]$RegistryTemplatesXml += Get-ChildItem "$SetOSDBuilderPathTemplates\Registry\AutoApply\$UpdateOS $OSArchitecture\*" *.xml -Recurse } if ($OSInstallationType -notlike "*Server*" -and $OSMajorVersion -eq 10) { #Write-Host " $SetOSDBuilderPathTemplates\Registry\AutoApply\$UpdateOS $OSArchitecture $ReleaseId" -ForegroundColor DarkGray [array]$RegistryTemplatesXml += Get-ChildItem "$SetOSDBuilderPathTemplates\Registry\AutoApply\$UpdateOS $OSArchitecture $ReleaseId\*" *.xml -Recurse } Return $RegistryTemplatesXml } function Get-OSTemplateScripts { [CmdletBinding()] param () #================================================= # Abort #================================================= if (Get-IsContentPacksEnabled) {Return} #================================================= # Process #================================================= $ScriptTemplates = @() #Write-Host " $SetOSDBuilderPathTemplates\Scripts\AutoApply\Global" -ForegroundColor DarkGray [array]$ScriptTemplates = Get-ChildItem "$SetOSDBuilderPathTemplates\Scripts\AutoApply\Global\*" *.ps1 -Recurse #Write-Host " $SetOSDBuilderPathTemplates\Scripts\AutoApply\Global $OSArchitecture" -ForegroundColor DarkGray [array]$ScriptTemplates += Get-ChildItem "$SetOSDBuilderPathTemplates\Scripts\AutoApply\Global $OSArchitecture\*" *.ps1 -Recurse #Write-Host " $SetOSDBuilderPathTemplates\Scripts\AutoApply\$UpdateOS" -ForegroundColor DarkGray [array]$ScriptTemplates += Get-ChildItem "$SetOSDBuilderPathTemplates\Scripts\AutoApply\$UpdateOS\*" *.ps1 -Recurse if ($OSInstallationType -notlike "*Server*") { #Write-Host " $SetOSDBuilderPathTemplates\Scripts\AutoApply\$UpdateOS $OSArchitecture" -ForegroundColor DarkGray [array]$ScriptTemplates += Get-ChildItem "$SetOSDBuilderPathTemplates\Scripts\AutoApply\$UpdateOS $OSArchitecture\*" *.ps1 -Recurse } if ($OSInstallationType -notlike "*Server*" -and $OSMajorVersion -eq 10) { #Write-Host " $SetOSDBuilderPathTemplates\Scripts\AutoApply\$UpdateOS $OSArchitecture $ReleaseId" -ForegroundColor DarkGray [array]$ScriptTemplates += Get-ChildItem "$SetOSDBuilderPathTemplates\Scripts\AutoApply\$UpdateOS $OSArchitecture $ReleaseId\*" *.ps1 -Recurse } Return $ScriptTemplates } function Get-PEBuildTask { [CmdletBinding()] param ( [switch]$GridView ) Begin { #Write-Host '========================================================================================' -ForegroundColor DarkGray #Write-Host "$($MyInvocation.MyCommand.Name) BEGIN" #================================================= Write-Verbose '19.1.1 Initialize OSDBuilder' #================================================= Get-OSDBuilder -CreatePaths -HideDetails #================================================= Write-Verbose '19.1.1 Gather All PEBuildTask' #================================================= $AllPEBuildTasks = @() $AllPEBuildTasks = Get-ChildItem -Path $SetOSDBuilderPathTasks *.json -File | Select-Object -Property * $AllPEBuildTasks = $AllPEBuildTasks | Where-Object {$_.Name -like "MDT*" -or $_.Name -like "Recovery*" -or $_.Name -like "WinPE*"} } Process { #Write-Host '========================================================================================' -ForegroundColor DarkGray #Write-Host "$($MyInvocation.MyCommand.Name) PROCESS" $PEBuildTask = foreach ($Item in $AllPEBuildTasks) { #================================================= #Write-Verbose '19.1.1 Get Windows Image Information' #================================================= $PEBuildTaskPath = $($Item.FullName) Write-Verbose "PEBuildTask Full Path: $PEBuildTaskPath" $PEBTask = @() $PEBTask = Get-Content "$($Item.FullName)" | ConvertFrom-Json $PEBTaskProps = @() $PEBTaskProps = Get-Item "$($Item.FullName)" | Select-Object -Property * if ([System.Version]$PEBTask.TaskVersion -lt [System.Version]"19.1.3.0") { $ObjectProperties = @{ LastWriteTime = $PEBTaskProps.LastWriteTime TaskName = $PEBTask.TaskName TaskVersion = $PEBTask.TaskVersion Name = $PEBTask.MediaName FullName = $Item.FullName } New-Object -TypeName PSObject -Property $ObjectProperties Write-Verbose "" } if ([System.Version]$PEBTask.TaskVersion -gt [System.Version]"19.1.3.0") { if ($PEBTask.ReleaseId -match '2009') {$PEBTask.ReleaseId = '20H2'} if ($null -eq $PEBTask.Languages) { Write-Warning "Reading Task: $PEBuildTaskPath" Write-Warning "Searching for OSMFamily: $($PEBTask.OSMFamily)" $LangUpdate = Get-OSMedia | Where-Object {$_.OSMFamilyV1 -eq $PEBTask.OSMFamily} | Select-Object -Last 1 Write-Warning "Adding Language: $($LangUpdate.Languages)" $PEBTask | Add-Member -Type NoteProperty -Name 'Languages' -Value "$LangUpdate.Languages" $PEBTask.Languages = $LangUpdate.Languages $PEBTask.OSMFamily = $PEBTask.InstallationType + " " + $PEBTask.EditionId + " " + $PEBTask.Arch + " " + [string]$PEBTask.Build + " " + $PEBTask.Languages Write-Warning "Updating OSMFamily: $($PEBTask.OSMFamily)" Write-Warning "Updating Task: $PEBuildTaskPath" $PEBTask | ConvertTo-Json | Out-File $PEBuildTaskPath Write-Host "" } $ObjectProperties = @{ TaskType = $PEBTask.TaskType TaskVersion = $PEBTask.TaskVersion TaskName = $PEBTask.TaskName TaskGuid = $PEBTask.TaskGuid CustomName = $PEBTask.CustomName SourceOSMedia = $PEBTask.Name ImageName = $PEBTask.ImageName Arch = $PEBTask.Arch ReleaseId = $PEBTask.ReleaseId UBR = $PEBTask.UBR EditionId = $PEBTask.EditionId FullName = $Item.FullName LastWriteTime = $PEBTaskProps.LastWriteTime CreatedTime = [datetime]$PEBTask.CreatedTime ModifiedTime = [datetime]$PEBTask.ModifiedTime OSMFamily = $PEBTask.OSMFamily OSMGuid = $PEBTask.OSMGuid } New-Object -TypeName PSObject -Property $ObjectProperties Write-Verbose "" } } #================================================= #Write-Verbose '19.1.3 Output' #================================================= if ($GridView.IsPresent) {$PEBuildTask | Select-Object TaskType,TaskVersion,TaskName,CustomName,SourceOSMedia,ImageName,Arch,ReleaseId,UBR,EditionId,FullName,LastWriteTime,OSMFamily,OSMGuid | Sort-Object TaskName | Out-GridView -PassThru -Title 'PEBuildTask'} else {$PEBuildTask | Select-Object TaskType,TaskVersion,TaskName,CustomName,SourceOSMedia,ImageName,Arch,ReleaseId,UBR,EditionId,FullName,LastWriteTime,OSMFamily,OSMGuid | Sort-Object TaskName } } End { #Write-Host '========================================================================================' -ForegroundColor DarkGray #Write-Host "$($MyInvocation.MyCommand.Name) END" } } function Get-TaskContentAddFeatureOnDemand { #================================================= # Install.Wim Features On Demand #================================================= [CmdletBinding()] param () $FeaturesOnDemandIsoExtractDir =@() $FeaturesOnDemandIsoExtractDir = $ContentIsoExtract if ($OSMedia.InstallationType -eq 'Client') { if ($($OSMedia.Arch) -eq 'x64') {$FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.FullName -like "*x64*"}} if ($($OSMedia.Arch) -eq 'x86') {$FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.FullName -like "*x86*"}} } $FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.Name -notlike "*lp.cab"} $FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.Name -notlike "*Language-Pack*"} $FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.Name -notlike "*Language-Interface-Pack*"} $FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.Name -notlike "*LanguageFeatures*"} $FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.Name -notlike "*LanguageExperiencePack*"} $FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.FullName -notlike "*metadata*"} if (($OSMedia.ReleaseId -gt 1803) -or ($OSMedia.ReleaseId -match '20H2') -or ($OSMedia.ReleaseId -match '21H1') -or ($OSMedia.ReleaseId -match '21H2')) { $FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.Name -notlike "*ActiveDirectory*"} $FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.Name -notlike "*BitLocker-Recovery*"} $FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.Name -notlike "*CertificateServices*"} $FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.Name -notlike "*DHCP-Tools*"} $FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.Name -notlike "*DNS-Tools*"} $FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.Name -notlike "*FailoverCluster*"} $FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.Name -notlike "*FileServices-Tools*"} $FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.Name -notlike "*GroupPolicy-Management*"} $FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.Name -notlike "*IPAM-Client*"} $FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.Name -notlike "*LLDP*"} $FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.Name -notlike "*NetworkController*"} $FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.Name -notlike "*NetworkLoadBalancing*"} $FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.Name -notlike "*RasCMAK*"} $FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.Name -notlike "*RasRip*"} $FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.Name -notlike "*RemoteAccess-Management*"} $FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.Name -notlike "*RemoteDesktop-Services*"} #$FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.Name -notlike "*Server-AppCompat*"} $FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.Name -notlike "*ServerManager-Tools*"} $FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.Name -notlike "*Shielded-VM*"} $FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.Name -notlike "*SNMP-Client*"} $FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.Name -notlike "*StorageManagement*"} $FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.Name -notlike "*StorageMigrationService*"} $FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.Name -notlike "*StorageReplica*"} $FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.Name -notlike "*SystemInsights*"} $FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.Name -notlike "*VolumeActivation*"} $FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.Name -notlike "*WMI-SNMP-Provider*"} $FeaturesOnDemandIsoExtractDir = $FeaturesOnDemandIsoExtractDir | Where-Object {$_.Name -notlike "*WSUS-Tools*"} } $FeaturesOnDemandUpdatesDir = @() if (Test-Path "$SetOSDBuilderPathContent\Updates\FeatureOnDemand") { $FeaturesOnDemandUpdatesDir = Get-ChildItem -Path "$SetOSDBuilderPathContent\Updates\FeatureOnDemand" *.cab -Recurse | Select-Object -Property Name, FullName } $AddFeatureOnDemand = [array]$FeaturesOnDemandIsoExtractDir + [array]$FeaturesOnDemandUpdatesDir if ($OSMedia.InstallationType -eq 'Client') {$AddFeatureOnDemand = $AddFeatureOnDemand | Where-Object {$_.FullName -notlike "*Windows Server*"}} if ($OSMedia.InstallationType -like "*Server*") {$AddFeatureOnDemand = $AddFeatureOnDemand | Where-Object {$_.FullName -like "*Windows Server*"}} if ($($OSMedia.ReleaseId)) { if ($($OSMedia.ReleaseId) -eq 1909) { $AddFeatureOnDemand = $AddFeatureOnDemand | Where-Object {$_.FullName -match '1903' -or $_.FullName -match '1909'} } elseif ($($OSMedia.ReleaseId) -eq 2009) { $AddFeatureOnDemand = $AddFeatureOnDemand | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '20H2') { $AddFeatureOnDemand = $AddFeatureOnDemand | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '21H1') { $AddFeatureOnDemand = $AddFeatureOnDemand | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '21H2') { $AddFeatureOnDemand = $AddFeatureOnDemand | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '22H2') { $AddFeatureOnDemand = $AddFeatureOnDemand | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } else { $AddFeatureOnDemand = $AddFeatureOnDemand | Where-Object {$_.FullName -match $OSMedia.ReleaseId} } } foreach ($Pack in $AddFeatureOnDemand) {$Pack.FullName = $($Pack.FullName).replace("$SetOSDBuilderPathContent\",'')} if ($null -eq $AddFeatureOnDemand) {Write-Warning "Install.wim Features On Demand: Not Found"} else { if ($ExistingTask.AddFeatureOnDemand) { foreach ($Item in $ExistingTask.AddFeatureOnDemand) { $AddFeatureOnDemand = $AddFeatureOnDemand | Where-Object {$_.FullName -ne $Item} } } $AddFeatureOnDemand = $AddFeatureOnDemand | Sort-Object -Property FullName | Out-GridView -Title "Install.wim Features On Demand: Select Packages to apply and press OK (Esc or Cancel to Skip)" -PassThru } foreach ($Item in $AddFeatureOnDemand) {Write-Host "$($Item.FullName)" -ForegroundColor White} Return $AddFeatureOnDemand } function Get-TaskContentAddWindowsPackage { #================================================= # Content Packages #================================================= [CmdletBinding()] param () $AddWindowsPackage = Get-ChildItem -Path "$GetOSDBuilderPathContentPackages\*" -Include *.cab, *.msu -Recurse | Select-Object -Property Name, FullName $AddWindowsPackage = $AddWindowsPackage | Where-Object {$_.FullName -like "*$($OSMedia.Arch)*"} foreach ($Item in $AddWindowsPackage) {$Item.FullName = $($Item.FullName).replace("$SetOSDBuilderPathContent\",'')} if ($null -eq $AddWindowsPackage) {Write-Warning "Packages: To select Windows Packages, add Content to $GetOSDBuilderPathContentPackages"} else { if ($ExistingTask.AddWindowsPackage) { foreach ($Item in $ExistingTask.AddWindowsPackage) { $AddWindowsPackage = $AddWindowsPackage | Where-Object {$_.FullName -ne $Item} } } $AddWindowsPackage = $AddWindowsPackage | Out-GridView -Title "Packages: Select Packages to apply and press OK (Esc or Cancel to Skip)" -PassThru } foreach ($Item in $AddWindowsPackage) {Write-Host "$($Item.FullName)" -ForegroundColor White} Return $AddWindowsPackage } function Get-TaskContentDrivers { #================================================= # Content Drivers #================================================= [CmdletBinding()] param () $Drivers = Get-ChildItem -Path $GetOSDBuilderPathContentDrivers -Directory -ErrorAction SilentlyContinue | Select-Object -Property Name, FullName foreach ($Pack in $Drivers) {$Pack.FullName = $($Pack.FullName).replace("$SetOSDBuilderPathContent\",'')} if ($null -eq $Drivers) {Write-Warning "Drivers: To select Windows Drivers, add Content to $GetOSDBuilderPathContentDrivers"} else { if ($ExistingTask.Drivers) { foreach ($Item in $ExistingTask.Drivers) { $Drivers = $Drivers | Where-Object {$_.FullName -ne $Item} } } $Drivers = $Drivers | Out-GridView -Title "Drivers: Select Driver Paths to apply and press OK (Esc or Cancel to Skip)" -PassThru } foreach ($Item in $Drivers) {Write-Host "$($Item.FullName)" -ForegroundColor White} Return $Drivers } function Get-TaskContentExtraFiles { #================================================= # Content ExtraFiles #================================================= [CmdletBinding()] param () $ExtraFiles = Get-ChildItem -Path $GetOSDBuilderPathContentExtraFiles -Directory -ErrorAction SilentlyContinue | Select-Object -Property Name, FullName $ExtraFiles = $ExtraFiles | Where-Object {(Get-ChildItem $_.FullName | Measure-Object).Count -gt 0} foreach ($Pack in $ExtraFiles) {$Pack.FullName = $($Pack.FullName).replace("$SetOSDBuilderPathContent\",'')} if ($null -eq $ExtraFiles) {Write-Warning "Extra Files: To select Extra Files, add Content to $GetOSDBuilderPathContentExtraFiles"} else { if ($ExistingTask.ExtraFiles) { foreach ($Item in $ExistingTask.ExtraFiles) { $ExtraFiles = $ExtraFiles | Where-Object {$_.FullName -ne $Item} } } $ExtraFiles = $ExtraFiles | Out-GridView -Title "Extra Files: Select directories to inject and press OK (Esc or Cancel to Skip)" -PassThru } foreach ($Item in $ExtraFiles) {Write-Host "$($Item.FullName)" -ForegroundColor White} Return $ExtraFiles } function Get-TaskContentIsoExtract { [CmdletBinding()] param () $ContentIsoExtract = Get-ChildItem -Path "$GetOSDBuilderPathContentIsoExtract\*" -Include *.cab, *.appx -Recurse | Select-Object -Property Name, FullName if ($($OSMedia.ReleaseId)) { if ($($OSMedia.ReleaseId) -eq 1909) { $ContentIsoExtract = $ContentIsoExtract | Where-Object {$_.FullName -match '1903' -or $_.FullName -match '1909'} } elseif ($($OSMedia.ReleaseId) -eq 2009) { $ContentIsoExtract = $ContentIsoExtract | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '20H2') { $ContentIsoExtract = $ContentIsoExtract | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '21H1') { $ContentIsoExtract = $ContentIsoExtract | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '21H2') { $ContentIsoExtract = $ContentIsoExtract | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '22H2') { $ContentIsoExtract = $ContentIsoExtract | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } else { $ContentIsoExtract = $ContentIsoExtract | Where-Object {$_.FullName -match $OSMedia.ReleaseId} } } foreach ($IsoExtractPackage in $ContentIsoExtract) {$IsoExtractPackage.FullName = $($IsoExtractPackage.FullName).replace("$SetOSDBuilderPathContent\",'')} $ContentIsoExtract = $ContentIsoExtract | Where-Object {$_.FullName -notlike "*\arm64\*"} if ($($OSMedia.Arch) -eq 'x64') {$ContentIsoExtract = $ContentIsoExtract | Where-Object {$_.Name -notlike "*x86*"}} if ($($OSMedia.Arch) -eq 'x64') {$ContentIsoExtract = $ContentIsoExtract | Where-Object {$_.FullName -notlike "*\x86\*"}} if ($($OSMedia.Arch) -eq 'x86') {$ContentIsoExtract = $ContentIsoExtract | Where-Object {$_.Name -notlike "*x64*"}} if ($($OSMedia.Arch) -eq 'x86') {$ContentIsoExtract = $ContentIsoExtract | Where-Object {$_.Name -notlike "*amd64*"}} if ($($OSMedia.Arch) -eq 'x86') {$ContentIsoExtract = $ContentIsoExtract | Where-Object {$_.FullName -notlike "*\x64\*"}} if ($($OSMedia.Arch) -eq 'x86') {$ContentIsoExtract = $ContentIsoExtract | Where-Object {$_.FullName -notlike "*\amd64\*"}} Return $ContentIsoExtract } function Get-TaskContentLanguageCopySources { #================================================= # Content Scripts #================================================= [CmdletBinding()] param () $LanguageCopySources = Get-OSMedia -Revision OK $LanguageCopySources = $LanguageCopySources | Where-Object {$_.Arch -eq $OSMedia.Arch} $LanguageCopySources = $LanguageCopySources | Where-Object {$_.Build -eq $OSMedia.Build} $LanguageCopySources = $LanguageCopySources | Where-Object {$_.OperatingSystem -eq $OSMedia.OperatingSystem} $LanguageCopySources = $LanguageCopySources | Where-Object {$_.OSMFamily -ne $OSMedia.OSMFamily} if ($ExistingTask.LanguageCopySources) { foreach ($Item in $ExistingTask.LanguageCopySources) { $LanguageCopySources = $LanguageCopySources | Where-Object {$_.OSMFamily -ne $Item} } } $LanguageCopySources = $LanguageCopySources | Out-GridView -Title "SourcesLanguageCopy: Select OSMedia to copy the Language Sources and press OK (Esc or Cancel to Skip)" -PassThru foreach ($Item in $LanguageCopySources) {Write-Host "$($Item.OSMFamily)" -ForegroundColor White} Return $LanguageCopySources } function Get-TaskContentLanguageFeature { [CmdletBinding()] param () $LanguageFodIsoExtractDir = @() $LanguageFodIsoExtractDir = $ContentIsoExtract | Where-Object {$_.Name -like "*LanguageFeatures*"} if ($OSMedia.InstallationType -eq 'Client') { if ($($OSMedia.Arch) -eq 'x86') {$LanguageFodIsoExtractDir = $LanguageFodIsoExtractDir | Where-Object {$_.FullName -like "*x86*"}} if ($($OSMedia.Arch) -eq 'x64') {$LanguageFodIsoExtractDir = $LanguageFodIsoExtractDir | Where-Object {$_.FullName -like "*x64*" -or $_.FullName -like "*amd64*"}} } $LanguageFodUpdatesDir = @() if (Test-Path "$SetOSDBuilderPathContent\Updates\LanguageFeature") { $LanguageFodUpdatesDir = Get-ChildItem -Path "$SetOSDBuilderPathContent\Updates\LanguageFeature" *.cab -Recurse | Select-Object -Property Name, FullName foreach ($Package in $LanguageFodUpdatesDir) {$Package.FullName = $($Package.FullName).replace("$SetOSDBuilderPathContent\",'')} if ($($OSMedia.Arch) -eq 'x86') {$LanguageFodUpdatesDir = $LanguageFodUpdatesDir | Where-Object {$_.FullName -like "*x86*"}} if ($($OSMedia.Arch) -eq 'x64') {$LanguageFodUpdatesDir = $LanguageFodUpdatesDir | Where-Object {$_.FullName -like "*x64*" -or $_.FullName -like "*amd64*"}} if ($($OSMedia.ReleaseId)) { if ($($OSMedia.ReleaseId) -eq 1909) { $LanguageFodUpdatesDir = $LanguageFodUpdatesDir | Where-Object {$_.FullName -match '1903' -or $_.FullName -match '1909'} } elseif ($($OSMedia.ReleaseId) -eq 2009) { $LanguageFodUpdatesDir = $LanguageFodUpdatesDir | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '20H2') { $LanguageFodUpdatesDir = $LanguageFodUpdatesDir | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '21H1') { $LanguageFodUpdatesDir = $LanguageFodUpdatesDir | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '21H2') { $LanguageFodUpdatesDir = $LanguageFodUpdatesDir | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '22H2') { $LanguageFodUpdatesDir = $LanguageFodUpdatesDir | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } else { $LanguageFodUpdatesDir = $LanguageFodUpdatesDir | Where-Object {$_.FullName -match $OSMedia.ReleaseId} } } } [array]$LanguageFeature = [array]$LanguageFodIsoExtractDir + [array]$LanguageFodUpdatesDir if ($null -eq $LanguageFeature) {Write-Warning "Install.wim Language Features On Demand: Not Found"} else { if ($ExistingTask.LanguageFeature) { foreach ($Item in $ExistingTask.LanguageFeature) { $LanguageFeature = $LanguageFeature | Where-Object {$_.FullName -ne $Item} } } $LanguageFeature = $LanguageFeature | Sort-Object -Property FullName | Out-GridView -Title "Install.wim Language Features On Demand: Select Packages to apply and press OK (Esc or Cancel to Skip)" -PassThru if($null -eq $LanguageFeature) {Write-Warning "Install.wim Language Features On Demand: Skipping"} } foreach ($Item in $LanguageFeature) {Write-Host "$($Item.FullName)" -ForegroundColor White} Return $LanguageFeature } function Get-TaskContentLanguageInterfacePack { [CmdletBinding()] param () $LanguageLipIsoExtractDir = @() $LanguageLipIsoExtractDir = $ContentIsoExtract | Where-Object {$_.Name -like "*Language-Interface-Pack*"} $LanguageLipIsoExtractDir = $LanguageLipIsoExtractDir | Where-Object {$_.Name -like "*$($OSMedia.Arch)*"} $LanguageLipUpdatesDir = @() if (Test-Path "$SetOSDBuilderPathContent\Updates\LanguageInterfacePack") { $LanguageLipUpdatesDir = Get-ChildItem -Path "$SetOSDBuilderPathContent\Updates\LanguageInterfacePack" *.cab -Recurse | Select-Object -Property Name, FullName foreach ($Package in $LanguageLipUpdatesDir) {$Package.FullName = $($Package.FullName).replace("$SetOSDBuilderPathContent\",'')} $LanguageLipUpdatesDir = $LanguageLipUpdatesDir | Where-Object {$_.FullName -like "*$($OSMedia.Arch)*"} if ($($OSMedia.ReleaseId)) { if ($($OSMedia.ReleaseId) -eq 1909) { $LanguageLipUpdatesDir = $LanguageLipUpdatesDir | Where-Object {$_.FullName -match '1903' -or $_.FullName -match '1909'} } elseif ($($OSMedia.ReleaseId) -eq 2009) { $LanguageLipUpdatesDir = $LanguageLipUpdatesDir | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '20H2') { $LanguageLipUpdatesDir = $LanguageLipUpdatesDir | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '21H1') { $LanguageLipUpdatesDir = $LanguageLipUpdatesDir | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '21H2') { $LanguageLipUpdatesDir = $LanguageLipUpdatesDir | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '22H2') { $LanguageLipUpdatesDir = $LanguageLipUpdatesDir | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } else { $LanguageLipUpdatesDir = $LanguageLipUpdatesDir | Where-Object {$_.FullName -match $OSMedia.ReleaseId} } } } [array]$LanguageInterfacePack = [array]$LanguageLipIsoExtractDir + [array]$LanguageLipUpdatesDir if ($null -eq $LanguageInterfacePack) {Write-Warning "Install.wim Language Interface Packs: Not Found"} else { if ($ExistingTask.LanguageInterfacePack) { foreach ($Item in $ExistingTask.LanguageInterfacePack) { $LanguageInterfacePack = $LanguageInterfacePack | Where-Object {$_.FullName -ne $Item} } } $LanguageInterfacePack = $LanguageInterfacePack | Sort-Object -Property FullName | Out-GridView -Title "Install.wim Language Interface Packs: Select Packages to apply and press OK (Esc or Cancel to Skip)" -PassThru if($null -eq $LanguageInterfacePack) {Write-Warning "Install.wim Language Interface Packs: Skipping"} } foreach ($Item in $LanguageInterfacePack) {Write-Host "$($Item.FullName)" -ForegroundColor White} Return $LanguageInterfacePack } function Get-TaskContentLanguagePack { [CmdletBinding()] param () $LanguageLpIsoExtractDir = @() $LanguageLpIsoExtractDir = $ContentIsoExtract | Where-Object {$_.FullName -notlike "*FOD*"} $LanguageLpIsoExtractDir = $LanguageLpIsoExtractDir | Where-Object {$_.FullName -notlike "*LanguageFeatures*"} $LanguageLpIsoExtractDir = $LanguageLpIsoExtractDir | Where-Object {$_.FullName -like "*\langpacks\*"} $LanguageLpIsoExtractDir = $LanguageLpIsoExtractDir | Where-Object {$_.Name -notlike "*Language-Interface-Pack*"} $LanguageLpUpdatesDir = @() if (Test-Path "$SetOSDBuilderPathContent\Updates\LanguagePack") { $LanguageLpUpdatesDir = Get-ChildItem -Path "$SetOSDBuilderPathContent\Updates\LanguagePack" *.cab -Recurse | Select-Object -Property Name, FullName $LanguageLpUpdatesDir = $LanguageLpUpdatesDir | Where-Object {$_.FullName -like "*$($OSMedia.Arch)*"} } $LanguageLpLegacyDir = @() if (Test-Path "$SetOSDBuilderPathContent\LanguagePacks") { $LanguageLpLegacyDir = Get-ChildItem -Path "$SetOSDBuilderPathContent\LanguagePacks" *.cab -Recurse | Select-Object -Property Name, FullName $LanguageLpLegacyDir = $LanguageLpLegacyDir | Where-Object {$_.FullName -like "*$($OSMedia.Arch)*"} } [array]$LanguagePack = [array]$LanguageLpIsoExtractDir + [array]$LanguageLpUpdatesDir + [array]$LanguageLpLegacyDir if ($OSMedia.InstallationType -eq 'Client') {$LanguagePack = $LanguagePack | Where-Object {$_.FullName -notlike "*Windows Server*"}} if ($OSMedia.InstallationType -like "*Server*") {$LanguagePack = $LanguagePack | Where-Object {$_.FullName -like "*Windows Server*"}} if ($($OSMedia.ReleaseId)) { if ($($OSMedia.ReleaseId) -eq 1909) { $LanguagePack = $LanguagePack | Where-Object {$_.FullName -match '1903' -or $_.FullName -match '1909'} } elseif ($($OSMedia.ReleaseId) -eq 2009) { $LanguagePack = $LanguagePack | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '20H2') { $LanguagePack = $LanguagePack | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '21H1') { $LanguagePack = $LanguagePack | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '21H2') { $LanguagePack = $LanguagePack | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '22H2') { $LanguagePack = $LanguagePack | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } else { $LanguagePack = $LanguagePack | Where-Object {$_.FullName -match $OSMedia.ReleaseId} } } foreach ($Package in $LanguagePack) {$Package.FullName = $($Package.FullName).replace("$SetOSDBuilderPathContent\",'')} if ($null -eq $LanguagePack) {Write-Warning "Install.wim Language Packs: Not Found"} else { if ($ExistingTask.LanguagePack) { foreach ($Item in $ExistingTask.LanguagePack) { $LanguagePack = $LanguagePack | Where-Object {$_.FullName -ne $Item} } } $LanguagePack = $LanguagePack | Sort-Object -Property FullName | Out-GridView -Title "Install.wim Language Packs: Select Packages to apply and press OK (Esc or Cancel to Skip)" -PassThru if ($null -eq $LanguagePack) {Write-Warning "Install.wim Language Packs: Skipping"} } foreach ($Item in $LanguagePack) {Write-Host "$($Item.FullName)" -ForegroundColor White} Return $LanguagePack } function Get-TaskContentLocalExperiencePacks { [CmdletBinding()] param () $LocalExperiencePacks = $ContentIsoExtract | Where-Object {$_.FullName -like "*\LocalExperiencePack\*" -and $_.Name -like "*.appx"} if ($OSMedia.InstallationType -eq 'Client') {$LocalExperiencePacks = $LocalExperiencePacks | Where-Object {$_.FullName -notlike "*Server*"}} if ($OSMedia.InstallationType -eq 'Server') {$LocalExperiencePacks = $LocalExperiencePacks | Where-Object {$_.FullName -like "*Server*"}} if ($OSMedia.InstallationType -eq 'Server') {$LocalExperiencePacks = $LocalExperiencePacks | Where-Object {$_.FullName -notlike "*Windows 10*"}} foreach ($Pack in $LocalExperiencePacks) {$Pack.FullName = $($Pack.FullName).replace("$SetOSDBuilderPathContent\",'')} if ($null -eq $LocalExperiencePacks) {Write-Warning "Install.wim Local Experience Packs: Not Found"} else { if ($ExistingTask.LocalExperiencePacks) { foreach ($Item in $ExistingTask.LocalExperiencePacks) { $LocalExperiencePacks = $LocalExperiencePacks | Where-Object {$_.FullName -ne $Item} } } $LocalExperiencePacks = $LocalExperiencePacks | Sort-Object -Property FullName | Out-GridView -Title "Install.wim Local Experience Packs: Select Capabilities to apply and press OK (Esc or Cancel to Skip)" -PassThru if ($null -eq $LocalExperiencePacks) {Write-Warning "Install.wim Local Experience Packs: Skipping"} } foreach ($Item in $LocalExperiencePacks) {Write-Host "$($Item.FullName)" -ForegroundColor White} Return $LocalExperiencePacks } function Get-TaskContentPacks { #================================================= # Content Box #================================================= [CmdletBinding()] param ( [switch]$Select ) $TaskContentPacks = Get-ChildItem -Path $SetOSDBuilderPathContentPacks -Directory -ErrorAction SilentlyContinue | Select-Object -Property Name if (!($Select.IsPresent)) {$TaskContentPacks = $TaskContentPacks | Where-Object {$_.Name -ne '_Global'}} if ($null -eq $TaskContentPacks) {Write-Warning "ContentPacks: No Packs exist in $SetOSDBuilderPathContentPacks"} else { if ($ExistingTask.ContentPacks) { foreach ($Item in $ExistingTask.ContentPacks) { $TaskContentPacks = $TaskContentPacks | Where-Object {$_.Name -ne $Item} } } if ($Select.IsPresent) { $TaskContentPacks = $TaskContentPacks | Out-GridView -Title "ContentPacks: Select only the ContentPacks to apply and press OK (Esc or Cancel to Skip)" -PassThru } else { $TaskContentPacks = $TaskContentPacks | Out-GridView -Title "ContentPacks: Select ContentPacks to add to this Task and press OK (Esc or Cancel to Skip)" -PassThru } } if (!($Select.IsPresent)) {foreach ($Item in $TaskContentPacks) {Write-Host "$($Item.Name)" -ForegroundColor White}} Return $TaskContentPacks } function Get-TaskContentScripts { #================================================= # Content Scripts #================================================= [CmdletBinding()] param () $Scripts = Get-ChildItem -Path $GetOSDBuilderPathContentScripts *.ps1 -ErrorAction SilentlyContinue | Select-Object -Property Name, FullName, Length, CreationTime | Sort-Object -Property FullName foreach ($Item in $Scripts) {$Item.FullName = $($Item.FullName).replace("$SetOSDBuilderPathContent\",'')} if ($null -eq $Scripts) {Write-Warning "Scripts: To select PowerShell Scripts add Content to $GetOSDBuilderPathContentScripts"} else { if ($ExistingTask.Scripts) { foreach ($Item in $ExistingTask.Scripts) { $Scripts = $Scripts | Where-Object {$_.FullName -ne $Item} } } $Scripts = $Scripts | Out-GridView -Title "Scripts: Select PowerShell Scripts to execute and press OK (Esc or Cancel to Skip)" -PassThru } foreach ($Item in $Scripts) {Write-Host "$($Item.FullName)" -ForegroundColor White} Return $Scripts } function Get-TaskContentStartLayoutXML { #================================================= # Content StartLayout #================================================= [CmdletBinding()] param () $StartLayoutXML = Get-ChildItem -Path $GetOSDBuilderPathContentStartLayout *.xml -ErrorAction SilentlyContinue | Select-Object -Property Name, FullName, Length, CreationTime | Sort-Object -Property FullName foreach ($Item in $StartLayoutXML) {$Item.FullName = $($Item.FullName).replace("$SetOSDBuilderPathContent\",'')} if ($null -eq $StartLayoutXML) {Write-Warning "StartLayoutXML: To select a Start Layout, add Content to $GetOSDBuilderPathContentStartLayout"} else { if ($ExistingTask.StartLayoutXML) { foreach ($Item in $ExistingTask.StartLayoutXML) { $StartLayoutXML = $StartLayoutXML | Where-Object {$_.FullName -ne $Item} } } $StartLayoutXML = $StartLayoutXML | Out-GridView -Title "StartLayoutXML: Select a Start Layout XML to apply and press OK (Esc or Cancel to Skip)" -OutputMode Single } foreach ($Item in $StartLayoutXML) {Write-Host "$($Item.FullName)" -ForegroundColor White} Return $StartLayoutXML } function Get-TaskContentUnattendXML { #================================================= # Content Unattend #================================================= [CmdletBinding()] param () $UnattendXML = Get-ChildItem -Path $GetOSDBuilderPathContentUnattend *.xml -ErrorAction SilentlyContinue | Select-Object -Property Name, FullName, Length, CreationTime | Sort-Object -Property FullName foreach ($Item in $UnattendXML) {$Item.FullName = $($Item.FullName).replace("$SetOSDBuilderPathContent\",'')} if ($null -eq $UnattendXML) {Write-Warning "UnattendXML: To select an Unattend XML, add Content to $GetOSDBuilderPathContentUnattend"} else { if ($ExistingTask.UnattendXML) { foreach ($Item in $ExistingTask.UnattendXML) { $UnattendXML = $UnattendXML | Where-Object {$_.FullName -ne $Item} } } $UnattendXML = $UnattendXML | Out-GridView -Title "UnattendXML: Select a Windows Unattend XML File to apply and press OK (Esc or Cancel to Skip)" -OutputMode Single } foreach ($Item in $UnattendXML) {Write-Host "$($Item.FullName)" -ForegroundColor White} Return $UnattendXML } function Get-TaskDisableWindowsOptionalFeature { #================================================= # DisableWindowsOptionalFeature #================================================= [CmdletBinding()] param () if (Test-Path "$($OSMedia.FullName)\info\xml\Get-WindowsOptionalFeature.xml") { $DisableWindowsOptionalFeature = Import-CliXml "$($OSMedia.FullName)\info\xml\Get-WindowsOptionalFeature.xml" } $DisableWindowsOptionalFeature = $DisableWindowsOptionalFeature | Select-Object -Property FeatureName, State | Sort-Object -Property FeatureName | Where-Object {$_.State -eq 2 -or $_.State -eq 3} $DisableWindowsOptionalFeature = $DisableWindowsOptionalFeature | Select-Object -Property FeatureName if ($ExistingTask.DisableWindowsOptionalFeature) { foreach ($Item in $ExistingTask.DisableWindowsOptionalFeature) { $DisableWindowsOptionalFeature = $DisableWindowsOptionalFeature | Where-Object {$_.FeatureName -ne $Item} } } $DisableWindowsOptionalFeature = $DisableWindowsOptionalFeature | Out-GridView -PassThru -Title "Disable-WindowsOptionalFeature: Select Windows Optional Features to Disable and press OK (Esc or Cancel to Skip)" foreach ($Item in $DisableWindowsOptionalFeature) {Write-Host "$($Item.FeatureName)" -ForegroundColor White} Return $DisableWindowsOptionalFeature } function Get-TaskEnableWindowsOptionalFeature { #================================================= # EnableWindowsOptionalFeature #================================================= [CmdletBinding()] param () if (Test-Path "$($OSMedia.FullName)\info\xml\Get-WindowsOptionalFeature.xml") { $EnableWindowsOptionalFeature = Import-CliXml "$($OSMedia.FullName)\info\xml\Get-WindowsOptionalFeature.xml" } $EnableWindowsOptionalFeature = $EnableWindowsOptionalFeature | Select-Object -Property FeatureName, State | Sort-Object -Property FeatureName | Where-Object {$_.State -eq 0} $EnableWindowsOptionalFeature = $EnableWindowsOptionalFeature | Select-Object -Property FeatureName if ($ExistingTask.EnableWindowsOptionalFeature) { foreach ($Item in $ExistingTask.EnableWindowsOptionalFeature) { $EnableWindowsOptionalFeature = $EnableWindowsOptionalFeature | Where-Object {$_.FeatureName -ne $Item} } } $EnableWindowsOptionalFeature = $EnableWindowsOptionalFeature | Out-GridView -PassThru -Title "Enable-WindowsOptionalFeature: Select Windows Optional Features to ENABLE and press OK (Esc or Cancel to Skip)" foreach ($Item in $EnableWindowsOptionalFeature) {Write-Host "$($Item.FeatureName)" -ForegroundColor White} Return $EnableWindowsOptionalFeature } function Get-TaskRemoveAppxProvisionedPackage { #================================================= # RemoveAppx #================================================= [CmdletBinding()] param () if ($($OSMedia.InstallationType) -eq 'Client') { if (Test-Path "$($OSMedia.FullName)\info\xml\Get-AppxProvisionedPackage.xml") { $RemoveAppxProvisionedPackage = Import-CliXml "$($OSMedia.FullName)\info\xml\Get-AppxProvisionedPackage.xml" $RemoveAppxProvisionedPackage = $RemoveAppxProvisionedPackage | Select-Object -Property DisplayName, PackageName if ($ExistingTask.RemoveAppxProvisionedPackage) { foreach ($Item in $ExistingTask.RemoveAppxProvisionedPackage) { $RemoveAppxProvisionedPackage = $RemoveAppxProvisionedPackage | Where-Object {$_.PackageName -ne $Item} } } $RemoveAppxProvisionedPackage = $RemoveAppxProvisionedPackage | Out-GridView -Title "Remove-AppxProvisionedPackage: Select Packages to REMOVE and press OK (Esc or Cancel to Skip)" -PassThru } foreach ($Item in $RemoveAppxProvisionedPackage) {Write-Host "$($Item.PackageName)" -ForegroundColor White} Return $RemoveAppxProvisionedPackage } else {Write-Warning "Remove-AppxProvisionedPackage: Unsupported"} } function Get-TaskRemoveWindowsCapability { #================================================= # RemoveCapability #================================================= [CmdletBinding()] param () if (Test-Path "$($OSMedia.FullName)\info\xml\Get-WindowsCapability.xml") { $RemoveWindowsCapability = Import-CliXml "$($OSMedia.FullName)\info\xml\Get-WindowsCapability.xml" $RemoveWindowsCapability = $RemoveWindowsCapability | Where-Object {$_.State -eq 4} $RemoveWindowsCapability = $RemoveWindowsCapability | Select-Object -Property Name, State if ($ExistingTask.RemoveWindowsCapability) { foreach ($Item in $ExistingTask.RemoveWindowsCapability) { $RemoveWindowsCapability = $RemoveWindowsCapability | Where-Object {$_.Name -ne $Item} } } $RemoveWindowsCapability = $RemoveWindowsCapability | Out-GridView -Title "Remove-WindowsCapability: Select Windows InBox Capability to REMOVE and press OK (Esc or Cancel to Skip)" -PassThru } foreach ($Item in $RemoveWindowsCapability) {Write-Host "$($Item.Name)" -ForegroundColor White} Return $RemoveWindowsCapability } function Get-TaskRemoveWindowsPackage { #================================================= # RemovePackage #================================================= [CmdletBinding()] param () if (Test-Path "$($OSMedia.FullName)\info\xml\Get-WindowsPackage.xml") { $RemoveWindowsPackage = Import-CliXml "$($OSMedia.FullName)\info\xml\Get-WindowsPackage.xml" $RemoveWindowsPackage = $RemoveWindowsPackage | Select-Object -Property PackageName if ($ExistingTask.RemoveWindowsPackage) { foreach ($Item in $ExistingTask.RemoveWindowsPackage) { $RemoveWindowsPackage = $RemoveWindowsPackage | Where-Object {$_.PackageName -ne $Item} } } $RemoveWindowsPackage = $RemoveWindowsPackage | Out-GridView -Title "Remove-WindowsPackage: Select Packages to REMOVE and press OK (Esc or Cancel to Skip)" -PassThru } foreach ($Item in $RemoveWindowsPackage) {Write-Host "$($Item.PackageName)" -ForegroundColor White} Return $RemoveWindowsPackage } function Get-TaskWinPEADK { #================================================= # WinPE ADK #================================================= [CmdletBinding()] param () $WinPEADK = Get-ChildItem -Path ("$SetOSDBuilderPathContent\WinPE\ADK\*","$GetOSDBuilderPathContentADK\*\Windows Preinstallation Environment\*\WinPE_OCs") *.cab -Recurse -ErrorAction SilentlyContinue | Select-Object -Property Name, FullName foreach ($Pack in $WinPEADK) {$Pack.FullName = $($Pack.FullName).replace("$SetOSDBuilderPathContent\",'')} if ($($OSMedia.ReleaseId) -eq 1909) { $WinPEADK = $WinPEADK | Where-Object {$_.FullName -match '1903' -or $_.FullName -match '1909'} } elseif ($($OSMedia.ReleaseId) -eq 2009) { $WinPEADK = $WinPEADK | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '20H2') { $WinPEADK = $WinPEADK | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '21H1') { $WinPEADK = $WinPEADK | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '21H2') { $WinPEADK = $WinPEADK | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '22H2') { $WinPEADK = $WinPEADK | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } else { $WinPEADK = $WinPEADK | Where-Object {$_.FullName -match $OSMedia.ReleaseId} } if ($OSMedia.Arch -eq 'x86') {$WinPEADK = $WinPEADK | Where-Object {$_.FullName -like "*x86*"} } else {$WinPEADK = $WinPEADK | Where-Object {($_.FullName -like "*x64*") -or ($_.FullName -like "*amd64*")}} $WinPEADKIE = @() $WinPEADKIE = $ContentIsoExtractWinPE | Select-Object -Property Name, FullName [array]$WinPEADK = [array]$WinPEADK + [array]$WinPEADKIE if ($null -eq $WinPEADK) {Write-Warning "WinPE.wim ADK Packages: Add Content to $GetOSDBuilderPathContentADK"} else { if ($ExistingTask.WinPEADK) { foreach ($Item in $ExistingTask.WinPEADK) { $WinPEADK = $WinPEADK | Where-Object {$_.FullName -ne $Item} } } $WinPEADK = $WinPEADK | Out-GridView -Title "WinPE.wim ADK Packages: Select ADK Packages to apply and press OK (Esc or Cancel to Skip)" -PassThru } foreach ($Item in $WinPEADK) {Write-Host "$($Item.FullName)" -ForegroundColor White} Return $WinPEADK } function Get-TaskWinPEADKPE { #================================================= # WinPE ADK #================================================= [CmdletBinding()] param () $WinPEADKPE = Get-ChildItem -Path ("$SetOSDBuilderPathContent\WinPE\ADK\*","$GetOSDBuilderPathContentADK\*\Windows Preinstallation Environment\*\WinPE_OCs") *.cab -Recurse -ErrorAction SilentlyContinue | Select-Object -Property Name, FullName foreach ($Pack in $WinPEADKPE) {$Pack.FullName = $($Pack.FullName).replace("$SetOSDBuilderPathContent\",'')} if ($($OSMedia.ReleaseId) -eq 1909) { $WinPEADKPE = $WinPEADKPE | Where-Object {$_.FullName -match '1903' -or $_.FullName -match '1909'} } elseif ($($OSMedia.ReleaseId) -eq 2009) { $WinPEADKPE = $WinPEADKPE | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '20H2') { $WinPEADKPE = $WinPEADKPE | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '21H1') { $WinPEADKPE = $WinPEADKPE | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '21H2') { $WinPEADKPE = $WinPEADKPE | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '22H2') { $WinPEADKPE = $WinPEADKPE | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } else { $WinPEADKPE = $WinPEADKPE | Where-Object {$_.FullName -match $OSMedia.ReleaseId} } if ($OSMedia.Arch -eq 'x86') {$WinPEADKPE = $WinPEADKPE | Where-Object {$_.FullName -like "*x86*"} } else {$WinPEADKPE = $WinPEADKPE | Where-Object {($_.FullName -like "*x64*") -or ($_.FullName -like "*amd64*")}} $WinPEADKPEIE = @() $WinPEADKPEIE = $ContentIsoExtractWinPE | Select-Object -Property Name, FullName [array]$WinPEADKPE = [array]$WinPEADKPE + [array]$WinPEADKPEIE if ($null -eq $WinPEADKPE) {Write-Warning "WinPE.wim ADK Packages: Add Content to $GetOSDBuilderPathContentADK"} else { if ($ExistingTask.WinPEADKPE) { foreach ($Item in $ExistingTask.WinPEADKPE) { $WinPEADKPE = $WinPEADKPE | Where-Object {$_.FullName -ne $Item} } } $WinPEADKPE = $WinPEADKPE | Out-GridView -Title "WinPE.wim ADK Packages: Select ADK Packages to apply and press OK (Esc or Cancel to Skip)" -PassThru } foreach ($Item in $WinPEADKPE) {Write-Host "$($Item.FullName)" -ForegroundColor White} Return $WinPEADKPE } function Get-TaskWinPEADKRE { #================================================= # WinRE ADK #================================================= [CmdletBinding()] param () $WinPEADKRE = Get-ChildItem -Path ("$SetOSDBuilderPathContent\WinPE\ADK\*","$GetOSDBuilderPathContentADK\*\Windows Preinstallation Environment\*\WinPE_OCs") *.cab -Recurse -ErrorAction SilentlyContinue | Select-Object -Property Name, FullName foreach ($Pack in $WinPEADKRE) {$Pack.FullName = $($Pack.FullName).replace("$SetOSDBuilderPathContent\",'')} if ($($OSMedia.ReleaseId) -eq 1909) { $WinPEADKRE = $WinPEADKRE | Where-Object {$_.FullName -match '1903' -or $_.FullName -match '1909'} } elseif ($($OSMedia.ReleaseId) -eq 2009) { $WinPEADKRE = $WinPEADKRE | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '20H2') { $WinPEADKRE = $WinPEADKRE | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '21H1') { $WinPEADKRE = $WinPEADKRE | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '21H2') { $WinPEADKRE = $WinPEADKRE | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '22H2') { $WinPEADKRE = $WinPEADKRE | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } else { $WinPEADKRE = $WinPEADKRE | Where-Object {$_.FullName -match $OSMedia.ReleaseId} } if ($OSMedia.Arch -eq 'x86') {$WinPEADKRE = $WinPEADKRE | Where-Object {$_.FullName -like "*x86*"} } else {$WinPEADKRE = $WinPEADKRE | Where-Object {($_.FullName -like "*x64*") -or ($_.FullName -like "*amd64*")}} $WinPEADKREIE = @() $WinPEADKREIE = $ContentIsoExtractWinPE | Select-Object -Property Name, FullName [array]$WinPEADKRE = [array]$WinPEADKRE + [array]$WinPEADKREIE if ($null -eq $WinPEADKRE) {Write-Warning "WinRE.wim ADK Packages: Add Content to $GetOSDBuilderPathContentADK"} else { if ($ExistingTask.WinPEADKRE) { foreach ($Item in $ExistingTask.WinPEADKRE) { $WinPEADKRE = $WinPEADKRE | Where-Object {$_.FullName -ne $Item} } } Write-Warning "If you add too many ADK Packages to WinRE, like .Net and PowerShell" Write-Warning "You run a risk of your WinRE size increasing considerably" Write-Warning "If your MBR System or UEFI Recovery Partition are 500MB," Write-Warning "your WinRE.wim should not be more than 400MB (100MB Free)" Write-Warning "Consider changing your Task Sequences to have a 984MB" Write-Warning "MBR System or UEFI Recovery Partition" $WinPEADKRE = $WinPEADKRE | Out-GridView -Title "WinRE.wim ADK Packages: Select ADK Packages to apply and press OK (Esc or Cancel to Skip)" -PassThru } foreach ($Item in $WinPEADKRE) {Write-Host "$($Item.FullName)" -ForegroundColor White} Return $WinPEADKRE } function Get-TaskWinPEADKSE { #================================================= # WinRE ADK #================================================= [CmdletBinding()] param () $WinPEADKSE = Get-ChildItem -Path ("$SetOSDBuilderPathContent\WinPE\ADK\*","$GetOSDBuilderPathContentADK\*\Windows Preinstallation Environment\*\WinPE_OCs") *.cab -Recurse -ErrorAction SilentlyContinue | Select-Object -Property Name, FullName foreach ($Pack in $WinPEADKSE) {$Pack.FullName = $($Pack.FullName).replace("$SetOSDBuilderPathContent\",'')} if ($($OSMedia.ReleaseId) -eq 1909) { $WinPEADKSE = $WinPEADKSE | Where-Object {$_.FullName -match '1903' -or $_.FullName -match '1909'} } elseif ($($OSMedia.ReleaseId) -eq 2009) { $WinPEADKSE = $WinPEADKSE | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '20H2') { $WinPEADKSE = $WinPEADKSE | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '21H1') { $WinPEADKSE = $WinPEADKSE | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '21H2') { $WinPEADKSE = $WinPEADKSE | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } elseif ($($OSMedia.ReleaseId) -eq '22H2') { $WinPEADKSE = $WinPEADKSE | Where-Object {$_.FullName -match '2004' -or $_.FullName -match '2009' -or $_.FullName -match '20H2' -or $_.FullName -match '21H1' -or $_.FullName -match '21H2' -or $_.FullName -match '22H2'} } else { $WinPEADKSE = $WinPEADKSE | Where-Object {$_.FullName -match $OSMedia.ReleaseId} } if ($OSMedia.Arch -eq 'x86') {$WinPEADKSE = $WinPEADKSE | Where-Object {$_.FullName -like "*x86*"} } else {$WinPEADKSE = $WinPEADKSE | Where-Object {($_.FullName -like "*x64*") -or ($_.FullName -like "*amd64*")}} $WinPEADKSEIE = @() $WinPEADKSEIE = $ContentIsoExtractWinPE | Select-Object -Property Name, FullName [array]$WinPEADKSE = [array]$WinPEADKSE + [array]$WinPEADKSEIE if ($null -eq $WinPEADKSE) {Write-Warning "WinSE.wim ADK Packages: Add Content to $GetOSDBuilderPathContentADK"} else { if ($ExistingTask.WinPEADKSE) { foreach ($Item in $ExistingTask.WinPEADKSE) { $WinPEADKSE = $WinPEADKSE | Where-Object {$_.FullName -ne $Item} } } $WinPEADKSE = $WinPEADKSE | Out-GridView -Title "WinSE.wim ADK Packages: Select ADK Packages to apply and press OK (Esc or Cancel to Skip)" -PassThru } foreach ($Item in $WinPEADKSE) {Write-Host "$($Item.FullName)" -ForegroundColor White} Return $WinPEADKSE } function Get-TaskWinPEDaRT { #================================================= # WinPE DaRT #================================================= [CmdletBinding()] param () $WinPEDaRT = Get-ChildItem -Path ($GetOSDBuilderPathContentDaRT,"$SetOSDBuilderPathContent\WinPE\DaRT") *.cab -Recurse -ErrorAction SilentlyContinue | Select-Object -Property Name, FullName $WinPEDaRT = $WinPEDaRT | Where-Object {$_.FullName -like "*$($OSMedia.Arch)*"} foreach ($Pack in $WinPEDaRT) {$Pack.FullName = $($Pack.FullName).replace("$SetOSDBuilderPathContent\",'')} if ($null -eq $WinPEDaRT) {Write-Warning "WinPEDaRT: Add Content to $GetOSDBuilderPathContentDaRT"} else { if ($ExistingTask.WinPEDaRT) { foreach ($Item in $ExistingTask.WinPEDaRT) { $WinPEDaRT = $WinPEDaRT | Where-Object {$_.FullName -ne $Item} } } $WinPEDaRT = $WinPEDaRT | Out-GridView -Title "WinPEDaRT: Select a WinPE DaRT Package to apply and press OK (Esc or Cancel to Skip)" -OutputMode Single } foreach ($Item in $WinPEDaRT) {Write-Host "$($Item.FullName)" -ForegroundColor White} Return $WinPEDaRT } function Get-TaskWinPEDrivers { #================================================= # WinPE Add-WindowsDriver #================================================= [CmdletBinding()] param () $WinPEDrivers = Get-ChildItem -Path ($GetOSDBuilderPathContentDrivers,"$SetOSDBuilderPathContent\WinPE\Drivers") -Directory -ErrorAction SilentlyContinue | Select-Object -Property Name, FullName foreach ($Pack in $WinPEDrivers) {$Pack.FullName = $($Pack.FullName).replace("$SetOSDBuilderPathContent\",'')} if ($null -eq $WinPEDrivers) {Write-Warning "WinPEDrivers: To select WinPE Drivers, add Content to $GetOSDBuilderPathContentDrivers"} else { if ($ExistingTask.WinPEDrivers) { foreach ($Item in $ExistingTask.WinPEDrivers) { $WinPEDrivers = $WinPEDrivers | Where-Object {$_.FullName -ne $Item} } } $WinPEDrivers = $WinPEDrivers | Out-GridView -Title "WinPEDrivers: Select Driver Paths to apply and press OK (Esc or Cancel to Skip)" -PassThru } foreach ($Item in $WinPEDrivers) {Write-Host "$($Item.FullName)" -ForegroundColor White} Return $WinPEDrivers } function Get-TaskWinPEExtraFiles { #================================================= # WinPEExtraFiles #================================================= [CmdletBinding()] param () $WinPEExtraFiles = Get-ChildItem -Path ($GetOSDBuilderPathContentExtraFiles,"$SetOSDBuilderPathContent\WinPE\ExtraFiles") -Directory -ErrorAction SilentlyContinue | Select-Object -Property Name, FullName $WinPEExtraFiles = $WinPEExtraFiles | Where-Object {(Get-ChildItem $_.FullName | Measure-Object).Count -gt 0} foreach ($Pack in $WinPEExtraFiles) {$Pack.FullName = $($Pack.FullName).replace("$SetOSDBuilderPathContent\",'')} if ($null -eq $WinPEExtraFiles) {Write-Warning "WinPEExtraFiles: To select WinPE Extra Files, add Content to $GetOSDBuilderPathContentExtraFiles"} else { if ($ExistingTask.WinPEExtraFiles) { foreach ($Item in $ExistingTask.WinPEExtraFiles) { $WinPEExtraFiles = $WinPEExtraFiles | Where-Object {$_.FullName -ne $Item} } } $WinPEExtraFiles = $WinPEExtraFiles | Out-GridView -Title "WinPEExtraFiles: Select directories to inject and press OK (Esc or Cancel to Skip)" -PassThru } foreach ($Item in $WinPEExtraFiles) {Write-Host "$($Item.FullName)" -ForegroundColor White} Return $WinPEExtraFiles } function Get-TaskWinPEExtraFilesPE { #================================================= # WinPEExtraFilesPE #================================================= [CmdletBinding()] param () $WinPEExtraFilesPE = Get-ChildItem -Path ($GetOSDBuilderPathContentExtraFiles,"$SetOSDBuilderPathContent\WinPE\ExtraFiles") -Directory -ErrorAction SilentlyContinue | Select-Object -Property Name, FullName $WinPEExtraFilesPE = $WinPEExtraFilesPE | Where-Object {(Get-ChildItem $_.FullName | Measure-Object).Count -gt 0} foreach ($Pack in $WinPEExtraFilesPE) {$Pack.FullName = $($Pack.FullName).replace("$SetOSDBuilderPathContent\",'')} if ($null -eq $WinPEExtraFilesPE) {Write-Warning "WinPEExtraFilesPE: To select WinPE Extra Files, add Content to $GetOSDBuilderPathContentExtraFiles"} else { if ($ExistingTask.WinPEExtraFilesPE) { foreach ($Item in $ExistingTask.WinPEExtraFilesPE) { $WinPEExtraFilesPE = $WinPEExtraFilesPE | Where-Object {$_.FullName -ne $Item} } } $WinPEExtraFilesPE = $WinPEExtraFilesPE | Out-GridView -Title "WinPEExtraFilesPE: Select directories to inject and press OK (Esc or Cancel to Skip)" -PassThru } foreach ($Item in $WinPEExtraFilesPE) {Write-Host "$($Item.FullName)" -ForegroundColor White} Return $WinPEExtraFilesPE } function Get-TaskWinPEExtraFilesRE { #================================================= # WinPEExtraFilesRE #================================================= [CmdletBinding()] param () $WinPEExtraFilesRE = Get-ChildItem -Path ($GetOSDBuilderPathContentExtraFiles,"$SetOSDBuilderPathContent\WinPE\ExtraFiles") -Directory -ErrorAction SilentlyContinue | Select-Object -Property Name, FullName $WinPEExtraFilesRE = $WinPEExtraFilesRE | Where-Object {(Get-ChildItem $_.FullName | Measure-Object).Count -gt 0} foreach ($Pack in $WinPEExtraFilesRE) {$Pack.FullName = $($Pack.FullName).replace("$SetOSDBuilderPathContent\",'')} if ($null -eq $WinPEExtraFilesRE) {Write-Warning "WinPEExtraFilesRE: To select WinRE Extra Files, add Content to $GetOSDBuilderPathContentExtraFiles"} else { if ($ExistingTask.WinPEExtraFilesRE) { foreach ($Item in $ExistingTask.WinPEExtraFilesRE) { $WinPEExtraFilesRE = $WinPEExtraFilesRE | Where-Object {$_.FullName -ne $Item} } } $WinPEExtraFilesRE = $WinPEExtraFilesRE | Out-GridView -Title "WinPEExtraFilesRE: Select directories to inject and press OK (Esc or Cancel to Skip)" -PassThru } foreach ($Item in $WinPEExtraFilesRE) {Write-Host "$($Item.FullName)" -ForegroundColor White} Return $WinPEExtraFilesRE } function Get-TaskWinPEExtraFilesSE { #================================================= # WinSE Add-ExtraFiles #================================================= [CmdletBinding()] param () $WinPEExtraFilesSE = Get-ChildItem -Path ($GetOSDBuilderPathContentExtraFiles,"$SetOSDBuilderPathContent\WinPE\ExtraFiles") -Directory -ErrorAction SilentlyContinue | Select-Object -Property Name, FullName $WinPEExtraFilesSE = $WinPEExtraFilesSE | Where-Object {(Get-ChildItem $_.FullName | Measure-Object).Count -gt 0} foreach ($Pack in $WinPEExtraFilesSE) {$Pack.FullName = $($Pack.FullName).replace("$SetOSDBuilderPathContent\",'')} if ($null -eq $WinPEExtraFilesSE) {Write-Warning "WinPEExtraFilesSE: To select WinSE Extra Files, add Content to $GetOSDBuilderPathContentExtraFiles"} else { if ($ExistingTask.WinPEExtraFilesSE) { foreach ($Item in $ExistingTask.WinPEExtraFilesSE) { $WinPEExtraFilesSE = $WinPEExtraFilesSE | Where-Object {$_.FullName -ne $Item} } } $WinPEExtraFilesSE = $WinPEExtraFilesSE | Out-GridView -Title "WinPEExtraFilesSE: Select directories to inject and press OK (Esc or Cancel to Skip)" -PassThru } foreach ($Item in $WinPEExtraFilesSE) {Write-Host "$($Item.FullName)" -ForegroundColor White} Return $WinPEExtraFilesSE } function Get-TaskWinPEScripts { #================================================= # WinPE PowerShell Scripts #================================================= [CmdletBinding()] param () $WinPEScripts = Get-ChildItem -Path ($GetOSDBuilderPathContentScripts,"$SetOSDBuilderPathContent\WinPE\Scripts") *.ps1 -ErrorAction SilentlyContinue | Select-Object -Property Name, FullName, Length, CreationTime | Sort-Object -Property FullName foreach ($TaskScript in $WinPEScripts) {$TaskScript.FullName = $($TaskScript.FullName).replace("$SetOSDBuilderPathContent\",'')} if ($null -eq $WinPEScripts) {Write-Warning "WinPE PowerShell Scripts: To select PowerShell Scripts add Content to $GetOSDBuilderPathContentScripts"} else { if ($ExistingTask.WinPEScripts) { foreach ($Item in $ExistingTask.WinPEScripts) { $WinPEScripts = $WinPEScripts | Where-Object {$_.FullName -ne $Item} } } $WinPEScripts = $WinPEScripts | Out-GridView -Title "WinPE PowerShell Scripts: Select PowerShell Scripts to execute and press OK (Esc or Cancel to Skip)" -PassThru } foreach ($Item in $WinPEScripts) {Write-Host "$($Item.FullName)" -ForegroundColor White} Return $WinPEScripts } function Get-TaskWinPEScriptsPE { #================================================= # WinPE PowerShell Scripts #================================================= [CmdletBinding()] param () $WinPEScriptsPE = Get-ChildItem -Path ($GetOSDBuilderPathContentScripts,"$SetOSDBuilderPathContent\WinPE\Scripts") *.ps1 -ErrorAction SilentlyContinue | Select-Object -Property Name, FullName, Length, CreationTime | Sort-Object -Property FullName foreach ($TaskScript in $WinPEScriptsPE) {$TaskScript.FullName = $($TaskScript.FullName).replace("$SetOSDBuilderPathContent\",'')} if ($null -eq $WinPEScriptsPE) {Write-Warning "WinPE PowerShell Scripts: To select PowerShell Scripts add Content to $GetOSDBuilderPathContentScripts"} else { if ($ExistingTask.WinPEScriptsPE) { foreach ($Item in $ExistingTask.WinPEScriptsPE) { $WinPEScriptsPE = $WinPEScriptsPE | Where-Object {$_.FullName -ne $Item} } } $WinPEScriptsPE = $WinPEScriptsPE | Out-GridView -Title "WinPE PowerShell Scripts: Select PowerShell Scripts to execute and press OK (Esc or Cancel to Skip)" -PassThru } foreach ($Item in $WinPEScriptsPE) {Write-Host "$($Item.FullName)" -ForegroundColor White} Return $WinPEScriptsPE } function Get-TaskWinPEScriptsRE { #================================================= # WinRE PowerShell Scripts #================================================= [CmdletBinding()] param () $WinPEScriptsRE = Get-ChildItem -Path ($GetOSDBuilderPathContentScripts,"$SetOSDBuilderPathContent\WinPE\Scripts") *.ps1 -ErrorAction SilentlyContinue | Select-Object -Property Name, FullName, Length, CreationTime | Sort-Object -Property FullName foreach ($TaskScript in $WinPEScriptsRE) {$TaskScript.FullName = $($TaskScript.FullName).replace("$SetOSDBuilderPathContent\",'')} if ($null -eq $WinPEScriptsRE) {Write-Warning "WinRE PowerShell Scripts: To select PowerShell Scripts add Content to $GetOSDBuilderPathContentScripts"} else { if ($ExistingTask.WinPEScriptsRE) { foreach ($Item in $ExistingTask.WinPEScriptsRE) { $WinPEScriptsRE = $WinPEScriptsRE | Where-Object {$_.FullName -ne $Item} } } $WinPEScriptsRE = $WinPEScriptsRE | Out-GridView -Title "WinRE PowerShell Scripts: Select PowerShell Scripts to execute and press OK (Esc or Cancel to Skip)" -PassThru } foreach ($Item in $WinPEScriptsRE) {Write-Host "$($Item.FullName)" -ForegroundColor White} Return $WinPEScriptsRE } function Get-TaskWinPEScriptsSE { #================================================= # WinSE PowerShell Scripts #================================================= [CmdletBinding()] param () $WinPEScriptsSE = Get-ChildItem -Path ($GetOSDBuilderPathContentScripts,"$SetOSDBuilderPathContent\WinPE\Scripts") *.ps1 -ErrorAction SilentlyContinue | Select-Object -Property Name, FullName, Length, CreationTime | Sort-Object -Property FullName foreach ($TaskScript in $WinPEScriptsSE) {$TaskScript.FullName = $($TaskScript.FullName).replace("$SetOSDBuilderPathContent\",'')} if ($null -eq $WinPEScriptsSE) {Write-Warning "WinSE PowerShell Scripts: To select PowerShell Scripts add Content to $GetOSDBuilderPathContentScripts"} else { if ($ExistingTask.WinPEScriptsSE) { foreach ($Item in $ExistingTask.WinPEScriptsSE) { $WinPEScriptsSE = $WinPEScriptsSE | Where-Object {$_.FullName -ne $Item} } } $WinPEScriptsSE = $WinPEScriptsSE | Out-GridView -Title "WinSE PowerShell Scripts: Select PowerShell Scripts to execute and press OK (Esc or Cancel to Skip)" -PassThru } foreach ($Item in $WinPEScriptsSE) {Write-Host "$($Item.FullName)" -ForegroundColor White} Return $WinPEScriptsSE } function Get-Value { param( $value ) $result = $null if ( $value -is [System.Management.Automation.PSCustomObject] ) { Write-Verbose "Get-Value: value is PSCustomObject" $result = @{} $value.psobject.properties | ForEach-Object { $result[$_.Name] = Get-Value -value $_.Value } } elseif ($value -is [System.Object[]]) { $list = New-Object System.Collections.ArrayList Write-Verbose "Get-Value: value is Array" $value | ForEach-Object { $list.Add((Get-Value -value $_)) | Out-Null } $result = $list } else { Write-Verbose "Get-Value: value is type: $($value.GetType())" $result = $value } return $result } function Import-AutoExtraFilesPE { [CmdletBinding()] param () #================================================= # Abort #================================================= if (($ScriptName -ne 'New-OSBuild') -and ($ScriptName -ne 'New-OSDCloudOSMedia')) {Return} if ($WinPEAutoExtraFiles -ne $true) {Return} #================================================= # Header #================================================= Show-ActionTime; Write-Host -ForegroundColor Green "WinPE: Import AutoExtraFiles" #================================================= # Execute #================================================= Write-Host -ForegroundColor Cyan " $WinPE\AutoExtraFiles" $CurrentLog = "$PEInfo\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Import-AutoExtraFilesPE.log" robocopy "$WinPE\AutoExtraFiles" "$MountWinPE" *.* /s /ndl /xf bcp47*.dll /xx /b /np /ts /tee /r:0 /w:0 /Log+:"$CurrentLog" | Out-Null robocopy "$WinPE\AutoExtraFiles" "$MountWinRE" *.* /s /ndl /xf bcp47*.dll /xx /b /np /ts /tee /r:0 /w:0 /Log+:"$CurrentLog" | Out-Null robocopy "$WinPE\AutoExtraFiles" "$MountWinSE" *.* /s /ndl /xf bcp47*.dll /xx /b /np /ts /tee /r:0 /w:0 /Log+:"$CurrentLog" | Out-Null #================================================= } function Import-RegistryRegOS { [CmdletBinding()] param () #================================================= # ABORT #================================================= if ([string]::IsNullOrWhiteSpace($RegistryTemplatesReg)) {Return} #================================================= # Execute #================================================= if ($RegistryTemplatesReg) { Show-ActionTime; Write-Host -ForegroundColor Green "OS: Template Registry REG" #====================================================================================== # Load Registry Hives #====================================================================================== if (Test-Path "$MountDirectory\Users\Default\NTUser.dat") { Write-Host "Loading Offline Registry Hive Default User" -ForegroundColor DarkGray Start-Process reg -ArgumentList "load HKLM\OfflineDefaultUser $MountDirectory\Users\Default\NTUser.dat" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path "$MountDirectory\Windows\System32\Config\DEFAULT") { Write-Host "Loading Offline Registry Hive DEFAULT" -ForegroundColor DarkGray Start-Process reg -ArgumentList "load HKLM\OfflineDefault $MountDirectory\Windows\System32\Config\DEFAULT" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path "$MountDirectory\Windows\System32\Config\SOFTWARE") { Write-Host "Loading Offline Registry Hive SOFTWARE" -ForegroundColor DarkGray Start-Process reg -ArgumentList "load HKLM\OfflineSoftware $MountDirectory\Windows\System32\Config\SOFTWARE" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path "$MountDirectory\Windows\System32\Config\SYSTEM") { Write-Host "Loading Offline Registry Hive SYSTEM" -ForegroundColor DarkGray Start-Process reg -ArgumentList "load HKLM\OfflineSystem $MountDirectory\Windows\System32\Config\SYSTEM" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } #====================================================================================== # Process Registry REG #====================================================================================== foreach ($RegistryREG in $RegistryTemplatesReg) { Write-Host "Processing $($RegistryREG.FullName)" $REGImportContent = @() $REGImportContent = Get-Content -Path $RegistryREG.FullName foreach ($Line in $REGImportContent) { Write-Host "$Line" -ForegroundColor Gray } Start-Process reg -ArgumentList ('import',"`"$($RegistryREG.FullName)`"") -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } #====================================================================================== # Unload Registry Hives #====================================================================================== if (Test-Path -Path "HKLM:\OfflineDefaultUser") { Write-Host "Unloading Registry HKLM\OfflineDefaultUser" -ForegroundColor DarkGray Start-Process reg -ArgumentList "unload HKLM\OfflineDefaultUser" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path -Path "HKLM:\OfflineDefault") { Write-Host "Unloading Registry HKLM\OfflineDefault" -ForegroundColor DarkGray Start-Process reg -ArgumentList "unload HKLM\OfflineDefault" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path -Path "HKLM:\OfflineSoftware") { Write-Host "Unloading Registry HKLM\OfflineSoftware" -ForegroundColor DarkGray Start-Process reg -ArgumentList "unload HKLM\OfflineSoftware" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path -Path "HKLM:\OfflineSystem") { Write-Host "Unloading Registry HKLM\OfflineSystem" -ForegroundColor DarkGray Start-Process reg -ArgumentList "unload HKLM\OfflineSystem" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path -Path "HKLM:\OfflineDefaultUser") { Write-Host "Unloading Registry HKLM\OfflineDefaultUser (Second Attempt)" -ForegroundColor DarkGray Start-Process reg -ArgumentList "unload HKLM\OfflineDefaultUser" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path -Path "HKLM:\OfflineDefault") { Write-Host "Unloading Registry HKLM\OfflineDefault (Second Attempt)" -ForegroundColor DarkGray Start-Process reg -ArgumentList "unload HKLM\OfflineDefault" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path -Path "HKLM:\OfflineSoftware") { Write-Host "Unloading Registry HKLM\OfflineSoftware (Second Attempt)" -ForegroundColor DarkGray Start-Process reg -ArgumentList "unload HKLM\OfflineSoftware" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path -Path "HKLM:\OfflineSystem") { Write-Host "Unloading Registry HKLM\OfflineSystem (Second Attempt)" -ForegroundColor DarkGray Start-Process reg -ArgumentList "unload HKLM\OfflineSystem" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path -Path "HKLM:\OfflineDefaultUser") { Write-Warning "HKLM:\OfflineDefaultUser could not be dismounted. Open Regedit and unload the Hive manually" Pause } if (Test-Path -Path "HKLM:\OfflineDefault") { Write-Warning "HKLM:\OfflineDefault could not be dismounted. Open Regedit and unload the Hive manually" Pause } if (Test-Path -Path "HKLM:\OfflineSoftware") { Write-Warning "HKLM:\OfflineSoftware could not be dismounted. Open Regedit and unload the Hive manually" Pause } if (Test-Path -Path "HKLM:\OfflineSystem") { Write-Warning "HKLM:\OfflineSystem could not be dismounted. Open Regedit and unload the Hive manually" Pause } } #====================================================================================== } function Import-RegistryXmlOS { [CmdletBinding()] param () #================================================= # ABORT #================================================= if ([string]::IsNullOrWhiteSpace($RegistryTemplatesXml)) {Return} #================================================= # Execute #================================================= Show-ActionTime; Write-Host -ForegroundColor Green "OS: Template Registry XML" if ($RegistryTemplatesXml) { #====================================================================================== # Load Registry Hives #====================================================================================== if (Test-Path "$MountDirectory\Users\Default\NTUser.dat") { Write-Host "Loading Offline Registry Hive Default User" -ForegroundColor DarkGray Start-Process reg -ArgumentList "load HKLM\OfflineDefaultUser $MountDirectory\Users\Default\NTUser.dat" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path "$MountDirectory\Windows\System32\Config\DEFAULT") { Write-Host "Loading Offline Registry Hive DEFAULT" -ForegroundColor DarkGray Start-Process reg -ArgumentList "load HKLM\OfflineDefault $MountDirectory\Windows\System32\Config\DEFAULT" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path "$MountDirectory\Windows\System32\Config\SOFTWARE") { Write-Host "Loading Offline Registry Hive SOFTWARE" -ForegroundColor DarkGray Start-Process reg -ArgumentList "load HKLM\OfflineSoftware $MountDirectory\Windows\System32\Config\SOFTWARE" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path "$MountDirectory\Windows\System32\Config\SYSTEM") { Write-Host "Loading Offline Registry Hive SYSTEM" -ForegroundColor DarkGray Start-Process reg -ArgumentList "load HKLM\OfflineSystem $MountDirectory\Windows\System32\Config\SYSTEM" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } #====================================================================================== # Process Registry XML #====================================================================================== foreach ($RegistryXml in $RegistryTemplatesXml) { $RegistrySettings = @() Write-Host "Processing $($RegistryXml.FullName)" [xml]$XmlDocument = Get-Content -Path $RegistryXml.FullName $nodes = $XmlDocument.SelectNodes("//*[@action]") foreach ($node in $nodes) { $NodeAction = $node.attributes['action'].value $NodeDefault = $node.attributes['default'].value $NodeHive = $node.attributes['hive'].value $NodeKey = $node.attributes['key'].value $NodeName = $node.attributes['name'].value $NodeType = $node.attributes['type'].value $NodeValue = $node.attributes['value'].value $obj = new-object psobject -prop @{Action=$NodeAction;Default=$NodeDefault;Hive=$NodeHive;Key=$NodeKey;Name=$NodeName;Type=$NodeType;Value=$NodeValue} $RegistrySettings += $obj } foreach ($RegEntry in $RegistrySettings) { $RegAction = $RegEntry.Action $RegDefault = $RegEntry.Default $RegHive = $RegEntry.Hive #$RegHive = $RegHive -replace 'HKEY_LOCAL_MACHINE','HKLM:' -replace 'HKEY_CURRENT_USER','HKCU:' -replace 'HKEY_USERS','HKU:' $RegKey = $RegEntry.Key $RegName = $RegEntry.Name $RegType = $RegEntry.Type $RegType = $RegType -replace 'REG_SZ','String' $RegType = $RegType -replace 'REG_DWORD','DWord' $RegType = $RegType -replace 'REG_QWORD','QWord' $RegType = $RegType -replace 'REG_MULTI_SZ','MultiString' $RegType = $RegType -replace 'REG_EXPAND_SZ','ExpandString' $RegType = $RegType -replace 'REG_BINARY','Binary' $RegValue = $RegEntry.Value if ($RegType -eq 'Binary') { $RegValue = $RegValue -replace '(..(?!$))','$1,' $RegValue = $RegValue.Split(',') | ForEach-Object {"0x$_"} } $RegPath = "Registry::$RegHive\$RegKey" $RegPath = $RegPath -replace 'HKEY_CURRENT_USER','HKEY_LOCAL_MACHINE\OfflineDefaultUser' $RegPath = $RegPath -replace 'HKEY_LOCAL_MACHINE\\SOFTWARE','HKEY_LOCAL_MACHINE\OfflineSoftware' $RegPath = $RegPath -replace 'HKEY_LOCAL_MACHINE\\SYSTEM','HKEY_LOCAL_MACHINE\OfflineSystem' $RegPath = $RegPath -replace 'HKEY_USERS\\.DEFAULT','HKEY_LOCAL_MACHINE\OfflineDefault' if ($RegAction -eq "D") { Write-Host "Remove-ItemProperty -LiteralPath $RegPath" -ForegroundColor Red if ($RegDefault -eq '0' -and $RegName -eq '' -and $RegValue -eq '') { Remove-ItemProperty -LiteralPath $RegPath -Force -ErrorAction SilentlyContinue | Out-Null } elseif ($RegDefault -eq '1') { Write-Host "-Name '(Default)'" Remove-ItemProperty -LiteralPath $RegPath -Name '(Default)' -Force -ErrorAction SilentlyContinue | Out-Null } else { Write-Host "-Name $RegName" Remove-ItemProperty -LiteralPath $RegPath -Name $RegName -Force -ErrorAction SilentlyContinue | Out-Null } } else { if (!(Test-Path -LiteralPath $RegPath)) { Write-Host "New-Item -Path $RegPath" -ForegroundColor Gray New-Item -Path $RegPath -Force | Out-Null } if ($RegDefault -eq '1') {$RegName = '(Default)'} if (!($RegType -eq '')) { Write-Host "New-ItemProperty -LiteralPath $RegPath" -ForegroundColor Gray Write-Host "-Name $RegName -PropertyType $RegType -Value $RegValue" -ForegroundColor DarkGray New-ItemProperty -LiteralPath $RegPath -Name $RegName -PropertyType $RegType -Value $RegValue -Force | Out-Null } } } } #====================================================================================== # Unload Registry Hives #====================================================================================== if (Test-Path -Path "HKLM:\OfflineDefaultUser") { Write-Host "Unloading Registry HKLM\OfflineDefaultUser" -ForegroundColor DarkGray Start-Process reg -ArgumentList "unload HKLM\OfflineDefaultUser" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path -Path "HKLM:\OfflineDefault") { Write-Host "Unloading Registry HKLM\OfflineDefault" -ForegroundColor DarkGray Start-Process reg -ArgumentList "unload HKLM\OfflineDefault" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path -Path "HKLM:\OfflineSoftware") { Write-Host "Unloading Registry HKLM\OfflineSoftware" -ForegroundColor DarkGray Start-Process reg -ArgumentList "unload HKLM\OfflineSoftware" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path -Path "HKLM:\OfflineSystem") { Write-Host "Unloading Registry HKLM\OfflineSystem" -ForegroundColor DarkGray Start-Process reg -ArgumentList "unload HKLM\OfflineSystem" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path -Path "HKLM:\OfflineDefaultUser") { Write-Host "Unloading Registry HKLM\OfflineDefaultUser (Second Attempt)" -ForegroundColor DarkGray Start-Process reg -ArgumentList "unload HKLM\OfflineDefaultUser" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path -Path "HKLM:\OfflineDefault") { Write-Host "Unloading Registry HKLM\OfflineDefault (Second Attempt)" -ForegroundColor DarkGray Start-Process reg -ArgumentList "unload HKLM\OfflineDefault" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path -Path "HKLM:\OfflineSoftware") { Write-Host "Unloading Registry HKLM\OfflineSoftware (Second Attempt)" -ForegroundColor DarkGray Start-Process reg -ArgumentList "unload HKLM\OfflineSoftware" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path -Path "HKLM:\OfflineSystem") { Write-Host "Unloading Registry HKLM\OfflineSystem (Second Attempt)" -ForegroundColor DarkGray Start-Process reg -ArgumentList "unload HKLM\OfflineSystem" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path -Path "HKLM:\OfflineDefaultUser") { Write-Warning "HKLM:\OfflineDefaultUser could not be dismounted. Open Regedit and unload the Hive manually" Pause } if (Test-Path -Path "HKLM:\OfflineDefault") { Write-Warning "HKLM:\OfflineDefault could not be dismounted. Open Regedit and unload the Hive manually" Pause } if (Test-Path -Path "HKLM:\OfflineSoftware") { Write-Warning "HKLM:\OfflineSoftware could not be dismounted. Open Regedit and unload the Hive manually" Pause } if (Test-Path -Path "HKLM:\OfflineSystem") { Write-Warning "HKLM:\OfflineSystem could not be dismounted. Open Regedit and unload the Hive manually" Pause } } #====================================================================================== } function Invoke-DismCleanupImage { [CmdletBinding()] param ( [switch]$HideCleanupProgress ) #19.10.14 Removed Out-Null. Modified Warning Message #================================================= # Abort #================================================= if ($SkipUpdates) {Return} if ($SkipComponentCleanup) {Return} if ($OSVersion -like "6.1*") {Return} #================================================= # Header #================================================= Show-ActionTime Write-Host -ForegroundColor Green "OS: DISM Cleanup-Image StartComponentCleanup ResetBase" #================================================= # Abort Pending Operations #================================================= if ($OSMajorVersion -eq 10) { if ($(Get-WindowsCapability -Path $MountDirectory | Where-Object {$_.state -eq "*pending*"})) { Write-Warning "Cannot run WindowsImage Cleanup on a WIM with Pending Installations" Return } } #================================================= # CurrentLog #================================================= $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Invoke-DismCleanupImage.log" #================================================= # Execute #================================================= if ($HideCleanupProgress.IsPresent) { Write-Warning "This process will take between 5 - 200 minutes to complete, depending on the number of Updates" Write-Warning "Check Task Manager DISM and DISMHOST processes for activity" Write-Host -ForegroundColor DarkGray " $CurrentLog" Dism /Image:"$MountDirectory" /Cleanup-Image /StartComponentCleanup /ResetBase /LogPath:"$CurrentLog" | Out-Null } else { Write-Verbose "$CurrentLog" Dism /Image:"$MountDirectory" /Cleanup-Image /StartComponentCleanup /ResetBase /LogPath:"$CurrentLog" } #================================================= } function Mount-ImportOSMediaWim { [CmdletBinding()] param () #================================================= # Header #================================================= Show-ActionTime; Write-Host -ForegroundColor Green "Mount Install.wim: $MountDirectory" #================================================= # Execute #================================================= if (!(Test-Path "$MountDirectory")) {New-Item "$MountDirectory" -ItemType Directory -Force | Out-Null} if ($OSMediaGetItem.Extension -eq '.esd') { Write-Host -ForegroundColor Gray " Image: $SourceTempWim" Write-Host -ForegroundColor Gray " Index: 1" Write-Host -ForegroundColor Gray " Mount Directory: $MountDirectory" Mount-WindowsImage -ImagePath $SourceTempWim -Index '1' -Path "$MountDirectory" -ReadOnly | Out-Null } else { Write-Host -ForegroundColor Gray " Image: $SourceImagePath" Write-Host -ForegroundColor Gray " Index: $SourceImageIndex" Write-Host -ForegroundColor Gray " Mount Directory: $MountDirectory" Mount-WindowsImage -ImagePath $SourceImagePath -Index $SourceImageIndex -Path "$MountDirectory" -ReadOnly | Out-Null } } function Mount-InstallwimOS { [CmdletBinding()] param () #================================================= # Header #================================================= Show-ActionTime Write-Host -ForegroundColor Green "OS: Mount to $MountDirectory" #================================================= # Execute #================================================= $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Mount-WindowsImage.log" Write-Verbose "CurrentLog: $CurrentLog" Mount-WindowsImage -ImagePath "$WimTemp\install.wim" -Index 1 -Path "$MountDirectory" -LogPath "$CurrentLog" | Out-Null } function Mount-OSDOfflineRegistryPE { [CmdletBinding()] param ( [Parameter(Mandatory)] [string]$MountPath ) if (($MountPath) -and (Test-Path "$MountPath" -ErrorAction SilentlyContinue)) { if (Test-Path "$MountPath\Windows\ServiceProfiles\LocalService\NTUser.dat") { Write-Verbose "Loading Offline Registry Hive System Profile" Start-Process reg -ArgumentList "load HKLM\OfflineDefaultUser $MountPath\Windows\ServiceProfiles\LocalService\NTUser.dat" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path "$MountPath\Windows\System32\Config\DEFAULT") { Write-Verbose "Loading Offline Registry Hive DEFAULT" Start-Process reg -ArgumentList "load HKLM\OfflineDefault $MountPath\Windows\System32\Config\DEFAULT" -Wait -WindowStyle Hidden -ErrorAction SilentlyContinue } if (Test-Path "$MountPath\Windows\System32\Config\SOFTWARE") { Write-Verbose "Loading Offline Registry Hive SOFTWARE" Start-Process reg -ArgumentList "load HKLM\OfflineSoftware $MountPath\Windows\System32\Config\SOFTWARE" -Wait -WindowStyle Hidden -ErrorAction Stop } if (Test-Path "$MountPath\Windows\System32\Config\SYSTEM") { Write-Verbose "Loading Offline Registry Hive SYSTEM" Start-Process reg -ArgumentList "load HKLM\OfflineSystem $MountPath\Windows\System32\Config\SYSTEM" -Wait -WindowStyle Hidden -ErrorAction Stop } } } function Mount-PEBuild { [CmdletBinding()] param ( [string]$MountDirectory, [string]$WorkingWim ) #================================================= # Header #================================================= Show-ActionTime; Write-Host -ForegroundColor Green "WinPE: Mount WinPE to $MountDirectory" #================================================= # Execute #================================================= $CurrentLog = "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Mount-PEBuild.log" Write-Verbose "CurrentLog: $CurrentLog" Mount-WindowsImage -ImagePath $WorkingWim -Index 1 -Path "$MountDirectory" -LogPath "$CurrentLog" | Out-Null } function Mount-WinPEwim { [CmdletBinding()] param ( [string]$OSMediaPath ) #================================================= # Header #================================================= Show-ActionTime; Write-Host -ForegroundColor Green "WinPE: Mount WinPE.wim to $MountWinPE" #================================================= # Execute #================================================= $CurrentLog = "$OSMediaPath\WinPE\info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Mount-WindowsImage-WinPE.log" Write-Verbose "CurrentLog: $CurrentLog" Mount-WindowsImage -ImagePath "$OSMediaPath\WimTemp\winpe.wim" -Index 1 -Path "$MountWinPE" -LogPath "$CurrentLog" | Out-Null } function Mount-WinREwim { [CmdletBinding()] param ( [string]$OSMediaPath ) #================================================= # Header #================================================= Show-ActionTime; Write-Host -ForegroundColor Green "WinPE: Mount WinRE.wim to $MountWinRE" #================================================= # Execute #================================================= $CurrentLog = "$OSMediaPath\WinPE\info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Mount-WindowsImage-WinRE.log" Write-Verbose "CurrentLog: $CurrentLog" Mount-WindowsImage -ImagePath "$OSMediaPath\WimTemp\winre.wim" -Index 1 -Path "$MountWinRE" -LogPath "$CurrentLog" | Out-Null } function Mount-WinSEwim { [CmdletBinding()] param ( [string]$OSMediaPath ) #================================================= # Header #================================================= Show-ActionTime; Write-Host -ForegroundColor Green "WinPE: Mount WinSE.wim to $MountWinSE" #================================================= # Execute #================================================= $CurrentLog = "$OSMediaPath\WinPE\info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Mount-WindowsImage-WinSE.log" Write-Verbose "CurrentLog: $CurrentLog" Mount-WindowsImage -ImagePath "$OSMediaPath\WimTemp\winse.wim" -Index 1 -Path "$MountWinSE" -LogPath "$CurrentLog" | Out-Null } function New-DirectoriesOSMedia { [CmdletBinding()] param () if (!(Test-Path "$Info")) {New-Item "$Info" -ItemType Directory -Force | Out-Null} if (!(Test-Path "$Info\json")) {New-Item "$Info\json" -ItemType Directory -Force | Out-Null} if (!(Test-Path "$Info\logs")) {New-Item "$Info\logs" -ItemType Directory -Force | Out-Null} if (!(Test-Path "$Info\xml")) {New-Item "$Info\xml" -ItemType Directory -Force | Out-Null} if (!(Test-Path "$OS")) {New-Item "$OS" -ItemType Directory -Force | Out-Null} if (!(Test-Path "$WinPE")) {New-Item "$WinPE" -ItemType Directory -Force | Out-Null} if (!(Test-Path "$PEInfo")) {New-Item "$PEInfo" -ItemType Directory -Force | Out-Null} if (!(Test-Path "$PEInfo\json")) {New-Item "$PEInfo\json" -ItemType Directory -Force | Out-Null} if (!(Test-Path "$PEInfo\logs")) {New-Item "$PEInfo\logs" -ItemType Directory -Force | Out-Null} if (!(Test-Path "$PEInfo\xml")) {New-Item "$PEInfo\xml" -ItemType Directory -Force | Out-Null} if (!(Test-Path "$WimTemp")) {New-Item "$WimTemp" -ItemType Directory -Force | Out-Null} if (!(Test-Path "$MountDirectory")) {New-Item "$MountDirectory" -ItemType Directory -Force | Out-Null} if (!(Test-Path "$MountWinPE")) {New-Item "$MountWinPE" -ItemType Directory -Force | Out-Null} if (!(Test-Path "$MountWinSE")) {New-Item "$MountWinSE" -ItemType Directory -Force | Out-Null} if (!(Test-Path "$MountWinRE")) {New-Item "$MountWinRE" -ItemType Directory -Force | Out-Null} } function New-ItemDirectoryGetOSDBuilderHome { [CmdletBinding()] param () $ItemDirectories = @( $GetOSDBuilderHome $SetOSDBuilderPathContent $SetOSDBuilderPathContentPacks $SetOSDBuilderPathFeatureUpdates $SetOSDBuilderPathOSBuilds $SetOSDBuilderPathOSImport $SetOSDBuilderPathOSMedia $SetOSDBuilderPathPEBuilds $SetOSDBuilderPathTasks $SetOSDBuilderPathTemplates $SetOSDBuilderPathMount $SetOSDBuilderPathUpdates ) foreach ($ItemDirectory in $ItemDirectories) { if (!(Test-Path $ItemDirectory)) {New-Item $ItemDirectory -ItemType Directory -Force | Out-Null} } } function New-ItemDirectorySetOSDBuilderPathContent { [CmdletBinding()] param () $ItemDirectories = @( $SetOSDBuilderPathContent $GetOSDBuilderPathContentADK "$GetOSDBuilderPathContentADK\Windows 10 1903\Windows Preinstallation Environment" #"$GetOSDBuilderPathContentADK\Windows 10 1909\Windows Preinstallation Environment" "$GetOSDBuilderPathContentADK\Windows 10 2004\Windows Preinstallation Environment" #"$GetOSDBuilderPathContentADK\Windows 10 2009\Windows Preinstallation Environment" $GetOSDBuilderPathContentDaRT "$GetOSDBuilderPathContentDaRT\DaRT 10" $GetOSDBuilderPathContentDrivers "$SetOSDBuilderPathContent\ExtraFiles" #"$GetOSDBuilderPathContentIsoExtract" "$GetOSDBuilderPathContentIsoExtract\Windows 10 1903 FOD x64" "$GetOSDBuilderPathContentIsoExtract\Windows 10 1903 Language" #"$GetOSDBuilderPathContentIsoExtract\Windows 10 1909 FOD x64" #"$GetOSDBuilderPathContentIsoExtract\Windows 10 1909 Language" "$GetOSDBuilderPathContentIsoExtract\Windows 10 2004 FOD x64" "$GetOSDBuilderPathContentIsoExtract\Windows 10 2004 Language" #"$GetOSDBuilderPathContentIsoExtract\Windows 10 2009 FOD x64" #"$GetOSDBuilderPathContentIsoExtract\Windows 10 2009 Language" #"$GetOSDBuilderPathContentIsoExtract\Windows 10 1909 Language" "$GetOSDBuilderPathContentIsoExtract\Windows Server 2019 1809 FOD x64" "$GetOSDBuilderPathContentIsoExtract\Windows Server 2019 1809 Language" #"$SetOSDBuilderPathContent\LanguagePacks" $SetOSDBuilderPathMount $GetOSDBuilderPathContentOneDrive $SetOSDBuilderPathUpdates $GetOSDBuilderPathContentPackages #"$GetOSDBuilderPathContentPackages\Win10 x64 1809" #"$SetOSDBuilderPathContent\Provisioning" #"$SetOSDBuilderPathContent\Registry" $GetOSDBuilderPathContentScripts $GetOSDBuilderPathContentStartLayout $GetOSDBuilderPathContentUnattend #"$SetOSDBuilderPathContent\Updates" #"$SetOSDBuilderPathContent\Updates\Custom" #"$SetOSDBuilderPathContent\WinPE" #"$SetOSDBuilderPathContent\WinPE\ADK\Win10 x64 1809" #"$SetOSDBuilderPathContent\WinPE\DaRT\DaRT 10" #"$SetOSDBuilderPathContent\WinPE\Drivers" #"$SetOSDBuilderPathContent\WinPE\Drivers\WinPE 10 x64" #"$SetOSDBuilderPathContent\WinPE\Drivers\WinPE 10 x86" #"$SetOSDBuilderPathContent\WinPE\ExtraFiles" #"$SetOSDBuilderPathContent\WinPE\Scripts" ) foreach ($ItemDirectory in $ItemDirectories) { if (!(Test-Path $ItemDirectory)) {New-Item $ItemDirectory -ItemType Directory -Force | Out-Null} } } function Remove-AppxProvisionedPackageOS { [CmdletBinding()] param () #================================================= # Abort #================================================= if ($ScriptName -ne 'New-OSBuild') {Return} if ($OSMajorVersion -ne 10) {Return} if ([string]::IsNullOrWhiteSpace($RemoveAppx)) {Return} #================================================= # Header #================================================= Show-ActionTime Write-Host -ForegroundColor Green "OS: Remove Appx Packages" #================================================= # Execute #================================================= foreach ($item in $RemoveAppx) { Write-Host -ForegroundColor Cyan " $item" Try { Remove-AppxProvisionedPackage -Path "$MountDirectory" -PackageName $item -LogPath "$Info\logs\$((Get-Date).ToString('yyyy-MM-dd-HHmmss'))-Remove-AppxProvisionedPackage.log" | Out-Null } Catch { $ErrorMessage = $_.Exception.Message Write-Warning "$ErrorMessage" } } } function Remove-WindowsCapabilityOS { [CmdletBinding()] param () #================================================= # Abort #================================================= if ($ScriptName -ne 'New-OSBuild') {Return} if ([string]::IsNullOrWhiteSpace($RemoveCapability)) {Return} #================================================= # Header #================================================= Show-ActionTime
16,670
https://github.com/freesewing/freesewing/blob/master/packages/new-design/prebuild.mjs
Github Open Source
Open Source
MIT
2,023
freesewing
freesewing
JavaScript
Code
67
163
import path from 'path' import fs from 'fs' /* * We don't run this in the linter * because it slows down linting for no good reason */ if (!process.env.LINTER) { // Avoid symlink so Windows users don't complain const copyThese = [ { from: ['..', '..', 'scripts', 'banner.mjs'], to: ['lib', 'banner.mjs'], }, ] for (const cp of copyThese) { fs.copyFile(path.resolve(...cp.from), path.resolve(...cp.to), () => null) } }
2,613
https://github.com/thebergamo/pintora/blob/master/packages/pintora-diagrams/src/er/parser.ts
Github Open Source
Open Source
MIT
2,022
pintora
thebergamo
TypeScript
Code
23
61
import db from './db' import grammar, { setYY } from './parser/erDiagram' import { genParserWithRules } from '../util/parser-util' setYY(db) export const parse = genParserWithRules(grammar)
15,349
https://github.com/carlosalexandre3107/MaskDecimalWithMVVMCross/blob/master/Core/App.cs
Github Open Source
Open Source
MIT
null
MaskDecimalWithMVVMCross
carlosalexandre3107
C#
Code
44
135
using MvvmCross; using MvvmCross.ViewModels; using System; namespace MaskDecimal.Core { [Preserve(AllMembers = true, Conditional = true)] public class App : MvxApplication { public override void Initialize() { try { RegisterAppStart<MaskDecimalViewModel>(); } catch (Exception ex) { Console.WriteLine($"Erro ao inicializar o app \n{ex.StackTrace}"); } } } }
30,845
https://github.com/KqSMea8/rEpo_RP/blob/master/admin/includes/html/box/email_template_form.php
Github Open Source
Open Source
curl
2,019
rEpo_RP
KqSMea8
PHP
Code
464
2,196
<?php require_once($Prefix."classes/configure.class.php"); $objConfigure=new configure(); $ModuleName = "Email Template"; if(!empty($_POST)) { /*******************/ $TemplateContent = $_POST['TemplateContent']; CleanPost(); $_POST['TemplateContent'] = $TemplateContent; /*******************/ $objConfigure->UpdateTemplateContent($_POST); $_SESSION['mess_template'] = EMAIL_TEMPLATE_UPDATED; header("location: emailTemplate.php?cat=".$_GET['cat']); exit; } $arrayCat = $objConfigure->GetTemplateCategory(''); if(empty($_GET['cat'])){ $_GET['cat'] = $arrayCat[0]['CatID']; } if($_GET['cat'] >0){ $arryTemplate = $objConfigure->GetTemplateByCategory($_GET['cat']); $TemplateID=$arryTemplate[0]['TemplateID']; if($TemplateID>0){ $arrayContents = $objConfigure->GetTemplateContent($TemplateID,''); if($arrayContents[0]['Status'] == 1) { $Status = 1; } else { $Status = 0; } } } ?> <script type="text/javascript" src="../FCKeditor/fckeditor.js"></script> <script type="text/javascript" src="../js/ewp50.js"></script> <script type="text/javascript"> var ew_DHTMLEditors = []; </script> <SCRIPT LANGUAGE=JAVASCRIPT> function ChangePage(){ ShowHideLoader('1','S'); var SendUrl = 'emailTemplate.php?cat='+document.getElementById("cat").value; location.href = SendUrl; } function validate(frm) { ShowHideLoader('1','S'); /*if (typeof ew_UpdateTextArea == 'function'){ ew_UpdateTextArea(); } if (!ew_ValidateForm(frm,"PageContent","Page Content")){ return false; }*/ } </SCRIPT> <SCRIPT LANGUAGE=JAVASCRIPT> function validate(frm){ if( ValidateForSimpleBlank(frm.subject, "Subject") //&& ValidateMandRange(frm.TemplateContent, "Template Content ",1,200) ){ ShowHideLoader('1','S'); }else{ return false; } } </SCRIPT> <div class="had"><?=$MainModuleName?> </div> <div class="message" align="center"><? if(!empty($_SESSION['mess_template'])) {echo $_SESSION['mess_template']; unset($_SESSION['mess_template']); }?></div> <? if($_GET['cat'] >0 && $TemplateID>0){ ?> <table width="100%" border="0" cellpadding="0" cellspacing="0" > <form name="form1" action="" method="post" onSubmit="return validate(this);" enctype="multipart/form-data"> <tr> <td align="center" valign="top" > <table width="100%" border="0" cellpadding="5" cellspacing="1" class="borderall"> <tr> <td width="20%" align="right" valign="top" class="blackbold"> Email Template Category :<span class="red">*</span> </td> <td align="left" valign="top"> <select name="cat" id="cat" class="inputbox" onchange="Javascript:ChangePage();" > <? for($i=0;$i<sizeof($arrayCat);$i++) {?> <option value="<?=$arrayCat[$i]['CatID']?>" <? if($arrayCat[$i]['CatID']==$_GET['cat']){echo "selected";}?>> <?=$arrayCat[$i]['Name']?> </option> <? } ?> </select> </td> </tr> <tr> <td width="20%" align="right" valign="top" class="blackbold"> Subject :<span class="red">*</span> </td> <td align="left" valign="top"> <input name="subject" id="subject" value="<?=stripslashes($arrayContents[0]['subject'])?>" type="text" class="textbox" size="80" maxlength="100" /> </td> </tr> <tr> <td></td> <td valign="top"> <? $arr_field = $arrayContents[0]['arr_field']; $column = explode(',', $arr_field); for ($i = 0; $i < sizeof($column); $i++) { echo '<a class="addTag add_link" title="' . strtoupper(preg_replace('/\s+/', '', $column[$i])) . '"> ' . strtoupper($column[$i]) . '</a>'; } ?> </td> </TR> <tr > <td align="right" valign="top" class="blackbold" > Email Template : </td> <td align="left" valign="top"> <textarea name="TemplateContent" id="TemplateContent" ><?=htmlentities(stripslashes($arrayContents[0]['Content']))?></textarea> <script type="text/javascript"> var editorName = 'TemplateContent'; var editor = new ew_DHTMLEditor(editorName); editor.create = function() { var sBasePath = '../FCKeditor/'; var oFCKeditor = new FCKeditor(editorName, '100%', 380, 'custom'); oFCKeditor.BasePath = sBasePath; oFCKeditor.ReplaceTextarea(); this.active = true; } ew_DHTMLEditors[ew_DHTMLEditors.length] = editor; ew_CreateEditor(); // Create DHTML editor(s) $(".addTag").click(function() { var txtToAdd = jQuery(this).attr("title"); var oEditor = FCKeditorAPI.GetInstance('TemplateContent') ; oEditor.InsertHtml("["+txtToAdd+"]"); }); //--> </script> </td> </tr> <tr> <td align="right" valign="top">Note : </td> <td align="left" valign="top"> [SITENAME] and [FOOTER_MESSAGE] are global parameters. </td> </tr> <tr> <td align="right" valign="top" class="blackbold">Status : </td> <td align="left" > <table width="151" border="0" cellpadding="0" cellspacing="0" style="margin:0"> <tr> <td width="20" align="left" valign="middle"><input name="Status" type="radio" value="1" <?= ($Status == 1) ? "checked" : "" ?> /></td> <td width="48" align="left" valign="middle">Active</td> <td width="20" align="left" valign="middle"><input name="Status" type="radio" <?= ($Status == 0) ? "checked" : "" ?> value="0" /></td> <td width="63" align="left" valign="middle">Inactive</td> </tr> </table> </td> </tr> </table></td> </tr> <tr><td align="center"> <br> <input name="Submit" type="submit" class="button" value="Update" /> <input type="hidden" name="TemplateID" id="TemplateID" value="<?=$arrayContents[0]['TemplateID']?>" /> <input type="hidden" name="EmpID" id="EmpID" value="<?=(isset($_GET['EmpID']) ? $_GET['EmpID'] : '');?>" /> </td></tr> </form> </table> <? }else{ echo '<div class=message>'.INVALID_REQUEST.'</div>';} ?>
47,536
https://github.com/tuwiendsg/MELA/blob/master/MELA-Core/MELA-Common/src/main/java/at/ac/tuwien/dsg/mela/common/elasticityAnalysis/concepts/elasticityDependencies/xmlAdapters/ElasticityDependencyStatisticsXMLAdapter.java
Github Open Source
Open Source
Apache-2.0
2,016
MELA
tuwiendsg
Java
Code
114
339
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package at.ac.tuwien.dsg.mela.common.elasticityAnalysis.concepts.elasticityDependencies.xmlAdapters; import java.util.HashMap; import java.util.Map; import javax.xml.bind.annotation.adapters.XmlAdapter; /** * * @author Daniel Moldovan E-Mail: d.moldovan@dsg.tuwien.ac.at */ public class ElasticityDependencyStatisticsXMLAdapter extends XmlAdapter<Statistics, Map<String, Double>> { @Override public Map<String, Double> unmarshal(Statistics in) throws Exception { HashMap<String, Double> hashMap = new HashMap<String, Double>(); for (Statistic entry : in.entries()) { hashMap.put(entry.getStatisticName(), entry.getValue()); } return hashMap; } @Override public Statistics marshal(Map<String, Double> map) throws Exception { Statistics props = new Statistics(); for (Map.Entry<String, Double> entry : map.entrySet()) { props.addEntry(new Statistic(entry.getKey(), entry.getValue())); } return props; } }
9,053
https://github.com/onezens/SmartQQ/blob/master/qqtw/qqheaders7.2/UserSummaryEditViewController.h
Github Open Source
Open Source
MIT
2,018
SmartQQ
onezens
Objective-C
Code
586
3,093
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import "QQViewController.h" #import "LocationSelectViewControllerDelegate.h" #import "QUIActionSheetDelegate.h" #import "SexAgePickerDelegate.h" #import "ThirdEntrySettingProtocol.h" #import "UIGestureRecognizerDelegate.h" #import "UITableViewDataSource.h" #import "UITableViewDelegate.h" #import "UserSummaryAgeConstellationViewControllerDelegate.h" #import "UserSummaryEditProfileCellDelegate.h" #import "UserSummaryIntroductionViewControllerDelegate.h" #import "UserSummarySelectOccupationViewControllerDelegate.h" @class ConditionModel, NSArray, NSMutableArray, NSString, NSTimer, QQCampusModifyRequestModel, QQCampusSchool, QQProfileModel, QZonePhotoWallCacheInfo, RichStateModel, UITableView, UITapGestureRecognizer, UIView, UserSummaryModel, UserSummaryPhotosWallImageModel, UserSummaryPtotosWallManager; @interface UserSummaryEditViewController : QQViewController <UITableViewDelegate, UITableViewDataSource, ThirdEntrySettingProtocol, UIGestureRecognizerDelegate, UserSummaryAgeConstellationViewControllerDelegate, UserSummarySelectOccupationViewControllerDelegate, UserSummaryIntroductionViewControllerDelegate, LocationSelectViewControllerDelegate, SexAgePickerDelegate, UserSummaryEditProfileCellDelegate, QUIActionSheetDelegate> { NSArray *_photosWallDataSource; NSArray *_photosWallImageModelList; UserSummaryPtotosWallManager *_photosWallManager; UserSummaryPhotosWallImageModel *_deleteModel; NSMutableArray *_imageViewsArray; NSTimer *_timer; UIView *_subBoradView; QQProfileModel *_profile; QQProfileModel *_profileEdit; UITapGestureRecognizer *_tableRecognizer; _Bool _sourceBeChange; _Bool _updateRequest; QQProfileModel *_profileBeforeSetting; int _sessionID; NSString *_iconTitle; long long _iconType; long long _curLocationType; long long _selectedSexCode; _Bool _showPickerView; _Bool _showKeyBoard; ConditionModel *_lastHomeTownConditionModel; ConditionModel *_lastLocationConditionModel; _Bool isEditNick; _Bool isEditEmail; NSMutableArray *_dataSources; NSMutableArray *_dataFoots; QZonePhotoWallCacheInfo *_photoWallInfo; unsigned int _getPhotoWallRequestId; RichStateModel *_sigModel; _Bool _goToSecondPage; int _xo; _Bool _needRefreshCampusCircleStatus; _Bool _hasModifiedSchoolInSearchPage; _Bool _isFromCampusCircle; _Bool _isRequest; _Bool _isGetMore; int _personalTagSwitchStatus; RichStateModel *_richSig; UserSummaryModel *_userSummaryModel; UITableView *_tableView; NSString *_textSchool; QQCampusSchool *_campusSchool; NSString *_textGrade; NSString *_textClass; NSString *_textCollege; QQCampusModifyRequestModel *_campusModifyModel; long long _entryType; NSString *_textfieldNick; NSString *_textEmail; NSString *_textCompany; } - (void).cxx_destruct; - (id)GetSexStr:(int)arg1; - (id)accountItemAtIndexPath:(id)arg1; - (void)actionSheet:(id)arg1 clickedButtonAtIndex:(long long)arg2; - (void)alertView:(id)arg1 clickedButtonAtIndex:(long long)arg2; - (void)campusAlertView:(id)arg1 clickedButtonAtIndex:(long long)arg2; @property(retain, nonatomic) QQCampusModifyRequestModel *campusModifyModel; // @synthesize campusModifyModel=_campusModifyModel; @property(retain, nonatomic) QQCampusSchool *campusSchool; // @synthesize campusSchool=_campusSchool; - (_Bool)canGoBack; - (void)cancelButtonClicked:(id)arg1; - (void)changePersonalTagSwitchStatus:(id)arg1; - (void)checkEmpty; - (_Bool)checkShowMaxPhotosWall; @property(retain, nonatomic) NSMutableArray *dataSources; // @synthesize dataSources=_dataSources; - (_Bool)dealFocusState:(id)arg1 item:(id)arg2; - (void)dealloc; - (void)didReceiveMemoryWarning; - (void)doneSettingWithType:(long long)arg1; - (void)endGetMorePhotosWall; - (void)endRequestPhotosWall; @property(nonatomic) long long entryType; // @synthesize entryType=_entryType; - (void)fillinIntroductionCallback:(id)arg1; - (id)findCampusItemWithTitle:(id)arg1; - (void)finishedButtonClicked:(id)arg1; - (_Bool)gestureRecognizer:(id)arg1 shouldReceiveTouch:(id)arg2; - (id)getConditionModel; - (id)getLocationStr:(id)arg1 type:(int)arg2; - (id)getReuseIDCell:(id)arg1; - (id)getVersion; - (void)handleGetEntrySettingNotification:(id)arg1; - (void)handleGetPersonProfileNotification:(id)arg1; - (void)handleSetEntrySettingVisibleNotification:(id)arg1; - (void)handleTimeout:(id)arg1; @property(nonatomic) _Bool hasModifiedSchoolInSearchPage; // @synthesize hasModifiedSchoolInSearchPage=_hasModifiedSchoolInSearchPage; - (void)hideKeyboard; - (void)hideLoadingTips:(id)arg1; - (void)hidePickerView:(id)arg1; - (id)init; - (_Bool)isCertificated; - (_Bool)isEmailAddress:(id)arg1; @property(nonatomic) _Bool isFromCampusCircle; // @synthesize isFromCampusCircle=_isFromCampusCircle; @property(nonatomic) _Bool isGetMore; // @synthesize isGetMore=_isGetMore; @property(nonatomic) _Bool isRequest; // @synthesize isRequest=_isRequest; - (_Bool)isSupportRightDragToGoBack; - (void)keyboardDidShow:(id)arg1; - (void)keyboardWillHide:(id)arg1; - (void)keyboardWillShow:(id)arg1; - (void)leftButtonClick:(id)arg1; - (id)loadCampusAccountItems; - (void)loadData; - (void)loadDataOnMainThread; - (id)loadProfileModel:(long long)arg1; - (void)loadView; @property(nonatomic) _Bool needRefreshCampusCircleStatus; // @synthesize needRefreshCampusCircleStatus=_needRefreshCampusCircleStatus; - (long long)numberOfCampusAccountItem; - (long long)numberOfSectionsInTableView:(id)arg1; - (id)occupationSctionItems; - (void)onGetNewPhotosWallList:(id)arg1; - (void)onSetSchoolNameNotification:(id)arg1; - (void)openAvatarEdit; - (void)openCardRemark; - (void)openDetailInfo; - (void)openLocationSelectVC:(int)arg1; - (void)openPhotosWall; - (void)openSigEdit; - (void)openSwitchOff; @property(nonatomic) int personalTagSwitchStatus; // @synthesize personalTagSwitchStatus=_personalTagSwitchStatus; - (void)postModifyCampusRequest; @property(retain, nonatomic) QQProfileModel *profile; // @synthesize profile=_profile; - (void)queryCampusSchool; - (void)refreshCampusCircleStatusIfNeeded; - (void)registerCampusObservers; - (void)registerNotifications; - (void)removePhotoWallDataSourceForType:(int)arg1; - (id)removeSpaceAndNewline:(id)arg1; - (void)replaceOccupationSectionItems:(id)arg1; - (void)requestCampusCircleStatus; - (void)restoreSexCellNormalState; @property(retain, nonatomic) RichStateModel *richSig; // @synthesize richSig=_richSig; - (void)richStateCallback:(id)arg1; - (id)schoolItem; - (void)scrollToCell:(id)arg1; - (void)selectCampusRow:(long long)arg1 indexPath:(id)arg2; - (void)selectDone; - (void)selectLocationCallback:(id)arg1; - (void)selectOccupationCallback:(id)arg1; - (void)selectSchoolEvent; - (void)setAgeConstellationCallback:(id)arg1; - (void)setBecomeFirstResponder:(id)arg1; - (void)setName:(id)arg1 code:(int)arg2 type:(int)arg3; @property(retain, nonatomic) UITableView *tableView; // @synthesize tableView=_tableView; @property(retain, nonatomic) NSString *textClass; // @synthesize textClass=_textClass; @property(retain, nonatomic) NSString *textCollege; // @synthesize textCollege=_textCollege; @property(retain, nonatomic) NSString *textCompany; // @synthesize textCompany=_textCompany; @property(retain, nonatomic) NSString *textEmail; // @synthesize textEmail=_textEmail; @property(retain, nonatomic) NSString *textGrade; // @synthesize textGrade=_textGrade; @property(retain, nonatomic) NSString *textSchool; // @synthesize textSchool=_textSchool; @property(retain, nonatomic) NSString *textfieldNick; // @synthesize textfieldNick=_textfieldNick; @property(retain, nonatomic) UserSummaryModel *userSummaryModel; // @synthesize userSummaryModel=_userSummaryModel; - (_Bool)shouldPromptToCertification; - (_Bool)shouldQueryCampusSchool; - (_Bool)shouldShowCampusAccountItems; - (void)showCertificatingWebView; - (void)showClassPickerView:(id)arg1; - (void)showCollegePickerView:(id)arg1; - (void)showGradePickerView:(id)arg1; - (void)showModifyOrCertificatingActionSheet; - (void)showModifySchoolWebView; - (void)showPickerView:(id)arg1 atIndexPath:(id)arg2; - (void)sortPhotoWallDataSoucre; - (void)startRequestPhotosWall; - (void)syncSaveProfileModel:(id)arg1; - (id)tableView:(id)arg1 cellForRowAtIndexPath:(id)arg2; - (void)tableView:(id)arg1 didSelectRowAtIndexPath:(id)arg2; - (double)tableView:(id)arg1 heightForFooterInSection:(long long)arg2; - (double)tableView:(id)arg1 heightForHeaderInSection:(long long)arg2; - (double)tableView:(id)arg1 heightForRowAtIndexPath:(id)arg2; - (long long)tableView:(id)arg1 numberOfRowsInSection:(long long)arg2; - (id)tableView:(id)arg1 viewForFooterInSection:(long long)arg2; - (void)textfieldInCellCallback:(id)arg1 indexPath:(id)arg2 state:(long long)arg3; - (void)updatePhotosWall:(id)arg1; - (void)viewDidAppear:(_Bool)arg1; - (void)viewDidLoad; - (void)viewWillAppear:(_Bool)arg1; - (void)viewWillDisappear:(_Bool)arg1; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end
24,945
https://github.com/turisap/nebula.gl/blob/master/modules/edit-modes/src/lib/draw-point-mode.ts
Github Open Source
Open Source
MIT
2,022
nebula.gl
turisap
TypeScript
Code
95
317
import { ClickEvent, PointerMoveEvent, ModeProps, TentativeFeature } from '../types'; import { FeatureCollection } from '../geojson-types'; import { GeoJsonEditMode } from './geojson-edit-mode'; export class DrawPointMode extends GeoJsonEditMode { createTentativeFeature(props: ModeProps<FeatureCollection>): TentativeFeature { const { lastPointerMoveEvent } = props; const lastCoords = lastPointerMoveEvent ? [lastPointerMoveEvent.mapCoords] : []; return { type: 'Feature', properties: { guideType: 'tentative', }, geometry: { type: 'Point', coordinates: lastCoords[0], }, }; } handleClick({ mapCoords }: ClickEvent, props: ModeProps<FeatureCollection>): void { const geometry = { type: 'Point', coordinates: mapCoords, }; // @ts-ignore props.onEdit(this.getAddFeatureAction(geometry, props.data)); } handlePointerMove(event: PointerMoveEvent, props: ModeProps<FeatureCollection>) { props.onUpdateCursor('cell'); super.handlePointerMove(event, props); } }
29,921
https://github.com/JonathanWilbur/x500-ts/blob/master/source/modules/DirectoryAbstractService/JoinAttPair.ta.ts
Github Open Source
Open Source
MIT
2,019
x500-ts
JonathanWilbur
TypeScript
Code
747
2,509
/* eslint-disable */ import { ASN1Element as _Element, ASN1TagClass as _TagClass, OPTIONAL, } from "asn1-ts"; import * as $ from "asn1-ts/dist/node/functional"; import { JoinContextType, _decode_JoinContextType, _encode_JoinContextType, } from "../DirectoryAbstractService/JoinContextType.ta"; import { AttributeType, _decode_AttributeType, _encode_AttributeType, } from "../InformationFramework/AttributeType.ta"; export { JoinContextType, _decode_JoinContextType, _encode_JoinContextType, } from "../DirectoryAbstractService/JoinContextType.ta"; export { AttributeType, _decode_AttributeType, _encode_AttributeType, } from "../InformationFramework/AttributeType.ta"; /* START_OF_SYMBOL_DEFINITION JoinAttPair */ /** * @summary JoinAttPair * @description * * ### ASN.1 Definition: * * ```asn1 * JoinAttPair ::= SEQUENCE { * baseAtt AttributeType, * joinAtt AttributeType, * joinContext SEQUENCE SIZE (1..MAX) OF JoinContextType OPTIONAL, * ... } * ``` * * @class */ export class JoinAttPair { constructor( /** * @summary `baseAtt`. * @public * @readonly */ readonly baseAtt: AttributeType, /** * @summary `joinAtt`. * @public * @readonly */ readonly joinAtt: AttributeType, /** * @summary `joinContext`. * @public * @readonly */ readonly joinContext: OPTIONAL<JoinContextType[]>, /** * @summary Extensions that are not recognized. * @public * @readonly */ readonly _unrecognizedExtensionsList: _Element[] = [] ) {} /** * @summary Restructures an object into a JoinAttPair * @description * * This takes an `object` and converts it to a `JoinAttPair`. * * @public * @static * @method * @param {Object} _o An object having all of the keys and values of a `JoinAttPair`. * @returns {JoinAttPair} */ public static _from_object( _o: { [_K in keyof JoinAttPair]: JoinAttPair[_K] } ): JoinAttPair { return new JoinAttPair( _o.baseAtt, _o.joinAtt, _o.joinContext, _o._unrecognizedExtensionsList ); } } /* END_OF_SYMBOL_DEFINITION JoinAttPair */ /* START_OF_SYMBOL_DEFINITION _root_component_type_list_1_spec_for_JoinAttPair */ /** * @summary The Leading Root Component Types of JoinAttPair * @description * * This is an array of `ComponentSpec`s that define how to decode the leading root component type list of a SET or SEQUENCE. * * @constant */ export const _root_component_type_list_1_spec_for_JoinAttPair: $.ComponentSpec[] = [ new $.ComponentSpec( "baseAtt", false, $.hasTag(_TagClass.universal, 6), undefined, undefined ), new $.ComponentSpec( "joinAtt", false, $.hasTag(_TagClass.universal, 6), undefined, undefined ), new $.ComponentSpec( "joinContext", true, $.hasTag(_TagClass.universal, 16), undefined, undefined ), ]; /* END_OF_SYMBOL_DEFINITION _root_component_type_list_1_spec_for_JoinAttPair */ /* START_OF_SYMBOL_DEFINITION _root_component_type_list_2_spec_for_JoinAttPair */ /** * @summary The Trailing Root Component Types of JoinAttPair * @description * * This is an array of `ComponentSpec`s that define how to decode the trailing root component type list of a SET or SEQUENCE. * * @constant */ export const _root_component_type_list_2_spec_for_JoinAttPair: $.ComponentSpec[] = []; /* END_OF_SYMBOL_DEFINITION _root_component_type_list_2_spec_for_JoinAttPair */ /* START_OF_SYMBOL_DEFINITION _extension_additions_list_spec_for_JoinAttPair */ /** * @summary The Extension Addition Component Types of JoinAttPair * @description * * This is an array of `ComponentSpec`s that define how to decode the extension addition component type list of a SET or SEQUENCE. * * @constant */ export const _extension_additions_list_spec_for_JoinAttPair: $.ComponentSpec[] = []; /* END_OF_SYMBOL_DEFINITION _extension_additions_list_spec_for_JoinAttPair */ /* START_OF_SYMBOL_DEFINITION _cached_decoder_for_JoinAttPair */ let _cached_decoder_for_JoinAttPair: $.ASN1Decoder<JoinAttPair> | null = null; /* END_OF_SYMBOL_DEFINITION _cached_decoder_for_JoinAttPair */ /* START_OF_SYMBOL_DEFINITION _decode_JoinAttPair */ /** * @summary Decodes an ASN.1 element into a(n) JoinAttPair * @function * @param {_Element} el The element being decoded. * @returns {JoinAttPair} The decoded data structure. */ export function _decode_JoinAttPair(el: _Element) { if (!_cached_decoder_for_JoinAttPair) { _cached_decoder_for_JoinAttPair = function (el: _Element): JoinAttPair { /* START_OF_SEQUENCE_COMPONENT_DECLARATIONS */ let baseAtt!: AttributeType; let joinAtt!: AttributeType; let joinContext: OPTIONAL<JoinContextType[]>; let _unrecognizedExtensionsList: _Element[] = []; /* END_OF_SEQUENCE_COMPONENT_DECLARATIONS */ /* START_OF_CALLBACKS_MAP */ const callbacks: $.DecodingMap = { baseAtt: (_el: _Element): void => { baseAtt = _decode_AttributeType(_el); }, joinAtt: (_el: _Element): void => { joinAtt = _decode_AttributeType(_el); }, joinContext: (_el: _Element): void => { joinContext = $._decodeSequenceOf<JoinContextType>( () => _decode_JoinContextType )(_el); }, }; /* END_OF_CALLBACKS_MAP */ $._parse_sequence( el, callbacks, _root_component_type_list_1_spec_for_JoinAttPair, _extension_additions_list_spec_for_JoinAttPair, _root_component_type_list_2_spec_for_JoinAttPair, (ext: _Element): void => { _unrecognizedExtensionsList.push(ext); } ); return new JoinAttPair( /* SEQUENCE_CONSTRUCTOR_CALL */ baseAtt, joinAtt, joinContext, _unrecognizedExtensionsList ); }; } return _cached_decoder_for_JoinAttPair(el); } /* END_OF_SYMBOL_DEFINITION _decode_JoinAttPair */ /* START_OF_SYMBOL_DEFINITION _cached_encoder_for_JoinAttPair */ let _cached_encoder_for_JoinAttPair: $.ASN1Encoder<JoinAttPair> | null = null; /* END_OF_SYMBOL_DEFINITION _cached_encoder_for_JoinAttPair */ /* START_OF_SYMBOL_DEFINITION _encode_JoinAttPair */ /** * @summary Encodes a(n) JoinAttPair into an ASN.1 Element. * @function * @param {value} el The element being decoded. * @param elGetter A function that can be used to get new ASN.1 elements. * @returns {_Element} The JoinAttPair, encoded as an ASN.1 Element. */ export function _encode_JoinAttPair( value: JoinAttPair, elGetter: $.ASN1Encoder<JoinAttPair> ) { if (!_cached_encoder_for_JoinAttPair) { _cached_encoder_for_JoinAttPair = function ( value: JoinAttPair, elGetter: $.ASN1Encoder<JoinAttPair> ): _Element { return $._encodeSequence( ([] as (_Element | undefined)[]) .concat( [ /* REQUIRED */ _encode_AttributeType( value.baseAtt, $.BER ), /* REQUIRED */ _encode_AttributeType( value.joinAtt, $.BER ), /* IF_ABSENT */ value.joinContext === undefined ? undefined : $._encodeSequenceOf<JoinContextType>( () => _encode_JoinContextType, $.BER )(value.joinContext, $.BER), ], value._unrecognizedExtensionsList ? value._unrecognizedExtensionsList : [] ) .filter((c: _Element | undefined): c is _Element => !!c), $.BER ); }; } return _cached_encoder_for_JoinAttPair(value, elGetter); } /* END_OF_SYMBOL_DEFINITION _encode_JoinAttPair */ /* eslint-enable */
35,436
https://github.com/AndrewDongminYoo/cucumber.com/blob/master/target/snippets/nearArticle/http-request.adoc
Github Open Source
Open Source
Apache-2.0
2,022
cucumber.com
AndrewDongminYoo
AsciiDoc
Code
10
53
[source,http,options="nowrap"] ---- GET /api/articles/37.501086/127.0365988 HTTP/1.1 Accept: application/json Host: localhost:8080 ----
31,549
https://github.com/isabella232/federalist-infra/blob/master/terraform/dev/backend.tf
Github Open Source
Open Source
CC0-1.0, LicenseRef-scancode-public-domain
2,021
federalist-infra
isabella232
HCL
Code
40
136
module "backend" { source = "../modules/backend" bucket = "federalist-commercial-terraform-state" table = "federalist-terraform-locks" } # The backend configuration does not accept variables... terraform { backend "s3" { bucket = "federalist-commercial-terraform-state" key = "dev/terraform.tfstate" dynamodb_table = "federalist-terraform-locks" encrypt = true } }
22,652
https://github.com/jackoalan/bullet3/blob/master/Demos3/CpuDemos/rendering/RenderDemo.cpp
Github Open Source
Open Source
Zlib
2,020
bullet3
jackoalan
C++
Code
83
545
#include "RenderDemo.h" #include "OpenGLWindow/GLInstancingRenderer.h" #include "OpenGLWindow/ShapeData.h" #include "Bullet3Common/b3Quaternion.h" static b3Vector4 colors[4] = { b3MakeVector4(1,0,0,1), b3MakeVector4(0,1,0,1), b3MakeVector4(0,1,1,1), b3MakeVector4(1,1,0,1), }; void RenderDemo::initPhysics(const ConstructionInfo& ci) { m_instancingRenderer = ci.m_instancingRenderer; m_instancingRenderer ->setCameraDistance(10); float target[4]={0,0,0,0}; m_instancingRenderer->setCameraTargetPosition(target); int strideInBytes = 9*sizeof(float); int numVertices = sizeof(cube_vertices)/strideInBytes; int numIndices = sizeof(cube_indices)/sizeof(int); int shapeId = ci.m_instancingRenderer->registerShape(&cube_vertices[0],numVertices,cube_indices,numIndices); b3Vector3 position = b3MakeVector3(0,0,0);//((j+1)&1)+i*2.2,1+j*2.,((j+1)&1)+k*2.2); b3Quaternion orn(0,0,0,1); static int curColor=0; b3Vector4 color = colors[curColor]; curColor++; curColor&=3; b3Vector4 scaling=b3MakeVector4(1,1,1,1); int id = ci.m_instancingRenderer->registerGraphicsInstance(shapeId,position,orn,color,scaling); ci.m_instancingRenderer->writeTransforms(); } void RenderDemo::exitPhysics() { } void RenderDemo::renderScene() { m_instancingRenderer->renderScene(); } void RenderDemo::clientMoveAndDisplay() { }
35,632
https://github.com/asepmulyadi011/SistemRumahSakit/blob/master/application/views/rsvberanda.php
Github Open Source
Open Source
MIT
null
SistemRumahSakit
asepmulyadi011
PHP
Code
147
801
<head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>RSMH 2016</title> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"> <meta name="description" content=""> <meta name="author" content=""> <link rel="stylesheet" href="<?php echo base_url('asset/bootstrap/css/bootstrap.min.css'); ?>"> <link rel="stylesheet" href="<?php echo base_url('asset/bootstrap/css/AdminLTE.min.css'); ?>"> <link rel="stylesheet" href="<?php echo base_url('asset/bootstrap/font-awesome/css/font-awesome.min.css'); ?>"> <link rel="stylesheet" href="<?php echo base_url('asset/bootstrap/css/skins/_all-skins.min.css'); ?>"> <link rel="stylesheet" href="<?php echo base_url('asset/bootstrap/css/styles.css'); ?>"> <script src="<?php echo base_url('asset/bootstrap/js/jQuery-2.1.4.min.js'); ?>"></script> <script src="<?php echo base_url('asset/bootstrap/js/bootstrap.min.js'); ?>"></script> <script src="<?php echo base_url('asset/bootstrap/js/app.min.js'); ?>"></script> </head> <header class="main-header"> <a href="#" class="logo"> <span class="logo-mini">RS</span> <span class="logo-lg">RSMH</span> </a> <nav class="navbar navbar-static-top" role="navigation"> </nav> </header> <body class="skin-blue"> <div class="wrapper"> <div class="container-fluid"> <div class="row"> <div class="col-md-6 col-md-offset-3"><hr/> <div class="form-group"> <a href="<?php echo site_url('irj/rjcregistrasi');?>" class="btn btn-default btn-lg btn-block">Instalasi Rawat Jalan</a></div> <div class="form-group"> <a href="<?php echo site_url('irj/rjcregistrasi');?>" class="btn btn-primary btn-lg btn-block">Instalasi Rawat Inap</a></div> <div class="form-group"> <a href="<?php echo site_url('irj/rjcregistrasi');?>" class="btn btn-default btn-lg btn-block">Instalasi Rawat Darurat</a></div> <div class="form-group"> <a href="<?php echo site_url('irj/rjcregistrasi');?>" class="btn btn-primary btn-lg btn-block">Laboratorium dan Radiologi</a></div><hr/> </div> </div> </div> </div> </div> </body>
48,894
https://github.com/fleskesvor/melosys-kodeverk/blob/master/src/behandlinger/behandlingstyper.js
Github Open Source
Open Source
MIT
null
melosys-kodeverk
fleskesvor
JavaScript
Code
53
200
/** * Kodeverk/behandlingstyper * @module */ const behandlingstyper = [ { kode: 'SOEKNAD', term: 'Søknad' }, { kode: 'SED', term: 'SED' }, { kode: 'NY_VURDERING', term: 'Ny vurdering' }, { kode: 'KLAGE', term: 'Klage' }, { kode: 'ANKE', term: 'Anke' }, { kode: 'ENDRET_PERIODE', term: 'Behandle forkortet periode' } ]; module.exports.behandlingstyper = behandlingstyper;
4,989
https://github.com/muhdfaiz/laravel-sql-lens/blob/master/packages/renderer/assets/scss/app.scss
Github Open Source
Open Source
MIT
null
laravel-sql-lens
muhdfaiz
SCSS
Code
111
538
@import "@fontsource/poppins/100.css"; @import "@fontsource/poppins/200.css"; @import "@fontsource/poppins/300.css"; @import "@fontsource/poppins/400.css"; @import "@fontsource/poppins/500.css"; @import "@fontsource/poppins/600.css"; @import "@fontsource/poppins/700.css"; @import "@fontsource/poppins/800.css"; @import "@fontsource/poppins/900.css"; @import 'primeflex/src/_variables'; @import 'primeflex/src/_grid'; @import 'primeflex/src/_formlayout'; @import 'primeflex/src/_display'; @import 'primeflex/src/_text'; @import 'primeflex/src/flexbox/_flexbox'; @import 'primeflex/src/_spacing'; @import 'primeflex/src/_elevation'; @import "./mixins/keyframe"; @import "./utility/table"; @import "./utility/size"; @import "./utility/primevue"; @import "./utility/font"; @import "./page/server_setting"; @import "./page/listening_sql_query"; html { font-size: 14px; } body { background: #2a323d !important; color: #E2E3E4 !important; font-family: "Poppins", Helvetica Neue Light, sans-serif !important; font-size: 1rem; height: calc(100vh - 0.8rem); position: relative; #app { height: 100%; } .logo-text { width: 25vw; } .dialog-overlay { display: block !important; position: fixed; top: 0; left: 0; overflow: auto; opacity: 0.9; background: #3b434e; z-index: 1000; width: 100%; height: 100%; } }
273
https://github.com/SCWells72/sirono-common/blob/master/force-app/main/default/classes/TriggerHandler.cls
Github Open Source
Open Source
Apache-2.0
2,023
sirono-common
SCWells72
Apex
Code
222
405
/* * Copyright 2017-present Sirono LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Common interface for trigger handlers. Trigger handlers are created by the trigger handler dispatcher using trigger * handler factories in response to DML events. The trigger handler dispatcher is then responsible for determining the * correct method to invoke based on the trigger context. * * @see Trigger * @see TriggerHandlerFactory * @see TriggerHandlerDispatcher */ public interface TriggerHandler { /** * Called before inserting SObjects. */ void beforeInsert(); /** * Called after inserting SObjects. */ void afterInsert(); /** * Called before updating SObjects. */ void beforeUpdate(); /** * Called after updating SObjects. */ void afterUpdate(); /** * Called before deleting SObjects. */ void beforeDelete(); /** * Called after deleting SObjects. */ void afterDelete(); /** * Called after restoring SObjects. */ void afterUndelete(); }
37,476
https://github.com/jatinrajani/Sorting/blob/master/quicksort.cpp
Github Open Source
Open Source
MIT
2,017
Sorting
jatinrajani
C++
Code
60
322
#include<iostream> using namespace std; int Partioning(int *a,int start,int end){ int pivot=a[end]; int pindex=start; for(int i=start;i<end;i++) if(a[i]<=pivot){ int temp=a[pindex]; a[pindex]=a[i]; a[i]=temp; pindex=pindex+1; } int temp1; temp1=a[pindex]; a[pindex]=a[end]; a[end]=temp1; return pindex; } void QuickSort(int *a,int start,int end){ if(start<end){ int pindex; pindex=Partioning(a,start,end); QuickSort(a,start,pindex-1); QuickSort(a,pindex+1,end); } } void printlist(int *a,int size){ for(int i=0;i<size;i++){ cout<<a[i]<<" "; } } int main(){ int a[]={7,2,3,4,5}; QuickSort(a,0,4); printlist(a,5); }
23,888
https://github.com/caiorss/xlw-cmake-fork/blob/master/examples/sample-project/mylib.h
Github Open Source
Open Source
BSD-3-Clause
2,020
xlw-cmake-fork
caiorss
C
Code
18
72
#ifndef _mylib_h_ #define _mylib_h_ #include <xlw/xlw.h> //<xlw:libraryname=MyLibrary double //Square root of an argument MySqrt(double x //argument ); #endif
38,036
https://github.com/venicegeo/vzutil-versioning/blob/master/web/app/retriever.go
Github Open Source
Open Source
Apache-2.0
2,018
vzutil-versioning
venicegeo
Go
Code
1,058
3,434
// Copyright 2018, RadiantBlue Technologies, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package app import ( "encoding/json" "strings" "sync" "github.com/venicegeo/pz-gocommon/elasticsearch" nt "github.com/venicegeo/pz-gocommon/gocommon" "github.com/venicegeo/vzutil-versioning/web/es" "github.com/venicegeo/vzutil-versioning/web/es/types" u "github.com/venicegeo/vzutil-versioning/web/util" ) type Retriever struct { app *Application } type Project struct { index elasticsearch.IIndex *types.Project } type Repository struct { index elasticsearch.IIndex project *Project *types.Repository } func NewRetriever(app *Application) *Retriever { return &Retriever{app} } //Test: TestGetScans func (p *Project) ScanBySha(sha string) (*types.Scan, bool, error) { var entry = new(types.Scan) var err error // var found bool result, err := p.index.GetByID(RepositoryEntryType, sha+"-"+p.Id) if result == nil { return nil, false, err } else if !result.Found { return nil, false, nil } return entry, true, json.Unmarshal(*result.Source, entry) } func (r *Retriever) ScanByShaNameGen(repo *Repository, sha string) (*types.Scan, error) { scan, found, err := repo.project.ScanBySha(sha) if err != nil || !found { { code, _, _, err := nt.HTTP(nt.HEAD, u.Format("https://github.com/%s/commit/%s", repo.Fullname, sha), nt.NewHeaderBuilder().GetHeader(), nil) if err != nil { return nil, u.Error("Could not verify this sha: %s", err.Error()) } if code != 200 { return nil, u.Error("Could not verify this sha, head code: %d", code) } } exists := make(chan *types.Scan, 1) ret := make(chan *types.Scan, 1) r.app.wrkr.AddTask(&SingleRunnerRequest{ repository: repo, sha: sha, ref: "", }, exists, ret) if <-exists == nil { scan = <-ret if scan == nil { return nil, u.Error("There was an error while running this") } } else { return nil, u.Error("Retriever said not found, worker said found") } } return scan, nil } func (project *Project) ScansByRefInProject(ref string) (map[string]*types.Scan, error) { repos, err := project.GetAllRepositories() if err != nil { return nil, err } res := map[string]*types.Scan{} query := map[string]interface{}{"query": map[string]interface{}{}} query["query"] = map[string]interface{}{"bool": es.NewBool(). SetMust( es.NewBoolQ( es.NewTerm(types.Scan_RefsField, "refs/"+ref), es.NewTerm(types.Scan_FullnameField, "%s")))} query["sort"] = map[string]interface{}{ types.Scan_TimestampField: map[string]interface{}{ "order": "desc", }, } query["size"] = 1 dat, err := json.MarshalIndent(query, " ", " ") if err != nil { return nil, err } wg := sync.WaitGroup{} wg.Add(len(repos)) mux := sync.Mutex{} addError := func(repoName, err string) { mux.Lock() res[repoName] = &types.Scan{RepoFullname: repoName, ProjectId: project.Id, Sha: err} wg.Done() mux.Unlock() } work := func(repoName string) { q := u.Format(string(dat), repoName) var i map[string]interface{} json.Unmarshal([]byte(q), &i) resp, err := project.index.SearchByJSON(RepositoryEntryType, i) if err != nil { addError(repoName, u.Format("Error during query: %s", err.Error())) return } if resp.Hits.TotalHits == 0 { wg.Done() return } var entry = new(types.Scan) if err = json.Unmarshal(*resp.Hits.Hits[0].Source, entry); err != nil { addError(repoName, "Couldnt get entry: "+err.Error()) return } mux.Lock() res[repoName] = entry wg.Done() mux.Unlock() } for _, repo := range repos { go work(repo.Fullname) } wg.Wait() return res, nil } // Returns map of refs to shas of a repository in a project func (r *Repository) MapRefToShas() (map[string][]string, int64, error) { boool := es.NewBool(). SetMust(es.NewBoolQ( es.NewTerm(types.Scan_FullnameField, r.Fullname), es.NewTerm(types.Scan_ProjectIdField, r.ProjectId))) entryDat, err := es.GetAll(r.index, RepositoryEntryType, map[string]interface{}{"bool": boool}, map[string]interface{}{types.Scan_TimestampField: "desc"}) if err != nil { return nil, 0, err } res := map[string][]string{} for _, entryD := range entryDat.Hits { entry := new(types.Scan) if err := json.Unmarshal(*entryD.Source, entry); err != nil { return nil, 0, err } for _, refName := range entry.Refs { if _, ok := res[refName]; !ok { res[refName] = []string{} } res[refName] = append(res[refName], entry.Sha) } } return res, entryDat.TotalHits, nil } //Test: TestGetRepositories func (r *Repository) GetAllRefs() ([]string, error) { in := es.NewAggQuery("refs", types.Scan_RefsField) boool := es.NewBool().SetMust(es.NewBoolQ(es.NewTerm(types.Scan_FullnameField, r.Fullname), es.NewTerm(types.Scan_ProjectIdField, r.project.Id))) in["query"] = map[string]interface{}{"bool": boool} // sort.Strings(res) resp, err := r.index.SearchByJSON(RepositoryEntryType, in) return es.GetAggKeysFromSearchResponse("refs", resp, err, func(a string) string { return strings.TrimPrefix(a, "refs/") }) } //Test: TestGetRepositories func (p *Project) GetAllRefs() ([]string, error) { repos, err := p.GetAllRepositories() if err != nil { return nil, err } reposStr := make([]string, len(repos), len(repos)) for i, repo := range repos { reposStr[i] = repo.Fullname } boool := es.NewBool().SetMust(es.NewBoolQ(es.NewTerms(types.Scan_FullnameField, reposStr...))) query := es.NewAggQuery("refs", types.Scan_RefsField) query["query"] = map[string]interface{}{"bool": boool} resp, err := p.index.SearchByJSON(RepositoryEntryType, query) return es.GetAggKeysFromSearchResponse("refs", resp, err, func(a string) string { return strings.TrimPrefix(a, "refs/") }) } //Test: TestGetRepositories func (r *Retriever) ListRepositories() ([]string, error) { agg := es.NewAggQuery("repo", types.Scan_FullnameField) resp, err := r.app.index.SearchByJSON(RepositoryEntryType, agg) return es.GetAggKeysFromSearchResponse("repo", resp, err) } //Test: TestAddRepositories func (p *Project) GetAllRepositories() ([]*Repository, error) { hits, err := es.GetAll(p.index, RepositoryType, es.NewTerm(types.Repository_ProjectIdField, p.Id)) if err != nil { return nil, err } res := make([]*Repository, hits.TotalHits, hits.TotalHits) for i, hitData := range hits.Hits { r := new(types.Repository) if err = json.Unmarshal(*hitData.Source, r); err != nil { return nil, err } res[i] = &Repository{p.index, p, r} } return res, nil } //Test: TestGetRepositories func (p *Project) GetRepository(repository string) (*Repository, error) { boolq := es.NewBool(). SetMust(es.NewBoolQ( es.NewTerm(types.Repository_ProjectIdField, p.Id), es.NewTerm(types.Repository_NameField, repository))) resp, err := p.index.SearchByJSON(RepositoryType, map[string]interface{}{ "query": map[string]interface{}{"bool": boolq}, }) if err != nil { return nil, err } if len(resp.Hits.Hits) != 1 { return nil, u.Error("Total hits not 1 but %d", len(resp.Hits.Hits)) } res := new(Repository) if err = json.Unmarshal(*resp.Hits.Hits[0].Source, res); err != nil { return nil, err } res.project = p res.index = p.index return res, nil } //Test: TestAddRepositories func (r *Retriever) GetRepository(repository, projectId string) (*Repository, *Project, error) { proj, err := r.GetProjectById(projectId) if err != nil { return nil, nil, err } repo, err := proj.GetRepository(repository) return repo, proj, err } //Test: TestAddProjects func (r *Retriever) GetProjectById(id string) (*Project, error) { resp, err := r.app.index.GetByID(ProjectType, id) if err != nil { return nil, err } else if !resp.Found { return nil, u.Error("Project %s does not exist", err.Error()) } p := new(types.Project) if err = json.Unmarshal(*resp.Source, p); err != nil { return nil, err } return &Project{r.app.index, p}, nil } //Test: TestAddProjects func (r *Retriever) GetAllProjects() ([]*Project, error) { hits, err := es.GetAll(r.app.index, ProjectType, map[string]interface{}{}) if err != nil { return nil, err } res := make([]*Project, hits.TotalHits, hits.TotalHits) for i, hitData := range hits.Hits { t := new(types.Project) if err = json.Unmarshal(*hitData.Source, t); err != nil { return nil, err } res[i] = &Project{r.app.index, t} } return res, nil } //Test: TestAddRepositories func (r *Retriever) GetAllProjectNamesUsingRepository(repo string) ([]string, error) { agg := es.NewAggQuery("projects", types.Repository_ProjectIdField) agg["query"] = es.NewTerm("repo", repo) resp, err := r.app.index.SearchByJSON(RepositoryType, agg) return es.GetAggKeysFromSearchResponse("projects", resp, err) }
5,714
https://github.com/b3nsn0w/artgen2/blob/master/webpack.config.js
Github Open Source
Open Source
WTFPL
null
artgen2
b3nsn0w
JavaScript
Code
94
367
const CleanWebpackPlugin = require('clean-webpack-plugin') const CopyWebpackPlugin = require('copy-webpack-plugin') const HTMLWebpackPlugin = require('html-webpack-plugin') const path = require('path') const process = require('process') const packageJson = require('./package.json') const outputPath = path.resolve(__dirname, process.env.OUTPUT_PATH || 'dist') module.exports = { entry: [ 'babel-polyfill', path.resolve(__dirname, packageJson.main) ], output: { filename: 'artgen.js', path: outputPath }, module: { rules: [ { test: /\.js$/, use: 'babel-loader' }, { test: /\.styl$/, use: [ 'style-loader', 'css-loader', 'stylus-loader' ] }, { test: /\.(png|woff|woff2|eot|ttf|svg)$/, use: 'url-loader?limit=10000' } ] }, plugins: [ new CleanWebpackPlugin(outputPath), new HTMLWebpackPlugin({ template: path.resolve(__dirname, 'src/index.html') }), new CopyWebpackPlugin([{ from: 'src/assets', to: 'assets' }]) ] }
46,332
https://github.com/CommunityHiQ/Frends.Community.Odbc/blob/master/Frends.Community.Odbc.Tests/Frends.Community.Odbc.Tests.cs
Github Open Source
Open Source
MIT
2,020
Frends.Community.Odbc
CommunityHiQ
C#
Code
136
405
using NUnit.Framework; using System.Threading; namespace Frends.Community.Odbc.Tests { [TestFixture] class TestClass { [Test] public void ShouldReadFromMsAccessViaOdbc() { // Configure first ODBC at Control Panel->Administrative Tools->ODBC Data sources (64-bit) to point to \TestFiles\ODBC_testDB.accdb, and ensure that the data source name equals ODBC_testDB var conn = new ConnectionInformation { ConnectionString = "DSN=ODBC_testDB", TimeoutSeconds = 30 }; var odbcQuery = new QueryParameters { Query = "SELECT Animal FROM AnimalTypes WHERE Animal = ? OR Animal = ?", ParametersInOrder = new[] { new QueryParameter { Value = "Bear" }, new QueryParameter { Value = "Moose" } }, }; var output = new OutputProperties { ReturnType = QueryReturnType.Xml, XmlOutput = new XmlOutputProperties { RootElementName = "ROW", RowElementName = "ROWSET", } }; var resultTask = OdbcTask.Query(odbcQuery, output, conn, new CancellationToken()); resultTask.Wait(); var result = resultTask.Result.Result; Assert.NotNull(result); Assert.That(result, Contains.Substring("<Animal>Bear</Animal>")); Assert.That(result, Contains.Substring("<Animal>Moose</Animal>")); } } }
16,168
https://github.com/fredj/mf-chsdi3/blob/master/chsdi/models/vector/bak.py
Github Open Source
Open Source
BSD-3-Clause
null
mf-chsdi3
fredj
Python
Code
193
861
# -*- coding: utf-8 -*- from sqlalchemy import Column, Integer from sqlalchemy.types import Numeric, Unicode from chsdi.models import register, bases from chsdi.models.vector import Vector, Geometry2D Base = bases['bak'] class Isos(Base, Vector): __tablename__ = 'isos' __table_args__ = ({'autoload': False}) __template__ = 'templates/htmlpopup/isos.mako' __bodId__ = 'ch.bak.bundesinventar-schuetzenswerte-ortsbilder' __label__ = 'ortsbildname' id = Column('gid', Integer, primary_key=True) ortsbildname = Column('ortsbildname', Unicode) kanton = Column('kanton', Unicode) vergleichsrastereinheit = Column('vergleichsrastereinheit', Unicode) lagequalitaeten = Column('lagequalitaeten', Unicode) raeumliche_qualitaeten = Column('raeumliche_qualitaeten', Unicode) arch__hist__qualitaeten = Column('arch__hist__qualitaeten', Unicode) fassungsjahr = Column('fassungsjahr', Unicode) band_1 = Column('band_1', Unicode) band_2 = Column('band_2', Unicode) publikationsjahr_1 = Column('publikationsjahr_1', Unicode) publikationsjahr_2 = Column('publikationsjahr_2', Unicode) pdf_dokument_1 = Column('pdf_dokument_1', Unicode) pdf_dokument_2 = Column('pdf_dokument_2', Unicode) pdfspecial = Column('pdfspecial', Unicode) the_geom = Column(Geometry2D) register('ch.bak.bundesinventar-schuetzenswerte-ortsbilder', Isos) class Unesco(Base, Vector): __tablename__ = 'unesco' __table_args__ = ({'autoload': False}) __template__ = 'templates/htmlpopup/unesco_bak.mako' __bodId__ = 'ch.bak.schutzgebiete-unesco_weltkulturerbe' __label__ = 'name_de' __returnedGeometry__ = 'the_geom_simplified_tolerance_3' id = Column('bgdi_id', Integer, primary_key=True) name_fr = Column('name_fr', Unicode) name_de = Column('bgdi_name', Unicode) name_it = Column('name_it', Unicode) name_en = Column('name_en', Unicode) name_rm = Column('name_rm', Unicode) type_fr = Column('type_fr', Unicode) type_de = Column('type_de', Unicode) type_it = Column('type_it', Unicode) type_en = Column('type_en', Unicode) type_rm = Column('type_rm', Unicode) bgdi_surface = Column('bgdi_surface', Numeric) the_geom = Column(Geometry2D) the_geom_simplified_tolerance_3 = Column('the_geom_simplified_tolerance_3', Geometry2D) register('ch.bak.schutzgebiete-unesco_weltkulturerbe', Unesco)
42,540
https://github.com/holmes2136/LineBotKit/blob/master/src/LineBotKit.Client/Request/LineGetStreamRequestcs.cs
Github Open Source
Open Source
Apache-2.0
2,020
LineBotKit
holmes2136
C#
Code
49
178
using LineBotKit.Client.Response; using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; namespace LineBotKit.Client.Request { internal class LineGetStreamRequest<T> : LineClientRequestBase { public LineGetStreamRequest(LineClientBase client, string path) : base(client, path, HttpMethod.Get) { } public Task<LineClientResult<Stream>> Execute(CancellationToken cancellationToken = default(CancellationToken)) { return base.ExecuteStreamServiceCall<Stream>(null, cancellationToken); } } }
47,016
https://github.com/scalapb/protoc-bridge/blob/master/bridge/src/test/scala/protocbridge/ProtocIntegrationSpec.scala
Github Open Source
Open Source
Apache-2.0
2,023
protoc-bridge
scalapb
Scala
Code
340
1,443
package protocbridge import java.io.File import java.nio.file.Files import java.util.concurrent.Executors import com.google.protobuf.Descriptors.FileDescriptor import com.google.protobuf.compiler.PluginProtos.{ CodeGeneratorRequest, CodeGeneratorResponse } import scala.concurrent.duration.{Duration, SECONDS} import scala.concurrent.{Await, ExecutionContext, Future, blocking} import scala.io.Source import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.must.Matchers import TestUtils.readLines import protocbridge.frontend.PluginFrontend object TestJvmPlugin extends ProtocCodeGenerator { import scala.jdk.CollectionConverters._ override def run(in: Array[Byte]): Array[Byte] = { val request = CodeGeneratorRequest.parseFrom(in) val filesByName: Map[String, FileDescriptor] = request.getProtoFileList.asScala .foldLeft[Map[String, FileDescriptor]](Map.empty) { case (acc, fp) => val deps = fp.getDependencyList.asScala.map(acc) acc + (fp.getName -> FileDescriptor.buildFrom(fp, deps.toArray)) } val content = (for { fileName <- request.getFileToGenerateList.asScala file = filesByName(fileName) msg <- file.getMessageTypes().asScala } yield (file.getName + ":" + msg.getFullName)).mkString("\n") val responseBuilder = CodeGeneratorResponse.newBuilder() responseBuilder .addFileBuilder() .setContent(content) .setName("msglist.txt") responseBuilder .addFileBuilder() .setContent( if (request.getParameter().isEmpty()) "Empty" else request.getParameter() ) .setName("parameters.txt") responseBuilder.build().toByteArray } } object TestUtils { def readLines(file: File) = { val s = Source.fromFile(file) try { Source.fromFile(file).getLines().toVector } finally { s.close() } } } class ProtocIntegrationSpec extends AnyFlatSpec with Matchers { "ProtocBridge.run" should "invoke JVM and Java plugin properly" in { val protoFile = new File(getClass.getResource("/test.proto").getFile).getAbsolutePath val protoDir = new File(getClass.getResource("/").getFile).getAbsolutePath val javaOutDir = Files.createTempDirectory("javaout").toFile() val testOutDirs = (0 to 4).map(i => Files.createTempDirectory(s"testout$i").toFile()) ProtocBridge.execute( RunProtoc, Seq( protocbridge.gens.java("3.8.0") -> javaOutDir, TestJvmPlugin -> testOutDirs(0), TestJvmPlugin -> testOutDirs(1), JvmGenerator("foo", TestJvmPlugin) -> testOutDirs(2), ( JvmGenerator("foo", TestJvmPlugin), Seq("foo", "bar:value", "baz=qux") ) -> testOutDirs(3), JvmGenerator("bar", TestJvmPlugin) -> testOutDirs(4) ), Seq(protoFile, "-I", protoDir) ) must be(0) Files.exists( javaOutDir.toPath.resolve("mytest").resolve("Test.java") ) must be( true ) testOutDirs.foreach { testOutDir => val expected = Seq( "test.proto:mytest.TestMsg", "test.proto:mytest.AnotherMsg" ) readLines(new File(testOutDir, "msglist.txt")) must be(expected) } readLines(new File(testOutDirs(3), "parameters.txt")) must be( Seq("foo,bar:value,baz=qux") ) readLines(new File(testOutDirs(0), "parameters.txt")) must be(Seq("Empty")) } it should "not deadlock for highly concurrent invocations" in { val availableProcessors = Runtime.getRuntime.availableProcessors assert( availableProcessors > 1, "Several vCPUs needed for the test to be relevant" ) val parallelProtocInvocations = availableProcessors * 8 val generatorsByInvocation = availableProcessors * 8 val protoFile = new File(getClass.getResource("/test.proto").getFile).getAbsolutePath val protoDir = new File(getClass.getResource("/").getFile).getAbsolutePath implicit val ec = ExecutionContext.fromExecutorService( Executors.newFixedThreadPool(parallelProtocInvocations) ) val invocations = List.fill(parallelProtocInvocations) { Future( blocking( ProtocBridge.execute( RunProtoc, List.fill(generatorsByInvocation)( Target( JvmGenerator("foo", TestJvmPlugin), Files.createTempDirectory(s"foo").toFile ) ), Seq(protoFile, "-I", protoDir) ) ) ) } Await.result( Future.sequence(invocations), Duration(60, SECONDS) ) must be(List.fill(parallelProtocInvocations)(0)) } }
1,521
https://github.com/Ligh7bringer/SET10108-practicals/blob/master/labs/lab02/condition-variables.cpp
Github Open Source
Open Source
MIT
null
SET10108-practicals
Ligh7bringer
C++
Code
321
883
#include <condition_variable> #include <iostream> #include <chrono> #include <mutex> #include <thread> std::mutex mut; void task_1(std::condition_variable &condition) { std::cout << "Task 1 sleeping for 3 seconds" << std::endl; std::this_thread::sleep_for(std::chrono::seconds(3)); auto lock = std::unique_lock<std::mutex>(mut); std::cout << "Task 1 notifying waiting thread" << std::endl; condition.notify_one(); std::cout << "Task 1 waiting for notification" << std::endl; condition.wait(lock); std::cout << "Task 1 notified" << std::endl; std::cout << "Task 1 sleeping for 3 seconds" << std::endl; std::this_thread::sleep_for(std::chrono::seconds(3)); std::cout << "Task 1 notifying waiting thread" << std::endl; condition.notify_one(); std::cout << "Task 1 waiting 3 seconds for notification" << std::endl; if (condition.wait_for(lock, std::chrono::seconds(3)) == std::cv_status::no_timeout) std::cout << "Task 1 notified before 3 seconds" << std::endl; else std::cout << "Task 1 got tired waiting" << std::endl; std::cout << "Task 1 finished" << std::endl; } void task_2(std::condition_variable &condition) { // Create lock auto lock = std::unique_lock<std::mutex>(mut); // Task two will initially wait for notification std::cout << "Task 2 waiting for notification" << std::endl; // Wait, releasing the lock as we do. condition.wait(lock); // We are free to continue std::cout << "Task 2 notified" << std::endl; // Sleep for 5 seconds std::cout << "Task 2 sleeping for 5 seconds" << std::endl; std::this_thread::sleep_for(std::chrono::seconds(5)); // Notify waiting thread std::cout << "Task 2 notifying waiting thread" << std::endl; condition.notify_one(); // Now wait 5 seconds for notification std::cout << "Task 2 waiting 5 seconds for notification" << std::endl; if (condition.wait_for(lock, std::chrono::seconds(5)) == std::cv_status::no_timeout) std::cout << "Task 2 notified before 5 seconds" << std::endl; else std::cout << "Task 2 got tired waiting" << std::endl; // Sleep for 5 seconds std::cout << "Task 2 sleeping for 5 seconds" << std::endl; std::this_thread::sleep_for(std::chrono::seconds(5)); // Notify any waiting thread std::cout << "Task 2 notifying waiting thread" << std::endl; condition.notify_one(); // Print finished message std::cout << "Task 2 finished" << std::endl; } int main(int argc, char **argv) { // Create condition variable std::condition_variable condition; // Create two threads std::thread t1(task_1, ref(condition)); std::thread t2(task_2, ref(condition)); // Join two threads t1.join(); t2.join(); getchar(); return 0; }
6,804
https://github.com/bryant1410/sela/blob/master/include/lpc.h
Github Open Source
Open Source
MIT
2,017
sela
bryant1410
C
Code
63
347
#ifndef _LPC_H_ #define _LPC_H_ #define SQRT2 1.4142135623730950488016887242096 #define MAX_LPC_ORDER 100 int32_t check_if_constant(const int16_t *data,int32_t num_elements); void auto_corr_fun(double *x,int32_t N,int64_t k,int16_t norm,double *rxx); void levinson(double *autoc,uint8_t max_order,double *ref,double lpc[][MAX_LPC_ORDER]); uint8_t compute_ref_coefs(double *autoc,uint8_t max_order,double *ref); int32_t qtz_ref_cof(double *par,uint8_t ord,int32_t *q_ref); int32_t dqtz_ref_cof(const int32_t *q_ref,uint8_t ord,double *ref); void calc_residue(const int32_t *samples,int64_t N,int16_t ord,int16_t Q,int64_t *coff,int32_t *residues); void calc_signal(const int32_t *residues,int64_t N,int16_t ord,int16_t Q,int64_t *coff,int32_t *samples); #endif
30,878
https://github.com/GirCore/gir.core/blob/master/src/Generation/Generator3/Model/Public/ReturnType/ReturnTypeFactory.cs
Github Open Source
Open Source
MIT
2,020
gir.core
GirCore
C#
Code
67
229
namespace Generator3.Model.Public { public static class ReturnTypeFactory { public static ReturnType CreatePublicModel(this GirModel.ReturnType returnValue) => returnValue.AnyType.Match<ReturnType>( type => type switch { GirModel.Pointer => new PointerReturnType(returnValue), GirModel.PrimitiveValueType => new PrimitiveValueReturnType(returnValue), GirModel.Class => new ClassReturnType(returnValue), GirModel.Interface => new InterfaceReturnType(returnValue), GirModel.Record => new RecordReturnType(returnValue), GirModel.Bitfield => new BitfieldReturnType(returnValue), GirModel.Enumeration => new EnumerationReturnType(returnValue), _ => new StandardReturnType(returnValue) }, arrayType => arrayType switch { _ => new StandardReturnType(returnValue) } ); } }
46,861
https://github.com/KajanM/DSVL/blob/master/flood/src/main/java/com/dsvl/flood/model/ForwardedQuery.java
Github Open Source
Open Source
MIT
2,019
DSVL
KajanM
Java
Code
41
114
package com.dsvl.flood.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * Used to keep track of sent queries */ @Data @NoArgsConstructor @AllArgsConstructor public class ForwardedQuery { private String msgOwnerIp; private int msgOwnerUdpPort; private String searchTerm; private String neighbourIp; private int neighbourPort; }
13,186
https://github.com/wallarelvo/CRoPS/blob/master/docs/html/boidsimulation_8py.js
Github Open Source
Open Source
Apache-2.0
null
CRoPS
wallarelvo
JavaScript
Code
15
96
var boidsimulation_8py = [ [ "FlockSim", "classboidsimulation_1_1FlockSim.html", "classboidsimulation_1_1FlockSim" ], [ "__author__", "boidsimulation_8py.html#a70f722357d7e5a4b5ac85e726863a7ef", null ] ];
3,973
https://github.com/MrMimic/covid-19-applet/blob/master/src/main/scripts/vm_startup_script.sh
Github Open Source
Open Source
MIT
2,020
covid-19-applet
MrMimic
Shell
Code
177
663
#!/usr/bin/bash # Create detached shell tmux new -s APP # Proxy update gcloud compute firewall-rules create --network=covid-19-network default-allow-ssh --allow tcp:22 gcloud compute firewall-rules create --network=covid-19-network allow-debug-app --allow tcp:5000 # Setup python sudo apt-get install -y software-properties-common python-software-properties sudo add-apt-repository -y ppa:jonathonf/python-3.6 sudo add-apt-repository -y ppa:deadsnakes/ppa sudo apt-get update -y sudo apt-get install -y python3.6 sudo rm /usr/bin/python3 sudo ln -s /usr/bin/python3.6 /usr/bin/python3 sudo apt-get install -y python-pip python3-pip sudo apt-get install python3.6-dev python3.6-venv pip install --upgrade pip # Mount GCstorage bucket sudo apt-get install python3.6-gdbm export GCSFUSE_REPO=gcsfuse-`lsb_release -c -s` echo "deb http://packages.cloud.google.com/apt $GCSFUSE_REPO main" | sudo tee /etc/apt/sources.list.d/gcsfuse.list curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add - sudo apt-get update sudo apt-get install gcsfuse mkdir data/ gcsfuse kaggle-covid-19-bucket data/ # Install app git clone https://github.com/MrMimic/covid-19-applet git clone https://github.com/MrMimic/covid-19-kaggle cd covid-19-applet python3 -m venv venv source venv/bin/activate pip install poetry poetry install # Download NLP stopwords and lemmatizer python3 -m nltk.downloader stopwords python3 -m nltk.downloader punkt # Update local path and run sed -i "s;LOCAL_DB_PATH = .*;LOCAL_DB_PATH = '/home/$USER/data/articles_database_v14_02052020_test.sqlite';" server.py sed -i "s;LOCAL_EMBEDDING_PATH = .*;LOCAL_EMBEDDING_PATH = '/home/$USER/covid-19-kaggle/resources/global_df_w2v_tfidf.parquet';" server.py python3 server.py
8,913
https://github.com/engalialaa/php-task/blob/master/resources/views/Front/layout/header.blade.php
Github Open Source
Open Source
MIT
null
php-task
engalialaa
PHP
Code
466
2,504
<?php $Categories = App\Models\Category::where('is_shown','yes')->latest()->get(); ?> <?php if (auth()->user()){ $Carts = \App\Models\Cart::where('user_id', auth()->user()->id)->latest()->get(); }else{ $Carts = []; } ?> <!doctype html> <html class="no-js" lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="csrf-token" content="{{ csrf_token() }}"/> <title>@yield('title')</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Favicon --> <!-- CSS ========================= --> <!--bootstrap min css--> <link rel="stylesheet" href="{{url('')}}/front/css/bootstrap.min.css"> <!--font awesome css--> <link rel="stylesheet" href="{{url('')}}/front/css/font.awesome.css"> <!--animate css--> <link rel="stylesheet" href="{{url('')}}/front/css/animate.css"> <!--swiper css--> <link rel="stylesheet" href="{{url('')}}/front/css/swiper.css"/> <!--nice-select css--> <link rel="stylesheet" href="{{url('')}}/front/css/nice-select.css"> <!--odometer css--> <link rel="stylesheet" href="{{url('')}}/front/css/odometer.css"> <!--dropify css--> <link rel="stylesheet" href="{{url('')}}/front/css/dropify.min.css"> <link rel="shortcut icon" type="image/x-icon" href="{{url('')}}/front/img/favicon.png"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@10/dist/sweetalert2.min.css" id="theme-styles"> @toastr_css <!-- Main Style CSS --> <link rel="stylesheet" href="{{url('')}}/front/css/styleEN.css?{{time()}}"> <link href="{{url('/')}}/admin/assets/plugins/notify/css/notifIt.css" rel="stylesheet"/> @include('Front.load.loaderCss') </head> <body> <!--mobile menu --> <div class="off_canvars_overlay"></div> <div class="offcanvas_menu"> <div class="container"> <input name="user_id" hidden id="user_id" value="1"> <div class="row"> <div class="col-12"> <div class="canvas_open"> <a href="#!"><i class="fal fa-bars"></i></a> </div> <div class="offcanvas_menu_wrapper"> <div class="canvas_close"> <a href="#!"><i class="fal fa-times"></i></a> </div> <div class="language_currency"> <ul> <li> @if(auth()->user()) <a href="{{route('user.logout')}}">{{trans('front.logout')}}</a> @else <a href="{{route('user.login')}}">{{trans('front.login')}}</a> @endif </li> </ul> </div> <div id="menu" class="text-left"> <ul class="offcanvas_main_menu"> @if(auth()->user()) <li> <a href="{{route('user.logout')}}">logout</a> </li> @else <li> <a href="{{route('user.login')}}">login</a> </li> @endif <li><a href="{{route('Front.Home')}}">Home</a></li> <li><a href="{{route('Front.products')}}">Products</a></li> <li><a href="{{route('Front.categories')}}">Categories</a></li> </ul> </div> </div> </div> </div> </div> </div> {{--<!-- / mobile menu -->--}} <header> <div class="main_header"> <div class="header_top"> <div class="container"> <div class="row align-items-center"> <div class="col-lg-6 col-md-6"> </div> <div class="col-lg-6"> <div class="header_social text-right"> </div> </div> </div> </div> </div> <div class="header_middle"> <div class="container"> <div class="row align-items-center"> <div class="col-lg-2 col-md-3 col-sm-3 col-3"> <div class="logo"> <a href="{{route('Front.Home')}}">PHP TASK</a> </div> </div> <div class="col-lg-10 col-md-6 col-sm-7 col-8"> <div class="header_right_info"> <div class="search_container mobail_s_none"> <form action="{{route('Front.search')}}" method="GET"> <div class="hover_category"> <select class="select_option" name="Category_id" id="categori2"> <option selected value="0">categories</option> @foreach($Categories as $Category) <option value="{{ $Category->id }}" {{ $Category->id == request()->Category_id ? 'selected' : '' }}>{{ $Category->name}}</option> @endforeach </select> </div> <div class="search_box"> <input placeholder="search" value="{{request()->search}}" name="search" type="text"> <button type="submit"><span class="fal fa-search"></span></button> </div> </form> </div> <div class="header_account_area"> <div class="header_account_list register"> <ul> @if(auth()->user()) <li> <a href="{{route('user.logout')}}">logout</a> </li> @else <li><a href="{{route('user.login')}}">Login</a></li> @endif </ul> </div> <div class="header_account_list mini_cart_wrapper"> <a href="#!"> <span class="fal fa-shopping-cart"></span> <span class="item_count" id="countItems"> @if(auth()->user()) {{$Carts->count()}} @else 0 @endif </span> </a> <!--mini cart--> <div class="mini_cart" id="loadNewCart"> @include('Front.load.cart') </div> </div> </div> </div> <!--mini cart end--> </div> </div> </div> </div> </div> <div class="header_bottom sticky-header"> <div class="container"> <div class="row align-items-center"> <div class="col-12 col-md-6 mobail_s_block"> <div class="search_container"> <form action="{{route('Front.search')}}" method="GET"> <div class="hover_category"> <select class="select_option" name="Category_id" id="categori3"> <option selected value="0">categories</option> @foreach($Categories as $Category) <option value="{{ $Category->id }}" {{ $Category->id == request()->Category_id ? 'selected' : '' }}>{{ $Category->name}}</option> @endforeach </select> </div> <div class="search_box"> <input placeholder="Search" value="{{request()->search}}" name="search" type="text"> <button type="submit"><span class="fal fa-search"></span></button> </div> </form> </div> </div> <div class="col-lg-3 col-md-6"> <div class="categories_menu"> <div class="categories_title"> <h2 class="categori_toggle">Categories</h2> </div> <div class="categories_menu_toggle"> <ul> @foreach($Categories as $Category) <li class="menu_item_children"> <a href="{{route('categories.products',$Category->id)}}">{{$Category->name}}</a> </li> @endforeach </ul> </li> </ul> </div> </div> </div> <div class="col-lg-9"> <!--main menu start--> <div class="main_menu menu_position "> <nav> <ul> <li><a href="{{route('Front.Home')}}">Home</a></li> <li><a href="{{route('Front.products')}}">Products</a></li> <li><a href="{{route('Front.categories')}}">Categories</a></li> </ul> </nav> </div> <!--main menu end--> </div> </div> </div> </div> </div> </header> <!-- / header -->
34,924
https://github.com/rangaimal/HMS/blob/master/demo/App.vue
Github Open Source
Open Source
MIT
null
HMS
rangaimal
Vue
Code
791
2,826
<template> <div id="demo" :class="[{'collapsed' : collapsed}]"> <div class="demo"> <div class="container"> <!-- <button class="collapse-btn" @click="toggleCollapse" />--> <!-- <h1> HMS </h1> --> <!-- <div> Select theme: <select v-model="selectedTheme"> <option v-for="(theme, index) in themes" :key="index" >{{ theme == '' ? 'default-theme' : theme }}</option> </select> </div> --> <!-- <hr style="margin: 50px 0px;border: 1px solid #e3e3e3; width:100%;"> --> <router-view/> </div> <sidebar-menu :menu="menu" :collapsed="collapsed" :theme="selectedTheme" :show-one-child="true" @collapse="onCollapse" @itemClick="onItemClick" /> </div> </div> </template> <script> const separator = { template: `<hr style="border-color: rgba(0, 0, 0, 0.1); margin: 20px;">` }; export default { name: "App", data() { return { menu: [ { header: true, title: "HMS" }, { href: "/", title: "Dashboard", icon: "fa fa fa-tachometer" }, { title: "Rooms Operations", icon: "fa fa-key", child: [ { href: "/RoomsOperations/RoomsList/RoomsList", title: "Rooms List", icon: "fa fa-caret-right" }, { href: "/RoomsOperations/RoomBooking/RoomDetails", title: "Room Booking", icon: "fa fa-caret-right" }, { href: "/RoomsOperations/PaymentTrackers/PaymentTrackers", title: "Payment Trackers", icon: "fa fa-caret-right" }, { href: "/RoomsOperations/CheckingList/CheckingList", title: "Checking List", icon: "fa fa-caret-right" }, { href: "/RoomsOperations/CheckoutList/CheckoutList", title: "Checkout List", icon: "fa fa-caret-right" }, { href: "/RoomsOperations/ReservationList/ReservationList", title: "Reservation List", icon: "fa fa-caret-right" }, { href: "/RoomsOperations/TempRoomList/TempRoomList", title: "Temp Room List", icon: "fa fa-caret-right" }, { href: "/RoomsOperations/CancelReservationList/CancelReservationList", title: "Cancel Reservation List", icon: "fa fa-caret-right" }, { href: "/RoomsOperations/CheckoutPendingList/CheckoutPendingList", title: "Checkout Pending List", icon: "fa fa-caret-right" }, { href: "/RoomsOperations/BookingDeposit/BookingDeposit", title: "Booking Deposit", icon: "fa fa-caret-right" } ] }, { title: "kitchen", icon: "fa fa-glass", child: [ { href: "/Kitchen/AllocationList", title: "Allocation List", icon: "fa fa-caret-right" }, { href: "/Kitchen/OrdersList", title: "Orders List", icon: "fa fa-caret-right" } ] }, { title: "Foods", icon: "fa fa-cutlery", child: [ { href: "/Foods/FoodsList", title: "Foods Lists", icon: "fa fa-caret-right" }, { href: "/Foods/CategoryList", title: "Category Lists", icon: "fa fa-caret-right" }, { href: "/Foods/AvailableFood", title: "Available Foods", icon: "fa fa-caret-right" } ] }, { title: "Food Reservation", icon: "fa fa-bookmark", child: [ { href: "/FoodReservation/FoodReservation", title: "Food Reservation Form", icon: "fa fa-caret-right" }, { href: "/FoodReservation/FoodDetails", title: "Food Details", icon: "fa fa-caret-right" }, { href: "/FoodReservation/AddedFoodList", title: "Added Food List(Customer)", icon: "fa fa-caret-right" }, { href: "/FoodReservation/OrderedFoodList", title: "Ordered Food List(Customer)", icon: "fa fa-caret-right" } ] }, { title: "Activities", icon: "fa fa-trophy", child: [ { href: "/Activities/CategoryListAct", title: "Category List", icon: "fa fa-caret-right" }, { href: "/Activities/ActivityList", title: "Activity List", icon: "fa fa-caret-right" }, { href: "/Activities/ActivityView", title: "Activity View", icon: "fa fa-caret-right" }, { href: "/Activities/ActivityDetails", title: "Activity Details", icon: "fa fa-caret-right" }, { href: "/Activities/AddedActivityList", title: "Added Activity List", icon: "fa fa-caret-right" }, { href: "/Activities/OrderedActivityList", title: "Ordered Activity List", icon: "fa fa-caret-right" }, { href: "/Activities/AllocationActivity", title: "Allocation Activity", icon: "fa fa-caret-right" }, { href: "/Activities/ActivityOrderList", title: "Activity Order List", icon: "fa fa-caret-right" }, ] }, // { // header: true, // title: 'Usage' // }, { href: "/Reports/Reports", title: "Reports", icon: "fa fa-book" } // { // href: '/events', // title: 'Events', // icon: 'fa fa-bell' // }, // { // href: '/styling', // title: 'Styling', // icon: 'fa fa-palette' // }, // { // header: true, // component: separator, // visibleOnCollapse: true // }, // { // header: true, // title: 'Example' // }, // { // href: '/disabled', // title: 'Disabled page', // icon: 'fa fa-lock', // disabled: true // }, // { // title: 'Badge', // icon: 'fa fa-cog', // badge: { // text: 'new', // class: 'default-badge' // } // }, // { // href: '/page', // title: 'Dropdown Page', // icon: 'fa fa-list-ul', // child: [ // { // href: '/page/sub-page-1', // title: 'Sub Page 01', // icon: 'fa fa-file-alt' // }, // { // href: '/page/sub-page-2', // title: 'Sub Page 02', // icon: 'fa fa-file-alt' // } // ] // }, // { // title: 'Multiple Level', // icon: 'fa fa-list-alt', // child: [ // { // title: 'page' // }, // { // title: 'Level 2 ', // child: [ // { // title: 'page' // }, // { // title: 'Page' // } // ] // }, // { // title: 'Page' // }, // { // title: 'Another Level 2', // child: [ // { // title: 'Level 3', // child: [ // { // title: 'Page' // }, // { // title: 'Page' // } // ] // } // ] // } // ] // } ], collapsed: false, themes: ["", "black-theme"], selectedTheme: "black-theme" }; }, methods: { onCollapse(collapsed) { console.log(collapsed); this.collapsed = collapsed; }, onItemClick(event, item) { console.log("onItemClick"); // console.log(event) // console.log(item) } } }; </script> <style lang="scss"> @import url("https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,600"); @import url("https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"); body, html { margin: 0; padding: 0; } body { font-family: "Source Sans Pro", sans-serif; background-color: #f2f4f7; } #demo { padding-left: 350px; } #demo.collapsed { padding-left: 50px; } .demo { padding: 50px; } .container { max-width: 600px; } pre { color: #2a2a2e; background: #fff; border-radius: 2px; padding: 10px; overflow: auto; } </style>
24,691
https://github.com/lulzzz/tellma/blob/master/Tellma.Database.Data/Provisioning/__Main.sql
Github Open Source
Open Source
Apache-2.0
2,023
tellma
lulzzz
SQL
Code
77
371
--IF DB_NAME() = N'Tellma.Tests.101' --BEGIN -- -- Provision data for unit tests -- :r .\Tests\00_Declarations.sql -- :r .\Tests\01_Users.sql -- :r .\Tests\02_Roles.sql --END --GO -- Important so that variable declarations do not conflict :r .\000\a_Declarations.sql :r .\000\b_AdminUser.sql :r .\000\c_Currencies.sql :r .\000\d_Units.sql --:r .\000\f_IfrsConcepts.sql --:r .\000\g_IfrsDisclosures.sql :r .\000\h_EntryTypes.sql :r .\000\i_LookupDefinitions.sql :r .\000\j_AgentDefinitions.sql :r .\000\l_ResourceDefinitions.sql :r .\000\m_AccountTypes.sql :r .\000\n_Settings.sql :r .\000\o_LineDefinitions.sql :r .\000\p_DocumentDefinitions.sql --:r .\000\r_AccountClassifications.sql :r .\000\t_Accounts.sql :r .\000\y_Roles.sql :r .\000\z_Translations.sql UPDATE Settings SET DefinitionsVersion = NewId(); RETURN; ERR_LABEL: RETURN;
41,319
https://github.com/leeeeeeeefulong/liwushuo/blob/master/liwushuo/liwushuo/Controllers/Mine/View/LWSMePromotionsControl.m
Github Open Source
Open Source
MIT
2,018
liwushuo
leeeeeeeefulong
Objective-C
Code
175
863
// // LWSMePromotionsControl.m // liwushuo // // Created by lee on 2017/12/29. // Copyright © 2017年 Pinellia Zeit. All rights reserved. // #import "LWSMePromotionsControl.h" #import "LWSMeImageBubbleView.h" @interface LWSMePromotionsControl () @end @implementation LWSMePromotionsControl - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { // self.backgroundColor = [UIColor whiteColor]; [self drawUI]; } return self; } - (void)drawUI { LWSMeImageBubbleView *shoppingCartView = [[LWSMeImageBubbleView alloc] init]; [self addSubview:shoppingCartView]; [shoppingCartView mas_makeConstraints:^(MASConstraintMaker *make) { make.top.left.bottom.equalTo(self); make.width.mas_equalTo(@53); }]; shoppingCartView.titleLabel.text = @"购物车"; shoppingCartView.imageView.image = [UIImage imageNamed:@"home_btn_shop_24x24_"]; LWSMeImageBubbleView *ordersView = [[LWSMeImageBubbleView alloc] init]; [self addSubview:ordersView]; [ordersView mas_makeConstraints:^(MASConstraintMaker *make) { make.width.height.equalTo(shoppingCartView); make.top.equalTo(self); make.centerX.equalTo(self.mas_centerX).offset(-51.88); }]; ordersView.titleLabel.text = @"订单"; ordersView.imageView.image = [UIImage imageNamed:@"home_btn_form_24x24_"]; LWSMeImageBubbleView *giftView = [[LWSMeImageBubbleView alloc] init]; [self addSubview:giftView]; [giftView mas_makeConstraints:^(MASConstraintMaker *make) { make.top.equalTo(self); make.width.height.equalTo(shoppingCartView); make.centerX.equalTo(self.mas_centerX).offset(51.88); }]; giftView.titleLabel.text = @"礼券"; giftView.imageView.image = [UIImage imageNamed:@"home_btn_deed_24x24_"]; LWSMeImageBubbleView *remindView = [[LWSMeImageBubbleView alloc] init]; [self addSubview:remindView]; [remindView mas_makeConstraints:^(MASConstraintMaker *make) { make.right.top.bottom.equalTo(self); make.width.equalTo(shoppingCartView); }]; remindView.titleLabel.text = @"送礼提醒"; remindView.imageView.image = [UIImage imageNamed:@"btn_remind_24x24_"]; } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. - (void)drawRect:(CGRect)rect { // Drawing code } */ @end
1,533
https://github.com/RafaelMunizz/POO/blob/master/Unidade2/Atividade3/Quest5/main.cpp
Github Open Source
Open Source
MIT
null
POO
RafaelMunizz
C++
Code
93
252
#include <iostream> using std::cout; using std::endl; using std::cin; #include "Array.h" int main() { Array a1(7); //array de 7 elementos Array a2; //array de 10 elementos cin >> a1; //lendo array cin >> a2; //lendo array //cout << a1; //escrevendo array if (a1 == a2) cout << "a1 e a2 são iguais"; Array a3 = a2 + a1; a3[5] = 100; //invoca int &operator[](int) //cout << "a3[5] == " << a3[5] << endl; //int operator[](int) const a2 = a3; //cout << "a2[5] == " << a3[5] << endl; //a2[100] = 50; return 0; }
45,775
https://github.com/jinghewang/yii2-basic-2.0.6/blob/master/db/yii2basic.sql
Github Open Source
Open Source
BSD-3-Clause
2,016
yii2-basic-2.0.6
jinghewang
PLpgSQL
Code
183
553
/* Navicat Premium Data Transfer Source Server : local Source Server Type : MySQL Source Server Version : 50710 Source Host : localhost Source Database : yii2basic Target Server Type : MySQL Target Server Version : 50710 File Encoding : utf-8 Date: 03/07/2016 13:00:33 PM */ SET NAMES utf8; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for `country` -- ---------------------------- DROP TABLE IF EXISTS `country`; CREATE TABLE `country` ( `code` varchar(50) NOT NULL COMMENT '国家代码', `name` varchar(200) DEFAULT NULL COMMENT '国家名称', `population` int(8) DEFAULT NULL COMMENT '国家人口', `createtime` datetime DEFAULT NULL COMMENT '创建时间', PRIMARY KEY (`code`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT; -- ---------------------------- -- Records of `country` -- ---------------------------- BEGIN; INSERT INTO `country` VALUES ('1', '1', '2', '2015-12-28 14:50:50'), ('2', '2', '3', '2015-12-28 14:50:57'), ('22', '22', '225', null), ('3', '3', '10', '2015-12-28 15:16:32'), ('32', '32', '32', '2015-12-28 14:49:20'), ('4', '4', '4', '2015-12-28 14:49:35'), ('43', '43', '43', '2015-12-28 14:46:42'), ('AU', 'Australia', '18886000', '2015-12-25 15:50:01'), ('BR', 'Brazil', '170115000', '2015-12-25 15:50:01'), ('CA', 'Canada', '1147000', '2015-12-25 15:50:01'), ('CN', '中国', '2222', null), ('USA', '美国', '800002', null), ('yp', 'yp', '122', '2015-12-25 15:20:12'); COMMIT; SET FOREIGN_KEY_CHECKS = 1;
8,865
https://github.com/Ignishky/mtg-collection/blob/master/src/main/java/fr/ignishky/mtgcollection/MtgCollectionApplication.java
Github Open Source
Open Source
Apache-2.0
2,021
mtg-collection
Ignishky
Java
Code
21
90
package fr.ignishky.mtgcollection; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MtgCollectionApplication { public static void main(String[] args) { SpringApplication.run(MtgCollectionApplication.class, args); } }
29,919
https://github.com/Edraak/code-dot-or/blob/master/apps/src/sites/studio/pages/pd/workshop_survey/new.js
Github Open Source
Open Source
Apache-2.0
2,022
code-dot-or
Edraak
JavaScript
Code
26
124
import React from 'react'; import ReactDOM from 'react-dom'; import WorkshopSurvey from '@cdo/apps/code-studio/pd/workshop_survey/WorkshopSurvey'; import getScriptData from '@cdo/apps/util/getScriptData'; document.addEventListener('DOMContentLoaded', function(event) { ReactDOM.render( <WorkshopSurvey {...getScriptData('props')} />, document.getElementById('application-container') ); });
11,021
https://github.com/Youssef1313/upgrade-assistant/blob/master/src/common/Microsoft.DotNet.UpgradeAssistant.Abstractions/ProjectExtensions.cs
Github Open Source
Open Source
MIT
null
upgrade-assistant
Youssef1313
C#
Code
86
228
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Diagnostics.CodeAnalysis; using System.Linq; namespace Microsoft.DotNet.UpgradeAssistant { public static class ProjectExtensions { public static IProject Required(this IProject? project) => project ?? throw new InvalidOperationException("Project cannot be null"); public static bool TryGetPackageByName(this IProject project, string packageName, [MaybeNullWhen(false)] out NuGetReference nugetReference) { var matches = project.Required().PackageReferences.Where(p => p.Name.Equals(packageName, StringComparison.OrdinalIgnoreCase)).OrderByDescending(p => Version.Parse(p.Version)); nugetReference = matches.FirstOrDefault(); return nugetReference is not null; } } }
43,419
https://github.com/halzhang/BDMyTracks/blob/master/MyTracks/src/com/google/android/apps/mytracks/maps/DynamicSpeedTrackPathPainter.java
Github Open Source
Open Source
WTFPL
2,021
BDMyTracks
halzhang
Java
Code
469
1,313
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.maps; import com.google.android.apps.mytracks.ColoredPath; import com.google.android.apps.mytracks.MapOverlay.CachedLocation; import com.google.android.maps.GeoPoint; import com.google.android.maps.Projection; import com.google.android.maps.mytracks.R; import com.google.common.annotations.VisibleForTesting; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Point; import android.graphics.Rect; import java.util.ArrayList; import java.util.List; /** * A path painter that varies the path colors based on fixed speeds or average * speed margin depending of the TrackPathDescriptor passed to its constructor. * * @author Vangelis S. */ public class DynamicSpeedTrackPathPainter implements TrackPathPainter { private final TrackPathDescriptor trackPathDescriptor; private final Paint slowPaint; private final Paint mediumPaint; private final Paint fastPaint; private final List<ColoredPath> coloredPaths; public DynamicSpeedTrackPathPainter(Context context, TrackPathDescriptor trackPathDescriptor) { this.trackPathDescriptor = trackPathDescriptor; slowPaint = TrackPathUtils.getPaint(context, R.color.slow_path); mediumPaint = TrackPathUtils.getPaint(context, R.color.normal_path); fastPaint = TrackPathUtils.getPaint(context, R.color.fast_path); coloredPaths = new ArrayList<ColoredPath>(); } @Override public boolean hasPath() { return !coloredPaths.isEmpty(); } @Override public boolean updateState() { return trackPathDescriptor.updateState(); } @Override public void updatePath( Projection projection, Rect viewRect, int startIndex, List<CachedLocation> points) { boolean hasLastPoint = startIndex != 0 && points.get(startIndex -1).isValid(); Point point = new Point(); if (hasLastPoint) { GeoPoint geoPoint = points.get(startIndex -1).getGeoPoint(); projection.toPixels(geoPoint, point); } boolean newSegment = !hasLastPoint; // Assume if last point exists, it is visible boolean lastPointVisible = hasLastPoint; int slowSpeed = trackPathDescriptor.getSlowSpeed(); int normalSpeed = trackPathDescriptor.getNormalSpeed(); for (int i = startIndex; i < points.size(); ++i) { CachedLocation cachedLocation = points.get(i); // If not valid, start a new segment if (!cachedLocation.isValid()) { newSegment = true; continue; } GeoPoint geoPoint = cachedLocation.getGeoPoint(); // Check if this breaks the existing segment. boolean pointVisible = viewRect.contains(geoPoint.getLongitudeE6(), geoPoint.getLatitudeE6()); if (!pointVisible && !lastPointVisible) { // This point and the last point are both outside visible area. newSegment = true; } lastPointVisible = pointVisible; // Either update point or draw a line from the last point if (newSegment) { projection.toPixels(geoPoint, point); newSegment = false; } else { ColoredPath coloredPath; if (cachedLocation.getSpeed() <= slowSpeed) { coloredPath = new ColoredPath(slowPaint); } else if (cachedLocation.getSpeed() <= normalSpeed) { coloredPath = new ColoredPath(mediumPaint); } else { coloredPath = new ColoredPath(fastPaint); } coloredPath.getPath().moveTo(point.x, point.y); projection.toPixels(geoPoint, point); coloredPath.getPath().lineTo(point.x, point.y); coloredPaths.add(coloredPath); } } } @Override public void clearPath() { coloredPaths.clear(); } @Override public void drawPath(Canvas canvas) { for (int i = 0; i < coloredPaths.size(); i++) { ColoredPath coloredPath = coloredPaths.get(i); canvas.drawPath(coloredPath.getPath(), coloredPath.getPathPaint()); } } /** * Gets the colored paths. */ @VisibleForTesting List<ColoredPath> getColoredPaths() { return coloredPaths; } }
2,211
https://github.com/VenelinGP/EClassBook/blob/master/EClassBook.API/wwwroot/lib/spa/core/models/course.js
Github Open Source
Open Source
MIT
null
EClassBook
VenelinGP
JavaScript
Code
27
74
"use strict"; class Course { constructor(name, userId, id, teacherName) { this.Id = id; this.Name = name; this.UserId = userId; this.TeacherName = teacherName; } } exports.Course = Course;
22,628
https://github.com/Mikael-Francisco/ProjetoRPGMaker1/blob/master/RPGMaker/Views/User/Create.cshtml
Github Open Source
Open Source
MIT
2,020
ProjetoRPGMaker1
Mikael-Francisco
HTML+Razor
Code
169
872
@model RPGMaker.Models.Inserts.UserInsertViewModel @{ ViewData["Title"] = "Create"; } <h1 class="d-flex justify-content-center">CADASTRO</h1> <h4 class="d-flex justify-content-center">Inicie sua aventura!</h4> <hr /> <div class="row d-flex justify-content-center"> <div class="col-md-4"> <form asp-action="Create"> <font color="Black" face="Arial" size="5"> <div asp-validation-summary="All" class="text-danger"></div> <div class="form-group"> <label asp-for="Name" class="control-label">Nome</label> <input asp-for="Name" class="form-control" /> <span asp-validation-for="Name" name="ErrorName" id="ErrorName" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Email" class="control-label">Email</label> <input asp-for="Email" class="form-control" /> <span asp-validation-for="Email" name="ErrorEmail" id="ErrorEmail" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="BirthDate" class="control-label">Data de Nascimento</label> <input asp-for="BirthDate" class="form-control" /> <span asp-validation-for="BirthDate" typeof="date" name="ErrorBirthDate" id="ErrorBirthDate" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Password" class="control-label">Senha</label> <input asp-for="Password" class="form-control" /> <span asp-validation-for="Password" name="ErrorPassword" id="ErrorPassword" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="ConfirmPassword" class="control-label">Confirmar Senha</label> <input asp-for="ConfirmPassword" class="form-control" /> <span asp-validation-for="ConfirmPassword" name="ErrorConfirmPassword" id="ErrorConfirmPassword" class="text-danger"></span> </div> @{ string[] permission = Enum.GetNames(typeof(DTO.Enums.Permission)); } <div class="form-group"> <label class="control-label col-md-2">Conta</label> <div class="col-md-10"> <select class="form-control" name="Permission" id="Permission"> @for (int i = 0; i < permission.Length; i++) { <option value="@i">@permission[i]</option> } </select> </div> </div> <div class="form-group"> <input type="submit" value="CADASTRAR" class="btn btn-primary" /> </div> </font> </form> </div> </div> <div> <a asp-action="Index">Back to List</a> </div> @section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} }
29,708
https://github.com/CIDARLAB/magelet/blob/master/src/magelets/optMAGE_1.java
Github Open Source
Open Source
BSD-3-Clause
null
magelet
CIDARLAB
Java
Code
380
1,292
package magelets; import java.io.IOException; import java.io.PrintWriter; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class optMAGE_1 */ public class optMAGE_1 extends Magelet { private static final long serialVersionUID = 1L; private static final String validHeaders = "validate.txt"; private static final String script = "optMAGEv0.9.pl"; private static final String oligoFile = "OUToligos.txt"; private static final String dumpFile = "OUTalldump.txt"; private static final String inputParameterFileName = "INPUTparam.txt"; private static final String servletFolder ="/optMage_1/"; private static final String inputTargetFileName = "INPUTtarg.txt"; private static final String inputGenomeFileName = "genome.fasta"; /** * @see Magelet#Magelet() */ public optMAGE_1() { super(); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // ENSURE THAT THE SERVER.XML FILE HAS HTTP CONNECTOR SET TO maxPostSize="25097152" or megabytes //no longer necessary, but still a good idea- MageEditor will now deliver the genome file in smaller slices // Set response type and create an output printer response.setContentType("application/x-www-form-urlencoded"); PrintWriter out = response.getWriter(); // Get Servlet Directory String source = getDirectory(servletFolder) + "/master/"; System.out.println("POST Received"); // Load and validate parameters Map<String,String[]> parameters = load(request); try{ if (validate(source+validHeaders,parameters)) { // Extract the user ID String user_id = parameters.get("id")[0]; String directory = getDirectory(servletFolder)+"/copy"+user_id+"/" ; // Try to make a new folder TextFile.copyDirectory(source, directory ); System.out.println("Valid Headers"); TextFile.deleteIfPossible(directory+oligoFile); TextFile.deleteIfPossible(directory+dumpFile); TextFile.deleteIfPossible(directory+inputTargetFileName); TextFile.deleteIfPossible(directory+inputParameterFileName); generate(directory, inputGenomeFileName, MageEditor.GENOME, parameters); //System.out.println("Folders Made"); // Something related to the genome would go here // Execute the optMAGE script if (Boolean.valueOf(parameters.get(MageEditor.RUN)[0])){ // Generate the inputParameterFile and inputTargetFile and write those to file system generate(directory, inputParameterFileName, MageEditor.PARAMETER, parameters ); generate(directory, inputTargetFileName, MageEditor.TARGET, parameters ); execute(directory, script); } // Read the MAGE results; this.map.put( MageEditor.RESULT, TextFile.getLinesAsArray(directory+oligoFile )); this.result = this.buildURLfromMap(); // Delete the files we just created //TextFile.delete(directory+oligoFile); TextFile.deleteIfPossible(directory+dumpFile); // Something about renaming the genome file would go here. //TextFile.delete(directory+inputTargetFileName); //TextFile.delete(directory+inputParameterFileName); } //else { this.result = "Invalid Request Parameters"; } } catch (Exception EE){ StringBuilder err = new StringBuilder(EE.toString()); //get the error stream from a failed OptMage script run try{ String user_id = parameters.get("id")[0]; String directory = getDirectory(servletFolder)+"/copy"+user_id+"/" ; for (String line : TextFile.getLinesAsArray(directory+"OptMageERR.txt")){ err.append("\n" + line); } } catch(IOException e){}; EE.printStackTrace(); this.map.remove(MageEditor.ERROR); this.map.put(MageEditor.ERROR, new String[] {err.toString()}); this.result = this.buildURLfromMap(); } finally{ // Print to console and return the results out.write(this.result); //System.out.println(this.result); // Close the output Stream. out.close(); } } }
45,376
https://github.com/gizmore/gwf4/blob/master/inc/install/merge/mergefuncs.php
Github Open Source
Open Source
MIT
2,019
gwf4
gizmore
PHP
Code
694
3,180
<?php /** * @return GDO_Database */ function merge_db($argv) { $db = gdo_db_instance('localhost', $argv[1], $argv[2], $argv[3]); return $db; } function merge_usage() { echo "user pass db prefix prevar\n"; die(0); } /** * Assume all users are new. Add them to real db with a prefix_ */ function merge_core(GDO_Database $db_from, GDO_Database $db_to, array &$db_offsets, $prefix, $prevar) { GDO::setCurrentDB($db_to); merge_calc_offset($db_from, $db_to, $db_offsets, 'GWF_User'); merge_gids($db_from, $db_to, $db_offsets, $prefix, $prevar); merge_users($db_from, $db_to, $db_offsets, $prefix, $prevar); merge_add_offset($db_from, $db_to, 'GWF_UserGroup', 'ug_userid', $db_offsets['GWF_User']); merge_use_mapping($db_from, $db_to, 'GWF_UserGroup', 'ug_groupid', $db_offsets['GWF_Group']); merge_table($db_from, $db_to, 'GWF_UserGroup'); } function merge_calc_offset(GDO_Database $db_from, GDO_Database $db_to, array &$db_offsets, $classname) { GDO::setCurrentDB($db_to); $db_offsets[$classname] = GDO::table($classname)->autoIncrement(); } function merge_add_offset(GDO_Database $db_from, GDO_Database $db_to, $classname, $colname, $add) { GDO::setCurrentDB($db_from); $add = ''.($add > 0 ? '+' : '-').$add; return GDO::table($classname)->update("`$colname` = `$colname` $add", "`$colname` > 0"); } function merge_use_mapping(GDO_Database $db_from, GDO_Database $db_to, $classname, $colname, array $map, $numerical=true) { GDO::setCurrentDB($db_from); $table = GDO::table($classname); foreach ($map as $from => $to) { if (Common::isNumeric($from)) { if (false === $table->update("`$colname` = 0x40000000|$to", "`$colname` = $from")) { return false; } } } return $table->update("`$colname` = `$colname` - 0x40000000", "`$colname` >= 0x40000000"); } function merge_clear_column(GDO_Database $db_from, GDO_Database $db_to, $classname, $colname, $with='0') { GDO::setCurrentDB($db_from); return GDO::table($classname)->update("`$colname`=$with"); } function merge_table(GDO_Database $db_from, GDO_Database $db_to, $classname) { GWF_Cronjob::notice(sprintf('Merging table %s', $classname)); GDO::setCurrentDB($db_from); $fromtable = GDO::table($classname); if (false === ($result = $fromtable->select('*'))) { return false; } GDO::setCurrentDB($db_to); $totable = GDO::table($classname); while (false !== ($row = $fromtable->fetch($result))) { GWF_Cronjob::notice(sprintf('Merging table %s ID %s', $classname, reset($row))); $totable->insertAssoc($row, GDO::ARRAY_A); } $fromtable->free($result); return true; } function merge_fix_uname(GDO_Database $db_from, GDO_Database $db_to, array &$db_offsets, $classname, $colname) { GDO::setCurrentDB($db_from); $table = GDO::table($classname); if (false === ($result = $table->select('*'))) { echo GWF_Error::err('ERR_DATABASE', array(__FILE__, __LINE__)); return false; } while (false !== ($row = $table->fetch($result, GDO::ARRAY_O))) { $oldname = $row->getVar($colname); if (isset($db_offsets['user_name'][$oldname])) { $row->saveVar($colname, $db_offsets['user_name'][$oldname]); } } $table->free($result); } function merge_fix_uid_blob(GDO_Database $db_from, GDO_Database $db_to, array &$db_offsets, $classname, $colname, $splitter=':') { GDO::setCurrentDB($db_from); $table = GDO::table($classname); if (false === ($result = $table->select('*'))) { echo GWF_Error::err('ERR_DATABASE', array(__FILE__, __LINE__)); return false; } $offset = $db_offsets['GWF_User']; while (false !== ($row = $table->fetch($result, GDO::ARRAY_O))) { $col = $row->getVar($colname); if ($col !== $splitter) { $newcol = $splitter; $uids = explode($splitter, $col); foreach ($uids as $uid) { $uid += $offset; $newcol .= $uid.$splitter; } $row->saveVar($colname, $newcol); } } $table->free($result); } function merge_fix_uname_blob(GDO_Database $db_from, GDO_Database $db_to, array &$db_offsets, $classname, $colname, $splitter=':') { GDO::setCurrentDB($db_from); $table = GDO::table($classname); if (false === ($result = $table->select('*'))) { echo GWF_Error::err('ERR_DATABASE', array(__FILE__, __LINE__)); return false; } while (false !== ($row = $table->fetch($result, GDO::ARRAY_O))) { $col = $row->getVar($colname); if ($col !== $splitter) { $newcol = $splitter; $names = explode($splitter, $col); foreach ($names as $name) { if (isset($db_offsets['user_name'][$name])) { $newcol .= $db_offsets['user_name'][$name]; } else { $newcol .= $name; } $newcol .= $splitter; } $row->saveVar($colname, $newcol); } } $table->free($result); } function merge_gids(GDO_Database $db_from, GDO_Database $db_to, array &$db_offsets, $prefix, $prevar) { $db_offsets['GWF_Group'] = array(); GDO::setCurrentDB($db_from); $fromgroups = GDO::table('GWF_Group'); if (false === ($result = $fromgroups->select('*', '', 'group_id ASC'))) { echo GWF_Error::err('ERR_DATABASE', array(__FILE__, __LINE__)); return false; } GDO::setCurrentDB($db_to); $togroups = GDO::table('GWF_Group'); while (false !== ($row = $fromgroups->fetch($result, GDO::ARRAY_A))) { $gname = $row['group_name']; $egname = GDO::escape($gname); if (false === ($oldgid = $togroups->selectVar('group_id', "group_name='$egname'"))) { $row['group_id'] = '0'; $togroups->insertAssoc($row); // $db_offsets['GWF_Group'][$gname] = $db_to->insertID(); $newgid = $db_to->insertID(); $db_offsets['GWF_Group'][(string)$row['group_id']] = $newgid; GWF_Cronjob::log("Group {$row['group_id']} => $newgid"); } else { // $db_offsets['GWF_Group'][$gname] = $oldgid; $db_offsets['GWF_Group'][(string)$row['group_id']] = $oldgid; GWF_Cronjob::log("Group {$row['group_id']} => $oldgid"); } } } function merge_users(GDO_Database $db_from, GDO_Database $db_to, array &$db_offsets, $prefix, $prevar) { $db_offsets['user_name'] = array(); GDO::setCurrentDB($db_from); $users = GDO::table('GWF_User'); if (false === ($result = $users->select('*', '', 'user_id ASC'))) { echo GWF_Error::err('ERR_DATABASE', array(__FILE__, __LINE__)); return false; } GDO::setCurrentDB($db_to); $to_users = GDO::table('GWF_User'); $off = $db_offsets['GWF_User']; while (false !== ($user = $users->fetch($result, GDO::ARRAY_A))) { $oldname = $user['user_name']; $newname = merge_user_name($user['user_name'], $to_users, $prefix, $prevar); $user['user_name'] = $newname; if ($oldname !== $newname) { $db_offsets['user_name'][$oldname] = $newname; } $user['user_id'] += $off; $to_users->insertAssoc($user); GWF_Cronjob::log('Added user '.$user['user_name'].' with id '.$user['user_id']); } $users->free($result); return true; } function merge_user_name($oldname, GDO $to_users, $prefix, $prevar) { // Try with prefix $oldname = $prefix.$oldname; $eoldname = GDO::escape($oldname); if (false === $to_users->selectVar('1', "user_name='$eoldname'")) { return $oldname; } // Try with prevar $oldname = $prevar.$oldname; $eoldname = GDO::escape($oldname); if (false === $to_users->selectVar('1', "user_name='$eoldname'")) { return $oldname; } // now while with numbers $n = 2; while (true) { $name = $oldname.$n; $eoldname = GDO::escape($name); if (false === $to_users->selectVar('1', "user_name='$eoldname'")) { return $name; } $n++; } }
24,345
https://github.com/vincentyang01/ruby-oo-relationships-practice-mini-mock-code-challenge/blob/master/console.rb
Github Open Source
Open Source
LicenseRef-scancode-public-domain, LicenseRef-scancode-unknown-license-reference
2,020
ruby-oo-relationships-practice-mini-mock-code-challenge
vincentyang01
Ruby
Code
43
183
require 'pry' require_relative './painter' require_relative './artwork' require_relative './painter_artwork' painter1 = Painter.new("ace", 10) painter2 = Painter.new("bob", 20) painter3 = Painter.new("cal", 30) artwork1 = Artwork.new("Mona Lisa") artwork2 = Artwork.new("Trees") artwork3 = Artwork.new("Grove") pa1 = Painter_Artwork.new(painter1, artwork1) pa2 = Painter_Artwork.new(painter2, artwork2) pa3 = Painter_Artwork.new(painter3, artwork3) binding.pry
49,274
https://github.com/chandusekhar/UMaMES/blob/master/uma-mes/src/main/java/me/zhengjie/uma_mes/service/ChemicalFiberProductionService.java
Github Open Source
Open Source
Apache-2.0
2,020
UMaMES
chandusekhar
Java
Code
117
588
package me.zhengjie.uma_mes.service; import com.lgmn.common.result.Result; import me.zhengjie.uma_mes.domain.ChemicalFiberProduction; import me.zhengjie.uma_mes.service.dto.ChemicalFiberProductionDTO; import me.zhengjie.uma_mes.service.dto.ChemicalFiberProductionQueryCriteria; import me.zhengjie.uma_mes.service.dto.ChemicalFiberProductionSetMachinesDTO; import me.zhengjie.uma_mes.service.dto.ChemicalFiberProductionSetProductionStatusDTO; import org.springframework.data.domain.Pageable; import java.util.Map; import java.util.List; import java.io.IOException; import javax.servlet.http.HttpServletResponse; /** * @author Tan Jun Ming * @date 2019-11-20 */ public interface ChemicalFiberProductionService { /** * 查询数据分页 * @param criteria 条件参数 * @param pageable 分页参数 * @return Map<String,Object> */ Map<String,Object> queryAll(ChemicalFiberProductionQueryCriteria criteria, Pageable pageable); /** * 查询所有数据不分页 * @param criteria 条件参数 * @return List<ChemicalFiberProductionDTO> */ List<ChemicalFiberProductionDTO> queryAll(ChemicalFiberProductionQueryCriteria criteria); /** * 根据ID查询 * @param id ID * @return ChemicalFiberProductionDTO */ ChemicalFiberProductionDTO findById(Integer id); ChemicalFiberProductionDTO create(ChemicalFiberProduction resources); void update(ChemicalFiberProduction resources); void delete(Integer id); void download(List<ChemicalFiberProductionDTO> all, HttpServletResponse response) throws IOException; ChemicalFiberProduction setMachines(ChemicalFiberProductionSetMachinesDTO resources); ChemicalFiberProduction setProductionStatus(ChemicalFiberProductionSetProductionStatusDTO resources); Map<String,Object> getProductionReport(ChemicalFiberProductionQueryCriteria criteria, Pageable pageable); Result getProductionReportSummaries(ChemicalFiberProductionQueryCriteria criteria); }
7,433
https://github.com/frol/trek/blob/master/trek/src/lib.rs
Github Open Source
Open Source
MIT, Apache-2.0
2,019
trek
frol
Rust
Code
193
658
use hyper::{ service::{make_service_fn, service_fn}, Body, Error, Response, Server, }; use std::sync::Arc; use trek_core::context::Context; use trek_router::router::Router; pub struct App<State> { state: Arc<State>, router: Arc<Router<Context<State>>>, } impl App<()> { pub fn new() -> App<()> { Self { state: Arc::new(()), router: Arc::new(Router::new()), } } } impl Default for App<()> { fn default() -> App<()> { Self::new() } } impl<State: Send + Sync + 'static> App<State> { pub fn with_state(state: State) -> Self { Self { state: Arc::new(state), router: Arc::new(Router::new()), } } pub fn router(&mut self) -> &mut Router<Context<State>> { Arc::get_mut(&mut self.router).unwrap() } pub async fn run(self, addr: impl std::net::ToSocketAddrs) -> std::io::Result<()> { let addr = addr .to_socket_addrs()? .next() .ok_or(std::io::ErrorKind::InvalidInput)?; let server = Server::bind(&addr).serve(make_service_fn(move |_| { let state = self.state.clone(); let router = self.router.clone(); async move { Ok::<_, Error>(service_fn(move |req| { let path = req.uri().path().to_owned(); let method = req.method().to_owned(); let res = match router.find(method, &path) { Some((m, p)) => { let cx = Context::new( state.clone(), req, p.iter() .map(|(k, v)| (k.to_string(), v.to_string())) .collect(), m.to_vec(), ); cx.next() } None => Box::pin(async move { Response::builder().status(404).body(Body::empty()).unwrap() }), }; async move { Ok::<_, Error>(res.await) } })) } })); if let Err(e) = server.await { eprintln!("server error: {}", e); } Ok(()) } }
9,553
https://github.com/snake0/barrelfish_sysbench/blob/master/lib/devif/backends/debug/devif_backend_debug.c
Github Open Source
Open Source
MIT
null
barrelfish_sysbench
snake0
C
Code
2,952
8,559
/* * Copyright (c) 2007, 2008, 2009, 2010, 2011, 2012, ETH Zurich. * All rights reserved. * * This file is distributed under the terms in the attached LICENSE file. * If you do not find this file, copies can be found by writing to: * ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group. */ #include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include <barrelfish/barrelfish.h> #include <barrelfish/waitset.h> #include <devif/queue_interface.h> #include <devif/queue_interface_backend.h> #include <devif/backends/debug.h> #include "debug.h" #define HIST_SIZE 128 #define MAX_STR_SIZE 128 /* * This is a debugging interface for the device queue interface that * can be used with any existing queue. It can be stacked on top * to check for non valid buffer enqueues/deqeues that might happen. * A not valid enqueue of a buffer is when the endpoint that enqueues * the buffer does not own the buffer. * * We keep track of the owned buffers as a list of regions which each * contains a list of memory chunks. * Each chunk specifies a offset within the region and its length. * * When a region is registered, we add one memory chunk that describes * the whole region i.e. offset=0 length= length of region * * If a a buffer is enqueued, it has to be contained in one of these * memory chunks. The memory chunk is then altered according how * the buffer is contained in the chunk. If it is at the beginning or * end of the chunk, the offset/length of the chunk is changed accordingly * If the buffer is in the middle of the chunk, we split the memory chunk * into two new memory chunks that do not contain the buffer. * * If a buffer is dequeued the buffer is added to the existing memory * chunks if possible, otherwise a new memory chunk is added to the * list of chunks. If a buffer is dequeued that is in between two * memory chunks, the memory chunks are merged to one big chunk. * We might fail to find the region id in our list of regions. In this * case we add the region with the deqeued offset+length as a size. * We can be sure that this region exists since the devq library itself * does these checks if the region is known to the endpoint. This simply * means the debugging queue on top of the other queue does not have a * consistant view of the registered regions (but the queue below does) * * When a region is deregistered, the list of chunks has to only * contain a single chunk that descirbes the whole region. Otherwise * the call will fail since some of the buffers are still in use. * */ struct memory_ele { genoffset_t offset; genoffset_t length; struct memory_ele* next; struct memory_ele* prev; }; struct memory_list { regionid_t rid; genoffset_t length; // is a region that we did not register ourselves bool not_consistent; struct memory_ele* buffers; struct memory_list* next; // next in list of lists }; struct operation { char str[MAX_STR_SIZE]; genoffset_t offset; genoffset_t length; }; struct debug_q { struct devq my_q; struct devq* q; struct memory_list* regions; // list of lists struct slab_allocator alloc; struct slab_allocator alloc_list; uint16_t hist_head; struct operation history[HIST_SIZE]; }; static void dump_list(struct memory_list* region) { struct memory_ele* ele = region->buffers; int index = 0; printf("================================================ \n"); while (ele != NULL) { printf("Idx=%d offset=%lu length=%lu", index, ele->offset, ele->length); if (ele->prev != NULL) { printf(" prev->offset=%lu prev->length=%lu", ele->prev->offset, ele->prev->length); } printf(" \n"); ele = ele->next; index++; } printf("================================================ \n"); } // checks if there are elements in the list that should be merged static void check_consistency(struct memory_list* region) { struct memory_ele* ele = region->buffers; while (ele->next != NULL) { if (ele->offset + ele->length == ele->next->offset) { printf("offset=%lu length=%lu \n", ele->offset, ele->length); dump_list(region); USER_PANIC("Found entry that should be merged \n"); } ele = ele->next; } } static void add_to_history(struct debug_q* q, genoffset_t offset, genoffset_t length, char* s) { q->history[q->hist_head].offset = offset; q->history[q->hist_head].length = length; strncpy(q->history[q->hist_head].str, s, MAX_STR_SIZE); q->hist_head = (q->hist_head + 1) % HIST_SIZE; } static void dump_history(struct debug_q* q) { for (int i = 0; i < HIST_SIZE; i++) { printf("offset=%lu length=%lu %s\n", q->history[q->hist_head].offset, q->history[q->hist_head].length, q->history[q->hist_head].str); q->hist_head = (q->hist_head + 1) % HIST_SIZE; } } /* static bool in_list(struct memory_list* region, genoffset_t offset, genoffset_t length) { struct memory_ele* ele = region->buffers; while (ele != NULL) { if (offset >= ele->offset && offset + length <= ele->offset+ele->length) { return true; } ele = ele->next; } return false; } */ static errval_t debug_register(struct devq* q, struct capref cap, regionid_t rid) { errval_t err; struct debug_q* que = (struct debug_q*) q; DEBUG("Register \n"); struct frame_identity id; err = invoke_frame_identify(cap, &id); if (err_is_fail(err)) { return err; } // queue of regions is empty if (que->regions == NULL) { // add the reigon err = que->q->f.reg(que->q, cap, rid); if (err_is_fail(err)) { return err; } que->regions = slab_alloc(&que->alloc_list); assert(que->regions != NULL); que->regions->rid = rid; que->regions->length = id.bytes; que->regions->not_consistent = false; que->regions->next = NULL; // add the whole regions as a buffer que->regions->buffers = slab_alloc(&que->alloc); assert(que->regions->buffers != NULL); memset(que->regions->buffers, 0, sizeof(que->regions->buffers)); que->regions->buffers->offset = 0; que->regions->buffers->length = id.bytes; que->regions->buffers->next = NULL; DEBUG("Register rid=%"PRIu32" size=%"PRIu64" \n", rid, id.bytes); return SYS_ERR_OK; } struct memory_list* ele = que->regions; while (ele->next != NULL) { ele = ele->next; } err = que->q->f.reg(que->q, cap, rid); if (err_is_fail(err)) { return err; } // add the reigon ele->next = slab_alloc(&que->alloc_list); assert(ele->next != NULL); ele = ele->next; ele->rid = rid; ele->next = NULL; ele->length = id.bytes; ele->not_consistent = false; // add the whole regions as a buffer ele->buffers = slab_alloc(&que->alloc); assert(ele->buffers != NULL); memset(ele->buffers, 0, sizeof(ele->buffers)); ele->buffers->offset = 0; ele->buffers->length = id.bytes; ele->buffers->next = NULL; DEBUG("Register rid=%"PRIu32" size=%"PRIu64" \n", rid, id.bytes); return SYS_ERR_OK; } static errval_t debug_deregister(struct devq* q, regionid_t rid) { DEBUG("Deregister \n"); struct debug_q* que = (struct debug_q*) q; errval_t err; struct memory_list* ele = que->regions; if (ele == NULL) { return DEVQ_ERR_INVALID_REGION_ID; } // remove head if (ele->rid == rid) { // there should only be a single element in the list // i.e. the whole region if (ele->buffers->offset == 0 && ele->buffers->length == ele->length && ele->buffers->next == NULL) { err = que->q->f.dereg(que->q, rid); if (err_is_fail(err)) { return err; } que->regions = ele->next; DEBUG("removed region rid=%"PRIu32" size=%"PRIu64" \n", rid, ele->length); slab_free(&que->alloc, ele->buffers); slab_free(&que->alloc_list, ele); return SYS_ERR_OK; } else { DEBUG("Destroy error rid=%d offset=%"PRIu64" length=%"PRIu64" " "should be offset=0 length=%"PRIu64"\n", ele->rid, ele->buffers->offset, ele->buffers->length, ele->length); dump_list(ele); return DEVQ_ERR_REGION_DESTROY; } } while (ele->next != NULL) { if (ele->next->rid == rid) { if (ele->next->buffers->offset == 0 && ele->next->buffers->length == ele->next->length && ele->next->buffers->next == NULL) { err = que->q->f.dereg(que->q, rid); if (err_is_fail(err)) { return err; } // remove from queue struct memory_list* next = ele->next; ele->next = ele->next->next; DEBUG("removed region rid=%"PRIu32" size=%"PRIu64" \n", rid, next->length); slab_free(&que->alloc, next->buffers); slab_free(&que->alloc_list, next); return SYS_ERR_OK; } else { DEBUG("Destroy error rid=%d offset=%"PRIu64" length=%"PRIu64" " "should be offset=0 length=%"PRIu64"\n", ele->next->rid, ele->next->buffers->offset, ele->next->buffers->length, ele->next->length); dump_list(ele); return DEVQ_ERR_REGION_DESTROY; } } else { ele = ele->next; } } return DEVQ_ERR_INVALID_REGION_ID; } static errval_t debug_control(struct devq* q, uint64_t cmd, uint64_t value, uint64_t* result) { DEBUG("control \n"); struct debug_q* que = (struct debug_q*) q; return que->q->f.ctrl(que->q, cmd, value, result); } static errval_t debug_notify(struct devq* q) { DEBUG("notify \n"); struct debug_q* que = (struct debug_q*) q; return que->q->f.notify(que->q); } // is b1 in bounds of b2? static bool buffer_in_bounds(genoffset_t offset_b1, genoffset_t len_b1, genoffset_t offset_b2, genoffset_t len_b2) { return (offset_b1 >= offset_b2) && (len_b1 <= len_b2) && ((offset_b1 + len_b1) <= offset_b2 + len_b2); } // assumes that the buffer described by offset and length is contained // in the buffer that is given as a struct static void remove_split_buffer(struct debug_q* que, struct memory_list* region, struct memory_ele* buffer, genoffset_t offset, genoffset_t length) { // split the buffer // insert half before the buffer DEBUG("enqueue offset=%"PRIu64" length=%"PRIu64" buf->offset=%lu " "buf->length %lu \n", offset, length, buffer->offset, buffer->length); // check if buffer at beginning of region if (buffer->offset == offset) { buffer->offset += length; buffer->length -= length; if (buffer->length == 0) { add_to_history(que, offset, length, "enq cut of beginning remove"); DEBUG("enqueue remove buffer from list\n"); // remove if (buffer->prev != NULL) { buffer->prev->next = buffer->next; } else { region->buffers = buffer->next; } if (buffer->next != NULL) { buffer->next->prev = buffer->prev; } slab_free(&que->alloc, buffer); } else { add_to_history(que, offset, length, "enq cut of beginning"); } DEBUG("enqueue first cut off begining results in offset=%"PRIu64" " "length=%"PRIu64"\n", buffer->offset, buffer->length); return; } // check if buffer at end of region if ((buffer->offset+buffer->length) == (offset+length)) { buffer->length -= length; if (buffer->length == 0) { add_to_history(que, offset, length, "enq cut of end remove"); // remove if (buffer->prev != NULL) { buffer->prev = buffer->next; } if (buffer->next != NULL) { buffer->next->prev = buffer->prev; } slab_free(&que->alloc, buffer); } else { add_to_history(que, offset, length, "enq cut of end"); } DEBUG("enqueue first cut off end results in offset=%"PRIu64" " "length=%"PRIu64"\n", buffer->offset, buffer->length); return; } // now if this did not work need to split buffer that contains the // enqueued buffer into two buffers (might also result only in one) // inset half before buffer genoffset_t old_len = buffer->length; buffer->length = offset - buffer->offset; struct memory_ele* after = NULL; after = slab_alloc(&que->alloc); assert(after != NULL); memset(after, 0, sizeof(after)); after->offset = buffer->offset + buffer->length + length; after->length = old_len - buffer->length - length; // insert after buffer after->prev = buffer; after->next = buffer->next; if (buffer->next != NULL) { buffer->next->prev = after; } buffer->next = after; add_to_history(que, offset, length, "enq split buffer"); DEBUG("Split buffer length=%lu to " "offset=%"PRIu64" length=%"PRIu64" and " "offset=%lu length=%lu \n", old_len, buffer->offset, buffer->length, after->offset, after->length); } /* * Inserts a buffer either before or after an existing buffer into the queue * Checks for merges of prev/next buffer in the queue */ static void insert_merge_buffer(struct debug_q* que, struct memory_list* region, struct memory_ele* buffer, genoffset_t offset, genoffset_t length) { assert(buffer != NULL); assert(region != NULL); if (offset >= buffer->offset+buffer->length) {// insert after // buffer is on lower boundary // if (buffer->offset+length == offset) { buffer->length += length; DEBUG("dequeue merge after " "offset=%"PRIu64" length=%"PRIu64" to offset=%"PRIu64" " "length=%"PRIu64"\n", offset, length, buffer->offset, buffer->length); // check other boundary for merge if (buffer->next != NULL && (buffer->offset + buffer->length == buffer->next->offset)) { buffer->length += buffer->next->length; struct memory_ele* next = buffer->next; if (buffer->next->next != NULL) { buffer->next = buffer->next->next; buffer->next->next->prev = buffer; } DEBUG("dequeue merge after more offset=%"PRIu64" " "length=%"PRIu64" to offset=%"PRIu64" length=%"PRIu64" \n ", next->offset, next->length, buffer->offset, buffer->length); add_to_history(que, offset, length, "deq insert after" " on lower boundary and merge"); slab_free(&que->alloc, next); } else { add_to_history(que, offset, length, "deq insert after on lower boundary"); } } else { // check higher boundary if (buffer->next != NULL && buffer->next->offset == offset+length) { buffer->next->offset = offset; buffer->next->length += length; DEBUG("dequeue merge after more offset=%"PRIu64" " "length=%"PRIu64" to offset=%"PRIu64" length=%"PRIu64" \n ", offset, length, buffer->next->offset, buffer->next->length); add_to_history(que, offset, length, "deq insert after" " on higer boundary"); } else { // buffer->next can be null and the newly inserted buffer // is the inserted at the end -> check boundary if (buffer->next == NULL && buffer->offset + buffer->length == offset) { buffer->length += length; add_to_history(que, offset, length, "deq insert after" " on higer boundary end"); DEBUG("dequeue insert after merged offset=%"PRIu64" " "length=%"PRIu64" " "to offset=%"PRIu64" length=%"PRIu64" \n", offset, length, buffer->offset, buffer->length); } else { // insert in between struct memory_ele* ele = slab_alloc(&que->alloc); assert(ele != NULL); ele->offset = offset; ele->length = length; ele->next = buffer->next; ele->prev = buffer; if (buffer->next != NULL) { buffer->next->prev = ele; } buffer->next = ele; add_to_history(que, offset, length, "deq insert after" " in between"); DEBUG("dequeue insert after offset=%"PRIu64" length=%"PRIu64" " "after offset=%"PRIu64" length=%"PRIu64" \n", offset, length, buffer->offset, buffer->length); } } } } else { // insert before buffer // buffer is on lower boundary if (buffer->offset == offset+length) { buffer->length += length; buffer->offset = offset; // check other boundary if (buffer->prev != NULL && (buffer->prev->offset+ buffer->prev->length == buffer->offset)) { struct memory_ele* prev = buffer->prev; prev->length += buffer->length; prev->next = buffer->next; if (buffer->next != NULL) { buffer->next->prev = prev; } slab_free(&que->alloc, buffer); add_to_history(que, offset, length, "deq insert buffer" " before lower boundary merge"); DEBUG("dequeue merge before more offset=%"PRIu64" " "length=%"PRIu64" to offset=%"PRIu64" length=%"PRIu64" \n ", offset, length, prev->offset, prev->length); } else { add_to_history(que, offset, length, "deq insert buffer" " before lower boundary"); } } else { // check lower boundary if (buffer->prev != NULL && (buffer->prev->offset+ buffer->prev->length == offset)) { if (length == 0) { printf("Length is 0 \n"); buffer->prev->length += 2048; } buffer->prev->length += length; add_to_history(que, offset, length, "deq insert buffer" " before prev lower boundary merge"); DEBUG("dequeue merge before more offset=%"PRIu64" " "length=%"PRIu64" to offset=%"PRIu64" length=%"PRIu64" \n ", offset, length, buffer->prev->offset, buffer->prev->length); } else { // insert in between // insert in between struct memory_ele* ele = slab_alloc(&que->alloc); assert(ele != NULL); memset(ele, 0, sizeof(ele)); ele->offset = offset; ele->length = length; ele->next = buffer; ele->prev = buffer->prev; if (buffer->prev != NULL) { buffer->prev->next = ele; } else { region->buffers = ele; } buffer->prev = ele; add_to_history(que, offset, length, "deq insert buffer" " before in between"); DEBUG("dequeue insert before offset=%"PRIu64" length=%"PRIu64" " "next is offset=%"PRIu64" length=%"PRIu64" \n", offset, length, buffer->offset, buffer->length); } } } } static errval_t find_region(struct debug_q* que, struct memory_list** list, regionid_t rid) { // find region struct memory_list* region = que->regions; while (region != NULL) { if (region->rid == rid) { break; } region = region->next; } // check if we found the region if (region == NULL) { return DEVQ_ERR_INVALID_REGION_ID; } *list = region; return SYS_ERR_OK; } static errval_t debug_enqueue(struct devq* q, regionid_t rid, genoffset_t offset, genoffset_t length, genoffset_t valid_data, genoffset_t valid_length, uint64_t flags) { assert(length > 0); DEBUG("enqueue offset %"PRIu64" \n", offset); errval_t err; struct debug_q* que = (struct debug_q*) q; // find region struct memory_list* region = NULL; err = find_region(que, &region, rid); if (err_is_fail(err)){ return err; } check_consistency(region); // find the buffer struct memory_ele* buffer = region->buffers; if (region->buffers == NULL) { return DEVQ_ERR_BUFFER_ALREADY_IN_USE; } // the only buffer if (buffer->next == NULL) { if (buffer_in_bounds(offset, length, buffer->offset, buffer->length)) { err = que->q->f.enq(que->q, rid, offset, length, valid_data, valid_length, flags); if (err_is_fail(err)) { return err; } remove_split_buffer(que, region, buffer, offset, length); return SYS_ERR_OK; } else { printf("Bounds check failed only buffer offset=%lu length=%lu " " buf->offset=%lu buf->len=%lu\n", offset, length, buffer->offset, buffer->length); dump_history(que); dump_list(region); return DEVQ_ERR_INVALID_BUFFER_ARGS; } } // more than one buffer while (buffer != NULL) { if (buffer_in_bounds(offset, length, buffer->offset, buffer->length)){ err = que->q->f.enq(que->q, rid, offset, length, valid_data, valid_length, flags); if (err_is_fail(err)) { return err; } remove_split_buffer(que, region, buffer, offset, length); return SYS_ERR_OK; } buffer = buffer->next; } printf("Did not find region offset=%ld length=%ld \n", offset, length); dump_history(que); dump_list(region); return DEVQ_ERR_INVALID_BUFFER_ARGS; } static errval_t debug_dequeue(struct devq* q, regionid_t* rid, genoffset_t* offset, genoffset_t* length, genoffset_t* valid_data, genoffset_t* valid_length, uint64_t* flags) { errval_t err; struct debug_q* que = (struct debug_q*) q; assert(que->q->f.deq != NULL); err = que->q->f.deq(que->q, rid, offset, length, valid_data, valid_length, flags); if (err_is_fail(err)) { return err; } DEBUG("dequeued offset=%lu \n", *offset); struct memory_list* region = NULL; err = find_region(que, &region, *rid); if (err_is_fail(err)){ // region ids are checked bythe devq library, if we do not find // the region id when dequeueing here we do not have a consistant // view of two endpoints // // Add region if (que->regions == NULL) { printf("Adding region frirst %lu len \n", *offset + *length); que->regions = slab_alloc(&que->alloc_list); assert(que->regions != NULL); que->regions->rid = *rid; que->regions->not_consistent = true; // region is at least offset + length que->regions->length = *offset + *length; que->regions->next = NULL; // add the whole regions as a buffer que->regions->buffers = slab_alloc(&que->alloc); assert(que->regions->buffers != NULL); memset(que->regions->buffers, 0, sizeof(que->regions->buffers)); que->regions->buffers->offset = 0; que->regions->buffers->length = *offset + *length; que->regions->buffers->next = NULL; return SYS_ERR_OK; } struct memory_list* ele = que->regions; while (ele->next != NULL) { ele = ele->next; } printf("Adding region second %lu len \n", *offset + *length); // add the reigon ele->next = slab_alloc(&que->alloc_list); assert(ele->next != NULL); memset(que->regions->buffers, 0, sizeof(ele->next)); ele = ele->next; ele->rid = *rid; ele->next = NULL; ele->not_consistent = true; ele->length = *offset + *length; // add the whole regions as a buffer ele->buffers = slab_alloc(&que->alloc); assert(ele->buffers != NULL); memset(ele->buffers, 0, sizeof(ele->buffers)); ele->buffers->offset = 0; ele->buffers->length = *offset + *length; ele->buffers->next = NULL; return SYS_ERR_OK; } if (region->not_consistent) { if ((*offset + *length) > region->length) { region->length = *offset + *length; } } //check_consistency(region); // find the buffer struct memory_ele* buffer = region->buffers; if (buffer == NULL) { region->buffers = slab_alloc(&que->alloc); assert(region->buffers != NULL); region->buffers->offset = *offset; region->buffers->length = *length; region->buffers->next = NULL; region->buffers->prev = NULL; return SYS_ERR_OK; } if (buffer->next == NULL) { if (!buffer_in_bounds(*offset, *length, buffer->offset, buffer->length)) { insert_merge_buffer(que, region, buffer, *offset, *length); return SYS_ERR_OK; } else { return DEVQ_ERR_BUFFER_NOT_IN_USE; } } while (buffer->next != NULL) { if (*offset >= buffer->offset) { buffer = buffer->next; } else { if (!buffer_in_bounds(*offset, *length, buffer->offset, buffer->length)) { insert_merge_buffer(que, region, buffer, *offset, *length); return SYS_ERR_OK; } else { return DEVQ_ERR_BUFFER_NOT_IN_USE; } } } // insert after the last buffer if (!buffer_in_bounds(*offset, *length, buffer->offset, buffer->length)) { insert_merge_buffer(que, region, buffer, *offset, *length); return SYS_ERR_OK; } return DEVQ_ERR_BUFFER_NOT_IN_USE; } static errval_t debug_destroy(struct devq* devq) { // TODO cleanup return SYS_ERR_OK; } /** * Public functions * */ errval_t debug_create(struct debug_q** q, struct devq* other_q) { errval_t err; struct debug_q* que; que = calloc(1, sizeof(struct debug_q)); assert(que); slab_init(&que->alloc, sizeof(struct memory_ele), slab_default_refill); slab_init(&que->alloc_list, sizeof(struct memory_list), slab_default_refill); que->q = other_q; err = devq_init(&que->my_q, false); if (err_is_fail(err)) { return err; } que->my_q.f.reg = debug_register; que->my_q.f.dereg = debug_deregister; que->my_q.f.ctrl = debug_control; que->my_q.f.notify = debug_notify; que->my_q.f.enq = debug_enqueue; que->my_q.f.deq = debug_dequeue; que->my_q.f.destroy = debug_destroy; *q = que; return SYS_ERR_OK; } errval_t debug_dump_region(struct debug_q* que, regionid_t rid) { errval_t err; // find region struct memory_list* region = NULL; err = find_region(que, &region, rid); if (err_is_fail(err)){ return err; } dump_list(region); return SYS_ERR_OK; } void debug_dump_history(struct debug_q* q) { dump_history(q); } errval_t debug_add_region(struct debug_q* q, struct capref cap, regionid_t rid) { return devq_add_region((struct devq*) q, cap, rid); } errval_t debug_remove_region(struct debug_q* q, regionid_t rid) { return devq_remove_region((struct devq*) q, rid); }
7,270