Create a empty report. All campaign run will be "Not Executed"
339963
private void createReport() {
        CampaignReportManager.getInstance().startReport(campaignStartTimeStamp, currentCampaign.getName());
        for (CampaignRun run : currentCampaign.getRuns()) {
            CampaignResult result = new CampaignResult(run.getTestbed());
            result.setStatus(Status.NOT_EXECUTED);
            CampaignReportManager.getInstance().putEntry(result);
        }

        CampaignReportManager.getInstance().refresh();
    }
1167863
def export_trials_data(args):
    
    nni_config = Config(get_config_filename(args))
    rest_port = nni_config.get_config('restServerPort')
    rest_pid = nni_config.get_config('restServerPid')
    if not detect_process(rest_pid):
        print_error('Experiment is not running...')
        return
    running, response = check_rest_server_quick(rest_port)
    if running:
        response = rest_get(trial_jobs_url(rest_port), 20)
        if response is not None and check_response(response):
            content = json.loads(response.text)
            # dframe = pd.DataFrame.from_records([parse_trial_data(t_data) for t_data in content])
            # dframe.to_csv(args.csv_path, sep='\t')
            records = parse_trial_data(content)
            if args.type == 'json':
                json_records = []
                for trial in records:
                    value = trial.pop('reward', None)
                    trial_id =  trial.pop('id', None)
                    json_records.append({'parameter': trial, 'value': value, 'id': trial_id})
            with open(args.path, 'w') as file:
                if args.type == 'csv':
                    writer = csv.DictWriter(file, set.union(*[set(r.keys()) for r in records]))
                    writer.writeheader()
                    writer.writerows(records)
                else:
                    json.dump(json_records, file)
        else:
            print_error('Export failed...')
    else:
        print_error('Restful server is not Running')
1012218
def call
      if rows.empty?
        report.done!
        return report
      end

      report.in_progress!

      persist_rows!

      report.done!
      report
    rescue ImportAborted
      report.aborted!
      report
    end
1358335
def blank_stim(self,type=None,fill=0):
        ''''''
        blank = copy.copy(self)
        blank.name = 'Blank'
        if type==None:
            type = self.type()
        if type=="column":
            num_reps = self.reps
            if num_reps==None:
                if self.type()=="column":
                    self.read_file()
                    num_reps = len(self.column)
                else:
                    nl.notify('Error: requested to return a blank column, but I can\'t figure out how many reps to make it!',level=nl.level.error)
            blank.column = [fill]*num_reps
            return blank
        if type=="times":
            blank.times = []
            return blank
481029
def main(argv=None):
    """"""
    arguments = cli_common(__doc__, argv=argv)
    driver = CampaignDriver(arguments['CAMPAIGN-DIR'], expandcampvars=False)
    driver(no_exec=True)
    if argv is not None:
        return driver
307652
public function sendCampaigns()
    {
        if ($this->jobHasAlreadyBeenRun('ddg_automation_campaign')) {
            $this->helper->log('Skipping ddg_automation_campaign job run');
            return;
        }

        $this->campaignFactory->create()->sendCampaigns();
    }
809084
def _CreateCampaign(client, budget):
  
  campaign_service = client.GetService('CampaignService')

  operations = [{
      'operator': 'ADD',
      'operand': {
          'name': 'Interplanetary Cruise #%d' % uuid.uuid4(),
          # Recommendation: Set the campaign to PAUSED when creating it to
          # prevent the ads from immediately serving. Set to ENABLED once you've
          # added targeting and the ads are ready to serve.
          'status': 'PAUSED',
          'advertisingChannelType': 'SEARCH',
          'biddingStrategyConfiguration': {
              'biddingStrategyType': 'MANUAL_CPC',
          },
          'budget': budget,
          # Required: Set the campaign's Dynamic Search Ad settings.
          'settings': [{
              'xsi_type': 'DynamicSearchAdsSetting',
              # Required: Set the domain name and language.
              'domainName': 'example.com',
              'languageCode': 'en'
          }],
          # Optional: Set the start date.
          'startDate': (datetime.datetime.now() +
                        datetime.timedelta(1)).strftime('%Y%m%d'),
          # Optional: Set the end date.
          'endDate': (datetime.datetime.now() +
                      datetime.timedelta(365)).strftime('%Y%m%d'),
      }
  }]

  campaign = campaign_service.mutate(operations)['value'][0]
  campaign_id = campaign['id']

  print 'Campaign with ID "%d" and name "%s" was added.' % (
      campaign_id, campaign['name'])

  return campaign_id
