docstring
stringlengths 52
499
| function
stringlengths 67
35.2k
| __index_level_0__
int64 52.6k
1.16M
|
---|---|---|
Returns a function that checkes whether a number belongs to an interval.
Args:
interval: A tensorboard.hparams.Interval protobuf describing the interval.
Returns:
A function taking a number (a float or an object of a type in
six.integer_types) that returns True if the number belongs to (the closed)
'interval'. | def _create_interval_filter(interval):
def filter_fn(value):
if (not isinstance(value, six.integer_types) and
not isinstance(value, float)):
raise error.HParamsError(
'Cannot use an interval filter for a value of type: %s, Value: %s' %
(type(value), value))
return interval.min_value <= value and value <= interval.max_value
return filter_fn | 58,044 |
Sets the metrics for session_group to those of its "median session".
The median session is the session in session_group with the median value
of the metric given by 'aggregation_metric'. The median is taken over the
subset of sessions in the group whose 'aggregation_metric' was measured
at the largest training step among the sessions in the group.
Args:
session_group: A SessionGroup protobuffer.
aggregation_metric: A MetricName protobuffer. | def _set_median_session_metrics(session_group, aggregation_metric):
measurements = sorted(_measurements(session_group, aggregation_metric),
key=operator.attrgetter('metric_value.value'))
median_session = measurements[(len(measurements) - 1) // 2].session_index
del session_group.metric_values[:]
session_group.metric_values.MergeFrom(
session_group.sessions[median_session].metric_values) | 58,047 |
A generator for the values of the metric across the sessions in the group.
Args:
session_group: A SessionGroup protobuffer.
metric_name: A MetricName protobuffer.
Yields:
The next metric value wrapped in a _Measurement instance. | def _measurements(session_group, metric_name):
for session_index, session in enumerate(session_group.sessions):
metric_value = _find_metric_value(session, metric_name)
if not metric_value:
continue
yield _Measurement(metric_value, session_index) | 58,049 |
Constructor.
Args:
context: A backend_context.Context instance.
request: A ListSessionGroupsRequest protobuf. | def __init__(self, context, request):
self._context = context
self._request = request
self._extractors = _create_extractors(request.col_params)
self._filters = _create_filters(request.col_params, self._extractors)
# Since an context.experiment() call may search through all the runs, we
# cache it here.
self._experiment = context.experiment() | 58,050 |
This function converts the MP3 files stored in a folder to WAV. If required, the output names of the WAV files are based on MP3 tags, otherwise the same names are used.
ARGUMENTS:
- dirName: the path of the folder where the MP3s are stored
- Fs: the sampling rate of the generated WAV files
- nC: the number of channels of the generated WAV files
- useMp3TagsAsName: True if the WAV filename is generated on MP3 tags | def convertDirMP3ToWav(dirName, Fs, nC, useMp3TagsAsName = False):
types = (dirName+os.sep+'*.mp3',) # the tuple of file types
filesToProcess = []
for files in types:
filesToProcess.extend(glob.glob(files))
for f in filesToProcess:
#tag.link(f)
audioFile = eyed3.load(f)
if useMp3TagsAsName and audioFile.tag != None:
artist = audioFile.tag.artist
title = audioFile.tag.title
if artist!=None and title!=None:
if len(title)>0 and len(artist)>0:
wavFileName = ntpath.split(f)[0] + os.sep + artist.replace(","," ") + " --- " + title.replace(","," ") + ".wav"
else:
wavFileName = f.replace(".mp3",".wav")
else:
wavFileName = f.replace(".mp3",".wav")
else:
wavFileName = f.replace(".mp3",".wav")
command = "avconv -i \"" + f + "\" -ar " +str(Fs) + " -ac " + str(nC) + " \"" + wavFileName + "\"";
print(command)
os.system(command.decode('unicode_escape').encode('ascii','ignore').replace("\0","")) | 58,086 |
This function converts the WAV files stored in a folder to WAV using a different sampling freq and number of channels.
ARGUMENTS:
- dirName: the path of the folder where the WAVs are stored
- Fs: the sampling rate of the generated WAV files
- nC: the number of channesl of the generated WAV files | def convertFsDirWavToWav(dirName, Fs, nC):
types = (dirName+os.sep+'*.wav',) # the tuple of file types
filesToProcess = []
for files in types:
filesToProcess.extend(glob.glob(files))
newDir = dirName + os.sep + "Fs" + str(Fs) + "_" + "NC"+str(nC)
if os.path.exists(newDir) and newDir!=".":
shutil.rmtree(newDir)
os.makedirs(newDir)
for f in filesToProcess:
_, wavFileName = ntpath.split(f)
command = "avconv -i \"" + f + "\" -ar " +str(Fs) + " -ac " + str(nC) + " \"" + newDir + os.sep + wavFileName + "\"";
print(command)
os.system(command) | 58,087 |
This function computes the self-similarity matrix for a sequence
of feature vectors.
ARGUMENTS:
- featureVectors: a numpy matrix (nDims x nVectors) whose i-th column
corresponds to the i-th feature vector
RETURNS:
- S: the self-similarity matrix (nVectors x nVectors) | def selfSimilarityMatrix(featureVectors):
[nDims, nVectors] = featureVectors.shape
[featureVectors2, MEAN, STD] = aT.normalizeFeatures([featureVectors.T])
featureVectors2 = featureVectors2[0].T
S = 1.0 - distance.squareform(distance.pdist(featureVectors2.T, 'cosine'))
return S | 58,091 |
This function converts segment endpoints and respective segment
labels to fix-sized class labels.
ARGUMENTS:
- seg_start: segment start points (in seconds)
- seg_end: segment endpoints (in seconds)
- seg_label: segment labels
- win_size: fix-sized window (in seconds)
RETURNS:
- flags: numpy array of class indices
- class_names: list of classnames (strings) | def segs2flags(seg_start, seg_end, seg_label, win_size):
flags = []
class_names = list(set(seg_label))
curPos = win_size / 2.0
while curPos < seg_end[-1]:
for i in range(len(seg_start)):
if curPos > seg_start[i] and curPos <= seg_end[i]:
break
flags.append(class_names.index(seg_label[i]))
curPos += win_size
return numpy.array(flags), class_names | 58,093 |
This function reads a segmentation ground truth file, following a simple CSV format with the following columns:
<segment start>,<segment end>,<class label>
ARGUMENTS:
- gt_file: the path of the CSV segment file
RETURNS:
- seg_start: a numpy array of segments' start positions
- seg_end: a numpy array of segments' ending positions
- seg_label: a list of respective class labels (strings) | def readSegmentGT(gt_file):
f = open(gt_file, 'rt')
reader = csv.reader(f, delimiter=',')
seg_start = []
seg_end = []
seg_label = []
for row in reader:
if len(row) == 3:
seg_start.append(float(row[0]))
seg_end.append(float(row[1]))
#if row[2]!="other":
# seg_label.append((row[2]))
#else:
# seg_label.append("silence")
seg_label.append((row[2]))
return numpy.array(seg_start), numpy.array(seg_end), seg_label | 58,095 |
This function prints the cluster purity and speaker purity for
each WAV file stored in a provided directory (.SEGMENT files
are needed as ground-truth)
ARGUMENTS:
- folder_name: the full path of the folder where the WAV and
SEGMENT (ground-truth) files are stored
- ldas: a list of LDA dimensions (0 for no LDA) | def speakerDiarizationEvaluateScript(folder_name, ldas):
types = ('*.wav', )
wavFilesList = []
for files in types:
wavFilesList.extend(glob.glob(os.path.join(folder_name, files)))
wavFilesList = sorted(wavFilesList)
# get number of unique speakers per file (from ground-truth)
N = []
for wav_file in wavFilesList:
gt_file = wav_file.replace('.wav', '.segments');
if os.path.isfile(gt_file):
[seg_start, seg_end, seg_labs] = readSegmentGT(gt_file)
N.append(len(list(set(seg_labs))))
else:
N.append(-1)
for l in ldas:
print("LDA = {0:d}".format(l))
for i, wav_file in enumerate(wavFilesList):
speakerDiarization(wav_file, N[i], 2.0, 0.2, 0.05, l, plot_res=False)
print | 58,106 |
This function generates a chordial visualization for the recordings of the provided path.
ARGUMENTS:
- folder: path of the folder that contains the WAV files to be processed
- dimReductionMethod: method used to reduce the dimension of the initial feature space before computing the similarity.
- priorKnowledge: if this is set equal to "artist" | def visualizeFeaturesFolder(folder, dimReductionMethod, priorKnowledge = "none"):
if dimReductionMethod=="pca":
allMtFeatures, wavFilesList, _ = aF.dirWavFeatureExtraction(folder, 30.0, 30.0, 0.050, 0.050, compute_beat = True)
if allMtFeatures.shape[0]==0:
print("Error: No data found! Check input folder")
return
namesCategoryToVisualize = [ntpath.basename(w).replace('.wav','').split(" --- ")[0] for w in wavFilesList];
namesToVisualize = [ntpath.basename(w).replace('.wav','') for w in wavFilesList];
(F, MEAN, STD) = aT.normalizeFeatures([allMtFeatures])
F = np.concatenate(F)
# check that the new PCA dimension is at most equal to the number of samples
K1 = 2
K2 = 10
if K1 > F.shape[0]:
K1 = F.shape[0]
if K2 > F.shape[0]:
K2 = F.shape[0]
pca1 = sklearn.decomposition.PCA(n_components = K1)
pca1.fit(F)
pca2 = sklearn.decomposition.PCA(n_components = K2)
pca2.fit(F)
finalDims = pca1.transform(F)
finalDims2 = pca2.transform(F)
else:
allMtFeatures, Ys, wavFilesList = aF.dirWavFeatureExtractionNoAveraging(folder, 20.0, 5.0, 0.040, 0.040) # long-term statistics cannot be applied in this context (LDA needs mid-term features)
if allMtFeatures.shape[0]==0:
print("Error: No data found! Check input folder")
return
namesCategoryToVisualize = [ntpath.basename(w).replace('.wav','').split(" --- ")[0] for w in wavFilesList];
namesToVisualize = [ntpath.basename(w).replace('.wav','') for w in wavFilesList];
ldaLabels = Ys
if priorKnowledge=="artist":
uNamesCategoryToVisualize = list(set(namesCategoryToVisualize))
YsNew = np.zeros( Ys.shape )
for i, uname in enumerate(uNamesCategoryToVisualize): # for each unique artist name:
indicesUCategories = [j for j, x in enumerate(namesCategoryToVisualize) if x == uname]
for j in indicesUCategories:
indices = np.nonzero(Ys==j)
YsNew[indices] = i
ldaLabels = YsNew
(F, MEAN, STD) = aT.normalizeFeatures([allMtFeatures])
F = np.array(F[0])
clf = sklearn.discriminant_analysis.LinearDiscriminantAnalysis(n_components=10)
clf.fit(F, ldaLabels)
reducedDims = clf.transform(F)
pca = sklearn.decomposition.PCA(n_components = 2)
pca.fit(reducedDims)
reducedDims = pca.transform(reducedDims)
# TODO: CHECK THIS ... SHOULD LDA USED IN SEMI-SUPERVISED ONLY????
uLabels = np.sort(np.unique((Ys))) # uLabels must have as many labels as the number of wavFilesList elements
reducedDimsAvg = np.zeros( (uLabels.shape[0], reducedDims.shape[1] ) )
finalDims = np.zeros( (uLabels.shape[0], 2) )
for i, u in enumerate(uLabels):
indices = [j for j, x in enumerate(Ys) if x == u]
f = reducedDims[indices, :]
finalDims[i, :] = f.mean(axis=0)
finalDims2 = reducedDims
for i in range(finalDims.shape[0]):
plt.text(finalDims[i,0], finalDims[i,1], ntpath.basename(wavFilesList[i].replace('.wav','')), horizontalalignment='center', verticalalignment='center', fontsize=10)
plt.plot(finalDims[i,0], finalDims[i,1], '*r')
plt.xlim([1.2*finalDims[:,0].min(), 1.2*finalDims[:,0].max()])
plt.ylim([1.2*finalDims[:,1].min(), 1.2*finalDims[:,1].max()])
plt.show()
SM = 1.0 - distance.squareform(distance.pdist(finalDims2, 'cosine'))
for i in range(SM.shape[0]):
SM[i,i] = 0.0;
chordialDiagram("visualization", SM, 0.50, namesToVisualize, namesCategoryToVisualize)
SM = 1.0 - distance.squareform(distance.pdist(F, 'cosine'))
for i in range(SM.shape[0]):
SM[i,i] = 0.0;
chordialDiagram("visualizationInitial", SM, 0.50, namesToVisualize, namesCategoryToVisualize)
# plot super-categories (i.e. artistname
uNamesCategoryToVisualize = sort(list(set(namesCategoryToVisualize)))
finalDimsGroup = np.zeros( (len(uNamesCategoryToVisualize), finalDims2.shape[1] ) )
for i, uname in enumerate(uNamesCategoryToVisualize):
indices = [j for j, x in enumerate(namesCategoryToVisualize) if x == uname]
f = finalDims2[indices, :]
finalDimsGroup[i, :] = f.mean(axis=0)
SMgroup = 1.0 - distance.squareform(distance.pdist(finalDimsGroup, 'cosine'))
for i in range(SMgroup.shape[0]):
SMgroup[i,i] = 0.0;
chordialDiagram("visualizationGroup", SMgroup, 0.50, uNamesCategoryToVisualize, uNamesCategoryToVisualize) | 58,113 |
Computes the spectral flux feature of the current frame
ARGUMENTS:
X: the abs(fft) of the current frame
X_prev: the abs(fft) of the previous frame | def stSpectralFlux(X, X_prev):
# compute the spectral flux as the sum of square distances:
sumX = numpy.sum(X + eps)
sumPrevX = numpy.sum(X_prev + eps)
F = numpy.sum((X / sumX - X_prev/sumPrevX) ** 2)
return F | 58,124 |
Computes the MFCCs of a frame, given the fft mag
ARGUMENTS:
X: fft magnitude abs(FFT)
fbank: filter bank (see mfccInitFilterBanks)
RETURN
ceps: MFCCs (13 element vector)
Note: MFCC calculation is, in general, taken from the
scikits.talkbox library (MIT Licence),
# with a small number of modifications to make it more
compact and suitable for the pyAudioAnalysis Lib | def stMFCC(X, fbank, n_mfcc_feats):
mspec = numpy.log10(numpy.dot(X, fbank.T)+eps)
ceps = dct(mspec, type=2, norm='ortho', axis=-1)[:n_mfcc_feats]
return ceps | 58,128 |
Short-term FFT mag for spectogram estimation:
Returns:
a numpy array (nFFT x numOfShortTermWindows)
ARGUMENTS:
signal: the input signal samples
fs: the sampling freq (in Hz)
win: the short-term window size (in samples)
step: the short-term window step (in samples)
PLOT: flag, 1 if results are to be ploted
RETURNS: | def stChromagram(signal, fs, win, step, PLOT=False):
win = int(win)
step = int(step)
signal = numpy.double(signal)
signal = signal / (2.0 ** 15)
DC = signal.mean()
MAX = (numpy.abs(signal)).max()
signal = (signal - DC) / (MAX - DC)
N = len(signal) # total number of signals
cur_p = 0
count_fr = 0
nfft = int(win / 2)
nChroma, nFreqsPerChroma = stChromaFeaturesInit(nfft, fs)
chromaGram = numpy.array([], dtype=numpy.float64)
while (cur_p + win - 1 < N):
count_fr += 1
x = signal[cur_p:cur_p + win]
cur_p = cur_p + step
X = abs(fft(x))
X = X[0:nfft]
X = X / len(X)
chromaNames, C = stChromaFeatures(X, fs, nChroma, nFreqsPerChroma)
C = C[:, 0]
if count_fr == 1:
chromaGram = C.T
else:
chromaGram = numpy.vstack((chromaGram, C.T))
FreqAxis = chromaNames
TimeAxis = [(t * step) / fs for t in range(chromaGram.shape[0])]
if (PLOT):
fig, ax = plt.subplots()
chromaGramToPlot = chromaGram.transpose()[::-1, :]
Ratio = int(chromaGramToPlot.shape[1] / (3*chromaGramToPlot.shape[0]))
if Ratio < 1:
Ratio = 1
chromaGramToPlot = numpy.repeat(chromaGramToPlot, Ratio, axis=0)
imgplot = plt.imshow(chromaGramToPlot)
fstep = int(nfft / 5.0)
# FreqTicks = range(0, int(nfft) + fstep, fstep)
# FreqTicksLabels = [str(fs/2-int((f*fs) / (2*nfft))) for f in FreqTicks]
ax.set_yticks(range(int(Ratio / 2), len(FreqAxis) * Ratio, Ratio))
ax.set_yticklabels(FreqAxis[::-1])
TStep = int(count_fr / 3)
TimeTicks = range(0, count_fr, TStep)
TimeTicksLabels = ['%.2f' % (float(t * step) / fs) for t in TimeTicks]
ax.set_xticks(TimeTicks)
ax.set_xticklabels(TimeTicksLabels)
ax.set_xlabel('time (secs)')
imgplot.set_cmap('jet')
plt.colorbar()
plt.show()
return (chromaGram, TimeAxis, FreqAxis) | 58,131 |
This function extracts an estimate of the beat rate for a musical signal.
ARGUMENTS:
- st_features: a numpy array (n_feats x numOfShortTermWindows)
- win_len: window size in seconds
RETURNS:
- BPM: estimates of beats per minute
- Ratio: a confidence measure | def beatExtraction(st_features, win_len, PLOT=False):
# Features that are related to the beat tracking task:
toWatch = [0, 1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
max_beat_time = int(round(2.0 / win_len))
hist_all = numpy.zeros((max_beat_time,))
for ii, i in enumerate(toWatch): # for each feature
DifThres = 2.0 * (numpy.abs(st_features[i, 0:-1] - st_features[i, 1::])).mean() # dif threshold (3 x Mean of Difs)
if DifThres<=0:
DifThres = 0.0000000000000001
[pos1, _] = utilities.peakdet(st_features[i, :], DifThres) # detect local maxima
posDifs = [] # compute histograms of local maxima changes
for j in range(len(pos1)-1):
posDifs.append(pos1[j+1]-pos1[j])
[hist_times, HistEdges] = numpy.histogram(posDifs, numpy.arange(0.5, max_beat_time + 1.5))
hist_centers = (HistEdges[0:-1] + HistEdges[1::]) / 2.0
hist_times = hist_times.astype(float) / st_features.shape[1]
hist_all += hist_times
if PLOT:
plt.subplot(9, 2, ii + 1)
plt.plot(st_features[i, :], 'k')
for k in pos1:
plt.plot(k, st_features[i, k], 'k*')
f1 = plt.gca()
f1.axes.get_xaxis().set_ticks([])
f1.axes.get_yaxis().set_ticks([])
if PLOT:
plt.show(block=False)
plt.figure()
# Get beat as the argmax of the agregated histogram:
I = numpy.argmax(hist_all)
bpms = 60 / (hist_centers * win_len)
BPM = bpms[I]
# ... and the beat ratio:
Ratio = hist_all[I] / hist_all.sum()
if PLOT:
# filter out >500 beats from plotting:
hist_all = hist_all[bpms < 500]
bpms = bpms[bpms < 500]
plt.plot(bpms, hist_all, 'k')
plt.xlabel('Beats per minute')
plt.ylabel('Freq Count')
plt.show(block=True)
return BPM, Ratio | 58,133 |
Short-term FFT mag for spectogram estimation:
Returns:
a numpy array (nFFT x numOfShortTermWindows)
ARGUMENTS:
signal: the input signal samples
fs: the sampling freq (in Hz)
win: the short-term window size (in samples)
step: the short-term window step (in samples)
PLOT: flag, 1 if results are to be ploted
RETURNS: | def stSpectogram(signal, fs, win, step, PLOT=False):
win = int(win)
step = int(step)
signal = numpy.double(signal)
signal = signal / (2.0 ** 15)
DC = signal.mean()
MAX = (numpy.abs(signal)).max()
signal = (signal - DC) / (MAX - DC)
N = len(signal) # total number of signals
cur_p = 0
count_fr = 0
nfft = int(win / 2)
specgram = numpy.array([], dtype=numpy.float64)
while (cur_p + win - 1 < N):
count_fr += 1
x = signal[cur_p:cur_p+win]
cur_p = cur_p + step
X = abs(fft(x))
X = X[0:nfft]
X = X / len(X)
if count_fr == 1:
specgram = X ** 2
else:
specgram = numpy.vstack((specgram, X))
FreqAxis = [float((f + 1) * fs) / (2 * nfft) for f in range(specgram.shape[1])]
TimeAxis = [float(t * step) / fs for t in range(specgram.shape[0])]
if (PLOT):
fig, ax = plt.subplots()
imgplot = plt.imshow(specgram.transpose()[::-1, :])
fstep = int(nfft / 5.0)
FreqTicks = range(0, int(nfft) + fstep, fstep)
FreqTicksLabels = [str(fs / 2 - int((f * fs) / (2 * nfft))) for f in FreqTicks]
ax.set_yticks(FreqTicks)
ax.set_yticklabels(FreqTicksLabels)
TStep = int(count_fr/3)
TimeTicks = range(0, count_fr, TStep)
TimeTicksLabels = ['%.2f' % (float(t * step) / fs) for t in TimeTicks]
ax.set_xticks(TimeTicks)
ax.set_xticklabels(TimeTicksLabels)
ax.set_xlabel('time (secs)')
ax.set_ylabel('freq (Hz)')
imgplot.set_cmap('jet')
plt.colorbar()
plt.show()
return (specgram, TimeAxis, FreqAxis) | 58,134 |
This function extracts the mid-term features of the WAVE files of a particular folder.
The resulting feature vector is extracted by long-term averaging the mid-term features.
Therefore ONE FEATURE VECTOR is extracted for each WAV file.
ARGUMENTS:
- dirName: the path of the WAVE directory
- mt_win, mt_step: mid-term window and step (in seconds)
- st_win, st_step: short-term window and step (in seconds) | def dirWavFeatureExtraction(dirName, mt_win, mt_step, st_win, st_step,
compute_beat=False):
all_mt_feats = numpy.array([])
process_times = []
types = ('*.wav', '*.aif', '*.aiff', '*.mp3', '*.au', '*.ogg')
wav_file_list = []
for files in types:
wav_file_list.extend(glob.glob(os.path.join(dirName, files)))
wav_file_list = sorted(wav_file_list)
wav_file_list2, mt_feature_names = [], []
for i, wavFile in enumerate(wav_file_list):
print("Analyzing file {0:d} of "
"{1:d}: {2:s}".format(i+1,
len(wav_file_list),
wavFile))
if os.stat(wavFile).st_size == 0:
print(" (EMPTY FILE -- SKIPPING)")
continue
[fs, x] = audioBasicIO.readAudioFile(wavFile)
if isinstance(x, int):
continue
t1 = time.clock()
x = audioBasicIO.stereo2mono(x)
if x.shape[0]<float(fs)/5:
print(" (AUDIO FILE TOO SMALL - SKIPPING)")
continue
wav_file_list2.append(wavFile)
if compute_beat:
[mt_term_feats, st_features, mt_feature_names] = \
mtFeatureExtraction(x, fs, round(mt_win * fs),
round(mt_step * fs),
round(fs * st_win), round(fs * st_step))
[beat, beat_conf] = beatExtraction(st_features, st_step)
else:
[mt_term_feats, _, mt_feature_names] = \
mtFeatureExtraction(x, fs, round(mt_win * fs),
round(mt_step * fs),
round(fs * st_win), round(fs * st_step))
mt_term_feats = numpy.transpose(mt_term_feats)
mt_term_feats = mt_term_feats.mean(axis=0)
# long term averaging of mid-term statistics
if (not numpy.isnan(mt_term_feats).any()) and \
(not numpy.isinf(mt_term_feats).any()):
if compute_beat:
mt_term_feats = numpy.append(mt_term_feats, beat)
mt_term_feats = numpy.append(mt_term_feats, beat_conf)
if len(all_mt_feats) == 0:
# append feature vector
all_mt_feats = mt_term_feats
else:
all_mt_feats = numpy.vstack((all_mt_feats, mt_term_feats))
t2 = time.clock()
duration = float(len(x)) / fs
process_times.append((t2 - t1) / duration)
if len(process_times) > 0:
print("Feature extraction complexity ratio: "
"{0:.1f} x realtime".format((1.0 / numpy.mean(numpy.array(process_times)))))
return (all_mt_feats, wav_file_list2, mt_feature_names) | 58,138 |
This function extracts the mid-term features of the WAVE
files of a particular folder without averaging each file.
ARGUMENTS:
- dirName: the path of the WAVE directory
- mt_win, mt_step: mid-term window and step (in seconds)
- st_win, st_step: short-term window and step (in seconds)
RETURNS:
- X: A feature matrix
- Y: A matrix of file labels
- filenames: | def dirWavFeatureExtractionNoAveraging(dirName, mt_win, mt_step, st_win, st_step):
all_mt_feats = numpy.array([])
signal_idx = numpy.array([])
process_times = []
types = ('*.wav', '*.aif', '*.aiff', '*.ogg')
wav_file_list = []
for files in types:
wav_file_list.extend(glob.glob(os.path.join(dirName, files)))
wav_file_list = sorted(wav_file_list)
for i, wavFile in enumerate(wav_file_list):
[fs, x] = audioBasicIO.readAudioFile(wavFile)
if isinstance(x, int):
continue
x = audioBasicIO.stereo2mono(x)
[mt_term_feats, _, _] = mtFeatureExtraction(x, fs, round(mt_win * fs),
round(mt_step * fs),
round(fs * st_win),
round(fs * st_step))
mt_term_feats = numpy.transpose(mt_term_feats)
if len(all_mt_feats) == 0: # append feature vector
all_mt_feats = mt_term_feats
signal_idx = numpy.zeros((mt_term_feats.shape[0], ))
else:
all_mt_feats = numpy.vstack((all_mt_feats, mt_term_feats))
signal_idx = numpy.append(signal_idx, i * numpy.ones((mt_term_feats.shape[0], )))
return (all_mt_feats, signal_idx, wav_file_list) | 58,140 |
Tokenizes a piece of text into its word pieces.
This uses a greedy longest-match-first algorithm to perform tokenization
using the given vocabulary.
For example:
input = "unaffable"
output = ["un", "##aff", "##able"]
Args:
text: A single token or whitespace separated tokens. This should have
already been passed through `BERTBasicTokenizer.
Returns:
A list of wordpiece tokens. | def _tokenize_wordpiece(self, text):
output_tokens = []
for token in self.basic_tokenizer._whitespace_tokenize(text):
chars = list(token)
if len(chars) > self.max_input_chars_per_word:
output_tokens.append(self.vocab.unknown_token)
continue
is_bad = False
start = 0
sub_tokens = []
while start < len(chars):
end = len(chars)
cur_substr = None
while start < end:
substr = ''.join(chars[start:end])
if start > 0:
substr = '##' + substr
if substr in self.vocab:
cur_substr = substr
break
end -= 1
if cur_substr is None:
is_bad = True
break
sub_tokens.append(cur_substr)
start = end
if is_bad:
output_tokens.append(self.vocab.unknown_token)
else:
output_tokens.extend(sub_tokens)
return output_tokens | 60,621 |
Take an IP string/int and return an object of the correct type.
Args:
address: A string or integer, the IP address. Either IPv4 or
IPv6 addresses may be supplied; integers less than 2**32 will
be considered to be IPv4 by default.
Returns:
An IPv4Address or IPv6Address object.
Raises:
ValueError: if the *address* passed isn't either a v4 or a v6
address | def ip_address(address):
try:
return IPv4Address(address)
except (AddressValueError, NetmaskValueError):
pass
try:
return IPv6Address(address)
except (AddressValueError, NetmaskValueError):
pass
raise ValueError('%r does not appear to be an IPv4 or IPv6 address' %
address) | 61,572 |
Take an IP string/int and return an object of the correct type.
Args:
address: A string or integer, the IP network. Either IPv4 or
IPv6 networks may be supplied; integers less than 2**32 will
be considered to be IPv4 by default.
Returns:
An IPv4Network or IPv6Network object.
Raises:
ValueError: if the string passed isn't either a v4 or a v6
address. Or if the network has host bits set. | def ip_network(address, strict=True):
try:
return IPv4Network(address, strict)
except (AddressValueError, NetmaskValueError):
pass
try:
return IPv6Network(address, strict)
except (AddressValueError, NetmaskValueError):
pass
raise ValueError('%r does not appear to be an IPv4 or IPv6 network' %
address) | 61,573 |
Count the number of zero bits on the right hand side.
Args:
number: an integer.
bits: maximum number of bits to count.
Returns:
The number of zero bits on the right hand side of the number. | def _count_righthand_zero_bits(number, bits):
if number == 0:
return bits
for i in range(bits):
if (number >> i) & 1:
return i
# All bits of interest were zero, even if there are more in the number
return bits | 61,575 |
Collapse a list of IP objects.
Example:
collapse_addresses([IPv4Network('192.0.2.0/25'),
IPv4Network('192.0.2.128/25')]) ->
[IPv4Network('192.0.2.0/24')]
Args:
addresses: An iterator of IPv4Network or IPv6Network objects.
Returns:
An iterator of the collapsed IPv(4|6)Network objects.
Raises:
TypeError: If passed a list of mixed version objects. | def collapse_addresses(addresses):
i = 0
addrs = []
ips = []
nets = []
# split IP addresses and networks
for ip in addresses:
if isinstance(ip, _BaseAddress):
if ips and ips[-1]._version != ip._version:
raise TypeError("%s and %s are not of the same version" % (
ip, ips[-1]))
ips.append(ip)
elif ip._prefixlen == ip._max_prefixlen:
if ips and ips[-1]._version != ip._version:
raise TypeError("%s and %s are not of the same version" % (
ip, ips[-1]))
try:
ips.append(ip.ip)
except AttributeError:
ips.append(ip.network_address)
else:
if nets and nets[-1]._version != ip._version:
raise TypeError("%s and %s are not of the same version" % (
ip, nets[-1]))
nets.append(ip)
# sort and dedup
ips = sorted(set(ips))
nets = sorted(set(nets))
while i < len(ips):
(first, last) = _find_address_range(ips[i:])
i = ips.index(last) + 1
addrs.extend(summarize_address_range(first, last))
return iter(_collapse_addresses_recursive(sorted(
addrs + nets, key=_BaseNetwork._get_networks_key))) | 61,577 |
Return prefix length from the bitwise netmask.
Args:
ip_int: An integer, the netmask in expanded bitwise format
Returns:
An integer, the prefix length.
Raises:
ValueError: If the input intermingles zeroes & ones | def _prefix_from_ip_int(self, ip_int):
trailing_zeroes = _count_righthand_zero_bits(ip_int,
self._max_prefixlen)
prefixlen = self._max_prefixlen - trailing_zeroes
leading_ones = ip_int >> trailing_zeroes
all_ones = (1 << prefixlen) - 1
if leading_ones != all_ones:
byteslen = self._max_prefixlen // 8
details = _int_to_bytes(ip_int, byteslen, 'big')
msg = 'Netmask pattern %r mixes zeroes & ones'
raise ValueError(msg % details)
return prefixlen | 61,578 |
Return prefix length from a numeric string
Args:
prefixlen_str: The string to be converted
Returns:
An integer, the prefix length.
Raises:
NetmaskValueError: If the input is not a valid netmask | def _prefix_from_prefix_string(self, prefixlen_str):
# int allows a leading +/- as well as surrounding whitespace,
# so we ensure that isn't the case
if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str):
self._report_invalid_netmask(prefixlen_str)
try:
prefixlen = int(prefixlen_str)
except ValueError:
self._report_invalid_netmask(prefixlen_str)
if not (0 <= prefixlen <= self._max_prefixlen):
self._report_invalid_netmask(prefixlen_str)
return prefixlen | 61,579 |
Turn a netmask/hostmask string into a prefix length
Args:
ip_str: The netmask/hostmask to be converted
Returns:
An integer, the prefix length.
Raises:
NetmaskValueError: If the input is not a valid netmask/hostmask | def _prefix_from_ip_string(self, ip_str):
# Parse the netmask/hostmask like an IP address.
try:
ip_int = self._ip_int_from_string(ip_str)
except AddressValueError:
self._report_invalid_netmask(ip_str)
# Try matching a netmask (this would be /1*0*/ as a bitwise regexp).
# Note that the two ambiguous cases (all-ones and all-zeroes) are
# treated as netmasks.
try:
return self._prefix_from_ip_int(ip_int)
except ValueError:
pass
# Invert the bits, and try matching a /0+1+/ hostmask instead.
ip_int ^= self._ALL_ONES
try:
return self._prefix_from_ip_int(ip_int)
except ValueError:
self._report_invalid_netmask(ip_str) | 61,580 |
Turn the given IP string into an integer for comparison.
Args:
ip_str: A string, the IP ip_str.
Returns:
The IP ip_str as an integer.
Raises:
AddressValueError: if ip_str isn't a valid IPv4 Address. | def _ip_int_from_string(self, ip_str):
if not ip_str:
raise AddressValueError('Address cannot be empty')
octets = ip_str.split('.')
if len(octets) != 4:
raise AddressValueError("Expected 4 octets in %r" % ip_str)
try:
return _int_from_bytes(map(self._parse_octet, octets), 'big')
except ValueError as exc:
raise AddressValueError("%s in %r" % (exc, ip_str)) | 61,586 |
Convert a decimal octet into an integer.
Args:
octet_str: A string, the number to parse.
Returns:
The octet as an integer.
Raises:
ValueError: if the octet isn't strictly a decimal from [0..255]. | def _parse_octet(self, octet_str):
if not octet_str:
raise ValueError("Empty octet not permitted")
# Whitelist the characters, since int() allows a lot of bizarre stuff.
if not self._DECIMAL_DIGITS.issuperset(octet_str):
msg = "Only decimal digits permitted in %r"
raise ValueError(msg % octet_str)
# We do the length check second, since the invalid character error
# is likely to be more informative for the user
if len(octet_str) > 3:
msg = "At most 3 characters permitted in %r"
raise ValueError(msg % octet_str)
# Convert to integer (we know digits are legal)
octet_int = int(octet_str, 10)
# Any octets that look like they *might* be written in octal,
# and which don't look exactly the same in both octal and
# decimal are rejected as ambiguous
if octet_int > 7 and octet_str[0] == '0':
msg = "Ambiguous (octal/decimal) value in %r not permitted"
raise ValueError(msg % octet_str)
if octet_int > 255:
raise ValueError("Octet %d (> 255) not permitted" % octet_int)
return octet_int | 61,587 |
Verify that the netmask is valid.
Args:
netmask: A string, either a prefix or dotted decimal
netmask.
Returns:
A boolean, True if the prefix represents a valid IPv4
netmask. | def _is_valid_netmask(self, netmask):
mask = netmask.split('.')
if len(mask) == 4:
try:
for x in mask:
if int(x) not in self._valid_mask_octets:
return False
except ValueError:
# Found something that isn't an integer or isn't valid
return False
for idx, y in enumerate(mask):
if idx > 0 and y > mask[idx - 1]:
return False
return True
try:
netmask = int(netmask)
except ValueError:
return False
return 0 <= netmask <= self._max_prefixlen | 61,588 |
Expand a shortened IPv6 address.
Args:
ip_str: A string, the IPv6 address.
Returns:
A string, the expanded IPv6 address. | def _explode_shorthand_ip_string(self):
if isinstance(self, IPv6Network):
ip_str = str(self.network_address)
elif isinstance(self, IPv6Interface):
ip_str = str(self.ip)
else:
ip_str = str(self)
ip_int = self._ip_int_from_string(ip_str)
hex_str = '%032x' % ip_int
parts = [hex_str[x:x+4] for x in range(0, 32, 4)]
if isinstance(self, (_BaseNetwork, IPv6Interface)):
return '%s/%d' % (':'.join(parts), self._prefixlen)
return ':'.join(parts) | 61,592 |
Find a device in Zenoss. If device not found, returns None.
Parameters:
device: (Optional) Will use the grain 'fqdn' by default
CLI Example:
salt '*' zenoss.find_device | def find_device(device=None):
data = [{'uid': '/zport/dmd/Devices', 'params': {}, 'limit': None}]
all_devices = _router_request('DeviceRouter', 'getDevices', data=data)
for dev in all_devices['devices']:
if dev['name'] == device:
# We need to save the has for later operations
dev['hash'] = all_devices['hash']
log.info('Found device %s in Zenoss', device)
return dev
log.info('Unable to find device %s in Zenoss', device)
return None | 61,746 |
A function to set the prod_state in zenoss.
Parameters:
prod_state: (Required) Integer value of the state
device: (Optional) Will use the grain 'fqdn' by default.
CLI Example:
salt zenoss.set_prod_state 1000 hostname | def set_prod_state(prod_state, device=None):
if not device:
device = __salt__['grains.get']('fqdn')
device_object = find_device(device)
if not device_object:
return "Unable to find a device in Zenoss for {0}".format(device)
log.info('Setting prodState to %d on %s device', prod_state, device)
data = dict(uids=[device_object['uid']], prodState=prod_state, hashcheck=device_object['hash'])
return _router_request('DeviceRouter', 'setProductionState', [data]) | 61,748 |
Filters file path against unwanted directories and decides whether file is marked as deleted.
Returns:
True if file is desired deleted file, else False.
Args:
path: A string - path to file | def _valid_deleted_file(path):
ret = False
if path.endswith(' (deleted)'):
ret = True
if re.compile(r"\(path inode=[0-9]+\)$").search(path):
ret = True
regex = re.compile("|".join(LIST_DIRS))
if regex.match(path):
ret = False
return ret | 61,749 |
Ensure an update is installed on the minion
Args:
name(str):
Name of the Windows KB ("KB123456")
source (str):
Source of .msu file corresponding to the KB
Example:
.. code-block:: yaml
KB123456:
wusa.installed:
- source: salt://kb123456.msu | def installed(name, source):
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
# Input validation
if not name:
raise SaltInvocationError('Must specify a KB "name"')
if not source:
raise SaltInvocationError('Must specify a "source" file to install')
# Is the KB already installed
if __salt__['wusa.is_installed'](name):
ret['result'] = True
ret['comment'] = '{0} already installed'.format(name)
return ret
# Check for test=True
if __opts__['test'] is True:
ret['result'] = None
ret['comment'] = '{0} would be installed'.format(name)
ret['result'] = None
return ret
# Cache the file
cached_source_path = __salt__['cp.cache_file'](path=source, saltenv=__env__)
if not cached_source_path:
msg = 'Unable to cache {0} from saltenv "{1}"'.format(
salt.utils.url.redact_http_basic_auth(source), __env__)
ret['comment'] = msg
return ret
# Install the KB
__salt__['wusa.install'](cached_source_path)
# Verify successful install
if __salt__['wusa.is_installed'](name):
ret['comment'] = '{0} was installed'.format(name)
ret['changes'] = {'old': False, 'new': True}
ret['result'] = True
else:
ret['comment'] = '{0} failed to install'.format(name)
return ret | 61,842 |
Ensure an update is uninstalled from the minion
Args:
name(str):
Name of the Windows KB ("KB123456")
Example:
.. code-block:: yaml
KB123456:
wusa.uninstalled | def uninstalled(name):
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
# Is the KB already uninstalled
if not __salt__['wusa.is_installed'](name):
ret['result'] = True
ret['comment'] = '{0} already uninstalled'.format(name)
return ret
# Check for test=True
if __opts__['test'] is True:
ret['result'] = None
ret['comment'] = '{0} would be uninstalled'.format(name)
ret['result'] = None
return ret
# Uninstall the KB
__salt__['wusa.uninstall'](name)
# Verify successful uninstall
if not __salt__['wusa.is_installed'](name):
ret['comment'] = '{0} was uninstalled'.format(name)
ret['changes'] = {'old': True, 'new': False}
ret['result'] = True
else:
ret['comment'] = '{0} failed to uninstall'.format(name)
return ret | 61,843 |
Create the salt proxy file and start the proxy process
if required
Parameters:
proxyname:
Name to be used for this proxy (should match entries in pillar)
start:
Boolean indicating if the process should be started
default = True
CLI Example:
.. code-block:: bash
salt deviceminion salt_proxy.configure_proxy p8000 | def configure_proxy(proxyname, start=True):
changes_new = []
changes_old = []
status_file = True
test = __opts__['test']
# write the proxy file if necessary
proxyfile = '/etc/salt/proxy'
status_file, msg_new, msg_old = _proxy_conf_file(proxyfile, test)
changes_new.extend(msg_new)
changes_old.extend(msg_old)
status_proc = False
# start the proxy process
if start:
status_proc, msg_new, msg_old = _proxy_process(proxyname, test)
changes_old.extend(msg_old)
changes_new.extend(msg_new)
else:
changes_old.append('Start is False, not starting salt-proxy process')
log.debug('Process not started')
return {
'result': status_file and status_proc,
'changes': {
'old': '\n'.join(changes_old),
'new': '\n'.join(changes_new),
},
} | 62,004 |
Ensure that the named package is not installed.
Args:
name (str): The flatpak package.
Returns:
dict: The ``result`` and ``output``.
Example:
.. code-block:: yaml
uninstall_package:
flatpack.uninstalled:
- name: gimp | def uninstalled(name):
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
old = __salt__['flatpak.is_installed'](name)
if not old:
ret['comment'] = 'Package {0} is not installed'.format(name)
ret['result'] = True
return ret
else:
if __opts__['test']:
ret['comment'] = 'Package {0} would have been uninstalled'.format(name)
ret['changes']['old'] = old[0]['version']
ret['changes']['new'] = None
ret['result'] = None
return ret
__salt__['flatpak.uninstall'](name)
if not __salt__['flatpak.is_installed'](name):
ret['comment'] = 'Package {0} uninstalled'.format(name)
ret['changes']['old'] = old[0]['version']
ret['changes']['new'] = None
ret['result'] = True
return ret | 62,457 |
Adds a new location to install flatpak packages from.
Args:
name (str): The repository's name.
location (str): The location of the repository.
Returns:
dict: The ``result`` and ``output``.
Example:
.. code-block:: yaml
add_flathub:
flatpack.add_remote:
- name: flathub
- location: https://flathub.org/repo/flathub.flatpakrepo | def add_remote(name, location):
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
old = __salt__['flatpak.is_remote_added'](name)
if not old:
if __opts__['test']:
ret['comment'] = 'Remote "{0}" would have been added'.format(name)
ret['changes']['new'] = name
ret['changes']['old'] = None
ret['result'] = None
return ret
install_ret = __salt__['flatpak.add_remote'](name)
if __salt__['flatpak.is_remote_added'](name):
ret['comment'] = 'Remote "{0}" was added'.format(name)
ret['changes']['new'] = name
ret['changes']['old'] = None
ret['result'] = True
return ret
ret['comment'] = 'Failed to add remote "{0}"'.format(name)
ret['comment'] += '\noutput:\n' + install_ret['output']
ret['result'] = False
return ret
ret['comment'] = 'Remote "{0}" already exists'.format(name)
if __opts__['test']:
ret['result'] = None
return ret
ret['result'] = True
return ret | 62,458 |
Set an effect to the lamp.
Arguments:
* **value**: 0~255 brightness of the lamp.
Options:
* **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.
* **transition**: Transition 0~200. Default 0.
CLI Example:
.. code-block:: bash
salt '*' hue.brightness value=100
salt '*' hue.brightness id=1 value=150
salt '*' hue.brightness id=1,2,3 value=255 | def call_brightness(*args, **kwargs):
res = dict()
if 'value' not in kwargs:
raise CommandExecutionError("Parameter 'value' is missing")
try:
brightness = max(min(int(kwargs['value']), 244), 1)
except Exception as err:
raise CommandExecutionError("Parameter 'value' does not contains an integer")
try:
transition = max(min(int(kwargs['transition']), 200), 0)
except Exception as err:
transition = 0
devices = _get_lights()
for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs):
res[dev_id] = _set(dev_id, {"bri": brightness, "transitiontime": transition})
return res | 62,477 |
Set the mired color temperature. More: http://en.wikipedia.org/wiki/Mired
Arguments:
* **value**: 150~500.
Options:
* **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.
CLI Example:
.. code-block:: bash
salt '*' hue.temperature value=150
salt '*' hue.temperature value=150 id=1
salt '*' hue.temperature value=150 id=1,2,3 | def call_temperature(*args, **kwargs):
res = dict()
if 'value' not in kwargs:
raise CommandExecutionError("Parameter 'value' (150~500) is missing")
try:
value = max(min(int(kwargs['value']), 500), 150)
except Exception as err:
raise CommandExecutionError("Parameter 'value' does not contains an integer")
devices = _get_lights()
for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs):
res[dev_id] = _set(dev_id, {"ct": value})
return res | 62,478 |
Sets the timezone using the tzutil.
Args:
timezone (str): A valid timezone
Returns:
bool: ``True`` if successful, otherwise ``False``
Raises:
CommandExecutionError: If invalid timezone is passed
CLI Example:
.. code-block:: bash
salt '*' timezone.set_zone 'America/Denver' | def set_zone(timezone):
# if it's one of the key's just use it
if timezone.lower() in mapper.win_to_unix:
win_zone = timezone
elif timezone.lower() in mapper.unix_to_win:
# if it's one of the values, use the key
win_zone = mapper.get_win(timezone)
else:
# Raise error because it's neither key nor value
raise CommandExecutionError('Invalid timezone passed: {0}'.format(timezone))
# Set the value
cmd = ['tzutil', '/s', win_zone]
res = __salt__['cmd.run_all'](cmd, python_shell=False)
if res['retcode']:
raise CommandExecutionError('tzutil encountered an error setting '
'timezone: {0}'.format(timezone),
info=res)
return zone_compare(timezone) | 63,586 |
Compares the given timezone with the machine timezone. Mostly useful for
running state checks.
Args:
timezone (str):
The timezone to compare. This can be in Windows or Unix format. Can
be any of the values returned by the ``timezone.list`` function
Returns:
bool: ``True`` if they match, otherwise ``False``
Example:
.. code-block:: bash
salt '*' timezone.zone_compare 'America/Denver' | def zone_compare(timezone):
# if it's one of the key's just use it
if timezone.lower() in mapper.win_to_unix:
check_zone = timezone
elif timezone.lower() in mapper.unix_to_win:
# if it's one of the values, use the key
check_zone = mapper.get_win(timezone)
else:
# Raise error because it's neither key nor value
raise CommandExecutionError('Invalid timezone passed: {0}'
''.format(timezone))
return get_zone() == mapper.get_unix(check_zone, 'Unknown') | 63,587 |
Set the Windows computer name
Args:
name (str):
The new name to give the computer. Requires a reboot to take effect.
Returns:
dict:
Returns a dictionary containing the old and new names if successful.
``False`` if not.
CLI Example:
.. code-block:: bash
salt 'minion-id' system.set_computer_name 'DavesComputer' | def set_computer_name(name):
if six.PY2:
name = _to_unicode(name)
if windll.kernel32.SetComputerNameExW(
win32con.ComputerNamePhysicalDnsHostname, name):
ret = {'Computer Name': {'Current': get_computer_name()}}
pending = get_pending_computer_name()
if pending not in (None, False):
ret['Computer Name']['Pending'] = pending
return ret
return False | 63,934 |
Set the Windows computer description
Args:
desc (str):
The computer description
Returns:
str: Description if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
salt 'minion-id' system.set_computer_desc 'This computer belongs to Dave!' | def set_computer_desc(desc=None):
if six.PY2:
desc = _to_unicode(desc)
# Make sure the system exists
# Return an object containing current information array for the computer
system_info = win32net.NetServerGetInfo(None, 101)
# If desc is passed, decode it for unicode
if desc is None:
return False
system_info['comment'] = desc
# Apply new settings
try:
win32net.NetServerSetInfo(None, 101, system_info)
except win32net.error as exc:
(number, context, message) = exc.args
log.error('Failed to update system')
log.error('nbr: %s', number)
log.error('ctx: %s', context)
log.error('msg: %s', message)
return False
return {'Computer Description': get_computer_desc()} | 63,936 |
Set the hostname of the windows minion, requires a restart before this will
be updated.
.. versionadded:: 2016.3.0
Args:
hostname (str): The hostname to set
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
salt 'minion-id' system.set_hostname newhostname | def set_hostname(hostname):
with salt.utils.winapi.Com():
conn = wmi.WMI()
comp = conn.Win32_ComputerSystem()[0]
return comp.Rename(Name=hostname) | 63,938 |
A helper function that attempts to parse the input time_str as a date.
Args:
time_str (str): A string representing the time
fmts (list): A list of date format strings
Returns:
datetime: Returns a datetime object if parsed properly, otherwise None | def _try_parse_datetime(time_str, fmts):
result = None
for fmt in fmts:
try:
result = datetime.strptime(time_str, fmt)
break
except ValueError:
pass
return result | 63,944 |
Set the Windows system date. Use <mm-dd-yy> format for the date.
Args:
newdate (str):
The date to set. Can be any of the following formats
- YYYY-MM-DD
- MM-DD-YYYY
- MM-DD-YY
- MM/DD/YYYY
- MM/DD/YY
- YYYY/MM/DD
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
salt '*' system.set_system_date '03-28-13' | def set_system_date(newdate):
fmts = ['%Y-%m-%d', '%m-%d-%Y', '%m-%d-%y',
'%m/%d/%Y', '%m/%d/%y', '%Y/%m/%d']
# Get date/time object from newdate
dt_obj = _try_parse_datetime(newdate, fmts)
if dt_obj is None:
return False
# Set time using set_system_date_time()
return set_system_date_time(years=dt_obj.year,
months=dt_obj.month,
days=dt_obj.day) | 63,947 |
Ensures that the named bridge exists, eventually creates it.
Args:
name: The name of the bridge.
parent: The name of the parent bridge (if the bridge shall be created
as a fake bridge). If specified, vlan must also be specified.
vlan: The VLAN ID of the bridge (if the bridge shall be created as a
fake bridge). If specified, parent must also be specified. | def present(name, parent=None, vlan=None):
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
# Comment and change messages
comment_bridge_created = 'Bridge {0} created.'.format(name)
comment_bridge_notcreated = 'Unable to create bridge: {0}.'.format(name)
comment_bridge_exists = 'Bridge {0} already exists.'.format(name)
comment_bridge_mismatch = ('Bridge {0} already exists, but has a different'
' parent or VLAN ID.').format(name)
changes_bridge_created = {name: {'old': 'Bridge {0} does not exist.'.format(name),
'new': 'Bridge {0} created'.format(name),
}
}
bridge_exists = __salt__['openvswitch.bridge_exists'](name)
if bridge_exists:
current_parent = __salt__['openvswitch.bridge_to_parent'](name)
if current_parent == name:
current_parent = None
current_vlan = __salt__['openvswitch.bridge_to_vlan'](name)
if current_vlan == 0:
current_vlan = None
# Dry run, test=true mode
if __opts__['test']:
if bridge_exists:
if current_parent == parent and current_vlan == vlan:
ret['result'] = True
ret['comment'] = comment_bridge_exists
else:
ret['result'] = False
ret['comment'] = comment_bridge_mismatch
else:
ret['result'] = None
ret['comment'] = comment_bridge_created
return ret
if bridge_exists:
if current_parent == parent and current_vlan == vlan:
ret['result'] = True
ret['comment'] = comment_bridge_exists
else:
ret['result'] = False
ret['comment'] = comment_bridge_mismatch
else:
bridge_create = __salt__['openvswitch.bridge_create'](
name, parent=parent, vlan=vlan)
if bridge_create:
ret['result'] = True
ret['comment'] = comment_bridge_created
ret['changes'] = changes_bridge_created
else:
ret['result'] = False
ret['comment'] = comment_bridge_notcreated
return ret | 63,963 |
Ensures that the named bridge does not exist, eventually deletes it.
Args:
name: The name of the bridge. | def absent(name):
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
# Comment and change messages
comment_bridge_deleted = 'Bridge {0} deleted.'.format(name)
comment_bridge_notdeleted = 'Unable to delete bridge: {0}.'.format(name)
comment_bridge_notexists = 'Bridge {0} does not exist.'.format(name)
changes_bridge_deleted = {name: {'old': 'Bridge {0} exists.'.format(name),
'new': 'Bridge {0} deleted.'.format(name),
}
}
bridge_exists = __salt__['openvswitch.bridge_exists'](name)
# Dry run, test=true mode
if __opts__['test']:
if not bridge_exists:
ret['result'] = True
ret['comment'] = comment_bridge_notexists
else:
ret['result'] = None
ret['comment'] = comment_bridge_deleted
return ret
if not bridge_exists:
ret['result'] = True
ret['comment'] = comment_bridge_notexists
else:
bridge_delete = __salt__['openvswitch.bridge_delete'](name)
if bridge_delete:
ret['result'] = True
ret['comment'] = comment_bridge_deleted
ret['changes'] = changes_bridge_deleted
else:
ret['result'] = False
ret['comment'] = comment_bridge_notdeleted
return ret | 63,964 |
Internal function for running commands. Used by the uninstall function.
Args:
cmd (str, list): The command to run
Returns:
str: The stdout of the command | def _run(self, cmd):
if isinstance(cmd, six.string_types):
cmd = salt.utils.args.shlex_split(cmd)
try:
log.debug(cmd)
p = subprocess.Popen(
cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
return p.communicate()
except (OSError, IOError) as exc:
log.debug('Command Failed: %s', ' '.join(cmd))
log.debug('Error: %s', exc)
raise CommandExecutionError(exc) | 66,018 |
Get the Security ID for the user
Args:
username (str): The user name for which to look up the SID
Returns:
str: The user SID
CLI Example:
.. code-block:: bash
salt '*' user.getUserSid jsnuffy | def getUserSid(username):
if six.PY2:
username = _to_unicode(username)
domain = win32api.GetComputerName()
if username.find('\\') != -1:
domain = username.split('\\')[0]
username = username.split('\\')[-1]
domain = domain.upper()
return win32security.ConvertSidToStringSid(
win32security.LookupAccountName(None, domain + '\\' + username)[0]) | 66,060 |
Add user to a group
Args:
name (str): The user name to add to the group
group (str): The name of the group to which to add the user
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' user.addgroup jsnuffy 'Power Users' | def addgroup(name, group):
if six.PY2:
name = _to_unicode(name)
group = _to_unicode(group)
name = _cmd_quote(name)
group = _cmd_quote(group).lstrip('\'').rstrip('\'')
user = info(name)
if not user:
return False
if group in user['groups']:
return True
cmd = 'net localgroup "{0}" {1} /add'.format(group, name)
ret = __salt__['cmd.run_all'](cmd, python_shell=True)
return ret['retcode'] == 0 | 66,061 |
Change the home directory of the user, pass True for persist to move files
to the new home directory if the old home directory exist.
Args:
name (str): The name of the user whose home directory you wish to change
home (str): The new location of the home directory
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' user.chhome foo \\\\fileserver\\home\\foo True | def chhome(name, home, **kwargs):
if six.PY2:
name = _to_unicode(name)
home = _to_unicode(home)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
persist = kwargs.pop('persist', False)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if persist:
log.info('Ignoring unsupported \'persist\' argument to user.chhome')
pre_info = info(name)
if not pre_info:
return False
if home == pre_info['home']:
return True
if not update(name=name, home=home):
return False
post_info = info(name)
if post_info['home'] != pre_info['home']:
return post_info['home'] == home
return False | 66,062 |
In case net user doesn't return the userprofile we can get it from the
registry
Args:
user (str): The user name, used in debug message
sid (str): The sid to lookup in the registry
Returns:
str: Profile directory | def _get_userprofile_from_registry(user, sid):
profile_dir = __utils__['reg.read_value'](
'HKEY_LOCAL_MACHINE',
'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\{0}'.format(sid),
'ProfileImagePath'
)['vdata']
log.debug(
'user %s with sid=%s profile is located at "%s"',
user, sid, profile_dir
)
return profile_dir | 66,065 |
Return a list of groups the named user belongs to
Args:
name (str): The user name for which to list groups
Returns:
list: A list of groups to which the user belongs
CLI Example:
.. code-block:: bash
salt '*' user.list_groups foo | def list_groups(name):
if six.PY2:
name = _to_unicode(name)
ugrp = set()
try:
user = info(name)['groups']
except KeyError:
return False
for group in user:
ugrp.add(group.strip(' *'))
return sorted(list(ugrp)) | 66,066 |
Return the list of all info for all users
Args:
refresh (bool, optional): Refresh the cached user information. Useful
when used from within a state function. Default is False.
Returns:
dict: A dictionary containing information about all users on the system
CLI Example:
.. code-block:: bash
salt '*' user.getent | def getent(refresh=False):
if 'user.getent' in __context__ and not refresh:
return __context__['user.getent']
ret = []
for user in __salt__['user.list_users']():
stuff = {}
user_info = __salt__['user.info'](user)
stuff['gid'] = ''
stuff['groups'] = user_info['groups']
stuff['home'] = user_info['home']
stuff['name'] = user_info['name']
stuff['passwd'] = user_info['passwd']
stuff['shell'] = ''
stuff['uid'] = user_info['uid']
ret.append(stuff)
__context__['user.getent'] = ret
return ret | 66,067 |
Change the username for a named user
Args:
name (str): The user name to change
new_name (str): The new name for the current user
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' user.rename jsnuffy jshmoe | def rename(name, new_name):
if six.PY2:
name = _to_unicode(name)
new_name = _to_unicode(new_name)
# Load information for the current name
current_info = info(name)
if not current_info:
raise CommandExecutionError('User \'{0}\' does not exist'.format(name))
# Look for an existing user with the new name
new_info = info(new_name)
if new_info:
raise CommandExecutionError(
'User \'{0}\' already exists'.format(new_name)
)
# Rename the user account
# Connect to WMI
with salt.utils.winapi.Com():
c = wmi.WMI(find_classes=0)
# Get the user object
try:
user = c.Win32_UserAccount(Name=name)[0]
except IndexError:
raise CommandExecutionError('User \'{0}\' does not exist'.format(name))
# Rename the user
result = user.Rename(new_name)[0]
# Check the result (0 means success)
if not result == 0:
# Define Error Dict
error_dict = {0: 'Success',
1: 'Instance not found',
2: 'Instance required',
3: 'Invalid parameter',
4: 'User not found',
5: 'Domain not found',
6: 'Operation is allowed only on the primary domain controller of the domain',
7: 'Operation is not allowed on the last administrative account',
8: 'Operation is not allowed on specified special groups: user, admin, local, or guest',
9: 'Other API error',
10: 'Internal error'}
raise CommandExecutionError(
'There was an error renaming \'{0}\' to \'{1}\'. Error: {2}'
.format(name, new_name, error_dict[result])
)
return info(new_name).get('name') == new_name | 66,069 |
Internal function for obfuscating the password used for AutoLogin
This is later written as the contents of the ``/etc/kcpassword`` file
.. versionadded:: 2017.7.3
Adapted from:
https://github.com/timsutton/osx-vm-templates/blob/master/scripts/support/set_kcpassword.py
Args:
password(str):
The password to obfuscate
Returns:
str: The obfuscated password | def _kcpassword(password):
# The magic 11 bytes - these are just repeated
# 0x7D 0x89 0x52 0x23 0xD2 0xBC 0xDD 0xEA 0xA3 0xB9 0x1F
key = [125, 137, 82, 35, 210, 188, 221, 234, 163, 185, 31]
key_len = len(key)
# Convert each character to a byte
password = list(map(ord, password))
# pad password length out to an even multiple of key length
remainder = len(password) % key_len
if remainder > 0:
password = password + [0] * (key_len - remainder)
# Break the password into chunks the size of len(key) (11)
for chunk_index in range(0, len(password), len(key)):
# Reset the key_index to 0 for each iteration
key_index = 0
# Do an XOR on each character of that chunk of the password with the
# corresponding item in the key
# The length of the password, or the length of the key, whichever is
# smaller
for password_index in range(chunk_index,
min(chunk_index + len(key), len(password))):
password[password_index] = password[password_index] ^ key[key_index]
key_index += 1
# Convert each byte back to a character
password = list(map(chr, password))
return b''.join(salt.utils.data.encode(password)) | 66,160 |
.. versionadded:: 2016.3.0
Configures the machine to auto login with the specified user
Args:
name (str): The user account use for auto login
password (str): The password to user for auto login
.. versionadded:: 2017.7.3
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
salt '*' user.enable_auto_login stevej | def enable_auto_login(name, password):
# Make the entry into the defaults file
cmd = ['defaults',
'write',
'/Library/Preferences/com.apple.loginwindow.plist',
'autoLoginUser',
name]
__salt__['cmd.run'](cmd)
current = get_auto_login()
# Create/Update the kcpassword file with an obfuscated password
o_password = _kcpassword(password=password)
with salt.utils.files.set_umask(0o077):
with salt.utils.files.fopen('/etc/kcpassword', 'w' if six.PY2 else 'wb') as fd:
fd.write(o_password)
return current if isinstance(current, bool) else current.lower() == name.lower() | 66,161 |
Get the ACL of an object. Will filter by user if one is provided.
Args:
path: The path to the object
objectType: The type of object (FILE, DIRECTORY, REGISTRY)
user: A user name to filter by
Returns (dict): A dictionary containing the ACL
CLI Example:
.. code-block:: bash
salt 'minion-id' win_dacl.get c:\temp directory | def get(path, objectType, user=None):
ret = {'Path': path,
'ACLs': []}
sidRet = _getUserSid(user)
if path and objectType:
dc = daclConstants()
objectTypeBit = dc.getObjectTypeBit(objectType)
path = dc.processPath(path, objectTypeBit)
tdacl = _get_dacl(path, objectTypeBit)
if tdacl:
for counter in range(0, tdacl.GetAceCount()):
tAce = tdacl.GetAce(counter)
if not sidRet['sid'] or (tAce[2] == sidRet['sid']):
ret['ACLs'].append(_ace_to_text(tAce, objectTypeBit))
return ret | 66,451 |
helper function to set the inheritance
Args:
path (str): The path to the object
objectType (str): The type of object
inheritance (bool): True enables inheritance, False disables
copy (bool): Copy inherited ACEs to the DACL before disabling
inheritance
clear (bool): Remove non-inherited ACEs from the DACL | def _set_dacl_inheritance(path, objectType, inheritance=True, copy=True, clear=False):
ret = {'result': False,
'comment': '',
'changes': {}}
if path:
try:
sd = win32security.GetNamedSecurityInfo(path, objectType, win32security.DACL_SECURITY_INFORMATION)
tdacl = sd.GetSecurityDescriptorDacl()
if inheritance:
if clear:
counter = 0
removedAces = []
while counter < tdacl.GetAceCount():
tAce = tdacl.GetAce(counter)
if (tAce[0][1] & win32security.INHERITED_ACE) != win32security.INHERITED_ACE:
tdacl.DeleteAce(counter)
removedAces.append(_ace_to_text(tAce, objectType))
else:
counter = counter + 1
if removedAces:
ret['changes']['Removed ACEs'] = removedAces
else:
ret['changes']['Non-Inherited ACEs'] = 'Left in the DACL'
win32security.SetNamedSecurityInfo(
path, objectType,
win32security.DACL_SECURITY_INFORMATION | win32security.UNPROTECTED_DACL_SECURITY_INFORMATION,
None, None, tdacl, None)
ret['changes']['Inheritance'] = 'Enabled'
else:
if not copy:
counter = 0
inheritedAcesRemoved = []
while counter < tdacl.GetAceCount():
tAce = tdacl.GetAce(counter)
if (tAce[0][1] & win32security.INHERITED_ACE) == win32security.INHERITED_ACE:
tdacl.DeleteAce(counter)
inheritedAcesRemoved.append(_ace_to_text(tAce, objectType))
else:
counter = counter + 1
if inheritedAcesRemoved:
ret['changes']['Removed ACEs'] = inheritedAcesRemoved
else:
ret['changes']['Previously Inherited ACEs'] = 'Copied to the DACL'
win32security.SetNamedSecurityInfo(
path, objectType,
win32security.DACL_SECURITY_INFORMATION | win32security.PROTECTED_DACL_SECURITY_INFORMATION,
None, None, tdacl, None)
ret['changes']['Inheritance'] = 'Disabled'
ret['result'] = True
except Exception as e:
ret['result'] = False
ret['comment'] = 'Error attempting to set the inheritance. The error was {0}.'.format(e)
return ret | 66,455 |
enable/disable inheritance on an object
Args:
path: The path to the object
objectType: The type of object (FILE, DIRECTORY, REGISTRY)
clear: True will remove non-Inherited ACEs from the ACL
Returns (dict): A dictionary containing the results
CLI Example:
.. code-block:: bash
salt 'minion-id' win_dacl.enable_inheritance c:\temp directory | def enable_inheritance(path, objectType, clear=False):
dc = daclConstants()
objectType = dc.getObjectTypeBit(objectType)
path = dc.processPath(path, objectType)
return _set_dacl_inheritance(path, objectType, True, None, clear) | 66,456 |
Disable inheritance on an object
Args:
path: The path to the object
objectType: The type of object (FILE, DIRECTORY, REGISTRY)
copy: True will copy the Inherited ACEs to the DACL before disabling inheritance
Returns (dict): A dictionary containing the results
CLI Example:
.. code-block:: bash
salt 'minion-id' win_dacl.disable_inheritance c:\temp directory | def disable_inheritance(path, objectType, copy=True):
dc = daclConstants()
objectType = dc.getObjectTypeBit(objectType)
path = dc.processPath(path, objectType)
return _set_dacl_inheritance(path, objectType, False, copy, None) | 66,457 |
Check a specified path to verify if inheritance is enabled
Args:
path: path of the registry key or file system object to check
objectType: The type of object (FILE, DIRECTORY, REGISTRY)
user: if provided, will consider only the ACEs for that user
Returns (bool): 'Inheritance' of True/False
CLI Example:
.. code-block:: bash
salt 'minion-id' win_dacl.check_inheritance c:\temp directory <username> | def check_inheritance(path, objectType, user=None):
ret = {'result': False,
'Inheritance': False,
'comment': ''}
sidRet = _getUserSid(user)
dc = daclConstants()
objectType = dc.getObjectTypeBit(objectType)
path = dc.processPath(path, objectType)
try:
sd = win32security.GetNamedSecurityInfo(path, objectType, win32security.DACL_SECURITY_INFORMATION)
dacls = sd.GetSecurityDescriptorDacl()
except Exception as e:
ret['result'] = False
ret['comment'] = 'Error obtaining the Security Descriptor or DACL of the path: {0}.'.format(e)
return ret
for counter in range(0, dacls.GetAceCount()):
ace = dacls.GetAce(counter)
if (ace[0][1] & win32security.INHERITED_ACE) == win32security.INHERITED_ACE:
if not sidRet['sid'] or ace[2] == sidRet['sid']:
ret['Inheritance'] = True
break
ret['result'] = True
return ret | 66,458 |
Gets the difference between the candidate and the current configuration.
.. code-block:: yaml
get the diff:
junos:
- diff
- id: 10
Parameters:
Optional
* id:
The rollback id value [0-49]. (default = 0) | def diff(name, **kwargs):
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.diff'](**kwargs)
return ret | 66,922 |
Shuts down the device.
.. code-block:: yaml
shut the device:
junos:
- shutdown
- in_min: 10
Parameters:
Optional
* kwargs:
* reboot:
Whether to reboot instead of shutdown. (default=False)
* at:
Specify time for reboot. (To be used only if reboot=yes)
* in_min:
Specify delay in minutes for shutdown | def shutdown(name, **kwargs):
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.shutdown'](**kwargs)
return ret | 66,924 |
Copies the file from the local device to the junos device.
.. code-block:: yaml
/home/m2/info.txt:
junos:
- file_copy
- dest: info_copy.txt
Parameters:
Required
* src:
The sorce path where the file is kept.
* dest:
The destination path where the file will be copied. | def file_copy(name, dest=None, **kwargs):
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.file_copy'](name, dest, **kwargs)
return ret | 66,927 |
List details of available certificates in the LocalMachine certificate
store.
Args:
certificate_store (str): The name of the certificate store on the local
machine.
Returns:
dict: A dictionary of certificates found in the store | def _list_certs(certificate_store='My'):
ret = dict()
blacklist_keys = ['DnsNameList', 'Thumbprint']
ps_cmd = ['Get-ChildItem',
'-Path', r"'Cert:\LocalMachine\{0}'".format(certificate_store),
'|',
'Select-Object DnsNameList, SerialNumber, Subject, Thumbprint, Version']
cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True)
try:
items = salt.utils.json.loads(cmd_ret['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Unable to parse return data as Json.')
for item in items:
cert_info = dict()
for key in item:
if key not in blacklist_keys:
cert_info[key.lower()] = item[key]
cert_info['dnsnames'] = []
if item['DnsNameList']:
cert_info['dnsnames'] = [name['Unicode'] for name in item['DnsNameList']]
ret[item['Thumbprint']] = cert_info
return ret | 67,004 |
Execute a powershell command from the WebAdministration PS module.
Args:
cmd (list): The command to execute in a list
return_json (bool): True formats the return in JSON, False just returns
the output of the command.
Returns:
str: The output from the command | def _srvmgr(cmd, return_json=False):
if isinstance(cmd, list):
cmd = ' '.join(cmd)
if return_json:
cmd = 'ConvertTo-Json -Compress -Depth 4 -InputObject @({0})' \
''.format(cmd)
cmd = 'Import-Module WebAdministration; {0}'.format(cmd)
ret = __salt__['cmd.run_all'](cmd, shell='powershell', python_shell=True)
if ret['retcode'] != 0:
msg = 'Unable to execute command: {0}\nError: {1}' \
''.format(cmd, ret['stderr'])
log.error(msg)
return ret | 67,006 |
Delete a website from IIS.
Args:
name (str): The IIS site name.
Returns:
bool: True if successful, otherwise False
.. note::
This will not remove the application pool used by the site.
CLI Example:
.. code-block:: bash
salt '*' win_iis.remove_site name='My Test Site' | def remove_site(name):
current_sites = list_sites()
if name not in current_sites:
log.debug('Site already absent: %s', name)
return True
ps_cmd = ['Remove-WebSite', '-Name', r"'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to remove site: {0}\nError: {1}' \
''.format(name, cmd_ret['stderr'])
raise CommandExecutionError(msg)
log.debug('Site removed successfully: %s', name)
return True | 67,012 |
Stop a Web Site in IIS.
.. versionadded:: 2017.7.0
Args:
name (str): The name of the website to stop.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.stop_site name='My Test Site' | def stop_site(name):
ps_cmd = ['Stop-WebSite', r"'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
return cmd_ret['retcode'] == 0 | 67,013 |
Start a Web Site in IIS.
.. versionadded:: 2017.7.0
Args:
name (str): The name of the website to start.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.start_site name='My Test Site' | def start_site(name):
ps_cmd = ['Start-WebSite', r"'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
return cmd_ret['retcode'] == 0 | 67,014 |
Get all configured IIS bindings for the specified site.
Args:
site (str): The name if the IIS Site
Returns:
dict: A dictionary of the binding names and properties.
CLI Example:
.. code-block:: bash
salt '*' win_iis.list_bindings site | def list_bindings(site):
ret = dict()
sites = list_sites()
if site not in sites:
log.warning('Site not found: %s', site)
return ret
ret = sites[site]['bindings']
if not ret:
log.warning('No bindings found for site: %s', site)
return ret | 67,015 |
Remove an IIS binding.
Args:
site (str): The IIS site name.
hostheader (str): The host header of the binding.
ipaddress (str): The IP address of the binding.
port (int): The TCP port of the binding.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.remove_binding site='site0' hostheader='example.com' ipaddress='*' port='80' | def remove_binding(site, hostheader='', ipaddress='*', port=80):
name = _get_binding_info(hostheader, ipaddress, port)
current_bindings = list_bindings(site)
if name not in current_bindings:
log.debug('Binding already absent: %s', name)
return True
ps_cmd = ['Remove-WebBinding',
'-HostHeader', "'{0}'".format(hostheader),
'-IpAddress', "'{0}'".format(ipaddress),
'-Port', "'{0}'".format(port)]
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to remove binding: {0}\nError: {1}' \
''.format(site, cmd_ret['stderr'])
raise CommandExecutionError(msg)
if name not in list_bindings(site):
log.debug('Binding removed successfully: %s', site)
return True
log.error('Unable to remove binding: %s', site)
return False | 67,018 |
List certificate bindings for an IIS site.
.. versionadded:: 2016.11.0
Args:
site (str): The IIS site name.
Returns:
dict: A dictionary of the binding names and properties.
CLI Example:
.. code-block:: bash
salt '*' win_iis.list_bindings site | def list_cert_bindings(site):
ret = dict()
sites = list_sites()
if site not in sites:
log.warning('Site not found: %s', site)
return ret
for binding in sites[site]['bindings']:
if sites[site]['bindings'][binding]['certificatehash']:
ret[binding] = sites[site]['bindings'][binding]
if not ret:
log.warning('No certificate bindings found for site: %s', site)
return ret | 67,019 |
Stop an IIS application pool.
.. versionadded:: 2017.7.0
Args:
name (str): The name of the App Pool to stop.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.stop_apppool name='MyTestPool' | def stop_apppool(name):
ps_cmd = ['Stop-WebAppPool', r"'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
return cmd_ret['retcode'] == 0 | 67,024 |
Start an IIS application pool.
.. versionadded:: 2017.7.0
Args:
name (str): The name of the App Pool to start.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.start_apppool name='MyTestPool' | def start_apppool(name):
ps_cmd = ['Start-WebAppPool', r"'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
return cmd_ret['retcode'] == 0 | 67,025 |
Restart an IIS application pool.
.. versionadded:: 2016.11.0
Args:
name (str): The name of the IIS application pool.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.restart_apppool name='MyTestPool' | def restart_apppool(name):
ps_cmd = ['Restart-WebAppPool', r"'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
return cmd_ret['retcode'] == 0 | 67,026 |
Get all configured IIS applications for the specified site.
Args:
site (str): The IIS site name.
Returns: A dictionary of the application names and properties.
CLI Example:
.. code-block:: bash
salt '*' win_iis.list_apps site | def list_apps(site):
ret = dict()
ps_cmd = list()
ps_cmd.append("Get-WebApplication -Site '{0}'".format(site))
ps_cmd.append(r"| Select-Object applicationPool, path, PhysicalPath, preloadEnabled,")
ps_cmd.append(r"@{ Name='name'; Expression={ $_.path.Split('/', 2)[-1] } },")
ps_cmd.append(r"@{ Name='protocols'; Expression={ @( $_.enabledProtocols.Split(',')")
ps_cmd.append(r"| Foreach-Object { $_.Trim() } ) } }")
cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True)
try:
items = salt.utils.json.loads(cmd_ret['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Unable to parse return data as Json.')
for item in items:
protocols = list()
# If there are no associated protocols, protocols will be an empty dict,
# if there is one protocol, it will be a string, and if there are
# multiple, it will be a dict with 'Count' and 'value' as the keys.
if isinstance(item['protocols'], dict):
if 'value' in item['protocols']:
protocols += item['protocols']['value']
else:
protocols.append(item['protocols'])
ret[item['name']] = {'apppool': item['applicationPool'],
'path': item['path'],
'preload': item['preloadEnabled'],
'protocols': protocols,
'sourcepath': item['PhysicalPath']}
if not ret:
log.warning('No apps found in output: %s', cmd_ret)
return ret | 67,029 |
Remove an IIS application.
Args:
name (str): The application name.
site (str): The IIS site name.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.remove_app name='app0' site='site0' | def remove_app(name, site):
current_apps = list_apps(site)
if name not in current_apps:
log.debug('Application already absent: %s', name)
return True
ps_cmd = ['Remove-WebApplication',
'-Name', "'{0}'".format(name),
'-Site', "'{0}'".format(site)]
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to remove application: {0}\nError: {1}' \
''.format(name, cmd_ret['stderr'])
raise CommandExecutionError(msg)
new_apps = list_apps(site)
if name not in new_apps:
log.debug('Application removed successfully: %s', name)
return True
log.error('Unable to remove application: %s', name)
return False | 67,031 |
Get all configured IIS virtual directories for the specified site, or for
the combination of site and application.
Args:
site (str): The IIS site name.
app (str): The IIS application.
Returns:
dict: A dictionary of the virtual directory names and properties.
CLI Example:
.. code-block:: bash
salt '*' win_iis.list_vdirs site | def list_vdirs(site, app=_DEFAULT_APP):
ret = dict()
ps_cmd = ['Get-WebVirtualDirectory',
'-Site', r"'{0}'".format(site),
'-Application', r"'{0}'".format(app),
'|', "Select-Object PhysicalPath, @{ Name = 'name';",
r"Expression = { $_.path.Split('/')[-1] } }"]
cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True)
try:
items = salt.utils.json.loads(cmd_ret['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Unable to parse return data as Json.')
for item in items:
ret[item['name']] = {'sourcepath': item['physicalPath']}
if not ret:
log.warning('No vdirs found in output: %s', cmd_ret)
return ret | 67,032 |
Remove an IIS virtual directory.
Args:
name (str): The virtual directory name.
site (str): The IIS site name.
app (str): The IIS application.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.remove_vdir name='vdir0' site='site0' | def remove_vdir(name, site, app=_DEFAULT_APP):
current_vdirs = list_vdirs(site, app)
app_path = os.path.join(*app.rstrip('/').split('/'))
if app_path:
app_path = '{0}\\'.format(app_path)
vdir_path = r'IIS:\Sites\{0}\{1}{2}'.format(site, app_path, name)
if name not in current_vdirs:
log.debug('Virtual directory already absent: %s', name)
return True
# We use Remove-Item here instead of Remove-WebVirtualDirectory, since the
# latter has a bug that causes it to always prompt for user input.
ps_cmd = ['Remove-Item',
'-Path', r"'{0}'".format(vdir_path),
'-Recurse']
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to remove virtual directory: {0}\nError: {1}' \
''.format(name, cmd_ret['stderr'])
raise CommandExecutionError(msg)
new_vdirs = list_vdirs(site, app)
if name not in new_vdirs:
log.debug('Virtual directory removed successfully: %s', name)
return True
log.error('Unable to remove virtual directory: %s', name)
return False | 67,034 |
r'''
Backup an IIS Configuration on the System.
.. versionadded:: 2017.7.0
.. note::
Backups are stored in the ``$env:Windir\System32\inetsrv\backup``
folder.
Args:
name (str): The name to give the backup
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.create_backup good_config_20170209 | def create_backup(name):
r
if name in list_backups():
raise CommandExecutionError('Backup already present: {0}'.format(name))
ps_cmd = ['Backup-WebConfiguration',
'-Name', "'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to backup web configuration: {0}\nError: {1}' \
''.format(name, cmd_ret['stderr'])
raise CommandExecutionError(msg)
return name in list_backups() | 67,035 |
Remove an IIS Configuration backup from the System.
.. versionadded:: 2017.7.0
Args:
name (str): The name of the backup to remove
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.remove_backup backup_20170209 | def remove_backup(name):
if name not in list_backups():
log.debug('Backup already removed: %s', name)
return True
ps_cmd = ['Remove-WebConfigurationBackup',
'-Name', "'{0}'".format(name)]
cmd_ret = _srvmgr(ps_cmd)
if cmd_ret['retcode'] != 0:
msg = 'Unable to remove web configuration: {0}\nError: {1}' \
''.format(name, cmd_ret['stderr'])
raise CommandExecutionError(msg)
return name not in list_backups() | 67,036 |
Returns a list of worker processes that correspond to the passed
application pool.
.. versionadded:: 2017.7.0
Args:
apppool (str): The application pool to query
Returns:
dict: A dictionary of worker processes with their process IDs
CLI Example:
.. code-block:: bash
salt '*' win_iis.list_worker_processes 'My App Pool' | def list_worker_processes(apppool):
ps_cmd = ['Get-ChildItem',
r"'IIS:\AppPools\{0}\WorkerProcesses'".format(apppool)]
cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True)
try:
items = salt.utils.json.loads(cmd_ret['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Unable to parse return data as Json.')
ret = dict()
for item in items:
ret[item['processId']] = item['appPoolName']
if not ret:
log.warning('No backups found in output: %s', cmd_ret)
return ret | 67,037 |
Helper function for adding new IDE controllers
.. versionadded:: 2016.3.0
Args:
ide_controller_label: label of the IDE controller
controller_key: if not None, the controller key to use; otherwise it is randomly generated
bus_number: bus number
Returns: created device spec for an IDE controller | def _add_new_ide_controller_helper(ide_controller_label,
controller_key,
bus_number):
if controller_key is None:
controller_key = randint(-200, 250)
ide_spec = vim.vm.device.VirtualDeviceSpec()
ide_spec.device = vim.vm.device.VirtualIDEController()
ide_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
ide_spec.device.key = controller_key
ide_spec.device.busNumber = bus_number
ide_spec.device.deviceInfo = vim.Description()
ide_spec.device.deviceInfo.label = ide_controller_label
ide_spec.device.deviceInfo.summary = ide_controller_label
return ide_spec | 67,056 |
Check if the package is valid on the given mirrors.
Args:
package: The name of the package
cyg_arch: The cygwin architecture
mirrors: any mirrors to check
Returns (bool): True if Valid, otherwise False
CLI Example:
.. code-block:: bash
salt '*' cyg.check_valid_package <package name> | def check_valid_package(package,
cyg_arch='x86_64',
mirrors=None):
if mirrors is None:
mirrors = [{DEFAULT_MIRROR: DEFAULT_MIRROR_KEY}]
LOG.debug('Checking Valid Mirrors: %s', mirrors)
for mirror in mirrors:
for mirror_url, key in mirror.items():
if package in _get_all_packages(mirror_url, cyg_arch):
return True
return False | 67,632 |
Manage the sending of authentication traps.
Args:
status (bool): True to enable traps. False to disable.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_snmp.set_auth_traps_enabled status='True' | def set_auth_traps_enabled(status=True):
vname = 'EnableAuthenticationTraps'
current_status = get_auth_traps_enabled()
if bool(status) == current_status:
_LOG.debug('%s already contains the provided value.', vname)
return True
vdata = int(status)
__utils__['reg.set_value'](_HKEY, _SNMP_KEY, vname, vdata, 'REG_DWORD')
new_status = get_auth_traps_enabled()
if status == new_status:
_LOG.debug('Setting %s configured successfully: %s', vname, vdata)
return True
_LOG.error('Unable to configure %s with value: %s', vname, vdata)
return False | 67,982 |
This module can also be run directly for testing
Args:
detail|list : Provide ``detail`` or version ``list``.
system|system+user: System installed and System and User installs. | def __main():
if len(sys.argv) < 3:
sys.stderr.write('usage: {0} <detail|list> <system|system+user>\n'.format(sys.argv[0]))
sys.exit(64)
user_pkgs = False
version_only = False
if six.text_type(sys.argv[1]) == 'list':
version_only = True
if six.text_type(sys.argv[2]) == 'system+user':
user_pkgs = True
import salt.utils.json
import timeit
def run():
pkg_list = WinSoftware(user_pkgs=user_pkgs, version_only=version_only)
print(salt.utils.json.dumps(pkg_list.data, sort_keys=True, indent=4)) # pylint: disable=superfluous-parens
print('Total: {}'.format(len(pkg_list))) # pylint: disable=superfluous-parens
print('Time Taken: {}'.format(timeit.timeit(run, number=1))) | 69,142 |
Squished GUID (SQUID) to GUID.
A SQUID is a Squished/Compressed version of a GUID to use up less space
in the registry.
Args:
squid (str): Squished GUID.
Returns:
str: the GUID if a valid SQUID provided. | def __squid_to_guid(self, squid):
if not squid:
return ''
squid_match = self.__squid_pattern.match(squid)
guid = ''
if squid_match is not None:
guid = '{' +\
squid_match.group(1)[::-1]+'-' +\
squid_match.group(2)[::-1]+'-' +\
squid_match.group(3)[::-1]+'-' +\
squid_match.group(4)[::-1]+squid_match.group(5)[::-1] + '-'
for index in range(6, 12):
guid += squid_match.group(index)[::-1]
guid += '}'
return guid | 69,144 |
Test for ``1`` as a number or a string and return ``True`` if it is.
Args:
value: string or number or None.
Returns:
bool: ``True`` if 1 otherwise ``False``. | def __one_equals_true(value):
if isinstance(value, six.integer_types) and value == 1:
return True
elif (isinstance(value, six.string_types) and
re.match(r'\d+', value, flags=re.IGNORECASE + re.UNICODE) is not None and
six.text_type(value) == '1'):
return True
return False | 69,145 |
Calls RegQueryValueEx
If PY2 ensure unicode string and expand REG_EXPAND_SZ before returning
Remember to catch not found exceptions when calling.
Args:
handle (object): open registry handle.
value_name (str): Name of the value you wished returned
Returns:
tuple: type, value | def __reg_query_value(handle, value_name):
# item_value, item_type = win32api.RegQueryValueEx(self.__reg_uninstall_handle, value_name)
item_value, item_type = win32api.RegQueryValueEx(handle, value_name) # pylint: disable=no-member
if six.PY2 and isinstance(item_value, six.string_types) and not isinstance(item_value, six.text_type):
try:
item_value = six.text_type(item_value, encoding='mbcs')
except UnicodeError:
pass
if item_type == win32con.REG_EXPAND_SZ:
# expects Unicode input
win32api.ExpandEnvironmentStrings(item_value) # pylint: disable=no-member
item_type = win32con.REG_SZ
return item_value, item_type | 69,146 |
For the uninstall section of the registry return the name value.
Args:
value_name (str): Registry value name.
wanted_type (str):
The type of value wanted if the type does not match
None is return. wanted_type support values are
``str`` ``int`` ``list`` ``bytes``.
Returns:
value: Value requested or None if not found. | def get_install_value(self, value_name, wanted_type=None):
try:
item_value, item_type = self.__reg_query_value(self.__reg_uninstall_handle, value_name)
except pywintypes.error as exc: # pylint: disable=no-member
if exc.winerror == winerror.ERROR_FILE_NOT_FOUND:
# Not Found
return None
raise
if wanted_type and item_type not in self.__reg_types[wanted_type]:
item_value = None
return item_value | 69,148 |
For the product section of the registry return the name value.
Args:
value_name (str): Registry value name.
wanted_type (str):
The type of value wanted if the type does not match
None is return. wanted_type support values are
``str`` ``int`` ``list`` ``bytes``.
Returns:
value: Value requested or ``None`` if not found. | def get_product_value(self, value_name, wanted_type=None):
if not self.__reg_products_handle:
return None
subkey, search_value_name = os.path.split(value_name)
try:
if subkey:
handle = win32api.RegOpenKeyEx( # pylint: disable=no-member
self.__reg_products_handle,
subkey,
0,
win32con.KEY_READ | self.__reg_32bit_access)
item_value, item_type = self.__reg_query_value(handle, search_value_name)
win32api.RegCloseKey(handle) # pylint: disable=no-member
else:
item_value, item_type = \
win32api.RegQueryValueEx(self.__reg_products_handle, value_name) # pylint: disable=no-member
except pywintypes.error as exc: # pylint: disable=no-member
if exc.winerror == winerror.ERROR_FILE_NOT_FOUND:
# Not Found
return None
raise
if wanted_type and item_type not in self.__reg_types[wanted_type]:
item_value = None
return item_value | 69,149 |
Returns information on a package.
Args:
pkg_id (str): Package Id of the software/component
Returns:
dict or list: List if ``version_only`` is ``True`` otherwise dict | def __getitem__(self, pkg_id):
if pkg_id in self.__reg_software:
return self.__reg_software[pkg_id]
else:
raise KeyError(pkg_id) | 69,154 |
Returns information on a package.
Args:
pkg_id (str): Package Id of the software/component.
Returns:
list: List of version numbers installed. | def pkg_version_list(self, pkg_id):
pkg_data = self.__reg_software.get(pkg_id, None)
if not pkg_data:
return []
if isinstance(pkg_data, list):
# raw data is 'pkgid': [sorted version list]
return pkg_data # already sorted oldest to newest
# Must be a dict or OrderDict, and contain full details
installed_versions = list(pkg_data.get('version').keys())
return sorted(installed_versions, key=cmp_to_key(self.__oldest_to_latest_version)) | 69,156 |
Provided with a valid Windows Security Identifier (SID) and returns a Username
Args:
sid (str): Security Identifier (SID).
Returns:
str: Username in the format of username@realm or username@computer. | def __sid_to_username(sid):
if sid is None or sid == '':
return ''
try:
sid_bin = win32security.GetBinarySid(sid) # pylint: disable=no-member
except pywintypes.error as exc: # pylint: disable=no-member
raise ValueError(
'pkg: Software owned by {0} is not valid: [{1}] {2}'.format(sid, exc.winerror, exc.strerror)
)
try:
name, domain, _account_type = win32security.LookupAccountSid(None, sid_bin) # pylint: disable=no-member
user_name = '{0}\\{1}'.format(domain, name)
except pywintypes.error as exc: # pylint: disable=no-member
# if user does not exist...
# winerror.ERROR_NONE_MAPPED = No mapping between account names and
# security IDs was carried out.
if exc.winerror == winerror.ERROR_NONE_MAPPED: # 1332
# As the sid is from the registry it should be valid
# even if it cannot be lookedup, so the sid is returned
return sid
else:
raise ValueError(
'Failed looking up sid \'{0}\' username: [{1}] {2}'.format(sid, exc.winerror, exc.strerror)
)
try:
user_principal = win32security.TranslateName( # pylint: disable=no-member
user_name,
win32api.NameSamCompatible, # pylint: disable=no-member
win32api.NameUserPrincipal) # pylint: disable=no-member
except pywintypes.error as exc: # pylint: disable=no-member
# winerror.ERROR_NO_SUCH_DOMAIN The specified domain either does not exist
# or could not be contacted, computer may not be part of a domain also
# winerror.ERROR_INVALID_DOMAINNAME The format of the specified domain name is
# invalid. e.g. S-1-5-19 which is a local account
# winerror.ERROR_NONE_MAPPED No mapping between account names and security IDs was done.
if exc.winerror in (winerror.ERROR_NO_SUCH_DOMAIN,
winerror.ERROR_INVALID_DOMAINNAME,
winerror.ERROR_NONE_MAPPED):
return '{0}@{1}'.format(name.lower(), domain.lower())
else:
raise
return user_principal | 69,157 |
Convert user name to a uid
Args:
user (str): The user to lookup
Returns:
str: The user id of the user
CLI Example:
.. code-block:: bash
salt '*' file.user_to_uid myusername | def user_to_uid(user):
if user is None:
user = salt.utils.user.get_user()
return salt.utils.win_dacl.get_sid_string(user) | 69,298 |
Return the mode of a file
Right now we're just returning None because Windows' doesn't have a mode
like Linux
Args:
path (str): The path to the file or directory
Returns:
None
CLI Example:
.. code-block:: bash
salt '*' file.get_mode /etc/passwd | def get_mode(path):
if not os.path.exists(path):
raise CommandExecutionError('Path not found: {0}'.format(path))
func_name = '{0}.get_mode'.format(__virtualname__)
if __opts__.get('fun', '') == func_name:
log.info('The function %s should not be used on Windows systems; '
'see function docs for details. The value returned is '
'always None.', func_name)
return None | 69,301 |
Return a dictionary object with the Windows
file attributes for a file.
Args:
path (str): The path to the file or directory
Returns:
dict: A dictionary of file attributes
CLI Example:
.. code-block:: bash
salt '*' file.get_attributes c:\\temp\\a.txt | def get_attributes(path):
if not os.path.exists(path):
raise CommandExecutionError('Path not found: {0}'.format(path))
# set up dictionary for attribute values
attributes = {}
# Get cumulative int value of attributes
intAttributes = win32file.GetFileAttributes(path)
# Assign individual attributes
attributes['archive'] = (intAttributes & 32) == 32
attributes['reparsePoint'] = (intAttributes & 1024) == 1024
attributes['compressed'] = (intAttributes & 2048) == 2048
attributes['directory'] = (intAttributes & 16) == 16
attributes['encrypted'] = (intAttributes & 16384) == 16384
attributes['hidden'] = (intAttributes & 2) == 2
attributes['normal'] = (intAttributes & 128) == 128
attributes['notIndexed'] = (intAttributes & 8192) == 8192
attributes['offline'] = (intAttributes & 4096) == 4096
attributes['readonly'] = (intAttributes & 1) == 1
attributes['system'] = (intAttributes & 4) == 4
attributes['temporary'] = (intAttributes & 256) == 256
# check if it's a Mounted Volume
attributes['mountedVolume'] = False
if attributes['reparsePoint'] is True and attributes['directory'] is True:
fileIterator = win32file.FindFilesIterator(path)
findDataTuple = next(fileIterator)
if findDataTuple[6] == 0xA0000003:
attributes['mountedVolume'] = True
# check if it's a soft (symbolic) link
# Note: os.path.islink() does not work in
# Python 2.7 for the Windows NTFS file system.
# The following code does, however, work (tested in Windows 8)
attributes['symbolicLink'] = False
if attributes['reparsePoint'] is True:
fileIterator = win32file.FindFilesIterator(path)
findDataTuple = next(fileIterator)
if findDataTuple[6] == 0xA000000C:
attributes['symbolicLink'] = True
return attributes | 69,306 |