Splits a large CSS file into several smaller files, each one
    containing less than the IE 4096 selector limit.
4265
def split_css_for_ie_selector_limit(input_file, output_file):
    
    from .modules import bless, utils

    if not isinstance(input_file, str):
        raise RuntimeError('CSS splitter takes only a single input file.')

    return {
        'dependencies_fn': utils.no_dependencies,
        'compiler_fn': bless.bless_css,
        'input': input_file,
        'output': output_file,
        'kwargs': {},
    }
1372383
private void process(File file) throws WatchingException {
        getLog().info("Minifying CSS files from " + file.getName() + " using Clean CSS");

        File filtered = getFilteredVersion(file);
        if (filtered == null) {
            filtered = file;
        }

        File output = getMinifiedFile(file);
        if (output.exists()) {
            FileUtils.deleteQuietly(output);
        }

        if (!output.getParentFile().isDirectory()) {
            getLog().debug("Creating output directory for " + output.getAbsolutePath() + " : "
                    + output.getParentFile().mkdirs());
        }

        getLog().info("Minifying " + filtered.getAbsolutePath() + " to " + output.getAbsolutePath());
        try {
            List<String> arguments = new ArrayList<>();
            arguments.add("--output");
            arguments.add(output.getAbsolutePath());
            arguments.add("--source-map");
            if (cleanCssArguments != null) {
                arguments.addAll(Splitter.on(' ').splitToList(cleanCssArguments));
            }
            // Input file:
            arguments.add(filtered.getAbsolutePath());
            int exit = cleancss.execute("cleancss", arguments.toArray(new String[arguments.size()]));
            getLog().debug("CSS minification execution exiting with " + exit + " status");
        } catch (MojoExecutionException e) {
            throw new WatchingException("Error during the minification of " + filtered.getName(), e);
        }
    }
123659
function splitLocalFile(file, N, callback) {
  const split = [];
  const size = fs.statSync(file).size;
  const maxBlockSize = Math.ceil(size / (N || 1));
  let start = 0;

  // var str = fs.readFileSync(file, {encoding: 'utf8'}).replace(/\n/g, '*');
  // console.log(str)
  while (start < size) {
    // console.log('Split n° %d = %s', split.length, str.substr(start, maxBlockSize + 1))
    split.push({index: split.length, chunk: [{path: file, opt: {start: start, end: start + maxBlockSize}}]});
    start += maxBlockSize + 1;
  }

  callback(split);
}
863496
private function splitIntoBlocks($css)
	{
		if (is_array($css)) {
			return $css;
		}

		$blocks = array();
		$css    = $this->stripComments($css);
		$offset = 0;

		// catch all @feature {...} blocks
		if (preg_match_all('/(@[^{]+){([^{}]*{[^}]*})*\s*}/ism', $css, $matches, PREG_OFFSET_CAPTURE) > 0) {
			foreach ($matches[0] as $key => $match) {
				$atRule              = trim($matches[1][$key][0]);
				list($rules, $start) = $match;

				if ($start > $offset) {
					// make previous selectors into their own block
					$block = trim(substr($css, $offset, $start - $offset));
					if (!empty($block)) {
						$blocks[] = $this->summarizeBlock($block);
					}
				}
				$offset = $start + strlen($rules);

				// currently only @media rules need to be parsed and counted for IE9 selectors
				if (strpos($atRule, '@media') === 0) {
					$block  = $this->summarizeBlock(substr($rules, strpos($rules, '{') + 1, -1));
				}
				else {
					$block  = array(
						'count'   => 1,
						'rules'   => array(
							array(
								'rule' => substr($rules, strpos($rules, '{') + 1, -1),
								'count' => 1,
							)
						),

					);
				}

				$block['at-rule'] = $atRule;
				$blocks[]               = $block;
			}

			// catch any remaining as it's own block
			$block = trim(substr($css, $offset));
			if (!empty($block)) {
				$blocks[] = $this->summarizeBlock($block);
			}
		}
		else {
			$blocks[] = $this->summarizeBlock($css);
		}

		return $blocks;
	}
