The servlet entry point. http://host:port/fedora/management/upload
516212
@Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Context context =
                ReadOnlyContext.getContext(Constants.HTTP_REQUEST.REST.uri,
                                           request);
        try {
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload();

            // Parse the request, looking for "file"
            InputStream in = null;
            FileItemIterator iter = upload.getItemIterator(request);
            while (in == null && iter.hasNext()) {
                FileItemStream item = iter.next();
                logger.info("Got next item: isFormField={} fieldName={}", item.isFormField(), item.getFieldName());
                if (!item.isFormField() && item.getFieldName().equals("file")) {
                    in = item.openStream();
                }
            }
            if (in == null) {
                sendResponse(HttpServletResponse.SC_BAD_REQUEST,
                             "No data sent.",
                             response);
            } else {
                sendResponse(HttpServletResponse.SC_CREATED,
                             m_management.putTempStream(context, in),
                             response);
            }
        } catch (AuthzException ae) {
            throw RootException.getServletException(ae,
                                                    request,
                                                    "Upload",
                                                    EMPTY_STRING_ARRAY);
        } catch (Exception e) {
            e.printStackTrace();
            sendResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e
                    .getClass().getName()
                    + ": " + e.getMessage(), response);
        }
    }
1365114
def main():
    
    parser = argparse.ArgumentParser(
        description='Performs attribute selection from the command-line. Calls JVM start/stop automatically.')
    parser.add_argument("-j", metavar="classpath", dest="classpath", help="additional classpath, jars/directories")
    parser.add_argument("-X", metavar="heap", dest="heap", help="max heap size for jvm, e.g., 512m")
    parser.add_argument("-i", metavar="input", dest="input", required=True, help="input file")
    parser.add_argument("-c", metavar="class index", dest="classindex", help="1-based class attribute index")
    parser.add_argument("-s", metavar="search", dest="search", help="search method, classname and options")
    parser.add_argument("-x", metavar="num folds", dest="numfolds", help="number of folds")
    parser.add_argument("-n", metavar="seed", dest="seed", help="the seed value for randomization")
    parser.add_argument("evaluator", help="evaluator classname, e.g., weka.attributeSelection.CfsSubsetEval")
    parser.add_argument("option", nargs=argparse.REMAINDER, help="additional evaluator options")
    parsed = parser.parse_args()
    jars = []
    if parsed.classpath is not None:
        jars = parsed.classpath.split(os.pathsep)
    params = []
    if parsed.input is not None:
        params.extend(["-i", parsed.input])
    if parsed.classindex is not None:
        params.extend(["-c", parsed.classindex])
    if parsed.search is not None:
        params.extend(["-s", parsed.search])
    if parsed.numfolds is not None:
        params.extend(["-x", parsed.numfolds])
    if parsed.seed is not None:
        params.extend(["-n", parsed.seed])

    jvm.start(jars, max_heap_size=parsed.heap, packages=True)

    logger.debug("Commandline: " + join_options(sys.argv[1:]))

    try:
        evaluation = ASEvaluation(classname=parsed.evaluator)
        if len(parsed.option) > 0:
            evaluation.options = parsed.option
        print(AttributeSelection.attribute_selection(evaluation, params))
    except Exception as e:
        print(e)
    finally:
        jvm.stop()
1252301
public static void main(String[] args) throws Exception {
    RouteGuideServer server = new RouteGuideServer(8980);
    server.start();
    server.blockUntilShutdown();
  }
73574
def post(self, url, content='', files=None, params=None, extra_headers={}, upload_callback=None):
        ''
        if not url.startswith('http'):
            # relative url
            url = self.rootpath + url

        log.debug('posting content (len %s) to url %s', len(content) if content is not None else '?', url)
        headers = self.session.headers.copy()
        headers.update(**extra_headers)

        if not files is None:
            m = requests_toolbelt.MultipartEncoder(fields=files)
            if upload_callback is not None:
                m_len = m.len # compute value for callback closure
                def callback(monitor):
                    upload_callback(monitor, m_len)

                m = requests_toolbelt.MultipartEncoderMonitor(m, callback)
            headers['content-type'] = m.content_type
        else:
            m = content
        url = self.escapeUrl(url)
        r = self.session.post(url, data=m, params=params, headers=headers)
        if not r.ok:
            log.warning('HTTP POST failed: %s', r.text)
            raise JFSError(r.reason)
        return self.getObject(r)
