Arquivo da categoria: Desenvolvimento

Developer Career Path

  1. Where do you want to go next in your career level?
  2. What kind of compensation are you looking for?
  3. How will my skills be utilised?
  4. What kind of obstacles am I likely to face?

Software Career

  • Web Developer - VueJs, React, Angular, etc…
  • Computer programmers - developer - Python, C#, and Java, TypeScript, etc…
  • Database Administrator - Oracle, PostgreSQL, Microsoft SQL Server, MongoDB, etc…
  • Software Developer - design computer systems or applications
  • Technical architect
  • Software development team lead or Lead developer
  • Computer systems analysts
  • Software architect
  • DevOps Engineer

Where Can I Work as a Software Developer?

  • several industries
  • large tech company vs small startups
  • freelancers.

Locations

  • Geographic location
  • Demand for software developers, possibly leading to high salaries
  • California, New Hampshire, and Colorado
  • Remote

Large companies vs Smaller companies

  • Google, Facebook, or Microsoft
  • vast resources and a major impact on the public
  • merit consideration
  • small teams
  • variety of responsibilities
  • help grow a business

Soft skills or core skills

  • Critical thinking: facts, evidence, observations, and arguments
  • Problem solving: the best way to achieve an ultimate goal.
  • Public speaking:
  • Professional writing
  • Teamwork: The collaborative effort of a group to achieve a common goal or to complete a task in the most effective and efficient way
  • Digital literacy: find, evaluate, and communicate information
  • Leadership: the ability of an individual, group, or organization to "lead"
  • Professional attitude
  • Work ethic
  • Career management: Career management is the combination of structured planning and the active management choice of one's professional career.

Hard skills

Ability to perform an action with determined results with good execution, a given amount of time and energy.

Continuing Education

  • Software developers should continue building up their skills throughout their careers.
  • promotions
  • become more specialized
  • excel at their jobs
  • Hack Reactor: coding bootcamp
  • Iron Hack: programs in web development, UX/UI design, and data analytics
  • Codecademy: Codecademy boasts free and paid classes on programming languages
  • Google Code: Through the Google Code Archive, students can access open source projects to help with their own programs.

LinkedIn

Portfolio

[GIT] Concentrar commits em um só

Método para concentrar/concatenar vários commits em um só.

Caso você seja uma pessoa que cada mexida em código faz um commit e na hora de versionar, tem dezenas do mesmo, é interessante concentrar os commits em um só ou mais de um para ficar mais claro sua alteração para que na branch de destino não fique poluído.

No caso existe o git squash, que consiste no passo a passo abaixo.

Inicialmente faz um rebase para a branch de destino

git rebase -i main

Após ter feito o rebase... cairá nessa tela onde você escolhe a partir de qual branch quer "deixar"

Normalmente deixamos o primeiro commit como pick e os demais como squash.

Após ter feito isso e salvar e fechar essa tela acima, abrirá uma tela para ver qual comentário você quer deixar. O git já te dá uma prévia de comentário... no caso abaixo eu apaguei todo o comentário e deixei nessa tela apenas "update Account Files with userId". Quando sair cairá na tela abaixo.

Para encerrar, é só dar o comando abaixo para fazer um push force.

git push -f

Feito!

Exemplo de uma História de Usuário

Funcionalidade: Pagamento com cartão de crédito
O cliente pode optar pelo pagamento com cartão de crédito ao finalizar a
compra. O pagamento via cartão de crédito deve ser autorizado pela
operadora. No caso do pagamento por um cartão de crédito ser negado pela
operadora, o cliente deve ter a opção de selecionar outro cartão de crédito.

Contexto:
- Dado que selecionei o produto "Nike Air Vapor Ace"
- E pressionei "Finalizar compra"
- E me autentiquei com o usuário "[email protected]" senha "123456"
- E estou na "Página de pagamento"

Cenário: Crédito não autorizado pela operadora de cartão de crédito
- Quando o cliente informa "Crédito" como meio de pagamento
- E o cliente informa a bandeira de cartão de crédito "Visa"
- E o cliente informa o número do cartão de crédito "0000 2222 3333 4444
6666"
- E o cliente informa o nome no cartão "Fulano de Tal"
- E o cliente informa a data de vencimento "10/2021"
- E o cliente informa pagamento "À vista"
- E o cliente pressiona o botão "Finalizar compra"
- E o sistema de crédito retorna "COD5000 - Crédito não autorizado"
- Então o cliente deve ser redirecionado para a "Página de pagamento"
- E o sistema exibe a mensagem "A transação não foi autorizada pela
operadora de crédito."

[ESA-02] Manifesto Metodologia Ágil

Muda a perspectiva do capitalismo

Não ter retorno financeiro.
ter outros tipos de retorno
recompensas / metas

======================================

débito técnico --> diferença técnica
Necessário equilibrar o conhecimento para não ficar refém de pessoas
é necessário uma infra estrtura básica para modificar o meio e a política tem alto poder social nesse sentido.

======================================

alinhamento de expectativa
Inception
Impacto gera conflitos (Positivos e Negativos)
Fuja de conflitos silenciosos (mais perigoso) (fofocas, )

======================================

Pareto
20% das funcionalidades solicitadas serão realmente usadas.
Dessas 20% --> 80% do tempo cairão nelas.

======================================

Ambientes complexos utilizam metodologias ágeis (Quase Caótico)
Riscos serão trabalhados no meio do desenvolvimento
Processos empíricos (baseado na experiência) e iterativos

Caso haja um risco e seja todo pensando no início
ele não é complexo.

======================================

experiência (Montando-se o quebra-cabeças) + Valores --> Modelo Mental (base de experiências)
Flexibilizar valor para mudar --> Resiliência
Quando consigo mudar sem quebrar
Processo para ser adulto

