Implements the 'youtube' snippet
555005
public function youtube($link, $width=480, $height=360) {
		$url = parse_url($link);
		if (!array_key_exists('query', $url)) {
			return "";
		}
		parse_str($url['query'], $query);
		$is_playlist = array_key_exists('list', $query);
		if ($is_playlist) {
			$playlist_id = $query['list'];
			$embed_url = "//www.youtube.com/embed?listType=playlist&list=$playlist_id";
		} else {
			$video_id = $query['v'];
			$embed_url = "//www.youtube.com/embed/$video_id";
		}

		return "<iframe width=\"$width\" height=\"$height\" src=\"$embed_url\" frameborder=\"0\" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>";
	}
683029
function _buildVideo(videoDescriptor) {
		this.url = videoDescriptor.url;
		this.appData = videoDescriptor.appData;
		descriptor = videoDescriptor;
	}
488626
function (param, options, callback) {
              // dailymotion make call toservice every time einsted of vidmeo and youtube
              embedProcessor.log(param.worker + ' started with parameters = ', param);
              var sourceUrl = encodeURIComponent(param.url);
              var api_url = '//api.embed.ly/1/oembed?key=c6544dc839bd11e088ae4040f9f86dcd&url=' + sourceUrl + (that.autoplay ? "":"&autoplay=1") + '&callback=?';
              $.getJSON(api_url, function (data) {
                if(data && data.html) {
                  param.status = true;
                  param.duration = false;
                  param.duration_formatted = false;
                  param.thumbnail_url = data.thumbnail_url ? data.thumbnail_url : '';
                  param.favicon_url = data.favicon_url;
                  if (param.source === 'dailymotion') {
                    param.favicon_url = '//favicon.yandex.net/favicon/dailymotion.com';
                  }
                  param.service_name = data.provider_name;
                  param.provider_url = data.provider_url;
                  param.html = data.html;
                  param.title = data.title || '';
                  param.views = false;
                  if (embedProcessor._sources[param.source] && embedProcessor._sources[param.source].prepareEmbedCode) {
                    param = embedProcessor._sources[param.source].prepareEmbedCode(param);
                  }
                  param.author = data.author_name || "";
                  param = embedProcessor._paramEmbedCodeNormalizer(param);
                } else {
                  /* prepare data from appData */
                  if(param.appData && param.appData.id && param.source === "dailymotion") {
                    param.status = true;
                    param.duration = false;
                    param.duration_formatted = false;
                    param.thumbnail_url = param.appData.thumbnail_small_url;
                    param.favicon_url = '//favicon.yandex.net/favicon/dailymotion.com';
                    param.service_name = "Dailymotion";
                    param.provider_url = "http://www.dailymotion.com";
                    param.html = '<iframe src="http://www.dailymotion.com/embed/video/' + param.appData.id + (that.autoplay ? "" : "?autoPlay=1") + '" width="480" height="301" frameborder="0"></iframe>';
                    param.title = param.appData.title || '';
                    param.views = false;
                    if (embedProcessor._sources[param.source] && embedProcessor._sources[param.source].prepareEmbedCode) {
                      param = embedProcessor._sources[param.source].prepareEmbedCode(param);
                    }
                    param.author = data.author_name || "";
                    param = embedProcessor._paramEmbedCodeNormalizer(param);
                  } else {
                    param.status = false;
                  }
                }
                embedProcessor.log(param.worker + ' receive parameters = ', param);
                callback(param);
              });
            }
869228
def ok_embedded_video(node):
    """"""
    good_keywords = ('youtube', 'blip.tv', 'vimeo')

    node_str = tounicode(node)
    for key in good_keywords:
        if key in node_str:
            return True

    return False
1781
private void initializeYoutubeFragment() {
    youtubeFragment = new YouTubePlayerSupportFragment();
    youtubeFragment.initialize(YOUTUBE_API_KEY, new YouTubePlayer.OnInitializedListener() {

      @Override public void onInitializationSuccess(YouTubePlayer.Provider provider,
          YouTubePlayer player, boolean wasRestored) {
        if (!wasRestored) {
          youtubePlayer = player;
          youtubePlayer.loadVideo(VIDEO_KEY);
          youtubePlayer.setShowFullscreenButton(true);
        }
      }

      @Override public void onInitializationFailure(YouTubePlayer.Provider provider,
          YouTubeInitializationResult error) {
      }
    });
  }
