TODO-Shunli: now upload video always failed, tip system error, check later
429481
public static MediaJsonRtn uploadMedia(License license, MediaFile mediaFile) {
        if (mediaFile == null) {
            return JsonRtnUtil.buildFailureJsonRtn(MediaJsonRtn.class, "missing mediaFile");
        }
        // maybe todo more mediaFile legality check

        String accessToken = AccessTokenUtil.getAccessToken(license);
        String url = WechatRequest.UPLOAD_MEDIA.getUrl();
        try {
            MediaType mediaType = mediaFile.getMediaType();
            URI uri = new URIBuilder(url)
                    .setParameter("access_token", accessToken)
                    .setParameter("type", mediaType.getName())
                    .build();

            HttpEntity httpEntity = MultipartEntityBuilder.create()
                    .addBinaryBody("body", mediaFile.getFile())
                    .build();

            String rtnJson = Request.Post(uri)
                    .connectTimeout(HttpUtil.CONNECT_TIMEOUT)
                    .socketTimeout(HttpUtil.SOCKET_TIMEOUT)
                    .body(httpEntity)
                    .execute().handleResponse(HttpUtil.UTF8_CONTENT_HANDLER);

            MediaJsonRtn jsonRtn = JsonRtnUtil.parseJsonRtn(rtnJson, MediaJsonRtn.class);
            log.info("upload media:\n url={},\n body={},\n rtn={},{}", uri, mediaFile, rtnJson, jsonRtn);
            return jsonRtn;
        } catch (Exception e) {
            String msg = "upload media failed:\n " +
                    "url=" + url + "?access_token=" + accessToken + ",\n body=" + mediaFile;
            log.error(msg, e);
            return JsonRtnUtil.buildFailureJsonRtn(MediaJsonRtn.class, "uploadMedia failed");
        }
    }
317647
def on_btn_upload(self, event):
        
        if not self.check_for_uncombined_files():
            return
        outstring="upload_magic.py"
        print("-I- running python script:\n %s"%(outstring))
        wait = wx.BusyInfo("Please wait, working...")
        wx.SafeYield()
        self.contribution.tables['measurements'].add_measurement_names()
        if self.data_model_num == 3:
            res, error_message, has_problems, all_failing_items = ipmag.upload_magic(concat=False, dir_path=self.WD,
                                                                                     vocab=self.contribution.vocab,
                                                                                     contribution=self.contribution)
        if self.data_model_num == 2:
            res, error_message, errors = ipmag.upload_magic2(dir_path=self.WD, data_model=self.er_magic.data_model)
            del wait

        if res:
            text = "You are ready to upload!\n{} was generated in {}".format(os.path.split(res)[1], os.path.split(res)[0])
            dlg = pw.ChooseOne(self, "Go to MagIC for uploading", "Not ready yet", text, "Saved")
            del wait
            #dlg = wx.MessageDialog(self, caption="Saved", message=text, style=wx.OK)
        else:
            text = "There were some problems with the creation of your upload file.\nError message: {}\nSee Terminal/message window for details".format(error_message)
            dlg = wx.MessageDialog(self, caption="Error", message=text, style=wx.OK)

        dlg.Centre()
        result = dlg.ShowModal()
        if result == wx.ID_OK:
            dlg.Destroy()
        if result == wx.ID_YES:
            pw.on_database_upload(None)

        if self.data_model_num == 3:
            if not res:
                from programs import magic_gui
                self.Disable()
                self.Hide()
                self.magic_gui_frame = magic_gui.MainFrame(self.WD,
                                                           dmodel=self.data_model,
                                                           title="Validations",
                                                           contribution=self.contribution)

                self.magic_gui_frame.validation_mode = ['specimens']
                self.magic_gui_frame.failing_items = all_failing_items
                self.magic_gui_frame.change_dir_button.Disable()
                self.magic_gui_frame.Centre()
                self.magic_gui_frame.Show()
                self.magic_gui_frame.highlight_problems(has_problems)
                #
                # change name of upload button to 'exit validation mode'
                self.magic_gui_frame.bSizer2.GetStaticBox().SetLabel('return to main GUI')
                self.magic_gui_frame.btn_upload.SetLabel("exit validation mode")
                # bind that button to quitting magic gui and re-enabling Pmag GUI
                self.magic_gui_frame.Bind(wx.EVT_BUTTON, self.on_end_validation, self.magic_gui_frame.btn_upload)
                # do binding so that closing/quitting re-opens the main frame
                self.magic_gui_frame.Bind(wx.EVT_CLOSE, self.on_end_validation)
                # this makes it work with only the validation window open
                self.magic_gui_frame.Bind(wx.EVT_MENU,
                                          lambda event: self.menubar.on_quit(event, self.magic_gui_frame),
                                          self.magic_gui_frame.menubar.file_quit)
                # this makes it work if an additional grid is open
                self.Bind(wx.EVT_MENU,
                          lambda event: self.menubar.on_quit(event, self.magic_gui_frame),
                          self.magic_gui_frame.menubar.file_quit)