até que ponto você pode aguentar?
até que ponto você pode aceitar?
Até que ponto são seus valores?
Você pode quebrar um valor??
É necessário romper?? Mais as pessoas estão dispostas a romper?

Coaching ontológico transformacional

======================================

******* Mais fácil pedir desculpas do que que pedir autorização --> Intra empreendedor

Sistema Adaptativo complexo
Você tem a necessidade de entregar um produto, mesmo sofrendo todas as influências do meio.

== Valores Ágeis ==
Treinamento --> Habilidade / Domínio

Sinergia / Domínio / Comprometimento / Confiança / Ferramentas / Treinamento / Propósito

C - Conhecimento
H - Habilidade
A - Atitude
J - Julgamento

************** Ninguém nasce competente

== Manifesto Ágil ==
Indivíduos e interação
Software em funcionamento (desempenho)
Colaboração com o cliente
Responder a mudanças

******** Contrato / Culpadologia XXXXXX Colaboração

**** Metodologia Prescritiva
O documento é que vale
Recurso e não pessoa
Minimiza os erros

********* Análise Transacional
Pai / Adulto (fatos e dados) / Criança

======================================

== Ágil ==
- Escopo / Pequenas entregas
- ambientes quase caóticos
- escalabilidade
- imprevisibilidade
- Estimativas empíricas
- Valores pessoais

== Tradicional ==
- Pode ser usado em manutenção pequenas e médias
- Estabilidade dos Requisitos
- Previsibilidade
- Estimativas "Análise de ponto de função"

======================================

12 Princípios
pautar forma de trabalho

01. Software funcionando. Satisfazer o cliente. Entrega adiantada e contínua do software
02. Aceitar mudança a qualquer instante (externalizar a mudança)
03. Entregar software funcionando com períodos mais curtos
04. Todo mundo junto, incluindo o pessoal de negócios
05. Construir projetos ao redor de indivíduos motivados... dando o ambiente e suporte necessário e confiar que farão seu trabalho.
06. O método mais eficiente e eficar é transmitir informações através de uma conversa cara a cara
07. Software funcional (funcionando e que possua valor) é a medida primária de progresso
08. ambiente sustentável. manter a cadência. passos constantes.
09. contínua atenção à excelência técnica e bom design, aumentando a agilidade
10. Simplicidade: a arte de maximizar a quantidade de trabalho que não precisou ser feito.
11. Melhores arquiteturas, requisitos e designs emergem de times auto-organizáveis
12. Em intervalos regulares... pensem em como o time pode ficar mais efetivo. Ajuste e otimize o seu comportamento de acordo

********* Você está no buraco... pare de cavar!!! Levanta e pede Ajuda!!!!
======================================

- Mudanças que não alterem custo e prazo
- Escopo - cadeado aberto
- Custo - cadeado fechado
- Prazo - cadeado fechado

======================================

- Necessidade de um processo adaptável
- Disciplina é essencial
- Fono no talento e habilidade
- Habilidade de resolver problemas
- Auto-organização

======================================

"Bando"
"Grupo"
"Equipe"

Líder + Pessoas

Líder tem que ter as seguintes qualidades
- Atitude
- CHA
- Comprometido
- Inspirador
- Envolvido
- Objetivo
- Comunicativo
- Responsável
- Engajado
- Visão Sistémica
- PSI
- Gestor

O Líder possui tem que possuir tantas qualidades que não aguenta o número de demandas... tornando-se imcompetente... Não quer dizer que ele é!!!!!

Então no time... é melhor não existir essa pessoa. todos devem exercitarem isso... amadurecimento e criação de cultura.

======================================

== Teoria da Complexidade ==

******** Nível de análise alto
Complexo
A --> ?
Práticas emergentes
Scrum cabe muito bem

Complicado
B <-- A --> C
Boas práticas
Práticas comuns como cascata, iterativos e entre outros.
Gerência de riscos tem uma importância mto importante

******** Nível de análise baixo
Caótico
? --> ?
Práticas inovadoras
Kanban (excelente para prioridades de atendimento)

Simples
A --> B
Melhores práticas
PMBok

Já a previsibilidade é maior para cenários complicados e simples (Sou resistente a mudanças)
Não há previsibilidade em cenários complexos e caóticos (Mudanças são bem vindas)

[ESA-01] Autonomia – Motivação – Propósito

Simplicidade
Multidisciplinar

======================================

Resultado X Objetividade X Agilidade

Autonomia
Propósito
Flexibilidade
Confiança (Base da metodologia ágil)
Compartilhar
Adaptação
Caminho (caminhar é mais importante do que concluir o caminho)
Prazer
Sucesso
Competitividade
Felicidade

======================================

Gerenciador de cronograma

0 não comecei
20 iniciei
60 metade
80 acabei

=====================================

Ondas de inovações são importantes...
É necessário criar a onda...
Se não criar a onda... é necessário surfar a onda....
Não pegou a onda... pegue a próxima onda!!!
Não seja a barreira que impedirá outras pessoas de pegar suas próprias ondas!!!

=====================================

Autonomia é necessária para as pessoas trabalharem de forma mais responsáveis e incentivadas
Pessoas tem que entender porque tem que fazer isso --> Propósito
Pessoas precisam de tempo para estudar para chegar a algum lugar --> Domínio

=====================================

Interdependência

=====================================

Teoria das restrições
"A Meta"
"Corrente crítica"
"5 doenças da gestão de projetos"

=====================================

Empreendedorismo e startup
Produto bom é produto entregue
Mínimo necessário
Produto mínimo viável

=====================================

Comunicação é muito importante na metodologia ágil
Comunique-se
Entenda
Interaja
Crie propósitos

=====================================