18470
def main():
    

    if len(sys.argv) < 6:
        print("Usage: %s server_url username password namespace' \
              ' classname" %  sys.argv[0])
        print('Using internal defaults')
        server_url = SERVER_URL
        namespace = TEST_NAMESPACE
        username = USERNAME
        password = PASSWORD
        classname = TEST_CLASS
    else:
        print('Get from input')
        server_url = sys.argv[1]
        namespace = sys.argv[2]
        username = sys.argv[3]
        password = sys.argv[4]
        classname = sys.argv[5]

    # create the credentials tuple for WBEMConnection
    creds = (username, password)

    # call the method to execute the request and display results
    execute_request(server_url, creds, namespace, classname)

    return 0
1129750
function startServer(devServerUrl) {
  const { port: devServerPort } = url.parse(devServerUrl);
  return choosePort(HOST, devServerPort - 1)
    .then(port => {
      if (port == null) {
        // We have not found a port.
        return;
      }
      const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
      const appName = require(paths.appPackageJson).name;
      const urls = prepareUrls(protocol, HOST, port);
      // Directly set the HOST, PORT and PROTOCOL, which would be used in DefinePlugin
      // let the webpack define the public path correctly in DefinePlugin
      process.env.HOST = HOST;
      process.env.PORT = port;
      process.env.PROTOCOL = protocol;
      process.env.PUBLIC_URL = url.format({ protocol: protocol, hostname: HOST, port: devServerPort });

      // Create a webpack compiler that is configured with custom messages.
      const webpackConfig = serverlize(paths, config, `${devServerUrl}/`);
      const compiler = createCompiler(webpack, webpackConfig, appName, urls, useYarn);
      let browserOpened = false;
      compiler.watch({
        quiet: true,
        stats: 'none'
      }, (err, stats) => {
        if (!browserOpened) {
          openBrowser(urls.localUrlForBrowser);
          browserOpened = true;
        }
        if (err) {
          console.log(chalk.red('Failed to compile.\n'));
          printBuildError(err);
          return;
        }
        if (isInteractive) {
          clearConsole();
        }
        const messages = formatWebpackMessages(stats.toJson({}, true));
        if (messages.errors.length) {
          // Only keep the first error. Others are often indicative
          // of the same problem, but confuse the reader with noise.
          if (messages.errors.length > 1) {
            messages.errors.length = 1;
          }
          console.log(chalk.red('Failed to compile.\n'));
          printBuildError(new Error(messages.errors.join('\n\n')));
          return;
        }
        console.log(chalk.green('Compiled successfully!'));
        console.log(
          `To create a production build, use ` +
            `${chalk.cyan(`${useYarn ? 'yarn' : 'npm run'} build:server`)}.`
        );
        console.log('Note that all client side errors or warnings are suppressed.');
        console.log();
      });
    })
    .catch(err => {
      if (err && err.message) {
        console.log(err.message);
      }
      process.exit(1);
    });
}
1001754
public static void main(String[] args)
    {
        if (args.length==0 || args.length>2)
        {
            System.err.println
                ("\nUsage - java org.browsermob.proxy.jetty.http.HttpServer [<addr>:]<port>");
            System.err.println
                ("\nUsage - java org.browsermob.proxy.jetty.http.HttpServer -r [savefile]");
            System.err.println
                ("  Serves files from '.' directory");
            System.err.println
                ("  Dump handler for not found requests");
            System.err.println
                ("  Default port is 8080");
            System.exit(1);
        }
        
        try{
            
            if (args.length==1)
            {
                // Create the server
                HttpServer server = new HttpServer();
                
                // Default is no virtual host
                String host=null;
                HttpContext context = server.getContext(host,"/");
                context.setResourceBase(".");
                context.addHandler(new ResourceHandler());
                context.addHandler(new DumpHandler());
                context.addHandler(new NotFoundHandler());

                InetAddrPort address = new InetAddrPort(args[0]);
                server.addListener(address);

                server.start();
            }
            else
            {
                Resource resource = Resource.newResource(args[1]);
                ObjectInputStream in = new ObjectInputStream(resource.getInputStream());
                HttpServer server = (HttpServer)in.readObject();
                in.close();
                server.start();
            }
            
        }
        catch (Exception e)
        {
            log.warn(LogSupport.EXCEPTION,e);
        }
    }