591609
public void addTangoArchiveListener(ITangoArchiveListener listener, boolean stateless)
            throws DevFailed {
        event_listeners.add(ITangoArchiveListener.class, listener);
        event_identifier = subscribe_archive_event(attr_name, filters, stateless);
    }
526281
def send_video(path, refer, &callback)
      fail_back(&callback) if not File.exist?(path)
      @client.send_video(targetize, path, &callback)
    end
395773
def get_upload_status(self):
        
        if self.id:
            return self.connection.post('get_upload_status', video_id=self.id)
934851
def update_video(self):
        
        window_start = self.parent.value('window_start')
        window_length = self.parent.value('window_length')
        d = self.parent.info.dataset

        videos, begsec, endsec = d.read_videos(window_start,
                                               window_start + window_length)
        
        lg.debug(f'Video: {begsec} - {endsec}')
        self.endsec = endsec
        videos = [str(v) for v in videos]  # make sure it's a str (not path)
        medialist = vlc.MediaList(videos)
        self.medialistplayer.set_media_list(medialist)

        self.cnt_video = 0
        self.n_video = len(videos)

        self.t = QTimer()
        self.t.timeout.connect(self.check_if_finished)
        self.t.start(100)

        self.medialistplayer.play()
        self.mediaplayer.set_time(int(begsec * 1000))