Autonomia
Domínio
Propósito


Daniel Pink

Excelentes Práticas com Git

gitEstou adicionando esse post porque através do Git, consegue-se elevar o nível de trabalho e cuidado com o código.

 

Esse diagrama de estados através de comandos é o princípio básico da ferramenta, e através dele conseguimos abstrair o cotidiano.

Git-transport

Caso precise de algo mais, esse diagrama de atividade abaixo é o ideal. Existe bastante informação e está um pouco bagunçado, mas se você quer seguir em frente na ferramenta, dê pelo menos uma olhada!!!

git-pretty

Todas as imagens foram tiradas da internet e peguei só para eu não precisar ficar procurando.

Enjoy
Marcos Carvalho

[Android] Notes About View, Layout and Adapters

View
Key building block for UI components
Occupy a rectangular space on screen
Responsible for drawing themselves and for handling events

Common View Operations
Set visibility: show or hide view
Set Checked state
Set Listeners: Code that should be executed when specific events occur
Set properties: opacity, background, rotation
Manage input focus: allow view to take focus, request focus

View Event Sources
User interaction
- Touch
- Keyboard/trackball/D-pad
System control
- Lifecycle changes

Displaying Views
Views are organized in a Tree
Displaying has multiple steps
Measure – get dimensions of each View
Layout – Position each View
Draw – Draw each view

ViewGroup
An invisible View that contains other views
Used for grouping & organizing a set of views
Base class for view containers & layouts

Adapters & AdapterViews
AdapterViews are views whose children and data are managed by an Adapter
Adapter manages the data and provides data views to AdapterView
AdapterView displays the data Views

Layout
A generic ViewGroup that defines a structure for the Views it contains

LinearLayout
Child views arranged in a single horizontal or vertical row

RelativeLayout
Child views are positioned relative to each other and to parent view

TableLayout
Child views arranged into rows & columns

GridView
Child views arranged in a two-dimensional, scrollable grid

Menus and ActionBar
Activities support menus
Activities can
- Add items to a menu
- handle clicks on the menu items

Menu Types
Options
- menu shown when user presses the menu button
Context
- View-specific menu shown when user touches and holds the view
Submenu
- A menu activated when user touches a visible menu item

Creating Menus
Define menu resource in XML file
- Store in res/menu/filename.xml
Inflate menu resource using Menu
Inflater in onCreate…Menu() methods
Handling item selection in appropriate on…ItemsSelected() methods

Menus
Many other features supported
- Grouping menu items
- Binding shortcut keys to menu items
- Binding Intents to menu items

ActionBar
Similar to Application Bar in many desktop applications
Enables quick Access to common operations

ActionBar.Tab
Screen is divided into tab & content areas
Allows multiple Fragments to share single content area
Each tab is associated with one Fragment
Exactly one tab is selected at any given time
Fragment corresponding to the selected tab is visible in the content area

Dialogs
Independent subwindows used by Activities to communicate with user
- AlertDialog
- ProgressDialog
- DatePickerDialog
- TimePickerDialog

Questions

An application's user interface can include more than just the visual components on the display screen.
True

Which of the following statements correctly describe the View class.
A View is a basic building block of user interfaces.
A View is responsible for drawing itself.
A View is responsible for handling events directed to it.

AdapterViews collaborate with Adapters to manage and display information. Which of the following statements are true of the Adapter interface? See: http://developer.android.com/reference/android/widget/Adapter.html for further documentation.
Adapters provide data using methods such as getCount() and getItem().
Adapters provide Views to the AdapterView.

Layouts are ViewGroups that arrange or organize the position of their child Views.
True

The child Views contained in a LinearLayout can be made to overlap each other by specifying a fractional value for android:layout_weight. See: http://developer.android.com/reference/android/widget/LinearLayout.html for more information.
False

The UIGridView application reads a bunch of Bitmaps into the application and then displays them. For example, one Bitmap is stored in a file called image1.jpg. What Java identifier was used to access this Bitmap file?
R.drawable.image1

Which one of the following statements correctly describes a difference between Context Menus and Options Menus?
Context Menus are generally associated with individual Views, while Options Menus are generally associated with the entire application.

If your application contains a Fragment and that Fragment wants to place actions in the Action Bar, which of the following methods will that Fragment likely call or implement?
onCreateOptionsMenu().
setHasOptionsMenu().

The example application you just saw created and displayed an AlertDialogFragment. This Object was created by using an AlertDialog.Builder Object. Take a look at the documentation for AlertDialog.Builder. Which class is most often used as the return type of this class' methods?
See: http://developer.android.com/reference/android/app/AlertDialog.Builder.html.
AlertDialog.Builder.

Which of the following statements describe key responsibilities of a View?
To respond to events directed to them.
To draw themselves.

Which of the following are properties that can be set on a View?
Position.
Visibility.
Opacity (transparency).

An AutoCompleteTextView is a subclass of ViewGroup. Hint: Consult the Android documentation at http://developer.android.com/reference/classes.html
False

Which of the following statements describe the relationship between and AdapterView and its Adapter?
The Adapter manages a data set for the AdapterView.
Adapters can notify the AdapterView when the Adapter data changes.

Suppose a layout file declares a LinearLayout called LL that contains two child Views, View1 and View2. In the layout file View1 is given an android:layout_weight of 2 and a layout_width of 0dp. View 2 is given an android:layout_weight of 3 and a layout_width of 0dp. In this example, which of the following statements must be true?
View 2 takes up 3/5 of LL's width.

When a user long clicks on a View that has registered to show a Context Menu, which one of the following methods will be called?
onCreateContextMenu().

Suppose that an application wants to create and display a Dialog. If the application embodies the Dialog in a DialogFragment, which DialogFragment method will it call to make the Dialog visible to the user?
show()

