Function Doesn't Return a value in Dart Language - api

I am trying to connect my app to an API and search using the API. If the search is successful and found the name, it will return Success and if not, will return Failed, but it doesn't return anything.
import 'dart:convert';
import 'package:http/http.dart' as http;
main() {
getData();
}
String linearSearch(List<dynamic> list, String x) {
for (var i = 0; i < list.length; i++){
if(x == list[i]["name"]){
return 'Success';
}
}
return 'Failed';
}
void getData() async {
List data;
var response = await
http.get("http://localhost:3000/data");
data = jsonDecode(response.body);
linearSearch(data, 'karim');
}

Your function returns String value without any additions. You just need to assign result of your function to String variable and do something with it, if needed.
Or you just could print result of the function
void getData() async {
List data;
var response = await
http.get("http://localhost:3000/data");
data = jsonDecode(response.body);
print(linearSearch(data, 'karim'));
}

Solved by editing my linearSearch function
linearSearch(List<dynamic> list, String x) {
for (var i = 0; i < list.length; i++){
if(x == list[i]["name"]){
return print('Success');
}
}
return print('Failed');
}

Related

Throwing an Exception In an Xss Attack

This is a Web API which Json payloads (so, no Razor).
I'm using ASP.NET Core 2.1
1st up I should mention that I am sanitizing the relevant inputs with HtmlEncoder. However, that is just in case any gets past my validator, which I want to ask about here.
I want to write a validator which will return an error code where a user tries to include an html string in an input (using a mobile app, which would be a property in the json payload).
I've seen some naive implementation suggestion here on SO - usually just checking to see of the string contains '<' or '>' (and maybe one or 2 other chars).
I guess I would like to know if that is sufficient for the task at hand. There's no reason for a user to post any kind of html/xml in this domain.
A lot of the libraries around will sanitize input. But none of them seem to have a method which tells you if a string contains potentially harmful input.
As I said, I'm already sanitizing (as a last line of defence). But ideally I would return an error code before it gets to that.
Use this class from Microsoft ASP.NET Core 1
// <copyright file="CrossSiteScriptingValidation.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
public static class CrossSiteScriptingValidation
{
private static readonly char[] StartingChars = { '<', '&' };
#region Public methods
// Only accepts http: and https: protocols, and protocolless urls.
// Used by web parts to validate import and editor input on Url properties.
// Review: is there a way to escape colon that will still be recognized by IE?
// %3a does not work with IE.
public static bool IsDangerousUrl(string s)
{
if (string.IsNullOrEmpty(s))
{
return false;
}
// Trim the string inside this method, since a Url starting with whitespace
// is not necessarily dangerous. This saves the caller from having to pre-trim
// the argument as well.
s = s.Trim();
var len = s.Length;
if ((len > 4) &&
((s[0] == 'h') || (s[0] == 'H')) &&
((s[1] == 't') || (s[1] == 'T')) &&
((s[2] == 't') || (s[2] == 'T')) &&
((s[3] == 'p') || (s[3] == 'P')))
{
if ((s[4] == ':') || ((len > 5) && ((s[4] == 's') || (s[4] == 'S')) && (s[5] == ':')))
{
return false;
}
}
var colonPosition = s.IndexOf(':');
return colonPosition != -1;
}
public static bool IsValidJavascriptId(string id)
{
return (string.IsNullOrEmpty(id) || System.CodeDom.Compiler.CodeGenerator.IsValidLanguageIndependentIdentifier(id));
}
public static bool IsDangerousString(string s, out int matchIndex)
{
//bool inComment = false;
matchIndex = 0;
for (var i = 0; ;)
{
// Look for the start of one of our patterns
var n = s.IndexOfAny(StartingChars, i);
// If not found, the string is safe
if (n < 0) return false;
// If it's the last char, it's safe
if (n == s.Length - 1) return false;
matchIndex = n;
switch (s[n])
{
case '<':
// If the < is followed by a letter or '!', it's unsafe (looks like a tag or HTML comment)
if (IsAtoZ(s[n + 1]) || s[n + 1] == '!' || s[n + 1] == '/' || s[n + 1] == '?') return true;
break;
case '&':
// If the & is followed by a #, it's unsafe (e.g. S)
if (s[n + 1] == '#') return true;
break;
}
// Continue searching
i = n + 1;
}
}
#endregion
#region Private methods
private static bool IsAtoZ(char c)
{
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
#endregion
}
Then use this middleware to control URL,Query Parameteres and Content:
public class XssMiddleware
{
private readonly RequestDelegate _next;
public XssMiddleware(RequestDelegate next)
{
if (next == null)
{
throw new ArgumentNullException(nameof(next));
}
_next = next;
}
public async Task Invoke(HttpContext context)
{
// Check XSS in URL
if (!string.IsNullOrWhiteSpace(context.Request.Path.Value))
{
var url = context.Request.Path.Value;
int matchIndex;
if (CrossSiteScriptingValidation.IsDangerousString(url, out matchIndex))
{
throw new CrossSiteScriptingException("YOUR_ERROR_MESSAGE");
}
}
// Check XSS in query string
if (!string.IsNullOrWhiteSpace(context.Request.QueryString.Value))
{
var queryString = WebUtility.UrlDecode(context.Request.QueryString.Value);
int matchIndex;
if (CrossSiteScriptingValidation.IsDangerousString(queryString, out matchIndex))
{
throw new CrossSiteScriptingException("YOUR_ERROR_MESSAGE");
}
}
// Check XSS in request content
var originalBody = context.Request.Body;
try
{
var content = await ReadRequestBody(context);
int matchIndex;
if (CrossSiteScriptingValidation.IsDangerousString(content, out matchIndex))
{
throw new CrossSiteScriptingException("YOUR_ERROR_MESSAGE");
}
await _next(context);
}
finally
{
context.Request.Body = originalBody;
}
}
private static async Task<string> ReadRequestBody(HttpContext context)
{
var buffer = new MemoryStream();
await context.Request.Body.CopyToAsync(buffer);
context.Request.Body = buffer;
buffer.Position = 0;
var encoding = Encoding.UTF8;
var contentType = context.Request.GetTypedHeaders().ContentType;
if (contentType?.Charset != null) encoding = Encoding.GetEncoding(contentType.Charset);
var requestContent = await new StreamReader(buffer, encoding).ReadToEndAsync();
context.Request.Body.Position = 0;
return requestContent;
}
}

How do I use a script to fill-color-yellow all of certain numbers I choose in google sheets?

I want to fill-color-yellow all of the prime numbers (within a certain range) in a google spreadsheet that I am working on. I don't even know where to begin.
function isPrime(value) {
for(var i = 2; i < value; i++) {
if(value % i === 0) {
return false;
}
}
return value > 1;
}
function testcolorPrimes()
{
colorPrimes('#ffff00');
}
function colorPrimes(color)
{
var ss=SpreadsheetApp.getActiveSpreadsheet();
var sht=ss.getSheetByName('colorprimes');
var rng=sht.getDataRange();
var rngA=rng.getValues();
for(var i=0;i<rngA.length;i++)
{
for(var j=0;j<rngA[i].length;j++)
{
if(!isNaN(rngA[i][j]))
{
if(isPrime(rngA[i][j]))
{
var range = sht.getRange(i+1, j+1).setBackground(color);
}
}
}
}
SpreadsheetApp.flush();
}

managed c++ classes crash in create_task

Basically, what is happening is when trying to change a variable of a Managed class (UWP), it crashes. Additionally, it seems to only crash if I try modifying a variable which is created with the app namespace. In other words, if I create a new namspace and managed class, I can modify variables just fine.
void ASynTaskCategories(void)
{
concurrency::task_completion_event<Platform::String^> taskDone;
MainPage^ rootPage = this;
UberSnip::HELPER::ASYNC_RESPONSE^ responseItem = ref new UberSnip::HELPER::ASYNC_RESPONSE();
create_task([taskDone, responseItem, rootPage]() -> Platform::String^
{
//UBERSNIP API 0.4
UberSnip::UBERSNIP_CLIENT* UberSnipAPI = new UberSnip::UBERSNIP_CLIENT();
UberSnipAPI->Http->RequestURL = "http://api.ubersnip.com/categories.php";
UberSnipAPI->Http->request();
taskDone.set(UberSnipAPI->Client->BodyResponse);
responseItem->Body = UberSnipAPI->Client->BodyResponse;
return "(done)";
}).then([taskDone, responseItem, rootPage](Platform::String^ BodyResponse) {
Platform::String^ BR = responseItem->Body;
cJSON* cats = cJSON_Parse(_string(BR));
cats = cats->child;
int *cat_count = new int(cJSON_GetArraySize(cats));
rootPage->Categories->Clear();
GENERIC_ITEM^ all_item = ref new GENERIC_ITEM();
all_item->Title = "All";
rootPage->Categories->Append(all_item);
for (int i = 0; i < *cat_count; i++) {
cJSON* cat = new cJSON();
cat = cJSON_GetArrayItem(cats, i);
string *track_title = new string(cJSON_GetObjectItem(cat, "name")->valuestring);
GENERIC_ITEM gitem;
gitem.Title = "Hi";
GENERIC_ITEM^ ubersnipCategory = ref new GENERIC_ITEM();
ubersnipCategory->Title = _String(*track_title);
rootPage->Categories->Append(ubersnipCategory);
}
});
This does not crash
UberSnipAPI->Http->RequestURL = "http://api.ubersnip.com/categories.php";
but this one does
all_item->Title = "All";
I am almost positive it has something to do with it being in the apps default namespace and it being accessed outside of the main thread ... At least that's what it seems like as that's really the only difference besides the actual class.
This is what GENERIC_ITEM looks like.
[Windows::UI::Xaml::Data::Bindable]
public ref class GENERIC_ITEM sealed {
private:
Platform::String^ _title = "";
Platform::String^ _description;
Windows::UI::Xaml::Media::ImageSource^ _Image;
event PropertyChangedEventHandler^ _PropertyChanged;
void OnPropertyChanged(Platform::String^ propertyName)
{
PropertyChangedEventArgs^ pcea = ref new PropertyChangedEventArgs(propertyName);
_PropertyChanged(this, pcea);
}
public:
GENERIC_ITEM() {
};
property Platform::String^ Title {
Platform::String^ get() {
return this->_title;
}
void set(Platform::String^ val) {
this->_title = val;
OnPropertyChanged("Title");
}
}
property Platform::String^ Description {
Platform::String^ get() {
return this->_description;
}
void set(Platform::String^ val) {
this->_description = val;
OnPropertyChanged("Description");
}
}
void SetImage(Platform::String^ path)
{
Windows::Foundation::Uri^ uri = ref new Windows::Foundation::Uri(path);
_Image = ref new Windows::UI::Xaml::Media::Imaging::BitmapImage(uri);
}
};
I know there is no issue with the class because it works perfectly fine if I run this exact same code on the initial thread.
Any suggestions? Thanks! :D
Figured it out after several hours! In case someone else is having this issue, all you must do is use the Dispatcher to run code on the UI that is not available outside of the UI thread.
void loadCats(UberSnip::HELPER::ASYNC_RESPONSE^ responseItem, MainPage^ rootPage) {
Platform::String^ BR = responseItem->Body;
cJSON* cats = cJSON_Parse(_string(BR));
cats = cats->child;
int *cat_count = new int(cJSON_GetArraySize(cats));
rootPage->Categories->Clear();
GENERIC_ITEM^ all_item = ref new GENERIC_ITEM();
all_item->Title = "All";
rootPage->Categories->Append(all_item);
for (int i = 0; i < *cat_count; i++) {
cJSON* cat = new cJSON();
cat = cJSON_GetArrayItem(cats, i);
string *track_title = new string(cJSON_GetObjectItem(cat, "name")->valuestring);
GENERIC_ITEM gitem;
gitem.Title = "Hi";
GENERIC_ITEM^ ubersnipCategory = ref new GENERIC_ITEM();
ubersnipCategory->Title = _String(*track_title);
rootPage->Categories->Append(ubersnipCategory);
}
}
void ASyncTaskCategories(void)
{
concurrency::task_completion_event<Platform::String^> taskDone;
MainPage^ rootPage = this;
UberSnip::HELPER::ASYNC_RESPONSE^ responseItem = ref new UberSnip::HELPER::ASYNC_RESPONSE();
auto dispatch = CoreWindow::GetForCurrentThread()->Dispatcher;
auto op2 = create_async([taskDone, responseItem, rootPage, dispatch] {
return create_task([taskDone, responseItem, rootPage, dispatch]() -> Platform::String^
{
//UBERSNIP API 0.4
UberSnip::UBERSNIP_CLIENT* UberSnipAPI = new UberSnip::UBERSNIP_CLIENT();
UberSnipAPI->Http->RequestURL = "http://api.ubersnip.com/categories.php";
try{
UberSnipAPI->Http->request();
}
catch (...) {
printf("Error");
}
int err = UberSnip::UTILS::STRING::StringToAscIIChars(UberSnipAPI->Client->BodyResponse).find("__api_err");
if (err < 0) {
if (UberSnip::UTILS::STRING::StringToAscIIChars(UberSnipAPI->Client->BodyResponse).length() < 3) {
return;
}
}
taskDone.set(UberSnipAPI->Client->BodyResponse);
responseItem->Body = UberSnipAPI->Client->BodyResponse;
dispatch->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([=]()
{
rootPage->loadCats(responseItem, rootPage);
}));
for (int i = 0; i < 100;) {
}
return "(done)";
}).then([taskDone, responseItem, rootPage](Platform::String^ BodyResponse) {
});
});
//rootPage->loadCats(responseItem, rootPage);
}

Get List of artifacts in an Ivy Repositoty

I manage an Ivy repository with an extensive number of artifacts and i have been requested to list all third party librarys which we have a hundred odd. does anyone know of a a way to retrieve a list of artifacts from an ivy repo?
i found no such way to do this, i wrote a script in java to get the results, thought i might share the answer if people wanted it in the future, it is also formatted to be copied straight into an excel document.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
public class ListArtifacts {
public static void main(String[] args) {
Collection<File> all = new ArrayList<File>();
addTree(new File("."), all);
String delimeter = "\\.";
List<String> remove = new ArrayList<String>();
List<String> everything = new ArrayList<String>();
remove.add("pom");
remove.add("jar");
remove.add("xml");
remove.add("txt");
remove.add("sha1");
remove.add("md5");
remove.add("metadata");
remove.add("tar");
remove.add("gz");
remove.add("zip");
remove.add("rar");
FileWriter fWriter = null;
BufferedWriter writer = null;
try {
fWriter = new FileWriter("info.txt");
writer = new BufferedWriter(fWriter);
Iterator itr = all.iterator();
while (itr.hasNext() == true){
String[] split;
String temp = itr.next().toString();
split = temp.split(delimeter);
int i = 0;
int j = 0;
boolean flag = false;
while (i < split.length){
while (j < remove.size()){
if (split[i].equals(remove.get(j))){
flag = true;
}
j++;
}
j = 0;
i++;
}
if (flag == false){
String output = "";
int k=0;
boolean flag2 = false;
boolean hasVersion = false;
while (k < split.length){
if (flag2 == true){
output += ".";
flag2 = false;
}
output = output + split[k].toString();
boolean lastInt = false;
try{
String last = split[k].substring(split[k].length() - 1);
if (isInteger(last) == true)
lastInt = true;
}catch(Exception e){}
if ((isInteger(split[k].toString()) == true) || (lastInt == true)){
flag2 = true;
hasVersion = true;
}
k++;
}
if (hasVersion == true){
everything.add(output.substring(1));
writer.append(output.substring(1));
writer.newLine();
}
}
}
int i = 0;
String delim = "\\\\";
String finalOutput = "";
String toSplit = "";
while (i < everything.size()){
toSplit = everything.get(i);
String[] split2 = toSplit.split(delim);
finalOutput = split2[0] + "\t";
int j = 1;
while (j < split2.length-2){
finalOutput += split2[j] + ".";
j++;
}
finalOutput += split2[split2.length-2] + "\t";
finalOutput += split2[split2.length-1];
writer.append(finalOutput);
writer.newLine();
i++;
}
writer.close();
} catch (Exception e) {
}
System.out.println(all);
}
public static boolean isInteger(String input )
{
try
{
Integer.parseInt(input);
return true;
}
catch(Exception e)
{
return false;
}
}
static void addTree(File file, Collection<File> all) {
File[] children = file.listFiles();
if (children != null) {
for (File child : children) {
all.add(child);
addTree(child, all);
}
}
}
}
im sure this can be done much more cleanly, but i did no higher thinking just did the first thing i thought of with no revision.
If you are looking to do this using ivy during a build, the report task should help you get a report of all the JARs you are using.
If you are trying to fetch these details from the repository manager (covering all possible users), could you answer the question from #oers? Repository managers often offer some API that you can use to get reports about the artifacts that they store.

How to write a custom FindElement routine in Selenium?

I'm trying to figure out how to write a custom FindElement routine in Selenium 2.0 WebDriver. The idea would be something like this:
driver.FindElement(By.Method( (ISearchContext) => {
/* examine search context logic here... */ }));
The anonymous method would examine the ISearchContext and return True if it matches; False otherwise.
I'm digging through the Selenium code, and getting a bit lost. It looks like the actual By.* logic is carried out server-side, not client side. That seems to be complicating matters.
Any suggestions?
I do a multi-staged search. I have a method that performs a try catch and then a method that gets the element. In theory you could do a try catch until instead of this way but I like this way better because of my setup.
public bool CheckUntil(IWebDriver driver, string selectorType, string selectorInfo)
{
int Timer = 160;
bool itemFound = false;
for (int i = 0; i < Timer; i++)
if(itemFound)
{
i = 0
}
else
{
Thread.Sleep(500);
if(selectorType.ToLower() == "id" && TryCatch(driver, selectorType, selectorInfo))
{
if(driver.FindElement(By.Id(selectorInfo).Displayed)
{
itemFound = true;
}
}
else if(selectorType.ToLower() == "tagname" && TryCatch(driver, selectorType, selectorInfo))
{
if(driver.FindElement(By.TagName(selectorInfo).Displayed)
{
itemFound = true;
}
}
}
return itemFound;
}
Here's my try catch method you can add as many different types as you want id, cssselector, xpath, tagname, classname, etc.
public bool TryCatch(IWebDriver driver, string selectorType, string selectorInfo)
{
bool ElementFound = false;
try
{
switch(selectorType)
{
case "id":
driver.FindElement(By.Id(selectorInfo);
break;
case "tagname":
driver.FindElement(By.TagName(selectorInfo);
break;
}
ElementFound = truel
}
catch
{
ElementFound = false;
}
return ElementFound;
}
Ok, I figured out how to do this. I'm leveraging driver.ExecuteScript() to run custom js on the webdriver. It looks a bit like this:
function elementFound(elem) {
var nodeType = navigator.appName == ""Microsoft Internet
Explorer"" ? document.ELEMENT_NODE : Node.ELEMENT_NODE;
if(elem.nodeType == nodeType)
{
/* Element identification logic here */
}
else { return false; }
}
function traverseElement(elem) {
if (elementFound(elem) == true) {
return elem;
}
else {
for (var i = 0; i < elem.childNodes.length; i++) {
var ret = traverseElement(elem.childNodes[i]);
if(ret != null) { return ret; }
}
}
}
return traverseElement(document);