801403
def pub_upload(args, location=None, prefix=""):
    
    upload(location, remotes=args, prefix=prefix)
1130938
function main() {
  var server = new grpc.Server();
  server.addService(services.GreeterService, {sayHello: sayHello});
  server.bind('0.0.0.0:50051', grpc.ServerCredentials.createInsecure());
  server.start();
}
1310304
public static void main(String[] args) throws IOException {
		String outputDirectory = args[0];

		for (final RestAPIVersion apiVersion : RestAPIVersion.values()) {
			if (apiVersion == RestAPIVersion.V0) {
				// this version exists only for testing purposes
				continue;
			}
			createHtmlFile(
				new DocumentingDispatcherRestEndpoint(),
				apiVersion,
				Paths.get(outputDirectory, "rest_" + apiVersion.getURLVersionPrefix() + "_dispatcher.html"));
		}
	}
207745
public static void main(String[] args) throws Exception {
		// javamelody parameters (optional),
		final Map<Parameter, String> parameters = new HashMap<>();
		// to add basic auth:
		// parameters.put(Parameter.AUTHORIZED_USERS, "admin:pwd");

		// to change the default storage directory:
		// parameters.put(Parameter.STORAGE_DIRECTORY, "/tmp/javamelody");

		// to change the default resolution in seconds:
		// parameters.put(Parameter.RESOLUTION_SECONDS, "60");

		// to hide all statistics such as http and sql, except logs:
		// parameters.put(Parameter.DISPLAYED_COUNTERS, "log");
		// parameters.put(Parameter.NO_DATABASE, "true");

		// enable hotspots sampling with a period of 1 second:
		parameters.put(Parameter.SAMPLING_SECONDS, "1.0");

		// set the path of the reports:
		parameters.put(Parameter.MONITORING_PATH, "/");

		// start the embedded http server with javamelody
		EmbeddedServer.start(8080, parameters);
		System.out.println("");
		System.out.println("For the reports, you can browse http://localhost:8080/");
		System.out.println("");

		// compute PI just to have something to do
		System.out.print("PI = ");
		final Pi p = new Pi();
		p.calcPiDigits();
	}
271747
def main():
   

   args = GetArgs()
   if args.password:
      password = args.password
   else:
      password = getpass.getpass(prompt='Enter password for host %s and '
                                        'user %s: ' % (args.host,args.user))

   context = None
   if hasattr(ssl, '_create_unverified_context'):
      context = ssl._create_unverified_context()
   si = SmartConnect(host=args.host,
                     user=args.user,
                     pwd=password,
                     port=int(args.port),
                     sslContext=context)
   if not si:
       print("Could not connect to the specified host using specified "
             "username and password")
       return -1

   atexit.register(Disconnect, si)

   content = si.RetrieveContent()
   for child in content.rootFolder.childEntity:
      if hasattr(child, 'vmFolder'):
         datacenter = child
         vmFolder = datacenter.vmFolder
         vmList = vmFolder.childEntity
         for vm in vmList:
            PrintVmInfo(vm)
   return 0