64201
def run(self, subdirectory=None):
        
        with tmp_chdir(self.gssha_directory):
            if self.hotstart_minimal_mode:
                # remove all optional output cards
                for gssha_optional_output_card in self.GSSHA_OPTIONAL_OUTPUT_CARDS:
                    self._delete_card(gssha_optional_output_card)
                # make sure running in SUPER_QUIET mode
                self._update_card('SUPER_QUIET', '')
                if subdirectory is None:
                    # give execute folder name
                    subdirectory = "minimal_hotstart_run_{0}to{1}" \
                                   .format(self.event_manager.simulation_start.strftime("%Y%m%d%H%M"),
                                           self.event_manager.simulation_end.strftime("%Y%m%d%H%M"))
            else:
                # give execute folder name
                subdirectory = "run_{0}to{1}".format(self.event_manager.simulation_start.strftime("%Y%m%d%H%M"),
                                                     self.event_manager.simulation_end.strftime("%Y%m%d%H%M"))

            # ensure unique folder naming conventions and add to exisitng event manager
            prj_evt_manager = self.project_manager.projectFileEventManager
            prj_event = prj_evt_manager.add_event(name=subdirectory,
                                                  subfolder=subdirectory,
                                                  session=self.db_session)
            eventyml_path = self.project_manager.getCard('#GSSHAPY_EVENT_YML') \
                                                .value.strip("'").strip('"')
            prj_evt_manager.write(session=self.db_session,
                                  directory=self.gssha_directory,
                                  name=os.path.basename(eventyml_path))
            # ensure event manager not propagated to child event
            self.project_manager.deleteCard('#GSSHAPY_EVENT_YML',
                                            db_session=self.db_session)
            self.db_session.delete(self.project_manager.projectFileEventManager)
            self.db_session.commit()

            # make working directory
            working_directory = os.path.join(self.gssha_directory, prj_event.subfolder)
            try:
                os.mkdir(working_directory)
            except OSError:
                pass

            # move simulation generated files to working directory
            # PRECIP_FILE, HMET_NETCDF, HMET_ASCII, CHAN_POINT_INPUT
            # TODO: Move HMET_ASCII files
            for sim_card in self.simulation_modified_input_cards:
                if sim_card != 'MAPPING_TABLE':
                    self._update_card_file_location(sim_card, working_directory)

            mapping_table_card = self.project_manager.getCard('MAPPING_TABLE')
            if mapping_table_card:
                # read in mapping table
                map_table_object = self.project_manager.readInputFile('MAPPING_TABLE',
                                                                      self.gssha_directory,
                                                                      self.db_session,
                                                                      readIndexMaps=False)

                # connect index maps to main gssha directory
                for indexMap in map_table_object.indexMaps:
                    indexMap.filename = os.path.join("..", os.path.basename(indexMap.filename))

                # write copy of mapping table to working directory
                map_table_filename = os.path.basename(mapping_table_card.value.strip("'").strip('"'))
                map_table_object.write(session=self.db_session,
                                       directory=working_directory,
                                       name=map_table_filename,
                                       writeIndexMaps=False)

            # connect to other output files in main gssha directory
            for gssha_card in self.project_manager.projectCards:
                if gssha_card.name not in self.GSSHA_REQUIRED_OUTPUT_PATH_CARDS + \
                                            self.GSSHA_OPTIONAL_OUTPUT_PATH_CARDS + \
                                            tuple(self.simulation_modified_input_cards):
                    if gssha_card.value:
                        updated_value = gssha_card.value.strip('"').strip("'")
                        if updated_value:
                            if gssha_card.name == "READ_CHAN_HOTSTART":
                                # there are two required files
                                # the .dht and .qht
                                if os.path.exists(updated_value + '.dht') \
                                        and os.path.exists(updated_value + '.qht'):
                                    updated_path = os.path.join("..", os.path.basename(updated_value))
                                    gssha_card.value = '"{0}"'.format(updated_path)
                            elif os.path.exists(updated_value):
                                updated_path = os.path.join("..", os.path.basename(updated_value))
                                gssha_card.value = '"{0}"'.format(updated_path)
                            elif gssha_card.name == '#INDEXGRID_GUID':
                                path_split = updated_value.split()
                                updated_path = os.path.basename(path_split[0].strip('"').strip("'"))
                                if os.path.exists(updated_path):
                                    new_path = os.path.join("..", os.path.basename(updated_path))
                                    try:
                                        # Get WMS ID for Index Map as part of value
                                        gssha_card.value = '"{0}" "{1}"'.format(new_path, path_split[1])
                                    except:
                                        # Like normal if the ID isn't there
                                        gssha_card.value = '"{0}"'.format(new_path)
                                else:
                                    log.warning("{0} {1} not found in project directory ...".format("#INDEXGRID_GUID", updated_path))

            # make sure project path is ""
            self._update_card("PROJECT_PATH", "", True)

            # WRITE OUT UPDATED GSSHA PROJECT FILE
            self.project_manager.write(session=self.db_session,
                                       directory=working_directory,
                                       name=self.project_manager.name)

            with tmp_chdir(working_directory):
                # RUN SIMULATION
                if self.gssha_executable and find_executable(self.gssha_executable) is not None:
                    log.info("Running GSSHA simulation ...")

                    try:
                        run_gssha_command = [self.gssha_executable,
                                             os.path.join(working_directory, self.project_filename)]
                        # run GSSHA
                        out = subprocess.check_output(run_gssha_command)

                        # write out GSSHA output
                        log_file_path = os.path.join(working_directory, 'simulation.log')
                        with open(log_file_path, mode='w') as logfile:
                            logfile.write(out.decode('utf-8'))
                            # log to other logger if debug mode on
                            if log.isEnabledFor(logging.DEBUG):
                                for line in out.split(b'\n'):
                                    log.debug(line.decode('utf-8'))

                    except subprocess.CalledProcessError as ex:
                        log.error("{0}: {1}".format(ex.returncode, ex.output))

                else:
                    missing_exe_error = ("GSSHA executable not found. "
                                         "Skipping GSSHA simulation run ...")
                    log.error(missing_exe_error)
                    raise ValueError(missing_exe_error)

            return working_directory
