how to call two #GET function on android paging3 PagingSource - android-studio

I'm using paging3 with retrofit to retrieve articles from an Api so they will be displayed on two fragments, one for all articles and the second for searching for articles that meet a query.
How to use PagingSource to feed the two fragments, I think I should define two #GET functions and two PagingSource, but I'm wondering is this the right way.
this my api interface:
interface MyApi {
#GET("top-headlines")
suspend fun getArticles(
#Query("country") country: String = "us",
#Query("page") pageNumber: Int = 1,
#Query("pageSize") pageSize: Int = Constants.pageSize,
#Query("apiKey") apiKey: String = API_KEY
): NewsResponse
#GET("everything")
suspend fun searchForNews(
#Query("q") searchQuery:String,
#Query("page") pageNumber: Int=1,
#Query("apiKey") apiKey: String = API_KEY
):NewsResponse
}
in the PagingSource here is the response:
val response = api.getNews(pageNumber)
this work for me to get news and display them on the first fragment.
now I want to call the other function searchNews() when switching to the second fragment.

Related

CS1646 Keyword, identifier, or string expected after verbatim specifier: #

tables in my EntityFramework model are events, eventtypes, subevents, subeventtypes
using the MVC5 builders (right click on controllers, add, add controller) I created controllers and views for the last three tables without issue however when I create the controller and views for the events entity I produce the following errors
Keyword, identifier, or string expected after verbatim specifier: #
'EventType' is a type, which is not valid in the given context
the code that was generated in the event controller is
{
private Entities db = new Entities();
// GET: Events
public ActionResult Index()
{
var events = db.Events.Include(# => #.EventType); ERROR HERE
return View(events.ToList());
}
any help with this issue would be greatly appreciated
TIA
I experienced the same issue when using the "MVC Controller with views, using Entity Framework" template.
var #group = await _context.Groups
.Include(# => #.Company)
.FirstOrDefaultAsync(m => m.GroupId == id);
My workaround was simple to replace the # symbol with another character i.e. g
var #group = await _context.Groups
.Include(g => g.Company)
.FirstOrDefaultAsync(m => m.GroupId == id);

How to fix performance issue in azure search

I am implementing azure search in my application to provide autosuggestion feature like google, big, and amazon. I have implemented the same available github code using below URL.All is working fine but getting result in more than 1.5 second for each term of sentence.
https://github.com/Azure-Samples/search-dotnet-getting-started/tree/master/DotNetHowToAutocomplete
Currently I am using two indexes for searching and created in basic tier. Below is code
public ActionResult Suggest(bool highlights, bool fuzzy, string term)
{
InitSearch();
// Call suggest API and return results
SuggestParameters sp = new SuggestParameters()
{
UseFuzzyMatching = fuzzy,
Top = 5,
Filter="name eq 'testid'",
OrderBy=new List<string>() { "Date desc"}
};
if (highlights)
{
sp.HighlightPreTag = "<b>";
sp.HighlightPostTag = "</b>";
}
DocumentSuggestResult suggestResult = _indexClient1.Documents.Suggest(term, "index1",sp);
if (suggestResult.Results.Count<5)
{
SuggestParameters sp2 = new SuggestParameters()
{
UseFuzzyMatching = fuzzy,
Top = 5- suggestResult.Results.Count,
Filter = "Product eq 'PAAS'",
OrderBy = new List<string>() { "Count desc" }
};
if (highlights)
{
sp2.HighlightPreTag = "<b>";
sp2.HighlightPostTag = "</b>";
}
DocumentSuggestResult suggestResult2= _indexClient2.Documents.Suggest(term, "index2", sp2);
suggestResult.Results = suggestResult.Results.Union(suggestResult2.Results).Distinct().ToList();
// final = suggestResult.Results.GroupBy(s => s.Text, StringComparer.CurrentCultureIgnoreCase).ToList();
}
// Convert the suggest query results to a list that can be displayed in the client.
List<string> suggestions = suggestResult.Results.Select(x => x.Text).Distinct().ToList();
return new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = suggestions
};
}
To test it- when I am typing any word it's taking too much time in populating results around 1.5 to 1.8 seconds, it's working like other web app searchbox.
Timing I am checking using inspect element of chrome browser. Attaching sreenshot.see screenshot
Please suggest.
I answered a similar question on another post: Why is Azure Search taking 1400 miliiseconds to return query results for simple query
The main thing is, you shouldn't be using the Chrome timer to measure the performance of azure search. Use the "elapsed-time" field of the HTTP response you receive (take an average over multiple call), since it accurately tells you how much time was spent getting your results from azure search. The chrome timer can be affected by your network/machine configuration. If that doesn't help, you can follow the other tips I suggested in the post I linked above.

How to use a parameter from a follow-up intent within the Inline Editor in DialogFlow

I'm using the DialogFlow Inline Editor and I need to be able to provide different responses based on the specific values of a parameter within a follow up intent.
Via the UI, I am able to build a follow up intent and refer to an entity in the previous intent, but I can't set up logic based on specific values of that entity, which is why i need to be able to do this via the Online Editor.
Can someone show me an example of how to use an entity within a follow up intent via the Online Editor?
So far, I am able to output a context within a function (function 1 below), but i am unable to use an entity that was provided by the user within function 1 in a function 2 that uses a follow-up intent.
//function 1:
function fruit(agent) {
const fruit = agent.parameters.FruitValue
agent.add(`what fruit do you like`)
agent.setContext({ name: 'cherries-followup', lifespan: 2, parameters: {FruitValue: fruit}})}
//function 2:
function details(agent) {
const context = agent.getContext('cherries-followup');
const fruit = context.parameters.FruitValue;
agent.add(`Good to know you like ${fruit}!`);
}
intentMap.set('CherriesIntent', fruit);
intentMap.set('CherriesDetailIntent', details);
Picture of what I did via the UI which i would like to replicate in the Online Editor
Update (Solved):
I have now rewritten the code to be in line with the DF post (so that it is easier to debug: https://dialogflow.com/docs/getting-started/integrate-services)
function languageHandler(agent) {
const language_spoken = agent.parameters.language;
{agent.add(`Wow! Where did you learn ${language_spoken} and for how long?`);
agent.setContext({
name: 'languages-followup',
lifespan: 2,
parameters:{languages: language_spoken}
});
}
}
function languageCustomHandler(agent) {
const context = agent.getContext('languages-followup');
//const allContexts = agent.contexts; // [{ name: 'languages-followup', ...}]
const language_spoken = context.parameters.language;
const country = agent.parameters.country;
const duration = agent.parameters.duration;
agent.add(`Wow! So cool you learned ${language_spoken} in ${country} for about ${duration.amount} ${duration.unit}!`);
}
intentMap.set('Language', languageHandler);
intentMap.set('Language - custom', languageCustomHandler);
It works now, after making sure that the duration parameter value is either set to duration.original in the UI or after adding .amount and .unit to duration (otherwise you will get: "Wow! So cool you learned German in China for about [object Object]!" instead of "Wow! So cool you learned German in China for about 1 mo!
PARAMETER VALUE
country China
duration {"amount":1,"unit":"mo"}

ASP.NET MVC routing without controller or action name in URL

My URL structure is like http://website.com/city-state/category e.g. /miami-fl/restaurants or /los-angeles-ca/bars. In order to send it to the correct controller, I have a class derived from RouteBase, which splits the request path and figures out the city, state and category. This is working fine for incoming URLs.
public class LegacyUrlRoute : RouteBase
{
public override RouteData GetRouteData(HttpContextBase httpContext)
{
RouteData routeData = new RouteData();
routeData.RouteHandler = new MvcRouteHandler();
string url = httpContext.Request.Path.ToLower(); //e.g. url = /los-angeles
string[] path = url.TrimStart('/').Split('/'); //
if (path.Length > 1)
{
string[] locale = path[0].Split('-');
if (locale.Length > 1) //This is a city page, so send it to category controller
{
string stateName = locale[locale.Length - 1];
string cityName = path[0].Replace(stateName, "").TrimEnd('-');
routeData.Values.Add("controller", "Category");
routeData.Values.Add("action", "City");
routeData.Values.Add("categoryname", path[1]);
routeData.Values.Add("city", cityName);
routeData.Values.Add("state", stateName);
}
}
}
}
However, when I try to use Html.ActionLink to create a link, it doesn't pick up from this class.
#Html.ActionLink("Restaurants in Miami", "Index", "Category", new {categoryname="Restaurants", state="FL", city="Miami"})
gives me a url of /category/index?categoryname=restaurants&state=fl&city=miami.
How do I generate accurate links for my URL structure.
If you want your outgoing URLs to function, you must implement GetVirtualPath, which converts a set of route values into a URL. It should typically be the mirror image of your GetRouteData method.
The simplest way to implement it would just be to make a data structure that maps your route values to URLs and then use it in both methods as in this example.

What's the correct way to implement default properties when doing default implementation of protocols in Swift?

I am truly fascinated by the concept of Protocol-Oriented Programming in Swift, and because of that, I'm moving an old project I created last year (which was originally an OOP framework) to POP.
At this stage, the problems I'm having could be because I'm either understanding POP incorrectly, or the Swift 2.0 Betas don't have everything to create a truly Protocol-Oriented framework (not very likely - If anything I might be misunderstanding certain aspects of POP).
Protocol-Oriented Programming is a whole new programming paradigm introduced to the world less than a month ago, so there is not much written content about it (the only tutorial I found on the topic doesn't address the problem I'm having, and the WWDC video didn't either).
Anyway, to the point: I am either doing something wrong here, or one of the downsides of Protocol-Oriented Programming is that you are bound to repeat a lot of code. Case in point:
I have the following protocol that has many properties and also complies with the Equatable protocol:
protocol MediaType : Equatable {
/// MARK: - Properties
/// The ID of the media, as assigned by MyAnimeList.
var ID: Int { get }
/// The title of the media.
var title: String { get }
/// Other titles by which this anime may be commonly known (only available in details requests).
var otherTitles: (synonyms: [String], english: [String], japanese: [String])? { get }
/// The global ranking of the title (only available in anime details requests).
var rank: Int? { get }
/// Rank of the title based on popularity (number of people adding title to the list) (only available in details requests).
var popularityRank: Int? { get }
/// URL to a representative image of the title. Usually a "cover" image.
var imageURL: String { get }
/// A list of adaptations of this media, or other media on which this media is based (only available in details requests).
var adaptations: Relationships { get }
/// The user's rating of the media.
var memberScore: Float { get }
/// Number of MyAnimeList members that that added the title to their list (only available in details requests).
var membersCount: Int? { get }
/// The number of MyAnimeList members that have this title on their favorites list (only available in details requests).
var favoritedCount: Int? { get }
/// A short HTML-formatted description of the media.
var synopsis: String { get }
/// A list of genres for this title (only available in details requests).
var genres: [String]? { get }
/// Popular tags for the title as assigned by MyAnimeList members (only available in details requests).
var tags: [String] { get }
}
In the original version of my framework, this protocol was a class called Media, and two other classes inherited from it. So they got all those properties for free.
But it doesn't look like I can give my objects that comply with that protocol a default implementation (namely, getters) for those properties?
The first thing I tried, which is to simply give the protocol to my struct declaration, failed, which was to be expected as I wasn't providing any implementation for the properties:
struct Anime : MediaType {
/// MARK: - MediaType
}
/// Compares two Anime_ objects. Two Anime_ objects are considered equal when they have the same ID and title.
func ==(lhs: Anime, rhs: Anime) -> Bool {
return (lhs.ID == rhs.ID) && (lhs.title == rhs.title)
}
This fails with:
Type 'Anime' does not conform to protocol 'MediaType'
My next attempt was to write an extension for MediaType, and throw the properties there:
extension MediaType {
/// The ID of the media, as assigned by MyAnimeList.
let ID: Int
/// The title of the media.
let title: String
/// Other titles by which this anime may be commonly known (only available in details requests).
let otherTitles: (synonyms: [String], english: [String], japanese: [String])?
/// The global ranking of the title (only available in anime details requests).
let rank: Int?
/// Rank of the title based on popularity (number of people adding title to the list) (only available in details requests).
let popularityRank: Int?
/// URL to a representative image of the title. Usually a "cover" image.
let imageURL: String
/// A list of adaptations of this media, or other media on which this media is based (only available in details requests).
let adaptations: Relationships
/// The user's rating of the media.
let memberScore: Float
/// Number of MyAnimeList members that that added the title to their list (only available in details requests).
let membersCount: Int?
/// The number of MyAnimeList members that have this title on their favorites list (only available in details requests).
let favoritedCount: Int?
/// A short HTML-formatted description of the media.
let synopsis: String
/// A list of genres for this title (only available in details requests).
let genres: [String]?
/// Popular tags for the title as assigned by MyAnimeList members (only available in details requests).
let tags: [String]
}
This didn't work:
Extensions may not contain stored properties.
And it had the one downside that I really didn't like: I was already duplicating code, by copying the properties of the protocol into the extension.
So in the end, I could never get my properties to be "spread" to the objects conforming to the protocol, so I ended up adding the properties to the Anime struct.
struct Anime : MediaType {
/// MARK: - MediaType
/// The ID of the media, as assigned by MyAnimeList.
let ID: Int
/// The title of the media.
let title: String
/// Other titles by which this anime may be commonly known (only available in details requests).
let otherTitles: (synonyms: [String], english: [String], japanese: [String])?
/// The global ranking of the title (only available in anime details requests).
let rank: Int?
/// Rank of the title based on popularity (number of people adding title to the list) (only available in details requests).
let popularityRank: Int?
/// URL to a representative image of the title. Usually a "cover" image.
let imageURL: String
/// A list of adaptations of this media, or other media on which this media is based (only available in details requests).
let adaptations: Relationships
/// The user's rating of the media.
let memberScore: Float
/// Number of MyAnimeList members that that added the title to their list (only available in details requests).
let membersCount: Int?
/// The number of MyAnimeList members that have this title on their favorites list (only available in details requests).
let favoritedCount: Int?
/// A short HTML-formatted description of the media.
let synopsis: String
/// A list of genres for this title (only available in details requests).
let genres: [String]?
/// Popular tags for the title as assigned by MyAnimeList members (only available in details requests).
let tags: [String]
/// MARK: - Anime
}
And this seemed to work. But now I have my properties in both MediaType and Anime. In OOP, you avoid the duplicate code by subclassing.
So I repeat my question here: Am I misunderstanding Protocol-Oriented Programming, or is the downside of POP that you have to copy-and paste your protocol-specific logic whenever you make a struct/class/enum comply with it?
It's been a few weeks since I posted this, but I believe what Aaron Brager said is true.
While Protocol-Oriented-Programming is rather new in itself, the idea of protocols has been present in Objective-C for a long time, they are in Swift, and they have their variants in languages such as Java. Due to the nature of protocols and extensions, it looks like doing default implementations of properties is not possible, as extensions won't allow you to set non-computed properties in them.
That is because your Anime struct doesn't implement all properties from the MediaType protocol. Here's a minimized example of how you can do it:
protocol MediaType : Equatable {
var ID: Int { get }
var title: String { get }
}
struct Anime : MediaType {
// Implement the MediaType protocol
var ID : Int
var title : String
}
/// Compares two Anime_ objects. Two Anime_ objects are considered equal when they have the same ID and title.
func ==(lhs: Anime, rhs: Anime) -> Bool {
return (lhs.ID == rhs.ID) && (lhs.title == rhs.title)
}
let x = Anime(ID: 1, title: "title 1")
let y = Anime(ID: 2, title: "title 2")
let z = Anime(ID: 1, title: "title 1")
println(x == y) // false
println(x == z) // true
One curiosity though: in the protocol, why are you declaring all properties as read-only?

Resources