The ActionBar has four functional areas: The App icon, a View control area, an Action Buttons area and an Action Overflow area. What is the purpose of the Action Overflow area? See; http://developer.android.com/design/patterns/actionbar.html for more information.
When Action Buttons cannot fit in or should not be placed on the Action Bar, they are displayed in a separate View that is accessible by touching the Action Overflow area.

Enjoy
Marcos Carvalho

[Android] Notes About Intent Class, Permissions and Fragment Class

Intent Class
A data structure that represents
- An operation to be performed
- An event that has occurred

Intent as desired operations
Intents provide a flexible language for specifying operations to be performed.
Intent is constructed by one component that wants some work done
Received by one activity that can perform that works

Intent Fiels
Action
- action_dial - dial a number
- action_edit - display data to edit
- action_sync - synchronize device data with server
- action_main - start as initial activity of app
Data
- Data associated with the intent
- Formatted as a URI (uniform resource identifier)
Category
- Additional information about the components that can handle the intent
Type
- Specifies the MIME type of the intent data
Component
- The component that should receive this intent
- Use this when there's exactly one component that should receive the intent
Extras
- Add'l information associated with intent
- treated as a map
Flags
- Specify how intent should be handled

The target activity
Can be named explicitly by setting the intent's component
Can be determined implicitly

Implicit activation
When the activity to be activated is not explicitly named, Android tries to find activities that match the intent
This process is called intent resolution process
- An intent describing a desired operation
- IntentFilters which describe which operations an activity can handle
-- Specified either in AndroidManifest.xml or programmatically

Intent Resolution Data
Action
Data (Both URI & TYPE)
Category

Priority
Android:Priority - Priority given to the parent component when handling matching intents
Causes Android to prefer one activity over another
Value should be greater than 1000 & less than 1000
Hiver values represent higher priority

Permissions
Android protects resources & data with permissions
Used to limit access to:
- User information
- cost-sensitive API's
- System resources
Permissions are represented as strings
In AndroidManifest.xml, apps declare permissions
They require of other components

Using Permissions
Apps specify permissions they use througha <uses-permission> tag
Users must accept these permissions before an application can be installed

Defining Permissions
Suppose your application performs a privileged/dangerous operation
You might not want to allow just any application to invoke yours
So you can define & enforce your own permission

Component Permissions
Individual components can set their own permissions, restricting which other components can access them
Component permissions take precedence over application-level permissions

Activity permissions
restricts which components can start the associated activity
Checked within execution of
- startActivity()
- startActivityForResult()
Throws SecutityException on permissions failure
onCreateView() must return the View at the root of the Fragments's layout
This view is added to the containing activity

Fragment Class
Represents a behavior / portion of UI within an activity
Multiple fragments can be embedded in an activity to create a Multi-pane UI
A single fragment can be reused across multiple activities
Fragment lifecycle is coordinated with the lifecycle of its containing activity
Fragments have their own lifecycles and receive their own callbaks

Adding Fragments to Activities
Two general ways to add fragments to an activity's layout
- Declare it statically in the activity's layout file
- Add it programmatically using the FragmentManager
Layout can be inflated/implemented in onCreateView()

Adding Fragments Dynamically (Frame layout)
While an activity's running you can add a fragment to it's layout
- Get reference to the FragmentManager
- Begin a FragmentTransaction
- Add the fragment
- Commit the FragmentTransaction

Dynamic Layout
Fragment transactions allow you to dynamically change your app's user interface
Can make the interface more fluid & take better advantage of available screen space

Configuration Changes
If you call setRetainInstance(true), Android won't destroy the Fragment on configuration changes
Results in some changes to lifecycle callback sequence
onDestroy() will not be called
onCreate() will not be called

Questions

Which of the following statements describe common uses of the Intent class?
To specify an operation to be performed.
To represent an event that has occurred.

If you want to send a message to a particular person using an Intent with the Intent.ACTION_SENDTO action, what one other piece of Intent information do you have to set?
See: http://developer.android.com/reference/android/content/Intent.html#ACTION_SENDTO for more information.
Data.

Which one of the following flags will help you get more information about how Android determines which Activities can respond to a given Intent?
Intent.FLAG_DEBUG_LOG_RESOLUTION.

Which of the following Intent fields are used as match criteria during Intent resolution?
Category.
Action.
Data

Which of the following describe situations where permissions might be used?
To restrict access to costly operations.
To restrict accesps to device hardware features.
To restrict access to user data.

Which XML tag does an application use to specify permissions that the device's user must grant to the application before that application can run on the user's device.
<uses-permission>

Which XML tag or attribute is used to specify an application-specific permission that an application may require of any other application that wants to interact with it?
<permission>

Which Exception is thrown if one Activity tries to start another Activity for which it does not have the appropriate permissions?
SecurityException.

When designing an application's user interface, it's a good practice to design a single, identical user interface for both Tablets and Phones.
False

Which one of the following Fragment lifecycle callback methods occurs at the earliest point in the Fragment lifecycle?
onAttach().

In which method does a Fragment normally create its user interface?
onCreateView().

When an application programatically adds a Fragment to an Activity, it normally performs the four steps shown below. Which of these steps is done last?
Commit the FragmentTransaction

When a Fragment is programmatically added to an Activity, by default Android adds the new Fragment to the Task backstack.
False

Which one of the following Fragment methods tells Android not to destroy a Fragment when a device configuration change occurs?
setRetainInstance().

Suppose that an application includes an Activity named A, and that the application declares an <activity> tag for A within its AndroidManifest.xml file. If Activity A should be the main entry point for this application, then it will specify an <intent-filter> element, containing an <action> element. What value should you include to complete the following <action> element definition - <action android:name= "…."/>?
android.intent.action.MAIN