534392
def execute_no_results(self, sock_info, generator):
        
        # Cannot have both unacknowledged write and bypass document validation.
        if self.bypass_doc_val and sock_info.max_wire_version >= 4:
            raise OperationFailure("Cannot set bypass_document_validation with"
                                   " unacknowledged write concern")
        coll = self.collection
        # If ordered is True we have to send GLE or use write
        # commands so we can abort on the first error.
        write_concern = WriteConcern(w=int(self.ordered))
        op_id = _randint()

        for run in generator:
            try:
                if run.op_type == _INSERT:
                    coll._insert(
                        sock_info,
                        run.ops,
                        self.ordered,
                        write_concern=write_concern,
                        op_id=op_id,
                        bypass_doc_val=self.bypass_doc_val)
                elif run.op_type == _UPDATE:
                    for operation in run.ops:
                        doc = operation['u']
                        check_keys = True
                        if doc and next(iter(doc)).startswith('$'):
                            check_keys = False
                        coll._update(
                            sock_info,
                            operation['q'],
                            doc,
                            operation['upsert'],
                            check_keys,
                            operation['multi'],
                            write_concern=write_concern,
                            op_id=op_id,
                            ordered=self.ordered,
                            bypass_doc_val=self.bypass_doc_val)
                else:
                    for operation in run.ops:
                        coll._delete(sock_info,
                                     operation['q'],
                                     not operation['limit'],
                                     write_concern,
                                     op_id,
                                     self.ordered)
            except OperationFailure:
                if self.ordered:
                    break