650963
def _split_file(f, blocksize):
    

    f_bytes = f.read()
    blocks = [int.from_bytes(f_bytes[i:i+blocksize].ljust(blocksize, b'0'), sys.byteorder) 
            for i in range(0, len(f_bytes), blocksize)]
    return len(f_bytes), blocks
959229
function processCSSFiles(optionsIn = null, configFileLocationIn = '') {


		var continueCSSFilesProcess = function(optionsIn2){
			// console.log(optionsIn2)
				// console.log(optionsIn2.css)
			CPEVENTS.removeListener('CONFIG_READ_REDUCE_PROPS_END', continueCSSFilesProcess);

			var continueCSSFilesProcessAfterConfig = function(optionsIn3){

				
				CPEVENTS.removeListener('continueCSSFilesProcessAfterConfig', continueCSSFilesProcessAfterConfig);

				//config
				if (OPTIONS.css === undefined && CONFIG.options.css) {
					OPTIONS.css = CONFIG.options.css;
				}

				//Options
				if (optionsIn !== null && optionsIn !== undefined) {

					for (key in optionsIn) {

						OPTIONS[key] = optionsIn[key];	
						
					}
				}
				// console.log(CONFIG)
				// console.log(optionsIn.css)
				// console.log(optionsIn3)
				//CSS Files
				// var files = CONFIG.options.css;

				// if (optionsIn.css !== null && optionsIn.css !== undefined) {

				// files = optionsIn.css;
					
				// }

				files = OPTIONS.css;

				if (files !== undefined && files !== '') {
					tmpCSSPaths = [];

					//check for file or files
					switch (typeof files) {
						case 'object':
						case 'array':
								
							for (i = 0; i < files.length; ++i) {

								getFilePaths(files[i], ['.css']);
							}

							if (tmpCSSPaths.length) {
								files = tmpCSSPaths;
							}

							break;
						case 'string':
							//formats
							files = files.replace(/ /g, '');
							// comma delimited list - filename1.css, filename2.css
							if (files.indexOf(',') > -1) { 
								files = files.replace(/^\s+|\s+$/g,'').split(',');
								
								for (i = 0; i < files.length; ++i) {

									getFilePaths(files[i], ['.css']);

								}

								if (tmpCSSPaths.length) {
									files = tmpCSSPaths;
								}


							} else {

								//string path
								getFilePaths(files, ['.css']);

								if (tmpCSSPaths.length) {
									files = tmpCSSPaths;
								}

							}

							break;
					} //end of switch

					fileLocation = files.toString();

					CPEVENTS.on('CSS_READ_AGAIN', function(){

						readCSSFile(files);
					});
					CPEVENTS.on('CSS_READ_END', function(){
						// CPEVENTS.emit('CONFIG_READ_REDUCE_PROPS_END');
						processCSS(null,OPTIONS,function(){

						});	
						
					});

					readCSSFile(files);


				} else { //end of files nothing check

					//
				}




			};

			if (currentConfig != configFileLocationIn) { //don't read same config
				CPEVENTS.on('CONFIG_READ_END', continueCSSFilesProcessAfterConfig); //end of config read
			}

			currentConfig = configFileLocationIn;

			if (configFileLocationIn != 'cmd_default') {
				readConfig(configFileLocationIn);	
			} else if (configFileLocationIn == 'cmd_default') {
				readConfig(configFileLocationIn, optionsIn);	
			}
		};

		CPEVENTS.on('CONFIG_READ_REDUCE_PROPS_END', continueCSSFilesProcess); //end of reduce config read
		

		if (!hasReadReduceDeclarations && fs.existsSync(OPTIONS.reduce_declarations_file_location)) {
			
			readReduceDeclarations();
		}

		if (!hasReadReduceDeclarations && !fs.existsSync(OPTIONS.reduce_declarations_file_location)) {

			//default process settings
			var default_reduce_declarations_config = {
				"declaration_names" : [
					"font",
					"margin",
					"padding",
					"list-style",
					"outline",
					"border",
					"border-top",
					"border-right",
					"border-bottom",
					"border-left",
					"border-radius",
					"border-color",
					"border-top-color",
					"border-right-color",
					"border-bottom-color",
					"border-left-color",
					"color",
					"background-color",
					"font-color",
					"outline-color",
					"box-shadow",
					"text-shadow",
					"float",
					"font-family",
					"font-size",
					"font-weight",
					"font-style",
					"font-variant",
					"font-stretch"
				]
			};

			if (optionsIn !== null && (optionsIn['reduceConfig'] === undefined || optionsIn['reduceConfig'] === null)) {

				optionsIn['reduceConfig'] = default_reduce_declarations_config;
				readReduceDeclarations(optionsIn['reduceConfig']);
			} else {

				readReduceDeclarations();
			}
		}

	}
