Announcing Experimental Mobile Blazor Bindings May update
Eilon
May 26th, 2020
It’s been a few months so it’s time for another update of Experimental Mobile Blazor Bindings! This release brings several bug fixes in the areas of CSS styling support, adding XML doc comments to common APIs, and several syntax improvements to common controls.
Here are the major changes in this release:
Update to latest native mobile component versions in Xamarin.Forms 4.5 and add doc comments #96, #110, #111
Because most of the components in Mobile Blazor Bindings are based on Xamarin.Forms native controls, the components have been updated to Xamarin.Forms 4.5. For example, properties such as Image.IsAnimationPlaying and Stepper.StepperPosition are now available. The doc comments that are seen in IntelliSense have also been imported so that you get useful help while coding:
Improve Label and Button syntax
Because one of the key motivators for building Mobile Blazor Bindings was to have patterns that were more familiar to web developers, the syntax for Label and Button components has been simplified and improved.
In previous versions setting the text for a Label’s Span’s Text or a Button’s Text had to be done via a property setter:
Speaking of Span.Text, a Label with complex formatting used to have many intermediate tags:
<Label FontSize="12"> <FormattedText> <FormattedString> <Spans> <Span Text="This text is large... " FontSize="50" /> <Span Text="and this is plain... " /> <Span Text="and this is green!" TextColor="Color.Green" /> </Spans> </FormattedString> </FormattedText>
</Label>
And starting with Preview 3, the intermediate tags have all been removed:
<Label FontSize="12"> <Span FontSize="50">This text is large... </Span> <Span>and this is plain... </Span> <Span TextColor="Color.Green">and this is green!</Span>
</Label>
CSS improvements
CSS is a great way to style your application while keeping it separate from the layout and behavior. Check out the CSS Styles topic for more information on how to use CSS in your Mobile Blazor Bindings apps.
There are three CSS-related improvements in this release:
The minimum version of Xamarin.Forms is now 4.5, which fixes most CSS issues, such as the ability to use almost all CSS selectors.
A small breaking change was made to use spaces as separators instead of commas when specifying multiple class names (this matches web behavior). See issue #100 for more information.
A bug fix was made to ensure CSS is loaded properly on iOS devices.
More information:
For more information please check out:
Thank you to community blog posts!
If you’d like to learn more, please check out these blog posts from community members:
Thank you!
What’s next? Let us know what you want!
We’re listening to your feedback, which has been both plentiful and helpful! We’re also fixing bugs and adding new features. And you may have seen last week’s announcement for .NET Multi-platform App UI (.NET MAUI). As an experiment, what we find with Mobile Blazor Bindings will feed directly into the Blazor aspects of .NET MAUI so please share with us your thoughts on using Blazor with .NET MAUI on this project’s repo or on .NET MAUI’s GitHub repo.
This project will continue to take shape in large part due to your feedback, so please let us know your thoughts at the GitHub repo.
P.S.: My apologies for the delay in this update. The realities of work-from-home (and stay-at-home parenting) meant that progress was extremely limited. I thank everyone for their patience, understanding, and support. You can always stay up-to-date by going to the GitHub repo and using the latest builds, or reach me on Twitter @original_ejl.
Apple mass producing ‘AirTags,’ about to begin ‘iPhone 12’ production
A new report from the supply chain says that Apple has already begun “AirTags” mass production, plus it will soon ramp up “iPhone 12” manufacturing, and it’s also increasing orders for iPads.
As rumors persist that Apple will announce the date of its “iPhone 12” event, a new report claims that production is now or shortly to be underway on Apple’s “AirTags,” certain models of “iPhone 12,” and new iPads.
According to the Nikkei Asian Review, Apple has managed to shorten the coronavirus-induced production delays to weeks instead of months. The “iPhone 12” range is reported to be about to begin limited manufacturing, before ramping up toward the end of September or the start of October.
“We’ve managed to shorten the delay significantly and we are not stopping here,” a supply chain executive reportedly said. “The final assembly for some models is still going to be early October, but we are working to keep moving the production as early as possible.”
Backing up other recent rumors, Nikkei Asian Review says that the “iPhone 12” production is going to start with the expected 6.1-inch OLED “iPhone 12 Max.” Reportedly this model amounts to 40% of all the 5G iPhone orders Apple has placed
It’s claimed that Apple has ordered components for up to 80 million 5G iPhones, but two sources have told Nikkei Asian Review that it’s more likely only between 73 and 74 million will be produced before the end of the year. The remainder will be produced in early 2021.
While production on the “iPhone 12” range builds up, Nikkei Asian Review also says that Apple is already mass producing the forthcoming “AirTags” accessory. Plus it has increased production for new iPads, reportedly aiming for 27 million devices between September and December.
That’s claimed to be almost as many as Apple produced of its entire iPad range in July to December 2019.
Nikkei Asian Review sources also deny rumors of an annual refresh of the iPhone SE. Reportedly multiple sources say that there won’t be a 2021 version.
Posted by: xSicKxBot - 09-08-2020, 11:28 AM - Forum: Windows
- No Replies
New steps to combat disinformation
Today, we’re announcing two new technologies to combat disinformation, new work to help educate the public about the problem, and partnerships to help advance these technologies and educational efforts quickly.
There is no question that disinformation is widespread. Research we supported from Professor Jacob Shapiro at Princeton, updated this month, cataloged 96 separate foreign influence campaigns targeting 30 countries between 2013 and 2019. These campaigns, carried out on social media, sought to defame notable people, persuade the public or polarize debates. While 26% of these campaigns targeted the U.S., other countries targeted include Armenia, Australia, Brazil, Canada, France, Germany, the Netherlands, Poland, Saudi Arabia, South Africa, Taiwan, Ukraine, the United Kingdom and Yemen. Some 93% of these campaigns included the creation of original content, 86% amplified pre-existing content and 74% distorted objectively verifiable facts. Recent reports also show that disinformation has been distributed about the COVID-19 pandemic, leading to deaths and hospitalizations of people seeking supposed cures that are actually dangerous.
What we’re announcing today is an important part of Microsoft’s Defending Democracy Program, which, in addition to fighting disinformation, helps to protect voting through ElectionGuard and helps secure campaigns and others involved in the democratic process through AccountGuard, Microsoft 365 for Campaigns and Election Security Advisors. It’s also part of a broader focus on protecting and promoting journalism as Brad Smith and Carol Ann Browne discussed in their Top Ten Tech Policy Issues for the 2020s.
New Technologies
Disinformation comes in many forms, and no single technology will solve the challenge of helping people decipher what is true and accurate. At Microsoft, we’ve been working on two separate technologies to address different aspects of the problem.
One major issue is deepfakes, or synthetic media, which are photos, videos or audio files manipulated by artificial intelligence (AI) in hard-to-detect ways. They could appear to make people say things they didn’t or to be places they weren’t, and the fact that they’re generated by AI that can continue to learn makes it inevitable that they will beat conventional detection technology. However, in the short run, such as the upcoming U.S. election, advanced detection technologies can be a useful tool to help discerning users identify deepfakes.
Today, we’re announcing Microsoft Video Authenticator. Video Authenticator can analyze a still photo or video to provide a percentage chance, or confidence score, that the media is artificially manipulated. In the case of a video, it can provide this percentage in real-time on each frame as the video plays. It works by detecting the blending boundary of the deepfake and subtle fading or greyscale elements that might not be detectable by the human eye.
This technology was originally developed by Microsoft Research in coordination with Microsoft’s Responsible AI team and the Microsoft AI, Ethics and Effects in Engineering and Research (AETHER) Committee, which is an advisory board at Microsoft that helps to ensure that new technology is developed and fielded in a responsible manner. Video Authenticator was created using a public dataset from Face Forensic++ and was tested on the DeepFake Detection Challenge Dataset, both leading models for training and testing deepfake detection technologies.
We expect that methods for generating synthetic media will continue to grow in sophistication. As all AI detection methods have rates of failure, we have to understand and be ready to respond to deepfakes that slip through detection methods. Thus, in the longer term, we must seek stronger methods for maintaining and certifying the authenticity of news articles and other media. There are few tools today to help assure readers that the media they’re seeing online came from a trusted source and that it wasn’t altered.
Today, we’re also announcing new technology that can both detect manipulated content and assure people that the media they’re viewing is authentic. This technology has two components. The first is a tool built into Microsoft Azure that enables a content producer to add digital hashes and certificates to a piece of content. The hashes and certificates then live with the content as metadata wherever it travels online. The second is a reader – which can exist as a browser extension or in other forms – that checks the certificates and matches the hashes, letting people know with a high degree of accuracy that the content is authentic and that it hasn’t been changed, as well as providing details about who produced it.
This technology has been built by Microsoft Research and Microsoft Azure in partnership with the Defending Democracy Program. It will power an initiative recently announced by the BBC called Project Origin.
Partnerships
No single organization is going to be able to have meaningful impact on combating disinformation and harmful deepfakes. We will do what we can to help, but the nature of the challenge requires that multiple technologies be widely adopted, that educational efforts reach consumers everywhere consistently and that we keep learning more about the challenge as it evolves.
Today, we’re highlighting partnerships we’ve been developing to help these efforts.
First, we’re partnering with the AI Foundation, a dual commercial and nonprofit enterprise based in San Francisco, with the mission to bring the power and protection of AI to everyone in the world. Through this partnership, the AI Foundation’s Reality Defender 2020 (RD2020) initiative will make Video Authenticator available to organizations involved in the democratic process, including news outlets and political campaigns. Video Authenticator will initially be available only through RD2020, which will guide organizations through the limitations and ethical considerations inherent in any deepfake detection technology. Campaigns and journalists interested in learning more can contact RD2020 here.
Second, we’ve partnered with a consortium of media companies including the BBC, CBC/Radio-Canada and the New York Times on Project Origin, which will test our authenticity technology and help advance it as a standard that can be adopted broadly. The Trusted News Initiative, which includes a range of publishers and social media companies, has also agreed to engage with this technology. In the months ahead, we hope to broaden work in this area to even more technology companies, news publishers and social media companies.
Media Literacy
We’re also partnering with the University of Washington (UW), Sensity and USA Today on media literacy. Improving media literacy will help people sort disinformation from genuine facts and manage risks posed by deepfakes and cheap fakes. Practical media knowledge can enable us all to think critically about the context of media and become more engaged citizens while still appreciating satire and parody. Though not all synthetic media is bad, even a short intervention with media literacy resources has been shown to help people identify it and treat it more cautiously.
Today, we are launching an interactive quiz for voters in the United States to learn about synthetic media, develop critical media literacy skills and gain awareness of the impact of synthetic media on democracy. The Spot the Deepfake Quiz is a media literacy tool in the form of an interactive experience developed in partnership with the UW Center for an Informed Public, Sensity and USA Today. The quiz will be distributed across web and social media properties owned by USA Today, Microsoft and the University of Washington and through social media advertising.
Additionally, in collaboration with the Radio Television Digital News Association, The Trust Project and UW’s Center for an Informed Public and Accelerating Social Transformation Program, Microsoft is supporting a public service announcement (PSA) campaign encouraging people to take a “reflective pause” and check to make sure information comes from a reputable news organization before they share or promote it on social media ahead of the upcoming U.S. election. The PSA campaign will help people better understand the harm misinformation and disinformation have on our democracy and the importance of taking the time to identify, share and consume reliable information. The ads will run across radio stations in the United States in September and October.
Finally, in recent months we have significantly expanded our implementation of NewsGuard, which enables people to learn more about an online news source before consuming its content. NewsGuard operates a team of experienced journalists who rate online news websites on the basis of nine journalistic integrity criteria, which they use to create both a “nutrition label” and a red/green rating for each rated news website. People can access NewsGuard’s service by downloading a simple browser extension, which is available for all standard browsers. It is free for users of the Microsoft Edge browser. Importantly, Microsoft has no editorial control over any of NewsGuard’s ratings and the NewsGuard browser extension does not limit access to information in any way. Instead, NewsGuard aims to provide greater transparency and encourage media literacy by providing important context about the news source itself.
Policy considerations
Governments, companies, non-profits and others around the world have a critical part to play in addressing disinformation and election interference broadly. In 2018, the Paris Call for Trust & Security in Cyberspace brought together a multistakeholder group of global leaders committing to nine principles that will help ensure peace and security online. One of the most critical of these principles is defending electoral processes. In May, Microsoft, the Alliance for Securing Democracy and the Government of Canada launched an effort to lead global activities on this principle. We encourage any organization interested in contributing to join the Paris Call.
Posted by: xSicKxBot - 09-08-2020, 11:28 AM - Forum: Windows
- No Replies
New grants aim to help job-seekers needing digital skills
In the spring of 2000, a young man walked into the Inner-City Computer Stars office in Chicago, determined to join this nonprofit’s digital skills training program and build a future for himself in technology. But first he had to prove that he was ready for that journey.
“He was 17 or 18 years old when he applied,” recalls Sandee Kastrul, the CEO and a founder of i.c.stars. Kastrul says she asked him to “go and build a website and come back.” So he did. “And this was back in the day, 20 years ago, so he had all these floppy disks with his code on it to show us what he had built. It was pretty incredible, and we said, ‘All right, we’ve got to have this kid joining the cohort.’”
Today, that young man, Kevin Gates, is a principal cloud solution architect at Microsoft. Gates remembers his first conversation with i.c.stars. He says he heard “HTML” mentioned for the first time. It sparked his curiosity, and learning to build a website was the beginning of a new chapter for Gates: “i.c.stars helped me stumble on what was a passion of mine, and that passion has led to a career. There is no doubt I would not be where I am without the program. I never would have imagined having the life I have without i.c.stars,” he says.
I.c.stars is a rigorous, tech-focused program that provides young adults from low-income communities with the tools to develop the technical and leadership skills needed for a career in technology, a field that continues to lack diversity and be in high demand.
Programs like this are vital to accelerating the distribution of digital skills. On Wednesday, Microsoft launched a new community skills grant program, part of the company’s commitment to racial equity and digital skills. It will include a $15 million investment over three years for Black- and African American-led nonprofits that are working to increase skill development and economic opportunities. The program includes grants, leadership development and technology enablement.
Research shows that companies with diverse leadership are more likely to be profitable. Despite this knowledge, the workplace does not reflect this.
There are several issues with hiring that further lock in inequality, says Byron Auguste, the CEO and co-founder of Opportunity@Work, an organization focused on economic inclusion. Auguste is a member of the advisory board for Microsoft’s community skills program that supports nonprofits in Black and African American communities.
One of the issues is the idea that you need a certain background to do a job. Auguste, however, thinks qualifications are what should matter. “If you can do the job, you should be able to get the job,” he says.
A part of the solution is building access to larger talent pools like i.c.stars does. Auguste says that often employers hire someone great and think that they just got lucky.
“Actually, they’re one of millions, not one in a million,” he says. The only way to get to the millions of talented people who are shut out, he continues, is by enabling not just one individual at a time, but via training programs and talent sources like these.
Microsoft’s skills initiative, of which this program is a part, hopes to help 25 million people around the world secure digital skills. In June, Microsoft made a public commitment to be more inclusive as an employer and to extend Microsoft’s support and outreach programs in Black and African American communities. As part of this, Microsoft’s community skills program will provide financial grants and tech enablement to community-based nonprofits reaching 5 million unemployed workers who need it most.
Naria Santa Lucia, general manager at Microsoft and lead on the larger skills initiative, explains the thinking behind this program: “It was designed with internal and external voices focused on community at the table. In addition to cash investments, we’re acting as a convener to bring together these organizations to share best practices.”
A part of this community-based skills program includes what Santa Lucia calls “a community of practice.” It offers a space for community leaders to come together and discuss concerns and issues they are having while Microsoft helps navigate solutions including tech enablement. The program aims to build up leadership in these programs but also individual nonprofit’s capabilities to help them further serve their communities.
“There are a lot of programs supporting skills, but this is explicitly supporting a level of capacity building, too,” observes Auguste. “The seeds of success are there, but there’s much more to be done to scale these programs up.”
YouTube Video
Paying it forward
I.c.stars interviews hundreds of potential candidates for each training cycle. Participants complete a two-year program that involves more than 1,000 hours of practical experience and advancing their public speaking skills – because Kastrul believes that technical skills aren’t enough on their own.
“I want people to be great technologists,” she says. “I want them to be able to solve complex problems, build awesome solutions, using systems thinking, but I also want people to be able to connect to what’s important, connect to the larger picture and to figure out, ‘How do I make opportunities for others?’”
That sense of paying it forward within a community runs deep through i.c.stars and organizations like it. It’s why recent alumni such as Ernest Roberts say they devote so much of their spare time to supporting new interns as well as their peers.
“We all help each other,” says Roberts. “It does create this community of those who successfully complete the program and continue on – we’re all together. It’s been two years, and if it wasn’t for quarantine, I’d still be going back almost every day.” He now serves as president of the alumni association.
Roberts believes that i.c.stars changed his life. Before the program, he worked at a distribution center in Mississippi – a state where he said he found limited opportunities to work in technology.
“That was a huge thing for me in Mississippi, because there’s no real technology hub, no technology jobs,” he says. “So now, I started thinking, as I’ve been going through i.c.stars, about how can I bring this into Mississippi, where kids don’t know that they don’t have to be a truck driver? You don’t have to be a farmer. You don’t have to be a warehouse worker. You can actually go and do other things and get paid for your mind instead of your physical body.”
Now working as a developer for a global financial services firm, Roberts says his outlook has been transformed: “I was living check to check,” he says. “Now, I can save up. Now, I can go ahead and start that bank account for my son that I thought about. I can start building for the future, where I was only living in the present.”
Realizing your potential
For another recent alum, i.c.stars has provided confidence. LaTonya Judkins had also worked in shipping and receiving, and since completing the i.c.stars program in 2019, has found a role at a sports data analytics firm – an ideal match for this basketball player who says she has always been tech savvy.
“I thought other people do software engineering, but I didn’t think that I would do it,” she says, “because I don’t have the education, the background, I’m not already into it. I figured that people that do software engineering, you have to have started doing it since you were a kid, and have to know a lot of stuff in order to do it. So, going through i.c.stars, they teach you that you can teach yourself how to do these things that everybody else does, and you can be successful doing it.”
“In technology, in corporate America – I’m not saying you have to fit in, but you kind of have to find your space, and also be comfortable and see ahead,” she points out. “With i.c.stars, and the program, it explains and it embraces diversity and inclusion – being Black, being a woman.”
The open grant application is how Microsoft Philanthropies says it is exercising its commitment to making access to technology more equitable. The focus is on groups that are based in local communities. Santa Lucia says, “We are looking for those nonprofits with local impact and community-based solutions. We are also looking at nonprofits led by Black and African American members as well as serving the Black and African American communities.”
There are areas across the country that have significant racial disparities in access to education, employment, health care and home ownership. But geography does not mean lack of skill, or lack of ambition, and it is the talent embedded in these neighborhoods that technology companies such as Microsoft hope to find and help flourish.
Gates says, “Microsoft has always been conscious about the impact the employees have in the communities where they live. I believe being able to make an impact in smaller communities is critical.”
For more on the community skills program, click here. And follow @MSFTIssues on Twitter.
(Main picture: Alums of the i.c.stars program, from left to right, Ernest Roberts, LaTonya Judkins and Kevin Gates)
There Are Currently No Plans To Bring More Kingdom Hearts Games To Switch
As you might have heard, the rhythm-action game Kingdom Hearts: Melody of Memory is coming to the Nintendo Switch this November. As excited as we are about it, of course – we would love to see the mainline series made available as well.
Unfortunately, though, there are no other Kingdom Hearts games planned for the Switch right now. This is according to Kingdom Heart’s director, Tetsuya Nomura, during a recent interview with Nintendo Enthusiast:
“Through a translator, Tetsuya Nomura confirmed there are currently no specific plans for more Kingdom Hearts games on Switch.”
Apparently Square Enix considered porting the existing titles in the series, but found it to be “technologically difficult”.
Nomura himself said he still finds the Switch appealing and apparently expressed how it was possible another game could make the switch to Nintendo’s hybrid system in the future.
Posted by: xSicKxBot - 09-08-2020, 07:23 AM - Forum: Lounge
- No Replies
Animal Crossing: New Horizons Staff Explain How They Keep The Series Fresh
Animal Crossing: New Horizons has been an extraordinary success on Switch, selling 22.4 million copies since its release in March, and the game's broad appeal was not by accident. During a presentation at Japan’s Computer Entertainment Developers Conference, which was viewed by Japanese site 4Gamer and translated by Video Games Chronicle, the game's director Aya Kyogoku went deep on the series' success, and who New Horizons has appealed to so far.
Kyogoku said that a series like Animal Crossing "cannot be sustained without change"--while the Animal Crossing games maintain similar gameplay between releases, there are a lot of changes that long-time fans will recognize. "Games are entertainment, so you will definitely get tired of making the same things," Kyogoku said. "In order for the series to continue to exist as an IP and for many people to enjoy it for a long time, it is important to continue to challenge and change with the times."
For New Horizons, she says, the main change was that players can get goals and achievements that change across their playtime, with the Nook Miles system giving more clear goals early on.
Hisashi Nogami, the series' head producer, was also involved in the presentation. He said that the New Horizons player base doesn't have a clear split between male and female players, and that many players are in their 20s and 30s. "What would the public imagine if they were asked what kind of game Animal Crossing is," he asked. "I think there is probably an image of 'a game where you can live leisurely with cute animals’ and ‘a game for young girls...However, looking at the gender and age data of Animal Crossing users, it is clear that the ratio of males and females is half and there are many users in their 20s and 30s."
This will likely not come as a surprise to anyone who has followed the hype around the game--even Danny Trejo loves it. Nogami says that many younger players have likely not gotten the game yet because it has not been available over a holiday period yet, when children are more likely to receive the game as a present.
A second presentation, focused on New Horizons' art, also happened. Art director Kouji Takahashi discussed the game's art, saying that fish and buys were rendered realistically so that players could inspect them closely and enjoy them. Certain other elements, like trees and plants, are rendered in a more cartoony way, because going too realistic would make the picture on the screen too busy, and when that happens "the player becomes passive."
Takahashi talks about the importances of the "imaginary gap," whereby the image sparks player's imaginations. "If artists are able to symbolize memories and images, each interpretation will be applied to the ‘imaginary gap’ and infinite value will be created," he says.
If you're on the hunt for new bugs and fish in September across New Horizons, here's what to look for.
We are excited to announce a new release of Red Hat Dependency Analytics, a solution that enables developers to create better applications by evaluating and adding high-quality open source components, directly from their IDE.
Red Hat Dependency Analytics helps your development team avoid security and licensing issues when building your applications. It plugs into the developer’s IDE, automatically analyzes your software composition, and provides recommendations to address security holes and licensing problems that your team may be missing.
Without further ado, let’s jump into the new capabilities offered in this release. This release includes a new version of the IDE plugin and the server-side analysis service hosted by Red Hat.
Support for Python applications
Along with Java (maven) and JavaScript (npm), Dependency Analytics now offers its full set of capabilities for Python (PyPI) applications. From your IDE, you can perform the vulnerability and license analysis of the “requirements.txt” file of your Python application, incorporate the recommended fixes, and generate the stack analysis report for more details.
Software composition analysis based on current vulnerability data
An estimated 15,000 open source packages get updated every day. On average, three new vulnerabilities get posted every day across JavaScript (npm) and Python (PyPi) packages. With this new release, the server-side analysis service hosted by Red Hat automatically processes the daily updates to open source packages that it is tracking. The hosted service also automatically ingests new vulnerability data posted to National Vulnerability Database (NVD) for JavaScript and Python packages. This allows the IDE plugin and API calls to provide source code analysis based on current vulnerability and release data.
Analyze transitive dependencies
In addition to the direct dependencies included in your application, Dependency Analytics now leverages the package managers to discover and add the dependencies of those dependencies, called “transitive” dependencies, to the dependency graph of your application. Analysis of your application is performed across the whole graph model and recommendations for fixes are provided across the entire set of dependencies.
Recommendations about complementary open source libraries
With this release, Dependency Analytics looks to recommend high-quality open source libraries that are complementary to the dependencies included in your application. The machine learning technology of the hosted service collects and analyzes various statistics on GitHub to curate a list of high-quality open source libraries that can be added to the current set of dependencies to augment your application. You can provide your feedback about the add-on libraries by clicking on the “thumbs-up” or “thumbs-down” icons shown for each recommendation. Your feedback is automatically processed to improve the quality of the recommendations.
IDE plugin support
The Dependency Analytics IDE plugin is now available for VS Code, Eclipse Che, and any JetBrains IDE, including IntelliJ and PyCharm.
We will continuously release new updates to our Dependency Analytics solution so you can minimize the delays in delivery of your applications due to last-minute security and licensing related issues.
Stay tuned for further updates; we look forward to your feedback about Dependency Analytics.
Posted by: xSicKxBot - 09-08-2020, 03:39 AM - Forum: Python
- No Replies
Python One Line Append
Do you want to one-linerize the append() method in Python? I feel you—writing short and concise one-liners can be an addiction!
This article will teach you all the ways to append one or more elements to a list in a single line of Python code!
Python List Append
Let’s quickly recap the append method that allows you add an arbitrary element to a given list.
How can you add an elements to a given list? Use the append() method in Python.
Definition and Usage
The list.append(x) method—as the name suggests—appends element x to the end of the list.
Here’s a short example:
>>> l = []
>>> l.append(42)
>>> l
[42]
>>> l.append(21)
>>> l
[42, 21]
In the first line of the example, you create the list l. You then append the integer element 42 to the end of the list. The result is the list with one element [42]. Finally, you append the integer element 21 to the end of that list which results in the list with two elements [42, 21].
Syntax
You can call this method on each list object in Python. Here’s the syntax:
Problem: How can you create a list and append an element to a list using only one line of Python code?
You may find this challenging because you must accomplish two things in one line: (1) creating the list and (2) appending an element to it.
Solution: We use the standard technique to one-linerize each “flat” multi-line code snippet: with the semicolon as a separator between the expressions.
a = [1, 2, 3]; a.append(42); print(a)
This way, we accomplish three things in a single line of Python code:
Creating the list [1, 2, 3] and assigning it to the variable a.
Appending the element 42 to the list referred to by a.
Problem: How can we append multiple elements to a list in a for loop but using only a single line of Python code?
Example: Say, you want to filter a list of words against another list and store the resulting words in a new list using the append() method in a for loop.
# FINXTER TUTORIAL:
# How to filter a list of words? words = ['hi', 'hello', 'Python', 'a', 'the']
stop_words = {'a', 'the'}
filtered_words = [] for word in words: if word not in stop_words: filtered_words.append(word) print(filtered_words)
# ['hi', 'hello', 'Python']
You first create a list of words to be filtered and stored in an initially empty list filtered_words. Second, you create a set of stop words against you want to check the words in the list. Note that it’s far more efficient to use the set data structure for this because checking membership in sets is much faster than checking membership in lists. See this tutorial for a full guide on Python sets.
You now iterate over all elements in the list words and add them to the filtered_words list if they are not in the set stop_words.
Solution: You can one-linerize this filtering process using the following code:
filtered_words = [word for word in words if word not in stop_words]
Here’s the complete code that solves the problem using the one-liner filtering method:
# FINXTER TUTORIAL:
# How to filter a list of words? words = ['hi', 'hello', 'Python', 'a', 'the']
stop_words = {'a', 'the'}
filtered_words = [word for word in words if word not in stop_words] print(filtered_words)
# ['hi', 'hello', 'Python']
Here’s a short tutorial on filtering in case you need more explanations:
In the previous example, you’ve already seen how to use the if statement in the list comprehension statement to append more elements to a list if they full-fill a given condition.
How can you filter a list in Python using an arbitrary condition? The most Pythonic and most performant way is to use list comprehension [x for x in list if condition] to filter all elements from a list.
Try It Yourself:
The most Pythonic way of filtering a list—in my opinion—is the list comprehension statement [x for x in list if condition]. You can replace condition with any function of x you would like to use as a filtering condition.
For example, if you want to filter all elements that are smaller than, say, 10, you’d use the list comprehension statement [x for x in list if x<10] to create a new list with all list elements that are smaller than 10.
Here are three examples of filtering a list:
Get elements smaller than eight: [x for x in lst if x<8].
Get even elements: [x for x in lst if x%2==0].
Get odd elements: [x for x in lst if x%2].
lst = [8, 2, 6, 4, 3, 1] # Filter all elements <8
small = [x for x in lst if x<8]
print(small) # Filter all even elements
even = [x for x in lst if x%2==0]
print(even) # Filter all odd elements
odd = [x for x in lst if x%2]
print(odd)
The output is:
# Elements <8
[2, 6, 4, 3, 1] # Even Elements
[8, 2, 6, 4] # Odd Elements
[3, 1]
This is the most efficient way of filtering a list and it’s also the most Pythonic one. If you look for alternatives though, keep reading because I’ll explain to you each and every nuance of filtering lists in Python in this comprehensive guide.
Python Append One Line to File
Problem: Given a string and a filename. How to write the string into the file with filename using only a single line of Python code?
Example: You have filename 'hello.txt' and you want to write string 'hello world!' into the file.
hi = 'hello world!'
file = 'hello.txt' # Write hi in file '''
# File: 'hello.txt':
hello world! '''
How to achieve this? In this tutorial, you’ll learn four ways of doing it in a single line of code!
Here’s a quick overview in our interactive Python shell:
Exercise: Run the code and check the file 'hello.txt'. How many 'hello worlds!' are there in the file? Change the code so that only one 'hello world!' is in the file!
The most straightforward way is to use the with statement in a single line (without line break).
hi = 'hello world!'
file = 'hello.txt' # Method 1: 'with' statement
with open(file, 'a') as f: f.write(hi) '''
# File: 'hello.txt':
hello world! '''
You use the following steps:
The with environment makes sure that there are no side-effects such as open files.
The open(file, 'a') statement opens the file with filename file and appends the text you write to the contents of the file. You can also use open(file, 'w') to overwrite the existing file content.
The new file returned by the open() statement is named f.
In the with body, you use the statement f.write(string) to write string into the file f. In our example, the string is 'hello world!'.
Of course, a prettier way to write this in two lines would be to use proper indentation:
with open(file, 'a') as f: f.write(hi)
This is the most well-known way to write a string into a file. The big advantage is that you don’t have to close the file—the with environment does it for you! That’s why many coders consider this to be the most Pythonic way.
You can find more ways on my detailed blog article.
Python programmers will improve their computer science skills with these useful one-liners.
Python One-Linerswill teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:
• Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution • Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning • Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators • Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.
How do you know your readers’ or customers’ thoughts on your website content? How does the star rating feature help to collect customers’ opinions?
Star rating is a feature that is used across different domains in a variety of ways. For example, it is one of the key building blocks in an eCommerce website.
Star rating helps you to know how people rank your content. It not only gives rank on your content. Also, it brings more readers to your page by the gained rating.
When you build a website, if you have got scope for implementing a star rating system and you should definitely experiment with it.
Websites use a variety of ways to allow users to rate content. For example, star rating, up-down rating, emoji rating and more.
We have seen so many examples for star rating, emoji rating and more. I grouped all those in this one single example.
I supported three UI alternatives for the rating section. Those are,
Five-star rating
Favorite rating
Emoji rating
I created a directive in PHP to configure the template for the rating appearance.
Existing plugins to implement a dynamic star rating
There are various plugins available in the market to enable star rating. The ready-made plugins are with enormous features.
For example, Rateit is a jQuery based star rating plugin. It allows embedding a star rating with a list, select and more HTML markup. It supports Font Awesome, Material icons to display rating icons.
The UpvoteJS is a JavaScript package to render a StackExchange-like rating widget.
If you are having a WordPress website, there are built-in rating plugins available. Wp-PostRatings is a popular plugin to implement rating.
Advantages of creating a custom star rating script
With a custom star rating, we can simplify the code logic instead of stuffing a lot.
And thereby, it will make it easy at the time of enhancement or maintenance phase.
It rectifies your overload with a feature-packed built-in. Also, it reduces your effort on managing a thousand lines of code for this simple UI feature.
Various types of rating options
Websites use a different type of rating options to get user’s reviews. The following list shows some of the types.
Single or multiple star rating
Facebook-like emoji rating
Simple up-down voting.
Like-unlike rating
Bar rating
The types are veries in user’s mindset while rating. For example, the like-unlike and up-down rating expects binary options 0 or 1 from the user. But with the bar rating, it can have a range of points out of some limit.
Star rating example with AJAX
I have created an AJAX-based star rating example code with PHP and jQuery.
This code will show a list of courses with an option to rate each course. The courses are from the database.
The rating element in the UI is configurable. I provided three UI alternatives for the rating section. Star, favorite and emoji ratings are there to collect users’ reviews.
While adding the rating, the code sends it to the PHP via AJAX. Then, it saves the ratings in the MySQL database.
Once rated, the user cannot rerate a course again to avoid duplicate ratings.
The following figure shows the file strucuture of the example code.
The rating example database
This section shows the structure and the SQL of the database used in this example.
I have created two tables tbl_courses and tbl_course_rating. The tbl_cources database table contains courses on which the user will add ratings.
The tbl_cource_rating table has the mapping with the tbl_cource database. It has a unique rating without duplicates.
The below script shows the CREATE statement and the data dump for these two tables. By importing this script, you can setup this example in the local environment.
sql/db_rating.sql
--
-- Database: `db_rating`
-- -- -------------------------------------------------------- --
-- Table structure for table `tbl_course`
-- CREATE TABLE `tbl_course` ( `id` int(11) NOT NULL, `name` varchar(255) NOT NULL, `description` varchar(255) NOT NULL, `period` varchar(255) NOT NULL, `availabe_seats` int(11) NOT NULL, `last_date_to_register` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1; --
-- Dumping data for table `tbl_course`
-- INSERT INTO `tbl_course` (`id`, `name`, `description`, `period`, `availabe_seats`, `last_date_to_register`) VALUES
(1, 'Professional Training for Finantial Analyst\r\n', 'Professional Training for Finantial Analyst', '30 days', 2, '2020-01-31'),
(2, 'Enterprise Programming in Artificial Intelligence\r\n', 'Enterprise Programming in Artificial Intelligence', '30 days', 2, '2020-01-24'); -- -------------------------------------------------------- --
-- Table structure for table `tbl_course_rating`
-- CREATE TABLE `tbl_course_rating` ( `id` int(11) NOT NULL, `course_id` int(11) NOT NULL, `member_id` int(11) NOT NULL, `rating` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1; --
-- Indexes for dumped tables
-- --
-- Indexes for table `tbl_course`
--
ALTER TABLE `tbl_course` ADD PRIMARY KEY (`id`); --
-- Indexes for table `tbl_course_rating`
--
ALTER TABLE `tbl_course_rating` ADD PRIMARY KEY (`id`); --
-- AUTO_INCREMENT for dumped tables
-- --
-- AUTO_INCREMENT for table `tbl_course`
--
ALTER TABLE `tbl_course` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; --
-- AUTO_INCREMENT for table `tbl_course_rating`
--
ALTER TABLE `tbl_course_rating` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=95;
COMMIT;
UI design to render star rating option
In a landing page, it shows the list of courses from the database. The HTML code for this page is below.
It loads the rating element based on the PHP constant defined in a common configuration file.
The rating element will show clickable 5-stars or favorite-icons or emoji icons.
On clicking the rating element, it invokes a jQuery script to send AJAX requests to save ratings.
I created separate template files to have different types of rating UI. Those are star-rating-view.php, favorite-rating-view.php and emoji_rating_view.php.
The template files show the onClick event handling specification in the markup.
In the emoji rating template, it shows a range of five emotion icons from very-sad to very-happy.
If you are providing support on the user’s queries, you can use the emoji rating. Embedding the emoji rating will give the customer’s emotional feel on your support.
This file contains jQuery functions to prepare AJAX requests to save user ratings.
It also handles the mouse hover events to highlight the rating element. The mouseOverRating() function highlights the star or other rating elements on hovering.
Similarly, mouseOutRating() resets the rating UI back to its original form on mouse out.
The AJAX code in the addRating() prepares the request with PHP endpoint URL and data params.
It receives the server response in the AJAX success callback at which it updates the UI accordingly.
assets/js/rating.js
function mouseOverRating(courseId, rating, appearance) { if (appearance == "star") { for (var i = 1; i <= rating; i++) { $('#' + courseId + "_" + i + ' img').attr('src', "./img/" + appearance + "-filled.png"); } } else { ratingIconPrefix = "./img/" + appearance; for (var i = 1; i <= rating; i++) { if (appearance == "emoji") { ratingIconPrefix = "./img/" + appearance + "1"; } if (i == rating) { $('#' + courseId + "_" + i + ' img').attr('src', ratingIconPrefix + "-filled.png"); } } } } function mouseOutRating(courseId, userRating, appearance) { var ratingId; if (appearance == "star") { if (userRating != 0) { for (var i = 1; i <= userRating; i++) { $('#' + courseId + "_" + i + ' img').attr('src', "./img/" + appearance + "-filled.png"); } } if (userRating <= 5) { for (var i = (userRating + 1); i <= 5; i++) { $('#' + courseId + "_" + i + ' img').attr('src', "./img/" + appearance + "-open.png"); } } $(".selected img").attr('src', "./img/" + appearance + "-filled.png"); } else { ratingIconPrefix = "./img/" + appearance; if (userRating <= 5) { for (var i = 1; i <= 5; i++) { if (appearance == "emoji") { ratingIconPrefix = "./img/" + appearance + i; } if (userRating == i) { $('#' + courseId + "_" + i + ' img').attr('src', ratingIconPrefix + "-filled.png"); } else { $('#' + courseId + "_" + i + ' img').attr('src', ratingIconPrefix + "-open.png"); } } } var selectedImageSource = $(".selected img").attr('src'); if (selectedImageSource) { selectedImageSource = selectedImageSource.replace('open', "filled"); $(".selected img").attr('src', selectedImageSource); } } } function addRating(currentElement, courseId, ratingValue, appearance) { var loaderIcon = $(currentElement).closest(".row-item"); $.ajax({ url : "ajax-end-point/insertRating.php", data : "index=" + ratingValue + "&course_id=" + courseId, type : "POST", beforeSend : function() { $(loaderIcon).find("#loader-icon").show(); }, success : function(data) { loaderIcon = $(currentElement).closest(".row-item"); $(loaderIcon).find("#loader-icon").hide(); if (data != "") { $('#response-' + courseId).text(data); return false; } if (appearance == 'star') { $('#list-' + courseId + ' li').each( function(index) { $(this).addClass('selected'); if (index == $('#list-' + courseId + ' li').index( currentElement)) { return false; } }); } else { $(currentElement).addClass('selected'); } } }); }
Storing user rating to MySQL database from PHP
When the AJAX script called, it prepares a request to the PHP. In PHP, it receives the chosen rating post data and stores it in the rating database.
Though the UI displays different elements, the rating value ranges from 1 to 5. In the database, it has the mapping between the rating value, course id and member id.
The below configuration is for setting the rating element appearance. The possible values are there with a comment statement.
Common/Config.php
<?php
namespace Phppot; class Config
{ // Possible values: star | favourite | emoji const RATING_APPEARANCE = "favourite";
}
Before insert, it checks if the user added a rating already for that particular course. If so, then the code will not allow the user to rate again.
ajax-end-point/insertRating.php
<?php
namespace Phppot; use Phppot\Rating;
require_once __DIR__ . "./../Model/Rating.php";
$rating = new Rating();
// Here the user id is harcoded.
// You can integrate your authentication code here to get the logged in user id
$userId = 5; if (isset($_POST["index"], $_POST["course_id"])) { $courseId = $_POST["course_id"]; $ratingIndex = $_POST["index"]; $rowCount = $rating->isUserRatingExist($userId, $courseId); if ($rowCount == 0) { $insertId = $rating->addRating($userId, $courseId, $ratingIndex); if (empty($insertId)) { echo "Problem in adding ratings."; } } else { echo "You have added rating already."; }
}
This file displays the courses list with the rating option in a landing page.
getRatingData.php
<?php
namespace Phppot; use Phppot\Rating;
require_once "./Common/Config.php";
$config = new Config();
require_once "./Model/Rating.php";
$rating = new Rating();
// Here the user id is harcoded.
// You can integrate your authentication code here to get the logged in user id
$userId = 5; $apperance = $config::RATING_APPEARANCE; $courseResult = $rating->getCourse();
if (! empty($courseResult)) { foreach ($courseResult as $row) { $userRating = $rating->getUserRating($userId, $row['id']); $totalRating = $rating->getTotalRating($row['id']); $date = date_create($row["last_date_to_register"]); ?>
<div class="row-item"> <div class="row-title"><?php echo $row['name']; ?></div> <ul class="list-inline" id="list-<?php echo $row['id']; ?>"> <?php require $apperance . "-rating-view.php"; ?> <img src="img/loader.gif" class="loader-icon" id="loader-icon"> </ul> <div class="response" id="response-<?php echo $row['id']; ?>"></div> <p class="review-note">Total Reviews: <?php echo $totalRating; ?></p> <p class="text-address"> <label class="course-detail">Period: <?php echo $row["period"]; ?></label><label class="course-detail">Available seats: <?php echo $row["availabe_seats"]; ?></label><label class="course-detail">Last Date to Register: <?php echo date_format($date, "d M Y"); ?></label> </p>
</div>
<?php }
}
?>
In the above two PHP files, I have harcoded the user id with a PHP variable $userId. You can plugin user authentication code and get the logged-in user id.
The Rating.php is a PHP model class created for performing the rating actions.
It has functions to read courses and user ratings on them. The getUserRating() and getTotalRating() functions returns data to display the rating statistics.
The isUserRatingExist() checks the uniqueness of the user rating on a particular course.
I used prepared statements with MySQLi for executing the database queries. The source contains a generic DAO class DataSource.php for executing database operations.
Model/Rating.php
<?php
namespace Phppot; use Phppot\DataSource; class Rating
{ private $ds; function __construct() { require_once __DIR__ . './../lib/DataSource.php'; $this->ds = new DataSource(); } function getCourse() { $query = "SELECT * FROM tbl_course ORDER BY id DESC"; $result = $this->ds->select($query); return $result; } function getUserRating($userId, $courseId) { $average = 0; $avgQuery = "SELECT rating FROM tbl_course_rating WHERE member_id = ? and course_id = ?"; $paramType = 'ii'; $paramValue = array( $userId, $courseId ); $result = $this->ds->select($avgQuery, $paramType, $paramValue); if ($result > 0) { foreach ($result as $row) { $average = round($row["rating"]); } // endForeach } // endIf return $average; } function getTotalRating($courseId) { $totalVotesQuery = "SELECT * FROM tbl_course_rating WHERE course_id = ?"; $paramType = 'i'; $paramValue = array( $courseId ); $result = $this->ds->getRecordCount($totalVotesQuery, $paramType, $paramValue); return $result; } function isUserRatingExist($userId, $courseId) { $checkIfExistQuery = "select * from tbl_course_rating where member_id = ? and course_id = ?"; $userId; $courseId; $paramType = 'ii'; $paramValue = array( $userId, $courseId ); $rowCount = $this->ds->getRecordCount($checkIfExistQuery, $paramType, $paramValue); return $rowCount; } function addRating($userId, $courseId, $rating) { $insertQuery = "INSERT INTO tbl_course_rating(member_id,course_id, rating) VALUES (?,?,?) "; $paramType = 'iii'; $paramValue = array( $userId, $courseId, $rating ); $insertId = $this->ds->insert($insertQuery, $paramType, $paramValue); return $insertId; }
}
Output screenshot of different rating options with star, favorite, emoji
In the following screenshot, it displays a text in red. It is an error message to notify the user if he tries to add rating again.
Conclusion
We have seen the importance of implementing a rating script in an application. Also, we have seen the types of ratings generally used by the applications.
By supporting 3 types of rating UI components in an example script, I sure it helps you to have options. You can choose and fix one among them on a need basis.
For example, if you manage more applications, then integrate this one in all. The rating configuration allows setting based on the nature of the application.
There is no limit. We can enhance this component by adding more rating options like-unlike, up-down voting, rating with a ranger and more.
FREE ToW2: Battle for Caen, Store Top Picks, GalaQuiz
Theatre of War 2 - Battle for Caen FREEbie
[freebies.indiegala.com] Get ready for strong opposition and witness even more spectacular battles in the latest FREEbie, Theatre of War 2 - Battle for Caen.
The 203rd GalaQuiz will be LIVE soon, win up to $50 in GalaCredit!
[www.indiegala.com] The GalaQuiz will take place in less than 15 minutes from this announcement Today's GalaQuiz[www.indiegala.com] hints are up. The theme will be Musicals.