485833
def main(unused_argv):
  """"""

  print('Wiping dir %s' % FLAGS.base_dir, flush=True)
  shutil.rmtree(FLAGS.base_dir, ignore_errors=True)
  dirs = [fsdb.models_dir(), fsdb.selfplay_dir(), fsdb.holdout_dir(),
          fsdb.eval_dir(), fsdb.golden_chunk_dir(), fsdb.working_dir()]
  for d in dirs:
    ensure_dir_exists(d);

  # Copy the flag files so there's no chance of them getting accidentally
  # overwritten while the RL loop is running.
  flags_dir = os.path.join(FLAGS.base_dir, 'flags')
  shutil.copytree(FLAGS.flags_dir, flags_dir)
  FLAGS.flags_dir = flags_dir

  # Copy the target model to the models directory so we can find it easily.
  shutil.copy(FLAGS.target_path, os.path.join(fsdb.models_dir(), 'target.pb'))

  logging.getLogger().addHandler(
      logging.FileHandler(os.path.join(FLAGS.base_dir, 'rl_loop.log')))
  formatter = logging.Formatter('[%(asctime)s] %(message)s',
                                '%Y-%m-%d %H:%M:%S')
  for handler in logging.getLogger().handlers:
    handler.setFormatter(formatter)

  with logged_timer('Total time'):
    try:
      rl_loop()
    finally:
      asyncio.get_event_loop().close()
965860
def run(self):
        """"""
        # Try to create the directory
        if not os.path.exists(self.output):
            try:
                os.mkdir(self.output)
            except:
                print 'failed to create output directory %s' % self.output

        # Be sure it is a directory
        if not os.path.isdir(self.output):
            print 'invalid output directory %s' % self.output
            sys.exit(1)

        # Create the CSV handlers
        visitors = [
            _CompaniesCSV(self.output),
            _ActivitiesCSV(self.output),
            _ActivitiesSeenCSV(self.output),
            _QSACSV(self.output),
        ]

        # Run by each company populating the CSV files
        for path in glob.glob(os.path.join(self.input, '*.json')):
            with open(path, 'r') as f:
                try:
                    data = json.load(f, encoding='utf-8')
                except ValueError:
                    continue

                for visitor in visitors:
                    visitor.visit(data)
448810
def generate_report(report_id, wait = false)
      xml = make_xml('ReportGenerateRequest', { 'report-id' => report_id })
      response = execute(xml)
      if response.success
        response.res.elements.each('//ReportSummary') do |summary|
          summary = ReportSummary.parse(summary)
          # If not waiting or the report is finished, return now.
          return summary unless wait && summary.status == 'Started'
        end
      end
      so_far = 0
      while wait
        summary = last_report(report_id)
        return summary unless summary.status == 'Started'
        sleep 5
        so_far += 5
        if (so_far % 60).zero?
          puts "Still waiting. Current status: #{summary.status}"
        end
      end
      nil
    end
843309
def main(unused_argv):
  """"""
  run_config = run_configs.get()

  if not gfile.Exists(FLAGS.replays):
    sys.exit("{} doesn't exist.".format(FLAGS.replays))

  stats_queue = multiprocessing.Queue()
  stats_thread = threading.Thread(target=stats_printer, args=(stats_queue,))
  stats_thread.start()
  try:
    # For some reason buffering everything into a JoinableQueue makes the
    # program not exit, so save it into a list then slowly fill it into the
    # queue in a separate thread. Grab the list synchronously so we know there
    # is work in the queue before the SC2 processes actually run, otherwise
    # The replay_queue.join below succeeds without doing any work, and exits.
    print("Getting replay list:", FLAGS.replays)
    replay_list = sorted(run_config.replay_paths(FLAGS.replays))
    print(len(replay_list), "replays found.\n")
    replay_queue = multiprocessing.JoinableQueue(FLAGS.parallel * 10)
    replay_queue_thread = threading.Thread(target=replay_queue_filler,
                                           args=(replay_queue, replay_list))
    replay_queue_thread.daemon = True
    replay_queue_thread.start()

    for i in range(FLAGS.parallel):
      p = ReplayProcessor(i, run_config, replay_queue, stats_queue)
      p.daemon = True
      p.start()
      time.sleep(1)  # Stagger startups, otherwise they seem to conflict somehow

    replay_queue.join()  # Wait for the queue to empty.
  except KeyboardInterrupt:
    print("Caught KeyboardInterrupt, exiting.")
  finally:
    stats_queue.put(None)  # Tell the stats_thread to print and exit.
    stats_thread.join()