Suppose that an application includes an Activity named A and that the application declares an activity tag for A within its AndroidManifest.xml file. If Activity A will be the main entry point for its application and if an icon for this application/activity should appear in the top-level launcher, how should you complete the following <category> element - <category android:name="…"/>?
android.intent.category.LAUNCHER

The MapLocationFromContacts application created an Intent with the Action, Intent.ACTION_PICK and a with data URI representing the contacts database. It then invoked an Activity using startActivityForResult(). What type of data will the started Activity return?
A String Uri.

Suppose you create an application that uses the Vibration Service to make a device vibrate as a deadline approaches. To receive permission to use the Vibrator Service, you will need to add a <uses-permission> element to your application's AndroidManifest.xml file. What permission value should you use to complete the <uses-permission> element - <uses-permission android:name="…"/>?
See: http://developer.android.com/reference/android/Manifest.permission.html for more information.
android.permission.VIBRATE

Suppose you create an application that captures and stores personal information from the user, such as the medicines they are currently taking. Other applications may want to use this information and then provide add-on services over it, for example, to create 'time to take your pill' reminders. Which of the following tags would you put in your application's AndroidManifest.xml file to define a new application-specific permission for accessing your application.
<permission>.
The Fragment class is a subclass of the Activity class and replaces Activities on large screen devices such as Tablets.
False

In which method do Fragments typically create their user interfaces?
onCreateView().

Which of the following are good reasons for dynamically modifying application layouts at runtime, rather than by using static layout files.
Dynamic layouts can take advantage of contextual information that's not tracked by Android's configuration system (such as current location, usage time, or ambient light measurements).
Dynamically-created user interfaces can adapt to an application's runtime state, such as the amount of data that needs to be displayed at any one time.

Suppose you have an Activity that hosts a Fragment. This Fragment has invoked the setRetainInstance() method, passing in the parameter true. Which of the following Fragment lifecycle methods will not be called if the Activity is later killed and restarted due to a reconfiguration?
onDestroy().
onCreate().

Enjoy
Marcos Carvalho

Application Fundamental Android

Activity
Primary class for user interaction
Usually implements a single, focused task that the user can do

Service
Run in the background
To perform long-running operations
To support interaction with remote processes

BroadcastReceiver
Component that listens for and responds to events
The subscriber in publish/subscribe pattern
Events represented by the intent class and the broadcast
BroadcastReceiver receives and responds to broadcast event

Content Providers
Store & share data across applications
- Uses database-style interface
- Handles interprocess communication

Build-simplified-android

Participation in the build process will usually involve the four steps:
Define Resources
- Resources are non-source code entities
Implement Application Classes
Package Application
Install & run application