1216281
function compressCSS() {
    let tasks = [];

    Object.keys(config.tasks).forEach((key) => {
        let val = config.tasks[key];
        tasks.push(gulp.src(val.src)
            .pipe(cleanCSS({processImport: false}))
            .pipe(rename(config.rename))
            .pipe(gulp.dest(val.dest)));
    });

    return merge(tasks);
}
1225847
def from_css(Class, csstext, encoding=None, href=None, media=None, title=None, validate=None):
        
        styles = Class()
        cssStyleSheet = cssutils.parseString(csstext, encoding=encoding, href=href, media=media, title=title, validate=validate)
        for rule in cssStyleSheet.cssRules:
            if rule.type==cssutils.css.CSSRule.FONT_FACE_RULE:
                if styles.get('@font-face') is None: styles['@font-face'] = []
                styles['@font-face'].append(Class.styleProperties(rule.style))
            
            elif rule.type==cssutils.css.CSSRule.IMPORT_RULE:
                if styles.get('@import') is None: styles['@import'] = []
                styles['@import'].append("url(%s)" % rule.href)

            elif rule.type==cssutils.css.CSSRule.NAMESPACE_RULE:
                if styles.get('@namespace') is None: styles['@namespace'] = {}
                styles['@namespace'][rule.prefix] = rule.namespaceURI
            
            elif rule.type==cssutils.css.CSSRule.MEDIA_RULE:
                if styles.get('@media') is None: styles['@media'] = []
                styles['@media'].append(rule.cssText)
            
            elif rule.type==cssutils.css.CSSRule.PAGE_RULE:
                if styles.get('@page') is None: styles['@page'] = []
                styles['@page'].append(rule.cssText)

            elif rule.type==cssutils.css.CSSRule.STYLE_RULE:
                for selector in rule.selectorList:
                    sel = selector.selectorText
                    if sel not in styles:
                        styles[sel] = Class.styleProperties(rule.style)
            
            elif rule.type==cssutils.css.CSSRule.CHARSET_RULE:
                styles['@charset'] = rule.encoding

            elif rule.type==cssutils.css.CSSRule.COMMENT:   # comments are thrown away
                pass

            elif rule.type==cssutils.css.CSSRule.VARIABLES_RULE:
                pass
            
            else:
                log.warning("Unknown rule type: %r" % rule.cssText)

        return styles
19272
function lintSCSS(src) {
  return gulp.src(src)
    .pipe(sassLint())
    .pipe(sassLint.format())
    .pipe(sassLint.failOnError());
}
1184845
private function splitIntoRules($css)
	{
		$rules = preg_split('/}/', trim($this->stripComments($css)));

		// complete any rules by append } to them
		array_walk($rules,
			function (&$s) {
				!empty($s) && $s = trim("$s}");
			});

		// clears out any empty rules
		return array_filter($rules);
	}
1172368
def dumb_css_parser(data):
    """"""
    # remove @import sentences
    data += ';'
    importIndex = data.find('@import')
    while importIndex != -1:
        data = data[0:importIndex] + data[data.find(';', importIndex) + 1:]
        importIndex = data.find('@import')

    # parse the css. reverted from dictionary compehension in order to support older pythons
    elements =  [x.split('{') for x in data.split('}') if '{' in x.strip()]
    try:
        elements = dict([(a.strip(), dumb_property_dict(b)) for a, b in elements])
    except ValueError:
        elements = {} # not that important

    return elements
3352
function cssToSss (css, file) {
    if (path.extname(file) === '.css') {
      return postcss().process(css, { stringifier: sugarss }).then(function (result) {
        return result.css
      })
    } else {
      return css
    }
  }