680906
private void createTransactionSummary(FilePath reportFolder,
                                          String testFolderPath,
                                          File artifactsDir,
                                          List<String> reportNames,
                                          TestResult testResult) throws IOException, InterruptedException {

        File testFolderPathFile = new File(testFolderPath);
        String subFolder = HTML_REPORT_FOLDER + File.separator + IE_REPORT_FOLDER + File.separator + HTML_REPORT_FOLDER;
        FilePath htmlReportPath = new FilePath(reportFolder, subFolder);
        if (htmlReportPath.exists()) {
            File reportDirectory = new File(artifactsDir.getParent(), TRANSACTION_SUMMARY_FOLDER);
            if (!reportDirectory.exists()) {
                reportDirectory.mkdir();
            }
            String newFolderName = org.apache.commons.io.FilenameUtils.getName(testFolderPathFile.getPath());
            File testDirectory = new File(reportDirectory, newFolderName);
            if (!testDirectory.exists()) {
                testDirectory.mkdir();
            }

            FilePath dstReportPath = new FilePath(testDirectory);
            FileFilter reportFileFilter = new WildcardFileFilter(TRANSACTION_REPORT_NAME + ".*");
            List<FilePath> reporFiles = htmlReportPath.list(reportFileFilter);
            for (FilePath fileToCopy : reporFiles) {
                FilePath dstFilePath = new FilePath(dstReportPath, fileToCopy.getName());
                fileToCopy.copyTo(dstFilePath);
            }
            FilePath cssFilePath = new FilePath(htmlReportPath, "Properties.css");
            if (cssFilePath.exists()) {
                FilePath dstFilePath = new FilePath(dstReportPath, cssFilePath.getName());
                cssFilePath.copyTo(dstFilePath);
            }
            FilePath pngFilePath = new FilePath(htmlReportPath, "tbic_toexcel.png");
            if (pngFilePath.exists()) {
                FilePath dstFilePath = new FilePath(dstReportPath, pngFilePath.getName());
                pngFilePath.copyTo(dstFilePath);
            }

            outputReportFiles(reportNames, reportDirectory, testResult, true);

        }

    }
6234
def schedule(argv)

      report = @account.report do
        name            'boh'
        type            'Url'
        aggregation     'Daily'
        cross_client    true
        zero_impression true

        start_day '2010-01-01'
        end_day   '2010-01-30'

        column "CustomerName"
        column "ExternalCustomerId"
        column "CampaignStatus"
        column "Campaign"
        column "CampaignId"
        column "AdGroup"
        column "AdGroupId"
        column "AdGroupStatus"
        column "QualityScore"
        column "FirstPageCpc"
        column "Keyword"
        column "KeywordId"
        column "KeywordTypeDisplay"
        column "DestinationURL"
        column "Impressions"
        column "Clicks"
        column "CTR"
        column "CPC"
        column "MaximumCPC"
        column "Cost"
        column "AveragePosition"
      end

      unless report.validate
        puts "report not valid"
        exit
      end
      puts "scheduled job"
      job = report.schedule
      job.wait(10) { |report, status| puts "status #{status}" }
      report.download("test_report.xml")
      true
    end
1141092
def save_report(self, file_path):
        """"""
        try:
            report = self.create_report()
        except coverage.CoverageException as e:
            log.error('Failure to gather coverage:', exc_info=e)
        else:
            with open(file_path, 'w') as report_file:
                report_file.write(report)
95598
def create_event(*args)
      raise "EventCampaign needs to be saved before Event creation" if self.id.nil?

      (args[0]).merge!(:campaign_id => self.id)

      event = ActionKitApi::Event.new(*args)
    end