User Interface Layout
UI layout specified in xml files
XML files typically stored in res/layout/*.xml
Accessed in Java as: R.layout.layout_name
Can specify different layout files based on your device's orientation, screen size, etc.

R.java
At compilation time, resources are used to generate the R.java class
Java code uses the R class to access resources

Implement Classes
Usually involves at least one Activity
Activity initialization code usually in onCreate()
- Restore saved state
- Set content view
- Initialize UI elements
- Link UI elements to code Actions

Package Application
System packages application components & resources into a .apk file
Developers specify required application information in a file called
AndroidManifest.xml

Navigation through activities
Android supports navigation in several ways
Tasks
- a task is a set of related activities
- These related activities don't have to be part of the same application
- Most tasks start at the home screen
The task backstack
- when an activity is launched, it goes on top of the backstack
- when the activity is destroyed, it is popped off the backstack
Suspending & resuming activities

The Activity Lifecycle
Android-Activity-Lifecycle

onCreate()
Called when activity is created
Sets up initial state
- Call super.onCreate()
- Set the activity's content view
- Retain references to UI views as necessary
- Configure views as necessary

Starting Activities
Pass newly created intent to methods, such as:
startActivity()
startActivityForResult()
- Invokes a callback method when the called activity finishes to return a result

Questions

The Android documentation describes an Activity as "a single, focused thing that the user can do." Which one of the following statements best expresses why this statement might be somewhat ambiguous today?
Some devices, such as Tablets, are large enough to accommodate multiple screenfuls of data at one time.

Which one of the following statements might explain why the Music application plays songs using a Service, rather than by using one of its Activities?
The user might want to listen to music and do something else at the same time.

The MediaPlaybackService class that we looked at earlier in the lecture is a Service. Did you notice that it also contains a BroadcastReceiver called mIntentReceiver? What BroadcastReceiver method is overriden in the MediaPlaybackService.java file by mIntentReceiver?
onReceive

Which of the following statements about the ContentProvider class are true?
ContentProviders can perform interprocess communication.
ContentProviders encapsulate data sets.
Android supports several system-wide ContentProviders.

Which one of the four fundamental components of Android applications is designed to provide an interface to the user?
Activity

Which one of the four fundamental components of Android applications is designed to listen for and respond to events?
BroadcastReceiver

Which one of the four fundamental components of Android applications is designed for sharing data across applications?
ContentProvider

Which one of the four fundamental components of Android applications is designed to in-the-background and remote operations?
Service

Resources are non-source code entities within your application. Which of the following statements capture advantages of using resources, rather than managing entities directly within application source code?
Resources can be changed without recompiling source code.
Sets of resources can be created for different devices, user preferences, and devices configurations.

If you create a resource, such as a string resource, in an XML file, how can you access that resource in your Java code?
In your Java code you can refer to a string, called "string_name", as R.string.string_name.

In which level of the Android Platform would you find the Activity, Service, BroadcastReceiver, and ContentProvider classes?
The Application Framework Layer

Customizing strings for different languages allows more people to use your application, but it's not always that easy to do. Have you thought about some of the difficulties that might come from trying to support users of many different languages? Which of the following might be examples of such difficulties?
Left-to-right vs. right to left ordering of words
Differing word lengths for the same concept.
Differing date and time formats.
Ensuring that the translation is correct.

In which directory did we put the main.xml layout file that specifies MapLocation's layout when the device is in landscape mode?
res/layout-land

The Button.onClickListener interface defines a "callback" method. A callback method is a method that will get called at a future time, in this case, whenever the user clicks on a particular Button. What is the name of the callback method where you put code to be executed when a user clicks on a Button?
onClick

In which method are Activities usually initialized?
onCreate

Which of the following are examples of element tags that you might find in an AndroidManifest.xml file? See: http://developer.android.com/guide/topics/manifest/manifest-intro.html for more information.
<application>
<uses-sdk>

Which of the following are advantages of using an emulator instead of using a device?
You don't have to buy an actual device.
The emulated hardware is reconfigurable.
Changes to the emulator state don't make permanent changes to a device.

Which one of the following statements best captures a common design theme or principle for Android Activities?
Each Activity should support one focused thing that the user can do.

Which one of the following steps is typically done in onCreate()?
Set the Activity's content view.

When an Activity calls startActivityForResult(), it will eventually receive a callback to which of its methods?
onActivityResult().

When one Activity wants to start another activity it creates an Object that specifies which Activity it wants to start. What is the type of this Object?
Intent

Enjoy
Marcos Carvalho

Notes About Android Course

The Android Platform comprises several components.
Software Developers Kit
Software Stack
Documentation

Android's Linux Kernel is not exactly the same as the Linux Kernels typically running on desktop machines. Why would Android make its own Linux Kernel?
Mobile devices require features not usually needed on traditional desktop devices.

In which of the following programming languages are Android's Native libraries typically written?
C/C++

The Resource Manager helps with internationalizing applications. Which of the following might explain why that's important to Android developers?
Android phones and applications are sold to and used by people who speak languages other than English.

Which of following kinds of information does the Location Manager provide to applications?
User movement.
User location.

Enjoy
Marcos Carvalho

Notes About NoSQL Databases

Which of the following are true of NoSQL databases?
At a very basic level, they are similar to hash tables

What is database normalization?
The process of ensuring that a piece of data is not duplicated multiple times in a database

What is the role of denormalization in NoSQL database optimization?
Denormalization can be used to make reads faster by duplicating data and requiring fewer key-based lookups

Which of the following are ways to optimize reads for specific queries?
Grouping all data needed for a specific query and attaching it to a single key

How does a sharded counter work?
A counter is broken into multiple shards that are each stored under a different key. When the counter is read, each shard is fetched and the sum of the counter shards is returned. On writes, a counter shard is randomly chosen and incremented. Write parallelism is proportional to the number of shards.

What is the relationship between read and write optimization in NoSQL databases?
Many write optimization strategies require denormalization, which can increase read complexity
Many read optimization strategies require denormalization, which can increase write complexity

Enjoy
Marcos Carvalho

Notes About Clouds

Which of the following are reasons that username/password logins and session cookies are not ideal for mobile clients?
It isn't possible to easily revoke access to a single app
Changing your password can revoke access to every app that uses it

Which of the following analogies is most appropriate for describing OAuth 2.0?
A valet key for a car

What is the purpose of a password grant in OAuth 2.0?
To obtain a token required for access to one or more resources on the system
To authenticate the user

How is a bearer token used?
It is provided in the Authorization header of a request to prove a client's identity

Which of the following is an example of horizontal scaling?
Adding a new server to support additional load for an application

Which of the following are accurate statements about stateless applications?
They typically allow requests to be routed to any node running an application instance

What is auto-scaling?
Automated addition or removal of computing resources to adapt to changes in an application's load, failures, etc.

Enjoy
Marcos Carvalho

Notes About Spring e Retrofit

Which of the following are true statements about the Retrofit library?
It can be used to provide strong typing for interactions with HTTP-based cloud services
It can automatically marshall Java objects into HTTP request bodies

Which of the following are reasons to use dependency injection?
To reduce the amount of manually written configuration code that is needed to "wire" an application together
To help decouple one or more classes from their dependencies

What is @Autowired used for?
To indicate that one or more of a class' dependencies should be automatically provided through dependency injection

Which of the following are true of object relational mapping?
It is used to aid in persisting instances of Java objects into a database

Which of the following statements are true of the code shown below:

@RequestMapping("/some/path")
public @ResponseBody List<Video> findVideos(@RequestParam("title") String videoTitle){
String query = "select * from video where video.title = '"+videoTitle+"'";
return executeDatabaseQuery(query)
}

@RequestParam will NOT filter the title parameter and the code could suffer from an SQL injection attack
Arbitrary logic could potentially be injected into the query

Which of the following are true of Spring JPA Repositories?
The implementations of repository interfaces are automatically created by Spring

Enjoy
Marcos Carvalho

Notes about Spring Dispatcher

Which of the following are true of Java annotations?
They can be used to provide metadata for methods and other Java constructs.

 

Which of the following are true statements regarding the Spring DispatcherServlet?
It is used to route requests to Spring Controller objects.
It can invoke different methods on a Controller object depending on the request path.

 

Which of the following are uses of the @RequestBody annotation?
To indicate to Spring that the body of an incoming HTTP request should be unmarshalled to provide the value for a parameter of a method annotated with @RequestMapping.

 

@RequestParam can be used if the HTTP request has a multipart body.

 

Which of the following are true of @ResponseBody?
@ResponseBody helps to decouple Controller method logic from HTTP-specific protocol details.
@ResponseBody indicates that the return value from a Controller method should be used to produce the body of the HTTP response.

 

Which of the following are true statements about an Application class, such as the Application class in the examples?
It can be used to provide configuration information to Spring.
It does not have to inherit from a Spring-specific super class.
With Spring Boot and the appropriate annotations, it can be used to setup a Dispatcher servlet.
It can provide a main() method to launch Spring Correct.

 

Which of the following are true statements about JSON?
It can be used to express the state of a Java object.
It can be used to express arrays of objects.
It is a text-based format.

 

Enjoy
Marcos Carvalho

Notes About HTTP and Servlets

Which of the following are correct statements regarding HTTP polling?
Since a client does not have direct access to any server-side state, the client may waste resources by polling the server for updates when there are none.
Dynamically adapting the polling interval is one approach to reducing unnecessary HTTP requests.
Polling can generate excess load on a server if the polling interval is too short.

 

Which of the following are true of Push Messaging?
If the state that needs to be pushed to a client is extremely sensitive, a "push to poll" model where the server sends a push notification and then the client polls for a state update is most appropriate
If the state that needs to be pushed to a client is extremely large (e.g., multiple megabytes), a "push to poll" model where the server sends a push notification and then the client polls for a state update is most appropriate
Push messaging relies on a persistent connection between a mobile device and a push messaging system's servers

 

Which of the following are true statements about Servlets?
A servlet has doXXXX methods for each type of request method that can be sent to the server

 

Which of the following is true about handling client input data in a servlet?
A servlet can access url encoded parameters placed in the body of a request sent by a client
A servlet can access URL query parameters sent by a client

 

Which of the following are true statements regarding request routing and servlets?
A web.xml file can be used to specify which requests should be routed to which servlets
Requests can be routed to different servlets based on the resource path specified in the request

 

Which of the following could lead to an injection attack?
Failing to verify that the type of data sent to the server is what was expected
Storing client-provided data without filtering it and then resending it to other clients
Allowing client-provided data to control an execution path involving sensitive data
Echoing executable client-provided data back to the client without filtering it

 

Which of the following are true statements regarding client-provided data?
None of the below are correct:

  • Careful filtering of client-provided data is not needed if only one type of client is expected to ever use a cloud service
  • Careful filtering of client-provided data is not needed if the same developer writes the mobile client and the cloud service
  • Because client-provided data is so hard to filter, a cloud service should never accept a body in an HTTP request
  • Client-provided data in URL query parameters is always safer than the same data provided in a URL encoded request body

 

Enjoy
Marcos de Carvalho Oliveira

Notes About Protocol and HTTP

What are the components of a protocol?
Semantics
Syntax
Timing

 

What is HTTP?

A communication protocol that is based on a client/server model
A communication protocol commonly used by web browsers

 

What are some of the reasons that HTTP is commonly used for mobile to cloud communication?
There is significant existing investment and infrastructure for HTTP communication

 

What are HTTP request methods?
An indication of an action that a client would like the server to apply to a resource

 

Which of the following are possible components of an HTTP request?
A Content-type for a body included with the request
Headers
A Request Body
Request Line

 

What is URL encoding?
An alternative representation of certain characters that can be placed in a URL

 

What is the purpose of the content-type header?
To tell either the client or server the format of the data included in a request or response body

 

What is the purpose of the numeric code included in the status line of an HTTP response?
To provide an indication of what happened when the server processed the request

 

Which of the following are possible outcomes of a request that a server could indicate with a 2XX response code?
The request was successfully processed

 

Which of the following are true of cookies?
They are small pieces of data that the server indicates should be included by the client in future requests

 

Enjoy
Marcos Carvalho

[C#] Manipulação de Dados

Manipulação de Dados com o Objeto SqlConnection:

public List buscarClientes()
{
    string query = @"select * from [dbo].[clientes]";

    string conexao = ConfigurationManager.ConnectionStrings[BANCO].ConnectionString;
    SqlConnection conn = new SqlConnection(conexao);

    SqlCommand comando = conn.CreateCommand();
    comando.CommandText = query;

    conn.Open();
    SqlDataReader reader = comando.ExecuteReader();
    List list = RetornarClientes(reader);
    conn.Close();

    return list;
}

private List RetornarClientes(System.Data.SqlClient.SqlDataReader reader)
{
    List list = new List();
    while (reader.Read())
    {
        list.Add(RetornarCliente(reader));
    }

    return list;
}

private Cliente RetornarCliente(System.Data.SqlClient.SqlDataReader reader)
{
    Cliente cliente = new Cliente();
    cliente.Id = (String)reader["cliente_id"];
    cliente.Nome = (String)reader["nome"];
    cliente.Sobrenome = (String)reader["sobrenome"];
    cliente.Rua = (String)reader["rua"];
    cliente.Cidade = (String)reader["cidade"];
    cliente.Estado = (String)reader["estado"];
    cliente.Cep = (String)reader["cep"];

    return cliente;
}

 

Manipulação de Dados com o Objeto OleDbConnection:

public List buscarClientesAccess()
{
    string query = "select * from [clientes]";

    OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|BancoMA.mdb");
    OleDbCommand comando = conn.CreateCommand();
    comando.CommandText = query;

    conn.Open();
    OleDbDataReader reader = comando.ExecuteReader();
    List list = RetornarClientes(reader);
    conn.Close();

    return list;
}

private List RetornarClientes(OleDbDataReader reader)
{
    List list = new List();

    while (reader.Read())
    {
        list.Add(RetornarCliente(reader));
    }

    return list;
}

private Cliente RetornarCliente(System.Data.OleDb.OleDbDataReader reader)
{
    Cliente cliente = new Cliente();
    cliente.Id = (String)reader["cliente_id"];
    cliente.Nome = (String)reader["nome"];
    cliente.Sobrenome = (String)reader["sobrenome"];
    cliente.Rua = (String)reader["rua"];
    cliente.Cidade = (String)reader["cidade"];
    cliente.Estado = (String)reader["estado"];
    cliente.Cep = (String)reader["cep"];
    return cliente;
}

 

Recuperando um array de Object de uma DataGridView:

private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
    Object o = dataGridView1.Rows[e.RowIndex].DataBoundItem;
    System.Data.DataRowView asdf = (DataRowView) o;
    object[] os = asdf.Row.ItemArray;
}

 

Arquivo de Exemplo: Avaliacao20140414 e 20140610

Enjoy
Marcos Carvalho

[HowTo] – [Git]

git init
Iniciar o versionamento dentro de uma pasta;
Criará um diretório .git;
Para fazer backup com todo histórico, apenas copiar o diretório .git.

git init --bare
Cria o repositório com as mesmas pastas que o git criaria dentro da pasta .git;
A pasta .git não existe nesse cenário;
Cria um repositório sem área de trabalho.

git status
Mostra o Status que está o Working Area e o Índice.

git add <>
Adicionar ao índice;
Dentro do <>, adicionará arquivos, arquivos de um tipo, ou tudo;
. ou * é igual a tudo;
Para arquivos de um tipo. Exp: *.java;
Caso tenha modificado o arquivo depois de ter adicionado ao índice, terá que refazer esse passo.

git add -i
Mostra um menu de opções para trabalhar em cima do Working Area X Índice.

git rm --cached <file>
Retira o arquivo do índice.

git commit -m "Mensagem para o commit que está fazendo. O Mesmo que histórico."
Envia ao repositório;
Grava o conteúdo do índice no repositório.

git commit -a -m "mensagem"
-a funciona para comitar arquivos que já foram modificados e já foram comitados ao menos uma vez.

git checkout --<file>
Caso queira retirar do índice.

git log
Lista os logs.

git log --stat
Mostra o que cada commit foi alterado.

git log --graph
Mostra os logs gráficamente.

gitk --all &
Git gráfico para visualização de logs.

git reset HEAD <>
Retira o arquivo modificado do índice, voltando para o Working Area.

git reset HEAD~1 --hard >
Esse comando retorna para o -1 commit;
--hard > Arranca fora o commit inteiro;
--soft > Ele volta para o Índice.

git commit -m "Teste" --amend
Para adicionar um arquivo no último commit;
Dica: Usar só locamente;
Joga fora o último commit e cria um novo.

.gitignore
Colocar as informações que não deseja versionar;
Ex: *.log >> Nunca versionará os arquivos com extensão .log.

git add target/teste.txt -f
Caso queira versionar mesmo estando configurando no .gitignore.

git reflog
Guarda o que foi-se apagando.

git merge <SHA1>
git merge <branch> > fazer merge com outro branch;
git merge <branch> --squash > Ele pega todos os commits de um branch e coloca no Índice no branch que está.

git clean -f
Pegar arquivos que estão no Working Area e jogam as modificações fora.

git stash
Pega os arquivos do índice e manda para o stash, retornando ao estado inicial do índice.
Usado para quando tem um ambiente estável e quer fazer novas modificações, por exemplo, testes.

git stash list
Mostra as listas que estão no Stash.

git stash apply
Ele pega o que está no stash e joga no índice novamente.

git stash apply stash@{0}
Retorna o último stash ou qualquer um que informou;
O mais recente sempre é o 0.

git stash clear
Apaga todas as listas do stash.

git stash save "<nome>"
Salva o stash com um nome.

git stash pop
Retira do stash, aplica no índice e apaga a lista do stash.

git stash drop <stash>
Retira da lista dos stashes.

  • Convenção

Convencione a não trabalhar-se em cima do Master
Pode-se criar branches. Quantas quiser. Foi feito para ter inúmeras.
Sempre usar.

git branch
Lista as branches.

git branch -a
Mostra todas as branches incluindo os remotos

git branch -d bugfix
Apaga o branch bugfix.

git checkout -b desenvolvimento
Cria um novo branch;
Para ficar indo de um branch para outro, é necessário commitar;
Pega o estado que encontra-se o branch e cria um novo da mesma forma.

git checkout <branch>
Mudando de branch.

git rebase <master>
Trazer o versionanmento do branch informado para o branch que encontra-se;
Tem a função de desfazer o último commit, faz o merge com o branch que informou e commita o commit que tinha desfeito;
A principal função é manter o histórico linear.

git rebase --continue
Para quando não encontra-se em nenhum branch, já retirou o conflito e está querendo commitar.

  • Repositórios Remotos

git clone <.gitRemoto> <repositorio>
Cria um clone do repositório informado para um novo diretório;
Cópia do repositório localmente;
Ex com Http: git clone https://github.com/marcoscarvalho/<path>.git <diretorio>

git remote
Lista os Repositórios remotos;

git remote show origin
Mostra o local da onde foi feito o clone;
"origin" é uma convenção para o primeiro remote/clone.

git remote add <nome> <url>
Adicionar novos repositórios remotos.

git remote rm <nomeRemote>
Desfaz a interligação com os outros repositórios.

git branch -b <novoBranch> origin/<velhoBranchDoQueVoceClonou>
Cria-se o branch a partir do branch clonado.

git push <remote> <branchRemoto>
Empurra para um branch remoto.

git pull <remote> <branchRemoto>
Puxa o repositório a partir do branch informado.

git fetch <remote> <branchRemoto>
Puxa novos commits do repo remoto para a branch especial <remote>/<branch>

git remote add <nome> <user>@<server>:<pasta>/<repositorio>
Adiciona um repositório externo

Enjoy
Marcos Carvalho