444003
function(wysiwygeditor)
        {
            // Add video to editor
            var insert_video_wysiwyg = function( url, html )
            {
                url = $.trim(url||'');
                html = $.trim(html||'');
                var website_url = false;
                if( url.length && ! html.length )
                    website_url = url;
                else if( html.indexOf('<') == -1 && html.indexOf('>') == -1 &&
                         html.match(/^(?:https?:\/)?\/?(?:[^:\/\s]+)(?:(?:\/\w+)*\/)(?:[\w\-\.]+[^#?\s]+)(?:.*)?(?:#[\w\-]+)?$/) )
                    website_url = html;
                if( website_url && video_from_url )
                    html = video_from_url( website_url ) || '';
                if( ! html.length && website_url )
                    html = '<video src="' + html_encode(website_url) + '">';
                wysiwygeditor.insertHTML( html ).closePopup().collapseSelection();
            };
            // Create popup
            var $content = $('<div/>').addClass('wysiwyg-toolbar-form')
                                      .prop('unselectable','on');
            // Add video via '<embed/>'
            var $textareaembed = $('<textarea>').addClass('wysiwyg-input wysiwyg-inputtextarea');
            if( placeholder_embed )
                $textareaembed.prop( 'placeholder', placeholder_embed );
            $('<div/>').addClass( 'wysiwyg-embedcode' )
                       .append( $textareaembed )
                       .appendTo( $content );
            // Add video via 'URL'
            var $inputurl = $('<input type="text" value="">').addClass('wysiwyg-input')
                                .keypress(function(event){
                                    if( event.which == 10 || event.which == 13 )
                                        insert_video_wysiwyg( $inputurl.val() );
                                });
            if( placeholder_url )
                $inputurl.prop( 'placeholder', placeholder_url );
            var $okaybutton = $();
            if( toolbar_submit )
                $okaybutton = toolbar_button(toolbar_submit).click(function(event){
                                    insert_video_wysiwyg( $inputurl.val(), $textareaembed.val() );
                                    event.stopPropagation();
                                    event.preventDefault();
                                    return false;
                                });
            $content.append( $('<div/>').append($inputurl).append($okaybutton) );
            return $content;
        }
253902
def snippet=(v)
      case v
      when String
        @snippet = Snippet.new(v)
      when Snippet
        @snippet = v
      else
        raise ArgumentError, "Snippet must be a String or a Snippet"
      end
    end
405032
def youtube_meta(client, channel, nick, message, match):
    
    if not API_KEY:
        return 'You must set YOUTUBE_DATA_API_KEY in settings!'
    identifier = match[0]
    params = {
        'id': identifier,
        'key': API_KEY,
        'part': 'snippet,statistics,contentDetails',
    }
    response = requests.get(API_ROOT, params=params)

    if response.status_code != 200:
        return 'Error in response, ' + str(response.status_code) + ' for identifier: ' + identifier
    try:
        data = response.json()['items'][0]
    except:
        print('Exception requesting info for identifier: ' + identifier)
        traceback.print_exc()

    response_dict = {
        'title': data['snippet']['title'],
        'poster': data['snippet']['channelTitle'],
        'date': str(parse_date(data['snippet']['publishedAt'])),
        'views': data['statistics']['viewCount'],
        'likes': data['statistics']['likeCount'],
        'dislikes': data['statistics']['dislikeCount'],
        'duration': parse_duration(data['contentDetails']['duration']),
    }

    return RESPONSE_TEMPLATE.format(**response_dict).encode('utf-8').strip()
21192
def by_youtube_id(cls, youtube_id):
        
        qset = cls.objects.filter(
            encoded_videos__profile__profile_name='youtube',
            encoded_videos__url=youtube_id
        ).prefetch_related('encoded_videos', 'courses')
        return qset
200936
def embed_snippet(views,
                  drop_defaults=True,
                  state=None,
                  indent=2,
                  embed_url=None,
                  requirejs=True,
                  cors=True
                 ):
    

    data = embed_data(views, drop_defaults=drop_defaults, state=state)

    widget_views = u'\n'.join(
        widget_view_template.format(view_spec=escape_script(json.dumps(view_spec)))
        for view_spec in data['view_specs']
    )

    if embed_url is None:
        embed_url = DEFAULT_EMBED_REQUIREJS_URL if requirejs else DEFAULT_EMBED_SCRIPT_URL

    load = load_requirejs_template if requirejs else load_template

    use_cors = ' crossorigin="anonymous"' if cors else ''
    values = {
        'load': load.format(embed_url=embed_url, use_cors=use_cors),
        'json_data': escape_script(json.dumps(data['manager_state'], indent=indent)),
        'widget_views': widget_views,
    }

    return snippet_template.format(**values)
663059
def get_snippet(method_name, args_names, do_block, brace_block, scope)
      ERB.new(SublimeSunippetter::Templates::SUNIPPET_TEMPLATE).result(binding)
    end
260070
function clean(e, tag) {
  var targetList = e.getElementsByTagName(tag);
  var isEmbed = (tag == 'object' || tag == 'embed');



  for (var y = targetList.length - 1; y >= 0; y--) {
    //------- user clean handler -----------------
    var validRule = false;
    for (var i = 0; i < cleanRules.length; i++) {
      if (cleanRules[i](targetList[y], tag) === true) {
        validRule = true;
        break;
      }
    }

    if (validRule) {
      continue;
    }
    //------- end user clean handler -----------------

    /* Allow youtube and vimeo videos through as people usually want to see those. */
    if (isEmbed) {
      if (targetList[y].innerHTML.search(regexps.videoRe) !== -1) {
        continue;
      }
    }

    targetList[y].parentNode.removeChild(targetList[y]);
  }
}
87995
public static function oembed($html, $url, $attr, $postId, $wrapper = true)
    {
        $provider = false;

        if (strpos(strtolower($url), 'youtube') !== false || strpos(strtolower($url), 'youtu.be') !== false) {
            $provider = 'YouTube';
        } elseif (strpos(strtolower($url), 'vimeo') !== false) {
            $provider = 'Vimeo';
        }

        $shouldFilter = apply_filters('Municipio/oembed/should_filter_markup', true, $provider, $url, $postId);

        // Check if there's a oembed class for the provider
        if (!class_exists('\Municipio\Oembed\\' . $provider) || !$shouldFilter) {
            return $html;
        }

        $class = '\Municipio\Oembed\\' . $provider;
        $oembed = new $class($url, $html, $wrapper);

        return $oembed->output();
    }
1215482
def snippets(session):
    """"""

    # Sanity check: Only run snippets tests if the environment variable is set.
    if not os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", ""):
        session.skip("Credentials must be set via environment variable.")

    # Install all test dependencies, then install local packages in place.
    session.install("mock", "pytest")
    for local_dep in LOCAL_DEPS:
        session.install("-e", local_dep)
    session.install("-e", os.path.join("..", "storage"))
    session.install("-e", os.path.join("..", "test_utils"))
    session.install("-e", ".[all]")

    # Run py.test against the snippets tests.
    session.run("py.test", os.path.join("docs", "snippets.py"), *session.posargs)
    session.run("py.test", "samples", *session.posargs)
1364748
function betterTrim(snippetEl) {
		// Helper functions
		function trimLeft(val) {
			// Adapted from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim#Polyfill
			return val.replace(/^[\s\uFEFF\xA0]+/g, '');
		}
		function trimLineBreaks(input) {
			var lines = input.split('\n');

			// Trim line-breaks from the beginning
			for (var i = 0; i < lines.length; i++) {
				if (lines[i].trim() === '') {
					lines.splice(i--, 1);
				} else break;
			}

			// Trim line-breaks from the end
			for (var i = lines.length-1; i >= 0; i--) {
				if (lines[i].trim() === '') {
					lines.splice(i, 1);
				} else break;
			}

			return lines.join('\n');
		}

		// Main function for betterTrim()
		return (function(snippetEl) {
			var content = trimLineBreaks(snippetEl.innerHTML);
			var lines = content.split('\n');
			// Calculate the minimum amount to remove on each line start of the snippet (can be 0)
			var pad = lines.reduce(function(acc, line) {
				if (line.length > 0 && trimLeft(line).length > 0 && acc > line.length - trimLeft(line).length) {
					return line.length - trimLeft(line).length;
				}
				return acc;
			}, Number.POSITIVE_INFINITY);
			// Slice each line with this amount
			return lines.map(function(line, index) {
				return line.slice(pad);
			})
			.join('\n');
		})(snippetEl);
	}
179966
def edit(snippet)
      if editor && !editor.empty?
        snippet_file = file_for(snippet)
        Process.exec "#{editor} '#{snippet_file}'"
      end
    end
958806
def snippetWithLink(self, url):
        
        link = self.soup.find("a", attrs={'href': url})
        if link:
            for p in link.parents:
                if p.name in ('p', 'div'):
                    return ' '.join(p.text.split()[0:30])
        return None