1253815
function flattenCss(fileName, fileContents, cssImportIgnore) {
        //Find the last slash in the name.
        fileName = fileName.replace(lang.backSlashRegExp, "/");
        var endIndex = fileName.lastIndexOf("/"),
            //Make a file path based on the last slash.
            //If no slash, so must be just a file name. Use empty string then.
            filePath = (endIndex !== -1) ? fileName.substring(0, endIndex + 1) : "";

        //Make sure we have a delimited ignore list to make matching faster
        if (cssImportIgnore && cssImportIgnore.charAt(cssImportIgnore.length - 1) !== ",") {
            cssImportIgnore += ",";
        }

        return fileContents.replace(cssImportRegExp, function (fullMatch, urlStart, importFileName, urlEnd, mediaTypes) {
            //Only process media type "all" or empty media type rules.
            if (mediaTypes && ((mediaTypes.replace(/^\s\s*/, '').replace(/\s\s*$/, '')) !== "all")) {
                return fullMatch;
            }

            importFileName = cleanCssUrlQuotes(importFileName);

            //Ignore the file import if it is part of an ignore list.
            if (cssImportIgnore && cssImportIgnore.indexOf(importFileName + ",") !== -1) {
                return fullMatch;
            }

            //Make sure we have a unix path for the rest of the operation.
            importFileName = importFileName.replace(lang.backSlashRegExp, "/");

            try {
                //if a relative path, then tack on the filePath.
                //If it is not a relative path, then the readFile below will fail,
                //and we will just skip that import.
                var fullImportFileName = importFileName.charAt(0) === "/" ? importFileName : filePath + importFileName,
                    importContents = file.readFile(fullImportFileName), i,
                    importEndIndex, importPath, fixedUrlMatch, colonIndex, parts;

                //Make sure to flatten any nested imports.
                importContents = flattenCss(fullImportFileName, importContents);

                //Make the full import path
                importEndIndex = importFileName.lastIndexOf("/");

                //Make a file path based on the last slash.
                //If no slash, so must be just a file name. Use empty string then.
                importPath = (importEndIndex !== -1) ? importFileName.substring(0, importEndIndex + 1) : "";

                //Modify URL paths to match the path represented by this file.
                importContents = importContents.replace(cssUrlRegExp, function (fullMatch, urlMatch) {
                    fixedUrlMatch = cleanCssUrlQuotes(urlMatch);
                    fixedUrlMatch = fixedUrlMatch.replace(lang.backSlashRegExp, "/");

                    //Only do the work for relative URLs. Skip things that start with / or have
                    //a protocol.
                    colonIndex = fixedUrlMatch.indexOf(":");
                    if (fixedUrlMatch.charAt(0) !== "/" && (colonIndex === -1 || colonIndex > fixedUrlMatch.indexOf("/"))) {
                        //It is a relative URL, tack on the path prefix
                        urlMatch = importPath + fixedUrlMatch;
                    } else {
                        logger.trace(importFileName + "\n  URL not a relative URL, skipping: " + urlMatch);
                    }

                    //Collapse .. and .
                    parts = urlMatch.split("/");
                    for (i = parts.length - 1; i > 0; i--) {
                        if (parts[i] === ".") {
                            parts.splice(i, 1);
                        } else if (parts[i] === "..") {
                            if (i !== 0 && parts[i - 1] !== "..") {
                                parts.splice(i - 1, 2);
                                i -= 1;
                            }
                        }
                    }

                    return "url(" + parts.join("/") + ")";
                });

                return importContents;
            } catch (e) {
                logger.trace(fileName + "\n  Cannot inline css import, skipping: " + importFileName);
                return fullMatch;
            }
        });
    }
