### Install go-soda Source: https://dev.socrata.com/libraries/golang.html Use the go get command to install the package. ```bash go get -u github.com/SebastiaanKlippert/go-soda ``` -------------------------------- ### Command Line Example Source: https://dev.socrata.com/libraries/python-socrata-py.html Run a command-line example to create a dataset. Replace placeholders with your actual file path, domain, username, and password. ```bash python -m examples.create 'Police Reports' ~/Desktop/catalog.data.gov/Seattle_Real_Time_Fire_911_Calls.csv 'pete-test.test-socrata.com' --username $SOCRATA_USERNAME --password $SOCRATA_PASSWORD ``` -------------------------------- ### Fetch Socrata Data with soda-ruby Source: https://dev.socrata.com/foundry/data.cityofchicago.org/6zsd-86xi Utilize the soda-ruby gem to interact with Socrata APIs from Ruby. This example shows how to initialize the client, fetch a limited number of results from a dataset, and print the first result's key-value pairs. Ensure the gem is installed and replace 'YOURAPPTOKENHERE' with your token. ```Ruby #!/usr/bin/env ruby require 'soda/client' client = SODA::Client.new({:domain => "data.cityofchicago.org", :app_token => "YOURAPPTOKENHERE"}) results = client.get("ijzp-q8t2", :$limit => 5000) puts "Got #{results.count} results. Dumping first results:" results.first.each do |k, v| puts "#{key}: #{value}" end ``` -------------------------------- ### OutputSchema Add Column Example Source: https://dev.socrata.com/libraries/python-socrata-py.html Example usage of adding columns to an OutputSchema. ```python new_output_schema = output # Add a new column, which is computed from the `celsius` column .add_column('fahrenheit', 'Degrees (Fahrenheit)', '(to_number(`celsius`) * (9 / 5)) + 32', 'the temperature in celsius') # Add a new column, which is computed from the `celsius` column .add_column('kelvin', 'Degrees (Kelvin)', '(to_number(`celsius`) + 273.15') .run() ``` -------------------------------- ### Reproject Geometry Examples Source: https://dev.socrata.com/docs/transforms/reproject.html Examples showing how to reproject points between different coordinate systems, including handling explicit source projections. ```text reproject(a_wgs84_point, '+proj=aea +lat_1=34 +lat_2=47 +lat_0=43 +lon_0=-120 +x_0=0 +y_0=0 +ellps=GRS80 +datum=NAD83 +units=m +no_defs') -- Result: {"type":"Point","coordinates":[-175581.00675423793,515668.2819819323]} ``` ```text reproject(to_point('POINT (-73.138260 40.792240)'), '+init=epsg:3627') -- Result: {"type":"Point","coordinates":[372728.3308536674,69825.24782297359]} ``` ```text reproject(set_projection(to_point('POINT (372728.3308536674 69825.24782297359)'), '+init=epsg:3627'), '+init=epsg:4326') -- Result: {"type":"Point","coordinates":[-73.13826,40.79224]} ``` ```text reproject(set_projection(to_point('POINT(752235200 34768994)'), '+proj=aea +lat_1=34 +lat_2=47 +lat_0=43 +lon_0=-120 +x_0=0 +y_0=0 +ellps=GRS80 +datum=NAD83 +units=m +no_defs'), '+init=epsg:4326') -- Result: {"type":"reprojection_error","english":"Failed to reproject that value, are the x and y out of range for that projection?","data":{"message":"Failed to reproject that value, are the x and y out of range for that projection?"}} ``` -------------------------------- ### Using LIMIT with ORDER BY Source: https://dev.socrata.com/docs/queries/limit.html Use the LIMIT parameter with $order to retrieve a specific number of top-ranked records from a dataset. This example shows how to get the ten strongest earthquakes. ```text SELECT * WHERE 'earthquake_magnitude' > 0 ORDER BY 'earthquake_magnitude' DESC LIMIT 10 ``` -------------------------------- ### Example: region_code with valid input Source: https://dev.socrata.com/docs/transforms/region_code.html This example demonstrates a successful region code lookup, returning a numeric region ID. ```SocrataQL region_code(make_point(2, 3), 'hehe-hehe') ``` -------------------------------- ### Install RSocrata Source: https://dev.socrata.com/libraries/r.html Installation methods for the released version from CRAN or development versions from GitHub. ```R install.packages("RSocrata") ``` ```R # install.packages("devtools") devtools::install_github("Chicago/RSocrata") ``` ```R # install.packages("devtools") devtools::install_github("Chicago/RSocrata", ref="dev") ``` -------------------------------- ### OutputSchema Drop Column Example Source: https://dev.socrata.com/libraries/python-socrata-py.html Example usage of dropping a column. ```python new_output_schema = output .drop_column('foo') .run() ``` -------------------------------- ### OutputSchema Change Column Transform Example Source: https://dev.socrata.com/libraries/python-socrata-py.html Example usage of changing column transforms. ```python new_output_schema = output .change_column_transform('the_date').to('to_fixed_timestamp(`date`)') # Make the celsius column all numbers .change_column_transform('celsius').to('to_number(`celsius`)') # Add a new column, which is computed from the `celsius` column .add_column('fahrenheit', 'Degrees (Fahrenheit)', '(to_number(`celsius`) * (9 / 5)) + 32', 'the temperature in celsius') .run() ``` -------------------------------- ### Install Python Packages with Pip Source: https://dev.socrata.com/blog/2014/11/04/data-visualization-with-python.html Install the necessary Python packages, Pandas and Bokeh, using pip before running the analysis script. ```bash pip install pandas pip install bokeh ``` -------------------------------- ### Example: Querying Employees by Department using STARTS_WITH() Source: https://dev.socrata.com/docs/datatypes/text.html This example demonstrates how to use the `starts_with()` function to find employees whose titles contain 'CHIEF'. This query is applicable to 2.1 and 3.0 endpoints. ```sql The TryIt macro has been disabled until future notice while we upgrade this site to SODA3. ``` -------------------------------- ### Example pypirc Configuration Source: https://dev.socrata.com/libraries/python-socrata-py.html Configuration file format for distributing packages via twine. ```ini [distutils] index-servers = local pypi [local] repository=https://repo.socrata.com/artifactory/api/pypi/pypi username=shared-engr password= [pypi] repository=https://upload.pypi.org/legacy/ username=socrata password= ``` -------------------------------- ### Import pandas and verify version Source: https://dev.socrata.com/blog/2016/02/01/pandas-and-jupyter-notebook.html Initializes the pandas library and checks the installed version. ```python import pandas as pd print(pd.__version__) > 0.17.1 ``` -------------------------------- ### OutputSchema Change Column Metadata Example Source: https://dev.socrata.com/libraries/python-socrata-py.html Example usage of changing column metadata. ```python new_output_schema = output # Change the field_name of date to the_date .change_column_metadata('date', 'field_name').to('the_date') # Change the description of the celsius column .change_column_metadata('celsius', 'description').to('the temperature in celsius') # Change the display name of the celsius column .change_column_metadata('celsius', 'display_name').to('Degrees (Celsius)') .run() ``` -------------------------------- ### Install socrata-py Source: https://dev.socrata.com/libraries/python-socrata-py.html Install the socrata-py package using pip. A virtual environment is recommended. This package has a hard dependency on 'requests'. ```bash pip3 install socrata-py ``` -------------------------------- ### Reproject Geometry to WGS84 Examples Source: https://dev.socrata.com/docs/transforms/reproject_to_wgs84.html Usage examples for reprojecting geometries, including direct point conversion and projection setting. ```text reproject_to_wgs84(a_epsg_3627_point) -- Result: {"type":"Point","coordinates":[-73.13826,40.79224]} reproject_to_wgs84(set_projection(to_point('POINT (372728.3308536674 69825.24782297359)'), '+init=epsg:3627')) -- Result: {"type":"Point","coordinates":[-73.13826,40.79224]} ``` -------------------------------- ### Install RSocrata Package Source: https://dev.socrata.com/foundry/data.cityofchicago.org/6zsd-86xi Instructions to install the RSocrata package from GitHub, which is maintained by The City of Chicago and the community. ```r ## Install the required package with: ``` -------------------------------- ### Geocode Function Usage Examples Source: https://dev.socrata.com/docs/transforms/geocode.html Examples demonstrating how to call the geocode function with and without a country parameter. ```text geocode(`my_address_column`, 'Seattle', 'WA', `zipcode_column`) geocode(`my_address_column`, 'Seattle', 'WA', `zipcode_column`, 'US') ``` -------------------------------- ### Install ember-socrata and Dependencies Source: https://dev.socrata.com/libraries/ember.html Install the ember-socrata addon and its dependencies, ember-browserify and soda-js, using the Ember CLI and npm. ```bash ember install ember-socrata ember install ember-browserify npm install soda-js ``` -------------------------------- ### Install Socrata.jl Package Source: https://dev.socrata.com/libraries/julia.html Use Pkg.clone to install the Socrata.jl package from GitHub. Ensure you have Julia and the Pkg manager set up. ```julia Pkg.clone("https://github.com/dreww2/Socrata.jl.git") ``` -------------------------------- ### Example: region_code with no matching region Source: https://dev.socrata.com/docs/transforms/region_code.html This example illustrates the response when the provided point does not fall within any region in the specified dataset. ```SocrataQL region_code(make_point(2, 3), 'no-match') ``` -------------------------------- ### HTTP Basic Authentication Example Source: https://dev.socrata.com/docs/authentication.html This example demonstrates an HTTP session using Basic Authentication. Ensure all requests are made over a secure HTTPS connection. The Authorization header is typically generated by your HTTP library. ```http POST /api/v3/views/4tka-6guv/query.json HTTP/1.1 Host: soda.demo.socrata.com Accept: */* Authorization: Basic [REDACTED] Content-Length: 253 Content-Type: application/json X-App-Token: [REDACTED] [ { ... } ] ``` -------------------------------- ### Example: region_code with permission error Source: https://dev.socrata.com/docs/transforms/region_code.html This example shows the error response when a user lacks permission to perform region coding against the specified dataset. ```SocrataQL region_code(make_point(2, 3), 'forbidden-view') ``` -------------------------------- ### Example: Find City with Most Vertices using num_points Source: https://dev.socrata.com/docs/functions/num_points.html This example demonstrates how to use the num_points function to find the city with the most vertices in the Tiger Line 'Places' dataset. Note: The TryIt macro is currently disabled. ```text The `num_points(...)` function returns the number of vertices that a given geometry is comprised of. For example, a rectangle would contain four vertices. For example, to get the city with the most vertices in the Tiger Line “Places” dataset: ``` -------------------------------- ### Access Socrata Data with SODA.NET Source: https://dev.socrata.com/foundry/data.seattle.gov/ivtm-938t Use the SODA.NET client library to fetch data from Socrata in a .NET environment. Install the CSM.SodaDotNet package via NuGet. The example shows how to get resource rows and iterate through the first result. ```csharp using System; using System.Linq; // Install the package from Nuget first: // PM> Install-Package CSM.SodaDotNet using SODA; var client = new SodaClient("https://data.seattle.gov", "YOURAPPTOKENHERE"); // Get a reference to the resource itself // The result (a Resouce object) is a generic type // The type parameter represents the underlying rows of the resource // and can be any JSON-serializable class var dataset = client.GetResource("egc4-d24i"); // Resource objects read their own data var rows = dataset.GetRows(limit: 5000); Console.WriteLine("Got {0} results. Dumping first results:", rows.Count()); foreach (var keyValue in rows.First()) { Console.WriteLine(keyValue); } ``` -------------------------------- ### API Endpoint Example Source: https://dev.socrata.com/foundry/data.cityofchicago.org/6zsd-86xi This is an example of a direct API endpoint URL for querying the Crimes - 2001 to Present dataset. It includes parameters for pagination and an application token. Use POST for longer queries. ```URL https://data.cityofchicago.org/api/v3/views/ijzp-q8t2/query.json?pageNumber=1&pageSize=10&app_token=$YOUR_APP_TOKEN ``` -------------------------------- ### Build the Project Source: https://dev.socrata.com/libraries/csharp.html Clone the repository and build the solution using the .NET CLI. ```bash git clone git@github.com:CityofSantaMonica/SODA.NET.git SODA.NET cd SODA.NET dotnet build ``` -------------------------------- ### Get Substring with Slice Function Source: https://dev.socrata.com/docs/transforms/slice.html Use the slice function to extract a portion of a string. It accepts a start index and a length. Negative indices are supported for both start and length. ```javascript slice('foobar', 0, 2) -- Result: "fo" ``` ```javascript slice('foobar', -3, 3) -- Result: "bar" ``` ```javascript slice('foobar', -10, 1300) -- Result: "" ``` ```javascript slice('foobar', 0, -2) -- Result: {"type":"invalid_length","english":"Invalid length -2. Slice length must be a nonnegative integer.","data":{"length":-2}} ``` -------------------------------- ### Navigate and Serve Ember Project Source: https://dev.socrata.com/blog/2016/06/30/quickly-building-an-ember-app-backed-by-socrata-open-data.html Change into the newly created project directory and start the local development server to view the application in a browser. ```bash $ cd cta-ridership $ ember serve ``` -------------------------------- ### Get Convex Hull of Chicago Crimes Source: https://dev.socrata.com/docs/functions/convex_hull.html Example demonstrating how to get the convex hull surrounding all crimes in Chicago for the year 2014. This function works with 2.1 and 3.0 endpoints. ```sql SELECT convex_hull(the_geom) FROM crimes_chicago_2014 WHERE the_geom IS NOT NULL ``` -------------------------------- ### Truncate dates using date_trunc_y Source: https://dev.socrata.com/docs/transforms/date_trunc_y.html Examples of truncating fixed and floating timestamps to the start of the year. ```SQL date_trunc_y(to_fixed_timestamp('2017-12-13T00:24:53Z')) -- Result: "2017-01-01T00:00:00Z" date_trunc_y(to_floating_timestamp('2017-12-13T00:24:53Z')) -- Result: "2017-01-01T00:00:00" date_trunc_y(to_fixed_timestamp('2017-12-31T23:24:53-0930')) -- Result: "2018-01-01T00:00:00Z" ``` -------------------------------- ### Generate Documentation Source: https://dev.socrata.com/libraries/python-socrata-py.html Generate project documentation using the make command. ```bash make docs ``` -------------------------------- ### Usage examples for region_code_label Source: https://dev.socrata.com/docs/transforms/region_code_label.html Demonstrates how to call the function with different region identifiers and the resulting outputs. ```SQL region_code_label(make_point(2, 3), 'hehe-hehe', 'columnName') -- Result: "7" region_code_label(make_point(2, 3), 'forbidden-view', 'columnName') -- Result: {"type":"region_coding_error","english":"Failed to Region Code that value; You don't have permission to region code against that dataset","data":{"message":"You don't have permission to region code against that dataset"}} region_code_label(make_point(2, 3), 'no-match', 'columnName') -- Result: {"type":"empty_region_code","english":"Region Coder said that point does not fall within any region","data":{}} ``` -------------------------------- ### Build Project with Maven Source: https://dev.socrata.com/libraries/datasync.html Use this command to clean and install the project dependencies using Apache Maven. Ensure you have an 'api-key.txt' file in the root directory. ```bash mvn clean install ``` -------------------------------- ### Generate a within_box() query with Leaflet.js Source: https://dev.socrata.com/blog Example of generating a within_box() query using Leaflet.js. No specific setup or imports are mentioned. ```javascript var query = new Socrata.SqlQuery() .within_box(column_name, south, west, north, east); ``` -------------------------------- ### Filter Aggregated Results in SoQL Source: https://dev.socrata.com/docs/queries/query.html Use the HAVING clause to filter the results of a GROUP BY aggregation. This example gets sources with more than 500 quakes. ```sql SELECT `source`, count(*) as `count` GROUP BY `source` HAVING `count` > 500 ``` -------------------------------- ### Run Gradle Tasks Source: https://dev.socrata.com/libraries/android.html Commands for listing tasks, running tests, and installing the sample application. ```bash ./gradlew tasks ``` ```bash ./gradlew connectedCheck --info ``` ```bash ./gradlew installDebug ``` -------------------------------- ### Install SODA.NET via NuGet Source: https://dev.socrata.com/libraries/csharp.html Use the .NET CLI to add the SODA.NET package to your project. ```bash dotnet add package CSM.SodaDotNet ``` -------------------------------- ### Calculate Average with avg() in $select Source: https://dev.socrata.com/docs/functions/avg.html Use this function in $select aggregations to get the average of numeric values. For example, to fetch the average salary of all employees at the City of Chicago. ```socrata-api SELECT avg(salary) FROM city_of_chicago ``` -------------------------------- ### Initialize Libraries and Environment Source: https://dev.socrata.com/blog/2016/05/03/natural-language-with-sodapy-and-algorithmia.html Imports necessary modules and configures the plotting environment for iPython notebooks. ```python from userConfig import socrataClient, algoKey import Algorithmia import matplotlib.pyplot as plt import seaborn as sns sns.set(color_codes=True) %matplotlib notebook # Show the plots in the iPython notebook ``` -------------------------------- ### Initialize SODA Client Source: https://dev.socrata.com/2014/03/26/ruby-upsert.html Create a client instance using HTTP Basic Authentication and an application token. ```ruby require 'soda/client' client = SODA::Client.new({:domain => "soda.demo.socrata.com", :username => "demouser@example.com", :password => "my_demo_user_password", :app_token => "CGxadgoQlgQSev4zyUh5aR5J3"}) ``` -------------------------------- ### Extract Day of Week with date_extract_dow Source: https://dev.socrata.com/docs/functions/date_extract_dow.html Use date_extract_dow in $select, $where, or $group parameters to get the day of the week (0-6) from a floating timestamp. Example: date_extract_dow('2013-10-24T09:33:00.000') returns 4. ```sql date_extract_dow('2013-10-24T09:33:00.000') ``` ```sql date_extract_dow('2013-10-24T09:33:00.000') ``` -------------------------------- ### Get Minimum Salary using min() in $select Source: https://dev.socrata.com/docs/functions/min.html Use the min() function in a $select aggregation to retrieve the minimum numeric value from a dataset. This example shows how to find the lowest salary. ```socrata-api SELECT min(salary) FROM city_employees ``` -------------------------------- ### Create SODA Client Instance Source: https://dev.socrata.com/libraries/ruby.html Instantiate a new SODA client by providing your domain and application token. Register for an application token at http://dev.socrata.com/register. ```ruby client = SODA::Client.new({:domain => "explore.data.gov", :app_token => "CGxadgoQlgQSev4zyUh5aR5J3"}) ``` -------------------------------- ### Import and Initialize Socrata Client Source: https://dev.socrata.com/libraries/python-sodapy.html Import the Socrata library and set up a connection to the Socrata API. Include username and password for data modification operations. An application token is recommended to avoid strict throttling. ```python from sodapy import Socrata client = Socrata( "sandbox.demo.socrata.com", "FakeAppToken", username="fakeuser@somedomain.com", password="mypassword", timeout=10 ) ``` -------------------------------- ### Calculate Average by Group with avg() in $group Source: https://dev.socrata.com/docs/functions/avg.html This function can be used in $group aggregations to calculate the average of a numeric column, grouped by another column. For example, to get the average salary by job type. ```socrata-api SELECT job_type, avg(salary) FROM city_of_chicago GROUP BY job_type ``` -------------------------------- ### Using OFFSET for Pagination Source: https://dev.socrata.com/docs/queries/offset.html Illustrates how to use the OFFSET parameter to retrieve a specific page of records when $limit is used for pagination. For example, to get the 4th page of 50 records, an OFFSET of 150 is required. ```text OFFSET 150 ``` -------------------------------- ### Create Dataset Shortcut Source: https://dev.socrata.com/libraries/python-socrata-py.html Create a dataset and apply the revision in one workflow. ```python (revision, output_schema) Socrata(auth).create( name = "cool dataset", description = "a description" ).csv(file) job = revision.apply(output_schema = output_schema) ``` ```python Socrata(auth).create( name = "cool dataset", description = "a description" ).csv(open('my-file.csv')) ``` -------------------------------- ### Get Minimum Salary by Job Type using min() in $group Source: https://dev.socrata.com/docs/functions/min.html Utilize the min() function within a $group aggregation to determine the minimum value for each group. This example finds the minimum salary for each job type. ```socrata-api SELECT job_type, min(salary) FROM city_employees GROUP BY job_type ``` -------------------------------- ### Create a new dataset Source: https://dev.socrata.com/libraries/python-sodapy.html Initializes a new dataset with specified metadata, columns, and configuration options. ```python >>> columns = [{"fieldName": "delegation", "name": "Delegation", "dataTypeName": "text"}, {"fieldName": "members", "name": "Members", "dataTypeName": "number"}] >>> tags = ["politics", "geography"] >>> client.create("Delegates", description="List of delegates", columns=columns, row_identifier="delegation", tags=tags, category="Transparency") {u'id': u'2frc-hyvj', u'name': u'Foo Bar', u'description': u'test dataset', u'publicationStage': u'unpublished', u'columns': [ { u'name': u'Foo', u'dataTypeName': u'text', u'fieldName': u'foo', ... }, { u'name': u'Bar', u'dataTypeName': u'number', u'fieldName': u'bar', ... } ], u'metadata': { u'rowIdentifier': 230641051 }, ... } ``` -------------------------------- ### Initialize Ember Project Source: https://dev.socrata.com/blog/2016/06/30/quickly-building-an-ember-app-backed-by-socrata-open-data.html Use Ember CLI to create a new Ember.js project. This command sets up the project structure and installs initial dependencies. ```bash $ ember new cta-ridership ``` -------------------------------- ### Install RSocrata package Source: https://dev.socrata.com/foundry/data.ct.gov/v4tt-nt9n Command to install the RSocrata package for R. ```r ## Install the required package with: ``` -------------------------------- ### Create a Dataset from a File Source: https://dev.socrata.com/libraries/python-socrata-py.html Upload a file and apply transformations to the dataset schema before finalizing the revision. ```python with open('cool_dataset.csv', 'rb') as file: # Upload + Transform step # revision is the *change* to the view in the catalog, which has not yet been applied. # output is the OutputSchema, which is a change to data which can be applied via the revision (revision, output) = Socrata(auth).create( name = "cool dataset", description = "a description" ).csv(file) # Transformation step # We want to add some metadata to our column, drop another column, and add a new column which will # be filled with values from another column and then transformed output = output\ .change_column_metadata('a_column', 'display_name').to('A Column!')\ .change_column_metadata('a_column', 'description').to('Here is a description of my A Column')\ .drop_column('b_column')\ .add_column('a_column_squared', 'A Column, but times itself', 'to_number(`a_column`) * to_number(`a_column`)', 'this is a column squared')\ .run() # Validation of the results step output = output.wait_for_finish() # The data has been validated now, and we can access errors that happened during validation. For example, if one of the cells in `a_column` couldn't be converted to a number in the call to `to_number`, that error would be reflected in this error_count assert output.attributes['error_count'] == 0 # If you want, you can get a csv stream of all the errors errors = output.schema_errors_csv() for line in errors.iter_lines(): print(line) # Update step # Apply the revision - this will make it public and available to make # visualizations from job = revision.apply(output_schema = output) # This opens a browser window to your revision, and you will see the progress # of the job revision.open_in_browser() # Application is async - this will block until all the data # is in place and readable job.wait_for_finish() ``` -------------------------------- ### Run Tests Source: https://dev.socrata.com/libraries/csharp.html Execute the test suite using the .NET CLI. ```bash dotnet test ``` -------------------------------- ### Include Source Files Source: https://dev.socrata.com/libraries/ios.html Reference the SODAClient source directory. ```text [SODAClient]() ``` -------------------------------- ### Install Pacman package manager Source: https://dev.socrata.com/blog/2015/05/20/data-visualisation-with-R.html Installs the Pacman package for managing other R packages. ```R install.packages("pacman") ``` -------------------------------- ### Initialize SODAClient Source: https://dev.socrata.com/libraries/swift.html Initialize a SODAClient with your domain and app's access token. This is the first step to interacting with Socrata OpenData servers. ```swift let client = SODAClient(domain: "(Domain name of the server)", token: "(Your app's access token)") ``` ```swift let client = SODAClient(domain: "data.cityofchicago.org", token: "Uo25eXiX14zEd2K6EKAkeMIDW") ``` -------------------------------- ### Fixed Timestamp Example Source: https://dev.socrata.com/docs/datatypes/fixed_timestamp.html An example of a fixed timestamp value in ISO8601 format with a UTC offset. ```json [ { "date_time_column": "2014-10-13T00:00:00.000Z" } ] ``` -------------------------------- ### Initialize Google Map Source: https://dev.socrata.com/blog/2014/05/31/google-maps.html Sets up the map instance centered on specific coordinates. ```javascript // Intialize our map var center = new google.maps.LatLng(41.7656874,-72.680087); var mapOptions = { zoom: 8, center: center } var map = new google.maps.Map(document.getElementById("map"), mapOptions); ``` -------------------------------- ### Usage examples for the least function Source: https://dev.socrata.com/docs/transforms/least.html Demonstrates how the function handles numeric arguments, null values, and all-null inputs. ```Socrata least(5, 4, 3, 2, 1) -- Result: "1" least(4, 1, null, 3, 6) -- Result: "1" least(null, null, null) -- Result: null ``` -------------------------------- ### Update Dataset License with Java Source: https://dev.socrata.com/libraries/java.html Load a dataset's information and use the `setupLicense` method on `DatasetInfo` to set its license. ```java SodaImporter importer = SodaImporter.newImporter("https://data.agency.gov", "you@agency.gov", "yoursupersecurepassword", APP_TOKEN); DatasetInfo di = importer.loadDatasetInfo("abcd-1234"); // LicenseInfo contains the licenses you can select from di.setupLicense(LicenseInfo.ccAttribution_3_0, "Department of Redundancy Department", "http://drd.agency.gov"); importer.updateDatasetInfo(di); ``` -------------------------------- ### Release Package Source: https://dev.socrata.com/libraries/python-socrata-py.html Commands to build and upload a distribution package. ```bash python3 setup.py sdist twine upload dist/ ``` -------------------------------- ### Chaining Query Options Source: https://dev.socrata.com/libraries/swift.html Demonstrates how to chain multiple query options like filtering and ordering to construct complex queries. This promotes clean and maintainable code. ```swift let fuelLocations = client.queryDataset("alternative-fuel-locations") let userWantsNaturalGas = true // Get this from the UI let stations = fuelLocations.filterColumn("fuel_type_code", userWantsNaturalGas ? "CNG" : "ELEC") let userWantsAscending = true // Get this from the UI let orderedStations = userWantsAscending ? stations.orderAscending("station_name") : stations.orderDescending("station_name") orderedStations.get { result in // Display the data or the error } ``` -------------------------------- ### Repair Geometry Examples Source: https://dev.socrata.com/docs/transforms/repair_geometry.html Examples showing how repair_geometry handles various invalid polygon, multipolygon, line, and multiline inputs. ```sql repair_geometry(to_polygon('POLYGON ((30 20, 45 40, 10 40, 30 20))')) -- Result: {"type":"Polygon","coordinates":[[[30,20],[45,40],[10,40],[30,20]]]} ``` ```sql repair_geometry(to_polygon('POLYGON ((30 20, 45 40, 10 40, 20 20))')) -- Result: {"type":"Polygon","coordinates":[[[30,20],[45,40],[10,40],[20,20],[30,20]]]} ``` ```sql repair_geometry(to_multipolygon('MULTIPOLYGON (((30 20, 45 40, 10 40, 30 20)))')) -- Result: {"type":"MultiPolygon","coordinates":[[[[30,20],[45,40],[10,40],[30,20]]]]} ``` ```sql repair_geometry(to_multipolygon('MULTIPOLYGON (((30 20, 45 40, 10 40, 20 20)))')) -- Result: {"type":"MultiPolygon","coordinates":[[[[30,20],[45,40],[10,40],[20,20],[30,20]]]]} ``` ```sql repair_geometry(to_polygon('POLYGON ((30 20))')) -- Result: {"type":"Polygon","coordinates":[[[30,20],[30,20],[30,20],[30,20]]]} ``` ```sql repair_geometry(to_multipolygon('MULTIPOLYGON (((30 20)))')) -- Result: {"type":"MultiPolygon","coordinates":[[[[30,20],[30,20],[30,20],[30,20]]]]} ``` ```sql repair_geometry(to_line('LINESTRING (30 10)')) -- Result: {"type":"LineString","coordinates":[[30,10],[30,10]]} ``` ```sql repair_geometry(to_multiline('MULTILINESTRING ((10 10),(40 40, 30 30))')) -- Result: {"type":"MultiLineString","coordinates":[[[10,10],[10,10]],[[40,40],[30,30]]]} ``` -------------------------------- ### Initialize SODAConsumer Source: https://dev.socrata.com/libraries/android.html Create a consumer instance using your Socrata domain and API token. ```java Consumer consumer = new Consumer("soda.demo.socrata.com", "YOUR_TOKEN"); ``` -------------------------------- ### Socrata API Setup Source: https://dev.socrata.com/libraries/julia.html Define the Socrata API URL and your application token before making requests. Replace 'your_app_token_goes_here' with your actual token. ```julia using Socrata url = "http://soda.demo.socrata.com/resource/4334-bgaj" token = "your_app_token_goes_here" ``` -------------------------------- ### GET /api/v3/views/hvv9-38ut/query.json Source: https://dev.socrata.com/foundry/data.cityofchicago.org/hvv9-38ut Retrieves bike route data from the Chicago dataset. While GET is supported, POST is recommended for complex queries. ```APIDOC ## GET /api/v3/views/hvv9-38ut/query.json ### Description Retrieves bike route data from the Chicago dataset. Supports JSON, XML, and CSV formats. ### Method GET ### Endpoint https://data.cityofchicago.org/api/v3/views/hvv9-38ut/query.json ### Parameters #### Query Parameters - **pageNumber** (integer) - Optional - The page number to retrieve. - **pageSize** (integer) - Optional - The number of rows per page. - **app_token** (string) - Optional - Application token for higher throttling limits. ### Request Example https://data.cityofchicago.org/api/v3/views/hvv9-38ut/query.json?pageNumber=1&pageSize=10&app_token=$YOUR_APP_TOKEN ``` -------------------------------- ### Initialize SODAConsumer Source: https://dev.socrata.com/libraries/ios.html Create a consumer instance using your Socrata domain and API token. ```objective-c SODAConsumer *consumer = [SODAConsumer consumerWithDomain:@"soda.demo.socrata.com" token:@"YOUR_TOKEN"]; ``` -------------------------------- ### Point Datatype - GeoJSON and WKT Examples Source: https://dev.socrata.com/docs/datatypes/point.html Examples of how the Point datatype is represented in GeoJSON and Well Known Text (WKT) formats. ```APIDOC ## Point Datatype Representation ### Description The `Point` datatype represents a location on Earth as a WGS84 Latitude and Longitude. It is encoded as a GeoJSON "point" or in Well Known Text (WKT) format. ### GeoJSON Example ```json { "type": "Point", "coordinates": [ -87.653274, 41.936172 ] } ``` ### Well Known Text (WKT) Example ``` POINT (-87.653274 41.936172) ``` ### Coordinate Ordering Note Contrary to the normal convention of "latitude, longitude" ordering in the `coordinates` property, GeoJSON and Well Known Text order the coordinates as "longitude, latitude" (X coordinate, Y coordinate). This is consistent with other GIS coordinate systems. However, SoQL `within_box` and `within_circle` functions use the conventional "latitude, longitude" ordering. ``` -------------------------------- ### Initialize and Train Prophet Model Source: https://dev.socrata.com/files/20191007.socrata-time-series-prophet.ipynb Prepare data by renaming the count column to 'y' and creating a 'ds' column for timestamps. Then, initialize and train a Prophet model for forecasting. ```python from fbprophet import Prophet model = Prophet() train_df = data_df.rename(columns={"count":'y'}) ``` -------------------------------- ### MultiPolygon GeoJSON Example Source: https://dev.socrata.com/docs/datatypes/multipolygon.html An example of a MultiPolygon datatype represented in GeoJSON format. Note the 'longitude, latitude' ordering within the coordinates. ```APIDOC ## MultiPolygon GeoJSON Example ### Description This is an example of a MultiPolygon datatype in GeoJSON format, which can represent polygons with holes or multiple disconnected polygons. ### Request Body ```json { "type": "MultiPolygon", "coordinates": [ [[[102.0, 2.0], [103.0, 2.0], [103.0, 3.0], [102.0, 3.0], [102.0, 2.0]]], [[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]], [[100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]]] ] } ``` ### Note on Coordinate Ordering GeoJSON orders coordinates as "longitude, latitude" (X coordinate, Y coordinate), which is contrary to the common "latitude, longitude" convention. However, SoQL functions like `within_box` and `within_circle` use the conventional ordering. ``` -------------------------------- ### POST /configs/create Source: https://dev.socrata.com/libraries/python-socrata-py.html Creates a new ImportConfig. ```APIDOC ## POST /configs/create ### Description Create a new ImportConfig. ### Parameters #### Request Body - **name** (string) - Required - **data_action** (string) - Required - **parse_options** (object) - Required - **columns** (array) - Required ``` -------------------------------- ### Install ember-socrata and Dependencies Source: https://dev.socrata.com/blog/2016/06/30/quickly-building-an-ember-app-backed-by-socrata-open-data.html Install the ember-socrata addon along with its required dependencies, ember-browserify and soda-js. These are necessary for the addon to function correctly. ```bash $ ember install ember-socrata $ ember install ember-browserify $ npm install --save-dev soda-js ``` -------------------------------- ### Retrieve Dataset Data Source: https://dev.socrata.com/libraries/SodaPhp.html Demonstrates initializing a client, defining a SOQL query, and fetching dataset results. ```php // Create a client with information about the API to handle tokens and authentication $sc = new SodaClient("opendata.socrata.com"); // Access a dataset based on the API end point $ds = new SodaDataset($sc, "pkfj-5jsd"); // Create a SoqlQuery that will be used to filter out the results of a dataset $soql = new SoqlQuery(); // Write a SoqlQuery naturally $soql->select("date_posted", "state", "sample_type") ->where("state = 'AR'") ->limit(1); // Fetch the dataset into an associative array $results = $ds->getDataset($soql); ``` -------------------------------- ### GET /api/datasets/{id}/metadata - Get dataset metadata Source: https://dev.socrata.com/libraries/powershell.html Retrieves the metadata for a specific Socrata dataset using its unique ID. ```APIDOC ## GET /api/datasets/{id}/metadata ### Description Retrieves the metadata for a specific Socrata dataset using its unique ID. ### Method GET ### Endpoint /api/datasets/{id}/metadata ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the dataset. #### Query Parameters None #### Request Body None ### Request Example ```powershell Import-Module "./Socrata-PowerShell/Socrata.psm1" Get-Metadata ` -Domain "data.example.gov" ` -DatasetId "prx6-94ku" ` -Credentials $Credentials ``` ### Parameters Details - **Domain** (string) - Required - The Socrata domain (e.g., "data.example.gov"). - **DatasetId** (string) - Required - The ID of the dataset whose metadata is to be retrieved. - **Credentials** (object) - Optional - Credentials object for authentication. If not supplied, it's looked up from environment variables `SOCRATA_USERNAME` and `SOCRATA_PASSWORD`. ### Response #### Success Response (200) Returns a hashtable object containing the dataset's metadata. #### Response Example ```powershell @{ id = "prx6-94ku" name = "Gross Domestic Product by County, 2021" attribution = "Bureau of Economic Analysis (BEA)" customFields = @{ Department = @{ Name = "Economic Development" Office = "Office of Data and Performance" } } tags = @( "economic", "performance", "gdp", "counties" ) } ``` ``` -------------------------------- ### Use SODA.NET for .NET Applications Source: https://dev.socrata.com/foundry/embed-sample.html This C# snippet demonstrates using the SODA.NET client library to fetch data from Socrata. Install the CSM.SodaDotNet package from Nuget first. ```csharp using System; using System.Linq; // Install the package from Nuget first: // PM> Install-Package CSM.SodaDotNet using SODA; var client = new SodaClient("https://soda.demo.socrata.com", "YOURAPPTOKENHERE"); // Get a reference to the resource itself // The result (a Resouce object) is a generic type // The type parameter represents the underlying rows of the resource // and can be any JSON-serializable class var dataset = client.GetResource("4tka-6guv"); // Resource objects read their own data var rows = dataset.GetRows(limit: 5000); Console.WriteLine("Got {0} results. Dumping first results:", rows.Count()); foreach (var keyValue in rows.First()) { Console.WriteLine(keyValue); } ``` -------------------------------- ### Create a new upload source Source: https://dev.socrata.com/libraries/python-socrata-py.html Initializes a new source for a file upload. ```python upload = revision.create_upload('foo.csv') ``` -------------------------------- ### Filter Dataset with SoQL Source: https://dev.socrata.com/foundry/data.oregon.gov/yid5-c4eq Example URL demonstrating how to filter the dataset by the agency field using a SoQL query. ```text https://data.oregon.gov/api/v3/views/gs36-7t8m/query.json?pageNumber=1&pageSize=10&app_token=$YOUR_APP_TOKEN&query=SELECT%20*%20WHERE%20%60agency%60%3D'Health%20Authority%2C%20Oregon' ```