100630
public void upload() {
    try {
      writer.flush();
      if (compress)
        zipCompress(filename);
      String remoteName = "failmon-";
      if ("true".equalsIgnoreCase(Environment.getProperty("anonymizer.hash.hostnames")))
        remoteName += Anonymizer.getMD5Hash(InetAddress.getLocalHost().getCanonicalHostName()) + "-";
      else
        remoteName += InetAddress.getLocalHost().getCanonicalHostName() + "-"; 
      remoteName += Calendar.getInstance().getTimeInMillis();//.toString();
      if (compress)
	copyToHDFS(filename + COMPRESSION_SUFFIX, hdfsDir + "/" + remoteName + COMPRESSION_SUFFIX);
      else
	copyToHDFS(filename, hdfsDir + "/" + remoteName);
    } catch (IOException e) {
      e.printStackTrace();
    }

    // delete and re-open
    try {
      fw.close();
      fw = new FileWriter(filename);
      writer = new BufferedWriter(fw);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
414642
def upload_permanent_media(self, media_type, media_file):
        
        return self.post(
            url="https://api.weixin.qq.com/cgi-bin/material/add_material",
            params={
                "access_token": self.token,
                "type": media_type
            },
            files={"media": media_file}
        )
1279108
def _upload(param_dict, timeout, data):
    
    param_dict['format'] = 'json'
    param_dict['wait'] = 'true'
    param_dict['bucket'] = 'audio_summary'
    result = util.callm('track/upload', param_dict, POST = True, socket_timeout = 300,  data = data)
    return _track_from_response(result, timeout)
798892
def do_upload(post_data, callback=None):
    

    encoder = MultipartEncoder(post_data)
    monitor = MultipartEncoderMonitor(encoder, callback)

    headers = {'User-Agent': USER_AGENT, 'Content-Type': monitor.content_type}
    response = post(API_URL, data=monitor, headers=headers)
    check_response(response)

    return response.json()[0]
838003
def check_for_allowed_file(f):
    
    for ext in SUPPORTED_EXTENSIONS:
        if f.endswith(ext):
            return True
    log.error("Failed upload: Not an allowed file extension: %s", f)
    raise SystemExit
715984
def save(self, create_multiple_renditions=True,
        preserve_source_rendition=True,
        encode_to=enums.EncodeToEnum.FLV):
        
        if is_ftp_connection(self.connection) and len(self.assets) > 0:
            self.connection.post(xml=self.to_xml(), assets=self.assets)
        elif not self.id and self._filename:
            self.id = self.connection.post('create_video', self._filename,
                create_multiple_renditions=create_multiple_renditions,
                preserve_source_rendition=preserve_source_rendition,
                encode_to=encode_to,
                video=self._to_dict())
        elif not self.id and len(self.renditions) > 0:
            self.id = self.connection.post('create_video',
                video=self._to_dict())
        elif self.id:
            data = self.connection.post('update_video', video=self._to_dict())
            if data:
                self._load(data)
592817
protected static function fail() {
		if (\Skeleton\Core\Hook::exists('media_not_found')) {
			\Skeleton\Core\Hook::call('media_not_found');
		} else {
			HTTP\Status::code_404('media');
		}
	}
509882
async function runSample(fileName) {
  const fileSize = fs.statSync(fileName).size;
  const res = await youtube.videos.insert(
    {
      part: 'id,snippet,status',
      notifySubscribers: false,
      requestBody: {
        snippet: {
          title: 'Node.js YouTube Upload Test',
          description: 'Testing YouTube upload via Google APIs Node.js Client',
        },
        status: {
          privacyStatus: 'private',
        },
      },
      media: {
        body: fs.createReadStream(fileName),
      },
    },
    {
      // Use the `onUploadProgress` event from Axios to track the
      // number of bytes uploaded to this point.
      onUploadProgress: evt => {
        const progress = (evt.bytesRead / fileSize) * 100;
        readline.clearLine(process.stdout, 0);
        readline.cursorTo(process.stdout, 0, null);
        process.stdout.write(`${Math.round(progress)}% complete`);
      },
    }
  );
  console.log('\n\n');
  console.log(res.data);
  return res.data;
}
161004
public static Media mediaUploadvideo(String access_token,Uploadvideo uploadvideo){
		String messageJson = JsonUtil.toJSONString(uploadvideo);
		HttpUriRequest httpUriRequest = RequestBuilder.post()
										.setHeader(jsonHeader)
										//2.8.20 修改URI  原URI MEDIA_URI+"/cgi-bin/media/uploadvideo"
										.setUri(BASE_URI+"/cgi-bin/media/uploadvideo")
										.addParameter(PARAM_ACCESS_TOKEN, API.accessToken(access_token))
										.setEntity(new StringEntity(messageJson,Charset.forName("utf-8")))
										.build();
		return LocalHttpClient.executeJsonResult(httpUriRequest,Media.class);
	}
8732
function parseStatsOldAPI (peerConnection,
                                                      prevStats,
                                                      currentStats,
                                                      completion) {

      /* this parses a result if there it contains the video bitrate */
      var parseVideoStats = function (result) {
            if (result.stat('googFrameRateSent')) {
              currentStats.videoSentBytes = Number(result.stat('bytesSent'));
              currentStats.videoSentPackets = Number(result.stat('packetsSent'));
              currentStats.videoSentPacketsLost = Number(result.stat('packetsLost'));
              currentStats.videoRtt = Number(result.stat('googRtt'));
              currentStats.videoFrameRate = Number(result.stat('googFrameRateInput'));
              currentStats.videoWidth = Number(result.stat('googFrameWidthSent'));
              currentStats.videoHeight = Number(result.stat('googFrameHeightSent'));
              currentStats.videoCodec = result.stat('googCodecName');
            } else if (result.stat('googFrameRateReceived')) {
              currentStats.videoRecvBytes = Number(result.stat('bytesReceived'));
              currentStats.videoRecvPackets = Number(result.stat('packetsReceived'));
              currentStats.videoRecvPacketsLost = Number(result.stat('packetsLost'));
              currentStats.videoFrameRate = Number(result.stat('googFrameRateOutput'));
              currentStats.videoWidth = Number(result.stat('googFrameWidthReceived'));
              currentStats.videoHeight = Number(result.stat('googFrameHeightReceived'));
              currentStats.videoCodec = result.stat('googCodecName');
            }
            return null;
          },

          parseAudioStats = function (result) {
            if (result.stat('audioInputLevel')) {
              currentStats.audioSentPackets = Number(result.stat('packetsSent'));
              currentStats.audioSentPacketsLost = Number(result.stat('packetsLost'));
              currentStats.audioSentBytes =  Number(result.stat('bytesSent'));
              currentStats.audioCodec = result.stat('googCodecName');
              currentStats.audioRtt = Number(result.stat('googRtt'));
            } else if (result.stat('audioOutputLevel')) {
              currentStats.audioRecvPackets = Number(result.stat('packetsReceived'));
              currentStats.audioRecvPacketsLost = Number(result.stat('packetsLost'));
              currentStats.audioRecvBytes =  Number(result.stat('bytesReceived'));
              currentStats.audioCodec = result.stat('googCodecName');
            }
          },

          parseStatsReports = function (stats) {
            if (stats.result) {
              var resultList = stats.result();
              for (var resultIndex = 0; resultIndex < resultList.length; resultIndex++) {
                var result = resultList[resultIndex];

                if (result.stat) {

                  if(result.stat('googActiveConnection') === 'true') {
                    currentStats.localCandidateType = result.stat('googLocalCandidateType');
                    currentStats.remoteCandidateType = result.stat('googRemoteCandidateType');
                    currentStats.transportType = result.stat('googTransportType');
                  }

                  parseAudioStats(result);
                  parseVideoStats(result);
                }
              }
            }

            completion(null, currentStats);
          };

      peerConnection.getStats(parseStatsReports);
    }
471168
function (e, data) {
                ctrl.coreWistia.setError(); //clear any previous errors

                data
                  .submit()
                  .then(function (result, textStatus, jqXHR) {
                    ctrl.coreWistia.playVideo(result.hashed_id);
                  })
                  .catch(function (jqXHR, textStatus, errorThrown) {
                    $timeout(function() {
                      ctrl.coreWistia.setError('WistiaError: ' + jqXHR.responseJSON ? jqXHR.responseJSON.error : errorThrown);
                    });
                  })
                ;
              }