693613
def main():
    """"""
    parser = argparse.ArgumentParser(
        description='Start an instance of the Cheroot WSGI/HTTP server.',
    )
    for arg, spec in _arg_spec.items():
        parser.add_argument(arg, **spec)
    raw_args = parser.parse_args()

    # ensure cwd in sys.path
    '' in sys.path or sys.path.insert(0, '')

    # create a server based on the arguments provided
    raw_args._wsgi_app.server(raw_args).safe_start()
263726
def main():
    
    try:
        # Get the `src` directory's absolute path
        src_path = os.path.dirname(
            # `aoiklivereload` directory's absolute path
            os.path.dirname(
                # `demo` directory's absolute path
                os.path.dirname(
                    # This file's absolute path
                    os.path.abspath(__file__)
                )
            )
        )

        # If the `src` directory path is not in `sys.path`
        if src_path not in sys.path:
            # Add to `sys.path`.
            #
            # This aims to save user setting PYTHONPATH when running this demo.
            #
            sys.path.append(src_path)

        # Import reloader class
        from aoiklivereload import LiveReloader

        # Create reloader
        reloader = LiveReloader()

        # Start watcher thread
        reloader.start_watcher_thread()

        # Server host
        server_host = '0.0.0.0'

        # Server port
        server_port = 8000

        # Get message
        msg = '# ----- Run server -----\nHost: {}\nPort: {}'.format(
            server_host, server_port
        )

        # Print message
        print(msg)

        # Create Flask app
        flask_app = flask.Flask(__name__)

        # Create request handler
        @flask_app.route('/')
        def hello_handler():  # pylint: disable=unused-variable
            """
            Request handler.

            :return:
                Response body.
            """
            # Return response body
            return 'hello'

        # Run server
        flask_app.run(
            host=server_host,
            port=server_port,
            # Disable Flask's reloader
            debug=False,
        )

    # If have `KeyboardInterrupt`
    except KeyboardInterrupt:
        # Not treat as error
        pass
853984
def main():
    """"""

    #
    # setup command line parsing a la argpase
    #
    parser = argparse.ArgumentParser()

    # positional args
    parser.add_argument('uri', metavar='URI', nargs='?', default='/',
                        help='[owserver:]//hostname:port/path')

    #
    # parse command line args
    #
    args = parser.parse_args()

    #
    # parse args.uri and substitute defaults
    #
    urlc = urlsplit(args.uri, scheme='owserver', allow_fragments=False)
    assert urlc.fragment == ''
    if urlc.scheme != 'owserver':
        parser.error("Invalid URI scheme '{0}:'".format(urlc.scheme))
    if urlc.query:
        parser.error("Invalid URI, query component '?{0}' not allowed"
                     .format(urlc.query))
    try:
        host = urlc.hostname or 'localhost'
        port = urlc.port or 4304
    except ValueError as error:
        parser.error("Invalid URI: invalid net location '//{0}/'"
                     .format(urlc.netloc))

    #
    # create owserver proxy object
    #
    try:
        owproxy = protocol.proxy(host, port, persistent=True)
    except protocol.ConnError as error:
        print("Unable to open connection to '{0}:{1}'\n{2}"
              .format(host, port, error), file=sys.stderr)
        sys.exit(1)
    except protocol.ProtocolError as error:
        print("Protocol error, '{0}:{1}' not an owserver?\n{2}"
              .format(host, port, error), file=sys.stderr)
        sys.exit(1)

    stress(owproxy, urlc.path)
1026006
@Override
  public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (req.getRequestURI().endsWith("upload")) {
      uploadCallback(req, resp);
    } else {
      resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
    }
  }
1369987
def post(self):
        
        filepath = self.get_body_argument('filepath')

        try:
            self.fs.create_directory(filepath)
            encoded_filepath = tornado.escape.url_escape(filepath,plus=True)
            resource_uri = self.reverse_url('filesystem:directories-details', encoded_filepath)
            self.write({'uri':resource_uri})
        except OSError:
            raise tornado.web.HTTPError(404)