956800
function readCSSFile(files = []) {

		if (OPTIONS.verbose) { console.log(info('Input - CSS File : ' + files[readCSSFileCount])); }

		if (validUrl.isUri(files[readCSSFileCount])) {
			request({
				url: files[readCSSFileCount],
				method: "GET"
			}, function(err, headRes, body) {
				if (headRes !== undefined) {
					var size = headRes.headers['content-length'];
					
					if (size == undefined || size == 0) {
						filesizeKB = kiloByteLength(body);
					} else {
						filesizeKB = size/1000;	
					}
				} else {
					var size = kiloByteLength(body);
					filesizeKB = size/1000;
				}

				
				stats.files.css.push({
					"filename" : files[readCSSFileCount],
					"filesizeKB" : filesizeKB
				});
				stats.before.totalFileSizeKB += filesizeKB;

			});
		} else {
			filesizeKB = getFilesizeInKiloBytes(files[readCSSFileCount]);

			stats.files.css.push({
				"filename" : files[readCSSFileCount],
				"filesizeKB" : filesizeKB
			});
			stats.before.totalFileSizeKB += filesizeKB;
		}


		summary.files.input.push(files[readCSSFileCount]);


		if (validUrl.isUri(files[readCSSFileCount])) {
			
		  request(files[readCSSFileCount], function (err, response, body) {

		  	if (response === undefined) {

		  		//try again
		  		request(files[readCSSFileCount], function (err, response, body) {

		  			if (response.statusCode == 200) {
				    	dataCSSIn.push(body);

				    	readCSSFileCount += 1;

							if (readCSSFileCount < files.length) {

								CPEVENTS.emit('CSS_READ_AGAIN');	
							} else {

								CPEVENTS.emit('CSS_READ_END');
							}

				    } else {
							CPEVENTS.emit('CSS_READ_ERROR');
							console.log(error("CSS File read error: check your CSS files and please try again."));
							console.log(err)
							process.exit(1);
				    }

		  		});


		  	} else if (response.statusCode == 200) {
		    	dataCSSIn.push(body);

		    	readCSSFileCount += 1;

					if (readCSSFileCount < files.length) {

						CPEVENTS.emit('CSS_READ_AGAIN');	
					} else {

						CPEVENTS.emit('CSS_READ_END');
					}

		    } else {
					CPEVENTS.emit('CSS_READ_ERROR');
					console.log(error("CSS File read error: check your CSS files and please try again."));
					console.log(err)
					process.exit(1);
		    }
			});

		} else {


			readStream = fs.createReadStream(files[readCSSFileCount], 'utf8');

			readStream.on('data', function(chunk) { 
				dataCSSIn.push(chunk);

			}).on('end', function() {
				readCSSFileCount += 1;
				if (readCSSFileCount < files.length) {

					CPEVENTS.emit('CSS_READ_AGAIN');	
				} else {
					CPEVENTS.emit('CSS_READ_END');
				}
				
			}).on('error', function(e) {
				CPEVENTS.emit('CSS_READ_ERROR');
				console.log(error("CSS File read error: Something went wrong while reading the file(s), check your CSS files and please try again."));
				console.log(e);
				process.exit(1);
			});

		} //end of url check
	}
393498
private static String stripFileExtensionIfAny(final String name) {
        final int suffix = name.lastIndexOf(".html");
        return suffix == -1 ? name : name.substring(0, suffix);
    }
1366872
function processCSS(state, minify, file) {
        /* jshint quotmark: false */
        var css = fs.readFileSync(file).toString(),
            js;
        state.css.push(css);
        
        if (minify) {
            css = css
        .replace(/\r?\n/g, '')
        .replace(/\/\*.*?\*\//g, '')
        .replace(/:\s+/g, ':')
        .replace(/\s*\{\s*/g, '{')
        .replace(/\s*\}\s*/g, '}')
        .replace(/\s*\,\s*/g, ',')
        .replace(/\s*\;\s*/g, ';');
        }
        //escape for js
        css = css
      .replace(/\\/g, '\\\\')
      .replace(/'/g, "\\'")
      .replace(/\r?\n/g, '\\n');
        js = "!angular.$$csp() && angular.element(document).find('head').prepend('<style type=\"text/css\">" + css + "</style>');";
        state.js.push(js);
        
        return state;
    }
963910
function(css) {
  css = css
    // remove comments
    .replace(/\/\*[^\0]*?\*\//g, '')
    // trim space before characters
    .replace(/\s+({|})/g, '$1')
    // trim space after characters
    .replace(/(;|,|:|{|}|^)\s+/g, '$1')
    // trim combinators
    .replace(/\s+(>|\+|~)\s+/g, '$1')
    // remove escaped newlines and spaces
    .replace(/\\\r?\n\s+/g, '')
    // remove trailing semicolons in rules
    .replace(/;(})/g, '$1');

  return css;
}